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.
15 /* Boehm, July 31, 1995 5:02 pm PDT */
25 #define I_HIDE_POINTERS /* To make GC_call_with_alloc_lock visible */
26 #include "private/gc_pmark.h"
28 #ifdef GC_SOLARIS_THREADS
29 # include <sys/syscall.h>
31 #if defined(MSWIN32) || defined(MSWINCE)
32 # define WIN32_LEAN_AND_MEAN
40 # include <sys/types.h>
41 # include <sys/stat.h>
43 int GC_log; /* Forward decl, so we can set it. */
50 #if defined(THREADS) && defined(PCR)
51 # include "il/PCR_IL.h"
52 PCR_Th_ML GC_allocate_ml;
54 /* For other platforms with threads, the lock and possibly */
55 /* GC_lock_holder variables are defined in the thread support code. */
57 #if defined(NOSYS) || defined(ECOS)
61 /* Dont unnecessarily call GC_register_main_static_data() in case */
62 /* dyn_load.c isn't linked in. */
63 #ifdef DYNAMIC_LOADING
64 # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
66 # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
69 GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
72 GC_bool GC_debugging_started = FALSE;
73 /* defined here so we don't have to load debug_malloc.o */
75 void (*GC_check_heap) (void) = (void (*) (void))0;
76 void (*GC_print_all_smashed) (void) = (void (*) (void))0;
78 void (*GC_start_call_back) (void) = (void (*) (void))0;
80 ptr_t GC_stackbottom = 0;
83 ptr_t GC_register_stackbottom = 0;
86 GC_bool GC_dont_gc = 0;
88 GC_bool GC_dont_precollect = 0;
93 GC_bool GC_print_stats = 0;
96 GC_bool GC_print_back_height = 0;
99 GC_bool GC_dump_regularly = 0; /* Generate regular debugging dumps. */
102 #ifdef KEEP_BACK_PTRS
103 long GC_backtraces = 0; /* Number of random backtraces to */
104 /* generate for each GC. */
108 int GC_find_leak = 1;
110 int GC_find_leak = 0;
113 #ifdef ALL_INTERIOR_POINTERS
114 int GC_all_interior_pointers = 1;
116 int GC_all_interior_pointers = 0;
119 long GC_large_alloc_warn_interval = 5;
120 /* Interval between unsuppressed warnings. */
122 long GC_large_alloc_warn_suppressed = 0;
123 /* Number of warnings suppressed so far. */
126 void * GC_default_oom_fn(size_t bytes_requested)
131 void * (*GC_oom_fn) (size_t bytes_requested) = GC_default_oom_fn;
133 void * GC_project2(void *arg1, void *arg2)
138 /* Set things up so that GC_size_map[i] >= granules(i), */
139 /* but not too much bigger */
140 /* and so that size_map contains relatively few distinct entries */
141 /* This was originally stolen from Russ Atkinson's Cedar */
142 /* quantization alogrithm (but we precompute it). */
143 void GC_init_size_map(void)
147 /* Map size 0 to something bigger. */
148 /* This avoids problems at lower levels. */
150 for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
151 GC_size_map[i] = ROUNDED_UP_GRANULES(i);
152 GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
154 /* We leave the rest of the array to be filled in on demand. */
157 /* Fill in additional entries in GC_size_map, including the ith one */
158 /* We assume the ith entry is currently 0. */
159 /* Note that a filled in section of the array ending at n always */
160 /* has length at least n/4. */
161 void GC_extend_size_map(size_t i)
163 size_t orig_granule_sz = ROUNDED_UP_GRANULES(i);
164 size_t granule_sz = orig_granule_sz;
165 size_t byte_sz = GRANULES_TO_BYTES(granule_sz);
166 /* The size we try to preserve. */
167 /* Close to i, unless this would */
168 /* introduce too many distinct sizes. */
169 size_t smaller_than_i = byte_sz - (byte_sz >> 3);
170 size_t much_smaller_than_i = byte_sz - (byte_sz >> 2);
171 size_t low_limit; /* The lowest indexed entry we */
175 if (GC_size_map[smaller_than_i] == 0) {
176 low_limit = much_smaller_than_i;
177 while (GC_size_map[low_limit] != 0) low_limit++;
179 low_limit = smaller_than_i + 1;
180 while (GC_size_map[low_limit] != 0) low_limit++;
181 granule_sz = ROUNDED_UP_GRANULES(low_limit);
182 granule_sz += granule_sz >> 3;
183 if (granule_sz < orig_granule_sz) granule_sz = orig_granule_sz;
185 /* For these larger sizes, we use an even number of granules. */
186 /* This makes it easier to, for example, construct a 16byte-aligned */
187 /* allocator even if GRANULE_BYTES is 8. */
190 if (granule_sz > MAXOBJGRANULES) {
191 granule_sz = MAXOBJGRANULES;
193 /* If we can fit the same number of larger objects in a block, */
196 size_t number_of_objs = HBLK_GRANULES/granule_sz;
197 granule_sz = HBLK_GRANULES/number_of_objs;
200 byte_sz = GRANULES_TO_BYTES(granule_sz);
201 /* We may need one extra byte; */
202 /* don't always fill in GC_size_map[byte_sz] */
203 byte_sz -= EXTRA_BYTES;
205 for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = granule_sz;
210 * The following is a gross hack to deal with a problem that can occur
211 * on machines that are sloppy about stack frame sizes, notably SPARC.
212 * Bogus pointers may be written to the stack and not cleared for
213 * a LONG time, because they always fall into holes in stack frames
214 * that are not written. We partially address this by clearing
215 * sections of the stack whenever we get control.
217 word GC_stack_last_cleared = 0; /* GC_no when we last did this */
219 # define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */
220 # define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */
222 # define CLEAR_SIZE 213 /* Granularity for GC_clear_stack_inner */
223 # define DEGRADE_RATE 50
225 ptr_t GC_min_sp; /* Coolest stack pointer value from which we've */
226 /* already cleared the stack. */
229 /* "hottest" stack pointer value we have seen */
230 /* recently. Degrades over time. */
232 word GC_bytes_allocd_at_reset;
234 #if defined(ASM_CLEAR_CODE)
235 extern void *GC_clear_stack_inner(void *, ptr_t);
237 /* Clear the stack up to about limit. Return arg. */
239 void * GC_clear_stack_inner(void *arg, ptr_t limit)
241 word dummy[CLEAR_SIZE];
243 BZERO(dummy, CLEAR_SIZE*sizeof(word));
244 if ((ptr_t)(dummy) COOLER_THAN limit) {
245 (void) GC_clear_stack_inner(arg, limit);
247 /* Make sure the recursive call is not a tail call, and the bzero */
248 /* call is not recognized as dead code. */
249 GC_noop1((word)dummy);
254 /* Clear some of the inaccessible part of the stack. Returns its */
255 /* argument, so it can be used in a tail call position, hence clearing */
257 void * GC_clear_stack(void *arg)
259 ptr_t sp = GC_approx_sp(); /* Hotter than actual sp */
261 word dummy[SMALL_CLEAR_SIZE];
262 static unsigned random_no = 0;
263 /* Should be more random than it is ... */
264 /* Used to occasionally clear a bigger */
270 /* Extra bytes we clear every time. This clears our own */
271 /* activation record, and should cause more frequent */
272 /* clearing near the cold end of the stack, a good thing. */
273 # define GC_SLOP 4000
274 /* We make GC_high_water this much hotter than we really saw */
275 /* saw it, to cover for GC noise etc. above our current frame. */
276 # define CLEAR_THRESHOLD 100000
277 /* We restart the clearing process after this many bytes of */
278 /* allocation. Otherwise very heavily recursive programs */
279 /* with sparse stacks may result in heaps that grow almost */
280 /* without bounds. As the heap gets larger, collection */
281 /* frequency decreases, thus clearing frequency would decrease, */
282 /* thus more junk remains accessible, thus the heap gets */
285 if (++random_no % 13 == 0) {
287 MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
288 limit = (ptr_t)((word)limit & ~0xf);
289 /* Make it sufficiently aligned for assembly */
290 /* implementations of GC_clear_stack_inner. */
291 return GC_clear_stack_inner(arg, limit);
293 BZERO(dummy, SMALL_CLEAR_SIZE*sizeof(word));
297 if (GC_gc_no > GC_stack_last_cleared) {
298 /* Start things over, so we clear the entire stack again */
299 if (GC_stack_last_cleared == 0) GC_high_water = (ptr_t)GC_stackbottom;
300 GC_min_sp = GC_high_water;
301 GC_stack_last_cleared = GC_gc_no;
302 GC_bytes_allocd_at_reset = GC_bytes_allocd;
304 /* Adjust GC_high_water */
305 MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
306 if (sp HOTTER_THAN GC_high_water) {
309 MAKE_HOTTER(GC_high_water, GC_SLOP);
311 MAKE_HOTTER(limit, SLOP);
312 if (sp COOLER_THAN limit) {
313 limit = (ptr_t)((word)limit & ~0xf);
314 /* Make it sufficiently aligned for assembly */
315 /* implementations of GC_clear_stack_inner. */
317 return(GC_clear_stack_inner(arg, limit));
318 } else if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) {
319 /* Restart clearing process, but limit how much clearing we do. */
321 MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
322 if (GC_min_sp HOTTER_THAN GC_high_water) GC_min_sp = GC_high_water;
323 GC_bytes_allocd_at_reset = GC_bytes_allocd;
330 /* Return a pointer to the base address of p, given a pointer to a */
331 /* an address within an object. Return 0 o.w. */
332 void * GC_base(void * p)
341 if (!GC_is_initialized) return 0;
344 candidate_hdr = HDR_FROM_BI(bi, r);
345 if (candidate_hdr == 0) return(0);
346 /* If it's a pointer to the middle of a large object, move it */
347 /* to the beginning. */
348 while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
349 h = FORWARDED_ADDR(h,candidate_hdr);
351 candidate_hdr = HDR(h);
353 if (HBLK_IS_FREE(candidate_hdr)) return(0);
354 /* Make sure r points to the beginning of the object */
355 r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
357 size_t offset = HBLKDISPL(r);
358 signed_word sz = candidate_hdr -> hb_sz;
359 size_t obj_displ = offset % sz;
363 if (limit > (ptr_t)(h + 1) && sz <= HBLKSIZE) {
366 if ((ptr_t)p >= limit) return(0);
372 /* Return the size of an object, given a pointer to its base. */
373 /* (For small obects this also happens to work from interior pointers, */
374 /* but that shouldn't be relied upon.) */
375 size_t GC_size(void * p)
379 return hhdr -> hb_sz;
382 size_t GC_get_heap_size(void)
387 size_t GC_get_free_bytes(void)
389 return GC_large_free_bytes;
392 size_t GC_get_bytes_since_gc(void)
394 return GC_bytes_allocd;
397 size_t GC_get_total_bytes(void)
399 return GC_bytes_allocd+GC_bytes_allocd_before_gc;
402 GC_bool GC_is_initialized = FALSE;
404 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
405 extern void GC_init_parallel(void);
406 # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
408 /* FIXME: The GC_init/GC_init_inner distinction should go away. */
411 /* LOCK(); -- no longer does anything this early. */
416 #if defined(MSWIN32) || defined(MSWINCE)
417 CRITICAL_SECTION GC_write_cs;
421 extern void GC_init_win32(void);
424 extern void GC_setpagesize();
427 extern GC_bool GC_no_win32_dlls;
429 # define GC_no_win32_dlls FALSE
432 void GC_exit_check(void)
437 #ifdef SEARCH_FOR_DATA_START
438 extern void GC_init_linux_data_start(void);
443 extern void GC_set_and_save_fault_handler(void (*handler)(int));
445 static void looping_handler(sig)
448 GC_err_printf("Caught signal %d: looping in handler\n", sig);
452 static GC_bool installed_looping_handler = FALSE;
454 static void maybe_install_looping_handler()
456 /* Install looping handler before the write fault handler, so we */
457 /* handle write faults correctly. */
458 if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
459 GC_set_and_save_fault_handler(looping_handler);
460 installed_looping_handler = TRUE;
464 #else /* !UNIX_LIKE */
466 # define maybe_install_looping_handler()
470 #if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
471 void GC_thr_init(void);
476 # if !defined(THREADS) && defined(GC_ASSERTIONS)
479 word initial_heap_sz = (word)MINHINCR;
481 if (GC_is_initialized) return;
483 /* Note that although we are nominally called with the */
484 /* allocation lock held, the allocation lock is now */
485 /* only really acquired once a second thread is forked.*/
486 /* And the initialization code needs to run before */
487 /* then. Thus we really don't hold any locks, and can */
488 /* in fact safely initialize them here. */
490 GC_ASSERT(!GC_need_to_lock);
492 # if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
493 if (!GC_is_initialized) {
494 BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL;
495 HMODULE hK32 = GetModuleHandleA("kernel32.dll");
497 pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD))
498 GetProcAddress (hK32,
499 "InitializeCriticalSectionAndSpinCount");
501 pfn(&GC_allocate_ml, 4000);
503 InitializeCriticalSection (&GC_allocate_ml);
506 # if defined(MSWIN32) || defined(MSWINCE)
507 InitializeCriticalSection(&GC_write_cs);
509 # if (!defined(SMALL_CONFIG))
510 if (0 != GETENV("GC_PRINT_STATS")) {
513 if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
514 GC_print_stats = VERBOSE;
516 # if defined(UNIX_LIKE)
518 char * file_name = GETENV("GC_LOG_FILE");
519 if (0 != file_name) {
520 int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666);
522 GC_log_printf("Failed to open %s as log file\n", file_name);
530 # ifndef NO_DEBUGGING
531 if (0 != GETENV("GC_DUMP_REGULARLY")) {
532 GC_dump_regularly = 1;
535 # ifdef KEEP_BACK_PTRS
537 char * backtraces_string = GETENV("GC_BACKTRACES");
538 if (0 != backtraces_string) {
539 GC_backtraces = atol(backtraces_string);
540 if (backtraces_string[0] == '\0') GC_backtraces = 1;
544 if (0 != GETENV("GC_FIND_LEAK")) {
546 atexit(GC_exit_check);
548 if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
549 GC_all_interior_pointers = 1;
551 if (0 != GETENV("GC_DONT_GC")) {
554 if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
555 GC_print_back_height = 1;
557 if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
558 GC_large_alloc_warn_interval = LONG_MAX;
561 char * addr_string = GETENV("GC_TRACE");
562 if (0 != addr_string) {
563 # ifndef ENABLE_TRACE
564 WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
567 long long addr = strtoull(addr_string, NULL, 16);
569 long addr = strtoul(addr_string, NULL, 16);
572 WARN("Unlikely trace address: 0x%lx\n", (GC_word)addr);
573 GC_trace_addr = (ptr_t)addr;
578 char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
579 if (0 != time_limit_string) {
580 long time_limit = atol(time_limit_string);
581 if (time_limit < 5) {
582 WARN("GC_PAUSE_TIME_TARGET environment variable value too small "
583 "or bad syntax: Ignoring\n", 0);
585 GC_time_limit = time_limit;
590 char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
591 if (0 != interval_string) {
592 long interval = atol(interval_string);
594 WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
595 "bad value: Ignoring\n", 0);
597 GC_large_alloc_warn_interval = interval;
601 maybe_install_looping_handler();
602 /* Adjust normal object descriptor for extra allocation. */
603 if (ALIGNMENT > GC_DS_TAGS && EXTRA_BYTES != 0) {
604 GC_obj_kinds[NORMAL].ok_descriptor = ((word)(-ALIGNMENT) | GC_DS_LENGTH);
607 GC_exclude_static_roots(beginGC_arrays, endGC_arrays);
608 GC_exclude_static_roots(beginGC_obj_kinds, endGC_obj_kinds);
609 # ifdef SEPARATE_GLOBALS
610 GC_exclude_static_roots(beginGC_objfreelist, endGC_objfreelist);
611 GC_exclude_static_roots(beginGC_aobjfreelist, endGC_aobjfreelist);
616 # if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
617 WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
618 /* If thread stacks are cached, they tend to be scanned in */
619 /* entirety as part of the root set. This wil grow them to */
620 /* maximum size, and is generally not desirable. */
622 # if defined(SEARCH_FOR_DATA_START)
623 GC_init_linux_data_start();
625 # if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
626 GC_init_netbsd_elf();
628 # if !defined(THREADS) || defined(GC_PTHREADS) || defined(GC_WIN32_THREADS) \
629 || defined(GC_SOLARIS_THREADS)
630 if (GC_stackbottom == 0) {
631 GC_stackbottom = GC_get_main_stack_base();
632 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
633 GC_register_stackbottom = GC_get_register_stack_base();
636 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
637 if (GC_register_stackbottom == 0) {
638 WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
639 /* The following may fail, since we may rely on */
640 /* alignment properties that may not hold with a user set */
641 /* GC_stackbottom. */
642 GC_register_stackbottom = GC_get_register_stack_base();
647 /* Ignore gcc -Wall warnings on the following. */
648 GC_STATIC_ASSERT(sizeof (ptr_t) == sizeof(word));
649 GC_STATIC_ASSERT(sizeof (signed_word) == sizeof(word));
650 GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
652 # ifdef STACK_GROWS_DOWN
653 GC_ASSERT((word)(&dummy) <= (word)GC_stackbottom);
655 GC_ASSERT((word)(&dummy) >= (word)GC_stackbottom);
658 # if !defined(_AUX_SOURCE) || defined(__GNUC__)
659 GC_ASSERT((word)(-1) > (word)0);
660 /* word should be unsigned */
662 GC_ASSERT((ptr_t)(word)(-1) > (ptr_t)0);
663 /* Ptr_t comparisons should behave as unsigned comparisons. */
664 GC_ASSERT((signed_word)(-1) < (signed_word)0);
665 # if !defined(SMALL_CONFIG)
666 if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
667 /* This used to test for !GC_no_win32_dlls. Why? */
669 /* For GWW_MPROTECT on Win32, this needs to happen before any */
670 /* heap memory is allocated. */
672 GC_ASSERT(GC_bytes_allocd == 0)
673 GC_incremental = TRUE;
675 # endif /* !SMALL_CONFIG */
677 /* Add initial guess of root sets. Do this first, since sbrk(0) */
679 if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
684 char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
685 if (sz_str != NULL) {
686 initial_heap_sz = atoi(sz_str);
687 if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
688 WARN("Bad initial heap size %s - ignoring it.\n",
691 initial_heap_sz = divHBLKSZ(initial_heap_sz);
695 char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
696 if (sz_str != NULL) {
697 word max_heap_sz = (word)atol(sz_str);
698 if (max_heap_sz < initial_heap_sz * HBLKSIZE) {
699 WARN("Bad maximum heap size %s - ignoring it.\n",
702 if (0 == GC_max_retries) GC_max_retries = 2;
703 GC_set_max_heap_size(max_heap_sz);
706 if (!GC_expand_hp_inner(initial_heap_sz)) {
707 GC_err_printf("Can't start up: not enough memory\n");
710 GC_initialize_offsets();
711 GC_register_displacement_inner(0L);
712 # if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
713 if (!GC_all_interior_pointers) {
714 /* TLS ABI uses pointer-sized offsets for dtv. */
715 GC_register_displacement_inner(sizeof(void *));
720 if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
722 ABORT("Can't lock load state\n");
723 } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
724 ABORT("Can't unlock load state\n");
729 GC_is_initialized = TRUE;
730 # if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
734 /* Get black list set up and/or incremental GC started */
735 if (!GC_dont_precollect || GC_incremental) GC_gcollect_inner();
736 # ifdef STUBBORN_ALLOC
739 /* Convince lint that some things are used */
742 extern char * GC_copyright[];
743 extern int GC_read();
744 extern void GC_register_finalizer_no_order();
746 GC_noop(GC_copyright, GC_find_header,
747 GC_push_one, GC_call_with_alloc_lock, GC_read,
749 # ifndef NO_DEBUGGING
752 GC_register_finalizer_no_order);
756 /* The rest of this again assumes we don't really hold */
757 /* the allocation lock. */
758 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
759 /* Make sure marker threads and started and thread local */
760 /* allocation is initialized, in case we didn't get */
761 /* called from GC_init_parallel(); */
765 # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
767 # if defined(DYNAMIC_LOADING) && defined(DARWIN)
769 /* This must be called WITHOUT the allocation lock held
770 and before any threads are created */
771 extern void GC_init_dyld();
777 void GC_enable_incremental(void)
779 # if !defined(SMALL_CONFIG) && !defined(KEEP_BACK_PTRS)
780 /* If we are keeping back pointers, the GC itself dirties all */
781 /* pages on which objects have been marked, making */
782 /* incremental GC pointless. */
787 if (GC_incremental) goto out;
789 /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
790 maybe_install_looping_handler(); /* Before write fault handler! */
791 GC_incremental = TRUE;
792 if (!GC_is_initialized) {
797 if (!GC_dirty_maintained) goto out;
799 /* Can't easily do it. */
803 if (GC_bytes_allocd > 0) {
804 /* There may be unmarked reachable objects */
806 } /* else we're OK in assuming everything's */
807 /* clean since nothing can point to an */
808 /* unmarked object. */
821 #if defined(MSWIN32) || defined(MSWINCE)
822 # if defined(_MSC_VER) && defined(_DEBUG)
825 # ifdef OLD_WIN32_LOG_FILE
826 # define LOG_FILE _T("gc.log")
829 HANDLE GC_stdout = 0;
833 if (GC_is_initialized) {
834 DeleteCriticalSection(&GC_write_cs);
839 # define GC_need_to_lock 0 /* Not defined without threads */
841 int GC_write(const char *buf, size_t len)
847 if (GC_need_to_lock) EnterCriticalSection(&GC_write_cs);
848 if (GC_stdout == INVALID_HANDLE_VALUE) {
849 if (GC_need_to_lock) LeaveCriticalSection(&GC_write_cs);
851 } else if (GC_stdout == 0) {
852 char * file_name = GETENV("GC_LOG_FILE");
853 char logPath[_MAX_PATH + 5];
855 if (0 == file_name) {
856 # ifdef OLD_WIN32_LOG_FILE
857 strcpy(logPath, LOG_FILE);
859 GetModuleFileName(NULL, logPath, _MAX_PATH);
860 strcat(logPath, ".log");
864 GC_stdout = CreateFile(logPath, GENERIC_WRITE,
866 NULL, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH,
868 if (GC_stdout == INVALID_HANDLE_VALUE)
869 ABORT("Open of log file failed");
871 tmp = WriteFile(GC_stdout, buf, (DWORD)len, &written, NULL);
874 # if defined(_MSC_VER) && defined(_DEBUG)
875 _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
877 if (GC_need_to_lock) LeaveCriticalSection(&GC_write_cs);
878 return tmp ? (int)written : -1;
880 # undef GC_need_to_lock
884 #if defined(OS2) || defined(MACOS)
885 FILE * GC_stdout = NULL;
886 FILE * GC_stderr = NULL;
887 FILE * GC_log = NULL;
888 int GC_tmp; /* Should really be local ... */
892 if (GC_stdout == NULL) {
895 if (GC_stderr == NULL) {
898 if (GC_log == NULL) {
904 #if !defined(OS2) && !defined(MACOS) && !defined(MSWIN32) && !defined(MSWINCE)
913 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(OS2) \
914 && !defined(MACOS) && !defined(ECOS) && !defined(NOSYS)
915 int GC_write(fd, buf, len)
920 register int bytes_written = 0;
923 while (bytes_written < len) {
924 # ifdef GC_SOLARIS_THREADS
925 result = syscall(SYS_write, fd, buf + bytes_written,
926 len - bytes_written);
928 result = write(fd, buf + bytes_written, len - bytes_written);
930 if (-1 == result) return(result);
931 bytes_written += result;
933 return(bytes_written);
938 int GC_write(fd, buf, len)
940 _Jv_diag_write (buf, len);
946 int GC_write(fd, buf, len)
954 #if defined(MSWIN32) || defined(MSWINCE)
955 /* FIXME: This is pretty ugly ... */
956 # define WRITE(f, buf, len) GC_write(buf, len)
958 # if defined(OS2) || defined(MACOS)
959 # define WRITE(f, buf, len) (GC_set_files(), \
960 GC_tmp = fwrite((buf), 1, (len), (f)), \
963 # define WRITE(f, buf, len) GC_write((f), (buf), (len))
969 # define vsnprintf _vsnprintf
971 /* A version of printf that is unlikely to call malloc, and is thus safer */
972 /* to call from the collector in case malloc has been bound to GC_malloc. */
973 /* Floating point arguments ans formats should be avoided, since fp */
974 /* conversion is more likely to allocate. */
975 /* Assumes that no more than BUFSZ-1 characters are written at once. */
976 void GC_printf(const char *format, ...)
981 va_start(args, format);
982 if (GC_quiet) return;
984 (void) vsnprintf(buf, BUFSZ, format, args);
986 if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
987 if (WRITE(GC_stdout, buf, strlen(buf)) < 0) ABORT("write to stdout failed");
990 void GC_err_printf(const char *format, ...)
995 va_start(args, format);
997 (void) vsnprintf(buf, BUFSZ, format, args);
999 if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1000 if (WRITE(GC_stderr, buf, strlen(buf)) < 0) ABORT("write to stderr failed");
1003 void GC_log_printf(const char *format, ...)
1008 va_start(args, format);
1010 (void) vsnprintf(buf, BUFSZ, format, args);
1012 if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1013 if (WRITE(GC_log, buf, strlen(buf)) < 0) ABORT("write to log failed");
1016 void GC_err_puts(const char *s)
1018 if (WRITE(GC_stderr, s, strlen(s)) < 0) ABORT("write to stderr failed");
1021 #if defined(LINUX) && !defined(SMALL_CONFIG)
1022 void GC_err_write(buf, len)
1026 if (WRITE(GC_stderr, buf, len) < 0) ABORT("write to stderr failed");
1030 void GC_default_warn_proc(char *msg, GC_word arg)
1032 GC_err_printf(msg, arg);
1035 GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1037 GC_warn_proc GC_set_warn_proc(GC_warn_proc p)
1039 GC_warn_proc result;
1041 # ifdef GC_WIN32_THREADS
1042 GC_ASSERT(GC_is_initialized);
1045 result = GC_current_warn_proc;
1046 GC_current_warn_proc = p;
1051 GC_word GC_set_free_space_divisor (GC_word value)
1053 GC_word old = GC_free_space_divisor;
1054 GC_free_space_divisor = value;
1059 void GC_abort(const char *msg)
1061 # if defined(MSWIN32)
1062 (void) MessageBoxA(NULL, msg, "Fatal error in gc", MB_ICONERROR|MB_OK);
1064 GC_err_printf("%s\n", msg);
1066 if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1067 /* In many cases it's easier to debug a running process. */
1068 /* It's arguably nicer to sleep, but that makes it harder */
1069 /* to look at the thread if the debugger doesn't know much */
1070 /* about threads. */
1073 # if defined(MSWIN32) || defined(MSWINCE)
1095 /* Helper procedures for new kind creation. */
1096 void ** GC_new_free_list_inner()
1098 void *result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1)*sizeof(ptr_t),
1100 if (result == 0) ABORT("Failed to allocate freelist for new kind");
1101 BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
1105 void ** GC_new_free_list()
1109 result = GC_new_free_list_inner();
1114 unsigned GC_new_kind_inner(void **fl, GC_word descr, int adjust, int clear)
1116 unsigned result = GC_n_kinds++;
1118 if (GC_n_kinds > MAXOBJKINDS) ABORT("Too many kinds");
1119 GC_obj_kinds[result].ok_freelist = fl;
1120 GC_obj_kinds[result].ok_reclaim_list = 0;
1121 GC_obj_kinds[result].ok_descriptor = descr;
1122 GC_obj_kinds[result].ok_relocate_descr = adjust;
1123 GC_obj_kinds[result].ok_init = clear;
1127 unsigned GC_new_kind(void **fl, GC_word descr, int adjust, int clear)
1131 result = GC_new_kind_inner(fl, descr, adjust, clear);
1136 unsigned GC_new_proc_inner(GC_mark_proc proc)
1138 unsigned result = GC_n_mark_procs++;
1140 if (GC_n_mark_procs > MAX_MARK_PROCS) ABORT("Too many mark procedures");
1141 GC_mark_procs[result] = proc;
1145 unsigned GC_new_proc(GC_mark_proc proc)
1149 result = GC_new_proc_inner(proc);
1154 GC_API void * GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
1157 struct GC_stack_base base;
1159 base.mem_base = (void *)&dummy;
1161 base.reg_base = (void *)GC_save_regs_in_stack();
1162 /* Unnecessarily flushes register stack, */
1163 /* but that probably doesn't hurt. */
1165 return fn(&base, arg);
1168 #if !defined(NO_DEBUGGING)
1172 GC_printf("***Static roots:\n");
1173 GC_print_static_roots();
1174 GC_printf("\n***Heap sections:\n");
1175 GC_print_heap_sects();
1176 GC_printf("\n***Free blocks:\n");
1177 GC_print_hblkfreelist();
1178 GC_printf("\n***Blocks in use:\n");
1179 GC_print_block_list();
1180 GC_printf("\n***Finalization statistics:\n");
1181 GC_print_finalization_stats();
1184 #endif /* NO_DEBUGGING */