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