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