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