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