OSDN Git Service

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