Clean merge -> gc7-branch
[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 void GC_init(void)
410 {
411     DCL_LOCK_STATE;
412     
413 #if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
414     if (!GC_is_initialized) {
415       BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL;
416       HMODULE hK32 = GetModuleHandleA("kernel32.dll");
417       if (hK32)
418           pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD))
419                 GetProcAddress (hK32,
420                                 "InitializeCriticalSectionAndSpinCount");
421       if (pfn)
422           pfn(&GC_allocate_ml, 4000);
423       else
424           InitializeCriticalSection (&GC_allocate_ml);
425     }
426 #endif /* MSWIN32 */
427
428     LOCK();
429     GC_init_inner();
430     UNLOCK();
431
432 #   if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
433         /* Make sure marker threads and started and thread local */
434         /* allocation is initialized, in case we didn't get      */
435         /* called from GC_init_parallel();                       */
436         {
437           GC_init_parallel();
438         }
439 #   endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
440
441 #   if defined(DYNAMIC_LOADING) && defined(DARWIN)
442     {
443         /* This must be called WITHOUT the allocation lock held
444         and before any threads are created */
445         extern void GC_init_dyld();
446         GC_init_dyld();
447     }
448 #   endif
449 }
450
451 #if defined(MSWIN32) || defined(MSWINCE)
452     CRITICAL_SECTION GC_write_cs;
453 #endif
454
455 #ifdef MSWIN32
456     extern void GC_init_win32(void);
457 #endif
458
459 extern void GC_setpagesize();
460
461
462 #ifdef MSWIN32
463 extern GC_bool GC_no_win32_dlls;
464 #else
465 # define GC_no_win32_dlls FALSE
466 #endif
467
468 void GC_exit_check(void)
469 {
470    GC_gcollect();
471 }
472
473 #ifdef SEARCH_FOR_DATA_START
474   extern void GC_init_linux_data_start(void);
475 #endif
476
477 #ifdef UNIX_LIKE
478
479 extern void GC_set_and_save_fault_handler(void (*handler)(int));
480
481 static void looping_handler(sig)
482 int sig;
483 {
484     GC_err_printf("Caught signal %d: looping in handler\n", sig);
485     for(;;);
486 }
487
488 static GC_bool installed_looping_handler = FALSE;
489
490 static void maybe_install_looping_handler()
491 {
492     /* Install looping handler before the write fault handler, so we    */
493     /* handle write faults correctly.                                   */
494       if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
495         GC_set_and_save_fault_handler(looping_handler);
496         installed_looping_handler = TRUE;
497       }
498 }
499
500 #else /* !UNIX_LIKE */
501
502 # define maybe_install_looping_handler()
503
504 #endif
505
506 void GC_init_inner()
507 {
508 #   if !defined(THREADS) && defined(GC_ASSERTIONS)
509         word dummy;
510 #   endif
511     word initial_heap_sz = (word)MINHINCR;
512     
513     if (GC_is_initialized) return;
514 #   if defined(MSWIN32) || defined(MSWINCE)
515       InitializeCriticalSection(&GC_write_cs);
516 #   endif
517 #   if (!defined(SMALL_CONFIG))
518       if (0 != GETENV("GC_PRINT_STATS")) {
519         GC_print_stats = 1;
520       } 
521       if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
522         GC_print_stats = VERBOSE;
523       } 
524 #     if defined(UNIX_LIKE)
525         {
526           char * file_name = GETENV("GC_LOG_FILE");
527           if (0 != file_name) {
528             int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666);
529             if (log_d < 0) {
530               GC_log_printf("Failed to open %s as log file\n", file_name);
531             } else {
532               GC_log = log_d;
533             }
534           }
535         }
536 #     endif
537 #   endif
538 #   ifndef NO_DEBUGGING
539       if (0 != GETENV("GC_DUMP_REGULARLY")) {
540         GC_dump_regularly = 1;
541       }
542 #   endif
543 #   ifdef KEEP_BACK_PTRS
544       {
545         char * backtraces_string = GETENV("GC_BACKTRACES");
546         if (0 != backtraces_string) {
547           GC_backtraces = atol(backtraces_string);
548           if (backtraces_string[0] == '\0') GC_backtraces = 1;
549         }
550       }
551 #   endif
552     if (0 != GETENV("GC_FIND_LEAK")) {
553       GC_find_leak = 1;
554       atexit(GC_exit_check);
555     }
556     if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
557       GC_all_interior_pointers = 1;
558     }
559     if (0 != GETENV("GC_DONT_GC")) {
560       GC_dont_gc = 1;
561     }
562     if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
563       GC_print_back_height = 1;
564     }
565     if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
566       GC_large_alloc_warn_interval = LONG_MAX;
567     }
568     {
569       char * addr_string = GETENV("GC_TRACE");
570       if (0 != addr_string) {
571 #       ifndef ENABLE_TRACE
572           WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
573 #       else
574 #         ifdef STRTOULL
575             long long addr = strtoull(addr_string, NULL, 16);
576 #         else
577             long addr = strtoul(addr_string, NULL, 16);
578 #         endif
579           if (addr < 0x1000)
580               WARN("Unlikely trace address: 0x%lx\n", (GC_word)addr);
581           GC_trace_addr = (ptr_t)addr;
582 #       endif
583       }
584     }
585     {
586       char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
587       if (0 != time_limit_string) {
588         long time_limit = atol(time_limit_string);
589         if (time_limit < 5) {
590           WARN("GC_PAUSE_TIME_TARGET environment variable value too small "
591                "or bad syntax: Ignoring\n", 0);
592         } else {
593           GC_time_limit = time_limit;
594         }
595       }
596     }
597     {
598       char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
599       if (0 != interval_string) {
600         long interval = atol(interval_string);
601         if (interval <= 0) {
602           WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
603                "bad value: Ignoring\n", 0);
604         } else {
605           GC_large_alloc_warn_interval = interval;
606         }
607       }
608     }
609     maybe_install_looping_handler();
610     /* Adjust normal object descriptor for extra allocation.    */
611     if (ALIGNMENT > GC_DS_TAGS && EXTRA_BYTES != 0) {
612       GC_obj_kinds[NORMAL].ok_descriptor = ((word)(-ALIGNMENT) | GC_DS_LENGTH);
613     }
614     GC_setpagesize();
615     GC_exclude_static_roots(beginGC_arrays, endGC_arrays);
616     GC_exclude_static_roots(beginGC_obj_kinds, endGC_obj_kinds);
617 #   ifdef SEPARATE_GLOBALS
618       GC_exclude_static_roots(beginGC_objfreelist, endGC_objfreelist);
619       GC_exclude_static_roots(beginGC_aobjfreelist, endGC_aobjfreelist);
620 #   endif
621 #   ifdef MSWIN32
622         GC_init_win32();
623 #   endif
624 #   if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
625         WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
626         /* If thread stacks are cached, they tend to be scanned in      */
627         /* entirety as part of the root set.  This wil grow them to     */
628         /* maximum size, and is generally not desirable.                */
629 #   endif
630 #   if defined(SEARCH_FOR_DATA_START)
631         GC_init_linux_data_start();
632 #   endif
633 #   if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
634         GC_init_netbsd_elf();
635 #   endif
636 #   if !defined(THREADS) || defined(GC_PTHREADS) || defined(GC_WIN32_THREADS) \
637         || defined(GC_SOLARIS_THREADS)
638       if (GC_stackbottom == 0) {
639         GC_stackbottom = GC_get_main_stack_base();
640 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
641           GC_register_stackbottom = GC_get_register_stack_base();
642 #       endif
643       } else {
644 #       if (defined(LINUX) || defined(HPUX)) && defined(IA64)
645           if (GC_register_stackbottom == 0) {
646             WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
647             /* The following may fail, since we may rely on             */
648             /* alignment properties that may not hold with a user set   */
649             /* GC_stackbottom.                                          */
650             GC_register_stackbottom = GC_get_register_stack_base();
651           }
652 #       endif
653       }
654 #   endif
655     /* Ignore gcc -Wall warnings on the following. */
656     GC_STATIC_ASSERT(sizeof (ptr_t) == sizeof(word));
657     GC_STATIC_ASSERT(sizeof (signed_word) == sizeof(word));
658     GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
659 #   ifndef THREADS
660 #     ifdef STACK_GROWS_DOWN
661         GC_ASSERT((word)(&dummy) <= (word)GC_stackbottom);
662 #     else
663         GC_ASSERT((word)(&dummy) >= (word)GC_stackbottom);
664 #     endif
665 #   endif
666 #   if !defined(_AUX_SOURCE) || defined(__GNUC__)
667       GC_ASSERT((word)(-1) > (word)0);
668       /* word should be unsigned */
669 #   endif
670     GC_ASSERT((ptr_t)(word)(-1) > (ptr_t)0);
671         /* Ptr_t comparisons should behave as unsigned comparisons.     */
672     GC_ASSERT((signed_word)(-1) < (signed_word)0);
673 #   if !defined(SMALL_CONFIG)
674       if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
675         /* This used to test for !GC_no_win32_dlls.  Why? */
676         GC_setpagesize();
677         /* For GWW_MPROTECT on Win32, this needs to happen before any   */
678         /* heap memory is allocated.                                    */
679         GC_dirty_init();
680         GC_ASSERT(GC_bytes_allocd == 0)
681         GC_incremental = TRUE;
682       }
683 #   endif /* !SMALL_CONFIG */
684     
685     /* Add initial guess of root sets.  Do this first, since sbrk(0)    */
686     /* might be used.                                                   */
687       if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
688     GC_init_headers();
689     GC_bl_init();
690     GC_mark_init();
691     {
692         char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
693         if (sz_str != NULL) {
694           initial_heap_sz = atoi(sz_str);
695           if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
696             WARN("Bad initial heap size %s - ignoring it.\n",
697                  sz_str);
698           } 
699           initial_heap_sz = divHBLKSZ(initial_heap_sz);
700         }
701     }
702     {
703         char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
704         if (sz_str != NULL) {
705           word max_heap_sz = (word)atol(sz_str);
706           if (max_heap_sz < initial_heap_sz * HBLKSIZE) {
707             WARN("Bad maximum heap size %s - ignoring it.\n",
708                  sz_str);
709           } 
710           if (0 == GC_max_retries) GC_max_retries = 2;
711           GC_set_max_heap_size(max_heap_sz);
712         }
713     }
714     if (!GC_expand_hp_inner(initial_heap_sz)) {
715         GC_err_printf("Can't start up: not enough memory\n");
716         EXIT();
717     }
718     GC_initialize_offsets();
719     GC_register_displacement_inner(0L);
720 #   if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
721       if (!GC_all_interior_pointers) {
722         /* TLS ABI uses pointer-sized offsets for dtv. */
723         GC_register_displacement_inner(sizeof(void *));
724       }
725 #   endif
726     GC_init_size_map();
727 #   ifdef PCR
728       if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
729           != PCR_ERes_okay) {
730           ABORT("Can't lock load state\n");
731       } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
732           ABORT("Can't unlock load state\n");
733       }
734       PCR_IL_Unlock();
735       GC_pcr_install();
736 #   endif
737     GC_is_initialized = TRUE;
738 #   if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
739         GC_thr_init();
740 #   endif
741     COND_DUMP;
742     /* Get black list set up and/or incremental GC started */
743       if (!GC_dont_precollect || GC_incremental) GC_gcollect_inner();
744 #   ifdef STUBBORN_ALLOC
745         GC_stubborn_init();
746 #   endif
747 #   if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
748         {
749           extern void GC_init_lib_bounds(void);
750           GC_init_lib_bounds();
751         }
752 #   endif
753     /* Convince lint that some things are used */
754 #   ifdef LINT
755       {
756           extern char * GC_copyright[];
757           extern int GC_read();
758           extern void GC_register_finalizer_no_order();
759           
760           GC_noop(GC_copyright, GC_find_header,
761                   GC_push_one, GC_call_with_alloc_lock, GC_read,
762                   GC_dont_expand,
763 #                 ifndef NO_DEBUGGING
764                     GC_dump,
765 #                 endif
766                   GC_register_finalizer_no_order);
767       }
768 #   endif
769 }
770
771 void GC_enable_incremental(void)
772 {
773 # if !defined(SMALL_CONFIG) && !defined(KEEP_BACK_PTRS)
774   /* If we are keeping back pointers, the GC itself dirties all */
775   /* pages on which objects have been marked, making            */
776   /* incremental GC pointless.                                  */
777   if (!GC_find_leak) {
778     DCL_LOCK_STATE;
779     
780     LOCK();
781     if (GC_incremental) goto out;
782     GC_setpagesize();
783     /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
784     maybe_install_looping_handler();  /* Before write fault handler! */
785     GC_incremental = TRUE;
786     if (!GC_is_initialized) {
787         GC_init_inner();
788     } else {
789         GC_dirty_init();
790     }
791     if (!GC_dirty_maintained) goto out;
792     if (GC_dont_gc) {
793         /* Can't easily do it. */
794         UNLOCK();
795         return;
796     }
797     if (GC_bytes_allocd > 0) {
798         /* There may be unmarked reachable objects      */
799         GC_gcollect_inner();
800     }   /* else we're OK in assuming everything's       */
801         /* clean since nothing can point to an          */
802         /* unmarked object.                             */
803     GC_read_dirty();
804 out:
805     UNLOCK();
806   } else {
807     GC_init();
808   }
809 # else
810     GC_init();
811 # endif
812 }
813
814
815 #if defined(MSWIN32) || defined(MSWINCE)
816 # if defined(_MSC_VER) && defined(_DEBUG)
817 #  include <crtdbg.h>
818 # endif
819 # ifdef OLD_WIN32_LOG_FILE
820 #   define LOG_FILE _T("gc.log")
821 # endif
822
823   HANDLE GC_stdout = 0;
824
825   void GC_deinit()
826   {
827       if (GC_is_initialized) {
828         DeleteCriticalSection(&GC_write_cs);
829       }
830   }
831
832 # ifndef THREADS
833 #   define GC_need_to_lock 0  /* Not defined without threads */
834 # endif
835   int GC_write(const char *buf, size_t len)
836   {
837       BOOL tmp;
838       DWORD written;
839       if (len == 0)
840           return 0;
841       if (GC_need_to_lock) EnterCriticalSection(&GC_write_cs);
842       if (GC_stdout == INVALID_HANDLE_VALUE) {
843           if (GC_need_to_lock) LeaveCriticalSection(&GC_write_cs);
844           return -1;
845       } else if (GC_stdout == 0) {
846         char * file_name = GETENV("GC_LOG_FILE");
847         char logPath[_MAX_PATH + 5];
848
849         if (0 == file_name) {
850 #         ifdef OLD_WIN32_LOG_FILE
851             strcpy(logPath, LOG_FILE);
852 #         else
853             GetModuleFileName(NULL, logPath, _MAX_PATH);
854             strcat(logPath, ".log");
855 #         endif
856           file_name = logPath;
857         }
858         GC_stdout = CreateFile(logPath, GENERIC_WRITE,
859                                FILE_SHARE_READ,
860                                NULL, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH,
861                                NULL); 
862         if (GC_stdout == INVALID_HANDLE_VALUE)
863             ABORT("Open of log file failed");
864       }
865       tmp = WriteFile(GC_stdout, buf, (DWORD)len, &written, NULL);
866       if (!tmp)
867           DebugBreak();
868 #     if defined(_MSC_VER) && defined(_DEBUG)
869           _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
870 #     endif
871       if (GC_need_to_lock) LeaveCriticalSection(&GC_write_cs);
872       return tmp ? (int)written : -1;
873   }
874 # undef GC_need_to_lock
875
876 #endif
877
878 #if defined(OS2) || defined(MACOS)
879 FILE * GC_stdout = NULL;
880 FILE * GC_stderr = NULL;
881 FILE * GC_log = NULL;
882 int GC_tmp;  /* Should really be local ... */
883
884   void GC_set_files()
885   {
886       if (GC_stdout == NULL) {
887         GC_stdout = stdout;
888     }
889     if (GC_stderr == NULL) {
890         GC_stderr = stderr;
891     }
892     if (GC_log == NULL) {
893         GC_log = stderr;
894     }
895   }
896 #endif
897
898 #if !defined(OS2) && !defined(MACOS) && !defined(MSWIN32) && !defined(MSWINCE)
899   int GC_stdout = 1;
900   int GC_stderr = 2;
901   int GC_log = 2;
902 # if !defined(AMIGA)
903 #   include <unistd.h>
904 # endif
905 #endif
906
907 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(OS2) \
908     && !defined(MACOS)  && !defined(ECOS) && !defined(NOSYS)
909 int GC_write(fd, buf, len)
910 int fd;
911 const char *buf;
912 size_t len;
913 {
914      register int bytes_written = 0;
915      register int result;
916      
917      while (bytes_written < len) {
918 #       ifdef GC_SOLARIS_THREADS
919             result = syscall(SYS_write, fd, buf + bytes_written,
920                                             len - bytes_written);
921 #       else
922             result = write(fd, buf + bytes_written, len - bytes_written);
923 #       endif
924         if (-1 == result) return(result);
925         bytes_written += result;
926     }
927     return(bytes_written);
928 }
929 #endif /* UN*X */
930
931 #ifdef ECOS
932 int GC_write(fd, buf, len)
933 {
934   _Jv_diag_write (buf, len);
935   return len;
936 }
937 #endif
938
939 #ifdef NOSYS
940 int GC_write(fd, buf, len)
941 {
942   /* No writing.  */
943   return len;
944 }
945 #endif
946
947
948 #if defined(MSWIN32) || defined(MSWINCE)
949     /* FIXME: This is pretty ugly ... */
950 #   define WRITE(f, buf, len) GC_write(buf, len)
951 #else
952 #   if defined(OS2) || defined(MACOS)
953 #   define WRITE(f, buf, len) (GC_set_files(), \
954                                GC_tmp = fwrite((buf), 1, (len), (f)), \
955                                fflush(f), GC_tmp)
956 #   else
957 #     define WRITE(f, buf, len) GC_write((f), (buf), (len))
958 #   endif
959 #endif
960
961 #define BUFSZ 1024
962 #ifdef _MSC_VER
963 # define vsnprintf _vsnprintf
964 #endif
965 /* A version of printf that is unlikely to call malloc, and is thus safer */
966 /* to call from the collector in case malloc has been bound to GC_malloc. */
967 /* Floating point arguments ans formats should be avoided, since fp       */
968 /* conversion is more likely to allocate.                                 */
969 /* Assumes that no more than BUFSZ-1 characters are written at once.      */
970 void GC_printf(const char *format, ...)
971 {
972     va_list args;
973     char buf[BUFSZ+1];
974     
975     va_start(args, format);
976     if (GC_quiet) return;
977     buf[BUFSZ] = 0x15;
978     (void) vsnprintf(buf, BUFSZ, format, args);
979     va_end(args);
980     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
981     if (WRITE(GC_stdout, buf, strlen(buf)) < 0) ABORT("write to stdout failed");
982 }
983
984 void GC_err_printf(const char *format, ...)
985 {
986     va_list args;
987     char buf[BUFSZ+1];
988     
989     va_start(args, format);
990     buf[BUFSZ] = 0x15;
991     (void) vsnprintf(buf, BUFSZ, format, args);
992     va_end(args);
993     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
994     if (WRITE(GC_stderr, buf, strlen(buf)) < 0) ABORT("write to stderr failed");
995 }
996
997 void GC_log_printf(const char *format, ...)
998 {
999     va_list args;
1000     char buf[BUFSZ+1];
1001     
1002     va_start(args, format);
1003     buf[BUFSZ] = 0x15;
1004     (void) vsnprintf(buf, BUFSZ, format, args);
1005     va_end(args);
1006     if (buf[BUFSZ] != 0x15) ABORT("GC_printf clobbered stack");
1007     if (WRITE(GC_log, buf, strlen(buf)) < 0) ABORT("write to log failed");
1008 }
1009
1010 void GC_err_puts(const char *s)
1011 {
1012     if (WRITE(GC_stderr, s, strlen(s)) < 0) ABORT("write to stderr failed");
1013 }
1014
1015 #if defined(LINUX) && !defined(SMALL_CONFIG)
1016 void GC_err_write(buf, len)
1017 const char *buf;
1018 size_t len;
1019 {
1020     if (WRITE(GC_stderr, buf, len) < 0) ABORT("write to stderr failed");
1021 }
1022 #endif
1023
1024 void GC_default_warn_proc(char *msg, GC_word arg)
1025 {
1026     GC_err_printf(msg, arg);
1027 }
1028
1029 GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
1030
1031 GC_warn_proc GC_set_warn_proc(GC_warn_proc p)
1032 {
1033     GC_warn_proc result;
1034
1035 #   ifdef GC_WIN32_THREADS
1036       GC_ASSERT(GC_is_initialized);
1037 #   endif
1038     LOCK();
1039     result = GC_current_warn_proc;
1040     GC_current_warn_proc = p;
1041     UNLOCK();
1042     return(result);
1043 }
1044
1045 GC_word GC_set_free_space_divisor (GC_word value)
1046 {
1047     GC_word old = GC_free_space_divisor;
1048     GC_free_space_divisor = value;
1049     return old;
1050 }
1051
1052 #ifndef PCR
1053 void GC_abort(const char *msg)
1054 {
1055 #   if defined(MSWIN32)
1056       (void) MessageBoxA(NULL, msg, "Fatal error in gc", MB_ICONERROR|MB_OK);
1057 #   else
1058       GC_err_printf("%s\n", msg);
1059 #   endif
1060     if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
1061             /* In many cases it's easier to debug a running process.    */
1062             /* It's arguably nicer to sleep, but that makes it harder   */
1063             /* to look at the thread if the debugger doesn't know much  */
1064             /* about threads.                                           */
1065             for(;;) {}
1066     }
1067 #   if defined(MSWIN32) || defined(MSWINCE)
1068         DebugBreak();
1069 #   else
1070         (void) abort();
1071 #   endif
1072 }
1073 #endif
1074
1075 void GC_enable()
1076 {
1077     LOCK();
1078     GC_dont_gc--;
1079     UNLOCK();
1080 }
1081
1082 void GC_disable()
1083 {
1084     LOCK();
1085     GC_dont_gc++;
1086     UNLOCK();
1087 }
1088
1089 /* Helper procedures for new kind creation.     */
1090 void ** GC_new_free_list_inner()
1091 {
1092     void *result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1)*sizeof(ptr_t),
1093                                       PTRFREE);
1094     if (result == 0) ABORT("Failed to allocate freelist for new kind");
1095     BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
1096     return result;
1097 }
1098
1099 void ** GC_new_free_list()
1100 {
1101     void *result;
1102     LOCK();
1103     result = GC_new_free_list_inner();
1104     UNLOCK();
1105     return result;
1106 }
1107
1108 unsigned GC_new_kind_inner(void **fl, GC_word descr, int adjust, int clear)
1109 {
1110     unsigned result = GC_n_kinds++;
1111
1112     if (GC_n_kinds > MAXOBJKINDS) ABORT("Too many kinds");
1113     GC_obj_kinds[result].ok_freelist = fl;
1114     GC_obj_kinds[result].ok_reclaim_list = 0;
1115     GC_obj_kinds[result].ok_descriptor = descr;
1116     GC_obj_kinds[result].ok_relocate_descr = adjust;
1117     GC_obj_kinds[result].ok_init = clear;
1118     return result;
1119 }
1120
1121 unsigned GC_new_kind(void **fl, GC_word descr, int adjust, int clear)
1122 {
1123     unsigned result;
1124     LOCK();
1125     result = GC_new_kind_inner(fl, descr, adjust, clear);
1126     UNLOCK();
1127     return result;
1128 }
1129
1130 unsigned GC_new_proc_inner(GC_mark_proc proc)
1131 {
1132     unsigned result = GC_n_mark_procs++;
1133
1134     if (GC_n_mark_procs > MAX_MARK_PROCS) ABORT("Too many mark procedures");
1135     GC_mark_procs[result] = proc;
1136     return result;
1137 }
1138
1139 unsigned GC_new_proc(GC_mark_proc proc)
1140 {
1141     unsigned result;
1142     LOCK();
1143     result = GC_new_proc_inner(proc);
1144     UNLOCK();
1145     return result;
1146 }
1147
1148 void * GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
1149 {
1150     int dummy;
1151     struct GC_stack_base base;
1152
1153     base.mem_base = (void *)&dummy;
1154 #   ifdef IA64
1155       base.reg_base = (void *)GC_save_regs_in_stack();
1156       /* Unnecessarily flushes register stack,          */
1157       /* but that probably doesn't hurt.                */
1158 #   endif
1159     return fn(&base, arg);
1160 }
1161
1162 #if !defined(NO_DEBUGGING)
1163
1164 void GC_dump()
1165 {
1166     GC_printf("***Static roots:\n");
1167     GC_print_static_roots();
1168     GC_printf("\n***Heap sections:\n");
1169     GC_print_heap_sects();
1170     GC_printf("\n***Free blocks:\n");
1171     GC_print_hblkfreelist();
1172     GC_printf("\n***Blocks in use:\n");
1173     GC_print_block_list();
1174     GC_printf("\n***Finalization statistics:\n");
1175     GC_print_finalization_stats();
1176 }
1177
1178 #endif /* NO_DEBUGGING */