2 * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3 * Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved.
4 * Copyright (c) 1996-1999 by Silicon Graphics. All rights reserved.
5 * Copyright (c) 1999 by Hewlett-Packard Company. All rights reserved.
7 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
10 * Permission is hereby granted to use or copy this program
11 * for any purpose, provided the above notices are retained on all copies.
12 * Permission to modify the code and to distribute modified code is granted,
13 * provided the above notices are retained, and a notice that the code was
14 * modified is included with the above copyright notice.
17 # include "private/gc_priv.h"
19 # if defined(LINUX) && !defined(POWERPC)
20 # include <linux/version.h>
21 # if (LINUX_VERSION_CODE <= 0x10400)
22 /* Ugly hack to get struct sigcontext_struct definition. Required */
23 /* for some early 1.3.X releases. Will hopefully go away soon. */
24 /* in some later Linux releases, asm/sigcontext.h may have to */
25 /* be included instead. */
27 # include <asm/signal.h>
30 /* Kernels prior to 2.1.1 defined struct sigcontext_struct instead of */
31 /* struct sigcontext. libc6 (glibc2) uses "struct sigcontext" in */
32 /* prototypes, so we have to include the top-level sigcontext.h to */
33 /* make sure the former gets defined to be the latter if appropriate. */
34 # include <features.h>
36 # if 2 == __GLIBC__ && 0 == __GLIBC_MINOR__
37 /* glibc 2.1 no longer has sigcontext.h. But signal.h */
38 /* has the right declaration for glibc 2.1. */
39 # include <sigcontext.h>
40 # endif /* 0 == __GLIBC_MINOR__ */
41 # else /* not 2 <= __GLIBC__ */
42 /* libc5 doesn't have <sigcontext.h>: go directly with the kernel */
43 /* one. Check LINUX_VERSION_CODE to see which we should reference. */
44 # include <asm/sigcontext.h>
45 # endif /* 2 <= __GLIBC__ */
48 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) && !defined(MACOS) \
50 # include <sys/types.h>
51 # if !defined(MSWIN32) && !defined(SUNOS4)
58 # define SIGSEGV 0 /* value is irrelevant */
63 /* Blatantly OS dependent routines, except for those that are related */
64 /* to dynamic loading. */
66 # if defined(HEURISTIC2) || defined(SEARCH_FOR_DATA_START)
67 # define NEED_FIND_LIMIT
70 # if !defined(STACKBOTTOM) && defined(HEURISTIC2)
71 # define NEED_FIND_LIMIT
74 # if (defined(SUNOS4) && defined(DYNAMIC_LOADING)) && !defined(PCR)
75 # define NEED_FIND_LIMIT
78 # if (defined(SVR4) || defined(AUX) || defined(DGUX) \
79 || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
80 # define NEED_FIND_LIMIT
83 #if defined(FREEBSD) && defined(I386)
84 # include <machine/trap.h>
86 # define NEED_FIND_LIMIT
90 #if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__) \
91 && !defined(NEED_FIND_LIMIT)
92 /* Used by GC_init_netbsd_elf() below. */
93 # define NEED_FIND_LIMIT
96 #ifdef NEED_FIND_LIMIT
101 # define GC_AMIGA_DEF
102 # include "AmigaOS.c"
106 #if defined(MSWIN32) || defined(MSWINCE)
107 # define WIN32_LEAN_AND_MEAN
109 # include <windows.h>
113 # include <Processes.h>
117 # include <sys/uio.h>
118 # include <malloc.h> /* for locking */
120 #if defined(USE_MMAP) || defined(USE_MUNMAP)
122 --> USE_MUNMAP requires USE_MMAP
124 # include <sys/types.h>
125 # include <sys/mman.h>
126 # include <sys/stat.h>
132 # if defined(SUNOS5SIGS) && !defined(FREEBSD)
133 # include <sys/siginfo.h>
135 /* Define SETJMP and friends to be the version that restores */
136 /* the signal mask. */
137 # define SETJMP(env) sigsetjmp(env, 1)
138 # define LONGJMP(env, val) siglongjmp(env, val)
139 # define JMP_BUF sigjmp_buf
141 # define SETJMP(env) setjmp(env)
142 # define LONGJMP(env, val) longjmp(env, val)
143 # define JMP_BUF jmp_buf
147 /* for get_etext and friends */
148 #include <mach-o/getsect.h>
152 /* Apparently necessary for djgpp 2.01. May cause problems with */
153 /* other versions. */
154 typedef long unsigned int caddr_t
;
158 # include "il/PCR_IL.h"
159 # include "th/PCR_ThCtl.h"
160 # include "mm/PCR_MM.h"
163 #if !defined(NO_EXECUTE_PERMISSION)
164 # define OPT_PROT_EXEC PROT_EXEC
166 # define OPT_PROT_EXEC 0
169 #if defined(LINUX) && \
170 (defined(USE_PROC_FOR_LIBRARIES) || defined(IA64) || !defined(SMALL_CONFIG))
172 /* We need to parse /proc/self/maps, either to find dynamic libraries, */
173 /* and/or to find the register backing store base (IA64). Do it once */
178 /* Repeatedly perform a read call until the buffer is filled or */
179 /* we encounter EOF. */
180 ssize_t
GC_repeat_read(int fd
, char *buf
, size_t count
)
182 ssize_t num_read
= 0;
185 while (num_read
< count
) {
186 result
= READ(fd
, buf
+ num_read
, count
- num_read
);
187 if (result
< 0) return result
;
188 if (result
== 0) break;
195 * Apply fn to a buffer containing the contents of /proc/self/maps.
196 * Return the result of fn or, if we failed, 0.
197 * We currently do nothing to /proc/self/maps other than simply read
198 * it. This code could be simplified if we could determine its size
202 word
GC_apply_to_maps(word (*fn
)(char *))
206 size_t maps_size
= 4000; /* Initial guess. */
207 static char init_buf
[1];
208 static char *maps_buf
= init_buf
;
209 static size_t maps_buf_sz
= 1;
211 /* Read /proc/self/maps, growing maps_buf as necessary. */
212 /* Note that we may not allocate conventionally, and */
213 /* thus can't use stdio. */
215 if (maps_size
>= maps_buf_sz
) {
216 /* Grow only by powers of 2, since we leak "too small" buffers. */
217 while (maps_size
>= maps_buf_sz
) maps_buf_sz
*= 2;
218 maps_buf
= GC_scratch_alloc(maps_buf_sz
);
219 if (maps_buf
== 0) return 0;
221 f
= open("/proc/self/maps", O_RDONLY
);
222 if (-1 == f
) return 0;
225 result
= GC_repeat_read(f
, maps_buf
, maps_buf_sz
-1);
226 if (result
<= 0) return 0;
228 } while (result
== maps_buf_sz
-1);
230 } while (maps_size
>= maps_buf_sz
);
231 maps_buf
[maps_size
] = '\0';
233 /* Apply fn to result. */
237 #endif /* Need GC_apply_to_maps */
239 #if defined(LINUX) && (defined(USE_PROC_FOR_LIBRARIES) || defined(IA64))
241 // GC_parse_map_entry parses an entry from /proc/self/maps so we can
242 // locate all writable data segments that belong to shared libraries.
243 // The format of one of these entries and the fields we care about
245 // XXXXXXXX-XXXXXXXX r-xp 00000000 30:05 260537 name of mapping...\n
246 // ^^^^^^^^ ^^^^^^^^ ^^^^ ^^
247 // start end prot maj_dev
253 // The parser is called with a pointer to the entry and the return value
254 // is either NULL or is advanced to the next entry(the byte after the
258 # define OFFSET_MAP_START 0
259 # define OFFSET_MAP_END 9
260 # define OFFSET_MAP_PROT 18
261 # define OFFSET_MAP_MAJDEV 32
262 # define ADDR_WIDTH 8
266 # define OFFSET_MAP_START 0
267 # define OFFSET_MAP_END 17
268 # define OFFSET_MAP_PROT 34
269 # define OFFSET_MAP_MAJDEV 56
270 # define ADDR_WIDTH 16
274 * Assign various fields of the first line in buf_ptr to *start, *end,
275 * *prot_buf and *maj_dev. Only *prot_buf may be set for unwritable maps.
277 char *GC_parse_map_entry(char *buf_ptr
, word
*start
, word
*end
,
278 char *prot_buf
, unsigned int *maj_dev
)
283 if (buf_ptr
== NULL
|| *buf_ptr
== '\0') {
287 memcpy(prot_buf
, buf_ptr
+OFFSET_MAP_PROT
, 4);
288 /* do the protections first. */
291 if (prot_buf
[1] == 'w') {/* we can skip all of this if it's not writable. */
294 buf_ptr
[OFFSET_MAP_START
+ADDR_WIDTH
] = '\0';
295 *start
= strtoul(tok
, NULL
, 16);
297 tok
= buf_ptr
+OFFSET_MAP_END
;
298 buf_ptr
[OFFSET_MAP_END
+ADDR_WIDTH
] = '\0';
299 *end
= strtoul(tok
, NULL
, 16);
301 buf_ptr
+= OFFSET_MAP_MAJDEV
;
303 while (*buf_ptr
!= ':') buf_ptr
++;
305 *maj_dev
= strtoul(tok
, NULL
, 16);
308 while (*buf_ptr
&& *buf_ptr
++ != '\n');
313 #endif /* Need to parse /proc/self/maps. */
315 #if defined(SEARCH_FOR_DATA_START)
316 /* The I386 case can be handled without a search. The Alpha case */
317 /* used to be handled differently as well, but the rules changed */
318 /* for recent Linux versions. This seems to be the easiest way to */
319 /* cover all versions. */
322 /* Some Linux distributions arrange to define __data_start. Some */
323 /* define data_start as a weak symbol. The latter is technically */
324 /* broken, since the user program may define data_start, in which */
325 /* case we lose. Nonetheless, we try both, prefering __data_start. */
326 /* We assume gcc-compatible pragmas. */
327 # pragma weak __data_start
328 extern int __data_start
[];
329 # pragma weak data_start
330 extern int data_start
[];
336 void GC_init_linux_data_start()
338 extern ptr_t
GC_find_limit();
341 /* Try the easy approaches first: */
342 if ((ptr_t
)__data_start
!= 0) {
343 GC_data_start
= (ptr_t
)(__data_start
);
346 if ((ptr_t
)data_start
!= 0) {
347 GC_data_start
= (ptr_t
)(data_start
);
351 GC_data_start
= GC_find_limit((ptr_t
)(_end
), FALSE
);
357 # ifndef ECOS_GC_MEMORY_SIZE
358 # define ECOS_GC_MEMORY_SIZE (448 * 1024)
359 # endif /* ECOS_GC_MEMORY_SIZE */
361 // setjmp() function, as described in ANSI para 7.6.1.1
363 #define SETJMP( __env__ ) hal_setjmp( __env__ )
365 // FIXME: This is a simple way of allocating memory which is
366 // compatible with ECOS early releases. Later releases use a more
367 // sophisticated means of allocating memory than this simple static
368 // allocator, but this method is at least bound to work.
369 static char memory
[ECOS_GC_MEMORY_SIZE
];
370 static char *brk
= memory
;
372 static void *tiny_sbrk(ptrdiff_t increment
)
378 if (brk
> memory
+ sizeof memory
)
386 #define sbrk tiny_sbrk
389 #if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__)
392 void GC_init_netbsd_elf()
394 extern ptr_t
GC_find_limit();
395 extern char **environ
;
396 /* This may need to be environ, without the underscore, for */
398 GC_data_start
= GC_find_limit((ptr_t
)&environ
, FALSE
);
406 # if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */
409 unsigned short magic_number
;
410 unsigned short padding
[29];
414 #define E_MAGIC(x) (x).magic_number
415 #define EMAGIC 0x5A4D
416 #define E_LFANEW(x) (x).new_exe_offset
419 unsigned char magic_number
[2];
420 unsigned char byte_order
;
421 unsigned char word_order
;
422 unsigned long exe_format_level
;
425 unsigned long padding1
[13];
426 unsigned long object_table_offset
;
427 unsigned long object_count
;
428 unsigned long padding2
[31];
431 #define E32_MAGIC1(x) (x).magic_number[0]
432 #define E32MAGIC1 'L'
433 #define E32_MAGIC2(x) (x).magic_number[1]
434 #define E32MAGIC2 'X'
435 #define E32_BORDER(x) (x).byte_order
437 #define E32_WORDER(x) (x).word_order
439 #define E32_CPU(x) (x).cpu
441 #define E32_OBJTAB(x) (x).object_table_offset
442 #define E32_OBJCNT(x) (x).object_count
448 unsigned long pagemap
;
449 unsigned long mapsize
;
450 unsigned long reserved
;
453 #define O32_FLAGS(x) (x).flags
454 #define OBJREAD 0x0001L
455 #define OBJWRITE 0x0002L
456 #define OBJINVALID 0x0080L
457 #define O32_SIZE(x) (x).size
458 #define O32_BASE(x) (x).base
460 # else /* IBM's compiler */
462 /* A kludge to get around what appears to be a header file bug */
464 # define WORD unsigned short
467 # define DWORD unsigned long
474 # endif /* __IBMC__ */
476 # define INCL_DOSEXCEPTIONS
477 # define INCL_DOSPROCESS
478 # define INCL_DOSERRORS
479 # define INCL_DOSMODULEMGR
480 # define INCL_DOSMEMMGR
484 /* Disable and enable signals during nontrivial allocations */
486 void GC_disable_signals(void)
490 DosEnterMustComplete(&nest
);
491 if (nest
!= 1) ABORT("nested GC_disable_signals");
494 void GC_enable_signals(void)
498 DosExitMustComplete(&nest
);
499 if (nest
!= 0) ABORT("GC_enable_signals");
505 # if !defined(PCR) && !defined(AMIGA) && !defined(MSWIN32) \
506 && !defined(MSWINCE) \
507 && !defined(MACOS) && !defined(DJGPP) && !defined(DOS4GW) \
508 && !defined(NOSYS) && !defined(ECOS)
510 # if defined(sigmask) && !defined(UTS4) && !defined(HURD)
511 /* Use the traditional BSD interface */
512 # define SIGSET_T int
513 # define SIG_DEL(set, signal) (set) &= ~(sigmask(signal))
514 # define SIG_FILL(set) (set) = 0x7fffffff
515 /* Setting the leading bit appears to provoke a bug in some */
516 /* longjmp implementations. Most systems appear not to have */
518 # define SIGSETMASK(old, new) (old) = sigsetmask(new)
520 /* Use POSIX/SYSV interface */
521 # define SIGSET_T sigset_t
522 # define SIG_DEL(set, signal) sigdelset(&(set), (signal))
523 # define SIG_FILL(set) sigfillset(&set)
524 # define SIGSETMASK(old, new) sigprocmask(SIG_SETMASK, &(new), &(old))
527 static GC_bool mask_initialized
= FALSE
;
529 static SIGSET_T new_mask
;
531 static SIGSET_T old_mask
;
533 static SIGSET_T dummy
;
535 #if defined(PRINTSTATS) && !defined(THREADS)
536 # define CHECK_SIGNALS
537 int GC_sig_disabled
= 0;
540 void GC_disable_signals()
542 if (!mask_initialized
) {
545 SIG_DEL(new_mask
, SIGSEGV
);
546 SIG_DEL(new_mask
, SIGILL
);
547 SIG_DEL(new_mask
, SIGQUIT
);
549 SIG_DEL(new_mask
, SIGBUS
);
552 SIG_DEL(new_mask
, SIGIOT
);
555 SIG_DEL(new_mask
, SIGEMT
);
558 SIG_DEL(new_mask
, SIGTRAP
);
560 mask_initialized
= TRUE
;
562 # ifdef CHECK_SIGNALS
563 if (GC_sig_disabled
!= 0) ABORT("Nested disables");
566 SIGSETMASK(old_mask
,new_mask
);
569 void GC_enable_signals()
571 # ifdef CHECK_SIGNALS
572 if (GC_sig_disabled
!= 1) ABORT("Unmatched enable");
575 SIGSETMASK(dummy
,old_mask
);
582 /* Ivan Demakov: simplest way (to me) */
584 void GC_disable_signals() { }
585 void GC_enable_signals() { }
588 /* Find the page size */
591 # if defined(MSWIN32) || defined(MSWINCE)
592 void GC_setpagesize()
594 GetSystemInfo(&GC_sysinfo
);
595 GC_page_size
= GC_sysinfo
.dwPageSize
;
599 # if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP) \
600 || defined(USE_MUNMAP)
601 void GC_setpagesize()
603 GC_page_size
= GETPAGESIZE();
606 /* It's acceptable to fake it. */
607 void GC_setpagesize()
609 GC_page_size
= HBLKSIZE
;
615 * Find the base of the stack.
616 * Used only in single-threaded environment.
617 * With threads, GC_mark_roots needs to know how to do this.
618 * Called with allocator lock held.
620 # if defined(MSWIN32) || defined(MSWINCE)
621 # define is_writable(prot) ((prot) == PAGE_READWRITE \
622 || (prot) == PAGE_WRITECOPY \
623 || (prot) == PAGE_EXECUTE_READWRITE \
624 || (prot) == PAGE_EXECUTE_WRITECOPY)
625 /* Return the number of bytes that are writable starting at p. */
626 /* The pointer p is assumed to be page aligned. */
627 /* If base is not 0, *base becomes the beginning of the */
628 /* allocation region containing p. */
629 word
GC_get_writable_length(ptr_t p
, ptr_t
*base
)
631 MEMORY_BASIC_INFORMATION buf
;
635 result
= VirtualQuery(p
, &buf
, sizeof(buf
));
636 if (result
!= sizeof(buf
)) ABORT("Weird VirtualQuery result");
637 if (base
!= 0) *base
= (ptr_t
)(buf
.AllocationBase
);
638 protect
= (buf
.Protect
& ~(PAGE_GUARD
| PAGE_NOCACHE
));
639 if (!is_writable(protect
)) {
642 if (buf
.State
!= MEM_COMMIT
) return(0);
643 return(buf
.RegionSize
);
646 ptr_t
GC_get_stack_base()
649 ptr_t sp
= (ptr_t
)(&dummy
);
650 ptr_t trunc_sp
= (ptr_t
)((word
)sp
& ~(GC_page_size
- 1));
651 word size
= GC_get_writable_length(trunc_sp
, 0);
653 return(trunc_sp
+ size
);
657 # endif /* MS Windows */
660 # include <kernel/OS.h>
661 ptr_t
GC_get_stack_base(){
663 get_thread_info(find_thread(NULL
),&th
);
671 ptr_t
GC_get_stack_base()
676 if (DosGetInfoBlocks(&ptib
, &ppib
) != NO_ERROR
) {
677 GC_err_printf0("DosGetInfoBlocks failed\n");
678 ABORT("DosGetInfoBlocks failed\n");
680 return((ptr_t
)(ptib
-> tib_pstacklimit
));
687 # include "AmigaOS.c"
691 # if defined(NEED_FIND_LIMIT) || defined(UNIX_LIKE)
694 typedef void (*handler
)(int);
696 typedef void (*handler
)();
699 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1) \
700 || defined(HURD) || defined(NETBSD)
701 static struct sigaction old_segv_act
;
702 # if defined(_sigargs) /* !Irix6.x */ || defined(HPUX) \
703 || defined(HURD) || defined(NETBSD)
704 static struct sigaction old_bus_act
;
707 static handler old_segv_handler
, old_bus_handler
;
711 void GC_set_and_save_fault_handler(handler h
)
713 void GC_set_and_save_fault_handler(h
)
717 # if defined(SUNOS5SIGS) || defined(IRIX5) \
718 || defined(OSF1) || defined(HURD) || defined(NETBSD)
719 struct sigaction act
;
722 # if 0 /* Was necessary for Solaris 2.3 and very temporary */
724 act
.sa_flags
= SA_RESTART
| SA_NODEFER
;
726 act
.sa_flags
= SA_RESTART
;
729 (void) sigemptyset(&act
.sa_mask
);
730 # ifdef GC_IRIX_THREADS
731 /* Older versions have a bug related to retrieving and */
732 /* and setting a handler at the same time. */
733 (void) sigaction(SIGSEGV
, 0, &old_segv_act
);
734 (void) sigaction(SIGSEGV
, &act
, 0);
736 (void) sigaction(SIGSEGV
, &act
, &old_segv_act
);
737 # if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \
738 || defined(HPUX) || defined(HURD) || defined(NETBSD)
739 /* Under Irix 5.x or HP/UX, we may get SIGBUS. */
740 /* Pthreads doesn't exist under Irix 5.x, so we */
741 /* don't have to worry in the threads case. */
742 (void) sigaction(SIGBUS
, &act
, &old_bus_act
);
744 # endif /* GC_IRIX_THREADS */
746 old_segv_handler
= signal(SIGSEGV
, h
);
748 old_bus_handler
= signal(SIGBUS
, h
);
752 # endif /* NEED_FIND_LIMIT || UNIX_LIKE */
754 # ifdef NEED_FIND_LIMIT
755 /* Some tools to implement HEURISTIC2 */
756 # define MIN_PAGE_SIZE 256 /* Smallest conceivable page size, bytes */
757 /* static */ JMP_BUF GC_jmp_buf
;
760 void GC_fault_handler(sig
)
763 LONGJMP(GC_jmp_buf
, 1);
766 void GC_setup_temporary_fault_handler()
768 GC_set_and_save_fault_handler(GC_fault_handler
);
771 void GC_reset_fault_handler()
773 # if defined(SUNOS5SIGS) || defined(IRIX5) \
774 || defined(OSF1) || defined(HURD) || defined(NETBSD)
775 (void) sigaction(SIGSEGV
, &old_segv_act
, 0);
776 # if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \
777 || defined(HPUX) || defined(HURD) || defined(NETBSD)
778 (void) sigaction(SIGBUS
, &old_bus_act
, 0);
781 (void) signal(SIGSEGV
, old_segv_handler
);
783 (void) signal(SIGBUS
, old_bus_handler
);
788 /* Return the first nonaddressible location > p (up) or */
789 /* the smallest location q s.t. [q,p) is addressable (!up). */
790 /* We assume that p (up) or p-1 (!up) is addressable. */
791 ptr_t
GC_find_limit(p
, up
)
795 static VOLATILE ptr_t result
;
796 /* Needs to be static, since otherwise it may not be */
797 /* preserved across the longjmp. Can safely be */
798 /* static since it's only called once, with the */
799 /* allocation lock held. */
802 GC_setup_temporary_fault_handler();
803 if (SETJMP(GC_jmp_buf
) == 0) {
804 result
= (ptr_t
)(((word
)(p
))
805 & ~(MIN_PAGE_SIZE
-1));
808 result
+= MIN_PAGE_SIZE
;
810 result
-= MIN_PAGE_SIZE
;
812 GC_noop1((word
)(*result
));
815 GC_reset_fault_handler();
817 result
+= MIN_PAGE_SIZE
;
823 #if defined(ECOS) || defined(NOSYS)
824 ptr_t
GC_get_stack_base()
830 #ifdef HPUX_STACKBOTTOM
832 #include <sys/param.h>
833 #include <sys/pstat.h>
835 ptr_t
GC_get_register_stack_base(void)
837 struct pst_vm_status vm_status
;
840 while (pstat_getprocvm(&vm_status
, sizeof(vm_status
), 0, i
++) == 1) {
841 if (vm_status
.pst_type
== PS_RSESTACK
) {
842 return (ptr_t
) vm_status
.pst_vaddr
;
846 /* old way to get the register stackbottom */
847 return (ptr_t
)(((word
)GC_stackbottom
- BACKING_STORE_DISPLACEMENT
- 1)
848 & ~(BACKING_STORE_ALIGNMENT
- 1));
851 #endif /* HPUX_STACK_BOTTOM */
853 #ifdef LINUX_STACKBOTTOM
855 #include <sys/types.h>
856 #include <sys/stat.h>
859 # define STAT_SKIP 27 /* Number of fields preceding startstack */
860 /* field in /proc/self/stat */
862 # pragma weak __libc_stack_end
863 extern ptr_t __libc_stack_end
;
866 /* Try to read the backing store base from /proc/self/maps. */
867 /* We look for the writable mapping with a 0 major device, */
868 /* which is as close to our frame as possible, but below it.*/
869 static word
backing_store_base_from_maps(char *maps
)
872 char *buf_ptr
= maps
;
874 unsigned int maj_dev
;
875 word current_best
= 0;
879 buf_ptr
= GC_parse_map_entry(buf_ptr
, &start
, &end
, prot_buf
, &maj_dev
);
880 if (buf_ptr
== NULL
) return current_best
;
881 if (prot_buf
[1] == 'w' && maj_dev
== 0) {
882 if (end
< (word
)(&dummy
) && start
> current_best
) current_best
= start
;
888 static word
backing_store_base_from_proc(void)
890 return GC_apply_to_maps(backing_store_base_from_maps
);
893 # pragma weak __libc_ia64_register_backing_store_base
894 extern ptr_t __libc_ia64_register_backing_store_base
;
896 ptr_t
GC_get_register_stack_base(void)
898 if (0 != &__libc_ia64_register_backing_store_base
899 && 0 != __libc_ia64_register_backing_store_base
) {
900 /* Glibc 2.2.4 has a bug such that for dynamically linked */
901 /* executables __libc_ia64_register_backing_store_base is */
902 /* defined but uninitialized during constructor calls. */
903 /* Hence we check for both nonzero address and value. */
904 return __libc_ia64_register_backing_store_base
;
906 word result
= backing_store_base_from_proc();
908 /* Use dumb heuristics. Works only for default configuration. */
909 result
= (word
)GC_stackbottom
- BACKING_STORE_DISPLACEMENT
;
910 result
+= BACKING_STORE_ALIGNMENT
- 1;
911 result
&= ~(BACKING_STORE_ALIGNMENT
- 1);
912 /* Verify that it's at least readable. If not, we goofed. */
913 GC_noop1(*(word
*)result
);
915 return (ptr_t
)result
;
920 ptr_t
GC_linux_stack_base(void)
922 /* We read the stack base value from /proc/self/stat. We do this */
923 /* using direct I/O system calls in order to avoid calling malloc */
924 /* in case REDIRECT_MALLOC is defined. */
925 # define STAT_BUF_SIZE 4096
926 # define STAT_READ read
927 /* Should probably call the real read, if read is wrapped. */
928 char stat_buf
[STAT_BUF_SIZE
];
932 size_t i
, buf_offset
= 0;
934 /* First try the easy way. This should work for glibc 2.2 */
935 /* This fails in a prelinked ("prelink" command) executable */
936 /* since the correct value of __libc_stack_end never */
937 /* becomes visible to us. The second test works around */
939 if (0 != &__libc_stack_end
&& 0 != __libc_stack_end
) {
941 /* Some versions of glibc set the address 16 bytes too */
942 /* low while the initialization code is running. */
943 if (((word
)__libc_stack_end
& 0xfff) + 0x10 < 0x1000) {
944 return __libc_stack_end
+ 0x10;
945 } /* Otherwise it's not safe to add 16 bytes and we fall */
946 /* back to using /proc. */
949 /* Older versions of glibc for 64-bit Sparc do not set
950 * this variable correctly, it gets set to either zero
953 if (__libc_stack_end
!= (ptr_t
) (unsigned long)0x1)
954 return __libc_stack_end
;
956 return __libc_stack_end
;
960 f
= open("/proc/self/stat", O_RDONLY
);
961 if (f
< 0 || STAT_READ(f
, stat_buf
, STAT_BUF_SIZE
) < 2 * STAT_SKIP
) {
962 ABORT("Couldn't read /proc/self/stat");
964 c
= stat_buf
[buf_offset
++];
965 /* Skip the required number of fields. This number is hopefully */
966 /* constant across all Linux implementations. */
967 for (i
= 0; i
< STAT_SKIP
; ++i
) {
968 while (isspace(c
)) c
= stat_buf
[buf_offset
++];
969 while (!isspace(c
)) c
= stat_buf
[buf_offset
++];
971 while (isspace(c
)) c
= stat_buf
[buf_offset
++];
975 c
= stat_buf
[buf_offset
++];
978 if (result
< 0x10000000) ABORT("Absurd stack bottom value");
979 return (ptr_t
)result
;
982 #endif /* LINUX_STACKBOTTOM */
984 #ifdef FREEBSD_STACKBOTTOM
986 /* This uses an undocumented sysctl call, but at least one expert */
987 /* believes it will stay. */
990 #include <sys/types.h>
991 #include <sys/sysctl.h>
993 ptr_t
GC_freebsd_stack_base(void)
995 int nm
[2] = {CTL_KERN
, KERN_USRSTACK
};
997 size_t len
= sizeof(ptr_t
);
998 int r
= sysctl(nm
, 2, &base
, &len
, NULL
, 0);
1000 if (r
) ABORT("Error getting stack base");
1005 #endif /* FREEBSD_STACKBOTTOM */
1007 #if !defined(BEOS) && !defined(AMIGA) && !defined(MSWIN32) \
1008 && !defined(MSWINCE) && !defined(OS2) && !defined(NOSYS) && !defined(ECOS)
1010 ptr_t
GC_get_stack_base()
1012 # if defined(HEURISTIC1) || defined(HEURISTIC2) || \
1013 defined(LINUX_STACKBOTTOM) || defined(FREEBSD_STACKBOTTOM)
1018 # define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
1021 return(STACKBOTTOM
);
1024 # ifdef STACK_GROWS_DOWN
1025 result
= (ptr_t
)((((word
)(&dummy
))
1026 + STACKBOTTOM_ALIGNMENT_M1
)
1027 & ~STACKBOTTOM_ALIGNMENT_M1
);
1029 result
= (ptr_t
)(((word
)(&dummy
))
1030 & ~STACKBOTTOM_ALIGNMENT_M1
);
1032 # endif /* HEURISTIC1 */
1033 # ifdef LINUX_STACKBOTTOM
1034 result
= GC_linux_stack_base();
1036 # ifdef FREEBSD_STACKBOTTOM
1037 result
= GC_freebsd_stack_base();
1040 # ifdef STACK_GROWS_DOWN
1041 result
= GC_find_limit((ptr_t
)(&dummy
), TRUE
);
1042 # ifdef HEURISTIC2_LIMIT
1043 if (result
> HEURISTIC2_LIMIT
1044 && (ptr_t
)(&dummy
) < HEURISTIC2_LIMIT
) {
1045 result
= HEURISTIC2_LIMIT
;
1049 result
= GC_find_limit((ptr_t
)(&dummy
), FALSE
);
1050 # ifdef HEURISTIC2_LIMIT
1051 if (result
< HEURISTIC2_LIMIT
1052 && (ptr_t
)(&dummy
) > HEURISTIC2_LIMIT
) {
1053 result
= HEURISTIC2_LIMIT
;
1058 # endif /* HEURISTIC2 */
1059 # ifdef STACK_GROWS_DOWN
1060 if (result
== 0) result
= (ptr_t
)(signed_word
)(-sizeof(ptr_t
));
1063 # endif /* STACKBOTTOM */
1066 # endif /* ! AMIGA, !OS 2, ! MS Windows, !BEOS, !NOSYS, !ECOS */
1069 * Register static data segment(s) as roots.
1070 * If more data segments are added later then they need to be registered
1071 * add that point (as we do with SunOS dynamic loading),
1072 * or GC_mark_roots needs to check for them (as we do with PCR).
1073 * Called with allocator lock held.
1078 void GC_register_data_segments()
1082 HMODULE module_handle
;
1083 # define PBUFSIZ 512
1084 UCHAR path
[PBUFSIZ
];
1086 struct exe_hdr hdrdos
; /* MSDOS header. */
1087 struct e32_exe hdr386
; /* Real header for my executable */
1088 struct o32_obj seg
; /* Currrent segment */
1092 if (DosGetInfoBlocks(&ptib
, &ppib
) != NO_ERROR
) {
1093 GC_err_printf0("DosGetInfoBlocks failed\n");
1094 ABORT("DosGetInfoBlocks failed\n");
1096 module_handle
= ppib
-> pib_hmte
;
1097 if (DosQueryModuleName(module_handle
, PBUFSIZ
, path
) != NO_ERROR
) {
1098 GC_err_printf0("DosQueryModuleName failed\n");
1099 ABORT("DosGetInfoBlocks failed\n");
1101 myexefile
= fopen(path
, "rb");
1102 if (myexefile
== 0) {
1103 GC_err_puts("Couldn't open executable ");
1104 GC_err_puts(path
); GC_err_puts("\n");
1105 ABORT("Failed to open executable\n");
1107 if (fread((char *)(&hdrdos
), 1, sizeof hdrdos
, myexefile
) < sizeof hdrdos
) {
1108 GC_err_puts("Couldn't read MSDOS header from ");
1109 GC_err_puts(path
); GC_err_puts("\n");
1110 ABORT("Couldn't read MSDOS header");
1112 if (E_MAGIC(hdrdos
) != EMAGIC
) {
1113 GC_err_puts("Executable has wrong DOS magic number: ");
1114 GC_err_puts(path
); GC_err_puts("\n");
1115 ABORT("Bad DOS magic number");
1117 if (fseek(myexefile
, E_LFANEW(hdrdos
), SEEK_SET
) != 0) {
1118 GC_err_puts("Seek to new header failed in ");
1119 GC_err_puts(path
); GC_err_puts("\n");
1120 ABORT("Bad DOS magic number");
1122 if (fread((char *)(&hdr386
), 1, sizeof hdr386
, myexefile
) < sizeof hdr386
) {
1123 GC_err_puts("Couldn't read MSDOS header from ");
1124 GC_err_puts(path
); GC_err_puts("\n");
1125 ABORT("Couldn't read OS/2 header");
1127 if (E32_MAGIC1(hdr386
) != E32MAGIC1
|| E32_MAGIC2(hdr386
) != E32MAGIC2
) {
1128 GC_err_puts("Executable has wrong OS/2 magic number:");
1129 GC_err_puts(path
); GC_err_puts("\n");
1130 ABORT("Bad OS/2 magic number");
1132 if ( E32_BORDER(hdr386
) != E32LEBO
|| E32_WORDER(hdr386
) != E32LEWO
) {
1133 GC_err_puts("Executable %s has wrong byte order: ");
1134 GC_err_puts(path
); GC_err_puts("\n");
1135 ABORT("Bad byte order");
1137 if ( E32_CPU(hdr386
) == E32CPU286
) {
1138 GC_err_puts("GC can't handle 80286 executables: ");
1139 GC_err_puts(path
); GC_err_puts("\n");
1142 if (fseek(myexefile
, E_LFANEW(hdrdos
) + E32_OBJTAB(hdr386
),
1144 GC_err_puts("Seek to object table failed: ");
1145 GC_err_puts(path
); GC_err_puts("\n");
1146 ABORT("Seek to object table failed");
1148 for (nsegs
= E32_OBJCNT(hdr386
); nsegs
> 0; nsegs
--) {
1150 if (fread((char *)(&seg
), 1, sizeof seg
, myexefile
) < sizeof seg
) {
1151 GC_err_puts("Couldn't read obj table entry from ");
1152 GC_err_puts(path
); GC_err_puts("\n");
1153 ABORT("Couldn't read obj table entry");
1155 flags
= O32_FLAGS(seg
);
1156 if (!(flags
& OBJWRITE
)) continue;
1157 if (!(flags
& OBJREAD
)) continue;
1158 if (flags
& OBJINVALID
) {
1159 GC_err_printf0("Object with invalid pages?\n");
1162 GC_add_roots_inner(O32_BASE(seg
), O32_BASE(seg
)+O32_SIZE(seg
), FALSE
);
1168 # if defined(MSWIN32) || defined(MSWINCE)
1171 /* Unfortunately, we have to handle win32s very differently from NT, */
1172 /* Since VirtualQuery has very different semantics. In particular, */
1173 /* under win32s a VirtualQuery call on an unmapped page returns an */
1174 /* invalid result. Under NT, GC_register_data_segments is a noop and */
1175 /* all real work is done by GC_register_dynamic_libraries. Under */
1176 /* win32s, we cannot find the data segments associated with dll's. */
1177 /* We register the main data segment here. */
1178 GC_bool GC_no_win32_dlls
= FALSE
;
1179 /* This used to be set for gcc, to avoid dealing with */
1180 /* the structured exception handling issues. But we now have */
1181 /* assembly code to do that right. */
1183 void GC_init_win32()
1185 /* if we're running under win32s, assume that no DLLs will be loaded */
1186 DWORD v
= GetVersion();
1187 GC_no_win32_dlls
|= ((v
& 0x80000000) && (v
& 0xff) <= 3);
1190 /* Return the smallest address a such that VirtualQuery */
1191 /* returns correct results for all addresses between a and start. */
1192 /* Assumes VirtualQuery returns correct information for start. */
1193 ptr_t
GC_least_described_address(ptr_t start
)
1195 MEMORY_BASIC_INFORMATION buf
;
1201 limit
= GC_sysinfo
.lpMinimumApplicationAddress
;
1202 p
= (ptr_t
)((word
)start
& ~(GC_page_size
- 1));
1204 q
= (LPVOID
)(p
- GC_page_size
);
1205 if ((ptr_t
)q
> (ptr_t
)p
/* underflow */ || q
< limit
) break;
1206 result
= VirtualQuery(q
, &buf
, sizeof(buf
));
1207 if (result
!= sizeof(buf
) || buf
.AllocationBase
== 0) break;
1208 p
= (ptr_t
)(buf
.AllocationBase
);
1214 # ifndef REDIRECT_MALLOC
1215 /* We maintain a linked list of AllocationBase values that we know */
1216 /* correspond to malloc heap sections. Currently this is only called */
1217 /* during a GC. But there is some hope that for long running */
1218 /* programs we will eventually see most heap sections. */
1220 /* In the long run, it would be more reliable to occasionally walk */
1221 /* the malloc heap with HeapWalk on the default heap. But that */
1222 /* apparently works only for NT-based Windows. */
1224 /* In the long run, a better data structure would also be nice ... */
1225 struct GC_malloc_heap_list
{
1226 void * allocation_base
;
1227 struct GC_malloc_heap_list
*next
;
1228 } *GC_malloc_heap_l
= 0;
1230 /* Is p the base of one of the malloc heap sections we already know */
1232 GC_bool
GC_is_malloc_heap_base(ptr_t p
)
1234 struct GC_malloc_heap_list
*q
= GC_malloc_heap_l
;
1237 if (q
-> allocation_base
== p
) return TRUE
;
1243 void *GC_get_allocation_base(void *p
)
1245 MEMORY_BASIC_INFORMATION buf
;
1246 DWORD result
= VirtualQuery(p
, &buf
, sizeof(buf
));
1247 if (result
!= sizeof(buf
)) {
1248 ABORT("Weird VirtualQuery result");
1250 return buf
.AllocationBase
;
1253 size_t GC_max_root_size
= 100000; /* Appr. largest root size. */
1255 void GC_add_current_malloc_heap()
1257 struct GC_malloc_heap_list
*new_l
=
1258 malloc(sizeof(struct GC_malloc_heap_list
));
1259 void * candidate
= GC_get_allocation_base(new_l
);
1261 if (new_l
== 0) return;
1262 if (GC_is_malloc_heap_base(candidate
)) {
1263 /* Try a little harder to find malloc heap. */
1264 size_t req_size
= 10000;
1266 void *p
= malloc(req_size
);
1267 if (0 == p
) { free(new_l
); return; }
1268 candidate
= GC_get_allocation_base(p
);
1271 } while (GC_is_malloc_heap_base(candidate
)
1272 && req_size
< GC_max_root_size
/10 && req_size
< 500000);
1273 if (GC_is_malloc_heap_base(candidate
)) {
1274 free(new_l
); return;
1279 GC_printf1("Found new system malloc AllocationBase at 0x%lx\n",
1282 new_l
-> allocation_base
= candidate
;
1283 new_l
-> next
= GC_malloc_heap_l
;
1284 GC_malloc_heap_l
= new_l
;
1286 # endif /* REDIRECT_MALLOC */
1288 /* Is p the start of either the malloc heap, or of one of our */
1289 /* heap sections? */
1290 GC_bool
GC_is_heap_base (ptr_t p
)
1295 # ifndef REDIRECT_MALLOC
1296 static word last_gc_no
= -1;
1298 if (last_gc_no
!= GC_gc_no
) {
1299 GC_add_current_malloc_heap();
1300 last_gc_no
= GC_gc_no
;
1302 if (GC_root_size
> GC_max_root_size
) GC_max_root_size
= GC_root_size
;
1303 if (GC_is_malloc_heap_base(p
)) return TRUE
;
1305 for (i
= 0; i
< GC_n_heap_bases
; i
++) {
1306 if (GC_heap_bases
[i
] == p
) return TRUE
;
1312 void GC_register_root_section(ptr_t static_root
)
1314 MEMORY_BASIC_INFORMATION buf
;
1319 char * limit
, * new_limit
;
1321 if (!GC_no_win32_dlls
) return;
1322 p
= base
= limit
= GC_least_described_address(static_root
);
1323 while (p
< GC_sysinfo
.lpMaximumApplicationAddress
) {
1324 result
= VirtualQuery(p
, &buf
, sizeof(buf
));
1325 if (result
!= sizeof(buf
) || buf
.AllocationBase
== 0
1326 || GC_is_heap_base(buf
.AllocationBase
)) break;
1327 new_limit
= (char *)p
+ buf
.RegionSize
;
1328 protect
= buf
.Protect
;
1329 if (buf
.State
== MEM_COMMIT
1330 && is_writable(protect
)) {
1331 if ((char *)p
== limit
) {
1334 if (base
!= limit
) GC_add_roots_inner(base
, limit
, FALSE
);
1339 if (p
> (LPVOID
)new_limit
/* overflow */) break;
1340 p
= (LPVOID
)new_limit
;
1342 if (base
!= limit
) GC_add_roots_inner(base
, limit
, FALSE
);
1346 void GC_register_data_segments()
1350 GC_register_root_section((ptr_t
)(&dummy
));
1354 # else /* !OS2 && !Windows */
1356 # if (defined(SVR4) || defined(AUX) || defined(DGUX) \
1357 || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
1358 ptr_t
GC_SysVGetDataStart(max_page_size
, etext_addr
)
1362 word text_end
= ((word
)(etext_addr
) + sizeof(word
) - 1)
1363 & ~(sizeof(word
) - 1);
1364 /* etext rounded to word boundary */
1365 word next_page
= ((text_end
+ (word
)max_page_size
- 1)
1366 & ~((word
)max_page_size
- 1));
1367 word page_offset
= (text_end
& ((word
)max_page_size
- 1));
1368 VOLATILE
char * result
= (char *)(next_page
+ page_offset
);
1369 /* Note that this isnt equivalent to just adding */
1370 /* max_page_size to &etext if &etext is at a page boundary */
1372 GC_setup_temporary_fault_handler();
1373 if (SETJMP(GC_jmp_buf
) == 0) {
1374 /* Try writing to the address. */
1376 GC_reset_fault_handler();
1378 GC_reset_fault_handler();
1379 /* We got here via a longjmp. The address is not readable. */
1380 /* This is known to happen under Solaris 2.4 + gcc, which place */
1381 /* string constants in the text segment, but after etext. */
1382 /* Use plan B. Note that we now know there is a gap between */
1383 /* text and data segments, so plan A bought us something. */
1384 result
= (char *)GC_find_limit((ptr_t
)(DATAEND
), FALSE
);
1386 return((ptr_t
)result
);
1390 # if defined(FREEBSD) && defined(I386) && !defined(PCR)
1391 /* Its unclear whether this should be identical to the above, or */
1392 /* whether it should apply to non-X86 architectures. */
1393 /* For now we don't assume that there is always an empty page after */
1394 /* etext. But in some cases there actually seems to be slightly more. */
1395 /* This also deals with holes between read-only data and writable data. */
1396 ptr_t
GC_FreeBSDGetDataStart(max_page_size
, etext_addr
)
1400 word text_end
= ((word
)(etext_addr
) + sizeof(word
) - 1)
1401 & ~(sizeof(word
) - 1);
1402 /* etext rounded to word boundary */
1403 VOLATILE word next_page
= (text_end
+ (word
)max_page_size
- 1)
1404 & ~((word
)max_page_size
- 1);
1405 VOLATILE ptr_t result
= (ptr_t
)text_end
;
1406 GC_setup_temporary_fault_handler();
1407 if (SETJMP(GC_jmp_buf
) == 0) {
1408 /* Try reading at the address. */
1409 /* This should happen before there is another thread. */
1410 for (; next_page
< (word
)(DATAEND
); next_page
+= (word
)max_page_size
)
1411 *(VOLATILE
char *)next_page
;
1412 GC_reset_fault_handler();
1414 GC_reset_fault_handler();
1415 /* As above, we go to plan B */
1416 result
= GC_find_limit((ptr_t
)(DATAEND
), FALSE
);
1426 # define GC_AMIGA_DS
1427 # include "AmigaOS.c"
1430 #else /* !OS2 && !Windows && !AMIGA */
1432 void GC_register_data_segments()
1434 # if !defined(PCR) && !defined(SRC_M3) && !defined(MACOS)
1435 # if defined(REDIRECT_MALLOC) && defined(GC_SOLARIS_THREADS)
1436 /* As of Solaris 2.3, the Solaris threads implementation */
1437 /* allocates the data structure for the initial thread with */
1438 /* sbrk at process startup. It needs to be scanned, so that */
1439 /* we don't lose some malloc allocated data structures */
1440 /* hanging from it. We're on thin ice here ... */
1441 extern caddr_t
sbrk();
1443 GC_add_roots_inner(DATASTART
, (char *)sbrk(0), FALSE
);
1445 GC_add_roots_inner(DATASTART
, (char *)(DATAEND
), FALSE
);
1446 # if defined(DATASTART2)
1447 GC_add_roots_inner(DATASTART2
, (char *)(DATAEND2
), FALSE
);
1453 # if defined(THINK_C)
1454 extern void* GC_MacGetDataStart(void);
1455 /* globals begin above stack and end at a5. */
1456 GC_add_roots_inner((ptr_t
)GC_MacGetDataStart(),
1457 (ptr_t
)LMGetCurrentA5(), FALSE
);
1459 # if defined(__MWERKS__)
1461 extern void* GC_MacGetDataStart(void);
1462 /* MATTHEW: Function to handle Far Globals (CW Pro 3) */
1463 # if __option(far_data)
1464 extern void* GC_MacGetDataEnd(void);
1466 /* globals begin above stack and end at a5. */
1467 GC_add_roots_inner((ptr_t
)GC_MacGetDataStart(),
1468 (ptr_t
)LMGetCurrentA5(), FALSE
);
1469 /* MATTHEW: Handle Far Globals */
1470 # if __option(far_data)
1471 /* Far globals follow he QD globals: */
1472 GC_add_roots_inner((ptr_t
)LMGetCurrentA5(),
1473 (ptr_t
)GC_MacGetDataEnd(), FALSE
);
1476 extern char __data_start__
[], __data_end__
[];
1477 GC_add_roots_inner((ptr_t
)&__data_start__
,
1478 (ptr_t
)&__data_end__
, FALSE
);
1479 # endif /* __POWERPC__ */
1480 # endif /* __MWERKS__ */
1481 # endif /* !THINK_C */
1485 /* Dynamic libraries are added at every collection, since they may */
1489 # endif /* ! AMIGA */
1490 # endif /* ! MSWIN32 && ! MSWINCE*/
1494 * Auxiliary routines for obtaining memory from OS.
1497 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \
1498 && !defined(MSWIN32) && !defined(MSWINCE) \
1499 && !defined(MACOS) && !defined(DOS4GW)
1502 extern caddr_t
sbrk();
1505 # define SBRK_ARG_T ptrdiff_t
1507 # define SBRK_ARG_T int
1512 /* The compiler seems to generate speculative reads one past the end of */
1513 /* an allocated object. Hence we need to make sure that the page */
1514 /* following the last heap page is also mapped. */
1515 ptr_t
GC_unix_get_mem(bytes
)
1518 caddr_t cur_brk
= (caddr_t
)sbrk(0);
1520 SBRK_ARG_T lsbs
= (word
)cur_brk
& (GC_page_size
-1);
1521 static caddr_t my_brk_val
= 0;
1523 if ((SBRK_ARG_T
)bytes
< 0) return(0); /* too big */
1525 if((caddr_t
)(sbrk(GC_page_size
- lsbs
)) == (caddr_t
)(-1)) return(0);
1527 if (cur_brk
== my_brk_val
) {
1528 /* Use the extra block we allocated last time. */
1529 result
= (ptr_t
)sbrk((SBRK_ARG_T
)bytes
);
1530 if (result
== (caddr_t
)(-1)) return(0);
1531 result
-= GC_page_size
;
1533 result
= (ptr_t
)sbrk(GC_page_size
+ (SBRK_ARG_T
)bytes
);
1534 if (result
== (caddr_t
)(-1)) return(0);
1536 my_brk_val
= result
+ bytes
+ GC_page_size
; /* Always page aligned */
1537 return((ptr_t
)result
);
1540 #else /* Not RS6000 */
1542 #if defined(USE_MMAP) || defined(USE_MUNMAP)
1544 #ifdef USE_MMAP_FIXED
1545 # define GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE
1546 /* Seems to yield better performance on Solaris 2, but can */
1547 /* be unreliable if something is already mapped at the address. */
1549 # define GC_MMAP_FLAGS MAP_PRIVATE
1552 #ifdef USE_MMAP_ANON
1554 # if defined(MAP_ANONYMOUS)
1555 # define OPT_MAP_ANON MAP_ANONYMOUS
1557 # define OPT_MAP_ANON MAP_ANON
1561 # define OPT_MAP_ANON 0
1564 #endif /* defined(USE_MMAP) || defined(USE_MUNMAP) */
1566 #if defined(USE_MMAP)
1567 /* Tested only under Linux, IRIX5 and Solaris 2 */
1570 # define HEAP_START 0
1573 ptr_t
GC_unix_get_mem(bytes
)
1577 static ptr_t last_addr
= HEAP_START
;
1579 # ifndef USE_MMAP_ANON
1580 static GC_bool initialized
= FALSE
;
1583 zero_fd
= open("/dev/zero", O_RDONLY
);
1584 fcntl(zero_fd
, F_SETFD
, FD_CLOEXEC
);
1589 if (bytes
& (GC_page_size
-1)) ABORT("Bad GET_MEM arg");
1590 result
= mmap(last_addr
, bytes
, PROT_READ
| PROT_WRITE
| OPT_PROT_EXEC
,
1591 GC_MMAP_FLAGS
| OPT_MAP_ANON
, zero_fd
, 0/* offset */);
1592 if (result
== MAP_FAILED
) return(0);
1593 last_addr
= (ptr_t
)result
+ bytes
+ GC_page_size
- 1;
1594 last_addr
= (ptr_t
)((word
)last_addr
& ~(GC_page_size
- 1));
1595 # if !defined(LINUX)
1596 if (last_addr
== 0) {
1597 /* Oops. We got the end of the address space. This isn't */
1598 /* usable by arbitrary C code, since one-past-end pointers */
1599 /* don't work, so we discard it and try again. */
1600 munmap(result
, (size_t)(-GC_page_size
) - (size_t)result
);
1601 /* Leave last page mapped, so we can't repeat. */
1602 return GC_unix_get_mem(bytes
);
1605 GC_ASSERT(last_addr
!= 0);
1607 return((ptr_t
)result
);
1610 #else /* Not RS6000, not USE_MMAP */
1611 ptr_t
GC_unix_get_mem(bytes
)
1616 /* Bare sbrk isn't thread safe. Play by malloc rules. */
1617 /* The equivalent may be needed on other systems as well. */
1621 ptr_t cur_brk
= (ptr_t
)sbrk(0);
1622 SBRK_ARG_T lsbs
= (word
)cur_brk
& (GC_page_size
-1);
1624 if ((SBRK_ARG_T
)bytes
< 0) return(0); /* too big */
1626 if((ptr_t
)sbrk(GC_page_size
- lsbs
) == (ptr_t
)(-1)) return(0);
1628 result
= (ptr_t
)sbrk((SBRK_ARG_T
)bytes
);
1629 if (result
== (ptr_t
)(-1)) result
= 0;
1637 #endif /* Not USE_MMAP */
1638 #endif /* Not RS6000 */
1644 void * os2_alloc(size_t bytes
)
1648 if (DosAllocMem(&result
, bytes
, PAG_EXECUTE
| PAG_READ
|
1649 PAG_WRITE
| PAG_COMMIT
)
1653 if (result
== 0) return(os2_alloc(bytes
));
1660 # if defined(MSWIN32) || defined(MSWINCE)
1661 SYSTEM_INFO GC_sysinfo
;
1666 # ifdef USE_GLOBAL_ALLOC
1667 # define GLOBAL_ALLOC_TEST 1
1669 # define GLOBAL_ALLOC_TEST GC_no_win32_dlls
1672 word GC_n_heap_bases
= 0;
1674 ptr_t
GC_win32_get_mem(bytes
)
1679 if (GLOBAL_ALLOC_TEST
) {
1680 /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE. */
1681 /* There are also unconfirmed rumors of other */
1682 /* problems, so we dodge the issue. */
1683 result
= (ptr_t
) GlobalAlloc(0, bytes
+ HBLKSIZE
);
1684 result
= (ptr_t
)(((word
)result
+ HBLKSIZE
) & ~(HBLKSIZE
-1));
1686 /* VirtualProtect only works on regions returned by a */
1687 /* single VirtualAlloc call. Thus we allocate one */
1688 /* extra page, which will prevent merging of blocks */
1689 /* in separate regions, and eliminate any temptation */
1690 /* to call VirtualProtect on a range spanning regions. */
1691 /* This wastes a small amount of memory, and risks */
1692 /* increased fragmentation. But better alternatives */
1693 /* would require effort. */
1694 result
= (ptr_t
) VirtualAlloc(NULL
, bytes
+ 1,
1695 MEM_COMMIT
| MEM_RESERVE
,
1696 PAGE_EXECUTE_READWRITE
);
1698 if (HBLKDISPL(result
) != 0) ABORT("Bad VirtualAlloc result");
1699 /* If I read the documentation correctly, this can */
1700 /* only happen if HBLKSIZE > 64k or not a power of 2. */
1701 if (GC_n_heap_bases
>= MAX_HEAP_SECTS
) ABORT("Too many heap sections");
1702 GC_heap_bases
[GC_n_heap_bases
++] = result
;
1706 void GC_win32_free_heap ()
1708 if (GC_no_win32_dlls
) {
1709 while (GC_n_heap_bases
> 0) {
1710 GlobalFree (GC_heap_bases
[--GC_n_heap_bases
]);
1711 GC_heap_bases
[GC_n_heap_bases
] = 0;
1718 # define GC_AMIGA_AM
1719 # include "AmigaOS.c"
1725 word GC_n_heap_bases
= 0;
1727 ptr_t
GC_wince_get_mem(bytes
)
1733 /* Round up allocation size to multiple of page size */
1734 bytes
= (bytes
+ GC_page_size
-1) & ~(GC_page_size
-1);
1736 /* Try to find reserved, uncommitted pages */
1737 for (i
= 0; i
< GC_n_heap_bases
; i
++) {
1738 if (((word
)(-(signed_word
)GC_heap_lengths
[i
])
1739 & (GC_sysinfo
.dwAllocationGranularity
-1))
1741 result
= GC_heap_bases
[i
] + GC_heap_lengths
[i
];
1746 if (i
== GC_n_heap_bases
) {
1747 /* Reserve more pages */
1748 word res_bytes
= (bytes
+ GC_sysinfo
.dwAllocationGranularity
-1)
1749 & ~(GC_sysinfo
.dwAllocationGranularity
-1);
1750 /* If we ever support MPROTECT_VDB here, we will probably need to */
1751 /* ensure that res_bytes is strictly > bytes, so that VirtualProtect */
1752 /* never spans regions. It seems to be OK for a VirtualFree argument */
1753 /* to span regions, so we should be OK for now. */
1754 result
= (ptr_t
) VirtualAlloc(NULL
, res_bytes
,
1755 MEM_RESERVE
| MEM_TOP_DOWN
,
1756 PAGE_EXECUTE_READWRITE
);
1757 if (HBLKDISPL(result
) != 0) ABORT("Bad VirtualAlloc result");
1758 /* If I read the documentation correctly, this can */
1759 /* only happen if HBLKSIZE > 64k or not a power of 2. */
1760 if (GC_n_heap_bases
>= MAX_HEAP_SECTS
) ABORT("Too many heap sections");
1761 GC_heap_bases
[GC_n_heap_bases
] = result
;
1762 GC_heap_lengths
[GC_n_heap_bases
] = 0;
1767 result
= (ptr_t
) VirtualAlloc(result
, bytes
,
1769 PAGE_EXECUTE_READWRITE
);
1770 if (result
!= NULL
) {
1771 if (HBLKDISPL(result
) != 0) ABORT("Bad VirtualAlloc result");
1772 GC_heap_lengths
[i
] += bytes
;
1781 /* For now, this only works on Win32/WinCE and some Unix-like */
1782 /* systems. If you have something else, don't define */
1784 /* We assume ANSI C to support this feature. */
1786 #if !defined(MSWIN32) && !defined(MSWINCE)
1789 #include <sys/mman.h>
1790 #include <sys/stat.h>
1791 #include <sys/types.h>
1795 /* Compute a page aligned starting address for the unmap */
1796 /* operation on a block of size bytes starting at start. */
1797 /* Return 0 if the block is too small to make this feasible. */
1798 ptr_t
GC_unmap_start(ptr_t start
, word bytes
)
1800 ptr_t result
= start
;
1801 /* Round start to next page boundary. */
1802 result
+= GC_page_size
- 1;
1803 result
= (ptr_t
)((word
)result
& ~(GC_page_size
- 1));
1804 if (result
+ GC_page_size
> start
+ bytes
) return 0;
1808 /* Compute end address for an unmap operation on the indicated */
1810 ptr_t
GC_unmap_end(ptr_t start
, word bytes
)
1812 ptr_t end_addr
= start
+ bytes
;
1813 end_addr
= (ptr_t
)((word
)end_addr
& ~(GC_page_size
- 1));
1817 /* Under Win32/WinCE we commit (map) and decommit (unmap) */
1818 /* memory using VirtualAlloc and VirtualFree. These functions */
1819 /* work on individual allocations of virtual memory, made */
1820 /* previously using VirtualAlloc with the MEM_RESERVE flag. */
1821 /* The ranges we need to (de)commit may span several of these */
1822 /* allocations; therefore we use VirtualQuery to check */
1823 /* allocation lengths, and split up the range as necessary. */
1825 /* We assume that GC_remap is called on exactly the same range */
1826 /* as a previous call to GC_unmap. It is safe to consistently */
1827 /* round the endpoints in both places. */
1828 void GC_unmap(ptr_t start
, word bytes
)
1830 ptr_t start_addr
= GC_unmap_start(start
, bytes
);
1831 ptr_t end_addr
= GC_unmap_end(start
, bytes
);
1832 word len
= end_addr
- start_addr
;
1833 if (0 == start_addr
) return;
1834 # if defined(MSWIN32) || defined(MSWINCE)
1836 MEMORY_BASIC_INFORMATION mem_info
;
1838 if (VirtualQuery(start_addr
, &mem_info
, sizeof(mem_info
))
1839 != sizeof(mem_info
))
1840 ABORT("Weird VirtualQuery result");
1841 free_len
= (len
< mem_info
.RegionSize
) ? len
: mem_info
.RegionSize
;
1842 if (!VirtualFree(start_addr
, free_len
, MEM_DECOMMIT
))
1843 ABORT("VirtualFree failed");
1844 GC_unmapped_bytes
+= free_len
;
1845 start_addr
+= free_len
;
1849 /* We immediately remap it to prevent an intervening mmap from */
1850 /* accidentally grabbing the same address space. */
1853 result
= mmap(start_addr
, len
, PROT_NONE
,
1854 MAP_PRIVATE
| MAP_FIXED
| OPT_MAP_ANON
,
1855 zero_fd
, 0/* offset */);
1856 if (result
!= (void *)start_addr
) ABORT("mmap(...PROT_NONE...) failed");
1858 GC_unmapped_bytes
+= len
;
1863 void GC_remap(ptr_t start
, word bytes
)
1865 ptr_t start_addr
= GC_unmap_start(start
, bytes
);
1866 ptr_t end_addr
= GC_unmap_end(start
, bytes
);
1867 word len
= end_addr
- start_addr
;
1869 # if defined(MSWIN32) || defined(MSWINCE)
1872 if (0 == start_addr
) return;
1874 MEMORY_BASIC_INFORMATION mem_info
;
1876 if (VirtualQuery(start_addr
, &mem_info
, sizeof(mem_info
))
1877 != sizeof(mem_info
))
1878 ABORT("Weird VirtualQuery result");
1879 alloc_len
= (len
< mem_info
.RegionSize
) ? len
: mem_info
.RegionSize
;
1880 result
= VirtualAlloc(start_addr
, alloc_len
,
1882 PAGE_EXECUTE_READWRITE
);
1883 if (result
!= start_addr
) {
1884 ABORT("VirtualAlloc remapping failed");
1886 GC_unmapped_bytes
-= alloc_len
;
1887 start_addr
+= alloc_len
;
1891 /* It was already remapped with PROT_NONE. */
1894 if (0 == start_addr
) return;
1895 result
= mprotect(start_addr
, len
,
1896 PROT_READ
| PROT_WRITE
| OPT_PROT_EXEC
);
1899 "Mprotect failed at 0x%lx (length %ld) with errno %ld\n",
1900 start_addr
, len
, errno
);
1901 ABORT("Mprotect remapping failed");
1903 GC_unmapped_bytes
-= len
;
1907 /* Two adjacent blocks have already been unmapped and are about to */
1908 /* be merged. Unmap the whole block. This typically requires */
1909 /* that we unmap a small section in the middle that was not previously */
1910 /* unmapped due to alignment constraints. */
1911 void GC_unmap_gap(ptr_t start1
, word bytes1
, ptr_t start2
, word bytes2
)
1913 ptr_t start1_addr
= GC_unmap_start(start1
, bytes1
);
1914 ptr_t end1_addr
= GC_unmap_end(start1
, bytes1
);
1915 ptr_t start2_addr
= GC_unmap_start(start2
, bytes2
);
1916 ptr_t end2_addr
= GC_unmap_end(start2
, bytes2
);
1917 ptr_t start_addr
= end1_addr
;
1918 ptr_t end_addr
= start2_addr
;
1920 GC_ASSERT(start1
+ bytes1
== start2
);
1921 if (0 == start1_addr
) start_addr
= GC_unmap_start(start1
, bytes1
+ bytes2
);
1922 if (0 == start2_addr
) end_addr
= GC_unmap_end(start1
, bytes1
+ bytes2
);
1923 if (0 == start_addr
) return;
1924 len
= end_addr
- start_addr
;
1925 # if defined(MSWIN32) || defined(MSWINCE)
1927 MEMORY_BASIC_INFORMATION mem_info
;
1929 if (VirtualQuery(start_addr
, &mem_info
, sizeof(mem_info
))
1930 != sizeof(mem_info
))
1931 ABORT("Weird VirtualQuery result");
1932 free_len
= (len
< mem_info
.RegionSize
) ? len
: mem_info
.RegionSize
;
1933 if (!VirtualFree(start_addr
, free_len
, MEM_DECOMMIT
))
1934 ABORT("VirtualFree failed");
1935 GC_unmapped_bytes
+= free_len
;
1936 start_addr
+= free_len
;
1940 if (len
!= 0 && munmap(start_addr
, len
) != 0) ABORT("munmap failed");
1941 GC_unmapped_bytes
+= len
;
1945 #endif /* USE_MUNMAP */
1947 /* Routine for pushing any additional roots. In THREADS */
1948 /* environment, this is also responsible for marking from */
1949 /* thread stacks. */
1951 void (*GC_push_other_roots
)() = 0;
1955 PCR_ERes
GC_push_thread_stack(PCR_Th_T
*t
, PCR_Any dummy
)
1957 struct PCR_ThCtl_TInfoRep info
;
1960 info
.ti_stkLow
= info
.ti_stkHi
= 0;
1961 result
= PCR_ThCtl_GetInfo(t
, &info
);
1962 GC_push_all_stack((ptr_t
)(info
.ti_stkLow
), (ptr_t
)(info
.ti_stkHi
));
1966 /* Push the contents of an old object. We treat this as stack */
1967 /* data only becasue that makes it robust against mark stack */
1969 PCR_ERes
GC_push_old_obj(void *p
, size_t size
, PCR_Any data
)
1971 GC_push_all_stack((ptr_t
)p
, (ptr_t
)p
+ size
);
1972 return(PCR_ERes_okay
);
1976 void GC_default_push_other_roots
GC_PROTO((void))
1978 /* Traverse data allocated by previous memory managers. */
1980 extern struct PCR_MM_ProcsRep
* GC_old_allocator
;
1982 if ((*(GC_old_allocator
->mmp_enumerate
))(PCR_Bool_false
,
1985 ABORT("Old object enumeration failed");
1988 /* Traverse all thread stacks. */
1990 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack
,0))
1991 || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
1992 ABORT("Thread stack marking failed\n");
2000 # ifdef ALL_INTERIOR_POINTERS
2004 void GC_push_thread_structures
GC_PROTO((void))
2006 /* Not our responsibibility. */
2009 extern void ThreadF__ProcessStacks();
2011 void GC_push_thread_stack(start
, stop
)
2014 GC_push_all_stack((ptr_t
)start
, (ptr_t
)stop
+ sizeof(word
));
2017 /* Push routine with M3 specific calling convention. */
2018 GC_m3_push_root(dummy1
, p
, dummy2
, dummy3
)
2020 ptr_t dummy1
, dummy2
;
2025 GC_PUSH_ONE_STACK(q
, p
);
2028 /* M3 set equivalent to RTHeap.TracedRefTypes */
2029 typedef struct { int elts
[1]; } RefTypeSet
;
2030 RefTypeSet GC_TracedRefTypes
= {{0x1}};
2032 void GC_default_push_other_roots
GC_PROTO((void))
2034 /* Use the M3 provided routine for finding static roots. */
2035 /* This is a bit dubious, since it presumes no C roots. */
2036 /* We handle the collector roots explicitly in GC_push_roots */
2037 RTMain__GlobalMapProc(GC_m3_push_root
, 0, GC_TracedRefTypes
);
2038 if (GC_words_allocd
> 0) {
2039 ThreadF__ProcessStacks(GC_push_thread_stack
);
2041 /* Otherwise this isn't absolutely necessary, and we have */
2042 /* startup ordering problems. */
2045 # endif /* SRC_M3 */
2047 # if defined(GC_SOLARIS_THREADS) || defined(GC_PTHREADS) || \
2048 defined(GC_WIN32_THREADS)
2050 extern void GC_push_all_stacks();
2052 void GC_default_push_other_roots
GC_PROTO((void))
2054 GC_push_all_stacks();
2057 # endif /* GC_SOLARIS_THREADS || GC_PTHREADS */
2059 void (*GC_push_other_roots
) GC_PROTO((void)) = GC_default_push_other_roots
;
2061 #endif /* THREADS */
2064 * Routines for accessing dirty bits on virtual pages.
2065 * We plan to eventually implement four strategies for doing so:
2066 * DEFAULT_VDB: A simple dummy implementation that treats every page
2067 * as possibly dirty. This makes incremental collection
2068 * useless, but the implementation is still correct.
2069 * PCR_VDB: Use PPCRs virtual dirty bit facility.
2070 * PROC_VDB: Use the /proc facility for reading dirty bits. Only
2071 * works under some SVR4 variants. Even then, it may be
2072 * too slow to be entirely satisfactory. Requires reading
2073 * dirty bits for entire address space. Implementations tend
2074 * to assume that the client is a (slow) debugger.
2075 * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
2076 * dirtied pages. The implementation (and implementability)
2077 * is highly system dependent. This usually fails when system
2078 * calls write to a protected page. We prevent the read system
2079 * call from doing so. It is the clients responsibility to
2080 * make sure that other system calls are similarly protected
2081 * or write only to the stack.
2083 GC_bool GC_dirty_maintained
= FALSE
;
2087 /* All of the following assume the allocation lock is held, and */
2088 /* signals are disabled. */
2090 /* The client asserts that unallocated pages in the heap are never */
2093 /* Initialize virtual dirty bit implementation. */
2094 void GC_dirty_init()
2097 GC_printf0("Initializing DEFAULT_VDB...\n");
2099 GC_dirty_maintained
= TRUE
;
2102 /* Retrieve system dirty bits for heap to a local buffer. */
2103 /* Restore the systems notion of which pages are dirty. */
2104 void GC_read_dirty()
2107 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */
2108 /* If the actual page size is different, this returns TRUE if any */
2109 /* of the pages overlapping h are dirty. This routine may err on the */
2110 /* side of labelling pages as dirty (and this implementation does). */
2112 GC_bool
GC_page_was_dirty(h
)
2119 * The following two routines are typically less crucial. They matter
2120 * most with large dynamic libraries, or if we can't accurately identify
2121 * stacks, e.g. under Solaris 2.X. Otherwise the following default
2122 * versions are adequate.
2125 /* Could any valid GC heap pointer ever have been written to this page? */
2127 GC_bool
GC_page_was_ever_dirty(h
)
2133 /* Reset the n pages starting at h to "was never dirty" status. */
2134 void GC_is_fresh(h
, n
)
2141 /* I) hints that [h, h+nblocks) is about to be written. */
2142 /* II) guarantees that protection is removed. */
2143 /* (I) may speed up some dirty bit implementations. */
2144 /* (II) may be essential if we need to ensure that */
2145 /* pointer-free system call buffers in the heap are */
2146 /* not protected. */
2148 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
2155 # endif /* DEFAULT_VDB */
2158 # ifdef MPROTECT_VDB
2161 * See DEFAULT_VDB for interface descriptions.
2165 * This implementation maintains dirty bits itself by catching write
2166 * faults and keeping track of them. We assume nobody else catches
2167 * SIGBUS or SIGSEGV. We assume no write faults occur in system calls.
2168 * This means that clients must ensure that system calls don't write
2169 * to the write-protected heap. Probably the best way to do this is to
2170 * ensure that system calls write at most to POINTERFREE objects in the
2171 * heap, and do even that only if we are on a platform on which those
2172 * are not protected. Another alternative is to wrap system calls
2173 * (see example for read below), but the current implementation holds
2174 * a lock across blocking calls, making it problematic for multithreaded
2176 * We assume the page size is a multiple of HBLKSIZE.
2177 * We prefer them to be the same. We avoid protecting POINTERFREE
2178 * objects only if they are the same.
2181 # if !defined(MSWIN32) && !defined(MSWINCE) && !defined(DARWIN)
2183 # include <sys/mman.h>
2184 # include <signal.h>
2185 # include <sys/syscall.h>
2187 # define PROTECT(addr, len) \
2188 if (mprotect((caddr_t)(addr), (size_t)(len), \
2189 PROT_READ | OPT_PROT_EXEC) < 0) { \
2190 ABORT("mprotect failed"); \
2192 # define UNPROTECT(addr, len) \
2193 if (mprotect((caddr_t)(addr), (size_t)(len), \
2194 PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
2195 ABORT("un-mprotect failed"); \
2201 /* Using vm_protect (mach syscall) over mprotect (BSD syscall) seems to
2202 decrease the likelihood of some of the problems described below. */
2203 #include <mach/vm_map.h>
2204 static mach_port_t GC_task_self
;
2205 #define PROTECT(addr,len) \
2206 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2207 FALSE,VM_PROT_READ) != KERN_SUCCESS) { \
2208 ABORT("vm_portect failed"); \
2210 #define UNPROTECT(addr,len) \
2211 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2212 FALSE,VM_PROT_READ|VM_PROT_WRITE) != KERN_SUCCESS) { \
2213 ABORT("vm_portect failed"); \
2218 # include <signal.h>
2221 static DWORD protect_junk
;
2222 # define PROTECT(addr, len) \
2223 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
2225 DWORD last_error = GetLastError(); \
2226 GC_printf1("Last error code: %lx\n", last_error); \
2227 ABORT("VirtualProtect failed"); \
2229 # define UNPROTECT(addr, len) \
2230 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
2232 ABORT("un-VirtualProtect failed"); \
2234 # endif /* !DARWIN */
2235 # endif /* MSWIN32 || MSWINCE || DARWIN */
2237 #if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2238 typedef void (* SIG_PF
)();
2239 #endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2241 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX) \
2244 typedef void (* SIG_PF
)(int);
2246 typedef void (* SIG_PF
)();
2248 #endif /* SUNOS5SIGS || OSF1 || LINUX || HURD */
2250 #if defined(MSWIN32)
2251 typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF
;
2253 # define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
2255 #if defined(MSWINCE)
2256 typedef LONG (WINAPI
*SIG_PF
)(struct _EXCEPTION_POINTERS
*);
2258 # define SIG_DFL (SIG_PF) (-1)
2261 #if defined(IRIX5) || defined(OSF1) || defined(HURD)
2262 typedef void (* REAL_SIG_PF
)(int, int, struct sigcontext
*);
2263 #endif /* IRIX5 || OSF1 || HURD */
2265 #if defined(SUNOS5SIGS)
2266 # if defined(HPUX) || defined(FREEBSD)
2267 # define SIGINFO_T siginfo_t
2269 # define SIGINFO_T struct siginfo
2272 typedef void (* REAL_SIG_PF
)(int, SIGINFO_T
*, void *);
2274 typedef void (* REAL_SIG_PF
)();
2276 #endif /* SUNOS5SIGS */
2279 # if __GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ >= 2
2280 typedef struct sigcontext s_c
;
2281 # else /* glibc < 2.2 */
2282 # include <linux/version.h>
2283 # if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA) || defined(ARM32)
2284 typedef struct sigcontext s_c
;
2286 typedef struct sigcontext_struct s_c
;
2288 # endif /* glibc < 2.2 */
2289 # if defined(ALPHA) || defined(M68K)
2290 typedef void (* REAL_SIG_PF
)(int, int, s_c
*);
2292 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2293 typedef void (* REAL_SIG_PF
)(int, siginfo_t
*, s_c
*);
2295 /* According to SUSV3, the last argument should have type */
2296 /* void * or ucontext_t * */
2298 typedef void (* REAL_SIG_PF
)(int, s_c
);
2302 /* Retrieve fault address from sigcontext structure by decoding */
2304 char * get_fault_addr(s_c
*sc
) {
2308 instr
= *((unsigned *)(sc
->sc_pc
));
2309 faultaddr
= sc
->sc_regs
[(instr
>> 16) & 0x1f];
2310 faultaddr
+= (word
) (((int)instr
<< 16) >> 16);
2311 return (char *)faultaddr
;
2313 # endif /* !ALPHA */
2317 SIG_PF GC_old_bus_handler
;
2318 SIG_PF GC_old_segv_handler
; /* Also old MSWIN32 ACCESS_VIOLATION filter */
2319 #endif /* !DARWIN */
2321 #if defined(THREADS)
2322 /* We need to lock around the bitmap update in the write fault handler */
2323 /* in order to avoid the risk of losing a bit. We do this with a */
2324 /* test-and-set spin lock if we know how to do that. Otherwise we */
2325 /* check whether we are already in the handler and use the dumb but */
2326 /* safe fallback algorithm of setting all bits in the word. */
2327 /* Contention should be very rare, so we do the minimum to handle it */
2329 #ifdef GC_TEST_AND_SET_DEFINED
2330 static VOLATILE
unsigned int fault_handler_lock
= 0;
2331 void async_set_pht_entry_from_index(VOLATILE page_hash_table db
, int index
) {
2332 while (GC_test_and_set(&fault_handler_lock
)) {}
2333 /* Could also revert to set_pht_entry_from_index_safe if initial */
2334 /* GC_test_and_set fails. */
2335 set_pht_entry_from_index(db
, index
);
2336 GC_clear(&fault_handler_lock
);
2338 #else /* !GC_TEST_AND_SET_DEFINED */
2339 /* THIS IS INCORRECT! The dirty bit vector may be temporarily wrong, */
2340 /* just before we notice the conflict and correct it. We may end up */
2341 /* looking at it while it's wrong. But this requires contention */
2342 /* exactly when a GC is triggered, which seems far less likely to */
2343 /* fail than the old code, which had no reported failures. Thus we */
2344 /* leave it this way while we think of something better, or support */
2345 /* GC_test_and_set on the remaining platforms. */
2346 static VOLATILE word currently_updating
= 0;
2347 void async_set_pht_entry_from_index(VOLATILE page_hash_table db
, int index
) {
2348 unsigned int update_dummy
;
2349 currently_updating
= (word
)(&update_dummy
);
2350 set_pht_entry_from_index(db
, index
);
2351 /* If we get contention in the 10 or so instruction window here, */
2352 /* and we get stopped by a GC between the two updates, we lose! */
2353 if (currently_updating
!= (word
)(&update_dummy
)) {
2354 set_pht_entry_from_index_safe(db
, index
);
2355 /* We claim that if two threads concurrently try to update the */
2356 /* dirty bit vector, the first one to execute UPDATE_START */
2357 /* will see it changed when UPDATE_END is executed. (Note that */
2358 /* &update_dummy must differ in two distinct threads.) It */
2359 /* will then execute set_pht_entry_from_index_safe, thus */
2360 /* returning us to a safe state, though not soon enough. */
2363 #endif /* !GC_TEST_AND_SET_DEFINED */
2364 #else /* !THREADS */
2365 # define async_set_pht_entry_from_index(db, index) \
2366 set_pht_entry_from_index(db, index)
2367 #endif /* !THREADS */
2370 #if !defined(DARWIN)
2371 # if defined (SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2372 void GC_write_fault_handler(sig
, code
, scp
, addr
)
2374 struct sigcontext
*scp
;
2377 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2378 # define CODE_OK (FC_CODE(code) == FC_PROT \
2379 || (FC_CODE(code) == FC_OBJERR \
2380 && FC_ERRNO(code) == FC_PROT))
2383 # define SIG_OK (sig == SIGBUS)
2384 # define CODE_OK (code == BUS_PAGE_FAULT)
2386 # endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2388 # if defined(IRIX5) || defined(OSF1) || defined(HURD)
2390 void GC_write_fault_handler(int sig
, int code
, struct sigcontext
*scp
)
2392 # define SIG_OK (sig == SIGSEGV)
2393 # define CODE_OK (code == 2 /* experimentally determined */)
2396 # define SIG_OK (sig == SIGSEGV)
2397 # define CODE_OK (code == EACCES)
2400 # define SIG_OK (sig == SIGBUS || sig == SIGSEGV)
2401 # define CODE_OK TRUE
2403 # endif /* IRIX5 || OSF1 || HURD */
2406 # if defined(ALPHA) || defined(M68K)
2407 void GC_write_fault_handler(int sig
, int code
, s_c
* sc
)
2409 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2410 void GC_write_fault_handler(int sig
, siginfo_t
* si
, s_c
* scp
)
2413 void GC_write_fault_handler(int sig
, int a2
, int a3
, int a4
, s_c sc
)
2415 void GC_write_fault_handler(int sig
, s_c sc
)
2419 # define SIG_OK (sig == SIGSEGV)
2420 # define CODE_OK TRUE
2421 /* Empirically c.trapno == 14, on IA32, but is that useful? */
2422 /* Should probably consider alignment issues on other */
2423 /* architectures. */
2426 # if defined(SUNOS5SIGS)
2428 void GC_write_fault_handler(int sig
, SIGINFO_T
*scp
, void * context
)
2430 void GC_write_fault_handler(sig
, scp
, context
)
2436 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2437 # define CODE_OK (scp -> si_code == SEGV_ACCERR) \
2438 || (scp -> si_code == BUS_ADRERR) \
2439 || (scp -> si_code == BUS_UNKNOWN) \
2440 || (scp -> si_code == SEGV_UNKNOWN) \
2441 || (scp -> si_code == BUS_OBJERR)
2444 # define SIG_OK (sig == SIGBUS)
2445 # define CODE_OK (scp -> si_code == BUS_PAGE_FAULT)
2447 # define SIG_OK (sig == SIGSEGV)
2448 # define CODE_OK (scp -> si_code == SEGV_ACCERR)
2451 # endif /* SUNOS5SIGS */
2453 # if defined(MSWIN32) || defined(MSWINCE)
2454 LONG WINAPI
GC_write_fault_handler(struct _EXCEPTION_POINTERS
*exc_info
)
2455 # define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
2456 STATUS_ACCESS_VIOLATION)
2457 # define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
2459 # endif /* MSWIN32 || MSWINCE */
2461 register unsigned i
;
2463 char *addr
= (char *) code
;
2466 char * addr
= (char *) (size_t) (scp
-> sc_badvaddr
);
2468 # if defined(OSF1) && defined(ALPHA)
2469 char * addr
= (char *) (scp
-> sc_traparg_a0
);
2472 char * addr
= (char *) (scp
-> si_addr
);
2476 char * addr
= (char *) (sc
.cr2
);
2481 struct sigcontext
*scp
= (struct sigcontext
*)(sc
);
2483 int format
= (scp
->sc_formatvec
>> 12) & 0xf;
2484 unsigned long *framedata
= (unsigned long *)(scp
+ 1);
2487 if (format
== 0xa || format
== 0xb) {
2490 } else if (format
== 7) {
2493 if (framedata
[1] & 0x08000000) {
2494 /* correct addr on misaligned access */
2495 ea
= (ea
+4095)&(~4095);
2497 } else if (format
== 4) {
2500 if (framedata
[1] & 0x08000000) {
2501 /* correct addr on misaligned access */
2502 ea
= (ea
+4095)&(~4095);
2508 char * addr
= get_fault_addr(sc
);
2510 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2511 char * addr
= si
-> si_addr
;
2512 /* I believe this is claimed to work on all platforms for */
2513 /* Linux 2.3.47 and later. Hopefully we don't have to */
2514 /* worry about earlier kernels on IA64. */
2516 # if defined(POWERPC)
2517 char * addr
= (char *) (sc
.regs
->dar
);
2520 char * addr
= (char *)sc
.fault_address
;
2522 --> architecture
not supported
2530 # if defined(MSWIN32) || defined(MSWINCE)
2531 char * addr
= (char *) (exc_info
-> ExceptionRecord
2532 -> ExceptionInformation
[1]);
2533 # define sig SIGSEGV
2536 if (SIG_OK
&& CODE_OK
) {
2537 register struct hblk
* h
=
2538 (struct hblk
*)((word
)addr
& ~(GC_page_size
-1));
2539 GC_bool in_allocd_block
;
2542 /* Address is only within the correct physical page. */
2543 in_allocd_block
= FALSE
;
2544 for (i
= 0; i
< divHBLKSZ(GC_page_size
); i
++) {
2545 if (HDR(h
+i
) != 0) {
2546 in_allocd_block
= TRUE
;
2550 in_allocd_block
= (HDR(addr
) != 0);
2552 if (!in_allocd_block
) {
2553 /* FIXME - We should make sure that we invoke the */
2554 /* old handler with the appropriate calling */
2555 /* sequence, which often depends on SA_SIGINFO. */
2557 /* Heap blocks now begin and end on page boundaries */
2560 if (sig
== SIGSEGV
) {
2561 old_handler
= GC_old_segv_handler
;
2563 old_handler
= GC_old_bus_handler
;
2565 if (old_handler
== SIG_DFL
) {
2566 # if !defined(MSWIN32) && !defined(MSWINCE)
2567 GC_err_printf1("Segfault at 0x%lx\n", addr
);
2568 ABORT("Unexpected bus error or segmentation fault");
2570 return(EXCEPTION_CONTINUE_SEARCH
);
2573 # if defined (SUNOS4) \
2574 || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2575 (*old_handler
) (sig
, code
, scp
, addr
);
2578 # if defined (SUNOS5SIGS)
2580 * FIXME: For FreeBSD, this code should check if the
2581 * old signal handler used the traditional BSD style and
2582 * if so call it using that style.
2584 (*(REAL_SIG_PF
)old_handler
) (sig
, scp
, context
);
2587 # if defined (LINUX)
2588 # if defined(ALPHA) || defined(M68K)
2589 (*(REAL_SIG_PF
)old_handler
) (sig
, code
, sc
);
2591 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2592 (*(REAL_SIG_PF
)old_handler
) (sig
, si
, scp
);
2594 (*(REAL_SIG_PF
)old_handler
) (sig
, sc
);
2599 # if defined (IRIX5) || defined(OSF1) || defined(HURD)
2600 (*(REAL_SIG_PF
)old_handler
) (sig
, code
, scp
);
2604 return((*old_handler
)(exc_info
));
2608 UNPROTECT(h
, GC_page_size
);
2609 /* We need to make sure that no collection occurs between */
2610 /* the UNPROTECT and the setting of the dirty bit. Otherwise */
2611 /* a write by a third thread might go unnoticed. Reversing */
2612 /* the order is just as bad, since we would end up unprotecting */
2613 /* a page in a GC cycle during which it's not marked. */
2614 /* Currently we do this by disabling the thread stopping */
2615 /* signals while this handler is running. An alternative might */
2616 /* be to record the fact that we're about to unprotect, or */
2617 /* have just unprotected a page in the GC's thread structure, */
2618 /* and then to have the thread stopping code set the dirty */
2619 /* flag, if necessary. */
2620 for (i
= 0; i
< divHBLKSZ(GC_page_size
); i
++) {
2621 register int index
= PHT_HASH(h
+i
);
2623 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
2626 /* These reset the signal handler each time by default. */
2627 signal(SIGSEGV
, (SIG_PF
) GC_write_fault_handler
);
2629 /* The write may not take place before dirty bits are read. */
2630 /* But then we'll fault again ... */
2631 # if defined(MSWIN32) || defined(MSWINCE)
2632 return(EXCEPTION_CONTINUE_EXECUTION
);
2637 #if defined(MSWIN32) || defined(MSWINCE)
2638 return EXCEPTION_CONTINUE_SEARCH
;
2640 GC_err_printf1("Segfault at 0x%lx\n", addr
);
2641 ABORT("Unexpected bus error or segmentation fault");
2644 #endif /* !DARWIN */
2647 * We hold the allocation lock. We expect block h to be written
2648 * shortly. Ensure that all pages containing any part of the n hblks
2649 * starting at h are no longer protected. If is_ptrfree is false,
2650 * also ensure that they will subsequently appear to be dirty.
2652 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
2657 struct hblk
* h_trunc
; /* Truncated to page boundary */
2658 struct hblk
* h_end
; /* Page boundary following block end */
2659 struct hblk
* current
;
2660 GC_bool found_clean
;
2662 if (!GC_dirty_maintained
) return;
2663 h_trunc
= (struct hblk
*)((word
)h
& ~(GC_page_size
-1));
2664 h_end
= (struct hblk
*)(((word
)(h
+ nblocks
) + GC_page_size
-1)
2665 & ~(GC_page_size
-1));
2666 found_clean
= FALSE
;
2667 for (current
= h_trunc
; current
< h_end
; ++current
) {
2668 int index
= PHT_HASH(current
);
2670 if (!is_ptrfree
|| current
< h
|| current
>= h
+ nblocks
) {
2671 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
2674 UNPROTECT(h_trunc
, (ptr_t
)h_end
- (ptr_t
)h_trunc
);
2677 #if !defined(DARWIN)
2678 void GC_dirty_init()
2680 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(LINUX) || \
2681 defined(OSF1) || defined(HURD)
2682 struct sigaction act
, oldact
;
2683 /* We should probably specify SA_SIGINFO for Linux, and handle */
2684 /* the different architectures more uniformly. */
2685 # if defined(IRIX5) || defined(LINUX) && !defined(X86_64) \
2686 || defined(OSF1) || defined(HURD)
2687 act
.sa_flags
= SA_RESTART
;
2688 act
.sa_handler
= (SIG_PF
)GC_write_fault_handler
;
2690 act
.sa_flags
= SA_RESTART
| SA_SIGINFO
;
2691 act
.sa_sigaction
= GC_write_fault_handler
;
2693 (void)sigemptyset(&act
.sa_mask
);
2695 /* Arrange to postpone SIG_SUSPEND while we're in a write fault */
2696 /* handler. This effectively makes the handler atomic w.r.t. */
2697 /* stopping the world for GC. */
2698 (void)sigaddset(&act
.sa_mask
, SIG_SUSPEND
);
2699 # endif /* SIG_SUSPEND */
2702 GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2704 GC_dirty_maintained
= TRUE
;
2705 if (GC_page_size
% HBLKSIZE
!= 0) {
2706 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
2707 ABORT("Page size not multiple of HBLKSIZE");
2709 # if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2710 GC_old_bus_handler
= signal(SIGBUS
, GC_write_fault_handler
);
2711 if (GC_old_bus_handler
== SIG_IGN
) {
2712 GC_err_printf0("Previously ignored bus error!?");
2713 GC_old_bus_handler
= SIG_DFL
;
2715 if (GC_old_bus_handler
!= SIG_DFL
) {
2717 GC_err_printf0("Replaced other SIGBUS handler\n");
2721 # if defined(SUNOS4)
2722 GC_old_segv_handler
= signal(SIGSEGV
, (SIG_PF
)GC_write_fault_handler
);
2723 if (GC_old_segv_handler
== SIG_IGN
) {
2724 GC_err_printf0("Previously ignored segmentation violation!?");
2725 GC_old_segv_handler
= SIG_DFL
;
2727 if (GC_old_segv_handler
!= SIG_DFL
) {
2729 GC_err_printf0("Replaced other SIGSEGV handler\n");
2733 # if (defined(SUNOS5SIGS) && !defined(FREEBSD)) || defined(IRIX5) \
2734 || defined(LINUX) || defined(OSF1) || defined(HURD)
2735 /* SUNOS5SIGS includes HPUX */
2736 # if defined(GC_IRIX_THREADS)
2737 sigaction(SIGSEGV
, 0, &oldact
);
2738 sigaction(SIGSEGV
, &act
, 0);
2741 int res
= sigaction(SIGSEGV
, &act
, &oldact
);
2742 if (res
!= 0) ABORT("Sigaction failed");
2745 # if defined(_sigargs) || defined(HURD) || !defined(SA_SIGINFO)
2746 /* This is Irix 5.x, not 6.x. Irix 5.x does not have */
2748 GC_old_segv_handler
= oldact
.sa_handler
;
2749 # else /* Irix 6.x or SUNOS5SIGS or LINUX */
2750 if (oldact
.sa_flags
& SA_SIGINFO
) {
2751 GC_old_segv_handler
= (SIG_PF
)(oldact
.sa_sigaction
);
2753 GC_old_segv_handler
= oldact
.sa_handler
;
2756 if (GC_old_segv_handler
== SIG_IGN
) {
2757 GC_err_printf0("Previously ignored segmentation violation!?");
2758 GC_old_segv_handler
= SIG_DFL
;
2760 if (GC_old_segv_handler
!= SIG_DFL
) {
2762 GC_err_printf0("Replaced other SIGSEGV handler\n");
2765 # endif /* (SUNOS5SIGS && !FREEBSD) || IRIX5 || LINUX || OSF1 || HURD */
2766 # if defined(HPUX) || defined(LINUX) || defined(HURD) \
2767 || (defined(FREEBSD) && defined(SUNOS5SIGS))
2768 sigaction(SIGBUS
, &act
, &oldact
);
2769 GC_old_bus_handler
= oldact
.sa_handler
;
2770 if (GC_old_bus_handler
== SIG_IGN
) {
2771 GC_err_printf0("Previously ignored bus error!?");
2772 GC_old_bus_handler
= SIG_DFL
;
2774 if (GC_old_bus_handler
!= SIG_DFL
) {
2776 GC_err_printf0("Replaced other SIGBUS handler\n");
2779 # endif /* HPUX || LINUX || HURD || (FREEBSD && SUNOS5SIGS) */
2780 # if defined(MSWIN32)
2781 GC_old_segv_handler
= SetUnhandledExceptionFilter(GC_write_fault_handler
);
2782 if (GC_old_segv_handler
!= NULL
) {
2784 GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
2787 GC_old_segv_handler
= SIG_DFL
;
2791 #endif /* !DARWIN */
2793 int GC_incremental_protection_needs()
2795 if (GC_page_size
== HBLKSIZE
) {
2796 return GC_PROTECTS_POINTER_HEAP
;
2798 return GC_PROTECTS_POINTER_HEAP
| GC_PROTECTS_PTRFREE_HEAP
;
2802 #define HAVE_INCREMENTAL_PROTECTION_NEEDS
2804 #define IS_PTRFREE(hhdr) ((hhdr)->hb_descr == 0)
2806 #define PAGE_ALIGNED(x) !((word)(x) & (GC_page_size - 1))
2807 void GC_protect_heap()
2811 struct hblk
* current
;
2812 struct hblk
* current_start
; /* Start of block to be protected. */
2813 struct hblk
* limit
;
2815 GC_bool protect_all
=
2816 (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP
));
2817 for (i
= 0; i
< GC_n_heap_sects
; i
++) {
2818 start
= GC_heap_sects
[i
].hs_start
;
2819 len
= GC_heap_sects
[i
].hs_bytes
;
2821 PROTECT(start
, len
);
2823 GC_ASSERT(PAGE_ALIGNED(len
))
2824 GC_ASSERT(PAGE_ALIGNED(start
))
2825 current_start
= current
= (struct hblk
*)start
;
2826 limit
= (struct hblk
*)(start
+ len
);
2827 while (current
< limit
) {
2832 GC_ASSERT(PAGE_ALIGNED(current
));
2833 GET_HDR(current
, hhdr
);
2834 if (IS_FORWARDING_ADDR_OR_NIL(hhdr
)) {
2835 /* This can happen only if we're at the beginning of a */
2836 /* heap segment, and a block spans heap segments. */
2837 /* We will handle that block as part of the preceding */
2839 GC_ASSERT(current_start
== current
);
2840 current_start
= ++current
;
2843 if (HBLK_IS_FREE(hhdr
)) {
2844 GC_ASSERT(PAGE_ALIGNED(hhdr
-> hb_sz
));
2845 nhblks
= divHBLKSZ(hhdr
-> hb_sz
);
2846 is_ptrfree
= TRUE
; /* dirty on alloc */
2848 nhblks
= OBJ_SZ_TO_BLOCKS(hhdr
-> hb_sz
);
2849 is_ptrfree
= IS_PTRFREE(hhdr
);
2852 if (current_start
< current
) {
2853 PROTECT(current_start
, (ptr_t
)current
- (ptr_t
)current_start
);
2855 current_start
= (current
+= nhblks
);
2860 if (current_start
< current
) {
2861 PROTECT(current_start
, (ptr_t
)current
- (ptr_t
)current_start
);
2867 /* We assume that either the world is stopped or its OK to lose dirty */
2868 /* bits while this is happenning (as in GC_enable_incremental). */
2869 void GC_read_dirty()
2871 BCOPY((word
*)GC_dirty_pages
, GC_grungy_pages
,
2872 (sizeof GC_dirty_pages
));
2873 BZERO((word
*)GC_dirty_pages
, (sizeof GC_dirty_pages
));
2877 GC_bool
GC_page_was_dirty(h
)
2880 register word index
= PHT_HASH(h
);
2882 return(HDR(h
) == 0 || get_pht_entry_from_index(GC_grungy_pages
, index
));
2886 * Acquiring the allocation lock here is dangerous, since this
2887 * can be called from within GC_call_with_alloc_lock, and the cord
2888 * package does so. On systems that allow nested lock acquisition, this
2890 * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
2893 static GC_bool syscall_acquired_lock
= FALSE
; /* Protected by GC lock. */
2895 void GC_begin_syscall()
2897 if (!I_HOLD_LOCK()) {
2899 syscall_acquired_lock
= TRUE
;
2903 void GC_end_syscall()
2905 if (syscall_acquired_lock
) {
2906 syscall_acquired_lock
= FALSE
;
2911 void GC_unprotect_range(addr
, len
)
2915 struct hblk
* start_block
;
2916 struct hblk
* end_block
;
2917 register struct hblk
*h
;
2920 if (!GC_dirty_maintained
) return;
2921 obj_start
= GC_base(addr
);
2922 if (obj_start
== 0) return;
2923 if (GC_base(addr
+ len
- 1) != obj_start
) {
2924 ABORT("GC_unprotect_range(range bigger than object)");
2926 start_block
= (struct hblk
*)((word
)addr
& ~(GC_page_size
- 1));
2927 end_block
= (struct hblk
*)((word
)(addr
+ len
- 1) & ~(GC_page_size
- 1));
2928 end_block
+= GC_page_size
/HBLKSIZE
- 1;
2929 for (h
= start_block
; h
<= end_block
; h
++) {
2930 register word index
= PHT_HASH(h
);
2932 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
2934 UNPROTECT(start_block
,
2935 ((ptr_t
)end_block
- (ptr_t
)start_block
) + HBLKSIZE
);
2940 /* We no longer wrap read by default, since that was causing too many */
2941 /* problems. It is preferred that the client instead avoids writing */
2942 /* to the write-protected heap with a system call. */
2943 /* This still serves as sample code if you do want to wrap system calls.*/
2945 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(GC_USE_LD_WRAP)
2946 /* Replacement for UNIX system call. */
2947 /* Other calls that write to the heap should be handled similarly. */
2948 /* Note that this doesn't work well for blocking reads: It will hold */
2949 /* the allocation lock for the entire duration of the call. Multithreaded */
2950 /* clients should really ensure that it won't block, either by setting */
2951 /* the descriptor nonblocking, or by calling select or poll first, to */
2952 /* make sure that input is available. */
2953 /* Another, preferred alternative is to ensure that system calls never */
2954 /* write to the protected heap (see above). */
2955 # if defined(__STDC__) && !defined(SUNOS4)
2956 # include <unistd.h>
2957 # include <sys/uio.h>
2958 ssize_t
read(int fd
, void *buf
, size_t nbyte
)
2961 int read(fd
, buf
, nbyte
)
2963 int GC_read(fd
, buf
, nbyte
)
2973 GC_unprotect_range(buf
, (word
)nbyte
);
2974 # if defined(IRIX5) || defined(GC_LINUX_THREADS)
2975 /* Indirect system call may not always be easily available. */
2976 /* We could call _read, but that would interfere with the */
2977 /* libpthread interception of read. */
2978 /* On Linux, we have to be careful with the linuxthreads */
2979 /* read interception. */
2984 iov
.iov_len
= nbyte
;
2985 result
= readv(fd
, &iov
, 1);
2989 result
= __read(fd
, buf
, nbyte
);
2991 /* The two zero args at the end of this list are because one
2992 IA-64 syscall() implementation actually requires six args
2993 to be passed, even though they aren't always used. */
2994 result
= syscall(SYS_read
, fd
, buf
, nbyte
, 0, 0);
3000 #endif /* !MSWIN32 && !MSWINCE && !GC_LINUX_THREADS */
3002 #if defined(GC_USE_LD_WRAP) && !defined(THREADS)
3003 /* We use the GNU ld call wrapping facility. */
3004 /* This requires that the linker be invoked with "--wrap read". */
3005 /* This can be done by passing -Wl,"--wrap read" to gcc. */
3006 /* I'm not sure that this actually wraps whatever version of read */
3007 /* is called by stdio. That code also mentions __read. */
3008 # include <unistd.h>
3009 ssize_t
__wrap_read(int fd
, void *buf
, size_t nbyte
)
3014 GC_unprotect_range(buf
, (word
)nbyte
);
3015 result
= __real_read(fd
, buf
, nbyte
);
3020 /* We should probably also do this for __read, or whatever stdio */
3021 /* actually calls. */
3027 GC_bool
GC_page_was_ever_dirty(h
)
3033 /* Reset the n pages starting at h to "was never dirty" status. */
3035 void GC_is_fresh(h
, n
)
3041 # endif /* MPROTECT_VDB */
3046 * See DEFAULT_VDB for interface descriptions.
3050 * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
3051 * from which we can read page modified bits. This facility is far from
3052 * optimal (e.g. we would like to get the info for only some of the
3053 * address space), but it avoids intercepting system calls.
3057 #include <sys/types.h>
3058 #include <sys/signal.h>
3059 #include <sys/fault.h>
3060 #include <sys/syscall.h>
3061 #include <sys/procfs.h>
3062 #include <sys/stat.h>
3064 #define INITIAL_BUF_SZ 16384
3065 word GC_proc_buf_size
= INITIAL_BUF_SZ
;
3068 #ifdef GC_SOLARIS_THREADS
3069 /* We don't have exact sp values for threads. So we count on */
3070 /* occasionally declaring stack pages to be fresh. Thus we */
3071 /* need a real implementation of GC_is_fresh. We can't clear */
3072 /* entries in GC_written_pages, since that would declare all */
3073 /* pages with the given hash address to be fresh. */
3074 # define MAX_FRESH_PAGES 8*1024 /* Must be power of 2 */
3075 struct hblk
** GC_fresh_pages
; /* A direct mapped cache. */
3076 /* Collisions are dropped. */
3078 # define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
3079 # define ADD_FRESH_PAGE(h) \
3080 GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
3081 # define PAGE_IS_FRESH(h) \
3082 (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
3085 /* Add all pages in pht2 to pht1 */
3086 void GC_or_pages(pht1
, pht2
)
3087 page_hash_table pht1
, pht2
;
3091 for (i
= 0; i
< PHT_SIZE
; i
++) pht1
[i
] |= pht2
[i
];
3096 void GC_dirty_init()
3101 GC_dirty_maintained
= TRUE
;
3102 if (GC_words_allocd
!= 0 || GC_words_allocd_before_gc
!= 0) {
3105 for (i
= 0; i
< PHT_SIZE
; i
++) GC_written_pages
[i
] = (word
)(-1);
3107 GC_printf1("Allocated words:%lu:all pages may have been written\n",
3109 (GC_words_allocd
+ GC_words_allocd_before_gc
));
3112 sprintf(buf
, "/proc/%d", getpid());
3113 fd
= open(buf
, O_RDONLY
);
3115 ABORT("/proc open failed");
3117 GC_proc_fd
= syscall(SYS_ioctl
, fd
, PIOCOPENPD
, 0);
3119 syscall(SYS_fcntl
, GC_proc_fd
, F_SETFD
, FD_CLOEXEC
);
3120 if (GC_proc_fd
< 0) {
3121 ABORT("/proc ioctl failed");
3123 GC_proc_buf
= GC_scratch_alloc(GC_proc_buf_size
);
3124 # ifdef GC_SOLARIS_THREADS
3125 GC_fresh_pages
= (struct hblk
**)
3126 GC_scratch_alloc(MAX_FRESH_PAGES
* sizeof (struct hblk
*));
3127 if (GC_fresh_pages
== 0) {
3128 GC_err_printf0("No space for fresh pages\n");
3131 BZERO(GC_fresh_pages
, MAX_FRESH_PAGES
* sizeof (struct hblk
*));
3135 /* Ignore write hints. They don't help us here. */
3137 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
3144 #ifdef GC_SOLARIS_THREADS
3145 # define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
3147 # define READ(fd,buf,nbytes) read(fd, buf, nbytes)
3150 void GC_read_dirty()
3152 unsigned long ps
, np
;
3155 struct prasmap
* map
;
3157 ptr_t current_addr
, limit
;
3161 BZERO(GC_grungy_pages
, (sizeof GC_grungy_pages
));
3164 if (READ(GC_proc_fd
, bufp
, GC_proc_buf_size
) <= 0) {
3166 GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
3170 /* Retry with larger buffer. */
3171 word new_size
= 2 * GC_proc_buf_size
;
3172 char * new_buf
= GC_scratch_alloc(new_size
);
3175 GC_proc_buf
= bufp
= new_buf
;
3176 GC_proc_buf_size
= new_size
;
3178 if (READ(GC_proc_fd
, bufp
, GC_proc_buf_size
) <= 0) {
3179 WARN("Insufficient space for /proc read\n", 0);
3181 memset(GC_grungy_pages
, 0xff, sizeof (page_hash_table
));
3182 memset(GC_written_pages
, 0xff, sizeof(page_hash_table
));
3183 # ifdef GC_SOLARIS_THREADS
3184 BZERO(GC_fresh_pages
,
3185 MAX_FRESH_PAGES
* sizeof (struct hblk
*));
3191 /* Copy dirty bits into GC_grungy_pages */
3192 nmaps
= ((struct prpageheader
*)bufp
) -> pr_nmap
;
3193 /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
3194 nmaps, PG_REFERENCED, PG_MODIFIED); */
3195 bufp
= bufp
+ sizeof(struct prpageheader
);
3196 for (i
= 0; i
< nmaps
; i
++) {
3197 map
= (struct prasmap
*)bufp
;
3198 vaddr
= (ptr_t
)(map
-> pr_vaddr
);
3199 ps
= map
-> pr_pagesize
;
3200 np
= map
-> pr_npage
;
3201 /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
3202 limit
= vaddr
+ ps
* np
;
3203 bufp
+= sizeof (struct prasmap
);
3204 for (current_addr
= vaddr
;
3205 current_addr
< limit
; current_addr
+= ps
){
3206 if ((*bufp
++) & PG_MODIFIED
) {
3207 register struct hblk
* h
= (struct hblk
*) current_addr
;
3209 while ((ptr_t
)h
< current_addr
+ ps
) {
3210 register word index
= PHT_HASH(h
);
3212 set_pht_entry_from_index(GC_grungy_pages
, index
);
3213 # ifdef GC_SOLARIS_THREADS
3215 register int slot
= FRESH_PAGE_SLOT(h
);
3217 if (GC_fresh_pages
[slot
] == h
) {
3218 GC_fresh_pages
[slot
] = 0;
3226 bufp
+= sizeof(long) - 1;
3227 bufp
= (char *)((unsigned long)bufp
& ~(sizeof(long)-1));
3229 /* Update GC_written_pages. */
3230 GC_or_pages(GC_written_pages
, GC_grungy_pages
);
3231 # ifdef GC_SOLARIS_THREADS
3232 /* Make sure that old stacks are considered completely clean */
3233 /* unless written again. */
3234 GC_old_stacks_are_fresh();
3240 GC_bool
GC_page_was_dirty(h
)
3243 register word index
= PHT_HASH(h
);
3244 register GC_bool result
;
3246 result
= get_pht_entry_from_index(GC_grungy_pages
, index
);
3247 # ifdef GC_SOLARIS_THREADS
3248 if (result
&& PAGE_IS_FRESH(h
)) result
= FALSE
;
3249 /* This happens only if page was declared fresh since */
3250 /* the read_dirty call, e.g. because it's in an unused */
3251 /* thread stack. It's OK to treat it as clean, in */
3252 /* that case. And it's consistent with */
3253 /* GC_page_was_ever_dirty. */
3258 GC_bool
GC_page_was_ever_dirty(h
)
3261 register word index
= PHT_HASH(h
);
3262 register GC_bool result
;
3264 result
= get_pht_entry_from_index(GC_written_pages
, index
);
3265 # ifdef GC_SOLARIS_THREADS
3266 if (result
&& PAGE_IS_FRESH(h
)) result
= FALSE
;
3271 /* Caller holds allocation lock. */
3272 void GC_is_fresh(h
, n
)
3277 register word index
;
3279 # ifdef GC_SOLARIS_THREADS
3282 if (GC_fresh_pages
!= 0) {
3283 for (i
= 0; i
< n
; i
++) {
3284 ADD_FRESH_PAGE(h
+ i
);
3290 # endif /* PROC_VDB */
3295 # include "vd/PCR_VD.h"
3297 # define NPAGES (32*1024) /* 128 MB */
3299 PCR_VD_DB GC_grungy_bits
[NPAGES
];
3301 ptr_t GC_vd_base
; /* Address corresponding to GC_grungy_bits[0] */
3302 /* HBLKSIZE aligned. */
3304 void GC_dirty_init()
3306 GC_dirty_maintained
= TRUE
;
3307 /* For the time being, we assume the heap generally grows up */
3308 GC_vd_base
= GC_heap_sects
[0].hs_start
;
3309 if (GC_vd_base
== 0) {
3310 ABORT("Bad initial heap segment");
3312 if (PCR_VD_Start(HBLKSIZE
, GC_vd_base
, NPAGES
*HBLKSIZE
)
3314 ABORT("dirty bit initialization failed");
3318 void GC_read_dirty()
3320 /* lazily enable dirty bits on newly added heap sects */
3322 static int onhs
= 0;
3323 int nhs
= GC_n_heap_sects
;
3324 for( ; onhs
< nhs
; onhs
++ ) {
3325 PCR_VD_WriteProtectEnable(
3326 GC_heap_sects
[onhs
].hs_start
,
3327 GC_heap_sects
[onhs
].hs_bytes
);
3332 if (PCR_VD_Clear(GC_vd_base
, NPAGES
*HBLKSIZE
, GC_grungy_bits
)
3334 ABORT("dirty bit read failed");
3338 GC_bool
GC_page_was_dirty(h
)
3341 if((ptr_t
)h
< GC_vd_base
|| (ptr_t
)h
>= GC_vd_base
+ NPAGES
*HBLKSIZE
) {
3344 return(GC_grungy_bits
[h
- (struct hblk
*)GC_vd_base
] & PCR_VD_DB_dirtyBit
);
3348 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
3353 PCR_VD_WriteProtectDisable(h
, nblocks
*HBLKSIZE
);
3354 PCR_VD_WriteProtectEnable(h
, nblocks
*HBLKSIZE
);
3357 # endif /* PCR_VDB */
3359 #if defined(MPROTECT_VDB) && defined(DARWIN)
3360 /* The following sources were used as a *reference* for this exception handling
3362 1. Apple's mach/xnu documentation
3363 2. Timothy J. Wood's "Mach Exception Handlers 101" post to the
3364 omnigroup's macosx-dev list.
3365 www.omnigroup.com/mailman/archive/macosx-dev/2000-June/002030.html
3366 3. macosx-nat.c from Apple's GDB source code.
3369 /* The bug that caused all this trouble should now be fixed. This should
3370 eventually be removed if all goes well. */
3371 /* define BROKEN_EXCEPTION_HANDLING */
3373 #include <mach/mach.h>
3374 #include <mach/mach_error.h>
3375 #include <mach/thread_status.h>
3376 #include <mach/exception.h>
3377 #include <mach/task.h>
3378 #include <pthread.h>
3380 /* These are not defined in any header, although they are documented */
3381 extern boolean_t
exc_server(mach_msg_header_t
*,mach_msg_header_t
*);
3382 extern kern_return_t
exception_raise(
3383 mach_port_t
,mach_port_t
,mach_port_t
,
3384 exception_type_t
,exception_data_t
,mach_msg_type_number_t
);
3385 extern kern_return_t
exception_raise_state(
3386 mach_port_t
,mach_port_t
,mach_port_t
,
3387 exception_type_t
,exception_data_t
,mach_msg_type_number_t
,
3388 thread_state_flavor_t
*,thread_state_t
,mach_msg_type_number_t
,
3389 thread_state_t
,mach_msg_type_number_t
*);
3390 extern kern_return_t
exception_raise_state_identity(
3391 mach_port_t
,mach_port_t
,mach_port_t
,
3392 exception_type_t
,exception_data_t
,mach_msg_type_number_t
,
3393 thread_state_flavor_t
*,thread_state_t
,mach_msg_type_number_t
,
3394 thread_state_t
,mach_msg_type_number_t
*);
3397 #define MAX_EXCEPTION_PORTS 16
3400 mach_msg_type_number_t count
;
3401 exception_mask_t masks
[MAX_EXCEPTION_PORTS
];
3402 exception_handler_t ports
[MAX_EXCEPTION_PORTS
];
3403 exception_behavior_t behaviors
[MAX_EXCEPTION_PORTS
];
3404 thread_state_flavor_t flavors
[MAX_EXCEPTION_PORTS
];
3408 mach_port_t exception
;
3409 #if defined(THREADS)
3415 mach_msg_header_t head
;
3419 GC_MP_NORMAL
, GC_MP_DISCARDING
, GC_MP_STOPPED
3420 } GC_mprotect_state_t
;
3422 /* FIXME: 1 and 2 seem to be safe to use in the msgh_id field,
3423 but it isn't documented. Use the source and see if they
3428 /* These values are only used on the reply port */
3431 #if defined(THREADS)
3433 GC_mprotect_state_t GC_mprotect_state
;
3435 /* The following should ONLY be called when the world is stopped */
3436 static void GC_mprotect_thread_notify(mach_msg_id_t id
) {
3439 mach_msg_trailer_t trailer
;
3441 mach_msg_return_t r
;
3443 buf
.msg
.head
.msgh_bits
=
3444 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
,0);
3445 buf
.msg
.head
.msgh_size
= sizeof(buf
.msg
);
3446 buf
.msg
.head
.msgh_remote_port
= GC_ports
.exception
;
3447 buf
.msg
.head
.msgh_local_port
= MACH_PORT_NULL
;
3448 buf
.msg
.head
.msgh_id
= id
;
3452 MACH_SEND_MSG
|MACH_RCV_MSG
|MACH_RCV_LARGE
,
3456 MACH_MSG_TIMEOUT_NONE
,
3458 if(r
!= MACH_MSG_SUCCESS
)
3459 ABORT("mach_msg failed in GC_mprotect_thread_notify");
3460 if(buf
.msg
.head
.msgh_id
!= ID_ACK
)
3461 ABORT("invalid ack in GC_mprotect_thread_notify");
3464 /* Should only be called by the mprotect thread */
3465 static void GC_mprotect_thread_reply() {
3467 mach_msg_return_t r
;
3469 msg
.head
.msgh_bits
=
3470 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
,0);
3471 msg
.head
.msgh_size
= sizeof(msg
);
3472 msg
.head
.msgh_remote_port
= GC_ports
.reply
;
3473 msg
.head
.msgh_local_port
= MACH_PORT_NULL
;
3474 msg
.head
.msgh_id
= ID_ACK
;
3482 MACH_MSG_TIMEOUT_NONE
,
3484 if(r
!= MACH_MSG_SUCCESS
)
3485 ABORT("mach_msg failed in GC_mprotect_thread_reply");
3488 void GC_mprotect_stop() {
3489 GC_mprotect_thread_notify(ID_STOP
);
3491 void GC_mprotect_resume() {
3492 GC_mprotect_thread_notify(ID_RESUME
);
3495 #else /* !THREADS */
3496 /* The compiler should optimize away any GC_mprotect_state computations */
3497 #define GC_mprotect_state GC_MP_NORMAL
3500 static void *GC_mprotect_thread(void *arg
) {
3501 mach_msg_return_t r
;
3502 /* These two structures contain some private kernel data. We don't need to
3503 access any of it so we don't bother defining a proper struct. The
3504 correct definitions are in the xnu source code. */
3506 mach_msg_header_t head
;
3510 mach_msg_header_t head
;
3511 mach_msg_body_t msgh_body
;
3517 GC_darwin_register_mach_handler_thread(mach_thread_self());
3522 MACH_RCV_MSG
|MACH_RCV_LARGE
|
3523 (GC_mprotect_state
== GC_MP_DISCARDING
? MACH_RCV_TIMEOUT
: 0),
3527 GC_mprotect_state
== GC_MP_DISCARDING
? 0 : MACH_MSG_TIMEOUT_NONE
,
3530 id
= r
== MACH_MSG_SUCCESS
? msg
.head
.msgh_id
: -1;
3532 #if defined(THREADS)
3533 if(GC_mprotect_state
== GC_MP_DISCARDING
) {
3534 if(r
== MACH_RCV_TIMED_OUT
) {
3535 GC_mprotect_state
= GC_MP_STOPPED
;
3536 GC_mprotect_thread_reply();
3539 if(r
== MACH_MSG_SUCCESS
&& (id
== ID_STOP
|| id
== ID_RESUME
))
3540 ABORT("out of order mprotect thread request");
3544 if(r
!= MACH_MSG_SUCCESS
) {
3545 GC_err_printf2("mach_msg failed with %d %s\n",
3546 (int)r
,mach_error_string(r
));
3547 ABORT("mach_msg failed");
3551 #if defined(THREADS)
3553 if(GC_mprotect_state
!= GC_MP_NORMAL
)
3554 ABORT("Called mprotect_stop when state wasn't normal");
3555 GC_mprotect_state
= GC_MP_DISCARDING
;
3558 if(GC_mprotect_state
!= GC_MP_STOPPED
)
3559 ABORT("Called mprotect_resume when state wasn't stopped");
3560 GC_mprotect_state
= GC_MP_NORMAL
;
3561 GC_mprotect_thread_reply();
3563 #endif /* THREADS */
3565 /* Handle the message (calls catch_exception_raise) */
3566 if(!exc_server(&msg
.head
,&reply
.head
))
3567 ABORT("exc_server failed");
3568 /* Send the reply */
3572 reply
.head
.msgh_size
,
3575 MACH_MSG_TIMEOUT_NONE
,
3577 if(r
!= MACH_MSG_SUCCESS
) {
3578 /* This will fail if the thread dies, but the thread shouldn't
3580 #ifdef BROKEN_EXCEPTION_HANDLING
3582 "mach_msg failed with %d %s while sending exc reply\n",
3583 (int)r
,mach_error_string(r
));
3585 ABORT("mach_msg failed while sending exception reply");
3594 /* All this SIGBUS code shouldn't be necessary. All protection faults should
3595 be going throught the mach exception handler. However, it seems a SIGBUS is
3596 occasionally sent for some unknown reason. Even more odd, it seems to be
3597 meaningless and safe to ignore. */
3598 #ifdef BROKEN_EXCEPTION_HANDLING
3600 typedef void (* SIG_PF
)();
3601 static SIG_PF GC_old_bus_handler
;
3603 /* Updates to this aren't atomic, but the SIGBUSs seem pretty rare.
3604 Even if this doesn't get updated property, it isn't really a problem */
3605 static int GC_sigbus_count
;
3607 static void GC_darwin_sigbus(int num
,siginfo_t
*sip
,void *context
) {
3608 if(num
!= SIGBUS
) ABORT("Got a non-sigbus signal in the sigbus handler");
3610 /* Ugh... some seem safe to ignore, but too many in a row probably means
3611 trouble. GC_sigbus_count is reset for each mach exception that is
3613 if(GC_sigbus_count
>= 8) {
3614 ABORT("Got more than 8 SIGBUSs in a row!");
3617 GC_err_printf0("GC: WARNING: Ignoring SIGBUS.\n");
3620 #endif /* BROKEN_EXCEPTION_HANDLING */
3622 void GC_dirty_init() {
3626 pthread_attr_t attr
;
3627 exception_mask_t mask
;
3630 GC_printf0("Inititalizing mach/darwin mprotect virtual dirty bit "
3631 "implementation\n");
3633 # ifdef BROKEN_EXCEPTION_HANDLING
3634 GC_err_printf0("GC: WARNING: Enabling workarounds for various darwin "
3635 "exception handling bugs.\n");
3637 GC_dirty_maintained
= TRUE
;
3638 if (GC_page_size
% HBLKSIZE
!= 0) {
3639 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
3640 ABORT("Page size not multiple of HBLKSIZE");
3643 GC_task_self
= me
= mach_task_self();
3645 r
= mach_port_allocate(me
,MACH_PORT_RIGHT_RECEIVE
,&GC_ports
.exception
);
3646 if(r
!= KERN_SUCCESS
) ABORT("mach_port_allocate failed (exception port)");
3648 r
= mach_port_insert_right(me
,GC_ports
.exception
,GC_ports
.exception
,
3649 MACH_MSG_TYPE_MAKE_SEND
);
3650 if(r
!= KERN_SUCCESS
)
3651 ABORT("mach_port_insert_right failed (exception port)");
3653 #if defined(THREADS)
3654 r
= mach_port_allocate(me
,MACH_PORT_RIGHT_RECEIVE
,&GC_ports
.reply
);
3655 if(r
!= KERN_SUCCESS
) ABORT("mach_port_allocate failed (reply port)");
3658 /* The exceptions we want to catch */
3659 mask
= EXC_MASK_BAD_ACCESS
;
3661 r
= task_get_exception_ports(
3664 GC_old_exc_ports
.masks
,
3665 &GC_old_exc_ports
.count
,
3666 GC_old_exc_ports
.ports
,
3667 GC_old_exc_ports
.behaviors
,
3668 GC_old_exc_ports
.flavors
3670 if(r
!= KERN_SUCCESS
) ABORT("task_get_exception_ports failed");
3672 r
= task_set_exception_ports(
3677 MACHINE_THREAD_STATE
3679 if(r
!= KERN_SUCCESS
) ABORT("task_set_exception_ports failed");
3681 if(pthread_attr_init(&attr
) != 0) ABORT("pthread_attr_init failed");
3682 if(pthread_attr_setdetachstate(&attr
,PTHREAD_CREATE_DETACHED
) != 0)
3683 ABORT("pthread_attr_setdetachedstate failed");
3685 # undef pthread_create
3686 /* This will call the real pthread function, not our wrapper */
3687 if(pthread_create(&thread
,&attr
,GC_mprotect_thread
,NULL
) != 0)
3688 ABORT("pthread_create failed");
3689 pthread_attr_destroy(&attr
);
3691 /* Setup the sigbus handler for ignoring the meaningless SIGBUSs */
3692 #ifdef BROKEN_EXCEPTION_HANDLING
3694 struct sigaction sa
, oldsa
;
3695 sa
.sa_handler
= (SIG_PF
)GC_darwin_sigbus
;
3696 sigemptyset(&sa
.sa_mask
);
3697 sa
.sa_flags
= SA_RESTART
|SA_SIGINFO
;
3698 if(sigaction(SIGBUS
,&sa
,&oldsa
) < 0) ABORT("sigaction");
3699 GC_old_bus_handler
= (SIG_PF
)oldsa
.sa_handler
;
3700 if (GC_old_bus_handler
!= SIG_DFL
) {
3702 GC_err_printf0("Replaced other SIGBUS handler\n");
3706 #endif /* BROKEN_EXCEPTION_HANDLING */
3709 /* The source code for Apple's GDB was used as a reference for the exception
3710 forwarding code. This code is similar to be GDB code only because there is
3711 only one way to do it. */
3712 static kern_return_t
GC_forward_exception(
3715 exception_type_t exception
,
3716 exception_data_t data
,
3717 mach_msg_type_number_t data_count
3722 exception_behavior_t behavior
;
3723 thread_state_flavor_t flavor
;
3725 thread_state_data_t thread_state
;
3726 mach_msg_type_number_t thread_state_count
= THREAD_STATE_MAX
;
3728 for(i
=0;i
<GC_old_exc_ports
.count
;i
++)
3729 if(GC_old_exc_ports
.masks
[i
] & (1 << exception
))
3731 if(i
==GC_old_exc_ports
.count
) ABORT("No handler for exception!");
3733 port
= GC_old_exc_ports
.ports
[i
];
3734 behavior
= GC_old_exc_ports
.behaviors
[i
];
3735 flavor
= GC_old_exc_ports
.flavors
[i
];
3737 if(behavior
!= EXCEPTION_DEFAULT
) {
3738 r
= thread_get_state(thread
,flavor
,thread_state
,&thread_state_count
);
3739 if(r
!= KERN_SUCCESS
)
3740 ABORT("thread_get_state failed in forward_exception");
3744 case EXCEPTION_DEFAULT
:
3745 r
= exception_raise(port
,thread
,task
,exception
,data
,data_count
);
3747 case EXCEPTION_STATE
:
3748 r
= exception_raise_state(port
,thread
,task
,exception
,data
,
3749 data_count
,&flavor
,thread_state
,thread_state_count
,
3750 thread_state
,&thread_state_count
);
3752 case EXCEPTION_STATE_IDENTITY
:
3753 r
= exception_raise_state_identity(port
,thread
,task
,exception
,data
,
3754 data_count
,&flavor
,thread_state
,thread_state_count
,
3755 thread_state
,&thread_state_count
);
3758 r
= KERN_FAILURE
; /* make gcc happy */
3759 ABORT("forward_exception: unknown behavior");
3763 if(behavior
!= EXCEPTION_DEFAULT
) {
3764 r
= thread_set_state(thread
,flavor
,thread_state
,thread_state_count
);
3765 if(r
!= KERN_SUCCESS
)
3766 ABORT("thread_set_state failed in forward_exception");
3772 #define FWD() GC_forward_exception(thread,task,exception,code,code_count)
3774 /* This violates the namespace rules but there isn't anything that can be done
3775 about it. The exception handling stuff is hard coded to call this */
3777 catch_exception_raise(
3778 mach_port_t exception_port
,mach_port_t thread
,mach_port_t task
,
3779 exception_type_t exception
,exception_data_t code
,
3780 mach_msg_type_number_t code_count
3787 thread_state_flavor_t flavor
= PPC_EXCEPTION_STATE
;
3788 mach_msg_type_number_t exc_state_count
= PPC_EXCEPTION_STATE_COUNT
;
3789 ppc_exception_state_t exc_state
;
3791 # error FIXME for non-ppc darwin
3795 if(exception
!= EXC_BAD_ACCESS
|| code
[0] != KERN_PROTECTION_FAILURE
) {
3796 #ifdef DEBUG_EXCEPTION_HANDLING
3797 /* We aren't interested, pass it on to the old handler */
3798 GC_printf3("Exception: 0x%x Code: 0x%x 0x%x in catch....\n",
3800 code_count
> 0 ? code
[0] : -1,
3801 code_count
> 1 ? code
[1] : -1);
3806 r
= thread_get_state(thread
,flavor
,
3807 (natural_t
*)&exc_state
,&exc_state_count
);
3808 if(r
!= KERN_SUCCESS
) {
3809 /* The thread is supposed to be suspended while the exception handler
3810 is called. This shouldn't fail. */
3811 #ifdef BROKEN_EXCEPTION_HANDLING
3812 GC_err_printf0("thread_get_state failed in "
3813 "catch_exception_raise\n");
3814 return KERN_SUCCESS
;
3816 ABORT("thread_get_state failed in catch_exception_raise");
3820 /* This is the address that caused the fault */
3821 addr
= (char*) exc_state
.dar
;
3823 if((HDR(addr
)) == 0) {
3824 /* Ugh... just like the SIGBUS problem above, it seems we get a bogus
3825 KERN_PROTECTION_FAILURE every once and a while. We wait till we get
3826 a bunch in a row before doing anything about it. If a "real" fault
3827 ever occurres it'll just keep faulting over and over and we'll hit
3828 the limit pretty quickly. */
3829 #ifdef BROKEN_EXCEPTION_HANDLING
3830 static char *last_fault
;
3831 static int last_fault_count
;
3833 if(addr
!= last_fault
) {
3835 last_fault_count
= 0;
3837 if(++last_fault_count
< 32) {
3838 if(last_fault_count
== 1)
3840 "GC: WARNING: Ignoring KERN_PROTECTION_FAILURE at %p\n",
3842 return KERN_SUCCESS
;
3845 GC_err_printf1("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr
);
3846 /* Can't pass it along to the signal handler because that is
3847 ignoring SIGBUS signals. We also shouldn't call ABORT here as
3848 signals don't always work too well from the exception handler. */
3849 GC_err_printf0("Aborting\n");
3851 #else /* BROKEN_EXCEPTION_HANDLING */
3852 /* Pass it along to the next exception handler
3853 (which should call SIGBUS/SIGSEGV) */
3855 #endif /* !BROKEN_EXCEPTION_HANDLING */
3858 #ifdef BROKEN_EXCEPTION_HANDLING
3859 /* Reset the number of consecutive SIGBUSs */
3860 GC_sigbus_count
= 0;
3863 if(GC_mprotect_state
== GC_MP_NORMAL
) { /* common case */
3864 h
= (struct hblk
*)((word
)addr
& ~(GC_page_size
-1));
3865 UNPROTECT(h
, GC_page_size
);
3866 for (i
= 0; i
< divHBLKSZ(GC_page_size
); i
++) {
3867 register int index
= PHT_HASH(h
+i
);
3868 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
3870 } else if(GC_mprotect_state
== GC_MP_DISCARDING
) {
3871 /* Lie to the thread for now. No sense UNPROTECT()ing the memory
3872 when we're just going to PROTECT() it again later. The thread
3873 will just fault again once it resumes */
3875 /* Shouldn't happen, i don't think */
3876 GC_printf0("KERN_PROTECTION_FAILURE while world is stopped\n");
3879 return KERN_SUCCESS
;
3883 /* These should never be called, but just in case... */
3884 kern_return_t
catch_exception_raise_state(mach_port_name_t exception_port
,
3885 int exception
, exception_data_t code
, mach_msg_type_number_t codeCnt
,
3886 int flavor
, thread_state_t old_state
, int old_stateCnt
,
3887 thread_state_t new_state
, int new_stateCnt
)
3889 ABORT("catch_exception_raise_state");
3890 return(KERN_INVALID_ARGUMENT
);
3892 kern_return_t
catch_exception_raise_state_identity(
3893 mach_port_name_t exception_port
, mach_port_t thread
, mach_port_t task
,
3894 int exception
, exception_data_t code
, mach_msg_type_number_t codeCnt
,
3895 int flavor
, thread_state_t old_state
, int old_stateCnt
,
3896 thread_state_t new_state
, int new_stateCnt
)
3898 ABORT("catch_exception_raise_state_identity");
3899 return(KERN_INVALID_ARGUMENT
);
3903 #endif /* DARWIN && MPROTECT_VDB */
3905 # ifndef HAVE_INCREMENTAL_PROTECTION_NEEDS
3906 int GC_incremental_protection_needs()
3908 return GC_PROTECTS_NONE
;
3910 # endif /* !HAVE_INCREMENTAL_PROTECTION_NEEDS */
3913 * Call stack save code for debugging.
3914 * Should probably be in mach_dep.c, but that requires reorganization.
3917 /* I suspect the following works for most X86 *nix variants, so */
3918 /* long as the frame pointer is explicitly stored. In the case of gcc, */
3919 /* compiler flags (e.g. -fomit-frame-pointer) determine whether it is. */
3920 #if defined(I386) && defined(LINUX) && defined(SAVE_CALL_CHAIN)
3921 # include <features.h>
3924 struct frame
*fr_savfp
;
3926 long fr_arg
[NARGS
]; /* All the arguments go here. */
3932 # include <features.h>
3937 struct frame
*fr_savfp
;
3946 # if defined(SUNOS4)
3947 # include <machine/frame.h>
3949 # if defined (DRSNX)
3950 # include <sys/sparc/frame.h>
3952 # if defined(OPENBSD) || defined(NETBSD)
3955 # include <sys/frame.h>
3961 --> We only know how to to get the first
6 arguments
3965 #ifdef NEED_CALLINFO
3966 /* Fill in the pc and argument information for up to NFRAMES of my */
3967 /* callers. Ignore my frame and my callers frame. */
3970 # include <unistd.h>
3973 #endif /* NEED_CALLINFO */
3975 #if defined(GC_HAVE_BUILTIN_BACKTRACE)
3976 # include <execinfo.h>
3979 #ifdef SAVE_CALL_CHAIN
3981 #if NARGS == 0 && NFRAMES % 2 == 0 /* No padding */ \
3982 && defined(GC_HAVE_BUILTIN_BACKTRACE)
3984 void GC_save_callers (info
)
3985 struct callinfo info
[NFRAMES
];
3987 void * tmp_info
[NFRAMES
+ 1];
3989 # define IGNORE_FRAMES 1
3991 /* We retrieve NFRAMES+1 pc values, but discard the first, since it */
3992 /* points to our own frame. */
3993 GC_ASSERT(sizeof(struct callinfo
) == sizeof(void *));
3994 npcs
= backtrace((void **)tmp_info
, NFRAMES
+ IGNORE_FRAMES
);
3995 BCOPY(tmp_info
+IGNORE_FRAMES
, info
, (npcs
- IGNORE_FRAMES
) * sizeof(void *));
3996 for (i
= npcs
- IGNORE_FRAMES
; i
< NFRAMES
; ++i
) info
[i
].ci_pc
= 0;
3999 #else /* No builtin backtrace; do it ourselves */
4001 #if (defined(OPENBSD) || defined(NETBSD)) && defined(SPARC)
4002 # define FR_SAVFP fr_fp
4003 # define FR_SAVPC fr_pc
4005 # define FR_SAVFP fr_savfp
4006 # define FR_SAVPC fr_savpc
4009 #if defined(SPARC) && (defined(__arch64__) || defined(__sparcv9))
4015 void GC_save_callers (info
)
4016 struct callinfo info
[NFRAMES
];
4018 struct frame
*frame
;
4022 /* We assume this is turned on only with gcc as the compiler. */
4023 asm("movl %%ebp,%0" : "=r"(frame
));
4026 frame
= (struct frame
*) GC_save_regs_in_stack ();
4027 fp
= (struct frame
*)((long) frame
-> FR_SAVFP
+ BIAS
);
4030 for (; (!(fp HOTTER_THAN frame
) && !(GC_stackbottom
HOTTER_THAN (ptr_t
)fp
)
4031 && (nframes
< NFRAMES
));
4032 fp
= (struct frame
*)((long) fp
-> FR_SAVFP
+ BIAS
), nframes
++) {
4035 info
[nframes
].ci_pc
= fp
->FR_SAVPC
;
4037 for (i
= 0; i
< NARGS
; i
++) {
4038 info
[nframes
].ci_arg
[i
] = ~(fp
->fr_arg
[i
]);
4040 # endif /* NARGS > 0 */
4042 if (nframes
< NFRAMES
) info
[nframes
].ci_pc
= 0;
4045 #endif /* No builtin backtrace */
4047 #endif /* SAVE_CALL_CHAIN */
4049 #ifdef NEED_CALLINFO
4051 /* Print info to stderr. We do NOT hold the allocation lock */
4052 void GC_print_callers (info
)
4053 struct callinfo info
[NFRAMES
];
4056 static int reentry_count
= 0;
4057 GC_bool stop
= FALSE
;
4059 /* FIXME: This should probably use a different lock, so that we */
4060 /* become callable with or without the allocation lock. */
4066 GC_err_printf0("\tCaller at allocation:\n");
4068 GC_err_printf0("\tCall chain at allocation:\n");
4070 for (i
= 0; i
< NFRAMES
&& !stop
; i
++) {
4071 if (info
[i
].ci_pc
== 0) break;
4076 GC_err_printf0("\t\targs: ");
4077 for (j
= 0; j
< NARGS
; j
++) {
4078 if (j
!= 0) GC_err_printf0(", ");
4079 GC_err_printf2("%d (0x%X)", ~(info
[i
].ci_arg
[j
]),
4080 ~(info
[i
].ci_arg
[j
]));
4082 GC_err_printf0("\n");
4085 if (reentry_count
> 1) {
4086 /* We were called during an allocation during */
4087 /* a previous GC_print_callers call; punt. */
4088 GC_err_printf1("\t\t##PC##= 0x%lx\n", info
[i
].ci_pc
);
4095 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4096 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4098 backtrace_symbols((void **)(&(info
[i
].ci_pc
)), 1);
4099 char *name
= sym_name
[0];
4103 sprintf(buf
, "##PC##= 0x%lx", info
[i
].ci_pc
);
4105 # if defined(LINUX) && !defined(SMALL_CONFIG)
4106 /* Try for a line number. */
4109 static char exe_name
[EXE_SZ
];
4111 char cmd_buf
[CMD_SZ
];
4112 # define RESULT_SZ 200
4113 static char result_buf
[RESULT_SZ
];
4116 # define PRELOAD_SZ 200
4117 char preload_buf
[PRELOAD_SZ
];
4118 static GC_bool found_exe_name
= FALSE
;
4119 static GC_bool will_fail
= FALSE
;
4121 /* Try to get it via a hairy and expensive scheme. */
4122 /* First we get the name of the executable: */
4123 if (will_fail
) goto out
;
4124 if (!found_exe_name
) {
4125 ret_code
= readlink("/proc/self/exe", exe_name
, EXE_SZ
);
4126 if (ret_code
< 0 || ret_code
>= EXE_SZ
4127 || exe_name
[0] != '/') {
4128 will_fail
= TRUE
; /* Dont try again. */
4131 exe_name
[ret_code
] = '\0';
4132 found_exe_name
= TRUE
;
4134 /* Then we use popen to start addr2line -e <exe> <addr> */
4135 /* There are faster ways to do this, but hopefully this */
4136 /* isn't time critical. */
4137 sprintf(cmd_buf
, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name
,
4138 (unsigned long)info
[i
].ci_pc
);
4139 old_preload
= getenv ("LD_PRELOAD");
4140 if (0 != old_preload
) {
4141 if (strlen (old_preload
) >= PRELOAD_SZ
) {
4145 strcpy (preload_buf
, old_preload
);
4146 unsetenv ("LD_PRELOAD");
4148 pipe
= popen(cmd_buf
, "r");
4149 if (0 != old_preload
4150 && 0 != setenv ("LD_PRELOAD", preload_buf
, 0)) {
4151 WARN("Failed to reset LD_PRELOAD\n", 0);
4154 || (result_len
= fread(result_buf
, 1, RESULT_SZ
- 1, pipe
))
4156 if (pipe
!= NULL
) pclose(pipe
);
4160 if (result_buf
[result_len
- 1] == '\n') --result_len
;
4161 result_buf
[result_len
] = 0;
4162 if (result_buf
[0] == '?'
4163 || result_buf
[result_len
-2] == ':'
4164 && result_buf
[result_len
-1] == '0') {
4168 /* Get rid of embedded newline, if any. Test for "main" */
4170 char * nl
= strchr(result_buf
, '\n');
4171 if (nl
!= NULL
&& nl
< result_buf
+ result_len
) {
4174 if (strncmp(result_buf
, "main", nl
- result_buf
) == 0) {
4178 if (result_len
< RESULT_SZ
- 25) {
4179 /* Add in hex address */
4180 sprintf(result_buf
+ result_len
, " [0x%lx]",
4181 (unsigned long)info
[i
].ci_pc
);
4188 GC_err_printf1("\t\t%s\n", name
);
4189 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4190 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4191 free(sym_name
); /* May call GC_free; that's OK */
4200 #endif /* NEED_CALLINFO */
4204 #if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
4206 /* Dump /proc/self/maps to GC_stderr, to enable looking up names for
4207 addresses in FIND_LEAK output. */
4209 static word
dump_maps(char *maps
)
4211 GC_err_write(maps
, strlen(maps
));
4215 void GC_print_address_map()
4217 GC_err_printf0("---------- Begin address map ----------\n");
4218 GC_apply_to_maps(dump_maps
);
4219 GC_err_printf0("---------- End address map ----------\n");