OSDN Git Service

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