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