* fv0: Defined.
[cacao.git] / src / boehm-gc / os_dep.c
1 /*
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved.
4  * Copyright (c) 1996-1999 by Silicon Graphics.  All rights reserved.
5  * Copyright (c) 1999 by Hewlett-Packard Company.  All rights reserved.
6  *
7  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
9  *
10  * Permission is hereby granted to use or copy this program
11  * for any purpose,  provided the above notices are retained on all copies.
12  * Permission to modify the code and to distribute modified code is granted,
13  * provided the above notices are retained, and a notice that the code was
14  * modified is included with the above copyright notice.
15  */
16
17 #include "config.h"
18
19 # include "private/gc_priv.h"
20
21 # if defined(LINUX) && !defined(POWERPC)
22 #   include <linux/version.h>
23 #   if (LINUX_VERSION_CODE <= 0x10400)
24       /* Ugly hack to get struct sigcontext_struct definition.  Required      */
25       /* for some early 1.3.X releases.  Will hopefully go away soon. */
26       /* in some later Linux releases, asm/sigcontext.h may have to   */
27       /* be included instead.                                         */
28 #     define __KERNEL__
29 #     include <asm/signal.h>
30 #     undef __KERNEL__
31 #   else
32       /* Kernels prior to 2.1.1 defined struct sigcontext_struct instead of */
33       /* struct sigcontext.  libc6 (glibc2) uses "struct sigcontext" in     */
34       /* prototypes, so we have to include the top-level sigcontext.h to    */
35       /* make sure the former gets defined to be the latter if appropriate. */
36 #     include <features.h>
37 #     if 2 <= __GLIBC__
38 #       if 2 == __GLIBC__ && 0 == __GLIBC_MINOR__
39           /* glibc 2.1 no longer has sigcontext.h.  But signal.h        */
40           /* has the right declaration for glibc 2.1.                   */
41 #         include <sigcontext.h>
42 #       endif /* 0 == __GLIBC_MINOR__ */
43 #     else /* not 2 <= __GLIBC__ */
44         /* libc5 doesn't have <sigcontext.h>: go directly with the kernel   */
45         /* one.  Check LINUX_VERSION_CODE to see which we should reference. */
46 #       include <asm/sigcontext.h>
47 #     endif /* 2 <= __GLIBC__ */
48 #   endif
49 # endif
50 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) && !defined(MACOS) \
51     && !defined(MSWINCE)
52 #   include <sys/types.h>
53 #   if !defined(MSWIN32) && !defined(SUNOS4)
54 #       include <unistd.h>
55 #   endif
56 # endif
57
58 # include <stdio.h>
59 # if defined(MSWINCE)
60 #   define SIGSEGV 0 /* value is irrelevant */
61 # else
62 #   include <signal.h>
63 # endif
64
65 #if defined(LINUX) || defined(LINUX_STACKBOTTOM)
66 # include <ctype.h>
67 #endif
68
69 /* Blatantly OS dependent routines, except for those that are related   */
70 /* to dynamic loading.                                                  */
71
72 # if defined(HEURISTIC2) || defined(SEARCH_FOR_DATA_START)
73 #   define NEED_FIND_LIMIT
74 # endif
75
76 # if !defined(STACKBOTTOM) && defined(HEURISTIC2)
77 #   define NEED_FIND_LIMIT
78 # endif
79
80 # if (defined(SUNOS4) && defined(DYNAMIC_LOADING)) && !defined(PCR)
81 #   define NEED_FIND_LIMIT
82 # endif
83
84 # if (defined(SVR4) || defined(AUX) || defined(DGUX) \
85       || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
86 #   define NEED_FIND_LIMIT
87 # endif
88
89 #if defined(FREEBSD) && (defined(I386) || defined(powerpc) || defined(__powerpc__))
90 #  include <machine/trap.h>
91 #  if !defined(PCR)
92 #    define NEED_FIND_LIMIT
93 #  endif
94 #endif
95
96 #if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__) \
97     && !defined(NEED_FIND_LIMIT)
98    /* Used by GC_init_netbsd_elf() below.       */
99 #  define NEED_FIND_LIMIT
100 #endif
101
102 #ifdef NEED_FIND_LIMIT
103 #   include <setjmp.h>
104 #endif
105
106 #ifdef AMIGA
107 # define GC_AMIGA_DEF
108 # include "AmigaOS.c"
109 # undef GC_AMIGA_DEF
110 #endif
111
112 #if defined(MSWIN32) || defined(MSWINCE)
113 # define WIN32_LEAN_AND_MEAN
114 # define NOSERVICE
115 # include <windows.h>
116 #endif
117
118 #ifdef MACOS
119 # include <Processes.h>
120 #endif
121
122 #ifdef IRIX5
123 # include <sys/uio.h>
124 # include <malloc.h>   /* for locking */
125 #endif
126 #if defined(USE_MMAP) || defined(USE_MUNMAP)
127 # ifndef USE_MMAP
128     --> USE_MUNMAP requires USE_MMAP
129 # endif
130 # include <sys/types.h>
131 # include <sys/mman.h>
132 # include <sys/stat.h>
133 # include <errno.h>
134 #endif
135
136 #ifdef UNIX_LIKE
137 # include <fcntl.h>
138 # if defined(SUNOS5SIGS) && !defined(FREEBSD)
139 #  include <sys/siginfo.h>
140 # endif
141   /* Define SETJMP and friends to be the version that restores  */
142   /* the signal mask.                                           */
143 # define SETJMP(env) sigsetjmp(env, 1)
144 # define LONGJMP(env, val) siglongjmp(env, val)
145 # define JMP_BUF sigjmp_buf
146 #else
147 # define SETJMP(env) setjmp(env)
148 # define LONGJMP(env, val) longjmp(env, val)
149 # define JMP_BUF jmp_buf
150 #endif
151
152 #ifdef DARWIN
153 /* for get_etext and friends */
154 #include <mach-o/getsect.h>
155 #endif
156
157 #ifdef DJGPP
158   /* Apparently necessary for djgpp 2.01.  May cause problems with      */
159   /* other versions.                                                    */
160   typedef long unsigned int caddr_t;
161 #endif
162
163 #ifdef PCR
164 # include "il/PCR_IL.h"
165 # include "th/PCR_ThCtl.h"
166 # include "mm/PCR_MM.h"
167 #endif
168
169 #if !defined(NO_EXECUTE_PERMISSION)
170 # define OPT_PROT_EXEC PROT_EXEC
171 #else
172 # define OPT_PROT_EXEC 0
173 #endif
174
175 #if defined(LINUX) && \
176     (defined(USE_PROC_FOR_LIBRARIES) || defined(IA64) || !defined(SMALL_CONFIG))
177
178 /* We need to parse /proc/self/maps, either to find dynamic libraries,  */
179 /* and/or to find the register backing store base (IA64).  Do it once   */
180 /* here.                                                                */
181
182 #define READ read
183
184 /* Repeatedly perform a read call until the buffer is filled or */
185 /* we encounter EOF.                                            */
186 ssize_t GC_repeat_read(int fd, char *buf, size_t count)
187 {
188     ssize_t num_read = 0;
189     ssize_t result;
190     
191     while (num_read < count) {
192         result = READ(fd, buf + num_read, count - num_read);
193         if (result < 0) return result;
194         if (result == 0) break;
195         num_read += result;
196     }
197     return num_read;
198 }
199
200 /*
201  * Apply fn to a buffer containing the contents of /proc/self/maps.
202  * Return the result of fn or, if we failed, 0.
203  * We currently do nothing to /proc/self/maps other than simply read
204  * it.  This code could be simplified if we could determine its size
205  * ahead of time.
206  */
207
208 word GC_apply_to_maps(word (*fn)(char *))
209 {
210     int f;
211     int result;
212     size_t maps_size = 4000;  /* Initial guess.         */
213     static char init_buf[1];
214     static char *maps_buf = init_buf;
215     static size_t maps_buf_sz = 1;
216
217     /* Read /proc/self/maps, growing maps_buf as necessary.     */
218         /* Note that we may not allocate conventionally, and    */
219         /* thus can't use stdio.                                */
220         do {
221             if (maps_size >= maps_buf_sz) {
222               /* Grow only by powers of 2, since we leak "too small" buffers. */
223               while (maps_size >= maps_buf_sz) maps_buf_sz *= 2;
224               maps_buf = GC_scratch_alloc(maps_buf_sz);
225               if (maps_buf == 0) return 0;
226             }
227             f = open("/proc/self/maps", O_RDONLY);
228             if (-1 == f) return 0;
229             maps_size = 0;
230             do {
231                 result = GC_repeat_read(f, maps_buf, maps_buf_sz-1);
232                 if (result <= 0) return 0;
233                 maps_size += result;
234             } while (result == maps_buf_sz-1);
235             close(f);
236         } while (maps_size >= maps_buf_sz);
237         maps_buf[maps_size] = '\0';
238         
239     /* Apply fn to result. */
240         return fn(maps_buf);
241 }
242
243 #endif /* Need GC_apply_to_maps */
244
245 #if defined(LINUX) && (defined(USE_PROC_FOR_LIBRARIES) || defined(IA64))
246 //
247 //  GC_parse_map_entry parses an entry from /proc/self/maps so we can
248 //  locate all writable data segments that belong to shared libraries.
249 //  The format of one of these entries and the fields we care about
250 //  is as follows:
251 //  XXXXXXXX-XXXXXXXX r-xp 00000000 30:05 260537     name of mapping...\n
252 //  ^^^^^^^^ ^^^^^^^^ ^^^^          ^^
253 //  start    end      prot          maj_dev
254 //
255 //  Note that since about auguat 2003 kernels, the columns no longer have
256 //  fixed offsets on 64-bit kernels.  Hence we no longer rely on fixed offsets
257 //  anywhere, which is safer anyway.
258 //
259
260 /*
261  * Assign various fields of the first line in buf_ptr to *start, *end,
262  * *prot_buf and *maj_dev.  Only *prot_buf may be set for unwritable maps.
263  */
264 char *GC_parse_map_entry(char *buf_ptr, word *start, word *end,
265                                 char *prot_buf, unsigned int *maj_dev)
266 {
267     char *start_start, *end_start, *prot_start, *maj_dev_start;
268     char *p;
269     char *endp;
270
271     if (buf_ptr == NULL || *buf_ptr == '\0') {
272         return NULL;
273     }
274
275     p = buf_ptr;
276     while (isspace(*p)) ++p;
277     start_start = p;
278     GC_ASSERT(isxdigit(*start_start));
279     *start = strtoul(start_start, &endp, 16); p = endp;
280     GC_ASSERT(*p=='-');
281
282     ++p;
283     end_start = p;
284     GC_ASSERT(isxdigit(*end_start));
285     *end = strtoul(end_start, &endp, 16); p = endp;
286     GC_ASSERT(isspace(*p));
287
288     while (isspace(*p)) ++p;
289     prot_start = p;
290     GC_ASSERT(*prot_start == 'r' || *prot_start == '-');
291     memcpy(prot_buf, prot_start, 4);
292     prot_buf[4] = '\0';
293     if (prot_buf[1] == 'w') {/* we can skip the rest if it's not writable. */
294         /* Skip past protection field to offset field */
295           while (!isspace(*p)) ++p; while (isspace(*p)) ++p;
296           GC_ASSERT(isxdigit(*p));
297         /* Skip past offset field, which we ignore */
298           while (!isspace(*p)) ++p; while (isspace(*p)) ++p;
299         maj_dev_start = p;
300         GC_ASSERT(isxdigit(*maj_dev_start));
301         *maj_dev = strtoul(maj_dev_start, NULL, 16);
302     }
303
304     while (*p && *p++ != '\n');
305
306     return p;
307 }
308
309 #endif /* Need to parse /proc/self/maps. */     
310
311 #if defined(SEARCH_FOR_DATA_START)
312   /* The I386 case can be handled without a search.  The Alpha case     */
313   /* used to be handled differently as well, but the rules changed      */
314   /* for recent Linux versions.  This seems to be the easiest way to    */
315   /* cover all versions.                                                */
316
317 # ifdef LINUX
318     /* Some Linux distributions arrange to define __data_start.  Some   */
319     /* define data_start as a weak symbol.  The latter is technically   */
320     /* broken, since the user program may define data_start, in which   */
321     /* case we lose.  Nonetheless, we try both, prefering __data_start. */
322     /* We assume gcc-compatible pragmas.        */
323 #   pragma weak __data_start
324     extern int __data_start[];
325 #   pragma weak data_start
326     extern int data_start[];
327 # endif /* LINUX */
328   extern int _end[];
329
330   ptr_t GC_data_start;
331
332   void GC_init_linux_data_start()
333   {
334     extern ptr_t GC_find_limit();
335
336 #   ifdef LINUX
337       /* Try the easy approaches first: */
338       if ((ptr_t)__data_start != 0) {
339           GC_data_start = (ptr_t)(__data_start);
340           return;
341       }
342       if ((ptr_t)data_start != 0) {
343           GC_data_start = (ptr_t)(data_start);
344           return;
345       }
346 #   endif /* LINUX */
347     GC_data_start = GC_find_limit((ptr_t)(_end), FALSE);
348   }
349 #endif
350
351 # ifdef ECOS
352
353 # ifndef ECOS_GC_MEMORY_SIZE
354 # define ECOS_GC_MEMORY_SIZE (448 * 1024)
355 # endif /* ECOS_GC_MEMORY_SIZE */
356
357 // setjmp() function, as described in ANSI para 7.6.1.1
358 #undef SETJMP
359 #define SETJMP( __env__ )  hal_setjmp( __env__ )
360
361 // FIXME: This is a simple way of allocating memory which is
362 // compatible with ECOS early releases.  Later releases use a more
363 // sophisticated means of allocating memory than this simple static
364 // allocator, but this method is at least bound to work.
365 static char memory[ECOS_GC_MEMORY_SIZE];
366 static char *brk = memory;
367
368 static void *tiny_sbrk(ptrdiff_t increment)
369 {
370   void *p = brk;
371
372   brk += increment;
373
374   if (brk >  memory + sizeof memory)
375     {
376       brk -= increment;
377       return NULL;
378     }
379
380   return p;
381 }
382 #define sbrk tiny_sbrk
383 # endif /* ECOS */
384
385 #if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
386   ptr_t GC_data_start;
387
388   void GC_init_netbsd_elf()
389   {
390     extern ptr_t GC_find_limit();
391     extern char **environ;
392         /* This may need to be environ, without the underscore, for     */
393         /* some versions.                                               */
394     GC_data_start = GC_find_limit((ptr_t)&environ, FALSE);
395   }
396 #endif
397
398 # ifdef OS2
399
400 # include <stddef.h>
401
402 # if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */
403
404 struct exe_hdr {
405     unsigned short      magic_number;
406     unsigned short      padding[29];
407     long                new_exe_offset;
408 };
409
410 #define E_MAGIC(x)      (x).magic_number
411 #define EMAGIC          0x5A4D  
412 #define E_LFANEW(x)     (x).new_exe_offset
413
414 struct e32_exe {
415     unsigned char       magic_number[2]; 
416     unsigned char       byte_order; 
417     unsigned char       word_order; 
418     unsigned long       exe_format_level;
419     unsigned short      cpu;       
420     unsigned short      os;
421     unsigned long       padding1[13];
422     unsigned long       object_table_offset;
423     unsigned long       object_count;    
424     unsigned long       padding2[31];
425 };
426
427 #define E32_MAGIC1(x)   (x).magic_number[0]
428 #define E32MAGIC1       'L'
429 #define E32_MAGIC2(x)   (x).magic_number[1]
430 #define E32MAGIC2       'X'
431 #define E32_BORDER(x)   (x).byte_order
432 #define E32LEBO         0
433 #define E32_WORDER(x)   (x).word_order
434 #define E32LEWO         0
435 #define E32_CPU(x)      (x).cpu
436 #define E32CPU286       1
437 #define E32_OBJTAB(x)   (x).object_table_offset
438 #define E32_OBJCNT(x)   (x).object_count
439
440 struct o32_obj {
441     unsigned long       size;  
442     unsigned long       base;
443     unsigned long       flags;  
444     unsigned long       pagemap;
445     unsigned long       mapsize; 
446     unsigned long       reserved;
447 };
448
449 #define O32_FLAGS(x)    (x).flags
450 #define OBJREAD         0x0001L
451 #define OBJWRITE        0x0002L
452 #define OBJINVALID      0x0080L
453 #define O32_SIZE(x)     (x).size
454 #define O32_BASE(x)     (x).base
455
456 # else  /* IBM's compiler */
457
458 /* A kludge to get around what appears to be a header file bug */
459 # ifndef WORD
460 #   define WORD unsigned short
461 # endif
462 # ifndef DWORD
463 #   define DWORD unsigned long
464 # endif
465
466 # define EXE386 1
467 # include <newexe.h>
468 # include <exe386.h>
469
470 # endif  /* __IBMC__ */
471
472 # define INCL_DOSEXCEPTIONS
473 # define INCL_DOSPROCESS
474 # define INCL_DOSERRORS
475 # define INCL_DOSMODULEMGR
476 # define INCL_DOSMEMMGR
477 # include <os2.h>
478
479
480 /* Disable and enable signals during nontrivial allocations     */
481
482 void GC_disable_signals(void)
483 {
484     ULONG nest;
485     
486     DosEnterMustComplete(&nest);
487     if (nest != 1) ABORT("nested GC_disable_signals");
488 }
489
490 void GC_enable_signals(void)
491 {
492     ULONG nest;
493     
494     DosExitMustComplete(&nest);
495     if (nest != 0) ABORT("GC_enable_signals");
496 }
497
498
499 # else
500
501 #  if !defined(PCR) && !defined(AMIGA) && !defined(MSWIN32) \
502       && !defined(MSWINCE) \
503       && !defined(MACOS) && !defined(DJGPP) && !defined(DOS4GW) \
504       && !defined(NOSYS) && !defined(ECOS)
505
506 #   if defined(sigmask) && !defined(UTS4) && !defined(HURD)
507         /* Use the traditional BSD interface */
508 #       define SIGSET_T int
509 #       define SIG_DEL(set, signal) (set) &= ~(sigmask(signal))
510 #       define SIG_FILL(set)  (set) = 0x7fffffff
511           /* Setting the leading bit appears to provoke a bug in some   */
512           /* longjmp implementations.  Most systems appear not to have  */
513           /* a signal 32.                                               */
514 #       define SIGSETMASK(old, new) (old) = sigsetmask(new)
515 #   else
516         /* Use POSIX/SYSV interface     */
517 #       define SIGSET_T sigset_t
518 #       define SIG_DEL(set, signal) sigdelset(&(set), (signal))
519 #       define SIG_FILL(set) sigfillset(&set)
520 #       define SIGSETMASK(old, new) sigprocmask(SIG_SETMASK, &(new), &(old))
521 #   endif
522
523 static GC_bool mask_initialized = FALSE;
524
525 static SIGSET_T new_mask;
526
527 static SIGSET_T old_mask;
528
529 static SIGSET_T dummy;
530
531 #if defined(PRINTSTATS) && !defined(THREADS)
532 # define CHECK_SIGNALS
533   int GC_sig_disabled = 0;
534 #endif
535
536 void GC_disable_signals()
537 {
538     if (!mask_initialized) {
539         SIG_FILL(new_mask);
540
541         SIG_DEL(new_mask, SIGSEGV);
542         SIG_DEL(new_mask, SIGILL);
543         SIG_DEL(new_mask, SIGQUIT);
544 #       ifdef SIGBUS
545             SIG_DEL(new_mask, SIGBUS);
546 #       endif
547 #       ifdef SIGIOT
548             SIG_DEL(new_mask, SIGIOT);
549 #       endif
550 #       ifdef SIGEMT
551             SIG_DEL(new_mask, SIGEMT);
552 #       endif
553 #       ifdef SIGTRAP
554             SIG_DEL(new_mask, SIGTRAP);
555 #       endif 
556         mask_initialized = TRUE;
557     }
558 #   ifdef CHECK_SIGNALS
559         if (GC_sig_disabled != 0) ABORT("Nested disables");
560         GC_sig_disabled++;
561 #   endif
562     SIGSETMASK(old_mask,new_mask);
563 }
564
565 void GC_enable_signals()
566 {
567 #   ifdef CHECK_SIGNALS
568         if (GC_sig_disabled != 1) ABORT("Unmatched enable");
569         GC_sig_disabled--;
570 #   endif
571     SIGSETMASK(dummy,old_mask);
572 }
573
574 #  endif  /* !PCR */
575
576 # endif /*!OS/2 */
577
578 /* Ivan Demakov: simplest way (to me) */
579 #if defined (DOS4GW)
580   void GC_disable_signals() { }
581   void GC_enable_signals() { }
582 #endif
583
584 /* Find the page size */
585 word GC_page_size;
586
587 # if defined(MSWIN32) || defined(MSWINCE)
588   void GC_setpagesize()
589   {
590     GetSystemInfo(&GC_sysinfo);
591     GC_page_size = GC_sysinfo.dwPageSize;
592   }
593
594 # else
595 #   if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP) \
596        || defined(USE_MUNMAP)
597         void GC_setpagesize()
598         {
599             GC_page_size = GETPAGESIZE();
600         }
601 #   else
602         /* It's acceptable to fake it. */
603         void GC_setpagesize()
604         {
605             GC_page_size = HBLKSIZE;
606         }
607 #   endif
608 # endif
609
610 /* 
611  * Find the base of the stack. 
612  * Used only in single-threaded environment.
613  * With threads, GC_mark_roots needs to know how to do this.
614  * Called with allocator lock held.
615  */
616 # if defined(MSWIN32) || defined(MSWINCE)
617 # define is_writable(prot) ((prot) == PAGE_READWRITE \
618                             || (prot) == PAGE_WRITECOPY \
619                             || (prot) == PAGE_EXECUTE_READWRITE \
620                             || (prot) == PAGE_EXECUTE_WRITECOPY)
621 /* Return the number of bytes that are writable starting at p.  */
622 /* The pointer p is assumed to be page aligned.                 */
623 /* If base is not 0, *base becomes the beginning of the         */
624 /* allocation region containing p.                              */
625 word GC_get_writable_length(ptr_t p, ptr_t *base)
626 {
627     MEMORY_BASIC_INFORMATION buf;
628     word result;
629     word protect;
630     
631     result = VirtualQuery(p, &buf, sizeof(buf));
632     if (result != sizeof(buf)) ABORT("Weird VirtualQuery result");
633     if (base != 0) *base = (ptr_t)(buf.AllocationBase);
634     protect = (buf.Protect & ~(PAGE_GUARD | PAGE_NOCACHE));
635     if (!is_writable(protect)) {
636         return(0);
637     }
638     if (buf.State != MEM_COMMIT) return(0);
639     return(buf.RegionSize);
640 }
641
642 ptr_t GC_get_stack_base()
643 {
644     int dummy;
645     ptr_t sp = (ptr_t)(&dummy);
646     ptr_t trunc_sp = (ptr_t)((word)sp & ~(GC_page_size - 1));
647     word size = GC_get_writable_length(trunc_sp, 0);
648    
649     return(trunc_sp + size);
650 }
651
652
653 # endif /* MS Windows */
654
655 # ifdef BEOS
656 # include <kernel/OS.h>
657 ptr_t GC_get_stack_base(){
658         thread_info th;
659         get_thread_info(find_thread(NULL),&th);
660         return th.stack_end;
661 }
662 # endif /* BEOS */
663
664
665 # ifdef OS2
666
667 ptr_t GC_get_stack_base()
668 {
669     PTIB ptib;
670     PPIB ppib;
671     
672     if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
673         GC_err_printf0("DosGetInfoBlocks failed\n");
674         ABORT("DosGetInfoBlocks failed\n");
675     }
676     return((ptr_t)(ptib -> tib_pstacklimit));
677 }
678
679 # endif /* OS2 */
680
681 # ifdef AMIGA
682 #   define GC_AMIGA_SB
683 #   include "AmigaOS.c"
684 #   undef GC_AMIGA_SB
685 # endif /* AMIGA */
686
687 # if defined(NEED_FIND_LIMIT) || defined(UNIX_LIKE)
688
689 #   ifdef __STDC__
690         typedef void (*handler)(int);
691 #   else
692         typedef void (*handler)();
693 #   endif
694
695 #   if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1) \
696     || defined(HURD) || defined(NETBSD)
697         static struct sigaction old_segv_act;
698 #       if defined(IRIX5) || defined(HPUX) \
699         || defined(HURD) || defined(NETBSD)
700             static struct sigaction old_bus_act;
701 #       endif
702 #   else
703         static handler old_segv_handler, old_bus_handler;
704 #   endif
705     
706 #   ifdef __STDC__
707       void GC_set_and_save_fault_handler(handler h)
708 #   else
709       void GC_set_and_save_fault_handler(h)
710       handler h;
711 #   endif
712     {
713 #       if defined(SUNOS5SIGS) || defined(IRIX5)  \
714         || defined(OSF1) || defined(HURD) || defined(NETBSD)
715           struct sigaction      act;
716
717           act.sa_handler        = h;
718 #         if 0 /* Was necessary for Solaris 2.3 and very temporary      */
719                /* NetBSD bugs.                                          */
720             act.sa_flags          = SA_RESTART | SA_NODEFER;
721 #         else
722             act.sa_flags          = SA_RESTART;
723 #         endif
724
725           (void) sigemptyset(&act.sa_mask);
726 #         ifdef GC_IRIX_THREADS
727                 /* Older versions have a bug related to retrieving and  */
728                 /* and setting a handler at the same time.              */
729                 (void) sigaction(SIGSEGV, 0, &old_segv_act);
730                 (void) sigaction(SIGSEGV, &act, 0);
731                 (void) sigaction(SIGBUS, 0, &old_bus_act);
732                 (void) sigaction(SIGBUS, &act, 0);
733 #         else
734                 (void) sigaction(SIGSEGV, &act, &old_segv_act);
735 #               if defined(IRIX5) \
736                    || defined(HPUX) || defined(HURD) || defined(NETBSD)
737                     /* Under Irix 5.x or HP/UX, we may get SIGBUS.      */
738                     /* Pthreads doesn't exist under Irix 5.x, so we     */
739                     /* don't have to worry in the threads case.         */
740                     (void) sigaction(SIGBUS, &act, &old_bus_act);
741 #               endif
742 #         endif /* GC_IRIX_THREADS */
743 #       else
744           old_segv_handler = signal(SIGSEGV, h);
745 #         ifdef SIGBUS
746             old_bus_handler = signal(SIGBUS, h);
747 #         endif
748 #       endif
749     }
750 # endif /* NEED_FIND_LIMIT || UNIX_LIKE */
751
752 # ifdef NEED_FIND_LIMIT
753   /* Some tools to implement HEURISTIC2 */
754 #   define MIN_PAGE_SIZE 256    /* Smallest conceivable page size, bytes */
755     /* static */ JMP_BUF GC_jmp_buf;
756     
757     /*ARGSUSED*/
758     void GC_fault_handler(sig)
759     int sig;
760     {
761         LONGJMP(GC_jmp_buf, 1);
762     }
763
764     void GC_setup_temporary_fault_handler()
765     {
766         GC_set_and_save_fault_handler(GC_fault_handler);
767     }
768     
769     void GC_reset_fault_handler()
770     {
771 #       if defined(SUNOS5SIGS) || defined(IRIX5) \
772            || defined(OSF1) || defined(HURD) || defined(NETBSD)
773           (void) sigaction(SIGSEGV, &old_segv_act, 0);
774 #         if defined(IRIX5) \
775              || defined(HPUX) || defined(HURD) || defined(NETBSD)
776               (void) sigaction(SIGBUS, &old_bus_act, 0);
777 #         endif
778 #       else
779           (void) signal(SIGSEGV, old_segv_handler);
780 #         ifdef SIGBUS
781             (void) signal(SIGBUS, old_bus_handler);
782 #         endif
783 #       endif
784     }
785
786     /* Return the first nonaddressible location > p (up) or     */
787     /* the smallest location q s.t. [q,p) is addressable (!up). */
788     /* We assume that p (up) or p-1 (!up) is addressable.       */
789     ptr_t GC_find_limit(p, up)
790     ptr_t p;
791     GC_bool up;
792     {
793         static VOLATILE ptr_t result;
794                 /* Needs to be static, since otherwise it may not be    */
795                 /* preserved across the longjmp.  Can safely be         */
796                 /* static since it's only called once, with the         */
797                 /* allocation lock held.                                */
798
799
800         GC_setup_temporary_fault_handler();
801         if (SETJMP(GC_jmp_buf) == 0) {
802             result = (ptr_t)(((word)(p))
803                               & ~(MIN_PAGE_SIZE-1));
804             for (;;) {
805                 if (up) {
806                     result += MIN_PAGE_SIZE;
807                 } else {
808                     result -= MIN_PAGE_SIZE;
809                 }
810                 GC_noop1((word)(*result));
811             }
812         }
813         GC_reset_fault_handler();
814         if (!up) {
815             result += MIN_PAGE_SIZE;
816         }
817         return(result);
818     }
819 # endif
820
821 #if defined(ECOS) || defined(NOSYS)
822   ptr_t GC_get_stack_base()
823   {
824     return STACKBOTTOM;
825   }
826 #endif
827
828 #ifdef HPUX_STACKBOTTOM
829
830 #include <sys/param.h>
831 #include <sys/pstat.h>
832
833   ptr_t GC_get_register_stack_base(void)
834   {
835     struct pst_vm_status vm_status;
836
837     int i = 0;
838     while (pstat_getprocvm(&vm_status, sizeof(vm_status), 0, i++) == 1) {
839       if (vm_status.pst_type == PS_RSESTACK) {
840         return (ptr_t) vm_status.pst_vaddr;
841       }
842     }
843
844     /* old way to get the register stackbottom */
845     return (ptr_t)(((word)GC_stackbottom - BACKING_STORE_DISPLACEMENT - 1)
846                    & ~(BACKING_STORE_ALIGNMENT - 1));
847   }
848
849 #endif /* HPUX_STACK_BOTTOM */
850
851 #ifdef LINUX_STACKBOTTOM
852
853 #include <sys/types.h>
854 #include <sys/stat.h>
855
856 # define STAT_SKIP 27   /* Number of fields preceding startstack        */
857                         /* field in /proc/self/stat                     */
858
859 #ifdef USE_LIBC_PRIVATES
860 # pragma weak __libc_stack_end
861   extern ptr_t __libc_stack_end;
862 #endif
863
864 # ifdef IA64
865     /* Try to read the backing store base from /proc/self/maps. */
866     /* We look for the writable mapping with a 0 major device,  */
867     /* which is as close to our frame as possible, but below it.*/
868     static word backing_store_base_from_maps(char *maps)
869     {
870       char prot_buf[5];
871       char *buf_ptr = maps;
872       word start, end;
873       unsigned int maj_dev;
874       word current_best = 0;
875       word dummy;
876   
877       for (;;) {
878         buf_ptr = GC_parse_map_entry(buf_ptr, &start, &end, prot_buf, &maj_dev);
879         if (buf_ptr == NULL) return current_best;
880         if (prot_buf[1] == 'w' && maj_dev == 0) {
881             if (end < (word)(&dummy) && start > current_best) current_best = start;
882         }
883       }
884       return current_best;
885     }
886
887     static word backing_store_base_from_proc(void)
888     {
889         return GC_apply_to_maps(backing_store_base_from_maps);
890     }
891
892 #   ifdef USE_LIBC_PRIVATES
893 #     pragma weak __libc_ia64_register_backing_store_base
894       extern ptr_t __libc_ia64_register_backing_store_base;
895 #   endif
896
897     ptr_t GC_get_register_stack_base(void)
898     {
899 #     ifdef USE_LIBC_PRIVATES
900         if (0 != &__libc_ia64_register_backing_store_base
901             && 0 != __libc_ia64_register_backing_store_base) {
902           /* Glibc 2.2.4 has a bug such that for dynamically linked     */
903           /* executables __libc_ia64_register_backing_store_base is     */
904           /* defined but uninitialized during constructor calls.        */
905           /* Hence we check for both nonzero address and value.         */
906           return __libc_ia64_register_backing_store_base;
907         }
908 #     endif
909       word result = backing_store_base_from_proc();
910       if (0 == result) {
911           /* Use dumb heuristics.  Works only for default configuration. */
912           result = (word)GC_stackbottom - BACKING_STORE_DISPLACEMENT;
913           result += BACKING_STORE_ALIGNMENT - 1;
914           result &= ~(BACKING_STORE_ALIGNMENT - 1);
915           /* Verify that it's at least readable.  If not, we goofed. */
916           GC_noop1(*(word *)result); 
917       }
918       return (ptr_t)result;
919     }
920 # endif
921
922   ptr_t GC_linux_stack_base(void)
923   {
924     /* We read the stack base value from /proc/self/stat.  We do this   */
925     /* using direct I/O system calls in order to avoid calling malloc   */
926     /* in case REDIRECT_MALLOC is defined.                              */ 
927 #   define STAT_BUF_SIZE 4096
928 #   define STAT_READ read
929           /* Should probably call the real read, if read is wrapped.    */
930     char stat_buf[STAT_BUF_SIZE];
931     int f;
932     char c;
933     word result = 0;
934     size_t i, buf_offset = 0;
935
936     /* First try the easy way.  This should work for glibc 2.2  */
937     /* This fails in a prelinked ("prelink" command) executable */
938     /* since the correct value of __libc_stack_end never        */
939     /* becomes visible to us.  The second test works around     */
940     /* this.                                                    */  
941 #   ifdef USE_LIBC_PRIVATES
942       if (0 != &__libc_stack_end && 0 != __libc_stack_end ) {
943 #       ifdef IA64
944           /* Some versions of glibc set the address 16 bytes too        */
945           /* low while the initialization code is running.              */
946           if (((word)__libc_stack_end & 0xfff) + 0x10 < 0x1000) {
947             return __libc_stack_end + 0x10;
948           } /* Otherwise it's not safe to add 16 bytes and we fall      */
949             /* back to using /proc.                                     */
950 #       else 
951 #       ifdef SPARC
952           /* Older versions of glibc for 64-bit Sparc do not set
953            * this variable correctly, it gets set to either zero
954            * or one.
955            */
956           if (__libc_stack_end != (ptr_t) (unsigned long)0x1)
957             return __libc_stack_end;
958 #       else
959           return __libc_stack_end;
960 #       endif
961 #       endif
962       }
963 #   endif
964     f = open("/proc/self/stat", O_RDONLY);
965     if (f < 0 || STAT_READ(f, stat_buf, STAT_BUF_SIZE) < 2 * STAT_SKIP) {
966         ABORT("Couldn't read /proc/self/stat");
967     }
968     c = stat_buf[buf_offset++];
969     /* Skip the required number of fields.  This number is hopefully    */
970     /* constant across all Linux implementations.                       */
971       for (i = 0; i < STAT_SKIP; ++i) {
972         while (isspace(c)) c = stat_buf[buf_offset++];
973         while (!isspace(c)) c = stat_buf[buf_offset++];
974       }
975     while (isspace(c)) c = stat_buf[buf_offset++];
976     while (isdigit(c)) {
977       result *= 10;
978       result += c - '0';
979       c = stat_buf[buf_offset++];
980     }
981     close(f);
982     if (result < 0x10000000) ABORT("Absurd stack bottom value");
983     return (ptr_t)result;
984   }
985
986 #endif /* LINUX_STACKBOTTOM */
987
988 #ifdef FREEBSD_STACKBOTTOM
989
990 /* This uses an undocumented sysctl call, but at least one expert       */
991 /* believes it will stay.                                               */
992
993 #include <unistd.h>
994 #include <sys/types.h>
995 #include <sys/sysctl.h>
996
997   ptr_t GC_freebsd_stack_base(void)
998   {
999     int nm[2] = {CTL_KERN, KERN_USRSTACK};
1000     ptr_t base;
1001     size_t len = sizeof(ptr_t);
1002     int r = sysctl(nm, 2, &base, &len, NULL, 0);
1003     
1004     if (r) ABORT("Error getting stack base");
1005
1006     return base;
1007   }
1008
1009 #endif /* FREEBSD_STACKBOTTOM */
1010
1011 #if !defined(BEOS) && !defined(AMIGA) && !defined(MSWIN32) \
1012     && !defined(MSWINCE) && !defined(OS2) && !defined(NOSYS) && !defined(ECOS)
1013
1014 ptr_t GC_get_stack_base()
1015 {
1016 #   if defined(HEURISTIC1) || defined(HEURISTIC2) || \
1017        defined(LINUX_STACKBOTTOM) || defined(FREEBSD_STACKBOTTOM)
1018     word dummy;
1019     ptr_t result;
1020 #   endif
1021
1022 #   define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
1023
1024 #   ifdef STACKBOTTOM
1025         return(STACKBOTTOM);
1026 #   else
1027 #       ifdef HEURISTIC1
1028 #          ifdef STACK_GROWS_DOWN
1029              result = (ptr_t)((((word)(&dummy))
1030                                + STACKBOTTOM_ALIGNMENT_M1)
1031                               & ~STACKBOTTOM_ALIGNMENT_M1);
1032 #          else
1033              result = (ptr_t)(((word)(&dummy))
1034                               & ~STACKBOTTOM_ALIGNMENT_M1);
1035 #          endif
1036 #       endif /* HEURISTIC1 */
1037 #       ifdef LINUX_STACKBOTTOM
1038            result = GC_linux_stack_base();
1039 #       endif
1040 #       ifdef FREEBSD_STACKBOTTOM
1041            result = GC_freebsd_stack_base();
1042 #       endif
1043 #       ifdef HEURISTIC2
1044 #           ifdef STACK_GROWS_DOWN
1045                 result = GC_find_limit((ptr_t)(&dummy), TRUE);
1046 #               ifdef HEURISTIC2_LIMIT
1047                     if (result > HEURISTIC2_LIMIT
1048                         && (ptr_t)(&dummy) < HEURISTIC2_LIMIT) {
1049                             result = HEURISTIC2_LIMIT;
1050                     }
1051 #               endif
1052 #           else
1053                 result = GC_find_limit((ptr_t)(&dummy), FALSE);
1054 #               ifdef HEURISTIC2_LIMIT
1055                     if (result < HEURISTIC2_LIMIT
1056                         && (ptr_t)(&dummy) > HEURISTIC2_LIMIT) {
1057                             result = HEURISTIC2_LIMIT;
1058                     }
1059 #               endif
1060 #           endif
1061
1062 #       endif /* HEURISTIC2 */
1063 #       ifdef STACK_GROWS_DOWN
1064             if (result == 0) result = (ptr_t)(signed_word)(-sizeof(ptr_t));
1065 #       endif
1066         return(result);
1067 #   endif /* STACKBOTTOM */
1068 }
1069
1070 # endif /* ! AMIGA, !OS 2, ! MS Windows, !BEOS, !NOSYS, !ECOS */
1071
1072 /*
1073  * Register static data segment(s) as roots.
1074  * If more data segments are added later then they need to be registered
1075  * add that point (as we do with SunOS dynamic loading),
1076  * or GC_mark_roots needs to check for them (as we do with PCR).
1077  * Called with allocator lock held.
1078  */
1079
1080 # ifdef OS2
1081
1082 void GC_register_data_segments()
1083 {
1084     PTIB ptib;
1085     PPIB ppib;
1086     HMODULE module_handle;
1087 #   define PBUFSIZ 512
1088     UCHAR path[PBUFSIZ];
1089     FILE * myexefile;
1090     struct exe_hdr hdrdos;      /* MSDOS header.        */
1091     struct e32_exe hdr386;      /* Real header for my executable */
1092     struct o32_obj seg; /* Currrent segment */
1093     int nsegs;
1094     
1095     
1096     if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
1097         GC_err_printf0("DosGetInfoBlocks failed\n");
1098         ABORT("DosGetInfoBlocks failed\n");
1099     }
1100     module_handle = ppib -> pib_hmte;
1101     if (DosQueryModuleName(module_handle, PBUFSIZ, path) != NO_ERROR) {
1102         GC_err_printf0("DosQueryModuleName failed\n");
1103         ABORT("DosGetInfoBlocks failed\n");
1104     }
1105     myexefile = fopen(path, "rb");
1106     if (myexefile == 0) {
1107         GC_err_puts("Couldn't open executable ");
1108         GC_err_puts(path); GC_err_puts("\n");
1109         ABORT("Failed to open executable\n");
1110     }
1111     if (fread((char *)(&hdrdos), 1, sizeof hdrdos, myexefile) < sizeof hdrdos) {
1112         GC_err_puts("Couldn't read MSDOS header from ");
1113         GC_err_puts(path); GC_err_puts("\n");
1114         ABORT("Couldn't read MSDOS header");
1115     }
1116     if (E_MAGIC(hdrdos) != EMAGIC) {
1117         GC_err_puts("Executable has wrong DOS magic number: ");
1118         GC_err_puts(path); GC_err_puts("\n");
1119         ABORT("Bad DOS magic number");
1120     }
1121     if (fseek(myexefile, E_LFANEW(hdrdos), SEEK_SET) != 0) {
1122         GC_err_puts("Seek to new header failed in ");
1123         GC_err_puts(path); GC_err_puts("\n");
1124         ABORT("Bad DOS magic number");
1125     }
1126     if (fread((char *)(&hdr386), 1, sizeof hdr386, myexefile) < sizeof hdr386) {
1127         GC_err_puts("Couldn't read MSDOS header from ");
1128         GC_err_puts(path); GC_err_puts("\n");
1129         ABORT("Couldn't read OS/2 header");
1130     }
1131     if (E32_MAGIC1(hdr386) != E32MAGIC1 || E32_MAGIC2(hdr386) != E32MAGIC2) {
1132         GC_err_puts("Executable has wrong OS/2 magic number:");
1133         GC_err_puts(path); GC_err_puts("\n");
1134         ABORT("Bad OS/2 magic number");
1135     }
1136     if ( E32_BORDER(hdr386) != E32LEBO || E32_WORDER(hdr386) != E32LEWO) {
1137         GC_err_puts("Executable %s has wrong byte order: ");
1138         GC_err_puts(path); GC_err_puts("\n");
1139         ABORT("Bad byte order");
1140     }
1141     if ( E32_CPU(hdr386) == E32CPU286) {
1142         GC_err_puts("GC can't handle 80286 executables: ");
1143         GC_err_puts(path); GC_err_puts("\n");
1144         EXIT();
1145     }
1146     if (fseek(myexefile, E_LFANEW(hdrdos) + E32_OBJTAB(hdr386),
1147               SEEK_SET) != 0) {
1148         GC_err_puts("Seek to object table failed: ");
1149         GC_err_puts(path); GC_err_puts("\n");
1150         ABORT("Seek to object table failed");
1151     }
1152     for (nsegs = E32_OBJCNT(hdr386); nsegs > 0; nsegs--) {
1153       int flags;
1154       if (fread((char *)(&seg), 1, sizeof seg, myexefile) < sizeof seg) {
1155         GC_err_puts("Couldn't read obj table entry from ");
1156         GC_err_puts(path); GC_err_puts("\n");
1157         ABORT("Couldn't read obj table entry");
1158       }
1159       flags = O32_FLAGS(seg);
1160       if (!(flags & OBJWRITE)) continue;
1161       if (!(flags & OBJREAD)) continue;
1162       if (flags & OBJINVALID) {
1163           GC_err_printf0("Object with invalid pages?\n");
1164           continue;
1165       } 
1166       GC_add_roots_inner(O32_BASE(seg), O32_BASE(seg)+O32_SIZE(seg), FALSE);
1167     }
1168 }
1169
1170 # else /* !OS2 */
1171
1172 # if defined(MSWIN32) || defined(MSWINCE)
1173
1174 # ifdef MSWIN32
1175   /* Unfortunately, we have to handle win32s very differently from NT,  */
1176   /* Since VirtualQuery has very different semantics.  In particular,   */
1177   /* under win32s a VirtualQuery call on an unmapped page returns an    */
1178   /* invalid result.  Under NT, GC_register_data_segments is a noop and */
1179   /* all real work is done by GC_register_dynamic_libraries.  Under     */
1180   /* win32s, we cannot find the data segments associated with dll's.    */
1181   /* We register the main data segment here.                            */
1182   GC_bool GC_no_win32_dlls = FALSE;      
1183         /* This used to be set for gcc, to avoid dealing with           */
1184         /* the structured exception handling issues.  But we now have   */
1185         /* assembly code to do that right.                              */
1186   
1187   void GC_init_win32()
1188   {
1189     /* if we're running under win32s, assume that no DLLs will be loaded */
1190     DWORD v = GetVersion();
1191     GC_no_win32_dlls |= ((v & 0x80000000) && (v & 0xff) <= 3);
1192   }
1193
1194   /* Return the smallest address a such that VirtualQuery               */
1195   /* returns correct results for all addresses between a and start.     */
1196   /* Assumes VirtualQuery returns correct information for start.        */
1197   ptr_t GC_least_described_address(ptr_t start)
1198   {  
1199     MEMORY_BASIC_INFORMATION buf;
1200     DWORD result;
1201     LPVOID limit;
1202     ptr_t p;
1203     LPVOID q;
1204     
1205     limit = GC_sysinfo.lpMinimumApplicationAddress;
1206     p = (ptr_t)((word)start & ~(GC_page_size - 1));
1207     for (;;) {
1208         q = (LPVOID)(p - GC_page_size);
1209         if ((ptr_t)q > (ptr_t)p /* underflow */ || q < limit) break;
1210         result = VirtualQuery(q, &buf, sizeof(buf));
1211         if (result != sizeof(buf) || buf.AllocationBase == 0) break;
1212         p = (ptr_t)(buf.AllocationBase);
1213     }
1214     return(p);
1215   }
1216 # endif
1217
1218 # ifndef REDIRECT_MALLOC
1219   /* We maintain a linked list of AllocationBase values that we know    */
1220   /* correspond to malloc heap sections.  Currently this is only called */
1221   /* during a GC.  But there is some hope that for long running         */
1222   /* programs we will eventually see most heap sections.                */
1223
1224   /* In the long run, it would be more reliable to occasionally walk    */
1225   /* the malloc heap with HeapWalk on the default heap.  But that       */
1226   /* apparently works only for NT-based Windows.                        */ 
1227
1228   /* In the long run, a better data structure would also be nice ...    */
1229   struct GC_malloc_heap_list {
1230     void * allocation_base;
1231     struct GC_malloc_heap_list *next;
1232   } *GC_malloc_heap_l = 0;
1233
1234   /* Is p the base of one of the malloc heap sections we already know   */
1235   /* about?                                                             */
1236   GC_bool GC_is_malloc_heap_base(ptr_t p)
1237   {
1238     struct GC_malloc_heap_list *q = GC_malloc_heap_l;
1239
1240     while (0 != q) {
1241       if (q -> allocation_base == p) return TRUE;
1242       q = q -> next;
1243     }
1244     return FALSE;
1245   }
1246
1247   void *GC_get_allocation_base(void *p)
1248   {
1249     MEMORY_BASIC_INFORMATION buf;
1250     DWORD result = VirtualQuery(p, &buf, sizeof(buf));
1251     if (result != sizeof(buf)) {
1252       ABORT("Weird VirtualQuery result");
1253     }
1254     return buf.AllocationBase;
1255   }
1256
1257   size_t GC_max_root_size = 100000;     /* Appr. largest root size.     */
1258
1259   void GC_add_current_malloc_heap()
1260   {
1261     struct GC_malloc_heap_list *new_l =
1262                  malloc(sizeof(struct GC_malloc_heap_list));
1263     void * candidate = GC_get_allocation_base(new_l);
1264
1265     if (new_l == 0) return;
1266     if (GC_is_malloc_heap_base(candidate)) {
1267       /* Try a little harder to find malloc heap.                       */
1268         size_t req_size = 10000;
1269         do {
1270           void *p = malloc(req_size);
1271           if (0 == p) { free(new_l); return; }
1272           candidate = GC_get_allocation_base(p);
1273           free(p);
1274           req_size *= 2;
1275         } while (GC_is_malloc_heap_base(candidate)
1276                  && req_size < GC_max_root_size/10 && req_size < 500000);
1277         if (GC_is_malloc_heap_base(candidate)) {
1278           free(new_l); return;
1279         }
1280     }
1281 #   ifdef CONDPRINT
1282       if (GC_print_stats)
1283           GC_printf1("Found new system malloc AllocationBase at 0x%lx\n",
1284                      candidate);
1285 #   endif
1286     new_l -> allocation_base = candidate;
1287     new_l -> next = GC_malloc_heap_l;
1288     GC_malloc_heap_l = new_l;
1289   }
1290 # endif /* REDIRECT_MALLOC */
1291   
1292   /* Is p the start of either the malloc heap, or of one of our */
1293   /* heap sections?                                             */
1294   GC_bool GC_is_heap_base (ptr_t p)
1295   {
1296      
1297      unsigned i;
1298      
1299 #    ifndef REDIRECT_MALLOC
1300        static word last_gc_no = -1;
1301      
1302        if (last_gc_no != GC_gc_no) {
1303          GC_add_current_malloc_heap();
1304          last_gc_no = GC_gc_no;
1305        }
1306        if (GC_root_size > GC_max_root_size) GC_max_root_size = GC_root_size;
1307        if (GC_is_malloc_heap_base(p)) return TRUE;
1308 #    endif
1309      for (i = 0; i < GC_n_heap_bases; i++) {
1310          if (GC_heap_bases[i] == p) return TRUE;
1311      }
1312      return FALSE ;
1313   }
1314
1315 # ifdef MSWIN32
1316   void GC_register_root_section(ptr_t static_root)
1317   {
1318       MEMORY_BASIC_INFORMATION buf;
1319       DWORD result;
1320       DWORD protect;
1321       LPVOID p;
1322       char * base;
1323       char * limit, * new_limit;
1324     
1325       if (!GC_no_win32_dlls) return;
1326       p = base = limit = GC_least_described_address(static_root);
1327       while (p < GC_sysinfo.lpMaximumApplicationAddress) {
1328         result = VirtualQuery(p, &buf, sizeof(buf));
1329         if (result != sizeof(buf) || buf.AllocationBase == 0
1330             || GC_is_heap_base(buf.AllocationBase)) break;
1331         new_limit = (char *)p + buf.RegionSize;
1332         protect = buf.Protect;
1333         if (buf.State == MEM_COMMIT
1334             && is_writable(protect)) {
1335             if ((char *)p == limit) {
1336                 limit = new_limit;
1337             } else {
1338                 if (base != limit) GC_add_roots_inner(base, limit, FALSE);
1339                 base = p;
1340                 limit = new_limit;
1341             }
1342         }
1343         if (p > (LPVOID)new_limit /* overflow */) break;
1344         p = (LPVOID)new_limit;
1345       }
1346       if (base != limit) GC_add_roots_inner(base, limit, FALSE);
1347   }
1348 #endif
1349   
1350   void GC_register_data_segments()
1351   {
1352 #     ifdef MSWIN32
1353       static char dummy;
1354       GC_register_root_section((ptr_t)(&dummy));
1355 #     endif
1356   }
1357
1358 # else /* !OS2 && !Windows */
1359
1360 # if (defined(SVR4) || defined(AUX) || defined(DGUX) \
1361       || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
1362 ptr_t GC_SysVGetDataStart(max_page_size, etext_addr)
1363 int max_page_size;
1364 int * etext_addr;
1365 {
1366     word text_end = ((word)(etext_addr) + sizeof(word) - 1)
1367                     & ~(sizeof(word) - 1);
1368         /* etext rounded to word boundary       */
1369     word next_page = ((text_end + (word)max_page_size - 1)
1370                       & ~((word)max_page_size - 1));
1371     word page_offset = (text_end & ((word)max_page_size - 1));
1372     VOLATILE char * result = (char *)(next_page + page_offset);
1373     /* Note that this isnt equivalent to just adding            */
1374     /* max_page_size to &etext if &etext is at a page boundary  */
1375     
1376     GC_setup_temporary_fault_handler();
1377     if (SETJMP(GC_jmp_buf) == 0) {
1378         /* Try writing to the address.  */
1379         *result = *result;
1380         GC_reset_fault_handler();
1381     } else {
1382         GC_reset_fault_handler();
1383         /* We got here via a longjmp.  The address is not readable.     */
1384         /* This is known to happen under Solaris 2.4 + gcc, which place */
1385         /* string constants in the text segment, but after etext.       */
1386         /* Use plan B.  Note that we now know there is a gap between    */
1387         /* text and data segments, so plan A bought us something.       */
1388         result = (char *)GC_find_limit((ptr_t)(DATAEND), FALSE);
1389     }
1390     return((ptr_t)result);
1391 }
1392 # endif
1393
1394 # if defined(FREEBSD) && (defined(I386) || defined(powerpc) || defined(__powerpc__)) && !defined(PCR)
1395 /* Its unclear whether this should be identical to the above, or        */
1396 /* whether it should apply to non-X86 architectures.                    */
1397 /* For now we don't assume that there is always an empty page after     */
1398 /* etext.  But in some cases there actually seems to be slightly more.  */
1399 /* This also deals with holes between read-only data and writable data. */
1400 ptr_t GC_FreeBSDGetDataStart(max_page_size, etext_addr)
1401 int max_page_size;
1402 int * etext_addr;
1403 {
1404     word text_end = ((word)(etext_addr) + sizeof(word) - 1)
1405                      & ~(sizeof(word) - 1);
1406         /* etext rounded to word boundary       */
1407     VOLATILE word next_page = (text_end + (word)max_page_size - 1)
1408                               & ~((word)max_page_size - 1);
1409     VOLATILE ptr_t result = (ptr_t)text_end;
1410     GC_setup_temporary_fault_handler();
1411     if (SETJMP(GC_jmp_buf) == 0) {
1412         /* Try reading at the address.                          */
1413         /* This should happen before there is another thread.   */
1414         for (; next_page < (word)(DATAEND); next_page += (word)max_page_size)
1415             *(VOLATILE char *)next_page;
1416         GC_reset_fault_handler();
1417     } else {
1418         GC_reset_fault_handler();
1419         /* As above, we go to plan B    */
1420         result = GC_find_limit((ptr_t)(DATAEND), FALSE);
1421     }
1422     return(result);
1423 }
1424
1425 # endif
1426
1427
1428 #ifdef AMIGA
1429
1430 #  define GC_AMIGA_DS
1431 #  include "AmigaOS.c"
1432 #  undef GC_AMIGA_DS
1433
1434 #else /* !OS2 && !Windows && !AMIGA */
1435
1436 void GC_register_data_segments()
1437 {
1438 #   if !defined(PCR) && !defined(SRC_M3) && !defined(MACOS)
1439 #     if defined(REDIRECT_MALLOC) && defined(GC_SOLARIS_THREADS)
1440         /* As of Solaris 2.3, the Solaris threads implementation        */
1441         /* allocates the data structure for the initial thread with     */
1442         /* sbrk at process startup.  It needs to be scanned, so that    */
1443         /* we don't lose some malloc allocated data structures          */
1444         /* hanging from it.  We're on thin ice here ...                 */
1445         extern caddr_t sbrk();
1446
1447         GC_add_roots_inner(DATASTART, (char *)sbrk(0), FALSE);
1448 #     else
1449         GC_add_roots_inner(DATASTART, (char *)(DATAEND), FALSE);
1450 #       if defined(DATASTART2)
1451          GC_add_roots_inner(DATASTART2, (char *)(DATAEND2), FALSE);
1452 #       endif
1453 #     endif
1454 #   endif
1455 #   if defined(MACOS)
1456     {
1457 #   if defined(THINK_C)
1458         extern void* GC_MacGetDataStart(void);
1459         /* globals begin above stack and end at a5. */
1460         GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
1461                            (ptr_t)LMGetCurrentA5(), FALSE);
1462 #   else
1463 #     if defined(__MWERKS__)
1464 #       if !__POWERPC__
1465           extern void* GC_MacGetDataStart(void);
1466           /* MATTHEW: Function to handle Far Globals (CW Pro 3) */
1467 #         if __option(far_data)
1468           extern void* GC_MacGetDataEnd(void);
1469 #         endif
1470           /* globals begin above stack and end at a5. */
1471           GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
1472                              (ptr_t)LMGetCurrentA5(), FALSE);
1473           /* MATTHEW: Handle Far Globals */                          
1474 #         if __option(far_data)
1475       /* Far globals follow he QD globals: */
1476           GC_add_roots_inner((ptr_t)LMGetCurrentA5(),
1477                              (ptr_t)GC_MacGetDataEnd(), FALSE);
1478 #         endif
1479 #       else
1480           extern char __data_start__[], __data_end__[];
1481           GC_add_roots_inner((ptr_t)&__data_start__,
1482                              (ptr_t)&__data_end__, FALSE);
1483 #       endif /* __POWERPC__ */
1484 #     endif /* __MWERKS__ */
1485 #   endif /* !THINK_C */
1486     }
1487 #   endif /* MACOS */
1488
1489     /* Dynamic libraries are added at every collection, since they may  */
1490     /* change.                                                          */
1491 }
1492
1493 # endif  /* ! AMIGA */
1494 # endif  /* ! MSWIN32 && ! MSWINCE*/
1495 # endif  /* ! OS2 */
1496
1497 /*
1498  * Auxiliary routines for obtaining memory from OS.
1499  */
1500
1501 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \
1502         && !defined(MSWIN32) && !defined(MSWINCE) \
1503         && !defined(MACOS) && !defined(DOS4GW)
1504
1505 # ifdef SUNOS4
1506     extern caddr_t sbrk();
1507 # endif
1508 # ifdef __STDC__
1509 #   define SBRK_ARG_T ptrdiff_t
1510 # else
1511 #   define SBRK_ARG_T int
1512 # endif
1513
1514
1515 # if 0 && defined(RS6000)  /* We now use mmap */
1516 /* The compiler seems to generate speculative reads one past the end of */
1517 /* an allocated object.  Hence we need to make sure that the page       */
1518 /* following the last heap page is also mapped.                         */
1519 ptr_t GC_unix_get_mem(bytes)
1520 word bytes;
1521 {
1522     caddr_t cur_brk = (caddr_t)sbrk(0);
1523     caddr_t result;
1524     SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
1525     static caddr_t my_brk_val = 0;
1526     
1527     if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
1528     if (lsbs != 0) {
1529         if((caddr_t)(sbrk(GC_page_size - lsbs)) == (caddr_t)(-1)) return(0);
1530     }
1531     if (cur_brk == my_brk_val) {
1532         /* Use the extra block we allocated last time. */
1533         result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
1534         if (result == (caddr_t)(-1)) return(0);
1535         result -= GC_page_size;
1536     } else {
1537         result = (ptr_t)sbrk(GC_page_size + (SBRK_ARG_T)bytes);
1538         if (result == (caddr_t)(-1)) return(0);
1539     }
1540     my_brk_val = result + bytes + GC_page_size; /* Always page aligned */
1541     return((ptr_t)result);
1542 }
1543
1544 #else  /* Not RS6000 */
1545
1546 #if defined(USE_MMAP) || defined(USE_MUNMAP)
1547
1548 #ifdef USE_MMAP_FIXED
1549 #   define GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE
1550         /* Seems to yield better performance on Solaris 2, but can      */
1551         /* be unreliable if something is already mapped at the address. */
1552 #else
1553 #   define GC_MMAP_FLAGS MAP_PRIVATE
1554 #endif
1555
1556 #ifdef USE_MMAP_ANON
1557 # define zero_fd -1
1558 # if defined(MAP_ANONYMOUS)
1559 #   define OPT_MAP_ANON MAP_ANONYMOUS
1560 # else
1561 #   define OPT_MAP_ANON MAP_ANON
1562 # endif
1563 #else
1564   static int zero_fd;
1565 # define OPT_MAP_ANON 0
1566 #endif 
1567
1568 #endif /* defined(USE_MMAP) || defined(USE_MUNMAP) */
1569
1570 #if defined(USE_MMAP)
1571 /* Tested only under Linux, IRIX5 and Solaris 2 */
1572
1573 #ifndef HEAP_START
1574 #   define HEAP_START 0
1575 #endif
1576
1577 ptr_t GC_unix_get_mem(bytes)
1578 word bytes;
1579 {
1580     void *result;
1581     static ptr_t last_addr = HEAP_START;
1582
1583 #   ifndef USE_MMAP_ANON
1584       static GC_bool initialized = FALSE;
1585
1586       if (!initialized) {
1587           zero_fd = open("/dev/zero", O_RDONLY);
1588           fcntl(zero_fd, F_SETFD, FD_CLOEXEC);
1589           initialized = TRUE;
1590       }
1591 #   endif
1592
1593     if (bytes & (GC_page_size -1)) ABORT("Bad GET_MEM arg");
1594     result = mmap(last_addr, bytes, PROT_READ | PROT_WRITE | OPT_PROT_EXEC,
1595                   GC_MMAP_FLAGS | OPT_MAP_ANON, zero_fd, 0/* offset */);
1596     if (result == MAP_FAILED) return(0);
1597     last_addr = (ptr_t)result + bytes + GC_page_size - 1;
1598     last_addr = (ptr_t)((word)last_addr & ~(GC_page_size - 1));
1599 #   if !defined(LINUX)
1600       if (last_addr == 0) {
1601         /* Oops.  We got the end of the address space.  This isn't      */
1602         /* usable by arbitrary C code, since one-past-end pointers      */
1603         /* don't work, so we discard it and try again.                  */
1604         munmap(result, (size_t)(-GC_page_size) - (size_t)result);
1605                         /* Leave last page mapped, so we can't repeat. */
1606         return GC_unix_get_mem(bytes);
1607       }
1608 #   else
1609       GC_ASSERT(last_addr != 0);
1610 #   endif
1611     return((ptr_t)result);
1612 }
1613
1614 #else /* Not RS6000, not USE_MMAP */
1615 ptr_t GC_unix_get_mem(bytes)
1616 word bytes;
1617 {
1618   ptr_t result;
1619 # ifdef IRIX5
1620     /* Bare sbrk isn't thread safe.  Play by malloc rules.      */
1621     /* The equivalent may be needed on other systems as well.   */
1622     __LOCK_MALLOC();
1623 # endif
1624   {
1625     ptr_t cur_brk = (ptr_t)sbrk(0);
1626     SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
1627     
1628     if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
1629     if (lsbs != 0) {
1630         if((ptr_t)sbrk(GC_page_size - lsbs) == (ptr_t)(-1)) return(0);
1631     }
1632     result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
1633     if (result == (ptr_t)(-1)) result = 0;
1634   }
1635 # ifdef IRIX5
1636     __UNLOCK_MALLOC();
1637 # endif
1638   return(result);
1639 }
1640
1641 #endif /* Not USE_MMAP */
1642 #endif /* Not RS6000 */
1643
1644 # endif /* UN*X */
1645
1646 # ifdef OS2
1647
1648 void * os2_alloc(size_t bytes)
1649 {
1650     void * result;
1651
1652     if (DosAllocMem(&result, bytes, PAG_EXECUTE | PAG_READ |
1653                                     PAG_WRITE | PAG_COMMIT)
1654                     != NO_ERROR) {
1655         return(0);
1656     }
1657     if (result == 0) return(os2_alloc(bytes));
1658     return(result);
1659 }
1660
1661 # endif /* OS2 */
1662
1663
1664 # if defined(MSWIN32) || defined(MSWINCE)
1665 SYSTEM_INFO GC_sysinfo;
1666 # endif
1667
1668 # ifdef MSWIN32
1669
1670 # ifdef USE_GLOBAL_ALLOC
1671 #   define GLOBAL_ALLOC_TEST 1
1672 # else
1673 #   define GLOBAL_ALLOC_TEST GC_no_win32_dlls
1674 # endif
1675
1676 word GC_n_heap_bases = 0;
1677
1678 ptr_t GC_win32_get_mem(bytes)
1679 word bytes;
1680 {
1681     ptr_t result;
1682
1683     if (GLOBAL_ALLOC_TEST) {
1684         /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE.    */
1685         /* There are also unconfirmed rumors of other           */
1686         /* problems, so we dodge the issue.                     */
1687         result = (ptr_t) GlobalAlloc(0, bytes + HBLKSIZE);
1688         result = (ptr_t)(((word)result + HBLKSIZE) & ~(HBLKSIZE-1));
1689     } else {
1690         /* VirtualProtect only works on regions returned by a   */
1691         /* single VirtualAlloc call.  Thus we allocate one      */
1692         /* extra page, which will prevent merging of blocks     */
1693         /* in separate regions, and eliminate any temptation    */
1694         /* to call VirtualProtect on a range spanning regions.  */
1695         /* This wastes a small amount of memory, and risks      */
1696         /* increased fragmentation.  But better alternatives    */
1697         /* would require effort.                                */
1698         result = (ptr_t) VirtualAlloc(NULL, bytes + 1,
1699                                       MEM_COMMIT | MEM_RESERVE,
1700                                       PAGE_EXECUTE_READWRITE);
1701     }
1702     if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1703         /* If I read the documentation correctly, this can      */
1704         /* only happen if HBLKSIZE > 64k or not a power of 2.   */
1705     if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
1706     GC_heap_bases[GC_n_heap_bases++] = result;
1707     return(result);                       
1708 }
1709
1710 void GC_win32_free_heap ()
1711 {
1712     if (GC_no_win32_dlls) {
1713         while (GC_n_heap_bases > 0) {
1714             GlobalFree (GC_heap_bases[--GC_n_heap_bases]);
1715             GC_heap_bases[GC_n_heap_bases] = 0;
1716         }
1717     }
1718 }
1719 # endif
1720
1721 #ifdef AMIGA
1722 # define GC_AMIGA_AM
1723 # include "AmigaOS.c"
1724 # undef GC_AMIGA_AM
1725 #endif
1726
1727
1728 # ifdef MSWINCE
1729 word GC_n_heap_bases = 0;
1730
1731 ptr_t GC_wince_get_mem(bytes)
1732 word bytes;
1733 {
1734     ptr_t result;
1735     word i;
1736
1737     /* Round up allocation size to multiple of page size */
1738     bytes = (bytes + GC_page_size-1) & ~(GC_page_size-1);
1739
1740     /* Try to find reserved, uncommitted pages */
1741     for (i = 0; i < GC_n_heap_bases; i++) {
1742         if (((word)(-(signed_word)GC_heap_lengths[i])
1743              & (GC_sysinfo.dwAllocationGranularity-1))
1744             >= bytes) {
1745             result = GC_heap_bases[i] + GC_heap_lengths[i];
1746             break;
1747         }
1748     }
1749
1750     if (i == GC_n_heap_bases) {
1751         /* Reserve more pages */
1752         word res_bytes = (bytes + GC_sysinfo.dwAllocationGranularity-1)
1753                          & ~(GC_sysinfo.dwAllocationGranularity-1);
1754         /* If we ever support MPROTECT_VDB here, we will probably need to       */
1755         /* ensure that res_bytes is strictly > bytes, so that VirtualProtect    */
1756         /* never spans regions.  It seems to be OK for a VirtualFree argument   */
1757         /* to span regions, so we should be OK for now.                         */
1758         result = (ptr_t) VirtualAlloc(NULL, res_bytes,
1759                                       MEM_RESERVE | MEM_TOP_DOWN,
1760                                       PAGE_EXECUTE_READWRITE);
1761         if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1762             /* If I read the documentation correctly, this can  */
1763             /* only happen if HBLKSIZE > 64k or not a power of 2.       */
1764         if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
1765         GC_heap_bases[GC_n_heap_bases] = result;
1766         GC_heap_lengths[GC_n_heap_bases] = 0;
1767         GC_n_heap_bases++;
1768     }
1769
1770     /* Commit pages */
1771     result = (ptr_t) VirtualAlloc(result, bytes,
1772                                   MEM_COMMIT,
1773                                   PAGE_EXECUTE_READWRITE);
1774     if (result != NULL) {
1775         if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1776         GC_heap_lengths[i] += bytes;
1777     }
1778
1779     return(result);                       
1780 }
1781 # endif
1782
1783 #ifdef USE_MUNMAP
1784
1785 /* For now, this only works on Win32/WinCE and some Unix-like   */
1786 /* systems.  If you have something else, don't define           */
1787 /* USE_MUNMAP.                                                  */
1788 /* We assume ANSI C to support this feature.                    */
1789
1790 #if !defined(MSWIN32) && !defined(MSWINCE)
1791
1792 #include <unistd.h>
1793 #include <sys/mman.h>
1794 #include <sys/stat.h>
1795 #include <sys/types.h>
1796
1797 #endif
1798
1799 /* Compute a page aligned starting address for the unmap        */
1800 /* operation on a block of size bytes starting at start.        */
1801 /* Return 0 if the block is too small to make this feasible.    */
1802 ptr_t GC_unmap_start(ptr_t start, word bytes)
1803 {
1804     ptr_t result = start;
1805     /* Round start to next page boundary.       */
1806         result += GC_page_size - 1;
1807         result = (ptr_t)((word)result & ~(GC_page_size - 1));
1808     if (result + GC_page_size > start + bytes) return 0;
1809     return result;
1810 }
1811
1812 /* Compute end address for an unmap operation on the indicated  */
1813 /* block.                                                       */
1814 ptr_t GC_unmap_end(ptr_t start, word bytes)
1815 {
1816     ptr_t end_addr = start + bytes;
1817     end_addr = (ptr_t)((word)end_addr & ~(GC_page_size - 1));
1818     return end_addr;
1819 }
1820
1821 /* Under Win32/WinCE we commit (map) and decommit (unmap)       */
1822 /* memory using VirtualAlloc and VirtualFree.  These functions  */
1823 /* work on individual allocations of virtual memory, made       */
1824 /* previously using VirtualAlloc with the MEM_RESERVE flag.     */
1825 /* The ranges we need to (de)commit may span several of these   */
1826 /* allocations; therefore we use VirtualQuery to check          */
1827 /* allocation lengths, and split up the range as necessary.     */
1828
1829 /* We assume that GC_remap is called on exactly the same range  */
1830 /* as a previous call to GC_unmap.  It is safe to consistently  */
1831 /* round the endpoints in both places.                          */
1832 void GC_unmap(ptr_t start, word bytes)
1833 {
1834     ptr_t start_addr = GC_unmap_start(start, bytes);
1835     ptr_t end_addr = GC_unmap_end(start, bytes);
1836     word len = end_addr - start_addr;
1837     if (0 == start_addr) return;
1838 #   if defined(MSWIN32) || defined(MSWINCE)
1839       while (len != 0) {
1840           MEMORY_BASIC_INFORMATION mem_info;
1841           GC_word free_len;
1842           if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
1843               != sizeof(mem_info))
1844               ABORT("Weird VirtualQuery result");
1845           free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
1846           if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT))
1847               ABORT("VirtualFree failed");
1848           GC_unmapped_bytes += free_len;
1849           start_addr += free_len;
1850           len -= free_len;
1851       }
1852 #   else
1853       /* We immediately remap it to prevent an intervening mmap from    */
1854       /* accidentally grabbing the same address space.                  */
1855       {
1856         void * result;
1857         result = mmap(start_addr, len, PROT_NONE,
1858                       MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON,
1859                       zero_fd, 0/* offset */);
1860         if (result != (void *)start_addr) ABORT("mmap(...PROT_NONE...) failed");
1861       }
1862       GC_unmapped_bytes += len;
1863 #   endif
1864 }
1865
1866
1867 void GC_remap(ptr_t start, word bytes)
1868 {
1869     ptr_t start_addr = GC_unmap_start(start, bytes);
1870     ptr_t end_addr = GC_unmap_end(start, bytes);
1871     word len = end_addr - start_addr;
1872
1873 #   if defined(MSWIN32) || defined(MSWINCE)
1874       ptr_t result;
1875
1876       if (0 == start_addr) return;
1877       while (len != 0) {
1878           MEMORY_BASIC_INFORMATION mem_info;
1879           GC_word alloc_len;
1880           if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
1881               != sizeof(mem_info))
1882               ABORT("Weird VirtualQuery result");
1883           alloc_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
1884           result = VirtualAlloc(start_addr, alloc_len,
1885                                 MEM_COMMIT,
1886                                 PAGE_EXECUTE_READWRITE);
1887           if (result != start_addr) {
1888               ABORT("VirtualAlloc remapping failed");
1889           }
1890           GC_unmapped_bytes -= alloc_len;
1891           start_addr += alloc_len;
1892           len -= alloc_len;
1893       }
1894 #   else
1895       /* It was already remapped with PROT_NONE. */
1896       int result; 
1897
1898       if (0 == start_addr) return;
1899       result = mprotect(start_addr, len,
1900                         PROT_READ | PROT_WRITE | OPT_PROT_EXEC);
1901       if (result != 0) {
1902           GC_err_printf3(
1903                 "Mprotect failed at 0x%lx (length %ld) with errno %ld\n",
1904                 start_addr, len, errno);
1905           ABORT("Mprotect remapping failed");
1906       }
1907       GC_unmapped_bytes -= len;
1908 #   endif
1909 }
1910
1911 /* Two adjacent blocks have already been unmapped and are about to      */
1912 /* be merged.  Unmap the whole block.  This typically requires          */
1913 /* that we unmap a small section in the middle that was not previously  */
1914 /* unmapped due to alignment constraints.                               */
1915 void GC_unmap_gap(ptr_t start1, word bytes1, ptr_t start2, word bytes2)
1916 {
1917     ptr_t start1_addr = GC_unmap_start(start1, bytes1);
1918     ptr_t end1_addr = GC_unmap_end(start1, bytes1);
1919     ptr_t start2_addr = GC_unmap_start(start2, bytes2);
1920     ptr_t end2_addr = GC_unmap_end(start2, bytes2);
1921     ptr_t start_addr = end1_addr;
1922     ptr_t end_addr = start2_addr;
1923     word len;
1924     GC_ASSERT(start1 + bytes1 == start2);
1925     if (0 == start1_addr) start_addr = GC_unmap_start(start1, bytes1 + bytes2);
1926     if (0 == start2_addr) end_addr = GC_unmap_end(start1, bytes1 + bytes2);
1927     if (0 == start_addr) return;
1928     len = end_addr - start_addr;
1929 #   if defined(MSWIN32) || defined(MSWINCE)
1930       while (len != 0) {
1931           MEMORY_BASIC_INFORMATION mem_info;
1932           GC_word free_len;
1933           if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
1934               != sizeof(mem_info))
1935               ABORT("Weird VirtualQuery result");
1936           free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
1937           if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT))
1938               ABORT("VirtualFree failed");
1939           GC_unmapped_bytes += free_len;
1940           start_addr += free_len;
1941           len -= free_len;
1942       }
1943 #   else
1944       if (len != 0 && munmap(start_addr, len) != 0) ABORT("munmap failed");
1945       GC_unmapped_bytes += len;
1946 #   endif
1947 }
1948
1949 #endif /* USE_MUNMAP */
1950
1951 /* Routine for pushing any additional roots.  In THREADS        */
1952 /* environment, this is also responsible for marking from       */
1953 /* thread stacks.                                               */
1954 #ifndef THREADS
1955 void (*GC_push_other_roots)() = 0;
1956 #else /* THREADS */
1957
1958 # ifdef PCR
1959 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
1960 {
1961     struct PCR_ThCtl_TInfoRep info;
1962     PCR_ERes result;
1963     
1964     info.ti_stkLow = info.ti_stkHi = 0;
1965     result = PCR_ThCtl_GetInfo(t, &info);
1966     GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi));
1967     return(result);
1968 }
1969
1970 /* Push the contents of an old object. We treat this as stack   */
1971 /* data only becasue that makes it robust against mark stack    */
1972 /* overflow.                                                    */
1973 PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data)
1974 {
1975     GC_push_all_stack((ptr_t)p, (ptr_t)p + size);
1976     return(PCR_ERes_okay);
1977 }
1978
1979
1980 void GC_default_push_other_roots GC_PROTO((void))
1981 {
1982     /* Traverse data allocated by previous memory managers.             */
1983         {
1984           extern struct PCR_MM_ProcsRep * GC_old_allocator;
1985           
1986           if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false,
1987                                                    GC_push_old_obj, 0)
1988               != PCR_ERes_okay) {
1989               ABORT("Old object enumeration failed");
1990           }
1991         }
1992     /* Traverse all thread stacks. */
1993         if (PCR_ERes_IsErr(
1994                 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0))
1995               || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
1996               ABORT("Thread stack marking failed\n");
1997         }
1998 }
1999
2000 # endif /* PCR */
2001
2002 # ifdef SRC_M3
2003
2004 # ifdef ALL_INTERIOR_POINTERS
2005     --> misconfigured
2006 # endif
2007
2008 void GC_push_thread_structures GC_PROTO((void))
2009 {
2010     /* Not our responsibibility. */
2011 }
2012
2013 extern void ThreadF__ProcessStacks();
2014
2015 void GC_push_thread_stack(start, stop)
2016 word start, stop;
2017 {
2018    GC_push_all_stack((ptr_t)start, (ptr_t)stop + sizeof(word));
2019 }
2020
2021 /* Push routine with M3 specific calling convention. */
2022 GC_m3_push_root(dummy1, p, dummy2, dummy3)
2023 word *p;
2024 ptr_t dummy1, dummy2;
2025 int dummy3;
2026 {
2027     word q = *p;
2028     
2029     GC_PUSH_ONE_STACK(q, p);
2030 }
2031
2032 /* M3 set equivalent to RTHeap.TracedRefTypes */
2033 typedef struct { int elts[1]; }  RefTypeSet;
2034 RefTypeSet GC_TracedRefTypes = {{0x1}};
2035
2036 void GC_default_push_other_roots GC_PROTO((void))
2037 {
2038     /* Use the M3 provided routine for finding static roots.     */
2039     /* This is a bit dubious, since it presumes no C roots.      */
2040     /* We handle the collector roots explicitly in GC_push_roots */
2041         RTMain__GlobalMapProc(GC_m3_push_root, 0, GC_TracedRefTypes);
2042         if (GC_words_allocd > 0) {
2043             ThreadF__ProcessStacks(GC_push_thread_stack);
2044         }
2045         /* Otherwise this isn't absolutely necessary, and we have       */
2046         /* startup ordering problems.                                   */
2047 }
2048
2049 # endif /* SRC_M3 */
2050
2051 # if defined(GC_SOLARIS_THREADS) || defined(GC_PTHREADS) || \
2052      defined(GC_WIN32_THREADS)
2053
2054 extern void GC_push_all_stacks();
2055
2056 void GC_default_push_other_roots GC_PROTO((void))
2057 {
2058     GC_push_all_stacks();
2059 }
2060
2061 # endif /* GC_SOLARIS_THREADS || GC_PTHREADS */
2062
2063 void (*GC_push_other_roots) GC_PROTO((void)) = GC_default_push_other_roots;
2064
2065 #endif /* THREADS */
2066
2067 /*
2068  * Routines for accessing dirty  bits on virtual pages.
2069  * We plan to eventually implement four strategies for doing so:
2070  * DEFAULT_VDB: A simple dummy implementation that treats every page
2071  *              as possibly dirty.  This makes incremental collection
2072  *              useless, but the implementation is still correct.
2073  * PCR_VDB:     Use PPCRs virtual dirty bit facility.
2074  * PROC_VDB:    Use the /proc facility for reading dirty bits.  Only
2075  *              works under some SVR4 variants.  Even then, it may be
2076  *              too slow to be entirely satisfactory.  Requires reading
2077  *              dirty bits for entire address space.  Implementations tend
2078  *              to assume that the client is a (slow) debugger.
2079  * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
2080  *              dirtied pages.  The implementation (and implementability)
2081  *              is highly system dependent.  This usually fails when system
2082  *              calls write to a protected page.  We prevent the read system
2083  *              call from doing so.  It is the clients responsibility to
2084  *              make sure that other system calls are similarly protected
2085  *              or write only to the stack.
2086  */
2087 GC_bool GC_dirty_maintained = FALSE;
2088
2089 # ifdef DEFAULT_VDB
2090
2091 /* All of the following assume the allocation lock is held, and */
2092 /* signals are disabled.                                        */
2093
2094 /* The client asserts that unallocated pages in the heap are never      */
2095 /* written.                                                             */
2096
2097 /* Initialize virtual dirty bit implementation.                 */
2098 void GC_dirty_init()
2099 {
2100 #   ifdef PRINTSTATS
2101       GC_printf0("Initializing DEFAULT_VDB...\n");
2102 #   endif
2103     GC_dirty_maintained = TRUE;
2104 }
2105
2106 /* Retrieve system dirty bits for heap to a local buffer.       */
2107 /* Restore the systems notion of which pages are dirty.         */
2108 void GC_read_dirty()
2109 {}
2110
2111 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer?    */
2112 /* If the actual page size is different, this returns TRUE if any       */
2113 /* of the pages overlapping h are dirty.  This routine may err on the   */
2114 /* side of labelling pages as dirty (and this implementation does).     */
2115 /*ARGSUSED*/
2116 GC_bool GC_page_was_dirty(h)
2117 struct hblk *h;
2118 {
2119     return(TRUE);
2120 }
2121
2122 /*
2123  * The following two routines are typically less crucial.  They matter
2124  * most with large dynamic libraries, or if we can't accurately identify
2125  * stacks, e.g. under Solaris 2.X.  Otherwise the following default
2126  * versions are adequate.
2127  */
2128  
2129 /* Could any valid GC heap pointer ever have been written to this page? */
2130 /*ARGSUSED*/
2131 GC_bool GC_page_was_ever_dirty(h)
2132 struct hblk *h;
2133 {
2134     return(TRUE);
2135 }
2136
2137 /* Reset the n pages starting at h to "was never dirty" status. */
2138 void GC_is_fresh(h, n)
2139 struct hblk *h;
2140 word n;
2141 {
2142 }
2143
2144 /* A call that:                                         */
2145 /* I) hints that [h, h+nblocks) is about to be written. */
2146 /* II) guarantees that protection is removed.           */
2147 /* (I) may speed up some dirty bit implementations.     */
2148 /* (II) may be essential if we need to ensure that      */
2149 /* pointer-free system call buffers in the heap are     */
2150 /* not protected.                                       */
2151 /*ARGSUSED*/
2152 void GC_remove_protection(h, nblocks, is_ptrfree)
2153 struct hblk *h;
2154 word nblocks;
2155 GC_bool is_ptrfree;
2156 {
2157 }
2158
2159 # endif /* DEFAULT_VDB */
2160
2161
2162 # ifdef MPROTECT_VDB
2163
2164 /*
2165  * See DEFAULT_VDB for interface descriptions.
2166  */
2167
2168 /*
2169  * This implementation maintains dirty bits itself by catching write
2170  * faults and keeping track of them.  We assume nobody else catches
2171  * SIGBUS or SIGSEGV.  We assume no write faults occur in system calls.
2172  * This means that clients must ensure that system calls don't write
2173  * to the write-protected heap.  Probably the best way to do this is to
2174  * ensure that system calls write at most to POINTERFREE objects in the
2175  * heap, and do even that only if we are on a platform on which those
2176  * are not protected.  Another alternative is to wrap system calls
2177  * (see example for read below), but the current implementation holds
2178  * a lock across blocking calls, making it problematic for multithreaded
2179  * applications. 
2180  * We assume the page size is a multiple of HBLKSIZE.
2181  * We prefer them to be the same.  We avoid protecting POINTERFREE
2182  * objects only if they are the same.
2183  */
2184
2185 # if !defined(MSWIN32) && !defined(MSWINCE) && !defined(DARWIN)
2186
2187 #   include <sys/mman.h>
2188 #   include <signal.h>
2189 #   include <sys/syscall.h>
2190
2191 #   define PROTECT(addr, len) \
2192           if (mprotect((caddr_t)(addr), (size_t)(len), \
2193                        PROT_READ | OPT_PROT_EXEC) < 0) { \
2194             ABORT("mprotect failed"); \
2195           }
2196 #   define UNPROTECT(addr, len) \
2197           if (mprotect((caddr_t)(addr), (size_t)(len), \
2198                        PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
2199             ABORT("un-mprotect failed"); \
2200           }
2201           
2202 # else
2203
2204 # ifdef DARWIN
2205     /* Using vm_protect (mach syscall) over mprotect (BSD syscall) seems to
2206        decrease the likelihood of some of the problems described below. */
2207     #include <mach/vm_map.h>
2208     static mach_port_t GC_task_self;
2209     #define PROTECT(addr,len) \
2210         if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2211                 FALSE,VM_PROT_READ) != KERN_SUCCESS) { \
2212             ABORT("vm_portect failed"); \
2213         }
2214     #define UNPROTECT(addr,len) \
2215         if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2216                 FALSE,VM_PROT_READ|VM_PROT_WRITE) != KERN_SUCCESS) { \
2217             ABORT("vm_portect failed"); \
2218         }
2219 # else
2220     
2221 #   ifndef MSWINCE
2222 #     include <signal.h>
2223 #   endif
2224
2225     static DWORD protect_junk;
2226 #   define PROTECT(addr, len) \
2227           if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
2228                               &protect_junk)) { \
2229             DWORD last_error = GetLastError(); \
2230             GC_printf1("Last error code: %lx\n", last_error); \
2231             ABORT("VirtualProtect failed"); \
2232           }
2233 #   define UNPROTECT(addr, len) \
2234           if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
2235                               &protect_junk)) { \
2236             ABORT("un-VirtualProtect failed"); \
2237           }
2238 # endif /* !DARWIN */
2239 # endif /* MSWIN32 || MSWINCE || DARWIN */
2240
2241 #if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2242     typedef void (* SIG_PF)();
2243 #endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2244
2245 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX) \
2246     || defined(HURD)
2247 # ifdef __STDC__
2248     typedef void (* SIG_PF)(int);
2249 # else
2250     typedef void (* SIG_PF)();
2251 # endif
2252 #endif /* SUNOS5SIGS || OSF1 || LINUX || HURD */
2253
2254 #if defined(MSWIN32)
2255     typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
2256 #   undef SIG_DFL
2257 #   define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
2258 #endif
2259 #if defined(MSWINCE)
2260     typedef LONG (WINAPI *SIG_PF)(struct _EXCEPTION_POINTERS *);
2261 #   undef SIG_DFL
2262 #   define SIG_DFL (SIG_PF) (-1)
2263 #endif
2264
2265 #if defined(IRIX5) || defined(OSF1) || defined(HURD)
2266     typedef void (* REAL_SIG_PF)(int, int, struct sigcontext *);
2267 #endif /* IRIX5 || OSF1 || HURD */
2268
2269 #if defined(SUNOS5SIGS)
2270 # if defined(HPUX) || defined(FREEBSD)
2271 #   define SIGINFO_T siginfo_t
2272 # else
2273 #   define SIGINFO_T struct siginfo
2274 # endif
2275 # ifdef __STDC__
2276     typedef void (* REAL_SIG_PF)(int, SIGINFO_T *, void *);
2277 # else
2278     typedef void (* REAL_SIG_PF)();
2279 # endif
2280 #endif /* SUNOS5SIGS */
2281
2282 #if defined(LINUX)
2283 #   if __GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ >= 2
2284       typedef struct sigcontext s_c;
2285 #   else  /* glibc < 2.2 */
2286 #     include <linux/version.h>
2287 #     if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA) || defined(ARM32)
2288         typedef struct sigcontext s_c;
2289 #     else
2290         typedef struct sigcontext_struct s_c;
2291 #     endif
2292 #   endif  /* glibc < 2.2 */
2293 #   if defined(ALPHA) || defined(M68K)
2294       typedef void (* REAL_SIG_PF)(int, int, s_c *);
2295 #   else
2296 #     if defined(IA64) || defined(HP_PA) || defined(X86_64)
2297         typedef void (* REAL_SIG_PF)(int, siginfo_t *, s_c *);
2298         /* FIXME:                                                 */
2299         /* According to SUSV3, the last argument should have type */
2300         /* void * or ucontext_t *                                 */
2301 #     else
2302         typedef void (* REAL_SIG_PF)(int, s_c);
2303 #     endif
2304 #   endif
2305 #   ifdef ALPHA
2306     /* Retrieve fault address from sigcontext structure by decoding     */
2307     /* instruction.                                                     */
2308     char * get_fault_addr(s_c *sc) {
2309         unsigned instr;
2310         word faultaddr;
2311
2312         instr = *((unsigned *)(sc->sc_pc));
2313         faultaddr = sc->sc_regs[(instr >> 16) & 0x1f];
2314         faultaddr += (word) (((int)instr << 16) >> 16);
2315         return (char *)faultaddr;
2316     }
2317 #   endif /* !ALPHA */
2318 # endif /* LINUX */
2319
2320 #ifndef DARWIN
2321 SIG_PF GC_old_bus_handler;
2322 SIG_PF GC_old_segv_handler;     /* Also old MSWIN32 ACCESS_VIOLATION filter */
2323 #endif /* !DARWIN */
2324
2325 #if defined(THREADS)
2326 /* We need to lock around the bitmap update in the write fault handler  */
2327 /* in order to avoid the risk of losing a bit.  We do this with a       */
2328 /* test-and-set spin lock if we know how to do that.  Otherwise we      */
2329 /* check whether we are already in the handler and use the dumb but     */
2330 /* safe fallback algorithm of setting all bits in the word.             */
2331 /* Contention should be very rare, so we do the minimum to handle it    */
2332 /* correctly.                                                           */
2333 #ifdef GC_TEST_AND_SET_DEFINED
2334   static VOLATILE unsigned int fault_handler_lock = 0;
2335   void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2336     while (GC_test_and_set(&fault_handler_lock)) {}
2337     /* Could also revert to set_pht_entry_from_index_safe if initial    */
2338     /* GC_test_and_set fails.                                           */
2339     set_pht_entry_from_index(db, index);
2340     GC_clear(&fault_handler_lock);
2341   }
2342 #else /* !GC_TEST_AND_SET_DEFINED */
2343   /* THIS IS INCORRECT! The dirty bit vector may be temporarily wrong,  */
2344   /* just before we notice the conflict and correct it. We may end up   */
2345   /* looking at it while it's wrong.  But this requires contention      */
2346   /* exactly when a GC is triggered, which seems far less likely to     */
2347   /* fail than the old code, which had no reported failures.  Thus we   */
2348   /* leave it this way while we think of something better, or support   */
2349   /* GC_test_and_set on the remaining platforms.                        */
2350   static VOLATILE word currently_updating = 0;
2351   void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2352     unsigned int update_dummy;
2353     currently_updating = (word)(&update_dummy);
2354     set_pht_entry_from_index(db, index);
2355     /* If we get contention in the 10 or so instruction window here,    */
2356     /* and we get stopped by a GC between the two updates, we lose!     */
2357     if (currently_updating != (word)(&update_dummy)) {
2358         set_pht_entry_from_index_safe(db, index);
2359         /* We claim that if two threads concurrently try to update the  */
2360         /* dirty bit vector, the first one to execute UPDATE_START      */
2361         /* will see it changed when UPDATE_END is executed.  (Note that */
2362         /* &update_dummy must differ in two distinct threads.)  It      */
2363         /* will then execute set_pht_entry_from_index_safe, thus        */
2364         /* returning us to a safe state, though not soon enough.        */
2365     }
2366   }
2367 #endif /* !GC_TEST_AND_SET_DEFINED */
2368 #else /* !THREADS */
2369 # define async_set_pht_entry_from_index(db, index) \
2370         set_pht_entry_from_index(db, index)
2371 #endif /* !THREADS */
2372
2373 /*ARGSUSED*/
2374 #if !defined(DARWIN)
2375 # if defined (SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2376     void GC_write_fault_handler(sig, code, scp, addr)
2377     int sig, code;
2378     struct sigcontext *scp;
2379     char * addr;
2380 #   ifdef SUNOS4
2381 #     define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2382 #     define CODE_OK (FC_CODE(code) == FC_PROT \
2383                     || (FC_CODE(code) == FC_OBJERR \
2384                        && FC_ERRNO(code) == FC_PROT))
2385 #   endif
2386 #   ifdef FREEBSD
2387 #     define SIG_OK (sig == SIGBUS)
2388 #     define CODE_OK TRUE
2389 #   endif
2390 # endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2391
2392 # if defined(IRIX5) || defined(OSF1) || defined(HURD)
2393 #   include <errno.h>
2394     void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
2395 #   ifdef OSF1
2396 #     define SIG_OK (sig == SIGSEGV)
2397 #     define CODE_OK (code == 2 /* experimentally determined */)
2398 #   endif
2399 #   ifdef IRIX5
2400 #     define SIG_OK (sig == SIGSEGV)
2401 #     define CODE_OK (code == EACCES)
2402 #   endif
2403 #   ifdef HURD
2404 #     define SIG_OK (sig == SIGBUS || sig == SIGSEGV)   
2405 #     define CODE_OK  TRUE
2406 #   endif
2407 # endif /* IRIX5 || OSF1 || HURD */
2408
2409 # if defined(LINUX)
2410 #   if defined(ALPHA) || defined(M68K)
2411       void GC_write_fault_handler(int sig, int code, s_c * sc)
2412 #   else
2413 #     if defined(IA64) || defined(HP_PA) || defined(X86_64)
2414         void GC_write_fault_handler(int sig, siginfo_t * si, s_c * scp)
2415 #     else
2416 #       if defined(ARM32)
2417           void GC_write_fault_handler(int sig, int a2, int a3, int a4, s_c sc)
2418 #       else
2419           void GC_write_fault_handler(int sig, s_c sc)
2420 #       endif
2421 #     endif
2422 #   endif
2423 #   define SIG_OK (sig == SIGSEGV)
2424 #   define CODE_OK TRUE
2425         /* Empirically c.trapno == 14, on IA32, but is that useful?     */
2426         /* Should probably consider alignment issues on other           */
2427         /* architectures.                                               */
2428 # endif /* LINUX */
2429
2430 # if defined(SUNOS5SIGS)
2431 #  ifdef __STDC__
2432     void GC_write_fault_handler(int sig, SIGINFO_T *scp, void * context)
2433 #  else
2434     void GC_write_fault_handler(sig, scp, context)
2435     int sig;
2436     SIGINFO_T *scp;
2437     void * context;
2438 #  endif
2439 #   ifdef HPUX
2440 #     define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2441 #     define CODE_OK (scp -> si_code == SEGV_ACCERR) \
2442                      || (scp -> si_code == BUS_ADRERR) \
2443                      || (scp -> si_code == BUS_UNKNOWN) \
2444                      || (scp -> si_code == SEGV_UNKNOWN) \
2445                      || (scp -> si_code == BUS_OBJERR)
2446 #   else
2447 #     ifdef FREEBSD
2448 #       define SIG_OK (sig == SIGBUS)
2449 #       define CODE_OK (scp -> si_code == BUS_PAGE_FAULT)
2450 #     else
2451 #       define SIG_OK (sig == SIGSEGV)
2452 #       define CODE_OK (scp -> si_code == SEGV_ACCERR)
2453 #     endif
2454 #   endif    
2455 # endif /* SUNOS5SIGS */
2456
2457 # if defined(MSWIN32) || defined(MSWINCE)
2458     LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info)
2459 #   define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
2460                         STATUS_ACCESS_VIOLATION)
2461 #   define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
2462                         /* Write fault */
2463 # endif /* MSWIN32 || MSWINCE */
2464 {
2465     register unsigned i;
2466 #   if defined(HURD) 
2467         char *addr = (char *) code;
2468 #   endif
2469 #   ifdef IRIX5
2470         char * addr = (char *) (size_t) (scp -> sc_badvaddr);
2471 #   endif
2472 #   if defined(OSF1) && defined(ALPHA)
2473         char * addr = (char *) (scp -> sc_traparg_a0);
2474 #   endif
2475 #   ifdef SUNOS5SIGS
2476         char * addr = (char *) (scp -> si_addr);
2477 #   endif
2478 #   ifdef LINUX
2479 #     if defined(I386)
2480         char * addr = (char *) (sc.cr2);
2481 #     else
2482 #       if defined(M68K)
2483           char * addr = NULL;
2484
2485           struct sigcontext *scp = (struct sigcontext *)(sc);
2486
2487           int format = (scp->sc_formatvec >> 12) & 0xf;
2488           unsigned long *framedata = (unsigned long *)(scp + 1); 
2489           unsigned long ea;
2490
2491           if (format == 0xa || format == 0xb) {
2492                 /* 68020/030 */
2493                 ea = framedata[2];
2494           } else if (format == 7) {
2495                 /* 68040 */
2496                 ea = framedata[3];
2497                 if (framedata[1] & 0x08000000) {
2498                         /* correct addr on misaligned access */
2499                         ea = (ea+4095)&(~4095);
2500                 }
2501           } else if (format == 4) {
2502                 /* 68060 */
2503                 ea = framedata[0];
2504                 if (framedata[1] & 0x08000000) {
2505                         /* correct addr on misaligned access */
2506                         ea = (ea+4095)&(~4095);
2507                 }
2508           }     
2509           addr = (char *)ea;
2510 #       else
2511 #         ifdef ALPHA
2512             char * addr = get_fault_addr(sc);
2513 #         else
2514 #           if defined(IA64) || defined(HP_PA) || defined(X86_64)
2515               char * addr = si -> si_addr;
2516               /* I believe this is claimed to work on all platforms for */
2517               /* Linux 2.3.47 and later.  Hopefully we don't have to    */
2518               /* worry about earlier kernels on IA64.                   */
2519 #           else
2520 #             if defined(POWERPC)
2521                 char * addr = (char *) (sc.regs->dar);
2522 #             else
2523 #               if defined(ARM32)
2524                   char * addr = (char *)sc.fault_address;
2525 #               else
2526 #                 if defined(CRIS)
2527                     char * addr = (char *)sc.regs.csraddr;
2528 #                 else
2529                     --> architecture not supported
2530 #                 endif
2531 #               endif
2532 #             endif
2533 #           endif
2534 #         endif
2535 #       endif
2536 #     endif
2537 #   endif
2538 #   if defined(MSWIN32) || defined(MSWINCE)
2539         char * addr = (char *) (exc_info -> ExceptionRecord
2540                                 -> ExceptionInformation[1]);
2541 #       define sig SIGSEGV
2542 #   endif
2543     
2544     if (SIG_OK && CODE_OK) {
2545         register struct hblk * h =
2546                         (struct hblk *)((word)addr & ~(GC_page_size-1));
2547         GC_bool in_allocd_block;
2548         
2549 #       ifdef SUNOS5SIGS
2550             /* Address is only within the correct physical page.        */
2551             in_allocd_block = FALSE;
2552             for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2553               if (HDR(h+i) != 0) {
2554                 in_allocd_block = TRUE;
2555               }
2556             }
2557 #       else
2558             in_allocd_block = (HDR(addr) != 0);
2559 #       endif
2560         if (!in_allocd_block) {
2561             /* FIXME - We should make sure that we invoke the   */
2562             /* old handler with the appropriate calling         */
2563             /* sequence, which often depends on SA_SIGINFO.     */
2564
2565             /* Heap blocks now begin and end on page boundaries */
2566             SIG_PF old_handler;
2567             
2568             if (sig == SIGSEGV) {
2569                 old_handler = GC_old_segv_handler;
2570             } else {
2571                 old_handler = GC_old_bus_handler;
2572             }
2573             if (old_handler == SIG_DFL) {
2574 #               if !defined(MSWIN32) && !defined(MSWINCE)
2575                     GC_err_printf1("Segfault at 0x%lx\n", addr);
2576                     ABORT("Unexpected bus error or segmentation fault");
2577 #               else
2578                     return(EXCEPTION_CONTINUE_SEARCH);
2579 #               endif
2580             } else {
2581 #               if defined (SUNOS4) \
2582                     || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2583                     (*old_handler) (sig, code, scp, addr);
2584                     return;
2585 #               endif
2586 #               if defined (SUNOS5SIGS)
2587                     /*
2588                      * FIXME: For FreeBSD, this code should check if the 
2589                      * old signal handler used the traditional BSD style and
2590                      * if so call it using that style.
2591                      */
2592                     (*(REAL_SIG_PF)old_handler) (sig, scp, context);
2593                     return;
2594 #               endif
2595 #               if defined (LINUX)
2596 #                   if defined(ALPHA) || defined(M68K)
2597                         (*(REAL_SIG_PF)old_handler) (sig, code, sc);
2598 #                   else 
2599 #                     if defined(IA64) || defined(HP_PA) || defined(X86_64)
2600                         (*(REAL_SIG_PF)old_handler) (sig, si, scp);
2601 #                     else
2602                         (*(REAL_SIG_PF)old_handler) (sig, sc);
2603 #                     endif
2604 #                   endif
2605                     return;
2606 #               endif
2607 #               if defined (IRIX5) || defined(OSF1) || defined(HURD)
2608                     (*(REAL_SIG_PF)old_handler) (sig, code, scp);
2609                     return;
2610 #               endif
2611 #               ifdef MSWIN32
2612                     return((*old_handler)(exc_info));
2613 #               endif
2614             }
2615         }
2616         UNPROTECT(h, GC_page_size);
2617         /* We need to make sure that no collection occurs between       */
2618         /* the UNPROTECT and the setting of the dirty bit.  Otherwise   */
2619         /* a write by a third thread might go unnoticed.  Reversing     */
2620         /* the order is just as bad, since we would end up unprotecting */
2621         /* a page in a GC cycle during which it's not marked.           */
2622         /* Currently we do this by disabling the thread stopping        */
2623         /* signals while this handler is running.  An alternative might */
2624         /* be to record the fact that we're about to unprotect, or      */
2625         /* have just unprotected a page in the GC's thread structure,   */
2626         /* and then to have the thread stopping code set the dirty      */
2627         /* flag, if necessary.                                          */
2628         for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2629             register int index = PHT_HASH(h+i);
2630             
2631             async_set_pht_entry_from_index(GC_dirty_pages, index);
2632         }
2633 #       if defined(OSF1)
2634             /* These reset the signal handler each time by default. */
2635             signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
2636 #       endif
2637         /* The write may not take place before dirty bits are read.     */
2638         /* But then we'll fault again ...                               */
2639 #       if defined(MSWIN32) || defined(MSWINCE)
2640             return(EXCEPTION_CONTINUE_EXECUTION);
2641 #       else
2642             return;
2643 #       endif
2644     }
2645 #if defined(MSWIN32) || defined(MSWINCE)
2646     return EXCEPTION_CONTINUE_SEARCH;
2647 #else
2648     GC_err_printf1("Segfault at 0x%lx\n", addr);
2649     ABORT("Unexpected bus error or segmentation fault");
2650 #endif
2651 }
2652 #endif /* !DARWIN */
2653
2654 /*
2655  * We hold the allocation lock.  We expect block h to be written
2656  * shortly.  Ensure that all pages containing any part of the n hblks
2657  * starting at h are no longer protected.  If is_ptrfree is false,
2658  * also ensure that they will subsequently appear to be dirty.
2659  */
2660 void GC_remove_protection(h, nblocks, is_ptrfree)
2661 struct hblk *h;
2662 word nblocks;
2663 GC_bool is_ptrfree;
2664 {
2665     struct hblk * h_trunc;  /* Truncated to page boundary */
2666     struct hblk * h_end;    /* Page boundary following block end */
2667     struct hblk * current;
2668     GC_bool found_clean;
2669     
2670     if (!GC_dirty_maintained) return;
2671     h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1));
2672     h_end = (struct hblk *)(((word)(h + nblocks) + GC_page_size-1)
2673                             & ~(GC_page_size-1));
2674     found_clean = FALSE;
2675     for (current = h_trunc; current < h_end; ++current) {
2676         int index = PHT_HASH(current);
2677             
2678         if (!is_ptrfree || current < h || current >= h + nblocks) {
2679             async_set_pht_entry_from_index(GC_dirty_pages, index);
2680         }
2681     }
2682     UNPROTECT(h_trunc, (ptr_t)h_end - (ptr_t)h_trunc);
2683 }
2684
2685 #if !defined(DARWIN)
2686 void GC_dirty_init()
2687 {
2688 #   if defined(SUNOS5SIGS) || defined(IRIX5) || defined(LINUX) || \
2689        defined(OSF1) || defined(HURD)
2690       struct sigaction  act, oldact;
2691       /* We should probably specify SA_SIGINFO for Linux, and handle    */
2692       /* the different architectures more uniformly.                    */
2693 #     if defined(IRIX5) || defined(LINUX) && !defined(X86_64) \
2694          || defined(OSF1) || defined(HURD)
2695         act.sa_flags    = SA_RESTART;
2696         act.sa_handler  = (SIG_PF)GC_write_fault_handler;
2697 #     else
2698         act.sa_flags    = SA_RESTART | SA_SIGINFO;
2699         act.sa_sigaction = GC_write_fault_handler;
2700 #     endif
2701       (void)sigemptyset(&act.sa_mask);
2702 #     ifdef SIG_SUSPEND
2703         /* Arrange to postpone SIG_SUSPEND while we're in a write fault */
2704         /* handler.  This effectively makes the handler atomic w.r.t.   */
2705         /* stopping the world for GC.                                   */
2706         (void)sigaddset(&act.sa_mask, SIG_SUSPEND);
2707 #     endif /* SIG_SUSPEND */
2708 #    endif
2709 #   ifdef PRINTSTATS
2710         GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2711 #   endif
2712     GC_dirty_maintained = TRUE;
2713     if (GC_page_size % HBLKSIZE != 0) {
2714         GC_err_printf0("Page size not multiple of HBLKSIZE\n");
2715         ABORT("Page size not multiple of HBLKSIZE");
2716     }
2717 #   if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2718       GC_old_bus_handler = signal(SIGBUS, GC_write_fault_handler);
2719       if (GC_old_bus_handler == SIG_IGN) {
2720         GC_err_printf0("Previously ignored bus error!?");
2721         GC_old_bus_handler = SIG_DFL;
2722       }
2723       if (GC_old_bus_handler != SIG_DFL) {
2724 #       ifdef PRINTSTATS
2725           GC_err_printf0("Replaced other SIGBUS handler\n");
2726 #       endif
2727       }
2728 #   endif
2729 #   if defined(SUNOS4)
2730       GC_old_segv_handler = signal(SIGSEGV, (SIG_PF)GC_write_fault_handler);
2731       if (GC_old_segv_handler == SIG_IGN) {
2732         GC_err_printf0("Previously ignored segmentation violation!?");
2733         GC_old_segv_handler = SIG_DFL;
2734       }
2735       if (GC_old_segv_handler != SIG_DFL) {
2736 #       ifdef PRINTSTATS
2737           GC_err_printf0("Replaced other SIGSEGV handler\n");
2738 #       endif
2739       }
2740 #   endif
2741 #   if (defined(SUNOS5SIGS) && !defined(FREEBSD)) || defined(IRIX5) \
2742        || defined(LINUX) || defined(OSF1) || defined(HURD)
2743       /* SUNOS5SIGS includes HPUX */
2744 #     if defined(GC_IRIX_THREADS)
2745         sigaction(SIGSEGV, 0, &oldact);
2746         sigaction(SIGSEGV, &act, 0);
2747 #     else 
2748         {
2749           int res = sigaction(SIGSEGV, &act, &oldact);
2750           if (res != 0) ABORT("Sigaction failed");
2751         }
2752 #     endif
2753 #     if defined(_sigargs) || defined(HURD) || !defined(SA_SIGINFO)
2754         /* This is Irix 5.x, not 6.x.  Irix 5.x does not have   */
2755         /* sa_sigaction.                                        */
2756         GC_old_segv_handler = oldact.sa_handler;
2757 #     else /* Irix 6.x or SUNOS5SIGS or LINUX */
2758         if (oldact.sa_flags & SA_SIGINFO) {
2759           GC_old_segv_handler = (SIG_PF)(oldact.sa_sigaction);
2760         } else {
2761           GC_old_segv_handler = oldact.sa_handler;
2762         }
2763 #     endif
2764       if (GC_old_segv_handler == SIG_IGN) {
2765              GC_err_printf0("Previously ignored segmentation violation!?");
2766              GC_old_segv_handler = SIG_DFL;
2767       }
2768       if (GC_old_segv_handler != SIG_DFL) {
2769 #       ifdef PRINTSTATS
2770           GC_err_printf0("Replaced other SIGSEGV handler\n");
2771 #       endif
2772       }
2773 #   endif /* (SUNOS5SIGS && !FREEBSD) || IRIX5 || LINUX || OSF1 || HURD */
2774 #   if defined(HPUX) || defined(LINUX) || defined(HURD) \
2775       || (defined(FREEBSD) && defined(SUNOS5SIGS))
2776       sigaction(SIGBUS, &act, &oldact);
2777       GC_old_bus_handler = oldact.sa_handler;
2778       if (GC_old_bus_handler == SIG_IGN) {
2779              GC_err_printf0("Previously ignored bus error!?");
2780              GC_old_bus_handler = SIG_DFL;
2781       }
2782       if (GC_old_bus_handler != SIG_DFL) {
2783 #       ifdef PRINTSTATS
2784           GC_err_printf0("Replaced other SIGBUS handler\n");
2785 #       endif
2786       }
2787 #   endif /* HPUX || LINUX || HURD || (FREEBSD && SUNOS5SIGS) */
2788 #   if defined(MSWIN32)
2789       GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler);
2790       if (GC_old_segv_handler != NULL) {
2791 #       ifdef PRINTSTATS
2792           GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
2793 #       endif
2794       } else {
2795           GC_old_segv_handler = SIG_DFL;
2796       }
2797 #   endif
2798 }
2799 #endif /* !DARWIN */
2800
2801 int GC_incremental_protection_needs()
2802 {
2803     if (GC_page_size == HBLKSIZE) {
2804         return GC_PROTECTS_POINTER_HEAP;
2805     } else {
2806         return GC_PROTECTS_POINTER_HEAP | GC_PROTECTS_PTRFREE_HEAP;
2807     }
2808 }
2809
2810 #define HAVE_INCREMENTAL_PROTECTION_NEEDS
2811
2812 #define IS_PTRFREE(hhdr) ((hhdr)->hb_descr == 0)
2813
2814 #define PAGE_ALIGNED(x) !((word)(x) & (GC_page_size - 1))
2815 void GC_protect_heap()
2816 {
2817     ptr_t start;
2818     word len;
2819     struct hblk * current;
2820     struct hblk * current_start;  /* Start of block to be protected. */
2821     struct hblk * limit;
2822     unsigned i;
2823     GC_bool protect_all = 
2824           (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP));
2825     for (i = 0; i < GC_n_heap_sects; i++) {
2826         start = GC_heap_sects[i].hs_start;
2827         len = GC_heap_sects[i].hs_bytes;
2828         if (protect_all) {
2829           PROTECT(start, len);
2830         } else {
2831           GC_ASSERT(PAGE_ALIGNED(len))
2832           GC_ASSERT(PAGE_ALIGNED(start))
2833           current_start = current = (struct hblk *)start;
2834           limit = (struct hblk *)(start + len);
2835           while (current < limit) {
2836             hdr * hhdr;
2837             word nhblks;
2838             GC_bool is_ptrfree;
2839
2840             GC_ASSERT(PAGE_ALIGNED(current));
2841             GET_HDR(current, hhdr);
2842             if (IS_FORWARDING_ADDR_OR_NIL(hhdr)) {
2843               /* This can happen only if we're at the beginning of a    */
2844               /* heap segment, and a block spans heap segments.         */
2845               /* We will handle that block as part of the preceding     */
2846               /* segment.                                               */
2847               GC_ASSERT(current_start == current);
2848               current_start = ++current;
2849               continue;
2850             }
2851             if (HBLK_IS_FREE(hhdr)) {
2852               GC_ASSERT(PAGE_ALIGNED(hhdr -> hb_sz));
2853               nhblks = divHBLKSZ(hhdr -> hb_sz);
2854               is_ptrfree = TRUE;        /* dirty on alloc */
2855             } else {
2856               nhblks = OBJ_SZ_TO_BLOCKS(hhdr -> hb_sz);
2857               is_ptrfree = IS_PTRFREE(hhdr);
2858             }
2859             if (is_ptrfree) {
2860               if (current_start < current) {
2861                 PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
2862               }
2863               current_start = (current += nhblks);
2864             } else {
2865               current += nhblks;
2866             }
2867           } 
2868           if (current_start < current) {
2869             PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
2870           }
2871         }
2872     }
2873 }
2874
2875 /* We assume that either the world is stopped or its OK to lose dirty   */
2876 /* bits while this is happenning (as in GC_enable_incremental).         */
2877 void GC_read_dirty()
2878 {
2879     BCOPY((word *)GC_dirty_pages, GC_grungy_pages,
2880           (sizeof GC_dirty_pages));
2881     BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages));
2882     GC_protect_heap();
2883 }
2884
2885 GC_bool GC_page_was_dirty(h)
2886 struct hblk * h;
2887 {
2888     register word index = PHT_HASH(h);
2889     
2890     return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index));
2891 }
2892
2893 /*
2894  * Acquiring the allocation lock here is dangerous, since this
2895  * can be called from within GC_call_with_alloc_lock, and the cord
2896  * package does so.  On systems that allow nested lock acquisition, this
2897  * happens to work.
2898  * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
2899  */
2900
2901 static GC_bool syscall_acquired_lock = FALSE;   /* Protected by GC lock. */
2902  
2903 void GC_begin_syscall()
2904 {
2905     if (!I_HOLD_LOCK()) {
2906         LOCK();
2907         syscall_acquired_lock = TRUE;
2908     }
2909 }
2910
2911 void GC_end_syscall()
2912 {
2913     if (syscall_acquired_lock) {
2914         syscall_acquired_lock = FALSE;
2915         UNLOCK();
2916     }
2917 }
2918
2919 void GC_unprotect_range(addr, len)
2920 ptr_t addr;
2921 word len;
2922 {
2923     struct hblk * start_block;
2924     struct hblk * end_block;
2925     register struct hblk *h;
2926     ptr_t obj_start;
2927     
2928     if (!GC_dirty_maintained) return;
2929     obj_start = GC_base(addr);
2930     if (obj_start == 0) return;
2931     if (GC_base(addr + len - 1) != obj_start) {
2932         ABORT("GC_unprotect_range(range bigger than object)");
2933     }
2934     start_block = (struct hblk *)((word)addr & ~(GC_page_size - 1));
2935     end_block = (struct hblk *)((word)(addr + len - 1) & ~(GC_page_size - 1));
2936     end_block += GC_page_size/HBLKSIZE - 1;
2937     for (h = start_block; h <= end_block; h++) {
2938         register word index = PHT_HASH(h);
2939         
2940         async_set_pht_entry_from_index(GC_dirty_pages, index);
2941     }
2942     UNPROTECT(start_block,
2943               ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE);
2944 }
2945
2946 #if 0
2947
2948 /* We no longer wrap read by default, since that was causing too many   */
2949 /* problems.  It is preferred that the client instead avoids writing    */
2950 /* to the write-protected heap with a system call.                      */
2951 /* This still serves as sample code if you do want to wrap system calls.*/
2952
2953 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(GC_USE_LD_WRAP)
2954 /* Replacement for UNIX system call.                                      */
2955 /* Other calls that write to the heap should be handled similarly.        */
2956 /* Note that this doesn't work well for blocking reads:  It will hold     */
2957 /* the allocation lock for the entire duration of the call. Multithreaded */
2958 /* clients should really ensure that it won't block, either by setting    */
2959 /* the descriptor nonblocking, or by calling select or poll first, to     */
2960 /* make sure that input is available.                                     */
2961 /* Another, preferred alternative is to ensure that system calls never    */
2962 /* write to the protected heap (see above).                               */
2963 # if defined(__STDC__) && !defined(SUNOS4)
2964 #   include <unistd.h>
2965 #   include <sys/uio.h>
2966     ssize_t read(int fd, void *buf, size_t nbyte)
2967 # else
2968 #   ifndef LINT
2969       int read(fd, buf, nbyte)
2970 #   else
2971       int GC_read(fd, buf, nbyte)
2972 #   endif
2973     int fd;
2974     char *buf;
2975     int nbyte;
2976 # endif
2977 {
2978     int result;
2979     
2980     GC_begin_syscall();
2981     GC_unprotect_range(buf, (word)nbyte);
2982 #   if defined(IRIX5) || defined(GC_LINUX_THREADS)
2983         /* Indirect system call may not always be easily available.     */
2984         /* We could call _read, but that would interfere with the       */
2985         /* libpthread interception of read.                             */
2986         /* On Linux, we have to be careful with the linuxthreads        */
2987         /* read interception.                                           */
2988         {
2989             struct iovec iov;
2990
2991             iov.iov_base = buf;
2992             iov.iov_len = nbyte;
2993             result = readv(fd, &iov, 1);
2994         }
2995 #   else
2996 #     if defined(HURD)  
2997         result = __read(fd, buf, nbyte);
2998 #     else
2999         /* The two zero args at the end of this list are because one
3000            IA-64 syscall() implementation actually requires six args
3001            to be passed, even though they aren't always used. */
3002         result = syscall(SYS_read, fd, buf, nbyte, 0, 0);
3003 #     endif /* !HURD */
3004 #   endif
3005     GC_end_syscall();
3006     return(result);
3007 }
3008 #endif /* !MSWIN32 && !MSWINCE && !GC_LINUX_THREADS */
3009
3010 #if defined(GC_USE_LD_WRAP) && !defined(THREADS)
3011     /* We use the GNU ld call wrapping facility.                        */
3012     /* This requires that the linker be invoked with "--wrap read".     */
3013     /* This can be done by passing -Wl,"--wrap read" to gcc.            */
3014     /* I'm not sure that this actually wraps whatever version of read   */
3015     /* is called by stdio.  That code also mentions __read.             */
3016 #   include <unistd.h>
3017     ssize_t __wrap_read(int fd, void *buf, size_t nbyte)
3018     {
3019         int result;
3020
3021         GC_begin_syscall();
3022         GC_unprotect_range(buf, (word)nbyte);
3023         result = __real_read(fd, buf, nbyte);
3024         GC_end_syscall();
3025         return(result);
3026     }
3027
3028     /* We should probably also do this for __read, or whatever stdio    */
3029     /* actually calls.                                                  */
3030 #endif
3031
3032 #endif /* 0 */
3033
3034 /*ARGSUSED*/
3035 GC_bool GC_page_was_ever_dirty(h)
3036 struct hblk *h;
3037 {
3038     return(TRUE);
3039 }
3040
3041 /* Reset the n pages starting at h to "was never dirty" status. */
3042 /*ARGSUSED*/
3043 void GC_is_fresh(h, n)
3044 struct hblk *h;
3045 word n;
3046 {
3047 }
3048
3049 # endif /* MPROTECT_VDB */
3050
3051 # ifdef PROC_VDB
3052
3053 /*
3054  * See DEFAULT_VDB for interface descriptions.
3055  */
3056  
3057 /*
3058  * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
3059  * from which we can read page modified bits.  This facility is far from
3060  * optimal (e.g. we would like to get the info for only some of the
3061  * address space), but it avoids intercepting system calls.
3062  */
3063
3064 #include <errno.h>
3065 #include <sys/types.h>
3066 #include <sys/signal.h>
3067 #include <sys/fault.h>
3068 #include <sys/syscall.h>
3069 #include <sys/procfs.h>
3070 #include <sys/stat.h>
3071
3072 #define INITIAL_BUF_SZ 16384
3073 word GC_proc_buf_size = INITIAL_BUF_SZ;
3074 char *GC_proc_buf;
3075
3076 #ifdef GC_SOLARIS_THREADS
3077 /* We don't have exact sp values for threads.  So we count on   */
3078 /* occasionally declaring stack pages to be fresh.  Thus we     */
3079 /* need a real implementation of GC_is_fresh.  We can't clear   */
3080 /* entries in GC_written_pages, since that would declare all    */
3081 /* pages with the given hash address to be fresh.               */
3082 #   define MAX_FRESH_PAGES 8*1024       /* Must be power of 2 */
3083     struct hblk ** GC_fresh_pages;      /* A direct mapped cache.       */
3084                                         /* Collisions are dropped.      */
3085
3086 #   define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
3087 #   define ADD_FRESH_PAGE(h) \
3088         GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
3089 #   define PAGE_IS_FRESH(h) \
3090         (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
3091 #endif
3092
3093 /* Add all pages in pht2 to pht1 */
3094 void GC_or_pages(pht1, pht2)
3095 page_hash_table pht1, pht2;
3096 {
3097     register int i;
3098     
3099     for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
3100 }
3101
3102 int GC_proc_fd;
3103
3104 void GC_dirty_init()
3105 {
3106     int fd;
3107     char buf[30];
3108
3109     GC_dirty_maintained = TRUE;
3110     if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
3111         register int i;
3112     
3113         for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
3114 #       ifdef PRINTSTATS
3115             GC_printf1("Allocated words:%lu:all pages may have been written\n",
3116                        (unsigned long)
3117                                 (GC_words_allocd + GC_words_allocd_before_gc));
3118 #       endif       
3119     }
3120     sprintf(buf, "/proc/%d", getpid());
3121     fd = open(buf, O_RDONLY);
3122     if (fd < 0) {
3123         ABORT("/proc open failed");
3124     }
3125     GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
3126     close(fd);
3127     syscall(SYS_fcntl, GC_proc_fd, F_SETFD, FD_CLOEXEC);
3128     if (GC_proc_fd < 0) {
3129         ABORT("/proc ioctl failed");
3130     }
3131     GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size);
3132 #   ifdef GC_SOLARIS_THREADS
3133         GC_fresh_pages = (struct hblk **)
3134           GC_scratch_alloc(MAX_FRESH_PAGES * sizeof (struct hblk *));
3135         if (GC_fresh_pages == 0) {
3136             GC_err_printf0("No space for fresh pages\n");
3137             EXIT();
3138         }
3139         BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
3140 #   endif
3141 }
3142
3143 /* Ignore write hints. They don't help us here. */
3144 /*ARGSUSED*/
3145 void GC_remove_protection(h, nblocks, is_ptrfree)
3146 struct hblk *h;
3147 word nblocks;
3148 GC_bool is_ptrfree;
3149 {
3150 }
3151
3152 #ifdef GC_SOLARIS_THREADS
3153 #   define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
3154 #else
3155 #   define READ(fd,buf,nbytes) read(fd, buf, nbytes)
3156 #endif
3157
3158 void GC_read_dirty()
3159 {
3160     unsigned long ps, np;
3161     int nmaps;
3162     ptr_t vaddr;
3163     struct prasmap * map;
3164     char * bufp;
3165     ptr_t current_addr, limit;
3166     int i;
3167 int dummy;
3168
3169     BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
3170     
3171     bufp = GC_proc_buf;
3172     if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3173 #       ifdef PRINTSTATS
3174             GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
3175                        GC_proc_buf_size);
3176 #       endif       
3177         {
3178             /* Retry with larger buffer. */
3179             word new_size = 2 * GC_proc_buf_size;
3180             char * new_buf = GC_scratch_alloc(new_size);
3181             
3182             if (new_buf != 0) {
3183                 GC_proc_buf = bufp = new_buf;
3184                 GC_proc_buf_size = new_size;
3185             }
3186             if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3187                 WARN("Insufficient space for /proc read\n", 0);
3188                 /* Punt:        */
3189                 memset(GC_grungy_pages, 0xff, sizeof (page_hash_table));
3190                 memset(GC_written_pages, 0xff, sizeof(page_hash_table));
3191 #               ifdef GC_SOLARIS_THREADS
3192                     BZERO(GC_fresh_pages,
3193                           MAX_FRESH_PAGES * sizeof (struct hblk *)); 
3194 #               endif
3195                 return;
3196             }
3197         }
3198     }
3199     /* Copy dirty bits into GC_grungy_pages */
3200         nmaps = ((struct prpageheader *)bufp) -> pr_nmap;
3201         /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
3202                      nmaps, PG_REFERENCED, PG_MODIFIED); */
3203         bufp = bufp + sizeof(struct prpageheader);
3204         for (i = 0; i < nmaps; i++) {
3205             map = (struct prasmap *)bufp;
3206             vaddr = (ptr_t)(map -> pr_vaddr);
3207             ps = map -> pr_pagesize;
3208             np = map -> pr_npage;
3209             /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
3210             limit = vaddr + ps * np;
3211             bufp += sizeof (struct prasmap);
3212             for (current_addr = vaddr;
3213                  current_addr < limit; current_addr += ps){
3214                 if ((*bufp++) & PG_MODIFIED) {
3215                     register struct hblk * h = (struct hblk *) current_addr;
3216                     
3217                     while ((ptr_t)h < current_addr + ps) {
3218                         register word index = PHT_HASH(h);
3219                         
3220                         set_pht_entry_from_index(GC_grungy_pages, index);
3221 #                       ifdef GC_SOLARIS_THREADS
3222                           {
3223                             register int slot = FRESH_PAGE_SLOT(h);
3224                             
3225                             if (GC_fresh_pages[slot] == h) {
3226                                 GC_fresh_pages[slot] = 0;
3227                             }
3228                           }
3229 #                       endif
3230                         h++;
3231                     }
3232                 }
3233             }
3234             bufp += sizeof(long) - 1;
3235             bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1));
3236         }
3237     /* Update GC_written_pages. */
3238         GC_or_pages(GC_written_pages, GC_grungy_pages);
3239 #   ifdef GC_SOLARIS_THREADS
3240       /* Make sure that old stacks are considered completely clean      */
3241       /* unless written again.                                          */
3242         GC_old_stacks_are_fresh();
3243 #   endif
3244 }
3245
3246 #undef READ
3247
3248 GC_bool GC_page_was_dirty(h)
3249 struct hblk *h;
3250 {
3251     register word index = PHT_HASH(h);
3252     register GC_bool result;
3253     
3254     result = get_pht_entry_from_index(GC_grungy_pages, index);
3255 #   ifdef GC_SOLARIS_THREADS
3256         if (result && PAGE_IS_FRESH(h)) result = FALSE;
3257         /* This happens only if page was declared fresh since   */
3258         /* the read_dirty call, e.g. because it's in an unused  */
3259         /* thread stack.  It's OK to treat it as clean, in      */
3260         /* that case.  And it's consistent with                 */
3261         /* GC_page_was_ever_dirty.                              */
3262 #   endif
3263     return(result);
3264 }
3265
3266 GC_bool GC_page_was_ever_dirty(h)
3267 struct hblk *h;
3268 {
3269     register word index = PHT_HASH(h);
3270     register GC_bool result;
3271     
3272     result = get_pht_entry_from_index(GC_written_pages, index);
3273 #   ifdef GC_SOLARIS_THREADS
3274         if (result && PAGE_IS_FRESH(h)) result = FALSE;
3275 #   endif
3276     return(result);
3277 }
3278
3279 /* Caller holds allocation lock.        */
3280 void GC_is_fresh(h, n)
3281 struct hblk *h;
3282 word n;
3283 {
3284
3285     register word index;
3286     
3287 #   ifdef GC_SOLARIS_THREADS
3288       register word i;
3289       
3290       if (GC_fresh_pages != 0) {
3291         for (i = 0; i < n; i++) {
3292           ADD_FRESH_PAGE(h + i);
3293         }
3294       }
3295 #   endif
3296 }
3297
3298 # endif /* PROC_VDB */
3299
3300
3301 # ifdef PCR_VDB
3302
3303 # include "vd/PCR_VD.h"
3304
3305 # define NPAGES (32*1024)       /* 128 MB */
3306
3307 PCR_VD_DB  GC_grungy_bits[NPAGES];
3308
3309 ptr_t GC_vd_base;       /* Address corresponding to GC_grungy_bits[0]   */
3310                         /* HBLKSIZE aligned.                            */
3311
3312 void GC_dirty_init()
3313 {
3314     GC_dirty_maintained = TRUE;
3315     /* For the time being, we assume the heap generally grows up */
3316     GC_vd_base = GC_heap_sects[0].hs_start;
3317     if (GC_vd_base == 0) {
3318         ABORT("Bad initial heap segment");
3319     }
3320     if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE)
3321         != PCR_ERes_okay) {
3322         ABORT("dirty bit initialization failed");
3323     }
3324 }
3325
3326 void GC_read_dirty()
3327 {
3328     /* lazily enable dirty bits on newly added heap sects */
3329     {
3330         static int onhs = 0;
3331         int nhs = GC_n_heap_sects;
3332         for( ; onhs < nhs; onhs++ ) {
3333             PCR_VD_WriteProtectEnable(
3334                     GC_heap_sects[onhs].hs_start,
3335                     GC_heap_sects[onhs].hs_bytes );
3336         }
3337     }
3338
3339
3340     if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits)
3341         != PCR_ERes_okay) {
3342         ABORT("dirty bit read failed");
3343     }
3344 }
3345
3346 GC_bool GC_page_was_dirty(h)
3347 struct hblk *h;
3348 {
3349     if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
3350         return(TRUE);
3351     }
3352     return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
3353 }
3354
3355 /*ARGSUSED*/
3356 void GC_remove_protection(h, nblocks, is_ptrfree)
3357 struct hblk *h;
3358 word nblocks;
3359 GC_bool is_ptrfree;
3360 {
3361     PCR_VD_WriteProtectDisable(h, nblocks*HBLKSIZE);
3362     PCR_VD_WriteProtectEnable(h, nblocks*HBLKSIZE);
3363 }
3364
3365 # endif /* PCR_VDB */
3366
3367 #if defined(MPROTECT_VDB) && defined(DARWIN)
3368 /* The following sources were used as a *reference* for this exception handling
3369    code:
3370       1. Apple's mach/xnu documentation
3371       2. Timothy J. Wood's "Mach Exception Handlers 101" post to the
3372          omnigroup's macosx-dev list. 
3373          www.omnigroup.com/mailman/archive/macosx-dev/2000-June/002030.html
3374       3. macosx-nat.c from Apple's GDB source code.
3375 */
3376    
3377 /* The bug that caused all this trouble should now be fixed. This should
3378    eventually be removed if all goes well. */
3379 /* define BROKEN_EXCEPTION_HANDLING */
3380     
3381 #include <mach/mach.h>
3382 #include <mach/mach_error.h>
3383 #include <mach/thread_status.h>
3384 #include <mach/exception.h>
3385 #include <mach/task.h>
3386 #include <pthread.h>
3387
3388 /* These are not defined in any header, although they are documented */
3389 extern boolean_t exc_server(mach_msg_header_t *,mach_msg_header_t *);
3390 extern kern_return_t exception_raise(
3391     mach_port_t,mach_port_t,mach_port_t,
3392     exception_type_t,exception_data_t,mach_msg_type_number_t);
3393 extern kern_return_t exception_raise_state(
3394     mach_port_t,mach_port_t,mach_port_t,
3395     exception_type_t,exception_data_t,mach_msg_type_number_t,
3396     thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3397     thread_state_t,mach_msg_type_number_t*);
3398 extern kern_return_t exception_raise_state_identity(
3399     mach_port_t,mach_port_t,mach_port_t,
3400     exception_type_t,exception_data_t,mach_msg_type_number_t,
3401     thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3402     thread_state_t,mach_msg_type_number_t*);
3403
3404
3405 #define MAX_EXCEPTION_PORTS 16
3406
3407 static struct {
3408     mach_msg_type_number_t count;
3409     exception_mask_t      masks[MAX_EXCEPTION_PORTS];
3410     exception_handler_t   ports[MAX_EXCEPTION_PORTS];
3411     exception_behavior_t  behaviors[MAX_EXCEPTION_PORTS];
3412     thread_state_flavor_t flavors[MAX_EXCEPTION_PORTS];
3413 } GC_old_exc_ports;
3414
3415 static struct {
3416     mach_port_t exception;
3417 #if defined(THREADS)
3418     mach_port_t reply;
3419 #endif
3420 } GC_ports;
3421
3422 typedef struct {
3423     mach_msg_header_t head;
3424 } GC_msg_t;
3425
3426 typedef enum {
3427     GC_MP_NORMAL, GC_MP_DISCARDING, GC_MP_STOPPED
3428 } GC_mprotect_state_t;
3429
3430 /* FIXME: 1 and 2 seem to be safe to use in the msgh_id field,
3431    but it isn't  documented. Use the source and see if they
3432    should be ok. */
3433 #define ID_STOP 1
3434 #define ID_RESUME 2
3435
3436 /* These values are only used on the reply port */
3437 #define ID_ACK 3
3438
3439 #if defined(THREADS)
3440
3441 GC_mprotect_state_t GC_mprotect_state;
3442
3443 /* The following should ONLY be called when the world is stopped  */
3444 static void GC_mprotect_thread_notify(mach_msg_id_t id) {
3445     struct {
3446         GC_msg_t msg;
3447         mach_msg_trailer_t trailer;
3448     } buf;
3449     mach_msg_return_t r;
3450     /* remote, local */
3451     buf.msg.head.msgh_bits = 
3452         MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3453     buf.msg.head.msgh_size = sizeof(buf.msg);
3454     buf.msg.head.msgh_remote_port = GC_ports.exception;
3455     buf.msg.head.msgh_local_port = MACH_PORT_NULL;
3456     buf.msg.head.msgh_id = id;
3457             
3458     r = mach_msg(
3459         &buf.msg.head,
3460         MACH_SEND_MSG|MACH_RCV_MSG|MACH_RCV_LARGE,
3461         sizeof(buf.msg),
3462         sizeof(buf),
3463         GC_ports.reply,
3464         MACH_MSG_TIMEOUT_NONE,
3465         MACH_PORT_NULL);
3466     if(r != MACH_MSG_SUCCESS)
3467         ABORT("mach_msg failed in GC_mprotect_thread_notify");
3468     if(buf.msg.head.msgh_id != ID_ACK)
3469         ABORT("invalid ack in GC_mprotect_thread_notify");
3470 }
3471
3472 /* Should only be called by the mprotect thread */
3473 static void GC_mprotect_thread_reply() {
3474     GC_msg_t msg;
3475     mach_msg_return_t r;
3476     /* remote, local */
3477     msg.head.msgh_bits = 
3478         MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3479     msg.head.msgh_size = sizeof(msg);
3480     msg.head.msgh_remote_port = GC_ports.reply;
3481     msg.head.msgh_local_port = MACH_PORT_NULL;
3482     msg.head.msgh_id = ID_ACK;
3483             
3484     r = mach_msg(
3485         &msg.head,
3486         MACH_SEND_MSG,
3487         sizeof(msg),
3488         0,
3489         MACH_PORT_NULL,
3490         MACH_MSG_TIMEOUT_NONE,
3491         MACH_PORT_NULL);
3492     if(r != MACH_MSG_SUCCESS)
3493         ABORT("mach_msg failed in GC_mprotect_thread_reply");
3494 }
3495
3496 void GC_mprotect_stop() {
3497     GC_mprotect_thread_notify(ID_STOP);
3498 }
3499 void GC_mprotect_resume() {
3500     GC_mprotect_thread_notify(ID_RESUME);
3501 }
3502
3503 #else /* !THREADS */
3504 /* The compiler should optimize away any GC_mprotect_state computations */
3505 #define GC_mprotect_state GC_MP_NORMAL
3506 #endif
3507
3508 static void *GC_mprotect_thread(void *arg) {
3509     mach_msg_return_t r;
3510     /* These two structures contain some private kernel data. We don't need to
3511        access any of it so we don't bother defining a proper struct. The
3512        correct definitions are in the xnu source code. */
3513     struct {
3514         mach_msg_header_t head;
3515         char data[256];
3516     } reply;
3517     struct {
3518         mach_msg_header_t head;
3519         mach_msg_body_t msgh_body;
3520         char data[1024];
3521     } msg;
3522
3523     mach_msg_id_t id;
3524
3525     GC_darwin_register_mach_handler_thread(mach_thread_self());
3526     
3527     for(;;) {
3528         r = mach_msg(
3529             &msg.head,
3530             MACH_RCV_MSG|MACH_RCV_LARGE|
3531                 (GC_mprotect_state == GC_MP_DISCARDING ? MACH_RCV_TIMEOUT : 0),
3532             0,
3533             sizeof(msg),
3534             GC_ports.exception,
3535             GC_mprotect_state == GC_MP_DISCARDING ? 0 : MACH_MSG_TIMEOUT_NONE,
3536             MACH_PORT_NULL);
3537         
3538         id = r == MACH_MSG_SUCCESS ? msg.head.msgh_id : -1;
3539         
3540 #if defined(THREADS)
3541         if(GC_mprotect_state == GC_MP_DISCARDING) {
3542             if(r == MACH_RCV_TIMED_OUT) {
3543                 GC_mprotect_state = GC_MP_STOPPED;
3544                 GC_mprotect_thread_reply();
3545                 continue;
3546             }
3547             if(r == MACH_MSG_SUCCESS && (id == ID_STOP || id == ID_RESUME))
3548                 ABORT("out of order mprotect thread request");
3549         }
3550 #endif
3551         
3552         if(r != MACH_MSG_SUCCESS) {
3553             GC_err_printf2("mach_msg failed with %d %s\n", 
3554                 (int)r,mach_error_string(r));
3555             ABORT("mach_msg failed");
3556         }
3557         
3558         switch(id) {
3559 #if defined(THREADS)
3560             case ID_STOP:
3561                 if(GC_mprotect_state != GC_MP_NORMAL)
3562                     ABORT("Called mprotect_stop when state wasn't normal");
3563                 GC_mprotect_state = GC_MP_DISCARDING;
3564                 break;
3565             case ID_RESUME:
3566                 if(GC_mprotect_state != GC_MP_STOPPED)
3567                     ABORT("Called mprotect_resume when state wasn't stopped");
3568                 GC_mprotect_state = GC_MP_NORMAL;
3569                 GC_mprotect_thread_reply();
3570                 break;
3571 #endif /* THREADS */
3572             default:
3573                     /* Handle the message (calls catch_exception_raise) */
3574                 if(!exc_server(&msg.head,&reply.head))
3575                     ABORT("exc_server failed");
3576                 /* Send the reply */
3577                 r = mach_msg(
3578                     &reply.head,
3579                     MACH_SEND_MSG,
3580                     reply.head.msgh_size,
3581                     0,
3582                     MACH_PORT_NULL,
3583                     MACH_MSG_TIMEOUT_NONE,
3584                     MACH_PORT_NULL);
3585                 if(r != MACH_MSG_SUCCESS) {
3586                         /* This will fail if the thread dies, but the thread shouldn't
3587                            die... */
3588                         #ifdef BROKEN_EXCEPTION_HANDLING
3589                         GC_err_printf2(
3590                         "mach_msg failed with %d %s while sending exc reply\n",
3591                         (int)r,mach_error_string(r));
3592                 #else
3593                         ABORT("mach_msg failed while sending exception reply");
3594                 #endif
3595                 }
3596         } /* switch */
3597     } /* for(;;) */
3598     /* NOT REACHED */
3599     return NULL;
3600 }
3601
3602 /* All this SIGBUS code shouldn't be necessary. All protection faults should
3603    be going throught the mach exception handler. However, it seems a SIGBUS is
3604    occasionally sent for some unknown reason. Even more odd, it seems to be
3605    meaningless and safe to ignore. */
3606 #ifdef BROKEN_EXCEPTION_HANDLING
3607
3608 typedef void (* SIG_PF)();
3609 static SIG_PF GC_old_bus_handler;
3610
3611 /* Updates to this aren't atomic, but the SIGBUSs seem pretty rare.
3612    Even if this doesn't get updated property, it isn't really a problem */
3613 static int GC_sigbus_count;
3614
3615 static void GC_darwin_sigbus(int num,siginfo_t *sip,void *context) {
3616     if(num != SIGBUS) ABORT("Got a non-sigbus signal in the sigbus handler");
3617     
3618     /* Ugh... some seem safe to ignore, but too many in a row probably means
3619        trouble. GC_sigbus_count is reset for each mach exception that is
3620        handled */
3621     if(GC_sigbus_count >= 8) {
3622         ABORT("Got more than 8 SIGBUSs in a row!");
3623     } else {
3624         GC_sigbus_count++;
3625         GC_err_printf0("GC: WARNING: Ignoring SIGBUS.\n");
3626     }
3627 }
3628 #endif /* BROKEN_EXCEPTION_HANDLING */
3629
3630 void GC_dirty_init() {
3631     kern_return_t r;
3632     mach_port_t me;
3633     pthread_t thread;
3634     pthread_attr_t attr;
3635     exception_mask_t mask;
3636     
3637 #   ifdef PRINTSTATS
3638         GC_printf0("Inititalizing mach/darwin mprotect virtual dirty bit "
3639             "implementation\n");
3640 #   endif  
3641 #       ifdef BROKEN_EXCEPTION_HANDLING
3642         GC_err_printf0("GC: WARNING: Enabling workarounds for various darwin "
3643             "exception handling bugs.\n");
3644 #       endif
3645     GC_dirty_maintained = TRUE;
3646     if (GC_page_size % HBLKSIZE != 0) {
3647         GC_err_printf0("Page size not multiple of HBLKSIZE\n");
3648         ABORT("Page size not multiple of HBLKSIZE");
3649     }
3650     
3651     GC_task_self = me = mach_task_self();
3652     
3653     r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.exception);
3654     if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (exception port)");
3655     
3656     r = mach_port_insert_right(me,GC_ports.exception,GC_ports.exception,
3657         MACH_MSG_TYPE_MAKE_SEND);
3658     if(r != KERN_SUCCESS)
3659         ABORT("mach_port_insert_right failed (exception port)");
3660
3661     #if defined(THREADS)
3662         r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.reply);
3663         if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (reply port)");
3664     #endif
3665
3666     /* The exceptions we want to catch */  
3667     mask = EXC_MASK_BAD_ACCESS;
3668
3669     r = task_get_exception_ports(
3670         me,
3671         mask,
3672         GC_old_exc_ports.masks,
3673         &GC_old_exc_ports.count,
3674         GC_old_exc_ports.ports,
3675         GC_old_exc_ports.behaviors,
3676         GC_old_exc_ports.flavors
3677     );
3678     if(r != KERN_SUCCESS) ABORT("task_get_exception_ports failed");
3679         
3680     r = task_set_exception_ports(
3681         me,
3682         mask,
3683         GC_ports.exception,
3684         EXCEPTION_DEFAULT,
3685         MACHINE_THREAD_STATE
3686     );
3687     if(r != KERN_SUCCESS) ABORT("task_set_exception_ports failed");
3688
3689     if(pthread_attr_init(&attr) != 0) ABORT("pthread_attr_init failed");
3690     if(pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED) != 0) 
3691         ABORT("pthread_attr_setdetachedstate failed");
3692
3693 #       undef pthread_create
3694     /* This will call the real pthread function, not our wrapper */
3695     if(pthread_create(&thread,&attr,GC_mprotect_thread,NULL) != 0)
3696         ABORT("pthread_create failed");
3697     pthread_attr_destroy(&attr);
3698     
3699     /* Setup the sigbus handler for ignoring the meaningless SIGBUSs */
3700     #ifdef BROKEN_EXCEPTION_HANDLING 
3701     {
3702         struct sigaction sa, oldsa;
3703         sa.sa_handler = (SIG_PF)GC_darwin_sigbus;
3704         sigemptyset(&sa.sa_mask);
3705         sa.sa_flags = SA_RESTART|SA_SIGINFO;
3706         if(sigaction(SIGBUS,&sa,&oldsa) < 0) ABORT("sigaction");
3707         GC_old_bus_handler = (SIG_PF)oldsa.sa_handler;
3708         if (GC_old_bus_handler != SIG_DFL) {
3709 #               ifdef PRINTSTATS
3710                 GC_err_printf0("Replaced other SIGBUS handler\n");
3711 #               endif
3712         }
3713     }
3714     #endif /* BROKEN_EXCEPTION_HANDLING  */
3715 }
3716  
3717 /* The source code for Apple's GDB was used as a reference for the exception
3718    forwarding code. This code is similar to be GDB code only because there is 
3719    only one way to do it. */
3720 static kern_return_t GC_forward_exception(
3721         mach_port_t thread,
3722         mach_port_t task,
3723         exception_type_t exception,
3724         exception_data_t data,
3725         mach_msg_type_number_t data_count
3726 ) {
3727     int i;
3728     kern_return_t r;
3729     mach_port_t port;
3730     exception_behavior_t behavior;
3731     thread_state_flavor_t flavor;
3732     
3733     thread_state_t thread_state;
3734     mach_msg_type_number_t thread_state_count = THREAD_STATE_MAX;
3735         
3736     for(i=0;i<GC_old_exc_ports.count;i++)
3737         if(GC_old_exc_ports.masks[i] & (1 << exception))
3738             break;
3739     if(i==GC_old_exc_ports.count) ABORT("No handler for exception!");
3740     
3741     port = GC_old_exc_ports.ports[i];
3742     behavior = GC_old_exc_ports.behaviors[i];
3743     flavor = GC_old_exc_ports.flavors[i];
3744
3745     if(behavior != EXCEPTION_DEFAULT) {
3746         r = thread_get_state(thread,flavor,thread_state,&thread_state_count);
3747         if(r != KERN_SUCCESS)
3748             ABORT("thread_get_state failed in forward_exception");
3749     }
3750     
3751     switch(behavior) {
3752         case EXCEPTION_DEFAULT:
3753             r = exception_raise(port,thread,task,exception,data,data_count);
3754             break;
3755         case EXCEPTION_STATE:
3756             r = exception_raise_state(port,thread,task,exception,data,
3757                 data_count,&flavor,thread_state,thread_state_count,
3758                 thread_state,&thread_state_count);
3759             break;
3760         case EXCEPTION_STATE_IDENTITY:
3761             r = exception_raise_state_identity(port,thread,task,exception,data,
3762                 data_count,&flavor,thread_state,thread_state_count,
3763                 thread_state,&thread_state_count);
3764             break;
3765         default:
3766             r = KERN_FAILURE; /* make gcc happy */
3767             ABORT("forward_exception: unknown behavior");
3768             break;
3769     }
3770     
3771     if(behavior != EXCEPTION_DEFAULT) {
3772         r = thread_set_state(thread,flavor,thread_state,thread_state_count);
3773         if(r != KERN_SUCCESS)
3774             ABORT("thread_set_state failed in forward_exception");
3775     }
3776     
3777     return r;
3778 }
3779
3780 #define FWD() GC_forward_exception(thread,task,exception,code,code_count)
3781
3782 /* This violates the namespace rules but there isn't anything that can be done
3783    about it. The exception handling stuff is hard coded to call this */
3784 kern_return_t
3785 catch_exception_raise(
3786    mach_port_t exception_port,mach_port_t thread,mach_port_t task,
3787    exception_type_t exception,exception_data_t code,
3788    mach_msg_type_number_t code_count
3789 ) {
3790     kern_return_t r;
3791     char *addr;
3792     struct hblk *h;
3793     int i;
3794 #   if defined(POWERPC)
3795 #     if CPP_WORDSZ == 32
3796         thread_state_flavor_t flavor = PPC_EXCEPTION_STATE;
3797         mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE_COUNT;
3798         ppc_exception_state_t exc_state;
3799 #     else
3800         thread_state_flavor_t flavor = PPC_EXCEPTION_STATE64;
3801         mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE64_COUNT;
3802         ppc_exception_state64_t exc_state;
3803 #     endif
3804 #   else
3805 #       error FIXME for non-ppc darwin
3806 #   endif
3807
3808     
3809     if(exception != EXC_BAD_ACCESS || code[0] != KERN_PROTECTION_FAILURE) {
3810         #ifdef DEBUG_EXCEPTION_HANDLING
3811         /* We aren't interested, pass it on to the old handler */
3812         GC_printf3("Exception: 0x%x Code: 0x%x 0x%x in catch....\n",
3813             exception,
3814             code_count > 0 ? code[0] : -1,
3815             code_count > 1 ? code[1] : -1); 
3816         #endif
3817         return FWD();
3818     }
3819
3820     r = thread_get_state(thread,flavor,
3821         (natural_t*)&exc_state,&exc_state_count);
3822     if(r != KERN_SUCCESS) {
3823         /* The thread is supposed to be suspended while the exception handler
3824            is called. This shouldn't fail. */
3825         #ifdef BROKEN_EXCEPTION_HANDLING
3826             GC_err_printf0("thread_get_state failed in "
3827                 "catch_exception_raise\n");
3828             return KERN_SUCCESS;
3829         #else
3830             ABORT("thread_get_state failed in catch_exception_raise");
3831         #endif
3832     }
3833     
3834     /* This is the address that caused the fault */
3835     addr = (char*) exc_state.dar;
3836         
3837     if((HDR(addr)) == 0) {
3838         /* Ugh... just like the SIGBUS problem above, it seems we get a bogus 
3839            KERN_PROTECTION_FAILURE every once and a while. We wait till we get
3840            a bunch in a row before doing anything about it. If a "real" fault 
3841            ever occurres it'll just keep faulting over and over and we'll hit
3842            the limit pretty quickly. */
3843         #ifdef BROKEN_EXCEPTION_HANDLING
3844             static char *last_fault;
3845             static int last_fault_count;
3846             
3847             if(addr != last_fault) {
3848                 last_fault = addr;
3849                 last_fault_count = 0;
3850             }
3851             if(++last_fault_count < 32) {
3852                 if(last_fault_count == 1)
3853                     GC_err_printf1(
3854                         "GC: WARNING: Ignoring KERN_PROTECTION_FAILURE at %p\n",
3855                         addr);
3856                 return KERN_SUCCESS;
3857             }
3858             
3859             GC_err_printf1("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr);
3860             /* Can't pass it along to the signal handler because that is
3861                ignoring SIGBUS signals. We also shouldn't call ABORT here as
3862                signals don't always work too well from the exception handler. */
3863             GC_err_printf0("Aborting\n");
3864             exit(EXIT_FAILURE);
3865         #else /* BROKEN_EXCEPTION_HANDLING */
3866             /* Pass it along to the next exception handler 
3867                (which should call SIGBUS/SIGSEGV) */
3868             return FWD();
3869         #endif /* !BROKEN_EXCEPTION_HANDLING */
3870     }
3871
3872     #ifdef BROKEN_EXCEPTION_HANDLING
3873         /* Reset the number of consecutive SIGBUSs */
3874         GC_sigbus_count = 0;
3875     #endif
3876     
3877     if(GC_mprotect_state == GC_MP_NORMAL) { /* common case */
3878         h = (struct hblk*)((word)addr & ~(GC_page_size-1));
3879         UNPROTECT(h, GC_page_size);     
3880         for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
3881             register int index = PHT_HASH(h+i);
3882             async_set_pht_entry_from_index(GC_dirty_pages, index);
3883         }
3884     } else if(GC_mprotect_state == GC_MP_DISCARDING) {
3885         /* Lie to the thread for now. No sense UNPROTECT()ing the memory
3886            when we're just going to PROTECT() it again later. The thread
3887            will just fault again once it resumes */
3888     } else {
3889         /* Shouldn't happen, i don't think */
3890         GC_printf0("KERN_PROTECTION_FAILURE while world is stopped\n");
3891         return FWD();
3892     }
3893     return KERN_SUCCESS;
3894 }
3895 #undef FWD
3896
3897 /* These should never be called, but just in case...  */
3898 kern_return_t catch_exception_raise_state(mach_port_name_t exception_port,
3899     int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
3900     int flavor, thread_state_t old_state, int old_stateCnt,
3901     thread_state_t new_state, int new_stateCnt)
3902 {
3903     ABORT("catch_exception_raise_state");
3904     return(KERN_INVALID_ARGUMENT);
3905 }
3906 kern_return_t catch_exception_raise_state_identity(
3907     mach_port_name_t exception_port, mach_port_t thread, mach_port_t task,
3908     int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
3909     int flavor, thread_state_t old_state, int old_stateCnt, 
3910     thread_state_t new_state, int new_stateCnt)
3911 {
3912     ABORT("catch_exception_raise_state_identity");
3913     return(KERN_INVALID_ARGUMENT);
3914 }
3915
3916
3917 #endif /* DARWIN && MPROTECT_VDB */
3918
3919 # ifndef HAVE_INCREMENTAL_PROTECTION_NEEDS
3920   int GC_incremental_protection_needs()
3921   {
3922     return GC_PROTECTS_NONE;
3923   }
3924 # endif /* !HAVE_INCREMENTAL_PROTECTION_NEEDS */
3925
3926 /*
3927  * Call stack save code for debugging.
3928  * Should probably be in mach_dep.c, but that requires reorganization.
3929  */
3930
3931 /* I suspect the following works for most X86 *nix variants, so         */
3932 /* long as the frame pointer is explicitly stored.  In the case of gcc, */
3933 /* compiler flags (e.g. -fomit-frame-pointer) determine whether it is.  */
3934 #if defined(I386) && defined(LINUX) && defined(SAVE_CALL_CHAIN)
3935 #   include <features.h>
3936
3937     struct frame {
3938         struct frame *fr_savfp;
3939         long    fr_savpc;
3940         long    fr_arg[NARGS];  /* All the arguments go here.   */
3941     };
3942 #endif
3943
3944 #if defined(SPARC)
3945 #  if defined(LINUX)
3946 #    include <features.h>
3947
3948      struct frame {
3949         long    fr_local[8];
3950         long    fr_arg[6];
3951         struct frame *fr_savfp;
3952         long    fr_savpc;
3953 #       ifndef __arch64__
3954           char  *fr_stret;
3955 #       endif
3956         long    fr_argd[6];
3957         long    fr_argx[0];
3958      };
3959 #  else
3960 #    if defined(SUNOS4)
3961 #      include <machine/frame.h>
3962 #    else
3963 #      if defined (DRSNX)
3964 #        include <sys/sparc/frame.h>
3965 #      else
3966 #        if defined(OPENBSD)
3967 #          include <frame.h>
3968 #        else
3969 #          if defined(FREEBSD) || defined(NETBSD)
3970 #            include <machine/frame.h>
3971 #          else
3972 #            include <sys/frame.h>
3973 #          endif
3974 #        endif
3975 #      endif
3976 #    endif
3977 #  endif
3978 #  if NARGS > 6
3979         --> We only know how to to get the first 6 arguments
3980 #  endif
3981 #endif /* SPARC */
3982
3983 #ifdef  NEED_CALLINFO
3984 /* Fill in the pc and argument information for up to NFRAMES of my      */
3985 /* callers.  Ignore my frame and my callers frame.                      */
3986
3987 #ifdef LINUX
3988 #   include <unistd.h>
3989 #endif
3990
3991 #endif /* NEED_CALLINFO */
3992
3993 #if defined(GC_HAVE_BUILTIN_BACKTRACE)
3994 # include <execinfo.h>
3995 #endif
3996
3997 #ifdef SAVE_CALL_CHAIN
3998
3999 #if NARGS == 0 && NFRAMES % 2 == 0 /* No padding */ \
4000     && defined(GC_HAVE_BUILTIN_BACKTRACE)
4001
4002 #ifdef REDIRECT_MALLOC
4003   /* Deal with possible malloc calls in backtrace by omitting   */
4004   /* the infinitely recursing backtrace.                        */
4005 # ifdef THREADS
4006     __thread    /* If your compiler doesn't understand this */
4007                 /* you could use something like pthread_getspecific.    */
4008 # endif
4009   GC_in_save_callers = FALSE;
4010 #endif
4011
4012 void GC_save_callers (info) 
4013 struct callinfo info[NFRAMES];
4014 {
4015   void * tmp_info[NFRAMES + 1];
4016   int npcs, i;
4017 # define IGNORE_FRAMES 1
4018   
4019   /* We retrieve NFRAMES+1 pc values, but discard the first, since it   */
4020   /* points to our own frame.                                           */
4021 # ifdef REDIRECT_MALLOC
4022     if (GC_in_save_callers) {
4023       info[0].ci_pc = (word)(&GC_save_callers);
4024       for (i = 1; i < NFRAMES; ++i) info[i].ci_pc = 0;
4025       return;
4026     }
4027     GC_in_save_callers = TRUE;
4028 # endif
4029   GC_ASSERT(sizeof(struct callinfo) == sizeof(void *));
4030   npcs = backtrace((void **)tmp_info, NFRAMES + IGNORE_FRAMES);
4031   BCOPY(tmp_info+IGNORE_FRAMES, info, (npcs - IGNORE_FRAMES) * sizeof(void *));
4032   for (i = npcs - IGNORE_FRAMES; i < NFRAMES; ++i) info[i].ci_pc = 0;
4033 # ifdef REDIRECT_MALLOC
4034     GC_in_save_callers = FALSE;
4035 # endif
4036 }
4037
4038 #else /* No builtin backtrace; do it ourselves */
4039
4040 #if (defined(OPENBSD) || defined(NETBSD) || defined(FREEBSD)) && defined(SPARC)
4041 #  define FR_SAVFP fr_fp
4042 #  define FR_SAVPC fr_pc
4043 #else
4044 #  define FR_SAVFP fr_savfp
4045 #  define FR_SAVPC fr_savpc
4046 #endif
4047
4048 #if defined(SPARC) && (defined(__arch64__) || defined(__sparcv9))
4049 #   define BIAS 2047
4050 #else
4051 #   define BIAS 0
4052 #endif
4053
4054 void GC_save_callers (info) 
4055 struct callinfo info[NFRAMES];
4056 {
4057   struct frame *frame;
4058   struct frame *fp;
4059   int nframes = 0;
4060 # ifdef I386
4061     /* We assume this is turned on only with gcc as the compiler. */
4062     asm("movl %%ebp,%0" : "=r"(frame));
4063     fp = frame;
4064 # else
4065     frame = (struct frame *) GC_save_regs_in_stack ();
4066     fp = (struct frame *)((long) frame -> FR_SAVFP + BIAS);
4067 #endif
4068   
4069    for (; (!(fp HOTTER_THAN frame) && !(GC_stackbottom HOTTER_THAN (ptr_t)fp)
4070            && (nframes < NFRAMES));
4071        fp = (struct frame *)((long) fp -> FR_SAVFP + BIAS), nframes++) {
4072       register int i;
4073       
4074       info[nframes].ci_pc = fp->FR_SAVPC;
4075 #     if NARGS > 0
4076         for (i = 0; i < NARGS; i++) {
4077           info[nframes].ci_arg[i] = ~(fp->fr_arg[i]);
4078         }
4079 #     endif /* NARGS > 0 */
4080   }
4081   if (nframes < NFRAMES) info[nframes].ci_pc = 0;
4082 }
4083
4084 #endif /* No builtin backtrace */
4085
4086 #endif /* SAVE_CALL_CHAIN */
4087
4088 #ifdef NEED_CALLINFO
4089
4090 /* Print info to stderr.  We do NOT hold the allocation lock */
4091 void GC_print_callers (info)
4092 struct callinfo info[NFRAMES];
4093 {
4094     register int i;
4095     static int reentry_count = 0;
4096     GC_bool stop = FALSE;
4097
4098     /* FIXME: This should probably use a different lock, so that we     */
4099     /* become callable with or without the allocation lock.             */
4100     LOCK();
4101       ++reentry_count;
4102     UNLOCK();
4103     
4104 #   if NFRAMES == 1
4105       GC_err_printf0("\tCaller at allocation:\n");
4106 #   else
4107       GC_err_printf0("\tCall chain at allocation:\n");
4108 #   endif
4109     for (i = 0; i < NFRAMES && !stop ; i++) {
4110         if (info[i].ci_pc == 0) break;
4111 #       if NARGS > 0
4112         {
4113           int j;
4114
4115           GC_err_printf0("\t\targs: ");
4116           for (j = 0; j < NARGS; j++) {
4117             if (j != 0) GC_err_printf0(", ");
4118             GC_err_printf2("%d (0x%X)", ~(info[i].ci_arg[j]),
4119                                         ~(info[i].ci_arg[j]));
4120           }
4121           GC_err_printf0("\n");
4122         }
4123 #       endif
4124         if (reentry_count > 1) {
4125             /* We were called during an allocation during       */
4126             /* a previous GC_print_callers call; punt.          */
4127             GC_err_printf1("\t\t##PC##= 0x%lx\n", info[i].ci_pc);
4128             continue;
4129         }
4130         {
4131 #         ifdef LINUX
4132             FILE *pipe;
4133 #         endif
4134 #         if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4135              && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4136             char **sym_name =
4137               backtrace_symbols((void **)(&(info[i].ci_pc)), 1);
4138             char *name = sym_name[0];
4139 #         else
4140             char buf[40];
4141             char *name = buf;
4142             sprintf(buf, "##PC##= 0x%lx", info[i].ci_pc);
4143 #         endif
4144 #         if defined(LINUX) && !defined(SMALL_CONFIG)
4145             /* Try for a line number. */
4146             {
4147 #               define EXE_SZ 100
4148                 static char exe_name[EXE_SZ];
4149 #               define CMD_SZ 200
4150                 char cmd_buf[CMD_SZ];
4151 #               define RESULT_SZ 200
4152                 static char result_buf[RESULT_SZ];
4153                 size_t result_len;
4154                 char *old_preload;
4155 #               define PRELOAD_SZ 200
4156                 char preload_buf[PRELOAD_SZ];
4157                 static GC_bool found_exe_name = FALSE;
4158                 static GC_bool will_fail = FALSE;
4159                 int ret_code;
4160                 /* Try to get it via a hairy and expensive scheme.      */
4161                 /* First we get the name of the executable:             */
4162                 if (will_fail) goto out;
4163                 if (!found_exe_name) { 
4164                   ret_code = readlink("/proc/self/exe", exe_name, EXE_SZ);
4165                   if (ret_code < 0 || ret_code >= EXE_SZ
4166                       || exe_name[0] != '/') {
4167                     will_fail = TRUE;   /* Dont try again. */
4168                     goto out;
4169                   }
4170                   exe_name[ret_code] = '\0';
4171                   found_exe_name = TRUE;
4172                 }
4173                 /* Then we use popen to start addr2line -e <exe> <addr> */
4174                 /* There are faster ways to do this, but hopefully this */
4175                 /* isn't time critical.                                 */
4176                 sprintf(cmd_buf, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name,
4177                                  (unsigned long)info[i].ci_pc);
4178                 old_preload = getenv ("LD_PRELOAD");
4179                 if (0 != old_preload) {
4180                   if (strlen (old_preload) >= PRELOAD_SZ) {
4181                     will_fail = TRUE;
4182                     goto out;
4183                   }
4184                   strcpy (preload_buf, old_preload);
4185                   unsetenv ("LD_PRELOAD");
4186                 }
4187                 pipe = popen(cmd_buf, "r");
4188                 if (0 != old_preload
4189                     && 0 != setenv ("LD_PRELOAD", preload_buf, 0)) {
4190                   WARN("Failed to reset LD_PRELOAD\n", 0);
4191                 }
4192                 if (pipe == NULL
4193                     || (result_len = fread(result_buf, 1, RESULT_SZ - 1, pipe))
4194                        == 0) {
4195                   if (pipe != NULL) pclose(pipe);
4196                   will_fail = TRUE;
4197                   goto out;
4198                 }
4199                 if (result_buf[result_len - 1] == '\n') --result_len;
4200                 result_buf[result_len] = 0;
4201                 if (result_buf[0] == '?'
4202                     || result_buf[result_len-2] == ':' 
4203                        && result_buf[result_len-1] == '0') {
4204                     pclose(pipe);
4205                     goto out;
4206                 }
4207                 /* Get rid of embedded newline, if any.  Test for "main" */
4208                 {
4209                    char * nl = strchr(result_buf, '\n');
4210                    if (nl != NULL && nl < result_buf + result_len) {
4211                      *nl = ':';
4212                    }
4213                    if (strncmp(result_buf, "main", nl - result_buf) == 0) {
4214                      stop = TRUE;
4215                    }
4216                 }
4217                 if (result_len < RESULT_SZ - 25) {
4218                   /* Add in hex address */
4219                     sprintf(result_buf + result_len, " [0x%lx]",
4220                           (unsigned long)info[i].ci_pc);
4221                 }
4222                 name = result_buf;
4223                 pclose(pipe);
4224                 out:;
4225             }
4226 #         endif /* LINUX */
4227           GC_err_printf1("\t\t%s\n", name);
4228 #         if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4229              && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4230             free(sym_name);  /* May call GC_free; that's OK */
4231 #         endif
4232         }
4233     }
4234     LOCK();
4235       --reentry_count;
4236     UNLOCK();
4237 }
4238
4239 #endif /* NEED_CALLINFO */
4240
4241
4242
4243 #if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
4244
4245 /* Dump /proc/self/maps to GC_stderr, to enable looking up names for
4246    addresses in FIND_LEAK output. */
4247
4248 static word dump_maps(char *maps)
4249 {
4250     GC_err_write(maps, strlen(maps));
4251     return 1;
4252 }
4253
4254 void GC_print_address_map()
4255 {
4256     GC_err_printf0("---------- Begin address map ----------\n");
4257     GC_apply_to_maps(dump_maps);
4258     GC_err_printf0("---------- End address map ----------\n");
4259 }
4260
4261 #endif
4262
4263