Upgrade Boehm GC to 7.2alpha4.
[cacao.git] / src / mm / boehm-gc / misc.c
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.
5  *
6  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
7  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
8  *
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.
14  */
15
16 #include "private/gc_pmark.h"
17
18 #include <stdio.h>
19 #include <limits.h>
20 #include <stdarg.h>
21
22 #ifndef MSWINCE
23 # include <signal.h>
24 #endif
25
26 #ifdef GC_SOLARIS_THREADS
27 # include <sys/syscall.h>
28 #endif
29 #if defined(MSWIN32) || defined(MSWINCE)
30 # ifndef WIN32_LEAN_AND_MEAN
31 #   define WIN32_LEAN_AND_MEAN 1
32 # endif
33 # define NOSERVICE
34 # include <windows.h>
35 #endif
36
37 #if defined(UNIX_LIKE) || defined(CYGWIN32)
38 # include <fcntl.h>
39 # include <sys/types.h>
40 # include <sys/stat.h>
41 #endif
42
43 #ifdef NONSTOP
44 # include <floss.h>
45 #endif
46
47 #if defined(THREADS) && defined(PCR)
48 # include "il/PCR_IL.h"
49   GC_INNER PCR_Th_ML GC_allocate_ml;
50 #endif
51 /* For other platforms with threads, the lock and possibly              */
52 /* GC_lock_holder variables are defined in the thread support code.     */
53
54 #ifdef DYNAMIC_LOADING
55   /* We need to register the main data segment.  Returns  TRUE unless   */
56   /* this is done implicitly as part of dynamic library registration.   */
57   GC_INNER GC_bool GC_register_main_static_data(void);
58 # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
59 #else
60   /* Don't unnecessarily call GC_register_main_static_data() in case    */
61   /* dyn_load.c isn't linked in.                                        */
62 # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
63 #endif
64
65 #ifdef NEED_CANCEL_DISABLE_COUNT
66   __thread unsigned char GC_cancel_disable_count = 0;
67 #endif
68
69 GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
70
71 GC_INNER GC_bool GC_debugging_started = FALSE;
72         /* defined here so we don't have to load debug_malloc.o */
73
74 GC_INNER void (*GC_check_heap)(void) = 0;
75 GC_INNER void (*GC_print_all_smashed)(void) = 0;
76
77 ptr_t GC_stackbottom = 0;
78
79 #ifdef IA64
80   ptr_t GC_register_stackbottom = 0;
81 #endif
82
83 GC_bool GC_dont_gc = 0;
84
85 GC_bool GC_dont_precollect = 0;
86
87 GC_bool GC_quiet = 0; /* used also in pcr_interface.c */
88
89 #ifndef SMALL_CONFIG
90   GC_bool GC_print_stats = 0;
91 #endif
92
93 GC_INNER GC_bool GC_print_back_height = 0;
94
95 #ifndef NO_DEBUGGING
96   GC_INNER GC_bool GC_dump_regularly = 0;
97                                 /* Generate regular debugging dumps. */
98 #endif
99
100 #ifdef KEEP_BACK_PTRS
101   GC_INNER long GC_backtraces = 0;
102                 /* Number of random backtraces to generate for each GC. */
103 #endif
104
105 #ifdef FIND_LEAK
106   int GC_find_leak = 1;
107 #else
108   int GC_find_leak = 0;
109 #endif
110
111 #ifdef ALL_INTERIOR_POINTERS
112   int GC_all_interior_pointers = 1;
113 #else
114   int GC_all_interior_pointers = 0;
115 #endif
116
117 #ifdef GC_FORCE_UNMAP_ON_GCOLLECT
118   /* Has no effect unless USE_MUNMAP.                           */
119   /* Has no effect on implicitly-initiated garbage collections. */
120   GC_INNER GC_bool GC_force_unmap_on_gcollect = TRUE;
121 #else
122   GC_INNER GC_bool GC_force_unmap_on_gcollect = FALSE;
123 #endif
124
125 #ifndef GC_LARGE_ALLOC_WARN_INTERVAL
126 # define GC_LARGE_ALLOC_WARN_INTERVAL 5
127 #endif
128 GC_INNER long GC_large_alloc_warn_interval = GC_LARGE_ALLOC_WARN_INTERVAL;
129                         /* Interval between unsuppressed warnings.      */
130
131 /*ARGSUSED*/
132 STATIC void * GC_CALLBACK GC_default_oom_fn(size_t bytes_requested)
133 {
134     return(0);
135 }
136
137 /* All accesses to it should be synchronized to avoid data races.       */
138 GC_oom_func GC_oom_fn = GC_default_oom_fn;
139
140 /* Set things up so that GC_size_map[i] >= granules(i),         */
141 /* but not too much bigger                                              */
142 /* and so that size_map contains relatively few distinct entries        */
143 /* This was originally stolen from Russ Atkinson's Cedar                */
144 /* quantization algorithm (but we precompute it).                       */
145 STATIC void GC_init_size_map(void)
146 {
147     int i;
148
149     /* Map size 0 to something bigger.                  */
150     /* This avoids problems at lower levels.            */
151       GC_size_map[0] = 1;
152     for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
153         GC_size_map[i] = ROUNDED_UP_GRANULES(i);
154 #       ifndef _MSC_VER
155           GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
156           /* Seems to tickle bug in VC++ 2008 for AMD64 */
157 #       endif
158     }
159     /* We leave the rest of the array to be filled in on demand. */
160 }
161
162 /* Fill in additional entries in GC_size_map, including the ith one */
163 /* We assume the ith entry is currently 0.                              */
164 /* Note that a filled in section of the array ending at n always    */
165 /* has length at least n/4.                                             */
166 GC_INNER void GC_extend_size_map(size_t i)
167 {
168     size_t orig_granule_sz = ROUNDED_UP_GRANULES(i);
169     size_t granule_sz = orig_granule_sz;
170     size_t byte_sz = GRANULES_TO_BYTES(granule_sz);
171                         /* The size we try to preserve.         */
172                         /* Close to i, unless this would        */
173                         /* introduce too many distinct sizes.   */
174     size_t smaller_than_i = byte_sz - (byte_sz >> 3);
175     size_t much_smaller_than_i = byte_sz - (byte_sz >> 2);
176     size_t low_limit;   /* The lowest indexed entry we  */
177                         /* initialize.                  */
178     size_t j;
179
180     if (GC_size_map[smaller_than_i] == 0) {
181         low_limit = much_smaller_than_i;
182         while (GC_size_map[low_limit] != 0) low_limit++;
183     } else {
184         low_limit = smaller_than_i + 1;
185         while (GC_size_map[low_limit] != 0) low_limit++;
186         granule_sz = ROUNDED_UP_GRANULES(low_limit);
187         granule_sz += granule_sz >> 3;
188         if (granule_sz < orig_granule_sz) granule_sz = orig_granule_sz;
189     }
190     /* For these larger sizes, we use an even number of granules.       */
191     /* This makes it easier to, for example, construct a 16byte-aligned */
192     /* allocator even if GRANULE_BYTES is 8.                            */
193         granule_sz += 1;
194         granule_sz &= ~1;
195     if (granule_sz > MAXOBJGRANULES) {
196         granule_sz = MAXOBJGRANULES;
197     }
198     /* If we can fit the same number of larger objects in a block,      */
199     /* do so.                                                   */
200     {
201         size_t number_of_objs = HBLK_GRANULES/granule_sz;
202         granule_sz = HBLK_GRANULES/number_of_objs;
203         granule_sz &= ~1;
204     }
205     byte_sz = GRANULES_TO_BYTES(granule_sz);
206     /* We may need one extra byte;                      */
207     /* don't always fill in GC_size_map[byte_sz]        */
208     byte_sz -= EXTRA_BYTES;
209
210     for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = granule_sz;
211 }
212
213
214 /*
215  * The following is a gross hack to deal with a problem that can occur
216  * on machines that are sloppy about stack frame sizes, notably SPARC.
217  * Bogus pointers may be written to the stack and not cleared for
218  * a LONG time, because they always fall into holes in stack frames
219  * that are not written.  We partially address this by clearing
220  * sections of the stack whenever we get control.
221  */
222 # ifdef THREADS
223 #   define BIG_CLEAR_SIZE 2048  /* Clear this much now and then.        */
224 #   define SMALL_CLEAR_SIZE 256 /* Clear this much every time.          */
225 # else
226   STATIC word GC_stack_last_cleared = 0; /* GC_no when we last did this */
227   STATIC ptr_t GC_min_sp = NULL;
228                         /* Coolest stack pointer value from which       */
229                         /* we've already cleared the stack.             */
230   STATIC ptr_t GC_high_water = NULL;
231                         /* "hottest" stack pointer value we have seen   */
232                         /* recently.  Degrades over time.               */
233   STATIC word GC_bytes_allocd_at_reset = 0;
234 #   define DEGRADE_RATE 50
235 # endif
236
237 # define CLEAR_SIZE 213  /* Granularity for GC_clear_stack_inner */
238
239 #if defined(ASM_CLEAR_CODE)
240   void *GC_clear_stack_inner(void *, ptr_t);
241 #else
242   /* Clear the stack up to about limit.  Return arg.  This function is  */
243   /* not static because it could also be errorneously defined in .S     */
244   /* file, so this error would be caught by the linker.                 */
245   /*ARGSUSED*/
246   void * GC_clear_stack_inner(void *arg, ptr_t limit)
247   {
248     word dummy[CLEAR_SIZE];
249
250     BZERO(dummy, CLEAR_SIZE*sizeof(word));
251     if ((ptr_t)(dummy) COOLER_THAN limit) {
252         (void) GC_clear_stack_inner(arg, limit);
253     }
254     /* Make sure the recursive call is not a tail call, and the bzero   */
255     /* call is not recognized as dead code.                             */
256     GC_noop1((word)dummy);
257     return(arg);
258   }
259 #endif
260
261 /* Clear some of the inaccessible part of the stack.  Returns its       */
262 /* argument, so it can be used in a tail call position, hence clearing  */
263 /* another frame.                                                       */
264 GC_INNER void * GC_clear_stack(void *arg)
265 {
266     ptr_t sp = GC_approx_sp();  /* Hotter than actual sp */
267 #   ifdef THREADS
268         word dummy[SMALL_CLEAR_SIZE];
269         static unsigned random_no = 0;
270                                  /* Should be more random than it is ... */
271                                  /* Used to occasionally clear a bigger  */
272                                  /* chunk.                               */
273 #   endif
274     ptr_t limit;
275
276 #   define SLOP 400
277         /* Extra bytes we clear every time.  This clears our own        */
278         /* activation record, and should cause more frequent            */
279         /* clearing near the cold end of the stack, a good thing.       */
280 #   define GC_SLOP 4000
281         /* We make GC_high_water this much hotter than we really saw    */
282         /* saw it, to cover for GC noise etc. above our current frame.  */
283 #   define CLEAR_THRESHOLD 100000
284         /* We restart the clearing process after this many bytes of     */
285         /* allocation.  Otherwise very heavily recursive programs       */
286         /* with sparse stacks may result in heaps that grow almost      */
287         /* without bounds.  As the heap gets larger, collection         */
288         /* frequency decreases, thus clearing frequency would decrease, */
289         /* thus more junk remains accessible, thus the heap gets        */
290         /* larger ...                                                   */
291 # ifdef THREADS
292     if (++random_no % 13 == 0) {
293         limit = sp;
294         MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
295         limit = (ptr_t)((word)limit & ~0xf);
296                         /* Make it sufficiently aligned for assembly    */
297                         /* implementations of GC_clear_stack_inner.     */
298         return GC_clear_stack_inner(arg, limit);
299     } else {
300         BZERO(dummy, SMALL_CLEAR_SIZE*sizeof(word));
301         return arg;
302     }
303 # else
304     if (GC_gc_no > GC_stack_last_cleared) {
305         /* Start things over, so we clear the entire stack again */
306         if (GC_stack_last_cleared == 0) GC_high_water = (ptr_t)GC_stackbottom;
307         GC_min_sp = GC_high_water;
308         GC_stack_last_cleared = GC_gc_no;
309         GC_bytes_allocd_at_reset = GC_bytes_allocd;
310     }
311     /* Adjust GC_high_water */
312         MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
313         if (sp HOTTER_THAN GC_high_water) {
314             GC_high_water = sp;
315         }
316         MAKE_HOTTER(GC_high_water, GC_SLOP);
317     limit = GC_min_sp;
318     MAKE_HOTTER(limit, SLOP);
319     if (sp COOLER_THAN limit) {
320         limit = (ptr_t)((word)limit & ~0xf);
321                         /* Make it sufficiently aligned for assembly    */
322                         /* implementations of GC_clear_stack_inner.     */
323         GC_min_sp = sp;
324         return(GC_clear_stack_inner(arg, limit));
325     } else if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) {
326         /* Restart clearing process, but limit how much clearing we do. */
327         GC_min_sp = sp;
328         MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
329         if (GC_min_sp HOTTER_THAN GC_high_water) GC_min_sp = GC_high_water;
330         GC_bytes_allocd_at_reset = GC_bytes_allocd;
331     }
332     return(arg);
333 # endif
334 }
335
336
337 /* Return a pointer to the base address of p, given a pointer to a      */
338 /* an address within an object.  Return 0 o.w.                          */
339 GC_API void * GC_CALL GC_base(void * p)
340 {
341     ptr_t r;
342     struct hblk *h;
343     bottom_index *bi;
344     hdr *candidate_hdr;
345     ptr_t limit;
346
347     r = p;
348     if (!GC_is_initialized) return 0;
349     h = HBLKPTR(r);
350     GET_BI(r, bi);
351     candidate_hdr = HDR_FROM_BI(bi, r);
352     if (candidate_hdr == 0) return(0);
353     /* If it's a pointer to the middle of a large object, move it       */
354     /* to the beginning.                                                */
355         while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
356            h = FORWARDED_ADDR(h,candidate_hdr);
357            r = (ptr_t)h;
358            candidate_hdr = HDR(h);
359         }
360     if (HBLK_IS_FREE(candidate_hdr)) return(0);
361     /* Make sure r points to the beginning of the object */
362         r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
363         {
364             size_t offset = HBLKDISPL(r);
365             signed_word sz = candidate_hdr -> hb_sz;
366             size_t obj_displ = offset % sz;
367
368             r -= obj_displ;
369             limit = r + sz;
370             if (limit > (ptr_t)(h + 1) && sz <= HBLKSIZE) {
371                 return(0);
372             }
373             if ((ptr_t)p >= limit) return(0);
374         }
375     return((void *)r);
376 }
377
378
379 /* Return the size of an object, given a pointer to its base.           */
380 /* (For small objects this also happens to work from interior pointers, */
381 /* but that shouldn't be relied upon.)                                  */
382 GC_API size_t GC_CALL GC_size(const void * p)
383 {
384     hdr * hhdr = HDR(p);
385
386     return hhdr -> hb_sz;
387 }
388
389 GC_API size_t GC_CALL GC_get_heap_size(void)
390 {
391     size_t value;
392     DCL_LOCK_STATE;
393     LOCK();
394     /* ignore the memory space returned to OS (i.e. count only the      */
395     /* space owned by the garbage collector)                            */
396     value = (size_t)(GC_heapsize - GC_unmapped_bytes);
397     UNLOCK();
398     return value;
399 }
400
401 GC_API size_t GC_CALL GC_get_free_bytes(void)
402 {
403     size_t value;
404     DCL_LOCK_STATE;
405     LOCK();
406     /* ignore the memory space returned to OS */
407     value = (size_t)(GC_large_free_bytes - GC_unmapped_bytes);
408     UNLOCK();
409     return value;
410 }
411
412 /* The _inner versions assume the caller holds the allocation lock.     */
413 /* Declared in gc_mark.h (where other public "inner" functions reside). */
414 GC_API size_t GC_CALL GC_get_heap_size_inner(void)
415 {
416     return (size_t)(GC_heapsize - GC_unmapped_bytes);
417 }
418
419 GC_API size_t GC_CALL GC_get_free_bytes_inner(void)
420 {
421     return (size_t)(GC_large_free_bytes - GC_unmapped_bytes);
422 }
423
424 GC_API size_t GC_CALL GC_get_unmapped_bytes(void)
425 {
426 # ifdef USE_MUNMAP
427     size_t value;
428     DCL_LOCK_STATE;
429     LOCK();
430     value = (size_t)GC_unmapped_bytes;
431     UNLOCK();
432     return value;
433 # else
434     return 0;
435 # endif
436 }
437
438 GC_API size_t GC_CALL GC_get_bytes_since_gc(void)
439 {
440     size_t value;
441     DCL_LOCK_STATE;
442     LOCK();
443     value = GC_bytes_allocd;
444     UNLOCK();
445     return value;
446 }
447
448 GC_API size_t GC_CALL GC_get_total_bytes(void)
449 {
450     size_t value;
451     DCL_LOCK_STATE;
452     LOCK();
453     value = GC_bytes_allocd+GC_bytes_allocd_before_gc;
454     UNLOCK();
455     return value;
456 }
457
458 #ifdef THREADS
459   GC_API int GC_CALL GC_get_suspend_signal(void)
460   {
461 #   ifdef SIG_SUSPEND
462       return SIG_SUSPEND;
463 #   else
464       return -1;
465 #   endif
466   }
467 #endif /* THREADS */
468
469 GC_INNER GC_bool GC_is_initialized = FALSE;
470
471 #if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
472     GC_INNER CRITICAL_SECTION GC_write_cs;
473 #endif
474
475 #ifdef MSWIN32
476     GC_INNER void GC_init_win32(void);
477 #endif
478
479 GC_INNER void GC_setpagesize(void);
480
481 STATIC void GC_exit_check(void)
482 {
483    GC_gcollect();
484 }
485
486 #ifdef SEARCH_FOR_DATA_START
487   GC_INNER void GC_init_linux_data_start(void);
488 #endif
489
490 #ifdef UNIX_LIKE
491
492   GC_INNER void GC_set_and_save_fault_handler(void (*handler)(int));
493
494   static void looping_handler(int sig)
495   {
496     GC_err_printf("Caught signal %d: looping in handler\n", sig);
497     for (;;) {}
498   }
499
500   static GC_bool installed_looping_handler = FALSE;
501
502   static void maybe_install_looping_handler(void)
503   {
504     /* Install looping handler before the write fault handler, so we    */
505     /* handle write faults correctly.                                   */
506     if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
507       GC_set_and_save_fault_handler(looping_handler);
508       installed_looping_handler = TRUE;
509     }
510   }
511
512 #else /* !UNIX_LIKE */
513 # define maybe_install_looping_handler()
514 #endif
515
516 #if defined(DYNAMIC_LOADING) && defined(DARWIN)
517   GC_INNER void GC_init_dyld(void);
518 #endif
519
520 #if defined(NETBSD) && defined(__ELF__)
521   GC_INNER void GC_init_netbsd_elf(void);
522 #endif
523
524 #if !defined(OS2) && !defined(MACOS) && !defined(MSWIN32) && !defined(MSWINCE)
525   STATIC int GC_log = 2;
526 #endif
527
528 GC_API void GC_CALL GC_init(void)
529 {
530     /* LOCK(); -- no longer does anything this early. */
531 #   if !defined(THREADS) && defined(GC_ASSERTIONS)
532         word dummy;
533 #   endif
534
535 #   ifdef GC_INITIAL_HEAP_SIZE
536         word initial_heap_sz = divHBLKSZ(GC_INITIAL_HEAP_SIZE);
537 #   else
538         word initial_heap_sz = (word)MINHINCR;
539 #   endif
540     IF_CANCEL(int cancel_state;)
541
542     if (GC_is_initialized) return;
543
544     DISABLE_CANCEL(cancel_state);
545     /* Note that although we are nominally called with the */
546     /* allocation lock held, the allocation lock is now    */
547     /* only really acquired once a second thread is forked.*/
548     /* And the initialization code needs to run before     */
549     /* then.  Thus we really don't hold any locks, and can */
550     /* in fact safely initialize them here.                */
551 #   ifdef THREADS
552       GC_ASSERT(!GC_need_to_lock);
553 #   endif
554 #   if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
555      {
556 #     ifndef MSWINCE
557         BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL;
558         HMODULE hK32 = GetModuleHandle(TEXT("kernel32.dll"));
559         if (hK32)
560           pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD))
561                 GetProcAddress (hK32,
562                                 "InitializeCriticalSectionAndSpinCount");
563         if (pfn)
564             pfn(&GC_allocate_ml, 4000);
565         else
566 #     endif /* !MSWINCE */
567         /* else */ InitializeCriticalSection (&GC_allocate_ml);
568      }
569 #   endif /* GC_WIN32_THREADS */
570 #   if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
571       InitializeCriticalSection(&GC_write_cs);
572 #   endif
573 #   ifndef SMALL_CONFIG
574 #     ifdef GC_PRINT_VERBOSE_STATS
575         /* This is useful for debugging and profiling on platforms with */
576         /* missing getenv() (like WinCE).                               */
577         GC_print_stats = VERBOSE;
578 #     else
579         if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
580           GC_print_stats = VERBOSE;
581         } else if (0 != GETENV("GC_PRINT_STATS")) {
582           GC_print_stats = 1;
583         }
584 #     endif
585 #     if defined(UNIX_LIKE) || defined(CYGWIN32)
586         {
587           char * file_name = GETENV("GC_LOG_FILE");
588           if (0 != file_name) {
589             int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666);
590             if (log_d < 0) {
591               GC_err_printf("Failed to open %s as log file\n", file_name);
592             } else {
593               GC_log = log_d;
594             }
595           }
596         }
597 #     endif
598 #   endif /* !SMALL_CONFIG */
599 #   ifndef NO_DEBUGGING
600       if (0 != GETENV("GC_DUMP_REGULARLY")) {
601         GC_dump_regularly = 1;
602       }
603 #   endif
604 #   ifdef KEEP_BACK_PTRS
605       {
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;
610         }
611       }
612 #   endif
613     if (0 != GETENV("GC_FIND_LEAK")) {
614       GC_find_leak = 1;
615       atexit(GC_exit_check);
616     }
617     if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
618       GC_all_interior_pointers = 1;
619     }
620     if (0 != GETENV("GC_DONT_GC")) {
621       GC_dont_gc = 1;
622     }
623     if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
624       GC_print_back_height = 1;
625     }
626     if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
627       GC_large_alloc_warn_interval = LONG_MAX;
628     }
629     {
630       char * addr_string = GETENV("GC_TRACE");
631       if (0 != addr_string) {
632 #       ifndef ENABLE_TRACE
633           WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
634 #       else
635           word addr = (word)STRTOULL(addr_string, NULL, 16);
636           if (addr < 0x1000)
637               WARN("Unlikely trace address: %p\n", addr);
638           GC_trace_addr = (ptr_t)addr;
639 #       endif
640       }
641     }
642 #   ifndef GC_DISABLE_INCREMENTAL
643       {
644         char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
645         if (0 != time_limit_string) {
646           long time_limit = atol(time_limit_string);
647           if (time_limit < 5) {
648             WARN("GC_PAUSE_TIME_TARGET environment variable value too small "
649                  "or bad syntax: Ignoring\n", 0);
650           } else {
651             GC_time_limit = time_limit;
652           }
653         }
654       }
655 #   endif
656 #   ifndef SMALL_CONFIG
657       {
658         char * full_freq_string = GETENV("GC_FULL_FREQUENCY");
659         if (full_freq_string != NULL) {
660           int full_freq = atoi(full_freq_string);
661           if (full_freq > 0)
662             GC_full_freq = full_freq;
663         }
664       }
665 #   endif
666     {
667       char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
668       if (0 != interval_string) {
669         long interval = atol(interval_string);
670         if (interval <= 0) {
671           WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
672                "bad value: Ignoring\n", 0);
673         } else {
674           GC_large_alloc_warn_interval = interval;
675         }
676       }
677     }
678     {
679         char * space_divisor_string = GETENV("GC_FREE_SPACE_DIVISOR");
680         if (space_divisor_string != NULL) {
681           int space_divisor = atoi(space_divisor_string);
682           if (space_divisor > 0)
683             GC_free_space_divisor = (GC_word)space_divisor;
684         }
685     }
686 #   ifdef USE_MUNMAP
687       {
688         char * string = GETENV("GC_UNMAP_THRESHOLD");
689         if (string != NULL) {
690           if (*string == '0' && *(string + 1) == '\0') {
691             /* "0" is used to disable unmapping. */
692             GC_unmap_threshold = 0;
693           } else {
694             int unmap_threshold = atoi(string);
695             if (unmap_threshold > 0)
696               GC_unmap_threshold = unmap_threshold;
697           }
698         }
699       }
700       {
701         char * string = GETENV("GC_FORCE_UNMAP_ON_GCOLLECT");
702         if (string != NULL) {
703           if (*string == '0' && *(string + 1) == '\0') {
704             /* "0" is used to turn off the mode. */
705             GC_force_unmap_on_gcollect = FALSE;
706           } else {
707             GC_force_unmap_on_gcollect = TRUE;
708           }
709         }
710       }
711 #   endif
712     maybe_install_looping_handler();
713     /* Adjust normal object descriptor for extra allocation.    */
714     if (ALIGNMENT > GC_DS_TAGS && EXTRA_BYTES != 0) {
715       GC_obj_kinds[NORMAL].ok_descriptor = ((word)(-ALIGNMENT) | GC_DS_LENGTH);
716     }
717     GC_setpagesize();
718     GC_exclude_static_roots_inner(beginGC_arrays, endGC_arrays);
719     GC_exclude_static_roots_inner(beginGC_obj_kinds, endGC_obj_kinds);
720 #   ifdef SEPARATE_GLOBALS
721       GC_exclude_static_roots_inner(beginGC_objfreelist, endGC_objfreelist);
722       GC_exclude_static_roots_inner(beginGC_aobjfreelist, endGC_aobjfreelist);
723 #   endif
724 #   ifdef MSWIN32
725         GC_init_win32();
726 #   endif
727 #   if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
728         WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
729         /* If thread stacks are cached, they tend to be scanned in      */
730         /* entirety as part of the root set.  This wil grow them to     */
731         /* maximum size, and is generally not desirable.                */
732 #   endif
733 #   if defined(SEARCH_FOR_DATA_START)
734         GC_init_linux_data_start();
735 #   endif
736 #   if defined(NETBSD) && defined(__ELF__)
737         GC_init_netbsd_elf();
738 #   endif
739 #   if !defined(THREADS) || defined(GC_PTHREADS) || defined(GC_WIN32_THREADS) \
740         || defined(GC_SOLARIS_THREADS)
741       if (GC_stackbottom == 0) {
742         GC_stackbottom = GC_get_main_stack_base();
743 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
744           GC_register_stackbottom = GC_get_register_stack_base();
745 #       endif
746       } else {
747 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
748           if (GC_register_stackbottom == 0) {
749             WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
750             /* The following may fail, since we may rely on             */
751             /* alignment properties that may not hold with a user set   */
752             /* GC_stackbottom.                                          */
753             GC_register_stackbottom = GC_get_register_stack_base();
754           }
755 #       endif
756       }
757 #   endif
758     GC_STATIC_ASSERT(sizeof (ptr_t) == sizeof(word));
759     GC_STATIC_ASSERT(sizeof (signed_word) == sizeof(word));
760     GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
761 #   ifndef THREADS
762 #     ifdef STACK_GROWS_DOWN
763         GC_ASSERT((word)(&dummy) <= (word)GC_stackbottom);
764 #     else
765         GC_ASSERT((word)(&dummy) >= (word)GC_stackbottom);
766 #     endif
767 #   endif
768 #   if !defined(_AUX_SOURCE) || defined(__GNUC__)
769       GC_STATIC_ASSERT((word)(-1) > (word)0);
770       /* word should be unsigned */
771 #   endif
772 #   if !defined(__BORLANDC__) /* Workaround for Borland C */
773         GC_STATIC_ASSERT((ptr_t)(word)(-1) > (ptr_t)0);
774         /* Ptr_t comparisons should behave as unsigned comparisons.     */
775 #   endif
776     GC_STATIC_ASSERT((signed_word)(-1) < (signed_word)0);
777 #   ifndef GC_DISABLE_INCREMENTAL
778       if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
779         /* For GWW_MPROTECT on Win32, this needs to happen before any   */
780         /* heap memory is allocated.                                    */
781         GC_dirty_init();
782         GC_ASSERT(GC_bytes_allocd == 0)
783         GC_incremental = TRUE;
784       }
785 #   endif
786
787     /* Add initial guess of root sets.  Do this first, since sbrk(0)    */
788     /* might be used.                                                   */
789       if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
790     GC_init_headers();
791     GC_bl_init();
792     GC_mark_init();
793     {
794         char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
795         if (sz_str != NULL) {
796           initial_heap_sz = (word)STRTOULL(sz_str, NULL, 10);
797           if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
798             WARN("Bad initial heap size %s - ignoring it.\n",
799                  sz_str);
800           }
801           initial_heap_sz = divHBLKSZ(initial_heap_sz);
802         }
803     }
804     {
805         char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
806         if (sz_str != NULL) {
807           word max_heap_sz = (word)STRTOULL(sz_str, NULL, 10);
808           if (max_heap_sz < initial_heap_sz * HBLKSIZE) {
809             WARN("Bad maximum heap size %s - ignoring it.\n",
810                  sz_str);
811           }
812           if (0 == GC_max_retries) GC_max_retries = 2;
813           GC_set_max_heap_size(max_heap_sz);
814         }
815     }
816     if (!GC_expand_hp_inner(initial_heap_sz)) {
817         GC_err_printf("Can't start up: not enough memory\n");
818         EXIT();
819     }
820     GC_initialize_offsets();
821     GC_register_displacement_inner(0L);
822 #   if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
823       if (!GC_all_interior_pointers) {
824         /* TLS ABI uses pointer-sized offsets for dtv. */
825         GC_register_displacement_inner(sizeof(void *));
826       }
827 #   endif
828     GC_init_size_map();
829 #   ifdef PCR
830       if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
831           != PCR_ERes_okay) {
832           ABORT("Can't lock load state\n");
833       } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
834           ABORT("Can't unlock load state\n");
835       }
836       PCR_IL_Unlock();
837       GC_pcr_install();
838 #   endif
839     GC_is_initialized = TRUE;
840 #   if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
841         GC_thr_init();
842 #   endif
843     COND_DUMP;
844     /* Get black list set up and/or incremental GC started */
845       if (!GC_dont_precollect || GC_incremental) GC_gcollect_inner();
846 #   ifdef STUBBORN_ALLOC
847         GC_stubborn_init();
848 #   endif
849     /* Convince lint that some things are used */
850 #   ifdef LINT
851       {
852           extern char * const GC_copyright[];
853           GC_noop(GC_copyright, GC_find_header, GC_push_one,
854                   GC_call_with_alloc_lock, GC_dont_expand,
855 #                 ifndef NO_DEBUGGING
856                     GC_dump,
857 #                 endif
858                   GC_register_finalizer_no_order);
859       }
860 #   endif
861
862     /* The rest of this again assumes we don't really hold      */
863     /* the allocation lock.                                     */
864 #   if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
865         /* Make sure marker threads are started and thread local */
866         /* allocation is initialized, in case we didn't get      */
867         /* called from GC_init_parallel.                         */
868         GC_init_parallel();
869 #   endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
870
871 #   if defined(DYNAMIC_LOADING) && defined(DARWIN)
872         /* This must be called WITHOUT the allocation lock held */
873         /* and before any threads are created.                  */
874         GC_init_dyld();
875 #   endif
876     RESTORE_CANCEL(cancel_state);
877 }
878
879 GC_API void GC_CALL GC_enable_incremental(void)
880 {
881 # if !defined(GC_DISABLE_INCREMENTAL) && !defined(KEEP_BACK_PTRS)
882     DCL_LOCK_STATE;
883     /* If we are keeping back pointers, the GC itself dirties all */
884     /* pages on which objects have been marked, making            */
885     /* incremental GC pointless.                                  */
886     if (!GC_find_leak && 0 == GETENV("GC_DISABLE_INCREMENTAL")) {
887       LOCK();
888       if (!GC_incremental) {
889         GC_setpagesize();
890         /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
891         maybe_install_looping_handler(); /* Before write fault handler! */
892         GC_incremental = TRUE;
893         if (!GC_is_initialized) {
894           GC_init();
895         } else {
896           GC_dirty_init();
897         }
898         if (GC_dirty_maintained && !GC_dont_gc) {
899                                 /* Can't easily do it if GC_dont_gc.    */
900           if (GC_bytes_allocd > 0) {
901             /* There may be unmarked reachable objects. */
902             GC_gcollect_inner();
903           }
904             /* else we're OK in assuming everything's   */
905             /* clean since nothing can point to an      */
906             /* unmarked object.                         */
907           GC_read_dirty();
908         }
909       }
910       UNLOCK();
911       return;
912     }
913 # endif
914   GC_init();
915 }
916
917
918 #if defined(MSWIN32) || defined(MSWINCE)
919
920 # if defined(_MSC_VER) && defined(_DEBUG) && !defined(MSWINCE)
921 #   include <crtdbg.h>
922 # endif
923
924   STATIC HANDLE GC_stdout = 0;
925
926   void GC_deinit(void)
927   {
928 #   ifdef THREADS
929       if (GC_is_initialized) {
930         DeleteCriticalSection(&GC_write_cs);
931       }
932 #   endif
933   }
934
935 #ifdef THREADS
936 # ifdef PARALLEL_MARK
937 #   define IF_NEED_TO_LOCK(x) if (GC_parallel || GC_need_to_lock) x
938 # else
939 #   define IF_NEED_TO_LOCK(x) if (GC_need_to_lock) x
940 # endif
941 #else
942 # define IF_NEED_TO_LOCK(x)
943 #endif
944
945 #ifndef _MAX_PATH
946 # define _MAX_PATH MAX_PATH
947 #endif
948
949   STATIC HANDLE GC_CreateLogFile(void)
950   {
951 #   if !defined(NO_GETENV_WIN32) || !defined(OLD_WIN32_LOG_FILE)
952       TCHAR logPath[_MAX_PATH + 0x10]; /* buffer for path + ext */
953 #   endif
954     /* Use GetEnvironmentVariable instead of GETENV() for unicode support. */
955 #   ifndef NO_GETENV_WIN32
956       if (GetEnvironmentVariable(TEXT("GC_LOG_FILE"), logPath,
957                                  _MAX_PATH + 1) - 1U >= (DWORD)_MAX_PATH)
958 #   endif
959     {
960       /* Env var not found or its value too long.       */
961 #     ifdef OLD_WIN32_LOG_FILE
962         return CreateFile(TEXT("gc.log"), GENERIC_WRITE, FILE_SHARE_READ,
963                           NULL /* lpSecurityAttributes */, CREATE_ALWAYS,
964                           FILE_FLAG_WRITE_THROUGH, NULL /* hTemplateFile */);
965 #     else
966         int len = (int)GetModuleFileName(NULL /* hModule */, logPath,
967                                          _MAX_PATH + 1);
968         /* If GetModuleFileName() has failed then len is 0. */
969         if (len > 4 && logPath[len - 4] == (TCHAR)'.') {
970           len -= 4; /* strip executable file extension */
971         }
972         /* strcat/wcscat() are deprecated on WinCE, so use memcpy()     */
973         memcpy(&logPath[len], TEXT(".gc.log"), sizeof(TEXT(".gc.log")));
974 #     endif
975     }
976 #   if !defined(NO_GETENV_WIN32) || !defined(OLD_WIN32_LOG_FILE)
977       return CreateFile(logPath, GENERIC_WRITE, FILE_SHARE_READ,
978                         NULL /* lpSecurityAttributes */, CREATE_ALWAYS,
979                         GC_print_stats == VERBOSE ? FILE_ATTRIBUTE_NORMAL :
980                             /* immediately flush writes unless very verbose */
981                             FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
982                         NULL /* hTemplateFile */);
983 #   endif
984   }
985
986   STATIC int GC_write(const char *buf, size_t len)
987   {
988       BOOL tmp;
989       DWORD written;
990       if (len == 0)
991           return 0;
992       IF_NEED_TO_LOCK(EnterCriticalSection(&GC_write_cs));
993 #     ifdef THREADS
994         GC_ASSERT(!GC_write_disabled);
995 #     endif
996       if (GC_stdout == INVALID_HANDLE_VALUE) {
997           IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
998           return -1;
999       } else if (GC_stdout == 0) {
1000         GC_stdout = GC_CreateLogFile();
1001         /* Ignore open log failure if the collector is built with       */
1002         /* print_stats always set on.                                   */
1003 #       ifndef GC_PRINT_VERBOSE_STATS
1004           if (GC_stdout == INVALID_HANDLE_VALUE)
1005             ABORT("Open of log file failed");
1006 #       endif
1007       }
1008       tmp = WriteFile(GC_stdout, buf, (DWORD)len, &written, NULL);
1009       if (!tmp)
1010           DebugBreak();
1011 #     if defined(_MSC_VER) && defined(_DEBUG)
1012 #         ifdef MSWINCE
1013               /* There is no CrtDbgReport() in WinCE */
1014               {
1015                   WCHAR wbuf[1024];
1016                   /* Always use Unicode variant of OutputDebugString() */
1017                   wbuf[MultiByteToWideChar(CP_ACP, 0 /* dwFlags */,
1018                                 buf, len, wbuf,
1019                                 sizeof(wbuf) / sizeof(wbuf[0]) - 1)] = 0;
1020                   OutputDebugStringW(wbuf);
1021               }
1022 #         else
1023               _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
1024 #         endif
1025 #     endif
1026       IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
1027       return tmp ? (int)written : -1;
1028   }
1029
1030 #endif /* MSWIN32 */
1031
1032 #if defined(OS2) || defined(MACOS)
1033   STATIC FILE * GC_stdout = NULL;
1034   STATIC FILE * GC_stderr = NULL;
1035   STATIC FILE * GC_log = NULL;
1036
1037   STATIC void GC_set_files(void)
1038   {
1039       if (GC_stdout == NULL) {
1040         GC_stdout = stdout;
1041     }
1042     if (GC_stderr == NULL) {
1043         GC_stderr = stderr;
1044     }
1045     if (GC_log == NULL) {
1046         GC_log = stderr;
1047     }
1048   }
1049 #endif
1050
1051 #if !defined(OS2) && !defined(MACOS) && !defined(MSWIN32) && !defined(MSWINCE)
1052   STATIC int GC_stdout = 1;
1053   STATIC int GC_stderr = 2;
1054 # if !defined(AMIGA)
1055 #   include <unistd.h>
1056 # endif
1057 #endif
1058
1059 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(OS2) \
1060     && !defined(MACOS)  && !defined(ECOS) && !defined(NOSYS)
1061 STATIC int GC_write(int fd, const char *buf, size_t len)
1062 {
1063      int bytes_written = 0;
1064      int result;
1065      IF_CANCEL(int cancel_state;)
1066
1067      DISABLE_CANCEL(cancel_state);
1068      while (bytes_written < len) {
1069 #       ifdef GC_SOLARIS_THREADS
1070             result = syscall(SYS_write, fd, buf + bytes_written,
1071                                             len - bytes_written);
1072 #       else
1073             result = write(fd, buf + bytes_written, len - bytes_written);
1074 #       endif
1075         if (-1 == result) {
1076             RESTORE_CANCEL(cancel_state);
1077             return(result);
1078         }
1079         bytes_written += result;
1080     }
1081     RESTORE_CANCEL(cancel_state);
1082     return(bytes_written);
1083 }
1084 #endif /* UN*X */
1085
1086 #ifdef ECOS
1087   STATIC int GC_write(int fd, const char *buf, size_t len)
1088   {
1089     /* FIXME: This seems to be defined nowhere at present. */
1090     /* _Jv_diag_write(buf, len); */
1091     return len;
1092   }
1093 #endif
1094
1095 #ifdef NOSYS
1096   STATIC int GC_write(int fd, const char *buf, size_t len)
1097   {
1098     /* No writing.  */
1099     return len;
1100   }
1101 #endif
1102
1103
1104 #if defined(MSWIN32) || defined(MSWINCE)
1105     /* FIXME: This is pretty ugly ... */
1106 #   define WRITE(f, buf, len) GC_write(buf, len)
1107 #else
1108 #   if defined(OS2) || defined(MACOS)
1109     static int fwrite_gc_res; /* Should really be local ... */
1110 #   define WRITE(f, buf, len) (GC_set_files(), \
1111                                fwrite_gc_res = fwrite((buf), 1, (len), (f)), \
1112                                fflush(f), fwrite_gc_res)
1113 #   else
1114 #     define WRITE(f, buf, len) GC_write((f), (buf), (len))
1115 #   endif
1116 #endif
1117
1118 #define BUFSZ 1024
1119 #ifdef _MSC_VER
1120 # ifdef MSWINCE
1121     /* _vsnprintf is deprecated in WinCE */
1122 #   define vsnprintf StringCchVPrintfA
1123 # else
1124 #   define vsnprintf _vsnprintf
1125 # endif
1126 #endif
1127 /* A version of printf that is unlikely to call malloc, and is thus safer */
1128 /* to call from the collector in case malloc has been bound to GC_malloc. */
1129 /* Floating point arguments and formats should be avoided, since fp       */
1130 /* conversion is more likely to allocate.                                 */
1131 /* Assumes that no more than BUFSZ-1 characters are written at once.      */
1132 void GC_printf(const char *format, ...)
1133 {
1134     va_list args;
1135     char buf[BUFSZ+1];
1136
1137     va_start(args, format);
1138     if (GC_quiet) return;
1139     buf[BUFSZ] = 0x15;
1140     (void) vsnprintf(buf, BUFSZ, format, args);
1141     va_end(args);
1142     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1143     if (WRITE(GC_stdout, buf, strlen(buf)) < 0)
1144       ABORT("write to stdout failed");
1145 }
1146
1147 void GC_err_printf(const char *format, ...)
1148 {
1149     va_list args;
1150     char buf[BUFSZ+1];
1151
1152     va_start(args, format);
1153     buf[BUFSZ] = 0x15;
1154     (void) vsnprintf(buf, BUFSZ, format, args);
1155     va_end(args);
1156     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1157     if (WRITE(GC_stderr, buf, strlen(buf)) < 0)
1158       ABORT("write to stderr failed");
1159 }
1160
1161 void GC_log_printf(const char *format, ...)
1162 {
1163     va_list args;
1164     char buf[BUFSZ+1];
1165
1166     va_start(args, format);
1167     buf[BUFSZ] = 0x15;
1168     (void) vsnprintf(buf, BUFSZ, format, args);
1169     va_end(args);
1170     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1171     if (WRITE(GC_log, buf, strlen(buf)) < 0)
1172       ABORT("write to log failed");
1173 }
1174
1175 void GC_err_puts(const char *s)
1176 {
1177     if (WRITE(GC_stderr, s, strlen(s)) < 0) ABORT("write to stderr failed");
1178 }
1179
1180 #if defined(LINUX) && !defined(SMALL_CONFIG)
1181   GC_INNER void GC_err_write(const char *buf, size_t len)
1182   {
1183     if (WRITE(GC_stderr, buf, len) < 0) ABORT("write to stderr failed");
1184   }
1185 #endif
1186
1187 STATIC void GC_CALLBACK GC_default_warn_proc(char *msg, GC_word arg)
1188 {
1189     GC_err_printf(msg, arg);
1190 }
1191
1192 GC_INNER GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1193
1194 /* This is recommended for production code (release). */
1195 GC_API void GC_CALLBACK GC_ignore_warn_proc(char *msg, GC_word arg)
1196 {
1197     if (GC_print_stats) {
1198       /* Don't ignore warnings if stats printing is on. */
1199       GC_default_warn_proc(msg, arg);
1200     }
1201 }
1202
1203 GC_API void GC_CALL GC_set_warn_proc(GC_warn_proc p)
1204 {
1205     GC_ASSERT(p != 0);
1206 #   ifdef GC_WIN32_THREADS
1207 #     ifdef CYGWIN32
1208         /* Need explicit GC_INIT call */
1209         GC_ASSERT(GC_is_initialized);
1210 #     else
1211         if (!GC_is_initialized) GC_init();
1212 #     endif
1213 #   endif
1214     LOCK();
1215     GC_current_warn_proc = p;
1216     UNLOCK();
1217 }
1218
1219 GC_API GC_warn_proc GC_CALL GC_get_warn_proc(void)
1220 {
1221     GC_warn_proc result;
1222     LOCK();
1223     result = GC_current_warn_proc;
1224     UNLOCK();
1225     return(result);
1226 }
1227
1228 #if !defined(PCR) && !defined(SMALL_CONFIG)
1229   /* Abort the program with a message. msg must not be NULL. */
1230   void GC_abort(const char *msg)
1231   {
1232 #   if defined(MSWIN32)
1233 #     ifndef DONT_USE_USER32_DLL
1234         /* Use static binding to "user32.dll".  */
1235         (void)MessageBoxA(NULL, msg, "Fatal error in GC", MB_ICONERROR|MB_OK);
1236 #     else
1237         /* This simplifies linking - resolve "MessageBoxA" at run-time. */
1238         HINSTANCE hU32 = LoadLibrary(TEXT("user32.dll"));
1239         if (hU32) {
1240           FARPROC pfn = GetProcAddress(hU32, "MessageBoxA");
1241           if (pfn)
1242             (void)(*(int (WINAPI *)(HWND, LPCSTR, LPCSTR, UINT))pfn)(
1243                                 NULL /* hWnd */, msg, "Fatal error in GC",
1244                                 MB_ICONERROR | MB_OK);
1245           (void)FreeLibrary(hU32);
1246         }
1247 #     endif
1248       /* Also duplicate msg to GC log file.     */
1249 #   endif
1250       /* Avoid calling GC_err_printf() here, as GC_abort() could be     */
1251       /* called from it.  Note 1: this is not an atomic output.         */
1252       /* Note 2: possible write errors are ignored.                     */
1253       if (WRITE(GC_stderr, (void *)msg, strlen(msg)) >= 0)
1254         (void)WRITE(GC_stderr, (void *)("\n"), 1);
1255
1256     if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1257             /* In many cases it's easier to debug a running process.    */
1258             /* It's arguably nicer to sleep, but that makes it harder   */
1259             /* to look at the thread if the debugger doesn't know much  */
1260             /* about threads.                                           */
1261             for(;;) {}
1262     }
1263 #   if defined(MSWIN32) && defined(NO_DEBUGGING)
1264       /* A more user-friendly abort after showing fatal message.        */
1265       if (msg) /* to suppress compiler warnings in ABORT callers. */
1266         _exit(-1); /* exit on error without running "at-exit" callbacks */
1267 #   elif defined(MSWIN32) || defined(MSWINCE)
1268         DebugBreak();
1269 #   else
1270         (void) abort();
1271 #   endif
1272   }
1273 #endif /* !SMALL_CONFIG */
1274
1275 GC_API void GC_CALL GC_enable(void)
1276 {
1277     LOCK();
1278     GC_dont_gc--;
1279     UNLOCK();
1280 }
1281
1282 GC_API void GC_CALL GC_disable(void)
1283 {
1284     LOCK();
1285     GC_dont_gc++;
1286     UNLOCK();
1287 }
1288
1289 /* Helper procedures for new kind creation.     */
1290 GC_API void ** GC_CALL GC_new_free_list_inner(void)
1291 {
1292     void *result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1)*sizeof(ptr_t),
1293                                       PTRFREE);
1294     if (result == 0) ABORT("Failed to allocate freelist for new kind");
1295     BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
1296     return result;
1297 }
1298
1299 GC_API void ** GC_CALL GC_new_free_list(void)
1300 {
1301     void *result;
1302     LOCK();
1303     result = GC_new_free_list_inner();
1304     UNLOCK();
1305     return result;
1306 }
1307
1308 GC_API unsigned GC_CALL GC_new_kind_inner(void **fl, GC_word descr,
1309                                         int adjust, int clear)
1310 {
1311     unsigned result = GC_n_kinds++;
1312
1313     if (GC_n_kinds > MAXOBJKINDS) ABORT("Too many kinds");
1314     GC_obj_kinds[result].ok_freelist = fl;
1315     GC_obj_kinds[result].ok_reclaim_list = 0;
1316     GC_obj_kinds[result].ok_descriptor = descr;
1317     GC_obj_kinds[result].ok_relocate_descr = adjust;
1318     GC_obj_kinds[result].ok_init = clear;
1319     return result;
1320 }
1321
1322 GC_API unsigned GC_CALL GC_new_kind(void **fl, GC_word descr, int adjust,
1323                                     int clear)
1324 {
1325     unsigned result;
1326     LOCK();
1327     result = GC_new_kind_inner(fl, descr, adjust, clear);
1328     UNLOCK();
1329     return result;
1330 }
1331
1332 GC_API unsigned GC_CALL GC_new_proc_inner(GC_mark_proc proc)
1333 {
1334     unsigned result = GC_n_mark_procs++;
1335
1336     if (GC_n_mark_procs > MAX_MARK_PROCS) ABORT("Too many mark procedures");
1337     GC_mark_procs[result] = proc;
1338     return result;
1339 }
1340
1341 GC_API unsigned GC_CALL GC_new_proc(GC_mark_proc proc)
1342 {
1343     unsigned result;
1344     LOCK();
1345     result = GC_new_proc_inner(proc);
1346     UNLOCK();
1347     return result;
1348 }
1349
1350 GC_API void * GC_CALL GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
1351 {
1352     int dummy;
1353     struct GC_stack_base base;
1354
1355     base.mem_base = (void *)&dummy;
1356 #   ifdef IA64
1357       base.reg_base = (void *)GC_save_regs_in_stack();
1358       /* Unnecessarily flushes register stack,          */
1359       /* but that probably doesn't hurt.                */
1360 #   endif
1361     return fn(&base, arg);
1362 }
1363
1364 #ifdef THREADS
1365
1366   /* Defined in pthread_support.c or win32_threads.c.     */
1367   GC_INNER void GC_do_blocking_inner(ptr_t data, void * context);
1368
1369 #else
1370
1371 GC_INNER ptr_t GC_blocked_sp = NULL;
1372         /* NULL value means we are not inside GC_do_blocking() call. */
1373 # ifdef IA64
1374     STATIC ptr_t GC_blocked_register_sp = NULL;
1375 # endif
1376
1377 GC_INNER struct GC_activation_frame_s *GC_activation_frame = NULL;
1378
1379 /* This is nearly the same as in win32_threads.c        */
1380 GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn,
1381                                              void * client_data)
1382 {
1383     struct GC_activation_frame_s frame;
1384     GC_ASSERT(GC_is_initialized);
1385
1386     /* Adjust our stack base value (this could happen if        */
1387     /* GC_get_main_stack_base() is unimplemented or broken for  */
1388     /* the platform).                                           */
1389     if (GC_stackbottom HOTTER_THAN (ptr_t)(&frame))
1390       GC_stackbottom = (ptr_t)(&frame);
1391
1392     if (GC_blocked_sp == NULL) {
1393       /* We are not inside GC_do_blocking() - do nothing more.  */
1394       return fn(client_data);
1395     }
1396
1397     /* Setup new "frame".       */
1398     frame.saved_stack_ptr = GC_blocked_sp;
1399 #   ifdef IA64
1400       /* This is the same as in GC_call_with_stack_base().      */
1401       frame.backing_store_end = GC_save_regs_in_stack();
1402       /* Unnecessarily flushes register stack,          */
1403       /* but that probably doesn't hurt.                */
1404       frame.saved_backing_store_ptr = GC_blocked_register_sp;
1405 #   endif
1406     frame.prev = GC_activation_frame;
1407     GC_blocked_sp = NULL;
1408     GC_activation_frame = &frame;
1409
1410     client_data = fn(client_data);
1411     GC_ASSERT(GC_blocked_sp == NULL);
1412     GC_ASSERT(GC_activation_frame == &frame);
1413
1414     /* Restore original "frame".        */
1415     GC_activation_frame = frame.prev;
1416 #   ifdef IA64
1417       GC_blocked_register_sp = frame.saved_backing_store_ptr;
1418 #   endif
1419     GC_blocked_sp = frame.saved_stack_ptr;
1420
1421     return client_data; /* result */
1422 }
1423
1424 /* This is nearly the same as in win32_threads.c        */
1425 /*ARGSUSED*/
1426 STATIC void GC_do_blocking_inner(ptr_t data, void * context)
1427 {
1428     struct blocking_data * d = (struct blocking_data *) data;
1429     GC_ASSERT(GC_is_initialized);
1430     GC_ASSERT(GC_blocked_sp == NULL);
1431 #   ifdef SPARC
1432         GC_blocked_sp = GC_save_regs_in_stack();
1433 #   else
1434         GC_blocked_sp = (ptr_t) &d; /* save approx. sp */
1435 #   endif
1436 #   ifdef IA64
1437         GC_blocked_register_sp = GC_save_regs_in_stack();
1438 #   endif
1439
1440     d -> client_data = (d -> fn)(d -> client_data);
1441
1442 #   ifdef SPARC
1443         GC_ASSERT(GC_blocked_sp != NULL);
1444 #   else
1445         GC_ASSERT(GC_blocked_sp == (ptr_t) &d);
1446 #   endif
1447     GC_blocked_sp = NULL;
1448 }
1449
1450 #endif /* !THREADS */
1451
1452 /* Wrapper for functions that are likely to block (or, at least, do not */
1453 /* allocate garbage collected memory and/or manipulate pointers to the  */
1454 /* garbage collected heap) for an appreciable length of time.           */
1455 /* In the single threaded case, GC_do_blocking() (together              */
1456 /* with GC_call_with_gc_active()) might be used to make stack scanning  */
1457 /* more precise (i.e. scan only stack frames of functions that allocate */
1458 /* garbage collected memory and/or manipulate pointers to the garbage   */
1459 /* collected heap).                                                     */
1460 GC_API void * GC_CALL GC_do_blocking(GC_fn_type fn, void * client_data)
1461 {
1462     struct blocking_data my_data;
1463
1464     my_data.fn = fn;
1465     my_data.client_data = client_data;
1466     GC_with_callee_saves_pushed(GC_do_blocking_inner, (ptr_t)(&my_data));
1467     return my_data.client_data; /* result */
1468 }
1469
1470 #if !defined(NO_DEBUGGING)
1471   GC_API void GC_CALL GC_dump(void)
1472   {
1473     GC_printf("***Static roots:\n");
1474     GC_print_static_roots();
1475     GC_printf("\n***Heap sections:\n");
1476     GC_print_heap_sects();
1477     GC_printf("\n***Free blocks:\n");
1478     GC_print_hblkfreelist();
1479     GC_printf("\n***Blocks in use:\n");
1480     GC_print_block_list();
1481   }
1482 #endif /* !NO_DEBUGGING */
1483
1484 /* Getter functions for the public Read-only variables.                 */
1485
1486 /* GC_get_gc_no() is unsynchronized and should be typically called      */
1487 /* inside the context of GC_call_with_alloc_lock() to prevent data      */
1488 /* races (on multiprocessors).                                          */
1489 GC_API GC_word GC_CALL GC_get_gc_no(void)
1490 {
1491     return GC_gc_no;
1492 }
1493
1494 GC_API int GC_CALL GC_get_parallel(void)
1495 {
1496     /* GC_parallel is initialized at start-up.  */
1497     return GC_parallel;
1498 }
1499
1500 /* Setter and getter functions for the public R/W function variables.   */
1501 /* These functions are synchronized (like GC_set_warn_proc() and        */
1502 /* GC_get_warn_proc()).                                                 */
1503
1504 GC_API void GC_CALL GC_set_oom_fn(GC_oom_func fn)
1505 {
1506     GC_ASSERT(fn != 0);
1507     LOCK();
1508     GC_oom_fn = fn;
1509     UNLOCK();
1510 }
1511
1512 GC_API GC_oom_func GC_CALL GC_get_oom_fn(void)
1513 {
1514     GC_oom_func fn;
1515     LOCK();
1516     fn = GC_oom_fn;
1517     UNLOCK();
1518     return fn;
1519 }
1520
1521 GC_API void GC_CALL GC_set_finalizer_notifier(GC_finalizer_notifier_proc fn)
1522 {
1523     /* fn may be 0 (means no finalizer notifier). */
1524     LOCK();
1525     GC_finalizer_notifier = fn;
1526     UNLOCK();
1527 }
1528
1529 GC_API GC_finalizer_notifier_proc GC_CALL GC_get_finalizer_notifier(void)
1530 {
1531     GC_finalizer_notifier_proc fn;
1532     LOCK();
1533     fn = GC_finalizer_notifier;
1534     UNLOCK();
1535     return fn;
1536 }
1537
1538 /* Setter and getter functions for the public numeric R/W variables.    */
1539 /* It is safe to call these functions even before GC_INIT().            */
1540 /* These functions are unsynchronized and should be typically called    */
1541 /* inside the context of GC_call_with_alloc_lock() (if called after     */
1542 /* GC_INIT()) to prevent data races (unless it is guaranteed the        */
1543 /* collector is not multi-threaded at that execution point).            */
1544
1545 GC_API void GC_CALL GC_set_find_leak(int value)
1546 {
1547     /* value is of boolean type. */
1548     GC_find_leak = value;
1549 }
1550
1551 GC_API int GC_CALL GC_get_find_leak(void)
1552 {
1553     return GC_find_leak;
1554 }
1555
1556 GC_API void GC_CALL GC_set_all_interior_pointers(int value)
1557 {
1558     GC_ASSERT(!GC_is_initialized || value == GC_all_interior_pointers);
1559     GC_ASSERT(value == 0 || value == 1);
1560     GC_all_interior_pointers = value;
1561 }
1562
1563 GC_API int GC_CALL GC_get_all_interior_pointers(void)
1564 {
1565     return GC_all_interior_pointers;
1566 }
1567
1568 GC_API void GC_CALL GC_set_finalize_on_demand(int value)
1569 {
1570     GC_ASSERT(value != -1);
1571     /* value is of boolean type. */
1572     GC_finalize_on_demand = value;
1573 }
1574
1575 GC_API int GC_CALL GC_get_finalize_on_demand(void)
1576 {
1577     return GC_finalize_on_demand;
1578 }
1579
1580 GC_API void GC_CALL GC_set_java_finalization(int value)
1581 {
1582     GC_ASSERT(value != -1);
1583     /* value is of boolean type. */
1584     GC_java_finalization = value;
1585 }
1586
1587 GC_API int GC_CALL GC_get_java_finalization(void)
1588 {
1589     return GC_java_finalization;
1590 }
1591
1592 GC_API void GC_CALL GC_set_dont_expand(int value)
1593 {
1594     GC_ASSERT(value != -1);
1595     /* value is of boolean type. */
1596     GC_dont_expand = value;
1597 }
1598
1599 GC_API int GC_CALL GC_get_dont_expand(void)
1600 {
1601     return GC_dont_expand;
1602 }
1603
1604 GC_API void GC_CALL GC_set_no_dls(int value)
1605 {
1606     GC_ASSERT(value != -1);
1607     /* value is of boolean type. */
1608     GC_no_dls = value;
1609 }
1610
1611 GC_API int GC_CALL GC_get_no_dls(void)
1612 {
1613     return GC_no_dls;
1614 }
1615
1616 GC_API void GC_CALL GC_set_non_gc_bytes(GC_word value)
1617 {
1618     GC_non_gc_bytes = value;
1619 }
1620
1621 GC_API GC_word GC_CALL GC_get_non_gc_bytes(void)
1622 {
1623     return GC_non_gc_bytes;
1624 }
1625
1626 GC_API void GC_CALL GC_set_free_space_divisor(GC_word value)
1627 {
1628     GC_ASSERT(value > 0);
1629     GC_free_space_divisor = value;
1630 }
1631
1632 GC_API GC_word GC_CALL GC_get_free_space_divisor(void)
1633 {
1634     return GC_free_space_divisor;
1635 }
1636
1637 GC_API void GC_CALL GC_set_max_retries(GC_word value)
1638 {
1639     GC_ASSERT(value != ~(GC_word)0);
1640     GC_max_retries = value;
1641 }
1642
1643 GC_API GC_word GC_CALL GC_get_max_retries(void)
1644 {
1645     return GC_max_retries;
1646 }
1647
1648 GC_API void GC_CALL GC_set_dont_precollect(int value)
1649 {
1650     GC_ASSERT(value != -1);
1651     /* value is of boolean type. */
1652     GC_dont_precollect = value;
1653 }
1654
1655 GC_API int GC_CALL GC_get_dont_precollect(void)
1656 {
1657     return GC_dont_precollect;
1658 }
1659
1660 GC_API void GC_CALL GC_set_full_freq(int value)
1661 {
1662     GC_ASSERT(value >= 0);
1663     GC_full_freq = value;
1664 }
1665
1666 GC_API int GC_CALL GC_get_full_freq(void)
1667 {
1668     return GC_full_freq;
1669 }
1670
1671 GC_API void GC_CALL GC_set_time_limit(unsigned long value)
1672 {
1673     GC_ASSERT(value != (unsigned long)-1L);
1674     GC_time_limit = value;
1675 }
1676
1677 GC_API unsigned long GC_CALL GC_get_time_limit(void)
1678 {
1679     return GC_time_limit;
1680 }
1681
1682 GC_API void GC_CALL GC_set_force_unmap_on_gcollect(int value)
1683 {
1684     GC_force_unmap_on_gcollect = (GC_bool)value;
1685 }
1686
1687 GC_API int GC_CALL GC_get_force_unmap_on_gcollect(void)
1688 {
1689     return (int)GC_force_unmap_on_gcollect;
1690 }