OSDN Git Service

744b1e0898be254ccbdb8c0963195ff9ca44ec8a
[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 "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 #   include <sys/types.h>
50 #   if !defined(MSWIN32) && !defined(SUNOS4)
51 #       include <unistd.h>
52 #   endif
53 # endif
54
55 # include <stdio.h>
56 # include <signal.h>
57
58 /* Blatantly OS dependent routines, except for those that are related   */
59 /* to dynamic loading.                                                  */
60
61 # if !defined(THREADS) && !defined(STACKBOTTOM) && defined(HEURISTIC2)
62 #   define NEED_FIND_LIMIT
63 # endif
64
65 # if defined(IRIX_THREADS) || defined(HPUX_THREADS)
66 #   define NEED_FIND_LIMIT
67 # endif
68
69 # if (defined(SUNOS4) & defined(DYNAMIC_LOADING)) && !defined(PCR)
70 #   define NEED_FIND_LIMIT
71 # endif
72
73 # if (defined(SVR4) || defined(AUX) || defined(DGUX)) && !defined(PCR)
74 #   define NEED_FIND_LIMIT
75 # endif
76
77 # if defined(LINUX) && \
78      (defined(POWERPC) || defined(SPARC) || defined(ALPHA) || defined(IA64))
79 #   define NEED_FIND_LIMIT
80 # endif
81
82 #ifdef NEED_FIND_LIMIT
83 #   include <setjmp.h>
84 #endif
85
86 #ifdef FREEBSD
87 #  include <machine/trap.h>
88 #endif
89
90 #ifdef AMIGA
91 # include <proto/exec.h>
92 # include <proto/dos.h>
93 # include <dos/dosextens.h>
94 # include <workbench/startup.h>
95 #endif
96
97 #ifdef MSWIN32
98 # define WIN32_LEAN_AND_MEAN
99 # define NOSERVICE
100 # include <windows.h>
101 #endif
102
103 #ifdef MACOS
104 # include <Processes.h>
105 #endif
106
107 #ifdef IRIX5
108 # include <sys/uio.h>
109 # include <malloc.h>   /* for locking */
110 #endif
111 #ifdef USE_MMAP
112 # include <sys/types.h>
113 # include <sys/mman.h>
114 # include <sys/stat.h>
115 # include <fcntl.h>
116 #endif
117
118 #ifdef SUNOS5SIGS
119 # include <sys/siginfo.h>
120 # undef setjmp
121 # undef longjmp
122 # define setjmp(env) sigsetjmp(env, 1)
123 # define longjmp(env, val) siglongjmp(env, val)
124 # define jmp_buf sigjmp_buf
125 #endif
126
127 #ifdef DJGPP
128   /* Apparently necessary for djgpp 2.01.  May casuse problems with     */
129   /* other versions.                                                    */
130   typedef long unsigned int caddr_t;
131 #endif
132
133 #ifdef PCR
134 # include "il/PCR_IL.h"
135 # include "th/PCR_ThCtl.h"
136 # include "mm/PCR_MM.h"
137 #endif
138
139 #if !defined(NO_EXECUTE_PERMISSION)
140 # define OPT_PROT_EXEC PROT_EXEC
141 #else
142 # define OPT_PROT_EXEC 0
143 #endif
144
145 #if defined(LINUX) && (defined(POWERPC) || defined(SPARC) || defined(ALPHA) \
146                        || defined(IA64))
147   /* The I386 case can be handled without a search.  The Alpha case     */
148   /* used to be handled differently as well, but the rules changed      */
149   /* for recent Linux versions.  This seems to be the easiest way to    */
150   /* cover all versions.                                                */
151   ptr_t GC_data_start;
152
153   extern char * GC_copyright[];  /* Any data symbol would do. */
154
155   void GC_init_linux_data_start()
156   {
157     extern ptr_t GC_find_limit();
158
159     GC_data_start = GC_find_limit((ptr_t)GC_copyright, FALSE);
160   }
161 #endif
162
163 # ifdef ECOS
164
165 # ifndef ECOS_GC_MEMORY_SIZE
166 # define ECOS_GC_MEMORY_SIZE (448 * 1024)
167 # endif /* ECOS_GC_MEMORY_SIZE */
168
169 // setjmp() function, as described in ANSI para 7.6.1.1
170 #define setjmp( __env__ )  hal_setjmp( __env__ )
171
172 // FIXME: This is a simple way of allocating memory which is
173 // compatible with ECOS early releases.  Later releases use a more
174 // sophisticated means of allocating memory than this simple static
175 // allocator, but this method is at least bound to work.
176 static char memory[ECOS_GC_MEMORY_SIZE];
177 static char *brk = memory;
178
179 static void *tiny_sbrk(ptrdiff_t increment)
180 {
181   void *p = brk;
182
183   brk += increment;
184
185   if (brk >  memory + sizeof memory)
186     {
187       brk -= increment;
188       return NULL;
189     }
190
191   return p;
192 }
193 #define sbrk tiny_sbrk
194 # endif /* ECOS */
195
196 # ifdef OS2
197
198 # include <stddef.h>
199
200 # if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */
201
202 struct exe_hdr {
203     unsigned short      magic_number;
204     unsigned short      padding[29];
205     long                new_exe_offset;
206 };
207
208 #define E_MAGIC(x)      (x).magic_number
209 #define EMAGIC          0x5A4D  
210 #define E_LFANEW(x)     (x).new_exe_offset
211
212 struct e32_exe {
213     unsigned char       magic_number[2]; 
214     unsigned char       byte_order; 
215     unsigned char       word_order; 
216     unsigned long       exe_format_level;
217     unsigned short      cpu;       
218     unsigned short      os;
219     unsigned long       padding1[13];
220     unsigned long       object_table_offset;
221     unsigned long       object_count;    
222     unsigned long       padding2[31];
223 };
224
225 #define E32_MAGIC1(x)   (x).magic_number[0]
226 #define E32MAGIC1       'L'
227 #define E32_MAGIC2(x)   (x).magic_number[1]
228 #define E32MAGIC2       'X'
229 #define E32_BORDER(x)   (x).byte_order
230 #define E32LEBO         0
231 #define E32_WORDER(x)   (x).word_order
232 #define E32LEWO         0
233 #define E32_CPU(x)      (x).cpu
234 #define E32CPU286       1
235 #define E32_OBJTAB(x)   (x).object_table_offset
236 #define E32_OBJCNT(x)   (x).object_count
237
238 struct o32_obj {
239     unsigned long       size;  
240     unsigned long       base;
241     unsigned long       flags;  
242     unsigned long       pagemap;
243     unsigned long       mapsize; 
244     unsigned long       reserved;
245 };
246
247 #define O32_FLAGS(x)    (x).flags
248 #define OBJREAD         0x0001L
249 #define OBJWRITE        0x0002L
250 #define OBJINVALID      0x0080L
251 #define O32_SIZE(x)     (x).size
252 #define O32_BASE(x)     (x).base
253
254 # else  /* IBM's compiler */
255
256 /* A kludge to get around what appears to be a header file bug */
257 # ifndef WORD
258 #   define WORD unsigned short
259 # endif
260 # ifndef DWORD
261 #   define DWORD unsigned long
262 # endif
263
264 # define EXE386 1
265 # include <newexe.h>
266 # include <exe386.h>
267
268 # endif  /* __IBMC__ */
269
270 # define INCL_DOSEXCEPTIONS
271 # define INCL_DOSPROCESS
272 # define INCL_DOSERRORS
273 # define INCL_DOSMODULEMGR
274 # define INCL_DOSMEMMGR
275 # include <os2.h>
276
277
278 /* Disable and enable signals during nontrivial allocations     */
279
280 void GC_disable_signals(void)
281 {
282     ULONG nest;
283     
284     DosEnterMustComplete(&nest);
285     if (nest != 1) ABORT("nested GC_disable_signals");
286 }
287
288 void GC_enable_signals(void)
289 {
290     ULONG nest;
291     
292     DosExitMustComplete(&nest);
293     if (nest != 0) ABORT("GC_enable_signals");
294 }
295
296
297 # else
298
299 #  if !defined(PCR) && !defined(AMIGA) && !defined(MSWIN32) \
300       && !defined(MACOS) && !defined(DJGPP) && !defined(DOS4GW) \
301       && !defined(NO_SIGSET)
302
303 #   if defined(sigmask) && !defined(UTS4)
304         /* Use the traditional BSD interface */
305 #       define SIGSET_T int
306 #       define SIG_DEL(set, signal) (set) &= ~(sigmask(signal))
307 #       define SIG_FILL(set)  (set) = 0x7fffffff
308           /* Setting the leading bit appears to provoke a bug in some   */
309           /* longjmp implementations.  Most systems appear not to have  */
310           /* a signal 32.                                               */
311 #       define SIGSETMASK(old, new) (old) = sigsetmask(new)
312 #   else
313         /* Use POSIX/SYSV interface     */
314 #       define SIGSET_T sigset_t
315 #       define SIG_DEL(set, signal) sigdelset(&(set), (signal))
316 #       define SIG_FILL(set) sigfillset(&set)
317 #       define SIGSETMASK(old, new) sigprocmask(SIG_SETMASK, &(new), &(old))
318 #   endif
319
320 static GC_bool mask_initialized = FALSE;
321
322 static SIGSET_T new_mask;
323
324 static SIGSET_T old_mask;
325
326 static SIGSET_T dummy;
327
328 #if defined(PRINTSTATS) && !defined(THREADS)
329 # define CHECK_SIGNALS
330   int GC_sig_disabled = 0;
331 #endif
332
333 void GC_disable_signals()
334 {
335     if (!mask_initialized) {
336         SIG_FILL(new_mask);
337
338         SIG_DEL(new_mask, SIGSEGV);
339         SIG_DEL(new_mask, SIGILL);
340         SIG_DEL(new_mask, SIGQUIT);
341 #       ifdef SIGBUS
342             SIG_DEL(new_mask, SIGBUS);
343 #       endif
344 #       ifdef SIGIOT
345             SIG_DEL(new_mask, SIGIOT);
346 #       endif
347 #       ifdef SIGEMT
348             SIG_DEL(new_mask, SIGEMT);
349 #       endif
350 #       ifdef SIGTRAP
351             SIG_DEL(new_mask, SIGTRAP);
352 #       endif 
353         mask_initialized = TRUE;
354     }
355 #   ifdef CHECK_SIGNALS
356         if (GC_sig_disabled != 0) ABORT("Nested disables");
357         GC_sig_disabled++;
358 #   endif
359     SIGSETMASK(old_mask,new_mask);
360 }
361
362 void GC_enable_signals()
363 {
364 #   ifdef CHECK_SIGNALS
365         if (GC_sig_disabled != 1) ABORT("Unmatched enable");
366         GC_sig_disabled--;
367 #   endif
368     SIGSETMASK(dummy,old_mask);
369 }
370
371 #  endif  /* !PCR */
372
373 # endif /*!OS/2 */
374
375 /* Ivan Demakov: simplest way (to me) */
376 #if defined (DOS4GW) || defined (NO_SIGSET)
377   void GC_disable_signals() { }
378   void GC_enable_signals() { }
379 #endif
380
381 /* Find the page size */
382 word GC_page_size;
383
384 # ifdef MSWIN32
385   void GC_setpagesize()
386   {
387     SYSTEM_INFO sysinfo;
388     
389     GetSystemInfo(&sysinfo);
390     GC_page_size = sysinfo.dwPageSize;
391   }
392
393 # else
394 #   if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP) \
395        || defined(USE_MUNMAP)
396         void GC_setpagesize()
397         {
398             GC_page_size = GETPAGESIZE();
399         }
400 #   else
401         /* It's acceptable to fake it. */
402         void GC_setpagesize()
403         {
404             GC_page_size = HBLKSIZE;
405         }
406 #   endif
407 # endif
408
409 /* 
410  * Find the base of the stack. 
411  * Used only in single-threaded environment.
412  * With threads, GC_mark_roots needs to know how to do this.
413  * Called with allocator lock held.
414  */
415 # ifdef MSWIN32 
416 # define is_writable(prot) ((prot) == PAGE_READWRITE \
417                             || (prot) == PAGE_WRITECOPY \
418                             || (prot) == PAGE_EXECUTE_READWRITE \
419                             || (prot) == PAGE_EXECUTE_WRITECOPY)
420 /* Return the number of bytes that are writable starting at p.  */
421 /* The pointer p is assumed to be page aligned.                 */
422 /* If base is not 0, *base becomes the beginning of the         */
423 /* allocation region containing p.                              */
424 word GC_get_writable_length(ptr_t p, ptr_t *base)
425 {
426     MEMORY_BASIC_INFORMATION buf;
427     word result;
428     word protect;
429     
430     result = VirtualQuery(p, &buf, sizeof(buf));
431     if (result != sizeof(buf)) ABORT("Weird VirtualQuery result");
432     if (base != 0) *base = (ptr_t)(buf.AllocationBase);
433     protect = (buf.Protect & ~(PAGE_GUARD | PAGE_NOCACHE));
434     if (!is_writable(protect)) {
435         return(0);
436     }
437     if (buf.State != MEM_COMMIT) return(0);
438     return(buf.RegionSize);
439 }
440
441 ptr_t GC_get_stack_base()
442 {
443     int dummy;
444     ptr_t sp = (ptr_t)(&dummy);
445     ptr_t trunc_sp = (ptr_t)((word)sp & ~(GC_page_size - 1));
446     word size = GC_get_writable_length(trunc_sp, 0);
447    
448     return(trunc_sp + size);
449 }
450
451
452 # else
453
454 # ifdef OS2
455
456 ptr_t GC_get_stack_base()
457 {
458     PTIB ptib;
459     PPIB ppib;
460     
461     if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
462         GC_err_printf0("DosGetInfoBlocks failed\n");
463         ABORT("DosGetInfoBlocks failed\n");
464     }
465     return((ptr_t)(ptib -> tib_pstacklimit));
466 }
467
468 # else
469
470 # ifdef AMIGA
471
472 ptr_t GC_get_stack_base()
473 {
474     struct Process *proc = (struct Process*)SysBase->ThisTask;
475  
476     /* Reference: Amiga Guru Book Pages: 42,567,574 */
477     if (proc->pr_Task.tc_Node.ln_Type==NT_PROCESS
478         && proc->pr_CLI != NULL) {
479         /* first ULONG is StackSize */
480         /*longPtr = proc->pr_ReturnAddr;
481         size = longPtr[0];*/
482
483         return (char *)proc->pr_ReturnAddr + sizeof(ULONG);
484     } else {
485         return (char *)proc->pr_Task.tc_SPUpper;
486     }
487 }
488
489 #if 0 /* old version */
490 ptr_t GC_get_stack_base()
491 {
492     extern struct WBStartup *_WBenchMsg;
493     extern long __base;
494     extern long __stack;
495     struct Task *task;
496     struct Process *proc;
497     struct CommandLineInterface *cli;
498     long size;
499
500     if ((task = FindTask(0)) == 0) {
501         GC_err_puts("Cannot find own task structure\n");
502         ABORT("task missing");
503     }
504     proc = (struct Process *)task;
505     cli = BADDR(proc->pr_CLI);
506
507     if (_WBenchMsg != 0 || cli == 0) {
508         size = (char *)task->tc_SPUpper - (char *)task->tc_SPLower;
509     } else {
510         size = cli->cli_DefaultStack * 4;
511     }
512     return (ptr_t)(__base + GC_max(size, __stack));
513 }
514 #endif /* 0 */
515
516 # else /* !AMIGA, !OS2, ... */
517
518 # ifdef NEED_FIND_LIMIT
519   /* Some tools to implement HEURISTIC2 */
520 #   define MIN_PAGE_SIZE 256    /* Smallest conceivable page size, bytes */
521     /* static */ jmp_buf GC_jmp_buf;
522     
523     /*ARGSUSED*/
524     void GC_fault_handler(sig)
525     int sig;
526     {
527         longjmp(GC_jmp_buf, 1);
528     }
529
530 #   ifdef __STDC__
531         typedef void (*handler)(int);
532 #   else
533         typedef void (*handler)();
534 #   endif
535
536 #   if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1)
537         static struct sigaction old_segv_act;
538 #       if defined(_sigargs) || defined(HPUX) /* !Irix6.x */
539             static struct sigaction old_bus_act;
540 #       endif
541 #   else
542         static handler old_segv_handler, old_bus_handler;
543 #   endif
544     
545     void GC_setup_temporary_fault_handler()
546     {
547 # ifndef ECOS
548 #       if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1)
549           struct sigaction      act;
550
551           act.sa_handler        = GC_fault_handler;
552           act.sa_flags          = SA_RESTART | SA_NODEFER;
553           /* The presence of SA_NODEFER represents yet another gross    */
554           /* hack.  Under Solaris 2.3, siglongjmp doesn't appear to     */
555           /* interact correctly with -lthread.  We hide the confusion   */
556           /* by making sure that signal handling doesn't affect the     */
557           /* signal mask.                                               */
558
559           (void) sigemptyset(&act.sa_mask);
560 #         ifdef IRIX_THREADS
561                 /* Older versions have a bug related to retrieving and  */
562                 /* and setting a handler at the same time.              */
563                 (void) sigaction(SIGSEGV, 0, &old_segv_act);
564                 (void) sigaction(SIGSEGV, &act, 0);
565 #         else
566                 (void) sigaction(SIGSEGV, &act, &old_segv_act);
567 #               if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \
568                    || defined(HPUX)
569                     /* Under Irix 5.x or HP/UX, we may get SIGBUS.      */
570                     /* Pthreads doesn't exist under Irix 5.x, so we     */
571                     /* don't have to worry in the threads case.         */
572                     (void) sigaction(SIGBUS, &act, &old_bus_act);
573 #               endif
574 #         endif /* IRIX_THREADS */
575 #       else
576           old_segv_handler = signal(SIGSEGV, GC_fault_handler);
577 #         ifdef SIGBUS
578             old_bus_handler = signal(SIGBUS, GC_fault_handler);
579 #         endif
580 #       endif
581 # endif /* ECOS */
582     }
583     
584     void GC_reset_fault_handler()
585     {
586 # ifndef ECOS
587 #       if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1)
588           (void) sigaction(SIGSEGV, &old_segv_act, 0);
589 #         if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \
590              || defined(HPUX)
591               (void) sigaction(SIGBUS, &old_bus_act, 0);
592 #         endif
593 #       else
594           (void) signal(SIGSEGV, old_segv_handler);
595 #         ifdef SIGBUS
596             (void) signal(SIGBUS, old_bus_handler);
597 #         endif
598 #       endif
599 # endif /* ECOS */
600     }
601
602     /* Return the first nonaddressible location > p (up) or     */
603     /* the smallest location q s.t. [q,p] is addressible (!up). */
604     ptr_t GC_find_limit(p, up)
605     ptr_t p;
606     GC_bool up;
607     {
608 # ifndef ECOS
609         static VOLATILE ptr_t result;
610                 /* Needs to be static, since otherwise it may not be    */
611                 /* preserved across the longjmp.  Can safely be         */
612                 /* static since it's only called once, with the         */
613                 /* allocation lock held.                                */
614
615
616         GC_setup_temporary_fault_handler();
617         if (setjmp(GC_jmp_buf) == 0) {
618             result = (ptr_t)(((word)(p))
619                               & ~(MIN_PAGE_SIZE-1));
620             for (;;) {
621                 if (up) {
622                     result += MIN_PAGE_SIZE;
623                 } else {
624                     result -= MIN_PAGE_SIZE;
625                 }
626                 GC_noop1((word)(*result));
627             }
628         }
629         GC_reset_fault_handler();
630         if (!up) {
631             result += MIN_PAGE_SIZE;
632         }
633         return(result);
634 # else /* ECOS */
635         abort();
636 # endif /* ECOS */
637     }
638 # endif
639
640 # ifndef ECOS
641
642 #ifdef LINUX_STACKBOTTOM
643
644 # define STAT_SKIP 27   /* Number of fields preceding startstack        */
645                         /* field in /proc/<pid>/stat                    */
646
647   ptr_t GC_linux_stack_base(void)
648   {
649     char buf[50];
650     FILE *f;
651     char c;
652     word result = 0;
653     int i;
654
655     sprintf(buf, "/proc/%d/stat", getpid());
656     f = fopen(buf, "r");
657     if (NULL == f) ABORT("Couldn't open /proc/<pid>/stat");
658     c = getc(f);
659     /* Skip the required number of fields.  This number is hopefully    */
660     /* constant across all Linux implementations.                       */
661       for (i = 0; i < STAT_SKIP; ++i) {
662         while (isspace(c)) c = getc(f);
663         while (!isspace(c)) c = getc(f);
664       }
665     while (isspace(c)) c = getc(f);
666     while (isdigit(c)) {
667       result *= 10;
668       result += c - '0';
669       c = getc(f);
670     }
671     if (result < 0x10000000) ABORT("Absurd stack bottom value");
672     return (ptr_t)result;
673   }
674
675 #endif /* LINUX_STACKBOTTOM */
676
677 ptr_t GC_get_stack_base()
678 {
679     word dummy;
680     ptr_t result;
681
682 #   define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
683
684 #  if defined(STACKBASE)
685     extern ptr_t STACKBASE;
686     return(STACKBASE);
687 #   else
688 #   ifdef STACKBOTTOM
689         return(STACKBOTTOM);
690 #   else
691 #       ifdef HEURISTIC1
692 #          ifdef STACK_GROWS_DOWN
693              result = (ptr_t)((((word)(&dummy))
694                                + STACKBOTTOM_ALIGNMENT_M1)
695                               & ~STACKBOTTOM_ALIGNMENT_M1);
696 #          else
697              result = (ptr_t)(((word)(&dummy))
698                               & ~STACKBOTTOM_ALIGNMENT_M1);
699 #          endif
700 #       endif /* HEURISTIC1 */
701 #       ifdef LINUX_STACKBOTTOM
702            result = GC_linux_stack_base();
703 #       endif
704 #       ifdef HEURISTIC2
705 #           ifdef STACK_GROWS_DOWN
706                 result = GC_find_limit((ptr_t)(&dummy), TRUE);
707 #               ifdef HEURISTIC2_LIMIT
708                     if (result > HEURISTIC2_LIMIT
709                         && (ptr_t)(&dummy) < HEURISTIC2_LIMIT) {
710                             result = HEURISTIC2_LIMIT;
711                     }
712 #               endif
713 #           else
714                 result = GC_find_limit((ptr_t)(&dummy), FALSE);
715 #               ifdef HEURISTIC2_LIMIT
716                     if (result < HEURISTIC2_LIMIT
717                         && (ptr_t)(&dummy) > HEURISTIC2_LIMIT) {
718                             result = HEURISTIC2_LIMIT;
719                     }
720 #               endif
721 #           endif
722
723 #       endif /* HEURISTIC2 */
724 #       ifdef STACK_GROWS_DOWN
725             if (result == 0) result = (ptr_t)(signed_word)(-sizeof(ptr_t));
726 #       endif
727         return(result);
728 #   endif /* STACKBOTTOM */
729 #   endif /* STACKBASE */
730 }
731 # endif /* ECOS */
732
733 # endif /* ! AMIGA */
734 # endif /* ! OS2 */
735 # endif /* ! MSWIN32 */
736
737 /*
738  * Register static data segment(s) as roots.
739  * If more data segments are added later then they need to be registered
740  * add that point (as we do with SunOS dynamic loading),
741  * or GC_mark_roots needs to check for them (as we do with PCR).
742  * Called with allocator lock held.
743  */
744
745 # ifdef OS2
746
747 void GC_register_data_segments()
748 {
749     PTIB ptib;
750     PPIB ppib;
751     HMODULE module_handle;
752 #   define PBUFSIZ 512
753     UCHAR path[PBUFSIZ];
754     FILE * myexefile;
755     struct exe_hdr hdrdos;      /* MSDOS header.        */
756     struct e32_exe hdr386;      /* Real header for my executable */
757     struct o32_obj seg; /* Currrent segment */
758     int nsegs;
759     
760     
761     if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
762         GC_err_printf0("DosGetInfoBlocks failed\n");
763         ABORT("DosGetInfoBlocks failed\n");
764     }
765     module_handle = ppib -> pib_hmte;
766     if (DosQueryModuleName(module_handle, PBUFSIZ, path) != NO_ERROR) {
767         GC_err_printf0("DosQueryModuleName failed\n");
768         ABORT("DosGetInfoBlocks failed\n");
769     }
770     myexefile = fopen(path, "rb");
771     if (myexefile == 0) {
772         GC_err_puts("Couldn't open executable ");
773         GC_err_puts(path); GC_err_puts("\n");
774         ABORT("Failed to open executable\n");
775     }
776     if (fread((char *)(&hdrdos), 1, sizeof hdrdos, myexefile) < sizeof hdrdos) {
777         GC_err_puts("Couldn't read MSDOS header from ");
778         GC_err_puts(path); GC_err_puts("\n");
779         ABORT("Couldn't read MSDOS header");
780     }
781     if (E_MAGIC(hdrdos) != EMAGIC) {
782         GC_err_puts("Executable has wrong DOS magic number: ");
783         GC_err_puts(path); GC_err_puts("\n");
784         ABORT("Bad DOS magic number");
785     }
786     if (fseek(myexefile, E_LFANEW(hdrdos), SEEK_SET) != 0) {
787         GC_err_puts("Seek to new header failed in ");
788         GC_err_puts(path); GC_err_puts("\n");
789         ABORT("Bad DOS magic number");
790     }
791     if (fread((char *)(&hdr386), 1, sizeof hdr386, myexefile) < sizeof hdr386) {
792         GC_err_puts("Couldn't read MSDOS header from ");
793         GC_err_puts(path); GC_err_puts("\n");
794         ABORT("Couldn't read OS/2 header");
795     }
796     if (E32_MAGIC1(hdr386) != E32MAGIC1 || E32_MAGIC2(hdr386) != E32MAGIC2) {
797         GC_err_puts("Executable has wrong OS/2 magic number:");
798         GC_err_puts(path); GC_err_puts("\n");
799         ABORT("Bad OS/2 magic number");
800     }
801     if ( E32_BORDER(hdr386) != E32LEBO || E32_WORDER(hdr386) != E32LEWO) {
802         GC_err_puts("Executable %s has wrong byte order: ");
803         GC_err_puts(path); GC_err_puts("\n");
804         ABORT("Bad byte order");
805     }
806     if ( E32_CPU(hdr386) == E32CPU286) {
807         GC_err_puts("GC can't handle 80286 executables: ");
808         GC_err_puts(path); GC_err_puts("\n");
809         EXIT();
810     }
811     if (fseek(myexefile, E_LFANEW(hdrdos) + E32_OBJTAB(hdr386),
812               SEEK_SET) != 0) {
813         GC_err_puts("Seek to object table failed: ");
814         GC_err_puts(path); GC_err_puts("\n");
815         ABORT("Seek to object table failed");
816     }
817     for (nsegs = E32_OBJCNT(hdr386); nsegs > 0; nsegs--) {
818       int flags;
819       if (fread((char *)(&seg), 1, sizeof seg, myexefile) < sizeof seg) {
820         GC_err_puts("Couldn't read obj table entry from ");
821         GC_err_puts(path); GC_err_puts("\n");
822         ABORT("Couldn't read obj table entry");
823       }
824       flags = O32_FLAGS(seg);
825       if (!(flags & OBJWRITE)) continue;
826       if (!(flags & OBJREAD)) continue;
827       if (flags & OBJINVALID) {
828           GC_err_printf0("Object with invalid pages?\n");
829           continue;
830       } 
831       GC_add_roots_inner(O32_BASE(seg), O32_BASE(seg)+O32_SIZE(seg), FALSE);
832     }
833 }
834
835 # else
836
837 # ifdef MSWIN32
838   /* Unfortunately, we have to handle win32s very differently from NT,  */
839   /* Since VirtualQuery has very different semantics.  In particular,   */
840   /* under win32s a VirtualQuery call on an unmapped page returns an    */
841   /* invalid result.  Under GC_register_data_segments is a noop and     */
842   /* all real work is done by GC_register_dynamic_libraries.  Under     */
843   /* win32s, we cannot find the data segments associated with dll's.    */
844   /* We rgister the main data segment here.                             */
845   GC_bool GC_win32s = FALSE;    /* We're running under win32s.  */
846   
847   GC_bool GC_is_win32s()
848   {
849       DWORD v = GetVersion();
850       
851       /* Check that this is not NT, and Windows major version <= 3      */
852       return ((v & 0x80000000) && (v & 0xff) <= 3);
853   }
854   
855   void GC_init_win32()
856   {
857       GC_win32s = GC_is_win32s();
858   }
859   
860   /* Return the smallest address a such that VirtualQuery               */
861   /* returns correct results for all addresses between a and start.     */
862   /* Assumes VirtualQuery returns correct information for start.        */
863   ptr_t GC_least_described_address(ptr_t start)
864   {  
865     MEMORY_BASIC_INFORMATION buf;
866     SYSTEM_INFO sysinfo;
867     DWORD result;
868     LPVOID limit;
869     ptr_t p;
870     LPVOID q;
871     
872     GetSystemInfo(&sysinfo);
873     limit = sysinfo.lpMinimumApplicationAddress;
874     p = (ptr_t)((word)start & ~(GC_page_size - 1));
875     for (;;) {
876         q = (LPVOID)(p - GC_page_size);
877         if ((ptr_t)q > (ptr_t)p /* underflow */ || q < limit) break;
878         result = VirtualQuery(q, &buf, sizeof(buf));
879         if (result != sizeof(buf) || buf.AllocationBase == 0) break;
880         p = (ptr_t)(buf.AllocationBase);
881     }
882     return(p);
883   }
884   
885   /* Is p the start of either the malloc heap, or of one of our */
886   /* heap sections?                                             */
887   GC_bool GC_is_heap_base (ptr_t p)
888   {
889      
890      register unsigned i;
891      
892 #    ifndef REDIRECT_MALLOC
893        static ptr_t malloc_heap_pointer = 0;
894      
895        if (0 == malloc_heap_pointer) {
896          MEMORY_BASIC_INFORMATION buf;
897          register DWORD result = VirtualQuery(malloc(1), &buf, sizeof(buf));
898          
899          if (result != sizeof(buf)) {
900              ABORT("Weird VirtualQuery result");
901          }
902          malloc_heap_pointer = (ptr_t)(buf.AllocationBase);
903        }
904        if (p == malloc_heap_pointer) return(TRUE);
905 #    endif
906      for (i = 0; i < GC_n_heap_bases; i++) {
907          if (GC_heap_bases[i] == p) return(TRUE);
908      }
909      return(FALSE);
910   }
911   
912   void GC_register_root_section(ptr_t static_root)
913   {
914       MEMORY_BASIC_INFORMATION buf;
915       SYSTEM_INFO sysinfo;
916       DWORD result;
917       DWORD protect;
918       LPVOID p;
919       char * base;
920       char * limit, * new_limit;
921     
922       if (!GC_win32s) return;
923       p = base = limit = GC_least_described_address(static_root);
924       GetSystemInfo(&sysinfo);
925       while (p < sysinfo.lpMaximumApplicationAddress) {
926         result = VirtualQuery(p, &buf, sizeof(buf));
927         if (result != sizeof(buf) || buf.AllocationBase == 0
928             || GC_is_heap_base(buf.AllocationBase)) break;
929         new_limit = (char *)p + buf.RegionSize;
930         protect = buf.Protect;
931         if (buf.State == MEM_COMMIT
932             && is_writable(protect)) {
933             if ((char *)p == limit) {
934                 limit = new_limit;
935             } else {
936                 if (base != limit) GC_add_roots_inner(base, limit, FALSE);
937                 base = p;
938                 limit = new_limit;
939             }
940         }
941         if (p > (LPVOID)new_limit /* overflow */) break;
942         p = (LPVOID)new_limit;
943       }
944       if (base != limit) GC_add_roots_inner(base, limit, FALSE);
945   }
946   
947   void GC_register_data_segments()
948   {
949       static char dummy;
950       
951       GC_register_root_section((ptr_t)(&dummy));
952   }
953 # else
954 # ifdef AMIGA
955
956    void GC_register_data_segments()
957    {
958      struct Process     *proc;
959      struct CommandLineInterface *cli;
960      BPTR myseglist;
961      ULONG *data;
962  
963      int        num;
964
965
966 #    ifdef __GNUC__
967         ULONG dataSegSize;
968         GC_bool found_segment = FALSE;
969         extern char __data_size[];
970
971         dataSegSize=__data_size+8;
972         /* Can`t find the Location of __data_size, because
973            it`s possible that is it, inside the segment. */
974
975 #     endif
976
977         proc= (struct Process*)SysBase->ThisTask;
978
979         /* Reference: Amiga Guru Book Pages: 538ff,565,573
980                      and XOper.asm */
981         if (proc->pr_Task.tc_Node.ln_Type==NT_PROCESS) {
982           if (proc->pr_CLI == NULL) {
983             myseglist = proc->pr_SegList;
984           } else {
985             /* ProcLoaded       'Loaded as a command: '*/
986             cli = BADDR(proc->pr_CLI);
987             myseglist = cli->cli_Module;
988           }
989         } else {
990           ABORT("Not a Process.");
991         }
992
993         if (myseglist == NULL) {
994             ABORT("Arrrgh.. can't find segments, aborting");
995         }
996
997         /* xoper hunks Shell Process */
998
999         num=0;
1000         for (data = (ULONG *)BADDR(myseglist); data != NULL;
1001              data = (ULONG *)BADDR(data[0])) {
1002           if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
1003               ((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
1004 #             ifdef __GNUC__
1005                 if (dataSegSize == data[-1]) {
1006                   found_segment = TRUE;
1007                 }
1008 #             endif
1009               GC_add_roots_inner((char *)&data[1],
1010                                  ((char *)&data[1]) + data[-1], FALSE);
1011           }
1012           ++num;
1013         } /* for */
1014 #       ifdef __GNUC__
1015            if (!found_segment) {
1016              ABORT("Can`t find correct Segments.\nSolution: Use an newer version of ixemul.library");
1017            }
1018 #       endif
1019   }
1020
1021 #if 0 /* old version */
1022   void GC_register_data_segments()
1023   {
1024     extern struct WBStartup *_WBenchMsg;
1025     struct Process      *proc;
1026     struct CommandLineInterface *cli;
1027     BPTR myseglist;
1028     ULONG *data;
1029
1030     if ( _WBenchMsg != 0 ) {
1031         if ((myseglist = _WBenchMsg->sm_Segment) == 0) {
1032             GC_err_puts("No seglist from workbench\n");
1033             return;
1034         }
1035     } else {
1036         if ((proc = (struct Process *)FindTask(0)) == 0) {
1037             GC_err_puts("Cannot find process structure\n");
1038             return;
1039         }
1040         if ((cli = BADDR(proc->pr_CLI)) == 0) {
1041             GC_err_puts("No CLI\n");
1042             return;
1043         }
1044         if ((myseglist = cli->cli_Module) == 0) {
1045             GC_err_puts("No seglist from CLI\n");
1046             return;
1047         }
1048     }
1049
1050     for (data = (ULONG *)BADDR(myseglist); data != 0;
1051          data = (ULONG *)BADDR(data[0])) {
1052 #        ifdef AMIGA_SKIP_SEG
1053            if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
1054            ((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
1055 #        else
1056            {
1057 #        endif /* AMIGA_SKIP_SEG */
1058           GC_add_roots_inner((char *)&data[1],
1059                              ((char *)&data[1]) + data[-1], FALSE);
1060          }
1061     }
1062   }
1063 #endif /* old version */
1064
1065
1066 # else
1067
1068 # if (defined(SVR4) || defined(AUX) || defined(DGUX)) && !defined(PCR)
1069 char * GC_SysVGetDataStart(max_page_size, etext_addr)
1070 int max_page_size;
1071 int * etext_addr;
1072 {
1073     word text_end = ((word)(etext_addr) + sizeof(word) - 1)
1074                     & ~(sizeof(word) - 1);
1075         /* etext rounded to word boundary       */
1076     word next_page = ((text_end + (word)max_page_size - 1)
1077                       & ~((word)max_page_size - 1));
1078     word page_offset = (text_end & ((word)max_page_size - 1));
1079     VOLATILE char * result = (char *)(next_page + page_offset);
1080     /* Note that this isnt equivalent to just adding            */
1081     /* max_page_size to &etext if &etext is at a page boundary  */
1082     
1083     GC_setup_temporary_fault_handler();
1084     if (setjmp(GC_jmp_buf) == 0) {
1085         /* Try writing to the address.  */
1086         *result = *result;
1087         GC_reset_fault_handler();
1088     } else {
1089         GC_reset_fault_handler();
1090         /* We got here via a longjmp.  The address is not readable.     */
1091         /* This is known to happen under Solaris 2.4 + gcc, which place */
1092         /* string constants in the text segment, but after etext.       */
1093         /* Use plan B.  Note that we now know there is a gap between    */
1094         /* text and data segments, so plan A bought us something.       */
1095         result = (char *)GC_find_limit((ptr_t)(DATAEND) - MIN_PAGE_SIZE, FALSE);
1096     }
1097     return((char *)result);
1098 }
1099 # endif
1100
1101
1102 void GC_register_data_segments()
1103 {
1104 #   if !defined(PCR) && !defined(SRC_M3) && !defined(NEXT) && !defined(MACOS) \
1105        && !defined(MACOSX)
1106 #     if defined(REDIRECT_MALLOC) && defined(SOLARIS_THREADS)
1107         /* As of Solaris 2.3, the Solaris threads implementation        */
1108         /* allocates the data structure for the initial thread with     */
1109         /* sbrk at process startup.  It needs to be scanned, so that    */
1110         /* we don't lose some malloc allocated data structures          */
1111         /* hanging from it.  We're on thin ice here ...                 */
1112         extern caddr_t sbrk();
1113
1114         GC_add_roots_inner(DATASTART, (char *)sbrk(0), FALSE);
1115 #     else
1116         GC_add_roots_inner(DATASTART, (char *)(DATAEND), FALSE);
1117 #     endif
1118 #   endif
1119 #   if !defined(PCR) && (defined(NEXT) || defined(MACOSX))
1120       GC_add_roots_inner(DATASTART, (char *) get_end(), FALSE);
1121 #   endif
1122 #   if defined(MACOS)
1123     {
1124 #   if defined(THINK_C)
1125         extern void* GC_MacGetDataStart(void);
1126         /* globals begin above stack and end at a5. */
1127         GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
1128                            (ptr_t)LMGetCurrentA5(), FALSE);
1129 #   else
1130 #     if defined(__MWERKS__)
1131 #       if !__POWERPC__
1132           extern void* GC_MacGetDataStart(void);
1133           /* MATTHEW: Function to handle Far Globals (CW Pro 3) */
1134 #         if __option(far_data)
1135           extern void* GC_MacGetDataEnd(void);
1136 #         endif
1137           /* globals begin above stack and end at a5. */
1138           GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
1139                              (ptr_t)LMGetCurrentA5(), FALSE);
1140           /* MATTHEW: Handle Far Globals */                          
1141 #         if __option(far_data)
1142       /* Far globals follow he QD globals: */
1143           GC_add_roots_inner((ptr_t)LMGetCurrentA5(),
1144                              (ptr_t)GC_MacGetDataEnd(), FALSE);
1145 #         endif
1146 #       else
1147           extern char __data_start__[], __data_end__[];
1148           GC_add_roots_inner((ptr_t)&__data_start__,
1149                              (ptr_t)&__data_end__, FALSE);
1150 #       endif /* __POWERPC__ */
1151 #     endif /* __MWERKS__ */
1152 #   endif /* !THINK_C */
1153     }
1154 #   endif /* MACOS */
1155
1156     /* Dynamic libraries are added at every collection, since they may  */
1157     /* change.                                                          */
1158 }
1159
1160 # endif  /* ! AMIGA */
1161 # endif  /* ! MSWIN32 */
1162 # endif  /* ! OS2 */
1163
1164 /*
1165  * Auxiliary routines for obtaining memory from OS.
1166  */
1167  
1168 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \
1169         && !defined(MSWIN32) && !defined(MACOS) && !defined(DOS4GW)
1170
1171 # ifdef SUNOS4
1172     extern caddr_t sbrk();
1173 # endif
1174 # ifdef __STDC__
1175 #   define SBRK_ARG_T ptrdiff_t
1176 # else
1177 #   define SBRK_ARG_T int
1178 # endif
1179
1180 # ifdef RS6000
1181 /* The compiler seems to generate speculative reads one past the end of */
1182 /* an allocated object.  Hence we need to make sure that the page       */
1183 /* following the last heap page is also mapped.                         */
1184 ptr_t GC_unix_get_mem(bytes)
1185 word bytes;
1186 {
1187     caddr_t cur_brk = (caddr_t)sbrk(0);
1188     caddr_t result;
1189     SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
1190     static caddr_t my_brk_val = 0;
1191     
1192     if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
1193     if (lsbs != 0) {
1194         if((caddr_t)(sbrk(GC_page_size - lsbs)) == (caddr_t)(-1)) return(0);
1195     }
1196     if (cur_brk == my_brk_val) {
1197         /* Use the extra block we allocated last time. */
1198         result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
1199         if (result == (caddr_t)(-1)) return(0);
1200         result -= GC_page_size;
1201     } else {
1202         result = (ptr_t)sbrk(GC_page_size + (SBRK_ARG_T)bytes);
1203         if (result == (caddr_t)(-1)) return(0);
1204     }
1205     my_brk_val = result + bytes + GC_page_size; /* Always page aligned */
1206     return((ptr_t)result);
1207 }
1208
1209 #else  /* Not RS6000 */
1210
1211 #if defined(USE_MMAP)
1212 /* Tested only under IRIX5 and Solaris 2 */
1213
1214 #ifdef USE_MMAP_FIXED
1215 #   define GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE
1216         /* Seems to yield better performance on Solaris 2, but can      */
1217         /* be unreliable if something is already mapped at the address. */
1218 #else
1219 #   define GC_MMAP_FLAGS MAP_PRIVATE
1220 #endif
1221
1222 ptr_t GC_unix_get_mem(bytes)
1223 word bytes;
1224 {
1225     static GC_bool initialized = FALSE;
1226     static int fd;
1227     void *result;
1228     static ptr_t last_addr = HEAP_START;
1229
1230     if (!initialized) {
1231         fd = open("/dev/zero", O_RDONLY);
1232         initialized = TRUE;
1233     }
1234     if (bytes & (GC_page_size -1)) ABORT("Bad GET_MEM arg");
1235     result = mmap(last_addr, bytes, PROT_READ | PROT_WRITE | OPT_PROT_EXEC,
1236                   GC_MMAP_FLAGS, fd, 0/* offset */);
1237     if (result == MAP_FAILED) return(0);
1238     last_addr = (ptr_t)result + bytes + GC_page_size - 1;
1239     last_addr = (ptr_t)((word)last_addr & ~(GC_page_size - 1));
1240     return((ptr_t)result);
1241 }
1242
1243 #else /* Not RS6000, not USE_MMAP */
1244 ptr_t GC_unix_get_mem(bytes)
1245 word bytes;
1246 {
1247   ptr_t result;
1248 # ifdef IRIX5
1249     /* Bare sbrk isn't thread safe.  Play by malloc rules.      */
1250     /* The equivalent may be needed on other systems as well.   */
1251     __LOCK_MALLOC();
1252 # endif
1253   {
1254     ptr_t cur_brk = (ptr_t)sbrk(0);
1255     SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
1256     
1257     if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
1258     if (lsbs != 0) {
1259         if((ptr_t)sbrk(GC_page_size - lsbs) == (ptr_t)(-1)) return(0);
1260     }
1261     result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
1262     if (result == (ptr_t)(-1)) result = 0;
1263   }
1264 # ifdef IRIX5
1265     __UNLOCK_MALLOC();
1266 # endif
1267   return(result);
1268 }
1269
1270 #endif /* Not USE_MMAP */
1271 #endif /* Not RS6000 */
1272
1273 # endif /* UN*X */
1274
1275 # ifdef OS2
1276
1277 void * os2_alloc(size_t bytes)
1278 {
1279     void * result;
1280
1281     if (DosAllocMem(&result, bytes, PAG_EXECUTE | PAG_READ |
1282                                     PAG_WRITE | PAG_COMMIT)
1283                     != NO_ERROR) {
1284         return(0);
1285     }
1286     if (result == 0) return(os2_alloc(bytes));
1287     return(result);
1288 }
1289
1290 # endif /* OS2 */
1291
1292
1293 # ifdef MSWIN32
1294 word GC_n_heap_bases = 0;
1295
1296 ptr_t GC_win32_get_mem(bytes)
1297 word bytes;
1298 {
1299     ptr_t result;
1300     
1301     if (GC_win32s) {
1302         /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE.    */
1303         /* There are also unconfirmed rumors of other           */
1304         /* problems, so we dodge the issue.                     */
1305         result = (ptr_t) GlobalAlloc(0, bytes + HBLKSIZE);
1306         result = (ptr_t)(((word)result + HBLKSIZE) & ~(HBLKSIZE-1));
1307     } else {
1308         result = (ptr_t) VirtualAlloc(NULL, bytes,
1309                                       MEM_COMMIT | MEM_RESERVE,
1310                                       PAGE_EXECUTE_READWRITE);
1311     }
1312     if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1313         /* If I read the documentation correctly, this can      */
1314         /* only happen if HBLKSIZE > 64k or not a power of 2.   */
1315     if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
1316     GC_heap_bases[GC_n_heap_bases++] = result;
1317     return(result);                       
1318 }
1319
1320 void GC_win32_free_heap ()
1321 {
1322     if (GC_win32s) {
1323         while (GC_n_heap_bases > 0) {
1324             GlobalFree (GC_heap_bases[--GC_n_heap_bases]);
1325             GC_heap_bases[GC_n_heap_bases] = 0;
1326         }
1327     }
1328 }
1329
1330
1331 # endif
1332
1333 #ifdef USE_MUNMAP
1334
1335 /* For now, this only works on some Unix-like systems.  If you  */
1336 /* have something else, don't define USE_MUNMAP.                */
1337 /* We assume ANSI C to support this feature.                    */
1338 #include <unistd.h>
1339 #include <sys/mman.h>
1340 #include <sys/stat.h>
1341 #include <sys/types.h>
1342 #include <fcntl.h>
1343
1344 /* Compute a page aligned starting address for the unmap        */
1345 /* operation on a block of size bytes starting at start.        */
1346 /* Return 0 if the block is too small to make this feasible.    */
1347 ptr_t GC_unmap_start(ptr_t start, word bytes)
1348 {
1349     ptr_t result = start;
1350     /* Round start to next page boundary.       */
1351         result += GC_page_size - 1;
1352         result = (ptr_t)((word)result & ~(GC_page_size - 1));
1353     if (result + GC_page_size > start + bytes) return 0;
1354     return result;
1355 }
1356
1357 /* Compute end address for an unmap operation on the indicated  */
1358 /* block.                                                       */
1359 ptr_t GC_unmap_end(ptr_t start, word bytes)
1360 {
1361     ptr_t end_addr = start + bytes;
1362     end_addr = (ptr_t)((word)end_addr & ~(GC_page_size - 1));
1363     return end_addr;
1364 }
1365
1366 /* We assume that GC_remap is called on exactly the same range  */
1367 /* as a previous call to GC_unmap.  It is safe to consistently  */
1368 /* round the endpoints in both places.                          */
1369 void GC_unmap(ptr_t start, word bytes)
1370 {
1371     ptr_t start_addr = GC_unmap_start(start, bytes);
1372     ptr_t end_addr = GC_unmap_end(start, bytes);
1373     word len = end_addr - start_addr;
1374     if (0 == start_addr) return;
1375     if (munmap(start_addr, len) != 0) ABORT("munmap failed");
1376     GC_unmapped_bytes += len;
1377 }
1378
1379
1380 void GC_remap(ptr_t start, word bytes)
1381 {
1382     static int zero_descr = -1;
1383     ptr_t start_addr = GC_unmap_start(start, bytes);
1384     ptr_t end_addr = GC_unmap_end(start, bytes);
1385     word len = end_addr - start_addr;
1386     ptr_t result;
1387
1388     if (-1 == zero_descr) zero_descr = open("/dev/zero", O_RDWR);
1389     if (0 == start_addr) return;
1390     result = mmap(start_addr, len, PROT_READ | PROT_WRITE | OPT_PROT_EXEC,
1391                   MAP_FIXED | MAP_PRIVATE, zero_descr, 0);
1392     if (result != start_addr) {
1393         ABORT("mmap remapping failed");
1394     }
1395     GC_unmapped_bytes -= len;
1396 }
1397
1398 /* Two adjacent blocks have already been unmapped and are about to      */
1399 /* be merged.  Unmap the whole block.  This typically requires          */
1400 /* that we unmap a small section in the middle that was not previously  */
1401 /* unmapped due to alignment constraints.                               */
1402 void GC_unmap_gap(ptr_t start1, word bytes1, ptr_t start2, word bytes2)
1403 {
1404     ptr_t start1_addr = GC_unmap_start(start1, bytes1);
1405     ptr_t end1_addr = GC_unmap_end(start1, bytes1);
1406     ptr_t start2_addr = GC_unmap_start(start2, bytes2);
1407     ptr_t end2_addr = GC_unmap_end(start2, bytes2);
1408     ptr_t start_addr = end1_addr;
1409     ptr_t end_addr = start2_addr;
1410     word len;
1411     GC_ASSERT(start1 + bytes1 == start2);
1412     if (0 == start1_addr) start_addr = GC_unmap_start(start1, bytes1 + bytes2);
1413     if (0 == start2_addr) end_addr = GC_unmap_end(start1, bytes1 + bytes2);
1414     if (0 == start_addr) return;
1415     len = end_addr - start_addr;
1416     if (len != 0 && munmap(start_addr, len) != 0) ABORT("munmap failed");
1417     GC_unmapped_bytes += len;
1418 }
1419
1420 #endif /* USE_MUNMAP */
1421
1422 /* Routine for pushing any additional roots.  In THREADS        */
1423 /* environment, this is also responsible for marking from       */
1424 /* thread stacks.  In the SRC_M3 case, it also handles          */
1425 /* global variables.                                            */
1426 #ifndef THREADS
1427 void (*GC_push_other_roots)() = 0;
1428 #else /* THREADS */
1429
1430 # ifdef PCR
1431 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
1432 {
1433     struct PCR_ThCtl_TInfoRep info;
1434     PCR_ERes result;
1435     
1436     info.ti_stkLow = info.ti_stkHi = 0;
1437     result = PCR_ThCtl_GetInfo(t, &info);
1438     GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi));
1439     return(result);
1440 }
1441
1442 /* Push the contents of an old object. We treat this as stack   */
1443 /* data only becasue that makes it robust against mark stack    */
1444 /* overflow.                                                    */
1445 PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data)
1446 {
1447     GC_push_all_stack((ptr_t)p, (ptr_t)p + size);
1448     return(PCR_ERes_okay);
1449 }
1450
1451
1452 void GC_default_push_other_roots()
1453 {
1454     /* Traverse data allocated by previous memory managers.             */
1455         {
1456           extern struct PCR_MM_ProcsRep * GC_old_allocator;
1457           
1458           if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false,
1459                                                    GC_push_old_obj, 0)
1460               != PCR_ERes_okay) {
1461               ABORT("Old object enumeration failed");
1462           }
1463         }
1464     /* Traverse all thread stacks. */
1465         if (PCR_ERes_IsErr(
1466                 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0))
1467               || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
1468               ABORT("Thread stack marking failed\n");
1469         }
1470 }
1471
1472 # endif /* PCR */
1473
1474 # ifdef SRC_M3
1475
1476 # ifdef ALL_INTERIOR_POINTERS
1477     --> misconfigured
1478 # endif
1479
1480
1481 extern void ThreadF__ProcessStacks();
1482
1483 void GC_push_thread_stack(start, stop)
1484 word start, stop;
1485 {
1486    GC_push_all_stack((ptr_t)start, (ptr_t)stop + sizeof(word));
1487 }
1488
1489 /* Push routine with M3 specific calling convention. */
1490 GC_m3_push_root(dummy1, p, dummy2, dummy3)
1491 word *p;
1492 ptr_t dummy1, dummy2;
1493 int dummy3;
1494 {
1495     word q = *p;
1496     
1497     if ((ptr_t)(q) >= GC_least_plausible_heap_addr
1498          && (ptr_t)(q) < GC_greatest_plausible_heap_addr) {
1499          GC_push_one_checked(q,FALSE);
1500     }
1501 }
1502
1503 /* M3 set equivalent to RTHeap.TracedRefTypes */
1504 typedef struct { int elts[1]; }  RefTypeSet;
1505 RefTypeSet GC_TracedRefTypes = {{0x1}};
1506
1507 /* From finalize.c */
1508 extern void GC_push_finalizer_structures();
1509
1510 /* From stubborn.c: */
1511 # ifdef STUBBORN_ALLOC
1512     extern GC_PTR * GC_changing_list_start;
1513 # endif
1514
1515
1516 void GC_default_push_other_roots()
1517 {
1518     /* Use the M3 provided routine for finding static roots.    */
1519     /* This is a bit dubious, since it presumes no C roots.     */
1520     /* We handle the collector roots explicitly.                */
1521        {
1522 #        ifdef STUBBORN_ALLOC
1523            GC_push_one(GC_changing_list_start);
1524 #        endif
1525          GC_push_finalizer_structures();
1526          RTMain__GlobalMapProc(GC_m3_push_root, 0, GC_TracedRefTypes);
1527        }
1528         if (GC_words_allocd > 0) {
1529             ThreadF__ProcessStacks(GC_push_thread_stack);
1530         }
1531         /* Otherwise this isn't absolutely necessary, and we have       */
1532         /* startup ordering problems.                                   */
1533 }
1534
1535 # endif /* SRC_M3 */
1536
1537 # if defined(SOLARIS_THREADS) || defined(WIN32_THREADS) \
1538      || defined(IRIX_THREADS) || defined(LINUX_THREADS) \
1539      || defined(IRIX_JDK_THREADS) || defined(HPUX_THREADS) \
1540      || defined(QUICK_THREADS)
1541
1542 extern void GC_push_all_stacks();
1543
1544 void GC_default_push_other_roots()
1545 {
1546     GC_push_all_stacks();
1547 }
1548
1549 # endif /* SOLARIS_THREADS || ... */
1550
1551 void (*GC_push_other_roots)() = GC_default_push_other_roots;
1552
1553 #endif
1554
1555 /*
1556  * Routines for accessing dirty  bits on virtual pages.
1557  * We plan to eventaually implement four strategies for doing so:
1558  * DEFAULT_VDB: A simple dummy implementation that treats every page
1559  *              as possibly dirty.  This makes incremental collection
1560  *              useless, but the implementation is still correct.
1561  * PCR_VDB:     Use PPCRs virtual dirty bit facility.
1562  * PROC_VDB:    Use the /proc facility for reading dirty bits.  Only
1563  *              works under some SVR4 variants.  Even then, it may be
1564  *              too slow to be entirely satisfactory.  Requires reading
1565  *              dirty bits for entire address space.  Implementations tend
1566  *              to assume that the client is a (slow) debugger.
1567  * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
1568  *              dirtied pages.  The implementation (and implementability)
1569  *              is highly system dependent.  This usually fails when system
1570  *              calls write to a protected page.  We prevent the read system
1571  *              call from doing so.  It is the clients responsibility to
1572  *              make sure that other system calls are similarly protected
1573  *              or write only to the stack.
1574  */
1575  
1576 GC_bool GC_dirty_maintained = FALSE;
1577
1578 # ifdef DEFAULT_VDB
1579
1580 /* All of the following assume the allocation lock is held, and */
1581 /* signals are disabled.                                        */
1582
1583 /* The client asserts that unallocated pages in the heap are never      */
1584 /* written.                                                             */
1585
1586 /* Initialize virtual dirty bit implementation.                 */
1587 void GC_dirty_init()
1588 {
1589     GC_dirty_maintained = TRUE;
1590 }
1591
1592 /* Retrieve system dirty bits for heap to a local buffer.       */
1593 /* Restore the systems notion of which pages are dirty.         */
1594 void GC_read_dirty()
1595 {}
1596
1597 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer?    */
1598 /* If the actual page size is different, this returns TRUE if any       */
1599 /* of the pages overlapping h are dirty.  This routine may err on the   */
1600 /* side of labelling pages as dirty (and this implementation does).     */
1601 /*ARGSUSED*/
1602 GC_bool GC_page_was_dirty(h)
1603 struct hblk *h;
1604 {
1605     return(TRUE);
1606 }
1607
1608 /*
1609  * The following two routines are typically less crucial.  They matter
1610  * most with large dynamic libraries, or if we can't accurately identify
1611  * stacks, e.g. under Solaris 2.X.  Otherwise the following default
1612  * versions are adequate.
1613  */
1614  
1615 /* Could any valid GC heap pointer ever have been written to this page? */
1616 /*ARGSUSED*/
1617 GC_bool GC_page_was_ever_dirty(h)
1618 struct hblk *h;
1619 {
1620     return(TRUE);
1621 }
1622
1623 /* Reset the n pages starting at h to "was never dirty" status. */
1624 void GC_is_fresh(h, n)
1625 struct hblk *h;
1626 word n;
1627 {
1628 }
1629
1630 /* A call hints that h is about to be written.  */
1631 /* May speed up some dirty bit implementations. */
1632 /*ARGSUSED*/
1633 void GC_write_hint(h)
1634 struct hblk *h;
1635 {
1636 }
1637
1638 # endif /* DEFAULT_VDB */
1639
1640
1641 # ifdef MPROTECT_VDB
1642
1643 /*
1644  * See DEFAULT_VDB for interface descriptions.
1645  */
1646
1647 /*
1648  * This implementation maintains dirty bits itself by catching write
1649  * faults and keeping track of them.  We assume nobody else catches
1650  * SIGBUS or SIGSEGV.  We assume no write faults occur in system calls
1651  * except as a result of a read system call.  This means clients must
1652  * either ensure that system calls do not touch the heap, or must
1653  * provide their own wrappers analogous to the one for read.
1654  * We assume the page size is a multiple of HBLKSIZE.
1655  * This implementation is currently SunOS 4.X and IRIX 5.X specific, though we
1656  * tried to use portable code where easily possible.  It is known
1657  * not to work under a number of other systems.
1658  */
1659
1660 # ifndef MSWIN32
1661
1662 #   include <sys/mman.h>
1663 #   include <signal.h>
1664 #   include <sys/syscall.h>
1665
1666 #   define PROTECT(addr, len) \
1667           if (mprotect((caddr_t)(addr), (size_t)(len), \
1668                        PROT_READ | OPT_PROT_EXEC) < 0) { \
1669             ABORT("mprotect failed"); \
1670           }
1671 #   define UNPROTECT(addr, len) \
1672           if (mprotect((caddr_t)(addr), (size_t)(len), \
1673                        PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
1674             ABORT("un-mprotect failed"); \
1675           }
1676           
1677 # else
1678
1679 #   include <signal.h>
1680
1681     static DWORD protect_junk;
1682 #   define PROTECT(addr, len) \
1683           if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
1684                               &protect_junk)) { \
1685             DWORD last_error = GetLastError(); \
1686             GC_printf1("Last error code: %lx\n", last_error); \
1687             ABORT("VirtualProtect failed"); \
1688           }
1689 #   define UNPROTECT(addr, len) \
1690           if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
1691                               &protect_junk)) { \
1692             ABORT("un-VirtualProtect failed"); \
1693           }
1694           
1695 # endif
1696
1697 #if defined(SUNOS4) || defined(FREEBSD)
1698     typedef void (* SIG_PF)();
1699 #endif
1700 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX)
1701 # ifdef __STDC__
1702     typedef void (* SIG_PF)(int);
1703 # else
1704     typedef void (* SIG_PF)();
1705 # endif
1706 #endif
1707 #if defined(MSWIN32)
1708     typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
1709 #   undef SIG_DFL
1710 #   define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
1711 #endif
1712
1713 #if defined(IRIX5) || defined(OSF1)
1714     typedef void (* REAL_SIG_PF)(int, int, struct sigcontext *);
1715 #endif
1716 #if defined(SUNOS5SIGS)
1717 # ifdef HPUX
1718 #   define SIGINFO __siginfo
1719 # else
1720 #   define SIGINFO siginfo
1721 # endif
1722 # ifdef __STDC__
1723     typedef void (* REAL_SIG_PF)(int, struct SIGINFO *, void *);
1724 # else
1725     typedef void (* REAL_SIG_PF)();
1726 # endif
1727 #endif
1728 #if defined(LINUX)
1729 #   include <linux/version.h>
1730 #   if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA) || defined(IA64)
1731       typedef struct sigcontext s_c;
1732 #   else
1733       typedef struct sigcontext_struct s_c;
1734 #   endif
1735 #   if defined(ALPHA) || defined(M68K)
1736       typedef void (* REAL_SIG_PF)(int, int, s_c *);
1737 #   else
1738 #     if defined(IA64)
1739         typedef void (* REAL_SIG_PF)(int, siginfo_t *, s_c *);
1740 #     else
1741         typedef void (* REAL_SIG_PF)(int, s_c);
1742 #     endif
1743 #   endif
1744 #   ifdef ALPHA
1745     /* Retrieve fault address from sigcontext structure by decoding     */
1746     /* instruction.                                                     */
1747     char * get_fault_addr(s_c *sc) {
1748         unsigned instr;
1749         word faultaddr;
1750
1751         instr = *((unsigned *)(sc->sc_pc));
1752         faultaddr = sc->sc_regs[(instr >> 16) & 0x1f];
1753         faultaddr += (word) (((int)instr << 16) >> 16);
1754         return (char *)faultaddr;
1755     }
1756 #   endif /* !ALPHA */
1757 # endif
1758
1759 SIG_PF GC_old_bus_handler;
1760 SIG_PF GC_old_segv_handler;     /* Also old MSWIN32 ACCESS_VIOLATION filter */
1761
1762 /*ARGSUSED*/
1763 # if defined (SUNOS4) || defined(FREEBSD)
1764     void GC_write_fault_handler(sig, code, scp, addr)
1765     int sig, code;
1766     struct sigcontext *scp;
1767     char * addr;
1768 #   ifdef SUNOS4
1769 #     define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
1770 #     define CODE_OK (FC_CODE(code) == FC_PROT \
1771                     || (FC_CODE(code) == FC_OBJERR \
1772                        && FC_ERRNO(code) == FC_PROT))
1773 #   endif
1774 #   ifdef FREEBSD
1775 #     define SIG_OK (sig == SIGBUS)
1776 #     define CODE_OK (code == BUS_PAGE_FAULT)
1777 #   endif
1778 # endif
1779 # if defined(IRIX5) || defined(OSF1)
1780 #   include <errno.h>
1781     void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
1782 #   define SIG_OK (sig == SIGSEGV)
1783 #   ifdef OSF1
1784 #     define CODE_OK (code == 2 /* experimentally determined */)
1785 #   endif
1786 #   ifdef IRIX5
1787 #     define CODE_OK (code == EACCES)
1788 #   endif
1789 # endif
1790 # if defined(LINUX)
1791 #   if defined(ALPHA) || defined(M68K)
1792       void GC_write_fault_handler(int sig, int code, s_c * sc)
1793 #   else
1794 #     if defined(IA64)
1795         void GC_write_fault_handler(int sig, siginfo_t * si, s_c * scp)
1796 #     else
1797         void GC_write_fault_handler(int sig, s_c sc)
1798 #     endif
1799 #   endif
1800 #   define SIG_OK (sig == SIGSEGV)
1801 #   define CODE_OK TRUE
1802         /* Empirically c.trapno == 14, on IA32, but is that useful?     */
1803         /* Should probably consider alignment issues on other           */
1804         /* architectures.                                               */
1805 # endif
1806 # if defined(SUNOS5SIGS)
1807 #  ifdef __STDC__
1808     void GC_write_fault_handler(int sig, struct SIGINFO *scp, void * context)
1809 #  else
1810     void GC_write_fault_handler(sig, scp, context)
1811     int sig;
1812     struct SIGINFO *scp;
1813     void * context;
1814 #  endif
1815 #   ifdef HPUX
1816 #     define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
1817 #     define CODE_OK (scp -> si_code == SEGV_ACCERR) \
1818                      || (scp -> si_code == BUS_ADRERR) \
1819                      || (scp -> si_code == BUS_UNKNOWN) \
1820                      || (scp -> si_code == SEGV_UNKNOWN) \
1821                      || (scp -> si_code == BUS_OBJERR)
1822 #   else
1823 #     define SIG_OK (sig == SIGSEGV)
1824 #     define CODE_OK (scp -> si_code == SEGV_ACCERR)
1825 #   endif
1826 # endif
1827 # if defined(MSWIN32)
1828     LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info)
1829 #   define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
1830                         EXCEPTION_ACCESS_VIOLATION)
1831 #   define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
1832                         /* Write fault */
1833 # endif
1834 {
1835     register unsigned i;
1836 #   ifdef IRIX5
1837         char * addr = (char *) (size_t) (scp -> sc_badvaddr);
1838 #   endif
1839 #   if defined(OSF1) && defined(ALPHA)
1840         char * addr = (char *) (scp -> sc_traparg_a0);
1841 #   endif
1842 #   ifdef SUNOS5SIGS
1843         char * addr = (char *) (scp -> si_addr);
1844 #   endif
1845 #   ifdef LINUX
1846 #     ifdef I386
1847         char * addr = (char *) (sc.cr2);
1848 #     else
1849 #       if defined(M68K)
1850           char * addr = NULL;
1851
1852           struct sigcontext *scp = (struct sigcontext *)(&sc);
1853
1854           int format = (scp->sc_formatvec >> 12) & 0xf;
1855           unsigned long *framedata = (unsigned long *)(scp + 1); 
1856           unsigned long ea;
1857
1858           if (format == 0xa || format == 0xb) {
1859                 /* 68020/030 */
1860                 ea = framedata[2];
1861           } else if (format == 7) {
1862                 /* 68040 */
1863                 ea = framedata[3];
1864           } else if (format == 4) {
1865                 /* 68060 */
1866                 ea = framedata[0];
1867                 if (framedata[1] & 0x08000000) {
1868                         /* correct addr on misaligned access */
1869                         ea = (ea+4095)&(~4095);
1870                 }
1871           }     
1872           addr = (char *)ea;
1873 #       else
1874 #         ifdef ALPHA
1875             char * addr = get_fault_addr(sc);
1876 #         else
1877 #           ifdef IA64
1878               char * addr = si -> si_addr;
1879 #           else
1880 #             if defined(POWERPC)
1881                 char * addr = (char *) (sc.regs->dar);
1882 #             else
1883                 --> architecture not supported
1884 #             endif
1885 #           endif
1886 #         endif
1887 #       endif
1888 #     endif
1889 #   endif
1890 #   if defined(MSWIN32)
1891         char * addr = (char *) (exc_info -> ExceptionRecord
1892                                 -> ExceptionInformation[1]);
1893 #       define sig SIGSEGV
1894 #   endif
1895     
1896     if (SIG_OK && CODE_OK) {
1897         register struct hblk * h =
1898                         (struct hblk *)((word)addr & ~(GC_page_size-1));
1899         GC_bool in_allocd_block;
1900         
1901 #       ifdef SUNOS5SIGS
1902             /* Address is only within the correct physical page.        */
1903             in_allocd_block = FALSE;
1904             for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
1905               if (HDR(h+i) != 0) {
1906                 in_allocd_block = TRUE;
1907               }
1908             }
1909 #       else
1910             in_allocd_block = (HDR(addr) != 0);
1911 #       endif
1912         if (!in_allocd_block) {
1913             /* Heap blocks now begin and end on page boundaries */
1914             SIG_PF old_handler;
1915             
1916             if (sig == SIGSEGV) {
1917                 old_handler = GC_old_segv_handler;
1918             } else {
1919                 old_handler = GC_old_bus_handler;
1920             }
1921             if (old_handler == SIG_DFL) {
1922 #               ifndef MSWIN32
1923                     GC_err_printf1("Segfault at 0x%lx\n", addr);
1924                     ABORT("Unexpected bus error or segmentation fault");
1925 #               else
1926                     return(EXCEPTION_CONTINUE_SEARCH);
1927 #               endif
1928             } else {
1929 #               if defined (SUNOS4) || defined(FREEBSD)
1930                     (*old_handler) (sig, code, scp, addr);
1931                     return;
1932 #               endif
1933 #               if defined (SUNOS5SIGS)
1934                     (*(REAL_SIG_PF)old_handler) (sig, scp, context);
1935                     return;
1936 #               endif
1937 #               if defined (LINUX)
1938 #                   if defined(ALPHA) || defined(M68K)
1939                         (*(REAL_SIG_PF)old_handler) (sig, code, sc);
1940 #                   else 
1941 #                     if defined(IA64)
1942                         (*(REAL_SIG_PF)old_handler) (sig, si, scp);
1943 #                     else
1944                         (*(REAL_SIG_PF)old_handler) (sig, sc);
1945 #                     endif
1946 #                   endif
1947                     return;
1948 #               endif
1949 #               if defined (IRIX5) || defined(OSF1)
1950                     (*(REAL_SIG_PF)old_handler) (sig, code, scp);
1951                     return;
1952 #               endif
1953 #               ifdef MSWIN32
1954                     return((*old_handler)(exc_info));
1955 #               endif
1956             }
1957         }
1958         for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
1959             register int index = PHT_HASH(h+i);
1960             
1961             set_pht_entry_from_index(GC_dirty_pages, index);
1962         }
1963         UNPROTECT(h, GC_page_size);
1964 #       if defined(OSF1) || defined(LINUX)
1965             /* These reset the signal handler each time by default. */
1966             signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
1967 #       endif
1968         /* The write may not take place before dirty bits are read.     */
1969         /* But then we'll fault again ...                               */
1970 #       ifdef MSWIN32
1971             return(EXCEPTION_CONTINUE_EXECUTION);
1972 #       else
1973             return;
1974 #       endif
1975     }
1976 #ifdef MSWIN32
1977     return EXCEPTION_CONTINUE_SEARCH;
1978 #else
1979     GC_err_printf1("Segfault at 0x%lx\n", addr);
1980     ABORT("Unexpected bus error or segmentation fault");
1981 #endif
1982 }
1983
1984 /*
1985  * We hold the allocation lock.  We expect block h to be written
1986  * shortly.
1987  */
1988 void GC_write_hint(h)
1989 struct hblk *h;
1990 {
1991     register struct hblk * h_trunc;
1992     register unsigned i;
1993     register GC_bool found_clean;
1994     
1995     if (!GC_dirty_maintained) return;
1996     h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1));
1997     found_clean = FALSE;
1998     for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
1999         register int index = PHT_HASH(h_trunc+i);
2000             
2001         if (!get_pht_entry_from_index(GC_dirty_pages, index)) {
2002             found_clean = TRUE;
2003             set_pht_entry_from_index(GC_dirty_pages, index);
2004         }
2005     }
2006     if (found_clean) {
2007         UNPROTECT(h_trunc, GC_page_size);
2008     }
2009 }
2010
2011 void GC_dirty_init()
2012 {
2013 #if defined(SUNOS5SIGS) || defined(IRIX5) /* || defined(OSF1) */
2014     struct sigaction    act, oldact;
2015 #   ifdef IRIX5
2016         act.sa_flags    = SA_RESTART;
2017         act.sa_handler  = GC_write_fault_handler;
2018 #   else
2019         act.sa_flags    = SA_RESTART | SA_SIGINFO;
2020         act.sa_sigaction = GC_write_fault_handler;
2021 #   endif
2022     (void)sigemptyset(&act.sa_mask); 
2023 #endif
2024 #   ifdef PRINTSTATS
2025         GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2026 #   endif
2027     GC_dirty_maintained = TRUE;
2028     if (GC_page_size % HBLKSIZE != 0) {
2029         GC_err_printf0("Page size not multiple of HBLKSIZE\n");
2030         ABORT("Page size not multiple of HBLKSIZE");
2031     }
2032 #   if defined(SUNOS4) || defined(FREEBSD)
2033       GC_old_bus_handler = signal(SIGBUS, GC_write_fault_handler);
2034       if (GC_old_bus_handler == SIG_IGN) {
2035         GC_err_printf0("Previously ignored bus error!?");
2036         GC_old_bus_handler = SIG_DFL;
2037       }
2038       if (GC_old_bus_handler != SIG_DFL) {
2039 #       ifdef PRINTSTATS
2040           GC_err_printf0("Replaced other SIGBUS handler\n");
2041 #       endif
2042       }
2043 #   endif
2044 #   if defined(OSF1) || defined(SUNOS4) || defined(LINUX)
2045       GC_old_segv_handler = signal(SIGSEGV, (SIG_PF)GC_write_fault_handler);
2046       if (GC_old_segv_handler == SIG_IGN) {
2047         GC_err_printf0("Previously ignored segmentation violation!?");
2048         GC_old_segv_handler = SIG_DFL;
2049       }
2050       if (GC_old_segv_handler != SIG_DFL) {
2051 #       ifdef PRINTSTATS
2052           GC_err_printf0("Replaced other SIGSEGV handler\n");
2053 #       endif
2054       }
2055 #   endif
2056 #   if defined(SUNOS5SIGS) || defined(IRIX5)
2057 #     if defined(IRIX_THREADS) || defined(IRIX_JDK_THREADS)
2058         sigaction(SIGSEGV, 0, &oldact);
2059         sigaction(SIGSEGV, &act, 0);
2060 #     else
2061         sigaction(SIGSEGV, &act, &oldact);
2062 #     endif
2063 #     if defined(_sigargs)
2064         /* This is Irix 5.x, not 6.x.  Irix 5.x does not have   */
2065         /* sa_sigaction.                                        */
2066         GC_old_segv_handler = oldact.sa_handler;
2067 #     else /* Irix 6.x or SUNOS5SIGS */
2068         if (oldact.sa_flags & SA_SIGINFO) {
2069           GC_old_segv_handler = (SIG_PF)(oldact.sa_sigaction);
2070         } else {
2071           GC_old_segv_handler = oldact.sa_handler;
2072         }
2073 #     endif
2074       if (GC_old_segv_handler == SIG_IGN) {
2075              GC_err_printf0("Previously ignored segmentation violation!?");
2076              GC_old_segv_handler = SIG_DFL;
2077       }
2078       if (GC_old_segv_handler != SIG_DFL) {
2079 #       ifdef PRINTSTATS
2080           GC_err_printf0("Replaced other SIGSEGV handler\n");
2081 #       endif
2082       }
2083 #     ifdef HPUX
2084           sigaction(SIGBUS, &act, &oldact);
2085           GC_old_bus_handler = oldact.sa_handler;
2086           if (GC_old_segv_handler != SIG_DFL) {
2087 #           ifdef PRINTSTATS
2088               GC_err_printf0("Replaced other SIGBUS handler\n");
2089 #           endif
2090           }
2091 #     endif
2092 #    endif
2093 #   if defined(MSWIN32)
2094       GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler);
2095       if (GC_old_segv_handler != NULL) {
2096 #       ifdef PRINTSTATS
2097           GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
2098 #       endif
2099       } else {
2100           GC_old_segv_handler = SIG_DFL;
2101       }
2102 #   endif
2103 }
2104
2105
2106
2107 void GC_protect_heap()
2108 {
2109     ptr_t start;
2110     word len;
2111     unsigned i;
2112     
2113     for (i = 0; i < GC_n_heap_sects; i++) {
2114         start = GC_heap_sects[i].hs_start;
2115         len = GC_heap_sects[i].hs_bytes;
2116         PROTECT(start, len);
2117     }
2118 }
2119
2120 /* We assume that either the world is stopped or its OK to lose dirty   */
2121 /* bits while this is happenning (as in GC_enable_incremental).         */
2122 void GC_read_dirty()
2123 {
2124     BCOPY((word *)GC_dirty_pages, GC_grungy_pages,
2125           (sizeof GC_dirty_pages));
2126     BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages));
2127     GC_protect_heap();
2128 }
2129
2130 GC_bool GC_page_was_dirty(h)
2131 struct hblk * h;
2132 {
2133     register word index = PHT_HASH(h);
2134     
2135     return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index));
2136 }
2137
2138 /*
2139  * Acquiring the allocation lock here is dangerous, since this
2140  * can be called from within GC_call_with_alloc_lock, and the cord
2141  * package does so.  On systems that allow nested lock acquisition, this
2142  * happens to work.
2143  * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
2144  */
2145  
2146 void GC_begin_syscall()
2147 {
2148     if (!I_HOLD_LOCK()) LOCK();
2149 }
2150
2151 void GC_end_syscall()
2152 {
2153     if (!I_HOLD_LOCK()) UNLOCK();
2154 }
2155
2156 void GC_unprotect_range(addr, len)
2157 ptr_t addr;
2158 word len;
2159 {
2160     struct hblk * start_block;
2161     struct hblk * end_block;
2162     register struct hblk *h;
2163     ptr_t obj_start;
2164     
2165     if (!GC_incremental) return;
2166     obj_start = GC_base(addr);
2167     if (obj_start == 0) return;
2168     if (GC_base(addr + len - 1) != obj_start) {
2169         ABORT("GC_unprotect_range(range bigger than object)");
2170     }
2171     start_block = (struct hblk *)((word)addr & ~(GC_page_size - 1));
2172     end_block = (struct hblk *)((word)(addr + len - 1) & ~(GC_page_size - 1));
2173     end_block += GC_page_size/HBLKSIZE - 1;
2174     for (h = start_block; h <= end_block; h++) {
2175         register word index = PHT_HASH(h);
2176         
2177         set_pht_entry_from_index(GC_dirty_pages, index);
2178     }
2179     UNPROTECT(start_block,
2180               ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE);
2181 }
2182
2183 #ifndef MSWIN32
2184 /* Replacement for UNIX system call.     */
2185 /* Other calls that write to the heap    */
2186 /* should be handled similarly.          */
2187 # if defined(__STDC__) && !defined(SUNOS4)
2188 #   include <unistd.h>
2189     ssize_t read(int fd, void *buf, size_t nbyte)
2190 # else
2191 #   ifndef LINT
2192       int read(fd, buf, nbyte)
2193 #   else
2194       int GC_read(fd, buf, nbyte)
2195 #   endif
2196     int fd;
2197     char *buf;
2198     int nbyte;
2199 # endif
2200 {
2201     int result;
2202     
2203     GC_begin_syscall();
2204     GC_unprotect_range(buf, (word)nbyte);
2205 #   ifdef IRIX5
2206         /* Indirect system call may not always be easily available.     */
2207         /* We could call _read, but that would interfere with the       */
2208         /* libpthread interception of read.                             */
2209         {
2210             struct iovec iov;
2211
2212             iov.iov_base = buf;
2213             iov.iov_len = nbyte;
2214             result = readv(fd, &iov, 1);
2215         }
2216 #   else
2217         result = syscall(SYS_read, fd, buf, nbyte);
2218 #   endif
2219     GC_end_syscall();
2220     return(result);
2221 }
2222 #endif /* !MSWIN32 */
2223
2224 /*ARGSUSED*/
2225 GC_bool GC_page_was_ever_dirty(h)
2226 struct hblk *h;
2227 {
2228     return(TRUE);
2229 }
2230
2231 /* Reset the n pages starting at h to "was never dirty" status. */
2232 /*ARGSUSED*/
2233 void GC_is_fresh(h, n)
2234 struct hblk *h;
2235 word n;
2236 {
2237 }
2238
2239 # endif /* MPROTECT_VDB */
2240
2241 # ifdef PROC_VDB
2242
2243 /*
2244  * See DEFAULT_VDB for interface descriptions.
2245  */
2246  
2247 /*
2248  * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
2249  * from which we can read page modified bits.  This facility is far from
2250  * optimal (e.g. we would like to get the info for only some of the
2251  * address space), but it avoids intercepting system calls.
2252  */
2253
2254 #include <errno.h>
2255 #include <sys/types.h>
2256 #include <sys/signal.h>
2257 #include <sys/fault.h>
2258 #include <sys/syscall.h>
2259 #include <sys/procfs.h>
2260 #include <sys/stat.h>
2261 #include <fcntl.h>
2262
2263 #define INITIAL_BUF_SZ 4096
2264 word GC_proc_buf_size = INITIAL_BUF_SZ;
2265 char *GC_proc_buf;
2266
2267 #ifdef SOLARIS_THREADS
2268 /* We don't have exact sp values for threads.  So we count on   */
2269 /* occasionally declaring stack pages to be fresh.  Thus we     */
2270 /* need a real implementation of GC_is_fresh.  We can't clear   */
2271 /* entries in GC_written_pages, since that would declare all    */
2272 /* pages with the given hash address to be fresh.               */
2273 #   define MAX_FRESH_PAGES 8*1024       /* Must be power of 2 */
2274     struct hblk ** GC_fresh_pages;      /* A direct mapped cache.       */
2275                                         /* Collisions are dropped.      */
2276
2277 #   define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
2278 #   define ADD_FRESH_PAGE(h) \
2279         GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
2280 #   define PAGE_IS_FRESH(h) \
2281         (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
2282 #endif
2283
2284 /* Add all pages in pht2 to pht1 */
2285 void GC_or_pages(pht1, pht2)
2286 page_hash_table pht1, pht2;
2287 {
2288     register int i;
2289     
2290     for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
2291 }
2292
2293 int GC_proc_fd;
2294
2295 void GC_dirty_init()
2296 {
2297     int fd;
2298     char buf[30];
2299
2300     GC_dirty_maintained = TRUE;
2301     if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
2302         register int i;
2303     
2304         for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
2305 #       ifdef PRINTSTATS
2306             GC_printf1("Allocated words:%lu:all pages may have been written\n",
2307                        (unsigned long)
2308                                 (GC_words_allocd + GC_words_allocd_before_gc));
2309 #       endif       
2310     }
2311     sprintf(buf, "/proc/%d", getpid());
2312     fd = open(buf, O_RDONLY);
2313     if (fd < 0) {
2314         ABORT("/proc open failed");
2315     }
2316     GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
2317     close(fd);
2318     if (GC_proc_fd < 0) {
2319         ABORT("/proc ioctl failed");
2320     }
2321     GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size);
2322 #   ifdef SOLARIS_THREADS
2323         GC_fresh_pages = (struct hblk **)
2324           GC_scratch_alloc(MAX_FRESH_PAGES * sizeof (struct hblk *));
2325         if (GC_fresh_pages == 0) {
2326             GC_err_printf0("No space for fresh pages\n");
2327             EXIT();
2328         }
2329         BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
2330 #   endif
2331 }
2332
2333 /* Ignore write hints. They don't help us here. */
2334 /*ARGSUSED*/
2335 void GC_write_hint(h)
2336 struct hblk *h;
2337 {
2338 }
2339
2340 #ifdef SOLARIS_THREADS
2341 #   define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
2342 #else
2343 #   define READ(fd,buf,nbytes) read(fd, buf, nbytes)
2344 #endif
2345
2346 void GC_read_dirty()
2347 {
2348     unsigned long ps, np;
2349     int nmaps;
2350     ptr_t vaddr;
2351     struct prasmap * map;
2352     char * bufp;
2353     ptr_t current_addr, limit;
2354     int i;
2355 int dummy;
2356
2357     BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
2358     
2359     bufp = GC_proc_buf;
2360     if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
2361 #       ifdef PRINTSTATS
2362             GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
2363                        GC_proc_buf_size);
2364 #       endif       
2365         {
2366             /* Retry with larger buffer. */
2367             word new_size = 2 * GC_proc_buf_size;
2368             char * new_buf = GC_scratch_alloc(new_size);
2369             
2370             if (new_buf != 0) {
2371                 GC_proc_buf = bufp = new_buf;
2372                 GC_proc_buf_size = new_size;
2373             }
2374             if (syscall(SYS_read, GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
2375                 WARN("Insufficient space for /proc read\n", 0);
2376                 /* Punt:        */
2377                 memset(GC_grungy_pages, 0xff, sizeof (page_hash_table));
2378                 memset(GC_written_pages, 0xff, sizeof(page_hash_table));
2379 #               ifdef SOLARIS_THREADS
2380                     BZERO(GC_fresh_pages,
2381                           MAX_FRESH_PAGES * sizeof (struct hblk *)); 
2382 #               endif
2383                 return;
2384             }
2385         }
2386     }
2387     /* Copy dirty bits into GC_grungy_pages */
2388         nmaps = ((struct prpageheader *)bufp) -> pr_nmap;
2389         /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
2390                      nmaps, PG_REFERENCED, PG_MODIFIED); */
2391         bufp = bufp + sizeof(struct prpageheader);
2392         for (i = 0; i < nmaps; i++) {
2393             map = (struct prasmap *)bufp;
2394             vaddr = (ptr_t)(map -> pr_vaddr);
2395             ps = map -> pr_pagesize;
2396             np = map -> pr_npage;
2397             /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
2398             limit = vaddr + ps * np;
2399             bufp += sizeof (struct prasmap);
2400             for (current_addr = vaddr;
2401                  current_addr < limit; current_addr += ps){
2402                 if ((*bufp++) & PG_MODIFIED) {
2403                     register struct hblk * h = (struct hblk *) current_addr;
2404                     
2405                     while ((ptr_t)h < current_addr + ps) {
2406                         register word index = PHT_HASH(h);
2407                         
2408                         set_pht_entry_from_index(GC_grungy_pages, index);
2409 #                       ifdef SOLARIS_THREADS
2410                           {
2411                             register int slot = FRESH_PAGE_SLOT(h);
2412                             
2413                             if (GC_fresh_pages[slot] == h) {
2414                                 GC_fresh_pages[slot] = 0;
2415                             }
2416                           }
2417 #                       endif
2418                         h++;
2419                     }
2420                 }
2421             }
2422             bufp += sizeof(long) - 1;
2423             bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1));
2424         }
2425     /* Update GC_written_pages. */
2426         GC_or_pages(GC_written_pages, GC_grungy_pages);
2427 #   ifdef SOLARIS_THREADS
2428       /* Make sure that old stacks are considered completely clean      */
2429       /* unless written again.                                          */
2430         GC_old_stacks_are_fresh();
2431 #   endif
2432 }
2433
2434 #undef READ
2435
2436 GC_bool GC_page_was_dirty(h)
2437 struct hblk *h;
2438 {
2439     register word index = PHT_HASH(h);
2440     register GC_bool result;
2441     
2442     result = get_pht_entry_from_index(GC_grungy_pages, index);
2443 #   ifdef SOLARIS_THREADS
2444         if (result && PAGE_IS_FRESH(h)) result = FALSE;
2445         /* This happens only if page was declared fresh since   */
2446         /* the read_dirty call, e.g. because it's in an unused  */
2447         /* thread stack.  It's OK to treat it as clean, in      */
2448         /* that case.  And it's consistent with                 */
2449         /* GC_page_was_ever_dirty.                              */
2450 #   endif
2451     return(result);
2452 }
2453
2454 GC_bool GC_page_was_ever_dirty(h)
2455 struct hblk *h;
2456 {
2457     register word index = PHT_HASH(h);
2458     register GC_bool result;
2459     
2460     result = get_pht_entry_from_index(GC_written_pages, index);
2461 #   ifdef SOLARIS_THREADS
2462         if (result && PAGE_IS_FRESH(h)) result = FALSE;
2463 #   endif
2464     return(result);
2465 }
2466
2467 /* Caller holds allocation lock.        */
2468 void GC_is_fresh(h, n)
2469 struct hblk *h;
2470 word n;
2471 {
2472
2473     register word index;
2474     
2475 #   ifdef SOLARIS_THREADS
2476       register word i;
2477       
2478       if (GC_fresh_pages != 0) {
2479         for (i = 0; i < n; i++) {
2480           ADD_FRESH_PAGE(h + i);
2481         }
2482       }
2483 #   endif
2484 }
2485
2486 # endif /* PROC_VDB */
2487
2488
2489 # ifdef PCR_VDB
2490
2491 # include "vd/PCR_VD.h"
2492
2493 # define NPAGES (32*1024)       /* 128 MB */
2494
2495 PCR_VD_DB  GC_grungy_bits[NPAGES];
2496
2497 ptr_t GC_vd_base;       /* Address corresponding to GC_grungy_bits[0]   */
2498                         /* HBLKSIZE aligned.                            */
2499
2500 void GC_dirty_init()
2501 {
2502     GC_dirty_maintained = TRUE;
2503     /* For the time being, we assume the heap generally grows up */
2504     GC_vd_base = GC_heap_sects[0].hs_start;
2505     if (GC_vd_base == 0) {
2506         ABORT("Bad initial heap segment");
2507     }
2508     if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE)
2509         != PCR_ERes_okay) {
2510         ABORT("dirty bit initialization failed");
2511     }
2512 }
2513
2514 void GC_read_dirty()
2515 {
2516     /* lazily enable dirty bits on newly added heap sects */
2517     {
2518         static int onhs = 0;
2519         int nhs = GC_n_heap_sects;
2520         for( ; onhs < nhs; onhs++ ) {
2521             PCR_VD_WriteProtectEnable(
2522                     GC_heap_sects[onhs].hs_start,
2523                     GC_heap_sects[onhs].hs_bytes );
2524         }
2525     }
2526
2527
2528     if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits)
2529         != PCR_ERes_okay) {
2530         ABORT("dirty bit read failed");
2531     }
2532 }
2533
2534 GC_bool GC_page_was_dirty(h)
2535 struct hblk *h;
2536 {
2537     if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
2538         return(TRUE);
2539     }
2540     return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
2541 }
2542
2543 /*ARGSUSED*/
2544 void GC_write_hint(h)
2545 struct hblk *h;
2546 {
2547     PCR_VD_WriteProtectDisable(h, HBLKSIZE);
2548     PCR_VD_WriteProtectEnable(h, HBLKSIZE);
2549 }
2550
2551 # endif /* PCR_VDB */
2552
2553 /*
2554  * Call stack save code for debugging.
2555  * Should probably be in mach_dep.c, but that requires reorganization.
2556  */
2557 #if defined(SPARC) && !defined(LINUX)
2558 #   if defined(SUNOS4)
2559 #     include <machine/frame.h>
2560 #   else
2561 #     if defined (DRSNX)
2562 #       include <sys/sparc/frame.h>
2563 #     else
2564 #        if defined(OPENBSD)
2565 #          include <frame.h>
2566 #        else
2567 #          include <sys/frame.h>
2568 #        endif
2569 #     endif
2570 #   endif
2571 #   if NARGS > 6
2572         --> We only know how to to get the first 6 arguments
2573 #   endif
2574
2575 #ifdef SAVE_CALL_CHAIN
2576 /* Fill in the pc and argument information for up to NFRAMES of my      */
2577 /* callers.  Ignore my frame and my callers frame.                      */
2578
2579 #ifdef OPENBSD
2580 #  define FR_SAVFP fr_fp
2581 #  define FR_SAVPC fr_pc
2582 #else
2583 #  define FR_SAVFP fr_savfp
2584 #  define FR_SAVPC fr_savpc
2585 #endif
2586
2587 void GC_save_callers (info) 
2588 struct callinfo info[NFRAMES];
2589 {
2590   struct frame *frame;
2591   struct frame *fp;
2592   int nframes = 0;
2593   word GC_save_regs_in_stack();
2594
2595   frame = (struct frame *) GC_save_regs_in_stack ();
2596   
2597   for (fp = frame -> FR_SAVFP; fp != 0 && nframes < NFRAMES;
2598        fp = fp -> FR_SAVFP, nframes++) {
2599       register int i;
2600       
2601       info[nframes].ci_pc = fp->FR_SAVPC;
2602       for (i = 0; i < NARGS; i++) {
2603         info[nframes].ci_arg[i] = ~(fp->fr_arg[i]);
2604       }
2605   }
2606   if (nframes < NFRAMES) info[nframes].ci_pc = 0;
2607 }
2608
2609 #endif /* SAVE_CALL_CHAIN */
2610 #endif /* SPARC */
2611
2612
2613