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