New test.
[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           if (((word)result % HBLKSIZE) != 0)
1621                   ABORT ("GC_unix_get_mem: Memory returned by mmap is not aligned to HBLKSIZE.");
1622     return((ptr_t)result);
1623 }
1624
1625 #endif
1626
1627 #ifndef USE_MMAP
1628
1629 ptr_t GC_unix_get_mem(bytes)
1630 word bytes;
1631 {
1632   ptr_t result;
1633 # ifdef IRIX5
1634     /* Bare sbrk isn't thread safe.  Play by malloc rules.      */
1635     /* The equivalent may be needed on other systems as well.   */
1636     __LOCK_MALLOC();
1637 # endif
1638   {
1639     ptr_t cur_brk = (ptr_t)sbrk(0);
1640     SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
1641     
1642     if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
1643     if (lsbs != 0) {
1644         if((ptr_t)sbrk(GC_page_size - lsbs) == (ptr_t)(-1)) return(0);
1645     }
1646     result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
1647     if (result == (ptr_t)(-1)) {
1648 #ifdef FALLBACK_TO_MMAP
1649                 result = GC_unix_get_mem_mmap (bytes);
1650 #else
1651                 result = 0;
1652 #endif
1653         }
1654   }
1655 # ifdef IRIX5
1656     __UNLOCK_MALLOC();
1657 # endif
1658   return(result);
1659 }
1660
1661 #endif /* Not USE_MMAP */
1662 #endif /* Not RS6000 */
1663
1664 # endif /* UN*X */
1665
1666 # ifdef OS2
1667
1668 void * os2_alloc(size_t bytes)
1669 {
1670     void * result;
1671
1672     if (DosAllocMem(&result, bytes, PAG_EXECUTE | PAG_READ |
1673                                     PAG_WRITE | PAG_COMMIT)
1674                     != NO_ERROR) {
1675         return(0);
1676     }
1677     if (result == 0) return(os2_alloc(bytes));
1678     return(result);
1679 }
1680
1681 # endif /* OS2 */
1682
1683
1684 # if defined(MSWIN32) || defined(MSWINCE)
1685 SYSTEM_INFO GC_sysinfo;
1686 # endif
1687
1688 # ifdef MSWIN32
1689
1690 # ifdef USE_GLOBAL_ALLOC
1691 #   define GLOBAL_ALLOC_TEST 1
1692 # else
1693 #   define GLOBAL_ALLOC_TEST GC_no_win32_dlls
1694 # endif
1695
1696 word GC_n_heap_bases = 0;
1697
1698 ptr_t GC_win32_get_mem(bytes)
1699 word bytes;
1700 {
1701     ptr_t result;
1702
1703     if (GLOBAL_ALLOC_TEST) {
1704         /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE.    */
1705         /* There are also unconfirmed rumors of other           */
1706         /* problems, so we dodge the issue.                     */
1707         result = (ptr_t) GlobalAlloc(0, bytes + HBLKSIZE);
1708         result = (ptr_t)(((word)result + HBLKSIZE) & ~(HBLKSIZE-1));
1709     } else {
1710         /* VirtualProtect only works on regions returned by a   */
1711         /* single VirtualAlloc call.  Thus we allocate one      */
1712         /* extra page, which will prevent merging of blocks     */
1713         /* in separate regions, and eliminate any temptation    */
1714         /* to call VirtualProtect on a range spanning regions.  */
1715         /* This wastes a small amount of memory, and risks      */
1716         /* increased fragmentation.  But better alternatives    */
1717         /* would require effort.                                */
1718         result = (ptr_t) VirtualAlloc(NULL, bytes + 1,
1719                                       MEM_COMMIT | MEM_RESERVE,
1720                                       PAGE_EXECUTE_READWRITE);
1721     }
1722     if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1723         /* If I read the documentation correctly, this can      */
1724         /* only happen if HBLKSIZE > 64k or not a power of 2.   */
1725     if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
1726     GC_heap_bases[GC_n_heap_bases++] = result;
1727     return(result);                       
1728 }
1729
1730 void GC_win32_free_heap ()
1731 {
1732     if (GC_no_win32_dlls) {
1733         while (GC_n_heap_bases > 0) {
1734             GlobalFree (GC_heap_bases[--GC_n_heap_bases]);
1735             GC_heap_bases[GC_n_heap_bases] = 0;
1736         }
1737     }
1738 }
1739 # endif
1740
1741 #ifdef AMIGA
1742 # define GC_AMIGA_AM
1743 # include "AmigaOS.c"
1744 # undef GC_AMIGA_AM
1745 #endif
1746
1747
1748 # ifdef MSWINCE
1749 word GC_n_heap_bases = 0;
1750
1751 ptr_t GC_wince_get_mem(bytes)
1752 word bytes;
1753 {
1754     ptr_t result;
1755     word i;
1756
1757     /* Round up allocation size to multiple of page size */
1758     bytes = (bytes + GC_page_size-1) & ~(GC_page_size-1);
1759
1760     /* Try to find reserved, uncommitted pages */
1761     for (i = 0; i < GC_n_heap_bases; i++) {
1762         if (((word)(-(signed_word)GC_heap_lengths[i])
1763              & (GC_sysinfo.dwAllocationGranularity-1))
1764             >= bytes) {
1765             result = GC_heap_bases[i] + GC_heap_lengths[i];
1766             break;
1767         }
1768     }
1769
1770     if (i == GC_n_heap_bases) {
1771         /* Reserve more pages */
1772         word res_bytes = (bytes + GC_sysinfo.dwAllocationGranularity-1)
1773                          & ~(GC_sysinfo.dwAllocationGranularity-1);
1774         /* If we ever support MPROTECT_VDB here, we will probably need to       */
1775         /* ensure that res_bytes is strictly > bytes, so that VirtualProtect    */
1776         /* never spans regions.  It seems to be OK for a VirtualFree argument   */
1777         /* to span regions, so we should be OK for now.                         */
1778         result = (ptr_t) VirtualAlloc(NULL, res_bytes,
1779                                       MEM_RESERVE | MEM_TOP_DOWN,
1780                                       PAGE_EXECUTE_READWRITE);
1781         if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1782             /* If I read the documentation correctly, this can  */
1783             /* only happen if HBLKSIZE > 64k or not a power of 2.       */
1784         if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
1785         GC_heap_bases[GC_n_heap_bases] = result;
1786         GC_heap_lengths[GC_n_heap_bases] = 0;
1787         GC_n_heap_bases++;
1788     }
1789
1790     /* Commit pages */
1791     result = (ptr_t) VirtualAlloc(result, bytes,
1792                                   MEM_COMMIT,
1793                                   PAGE_EXECUTE_READWRITE);
1794     if (result != NULL) {
1795         if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1796         GC_heap_lengths[i] += bytes;
1797     }
1798
1799     return(result);                       
1800 }
1801 # endif
1802
1803 #ifdef USE_MUNMAP
1804
1805 /* For now, this only works on Win32/WinCE and some Unix-like   */
1806 /* systems.  If you have something else, don't define           */
1807 /* USE_MUNMAP.                                                  */
1808 /* We assume ANSI C to support this feature.                    */
1809
1810 #if !defined(MSWIN32) && !defined(MSWINCE)
1811
1812 #include <unistd.h>
1813 #include <sys/mman.h>
1814 #include <sys/stat.h>
1815 #include <sys/types.h>
1816
1817 #endif
1818
1819 /* Compute a page aligned starting address for the unmap        */
1820 /* operation on a block of size bytes starting at start.        */
1821 /* Return 0 if the block is too small to make this feasible.    */
1822 ptr_t GC_unmap_start(ptr_t start, word bytes)
1823 {
1824     ptr_t result = start;
1825     /* Round start to next page boundary.       */
1826         result += GC_page_size - 1;
1827         result = (ptr_t)((word)result & ~(GC_page_size - 1));
1828     if (result + GC_page_size > start + bytes) return 0;
1829     return result;
1830 }
1831
1832 /* Compute end address for an unmap operation on the indicated  */
1833 /* block.                                                       */
1834 ptr_t GC_unmap_end(ptr_t start, word bytes)
1835 {
1836     ptr_t end_addr = start + bytes;
1837     end_addr = (ptr_t)((word)end_addr & ~(GC_page_size - 1));
1838     return end_addr;
1839 }
1840
1841 /* Under Win32/WinCE we commit (map) and decommit (unmap)       */
1842 /* memory using VirtualAlloc and VirtualFree.  These functions  */
1843 /* work on individual allocations of virtual memory, made       */
1844 /* previously using VirtualAlloc with the MEM_RESERVE flag.     */
1845 /* The ranges we need to (de)commit may span several of these   */
1846 /* allocations; therefore we use VirtualQuery to check          */
1847 /* allocation lengths, and split up the range as necessary.     */
1848
1849 /* We assume that GC_remap is called on exactly the same range  */
1850 /* as a previous call to GC_unmap.  It is safe to consistently  */
1851 /* round the endpoints in both places.                          */
1852 void GC_unmap(ptr_t start, word bytes)
1853 {
1854     ptr_t start_addr = GC_unmap_start(start, bytes);
1855     ptr_t end_addr = GC_unmap_end(start, bytes);
1856     word len = end_addr - start_addr;
1857     if (0 == start_addr) return;
1858 #   if defined(MSWIN32) || defined(MSWINCE)
1859       while (len != 0) {
1860           MEMORY_BASIC_INFORMATION mem_info;
1861           GC_word free_len;
1862           if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
1863               != sizeof(mem_info))
1864               ABORT("Weird VirtualQuery result");
1865           free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
1866           if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT))
1867               ABORT("VirtualFree failed");
1868           GC_unmapped_bytes += free_len;
1869           start_addr += free_len;
1870           len -= free_len;
1871       }
1872 #   else
1873       /* We immediately remap it to prevent an intervening mmap from    */
1874       /* accidentally grabbing the same address space.                  */
1875       {
1876         void * result;
1877         result = mmap(start_addr, len, PROT_NONE,
1878                       MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON,
1879                       zero_fd, 0/* offset */);
1880         if (result != (void *)start_addr) ABORT("mmap(...PROT_NONE...) failed");
1881       }
1882       GC_unmapped_bytes += len;
1883 #   endif
1884 }
1885
1886
1887 void GC_remap(ptr_t start, word bytes)
1888 {
1889     ptr_t start_addr = GC_unmap_start(start, bytes);
1890     ptr_t end_addr = GC_unmap_end(start, bytes);
1891     word len = end_addr - start_addr;
1892
1893 #   if defined(MSWIN32) || defined(MSWINCE)
1894       ptr_t result;
1895
1896       if (0 == start_addr) return;
1897       while (len != 0) {
1898           MEMORY_BASIC_INFORMATION mem_info;
1899           GC_word alloc_len;
1900           if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
1901               != sizeof(mem_info))
1902               ABORT("Weird VirtualQuery result");
1903           alloc_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
1904           result = VirtualAlloc(start_addr, alloc_len,
1905                                 MEM_COMMIT,
1906                                 PAGE_EXECUTE_READWRITE);
1907           if (result != start_addr) {
1908               ABORT("VirtualAlloc remapping failed");
1909           }
1910           GC_unmapped_bytes -= alloc_len;
1911           start_addr += alloc_len;
1912           len -= alloc_len;
1913       }
1914 #   else
1915       /* It was already remapped with PROT_NONE. */
1916       int result; 
1917
1918       if (0 == start_addr) return;
1919       result = mprotect(start_addr, len,
1920                         PROT_READ | PROT_WRITE | OPT_PROT_EXEC);
1921       if (result != 0) {
1922           GC_err_printf3(
1923                 "Mprotect failed at 0x%lx (length %ld) with errno %ld\n",
1924                 start_addr, len, errno);
1925           ABORT("Mprotect remapping failed");
1926       }
1927       GC_unmapped_bytes -= len;
1928 #   endif
1929 }
1930
1931 /* Two adjacent blocks have already been unmapped and are about to      */
1932 /* be merged.  Unmap the whole block.  This typically requires          */
1933 /* that we unmap a small section in the middle that was not previously  */
1934 /* unmapped due to alignment constraints.                               */
1935 void GC_unmap_gap(ptr_t start1, word bytes1, ptr_t start2, word bytes2)
1936 {
1937     ptr_t start1_addr = GC_unmap_start(start1, bytes1);
1938     ptr_t end1_addr = GC_unmap_end(start1, bytes1);
1939     ptr_t start2_addr = GC_unmap_start(start2, bytes2);
1940     ptr_t end2_addr = GC_unmap_end(start2, bytes2);
1941     ptr_t start_addr = end1_addr;
1942     ptr_t end_addr = start2_addr;
1943     word len;
1944     GC_ASSERT(start1 + bytes1 == start2);
1945     if (0 == start1_addr) start_addr = GC_unmap_start(start1, bytes1 + bytes2);
1946     if (0 == start2_addr) end_addr = GC_unmap_end(start1, bytes1 + bytes2);
1947     if (0 == start_addr) return;
1948     len = end_addr - start_addr;
1949 #   if defined(MSWIN32) || defined(MSWINCE)
1950       while (len != 0) {
1951           MEMORY_BASIC_INFORMATION mem_info;
1952           GC_word free_len;
1953           if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
1954               != sizeof(mem_info))
1955               ABORT("Weird VirtualQuery result");
1956           free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
1957           if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT))
1958               ABORT("VirtualFree failed");
1959           GC_unmapped_bytes += free_len;
1960           start_addr += free_len;
1961           len -= free_len;
1962       }
1963 #   else
1964       if (len != 0 && munmap(start_addr, len) != 0) ABORT("munmap failed");
1965       GC_unmapped_bytes += len;
1966 #   endif
1967 }
1968
1969 #endif /* USE_MUNMAP */
1970
1971 /* Routine for pushing any additional roots.  In THREADS        */
1972 /* environment, this is also responsible for marking from       */
1973 /* thread stacks.                                               */
1974 #ifndef THREADS
1975 void (*GC_push_other_roots)() = 0;
1976 #else /* THREADS */
1977
1978 # ifdef PCR
1979 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
1980 {
1981     struct PCR_ThCtl_TInfoRep info;
1982     PCR_ERes result;
1983     
1984     info.ti_stkLow = info.ti_stkHi = 0;
1985     result = PCR_ThCtl_GetInfo(t, &info);
1986     GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi));
1987     return(result);
1988 }
1989
1990 /* Push the contents of an old object. We treat this as stack   */
1991 /* data only becasue that makes it robust against mark stack    */
1992 /* overflow.                                                    */
1993 PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data)
1994 {
1995     GC_push_all_stack((ptr_t)p, (ptr_t)p + size);
1996     return(PCR_ERes_okay);
1997 }
1998
1999
2000 void GC_default_push_other_roots GC_PROTO((void))
2001 {
2002     /* Traverse data allocated by previous memory managers.             */
2003         {
2004           extern struct PCR_MM_ProcsRep * GC_old_allocator;
2005           
2006           if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false,
2007                                                    GC_push_old_obj, 0)
2008               != PCR_ERes_okay) {
2009               ABORT("Old object enumeration failed");
2010           }
2011         }
2012     /* Traverse all thread stacks. */
2013         if (PCR_ERes_IsErr(
2014                 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0))
2015               || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
2016               ABORT("Thread stack marking failed\n");
2017         }
2018 }
2019
2020 # endif /* PCR */
2021
2022 # ifdef SRC_M3
2023
2024 # ifdef ALL_INTERIOR_POINTERS
2025     --> misconfigured
2026 # endif
2027
2028 void GC_push_thread_structures GC_PROTO((void))
2029 {
2030     /* Not our responsibibility. */
2031 }
2032
2033 extern void ThreadF__ProcessStacks();
2034
2035 void GC_push_thread_stack(start, stop)
2036 word start, stop;
2037 {
2038    GC_push_all_stack((ptr_t)start, (ptr_t)stop + sizeof(word));
2039 }
2040
2041 /* Push routine with M3 specific calling convention. */
2042 GC_m3_push_root(dummy1, p, dummy2, dummy3)
2043 word *p;
2044 ptr_t dummy1, dummy2;
2045 int dummy3;
2046 {
2047     word q = *p;
2048     
2049     GC_PUSH_ONE_STACK(q, p);
2050 }
2051
2052 /* M3 set equivalent to RTHeap.TracedRefTypes */
2053 typedef struct { int elts[1]; }  RefTypeSet;
2054 RefTypeSet GC_TracedRefTypes = {{0x1}};
2055
2056 void GC_default_push_other_roots GC_PROTO((void))
2057 {
2058     /* Use the M3 provided routine for finding static roots.     */
2059     /* This is a bit dubious, since it presumes no C roots.      */
2060     /* We handle the collector roots explicitly in GC_push_roots */
2061         RTMain__GlobalMapProc(GC_m3_push_root, 0, GC_TracedRefTypes);
2062         if (GC_words_allocd > 0) {
2063             ThreadF__ProcessStacks(GC_push_thread_stack);
2064         }
2065         /* Otherwise this isn't absolutely necessary, and we have       */
2066         /* startup ordering problems.                                   */
2067 }
2068
2069 # endif /* SRC_M3 */
2070
2071 # if defined(GC_SOLARIS_THREADS) || defined(GC_PTHREADS) || \
2072      defined(GC_WIN32_THREADS)
2073
2074 extern void GC_push_all_stacks();
2075
2076 void GC_default_push_other_roots GC_PROTO((void))
2077 {
2078     GC_push_all_stacks();
2079 }
2080
2081 # endif /* GC_SOLARIS_THREADS || GC_PTHREADS */
2082
2083 void (*GC_push_other_roots) GC_PROTO((void)) = GC_default_push_other_roots;
2084
2085 #endif /* THREADS */
2086
2087 /*
2088  * Routines for accessing dirty  bits on virtual pages.
2089  * We plan to eventually implement four strategies for doing so:
2090  * DEFAULT_VDB: A simple dummy implementation that treats every page
2091  *              as possibly dirty.  This makes incremental collection
2092  *              useless, but the implementation is still correct.
2093  * PCR_VDB:     Use PPCRs virtual dirty bit facility.
2094  * PROC_VDB:    Use the /proc facility for reading dirty bits.  Only
2095  *              works under some SVR4 variants.  Even then, it may be
2096  *              too slow to be entirely satisfactory.  Requires reading
2097  *              dirty bits for entire address space.  Implementations tend
2098  *              to assume that the client is a (slow) debugger.
2099  * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
2100  *              dirtied pages.  The implementation (and implementability)
2101  *              is highly system dependent.  This usually fails when system
2102  *              calls write to a protected page.  We prevent the read system
2103  *              call from doing so.  It is the clients responsibility to
2104  *              make sure that other system calls are similarly protected
2105  *              or write only to the stack.
2106  */
2107 GC_bool GC_dirty_maintained = FALSE;
2108
2109 # ifdef DEFAULT_VDB
2110
2111 /* All of the following assume the allocation lock is held, and */
2112 /* signals are disabled.                                        */
2113
2114 /* The client asserts that unallocated pages in the heap are never      */
2115 /* written.                                                             */
2116
2117 /* Initialize virtual dirty bit implementation.                 */
2118 void GC_dirty_init()
2119 {
2120 #   ifdef PRINTSTATS
2121       GC_printf0("Initializing DEFAULT_VDB...\n");
2122 #   endif
2123     GC_dirty_maintained = TRUE;
2124 }
2125
2126 /* Retrieve system dirty bits for heap to a local buffer.       */
2127 /* Restore the systems notion of which pages are dirty.         */
2128 void GC_read_dirty()
2129 {}
2130
2131 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer?    */
2132 /* If the actual page size is different, this returns TRUE if any       */
2133 /* of the pages overlapping h are dirty.  This routine may err on the   */
2134 /* side of labelling pages as dirty (and this implementation does).     */
2135 /*ARGSUSED*/
2136 GC_bool GC_page_was_dirty(h)
2137 struct hblk *h;
2138 {
2139     return(TRUE);
2140 }
2141
2142 /*
2143  * The following two routines are typically less crucial.  They matter
2144  * most with large dynamic libraries, or if we can't accurately identify
2145  * stacks, e.g. under Solaris 2.X.  Otherwise the following default
2146  * versions are adequate.
2147  */
2148  
2149 /* Could any valid GC heap pointer ever have been written to this page? */
2150 /*ARGSUSED*/
2151 GC_bool GC_page_was_ever_dirty(h)
2152 struct hblk *h;
2153 {
2154     return(TRUE);
2155 }
2156
2157 /* Reset the n pages starting at h to "was never dirty" status. */
2158 void GC_is_fresh(h, n)
2159 struct hblk *h;
2160 word n;
2161 {
2162 }
2163
2164 /* A call that:                                         */
2165 /* I) hints that [h, h+nblocks) is about to be written. */
2166 /* II) guarantees that protection is removed.           */
2167 /* (I) may speed up some dirty bit implementations.     */
2168 /* (II) may be essential if we need to ensure that      */
2169 /* pointer-free system call buffers in the heap are     */
2170 /* not protected.                                       */
2171 /*ARGSUSED*/
2172 void GC_remove_protection(h, nblocks, is_ptrfree)
2173 struct hblk *h;
2174 word nblocks;
2175 GC_bool is_ptrfree;
2176 {
2177 }
2178
2179 # endif /* DEFAULT_VDB */
2180
2181
2182 # ifdef MPROTECT_VDB
2183
2184 /*
2185  * See DEFAULT_VDB for interface descriptions.
2186  */
2187
2188 /*
2189  * This implementation maintains dirty bits itself by catching write
2190  * faults and keeping track of them.  We assume nobody else catches
2191  * SIGBUS or SIGSEGV.  We assume no write faults occur in system calls.
2192  * This means that clients must ensure that system calls don't write
2193  * to the write-protected heap.  Probably the best way to do this is to
2194  * ensure that system calls write at most to POINTERFREE objects in the
2195  * heap, and do even that only if we are on a platform on which those
2196  * are not protected.  Another alternative is to wrap system calls
2197  * (see example for read below), but the current implementation holds
2198  * a lock across blocking calls, making it problematic for multithreaded
2199  * applications. 
2200  * We assume the page size is a multiple of HBLKSIZE.
2201  * We prefer them to be the same.  We avoid protecting POINTERFREE
2202  * objects only if they are the same.
2203  */
2204
2205 # if !defined(MSWIN32) && !defined(MSWINCE) && !defined(DARWIN)
2206
2207 #   include <sys/mman.h>
2208 #   include <signal.h>
2209 #   include <sys/syscall.h>
2210
2211 #   define PROTECT(addr, len) \
2212           if (mprotect((caddr_t)(addr), (size_t)(len), \
2213                        PROT_READ | OPT_PROT_EXEC) < 0) { \
2214             ABORT("mprotect failed"); \
2215           }
2216 #   define UNPROTECT(addr, len) \
2217           if (mprotect((caddr_t)(addr), (size_t)(len), \
2218                        PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
2219             ABORT("un-mprotect failed"); \
2220           }
2221           
2222 # else
2223
2224 # ifdef DARWIN
2225     /* Using vm_protect (mach syscall) over mprotect (BSD syscall) seems to
2226        decrease the likelihood of some of the problems described below. */
2227     #include <mach/vm_map.h>
2228     static mach_port_t GC_task_self;
2229     #define PROTECT(addr,len) \
2230         if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2231                 FALSE,VM_PROT_READ) != KERN_SUCCESS) { \
2232             ABORT("vm_portect failed"); \
2233         }
2234     #define UNPROTECT(addr,len) \
2235         if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2236                 FALSE,VM_PROT_READ|VM_PROT_WRITE) != KERN_SUCCESS) { \
2237             ABORT("vm_portect failed"); \
2238         }
2239 # else
2240     
2241 #   ifndef MSWINCE
2242 #     include <signal.h>
2243 #   endif
2244
2245     static DWORD protect_junk;
2246 #   define PROTECT(addr, len) \
2247           if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
2248                               &protect_junk)) { \
2249             DWORD last_error = GetLastError(); \
2250             GC_printf1("Last error code: %lx\n", last_error); \
2251             ABORT("VirtualProtect failed"); \
2252           }
2253 #   define UNPROTECT(addr, len) \
2254           if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
2255                               &protect_junk)) { \
2256             ABORT("un-VirtualProtect failed"); \
2257           }
2258 # endif /* !DARWIN */
2259 # endif /* MSWIN32 || MSWINCE || DARWIN */
2260
2261 #if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2262     typedef void (* SIG_PF)();
2263 #endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2264
2265 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX) \
2266     || defined(HURD)
2267 # ifdef __STDC__
2268     typedef void (* SIG_PF)(int);
2269 # else
2270     typedef void (* SIG_PF)();
2271 # endif
2272 #endif /* SUNOS5SIGS || OSF1 || LINUX || HURD */
2273
2274 #if defined(MSWIN32)
2275     typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
2276 #   undef SIG_DFL
2277 #   define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
2278 #endif
2279 #if defined(MSWINCE)
2280     typedef LONG (WINAPI *SIG_PF)(struct _EXCEPTION_POINTERS *);
2281 #   undef SIG_DFL
2282 #   define SIG_DFL (SIG_PF) (-1)
2283 #endif
2284
2285 #if defined(IRIX5) || defined(OSF1) || defined(HURD)
2286     typedef void (* REAL_SIG_PF)(int, int, struct sigcontext *);
2287 #endif /* IRIX5 || OSF1 || HURD */
2288
2289 #if defined(SUNOS5SIGS)
2290 # if defined(HPUX) || defined(FREEBSD)
2291 #   define SIGINFO_T siginfo_t
2292 # else
2293 #   define SIGINFO_T struct siginfo
2294 # endif
2295 # ifdef __STDC__
2296     typedef void (* REAL_SIG_PF)(int, SIGINFO_T *, void *);
2297 # else
2298     typedef void (* REAL_SIG_PF)();
2299 # endif
2300 #endif /* SUNOS5SIGS */
2301
2302 #if defined(LINUX)
2303 #   if __GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ >= 2
2304       typedef struct sigcontext s_c;
2305 #   else  /* glibc < 2.2 */
2306 #     include <linux/version.h>
2307 #     if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA) || defined(ARM32)
2308         typedef struct sigcontext s_c;
2309 #     else
2310         typedef struct sigcontext_struct s_c;
2311 #     endif
2312 #   endif  /* glibc < 2.2 */
2313 #   if defined(ALPHA) || defined(M68K)
2314       typedef void (* REAL_SIG_PF)(int, int, s_c *);
2315 #   else
2316 #     if defined(IA64) || defined(HP_PA) || defined(X86_64)
2317         typedef void (* REAL_SIG_PF)(int, siginfo_t *, s_c *);
2318         /* FIXME:                                                 */
2319         /* According to SUSV3, the last argument should have type */
2320         /* void * or ucontext_t *                                 */
2321 #     else
2322         typedef void (* REAL_SIG_PF)(int, s_c);
2323 #     endif
2324 #   endif
2325 #   ifdef ALPHA
2326     /* Retrieve fault address from sigcontext structure by decoding     */
2327     /* instruction.                                                     */
2328     char * get_fault_addr(s_c *sc) {
2329         unsigned instr;
2330         word faultaddr;
2331
2332         instr = *((unsigned *)(sc->sc_pc));
2333         faultaddr = sc->sc_regs[(instr >> 16) & 0x1f];
2334         faultaddr += (word) (((int)instr << 16) >> 16);
2335         return (char *)faultaddr;
2336     }
2337 #   endif /* !ALPHA */
2338 # endif /* LINUX */
2339
2340 #ifndef DARWIN
2341 SIG_PF GC_old_bus_handler;
2342 SIG_PF GC_old_segv_handler;     /* Also old MSWIN32 ACCESS_VIOLATION filter */
2343 #endif /* !DARWIN */
2344
2345 #if defined(THREADS)
2346 /* We need to lock around the bitmap update in the write fault handler  */
2347 /* in order to avoid the risk of losing a bit.  We do this with a       */
2348 /* test-and-set spin lock if we know how to do that.  Otherwise we      */
2349 /* check whether we are already in the handler and use the dumb but     */
2350 /* safe fallback algorithm of setting all bits in the word.             */
2351 /* Contention should be very rare, so we do the minimum to handle it    */
2352 /* correctly.                                                           */
2353 #ifdef GC_TEST_AND_SET_DEFINED
2354   static VOLATILE unsigned int fault_handler_lock = 0;
2355   void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2356     while (GC_test_and_set(&fault_handler_lock)) {}
2357     /* Could also revert to set_pht_entry_from_index_safe if initial    */
2358     /* GC_test_and_set fails.                                           */
2359     set_pht_entry_from_index(db, index);
2360     GC_clear(&fault_handler_lock);
2361   }
2362 #else /* !GC_TEST_AND_SET_DEFINED */
2363   /* THIS IS INCORRECT! The dirty bit vector may be temporarily wrong,  */
2364   /* just before we notice the conflict and correct it. We may end up   */
2365   /* looking at it while it's wrong.  But this requires contention      */
2366   /* exactly when a GC is triggered, which seems far less likely to     */
2367   /* fail than the old code, which had no reported failures.  Thus we   */
2368   /* leave it this way while we think of something better, or support   */
2369   /* GC_test_and_set on the remaining platforms.                        */
2370   static VOLATILE word currently_updating = 0;
2371   void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2372     unsigned int update_dummy;
2373     currently_updating = (word)(&update_dummy);
2374     set_pht_entry_from_index(db, index);
2375     /* If we get contention in the 10 or so instruction window here,    */
2376     /* and we get stopped by a GC between the two updates, we lose!     */
2377     if (currently_updating != (word)(&update_dummy)) {
2378         set_pht_entry_from_index_safe(db, index);
2379         /* We claim that if two threads concurrently try to update the  */
2380         /* dirty bit vector, the first one to execute UPDATE_START      */
2381         /* will see it changed when UPDATE_END is executed.  (Note that */
2382         /* &update_dummy must differ in two distinct threads.)  It      */
2383         /* will then execute set_pht_entry_from_index_safe, thus        */
2384         /* returning us to a safe state, though not soon enough.        */
2385     }
2386   }
2387 #endif /* !GC_TEST_AND_SET_DEFINED */
2388 #else /* !THREADS */
2389 # define async_set_pht_entry_from_index(db, index) \
2390         set_pht_entry_from_index(db, index)
2391 #endif /* !THREADS */
2392
2393 /*ARGSUSED*/
2394 #if !defined(DARWIN)
2395 # if defined (SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2396     void GC_write_fault_handler(sig, code, scp, addr)
2397     int sig, code;
2398     struct sigcontext *scp;
2399     char * addr;
2400 #   ifdef SUNOS4
2401 #     define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2402 #     define CODE_OK (FC_CODE(code) == FC_PROT \
2403                     || (FC_CODE(code) == FC_OBJERR \
2404                        && FC_ERRNO(code) == FC_PROT))
2405 #   endif
2406 #   ifdef FREEBSD
2407 #     define SIG_OK (sig == SIGBUS)
2408 #     define CODE_OK TRUE
2409 #   endif
2410 # endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2411
2412 # if defined(IRIX5) || defined(OSF1) || defined(HURD)
2413 #   include <errno.h>
2414     void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
2415 #   ifdef OSF1
2416 #     define SIG_OK (sig == SIGSEGV)
2417 #     define CODE_OK (code == 2 /* experimentally determined */)
2418 #   endif
2419 #   ifdef IRIX5
2420 #     define SIG_OK (sig == SIGSEGV)
2421 #     define CODE_OK (code == EACCES)
2422 #   endif
2423 #   ifdef HURD
2424 #     define SIG_OK (sig == SIGBUS || sig == SIGSEGV)   
2425 #     define CODE_OK  TRUE
2426 #   endif
2427 # endif /* IRIX5 || OSF1 || HURD */
2428
2429 # if defined(LINUX)
2430 #   if defined(ALPHA) || defined(M68K)
2431       void GC_write_fault_handler(int sig, int code, s_c * sc)
2432 #   else
2433 #     if defined(IA64) || defined(HP_PA) || defined(X86_64)
2434         void GC_write_fault_handler(int sig, siginfo_t * si, s_c * scp)
2435 #     else
2436 #       if defined(ARM32)
2437           void GC_write_fault_handler(int sig, int a2, int a3, int a4, s_c sc)
2438 #       else
2439           void GC_write_fault_handler(int sig, s_c sc)
2440 #       endif
2441 #     endif
2442 #   endif
2443 #   define SIG_OK (sig == SIGSEGV)
2444 #   define CODE_OK TRUE
2445         /* Empirically c.trapno == 14, on IA32, but is that useful?     */
2446         /* Should probably consider alignment issues on other           */
2447         /* architectures.                                               */
2448 # endif /* LINUX */
2449
2450 # if defined(SUNOS5SIGS)
2451 #  ifdef __STDC__
2452     void GC_write_fault_handler(int sig, SIGINFO_T *scp, void * context)
2453 #  else
2454     void GC_write_fault_handler(sig, scp, context)
2455     int sig;
2456     SIGINFO_T *scp;
2457     void * context;
2458 #  endif
2459 #   ifdef HPUX
2460 #     define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2461 #     define CODE_OK (scp -> si_code == SEGV_ACCERR) \
2462                      || (scp -> si_code == BUS_ADRERR) \
2463                      || (scp -> si_code == BUS_UNKNOWN) \
2464                      || (scp -> si_code == SEGV_UNKNOWN) \
2465                      || (scp -> si_code == BUS_OBJERR)
2466 #   else
2467 #     ifdef FREEBSD
2468 #       define SIG_OK (sig == SIGBUS)
2469 #       define CODE_OK (scp -> si_code == BUS_PAGE_FAULT)
2470 #     else
2471 #       define SIG_OK (sig == SIGSEGV)
2472 #       define CODE_OK (scp -> si_code == SEGV_ACCERR)
2473 #     endif
2474 #   endif    
2475 # endif /* SUNOS5SIGS */
2476
2477 # if defined(MSWIN32) || defined(MSWINCE)
2478     LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info)
2479 #   define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
2480                         STATUS_ACCESS_VIOLATION)
2481 #   define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
2482                         /* Write fault */
2483 # endif /* MSWIN32 || MSWINCE */
2484 {
2485     register unsigned i;
2486 #   if defined(HURD) 
2487         char *addr = (char *) code;
2488 #   endif
2489 #   ifdef IRIX5
2490         char * addr = (char *) (size_t) (scp -> sc_badvaddr);
2491 #   endif
2492 #   if defined(OSF1) && defined(ALPHA)
2493         char * addr = (char *) (scp -> sc_traparg_a0);
2494 #   endif
2495 #   ifdef SUNOS5SIGS
2496         char * addr = (char *) (scp -> si_addr);
2497 #   endif
2498 #   ifdef LINUX
2499 #     if defined(I386)
2500         char * addr = (char *) (sc.cr2);
2501 #     else
2502 #       if defined(M68K)
2503           char * addr = NULL;
2504
2505           struct sigcontext *scp = (struct sigcontext *)(sc);
2506
2507           int format = (scp->sc_formatvec >> 12) & 0xf;
2508           unsigned long *framedata = (unsigned long *)(scp + 1); 
2509           unsigned long ea;
2510
2511           if (format == 0xa || format == 0xb) {
2512                 /* 68020/030 */
2513                 ea = framedata[2];
2514           } else if (format == 7) {
2515                 /* 68040 */
2516                 ea = framedata[3];
2517                 if (framedata[1] & 0x08000000) {
2518                         /* correct addr on misaligned access */
2519                         ea = (ea+4095)&(~4095);
2520                 }
2521           } else if (format == 4) {
2522                 /* 68060 */
2523                 ea = framedata[0];
2524                 if (framedata[1] & 0x08000000) {
2525                         /* correct addr on misaligned access */
2526                         ea = (ea+4095)&(~4095);
2527                 }
2528           }     
2529           addr = (char *)ea;
2530 #       else
2531 #         ifdef ALPHA
2532             char * addr = get_fault_addr(sc);
2533 #         else
2534 #           if defined(IA64) || defined(HP_PA) || defined(X86_64)
2535               char * addr = si -> si_addr;
2536               /* I believe this is claimed to work on all platforms for */
2537               /* Linux 2.3.47 and later.  Hopefully we don't have to    */
2538               /* worry about earlier kernels on IA64.                   */
2539 #           else
2540 #             if defined(POWERPC)
2541                 char * addr = (char *) (sc.regs->dar);
2542 #             else
2543 #               if defined(ARM32)
2544                   char * addr = (char *)sc.fault_address;
2545 #               else
2546 #                 if defined(CRIS)
2547                     char * addr = (char *)sc.regs.csraddr;
2548 #                 else
2549                     --> architecture not supported
2550 #                 endif
2551 #               endif
2552 #             endif
2553 #           endif
2554 #         endif
2555 #       endif
2556 #     endif
2557 #   endif
2558 #   if defined(MSWIN32) || defined(MSWINCE)
2559         char * addr = (char *) (exc_info -> ExceptionRecord
2560                                 -> ExceptionInformation[1]);
2561 #       define sig SIGSEGV
2562 #   endif
2563     
2564     if (SIG_OK && CODE_OK) {
2565         register struct hblk * h =
2566                         (struct hblk *)((word)addr & ~(GC_page_size-1));
2567         GC_bool in_allocd_block;
2568         
2569 #       ifdef SUNOS5SIGS
2570             /* Address is only within the correct physical page.        */
2571             in_allocd_block = FALSE;
2572             for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2573               if (HDR(h+i) != 0) {
2574                 in_allocd_block = TRUE;
2575               }
2576             }
2577 #       else
2578             in_allocd_block = (HDR(addr) != 0);
2579 #       endif
2580         if (!in_allocd_block) {
2581             /* FIXME - We should make sure that we invoke the   */
2582             /* old handler with the appropriate calling         */
2583             /* sequence, which often depends on SA_SIGINFO.     */
2584
2585             /* Heap blocks now begin and end on page boundaries */
2586             SIG_PF old_handler;
2587             
2588             if (sig == SIGSEGV) {
2589                 old_handler = GC_old_segv_handler;
2590             } else {
2591                 old_handler = GC_old_bus_handler;
2592             }
2593             if (old_handler == SIG_DFL) {
2594 #               if !defined(MSWIN32) && !defined(MSWINCE)
2595                     GC_err_printf1("Segfault at 0x%lx\n", addr);
2596                     ABORT("Unexpected bus error or segmentation fault");
2597 #               else
2598                     return(EXCEPTION_CONTINUE_SEARCH);
2599 #               endif
2600             } else {
2601 #               if defined (SUNOS4) \
2602                     || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2603                     (*old_handler) (sig, code, scp, addr);
2604                     return;
2605 #               endif
2606 #               if defined (SUNOS5SIGS)
2607                     /*
2608                      * FIXME: For FreeBSD, this code should check if the 
2609                      * old signal handler used the traditional BSD style and
2610                      * if so call it using that style.
2611                      */
2612                     (*(REAL_SIG_PF)old_handler) (sig, scp, context);
2613                     return;
2614 #               endif
2615 #               if defined (LINUX)
2616 #                   if defined(ALPHA) || defined(M68K)
2617                         (*(REAL_SIG_PF)old_handler) (sig, code, sc);
2618 #                   else 
2619 #                     if defined(IA64) || defined(HP_PA) || defined(X86_64)
2620                         (*(REAL_SIG_PF)old_handler) (sig, si, scp);
2621 #                     else
2622                         (*(REAL_SIG_PF)old_handler) (sig, sc);
2623 #                     endif
2624 #                   endif
2625                     return;
2626 #               endif
2627 #               if defined (IRIX5) || defined(OSF1) || defined(HURD)
2628                     (*(REAL_SIG_PF)old_handler) (sig, code, scp);
2629                     return;
2630 #               endif
2631 #               ifdef MSWIN32
2632                     return((*old_handler)(exc_info));
2633 #               endif
2634             }
2635         }
2636         UNPROTECT(h, GC_page_size);
2637         /* We need to make sure that no collection occurs between       */
2638         /* the UNPROTECT and the setting of the dirty bit.  Otherwise   */
2639         /* a write by a third thread might go unnoticed.  Reversing     */
2640         /* the order is just as bad, since we would end up unprotecting */
2641         /* a page in a GC cycle during which it's not marked.           */
2642         /* Currently we do this by disabling the thread stopping        */
2643         /* signals while this handler is running.  An alternative might */
2644         /* be to record the fact that we're about to unprotect, or      */
2645         /* have just unprotected a page in the GC's thread structure,   */
2646         /* and then to have the thread stopping code set the dirty      */
2647         /* flag, if necessary.                                          */
2648         for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2649             register int index = PHT_HASH(h+i);
2650             
2651             async_set_pht_entry_from_index(GC_dirty_pages, index);
2652         }
2653 #       if defined(OSF1)
2654             /* These reset the signal handler each time by default. */
2655             signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
2656 #       endif
2657         /* The write may not take place before dirty bits are read.     */
2658         /* But then we'll fault again ...                               */
2659 #       if defined(MSWIN32) || defined(MSWINCE)
2660             return(EXCEPTION_CONTINUE_EXECUTION);
2661 #       else
2662             return;
2663 #       endif
2664     }
2665 #if defined(MSWIN32) || defined(MSWINCE)
2666     return EXCEPTION_CONTINUE_SEARCH;
2667 #else
2668     GC_err_printf1("Segfault at 0x%lx\n", addr);
2669     ABORT("Unexpected bus error or segmentation fault");
2670 #endif
2671 }
2672 #endif /* !DARWIN */
2673
2674 /*
2675  * We hold the allocation lock.  We expect block h to be written
2676  * shortly.  Ensure that all pages containing any part of the n hblks
2677  * starting at h are no longer protected.  If is_ptrfree is false,
2678  * also ensure that they will subsequently appear to be dirty.
2679  */
2680 void GC_remove_protection(h, nblocks, is_ptrfree)
2681 struct hblk *h;
2682 word nblocks;
2683 GC_bool is_ptrfree;
2684 {
2685     struct hblk * h_trunc;  /* Truncated to page boundary */
2686     struct hblk * h_end;    /* Page boundary following block end */
2687     struct hblk * current;
2688     GC_bool found_clean;
2689     
2690     if (!GC_dirty_maintained) return;
2691     h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1));
2692     h_end = (struct hblk *)(((word)(h + nblocks) + GC_page_size-1)
2693                             & ~(GC_page_size-1));
2694     found_clean = FALSE;
2695     for (current = h_trunc; current < h_end; ++current) {
2696         int index = PHT_HASH(current);
2697             
2698         if (!is_ptrfree || current < h || current >= h + nblocks) {
2699             async_set_pht_entry_from_index(GC_dirty_pages, index);
2700         }
2701     }
2702     UNPROTECT(h_trunc, (ptr_t)h_end - (ptr_t)h_trunc);
2703 }
2704
2705 #if !defined(DARWIN)
2706 void GC_dirty_init()
2707 {
2708 #   if defined(SUNOS5SIGS) || defined(IRIX5) || defined(LINUX) || \
2709        defined(OSF1) || defined(HURD)
2710       struct sigaction  act, oldact;
2711       /* We should probably specify SA_SIGINFO for Linux, and handle    */
2712       /* the different architectures more uniformly.                    */
2713 #     if defined(IRIX5) || defined(LINUX) && !defined(X86_64) \
2714          || defined(OSF1) || defined(HURD)
2715         act.sa_flags    = SA_RESTART;
2716         act.sa_handler  = (SIG_PF)GC_write_fault_handler;
2717 #     else
2718         act.sa_flags    = SA_RESTART | SA_SIGINFO;
2719         act.sa_sigaction = GC_write_fault_handler;
2720 #     endif
2721       (void)sigemptyset(&act.sa_mask);
2722 #     ifdef SIG_SUSPEND
2723         /* Arrange to postpone SIG_SUSPEND while we're in a write fault */
2724         /* handler.  This effectively makes the handler atomic w.r.t.   */
2725         /* stopping the world for GC.                                   */
2726         (void)sigaddset(&act.sa_mask, SIG_SUSPEND);
2727 #     endif /* SIG_SUSPEND */
2728 #    endif
2729 #   ifdef PRINTSTATS
2730         GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2731 #   endif
2732     GC_dirty_maintained = TRUE;
2733     if (GC_page_size % HBLKSIZE != 0) {
2734         GC_err_printf0("Page size not multiple of HBLKSIZE\n");
2735         ABORT("Page size not multiple of HBLKSIZE");
2736     }
2737 #   if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2738       GC_old_bus_handler = signal(SIGBUS, GC_write_fault_handler);
2739       if (GC_old_bus_handler == SIG_IGN) {
2740         GC_err_printf0("Previously ignored bus error!?");
2741         GC_old_bus_handler = SIG_DFL;
2742       }
2743       if (GC_old_bus_handler != SIG_DFL) {
2744 #       ifdef PRINTSTATS
2745           GC_err_printf0("Replaced other SIGBUS handler\n");
2746 #       endif
2747       }
2748 #   endif
2749 #   if defined(SUNOS4)
2750       GC_old_segv_handler = signal(SIGSEGV, (SIG_PF)GC_write_fault_handler);
2751       if (GC_old_segv_handler == SIG_IGN) {
2752         GC_err_printf0("Previously ignored segmentation violation!?");
2753         GC_old_segv_handler = SIG_DFL;
2754       }
2755       if (GC_old_segv_handler != SIG_DFL) {
2756 #       ifdef PRINTSTATS
2757           GC_err_printf0("Replaced other SIGSEGV handler\n");
2758 #       endif
2759       }
2760 #   endif
2761 #   if (defined(SUNOS5SIGS) && !defined(FREEBSD)) || defined(IRIX5) \
2762        || defined(LINUX) || defined(OSF1) || defined(HURD)
2763       /* SUNOS5SIGS includes HPUX */
2764 #     if defined(GC_IRIX_THREADS)
2765         sigaction(SIGSEGV, 0, &oldact);
2766         sigaction(SIGSEGV, &act, 0);
2767 #     else 
2768         {
2769           int res = sigaction(SIGSEGV, &act, &oldact);
2770           if (res != 0) ABORT("Sigaction failed");
2771         }
2772 #     endif
2773 #     if defined(_sigargs) || defined(HURD) || !defined(SA_SIGINFO)
2774         /* This is Irix 5.x, not 6.x.  Irix 5.x does not have   */
2775         /* sa_sigaction.                                        */
2776         GC_old_segv_handler = oldact.sa_handler;
2777 #     else /* Irix 6.x or SUNOS5SIGS or LINUX */
2778         if (oldact.sa_flags & SA_SIGINFO) {
2779           GC_old_segv_handler = (SIG_PF)(oldact.sa_sigaction);
2780         } else {
2781           GC_old_segv_handler = oldact.sa_handler;
2782         }
2783 #     endif
2784       if (GC_old_segv_handler == SIG_IGN) {
2785              GC_err_printf0("Previously ignored segmentation violation!?");
2786              GC_old_segv_handler = SIG_DFL;
2787       }
2788       if (GC_old_segv_handler != SIG_DFL) {
2789 #       ifdef PRINTSTATS
2790           GC_err_printf0("Replaced other SIGSEGV handler\n");
2791 #       endif
2792       }
2793 #   endif /* (SUNOS5SIGS && !FREEBSD) || IRIX5 || LINUX || OSF1 || HURD */
2794 #   if defined(HPUX) || defined(LINUX) || defined(HURD) \
2795       || (defined(FREEBSD) && defined(SUNOS5SIGS))
2796       sigaction(SIGBUS, &act, &oldact);
2797       GC_old_bus_handler = oldact.sa_handler;
2798       if (GC_old_bus_handler == SIG_IGN) {
2799              GC_err_printf0("Previously ignored bus error!?");
2800              GC_old_bus_handler = SIG_DFL;
2801       }
2802       if (GC_old_bus_handler != SIG_DFL) {
2803 #       ifdef PRINTSTATS
2804           GC_err_printf0("Replaced other SIGBUS handler\n");
2805 #       endif
2806       }
2807 #   endif /* HPUX || LINUX || HURD || (FREEBSD && SUNOS5SIGS) */
2808 #   if defined(MSWIN32)
2809       GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler);
2810       if (GC_old_segv_handler != NULL) {
2811 #       ifdef PRINTSTATS
2812           GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
2813 #       endif
2814       } else {
2815           GC_old_segv_handler = SIG_DFL;
2816       }
2817 #   endif
2818 }
2819 #endif /* !DARWIN */
2820
2821 int GC_incremental_protection_needs()
2822 {
2823     if (GC_page_size == HBLKSIZE) {
2824         return GC_PROTECTS_POINTER_HEAP;
2825     } else {
2826         return GC_PROTECTS_POINTER_HEAP | GC_PROTECTS_PTRFREE_HEAP;
2827     }
2828 }
2829
2830 #define HAVE_INCREMENTAL_PROTECTION_NEEDS
2831
2832 #define IS_PTRFREE(hhdr) ((hhdr)->hb_descr == 0)
2833
2834 #define PAGE_ALIGNED(x) !((word)(x) & (GC_page_size - 1))
2835 void GC_protect_heap()
2836 {
2837     ptr_t start;
2838     word len;
2839     struct hblk * current;
2840     struct hblk * current_start;  /* Start of block to be protected. */
2841     struct hblk * limit;
2842     unsigned i;
2843     GC_bool protect_all = 
2844           (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP));
2845     for (i = 0; i < GC_n_heap_sects; i++) {
2846         start = GC_heap_sects[i].hs_start;
2847         len = GC_heap_sects[i].hs_bytes;
2848         if (protect_all) {
2849           PROTECT(start, len);
2850         } else {
2851           GC_ASSERT(PAGE_ALIGNED(len))
2852           GC_ASSERT(PAGE_ALIGNED(start))
2853           current_start = current = (struct hblk *)start;
2854           limit = (struct hblk *)(start + len);
2855           while (current < limit) {
2856             hdr * hhdr;
2857             word nhblks;
2858             GC_bool is_ptrfree;
2859
2860             GC_ASSERT(PAGE_ALIGNED(current));
2861             GET_HDR(current, hhdr);
2862             if (IS_FORWARDING_ADDR_OR_NIL(hhdr)) {
2863               /* This can happen only if we're at the beginning of a    */
2864               /* heap segment, and a block spans heap segments.         */
2865               /* We will handle that block as part of the preceding     */
2866               /* segment.                                               */
2867               GC_ASSERT(current_start == current);
2868               current_start = ++current;
2869               continue;
2870             }
2871             if (HBLK_IS_FREE(hhdr)) {
2872               GC_ASSERT(PAGE_ALIGNED(hhdr -> hb_sz));
2873               nhblks = divHBLKSZ(hhdr -> hb_sz);
2874               is_ptrfree = TRUE;        /* dirty on alloc */
2875             } else {
2876               nhblks = OBJ_SZ_TO_BLOCKS(hhdr -> hb_sz);
2877               is_ptrfree = IS_PTRFREE(hhdr);
2878             }
2879             if (is_ptrfree) {
2880               if (current_start < current) {
2881                 PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
2882               }
2883               current_start = (current += nhblks);
2884             } else {
2885               current += nhblks;
2886             }
2887           } 
2888           if (current_start < current) {
2889             PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
2890           }
2891         }
2892     }
2893 }
2894
2895 /* We assume that either the world is stopped or its OK to lose dirty   */
2896 /* bits while this is happenning (as in GC_enable_incremental).         */
2897 void GC_read_dirty()
2898 {
2899     BCOPY((word *)GC_dirty_pages, GC_grungy_pages,
2900           (sizeof GC_dirty_pages));
2901     BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages));
2902     GC_protect_heap();
2903 }
2904
2905 GC_bool GC_page_was_dirty(h)
2906 struct hblk * h;
2907 {
2908     register word index = PHT_HASH(h);
2909     
2910     return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index));
2911 }
2912
2913 /*
2914  * Acquiring the allocation lock here is dangerous, since this
2915  * can be called from within GC_call_with_alloc_lock, and the cord
2916  * package does so.  On systems that allow nested lock acquisition, this
2917  * happens to work.
2918  * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
2919  */
2920
2921 static GC_bool syscall_acquired_lock = FALSE;   /* Protected by GC lock. */
2922  
2923 void GC_begin_syscall()
2924 {
2925     if (!I_HOLD_LOCK()) {
2926         LOCK();
2927         syscall_acquired_lock = TRUE;
2928     }
2929 }
2930
2931 void GC_end_syscall()
2932 {
2933     if (syscall_acquired_lock) {
2934         syscall_acquired_lock = FALSE;
2935         UNLOCK();
2936     }
2937 }
2938
2939 void GC_unprotect_range(addr, len)
2940 ptr_t addr;
2941 word len;
2942 {
2943     struct hblk * start_block;
2944     struct hblk * end_block;
2945     register struct hblk *h;
2946     ptr_t obj_start;
2947     
2948     if (!GC_dirty_maintained) return;
2949     obj_start = GC_base(addr);
2950     if (obj_start == 0) return;
2951     if (GC_base(addr + len - 1) != obj_start) {
2952         ABORT("GC_unprotect_range(range bigger than object)");
2953     }
2954     start_block = (struct hblk *)((word)addr & ~(GC_page_size - 1));
2955     end_block = (struct hblk *)((word)(addr + len - 1) & ~(GC_page_size - 1));
2956     end_block += GC_page_size/HBLKSIZE - 1;
2957     for (h = start_block; h <= end_block; h++) {
2958         register word index = PHT_HASH(h);
2959         
2960         async_set_pht_entry_from_index(GC_dirty_pages, index);
2961     }
2962     UNPROTECT(start_block,
2963               ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE);
2964 }
2965
2966 #if 0
2967
2968 /* We no longer wrap read by default, since that was causing too many   */
2969 /* problems.  It is preferred that the client instead avoids writing    */
2970 /* to the write-protected heap with a system call.                      */
2971 /* This still serves as sample code if you do want to wrap system calls.*/
2972
2973 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(GC_USE_LD_WRAP)
2974 /* Replacement for UNIX system call.                                      */
2975 /* Other calls that write to the heap should be handled similarly.        */
2976 /* Note that this doesn't work well for blocking reads:  It will hold     */
2977 /* the allocation lock for the entire duration of the call. Multithreaded */
2978 /* clients should really ensure that it won't block, either by setting    */
2979 /* the descriptor nonblocking, or by calling select or poll first, to     */
2980 /* make sure that input is available.                                     */
2981 /* Another, preferred alternative is to ensure that system calls never    */
2982 /* write to the protected heap (see above).                               */
2983 # if defined(__STDC__) && !defined(SUNOS4)
2984 #   include <unistd.h>
2985 #   include <sys/uio.h>
2986     ssize_t read(int fd, void *buf, size_t nbyte)
2987 # else
2988 #   ifndef LINT
2989       int read(fd, buf, nbyte)
2990 #   else
2991       int GC_read(fd, buf, nbyte)
2992 #   endif
2993     int fd;
2994     char *buf;
2995     int nbyte;
2996 # endif
2997 {
2998     int result;
2999     
3000     GC_begin_syscall();
3001     GC_unprotect_range(buf, (word)nbyte);
3002 #   if defined(IRIX5) || defined(GC_LINUX_THREADS)
3003         /* Indirect system call may not always be easily available.     */
3004         /* We could call _read, but that would interfere with the       */
3005         /* libpthread interception of read.                             */
3006         /* On Linux, we have to be careful with the linuxthreads        */
3007         /* read interception.                                           */
3008         {
3009             struct iovec iov;
3010
3011             iov.iov_base = buf;
3012             iov.iov_len = nbyte;
3013             result = readv(fd, &iov, 1);
3014         }
3015 #   else
3016 #     if defined(HURD)  
3017         result = __read(fd, buf, nbyte);
3018 #     else
3019         /* The two zero args at the end of this list are because one
3020            IA-64 syscall() implementation actually requires six args
3021            to be passed, even though they aren't always used. */
3022         result = syscall(SYS_read, fd, buf, nbyte, 0, 0);
3023 #     endif /* !HURD */
3024 #   endif
3025     GC_end_syscall();
3026     return(result);
3027 }
3028 #endif /* !MSWIN32 && !MSWINCE && !GC_LINUX_THREADS */
3029
3030 #if defined(GC_USE_LD_WRAP) && !defined(THREADS)
3031     /* We use the GNU ld call wrapping facility.                        */
3032     /* This requires that the linker be invoked with "--wrap read".     */
3033     /* This can be done by passing -Wl,"--wrap read" to gcc.            */
3034     /* I'm not sure that this actually wraps whatever version of read   */
3035     /* is called by stdio.  That code also mentions __read.             */
3036 #   include <unistd.h>
3037     ssize_t __wrap_read(int fd, void *buf, size_t nbyte)
3038     {
3039         int result;
3040
3041         GC_begin_syscall();
3042         GC_unprotect_range(buf, (word)nbyte);
3043         result = __real_read(fd, buf, nbyte);
3044         GC_end_syscall();
3045         return(result);
3046     }
3047
3048     /* We should probably also do this for __read, or whatever stdio    */
3049     /* actually calls.                                                  */
3050 #endif
3051
3052 #endif /* 0 */
3053
3054 /*ARGSUSED*/
3055 GC_bool GC_page_was_ever_dirty(h)
3056 struct hblk *h;
3057 {
3058     return(TRUE);
3059 }
3060
3061 /* Reset the n pages starting at h to "was never dirty" status. */
3062 /*ARGSUSED*/
3063 void GC_is_fresh(h, n)
3064 struct hblk *h;
3065 word n;
3066 {
3067 }
3068
3069 # endif /* MPROTECT_VDB */
3070
3071 # ifdef PROC_VDB
3072
3073 /*
3074  * See DEFAULT_VDB for interface descriptions.
3075  */
3076  
3077 /*
3078  * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
3079  * from which we can read page modified bits.  This facility is far from
3080  * optimal (e.g. we would like to get the info for only some of the
3081  * address space), but it avoids intercepting system calls.
3082  */
3083
3084 #include <errno.h>
3085 #include <sys/types.h>
3086 #include <sys/signal.h>
3087 #include <sys/fault.h>
3088 #include <sys/syscall.h>
3089 #include <sys/procfs.h>
3090 #include <sys/stat.h>
3091
3092 #define INITIAL_BUF_SZ 16384
3093 word GC_proc_buf_size = INITIAL_BUF_SZ;
3094 char *GC_proc_buf;
3095
3096 #ifdef GC_SOLARIS_THREADS
3097 /* We don't have exact sp values for threads.  So we count on   */
3098 /* occasionally declaring stack pages to be fresh.  Thus we     */
3099 /* need a real implementation of GC_is_fresh.  We can't clear   */
3100 /* entries in GC_written_pages, since that would declare all    */
3101 /* pages with the given hash address to be fresh.               */
3102 #   define MAX_FRESH_PAGES 8*1024       /* Must be power of 2 */
3103     struct hblk ** GC_fresh_pages;      /* A direct mapped cache.       */
3104                                         /* Collisions are dropped.      */
3105
3106 #   define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
3107 #   define ADD_FRESH_PAGE(h) \
3108         GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
3109 #   define PAGE_IS_FRESH(h) \
3110         (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
3111 #endif
3112
3113 /* Add all pages in pht2 to pht1 */
3114 void GC_or_pages(pht1, pht2)
3115 page_hash_table pht1, pht2;
3116 {
3117     register int i;
3118     
3119     for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
3120 }
3121
3122 int GC_proc_fd;
3123
3124 void GC_dirty_init()
3125 {
3126     int fd;
3127     char buf[30];
3128
3129     GC_dirty_maintained = TRUE;
3130     if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
3131         register int i;
3132     
3133         for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
3134 #       ifdef PRINTSTATS
3135             GC_printf1("Allocated words:%lu:all pages may have been written\n",
3136                        (unsigned long)
3137                                 (GC_words_allocd + GC_words_allocd_before_gc));
3138 #       endif       
3139     }
3140     sprintf(buf, "/proc/%d", getpid());
3141     fd = open(buf, O_RDONLY);
3142     if (fd < 0) {
3143         ABORT("/proc open failed");
3144     }
3145     GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
3146     close(fd);
3147     syscall(SYS_fcntl, GC_proc_fd, F_SETFD, FD_CLOEXEC);
3148     if (GC_proc_fd < 0) {
3149         ABORT("/proc ioctl failed");
3150     }
3151     GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size);
3152 #   ifdef GC_SOLARIS_THREADS
3153         GC_fresh_pages = (struct hblk **)
3154           GC_scratch_alloc(MAX_FRESH_PAGES * sizeof (struct hblk *));
3155         if (GC_fresh_pages == 0) {
3156             GC_err_printf0("No space for fresh pages\n");
3157             EXIT();
3158         }
3159         BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
3160 #   endif
3161 }
3162
3163 /* Ignore write hints. They don't help us here. */
3164 /*ARGSUSED*/
3165 void GC_remove_protection(h, nblocks, is_ptrfree)
3166 struct hblk *h;
3167 word nblocks;
3168 GC_bool is_ptrfree;
3169 {
3170 }
3171
3172 #ifdef GC_SOLARIS_THREADS
3173 #   define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
3174 #else
3175 #   define READ(fd,buf,nbytes) read(fd, buf, nbytes)
3176 #endif
3177
3178 void GC_read_dirty()
3179 {
3180     unsigned long ps, np;
3181     int nmaps;
3182     ptr_t vaddr;
3183     struct prasmap * map;
3184     char * bufp;
3185     ptr_t current_addr, limit;
3186     int i;
3187 int dummy;
3188
3189     BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
3190     
3191     bufp = GC_proc_buf;
3192     if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3193 #       ifdef PRINTSTATS
3194             GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
3195                        GC_proc_buf_size);
3196 #       endif       
3197         {
3198             /* Retry with larger buffer. */
3199             word new_size = 2 * GC_proc_buf_size;
3200             char * new_buf = GC_scratch_alloc(new_size);
3201             
3202             if (new_buf != 0) {
3203                 GC_proc_buf = bufp = new_buf;
3204                 GC_proc_buf_size = new_size;
3205             }
3206             if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3207                 WARN("Insufficient space for /proc read\n", 0);
3208                 /* Punt:        */
3209                 memset(GC_grungy_pages, 0xff, sizeof (page_hash_table));
3210                 memset(GC_written_pages, 0xff, sizeof(page_hash_table));
3211 #               ifdef GC_SOLARIS_THREADS
3212                     BZERO(GC_fresh_pages,
3213                           MAX_FRESH_PAGES * sizeof (struct hblk *)); 
3214 #               endif
3215                 return;
3216             }
3217         }
3218     }
3219     /* Copy dirty bits into GC_grungy_pages */
3220         nmaps = ((struct prpageheader *)bufp) -> pr_nmap;
3221         /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
3222                      nmaps, PG_REFERENCED, PG_MODIFIED); */
3223         bufp = bufp + sizeof(struct prpageheader);
3224         for (i = 0; i < nmaps; i++) {
3225             map = (struct prasmap *)bufp;
3226             vaddr = (ptr_t)(map -> pr_vaddr);
3227             ps = map -> pr_pagesize;
3228             np = map -> pr_npage;
3229             /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
3230             limit = vaddr + ps * np;
3231             bufp += sizeof (struct prasmap);
3232             for (current_addr = vaddr;
3233                  current_addr < limit; current_addr += ps){
3234                 if ((*bufp++) & PG_MODIFIED) {
3235                     register struct hblk * h = (struct hblk *) current_addr;
3236                     
3237                     while ((ptr_t)h < current_addr + ps) {
3238                         register word index = PHT_HASH(h);
3239                         
3240                         set_pht_entry_from_index(GC_grungy_pages, index);
3241 #                       ifdef GC_SOLARIS_THREADS
3242                           {
3243                             register int slot = FRESH_PAGE_SLOT(h);
3244                             
3245                             if (GC_fresh_pages[slot] == h) {
3246                                 GC_fresh_pages[slot] = 0;
3247                             }
3248                           }
3249 #                       endif
3250                         h++;
3251                     }
3252                 }
3253             }
3254             bufp += sizeof(long) - 1;
3255             bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1));
3256         }
3257     /* Update GC_written_pages. */
3258         GC_or_pages(GC_written_pages, GC_grungy_pages);
3259 #   ifdef GC_SOLARIS_THREADS
3260       /* Make sure that old stacks are considered completely clean      */
3261       /* unless written again.                                          */
3262         GC_old_stacks_are_fresh();
3263 #   endif
3264 }
3265
3266 #undef READ
3267
3268 GC_bool GC_page_was_dirty(h)
3269 struct hblk *h;
3270 {
3271     register word index = PHT_HASH(h);
3272     register GC_bool result;
3273     
3274     result = get_pht_entry_from_index(GC_grungy_pages, index);
3275 #   ifdef GC_SOLARIS_THREADS
3276         if (result && PAGE_IS_FRESH(h)) result = FALSE;
3277         /* This happens only if page was declared fresh since   */
3278         /* the read_dirty call, e.g. because it's in an unused  */
3279         /* thread stack.  It's OK to treat it as clean, in      */
3280         /* that case.  And it's consistent with                 */
3281         /* GC_page_was_ever_dirty.                              */
3282 #   endif
3283     return(result);
3284 }
3285
3286 GC_bool GC_page_was_ever_dirty(h)
3287 struct hblk *h;
3288 {
3289     register word index = PHT_HASH(h);
3290     register GC_bool result;
3291     
3292     result = get_pht_entry_from_index(GC_written_pages, index);
3293 #   ifdef GC_SOLARIS_THREADS
3294         if (result && PAGE_IS_FRESH(h)) result = FALSE;
3295 #   endif
3296     return(result);
3297 }
3298
3299 /* Caller holds allocation lock.        */
3300 void GC_is_fresh(h, n)
3301 struct hblk *h;
3302 word n;
3303 {
3304
3305     register word index;
3306     
3307 #   ifdef GC_SOLARIS_THREADS
3308       register word i;
3309       
3310       if (GC_fresh_pages != 0) {
3311         for (i = 0; i < n; i++) {
3312           ADD_FRESH_PAGE(h + i);
3313         }
3314       }
3315 #   endif
3316 }
3317
3318 # endif /* PROC_VDB */
3319
3320
3321 # ifdef PCR_VDB
3322
3323 # include "vd/PCR_VD.h"
3324
3325 # define NPAGES (32*1024)       /* 128 MB */
3326
3327 PCR_VD_DB  GC_grungy_bits[NPAGES];
3328
3329 ptr_t GC_vd_base;       /* Address corresponding to GC_grungy_bits[0]   */
3330                         /* HBLKSIZE aligned.                            */
3331
3332 void GC_dirty_init()
3333 {
3334     GC_dirty_maintained = TRUE;
3335     /* For the time being, we assume the heap generally grows up */
3336     GC_vd_base = GC_heap_sects[0].hs_start;
3337     if (GC_vd_base == 0) {
3338         ABORT("Bad initial heap segment");
3339     }
3340     if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE)
3341         != PCR_ERes_okay) {
3342         ABORT("dirty bit initialization failed");
3343     }
3344 }
3345
3346 void GC_read_dirty()
3347 {
3348     /* lazily enable dirty bits on newly added heap sects */
3349     {
3350         static int onhs = 0;
3351         int nhs = GC_n_heap_sects;
3352         for( ; onhs < nhs; onhs++ ) {
3353             PCR_VD_WriteProtectEnable(
3354                     GC_heap_sects[onhs].hs_start,
3355                     GC_heap_sects[onhs].hs_bytes );
3356         }
3357     }
3358
3359
3360     if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits)
3361         != PCR_ERes_okay) {
3362         ABORT("dirty bit read failed");
3363     }
3364 }
3365
3366 GC_bool GC_page_was_dirty(h)
3367 struct hblk *h;
3368 {
3369     if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
3370         return(TRUE);
3371     }
3372     return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
3373 }
3374
3375 /*ARGSUSED*/
3376 void GC_remove_protection(h, nblocks, is_ptrfree)
3377 struct hblk *h;
3378 word nblocks;
3379 GC_bool is_ptrfree;
3380 {
3381     PCR_VD_WriteProtectDisable(h, nblocks*HBLKSIZE);
3382     PCR_VD_WriteProtectEnable(h, nblocks*HBLKSIZE);
3383 }
3384
3385 # endif /* PCR_VDB */
3386
3387 #if defined(MPROTECT_VDB) && defined(DARWIN)
3388 /* The following sources were used as a *reference* for this exception handling
3389    code:
3390       1. Apple's mach/xnu documentation
3391       2. Timothy J. Wood's "Mach Exception Handlers 101" post to the
3392          omnigroup's macosx-dev list. 
3393          www.omnigroup.com/mailman/archive/macosx-dev/2000-June/002030.html
3394       3. macosx-nat.c from Apple's GDB source code.
3395 */
3396    
3397 /* The bug that caused all this trouble should now be fixed. This should
3398    eventually be removed if all goes well. */
3399 /* define BROKEN_EXCEPTION_HANDLING */
3400     
3401 #include <mach/mach.h>
3402 #include <mach/mach_error.h>
3403 #include <mach/thread_status.h>
3404 #include <mach/exception.h>
3405 #include <mach/task.h>
3406 #include <pthread.h>
3407
3408 /* These are not defined in any header, although they are documented */
3409 extern boolean_t exc_server(mach_msg_header_t *,mach_msg_header_t *);
3410 extern kern_return_t exception_raise(
3411     mach_port_t,mach_port_t,mach_port_t,
3412     exception_type_t,exception_data_t,mach_msg_type_number_t);
3413 extern kern_return_t exception_raise_state(
3414     mach_port_t,mach_port_t,mach_port_t,
3415     exception_type_t,exception_data_t,mach_msg_type_number_t,
3416     thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3417     thread_state_t,mach_msg_type_number_t*);
3418 extern kern_return_t exception_raise_state_identity(
3419     mach_port_t,mach_port_t,mach_port_t,
3420     exception_type_t,exception_data_t,mach_msg_type_number_t,
3421     thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3422     thread_state_t,mach_msg_type_number_t*);
3423
3424
3425 #define MAX_EXCEPTION_PORTS 16
3426
3427 static struct {
3428     mach_msg_type_number_t count;
3429     exception_mask_t      masks[MAX_EXCEPTION_PORTS];
3430     exception_handler_t   ports[MAX_EXCEPTION_PORTS];
3431     exception_behavior_t  behaviors[MAX_EXCEPTION_PORTS];
3432     thread_state_flavor_t flavors[MAX_EXCEPTION_PORTS];
3433 } GC_old_exc_ports;
3434
3435 static struct {
3436     mach_port_t exception;
3437 #if defined(THREADS)
3438     mach_port_t reply;
3439 #endif
3440 } GC_ports;
3441
3442 typedef struct {
3443     mach_msg_header_t head;
3444 } GC_msg_t;
3445
3446 typedef enum {
3447     GC_MP_NORMAL, GC_MP_DISCARDING, GC_MP_STOPPED
3448 } GC_mprotect_state_t;
3449
3450 /* FIXME: 1 and 2 seem to be safe to use in the msgh_id field,
3451    but it isn't  documented. Use the source and see if they
3452    should be ok. */
3453 #define ID_STOP 1
3454 #define ID_RESUME 2
3455
3456 /* These values are only used on the reply port */
3457 #define ID_ACK 3
3458
3459 #if defined(THREADS)
3460
3461 GC_mprotect_state_t GC_mprotect_state;
3462
3463 /* The following should ONLY be called when the world is stopped  */
3464 static void GC_mprotect_thread_notify(mach_msg_id_t id) {
3465     struct {
3466         GC_msg_t msg;
3467         mach_msg_trailer_t trailer;
3468     } buf;
3469     mach_msg_return_t r;
3470     /* remote, local */
3471     buf.msg.head.msgh_bits = 
3472         MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3473     buf.msg.head.msgh_size = sizeof(buf.msg);
3474     buf.msg.head.msgh_remote_port = GC_ports.exception;
3475     buf.msg.head.msgh_local_port = MACH_PORT_NULL;
3476     buf.msg.head.msgh_id = id;
3477             
3478     r = mach_msg(
3479         &buf.msg.head,
3480         MACH_SEND_MSG|MACH_RCV_MSG|MACH_RCV_LARGE,
3481         sizeof(buf.msg),
3482         sizeof(buf),
3483         GC_ports.reply,
3484         MACH_MSG_TIMEOUT_NONE,
3485         MACH_PORT_NULL);
3486     if(r != MACH_MSG_SUCCESS)
3487         ABORT("mach_msg failed in GC_mprotect_thread_notify");
3488     if(buf.msg.head.msgh_id != ID_ACK)
3489         ABORT("invalid ack in GC_mprotect_thread_notify");
3490 }
3491
3492 /* Should only be called by the mprotect thread */
3493 static void GC_mprotect_thread_reply() {
3494     GC_msg_t msg;
3495     mach_msg_return_t r;
3496     /* remote, local */
3497     msg.head.msgh_bits = 
3498         MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3499     msg.head.msgh_size = sizeof(msg);
3500     msg.head.msgh_remote_port = GC_ports.reply;
3501     msg.head.msgh_local_port = MACH_PORT_NULL;
3502     msg.head.msgh_id = ID_ACK;
3503             
3504     r = mach_msg(
3505         &msg.head,
3506         MACH_SEND_MSG,
3507         sizeof(msg),
3508         0,
3509         MACH_PORT_NULL,
3510         MACH_MSG_TIMEOUT_NONE,
3511         MACH_PORT_NULL);
3512     if(r != MACH_MSG_SUCCESS)
3513         ABORT("mach_msg failed in GC_mprotect_thread_reply");
3514 }
3515
3516 void GC_mprotect_stop() {
3517     GC_mprotect_thread_notify(ID_STOP);
3518 }
3519 void GC_mprotect_resume() {
3520     GC_mprotect_thread_notify(ID_RESUME);
3521 }
3522
3523 #else /* !THREADS */
3524 /* The compiler should optimize away any GC_mprotect_state computations */
3525 #define GC_mprotect_state GC_MP_NORMAL
3526 #endif
3527
3528 static void *GC_mprotect_thread(void *arg) {
3529     mach_msg_return_t r;
3530     /* These two structures contain some private kernel data. We don't need to
3531        access any of it so we don't bother defining a proper struct. The
3532        correct definitions are in the xnu source code. */
3533     struct {
3534         mach_msg_header_t head;
3535         char data[256];
3536     } reply;
3537     struct {
3538         mach_msg_header_t head;
3539         mach_msg_body_t msgh_body;
3540         char data[1024];
3541     } msg;
3542
3543     mach_msg_id_t id;
3544
3545     GC_darwin_register_mach_handler_thread(mach_thread_self());
3546     
3547     for(;;) {
3548         r = mach_msg(
3549             &msg.head,
3550             MACH_RCV_MSG|MACH_RCV_LARGE|
3551                 (GC_mprotect_state == GC_MP_DISCARDING ? MACH_RCV_TIMEOUT : 0),
3552             0,
3553             sizeof(msg),
3554             GC_ports.exception,
3555             GC_mprotect_state == GC_MP_DISCARDING ? 0 : MACH_MSG_TIMEOUT_NONE,
3556             MACH_PORT_NULL);
3557         
3558         id = r == MACH_MSG_SUCCESS ? msg.head.msgh_id : -1;
3559         
3560 #if defined(THREADS)
3561         if(GC_mprotect_state == GC_MP_DISCARDING) {
3562             if(r == MACH_RCV_TIMED_OUT) {
3563                 GC_mprotect_state = GC_MP_STOPPED;
3564                 GC_mprotect_thread_reply();
3565                 continue;
3566             }
3567             if(r == MACH_MSG_SUCCESS && (id == ID_STOP || id == ID_RESUME))
3568                 ABORT("out of order mprotect thread request");
3569         }
3570 #endif
3571         
3572         if(r != MACH_MSG_SUCCESS) {
3573             GC_err_printf2("mach_msg failed with %d %s\n", 
3574                 (int)r,mach_error_string(r));
3575             ABORT("mach_msg failed");
3576         }
3577         
3578         switch(id) {
3579 #if defined(THREADS)
3580             case ID_STOP:
3581                 if(GC_mprotect_state != GC_MP_NORMAL)
3582                     ABORT("Called mprotect_stop when state wasn't normal");
3583                 GC_mprotect_state = GC_MP_DISCARDING;
3584                 break;
3585             case ID_RESUME:
3586                 if(GC_mprotect_state != GC_MP_STOPPED)
3587                     ABORT("Called mprotect_resume when state wasn't stopped");
3588                 GC_mprotect_state = GC_MP_NORMAL;
3589                 GC_mprotect_thread_reply();
3590                 break;
3591 #endif /* THREADS */
3592             default:
3593                     /* Handle the message (calls catch_exception_raise) */
3594                 if(!exc_server(&msg.head,&reply.head))
3595                     ABORT("exc_server failed");
3596                 /* Send the reply */
3597                 r = mach_msg(
3598                     &reply.head,
3599                     MACH_SEND_MSG,
3600                     reply.head.msgh_size,
3601                     0,
3602                     MACH_PORT_NULL,
3603                     MACH_MSG_TIMEOUT_NONE,
3604                     MACH_PORT_NULL);
3605                 if(r != MACH_MSG_SUCCESS) {
3606                         /* This will fail if the thread dies, but the thread shouldn't
3607                            die... */
3608                         #ifdef BROKEN_EXCEPTION_HANDLING
3609                         GC_err_printf2(
3610                         "mach_msg failed with %d %s while sending exc reply\n",
3611                         (int)r,mach_error_string(r));
3612                 #else
3613                         ABORT("mach_msg failed while sending exception reply");
3614                 #endif
3615                 }
3616         } /* switch */
3617     } /* for(;;) */
3618     /* NOT REACHED */
3619     return NULL;
3620 }
3621
3622 /* All this SIGBUS code shouldn't be necessary. All protection faults should
3623    be going throught the mach exception handler. However, it seems a SIGBUS is
3624    occasionally sent for some unknown reason. Even more odd, it seems to be
3625    meaningless and safe to ignore. */
3626 #ifdef BROKEN_EXCEPTION_HANDLING
3627
3628 typedef void (* SIG_PF)();
3629 static SIG_PF GC_old_bus_handler;
3630
3631 /* Updates to this aren't atomic, but the SIGBUSs seem pretty rare.
3632    Even if this doesn't get updated property, it isn't really a problem */
3633 static int GC_sigbus_count;
3634
3635 static void GC_darwin_sigbus(int num,siginfo_t *sip,void *context) {
3636     if(num != SIGBUS) ABORT("Got a non-sigbus signal in the sigbus handler");
3637     
3638     /* Ugh... some seem safe to ignore, but too many in a row probably means
3639        trouble. GC_sigbus_count is reset for each mach exception that is
3640        handled */
3641     if(GC_sigbus_count >= 8) {
3642         ABORT("Got more than 8 SIGBUSs in a row!");
3643     } else {
3644         GC_sigbus_count++;
3645         GC_err_printf0("GC: WARNING: Ignoring SIGBUS.\n");
3646     }
3647 }
3648 #endif /* BROKEN_EXCEPTION_HANDLING */
3649
3650 void GC_dirty_init() {
3651     kern_return_t r;
3652     mach_port_t me;
3653     pthread_t thread;
3654     pthread_attr_t attr;
3655     exception_mask_t mask;
3656     
3657 #   ifdef PRINTSTATS
3658         GC_printf0("Inititalizing mach/darwin mprotect virtual dirty bit "
3659             "implementation\n");
3660 #   endif  
3661 #       ifdef BROKEN_EXCEPTION_HANDLING
3662         GC_err_printf0("GC: WARNING: Enabling workarounds for various darwin "
3663             "exception handling bugs.\n");
3664 #       endif
3665     GC_dirty_maintained = TRUE;
3666     if (GC_page_size % HBLKSIZE != 0) {
3667         GC_err_printf0("Page size not multiple of HBLKSIZE\n");
3668         ABORT("Page size not multiple of HBLKSIZE");
3669     }
3670     
3671     GC_task_self = me = mach_task_self();
3672     
3673     r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.exception);
3674     if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (exception port)");
3675     
3676     r = mach_port_insert_right(me,GC_ports.exception,GC_ports.exception,
3677         MACH_MSG_TYPE_MAKE_SEND);
3678     if(r != KERN_SUCCESS)
3679         ABORT("mach_port_insert_right failed (exception port)");
3680
3681     #if defined(THREADS)
3682         r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.reply);
3683         if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (reply port)");
3684     #endif
3685
3686     /* The exceptions we want to catch */  
3687     mask = EXC_MASK_BAD_ACCESS;
3688
3689     r = task_get_exception_ports(
3690         me,
3691         mask,
3692         GC_old_exc_ports.masks,
3693         &GC_old_exc_ports.count,
3694         GC_old_exc_ports.ports,
3695         GC_old_exc_ports.behaviors,
3696         GC_old_exc_ports.flavors
3697     );
3698     if(r != KERN_SUCCESS) ABORT("task_get_exception_ports failed");
3699         
3700     r = task_set_exception_ports(
3701         me,
3702         mask,
3703         GC_ports.exception,
3704         EXCEPTION_DEFAULT,
3705         MACHINE_THREAD_STATE
3706     );
3707     if(r != KERN_SUCCESS) ABORT("task_set_exception_ports failed");
3708
3709     if(pthread_attr_init(&attr) != 0) ABORT("pthread_attr_init failed");
3710     if(pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED) != 0) 
3711         ABORT("pthread_attr_setdetachedstate failed");
3712
3713 #       undef pthread_create
3714     /* This will call the real pthread function, not our wrapper */
3715     if(pthread_create(&thread,&attr,GC_mprotect_thread,NULL) != 0)
3716         ABORT("pthread_create failed");
3717     pthread_attr_destroy(&attr);
3718     
3719     /* Setup the sigbus handler for ignoring the meaningless SIGBUSs */
3720     #ifdef BROKEN_EXCEPTION_HANDLING 
3721     {
3722         struct sigaction sa, oldsa;
3723         sa.sa_handler = (SIG_PF)GC_darwin_sigbus;
3724         sigemptyset(&sa.sa_mask);
3725         sa.sa_flags = SA_RESTART|SA_SIGINFO;
3726         if(sigaction(SIGBUS,&sa,&oldsa) < 0) ABORT("sigaction");
3727         GC_old_bus_handler = (SIG_PF)oldsa.sa_handler;
3728         if (GC_old_bus_handler != SIG_DFL) {
3729 #               ifdef PRINTSTATS
3730                 GC_err_printf0("Replaced other SIGBUS handler\n");
3731 #               endif
3732         }
3733     }
3734     #endif /* BROKEN_EXCEPTION_HANDLING  */
3735 }
3736  
3737 /* The source code for Apple's GDB was used as a reference for the exception
3738    forwarding code. This code is similar to be GDB code only because there is 
3739    only one way to do it. */
3740 static kern_return_t GC_forward_exception(
3741         mach_port_t thread,
3742         mach_port_t task,
3743         exception_type_t exception,
3744         exception_data_t data,
3745         mach_msg_type_number_t data_count
3746 ) {
3747     int i;
3748     kern_return_t r;
3749     mach_port_t port;
3750     exception_behavior_t behavior;
3751     thread_state_flavor_t flavor;
3752     
3753     thread_state_t thread_state;
3754     mach_msg_type_number_t thread_state_count = THREAD_STATE_MAX;
3755         
3756     for(i=0;i<GC_old_exc_ports.count;i++)
3757         if(GC_old_exc_ports.masks[i] & (1 << exception))
3758             break;
3759     if(i==GC_old_exc_ports.count) ABORT("No handler for exception!");
3760     
3761     port = GC_old_exc_ports.ports[i];
3762     behavior = GC_old_exc_ports.behaviors[i];
3763     flavor = GC_old_exc_ports.flavors[i];
3764
3765     if(behavior != EXCEPTION_DEFAULT) {
3766         r = thread_get_state(thread,flavor,thread_state,&thread_state_count);
3767         if(r != KERN_SUCCESS)
3768             ABORT("thread_get_state failed in forward_exception");
3769     }
3770     
3771     switch(behavior) {
3772         case EXCEPTION_DEFAULT:
3773             r = exception_raise(port,thread,task,exception,data,data_count);
3774             break;
3775         case EXCEPTION_STATE:
3776             r = exception_raise_state(port,thread,task,exception,data,
3777                 data_count,&flavor,thread_state,thread_state_count,
3778                 thread_state,&thread_state_count);
3779             break;
3780         case EXCEPTION_STATE_IDENTITY:
3781             r = exception_raise_state_identity(port,thread,task,exception,data,
3782                 data_count,&flavor,thread_state,thread_state_count,
3783                 thread_state,&thread_state_count);
3784             break;
3785         default:
3786             r = KERN_FAILURE; /* make gcc happy */
3787             ABORT("forward_exception: unknown behavior");
3788             break;
3789     }
3790     
3791     if(behavior != EXCEPTION_DEFAULT) {
3792         r = thread_set_state(thread,flavor,thread_state,thread_state_count);
3793         if(r != KERN_SUCCESS)
3794             ABORT("thread_set_state failed in forward_exception");
3795     }
3796     
3797     return r;
3798 }
3799
3800 #define FWD() GC_forward_exception(thread,task,exception,code,code_count)
3801
3802 /* This violates the namespace rules but there isn't anything that can be done
3803    about it. The exception handling stuff is hard coded to call this */
3804 kern_return_t
3805 catch_exception_raise(
3806    mach_port_t exception_port,mach_port_t thread,mach_port_t task,
3807    exception_type_t exception,exception_data_t code,
3808    mach_msg_type_number_t code_count
3809 ) {
3810     kern_return_t r;
3811     char *addr;
3812     struct hblk *h;
3813     int i;
3814 #   if defined(POWERPC)
3815 #     if CPP_WORDSZ == 32
3816         thread_state_flavor_t flavor = PPC_EXCEPTION_STATE;
3817         mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE_COUNT;
3818         ppc_exception_state_t exc_state;
3819 #     else
3820         thread_state_flavor_t flavor = PPC_EXCEPTION_STATE64;
3821         mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE64_COUNT;
3822         ppc_exception_state64_t exc_state;
3823 #     endif
3824 #   elif defined(I386)
3825         thread_state_flavor_t flavor = i386_EXCEPTION_STATE;
3826         mach_msg_type_number_t exc_state_count = i386_EXCEPTION_STATE_COUNT;
3827         i386_exception_state_t exc_state;
3828 #   else
3829 #       error FIXME for non-ppc darwin
3830 #   endif
3831
3832     
3833     if(exception != EXC_BAD_ACCESS || code[0] != KERN_PROTECTION_FAILURE) {
3834         #ifdef DEBUG_EXCEPTION_HANDLING
3835         /* We aren't interested, pass it on to the old handler */
3836         GC_printf3("Exception: 0x%x Code: 0x%x 0x%x in catch....\n",
3837             exception,
3838             code_count > 0 ? code[0] : -1,
3839             code_count > 1 ? code[1] : -1); 
3840         #endif
3841         return FWD();
3842     }
3843
3844     r = thread_get_state(thread,flavor,
3845         (natural_t*)&exc_state,&exc_state_count);
3846     if(r != KERN_SUCCESS) {
3847         /* The thread is supposed to be suspended while the exception handler
3848            is called. This shouldn't fail. */
3849         #ifdef BROKEN_EXCEPTION_HANDLING
3850             GC_err_printf0("thread_get_state failed in "
3851                 "catch_exception_raise\n");
3852             return KERN_SUCCESS;
3853         #else
3854             ABORT("thread_get_state failed in catch_exception_raise");
3855         #endif
3856     }
3857     
3858     /* This is the address that caused the fault */
3859 #if defined(POWERPC)
3860     addr = (char*) exc_state.dar;
3861 #elif defined (I386)
3862     addr = (char*) exc_state.faultvaddr;
3863 #else
3864 #   error FIXME for non POWERPC/I386
3865 #endif
3866         
3867     if((HDR(addr)) == 0) {
3868         /* Ugh... just like the SIGBUS problem above, it seems we get a bogus 
3869            KERN_PROTECTION_FAILURE every once and a while. We wait till we get
3870            a bunch in a row before doing anything about it. If a "real" fault 
3871            ever occurres it'll just keep faulting over and over and we'll hit
3872            the limit pretty quickly. */
3873         #ifdef BROKEN_EXCEPTION_HANDLING
3874             static char *last_fault;
3875             static int last_fault_count;
3876             
3877             if(addr != last_fault) {
3878                 last_fault = addr;
3879                 last_fault_count = 0;
3880             }
3881             if(++last_fault_count < 32) {
3882                 if(last_fault_count == 1)
3883                     GC_err_printf1(
3884                         "GC: WARNING: Ignoring KERN_PROTECTION_FAILURE at %p\n",
3885                         addr);
3886                 return KERN_SUCCESS;
3887             }
3888             
3889             GC_err_printf1("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr);
3890             /* Can't pass it along to the signal handler because that is
3891                ignoring SIGBUS signals. We also shouldn't call ABORT here as
3892                signals don't always work too well from the exception handler. */
3893             GC_err_printf0("Aborting\n");
3894             exit(EXIT_FAILURE);
3895         #else /* BROKEN_EXCEPTION_HANDLING */
3896             /* Pass it along to the next exception handler 
3897                (which should call SIGBUS/SIGSEGV) */
3898             return FWD();
3899         #endif /* !BROKEN_EXCEPTION_HANDLING */
3900     }
3901
3902     #ifdef BROKEN_EXCEPTION_HANDLING
3903         /* Reset the number of consecutive SIGBUSs */
3904         GC_sigbus_count = 0;
3905     #endif
3906     
3907     if(GC_mprotect_state == GC_MP_NORMAL) { /* common case */
3908         h = (struct hblk*)((word)addr & ~(GC_page_size-1));
3909         UNPROTECT(h, GC_page_size);     
3910         for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
3911             register int index = PHT_HASH(h+i);
3912             async_set_pht_entry_from_index(GC_dirty_pages, index);
3913         }
3914     } else if(GC_mprotect_state == GC_MP_DISCARDING) {
3915         /* Lie to the thread for now. No sense UNPROTECT()ing the memory
3916            when we're just going to PROTECT() it again later. The thread
3917            will just fault again once it resumes */
3918     } else {
3919         /* Shouldn't happen, i don't think */
3920         GC_printf0("KERN_PROTECTION_FAILURE while world is stopped\n");
3921         return FWD();
3922     }
3923     return KERN_SUCCESS;
3924 }
3925 #undef FWD
3926
3927 /* These should never be called, but just in case...  */
3928 kern_return_t catch_exception_raise_state(mach_port_name_t exception_port,
3929     int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
3930     int flavor, thread_state_t old_state, int old_stateCnt,
3931     thread_state_t new_state, int new_stateCnt)
3932 {
3933     ABORT("catch_exception_raise_state");
3934     return(KERN_INVALID_ARGUMENT);
3935 }
3936 kern_return_t catch_exception_raise_state_identity(
3937     mach_port_name_t exception_port, mach_port_t thread, mach_port_t task,
3938     int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
3939     int flavor, thread_state_t old_state, int old_stateCnt, 
3940     thread_state_t new_state, int new_stateCnt)
3941 {
3942     ABORT("catch_exception_raise_state_identity");
3943     return(KERN_INVALID_ARGUMENT);
3944 }
3945
3946
3947 #endif /* DARWIN && MPROTECT_VDB */
3948
3949 # ifndef HAVE_INCREMENTAL_PROTECTION_NEEDS
3950   int GC_incremental_protection_needs()
3951   {
3952     return GC_PROTECTS_NONE;
3953   }
3954 # endif /* !HAVE_INCREMENTAL_PROTECTION_NEEDS */
3955
3956 /*
3957  * Call stack save code for debugging.
3958  * Should probably be in mach_dep.c, but that requires reorganization.
3959  */
3960
3961 /* I suspect the following works for most X86 *nix variants, so         */
3962 /* long as the frame pointer is explicitly stored.  In the case of gcc, */
3963 /* compiler flags (e.g. -fomit-frame-pointer) determine whether it is.  */
3964 #if defined(I386) && defined(LINUX) && defined(SAVE_CALL_CHAIN)
3965 #   include <features.h>
3966
3967     struct frame {
3968         struct frame *fr_savfp;
3969         long    fr_savpc;
3970         long    fr_arg[NARGS];  /* All the arguments go here.   */
3971     };
3972 #endif
3973
3974 #if defined(SPARC)
3975 #  if defined(LINUX)
3976 #    include <features.h>
3977
3978      struct frame {
3979         long    fr_local[8];
3980         long    fr_arg[6];
3981         struct frame *fr_savfp;
3982         long    fr_savpc;
3983 #       ifndef __arch64__
3984           char  *fr_stret;
3985 #       endif
3986         long    fr_argd[6];
3987         long    fr_argx[0];
3988      };
3989 #  else
3990 #    if defined(SUNOS4)
3991 #      include <machine/frame.h>
3992 #    else
3993 #      if defined (DRSNX)
3994 #        include <sys/sparc/frame.h>
3995 #      else
3996 #        if defined(OPENBSD)
3997 #          include <frame.h>
3998 #        else
3999 #          if defined(FREEBSD) || defined(NETBSD)
4000 #            include <machine/frame.h>
4001 #          else
4002 #            include <sys/frame.h>
4003 #          endif
4004 #        endif
4005 #      endif
4006 #    endif
4007 #  endif
4008 #  if NARGS > 6
4009         --> We only know how to to get the first 6 arguments
4010 #  endif
4011 #endif /* SPARC */
4012
4013 #ifdef  NEED_CALLINFO
4014 /* Fill in the pc and argument information for up to NFRAMES of my      */
4015 /* callers.  Ignore my frame and my callers frame.                      */
4016
4017 #ifdef LINUX
4018 #   include <unistd.h>
4019 #endif
4020
4021 #endif /* NEED_CALLINFO */
4022
4023 #if defined(GC_HAVE_BUILTIN_BACKTRACE)
4024 # include <execinfo.h>
4025 #endif
4026
4027 #ifdef SAVE_CALL_CHAIN
4028
4029 #if NARGS == 0 && NFRAMES % 2 == 0 /* No padding */ \
4030     && defined(GC_HAVE_BUILTIN_BACKTRACE)
4031
4032 #ifdef REDIRECT_MALLOC
4033   /* Deal with possible malloc calls in backtrace by omitting   */
4034   /* the infinitely recursing backtrace.                        */
4035 # ifdef THREADS
4036     __thread    /* If your compiler doesn't understand this */
4037                 /* you could use something like pthread_getspecific.    */
4038 # endif
4039   GC_in_save_callers = FALSE;
4040 #endif
4041
4042 void GC_save_callers (info) 
4043 struct callinfo info[NFRAMES];
4044 {
4045   void * tmp_info[NFRAMES + 1];
4046   int npcs, i;
4047 # define IGNORE_FRAMES 1
4048   
4049   /* We retrieve NFRAMES+1 pc values, but discard the first, since it   */
4050   /* points to our own frame.                                           */
4051 # ifdef REDIRECT_MALLOC
4052     if (GC_in_save_callers) {
4053       info[0].ci_pc = (word)(&GC_save_callers);
4054       for (i = 1; i < NFRAMES; ++i) info[i].ci_pc = 0;
4055       return;
4056     }
4057     GC_in_save_callers = TRUE;
4058 # endif
4059   GC_ASSERT(sizeof(struct callinfo) == sizeof(void *));
4060   npcs = backtrace((void **)tmp_info, NFRAMES + IGNORE_FRAMES);
4061   BCOPY(tmp_info+IGNORE_FRAMES, info, (npcs - IGNORE_FRAMES) * sizeof(void *));
4062   for (i = npcs - IGNORE_FRAMES; i < NFRAMES; ++i) info[i].ci_pc = 0;
4063 # ifdef REDIRECT_MALLOC
4064     GC_in_save_callers = FALSE;
4065 # endif
4066 }
4067
4068 #else /* No builtin backtrace; do it ourselves */
4069
4070 #if (defined(OPENBSD) || defined(NETBSD) || defined(FREEBSD)) && defined(SPARC)
4071 #  define FR_SAVFP fr_fp
4072 #  define FR_SAVPC fr_pc
4073 #else
4074 #  define FR_SAVFP fr_savfp
4075 #  define FR_SAVPC fr_savpc
4076 #endif
4077
4078 #if defined(SPARC) && (defined(__arch64__) || defined(__sparcv9))
4079 #   define BIAS 2047
4080 #else
4081 #   define BIAS 0
4082 #endif
4083
4084 void GC_save_callers (info) 
4085 struct callinfo info[NFRAMES];
4086 {
4087   struct frame *frame;
4088   struct frame *fp;
4089   int nframes = 0;
4090 # ifdef I386
4091     /* We assume this is turned on only with gcc as the compiler. */
4092     asm("movl %%ebp,%0" : "=r"(frame));
4093     fp = frame;
4094 # else
4095     frame = (struct frame *) GC_save_regs_in_stack ();
4096     fp = (struct frame *)((long) frame -> FR_SAVFP + BIAS);
4097 #endif
4098   
4099    for (; (!(fp HOTTER_THAN frame) && !(GC_stackbottom HOTTER_THAN (ptr_t)fp)
4100            && (nframes < NFRAMES));
4101        fp = (struct frame *)((long) fp -> FR_SAVFP + BIAS), nframes++) {
4102       register int i;
4103       
4104       info[nframes].ci_pc = fp->FR_SAVPC;
4105 #     if NARGS > 0
4106         for (i = 0; i < NARGS; i++) {
4107           info[nframes].ci_arg[i] = ~(fp->fr_arg[i]);
4108         }
4109 #     endif /* NARGS > 0 */
4110   }
4111   if (nframes < NFRAMES) info[nframes].ci_pc = 0;
4112 }
4113
4114 #endif /* No builtin backtrace */
4115
4116 #endif /* SAVE_CALL_CHAIN */
4117
4118 #ifdef NEED_CALLINFO
4119
4120 /* Print info to stderr.  We do NOT hold the allocation lock */
4121 void GC_print_callers (info)
4122 struct callinfo info[NFRAMES];
4123 {
4124     register int i;
4125     static int reentry_count = 0;
4126     GC_bool stop = FALSE;
4127
4128     /* FIXME: This should probably use a different lock, so that we     */
4129     /* become callable with or without the allocation lock.             */
4130     LOCK();
4131       ++reentry_count;
4132     UNLOCK();
4133     
4134 #   if NFRAMES == 1
4135       GC_err_printf0("\tCaller at allocation:\n");
4136 #   else
4137       GC_err_printf0("\tCall chain at allocation:\n");
4138 #   endif
4139     for (i = 0; i < NFRAMES && !stop ; i++) {
4140         if (info[i].ci_pc == 0) break;
4141 #       if NARGS > 0
4142         {
4143           int j;
4144
4145           GC_err_printf0("\t\targs: ");
4146           for (j = 0; j < NARGS; j++) {
4147             if (j != 0) GC_err_printf0(", ");
4148             GC_err_printf2("%d (0x%X)", ~(info[i].ci_arg[j]),
4149                                         ~(info[i].ci_arg[j]));
4150           }
4151           GC_err_printf0("\n");
4152         }
4153 #       endif
4154         if (reentry_count > 1) {
4155             /* We were called during an allocation during       */
4156             /* a previous GC_print_callers call; punt.          */
4157             GC_err_printf1("\t\t##PC##= 0x%lx\n", info[i].ci_pc);
4158             continue;
4159         }
4160         {
4161 #         ifdef LINUX
4162             FILE *pipe;
4163 #         endif
4164 #         if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4165              && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4166             char **sym_name =
4167               backtrace_symbols((void **)(&(info[i].ci_pc)), 1);
4168             char *name = sym_name[0];
4169 #         else
4170             char buf[40];
4171             char *name = buf;
4172             sprintf(buf, "##PC##= 0x%lx", info[i].ci_pc);
4173 #         endif
4174 #         if defined(LINUX) && !defined(SMALL_CONFIG)
4175             /* Try for a line number. */
4176             {
4177 #               define EXE_SZ 100
4178                 static char exe_name[EXE_SZ];
4179 #               define CMD_SZ 200
4180                 char cmd_buf[CMD_SZ];
4181 #               define RESULT_SZ 200
4182                 static char result_buf[RESULT_SZ];
4183                 size_t result_len;
4184                 char *old_preload;
4185 #               define PRELOAD_SZ 200
4186                 char preload_buf[PRELOAD_SZ];
4187                 static GC_bool found_exe_name = FALSE;
4188                 static GC_bool will_fail = FALSE;
4189                 int ret_code;
4190                 /* Try to get it via a hairy and expensive scheme.      */
4191                 /* First we get the name of the executable:             */
4192                 if (will_fail) goto out;
4193                 if (!found_exe_name) { 
4194                   ret_code = readlink("/proc/self/exe", exe_name, EXE_SZ);
4195                   if (ret_code < 0 || ret_code >= EXE_SZ
4196                       || exe_name[0] != '/') {
4197                     will_fail = TRUE;   /* Dont try again. */
4198                     goto out;
4199                   }
4200                   exe_name[ret_code] = '\0';
4201                   found_exe_name = TRUE;
4202                 }
4203                 /* Then we use popen to start addr2line -e <exe> <addr> */
4204                 /* There are faster ways to do this, but hopefully this */
4205                 /* isn't time critical.                                 */
4206                 sprintf(cmd_buf, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name,
4207                                  (unsigned long)info[i].ci_pc);
4208                 old_preload = getenv ("LD_PRELOAD");
4209                 if (0 != old_preload) {
4210                   if (strlen (old_preload) >= PRELOAD_SZ) {
4211                     will_fail = TRUE;
4212                     goto out;
4213                   }
4214                   strcpy (preload_buf, old_preload);
4215                   unsetenv ("LD_PRELOAD");
4216                 }
4217                 pipe = popen(cmd_buf, "r");
4218                 if (0 != old_preload
4219                     && 0 != setenv ("LD_PRELOAD", preload_buf, 0)) {
4220                   WARN("Failed to reset LD_PRELOAD\n", 0);
4221                 }
4222                 if (pipe == NULL
4223                     || (result_len = fread(result_buf, 1, RESULT_SZ - 1, pipe))
4224                        == 0) {
4225                   if (pipe != NULL) pclose(pipe);
4226                   will_fail = TRUE;
4227                   goto out;
4228                 }
4229                 if (result_buf[result_len - 1] == '\n') --result_len;
4230                 result_buf[result_len] = 0;
4231                 if (result_buf[0] == '?'
4232                     || result_buf[result_len-2] == ':' 
4233                        && result_buf[result_len-1] == '0') {
4234                     pclose(pipe);
4235                     goto out;
4236                 }
4237                 /* Get rid of embedded newline, if any.  Test for "main" */
4238                 {
4239                    char * nl = strchr(result_buf, '\n');
4240                    if (nl != NULL && nl < result_buf + result_len) {
4241                      *nl = ':';
4242                    }
4243                    if (strncmp(result_buf, "main", nl - result_buf) == 0) {
4244                      stop = TRUE;
4245                    }
4246                 }
4247                 if (result_len < RESULT_SZ - 25) {
4248                   /* Add in hex address */
4249                     sprintf(result_buf + result_len, " [0x%lx]",
4250                           (unsigned long)info[i].ci_pc);
4251                 }
4252                 name = result_buf;
4253                 pclose(pipe);
4254                 out:;
4255             }
4256 #         endif /* LINUX */
4257           GC_err_printf1("\t\t%s\n", name);
4258 #         if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4259              && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4260             free(sym_name);  /* May call GC_free; that's OK */
4261 #         endif
4262         }
4263     }
4264     LOCK();
4265       --reentry_count;
4266     UNLOCK();
4267 }
4268
4269 #endif /* NEED_CALLINFO */
4270
4271
4272
4273 #if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
4274
4275 /* Dump /proc/self/maps to GC_stderr, to enable looking up names for
4276    addresses in FIND_LEAK output. */
4277
4278 static word dump_maps(char *maps)
4279 {
4280     GC_err_write(maps, strlen(maps));
4281     return 1;
4282 }
4283
4284 void GC_print_address_map()
4285 {
4286     GC_err_printf0("---------- Begin address map ----------\n");
4287     GC_apply_to_maps(dump_maps);
4288     GC_err_printf0("---------- End address map ----------\n");
4289 }
4290
4291 #endif
4292
4293