xref: /PHP-7.3/Zend/zend_alloc.c (revision 45b4368d)
1 /*
2    +----------------------------------------------------------------------+
3    | Zend Engine                                                          |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1998-2018 Zend Technologies Ltd. (http://www.zend.com) |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 2.00 of the Zend license,     |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.zend.com/license/2_00.txt.                                |
11    | If you did not receive a copy of the Zend license and are unable to  |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@zend.com so we can mail you a copy immediately.              |
14    +----------------------------------------------------------------------+
15    | Authors: Andi Gutmans <andi@php.net>                                 |
16    |          Zeev Suraski <zeev@php.net>                                 |
17    |          Dmitry Stogov <dmitry@php.net>                              |
18    +----------------------------------------------------------------------+
19 */
20 
21 /*
22  * zend_alloc is designed to be a modern CPU cache friendly memory manager
23  * for PHP. Most ideas are taken from jemalloc and tcmalloc implementations.
24  *
25  * All allocations are split into 3 categories:
26  *
27  * Huge  - the size is greater than CHUNK size (~2M by default), allocation is
28  *         performed using mmap(). The result is aligned on 2M boundary.
29  *
30  * Large - a number of 4096K pages inside a CHUNK. Large blocks
31  *         are always aligned on page boundary.
32  *
33  * Small - less than 3/4 of page size. Small sizes are rounded up to nearest
34  *         greater predefined small size (there are 30 predefined sizes:
35  *         8, 16, 24, 32, ... 3072). Small blocks are allocated from
36  *         RUNs. Each RUN is allocated as a single or few following pages.
37  *         Allocation inside RUNs implemented using linked list of free
38  *         elements. The result is aligned to 8 bytes.
39  *
40  * zend_alloc allocates memory from OS by CHUNKs, these CHUNKs and huge memory
41  * blocks are always aligned to CHUNK boundary. So it's very easy to determine
42  * the CHUNK owning the certain pointer. Regular CHUNKs reserve a single
43  * page at start for special purpose. It contains bitset of free pages,
44  * few bitset for available runs of predefined small sizes, map of pages that
45  * keeps information about usage of each page in this CHUNK, etc.
46  *
47  * zend_alloc provides familiar emalloc/efree/erealloc API, but in addition it
48  * provides specialized and optimized routines to allocate blocks of predefined
49  * sizes (e.g. emalloc_2(), emallc_4(), ..., emalloc_large(), etc)
50  * The library uses C preprocessor tricks that substitute calls to emalloc()
51  * with more specialized routines when the requested size is known.
52  */
53 
54 #include "zend.h"
55 #include "zend_alloc.h"
56 #include "zend_globals.h"
57 #include "zend_operators.h"
58 #include "zend_multiply.h"
59 #include "zend_bitset.h"
60 
61 #ifdef HAVE_SIGNAL_H
62 # include <signal.h>
63 #endif
64 #ifdef HAVE_UNISTD_H
65 # include <unistd.h>
66 #endif
67 
68 #ifdef ZEND_WIN32
69 # include <wincrypt.h>
70 # include <process.h>
71 #endif
72 
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 
77 #include <sys/types.h>
78 #include <sys/stat.h>
79 #if HAVE_LIMITS_H
80 #include <limits.h>
81 #endif
82 #include <fcntl.h>
83 #include <errno.h>
84 
85 #ifndef _WIN32
86 # ifdef HAVE_MREMAP
87 #  ifndef _GNU_SOURCE
88 #   define _GNU_SOURCE
89 #  endif
90 #  ifndef __USE_GNU
91 #   define __USE_GNU
92 #  endif
93 # endif
94 # include <sys/mman.h>
95 # ifndef MAP_ANON
96 #  ifdef MAP_ANONYMOUS
97 #   define MAP_ANON MAP_ANONYMOUS
98 #  endif
99 # endif
100 # ifndef MREMAP_MAYMOVE
101 #  define MREMAP_MAYMOVE 0
102 # endif
103 # ifndef MAP_FAILED
104 #  define MAP_FAILED ((void*)-1)
105 # endif
106 # ifndef MAP_POPULATE
107 #  define MAP_POPULATE 0
108 # endif
109 #  if defined(_SC_PAGESIZE) || (_SC_PAGE_SIZE)
110 #    define REAL_PAGE_SIZE _real_page_size
111 static size_t _real_page_size = ZEND_MM_PAGE_SIZE;
112 #  endif
113 #endif
114 
115 #ifndef REAL_PAGE_SIZE
116 # define REAL_PAGE_SIZE ZEND_MM_PAGE_SIZE
117 #endif
118 
119 #ifndef ZEND_MM_STAT
120 # define ZEND_MM_STAT 1    /* track current and peak memory usage            */
121 #endif
122 #ifndef ZEND_MM_LIMIT
123 # define ZEND_MM_LIMIT 1   /* support for user-defined memory limit          */
124 #endif
125 #ifndef ZEND_MM_CUSTOM
126 # define ZEND_MM_CUSTOM 1  /* support for custom memory allocator            */
127                            /* USE_ZEND_ALLOC=0 may switch to system malloc() */
128 #endif
129 #ifndef ZEND_MM_STORAGE
130 # define ZEND_MM_STORAGE 1 /* support for custom memory storage              */
131 #endif
132 #ifndef ZEND_MM_ERROR
133 # define ZEND_MM_ERROR 1   /* report system errors                           */
134 #endif
135 
136 #ifndef ZEND_MM_CHECK
137 # define ZEND_MM_CHECK(condition, message)  do { \
138 		if (UNEXPECTED(!(condition))) { \
139 			zend_mm_panic(message); \
140 		} \
141 	} while (0)
142 #endif
143 
144 typedef uint32_t   zend_mm_page_info; /* 4-byte integer */
145 typedef zend_ulong zend_mm_bitset;    /* 4-byte or 8-byte integer */
146 
147 #define ZEND_MM_ALIGNED_OFFSET(size, alignment) \
148 	(((size_t)(size)) & ((alignment) - 1))
149 #define ZEND_MM_ALIGNED_BASE(size, alignment) \
150 	(((size_t)(size)) & ~((alignment) - 1))
151 #define ZEND_MM_SIZE_TO_NUM(size, alignment) \
152 	(((size_t)(size) + ((alignment) - 1)) / (alignment))
153 
154 #define ZEND_MM_BITSET_LEN		(sizeof(zend_mm_bitset) * 8)       /* 32 or 64 */
155 #define ZEND_MM_PAGE_MAP_LEN	(ZEND_MM_PAGES / ZEND_MM_BITSET_LEN) /* 16 or 8 */
156 
157 typedef zend_mm_bitset zend_mm_page_map[ZEND_MM_PAGE_MAP_LEN];     /* 64B */
158 
159 #define ZEND_MM_IS_FRUN                  0x00000000
160 #define ZEND_MM_IS_LRUN                  0x40000000
161 #define ZEND_MM_IS_SRUN                  0x80000000
162 
163 #define ZEND_MM_LRUN_PAGES_MASK          0x000003ff
164 #define ZEND_MM_LRUN_PAGES_OFFSET        0
165 
166 #define ZEND_MM_SRUN_BIN_NUM_MASK        0x0000001f
167 #define ZEND_MM_SRUN_BIN_NUM_OFFSET      0
168 
169 #define ZEND_MM_SRUN_FREE_COUNTER_MASK   0x01ff0000
170 #define ZEND_MM_SRUN_FREE_COUNTER_OFFSET 16
171 
172 #define ZEND_MM_NRUN_OFFSET_MASK         0x01ff0000
173 #define ZEND_MM_NRUN_OFFSET_OFFSET       16
174 
175 #define ZEND_MM_LRUN_PAGES(info)         (((info) & ZEND_MM_LRUN_PAGES_MASK) >> ZEND_MM_LRUN_PAGES_OFFSET)
176 #define ZEND_MM_SRUN_BIN_NUM(info)       (((info) & ZEND_MM_SRUN_BIN_NUM_MASK) >> ZEND_MM_SRUN_BIN_NUM_OFFSET)
177 #define ZEND_MM_SRUN_FREE_COUNTER(info)  (((info) & ZEND_MM_SRUN_FREE_COUNTER_MASK) >> ZEND_MM_SRUN_FREE_COUNTER_OFFSET)
178 #define ZEND_MM_NRUN_OFFSET(info)        (((info) & ZEND_MM_NRUN_OFFSET_MASK) >> ZEND_MM_NRUN_OFFSET_OFFSET)
179 
180 #define ZEND_MM_FRUN()                   ZEND_MM_IS_FRUN
181 #define ZEND_MM_LRUN(count)              (ZEND_MM_IS_LRUN | ((count) << ZEND_MM_LRUN_PAGES_OFFSET))
182 #define ZEND_MM_SRUN(bin_num)            (ZEND_MM_IS_SRUN | ((bin_num) << ZEND_MM_SRUN_BIN_NUM_OFFSET))
183 #define ZEND_MM_SRUN_EX(bin_num, count)  (ZEND_MM_IS_SRUN | ((bin_num) << ZEND_MM_SRUN_BIN_NUM_OFFSET) | ((count) << ZEND_MM_SRUN_FREE_COUNTER_OFFSET))
184 #define ZEND_MM_NRUN(bin_num, offset)    (ZEND_MM_IS_SRUN | ZEND_MM_IS_LRUN | ((bin_num) << ZEND_MM_SRUN_BIN_NUM_OFFSET) | ((offset) << ZEND_MM_NRUN_OFFSET_OFFSET))
185 
186 #define ZEND_MM_BINS 30
187 
188 typedef struct  _zend_mm_page      zend_mm_page;
189 typedef struct  _zend_mm_bin       zend_mm_bin;
190 typedef struct  _zend_mm_free_slot zend_mm_free_slot;
191 typedef struct  _zend_mm_chunk     zend_mm_chunk;
192 typedef struct  _zend_mm_huge_list zend_mm_huge_list;
193 
194 int zend_mm_use_huge_pages = 0;
195 
196 /*
197  * Memory is retrived from OS by chunks of fixed size 2MB.
198  * Inside chunk it's managed by pages of fixed size 4096B.
199  * So each chunk consists from 512 pages.
200  * The first page of each chunk is reseved for chunk header.
201  * It contains service information about all pages.
202  *
203  * free_pages - current number of free pages in this chunk
204  *
205  * free_tail  - number of continuous free pages at the end of chunk
206  *
207  * free_map   - bitset (a bit for each page). The bit is set if the corresponding
208  *              page is allocated. Allocator for "lage sizes" may easily find a
209  *              free page (or a continuous number of pages) searching for zero
210  *              bits.
211  *
212  * map        - contains service information for each page. (32-bits for each
213  *              page).
214  *    usage:
215  *				(2 bits)
216  * 				FRUN - free page,
217  *              LRUN - first page of "large" allocation
218  *              SRUN - first page of a bin used for "small" allocation
219  *
220  *    lrun_pages:
221  *              (10 bits) number of allocated pages
222  *
223  *    srun_bin_num:
224  *              (5 bits) bin number (e.g. 0 for sizes 0-2, 1 for 3-4,
225  *               2 for 5-8, 3 for 9-16 etc) see zend_alloc_sizes.h
226  */
227 
228 struct _zend_mm_heap {
229 #if ZEND_MM_CUSTOM
230 	int                use_custom_heap;
231 #endif
232 #if ZEND_MM_STORAGE
233 	zend_mm_storage   *storage;
234 #endif
235 #if ZEND_MM_STAT
236 	size_t             size;                    /* current memory usage */
237 	size_t             peak;                    /* peak memory usage */
238 #endif
239 	zend_mm_free_slot *free_slot[ZEND_MM_BINS]; /* free lists for small sizes */
240 #if ZEND_MM_STAT || ZEND_MM_LIMIT
241 	size_t             real_size;               /* current size of allocated pages */
242 #endif
243 #if ZEND_MM_STAT
244 	size_t             real_peak;               /* peak size of allocated pages */
245 #endif
246 #if ZEND_MM_LIMIT
247 	size_t             limit;                   /* memory limit */
248 	int                overflow;                /* memory overflow flag */
249 #endif
250 
251 	zend_mm_huge_list *huge_list;               /* list of huge allocated blocks */
252 
253 	zend_mm_chunk     *main_chunk;
254 	zend_mm_chunk     *cached_chunks;			/* list of unused chunks */
255 	int                chunks_count;			/* number of alocated chunks */
256 	int                peak_chunks_count;		/* peak number of allocated chunks for current request */
257 	int                cached_chunks_count;		/* number of cached chunks */
258 	double             avg_chunks_count;		/* average number of chunks allocated per request */
259 	int                last_chunks_delete_boundary; /* numer of chunks after last deletion */
260 	int                last_chunks_delete_count;    /* number of deletion over the last boundary */
261 #if ZEND_MM_CUSTOM
262 	union {
263 		struct {
264 			void      *(*_malloc)(size_t);
265 			void       (*_free)(void*);
266 			void      *(*_realloc)(void*, size_t);
267 		} std;
268 		struct {
269 			void      *(*_malloc)(size_t ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
270 			void       (*_free)(void*  ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
271 			void      *(*_realloc)(void*, size_t  ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
272 		} debug;
273 	} custom_heap;
274 #endif
275 };
276 
277 struct _zend_mm_chunk {
278 	zend_mm_heap      *heap;
279 	zend_mm_chunk     *next;
280 	zend_mm_chunk     *prev;
281 	uint32_t           free_pages;				/* number of free pages */
282 	uint32_t           free_tail;               /* number of free pages at the end of chunk */
283 	uint32_t           num;
284 	char               reserve[64 - (sizeof(void*) * 3 + sizeof(uint32_t) * 3)];
285 	zend_mm_heap       heap_slot;               /* used only in main chunk */
286 	zend_mm_page_map   free_map;                /* 512 bits or 64 bytes */
287 	zend_mm_page_info  map[ZEND_MM_PAGES];      /* 2 KB = 512 * 4 */
288 };
289 
290 struct _zend_mm_page {
291 	char               bytes[ZEND_MM_PAGE_SIZE];
292 };
293 
294 /*
295  * bin - is one or few continuous pages (up to 8) used for allocation of
296  * a particular "small size".
297  */
298 struct _zend_mm_bin {
299 	char               bytes[ZEND_MM_PAGE_SIZE * 8];
300 };
301 
302 struct _zend_mm_free_slot {
303 	zend_mm_free_slot *next_free_slot;
304 };
305 
306 struct _zend_mm_huge_list {
307 	void              *ptr;
308 	size_t             size;
309 	zend_mm_huge_list *next;
310 #if ZEND_DEBUG
311 	zend_mm_debug_info dbg;
312 #endif
313 };
314 
315 #define ZEND_MM_PAGE_ADDR(chunk, page_num) \
316 	((void*)(((zend_mm_page*)(chunk)) + (page_num)))
317 
318 #define _BIN_DATA_SIZE(num, size, elements, pages, x, y) size,
319 static const uint32_t bin_data_size[] = {
320   ZEND_MM_BINS_INFO(_BIN_DATA_SIZE, x, y)
321 };
322 
323 #define _BIN_DATA_ELEMENTS(num, size, elements, pages, x, y) elements,
324 static const uint32_t bin_elements[] = {
325   ZEND_MM_BINS_INFO(_BIN_DATA_ELEMENTS, x, y)
326 };
327 
328 #define _BIN_DATA_PAGES(num, size, elements, pages, x, y) pages,
329 static const uint32_t bin_pages[] = {
330   ZEND_MM_BINS_INFO(_BIN_DATA_PAGES, x, y)
331 };
332 
333 #if ZEND_DEBUG
zend_debug_alloc_output(char * format,...)334 ZEND_COLD void zend_debug_alloc_output(char *format, ...)
335 {
336 	char output_buf[256];
337 	va_list args;
338 
339 	va_start(args, format);
340 	vsprintf(output_buf, format, args);
341 	va_end(args);
342 
343 #ifdef ZEND_WIN32
344 	OutputDebugString(output_buf);
345 #else
346 	fprintf(stderr, "%s", output_buf);
347 #endif
348 }
349 #endif
350 
zend_mm_panic(const char * message)351 static ZEND_COLD ZEND_NORETURN void zend_mm_panic(const char *message)
352 {
353 	fprintf(stderr, "%s\n", message);
354 /* See http://support.microsoft.com/kb/190351 */
355 #ifdef ZEND_WIN32
356 	fflush(stderr);
357 #endif
358 #if ZEND_DEBUG && defined(HAVE_KILL) && defined(HAVE_GETPID)
359 	kill(getpid(), SIGSEGV);
360 #endif
361 	exit(1);
362 }
363 
zend_mm_safe_error(zend_mm_heap * heap,const char * format,size_t limit,const char * filename,uint32_t lineno,size_t size)364 static ZEND_COLD ZEND_NORETURN void zend_mm_safe_error(zend_mm_heap *heap,
365 	const char *format,
366 	size_t limit,
367 #if ZEND_DEBUG
368 	const char *filename,
369 	uint32_t lineno,
370 #endif
371 	size_t size)
372 {
373 
374 	heap->overflow = 1;
375 	zend_try {
376 		zend_error_noreturn(E_ERROR,
377 			format,
378 			limit,
379 #if ZEND_DEBUG
380 			filename,
381 			lineno,
382 #endif
383 			size);
384 	} zend_catch {
385 	}  zend_end_try();
386 	heap->overflow = 0;
387 	zend_bailout();
388 	exit(1);
389 }
390 
391 #ifdef _WIN32
392 void
stderr_last_error(char * msg)393 stderr_last_error(char *msg)
394 {
395 	LPSTR buf = NULL;
396 	DWORD err = GetLastError();
397 
398 	if (!FormatMessage(
399 			FORMAT_MESSAGE_ALLOCATE_BUFFER |
400 			FORMAT_MESSAGE_FROM_SYSTEM |
401 			FORMAT_MESSAGE_IGNORE_INSERTS,
402 			NULL,
403 			err,
404 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
405 			(LPSTR)&buf,
406 		0, NULL)) {
407 		fprintf(stderr, "\n%s: [0x%08lx]\n", msg, err);
408 	}
409 	else {
410 		fprintf(stderr, "\n%s: [0x%08lx] %s\n", msg, err, buf);
411 	}
412 }
413 #endif
414 
415 /*****************/
416 /* OS Allocation */
417 /*****************/
418 
zend_mm_mmap_fixed(void * addr,size_t size)419 static void *zend_mm_mmap_fixed(void *addr, size_t size)
420 {
421 #ifdef _WIN32
422 	return VirtualAlloc(addr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
423 #else
424 	int flags = MAP_PRIVATE | MAP_ANON;
425 #if defined(MAP_EXCL)
426 	flags |= MAP_FIXED | MAP_EXCL;
427 #endif
428 	/* MAP_FIXED leads to discarding of the old mapping, so it can't be used. */
429 	void *ptr = mmap(addr, size, PROT_READ | PROT_WRITE, flags /*| MAP_POPULATE | MAP_HUGETLB*/, -1, 0);
430 
431 	if (ptr == MAP_FAILED) {
432 #if ZEND_MM_ERROR && !defined(MAP_EXCL)
433 		fprintf(stderr, "\nmmap() failed: [%d] %s\n", errno, strerror(errno));
434 #endif
435 		return NULL;
436 	} else if (ptr != addr) {
437 		if (munmap(ptr, size) != 0) {
438 #if ZEND_MM_ERROR
439 			fprintf(stderr, "\nmunmap() failed: [%d] %s\n", errno, strerror(errno));
440 #endif
441 		}
442 		return NULL;
443 	}
444 	return ptr;
445 #endif
446 }
447 
zend_mm_mmap(size_t size)448 static void *zend_mm_mmap(size_t size)
449 {
450 #ifdef _WIN32
451 	void *ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
452 
453 	if (ptr == NULL) {
454 #if ZEND_MM_ERROR
455 		stderr_last_error("VirtualAlloc() failed");
456 #endif
457 		return NULL;
458 	}
459 	return ptr;
460 #else
461 	void *ptr;
462 
463 #ifdef MAP_HUGETLB
464 	if (zend_mm_use_huge_pages && size == ZEND_MM_CHUNK_SIZE) {
465 		ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_HUGETLB, -1, 0);
466 		if (ptr != MAP_FAILED) {
467 			return ptr;
468 		}
469 	}
470 #endif
471 
472 	ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
473 
474 	if (ptr == MAP_FAILED) {
475 #if ZEND_MM_ERROR
476 		fprintf(stderr, "\nmmap() failed: [%d] %s\n", errno, strerror(errno));
477 #endif
478 		return NULL;
479 	}
480 	return ptr;
481 #endif
482 }
483 
zend_mm_munmap(void * addr,size_t size)484 static void zend_mm_munmap(void *addr, size_t size)
485 {
486 #ifdef _WIN32
487 	if (VirtualFree(addr, 0, MEM_RELEASE) == 0) {
488 #if ZEND_MM_ERROR
489 		stderr_last_error("VirtualFree() failed");
490 #endif
491 	}
492 #else
493 	if (munmap(addr, size) != 0) {
494 #if ZEND_MM_ERROR
495 		fprintf(stderr, "\nmunmap() failed: [%d] %s\n", errno, strerror(errno));
496 #endif
497 	}
498 #endif
499 }
500 
501 /***********/
502 /* Bitmask */
503 /***********/
504 
505 /* number of trailing set (1) bits */
zend_mm_bitset_nts(zend_mm_bitset bitset)506 static zend_always_inline int zend_mm_bitset_nts(zend_mm_bitset bitset)
507 {
508 #if (defined(__GNUC__) || __has_builtin(__builtin_ctzl)) && SIZEOF_ZEND_LONG == SIZEOF_LONG && defined(PHP_HAVE_BUILTIN_CTZL)
509 	return __builtin_ctzl(~bitset);
510 #elif (defined(__GNUC__) || __has_builtin(__builtin_ctzll)) && defined(PHP_HAVE_BUILTIN_CTZLL)
511 	return __builtin_ctzll(~bitset);
512 #elif defined(_WIN32)
513 	unsigned long index;
514 
515 #if defined(_WIN64)
516 	if (!BitScanForward64(&index, ~bitset)) {
517 #else
518 	if (!BitScanForward(&index, ~bitset)) {
519 #endif
520 		/* undefined behavior */
521 		return 32;
522 	}
523 
524 	return (int)index;
525 #else
526 	int n;
527 
528 	if (bitset == (zend_mm_bitset)-1) return ZEND_MM_BITSET_LEN;
529 
530 	n = 0;
531 #if SIZEOF_ZEND_LONG == 8
532 	if (sizeof(zend_mm_bitset) == 8) {
533 		if ((bitset & 0xffffffff) == 0xffffffff) {n += 32; bitset = bitset >> Z_UL(32);}
534 	}
535 #endif
536 	if ((bitset & 0x0000ffff) == 0x0000ffff) {n += 16; bitset = bitset >> 16;}
537 	if ((bitset & 0x000000ff) == 0x000000ff) {n +=  8; bitset = bitset >>  8;}
538 	if ((bitset & 0x0000000f) == 0x0000000f) {n +=  4; bitset = bitset >>  4;}
539 	if ((bitset & 0x00000003) == 0x00000003) {n +=  2; bitset = bitset >>  2;}
540 	return n + (bitset & 1);
541 #endif
542 }
543 
544 static zend_always_inline int zend_mm_bitset_find_zero(zend_mm_bitset *bitset, int size)
545 {
546 	int i = 0;
547 
548 	do {
549 		zend_mm_bitset tmp = bitset[i];
550 		if (tmp != (zend_mm_bitset)-1) {
551 			return i * ZEND_MM_BITSET_LEN + zend_mm_bitset_nts(tmp);
552 		}
553 		i++;
554 	} while (i < size);
555 	return -1;
556 }
557 
558 static zend_always_inline int zend_mm_bitset_find_one(zend_mm_bitset *bitset, int size)
559 {
560 	int i = 0;
561 
562 	do {
563 		zend_mm_bitset tmp = bitset[i];
564 		if (tmp != 0) {
565 			return i * ZEND_MM_BITSET_LEN + zend_ulong_ntz(tmp);
566 		}
567 		i++;
568 	} while (i < size);
569 	return -1;
570 }
571 
572 static zend_always_inline int zend_mm_bitset_find_zero_and_set(zend_mm_bitset *bitset, int size)
573 {
574 	int i = 0;
575 
576 	do {
577 		zend_mm_bitset tmp = bitset[i];
578 		if (tmp != (zend_mm_bitset)-1) {
579 			int n = zend_mm_bitset_nts(tmp);
580 			bitset[i] |= Z_UL(1) << n;
581 			return i * ZEND_MM_BITSET_LEN + n;
582 		}
583 		i++;
584 	} while (i < size);
585 	return -1;
586 }
587 
588 static zend_always_inline int zend_mm_bitset_is_set(zend_mm_bitset *bitset, int bit)
589 {
590 	return ZEND_BIT_TEST(bitset, bit);
591 }
592 
593 static zend_always_inline void zend_mm_bitset_set_bit(zend_mm_bitset *bitset, int bit)
594 {
595 	bitset[bit / ZEND_MM_BITSET_LEN] |= (Z_L(1) << (bit & (ZEND_MM_BITSET_LEN-1)));
596 }
597 
598 static zend_always_inline void zend_mm_bitset_reset_bit(zend_mm_bitset *bitset, int bit)
599 {
600 	bitset[bit / ZEND_MM_BITSET_LEN] &= ~(Z_L(1) << (bit & (ZEND_MM_BITSET_LEN-1)));
601 }
602 
603 static zend_always_inline void zend_mm_bitset_set_range(zend_mm_bitset *bitset, int start, int len)
604 {
605 	if (len == 1) {
606 		zend_mm_bitset_set_bit(bitset, start);
607 	} else {
608 		int pos = start / ZEND_MM_BITSET_LEN;
609 		int end = (start + len - 1) / ZEND_MM_BITSET_LEN;
610 		int bit = start & (ZEND_MM_BITSET_LEN - 1);
611 		zend_mm_bitset tmp;
612 
613 		if (pos != end) {
614 			/* set bits from "bit" to ZEND_MM_BITSET_LEN-1 */
615 			tmp = (zend_mm_bitset)-1 << bit;
616 			bitset[pos++] |= tmp;
617 			while (pos != end) {
618 				/* set all bits */
619 				bitset[pos++] = (zend_mm_bitset)-1;
620 			}
621 			end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1);
622 			/* set bits from "0" to "end" */
623 			tmp = (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end);
624 			bitset[pos] |= tmp;
625 		} else {
626 			end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1);
627 			/* set bits from "bit" to "end" */
628 			tmp = (zend_mm_bitset)-1 << bit;
629 			tmp &= (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end);
630 			bitset[pos] |= tmp;
631 		}
632 	}
633 }
634 
635 static zend_always_inline void zend_mm_bitset_reset_range(zend_mm_bitset *bitset, int start, int len)
636 {
637 	if (len == 1) {
638 		zend_mm_bitset_reset_bit(bitset, start);
639 	} else {
640 		int pos = start / ZEND_MM_BITSET_LEN;
641 		int end = (start + len - 1) / ZEND_MM_BITSET_LEN;
642 		int bit = start & (ZEND_MM_BITSET_LEN - 1);
643 		zend_mm_bitset tmp;
644 
645 		if (pos != end) {
646 			/* reset bits from "bit" to ZEND_MM_BITSET_LEN-1 */
647 			tmp = ~((Z_L(1) << bit) - 1);
648 			bitset[pos++] &= ~tmp;
649 			while (pos != end) {
650 				/* set all bits */
651 				bitset[pos++] = 0;
652 			}
653 			end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1);
654 			/* reset bits from "0" to "end" */
655 			tmp = (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end);
656 			bitset[pos] &= ~tmp;
657 		} else {
658 			end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1);
659 			/* reset bits from "bit" to "end" */
660 			tmp = (zend_mm_bitset)-1 << bit;
661 			tmp &= (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end);
662 			bitset[pos] &= ~tmp;
663 		}
664 	}
665 }
666 
667 static zend_always_inline int zend_mm_bitset_is_free_range(zend_mm_bitset *bitset, int start, int len)
668 {
669 	if (len == 1) {
670 		return !zend_mm_bitset_is_set(bitset, start);
671 	} else {
672 		int pos = start / ZEND_MM_BITSET_LEN;
673 		int end = (start + len - 1) / ZEND_MM_BITSET_LEN;
674 		int bit = start & (ZEND_MM_BITSET_LEN - 1);
675 		zend_mm_bitset tmp;
676 
677 		if (pos != end) {
678 			/* set bits from "bit" to ZEND_MM_BITSET_LEN-1 */
679 			tmp = (zend_mm_bitset)-1 << bit;
680 			if ((bitset[pos++] & tmp) != 0) {
681 				return 0;
682 			}
683 			while (pos != end) {
684 				/* set all bits */
685 				if (bitset[pos++] != 0) {
686 					return 0;
687 				}
688 			}
689 			end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1);
690 			/* set bits from "0" to "end" */
691 			tmp = (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end);
692 			return (bitset[pos] & tmp) == 0;
693 		} else {
694 			end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1);
695 			/* set bits from "bit" to "end" */
696 			tmp = (zend_mm_bitset)-1 << bit;
697 			tmp &= (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end);
698 			return (bitset[pos] & tmp) == 0;
699 		}
700 	}
701 }
702 
703 /**********/
704 /* Chunks */
705 /**********/
706 
707 static void *zend_mm_chunk_alloc_int(size_t size, size_t alignment)
708 {
709 	void *ptr = zend_mm_mmap(size);
710 
711 	if (ptr == NULL) {
712 		return NULL;
713 	} else if (ZEND_MM_ALIGNED_OFFSET(ptr, alignment) == 0) {
714 #ifdef MADV_HUGEPAGE
715 		if (zend_mm_use_huge_pages) {
716 			madvise(ptr, size, MADV_HUGEPAGE);
717 		}
718 #endif
719 		return ptr;
720 	} else {
721 		size_t offset;
722 
723 		/* chunk has to be aligned */
724 		zend_mm_munmap(ptr, size);
725 		ptr = zend_mm_mmap(size + alignment - REAL_PAGE_SIZE);
726 #ifdef _WIN32
727 		offset = ZEND_MM_ALIGNED_OFFSET(ptr, alignment);
728 		zend_mm_munmap(ptr, size + alignment - REAL_PAGE_SIZE);
729 		ptr = zend_mm_mmap_fixed((void*)((char*)ptr + (alignment - offset)), size);
730 		offset = ZEND_MM_ALIGNED_OFFSET(ptr, alignment);
731 		if (offset != 0) {
732 			zend_mm_munmap(ptr, size);
733 			return NULL;
734 		}
735 		return ptr;
736 #else
737 		offset = ZEND_MM_ALIGNED_OFFSET(ptr, alignment);
738 		if (offset != 0) {
739 			offset = alignment - offset;
740 			zend_mm_munmap(ptr, offset);
741 			ptr = (char*)ptr + offset;
742 			alignment -= offset;
743 		}
744 		if (alignment > REAL_PAGE_SIZE) {
745 			zend_mm_munmap((char*)ptr + size, alignment - REAL_PAGE_SIZE);
746 		}
747 # ifdef MADV_HUGEPAGE
748 		if (zend_mm_use_huge_pages) {
749 			madvise(ptr, size, MADV_HUGEPAGE);
750 		}
751 # endif
752 #endif
753 		return ptr;
754 	}
755 }
756 
757 static void *zend_mm_chunk_alloc(zend_mm_heap *heap, size_t size, size_t alignment)
758 {
759 #if ZEND_MM_STORAGE
760 	if (UNEXPECTED(heap->storage)) {
761 		void *ptr = heap->storage->handlers.chunk_alloc(heap->storage, size, alignment);
762 		ZEND_ASSERT(((zend_uintptr_t)((char*)ptr + (alignment-1)) & (alignment-1)) == (zend_uintptr_t)ptr);
763 		return ptr;
764 	}
765 #endif
766 	return zend_mm_chunk_alloc_int(size, alignment);
767 }
768 
769 static void zend_mm_chunk_free(zend_mm_heap *heap, void *addr, size_t size)
770 {
771 #if ZEND_MM_STORAGE
772 	if (UNEXPECTED(heap->storage)) {
773 		heap->storage->handlers.chunk_free(heap->storage, addr, size);
774 		return;
775 	}
776 #endif
777 	zend_mm_munmap(addr, size);
778 }
779 
780 static int zend_mm_chunk_truncate(zend_mm_heap *heap, void *addr, size_t old_size, size_t new_size)
781 {
782 #if ZEND_MM_STORAGE
783 	if (UNEXPECTED(heap->storage)) {
784 		if (heap->storage->handlers.chunk_truncate) {
785 			return heap->storage->handlers.chunk_truncate(heap->storage, addr, old_size, new_size);
786 		} else {
787 			return 0;
788 		}
789 	}
790 #endif
791 #ifndef _WIN32
792 	zend_mm_munmap((char*)addr + new_size, old_size - new_size);
793 	return 1;
794 #else
795 	return 0;
796 #endif
797 }
798 
799 static int zend_mm_chunk_extend(zend_mm_heap *heap, void *addr, size_t old_size, size_t new_size)
800 {
801 #if ZEND_MM_STORAGE
802 	if (UNEXPECTED(heap->storage)) {
803 		if (heap->storage->handlers.chunk_extend) {
804 			return heap->storage->handlers.chunk_extend(heap->storage, addr, old_size, new_size);
805 		} else {
806 			return 0;
807 		}
808 	}
809 #endif
810 #ifndef _WIN32
811 	return (zend_mm_mmap_fixed((char*)addr + old_size, new_size - old_size) != NULL);
812 #else
813 	return 0;
814 #endif
815 }
816 
817 static zend_always_inline void zend_mm_chunk_init(zend_mm_heap *heap, zend_mm_chunk *chunk)
818 {
819 	chunk->heap = heap;
820 	chunk->next = heap->main_chunk;
821 	chunk->prev = heap->main_chunk->prev;
822 	chunk->prev->next = chunk;
823 	chunk->next->prev = chunk;
824 	/* mark first pages as allocated */
825 	chunk->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE;
826 	chunk->free_tail = ZEND_MM_FIRST_PAGE;
827 	/* the younger chunks have bigger number */
828 	chunk->num = chunk->prev->num + 1;
829 	/* mark first pages as allocated */
830 	chunk->free_map[0] = (1L << ZEND_MM_FIRST_PAGE) - 1;
831 	chunk->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE);
832 }
833 
834 /***********************/
835 /* Huge Runs (forward) */
836 /***********************/
837 
838 static size_t zend_mm_get_huge_block_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
839 static void *zend_mm_alloc_huge(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
840 static void zend_mm_free_huge(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
841 
842 #if ZEND_DEBUG
843 static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size, size_t dbg_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
844 #else
845 static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC);
846 #endif
847 
848 /**************/
849 /* Large Runs */
850 /**************/
851 
852 #if ZEND_DEBUG
853 static void *zend_mm_alloc_pages(zend_mm_heap *heap, uint32_t pages_count, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
854 #else
855 static void *zend_mm_alloc_pages(zend_mm_heap *heap, uint32_t pages_count ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
856 #endif
857 {
858 	zend_mm_chunk *chunk = heap->main_chunk;
859 	uint32_t page_num, len;
860 	int steps = 0;
861 
862 	while (1) {
863 		if (UNEXPECTED(chunk->free_pages < pages_count)) {
864 			goto not_found;
865 #if 0
866 		} else if (UNEXPECTED(chunk->free_pages + chunk->free_tail == ZEND_MM_PAGES)) {
867 			if (UNEXPECTED(ZEND_MM_PAGES - chunk->free_tail < pages_count)) {
868 				goto not_found;
869 			} else {
870 				page_num = chunk->free_tail;
871 				goto found;
872 			}
873 		} else if (0) {
874 			/* First-Fit Search */
875 			int free_tail = chunk->free_tail;
876 			zend_mm_bitset *bitset = chunk->free_map;
877 			zend_mm_bitset tmp = *(bitset++);
878 			int i = 0;
879 
880 			while (1) {
881 				/* skip allocated blocks */
882 				while (tmp == (zend_mm_bitset)-1) {
883 					i += ZEND_MM_BITSET_LEN;
884 					if (i == ZEND_MM_PAGES) {
885 						goto not_found;
886 					}
887 					tmp = *(bitset++);
888 				}
889 				/* find first 0 bit */
890 				page_num = i + zend_mm_bitset_nts(tmp);
891 				/* reset bits from 0 to "bit" */
892 				tmp &= tmp + 1;
893 				/* skip free blocks */
894 				while (tmp == 0) {
895 					i += ZEND_MM_BITSET_LEN;
896 					len = i - page_num;
897 					if (len >= pages_count) {
898 						goto found;
899 					} else if (i >= free_tail) {
900 						goto not_found;
901 					}
902 					tmp = *(bitset++);
903 				}
904 				/* find first 1 bit */
905 				len = (i + zend_ulong_ntz(tmp)) - page_num;
906 				if (len >= pages_count) {
907 					goto found;
908 				}
909 				/* set bits from 0 to "bit" */
910 				tmp |= tmp - 1;
911 			}
912 #endif
913 		} else {
914 			/* Best-Fit Search */
915 			int best = -1;
916 			uint32_t best_len = ZEND_MM_PAGES;
917 			uint32_t free_tail = chunk->free_tail;
918 			zend_mm_bitset *bitset = chunk->free_map;
919 			zend_mm_bitset tmp = *(bitset++);
920 			uint32_t i = 0;
921 
922 			while (1) {
923 				/* skip allocated blocks */
924 				while (tmp == (zend_mm_bitset)-1) {
925 					i += ZEND_MM_BITSET_LEN;
926 					if (i == ZEND_MM_PAGES) {
927 						if (best > 0) {
928 							page_num = best;
929 							goto found;
930 						} else {
931 							goto not_found;
932 						}
933 					}
934 					tmp = *(bitset++);
935 				}
936 				/* find first 0 bit */
937 				page_num = i + zend_mm_bitset_nts(tmp);
938 				/* reset bits from 0 to "bit" */
939 				tmp &= tmp + 1;
940 				/* skip free blocks */
941 				while (tmp == 0) {
942 					i += ZEND_MM_BITSET_LEN;
943 					if (i >= free_tail || i == ZEND_MM_PAGES) {
944 						len = ZEND_MM_PAGES - page_num;
945 						if (len >= pages_count && len < best_len) {
946 							chunk->free_tail = page_num + pages_count;
947 							goto found;
948 						} else {
949 							/* set accurate value */
950 							chunk->free_tail = page_num;
951 							if (best > 0) {
952 								page_num = best;
953 								goto found;
954 							} else {
955 								goto not_found;
956 							}
957 						}
958 					}
959 					tmp = *(bitset++);
960 				}
961 				/* find first 1 bit */
962 				len = i + zend_ulong_ntz(tmp) - page_num;
963 				if (len >= pages_count) {
964 					if (len == pages_count) {
965 						goto found;
966 					} else if (len < best_len) {
967 						best_len = len;
968 						best = page_num;
969 					}
970 				}
971 				/* set bits from 0 to "bit" */
972 				tmp |= tmp - 1;
973 			}
974 		}
975 
976 not_found:
977 		if (chunk->next == heap->main_chunk) {
978 get_chunk:
979 			if (heap->cached_chunks) {
980 				heap->cached_chunks_count--;
981 				chunk = heap->cached_chunks;
982 				heap->cached_chunks = chunk->next;
983 			} else {
984 #if ZEND_MM_LIMIT
985 				if (UNEXPECTED(ZEND_MM_CHUNK_SIZE > heap->limit - heap->real_size)) {
986 					if (zend_mm_gc(heap)) {
987 						goto get_chunk;
988 					} else if (heap->overflow == 0) {
989 #if ZEND_DEBUG
990 						zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)", heap->limit, __zend_filename, __zend_lineno, size);
991 #else
992 						zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)", heap->limit, ZEND_MM_PAGE_SIZE * pages_count);
993 #endif
994 						return NULL;
995 					}
996 				}
997 #endif
998 				chunk = (zend_mm_chunk*)zend_mm_chunk_alloc(heap, ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE);
999 				if (UNEXPECTED(chunk == NULL)) {
1000 					/* insufficient memory */
1001 					if (zend_mm_gc(heap) &&
1002 					    (chunk = (zend_mm_chunk*)zend_mm_chunk_alloc(heap, ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE)) != NULL) {
1003 						/* pass */
1004 					} else {
1005 #if !ZEND_MM_LIMIT
1006 						zend_mm_safe_error(heap, "Out of memory");
1007 #elif ZEND_DEBUG
1008 						zend_mm_safe_error(heap, "Out of memory (allocated %zu) at %s:%d (tried to allocate %zu bytes)", heap->real_size, __zend_filename, __zend_lineno, size);
1009 #else
1010 						zend_mm_safe_error(heap, "Out of memory (allocated %zu) (tried to allocate %zu bytes)", heap->real_size, ZEND_MM_PAGE_SIZE * pages_count);
1011 #endif
1012 						return NULL;
1013 					}
1014 				}
1015 #if ZEND_MM_STAT
1016 				do {
1017 					size_t size = heap->real_size + ZEND_MM_CHUNK_SIZE;
1018 					size_t peak = MAX(heap->real_peak, size);
1019 					heap->real_size = size;
1020 					heap->real_peak = peak;
1021 				} while (0);
1022 #elif ZEND_MM_LIMIT
1023 				heap->real_size += ZEND_MM_CHUNK_SIZE;
1024 
1025 #endif
1026 			}
1027 			heap->chunks_count++;
1028 			if (heap->chunks_count > heap->peak_chunks_count) {
1029 				heap->peak_chunks_count = heap->chunks_count;
1030 			}
1031 			zend_mm_chunk_init(heap, chunk);
1032 			page_num = ZEND_MM_FIRST_PAGE;
1033 			len = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE;
1034 			goto found;
1035 		} else {
1036 			chunk = chunk->next;
1037 			steps++;
1038 		}
1039 	}
1040 
1041 found:
1042 	if (steps > 2 && pages_count < 8) {
1043 		/* move chunk into the head of the linked-list */
1044 		chunk->prev->next = chunk->next;
1045 		chunk->next->prev = chunk->prev;
1046 		chunk->next = heap->main_chunk->next;
1047 		chunk->prev = heap->main_chunk;
1048 		chunk->prev->next = chunk;
1049 		chunk->next->prev = chunk;
1050 	}
1051 	/* mark run as allocated */
1052 	chunk->free_pages -= pages_count;
1053 	zend_mm_bitset_set_range(chunk->free_map, page_num, pages_count);
1054 	chunk->map[page_num] = ZEND_MM_LRUN(pages_count);
1055 	if (page_num == chunk->free_tail) {
1056 		chunk->free_tail = page_num + pages_count;
1057 	}
1058 	return ZEND_MM_PAGE_ADDR(chunk, page_num);
1059 }
1060 
1061 static zend_always_inline void *zend_mm_alloc_large_ex(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1062 {
1063 	int pages_count = (int)ZEND_MM_SIZE_TO_NUM(size, ZEND_MM_PAGE_SIZE);
1064 #if ZEND_DEBUG
1065 	void *ptr = zend_mm_alloc_pages(heap, pages_count, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1066 #else
1067 	void *ptr = zend_mm_alloc_pages(heap, pages_count ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1068 #endif
1069 #if ZEND_MM_STAT
1070 	do {
1071 		size_t size = heap->size + pages_count * ZEND_MM_PAGE_SIZE;
1072 		size_t peak = MAX(heap->peak, size);
1073 		heap->size = size;
1074 		heap->peak = peak;
1075 	} while (0);
1076 #endif
1077 	return ptr;
1078 }
1079 
1080 #if ZEND_DEBUG
1081 static zend_never_inline void *zend_mm_alloc_large(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1082 {
1083 	return zend_mm_alloc_large_ex(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1084 }
1085 #else
1086 static zend_never_inline void *zend_mm_alloc_large(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1087 {
1088 	return zend_mm_alloc_large_ex(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1089 }
1090 #endif
1091 
1092 static zend_always_inline void zend_mm_delete_chunk(zend_mm_heap *heap, zend_mm_chunk *chunk)
1093 {
1094 	chunk->next->prev = chunk->prev;
1095 	chunk->prev->next = chunk->next;
1096 	heap->chunks_count--;
1097 	if (heap->chunks_count + heap->cached_chunks_count < heap->avg_chunks_count + 0.1
1098 	 || (heap->chunks_count == heap->last_chunks_delete_boundary
1099 	  && heap->last_chunks_delete_count >= 4)) {
1100 		/* delay deletion */
1101 		heap->cached_chunks_count++;
1102 		chunk->next = heap->cached_chunks;
1103 		heap->cached_chunks = chunk;
1104 	} else {
1105 #if ZEND_MM_STAT || ZEND_MM_LIMIT
1106 		heap->real_size -= ZEND_MM_CHUNK_SIZE;
1107 #endif
1108 		if (!heap->cached_chunks) {
1109 			if (heap->chunks_count != heap->last_chunks_delete_boundary) {
1110 				heap->last_chunks_delete_boundary = heap->chunks_count;
1111 				heap->last_chunks_delete_count = 0;
1112 			} else {
1113 				heap->last_chunks_delete_count++;
1114 			}
1115 		}
1116 		if (!heap->cached_chunks || chunk->num > heap->cached_chunks->num) {
1117 			zend_mm_chunk_free(heap, chunk, ZEND_MM_CHUNK_SIZE);
1118 		} else {
1119 //TODO: select the best chunk to delete???
1120 			chunk->next = heap->cached_chunks->next;
1121 			zend_mm_chunk_free(heap, heap->cached_chunks, ZEND_MM_CHUNK_SIZE);
1122 			heap->cached_chunks = chunk;
1123 		}
1124 	}
1125 }
1126 
1127 static zend_always_inline void zend_mm_free_pages_ex(zend_mm_heap *heap, zend_mm_chunk *chunk, uint32_t page_num, uint32_t pages_count, int free_chunk)
1128 {
1129 	chunk->free_pages += pages_count;
1130 	zend_mm_bitset_reset_range(chunk->free_map, page_num, pages_count);
1131 	chunk->map[page_num] = 0;
1132 	if (chunk->free_tail == page_num + pages_count) {
1133 		/* this setting may be not accurate */
1134 		chunk->free_tail = page_num;
1135 	}
1136 	if (free_chunk && chunk->free_pages == ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE) {
1137 		zend_mm_delete_chunk(heap, chunk);
1138 	}
1139 }
1140 
1141 static zend_never_inline void zend_mm_free_pages(zend_mm_heap *heap, zend_mm_chunk *chunk, int page_num, int pages_count)
1142 {
1143 	zend_mm_free_pages_ex(heap, chunk, page_num, pages_count, 1);
1144 }
1145 
1146 static zend_always_inline void zend_mm_free_large(zend_mm_heap *heap, zend_mm_chunk *chunk, int page_num, int pages_count)
1147 {
1148 #if ZEND_MM_STAT
1149 	heap->size -= pages_count * ZEND_MM_PAGE_SIZE;
1150 #endif
1151 	zend_mm_free_pages(heap, chunk, page_num, pages_count);
1152 }
1153 
1154 /**************/
1155 /* Small Runs */
1156 /**************/
1157 
1158 /* higher set bit number (0->N/A, 1->1, 2->2, 4->3, 8->4, 127->7, 128->8 etc) */
1159 static zend_always_inline int zend_mm_small_size_to_bit(int size)
1160 {
1161 #if (defined(__GNUC__) || __has_builtin(__builtin_clz))  && defined(PHP_HAVE_BUILTIN_CLZ)
1162 	return (__builtin_clz(size) ^ 0x1f) + 1;
1163 #elif defined(_WIN32)
1164 	unsigned long index;
1165 
1166 	if (!BitScanReverse(&index, (unsigned long)size)) {
1167 		/* undefined behavior */
1168 		return 64;
1169 	}
1170 
1171 	return (((31 - (int)index) ^ 0x1f) + 1);
1172 #else
1173 	int n = 16;
1174 	if (size <= 0x00ff) {n -= 8; size = size << 8;}
1175 	if (size <= 0x0fff) {n -= 4; size = size << 4;}
1176 	if (size <= 0x3fff) {n -= 2; size = size << 2;}
1177 	if (size <= 0x7fff) {n -= 1;}
1178 	return n;
1179 #endif
1180 }
1181 
1182 #ifndef MAX
1183 # define MAX(a, b) (((a) > (b)) ? (a) : (b))
1184 #endif
1185 
1186 #ifndef MIN
1187 # define MIN(a, b) (((a) < (b)) ? (a) : (b))
1188 #endif
1189 
1190 static zend_always_inline int zend_mm_small_size_to_bin(size_t size)
1191 {
1192 #if 0
1193 	int n;
1194                             /*0,  1,  2,  3,  4,  5,  6,  7,  8,  9  10, 11, 12*/
1195 	static const int f1[] = { 3,  3,  3,  3,  3,  3,  3,  4,  5,  6,  7,  8,  9};
1196 	static const int f2[] = { 0,  0,  0,  0,  0,  0,  0,  4,  8, 12, 16, 20, 24};
1197 
1198 	if (UNEXPECTED(size <= 2)) return 0;
1199 	n = zend_mm_small_size_to_bit(size - 1);
1200 	return ((size-1) >> f1[n]) + f2[n];
1201 #else
1202 	unsigned int t1, t2;
1203 
1204 	if (size <= 64) {
1205 		/* we need to support size == 0 ... */
1206 		return (size - !!size) >> 3;
1207 	} else {
1208 		t1 = size - 1;
1209 		t2 = zend_mm_small_size_to_bit(t1) - 3;
1210 		t1 = t1 >> t2;
1211 		t2 = t2 - 3;
1212 		t2 = t2 << 2;
1213 		return (int)(t1 + t2);
1214 	}
1215 #endif
1216 }
1217 
1218 #define ZEND_MM_SMALL_SIZE_TO_BIN(size)  zend_mm_small_size_to_bin(size)
1219 
1220 static zend_never_inline void *zend_mm_alloc_small_slow(zend_mm_heap *heap, uint32_t bin_num ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1221 {
1222     zend_mm_chunk *chunk;
1223     int page_num;
1224 	zend_mm_bin *bin;
1225 	zend_mm_free_slot *p, *end;
1226 
1227 #if ZEND_DEBUG
1228 	bin = (zend_mm_bin*)zend_mm_alloc_pages(heap, bin_pages[bin_num], bin_data_size[bin_num] ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1229 #else
1230 	bin = (zend_mm_bin*)zend_mm_alloc_pages(heap, bin_pages[bin_num] ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1231 #endif
1232 	if (UNEXPECTED(bin == NULL)) {
1233 		/* insufficient memory */
1234 		return NULL;
1235 	}
1236 
1237 	chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(bin, ZEND_MM_CHUNK_SIZE);
1238 	page_num = ZEND_MM_ALIGNED_OFFSET(bin, ZEND_MM_CHUNK_SIZE) / ZEND_MM_PAGE_SIZE;
1239 	chunk->map[page_num] = ZEND_MM_SRUN(bin_num);
1240 	if (bin_pages[bin_num] > 1) {
1241 		uint32_t i = 1;
1242 
1243 		do {
1244 			chunk->map[page_num+i] = ZEND_MM_NRUN(bin_num, i);
1245 			i++;
1246 		} while (i < bin_pages[bin_num]);
1247 	}
1248 
1249 	/* create a linked list of elements from 1 to last */
1250 	end = (zend_mm_free_slot*)((char*)bin + (bin_data_size[bin_num] * (bin_elements[bin_num] - 1)));
1251 	heap->free_slot[bin_num] = p = (zend_mm_free_slot*)((char*)bin + bin_data_size[bin_num]);
1252 	do {
1253 		p->next_free_slot = (zend_mm_free_slot*)((char*)p + bin_data_size[bin_num]);
1254 #if ZEND_DEBUG
1255 		do {
1256 			zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
1257 			dbg->size = 0;
1258 		} while (0);
1259 #endif
1260 		p = (zend_mm_free_slot*)((char*)p + bin_data_size[bin_num]);
1261 	} while (p != end);
1262 
1263 	/* terminate list using NULL */
1264 	p->next_free_slot = NULL;
1265 #if ZEND_DEBUG
1266 		do {
1267 			zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
1268 			dbg->size = 0;
1269 		} while (0);
1270 #endif
1271 
1272 	/* return first element */
1273 	return (char*)bin;
1274 }
1275 
1276 static zend_always_inline void *zend_mm_alloc_small(zend_mm_heap *heap, size_t size, int bin_num ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1277 {
1278 #if ZEND_MM_STAT
1279 	do {
1280 		size_t size = heap->size + bin_data_size[bin_num];
1281 		size_t peak = MAX(heap->peak, size);
1282 		heap->size = size;
1283 		heap->peak = peak;
1284 	} while (0);
1285 #endif
1286 
1287 	if (EXPECTED(heap->free_slot[bin_num] != NULL)) {
1288 		zend_mm_free_slot *p = heap->free_slot[bin_num];
1289 		heap->free_slot[bin_num] = p->next_free_slot;
1290 		return (void*)p;
1291 	} else {
1292 		return zend_mm_alloc_small_slow(heap, bin_num ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1293 	}
1294 }
1295 
1296 static zend_always_inline void zend_mm_free_small(zend_mm_heap *heap, void *ptr, int bin_num)
1297 {
1298 	zend_mm_free_slot *p;
1299 
1300 #if ZEND_MM_STAT
1301 	heap->size -= bin_data_size[bin_num];
1302 #endif
1303 
1304 #if ZEND_DEBUG
1305 	do {
1306 		zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)ptr + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
1307 		dbg->size = 0;
1308 	} while (0);
1309 #endif
1310 
1311     p = (zend_mm_free_slot*)ptr;
1312     p->next_free_slot = heap->free_slot[bin_num];
1313     heap->free_slot[bin_num] = p;
1314 }
1315 
1316 /********/
1317 /* Heap */
1318 /********/
1319 
1320 #if ZEND_DEBUG
1321 static zend_always_inline zend_mm_debug_info *zend_mm_get_debug_info(zend_mm_heap *heap, void *ptr)
1322 {
1323 	size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE);
1324 	zend_mm_chunk *chunk;
1325 	int page_num;
1326 	zend_mm_page_info info;
1327 
1328 	ZEND_MM_CHECK(page_offset != 0, "zend_mm_heap corrupted");
1329 	chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE);
1330 	page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE);
1331 	info = chunk->map[page_num];
1332 	ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted");
1333 	if (EXPECTED(info & ZEND_MM_IS_SRUN)) {
1334 		int bin_num = ZEND_MM_SRUN_BIN_NUM(info);
1335 		return (zend_mm_debug_info*)((char*)ptr + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
1336 	} else /* if (info & ZEND_MM_IS_LRUN) */ {
1337 		int pages_count = ZEND_MM_LRUN_PAGES(info);
1338 
1339 		return (zend_mm_debug_info*)((char*)ptr + ZEND_MM_PAGE_SIZE * pages_count - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
1340 	}
1341 }
1342 #endif
1343 
1344 static zend_always_inline void *zend_mm_alloc_heap(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1345 {
1346 	void *ptr;
1347 #if ZEND_DEBUG
1348 	size_t real_size = size;
1349 	zend_mm_debug_info *dbg;
1350 
1351 	/* special handling for zero-size allocation */
1352 	size = MAX(size, 1);
1353 	size = ZEND_MM_ALIGNED_SIZE(size) + ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info));
1354 	if (UNEXPECTED(size < real_size)) {
1355 		zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu + %zu)", ZEND_MM_ALIGNED_SIZE(real_size), ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
1356 		return NULL;
1357 	}
1358 #endif
1359 	if (EXPECTED(size <= ZEND_MM_MAX_SMALL_SIZE)) {
1360 		ptr = zend_mm_alloc_small(heap, size, ZEND_MM_SMALL_SIZE_TO_BIN(size) ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1361 #if ZEND_DEBUG
1362 		dbg = zend_mm_get_debug_info(heap, ptr);
1363 		dbg->size = real_size;
1364 		dbg->filename = __zend_filename;
1365 		dbg->orig_filename = __zend_orig_filename;
1366 		dbg->lineno = __zend_lineno;
1367 		dbg->orig_lineno = __zend_orig_lineno;
1368 #endif
1369 		return ptr;
1370 	} else if (EXPECTED(size <= ZEND_MM_MAX_LARGE_SIZE)) {
1371 		ptr = zend_mm_alloc_large(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1372 #if ZEND_DEBUG
1373 		dbg = zend_mm_get_debug_info(heap, ptr);
1374 		dbg->size = real_size;
1375 		dbg->filename = __zend_filename;
1376 		dbg->orig_filename = __zend_orig_filename;
1377 		dbg->lineno = __zend_lineno;
1378 		dbg->orig_lineno = __zend_orig_lineno;
1379 #endif
1380 		return ptr;
1381 	} else {
1382 #if ZEND_DEBUG
1383 		size = real_size;
1384 #endif
1385 		return zend_mm_alloc_huge(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1386 	}
1387 }
1388 
1389 static zend_always_inline void zend_mm_free_heap(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1390 {
1391 	size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE);
1392 
1393 	if (UNEXPECTED(page_offset == 0)) {
1394 		if (ptr != NULL) {
1395 			zend_mm_free_huge(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1396 		}
1397 	} else {
1398 		zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE);
1399 		int page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE);
1400 		zend_mm_page_info info = chunk->map[page_num];
1401 
1402 		ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted");
1403 		if (EXPECTED(info & ZEND_MM_IS_SRUN)) {
1404 			zend_mm_free_small(heap, ptr, ZEND_MM_SRUN_BIN_NUM(info));
1405 		} else /* if (info & ZEND_MM_IS_LRUN) */ {
1406 			int pages_count = ZEND_MM_LRUN_PAGES(info);
1407 
1408 			ZEND_MM_CHECK(ZEND_MM_ALIGNED_OFFSET(page_offset, ZEND_MM_PAGE_SIZE) == 0, "zend_mm_heap corrupted");
1409 			zend_mm_free_large(heap, chunk, page_num, pages_count);
1410 		}
1411 	}
1412 }
1413 
1414 static size_t zend_mm_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1415 {
1416 	size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE);
1417 
1418 	if (UNEXPECTED(page_offset == 0)) {
1419 		return zend_mm_get_huge_block_size(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1420 	} else {
1421 		zend_mm_chunk *chunk;
1422 #if 0 && ZEND_DEBUG
1423 		zend_mm_debug_info *dbg = zend_mm_get_debug_info(heap, ptr);
1424 		return dbg->size;
1425 #else
1426 		int page_num;
1427 		zend_mm_page_info info;
1428 
1429 		chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE);
1430 		page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE);
1431 		info = chunk->map[page_num];
1432 		ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted");
1433 		if (EXPECTED(info & ZEND_MM_IS_SRUN)) {
1434 			return bin_data_size[ZEND_MM_SRUN_BIN_NUM(info)];
1435 		} else /* if (info & ZEND_MM_IS_LARGE_RUN) */ {
1436 			return ZEND_MM_LRUN_PAGES(info) * ZEND_MM_PAGE_SIZE;
1437 		}
1438 #endif
1439 	}
1440 }
1441 
1442 static zend_never_inline void *zend_mm_realloc_slow(zend_mm_heap *heap, void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1443 {
1444 	void *ret;
1445 
1446 #if ZEND_MM_STAT
1447 	do {
1448 		size_t orig_peak = heap->peak;
1449 		size_t orig_real_peak = heap->real_peak;
1450 #endif
1451 		ret = zend_mm_alloc_heap(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1452 		memcpy(ret, ptr, copy_size);
1453 		zend_mm_free_heap(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1454 #if ZEND_MM_STAT
1455 		heap->peak = MAX(orig_peak, heap->size);
1456 		heap->real_peak = MAX(orig_real_peak, heap->real_size);
1457 	} while (0);
1458 #endif
1459 	return ret;
1460 }
1461 
1462 static zend_never_inline void *zend_mm_realloc_huge(zend_mm_heap *heap, void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1463 {
1464 	size_t old_size;
1465 	size_t new_size;
1466 #if ZEND_DEBUG
1467 	size_t real_size;
1468 #endif
1469 
1470 	old_size = zend_mm_get_huge_block_size(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1471 #if ZEND_DEBUG
1472 	real_size = size;
1473 	size = ZEND_MM_ALIGNED_SIZE(size) + ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info));
1474 #endif
1475 	if (size > ZEND_MM_MAX_LARGE_SIZE) {
1476 #if ZEND_DEBUG
1477 		size = real_size;
1478 #endif
1479 #ifdef ZEND_WIN32
1480 		/* On Windows we don't have ability to extend huge blocks in-place.
1481 		 * We allocate them with 2MB size granularity, to avoid many
1482 		 * reallocations when they are extended by small pieces
1483 		 */
1484 		new_size = ZEND_MM_ALIGNED_SIZE_EX(size, MAX(REAL_PAGE_SIZE, ZEND_MM_CHUNK_SIZE));
1485 #else
1486 		new_size = ZEND_MM_ALIGNED_SIZE_EX(size, REAL_PAGE_SIZE);
1487 #endif
1488 		if (new_size == old_size) {
1489 #if ZEND_DEBUG
1490 			zend_mm_change_huge_block_size(heap, ptr, new_size, real_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1491 #else
1492 			zend_mm_change_huge_block_size(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1493 #endif
1494 			return ptr;
1495 		} else if (new_size < old_size) {
1496 			/* unmup tail */
1497 			if (zend_mm_chunk_truncate(heap, ptr, old_size, new_size)) {
1498 #if ZEND_MM_STAT || ZEND_MM_LIMIT
1499 				heap->real_size -= old_size - new_size;
1500 #endif
1501 #if ZEND_MM_STAT
1502 				heap->size -= old_size - new_size;
1503 #endif
1504 #if ZEND_DEBUG
1505 				zend_mm_change_huge_block_size(heap, ptr, new_size, real_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1506 #else
1507 				zend_mm_change_huge_block_size(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1508 #endif
1509 				return ptr;
1510 			}
1511 		} else /* if (new_size > old_size) */ {
1512 #if ZEND_MM_LIMIT
1513 			if (UNEXPECTED(new_size - old_size > heap->limit - heap->real_size)) {
1514 				if (zend_mm_gc(heap) && new_size - old_size <= heap->limit - heap->real_size) {
1515 					/* pass */
1516 				} else if (heap->overflow == 0) {
1517 #if ZEND_DEBUG
1518 					zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)", heap->limit, __zend_filename, __zend_lineno, size);
1519 #else
1520 					zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)", heap->limit, size);
1521 #endif
1522 					return NULL;
1523 				}
1524 			}
1525 #endif
1526 			/* try to map tail right after this block */
1527 			if (zend_mm_chunk_extend(heap, ptr, old_size, new_size)) {
1528 #if ZEND_MM_STAT || ZEND_MM_LIMIT
1529 				heap->real_size += new_size - old_size;
1530 #endif
1531 #if ZEND_MM_STAT
1532 				heap->real_peak = MAX(heap->real_peak, heap->real_size);
1533 				heap->size += new_size - old_size;
1534 				heap->peak = MAX(heap->peak, heap->size);
1535 #endif
1536 #if ZEND_DEBUG
1537 				zend_mm_change_huge_block_size(heap, ptr, new_size, real_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1538 #else
1539 				zend_mm_change_huge_block_size(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1540 #endif
1541 				return ptr;
1542 			}
1543 		}
1544 	}
1545 
1546 	return zend_mm_realloc_slow(heap, ptr, size, MIN(old_size, copy_size) ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1547 }
1548 
1549 static zend_always_inline void *zend_mm_realloc_heap(zend_mm_heap *heap, void *ptr, size_t size, zend_bool use_copy_size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1550 {
1551 	size_t page_offset;
1552 	size_t old_size;
1553 	size_t new_size;
1554 	void *ret;
1555 #if ZEND_DEBUG
1556 	zend_mm_debug_info *dbg;
1557 #endif
1558 
1559 	page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE);
1560 	if (UNEXPECTED(page_offset == 0)) {
1561 		if (EXPECTED(ptr == NULL)) {
1562 			return _zend_mm_alloc(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1563 		} else {
1564 			return zend_mm_realloc_huge(heap, ptr, size, copy_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1565 		}
1566 	} else {
1567 		zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE);
1568 		int page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE);
1569 		zend_mm_page_info info = chunk->map[page_num];
1570 #if ZEND_DEBUG
1571 		size_t real_size = size;
1572 
1573 		size = ZEND_MM_ALIGNED_SIZE(size) + ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info));
1574 #endif
1575 
1576 		ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted");
1577 		if (info & ZEND_MM_IS_SRUN) {
1578 			int old_bin_num = ZEND_MM_SRUN_BIN_NUM(info);
1579 
1580 			do {
1581 				old_size = bin_data_size[old_bin_num];
1582 
1583 				/* Check if requested size fits into current bin */
1584 				if (size <= old_size) {
1585 					/* Check if truncation is necessary */
1586 					if (old_bin_num > 0 && size < bin_data_size[old_bin_num - 1]) {
1587 						/* truncation */
1588 						ret = zend_mm_alloc_small(heap, size, ZEND_MM_SMALL_SIZE_TO_BIN(size) ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1589 						copy_size = use_copy_size ? MIN(size, copy_size) : size;
1590 						memcpy(ret, ptr, copy_size);
1591 						zend_mm_free_small(heap, ptr, old_bin_num);
1592 					} else {
1593 						/* reallocation in-place */
1594 						ret = ptr;
1595 					}
1596 				} else if (size <= ZEND_MM_MAX_SMALL_SIZE) {
1597 					/* small extension */
1598 
1599 #if ZEND_MM_STAT
1600 					do {
1601 						size_t orig_peak = heap->peak;
1602 						size_t orig_real_peak = heap->real_peak;
1603 #endif
1604 						ret = zend_mm_alloc_small(heap, size, ZEND_MM_SMALL_SIZE_TO_BIN(size) ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1605 						copy_size = use_copy_size ? MIN(old_size, copy_size) : old_size;
1606 						memcpy(ret, ptr, copy_size);
1607 						zend_mm_free_small(heap, ptr, old_bin_num);
1608 #if ZEND_MM_STAT
1609 						heap->peak = MAX(orig_peak, heap->size);
1610 						heap->real_peak = MAX(orig_real_peak, heap->real_size);
1611 					} while (0);
1612 #endif
1613 				} else {
1614 					/* slow reallocation */
1615 					break;
1616 				}
1617 
1618 #if ZEND_DEBUG
1619 				dbg = zend_mm_get_debug_info(heap, ret);
1620 				dbg->size = real_size;
1621 				dbg->filename = __zend_filename;
1622 				dbg->orig_filename = __zend_orig_filename;
1623 				dbg->lineno = __zend_lineno;
1624 				dbg->orig_lineno = __zend_orig_lineno;
1625 #endif
1626 				return ret;
1627 			}  while (0);
1628 
1629 		} else /* if (info & ZEND_MM_IS_LARGE_RUN) */ {
1630 			ZEND_MM_CHECK(ZEND_MM_ALIGNED_OFFSET(page_offset, ZEND_MM_PAGE_SIZE) == 0, "zend_mm_heap corrupted");
1631 			old_size = ZEND_MM_LRUN_PAGES(info) * ZEND_MM_PAGE_SIZE;
1632 			if (size > ZEND_MM_MAX_SMALL_SIZE && size <= ZEND_MM_MAX_LARGE_SIZE) {
1633 				new_size = ZEND_MM_ALIGNED_SIZE_EX(size, ZEND_MM_PAGE_SIZE);
1634 				if (new_size == old_size) {
1635 #if ZEND_DEBUG
1636 					dbg = zend_mm_get_debug_info(heap, ptr);
1637 					dbg->size = real_size;
1638 					dbg->filename = __zend_filename;
1639 					dbg->orig_filename = __zend_orig_filename;
1640 					dbg->lineno = __zend_lineno;
1641 					dbg->orig_lineno = __zend_orig_lineno;
1642 #endif
1643 					return ptr;
1644 				} else if (new_size < old_size) {
1645 					/* free tail pages */
1646 					int new_pages_count = (int)(new_size / ZEND_MM_PAGE_SIZE);
1647 					int rest_pages_count = (int)((old_size - new_size) / ZEND_MM_PAGE_SIZE);
1648 
1649 #if ZEND_MM_STAT
1650 					heap->size -= rest_pages_count * ZEND_MM_PAGE_SIZE;
1651 #endif
1652 					chunk->map[page_num] = ZEND_MM_LRUN(new_pages_count);
1653 					chunk->free_pages += rest_pages_count;
1654 					zend_mm_bitset_reset_range(chunk->free_map, page_num + new_pages_count, rest_pages_count);
1655 #if ZEND_DEBUG
1656 					dbg = zend_mm_get_debug_info(heap, ptr);
1657 					dbg->size = real_size;
1658 					dbg->filename = __zend_filename;
1659 					dbg->orig_filename = __zend_orig_filename;
1660 					dbg->lineno = __zend_lineno;
1661 					dbg->orig_lineno = __zend_orig_lineno;
1662 #endif
1663 					return ptr;
1664 				} else /* if (new_size > old_size) */ {
1665 					int new_pages_count = (int)(new_size / ZEND_MM_PAGE_SIZE);
1666 					int old_pages_count = (int)(old_size / ZEND_MM_PAGE_SIZE);
1667 
1668 					/* try to allocate tail pages after this block */
1669 					if (page_num + new_pages_count <= ZEND_MM_PAGES &&
1670 					    zend_mm_bitset_is_free_range(chunk->free_map, page_num + old_pages_count, new_pages_count - old_pages_count)) {
1671 #if ZEND_MM_STAT
1672 						do {
1673 							size_t size = heap->size + (new_size - old_size);
1674 							size_t peak = MAX(heap->peak, size);
1675 							heap->size = size;
1676 							heap->peak = peak;
1677 						} while (0);
1678 #endif
1679 						chunk->free_pages -= new_pages_count - old_pages_count;
1680 						zend_mm_bitset_set_range(chunk->free_map, page_num + old_pages_count, new_pages_count - old_pages_count);
1681 						chunk->map[page_num] = ZEND_MM_LRUN(new_pages_count);
1682 #if ZEND_DEBUG
1683 						dbg = zend_mm_get_debug_info(heap, ptr);
1684 						dbg->size = real_size;
1685 						dbg->filename = __zend_filename;
1686 						dbg->orig_filename = __zend_orig_filename;
1687 						dbg->lineno = __zend_lineno;
1688 						dbg->orig_lineno = __zend_orig_lineno;
1689 #endif
1690 						return ptr;
1691 					}
1692 				}
1693 			}
1694 		}
1695 #if ZEND_DEBUG
1696 		size = real_size;
1697 #endif
1698 	}
1699 
1700 	copy_size = MIN(old_size, copy_size);
1701 	return zend_mm_realloc_slow(heap, ptr, size, copy_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1702 }
1703 
1704 /*********************/
1705 /* Huge Runs (again) */
1706 /*********************/
1707 
1708 #if ZEND_DEBUG
1709 static void zend_mm_add_huge_block(zend_mm_heap *heap, void *ptr, size_t size, size_t dbg_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1710 #else
1711 static void zend_mm_add_huge_block(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1712 #endif
1713 {
1714 	zend_mm_huge_list *list = (zend_mm_huge_list*)zend_mm_alloc_heap(heap, sizeof(zend_mm_huge_list) ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1715 	list->ptr = ptr;
1716 	list->size = size;
1717 	list->next = heap->huge_list;
1718 #if ZEND_DEBUG
1719 	list->dbg.size = dbg_size;
1720 	list->dbg.filename = __zend_filename;
1721 	list->dbg.orig_filename = __zend_orig_filename;
1722 	list->dbg.lineno = __zend_lineno;
1723 	list->dbg.orig_lineno = __zend_orig_lineno;
1724 #endif
1725 	heap->huge_list = list;
1726 }
1727 
1728 static size_t zend_mm_del_huge_block(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1729 {
1730 	zend_mm_huge_list *prev = NULL;
1731 	zend_mm_huge_list *list = heap->huge_list;
1732 	while (list != NULL) {
1733 		if (list->ptr == ptr) {
1734 			size_t size;
1735 
1736 			if (prev) {
1737 				prev->next = list->next;
1738 			} else {
1739 				heap->huge_list = list->next;
1740 			}
1741 			size = list->size;
1742 			zend_mm_free_heap(heap, list ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1743 			return size;
1744 		}
1745 		prev = list;
1746 		list = list->next;
1747 	}
1748 	ZEND_MM_CHECK(0, "zend_mm_heap corrupted");
1749 	return 0;
1750 }
1751 
1752 static size_t zend_mm_get_huge_block_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1753 {
1754 	zend_mm_huge_list *list = heap->huge_list;
1755 	while (list != NULL) {
1756 		if (list->ptr == ptr) {
1757 			return list->size;
1758 		}
1759 		list = list->next;
1760 	}
1761 	ZEND_MM_CHECK(0, "zend_mm_heap corrupted");
1762 	return 0;
1763 }
1764 
1765 #if ZEND_DEBUG
1766 static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size, size_t dbg_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1767 #else
1768 static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1769 #endif
1770 {
1771 	zend_mm_huge_list *list = heap->huge_list;
1772 	while (list != NULL) {
1773 		if (list->ptr == ptr) {
1774 			list->size = size;
1775 #if ZEND_DEBUG
1776 			list->dbg.size = dbg_size;
1777 			list->dbg.filename = __zend_filename;
1778 			list->dbg.orig_filename = __zend_orig_filename;
1779 			list->dbg.lineno = __zend_lineno;
1780 			list->dbg.orig_lineno = __zend_orig_lineno;
1781 #endif
1782 			return;
1783 		}
1784 		list = list->next;
1785 	}
1786 }
1787 
1788 static void *zend_mm_alloc_huge(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1789 {
1790 #ifdef ZEND_WIN32
1791 	/* On Windows we don't have ability to extend huge blocks in-place.
1792 	 * We allocate them with 2MB size granularity, to avoid many
1793 	 * reallocations when they are extended by small pieces
1794 	 */
1795 	size_t alignment = MAX(REAL_PAGE_SIZE, ZEND_MM_CHUNK_SIZE);
1796 #else
1797 	size_t alignment = REAL_PAGE_SIZE;
1798 #endif
1799 	size_t new_size = ZEND_MM_ALIGNED_SIZE_EX(size, alignment);
1800 	void *ptr;
1801 
1802 	if (UNEXPECTED(new_size < size)) {
1803 		zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu + %zu)", size, alignment);
1804 	}
1805 
1806 #if ZEND_MM_LIMIT
1807 	if (UNEXPECTED(new_size > heap->limit - heap->real_size)) {
1808 		if (zend_mm_gc(heap) && new_size <= heap->limit - heap->real_size) {
1809 			/* pass */
1810 		} else if (heap->overflow == 0) {
1811 #if ZEND_DEBUG
1812 			zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)", heap->limit, __zend_filename, __zend_lineno, size);
1813 #else
1814 			zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)", heap->limit, size);
1815 #endif
1816 			return NULL;
1817 		}
1818 	}
1819 #endif
1820 	ptr = zend_mm_chunk_alloc(heap, new_size, ZEND_MM_CHUNK_SIZE);
1821 	if (UNEXPECTED(ptr == NULL)) {
1822 		/* insufficient memory */
1823 		if (zend_mm_gc(heap) &&
1824 		    (ptr = zend_mm_chunk_alloc(heap, new_size, ZEND_MM_CHUNK_SIZE)) != NULL) {
1825 			/* pass */
1826 		} else {
1827 #if !ZEND_MM_LIMIT
1828 			zend_mm_safe_error(heap, "Out of memory");
1829 #elif ZEND_DEBUG
1830 			zend_mm_safe_error(heap, "Out of memory (allocated %zu) at %s:%d (tried to allocate %zu bytes)", heap->real_size, __zend_filename, __zend_lineno, size);
1831 #else
1832 			zend_mm_safe_error(heap, "Out of memory (allocated %zu) (tried to allocate %zu bytes)", heap->real_size, size);
1833 #endif
1834 			return NULL;
1835 		}
1836 	}
1837 #if ZEND_DEBUG
1838 	zend_mm_add_huge_block(heap, ptr, new_size, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1839 #else
1840 	zend_mm_add_huge_block(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1841 #endif
1842 #if ZEND_MM_STAT
1843 	do {
1844 		size_t size = heap->real_size + new_size;
1845 		size_t peak = MAX(heap->real_peak, size);
1846 		heap->real_size = size;
1847 		heap->real_peak = peak;
1848 	} while (0);
1849 	do {
1850 		size_t size = heap->size + new_size;
1851 		size_t peak = MAX(heap->peak, size);
1852 		heap->size = size;
1853 		heap->peak = peak;
1854 	} while (0);
1855 #elif ZEND_MM_LIMIT
1856 	heap->real_size += new_size;
1857 #endif
1858 	return ptr;
1859 }
1860 
1861 static void zend_mm_free_huge(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
1862 {
1863 	size_t size;
1864 
1865 	ZEND_MM_CHECK(ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE) == 0, "zend_mm_heap corrupted");
1866 	size = zend_mm_del_huge_block(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
1867 	zend_mm_chunk_free(heap, ptr, size);
1868 #if ZEND_MM_STAT || ZEND_MM_LIMIT
1869 	heap->real_size -= size;
1870 #endif
1871 #if ZEND_MM_STAT
1872 	heap->size -= size;
1873 #endif
1874 }
1875 
1876 /******************/
1877 /* Initialization */
1878 /******************/
1879 
1880 static zend_mm_heap *zend_mm_init(void)
1881 {
1882 	zend_mm_chunk *chunk = (zend_mm_chunk*)zend_mm_chunk_alloc_int(ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE);
1883 	zend_mm_heap *heap;
1884 
1885 	if (UNEXPECTED(chunk == NULL)) {
1886 #if ZEND_MM_ERROR
1887 #ifdef _WIN32
1888 		stderr_last_error("Can't initialize heap");
1889 #else
1890 		fprintf(stderr, "\nCan't initialize heap: [%d] %s\n", errno, strerror(errno));
1891 #endif
1892 #endif
1893 		return NULL;
1894 	}
1895 	heap = &chunk->heap_slot;
1896 	chunk->heap = heap;
1897 	chunk->next = chunk;
1898 	chunk->prev = chunk;
1899 	chunk->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE;
1900 	chunk->free_tail = ZEND_MM_FIRST_PAGE;
1901 	chunk->num = 0;
1902 	chunk->free_map[0] = (Z_L(1) << ZEND_MM_FIRST_PAGE) - 1;
1903 	chunk->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE);
1904 	heap->main_chunk = chunk;
1905 	heap->cached_chunks = NULL;
1906 	heap->chunks_count = 1;
1907 	heap->peak_chunks_count = 1;
1908 	heap->cached_chunks_count = 0;
1909 	heap->avg_chunks_count = 1.0;
1910 	heap->last_chunks_delete_boundary = 0;
1911 	heap->last_chunks_delete_count = 0;
1912 #if ZEND_MM_STAT || ZEND_MM_LIMIT
1913 	heap->real_size = ZEND_MM_CHUNK_SIZE;
1914 #endif
1915 #if ZEND_MM_STAT
1916 	heap->real_peak = ZEND_MM_CHUNK_SIZE;
1917 	heap->size = 0;
1918 	heap->peak = 0;
1919 #endif
1920 #if ZEND_MM_LIMIT
1921 	heap->limit = ((size_t)Z_L(-1) >> (size_t)Z_L(1));
1922 	heap->overflow = 0;
1923 #endif
1924 #if ZEND_MM_CUSTOM
1925 	heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_NONE;
1926 #endif
1927 #if ZEND_MM_STORAGE
1928 	heap->storage = NULL;
1929 #endif
1930 	heap->huge_list = NULL;
1931 	return heap;
1932 }
1933 
1934 ZEND_API size_t zend_mm_gc(zend_mm_heap *heap)
1935 {
1936 	zend_mm_free_slot *p, **q;
1937 	zend_mm_chunk *chunk;
1938 	size_t page_offset;
1939 	int page_num;
1940 	zend_mm_page_info info;
1941 	uint32_t i, free_counter;
1942 	int has_free_pages;
1943 	size_t collected = 0;
1944 
1945 #if ZEND_MM_CUSTOM
1946 	if (heap->use_custom_heap) {
1947 		return 0;
1948 	}
1949 #endif
1950 
1951 	for (i = 0; i < ZEND_MM_BINS; i++) {
1952 		has_free_pages = 0;
1953 		p = heap->free_slot[i];
1954 		while (p != NULL) {
1955 			chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(p, ZEND_MM_CHUNK_SIZE);
1956 			ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted");
1957 			page_offset = ZEND_MM_ALIGNED_OFFSET(p, ZEND_MM_CHUNK_SIZE);
1958 			ZEND_ASSERT(page_offset != 0);
1959 			page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE);
1960 			info = chunk->map[page_num];
1961 			ZEND_ASSERT(info & ZEND_MM_IS_SRUN);
1962 			if (info & ZEND_MM_IS_LRUN) {
1963 				page_num -= ZEND_MM_NRUN_OFFSET(info);
1964 				info = chunk->map[page_num];
1965 				ZEND_ASSERT(info & ZEND_MM_IS_SRUN);
1966 				ZEND_ASSERT(!(info & ZEND_MM_IS_LRUN));
1967 			}
1968 			ZEND_ASSERT(ZEND_MM_SRUN_BIN_NUM(info) == i);
1969 			free_counter = ZEND_MM_SRUN_FREE_COUNTER(info) + 1;
1970 			if (free_counter == bin_elements[i]) {
1971 				has_free_pages = 1;
1972 			}
1973 			chunk->map[page_num] = ZEND_MM_SRUN_EX(i, free_counter);
1974 			p = p->next_free_slot;
1975 		}
1976 
1977 		if (!has_free_pages) {
1978 			continue;
1979 		}
1980 
1981 		q = &heap->free_slot[i];
1982 		p = *q;
1983 		while (p != NULL) {
1984 			chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(p, ZEND_MM_CHUNK_SIZE);
1985 			ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted");
1986 			page_offset = ZEND_MM_ALIGNED_OFFSET(p, ZEND_MM_CHUNK_SIZE);
1987 			ZEND_ASSERT(page_offset != 0);
1988 			page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE);
1989 			info = chunk->map[page_num];
1990 			ZEND_ASSERT(info & ZEND_MM_IS_SRUN);
1991 			if (info & ZEND_MM_IS_LRUN) {
1992 				page_num -= ZEND_MM_NRUN_OFFSET(info);
1993 				info = chunk->map[page_num];
1994 				ZEND_ASSERT(info & ZEND_MM_IS_SRUN);
1995 				ZEND_ASSERT(!(info & ZEND_MM_IS_LRUN));
1996 			}
1997 			ZEND_ASSERT(ZEND_MM_SRUN_BIN_NUM(info) == i);
1998 			if (ZEND_MM_SRUN_FREE_COUNTER(info) == bin_elements[i]) {
1999 				/* remove from cache */
2000 				p = p->next_free_slot;
2001 				*q = p;
2002 			} else {
2003 				q = &p->next_free_slot;
2004 				p = *q;
2005 			}
2006 		}
2007 	}
2008 
2009 	chunk = heap->main_chunk;
2010 	do {
2011 		i = ZEND_MM_FIRST_PAGE;
2012 		while (i < chunk->free_tail) {
2013 			if (zend_mm_bitset_is_set(chunk->free_map, i)) {
2014 				info = chunk->map[i];
2015 				if (info & ZEND_MM_IS_SRUN) {
2016 					int bin_num = ZEND_MM_SRUN_BIN_NUM(info);
2017 					int pages_count = bin_pages[bin_num];
2018 
2019 					if (ZEND_MM_SRUN_FREE_COUNTER(info) == bin_elements[bin_num]) {
2020 						/* all elemens are free */
2021 						zend_mm_free_pages_ex(heap, chunk, i, pages_count, 0);
2022 						collected += pages_count;
2023 					} else {
2024 						/* reset counter */
2025 						chunk->map[i] = ZEND_MM_SRUN(bin_num);
2026 					}
2027 					i += bin_pages[bin_num];
2028 				} else /* if (info & ZEND_MM_IS_LRUN) */ {
2029 					i += ZEND_MM_LRUN_PAGES(info);
2030 				}
2031 			} else {
2032 				i++;
2033 			}
2034 		}
2035 		if (chunk->free_pages == ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE) {
2036 			zend_mm_chunk *next_chunk = chunk->next;
2037 
2038 			zend_mm_delete_chunk(heap, chunk);
2039 			chunk = next_chunk;
2040 		} else {
2041 			chunk = chunk->next;
2042 		}
2043 	} while (chunk != heap->main_chunk);
2044 
2045 	return collected * ZEND_MM_PAGE_SIZE;
2046 }
2047 
2048 #if ZEND_DEBUG
2049 /******************/
2050 /* Leak detection */
2051 /******************/
2052 
2053 static zend_long zend_mm_find_leaks_small(zend_mm_chunk *p, uint32_t i, uint32_t j, zend_leak_info *leak)
2054 {
2055     int empty = 1;
2056 	zend_long count = 0;
2057 	int bin_num = ZEND_MM_SRUN_BIN_NUM(p->map[i]);
2058 	zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * i + bin_data_size[bin_num] * (j + 1) - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
2059 
2060 	while (j < bin_elements[bin_num]) {
2061 		if (dbg->size != 0) {
2062 			if (dbg->filename == leak->filename && dbg->lineno == leak->lineno) {
2063 				count++;
2064 				dbg->size = 0;
2065 				dbg->filename = NULL;
2066 				dbg->lineno = 0;
2067 			} else {
2068 				empty = 0;
2069 			}
2070 		}
2071 		j++;
2072 		dbg = (zend_mm_debug_info*)((char*)dbg + bin_data_size[bin_num]);
2073 	}
2074 	if (empty) {
2075 		zend_mm_bitset_reset_range(p->free_map, i, bin_pages[bin_num]);
2076 	}
2077 	return count;
2078 }
2079 
2080 static zend_long zend_mm_find_leaks(zend_mm_heap *heap, zend_mm_chunk *p, uint32_t i, zend_leak_info *leak)
2081 {
2082 	zend_long count = 0;
2083 
2084 	do {
2085 		while (i < p->free_tail) {
2086 			if (zend_mm_bitset_is_set(p->free_map, i)) {
2087 				if (p->map[i] & ZEND_MM_IS_SRUN) {
2088 					int bin_num = ZEND_MM_SRUN_BIN_NUM(p->map[i]);
2089 					count += zend_mm_find_leaks_small(p, i, 0, leak);
2090 					i += bin_pages[bin_num];
2091 				} else /* if (p->map[i] & ZEND_MM_IS_LRUN) */ {
2092 					int pages_count = ZEND_MM_LRUN_PAGES(p->map[i]);
2093 					zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * (i + pages_count) - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
2094 
2095 					if (dbg->filename == leak->filename && dbg->lineno == leak->lineno) {
2096 						count++;
2097 					}
2098 					zend_mm_bitset_reset_range(p->free_map, i, pages_count);
2099 					i += pages_count;
2100 				}
2101 			} else {
2102 				i++;
2103 			}
2104 		}
2105 		p = p->next;
2106 		i = ZEND_MM_FIRST_PAGE;
2107 	} while (p != heap->main_chunk);
2108 	return count;
2109 }
2110 
2111 static zend_long zend_mm_find_leaks_huge(zend_mm_heap *heap, zend_mm_huge_list *list)
2112 {
2113 	zend_long count = 0;
2114 	zend_mm_huge_list *prev = list;
2115 	zend_mm_huge_list *p = list->next;
2116 
2117 	while (p) {
2118 		if (p->dbg.filename == list->dbg.filename && p->dbg.lineno == list->dbg.lineno) {
2119 			prev->next = p->next;
2120 			zend_mm_chunk_free(heap, p->ptr, p->size);
2121 			zend_mm_free_heap(heap, p, NULL, 0, NULL, 0);
2122 			count++;
2123 		} else {
2124 			prev = p;
2125 		}
2126 		p = prev->next;
2127 	}
2128 
2129 	return count;
2130 }
2131 
2132 static void zend_mm_check_leaks(zend_mm_heap *heap)
2133 {
2134 	zend_mm_huge_list *list;
2135 	zend_mm_chunk *p;
2136 	zend_leak_info leak;
2137 	zend_long repeated = 0;
2138 	uint32_t total = 0;
2139 	uint32_t i, j;
2140 
2141 	/* find leaked huge blocks and free them */
2142 	list = heap->huge_list;
2143 	while (list) {
2144 		zend_mm_huge_list *q = list;
2145 
2146 		leak.addr = list->ptr;
2147 		leak.size = list->dbg.size;
2148 		leak.filename = list->dbg.filename;
2149 		leak.orig_filename = list->dbg.orig_filename;
2150 		leak.lineno = list->dbg.lineno;
2151 		leak.orig_lineno = list->dbg.orig_lineno;
2152 
2153 		zend_message_dispatcher(ZMSG_LOG_SCRIPT_NAME, NULL);
2154 		zend_message_dispatcher(ZMSG_MEMORY_LEAK_DETECTED, &leak);
2155 		repeated = zend_mm_find_leaks_huge(heap, list);
2156 		total += 1 + repeated;
2157 		if (repeated) {
2158 			zend_message_dispatcher(ZMSG_MEMORY_LEAK_REPEATED, (void *)(zend_uintptr_t)repeated);
2159 		}
2160 
2161 		heap->huge_list = list = list->next;
2162 		zend_mm_chunk_free(heap, q->ptr, q->size);
2163 		zend_mm_free_heap(heap, q, NULL, 0, NULL, 0);
2164 	}
2165 
2166 	/* for each chunk */
2167 	p = heap->main_chunk;
2168 	do {
2169 		i = ZEND_MM_FIRST_PAGE;
2170 		while (i < p->free_tail) {
2171 			if (zend_mm_bitset_is_set(p->free_map, i)) {
2172 				if (p->map[i] & ZEND_MM_IS_SRUN) {
2173 					int bin_num = ZEND_MM_SRUN_BIN_NUM(p->map[i]);
2174 					zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * i + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
2175 
2176 					j = 0;
2177 					while (j < bin_elements[bin_num]) {
2178 						if (dbg->size != 0) {
2179 							leak.addr = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * i + bin_data_size[bin_num] * j);
2180 							leak.size = dbg->size;
2181 							leak.filename = dbg->filename;
2182 							leak.orig_filename = dbg->orig_filename;
2183 							leak.lineno = dbg->lineno;
2184 							leak.orig_lineno = dbg->orig_lineno;
2185 
2186 							zend_message_dispatcher(ZMSG_LOG_SCRIPT_NAME, NULL);
2187 							zend_message_dispatcher(ZMSG_MEMORY_LEAK_DETECTED, &leak);
2188 
2189 							dbg->size = 0;
2190 							dbg->filename = NULL;
2191 							dbg->lineno = 0;
2192 
2193 							repeated = zend_mm_find_leaks_small(p, i, j + 1, &leak) +
2194 							           zend_mm_find_leaks(heap, p, i + bin_pages[bin_num], &leak);
2195 							total += 1 + repeated;
2196 							if (repeated) {
2197 								zend_message_dispatcher(ZMSG_MEMORY_LEAK_REPEATED, (void *)(zend_uintptr_t)repeated);
2198 							}
2199 						}
2200 						dbg = (zend_mm_debug_info*)((char*)dbg + bin_data_size[bin_num]);
2201 						j++;
2202 					}
2203 					i += bin_pages[bin_num];
2204 				} else /* if (p->map[i] & ZEND_MM_IS_LRUN) */ {
2205 					int pages_count = ZEND_MM_LRUN_PAGES(p->map[i]);
2206 					zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * (i + pages_count) - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)));
2207 
2208 					leak.addr = (void*)((char*)p + ZEND_MM_PAGE_SIZE * i);
2209 					leak.size = dbg->size;
2210 					leak.filename = dbg->filename;
2211 					leak.orig_filename = dbg->orig_filename;
2212 					leak.lineno = dbg->lineno;
2213 					leak.orig_lineno = dbg->orig_lineno;
2214 
2215 					zend_message_dispatcher(ZMSG_LOG_SCRIPT_NAME, NULL);
2216 					zend_message_dispatcher(ZMSG_MEMORY_LEAK_DETECTED, &leak);
2217 
2218 					zend_mm_bitset_reset_range(p->free_map, i, pages_count);
2219 
2220 					repeated = zend_mm_find_leaks(heap, p, i + pages_count, &leak);
2221 					total += 1 + repeated;
2222 					if (repeated) {
2223 						zend_message_dispatcher(ZMSG_MEMORY_LEAK_REPEATED, (void *)(zend_uintptr_t)repeated);
2224 					}
2225 					i += pages_count;
2226 				}
2227 			} else {
2228 				i++;
2229 			}
2230 		}
2231 		p = p->next;
2232 	} while (p != heap->main_chunk);
2233 	if (total) {
2234 		zend_message_dispatcher(ZMSG_MEMORY_LEAKS_GRAND_TOTAL, &total);
2235 	}
2236 }
2237 #endif
2238 
2239 void zend_mm_shutdown(zend_mm_heap *heap, int full, int silent)
2240 {
2241 	zend_mm_chunk *p;
2242 	zend_mm_huge_list *list;
2243 
2244 #if ZEND_MM_CUSTOM
2245 	if (heap->use_custom_heap) {
2246 		if (full) {
2247 			if (ZEND_DEBUG && heap->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) {
2248 				heap->custom_heap.debug._free(heap ZEND_FILE_LINE_CC ZEND_FILE_LINE_EMPTY_CC);
2249 			} else {
2250 				heap->custom_heap.std._free(heap);
2251 			}
2252 		}
2253 		return;
2254 	}
2255 #endif
2256 
2257 #if ZEND_DEBUG
2258 	if (!silent) {
2259 		zend_mm_check_leaks(heap);
2260 	}
2261 #endif
2262 
2263 	/* free huge blocks */
2264 	list = heap->huge_list;
2265 	heap->huge_list = NULL;
2266 	while (list) {
2267 		zend_mm_huge_list *q = list;
2268 		list = list->next;
2269 		zend_mm_chunk_free(heap, q->ptr, q->size);
2270 	}
2271 
2272 	/* move all chunks except of the first one into the cache */
2273 	p = heap->main_chunk->next;
2274 	while (p != heap->main_chunk) {
2275 		zend_mm_chunk *q = p->next;
2276 		p->next = heap->cached_chunks;
2277 		heap->cached_chunks = p;
2278 		p = q;
2279 		heap->chunks_count--;
2280 		heap->cached_chunks_count++;
2281 	}
2282 
2283 	if (full) {
2284 		/* free all cached chunks */
2285 		while (heap->cached_chunks) {
2286 			p = heap->cached_chunks;
2287 			heap->cached_chunks = p->next;
2288 			zend_mm_chunk_free(heap, p, ZEND_MM_CHUNK_SIZE);
2289 		}
2290 		/* free the first chunk */
2291 		zend_mm_chunk_free(heap, heap->main_chunk, ZEND_MM_CHUNK_SIZE);
2292 	} else {
2293 		zend_mm_heap old_heap;
2294 
2295 		/* free some cached chunks to keep average count */
2296 		heap->avg_chunks_count = (heap->avg_chunks_count + (double)heap->peak_chunks_count) / 2.0;
2297 		while ((double)heap->cached_chunks_count + 0.9 > heap->avg_chunks_count &&
2298 		       heap->cached_chunks) {
2299 			p = heap->cached_chunks;
2300 			heap->cached_chunks = p->next;
2301 			zend_mm_chunk_free(heap, p, ZEND_MM_CHUNK_SIZE);
2302 			heap->cached_chunks_count--;
2303 		}
2304 		/* clear cached chunks */
2305 		p = heap->cached_chunks;
2306 		while (p != NULL) {
2307 			zend_mm_chunk *q = p->next;
2308 			memset(p, 0, sizeof(zend_mm_chunk));
2309 			p->next = q;
2310 			p = q;
2311 		}
2312 
2313 		/* reinitialize the first chunk and heap */
2314 		old_heap = *heap;
2315 		p = heap->main_chunk;
2316 		memset(p, 0, ZEND_MM_FIRST_PAGE * ZEND_MM_PAGE_SIZE);
2317 		*heap = old_heap;
2318 		memset(heap->free_slot, 0, sizeof(heap->free_slot));
2319 		heap->main_chunk = p;
2320 		p->heap = &p->heap_slot;
2321 		p->next = p;
2322 		p->prev = p;
2323 		p->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE;
2324 		p->free_tail = ZEND_MM_FIRST_PAGE;
2325 		p->free_map[0] = (1L << ZEND_MM_FIRST_PAGE) - 1;
2326 		p->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE);
2327 		heap->chunks_count = 1;
2328 		heap->peak_chunks_count = 1;
2329 		heap->last_chunks_delete_boundary = 0;
2330 		heap->last_chunks_delete_count = 0;
2331 #if ZEND_MM_STAT || ZEND_MM_LIMIT
2332 		heap->real_size = ZEND_MM_CHUNK_SIZE;
2333 #endif
2334 #if ZEND_MM_STAT
2335 		heap->real_peak = ZEND_MM_CHUNK_SIZE;
2336 		heap->size = heap->peak = 0;
2337 #endif
2338 	}
2339 }
2340 
2341 /**************/
2342 /* PUBLIC API */
2343 /**************/
2344 
2345 ZEND_API void* ZEND_FASTCALL _zend_mm_alloc(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2346 {
2347 	return zend_mm_alloc_heap(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2348 }
2349 
2350 ZEND_API void ZEND_FASTCALL _zend_mm_free(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2351 {
2352 	zend_mm_free_heap(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2353 }
2354 
2355 void* ZEND_FASTCALL _zend_mm_realloc(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2356 {
2357 	return zend_mm_realloc_heap(heap, ptr, size, 0, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2358 }
2359 
2360 void* ZEND_FASTCALL _zend_mm_realloc2(zend_mm_heap *heap, void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2361 {
2362 	return zend_mm_realloc_heap(heap, ptr, size, 1, copy_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2363 }
2364 
2365 ZEND_API size_t ZEND_FASTCALL _zend_mm_block_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2366 {
2367 	return zend_mm_size(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2368 }
2369 
2370 /**********************/
2371 /* Allocation Manager */
2372 /**********************/
2373 
2374 typedef struct _zend_alloc_globals {
2375 	zend_mm_heap *mm_heap;
2376 } zend_alloc_globals;
2377 
2378 #ifdef ZTS
2379 static int alloc_globals_id;
2380 # define AG(v) ZEND_TSRMG(alloc_globals_id, zend_alloc_globals *, v)
2381 #else
2382 # define AG(v) (alloc_globals.v)
2383 static zend_alloc_globals alloc_globals;
2384 #endif
2385 
2386 ZEND_API int is_zend_mm(void)
2387 {
2388 #if ZEND_MM_CUSTOM
2389 	return !AG(mm_heap)->use_custom_heap;
2390 #else
2391 	return 1;
2392 #endif
2393 }
2394 
2395 #if !ZEND_DEBUG && defined(HAVE_BUILTIN_CONSTANT_P)
2396 #undef _emalloc
2397 
2398 #if ZEND_MM_CUSTOM
2399 # define ZEND_MM_CUSTOM_ALLOCATOR(size) do { \
2400 		if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { \
2401 			if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { \
2402 				return AG(mm_heap)->custom_heap.debug._malloc(size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); \
2403 			} else { \
2404 				return AG(mm_heap)->custom_heap.std._malloc(size); \
2405 			} \
2406 		} \
2407 	} while (0)
2408 # define ZEND_MM_CUSTOM_DEALLOCATOR(ptr) do { \
2409 		if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { \
2410 			if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { \
2411 				AG(mm_heap)->custom_heap.debug._free(ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); \
2412 			} else { \
2413 				AG(mm_heap)->custom_heap.std._free(ptr); \
2414 			} \
2415 			return; \
2416 		} \
2417 	} while (0)
2418 #else
2419 # define ZEND_MM_CUSTOM_ALLOCATOR(size)
2420 # define ZEND_MM_CUSTOM_DEALLOCATOR(ptr)
2421 #endif
2422 
2423 # define _ZEND_BIN_ALLOCATOR(_num, _size, _elements, _pages, x, y) \
2424 	ZEND_API void* ZEND_FASTCALL _emalloc_ ## _size(void) { \
2425 		ZEND_MM_CUSTOM_ALLOCATOR(_size); \
2426 		return zend_mm_alloc_small(AG(mm_heap), _size, _num ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); \
2427 	}
2428 
2429 ZEND_MM_BINS_INFO(_ZEND_BIN_ALLOCATOR, x, y)
2430 
2431 ZEND_API void* ZEND_FASTCALL _emalloc_large(size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2432 {
2433 	ZEND_MM_CUSTOM_ALLOCATOR(size);
2434 	return zend_mm_alloc_large_ex(AG(mm_heap), size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2435 }
2436 
2437 ZEND_API void* ZEND_FASTCALL _emalloc_huge(size_t size)
2438 {
2439 	ZEND_MM_CUSTOM_ALLOCATOR(size);
2440 	return zend_mm_alloc_huge(AG(mm_heap), size);
2441 }
2442 
2443 #if ZEND_DEBUG
2444 # define _ZEND_BIN_FREE(_num, _size, _elements, _pages, x, y) \
2445 	ZEND_API void ZEND_FASTCALL _efree_ ## _size(void *ptr) { \
2446 		ZEND_MM_CUSTOM_DEALLOCATOR(ptr); \
2447 		{ \
2448 			size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE); \
2449 			zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); \
2450 			int page_num = page_offset / ZEND_MM_PAGE_SIZE; \
2451 			ZEND_MM_CHECK(chunk->heap == AG(mm_heap), "zend_mm_heap corrupted"); \
2452 			ZEND_ASSERT(chunk->map[page_num] & ZEND_MM_IS_SRUN); \
2453 			ZEND_ASSERT(ZEND_MM_SRUN_BIN_NUM(chunk->map[page_num]) == _num); \
2454 			zend_mm_free_small(AG(mm_heap), ptr, _num); \
2455 		} \
2456 	}
2457 #else
2458 # define _ZEND_BIN_FREE(_num, _size, _elements, _pages, x, y) \
2459 	ZEND_API void ZEND_FASTCALL _efree_ ## _size(void *ptr) { \
2460 		ZEND_MM_CUSTOM_DEALLOCATOR(ptr); \
2461 		{ \
2462 			zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); \
2463 			ZEND_MM_CHECK(chunk->heap == AG(mm_heap), "zend_mm_heap corrupted"); \
2464 			zend_mm_free_small(AG(mm_heap), ptr, _num); \
2465 		} \
2466 	}
2467 #endif
2468 
2469 ZEND_MM_BINS_INFO(_ZEND_BIN_FREE, x, y)
2470 
2471 ZEND_API void ZEND_FASTCALL _efree_large(void *ptr, size_t size)
2472 {
2473 	ZEND_MM_CUSTOM_DEALLOCATOR(ptr);
2474 	{
2475 		size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE);
2476 		zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE);
2477 		int page_num = page_offset / ZEND_MM_PAGE_SIZE;
2478 		uint32_t pages_count = ZEND_MM_ALIGNED_SIZE_EX(size, ZEND_MM_PAGE_SIZE) / ZEND_MM_PAGE_SIZE;
2479 
2480 		ZEND_MM_CHECK(chunk->heap == AG(mm_heap) && ZEND_MM_ALIGNED_OFFSET(page_offset, ZEND_MM_PAGE_SIZE) == 0, "zend_mm_heap corrupted");
2481 		ZEND_ASSERT(chunk->map[page_num] & ZEND_MM_IS_LRUN);
2482 		ZEND_ASSERT(ZEND_MM_LRUN_PAGES(chunk->map[page_num]) == pages_count);
2483 		zend_mm_free_large(AG(mm_heap), chunk, page_num, pages_count);
2484 	}
2485 }
2486 
2487 ZEND_API void ZEND_FASTCALL _efree_huge(void *ptr, size_t size)
2488 {
2489 
2490 	ZEND_MM_CUSTOM_DEALLOCATOR(ptr);
2491 	zend_mm_free_huge(AG(mm_heap), ptr);
2492 }
2493 #endif
2494 
2495 ZEND_API void* ZEND_FASTCALL _emalloc(size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2496 {
2497 #if ZEND_MM_CUSTOM
2498 	if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) {
2499 		if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) {
2500 			return AG(mm_heap)->custom_heap.debug._malloc(size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2501 		} else {
2502 			return AG(mm_heap)->custom_heap.std._malloc(size);
2503 		}
2504 	}
2505 #endif
2506 	return zend_mm_alloc_heap(AG(mm_heap), size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2507 }
2508 
2509 ZEND_API void ZEND_FASTCALL _efree(void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2510 {
2511 #if ZEND_MM_CUSTOM
2512 	if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) {
2513 		if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) {
2514 			AG(mm_heap)->custom_heap.debug._free(ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2515 		} else {
2516 			AG(mm_heap)->custom_heap.std._free(ptr);
2517 	    }
2518 		return;
2519 	}
2520 #endif
2521 	zend_mm_free_heap(AG(mm_heap), ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2522 }
2523 
2524 ZEND_API void* ZEND_FASTCALL _erealloc(void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2525 {
2526 #if ZEND_MM_CUSTOM
2527 	if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) {
2528 		if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) {
2529 			return AG(mm_heap)->custom_heap.debug._realloc(ptr, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2530 		} else {
2531 			return AG(mm_heap)->custom_heap.std._realloc(ptr, size);
2532 		}
2533 	}
2534 #endif
2535 	return zend_mm_realloc_heap(AG(mm_heap), ptr, size, 0, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2536 }
2537 
2538 ZEND_API void* ZEND_FASTCALL _erealloc2(void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2539 {
2540 #if ZEND_MM_CUSTOM
2541 	if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) {
2542 		if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) {
2543 			return AG(mm_heap)->custom_heap.debug._realloc(ptr, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2544 		} else {
2545 			return AG(mm_heap)->custom_heap.std._realloc(ptr, size);
2546 		}
2547 	}
2548 #endif
2549 	return zend_mm_realloc_heap(AG(mm_heap), ptr, size, 1, copy_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2550 }
2551 
2552 ZEND_API size_t ZEND_FASTCALL _zend_mem_block_size(void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2553 {
2554 #if ZEND_MM_CUSTOM
2555 	if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) {
2556 		return 0;
2557 	}
2558 #endif
2559 	return zend_mm_size(AG(mm_heap), ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2560 }
2561 
2562 ZEND_API void* ZEND_FASTCALL _safe_emalloc(size_t nmemb, size_t size, size_t offset ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2563 {
2564 	return emalloc_rel(zend_safe_address_guarded(nmemb, size, offset));
2565 }
2566 
2567 ZEND_API void* ZEND_FASTCALL _safe_malloc(size_t nmemb, size_t size, size_t offset)
2568 {
2569 	return pemalloc(zend_safe_address_guarded(nmemb, size, offset), 1);
2570 }
2571 
2572 ZEND_API void* ZEND_FASTCALL _safe_erealloc(void *ptr, size_t nmemb, size_t size, size_t offset ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2573 {
2574 	return erealloc_rel(ptr, zend_safe_address_guarded(nmemb, size, offset));
2575 }
2576 
2577 ZEND_API void* ZEND_FASTCALL _safe_realloc(void *ptr, size_t nmemb, size_t size, size_t offset)
2578 {
2579 	return perealloc(ptr, zend_safe_address_guarded(nmemb, size, offset), 1);
2580 }
2581 
2582 ZEND_API void* ZEND_FASTCALL _ecalloc(size_t nmemb, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2583 {
2584 	void *p;
2585 
2586 	size = zend_safe_address_guarded(nmemb, size, 0);
2587 	p = emalloc_rel(size);
2588 	memset(p, 0, size);
2589 	return p;
2590 }
2591 
2592 ZEND_API char* ZEND_FASTCALL _estrdup(const char *s ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2593 {
2594 	size_t length;
2595 	char *p;
2596 
2597 	length = strlen(s);
2598 	if (UNEXPECTED(length + 1 == 0)) {
2599 		zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (1 * %zu + 1)", length);
2600 	}
2601 	p = (char *) _emalloc(length + 1 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2602 	memcpy(p, s, length+1);
2603 	return p;
2604 }
2605 
2606 ZEND_API char* ZEND_FASTCALL _estrndup(const char *s, size_t length ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)
2607 {
2608 	char *p;
2609 
2610 	if (UNEXPECTED(length + 1 == 0)) {
2611 		zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (1 * %zu + 1)", length);
2612 	}
2613 	p = (char *) _emalloc(length + 1 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC);
2614 	memcpy(p, s, length);
2615 	p[length] = 0;
2616 	return p;
2617 }
2618 
2619 
2620 ZEND_API char* ZEND_FASTCALL zend_strndup(const char *s, size_t length)
2621 {
2622 	char *p;
2623 
2624 	if (UNEXPECTED(length + 1 == 0)) {
2625 		zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (1 * %zu + 1)", length);
2626 	}
2627 	p = (char *) malloc(length + 1);
2628 	if (UNEXPECTED(p == NULL)) {
2629 		return p;
2630 	}
2631 	if (EXPECTED(length)) {
2632 		memcpy(p, s, length);
2633 	}
2634 	p[length] = 0;
2635 	return p;
2636 }
2637 
2638 
2639 ZEND_API int zend_set_memory_limit(size_t memory_limit)
2640 {
2641 #if ZEND_MM_LIMIT
2642 	AG(mm_heap)->limit = (memory_limit >= ZEND_MM_CHUNK_SIZE) ? memory_limit : ZEND_MM_CHUNK_SIZE;
2643 #endif
2644 	return SUCCESS;
2645 }
2646 
2647 ZEND_API size_t zend_memory_usage(int real_usage)
2648 {
2649 #if ZEND_MM_STAT
2650 	if (real_usage) {
2651 		return AG(mm_heap)->real_size;
2652 	} else {
2653 		size_t usage = AG(mm_heap)->size;
2654 		return usage;
2655 	}
2656 #endif
2657 	return 0;
2658 }
2659 
2660 ZEND_API size_t zend_memory_peak_usage(int real_usage)
2661 {
2662 #if ZEND_MM_STAT
2663 	if (real_usage) {
2664 		return AG(mm_heap)->real_peak;
2665 	} else {
2666 		return AG(mm_heap)->peak;
2667 	}
2668 #endif
2669 	return 0;
2670 }
2671 
2672 ZEND_API void shutdown_memory_manager(int silent, int full_shutdown)
2673 {
2674 	zend_mm_shutdown(AG(mm_heap), full_shutdown, silent);
2675 }
2676 
2677 static void alloc_globals_ctor(zend_alloc_globals *alloc_globals)
2678 {
2679 	char *tmp;
2680 
2681 #if ZEND_MM_CUSTOM
2682 	tmp = getenv("USE_ZEND_ALLOC");
2683 	if (tmp && !zend_atoi(tmp, 0)) {
2684 		alloc_globals->mm_heap = malloc(sizeof(zend_mm_heap));
2685 		memset(alloc_globals->mm_heap, 0, sizeof(zend_mm_heap));
2686 		alloc_globals->mm_heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_STD;
2687 		alloc_globals->mm_heap->custom_heap.std._malloc = __zend_malloc;
2688 		alloc_globals->mm_heap->custom_heap.std._free = free;
2689 		alloc_globals->mm_heap->custom_heap.std._realloc = __zend_realloc;
2690 		return;
2691 	}
2692 #endif
2693 
2694 	tmp = getenv("USE_ZEND_ALLOC_HUGE_PAGES");
2695 	if (tmp && zend_atoi(tmp, 0)) {
2696 		zend_mm_use_huge_pages = 1;
2697 	}
2698 	ZEND_TSRMLS_CACHE_UPDATE();
2699 	alloc_globals->mm_heap = zend_mm_init();
2700 }
2701 
2702 #ifdef ZTS
2703 static void alloc_globals_dtor(zend_alloc_globals *alloc_globals)
2704 {
2705 	zend_mm_shutdown(alloc_globals->mm_heap, 1, 1);
2706 }
2707 #endif
2708 
2709 ZEND_API void start_memory_manager(void)
2710 {
2711 #ifdef ZTS
2712 	ts_allocate_id(&alloc_globals_id, sizeof(zend_alloc_globals), (ts_allocate_ctor) alloc_globals_ctor, (ts_allocate_dtor) alloc_globals_dtor);
2713 #else
2714 	alloc_globals_ctor(&alloc_globals);
2715 #endif
2716 #ifndef _WIN32
2717 #  if defined(_SC_PAGESIZE)
2718 	REAL_PAGE_SIZE = sysconf(_SC_PAGESIZE);
2719 #  elif defined(_SC_PAGE_SIZE)
2720 	REAL_PAGE_SIZE = sysconf(_SC_PAGE_SIZE);
2721 #  endif
2722 #endif
2723 }
2724 
2725 ZEND_API zend_mm_heap *zend_mm_set_heap(zend_mm_heap *new_heap)
2726 {
2727 	zend_mm_heap *old_heap;
2728 
2729 	old_heap = AG(mm_heap);
2730 	AG(mm_heap) = (zend_mm_heap*)new_heap;
2731 	return (zend_mm_heap*)old_heap;
2732 }
2733 
2734 ZEND_API zend_mm_heap *zend_mm_get_heap(void)
2735 {
2736 	return AG(mm_heap);
2737 }
2738 
2739 ZEND_API int zend_mm_is_custom_heap(zend_mm_heap *new_heap)
2740 {
2741 #if ZEND_MM_CUSTOM
2742 	return AG(mm_heap)->use_custom_heap;
2743 #else
2744 	return 0;
2745 #endif
2746 }
2747 
2748 ZEND_API void zend_mm_set_custom_handlers(zend_mm_heap *heap,
2749                                           void* (*_malloc)(size_t),
2750                                           void  (*_free)(void*),
2751                                           void* (*_realloc)(void*, size_t))
2752 {
2753 #if ZEND_MM_CUSTOM
2754 	zend_mm_heap *_heap = (zend_mm_heap*)heap;
2755 
2756 	if (!_malloc && !_free && !_realloc) {
2757 		_heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_NONE;
2758 	} else {
2759 		_heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_STD;
2760 		_heap->custom_heap.std._malloc = _malloc;
2761 		_heap->custom_heap.std._free = _free;
2762 		_heap->custom_heap.std._realloc = _realloc;
2763 	}
2764 #endif
2765 }
2766 
2767 ZEND_API void zend_mm_get_custom_handlers(zend_mm_heap *heap,
2768                                           void* (**_malloc)(size_t),
2769                                           void  (**_free)(void*),
2770                                           void* (**_realloc)(void*, size_t))
2771 {
2772 #if ZEND_MM_CUSTOM
2773 	zend_mm_heap *_heap = (zend_mm_heap*)heap;
2774 
2775 	if (heap->use_custom_heap) {
2776 		*_malloc = _heap->custom_heap.std._malloc;
2777 		*_free = _heap->custom_heap.std._free;
2778 		*_realloc = _heap->custom_heap.std._realloc;
2779 	} else {
2780 		*_malloc = NULL;
2781 		*_free = NULL;
2782 		*_realloc = NULL;
2783 	}
2784 #else
2785 	*_malloc = NULL;
2786 	*_free = NULL;
2787 	*_realloc = NULL;
2788 #endif
2789 }
2790 
2791 #if ZEND_DEBUG
2792 ZEND_API void zend_mm_set_custom_debug_handlers(zend_mm_heap *heap,
2793                                           void* (*_malloc)(size_t ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC),
2794                                           void  (*_free)(void* ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC),
2795                                           void* (*_realloc)(void*, size_t ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC))
2796 {
2797 #if ZEND_MM_CUSTOM
2798 	zend_mm_heap *_heap = (zend_mm_heap*)heap;
2799 
2800 	_heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_DEBUG;
2801 	_heap->custom_heap.debug._malloc = _malloc;
2802 	_heap->custom_heap.debug._free = _free;
2803 	_heap->custom_heap.debug._realloc = _realloc;
2804 #endif
2805 }
2806 #endif
2807 
2808 ZEND_API zend_mm_storage *zend_mm_get_storage(zend_mm_heap *heap)
2809 {
2810 #if ZEND_MM_STORAGE
2811 	return heap->storage;
2812 #else
2813 	return NULL
2814 #endif
2815 }
2816 
2817 ZEND_API zend_mm_heap *zend_mm_startup(void)
2818 {
2819 	return zend_mm_init();
2820 }
2821 
2822 ZEND_API zend_mm_heap *zend_mm_startup_ex(const zend_mm_handlers *handlers, void *data, size_t data_size)
2823 {
2824 #if ZEND_MM_STORAGE
2825 	zend_mm_storage tmp_storage, *storage;
2826 	zend_mm_chunk *chunk;
2827 	zend_mm_heap *heap;
2828 
2829 	memcpy((zend_mm_handlers*)&tmp_storage.handlers, handlers, sizeof(zend_mm_handlers));
2830 	tmp_storage.data = data;
2831 	chunk = (zend_mm_chunk*)handlers->chunk_alloc(&tmp_storage, ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE);
2832 	if (UNEXPECTED(chunk == NULL)) {
2833 #if ZEND_MM_ERROR
2834 #ifdef _WIN32
2835 		stderr_last_error("Can't initialize heap");
2836 #else
2837 		fprintf(stderr, "\nCan't initialize heap: [%d] %s\n", errno, strerror(errno));
2838 #endif
2839 #endif
2840 		return NULL;
2841 	}
2842 	heap = &chunk->heap_slot;
2843 	chunk->heap = heap;
2844 	chunk->next = chunk;
2845 	chunk->prev = chunk;
2846 	chunk->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE;
2847 	chunk->free_tail = ZEND_MM_FIRST_PAGE;
2848 	chunk->num = 0;
2849 	chunk->free_map[0] = (Z_L(1) << ZEND_MM_FIRST_PAGE) - 1;
2850 	chunk->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE);
2851 	heap->main_chunk = chunk;
2852 	heap->cached_chunks = NULL;
2853 	heap->chunks_count = 1;
2854 	heap->peak_chunks_count = 1;
2855 	heap->cached_chunks_count = 0;
2856 	heap->avg_chunks_count = 1.0;
2857 	heap->last_chunks_delete_boundary = 0;
2858 	heap->last_chunks_delete_count = 0;
2859 #if ZEND_MM_STAT || ZEND_MM_LIMIT
2860 	heap->real_size = ZEND_MM_CHUNK_SIZE;
2861 #endif
2862 #if ZEND_MM_STAT
2863 	heap->real_peak = ZEND_MM_CHUNK_SIZE;
2864 	heap->size = 0;
2865 	heap->peak = 0;
2866 #endif
2867 #if ZEND_MM_LIMIT
2868 	heap->limit = (Z_L(-1) >> Z_L(1));
2869 	heap->overflow = 0;
2870 #endif
2871 #if ZEND_MM_CUSTOM
2872 	heap->use_custom_heap = 0;
2873 #endif
2874 	heap->storage = &tmp_storage;
2875 	heap->huge_list = NULL;
2876 	memset(heap->free_slot, 0, sizeof(heap->free_slot));
2877 	storage = _zend_mm_alloc(heap, sizeof(zend_mm_storage) + data_size ZEND_FILE_LINE_CC ZEND_FILE_LINE_CC);
2878 	if (!storage) {
2879 		handlers->chunk_free(&tmp_storage, chunk, ZEND_MM_CHUNK_SIZE);
2880 #if ZEND_MM_ERROR
2881 #ifdef _WIN32
2882 		stderr_last_error("Can't initialize heap");
2883 #else
2884 		fprintf(stderr, "\nCan't initialize heap: [%d] %s\n", errno, strerror(errno));
2885 #endif
2886 #endif
2887 		return NULL;
2888 	}
2889 	memcpy(storage, &tmp_storage, sizeof(zend_mm_storage));
2890 	if (data) {
2891 		storage->data = (void*)(((char*)storage + sizeof(zend_mm_storage)));
2892 		memcpy(storage->data, data, data_size);
2893 	}
2894 	heap->storage = storage;
2895 	return heap;
2896 #else
2897 	return NULL;
2898 #endif
2899 }
2900 
2901 static ZEND_COLD ZEND_NORETURN void zend_out_of_memory(void)
2902 {
2903 	fprintf(stderr, "Out of memory\n");
2904 	exit(1);
2905 }
2906 
2907 ZEND_API void * __zend_malloc(size_t len)
2908 {
2909 	void *tmp = malloc(len);
2910 	if (EXPECTED(tmp || !len)) {
2911 		return tmp;
2912 	}
2913 	zend_out_of_memory();
2914 }
2915 
2916 ZEND_API void * __zend_calloc(size_t nmemb, size_t len)
2917 {
2918 	void *tmp;
2919 
2920 	len = zend_safe_address_guarded(nmemb, len, 0);
2921 	tmp = __zend_malloc(len);
2922 	memset(tmp, 0, len);
2923 	return tmp;
2924 }
2925 
2926 ZEND_API void * __zend_realloc(void *p, size_t len)
2927 {
2928 	p = realloc(p, len);
2929 	if (EXPECTED(p || !len)) {
2930 		return p;
2931 	}
2932 	zend_out_of_memory();
2933 }
2934 
2935 /*
2936  * Local variables:
2937  * tab-width: 4
2938  * c-basic-offset: 4
2939  * indent-tabs-mode: t
2940  * End:
2941  * vim600: sw=4 ts=4 fdm=marker
2942  * vim<600: sw=4 ts=4
2943  */
2944