OSDN Git Service

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