2009-11-01 Zoltan Varga <vargaz@gmail.com>
[mono-project.git] / libgc / misc.c
blob22fc564c89518bc08b2d1f19b695beac1c048e14
1 /*
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 */
18 #include <stdio.h>
19 #include <limits.h>
20 #ifndef _WIN32_WCE
21 #include <signal.h>
22 #endif
24 #define I_HIDE_POINTERS /* To make GC_call_with_alloc_lock visible */
25 #include "private/gc_pmark.h"
27 #ifdef GC_SOLARIS_THREADS
28 # include <sys/syscall.h>
29 #endif
30 #if defined(MSWIN32) || defined(MSWINCE)
31 # define WIN32_LEAN_AND_MEAN
32 # define NOSERVICE
33 # include <windows.h>
34 # include <tchar.h>
35 #endif
37 # ifdef THREADS
38 # ifdef PCR
39 # include "il/PCR_IL.h"
40 PCR_Th_ML GC_allocate_ml;
41 # else
42 # ifdef SRC_M3
43 /* Critical section counter is defined in the M3 runtime */
44 /* That's all we use. */
45 # else
46 # ifdef GC_SOLARIS_THREADS
47 mutex_t GC_allocate_ml; /* Implicitly initialized. */
48 # else
49 # if defined(GC_WIN32_THREADS)
50 # if defined(GC_PTHREADS)
51 pthread_mutex_t GC_allocate_ml = PTHREAD_MUTEX_INITIALIZER;
52 # elif defined(GC_DLL)
53 __declspec(dllexport) CRITICAL_SECTION GC_allocate_ml;
54 # else
55 CRITICAL_SECTION GC_allocate_ml;
56 # endif
57 # else
58 # if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS)
59 # if defined(USE_SPIN_LOCK)
60 pthread_t GC_lock_holder = NO_THREAD;
61 # else
62 pthread_mutex_t GC_allocate_ml = PTHREAD_MUTEX_INITIALIZER;
63 pthread_t GC_lock_holder = NO_THREAD;
64 /* Used only for assertions, and to prevent */
65 /* recursive reentry in the system call wrapper. */
66 # endif
67 # else
68 --> declare allocator lock here
69 # endif
70 # endif
71 # endif
72 # endif
73 # endif
74 # endif
76 #if defined(NOSYS) || defined(ECOS)
77 #undef STACKBASE
78 #endif
80 /* Dont unnecessarily call GC_register_main_static_data() in case */
81 /* dyn_load.c isn't linked in. */
82 #ifdef DYNAMIC_LOADING
83 # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
84 #elif defined(GC_DONT_REGISTER_MAIN_STATIC_DATA)
85 # define GC_REGISTER_MAIN_STATIC_DATA() FALSE
86 #else
87 # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
88 #endif
90 GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
93 GC_bool GC_debugging_started = FALSE;
94 /* defined here so we don't have to load debug_malloc.o */
96 void (*GC_check_heap) GC_PROTO((void)) = (void (*) GC_PROTO((void)))0;
97 void (*GC_print_all_smashed) GC_PROTO((void)) = (void (*) GC_PROTO((void)))0;
99 void (*GC_start_call_back) GC_PROTO((void)) = (void (*) GC_PROTO((void)))0;
101 ptr_t GC_stackbottom = 0;
103 #ifdef IA64
104 ptr_t GC_register_stackbottom = 0;
105 #endif
107 GC_bool GC_dont_gc = 0;
109 GC_bool GC_dont_precollect = 0;
111 GC_bool GC_quiet = 0;
113 GC_bool GC_print_stats = 0;
115 GC_bool GC_print_back_height = 0;
117 #ifndef NO_DEBUGGING
118 GC_bool GC_dump_regularly = 0; /* Generate regular debugging dumps. */
119 #endif
121 #ifdef KEEP_BACK_PTRS
122 long GC_backtraces = 0; /* Number of random backtraces to */
123 /* generate for each GC. */
124 #endif
126 #ifdef FIND_LEAK
127 int GC_find_leak = 1;
128 #else
129 int GC_find_leak = 0;
130 #endif
132 #ifdef ALL_INTERIOR_POINTERS
133 int GC_all_interior_pointers = 1;
134 #else
135 int GC_all_interior_pointers = 0;
136 #endif
138 long GC_large_alloc_warn_interval = 5;
139 /* Interval between unsuppressed warnings. */
141 long GC_large_alloc_warn_suppressed = 0;
142 /* Number of warnings suppressed so far. */
144 /*ARGSUSED*/
145 GC_PTR GC_default_oom_fn GC_PROTO((size_t bytes_requested))
147 return(0);
150 GC_PTR (*GC_oom_fn) GC_PROTO((size_t bytes_requested)) = GC_default_oom_fn;
152 extern signed_word GC_mem_found;
154 void * GC_project2(arg1, arg2)
155 void *arg1;
156 void *arg2;
158 return arg2;
161 # ifdef MERGE_SIZES
162 /* Set things up so that GC_size_map[i] >= words(i), */
163 /* but not too much bigger */
164 /* and so that size_map contains relatively few distinct entries */
165 /* This is stolen from Russ Atkinson's Cedar quantization */
166 /* alogrithm (but we precompute it). */
169 void GC_init_size_map()
171 register unsigned i;
173 /* Map size 0 to something bigger. */
174 /* This avoids problems at lower levels. */
175 /* One word objects don't have to be 2 word aligned, */
176 /* unless we're using mark bytes. */
177 for (i = 0; i < sizeof(word); i++) {
178 GC_size_map[i] = MIN_WORDS;
180 # if MIN_WORDS > 1
181 GC_size_map[sizeof(word)] = MIN_WORDS;
182 # else
183 GC_size_map[sizeof(word)] = ROUNDED_UP_WORDS(sizeof(word));
184 # endif
185 for (i = sizeof(word) + 1; i <= 8 * sizeof(word); i++) {
186 GC_size_map[i] = ALIGNED_WORDS(i);
188 for (i = 8*sizeof(word) + 1; i <= 16 * sizeof(word); i++) {
189 GC_size_map[i] = (ROUNDED_UP_WORDS(i) + 1) & (~1);
191 # ifdef GC_GCJ_SUPPORT
192 /* Make all sizes up to 32 words predictable, so that a */
193 /* compiler can statically perform the same computation, */
194 /* or at least a computation that results in similar size */
195 /* classes. */
196 for (i = 16*sizeof(word) + 1; i <= 32 * sizeof(word); i++) {
197 GC_size_map[i] = (ROUNDED_UP_WORDS(i) + 3) & (~3);
199 # endif
200 /* We leave the rest of the array to be filled in on demand. */
203 /* Fill in additional entries in GC_size_map, including the ith one */
204 /* We assume the ith entry is currently 0. */
205 /* Note that a filled in section of the array ending at n always */
206 /* has length at least n/4. */
207 void GC_extend_size_map(i)
208 word i;
210 word orig_word_sz = ROUNDED_UP_WORDS(i);
211 word word_sz = orig_word_sz;
212 register word byte_sz = WORDS_TO_BYTES(word_sz);
213 /* The size we try to preserve. */
214 /* Close to to i, unless this would */
215 /* introduce too many distinct sizes. */
216 word smaller_than_i = byte_sz - (byte_sz >> 3);
217 word much_smaller_than_i = byte_sz - (byte_sz >> 2);
218 register word low_limit; /* The lowest indexed entry we */
219 /* initialize. */
220 register word j;
222 if (GC_size_map[smaller_than_i] == 0) {
223 low_limit = much_smaller_than_i;
224 while (GC_size_map[low_limit] != 0) low_limit++;
225 } else {
226 low_limit = smaller_than_i + 1;
227 while (GC_size_map[low_limit] != 0) low_limit++;
228 word_sz = ROUNDED_UP_WORDS(low_limit);
229 word_sz += word_sz >> 3;
230 if (word_sz < orig_word_sz) word_sz = orig_word_sz;
232 # ifdef ALIGN_DOUBLE
233 word_sz += 1;
234 word_sz &= ~1;
235 # endif
236 if (word_sz > MAXOBJSZ) {
237 word_sz = MAXOBJSZ;
239 /* If we can fit the same number of larger objects in a block, */
240 /* do so. */
242 size_t number_of_objs = BODY_SZ/word_sz;
243 word_sz = BODY_SZ/number_of_objs;
244 # ifdef ALIGN_DOUBLE
245 word_sz &= ~1;
246 # endif
248 byte_sz = WORDS_TO_BYTES(word_sz);
249 if (GC_all_interior_pointers) {
250 /* We need one extra byte; don't fill in GC_size_map[byte_sz] */
251 byte_sz -= EXTRA_BYTES;
254 for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = word_sz;
256 # endif
260 * The following is a gross hack to deal with a problem that can occur
261 * on machines that are sloppy about stack frame sizes, notably SPARC.
262 * Bogus pointers may be written to the stack and not cleared for
263 * a LONG time, because they always fall into holes in stack frames
264 * that are not written. We partially address this by clearing
265 * sections of the stack whenever we get control.
267 word GC_stack_last_cleared = 0; /* GC_no when we last did this */
268 # ifdef THREADS
269 # define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */
270 # define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */
271 # endif
272 # define CLEAR_SIZE 213 /* Granularity for GC_clear_stack_inner */
273 # define DEGRADE_RATE 50
275 word GC_min_sp; /* Coolest stack pointer value from which we've */
276 /* already cleared the stack. */
278 word GC_high_water;
279 /* "hottest" stack pointer value we have seen */
280 /* recently. Degrades over time. */
282 word GC_words_allocd_at_reset;
284 #if defined(ASM_CLEAR_CODE)
285 extern ptr_t GC_clear_stack_inner();
286 #else
287 /* Clear the stack up to about limit. Return arg. */
288 /*ARGSUSED*/
289 ptr_t GC_clear_stack_inner(arg, limit)
290 ptr_t arg;
291 word limit;
293 word dummy[CLEAR_SIZE];
295 BZERO(dummy, CLEAR_SIZE*sizeof(word));
296 if ((word)(dummy) COOLER_THAN limit) {
297 (void) GC_clear_stack_inner(arg, limit);
299 /* Make sure the recursive call is not a tail call, and the bzero */
300 /* call is not recognized as dead code. */
301 GC_noop1((word)dummy);
302 return(arg);
304 #endif
306 /* Clear some of the inaccessible part of the stack. Returns its */
307 /* argument, so it can be used in a tail call position, hence clearing */
308 /* another frame. */
309 ptr_t GC_clear_stack(arg)
310 ptr_t arg;
312 register word sp = (word)GC_approx_sp(); /* Hotter than actual sp */
313 # ifdef THREADS
314 word dummy[SMALL_CLEAR_SIZE];
315 static unsigned random_no = 0;
316 /* Should be more random than it is ... */
317 /* Used to occasionally clear a bigger */
318 /* chunk. */
319 # endif
320 register word limit;
322 # define SLOP 400
323 /* Extra bytes we clear every time. This clears our own */
324 /* activation record, and should cause more frequent */
325 /* clearing near the cold end of the stack, a good thing. */
326 # define GC_SLOP 4000
327 /* We make GC_high_water this much hotter than we really saw */
328 /* saw it, to cover for GC noise etc. above our current frame. */
329 # define CLEAR_THRESHOLD 100000
330 /* We restart the clearing process after this many bytes of */
331 /* allocation. Otherwise very heavily recursive programs */
332 /* with sparse stacks may result in heaps that grow almost */
333 /* without bounds. As the heap gets larger, collection */
334 /* frequency decreases, thus clearing frequency would decrease, */
335 /* thus more junk remains accessible, thus the heap gets */
336 /* larger ... */
337 # ifdef THREADS
338 if (++random_no % 13 == 0) {
339 limit = sp;
340 MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
341 limit &= ~0xf; /* Make it sufficiently aligned for assembly */
342 /* implementations of GC_clear_stack_inner. */
343 return GC_clear_stack_inner(arg, limit);
344 } else {
345 BZERO(dummy, SMALL_CLEAR_SIZE*sizeof(word));
346 return arg;
348 # else
349 if (GC_gc_no > GC_stack_last_cleared) {
350 /* Start things over, so we clear the entire stack again */
351 if (GC_stack_last_cleared == 0) GC_high_water = (word) GC_stackbottom;
352 GC_min_sp = GC_high_water;
353 GC_stack_last_cleared = GC_gc_no;
354 GC_words_allocd_at_reset = GC_words_allocd;
356 /* Adjust GC_high_water */
357 MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
358 if (sp HOTTER_THAN GC_high_water) {
359 GC_high_water = sp;
361 MAKE_HOTTER(GC_high_water, GC_SLOP);
362 limit = GC_min_sp;
363 MAKE_HOTTER(limit, SLOP);
364 if (sp COOLER_THAN limit) {
365 limit &= ~0xf; /* Make it sufficiently aligned for assembly */
366 /* implementations of GC_clear_stack_inner. */
367 GC_min_sp = sp;
368 return(GC_clear_stack_inner(arg, limit));
369 } else if (WORDS_TO_BYTES(GC_words_allocd - GC_words_allocd_at_reset)
370 > CLEAR_THRESHOLD) {
371 /* Restart clearing process, but limit how much clearing we do. */
372 GC_min_sp = sp;
373 MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
374 if (GC_min_sp HOTTER_THAN GC_high_water) GC_min_sp = GC_high_water;
375 GC_words_allocd_at_reset = GC_words_allocd;
377 return(arg);
378 # endif
382 /* Return a pointer to the base address of p, given a pointer to a */
383 /* an address within an object. Return 0 o.w. */
384 # ifdef __STDC__
385 GC_PTR GC_base(GC_PTR p)
386 # else
387 GC_PTR GC_base(p)
388 GC_PTR p;
389 # endif
391 register word r;
392 register struct hblk *h;
393 register bottom_index *bi;
394 register hdr *candidate_hdr;
395 register word limit;
397 r = (word)p;
398 if (!GC_is_initialized) return 0;
399 h = HBLKPTR(r);
400 GET_BI(r, bi);
401 candidate_hdr = HDR_FROM_BI(bi, r);
402 if (candidate_hdr == 0) return(0);
403 /* If it's a pointer to the middle of a large object, move it */
404 /* to the beginning. */
405 while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
406 h = FORWARDED_ADDR(h,candidate_hdr);
407 r = (word)h;
408 candidate_hdr = HDR(h);
410 if (candidate_hdr -> hb_map == GC_invalid_map) return(0);
411 /* Make sure r points to the beginning of the object */
412 r &= ~(WORDS_TO_BYTES(1) - 1);
414 register int offset = HBLKDISPL(r);
415 register signed_word sz = candidate_hdr -> hb_sz;
416 register signed_word map_entry;
418 map_entry = MAP_ENTRY((candidate_hdr -> hb_map), offset);
419 if (map_entry > CPP_MAX_OFFSET) {
420 map_entry = (signed_word)(BYTES_TO_WORDS(offset)) % sz;
422 r -= WORDS_TO_BYTES(map_entry);
423 limit = r + WORDS_TO_BYTES(sz);
424 if (limit > (word)(h + 1)
425 && sz <= BYTES_TO_WORDS(HBLKSIZE)) {
426 return(0);
428 if ((word)p >= limit) return(0);
430 return((GC_PTR)r);
434 /* Return the size of an object, given a pointer to its base. */
435 /* (For small obects this also happens to work from interior pointers, */
436 /* but that shouldn't be relied upon.) */
437 # ifdef __STDC__
438 size_t GC_size(GC_PTR p)
439 # else
440 size_t GC_size(p)
441 GC_PTR p;
442 # endif
444 register int sz;
445 register hdr * hhdr = HDR(p);
447 sz = WORDS_TO_BYTES(hhdr -> hb_sz);
448 return(sz);
451 size_t GC_get_heap_size GC_PROTO(())
453 return ((size_t) GC_heapsize);
456 size_t GC_get_free_bytes GC_PROTO(())
458 return ((size_t) GC_large_free_bytes);
461 size_t GC_get_bytes_since_gc GC_PROTO(())
463 return ((size_t) WORDS_TO_BYTES(GC_words_allocd));
466 size_t GC_get_total_bytes GC_PROTO(())
468 return ((size_t) WORDS_TO_BYTES(GC_words_allocd+GC_words_allocd_before_gc));
471 int GC_get_suspend_signal GC_PROTO(())
473 #if defined(SIG_SUSPEND) && defined(GC_PTHREADS) && !defined(GC_MACOSX_THREADS)
474 return SIG_SUSPEND;
475 #else
476 return -1;
477 #endif
480 GC_bool GC_is_initialized = FALSE;
482 void GC_init()
484 DCL_LOCK_STATE;
486 DISABLE_SIGNALS();
488 #if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
489 if (!GC_is_initialized) {
490 BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL;
491 HMODULE hK32 = GetModuleHandle(_T("kernel32.dll"));
492 if (hK32)
493 pfn = GetProcAddress(hK32,
494 "InitializeCriticalSectionAndSpinCount");
495 if (pfn)
496 pfn(&GC_allocate_ml, 4000);
497 else
498 InitializeCriticalSection (&GC_allocate_ml);
500 #endif /* MSWIN32 */
502 LOCK();
503 GC_init_inner();
504 UNLOCK();
505 ENABLE_SIGNALS();
507 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
508 /* Make sure marker threads and started and thread local */
509 /* allocation is initialized, in case we didn't get */
510 /* called from GC_init_parallel(); */
512 extern void GC_init_parallel(void);
513 GC_init_parallel();
515 # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
517 # if defined(DYNAMIC_LOADING) && defined(DARWIN)
519 /* This must be called WITHOUT the allocation lock held
520 and before any threads are created */
521 extern void GC_init_dyld();
522 GC_init_dyld();
524 # endif
527 #if defined(MSWIN32) || defined(MSWINCE)
528 CRITICAL_SECTION GC_write_cs;
529 #endif
531 #ifdef MSWIN32
532 extern void GC_init_win32 GC_PROTO((void));
533 #endif
535 extern void GC_setpagesize();
538 #ifdef MSWIN32
539 extern GC_bool GC_no_win32_dlls;
540 #else
541 # define GC_no_win32_dlls FALSE
542 #endif
544 void GC_exit_check GC_PROTO((void))
546 GC_gcollect();
549 #ifdef SEARCH_FOR_DATA_START
550 extern void GC_init_linux_data_start GC_PROTO((void));
551 #endif
553 #ifdef UNIX_LIKE
555 extern void GC_set_and_save_fault_handler GC_PROTO((void (*handler)(int)));
557 static void looping_handler(sig)
558 int sig;
560 GC_err_printf1("Caught signal %d: looping in handler\n", sig);
561 for(;;);
564 static GC_bool installed_looping_handler = FALSE;
566 static void maybe_install_looping_handler()
568 /* Install looping handler before the write fault handler, so we */
569 /* handle write faults correctly. */
570 if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
571 GC_set_and_save_fault_handler(looping_handler);
572 installed_looping_handler = TRUE;
576 #else /* !UNIX_LIKE */
578 # define maybe_install_looping_handler()
580 #endif
582 void GC_init_inner()
584 # if !defined(THREADS) && defined(GC_ASSERTIONS)
585 word dummy;
586 # endif
587 word initial_heap_sz = (word)MINHINCR;
589 if (GC_is_initialized) return;
590 # ifdef PRINTSTATS
591 GC_print_stats = 1;
592 # endif
593 # if defined(MSWIN32) || defined(MSWINCE)
594 InitializeCriticalSection(&GC_write_cs);
595 # endif
596 if (0 != GETENV("GC_PRINT_STATS")) {
597 GC_print_stats = 1;
599 # ifndef NO_DEBUGGING
600 if (0 != GETENV("GC_DUMP_REGULARLY")) {
601 GC_dump_regularly = 1;
603 # endif
604 # ifdef KEEP_BACK_PTRS
606 char * backtraces_string = GETENV("GC_BACKTRACES");
607 if (0 != backtraces_string) {
608 GC_backtraces = atol(backtraces_string);
609 if (backtraces_string[0] == '\0') GC_backtraces = 1;
612 # endif
613 if (0 != GETENV("GC_FIND_LEAK")) {
614 GC_find_leak = 1;
615 # ifdef __STDC__
616 atexit(GC_exit_check);
617 # endif
619 if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
620 GC_all_interior_pointers = 1;
622 if (0 != GETENV("GC_DONT_GC")) {
623 GC_dont_gc = 1;
625 if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
626 GC_print_back_height = 1;
628 if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
629 GC_large_alloc_warn_interval = LONG_MAX;
632 char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
633 if (0 != time_limit_string) {
634 long time_limit = atol(time_limit_string);
635 if (time_limit < 5) {
636 WARN("GC_PAUSE_TIME_TARGET environment variable value too small "
637 "or bad syntax: Ignoring\n", 0);
638 } else {
639 GC_time_limit = time_limit;
644 char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
645 if (0 != interval_string) {
646 long interval = atol(interval_string);
647 if (interval <= 0) {
648 WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
649 "bad value: Ignoring\n", 0);
650 } else {
651 GC_large_alloc_warn_interval = interval;
655 maybe_install_looping_handler();
656 /* Adjust normal object descriptor for extra allocation. */
657 if (ALIGNMENT > GC_DS_TAGS && EXTRA_BYTES != 0) {
658 GC_obj_kinds[NORMAL].ok_descriptor = ((word)(-ALIGNMENT) | GC_DS_LENGTH);
660 GC_setpagesize();
661 GC_exclude_static_roots(beginGC_arrays, endGC_arrays);
662 GC_exclude_static_roots(beginGC_obj_kinds, endGC_obj_kinds);
663 # ifdef SEPARATE_GLOBALS
664 GC_exclude_static_roots(beginGC_objfreelist, endGC_objfreelist);
665 GC_exclude_static_roots(beginGC_aobjfreelist, endGC_aobjfreelist);
666 # endif
667 # ifdef MSWIN32
668 GC_init_win32();
669 # endif
670 # if defined(SEARCH_FOR_DATA_START)
671 GC_init_linux_data_start();
672 # endif
673 # if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
674 GC_init_netbsd_elf();
675 # endif
676 # if defined(GC_PTHREADS) || defined(GC_SOLARIS_THREADS) \
677 || defined(GC_WIN32_THREADS)
678 GC_thr_init();
679 # endif
680 # ifdef GC_SOLARIS_THREADS
681 /* We need dirty bits in order to find live stack sections. */
682 GC_dirty_init();
683 # endif
684 # if !defined(THREADS) || defined(GC_PTHREADS) || defined(GC_WIN32_THREADS) \
685 || defined(GC_SOLARIS_THREADS)
686 if (GC_stackbottom == 0) {
687 GC_stackbottom = GC_get_stack_base();
688 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
689 GC_register_stackbottom = GC_get_register_stack_base();
690 # endif
691 } else {
692 # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
693 if (GC_register_stackbottom == 0) {
694 WARN("GC_register_stackbottom should be set with GC_stackbottom", 0);
695 /* The following may fail, since we may rely on */
696 /* alignment properties that may not hold with a user set */
697 /* GC_stackbottom. */
698 GC_register_stackbottom = GC_get_register_stack_base();
700 # endif
702 # endif
703 GC_STATIC_ASSERT(sizeof (ptr_t) == sizeof(word));
704 GC_STATIC_ASSERT(sizeof (signed_word) == sizeof(word));
705 GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
706 # ifndef THREADS
707 # if defined(STACK_GROWS_UP) && defined(STACK_GROWS_DOWN)
708 ABORT(
709 "Only one of STACK_GROWS_UP and STACK_GROWS_DOWN should be defd\n");
710 # endif
711 # if !defined(STACK_GROWS_UP) && !defined(STACK_GROWS_DOWN)
712 ABORT(
713 "One of STACK_GROWS_UP and STACK_GROWS_DOWN should be defd\n");
714 # endif
715 # ifdef STACK_GROWS_DOWN
716 GC_ASSERT((word)(&dummy) <= (word)GC_stackbottom);
717 # else
718 GC_ASSERT((word)(&dummy) >= (word)GC_stackbottom);
719 # endif
720 # endif
721 # if !defined(_AUX_SOURCE) || defined(__GNUC__)
722 GC_ASSERT((word)(-1) > (word)0);
723 /* word should be unsigned */
724 # endif
725 GC_ASSERT((signed_word)(-1) < (signed_word)0);
727 /* Add initial guess of root sets. Do this first, since sbrk(0) */
728 /* might be used. */
729 if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
730 GC_init_headers();
731 GC_bl_init();
732 GC_mark_init();
734 char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
735 if (sz_str != NULL) {
736 initial_heap_sz = atoi(sz_str);
737 if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
738 WARN("Bad initial heap size %s - ignoring it.\n",
739 sz_str);
741 initial_heap_sz = divHBLKSZ(initial_heap_sz);
745 char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
746 if (sz_str != NULL) {
747 word max_heap_sz = (word)atol(sz_str);
748 if (max_heap_sz < initial_heap_sz * HBLKSIZE) {
749 WARN("Bad maximum heap size %s - ignoring it.\n",
750 sz_str);
752 if (0 == GC_max_retries) GC_max_retries = 2;
753 GC_set_max_heap_size(max_heap_sz);
756 if (!GC_expand_hp_inner(initial_heap_sz)) {
757 GC_err_printf0("Can't start up: not enough memory\n");
758 EXIT();
760 /* Preallocate large object map. It's otherwise inconvenient to */
761 /* deal with failure. */
762 if (!GC_add_map_entry((word)0)) {
763 GC_err_printf0("Can't start up: not enough memory\n");
764 EXIT();
766 GC_register_displacement_inner(0L);
767 # ifdef MERGE_SIZES
768 GC_init_size_map();
769 # endif
770 # ifdef PCR
771 if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
772 != PCR_ERes_okay) {
773 ABORT("Can't lock load state\n");
774 } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
775 ABORT("Can't unlock load state\n");
777 PCR_IL_Unlock();
778 GC_pcr_install();
779 # endif
780 # if !defined(SMALL_CONFIG)
781 if (!GC_no_win32_dlls && 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
782 GC_ASSERT(!GC_incremental);
783 GC_setpagesize();
784 # ifndef GC_SOLARIS_THREADS
785 GC_dirty_init();
786 # endif
787 GC_ASSERT(GC_words_allocd == 0)
788 GC_incremental = TRUE;
790 # endif /* !SMALL_CONFIG */
791 COND_DUMP;
792 /* Get black list set up and/or incremental GC started */
793 if (!GC_dont_precollect || GC_incremental) GC_gcollect_inner();
794 GC_is_initialized = TRUE;
795 # ifdef STUBBORN_ALLOC
796 GC_stubborn_init();
797 # endif
798 /* Convince lint that some things are used */
799 # ifdef LINT
801 extern char * GC_copyright[];
802 extern int GC_read();
803 extern void GC_register_finalizer_no_order();
805 GC_noop(GC_copyright, GC_find_header,
806 GC_push_one, GC_call_with_alloc_lock, GC_read,
807 GC_dont_expand,
808 # ifndef NO_DEBUGGING
809 GC_dump,
810 # endif
811 GC_register_finalizer_no_order);
813 # endif
816 void GC_enable_incremental GC_PROTO(())
818 # if !defined(SMALL_CONFIG) && !defined(KEEP_BACK_PTRS)
819 /* If we are keeping back pointers, the GC itself dirties all */
820 /* pages on which objects have been marked, making */
821 /* incremental GC pointless. */
822 if (!GC_find_leak) {
823 DCL_LOCK_STATE;
825 DISABLE_SIGNALS();
826 LOCK();
827 if (GC_incremental) goto out;
828 GC_setpagesize();
829 if (GC_no_win32_dlls) goto out;
830 # ifndef GC_SOLARIS_THREADS
831 maybe_install_looping_handler(); /* Before write fault handler! */
832 GC_dirty_init();
833 # endif
834 if (!GC_is_initialized) {
835 GC_init_inner();
837 if (GC_incremental) goto out;
838 if (GC_dont_gc) {
839 /* Can't easily do it. */
840 UNLOCK();
841 ENABLE_SIGNALS();
842 return;
844 if (GC_words_allocd > 0) {
845 /* There may be unmarked reachable objects */
846 GC_gcollect_inner();
847 } /* else we're OK in assuming everything's */
848 /* clean since nothing can point to an */
849 /* unmarked object. */
850 GC_read_dirty();
851 GC_incremental = TRUE;
852 out:
853 UNLOCK();
854 ENABLE_SIGNALS();
856 # endif
860 #if defined(MSWIN32) || defined(MSWINCE)
861 # define LOG_FILE _T("gc.log")
863 HANDLE GC_stdout = 0;
865 void GC_deinit()
867 if (GC_is_initialized) {
868 DeleteCriticalSection(&GC_write_cs);
872 int GC_write(buf, len)
873 GC_CONST char * buf;
874 size_t len;
876 BOOL tmp;
877 DWORD written;
878 if (len == 0)
879 return 0;
880 EnterCriticalSection(&GC_write_cs);
881 if (GC_stdout == INVALID_HANDLE_VALUE) {
882 return -1;
883 } else if (GC_stdout == 0) {
884 GC_stdout = CreateFile(LOG_FILE, GENERIC_WRITE,
885 FILE_SHARE_READ | FILE_SHARE_WRITE,
886 NULL, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH,
887 NULL);
888 if (GC_stdout == INVALID_HANDLE_VALUE) ABORT("Open of log file failed");
890 tmp = WriteFile(GC_stdout, buf, len, &written, NULL);
891 if (!tmp)
892 DebugBreak();
893 LeaveCriticalSection(&GC_write_cs);
894 return tmp ? (int)written : -1;
897 #endif
899 #if defined(OS2) || defined(MACOS)
900 FILE * GC_stdout = NULL;
901 FILE * GC_stderr = NULL;
902 int GC_tmp; /* Should really be local ... */
904 void GC_set_files()
906 if (GC_stdout == NULL) {
907 GC_stdout = stdout;
909 if (GC_stderr == NULL) {
910 GC_stderr = stderr;
913 #endif
915 #if !defined(OS2) && !defined(MACOS) && !defined(MSWIN32) && !defined(MSWINCE)
916 int GC_stdout = 1;
917 int GC_stderr = 2;
918 # if !defined(AMIGA)
919 # include <unistd.h>
920 # endif
921 #endif
923 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(OS2) \
924 && !defined(MACOS) && !defined(ECOS) && !defined(NOSYS)
925 int GC_write(fd, buf, len)
926 int fd;
927 GC_CONST char *buf;
928 size_t len;
930 register int bytes_written = 0;
931 register int result;
933 while (bytes_written < len) {
934 # ifdef GC_SOLARIS_THREADS
935 result = syscall(SYS_write, fd, buf + bytes_written,
936 len - bytes_written);
937 # else
938 result = write(fd, buf + bytes_written, len - bytes_written);
939 # endif
940 if (-1 == result) return(result);
941 bytes_written += result;
943 return(bytes_written);
945 #endif /* UN*X */
947 #ifdef ECOS
948 int GC_write(fd, buf, len)
950 _Jv_diag_write (buf, len);
951 return len;
953 #endif
955 #ifdef NOSYS
956 int GC_write(fd, buf, len)
958 /* No writing. */
959 return len;
961 #endif
964 #if defined(MSWIN32) || defined(MSWINCE)
965 # define WRITE(f, buf, len) GC_write(buf, len)
966 #else
967 # if defined(OS2) || defined(MACOS)
968 # define WRITE(f, buf, len) (GC_set_files(), \
969 GC_tmp = fwrite((buf), 1, (len), (f)), \
970 fflush(f), GC_tmp)
971 # else
972 # define WRITE(f, buf, len) GC_write((f), (buf), (len))
973 # endif
974 #endif
976 /* A version of printf that is unlikely to call malloc, and is thus safer */
977 /* to call from the collector in case malloc has been bound to GC_malloc. */
978 /* Assumes that no more than 1023 characters are written at once. */
979 /* Assumes that all arguments have been converted to something of the */
980 /* same size as long, and that the format conversions expect something */
981 /* of that size. */
982 void GC_printf(format, a, b, c, d, e, f)
983 GC_CONST char * format;
984 long a, b, c, d, e, f;
986 char buf[1025];
988 if (GC_quiet) return;
989 buf[1024] = 0x15;
990 (void) sprintf(buf, format, a, b, c, d, e, f);
991 if (buf[1024] != 0x15) ABORT("GC_printf clobbered stack");
992 if (WRITE(GC_stdout, buf, strlen(buf)) < 0) ABORT("write to stdout failed");
995 void GC_err_printf(format, a, b, c, d, e, f)
996 GC_CONST char * format;
997 long a, b, c, d, e, f;
999 char buf[1025];
1001 buf[1024] = 0x15;
1002 (void) sprintf(buf, format, a, b, c, d, e, f);
1003 if (buf[1024] != 0x15) ABORT("GC_err_printf clobbered stack");
1004 if (WRITE(GC_stderr, buf, strlen(buf)) < 0) ABORT("write to stderr failed");
1007 void GC_err_puts(s)
1008 GC_CONST char *s;
1010 if (WRITE(GC_stderr, s, strlen(s)) < 0) ABORT("write to stderr failed");
1013 #if defined(LINUX) && !defined(SMALL_CONFIG)
1014 void GC_err_write(buf, len)
1015 GC_CONST char *buf;
1016 size_t len;
1018 if (WRITE(GC_stderr, buf, len) < 0) ABORT("write to stderr failed");
1020 #endif
1022 # if defined(__STDC__) || defined(__cplusplus)
1023 void GC_default_warn_proc(char *msg, GC_word arg)
1024 # else
1025 void GC_default_warn_proc(msg, arg)
1026 char *msg;
1027 GC_word arg;
1028 # endif
1030 GC_err_printf1(msg, (unsigned long)arg);
1033 GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1035 # if defined(__STDC__) || defined(__cplusplus)
1036 GC_warn_proc GC_set_warn_proc(GC_warn_proc p)
1037 # else
1038 GC_warn_proc GC_set_warn_proc(p)
1039 GC_warn_proc p;
1040 # endif
1042 GC_warn_proc result;
1044 # ifdef GC_WIN32_THREADS
1045 GC_ASSERT(GC_is_initialized);
1046 # endif
1047 LOCK();
1048 result = GC_current_warn_proc;
1049 GC_current_warn_proc = p;
1050 UNLOCK();
1051 return(result);
1054 # if defined(__STDC__) || defined(__cplusplus)
1055 GC_word GC_set_free_space_divisor (GC_word value)
1056 # else
1057 GC_word GC_set_free_space_divisor (value)
1058 GC_word value;
1059 # endif
1061 GC_word old = GC_free_space_divisor;
1062 GC_free_space_divisor = value;
1063 return old;
1066 #ifndef PCR
1067 void GC_abort(msg)
1068 GC_CONST char * msg;
1070 # if defined(MSWIN32)
1071 (void) MessageBoxA(NULL, msg, "Fatal error in gc", MB_ICONERROR|MB_OK);
1072 # else
1073 GC_err_printf1("%s\n", msg);
1074 # endif
1075 if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1076 /* In many cases it's easier to debug a running process. */
1077 /* It's arguably nicer to sleep, but that makes it harder */
1078 /* to look at the thread if the debugger doesn't know much */
1079 /* about threads. */
1080 for(;;) {}
1082 # if defined(MSWIN32) || defined(MSWINCE)
1083 DebugBreak();
1084 # else
1085 (void) abort();
1086 # endif
1088 #endif
1090 void GC_enable()
1092 LOCK();
1093 GC_dont_gc--;
1094 UNLOCK();
1097 void GC_disable()
1099 LOCK();
1100 GC_dont_gc++;
1101 UNLOCK();
1104 /* Helper procedures for new kind creation. */
1105 void ** GC_new_free_list_inner()
1107 void *result = GC_INTERNAL_MALLOC((MAXOBJSZ+1)*sizeof(ptr_t), PTRFREE);
1108 if (result == 0) ABORT("Failed to allocate freelist for new kind");
1109 BZERO(result, (MAXOBJSZ+1)*sizeof(ptr_t));
1110 return result;
1113 void ** GC_new_free_list()
1115 void *result;
1116 LOCK(); DISABLE_SIGNALS();
1117 result = GC_new_free_list_inner();
1118 UNLOCK(); ENABLE_SIGNALS();
1119 return result;
1122 int GC_new_kind_inner(fl, descr, adjust, clear)
1123 void **fl;
1124 GC_word descr;
1125 int adjust;
1126 int clear;
1128 int result = GC_n_kinds++;
1130 if (GC_n_kinds > MAXOBJKINDS) ABORT("Too many kinds");
1131 GC_obj_kinds[result].ok_freelist = (ptr_t *)fl;
1132 GC_obj_kinds[result].ok_reclaim_list = 0;
1133 GC_obj_kinds[result].ok_descriptor = descr;
1134 GC_obj_kinds[result].ok_relocate_descr = adjust;
1135 GC_obj_kinds[result].ok_init = clear;
1136 return result;
1139 int GC_new_kind(fl, descr, adjust, clear)
1140 void **fl;
1141 GC_word descr;
1142 int adjust;
1143 int clear;
1145 int result;
1146 LOCK(); DISABLE_SIGNALS();
1147 result = GC_new_kind_inner(fl, descr, adjust, clear);
1148 UNLOCK(); ENABLE_SIGNALS();
1149 return result;
1152 int GC_new_proc_inner(proc)
1153 GC_mark_proc proc;
1155 int result = GC_n_mark_procs++;
1157 if (GC_n_mark_procs > MAX_MARK_PROCS) ABORT("Too many mark procedures");
1158 GC_mark_procs[result] = proc;
1159 return result;
1162 int GC_new_proc(proc)
1163 GC_mark_proc proc;
1165 int result;
1166 LOCK(); DISABLE_SIGNALS();
1167 result = GC_new_proc_inner(proc);
1168 UNLOCK(); ENABLE_SIGNALS();
1169 return result;
1173 #if !defined(NO_DEBUGGING)
1175 void GC_dump()
1177 GC_printf0("***Static roots:\n");
1178 GC_print_static_roots();
1179 GC_printf0("\n***Heap sections:\n");
1180 GC_print_heap_sects();
1181 GC_printf0("\n***Free blocks:\n");
1182 GC_print_hblkfreelist();
1183 GC_printf0("\n***Blocks in use:\n");
1184 GC_print_block_list();
1185 GC_printf0("\n***Finalization statistics:\n");
1186 GC_print_finalization_stats();
1189 #endif /* NO_DEBUGGING */