2 * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3 * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
4 * Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved.
6 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
7 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
9 * Permission is hereby granted to use or copy this program
10 * for any purpose, provided the above notices are retained on all copies.
11 * Permission to modify the code and to distribute modified code is granted,
12 * provided the above notices are retained, and a notice that the code was
13 * modified is included with the above copyright notice.
16 #include "private/gc_pmark.h"
26 #ifdef GC_SOLARIS_THREADS
27 # include <sys/syscall.h>
30 #if defined(MSWIN32) || defined(MSWINCE) \
31 || (defined(CYGWIN32) && defined(GC_READ_ENV_FILE))
32 # ifndef WIN32_LEAN_AND_MEAN
33 # define WIN32_LEAN_AND_MEAN 1
39 #if defined(UNIX_LIKE) || defined(CYGWIN32) || defined(SYMBIAN)
41 # include <sys/types.h>
42 # include <sys/stat.h>
51 # include "il/PCR_IL.h"
52 GC_INNER PCR_Th_ML GC_allocate_ml;
53 # elif defined(SN_TARGET_PSP2)
54 GC_INNER WapiMutex GC_allocate_ml_PSP2 = { 0, NULL };
55 # elif defined(SN_TARGET_ORBIS) || defined(SN_TARGET_PS3)
57 GC_INNER pthread_mutex_t GC_allocate_ml;
59 /* For other platforms with threads, the lock and possibly */
60 /* GC_lock_holder variables are defined in the thread support code. */
63 #ifdef DYNAMIC_LOADING
64 /* We need to register the main data segment. Returns TRUE unless */
65 /* this is done implicitly as part of dynamic library registration. */
66 # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
67 #elif defined(GC_DONT_REGISTER_MAIN_STATIC_DATA)
68 # define GC_REGISTER_MAIN_STATIC_DATA() FALSE
70 /* Don't unnecessarily call GC_register_main_static_data() in case */
71 /* dyn_load.c isn't linked in. */
72 # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
75 #ifdef NEED_CANCEL_DISABLE_COUNT
76 __thread unsigned char GC_cancel_disable_count = 0;
79 GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
81 GC_INNER GC_bool GC_debugging_started = FALSE;
82 /* defined here so we don't have to load dbg_mlc.o */
84 ptr_t GC_stackbottom = 0;
87 ptr_t GC_register_stackbottom = 0;
90 int GC_dont_gc = FALSE;
92 int GC_dont_precollect = FALSE;
94 GC_bool GC_quiet = 0; /* used also in pcr_interface.c */
96 #if !defined(NO_CLOCK) || !defined(SMALL_CONFIG)
97 int GC_print_stats = 0;
100 #ifdef GC_PRINT_BACK_HEIGHT
101 GC_INNER GC_bool GC_print_back_height = TRUE;
103 GC_INNER GC_bool GC_print_back_height = FALSE;
107 # ifdef GC_DUMP_REGULARLY
108 GC_INNER GC_bool GC_dump_regularly = TRUE;
109 /* Generate regular debugging dumps. */
111 GC_INNER GC_bool GC_dump_regularly = FALSE;
114 STATIC CLOCK_TYPE GC_init_time;
115 /* The time that the GC was initialized at. */
117 #endif /* !NO_DEBUGGING */
119 #ifdef KEEP_BACK_PTRS
120 GC_INNER long GC_backtraces = 0;
121 /* Number of random backtraces to generate for each GC. */
125 int GC_find_leak = 1;
127 int GC_find_leak = 0;
130 #ifndef SHORT_DBG_HDRS
131 # ifdef GC_FINDLEAK_DELAY_FREE
132 GC_INNER GC_bool GC_findleak_delay_free = TRUE;
134 GC_INNER GC_bool GC_findleak_delay_free = FALSE;
136 #endif /* !SHORT_DBG_HDRS */
138 #ifdef ALL_INTERIOR_POINTERS
139 int GC_all_interior_pointers = 1;
141 int GC_all_interior_pointers = 0;
144 #ifdef FINALIZE_ON_DEMAND
145 int GC_finalize_on_demand = 1;
147 int GC_finalize_on_demand = 0;
150 #ifdef JAVA_FINALIZATION
151 int GC_java_finalization = 1;
153 int GC_java_finalization = 0;
156 /* All accesses to it should be synchronized to avoid data races. */
157 GC_finalizer_notifier_proc GC_finalizer_notifier =
158 (GC_finalizer_notifier_proc)0;
160 #ifdef GC_FORCE_UNMAP_ON_GCOLLECT
161 /* Has no effect unless USE_MUNMAP. */
162 /* Has no effect on implicitly-initiated garbage collections. */
163 GC_INNER GC_bool GC_force_unmap_on_gcollect = TRUE;
165 GC_INNER GC_bool GC_force_unmap_on_gcollect = FALSE;
168 #ifndef GC_LARGE_ALLOC_WARN_INTERVAL
169 # define GC_LARGE_ALLOC_WARN_INTERVAL 5
171 GC_INNER long GC_large_alloc_warn_interval = GC_LARGE_ALLOC_WARN_INTERVAL;
172 /* Interval between unsuppressed warnings. */
174 STATIC void * GC_CALLBACK GC_default_oom_fn(
175 size_t bytes_requested GC_ATTR_UNUSED)
180 /* All accesses to it should be synchronized to avoid data races. */
181 GC_oom_func GC_oom_fn = GC_default_oom_fn;
183 #ifdef CAN_HANDLE_FORK
185 GC_INNER int GC_handle_fork = 1;
186 /* The value is examined by GC_thr_init. */
188 GC_INNER int GC_handle_fork = FALSE;
191 #elif !defined(HAVE_NO_FORK)
193 /* Same as above but with GC_CALL calling conventions. */
194 GC_API void GC_CALL GC_atfork_prepare(void)
197 ABORT("fork() handling unsupported");
201 GC_API void GC_CALL GC_atfork_parent(void)
206 GC_API void GC_CALL GC_atfork_child(void)
210 #endif /* !CAN_HANDLE_FORK && !HAVE_NO_FORK */
212 /* Overrides the default automatic handle-fork mode. Has effect only */
213 /* if called before GC_INIT. */
214 GC_API void GC_CALL GC_set_handle_fork(int value GC_ATTR_UNUSED)
216 # ifdef CAN_HANDLE_FORK
217 if (!GC_is_initialized)
218 GC_handle_fork = value >= -1 ? value : 1;
219 /* Map all negative values except for -1 to a positive one. */
220 # elif defined(THREADS) || (defined(DARWIN) && defined(MPROTECT_VDB))
221 if (!GC_is_initialized && value) {
222 # ifndef SMALL_CONFIG
223 GC_init(); /* to initialize GC_manual_vdb and GC_stderr */
229 ABORT("fork() handling unsupported");
232 /* No at-fork handler is needed in the single-threaded mode. */
236 /* Set things up so that GC_size_map[i] >= granules(i), */
237 /* but not too much bigger */
238 /* and so that size_map contains relatively few distinct entries */
239 /* This was originally stolen from Russ Atkinson's Cedar */
240 /* quantization algorithm (but we precompute it). */
241 STATIC void GC_init_size_map(void)
245 /* Map size 0 to something bigger. */
246 /* This avoids problems at lower levels. */
248 for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
249 GC_size_map[i] = ROUNDED_UP_GRANULES(i);
251 GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
252 /* Seems to tickle bug in VC++ 2008 for AMD64 */
255 /* We leave the rest of the array to be filled in on demand. */
259 * The following is a gross hack to deal with a problem that can occur
260 * on machines that are sloppy about stack frame sizes, notably SPARC.
261 * Bogus pointers may be written to the stack and not cleared for
262 * a LONG time, because they always fall into holes in stack frames
263 * that are not written. We partially address this by clearing
264 * sections of the stack whenever we get control.
267 #ifndef SMALL_CLEAR_SIZE
268 # define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */
271 #if defined(ALWAYS_SMALL_CLEAR_STACK) || defined(STACK_NOT_SCANNED)
272 GC_API void * GC_CALL GC_clear_stack(void *arg)
274 # ifndef STACK_NOT_SCANNED
275 word volatile dummy[SMALL_CLEAR_SIZE];
276 BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
283 # define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */
285 STATIC word GC_stack_last_cleared = 0; /* GC_no when we last did this */
286 STATIC ptr_t GC_min_sp = NULL;
287 /* Coolest stack pointer value from which */
288 /* we've already cleared the stack. */
289 STATIC ptr_t GC_high_water = NULL;
290 /* "hottest" stack pointer value we have seen */
291 /* recently. Degrades over time. */
292 STATIC word GC_bytes_allocd_at_reset = 0;
293 # define DEGRADE_RATE 50
296 # if defined(ASM_CLEAR_CODE)
297 void *GC_clear_stack_inner(void *, ptr_t);
299 /* Clear the stack up to about limit. Return arg. This function */
300 /* is not static because it could also be erroneously defined in .S */
301 /* file, so this error would be caught by the linker. */
302 void *GC_clear_stack_inner(void *arg,
303 # if defined(__APPLE_CC__) && !GC_CLANG_PREREQ(6, 0)
304 volatile /* to workaround some bug */
308 # define CLEAR_SIZE 213 /* granularity */
309 volatile word dummy[CLEAR_SIZE];
311 BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
312 if ((word)GC_approx_sp() COOLER_THAN (word)limit) {
313 (void)GC_clear_stack_inner(arg, limit);
315 /* Make sure the recursive call is not a tail call, and the bzero */
316 /* call is not recognized as dead code. */
317 # if defined(CPPCHECK)
320 GC_noop1(COVERT_DATAFLOW(dummy));
324 # endif /* !ASM_CLEAR_CODE */
327 /* Used to occasionally clear a bigger chunk. */
328 /* TODO: Should be more random than it is ... */
329 GC_ATTR_NO_SANITIZE_THREAD
330 static unsigned next_random_no(void)
332 static unsigned random_no = 0;
333 return ++random_no % 13;
335 # endif /* THREADS */
337 /* Clear some of the inaccessible part of the stack. Returns its */
338 /* argument, so it can be used in a tail call position, hence clearing */
340 GC_API void * GC_CALL GC_clear_stack(void *arg)
342 ptr_t sp = GC_approx_sp(); /* Hotter than actual sp */
344 word volatile dummy[SMALL_CLEAR_SIZE];
348 /* Extra bytes we clear every time. This clears our own */
349 /* activation record, and should cause more frequent */
350 /* clearing near the cold end of the stack, a good thing. */
351 # define GC_SLOP 4000
352 /* We make GC_high_water this much hotter than we really saw */
353 /* it, to cover for GC noise etc. above our current frame. */
354 # define CLEAR_THRESHOLD 100000
355 /* We restart the clearing process after this many bytes of */
356 /* allocation. Otherwise very heavily recursive programs */
357 /* with sparse stacks may result in heaps that grow almost */
358 /* without bounds. As the heap gets larger, collection */
359 /* frequency decreases, thus clearing frequency would decrease, */
360 /* thus more junk remains accessible, thus the heap gets */
363 if (next_random_no() == 0) {
366 MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
367 limit = (ptr_t)((word)limit & ~0xf);
368 /* Make it sufficiently aligned for assembly */
369 /* implementations of GC_clear_stack_inner. */
370 return GC_clear_stack_inner(arg, limit);
372 BZERO((void *)dummy, SMALL_CLEAR_SIZE*sizeof(word));
374 if (GC_gc_no > GC_stack_last_cleared) {
375 /* Start things over, so we clear the entire stack again */
376 if (GC_stack_last_cleared == 0)
377 GC_high_water = (ptr_t)GC_stackbottom;
378 GC_min_sp = GC_high_water;
379 GC_stack_last_cleared = GC_gc_no;
380 GC_bytes_allocd_at_reset = GC_bytes_allocd;
382 /* Adjust GC_high_water */
383 MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
384 if ((word)sp HOTTER_THAN (word)GC_high_water) {
387 MAKE_HOTTER(GC_high_water, GC_SLOP);
389 ptr_t limit = GC_min_sp;
391 MAKE_HOTTER(limit, SLOP);
392 if ((word)sp COOLER_THAN (word)limit) {
393 limit = (ptr_t)((word)limit & ~0xf);
394 /* Make it sufficiently aligned for assembly */
395 /* implementations of GC_clear_stack_inner. */
397 return GC_clear_stack_inner(arg, limit);
400 if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) {
401 /* Restart clearing process, but limit how much clearing we do. */
403 MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
404 if ((word)GC_min_sp HOTTER_THAN (word)GC_high_water)
405 GC_min_sp = GC_high_water;
406 GC_bytes_allocd_at_reset = GC_bytes_allocd;
412 #endif /* !ALWAYS_SMALL_CLEAR_STACK && !STACK_NOT_SCANNED */
414 /* Return a pointer to the base address of p, given a pointer to a */
415 /* an address within an object. Return 0 o.w. */
416 GC_API void * GC_CALL GC_base(void * p)
424 if (!EXPECT(GC_is_initialized, TRUE)) return 0;
427 candidate_hdr = HDR_FROM_BI(bi, r);
428 if (candidate_hdr == 0) return(0);
429 /* If it's a pointer to the middle of a large object, move it */
430 /* to the beginning. */
431 while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
432 h = FORWARDED_ADDR(h,candidate_hdr);
434 candidate_hdr = HDR(h);
436 if (HBLK_IS_FREE(candidate_hdr)) return(0);
437 /* Make sure r points to the beginning of the object */
438 r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
440 size_t offset = HBLKDISPL(r);
441 word sz = candidate_hdr -> hb_sz;
442 size_t obj_displ = offset % sz;
447 if ((word)limit > (word)(h + 1) && sz <= HBLKSIZE) {
450 if ((word)p >= (word)limit) return(0);
455 /* Return TRUE if and only if p points to somewhere in GC heap. */
456 GC_API int GC_CALL GC_is_heap_ptr(const void *p)
460 GC_ASSERT(GC_is_initialized);
462 return HDR_FROM_BI(bi, p) != 0;
465 /* Return the size of an object, given a pointer to its base. */
466 /* (For small objects this also happens to work from interior pointers, */
467 /* but that shouldn't be relied upon.) */
468 GC_API size_t GC_CALL GC_size(const void * p)
472 return (size_t)hhdr->hb_sz;
476 /* These getters remain unsynchronized for compatibility (since some */
477 /* clients could call some of them from a GC callback holding the */
478 /* allocator lock). */
479 GC_API size_t GC_CALL GC_get_heap_size(void)
481 /* ignore the memory space returned to OS (i.e. count only the */
482 /* space owned by the garbage collector) */
483 return (size_t)(GC_heapsize - GC_unmapped_bytes);
486 GC_API size_t GC_CALL GC_get_free_bytes(void)
488 /* ignore the memory space returned to OS */
489 return (size_t)(GC_large_free_bytes - GC_unmapped_bytes);
492 GC_API size_t GC_CALL GC_get_unmapped_bytes(void)
494 return (size_t)GC_unmapped_bytes;
497 GC_API size_t GC_CALL GC_get_bytes_since_gc(void)
499 return (size_t)GC_bytes_allocd;
502 GC_API size_t GC_CALL GC_get_total_bytes(void)
504 return (size_t)(GC_bytes_allocd + GC_bytes_allocd_before_gc);
507 #ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
509 GC_API size_t GC_CALL GC_get_size_map_at(int i)
511 if ((unsigned)i > MAXOBJBYTES)
513 return GRANULES_TO_BYTES(GC_size_map[i]);
516 /* Return the heap usage information. This is a thread-safe (atomic) */
517 /* alternative for the five above getters. NULL pointer is allowed for */
518 /* any argument. Returned (filled in) values are of word type. */
519 GC_API void GC_CALL GC_get_heap_usage_safe(GC_word *pheap_size,
520 GC_word *pfree_bytes, GC_word *punmapped_bytes,
521 GC_word *pbytes_since_gc, GC_word *ptotal_bytes)
526 if (pheap_size != NULL)
527 *pheap_size = GC_heapsize - GC_unmapped_bytes;
528 if (pfree_bytes != NULL)
529 *pfree_bytes = GC_large_free_bytes - GC_unmapped_bytes;
530 if (punmapped_bytes != NULL)
531 *punmapped_bytes = GC_unmapped_bytes;
532 if (pbytes_since_gc != NULL)
533 *pbytes_since_gc = GC_bytes_allocd;
534 if (ptotal_bytes != NULL)
535 *ptotal_bytes = GC_bytes_allocd + GC_bytes_allocd_before_gc;
539 GC_INNER word GC_reclaimed_bytes_before_gc = 0;
541 /* Fill in GC statistics provided the destination is of enough size. */
542 static void fill_prof_stats(struct GC_prof_stats_s *pstats)
544 pstats->heapsize_full = GC_heapsize;
545 pstats->free_bytes_full = GC_large_free_bytes;
546 pstats->unmapped_bytes = GC_unmapped_bytes;
547 pstats->bytes_allocd_since_gc = GC_bytes_allocd;
548 pstats->allocd_bytes_before_gc = GC_bytes_allocd_before_gc;
549 pstats->non_gc_bytes = GC_non_gc_bytes;
550 pstats->gc_no = GC_gc_no; /* could be -1 */
551 # ifdef PARALLEL_MARK
552 pstats->markers_m1 = (word)((signed_word)GC_markers_m1);
554 pstats->markers_m1 = 0; /* one marker */
556 pstats->bytes_reclaimed_since_gc = GC_bytes_found > 0 ?
557 (word)GC_bytes_found : 0;
558 pstats->reclaimed_bytes_before_gc = GC_reclaimed_bytes_before_gc;
559 pstats->expl_freed_bytes_since_gc = GC_bytes_freed; /* since gc-7.7 */
562 # include <string.h> /* for memset() */
564 GC_API size_t GC_CALL GC_get_prof_stats(struct GC_prof_stats_s *pstats,
567 struct GC_prof_stats_s stats;
571 fill_prof_stats(stats_sz >= sizeof(stats) ? pstats : &stats);
574 if (stats_sz == sizeof(stats)) {
575 return sizeof(stats);
576 } else if (stats_sz > sizeof(stats)) {
577 /* Fill in the remaining part with -1. */
578 memset((char *)pstats + sizeof(stats), 0xff, stats_sz - sizeof(stats));
579 return sizeof(stats);
581 if (EXPECT(stats_sz > 0, TRUE))
582 BCOPY(&stats, pstats, stats_sz);
588 /* The _unsafe version assumes the caller holds the allocation lock. */
589 GC_API size_t GC_CALL GC_get_prof_stats_unsafe(
590 struct GC_prof_stats_s *pstats,
593 struct GC_prof_stats_s stats;
595 if (stats_sz >= sizeof(stats)) {
596 fill_prof_stats(pstats);
597 if (stats_sz > sizeof(stats))
598 memset((char *)pstats + sizeof(stats), 0xff,
599 stats_sz - sizeof(stats));
600 return sizeof(stats);
602 if (EXPECT(stats_sz > 0, TRUE)) {
603 fill_prof_stats(&stats);
604 BCOPY(&stats, pstats, stats_sz);
609 # endif /* THREADS */
611 #endif /* !GC_GET_HEAP_USAGE_NOT_NEEDED */
613 #if defined(GC_DARWIN_THREADS) || defined(GC_OPENBSD_UTHREADS) \
614 || defined(GC_WIN32_THREADS) || (defined(NACL) && defined(THREADS))
615 /* GC does not use signals to suspend and restart threads. */
616 GC_API void GC_CALL GC_set_suspend_signal(int sig GC_ATTR_UNUSED)
621 GC_API void GC_CALL GC_set_thr_restart_signal(int sig GC_ATTR_UNUSED)
626 GC_API int GC_CALL GC_get_suspend_signal(void)
631 GC_API int GC_CALL GC_get_thr_restart_signal(void)
635 #endif /* GC_DARWIN_THREADS || GC_WIN32_THREADS || ... */
637 #if !defined(_MAX_PATH) && (defined(MSWIN32) || defined(MSWINCE) \
638 || defined(CYGWIN32))
639 # define _MAX_PATH MAX_PATH
642 #ifdef GC_READ_ENV_FILE
643 /* This works for Win32/WinCE for now. Really useful only for WinCE. */
644 STATIC char *GC_envfile_content = NULL;
645 /* The content of the GC "env" file with CR and */
646 /* LF replaced to '\0'. NULL if the file is */
647 /* missing or empty. Otherwise, always ends */
649 STATIC unsigned GC_envfile_length = 0;
650 /* Length of GC_envfile_content (if non-NULL). */
652 # ifndef GC_ENVFILE_MAXLEN
653 # define GC_ENVFILE_MAXLEN 0x4000
656 # define GC_ENV_FILE_EXT ".gc.env"
658 /* The routine initializes GC_envfile_content from the GC "env" file. */
659 STATIC void GC_envfile_init(void)
661 # if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
667 TCHAR path[_MAX_PATH + 0x10]; /* buffer for path + ext */
668 len = (unsigned)GetModuleFileName(NULL /* hModule */, path,
670 /* If GetModuleFileName() has failed then len is 0. */
671 if (len > 4 && path[len - 4] == (TCHAR)'.') {
672 len -= 4; /* strip executable file extension */
674 BCOPY(TEXT(GC_ENV_FILE_EXT), &path[len], sizeof(TEXT(GC_ENV_FILE_EXT)));
675 hFile = CreateFile(path, GENERIC_READ,
676 FILE_SHARE_READ | FILE_SHARE_WRITE,
677 NULL /* lpSecurityAttributes */, OPEN_EXISTING,
678 FILE_ATTRIBUTE_NORMAL, NULL /* hTemplateFile */);
679 if (hFile == INVALID_HANDLE_VALUE)
680 return; /* the file is absent or the operation is failed */
681 len = (unsigned)GetFileSize(hFile, NULL);
682 if (len <= 1 || len >= GC_ENVFILE_MAXLEN) {
684 return; /* invalid file length - ignoring the file content */
686 /* At this execution point, GC_setpagesize() and GC_init_win32() */
687 /* must already be called (for GET_MEM() to work correctly). */
688 content = (char *)GET_MEM(ROUNDUP_PAGESIZE_IF_MMAP((size_t)len + 1));
689 if (content == NULL) {
691 return; /* allocation failure */
694 nBytesRead = (DWORD)-1L;
695 /* Last ReadFile() call should clear nBytesRead on success. */
696 while (ReadFile(hFile, content + ofs, len - ofs + 1, &nBytesRead,
697 NULL /* lpOverlapped */) && nBytesRead != 0) {
698 if ((ofs += nBytesRead) > len)
702 if (ofs != len || nBytesRead != 0)
703 return; /* read operation is failed - ignoring the file content */
706 if (content[ofs] == '\r' || content[ofs] == '\n')
709 GC_ASSERT(NULL == GC_envfile_content);
710 GC_envfile_length = len + 1;
711 GC_envfile_content = content;
715 /* This routine scans GC_envfile_content for the specified */
716 /* environment variable (and returns its value if found). */
717 GC_INNER char * GC_envfile_getenv(const char *name)
720 char *end_of_content;
723 p = getenv(name); /* try the standard getenv() first */
725 return *p != '\0' ? p : NULL;
727 p = GC_envfile_content;
729 return NULL; /* "env" file is absent (or empty) */
730 namelen = strlen(name);
731 if (namelen == 0) /* a sanity check */
733 for (end_of_content = p + GC_envfile_length;
734 p != end_of_content; p += strlen(p) + 1) {
735 if (strncmp(p, name, namelen) == 0 && *(p += namelen) == '=') {
736 p++; /* the match is found; skip '=' */
737 return *p != '\0' ? p : NULL;
739 /* If not matching then skip to the next line. */
741 return NULL; /* no match found */
743 #endif /* GC_READ_ENV_FILE */
745 GC_INNER GC_bool GC_is_initialized = FALSE;
747 GC_API int GC_CALL GC_is_init_called(void)
749 return GC_is_initialized;
752 #if (defined(MSWIN32) || defined(MSWINCE) || defined(MSWIN_XBOX1)) \
754 GC_INNER CRITICAL_SECTION GC_write_cs;
757 #ifndef DONT_USE_ATEXIT
758 # if !defined(PCR) && !defined(SMALL_CONFIG)
759 /* A dedicated variable to avoid a garbage collection on abort. */
760 /* GC_find_leak cannot be used for this purpose as otherwise */
761 /* TSan finds a data race (between GC_default_on_abort and, e.g., */
762 /* GC_finish_collection). */
763 static GC_bool skip_gc_atexit = FALSE;
765 # define skip_gc_atexit FALSE
768 STATIC void GC_exit_check(void)
770 if (GC_find_leak && !skip_gc_atexit) {
772 GC_in_thread_creation = TRUE; /* OK to collect from unknown thread. */
774 GC_in_thread_creation = FALSE;
782 #if defined(UNIX_LIKE) && !defined(NO_DEBUGGING)
783 static void looping_handler(int sig)
785 GC_err_printf("Caught signal %d: looping in handler\n", sig);
791 static GC_bool installed_looping_handler = FALSE;
793 static void maybe_install_looping_handler(void)
795 /* Install looping handler before the write fault handler, so we */
796 /* handle write faults correctly. */
797 if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
798 GC_set_and_save_fault_handler(looping_handler);
799 installed_looping_handler = TRUE;
803 #else /* !UNIX_LIKE */
804 # define maybe_install_looping_handler()
807 #define GC_DEFAULT_STDOUT_FD 1
808 #define GC_DEFAULT_STDERR_FD 2
810 #if !defined(OS2) && !defined(MACOS) && !defined(GC_ANDROID_LOG) \
811 && !defined(NN_PLATFORM_CTR) && !defined(NINTENDO_SWITCH) \
812 && !defined(MSWIN32) && !defined(MSWINCE)
813 STATIC int GC_stdout = GC_DEFAULT_STDOUT_FD;
814 STATIC int GC_stderr = GC_DEFAULT_STDERR_FD;
815 STATIC int GC_log = GC_DEFAULT_STDERR_FD;
817 GC_API void GC_CALL GC_set_log_fd(int fd)
823 #ifdef MSGBOX_ON_ERROR
824 STATIC void GC_win32_MessageBoxA(const char *msg, const char *caption,
827 # ifndef DONT_USE_USER32_DLL
828 /* Use static binding to "user32.dll". */
829 (void)MessageBoxA(NULL, msg, caption, flags);
831 /* This simplifies linking - resolve "MessageBoxA" at run-time. */
832 HINSTANCE hU32 = LoadLibrary(TEXT("user32.dll"));
834 FARPROC pfn = GetProcAddress(hU32, "MessageBoxA");
836 (void)(*(int (WINAPI *)(HWND, LPCSTR, LPCSTR, UINT))pfn)(
837 NULL /* hWnd */, msg, caption, flags);
838 (void)FreeLibrary(hU32);
842 #endif /* MSGBOX_ON_ERROR */
844 #if defined(THREADS) && defined(UNIX_LIKE) && !defined(NO_GETCONTEXT)
845 static void callee_saves_pushed_dummy_fn(ptr_t data GC_ATTR_UNUSED,
846 void * context GC_ATTR_UNUSED) {}
851 static GC_bool manual_vdb_allowed = TRUE;
853 static GC_bool manual_vdb_allowed = FALSE;
856 GC_API void GC_CALL GC_set_manual_vdb_allowed(int value)
858 manual_vdb_allowed = (GC_bool)value;
861 GC_API int GC_CALL GC_get_manual_vdb_allowed(void)
863 return (int)manual_vdb_allowed;
865 #endif /* !SMALL_CONFIG */
867 STATIC word GC_parse_mem_size_arg(const char *str)
869 word result = 0; /* bad value */
875 result = (word)STRTOULL(str, &endptr, 10);
878 if (*(endptr + 1) != '\0')
880 /* Allow k, M or G suffix. */
902 #define GC_LOG_STD_NAME "gc.log"
904 GC_API void GC_CALL GC_init(void)
906 /* LOCK(); -- no longer does anything this early. */
907 word initial_heap_sz;
908 IF_CANCEL(int cancel_state;)
909 # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
913 if (EXPECT(GC_is_initialized, TRUE)) return;
914 # ifdef REDIRECT_MALLOC
916 static GC_bool init_started = FALSE;
918 ABORT("Redirected malloc() called during GC init");
923 # if defined(GC_INITIAL_HEAP_SIZE) && !defined(CPPCHECK)
924 initial_heap_sz = GC_INITIAL_HEAP_SIZE;
926 initial_heap_sz = MINHINCR * HBLKSIZE;
929 DISABLE_CANCEL(cancel_state);
930 /* Note that although we are nominally called with the */
931 /* allocation lock held, the allocation lock is now */
932 /* only really acquired once a second thread is forked.*/
933 /* And the initialization code needs to run before */
934 /* then. Thus we really don't hold any locks, and can */
935 /* in fact safely initialize them here. */
937 # ifndef GC_ALWAYS_MULTITHREADED
938 GC_ASSERT(!GC_need_to_lock);
940 # ifdef SN_TARGET_PS3
942 pthread_mutexattr_t mattr;
944 if (0 != pthread_mutexattr_init(&mattr)) {
945 ABORT("pthread_mutexattr_init failed");
947 if (0 != pthread_mutex_init(&GC_allocate_ml, &mattr)) {
948 ABORT("pthread_mutex_init failed");
950 (void)pthread_mutexattr_destroy(&mattr);
953 # endif /* THREADS */
954 # if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
956 # define SPIN_COUNT 4000
958 # ifdef MSWINRT_FLAVOR
959 InitializeCriticalSectionAndSpinCount(&GC_allocate_ml, SPIN_COUNT);
963 BOOL (WINAPI *pfn)(LPCRITICAL_SECTION, DWORD) = 0;
964 HMODULE hK32 = GetModuleHandle(TEXT("kernel32.dll"));
966 pfn = (BOOL (WINAPI *)(LPCRITICAL_SECTION, DWORD))
968 "InitializeCriticalSectionAndSpinCount");
970 pfn(&GC_allocate_ml, SPIN_COUNT);
972 # endif /* !MSWINCE */
973 /* else */ InitializeCriticalSection(&GC_allocate_ml);
976 # endif /* GC_WIN32_THREADS */
977 # if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
978 InitializeCriticalSection(&GC_write_cs);
984 # ifdef GC_READ_ENV_FILE
987 # if !defined(NO_CLOCK) || !defined(SMALL_CONFIG)
988 # ifdef GC_PRINT_VERBOSE_STATS
989 /* This is useful for debugging and profiling on platforms with */
990 /* missing getenv() (like WinCE). */
991 GC_print_stats = VERBOSE;
993 if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
994 GC_print_stats = VERBOSE;
995 } else if (0 != GETENV("GC_PRINT_STATS")) {
1000 # if ((defined(UNIX_LIKE) && !defined(GC_ANDROID_LOG)) \
1001 || defined(CYGWIN32) || defined(SYMBIAN)) && !defined(SMALL_CONFIG)
1003 char * file_name = TRUSTED_STRING(GETENV("GC_LOG_FILE"));
1004 # ifdef GC_LOG_TO_FILE_ALWAYS
1005 if (NULL == file_name)
1006 file_name = GC_LOG_STD_NAME;
1011 int log_d = open(file_name, O_CREAT | O_WRONLY | O_APPEND, 0644);
1013 GC_err_printf("Failed to open %s as log file\n", file_name);
1017 str = GETENV("GC_ONLY_LOG_TO_FILE");
1018 # ifdef GC_ONLY_LOG_TO_FILE
1019 /* The similar environment variable set to "0" */
1020 /* overrides the effect of the macro defined. */
1021 if (str != NULL && *str == '0' && *(str + 1) == '\0')
1023 /* Otherwise setting the environment variable */
1024 /* to anything other than "0" will prevent from */
1025 /* redirecting stdout/err to the log file. */
1026 if (str == NULL || (*str == '0' && *(str + 1) == '\0'))
1036 # if !defined(NO_DEBUGGING) && !defined(GC_DUMP_REGULARLY)
1037 if (0 != GETENV("GC_DUMP_REGULARLY")) {
1038 GC_dump_regularly = TRUE;
1041 # ifdef KEEP_BACK_PTRS
1043 char * backtraces_string = GETENV("GC_BACKTRACES");
1044 if (0 != backtraces_string) {
1045 GC_backtraces = atol(backtraces_string);
1046 if (backtraces_string[0] == '\0') GC_backtraces = 1;
1050 if (0 != GETENV("GC_FIND_LEAK")) {
1053 # ifndef SHORT_DBG_HDRS
1054 if (0 != GETENV("GC_FINDLEAK_DELAY_FREE")) {
1055 GC_findleak_delay_free = TRUE;
1058 if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
1059 GC_all_interior_pointers = 1;
1061 if (0 != GETENV("GC_DONT_GC")) {
1064 if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
1065 GC_print_back_height = TRUE;
1067 if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
1068 GC_large_alloc_warn_interval = LONG_MAX;
1071 char * addr_string = GETENV("GC_TRACE");
1072 if (0 != addr_string) {
1073 # ifndef ENABLE_TRACE
1074 WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
1076 word addr = (word)STRTOULL(addr_string, NULL, 16);
1078 WARN("Unlikely trace address: %p\n", (void *)addr);
1079 GC_trace_addr = (ptr_t)addr;
1083 # ifdef GC_COLLECT_AT_MALLOC
1085 char * string = GETENV("GC_COLLECT_AT_MALLOC");
1087 size_t min_lb = (size_t)STRTOULL(string, NULL, 10);
1089 GC_dbg_collect_at_malloc_min_lb = min_lb;
1093 # if !defined(GC_DISABLE_INCREMENTAL) && !defined(NO_CLOCK)
1095 char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
1096 if (0 != time_limit_string) {
1097 long time_limit = atol(time_limit_string);
1098 if (time_limit > 0) {
1099 GC_time_limit = time_limit;
1104 # ifndef SMALL_CONFIG
1106 char * full_freq_string = GETENV("GC_FULL_FREQUENCY");
1107 if (full_freq_string != NULL) {
1108 int full_freq = atoi(full_freq_string);
1110 GC_full_freq = full_freq;
1115 char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
1116 if (0 != interval_string) {
1117 long interval = atol(interval_string);
1118 if (interval <= 0) {
1119 WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
1120 "bad value: Ignoring\n", 0);
1122 GC_large_alloc_warn_interval = interval;
1127 char * space_divisor_string = GETENV("GC_FREE_SPACE_DIVISOR");
1128 if (space_divisor_string != NULL) {
1129 int space_divisor = atoi(space_divisor_string);
1130 if (space_divisor > 0)
1131 GC_free_space_divisor = (unsigned)space_divisor;
1136 char * string = GETENV("GC_UNMAP_THRESHOLD");
1137 if (string != NULL) {
1138 if (*string == '0' && *(string + 1) == '\0') {
1139 /* "0" is used to disable unmapping. */
1140 GC_unmap_threshold = 0;
1142 int unmap_threshold = atoi(string);
1143 if (unmap_threshold > 0)
1144 GC_unmap_threshold = unmap_threshold;
1149 char * string = GETENV("GC_FORCE_UNMAP_ON_GCOLLECT");
1150 if (string != NULL) {
1151 if (*string == '0' && *(string + 1) == '\0') {
1152 /* "0" is used to turn off the mode. */
1153 GC_force_unmap_on_gcollect = FALSE;
1155 GC_force_unmap_on_gcollect = TRUE;
1160 char * string = GETENV("GC_USE_ENTIRE_HEAP");
1161 if (string != NULL) {
1162 if (*string == '0' && *(string + 1) == '\0') {
1163 /* "0" is used to turn off the mode. */
1164 GC_use_entire_heap = FALSE;
1166 GC_use_entire_heap = TRUE;
1171 # if !defined(NO_DEBUGGING) && !defined(NO_CLOCK)
1172 GET_TIME(GC_init_time);
1174 maybe_install_looping_handler();
1175 # if ALIGNMENT > GC_DS_TAGS
1176 /* Adjust normal object descriptor for extra allocation. */
1177 if (EXTRA_BYTES != 0)
1178 GC_obj_kinds[NORMAL].ok_descriptor = (word)(-ALIGNMENT) | GC_DS_LENGTH;
1180 GC_exclude_static_roots_inner(beginGC_arrays, endGC_arrays);
1181 GC_exclude_static_roots_inner(beginGC_obj_kinds, endGC_obj_kinds);
1182 # ifdef SEPARATE_GLOBALS
1183 GC_exclude_static_roots_inner(beginGC_objfreelist, endGC_objfreelist);
1184 GC_exclude_static_roots_inner(beginGC_aobjfreelist, endGC_aobjfreelist);
1186 # if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
1187 WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
1188 /* If thread stacks are cached, they tend to be scanned in */
1189 /* entirety as part of the root set. This will grow them to */
1190 /* maximum size, and is generally not desirable. */
1192 # if defined(SEARCH_FOR_DATA_START)
1193 GC_init_linux_data_start();
1195 # if defined(NETBSD) && defined(__ELF__)
1196 GC_init_netbsd_elf();
1198 # if !defined(THREADS) || defined(GC_PTHREADS) \
1199 || defined(NN_PLATFORM_CTR) || defined(NINTENDO_SWITCH) \
1200 || defined(GC_WIN32_THREADS) || defined(GC_SOLARIS_THREADS)
1201 if (GC_stackbottom == 0) {
1202 GC_stackbottom = GC_get_main_stack_base();
1203 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
1204 GC_register_stackbottom = GC_get_register_stack_base();
1207 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
1208 if (GC_register_stackbottom == 0) {
1209 WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
1210 /* The following may fail, since we may rely on */
1211 /* alignment properties that may not hold with a user set */
1212 /* GC_stackbottom. */
1213 GC_register_stackbottom = GC_get_register_stack_base();
1218 # if !defined(CPPCHECK)
1219 GC_STATIC_ASSERT(sizeof(ptr_t) == sizeof(word));
1220 GC_STATIC_ASSERT(sizeof(signed_word) == sizeof(word));
1221 # if !defined(_AUX_SOURCE) || defined(__GNUC__)
1222 GC_STATIC_ASSERT((word)(-1) > (word)0);
1223 /* word should be unsigned */
1225 /* We no longer check for ((void*)(-1) > NULL) since all pointers */
1226 /* are explicitly cast to word in every less/greater comparison. */
1227 GC_STATIC_ASSERT((signed_word)(-1) < (signed_word)0);
1229 GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
1231 GC_ASSERT(!((word)GC_stackbottom HOTTER_THAN (word)GC_approx_sp()));
1233 # ifndef GC_DISABLE_INCREMENTAL
1234 if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
1235 # if defined(BASE_ATOMIC_OPS_EMULATED) || defined(CHECKSUMS) \
1236 || defined(REDIRECT_MALLOC) || defined(REDIRECT_MALLOC_IN_HEADER) \
1237 || defined(SMALL_CONFIG)
1238 /* TODO: Implement CHECKSUMS for manual VDB. */
1240 if (manual_vdb_allowed) {
1241 GC_manual_vdb = TRUE;
1242 GC_incremental = TRUE;
1246 /* For GWW_VDB on Win32, this needs to happen before any */
1247 /* heap memory is allocated. */
1248 GC_incremental = GC_dirty_init();
1249 GC_ASSERT(GC_bytes_allocd == 0);
1254 /* Add initial guess of root sets. Do this first, since sbrk(0) */
1255 /* might be used. */
1256 if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
1261 char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
1262 if (sz_str != NULL) {
1263 initial_heap_sz = GC_parse_mem_size_arg(sz_str);
1264 if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
1265 WARN("Bad initial heap size %s - ignoring it.\n", sz_str);
1270 char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
1271 if (sz_str != NULL) {
1272 word max_heap_sz = GC_parse_mem_size_arg(sz_str);
1273 if (max_heap_sz < initial_heap_sz) {
1274 WARN("Bad maximum heap size %s - ignoring it.\n", sz_str);
1276 if (0 == GC_max_retries) GC_max_retries = 2;
1277 GC_set_max_heap_size(max_heap_sz);
1280 # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1281 LOCK(); /* just to set GC_lock_holder */
1283 if (!GC_expand_hp_inner(divHBLKSZ(initial_heap_sz))) {
1284 GC_err_printf("Can't start up: not enough memory\n");
1287 GC_requested_heapsize += initial_heap_sz;
1289 if (GC_all_interior_pointers)
1290 GC_initialize_offsets();
1291 GC_register_displacement_inner(0L);
1292 # if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
1293 if (!GC_all_interior_pointers) {
1294 /* TLS ABI uses pointer-sized offsets for dtv. */
1295 GC_register_displacement_inner(sizeof(void *));
1300 if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
1302 ABORT("Can't lock load state");
1303 } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
1304 ABORT("Can't unlock load state");
1309 GC_is_initialized = TRUE;
1310 # if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
1312 # ifdef PARALLEL_MARK
1313 /* Actually start helper threads. */
1314 # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1317 GC_start_mark_threads_inner();
1318 # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1324 /* Get black list set up and/or incremental GC started */
1325 if (!GC_dont_precollect || GC_incremental) {
1326 GC_gcollect_inner();
1328 # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
1331 # if defined(THREADS) && defined(UNIX_LIKE) && !defined(NO_GETCONTEXT)
1332 /* Ensure getcontext_works is set to avoid potential data race. */
1333 if (GC_dont_gc || GC_dont_precollect)
1334 GC_with_callee_saves_pushed(callee_saves_pushed_dummy_fn, NULL);
1336 # ifndef DONT_USE_ATEXIT
1338 /* This is to give us at least one chance to detect leaks. */
1339 /* This may report some very benign leaks, but ... */
1340 atexit(GC_exit_check);
1344 /* The rest of this again assumes we don't really hold */
1345 /* the allocation lock. */
1346 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC) \
1347 || (defined(GC_ALWAYS_MULTITHREADED) && defined(GC_WIN32_THREADS) \
1348 && !defined(GC_NO_THREADS_DISCOVERY))
1349 /* Make sure marker threads are started and thread local */
1350 /* allocation is initialized, in case we didn't get */
1351 /* called from GC_init_parallel. */
1353 # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
1355 # if defined(DYNAMIC_LOADING) && defined(DARWIN)
1356 /* This must be called WITHOUT the allocation lock held */
1357 /* and before any threads are created. */
1360 RESTORE_CANCEL(cancel_state);
1363 GC_API void GC_CALL GC_enable_incremental(void)
1365 # if !defined(GC_DISABLE_INCREMENTAL) && !defined(KEEP_BACK_PTRS)
1367 /* If we are keeping back pointers, the GC itself dirties all */
1368 /* pages on which objects have been marked, making */
1369 /* incremental GC pointless. */
1370 if (!GC_find_leak && 0 == GETENV("GC_DISABLE_INCREMENTAL")) {
1372 if (!GC_incremental) {
1374 /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
1375 maybe_install_looping_handler(); /* Before write fault handler! */
1376 if (!GC_is_initialized) {
1378 GC_incremental = TRUE; /* indicate intention to turn it on */
1382 # if !defined(BASE_ATOMIC_OPS_EMULATED) && !defined(CHECKSUMS) \
1383 && !defined(REDIRECT_MALLOC) \
1384 && !defined(REDIRECT_MALLOC_IN_HEADER) && !defined(SMALL_CONFIG)
1385 if (manual_vdb_allowed) {
1386 GC_manual_vdb = TRUE;
1387 GC_incremental = TRUE;
1391 GC_incremental = GC_dirty_init();
1394 if (GC_incremental && !GC_dont_gc) {
1395 /* Can't easily do it if GC_dont_gc. */
1396 IF_CANCEL(int cancel_state;)
1398 DISABLE_CANCEL(cancel_state);
1399 if (GC_bytes_allocd > 0) {
1400 /* There may be unmarked reachable objects. */
1401 GC_gcollect_inner();
1403 /* else we're OK in assuming everything's */
1404 /* clean since nothing can point to an */
1405 /* unmarked object. */
1406 GC_read_dirty(FALSE);
1407 RESTORE_CANCEL(cancel_state);
1417 #if defined(THREADS)
1418 GC_API void GC_CALL GC_start_mark_threads(void)
1420 # if defined(PARALLEL_MARK) && defined(CAN_HANDLE_FORK) \
1421 && !defined(THREAD_SANITIZER)
1422 /* TSan does not support threads creation in the child process. */
1423 IF_CANCEL(int cancel_state;)
1425 DISABLE_CANCEL(cancel_state);
1426 GC_start_mark_threads_inner();
1427 RESTORE_CANCEL(cancel_state);
1429 /* No action since parallel markers are disabled (or no POSIX fork). */
1430 GC_ASSERT(I_DONT_HOLD_LOCK());
1435 GC_API void GC_CALL GC_deinit(void)
1437 if (GC_is_initialized) {
1438 /* Prevent duplicate resource close. */
1439 GC_is_initialized = FALSE;
1440 # if defined(THREADS) && (defined(MSWIN32) || defined(MSWINCE))
1441 DeleteCriticalSection(&GC_write_cs);
1442 DeleteCriticalSection(&GC_allocate_ml);
1447 #if defined(MSWIN32) || defined(MSWINCE)
1449 # if defined(_MSC_VER) && defined(_DEBUG) && !defined(MSWINCE)
1450 # include <crtdbg.h>
1453 STATIC HANDLE GC_log = 0;
1456 # if defined(PARALLEL_MARK) && !defined(GC_ALWAYS_MULTITHREADED)
1457 # define IF_NEED_TO_LOCK(x) if (GC_parallel || GC_need_to_lock) x
1459 # define IF_NEED_TO_LOCK(x) if (GC_need_to_lock) x
1462 # define IF_NEED_TO_LOCK(x)
1463 # endif /* !THREADS */
1465 # ifdef MSWINRT_FLAVOR
1466 # include <windows.storage.h>
1468 /* This API is defined in roapi.h, but we cannot include it here */
1469 /* since it does not compile in C. */
1470 DECLSPEC_IMPORT HRESULT WINAPI RoGetActivationFactory(
1471 HSTRING activatableClassId,
1472 REFIID iid, void** factory);
1474 static GC_bool getWinRTLogPath(wchar_t* buf, size_t bufLen)
1476 static const GUID kIID_IApplicationDataStatics = {
1477 0x5612147B, 0xE843, 0x45E3,
1478 0x94, 0xD8, 0x06, 0x16, 0x9E, 0x3C, 0x8E, 0x17
1480 static const GUID kIID_IStorageItem = {
1481 0x4207A996, 0xCA2F, 0x42F7,
1482 0xBD, 0xE8, 0x8B, 0x10, 0x45, 0x7A, 0x7F, 0x30
1484 GC_bool result = FALSE;
1485 HSTRING_HEADER appDataClassNameHeader;
1486 HSTRING appDataClassName;
1487 __x_ABI_CWindows_CStorage_CIApplicationDataStatics* appDataStatics = 0;
1489 GC_ASSERT(bufLen > 0);
1490 if (SUCCEEDED(WindowsCreateStringReference(
1491 RuntimeClass_Windows_Storage_ApplicationData,
1492 (sizeof(RuntimeClass_Windows_Storage_ApplicationData)-1)
1494 &appDataClassNameHeader, &appDataClassName))
1495 && SUCCEEDED(RoGetActivationFactory(appDataClassName,
1496 &kIID_IApplicationDataStatics,
1497 &appDataStatics))) {
1498 __x_ABI_CWindows_CStorage_CIApplicationData* appData = NULL;
1499 __x_ABI_CWindows_CStorage_CIStorageFolder* tempFolder = NULL;
1500 __x_ABI_CWindows_CStorage_CIStorageItem* tempFolderItem = NULL;
1501 HSTRING tempPath = NULL;
1503 if (SUCCEEDED(appDataStatics->lpVtbl->get_Current(appDataStatics,
1505 && SUCCEEDED(appData->lpVtbl->get_TemporaryFolder(appData,
1507 && SUCCEEDED(tempFolder->lpVtbl->QueryInterface(tempFolder,
1510 && SUCCEEDED(tempFolderItem->lpVtbl->get_Path(tempFolderItem,
1513 const wchar_t* tempPathBuf =
1514 WindowsGetStringRawBuffer(tempPath, &tempPathLen);
1517 if (wcsncat_s(buf, bufLen, tempPathBuf, tempPathLen) == 0
1518 && wcscat_s(buf, bufLen, L"\\") == 0
1519 && wcscat_s(buf, bufLen, TEXT(GC_LOG_STD_NAME)) == 0)
1521 WindowsDeleteString(tempPath);
1524 if (tempFolderItem != NULL)
1525 tempFolderItem->lpVtbl->Release(tempFolderItem);
1526 if (tempFolder != NULL)
1527 tempFolder->lpVtbl->Release(tempFolder);
1528 if (appData != NULL)
1529 appData->lpVtbl->Release(appData);
1530 appDataStatics->lpVtbl->Release(appDataStatics);
1534 # endif /* MSWINRT_FLAVOR */
1536 STATIC HANDLE GC_CreateLogFile(void)
1539 # ifdef MSWINRT_FLAVOR
1540 TCHAR pathBuf[_MAX_PATH + 0x10]; /* buffer for path + ext */
1542 hFile = INVALID_HANDLE_VALUE;
1543 if (getWinRTLogPath(pathBuf, _MAX_PATH + 1)) {
1544 CREATEFILE2_EXTENDED_PARAMETERS extParams;
1546 BZERO(&extParams, sizeof(extParams));
1547 extParams.dwSize = sizeof(extParams);
1548 extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
1549 extParams.dwFileFlags = GC_print_stats == VERBOSE ? 0
1550 : FILE_FLAG_WRITE_THROUGH;
1551 hFile = CreateFile2(pathBuf, GENERIC_WRITE, FILE_SHARE_READ,
1552 CREATE_ALWAYS, &extParams);
1557 BOOL appendToFile = FALSE;
1558 # if !defined(NO_GETENV_WIN32) || !defined(OLD_WIN32_LOG_FILE)
1559 TCHAR pathBuf[_MAX_PATH + 0x10]; /* buffer for path + ext */
1564 /* Use GetEnvironmentVariable instead of GETENV() for unicode support. */
1565 # ifndef NO_GETENV_WIN32
1566 if (GetEnvironmentVariable(TEXT("GC_LOG_FILE"), pathBuf,
1567 _MAX_PATH + 1) - 1U < (DWORD)_MAX_PATH) {
1568 appendToFile = TRUE;
1572 /* Env var not found or its value too long. */
1573 # ifdef OLD_WIN32_LOG_FILE
1574 logPath = TEXT(GC_LOG_STD_NAME);
1576 int len = (int)GetModuleFileName(NULL /* hModule */, pathBuf,
1578 /* If GetModuleFileName() has failed then len is 0. */
1579 if (len > 4 && pathBuf[len - 4] == (TCHAR)'.') {
1580 len -= 4; /* strip executable file extension */
1582 BCOPY(TEXT(".") TEXT(GC_LOG_STD_NAME), &pathBuf[len],
1583 sizeof(TEXT(".") TEXT(GC_LOG_STD_NAME)));
1587 hFile = CreateFile(logPath, GENERIC_WRITE, FILE_SHARE_READ,
1588 NULL /* lpSecurityAttributes */,
1589 appendToFile ? OPEN_ALWAYS : CREATE_ALWAYS,
1590 GC_print_stats == VERBOSE ? FILE_ATTRIBUTE_NORMAL :
1591 /* immediately flush writes unless very verbose */
1592 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
1593 NULL /* hTemplateFile */);
1595 # ifndef NO_GETENV_WIN32
1596 if (appendToFile && hFile != INVALID_HANDLE_VALUE) {
1598 (void)SetFilePointer(hFile, 0, &posHigh, FILE_END);
1599 /* Seek to file end (ignoring any error) */
1606 STATIC int GC_write(const char *buf, size_t len)
1610 # if defined(THREADS) && defined(GC_ASSERTIONS)
1611 static GC_bool inside_write = FALSE;
1612 /* to prevent infinite recursion at abort. */
1619 IF_NEED_TO_LOCK(EnterCriticalSection(&GC_write_cs));
1620 # if defined(THREADS) && defined(GC_ASSERTIONS)
1621 if (GC_write_disabled) {
1622 inside_write = TRUE;
1623 ABORT("Assertion failure: GC_write called with write_disabled");
1627 GC_log = GC_CreateLogFile();
1629 if (GC_log == INVALID_HANDLE_VALUE) {
1630 IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
1631 # ifdef NO_DEBUGGING
1632 /* Ignore open log failure (e.g., it might be caused by */
1633 /* read-only folder of the client application). */
1639 res = WriteFile(GC_log, buf, (DWORD)len, &written, NULL);
1640 # if defined(_MSC_VER) && defined(_DEBUG) && !defined(NO_CRT)
1642 /* There is no CrtDbgReport() in WinCE */
1645 /* Always use Unicode variant of OutputDebugString() */
1646 wbuf[MultiByteToWideChar(CP_ACP, 0 /* dwFlags */,
1648 sizeof(wbuf) / sizeof(wbuf[0]) - 1)] = 0;
1649 OutputDebugStringW(wbuf);
1652 _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
1655 IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
1656 return res ? (int)written : -1;
1659 /* TODO: This is pretty ugly ... */
1660 # define WRITE(f, buf, len) GC_write(buf, len)
1662 #elif defined(OS2) || defined(MACOS)
1663 STATIC FILE * GC_stdout = NULL;
1664 STATIC FILE * GC_stderr = NULL;
1665 STATIC FILE * GC_log = NULL;
1667 /* Initialize GC_log (and the friends) passed to GC_write(). */
1668 STATIC void GC_set_files(void)
1670 if (GC_stdout == NULL) {
1673 if (GC_stderr == NULL) {
1676 if (GC_log == NULL) {
1681 GC_INLINE int GC_write(FILE *f, const char *buf, size_t len)
1683 int res = fwrite(buf, 1, len, f);
1688 # define WRITE(f, buf, len) (GC_set_files(), GC_write(f, buf, len))
1690 #elif defined(GC_ANDROID_LOG)
1692 # include <android/log.h>
1694 # ifndef GC_ANDROID_LOG_TAG
1695 # define GC_ANDROID_LOG_TAG "BDWGC"
1698 # define GC_stdout ANDROID_LOG_DEBUG
1699 # define GC_stderr ANDROID_LOG_ERROR
1700 # define GC_log GC_stdout
1702 # define WRITE(level, buf, unused_len) \
1703 __android_log_write(level, GC_ANDROID_LOG_TAG, buf)
1705 # elif defined(NN_PLATFORM_CTR)
1706 int n3ds_log_write(const char* text, int length);
1707 # define WRITE(level, buf, len) n3ds_log_write(buf, len)
1708 # elif defined(NINTENDO_SWITCH)
1709 int switch_log_write(const char* text, int length);
1710 # define WRITE(level, buf, len) switch_log_write(buf, len)
1713 # if !defined(AMIGA) && !defined(MSWIN_XBOX1) && !defined(SN_TARGET_ORBIS) \
1714 && !defined(SN_TARGET_PSP2) && !defined(__CC_ARM)
1715 # include <unistd.h>
1718 STATIC int GC_write(int fd, const char *buf, size_t len)
1720 # if defined(ECOS) || defined(SN_TARGET_ORBIS) || defined(SN_TARGET_PSP2) \
1723 /* FIXME: This seems to be defined nowhere at present. */
1724 /* _Jv_diag_write(buf, len); */
1730 int bytes_written = 0;
1731 IF_CANCEL(int cancel_state;)
1733 DISABLE_CANCEL(cancel_state);
1734 while ((unsigned)bytes_written < len) {
1735 # ifdef GC_SOLARIS_THREADS
1736 int result = syscall(SYS_write, fd, buf + bytes_written,
1737 len - bytes_written);
1739 int result = write(fd, buf + bytes_written, len - bytes_written);
1743 RESTORE_CANCEL(cancel_state);
1746 bytes_written += result;
1748 RESTORE_CANCEL(cancel_state);
1749 return(bytes_written);
1753 # define WRITE(f, buf, len) GC_write(f, buf, len)
1754 #endif /* !MSWIN32 && !OS2 && !MACOS && !GC_ANDROID_LOG */
1758 #if defined(DJGPP) || defined(__STRICT_ANSI__)
1759 /* vsnprintf is missing in DJGPP (v2.0.3) */
1760 # define GC_VSNPRINTF(buf, bufsz, format, args) vsprintf(buf, format, args)
1761 #elif defined(_MSC_VER)
1763 /* _vsnprintf is deprecated in WinCE */
1764 # define GC_VSNPRINTF StringCchVPrintfA
1766 # define GC_VSNPRINTF _vsnprintf
1769 # define GC_VSNPRINTF vsnprintf
1772 /* A version of printf that is unlikely to call malloc, and is thus safer */
1773 /* to call from the collector in case malloc has been bound to GC_malloc. */
1774 /* Floating point arguments and formats should be avoided, since FP */
1775 /* conversion is more likely to allocate memory. */
1776 /* Assumes that no more than BUFSZ-1 characters are written at once. */
1777 #define GC_PRINTF_FILLBUF(buf, format) \
1780 va_start(args, format); \
1781 (buf)[sizeof(buf) - 1] = 0x15; /* guard */ \
1782 (void)GC_VSNPRINTF(buf, sizeof(buf) - 1, format, args); \
1784 if ((buf)[sizeof(buf) - 1] != 0x15) \
1785 ABORT("GC_printf clobbered stack"); \
1788 void GC_printf(const char *format, ...)
1791 char buf[BUFSZ + 1];
1793 GC_PRINTF_FILLBUF(buf, format);
1795 (void)WRITE(GC_stdout, buf, strlen(buf));
1796 /* Ignore errors silently. */
1798 if (WRITE(GC_stdout, buf, strlen(buf)) < 0)
1799 ABORT("write to stdout failed");
1804 void GC_err_printf(const char *format, ...)
1806 char buf[BUFSZ + 1];
1808 GC_PRINTF_FILLBUF(buf, format);
1812 void GC_log_printf(const char *format, ...)
1814 char buf[BUFSZ + 1];
1816 GC_PRINTF_FILLBUF(buf, format);
1818 (void)WRITE(GC_log, buf, strlen(buf));
1820 if (WRITE(GC_log, buf, strlen(buf)) < 0)
1821 ABORT("write to GC log failed");
1825 #ifndef GC_ANDROID_LOG
1827 # define GC_warn_printf GC_err_printf
1831 GC_INNER void GC_info_log_printf(const char *format, ...)
1833 char buf[BUFSZ + 1];
1835 GC_PRINTF_FILLBUF(buf, format);
1836 (void)WRITE(ANDROID_LOG_INFO, buf, 0 /* unused */);
1839 GC_INNER void GC_verbose_log_printf(const char *format, ...)
1841 char buf[BUFSZ + 1];
1843 GC_PRINTF_FILLBUF(buf, format);
1844 (void)WRITE(ANDROID_LOG_VERBOSE, buf, 0); /* ignore write errors */
1847 STATIC void GC_warn_printf(const char *format, ...)
1849 char buf[BUFSZ + 1];
1851 GC_PRINTF_FILLBUF(buf, format);
1852 (void)WRITE(ANDROID_LOG_WARN, buf, 0);
1855 #endif /* GC_ANDROID_LOG */
1857 void GC_err_puts(const char *s)
1859 (void)WRITE(GC_stderr, s, strlen(s)); /* ignore errors */
1862 STATIC void GC_CALLBACK GC_default_warn_proc(char *msg, GC_word arg)
1864 /* TODO: Add assertion on arg comply with msg (format). */
1865 GC_warn_printf(msg, arg);
1868 GC_INNER GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1870 /* This is recommended for production code (release). */
1871 GC_API void GC_CALLBACK GC_ignore_warn_proc(char *msg, GC_word arg)
1873 if (GC_print_stats) {
1874 /* Don't ignore warnings if stats printing is on. */
1875 GC_default_warn_proc(msg, arg);
1879 GC_API void GC_CALL GC_set_warn_proc(GC_warn_proc p)
1882 GC_ASSERT(NONNULL_ARG_NOT_NULL(p));
1883 # ifdef GC_WIN32_THREADS
1885 /* Need explicit GC_INIT call */
1886 GC_ASSERT(GC_is_initialized);
1888 if (!GC_is_initialized) GC_init();
1892 GC_current_warn_proc = p;
1896 GC_API GC_warn_proc GC_CALL GC_get_warn_proc(void)
1898 GC_warn_proc result;
1901 result = GC_current_warn_proc;
1906 #if !defined(PCR) && !defined(SMALL_CONFIG)
1907 /* Print (or display) a message before abnormal exit (including */
1908 /* abort). Invoked from ABORT(msg) macro (there msg is non-NULL) */
1909 /* and from EXIT() macro (msg is NULL in that case). */
1910 STATIC void GC_CALLBACK GC_default_on_abort(const char *msg)
1912 # ifndef DONT_USE_ATEXIT
1913 skip_gc_atexit = TRUE; /* disable at-exit GC_gcollect() */
1917 # ifdef MSGBOX_ON_ERROR
1918 GC_win32_MessageBoxA(msg, "Fatal error in GC", MB_ICONERROR | MB_OK);
1919 /* Also duplicate msg to GC log file. */
1922 # ifndef GC_ANDROID_LOG
1923 /* Avoid calling GC_err_printf() here, as GC_on_abort() could be */
1924 /* called from it. Note 1: this is not an atomic output. */
1925 /* Note 2: possible write errors are ignored. */
1926 # if defined(THREADS) && defined(GC_ASSERTIONS) \
1927 && (defined(MSWIN32) || defined(MSWINCE))
1928 if (!GC_write_disabled)
1931 if (WRITE(GC_stderr, msg, strlen(msg)) >= 0)
1932 (void)WRITE(GC_stderr, "\n", 1);
1935 __android_log_assert("*" /* cond */, GC_ANDROID_LOG_TAG, "%s\n", msg);
1939 # if !defined(NO_DEBUGGING) && !defined(GC_ANDROID_LOG)
1940 if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1941 /* In many cases it's easier to debug a running process. */
1942 /* It's arguably nicer to sleep, but that makes it harder */
1943 /* to look at the thread if the debugger doesn't know much */
1944 /* about threads. */
1952 GC_abort_func GC_on_abort = GC_default_on_abort;
1954 GC_API void GC_CALL GC_set_abort_func(GC_abort_func fn)
1957 GC_ASSERT(NONNULL_ARG_NOT_NULL(fn));
1963 GC_API GC_abort_func GC_CALL GC_get_abort_func(void)
1972 #endif /* !SMALL_CONFIG */
1974 GC_API void GC_CALL GC_enable(void)
1979 GC_ASSERT(GC_dont_gc != 0); /* ensure no counter underflow */
1984 GC_API void GC_CALL GC_disable(void)
1992 GC_API int GC_CALL GC_is_disabled(void)
1994 return GC_dont_gc != 0;
1997 /* Helper procedures for new kind creation. */
1998 GC_API void ** GC_CALL GC_new_free_list_inner(void)
2002 GC_ASSERT(I_HOLD_LOCK());
2003 result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1) * sizeof(ptr_t), PTRFREE);
2004 if (NULL == result) ABORT("Failed to allocate freelist for new kind");
2005 BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
2006 return (void **)result;
2009 GC_API void ** GC_CALL GC_new_free_list(void)
2014 result = GC_new_free_list_inner();
2019 GC_API unsigned GC_CALL GC_new_kind_inner(void **fl, GC_word descr,
2020 int adjust, int clear)
2022 unsigned result = GC_n_kinds;
2024 GC_ASSERT(adjust == FALSE || adjust == TRUE);
2025 /* If an object is not needed to be cleared (when moved to the */
2026 /* free list) then its descriptor should be zero to denote */
2027 /* a pointer-free object (and, as a consequence, the size of the */
2028 /* object should not be added to the descriptor template). */
2029 GC_ASSERT(clear == TRUE
2030 || (descr == 0 && adjust == FALSE && clear == FALSE));
2031 if (result < MAXOBJKINDS) {
2033 GC_obj_kinds[result].ok_freelist = fl;
2034 GC_obj_kinds[result].ok_reclaim_list = 0;
2035 GC_obj_kinds[result].ok_descriptor = descr;
2036 GC_obj_kinds[result].ok_relocate_descr = adjust;
2037 GC_obj_kinds[result].ok_init = (GC_bool)clear;
2038 # ifdef ENABLE_DISCLAIM
2039 GC_obj_kinds[result].ok_mark_unconditionally = FALSE;
2040 GC_obj_kinds[result].ok_disclaim_proc = 0;
2043 ABORT("Too many kinds");
2048 GC_API unsigned GC_CALL GC_new_kind(void **fl, GC_word descr, int adjust,
2054 result = GC_new_kind_inner(fl, descr, adjust, clear);
2059 GC_API unsigned GC_CALL GC_new_proc_inner(GC_mark_proc proc)
2061 unsigned result = GC_n_mark_procs;
2063 if (result < MAX_MARK_PROCS) {
2065 GC_mark_procs[result] = proc;
2067 ABORT("Too many mark procedures");
2072 GC_API unsigned GC_CALL GC_new_proc(GC_mark_proc proc)
2077 result = GC_new_proc_inner(proc);
2082 GC_API void * GC_CALL GC_call_with_alloc_lock(GC_fn_type fn, void *client_data)
2090 result = (*fn)(client_data);
2097 GC_API void * GC_CALL GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
2099 struct GC_stack_base base;
2102 base.mem_base = (void *)&base;
2104 base.reg_base = (void *)GC_save_regs_in_stack();
2105 /* Unnecessarily flushes register stack, */
2106 /* but that probably doesn't hurt. */
2108 result = fn(&base, arg);
2109 /* Strongly discourage the compiler from treating the above */
2110 /* as a tail call. */
2111 GC_noop1(COVERT_DATAFLOW(&base));
2117 GC_INNER ptr_t GC_blocked_sp = NULL;
2118 /* NULL value means we are not inside GC_do_blocking() call. */
2120 STATIC ptr_t GC_blocked_register_sp = NULL;
2123 GC_INNER struct GC_traced_stack_sect_s *GC_traced_stack_sect = NULL;
2125 /* This is nearly the same as in win32_threads.c */
2126 GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn,
2129 struct GC_traced_stack_sect_s stacksect;
2130 GC_ASSERT(GC_is_initialized);
2132 /* Adjust our stack bottom pointer (this could happen if */
2133 /* GC_get_main_stack_base() is unimplemented or broken for */
2134 /* the platform). */
2135 if ((word)GC_stackbottom HOTTER_THAN (word)(&stacksect))
2136 GC_stackbottom = (ptr_t)COVERT_DATAFLOW(&stacksect);
2138 if (GC_blocked_sp == NULL) {
2139 /* We are not inside GC_do_blocking() - do nothing more. */
2140 client_data = fn(client_data);
2141 /* Prevent treating the above as a tail call. */
2142 GC_noop1(COVERT_DATAFLOW(&stacksect));
2143 return client_data; /* result */
2146 /* Setup new "stack section". */
2147 stacksect.saved_stack_ptr = GC_blocked_sp;
2149 /* This is the same as in GC_call_with_stack_base(). */
2150 stacksect.backing_store_end = GC_save_regs_in_stack();
2151 /* Unnecessarily flushes register stack, */
2152 /* but that probably doesn't hurt. */
2153 stacksect.saved_backing_store_ptr = GC_blocked_register_sp;
2155 stacksect.prev = GC_traced_stack_sect;
2156 GC_blocked_sp = NULL;
2157 GC_traced_stack_sect = &stacksect;
2159 client_data = fn(client_data);
2160 GC_ASSERT(GC_blocked_sp == NULL);
2161 GC_ASSERT(GC_traced_stack_sect == &stacksect);
2163 # if defined(CPPCHECK)
2164 GC_noop1((word)GC_traced_stack_sect - (word)GC_blocked_sp);
2166 /* Restore original "stack section". */
2167 GC_traced_stack_sect = stacksect.prev;
2169 GC_blocked_register_sp = stacksect.saved_backing_store_ptr;
2171 GC_blocked_sp = stacksect.saved_stack_ptr;
2173 return client_data; /* result */
2176 /* This is nearly the same as in win32_threads.c */
2177 STATIC void GC_do_blocking_inner(ptr_t data, void * context GC_ATTR_UNUSED)
2179 struct blocking_data * d = (struct blocking_data *) data;
2180 GC_ASSERT(GC_is_initialized);
2181 GC_ASSERT(GC_blocked_sp == NULL);
2183 GC_blocked_sp = GC_save_regs_in_stack();
2185 GC_blocked_sp = (ptr_t) &d; /* save approx. sp */
2188 GC_blocked_register_sp = GC_save_regs_in_stack();
2191 d -> client_data = (d -> fn)(d -> client_data);
2194 GC_ASSERT(GC_blocked_sp != NULL);
2196 GC_ASSERT(GC_blocked_sp == (ptr_t)(&d));
2198 # if defined(CPPCHECK)
2199 GC_noop1((word)GC_blocked_sp);
2201 GC_blocked_sp = NULL;
2204 GC_API void GC_CALL GC_set_stackbottom(void *gc_thread_handle,
2205 const struct GC_stack_base *sb)
2207 GC_ASSERT(sb -> mem_base != NULL);
2208 GC_ASSERT(NULL == gc_thread_handle || &GC_stackbottom == gc_thread_handle);
2209 GC_ASSERT(NULL == GC_blocked_sp
2210 && NULL == GC_traced_stack_sect); /* for now */
2211 (void)gc_thread_handle;
2213 GC_stackbottom = (char *)sb->mem_base;
2215 GC_register_stackbottom = (ptr_t)sb->reg_base;
2219 GC_API void * GC_CALL GC_get_my_stackbottom(struct GC_stack_base *sb)
2221 GC_ASSERT(GC_is_initialized);
2222 sb -> mem_base = GC_stackbottom;
2224 sb -> reg_base = GC_register_stackbottom;
2226 return &GC_stackbottom; /* gc_thread_handle */
2228 #endif /* !THREADS */
2230 GC_API void * GC_CALL GC_do_blocking(GC_fn_type fn, void * client_data)
2232 struct blocking_data my_data;
2235 my_data.client_data = client_data;
2236 GC_with_callee_saves_pushed(GC_do_blocking_inner, (ptr_t)(&my_data));
2237 return my_data.client_data; /* result */
2240 #if !defined(NO_DEBUGGING)
2241 GC_API void GC_CALL GC_dump(void)
2246 GC_dump_named(NULL);
2250 GC_API void GC_CALL GC_dump_named(const char *name)
2253 CLOCK_TYPE current_time;
2255 GET_TIME(current_time);
2258 GC_printf("***GC Dump %s\n", name);
2260 GC_printf("***GC Dump collection #%lu\n", (unsigned long)GC_gc_no);
2263 /* Note that the time is wrapped in ~49 days if sizeof(long)==4. */
2264 GC_printf("Time since GC init: %lu ms\n",
2265 MS_TIME_DIFF(current_time, GC_init_time));
2268 GC_printf("\n***Static roots:\n");
2269 GC_print_static_roots();
2270 GC_printf("\n***Heap sections:\n");
2271 GC_print_heap_sects();
2272 GC_printf("\n***Free blocks:\n");
2273 GC_print_hblkfreelist();
2274 GC_printf("\n***Blocks in use:\n");
2275 GC_print_block_list();
2277 #endif /* !NO_DEBUGGING */
2279 static void block_add_size(struct hblk *h, word pbytes)
2282 *(word *)pbytes += (WORDS_TO_BYTES(hhdr->hb_sz) + (HBLKSIZE - 1))
2283 & ~(word)(HBLKSIZE - 1);
2286 GC_API size_t GC_CALL GC_get_memory_use(void)
2292 GC_apply_to_all_blocks(block_add_size, (word)(&bytes));
2294 return (size_t)bytes;
2297 /* Getter functions for the public Read-only variables. */
2299 /* GC_get_gc_no() is unsynchronized and should be typically called */
2300 /* inside the context of GC_call_with_alloc_lock() to prevent data */
2301 /* races (on multiprocessors). */
2302 GC_API GC_word GC_CALL GC_get_gc_no(void)
2308 GC_API int GC_CALL GC_get_parallel(void)
2310 /* GC_parallel is initialized at start-up. */
2314 GC_API void GC_CALL GC_alloc_lock(void)
2320 GC_API void GC_CALL GC_alloc_unlock(void)
2322 /* no DCL_LOCK_STATE */
2326 GC_INNER GC_on_thread_event_proc GC_on_thread_event = 0;
2328 GC_API void GC_CALL GC_set_on_thread_event(GC_on_thread_event_proc fn)
2330 /* fn may be 0 (means no event notifier). */
2333 GC_on_thread_event = fn;
2337 GC_API GC_on_thread_event_proc GC_CALL GC_get_on_thread_event(void)
2339 GC_on_thread_event_proc fn;
2342 fn = GC_on_thread_event;
2346 #endif /* THREADS */
2348 /* Setter and getter functions for the public R/W function variables. */
2349 /* These functions are synchronized (like GC_set_warn_proc() and */
2350 /* GC_get_warn_proc()). */
2352 GC_API void GC_CALL GC_set_oom_fn(GC_oom_func fn)
2354 GC_ASSERT(NONNULL_ARG_NOT_NULL(fn));
2361 GC_API GC_oom_func GC_CALL GC_get_oom_fn(void)
2371 GC_API void GC_CALL GC_set_on_heap_resize(GC_on_heap_resize_proc fn)
2373 /* fn may be 0 (means no event notifier). */
2376 GC_on_heap_resize = fn;
2380 GC_API GC_on_heap_resize_proc GC_CALL GC_get_on_heap_resize(void)
2382 GC_on_heap_resize_proc fn;
2385 fn = GC_on_heap_resize;
2390 GC_API void GC_CALL GC_set_finalizer_notifier(GC_finalizer_notifier_proc fn)
2392 /* fn may be 0 (means no finalizer notifier). */
2395 GC_finalizer_notifier = fn;
2399 GC_API GC_finalizer_notifier_proc GC_CALL GC_get_finalizer_notifier(void)
2401 GC_finalizer_notifier_proc fn;
2404 fn = GC_finalizer_notifier;
2409 /* Setter and getter functions for the public numeric R/W variables. */
2410 /* It is safe to call these functions even before GC_INIT(). */
2411 /* These functions are unsynchronized and should be typically called */
2412 /* inside the context of GC_call_with_alloc_lock() (if called after */
2413 /* GC_INIT()) to prevent data races (unless it is guaranteed the */
2414 /* collector is not multi-threaded at that execution point). */
2416 GC_API void GC_CALL GC_set_find_leak(int value)
2418 /* value is of boolean type. */
2419 GC_find_leak = value;
2422 GC_API int GC_CALL GC_get_find_leak(void)
2424 return GC_find_leak;
2427 GC_API void GC_CALL GC_set_all_interior_pointers(int value)
2431 GC_all_interior_pointers = value ? 1 : 0;
2432 if (GC_is_initialized) {
2433 /* It is not recommended to change GC_all_interior_pointers value */
2434 /* after GC is initialized but it seems GC could work correctly */
2435 /* even after switching the mode. */
2437 GC_initialize_offsets(); /* NOTE: this resets manual offsets as well */
2438 if (!GC_all_interior_pointers)
2439 GC_bl_init_no_interiors();
2444 GC_API int GC_CALL GC_get_all_interior_pointers(void)
2446 return GC_all_interior_pointers;
2449 GC_API void GC_CALL GC_set_finalize_on_demand(int value)
2451 GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2452 /* value is of boolean type. */
2453 GC_finalize_on_demand = value;
2456 GC_API int GC_CALL GC_get_finalize_on_demand(void)
2458 return GC_finalize_on_demand;
2461 GC_API void GC_CALL GC_set_java_finalization(int value)
2463 GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2464 /* value is of boolean type. */
2465 GC_java_finalization = value;
2468 GC_API int GC_CALL GC_get_java_finalization(void)
2470 return GC_java_finalization;
2473 GC_API void GC_CALL GC_set_dont_expand(int value)
2475 GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2476 /* value is of boolean type. */
2477 GC_dont_expand = value;
2480 GC_API int GC_CALL GC_get_dont_expand(void)
2482 return GC_dont_expand;
2485 GC_API void GC_CALL GC_set_no_dls(int value)
2487 GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2488 /* value is of boolean type. */
2492 GC_API int GC_CALL GC_get_no_dls(void)
2497 GC_API void GC_CALL GC_set_non_gc_bytes(GC_word value)
2499 GC_non_gc_bytes = value;
2502 GC_API GC_word GC_CALL GC_get_non_gc_bytes(void)
2504 return GC_non_gc_bytes;
2507 GC_API void GC_CALL GC_set_free_space_divisor(GC_word value)
2509 GC_ASSERT(value > 0);
2510 GC_free_space_divisor = value;
2513 GC_API GC_word GC_CALL GC_get_free_space_divisor(void)
2515 return GC_free_space_divisor;
2518 GC_API void GC_CALL GC_set_max_retries(GC_word value)
2520 GC_ASSERT((GC_signed_word)value != -1);
2521 /* -1 was used to retrieve old value in gc-7.2 */
2522 GC_max_retries = value;
2525 GC_API GC_word GC_CALL GC_get_max_retries(void)
2527 return GC_max_retries;
2530 GC_API void GC_CALL GC_set_dont_precollect(int value)
2532 GC_ASSERT(value != -1); /* -1 was used to retrieve old value in gc-7.2 */
2533 /* value is of boolean type. */
2534 GC_dont_precollect = value;
2537 GC_API int GC_CALL GC_get_dont_precollect(void)
2539 return GC_dont_precollect;
2542 GC_API void GC_CALL GC_set_full_freq(int value)
2544 GC_ASSERT(value >= 0);
2545 GC_full_freq = value;
2548 GC_API int GC_CALL GC_get_full_freq(void)
2550 return GC_full_freq;
2553 GC_API void GC_CALL GC_set_time_limit(unsigned long value)
2555 GC_ASSERT((long)value != -1L);
2556 /* -1 was used to retrieve old value in gc-7.2 */
2557 GC_time_limit = value;
2560 GC_API unsigned long GC_CALL GC_get_time_limit(void)
2562 return GC_time_limit;
2565 GC_API void GC_CALL GC_set_force_unmap_on_gcollect(int value)
2567 GC_force_unmap_on_gcollect = (GC_bool)value;
2570 GC_API int GC_CALL GC_get_force_unmap_on_gcollect(void)
2572 return (int)GC_force_unmap_on_gcollect;
2575 GC_API void GC_CALL GC_abort_on_oom(void)
2577 GC_err_printf("Insufficient memory for the allocation\n");
2582 GC_API void GC_CALL GC_stop_world_external(void)
2584 GC_ASSERT(GC_is_initialized);
2586 # ifdef THREAD_LOCAL_ALLOC
2587 GC_ASSERT(!GC_world_stopped);
2590 # ifdef THREAD_LOCAL_ALLOC
2591 GC_world_stopped = TRUE;
2595 GC_API void GC_CALL GC_start_world_external(void)
2597 # ifdef THREAD_LOCAL_ALLOC
2598 GC_ASSERT(GC_world_stopped);
2599 GC_world_stopped = FALSE;
2601 GC_ASSERT(GC_is_initialized);
2606 #endif /* THREADS */