v2 / thirdparty / libgc / include / gc / gc.h
2826 lines · 2559 sloc · 120.7 KB · 58073f929fd40859d75b47f3936a062386d2773d
Raw
1/*
2 * Copyright (c) 1988-1989 Hans-J. Boehm, Alan J. Demers
3 * Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved.
4 * Copyright (c) 1996-1999 by Silicon Graphics. All rights reserved.
5 * Copyright (c) 1999 by Hewlett-Packard Company. All rights reserved.
6 * Copyright (c) 2007 Free Software Foundation, Inc.
7 * Copyright (c) 2000-2011 by Hewlett-Packard Development Company.
8 * Copyright (c) 2009-2025 Ivan Maidanski
9 *
10 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
11 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
12 *
13 * Permission is hereby granted to use or copy this program
14 * for any purpose, provided the above notices are retained on all copies.
15 * Permission to modify the code and to distribute modified code is granted,
16 * provided the above notices are retained, and a notice that the code was
17 * modified is included with the above copyright notice.
18 */
19
20/*
21 * Note that this defines a large number of tuning hooks, which can
22 * safely be ignored in nearly all cases. For normal use it suffices
23 * to call only `GC_MALLOC` and, perhaps, `GC_REALLOC`.
24 * For better performance, also look at `GC_MALLOC_ATOMIC`, and
25 * `GC_enable_incremental`. If you need an action to be performed
26 * immediately before an object is collected, look at `GC_register_finalizer`.
27 * Everything else is best ignored unless you encounter performance
28 * problems.
29 */
30
31#ifndef GC_H
32#define GC_H
33
34/* Help debug mixed up preprocessor symbols. */
35#if defined(WIN64) && !defined(_WIN64) && defined(_MSC_VER)
36# pragma message("Warning: Expecting _WIN64 for x64 targets!")
37#endif
38
39/*
40 * Define version numbers here to allow test on build machine for
41 * cross-builds. Note that this defines the header version number,
42 * which may or may not match that of the dynamic library.
43 * `GC_get_version()` can be used to obtain the latter.
44 */
45#include "gc_version.h"
46
47#include "gc_config_macros.h"
48
49#ifdef __cplusplus
50extern "C" {
51#endif
52
53typedef void *GC_PTR; /*< preserved only for backward compatibility */
54
55/**
56 * Define public `word` and `signed_word` to be unsigned and signed types
57 * of the size same as of `size_t`, `ptrdiff_t`, and of the address part
58 * of data pointers (like `char *` and `void *`).
59 */
60typedef GC_UNSIGNEDWORD GC_word;
61typedef GC_SIGNEDWORD GC_signed_word;
62#undef GC_SIGNEDWORD
63#undef GC_UNSIGNEDWORD
64
65#if (defined(_UINTPTR_T) || defined(_UINTPTR_T_DECLARED) \
66 || defined(_UINTPTR_T_DEFINED)) \
67 && !defined(__CYGWIN__) && !defined(__MSYS__)
68/* Note: Cygwin and MSYS2 might provide `__uintptr_t` but not `uintptr_t`. */
69typedef uintptr_t GC_uintptr_t;
70#else
71typedef GC_word GC_uintptr_t;
72#endif
73
74/**
75 * Is first pointer has a smaller address than the second one?
76 * The arguments should be of the same pointer type, e.g. of `char *` type.
77 * Ancient compilers might treat a pointer as a signed value, thus we
78 * need a cast to unsigned `word` of each compared pointer.
79 */
80#if defined(__GNUC__) && !defined(__CHERI_PURE_CAPABILITY__)
81# define GC_ADDR_LT(p, q) ((p) < (q))
82#else
83# define GC_ADDR_LT(p, q) \
84 ((GC_word)(GC_uintptr_t)(p) < (GC_word)(GC_uintptr_t)(q))
85#endif
86
87/**
88 * Get the collector library version. The returned value is a constant
89 * in the form:
90 * `((version_major << 16) | (version_minor << 8) | version_micro)`.
91 */
92GC_API GC_VERSION_VAL_T GC_CALL GC_get_version(void);
93
94/*
95 * Public read-only variables. The supplied getter functions are
96 * preferred for new client code.
97 */
98
99/**
100 * Counter incremented once per collection. Includes empty collections
101 * at startup. `GC_get_gc_no()` is unsynchronized, so it requires
102 * `GC_call_with_reader_lock()` to avoid data race on multiprocessors.
103 */
104GC_API GC_ATTR_DEPRECATED GC_word GC_gc_no;
105GC_API GC_word GC_CALL GC_get_gc_no(void);
106
107#ifdef GC_THREADS
108/**
109 * GC is parallelized for performance on multiprocessors.
110 * Set to a nonzero value when client calls `GC_start_mark_threads()`
111 * directly or starts the first non-main thread, provided the
112 * collector is built with `PARALLEL_MARK` macro defined, and either
113 * `GC_MARKERS` (or `GC_NPROCS`) environment variable is set to a value
114 * bigger than 1, or multiple cores (processors) are available, or
115 * the client calls `GC_set_markers_count()` before the collector
116 * initialization. After setting, `GC_parallel` value is equal to the
117 * number of marker threads minus one (i.e. the number of existing
118 * parallel marker threads excluding the initiating one).
119 */
120GC_API GC_ATTR_DEPRECATED int GC_parallel;
121#endif
122
123/** Return value of `GC_parallel`. Does not acquire the allocator lock. */
124GC_API int GC_CALL GC_get_parallel(void);
125
126/**
127 * Set the number of marker threads (including the initiating one)
128 * to the desired value at start-up. Zero value means the collector
129 * is to decide. If the correct nonzero value is passed, then
130 * `GC_parallel` will be set to the value minus one later. Has no effect
131 * if called after the collector initialization. Does not itself cause
132 * creation of the marker threads. Does not use any synchronization.
133 */
134GC_API void GC_CALL GC_set_markers_count(unsigned);
135
136/*
137 * Public R/W variables. The supplied setter and getter functions are
138 * preferred for new client code.
139 */
140
141/**
142 * When there is insufficient memory to satisfy an allocation request,
143 * we return `(*GC_oom_fn)(size)`. If it returns, it must return either
144 * `NULL` or a valid pointer to a previously allocated heap object.
145 * By default, this just returns `NULL`. If it points to a function which
146 * never returns `NULL`, probably by aborting the program instead, then
147 * invocations of `GC_MALLOC()` and friends (that are additionally marked
148 * as "never returning NULL unless GC_oom_fn returns NULL") do not need to
149 * be followed by code that checks for the `NULL` result.
150 * `GC_oom_fn` must not be 0. Both the setter and the getter acquire
151 * the allocator lock (in the reader mode in case of the getter) to
152 * avoid data race.
153 */
154typedef void *(GC_CALLBACK *GC_oom_func)(size_t /* `bytes_requested` */);
155GC_API GC_ATTR_DEPRECATED GC_oom_func GC_oom_fn;
156GC_API void GC_CALL GC_set_oom_fn(GC_oom_func) GC_ATTR_NONNULL(1);
157GC_API GC_oom_func GC_CALL GC_get_oom_fn(void);
158
159/**
160 * Invoked when the heap grows or shrinks. Called with the world
161 * stopped (and the allocator lock held). May be 0. Both the setter
162 * and the getter acquire the allocator lock (in the reader mode in
163 * case of the getter).
164 */
165typedef void(GC_CALLBACK *GC_on_heap_resize_proc)(GC_word /* new_size */);
166GC_API GC_ATTR_DEPRECATED GC_on_heap_resize_proc GC_on_heap_resize;
167GC_API void GC_CALL GC_set_on_heap_resize(GC_on_heap_resize_proc);
168GC_API GC_on_heap_resize_proc GC_CALL GC_get_on_heap_resize(void);
169
170typedef enum {
171 GC_EVENT_START, /*< start collection */
172 GC_EVENT_MARK_START,
173 GC_EVENT_MARK_END,
174 GC_EVENT_RECLAIM_START,
175 GC_EVENT_RECLAIM_END,
176 GC_EVENT_END, /*< end collection */
177 GC_EVENT_PRE_STOP_WORLD, /*< begin stopping world */
178 GC_EVENT_POST_STOP_WORLD, /*< end stopping world */
179 GC_EVENT_PRE_START_WORLD, /*< begin restarting world */
180 GC_EVENT_POST_START_WORLD, /*< end restarting world */
181 GC_EVENT_THREAD_SUSPENDED,
182 GC_EVENT_THREAD_UNSUSPENDED
183} GC_EventType;
184
185/**
186 * Invoked to indicate progress through the collection process.
187 * Not used for thread suspend/resume notifications. Called with the
188 * allocator lock held (or, even, the world stopped). May be 0 (means
189 * no notifier). Both the setter and the getter acquire the allocator
190 * lock (in the reader mode in case of the getter).
191 */
192typedef void(GC_CALLBACK *GC_on_collection_event_proc)(GC_EventType);
193GC_API void GC_CALL GC_set_on_collection_event(GC_on_collection_event_proc);
194GC_API GC_on_collection_event_proc GC_CALL GC_get_on_collection_event(void);
195
196#ifdef GC_THREADS
197/**
198 * Invoked when a thread is suspended or resumed during collection.
199 * Called with the allocator lock held (and the world stopped partially).
200 * May be 0 (means no notifier). Both the setter and the getter acquire
201 * the allocator lock (in the reader mode in case of the getter).
202 */
203typedef void(GC_CALLBACK *GC_on_thread_event_proc)(GC_EventType,
204 void * /* `thread_id` */);
205GC_API void GC_CALL GC_set_on_thread_event(GC_on_thread_event_proc);
206GC_API GC_on_thread_event_proc GC_CALL GC_get_on_thread_event(void);
207#endif
208
209/**
210 * Turn on the find-leak mode (do not actually garbage collect, but
211 * simply report inaccessible memory that was not deallocated with
212 * `GC_FREE()`). Initial value is determined by `FIND_LEAK` macro.
213 * The value should not typically be modified after the collector
214 * initialization (and, thus, it does not use or need synchronization).
215 * The mode is supported only if the library has been compiled without
216 * `NO_FIND_LEAK` macro defined.
217 */
218GC_API GC_ATTR_DEPRECATED int GC_find_leak;
219GC_API void GC_CALL GC_set_find_leak(int);
220GC_API int GC_CALL GC_get_find_leak(void);
221
222/**
223 * Arrange for pointers to object interiors to be recognized as valid.
224 * Typically should not be changed after the collector initialization
225 * (in case of calling it after the collector is initialized, the
226 * setter acquires the allocator lock). Must be only 0 or 1.
227 * The initial value depends on whether the collector is built with
228 * `ALL_INTERIOR_POINTERS` macro defined or not. This also affects,
229 * unless `GC_get_dont_add_byte_at_end()` returns a nonzero value,
230 * whether the object sizes are increased by at least a byte to allow
231 * "off-the-end" pointer recognition (but the size is not increased
232 * for uncollectible objects as well as for ignore-off-page objects of
233 * at least heap block size).
234 */
235GC_API GC_ATTR_DEPRECATED int GC_all_interior_pointers;
236GC_API void GC_CALL GC_set_all_interior_pointers(int);
237GC_API int GC_CALL GC_get_all_interior_pointers(void);
238
239/**
240 * If nonzero, finalizers will only be run in response to an explicit
241 * `GC_invoke_finalizers()` call. The default is determined by whether
242 * the `FINALIZE_ON_DEMAND` macro is defined when the collector is built.
243 * The setter and the getter are unsynchronized.
244 */
245GC_API GC_ATTR_DEPRECATED int GC_finalize_on_demand;
246GC_API void GC_CALL GC_set_finalize_on_demand(int);
247GC_API int GC_CALL GC_get_finalize_on_demand(void);
248
249/**
250 * Mark objects reachable from finalizable objects in a separate post-pass.
251 * This makes it a bit safer to use non-topologically-ordered finalization.
252 * Default value is determined by `JAVA_FINALIZATION` macro.
253 * Enables `GC_register_finalizer_unreachable()` to work correctly.
254 * The setter and the getter are unsynchronized.
255 */
256GC_API GC_ATTR_DEPRECATED int GC_java_finalization;
257GC_API void GC_CALL GC_set_java_finalization(int);
258GC_API int GC_CALL GC_get_java_finalization(void);
259
260/**
261 * Invoked by the collector when there are objects to be finalized.
262 * Invoked at most once per collection cycle. Never invoked unless
263 * `GC_finalize_on_demand` is set. Typically this will notify
264 * a finalization thread, which will call `GC_invoke_finalizers()` in
265 * response. May be 0 (means no notifier). Both the setter and the getter
266 * acquire the allocator lock (in the reader mode in case of the getter).
267 */
268typedef void(GC_CALLBACK *GC_finalizer_notifier_proc)(void);
269GC_API GC_ATTR_DEPRECATED GC_finalizer_notifier_proc GC_finalizer_notifier;
270GC_API void GC_CALL GC_set_finalizer_notifier(GC_finalizer_notifier_proc);
271GC_API GC_finalizer_notifier_proc GC_CALL GC_get_finalizer_notifier(void);
272
273/**
274 * The functions called to report pointer checking errors. Called without
275 * the allocator lock held. The default behavior is to fail with the
276 * appropriate message which includes the pointers. The functions
277 * (variables) must not be 0. Both the setters and the getters are
278 * unsynchronized.
279 */
280typedef void(GC_CALLBACK *GC_valid_ptr_print_proc_t)(void *);
281typedef void(GC_CALLBACK *GC_same_obj_print_proc_t)(void * /* `p` */,
282 void * /* `q` */);
283GC_API GC_ATTR_DEPRECATED GC_same_obj_print_proc_t GC_same_obj_print_proc;
284GC_API GC_ATTR_DEPRECATED GC_valid_ptr_print_proc_t
285 GC_is_valid_displacement_print_proc;
286GC_API GC_ATTR_DEPRECATED GC_valid_ptr_print_proc_t GC_is_visible_print_proc;
287GC_API void GC_CALL GC_set_same_obj_print_proc(GC_same_obj_print_proc_t)
288 GC_ATTR_NONNULL(1);
289GC_API GC_same_obj_print_proc_t GC_CALL GC_get_same_obj_print_proc(void);
290GC_API void
291 GC_CALL GC_set_is_valid_displacement_print_proc(GC_valid_ptr_print_proc_t)
292 GC_ATTR_NONNULL(1);
293GC_API GC_valid_ptr_print_proc_t GC_CALL
294GC_get_is_valid_displacement_print_proc(void);
295GC_API void GC_CALL GC_set_is_visible_print_proc(GC_valid_ptr_print_proc_t)
296 GC_ATTR_NONNULL(1);
297GC_API GC_valid_ptr_print_proc_t GC_CALL GC_get_is_visible_print_proc(void);
298
299/*
300 * A flag indicating "do not collect" mode. This overrides explicit
301 * `GC_gcollect()` calls as well. Used as a counter, so that nested
302 * enabling and disabling work correctly. Should normally be updated
303 * with `GC_enable()` and `GC_disable()` calls. Direct assignment to
304 * `GC_dont_gc` variable is deprecated. To check whether collections
305 * are disabled, `GC_is_disabled()` is preferred for new code.
306 */
307GC_API
308#ifndef GC_DONT_GC
309GC_ATTR_DEPRECATED
310#endif
311int GC_dont_gc;
312
313/**
314 * Do not expand the heap unless explicitly requested or forced to.
315 * The setter and the getter are unsynchronized.
316 */
317GC_API GC_ATTR_DEPRECATED int GC_dont_expand;
318GC_API void GC_CALL GC_set_dont_expand(int);
319GC_API int GC_CALL GC_get_dont_expand(void);
320
321/**
322 * Causes the non-incremental collector to use the entire heap before
323 * collecting. This sometimes results in more large-block fragmentation,
324 * since very large blocks will tend to get broken up during each
325 * collection cycle. It is likely to result in a larger working set, but
326 * lower collection frequencies, and hence fewer instructions executed in
327 * the collector.
328 */
329GC_API GC_ATTR_DEPRECATED int GC_use_entire_heap;
330
331/**
332 * Number of partial collections between full collections. Matters only
333 * if `GC_is_incremental_mode()`. Full collections are also triggered
334 * if the collector detects a substantial increase in the number of the
335 * in-use heap blocks. Values in the tens are now perfectly reasonable.
336 * The setter and the getter are unsynchronized, so
337 * `GC_call_with_alloc_lock()` (`GC_call_with_reader_lock()` in case
338 * of the getter) is required to avoid data race (if the value is
339 * modified after the collector is put into the multi-threaded mode).
340 */
341GC_API GC_ATTR_DEPRECATED int GC_full_freq;
342GC_API void GC_CALL GC_set_full_freq(int);
343GC_API int GC_CALL GC_get_full_freq(void);
344
345/**
346 * Bytes not considered candidates for collection. Used only to control
347 * scheduling of collections. Updated by `GC_malloc_uncollectable()` and
348 * `GC_free()`. Wizards only. The setter and the getter are unsynchronized,
349 * so `GC_call_with_alloc_lock()` (`GC_call_with_reader_lock()` in case of
350 * the getter) is required to avoid data race (if the value is modified
351 * after the collector is put into the multi-threaded mode).
352 */
353GC_API GC_ATTR_DEPRECATED GC_word GC_non_gc_bytes;
354GC_API void GC_CALL GC_set_non_gc_bytes(GC_word);
355GC_API GC_word GC_CALL GC_get_non_gc_bytes(void);
356
357/**
358 * Do not register dynamic library data segments automatically.
359 * Also, if set by the collector itself (during a collection), this
360 * means that such a registration is not supported. Wizards only.
361 * Should be set only if the client explicitly registers all roots.
362 * (In some environments like Microsoft Windows and Apple's Darwin,
363 * this may also prevent registration of the main data segment as a part
364 * of the root set.) The setter and the getter are unsynchronized.
365 */
366GC_API GC_ATTR_DEPRECATED int GC_no_dls;
367GC_API void GC_CALL GC_set_no_dls(int);
368GC_API int GC_CALL GC_get_no_dls(void);
369
370/**
371 * We try to make sure that we allocate at least
372 * `N / GC_free_space_divisor` bytes between collections, where `N` is
373 * twice the number of traced bytes, plus the number of untraced bytes
374 * (i.e. bytes in the "atomic" objects), plus a rough estimate of the
375 * root set size. `N` approximates GC tracing work per collection.
376 * The initial value is given by `GC_FREE_SPACE_DIVISOR` macro.
377 * Increasing its value will use less space but more collection time.
378 * Decreasing it will appreciably decrease total collection time at the
379 * expense of space. The setter and the getter are unsynchronized, so
380 * `GC_call_with_alloc_lock()` (`GC_call_with_reader_lock()` in case of
381 * the getter) is required to avoid data race (if the value is modified
382 * after the collector is put into the multi-threaded mode).
383 * In GC v7.1 and before, the setter returned the old value.
384 */
385GC_API GC_ATTR_DEPRECATED GC_word GC_free_space_divisor;
386GC_API void GC_CALL GC_set_free_space_divisor(GC_word);
387GC_API GC_word GC_CALL GC_get_free_space_divisor(void);
388
389/**
390 * The maximum number of collections attempted before reporting out of
391 * memory after heap expansion fails. Initially 0. The setter and
392 * getter are unsynchronized, so `GC_call_with_alloc_lock()`
393 * (`GC_call_with_reader_lock()` in case of the getter) is required to
394 * avoid data race (if the value is modified after the collector is put
395 * into the multi-threaded mode).
396 */
397GC_API GC_ATTR_DEPRECATED GC_word GC_max_retries;
398GC_API void GC_CALL GC_set_max_retries(GC_word);
399GC_API GC_word GC_CALL GC_get_max_retries(void);
400
401/**
402 * The cold end (bottom) of user stack. May be set in the client prior
403 * to calling any `GC_` routines. This avoids some overhead, and
404 * potentially some signals that can confuse debuggers. Otherwise the
405 * collector attempts to set it automatically. For multi-threaded
406 * code, this is the cold end of the stack for the primordial thread.
407 * For multi-threaded code, altering `GC_stackbottom` value directly
408 * after the collector initialization has no effect. Portable clients
409 * should use `GC_set_stackbottom()`, `GC_get_stack_base()`,
410 * `GC_call_with_gc_active()` and `GC_register_my_thread()` instead.
411 */
412GC_API GC_ATTR_DEPRECATED char *GC_stackbottom;
413
414/**
415 * Do not collect as part of the collector initialization. Should be
416 * set only if the client wants a chance to manually initialize the
417 * root set before the first collection. Interferes with black-listing.
418 * Wizards only. The setter and the getter are unsynchronized (and no
419 * external locking is needed since the value is accessed at the collector
420 * initialization only).
421 */
422GC_API GC_ATTR_DEPRECATED int GC_dont_precollect;
423GC_API void GC_CALL GC_set_dont_precollect(int);
424GC_API int GC_CALL GC_get_dont_precollect(void);
425
426/**
427 * If incremental collection is enabled, we try to terminate collections
428 * after this many milliseconds (plus the amount of nanoseconds as given in
429 * the latest `GC_set_time_limit_tv()` call, if any). Not a hard time bound.
430 * Setting this variable to `GC_TIME_UNLIMITED` essentially disables
431 * incremental collection (i.e. disables the "pause time exceeded" tests)
432 * while leaving generational collection enabled. The setter and the
433 * getter are unsynchronized, so `GC_call_with_alloc_lock()`
434 * (`GC_call_with_reader_lock()` in case of the getter) is required to
435 * avoid data race (if the value is modified after the collector is put
436 * into the multi-threaded mode). The setter does not update the value
437 * of the nanosecond part of the time limit (it is zero unless ever set
438 * by `GC_set_time_limit_tv()` call).
439 */
440GC_API GC_ATTR_DEPRECATED unsigned long GC_time_limit;
441#define GC_TIME_UNLIMITED 999999
442GC_API void GC_CALL GC_set_time_limit(unsigned long);
443GC_API unsigned long GC_CALL GC_get_time_limit(void);
444
445/** A portable type definition of time with a nanosecond precision. */
446struct GC_timeval_s {
447 unsigned long tv_ms; /*< time in milliseconds */
448 unsigned long tv_nsec; /*< nanoseconds fraction (less than 1000000) */
449};
450
451/* Public procedures */
452
453/**
454 * Set/get the time limit of the incremental collections. This is
455 * similar to `GC_set_time_limit` and `GC_get_time_limit` but the time
456 * is provided with the nanosecond precision. The value of `tv_nsec`
457 * part should be less than a million. If the value of `tv_ms` part is
458 * `GC_TIME_UNLIMITED`, then `tv_nsec` part is ignored. Initially, the
459 * value of `tv_nsec` part of the time limit is zero. The functions do
460 * not use any synchronization. Defined only if the library has been
461 * compiled without `NO_CLOCK` macro defined.
462 */
463GC_API void GC_CALL GC_set_time_limit_tv(struct GC_timeval_s);
464GC_API struct GC_timeval_s GC_CALL GC_get_time_limit_tv(void);
465
466/**
467 * Set/get the minimum value of the ratio of allocated bytes since
468 * garbage collection to the amount of finalizers created since that
469 * collection (so value is greater than
470 * `GC_bytes_allocd / (GC_fo_entries - last_fo_entries)`) which
471 * triggers the collection instead heap expansion. The value has no
472 * effect in the collector incremental mode. The default value is
473 * 10000 unless `GC_ALLOCD_BYTES_PER_FINALIZER` macro with a custom value
474 * is defined to build the collector. The default value might be not the
475 * right choice for clients where e.g. most objects have a finalizer.
476 * Zero value effectively disables taking amount of finalizers in the
477 * decision whether to collect or not. The functions do not use any
478 * synchronization.
479 */
480GC_API void GC_CALL GC_set_allocd_bytes_per_finalizer(GC_word);
481GC_API GC_word GC_CALL GC_get_allocd_bytes_per_finalizer(void);
482
483/**
484 * Tell the collector to start various performance measurements.
485 * Only the total time taken by full collections and the average time
486 * spent in the world-stopped collections are calculated, as of now.
487 * And, currently, there is no way to stop the measurements.
488 * The function does not use any synchronization. Defined only if the
489 * library has been compiled without `NO_CLOCK` macro defined.
490 */
491GC_API void GC_CALL GC_start_performance_measurement(void);
492
493/**
494 * Get the total time of all full collections since the start of the
495 * performance measurements. Includes time spent in the supplementary
496 * actions like blacklists promotion, marks clearing, free lists
497 * reconstruction and objects finalization. The measurement unit is a
498 * millisecond. Note that the returned value wraps around on overflow.
499 * The function does not use any synchronization. Defined only if the
500 * library has been compiled without `NO_CLOCK` macro defined.
501 */
502GC_API unsigned long GC_CALL GC_get_full_gc_total_time(void);
503
504/**
505 * Same as `GC_get_full_gc_total_time` but takes into account all mark
506 * phases with the world stopped and nothing else.
507 */
508GC_API unsigned long GC_CALL GC_get_stopped_mark_total_time(void);
509
510/**
511 * Get the average time spent in all mark phases with the world stopped.
512 * The average value is computed since the start of the performance
513 * measurements (or right since the collector initialization if the
514 * collector logging is enabled). The result is in nanoseconds.
515 * The function acquires the allocator lock (in the reader mode) to avoid
516 * data race. Defined only if the library has been compiled without
517 * `NO_CLOCK` macro defined.
518 */
519GC_API unsigned long GC_CALL GC_get_avg_stopped_mark_time_ns(void);
520
521/**
522 * Set whether the garbage collector will allocate executable memory
523 * pages or not. A nonzero argument instructs the collector to
524 * allocate memory with the executable flag on. Must be called before
525 * the collector is initialized. May have no effect on some platforms.
526 * The default value is controlled by `NO_EXECUTE_PERMISSION` macro (if
527 * present then the flag is off). Portable clients should have
528 * `GC_set_pages_executable(1)` call (before `GC_INIT()` one) provided
529 * they are going to execute code on any of the GC-allocated memory objects.
530 */
531GC_API void GC_CALL GC_set_pages_executable(int);
532
533/**
534 * Returns nonzero value if the garbage collector is set to the
535 * allocate-executable-memory mode. The mode could be changed by
536 * `GC_set_pages_executable` (before `GC_INIT()` call) unless the former
537 * has no effect on the platform. Does not use or need synchronization.
538 */
539GC_API int GC_CALL GC_get_pages_executable(void);
540
541/**
542 * The setter and the getter of the minimum value returned by the internal
543 * `min_bytes_allocd()`. The value should not be zero; the default value
544 * is one. Not synchronized.
545 */
546GC_API void GC_CALL GC_set_min_bytes_allocd(size_t);
547GC_API size_t GC_CALL GC_get_min_bytes_allocd(void);
548
549/**
550 * Set/get the size in pages of units operated by `GC_collect_a_little()`.
551 * The value should not be zero. Not synchronized.
552 */
553GC_API void GC_CALL GC_set_rate(int);
554GC_API int GC_CALL GC_get_rate(void);
555
556/**
557 * Set/get the maximum number of prior attempts at the world-stop marking.
558 * Not synchronized.
559 */
560GC_API void GC_CALL GC_set_max_prior_attempts(int);
561GC_API int GC_CALL GC_get_max_prior_attempts(void);
562
563/**
564 * Control whether to disable algorithm deciding if a collection should
565 * be started when we allocated enough to amortize the collection.
566 * Both the setter and the getter acquire the allocator lock (in the reader
567 * mode in case of the getter) to avoid data race.
568 */
569GC_API void GC_CALL GC_set_disable_automatic_collection(int);
570GC_API int GC_CALL GC_get_disable_automatic_collection(void);
571
572/**
573 * Overrides the default handle-fork mode. A nonzero value means GC
574 * should install proper `pthread_atfork` handlers. Has effect only
575 * if called before the collector initialization. Clients should call
576 * `GC_set_handle_fork()` with nonzero argument if going to use `fork`
577 * with the GC functions called in the child process. (Note that such
578 * client and at-fork handler activities are not fully POSIX-compliant.)
579 * `GC_set_handle_fork()` instructs `GC_init` to setup GC fork handlers
580 * using `pthread_atfork()`, the latter might fail (or, even, absent on
581 * some targets) causing `abort` at the collector initialization.
582 * Issues with missing (or failed) `pthread_atfork()` could be avoided
583 * by invocation of `GC_set_handle_fork(-1)` at application start-up and
584 * surrounding each `fork()` with the relevant
585 * `GC_atfork_prepare`/`GC_atfork_parent`/`GC_atfork_child` calls.
586 */
587GC_API void GC_CALL GC_set_handle_fork(int);
588
589/**
590 * Routines to handle POSIX `fork()` manually (no-op if handled
591 * automatically). `GC_atfork_prepare()` should be called immediately
592 * before `fork()`; `GC_atfork_parent()` should be invoked just after
593 * `fork` in the branch that corresponds to parent process (i.e.,
594 * `fork` result is nonzero); `GC_atfork_child()` is to be called
595 * immediately in the child branch (i.e., `fork` result is 0).
596 * Note that `GC_atfork_child()` call should, of course, precede
597 * `GC_start_mark_threads()` call, if any.
598 */
599GC_API void GC_CALL GC_atfork_prepare(void);
600GC_API void GC_CALL GC_atfork_parent(void);
601GC_API void GC_CALL GC_atfork_child(void);
602
603/**
604 * Initialize the collector. Portable clients should call `GC_INIT()`
605 * from the program's `main()` instead.
606 */
607GC_API void GC_CALL GC_init(void);
608
609/**
610 * Return 1 (true) if the collector is initialized (or, at least, the
611 * initialization is in progress), 0 otherwise.
612 */
613GC_API int GC_CALL GC_is_init_called(void);
614
615/**
616 * Perform the collector shutdown. (E.g. dispose critical sections on
617 * Windows target.) A duplicate invocation is a no-op. In case of Windows,
618 * typically, the client should also call `GC_win32_free_heap()` before this
619 * function call.
620 * TODO: The collector reinitialization after shutdown might work in certain
621 * configurations, but not tested.
622 */
623GC_API void GC_CALL GC_deinit(void);
624
625/**
626 * General-purpose allocation functions, with roughly `malloc` calling
627 * conventions. The atomic variants promise that no relevant pointers
628 * are contained in the object. The non-atomic variants guarantee that
629 * the new object is cleared. `GC_malloc_uncollectable()` allocates
630 * an object that is scanned for pointers to collectible objects, but
631 * is not itself collectible. The object is scanned even if it does
632 * not appear to be reachable. `GC_malloc_uncollectable()` and `GC_free()`
633 * called on the resulting object implicitly update `GC_non_gc_bytes`
634 * appropriately. All these functions (`GC_malloc`, `GC_malloc_atomic`,
635 * `GC_strdup`, `GC_strndup`, `GC_malloc_uncollectable`) are guaranteed
636 * never to return `NULL` unless `GC_oom_fn()` returns `NULL`.
637 */
638GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
639 GC_malloc(size_t /* `size_in_bytes` */);
640GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
641 GC_malloc_atomic(size_t /* `size_in_bytes` */);
642GC_API GC_ATTR_MALLOC char *GC_CALL GC_strdup(const char *);
643GC_API GC_ATTR_MALLOC char *GC_CALL GC_strndup(const char *, size_t)
644 GC_ATTR_NONNULL(1);
645GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
646 GC_malloc_uncollectable(size_t /* `size_in_bytes` */);
647
648/**
649 * The allocation function which guarantees the requested alignment of
650 * the allocated memory object. The `align` argument should be nonzero
651 * and a power of two. It is guaranteed never to return `NULL` unless
652 * `GC_oom_fn()` returns `NULL`.
653 */
654GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(2) void *GC_CALL
655 GC_memalign(size_t /* `align` */, size_t /* `lb` */);
656
657/**
658 * A function similar to `GC_memalign` but existing largely for
659 * redirection in the find-leak mode. The `align` argument should be
660 * nonzero and a power of two, but additionally the argument is
661 * required to be not less than size of a pointer. Note that the
662 * function does not change value of `*memptr` in case of failure
663 * (i.e. when the result is nonzero). It is guaranteed never to return
664 * `NULL` unless `GC_oom_fn()` returns `NULL`.
665 */
666GC_API int GC_CALL GC_posix_memalign(void ** /* `memptr` */,
667 size_t /* `align` */, size_t /* `lb` */)
668 GC_ATTR_NONNULL(1);
669
670#ifndef GC_NO_VALLOC
671/**
672 * The allocation functions that guarantee the memory page alignment of
673 * the returned object. Exist largely for redirection in the find-leak
674 * mode. All these functions (`GC_pvalloc`, `GC_valloc`) are guaranteed
675 * never to return `NULL` unless `GC_oom_fn()` returns `NULL`.
676 */
677GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
678 GC_valloc(size_t /* `lb` */);
679GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
680 GC_pvalloc(size_t /* `lb` */);
681#endif
682
683/**
684 * Explicitly deallocate an object. Dangerous if used incorrectly.
685 * Requires a pointer to the base of an object. An object should not
686 * be enabled for finalization (and it should not contain registered
687 * disappearing links of any kind) when it is explicitly deallocated.
688 * `GC_free(0)` is a no-op, as required by ANSI C for `free()`.
689 */
690GC_API void GC_CALL GC_free(void *);
691GC_API void GC_CALL GC_debug_free(void *);
692
693/**
694 * A symbol to be intercepted by heap profilers so that they can
695 * accurately track allocations. Programs such as Valgrind `massif`
696 * and KDE heaptrack do tracking of allocated objects by overriding
697 * common allocator methods (e.g. `malloc` and `free`). However,
698 * because the collector does not work by calling standard allocation
699 * methods on objects that were reclaimed, we need a way to tell the
700 * profiler that an object has been freed. This function is not
701 * intended to be called by the client, it should be used for the
702 * interception purpose only. The collector calls this function
703 * internally whenever an object is freed. Defined only if the library
704 * has been compiled with `VALGRIND_TRACKING` macro defined.
705 */
706GC_API void GC_CALLBACK GC_free_profiler_hook(void *);
707
708#if (defined(GC_CAN_SAVE_CALL_STACKS) || defined(GC_ADD_CALLER)) \
709 && !defined(GC_RETURN_ADDR_T_DEFINED)
710/*
711 * A type to hold a function return address (pointer). Never used for
712 * calling a function.
713 */
714# if defined(__GNUC__)
715/*
716 * Defined as a data (object) pointer type to avoid the compiler complain
717 * that ISO C forbids conversion between object and function pointer types.
718 */
719typedef void *GC_return_addr_t;
720# else
721typedef void (*GC_return_addr_t)(void);
722# endif
723# define GC_RETURN_ADDR_T_DEFINED
724#endif /* GC_CAN_SAVE_CALL_STACKS || GC_ADD_CALLER */
725
726#ifdef GC_ADD_CALLER
727# define GC_EXTRAS GC_RETURN_ADDR, __FILE__, __LINE__
728# define GC_EXTRA_PARAMS GC_return_addr_t ra, const char *s, int i
729#else
730# define GC_EXTRAS __FILE__, __LINE__
731# define GC_EXTRA_PARAMS const char *s, int i
732#endif
733
734/*
735 * The "stubborn" objects allocation is not supported anymore.
736 * Exists only for the backward compatibility.
737 */
738#define GC_MALLOC_STUBBORN(sz) GC_MALLOC(sz)
739#define GC_NEW_STUBBORN(t) GC_NEW(t)
740#define GC_CHANGE_STUBBORN(p) GC_change_stubborn(p)
741GC_API GC_ATTR_DEPRECATED void GC_CALL GC_change_stubborn(const void *);
742GC_API GC_ATTR_DEPRECATED void GC_CALL GC_debug_change_stubborn(const void *);
743GC_API GC_ATTR_ALLOC_SIZE(1) GC_ATTR_DEPRECATED void *GC_CALL
744 GC_malloc_stubborn(size_t);
745GC_API GC_ATTR_ALLOC_SIZE(1) GC_ATTR_DEPRECATED void *GC_CALL
746 GC_debug_malloc_stubborn(size_t, GC_EXTRA_PARAMS);
747
748/**
749 * Inform the collector that the object has been changed.
750 * Only non-`NULL` pointer stores into the object are considered to be
751 * changes. Matters only if the incremental collection is enabled in
752 * the manual VDB (virtual dirty bits) mode; otherwise the function
753 * does nothing. Should be followed typically by `GC_reachable_here()`
754 * called for each of the stored pointers.
755 */
756GC_API void GC_CALL GC_end_stubborn_change(const void *) GC_ATTR_NONNULL(1);
757GC_API void GC_CALL GC_debug_end_stubborn_change(const void *)
758 GC_ATTR_NONNULL(1);
759
760/**
761 * Return a pointer to the base (lowest address) of an object given
762 * a pointer to a location within the object. I.e., map an interior
763 * pointer to the corresponding base pointer. Note that with debugging
764 * allocation, this returns a pointer to the actual base of the object,
765 * i.e. the debug information, not to the base of the user object.
766 * Return `NULL` if `displaced_pointer` does not point to within
767 * a valid object. Note that a deallocated object in the garbage
768 * collected heap may be considered valid, even if it has been
769 * deallocated with `GC_free()`.
770 */
771GC_API void *GC_CALL GC_base(void * /* `displaced_pointer` */);
772
773/**
774 * Return 1 (true) if the argument points to somewhere in the garbage
775 * collected heap, 0 otherwise. Primary use is as a fast alternative to
776 * `GC_base()` to check whether the given object is allocated by the
777 * collector or not. It is assumed that the collector is already initialized.
778 */
779GC_API int GC_CALL GC_is_heap_ptr(const void *);
780
781/**
782 * Given a pointer to the base of an object, return its size in bytes.
783 * (For small objects this also happens to work from interior pointers,
784 * but that should not be relied upon.) The returned size may be slightly
785 * larger than what was originally requested. The argument may be `NULL`
786 * (causing 0 to be returned).
787 */
788GC_API size_t GC_CALL GC_size(const void * /* `obj` */);
789
790/**
791 * For compatibility with C library. This is occasionally faster than
792 * a `malloc` followed by a `bcopy`. But if you rely on that, either
793 * here or with the standard C library, your code is broken.
794 * Probably, it should not have been invented, but now we are stuck.
795 * The resulting object has the same kind as the original one.
796 * It is an error to have changes enabled for the original object.
797 * It does not change the content of the object from its beginning to
798 * the minimum of old size and `new_size_in_bytes`; the content above in
799 * case of object size growth is initialized to zero (not guaranteed for
800 * atomic object type). The function follows ANSI conventions for `NULL`
801 * `old_object` (i.e., equivalent to `GC_malloc` regardless of
802 * `new_size_in_bytes`). If `new_size_in_bytes` is zero (and
803 * `old_object` is non-`NULL`), then the call is equivalent to
804 * `GC_free` (and `NULL` is returned). If `old_object` is non-`NULL`,
805 * it must have been returned by an earlier call to `GC_realloc`,
806 * `GC_malloc` or friends. In case of the allocation failure, the
807 * memory pointed by `old_object` is untouched (and not freed). If the
808 * returned pointer is not the same as `old_object` and both of them
809 * are non-`NULL`, then `old_object` is freed. Returns either `NULL`
810 * (in case of the allocation failure or zero `new_size_in_bytes`) or
811 * pointer to the allocated memory. For a nonzero `new_size_in_bytes`,
812 * the function (including its debug variant) is guaranteed never to
813 * return `NULL` unless `GC_oom_fn()` returns `NULL`.
814 */
815GC_API void *GC_CALL GC_realloc(void * /* `old_object` */,
816 size_t /* `new_size_in_bytes` */)
817 /* `realloc` attribute */ GC_ATTR_ALLOC_SIZE(2);
818GC_API void *GC_CALL GC_debug_realloc(void * /* `old_object` */,
819 size_t /* `new_size_in_bytes` */,
820 GC_EXTRA_PARAMS)
821 /* `realloc` attribute */ GC_ATTR_ALLOC_SIZE(2);
822
823/**
824 * Increase the heap size explicitly. The performed increase is at
825 * least `number_of_bytes`. Does the collector initialization as well
826 * (if not yet). Returns 0 on failure, 1 on success.
827 */
828GC_API int GC_CALL GC_expand_hp(size_t /* `number_of_bytes` */);
829
830/**
831 * Limit the heap size to `n` bytes. Useful when you are debugging,
832 * especially on systems that do not handle running out of memory well.
833 * A zero `n` means the heap is unbounded; this is the default.
834 * This setter function is unsynchronized (so it might require
835 * `GC_call_with_alloc_lock` to avoid data race).
836 */
837GC_API void GC_CALL GC_set_max_heap_size(GC_word /* `n` */);
838
839/**
840 * Inform the collector that a certain section of statically allocated
841 * memory contains no pointers to garbage-collected memory. Thus it does
842 * not need to be scanned. This is sometimes important if the application
843 * maps large read/write files into the address space, which could be
844 * mistaken for dynamic library data segments on some systems.
845 * Both section start (`low_address`) and end (`high_address_plus_1`)
846 * are not needed to be pointer-aligned.
847 */
848GC_API void GC_CALL GC_exclude_static_roots(
849 void * /* `low_address` */, void * /* `high_address_plus_1` */);
850
851/**
852 * Clear the number of entries in the exclusion table. Wizards only.
853 * Should be called typically with the allocator lock held, but no
854 * assertion about it by design.
855 */
856GC_API void GC_CALL GC_clear_exclusion_table(void);
857
858/** Clear the set of root segments. Wizards only. */
859GC_API void GC_CALL GC_clear_roots(void);
860
861/**
862 * Add a root segment. Wizards only. May merge adjacent or overlapping
863 * segments if appropriate. Both segment start (`low_address`) and
864 * end (`high_address_plus_1`) are not needed to be pointer-aligned.
865 * `low_address` must not be greater than `high_address_plus_1`.
866 */
867GC_API void GC_CALL GC_add_roots(void * /* `low_address` */,
868 void * /* `high_address_plus_1` */);
869
870/** Remove root segments located fully in the region. Wizards only. */
871GC_API void GC_CALL GC_remove_roots(void * /* `low_address` */,
872 void * /* `high_address_plus_1` */);
873
874/**
875 * Add a displacement to the set of those considered valid by the
876 * collector. `GC_register_displacement(offset)` means that if `p` was
877 * returned by `GC_malloc()`, then `(char *)p + offset` will be
878 * considered to be a valid pointer to `p`. `offset` must be less than
879 * the size of a heap block. (All pointers to the interior of objects
880 * from the stack are considered valid in any case. This applies to
881 * heap objects and static data.) Preferably, this should be called
882 * before any other GC procedures. Calling it later adds to the
883 * probability of excess memory retention. This is a no-op if the
884 * collector has recognition of arbitrary interior pointers enabled,
885 * which is the default (assuming the collector is built with
886 * `ALL_INTERIOR_POINTERS` macro defined). The debugging variant should
887 * be used if any debugging allocation is being done.
888 */
889GC_API void GC_CALL GC_register_displacement(size_t /* `offset` */);
890GC_API void GC_CALL GC_debug_register_displacement(size_t /* `offset` */);
891
892/** Explicitly trigger a full, world-stop collection. */
893GC_API void GC_CALL GC_gcollect(void);
894
895/**
896 * Same as above but ignores the default `stop_func` setting and tries
897 * to unmap as much memory as possible (regardless of the corresponding
898 * switch setting). The recommended usage: on receiving a system
899 * low-memory event; before retrying a system call failed because of
900 * the system is running out of resources.
901 */
902GC_API void GC_CALL GC_gcollect_and_unmap(void);
903
904/**
905 * Trigger a full world-stopped collection. Abort the collection if
906 * and when `stop_func()` returns a nonzero value. `stop_func()` will
907 * be called frequently, and should be reasonably fast.
908 * (`stop_func()` is called with the allocator lock held and the world
909 * might be stopped; it is not allowed for `stop_func()` to manipulate
910 * pointers to the garbage-collected heap or call most of GC functions.)
911 * This works even if no virtual dirty bits, and hence incremental
912 * collection is not available for the architecture. Collections can
913 * be aborted faster than normal pause times for incremental collection;
914 * however, aborted collections do no useful work; the next collection
915 * needs to start from the beginning. `stop_func` must not be 0.
916 * `GC_try_to_collect()` returns 0 if the collection was aborted (or the
917 * collections are disabled), 1 if it succeeded.
918 */
919typedef int(GC_CALLBACK *GC_stop_func)(void);
920GC_API int GC_CALL GC_try_to_collect(GC_stop_func /* `stop_func` */)
921 GC_ATTR_NONNULL(1);
922
923/**
924 * Set/get the default `stop_func`. The latter is used by `GC_gcollect()`
925 * and by implicitly triggered collections (except for the case when
926 * handling out of memory). Must not be 0. Both the setter and the getter
927 * acquire the allocator lock (in the reader mode in case of the getter)
928 * to avoid data race.
929 */
930GC_API void GC_CALL GC_set_stop_func(GC_stop_func /* `stop_func` */)
931 GC_ATTR_NONNULL(1);
932GC_API GC_stop_func GC_CALL GC_get_stop_func(void);
933
934/**
935 * Return the number of bytes in the heap. Excludes collector private
936 * data structures; excludes the unmapped memory (returned to the OS).
937 * Includes empty blocks and fragmentation loss. Includes some pages
938 * that were allocated but never written. This is an unsynchronized
939 * getter, so it should be called typically with the allocator lock
940 * held, at least in the reader mode, to avoid data race on
941 * multiprocessors (the alternative way is to use `GC_get_prof_stats`
942 * or `GC_get_heap_usage_safe` API calls instead).
943 * This getter remains lock-free (unsynchronized) for compatibility
944 * reason since some existing clients call it from a GC callback
945 * holding the allocator lock. (This API function and the following
946 * four ones below were made thread-safe in GC v7.2alpha1 and
947 * reverted back in v7.2alpha7 for the reason described.)
948 */
949GC_API size_t GC_CALL GC_get_heap_size(void);
950
951/**
952 * Return a lower bound on the number of free bytes in the heap
953 * (excluding the unmapped memory space). This is an unsynchronized
954 * getter (see `GC_get_heap_size` comment regarding thread-safety).
955 */
956GC_API size_t GC_CALL GC_get_free_bytes(void);
957
958/**
959 * Return the size (in bytes) of the unmapped memory (which is returned
960 * to the OS but could be remapped back by the collector later unless
961 * the OS runs out of system/virtual memory). This is an unsynchronized
962 * getter (see `GC_get_heap_size` comment regarding thread-safety).
963 */
964GC_API size_t GC_CALL GC_get_unmapped_bytes(void);
965
966/**
967 * Return the number of bytes allocated since the last collection.
968 * This is an unsynchronized getter (see `GC_get_heap_size` comment
969 * regarding thread-safety).
970 */
971GC_API size_t GC_CALL GC_get_bytes_since_gc(void);
972
973/**
974 * Return the number of explicitly deallocated bytes of memory since
975 * the recent collection. This is an unsynchronized getter.
976 */
977GC_API size_t GC_CALL GC_get_expl_freed_bytes_since_gc(void);
978
979/**
980 * Return the total number of bytes allocated in this process.
981 * Never decreases, except due to wrapping. This is an unsynchronized
982 * getter (see `GC_get_heap_size` comment regarding thread-safety).
983 */
984GC_API size_t GC_CALL GC_get_total_bytes(void);
985
986/**
987 * Return the total number of bytes obtained from OS. Includes the
988 * unmapped memory. Never decreases. It is an unsynchronized getter.
989 */
990GC_API size_t GC_CALL GC_get_obtained_from_os_bytes(void);
991
992/**
993 * Return the heap usage information. This is a thread-safe (atomic)
994 * alternative for the five above getters. (This function acquires
995 * the allocator lock in the reader mode, thus preventing data race and
996 * returning the consistent result.) Passing `NULL` pointer is allowed
997 * for any argument. Returned (filled in) values are of `GC_word` type.
998 */
999GC_API void GC_CALL GC_get_heap_usage_safe(GC_word * /* `pheap_size` */,
1000 GC_word * /* `pfree_bytes` */,
1001 GC_word * /* `punmapped_bytes` */,
1002 GC_word * /* `pbytes_since_gc` */,
1003 GC_word * /* `ptotal_bytes` */);
1004
1005/**
1006 * Structure used to query the GC statistics (profiling information).
1007 * More fields could be added in the future. To preserve compatibility
1008 * new fields should be added only to the end, and no deprecated fields
1009 * should be removed from.
1010 */
1011struct GC_prof_stats_s {
1012 /**
1013 * Heap size in bytes (including the area unmapped to OS).
1014 * Same as value of `GC_get_heap_size() + GC_get_unmapped_bytes()`.
1015 */
1016 GC_word heapsize_full;
1017
1018 /**
1019 * Total bytes contained in free and unmapped blocks.
1020 * Same as result of `GC_get_free_bytes() + GC_get_unmapped_bytes()`.
1021 */
1022 GC_word free_bytes_full;
1023
1024 /**
1025 * Amount of memory unmapped to OS. Same as the value returned by
1026 * `GC_get_unmapped_bytes()`.
1027 */
1028 GC_word unmapped_bytes;
1029
1030 /**
1031 * Number of bytes allocated since the recent collection.
1032 * Same as the value returned by `GC_get_bytes_since_gc()`.
1033 */
1034 GC_word bytes_allocd_since_gc;
1035
1036 /**
1037 * Number of bytes allocated before the recent garbage collection.
1038 * The value may wrap. Same as the result of
1039 * `GC_get_total_bytes() - GC_get_bytes_since_gc()`.
1040 */
1041 GC_word allocd_bytes_before_gc;
1042
1043 /**
1044 * Number of bytes not considered candidates for garbage collection.
1045 * Same as the value returned by `GC_get_non_gc_bytes()`.
1046 */
1047 GC_word non_gc_bytes;
1048
1049 /**
1050 * Garbage collection cycle number. The value may wrap. Same as the
1051 * value returned by `GC_get_gc_no()`.
1052 */
1053 GC_word gc_no;
1054
1055 /**
1056 * Number of marker threads (excluding the initiating one). Same as
1057 * the value returned by `GC_get_parallel()` (or 0 if the collector
1058 * is single-threaded).
1059 */
1060 GC_word markers_m1;
1061
1062 /**
1063 * Approximate number of reclaimed bytes after the recent garbage
1064 * collection.
1065 */
1066 GC_word bytes_reclaimed_since_gc;
1067
1068 /**
1069 * Approximate number of bytes reclaimed before the recent garbage
1070 * collection. The value may wrap.
1071 */
1072 GC_word reclaimed_bytes_before_gc;
1073
1074 /**
1075 * Number of bytes freed explicitly since the recent garbage collection.
1076 * Same as the value returned by `GC_get_expl_freed_bytes_since_gc()`.
1077 */
1078 GC_word expl_freed_bytes_since_gc;
1079
1080 /** Total amount of memory obtained from OS, in bytes. */
1081 GC_word obtained_from_os_bytes;
1082};
1083
1084/**
1085 * Atomically get the collector statistics (various global counters).
1086 * Clients should pass the size of the buffer (of `GC_prof_stats_s` type)
1087 * to fill in the values - this is for interoperability between different
1088 * collector versions: an old client could have fewer fields, and vice
1089 * versa, client could use newer `gc.h` file (with more entries declared
1090 * in the structure) than that of the linked collector library; in the
1091 * latter case, unsupported (unknown) fields are filled in with -1 (`~0`).
1092 * Return the size (in bytes) of the filled in part of the structure
1093 * (excluding all unknown fields, if any).
1094 */
1095GC_API size_t GC_CALL GC_get_prof_stats(struct GC_prof_stats_s *,
1096 size_t /* `stats_sz` */);
1097#ifdef GC_THREADS
1098/**
1099 * Same as `GC_get_prof_stats` but unsynchronized (i.e., not holding
1100 * the allocator lock). Clients should call it using
1101 * `GC_call_with_reader_lock()` to avoid data race on multiprocessors.
1102 */
1103GC_API size_t GC_CALL GC_get_prof_stats_unsafe(struct GC_prof_stats_s *,
1104 size_t /* `stats_sz` */);
1105#endif
1106
1107/**
1108 * Get the element value (converted to bytes) at a given index of
1109 * `GC_size_map` table which provides requested-to-actual allocation size
1110 * mapping. Assumes the collector is initialized. Returns -1 (`~0`) if
1111 * the index is out of `GC_size_map` table bounds. Does not use
1112 * synchronization, thus clients should call it using
1113 * `GC_call_with_reader_lock()` typically to avoid data race on
1114 * multiprocessors.
1115 */
1116GC_API size_t GC_CALL GC_get_size_map_at(int i);
1117
1118/**
1119 * Return the total memory use (in bytes) by all allocated blocks.
1120 * The result is equal to `GC_get_heap_size() - GC_get_free_bytes()`.
1121 * Acquires the allocator lock in the reader mode.
1122 */
1123GC_API GC_word GC_CALL GC_get_memory_use(void);
1124
1125/**
1126 * Disable garbage collection. Even `GC_gcollect()` calls will be
1127 * ineffective.
1128 */
1129GC_API void GC_CALL GC_disable(void);
1130
1131/**
1132 * Return 1 (true) if the garbage collection is disabled (i.e., the
1133 * value of `GC_dont_gc` is nonzero), 0 otherwise. Does not acquire
1134 * the allocator lock.
1135 */
1136GC_API int GC_CALL GC_is_disabled(void);
1137
1138/**
1139 * Try to re-enable garbage collection. `GC_disable()` and `GC_enable()`
1140 * calls could be nested. Garbage collection is enabled if the number of
1141 * calls to both functions is equal.
1142 */
1143GC_API void GC_CALL GC_enable(void);
1144
1145/**
1146 * Select whether to use the manual VDB (virtual dirty bits) mode for
1147 * the incremental collection. Has no effect if called after enabling
1148 * the incremental collection. The default value is off unless the
1149 * collector is compiled with `MANUAL_VDB` macro defined. The manual
1150 * VDB mode should be used only if the client has the appropriate
1151 * `GC_END_STUBBORN_CHANGE()` and `GC_reachable_here()` (or,
1152 * alternatively, `GC_PTR_STORE_AND_DIRTY()`) calls (to ensure proper
1153 * write barriers). The setter and the getter are not synchronized.
1154 */
1155GC_API void GC_CALL GC_set_manual_vdb_allowed(int);
1156GC_API int GC_CALL GC_get_manual_vdb_allowed(void);
1157
1158/*
1159 * The constants to represent available VDB (virtual dirty bits)
1160 * techniques.
1161 */
1162
1163/** Means the incremental mode is unsupported. */
1164#define GC_VDB_NONE 0
1165
1166#define GC_VDB_MPROTECT 0x1
1167
1168/** Means `GC_set_manual_vdb_allowed(1)` has effect. */
1169#define GC_VDB_MANUAL 0x2
1170
1171/** Means no other technique is usable. */
1172#define GC_VDB_DEFAULT 0x4
1173
1174#define GC_VDB_GWW 0x8
1175
1176#define GC_VDB_PROC 0x20
1177#define GC_VDB_SOFT 0x40
1178
1179/**
1180 * Get the list of available VDB (virtual dirty bits) techniques.
1181 * The returned value is a constant one, either `GC_VDB_NONE`, or one
1182 * or more of the above `GC_VDB_` constants, or'ed together. May be
1183 * called before the collector is initialized.
1184 */
1185GC_API unsigned GC_CALL GC_get_supported_vdbs(void);
1186
1187/**
1188 * Enable incremental/generational collection. Not advisable unless
1189 * dirty bits are available or most heap objects are pointer-free
1190 * (atomic) or immutable. Do not use in the find-leak mode.
1191 * Ignored if `GC_dont_gc` is nonzero. Only the generational piece of
1192 * this is functional if `GC_time_limit` is set to `GC_TIME_UNLIMITED`.
1193 * Causes thread-local variant of `GC_gcj_malloc()` to revert to locked
1194 * allocation. Must be called before any such `GC_gcj_malloc()` calls.
1195 * For best performance, should be called as early as possible.
1196 * On some platforms, calling it later may have adverse effects.
1197 * Safe to call before the collector initialization; it performs the
1198 * latter if not done yet.
1199 */
1200GC_API void GC_CALL GC_enable_incremental(void);
1201
1202/**
1203 * Return 1 (true) if the incremental mode is on, 0 otherwise.
1204 * Does not acquire the allocator lock.
1205 */
1206GC_API int GC_CALL GC_is_incremental_mode(void);
1207
1208/**
1209 * An extended variant of `GC_is_incremental_mode()` to return one of
1210 * `GC_VDB_` constants designating which VDB (virtual dirty bits)
1211 * technique is used exactly. Does not acquire the allocator lock.
1212 */
1213GC_API unsigned GC_CALL GC_get_actual_vdb(void);
1214
1215/** May protect non-atomic objects. */
1216#define GC_PROTECTS_POINTER_HEAP 1
1217
1218#define GC_PROTECTS_PTRFREE_HEAP 2
1219
1220/* Protects static data. But this is currently never. */
1221#define GC_PROTECTS_STATIC_DATA 4
1222
1223/* Deprecated. It is probably impractical to protect stacks. */
1224#define GC_PROTECTS_STACK 8
1225
1226#define GC_PROTECTS_NONE 0
1227
1228/**
1229 * Does incremental mode write-protect pages? Returns zero or
1230 * more of the above `GC_PROTECTS_` constants, or'ed together.
1231 * The collector is assumed to be initialized before this call.
1232 * The result is not affected by `GC_set_manual_vdb_allowed()`.
1233 * Call of `GC_enable_incremental()` may change the result to
1234 * `GC_PROTECTS_NONE` if some implementation is chosen at
1235 * runtime not needing to write-protect the pages.
1236 */
1237GC_API int GC_CALL GC_incremental_protection_needs(void);
1238
1239/**
1240 * Force start of incremental collection. Acquires the allocator lock.
1241 * No-op unless the incremental mode is on.
1242 */
1243GC_API void GC_CALL GC_start_incremental_collection(void);
1244
1245/**
1246 * Perform some garbage collection work, if appropriate.
1247 * Return 0 if there is no more work to be done (including the
1248 * case when garbage collection is not appropriate).
1249 * Typically performs an amount of work corresponding roughly
1250 * to marking from one page. May do more work if further
1251 * progress requires it, e.g. if incremental collection is
1252 * disabled. It is reasonable to call this in a wait loop
1253 * until it returns 0. If the garbage collection is disabled
1254 * but the incremental collection is already ongoing, then
1255 * perform marking anyway but not stopping the world (and
1256 * without the reclaim phase).
1257 */
1258GC_API int GC_CALL GC_collect_a_little(void);
1259
1260/**
1261 * Allocate an object of size `lb` bytes. The client guarantees that
1262 * as long as the object is live, it will be referenced by a pointer
1263 * that points to somewhere within the first GC heap block (`hblk`) of
1264 * the object. (This should normally be declared `volatile` to prevent
1265 * the compiler from invalidating this assertion.) This function is
1266 * only useful if a large array is being allocated. It reduces the
1267 * chance of accidentally retaining such an array as a result of
1268 * scanning an integer that happens to be an address inside the array.
1269 * (Actually, it reduces the chance of the allocator not finding space
1270 * for such an array, since it will try hard to avoid introducing such
1271 * a false reference.) On a SunOS 4.x or Windows system this is
1272 * recommended for arrays likely to be larger than 100 KB or so.
1273 * For other systems, or if the collector is not configured to
1274 * recognize all interior pointers, the threshold is normally much
1275 * higher. These functions are guaranteed never to return `NULL`
1276 * unless `GC_oom_fn()` returns `NULL`.
1277 */
1278GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1279 GC_malloc_ignore_off_page(size_t /* `lb` */);
1280GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1281 GC_malloc_atomic_ignore_off_page(size_t /* `lb` */);
1282
1283/**
1284 * Allocate `lb` bytes of pointer-free, untraced, uncollectible data.
1285 * This is normally roughly equivalent to the system `malloc`. But it
1286 * may be useful if `malloc` is redefined. The function (including its
1287 * debug variant) is guaranteed never to return `NULL` unless
1288 * `GC_oom_fn()` returns `NULL`. Defined only if the library has been
1289 * compiled with `GC_ATOMIC_UNCOLLECTABLE` macro defined.
1290 */
1291GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1292 GC_malloc_atomic_uncollectable(size_t /* `size_in_bytes` */);
1293GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1294 GC_debug_malloc_atomic_uncollectable(size_t, GC_EXTRA_PARAMS);
1295
1296/**
1297 * Debugging (annotated) allocation. `GC_gcollect()` will check
1298 * objects allocated in this way for overwrites, etc.
1299 */
1300GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1301 GC_debug_malloc(size_t /* `size_in_bytes` */, GC_EXTRA_PARAMS);
1302GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1303 GC_debug_malloc_atomic(size_t /* `size_in_bytes` */, GC_EXTRA_PARAMS);
1304GC_API GC_ATTR_MALLOC char *GC_CALL GC_debug_strdup(const char *,
1305 GC_EXTRA_PARAMS);
1306GC_API GC_ATTR_MALLOC char *GC_CALL GC_debug_strndup(const char *, size_t,
1307 GC_EXTRA_PARAMS)
1308 GC_ATTR_NONNULL(1);
1309GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1310 GC_debug_malloc_uncollectable(size_t /* `size_in_bytes` */,
1311 GC_EXTRA_PARAMS);
1312GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1313 GC_debug_malloc_ignore_off_page(size_t /* `size_in_bytes` */,
1314 GC_EXTRA_PARAMS);
1315GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1316 GC_debug_malloc_atomic_ignore_off_page(size_t /* `size_in_bytes` */,
1317 GC_EXTRA_PARAMS);
1318
1319/**
1320 * The functions that allocate objects with debug information (like the
1321 * above), but just fill in dummy file and line number information.
1322 * Thus they can serve as drop-in `malloc`/`realloc` replacements.
1323 * This can be useful for two reasons:
1324 * 1. It allows the collector to be built with `DBG_HDRS_ALL` macro
1325 * defined even if some allocation calls come from 3rd-party
1326 * libraries that cannot be recompiled.
1327 * 2. On some platforms, the file and line information is redundant,
1328 * since it can be reconstructed from a stack trace. On such
1329 * platforms it may be more convenient not to recompile, e.g. for
1330 * leak detection. This can be accomplished by instructing the
1331 * linker to replace `malloc`/`realloc` with these.
1332 *
1333 * Note that these functions (for a nonzero new size in case of
1334 * `realloc`) are guaranteed never to return `NULL` unless
1335 * `GC_oom_fn()` returns `NULL`.
1336 */
1337GC_API GC_ATTR_MALLOC GC_ATTR_ALLOC_SIZE(1) void *GC_CALL
1338 GC_debug_malloc_replacement(size_t /* `size_in_bytes` */);
1339GC_API /* `realloc` attribute */ GC_ATTR_ALLOC_SIZE(2) void *GC_CALL
1340 GC_debug_realloc_replacement(void * /* `obj` */,
1341 size_t /* `size_in_bytes` */);
1342
1343#ifdef __cplusplus
1344# define GC_CAST_AWAY_CONST_PVOID(p) \
1345 reinterpret_cast</* no const */ void *>(reinterpret_cast<GC_uintptr_t>(p))
1346#else
1347# define GC_CAST_AWAY_CONST_PVOID(p) \
1348 ((/* no const */ void *)(GC_uintptr_t)(p))
1349#endif
1350
1351/**
1352 * Convenient macros for disappearing links registration working both
1353 * for debug and non-debug allocated objects, and accepting interior
1354 * pointers to object.
1355 */
1356#define GC_GENERAL_REGISTER_DISAPPEARING_LINK_SAFE(link, obj) \
1357 GC_general_register_disappearing_link( \
1358 link, GC_base(GC_CAST_AWAY_CONST_PVOID(obj)))
1359#define GC_REGISTER_LONG_LINK_SAFE(link, obj) \
1360 GC_register_long_link(link, GC_base(GC_CAST_AWAY_CONST_PVOID(obj)))
1361
1362/*
1363 * Convenient macros over debug and non-debug allocation functions.
1364 * All these macros (`GC_MALLOC`, `GC_REALLOC`, `GC_MALLOC_ATOMIC`,
1365 * `GC_STRDUP`, `GC_STRNDUP`, `GC_MALLOC_ATOMIC_UNCOLLECTABLE`,
1366 * `GC_MALLOC_UNCOLLECTABLE`, `GC_MALLOC_IGNORE_OFF_PAGE`,
1367 * `GC_MALLOC_ATOMIC_IGNORE_OFF_PAGE`) are guaranteed never to return
1368 * `NULL` (for a nonzero new size in case of `GC_REALLOC`) unless
1369 * `GC_oom_fn()` returns `NULL`.
1370 */
1371#ifdef GC_DEBUG_REPLACEMENT
1372# define GC_MALLOC(sz) GC_debug_malloc_replacement(sz)
1373# define GC_REALLOC(old, sz) GC_debug_realloc_replacement(old, sz)
1374#elif defined(GC_DEBUG)
1375# define GC_MALLOC(sz) GC_debug_malloc(sz, GC_EXTRAS)
1376# define GC_REALLOC(old, sz) GC_debug_realloc(old, sz, GC_EXTRAS)
1377#else
1378# define GC_MALLOC(sz) GC_malloc(sz)
1379# define GC_REALLOC(old, sz) GC_realloc(old, sz)
1380#endif /* !GC_DEBUG_REPLACEMENT && !GC_DEBUG */
1381#ifdef GC_DEBUG
1382# define GC_MALLOC_ATOMIC(sz) GC_debug_malloc_atomic(sz, GC_EXTRAS)
1383# define GC_STRDUP(s) GC_debug_strdup(s, GC_EXTRAS)
1384# define GC_STRNDUP(s, sz) GC_debug_strndup(s, sz, GC_EXTRAS)
1385# define GC_MALLOC_ATOMIC_UNCOLLECTABLE(sz) \
1386 GC_debug_malloc_atomic_uncollectable(sz, GC_EXTRAS)
1387# define GC_MALLOC_UNCOLLECTABLE(sz) \
1388 GC_debug_malloc_uncollectable(sz, GC_EXTRAS)
1389# define GC_MALLOC_IGNORE_OFF_PAGE(sz) \
1390 GC_debug_malloc_ignore_off_page(sz, GC_EXTRAS)
1391# define GC_MALLOC_ATOMIC_IGNORE_OFF_PAGE(sz) \
1392 GC_debug_malloc_atomic_ignore_off_page(sz, GC_EXTRAS)
1393#else
1394# define GC_MALLOC_ATOMIC(sz) GC_malloc_atomic(sz)
1395# define GC_STRDUP(s) GC_strdup(s)
1396# define GC_STRNDUP(s, sz) GC_strndup(s, sz)
1397# define GC_MALLOC_ATOMIC_UNCOLLECTABLE(sz) GC_malloc_atomic_uncollectable(sz)
1398# define GC_MALLOC_UNCOLLECTABLE(sz) GC_malloc_uncollectable(sz)
1399# define GC_MALLOC_IGNORE_OFF_PAGE(sz) GC_malloc_ignore_off_page(sz)
1400# define GC_MALLOC_ATOMIC_IGNORE_OFF_PAGE(sz) \
1401 GC_malloc_atomic_ignore_off_page(sz)
1402#endif /* !GC_DEBUG */
1403
1404#ifdef GC_DEBUG
1405# define GC_FREE(p) GC_debug_free(p)
1406# define GC_REGISTER_FINALIZER(p, f, d, of, od) \
1407 GC_debug_register_finalizer(p, f, d, of, od)
1408# define GC_REGISTER_FINALIZER_IGNORE_SELF(p, f, d, of, od) \
1409 GC_debug_register_finalizer_ignore_self(p, f, d, of, od)
1410# define GC_REGISTER_FINALIZER_NO_ORDER(p, f, d, of, od) \
1411 GC_debug_register_finalizer_no_order(p, f, d, of, od)
1412# define GC_REGISTER_FINALIZER_UNREACHABLE(p, f, d, of, od) \
1413 GC_debug_register_finalizer_unreachable(p, f, d, of, od)
1414# define GC_TOGGLEREF_ADD(p, is_strong) GC_debug_toggleref_add(p, is_strong)
1415# define GC_END_STUBBORN_CHANGE(p) GC_debug_end_stubborn_change(p)
1416# define GC_PTR_STORE_AND_DIRTY(p, q) GC_debug_ptr_store_and_dirty(p, q)
1417# define GC_GENERAL_REGISTER_DISAPPEARING_LINK(link, obj) \
1418 GC_GENERAL_REGISTER_DISAPPEARING_LINK_SAFE(link, obj)
1419# define GC_REGISTER_LONG_LINK(link, obj) \
1420 GC_REGISTER_LONG_LINK_SAFE(link, obj)
1421# define GC_REGISTER_DISPLACEMENT(n) GC_debug_register_displacement(n)
1422#else
1423# define GC_FREE(p) GC_free(p)
1424# define GC_REGISTER_FINALIZER(p, f, d, of, od) \
1425 GC_register_finalizer(p, f, d, of, od)
1426# define GC_REGISTER_FINALIZER_IGNORE_SELF(p, f, d, of, od) \
1427 GC_register_finalizer_ignore_self(p, f, d, of, od)
1428# define GC_REGISTER_FINALIZER_NO_ORDER(p, f, d, of, od) \
1429 GC_register_finalizer_no_order(p, f, d, of, od)
1430# define GC_REGISTER_FINALIZER_UNREACHABLE(p, f, d, of, od) \
1431 GC_register_finalizer_unreachable(p, f, d, of, od)
1432# define GC_TOGGLEREF_ADD(p, is_strong) GC_toggleref_add(p, is_strong)
1433# define GC_END_STUBBORN_CHANGE(p) GC_end_stubborn_change(p)
1434# define GC_PTR_STORE_AND_DIRTY(p, q) GC_ptr_store_and_dirty(p, q)
1435# define GC_GENERAL_REGISTER_DISAPPEARING_LINK(link, obj) \
1436 GC_general_register_disappearing_link(link, obj)
1437# define GC_REGISTER_LONG_LINK(link, obj) GC_register_long_link(link, obj)
1438# define GC_REGISTER_DISPLACEMENT(n) GC_register_displacement(n)
1439#endif /* !GC_DEBUG */
1440
1441/**
1442 * Convenient macros for object allocation in C++ style. The use of
1443 * them also reduces the chance for a misspecified size argument.
1444 * But, note, that they may expand to something syntactically incorrect
1445 * if the argument is a complicated type expression. Note also, unlike
1446 * C++ new operator, these ones may return `NULL` (in case of out of
1447 * memory); however these macros are guaranteed never to return `NULL`
1448 * unless `GC_oom_fn()` returns `NULL`.
1449 */
1450#define GC_NEW(t) ((t *)GC_MALLOC(sizeof(t)))
1451#define GC_NEW_ATOMIC(t) ((t *)GC_MALLOC_ATOMIC(sizeof(t)))
1452#define GC_NEW_UNCOLLECTABLE(t) ((t *)GC_MALLOC_UNCOLLECTABLE(sizeof(t)))
1453
1454#ifdef GC_REQUIRE_WCSDUP
1455/**
1456 * Same as `GC_strdup` but for a `wchar_t` string. Might be
1457 * unavailable on some targets (or not needed). `wchar_t` type should
1458 * be defined in the platform `stddef.h` file. The function (including
1459 * its debug variant) is guaranteed never to return `NULL` unless
1460 * `GC_oom_fn()` returns `NULL`.
1461 */
1462GC_API GC_ATTR_MALLOC wchar_t *GC_CALL GC_wcsdup(const wchar_t *)
1463 GC_ATTR_NONNULL(1);
1464GC_API GC_ATTR_MALLOC wchar_t *GC_CALL GC_debug_wcsdup(const wchar_t *,
1465 GC_EXTRA_PARAMS)
1466 GC_ATTR_NONNULL(1);
1467# ifdef GC_DEBUG
1468# define GC_WCSDUP(s) GC_debug_wcsdup(s, GC_EXTRAS)
1469# else
1470# define GC_WCSDUP(s) GC_wcsdup(s)
1471# endif
1472#endif /* GC_REQUIRE_WCSDUP */
1473
1474/*
1475 * The finalization. Some of these primitives are grossly unsafe.
1476 * The idea is to make them both cheap, and sufficient to build
1477 * a safer layer, closer to Modula-3, Java, or PCedar finalization.
1478 * The interface represents my conclusions from a long discussion
1479 * with Alan Demers, Dan Greene, Carl Hauser, Barry Hayes,
1480 * Christian Jacobi, and Russ Atkinson. It is not perfect, and
1481 * probably nobody else agrees with it.
1482 */
1483
1484typedef void(GC_CALLBACK *GC_finalization_proc)(void * /* `obj` */,
1485 void * /* `client_data` */);
1486
1487/**
1488 * When `obj` is no longer accessible, invoke `(*fn)(obj, cd)`. If `a`
1489 * and `b` are inaccessible, and `a` points to `b` (after disappearing
1490 * links have been made to disappear), then only `a` will be finalized.
1491 * (If this does not create any new pointers to `b`, then `b` will be
1492 * finalized after the next collection.) Any finalizable object that
1493 * is reachable from itself by following one or more pointers will not
1494 * be finalized (or collected). Thus cycles involving finalizable
1495 * objects should be avoided, or broken by disappearing links. All but
1496 * the last finalizer registered for an object is ignored. No-op in
1497 * the find-leak mode. Finalization may be removed by passing 0 as
1498 * `fn`. Finalizers are implicitly unregistered when they are enqueued
1499 * for finalization (i.e. become ready to be finalized). The old
1500 * finalizer and client data are stored in `*ofn` and `*ocd`,
1501 * respectively. (`ofn` and/or `ocd` may be `NULL`. The allocator
1502 * lock is held while `*ofn` and `*ocd` are updated. In case of error
1503 * (no memory to register new finalizer), `*ofn` and `*ocd` remain
1504 * unchanged.) `fn` is never invoked on an accessible object, provided
1505 * hidden pointers are converted to real pointers only if the allocator
1506 * lock is held, at least in the reader mode, and such conversions are
1507 * not performed by finalization routines.
1508 * If `GC_register_finalizer()` is aborted as a result of a signal,
1509 * then the object may be left with no finalization, even if neither
1510 * the old nor new finalizer were `NULL`. `obj` should be the starting
1511 * address of an object allocated by `GC_malloc` or friends. `obj` may
1512 * also be `NULL` or point to something outside the collector heap (in
1513 * this case, `fn` is ignored, `*ofn` and `*ocd` are set to `NULL`).
1514 * Note that any garbage collectible object referenced by `cd` will be
1515 * considered accessible until the finalizer is invoked.
1516 */
1517GC_API void GC_CALL GC_register_finalizer(void * /* `obj` */,
1518 GC_finalization_proc /* `fn` */,
1519 void * /* `cd` */,
1520 GC_finalization_proc * /* `ofn` */,
1521 void ** /* `ocd` */)
1522 GC_ATTR_NONNULL(1);
1523GC_API void GC_CALL GC_debug_register_finalizer(
1524 void * /* `obj` */, GC_finalization_proc /* `fn` */, void * /* `cd` */,
1525 GC_finalization_proc * /* `ofn` */, void ** /* `ocd` */)
1526 GC_ATTR_NONNULL(1);
1527
1528/**
1529 * Another variant of `GC_register_finalizer` but ignoring self-cycles,
1530 * i.e. pointers from a finalizable object to itself. There is
1531 * a stylistic argument that this is wrong, but it is unavoidable for
1532 * C++, since the compiler may silently introduce these. It is also
1533 * benign in that specific case. And it helps if finalizable objects
1534 * are split to avoid cycles. Note that `cd` will still be viewed as
1535 * accessible, even if it refers to the object itself.
1536 */
1537GC_API void GC_CALL GC_register_finalizer_ignore_self(
1538 void * /* `obj` */, GC_finalization_proc /* `fn` */, void * /* `cd` */,
1539 GC_finalization_proc * /* `ofn` */, void ** /* `ocd` */)
1540 GC_ATTR_NONNULL(1);
1541GC_API void GC_CALL GC_debug_register_finalizer_ignore_self(
1542 void * /* `obj` */, GC_finalization_proc /* `fn` */, void * /* `cd` */,
1543 GC_finalization_proc * /* `ofn` */, void ** /* `ocd` */)
1544 GC_ATTR_NONNULL(1);
1545
1546/**
1547 * Another variant of `GC_register_finalizer` which ignores all cycles.
1548 * It should probably only be used by Java implementations. Note that
1549 * `cd` will still be viewed as accessible, even if it refers to the
1550 * object itself.
1551 */
1552GC_API void GC_CALL GC_register_finalizer_no_order(
1553 void * /* `obj` */, GC_finalization_proc /* `fn` */, void * /* `cd` */,
1554 GC_finalization_proc * /* `ofn` */, void ** /* `ocd` */)
1555 GC_ATTR_NONNULL(1);
1556GC_API void GC_CALL GC_debug_register_finalizer_no_order(
1557 void * /* `obj` */, GC_finalization_proc /* `fn` */, void * /* `cd` */,
1558 GC_finalization_proc * /* `ofn` */, void ** /* `ocd` */)
1559 GC_ATTR_NONNULL(1);
1560
1561/**
1562 * This is a special finalizer that is useful when an object's finalizer
1563 * must be run when the object is known to be no longer reachable, not even
1564 * from other finalizable objects. It behaves like "normal" finalization,
1565 * except that the finalizer is not run while the object is reachable from
1566 * other objects specifying unordered finalization. Effectively it allows
1567 * an object referenced, possibly indirectly, from an unordered finalizable
1568 * object to override the unordered finalization request. This can be used
1569 * in combination with `GC_register_finalizer_no_order` so as to release
1570 * resources that must not be released while an object can still be brought
1571 * back to life by other finalizers. Only works if `GC_java_finalization`
1572 * is set. Probably only of interest when implementing a language that
1573 * requires unordered finalization (e.g. Java, C#).
1574 */
1575GC_API void GC_CALL GC_register_finalizer_unreachable(
1576 void * /* `obj` */, GC_finalization_proc /* `fn` */, void * /* `cd` */,
1577 GC_finalization_proc * /* `ofn` */, void ** /* `ocd` */)
1578 GC_ATTR_NONNULL(1);
1579GC_API void GC_CALL GC_debug_register_finalizer_unreachable(
1580 void * /* `obj` */, GC_finalization_proc /* `fn` */, void * /* `cd` */,
1581 GC_finalization_proc * /* `ofn` */, void ** /* `ocd` */)
1582 GC_ATTR_NONNULL(1);
1583
1584/** A constant indicating a failure due to lack of memory. */
1585#define GC_NO_MEMORY 2
1586
1587/**
1588 * This routine may be used to break cycles between finalizable objects,
1589 * thus causing cyclic finalizable objects to be finalized in
1590 * the correct order. The standard use involves calling
1591 * `GC_register_disappearing_link(&p)`, where `p` is a pointer that is
1592 * not followed by finalization code, and should not be considered in
1593 * determining finalization order. `link` should point to a field of
1594 * a heap-allocated object. `*link` will be cleared when the object is
1595 * found to be inaccessible. This happens before any finalization code
1596 * is invoked, and before any decisions about finalization order are
1597 * made. This is useful in telling the finalizer that some pointers
1598 * are not essential for proper finalization. This may avoid
1599 * finalization cycles. Note that the object may be resurrected by
1600 * another finalizer, and thus the clearing of `*link` may be visible
1601 * to non-finalization code. There is an argument that an arbitrary
1602 * action should be allowed here, instead of just clearing a pointer.
1603 * But this causes problems if that action alters, or examines
1604 * connectivity. Returns `GC_DUPLICATE` if given `link` was already
1605 * registered, `GC_SUCCESS` if registration succeeded, `GC_NO_MEMORY`
1606 * if it failed for lack of memory (and `GC_oom_fn` did not handle the
1607 * problem). Only exists for backward compatibility, use
1608 * `GC_general_register_disappearing_link()` instead.
1609 */
1610GC_API int GC_CALL GC_register_disappearing_link(void ** /* `link` */)
1611 GC_ATTR_NONNULL(1);
1612
1613/**
1614 * A slight generalization of `GC_register_disappearing_link`.
1615 * `*link` is cleared when `obj` first becomes inaccessible. This can be
1616 * used to implement weak pointers easily and safely. Typically `link`
1617 * will point to a location (in a GC-allocated object or not) holding
1618 * a disguised pointer to `obj`. (A pointer inside an "atomic" object
1619 * is effectively disguised.) In this way, weak pointers are broken
1620 * before any object reachable from them gets finalized. Each `link`
1621 * may be registered only with one `obj` value, i.e. all objects but
1622 * the last one (`link` registered with) are ignored. `link` must be
1623 * non-`NULL` (and be properly aligned). `obj` must be a pointer to
1624 * the beginning of an object allocated by `GC_malloc` or friends.
1625 * A link disappears when it is unregistered manually, or when `*link`
1626 * is cleared, or when the object containing this `link` is garbage
1627 * collected. It is unsafe to explicitly deallocate the object
1628 * containing `link`. Explicit deallocation of `obj` may or may not
1629 * cause `link` to eventually be cleared. No-op in the find-leak mode.
1630 * This function can be used to implement certain types of weak pointers.
1631 * Note, however, this generally requires that the allocator lock is held,
1632 * at least in the reader mode (e.g. using `GC_call_with_reader_lock()`),
1633 * when the disguised pointer is accessed. Otherwise a strong pointer
1634 * could be recreated between the time the collector decides to reclaim
1635 * the object and the link is cleared. Returns `GC_SUCCESS` if
1636 * registration succeeded (a new link is registered), `GC_DUPLICATE` if
1637 * `link` was already registered (with some object), `GC_NO_MEMORY` if
1638 * registration failed for lack of memory (and `GC_oom_fn` did not handle
1639 * the problem), `GC_UNIMPLEMENTED` if `GC_find_leak` is true.
1640 */
1641GC_API int GC_CALL GC_general_register_disappearing_link(
1642 void ** /* `link` */, const void * /* `obj` */) GC_ATTR_NONNULL(1)
1643 GC_ATTR_NONNULL(2);
1644
1645/**
1646 * Moves a `link` previously registered via
1647 * `GC_general_register_disappearing_link` (or
1648 * `GC_register_disappearing_link`). Does not change the target object
1649 * of the weak reference. Does not change `*new_link` content. May be
1650 * called with `new_link` equal to `link` (to check whether `link` has
1651 * been registered). Returns `GC_SUCCESS` on success, `GC_DUPLICATE`
1652 * if there is already another disappearing link at the new location
1653 * (never returned if `new_link` is equal to `link`), `GC_NOT_FOUND`
1654 * if no `link` is registered at the original location.
1655 */
1656GC_API int GC_CALL GC_move_disappearing_link(void ** /* `link` */,
1657 void ** /* `new_link` */)
1658 GC_ATTR_NONNULL(2);
1659
1660/**
1661 * Undoes a registration by either `GC_register_disappearing_link()` or
1662 * `GC_general_register_disappearing_link()`. Returns 0 if `link` was
1663 * not actually registered (otherwise returns 1).
1664 */
1665GC_API int GC_CALL GC_unregister_disappearing_link(void ** /* `link` */);
1666
1667/**
1668 * Similar to `GC_general_register_disappearing_link` but `*link` only
1669 * gets cleared when `obj` becomes truly inaccessible. An object becomes
1670 * truly inaccessible when it can no longer be resurrected from its
1671 * finalizer (e.g. by assigning itself to a pointer traceable from root).
1672 * This can be used to implement "long" weak pointers easily and safely.
1673 */
1674GC_API int GC_CALL GC_register_long_link(void ** /* `link` */,
1675 const void * /* `obj` */)
1676 GC_ATTR_NONNULL(1) GC_ATTR_NONNULL(2);
1677
1678/**
1679 * Similar to `GC_move_disappearing_link` but for a `link` previously
1680 * registered via `GC_register_long_link`.
1681 */
1682GC_API int GC_CALL GC_move_long_link(void ** /* `link` */,
1683 void ** /* `new_link` */)
1684 GC_ATTR_NONNULL(2);
1685
1686/**
1687 * Similar to `GC_unregister_disappearing_link` but for `link`
1688 * registration done by `GC_register_long_link()`.
1689 */
1690GC_API int GC_CALL GC_unregister_long_link(void ** /* `link` */);
1691
1692/*
1693 * Support of "toggle-refs" style of external memory management without
1694 * hooking up to the host retain/release machinery. The idea of
1695 * "toggle-refs" is that an external reference to an object is kept and
1696 * it can be either a strong or weak reference; a weak reference is
1697 * used when the external peer has no interest in the object, and
1698 * a strong otherwise.
1699 */
1700
1701typedef enum {
1702 GC_TOGGLE_REF_DROP,
1703 GC_TOGGLE_REF_STRONG,
1704 GC_TOGGLE_REF_WEAK
1705} GC_ToggleRefStatus;
1706
1707/**
1708 * The callback is to decide (return) the new state of a given object.
1709 * Invoked by the collector for all objects registered for "toggle-refs"
1710 * processing. Invoked with the allocator lock held but the world is
1711 * running.
1712 */
1713typedef GC_ToggleRefStatus(GC_CALLBACK *GC_toggleref_func)(void * /* `obj` */);
1714
1715/**
1716 * Set (register) a callback that decides the state of a given object (by,
1717 * probably, inspecting its native state). The argument may be 0 (means
1718 * no callback). Both the setter and the getter acquire the allocator lock
1719 * (in the reader mode in case of the getter).
1720 */
1721GC_API void GC_CALL GC_set_toggleref_func(GC_toggleref_func);
1722GC_API GC_toggleref_func GC_CALL GC_get_toggleref_func(void);
1723
1724/**
1725 * Register a given object for "toggle-refs" processing. It will be
1726 * stored internally and the "toggle-refs" callback will be invoked on
1727 * the object until the callback returns `GC_TOGGLE_REF_DROP` or the
1728 * object is collected. If `is_strong`, then the object is registered
1729 * with a strong ref, a weak one otherwise. `obj` should be the starting
1730 * address of an object allocated by `GC_malloc` (`GC_debug_malloc`)
1731 * or friends. Returns `GC_SUCCESS` if registration succeeded (or no
1732 * callback is registered yet), `GC_NO_MEMORY` if it failed for a lack
1733 * of memory reason.
1734 */
1735GC_API int GC_CALL GC_toggleref_add(void * /* `obj` */, int /* `is_strong` */)
1736 GC_ATTR_NONNULL(1);
1737GC_API int GC_CALL GC_debug_toggleref_add(void * /* `obj` */,
1738 int /* `is_strong` */)
1739 GC_ATTR_NONNULL(1);
1740
1741/**
1742 * Finalizer callback support. Invoked by the collector (with the allocator
1743 * lock held) for each unreachable object enqueued for finalization.
1744 * Zero means no callback. The setter and the getter acquire the allocator
1745 * lock too (in the reader mode in case of the getter).
1746 */
1747typedef void(GC_CALLBACK *GC_await_finalize_proc)(void * /* `obj` */);
1748GC_API void GC_CALL GC_set_await_finalize_proc(GC_await_finalize_proc);
1749GC_API GC_await_finalize_proc GC_CALL GC_get_await_finalize_proc(void);
1750
1751/**
1752 * Returns a nonzero value (true) if `GC_invoke_finalizers()` has
1753 * something to do. (Useful if finalizers can only be called from some
1754 * kind of "safe state" and getting into that safe state is expensive.)
1755 * Does not use any synchronization.
1756 */
1757GC_API int GC_CALL GC_should_invoke_finalizers(void);
1758
1759/**
1760 * Set maximum amount of finalizers to run during a single invocation
1761 * of `GC_invoke_finalizers()`. Zero means no limit. Both the setter
1762 * and the getter acquire the allocator lock (in the reader mode in
1763 * case of the getter). Note that invocation of `GC_finalize_all()`
1764 * resets the maximum amount value.
1765 */
1766GC_API void GC_CALL GC_set_interrupt_finalizers(unsigned);
1767GC_API unsigned GC_CALL GC_get_interrupt_finalizers(void);
1768
1769/**
1770 * Run finalizers for all objects that are ready to be finalized.
1771 * Return the number of finalizers that were run. Normally this is
1772 * also called implicitly during some allocations.
1773 * If `GC_finalize_on_demand` is nonzero, it must be called explicitly.
1774 */
1775GC_API int GC_CALL GC_invoke_finalizers(void);
1776
1777/*
1778 * Explicitly tell the collector that an object is reachable
1779 * at a particular program point. This prevents the argument
1780 * pointer from being optimized away, even it is otherwise no
1781 * longer needed. It should have no visible effect in the
1782 * absence of finalizers or disappearing links. But it may be
1783 * needed to prevent finalizers from running while the
1784 * associated external resource is still in use.
1785 * The function is sometimes called to keep some object alive.
1786 */
1787#if defined(__GNUC__) && !defined(__INTEL_COMPILER) \
1788 && !(defined(__APPLE__) && (defined(__arm__) || defined(__aarch64__)) \
1789 && defined(__TINYC__))
1790/* TCC (as of v0.9.28rc) does not support asm on macOS/arm (32 or 64 bit). */
1791# if defined(__CHERI_PURE_CAPABILITY__) || defined(__TINYC__)
1792# define GC_reachable_here(ptr) \
1793 __asm__ __volatile__(" " : : "g"(ptr) : "memory")
1794# elif defined(__e2k__)
1795# define GC_reachable_here(ptr) \
1796 __asm__ __volatile__(" " : : "r"(ptr) : "memory")
1797# else
1798# define GC_reachable_here(ptr) \
1799 __asm__ __volatile__(" " : : "X"(ptr) : "memory")
1800# endif
1801#elif defined(LINT2)
1802/* The definition is similar to that of `COVERT_DATAFLOW()`. */
1803# define GC_reachable_here(ptr) GC_noop1(~(GC_word)(ptr) ^ (~(GC_word)0))
1804#else
1805# define GC_reachable_here(ptr) GC_noop1_ptr(GC_CAST_AWAY_CONST_PVOID(ptr))
1806#endif
1807
1808/**
1809 * Make the argument of `GC_word` type appear live to compiler.
1810 * This could be used to prevent certain compiler false positive (FP)
1811 * warnings and misoptimizations. Should be robust against the whole
1812 * program analysis.
1813 */
1814GC_API void GC_CALL GC_noop1(GC_word);
1815
1816/** Same as `GC_noop1()` but for a pointer. */
1817GC_API void GC_CALL GC_noop1_ptr(volatile void *);
1818
1819/**
1820 * `GC_set_warn_proc` can be used to redirect or filter warning messages.
1821 * `p` may not be a `NULL` pointer. `msg` is a `printf` format string
1822 * (`arg` must match the format). Both the setter and the getter acquire
1823 * the allocator lock (in the reader mode in case of the getter) to avoid
1824 * data race. In GC v7.1 and before: the setter returned the value of
1825 * old `warn_proc`. In GC v8.2.x and before: `msg` pointer type had
1826 * no `const` qualifier.
1827 */
1828typedef void(GC_CALLBACK *GC_warn_proc)(const char * /* `msg` */,
1829 GC_uintptr_t /* `arg` */);
1830GC_API void GC_CALL GC_set_warn_proc(GC_warn_proc /* `p` */)
1831 GC_ATTR_NONNULL(1);
1832GC_API GC_warn_proc GC_CALL GC_get_warn_proc(void);
1833
1834/**
1835 * `GC_ignore_warn_proc` may be used as an argument for `GC_set_warn_proc()`
1836 * to suppress all warnings (unless statistics printing is turned on).
1837 * This is recommended for production code (release).
1838 */
1839GC_API void GC_CALLBACK GC_ignore_warn_proc(const char *, GC_uintptr_t);
1840
1841/**
1842 * Change file descriptor of the collector log. Unavailable on some
1843 * targets.
1844 */
1845GC_API void GC_CALL GC_set_log_fd(int);
1846
1847/**
1848 * This is invoked on the collector fatal aborts (just before
1849 * OS-dependent `abort()` or `exit(1)` is called). Must be non-`NULL`.
1850 * The default one outputs `msg` to the platform `stderr` provided
1851 * `msg` is non-`NULL`. `msg` is `NULL` if invoked before `exit(1)`
1852 * otherwise `msg` is non-`NULL` (i.e., if invoked before `abort`).
1853 * Both the setter and the getter acquire the allocator lock (in the reader
1854 * mode in case of the getter). The setter does not change `GC_abort_func`
1855 * if the library has been compiled with `SMALL_CONFIG` macro defined.
1856 */
1857typedef void(GC_CALLBACK *GC_abort_func)(const char * /* `msg` */);
1858GC_API void GC_CALL GC_set_abort_func(GC_abort_func) GC_ATTR_NONNULL(1);
1859GC_API GC_abort_func GC_CALL GC_get_abort_func(void);
1860
1861/*
1862 * Clients should define `GC_EXIT_LACKS_NORETURN` macro if the platform
1863 * `exit()` does not have a `noreturn` attribute.
1864 */
1865#ifdef GC_EXIT_LACKS_NORETURN
1866# define GC_OOM_ABORT_THROW_ATTRIBUTE /*< empty */
1867#else
1868# define GC_OOM_ABORT_THROW_ATTRIBUTE GC_ATTR_NORETURN
1869#endif
1870
1871/** A portable way to abort the application because of not enough memory. */
1872GC_API GC_OOM_ABORT_THROW_ATTRIBUTE void GC_CALL GC_abort_on_oom(void);
1873
1874/*
1875 * The following is intended to be used by a higher level (e.g.
1876 * Java-like) finalization facility. It is expected that finalization
1877 * code will arrange for hidden pointers to disappear. Otherwise,
1878 * objects can be accessed after they have been collected. Should not
1879 * be used in the find-leak mode.
1880 * Note that putting pointers in atomic objects or in non-pointer slots
1881 * of "typed" objects is equivalent to disguising them in this way, and
1882 * may have other advantages. Note also that some code relies on that
1883 * the least significant bit of the argument (including for `NULL`) is
1884 * inverted by these primitives.
1885 * Important: converting a hidden pointer to a real pointer requires
1886 * verifying that the object still exists; this should involve
1887 * acquiring the allocator lock, at least in the reader mode, to avoid
1888 * a race with the collector (e.g., one thread might fetch hidden link
1889 * value, while another thread might collect the relevant object and
1890 * reuse the free space for another object).
1891 */
1892typedef GC_uintptr_t GC_hidden_pointer;
1893#define GC_HIDE_POINTER(p) (~(GC_hidden_pointer)(p))
1894#define GC_REVEAL_POINTER(p) ((void *)GC_HIDE_POINTER(p))
1895
1896#if defined(I_HIDE_POINTERS) || defined(GC_I_HIDE_POINTERS)
1897/*
1898 * This exists only for compatibility (the GC-prefixed symbols are
1899 * preferred for new code).
1900 */
1901# define HIDE_POINTER(p) GC_HIDE_POINTER(p)
1902# define REVEAL_POINTER(p) GC_REVEAL_POINTER(p)
1903#endif
1904
1905/*
1906 * A slightly modified variant of `GC_HIDE_POINTER` which guarantees
1907 * not to "hide" `NULL` (i.e. passing zero argument gives zero result).
1908 * This might be useful in conjunction with `GC_register_disappearing_link`.
1909 * Note that unlike `GC_HIDE_POINTER`, inversion of the least significant
1910 * bit of the argument is not guaranteed.
1911 */
1912#if defined(__CHERI_PURE_CAPABILITY__)
1913# define GC_HIDE_NZ_POINTER(p) ((GC_hidden_pointer)(-(intptr_t)(p)))
1914#else
1915# define GC_HIDE_NZ_POINTER(p) ((GC_hidden_pointer)(-(GC_signed_word)(p)))
1916#endif
1917#define GC_REVEAL_NZ_POINTER(p) ((void *)GC_HIDE_NZ_POINTER(p))
1918
1919/*
1920 * The routines to acquire/release the GC (allocator) lock.
1921 * The lock is not reentrant. `GC_alloc_unlock()` should not be called
1922 * unless the allocator lock is acquired by the current thread.
1923 */
1924#ifdef GC_THREADS
1925GC_API void GC_CALL GC_alloc_lock(void);
1926GC_API void GC_CALL GC_alloc_unlock(void);
1927#else
1928/* No need for real locking if the client is single-threaded. */
1929# define GC_alloc_lock() (void)0
1930# define GC_alloc_unlock() (void)0
1931#endif /* !GC_THREADS */
1932
1933typedef void *(GC_CALLBACK *GC_fn_type)(void * /* `client_data` */);
1934
1935/**
1936 * Execute given function with the allocator lock held (in the exclusive
1937 * mode).
1938 */
1939GC_API void *GC_CALL GC_call_with_alloc_lock(GC_fn_type /* `fn` */,
1940 void * /* `client_data` */)
1941 GC_ATTR_NONNULL(1);
1942
1943/*
1944 * Execute given function with the allocator lock held in the reader
1945 * (shared) mode. The 3rd argument (`release`), if nonzero, indicates
1946 * that `fn` might write some data that should be made visible to the
1947 * thread which acquires the allocator lock in the exclusive mode later.
1948 */
1949#ifdef GC_THREADS
1950GC_API void *GC_CALL GC_call_with_reader_lock(GC_fn_type /* `fn` */,
1951 void * /* `client_data` */,
1952 int /* `release` */)
1953 GC_ATTR_NONNULL(1);
1954#else
1955# define GC_call_with_reader_lock(fn, cd, r) ((void)(r), (fn)(cd))
1956#endif
1957
1958/*
1959 * These routines are intended to explicitly notify the collector
1960 * of new threads. Often this is unnecessary because thread creation
1961 * is implicitly intercepted by the collector, using header-file defines,
1962 * or linker-based interception. In the long run, the intent is to
1963 * always make redundant registration safe. In the short run, this is
1964 * being implemented a platform at a time. The interface is complicated
1965 * by the fact that we probably will not ever be able to automatically
1966 * determine the stack bottom for thread stacks on all platforms.
1967 */
1968
1969/**
1970 * Structure representing the bottom (cold end) of a thread stack.
1971 * On most platforms this contains just a single address.
1972 */
1973struct GC_stack_base {
1974 /* The bottom of the general-purpose stack. */
1975 void *mem_base;
1976#if defined(__e2k__) || defined(__ia64) || defined(__ia64__) \
1977 || defined(_M_IA64)
1978 /* The bottom of the register stack. */
1979 void *reg_base;
1980#endif
1981};
1982
1983typedef void *(GC_CALLBACK *GC_stack_base_func)(
1984 struct GC_stack_base * /* `sb` */, void * /* `arg` */);
1985
1986/**
1987 * Call a function with a stack base structure corresponding to somewhere in
1988 * the `GC_call_with_stack_base` frame. This often can be used to provide
1989 * a sufficiently accurate stack bottom. And we implement it everywhere.
1990 */
1991GC_API void *GC_CALL GC_call_with_stack_base(GC_stack_base_func /* fn */,
1992 void * /* arg */)
1993 GC_ATTR_NONNULL(1);
1994
1995#define GC_SUCCESS 0
1996
1997/** Means was already registered. */
1998#define GC_DUPLICATE 1
1999
2000/* Deprecated. No thread support in the collector. */
2001#define GC_NO_THREADS 2
2002
2003/** Not yet implemented on this platform. */
2004#define GC_UNIMPLEMENTED 3
2005
2006/** Requested `link` not found (returned by `GC_move_disappearing_link()`). */
2007#define GC_NOT_FOUND 4
2008
2009/**
2010 * Start the parallel marker threads, if available. Useful, e.g.,
2011 * after POSIX `fork` in a child process (provided not followed by
2012 * `exec()`) or in single-threaded clients (provided it is OK for the
2013 * client to perform marking in parallel). Acquires the allocator lock
2014 * to avoid a race.
2015 */
2016GC_API void GC_CALL GC_start_mark_threads(void);
2017
2018#if defined(GC_DARWIN_THREADS) || defined(GC_WIN32_THREADS)
2019/**
2020 * Use implicit thread registration and processing (via Win32 `DllMain`
2021 * or Darwin `task_threads`). Deprecated. Must be called before
2022 * `GC_INIT()` and other GC routines (or, at least, before going
2023 * multi-threaded). Performs the collector initialization. Should be
2024 * avoided if `GC_pthread_create`, `GC_beginthreadex` (or `GC_CreateThread`),
2025 * or `GC_register_my_thread` could be used instead. Disables parallelized
2026 * garbage collection on Win32.
2027 */
2028GC_API void GC_CALL GC_use_threads_discovery(void);
2029#endif
2030
2031#ifdef GC_THREADS
2032/**
2033 * Suggest the collector to use the specific signal to suspend threads.
2034 * Has no effect after the collector initialization and on non-POSIX systems.
2035 */
2036GC_API void GC_CALL GC_set_suspend_signal(int);
2037
2038/**
2039 * Return the signal number (which is a constant after the collector
2040 * initialization) used by the collector to suspend threads on POSIX systems.
2041 * Return -1 otherwise.
2042 */
2043GC_API int GC_CALL GC_get_suspend_signal(void);
2044
2045/**
2046 * Suggest the collector to use the specific signal to resume threads.
2047 * Has no effect after the collector initialization and on non-POSIX systems.
2048 * The same signal might be used for threads suspension and restart.
2049 */
2050GC_API void GC_CALL GC_set_thr_restart_signal(int);
2051
2052/**
2053 * Return the signal number (which is a constant after the collector
2054 * initialization) used by the collector to restart (resume) threads on
2055 * POSIX systems. Return -1 otherwise.
2056 */
2057GC_API int GC_CALL GC_get_thr_restart_signal(void);
2058
2059/**
2060 * Explicitly enable `GC_register_my_thread()` invocation.
2061 * Done implicitly if a GC thread-creation function is called
2062 * (or implicit thread registration is activated, or the collector is
2063 * compiled with `GC_ALWAYS_MULTITHREADED` macro defined). Otherwise,
2064 * it must be called from the main (or any previously registered)
2065 * thread between the collector initialization and the first explicit
2066 * registering of a thread (it should be called as late as possible).
2067 * Includes a `GC_start_mark_threads()` call.
2068 */
2069GC_API void GC_CALL GC_allow_register_threads(void);
2070
2071/**
2072 * Register the current thread, with the indicated stack bottom, as
2073 * a new thread whose stack(s) should be traced by the collector.
2074 * If it is not implicitly called by the collector, this must be called
2075 * before a thread can allocate garbage-collected memory, or assign
2076 * pointers to the garbage-collected heap. Once registered, a thread
2077 * will be stopped during garbage collections. This call must be
2078 * previously enabled (see `GC_allow_register_threads`). This should
2079 * never be called from the main thread, where it is always done
2080 * implicitly. This is normally done implicitly if `GC_` functions are
2081 * called to create the thread, e.g. by include `gc.h` file (which
2082 * redefines some system functions) before calling the system thread
2083 * creation function. Nonetheless, thread cleanup routines (e.g.,
2084 * `pthreads` key destructor) typically require manual thread
2085 * registering (and unregistering) if pointers to GC-allocated objects
2086 * are manipulated inside. It is also always done implicitly on some
2087 * platforms if `GC_use_threads_discovery()` is called at start-up.
2088 * Except for the latter case, the explicit call is normally required
2089 * for threads created by third-party libraries. A manually registered
2090 * thread requires manual unregistering. Returns `GC_SUCCESS` on
2091 * success, `GC_DUPLICATE` if already registered.
2092 */
2093GC_API int GC_CALL GC_register_my_thread(const struct GC_stack_base *)
2094 GC_ATTR_NONNULL(1);
2095
2096/**
2097 * Return 1 (true) if the calling (current) thread is registered with the
2098 * garbage collector, 0 otherwise. Acquires the allocator lock in the
2099 * reader mode. If the thread is finished (e.g. running in a destructor
2100 * and not registered manually again), then it is considered as not
2101 * registered.
2102 */
2103GC_API int GC_CALL GC_thread_is_registered(void);
2104
2105/**
2106 * Notify the collector about the stack and the alt-stack of the current
2107 * thread. `normstack` and `normstack_size` are used to determine the
2108 * "normal" stack boundaries when a thread is suspended while it is on
2109 * an alt-stack. Acquires the allocator lock in the reader mode.
2110 */
2111GC_API void GC_CALL GC_register_altstack(void * /* `normstack` */,
2112 size_t /* `normstack_size` */,
2113 void * /* `altstack` */,
2114 size_t /* `altstack_size` */);
2115
2116/**
2117 * Unregister the current thread. Only an explicitly registered thread
2118 * (i.e. for which `GC_register_my_thread()` returns `GC_SUCCESS`)
2119 * is allowed (and required) to call this function. (As a special
2120 * exception, it is also allowed to once unregister the main thread.)
2121 * The thread may no longer allocate garbage-collected memory or
2122 * manipulate pointers to the garbage-collected heap after making this
2123 * call. Specifically, if it wants to return or otherwise communicate
2124 * a pointer to the garbage-collected heap to another thread, it must
2125 * do this before calling `GC_unregister_my_thread`, most probably by
2126 * saving it in a global data structure. Must not be called inside
2127 * a GC callback function (except for `GC_call_with_stack_base()` one).
2128 * Always returns `GC_SUCCESS`.
2129 */
2130GC_API int GC_CALL GC_unregister_my_thread(void);
2131
2132/** Stop/start the world explicitly. Not recommended for general use. */
2133GC_API void GC_CALL GC_stop_world_external(void);
2134GC_API void GC_CALL GC_start_world_external(void);
2135
2136/**
2137 * Provide a verifier/modifier of the stack pointer when pushing the
2138 * thread stacks. This might be useful for a crude integration
2139 * with certain coroutine implementations. `*sp_ptr` is the captured
2140 * stack pointer of the suspended thread with `pthread_id` (the latter
2141 * is actually of `pthread_t` type). The functionality is unsupported
2142 * on some targets (the getter always returns 0 in such a case).
2143 * Both the setter and the getter acquire the allocator lock (in the reader
2144 * mode in case of the getter). The client function (if provided) is called
2145 * with the allocator lock held and, might be, with the world stopped.
2146 */
2147typedef void(GC_CALLBACK *GC_sp_corrector_proc)(void ** /* `sp_ptr` */,
2148 void * /* `pthread_id` */);
2149GC_API void GC_CALL GC_set_sp_corrector(GC_sp_corrector_proc);
2150GC_API GC_sp_corrector_proc GC_CALL GC_get_sp_corrector(void);
2151#endif /* GC_THREADS */
2152
2153/**
2154 * Wrapper for functions that are likely to block (or, at least, do not
2155 * allocate garbage-collected memory and/or manipulate pointers to the
2156 * garbage-collected heap) for an appreciable length of time.
2157 * While `fn` is running, the collector is said to be in the "inactive"
2158 * state for the current thread (this means that the thread is not
2159 * suspended and the thread's stack frames "belonging" to the functions
2160 * in the "inactive" state are not scanned during garbage collections).
2161 * It is assumed that the collector is already initialized and the
2162 * current thread is registered. It is allowed for `fn` to call
2163 * `GC_call_with_gc_active()` (even recursively), thus temporarily
2164 * toggling the collector's state back to "active". The latter
2165 * technique might be used to make stack scanning more precise (i.e.
2166 * scan only stack frames of functions that allocate garbage-collected
2167 * memory and/or manipulate pointers to the garbage-collected heap).
2168 * Acquires the allocator lock in the reader mode (but `fn` is called
2169 * not holding it).
2170 */
2171GC_API void *GC_CALL GC_do_blocking(GC_fn_type /* `fn` */,
2172 void * /* `client_data` */)
2173 GC_ATTR_NONNULL(1);
2174
2175/**
2176 * Call a function switching to the "active" state of the collector for
2177 * the current thread (i.e. the user function is temporarily back
2178 * allowed to call any GC function and/or manipulate pointers to the
2179 * garbage-collected heap). `GC_call_with_gc_active()` has the
2180 * functionality opposite to `GC_do_blocking()` one. It is assumed
2181 * that the collector is already initialized and the current thread is
2182 * registered. `fn` may toggle the collector thread's state
2183 * temporarily to "inactive" one by using `GC_do_blocking()`.
2184 * `GC_call_with_gc_active()` often can be used to provide
2185 * a sufficiently accurate stack bottom. Acquires the allocator lock
2186 * in the reader mode (but `fn` is called not holding it).
2187 */
2188GC_API void *GC_CALL GC_call_with_gc_active(GC_fn_type /* `fn` */,
2189 void * /* `client_data` */)
2190 GC_ATTR_NONNULL(1);
2191
2192/**
2193 * Attempt to fill in the `GC_stack_base` structure with the stack
2194 * bottom for this thread. This appears to be required to implement
2195 * anything like the JNI (Java Native Interface) `AttachCurrentThread`
2196 * in an environment in which new threads are not automatically registered
2197 * with the collector. It is also unfortunately hard to implement well
2198 * on many platforms. Returns `GC_SUCCESS` or `GC_UNIMPLEMENTED`.
2199 * Acquires the allocator lock on some platforms.
2200 */
2201GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *)
2202 GC_ATTR_NONNULL(1);
2203
2204/**
2205 * Fill in the GC_stack_base structure with the cold end (bottom) of
2206 * the stack of the current thread (or coroutine).
2207 * Unlike `GC_get_stack_base`, it retrieves the value stored in the
2208 * collector (which is initially set by the collector upon the thread
2209 * is started or registered manually but it could be later updated by
2210 * client using `GC_set_stackbottom`). Returns the GC-internal
2211 * non-`NULL` handle of the thread which could be passed to
2212 * `GC_set_stackbottom()` later. It is assumed that the collector is
2213 * already initialized and the thread is registered. Acquires the
2214 * allocator lock in the reader mode.
2215 */
2216GC_API void *GC_CALL GC_get_my_stackbottom(struct GC_stack_base *)
2217 GC_ATTR_NONNULL(1);
2218
2219/**
2220 * Set the cool end of the user (coroutine) stack of the specified thread.
2221 * The GC thread handle (`gc_thread_handle`) is either the one returned by
2222 * `GC_get_my_stackbottom()` or `NULL` (the latter designates the current
2223 * thread). The caller should hold the allocator lock (e.g. using
2224 * `GC_call_with_reader_lock()` with `release` argument set to 1), the
2225 * reader mode should be enough typically, at least for the collector
2226 * itself (the client is responsible to avoid data race between this and
2227 * `GC_get_my_stackbottom` functions if the client acquires the allocator
2228 * lock in the reader mode). Also, the function could be used for setting
2229 * `GC_stackbottom` value (the bottom of the primordial thread) before the
2230 * collector is initialized (the allocator lock is not needed to be
2231 * acquired at all in this case).
2232 */
2233GC_API void GC_CALL GC_set_stackbottom(void * /* `gc_thread_handle` */,
2234 const struct GC_stack_base *)
2235 GC_ATTR_NONNULL(2);
2236
2237/*
2238 * The following routines are primarily intended for use with a preprocessor
2239 * which inserts calls to check C pointer arithmetic. They indicate failure
2240 * by invoking the corresponding print procedure (`GC_same_obj_print_proc`,
2241 * `GC_is_valid_displacement_print_proc` or `GC_is_visible_print_proc`).
2242 */
2243
2244/**
2245 * Checked pointer pre- and post-increment operations. Note that the second
2246 * argument (`how_much`) is in units of bytes, not multiples of the object
2247 * size. This should either be invoked from a macro, or the call should be
2248 * automatically generated.
2249 */
2250GC_API void *GC_CALL GC_pre_incr(void **, ptrdiff_t /* `how_much` */)
2251 GC_ATTR_NONNULL(1);
2252GC_API void *GC_CALL GC_post_incr(void **, ptrdiff_t /* `how_much` */)
2253 GC_ATTR_NONNULL(1);
2254
2255/**
2256 * Check that `p` and `q` point to the same object.
2257 * `GC_same_obj_print_proc` is called (fail by default) if they do not.
2258 * Succeeds, as well, if neither `p` nor `q` points to the heap.
2259 * (May succeed also if both `p` and `q` point to between heap objects.)
2260 * Returns the first argument (`p`). (The returned value may be hard to
2261 * use due to typing issues. But if we had a suitable preprocessor...)
2262 * We assume this is somewhat performance critical (it should not be
2263 * called by production code, of course, but it can easily make even
2264 * debugging intolerably slow).
2265 */
2266GC_API void *GC_CALL GC_same_obj(void * /* `p` */, void * /* `q` */);
2267
2268/**
2269 * Check that `p` is visible to the collector as a possibly pointer
2270 * containing location. If it is not, call `GC_is_visible_print_proc`
2271 * (fail by default). Always returns the argument (`p`).
2272 * May erroneously succeed in hard cases. The function is intended for
2273 * debugging use with untyped allocations. (The idea is that it should
2274 * be possible, though slow, to add such a call to all indirect pointer
2275 * stores.) Currently almost useless for the multi-threaded worlds.
2276 */
2277GC_API void *GC_CALL GC_is_visible(void * /* p */);
2278
2279/**
2280 * Check that if `p` is a pointer to a heap page, then it points to
2281 * a valid displacement within a heap object. If it is not, invoke
2282 * `GC_is_valid_displacement_print_proc` (fail by default).
2283 * Always returns the argument (`p`). Uninteresting in the
2284 * all-interior-pointers mode. Note that we do not acquire the
2285 * allocator lock, since nothing relevant about the header should
2286 * change while we have a valid object pointer to the block.
2287 */
2288GC_API void *GC_CALL GC_is_valid_displacement(void * /* `p` */);
2289
2290/**
2291 * Explicitly dump the collector state. This is most often called from
2292 * the debugger, or by setting the `GC_DUMP_REGULARLY` environment
2293 * variable, but it may be useful to call it from client code during
2294 * debugging. The current collection number is printed in the header
2295 * of the dump. Acquires the allocator lock in the reader mode to
2296 * avoid data race. Defined only if the library has been compiled
2297 * without `NO_DEBUGGING` macro defined.
2298 */
2299GC_API void GC_CALL GC_dump(void);
2300
2301/**
2302 * The same as `GC_dump` but allows to specify the name of dump and
2303 * does not acquire the allocator lock. If `name` is non-`NULL`, it is
2304 * printed to help identifying individual dumps. Otherwise the current
2305 * collection number is used as the name. Defined only if the library
2306 * has been compiled without `NO_DEBUGGING` macro defined.
2307 */
2308GC_API void GC_CALL GC_dump_named(const char * /* `name` */);
2309
2310/**
2311 * Dump information about each block of every GC memory section.
2312 * Defined only if the library has been compiled without `NO_DEBUGGING`
2313 * macro defined.
2314 */
2315GC_API void GC_CALL GC_dump_regions(void);
2316
2317/**
2318 * Dump information about every registered disappearing link and
2319 * finalizable object. Defined only if the library has been compiled
2320 * without `NO_DEBUGGING` macro defined.
2321 */
2322GC_API void GC_CALL GC_dump_finalization(void);
2323
2324typedef enum {
2325 GC_HEAP_SECTION_TYPE_FREE,
2326 GC_HEAP_SECTION_TYPE_PADDING,
2327 GC_HEAP_SECTION_TYPE_USED,
2328 GC_HEAP_SECTION_TYPE_UNMAPPED,
2329 GC_HEAP_SECTION_TYPE_FORWARDING,
2330 GC_HEAP_SECTION_TYPE_WHOLE_SECT
2331} GC_heap_section_type;
2332
2333typedef void(GC_CALLBACK *GC_heap_section_proc)(
2334 void * /* `start` */, void * /* `finish` */,
2335 GC_heap_section_type /* `type` */, void * /* `client_data` */);
2336
2337/**
2338 * Apply `fn` to each heap section and each heap block inside.
2339 * Similar to `GC_apply_to_all_blocks()`. Assumes the allocator lock
2340 * is held at least in the reader mode, but no assertion about it
2341 * by design. Defined only if the library has been compiled without
2342 * `NO_DEBUGGING` macro defined.
2343 */
2344GC_API void GC_CALL GC_foreach_heap_section_inner(GC_heap_section_proc fn,
2345 void *client_data)
2346 GC_ATTR_NONNULL(1);
2347
2348/*
2349 * Safer, but slow, pointer addition. Probably useful mainly with
2350 * a preprocessor. Useful only for heap pointers. Only the macros
2351 * without trailing digits are meant to be used by clients. These are
2352 * designed to model the available C pointer arithmetic expressions.
2353 * Even then, these are probably more useful as documentation than as
2354 * a part of the API. Note that `GC_PTR_ADD()` evaluates the first
2355 * argument more than once.
2356 */
2357#if defined(GC_DEBUG) && (defined(__GNUC__) || defined(__clang__))
2358# define GC_PTR_ADD3(x, n, type_of_result) \
2359 ((type_of_result)GC_same_obj((x) + (n), (x)))
2360# define GC_PRE_INCR3(x, n, type_of_result) \
2361 ((type_of_result)GC_pre_incr((void **)&(x), (n) * sizeof(*(x))))
2362# define GC_POST_INCR3(x, n, type_of_result) \
2363 ((type_of_result)GC_post_incr((void **)&(x), (n) * sizeof(*(x))))
2364# define GC_PTR_ADD(x, n) GC_PTR_ADD3(x, n, __typeof__(x))
2365# define GC_PRE_INCR(x, n) GC_PRE_INCR3(x, n, __typeof__(x))
2366# define GC_POST_INCR(x) GC_POST_INCR3(x, 1, __typeof__(x))
2367# define GC_POST_DECR(x) GC_POST_INCR3(x, -1, __typeof__(x))
2368#else /* !GC_DEBUG || !__GNUC__ */
2369/*
2370 * We cannot do this right without `typeof`, which ANSI decided was not
2371 * sufficiently useful. Without it we resort to the non-debug variant.
2372 */
2373/* TODO: This should eventually support C++0x `decltype`. */
2374# define GC_PTR_ADD(x, n) ((x) + (n))
2375# define GC_PRE_INCR(x, n) ((x) += (n))
2376# define GC_POST_INCR(x) ((x)++)
2377# define GC_POST_DECR(x) ((x)--)
2378#endif /* !GC_DEBUG || !__GNUC__ */
2379
2380/* Safer assignment of a pointer to a non-stack location. */
2381#ifdef GC_DEBUG
2382# define GC_PTR_STORE(p, q) \
2383 (*(void **)GC_is_visible((void *)(p)) \
2384 = GC_is_valid_displacement((void *)(q)))
2385#else
2386# define GC_PTR_STORE(p, q) (*(void **)(p) = (void *)(q))
2387#endif
2388
2389/*
2390 * `GC_PTR_STORE_AND_DIRTY(p, q)` is equivalent to `GC_PTR_STORE(p, q)`
2391 * followed by `GC_END_STUBBORN_CHANGE(p)` and `GC_reachable_here(q)`
2392 * (assuming `p` and `q` do not have side effects).
2393 */
2394GC_API void GC_CALL GC_ptr_store_and_dirty(void * /* `p` */,
2395 const void * /* `q` */);
2396GC_API void GC_CALL GC_debug_ptr_store_and_dirty(void * /* `p` */,
2397 const void * /* `q` */);
2398
2399#ifdef GC_PTHREADS
2400/*
2401 * For `pthreads` support, we generally need to intercept a number of
2402 * thread library calls. We do that here by macro defining them.
2403 */
2404# ifdef __cplusplus
2405} /* extern "C" */
2406# endif
2407# include "gc_pthread_redirects.h"
2408# ifdef __cplusplus
2409extern "C" {
2410# endif
2411#endif
2412
2413/**
2414 * This returns a list of objects with the link pointer located at the
2415 * beginning of each object. The use of such list can greatly reduce
2416 * lock contention problems, since the allocator lock can be acquired
2417 * and released many fewer times. Note that there is no "atomic"
2418 * variant of this function, as otherwise the links would not be seen
2419 * by the collector. If the argument (`lb`) is zero, then it is
2420 * treated as 1. The function is guaranteed never to return `NULL`
2421 * unless `GC_oom_fn()` returns `NULL`.
2422 */
2423GC_API GC_ATTR_MALLOC void *GC_CALL GC_malloc_many(size_t /* `lb` */);
2424
2425/* Retrieve the next element in the list returned by `GC_malloc_many()`. */
2426#define GC_NEXT(p) (*(void **)(p))
2427
2428/**
2429 * A filter function to control the scanning of dynamic libraries.
2430 * If implemented, called by the collector before registering a dynamic
2431 * library (discovered by the collector) section as a static data root
2432 * (called only as a last reason not to register). The filename
2433 * (`dlpi_name`) of the library, the address and the length of the
2434 * memory region (section) are passed. This routine should return
2435 * a nonzero value if that region should be scanned. Always called
2436 * with the allocator lock held. Depending on the platform, might be
2437 * called with the world stopped.
2438 */
2439typedef int(GC_CALLBACK *GC_has_static_roots_func)(
2440 const char * /* `dlpi_name` */, void * /* `section_start` */,
2441 size_t /* `section_size` */);
2442
2443/**
2444 * Register a new callback (a user-supplied filter) to control the
2445 * scanning of dynamic libraries. Replaces any previously registered
2446 * callback. May be 0 (means no filtering). May be unused on some
2447 * platforms (if the filtering is unimplemented or inappropriate).
2448 */
2449GC_API void
2450 GC_CALL GC_register_has_static_roots_callback(GC_has_static_roots_func);
2451
2452#if !defined(CPPCHECK) && !defined(GC_WINDOWS_H_INCLUDED) && defined(WINAPI)
2453/* Platform `windows.h` file is included before `gc.h` file. */
2454# define GC_WINDOWS_H_INCLUDED
2455#endif
2456
2457#if defined(GC_WIN32_THREADS) \
2458 && (!defined(GC_PTHREADS) || defined(GC_BUILD) \
2459 || defined(GC_WINDOWS_H_INCLUDED))
2460/*
2461 * Note: for Cygwin and pthreads-win32, this is skipped unless platform
2462 * `windows.h` file is included before `gc.h` file.
2463 */
2464
2465# if (!defined(GC_NO_THREAD_DECLS) || defined(GC_BUILD)) \
2466 && !defined(GC_DONT_INCL_WINDOWS_H)
2467
2468/*
2469 * Including platform `windows.h` file in an `extern "C"` context
2470 * no longer works.
2471 */
2472# ifdef __cplusplus
2473}
2474# endif
2475
2476# if !defined(_WIN32_WCE) && !defined(__CEGCC__)
2477# include <process.h> /* for `_beginthreadex`, `_endthreadex` */
2478# endif
2479
2480# if defined(GC_BUILD) || !defined(GC_DONT_INCLUDE_WINDOWS_H)
2481# include <windows.h>
2482# define GC_WINDOWS_H_INCLUDED
2483# endif
2484
2485# ifdef __cplusplus
2486extern "C" {
2487# endif
2488
2489# ifdef GC_UNDERSCORE_STDCALL
2490/*
2491 * Explicitly prefix exported/imported WINAPI (`__stdcall`) symbols
2492 * with "_" (underscore). Might be useful if MinGW/x86 is used.
2493 */
2494# define GC_CreateThread _GC_CreateThread
2495# define GC_ExitThread _GC_ExitThread
2496# endif
2497
2498# ifndef DECLSPEC_NORETURN
2499/* Typically defined in platform `winnt.h` file. */
2500# ifdef GC_WINDOWS_H_INCLUDED
2501# define DECLSPEC_NORETURN /*< empty */
2502# else
2503# define DECLSPEC_NORETURN GC_ATTR_NORETURN
2504# endif
2505# endif
2506
2507# ifdef _WIN64
2508# define GC_WIN32_SIZE_T GC_uintptr_t
2509# elif defined(GC_WINDOWS_H_INCLUDED)
2510# define GC_WIN32_SIZE_T DWORD
2511# else
2512# define GC_WIN32_SIZE_T unsigned long
2513# endif
2514
2515# ifdef GC_INSIDE_DLL
2516/* Export GC `DllMain()` to be invoked from the client `DllMain`. */
2517# ifdef GC_UNDERSCORE_STDCALL
2518# define GC_DllMain _GC_DllMain
2519# endif
2520# ifdef GC_WINDOWS_H_INCLUDED
2521GC_API BOOL WINAPI GC_DllMain(HINSTANCE /* `inst` */, ULONG /* `reason` */,
2522 LPVOID /* `reserved` */);
2523# else
2524GC_API int __stdcall GC_DllMain(void *, unsigned long, void *);
2525# endif
2526# endif /* GC_INSIDE_DLL */
2527
2528/*
2529 * All threads must be created using `GC_CreateThread` or
2530 * `GC_beginthreadex`, or must explicitly call `GC_register_my_thread`
2531 * (and call `GC_unregister_my_thread` before thread termination), so
2532 * that they will be recorded in the thread table. For backward
2533 * compatibility, it is possible to build the collector with `GC_DLL`
2534 * macro defined, and to call `GC_use_threads_discovery()`.
2535 * This implicitly registers all created threads, but appears to be
2536 * less robust. Currently the collector expects all threads to fall
2537 * through and terminate normally, or call `GC_endthreadex` or
2538 * `GC_ExitThread`, so that the thread is properly unregistered.
2539 */
2540# ifdef GC_WINDOWS_H_INCLUDED
2541GC_API HANDLE WINAPI GC_CreateThread(
2542 LPSECURITY_ATTRIBUTES /* `lpThreadAttributes` */,
2543 GC_WIN32_SIZE_T /* `dwStackSize` */,
2544 LPTHREAD_START_ROUTINE /* `lpStartAddress` */, LPVOID /* `lpParameter` */,
2545 DWORD /* `dwCreationFlags` */, LPDWORD /* `lpThreadId` */);
2546
2547GC_API DECLSPEC_NORETURN void WINAPI GC_ExitThread(DWORD /* `dwExitCode` */);
2548# else
2549struct _SECURITY_ATTRIBUTES;
2550GC_API void *__stdcall GC_CreateThread(struct _SECURITY_ATTRIBUTES *,
2551 GC_WIN32_SIZE_T,
2552 unsigned long(__stdcall *)(void *),
2553 void *, unsigned long, unsigned long *);
2554GC_API DECLSPEC_NORETURN void __stdcall GC_ExitThread(unsigned long);
2555# endif
2556
2557# if !defined(_WIN32_WCE) && !defined(__CEGCC__)
2558GC_API GC_uintptr_t GC_CALL GC_beginthreadex(void * /* `security` */,
2559 unsigned /* `stack_size` */,
2560 unsigned(__stdcall *)(void *),
2561 void * /* `arglist` */,
2562 unsigned /* `initflag` */,
2563 unsigned * /* `thrdaddr` */);
2564
2565/*
2566 * Note: `_endthreadex()` is not currently marked as `noreturn` in VC++
2567 * and MinGW headers, so we do not mark it neither.
2568 */
2569GC_API void GC_CALL GC_endthreadex(unsigned /* `retval` */);
2570# endif /* !_WIN32_WCE */
2571
2572# endif /* !GC_NO_THREAD_DECLS */
2573
2574# ifdef GC_WINMAIN_REDIRECT
2575/*
2576 * The collector provides the real `WinMain()`, which starts a new thread
2577 * to call `GC_WinMain()` after initializing the collector.
2578 */
2579# define WinMain GC_WinMain
2580# endif
2581
2582/* For compatibility only. */
2583# define GC_use_DllMain GC_use_threads_discovery
2584
2585# ifndef GC_NO_THREAD_REDIRECTS
2586# define CreateThread GC_CreateThread
2587# define ExitThread GC_ExitThread
2588# undef _beginthreadex
2589# define _beginthreadex GC_beginthreadex
2590# undef _endthreadex
2591# define _endthreadex GC_endthreadex
2592/* `#define _beginthread { "Use _beginthreadex instead of _beginthread" }` */
2593# endif /* !GC_NO_THREAD_REDIRECTS */
2594
2595#endif /* GC_WIN32_THREADS */
2596
2597/**
2598 * The setter and the getter for switching "unmap as much as possible"
2599 * mode on(1) and off(0). Has no effect unless unmapping is turned on.
2600 * Initial value is controlled by `GC_FORCE_UNMAP_ON_GCOLLECT` macro.
2601 * The setter and the getter are unsynchronized.
2602 */
2603GC_API void GC_CALL GC_set_force_unmap_on_gcollect(int);
2604GC_API int GC_CALL GC_get_force_unmap_on_gcollect(void);
2605
2606/*
2607 * Fully portable code should call `GC_INIT()` from the main program
2608 * before making any other `GC_` calls. On most platforms this is
2609 * a no-op and the collector self-initializes. But a number of
2610 * platforms make that too hard. A `GC_INIT()` call is required if the
2611 * collector is built with `THREAD_LOCAL_ALLOC` macro defined and the
2612 * initial allocation call is not to `GC_malloc` or `GC_malloc_atomic`.
2613 */
2614
2615#if defined(__CYGWIN32__) || defined(__CYGWIN__)
2616/*
2617 * Similarly gnu-win32 DLLs need explicit initialization from the
2618 * main program, as does AIX.
2619 */
2620# ifdef __x86_64__
2621/* Cygwin/x86_64 does not add leading underscore to symbols anymore. */
2622extern int __data_start__[], __data_end__[];
2623extern int __bss_start__[], __bss_end__[];
2624# define GC_DATASTART \
2625 (GC_ADDR_LT((char *)__data_start__, (char *)__bss_start__) \
2626 ? (void *)__data_start__ \
2627 : (void *)__bss_start__)
2628# define GC_DATAEND \
2629 (GC_ADDR_LT((char *)__bss_end__, (char *)__data_end__) \
2630 ? (void *)__data_end__ \
2631 : (void *)__bss_end__)
2632# else
2633extern int _data_start__[], _data_end__[], _bss_start__[], _bss_end__[];
2634# define GC_DATASTART \
2635 (GC_ADDR_LT((char *)_data_start__, (char *)_bss_start__) \
2636 ? (void *)_data_start__ \
2637 : (void *)_bss_start__)
2638# define GC_DATAEND \
2639 (GC_ADDR_LT((char *)_bss_end__, (char *)_data_end__) \
2640 ? (void *)_data_end__ \
2641 : (void *)_bss_end__)
2642# endif /* !__x86_64__ */
2643/*
2644 * This is required at least if the collector is in a DLL; and does not
2645 * hurt.
2646 */
2647# define GC_INIT_CONF_ROOTS \
2648 GC_add_roots(GC_DATASTART, GC_DATAEND); \
2649 GC_gcollect() /*< for black-listing */
2650#elif defined(_AIX)
2651extern int _data[], _end[];
2652# define GC_DATASTART ((void *)_data)
2653# define GC_DATAEND ((void *)_end)
2654# define GC_INIT_CONF_ROOTS GC_add_roots(GC_DATASTART, GC_DATAEND)
2655#elif (defined(HOST_ANDROID) || defined(__ANDROID__)) \
2656 && defined(IGNORE_DYNAMIC_LOADING)
2657/*
2658 * This is ugly but seems the only way to register data roots of the
2659 * client shared library if the GC dynamic loading support is off.
2660 */
2661# pragma weak __dso_handle
2662extern int __dso_handle[];
2663GC_API void *GC_CALL GC_find_limit(void * /* `start` */, int /* `up` */);
2664# define GC_INIT_CONF_ROOTS \
2665 (void)(__dso_handle != 0 \
2666 ? (GC_add_roots(__dso_handle, \
2667 GC_find_limit(__dso_handle, 1 /* `up` */)), \
2668 0) \
2669 : 0)
2670#else
2671# define GC_INIT_CONF_ROOTS (void)0
2672#endif
2673
2674#ifdef GC_DONT_EXPAND
2675/* Set `GC_dont_expand` to true at start-up. */
2676# define GC_INIT_CONF_DONT_EXPAND GC_set_dont_expand(1)
2677#else
2678# define GC_INIT_CONF_DONT_EXPAND (void)0
2679#endif
2680
2681#ifdef GC_FORCE_UNMAP_ON_GCOLLECT
2682/* Turn on "unmap as much as possible on explicit GC" mode at start-up. */
2683# define GC_INIT_CONF_FORCE_UNMAP_ON_GCOLLECT \
2684 GC_set_force_unmap_on_gcollect(1)
2685#else
2686# define GC_INIT_CONF_FORCE_UNMAP_ON_GCOLLECT (void)0
2687#endif
2688
2689#ifdef GC_DONT_GC
2690/*
2691 * This is for debugging only (useful if environment variables are
2692 * unsupported); cannot call `GC_disable()` as goes before the
2693 * collector initialization.
2694 */
2695# define GC_INIT_CONF_MAX_RETRIES (void)(GC_dont_gc = 1)
2696#elif defined(GC_MAX_RETRIES) && !defined(CPPCHECK)
2697/* Set `GC_max_retries` to the desired value at start-up. */
2698# define GC_INIT_CONF_MAX_RETRIES GC_set_max_retries(GC_MAX_RETRIES)
2699#else
2700# define GC_INIT_CONF_MAX_RETRIES (void)0
2701#endif
2702
2703#if defined(GC_ALLOCD_BYTES_PER_FINALIZER) && !defined(CPPCHECK)
2704/* Set `GC_allocd_bytes_per_finalizer` to the desired value at start-up. */
2705# define GC_INIT_CONF_ALLOCD_BYTES_PER_FINALIZER \
2706 GC_set_allocd_bytes_per_finalizer(GC_ALLOCD_BYTES_PER_FINALIZER)
2707#else
2708# define GC_INIT_CONF_ALLOCD_BYTES_PER_FINALIZER (void)0
2709#endif
2710
2711#if defined(GC_FREE_SPACE_DIVISOR) && !defined(CPPCHECK)
2712/* Set `GC_free_space_divisor` to the desired value at start-up. */
2713# define GC_INIT_CONF_FREE_SPACE_DIVISOR \
2714 GC_set_free_space_divisor(GC_FREE_SPACE_DIVISOR)
2715#else
2716# define GC_INIT_CONF_FREE_SPACE_DIVISOR (void)0
2717#endif
2718
2719#if defined(GC_FULL_FREQ) && !defined(CPPCHECK)
2720/* Set `GC_full_freq` to the desired value at start-up. */
2721# define GC_INIT_CONF_FULL_FREQ GC_set_full_freq(GC_FULL_FREQ)
2722#else
2723# define GC_INIT_CONF_FULL_FREQ (void)0
2724#endif
2725
2726#if defined(GC_TIME_LIMIT) && !defined(CPPCHECK)
2727/* Set `GC_time_limit` (in ms) to the desired value at start-up. */
2728# define GC_INIT_CONF_TIME_LIMIT GC_set_time_limit(GC_TIME_LIMIT)
2729#else
2730# define GC_INIT_CONF_TIME_LIMIT (void)0
2731#endif
2732
2733#if defined(GC_MARKERS) && defined(GC_THREADS) && !defined(CPPCHECK)
2734/*
2735 * Set the number of marker threads (including the initiating one) to
2736 * the desired value at start-up.
2737 */
2738# define GC_INIT_CONF_MARKERS GC_set_markers_count(GC_MARKERS)
2739#else
2740# define GC_INIT_CONF_MARKERS (void)0
2741#endif
2742
2743#if defined(GC_SIG_SUSPEND) && defined(GC_THREADS) && !defined(CPPCHECK)
2744# define GC_INIT_CONF_SUSPEND_SIGNAL GC_set_suspend_signal(GC_SIG_SUSPEND)
2745#else
2746# define GC_INIT_CONF_SUSPEND_SIGNAL (void)0
2747#endif
2748
2749#if defined(GC_SIG_THR_RESTART) && defined(GC_THREADS) && !defined(CPPCHECK)
2750# define GC_INIT_CONF_THR_RESTART_SIGNAL \
2751 GC_set_thr_restart_signal(GC_SIG_THR_RESTART)
2752#else
2753# define GC_INIT_CONF_THR_RESTART_SIGNAL (void)0
2754#endif
2755
2756#if defined(GC_MAXIMUM_HEAP_SIZE) && !defined(CPPCHECK)
2757/*
2758 * Limit the heap size to the desired value (useful for debugging).
2759 * The limit could be overridden either at the program start-up by
2760 * the similar environment variable or anytime later by the corresponding
2761 * API function call.
2762 */
2763# define GC_INIT_CONF_MAXIMUM_HEAP_SIZE \
2764 GC_set_max_heap_size(GC_MAXIMUM_HEAP_SIZE)
2765#else
2766# define GC_INIT_CONF_MAXIMUM_HEAP_SIZE (void)0
2767#endif
2768
2769#ifdef GC_IGNORE_WARN
2770/* Turn off all warnings at start-up (after the collector initialization). */
2771# define GC_INIT_CONF_IGNORE_WARN GC_set_warn_proc(GC_ignore_warn_proc)
2772#else
2773# define GC_INIT_CONF_IGNORE_WARN (void)0
2774#endif
2775
2776#if defined(GC_INITIAL_HEAP_SIZE) && !defined(CPPCHECK)
2777/* Set heap size to the desired value at start-up. */
2778# define GC_INIT_CONF_INITIAL_HEAP_SIZE \
2779 { \
2780 size_t heap_size = GC_get_heap_size(); \
2781 if (heap_size < (size_t)(GC_INITIAL_HEAP_SIZE)) \
2782 (void)GC_expand_hp(((size_t)(GC_INITIAL_HEAP_SIZE)) - heap_size); \
2783 }
2784#else
2785# define GC_INIT_CONF_INITIAL_HEAP_SIZE (void)0
2786#endif
2787
2788/**
2789 * Portable clients should call this at the program start-up.
2790 * More over, some platforms require this call to be done strictly from
2791 * the primordial thread. Multiple invocations are harmless.
2792 */
2793#define GC_INIT() \
2794 { \
2795 GC_INIT_CONF_DONT_EXPAND; /*< pre-init */ \
2796 GC_INIT_CONF_FORCE_UNMAP_ON_GCOLLECT; \
2797 GC_INIT_CONF_MAX_RETRIES; \
2798 GC_INIT_CONF_ALLOCD_BYTES_PER_FINALIZER; \
2799 GC_INIT_CONF_FREE_SPACE_DIVISOR; \
2800 GC_INIT_CONF_FULL_FREQ; \
2801 GC_INIT_CONF_TIME_LIMIT; \
2802 GC_INIT_CONF_MARKERS; \
2803 GC_INIT_CONF_SUSPEND_SIGNAL; \
2804 GC_INIT_CONF_THR_RESTART_SIGNAL; \
2805 GC_INIT_CONF_MAXIMUM_HEAP_SIZE; \
2806 GC_init(); /*< real GC initialization */ \
2807 GC_INIT_CONF_ROOTS; /*< post-init */ \
2808 GC_INIT_CONF_IGNORE_WARN; \
2809 GC_INIT_CONF_INITIAL_HEAP_SIZE; \
2810 }
2811
2812/**
2813 * win32s may not free all resources on process exit.
2814 * This explicitly deallocates the heap. Defined only for Windows.
2815 */
2816GC_API void GC_CALL GC_win32_free_heap(void);
2817
2818#if defined(__SYMBIAN32__)
2819GC_API void GC_CALL GC_init_global_static_roots(void);
2820#endif
2821
2822#ifdef __cplusplus
2823} /* extern "C" */
2824#endif
2825
2826#endif /* GC_H */
2827