Coverage Report

Created: 2026-09-14 06:25

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