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>
29 #if defined(MSWIN32) || defined(MSWINCE) \
30 || (defined(CYGWIN32) && defined(GC_READ_ENV_FILE))
31 # ifndef WIN32_LEAN_AND_MEAN
32 # define WIN32_LEAN_AND_MEAN 1
38 #if defined(UNIX_LIKE) || defined(CYGWIN32)
40 # include <sys/types.h>
41 # include <sys/stat.h>
50 # include "il/PCR_IL.h"
51 GC_INNER PCR_Th_ML GC_allocate_ml;
52 # elif defined(SN_TARGET_PS3)
54 GC_INNER pthread_mutex_t GC_allocate_ml;
56 /* For other platforms with threads, the lock and possibly */
57 /* GC_lock_holder variables are defined in the thread support code. */
60 #ifdef DYNAMIC_LOADING
61 /* We need to register the main data segment. Returns TRUE unless */
62 /* this is done implicitly as part of dynamic library registration. */
63 # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
65 /* Don't unnecessarily call GC_register_main_static_data() in case */
66 /* dyn_load.c isn't linked in. */
67 # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
70 #ifdef NEED_CANCEL_DISABLE_COUNT
71 __thread unsigned char GC_cancel_disable_count = 0;
74 GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
76 GC_INNER GC_bool GC_debugging_started = FALSE;
77 /* defined here so we don't have to load debug_malloc.o */
79 ptr_t GC_stackbottom = 0;
82 ptr_t GC_register_stackbottom = 0;
85 GC_bool GC_dont_gc = 0;
87 GC_bool GC_dont_precollect = 0;
89 GC_bool GC_quiet = 0; /* used also in pcr_interface.c */
92 GC_bool GC_print_stats = 0;
95 #ifdef GC_PRINT_BACK_HEIGHT
96 GC_INNER GC_bool GC_print_back_height = TRUE;
98 GC_INNER GC_bool GC_print_back_height = FALSE;
102 GC_INNER GC_bool GC_dump_regularly = FALSE;
103 /* Generate regular debugging dumps. */
106 #ifdef KEEP_BACK_PTRS
107 GC_INNER long GC_backtraces = 0;
108 /* Number of random backtraces to generate for each GC. */
112 int GC_find_leak = 1;
114 int GC_find_leak = 0;
117 #ifndef SHORT_DBG_HDRS
118 # ifdef GC_FINDLEAK_DELAY_FREE
119 GC_INNER GC_bool GC_findleak_delay_free = TRUE;
121 GC_INNER GC_bool GC_findleak_delay_free = FALSE;
123 #endif /* !SHORT_DBG_HDRS */
125 #ifdef ALL_INTERIOR_POINTERS
126 int GC_all_interior_pointers = 1;
128 int GC_all_interior_pointers = 0;
131 #ifdef GC_FORCE_UNMAP_ON_GCOLLECT
132 /* Has no effect unless USE_MUNMAP. */
133 /* Has no effect on implicitly-initiated garbage collections. */
134 GC_INNER GC_bool GC_force_unmap_on_gcollect = TRUE;
136 GC_INNER GC_bool GC_force_unmap_on_gcollect = FALSE;
139 #ifndef GC_LARGE_ALLOC_WARN_INTERVAL
140 # define GC_LARGE_ALLOC_WARN_INTERVAL 5
142 GC_INNER long GC_large_alloc_warn_interval = GC_LARGE_ALLOC_WARN_INTERVAL;
143 /* Interval between unsuppressed warnings. */
146 STATIC void * GC_CALLBACK GC_default_oom_fn(size_t bytes_requested)
151 /* All accesses to it should be synchronized to avoid data races. */
152 GC_oom_func GC_oom_fn = GC_default_oom_fn;
154 #ifdef CAN_HANDLE_FORK
156 GC_INNER GC_bool GC_handle_fork = TRUE;
157 /* The value is examined by GC_thr_init. */
159 GC_INNER GC_bool GC_handle_fork = FALSE;
161 #endif /* CAN_HANDLE_FORK */
163 /* Overrides the default handle-fork mode. Non-zero value means GC */
164 /* should install proper pthread_atfork handlers (or abort if not */
165 /* supported). Has effect only if called before GC_INIT. */
167 GC_API void GC_CALL GC_set_handle_fork(int value)
169 # ifdef CAN_HANDLE_FORK
170 if (!GC_is_initialized)
171 GC_handle_fork = (GC_bool)value;
172 # elif defined(THREADS) || (defined(DARWIN) && defined(MPROTECT_VDB))
173 if (!GC_is_initialized && value)
174 ABORT("fork() handling disabled");
176 /* No at-fork handler is needed in the single-threaded mode. */
180 /* Set things up so that GC_size_map[i] >= granules(i), */
181 /* but not too much bigger */
182 /* and so that size_map contains relatively few distinct entries */
183 /* This was originally stolen from Russ Atkinson's Cedar */
184 /* quantization algorithm (but we precompute it). */
185 STATIC void GC_init_size_map(void)
189 /* Map size 0 to something bigger. */
190 /* This avoids problems at lower levels. */
192 for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
193 GC_size_map[i] = ROUNDED_UP_GRANULES(i);
195 GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
196 /* Seems to tickle bug in VC++ 2008 for AMD64 */
199 /* We leave the rest of the array to be filled in on demand. */
202 /* Fill in additional entries in GC_size_map, including the ith one */
203 /* We assume the ith entry is currently 0. */
204 /* Note that a filled in section of the array ending at n always */
205 /* has length at least n/4. */
206 GC_INNER void GC_extend_size_map(size_t i)
208 size_t orig_granule_sz = ROUNDED_UP_GRANULES(i);
209 size_t granule_sz = orig_granule_sz;
210 size_t byte_sz = GRANULES_TO_BYTES(granule_sz);
211 /* The size we try to preserve. */
212 /* Close to i, unless this would */
213 /* introduce too many distinct sizes. */
214 size_t smaller_than_i = byte_sz - (byte_sz >> 3);
215 size_t much_smaller_than_i = byte_sz - (byte_sz >> 2);
216 size_t low_limit; /* The lowest indexed entry we */
220 if (GC_size_map[smaller_than_i] == 0) {
221 low_limit = much_smaller_than_i;
222 while (GC_size_map[low_limit] != 0) low_limit++;
224 low_limit = smaller_than_i + 1;
225 while (GC_size_map[low_limit] != 0) low_limit++;
226 granule_sz = ROUNDED_UP_GRANULES(low_limit);
227 granule_sz += granule_sz >> 3;
228 if (granule_sz < orig_granule_sz) granule_sz = orig_granule_sz;
230 /* For these larger sizes, we use an even number of granules. */
231 /* This makes it easier to, for example, construct a 16byte-aligned */
232 /* allocator even if GRANULE_BYTES is 8. */
235 if (granule_sz > MAXOBJGRANULES) {
236 granule_sz = MAXOBJGRANULES;
238 /* If we can fit the same number of larger objects in a block, */
241 size_t number_of_objs = HBLK_GRANULES/granule_sz;
242 granule_sz = HBLK_GRANULES/number_of_objs;
245 byte_sz = GRANULES_TO_BYTES(granule_sz);
246 /* We may need one extra byte; */
247 /* don't always fill in GC_size_map[byte_sz] */
248 byte_sz -= EXTRA_BYTES;
250 for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = granule_sz;
255 * The following is a gross hack to deal with a problem that can occur
256 * on machines that are sloppy about stack frame sizes, notably SPARC.
257 * Bogus pointers may be written to the stack and not cleared for
258 * a LONG time, because they always fall into holes in stack frames
259 * that are not written. We partially address this by clearing
260 * sections of the stack whenever we get control.
263 # define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */
264 # define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */
266 STATIC word GC_stack_last_cleared = 0; /* GC_no when we last did this */
267 STATIC ptr_t GC_min_sp = NULL;
268 /* Coolest stack pointer value from which */
269 /* we've already cleared the stack. */
270 STATIC ptr_t GC_high_water = NULL;
271 /* "hottest" stack pointer value we have seen */
272 /* recently. Degrades over time. */
273 STATIC word GC_bytes_allocd_at_reset = 0;
274 # define DEGRADE_RATE 50
277 # define CLEAR_SIZE 213 /* Granularity for GC_clear_stack_inner */
279 #if defined(ASM_CLEAR_CODE)
280 void *GC_clear_stack_inner(void *, ptr_t);
282 /* Clear the stack up to about limit. Return arg. This function is */
283 /* not static because it could also be errorneously defined in .S */
284 /* file, so this error would be caught by the linker. */
286 void * GC_clear_stack_inner(void *arg, ptr_t limit)
288 volatile word dummy[CLEAR_SIZE];
290 BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
291 if ((word)GC_approx_sp() COOLER_THAN (word)limit) {
292 (void) GC_clear_stack_inner(arg, limit);
294 /* Make sure the recursive call is not a tail call, and the bzero */
295 /* call is not recognized as dead code. */
296 GC_noop1((word)dummy);
301 /* Clear some of the inaccessible part of the stack. Returns its */
302 /* argument, so it can be used in a tail call position, hence clearing */
304 GC_API void * GC_CALL GC_clear_stack(void *arg)
306 ptr_t sp = GC_approx_sp(); /* Hotter than actual sp */
308 word dummy[SMALL_CLEAR_SIZE];
309 static unsigned random_no = 0;
310 /* Should be more random than it is ... */
311 /* Used to occasionally clear a bigger */
317 /* Extra bytes we clear every time. This clears our own */
318 /* activation record, and should cause more frequent */
319 /* clearing near the cold end of the stack, a good thing. */
320 # define GC_SLOP 4000
321 /* We make GC_high_water this much hotter than we really saw */
322 /* saw it, to cover for GC noise etc. above our current frame. */
323 # define CLEAR_THRESHOLD 100000
324 /* We restart the clearing process after this many bytes of */
325 /* allocation. Otherwise very heavily recursive programs */
326 /* with sparse stacks may result in heaps that grow almost */
327 /* without bounds. As the heap gets larger, collection */
328 /* frequency decreases, thus clearing frequency would decrease, */
329 /* thus more junk remains accessible, thus the heap gets */
332 if (++random_no % 13 == 0) {
334 MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
335 limit = (ptr_t)((word)limit & ~0xf);
336 /* Make it sufficiently aligned for assembly */
337 /* implementations of GC_clear_stack_inner. */
338 return GC_clear_stack_inner(arg, limit);
340 BZERO(dummy, SMALL_CLEAR_SIZE*sizeof(word));
344 if (GC_gc_no > GC_stack_last_cleared) {
345 /* Start things over, so we clear the entire stack again */
346 if (GC_stack_last_cleared == 0) GC_high_water = (ptr_t)GC_stackbottom;
347 GC_min_sp = GC_high_water;
348 GC_stack_last_cleared = GC_gc_no;
349 GC_bytes_allocd_at_reset = GC_bytes_allocd;
351 /* Adjust GC_high_water */
352 MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
353 if (sp HOTTER_THAN GC_high_water) {
356 MAKE_HOTTER(GC_high_water, GC_SLOP);
358 MAKE_HOTTER(limit, SLOP);
359 if (sp COOLER_THAN limit) {
360 limit = (ptr_t)((word)limit & ~0xf);
361 /* Make it sufficiently aligned for assembly */
362 /* implementations of GC_clear_stack_inner. */
364 return(GC_clear_stack_inner(arg, limit));
365 } else if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) {
366 /* Restart clearing process, but limit how much clearing we do. */
368 MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
369 if (GC_min_sp HOTTER_THAN GC_high_water) GC_min_sp = GC_high_water;
370 GC_bytes_allocd_at_reset = GC_bytes_allocd;
377 /* Return a pointer to the base address of p, given a pointer to a */
378 /* an address within an object. Return 0 o.w. */
379 GC_API void * GC_CALL GC_base(void * p)
388 if (!GC_is_initialized) return 0;
391 candidate_hdr = HDR_FROM_BI(bi, r);
392 if (candidate_hdr == 0) return(0);
393 /* If it's a pointer to the middle of a large object, move it */
394 /* to the beginning. */
395 while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
396 h = FORWARDED_ADDR(h,candidate_hdr);
398 candidate_hdr = HDR(h);
400 if (HBLK_IS_FREE(candidate_hdr)) return(0);
401 /* Make sure r points to the beginning of the object */
402 r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
404 size_t offset = HBLKDISPL(r);
405 word sz = candidate_hdr -> hb_sz;
406 size_t obj_displ = offset % sz;
410 if (limit > (ptr_t)(h + 1) && sz <= HBLKSIZE) {
413 if ((ptr_t)p >= limit) return(0);
419 /* Return the size of an object, given a pointer to its base. */
420 /* (For small objects this also happens to work from interior pointers, */
421 /* but that shouldn't be relied upon.) */
422 GC_API size_t GC_CALL GC_size(const void * p)
426 return hhdr -> hb_sz;
430 /* These getters remain unsynchronized for compatibility (since some */
431 /* clients could call some of them from a GC callback holding the */
432 /* allocator lock). */
433 GC_API size_t GC_CALL GC_get_heap_size(void)
435 /* ignore the memory space returned to OS (i.e. count only the */
436 /* space owned by the garbage collector) */
437 return (size_t)(GC_heapsize - GC_unmapped_bytes);
440 GC_API size_t GC_CALL GC_get_free_bytes(void)
442 /* ignore the memory space returned to OS */
443 return (size_t)(GC_large_free_bytes - GC_unmapped_bytes);
446 GC_API size_t GC_CALL GC_get_unmapped_bytes(void)
448 return (size_t)GC_unmapped_bytes;
451 GC_API size_t GC_CALL GC_get_bytes_since_gc(void)
453 return (size_t)GC_bytes_allocd;
456 GC_API size_t GC_CALL GC_get_total_bytes(void)
458 return (size_t)(GC_bytes_allocd + GC_bytes_allocd_before_gc);
461 /* Return the heap usage information. This is a thread-safe (atomic) */
462 /* alternative for the five above getters. NULL pointer is allowed for */
463 /* any argument. Returned (filled in) values are of word type. */
464 GC_API void GC_CALL GC_get_heap_usage_safe(GC_word *pheap_size,
465 GC_word *pfree_bytes, GC_word *punmapped_bytes,
466 GC_word *pbytes_since_gc, GC_word *ptotal_bytes)
471 if (pheap_size != NULL)
472 *pheap_size = GC_heapsize - GC_unmapped_bytes;
473 if (pfree_bytes != NULL)
474 *pfree_bytes = GC_large_free_bytes - GC_unmapped_bytes;
475 if (punmapped_bytes != NULL)
476 *punmapped_bytes = GC_unmapped_bytes;
477 if (pbytes_since_gc != NULL)
478 *pbytes_since_gc = GC_bytes_allocd;
479 if (ptotal_bytes != NULL)
480 *ptotal_bytes = GC_bytes_allocd + GC_bytes_allocd_before_gc;
486 GC_API int GC_CALL GC_get_suspend_signal(void)
496 #if !defined(_MAX_PATH) && (defined(MSWIN32) || defined(MSWINCE) \
497 || defined(CYGWIN32))
498 # define _MAX_PATH MAX_PATH
501 #ifdef GC_READ_ENV_FILE
502 /* This works for Win32/WinCE for now. Really useful only for WinCE. */
503 STATIC char *GC_envfile_content = NULL;
504 /* The content of the GC "env" file with CR and */
505 /* LF replaced to '\0'. NULL if the file is */
506 /* missing or empty. Otherwise, always ends */
508 STATIC unsigned GC_envfile_length = 0;
509 /* Length of GC_envfile_content (if non-NULL). */
511 # ifndef GC_ENVFILE_MAXLEN
512 # define GC_ENVFILE_MAXLEN 0x4000
515 /* The routine initializes GC_envfile_content from the GC "env" file. */
516 STATIC void GC_envfile_init(void)
518 # if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
524 TCHAR path[_MAX_PATH + 0x10]; /* buffer for path + ext */
525 len = (unsigned)GetModuleFileName(NULL /* hModule */, path,
527 /* If GetModuleFileName() has failed then len is 0. */
528 if (len > 4 && path[len - 4] == (TCHAR)'.') {
529 len -= 4; /* strip executable file extension */
531 memcpy(&path[len], TEXT(".gc.env"), sizeof(TEXT(".gc.env")));
532 hFile = CreateFile(path, GENERIC_READ,
533 FILE_SHARE_READ | FILE_SHARE_WRITE,
534 NULL /* lpSecurityAttributes */, OPEN_EXISTING,
535 FILE_ATTRIBUTE_NORMAL, NULL /* hTemplateFile */);
536 if (hFile == INVALID_HANDLE_VALUE)
537 return; /* the file is absent or the operation is failed */
538 len = (unsigned)GetFileSize(hFile, NULL);
539 if (len <= 1 || len >= GC_ENVFILE_MAXLEN) {
541 return; /* invalid file length - ignoring the file content */
543 /* At this execution point, GC_setpagesize() and GC_init_win32() */
544 /* must already be called (for GET_MEM() to work correctly). */
545 content = (char *)GET_MEM(len + 1);
546 if (content == NULL) {
548 return; /* allocation failure */
551 nBytesRead = (DWORD)-1L;
552 /* Last ReadFile() call should clear nBytesRead on success. */
553 while (ReadFile(hFile, content + ofs, len - ofs + 1, &nBytesRead,
554 NULL /* lpOverlapped */) && nBytesRead != 0) {
555 if ((ofs += nBytesRead) > len)
559 if (ofs != len || nBytesRead != 0)
560 return; /* read operation is failed - ignoring the file content */
563 if (content[ofs] == '\r' || content[ofs] == '\n')
566 GC_envfile_length = len + 1;
567 GC_envfile_content = content;
571 /* This routine scans GC_envfile_content for the specified */
572 /* environment variable (and returns its value if found). */
573 GC_INNER char * GC_envfile_getenv(const char *name)
576 char *end_of_content;
579 p = getenv(name); /* try the standard getenv() first */
581 return *p != '\0' ? p : NULL;
583 p = GC_envfile_content;
585 return NULL; /* "env" file is absent (or empty) */
586 namelen = strlen(name);
587 if (namelen == 0) /* a sanity check */
589 for (end_of_content = p + GC_envfile_length;
590 p != end_of_content; p += strlen(p) + 1) {
591 if (strncmp(p, name, namelen) == 0 && *(p += namelen) == '=') {
592 p++; /* the match is found; skip '=' */
593 return *p != '\0' ? p : NULL;
595 /* If not matching then skip to the next line. */
597 return NULL; /* no match found */
599 #endif /* GC_READ_ENV_FILE */
601 GC_INNER GC_bool GC_is_initialized = FALSE;
603 #if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
604 GC_INNER CRITICAL_SECTION GC_write_cs;
607 STATIC void GC_exit_check(void)
613 static void looping_handler(int sig)
615 GC_err_printf("Caught signal %d: looping in handler\n", sig);
619 static GC_bool installed_looping_handler = FALSE;
621 static void maybe_install_looping_handler(void)
623 /* Install looping handler before the write fault handler, so we */
624 /* handle write faults correctly. */
625 if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
626 GC_set_and_save_fault_handler(looping_handler);
627 installed_looping_handler = TRUE;
631 #else /* !UNIX_LIKE */
632 # define maybe_install_looping_handler()
635 #if !defined(OS2) && !defined(MACOS) && !defined(MSWIN32) && !defined(MSWINCE)
636 STATIC int GC_stdout = 1;
637 STATIC int GC_stderr = 2;
638 STATIC int GC_log = 2; /* stderr */
641 STATIC word GC_parse_mem_size_arg(const char *str)
644 word result = 0; /* bad value */
648 result = (word)STRTOULL(str, &endptr, 10);
651 if (*(endptr + 1) != '\0')
653 /* Allow k, M or G suffix. */
675 GC_API void GC_CALL GC_init(void)
677 /* LOCK(); -- no longer does anything this early. */
678 word initial_heap_sz;
679 IF_CANCEL(int cancel_state;)
681 if (GC_is_initialized) return;
682 # ifdef REDIRECT_MALLOC
684 static GC_bool init_started = FALSE;
686 ABORT("Redirected malloc() called during GC init");
691 # ifdef GC_INITIAL_HEAP_SIZE
692 initial_heap_sz = divHBLKSZ(GC_INITIAL_HEAP_SIZE);
694 initial_heap_sz = (word)MINHINCR;
696 DISABLE_CANCEL(cancel_state);
697 /* Note that although we are nominally called with the */
698 /* allocation lock held, the allocation lock is now */
699 /* only really acquired once a second thread is forked.*/
700 /* And the initialization code needs to run before */
701 /* then. Thus we really don't hold any locks, and can */
702 /* in fact safely initialize them here. */
704 GC_ASSERT(!GC_need_to_lock);
705 # ifdef SN_TARGET_PS3
707 pthread_mutexattr_t mattr;
708 pthread_mutexattr_init(&mattr);
709 pthread_mutex_init(&GC_allocate_ml, &mattr);
710 pthread_mutexattr_destroy(&mattr);
713 # endif /* THREADS */
714 # if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
717 BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL;
718 HMODULE hK32 = GetModuleHandle(TEXT("kernel32.dll"));
720 pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD))
721 GetProcAddress (hK32,
722 "InitializeCriticalSectionAndSpinCount");
724 pfn(&GC_allocate_ml, 4000);
726 # endif /* !MSWINCE */
727 /* else */ InitializeCriticalSection (&GC_allocate_ml);
729 # endif /* GC_WIN32_THREADS */
730 # if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
731 InitializeCriticalSection(&GC_write_cs);
737 # ifdef GC_READ_ENV_FILE
740 # ifndef SMALL_CONFIG
741 # ifdef GC_PRINT_VERBOSE_STATS
742 /* This is useful for debugging and profiling on platforms with */
743 /* missing getenv() (like WinCE). */
744 GC_print_stats = VERBOSE;
746 if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
747 GC_print_stats = VERBOSE;
748 } else if (0 != GETENV("GC_PRINT_STATS")) {
752 # if defined(UNIX_LIKE) || defined(CYGWIN32)
754 char * file_name = GETENV("GC_LOG_FILE");
755 if (0 != file_name) {
756 int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666);
758 GC_err_printf("Failed to open %s as log file\n", file_name);
762 str = GETENV("GC_ONLY_LOG_TO_FILE");
763 # ifdef GC_ONLY_LOG_TO_FILE
764 /* The similar environment variable set to "0" */
765 /* overrides the effect of the macro defined. */
766 if (str != NULL && *str == '0' && *(str + 1) == '\0')
768 /* Otherwise setting the environment variable */
769 /* to anything other than "0" will prevent from */
770 /* redirecting stdout/err to the log file. */
771 if (str == NULL || (*str == '0' && *(str + 1) == '\0'))
781 # endif /* !SMALL_CONFIG */
782 # ifndef NO_DEBUGGING
783 if (0 != GETENV("GC_DUMP_REGULARLY")) {
784 GC_dump_regularly = TRUE;
787 # ifdef KEEP_BACK_PTRS
789 char * backtraces_string = GETENV("GC_BACKTRACES");
790 if (0 != backtraces_string) {
791 GC_backtraces = atol(backtraces_string);
792 if (backtraces_string[0] == '\0') GC_backtraces = 1;
796 if (0 != GETENV("GC_FIND_LEAK")) {
799 # ifndef SHORT_DBG_HDRS
800 if (0 != GETENV("GC_FINDLEAK_DELAY_FREE")) {
801 GC_findleak_delay_free = TRUE;
804 if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
805 GC_all_interior_pointers = 1;
807 if (0 != GETENV("GC_DONT_GC")) {
810 if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
811 GC_print_back_height = TRUE;
813 if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
814 GC_large_alloc_warn_interval = LONG_MAX;
817 char * addr_string = GETENV("GC_TRACE");
818 if (0 != addr_string) {
819 # ifndef ENABLE_TRACE
820 WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
822 word addr = (word)STRTOULL(addr_string, NULL, 16);
824 WARN("Unlikely trace address: %p\n", addr);
825 GC_trace_addr = (ptr_t)addr;
829 # ifndef GC_DISABLE_INCREMENTAL
831 char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
832 if (0 != time_limit_string) {
833 long time_limit = atol(time_limit_string);
834 if (time_limit < 5) {
835 WARN("GC_PAUSE_TIME_TARGET environment variable value too small "
836 "or bad syntax: Ignoring\n", 0);
838 GC_time_limit = time_limit;
843 # ifndef SMALL_CONFIG
845 char * full_freq_string = GETENV("GC_FULL_FREQUENCY");
846 if (full_freq_string != NULL) {
847 int full_freq = atoi(full_freq_string);
849 GC_full_freq = full_freq;
854 char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
855 if (0 != interval_string) {
856 long interval = atol(interval_string);
858 WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
859 "bad value: Ignoring\n", 0);
861 GC_large_alloc_warn_interval = interval;
866 char * space_divisor_string = GETENV("GC_FREE_SPACE_DIVISOR");
867 if (space_divisor_string != NULL) {
868 int space_divisor = atoi(space_divisor_string);
869 if (space_divisor > 0)
870 GC_free_space_divisor = (GC_word)space_divisor;
875 char * string = GETENV("GC_UNMAP_THRESHOLD");
876 if (string != NULL) {
877 if (*string == '0' && *(string + 1) == '\0') {
878 /* "0" is used to disable unmapping. */
879 GC_unmap_threshold = 0;
881 int unmap_threshold = atoi(string);
882 if (unmap_threshold > 0)
883 GC_unmap_threshold = unmap_threshold;
888 char * string = GETENV("GC_FORCE_UNMAP_ON_GCOLLECT");
889 if (string != NULL) {
890 if (*string == '0' && *(string + 1) == '\0') {
891 /* "0" is used to turn off the mode. */
892 GC_force_unmap_on_gcollect = FALSE;
894 GC_force_unmap_on_gcollect = TRUE;
899 char * string = GETENV("GC_USE_ENTIRE_HEAP");
900 if (string != NULL) {
901 if (*string == '0' && *(string + 1) == '\0') {
902 /* "0" is used to turn off the mode. */
903 GC_use_entire_heap = FALSE;
905 GC_use_entire_heap = TRUE;
910 maybe_install_looping_handler();
911 /* Adjust normal object descriptor for extra allocation. */
912 if (ALIGNMENT > GC_DS_TAGS && EXTRA_BYTES != 0) {
913 GC_obj_kinds[NORMAL].ok_descriptor = ((word)(-ALIGNMENT) | GC_DS_LENGTH);
915 GC_exclude_static_roots_inner(beginGC_arrays, endGC_arrays);
916 GC_exclude_static_roots_inner(beginGC_obj_kinds, endGC_obj_kinds);
917 # ifdef SEPARATE_GLOBALS
918 GC_exclude_static_roots_inner(beginGC_objfreelist, endGC_objfreelist);
919 GC_exclude_static_roots_inner(beginGC_aobjfreelist, endGC_aobjfreelist);
921 # if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
922 WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
923 /* If thread stacks are cached, they tend to be scanned in */
924 /* entirety as part of the root set. This wil grow them to */
925 /* maximum size, and is generally not desirable. */
927 # if defined(SEARCH_FOR_DATA_START)
928 GC_init_linux_data_start();
930 # if defined(NETBSD) && defined(__ELF__)
931 GC_init_netbsd_elf();
933 # if !defined(THREADS) || defined(GC_PTHREADS) \
934 || defined(GC_WIN32_THREADS) || defined(GC_SOLARIS_THREADS)
935 if (GC_stackbottom == 0) {
936 GC_stackbottom = GC_get_main_stack_base();
937 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
938 GC_register_stackbottom = GC_get_register_stack_base();
941 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
942 if (GC_register_stackbottom == 0) {
943 WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
944 /* The following may fail, since we may rely on */
945 /* alignment properties that may not hold with a user set */
946 /* GC_stackbottom. */
947 GC_register_stackbottom = GC_get_register_stack_base();
952 GC_STATIC_ASSERT(sizeof (ptr_t) == sizeof(word));
953 GC_STATIC_ASSERT(sizeof (signed_word) == sizeof(word));
954 GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
956 GC_ASSERT(!((word)GC_stackbottom HOTTER_THAN (word)GC_approx_sp()));
958 # if !defined(_AUX_SOURCE) || defined(__GNUC__)
959 GC_STATIC_ASSERT((word)(-1) > (word)0);
960 /* word should be unsigned */
962 # if !defined(__BORLANDC__) && !defined(__CC_ARM) \
963 && !(defined(__clang__) && defined(X86_64)) /* Workaround */
964 GC_STATIC_ASSERT((ptr_t)(word)(-1) > (ptr_t)0);
965 /* Ptr_t comparisons should behave as unsigned comparisons. */
967 GC_STATIC_ASSERT((signed_word)(-1) < (signed_word)0);
968 # ifndef GC_DISABLE_INCREMENTAL
969 if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
970 /* For GWW_VDB on Win32, this needs to happen before any */
971 /* heap memory is allocated. */
973 GC_ASSERT(GC_bytes_allocd == 0);
974 GC_incremental = TRUE;
978 /* Add initial guess of root sets. Do this first, since sbrk(0) */
980 if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
985 char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
986 if (sz_str != NULL) {
987 initial_heap_sz = GC_parse_mem_size_arg(sz_str);
988 if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
989 WARN("Bad initial heap size %s - ignoring it.\n", sz_str);
991 initial_heap_sz = divHBLKSZ(initial_heap_sz);
995 char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
996 if (sz_str != NULL) {
997 word max_heap_sz = GC_parse_mem_size_arg(sz_str);
998 if (max_heap_sz < initial_heap_sz * HBLKSIZE) {
999 WARN("Bad maximum heap size %s - ignoring it.\n", sz_str);
1001 if (0 == GC_max_retries) GC_max_retries = 2;
1002 GC_set_max_heap_size(max_heap_sz);
1005 if (!GC_expand_hp_inner(initial_heap_sz)) {
1006 GC_err_printf("Can't start up: not enough memory\n");
1009 if (GC_all_interior_pointers)
1010 GC_initialize_offsets();
1011 GC_register_displacement_inner(0L);
1012 # if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
1013 if (!GC_all_interior_pointers) {
1014 /* TLS ABI uses pointer-sized offsets for dtv. */
1015 GC_register_displacement_inner(sizeof(void *));
1020 if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
1022 ABORT("Can't lock load state");
1023 } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
1024 ABORT("Can't unlock load state");
1029 GC_is_initialized = TRUE;
1030 # if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
1034 /* Get black list set up and/or incremental GC started */
1035 if (!GC_dont_precollect || GC_incremental) GC_gcollect_inner();
1036 # ifdef STUBBORN_ALLOC
1039 /* Convince lint that some things are used */
1042 extern char * const GC_copyright[];
1043 GC_noop(GC_copyright, GC_find_header, GC_push_one,
1044 GC_call_with_alloc_lock, GC_dont_expand,
1045 # ifndef NO_DEBUGGING
1048 GC_register_finalizer_no_order);
1053 /* This is to give us at least one chance to detect leaks. */
1054 /* This may report some very benign leaks, but ... */
1055 atexit(GC_exit_check);
1058 /* The rest of this again assumes we don't really hold */
1059 /* the allocation lock. */
1060 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
1061 /* Make sure marker threads are started and thread local */
1062 /* allocation is initialized, in case we didn't get */
1063 /* called from GC_init_parallel. */
1065 # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
1067 # if defined(DYNAMIC_LOADING) && defined(DARWIN)
1068 /* This must be called WITHOUT the allocation lock held */
1069 /* and before any threads are created. */
1072 RESTORE_CANCEL(cancel_state);
1075 GC_API void GC_CALL GC_enable_incremental(void)
1077 # if !defined(GC_DISABLE_INCREMENTAL) && !defined(KEEP_BACK_PTRS)
1079 /* If we are keeping back pointers, the GC itself dirties all */
1080 /* pages on which objects have been marked, making */
1081 /* incremental GC pointless. */
1082 if (!GC_find_leak && 0 == GETENV("GC_DISABLE_INCREMENTAL")) {
1084 if (!GC_incremental) {
1086 /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
1087 maybe_install_looping_handler(); /* Before write fault handler! */
1088 GC_incremental = TRUE;
1089 if (!GC_is_initialized) {
1094 if (GC_dirty_maintained && !GC_dont_gc) {
1095 /* Can't easily do it if GC_dont_gc. */
1096 if (GC_bytes_allocd > 0) {
1097 /* There may be unmarked reachable objects. */
1098 GC_gcollect_inner();
1100 /* else we're OK in assuming everything's */
1101 /* clean since nothing can point to an */
1102 /* unmarked object. */
1113 #if defined(MSWIN32) || defined(MSWINCE)
1115 # if defined(_MSC_VER) && defined(_DEBUG) && !defined(MSWINCE)
1116 # include <crtdbg.h>
1119 STATIC HANDLE GC_log = 0;
1121 void GC_deinit(void)
1124 if (GC_is_initialized) {
1125 DeleteCriticalSection(&GC_write_cs);
1131 # ifdef PARALLEL_MARK
1132 # define IF_NEED_TO_LOCK(x) if (GC_parallel || GC_need_to_lock) x
1134 # define IF_NEED_TO_LOCK(x) if (GC_need_to_lock) x
1137 # define IF_NEED_TO_LOCK(x)
1138 # endif /* !THREADS */
1140 STATIC HANDLE GC_CreateLogFile(void)
1142 # if !defined(NO_GETENV_WIN32) || !defined(OLD_WIN32_LOG_FILE)
1143 TCHAR logPath[_MAX_PATH + 0x10]; /* buffer for path + ext */
1145 /* Use GetEnvironmentVariable instead of GETENV() for unicode support. */
1146 # ifndef NO_GETENV_WIN32
1147 if (GetEnvironmentVariable(TEXT("GC_LOG_FILE"), logPath,
1148 _MAX_PATH + 1) - 1U >= (DWORD)_MAX_PATH)
1151 /* Env var not found or its value too long. */
1152 # ifdef OLD_WIN32_LOG_FILE
1153 return CreateFile(TEXT("gc.log"), GENERIC_WRITE, FILE_SHARE_READ,
1154 NULL /* lpSecurityAttributes */, CREATE_ALWAYS,
1155 FILE_FLAG_WRITE_THROUGH, NULL /* hTemplateFile */);
1157 int len = (int)GetModuleFileName(NULL /* hModule */, logPath,
1159 /* If GetModuleFileName() has failed then len is 0. */
1160 if (len > 4 && logPath[len - 4] == (TCHAR)'.') {
1161 len -= 4; /* strip executable file extension */
1163 /* strcat/wcscat() are deprecated on WinCE, so use memcpy() */
1164 memcpy(&logPath[len], TEXT(".gc.log"), sizeof(TEXT(".gc.log")));
1167 # if !defined(NO_GETENV_WIN32) || !defined(OLD_WIN32_LOG_FILE)
1168 return CreateFile(logPath, GENERIC_WRITE, FILE_SHARE_READ,
1169 NULL /* lpSecurityAttributes */, CREATE_ALWAYS,
1170 GC_print_stats == VERBOSE ? FILE_ATTRIBUTE_NORMAL :
1171 /* immediately flush writes unless very verbose */
1172 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
1173 NULL /* hTemplateFile */);
1177 STATIC int GC_write(const char *buf, size_t len)
1183 IF_NEED_TO_LOCK(EnterCriticalSection(&GC_write_cs));
1185 GC_ASSERT(!GC_write_disabled);
1187 if (GC_log == INVALID_HANDLE_VALUE) {
1188 IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
1190 } else if (GC_log == 0) {
1191 GC_log = GC_CreateLogFile();
1192 /* Ignore open log failure if the collector is built with */
1193 /* print_stats always set on. */
1194 # ifndef GC_PRINT_VERBOSE_STATS
1195 if (GC_log == INVALID_HANDLE_VALUE)
1196 ABORT("Open of log file failed");
1199 tmp = WriteFile(GC_log, buf, (DWORD)len, &written, NULL);
1202 # if defined(_MSC_VER) && defined(_DEBUG)
1204 /* There is no CrtDbgReport() in WinCE */
1207 /* Always use Unicode variant of OutputDebugString() */
1208 wbuf[MultiByteToWideChar(CP_ACP, 0 /* dwFlags */,
1210 sizeof(wbuf) / sizeof(wbuf[0]) - 1)] = 0;
1211 OutputDebugStringW(wbuf);
1214 _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
1217 IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
1218 return tmp ? (int)written : -1;
1221 /* FIXME: This is pretty ugly ... */
1222 # define WRITE(f, buf, len) GC_write(buf, len)
1224 #elif defined(OS2) || defined(MACOS)
1225 STATIC FILE * GC_stdout = NULL;
1226 STATIC FILE * GC_stderr = NULL;
1227 STATIC FILE * GC_log = NULL;
1229 /* Initialize GC_log (and the friends) passed to GC_write(). */
1230 STATIC void GC_set_files(void)
1232 if (GC_stdout == NULL) {
1235 if (GC_stderr == NULL) {
1238 if (GC_log == NULL) {
1243 GC_INLINE int GC_write(FILE *f, const char *buf, size_t len)
1245 int res = fwrite(buf, 1, len, f);
1250 # define WRITE(f, buf, len) (GC_set_files(), GC_write(f, buf, len))
1253 # if !defined(AMIGA) && !defined(__CC_ARM)
1254 # include <unistd.h>
1257 STATIC int GC_write(int fd, const char *buf, size_t len)
1259 # if defined(ECOS) || defined(NOSYS)
1261 /* FIXME: This seems to be defined nowhere at present. */
1262 /* _Jv_diag_write(buf, len); */
1268 int bytes_written = 0;
1270 IF_CANCEL(int cancel_state;)
1272 DISABLE_CANCEL(cancel_state);
1273 while ((size_t)bytes_written < len) {
1274 # ifdef GC_SOLARIS_THREADS
1275 result = syscall(SYS_write, fd, buf + bytes_written,
1276 len - bytes_written);
1278 result = write(fd, buf + bytes_written, len - bytes_written);
1281 RESTORE_CANCEL(cancel_state);
1284 bytes_written += result;
1286 RESTORE_CANCEL(cancel_state);
1287 return(bytes_written);
1291 # define WRITE(f, buf, len) GC_write(f, buf, len)
1292 #endif /* !MSWIN32 && !OS2 && !MACOS */
1297 /* In case this function is missing (eg., in DJGPP v2.0.3). */
1298 # define vsnprintf(buf, bufsz, format, args) vsprintf(buf, format, args)
1299 #elif defined(_MSC_VER)
1301 /* _vsnprintf is deprecated in WinCE */
1302 # define vsnprintf StringCchVPrintfA
1304 # define vsnprintf _vsnprintf
1307 /* A version of printf that is unlikely to call malloc, and is thus safer */
1308 /* to call from the collector in case malloc has been bound to GC_malloc. */
1309 /* Floating point arguments and formats should be avoided, since fp */
1310 /* conversion is more likely to allocate. */
1311 /* Assumes that no more than BUFSZ-1 characters are written at once. */
1312 void GC_printf(const char *format, ...)
1317 if (GC_quiet) return;
1318 va_start(args, format);
1320 (void) vsnprintf(buf, BUFSZ, format, args);
1322 if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1323 if (WRITE(GC_stdout, buf, strlen(buf)) < 0)
1324 ABORT("write to stdout failed");
1327 void GC_err_printf(const char *format, ...)
1332 va_start(args, format);
1334 (void) vsnprintf(buf, BUFSZ, format, args);
1336 if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1337 if (WRITE(GC_stderr, buf, strlen(buf)) < 0)
1338 ABORT("write to stderr failed");
1341 void GC_log_printf(const char *format, ...)
1346 va_start(args, format);
1348 (void) vsnprintf(buf, BUFSZ, format, args);
1350 if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1351 if (WRITE(GC_log, buf, strlen(buf)) < 0)
1352 ABORT("write to log failed");
1355 /* This is equivalent to GC_err_printf("%s",s). */
1356 void GC_err_puts(const char *s)
1358 if (WRITE(GC_stderr, s, strlen(s)) < 0) ABORT("write to stderr failed");
1361 STATIC void GC_CALLBACK GC_default_warn_proc(char *msg, GC_word arg)
1363 GC_err_printf(msg, arg);
1366 GC_INNER GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1368 /* This is recommended for production code (release). */
1369 GC_API void GC_CALLBACK GC_ignore_warn_proc(char *msg, GC_word arg)
1371 if (GC_print_stats) {
1372 /* Don't ignore warnings if stats printing is on. */
1373 GC_default_warn_proc(msg, arg);
1377 GC_API void GC_CALL GC_set_warn_proc(GC_warn_proc p)
1381 # ifdef GC_WIN32_THREADS
1383 /* Need explicit GC_INIT call */
1384 GC_ASSERT(GC_is_initialized);
1386 if (!GC_is_initialized) GC_init();
1390 GC_current_warn_proc = p;
1394 GC_API GC_warn_proc GC_CALL GC_get_warn_proc(void)
1396 GC_warn_proc result;
1399 result = GC_current_warn_proc;
1404 #if !defined(PCR) && !defined(SMALL_CONFIG)
1405 /* Abort the program with a message. msg must not be NULL. */
1406 void GC_abort(const char *msg)
1408 # if defined(MSWIN32)
1409 # ifndef DONT_USE_USER32_DLL
1410 /* Use static binding to "user32.dll". */
1411 (void)MessageBoxA(NULL, msg, "Fatal error in GC", MB_ICONERROR|MB_OK);
1413 /* This simplifies linking - resolve "MessageBoxA" at run-time. */
1414 HINSTANCE hU32 = LoadLibrary(TEXT("user32.dll"));
1416 FARPROC pfn = GetProcAddress(hU32, "MessageBoxA");
1418 (void)(*(int (WINAPI *)(HWND, LPCSTR, LPCSTR, UINT))pfn)(
1419 NULL /* hWnd */, msg, "Fatal error in GC",
1420 MB_ICONERROR | MB_OK);
1421 (void)FreeLibrary(hU32);
1424 /* Also duplicate msg to GC log file. */
1426 /* Avoid calling GC_err_printf() here, as GC_abort() could be */
1427 /* called from it. Note 1: this is not an atomic output. */
1428 /* Note 2: possible write errors are ignored. */
1429 if (WRITE(GC_stderr, (void *)msg, strlen(msg)) >= 0)
1430 (void)WRITE(GC_stderr, (void *)("\n"), 1);
1432 if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1433 /* In many cases it's easier to debug a running process. */
1434 /* It's arguably nicer to sleep, but that makes it harder */
1435 /* to look at the thread if the debugger doesn't know much */
1436 /* about threads. */
1440 if (!msg) return; /* to suppress compiler warnings in ABORT callers. */
1442 # if defined(MSWIN32) && (defined(NO_DEBUGGING) || defined(LINT2))
1443 /* A more user-friendly abort after showing fatal message. */
1444 _exit(-1); /* exit on error without running "at-exit" callbacks */
1445 # elif defined(MSWINCE) && defined(NO_DEBUGGING)
1447 # elif defined(MSWIN32) || defined(MSWINCE)
1449 /* Note that on a WinCE box, this could be silently */
1450 /* ignored (i.e., the program is not aborted). */
1455 #endif /* !SMALL_CONFIG */
1457 GC_API void GC_CALL GC_enable(void)
1465 GC_API void GC_CALL GC_disable(void)
1473 GC_API int GC_CALL GC_is_disabled(void)
1475 return GC_dont_gc != 0;
1478 /* Helper procedures for new kind creation. */
1479 GC_API void ** GC_CALL GC_new_free_list_inner(void)
1481 void *result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1)*sizeof(ptr_t),
1483 if (result == 0) ABORT("Failed to allocate freelist for new kind");
1484 BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
1488 GC_API void ** GC_CALL GC_new_free_list(void)
1493 result = GC_new_free_list_inner();
1498 GC_API unsigned GC_CALL GC_new_kind_inner(void **fl, GC_word descr,
1499 int adjust, int clear)
1501 unsigned result = GC_n_kinds++;
1503 if (GC_n_kinds > MAXOBJKINDS) ABORT("Too many kinds");
1504 GC_obj_kinds[result].ok_freelist = fl;
1505 GC_obj_kinds[result].ok_reclaim_list = 0;
1506 GC_obj_kinds[result].ok_descriptor = descr;
1507 GC_obj_kinds[result].ok_relocate_descr = adjust;
1508 GC_obj_kinds[result].ok_init = clear;
1512 GC_API unsigned GC_CALL GC_new_kind(void **fl, GC_word descr, int adjust,
1518 result = GC_new_kind_inner(fl, descr, adjust, clear);
1523 GC_API unsigned GC_CALL GC_new_proc_inner(GC_mark_proc proc)
1525 unsigned result = GC_n_mark_procs++;
1527 if (GC_n_mark_procs > MAX_MARK_PROCS) ABORT("Too many mark procedures");
1528 GC_mark_procs[result] = proc;
1532 GC_API unsigned GC_CALL GC_new_proc(GC_mark_proc proc)
1537 result = GC_new_proc_inner(proc);
1542 GC_API void * GC_CALL GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
1544 struct GC_stack_base base;
1547 base.mem_base = (void *)&base;
1549 base.reg_base = (void *)GC_save_regs_in_stack();
1550 /* Unnecessarily flushes register stack, */
1551 /* but that probably doesn't hurt. */
1553 result = fn(&base, arg);
1554 /* Strongly discourage the compiler from treating the above */
1555 /* as a tail call. */
1556 GC_noop1((word)(&base));
1562 GC_INNER ptr_t GC_blocked_sp = NULL;
1563 /* NULL value means we are not inside GC_do_blocking() call. */
1565 STATIC ptr_t GC_blocked_register_sp = NULL;
1568 GC_INNER struct GC_traced_stack_sect_s *GC_traced_stack_sect = NULL;
1570 /* This is nearly the same as in win32_threads.c */
1571 GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn,
1574 struct GC_traced_stack_sect_s stacksect;
1575 GC_ASSERT(GC_is_initialized);
1577 /* Adjust our stack base value (this could happen if */
1578 /* GC_get_main_stack_base() is unimplemented or broken for */
1579 /* the platform). */
1580 if (GC_stackbottom HOTTER_THAN (ptr_t)(&stacksect))
1581 GC_stackbottom = (ptr_t)(&stacksect);
1583 if (GC_blocked_sp == NULL) {
1584 /* We are not inside GC_do_blocking() - do nothing more. */
1585 return fn(client_data);
1588 /* Setup new "stack section". */
1589 stacksect.saved_stack_ptr = GC_blocked_sp;
1591 /* This is the same as in GC_call_with_stack_base(). */
1592 stacksect.backing_store_end = GC_save_regs_in_stack();
1593 /* Unnecessarily flushes register stack, */
1594 /* but that probably doesn't hurt. */
1595 stacksect.saved_backing_store_ptr = GC_blocked_register_sp;
1597 stacksect.prev = GC_traced_stack_sect;
1598 GC_blocked_sp = NULL;
1599 GC_traced_stack_sect = &stacksect;
1601 client_data = fn(client_data);
1602 GC_ASSERT(GC_blocked_sp == NULL);
1603 GC_ASSERT(GC_traced_stack_sect == &stacksect);
1605 /* Restore original "stack section". */
1606 GC_traced_stack_sect = stacksect.prev;
1608 GC_blocked_register_sp = stacksect.saved_backing_store_ptr;
1610 GC_blocked_sp = stacksect.saved_stack_ptr;
1612 return client_data; /* result */
1615 /* This is nearly the same as in win32_threads.c */
1617 STATIC void GC_do_blocking_inner(ptr_t data, void * context)
1619 struct blocking_data * d = (struct blocking_data *) data;
1620 GC_ASSERT(GC_is_initialized);
1621 GC_ASSERT(GC_blocked_sp == NULL);
1623 GC_blocked_sp = GC_save_regs_in_stack();
1625 GC_blocked_sp = (ptr_t) &d; /* save approx. sp */
1628 GC_blocked_register_sp = GC_save_regs_in_stack();
1631 d -> client_data = (d -> fn)(d -> client_data);
1634 GC_ASSERT(GC_blocked_sp != NULL);
1636 GC_ASSERT(GC_blocked_sp == (ptr_t) &d);
1638 GC_blocked_sp = NULL;
1641 #endif /* !THREADS */
1643 /* Wrapper for functions that are likely to block (or, at least, do not */
1644 /* allocate garbage collected memory and/or manipulate pointers to the */
1645 /* garbage collected heap) for an appreciable length of time. */
1646 /* In the single threaded case, GC_do_blocking() (together */
1647 /* with GC_call_with_gc_active()) might be used to make stack scanning */
1648 /* more precise (i.e. scan only stack frames of functions that allocate */
1649 /* garbage collected memory and/or manipulate pointers to the garbage */
1650 /* collected heap). */
1651 GC_API void * GC_CALL GC_do_blocking(GC_fn_type fn, void * client_data)
1653 struct blocking_data my_data;
1656 my_data.client_data = client_data;
1657 GC_with_callee_saves_pushed(GC_do_blocking_inner, (ptr_t)(&my_data));
1658 return my_data.client_data; /* result */
1661 #if !defined(NO_DEBUGGING)
1662 GC_API void GC_CALL GC_dump(void)
1664 GC_printf("***Static roots:\n");
1665 GC_print_static_roots();
1666 GC_printf("\n***Heap sections:\n");
1667 GC_print_heap_sects();
1668 GC_printf("\n***Free blocks:\n");
1669 GC_print_hblkfreelist();
1670 GC_printf("\n***Blocks in use:\n");
1671 GC_print_block_list();
1673 #endif /* !NO_DEBUGGING */
1675 /* Getter functions for the public Read-only variables. */
1677 /* GC_get_gc_no() is unsynchronized and should be typically called */
1678 /* inside the context of GC_call_with_alloc_lock() to prevent data */
1679 /* races (on multiprocessors). */
1680 GC_API GC_word GC_CALL GC_get_gc_no(void)
1686 GC_API int GC_CALL GC_get_parallel(void)
1688 /* GC_parallel is initialized at start-up. */
1693 /* Setter and getter functions for the public R/W function variables. */
1694 /* These functions are synchronized (like GC_set_warn_proc() and */
1695 /* GC_get_warn_proc()). */
1697 GC_API void GC_CALL GC_set_oom_fn(GC_oom_func fn)
1706 GC_API GC_oom_func GC_CALL GC_get_oom_fn(void)
1716 GC_API void GC_CALL GC_set_finalizer_notifier(GC_finalizer_notifier_proc fn)
1718 /* fn may be 0 (means no finalizer notifier). */
1721 GC_finalizer_notifier = fn;
1725 GC_API GC_finalizer_notifier_proc GC_CALL GC_get_finalizer_notifier(void)
1727 GC_finalizer_notifier_proc fn;
1730 fn = GC_finalizer_notifier;
1735 /* Setter and getter functions for the public numeric R/W variables. */
1736 /* It is safe to call these functions even before GC_INIT(). */
1737 /* These functions are unsynchronized and should be typically called */
1738 /* inside the context of GC_call_with_alloc_lock() (if called after */
1739 /* GC_INIT()) to prevent data races (unless it is guaranteed the */
1740 /* collector is not multi-threaded at that execution point). */
1742 GC_API void GC_CALL GC_set_find_leak(int value)
1744 /* value is of boolean type. */
1745 GC_find_leak = value;
1748 GC_API int GC_CALL GC_get_find_leak(void)
1750 return GC_find_leak;
1753 GC_API void GC_CALL GC_set_all_interior_pointers(int value)
1757 GC_all_interior_pointers = value ? 1 : 0;
1758 if (GC_is_initialized) {
1759 /* It is not recommended to change GC_all_interior_pointers value */
1760 /* after GC is initialized but it seems GC could work correctly */
1761 /* even after switching the mode. */
1763 GC_initialize_offsets(); /* NOTE: this resets manual offsets as well */
1764 if (!GC_all_interior_pointers)
1765 GC_bl_init_no_interiors();
1770 GC_API int GC_CALL GC_get_all_interior_pointers(void)
1772 return GC_all_interior_pointers;
1775 GC_API void GC_CALL GC_set_finalize_on_demand(int value)
1777 GC_ASSERT(value != -1);
1778 /* value is of boolean type. */
1779 GC_finalize_on_demand = value;
1782 GC_API int GC_CALL GC_get_finalize_on_demand(void)
1784 return GC_finalize_on_demand;
1787 GC_API void GC_CALL GC_set_java_finalization(int value)
1789 GC_ASSERT(value != -1);
1790 /* value is of boolean type. */
1791 GC_java_finalization = value;
1794 GC_API int GC_CALL GC_get_java_finalization(void)
1796 return GC_java_finalization;
1799 GC_API void GC_CALL GC_set_dont_expand(int value)
1801 GC_ASSERT(value != -1);
1802 /* value is of boolean type. */
1803 GC_dont_expand = value;
1806 GC_API int GC_CALL GC_get_dont_expand(void)
1808 return GC_dont_expand;
1811 GC_API void GC_CALL GC_set_no_dls(int value)
1813 GC_ASSERT(value != -1);
1814 /* value is of boolean type. */
1818 GC_API int GC_CALL GC_get_no_dls(void)
1823 GC_API void GC_CALL GC_set_non_gc_bytes(GC_word value)
1825 GC_non_gc_bytes = value;
1828 GC_API GC_word GC_CALL GC_get_non_gc_bytes(void)
1830 return GC_non_gc_bytes;
1833 GC_API void GC_CALL GC_set_free_space_divisor(GC_word value)
1835 GC_ASSERT(value > 0);
1836 GC_free_space_divisor = value;
1839 GC_API GC_word GC_CALL GC_get_free_space_divisor(void)
1841 return GC_free_space_divisor;
1844 GC_API void GC_CALL GC_set_max_retries(GC_word value)
1846 GC_ASSERT(value != ~(GC_word)0);
1847 GC_max_retries = value;
1850 GC_API GC_word GC_CALL GC_get_max_retries(void)
1852 return GC_max_retries;
1855 GC_API void GC_CALL GC_set_dont_precollect(int value)
1857 GC_ASSERT(value != -1);
1858 /* value is of boolean type. */
1859 GC_dont_precollect = value;
1862 GC_API int GC_CALL GC_get_dont_precollect(void)
1864 return GC_dont_precollect;
1867 GC_API void GC_CALL GC_set_full_freq(int value)
1869 GC_ASSERT(value >= 0);
1870 GC_full_freq = value;
1873 GC_API int GC_CALL GC_get_full_freq(void)
1875 return GC_full_freq;
1878 GC_API void GC_CALL GC_set_time_limit(unsigned long value)
1880 GC_ASSERT(value != (unsigned long)-1L);
1881 GC_time_limit = value;
1884 GC_API unsigned long GC_CALL GC_get_time_limit(void)
1886 return GC_time_limit;
1889 GC_API void GC_CALL GC_set_force_unmap_on_gcollect(int value)
1891 GC_force_unmap_on_gcollect = (GC_bool)value;
1894 GC_API int GC_CALL GC_get_force_unmap_on_gcollect(void)
1896 return (int)GC_force_unmap_on_gcollect;