2 * Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved.
3 * Copyright (c) 1996-1997 by Silicon Graphics. All rights reserved.
5 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
6 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
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.
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. */
25 # include <asm/signal.h>
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>
34 # if 0 == __GLIBC_MINOR__
35 /* glibc 2.1 no longer has sigcontext.h. But signal.h */
36 /* has the right declaration for glibc 2.1. */
37 # include <sigcontext.h>
38 # endif /* 0 == __GLIBC_MINOR__ */
39 # else /* not 2 <= __GLIBC__ */
40 /* libc5 doesn't have <sigcontext.h>: go directly with the kernel */
41 /* one. Check LINUX_VERSION_CODE to see which we should reference. */
42 # include <asm/sigcontext.h>
43 # endif /* 2 <= __GLIBC__ */
46 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) && !defined(MACOS)
47 # include <sys/types.h>
48 # if !defined(MSWIN32) && !defined(SUNOS4)
56 /* Blatantly OS dependent routines, except for those that are related */
57 /* dynamic loading. */
59 # if !defined(THREADS) && !defined(STACKBOTTOM) && defined(HEURISTIC2)
60 # define NEED_FIND_LIMIT
63 # if defined(IRIX_THREADS)
64 # define NEED_FIND_LIMIT
67 # if (defined(SUNOS4) & defined(DYNAMIC_LOADING)) && !defined(PCR)
68 # define NEED_FIND_LIMIT
71 # if (defined(SVR4) || defined(AUX) || defined(DGUX)) && !defined(PCR)
72 # define NEED_FIND_LIMIT
75 # if defined(LINUX) && (defined(POWERPC) || defined(SPARC) || defined(ALPHA))
76 # define NEED_FIND_LIMIT
79 #ifdef NEED_FIND_LIMIT
84 # include <machine/trap.h>
88 # include <proto/exec.h>
89 # include <proto/dos.h>
90 # include <dos/dosextens.h>
91 # include <workbench/startup.h>
95 # define WIN32_LEAN_AND_MEAN
101 # include <Processes.h>
105 # include <sys/uio.h>
106 # include <malloc.h> /* for locking */
109 # include <sys/types.h>
110 # include <sys/mman.h>
111 # include <sys/stat.h>
116 # include <sys/siginfo.h>
119 # define setjmp(env) sigsetjmp(env, 1)
120 # define longjmp(env, val) siglongjmp(env, val)
121 # define jmp_buf sigjmp_buf
125 /* Apparently necessary for djgpp 2.01. May casuse problems with */
126 /* other versions. */
127 typedef long unsigned int caddr_t;
131 # include "il/PCR_IL.h"
132 # include "th/PCR_ThCtl.h"
133 # include "mm/PCR_MM.h"
136 #if !defined(NO_EXECUTE_PERMISSION)
137 # define OPT_PROT_EXEC PROT_EXEC
139 # define OPT_PROT_EXEC 0
142 #if defined(LINUX) && (defined(POWERPC) || defined(SPARC) || defined(ALPHA))
143 /* The I386 case can be handled without a search. The Alpha case */
144 /* used to be handled differently as well, but the rules changed */
145 /* for recent Linux versions. This seems to be the easiest way to */
146 /* cover all versions. */
149 extern char * GC_copyright[]; /* Any data symbol would do. */
151 void GC_init_linux_data_start()
153 extern ptr_t GC_find_limit();
155 GC_data_start = GC_find_limit((ptr_t)GC_copyright, FALSE);
163 # if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */
166 unsigned short magic_number;
167 unsigned short padding[29];
171 #define E_MAGIC(x) (x).magic_number
172 #define EMAGIC 0x5A4D
173 #define E_LFANEW(x) (x).new_exe_offset
176 unsigned char magic_number[2];
177 unsigned char byte_order;
178 unsigned char word_order;
179 unsigned long exe_format_level;
182 unsigned long padding1[13];
183 unsigned long object_table_offset;
184 unsigned long object_count;
185 unsigned long padding2[31];
188 #define E32_MAGIC1(x) (x).magic_number[0]
189 #define E32MAGIC1 'L'
190 #define E32_MAGIC2(x) (x).magic_number[1]
191 #define E32MAGIC2 'X'
192 #define E32_BORDER(x) (x).byte_order
194 #define E32_WORDER(x) (x).word_order
196 #define E32_CPU(x) (x).cpu
198 #define E32_OBJTAB(x) (x).object_table_offset
199 #define E32_OBJCNT(x) (x).object_count
205 unsigned long pagemap;
206 unsigned long mapsize;
207 unsigned long reserved;
210 #define O32_FLAGS(x) (x).flags
211 #define OBJREAD 0x0001L
212 #define OBJWRITE 0x0002L
213 #define OBJINVALID 0x0080L
214 #define O32_SIZE(x) (x).size
215 #define O32_BASE(x) (x).base
217 # else /* IBM's compiler */
219 /* A kludge to get around what appears to be a header file bug */
221 # define WORD unsigned short
224 # define DWORD unsigned long
231 # endif /* __IBMC__ */
233 # define INCL_DOSEXCEPTIONS
234 # define INCL_DOSPROCESS
235 # define INCL_DOSERRORS
236 # define INCL_DOSMODULEMGR
237 # define INCL_DOSMEMMGR
241 /* Disable and enable signals during nontrivial allocations */
243 void GC_disable_signals(void)
247 DosEnterMustComplete(&nest);
248 if (nest != 1) ABORT("nested GC_disable_signals");
251 void GC_enable_signals(void)
255 DosExitMustComplete(&nest);
256 if (nest != 0) ABORT("GC_enable_signals");
262 # if !defined(PCR) && !defined(AMIGA) && !defined(MSWIN32) \
263 && !defined(MACOS) && !defined(DJGPP) && !defined(DOS4GW)
265 # if defined(sigmask) && !defined(UTS4)
266 /* Use the traditional BSD interface */
267 # define SIGSET_T int
268 # define SIG_DEL(set, signal) (set) &= ~(sigmask(signal))
269 # define SIG_FILL(set) (set) = 0x7fffffff
270 /* Setting the leading bit appears to provoke a bug in some */
271 /* longjmp implementations. Most systems appear not to have */
273 # define SIGSETMASK(old, new) (old) = sigsetmask(new)
275 /* Use POSIX/SYSV interface */
276 # define SIGSET_T sigset_t
277 # define SIG_DEL(set, signal) sigdelset(&(set), (signal))
278 # define SIG_FILL(set) sigfillset(&set)
279 # define SIGSETMASK(old, new) sigprocmask(SIG_SETMASK, &(new), &(old))
282 static GC_bool mask_initialized = FALSE;
284 static SIGSET_T new_mask;
286 static SIGSET_T old_mask;
288 static SIGSET_T dummy;
290 #if defined(PRINTSTATS) && !defined(THREADS)
291 # define CHECK_SIGNALS
292 int GC_sig_disabled = 0;
295 void GC_disable_signals()
297 if (!mask_initialized) {
300 SIG_DEL(new_mask, SIGSEGV);
301 SIG_DEL(new_mask, SIGILL);
302 SIG_DEL(new_mask, SIGQUIT);
304 SIG_DEL(new_mask, SIGBUS);
307 SIG_DEL(new_mask, SIGIOT);
310 SIG_DEL(new_mask, SIGEMT);
313 SIG_DEL(new_mask, SIGTRAP);
315 mask_initialized = TRUE;
317 # ifdef CHECK_SIGNALS
318 if (GC_sig_disabled != 0) ABORT("Nested disables");
321 SIGSETMASK(old_mask,new_mask);
324 void GC_enable_signals()
326 # ifdef CHECK_SIGNALS
327 if (GC_sig_disabled != 1) ABORT("Unmatched enable");
330 SIGSETMASK(dummy,old_mask);
337 /* Ivan Demakov: simplest way (to me) */
339 void GC_disable_signals() { }
340 void GC_enable_signals() { }
343 /* Find the page size */
347 void GC_setpagesize()
351 GetSystemInfo(&sysinfo);
352 GC_page_size = sysinfo.dwPageSize;
356 # if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP) \
357 || defined(USE_MUNMAP)
358 void GC_setpagesize()
360 GC_page_size = GETPAGESIZE();
363 /* It's acceptable to fake it. */
364 void GC_setpagesize()
366 GC_page_size = HBLKSIZE;
372 * Find the base of the stack.
373 * Used only in single-threaded environment.
374 * With threads, GC_mark_roots needs to know how to do this.
375 * Called with allocator lock held.
378 # define is_writable(prot) ((prot) == PAGE_READWRITE \
379 || (prot) == PAGE_WRITECOPY \
380 || (prot) == PAGE_EXECUTE_READWRITE \
381 || (prot) == PAGE_EXECUTE_WRITECOPY)
382 /* Return the number of bytes that are writable starting at p. */
383 /* The pointer p is assumed to be page aligned. */
384 /* If base is not 0, *base becomes the beginning of the */
385 /* allocation region containing p. */
386 word GC_get_writable_length(ptr_t p, ptr_t *base)
388 MEMORY_BASIC_INFORMATION buf;
392 result = VirtualQuery(p, &buf, sizeof(buf));
393 if (result != sizeof(buf)) ABORT("Weird VirtualQuery result");
394 if (base != 0) *base = (ptr_t)(buf.AllocationBase);
395 protect = (buf.Protect & ~(PAGE_GUARD | PAGE_NOCACHE));
396 if (!is_writable(protect)) {
399 if (buf.State != MEM_COMMIT) return(0);
400 return(buf.RegionSize);
403 ptr_t GC_get_stack_base()
406 ptr_t sp = (ptr_t)(&dummy);
407 ptr_t trunc_sp = (ptr_t)((word)sp & ~(GC_page_size - 1));
408 word size = GC_get_writable_length(trunc_sp, 0);
410 return(trunc_sp + size);
418 ptr_t GC_get_stack_base()
423 if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
424 GC_err_printf0("DosGetInfoBlocks failed\n");
425 ABORT("DosGetInfoBlocks failed\n");
427 return((ptr_t)(ptib -> tib_pstacklimit));
434 ptr_t GC_get_stack_base()
436 struct Process *proc = (struct Process*)SysBase->ThisTask;
438 /* Reference: Amiga Guru Book Pages: 42,567,574 */
439 if (proc->pr_Task.tc_Node.ln_Type==NT_PROCESS
440 && proc->pr_CLI != NULL) {
441 /* first ULONG is StackSize */
442 /*longPtr = proc->pr_ReturnAddr;
445 return (char *)proc->pr_ReturnAddr + sizeof(ULONG);
447 return (char *)proc->pr_Task.tc_SPUpper;
451 #if 0 /* old version */
452 ptr_t GC_get_stack_base()
454 extern struct WBStartup *_WBenchMsg;
458 struct Process *proc;
459 struct CommandLineInterface *cli;
462 if ((task = FindTask(0)) == 0) {
463 GC_err_puts("Cannot find own task structure\n");
464 ABORT("task missing");
466 proc = (struct Process *)task;
467 cli = BADDR(proc->pr_CLI);
469 if (_WBenchMsg != 0 || cli == 0) {
470 size = (char *)task->tc_SPUpper - (char *)task->tc_SPLower;
472 size = cli->cli_DefaultStack * 4;
474 return (ptr_t)(__base + GC_max(size, __stack));
478 # else /* !AMIGA, !OS2, ... */
480 # ifdef NEED_FIND_LIMIT
481 /* Some tools to implement HEURISTIC2 */
482 # define MIN_PAGE_SIZE 256 /* Smallest conceivable page size, bytes */
483 /* static */ jmp_buf GC_jmp_buf;
486 void GC_fault_handler(sig)
489 longjmp(GC_jmp_buf, 1);
493 typedef void (*handler)(int);
495 typedef void (*handler)();
498 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1)
499 static struct sigaction old_segv_act;
500 # if defined(_sigargs) /* !Irix6.x */
501 static struct sigaction old_bus_act;
504 static handler old_segv_handler, old_bus_handler;
507 void GC_setup_temporary_fault_handler()
509 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1)
510 struct sigaction act;
512 act.sa_handler = GC_fault_handler;
513 act.sa_flags = SA_RESTART | SA_NODEFER;
514 /* The presence of SA_NODEFER represents yet another gross */
515 /* hack. Under Solaris 2.3, siglongjmp doesn't appear to */
516 /* interact correctly with -lthread. We hide the confusion */
517 /* by making sure that signal handling doesn't affect the */
520 (void) sigemptyset(&act.sa_mask);
522 /* Older versions have a bug related to retrieving and */
523 /* and setting a handler at the same time. */
524 (void) sigaction(SIGSEGV, 0, &old_segv_act);
525 (void) sigaction(SIGSEGV, &act, 0);
527 (void) sigaction(SIGSEGV, &act, &old_segv_act);
528 # ifdef _sigargs /* Irix 5.x, not 6.x */
529 /* Under 5.x, we may get SIGBUS. */
530 /* Pthreads doesn't exist under 5.x, so we don't */
531 /* have to worry in the threads case. */
532 (void) sigaction(SIGBUS, &act, &old_bus_act);
534 # endif /* IRIX_THREADS */
536 old_segv_handler = signal(SIGSEGV, GC_fault_handler);
538 old_bus_handler = signal(SIGBUS, GC_fault_handler);
543 void GC_reset_fault_handler()
545 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1)
546 (void) sigaction(SIGSEGV, &old_segv_act, 0);
547 # ifdef _sigargs /* Irix 5.x, not 6.x */
548 (void) sigaction(SIGBUS, &old_bus_act, 0);
551 (void) signal(SIGSEGV, old_segv_handler);
553 (void) signal(SIGBUS, old_bus_handler);
558 /* Return the first nonaddressible location > p (up) or */
559 /* the smallest location q s.t. [q,p] is addressible (!up). */
560 ptr_t GC_find_limit(p, up)
564 static VOLATILE ptr_t result;
565 /* Needs to be static, since otherwise it may not be */
566 /* preserved across the longjmp. Can safely be */
567 /* static since it's only called once, with the */
568 /* allocation lock held. */
571 GC_setup_temporary_fault_handler();
572 if (setjmp(GC_jmp_buf) == 0) {
573 result = (ptr_t)(((word)(p))
574 & ~(MIN_PAGE_SIZE-1));
577 result += MIN_PAGE_SIZE;
579 result -= MIN_PAGE_SIZE;
581 GC_noop1((word)(*result));
584 GC_reset_fault_handler();
586 result += MIN_PAGE_SIZE;
593 ptr_t GC_get_stack_base()
598 # define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
604 # ifdef STACK_GROWS_DOWN
605 result = (ptr_t)((((word)(&dummy))
606 + STACKBOTTOM_ALIGNMENT_M1)
607 & ~STACKBOTTOM_ALIGNMENT_M1);
609 result = (ptr_t)(((word)(&dummy))
610 & ~STACKBOTTOM_ALIGNMENT_M1);
612 # endif /* HEURISTIC1 */
614 # ifdef STACK_GROWS_DOWN
615 result = GC_find_limit((ptr_t)(&dummy), TRUE);
616 # ifdef HEURISTIC2_LIMIT
617 if (result > HEURISTIC2_LIMIT
618 && (ptr_t)(&dummy) < HEURISTIC2_LIMIT) {
619 result = HEURISTIC2_LIMIT;
623 result = GC_find_limit((ptr_t)(&dummy), FALSE);
624 # ifdef HEURISTIC2_LIMIT
625 if (result < HEURISTIC2_LIMIT
626 && (ptr_t)(&dummy) > HEURISTIC2_LIMIT) {
627 result = HEURISTIC2_LIMIT;
632 # endif /* HEURISTIC2 */
633 # ifdef STACK_GROWS_DOWN
634 if (result == 0) result = (ptr_t)(signed_word)(-sizeof(ptr_t));
637 # endif /* STACKBOTTOM */
640 # endif /* ! AMIGA */
642 # endif /* ! MSWIN32 */
645 * Register static data segment(s) as roots.
646 * If more data segments are added later then they need to be registered
647 * add that point (as we do with SunOS dynamic loading),
648 * or GC_mark_roots needs to check for them (as we do with PCR).
649 * Called with allocator lock held.
654 void GC_register_data_segments()
658 HMODULE module_handle;
662 struct exe_hdr hdrdos; /* MSDOS header. */
663 struct e32_exe hdr386; /* Real header for my executable */
664 struct o32_obj seg; /* Currrent segment */
668 if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) {
669 GC_err_printf0("DosGetInfoBlocks failed\n");
670 ABORT("DosGetInfoBlocks failed\n");
672 module_handle = ppib -> pib_hmte;
673 if (DosQueryModuleName(module_handle, PBUFSIZ, path) != NO_ERROR) {
674 GC_err_printf0("DosQueryModuleName failed\n");
675 ABORT("DosGetInfoBlocks failed\n");
677 myexefile = fopen(path, "rb");
678 if (myexefile == 0) {
679 GC_err_puts("Couldn't open executable ");
680 GC_err_puts(path); GC_err_puts("\n");
681 ABORT("Failed to open executable\n");
683 if (fread((char *)(&hdrdos), 1, sizeof hdrdos, myexefile) < sizeof hdrdos) {
684 GC_err_puts("Couldn't read MSDOS header from ");
685 GC_err_puts(path); GC_err_puts("\n");
686 ABORT("Couldn't read MSDOS header");
688 if (E_MAGIC(hdrdos) != EMAGIC) {
689 GC_err_puts("Executable has wrong DOS magic number: ");
690 GC_err_puts(path); GC_err_puts("\n");
691 ABORT("Bad DOS magic number");
693 if (fseek(myexefile, E_LFANEW(hdrdos), SEEK_SET) != 0) {
694 GC_err_puts("Seek to new header failed in ");
695 GC_err_puts(path); GC_err_puts("\n");
696 ABORT("Bad DOS magic number");
698 if (fread((char *)(&hdr386), 1, sizeof hdr386, myexefile) < sizeof hdr386) {
699 GC_err_puts("Couldn't read MSDOS header from ");
700 GC_err_puts(path); GC_err_puts("\n");
701 ABORT("Couldn't read OS/2 header");
703 if (E32_MAGIC1(hdr386) != E32MAGIC1 || E32_MAGIC2(hdr386) != E32MAGIC2) {
704 GC_err_puts("Executable has wrong OS/2 magic number:");
705 GC_err_puts(path); GC_err_puts("\n");
706 ABORT("Bad OS/2 magic number");
708 if ( E32_BORDER(hdr386) != E32LEBO || E32_WORDER(hdr386) != E32LEWO) {
709 GC_err_puts("Executable %s has wrong byte order: ");
710 GC_err_puts(path); GC_err_puts("\n");
711 ABORT("Bad byte order");
713 if ( E32_CPU(hdr386) == E32CPU286) {
714 GC_err_puts("GC can't handle 80286 executables: ");
715 GC_err_puts(path); GC_err_puts("\n");
718 if (fseek(myexefile, E_LFANEW(hdrdos) + E32_OBJTAB(hdr386),
720 GC_err_puts("Seek to object table failed: ");
721 GC_err_puts(path); GC_err_puts("\n");
722 ABORT("Seek to object table failed");
724 for (nsegs = E32_OBJCNT(hdr386); nsegs > 0; nsegs--) {
726 if (fread((char *)(&seg), 1, sizeof seg, myexefile) < sizeof seg) {
727 GC_err_puts("Couldn't read obj table entry from ");
728 GC_err_puts(path); GC_err_puts("\n");
729 ABORT("Couldn't read obj table entry");
731 flags = O32_FLAGS(seg);
732 if (!(flags & OBJWRITE)) continue;
733 if (!(flags & OBJREAD)) continue;
734 if (flags & OBJINVALID) {
735 GC_err_printf0("Object with invalid pages?\n");
738 GC_add_roots_inner(O32_BASE(seg), O32_BASE(seg)+O32_SIZE(seg), FALSE);
745 /* Unfortunately, we have to handle win32s very differently from NT, */
746 /* Since VirtualQuery has very different semantics. In particular, */
747 /* under win32s a VirtualQuery call on an unmapped page returns an */
748 /* invalid result. Under GC_register_data_segments is a noop and */
749 /* all real work is done by GC_register_dynamic_libraries. Under */
750 /* win32s, we cannot find the data segments associated with dll's. */
751 /* We rgister the main data segment here. */
752 GC_bool GC_win32s = FALSE; /* We're running under win32s. */
754 GC_bool GC_is_win32s()
756 DWORD v = GetVersion();
758 /* Check that this is not NT, and Windows major version <= 3 */
759 return ((v & 0x80000000) && (v & 0xff) <= 3);
764 GC_win32s = GC_is_win32s();
767 /* Return the smallest address a such that VirtualQuery */
768 /* returns correct results for all addresses between a and start. */
769 /* Assumes VirtualQuery returns correct information for start. */
770 ptr_t GC_least_described_address(ptr_t start)
772 MEMORY_BASIC_INFORMATION buf;
779 GetSystemInfo(&sysinfo);
780 limit = sysinfo.lpMinimumApplicationAddress;
781 p = (ptr_t)((word)start & ~(GC_page_size - 1));
783 q = (LPVOID)(p - GC_page_size);
784 if ((ptr_t)q > (ptr_t)p /* underflow */ || q < limit) break;
785 result = VirtualQuery(q, &buf, sizeof(buf));
786 if (result != sizeof(buf) || buf.AllocationBase == 0) break;
787 p = (ptr_t)(buf.AllocationBase);
792 /* Is p the start of either the malloc heap, or of one of our */
794 GC_bool GC_is_heap_base (ptr_t p)
799 # ifndef REDIRECT_MALLOC
800 static ptr_t malloc_heap_pointer = 0;
802 if (0 == malloc_heap_pointer) {
803 MEMORY_BASIC_INFORMATION buf;
804 register DWORD result = VirtualQuery(malloc(1), &buf, sizeof(buf));
806 if (result != sizeof(buf)) {
807 ABORT("Weird VirtualQuery result");
809 malloc_heap_pointer = (ptr_t)(buf.AllocationBase);
811 if (p == malloc_heap_pointer) return(TRUE);
813 for (i = 0; i < GC_n_heap_bases; i++) {
814 if (GC_heap_bases[i] == p) return(TRUE);
819 void GC_register_root_section(ptr_t static_root)
821 MEMORY_BASIC_INFORMATION buf;
827 char * limit, * new_limit;
829 if (!GC_win32s) return;
830 p = base = limit = GC_least_described_address(static_root);
831 GetSystemInfo(&sysinfo);
832 while (p < sysinfo.lpMaximumApplicationAddress) {
833 result = VirtualQuery(p, &buf, sizeof(buf));
834 if (result != sizeof(buf) || buf.AllocationBase == 0
835 || GC_is_heap_base(buf.AllocationBase)) break;
836 new_limit = (char *)p + buf.RegionSize;
837 protect = buf.Protect;
838 if (buf.State == MEM_COMMIT
839 && is_writable(protect)) {
840 if ((char *)p == limit) {
843 if (base != limit) GC_add_roots_inner(base, limit, FALSE);
848 if (p > (LPVOID)new_limit /* overflow */) break;
849 p = (LPVOID)new_limit;
851 if (base != limit) GC_add_roots_inner(base, limit, FALSE);
854 void GC_register_data_segments()
858 GC_register_root_section((ptr_t)(&dummy));
863 void GC_register_data_segments()
865 struct Process *proc;
866 struct CommandLineInterface *cli;
875 GC_bool found_segment = FALSE;
876 extern char __data_size[];
878 dataSegSize=__data_size+8;
879 /* Can`t find the Location of __data_size, because
880 it`s possible that is it, inside the segment. */
884 proc= (struct Process*)SysBase->ThisTask;
886 /* Reference: Amiga Guru Book Pages: 538ff,565,573
888 if (proc->pr_Task.tc_Node.ln_Type==NT_PROCESS) {
889 if (proc->pr_CLI == NULL) {
890 myseglist = proc->pr_SegList;
892 /* ProcLoaded 'Loaded as a command: '*/
893 cli = BADDR(proc->pr_CLI);
894 myseglist = cli->cli_Module;
897 ABORT("Not a Process.");
900 if (myseglist == NULL) {
901 ABORT("Arrrgh.. can't find segments, aborting");
904 /* xoper hunks Shell Process */
907 for (data = (ULONG *)BADDR(myseglist); data != NULL;
908 data = (ULONG *)BADDR(data[0])) {
909 if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
910 ((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
912 if (dataSegSize == data[-1]) {
913 found_segment = TRUE;
916 GC_add_roots_inner((char *)&data[1],
917 ((char *)&data[1]) + data[-1], FALSE);
922 if (!found_segment) {
923 ABORT("Can`t find correct Segments.\nSolution: Use an newer version of ixemul.library");
928 #if 0 /* old version */
929 void GC_register_data_segments()
931 extern struct WBStartup *_WBenchMsg;
932 struct Process *proc;
933 struct CommandLineInterface *cli;
937 if ( _WBenchMsg != 0 ) {
938 if ((myseglist = _WBenchMsg->sm_Segment) == 0) {
939 GC_err_puts("No seglist from workbench\n");
943 if ((proc = (struct Process *)FindTask(0)) == 0) {
944 GC_err_puts("Cannot find process structure\n");
947 if ((cli = BADDR(proc->pr_CLI)) == 0) {
948 GC_err_puts("No CLI\n");
951 if ((myseglist = cli->cli_Module) == 0) {
952 GC_err_puts("No seglist from CLI\n");
957 for (data = (ULONG *)BADDR(myseglist); data != 0;
958 data = (ULONG *)BADDR(data[0])) {
959 # ifdef AMIGA_SKIP_SEG
960 if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
961 ((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
964 # endif /* AMIGA_SKIP_SEG */
965 GC_add_roots_inner((char *)&data[1],
966 ((char *)&data[1]) + data[-1], FALSE);
970 #endif /* old version */
975 # if (defined(SVR4) || defined(AUX) || defined(DGUX)) && !defined(PCR)
976 char * GC_SysVGetDataStart(max_page_size, etext_addr)
980 word text_end = ((word)(etext_addr) + sizeof(word) - 1)
981 & ~(sizeof(word) - 1);
982 /* etext rounded to word boundary */
983 word next_page = ((text_end + (word)max_page_size - 1)
984 & ~((word)max_page_size - 1));
985 word page_offset = (text_end & ((word)max_page_size - 1));
986 VOLATILE char * result = (char *)(next_page + page_offset);
987 /* Note that this isnt equivalent to just adding */
988 /* max_page_size to &etext if &etext is at a page boundary */
990 GC_setup_temporary_fault_handler();
991 if (setjmp(GC_jmp_buf) == 0) {
992 /* Try writing to the address. */
994 GC_reset_fault_handler();
996 GC_reset_fault_handler();
997 /* We got here via a longjmp. The address is not readable. */
998 /* This is known to happen under Solaris 2.4 + gcc, which place */
999 /* string constants in the text segment, but after etext. */
1000 /* Use plan B. Note that we now know there is a gap between */
1001 /* text and data segments, so plan A bought us something. */
1002 result = (char *)GC_find_limit((ptr_t)(DATAEND) - MIN_PAGE_SIZE, FALSE);
1004 return((char *)result);
1009 void GC_register_data_segments()
1011 # if !defined(PCR) && !defined(SRC_M3) && !defined(NEXT) && !defined(MACOS) \
1013 # if defined(REDIRECT_MALLOC) && defined(SOLARIS_THREADS)
1014 /* As of Solaris 2.3, the Solaris threads implementation */
1015 /* allocates the data structure for the initial thread with */
1016 /* sbrk at process startup. It needs to be scanned, so that */
1017 /* we don't lose some malloc allocated data structures */
1018 /* hanging from it. We're on thin ice here ... */
1019 extern caddr_t sbrk();
1021 GC_add_roots_inner(DATASTART, (char *)sbrk(0), FALSE);
1023 GC_add_roots_inner(DATASTART, (char *)(DATAEND), FALSE);
1026 # if !defined(PCR) && (defined(NEXT) || defined(MACOSX))
1027 GC_add_roots_inner(DATASTART, (char *) get_end(), FALSE);
1031 # if defined(THINK_C)
1032 extern void* GC_MacGetDataStart(void);
1033 /* globals begin above stack and end at a5. */
1034 GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
1035 (ptr_t)LMGetCurrentA5(), FALSE);
1037 # if defined(__MWERKS__)
1039 extern void* GC_MacGetDataStart(void);
1040 /* MATTHEW: Function to handle Far Globals (CW Pro 3) */
1041 # if __option(far_data)
1042 extern void* GC_MacGetDataEnd(void);
1044 /* globals begin above stack and end at a5. */
1045 GC_add_roots_inner((ptr_t)GC_MacGetDataStart(),
1046 (ptr_t)LMGetCurrentA5(), FALSE);
1047 /* MATTHEW: Handle Far Globals */
1048 # if __option(far_data)
1049 /* Far globals follow he QD globals: */
1050 GC_add_roots_inner((ptr_t)LMGetCurrentA5(),
1051 (ptr_t)GC_MacGetDataEnd(), FALSE);
1054 extern char __data_start__[], __data_end__[];
1055 GC_add_roots_inner((ptr_t)&__data_start__,
1056 (ptr_t)&__data_end__, FALSE);
1057 # endif /* __POWERPC__ */
1058 # endif /* __MWERKS__ */
1059 # endif /* !THINK_C */
1063 /* Dynamic libraries are added at every collection, since they may */
1067 # endif /* ! AMIGA */
1068 # endif /* ! MSWIN32 */
1072 * Auxiliary routines for obtaining memory from OS.
1075 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \
1076 && !defined(MSWIN32) && !defined(MACOS) && !defined(DOS4GW)
1079 extern caddr_t sbrk();
1082 # define SBRK_ARG_T ptrdiff_t
1084 # define SBRK_ARG_T int
1088 /* The compiler seems to generate speculative reads one past the end of */
1089 /* an allocated object. Hence we need to make sure that the page */
1090 /* following the last heap page is also mapped. */
1091 ptr_t GC_unix_get_mem(bytes)
1094 caddr_t cur_brk = (caddr_t)sbrk(0);
1096 SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
1097 static caddr_t my_brk_val = 0;
1099 if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
1101 if((caddr_t)(sbrk(GC_page_size - lsbs)) == (caddr_t)(-1)) return(0);
1103 if (cur_brk == my_brk_val) {
1104 /* Use the extra block we allocated last time. */
1105 result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
1106 if (result == (caddr_t)(-1)) return(0);
1107 result -= GC_page_size;
1109 result = (ptr_t)sbrk(GC_page_size + (SBRK_ARG_T)bytes);
1110 if (result == (caddr_t)(-1)) return(0);
1112 my_brk_val = result + bytes + GC_page_size; /* Always page aligned */
1113 return((ptr_t)result);
1116 #else /* Not RS6000 */
1118 #if defined(USE_MMAP)
1119 /* Tested only under IRIX5 and Solaris 2 */
1121 #ifdef USE_MMAP_FIXED
1122 # define GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE
1123 /* Seems to yield better performance on Solaris 2, but can */
1124 /* be unreliable if something is already mapped at the address. */
1126 # define GC_MMAP_FLAGS MAP_PRIVATE
1129 ptr_t GC_unix_get_mem(bytes)
1132 static GC_bool initialized = FALSE;
1135 static ptr_t last_addr = HEAP_START;
1138 fd = open("/dev/zero", O_RDONLY);
1141 if (bytes & (GC_page_size -1)) ABORT("Bad GET_MEM arg");
1142 result = mmap(last_addr, bytes, PROT_READ | PROT_WRITE | OPT_PROT_EXEC,
1143 GC_MMAP_FLAGS, fd, 0/* offset */);
1144 if (result == MAP_FAILED) return(0);
1145 last_addr = (ptr_t)result + bytes + GC_page_size - 1;
1146 last_addr = (ptr_t)((word)last_addr & ~(GC_page_size - 1));
1147 return((ptr_t)result);
1150 #else /* Not RS6000, not USE_MMAP */
1151 ptr_t GC_unix_get_mem(bytes)
1156 /* Bare sbrk isn't thread safe. Play by malloc rules. */
1157 /* The equivalent may be needed on other systems as well. */
1161 ptr_t cur_brk = (ptr_t)sbrk(0);
1162 SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1);
1164 if ((SBRK_ARG_T)bytes < 0) return(0); /* too big */
1166 if((ptr_t)sbrk(GC_page_size - lsbs) == (ptr_t)(-1)) return(0);
1168 result = (ptr_t)sbrk((SBRK_ARG_T)bytes);
1169 if (result == (ptr_t)(-1)) result = 0;
1177 #endif /* Not USE_MMAP */
1178 #endif /* Not RS6000 */
1184 void * os2_alloc(size_t bytes)
1188 if (DosAllocMem(&result, bytes, PAG_EXECUTE | PAG_READ |
1189 PAG_WRITE | PAG_COMMIT)
1193 if (result == 0) return(os2_alloc(bytes));
1201 word GC_n_heap_bases = 0;
1203 ptr_t GC_win32_get_mem(bytes)
1209 /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE. */
1210 /* There are also unconfirmed rumors of other */
1211 /* problems, so we dodge the issue. */
1212 result = (ptr_t) GlobalAlloc(0, bytes + HBLKSIZE);
1213 result = (ptr_t)(((word)result + HBLKSIZE) & ~(HBLKSIZE-1));
1215 result = (ptr_t) VirtualAlloc(NULL, bytes,
1216 MEM_COMMIT | MEM_RESERVE,
1217 PAGE_EXECUTE_READWRITE);
1219 if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1220 /* If I read the documentation correctly, this can */
1221 /* only happen if HBLKSIZE > 64k or not a power of 2. */
1222 if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections");
1223 GC_heap_bases[GC_n_heap_bases++] = result;
1227 void GC_win32_free_heap ()
1230 while (GC_n_heap_bases > 0) {
1231 GlobalFree (GC_heap_bases[--GC_n_heap_bases]);
1232 GC_heap_bases[GC_n_heap_bases] = 0;
1242 /* For now, this only works on some Unix-like systems. If you */
1243 /* have something else, don't define USE_MUNMAP. */
1244 /* We assume ANSI C to support this feature. */
1246 #include <sys/mman.h>
1247 #include <sys/stat.h>
1248 #include <sys/types.h>
1251 /* Compute a page aligned starting address for the unmap */
1252 /* operation on a block of size bytes starting at start. */
1253 /* Return 0 if the block is too small to make this feasible. */
1254 ptr_t GC_unmap_start(ptr_t start, word bytes)
1256 ptr_t result = start;
1257 /* Round start to next page boundary. */
1258 result += GC_page_size - 1;
1259 result = (ptr_t)((word)result & ~(GC_page_size - 1));
1260 if (result + GC_page_size > start + bytes) return 0;
1264 /* Compute end address for an unmap operation on the indicated */
1266 ptr_t GC_unmap_end(ptr_t start, word bytes)
1268 ptr_t end_addr = start + bytes;
1269 end_addr = (ptr_t)((word)end_addr & ~(GC_page_size - 1));
1273 /* We assume that GC_remap is called on exactly the same range */
1274 /* as a previous call to GC_unmap. It is safe to consistently */
1275 /* round the endpoints in both places. */
1276 void GC_unmap(ptr_t start, word bytes)
1278 ptr_t start_addr = GC_unmap_start(start, bytes);
1279 ptr_t end_addr = GC_unmap_end(start, bytes);
1280 word len = end_addr - start_addr;
1281 if (0 == start_addr) return;
1282 if (munmap(start_addr, len) != 0) ABORT("munmap failed");
1283 GC_unmapped_bytes += len;
1287 void GC_remap(ptr_t start, word bytes)
1289 static int zero_descr = -1;
1290 ptr_t start_addr = GC_unmap_start(start, bytes);
1291 ptr_t end_addr = GC_unmap_end(start, bytes);
1292 word len = end_addr - start_addr;
1295 if (-1 == zero_descr) zero_descr = open("/dev/zero", O_RDWR);
1296 if (0 == start_addr) return;
1297 result = mmap(start_addr, len, PROT_READ | PROT_WRITE | OPT_PROT_EXEC,
1298 MAP_FIXED | MAP_PRIVATE, zero_descr, 0);
1299 if (result != start_addr) {
1300 ABORT("mmap remapping failed");
1302 GC_unmapped_bytes -= len;
1305 /* Two adjacent blocks have already been unmapped and are about to */
1306 /* be merged. Unmap the whole block. This typically requires */
1307 /* that we unmap a small section in the middle that was not previously */
1308 /* unmapped due to alignment constraints. */
1309 void GC_unmap_gap(ptr_t start1, word bytes1, ptr_t start2, word bytes2)
1311 ptr_t start1_addr = GC_unmap_start(start1, bytes1);
1312 ptr_t end1_addr = GC_unmap_end(start1, bytes1);
1313 ptr_t start2_addr = GC_unmap_start(start2, bytes2);
1314 ptr_t end2_addr = GC_unmap_end(start2, bytes2);
1315 ptr_t start_addr = end1_addr;
1316 ptr_t end_addr = start2_addr;
1318 GC_ASSERT(start1 + bytes1 == start2);
1319 if (0 == start1_addr) start_addr = GC_unmap_start(start1, bytes1 + bytes2);
1320 if (0 == start2_addr) end_addr = GC_unmap_end(start1, bytes1 + bytes2);
1321 if (0 == start_addr) return;
1322 len = end_addr - start_addr;
1323 if (len != 0 && munmap(start_addr, len) != 0) ABORT("munmap failed");
1324 GC_unmapped_bytes += len;
1327 #endif /* USE_MUNMAP */
1329 /* Routine for pushing any additional roots. In THREADS */
1330 /* environment, this is also responsible for marking from */
1331 /* thread stacks. In the SRC_M3 case, it also handles */
1332 /* global variables. */
1334 void (*GC_push_other_roots)() = 0;
1338 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
1340 struct PCR_ThCtl_TInfoRep info;
1343 info.ti_stkLow = info.ti_stkHi = 0;
1344 result = PCR_ThCtl_GetInfo(t, &info);
1345 GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi));
1349 /* Push the contents of an old object. We treat this as stack */
1350 /* data only becasue that makes it robust against mark stack */
1352 PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data)
1354 GC_push_all_stack((ptr_t)p, (ptr_t)p + size);
1355 return(PCR_ERes_okay);
1359 void GC_default_push_other_roots()
1361 /* Traverse data allocated by previous memory managers. */
1363 extern struct PCR_MM_ProcsRep * GC_old_allocator;
1365 if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false,
1368 ABORT("Old object enumeration failed");
1371 /* Traverse all thread stacks. */
1373 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0))
1374 || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
1375 ABORT("Thread stack marking failed\n");
1383 # ifdef ALL_INTERIOR_POINTERS
1388 extern void ThreadF__ProcessStacks();
1390 void GC_push_thread_stack(start, stop)
1393 GC_push_all_stack((ptr_t)start, (ptr_t)stop + sizeof(word));
1396 /* Push routine with M3 specific calling convention. */
1397 GC_m3_push_root(dummy1, p, dummy2, dummy3)
1399 ptr_t dummy1, dummy2;
1404 if ((ptr_t)(q) >= GC_least_plausible_heap_addr
1405 && (ptr_t)(q) < GC_greatest_plausible_heap_addr) {
1406 GC_push_one_checked(q,FALSE);
1410 /* M3 set equivalent to RTHeap.TracedRefTypes */
1411 typedef struct { int elts[1]; } RefTypeSet;
1412 RefTypeSet GC_TracedRefTypes = {{0x1}};
1414 /* From finalize.c */
1415 extern void GC_push_finalizer_structures();
1417 /* From stubborn.c: */
1418 # ifdef STUBBORN_ALLOC
1419 extern GC_PTR * GC_changing_list_start;
1423 void GC_default_push_other_roots()
1425 /* Use the M3 provided routine for finding static roots. */
1426 /* This is a bit dubious, since it presumes no C roots. */
1427 /* We handle the collector roots explicitly. */
1429 # ifdef STUBBORN_ALLOC
1430 GC_push_one(GC_changing_list_start);
1432 GC_push_finalizer_structures();
1433 RTMain__GlobalMapProc(GC_m3_push_root, 0, GC_TracedRefTypes);
1435 if (GC_words_allocd > 0) {
1436 ThreadF__ProcessStacks(GC_push_thread_stack);
1438 /* Otherwise this isn't absolutely necessary, and we have */
1439 /* startup ordering problems. */
1442 # endif /* SRC_M3 */
1444 # if defined(SOLARIS_THREADS) || defined(WIN32_THREADS) \
1445 || defined(IRIX_THREADS) || defined(LINUX_THREADS) \
1446 || defined(IRIX_PCR_THREADS)
1448 extern void GC_push_all_stacks();
1450 void GC_default_push_other_roots()
1452 GC_push_all_stacks();
1455 # endif /* SOLARIS_THREADS || ... */
1457 void (*GC_push_other_roots)() = GC_default_push_other_roots;
1462 * Routines for accessing dirty bits on virtual pages.
1463 * We plan to eventaually implement four strategies for doing so:
1464 * DEFAULT_VDB: A simple dummy implementation that treats every page
1465 * as possibly dirty. This makes incremental collection
1466 * useless, but the implementation is still correct.
1467 * PCR_VDB: Use PPCRs virtual dirty bit facility.
1468 * PROC_VDB: Use the /proc facility for reading dirty bits. Only
1469 * works under some SVR4 variants. Even then, it may be
1470 * too slow to be entirely satisfactory. Requires reading
1471 * dirty bits for entire address space. Implementations tend
1472 * to assume that the client is a (slow) debugger.
1473 * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
1474 * dirtied pages. The implementation (and implementability)
1475 * is highly system dependent. This usually fails when system
1476 * calls write to a protected page. We prevent the read system
1477 * call from doing so. It is the clients responsibility to
1478 * make sure that other system calls are similarly protected
1479 * or write only to the stack.
1482 GC_bool GC_dirty_maintained = FALSE;
1486 /* All of the following assume the allocation lock is held, and */
1487 /* signals are disabled. */
1489 /* The client asserts that unallocated pages in the heap are never */
1492 /* Initialize virtual dirty bit implementation. */
1493 void GC_dirty_init()
1495 GC_dirty_maintained = TRUE;
1498 /* Retrieve system dirty bits for heap to a local buffer. */
1499 /* Restore the systems notion of which pages are dirty. */
1500 void GC_read_dirty()
1503 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */
1504 /* If the actual page size is different, this returns TRUE if any */
1505 /* of the pages overlapping h are dirty. This routine may err on the */
1506 /* side of labelling pages as dirty (and this implementation does). */
1508 GC_bool GC_page_was_dirty(h)
1515 * The following two routines are typically less crucial. They matter
1516 * most with large dynamic libraries, or if we can't accurately identify
1517 * stacks, e.g. under Solaris 2.X. Otherwise the following default
1518 * versions are adequate.
1521 /* Could any valid GC heap pointer ever have been written to this page? */
1523 GC_bool GC_page_was_ever_dirty(h)
1529 /* Reset the n pages starting at h to "was never dirty" status. */
1530 void GC_is_fresh(h, n)
1536 /* A call hints that h is about to be written. */
1537 /* May speed up some dirty bit implementations. */
1539 void GC_write_hint(h)
1544 # endif /* DEFAULT_VDB */
1547 # ifdef MPROTECT_VDB
1550 * See DEFAULT_VDB for interface descriptions.
1554 * This implementation maintains dirty bits itself by catching write
1555 * faults and keeping track of them. We assume nobody else catches
1556 * SIGBUS or SIGSEGV. We assume no write faults occur in system calls
1557 * except as a result of a read system call. This means clients must
1558 * either ensure that system calls do not touch the heap, or must
1559 * provide their own wrappers analogous to the one for read.
1560 * We assume the page size is a multiple of HBLKSIZE.
1561 * This implementation is currently SunOS 4.X and IRIX 5.X specific, though we
1562 * tried to use portable code where easily possible. It is known
1563 * not to work under a number of other systems.
1568 # include <sys/mman.h>
1569 # include <signal.h>
1570 # include <sys/syscall.h>
1572 # define PROTECT(addr, len) \
1573 if (mprotect((caddr_t)(addr), (int)(len), \
1574 PROT_READ | OPT_PROT_EXEC) < 0) { \
1575 ABORT("mprotect failed"); \
1577 # define UNPROTECT(addr, len) \
1578 if (mprotect((caddr_t)(addr), (int)(len), \
1579 PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
1580 ABORT("un-mprotect failed"); \
1585 # include <signal.h>
1587 static DWORD protect_junk;
1588 # define PROTECT(addr, len) \
1589 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
1591 DWORD last_error = GetLastError(); \
1592 GC_printf1("Last error code: %lx\n", last_error); \
1593 ABORT("VirtualProtect failed"); \
1595 # define UNPROTECT(addr, len) \
1596 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
1598 ABORT("un-VirtualProtect failed"); \
1603 #if defined(SUNOS4) || defined(FREEBSD)
1604 typedef void (* SIG_PF)();
1606 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX)
1607 typedef void (* SIG_PF)(int);
1609 #if defined(MSWIN32)
1610 typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
1612 # define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
1615 #if defined(IRIX5) || defined(OSF1)
1616 typedef void (* REAL_SIG_PF)(int, int, struct sigcontext *);
1618 #if defined(SUNOS5SIGS)
1619 typedef void (* REAL_SIG_PF)(int, struct siginfo *, void *);
1622 # include <linux/version.h>
1623 # if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA)
1624 typedef struct sigcontext s_c;
1626 typedef struct sigcontext_struct s_c;
1629 typedef void (* REAL_SIG_PF)(int, int, s_c *);
1630 /* Retrieve fault address from sigcontext structure by decoding */
1632 char * get_fault_addr(s_c *sc) {
1636 instr = *((unsigned *)(sc->sc_pc));
1637 faultaddr = sc->sc_regs[(instr >> 16) & 0x1f];
1638 faultaddr += (word) (((int)instr << 16) >> 16);
1639 return (char *)faultaddr;
1642 typedef void (* REAL_SIG_PF)(int, s_c);
1643 # endif /* !ALPHA */
1646 SIG_PF GC_old_bus_handler;
1647 SIG_PF GC_old_segv_handler; /* Also old MSWIN32 ACCESS_VIOLATION filter */
1650 # if defined (SUNOS4) || defined(FREEBSD)
1651 void GC_write_fault_handler(sig, code, scp, addr)
1653 struct sigcontext *scp;
1656 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
1657 # define CODE_OK (FC_CODE(code) == FC_PROT \
1658 || (FC_CODE(code) == FC_OBJERR \
1659 && FC_ERRNO(code) == FC_PROT))
1662 # define SIG_OK (sig == SIGBUS)
1663 # define CODE_OK (code == BUS_PAGE_FAULT)
1666 # if defined(IRIX5) || defined(OSF1)
1668 void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
1669 # define SIG_OK (sig == SIGSEGV)
1671 # define CODE_OK (code == 2 /* experimentally determined */)
1674 # define CODE_OK (code == EACCES)
1679 void GC_write_fault_handler(int sig, int code, s_c * sc)
1681 void GC_write_fault_handler(int sig, s_c sc)
1683 # define SIG_OK (sig == SIGSEGV)
1684 # define CODE_OK TRUE
1685 /* Empirically c.trapno == 14, but is that useful? */
1686 /* We assume Intel architecture, so alignment */
1687 /* faults are not possible. */
1689 # if defined(SUNOS5SIGS)
1690 void GC_write_fault_handler(int sig, struct siginfo *scp, void * context)
1691 # define SIG_OK (sig == SIGSEGV)
1692 # define CODE_OK (scp -> si_code == SEGV_ACCERR)
1694 # if defined(MSWIN32)
1695 LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info)
1696 # define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
1697 EXCEPTION_ACCESS_VIOLATION)
1698 # define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
1702 register unsigned i;
1704 char * addr = (char *) (size_t) (scp -> sc_badvaddr);
1706 # if defined(OSF1) && defined(ALPHA)
1707 char * addr = (char *) (scp -> sc_traparg_a0);
1710 char * addr = (char *) (scp -> si_addr);
1714 char * addr = (char *) (sc.cr2);
1719 struct sigcontext *scp = (struct sigcontext *)(&sc);
1721 int format = (scp->sc_formatvec >> 12) & 0xf;
1722 unsigned long *framedata = (unsigned long *)(scp + 1);
1725 if (format == 0xa || format == 0xb) {
1728 } else if (format == 7) {
1731 } else if (format == 4) {
1734 if (framedata[1] & 0x08000000) {
1735 /* correct addr on misaligned access */
1736 ea = (ea+4095)&(~4095);
1742 char * addr = get_fault_addr(sc);
1744 --> architecture not supported
1749 # if defined(MSWIN32)
1750 char * addr = (char *) (exc_info -> ExceptionRecord
1751 -> ExceptionInformation[1]);
1752 # define sig SIGSEGV
1755 if (SIG_OK && CODE_OK) {
1756 register struct hblk * h =
1757 (struct hblk *)((word)addr & ~(GC_page_size-1));
1758 GC_bool in_allocd_block;
1761 /* Address is only within the correct physical page. */
1762 in_allocd_block = FALSE;
1763 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
1764 if (HDR(h+i) != 0) {
1765 in_allocd_block = TRUE;
1769 in_allocd_block = (HDR(addr) != 0);
1771 if (!in_allocd_block) {
1772 /* Heap blocks now begin and end on page boundaries */
1775 if (sig == SIGSEGV) {
1776 old_handler = GC_old_segv_handler;
1778 old_handler = GC_old_bus_handler;
1780 if (old_handler == SIG_DFL) {
1782 GC_err_printf1("Segfault at 0x%lx\n", addr);
1783 ABORT("Unexpected bus error or segmentation fault");
1785 return(EXCEPTION_CONTINUE_SEARCH);
1788 # if defined (SUNOS4) || defined(FREEBSD)
1789 (*old_handler) (sig, code, scp, addr);
1792 # if defined (SUNOS5SIGS)
1793 (*(REAL_SIG_PF)old_handler) (sig, scp, context);
1796 # if defined (LINUX)
1798 (*(REAL_SIG_PF)old_handler) (sig, code, sc);
1800 (*(REAL_SIG_PF)old_handler) (sig, sc);
1804 # if defined (IRIX5) || defined(OSF1)
1805 (*(REAL_SIG_PF)old_handler) (sig, code, scp);
1809 return((*old_handler)(exc_info));
1813 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
1814 register int index = PHT_HASH(h+i);
1816 set_pht_entry_from_index(GC_dirty_pages, index);
1818 UNPROTECT(h, GC_page_size);
1819 # if defined(OSF1) || defined(LINUX)
1820 /* These reset the signal handler each time by default. */
1821 signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
1823 /* The write may not take place before dirty bits are read. */
1824 /* But then we'll fault again ... */
1826 return(EXCEPTION_CONTINUE_EXECUTION);
1832 return EXCEPTION_CONTINUE_SEARCH;
1834 GC_err_printf1("Segfault at 0x%lx\n", addr);
1835 ABORT("Unexpected bus error or segmentation fault");
1840 * We hold the allocation lock. We expect block h to be written
1843 void GC_write_hint(h)
1846 register struct hblk * h_trunc;
1847 register unsigned i;
1848 register GC_bool found_clean;
1850 if (!GC_dirty_maintained) return;
1851 h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1));
1852 found_clean = FALSE;
1853 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
1854 register int index = PHT_HASH(h_trunc+i);
1856 if (!get_pht_entry_from_index(GC_dirty_pages, index)) {
1858 set_pht_entry_from_index(GC_dirty_pages, index);
1862 UNPROTECT(h_trunc, GC_page_size);
1866 void GC_dirty_init()
1868 #if defined(SUNOS5SIGS) || defined(IRIX5) /* || defined(OSF1) */
1869 struct sigaction act, oldact;
1871 act.sa_flags = SA_RESTART;
1872 act.sa_handler = GC_write_fault_handler;
1874 act.sa_flags = SA_RESTART | SA_SIGINFO;
1875 act.sa_sigaction = GC_write_fault_handler;
1877 (void)sigemptyset(&act.sa_mask);
1880 GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
1882 GC_dirty_maintained = TRUE;
1883 if (GC_page_size % HBLKSIZE != 0) {
1884 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
1885 ABORT("Page size not multiple of HBLKSIZE");
1887 # if defined(SUNOS4) || defined(FREEBSD)
1888 GC_old_bus_handler = signal(SIGBUS, GC_write_fault_handler);
1889 if (GC_old_bus_handler == SIG_IGN) {
1890 GC_err_printf0("Previously ignored bus error!?");
1891 GC_old_bus_handler = SIG_DFL;
1893 if (GC_old_bus_handler != SIG_DFL) {
1895 GC_err_printf0("Replaced other SIGBUS handler\n");
1899 # if defined(OSF1) || defined(SUNOS4) || defined(LINUX)
1900 GC_old_segv_handler = signal(SIGSEGV, (SIG_PF)GC_write_fault_handler);
1901 if (GC_old_segv_handler == SIG_IGN) {
1902 GC_err_printf0("Previously ignored segmentation violation!?");
1903 GC_old_segv_handler = SIG_DFL;
1905 if (GC_old_segv_handler != SIG_DFL) {
1907 GC_err_printf0("Replaced other SIGSEGV handler\n");
1911 # if defined(SUNOS5SIGS) || defined(IRIX5)
1912 # if defined(IRIX_THREADS) || defined(IRIX_PCR_THREADS)
1913 sigaction(SIGSEGV, 0, &oldact);
1914 sigaction(SIGSEGV, &act, 0);
1916 sigaction(SIGSEGV, &act, &oldact);
1918 # if defined(_sigargs)
1919 /* This is Irix 5.x, not 6.x. Irix 5.x does not have */
1921 GC_old_segv_handler = oldact.sa_handler;
1922 # else /* Irix 6.x or SUNOS5SIGS */
1923 if (oldact.sa_flags & SA_SIGINFO) {
1924 GC_old_segv_handler = (SIG_PF)(oldact.sa_sigaction);
1926 GC_old_segv_handler = oldact.sa_handler;
1929 if (GC_old_segv_handler == SIG_IGN) {
1930 GC_err_printf0("Previously ignored segmentation violation!?");
1931 GC_old_segv_handler = SIG_DFL;
1933 if (GC_old_segv_handler != SIG_DFL) {
1935 GC_err_printf0("Replaced other SIGSEGV handler\n");
1939 # if defined(MSWIN32)
1940 GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler);
1941 if (GC_old_segv_handler != NULL) {
1943 GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
1946 GC_old_segv_handler = SIG_DFL;
1953 void GC_protect_heap()
1959 for (i = 0; i < GC_n_heap_sects; i++) {
1960 start = GC_heap_sects[i].hs_start;
1961 len = GC_heap_sects[i].hs_bytes;
1962 PROTECT(start, len);
1966 /* We assume that either the world is stopped or its OK to lose dirty */
1967 /* bits while this is happenning (as in GC_enable_incremental). */
1968 void GC_read_dirty()
1970 BCOPY((word *)GC_dirty_pages, GC_grungy_pages,
1971 (sizeof GC_dirty_pages));
1972 BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages));
1976 GC_bool GC_page_was_dirty(h)
1979 register word index = PHT_HASH(h);
1981 return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index));
1985 * Acquiring the allocation lock here is dangerous, since this
1986 * can be called from within GC_call_with_alloc_lock, and the cord
1987 * package does so. On systems that allow nested lock acquisition, this
1989 * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
1992 void GC_begin_syscall()
1994 if (!I_HOLD_LOCK()) LOCK();
1997 void GC_end_syscall()
1999 if (!I_HOLD_LOCK()) UNLOCK();
2002 void GC_unprotect_range(addr, len)
2006 struct hblk * start_block;
2007 struct hblk * end_block;
2008 register struct hblk *h;
2011 if (!GC_incremental) return;
2012 obj_start = GC_base(addr);
2013 if (obj_start == 0) return;
2014 if (GC_base(addr + len - 1) != obj_start) {
2015 ABORT("GC_unprotect_range(range bigger than object)");
2017 start_block = (struct hblk *)((word)addr & ~(GC_page_size - 1));
2018 end_block = (struct hblk *)((word)(addr + len - 1) & ~(GC_page_size - 1));
2019 end_block += GC_page_size/HBLKSIZE - 1;
2020 for (h = start_block; h <= end_block; h++) {
2021 register word index = PHT_HASH(h);
2023 set_pht_entry_from_index(GC_dirty_pages, index);
2025 UNPROTECT(start_block,
2026 ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE);
2030 /* Replacement for UNIX system call. */
2031 /* Other calls that write to the heap */
2032 /* should be handled similarly. */
2033 # if defined(__STDC__) && !defined(SUNOS4)
2034 # include <unistd.h>
2035 ssize_t read(int fd, void *buf, size_t nbyte)
2038 int read(fd, buf, nbyte)
2040 int GC_read(fd, buf, nbyte)
2050 GC_unprotect_range(buf, (word)nbyte);
2052 /* Indirect system call may not always be easily available. */
2053 /* We could call _read, but that would interfere with the */
2054 /* libpthread interception of read. */
2059 iov.iov_len = nbyte;
2060 result = readv(fd, &iov, 1);
2063 result = syscall(SYS_read, fd, buf, nbyte);
2068 #endif /* !MSWIN32 */
2071 GC_bool GC_page_was_ever_dirty(h)
2077 /* Reset the n pages starting at h to "was never dirty" status. */
2079 void GC_is_fresh(h, n)
2085 # endif /* MPROTECT_VDB */
2090 * See DEFAULT_VDB for interface descriptions.
2094 * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
2095 * from which we can read page modified bits. This facility is far from
2096 * optimal (e.g. we would like to get the info for only some of the
2097 * address space), but it avoids intercepting system calls.
2101 #include <sys/types.h>
2102 #include <sys/signal.h>
2103 #include <sys/fault.h>
2104 #include <sys/syscall.h>
2105 #include <sys/procfs.h>
2106 #include <sys/stat.h>
2109 #define INITIAL_BUF_SZ 4096
2110 word GC_proc_buf_size = INITIAL_BUF_SZ;
2113 #ifdef SOLARIS_THREADS
2114 /* We don't have exact sp values for threads. So we count on */
2115 /* occasionally declaring stack pages to be fresh. Thus we */
2116 /* need a real implementation of GC_is_fresh. We can't clear */
2117 /* entries in GC_written_pages, since that would declare all */
2118 /* pages with the given hash address to be fresh. */
2119 # define MAX_FRESH_PAGES 8*1024 /* Must be power of 2 */
2120 struct hblk ** GC_fresh_pages; /* A direct mapped cache. */
2121 /* Collisions are dropped. */
2123 # define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
2124 # define ADD_FRESH_PAGE(h) \
2125 GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
2126 # define PAGE_IS_FRESH(h) \
2127 (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
2130 /* Add all pages in pht2 to pht1 */
2131 void GC_or_pages(pht1, pht2)
2132 page_hash_table pht1, pht2;
2136 for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
2141 void GC_dirty_init()
2146 GC_dirty_maintained = TRUE;
2147 if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
2150 for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
2152 GC_printf1("Allocated words:%lu:all pages may have been written\n",
2154 (GC_words_allocd + GC_words_allocd_before_gc));
2157 sprintf(buf, "/proc/%d", getpid());
2158 fd = open(buf, O_RDONLY);
2160 ABORT("/proc open failed");
2162 GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
2164 if (GC_proc_fd < 0) {
2165 ABORT("/proc ioctl failed");
2167 GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size);
2168 # ifdef SOLARIS_THREADS
2169 GC_fresh_pages = (struct hblk **)
2170 GC_scratch_alloc(MAX_FRESH_PAGES * sizeof (struct hblk *));
2171 if (GC_fresh_pages == 0) {
2172 GC_err_printf0("No space for fresh pages\n");
2175 BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
2179 /* Ignore write hints. They don't help us here. */
2181 void GC_write_hint(h)
2186 #ifdef SOLARIS_THREADS
2187 # define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
2189 # define READ(fd,buf,nbytes) read(fd, buf, nbytes)
2192 void GC_read_dirty()
2194 unsigned long ps, np;
2197 struct prasmap * map;
2199 ptr_t current_addr, limit;
2203 BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
2206 if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
2208 GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
2212 /* Retry with larger buffer. */
2213 word new_size = 2 * GC_proc_buf_size;
2214 char * new_buf = GC_scratch_alloc(new_size);
2217 GC_proc_buf = bufp = new_buf;
2218 GC_proc_buf_size = new_size;
2220 if (syscall(SYS_read, GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
2221 WARN("Insufficient space for /proc read\n", 0);
2223 memset(GC_grungy_pages, 0xff, sizeof (page_hash_table));
2224 memset(GC_written_pages, 0xff, sizeof(page_hash_table));
2225 # ifdef SOLARIS_THREADS
2226 BZERO(GC_fresh_pages,
2227 MAX_FRESH_PAGES * sizeof (struct hblk *));
2233 /* Copy dirty bits into GC_grungy_pages */
2234 nmaps = ((struct prpageheader *)bufp) -> pr_nmap;
2235 /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
2236 nmaps, PG_REFERENCED, PG_MODIFIED); */
2237 bufp = bufp + sizeof(struct prpageheader);
2238 for (i = 0; i < nmaps; i++) {
2239 map = (struct prasmap *)bufp;
2240 vaddr = (ptr_t)(map -> pr_vaddr);
2241 ps = map -> pr_pagesize;
2242 np = map -> pr_npage;
2243 /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
2244 limit = vaddr + ps * np;
2245 bufp += sizeof (struct prasmap);
2246 for (current_addr = vaddr;
2247 current_addr < limit; current_addr += ps){
2248 if ((*bufp++) & PG_MODIFIED) {
2249 register struct hblk * h = (struct hblk *) current_addr;
2251 while ((ptr_t)h < current_addr + ps) {
2252 register word index = PHT_HASH(h);
2254 set_pht_entry_from_index(GC_grungy_pages, index);
2255 # ifdef SOLARIS_THREADS
2257 register int slot = FRESH_PAGE_SLOT(h);
2259 if (GC_fresh_pages[slot] == h) {
2260 GC_fresh_pages[slot] = 0;
2268 bufp += sizeof(long) - 1;
2269 bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1));
2271 /* Update GC_written_pages. */
2272 GC_or_pages(GC_written_pages, GC_grungy_pages);
2273 # ifdef SOLARIS_THREADS
2274 /* Make sure that old stacks are considered completely clean */
2275 /* unless written again. */
2276 GC_old_stacks_are_fresh();
2282 GC_bool GC_page_was_dirty(h)
2285 register word index = PHT_HASH(h);
2286 register GC_bool result;
2288 result = get_pht_entry_from_index(GC_grungy_pages, index);
2289 # ifdef SOLARIS_THREADS
2290 if (result && PAGE_IS_FRESH(h)) result = FALSE;
2291 /* This happens only if page was declared fresh since */
2292 /* the read_dirty call, e.g. because it's in an unused */
2293 /* thread stack. It's OK to treat it as clean, in */
2294 /* that case. And it's consistent with */
2295 /* GC_page_was_ever_dirty. */
2300 GC_bool GC_page_was_ever_dirty(h)
2303 register word index = PHT_HASH(h);
2304 register GC_bool result;
2306 result = get_pht_entry_from_index(GC_written_pages, index);
2307 # ifdef SOLARIS_THREADS
2308 if (result && PAGE_IS_FRESH(h)) result = FALSE;
2313 /* Caller holds allocation lock. */
2314 void GC_is_fresh(h, n)
2319 register word index;
2321 # ifdef SOLARIS_THREADS
2324 if (GC_fresh_pages != 0) {
2325 for (i = 0; i < n; i++) {
2326 ADD_FRESH_PAGE(h + i);
2332 # endif /* PROC_VDB */
2337 # include "vd/PCR_VD.h"
2339 # define NPAGES (32*1024) /* 128 MB */
2341 PCR_VD_DB GC_grungy_bits[NPAGES];
2343 ptr_t GC_vd_base; /* Address corresponding to GC_grungy_bits[0] */
2344 /* HBLKSIZE aligned. */
2346 void GC_dirty_init()
2348 GC_dirty_maintained = TRUE;
2349 /* For the time being, we assume the heap generally grows up */
2350 GC_vd_base = GC_heap_sects[0].hs_start;
2351 if (GC_vd_base == 0) {
2352 ABORT("Bad initial heap segment");
2354 if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE)
2356 ABORT("dirty bit initialization failed");
2360 void GC_read_dirty()
2362 /* lazily enable dirty bits on newly added heap sects */
2364 static int onhs = 0;
2365 int nhs = GC_n_heap_sects;
2366 for( ; onhs < nhs; onhs++ ) {
2367 PCR_VD_WriteProtectEnable(
2368 GC_heap_sects[onhs].hs_start,
2369 GC_heap_sects[onhs].hs_bytes );
2374 if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits)
2376 ABORT("dirty bit read failed");
2380 GC_bool GC_page_was_dirty(h)
2383 if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
2386 return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
2390 void GC_write_hint(h)
2393 PCR_VD_WriteProtectDisable(h, HBLKSIZE);
2394 PCR_VD_WriteProtectEnable(h, HBLKSIZE);
2397 # endif /* PCR_VDB */
2400 * Call stack save code for debugging.
2401 * Should probably be in mach_dep.c, but that requires reorganization.
2403 #if defined(SPARC) && !defined(LINUX)
2404 # if defined(SUNOS4)
2405 # include <machine/frame.h>
2407 # if defined (DRSNX)
2408 # include <sys/sparc/frame.h>
2410 # if defined(OPENBSD)
2413 # include <sys/frame.h>
2418 --> We only know how to to get the first 6 arguments
2421 #ifdef SAVE_CALL_CHAIN
2422 /* Fill in the pc and argument information for up to NFRAMES of my */
2423 /* callers. Ignore my frame and my callers frame. */
2426 # define FR_SAVFP fr_fp
2427 # define FR_SAVPC fr_pc
2429 # define FR_SAVFP fr_savfp
2430 # define FR_SAVPC fr_savpc
2433 void GC_save_callers (info)
2434 struct callinfo info[NFRAMES];
2436 struct frame *frame;
2439 word GC_save_regs_in_stack();
2441 frame = (struct frame *) GC_save_regs_in_stack ();
2443 for (fp = frame -> FR_SAVFP; fp != 0 && nframes < NFRAMES;
2444 fp = fp -> FR_SAVFP, nframes++) {
2447 info[nframes].ci_pc = fp->FR_SAVPC;
2448 for (i = 0; i < NARGS; i++) {
2449 info[nframes].ci_arg[i] = ~(fp->fr_arg[i]);
2452 if (nframes < NFRAMES) info[nframes].ci_pc = 0;
2455 #endif /* SAVE_CALL_CHAIN */