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