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