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