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