OSDN Git Service

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