• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ivmai / bdwgc / 1490

28 Apr 2023 10:30AM UTC coverage: 72.923% (+0.001%) from 72.922%
1490

push

travis-ci-com

ivmai
Fix missing extern C for __asan_default_options
(fix of commit 84b695d01)

Issue #206 (bdwgc).

* os_dep.c [ADDRESS_SANITIZER && (UNIX_LIKE || NEED_FIND_LIMIT
|| MPROTECT_VDB) && !CUSTOM_ASAN_DEF_OPTIONS] (__asan_default_options):
Add the declaration wrapped into EXTERN_C_BEGIN.

7231 of 9916 relevant lines covered (72.92%)

11031094.35 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

74.75
/alloc.c
1
/*
2
 * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3
 * Copyright (c) 1991-1996 by Xerox Corporation.  All rights reserved.
4
 * Copyright (c) 1998 by Silicon Graphics.  All rights reserved.
5
 * Copyright (c) 1999-2004 Hewlett-Packard Development Company, L.P.
6
 * Copyright (c) 2008-2021 Ivan Maidanski
7
 *
8
 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
9
 * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
10
 *
11
 * Permission is hereby granted to use or copy this program
12
 * for any purpose,  provided the above notices are retained on all copies.
13
 * Permission to modify the code and to distribute modified code is granted,
14
 * provided the above notices are retained, and a notice that the code was
15
 * modified is included with the above copyright notice.
16
 *
17
 */
18

19
#include "private/gc_priv.h"
20

21
#include <stdio.h>
22
#if !defined(MACOS) && !defined(MSWINCE)
23
# include <signal.h>
24
# if !defined(GC_NO_TYPES) && !defined(SN_TARGET_PSP2) \
25
     && !defined(__CC_ARM)
26
#   include <sys/types.h>
27
# endif
28
#endif
29

30
/*
31
 * Separate free lists are maintained for different sized objects
32
 * up to MAXOBJBYTES.
33
 * The call GC_allocobj(i,k) ensures that the freelist for
34
 * kind k objects of size i points to a non-empty
35
 * free list. It returns a pointer to the first entry on the free list.
36
 * In a single-threaded world, GC_allocobj may be called to allocate
37
 * an object of small size lb (and NORMAL kind) as follows
38
 * (GC_generic_malloc_inner is a wrapper over GC_allocobj which also
39
 * fills in GC_size_map if needed):
40
 *
41
 *   lg = GC_size_map[lb];
42
 *   op = GC_objfreelist[lg];
43
 *   if (NULL == op) {
44
 *     op = GC_generic_malloc_inner(lb, NORMAL);
45
 *   } else {
46
 *     GC_objfreelist[lg] = obj_link(op);
47
 *     GC_bytes_allocd += GRANULES_TO_BYTES((word)lg);
48
 *   }
49
 *
50
 * Note that this is very fast if the free list is non-empty; it should
51
 * only involve the execution of 4 or 5 simple instructions.
52
 * All composite objects on freelists are cleared, except for
53
 * their first word.
54
 */
55

56
/*
57
 * The allocator uses GC_allochblk to allocate large chunks of objects.
58
 * These chunks all start on addresses which are multiples of
59
 * HBLKSZ.   Each allocated chunk has an associated header,
60
 * which can be located quickly based on the address of the chunk.
61
 * (See headers.c for details.)
62
 * This makes it possible to check quickly whether an
63
 * arbitrary address corresponds to an object administered by the
64
 * allocator.
65
 */
66

67
word GC_non_gc_bytes = 0;  /* Number of bytes not intended to be collected */
68

69
word GC_gc_no = 0;
70

71
#ifndef NO_CLOCK
72
  static unsigned long full_gc_total_time = 0; /* in ms, may wrap */
73
  static unsigned full_gc_total_ns_frac = 0; /* fraction of 1 ms */
74
  static GC_bool measure_performance = FALSE;
75
                /* Do performance measurements if set to true (e.g.,    */
76
                /* accumulation of the total time of full collections). */
77

78
  GC_API void GC_CALL GC_start_performance_measurement(void)
2✔
79
  {
80
    measure_performance = TRUE;
2✔
81
  }
2✔
82

83
  GC_API unsigned long GC_CALL GC_get_full_gc_total_time(void)
2✔
84
  {
85
    return full_gc_total_time;
2✔
86
  }
87
#endif /* !NO_CLOCK */
88

89
#ifndef GC_DISABLE_INCREMENTAL
90
  GC_INNER GC_bool GC_incremental = FALSE; /* By default, stop the world. */
91
  STATIC GC_bool GC_should_start_incremental_collection = FALSE;
92
#endif
93

94
GC_API int GC_CALL GC_is_incremental_mode(void)
22✔
95
{
96
  return (int)GC_incremental;
22✔
97
}
98

99
#ifdef THREADS
100
  int GC_parallel = FALSE;      /* By default, parallel GC is off.      */
101
#endif
102

103
#if defined(GC_FULL_FREQ) && !defined(CPPCHECK)
104
  int GC_full_freq = GC_FULL_FREQ;
105
#else
106
  int GC_full_freq = 19;   /* Every 20th collection is a full   */
107
                           /* collection, whether we need it    */
108
                           /* or not.                           */
109
#endif
110

111
STATIC GC_bool GC_need_full_gc = FALSE;
112
                           /* Need full GC due to heap growth.  */
113

114
#ifdef THREAD_LOCAL_ALLOC
115
  GC_INNER GC_bool GC_world_stopped = FALSE;
116
#endif
117

118
STATIC GC_bool GC_disable_automatic_collection = FALSE;
119

120
GC_API void GC_CALL GC_set_disable_automatic_collection(int value)
2✔
121
{
122
  DCL_LOCK_STATE;
123

124
  LOCK();
2✔
125
  GC_disable_automatic_collection = (GC_bool)value;
2✔
126
  UNLOCK();
2✔
127
}
2✔
128

129
GC_API int GC_CALL GC_get_disable_automatic_collection(void)
2✔
130
{
131
  int value;
132
  DCL_LOCK_STATE;
133

134
  LOCK();
2✔
135
  value = (int)GC_disable_automatic_collection;
2✔
136
  UNLOCK();
2✔
137
  return value;
2✔
138
}
139

140
STATIC word GC_used_heap_size_after_full = 0;
141

142
/* GC_copyright symbol is externally visible. */
143
EXTERN_C_BEGIN
144
extern const char * const GC_copyright[];
145
EXTERN_C_END
146
const char * const GC_copyright[] =
147
{"Copyright 1988, 1989 Hans-J. Boehm and Alan J. Demers ",
148
"Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved. ",
149
"Copyright (c) 1996-1998 by Silicon Graphics.  All rights reserved. ",
150
"Copyright (c) 1999-2009 by Hewlett-Packard Company.  All rights reserved. ",
151
"Copyright (c) 2008-2021 Ivan Maidanski ",
152
"THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
153
" EXPRESSED OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.",
154
"See source code for details." };
155

156
/* Version macros are now defined in gc_version.h, which is included by */
157
/* gc.h, which is included by gc_priv.h.                                */
158
#ifndef GC_NO_VERSION_VAR
159
  EXTERN_C_BEGIN
160
  extern const unsigned GC_version;
161
  EXTERN_C_END
162
  const unsigned GC_version = ((GC_VERSION_MAJOR << 16) |
163
                        (GC_VERSION_MINOR << 8) | GC_VERSION_MICRO);
164
#endif
165

166
GC_API unsigned GC_CALL GC_get_version(void)
2✔
167
{
168
  return (GC_VERSION_MAJOR << 16) | (GC_VERSION_MINOR << 8) |
2✔
169
          GC_VERSION_MICRO;
170
}
171

172
/* some more variables */
173

174
#ifdef GC_DONT_EXPAND
175
  int GC_dont_expand = TRUE;
176
#else
177
  int GC_dont_expand = FALSE;
178
#endif
179

180
#if defined(GC_FREE_SPACE_DIVISOR) && !defined(CPPCHECK)
181
  word GC_free_space_divisor = GC_FREE_SPACE_DIVISOR; /* must be > 0 */
182
#else
183
  word GC_free_space_divisor = 3;
184
#endif
185

186
GC_INNER int GC_CALLBACK GC_never_stop_func(void)
4,652,323✔
187
{
188
  return(0);
4,652,323✔
189
}
190

191
#if defined(GC_TIME_LIMIT) && !defined(CPPCHECK)
192
  unsigned long GC_time_limit = GC_TIME_LIMIT;
193
                           /* We try to keep pause times from exceeding  */
194
                           /* this by much. In milliseconds.             */
195
#elif defined(PARALLEL_MARK)
196
  unsigned long GC_time_limit = GC_TIME_UNLIMITED;
197
                        /* The parallel marker cannot be interrupted for */
198
                        /* now, so the time limit is absent by default.  */
199
#else
200
  unsigned long GC_time_limit = 50;
201
#endif
202

203
#ifndef NO_CLOCK
204
  STATIC unsigned long GC_time_lim_nsec = 0;
205
                        /* The nanoseconds add-on to GC_time_limit      */
206
                        /* value.  Not updated by GC_set_time_limit().  */
207
                        /* Ignored if the value of GC_time_limit is     */
208
                        /* GC_TIME_UNLIMITED.                           */
209

210
# define TV_NSEC_LIMIT (1000UL * 1000) /* amount of nanoseconds in 1 ms */
211

212
  GC_API void GC_CALL GC_set_time_limit_tv(struct GC_timeval_s tv)
2✔
213
  {
214
    GC_ASSERT(tv.tv_ms <= GC_TIME_UNLIMITED);
2✔
215
    GC_ASSERT(tv.tv_nsec < TV_NSEC_LIMIT);
2✔
216
    GC_time_limit = tv.tv_ms;
2✔
217
    GC_time_lim_nsec = tv.tv_nsec;
2✔
218
  }
2✔
219

220
  GC_API struct GC_timeval_s GC_CALL GC_get_time_limit_tv(void)
2✔
221
  {
222
    struct GC_timeval_s tv;
223

224
    tv.tv_ms = GC_time_limit;
2✔
225
    tv.tv_nsec = GC_time_lim_nsec;
2✔
226
    return tv;
2✔
227
  }
228

229
  STATIC CLOCK_TYPE GC_start_time = CLOCK_TYPE_INITIALIZER;
230
                                /* Time at which we stopped world.      */
231
                                /* used only in GC_timeout_stop_func.   */
232
#endif /* !NO_CLOCK */
233

234
STATIC int GC_n_attempts = 0;   /* Number of attempts at finishing      */
235
                                /* collection within GC_time_limit.     */
236

237
STATIC GC_stop_func GC_default_stop_func = GC_never_stop_func;
238
                                /* accessed holding the lock.           */
239

240
GC_API void GC_CALL GC_set_stop_func(GC_stop_func stop_func)
2✔
241
{
242
  DCL_LOCK_STATE;
243
  GC_ASSERT(NONNULL_ARG_NOT_NULL(stop_func));
2✔
244
  LOCK();
2✔
245
  GC_default_stop_func = stop_func;
2✔
246
  UNLOCK();
2✔
247
}
2✔
248

249
GC_API GC_stop_func GC_CALL GC_get_stop_func(void)
2✔
250
{
251
  GC_stop_func stop_func;
252
  DCL_LOCK_STATE;
253
  LOCK();
2✔
254
  stop_func = GC_default_stop_func;
2✔
255
  UNLOCK();
2✔
256
  return stop_func;
2✔
257
}
258

259
#if defined(GC_DISABLE_INCREMENTAL) || defined(NO_CLOCK)
260
# define GC_timeout_stop_func GC_default_stop_func
261
#else
262
  STATIC int GC_CALLBACK GC_timeout_stop_func (void)
×
263
  {
264
    CLOCK_TYPE current_time;
265
    static unsigned count = 0;
266
    unsigned long time_diff, nsec_diff;
267

268
    if ((*GC_default_stop_func)())
×
269
      return(1);
×
270

271
    if ((count++ & 3) != 0) return(0);
×
272
    GET_TIME(current_time);
×
273
    time_diff = MS_TIME_DIFF(current_time,GC_start_time);
×
274
    nsec_diff = NS_FRAC_TIME_DIFF(current_time, GC_start_time);
×
275
#   if defined(CPPCHECK)
276
      GC_noop1((word)&nsec_diff);
277
#   endif
278
    if (time_diff >= GC_time_limit
×
279
        && (time_diff > GC_time_limit || nsec_diff >= GC_time_lim_nsec)) {
×
280
      GC_COND_LOG_PRINTF("Abandoning stopped marking after %lu ms %lu ns"
×
281
                         " (attempt %d)\n",
282
                         time_diff, nsec_diff, GC_n_attempts);
283
      return 1;
×
284
    }
285
    return(0);
×
286
  }
287
#endif /* !GC_DISABLE_INCREMENTAL */
288

289
#ifdef THREADS
290
  GC_INNER word GC_total_stacksize = 0; /* updated on every push_all_stacks */
291
#endif
292

293
static size_t min_bytes_allocd_minimum = 1;
294
                        /* The lowest value returned by min_bytes_allocd(). */
295

296
GC_API void GC_CALL GC_set_min_bytes_allocd(size_t value)
2✔
297
{
298
    GC_ASSERT(value > 0);
2✔
299
    min_bytes_allocd_minimum = value;
2✔
300
}
2✔
301

302
GC_API size_t GC_CALL GC_get_min_bytes_allocd(void)
2✔
303
{
304
    return min_bytes_allocd_minimum;
2✔
305
}
306

307
/* Return the minimum number of bytes that must be allocated between    */
308
/* collections to amortize the collection cost.  Should be non-zero.    */
309
static word min_bytes_allocd(void)
37,349✔
310
{
311
    word result;
312
    word stack_size;
313
    word total_root_size;       /* includes double stack size,  */
314
                                /* since the stack is expensive */
315
                                /* to scan.                     */
316
    word scan_size;             /* Estimate of memory to be scanned     */
317
                                /* during normal GC.                    */
318

319
#   ifdef THREADS
320
      if (GC_need_to_lock) {
37,349✔
321
        /* We are multi-threaded... */
322
        stack_size = GC_total_stacksize;
7,370✔
323
        /* For now, we just use the value computed during the latest GC. */
324
#       ifdef DEBUG_THREADS
325
          GC_log_printf("Total stacks size: %lu\n",
326
                        (unsigned long)stack_size);
327
#       endif
328
      } else
329
#   endif
330
    /* else*/ {
331
#     ifdef STACK_NOT_SCANNED
332
        stack_size = 0;
333
#     elif defined(STACK_GROWS_UP)
334
        stack_size = GC_approx_sp() - GC_stackbottom;
335
#     else
336
        stack_size = GC_stackbottom - GC_approx_sp();
29,979✔
337
#     endif
338
    }
339

340
    total_root_size = 2 * stack_size + GC_root_size;
37,349✔
341
    scan_size = 2 * GC_composite_in_use + GC_atomic_in_use / 4
37,349✔
342
                + total_root_size;
343
    result = scan_size / GC_free_space_divisor;
37,349✔
344
    if (GC_incremental) {
37,349✔
345
      result /= 2;
30,045✔
346
    }
347
    return result > min_bytes_allocd_minimum
37,349✔
348
            ? result : min_bytes_allocd_minimum;
37,349✔
349
}
350

351
STATIC word GC_non_gc_bytes_at_gc = 0;
352
                /* Number of explicitly managed bytes of storage        */
353
                /* at last collection.                                  */
354

355
/* Return the number of bytes allocated, adjusted for explicit storage  */
356
/* management, etc..  This number is used in deciding when to trigger   */
357
/* collections.                                                         */
358
STATIC word GC_adj_bytes_allocd(void)
11,294,713✔
359
{
360
    signed_word result;
361
    signed_word expl_managed = (signed_word)GC_non_gc_bytes
22,589,426✔
362
                                - (signed_word)GC_non_gc_bytes_at_gc;
11,294,713✔
363

364
    /* Don't count what was explicitly freed, or newly allocated for    */
365
    /* explicit management.  Note that deallocating an explicitly       */
366
    /* managed object should not alter result, assuming the client      */
367
    /* is playing by the rules.                                         */
368
    result = (signed_word)GC_bytes_allocd
22,589,426✔
369
             + (signed_word)GC_bytes_dropped
11,294,713✔
370
             - (signed_word)GC_bytes_freed
11,294,713✔
371
             + (signed_word)GC_finalizer_bytes_freed
11,294,713✔
372
             - expl_managed;
373
    if (result > (signed_word)GC_bytes_allocd) {
11,294,713✔
374
        result = GC_bytes_allocd;
7,064,686✔
375
        /* probably client bug or unfortunate scheduling */
376
    }
377
    result += GC_bytes_finalized;
11,294,713✔
378
        /* We count objects enqueued for finalization as though they    */
379
        /* had been reallocated this round. Finalization is user        */
380
        /* visible progress.  And if we don't count this, we have       */
381
        /* stability problems for programs that finalize all objects.   */
382
    if (result < (signed_word)(GC_bytes_allocd >> 3)) {
11,294,713✔
383
        /* Always count at least 1/8 of the allocations.  We don't want */
384
        /* to collect too infrequently, since that would inhibit        */
385
        /* coalescing of free storage blocks.                           */
386
        /* This also makes us partially robust against client bugs.     */
387
        return(GC_bytes_allocd >> 3);
494✔
388
    } else {
389
        return(result);
11,294,219✔
390
    }
391
}
392

393

394
/* Clear up a few frames worth of garbage left at the top of the stack. */
395
/* This is used to prevent us from accidentally treating garbage left   */
396
/* on the stack by other parts of the collector as roots.  This         */
397
/* differs from the code in misc.c, which actually tries to keep the    */
398
/* stack clear of long-lived, client-generated garbage.                 */
399
STATIC void GC_clear_a_few_frames(void)
24,114✔
400
{
401
#   ifndef CLEAR_NWORDS
402
#     define CLEAR_NWORDS 64
403
#   endif
404
    volatile word frames[CLEAR_NWORDS];
405
    BZERO((word *)frames, CLEAR_NWORDS * sizeof(word));
24,114✔
406
}
24,114✔
407

408
/* Heap size at which we need a collection to avoid expanding past      */
409
/* limits used by blacklisting.                                         */
410
STATIC word GC_collect_at_heapsize = GC_WORD_MAX;
411

412
GC_API void GC_CALL GC_start_incremental_collection(void)
×
413
{
414
# ifndef GC_DISABLE_INCREMENTAL
415
    DCL_LOCK_STATE;
416

417
    if (!GC_incremental) return;
×
418
    LOCK();
×
419
    GC_should_start_incremental_collection = TRUE;
×
420
    if (!GC_dont_gc) {
×
421
      ENTER_GC();
×
422
      GC_collect_a_little_inner(1);
×
423
      EXIT_GC();
×
424
    }
425
    UNLOCK();
×
426
# endif
427
}
428

429
/* Have we allocated enough to amortize a collection? */
430
GC_INNER GC_bool GC_should_collect(void)
11,294,713✔
431
{
432
    static word last_min_bytes_allocd;
433
    static word last_gc_no;
434

435
    GC_ASSERT(I_HOLD_LOCK());
11,294,713✔
436
    if (last_gc_no != GC_gc_no) {
11,294,713✔
437
      last_min_bytes_allocd = min_bytes_allocd();
23,424✔
438
      last_gc_no = GC_gc_no;
23,424✔
439
    }
440
# ifndef GC_DISABLE_INCREMENTAL
441
    if (GC_should_start_incremental_collection) {
11,294,713✔
442
      GC_should_start_incremental_collection = FALSE;
×
443
      return TRUE;
×
444
    }
445
# endif
446
    if (GC_disable_automatic_collection) return FALSE;
11,294,713✔
447

448
    return(GC_adj_bytes_allocd() >= last_min_bytes_allocd
22,589,426✔
449
           || GC_heapsize >= GC_collect_at_heapsize);
11,294,713✔
450
}
451

452
/* STATIC */ GC_start_callback_proc GC_start_call_back = 0;
453
                        /* Called at start of full collections.         */
454
                        /* Not called if 0.  Called with the allocation */
455
                        /* lock held.  Not used by GC itself.           */
456

457
GC_API void GC_CALL GC_set_start_callback(GC_start_callback_proc fn)
2✔
458
{
459
    DCL_LOCK_STATE;
460
    LOCK();
2✔
461
    GC_start_call_back = fn;
2✔
462
    UNLOCK();
2✔
463
}
2✔
464

465
GC_API GC_start_callback_proc GC_CALL GC_get_start_callback(void)
2✔
466
{
467
    GC_start_callback_proc fn;
468
    DCL_LOCK_STATE;
469
    LOCK();
2✔
470
    fn = GC_start_call_back;
2✔
471
    UNLOCK();
2✔
472
    return fn;
2✔
473
}
474

475
GC_INLINE void GC_notify_full_gc(void)
10,789✔
476
{
477
    if (GC_start_call_back != 0) {
10,789✔
478
        (*GC_start_call_back)();
×
479
    }
480
}
10,789✔
481

482
STATIC GC_bool GC_is_full_gc = FALSE;
483

484
STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func);
485
STATIC void GC_finish_collection(void);
486

487
/*
488
 * Initiate a garbage collection if appropriate.
489
 * Choose judiciously
490
 * between partial, full, and stop-world collections.
491
 */
492
STATIC void GC_maybe_gc(void)
9,568,783✔
493
{
494
    GC_ASSERT(I_HOLD_LOCK());
9,568,783✔
495
    ASSERT_CANCEL_DISABLED();
9,568,783✔
496
    if (GC_should_collect()) {
9,568,783✔
497
        static int n_partial_gcs = 0;
498

499
        if (!GC_incremental) {
14,249✔
500
            /* TODO: If possible, GC_default_stop_func should be used here */
501
            GC_try_to_collect_inner(GC_never_stop_func);
×
502
            n_partial_gcs = 0;
×
503
            return;
×
504
        } else {
505
#         ifdef PARALLEL_MARK
506
            if (GC_parallel)
14,249✔
507
              GC_wait_for_reclaim();
2,673✔
508
#         endif
509
          if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
14,249✔
510
            GC_COND_LOG_PRINTF(
924✔
511
                "***>Full mark for collection #%lu after %lu allocd bytes\n",
512
                (unsigned long)GC_gc_no + 1, (unsigned long)GC_bytes_allocd);
×
513
            GC_promote_black_lists();
924✔
514
            (void)GC_reclaim_all((GC_stop_func)0, TRUE);
924✔
515
            GC_notify_full_gc();
924✔
516
            GC_clear_marks();
924✔
517
            n_partial_gcs = 0;
924✔
518
            GC_is_full_gc = TRUE;
924✔
519
          } else {
520
            n_partial_gcs++;
13,325✔
521
          }
522
        }
523
        /* We try to mark with the world stopped.       */
524
        /* If we run out of time, this turns into       */
525
        /* incremental marking.                         */
526
#       ifndef NO_CLOCK
527
          if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
14,249✔
528
#       endif
529
        /* TODO: If possible, GC_default_stop_func should be    */
530
        /* used instead of GC_never_stop_func here.             */
531
        if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
14,249✔
532
                            GC_never_stop_func : GC_timeout_stop_func)) {
533
#           ifdef SAVE_CALL_CHAIN
534
                GC_save_callers(GC_last_stack);
535
#           endif
536
            GC_finish_collection();
14,249✔
537
        } else {
538
            if (!GC_is_full_gc) {
×
539
                /* Count this as the first attempt */
540
                GC_n_attempts++;
×
541
            }
542
        }
543
    }
544
}
545

546
STATIC GC_on_collection_event_proc GC_on_collection_event = 0;
547

548
GC_API void GC_CALL GC_set_on_collection_event(GC_on_collection_event_proc fn)
2✔
549
{
550
    /* fn may be 0 (means no event notifier). */
551
    DCL_LOCK_STATE;
552
    LOCK();
2✔
553
    GC_on_collection_event = fn;
2✔
554
    UNLOCK();
2✔
555
}
2✔
556

557
GC_API GC_on_collection_event_proc GC_CALL GC_get_on_collection_event(void)
2✔
558
{
559
    GC_on_collection_event_proc fn;
560
    DCL_LOCK_STATE;
561
    LOCK();
2✔
562
    fn = GC_on_collection_event;
2✔
563
    UNLOCK();
2✔
564
    return fn;
2✔
565
}
566

567
/* Stop the world garbage collection.  If stop_func is not      */
568
/* GC_never_stop_func then abort if stop_func returns TRUE.     */
569
/* Return TRUE if we successfully completed the collection.     */
570
GC_INNER GC_bool GC_try_to_collect_inner(GC_stop_func stop_func)
9,865✔
571
{
572
#   ifndef NO_CLOCK
573
      CLOCK_TYPE start_time = CLOCK_TYPE_INITIALIZER;
9,865✔
574
      GC_bool start_time_valid;
575
#   endif
576

577
    ASSERT_CANCEL_DISABLED();
9,865✔
578
    GC_ASSERT(I_HOLD_LOCK());
9,865✔
579
    if (GC_dont_gc || (*stop_func)()) return FALSE;
19,733✔
580
    if (GC_on_collection_event)
9,865✔
581
      GC_on_collection_event(GC_EVENT_START);
×
582
    if (GC_incremental && GC_collection_in_progress()) {
9,865✔
583
      GC_COND_LOG_PRINTF(
×
584
            "GC_try_to_collect_inner: finishing collection in progress\n");
585
      /* Just finish collection already in progress.    */
586
        while(GC_collection_in_progress()) {
×
587
            if ((*stop_func)()) {
×
588
              /* TODO: Notify GC_EVENT_ABANDON */
589
              return(FALSE);
×
590
            }
591
            ENTER_GC();
×
592
            GC_collect_a_little_inner(1);
×
593
            EXIT_GC();
×
594
        }
595
    }
596
    GC_notify_full_gc();
9,865✔
597
#   ifndef NO_CLOCK
598
      start_time_valid = FALSE;
9,865✔
599
      if ((GC_print_stats | (int)measure_performance) != 0) {
9,865✔
600
        if (GC_print_stats)
2,276✔
601
          GC_log_printf("Initiating full world-stop collection!\n");
×
602
        start_time_valid = TRUE;
2,276✔
603
        GET_TIME(start_time);
2,276✔
604
      }
605
#   endif
606
    GC_promote_black_lists();
9,865✔
607
    /* Make sure all blocks have been reclaimed, so sweep routines      */
608
    /* don't see cleared mark bits.                                     */
609
    /* If we're guaranteed to finish, then this is unnecessary.         */
610
    /* In the find_leak case, we have to finish to guarantee that       */
611
    /* previously unmarked objects are not reported as leaks.           */
612
#       ifdef PARALLEL_MARK
613
          if (GC_parallel)
9,865✔
614
            GC_wait_for_reclaim();
3,279✔
615
#       endif
616
        if ((GC_find_leak || stop_func != GC_never_stop_func)
9,865✔
617
            && !GC_reclaim_all(stop_func, FALSE)) {
62✔
618
            /* Aborted.  So far everything is still consistent. */
619
            /* TODO: Notify GC_EVENT_ABANDON */
620
            return(FALSE);
×
621
        }
622
    GC_invalidate_mark_state();  /* Flush mark stack.   */
9,865✔
623
    GC_clear_marks();
9,865✔
624
#   ifdef SAVE_CALL_CHAIN
625
        GC_save_callers(GC_last_stack);
626
#   endif
627
    GC_is_full_gc = TRUE;
9,865✔
628
    if (!GC_stopped_mark(stop_func)) {
9,865✔
629
      if (!GC_incremental) {
×
630
        /* We're partially done and have no way to complete or use      */
631
        /* current work.  Reestablish invariants as cheaply as          */
632
        /* possible.                                                    */
633
        GC_invalidate_mark_state();
×
634
        GC_unpromote_black_lists();
×
635
      } /* else we claim the world is already still consistent.  We'll  */
636
        /* finish incrementally.                                        */
637
      /* TODO: Notify GC_EVENT_ABANDON */
638
      return(FALSE);
×
639
    }
640
    GC_finish_collection();
9,868✔
641
#   ifndef NO_CLOCK
642
      if (start_time_valid) {
9,868✔
643
        CLOCK_TYPE current_time;
644
        unsigned long time_diff, ns_frac_diff;
645

646
        GET_TIME(current_time);
2,279✔
647
        time_diff = MS_TIME_DIFF(current_time, start_time);
2,279✔
648
        ns_frac_diff = NS_FRAC_TIME_DIFF(current_time, start_time);
2,279✔
649
        if (measure_performance) {
2,279✔
650
          full_gc_total_time += time_diff; /* may wrap */
2,279✔
651
          full_gc_total_ns_frac += (unsigned)ns_frac_diff;
2,279✔
652
          if (full_gc_total_ns_frac >= 1000000U) {
2,279✔
653
            /* Overflow of the nanoseconds part. */
654
            full_gc_total_ns_frac -= 1000000U;
1,148✔
655
            full_gc_total_time++;
1,148✔
656
          }
657
        }
658
        if (GC_print_stats)
2,279✔
659
          GC_log_printf("Complete collection took %lu ms %lu ns\n",
×
660
                        time_diff, ns_frac_diff);
661
      }
662
#   endif
663
    if (GC_on_collection_event)
9,868✔
664
      GC_on_collection_event(GC_EVENT_END);
×
665
    return(TRUE);
9,868✔
666
}
667

668
/* The number of extra calls to GC_mark_some that we have made. */
669
STATIC int GC_deficit = 0;
670

671
/* The default value of GC_rate.        */
672
#ifndef GC_RATE
673
# define GC_RATE 10
674
#endif
675

676
/* When GC_collect_a_little_inner() performs n units of GC work, a unit */
677
/* is intended to touch roughly GC_rate pages.  (But, every once in     */
678
/* a while, we do more than that.)  This needs to be a fairly large     */
679
/* number with our current incremental GC strategy, since otherwise we  */
680
/* allocate too much during GC, and the cleanup gets expensive.         */
681
STATIC int GC_rate = GC_RATE;
682

683
GC_API void GC_CALL GC_set_rate(int value)
2✔
684
{
685
    GC_ASSERT(value > 0);
2✔
686
    GC_rate = value;
2✔
687
}
2✔
688

689
GC_API int GC_CALL GC_get_rate(void)
2✔
690
{
691
    return GC_rate;
2✔
692
}
693

694
/* The default maximum number of prior attempts at world stop marking.  */
695
#ifndef MAX_PRIOR_ATTEMPTS
696
# define MAX_PRIOR_ATTEMPTS 1
697
#endif
698

699
/* The maximum number of prior attempts at world stop marking.          */
700
/* A value of 1 means that we finish the second time, no matter how     */
701
/* long it takes.  Does not count the initial root scan for a full GC.  */
702
static int max_prior_attempts = MAX_PRIOR_ATTEMPTS;
703

704
GC_API void GC_CALL GC_set_max_prior_attempts(int value)
2✔
705
{
706
    GC_ASSERT(value >= 0);
2✔
707
    max_prior_attempts = value;
2✔
708
}
2✔
709

710
GC_API int GC_CALL GC_get_max_prior_attempts(void)
2✔
711
{
712
    return max_prior_attempts;
2✔
713
}
714

715
GC_INNER void GC_collect_a_little_inner(int n)
9,568,783✔
716
{
717
    IF_CANCEL(int cancel_state;)
718

719
    GC_ASSERT(I_HOLD_LOCK());
9,568,783✔
720
    DISABLE_CANCEL(cancel_state);
9,568,783✔
721
    if (GC_incremental && GC_collection_in_progress()) {
9,568,783✔
722
        int i;
723
        int max_deficit = GC_rate * n;
×
724

725
#       ifdef PARALLEL_MARK
726
            if (GC_time_limit != GC_TIME_UNLIMITED)
×
727
                GC_parallel_mark_disabled = TRUE;
×
728
#       endif
729
        for (i = GC_deficit; i < max_deficit; i++) {
×
730
            if (GC_mark_some(NULL))
×
731
                break;
×
732
        }
733
#       ifdef PARALLEL_MARK
734
            GC_parallel_mark_disabled = FALSE;
×
735
#       endif
736

737
        if (i < max_deficit && !GC_dont_gc) {
×
738
            /* Need to finish a collection.     */
739
#           ifdef SAVE_CALL_CHAIN
740
                GC_save_callers(GC_last_stack);
741
#           endif
742
#           ifdef PARALLEL_MARK
743
                if (GC_parallel)
×
744
                    GC_wait_for_reclaim();
×
745
#           endif
746
            if (GC_n_attempts < max_prior_attempts
×
747
                && GC_time_limit != GC_TIME_UNLIMITED) {
×
748
#               ifndef NO_CLOCK
749
                    GET_TIME(GC_start_time);
×
750
#               endif
751
                if (GC_stopped_mark(GC_timeout_stop_func)) {
×
752
                    GC_finish_collection();
×
753
                } else {
754
                    GC_n_attempts++;
×
755
                }
756
            } else {
757
                /* TODO: If possible, GC_default_stop_func should be    */
758
                /* used here.                                           */
759
                (void)GC_stopped_mark(GC_never_stop_func);
×
760
                GC_finish_collection();
×
761
            }
762
        }
763
        if (GC_deficit > 0) {
×
764
            GC_deficit -= max_deficit;
×
765
            if (GC_deficit < 0)
×
766
                GC_deficit = 0;
×
767
        }
768
    } else if (!GC_dont_gc) {
9,568,783✔
769
        GC_maybe_gc();
9,568,783✔
770
    }
771
    RESTORE_CANCEL(cancel_state);
9,568,783✔
772
}
9,568,783✔
773

774
GC_INNER void (*GC_check_heap)(void) = 0;
775
GC_INNER void (*GC_print_all_smashed)(void) = 0;
776

777
GC_API int GC_CALL GC_collect_a_little(void)
2✔
778
{
779
    int result;
780
    DCL_LOCK_STATE;
781

782
    LOCK();
2✔
783
    if (!GC_dont_gc) {
2✔
784
      ENTER_GC();
2✔
785
      GC_collect_a_little_inner(1);
2✔
786
      EXIT_GC();
2✔
787
    }
788
    result = (int)GC_collection_in_progress();
2✔
789
    UNLOCK();
2✔
790
    if (!result && GC_debugging_started) GC_print_all_smashed();
2✔
791
    return(result);
2✔
792
}
793

794
#ifndef NO_CLOCK
795
  /* Variables for world-stop average delay time statistic computation. */
796
  /* "divisor" is incremented every world-stop and halved when reached  */
797
  /* its maximum (or upon "total_time" overflow).                       */
798
  static unsigned world_stopped_total_time = 0;
799
  static unsigned world_stopped_total_divisor = 0;
800
# ifndef MAX_TOTAL_TIME_DIVISOR
801
    /* We shall not use big values here (so "outdated" delay time       */
802
    /* values would have less impact on "average" delay time value than */
803
    /* newer ones).                                                     */
804
#   define MAX_TOTAL_TIME_DIVISOR 1000
805
# endif
806
#endif /* !NO_CLOCK */
807

808
#ifdef USE_MUNMAP
809
# define IF_USE_MUNMAP(x) x
810
# define COMMA_IF_USE_MUNMAP(x) /* comma */, x
811
#else
812
# define IF_USE_MUNMAP(x) /* empty */
813
# define COMMA_IF_USE_MUNMAP(x) /* empty */
814
#endif
815

816
/*
817
 * We stop the world and mark from all roots.
818
 * If stop_func() ever returns TRUE, we may fail and return FALSE.
819
 * Increment GC_gc_no if we succeed.
820
 */
821
STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func)
24,114✔
822
{
823
    int i;
824
#   ifndef NO_CLOCK
825
      CLOCK_TYPE start_time = CLOCK_TYPE_INITIALIZER;
24,114✔
826
#   endif
827

828
    GC_ASSERT(I_HOLD_LOCK());
24,114✔
829
#   if !defined(REDIRECT_MALLOC) && defined(USE_WINALLOC)
830
        GC_add_current_malloc_heap();
831
#   endif
832
#   if defined(REGISTER_LIBRARIES_EARLY)
833
        GC_cond_register_dynamic_libraries();
24,114✔
834
#   endif
835

836
#   ifndef NO_CLOCK
837
      if (GC_PRINT_STATS_FLAG)
24,114✔
838
        GET_TIME(start_time);
×
839
#   endif
840

841
#   if !defined(GC_NO_FINALIZATION) && !defined(GC_TOGGLE_REFS_NOT_NEEDED)
842
      GC_process_togglerefs();
24,114✔
843
#   endif
844
#   ifdef THREADS
845
      if (GC_on_collection_event)
24,114✔
846
        GC_on_collection_event(GC_EVENT_PRE_STOP_WORLD);
×
847
#   endif
848
    STOP_WORLD();
24,114✔
849
#   ifdef THREADS
850
      if (GC_on_collection_event)
24,114✔
851
        GC_on_collection_event(GC_EVENT_POST_STOP_WORLD);
×
852
#   endif
853

854
#   ifdef THREAD_LOCAL_ALLOC
855
      GC_world_stopped = TRUE;
24,114✔
856
#   endif
857
        /* Output blank line for convenience here */
858
    GC_COND_LOG_PRINTF(
24,114✔
859
              "\n--> Marking for collection #%lu after %lu allocated bytes\n",
860
              (unsigned long)GC_gc_no + 1, (unsigned long) GC_bytes_allocd);
×
861
#   ifdef MAKE_BACK_GRAPH
862
      if (GC_print_back_height) {
863
        GC_build_back_graph();
864
      }
865
#   endif
866

867
    /* Mark from all roots.  */
868
        if (GC_on_collection_event)
24,114✔
869
          GC_on_collection_event(GC_EVENT_MARK_START);
×
870

871
        /* Minimize junk left in my registers and on the stack */
872
            GC_clear_a_few_frames();
24,114✔
873
            GC_noop6(0,0,0,0,0,0);
24,114✔
874

875
        GC_initiate_gc();
24,114✔
876
#       ifdef PARALLEL_MARK
877
          if (stop_func != GC_never_stop_func)
24,114✔
878
            GC_parallel_mark_disabled = TRUE;
×
879
#       endif
880
        for (i = 0; !(*stop_func)(); i++) {
4,642,344✔
881
          if (GC_mark_some(GC_approx_sp())) {
4,642,344✔
882
#           ifdef PARALLEL_MARK
883
              if (GC_parallel && GC_parallel_mark_disabled) {
24,114✔
884
                GC_COND_LOG_PRINTF("Stopped marking done after %d iterations"
×
885
                                   " with disabled parallel marker\n", i);
886
              }
887
#           endif
888
            i = -1;
24,114✔
889
            break;
24,114✔
890
          }
891
        }
892
#       ifdef PARALLEL_MARK
893
          GC_parallel_mark_disabled = FALSE;
24,114✔
894
#       endif
895

896
        if (i >= 0) {
24,114✔
897
          GC_COND_LOG_PRINTF("Abandoned stopped marking after"
×
898
                             " %d iterations\n", i);
899
          GC_deficit = i;       /* Give the mutator a chance.   */
×
900
#         ifdef THREAD_LOCAL_ALLOC
901
            GC_world_stopped = FALSE;
×
902
#         endif
903

904
#         ifdef THREADS
905
            if (GC_on_collection_event)
×
906
              GC_on_collection_event(GC_EVENT_PRE_START_WORLD);
×
907
#         endif
908

909
          START_WORLD();
×
910

911
#         ifdef THREADS
912
            if (GC_on_collection_event)
×
913
              GC_on_collection_event(GC_EVENT_POST_START_WORLD);
×
914
#         endif
915

916
          /* TODO: Notify GC_EVENT_MARK_ABANDON */
917
          return FALSE;
24,117✔
918
        }
919

920
    GC_gc_no++;
24,114✔
921
#   ifdef USE_MUNMAP
922
      GC_ASSERT(GC_heapsize >= GC_unmapped_bytes);
24,114✔
923
#   endif
924
    GC_ASSERT(GC_our_mem_bytes >= GC_heapsize);
24,114✔
925
    GC_DBGLOG_PRINTF("GC #%lu freed %ld bytes, heap %lu KiB ("
24,114✔
926
                     IF_USE_MUNMAP("+ %lu KiB unmapped ")
927
                     "+ %lu KiB internal)\n",
928
                     (unsigned long)GC_gc_no, (long)GC_bytes_found,
929
                     TO_KiB_UL(GC_heapsize - GC_unmapped_bytes) /*, */
×
930
                     COMMA_IF_USE_MUNMAP(TO_KiB_UL(GC_unmapped_bytes)),
×
931
                     TO_KiB_UL(GC_our_mem_bytes - GC_heapsize));
×
932

933
    /* Check all debugged objects for consistency */
934
    if (GC_debugging_started) {
24,114✔
935
      (*GC_check_heap)();
224✔
936
    }
937
    if (GC_on_collection_event) {
24,114✔
938
      GC_on_collection_event(GC_EVENT_MARK_END);
×
939
#     ifdef THREADS
940
        GC_on_collection_event(GC_EVENT_PRE_START_WORLD);
×
941
#     endif
942
    }
943
#   ifdef THREAD_LOCAL_ALLOC
944
      GC_world_stopped = FALSE;
24,114✔
945
#   endif
946

947
    START_WORLD();
24,114✔
948

949
#   ifdef THREADS
950
      if (GC_on_collection_event)
24,117✔
951
        GC_on_collection_event(GC_EVENT_POST_START_WORLD);
×
952
#   endif
953

954
#   ifndef NO_CLOCK
955
      if (GC_PRINT_STATS_FLAG) {
24,117✔
956
        unsigned long time_diff;
957
        unsigned total_time, divisor;
958
        CLOCK_TYPE current_time;
959

960
        GET_TIME(current_time);
×
961
        time_diff = MS_TIME_DIFF(current_time,start_time);
×
962

963
        /* Compute new world-stop delay total time */
964
        total_time = world_stopped_total_time;
×
965
        divisor = world_stopped_total_divisor;
×
966
        if ((int)total_time < 0 || divisor >= MAX_TOTAL_TIME_DIVISOR) {
×
967
          /* Halve values if overflow occurs */
968
          total_time >>= 1;
×
969
          divisor >>= 1;
×
970
        }
971
        total_time += time_diff < (((unsigned)-1) >> 1) ?
×
972
                        (unsigned)time_diff : ((unsigned)-1) >> 1;
×
973
        /* Update old world_stopped_total_time and its divisor */
974
        world_stopped_total_time = total_time;
×
975
        world_stopped_total_divisor = ++divisor;
×
976

977
        GC_ASSERT(divisor != 0);
×
978
        GC_log_printf("World-stopped marking took %lu ms %lu ns"
×
979
                      " (%u ms in average)\n",
980
                      time_diff, NS_FRAC_TIME_DIFF(current_time, start_time),
×
981
                      total_time / divisor);
982
      }
983
#   endif
984
    return(TRUE);
24,117✔
985
}
986

987
/* Set all mark bits for the free list whose first entry is q   */
988
GC_INNER void GC_set_fl_marks(ptr_t q)
930,618✔
989
{
990
    if (q /* != NULL */) { /* CPPCHECK */
930,618✔
991
      struct hblk *h = HBLKPTR(q);
930,618✔
992
      struct hblk *last_h = h;
930,618✔
993
      hdr *hhdr = HDR(h);
930,618✔
994
      IF_PER_OBJ(word sz = hhdr->hb_sz;)
995

996
      for (;;) {
997
        word bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz);
23,294,904✔
998

999
        if (!mark_bit_from_hdr(hhdr, bit_no)) {
23,294,904✔
1000
          set_mark_bit_from_hdr(hhdr, bit_no);
15,977,802✔
1001
          ++hhdr -> hb_n_marks;
15,977,802✔
1002
        }
1003

1004
        q = (ptr_t)obj_link(q);
23,294,904✔
1005
        if (q == NULL)
23,294,904✔
1006
          break;
930,618✔
1007

1008
        h = HBLKPTR(q);
22,364,286✔
1009
        if (h != last_h) {
22,364,286✔
1010
          last_h = h;
630,465✔
1011
          hhdr = HDR(h);
630,465✔
1012
          IF_PER_OBJ(sz = hhdr->hb_sz;)
1013
        }
1014
      }
22,364,286✔
1015
    }
1016
}
930,618✔
1017

1018
#if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
1019
  /* Check that all mark bits for the free list whose first entry is    */
1020
  /* (*pfreelist) are set.  Check skipped if points to a special value. */
1021
  void GC_check_fl_marks(void **pfreelist)
7,991,808✔
1022
  {
1023
    /* TODO: There is a data race with GC_FAST_MALLOC_GRANS (which does */
1024
    /* not do atomic updates to the free-list).  The race seems to be   */
1025
    /* harmless, and for now we just skip this check in case of TSan.   */
1026
#   if defined(AO_HAVE_load_acquire_read) && !defined(THREAD_SANITIZER)
1027
      AO_t *list = (AO_t *)AO_load_acquire_read((AO_t *)pfreelist);
7,991,808✔
1028
                /* Atomic operations are used because the world is running. */
1029
      AO_t *prev;
1030
      AO_t *p;
1031

1032
      if ((word)list <= HBLKSIZE) return;
7,991,808✔
1033

1034
      prev = (AO_t *)pfreelist;
930,064✔
1035
      for (p = list; p != NULL;) {
25,147,949✔
1036
        AO_t *next;
1037

1038
        if (!GC_is_marked(p)) {
23,287,821✔
1039
          ABORT_ARG2("Unmarked local free list entry",
×
1040
                     ": object %p on list %p", (void *)p, (void *)list);
1041
        }
1042

1043
        /* While traversing the free-list, it re-reads the pointer to   */
1044
        /* the current node before accepting its next pointer and       */
1045
        /* bails out if the latter has changed.  That way, it won't     */
1046
        /* try to follow the pointer which might be been modified       */
1047
        /* after the object was returned to the client.  It might       */
1048
        /* perform the mark-check on the just allocated object but      */
1049
        /* that should be harmless.                                     */
1050
        next = (AO_t *)AO_load_acquire_read(p);
23,287,821✔
1051
        if (AO_load(prev) != (AO_t)p)
23,287,821✔
1052
          break;
×
1053
        prev = p;
23,287,821✔
1054
        p = next;
23,287,821✔
1055
      }
1056
#   else
1057
      /* FIXME: Not implemented (just skipped). */
1058
      (void)pfreelist;
1059
#   endif
1060
  }
1061
#endif /* GC_ASSERTIONS && THREAD_LOCAL_ALLOC */
1062

1063
/* Clear all mark bits for the free list whose first entry is q */
1064
/* Decrement GC_bytes_found by number of bytes on free list.    */
1065
STATIC void GC_clear_fl_marks(ptr_t q)
40,050✔
1066
{
1067
      struct hblk *h = HBLKPTR(q);
40,050✔
1068
      struct hblk *last_h = h;
40,050✔
1069
      hdr *hhdr = HDR(h);
40,050✔
1070
      word sz = hhdr->hb_sz; /* Normally set only once. */
40,050✔
1071

1072
      for (;;) {
1073
        word bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz);
1,899,481✔
1074

1075
        if (mark_bit_from_hdr(hhdr, bit_no)) {
1,899,481✔
1076
          size_t n_marks = hhdr -> hb_n_marks;
173,782✔
1077

1078
          GC_ASSERT(n_marks != 0);
173,782✔
1079
          clear_mark_bit_from_hdr(hhdr, bit_no);
173,782✔
1080
          n_marks--;
173,782✔
1081
#         ifdef PARALLEL_MARK
1082
            /* Appr. count, don't decrement to zero! */
1083
            if (0 != n_marks || !GC_parallel) {
173,782✔
1084
              hhdr -> hb_n_marks = n_marks;
173,489✔
1085
            }
1086
#         else
1087
            hhdr -> hb_n_marks = n_marks;
1088
#         endif
1089
        }
1090
        GC_bytes_found -= sz;
1,899,481✔
1091

1092
        q = (ptr_t)obj_link(q);
1,899,481✔
1093
        if (q == NULL)
1,899,481✔
1094
          break;
40,050✔
1095

1096
        h = HBLKPTR(q);
1,859,431✔
1097
        if (h != last_h) {
1,859,431✔
1098
          last_h = h;
69,726✔
1099
          hhdr = HDR(h);
69,726✔
1100
          sz = hhdr->hb_sz;
69,726✔
1101
        }
1102
      }
1,859,431✔
1103
}
40,050✔
1104

1105
#if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
1106
  void GC_check_tls(void);
1107
#endif
1108

1109
GC_on_heap_resize_proc GC_on_heap_resize = 0;
1110

1111
/* Used for logging only. */
1112
GC_INLINE int GC_compute_heap_usage_percent(void)
×
1113
{
1114
  word used = GC_composite_in_use + GC_atomic_in_use;
×
1115
  word heap_sz = GC_heapsize - GC_unmapped_bytes;
×
1116
# if defined(CPPCHECK)
1117
    word limit = (GC_WORD_MAX >> 1) / 50; /* to avoid a false positive */
1118
# else
1119
    const word limit = GC_WORD_MAX / 100;
×
1120
# endif
1121

1122
  return used >= heap_sz ? 0 : used < limit ?
×
1123
                (int)((used * 100) / heap_sz) : (int)(used / (heap_sz / 100));
×
1124
}
1125

1126
/* Finish up a collection.  Assumes mark bits are consistent, lock is   */
1127
/* held, but the world is otherwise running.                            */
1128
STATIC void GC_finish_collection(void)
24,117✔
1129
{
1130
#   ifndef NO_CLOCK
1131
      CLOCK_TYPE start_time = CLOCK_TYPE_INITIALIZER;
24,117✔
1132
      CLOCK_TYPE finalize_time = CLOCK_TYPE_INITIALIZER;
24,117✔
1133
#   endif
1134

1135
    GC_ASSERT(I_HOLD_LOCK());
24,117✔
1136
#   if defined(GC_ASSERTIONS) \
1137
       && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
1138
        /* Check that we marked some of our own data.           */
1139
        /* TODO: Add more checks. */
1140
        GC_check_tls();
24,117✔
1141
#   endif
1142

1143
#   ifndef NO_CLOCK
1144
      if (GC_print_stats)
24,117✔
1145
        GET_TIME(start_time);
×
1146
#   endif
1147
    if (GC_on_collection_event)
24,117✔
1148
      GC_on_collection_event(GC_EVENT_RECLAIM_START);
×
1149

1150
#   ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
1151
      if (GC_bytes_found > 0)
24,117✔
1152
        GC_reclaimed_bytes_before_gc += (word)GC_bytes_found;
23,779✔
1153
#   endif
1154
    GC_bytes_found = 0;
24,117✔
1155
#   if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
1156
        if (GETENV("GC_PRINT_ADDRESS_MAP") != 0) {
24,117✔
1157
          GC_print_address_map();
×
1158
        }
1159
#   endif
1160
    COND_DUMP;
24,117✔
1161
    if (GC_find_leak) {
24,117✔
1162
      /* Mark all objects on the free list.  All objects should be      */
1163
      /* marked when we're done.                                        */
1164
      word size;        /* current object size  */
1165
      unsigned kind;
1166
      ptr_t q;
1167

1168
      for (kind = 0; kind < GC_n_kinds; kind++) {
310✔
1169
        for (size = 1; size <= MAXOBJGRANULES; size++) {
31,992✔
1170
          q = (ptr_t)GC_obj_kinds[kind].ok_freelist[size];
31,744✔
1171
          if (q != NULL)
31,744✔
1172
            GC_set_fl_marks(q);
156✔
1173
        }
1174
      }
1175
      GC_start_reclaim(TRUE);
62✔
1176
        /* The above just checks; it doesn't really reclaim anything.   */
1177
    }
1178

1179
#   ifndef GC_NO_FINALIZATION
1180
      GC_finalize();
24,117✔
1181
#   endif
1182
#   ifndef NO_CLOCK
1183
      if (GC_print_stats)
24,117✔
1184
        GET_TIME(finalize_time);
×
1185
#   endif
1186

1187
    if (GC_print_back_height) {
24,117✔
1188
#     ifdef MAKE_BACK_GRAPH
1189
        GC_traverse_back_graph();
1190
#     elif !defined(SMALL_CONFIG)
1191
        GC_err_printf("Back height not available: "
×
1192
                      "Rebuild collector with -DMAKE_BACK_GRAPH\n");
1193
#     endif
1194
    }
1195

1196
    /* Clear free list mark bits, in case they got accidentally marked   */
1197
    /* (or GC_find_leak is set and they were intentionally marked).      */
1198
    /* Also subtract memory remaining from GC_bytes_found count.         */
1199
    /* Note that composite objects on free list are cleared.             */
1200
    /* Thus accidentally marking a free list is not a problem;  only     */
1201
    /* objects on the list itself will be marked, and that's fixed here. */
1202
    {
1203
      word size;        /* current object size          */
1204
      ptr_t q;          /* pointer to current object    */
1205
      unsigned kind;
1206

1207
      for (kind = 0; kind < GC_n_kinds; kind++) {
136,044✔
1208
        for (size = 1; size <= MAXOBJGRANULES; size++) {
14,438,583✔
1209
          q = (ptr_t)GC_obj_kinds[kind].ok_freelist[size];
14,326,656✔
1210
          if (q != NULL)
14,326,656✔
1211
            GC_clear_fl_marks(q);
40,050✔
1212
        }
1213
      }
1214
    }
1215

1216
    GC_VERBOSE_LOG_PRINTF("Bytes recovered before sweep - f.l. count = %ld\n",
24,117✔
1217
                          (long)GC_bytes_found);
1218

1219
    /* Reconstruct free lists to contain everything not marked */
1220
    GC_start_reclaim(FALSE);
24,117✔
1221
    GC_DBGLOG_PRINTF("In-use heap: %d%% (%lu KiB pointers + %lu KiB other)\n",
24,117✔
1222
                     GC_compute_heap_usage_percent(),
1223
                     TO_KiB_UL(GC_composite_in_use),
×
1224
                     TO_KiB_UL(GC_atomic_in_use));
×
1225
    if (GC_is_full_gc) {
24,117✔
1226
        GC_used_heap_size_after_full = USED_HEAP_SIZE;
10,792✔
1227
        GC_need_full_gc = FALSE;
10,792✔
1228
    } else {
1229
        GC_need_full_gc = USED_HEAP_SIZE - GC_used_heap_size_after_full
26,650✔
1230
                            > min_bytes_allocd();
13,325✔
1231
    }
1232

1233
    GC_VERBOSE_LOG_PRINTF("Immediately reclaimed %ld bytes, heapsize:"
24,117✔
1234
                          " %lu bytes" IF_USE_MUNMAP(" (%lu unmapped)") "\n",
1235
                          (long)GC_bytes_found,
1236
                          (unsigned long)GC_heapsize /*, */
×
1237
                          COMMA_IF_USE_MUNMAP((unsigned long)
×
1238
                                              GC_unmapped_bytes));
1239

1240
    /* Reset or increment counters for next cycle */
1241
    GC_n_attempts = 0;
24,117✔
1242
    GC_is_full_gc = FALSE;
24,117✔
1243
    GC_bytes_allocd_before_gc += GC_bytes_allocd;
24,117✔
1244
    GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
24,117✔
1245
    GC_bytes_allocd = 0;
24,117✔
1246
    GC_bytes_dropped = 0;
24,117✔
1247
    GC_bytes_freed = 0;
24,117✔
1248
    GC_finalizer_bytes_freed = 0;
24,117✔
1249

1250
    IF_USE_MUNMAP(GC_unmap_old());
24,117✔
1251

1252
    if (GC_on_collection_event)
24,117✔
1253
      GC_on_collection_event(GC_EVENT_RECLAIM_END);
×
1254
#   ifndef NO_CLOCK
1255
      if (GC_print_stats) {
24,117✔
1256
        CLOCK_TYPE done_time;
1257

1258
        GET_TIME(done_time);
×
1259
#       if !defined(SMALL_CONFIG) && !defined(GC_NO_FINALIZATION)
1260
          /* A convenient place to output finalization statistics.      */
1261
          GC_print_finalization_stats();
×
1262
#       endif
1263
        GC_log_printf("Finalize and initiate sweep took %lu ms %lu ns"
×
1264
                      " + %lu ms %lu ns\n",
1265
                      MS_TIME_DIFF(finalize_time, start_time),
×
1266
                      NS_FRAC_TIME_DIFF(finalize_time, start_time),
×
1267
                      MS_TIME_DIFF(done_time, finalize_time),
×
1268
                      NS_FRAC_TIME_DIFF(done_time, finalize_time));
×
1269
      }
1270
#   elif !defined(SMALL_CONFIG) && !defined(GC_NO_FINALIZATION)
1271
      if (GC_print_stats)
1272
        GC_print_finalization_stats();
1273
#   endif
1274
}
24,117✔
1275

1276
STATIC word GC_heapsize_at_forced_unmap = 0;
1277
                                /* accessed with the allocation lock held */
1278

1279
/* If stop_func == 0 then GC_default_stop_func is used instead.         */
1280
STATIC GC_bool GC_try_to_collect_general(GC_stop_func stop_func,
2,426✔
1281
                                         GC_bool force_unmap)
1282
{
1283
    GC_bool result;
1284
    IF_USE_MUNMAP(int old_unmap_threshold;)
1285
    IF_CANCEL(int cancel_state;)
1286
    DCL_LOCK_STATE;
1287

1288
    if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
2,426✔
1289
    if (GC_debugging_started) GC_print_all_smashed();
2,426✔
1290
    GC_INVOKE_FINALIZERS();
2,426✔
1291
    LOCK();
2,426✔
1292
    if (force_unmap) {
2,426✔
1293
      /* Record current heap size to make heap growth more conservative */
1294
      /* afterwards (as if the heap is growing from zero size again).   */
1295
      GC_heapsize_at_forced_unmap = GC_heapsize;
×
1296
    }
1297
    DISABLE_CANCEL(cancel_state);
2,426✔
1298
#   ifdef USE_MUNMAP
1299
      old_unmap_threshold = GC_unmap_threshold;
2,426✔
1300
      if (force_unmap ||
4,852✔
1301
          (GC_force_unmap_on_gcollect && old_unmap_threshold > 0))
2,426✔
1302
        GC_unmap_threshold = 1; /* unmap as much as possible */
×
1303
#   endif
1304
    ENTER_GC();
2,426✔
1305
    /* Minimize junk left in my registers */
1306
      GC_noop6(0,0,0,0,0,0);
2,426✔
1307
    result = GC_try_to_collect_inner(stop_func != 0 ? stop_func :
2,426✔
1308
                                     GC_default_stop_func);
1309
    EXIT_GC();
2,429✔
1310
    IF_USE_MUNMAP(GC_unmap_threshold = old_unmap_threshold); /* restore */
2,429✔
1311
    RESTORE_CANCEL(cancel_state);
2,429✔
1312
    UNLOCK();
2,429✔
1313
    if (result) {
2,428✔
1314
        if (GC_debugging_started) GC_print_all_smashed();
2,428✔
1315
        GC_INVOKE_FINALIZERS();
2,428✔
1316
    }
1317
    return(result);
2,428✔
1318
}
1319

1320
/* Externally callable routines to invoke full, stop-the-world collection. */
1321

1322
GC_API int GC_CALL GC_try_to_collect(GC_stop_func stop_func)
×
1323
{
1324
    GC_ASSERT(NONNULL_ARG_NOT_NULL(stop_func));
×
1325
    return (int)GC_try_to_collect_general(stop_func, FALSE);
×
1326
}
1327

1328
GC_API void GC_CALL GC_gcollect(void)
2,426✔
1329
{
1330
    /* 0 is passed as stop_func to get GC_default_stop_func value       */
1331
    /* while holding the allocation lock (to prevent data races).       */
1332
    (void)GC_try_to_collect_general(0, FALSE);
2,426✔
1333
    if (get_have_errors())
2,428✔
1334
      GC_print_all_errors();
56✔
1335
}
2,428✔
1336

1337
GC_API void GC_CALL GC_gcollect_and_unmap(void)
×
1338
{
1339
    /* Collect and force memory unmapping to OS. */
1340
    (void)GC_try_to_collect_general(GC_never_stop_func, TRUE);
×
1341
}
×
1342

1343
#ifdef USE_PROC_FOR_LIBRARIES
1344
  /* Add HBLKSIZE aligned, GET_MEM-generated block to GC_our_memory. */
1345
  GC_INNER void GC_add_to_our_memory(ptr_t p, size_t bytes)
1346
  {
1347
    GC_ASSERT(p != NULL);
1348
    if (GC_n_memory >= MAX_HEAP_SECTS)
1349
      ABORT("Too many GC-allocated memory sections: Increase MAX_HEAP_SECTS");
1350
    GC_our_memory[GC_n_memory].hs_start = p;
1351
    GC_our_memory[GC_n_memory].hs_bytes = bytes;
1352
    GC_n_memory++;
1353
    GC_our_mem_bytes += bytes;
1354
  }
1355
#endif
1356

1357
/* Use the chunk of memory starting at p of size bytes as part of the heap. */
1358
/* Assumes p is HBLKSIZE aligned, bytes argument is a multiple of HBLKSIZE. */
1359
STATIC void GC_add_to_heap(struct hblk *p, size_t bytes)
827✔
1360
{
1361
    hdr * phdr;
1362
    word endp;
1363
    size_t old_capacity = 0;
827✔
1364
    void *old_heap_sects = NULL;
827✔
1365
#   ifdef GC_ASSERTIONS
1366
      unsigned i;
1367
#   endif
1368

1369
    GC_ASSERT((word)p % HBLKSIZE == 0);
827✔
1370
    GC_ASSERT(bytes % HBLKSIZE == 0);
827✔
1371
    GC_ASSERT(bytes > 0);
827✔
1372
    GC_ASSERT(GC_all_nils != NULL);
827✔
1373

1374
    if (GC_n_heap_sects == GC_capacity_heap_sects) {
827✔
1375
      /* Allocate new GC_heap_sects with sufficient capacity.   */
1376
#     ifndef INITIAL_HEAP_SECTS
1377
#       define INITIAL_HEAP_SECTS 32
1378
#     endif
1379
      size_t new_capacity = GC_n_heap_sects > 0 ?
66✔
1380
                (size_t)GC_n_heap_sects * 2 : INITIAL_HEAP_SECTS;
33✔
1381
      void *new_heap_sects =
33✔
1382
                GC_scratch_alloc(new_capacity * sizeof(struct HeapSect));
33✔
1383

1384
      if (EXPECT(NULL == new_heap_sects, FALSE)) {
33✔
1385
        /* Retry with smaller yet sufficient capacity.  */
1386
        new_capacity = (size_t)GC_n_heap_sects + INITIAL_HEAP_SECTS;
×
1387
        new_heap_sects =
×
1388
                GC_scratch_alloc(new_capacity * sizeof(struct HeapSect));
×
1389
        if (NULL == new_heap_sects)
×
1390
          ABORT("Insufficient memory for heap sections");
×
1391
      }
1392
      old_capacity = GC_capacity_heap_sects;
33✔
1393
      old_heap_sects = GC_heap_sects;
33✔
1394
      /* Transfer GC_heap_sects contents to the newly allocated array.  */
1395
      if (GC_n_heap_sects > 0)
33✔
1396
        BCOPY(old_heap_sects, new_heap_sects,
2✔
1397
              GC_n_heap_sects * sizeof(struct HeapSect));
1398
      GC_capacity_heap_sects = new_capacity;
33✔
1399
      GC_heap_sects = (struct HeapSect *)new_heap_sects;
33✔
1400
      GC_COND_LOG_PRINTF("Grew heap sections array to %lu elements\n",
33✔
1401
                         (unsigned long)new_capacity);
1402
    }
1403

1404
    while ((word)p <= HBLKSIZE) {
1,654✔
1405
        /* Can't handle memory near address zero. */
1406
        ++p;
×
1407
        bytes -= HBLKSIZE;
×
1408
        if (0 == bytes) return;
×
1409
    }
1410
    endp = (word)p + bytes;
827✔
1411
    if (endp <= (word)p) {
827✔
1412
        /* Address wrapped. */
1413
        bytes -= HBLKSIZE;
×
1414
        if (0 == bytes) return;
×
1415
        endp -= HBLKSIZE;
×
1416
    }
1417
    phdr = GC_install_header(p);
827✔
1418
    if (0 == phdr) {
827✔
1419
        /* This is extremely unlikely. Can't add it.  This will         */
1420
        /* almost certainly result in a 0 return from the allocator,    */
1421
        /* which is entirely appropriate.                               */
1422
        return;
×
1423
    }
1424
    GC_ASSERT(endp > (word)p && endp == (word)p + bytes);
827✔
1425
#   ifdef GC_ASSERTIONS
1426
      /* Ensure no intersection between sections.       */
1427
      for (i = 0; i < GC_n_heap_sects; i++) {
10,880✔
1428
        word hs_start = (word)GC_heap_sects[i].hs_start;
10,053✔
1429
        word hs_end = hs_start + GC_heap_sects[i].hs_bytes;
10,053✔
1430
        word p_e = (word)p + bytes;
10,053✔
1431

1432
        GC_ASSERT(!((hs_start <= (word)p && (word)p < hs_end)
10,053✔
1433
                    || (hs_start < p_e && p_e <= hs_end)
1434
                    || ((word)p < hs_start && hs_end < p_e)));
1435
      }
1436
#   endif
1437
    GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
827✔
1438
    GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
827✔
1439
    GC_n_heap_sects++;
827✔
1440
    phdr -> hb_sz = bytes;
827✔
1441
    phdr -> hb_flags = 0;
827✔
1442
    GC_freehblk(p);
827✔
1443
    GC_heapsize += bytes;
827✔
1444

1445
    /* Normally the caller calculates a new GC_collect_at_heapsize,
1446
     * but this is also called directly from GC_scratch_recycle_inner, so
1447
     * adjust here. It will be recalculated when called from
1448
     * GC_expand_hp_inner.
1449
     */
1450
    GC_collect_at_heapsize += bytes;
827✔
1451
    if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
827✔
1452
       GC_collect_at_heapsize = GC_WORD_MAX;
31✔
1453

1454
    if ((word)p <= (word)GC_least_plausible_heap_addr
827✔
1455
        || GC_least_plausible_heap_addr == 0) {
787✔
1456
        GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word));
40✔
1457
                /* Making it a little smaller than necessary prevents   */
1458
                /* us from getting a false hit from the variable        */
1459
                /* itself.  There's some unintentional reflection       */
1460
                /* here.                                                */
1461
    }
1462
    if ((word)p + bytes >= (word)GC_greatest_plausible_heap_addr) {
827✔
1463
        GC_greatest_plausible_heap_addr = (void *)endp;
×
1464
    }
1465

1466
    if (old_capacity > 0) {
827✔
1467
#     ifndef GWW_VDB
1468
        /* Recycling may call GC_add_to_heap() again but should not     */
1469
        /* cause resizing of GC_heap_sects.                             */
1470
        GC_scratch_recycle_no_gww(old_heap_sects,
2✔
1471
                                  old_capacity * sizeof(struct HeapSect));
1472
#     else
1473
        /* TODO: implement GWW-aware recycling as in alloc_mark_stack */
1474
        GC_noop1((word)old_heap_sects);
1475
#     endif
1476
    }
1477
}
1478

1479
#if !defined(NO_DEBUGGING)
1480
  void GC_print_heap_sects(void)
×
1481
  {
1482
    unsigned i;
1483

1484
    GC_printf("Total heap size: %lu" IF_USE_MUNMAP(" (%lu unmapped)") "\n",
×
1485
              (unsigned long)GC_heapsize /*, */
×
1486
              COMMA_IF_USE_MUNMAP((unsigned long)GC_unmapped_bytes));
×
1487

1488
    for (i = 0; i < GC_n_heap_sects; i++) {
×
1489
      ptr_t start = GC_heap_sects[i].hs_start;
×
1490
      size_t len = GC_heap_sects[i].hs_bytes;
×
1491
      struct hblk *h;
1492
      unsigned nbl = 0;
×
1493

1494
      for (h = (struct hblk *)start; (word)h < (word)(start + len); h++) {
×
1495
        if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
×
1496
      }
1497
      GC_printf("Section %d from %p to %p %u/%lu blacklisted\n",
×
1498
                i, (void *)start, (void *)&start[len],
1499
                nbl, (unsigned long)divHBLKSZ(len));
×
1500
    }
1501
  }
×
1502
#endif
1503

1504
void * GC_least_plausible_heap_addr = (void *)GC_WORD_MAX;
1505
void * GC_greatest_plausible_heap_addr = 0;
1506

1507
GC_INLINE word GC_max(word x, word y)
36✔
1508
{
1509
    return(x > y? x : y);
36✔
1510
}
1511

1512
GC_INLINE word GC_min(word x, word y)
564✔
1513
{
1514
    return(x < y? x : y);
564✔
1515
}
1516

1517
STATIC word GC_max_heapsize = 0;
1518

1519
GC_API void GC_CALL GC_set_max_heap_size(GC_word n)
2✔
1520
{
1521
    GC_max_heapsize = n;
2✔
1522
}
2✔
1523

1524
GC_word GC_max_retries = 0;
1525

1526
GC_INNER void GC_scratch_recycle_inner(void *ptr, size_t bytes)
229✔
1527
{
1528
  size_t page_offset;
1529
  size_t displ = 0;
229✔
1530
  size_t recycled_bytes;
1531

1532
  if (NULL == ptr) return;
229✔
1533

1534
  GC_ASSERT(bytes != 0);
229✔
1535
  GC_ASSERT(GC_page_size != 0);
229✔
1536
  /* TODO: Assert correct memory flags if GWW_VDB */
1537
  page_offset = (word)ptr & (GC_page_size - 1);
229✔
1538
  if (page_offset != 0)
229✔
1539
    displ = GC_page_size - page_offset;
×
1540
  recycled_bytes = bytes > displ ? (bytes - displ) & ~(GC_page_size - 1) : 0;
229✔
1541
  GC_COND_LOG_PRINTF("Recycle %lu/%lu scratch-allocated bytes at %p\n",
229✔
1542
                (unsigned long)recycled_bytes, (unsigned long)bytes, ptr);
1543
  if (recycled_bytes > 0)
229✔
1544
    GC_add_to_heap((struct hblk *)((word)ptr + displ), recycled_bytes);
227✔
1545
}
1546

1547
/* This explicitly increases the size of the heap.  It is used          */
1548
/* internally, but may also be invoked from GC_expand_hp by the user.   */
1549
/* The argument is in units of HBLKSIZE (tiny values are rounded up).   */
1550
/* Returns FALSE on failure.                                            */
1551
GC_INNER GC_bool GC_expand_hp_inner(word n)
626✔
1552
{
1553
    size_t bytes;
1554
    struct hblk * space;
1555
    word expansion_slop;        /* Number of bytes by which we expect   */
1556
                                /* the heap to expand soon.             */
1557

1558
    GC_ASSERT(I_HOLD_LOCK());
626✔
1559
    GC_ASSERT(GC_page_size != 0);
626✔
1560
    if (n < MINHINCR) n = MINHINCR;
626✔
1561
    bytes = ROUNDUP_PAGESIZE((size_t)n * HBLKSIZE);
626✔
1562
    if (GC_max_heapsize != 0
626✔
1563
        && (GC_max_heapsize < (word)bytes
30✔
1564
            || GC_heapsize > GC_max_heapsize - (word)bytes)) {
4✔
1565
        /* Exceeded self-imposed limit */
1566
        return(FALSE);
26✔
1567
    }
1568
    space = GET_MEM(bytes);
600✔
1569
    if (EXPECT(NULL == space, FALSE)) {
600✔
1570
        WARN("Failed to expand heap by %" WARN_PRIuPTR " KiB\n", bytes >> 10);
×
1571
        return(FALSE);
×
1572
    }
1573
    GC_add_to_our_memory((ptr_t)space, bytes);
600✔
1574
    GC_INFOLOG_PRINTF("Grow heap to %lu KiB after %lu bytes allocated\n",
600✔
1575
                      TO_KiB_UL(GC_heapsize + bytes),
×
1576
                      (unsigned long)GC_bytes_allocd);
×
1577

1578
    /* Adjust heap limits generously for blacklisting to work better.   */
1579
    /* GC_add_to_heap performs minimal adjustment needed for            */
1580
    /* correctness.                                                     */
1581
    expansion_slop = min_bytes_allocd() + 4 * MAXHINCR * HBLKSIZE;
600✔
1582
    if ((GC_last_heap_addr == 0 && !((word)space & SIGNB))
600✔
1583
        || (GC_last_heap_addr != 0
569✔
1584
            && (word)GC_last_heap_addr < (word)space)) {
605✔
1585
        /* Assume the heap is growing up. */
1586
        word new_limit = (word)space + (word)bytes + expansion_slop;
36✔
1587
        if (new_limit > (word)space) {
36✔
1588
          GC_greatest_plausible_heap_addr =
36✔
1589
            (void *)GC_max((word)GC_greatest_plausible_heap_addr,
36✔
1590
                           (word)new_limit);
1591
        }
1592
    } else {
1593
        /* Heap is growing down. */
1594
        word new_limit = (word)space - expansion_slop;
564✔
1595
        if (new_limit < (word)space) {
564✔
1596
          GC_least_plausible_heap_addr =
564✔
1597
            (void *)GC_min((word)GC_least_plausible_heap_addr,
564✔
1598
                           (word)space - expansion_slop);
564✔
1599
        }
1600
    }
1601
    GC_last_heap_addr = (ptr_t)space;
600✔
1602

1603
    GC_add_to_heap(space, bytes);
600✔
1604

1605
    /* Force GC before we are likely to allocate past expansion_slop.   */
1606
    GC_collect_at_heapsize =
600✔
1607
        GC_heapsize + expansion_slop - 2 * MAXHINCR * HBLKSIZE;
600✔
1608
    if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
600✔
1609
        GC_collect_at_heapsize = GC_WORD_MAX;
×
1610
    if (GC_on_heap_resize)
600✔
1611
        (*GC_on_heap_resize)(GC_heapsize);
×
1612

1613
    return(TRUE);
600✔
1614
}
1615

1616
/* Really returns a bool, but it's externally visible, so that's clumsy. */
1617
/* The argument is in bytes.  Includes GC_init() call.                   */
1618
GC_API int GC_CALL GC_expand_hp(size_t bytes)
2✔
1619
{
1620
    int result;
1621
    DCL_LOCK_STATE;
1622

1623
    if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
2✔
1624
    LOCK();
2✔
1625
    result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
2✔
1626
    if (result) GC_requested_heapsize += bytes;
2✔
1627
    UNLOCK();
2✔
1628
    return(result);
2✔
1629
}
1630

1631
GC_INNER unsigned GC_fail_count = 0;
1632
                        /* How many consecutive GC/expansion failures?  */
1633
                        /* Reset by GC_allochblk.                       */
1634

1635
/* The minimum value of the ratio of allocated bytes since the latest   */
1636
/* GC to the amount of finalizers created since that GC which triggers  */
1637
/* the collection instead heap expansion.  Has no effect in the         */
1638
/* incremental mode.                                                    */
1639
#if defined(GC_ALLOCD_BYTES_PER_FINALIZER) && !defined(CPPCHECK)
1640
  STATIC word GC_allocd_bytes_per_finalizer = GC_ALLOCD_BYTES_PER_FINALIZER;
1641
#else
1642
  STATIC word GC_allocd_bytes_per_finalizer = 10000;
1643
#endif
1644

1645
GC_API void GC_CALL GC_set_allocd_bytes_per_finalizer(GC_word value)
2✔
1646
{
1647
  GC_allocd_bytes_per_finalizer = value;
2✔
1648
}
2✔
1649

1650
GC_API GC_word GC_CALL GC_get_allocd_bytes_per_finalizer(void)
2✔
1651
{
1652
  return GC_allocd_bytes_per_finalizer;
2✔
1653
}
1654

1655
static word last_fo_entries = 0;
1656
static word last_bytes_finalized = 0;
1657

1658
/* Collect or expand heap in an attempt make the indicated number of    */
1659
/* free blocks available.  Should be called until the blocks are        */
1660
/* available (setting retry value to TRUE unless this is the first call */
1661
/* in a loop) or until it fails by returning FALSE.                     */
1662
GC_INNER GC_bool GC_collect_or_expand(word needed_blocks,
7,772✔
1663
                                      GC_bool ignore_off_page,
1664
                                      GC_bool retry)
1665
{
1666
    GC_bool gc_not_stopped = TRUE;
7,772✔
1667
    word blocks_to_get;
1668
    IF_CANCEL(int cancel_state;)
1669

1670
    GC_ASSERT(I_HOLD_LOCK());
7,772✔
1671
    DISABLE_CANCEL(cancel_state);
7,772✔
1672
    if (!GC_incremental && !GC_dont_gc &&
15,027✔
1673
        ((GC_dont_expand && GC_bytes_allocd > 0)
7,255✔
1674
         || (GC_fo_entries > last_fo_entries
7,255✔
1675
             && (last_bytes_finalized | GC_bytes_finalized) != 0
334✔
1676
             && (GC_fo_entries - last_fo_entries)
644✔
1677
                * GC_allocd_bytes_per_finalizer > GC_bytes_allocd)
322✔
1678
         || GC_should_collect())) {
6,933✔
1679
      /* Try to do a full collection using 'default' stop_func (unless  */
1680
      /* nothing has been allocated since the latest collection or heap */
1681
      /* expansion is disabled).                                        */
1682
      gc_not_stopped = GC_try_to_collect_inner(
14,369✔
1683
                        GC_bytes_allocd > 0 && (!GC_dont_expand || !retry) ?
14,369✔
1684
                        GC_default_stop_func : GC_never_stop_func);
1685
      if (gc_not_stopped == TRUE || !retry) {
7,187✔
1686
        /* Either the collection hasn't been aborted or this is the     */
1687
        /* first attempt (in a loop).                                   */
1688
        last_fo_entries = GC_fo_entries;
7,187✔
1689
        last_bytes_finalized = GC_bytes_finalized;
7,187✔
1690
        RESTORE_CANCEL(cancel_state);
7,187✔
1691
        return(TRUE);
14,959✔
1692
      }
1693
    }
1694

1695
    blocks_to_get = (GC_heapsize - GC_heapsize_at_forced_unmap)
1,170✔
1696
                        / (HBLKSIZE * GC_free_space_divisor)
585✔
1697
                    + needed_blocks;
1698
    if (blocks_to_get > MAXHINCR) {
585✔
1699
      word slop;
1700

1701
      /* Get the minimum required to make it likely that we can satisfy */
1702
      /* the current request in the presence of black-listing.          */
1703
      /* This will probably be more than MAXHINCR.                      */
1704
      if (ignore_off_page) {
43✔
1705
        slop = 4;
×
1706
      } else {
1707
        slop = 2 * divHBLKSZ(BL_LIMIT);
43✔
1708
        if (slop > needed_blocks) slop = needed_blocks;
43✔
1709
      }
1710
      if (needed_blocks + slop > MAXHINCR) {
43✔
1711
        blocks_to_get = needed_blocks + slop;
18✔
1712
      } else {
1713
        blocks_to_get = MAXHINCR;
25✔
1714
      }
1715
      if (blocks_to_get > divHBLKSZ(GC_WORD_MAX))
43✔
1716
        blocks_to_get = divHBLKSZ(GC_WORD_MAX);
10✔
1717
    }
1718

1719
    if (!GC_expand_hp_inner(blocks_to_get)
585✔
1720
        && (blocks_to_get == needed_blocks
18✔
1721
            || !GC_expand_hp_inner(needed_blocks))) {
8✔
1722
      if (gc_not_stopped == FALSE) {
18✔
1723
        /* Don't increment GC_fail_count here (and no warning).     */
1724
        GC_gcollect_inner();
×
1725
        GC_ASSERT(GC_bytes_allocd == 0);
×
1726
      } else if (GC_fail_count++ < GC_max_retries) {
18✔
1727
        WARN("Out of Memory!  Trying to continue...\n", 0);
×
1728
        GC_gcollect_inner();
×
1729
      } else {
1730
#       if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
1731
#         ifdef USE_MUNMAP
1732
            GC_ASSERT(GC_heapsize >= GC_unmapped_bytes);
18✔
1733
#         endif
1734
          WARN("Out of Memory! Heap size: %" WARN_PRIuPTR " MiB."
18✔
1735
               " Returning NULL!\n", (GC_heapsize - GC_unmapped_bytes) >> 20);
1736
#       endif
1737
        RESTORE_CANCEL(cancel_state);
18✔
1738
        return(FALSE);
18✔
1739
      }
1740
    } else if (GC_fail_count) {
567✔
1741
      GC_COND_LOG_PRINTF("Memory available again...\n");
×
1742
    }
1743
    RESTORE_CANCEL(cancel_state);
567✔
1744
    return(TRUE);
567✔
1745
}
1746

1747
/*
1748
 * Make sure the object free list for size gran (in granules) is not empty.
1749
 * Return a pointer to the first object on the free list.
1750
 * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
1751
 */
1752
GC_INNER ptr_t GC_allocobj(size_t gran, int kind)
961,206✔
1753
{
1754
    void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]);
961,206✔
1755
    GC_bool tried_minor = FALSE;
961,206✔
1756
    GC_bool retry = FALSE;
961,206✔
1757

1758
    GC_ASSERT(I_HOLD_LOCK());
961,206✔
1759
    if (gran == 0) return(0);
961,206✔
1760

1761
    while (*flh == 0) {
2,889,761✔
1762
      ENTER_GC();
967,349✔
1763
#     ifndef GC_DISABLE_INCREMENTAL
1764
        if (GC_incremental && GC_time_limit != GC_TIME_UNLIMITED
967,349✔
1765
            && !GC_dont_gc) {
×
1766
          /* True incremental mode, not just generational.      */
1767
          /* Do our share of marking work.                      */
1768
          GC_collect_a_little_inner(1);
×
1769
        }
1770
#     endif
1771
      /* Sweep blocks for objects of this size */
1772
        GC_ASSERT(!GC_is_full_gc
967,349✔
1773
                  || NULL == GC_obj_kinds[kind].ok_reclaim_list
1774
                  || NULL == GC_obj_kinds[kind].ok_reclaim_list[gran]);
1775
        GC_continue_reclaim(gran, kind);
967,349✔
1776
      EXIT_GC();
967,349✔
1777
#     if defined(CPPCHECK)
1778
        GC_noop1((word)&flh);
1779
#     endif
1780
      if (NULL == *flh) {
967,349✔
1781
        GC_new_hblk(gran, kind);
442,082✔
1782
#       if defined(CPPCHECK)
1783
          GC_noop1((word)&flh);
1784
#       endif
1785
        if (NULL == *flh) {
442,082✔
1786
          ENTER_GC();
6,171✔
1787
          if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
6,171✔
1788
              && !tried_minor && !GC_dont_gc) {
939✔
1789
            GC_collect_a_little_inner(1);
476✔
1790
            tried_minor = TRUE;
476✔
1791
          } else {
1792
            if (!GC_collect_or_expand(1, FALSE, retry)) {
5,695✔
1793
              EXIT_GC();
×
1794
              return(0);
×
1795
            }
1796
            retry = TRUE;
5,695✔
1797
          }
1798
          EXIT_GC();
6,171✔
1799
        }
1800
      }
1801
    }
1802
    /* Successful allocation; reset failure count.      */
1803
    GC_fail_count = 0;
961,206✔
1804

1805
    return (ptr_t)(*flh);
961,206✔
1806
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc