OSDN Git Service

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