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