Back to index

lightning-sunbird  0.9+nobinonly
os_dep.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 1991-1995 by Xerox Corporation.  All rights reserved.
00003  * Copyright (c) 1996-1997 by Silicon Graphics.  All rights reserved.
00004  *
00005  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
00006  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
00007  *
00008  * Permission is hereby granted to use or copy this program
00009  * for any purpose,  provided the above notices are retained on all copies.
00010  * Permission to modify the code and to distribute modified code is granted,
00011  * provided the above notices are retained, and a notice that the code was
00012  * modified is included with the above copyright notice.
00013  */
00014 
00015 # include "gc_priv.h"
00016 
00017 # if defined(LINUX) && !defined(POWERPC)
00018 #   include <linux/version.h>
00019 #   include <asm/sigcontext.h>
00020 typedef char* caddr_t;
00021 #   if (LINUX_VERSION_CODE <= 0x10400)
00022       /* Ugly hack to get struct sigcontext_struct definition.  Required      */
00023       /* for some early 1.3.X releases.  Will hopefully go away soon. */
00024       /* in some later Linux releases, asm/sigcontext.h may have to   */
00025       /* be included instead.                                         */
00026 #     define __KERNEL__
00027 #     include <asm/signal.h>
00028 #     undef __KERNEL__
00029 #   else
00030       /* Kernels prior to 2.1.1 defined struct sigcontext_struct instead of */
00031       /* struct sigcontext.  libc6 (glibc2) uses "struct sigcontext" in     */
00032       /* prototypes, so we have to include the top-level sigcontext.h to    */
00033       /* make sure the former gets defined to be the latter if appropriate. */
00034 #     include <features.h>
00035 #     if 2 <= __GLIBC__
00036 #       if 0 == __GLIBC_MINOR__
00037          /* glibc 2.1 no longer has sigcontext.h.  But signal.h       */
00038          /* has the right declaration for glibc 2.1.                  */
00039 #         include <sigcontext.h>
00040 #       endif /* 0 == __GLIBC_MINOR__ */
00041 #     else /* not 2 <= __GLIBC__ */
00042         /* libc5 doesn't have <sigcontext.h>: go directly with the kernel   */
00043         /* one.  Check LINUX_VERSION_CODE to see which we should reference. */
00044 #       include <asm/sigcontext.h>
00045 #     endif /* 2 <= __GLIBC__ */
00046 #   endif
00047 # endif
00048 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) && !defined(MACOS)
00049 #   include <sys/types.h>
00050 #   if !defined(MSWIN32) && !defined(SUNOS4)
00051 #      include <unistd.h>
00052 #   endif
00053 # endif
00054 
00055 # include <stdio.h>
00056 # include <signal.h>
00057 
00058 /* Blatantly OS dependent routines, except for those that are related        */
00059 /* dynamic loading.                                            */
00060 
00061 # if !defined(THREADS) && !defined(STACKBOTTOM) && defined(HEURISTIC2)
00062 #   define NEED_FIND_LIMIT
00063 # endif
00064 
00065 # if defined(IRIX_THREADS)
00066 #   define NEED_FIND_LIMIT
00067 # endif
00068 
00069 # if (defined(SUNOS4) & defined(DYNAMIC_LOADING)) && !defined(PCR)
00070 #   define NEED_FIND_LIMIT
00071 # endif
00072 
00073 # if (defined(SVR4) || defined(AUX) || defined(DGUX)) && !defined(PCR)
00074 #   define NEED_FIND_LIMIT
00075 # endif
00076 
00077 # if defined(LINUX) && (defined(POWERPC) || defined(SPARC))
00078 #   define NEED_FIND_LIMIT
00079 # endif
00080 
00081 #ifdef NEED_FIND_LIMIT
00082 #   include <setjmp.h>
00083 #endif
00084 
00085 #ifdef FREEBSD
00086 #  include <machine/trap.h>
00087 #endif
00088 
00089 #ifdef AMIGA
00090 # include <proto/exec.h>
00091 # include <proto/dos.h>
00092 # include <dos/dosextens.h>
00093 # include <workbench/startup.h>
00094 #endif
00095 
00096 #ifdef MSWIN32
00097 # define WIN32_LEAN_AND_MEAN
00098 # define NOSERVICE
00099 # include <windows.h>
00100 #endif
00101 
00102 #ifdef MACOS
00103 # include <Processes.h>
00104 #endif
00105 
00106 #ifdef IRIX5
00107 # include <sys/uio.h>
00108 # include <malloc.h>   /* for locking */
00109 #endif
00110 #ifdef USE_MMAP
00111 # include <sys/types.h>
00112 # include <sys/mman.h>
00113 # include <sys/stat.h>
00114 # include <fcntl.h>
00115 #endif
00116 
00117 #ifdef SUNOS5SIGS
00118 # include <sys/siginfo.h>
00119 # undef setjmp
00120 # undef longjmp
00121 # define setjmp(env) sigsetjmp(env, 1)
00122 # define longjmp(env, val) siglongjmp(env, val)
00123 # define jmp_buf sigjmp_buf
00124 #endif
00125 
00126 #ifdef DJGPP
00127   /* Apparently necessary for djgpp 2.01.  May casuse problems with   */
00128   /* other versions.                                           */
00129   typedef long unsigned int caddr_t;
00130 #endif
00131 
00132 #ifdef PCR
00133 # include "il/PCR_IL.h"
00134 # include "th/PCR_ThCtl.h"
00135 # include "mm/PCR_MM.h"
00136 #endif
00137 
00138 #if !defined(NO_EXECUTE_PERMISSION)
00139 # define OPT_PROT_EXEC PROT_EXEC
00140 #else
00141 # define OPT_PROT_EXEC 0
00142 #endif
00143 
00144 #if defined(LINUX) && defined(POWERPC)
00145   ptr_t GC_data_start;
00146 
00147   void GC_init_linuxppc()
00148   {
00149     extern ptr_t GC_find_limit();
00150     extern char **_environ;
00151        /* This may need to be environ, without the underscore, for    */
00152        /* some versions.                                       */
00153     GC_data_start = GC_find_limit((ptr_t)&_environ, FALSE);
00154   }
00155 #endif
00156 
00157 #if defined(LINUX) && defined(SPARC)
00158   ptr_t GC_data_start;
00159 
00160   void GC_init_linuxsparc()
00161   {
00162     extern ptr_t GC_find_limit();
00163     extern char **_environ;
00164       /* This may need to be environ, without the underscore, for     */
00165       /* some versions.                                               */
00166     GC_data_start = GC_find_limit((ptr_t)&_environ, FALSE);
00167   }
00168 #endif
00169 
00170 # ifdef OS2
00171 
00172 # include <stddef.h>
00173 
00174 # if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */
00175 
00176 struct exe_hdr {
00177     unsigned short      magic_number;
00178     unsigned short      padding[29];
00179     long                new_exe_offset;
00180 };
00181 
00182 #define E_MAGIC(x)      (x).magic_number
00183 #define EMAGIC          0x5A4D  
00184 #define E_LFANEW(x)     (x).new_exe_offset
00185 
00186 struct e32_exe {
00187     unsigned char       magic_number[2]; 
00188     unsigned char       byte_order; 
00189     unsigned char       word_order; 
00190     unsigned long       exe_format_level;
00191     unsigned short      cpu;       
00192     unsigned short      os;
00193     unsigned long       padding1[13];
00194     unsigned long       object_table_offset;
00195     unsigned long       object_count;    
00196     unsigned long       padding2[31];
00197 };
00198 
00199 #define E32_MAGIC1(x)   (x).magic_number[0]
00200 #define E32MAGIC1       'L'
00201 #define E32_MAGIC2(x)   (x).magic_number[1]
00202 #define E32MAGIC2       'X'
00203 #define E32_BORDER(x)   (x).byte_order
00204 #define E32LEBO         0
00205 #define E32_WORDER(x)   (x).word_order
00206 #define E32LEWO         0
00207 #define E32_CPU(x)      (x).cpu
00208 #define E32CPU286       1
00209 #define E32_OBJTAB(x)   (x).object_table_offset
00210 #define E32_OBJCNT(x)   (x).object_count
00211 
00212 struct o32_obj {
00213     unsigned long       size;  
00214     unsigned long       base;
00215     unsigned long       flags;  
00216     unsigned long       pagemap;
00217     unsigned long       mapsize; 
00218     unsigned long       reserved;
00219 };
00220 
00221 #define O32_FLAGS(x)    (x).flags
00222 #define OBJREAD         0x0001L
00223 #define OBJWRITE        0x0002L
00224 #define OBJINVALID      0x0080L
00225 #define O32_SIZE(x)     (x).size
00226 #define O32_BASE(x)     (x).base
00227 
00228 # else  /* IBM's compiler */
00229 
00230 /* A kludge to get around what appears to be a header file bug */
00231 # ifndef WORD
00232 #   define WORD unsigned short
00233 # endif
00234 # ifndef DWORD
00235 #   define DWORD unsigned long
00236 # endif
00237 
00238 # define EXE386 1
00239 # include <newexe.h>
00240 # include <exe386.h>
00241 
00242 # endif  /* __IBMC__ */
00243 
00244 # define INCL_DOSEXCEPTIONS
00245 # define INCL_DOSPROCESS
00246 # define INCL_DOSERRORS
00247 # define INCL_DOSMODULEMGR
00248 # define INCL_DOSMEMMGR
00249 # include <os2.h>
00250 
00251 
00252 /* Disable and enable signals during nontrivial allocations    */
00253 
00254 void GC_disable_signals(void)
00255 {
00256     ULONG nest;
00257     
00258     DosEnterMustComplete(&nest);
00259     if (nest != 1) ABORT("nested GC_disable_signals");
00260 }
00261 
00262 void GC_enable_signals(void)
00263 {
00264     ULONG nest;
00265     
00266     DosExitMustComplete(&nest);
00267     if (nest != 0) ABORT("GC_enable_signals");
00268 }
00269 
00270 
00271 # else
00272 
00273 #  if !defined(PCR) && !defined(AMIGA) && !defined(MSWIN32) \
00274       && !defined(MACOS) && !defined(DJGPP) && !defined(DOS4GW)
00275 
00276 #   if defined(sigmask) && !defined(UTS4)
00277        /* Use the traditional BSD interface */
00278 #      define SIGSET_T int
00279 #      define SIG_DEL(set, signal) (set) &= ~(sigmask(signal))
00280 #      define SIG_FILL(set)  (set) = 0x7fffffff
00281          /* Setting the leading bit appears to provoke a bug in some  */
00282          /* longjmp implementations.  Most systems appear not to have */
00283          /* a signal 32.                                       */
00284 #      define SIGSETMASK(old, new) (old) = sigsetmask(new)
00285 #   else
00286        /* Use POSIX/SYSV interface */
00287 #      define SIGSET_T sigset_t
00288 #      define SIG_DEL(set, signal) sigdelset(&(set), (signal))
00289 #      define SIG_FILL(set) sigfillset(&set)
00290 #      define SIGSETMASK(old, new) sigprocmask(SIG_SETMASK, &(new), &(old))
00291 #   endif
00292 
00293 static GC_bool mask_initialized = FALSE;
00294 
00295 static SIGSET_T new_mask;
00296 
00297 static SIGSET_T old_mask;
00298 
00299 static SIGSET_T dummy;
00300 
00301 #if defined(PRINTSTATS) && !defined(THREADS)
00302 # define CHECK_SIGNALS
00303   int GC_sig_disabled = 0;
00304 #endif
00305 
00306 void GC_disable_signals()
00307 {
00308     if (!mask_initialized) {
00309        SIG_FILL(new_mask);
00310 
00311        SIG_DEL(new_mask, SIGSEGV);
00312        SIG_DEL(new_mask, SIGILL);
00313        SIG_DEL(new_mask, SIGQUIT);
00314 #      ifdef SIGBUS
00315            SIG_DEL(new_mask, SIGBUS);
00316 #      endif
00317 #      ifdef SIGIOT
00318            SIG_DEL(new_mask, SIGIOT);
00319 #      endif
00320 #      ifdef SIGEMT
00321            SIG_DEL(new_mask, SIGEMT);
00322 #      endif
00323 #      ifdef SIGTRAP
00324            SIG_DEL(new_mask, SIGTRAP);
00325 #      endif 
00326        mask_initialized = TRUE;
00327     }
00328 #   ifdef CHECK_SIGNALS
00329        if (GC_sig_disabled != 0) ABORT("Nested disables");
00330        GC_sig_disabled++;
00331 #   endif
00332     SIGSETMASK(old_mask,new_mask);
00333 }
00334 
00335 void GC_enable_signals()
00336 {
00337 #   ifdef CHECK_SIGNALS
00338        if (GC_sig_disabled != 1) ABORT("Unmatched enable");
00339        GC_sig_disabled--;
00340 #   endif
00341     SIGSETMASK(dummy,old_mask);
00342 }
00343 
00344 #  endif  /* !PCR */
00345 
00346 # endif 
00348 /* Ivan Demakov: simplest way (to me) */
00349 #ifdef DOS4GW
00350   void GC_disable_signals() { }
00351   void GC_enable_signals() { }
00352 #endif
00353 
00354 /* Find the page size */
00355 word GC_page_size;
00356 
00357 # ifdef MSWIN32
00358   void GC_setpagesize()
00359   {
00360     SYSTEM_INFO sysinfo;
00361     
00362     GetSystemInfo(&sysinfo);
00363     GC_page_size = sysinfo.dwPageSize;
00364   }
00365 
00366 # else
00367 #   if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP)
00368        void GC_setpagesize()
00369        {
00370            GC_page_size = GETPAGESIZE();
00371        }
00372 #   else
00373        /* It's acceptable to fake it. */
00374        void GC_setpagesize()
00375        {
00376            GC_page_size = HBLKSIZE;
00377        }
00378 #   endif
00379 # endif
00380 
00381 /* 
00382  * Find the base of the stack. 
00383  * Used only in single-threaded environment.
00384  * With threads, GC_mark_roots needs to know how to do this.
00385  * Called with allocator lock held.
00386  */
00387 # ifdef MSWIN32 
00388 # define is_writable(prot) ((prot) == PAGE_READWRITE \
00389                          || (prot) == PAGE_WRITECOPY \
00390                          || (prot) == PAGE_EXECUTE_READWRITE \
00391                          || (prot) == PAGE_EXECUTE_WRITECOPY)
00392 /* Return the number of bytes that are writable starting at p. */
00393 /* The pointer p is assumed to be page aligned.                */
00394 /* If base is not 0, *base becomes the beginning of the        */
00395 /* allocation region containing p.                      */
00396 word GC_get_writable_length(ptr_t p, ptr_t *base)
00397 {
00398     MEMORY_BASIC_INFORMATION buf;
00399     word result;
00400     word protect;
00401     
00402     result = VirtualQuery(p, &buf, sizeof(buf));
00403     if (result != sizeof(buf)) ABORT("Weird VirtualQuery result");
00404     if (base != 0) *base = (ptr_t)(buf.AllocationBase);
00405     protect = (buf.Protect & ~(PAGE_GUARD | PAGE_NOCACHE));
00406     if (!is_writable(protect)) {
00407         return(0);
00408     }
00409     if (buf.State != MEM_COMMIT) return(0);
00410     return(buf.RegionSize);
00411 }
00412 
00413 ptr_t GC_get_stack_base()
00414 {
00415     int dummy;
00416     ptr_t sp = (ptr_t)(&dummy);
00417     ptr_t trunc_sp = (ptr_t)((word)sp & ~(GC_page_size - 1));
00418     word size = GC_get_writable_length(trunc_sp, 0);
00419    
00420     return(trunc_sp + size);
00421 }
00422 
00423 
00424 # else
00425 
00426 # ifdef OS2
00427 
00428 ptr_t GC_get_stack_base()
00429 {
00430     PTIB ptib;
00431     PPIB ppib;
00432     
00433     if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
00434        GC_err_printf0("DosGetInfoBlocks failed\n");
00435        ABORT("DosGetInfoBlocks failed\n");
00436     }
00437     return((ptr_t)(ptib -> tib_pstacklimit));
00438 }
00439 
00440 # else
00441 
00442 # ifdef AMIGA
00443 
00444 ptr_t GC_get_stack_base()
00445 {
00446     extern struct WBStartup *_WBenchMsg;
00447     extern long __base;
00448     extern long __stack;
00449     struct Task *task;
00450     struct Process *proc;
00451     struct CommandLineInterface *cli;
00452     long size;
00453 
00454     if ((task = FindTask(0)) == 0) {
00455        GC_err_puts("Cannot find own task structure\n");
00456        ABORT("task missing");
00457     }
00458     proc = (struct Process *)task;
00459     cli = BADDR(proc->pr_CLI);
00460 
00461     if (_WBenchMsg != 0 || cli == 0) {
00462        size = (char *)task->tc_SPUpper - (char *)task->tc_SPLower;
00463     } else {
00464        size = cli->cli_DefaultStack * 4;
00465     }
00466     return (ptr_t)(__base + GC_max(size, __stack));
00467 }
00468 
00469 # else
00470 
00471 
00472 
00473 # ifdef NEED_FIND_LIMIT
00474   /* Some tools to implement HEURISTIC2   */
00475 #   define MIN_PAGE_SIZE 256       /* Smallest conceivable page size, bytes */
00476     /* static */ jmp_buf GC_jmp_buf;
00477     
00478     /*ARGSUSED*/
00479     void GC_fault_handler(sig)
00480     int sig;
00481     {
00482         longjmp(GC_jmp_buf, 1);
00483     }
00484 
00485 #   ifdef __STDC__
00486        typedef void (*handler)(int);
00487 #   else
00488        typedef void (*handler)();
00489 #   endif
00490 
00491 #   if defined(SUNOS5SIGS) || defined(IRIX5)
00492        static struct sigaction old_segv_act;
00493 #      if defined(_sigargs) /* !Irix6.x */
00494            static struct sigaction old_bus_act;
00495 #      endif
00496 #   else
00497         static handler old_segv_handler, old_bus_handler;
00498 #   endif
00499     
00500     void GC_setup_temporary_fault_handler()
00501     {
00502 #      if defined(SUNOS5SIGS) || defined(IRIX5)
00503          struct sigaction   act;
00504 
00505          act.sa_handler     = GC_fault_handler;
00506           act.sa_flags          = SA_RESTART | SA_NODEFER;
00507           /* The presence of SA_NODEFER represents yet another gross    */
00508           /* hack.  Under Solaris 2.3, siglongjmp doesn't appear to     */
00509           /* interact correctly with -lthread.  We hide the confusion   */
00510           /* by making sure that signal handling doesn't affect the     */
00511           /* signal mask.                                               */
00512 
00513          (void) sigemptyset(&act.sa_mask);
00514 #        ifdef IRIX_THREADS
00515               /* Older versions have a bug related to retrieving and  */
00516               /* and setting a handler at the same time.              */
00517                (void) sigaction(SIGSEGV, 0, &old_segv_act);
00518                (void) sigaction(SIGSEGV, &act, 0);
00519 #        else
00520                (void) sigaction(SIGSEGV, &act, &old_segv_act);
00521 #             ifdef _sigargs       /* Irix 5.x, not 6.x */
00522                   /* Under 5.x, we may get SIGBUS.                    */
00523                   /* Pthreads doesn't exist under 5.x, so we don't    */
00524                   /* have to worry in the threads case.        */
00525                   (void) sigaction(SIGBUS, &act, &old_bus_act);
00526 #             endif
00527 #        endif       /* IRIX_THREADS */
00528 #      else
00529          old_segv_handler = signal(SIGSEGV, GC_fault_handler);
00530 #        ifdef SIGBUS
00531            old_bus_handler = signal(SIGBUS, GC_fault_handler);
00532 #        endif
00533 #      endif
00534     }
00535     
00536     void GC_reset_fault_handler()
00537     {
00538 #       if defined(SUNOS5SIGS) || defined(IRIX5)
00539          (void) sigaction(SIGSEGV, &old_segv_act, 0);
00540 #        ifdef _sigargs     /* Irix 5.x, not 6.x */
00541              (void) sigaction(SIGBUS, &old_bus_act, 0);
00542 #        endif
00543 #       else
00544          (void) signal(SIGSEGV, old_segv_handler);
00545 #        ifdef SIGBUS
00546            (void) signal(SIGBUS, old_bus_handler);
00547 #        endif
00548 #       endif
00549     }
00550 
00551     /* Return the first nonaddressible location > p (up) or    */
00552     /* the smallest location q s.t. [q,p] is addressible (!up).       */
00553     ptr_t GC_find_limit(p, up)
00554     ptr_t p;
00555     GC_bool up;
00556     {
00557         static VOLATILE ptr_t result;
00558               /* Needs to be static, since otherwise it may not be    */
00559               /* preserved across the longjmp.  Can safely be  */
00560               /* static since it's only called once, with the         */
00561               /* allocation lock held.                         */
00562 
00563 
00564        GC_setup_temporary_fault_handler();
00565        if (setjmp(GC_jmp_buf) == 0) {
00566            result = (ptr_t)(((word)(p))
00567                            & ~(MIN_PAGE_SIZE-1));
00568            for (;;) {
00569                if (up) {
00570                   result += MIN_PAGE_SIZE;
00571                } else {
00572                   result -= MIN_PAGE_SIZE;
00573                }
00574               GC_noop1((word)(*result));
00575            }
00576        }
00577        GC_reset_fault_handler();
00578        if (!up) {
00579            result += MIN_PAGE_SIZE;
00580        }
00581        return(result);
00582     }
00583 # endif
00584 
00585 
00586 ptr_t GC_get_stack_base()
00587 {
00588     word dummy;
00589     ptr_t result;
00590 
00591 #   define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
00592 
00593 #   ifdef STACKBOTTOM
00594        return(STACKBOTTOM);
00595 #   else
00596 #      ifdef HEURISTIC1
00597 #         ifdef STACK_GROWS_DOWN
00598             result = (ptr_t)((((word)(&dummy))
00599                             + STACKBOTTOM_ALIGNMENT_M1)
00600                            & ~STACKBOTTOM_ALIGNMENT_M1);
00601 #         else
00602             result = (ptr_t)(((word)(&dummy))
00603                            & ~STACKBOTTOM_ALIGNMENT_M1);
00604 #         endif
00605 #      endif /* HEURISTIC1 */
00606 #      ifdef HEURISTIC2
00607 #          ifdef STACK_GROWS_DOWN
00608               result = GC_find_limit((ptr_t)(&dummy), TRUE);
00609 #             ifdef HEURISTIC2_LIMIT
00610                   if (result > HEURISTIC2_LIMIT
00611                       && (ptr_t)(&dummy) < HEURISTIC2_LIMIT) {
00612                           result = HEURISTIC2_LIMIT;
00613                   }
00614 #              endif
00615 #          else
00616               result = GC_find_limit((ptr_t)(&dummy), FALSE);
00617 #             ifdef HEURISTIC2_LIMIT
00618                   if (result < HEURISTIC2_LIMIT
00619                       && (ptr_t)(&dummy) > HEURISTIC2_LIMIT) {
00620                           result = HEURISTIC2_LIMIT;
00621                   }
00622 #              endif
00623 #          endif
00624 
00625 #      endif /* HEURISTIC2 */
00626 #      ifdef STACK_GROWS_DOWN
00627            if (result == 0) result = (ptr_t)(signed_word)(-sizeof(ptr_t));
00628 #      endif
00629        return(result);
00630 #   endif /* STACKBOTTOM */
00631 }
00632 
00633 # endif /* ! AMIGA */
00634 # endif /* ! OS2 */
00635 # endif /* ! MSWIN32 */
00636 
00637 /*
00638  * Register static data segment(s) as roots.
00639  * If more data segments are added later then they need to be registered
00640  * add that point (as we do with SunOS dynamic loading),
00641  * or GC_mark_roots needs to check for them (as we do with PCR).
00642  * Called with allocator lock held.
00643  */
00644 
00645 # ifdef OS2
00646 
00647 void GC_register_data_segments()
00648 {
00649     PTIB ptib;
00650     PPIB ppib;
00651     HMODULE module_handle;
00652 #   define PBUFSIZ 512
00653     UCHAR path[PBUFSIZ];
00654     FILE * myexefile;
00655     struct exe_hdr hdrdos;  /* MSDOS header.     */
00656     struct e32_exe hdr386;  /* Real header for my executable */
00657     struct o32_obj seg;     /* Currrent segment */
00658     int nsegs;
00659     
00660     
00661     if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
00662        GC_err_printf0("DosGetInfoBlocks failed\n");
00663        ABORT("DosGetInfoBlocks failed\n");
00664     }
00665     module_handle = ppib -> pib_hmte;
00666     if (DosQueryModuleName(module_handle, PBUFSIZ, path) != NO_ERROR) {
00667        GC_err_printf0("DosQueryModuleName failed\n");
00668        ABORT("DosGetInfoBlocks failed\n");
00669     }
00670     myexefile = fopen(path, "rb");
00671     if (myexefile == 0) {
00672         GC_err_puts("Couldn't open executable ");
00673         GC_err_puts(path); GC_err_puts("\n");
00674         ABORT("Failed to open executable\n");
00675     }
00676     if (fread((char *)(&hdrdos), 1, sizeof hdrdos, myexefile) < sizeof hdrdos) {
00677         GC_err_puts("Couldn't read MSDOS header from ");
00678         GC_err_puts(path); GC_err_puts("\n");
00679         ABORT("Couldn't read MSDOS header");
00680     }
00681     if (E_MAGIC(hdrdos) != EMAGIC) {
00682         GC_err_puts("Executable has wrong DOS magic number: ");
00683         GC_err_puts(path); GC_err_puts("\n");
00684         ABORT("Bad DOS magic number");
00685     }
00686     if (fseek(myexefile, E_LFANEW(hdrdos), SEEK_SET) != 0) {
00687         GC_err_puts("Seek to new header failed in ");
00688         GC_err_puts(path); GC_err_puts("\n");
00689         ABORT("Bad DOS magic number");
00690     }
00691     if (fread((char *)(&hdr386), 1, sizeof hdr386, myexefile) < sizeof hdr386) {
00692         GC_err_puts("Couldn't read MSDOS header from ");
00693         GC_err_puts(path); GC_err_puts("\n");
00694         ABORT("Couldn't read OS/2 header");
00695     }
00696     if (E32_MAGIC1(hdr386) != E32MAGIC1 || E32_MAGIC2(hdr386) != E32MAGIC2) {
00697         GC_err_puts("Executable has wrong OS/2 magic number:");
00698         GC_err_puts(path); GC_err_puts("\n");
00699         ABORT("Bad OS/2 magic number");
00700     }
00701     if ( E32_BORDER(hdr386) != E32LEBO || E32_WORDER(hdr386) != E32LEWO) {
00702         GC_err_puts("Executable %s has wrong byte order: ");
00703         GC_err_puts(path); GC_err_puts("\n");
00704         ABORT("Bad byte order");
00705     }
00706     if ( E32_CPU(hdr386) == E32CPU286) {
00707         GC_err_puts("GC can't handle 80286 executables: ");
00708         GC_err_puts(path); GC_err_puts("\n");
00709         EXIT();
00710     }
00711     if (fseek(myexefile, E_LFANEW(hdrdos) + E32_OBJTAB(hdr386),
00712              SEEK_SET) != 0) {
00713         GC_err_puts("Seek to object table failed: ");
00714         GC_err_puts(path); GC_err_puts("\n");
00715         ABORT("Seek to object table failed");
00716     }
00717     for (nsegs = E32_OBJCNT(hdr386); nsegs > 0; nsegs--) {
00718       int flags;
00719       if (fread((char *)(&seg), 1, sizeof seg, myexefile) < sizeof seg) {
00720         GC_err_puts("Couldn't read obj table entry from ");
00721         GC_err_puts(path); GC_err_puts("\n");
00722         ABORT("Couldn't read obj table entry");
00723       }
00724       flags = O32_FLAGS(seg);
00725       if (!(flags & OBJWRITE)) continue;
00726       if (!(flags & OBJREAD)) continue;
00727       if (flags & OBJINVALID) {
00728           GC_err_printf0("Object with invalid pages?\n");
00729           continue;
00730       } 
00731       GC_add_roots_inner(O32_BASE(seg), O32_BASE(seg)+O32_SIZE(seg), FALSE);
00732     }
00733 }
00734 
00735 # else
00736 
00737 # ifdef MSWIN32
00738   /* Unfortunately, we have to handle win32s very differently from NT,       */
00739   /* Since VirtualQuery has very different semantics.  In particular, */
00740   /* under win32s a VirtualQuery call on an unmapped page returns an  */
00741   /* invalid result.  Under GC_register_data_segments is a noop and   */
00742   /* all real work is done by GC_register_dynamic_libraries.  Under   */
00743   /* win32s, we cannot find the data segments associated with dll's.  */
00744   /* We rgister the main data segment here.                           */
00745   GC_bool GC_win32s = FALSE;       /* We're running under win32s.     */
00746   
00747   GC_bool GC_is_win32s()
00748   {
00749       DWORD v = GetVersion();
00750       
00751       /* Check that this is not NT, and Windows major version <= 3    */
00752       return ((v & 0x80000000) && (v & 0xff) <= 3);
00753   }
00754   
00755   void GC_init_win32()
00756   {
00757       GC_win32s = GC_is_win32s();
00758   }
00759   
00760   /* Return the smallest address a such that VirtualQuery             */
00761   /* returns correct results for all addresses between a and start.   */
00762   /* Assumes VirtualQuery returns correct information for start.      */
00763   ptr_t GC_least_described_address(ptr_t start)
00764   {  
00765     MEMORY_BASIC_INFORMATION buf;
00766     SYSTEM_INFO sysinfo;
00767     DWORD result;
00768     LPVOID limit;
00769     ptr_t p;
00770     LPVOID q;
00771     
00772     GetSystemInfo(&sysinfo);
00773     limit = sysinfo.lpMinimumApplicationAddress;
00774     p = (ptr_t)((word)start & ~(GC_page_size - 1));
00775     for (;;) {
00776        q = (LPVOID)(p - GC_page_size);
00777        if ((ptr_t)q > (ptr_t)p /* underflow */ || q < limit) break;
00778        result = VirtualQuery(q, &buf, sizeof(buf));
00779        if (result != sizeof(buf) || buf.AllocationBase == 0) break;
00780        p = (ptr_t)(buf.AllocationBase);
00781     }
00782     return(p);
00783   }
00784   
00785   /* Is p the start of either the malloc heap, or of one of our */
00786   /* heap sections?                                     */
00787   GC_bool GC_is_heap_base (ptr_t p)
00788   {
00789      
00790      register unsigned i;
00791      
00792 #    ifndef REDIRECT_MALLOC
00793        static ptr_t malloc_heap_pointer = 0;
00794      
00795        if (0 == malloc_heap_pointer) {
00796          MEMORY_BASIC_INFORMATION buf;
00797          register DWORD result = VirtualQuery(malloc(1), &buf, sizeof(buf));
00798          
00799          if (result != sizeof(buf)) {
00800              ABORT("Weird VirtualQuery result");
00801          }
00802          malloc_heap_pointer = (ptr_t)(buf.AllocationBase);
00803        }
00804        if (p == malloc_heap_pointer) return(TRUE);
00805 #    endif
00806      for (i = 0; i < GC_n_heap_bases; i++) {
00807          if (GC_heap_bases[i] == p) return(TRUE);
00808      }
00809      return(FALSE);
00810   }
00811   
00812   void GC_register_root_section(ptr_t static_root)
00813   {
00814       MEMORY_BASIC_INFORMATION buf;
00815       SYSTEM_INFO sysinfo;
00816       DWORD result;
00817       DWORD protect;
00818       LPVOID p;
00819       char * base;
00820       char * limit, * new_limit;
00821     
00822       if (!GC_win32s) return;
00823       p = base = limit = GC_least_described_address(static_root);
00824       GetSystemInfo(&sysinfo);
00825       while (p < sysinfo.lpMaximumApplicationAddress) {
00826         result = VirtualQuery(p, &buf, sizeof(buf));
00827         if (result != sizeof(buf) || buf.AllocationBase == 0
00828             || GC_is_heap_base(buf.AllocationBase)) break;
00829         new_limit = (char *)p + buf.RegionSize;
00830         protect = buf.Protect;
00831         if (buf.State == MEM_COMMIT
00832             && is_writable(protect)) {
00833             if ((char *)p == limit) {
00834                 limit = new_limit;
00835             } else {
00836                 if (base != limit) GC_add_roots_inner(base, limit, FALSE);
00837                 base = p;
00838                 limit = new_limit;
00839             }
00840         }
00841         if (p > (LPVOID)new_limit /* overflow */) break;
00842         p = (LPVOID)new_limit;
00843       }
00844       if (base != limit) GC_add_roots_inner(base, limit, FALSE);
00845   }
00846   
00847   void GC_register_data_segments()
00848   {
00849       static char dummy;
00850       
00851       GC_register_root_section((ptr_t)(&dummy));
00852   }
00853 # else
00854 # ifdef AMIGA
00855 
00856   void GC_register_data_segments()
00857   {
00858     extern struct WBStartup *_WBenchMsg;
00859     struct Process   *proc;
00860     struct CommandLineInterface *cli;
00861     BPTR myseglist;
00862     ULONG *data;
00863 
00864     if ( _WBenchMsg != 0 ) {
00865        if ((myseglist = _WBenchMsg->sm_Segment) == 0) {
00866            GC_err_puts("No seglist from workbench\n");
00867            return;
00868        }
00869     } else {
00870        if ((proc = (struct Process *)FindTask(0)) == 0) {
00871            GC_err_puts("Cannot find process structure\n");
00872            return;
00873        }
00874        if ((cli = BADDR(proc->pr_CLI)) == 0) {
00875            GC_err_puts("No CLI\n");
00876            return;
00877        }
00878        if ((myseglist = cli->cli_Module) == 0) {
00879            GC_err_puts("No seglist from CLI\n");
00880            return;
00881        }
00882     }
00883 
00884     for (data = (ULONG *)BADDR(myseglist); data != 0;
00885          data = (ULONG *)BADDR(data[0])) {
00886 #        ifdef AMIGA_SKIP_SEG
00887            if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
00888            ((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
00889 #       else
00890           {
00891 #       endif /* AMIGA_SKIP_SEG */
00892           GC_add_roots_inner((char *)&data[1],
00893                           ((char *)&data[1]) + data[-1], FALSE);
00894          }
00895     }
00896   }
00897 
00898 
00899 # else
00900 
00901 # if (defined(SVR4) || defined(AUX) || defined(DGUX)) && !defined(PCR)
00902 char * GC_SysVGetDataStart(max_page_size, etext_addr)
00903 int max_page_size;
00904 int * etext_addr;
00905 {
00906     word text_end = ((word)(etext_addr) + sizeof(word) - 1)
00907                   & ~(sizeof(word) - 1);
00908        /* etext rounded to word boundary  */
00909     word next_page = ((text_end + (word)max_page_size - 1)
00910                     & ~((word)max_page_size - 1));
00911     word page_offset = (text_end & ((word)max_page_size - 1));
00912     VOLATILE char * result = (char *)(next_page + page_offset);
00913     /* Note that this isnt equivalent to just adding           */
00914     /* max_page_size to &etext if &etext is at a page boundary */
00915     
00916     GC_setup_temporary_fault_handler();
00917     if (setjmp(GC_jmp_buf) == 0) {
00918        /* Try writing to the address.     */
00919        *result = *result;
00920         GC_reset_fault_handler();
00921     } else {
00922         GC_reset_fault_handler();
00923        /* We got here via a longjmp.  The address is not readable.    */
00924        /* This is known to happen under Solaris 2.4 + gcc, which place       */
00925        /* string constants in the text segment, but after etext.      */
00926        /* Use plan B.  Note that we now know there is a gap between   */
00927        /* text and data segments, so plan A bought us something.      */
00928        result = (char *)GC_find_limit((ptr_t)(DATAEND) - MIN_PAGE_SIZE, FALSE);
00929     }
00930     return((char *)result);
00931 }
00932 # endif
00933 
00934 
00935 void GC_register_data_segments()
00936 {
00937 #   if !defined(PCR) && !defined(SRC_M3) && !defined(NEXT) && !defined(MACOS)
00938 #     if defined(REDIRECT_MALLOC) && defined(SOLARIS_THREADS)
00939        /* As of Solaris 2.3, the Solaris threads implementation       */
00940        /* allocates the data structure for the initial thread with    */
00941        /* sbrk at process startup.  It needs to be scanned, so that   */
00942        /* we don't lose some malloc allocated data structures         */
00943        /* hanging from it.  We're on thin ice here ...                */
00944         extern caddr_t sbrk();
00945 
00946        GC_add_roots_inner(DATASTART, (char *)sbrk(0), FALSE);
00947 #     else
00948        GC_add_roots_inner(DATASTART, (char *)(DATAEND), FALSE);
00949 #     endif
00950 #   endif
00951 #   if !defined(PCR) && defined(NEXT)
00952       GC_add_roots_inner(DATASTART, (char *) get_end(), FALSE);
00953 #   endif
00954 #   if defined(MACOS)
00955     {
00956 #   if defined(THINK_C)
00957        extern void* GC_MacGetDataStart(void);
00958        /* globals begin above stack and end at a5. */
00959        GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
00960                         (ptr_t)LMGetCurrentA5(), FALSE);
00961 #   else
00962 #     if defined(__MWERKS__)
00963 #       if !__POWERPC__
00964          extern void* GC_MacGetDataStart(void);
00965          /* MATTHEW: Function to handle Far Globals (CW Pro 3) */
00966 #         if __option(far_data)
00967          extern void* GC_MacGetDataEnd(void);
00968 #         endif
00969          /* globals begin above stack and end at a5. */
00970          GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
00971                           (ptr_t)LMGetCurrentA5(), FALSE);
00972          /* MATTHEW: Handle Far Globals */                          
00973 #         if __option(far_data)
00974       /* Far globals follow he QD globals: */
00975          GC_add_roots_inner((ptr_t)LMGetCurrentA5(),
00976                           (ptr_t)GC_MacGetDataEnd(), FALSE);
00977 #         endif
00978 #       else
00979          extern char __data_start__[], __data_end__[];
00980          GC_add_roots_inner((ptr_t)&__data_start__,
00981                           (ptr_t)&__data_end__, FALSE);
00982 #       endif /* __POWERPC__ */
00983 #     endif /* __MWERKS__ */
00984 #   endif /* !THINK_C */
00985     }
00986 #   endif /* MACOS */
00987 
00988     /* Dynamic libraries are added at every collection, since they may  */
00989     /* change.                                                        */
00990 }
00991 
00992 # endif  /* ! AMIGA */
00993 # endif  /* ! MSWIN32 */
00994 # endif  /* ! OS2 */
00995 
00996 /*
00997  * Auxiliary routines for obtaining memory from OS.
00998  */
00999  
01000 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \
01001        && !defined(MSWIN32) && !defined(MACOS) && !defined(DOS4GW)
01002 
01003 # ifdef SUNOS4
01004     extern caddr_t sbrk();
01005 # endif
01006 # ifdef __STDC__
01007 #   define SBRK_ARG_T ptrdiff_t
01008 # else
01009 #   define SBRK_ARG_T int
01010 # endif
01011 
01012 # ifdef RS6000
01013 /* The compiler seems to generate speculative reads one past the end of      */
01014 /* an allocated object.  Hence we need to make sure that the page     */
01015 /* following the last heap page is also mapped.                       */
01016 ptr_t GC_unix_get_mem(bytes)
01017 word bytes;
01018 {
01019     caddr_t cur_brk = (caddr_t)sbrk(0);
01020     caddr_t result;
01021     SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
01022     static caddr_t my_brk_val = 0;
01023     
01024     if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
01025     if (lsbs != 0) {
01026         if((caddr_t)(sbrk(GC_page_size - lsbs)) == (caddr_t)(-1)) return(0);
01027     }
01028     if (cur_brk == my_brk_val) {
01029        /* Use the extra block we allocated last time. */
01030         result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
01031         if (result == (caddr_t)(-1)) return(0);
01032         result -= GC_page_size;
01033     } else {
01034         result = (ptr_t)sbrk(GC_page_size + (SBRK_ARG_T)bytes);
01035         if (result == (caddr_t)(-1)) return(0);
01036     }
01037     my_brk_val = result + bytes + GC_page_size;  /* Always page aligned */
01038     return((ptr_t)result);
01039 }
01040 
01041 #else  /* Not RS6000 */
01042 
01043 #if defined(USE_MMAP)
01044 /* Tested only under IRIX5 and Solaris 2 */
01045 
01046 #ifdef USE_MMAP_FIXED
01047 #   define GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE
01048        /* Seems to yield better performance on Solaris 2, but can     */
01049        /* be unreliable if something is already mapped at the address.       */
01050 #else
01051 #   define GC_MMAP_FLAGS MAP_PRIVATE
01052 #endif
01053 
01054 ptr_t GC_unix_get_mem(bytes)
01055 word bytes;
01056 {
01057     static GC_bool initialized = FALSE;
01058     static int fd;
01059     void *result;
01060     static ptr_t last_addr = HEAP_START;
01061 
01062     if (!initialized) {
01063        fd = open("/dev/zero", O_RDONLY);
01064        initialized = TRUE;
01065     }
01066     if (bytes & (GC_page_size -1)) ABORT("Bad GET_MEM arg");
01067     result = mmap(last_addr, bytes, PROT_READ | PROT_WRITE | OPT_PROT_EXEC,
01068                 GC_MMAP_FLAGS, fd, 0/* offset */);
01069     if (result == MAP_FAILED) return(0);
01070     last_addr = (ptr_t)result + bytes + GC_page_size - 1;
01071     last_addr = (ptr_t)((word)last_addr & ~(GC_page_size - 1));
01072     return((ptr_t)result);
01073 }
01074 
01075 #else /* Not RS6000, not USE_MMAP */
01076 ptr_t GC_unix_get_mem(bytes)
01077 word bytes;
01078 {
01079   ptr_t result;
01080 # ifdef IRIX5
01081     /* Bare sbrk isn't thread safe.  Play by malloc rules.     */
01082     /* The equivalent may be needed on other systems as well.  */
01083     __LOCK_MALLOC();
01084 # endif
01085   {
01086     ptr_t cur_brk = (ptr_t)sbrk(0);
01087     SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
01088     
01089     if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
01090     if (lsbs != 0) {
01091         if((ptr_t)sbrk(GC_page_size - lsbs) == (ptr_t)(-1)) return(0);
01092     }
01093     result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
01094     if (result == (ptr_t)(-1)) result = 0;
01095   }
01096 # ifdef IRIX5
01097     __UNLOCK_MALLOC();
01098 # endif
01099   return(result);
01100 }
01101 
01102 #endif /* Not USE_MMAP */
01103 #endif /* Not RS6000 */
01104 
01105 # endif /* UN*X */
01106 
01107 # ifdef OS2
01108 
01109 void * os2_alloc(size_t bytes)
01110 {
01111     void * result;
01112 
01113     if (DosAllocMem(&result, bytes, PAG_EXECUTE | PAG_READ |
01114                                 PAG_WRITE | PAG_COMMIT)
01115                   != NO_ERROR) {
01116        return(0);
01117     }
01118     if (result == 0) return(os2_alloc(bytes));
01119     return(result);
01120 }
01121 
01122 # endif /* OS2 */
01123 
01124 
01125 # ifdef MSWIN32
01126 word GC_n_heap_bases = 0;
01127 
01128 ptr_t GC_win32_get_mem(bytes)
01129 word bytes;
01130 {
01131     ptr_t result;
01132     
01133     if (GC_win32s) {
01134        /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE.    */
01135        /* There are also unconfirmed rumors of other           */
01136        /* problems, so we dodge the issue.                     */
01137         result = (ptr_t) GlobalAlloc(0, bytes + HBLKSIZE);
01138         result = (ptr_t)(((word)result + HBLKSIZE) & ~(HBLKSIZE-1));
01139     } else {
01140         result = (ptr_t) VirtualAlloc(NULL, bytes,
01141                                   MEM_COMMIT | MEM_RESERVE,
01142                                   PAGE_EXECUTE_READWRITE);
01143     }
01144     if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
01145        /* If I read the documentation correctly, this can      */
01146        /* only happen if HBLKSIZE > 64k or not a power of 2.   */
01147     if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
01148     GC_heap_bases[GC_n_heap_bases++] = result;
01149     return(result);                  
01150 }
01151 
01152 void GC_win32_free_heap ()
01153 {
01154     if (GC_win32s) {
01155        while (GC_n_heap_bases > 0) {
01156            GlobalFree (GC_heap_bases[--GC_n_heap_bases]);
01157            GC_heap_bases[GC_n_heap_bases] = 0;
01158        }
01159     }
01160 }
01161 
01162 
01163 # endif
01164 
01165 /* Routine for pushing any additional roots.  In THREADS       */
01166 /* environment, this is also responsible for marking from      */
01167 /* thread stacks.  In the SRC_M3 case, it also handles         */
01168 /* global variables.                                    */
01169 #ifndef THREADS
01170 void (*GC_push_other_roots)() = 0;
01171 #else /* THREADS */
01172 
01173 # ifdef PCR
01174 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
01175 {
01176     struct PCR_ThCtl_TInfoRep info;
01177     PCR_ERes result;
01178     
01179     info.ti_stkLow = info.ti_stkHi = 0;
01180     result = PCR_ThCtl_GetInfo(t, &info);
01181     GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi));
01182     return(result);
01183 }
01184 
01185 /* Push the contents of an old object. We treat this as stack  */
01186 /* data only becasue that makes it robust against mark stack   */
01187 /* overflow.                                            */
01188 PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data)
01189 {
01190     GC_push_all_stack((ptr_t)p, (ptr_t)p + size);
01191     return(PCR_ERes_okay);
01192 }
01193 
01194 
01195 void GC_default_push_other_roots()
01196 {
01197     /* Traverse data allocated by previous memory managers.           */
01198        {
01199          extern struct PCR_MM_ProcsRep * GC_old_allocator;
01200          
01201          if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false,
01202                                              GC_push_old_obj, 0)
01203              != PCR_ERes_okay) {
01204              ABORT("Old object enumeration failed");
01205          }
01206        }
01207     /* Traverse all thread stacks. */
01208        if (PCR_ERes_IsErr(
01209                 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0))
01210               || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
01211               ABORT("Thread stack marking failed\n");
01212        }
01213 }
01214 
01215 # endif /* PCR */
01216 
01217 # ifdef SRC_M3
01218 
01219 # ifdef ALL_INTERIOR_POINTERS
01220     --> misconfigured
01221 # endif
01222 
01223 
01224 extern void ThreadF__ProcessStacks();
01225 
01226 void GC_push_thread_stack(start, stop)
01227 word start, stop;
01228 {
01229    GC_push_all_stack((ptr_t)start, (ptr_t)stop + sizeof(word));
01230 }
01231 
01232 /* Push routine with M3 specific calling convention. */
01233 GC_m3_push_root(dummy1, p, dummy2, dummy3)
01234 word *p;
01235 ptr_t dummy1, dummy2;
01236 int dummy3;
01237 {
01238     word q = *p;
01239     
01240     if ((ptr_t)(q) >= GC_least_plausible_heap_addr
01241         && (ptr_t)(q) < GC_greatest_plausible_heap_addr) {
01242         GC_push_one_checked(q,FALSE);
01243     }
01244 }
01245 
01246 /* M3 set equivalent to RTHeap.TracedRefTypes */
01247 typedef struct { int elts[1]; }  RefTypeSet;
01248 RefTypeSet GC_TracedRefTypes = {{0x1}};
01249 
01250 /* From finalize.c */
01251 extern void GC_push_finalizer_structures();
01252 
01253 /* From stubborn.c: */
01254 # ifdef STUBBORN_ALLOC
01255     extern GC_PTR * GC_changing_list_start;
01256 # endif
01257 
01258 
01259 void GC_default_push_other_roots()
01260 {
01261     /* Use the M3 provided routine for finding static roots.   */
01262     /* This is a bit dubious, since it presumes no C roots.    */
01263     /* We handle the collector roots explicitly.        */
01264        {
01265 #       ifdef STUBBORN_ALLOC
01266            GC_push_one(GC_changing_list_start);
01267 #       endif
01268         GC_push_finalizer_structures();
01269         RTMain__GlobalMapProc(GC_m3_push_root, 0, GC_TracedRefTypes);
01270        }
01271        if (GC_words_allocd > 0) {
01272            ThreadF__ProcessStacks(GC_push_thread_stack);
01273        }
01274        /* Otherwise this isn't absolutely necessary, and we have      */
01275        /* startup ordering problems.                                  */
01276 }
01277 
01278 # endif /* SRC_M3 */
01279 
01280 # if defined(SOLARIS_THREADS) || defined(WIN32_THREADS) \
01281      || defined(IRIX_THREADS) || defined(LINUX_THREADS) \
01282      || defined(IRIX_PCR_THREADS) || defined(GENERIC_THREADS)
01283 
01284 extern void GC_push_all_stacks();
01285 
01286 void GC_default_push_other_roots()
01287 {
01288     GC_push_all_stacks();
01289 }
01290 
01291 # endif /* SOLARIS_THREADS || ... */
01292 
01293 void (*GC_push_other_roots)() = GC_default_push_other_roots;
01294 
01295 #endif
01296 
01297 /*
01298  * Routines for accessing dirty  bits on virtual pages.
01299  * We plan to eventaually implement four strategies for doing so:
01300  * DEFAULT_VDB:      A simple dummy implementation that treats every page
01301  *            as possibly dirty.  This makes incremental collection
01302  *            useless, but the implementation is still correct.
01303  * PCR_VDB:   Use PPCRs virtual dirty bit facility.
01304  * PROC_VDB:  Use the /proc facility for reading dirty bits.  Only
01305  *            works under some SVR4 variants.  Even then, it may be
01306  *            too slow to be entirely satisfactory.  Requires reading
01307  *            dirty bits for entire address space.  Implementations tend
01308  *            to assume that the client is a (slow) debugger.
01309  * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
01310  *            dirtied pages.  The implementation (and implementability)
01311  *            is highly system dependent.  This usually fails when system
01312  *            calls write to a protected page.  We prevent the read system
01313  *            call from doing so.  It is the clients responsibility to
01314  *            make sure that other system calls are similarly protected
01315  *            or write only to the stack.
01316  */
01317  
01318 GC_bool GC_dirty_maintained = FALSE;
01319 
01320 # ifdef DEFAULT_VDB
01321 
01322 /* All of the following assume the allocation lock is held, and       */
01323 /* signals are disabled.                                */
01324 
01325 /* The client asserts that unallocated pages in the heap are never    */
01326 /* written.                                                    */
01327 
01328 /* Initialize virtual dirty bit implementation.                */
01329 void GC_dirty_init()
01330 {
01331     GC_dirty_maintained = TRUE;
01332 }
01333 
01334 /* Retrieve system dirty bits for heap to a local buffer.      */
01335 /* Restore the systems notion of which pages are dirty.        */
01336 void GC_read_dirty()
01337 {}
01338 
01339 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer?  */
01340 /* If the actual page size is different, this returns TRUE if any     */
01341 /* of the pages overlapping h are dirty.  This routine may err on the */
01342 /* side of labelling pages as dirty (and this implementation does).   */
01343 /*ARGSUSED*/
01344 GC_bool GC_page_was_dirty(h)
01345 struct hblk *h;
01346 {
01347     return(TRUE);
01348 }
01349 
01350 /*
01351  * The following two routines are typically less crucial.  They matter
01352  * most with large dynamic libraries, or if we can't accurately identify
01353  * stacks, e.g. under Solaris 2.X.  Otherwise the following default
01354  * versions are adequate.
01355  */
01356  
01357 /* Could any valid GC heap pointer ever have been written to this page?      */
01358 /*ARGSUSED*/
01359 GC_bool GC_page_was_ever_dirty(h)
01360 struct hblk *h;
01361 {
01362     return(TRUE);
01363 }
01364 
01365 /* Reset the n pages starting at h to "was never dirty" status.       */
01366 void GC_is_fresh(h, n)
01367 struct hblk *h;
01368 word n;
01369 {
01370 }
01371 
01372 /* A call hints that h is about to be written.   */
01373 /* May speed up some dirty bit implementations.  */
01374 /*ARGSUSED*/
01375 void GC_write_hint(h)
01376 struct hblk *h;
01377 {
01378 }
01379 
01380 # endif /* DEFAULT_VDB */
01381 
01382 
01383 # ifdef MPROTECT_VDB
01384 
01385 /*
01386  * See DEFAULT_VDB for interface descriptions.
01387  */
01388 
01389 /*
01390  * This implementation maintains dirty bits itself by catching write
01391  * faults and keeping track of them.  We assume nobody else catches
01392  * SIGBUS or SIGSEGV.  We assume no write faults occur in system calls
01393  * except as a result of a read system call.  This means clients must
01394  * either ensure that system calls do not touch the heap, or must
01395  * provide their own wrappers analogous to the one for read.
01396  * We assume the page size is a multiple of HBLKSIZE.
01397  * This implementation is currently SunOS 4.X and IRIX 5.X specific, though we
01398  * tried to use portable code where easily possible.  It is known
01399  * not to work under a number of other systems.
01400  */
01401 
01402 # ifndef MSWIN32
01403 
01404 #   include <sys/mman.h>
01405 #   include <signal.h>
01406 #   include <sys/syscall.h>
01407 
01408 #   define PROTECT(addr, len) \
01409          if (mprotect((caddr_t)(addr), (int)(len), \
01410                      PROT_READ | OPT_PROT_EXEC) < 0) { \
01411            ABORT("mprotect failed"); \
01412          }
01413 #   define UNPROTECT(addr, len) \
01414          if (mprotect((caddr_t)(addr), (int)(len), \
01415                      PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
01416            ABORT("un-mprotect failed"); \
01417          }
01418          
01419 # else
01420 
01421 #   include <signal.h>
01422 
01423     static DWORD protect_junk;
01424 #   define PROTECT(addr, len) \
01425          if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
01426                            &protect_junk)) { \
01427            DWORD last_error = GetLastError(); \
01428            GC_printf1("Last error code: %lx\n", last_error); \
01429            ABORT("VirtualProtect failed"); \
01430          }
01431 #   define UNPROTECT(addr, len) \
01432          if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
01433                            &protect_junk)) { \
01434            ABORT("un-VirtualProtect failed"); \
01435          }
01436          
01437 # endif
01438 
01439 #if defined(SUNOS4) || defined(FREEBSD)
01440     typedef void (* SIG_PF)();
01441 #endif
01442 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX)
01443     typedef void (* SIG_PF)(int);
01444 #endif
01445 #if defined(MSWIN32)
01446     typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
01447 #   undef SIG_DFL
01448 #   define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
01449 #endif
01450 
01451 #if defined(IRIX5) || defined(OSF1)
01452     typedef void (* REAL_SIG_PF)(int, int, struct sigcontext *);
01453 #endif
01454 #if defined(SUNOS5SIGS)
01455     typedef void (* REAL_SIG_PF)(int, struct siginfo *, void *);
01456 #endif
01457 #if defined(LINUX)
01458 #   include <linux/version.h>
01459 #   if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA)
01460       typedef struct sigcontext s_c;
01461 #   else
01462       typedef struct sigcontext_struct s_c;
01463 #   endif
01464 #   ifdef ALPHA
01465     typedef void (* REAL_SIG_PF)(int, int, s_c *);
01466     /* Retrieve fault address from sigcontext structure by decoding   */
01467     /* instruction.                                            */
01468     char * get_fault_addr(s_c *sc) {
01469         unsigned instr;
01470        word faultaddr;
01471 
01472        instr = *((unsigned *)(sc->sc_pc));
01473        faultaddr = sc->sc_regs[(instr >> 16) & 0x1f];
01474        faultaddr += (word) (((int)instr << 16) >> 16);
01475        return (char *)faultaddr;
01476     }
01477 #   else /* !ALPHA */
01478     typedef void (* REAL_SIG_PF)(int, s_c);
01479 #   endif /* !ALPHA */
01480 # endif
01481 
01482 SIG_PF GC_old_bus_handler;
01483 SIG_PF GC_old_segv_handler; /* Also old MSWIN32 ACCESS_VIOLATION filter */
01484 
01485 /*ARGSUSED*/
01486 # if defined (SUNOS4) || defined(FREEBSD)
01487     void GC_write_fault_handler(sig, code, scp, addr)
01488     int sig, code;
01489     struct sigcontext *scp;
01490     char * addr;
01491 #   ifdef SUNOS4
01492 #     define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
01493 #     define CODE_OK (FC_CODE(code) == FC_PROT \
01494                          || (FC_CODE(code) == FC_OBJERR \
01495                             && FC_ERRNO(code) == FC_PROT))
01496 #   endif
01497 #   ifdef FREEBSD
01498 #     define SIG_OK (sig == SIGBUS)
01499 #     define CODE_OK (code == BUS_PAGE_FAULT)
01500 #   endif
01501 # endif
01502 # if defined(IRIX5) || defined(OSF1)
01503 #   include <errno.h>
01504     void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
01505 #   define SIG_OK (sig == SIGSEGV)
01506 #   ifdef OSF1
01507 #     define CODE_OK (code == 2 /* experimentally determined */)
01508 #   endif
01509 #   ifdef IRIX5
01510 #     define CODE_OK (code == EACCES)
01511 #   endif
01512 # endif
01513 # if defined(LINUX)
01514 #   ifdef ALPHA
01515       void GC_write_fault_handler(int sig, int code, s_c * sc)
01516 #   else
01517       void GC_write_fault_handler(int sig, s_c sc)
01518 #   endif
01519 #   define SIG_OK (sig == SIGSEGV)
01520 #   define CODE_OK TRUE
01521        /* Empirically c.trapno == 14, but is that useful?      */
01522        /* We assume Intel architecture, so alignment           */
01523        /* faults are not possible.                      */
01524 # endif
01525 # if defined(SUNOS5SIGS)
01526     void GC_write_fault_handler(int sig, struct siginfo *scp, void * context)
01527 #   define SIG_OK (sig == SIGSEGV)
01528 #   define CODE_OK (scp -> si_code == SEGV_ACCERR)
01529 # endif
01530 # if defined(MSWIN32)
01531     LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info)
01532 #   define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
01533                      EXCEPTION_ACCESS_VIOLATION)
01534 #   define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
01535                      /* Write fault */
01536 # endif
01537 {
01538     register unsigned i;
01539 #   ifdef IRIX5
01540        char * addr = (char *) (size_t) (scp -> sc_badvaddr);
01541 #   endif
01542 #   if defined(OSF1) && defined(ALPHA)
01543        char * addr = (char *) (scp -> sc_traparg_a0);
01544 #   endif
01545 #   ifdef SUNOS5SIGS
01546        char * addr = (char *) (scp -> si_addr);
01547 #   endif
01548 #   ifdef LINUX
01549 #     ifdef I386
01550        char * addr = (char *) (sc.cr2);
01551 #     else
01552 #      if defined(M68K)
01553           char * addr = NULL;
01554 
01555          struct sigcontext *scp = (struct sigcontext *)(&sc);
01556 
01557          int format = (scp->sc_formatvec >> 12) & 0xf;
01558          unsigned long *framedata = (unsigned long *)(scp + 1); 
01559          unsigned long ea;
01560 
01561          if (format == 0xa || format == 0xb) {
01562               /* 68020/030 */
01563               ea = framedata[2];
01564          } else if (format == 7) {
01565               /* 68040 */
01566               ea = framedata[3];
01567          } else if (format == 4) {
01568               /* 68060 */
01569               ea = framedata[0];
01570               if (framedata[1] & 0x08000000) {
01571                      /* correct addr on misaligned access */
01572                      ea = (ea+4095)&(~4095);
01573               }
01574          }    
01575          addr = (char *)ea;
01576 #      else
01577 #        ifdef ALPHA
01578             char * addr = get_fault_addr(sc);
01579 #        else
01580               --> architecture not supported
01581 #        endif
01582 #      endif
01583 #     endif
01584 #   endif
01585 #   if defined(MSWIN32)
01586        char * addr = (char *) (exc_info -> ExceptionRecord
01587                             -> ExceptionInformation[1]);
01588 #      define sig SIGSEGV
01589 #   endif
01590     
01591     if (SIG_OK && CODE_OK) {
01592         register struct hblk * h =
01593                      (struct hblk *)((word)addr & ~(GC_page_size-1));
01594         GC_bool in_allocd_block;
01595         
01596 #      ifdef SUNOS5SIGS
01597            /* Address is only within the correct physical page.       */
01598            in_allocd_block = FALSE;
01599             for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
01600               if (HDR(h+i) != 0) {
01601                 in_allocd_block = TRUE;
01602               }
01603             }
01604 #      else
01605            in_allocd_block = (HDR(addr) != 0);
01606 #      endif
01607         if (!in_allocd_block) {
01608            /* Heap blocks now begin and end on page boundaries */
01609             SIG_PF old_handler;
01610             
01611             if (sig == SIGSEGV) {
01612               old_handler = GC_old_segv_handler;
01613             } else {
01614                 old_handler = GC_old_bus_handler;
01615             }
01616             if (old_handler == SIG_DFL) {
01617 #             ifndef MSWIN32
01618                   GC_err_printf1("Segfault at 0x%lx\n", addr);
01619                     ABORT("Unexpected bus error or segmentation fault");
01620 #             else
01621                   return(EXCEPTION_CONTINUE_SEARCH);
01622 #             endif
01623             } else {
01624 #             if defined (SUNOS4) || defined(FREEBSD)
01625                   (*old_handler) (sig, code, scp, addr);
01626                   return;
01627 #             endif
01628 #             if defined (SUNOS5SIGS)
01629                   (*(REAL_SIG_PF)old_handler) (sig, scp, context);
01630                   return;
01631 #             endif
01632 #             if defined (LINUX)
01633 #                 ifdef ALPHA
01634                       (*(REAL_SIG_PF)old_handler) (sig, code, sc);
01635 #                 else 
01636                       (*(REAL_SIG_PF)old_handler) (sig, sc);
01637 #                 endif
01638                   return;
01639 #             endif
01640 #             if defined (IRIX5) || defined(OSF1)
01641                   (*(REAL_SIG_PF)old_handler) (sig, code, scp);
01642                   return;
01643 #             endif
01644 #             ifdef MSWIN32
01645                   return((*old_handler)(exc_info));
01646 #             endif
01647             }
01648         }
01649         for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
01650             register int index = PHT_HASH(h+i);
01651             
01652             set_pht_entry_from_index(GC_dirty_pages, index);
01653         }
01654         UNPROTECT(h, GC_page_size);
01655 #      if defined(OSF1) || defined(LINUX)
01656            /* These reset the signal handler each time by default. */
01657            signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
01658 #      endif
01659        /* The write may not take place before dirty bits are read.    */
01660        /* But then we'll fault again ...                       */
01661 #      ifdef MSWIN32
01662            return(EXCEPTION_CONTINUE_EXECUTION);
01663 #      else
01664            return;
01665 #      endif
01666     }
01667 #ifdef MSWIN32
01668     return EXCEPTION_CONTINUE_SEARCH;
01669 #else
01670     GC_err_printf1("Segfault at 0x%lx\n", addr);
01671     ABORT("Unexpected bus error or segmentation fault");
01672 #endif
01673 }
01674 
01675 /*
01676  * We hold the allocation lock.  We expect block h to be written
01677  * shortly.
01678  */
01679 void GC_write_hint(h)
01680 struct hblk *h;
01681 {
01682     register struct hblk * h_trunc;
01683     register unsigned i;
01684     register GC_bool found_clean;
01685     
01686     if (!GC_dirty_maintained) return;
01687     h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1));
01688     found_clean = FALSE;
01689     for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
01690         register int index = PHT_HASH(h_trunc+i);
01691             
01692         if (!get_pht_entry_from_index(GC_dirty_pages, index)) {
01693             found_clean = TRUE;
01694             set_pht_entry_from_index(GC_dirty_pages, index);
01695         }
01696     }
01697     if (found_clean) {
01698        UNPROTECT(h_trunc, GC_page_size);
01699     }
01700 }
01701 
01702 void GC_dirty_init()
01703 {
01704 #if defined(SUNOS5SIGS) || defined(IRIX5)
01705     struct sigaction act, oldact;
01706 #   ifdef IRIX5
01707        act.sa_flags  = SA_RESTART;
01708         act.sa_handler  = GC_write_fault_handler;
01709 #   else
01710        act.sa_flags  = SA_RESTART | SA_SIGINFO;
01711         act.sa_sigaction = GC_write_fault_handler;
01712 #   endif
01713     (void)sigemptyset(&act.sa_mask); 
01714 #endif
01715 #   ifdef PRINTSTATS
01716        GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
01717 #   endif
01718     GC_dirty_maintained = TRUE;
01719     if (GC_page_size % HBLKSIZE != 0) {
01720         GC_err_printf0("Page size not multiple of HBLKSIZE\n");
01721         ABORT("Page size not multiple of HBLKSIZE");
01722     }
01723 #   if defined(SUNOS4) || defined(FREEBSD)
01724       GC_old_bus_handler = signal(SIGBUS, GC_write_fault_handler);
01725       if (GC_old_bus_handler == SIG_IGN) {
01726         GC_err_printf0("Previously ignored bus error!?");
01727         GC_old_bus_handler = SIG_DFL;
01728       }
01729       if (GC_old_bus_handler != SIG_DFL) {
01730 #      ifdef PRINTSTATS
01731           GC_err_printf0("Replaced other SIGBUS handler\n");
01732 #      endif
01733       }
01734 #   endif
01735 #   if defined(OSF1) || defined(SUNOS4) || defined(LINUX)
01736       GC_old_segv_handler = signal(SIGSEGV, (SIG_PF)GC_write_fault_handler);
01737       if (GC_old_segv_handler == SIG_IGN) {
01738         GC_err_printf0("Previously ignored segmentation violation!?");
01739         GC_old_segv_handler = SIG_DFL;
01740       }
01741       if (GC_old_segv_handler != SIG_DFL) {
01742 #      ifdef PRINTSTATS
01743           GC_err_printf0("Replaced other SIGSEGV handler\n");
01744 #      endif
01745       }
01746 #   endif
01747 #   if defined(SUNOS5SIGS) || defined(IRIX5)
01748 #     if defined(IRIX_THREADS) || defined(IRIX_PCR_THREADS)
01749        sigaction(SIGSEGV, 0, &oldact);
01750        sigaction(SIGSEGV, &act, 0);
01751 #     else
01752        sigaction(SIGSEGV, &act, &oldact);
01753 #     endif
01754 #     if defined(_sigargs)
01755        /* This is Irix 5.x, not 6.x.  Irix 5.x does not have   */
01756        /* sa_sigaction.                                 */
01757        GC_old_segv_handler = oldact.sa_handler;
01758 #     else /* Irix 6.x or SUNOS5SIGS */
01759         if (oldact.sa_flags & SA_SIGINFO) {
01760           GC_old_segv_handler = (SIG_PF)(oldact.sa_sigaction);
01761         } else {
01762           GC_old_segv_handler = oldact.sa_handler;
01763         }
01764 #     endif
01765       if (GC_old_segv_handler == SIG_IGN) {
01766             GC_err_printf0("Previously ignored segmentation violation!?");
01767             GC_old_segv_handler = SIG_DFL;
01768       }
01769       if (GC_old_segv_handler != SIG_DFL) {
01770 #       ifdef PRINTSTATS
01771          GC_err_printf0("Replaced other SIGSEGV handler\n");
01772 #       endif
01773       }
01774 #    endif
01775 #   if defined(MSWIN32)
01776       GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler);
01777       if (GC_old_segv_handler != NULL) {
01778 #      ifdef PRINTSTATS
01779           GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
01780 #      endif
01781       } else {
01782           GC_old_segv_handler = SIG_DFL;
01783       }
01784 #   endif
01785 }
01786 
01787 
01788 
01789 void GC_protect_heap()
01790 {
01791     ptr_t start;
01792     word len;
01793     unsigned i;
01794     
01795     for (i = 0; i < GC_n_heap_sects; i++) {
01796         start = GC_heap_sects[i].hs_start;
01797         len = GC_heap_sects[i].hs_bytes;
01798         PROTECT(start, len);
01799     }
01800 }
01801 
01802 /* We assume that either the world is stopped or its OK to lose dirty */
01803 /* bits while this is happenning (as in GC_enable_incremental).              */
01804 void GC_read_dirty()
01805 {
01806     BCOPY((word *)GC_dirty_pages, GC_grungy_pages,
01807           (sizeof GC_dirty_pages));
01808     BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages));
01809     GC_protect_heap();
01810 }
01811 
01812 GC_bool GC_page_was_dirty(h)
01813 struct hblk * h;
01814 {
01815     register word index = PHT_HASH(h);
01816     
01817     return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index));
01818 }
01819 
01820 /*
01821  * Acquiring the allocation lock here is dangerous, since this
01822  * can be called from within GC_call_with_alloc_lock, and the cord
01823  * package does so.  On systems that allow nested lock acquisition, this
01824  * happens to work.
01825  * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
01826  */
01827  
01828 void GC_begin_syscall()
01829 {
01830     if (!I_HOLD_LOCK()) LOCK();
01831 }
01832 
01833 void GC_end_syscall()
01834 {
01835     if (!I_HOLD_LOCK()) UNLOCK();
01836 }
01837 
01838 void GC_unprotect_range(addr, len)
01839 ptr_t addr;
01840 word len;
01841 {
01842     struct hblk * start_block;
01843     struct hblk * end_block;
01844     register struct hblk *h;
01845     ptr_t obj_start;
01846     
01847     if (!GC_incremental) return;
01848     obj_start = GC_base(addr);
01849     if (obj_start == 0) return;
01850     if (GC_base(addr + len - 1) != obj_start) {
01851         ABORT("GC_unprotect_range(range bigger than object)");
01852     }
01853     start_block = (struct hblk *)((word)addr & ~(GC_page_size - 1));
01854     end_block = (struct hblk *)((word)(addr + len - 1) & ~(GC_page_size - 1));
01855     end_block += GC_page_size/HBLKSIZE - 1;
01856     for (h = start_block; h <= end_block; h++) {
01857         register word index = PHT_HASH(h);
01858         
01859         set_pht_entry_from_index(GC_dirty_pages, index);
01860     }
01861     UNPROTECT(start_block,
01862              ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE);
01863 }
01864 
01865 #if 0
01866 #ifndef MSWIN32
01867 /* Replacement for UNIX system call.       */
01868 /* Other calls that write to the heap      */
01869 /* should be handled similarly.            */
01870 # if defined(__STDC__) && !defined(SUNOS4)
01871 #   include <unistd.h>
01872     ssize_t read(int fd, void *buf, size_t nbyte)
01873 # else
01874 #   ifndef LINT
01875       int read(fd, buf, nbyte)
01876 #   else
01877       int GC_read(fd, buf, nbyte)
01878 #   endif
01879     int fd;
01880     char *buf;
01881     int nbyte;
01882 # endif
01883 {
01884     int result;
01885     
01886     GC_begin_syscall();
01887     GC_unprotect_range(buf, (word)nbyte);
01888 #   ifdef IRIX5
01889        /* Indirect system call may not always be easily available.    */
01890        /* We could call _read, but that would interfere with the      */
01891        /* libpthread interception of read.                            */
01892        {
01893            struct iovec iov;
01894 
01895            iov.iov_base = buf;
01896            iov.iov_len = nbyte;
01897            result = readv(fd, &iov, 1);
01898        }
01899 #   else
01900        result = syscall(SYS_read, fd, buf, nbyte);
01901 #   endif
01902     GC_end_syscall();
01903     return(result);
01904 }
01905 #endif /* !MSWIN32 */
01906 #endif
01907 
01908 
01909 /*ARGSUSED*/
01910 GC_bool GC_page_was_ever_dirty(h)
01911 struct hblk *h;
01912 {
01913     return(TRUE);
01914 }
01915 
01916 /* Reset the n pages starting at h to "was never dirty" status.       */
01917 /*ARGSUSED*/
01918 void GC_is_fresh(h, n)
01919 struct hblk *h;
01920 word n;
01921 {
01922 }
01923 
01924 # endif /* MPROTECT_VDB */
01925 
01926 # ifdef PROC_VDB
01927 
01928 /*
01929  * See DEFAULT_VDB for interface descriptions.
01930  */
01931  
01932 /*
01933  * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
01934  * from which we can read page modified bits.  This facility is far from
01935  * optimal (e.g. we would like to get the info for only some of the
01936  * address space), but it avoids intercepting system calls.
01937  */
01938 
01939 #include <errno.h>
01940 #include <sys/types.h>
01941 #include <sys/signal.h>
01942 #include <sys/fault.h>
01943 #include <sys/syscall.h>
01944 #include <sys/procfs.h>
01945 #include <sys/stat.h>
01946 #include <fcntl.h>
01947 
01948 #define INITIAL_BUF_SZ 4096
01949 word GC_proc_buf_size = INITIAL_BUF_SZ;
01950 char *GC_proc_buf;
01951 
01952 #ifdef SOLARIS_THREADS
01953 /* We don't have exact sp values for threads.  So we count on  */
01954 /* occasionally declaring stack pages to be fresh.  Thus we    */
01955 /* need a real implementation of GC_is_fresh.  We can't clear  */
01956 /* entries in GC_written_pages, since that would declare all   */
01957 /* pages with the given hash address to be fresh.              */
01958 #   define MAX_FRESH_PAGES 8*1024  /* Must be power of 2 */
01959     struct hblk ** GC_fresh_pages; /* A direct mapped cache.   */
01960                                    /* Collisions are dropped.  */
01961 
01962 #   define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
01963 #   define ADD_FRESH_PAGE(h) \
01964        GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
01965 #   define PAGE_IS_FRESH(h) \
01966        (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
01967 #endif
01968 
01969 /* Add all pages in pht2 to pht1 */
01970 void GC_or_pages(pht1, pht2)
01971 page_hash_table pht1, pht2;
01972 {
01973     register int i;
01974     
01975     for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
01976 }
01977 
01978 int GC_proc_fd;
01979 
01980 void GC_dirty_init()
01981 {
01982     int fd;
01983     char buf[30];
01984 
01985     GC_dirty_maintained = TRUE;
01986     if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
01987        register int i;
01988     
01989         for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
01990 #       ifdef PRINTSTATS
01991            GC_printf1("Allocated words:%lu:all pages may have been written\n",
01992                      (unsigned long)
01993                             (GC_words_allocd + GC_words_allocd_before_gc));
01994 #      endif       
01995     }
01996     sprintf(buf, "/proc/%d", getpid());
01997     fd = open(buf, O_RDONLY);
01998     if (fd < 0) {
01999        ABORT("/proc open failed");
02000     }
02001     GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
02002     close(fd);
02003     if (GC_proc_fd < 0) {
02004        ABORT("/proc ioctl failed");
02005     }
02006     GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size);
02007 #   ifdef SOLARIS_THREADS
02008        GC_fresh_pages = (struct hblk **)
02009          GC_scratch_alloc(MAX_FRESH_PAGES * sizeof (struct hblk *));
02010        if (GC_fresh_pages == 0) {
02011            GC_err_printf0("No space for fresh pages\n");
02012            EXIT();
02013        }
02014        BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
02015 #   endif
02016 }
02017 
02018 /* Ignore write hints. They don't help us here.  */
02019 /*ARGSUSED*/
02020 void GC_write_hint(h)
02021 struct hblk *h;
02022 {
02023 }
02024 
02025 #ifdef SOLARIS_THREADS
02026 #   define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
02027 #else
02028 #   define READ(fd,buf,nbytes) read(fd, buf, nbytes)
02029 #endif
02030 
02031 void GC_read_dirty()
02032 {
02033     unsigned long ps, np;
02034     int nmaps;
02035     ptr_t vaddr;
02036     struct prasmap * map;
02037     char * bufp;
02038     ptr_t current_addr, limit;
02039     int i;
02040 int dummy;
02041 
02042     BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
02043     
02044     bufp = GC_proc_buf;
02045     if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
02046 #      ifdef PRINTSTATS
02047             GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
02048                      GC_proc_buf_size);
02049 #      endif       
02050         {
02051             /* Retry with larger buffer. */
02052             word new_size = 2 * GC_proc_buf_size;
02053             char * new_buf = GC_scratch_alloc(new_size);
02054             
02055             if (new_buf != 0) {
02056                 GC_proc_buf = bufp = new_buf;
02057                 GC_proc_buf_size = new_size;
02058             }
02059             if (syscall(SYS_read, GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
02060                 WARN("Insufficient space for /proc read\n", 0);
02061                 /* Punt:    */
02062               memset(GC_grungy_pages, 0xff, sizeof (page_hash_table));
02063               memset(GC_written_pages, 0xff, sizeof(page_hash_table));
02064 #             ifdef SOLARIS_THREADS
02065                   BZERO(GC_fresh_pages,
02066                        MAX_FRESH_PAGES * sizeof (struct hblk *)); 
02067 #             endif
02068               return;
02069             }
02070         }
02071     }
02072     /* Copy dirty bits into GC_grungy_pages */
02073        nmaps = ((struct prpageheader *)bufp) -> pr_nmap;
02074        /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
02075                    nmaps, PG_REFERENCED, PG_MODIFIED); */
02076        bufp = bufp + sizeof(struct prpageheader);
02077        for (i = 0; i < nmaps; i++) {
02078            map = (struct prasmap *)bufp;
02079            vaddr = (ptr_t)(map -> pr_vaddr);
02080            ps = map -> pr_pagesize;
02081            np = map -> pr_npage;
02082            /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
02083            limit = vaddr + ps * np;
02084            bufp += sizeof (struct prasmap);
02085            for (current_addr = vaddr;
02086                 current_addr < limit; current_addr += ps){
02087                if ((*bufp++) & PG_MODIFIED) {
02088                    register struct hblk * h = (struct hblk *) current_addr;
02089                    
02090                    while ((ptr_t)h < current_addr + ps) {
02091                        register word index = PHT_HASH(h);
02092                        
02093                        set_pht_entry_from_index(GC_grungy_pages, index);
02094 #                    ifdef SOLARIS_THREADS
02095                        {
02096                          register int slot = FRESH_PAGE_SLOT(h);
02097                          
02098                          if (GC_fresh_pages[slot] == h) {
02099                              GC_fresh_pages[slot] = 0;
02100                          }
02101                        }
02102 #                    endif
02103                        h++;
02104                    }
02105                }
02106            }
02107            bufp += sizeof(long) - 1;
02108            bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1));
02109        }
02110     /* Update GC_written_pages. */
02111         GC_or_pages(GC_written_pages, GC_grungy_pages);
02112 #   ifdef SOLARIS_THREADS
02113       /* Make sure that old stacks are considered completely clean    */
02114       /* unless written again.                                        */
02115        GC_old_stacks_are_fresh();
02116 #   endif
02117 }
02118 
02119 #undef READ
02120 
02121 GC_bool GC_page_was_dirty(h)
02122 struct hblk *h;
02123 {
02124     register word index = PHT_HASH(h);
02125     register GC_bool result;
02126     
02127     result = get_pht_entry_from_index(GC_grungy_pages, index);
02128 #   ifdef SOLARIS_THREADS
02129        if (result && PAGE_IS_FRESH(h)) result = FALSE;
02130        /* This happens only if page was declared fresh since   */
02131        /* the read_dirty call, e.g. because it's in an unused  */
02132        /* thread stack.  It's OK to treat it as clean, in      */
02133        /* that case.  And it's consistent with          */
02134        /* GC_page_was_ever_dirty.                       */
02135 #   endif
02136     return(result);
02137 }
02138 
02139 GC_bool GC_page_was_ever_dirty(h)
02140 struct hblk *h;
02141 {
02142     register word index = PHT_HASH(h);
02143     register GC_bool result;
02144     
02145     result = get_pht_entry_from_index(GC_written_pages, index);
02146 #   ifdef SOLARIS_THREADS
02147        if (result && PAGE_IS_FRESH(h)) result = FALSE;
02148 #   endif
02149     return(result);
02150 }
02151 
02152 /* Caller holds allocation lock.   */
02153 void GC_is_fresh(h, n)
02154 struct hblk *h;
02155 word n;
02156 {
02157 
02158     register word index;
02159     
02160 #   ifdef SOLARIS_THREADS
02161       register word i;
02162       
02163       if (GC_fresh_pages != 0) {
02164         for (i = 0; i < n; i++) {
02165           ADD_FRESH_PAGE(h + i);
02166         }
02167       }
02168 #   endif
02169 }
02170 
02171 # endif /* PROC_VDB */
02172 
02173 
02174 # ifdef PCR_VDB
02175 
02176 # include "vd/PCR_VD.h"
02177 
02178 # define NPAGES (32*1024)   /* 128 MB */
02179 
02180 PCR_VD_DB  GC_grungy_bits[NPAGES];
02181 
02182 ptr_t GC_vd_base;    /* Address corresponding to GC_grungy_bits[0]    */
02183                      /* HBLKSIZE aligned.                      */
02184 
02185 void GC_dirty_init()
02186 {
02187     GC_dirty_maintained = TRUE;
02188     /* For the time being, we assume the heap generally grows up */
02189     GC_vd_base = GC_heap_sects[0].hs_start;
02190     if (GC_vd_base == 0) {
02191        ABORT("Bad initial heap segment");
02192     }
02193     if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE)
02194        != PCR_ERes_okay) {
02195        ABORT("dirty bit initialization failed");
02196     }
02197 }
02198 
02199 void GC_read_dirty()
02200 {
02201     /* lazily enable dirty bits on newly added heap sects */
02202     {
02203         static int onhs = 0;
02204         int nhs = GC_n_heap_sects;
02205         for( ; onhs < nhs; onhs++ ) {
02206             PCR_VD_WriteProtectEnable(
02207                     GC_heap_sects[onhs].hs_start,
02208                     GC_heap_sects[onhs].hs_bytes );
02209         }
02210     }
02211 
02212 
02213     if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits)
02214         != PCR_ERes_okay) {
02215        ABORT("dirty bit read failed");
02216     }
02217 }
02218 
02219 GC_bool GC_page_was_dirty(h)
02220 struct hblk *h;
02221 {
02222     if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
02223        return(TRUE);
02224     }
02225     return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
02226 }
02227 
02228 /*ARGSUSED*/
02229 void GC_write_hint(h)
02230 struct hblk *h;
02231 {
02232     PCR_VD_WriteProtectDisable(h, HBLKSIZE);
02233     PCR_VD_WriteProtectEnable(h, HBLKSIZE);
02234 }
02235 
02236 # endif /* PCR_VDB */
02237 
02238 /*
02239  * Call stack save code for debugging.
02240  * Should probably be in mach_dep.c, but that requires reorganization.
02241  */
02242 #if defined(SPARC) && !defined(LINUX)
02243 #   if defined(SUNOS4)
02244 #     include <machine/frame.h>
02245 #   else
02246 #     if defined (DRSNX)
02247 #      include <sys/sparc/frame.h>
02248 #     else
02249 #       include <sys/frame.h>
02250 #     endif
02251 #   endif
02252 #   if NARGS > 6
02253        --> We only know how to to get the first 6 arguments
02254 #   endif
02255 
02256 #ifdef SAVE_CALL_CHAIN
02257 /* Fill in the pc and argument information for up to NFRAMES of my    */
02258 /* callers.  Ignore my frame and my callers frame.                    */
02259 void GC_save_callers (info) 
02260 struct callinfo info[NFRAMES];
02261 {
02262   struct frame *frame;
02263   struct frame *fp;
02264   int nframes = 0;
02265   word GC_save_regs_in_stack();
02266 
02267   frame = (struct frame *) GC_save_regs_in_stack ();
02268   
02269   for (fp = frame -> fr_savfp; fp != 0 && nframes < NFRAMES;
02270        fp = fp -> fr_savfp, nframes++) {
02271       register int i;
02272       
02273       info[nframes].ci_pc = fp->fr_savpc;
02274 #     if NARGS > 0
02275       for (i = 0; i < NARGS; i++) {
02276        info[nframes].ci_arg[i] = ~(fp->fr_arg[i]);
02277       }
02278 #     endif
02279   }
02280   if (nframes < NFRAMES) info[nframes].ci_pc = 0;
02281 }
02282 
02283 #endif /* SAVE_CALL_CHAIN */
02284 #endif /* SPARC */
02285 
02286 
02287 #if defined(SAVE_CALL_CHAIN) && defined(POWERPC) && defined(MACOS)
02288 
02289 #if (NFRAMES > 2)
02290 
02291 /* traditional, fixed-size call chain buffer. */
02292 
02293 static asm void *GetSP() 
02294 {
02295        mr            r3, sp
02296        blr
02297 }
02298 
02299 void GC_save_callers(struct callinfo info[NFRAMES]) 
02300 {
02301        int    i;
02302        void* currentSP;
02303        
02304        currentSP = GetSP();                      // GC_save_callers's frame.
02305        currentSP = *((void **)currentSP); // GC_debug_malloc's frame.
02306        currentSP = *((void **)currentSP); // GC_debug_malloc's caller's frame.
02307        
02308        for (i = 0; i < NFRAMES; i++) {
02309               word* linkageArea = (word *)currentSP;
02310               // LR saved at 8(SP) in each frame. subtract 4 to get address of calling instruction.
02311               info[i].ci_pc = linkageArea[2] - sizeof(word);
02312               currentSP = *((void **)currentSP);
02313               // the bottom-most frame is marked as pointing to NULL.
02314               if (currentSP == NULL || (word)currentSP & 0x1)
02315                      break;
02316        }
02317 }
02318 
02319 #else
02320 
02321 /* new and improved store all call chains in a tree, which lets us track arbitrarily deep chains. */ 
02322 /* use GC_scratch_alloc() to allocate the tree nodes. */
02323 
02324 #include "call_tree.h"
02325 
02326 typedef struct stack_frame stack_frame;
02327 
02328 struct stack_frame {
02329        stack_frame*  next;                       // savedSP
02330        void*                savedCR;
02331        void*                savedLR;
02332        void*                reserved0;
02333        void*                reserved1;
02334        void*                savedTOC;
02335 };
02336 
02337 asm stack_frame* getStackFrame()
02338 {
02339        mr            r3, sp
02340        blr
02341 }
02342 
02343 static call_tree* find_tree(stack_frame* frame)
02344 {
02345     /* primordial root of the call tree. */
02346     static call_tree root = { 0, 0, 0, 0, 0 };
02347 
02348     /* ensure frame is non-NULL and 4-byte aligned. */
02349     if ((frame == NULL) || ((word)frame & 0x3))
02350         return &root;
02351     else {
02352         call_tree* parent = find_tree(frame->next);
02353         if (parent != NULL) {
02354             call_tree** link = &parent->children;
02355             call_tree* tree = *link;
02356             while (tree != NULL) {
02357                 if (tree->pc == frame->savedLR)
02358                     break;
02359                 link = &tree->siblings;
02360                 tree = *link;
02361             }
02362             if (tree == NULL) {
02363                 /* no tree exists for this frame, so we create one. */
02364                 tree = (call_tree*) GC_scratch_alloc(sizeof(call_tree));
02365                 if (tree != NULL) {
02366                     tree->pc = frame->savedLR;
02367                     tree->id = 0;
02368                     tree->parent = parent;
02369                     tree->siblings = parent->children;
02370                     parent->children = tree;
02371                     tree->children = NULL;
02372                 }
02373             } else {
02374                 if (parent->children != tree) {
02375                     /* splay tree to front of list. */
02376                     *link = tree->siblings;
02377                     tree->siblings = parent->children;
02378                     parent->children = tree;
02379                 }
02380             }
02381             return tree;
02382         }
02383         return NULL;
02384     }
02385 }
02386 
02387 static int fix_stack(stack_frame* frame)
02388 {
02389     // only fix the REAL stack.
02390     if (! GC_base(frame)) {
02391         Ptr stackBase = LMGetCurStackBase();
02392         while (frame) {
02393             // if we find a bogus frame in the stack, we clear it out.
02394             if (frame->next < frame || (Ptr)frame->next > stackBase) {
02395                 frame->next = NULL;
02396                 return 1;
02397             }
02398             frame = frame->next;
02399         }
02400     }
02401     return 0;
02402 }
02403 
02404 void GC_save_callers(struct callinfo info[NFRAMES]) 
02405 {
02406        int    i;
02407        stack_frame* currentFrame;
02408        call_tree* currentTree = NULL;
02409        
02410        currentFrame = getStackFrame();           // GC_save_callers's frame.
02411        currentFrame = currentFrame->next; // GC_debug_malloc's frame.
02412        currentFrame = currentFrame->next; // GC_debug_malloc's caller's frame.
02413 
02414        if (info != GC_last_stack) {
02415        currentTree = find_tree(currentFrame);
02416     } else {
02417         static int fixed_stack = 0;
02418         if (!fixed_stack)
02419             fixed_stack = fix_stack(currentFrame);
02420     }
02421     
02422        info[0].ci_pc = (word) currentTree;
02423        info[1].ci_pc = 0;
02424 }
02425 
02426 #endif
02427 
02428 #endif /* POWERPC && MACOS */
02429 
02430 #if defined(SAVE_CALL_CHAIN) && defined(LINUX)
02431 
02432 #include "call_tree.h"
02433 
02434 typedef struct stack_frame stack_frame;
02435 
02436 #if defined(__i386) 
02437 struct stack_frame {
02438   stack_frame* next;
02439   void* pc;
02440 };
02441 
02442 static stack_frame* getStackFrame()
02443 {
02444   stack_frame* currentFrame;
02445 #if defined(__i386) 
02446   __asm__( "movl %%ebp, %0" : "=g"(currentFrame));
02447 #elif defined(__x86_64__)
02448   __asm__( "movq %%rbp, %0" : "=g"(currentFrame));
02449 #else
02450   /*
02451    * It would be nice if this worked uniformly, but at least on i386 and
02452    * x86_64, it stopped working with gcc 4.1, because it points to the
02453    * end of the saved registers instead of the start.
02454    */
02455   currentFrame = (stack_frame*)__builtin_frame_address(0);
02456 #endif
02457   currentFrame = currentFrame->next;
02458   return currentFrame;
02459 }
02460 #endif /* __i386 */
02461 
02462 static call_tree* find_tree(stack_frame* frame)
02463 {
02464     /* primordial root of the call tree. */
02465     static call_tree root = { 0, 0, 0, 0, 0 };
02466 
02467     long pc = (long)frame->pc;
02468 
02469     if ((pc < 0x08000000) || (pc > 0x7fffffff) || (frame->next < frame)) {
02470         return &root;
02471     } else {
02472         call_tree* parent = find_tree(frame->next);
02473         if (parent != NULL) {
02474             call_tree** link = &parent->children;
02475             call_tree* tree = *link;
02476             while (tree != NULL) {
02477                 if (tree->pc == frame->pc)
02478                     break;
02479                 link = &tree->siblings;
02480                 tree = *link;
02481             }
02482             if (tree == NULL) {
02483                 /* no tree exists for this frame, so we create one. */
02484                 tree = (call_tree*) GC_scratch_alloc(sizeof(call_tree));
02485                 if (tree != NULL) {
02486                     tree->pc = frame->pc;
02487                     tree->id = 0;
02488                     tree->parent = parent;
02489                     tree->siblings = parent->children;
02490                     parent->children = tree;
02491                     tree->children = NULL;
02492                 }
02493             } else {
02494                 if (parent->children != tree) {
02495                     /* splay tree to front of list. */
02496                     *link = tree->siblings;
02497                     tree->siblings = parent->children;
02498                     parent->children = tree;
02499                 }
02500             }
02501             return tree;
02502         }
02503         return NULL;
02504     }
02505 }
02506 
02507 void GC_save_callers(struct callinfo info[NFRAMES]) 
02508 {
02509   stack_frame* currentFrame;
02510   call_tree* currentTree;
02511        
02512   currentFrame = getStackFrame();  // GC_save_callers's frame.
02513   currentFrame = currentFrame->next;      // GC_debug_malloc's frame.
02514   currentFrame = currentFrame->next;      // GC_debug_malloc's caller's frame.
02515        
02516   currentTree = find_tree(currentFrame);
02517        
02518   info[0].ci_pc = (word) currentTree;
02519   info[1].ci_pc = 0;
02520 }
02521 
02522 #endif /* defined(SAVE_CALL_CHAIN) && defined(LINUX) */
02523