70ea201843719342d975d81dae82e9477b7eab7c
[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 /* Boehm, July 31, 1995 5:02 pm PDT */
16
17 #include "config.h"
18
19 #include <stdio.h>
20 #include <limits.h>
21 #include <stdarg.h>
22 #ifndef _WIN32_WCE
23 #include <signal.h>
24 #endif
25
26 #define I_HIDE_POINTERS /* To make GC_call_with_alloc_lock visible */
27 #include "private/gc_pmark.h"
28
29 #ifdef GC_SOLARIS_THREADS
30 # include <sys/syscall.h>
31 #endif
32 #if defined(MSWIN32) || defined(MSWINCE)
33 # define WIN32_LEAN_AND_MEAN
34 # define NOSERVICE
35 # include <windows.h>
36 # include <tchar.h>
37 #endif
38
39 #ifdef UNIX_LIKE
40 # include <fcntl.h>
41 # include <sys/types.h>
42 # include <sys/stat.h>
43
44   int GC_log;  /* Forward decl, so we can set it.       */
45 #endif
46
47 #ifdef NONSTOP
48 # include <floss.h>
49 #endif
50
51 #if defined(THREADS) && defined(PCR)
52 # include "il/PCR_IL.h"
53   PCR_Th_ML GC_allocate_ml;
54 #endif
55 /* For other platforms with threads, the lock and possibly              */
56 /* GC_lock_holder variables are defined in the thread support code.     */
57
58 #if defined(NOSYS) || defined(ECOS)
59 #undef STACKBASE
60 #endif
61
62 /* Dont unnecessarily call GC_register_main_static_data() in case       */
63 /* dyn_load.c isn't linked in.                                          */
64 #ifdef DYNAMIC_LOADING
65 # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
66 #else
67 # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
68 #endif
69
70 GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
71
72
73 GC_bool GC_debugging_started = FALSE;
74         /* defined here so we don't have to load debug_malloc.o */
75
76 void (*GC_check_heap) (void) = (void (*) (void))0;
77 void (*GC_print_all_smashed) (void) = (void (*) (void))0;
78
79 void (*GC_start_call_back) (void) = (void (*) (void))0;
80
81 ptr_t GC_stackbottom = 0;
82
83 #ifdef IA64
84   ptr_t GC_register_stackbottom = 0;
85 #endif
86
87 GC_bool GC_dont_gc = 0;
88
89 GC_bool GC_dont_precollect = 0;
90
91 GC_bool GC_quiet = 0;
92
93 #ifndef SMALL_CONFIG
94   GC_bool GC_print_stats = 0;
95 #endif
96
97 GC_bool GC_print_back_height = 0;
98
99 #ifndef NO_DEBUGGING
100   GC_bool GC_dump_regularly = 0;  /* Generate regular debugging dumps. */
101 #endif
102
103 #ifdef KEEP_BACK_PTRS
104   long GC_backtraces = 0;       /* Number of random backtraces to       */
105                                 /* generate for each GC.                */
106 #endif
107
108 #ifdef FIND_LEAK
109   int GC_find_leak = 1;
110 #else
111   int GC_find_leak = 0;
112 #endif
113
114 #ifdef ALL_INTERIOR_POINTERS
115   int GC_all_interior_pointers = 1;
116 #else
117   int GC_all_interior_pointers = 0;
118 #endif
119
120 long GC_large_alloc_warn_interval = 5;
121         /* Interval between unsuppressed warnings.      */
122
123 long GC_large_alloc_warn_suppressed = 0;
124         /* Number of warnings suppressed so far.        */
125
126 /*ARGSUSED*/
127 void * GC_default_oom_fn(size_t bytes_requested)
128 {
129     return(0);
130 }
131
132 void * (*GC_oom_fn) (size_t bytes_requested) = GC_default_oom_fn;
133
134 void * GC_project2(void *arg1, void *arg2)
135 {
136   return arg2;
137 }
138
139 /* Set things up so that GC_size_map[i] >= granules(i),         */
140 /* but not too much bigger                                              */
141 /* and so that size_map contains relatively few distinct entries        */
142 /* This was originally stolen from Russ Atkinson's Cedar                */
143 /* quantization alogrithm (but we precompute it).                       */ 
144 void GC_init_size_map(void)
145 {
146     int i;
147
148     /* Map size 0 to something bigger.                  */
149     /* This avoids problems at lower levels.            */
150       GC_size_map[0] = 1;
151     for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
152         GC_size_map[i] = ROUNDED_UP_GRANULES(i);
153         GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
154     }
155     /* We leave the rest of the array to be filled in on demand. */
156 }
157
158 /* Fill in additional entries in GC_size_map, including the ith one */
159 /* We assume the ith entry is currently 0.                              */
160 /* Note that a filled in section of the array ending at n always    */
161 /* has length at least n/4.                                             */
162 void GC_extend_size_map(size_t i)
163 {
164     size_t orig_granule_sz = ROUNDED_UP_GRANULES(i);
165     size_t granule_sz = orig_granule_sz;
166     size_t byte_sz = GRANULES_TO_BYTES(granule_sz);
167                         /* The size we try to preserve.         */
168                         /* Close to i, unless this would        */
169                         /* introduce too many distinct sizes.   */
170     size_t smaller_than_i = byte_sz - (byte_sz >> 3);
171     size_t much_smaller_than_i = byte_sz - (byte_sz >> 2);
172     size_t low_limit;   /* The lowest indexed entry we  */
173                         /* initialize.                  */
174     size_t j;
175     
176     if (GC_size_map[smaller_than_i] == 0) {
177         low_limit = much_smaller_than_i;
178         while (GC_size_map[low_limit] != 0) low_limit++;
179     } else {
180         low_limit = smaller_than_i + 1;
181         while (GC_size_map[low_limit] != 0) low_limit++;
182         granule_sz = ROUNDED_UP_GRANULES(low_limit);
183         granule_sz += granule_sz >> 3;
184         if (granule_sz < orig_granule_sz) granule_sz = orig_granule_sz;
185     }
186     /* For these larger sizes, we use an even number of granules.       */
187     /* This makes it easier to, for example, construct a 16byte-aligned */
188     /* allocator even if GRANULE_BYTES is 8.                            */
189         granule_sz += 1;
190         granule_sz &= ~1;
191     if (granule_sz > MAXOBJGRANULES) {
192         granule_sz = MAXOBJGRANULES;
193     }
194     /* If we can fit the same number of larger objects in a block,      */
195     /* do so.                                                   */ 
196     {
197         size_t number_of_objs = HBLK_GRANULES/granule_sz;
198         granule_sz = HBLK_GRANULES/number_of_objs;
199         granule_sz &= ~1;
200     }
201     byte_sz = GRANULES_TO_BYTES(granule_sz);
202     /* We may need one extra byte;                      */
203     /* don't always fill in GC_size_map[byte_sz]        */
204     byte_sz -= EXTRA_BYTES;
205
206     for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = granule_sz;  
207 }
208
209
210 /*
211  * The following is a gross hack to deal with a problem that can occur
212  * on machines that are sloppy about stack frame sizes, notably SPARC.
213  * Bogus pointers may be written to the stack and not cleared for
214  * a LONG time, because they always fall into holes in stack frames
215  * that are not written.  We partially address this by clearing
216  * sections of the stack whenever we get control.
217  */
218 word GC_stack_last_cleared = 0; /* GC_no when we last did this */
219 # ifdef THREADS
220 #   define BIG_CLEAR_SIZE 2048  /* Clear this much now and then.        */
221 #   define SMALL_CLEAR_SIZE 256 /* Clear this much every time.          */
222 # endif
223 # define CLEAR_SIZE 213  /* Granularity for GC_clear_stack_inner */
224 # define DEGRADE_RATE 50
225
226 ptr_t GC_min_sp;        /* Coolest stack pointer value from which we've */
227                         /* already cleared the stack.                   */
228                         
229 ptr_t GC_high_water;
230                         /* "hottest" stack pointer value we have seen   */
231                         /* recently.  Degrades over time.               */
232
233 word GC_bytes_allocd_at_reset;
234
235 #if defined(ASM_CLEAR_CODE)
236   extern void *GC_clear_stack_inner(void *, ptr_t);
237 #else  
238 /* Clear the stack up to about limit.  Return arg. */
239 /*ARGSUSED*/
240 void * GC_clear_stack_inner(void *arg, ptr_t limit)
241 {
242     word dummy[CLEAR_SIZE];
243     
244     BZERO(dummy, CLEAR_SIZE*sizeof(word));
245     if ((ptr_t)(dummy) COOLER_THAN limit) {
246         (void) GC_clear_stack_inner(arg, limit);
247     }
248     /* Make sure the recursive call is not a tail call, and the bzero   */
249     /* call is not recognized as dead code.                             */
250     GC_noop1((word)dummy);
251     return(arg);
252 }
253 #endif
254
255 /* Clear some of the inaccessible part of the stack.  Returns its       */
256 /* argument, so it can be used in a tail call position, hence clearing  */
257 /* another frame.                                                       */
258 void * GC_clear_stack(void *arg)
259 {
260     ptr_t sp = GC_approx_sp();  /* Hotter than actual sp */
261 #   ifdef THREADS
262         word dummy[SMALL_CLEAR_SIZE];
263         static unsigned random_no = 0;
264                                  /* Should be more random than it is ... */
265                                  /* Used to occasionally clear a bigger  */
266                                  /* chunk.                               */
267 #   endif
268     ptr_t limit;
269     
270 #   define SLOP 400
271         /* Extra bytes we clear every time.  This clears our own        */
272         /* activation record, and should cause more frequent            */
273         /* clearing near the cold end of the stack, a good thing.       */
274 #   define GC_SLOP 4000
275         /* We make GC_high_water this much hotter than we really saw    */
276         /* saw it, to cover for GC noise etc. above our current frame.  */
277 #   define CLEAR_THRESHOLD 100000
278         /* We restart the clearing process after this many bytes of     */
279         /* allocation.  Otherwise very heavily recursive programs       */
280         /* with sparse stacks may result in heaps that grow almost      */
281         /* without bounds.  As the heap gets larger, collection         */
282         /* frequency decreases, thus clearing frequency would decrease, */
283         /* thus more junk remains accessible, thus the heap gets        */
284         /* larger ...                                                   */
285 # ifdef THREADS
286     if (++random_no % 13 == 0) {
287         limit = sp;
288         MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
289         limit = (ptr_t)((word)limit & ~0xf);
290                         /* Make it sufficiently aligned for assembly    */
291                         /* implementations of GC_clear_stack_inner.     */
292         return GC_clear_stack_inner(arg, limit);
293     } else {
294         BZERO(dummy, SMALL_CLEAR_SIZE*sizeof(word));
295         return arg;
296     }
297 # else
298     if (GC_gc_no > GC_stack_last_cleared) {
299         /* Start things over, so we clear the entire stack again */
300         if (GC_stack_last_cleared == 0) GC_high_water = (ptr_t)GC_stackbottom;
301         GC_min_sp = GC_high_water;
302         GC_stack_last_cleared = GC_gc_no;
303         GC_bytes_allocd_at_reset = GC_bytes_allocd;
304     }
305     /* Adjust GC_high_water */
306         MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
307         if (sp HOTTER_THAN GC_high_water) {
308             GC_high_water = sp;
309         }
310         MAKE_HOTTER(GC_high_water, GC_SLOP);
311     limit = GC_min_sp;
312     MAKE_HOTTER(limit, SLOP);
313     if (sp COOLER_THAN limit) {
314         limit = (ptr_t)((word)limit & ~0xf);
315                         /* Make it sufficiently aligned for assembly    */
316                         /* implementations of GC_clear_stack_inner.     */
317         GC_min_sp = sp;
318         return(GC_clear_stack_inner(arg, limit));
319     } else if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) {
320         /* Restart clearing process, but limit how much clearing we do. */
321         GC_min_sp = sp;
322         MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
323         if (GC_min_sp HOTTER_THAN GC_high_water) GC_min_sp = GC_high_water;
324         GC_bytes_allocd_at_reset = GC_bytes_allocd;
325     }  
326     return(arg);
327 # endif
328 }
329
330
331 /* Return a pointer to the base address of p, given a pointer to a      */
332 /* an address within an object.  Return 0 o.w.                          */
333 void * GC_base(void * p)
334 {
335     ptr_t r;
336     struct hblk *h;
337     bottom_index *bi;
338     hdr *candidate_hdr;
339     ptr_t limit;
340     
341     r = p;
342     if (!GC_is_initialized) return 0;
343     h = HBLKPTR(r);
344     GET_BI(r, bi);
345     candidate_hdr = HDR_FROM_BI(bi, r);
346     if (candidate_hdr == 0) return(0);
347     /* If it's a pointer to the middle of a large object, move it       */
348     /* to the beginning.                                                */
349         while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
350            h = FORWARDED_ADDR(h,candidate_hdr);
351            r = (ptr_t)h;
352            candidate_hdr = HDR(h);
353         }
354     if (HBLK_IS_FREE(candidate_hdr)) return(0);
355     /* Make sure r points to the beginning of the object */
356         r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
357         {
358             size_t offset = HBLKDISPL(r);
359             signed_word sz = candidate_hdr -> hb_sz;
360             size_t obj_displ = offset % sz;
361
362             r -= obj_displ;
363             limit = r + sz;
364             if (limit > (ptr_t)(h + 1) && sz <= HBLKSIZE) {
365                 return(0);
366             }
367             if ((ptr_t)p >= limit) return(0);
368         }
369     return((void *)r);
370 }
371
372
373 /* Return the size of an object, given a pointer to its base.           */
374 /* (For small obects this also happens to work from interior pointers,  */
375 /* but that shouldn't be relied upon.)                                  */
376 size_t GC_size(void * p)
377 {
378     hdr * hhdr = HDR(p);
379     
380     return hhdr -> hb_sz;
381 }
382
383 size_t GC_get_heap_size(void)
384 {
385     return GC_heapsize;
386 }
387
388 size_t GC_get_free_bytes(void)
389 {
390     return GC_large_free_bytes;
391 }
392
393 size_t GC_get_bytes_since_gc(void)
394 {
395     return GC_bytes_allocd;
396 }
397
398 size_t GC_get_total_bytes(void)
399 {
400     return GC_bytes_allocd+GC_bytes_allocd_before_gc;
401 }
402
403 GC_bool GC_is_initialized = FALSE;
404
405 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
406   extern void GC_init_parallel(void);
407 # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
408
409 /* FIXME: The GC_init/GC_init_inner distinction should go away. */
410 void GC_init(void)
411 {
412     /* LOCK(); -- no longer does anything this early. */
413     GC_init_inner();
414     /* UNLOCK(); */
415 }
416
417 #if defined(MSWIN32) || defined(MSWINCE)
418     CRITICAL_SECTION GC_write_cs;
419 #endif
420
421 #ifdef MSWIN32
422     extern void GC_init_win32(void);
423 #endif
424
425 extern void GC_setpagesize();
426
427 #ifdef MSWIN32
428 extern GC_bool GC_no_win32_dlls;
429 #else
430 # define GC_no_win32_dlls FALSE
431 #endif
432
433 void GC_exit_check(void)
434 {
435    GC_gcollect();
436 }
437
438 #ifdef SEARCH_FOR_DATA_START
439   extern void GC_init_linux_data_start(void);
440 #endif
441
442 #ifdef UNIX_LIKE
443
444 extern void GC_set_and_save_fault_handler(void (*handler)(int));
445
446 static void looping_handler(sig)
447 int sig;
448 {
449     GC_err_printf("Caught signal %d: looping in handler\n", sig);
450     for(;;);
451 }
452
453 static GC_bool installed_looping_handler = FALSE;
454
455 static void maybe_install_looping_handler()
456 {
457     /* Install looping handler before the write fault handler, so we    */
458     /* handle write faults correctly.                                   */
459       if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
460         GC_set_and_save_fault_handler(looping_handler);
461         installed_looping_handler = TRUE;
462       }
463 }
464
465 #else /* !UNIX_LIKE */
466
467 # define maybe_install_looping_handler()
468
469 #endif
470
471 #if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
472   void GC_thr_init(void);
473 #endif
474
475 void GC_init_inner()
476 {
477 #   if !defined(THREADS) && defined(GC_ASSERTIONS)
478         word dummy;
479 #   endif
480     word initial_heap_sz = (word)MINHINCR;
481     
482     if (GC_is_initialized) return;
483
484     /* Note that although we are nominally called with the */
485     /* allocation lock held, the allocation lock is now    */
486     /* only really acquired once a second thread is forked.*/
487     /* And the initialization code needs to run before     */
488     /* then.  Thus we really don't hold any locks, and can */
489     /* in fact safely initialize them here.                */
490 #   ifdef THREADS
491       GC_ASSERT(!GC_need_to_lock);
492 #   endif
493 #   if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
494       if (!GC_is_initialized) {
495         BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL;
496         HMODULE hK32 = GetModuleHandleA("kernel32.dll");
497         if (hK32)
498           pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD))
499                 GetProcAddress (hK32,
500                                 "InitializeCriticalSectionAndSpinCount");
501         if (pfn)
502             pfn(&GC_allocate_ml, 4000);
503         else
504           InitializeCriticalSection (&GC_allocate_ml);
505       }
506 #endif /* MSWIN32 */
507 #   if defined(MSWIN32) || defined(MSWINCE)
508       InitializeCriticalSection(&GC_write_cs);
509 #   endif
510 #   if (!defined(SMALL_CONFIG))
511       if (0 != GETENV("GC_PRINT_STATS")) {
512         GC_print_stats = 1;
513       } 
514       if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
515         GC_print_stats = VERBOSE;
516       } 
517 #     if defined(UNIX_LIKE)
518         {
519           char * file_name = GETENV("GC_LOG_FILE");
520           if (0 != file_name) {
521             int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666);
522             if (log_d < 0) {
523               GC_log_printf("Failed to open %s as log file\n", file_name);
524             } else {
525               GC_log = log_d;
526             }
527           }
528         }
529 #     endif
530 #   endif
531 #   ifndef NO_DEBUGGING
532       if (0 != GETENV("GC_DUMP_REGULARLY")) {
533         GC_dump_regularly = 1;
534       }
535 #   endif
536 #   ifdef KEEP_BACK_PTRS
537       {
538         char * backtraces_string = GETENV("GC_BACKTRACES");
539         if (0 != backtraces_string) {
540           GC_backtraces = atol(backtraces_string);
541           if (backtraces_string[0] == '\0') GC_backtraces = 1;
542         }
543       }
544 #   endif
545     if (0 != GETENV("GC_FIND_LEAK")) {
546       GC_find_leak = 1;
547       atexit(GC_exit_check);
548     }
549     if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
550       GC_all_interior_pointers = 1;
551     }
552     if (0 != GETENV("GC_DONT_GC")) {
553       GC_dont_gc = 1;
554     }
555     if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
556       GC_print_back_height = 1;
557     }
558     if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
559       GC_large_alloc_warn_interval = LONG_MAX;
560     }
561     {
562       char * addr_string = GETENV("GC_TRACE");
563       if (0 != addr_string) {
564 #       ifndef ENABLE_TRACE
565           WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
566 #       else
567 #         ifdef STRTOULL
568             long long addr = strtoull(addr_string, NULL, 16);
569 #         else
570             long addr = strtoul(addr_string, NULL, 16);
571 #         endif
572           if (addr < 0x1000)
573               WARN("Unlikely trace address: 0x%lx\n", (GC_word)addr);
574           GC_trace_addr = (ptr_t)addr;
575 #       endif
576       }
577     }
578     {
579       char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
580       if (0 != time_limit_string) {
581         long time_limit = atol(time_limit_string);
582         if (time_limit < 5) {
583           WARN("GC_PAUSE_TIME_TARGET environment variable value too small "
584                "or bad syntax: Ignoring\n", 0);
585         } else {
586           GC_time_limit = time_limit;
587         }
588       }
589     }
590     {
591       char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
592       if (0 != interval_string) {
593         long interval = atol(interval_string);
594         if (interval <= 0) {
595           WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
596                "bad value: Ignoring\n", 0);
597         } else {
598           GC_large_alloc_warn_interval = interval;
599         }
600       }
601     }
602     maybe_install_looping_handler();
603     /* Adjust normal object descriptor for extra allocation.    */
604     if (ALIGNMENT > GC_DS_TAGS && EXTRA_BYTES != 0) {
605       GC_obj_kinds[NORMAL].ok_descriptor = ((word)(-ALIGNMENT) | GC_DS_LENGTH);
606     }
607     GC_setpagesize();
608     GC_exclude_static_roots(beginGC_arrays, endGC_arrays);
609     GC_exclude_static_roots(beginGC_obj_kinds, endGC_obj_kinds);
610 #   ifdef SEPARATE_GLOBALS
611       GC_exclude_static_roots(beginGC_objfreelist, endGC_objfreelist);
612       GC_exclude_static_roots(beginGC_aobjfreelist, endGC_aobjfreelist);
613 #   endif
614 #   ifdef MSWIN32
615         GC_init_win32();
616 #   endif
617 #   if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
618         WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
619         /* If thread stacks are cached, they tend to be scanned in      */
620         /* entirety as part of the root set.  This wil grow them to     */
621         /* maximum size, and is generally not desirable.                */
622 #   endif
623 #   if defined(SEARCH_FOR_DATA_START)
624         GC_init_linux_data_start();
625 #   endif
626 #   if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
627         GC_init_netbsd_elf();
628 #   endif
629 #   if !defined(THREADS) || defined(GC_PTHREADS) || defined(GC_WIN32_THREADS) \
630         || defined(GC_SOLARIS_THREADS)
631       if (GC_stackbottom == 0) {
632         GC_stackbottom = GC_get_main_stack_base();
633 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
634           GC_register_stackbottom = GC_get_register_stack_base();
635 #       endif
636       } else {
637 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
638           if (GC_register_stackbottom == 0) {
639             WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
640             /* The following may fail, since we may rely on             */
641             /* alignment properties that may not hold with a user set   */
642             /* GC_stackbottom.                                          */
643             GC_register_stackbottom = GC_get_register_stack_base();
644           }
645 #       endif
646       }
647 #   endif
648     /* Ignore gcc -Wall warnings on the following. */
649     GC_STATIC_ASSERT(sizeof (ptr_t) == sizeof(word));
650     GC_STATIC_ASSERT(sizeof (signed_word) == sizeof(word));
651     GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
652 #   ifndef THREADS
653 #     ifdef STACK_GROWS_DOWN
654         GC_ASSERT((word)(&dummy) <= (word)GC_stackbottom);
655 #     else
656         GC_ASSERT((word)(&dummy) >= (word)GC_stackbottom);
657 #     endif
658 #   endif
659 #   if !defined(_AUX_SOURCE) || defined(__GNUC__)
660       GC_ASSERT((word)(-1) > (word)0);
661       /* word should be unsigned */
662 #   endif
663     GC_ASSERT((ptr_t)(word)(-1) > (ptr_t)0);
664         /* Ptr_t comparisons should behave as unsigned comparisons.     */
665     GC_ASSERT((signed_word)(-1) < (signed_word)0);
666 #   if !defined(SMALL_CONFIG)
667       if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
668         /* This used to test for !GC_no_win32_dlls.  Why? */
669         GC_setpagesize();
670         /* For GWW_MPROTECT on Win32, this needs to happen before any   */
671         /* heap memory is allocated.                                    */
672         GC_dirty_init();
673         GC_ASSERT(GC_bytes_allocd == 0)
674         GC_incremental = TRUE;
675       }
676 #   endif /* !SMALL_CONFIG */
677     
678     /* Add initial guess of root sets.  Do this first, since sbrk(0)    */
679     /* might be used.                                                   */
680       if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
681     GC_init_headers();
682     GC_bl_init();
683     GC_mark_init();
684     {
685         char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
686         if (sz_str != NULL) {
687           initial_heap_sz = atoi(sz_str);
688           if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
689             WARN("Bad initial heap size %s - ignoring it.\n",
690                  sz_str);
691           } 
692           initial_heap_sz = divHBLKSZ(initial_heap_sz);
693         }
694     }
695     {
696         char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
697         if (sz_str != NULL) {
698           word max_heap_sz = (word)atol(sz_str);
699           if (max_heap_sz < initial_heap_sz * HBLKSIZE) {
700             WARN("Bad maximum heap size %s - ignoring it.\n",
701                  sz_str);
702           } 
703           if (0 == GC_max_retries) GC_max_retries = 2;
704           GC_set_max_heap_size(max_heap_sz);
705         }
706     }
707     if (!GC_expand_hp_inner(initial_heap_sz)) {
708         GC_err_printf("Can't start up: not enough memory\n");
709         EXIT();
710     }
711     GC_initialize_offsets();
712     GC_register_displacement_inner(0L);
713 #   if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
714       if (!GC_all_interior_pointers) {
715         /* TLS ABI uses pointer-sized offsets for dtv. */
716         GC_register_displacement_inner(sizeof(void *));
717       }
718 #   endif
719     GC_init_size_map();
720 #   ifdef PCR
721       if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
722           != PCR_ERes_okay) {
723           ABORT("Can't lock load state\n");
724       } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
725           ABORT("Can't unlock load state\n");
726       }
727       PCR_IL_Unlock();
728       GC_pcr_install();
729 #   endif
730     GC_is_initialized = TRUE;
731 #   if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
732         GC_thr_init();
733 #   endif
734     COND_DUMP;
735     /* Get black list set up and/or incremental GC started */
736       if (!GC_dont_precollect || GC_incremental) GC_gcollect_inner();
737 #   ifdef STUBBORN_ALLOC
738         GC_stubborn_init();
739 #   endif
740     /* Convince lint that some things are used */
741 #   ifdef LINT
742       {
743           extern char * GC_copyright[];
744           extern int GC_read();
745           extern void GC_register_finalizer_no_order();
746           
747           GC_noop(GC_copyright, GC_find_header,
748                   GC_push_one, GC_call_with_alloc_lock, GC_read,
749                   GC_dont_expand,
750 #                 ifndef NO_DEBUGGING
751                     GC_dump,
752 #                 endif
753                   GC_register_finalizer_no_order);
754       }
755 #   endif
756
757     /* The rest of this again assumes we don't really hold      */
758     /* the allocation lock.                                     */
759 #   if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
760         /* Make sure marker threads and started and thread local */
761         /* allocation is initialized, in case we didn't get      */
762         /* called from GC_init_parallel();                       */
763         {
764           GC_init_parallel();
765         }
766 #   endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
767
768 #   if defined(DYNAMIC_LOADING) && defined(DARWIN)
769     {
770         /* This must be called WITHOUT the allocation lock held
771         and before any threads are created */
772         extern void GC_init_dyld();
773         GC_init_dyld();
774     }
775 #   endif
776 }
777
778 void GC_enable_incremental(void)
779 {
780 # if !defined(SMALL_CONFIG) && !defined(KEEP_BACK_PTRS)
781   /* If we are keeping back pointers, the GC itself dirties all */
782   /* pages on which objects have been marked, making            */
783   /* incremental GC pointless.                                  */
784   if (!GC_find_leak) {
785     DCL_LOCK_STATE;
786     
787     LOCK();
788     if (GC_incremental) goto out;
789     GC_setpagesize();
790     /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
791     maybe_install_looping_handler();  /* Before write fault handler! */
792     GC_incremental = TRUE;
793     if (!GC_is_initialized) {
794         GC_init_inner();
795     } else {
796         GC_dirty_init();
797     }
798     if (!GC_dirty_maintained) goto out;
799     if (GC_dont_gc) {
800         /* Can't easily do it. */
801         UNLOCK();
802         return;
803     }
804     if (GC_bytes_allocd > 0) {
805         /* There may be unmarked reachable objects      */
806         GC_gcollect_inner();
807     }   /* else we're OK in assuming everything's       */
808         /* clean since nothing can point to an          */
809         /* unmarked object.                             */
810     GC_read_dirty();
811 out:
812     UNLOCK();
813   } else {
814     GC_init();
815   }
816 # else
817     GC_init();
818 # endif
819 }
820
821
822 #if defined(MSWIN32) || defined(MSWINCE)
823 # if defined(_MSC_VER) && defined(_DEBUG)
824 #  include <crtdbg.h>
825 # endif
826 # ifdef OLD_WIN32_LOG_FILE
827 #   define LOG_FILE _T("gc.log")
828 # endif
829
830   HANDLE GC_stdout = 0;
831
832   void GC_deinit()
833   {
834       if (GC_is_initialized) {
835         DeleteCriticalSection(&GC_write_cs);
836       }
837   }
838
839 # ifndef THREADS
840 #   define GC_need_to_lock 0  /* Not defined without threads */
841 # endif
842   int GC_write(const char *buf, size_t len)
843   {
844       BOOL tmp;
845       DWORD written;
846       if (len == 0)
847           return 0;
848       if (GC_need_to_lock) EnterCriticalSection(&GC_write_cs);
849       if (GC_stdout == INVALID_HANDLE_VALUE) {
850           if (GC_need_to_lock) LeaveCriticalSection(&GC_write_cs);
851           return -1;
852       } else if (GC_stdout == 0) {
853         char * file_name = GETENV("GC_LOG_FILE");
854         char logPath[_MAX_PATH + 5];
855
856         if (0 == file_name) {
857 #         ifdef OLD_WIN32_LOG_FILE
858             strcpy(logPath, LOG_FILE);
859 #         else
860             GetModuleFileName(NULL, logPath, _MAX_PATH);
861             strcat(logPath, ".log");
862 #         endif
863           file_name = logPath;
864         }
865         GC_stdout = CreateFile(logPath, GENERIC_WRITE,
866                                FILE_SHARE_READ,
867                                NULL, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH,
868                                NULL); 
869         if (GC_stdout == INVALID_HANDLE_VALUE)
870             ABORT("Open of log file failed");
871       }
872       tmp = WriteFile(GC_stdout, buf, (DWORD)len, &written, NULL);
873       if (!tmp)
874           DebugBreak();
875 #     if defined(_MSC_VER) && defined(_DEBUG)
876           _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
877 #     endif
878       if (GC_need_to_lock) LeaveCriticalSection(&GC_write_cs);
879       return tmp ? (int)written : -1;
880   }
881 # undef GC_need_to_lock
882
883 #endif
884
885 #if defined(OS2) || defined(MACOS)
886 FILE * GC_stdout = NULL;
887 FILE * GC_stderr = NULL;
888 FILE * GC_log = NULL;
889 int GC_tmp;  /* Should really be local ... */
890
891   void GC_set_files()
892   {
893       if (GC_stdout == NULL) {
894         GC_stdout = stdout;
895     }
896     if (GC_stderr == NULL) {
897         GC_stderr = stderr;
898     }
899     if (GC_log == NULL) {
900         GC_log = stderr;
901     }
902   }
903 #endif
904
905 #if !defined(OS2) && !defined(MACOS) && !defined(MSWIN32) && !defined(MSWINCE)
906   int GC_stdout = 1;
907   int GC_stderr = 2;
908   int GC_log = 2;
909 # if !defined(AMIGA)
910 #   include <unistd.h>
911 # endif
912 #endif
913
914 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(OS2) \
915     && !defined(MACOS)  && !defined(ECOS) && !defined(NOSYS)
916 int GC_write(fd, buf, len)
917 int fd;
918 const char *buf;
919 size_t len;
920 {
921      register int bytes_written = 0;
922      register int result;
923      
924      while (bytes_written < len) {
925 #       ifdef GC_SOLARIS_THREADS
926             result = syscall(SYS_write, fd, buf + bytes_written,
927                                             len - bytes_written);
928 #       else
929             result = write(fd, buf + bytes_written, len - bytes_written);
930 #       endif
931         if (-1 == result) return(result);
932         bytes_written += result;
933     }
934     return(bytes_written);
935 }
936 #endif /* UN*X */
937
938 #ifdef ECOS
939 int GC_write(fd, buf, len)
940 {
941   _Jv_diag_write (buf, len);
942   return len;
943 }
944 #endif
945
946 #ifdef NOSYS
947 int GC_write(fd, buf, len)
948 {
949   /* No writing.  */
950   return len;
951 }
952 #endif
953
954
955 #if defined(MSWIN32) || defined(MSWINCE)
956     /* FIXME: This is pretty ugly ... */
957 #   define WRITE(f, buf, len) GC_write(buf, len)
958 #else
959 #   if defined(OS2) || defined(MACOS)
960 #   define WRITE(f, buf, len) (GC_set_files(), \
961                                GC_tmp = fwrite((buf), 1, (len), (f)), \
962                                fflush(f), GC_tmp)
963 #   else
964 #     define WRITE(f, buf, len) GC_write((f), (buf), (len))
965 #   endif
966 #endif
967
968 #define BUFSZ 1024
969 #ifdef _MSC_VER
970 # define vsnprintf _vsnprintf
971 #endif
972 /* A version of printf that is unlikely to call malloc, and is thus safer */
973 /* to call from the collector in case malloc has been bound to GC_malloc. */
974 /* Floating point arguments ans formats should be avoided, since fp       */
975 /* conversion is more likely to allocate.                                 */
976 /* Assumes that no more than BUFSZ-1 characters are written at once.      */
977 void GC_printf(const char *format, ...)
978 {
979     va_list args;
980     char buf[BUFSZ+1];
981     
982     va_start(args, format);
983     if (GC_quiet) return;
984     buf[BUFSZ] = 0x15;
985     (void) vsnprintf(buf, BUFSZ, format, args);
986     va_end(args);
987     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
988     if (WRITE(GC_stdout, buf, strlen(buf)) < 0) ABORT("write to stdout failed");
989 }
990
991 void GC_err_printf(const char *format, ...)
992 {
993     va_list args;
994     char buf[BUFSZ+1];
995     
996     va_start(args, format);
997     buf[BUFSZ] = 0x15;
998     (void) vsnprintf(buf, BUFSZ, format, args);
999     va_end(args);
1000     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1001     if (WRITE(GC_stderr, buf, strlen(buf)) < 0) ABORT("write to stderr failed");
1002 }
1003
1004 void GC_log_printf(const char *format, ...)
1005 {
1006     va_list args;
1007     char buf[BUFSZ+1];
1008     
1009     va_start(args, format);
1010     buf[BUFSZ] = 0x15;
1011     (void) vsnprintf(buf, BUFSZ, format, args);
1012     va_end(args);
1013     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1014     if (WRITE(GC_log, buf, strlen(buf)) < 0) ABORT("write to log failed");
1015 }
1016
1017 void GC_err_puts(const char *s)
1018 {
1019     if (WRITE(GC_stderr, s, strlen(s)) < 0) ABORT("write to stderr failed");
1020 }
1021
1022 #if defined(LINUX) && !defined(SMALL_CONFIG)
1023 void GC_err_write(buf, len)
1024 const char *buf;
1025 size_t len;
1026 {
1027     if (WRITE(GC_stderr, buf, len) < 0) ABORT("write to stderr failed");
1028 }
1029 #endif
1030
1031 void GC_default_warn_proc(char *msg, GC_word arg)
1032 {
1033     GC_err_printf(msg, arg);
1034 }
1035
1036 GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1037
1038 GC_warn_proc GC_set_warn_proc(GC_warn_proc p)
1039 {
1040     GC_warn_proc result;
1041
1042 #   ifdef GC_WIN32_THREADS
1043       GC_ASSERT(GC_is_initialized);
1044 #   endif
1045     LOCK();
1046     result = GC_current_warn_proc;
1047     GC_current_warn_proc = p;
1048     UNLOCK();
1049     return(result);
1050 }
1051
1052 GC_word GC_set_free_space_divisor (GC_word value)
1053 {
1054     GC_word old = GC_free_space_divisor;
1055     GC_free_space_divisor = value;
1056     return old;
1057 }
1058
1059 #ifndef PCR
1060 void GC_abort(const char *msg)
1061 {
1062 #   if defined(MSWIN32)
1063       (void) MessageBoxA(NULL, msg, "Fatal error in gc", MB_ICONERROR|MB_OK);
1064 #   else
1065       GC_err_printf("%s\n", msg);
1066 #   endif
1067     if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1068             /* In many cases it's easier to debug a running process.    */
1069             /* It's arguably nicer to sleep, but that makes it harder   */
1070             /* to look at the thread if the debugger doesn't know much  */
1071             /* about threads.                                           */
1072             for(;;) {}
1073     }
1074 #   if defined(MSWIN32) || defined(MSWINCE)
1075         DebugBreak();
1076 #   else
1077         (void) abort();
1078 #   endif
1079 }
1080 #endif
1081
1082 void GC_enable()
1083 {
1084     LOCK();
1085     GC_dont_gc--;
1086     UNLOCK();
1087 }
1088
1089 void GC_disable()
1090 {
1091     LOCK();
1092     GC_dont_gc++;
1093     UNLOCK();
1094 }
1095
1096 /* Helper procedures for new kind creation.     */
1097 void ** GC_new_free_list_inner()
1098 {
1099     void *result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1)*sizeof(ptr_t),
1100                                       PTRFREE);
1101     if (result == 0) ABORT("Failed to allocate freelist for new kind");
1102     BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
1103     return result;
1104 }
1105
1106 void ** GC_new_free_list()
1107 {
1108     void *result;
1109     LOCK();
1110     result = GC_new_free_list_inner();
1111     UNLOCK();
1112     return result;
1113 }
1114
1115 unsigned GC_new_kind_inner(void **fl, GC_word descr, int adjust, int clear)
1116 {
1117     unsigned result = GC_n_kinds++;
1118
1119     if (GC_n_kinds > MAXOBJKINDS) ABORT("Too many kinds");
1120     GC_obj_kinds[result].ok_freelist = fl;
1121     GC_obj_kinds[result].ok_reclaim_list = 0;
1122     GC_obj_kinds[result].ok_descriptor = descr;
1123     GC_obj_kinds[result].ok_relocate_descr = adjust;
1124     GC_obj_kinds[result].ok_init = clear;
1125     return result;
1126 }
1127
1128 unsigned GC_new_kind(void **fl, GC_word descr, int adjust, int clear)
1129 {
1130     unsigned result;
1131     LOCK();
1132     result = GC_new_kind_inner(fl, descr, adjust, clear);
1133     UNLOCK();
1134     return result;
1135 }
1136
1137 unsigned GC_new_proc_inner(GC_mark_proc proc)
1138 {
1139     unsigned result = GC_n_mark_procs++;
1140
1141     if (GC_n_mark_procs > MAX_MARK_PROCS) ABORT("Too many mark procedures");
1142     GC_mark_procs[result] = proc;
1143     return result;
1144 }
1145
1146 unsigned GC_new_proc(GC_mark_proc proc)
1147 {
1148     unsigned result;
1149     LOCK();
1150     result = GC_new_proc_inner(proc);
1151     UNLOCK();
1152     return result;
1153 }
1154
1155 GC_API void * GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
1156 {
1157     int dummy;
1158     struct GC_stack_base base;
1159
1160     base.mem_base = (void *)&dummy;
1161 #   ifdef IA64
1162       base.reg_base = (void *)GC_save_regs_in_stack();
1163       /* Unnecessarily flushes register stack,          */
1164       /* but that probably doesn't hurt.                */
1165 #   endif
1166     return fn(&base, arg);
1167 }
1168
1169 #if !defined(NO_DEBUGGING)
1170
1171 void GC_dump()
1172 {
1173     GC_printf("***Static roots:\n");
1174     GC_print_static_roots();
1175     GC_printf("\n***Heap sections:\n");
1176     GC_print_heap_sects();
1177     GC_printf("\n***Free blocks:\n");
1178     GC_print_hblkfreelist();
1179     GC_printf("\n***Blocks in use:\n");
1180     GC_print_block_list();
1181     GC_printf("\n***Finalization statistics:\n");
1182     GC_print_finalization_stats();
1183 }
1184
1185 #endif /* NO_DEBUGGING */