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