Coverage Report

Created: 2026-10-28 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/php-src/Zend/zend_gc.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: David Wang <planetbeing@gmail.com>                          |
15
   |          Dmitry Stogov <dmitry@php.net>                              |
16
   +----------------------------------------------------------------------+
17
*/
18
19
/**
20
 * zend_gc_collect_cycles
21
 * ======================
22
 *
23
 * Colors and its meaning
24
 * ----------------------
25
 *
26
 * BLACK  (GC_BLACK)   - In use or free.
27
 * GREY   (GC_GREY)    - Possible member of cycle.
28
 * WHITE  (GC_WHITE)   - Member of garbage cycle.
29
 * PURPLE (GC_PURPLE)  - Possible root of cycle.
30
 *
31
 * Colors described in the paper but not used
32
 * ------------------------------------------
33
 *
34
 * GREEN - Acyclic
35
 * RED   - Candidate cycle undergoing
36
 * ORANGE - Candidate cycle awaiting epoch boundary.
37
 *
38
 *
39
 * Flow
40
 * =====
41
 *
42
 * The garbage collect cycle starts from 'gc_mark_roots', which traverses the
43
 * possible roots, and calls mark_grey for roots are marked purple with
44
 * depth-first traverse.
45
 *
46
 * After all possible roots are traversed and marked,
47
 * gc_scan_roots will be called, and each root will be called with
48
 * gc_scan(root->ref)
49
 *
50
 * gc_scan checks the colors of possible members.
51
 *
52
 * If the node is marked as grey and the refcount > 0
53
 *    gc_scan_black will be called on that node to scan it's subgraph.
54
 * otherwise (refcount == 0), it marks the node white.
55
 *
56
 * A node MAY be added to possible roots when ZEND_UNSET_VAR happens or
57
 * zend_assign_to_variable is called only when possible garbage node is
58
 * produced.
59
 * gc_possible_root() will be called to add the nodes to possible roots.
60
 *
61
 *
62
 * For objects, we call their get_gc handler (by default 'zend_std_get_gc') to
63
 * get the object properties to scan.
64
 *
65
 *
66
 * @see http://researcher.watson.ibm.com/researcher/files/us-bacon/Bacon01Concurrent.pdf
67
 */
68
#include "zend.h"
69
#include "zend_API.h"
70
#include "zend_compile.h"
71
#include "zend_errors.h"
72
#include "zend_fibers.h"
73
#include "zend_hrtime.h"
74
#include "zend_portability.h"
75
#include "zend_types.h"
76
#include "zend_weakrefs.h"
77
#include "zend_string.h"
78
#include "zend_exceptions.h"
79
80
#ifndef GC_BENCH
81
# define GC_BENCH 0
82
#endif
83
84
#ifndef ZEND_GC_DEBUG
85
# define ZEND_GC_DEBUG 0
86
#endif
87
88
/* GC_INFO layout */
89
3.14M
#define GC_ADDRESS  0x0fffffu
90
15.7M
#define GC_COLOR    0x300000u
91
92
#define GC_BLACK    0x000000u /* must be zero */
93
#define GC_WHITE    0x100000u
94
#define GC_GREY     0x200000u
95
#define GC_PURPLE   0x300000u
96
97
/* Debug tracing */
98
#if ZEND_GC_DEBUG > 1
99
# define GC_TRACE(format, ...) fprintf(stderr, format "\n", ##__VA_ARGS__);
100
# define GC_TRACE_REF(ref, format, ...) \
101
  do { \
102
    gc_trace_ref((zend_refcounted *) ref); \
103
    fprintf(stderr, format "\n", ##__VA_ARGS__); \
104
  } while (0)
105
# define GC_TRACE_SET_COLOR(ref, color) \
106
  GC_TRACE_REF(ref, "->%s", gc_color_name(color))
107
#else
108
# define GC_TRACE_REF(ref, format, ...)
109
# define GC_TRACE_SET_COLOR(ref, new_color)
110
# define GC_TRACE(str)
111
#endif
112
113
/* GC_INFO access */
114
#define GC_REF_ADDRESS(ref) \
115
3.14M
  (((GC_TYPE_INFO(ref)) & (GC_ADDRESS << GC_INFO_SHIFT)) >> GC_INFO_SHIFT)
116
117
#define GC_REF_COLOR(ref) \
118
  (((GC_TYPE_INFO(ref)) & (GC_COLOR << GC_INFO_SHIFT)) >> GC_INFO_SHIFT)
119
120
#define GC_REF_CHECK_COLOR(ref, color) \
121
11.7M
  ((GC_TYPE_INFO(ref) & (GC_COLOR << GC_INFO_SHIFT)) == ((color) << GC_INFO_SHIFT))
122
123
6.42M
#define GC_REF_SET_INFO(ref, info) do { \
124
6.42M
    GC_TYPE_INFO(ref) = \
125
6.42M
      (GC_TYPE_INFO(ref) & (GC_TYPE_MASK | GC_FLAGS_MASK)) | \
126
6.42M
      ((info) << GC_INFO_SHIFT); \
127
6.42M
  } while (0)
128
129
2.65M
#define GC_REF_SET_COLOR(ref, c) do { \
130
2.65M
    GC_TRACE_SET_COLOR(ref, c); \
131
2.65M
    GC_TYPE_INFO(ref) = \
132
2.65M
      (GC_TYPE_INFO(ref) & ~(GC_COLOR << GC_INFO_SHIFT)) | \
133
2.65M
      ((c) << GC_INFO_SHIFT); \
134
2.65M
  } while (0)
135
136
1.32M
#define GC_REF_SET_BLACK(ref) do { \
137
1.32M
    GC_TRACE_SET_COLOR(ref, GC_BLACK); \
138
1.32M
    GC_TYPE_INFO(ref) &= ~(GC_COLOR << GC_INFO_SHIFT); \
139
1.32M
  } while (0)
140
141
#define GC_REF_SET_PURPLE(ref) do { \
142
    GC_TRACE_SET_COLOR(ref, GC_PURPLE); \
143
    GC_TYPE_INFO(ref) |= (GC_COLOR << GC_INFO_SHIFT); \
144
  } while (0)
145
146
/* bit stealing tags for gc_root_buffer.ref */
147
4.21M
#define GC_BITS    0x3
148
149
1.09M
#define GC_ROOT    0x0 /* possible root of circular garbage     */
150
3.57M
#define GC_UNUSED  0x1 /* part of linked list of unused buffers */
151
4.00M
#define GC_GARBAGE 0x2 /* garbage to delete                     */
152
5
#define GC_DTOR_GARBAGE 0x3 /* garbage on which only the dtor should be invoked */
153
154
#define GC_GET_PTR(ptr) \
155
210k
  ((void*)(((uintptr_t)(ptr)) & ~GC_BITS))
156
157
#define GC_IS_ROOT(ptr) \
158
1.09M
  ((((uintptr_t)(ptr)) & GC_BITS) == GC_ROOT)
159
#define GC_IS_UNUSED(ptr) \
160
313k
  ((((uintptr_t)(ptr)) & GC_BITS) == GC_UNUSED)
161
#define GC_IS_GARBAGE(ptr) \
162
2.60M
  ((((uintptr_t)(ptr)) & GC_BITS) == GC_GARBAGE)
163
#define GC_IS_DTOR_GARBAGE(ptr) \
164
4
  ((((uintptr_t)(ptr)) & GC_BITS) == GC_DTOR_GARBAGE)
165
166
#define GC_MAKE_GARBAGE(ptr) \
167
1.40M
  ((void*)(((uintptr_t)(ptr)) | GC_GARBAGE))
168
#define GC_MAKE_DTOR_GARBAGE(ptr) \
169
1
  ((void*)(((uintptr_t)(ptr)) | GC_DTOR_GARBAGE))
170
171
/* GC address conversion */
172
8.83M
#define GC_IDX2PTR(idx)      (GC_G(buf) + (idx))
173
3.26M
#define GC_PTR2IDX(ptr)      ((ptr) - GC_G(buf))
174
175
/* Get the value to be placed in an unused buffer entry with the specified next unused list index */
176
3.26M
#define GC_IDX2LIST(idx)     ((void*)(uintptr_t)(((idx) * sizeof(void*)) | GC_UNUSED))
177
/* Get the index of the next item in the unused list from the given root buffer entry. */
178
383k
#define GC_LIST2IDX(list)    (((uint32_t)(uintptr_t)(list)) / sizeof(void*))
179
180
/* GC buffers */
181
1.69M
#define GC_INVALID           0
182
1.95M
#define GC_FIRST_ROOT        1
183
184
16
#define GC_DEFAULT_BUF_SIZE  (16 * 1024)
185
2
#define GC_BUF_GROW_STEP     (128 * 1024)
186
187
0
#define GC_MAX_UNCOMPRESSED  (512 * 1024)
188
4
#define GC_MAX_BUF_SIZE      0x40000000
189
190
16
#define GC_THRESHOLD_DEFAULT (10000 + GC_FIRST_ROOT)
191
0
#define GC_THRESHOLD_STEP    10000
192
0
#define GC_THRESHOLD_MAX     1000000000
193
0
#define GC_THRESHOLD_TRIGGER 100
194
195
/* GC flags */
196
2.67k
#define GC_HAS_DESTRUCTORS  (1<<0)
197
198
/* Weak maps */
199
26
#define Z_FROM_WEAKMAP_KEY    (1<<0)
200
27
#define Z_FROM_WEAKMAP      (1<<1)
201
202
/* The WeakMap entry zv is reachable from roots by following the virtual
203
 * reference from the a WeakMap key to the entry */
204
#define GC_FROM_WEAKMAP_KEY(zv) \
205
12
  (Z_TYPE_INFO_P((zv)) & (Z_FROM_WEAKMAP_KEY << Z_TYPE_INFO_EXTRA_SHIFT))
206
207
7
#define GC_SET_FROM_WEAKMAP_KEY(zv) do {                    \
208
7
  zval *_z = (zv);                               \
209
7
  Z_TYPE_INFO_P(_z) = Z_TYPE_INFO_P(_z) | (Z_FROM_WEAKMAP_KEY << Z_TYPE_INFO_EXTRA_SHIFT); \
210
7
} while (0)
211
212
7
#define GC_UNSET_FROM_WEAKMAP_KEY(zv) do {                    \
213
7
  zval *_z = (zv);                               \
214
7
  Z_TYPE_INFO_P(_z) = Z_TYPE_INFO_P(_z) & ~(Z_FROM_WEAKMAP_KEY << Z_TYPE_INFO_EXTRA_SHIFT); \
215
7
} while (0)
216
217
/* The WeakMap entry zv is reachable from roots by following the reference from
218
 * the WeakMap */
219
#define GC_FROM_WEAKMAP(zv) \
220
12
  (Z_TYPE_INFO_P((zv)) & (Z_FROM_WEAKMAP << Z_TYPE_INFO_EXTRA_SHIFT))
221
222
7
#define GC_SET_FROM_WEAKMAP(zv) do {                        \
223
7
  zval *_z = (zv);                               \
224
7
  Z_TYPE_INFO_P(_z) = Z_TYPE_INFO_P(_z) | (Z_FROM_WEAKMAP << Z_TYPE_INFO_EXTRA_SHIFT); \
225
7
} while (0)
226
227
8
#define GC_UNSET_FROM_WEAKMAP(zv) do {                      \
228
8
  zval *_z = (zv);                               \
229
8
  Z_TYPE_INFO_P(_z) = Z_TYPE_INFO_P(_z) & ~(Z_FROM_WEAKMAP << Z_TYPE_INFO_EXTRA_SHIFT); \
230
8
} while (0)
231
232
/* unused buffers */
233
234
/* Are there any unused root buffer entries? */
235
#define GC_HAS_UNUSED() \
236
946k
  (GC_G(unused) != GC_INVALID)
237
238
/* Get the next unused entry and remove it from the list */
239
#define GC_FETCH_UNUSED() \
240
383k
  gc_fetch_unused()
241
242
/* Add a root buffer entry to the unused list */
243
#define GC_LINK_UNUSED(root) \
244
3.26M
  gc_link_unused(root)
245
246
#define GC_HAS_NEXT_UNUSED_UNDER_THRESHOLD() \
247
  (GC_G(first_unused) < GC_G(gc_threshold))
248
#define GC_HAS_NEXT_UNUSED() \
249
946k
  (GC_G(first_unused) != GC_G(buf_size))
250
#define GC_FETCH_NEXT_UNUSED() \
251
2.87M
  gc_fetch_next_unused()
252
253
ZEND_API int (*gc_collect_cycles)(void);
254
255
/* The type of a root buffer entry.
256
 *
257
 * The lower two bits are used for flags and need to be masked out to
258
 * reconstruct a pointer.
259
 *
260
 * When a node in the root buffer is removed, the non-flag bits of the
261
 * unused entry are used to store the index of the next entry in the unused
262
 * list. */
263
typedef struct _gc_root_buffer {
264
  zend_refcounted  *ref;
265
} gc_root_buffer;
266
267
typedef struct _zend_gc_globals {
268
  /* The root buffer, which stores possible roots of reference cycles. It is
269
   * also used to store garbage to be collected at the end of a run.
270
   * A single array which is reallocated as necessary. */
271
  gc_root_buffer   *buf;
272
273
  bool         gc_enabled;
274
  bool         gc_active;        /* GC currently running, forbid nested GC */
275
  bool         gc_protected;     /* GC protected, forbid root additions */
276
  bool         gc_full;
277
278
  uint32_t          unused;     /* linked list of unused buffers    */
279
  uint32_t          first_unused;   /* first unused buffer              */
280
  uint32_t          gc_threshold;     /* GC collection threshold          */
281
  uint32_t          buf_size;     /* size of the GC buffer            */
282
  uint32_t          num_roots;    /* number of roots in GC buffer     */
283
284
  uint32_t gc_runs;         /* number of GC runs since reset */
285
  uint32_t collected;         /* number of collected nodes since reset */
286
287
  zend_hrtime_t activated_at;     /* the timestamp of the last reset */
288
  zend_hrtime_t collector_time;   /* time spent running GC (ns) */
289
  zend_hrtime_t dtor_time;      /* time spent calling destructors (ns) */
290
  zend_hrtime_t free_time;      /* time spent destroying nodes and freeing memory (ns) */
291
292
  uint32_t dtor_idx;      /* root buffer index */
293
  uint32_t dtor_end;
294
  zend_fiber *dtor_fiber;
295
  bool dtor_fiber_running;
296
297
#if GC_BENCH
298
  uint32_t root_buf_length;
299
  uint32_t root_buf_peak;
300
  uint32_t zval_possible_root;
301
  uint32_t zval_buffered;
302
  uint32_t zval_remove_from_buffer;
303
  uint32_t zval_marked_grey;
304
#endif
305
} zend_gc_globals;
306
307
#ifdef ZTS
308
static int gc_globals_id;
309
static size_t gc_globals_offset;
310
#define GC_G(v) ZEND_TSRMG_FAST(gc_globals_offset, zend_gc_globals *, v)
311
#else
312
48.3M
#define GC_G(v) (gc_globals.v)
313
static zend_gc_globals gc_globals;
314
#endif
315
316
#if GC_BENCH
317
# define GC_BENCH_INC(counter) GC_G(counter)++
318
# define GC_BENCH_DEC(counter) GC_G(counter)--
319
# define GC_BENCH_PEAK(peak, counter) do {    \
320
    if (GC_G(counter) > GC_G(peak)) {   \
321
      GC_G(peak) = GC_G(counter);     \
322
    }                   \
323
  } while (0)
324
#else
325
# define GC_BENCH_INC(counter)
326
# define GC_BENCH_DEC(counter)
327
# define GC_BENCH_PEAK(peak, counter)
328
#endif
329
330
331
3.01k
#define GC_STACK_SEGMENT_SIZE (((4096 - ZEND_MM_OVERHEAD) / sizeof(void*)) - 2)
332
333
typedef struct _gc_stack gc_stack;
334
335
/* The stack used for graph traversal is stored as a linked list of segments */
336
struct _gc_stack {
337
  gc_stack        *prev;
338
  gc_stack        *next;
339
  zend_refcounted *data[GC_STACK_SEGMENT_SIZE];
340
};
341
342
#define GC_STACK_DCL(init) \
343
314k
  gc_stack *_stack = init; \
344
314k
  size_t    _top = 0;
345
346
#define GC_STACK_PUSH(ref) \
347
1.93M
  gc_stack_push(&_stack, &_top, ref);
348
349
#define GC_STACK_POP() \
350
2.24M
  gc_stack_pop(&_stack, &_top)
351
352
static zend_never_inline gc_stack* gc_stack_next(gc_stack *stack)
353
2.13k
{
354
2.13k
  if (UNEXPECTED(!stack->next)) {
355
1.08k
    gc_stack *segment = emalloc(sizeof(gc_stack));
356
1.08k
    segment->prev = stack;
357
1.08k
    segment->next = NULL;
358
1.08k
    stack->next = segment;
359
1.08k
  }
360
2.13k
  return stack->next;
361
2.13k
}
362
363
static zend_always_inline void gc_stack_push(gc_stack **stack, size_t *top, zend_refcounted *ref)
364
1.93M
{
365
1.93M
  if (UNEXPECTED(*top == GC_STACK_SEGMENT_SIZE)) {
366
1.50k
    (*stack) = gc_stack_next(*stack);
367
1.50k
    (*top) = 0;
368
1.50k
  }
369
1.93M
  (*stack)->data[(*top)++] = ref;
370
1.93M
}
371
372
static zend_always_inline zend_refcounted* gc_stack_pop(gc_stack **stack, size_t *top)
373
2.24M
{
374
2.24M
  if (UNEXPECTED((*top) == 0)) {
375
316k
    if (!(*stack)->prev) {
376
314k
      return NULL;
377
314k
    } else {
378
1.50k
      (*stack) = (*stack)->prev;
379
1.50k
      (*top) = GC_STACK_SEGMENT_SIZE - 1;
380
1.50k
      return (*stack)->data[GC_STACK_SEGMENT_SIZE - 1];
381
1.50k
    }
382
1.92M
  } else {
383
1.92M
    return (*stack)->data[--(*top)];
384
1.92M
  }
385
2.24M
}
386
387
static void gc_stack_free(gc_stack *stack)
388
3.29k
{
389
3.29k
  gc_stack *p = stack->next;
390
391
4.38k
  while (p) {
392
1.08k
    stack = p->next;
393
1.08k
    efree(p);
394
1.08k
    p = stack;
395
1.08k
  }
396
3.29k
}
397
398
/* Map a full index to a compressed index.
399
 *
400
 * The root buffer can have up to 2^30 entries, but we only have 20 bits to
401
 * store the index. So we use the 1<<19 bit as a compression flag and use the
402
 * other 19 bits to store the index modulo 2^19. */
403
static zend_always_inline uint32_t gc_compress(uint32_t idx)
404
3.26M
{
405
3.26M
  if (EXPECTED(idx < GC_MAX_UNCOMPRESSED)) {
406
3.26M
    return idx;
407
3.26M
  }
408
0
  return (idx % GC_MAX_UNCOMPRESSED) | GC_MAX_UNCOMPRESSED;
409
3.26M
}
410
411
/* Find the root buffer entry given a pointer and a compressed index.
412
 * Iterate through the root buffer in steps of 2^19 until the pointer
413
 * matches. */
414
static zend_always_inline gc_root_buffer* gc_decompress(zend_refcounted *ref, uint32_t idx)
415
0
{
416
0
  gc_root_buffer *root = GC_IDX2PTR(idx);
417
418
0
  if (EXPECTED(GC_GET_PTR(root->ref) == ref)) {
419
0
    return root;
420
0
  }
421
422
0
  while (1) {
423
0
    idx += GC_MAX_UNCOMPRESSED;
424
0
    ZEND_ASSERT(idx < GC_G(first_unused));
425
0
    root = GC_IDX2PTR(idx);
426
0
    if (GC_GET_PTR(root->ref) == ref) {
427
0
      return root;
428
0
    }
429
0
  }
430
0
}
431
432
/* Get the index of the next unused root buffer entry, and remove it from the
433
 * unused list. GC_HAS_UNUSED() must be true before calling this. */
434
static zend_always_inline uint32_t gc_fetch_unused(void)
435
383k
{
436
383k
  uint32_t idx;
437
383k
  gc_root_buffer *root;
438
439
383k
  ZEND_ASSERT(GC_HAS_UNUSED());
440
383k
  idx = GC_G(unused);
441
383k
  root = GC_IDX2PTR(idx);
442
383k
  ZEND_ASSERT(GC_IS_UNUSED(root->ref));
443
383k
  GC_G(unused) = GC_LIST2IDX(root->ref);
444
383k
  return idx;
445
383k
}
446
447
/* Add a root buffer entry to the unused list */
448
static zend_always_inline void gc_link_unused(gc_root_buffer *root)
449
3.26M
{
450
3.26M
  root->ref = GC_IDX2LIST(GC_G(unused));
451
3.26M
  GC_G(unused) = GC_PTR2IDX(root);
452
3.26M
}
453
454
static zend_always_inline uint32_t gc_fetch_next_unused(void)
455
2.87M
{
456
2.87M
  uint32_t idx;
457
458
2.87M
  ZEND_ASSERT(GC_HAS_NEXT_UNUSED());
459
2.87M
  idx = GC_G(first_unused);
460
2.87M
  GC_G(first_unused) = GC_G(first_unused) + 1;
461
2.87M
  return idx;
462
2.87M
}
463
464
#if ZEND_GC_DEBUG > 1
465
static const char *gc_color_name(uint32_t color) {
466
  switch (color) {
467
    case GC_BLACK: return "black";
468
    case GC_WHITE: return "white";
469
    case GC_GREY: return "grey";
470
    case GC_PURPLE: return "purple";
471
    default: return "unknown";
472
  }
473
}
474
static void gc_trace_ref(zend_refcounted *ref) {
475
  if (GC_TYPE(ref) == IS_OBJECT) {
476
    zend_object *obj = (zend_object *) ref;
477
    fprintf(stderr, "[%p] rc=%d addr=%d %s object(%s)#%d ",
478
      ref, GC_REFCOUNT(ref), GC_REF_ADDRESS(ref),
479
      gc_color_name(GC_REF_COLOR(ref)),
480
      obj->ce->name->val, obj->handle);
481
  } else if (GC_TYPE(ref) == IS_ARRAY) {
482
    zend_array *arr = (zend_array *) ref;
483
    fprintf(stderr, "[%p] rc=%d addr=%d %s array(%d) ",
484
      ref, GC_REFCOUNT(ref), GC_REF_ADDRESS(ref),
485
      gc_color_name(GC_REF_COLOR(ref)),
486
      zend_hash_num_elements(arr));
487
  } else {
488
    fprintf(stderr, "[%p] rc=%d addr=%d %s %s ",
489
      ref, GC_REFCOUNT(ref), GC_REF_ADDRESS(ref),
490
      gc_color_name(GC_REF_COLOR(ref)),
491
      GC_TYPE(ref) == IS_REFERENCE
492
        ? "reference" : zend_get_type_by_const(GC_TYPE(ref)));
493
  }
494
}
495
#endif
496
497
/* Mark a root buffer entry unused */
498
static zend_always_inline void gc_remove_from_roots(gc_root_buffer *root)
499
3.15M
{
500
3.15M
  GC_LINK_UNUSED(root);
501
3.15M
  GC_G(num_roots)--;
502
3.15M
  GC_BENCH_DEC(root_buf_length);
503
3.15M
}
504
505
static void root_buffer_dtor(zend_gc_globals *gc_globals)
506
0
{
507
0
  if (gc_globals->buf) {
508
0
    free(gc_globals->buf);
509
0
    gc_globals->buf = NULL;
510
0
  }
511
0
}
512
513
static void gc_globals_ctor_ex(zend_gc_globals *gc_globals)
514
16
{
515
16
  gc_globals->gc_enabled = false;
516
16
  gc_globals->gc_active = false;
517
16
  gc_globals->gc_protected = true;
518
16
  gc_globals->gc_full = false;
519
520
16
  gc_globals->buf = NULL;
521
16
  gc_globals->unused = GC_INVALID;
522
16
  gc_globals->first_unused = GC_INVALID;
523
16
  gc_globals->gc_threshold = GC_INVALID;
524
16
  gc_globals->buf_size = GC_INVALID;
525
16
  gc_globals->num_roots = 0;
526
527
16
  gc_globals->gc_runs = 0;
528
16
  gc_globals->collected = 0;
529
16
  gc_globals->collector_time = 0;
530
16
  gc_globals->dtor_time = 0;
531
16
  gc_globals->free_time = 0;
532
16
  gc_globals->activated_at = 0;
533
534
16
  gc_globals->dtor_idx = GC_FIRST_ROOT;
535
16
  gc_globals->dtor_end = 0;
536
16
  gc_globals->dtor_fiber = NULL;
537
16
  gc_globals->dtor_fiber_running = false;
538
539
#if GC_BENCH
540
  gc_globals->root_buf_length = 0;
541
  gc_globals->root_buf_peak = 0;
542
  gc_globals->zval_possible_root = 0;
543
  gc_globals->zval_buffered = 0;
544
  gc_globals->zval_remove_from_buffer = 0;
545
  gc_globals->zval_marked_grey = 0;
546
#endif
547
16
}
548
549
void gc_globals_ctor(void)
550
16
{
551
#ifdef ZTS
552
  ts_allocate_fast_id(&gc_globals_id, &gc_globals_offset, sizeof(zend_gc_globals), (ts_allocate_ctor) gc_globals_ctor_ex, (ts_allocate_dtor) root_buffer_dtor);
553
#else
554
16
  gc_globals_ctor_ex(&gc_globals);
555
16
#endif
556
16
}
557
558
void gc_globals_dtor(void)
559
0
{
560
0
#ifndef ZTS
561
0
  root_buffer_dtor(&gc_globals);
562
0
#endif
563
0
}
564
565
void gc_reset(void)
566
306k
{
567
306k
  if (GC_G(buf)) {
568
306k
    GC_G(gc_active) = 0;
569
306k
    GC_G(gc_protected) = 0;
570
306k
    GC_G(gc_full) = 0;
571
306k
    GC_G(unused) = GC_INVALID;
572
306k
    GC_G(first_unused) = GC_FIRST_ROOT;
573
306k
    GC_G(num_roots) = 0;
574
575
306k
    GC_G(gc_runs) = 0;
576
306k
    GC_G(collected) = 0;
577
578
306k
    GC_G(collector_time) = 0;
579
306k
    GC_G(dtor_time) = 0;
580
306k
    GC_G(free_time) = 0;
581
582
306k
    GC_G(dtor_idx) = GC_FIRST_ROOT;
583
306k
    GC_G(dtor_end) = 0;
584
306k
    GC_G(dtor_fiber) = NULL;
585
306k
    GC_G(dtor_fiber_running) = false;
586
587
#if GC_BENCH
588
    GC_G(root_buf_length) = 0;
589
    GC_G(root_buf_peak) = 0;
590
    GC_G(zval_possible_root) = 0;
591
    GC_G(zval_buffered) = 0;
592
    GC_G(zval_remove_from_buffer) = 0;
593
    GC_G(zval_marked_grey) = 0;
594
#endif
595
306k
  }
596
597
306k
  GC_G(activated_at) = zend_hrtime();
598
306k
}
599
600
/* Enable/disable the garbage collector.
601
 * Initialize globals if necessary. */
602
ZEND_API bool gc_enable(bool enable)
603
50.7k
{
604
50.7k
  bool old_enabled = GC_G(gc_enabled);
605
50.7k
  GC_G(gc_enabled) = enable;
606
50.7k
  if (enable && !old_enabled && GC_G(buf) == NULL) {
607
16
    GC_G(buf) = (gc_root_buffer*) pemalloc(sizeof(gc_root_buffer) * GC_DEFAULT_BUF_SIZE, 1);
608
16
    GC_G(buf)[0].ref = NULL;
609
16
    GC_G(buf_size) = GC_DEFAULT_BUF_SIZE;
610
16
    GC_G(gc_threshold) = GC_THRESHOLD_DEFAULT;
611
16
    gc_reset();
612
16
  }
613
50.7k
  return old_enabled;
614
50.7k
}
615
616
ZEND_API bool gc_enabled(void)
617
11
{
618
11
  return GC_G(gc_enabled);
619
11
}
620
621
/* Protect the GC root buffer (prevent additions) */
622
ZEND_API bool gc_protect(bool protect)
623
9.43k
{
624
9.43k
  bool old_protected = GC_G(gc_protected);
625
9.43k
  GC_G(gc_protected) = protect;
626
9.43k
  return old_protected;
627
9.43k
}
628
629
ZEND_API bool gc_protected(void)
630
0
{
631
0
  return GC_G(gc_protected);
632
0
}
633
634
static void gc_grow_root_buffer(void)
635
2
{
636
2
  size_t new_size;
637
638
2
  if (GC_G(buf_size) >= GC_MAX_BUF_SIZE) {
639
0
    if (!GC_G(gc_full)) {
640
0
      zend_error(E_WARNING, "GC buffer overflow (GC disabled)\n");
641
0
      GC_G(gc_active) = 1;
642
0
      GC_G(gc_protected) = 1;
643
0
      GC_G(gc_full) = 1;
644
0
      return;
645
0
    }
646
0
  }
647
2
  if (GC_G(buf_size) < GC_BUF_GROW_STEP) {
648
2
    new_size = GC_G(buf_size) * 2;
649
2
  } else {
650
0
    new_size = GC_G(buf_size) + GC_BUF_GROW_STEP;
651
0
  }
652
2
  if (new_size > GC_MAX_BUF_SIZE) {
653
0
    new_size = GC_MAX_BUF_SIZE;
654
0
  }
655
2
  GC_G(buf) = perealloc(GC_G(buf), sizeof(gc_root_buffer) * new_size, 1);
656
2
  GC_G(buf_size) = new_size;
657
2
}
658
659
/* Adjust the GC activation threshold given the number of nodes collected by the last run */
660
static void gc_adjust_threshold(int count)
661
0
{
662
0
  uint32_t new_threshold;
663
664
  /* TODO Very simple heuristic for dynamic GC buffer resizing:
665
   * If there are "too few" collections, increase the collection threshold
666
   * by a fixed step */
667
0
  if (count < GC_THRESHOLD_TRIGGER || GC_G(num_roots) >= GC_G(gc_threshold)) {
668
    /* increase */
669
0
    if (GC_G(gc_threshold) < GC_THRESHOLD_MAX) {
670
0
      new_threshold = GC_G(gc_threshold) + GC_THRESHOLD_STEP;
671
0
      if (new_threshold > GC_THRESHOLD_MAX) {
672
0
        new_threshold = GC_THRESHOLD_MAX;
673
0
      }
674
0
      if (new_threshold > GC_G(buf_size)) {
675
0
        gc_grow_root_buffer();
676
0
      }
677
0
      if (new_threshold <= GC_G(buf_size)) {
678
0
        GC_G(gc_threshold) = new_threshold;
679
0
      }
680
0
    }
681
0
  } else if (GC_G(gc_threshold) > GC_THRESHOLD_DEFAULT) {
682
0
    new_threshold = GC_G(gc_threshold) - GC_THRESHOLD_STEP;
683
0
    if (new_threshold < GC_THRESHOLD_DEFAULT) {
684
0
      new_threshold = GC_THRESHOLD_DEFAULT;
685
0
    }
686
0
    GC_G(gc_threshold) = new_threshold;
687
0
  }
688
0
}
689
690
/* Perform a GC run and then add a node as a possible root. */
691
static zend_never_inline void ZEND_FASTCALL gc_possible_root_when_full(zend_refcounted *ref)
692
0
{
693
0
  uint32_t idx;
694
0
  gc_root_buffer *newRoot;
695
696
0
  ZEND_ASSERT(GC_TYPE(ref) == IS_ARRAY || GC_TYPE(ref) == IS_OBJECT);
697
0
  ZEND_ASSERT(GC_INFO(ref) == 0);
698
699
0
  if (GC_G(gc_enabled) && !GC_G(gc_active)) {
700
0
    GC_ADDREF(ref);
701
0
    gc_adjust_threshold(gc_collect_cycles());
702
0
    if (UNEXPECTED(GC_DELREF(ref) == 0)) {
703
0
      rc_dtor_func(ref);
704
0
      return;
705
0
    } else if (UNEXPECTED(GC_INFO(ref))) {
706
0
      return;
707
0
    }
708
0
  }
709
710
0
  if (GC_HAS_UNUSED()) {
711
0
    idx = GC_FETCH_UNUSED();
712
0
  } else if (EXPECTED(GC_HAS_NEXT_UNUSED())) {
713
0
    idx = GC_FETCH_NEXT_UNUSED();
714
0
  } else {
715
0
    gc_grow_root_buffer();
716
0
    if (UNEXPECTED(!GC_HAS_NEXT_UNUSED())) {
717
0
      return;
718
0
    }
719
0
    idx = GC_FETCH_NEXT_UNUSED();
720
0
  }
721
722
0
  newRoot = GC_IDX2PTR(idx);
723
0
  newRoot->ref = ref; /* GC_ROOT tag is 0 */
724
0
  GC_TRACE_SET_COLOR(ref, GC_PURPLE);
725
726
0
  idx = gc_compress(idx);
727
0
  GC_REF_SET_INFO(ref, idx | GC_PURPLE);
728
0
  GC_G(num_roots)++;
729
730
0
  GC_BENCH_INC(zval_buffered);
731
0
  GC_BENCH_INC(root_buf_length);
732
0
  GC_BENCH_PEAK(root_buf_peak, root_buf_length);
733
0
}
734
735
/* Add a possible root node to the buffer.
736
 * Maybe perform a GC run. */
737
ZEND_API void ZEND_FASTCALL gc_possible_root(zend_refcounted *ref)
738
2.34M
{
739
2.34M
  uint32_t idx;
740
2.34M
  gc_root_buffer *newRoot;
741
742
2.34M
  if (UNEXPECTED(GC_G(gc_protected))) {
743
28.5k
    return;
744
28.5k
  }
745
746
2.31M
  GC_BENCH_INC(zval_possible_root);
747
748
2.31M
  if (EXPECTED(GC_HAS_UNUSED())) {
749
383k
    idx = GC_FETCH_UNUSED();
750
1.92M
  } else if (EXPECTED(GC_HAS_NEXT_UNUSED_UNDER_THRESHOLD())) {
751
1.92M
    idx = GC_FETCH_NEXT_UNUSED();
752
1.92M
  } else {
753
0
    gc_possible_root_when_full(ref);
754
0
    return;
755
0
  }
756
757
2.31M
  ZEND_ASSERT(GC_TYPE(ref) == IS_ARRAY || GC_TYPE(ref) == IS_OBJECT);
758
2.31M
  ZEND_ASSERT(GC_INFO(ref) == 0);
759
760
2.31M
  newRoot = GC_IDX2PTR(idx);
761
2.31M
  newRoot->ref = ref; /* GC_ROOT tag is 0 */
762
2.31M
  GC_TRACE_SET_COLOR(ref, GC_PURPLE);
763
764
2.31M
  idx = gc_compress(idx);
765
2.31M
  GC_REF_SET_INFO(ref, idx | GC_PURPLE);
766
2.31M
  GC_G(num_roots)++;
767
768
2.31M
  GC_BENCH_INC(zval_buffered);
769
2.31M
  GC_BENCH_INC(root_buf_length);
770
2.31M
  GC_BENCH_PEAK(root_buf_peak, root_buf_length);
771
2.31M
}
772
773
/* Add an extra root during a GC run */
774
static void ZEND_FASTCALL gc_extra_root(zend_refcounted *ref)
775
2
{
776
2
  uint32_t idx;
777
2
  gc_root_buffer *newRoot;
778
779
2
  if (EXPECTED(GC_HAS_UNUSED())) {
780
0
    idx = GC_FETCH_UNUSED();
781
2
  } else if (EXPECTED(GC_HAS_NEXT_UNUSED())) {
782
2
    idx = GC_FETCH_NEXT_UNUSED();
783
2
  } else {
784
0
    gc_grow_root_buffer();
785
0
    if (UNEXPECTED(!GC_HAS_NEXT_UNUSED())) {
786
      /* TODO: can this really happen? */
787
0
      return;
788
0
    }
789
0
    idx = GC_FETCH_NEXT_UNUSED();
790
0
  }
791
792
2
  ZEND_ASSERT(GC_TYPE(ref) == IS_ARRAY || GC_TYPE(ref) == IS_OBJECT);
793
2
  ZEND_ASSERT(GC_REF_ADDRESS(ref) == 0);
794
795
2
  newRoot = GC_IDX2PTR(idx);
796
2
  newRoot->ref = ref; /* GC_ROOT tag is 0 */
797
798
2
  idx = gc_compress(idx);
799
2
  GC_REF_SET_INFO(ref, idx | GC_REF_COLOR(ref));
800
2
  GC_G(num_roots)++;
801
802
2
  GC_BENCH_INC(zval_buffered);
803
2
  GC_BENCH_INC(root_buf_length);
804
2
  GC_BENCH_PEAK(root_buf_peak, root_buf_length);
805
2
}
806
807
/* Remove a node from the root buffer given its compressed index */
808
static zend_never_inline void ZEND_FASTCALL gc_remove_compressed(zend_refcounted *ref, uint32_t idx)
809
0
{
810
0
  gc_root_buffer *root = gc_decompress(ref, idx);
811
0
  gc_remove_from_roots(root);
812
0
}
813
814
ZEND_API void ZEND_FASTCALL gc_remove_from_buffer(zend_refcounted *ref)
815
3.14M
{
816
3.14M
  gc_root_buffer *root;
817
3.14M
  uint32_t idx = GC_REF_ADDRESS(ref);
818
819
3.14M
  GC_BENCH_INC(zval_remove_from_buffer);
820
821
3.14M
  if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
822
1.94M
    GC_TRACE_SET_COLOR(ref, GC_BLACK);
823
1.94M
  }
824
3.14M
  GC_REF_SET_INFO(ref, 0);
825
826
  /* Perform decompression only in case of large buffers */
827
3.14M
  if (UNEXPECTED(GC_G(first_unused) >= GC_MAX_UNCOMPRESSED)) {
828
0
    gc_remove_compressed(ref, idx);
829
0
    return;
830
0
  }
831
832
3.14M
  ZEND_ASSERT(idx);
833
3.14M
  root = GC_IDX2PTR(idx);
834
3.14M
  gc_remove_from_roots(root);
835
3.14M
}
836
837
/* Mark all nodes reachable from ref as black (live). Restore the reference
838
 * counts decremented by gc_mark_grey(). See ScanBlack() in Bacon & Rajan.
839
 * To implement a depth-first search, discovered nodes are added to a stack
840
 * which is processed iteratively. */
841
static void gc_scan_black(zend_refcounted *ref, gc_stack *stack)
842
3.58k
{
843
3.58k
  HashTable *ht;
844
3.58k
  Bucket *p;
845
3.58k
  zval *zv;
846
3.58k
  uint32_t n;
847
3.58k
  GC_STACK_DCL(stack);
848
849
19.1k
tail_call:
850
19.1k
  if (GC_TYPE(ref) == IS_OBJECT) {
851
291
    zend_object *obj = (zend_object*)ref;
852
853
291
    if (EXPECTED(!(OBJ_FLAGS(ref) & IS_OBJ_FREE_CALLED))) {
854
291
      zval *table;
855
291
      int len;
856
857
291
      if (UNEXPECTED(GC_FLAGS(obj) & IS_OBJ_WEAKLY_REFERENCED)) {
858
4
        zend_weakmap_get_object_key_entry_gc(obj, &table, &len);
859
4
        n = len;
860
4
        zv = table;
861
8
        for (; n != 0; n-=2) {
862
4
          ZEND_ASSERT(Z_TYPE_P(zv) == IS_PTR);
863
4
          zval *entry = (zval*) Z_PTR_P(zv);
864
4
          zval *weakmap = zv+1;
865
4
          ZEND_ASSERT(Z_REFCOUNTED_P(weakmap));
866
4
          if (Z_OPT_COLLECTABLE_P(entry)) {
867
4
            GC_UNSET_FROM_WEAKMAP_KEY(entry);
868
4
            if (GC_REF_CHECK_COLOR(Z_COUNTED_P(weakmap), GC_GREY)) {
869
              /* Weakmap was scanned in gc_mark_roots, we must
870
               * ensure that it's eventually scanned in
871
               * gc_scan_roots as well. */
872
1
              if (!GC_REF_ADDRESS(Z_COUNTED_P(weakmap))) {
873
1
                gc_extra_root(Z_COUNTED_P(weakmap));
874
1
              }
875
3
            } else if (/* GC_REF_CHECK_COLOR(Z_COUNTED_P(weakmap), GC_BLACK) && */ !GC_FROM_WEAKMAP(entry)) {
876
              /* Both the entry weakmap and key are BLACK, so we
877
               * can mark the entry BLACK as well.
878
               * !GC_FROM_WEAKMAP(entry) means that the weakmap
879
               * was already scanned black (or will not be
880
               * scanned), so it's our responsibility to mark the
881
               * entry */
882
2
              ZEND_ASSERT(GC_REF_CHECK_COLOR(Z_COUNTED_P(weakmap), GC_BLACK));
883
2
              ref = Z_COUNTED_P(entry);
884
2
              GC_ADDREF(ref);
885
2
              if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
886
0
                GC_REF_SET_BLACK(ref);
887
0
                GC_STACK_PUSH(ref);
888
0
              }
889
2
            }
890
4
          }
891
4
          zv+=2;
892
4
        }
893
4
      }
894
895
291
      if (UNEXPECTED(obj->handlers->get_gc == zend_weakmap_get_gc)) {
896
3
        zend_weakmap_get_key_entry_gc(obj, &table, &len);
897
3
        n = len;
898
3
        zv = table;
899
8
        for (; n != 0; n-=2) {
900
5
          ZEND_ASSERT(Z_TYPE_P(zv+1) == IS_PTR);
901
5
          zval *key = zv;
902
5
          zval *entry = (zval*) Z_PTR_P(zv+1);
903
5
          if (Z_OPT_COLLECTABLE_P(entry)) {
904
5
            GC_UNSET_FROM_WEAKMAP(entry);
905
5
            if (GC_REF_CHECK_COLOR(Z_COUNTED_P(key), GC_GREY)) {
906
              /* Key was scanned in gc_mark_roots, we must
907
               * ensure that it's eventually scanned in
908
               * gc_scan_roots as well. */
909
3
              if (!GC_REF_ADDRESS(Z_COUNTED_P(key))) {
910
1
                gc_extra_root(Z_COUNTED_P(key));
911
1
              }
912
3
            } else if (/* GC_REF_CHECK_COLOR(Z_COUNTED_P(key), GC_BLACK) && */ !GC_FROM_WEAKMAP_KEY(entry)) {
913
              /* Both the entry weakmap and key are BLACK, so we
914
               * can mark the entry BLACK as well.
915
               * !GC_FROM_WEAKMAP_KEY(entry) means that the key
916
               * was already scanned black (or will not be
917
               * scanned), so it's our responsibility to mark the
918
               * entry */
919
2
              ZEND_ASSERT(GC_REF_CHECK_COLOR(Z_COUNTED_P(key), GC_BLACK));
920
2
              ref = Z_COUNTED_P(entry);
921
2
              GC_ADDREF(ref);
922
2
              if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
923
2
                GC_REF_SET_BLACK(ref);
924
2
                GC_STACK_PUSH(ref);
925
2
              }
926
2
            }
927
5
          }
928
5
          zv += 2;
929
5
        }
930
3
        goto next;
931
3
      }
932
933
288
      ht = obj->handlers->get_gc(obj, &table, &len);
934
288
      n = len;
935
288
      zv = table;
936
288
      if (UNEXPECTED(ht)) {
937
115
        GC_ADDREF(ht);
938
115
        if (!GC_REF_CHECK_COLOR(ht, GC_BLACK)) {
939
115
          GC_REF_SET_BLACK(ht);
940
184
          for (; n != 0; n--) {
941
69
            if (Z_COLLECTABLE_P(zv)) {
942
22
              ref = Z_COUNTED_P(zv);
943
22
              GC_ADDREF(ref);
944
22
              if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
945
20
                GC_REF_SET_BLACK(ref);
946
20
                GC_STACK_PUSH(ref);
947
20
              }
948
22
            }
949
69
            zv++;
950
69
          }
951
115
          goto handle_ht;
952
115
        }
953
115
      }
954
955
16.8k
handle_zvals:
956
37.4k
      for (; n != 0; n--) {
957
23.0k
        if (Z_COLLECTABLE_P(zv)) {
958
4.22k
          ref = Z_COUNTED_P(zv);
959
4.22k
          GC_ADDREF(ref);
960
4.22k
          if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
961
2.46k
            GC_REF_SET_BLACK(ref);
962
2.46k
            zv++;
963
14.6k
            while (--n) {
964
12.1k
              if (Z_COLLECTABLE_P(zv)) {
965
9.54k
                zend_refcounted *ref = Z_COUNTED_P(zv);
966
9.54k
                GC_ADDREF(ref);
967
9.54k
                if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
968
9.54k
                  GC_REF_SET_BLACK(ref);
969
9.54k
                  GC_STACK_PUSH(ref);
970
9.54k
                }
971
9.54k
              }
972
12.1k
              zv++;
973
12.1k
            }
974
2.46k
            goto tail_call;
975
2.46k
          }
976
4.22k
        }
977
20.6k
        zv++;
978
20.6k
      }
979
16.8k
    }
980
18.8k
  } else if (GC_TYPE(ref) == IS_ARRAY) {
981
18.8k
    ZEND_ASSERT((zend_array*)ref != &EG(symbol_table));
982
18.8k
    ht = (zend_array*)ref;
983
18.9k
handle_ht:
984
18.9k
    n = ht->nNumUsed;
985
18.9k
    zv = ht->arPacked;
986
18.9k
    if (HT_IS_PACKED(ht)) {
987
16.6k
      goto handle_zvals;
988
16.6k
    }
989
990
2.27k
    p = (Bucket*)zv;
991
6.13k
    for (; n != 0; n--) {
992
4.85k
      zv = &p->val;
993
4.85k
      if (Z_TYPE_P(zv) == IS_INDIRECT) {
994
102
        zv = Z_INDIRECT_P(zv);
995
102
      }
996
4.85k
      if (Z_COLLECTABLE_P(zv)) {
997
1.20k
        ref = Z_COUNTED_P(zv);
998
1.20k
        GC_ADDREF(ref);
999
1.20k
        if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
1000
999
          GC_REF_SET_BLACK(ref);
1001
999
          p++;
1002
6.45k
          while (--n) {
1003
5.45k
            zv = &p->val;
1004
5.45k
            if (Z_TYPE_P(zv) == IS_INDIRECT) {
1005
5
              zv = Z_INDIRECT_P(zv);
1006
5
            }
1007
5.45k
            if (Z_COLLECTABLE_P(zv)) {
1008
2.51k
              zend_refcounted *ref = Z_COUNTED_P(zv);
1009
2.51k
              GC_ADDREF(ref);
1010
2.51k
              if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
1011
2.50k
                GC_REF_SET_BLACK(ref);
1012
2.50k
                GC_STACK_PUSH(ref);
1013
2.50k
              }
1014
2.51k
            }
1015
5.45k
            p++;
1016
5.45k
          }
1017
999
          goto tail_call;
1018
999
        }
1019
1.20k
      }
1020
3.85k
      p++;
1021
3.85k
    }
1022
2.27k
  } else if (GC_TYPE(ref) == IS_REFERENCE) {
1023
54
    if (Z_COLLECTABLE(((zend_reference*)ref)->val)) {
1024
23
      ref = Z_COUNTED(((zend_reference*)ref)->val);
1025
23
      GC_ADDREF(ref);
1026
23
      if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
1027
19
        GC_REF_SET_BLACK(ref);
1028
19
        goto tail_call;
1029
19
      }
1030
23
    }
1031
54
  }
1032
1033
15.6k
next:
1034
15.6k
  ref = GC_STACK_POP();
1035
15.6k
  if (ref) {
1036
12.0k
    goto tail_call;
1037
12.0k
  }
1038
15.6k
}
1039
1040
/* Traverse the graph of nodes referred to by ref. Decrement the reference
1041
 * counts and mark visited nodes grey. See MarkGray() in Bacon & Rajan. */
1042
static void gc_mark_grey(zend_refcounted *ref, gc_stack *stack)
1043
106k
{
1044
106k
  HashTable *ht;
1045
106k
  Bucket *p;
1046
106k
  zval *zv;
1047
106k
  uint32_t n;
1048
106k
  GC_STACK_DCL(stack);
1049
1050
854k
tail_call:
1051
854k
  GC_BENCH_INC(zval_marked_grey);
1052
1053
854k
  if (GC_TYPE(ref) == IS_OBJECT) {
1054
477k
    zend_object *obj = (zend_object*)ref;
1055
1056
477k
    if (EXPECTED(!(OBJ_FLAGS(ref) & IS_OBJ_FREE_CALLED))) {
1057
477k
      zval *table;
1058
477k
      int len;
1059
1060
477k
      if (UNEXPECTED(GC_FLAGS(obj) & IS_OBJ_WEAKLY_REFERENCED)) {
1061
7
        zend_weakmap_get_object_key_entry_gc(obj, &table, &len);
1062
7
        n = len;
1063
7
        zv = table;
1064
14
        for (; n != 0; n-=2) {
1065
7
          ZEND_ASSERT(Z_TYPE_P(zv) == IS_PTR);
1066
7
          zval *entry = (zval*) Z_PTR_P(zv);
1067
7
          zval *weakmap = zv+1;
1068
7
          ZEND_ASSERT(Z_REFCOUNTED_P(weakmap));
1069
7
          if (Z_COLLECTABLE_P(entry)) {
1070
7
            GC_SET_FROM_WEAKMAP_KEY(entry);
1071
7
            ref = Z_COUNTED_P(entry);
1072
            /* Only DELREF if the contribution from the weakmap has
1073
             * not been cancelled yet */
1074
7
            if (!GC_FROM_WEAKMAP(entry)) {
1075
2
              GC_DELREF(ref);
1076
2
            }
1077
7
            if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1078
1
              GC_REF_SET_COLOR(ref, GC_GREY);
1079
1
              GC_STACK_PUSH(ref);
1080
1
            }
1081
7
          }
1082
7
          zv+=2;
1083
7
        }
1084
7
      }
1085
1086
477k
      if (UNEXPECTED(obj->handlers->get_gc == zend_weakmap_get_gc)) {
1087
4
        zend_weakmap_get_entry_gc(obj, &table, &len);
1088
4
        n = len;
1089
4
        zv = table;
1090
11
        for (; n != 0; n--) {
1091
7
          ZEND_ASSERT(Z_TYPE_P(zv) == IS_PTR);
1092
7
          zval *entry = (zval*) Z_PTR_P(zv);
1093
7
          if (Z_COLLECTABLE_P(entry)) {
1094
7
            GC_SET_FROM_WEAKMAP(entry);
1095
7
            ref = Z_COUNTED_P(entry);
1096
            /* Only DELREF if the contribution from the weakmap key
1097
             * has not been cancelled yet */
1098
7
            if (!GC_FROM_WEAKMAP_KEY(entry)) {
1099
5
              GC_DELREF(ref);
1100
5
            }
1101
7
            if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1102
5
              GC_REF_SET_COLOR(ref, GC_GREY);
1103
5
              GC_STACK_PUSH(ref);
1104
5
            }
1105
7
          }
1106
7
          zv++;
1107
7
        }
1108
4
        goto next;
1109
4
      }
1110
1111
477k
      ht = obj->handlers->get_gc(obj, &table, &len);
1112
477k
      n = len;
1113
477k
      zv = table;
1114
477k
      if (UNEXPECTED(ht)) {
1115
474k
        GC_DELREF(ht);
1116
474k
        if (!GC_REF_CHECK_COLOR(ht, GC_GREY)) {
1117
474k
          GC_REF_SET_COLOR(ht, GC_GREY);
1118
647k
          for (; n != 0; n--) {
1119
172k
            if (Z_COLLECTABLE_P(zv)) {
1120
172k
              ref = Z_COUNTED_P(zv);
1121
172k
              GC_DELREF(ref);
1122
172k
              if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1123
169k
                GC_REF_SET_COLOR(ref, GC_GREY);
1124
169k
                GC_STACK_PUSH(ref);
1125
169k
              }
1126
172k
            }
1127
172k
            zv++;
1128
172k
          }
1129
474k
          goto handle_ht;
1130
474k
        }
1131
474k
      }
1132
36.5k
handle_zvals:
1133
182k
      for (; n != 0; n--) {
1134
152k
        if (Z_COLLECTABLE_P(zv)) {
1135
44.0k
          ref = Z_COUNTED_P(zv);
1136
44.0k
          GC_DELREF(ref);
1137
44.0k
          if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1138
6.32k
            GC_REF_SET_COLOR(ref, GC_GREY);
1139
6.32k
            zv++;
1140
18.8k
            while (--n) {
1141
12.4k
              if (Z_COLLECTABLE_P(zv)) {
1142
9.10k
                zend_refcounted *ref = Z_COUNTED_P(zv);
1143
9.10k
                GC_DELREF(ref);
1144
9.10k
                if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1145
7.54k
                  GC_REF_SET_COLOR(ref, GC_GREY);
1146
7.54k
                  GC_STACK_PUSH(ref);
1147
7.54k
                }
1148
9.10k
              }
1149
12.4k
              zv++;
1150
12.4k
            }
1151
6.32k
            goto tail_call;
1152
6.32k
          }
1153
44.0k
        }
1154
145k
        zv++;
1155
145k
      }
1156
36.5k
    }
1157
477k
  } else if (GC_TYPE(ref) == IS_ARRAY) {
1158
367k
    ZEND_ASSERT(((zend_array*)ref) != &EG(symbol_table));
1159
367k
    ht = (zend_array*)ref;
1160
842k
handle_ht:
1161
842k
    n = ht->nNumUsed;
1162
842k
    if (HT_IS_PACKED(ht)) {
1163
34.0k
            zv = ht->arPacked;
1164
34.0k
            goto handle_zvals;
1165
34.0k
    }
1166
1167
808k
    p = ht->arData;
1168
1.53M
    for (; n != 0; n--) {
1169
978k
      zv = &p->val;
1170
978k
      if (Z_TYPE_P(zv) == IS_INDIRECT) {
1171
395k
        zv = Z_INDIRECT_P(zv);
1172
395k
      }
1173
978k
      if (Z_COLLECTABLE_P(zv)) {
1174
448k
        ref = Z_COUNTED_P(zv);
1175
448k
        GC_DELREF(ref);
1176
448k
        if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1177
256k
          GC_REF_SET_COLOR(ref, GC_GREY);
1178
256k
          p++;
1179
1.00M
          while (--n) {
1180
752k
            zv = &p->val;
1181
752k
            if (Z_TYPE_P(zv) == IS_INDIRECT) {
1182
66.1k
              zv = Z_INDIRECT_P(zv);
1183
66.1k
            }
1184
752k
            if (Z_COLLECTABLE_P(zv)) {
1185
592k
              zend_refcounted *ref = Z_COUNTED_P(zv);
1186
592k
              GC_DELREF(ref);
1187
592k
              if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1188
307k
                GC_REF_SET_COLOR(ref, GC_GREY);
1189
307k
                GC_STACK_PUSH(ref);
1190
307k
              }
1191
592k
            }
1192
752k
            p++;
1193
752k
          }
1194
256k
          goto tail_call;
1195
256k
        }
1196
448k
      }
1197
722k
      p++;
1198
722k
    }
1199
808k
  } else if (GC_TYPE(ref) == IS_REFERENCE) {
1200
10.0k
    if (Z_COLLECTABLE(((zend_reference*)ref)->val)) {
1201
8.87k
      ref = Z_COUNTED(((zend_reference*)ref)->val);
1202
8.87k
      GC_DELREF(ref);
1203
8.87k
      if (!GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1204
1.27k
        GC_REF_SET_COLOR(ref, GC_GREY);
1205
1.27k
        goto tail_call;
1206
1.27k
      }
1207
8.87k
    }
1208
10.0k
  }
1209
1210
590k
next:
1211
590k
  ref = GC_STACK_POP();
1212
590k
  if (ref) {
1213
484k
    goto tail_call;
1214
484k
  }
1215
590k
}
1216
1217
/* Two-Finger compaction algorithm */
1218
static void gc_compact(void)
1219
890k
{
1220
890k
  if (GC_G(num_roots) + GC_FIRST_ROOT != GC_G(first_unused)) {
1221
439k
    if (GC_G(num_roots)) {
1222
1.35k
      gc_root_buffer *free = GC_IDX2PTR(GC_FIRST_ROOT);
1223
1.35k
      gc_root_buffer *scan = GC_IDX2PTR(GC_G(first_unused) - 1);
1224
1.35k
      gc_root_buffer *end  = GC_IDX2PTR(GC_G(num_roots));
1225
1.35k
      uint32_t idx;
1226
1.35k
      zend_refcounted *p;
1227
1228
5.90k
      while (free < scan) {
1229
278k
        while (!GC_IS_UNUSED(free->ref)) {
1230
273k
          free++;
1231
273k
        }
1232
34.8k
        while (GC_IS_UNUSED(scan->ref)) {
1233
29.9k
          scan--;
1234
29.9k
        }
1235
4.89k
        if (scan > free) {
1236
3.90k
          p = scan->ref;
1237
3.90k
          free->ref = p;
1238
3.90k
          p = GC_GET_PTR(p);
1239
3.90k
          idx = gc_compress(GC_PTR2IDX(free));
1240
3.90k
          GC_REF_SET_INFO(p, idx | GC_REF_COLOR(p));
1241
3.90k
          free++;
1242
3.90k
          scan--;
1243
3.90k
          if (scan <= end) {
1244
345
            break;
1245
345
          }
1246
3.90k
        }
1247
4.89k
      }
1248
1.35k
    }
1249
439k
    GC_G(unused) = GC_INVALID;
1250
439k
    GC_G(first_unused) = GC_G(num_roots) + GC_FIRST_ROOT;
1251
439k
  }
1252
890k
}
1253
1254
/* For all roots marked purple, traverse the graph, decrementing the reference
1255
 * count of their child nodes. Mark visited nodes grey so that they are not
1256
 * visited again. See MarkRoots() in Bacon & Rajan. */
1257
static void gc_mark_roots(gc_stack *stack)
1258
3.29k
{
1259
3.29k
  gc_root_buffer *current, *last;
1260
1261
3.29k
  gc_compact();
1262
1263
3.29k
  current = GC_IDX2PTR(GC_FIRST_ROOT);
1264
3.29k
  last = GC_IDX2PTR(GC_G(first_unused));
1265
366k
  while (current != last) {
1266
363k
    if (GC_IS_ROOT(current->ref)) {
1267
363k
      if (GC_REF_CHECK_COLOR(current->ref, GC_PURPLE)) {
1268
106k
        GC_REF_SET_COLOR(current->ref, GC_GREY);
1269
106k
        gc_mark_grey(current->ref, stack);
1270
106k
      }
1271
363k
    }
1272
363k
    current++;
1273
363k
  }
1274
3.29k
}
1275
1276
/* Traverse the reference graph of ref. Evaluate grey nodes and mark them
1277
 * black (to keep) or white (to free). Note that nodes initially marked white
1278
 * may later become black if they are visited from a live node.
1279
 * See Scan() in Bacon & Rajan. */
1280
static void gc_scan(zend_refcounted *ref, gc_stack *stack)
1281
106k
{
1282
106k
  HashTable *ht;
1283
106k
  Bucket *p;
1284
106k
  zval *zv;
1285
106k
  uint32_t n;
1286
106k
  GC_STACK_DCL(stack);
1287
1288
1.32M
tail_call:
1289
1.32M
  if (!GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1290
2
    goto next;
1291
2
  }
1292
1293
1.32M
  if (GC_REFCOUNT(ref) > 0) {
1294
3.58k
    if (!GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
1295
3.58k
      GC_REF_SET_BLACK(ref);
1296
3.58k
      if (UNEXPECTED(!_stack->next)) {
1297
622
        gc_stack_next(_stack);
1298
622
      }
1299
      /* Split stack and reuse the tail */
1300
3.58k
      _stack->next->prev = NULL;
1301
3.58k
      gc_scan_black(ref, _stack->next);
1302
3.58k
      _stack->next->prev = _stack;
1303
3.58k
    }
1304
3.58k
    goto next;
1305
3.58k
  }
1306
1307
1.32M
  if (GC_TYPE(ref) == IS_OBJECT) {
1308
477k
    zend_object *obj = (zend_object*)ref;
1309
477k
    if (EXPECTED(!(OBJ_FLAGS(ref) & IS_OBJ_FREE_CALLED))) {
1310
477k
      zval *table;
1311
477k
      int len;
1312
1313
477k
      if (UNEXPECTED(GC_FLAGS(obj) & IS_OBJ_WEAKLY_REFERENCED)) {
1314
3
        zend_weakmap_get_object_entry_gc(obj, &table, &len);
1315
3
        n = len;
1316
3
        zv = table;
1317
6
        for (; n != 0; n--) {
1318
3
          ZEND_ASSERT(Z_TYPE_P(zv) == IS_PTR);
1319
3
          zval *entry = (zval*) Z_PTR_P(zv);
1320
3
          if (Z_OPT_COLLECTABLE_P(entry)) {
1321
3
            ref = Z_COUNTED_P(entry);
1322
3
            if (GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1323
1
              GC_REF_SET_COLOR(ref, GC_WHITE);
1324
1
              GC_STACK_PUSH(ref);
1325
1
            }
1326
3
          }
1327
3
          zv++;
1328
3
        }
1329
3
      }
1330
1331
477k
      ht = obj->handlers->get_gc(obj, &table, &len);
1332
477k
      n = len;
1333
477k
      zv = table;
1334
477k
      if (UNEXPECTED(ht)) {
1335
474k
        if (GC_REF_CHECK_COLOR(ht, GC_GREY)) {
1336
474k
          GC_REF_SET_COLOR(ht, GC_WHITE);
1337
474k
          GC_STACK_PUSH((zend_refcounted *) ht);
1338
647k
          for (; n != 0; n--) {
1339
172k
            if (Z_COLLECTABLE_P(zv)) {
1340
172k
              ref = Z_COUNTED_P(zv);
1341
172k
              if (GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1342
169k
                GC_REF_SET_COLOR(ref, GC_WHITE);
1343
169k
                GC_STACK_PUSH(ref);
1344
169k
              }
1345
172k
            }
1346
172k
            zv++;
1347
172k
          }
1348
474k
          goto handle_ht;
1349
474k
        }
1350
474k
      }
1351
1352
48.9k
handle_zvals:
1353
307k
      for (; n != 0; n--) {
1354
263k
        if (Z_COLLECTABLE_P(zv)) {
1355
75.3k
          ref = Z_COUNTED_P(zv);
1356
75.3k
          if (GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1357
5.40k
            GC_REF_SET_COLOR(ref, GC_WHITE);
1358
5.40k
            zv++;
1359
15.9k
            while (--n) {
1360
10.5k
              if (Z_COLLECTABLE_P(zv)) {
1361
7.89k
                zend_refcounted *ref = Z_COUNTED_P(zv);
1362
7.89k
                if (GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1363
6.49k
                  GC_REF_SET_COLOR(ref, GC_WHITE);
1364
6.49k
                  GC_STACK_PUSH(ref);
1365
6.49k
                }
1366
7.89k
              }
1367
10.5k
              zv++;
1368
10.5k
            }
1369
5.40k
            goto tail_call;
1370
5.40k
          }
1371
75.3k
        }
1372
258k
        zv++;
1373
258k
      }
1374
48.9k
    }
1375
846k
  } else if (GC_TYPE(ref) == IS_ARRAY) {
1376
836k
    ht = (HashTable *)ref;
1377
836k
    ZEND_ASSERT(ht != &EG(symbol_table));
1378
1379
1.31M
handle_ht:
1380
1.31M
    n = ht->nNumUsed;
1381
1.31M
    if (HT_IS_PACKED(ht)) {
1382
46.6k
            zv = ht->arPacked;
1383
46.6k
            goto handle_zvals;
1384
46.6k
    }
1385
1386
1.26M
    p = ht->arData;
1387
3.17M
    for (; n != 0; n--) {
1388
2.16M
      zv = &p->val;
1389
2.16M
      if (Z_TYPE_P(zv) == IS_INDIRECT) {
1390
856k
        zv = Z_INDIRECT_P(zv);
1391
856k
      }
1392
2.16M
      if (Z_COLLECTABLE_P(zv)) {
1393
1.02M
        ref = Z_COUNTED_P(zv);
1394
1.02M
        if (GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1395
256k
          GC_REF_SET_COLOR(ref, GC_WHITE);
1396
256k
          p++;
1397
1.00M
          while (--n) {
1398
752k
            zv = &p->val;
1399
752k
            if (Z_TYPE_P(zv) == IS_INDIRECT) {
1400
66.1k
              zv = Z_INDIRECT_P(zv);
1401
66.1k
            }
1402
752k
            if (Z_COLLECTABLE_P(zv)) {
1403
591k
              zend_refcounted *ref = Z_COUNTED_P(zv);
1404
591k
              if (GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1405
307k
                GC_REF_SET_COLOR(ref, GC_WHITE);
1406
307k
                GC_STACK_PUSH(ref);
1407
307k
              }
1408
591k
            }
1409
752k
            p++;
1410
752k
          }
1411
256k
          goto tail_call;
1412
256k
        }
1413
1.02M
      }
1414
1.90M
      p++;
1415
1.90M
    }
1416
1.26M
  } else if (GC_TYPE(ref) == IS_REFERENCE) {
1417
9.95k
    if (Z_COLLECTABLE(((zend_reference*)ref)->val)) {
1418
8.85k
      ref = Z_COUNTED(((zend_reference*)ref)->val);
1419
8.85k
      if (GC_REF_CHECK_COLOR(ref, GC_GREY)) {
1420
1.26k
        GC_REF_SET_COLOR(ref, GC_WHITE);
1421
1.26k
        goto tail_call;
1422
1.26k
      }
1423
8.85k
    }
1424
9.95k
  }
1425
1426
1.06M
next:
1427
1.06M
  ref = GC_STACK_POP();
1428
1.06M
  if (ref) {
1429
957k
    goto tail_call;
1430
957k
  }
1431
1.06M
}
1432
1433
/* Scan all roots, coloring grey nodes black or white */
1434
static void gc_scan_roots(gc_stack *stack)
1435
3.29k
{
1436
3.29k
  uint32_t idx, end;
1437
3.29k
  gc_root_buffer *current;
1438
1439
  /* Root buffer might be reallocated during gc_scan,
1440
   * make sure to reload pointers. */
1441
3.29k
  idx = GC_FIRST_ROOT;
1442
3.29k
  end = GC_G(first_unused);
1443
366k
  while (idx != end) {
1444
363k
    current = GC_IDX2PTR(idx);
1445
363k
    if (GC_IS_ROOT(current->ref)) {
1446
363k
      if (GC_REF_CHECK_COLOR(current->ref, GC_GREY)) {
1447
106k
        GC_REF_SET_COLOR(current->ref, GC_WHITE);
1448
106k
        gc_scan(current->ref, stack);
1449
106k
      }
1450
363k
    }
1451
363k
    idx++;
1452
363k
  }
1453
1454
  /* Scan extra roots added during gc_scan */
1455
3.30k
  while (idx != GC_G(first_unused)) {
1456
2
    current = GC_IDX2PTR(idx);
1457
2
    if (GC_IS_ROOT(current->ref)) {
1458
2
      if (GC_REF_CHECK_COLOR(current->ref, GC_GREY)) {
1459
2
        GC_REF_SET_COLOR(current->ref, GC_WHITE);
1460
2
        gc_scan(current->ref, stack);
1461
2
      }
1462
2
    }
1463
2
    idx++;
1464
2
  }
1465
3.29k
}
1466
1467
/* Add a node to the buffer with the garbage flag, so that it will be
1468
 * destroyed and freed when the scan is complete. */
1469
static void gc_add_garbage(zend_refcounted *ref)
1470
946k
{
1471
946k
  uint32_t idx;
1472
946k
  gc_root_buffer *buf;
1473
1474
946k
  if (GC_HAS_UNUSED()) {
1475
0
    idx = GC_FETCH_UNUSED();
1476
946k
  } else if (GC_HAS_NEXT_UNUSED()) {
1477
946k
    idx = GC_FETCH_NEXT_UNUSED();
1478
946k
  } else {
1479
2
    gc_grow_root_buffer();
1480
2
    if (UNEXPECTED(!GC_HAS_NEXT_UNUSED())) {
1481
0
      return;
1482
0
    }
1483
2
    idx = GC_FETCH_NEXT_UNUSED();
1484
2
  }
1485
1486
946k
  buf = GC_IDX2PTR(idx);
1487
946k
  buf->ref = GC_MAKE_GARBAGE(ref);
1488
1489
946k
  idx = gc_compress(idx);
1490
946k
  GC_REF_SET_INFO(ref, idx | GC_BLACK);
1491
946k
  GC_G(num_roots)++;
1492
946k
}
1493
1494
/* Traverse the reference graph from ref, marking any white nodes as garbage. */
1495
static int gc_collect_white(zend_refcounted *ref, uint32_t *flags, gc_stack *stack)
1496
97.8k
{
1497
97.8k
  int count = 0;
1498
97.8k
  HashTable *ht;
1499
97.8k
  Bucket *p;
1500
97.8k
  zval *zv;
1501
97.8k
  uint32_t n;
1502
97.8k
  GC_STACK_DCL(stack);
1503
1504
835k
tail_call:
1505
  /* don't count references for compatibility ??? */
1506
835k
  if (GC_TYPE(ref) != IS_REFERENCE) {
1507
825k
    count++;
1508
825k
  }
1509
1510
835k
  if (GC_TYPE(ref) == IS_OBJECT) {
1511
477k
    zend_object *obj = (zend_object*)ref;
1512
1513
477k
    if (EXPECTED(!(OBJ_FLAGS(ref) & IS_OBJ_FREE_CALLED))) {
1514
477k
      int len;
1515
477k
      zval *table;
1516
1517
      /* optimization: color is GC_BLACK (0) */
1518
477k
      if (!GC_INFO(ref)) {
1519
127k
        gc_add_garbage(ref);
1520
127k
      }
1521
477k
      if (!(OBJ_FLAGS(obj) & IS_OBJ_DESTRUCTOR_CALLED)
1522
404k
       && (obj->handlers->dtor_obj != zend_objects_destroy_object
1523
404k
        || obj->ce->destructor != NULL)) {
1524
1
        *flags |= GC_HAS_DESTRUCTORS;
1525
1
      }
1526
1527
477k
      if (UNEXPECTED(GC_FLAGS(obj) & IS_OBJ_WEAKLY_REFERENCED)) {
1528
3
        zend_weakmap_get_object_entry_gc(obj, &table, &len);
1529
3
        n = len;
1530
3
        zv = table;
1531
6
        for (; n != 0; n--) {
1532
3
          ZEND_ASSERT(Z_TYPE_P(zv) == IS_PTR);
1533
3
          zval *entry = (zval*) Z_PTR_P(zv);
1534
3
          if (Z_COLLECTABLE_P(entry) && GC_FROM_WEAKMAP_KEY(entry)) {
1535
1
            GC_UNSET_FROM_WEAKMAP_KEY(entry);
1536
1
            GC_UNSET_FROM_WEAKMAP(entry);
1537
1
            ref = Z_COUNTED_P(entry);
1538
1
            GC_ADDREF(ref);
1539
1
            if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1540
0
              GC_REF_SET_BLACK(ref);
1541
0
              GC_STACK_PUSH(ref);
1542
0
            }
1543
1
          }
1544
3
          zv++;
1545
3
        }
1546
3
      }
1547
1548
477k
      if (UNEXPECTED(obj->handlers->get_gc == zend_weakmap_get_gc)) {
1549
1
        zend_weakmap_get_entry_gc(obj, &table, &len);
1550
1
        n = len;
1551
1
        zv = table;
1552
3
        for (; n != 0; n--) {
1553
2
          ZEND_ASSERT(Z_TYPE_P(zv) == IS_PTR);
1554
2
          zval *entry = (zval*) Z_PTR_P(zv);
1555
2
          if (Z_COLLECTABLE_P(entry) && GC_FROM_WEAKMAP(entry)) {
1556
2
            GC_UNSET_FROM_WEAKMAP_KEY(entry);
1557
2
            GC_UNSET_FROM_WEAKMAP(entry);
1558
2
            ref = Z_COUNTED_P(entry);
1559
2
            GC_ADDREF(ref);
1560
2
            if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1561
2
              GC_REF_SET_BLACK(ref);
1562
2
              GC_STACK_PUSH(ref);
1563
2
            }
1564
2
          }
1565
2
          zv++;
1566
2
        }
1567
1
        goto next;
1568
1
      }
1569
1570
477k
      ht = obj->handlers->get_gc(obj, &table, &len);
1571
477k
      n = len;
1572
477k
      zv = table;
1573
477k
      if (UNEXPECTED(ht)) {
1574
474k
        GC_ADDREF(ht);
1575
474k
        if (GC_REF_CHECK_COLOR(ht, GC_WHITE)) {
1576
474k
          GC_REF_SET_BLACK(ht);
1577
474k
          if (!GC_INFO(ht)) {
1578
474k
            gc_add_garbage((zend_refcounted *)ht);
1579
474k
          }
1580
647k
          for (; n != 0; n--) {
1581
172k
            if (Z_COLLECTABLE_P(zv)) {
1582
172k
              ref = Z_COUNTED_P(zv);
1583
172k
              GC_ADDREF(ref);
1584
172k
              if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1585
169k
                GC_REF_SET_BLACK(ref);
1586
169k
                GC_STACK_PUSH(ref);
1587
169k
              }
1588
172k
            }
1589
172k
            zv++;
1590
172k
          }
1591
474k
          goto handle_ht;
1592
474k
        }
1593
474k
      }
1594
1595
19.7k
handle_zvals:
1596
142k
      for (; n != 0; n--) {
1597
126k
        if (Z_COLLECTABLE_P(zv)) {
1598
37.6k
          ref = Z_COUNTED_P(zv);
1599
37.6k
          GC_ADDREF(ref);
1600
37.6k
          if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1601
4.17k
            GC_REF_SET_BLACK(ref);
1602
4.17k
            zv++;
1603
6.78k
            while (--n) {
1604
2.61k
              if (Z_COLLECTABLE_P(zv)) {
1605
1.74k
                zend_refcounted *ref = Z_COUNTED_P(zv);
1606
1.74k
                GC_ADDREF(ref);
1607
1.74k
                if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1608
401
                  GC_REF_SET_BLACK(ref);
1609
401
                  GC_STACK_PUSH(ref);
1610
401
                }
1611
1.74k
              }
1612
2.61k
              zv++;
1613
2.61k
            }
1614
4.17k
            goto tail_call;
1615
4.17k
          }
1616
37.6k
        }
1617
122k
        zv++;
1618
122k
      }
1619
19.7k
    }
1620
477k
  } else if (GC_TYPE(ref) == IS_ARRAY) {
1621
    /* optimization: color is GC_BLACK (0) */
1622
348k
    if (!GC_INFO(ref)) {
1623
345k
      gc_add_garbage(ref);
1624
345k
    }
1625
348k
    ht = (zend_array*)ref;
1626
1627
823k
handle_ht:
1628
823k
    n = ht->nNumUsed;
1629
823k
    if (HT_IS_PACKED(ht)) {
1630
17.3k
      zv = ht->arPacked;
1631
17.3k
      goto handle_zvals;
1632
17.3k
    }
1633
1634
806k
    p = ht->arData;
1635
1.52M
    for (; n != 0; n--) {
1636
970k
      zv = &p->val;
1637
970k
      if (Z_TYPE_P(zv) == IS_INDIRECT) {
1638
395k
        zv = Z_INDIRECT_P(zv);
1639
395k
      }
1640
970k
      if (Z_COLLECTABLE_P(zv)) {
1641
446k
        ref = Z_COUNTED_P(zv);
1642
446k
        GC_ADDREF(ref);
1643
446k
        if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1644
256k
          GC_REF_SET_BLACK(ref);
1645
256k
          p++;
1646
1.00M
          while (--n) {
1647
751k
            zv = &p->val;
1648
751k
            if (Z_TYPE_P(zv) == IS_INDIRECT) {
1649
66.1k
              zv = Z_INDIRECT_P(zv);
1650
66.1k
            }
1651
751k
            if (Z_COLLECTABLE_P(zv)) {
1652
590k
              zend_refcounted *ref = Z_COUNTED_P(zv);
1653
590k
              GC_ADDREF(ref);
1654
590k
              if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1655
306k
                GC_REF_SET_BLACK(ref);
1656
306k
                GC_STACK_PUSH(ref);
1657
306k
              }
1658
590k
            }
1659
751k
            p++;
1660
751k
          }
1661
256k
          goto tail_call;
1662
256k
        }
1663
446k
      }
1664
714k
      p++;
1665
714k
    }
1666
806k
  } else if (GC_TYPE(ref) == IS_REFERENCE) {
1667
9.95k
    if (Z_COLLECTABLE(((zend_reference*)ref)->val)) {
1668
8.85k
      ref = Z_COUNTED(((zend_reference*)ref)->val);
1669
8.85k
      GC_ADDREF(ref);
1670
8.85k
      if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1671
1.26k
        GC_REF_SET_BLACK(ref);
1672
1.26k
        goto tail_call;
1673
1.26k
      }
1674
8.85k
    }
1675
9.95k
  }
1676
1677
574k
next:
1678
574k
  ref = GC_STACK_POP();
1679
574k
  if (ref) {
1680
476k
    goto tail_call;
1681
476k
  }
1682
1683
97.8k
  return count;
1684
574k
}
1685
1686
/* Traverse the reference graph from all roots, marking white nodes as garbage. */
1687
static int gc_collect_roots(uint32_t *flags, gc_stack *stack)
1688
3.29k
{
1689
3.29k
  uint32_t idx, end;
1690
3.29k
  zend_refcounted *ref;
1691
3.29k
  int count = 0;
1692
3.29k
  gc_root_buffer *current = GC_IDX2PTR(GC_FIRST_ROOT);
1693
3.29k
  gc_root_buffer *last = GC_IDX2PTR(GC_G(first_unused));
1694
1695
  /* remove non-garbage from the list */
1696
366k
  while (current != last) {
1697
363k
    if (GC_IS_ROOT(current->ref)) {
1698
363k
      if (GC_REF_CHECK_COLOR(current->ref, GC_BLACK)) {
1699
10.0k
        GC_REF_SET_INFO(current->ref, 0); /* reset GC_ADDRESS() and keep GC_BLACK */
1700
10.0k
        gc_remove_from_roots(current);
1701
10.0k
      }
1702
363k
    }
1703
363k
    current++;
1704
363k
  }
1705
1706
3.29k
  gc_compact();
1707
1708
  /* Root buffer might be reallocated during gc_collect_white,
1709
   * make sure to reload pointers. */
1710
3.29k
  idx = GC_FIRST_ROOT;
1711
3.29k
  end = GC_G(first_unused);
1712
356k
  while (idx != end) {
1713
353k
    current = GC_IDX2PTR(idx);
1714
353k
    ref = current->ref;
1715
353k
    ZEND_ASSERT(GC_IS_ROOT(ref));
1716
353k
    current->ref = GC_MAKE_GARBAGE(ref);
1717
353k
    if (GC_REF_CHECK_COLOR(ref, GC_WHITE)) {
1718
97.8k
      GC_REF_SET_BLACK(ref);
1719
97.8k
      count += gc_collect_white(ref, flags, stack);
1720
97.8k
    }
1721
353k
    idx++;
1722
353k
  }
1723
1724
3.29k
  return count;
1725
3.29k
}
1726
1727
static int gc_remove_nested_data_from_buffer(zend_refcounted *ref, gc_root_buffer *root, gc_stack *stack)
1728
1
{
1729
1
  HashTable *ht;
1730
1
  Bucket *p;
1731
1
  zval *zv;
1732
1
  uint32_t n;
1733
1
  int count = 0;
1734
1
  GC_STACK_DCL(stack);
1735
1736
2
tail_call:
1737
2
  if (root) {
1738
1
    root = NULL;
1739
1
    count++;
1740
1
  } else if (GC_REF_ADDRESS(ref) != 0
1741
1
   && GC_REF_CHECK_COLOR(ref, GC_BLACK)) {
1742
0
    GC_TRACE_REF(ref, "removing from buffer");
1743
0
    GC_REMOVE_FROM_BUFFER(ref);
1744
0
    count++;
1745
1
  } else if (GC_TYPE(ref) == IS_REFERENCE) {
1746
0
    if (Z_COLLECTABLE(((zend_reference*)ref)->val)) {
1747
0
      ref = Z_COUNTED(((zend_reference*)ref)->val);
1748
0
      goto tail_call;
1749
0
    }
1750
0
    goto next;
1751
1
  } else {
1752
1
    goto next;
1753
1
  }
1754
1755
1
  if (GC_TYPE(ref) == IS_OBJECT) {
1756
1
    zend_object *obj = (zend_object*)ref;
1757
1758
1
    if (EXPECTED(!(OBJ_FLAGS(ref) & IS_OBJ_FREE_CALLED))) {
1759
1
      int len;
1760
1
      zval *table;
1761
1762
1
      if (UNEXPECTED(GC_FLAGS(obj) & IS_OBJ_WEAKLY_REFERENCED)) {
1763
0
        zend_weakmap_get_object_entry_gc(obj, &table, &len);
1764
0
        n = len;
1765
0
        zv = table;
1766
0
        for (; n != 0; n--) {
1767
0
          ZEND_ASSERT(Z_TYPE_P(zv) == IS_PTR);
1768
0
          zval *entry = (zval*) Z_PTR_P(zv);
1769
0
          if (Z_OPT_COLLECTABLE_P(entry)) {
1770
0
            ref = Z_COUNTED_P(entry);
1771
0
            GC_STACK_PUSH(ref);
1772
0
          }
1773
0
          zv++;
1774
0
        }
1775
0
      }
1776
1777
1
      ht = obj->handlers->get_gc(obj, &table, &len);
1778
1
      n = len;
1779
1
      zv = table;
1780
1
      if (UNEXPECTED(ht)) {
1781
1
        for (; n != 0; n--) {
1782
0
          if (Z_COLLECTABLE_P(zv)) {
1783
0
            ref = Z_COUNTED_P(zv);
1784
0
            GC_STACK_PUSH(ref);
1785
0
          }
1786
0
          zv++;
1787
0
        }
1788
1
        if (GC_REF_ADDRESS(ht) != 0 && GC_REF_CHECK_COLOR(ht, GC_BLACK)) {
1789
1
          GC_TRACE_REF(ht, "removing from buffer");
1790
1
          GC_REMOVE_FROM_BUFFER(ht);
1791
1
        }
1792
1
        goto handle_ht;
1793
1
      }
1794
1795
0
handle_zvals:
1796
0
      for (; n != 0; n--) {
1797
0
        if (Z_COLLECTABLE_P(zv)) {
1798
0
          ref = Z_COUNTED_P(zv);
1799
0
          zv++;
1800
0
          while (--n) {
1801
0
            if (Z_COLLECTABLE_P(zv)) {
1802
0
              zend_refcounted *ref = Z_COUNTED_P(zv);
1803
0
              GC_STACK_PUSH(ref);
1804
0
            }
1805
0
            zv++;
1806
0
          }
1807
0
          goto tail_call;
1808
0
        }
1809
0
        zv++;
1810
0
      }
1811
0
    }
1812
1
  } else if (GC_TYPE(ref) == IS_ARRAY) {
1813
0
    ht = (zend_array*)ref;
1814
1815
1
handle_ht:
1816
1
    n = ht->nNumUsed;
1817
1
    if (HT_IS_PACKED(ht)) {
1818
0
      zv = ht->arPacked;
1819
0
      goto handle_zvals;
1820
0
    }
1821
1822
1
    p = ht->arData;
1823
1
    for (; n != 0; n--) {
1824
1
      zv = &p->val;
1825
1
      if (Z_TYPE_P(zv) == IS_INDIRECT) {
1826
1
        zv = Z_INDIRECT_P(zv);
1827
1
      }
1828
1
      if (Z_COLLECTABLE_P(zv)) {
1829
1
        ref = Z_COUNTED_P(zv);
1830
1
        p++;
1831
1
        while (--n) {
1832
0
          zv = &p->val;
1833
0
          if (Z_TYPE_P(zv) == IS_INDIRECT) {
1834
0
            zv = Z_INDIRECT_P(zv);
1835
0
          }
1836
0
          if (Z_COLLECTABLE_P(zv)) {
1837
0
            zend_refcounted *ref = Z_COUNTED_P(zv);
1838
0
            GC_STACK_PUSH(ref);
1839
0
          }
1840
0
          p++;
1841
0
        }
1842
1
        goto tail_call;
1843
1
      }
1844
0
      p++;
1845
0
    }
1846
1
  }
1847
1848
1
next:
1849
1
  ref = GC_STACK_POP();
1850
1
  if (ref) {
1851
0
    goto tail_call;
1852
0
  }
1853
1854
1
  return count;
1855
1
}
1856
1857
static void zend_get_gc_buffer_release(void);
1858
static void zend_gc_check_root_tmpvars(void);
1859
static void zend_gc_remove_root_tmpvars(void);
1860
1861
static zend_internal_function gc_destructor_fiber;
1862
1863
ZEND_NORETURN static ZEND_COLD void gc_create_destructor_fiber_error(void)
1864
0
{
1865
0
  zend_error_noreturn(E_ERROR, "Unable to create destructor fiber");
1866
0
}
1867
1868
ZEND_NORETURN static ZEND_COLD void gc_start_destructor_fiber_error(void)
1869
0
{
1870
0
  zend_error_noreturn(E_ERROR, "Unable to start destructor fiber");
1871
0
}
1872
1873
/* Call destructors for garbage in the buffer. */
1874
static zend_always_inline zend_result gc_call_destructors(uint32_t idx, uint32_t end, zend_fiber *fiber)
1875
1
{
1876
1
  gc_root_buffer *current;
1877
1
  zend_refcounted *p;
1878
1879
  /* The root buffer might be reallocated during destructors calls,
1880
   * make sure to reload pointers as necessary. */
1881
3
  while (idx != end) {
1882
2
    current = GC_IDX2PTR(idx);
1883
2
    if (GC_IS_DTOR_GARBAGE(current->ref)) {
1884
1
      p = GC_GET_PTR(current->ref);
1885
      /* Mark this is as a normal root for the next GC run */
1886
1
      current->ref = p;
1887
      /* Double check that the destructor hasn't been called yet. It
1888
       * could have already been invoked indirectly by some other
1889
       * destructor. */
1890
1
      if (!(OBJ_FLAGS(p) & IS_OBJ_DESTRUCTOR_CALLED)) {
1891
1
        if (fiber != NULL) {
1892
0
          GC_G(dtor_idx) = idx;
1893
0
        }
1894
1
        zend_object *obj = (zend_object*)p;
1895
1
        GC_TRACE_REF(obj, "calling destructor");
1896
1
        GC_ADD_FLAGS(obj, IS_OBJ_DESTRUCTOR_CALLED);
1897
1
        GC_ADDREF(obj);
1898
1
        obj->handlers->dtor_obj(obj);
1899
1
        GC_TRACE_REF(obj, "returned from destructor");
1900
1
        GC_DELREF(obj);
1901
1
        if (UNEXPECTED(fiber != NULL && GC_G(dtor_fiber) != fiber)) {
1902
          /* We resumed after suspension */
1903
0
          gc_check_possible_root((zend_refcounted*)&obj->gc);
1904
0
          return FAILURE;
1905
0
        }
1906
1
      }
1907
1
    }
1908
2
    idx++;
1909
2
  }
1910
1911
1
  return SUCCESS;
1912
1
}
1913
1914
static zend_fiber *gc_create_destructor_fiber(void)
1915
0
{
1916
0
  zval zobj;
1917
0
  zend_fiber *fiber;
1918
1919
0
  GC_TRACE("starting destructor fiber");
1920
1921
0
  if (UNEXPECTED(object_init_ex(&zobj, zend_ce_fiber) == FAILURE)) {
1922
0
    gc_create_destructor_fiber_error();
1923
0
  }
1924
1925
0
  fiber = (zend_fiber *)Z_OBJ(zobj);
1926
0
  fiber->fci.size = sizeof(fiber->fci);
1927
0
  fiber->fci_cache.function_handler = (zend_function*) &gc_destructor_fiber;
1928
1929
0
  GC_G(dtor_fiber) = fiber;
1930
1931
0
  if (UNEXPECTED(zend_fiber_start(fiber, NULL) == FAILURE)) {
1932
0
    gc_start_destructor_fiber_error();
1933
0
  }
1934
1935
0
  return fiber;
1936
0
}
1937
1938
static void remember_prev_exception(zend_object **prev_exception)
1939
0
{
1940
0
  if (EG(exception)) {
1941
0
    if (*prev_exception) {
1942
0
      zend_exception_set_previous(EG(exception), *prev_exception);
1943
0
    }
1944
0
    *prev_exception = EG(exception);
1945
0
    EG(exception) = NULL;
1946
0
  }
1947
0
}
1948
1949
static zend_never_inline void gc_call_destructors_in_fiber(void)
1950
0
{
1951
0
  ZEND_ASSERT(!GC_G(dtor_fiber_running));
1952
1953
0
  zend_fiber *fiber = GC_G(dtor_fiber);
1954
1955
0
  GC_G(dtor_idx) = GC_FIRST_ROOT;
1956
0
  GC_G(dtor_end) = GC_G(first_unused);
1957
1958
0
  zend_object *exception = NULL;
1959
0
  const zend_op *opline_before_exception = EG(opline_before_exception);
1960
0
  remember_prev_exception(&exception);
1961
0
  zend_object *old_exception = exception;
1962
1963
0
  if (UNEXPECTED(!fiber)) {
1964
0
    fiber = gc_create_destructor_fiber();
1965
0
  } else {
1966
0
    zend_fiber_resume(fiber, NULL, NULL);
1967
0
  }
1968
1969
0
  remember_prev_exception(&exception);
1970
1971
0
  for (;;) {
1972
    /* At this point, fiber has executed until suspension */
1973
0
    GC_TRACE("resumed from destructor fiber");
1974
1975
0
    if (UNEXPECTED(GC_G(dtor_fiber_running))) {
1976
      /* Fiber was suspended by a destructor. Start a new one for the
1977
       * remaining destructors. */
1978
0
      GC_TRACE("destructor fiber suspended by destructor");
1979
0
      GC_G(dtor_fiber) = NULL;
1980
0
      GC_G(dtor_idx)++;
1981
      /* We do not own the fiber anymore. It may be collected if the
1982
       * application does not reference it. */
1983
0
      zend_object_release(&fiber->std);
1984
0
      remember_prev_exception(&exception);
1985
0
      fiber = gc_create_destructor_fiber();
1986
0
      remember_prev_exception(&exception);
1987
0
      continue;
1988
0
    } else {
1989
      /* Fiber suspended itself after calling all destructors */
1990
0
      GC_TRACE("destructor fiber suspended itself");
1991
0
      break;
1992
0
    }
1993
0
  }
1994
1995
0
  EG(exception) = exception;
1996
0
  EG(opline_before_exception) = opline_before_exception;
1997
1998
  /* Destructors ran in another fiber, out of reach of zend_call_function()'s rethrow */
1999
0
  if (exception && !old_exception && EG(current_execute_data) && EG(current_execute_data)->func
2000
0
      && ZEND_USER_CODE(EG(current_execute_data)->func->common.type)) {
2001
0
    zend_rethrow_exception(EG(current_execute_data));
2002
0
  }
2003
0
}
2004
2005
/* Perform a garbage collection run. The default implementation of gc_collect_cycles. */
2006
ZEND_API int zend_gc_collect_cycles(void)
2007
884k
{
2008
884k
  int total_count = 0;
2009
884k
  bool should_rerun_gc = false;
2010
884k
  bool did_rerun_gc = false;
2011
2012
884k
  zend_hrtime_t start_time = zend_hrtime();
2013
884k
  if (GC_G(num_roots) && !GC_G(gc_active)) {
2014
3.29k
    zend_gc_remove_root_tmpvars();
2015
3.29k
  }
2016
2017
884k
rerun_gc:
2018
884k
  if (GC_G(num_roots)) {
2019
3.29k
    int count;
2020
3.29k
    gc_root_buffer *current, *last;
2021
3.29k
    zend_refcounted *p;
2022
3.29k
    uint32_t gc_flags = 0;
2023
3.29k
    uint32_t idx, end;
2024
3.29k
    gc_stack stack;
2025
2026
3.29k
    stack.prev = NULL;
2027
3.29k
    stack.next = NULL;
2028
2029
3.29k
    if (GC_G(gc_active)) {
2030
0
      GC_G(collector_time) += zend_hrtime() - start_time;
2031
0
      return 0;
2032
0
    }
2033
2034
3.29k
    GC_TRACE("Collecting cycles");
2035
3.29k
    GC_G(gc_runs)++;
2036
3.29k
    GC_G(gc_active) = 1;
2037
2038
3.29k
    GC_TRACE("Marking roots");
2039
3.29k
    gc_mark_roots(&stack);
2040
3.29k
    GC_TRACE("Scanning roots");
2041
3.29k
    gc_scan_roots(&stack);
2042
2043
3.29k
    GC_TRACE("Collecting roots");
2044
3.29k
    count = gc_collect_roots(&gc_flags, &stack);
2045
2046
3.29k
    if (!GC_G(num_roots)) {
2047
      /* nothing to free */
2048
625
      GC_TRACE("Nothing to free");
2049
625
      gc_stack_free(&stack);
2050
625
      GC_G(gc_active) = 0;
2051
625
      goto finish;
2052
625
    }
2053
2054
2.67k
    end = GC_G(first_unused);
2055
2056
2.67k
    if (gc_flags & GC_HAS_DESTRUCTORS) {
2057
1
      GC_TRACE("Calling destructors");
2058
2059
      /* During a destructor call, new externally visible references to nested data may
2060
       * be introduced. These references can be introduced in a way that does not
2061
       * modify any refcounts, so we have no real way to detect this situation
2062
       * short of rerunning full GC tracing. What we do instead is to only run
2063
       * destructors at this point and automatically re-run GC afterwards. */
2064
1
      should_rerun_gc = true;
2065
2066
      /* Mark all roots for which a dtor will be invoked as DTOR_GARBAGE. Additionally
2067
       * color them purple. This serves a double purpose: First, they should be
2068
       * considered new potential roots for the next GC run. Second, it will prevent
2069
       * their removal from the root buffer by nested data removal. */
2070
1
      idx = GC_FIRST_ROOT;
2071
1
      current = GC_IDX2PTR(GC_FIRST_ROOT);
2072
3
      while (idx != end) {
2073
2
        if (GC_IS_GARBAGE(current->ref)) {
2074
2
          p = GC_GET_PTR(current->ref);
2075
2
          if (GC_TYPE(p) == IS_OBJECT && !(OBJ_FLAGS(p) & IS_OBJ_DESTRUCTOR_CALLED)) {
2076
1
            zend_object *obj = (zend_object *) p;
2077
1
            if (obj->handlers->dtor_obj != zend_objects_destroy_object
2078
1
              || obj->ce->destructor) {
2079
1
              current->ref = GC_MAKE_DTOR_GARBAGE(obj);
2080
1
              GC_REF_SET_COLOR(obj, GC_PURPLE);
2081
1
            } else {
2082
0
              GC_ADD_FLAGS(obj, IS_OBJ_DESTRUCTOR_CALLED);
2083
0
            }
2084
1
          }
2085
2
        }
2086
2
        current++;
2087
2
        idx++;
2088
2
      }
2089
2090
      /* Remove nested data for objects on which a destructor will be called.
2091
       * This will not remove the objects themselves, as they have been colored
2092
       * purple. */
2093
1
      idx = GC_FIRST_ROOT;
2094
1
      current = GC_IDX2PTR(GC_FIRST_ROOT);
2095
3
      while (idx != end) {
2096
2
        if (GC_IS_DTOR_GARBAGE(current->ref)) {
2097
1
          p = GC_GET_PTR(current->ref);
2098
1
          count -= gc_remove_nested_data_from_buffer(p, current, &stack);
2099
1
        }
2100
2
        current++;
2101
2
        idx++;
2102
2
      }
2103
2104
      /* Actually call destructors. */
2105
1
      zend_hrtime_t dtor_start_time = zend_hrtime();
2106
1
      if (EXPECTED(!EG(active_fiber))) {
2107
1
        gc_call_destructors(GC_FIRST_ROOT, end, NULL);
2108
1
      } else {
2109
0
        gc_call_destructors_in_fiber();
2110
0
      }
2111
1
      GC_G(dtor_time) += zend_hrtime() - dtor_start_time;
2112
2113
1
      if (GC_G(gc_protected)) {
2114
        /* something went wrong */
2115
0
        zend_get_gc_buffer_release();
2116
0
        GC_G(collector_time) += zend_hrtime() - start_time;
2117
0
        return 0;
2118
0
      }
2119
1
    }
2120
2121
2.67k
    gc_stack_free(&stack);
2122
2123
    /* Destroy zvals. The root buffer may be reallocated. */
2124
2.67k
    GC_TRACE("Destroying zvals");
2125
2.67k
    zend_hrtime_t free_start_time = zend_hrtime();
2126
2.67k
    idx = GC_FIRST_ROOT;
2127
1.30M
    while (idx != end) {
2128
1.30M
      current = GC_IDX2PTR(idx);
2129
1.30M
      if (GC_IS_GARBAGE(current->ref)) {
2130
103k
        p = GC_GET_PTR(current->ref);
2131
103k
        GC_TRACE_REF(p, "destroying");
2132
103k
        if (GC_TYPE(p) == IS_OBJECT) {
2133
102k
          zend_object *obj = (zend_object*)p;
2134
2135
102k
          EG(objects_store).object_buckets[obj->handle] = SET_OBJ_INVALID(obj);
2136
102k
          GC_TYPE_INFO(obj) = GC_NULL |
2137
102k
            (GC_TYPE_INFO(obj) & ~GC_TYPE_MASK);
2138
          /* Modify current before calling free_obj (bug #78811: free_obj() can cause the root buffer (with current) to be reallocated.) */
2139
102k
          current->ref = GC_MAKE_GARBAGE(((char*)obj) - obj->handlers->offset);
2140
102k
          if (!(OBJ_FLAGS(obj) & IS_OBJ_FREE_CALLED)) {
2141
102k
            GC_ADD_FLAGS(obj, IS_OBJ_FREE_CALLED);
2142
102k
            GC_ADDREF(obj);
2143
102k
            obj->handlers->free_obj(obj);
2144
102k
            GC_DELREF(obj);
2145
102k
          }
2146
2147
102k
          ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST(obj->handle);
2148
102k
        } else if (GC_TYPE(p) == IS_ARRAY) {
2149
1.26k
          zend_array *arr = (zend_array*)p;
2150
2151
1.26k
          GC_TYPE_INFO(arr) = GC_NULL |
2152
1.26k
            (GC_TYPE_INFO(arr) & ~GC_TYPE_MASK);
2153
2154
          /* GC may destroy arrays with rc>1. This is valid and safe. */
2155
1.26k
          HT_ALLOW_COW_VIOLATION(arr);
2156
2157
1.26k
          zend_hash_destroy(arr);
2158
1.26k
        }
2159
103k
      }
2160
1.30M
      idx++;
2161
1.30M
    }
2162
2163
    /* Free objects */
2164
2.67k
    current = GC_IDX2PTR(GC_FIRST_ROOT);
2165
2.67k
    last = GC_IDX2PTR(end);
2166
1.30M
    while (current != last) {
2167
1.30M
      if (GC_IS_GARBAGE(current->ref)) {
2168
103k
        p = GC_GET_PTR(current->ref);
2169
103k
        GC_LINK_UNUSED(current);
2170
103k
        GC_G(num_roots)--;
2171
103k
        efree(p);
2172
103k
      }
2173
1.30M
      current++;
2174
1.30M
    }
2175
2176
2.67k
    GC_G(free_time) += zend_hrtime() - free_start_time;
2177
2178
2.67k
    GC_TRACE("Collection finished");
2179
2.67k
    GC_G(collected) += count;
2180
2.67k
    total_count += count;
2181
2.67k
    GC_G(gc_active) = 0;
2182
2.67k
  }
2183
2184
884k
  gc_compact();
2185
2186
  /* Objects with destructors were removed from this GC run. Rerun GC right away to clean them
2187
   * up. We do this only once: If we encounter more destructors on the second run, we'll not
2188
   * run GC another time. */
2189
884k
  if (should_rerun_gc && !did_rerun_gc) {
2190
1
    did_rerun_gc = true;
2191
1
    goto rerun_gc;
2192
1
  }
2193
2194
884k
finish:
2195
884k
  zend_get_gc_buffer_release();
2196
2197
  /* Prevent GC from running during zend_gc_check_root_tmpvars, before
2198
   * gc_threshold is adjusted, as this may result in unbounded recursion */
2199
884k
  GC_G(gc_active) = 1;
2200
884k
  zend_gc_check_root_tmpvars();
2201
884k
  GC_G(gc_active) = 0;
2202
2203
884k
  GC_G(collector_time) += zend_hrtime() - start_time;
2204
884k
  return total_count;
2205
884k
}
2206
2207
ZEND_API void zend_gc_get_status(zend_gc_status *status)
2208
0
{
2209
0
  status->active = GC_G(gc_active);
2210
0
  status->gc_protected = GC_G(gc_protected);
2211
0
  status->full = GC_G(gc_full);
2212
0
  status->runs = GC_G(gc_runs);
2213
0
  status->collected = GC_G(collected);
2214
0
  status->threshold = GC_G(gc_threshold);
2215
0
  status->buf_size = GC_G(buf_size);
2216
0
  status->num_roots = GC_G(num_roots);
2217
0
  status->application_time = zend_hrtime() - GC_G(activated_at);
2218
0
  status->collector_time = GC_G(collector_time);
2219
0
  status->dtor_time = GC_G(dtor_time);
2220
0
  status->free_time = GC_G(free_time);
2221
0
}
2222
2223
86.4k
ZEND_API zend_get_gc_buffer *zend_get_gc_buffer_create(void) {
2224
  /* There can only be one get_gc() call active at a time,
2225
   * so there only needs to be one buffer. */
2226
86.4k
  zend_get_gc_buffer *gc_buffer = &EG(get_gc_buffer);
2227
86.4k
  gc_buffer->cur = gc_buffer->start;
2228
86.4k
  return gc_buffer;
2229
86.4k
}
2230
2231
132
ZEND_API void zend_get_gc_buffer_grow(zend_get_gc_buffer *gc_buffer) {
2232
132
  size_t old_capacity = gc_buffer->end - gc_buffer->start;
2233
132
  size_t new_capacity = old_capacity == 0 ? 64 : old_capacity * 2;
2234
132
  gc_buffer->start = erealloc(gc_buffer->start, new_capacity * sizeof(zval));
2235
132
  gc_buffer->end = gc_buffer->start + new_capacity;
2236
132
  gc_buffer->cur = gc_buffer->start + old_capacity;
2237
132
}
2238
2239
884k
static void zend_get_gc_buffer_release(void) {
2240
884k
  zend_get_gc_buffer *gc_buffer = &EG(get_gc_buffer);
2241
884k
  efree(gc_buffer->start);
2242
884k
  gc_buffer->start = gc_buffer->end = gc_buffer->cur = NULL;
2243
884k
}
2244
2245
/* TMPVAR operands are destroyed using zval_ptr_dtor_nogc(), because they usually cannot contain
2246
 * cycles. However, there are some rare exceptions where this is possible, in which case we rely
2247
 * on the producing code to root the value. If a GC run occurs between the rooting and consumption
2248
 * of the value, we would end up leaking it. To avoid this, root all live TMPVAR values here. */
2249
884k
static void zend_gc_check_root_tmpvars(void) {
2250
884k
  zend_execute_data *ex = EG(current_execute_data);
2251
1.14M
  for (; ex; ex = ex->prev_execute_data) {
2252
259k
    zend_function *func = ex->func;
2253
259k
    if (!func || !ZEND_USER_CODE(func->type)) {
2254
259k
      continue;
2255
259k
    }
2256
2257
17
    uint32_t op_num = ex->opline - ex->func->op_array.opcodes;
2258
45
    for (uint32_t i = 0; i < func->op_array.last_live_range; i++) {
2259
28
      const zend_live_range *range = &func->op_array.live_range[i];
2260
28
      if (range->start > op_num) {
2261
0
        break;
2262
0
      }
2263
28
      if (range->end <= op_num) {
2264
26
        continue;
2265
26
      }
2266
2267
2
      uint32_t kind = range->var & ZEND_LIVE_MASK;
2268
2
      if (kind == ZEND_LIVE_TMPVAR || kind == ZEND_LIVE_LOOP) {
2269
2
        uint32_t var_num = range->var & ~ZEND_LIVE_MASK;
2270
2
        zval *var = ZEND_CALL_VAR(ex, var_num);
2271
2
        if (Z_COLLECTABLE_P(var)) {
2272
2
          gc_check_possible_root(Z_COUNTED_P(var));
2273
2
        }
2274
2
      }
2275
2
    }
2276
17
  }
2277
884k
}
2278
2279
3.29k
static void zend_gc_remove_root_tmpvars(void) {
2280
3.29k
  zend_execute_data *ex = EG(current_execute_data);
2281
5.91k
  for (; ex; ex = ex->prev_execute_data) {
2282
2.62k
    zend_function *func = ex->func;
2283
2.62k
    if (!func || !ZEND_USER_CODE(func->type)) {
2284
2.61k
      continue;
2285
2.61k
    }
2286
2287
10
    uint32_t op_num = ex->opline - ex->func->op_array.opcodes;
2288
32
    for (uint32_t i = 0; i < func->op_array.last_live_range; i++) {
2289
22
      const zend_live_range *range = &func->op_array.live_range[i];
2290
22
      if (range->start > op_num) {
2291
0
        break;
2292
0
      }
2293
22
      if (range->end <= op_num) {
2294
21
        continue;
2295
21
      }
2296
2297
1
      uint32_t kind = range->var & ZEND_LIVE_MASK;
2298
1
      if (kind == ZEND_LIVE_TMPVAR || kind == ZEND_LIVE_LOOP) {
2299
1
        uint32_t var_num = range->var & ~ZEND_LIVE_MASK;
2300
1
        zval *var = ZEND_CALL_VAR(ex, var_num);
2301
1
        if (Z_COLLECTABLE_P(var)) {
2302
1
          GC_REMOVE_FROM_BUFFER(Z_COUNTED_P(var));
2303
1
        }
2304
1
      }
2305
1
    }
2306
10
  }
2307
3.29k
}
2308
2309
#if GC_BENCH
2310
void gc_bench_print(void)
2311
{
2312
  fprintf(stderr, "GC Statistics\n");
2313
  fprintf(stderr, "-------------\n");
2314
  fprintf(stderr, "Runs:               %d\n", GC_G(gc_runs));
2315
  fprintf(stderr, "Collected:          %d\n", GC_G(collected));
2316
  fprintf(stderr, "Root buffer length: %d\n", GC_G(root_buf_length));
2317
  fprintf(stderr, "Root buffer peak:   %d\n\n", GC_G(root_buf_peak));
2318
  fprintf(stderr, "      Possible            Remove from  Marked\n");
2319
  fprintf(stderr, "        Root    Buffered     buffer     grey\n");
2320
  fprintf(stderr, "      --------  --------  -----------  ------\n");
2321
  fprintf(stderr, "ZVAL  %8d  %8d  %9d  %8d\n", GC_G(zval_possible_root), GC_G(zval_buffered), GC_G(zval_remove_from_buffer), GC_G(zval_marked_grey));
2322
}
2323
#endif
2324
2325
#ifdef ZTS
2326
size_t zend_gc_globals_size(void)
2327
{
2328
  return sizeof(zend_gc_globals);
2329
}
2330
#endif
2331
2332
static ZEND_FUNCTION(gc_destructor_fiber)
2333
0
{
2334
0
  uint32_t idx, end;
2335
2336
0
  zend_fiber *fiber = GC_G(dtor_fiber);
2337
0
  ZEND_ASSERT(fiber != NULL);
2338
0
  ZEND_ASSERT(fiber == EG(active_fiber));
2339
2340
0
  for (;;) {
2341
0
    GC_G(dtor_fiber_running) = true;
2342
2343
0
    idx = GC_G(dtor_idx);
2344
0
    end = GC_G(dtor_end);
2345
0
    if (UNEXPECTED(gc_call_destructors(idx, end, fiber) == FAILURE)) {
2346
      /* We resumed after being suspended by a destructor */
2347
0
      return;
2348
0
    }
2349
2350
    /* We have called all destructors. Suspend fiber until the next GC run
2351
     */
2352
0
    GC_G(dtor_fiber_running) = false;
2353
0
    zend_fiber_suspend(fiber, NULL, NULL);
2354
2355
0
    if (UNEXPECTED(fiber->flags & ZEND_FIBER_FLAG_DESTROYED)) {
2356
      /* Fiber is being destroyed by shutdown sequence */
2357
0
      if (GC_G(dtor_fiber) == fiber) {
2358
0
        GC_G(dtor_fiber) = NULL;
2359
0
      }
2360
0
      GC_DELREF(&fiber->std);
2361
0
      gc_check_possible_root((zend_refcounted*)&fiber->std.gc);
2362
0
      return;
2363
0
    }
2364
0
  }
2365
0
}
2366
2367
static zend_internal_function gc_destructor_fiber = {
2368
  .type = ZEND_INTERNAL_FUNCTION,
2369
  .fn_flags = ZEND_ACC_PUBLIC,
2370
  .handler = ZEND_FN(gc_destructor_fiber),
2371
};
2372
2373
void gc_init(void)
2374
16
{
2375
16
  gc_destructor_fiber.function_name = zend_string_init_interned(
2376
16
      "gc_destructor_fiber",
2377
16
      strlen("gc_destructor_fiber"),
2378
      true);
2379
16
}