OSDN Git Service

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