OSDN Git Service

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