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)
57 # if defined(MSWINCE) || defined (SN_TARGET_PS3)
58 # define SIGSEGV 0 /* value is irrelevant */
63 #if defined(LINUX) || defined(LINUX_STACKBOTTOM)
67 /* Blatantly OS dependent routines, except for those that are related */
68 /* to dynamic loading. */
70 # if defined(HEURISTIC2) || defined(SEARCH_FOR_DATA_START)
71 # define NEED_FIND_LIMIT
74 # if !defined(STACKBOTTOM) && defined(HEURISTIC2)
75 # define NEED_FIND_LIMIT
78 # if (defined(SUNOS4) && defined(DYNAMIC_LOADING)) && !defined(PCR)
79 # define NEED_FIND_LIMIT
82 # if (defined(SVR4) || defined(AUX) || defined(DGUX) \
83 || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
84 # define NEED_FIND_LIMIT
87 #if defined(FREEBSD) && (defined(I386) || defined(powerpc) || defined(__powerpc__))
88 # include <machine/trap.h>
90 # define NEED_FIND_LIMIT
94 #if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__) \
95 && !defined(NEED_FIND_LIMIT)
96 /* Used by GC_init_netbsd_elf() below. */
97 # define NEED_FIND_LIMIT
100 #ifdef NEED_FIND_LIMIT
105 # define GC_AMIGA_DEF
106 # include "AmigaOS.c"
110 #if defined(MSWIN32) || defined(MSWINCE)
111 # define WIN32_LEAN_AND_MEAN
113 # include <windows.h>
117 # include <Processes.h>
121 # include <sys/uio.h>
122 # include <malloc.h> /* for locking */
124 #if defined(USE_MUNMAP)
126 --> USE_MUNMAP requires USE_MMAP
129 #if defined(USE_MMAP) || defined(USE_MUNMAP) || defined(FALLBACK_TO_MMAP)
130 # include <sys/types.h>
131 # include <sys/mman.h>
132 # include <sys/stat.h>
136 #if defined( UNIX_LIKE ) || defined(NACL)
140 #if (defined(SUNOS5SIGS) || defined (HURD) || defined(LINUX) || defined(NETBSD)) && !defined(FREEBSD)
142 # include <sys/siginfo.h>
144 /* Define SETJMP and friends to be the version that restores */
145 /* the signal mask. */
146 # define SETJMP(env) sigsetjmp(env, 1)
147 # define LONGJMP(env, val) siglongjmp(env, val)
148 # define JMP_BUF sigjmp_buf
150 # define SETJMP(env) setjmp(env)
151 # define LONGJMP(env, val) longjmp(env, val)
152 # define JMP_BUF jmp_buf
156 /* for get_etext and friends */
157 #include <mach-o/getsect.h>
161 /* Apparently necessary for djgpp 2.01. May cause problems with */
162 /* other versions. */
163 typedef long unsigned int caddr_t
;
167 # include "il/PCR_IL.h"
168 # include "th/PCR_ThCtl.h"
169 # include "mm/PCR_MM.h"
172 #if !defined(NO_EXECUTE_PERMISSION)
173 # define OPT_PROT_EXEC PROT_EXEC
175 # define OPT_PROT_EXEC 0
178 #if defined(LINUX) && \
179 (defined(USE_PROC_FOR_LIBRARIES) || defined(IA64) || !defined(SMALL_CONFIG))
181 /* We need to parse /proc/self/maps, either to find dynamic libraries, */
182 /* and/or to find the register backing store base (IA64). Do it once */
187 /* Repeatedly perform a read call until the buffer is filled or */
188 /* we encounter EOF. */
189 ssize_t
GC_repeat_read(int fd
, char *buf
, size_t count
)
191 ssize_t num_read
= 0;
194 while (num_read
< count
) {
195 result
= READ(fd
, buf
+ num_read
, count
- num_read
);
196 if (result
< 0) return result
;
197 if (result
== 0) break;
204 * Apply fn to a buffer containing the contents of /proc/self/maps.
205 * Return the result of fn or, if we failed, 0.
206 * We currently do nothing to /proc/self/maps other than simply read
207 * it. This code could be simplified if we could determine its size
211 word
GC_apply_to_maps(word (*fn
)(char *))
215 size_t maps_size
= 4000; /* Initial guess. */
216 static char init_buf
[1];
217 static char *maps_buf
= init_buf
;
218 static size_t maps_buf_sz
= 1;
220 /* Read /proc/self/maps, growing maps_buf as necessary. */
221 /* Note that we may not allocate conventionally, and */
222 /* thus can't use stdio. */
224 if (maps_size
>= maps_buf_sz
) {
225 /* Grow only by powers of 2, since we leak "too small" buffers. */
226 while (maps_size
>= maps_buf_sz
) maps_buf_sz
*= 2;
227 maps_buf
= GC_scratch_alloc(maps_buf_sz
);
228 if (maps_buf
== 0) return 0;
230 f
= open("/proc/self/maps", O_RDONLY
);
231 if (-1 == f
) return 0;
234 result
= GC_repeat_read(f
, maps_buf
, maps_buf_sz
-1);
235 if (result
<= 0) return 0;
237 } while (result
== maps_buf_sz
-1);
239 } while (maps_size
>= maps_buf_sz
);
240 maps_buf
[maps_size
] = '\0';
242 /* Apply fn to result. */
246 #endif /* Need GC_apply_to_maps */
248 #if defined(LINUX) && (defined(USE_PROC_FOR_LIBRARIES) || defined(IA64))
250 // GC_parse_map_entry parses an entry from /proc/self/maps so we can
251 // locate all writable data segments that belong to shared libraries.
252 // The format of one of these entries and the fields we care about
254 // XXXXXXXX-XXXXXXXX r-xp 00000000 30:05 260537 name of mapping...\n
255 // ^^^^^^^^ ^^^^^^^^ ^^^^ ^^
256 // start end prot maj_dev
258 // Note that since about auguat 2003 kernels, the columns no longer have
259 // fixed offsets on 64-bit kernels. Hence we no longer rely on fixed offsets
260 // anywhere, which is safer anyway.
264 * Assign various fields of the first line in buf_ptr to *start, *end,
265 * *prot_buf and *maj_dev. Only *prot_buf may be set for unwritable maps.
267 char *GC_parse_map_entry(char *buf_ptr
, word
*start
, word
*end
,
268 char *prot_buf
, unsigned int *maj_dev
)
270 char *start_start
, *end_start
, *prot_start
, *maj_dev_start
;
274 if (buf_ptr
== NULL
|| *buf_ptr
== '\0') {
279 while (isspace(*p
)) ++p
;
281 GC_ASSERT(isxdigit(*start_start
));
282 *start
= strtoul(start_start
, &endp
, 16); p
= endp
;
287 GC_ASSERT(isxdigit(*end_start
));
288 *end
= strtoul(end_start
, &endp
, 16); p
= endp
;
289 GC_ASSERT(isspace(*p
));
291 while (isspace(*p
)) ++p
;
293 GC_ASSERT(*prot_start
== 'r' || *prot_start
== '-');
294 memcpy(prot_buf
, prot_start
, 4);
296 if (prot_buf
[1] == 'w') {/* we can skip the rest if it's not writable. */
297 /* Skip past protection field to offset field */
298 while (!isspace(*p
)) ++p
; while (isspace(*p
)) ++p
;
299 GC_ASSERT(isxdigit(*p
));
300 /* Skip past offset field, which we ignore */
301 while (!isspace(*p
)) ++p
; while (isspace(*p
)) ++p
;
303 GC_ASSERT(isxdigit(*maj_dev_start
));
304 *maj_dev
= strtoul(maj_dev_start
, NULL
, 16);
307 while (*p
&& *p
++ != '\n');
312 #endif /* Need to parse /proc/self/maps. */
314 #if defined(SEARCH_FOR_DATA_START)
315 /* The I386 case can be handled without a search. The Alpha case */
316 /* used to be handled differently as well, but the rules changed */
317 /* for recent Linux versions. This seems to be the easiest way to */
318 /* cover all versions. */
321 /* Some Linux distributions arrange to define __data_start. Some */
322 /* define data_start as a weak symbol. The latter is technically */
323 /* broken, since the user program may define data_start, in which */
324 /* case we lose. Nonetheless, we try both, prefering __data_start. */
325 /* We assume gcc-compatible pragmas. */
326 # pragma weak __data_start
327 extern int __data_start
[];
328 # pragma weak data_start
329 extern int data_start
[];
335 void GC_init_linux_data_start()
337 extern ptr_t
GC_find_limit();
341 * Not needed, avoids the SIGSEGV caused by GC_find_limit which
342 * complicates debugging.
347 /* Try the easy approaches first: */
348 if ((ptr_t
)__data_start
!= 0) {
349 GC_data_start
= (ptr_t
)(__data_start
);
352 if ((ptr_t
)data_start
!= 0) {
353 GC_data_start
= (ptr_t
)(data_start
);
357 GC_data_start
= GC_find_limit((ptr_t
)(_end
), FALSE
);
363 # ifndef ECOS_GC_MEMORY_SIZE
364 # define ECOS_GC_MEMORY_SIZE (448 * 1024)
365 # endif /* ECOS_GC_MEMORY_SIZE */
367 // setjmp() function, as described in ANSI para 7.6.1.1
369 #define SETJMP( __env__ ) hal_setjmp( __env__ )
371 // FIXME: This is a simple way of allocating memory which is
372 // compatible with ECOS early releases. Later releases use a more
373 // sophisticated means of allocating memory than this simple static
374 // allocator, but this method is at least bound to work.
375 static char memory
[ECOS_GC_MEMORY_SIZE
];
376 static char *brk
= memory
;
378 static void *tiny_sbrk(ptrdiff_t increment
)
384 if (brk
> memory
+ sizeof memory
)
392 #define sbrk tiny_sbrk
395 #if defined(NETBSD) && defined(__ELF__)
398 void GC_init_netbsd_elf()
400 extern ptr_t
GC_find_limit();
401 extern char **environ
;
402 /* This may need to be environ, without the underscore, for */
404 GC_data_start
= GC_find_limit((ptr_t
)&environ
, FALSE
);
409 static struct sigaction old_segv_act
;
410 sigjmp_buf GC_jmp_buf_openbsd
;
412 # if defined(GC_OPENBSD_THREADS)
413 # include <sys/syscall.h>
414 sigset_t
__syscall(quad_t
, ...);
418 * Dont use GC_find_limit() because siglongjmp out of the
419 * signal handler by-passes our userland pthreads lib, leaving
420 * SIGSEGV and SIGPROF masked. Instead use this custom one
421 * that works-around the issues.
425 void GC_fault_handler_openbsd(int sig
)
427 siglongjmp(GC_jmp_buf_openbsd
, 1);
430 /* Return the first nonaddressible location > p or bound */
431 /* Requires allocation lock. */
432 ptr_t
GC_find_limit_openbsd(ptr_t p
, ptr_t bound
)
434 static volatile ptr_t result
;
435 /* Safer if static, since otherwise it may not be */
436 /* preserved across the longjmp. Can safely be */
437 /* static since it's only called with the */
438 /* allocation lock held. */
439 struct sigaction act
;
440 size_t pgsz
= (size_t)sysconf(_SC_PAGESIZE
);
442 GC_ASSERT(I_HOLD_LOCK());
444 act
.sa_handler
= GC_fault_handler_openbsd
;
445 sigemptyset(&act
.sa_mask
);
446 act
.sa_flags
= SA_NODEFER
| SA_RESTART
;
447 sigaction(SIGSEGV
, &act
, &old_segv_act
);
449 if (sigsetjmp(GC_jmp_buf_openbsd
, 1) == 0) {
450 result
= (ptr_t
)(((word
)(p
)) & ~(pgsz
-1));
453 if (result
>= bound
) {
457 GC_noop1((word
)(*result
));
461 # if defined(GC_OPENBSD_THREADS)
462 /* due to the siglongjump we need to manually unmask SIGPROF */
463 __syscall(SYS_sigprocmask
, SIG_UNBLOCK
, sigmask(SIGPROF
));
466 sigaction(SIGSEGV
, &old_segv_act
, 0);
471 /* Return first addressable location > p or bound */
472 /* Requires allocation lock. */
473 ptr_t
GC_skip_hole_openbsd(ptr_t p
, ptr_t bound
)
475 static volatile ptr_t result
;
476 struct sigaction act
;
477 size_t pgsz
= (size_t)sysconf(_SC_PAGESIZE
);
478 static volatile int firstpass
;
480 GC_ASSERT(I_HOLD_LOCK());
482 act
.sa_handler
= GC_fault_handler_openbsd
;
483 sigemptyset(&act
.sa_mask
);
484 act
.sa_flags
= SA_NODEFER
| SA_RESTART
;
485 sigaction(SIGSEGV
, &act
, &old_segv_act
);
488 result
= (ptr_t
)(((word
)(p
)) & ~(pgsz
-1));
489 if (sigsetjmp(GC_jmp_buf_openbsd
, 1) != 0 || firstpass
) {
492 if (result
>= bound
) {
495 GC_noop1((word
)(*result
));
498 sigaction(SIGSEGV
, &old_segv_act
, 0);
508 # if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */
511 unsigned short magic_number
;
512 unsigned short padding
[29];
516 #define E_MAGIC(x) (x).magic_number
517 #define EMAGIC 0x5A4D
518 #define E_LFANEW(x) (x).new_exe_offset
521 unsigned char magic_number
[2];
522 unsigned char byte_order
;
523 unsigned char word_order
;
524 unsigned long exe_format_level
;
527 unsigned long padding1
[13];
528 unsigned long object_table_offset
;
529 unsigned long object_count
;
530 unsigned long padding2
[31];
533 #define E32_MAGIC1(x) (x).magic_number[0]
534 #define E32MAGIC1 'L'
535 #define E32_MAGIC2(x) (x).magic_number[1]
536 #define E32MAGIC2 'X'
537 #define E32_BORDER(x) (x).byte_order
539 #define E32_WORDER(x) (x).word_order
541 #define E32_CPU(x) (x).cpu
543 #define E32_OBJTAB(x) (x).object_table_offset
544 #define E32_OBJCNT(x) (x).object_count
550 unsigned long pagemap
;
551 unsigned long mapsize
;
552 unsigned long reserved
;
555 #define O32_FLAGS(x) (x).flags
556 #define OBJREAD 0x0001L
557 #define OBJWRITE 0x0002L
558 #define OBJINVALID 0x0080L
559 #define O32_SIZE(x) (x).size
560 #define O32_BASE(x) (x).base
562 # else /* IBM's compiler */
564 /* A kludge to get around what appears to be a header file bug */
566 # define WORD unsigned short
569 # define DWORD unsigned long
576 # endif /* __IBMC__ */
578 # define INCL_DOSEXCEPTIONS
579 # define INCL_DOSPROCESS
580 # define INCL_DOSERRORS
581 # define INCL_DOSMODULEMGR
582 # define INCL_DOSMEMMGR
586 /* Disable and enable signals during nontrivial allocations */
588 void GC_disable_signals(void)
592 DosEnterMustComplete(&nest
);
593 if (nest
!= 1) ABORT("nested GC_disable_signals");
596 void GC_enable_signals(void)
600 DosExitMustComplete(&nest
);
601 if (nest
!= 0) ABORT("GC_enable_signals");
607 # if !defined(PCR) && !defined(AMIGA) && !defined(MSWIN32) \
608 && !defined(MSWINCE) \
609 && !defined(MACOS) && !defined(DJGPP) && !defined(DOS4GW) \
610 && !defined(NOSYS) && !defined(ECOS) && !defined(SN_TARGET_PS3)
612 # if defined(sigmask) && !defined(UTS4) && !defined(HURD)
613 /* Use the traditional BSD interface */
614 # define SIGSET_T int
615 # define SIG_DEL(set, signal) (set) &= ~(sigmask(signal))
616 # define SIG_FILL(set) (set) = 0x7fffffff
617 /* Setting the leading bit appears to provoke a bug in some */
618 /* longjmp implementations. Most systems appear not to have */
620 # define SIGSETMASK(old, new) (old) = sigsetmask(new)
622 /* We don't use signals in NaCl. */
623 # define SIGSET_T int
624 # define SIG_DEL(set, signal)
625 # define SIG_FILL(set)
626 # define SIGSETMASK(old, new)
628 /* Use POSIX/SYSV interface */
629 # define SIGSET_T sigset_t
630 # define SIG_DEL(set, signal) sigdelset(&(set), (signal))
631 # define SIG_FILL(set) sigfillset(&set)
632 # define SIGSETMASK(old, new) sigprocmask(SIG_SETMASK, &(new), &(old))
635 static GC_bool mask_initialized
= FALSE
;
637 static SIGSET_T new_mask
;
639 static SIGSET_T old_mask
;
641 static SIGSET_T dummy
;
643 #if defined(PRINTSTATS) && !defined(THREADS)
644 # define CHECK_SIGNALS
645 int GC_sig_disabled
= 0;
648 void GC_disable_signals()
650 if (!mask_initialized
) {
653 SIG_DEL(new_mask
, SIGSEGV
);
654 SIG_DEL(new_mask
, SIGILL
);
655 SIG_DEL(new_mask
, SIGQUIT
);
657 SIG_DEL(new_mask
, SIGBUS
);
660 SIG_DEL(new_mask
, SIGIOT
);
663 SIG_DEL(new_mask
, SIGEMT
);
666 SIG_DEL(new_mask
, SIGTRAP
);
668 mask_initialized
= TRUE
;
670 # ifdef CHECK_SIGNALS
671 if (GC_sig_disabled
!= 0) ABORT("Nested disables");
674 SIGSETMASK(old_mask
,new_mask
);
677 void GC_enable_signals()
679 # ifdef CHECK_SIGNALS
680 if (GC_sig_disabled
!= 1) ABORT("Unmatched enable");
683 SIGSETMASK(dummy
,old_mask
);
690 /* Ivan Demakov: simplest way (to me) */
692 void GC_disable_signals() { }
693 void GC_enable_signals() { }
696 /* Find the page size */
699 # if defined(MSWIN32) || defined(MSWINCE)
700 void GC_setpagesize()
702 GetSystemInfo(&GC_sysinfo
);
703 GC_page_size
= GC_sysinfo
.dwPageSize
;
707 # if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP) \
708 || defined(USE_MUNMAP) || defined(FALLBACK_TO_MMAP)
709 void GC_setpagesize()
711 GC_page_size
= GETPAGESIZE();
714 /* It's acceptable to fake it. */
715 void GC_setpagesize()
717 GC_page_size
= HBLKSIZE
;
723 * Find the base of the stack.
724 * Used only in single-threaded environment.
725 * With threads, GC_mark_roots needs to know how to do this.
726 * Called with allocator lock held.
728 # if defined(MSWIN32) || defined(MSWINCE)
729 # define is_writable(prot) ((prot) == PAGE_READWRITE \
730 || (prot) == PAGE_WRITECOPY \
731 || (prot) == PAGE_EXECUTE_READWRITE \
732 || (prot) == PAGE_EXECUTE_WRITECOPY)
733 /* Return the number of bytes that are writable starting at p. */
734 /* The pointer p is assumed to be page aligned. */
735 /* If base is not 0, *base becomes the beginning of the */
736 /* allocation region containing p. */
737 word
GC_get_writable_length(ptr_t p
, ptr_t
*base
)
739 MEMORY_BASIC_INFORMATION buf
;
743 result
= VirtualQuery(p
, &buf
, sizeof(buf
));
744 if (result
!= sizeof(buf
)) ABORT("Weird VirtualQuery result");
745 if (base
!= 0) *base
= (ptr_t
)(buf
.AllocationBase
);
746 protect
= (buf
.Protect
& ~(PAGE_GUARD
| PAGE_NOCACHE
));
747 if (!is_writable(protect
)) {
750 if (buf
.State
!= MEM_COMMIT
) return(0);
751 return(buf
.RegionSize
);
754 ptr_t
GC_get_stack_base()
757 ptr_t sp
= (ptr_t
)(&dummy
);
758 ptr_t trunc_sp
= (ptr_t
)((word
)sp
& ~(GC_page_size
- 1));
759 word size
= GC_get_writable_length(trunc_sp
, 0);
761 return(trunc_sp
+ size
);
765 # endif /* MS Windows */
768 # include <kernel/OS.h>
769 ptr_t
GC_get_stack_base(){
771 get_thread_info(find_thread(NULL
),&th
);
779 ptr_t
GC_get_stack_base()
784 if (DosGetInfoBlocks(&ptib
, &ppib
) != NO_ERROR
) {
785 GC_err_printf0("DosGetInfoBlocks failed\n");
786 ABORT("DosGetInfoBlocks failed\n");
788 return((ptr_t
)(ptib
-> tib_pstacklimit
));
795 # include "AmigaOS.c"
799 # if defined(NEED_FIND_LIMIT) || defined(UNIX_LIKE)
802 typedef void (*handler
)(int);
804 typedef void (*handler
)();
807 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1) \
808 || defined(HURD) || defined(NETBSD) || defined(FREEBSD)
809 static struct sigaction old_segv_act
;
810 # if defined(IRIX5) || defined(HPUX) \
811 || defined(HURD) || defined(NETBSD)
812 static struct sigaction old_bus_act
;
815 static handler old_segv_handler
, old_bus_handler
;
819 void GC_set_and_save_fault_handler(handler h
)
821 void GC_set_and_save_fault_handler(h
)
825 # if defined(SUNOS5SIGS) || defined(IRIX5) \
826 || defined(OSF1) || defined(HURD) || defined(NETBSD) || defined(FREEBSD)
827 struct sigaction act
;
830 # if 0 /* Was necessary for Solaris 2.3 and very temporary */
832 act
.sa_flags
= SA_RESTART
| SA_NODEFER
;
834 act
.sa_flags
= SA_RESTART
;
837 (void) sigemptyset(&act
.sa_mask
);
838 # ifdef GC_IRIX_THREADS
839 /* Older versions have a bug related to retrieving and */
840 /* and setting a handler at the same time. */
841 (void) sigaction(SIGSEGV
, 0, &old_segv_act
);
842 (void) sigaction(SIGSEGV
, &act
, 0);
843 (void) sigaction(SIGBUS
, 0, &old_bus_act
);
844 (void) sigaction(SIGBUS
, &act
, 0);
846 (void) sigaction(SIGSEGV
, &act
, &old_segv_act
);
847 # if defined(IRIX5) \
848 || defined(HPUX) || defined(HURD) || defined(NETBSD)
849 /* Under Irix 5.x or HP/UX, we may get SIGBUS. */
850 /* Pthreads doesn't exist under Irix 5.x, so we */
851 /* don't have to worry in the threads case. */
852 (void) sigaction(SIGBUS
, &act
, &old_bus_act
);
854 # endif /* GC_IRIX_THREADS */
856 old_segv_handler
= signal(SIGSEGV
, h
);
858 old_bus_handler
= signal(SIGBUS
, h
);
862 # endif /* NEED_FIND_LIMIT || UNIX_LIKE */
864 # ifdef NEED_FIND_LIMIT
865 /* Some tools to implement HEURISTIC2 */
866 # define MIN_PAGE_SIZE 256 /* Smallest conceivable page size, bytes */
867 /* static */ JMP_BUF GC_jmp_buf
;
870 void GC_fault_handler(sig
)
873 LONGJMP(GC_jmp_buf
, 1);
876 void GC_setup_temporary_fault_handler()
878 GC_set_and_save_fault_handler(GC_fault_handler
);
881 void GC_reset_fault_handler()
883 # if defined(SUNOS5SIGS) || defined(IRIX5) \
884 || defined(OSF1) || defined(HURD) || defined(NETBSD) || defined(FREEBSD)
885 (void) sigaction(SIGSEGV
, &old_segv_act
, 0);
886 # if defined(IRIX5) \
887 || defined(HPUX) || defined(HURD) || defined(NETBSD)
888 (void) sigaction(SIGBUS
, &old_bus_act
, 0);
891 (void) signal(SIGSEGV
, old_segv_handler
);
893 (void) signal(SIGBUS
, old_bus_handler
);
898 /* Return the first nonaddressible location > p (up) or */
899 /* the smallest location q s.t. [q,p) is addressable (!up). */
900 /* We assume that p (up) or p-1 (!up) is addressable. */
901 ptr_t
GC_find_limit(p
, up
)
905 static VOLATILE ptr_t result
;
906 /* Needs to be static, since otherwise it may not be */
907 /* preserved across the longjmp. Can safely be */
908 /* static since it's only called once, with the */
909 /* allocation lock held. */
912 GC_setup_temporary_fault_handler();
913 if (SETJMP(GC_jmp_buf
) == 0) {
914 result
= (ptr_t
)(((word
)(p
))
915 & ~(MIN_PAGE_SIZE
-1));
918 result
+= MIN_PAGE_SIZE
;
920 result
-= MIN_PAGE_SIZE
;
922 GC_noop1((word
)(*result
));
925 GC_reset_fault_handler();
927 result
+= MIN_PAGE_SIZE
;
933 #if defined(ECOS) || defined(NOSYS)
934 ptr_t
GC_get_stack_base()
940 #ifdef HPUX_STACKBOTTOM
942 #include <sys/param.h>
943 #include <sys/pstat.h>
945 ptr_t
GC_get_register_stack_base(void)
947 struct pst_vm_status vm_status
;
950 while (pstat_getprocvm(&vm_status
, sizeof(vm_status
), 0, i
++) == 1) {
951 if (vm_status
.pst_type
== PS_RSESTACK
) {
952 return (ptr_t
) vm_status
.pst_vaddr
;
956 /* old way to get the register stackbottom */
957 return (ptr_t
)(((word
)GC_stackbottom
- BACKING_STORE_DISPLACEMENT
- 1)
958 & ~(BACKING_STORE_ALIGNMENT
- 1));
961 #endif /* HPUX_STACK_BOTTOM */
963 #ifdef LINUX_STACKBOTTOM
965 #include <sys/types.h>
966 #include <sys/stat.h>
968 # define STAT_SKIP 27 /* Number of fields preceding startstack */
969 /* field in /proc/self/stat */
971 #ifdef USE_LIBC_PRIVATES
972 # pragma weak __libc_stack_end
973 extern ptr_t __libc_stack_end
;
977 /* Try to read the backing store base from /proc/self/maps. */
978 /* We look for the writable mapping with a 0 major device, */
979 /* which is as close to our frame as possible, but below it.*/
980 static word
backing_store_base_from_maps(char *maps
)
983 char *buf_ptr
= maps
;
985 unsigned int maj_dev
;
986 word current_best
= 0;
990 buf_ptr
= GC_parse_map_entry(buf_ptr
, &start
, &end
, prot_buf
, &maj_dev
);
991 if (buf_ptr
== NULL
) return current_best
;
992 if (prot_buf
[1] == 'w' && maj_dev
== 0) {
993 if (end
< (word
)(&dummy
) && start
> current_best
) current_best
= start
;
999 static word
backing_store_base_from_proc(void)
1001 return GC_apply_to_maps(backing_store_base_from_maps
);
1004 # ifdef USE_LIBC_PRIVATES
1005 # pragma weak __libc_ia64_register_backing_store_base
1006 extern ptr_t __libc_ia64_register_backing_store_base
;
1009 ptr_t
GC_get_register_stack_base(void)
1011 # ifdef USE_LIBC_PRIVATES
1012 if (0 != &__libc_ia64_register_backing_store_base
1013 && 0 != __libc_ia64_register_backing_store_base
) {
1014 /* Glibc 2.2.4 has a bug such that for dynamically linked */
1015 /* executables __libc_ia64_register_backing_store_base is */
1016 /* defined but uninitialized during constructor calls. */
1017 /* Hence we check for both nonzero address and value. */
1018 return __libc_ia64_register_backing_store_base
;
1021 word result
= backing_store_base_from_proc();
1023 /* Use dumb heuristics. Works only for default configuration. */
1024 result
= (word
)GC_stackbottom
- BACKING_STORE_DISPLACEMENT
;
1025 result
+= BACKING_STORE_ALIGNMENT
- 1;
1026 result
&= ~(BACKING_STORE_ALIGNMENT
- 1);
1027 /* Verify that it's at least readable. If not, we goofed. */
1028 GC_noop1(*(word
*)result
);
1030 return (ptr_t
)result
;
1034 void *GC_set_stackbottom
= NULL
;
1036 ptr_t
GC_linux_stack_base(void)
1038 /* We read the stack base value from /proc/self/stat. We do this */
1039 /* using direct I/O system calls in order to avoid calling malloc */
1040 /* in case REDIRECT_MALLOC is defined. */
1041 # define STAT_BUF_SIZE 4096
1042 # define STAT_READ read
1043 /* Should probably call the real read, if read is wrapped. */
1044 char stat_buf
[STAT_BUF_SIZE
];
1048 size_t i
, buf_offset
= 0;
1050 /* First try the easy way. This should work for glibc 2.2 */
1051 /* This fails in a prelinked ("prelink" command) executable */
1052 /* since the correct value of __libc_stack_end never */
1053 /* becomes visible to us. The second test works around */
1055 # ifdef USE_LIBC_PRIVATES
1056 if (0 != &__libc_stack_end
&& 0 != __libc_stack_end
) {
1058 /* Some versions of glibc set the address 16 bytes too */
1059 /* low while the initialization code is running. */
1060 if (((word
)__libc_stack_end
& 0xfff) + 0x10 < 0x1000) {
1061 return __libc_stack_end
+ 0x10;
1062 } /* Otherwise it's not safe to add 16 bytes and we fall */
1063 /* back to using /proc. */
1066 /* Older versions of glibc for 64-bit Sparc do not set
1067 * this variable correctly, it gets set to either zero
1070 if (__libc_stack_end
!= (ptr_t
) (unsigned long)0x1)
1071 return __libc_stack_end
;
1073 return __libc_stack_end
;
1078 f
= open("/proc/self/stat", O_RDONLY
);
1079 if (f
< 0 || STAT_READ(f
, stat_buf
, STAT_BUF_SIZE
) < 2 * STAT_SKIP
) {
1080 ABORT("Couldn't read /proc/self/stat");
1082 c
= stat_buf
[buf_offset
++];
1083 /* Skip the required number of fields. This number is hopefully */
1084 /* constant across all Linux implementations. */
1085 for (i
= 0; i
< STAT_SKIP
; ++i
) {
1086 while (isspace(c
)) c
= stat_buf
[buf_offset
++];
1087 while (!isspace(c
)) c
= stat_buf
[buf_offset
++];
1089 while (isspace(c
)) c
= stat_buf
[buf_offset
++];
1090 while (isdigit(c
)) {
1093 c
= stat_buf
[buf_offset
++];
1096 if (result
< 0x10000000) ABORT("Absurd stack bottom value");
1097 return (ptr_t
)result
;
1100 #endif /* LINUX_STACKBOTTOM */
1102 #ifdef FREEBSD_STACKBOTTOM
1104 /* This uses an undocumented sysctl call, but at least one expert */
1105 /* believes it will stay. */
1108 #include <sys/types.h>
1109 #include <sys/sysctl.h>
1111 ptr_t
GC_freebsd_stack_base(void)
1113 int nm
[2] = {CTL_KERN
, KERN_USRSTACK
};
1115 size_t len
= sizeof(ptr_t
);
1116 int r
= sysctl(nm
, 2, &base
, &len
, NULL
, 0);
1118 if (r
) ABORT("Error getting stack base");
1123 #endif /* FREEBSD_STACKBOTTOM */
1125 #if !defined(BEOS) && !defined(AMIGA) && !defined(MSWIN32) \
1126 && !defined(MSWINCE) && !defined(OS2) && !defined(NOSYS) && !defined(ECOS) \
1127 && !defined(GC_OPENBSD_THREADS)
1129 ptr_t
GC_get_stack_base()
1131 # if defined(HEURISTIC1) || defined(HEURISTIC2) || \
1132 defined(LINUX_STACKBOTTOM) || defined(FREEBSD_STACKBOTTOM)
1137 # define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
1140 return(STACKBOTTOM
);
1143 # ifdef STACK_GROWS_DOWN
1144 result
= (ptr_t
)((((word
)(&dummy
))
1145 + STACKBOTTOM_ALIGNMENT_M1
)
1146 & ~STACKBOTTOM_ALIGNMENT_M1
);
1148 result
= (ptr_t
)(((word
)(&dummy
))
1149 & ~STACKBOTTOM_ALIGNMENT_M1
);
1151 # endif /* HEURISTIC1 */
1152 # ifdef LINUX_STACKBOTTOM
1153 result
= GC_linux_stack_base();
1155 # ifdef FREEBSD_STACKBOTTOM
1156 result
= GC_freebsd_stack_base();
1159 # ifdef STACK_GROWS_DOWN
1160 result
= GC_find_limit((ptr_t
)(&dummy
), TRUE
);
1161 # ifdef HEURISTIC2_LIMIT
1162 if (result
> HEURISTIC2_LIMIT
1163 && (ptr_t
)(&dummy
) < HEURISTIC2_LIMIT
) {
1164 result
= HEURISTIC2_LIMIT
;
1168 result
= GC_find_limit((ptr_t
)(&dummy
), FALSE
);
1169 # ifdef HEURISTIC2_LIMIT
1170 if (result
< HEURISTIC2_LIMIT
1171 && (ptr_t
)(&dummy
) > HEURISTIC2_LIMIT
) {
1172 result
= HEURISTIC2_LIMIT
;
1177 # endif /* HEURISTIC2 */
1178 # ifdef STACK_GROWS_DOWN
1179 if (result
== 0) result
= (ptr_t
)(signed_word
)(-sizeof(ptr_t
));
1182 # endif /* STACKBOTTOM */
1185 # endif /* ! AMIGA, !OS 2, ! MS Windows, !BEOS, !NOSYS, !ECOS */
1187 #if defined(GC_OPENBSD_THREADS)
1189 /* Find the stack using pthread_stackseg_np() */
1191 # include <sys/signal.h>
1192 # include <pthread.h>
1193 # include <pthread_np.h>
1195 #define HAVE_GET_STACK_BASE
1197 ptr_t
GC_get_stack_base()
1200 pthread_stackseg_np(pthread_self(), &stack
);
1204 #endif /* GC_OPENBSD_THREADS */
1207 * Register static data segment(s) as roots.
1208 * If more data segments are added later then they need to be registered
1209 * add that point (as we do with SunOS dynamic loading),
1210 * or GC_mark_roots needs to check for them (as we do with PCR).
1211 * Called with allocator lock held.
1216 void GC_register_data_segments()
1220 HMODULE module_handle
;
1221 # define PBUFSIZ 512
1222 UCHAR path
[PBUFSIZ
];
1224 struct exe_hdr hdrdos
; /* MSDOS header. */
1225 struct e32_exe hdr386
; /* Real header for my executable */
1226 struct o32_obj seg
; /* Currrent segment */
1230 if (DosGetInfoBlocks(&ptib
, &ppib
) != NO_ERROR
) {
1231 GC_err_printf0("DosGetInfoBlocks failed\n");
1232 ABORT("DosGetInfoBlocks failed\n");
1234 module_handle
= ppib
-> pib_hmte
;
1235 if (DosQueryModuleName(module_handle
, PBUFSIZ
, path
) != NO_ERROR
) {
1236 GC_err_printf0("DosQueryModuleName failed\n");
1237 ABORT("DosGetInfoBlocks failed\n");
1239 myexefile
= fopen(path
, "rb");
1240 if (myexefile
== 0) {
1241 GC_err_puts("Couldn't open executable ");
1242 GC_err_puts(path
); GC_err_puts("\n");
1243 ABORT("Failed to open executable\n");
1245 if (fread((char *)(&hdrdos
), 1, sizeof hdrdos
, myexefile
) < sizeof hdrdos
) {
1246 GC_err_puts("Couldn't read MSDOS header from ");
1247 GC_err_puts(path
); GC_err_puts("\n");
1248 ABORT("Couldn't read MSDOS header");
1250 if (E_MAGIC(hdrdos
) != EMAGIC
) {
1251 GC_err_puts("Executable has wrong DOS magic number: ");
1252 GC_err_puts(path
); GC_err_puts("\n");
1253 ABORT("Bad DOS magic number");
1255 if (fseek(myexefile
, E_LFANEW(hdrdos
), SEEK_SET
) != 0) {
1256 GC_err_puts("Seek to new header failed in ");
1257 GC_err_puts(path
); GC_err_puts("\n");
1258 ABORT("Bad DOS magic number");
1260 if (fread((char *)(&hdr386
), 1, sizeof hdr386
, myexefile
) < sizeof hdr386
) {
1261 GC_err_puts("Couldn't read MSDOS header from ");
1262 GC_err_puts(path
); GC_err_puts("\n");
1263 ABORT("Couldn't read OS/2 header");
1265 if (E32_MAGIC1(hdr386
) != E32MAGIC1
|| E32_MAGIC2(hdr386
) != E32MAGIC2
) {
1266 GC_err_puts("Executable has wrong OS/2 magic number:");
1267 GC_err_puts(path
); GC_err_puts("\n");
1268 ABORT("Bad OS/2 magic number");
1270 if ( E32_BORDER(hdr386
) != E32LEBO
|| E32_WORDER(hdr386
) != E32LEWO
) {
1271 GC_err_puts("Executable %s has wrong byte order: ");
1272 GC_err_puts(path
); GC_err_puts("\n");
1273 ABORT("Bad byte order");
1275 if ( E32_CPU(hdr386
) == E32CPU286
) {
1276 GC_err_puts("GC can't handle 80286 executables: ");
1277 GC_err_puts(path
); GC_err_puts("\n");
1280 if (fseek(myexefile
, E_LFANEW(hdrdos
) + E32_OBJTAB(hdr386
),
1282 GC_err_puts("Seek to object table failed: ");
1283 GC_err_puts(path
); GC_err_puts("\n");
1284 ABORT("Seek to object table failed");
1286 for (nsegs
= E32_OBJCNT(hdr386
); nsegs
> 0; nsegs
--) {
1288 if (fread((char *)(&seg
), 1, sizeof seg
, myexefile
) < sizeof seg
) {
1289 GC_err_puts("Couldn't read obj table entry from ");
1290 GC_err_puts(path
); GC_err_puts("\n");
1291 ABORT("Couldn't read obj table entry");
1293 flags
= O32_FLAGS(seg
);
1294 if (!(flags
& OBJWRITE
)) continue;
1295 if (!(flags
& OBJREAD
)) continue;
1296 if (flags
& OBJINVALID
) {
1297 GC_err_printf0("Object with invalid pages?\n");
1300 GC_add_roots_inner(O32_BASE(seg
), O32_BASE(seg
)+O32_SIZE(seg
), FALSE
);
1306 # if defined(MSWIN32) || defined(MSWINCE)
1309 /* Unfortunately, we have to handle win32s very differently from NT, */
1310 /* Since VirtualQuery has very different semantics. In particular, */
1311 /* under win32s a VirtualQuery call on an unmapped page returns an */
1312 /* invalid result. Under NT, GC_register_data_segments is a noop and */
1313 /* all real work is done by GC_register_dynamic_libraries. Under */
1314 /* win32s, we cannot find the data segments associated with dll's. */
1315 /* We register the main data segment here. */
1316 GC_bool GC_no_win32_dlls
= FALSE
;
1317 /* This used to be set for gcc, to avoid dealing with */
1318 /* the structured exception handling issues. But we now have */
1319 /* assembly code to do that right. */
1321 void GC_init_win32()
1323 /* if we're running under win32s, assume that no DLLs will be loaded */
1324 DWORD v
= GetVersion();
1325 GC_no_win32_dlls
|= ((v
& 0x80000000) && (v
& 0xff) <= 3);
1328 /* Return the smallest address a such that VirtualQuery */
1329 /* returns correct results for all addresses between a and start. */
1330 /* Assumes VirtualQuery returns correct information for start. */
1331 ptr_t
GC_least_described_address(ptr_t start
)
1333 MEMORY_BASIC_INFORMATION buf
;
1339 limit
= GC_sysinfo
.lpMinimumApplicationAddress
;
1340 p
= (ptr_t
)((word
)start
& ~(GC_page_size
- 1));
1342 q
= (LPVOID
)(p
- GC_page_size
);
1343 if ((ptr_t
)q
> (ptr_t
)p
/* underflow */ || q
< limit
) break;
1344 result
= VirtualQuery(q
, &buf
, sizeof(buf
));
1345 if (result
!= sizeof(buf
) || buf
.AllocationBase
== 0) break;
1346 p
= (ptr_t
)(buf
.AllocationBase
);
1352 # ifndef REDIRECT_MALLOC
1353 /* We maintain a linked list of AllocationBase values that we know */
1354 /* correspond to malloc heap sections. Currently this is only called */
1355 /* during a GC. But there is some hope that for long running */
1356 /* programs we will eventually see most heap sections. */
1358 /* In the long run, it would be more reliable to occasionally walk */
1359 /* the malloc heap with HeapWalk on the default heap. But that */
1360 /* apparently works only for NT-based Windows. */
1362 /* In the long run, a better data structure would also be nice ... */
1363 struct GC_malloc_heap_list
{
1364 void * allocation_base
;
1365 struct GC_malloc_heap_list
*next
;
1366 } *GC_malloc_heap_l
= 0;
1368 /* Is p the base of one of the malloc heap sections we already know */
1370 GC_bool
GC_is_malloc_heap_base(ptr_t p
)
1372 struct GC_malloc_heap_list
*q
= GC_malloc_heap_l
;
1375 if (q
-> allocation_base
== p
) return TRUE
;
1381 void *GC_get_allocation_base(void *p
)
1383 MEMORY_BASIC_INFORMATION buf
;
1384 DWORD result
= VirtualQuery(p
, &buf
, sizeof(buf
));
1385 if (result
!= sizeof(buf
)) {
1386 ABORT("Weird VirtualQuery result");
1388 return buf
.AllocationBase
;
1391 size_t GC_max_root_size
= 100000; /* Appr. largest root size. */
1393 void GC_add_current_malloc_heap()
1395 struct GC_malloc_heap_list
*new_l
=
1396 malloc(sizeof(struct GC_malloc_heap_list
));
1397 void * candidate
= GC_get_allocation_base(new_l
);
1399 if (new_l
== 0) return;
1400 if (GC_is_malloc_heap_base(candidate
)) {
1401 /* Try a little harder to find malloc heap. */
1402 size_t req_size
= 10000;
1404 void *p
= malloc(req_size
);
1405 if (0 == p
) { free(new_l
); return; }
1406 candidate
= GC_get_allocation_base(p
);
1409 } while (GC_is_malloc_heap_base(candidate
)
1410 && req_size
< GC_max_root_size
/10 && req_size
< 500000);
1411 if (GC_is_malloc_heap_base(candidate
)) {
1412 free(new_l
); return;
1417 GC_printf1("Found new system malloc AllocationBase at 0x%lx\n",
1420 new_l
-> allocation_base
= candidate
;
1421 new_l
-> next
= GC_malloc_heap_l
;
1422 GC_malloc_heap_l
= new_l
;
1424 # endif /* REDIRECT_MALLOC */
1426 /* Is p the start of either the malloc heap, or of one of our */
1427 /* heap sections? */
1428 GC_bool
GC_is_heap_base (ptr_t p
)
1433 # ifndef REDIRECT_MALLOC
1434 static word last_gc_no
= -1;
1436 if (last_gc_no
!= GC_gc_no
) {
1437 GC_add_current_malloc_heap();
1438 last_gc_no
= GC_gc_no
;
1440 if (GC_root_size
> GC_max_root_size
) GC_max_root_size
= GC_root_size
;
1441 if (GC_is_malloc_heap_base(p
)) return TRUE
;
1443 for (i
= 0; i
< GC_n_heap_bases
; i
++) {
1444 if (GC_heap_bases
[i
] == p
) return TRUE
;
1450 void GC_register_root_section(ptr_t static_root
)
1452 MEMORY_BASIC_INFORMATION buf
;
1457 char * limit
, * new_limit
;
1459 if (!GC_no_win32_dlls
) return;
1460 p
= base
= limit
= GC_least_described_address(static_root
);
1461 while (p
< GC_sysinfo
.lpMaximumApplicationAddress
) {
1462 result
= VirtualQuery(p
, &buf
, sizeof(buf
));
1463 if (result
!= sizeof(buf
) || buf
.AllocationBase
== 0
1464 || GC_is_heap_base(buf
.AllocationBase
)) break;
1465 new_limit
= (char *)p
+ buf
.RegionSize
;
1466 protect
= buf
.Protect
;
1467 if (buf
.State
== MEM_COMMIT
1468 && is_writable(protect
)) {
1469 if ((char *)p
== limit
) {
1472 if (base
!= limit
) GC_add_roots_inner(base
, limit
, FALSE
);
1477 if (p
> (LPVOID
)new_limit
/* overflow */) break;
1478 p
= (LPVOID
)new_limit
;
1480 if (base
!= limit
) GC_add_roots_inner(base
, limit
, FALSE
);
1484 void GC_register_data_segments()
1488 GC_register_root_section((ptr_t
)(&dummy
));
1492 # else /* !OS2 && !Windows */
1494 # if (defined(SVR4) || defined(AUX) || defined(DGUX) \
1495 || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
1496 ptr_t
GC_SysVGetDataStart(max_page_size
, etext_addr
)
1500 word text_end
= ((word
)(etext_addr
) + sizeof(word
) - 1)
1501 & ~(sizeof(word
) - 1);
1502 /* etext rounded to word boundary */
1503 word next_page
= ((text_end
+ (word
)max_page_size
- 1)
1504 & ~((word
)max_page_size
- 1));
1505 word page_offset
= (text_end
& ((word
)max_page_size
- 1));
1506 VOLATILE
char * result
= (char *)(next_page
+ page_offset
);
1507 /* Note that this isnt equivalent to just adding */
1508 /* max_page_size to &etext if &etext is at a page boundary */
1510 GC_setup_temporary_fault_handler();
1511 if (SETJMP(GC_jmp_buf
) == 0) {
1512 /* Try writing to the address. */
1514 GC_reset_fault_handler();
1516 GC_reset_fault_handler();
1517 /* We got here via a longjmp. The address is not readable. */
1518 /* This is known to happen under Solaris 2.4 + gcc, which place */
1519 /* string constants in the text segment, but after etext. */
1520 /* Use plan B. Note that we now know there is a gap between */
1521 /* text and data segments, so plan A bought us something. */
1522 result
= (char *)GC_find_limit((ptr_t
)(DATAEND
), FALSE
);
1524 return((ptr_t
)result
);
1528 # if defined(FREEBSD) && (defined(I386) || defined(powerpc) || defined(__powerpc__) || defined(__x86_64__)) && !defined(PCR)
1529 /* Its unclear whether this should be identical to the above, or */
1530 /* whether it should apply to non-X86 architectures. */
1531 /* For now we don't assume that there is always an empty page after */
1532 /* etext. But in some cases there actually seems to be slightly more. */
1533 /* This also deals with holes between read-only data and writable data. */
1534 ptr_t
GC_FreeBSDGetDataStart(max_page_size
, etext_addr
)
1538 word text_end
= ((word
)(etext_addr
) + sizeof(word
) - 1)
1539 & ~(sizeof(word
) - 1);
1540 /* etext rounded to word boundary */
1541 VOLATILE word next_page
= (text_end
+ (word
)max_page_size
- 1)
1542 & ~((word
)max_page_size
- 1);
1543 VOLATILE ptr_t result
= (ptr_t
)text_end
;
1544 GC_setup_temporary_fault_handler();
1545 if (SETJMP(GC_jmp_buf
) == 0) {
1546 /* Try reading at the address. */
1547 /* This should happen before there is another thread. */
1548 for (; next_page
< (word
)(DATAEND
); next_page
+= (word
)max_page_size
)
1549 *(VOLATILE
char *)next_page
;
1550 GC_reset_fault_handler();
1552 GC_reset_fault_handler();
1553 /* As above, we go to plan B */
1554 result
= GC_find_limit((ptr_t
)(DATAEND
), FALSE
);
1564 # define GC_AMIGA_DS
1565 # include "AmigaOS.c"
1568 #else /* !OS2 && !Windows && !AMIGA */
1570 #if defined(OPENBSD)
1573 * Depending on arch alignment there can be multiple holes
1574 * between DATASTART & DATAEND. Scan from DATASTART - DATAEND
1575 * and register each region.
1577 void GC_register_data_segments(void)
1579 ptr_t region_start
, region_end
;
1581 region_start
= DATASTART
;
1584 region_end
= GC_find_limit_openbsd(region_start
, DATAEND
);
1585 GC_add_roots_inner(region_start
, region_end
, FALSE
);
1586 if (region_end
< DATAEND
)
1587 region_start
= GC_skip_hole_openbsd(region_end
, DATAEND
);
1593 # else /* !OS2 && !Windows && !AMIGA && !OPENBSD */
1595 void GC_register_data_segments()
1597 # if !defined(PCR) && !defined(SRC_M3) && !defined(MACOS)
1598 # if defined(REDIRECT_MALLOC) && defined(GC_SOLARIS_THREADS)
1599 /* As of Solaris 2.3, the Solaris threads implementation */
1600 /* allocates the data structure for the initial thread with */
1601 /* sbrk at process startup. It needs to be scanned, so that */
1602 /* we don't lose some malloc allocated data structures */
1603 /* hanging from it. We're on thin ice here ... */
1604 extern caddr_t
sbrk();
1606 GC_ASSERT(DATASTART
);
1607 GC_add_roots_inner(DATASTART
, (char *)sbrk(0), FALSE
);
1609 GC_ASSERT(DATASTART
);
1610 GC_add_roots_inner(DATASTART
, (char *)(DATAEND
), FALSE
);
1611 # if defined(DATASTART2)
1612 GC_add_roots_inner(DATASTART2
, (char *)(DATAEND2
), FALSE
);
1618 # if defined(THINK_C)
1619 extern void* GC_MacGetDataStart(void);
1620 /* globals begin above stack and end at a5. */
1621 GC_add_roots_inner((ptr_t
)GC_MacGetDataStart(),
1622 (ptr_t
)LMGetCurrentA5(), FALSE
);
1624 # if defined(__MWERKS__)
1626 extern void* GC_MacGetDataStart(void);
1627 /* MATTHEW: Function to handle Far Globals (CW Pro 3) */
1628 # if __option(far_data)
1629 extern void* GC_MacGetDataEnd(void);
1631 /* globals begin above stack and end at a5. */
1632 GC_add_roots_inner((ptr_t
)GC_MacGetDataStart(),
1633 (ptr_t
)LMGetCurrentA5(), FALSE
);
1634 /* MATTHEW: Handle Far Globals */
1635 # if __option(far_data)
1636 /* Far globals follow he QD globals: */
1637 GC_add_roots_inner((ptr_t
)LMGetCurrentA5(),
1638 (ptr_t
)GC_MacGetDataEnd(), FALSE
);
1641 extern char __data_start__
[], __data_end__
[];
1642 GC_add_roots_inner((ptr_t
)&__data_start__
,
1643 (ptr_t
)&__data_end__
, FALSE
);
1644 # endif /* __POWERPC__ */
1645 # endif /* __MWERKS__ */
1646 # endif /* !THINK_C */
1650 /* Dynamic libraries are added at every collection, since they may */
1654 # endif /* ! OPENBSD */
1655 # endif /* ! AMIGA */
1656 # endif /* ! MSWIN32 && ! MSWINCE*/
1660 * Auxiliary routines for obtaining memory from OS.
1663 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \
1664 && !defined(MSWIN32) && !defined(MSWINCE) \
1665 && !defined(MACOS) && !defined(DOS4GW) && !defined(SN_TARGET_PS3)
1668 extern caddr_t
sbrk();
1671 # define SBRK_ARG_T ptrdiff_t
1673 # define SBRK_ARG_T int
1677 # if 0 && defined(RS6000) /* We now use mmap */
1678 /* The compiler seems to generate speculative reads one past the end of */
1679 /* an allocated object. Hence we need to make sure that the page */
1680 /* following the last heap page is also mapped. */
1681 ptr_t
GC_unix_get_mem(bytes
)
1684 caddr_t cur_brk
= (caddr_t
)sbrk(0);
1686 SBRK_ARG_T lsbs
= (word
)cur_brk
& (GC_page_size
-1);
1687 static caddr_t my_brk_val
= 0;
1689 if ((SBRK_ARG_T
)bytes
< 0) return(0); /* too big */
1691 if((caddr_t
)(sbrk(GC_page_size
- lsbs
)) == (caddr_t
)(-1)) return(0);
1693 if (cur_brk
== my_brk_val
) {
1694 /* Use the extra block we allocated last time. */
1695 result
= (ptr_t
)sbrk((SBRK_ARG_T
)bytes
);
1696 if (result
== (caddr_t
)(-1)) return(0);
1697 result
-= GC_page_size
;
1699 result
= (ptr_t
)sbrk(GC_page_size
+ (SBRK_ARG_T
)bytes
);
1700 if (result
== (caddr_t
)(-1)) return(0);
1702 my_brk_val
= result
+ bytes
+ GC_page_size
; /* Always page aligned */
1703 return((ptr_t
)result
);
1706 #else /* Not RS6000 */
1708 #if defined(USE_MMAP) || defined(USE_MUNMAP) || defined(FALLBACK_TO_MMAP)
1710 #ifdef USE_MMAP_FIXED
1711 # define GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE
1712 /* Seems to yield better performance on Solaris 2, but can */
1713 /* be unreliable if something is already mapped at the address. */
1715 # define GC_MMAP_FLAGS MAP_PRIVATE
1718 #ifdef USE_MMAP_ANON
1720 # if defined(MAP_ANONYMOUS)
1721 # define OPT_MAP_ANON MAP_ANONYMOUS
1723 # define OPT_MAP_ANON MAP_ANON
1727 # define OPT_MAP_ANON 0
1730 #endif /* defined(USE_MMAP) || defined(USE_MUNMAP) */
1732 #if defined(USE_MMAP) || defined(FALLBACK_TO_MMAP)
1733 /* Tested only under Linux, IRIX5 and Solaris 2 */
1736 # define HEAP_START 0
1739 #ifdef FALLBACK_TO_MMAP
1740 static ptr_t
GC_unix_get_mem_mmap(bytes
)
1742 ptr_t
GC_unix_get_mem(bytes
)
1747 static ptr_t last_addr
= HEAP_START
;
1749 # ifndef USE_MMAP_ANON
1750 static GC_bool initialized
= FALSE
;
1753 zero_fd
= open("/dev/zero", O_RDONLY
);
1754 fcntl(zero_fd
, F_SETFD
, FD_CLOEXEC
);
1759 if (bytes
& (GC_page_size
-1)) ABORT("Bad GET_MEM arg");
1760 result
= mmap(last_addr
, bytes
, PROT_READ
| PROT_WRITE
| OPT_PROT_EXEC
,
1761 GC_MMAP_FLAGS
| OPT_MAP_ANON
, zero_fd
, 0/* offset */);
1762 if (result
== MAP_FAILED
) return(0);
1763 last_addr
= (ptr_t
)result
+ bytes
+ GC_page_size
- 1;
1764 last_addr
= (ptr_t
)((word
)last_addr
& ~(GC_page_size
- 1));
1765 # if !defined(LINUX)
1766 if (last_addr
== 0) {
1767 /* Oops. We got the end of the address space. This isn't */
1768 /* usable by arbitrary C code, since one-past-end pointers */
1769 /* don't work, so we discard it and try again. */
1770 munmap(result
, (size_t)(-GC_page_size
) - (size_t)result
);
1771 /* Leave last page mapped, so we can't repeat. */
1772 return GC_unix_get_mem(bytes
);
1775 GC_ASSERT(last_addr
!= 0);
1777 if (((word
)result
% HBLKSIZE
) != 0)
1778 ABORT ("GC_unix_get_mem: Memory returned by mmap is not aligned to HBLKSIZE.");
1779 return((ptr_t
)result
);
1786 ptr_t
GC_unix_get_mem(bytes
)
1791 /* Bare sbrk isn't thread safe. Play by malloc rules. */
1792 /* The equivalent may be needed on other systems as well. */
1796 ptr_t cur_brk
= (ptr_t
)sbrk(0);
1797 SBRK_ARG_T lsbs
= (word
)cur_brk
& (GC_page_size
-1);
1799 if ((SBRK_ARG_T
)bytes
< 0) return(0); /* too big */
1801 if((ptr_t
)sbrk(GC_page_size
- lsbs
) == (ptr_t
)(-1)) return(0);
1803 result
= (ptr_t
)sbrk((SBRK_ARG_T
)bytes
);
1804 if (result
== (ptr_t
)(-1)) {
1805 #ifdef FALLBACK_TO_MMAP
1806 result
= GC_unix_get_mem_mmap (bytes
);
1818 #endif /* Not USE_MMAP */
1819 #endif /* Not RS6000 */
1825 void * os2_alloc(size_t bytes
)
1829 if (DosAllocMem(&result
, bytes
, PAG_EXECUTE
| PAG_READ
|
1830 PAG_WRITE
| PAG_COMMIT
)
1834 if (result
== 0) return(os2_alloc(bytes
));
1841 # if defined(MSWIN32) || defined(MSWINCE)
1842 SYSTEM_INFO GC_sysinfo
;
1847 # ifdef USE_GLOBAL_ALLOC
1848 # define GLOBAL_ALLOC_TEST 1
1850 # define GLOBAL_ALLOC_TEST GC_no_win32_dlls
1853 word GC_n_heap_bases
= 0;
1855 ptr_t
GC_win32_get_mem(bytes
)
1860 if (GLOBAL_ALLOC_TEST
) {
1861 /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE. */
1862 /* There are also unconfirmed rumors of other */
1863 /* problems, so we dodge the issue. */
1864 result
= (ptr_t
) GlobalAlloc(0, bytes
+ HBLKSIZE
);
1865 result
= (ptr_t
)(((word
)result
+ HBLKSIZE
) & ~(HBLKSIZE
-1));
1867 /* VirtualProtect only works on regions returned by a */
1868 /* single VirtualAlloc call. Thus we allocate one */
1869 /* extra page, which will prevent merging of blocks */
1870 /* in separate regions, and eliminate any temptation */
1871 /* to call VirtualProtect on a range spanning regions. */
1872 /* This wastes a small amount of memory, and risks */
1873 /* increased fragmentation. But better alternatives */
1874 /* would require effort. */
1875 result
= (ptr_t
) VirtualAlloc(NULL
, bytes
+ 1,
1876 MEM_COMMIT
| MEM_RESERVE
,
1877 PAGE_EXECUTE_READWRITE
);
1879 if (HBLKDISPL(result
) != 0) ABORT("Bad VirtualAlloc result");
1880 /* If I read the documentation correctly, this can */
1881 /* only happen if HBLKSIZE > 64k or not a power of 2. */
1882 if (GC_n_heap_bases
>= MAX_HEAP_SECTS
) ABORT("Too many heap sections");
1883 GC_heap_bases
[GC_n_heap_bases
++] = result
;
1887 void GC_win32_free_heap ()
1889 if (GC_no_win32_dlls
) {
1890 while (GC_n_heap_bases
> 0) {
1891 GlobalFree (GC_heap_bases
[--GC_n_heap_bases
]);
1892 GC_heap_bases
[GC_n_heap_bases
] = 0;
1899 # define GC_AMIGA_AM
1900 # include "AmigaOS.c"
1906 word GC_n_heap_bases
= 0;
1908 ptr_t
GC_wince_get_mem(bytes
)
1914 /* Round up allocation size to multiple of page size */
1915 bytes
= (bytes
+ GC_page_size
-1) & ~(GC_page_size
-1);
1917 /* Try to find reserved, uncommitted pages */
1918 for (i
= 0; i
< GC_n_heap_bases
; i
++) {
1919 if (((word
)(-(signed_word
)GC_heap_lengths
[i
])
1920 & (GC_sysinfo
.dwAllocationGranularity
-1))
1922 result
= GC_heap_bases
[i
] + GC_heap_lengths
[i
];
1927 if (i
== GC_n_heap_bases
) {
1928 /* Reserve more pages */
1929 word res_bytes
= (bytes
+ GC_sysinfo
.dwAllocationGranularity
-1)
1930 & ~(GC_sysinfo
.dwAllocationGranularity
-1);
1931 /* If we ever support MPROTECT_VDB here, we will probably need to */
1932 /* ensure that res_bytes is strictly > bytes, so that VirtualProtect */
1933 /* never spans regions. It seems to be OK for a VirtualFree argument */
1934 /* to span regions, so we should be OK for now. */
1935 result
= (ptr_t
) VirtualAlloc(NULL
, res_bytes
,
1936 MEM_RESERVE
| MEM_TOP_DOWN
,
1937 PAGE_EXECUTE_READWRITE
);
1938 if (HBLKDISPL(result
) != 0) ABORT("Bad VirtualAlloc result");
1939 /* If I read the documentation correctly, this can */
1940 /* only happen if HBLKSIZE > 64k or not a power of 2. */
1941 if (GC_n_heap_bases
>= MAX_HEAP_SECTS
) ABORT("Too many heap sections");
1942 GC_heap_bases
[GC_n_heap_bases
] = result
;
1943 GC_heap_lengths
[GC_n_heap_bases
] = 0;
1948 result
= (ptr_t
) VirtualAlloc(result
, bytes
,
1950 PAGE_EXECUTE_READWRITE
);
1951 if (result
!= NULL
) {
1952 if (HBLKDISPL(result
) != 0) ABORT("Bad VirtualAlloc result");
1953 GC_heap_lengths
[i
] += bytes
;
1962 /* For now, this only works on Win32/WinCE and some Unix-like */
1963 /* systems. If you have something else, don't define */
1965 /* We assume ANSI C to support this feature. */
1967 #if !defined(MSWIN32) && !defined(MSWINCE)
1970 #include <sys/mman.h>
1971 #include <sys/stat.h>
1972 #include <sys/types.h>
1976 /* Compute a page aligned starting address for the unmap */
1977 /* operation on a block of size bytes starting at start. */
1978 /* Return 0 if the block is too small to make this feasible. */
1979 ptr_t
GC_unmap_start(ptr_t start
, word bytes
)
1981 ptr_t result
= start
;
1982 /* Round start to next page boundary. */
1983 result
+= GC_page_size
- 1;
1984 result
= (ptr_t
)((word
)result
& ~(GC_page_size
- 1));
1985 if (result
+ GC_page_size
> start
+ bytes
) return 0;
1989 /* Compute end address for an unmap operation on the indicated */
1991 ptr_t
GC_unmap_end(ptr_t start
, word bytes
)
1993 ptr_t end_addr
= start
+ bytes
;
1994 end_addr
= (ptr_t
)((word
)end_addr
& ~(GC_page_size
- 1));
1998 /* Under Win32/WinCE we commit (map) and decommit (unmap) */
1999 /* memory using VirtualAlloc and VirtualFree. These functions */
2000 /* work on individual allocations of virtual memory, made */
2001 /* previously using VirtualAlloc with the MEM_RESERVE flag. */
2002 /* The ranges we need to (de)commit may span several of these */
2003 /* allocations; therefore we use VirtualQuery to check */
2004 /* allocation lengths, and split up the range as necessary. */
2006 /* We assume that GC_remap is called on exactly the same range */
2007 /* as a previous call to GC_unmap. It is safe to consistently */
2008 /* round the endpoints in both places. */
2009 void GC_unmap(ptr_t start
, word bytes
)
2011 ptr_t start_addr
= GC_unmap_start(start
, bytes
);
2012 ptr_t end_addr
= GC_unmap_end(start
, bytes
);
2013 word len
= end_addr
- start_addr
;
2014 if (0 == start_addr
) return;
2015 # if defined(MSWIN32) || defined(MSWINCE)
2017 MEMORY_BASIC_INFORMATION mem_info
;
2019 if (VirtualQuery(start_addr
, &mem_info
, sizeof(mem_info
))
2020 != sizeof(mem_info
))
2021 ABORT("Weird VirtualQuery result");
2022 free_len
= (len
< mem_info
.RegionSize
) ? len
: mem_info
.RegionSize
;
2023 if (!VirtualFree(start_addr
, free_len
, MEM_DECOMMIT
))
2024 ABORT("VirtualFree failed");
2025 GC_unmapped_bytes
+= free_len
;
2026 start_addr
+= free_len
;
2030 /* We immediately remap it to prevent an intervening mmap from */
2031 /* accidentally grabbing the same address space. */
2034 result
= mmap(start_addr
, len
, PROT_NONE
,
2035 MAP_PRIVATE
| MAP_FIXED
| OPT_MAP_ANON
,
2036 zero_fd
, 0/* offset */);
2037 if (result
!= (void *)start_addr
) ABORT("mmap(...PROT_NONE...) failed");
2039 GC_unmapped_bytes
+= len
;
2044 void GC_remap(ptr_t start
, word bytes
)
2046 ptr_t start_addr
= GC_unmap_start(start
, bytes
);
2047 ptr_t end_addr
= GC_unmap_end(start
, bytes
);
2048 word len
= end_addr
- start_addr
;
2050 # if defined(MSWIN32) || defined(MSWINCE)
2053 if (0 == start_addr
) return;
2055 MEMORY_BASIC_INFORMATION mem_info
;
2057 if (VirtualQuery(start_addr
, &mem_info
, sizeof(mem_info
))
2058 != sizeof(mem_info
))
2059 ABORT("Weird VirtualQuery result");
2060 alloc_len
= (len
< mem_info
.RegionSize
) ? len
: mem_info
.RegionSize
;
2061 result
= VirtualAlloc(start_addr
, alloc_len
,
2063 PAGE_EXECUTE_READWRITE
);
2064 if (result
!= start_addr
) {
2065 ABORT("VirtualAlloc remapping failed");
2067 GC_unmapped_bytes
-= alloc_len
;
2068 start_addr
+= alloc_len
;
2072 /* It was already remapped with PROT_NONE. */
2075 if (0 == start_addr
) return;
2078 /* NaCl doesn't expose mprotect, but mmap should work fine */
2080 mmap_result
= mmap(start_addr
, len
, PROT_READ
| PROT_WRITE
| OPT_PROT_EXEC
,
2081 MAP_PRIVATE
| MAP_FIXED
| OPT_MAP_ANON
,
2082 zero_fd
, 0/* offset */);
2083 if (mmap_result
!= (void *)start_addr
) ABORT("mmap as mprotect failed");
2084 /* Fake the return value as if mprotect succeeded. */
2088 result
= mprotect(start_addr
, len
,
2089 PROT_READ
| PROT_WRITE
| OPT_PROT_EXEC
);
2093 "Mprotect failed at 0x%lx (length %ld) with errno %ld\n",
2094 start_addr
, len
, errno
);
2095 ABORT("Mprotect remapping failed");
2097 GC_unmapped_bytes
-= len
;
2101 /* Two adjacent blocks have already been unmapped and are about to */
2102 /* be merged. Unmap the whole block. This typically requires */
2103 /* that we unmap a small section in the middle that was not previously */
2104 /* unmapped due to alignment constraints. */
2105 void GC_unmap_gap(ptr_t start1
, word bytes1
, ptr_t start2
, word bytes2
)
2107 ptr_t start1_addr
= GC_unmap_start(start1
, bytes1
);
2108 ptr_t end1_addr
= GC_unmap_end(start1
, bytes1
);
2109 ptr_t start2_addr
= GC_unmap_start(start2
, bytes2
);
2110 ptr_t end2_addr
= GC_unmap_end(start2
, bytes2
);
2111 ptr_t start_addr
= end1_addr
;
2112 ptr_t end_addr
= start2_addr
;
2114 GC_ASSERT(start1
+ bytes1
== start2
);
2115 if (0 == start1_addr
) start_addr
= GC_unmap_start(start1
, bytes1
+ bytes2
);
2116 if (0 == start2_addr
) end_addr
= GC_unmap_end(start1
, bytes1
+ bytes2
);
2117 if (0 == start_addr
) return;
2118 len
= end_addr
- start_addr
;
2119 # if defined(MSWIN32) || defined(MSWINCE)
2121 MEMORY_BASIC_INFORMATION mem_info
;
2123 if (VirtualQuery(start_addr
, &mem_info
, sizeof(mem_info
))
2124 != sizeof(mem_info
))
2125 ABORT("Weird VirtualQuery result");
2126 free_len
= (len
< mem_info
.RegionSize
) ? len
: mem_info
.RegionSize
;
2127 if (!VirtualFree(start_addr
, free_len
, MEM_DECOMMIT
))
2128 ABORT("VirtualFree failed");
2129 GC_unmapped_bytes
+= free_len
;
2130 start_addr
+= free_len
;
2135 /* Immediately remap as above. */
2137 result
= mmap(start_addr
, len
, PROT_NONE
,
2138 MAP_PRIVATE
| MAP_FIXED
| OPT_MAP_ANON
,
2139 zero_fd
, 0/* offset */);
2140 if (result
!= (void *)start_addr
) ABORT("mmap(...PROT_NONE...) failed");
2142 GC_unmapped_bytes
+= len
;
2146 #endif /* USE_MUNMAP */
2148 /* Routine for pushing any additional roots. In THREADS */
2149 /* environment, this is also responsible for marking from */
2150 /* thread stacks. */
2152 void (*GC_push_other_roots
)() = 0;
2156 PCR_ERes
GC_push_thread_stack(PCR_Th_T
*t
, PCR_Any dummy
)
2158 struct PCR_ThCtl_TInfoRep info
;
2161 info
.ti_stkLow
= info
.ti_stkHi
= 0;
2162 result
= PCR_ThCtl_GetInfo(t
, &info
);
2163 GC_push_all_stack((ptr_t
)(info
.ti_stkLow
), (ptr_t
)(info
.ti_stkHi
));
2167 /* Push the contents of an old object. We treat this as stack */
2168 /* data only becasue that makes it robust against mark stack */
2170 PCR_ERes
GC_push_old_obj(void *p
, size_t size
, PCR_Any data
)
2172 GC_push_all_stack((ptr_t
)p
, (ptr_t
)p
+ size
);
2173 return(PCR_ERes_okay
);
2177 void GC_default_push_other_roots
GC_PROTO((void))
2179 /* Traverse data allocated by previous memory managers. */
2181 extern struct PCR_MM_ProcsRep
* GC_old_allocator
;
2183 if ((*(GC_old_allocator
->mmp_enumerate
))(PCR_Bool_false
,
2186 ABORT("Old object enumeration failed");
2189 /* Traverse all thread stacks. */
2191 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack
,0))
2192 || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
2193 ABORT("Thread stack marking failed\n");
2201 # ifdef ALL_INTERIOR_POINTERS
2205 void GC_push_thread_structures
GC_PROTO((void))
2207 /* Not our responsibibility. */
2210 extern void ThreadF__ProcessStacks();
2212 void GC_push_thread_stack(start
, stop
)
2215 GC_push_all_stack((ptr_t
)start
, (ptr_t
)stop
+ sizeof(word
));
2218 /* Push routine with M3 specific calling convention. */
2219 GC_m3_push_root(dummy1
, p
, dummy2
, dummy3
)
2221 ptr_t dummy1
, dummy2
;
2226 GC_PUSH_ONE_STACK(q
, p
);
2229 /* M3 set equivalent to RTHeap.TracedRefTypes */
2230 typedef struct { int elts
[1]; } RefTypeSet
;
2231 RefTypeSet GC_TracedRefTypes
= {{0x1}};
2233 void GC_default_push_other_roots
GC_PROTO((void))
2235 /* Use the M3 provided routine for finding static roots. */
2236 /* This is a bit dubious, since it presumes no C roots. */
2237 /* We handle the collector roots explicitly in GC_push_roots */
2238 RTMain__GlobalMapProc(GC_m3_push_root
, 0, GC_TracedRefTypes
);
2239 if (GC_words_allocd
> 0) {
2240 ThreadF__ProcessStacks(GC_push_thread_stack
);
2242 /* Otherwise this isn't absolutely necessary, and we have */
2243 /* startup ordering problems. */
2246 # endif /* SRC_M3 */
2248 # if defined(GC_SOLARIS_THREADS) || defined(GC_PTHREADS) || \
2249 defined(GC_WIN32_THREADS)
2251 extern void GC_push_all_stacks();
2253 void GC_default_push_other_roots
GC_PROTO((void))
2255 GC_push_all_stacks();
2258 # endif /* GC_SOLARIS_THREADS || GC_PTHREADS */
2259 #ifdef SN_TARGET_PS3
2260 void GC_default_push_other_roots
GC_PROTO((void))
2262 printf ("WARNING WARNING WARNING\nGC_default_push_other_roots is not implemented\n");
2264 void GC_push_thread_structures
GC_PROTO((void))
2266 printf ("WARNING WARNING WARNING\nGC_default_push_thread_structures is not implemented\n");
2270 void (*GC_push_other_roots
) GC_PROTO((void)) = GC_default_push_other_roots
;
2272 #endif /* THREADS */
2275 * Routines for accessing dirty bits on virtual pages.
2276 * We plan to eventually implement four strategies for doing so:
2277 * DEFAULT_VDB: A simple dummy implementation that treats every page
2278 * as possibly dirty. This makes incremental collection
2279 * useless, but the implementation is still correct.
2280 * PCR_VDB: Use PPCRs virtual dirty bit facility.
2281 * PROC_VDB: Use the /proc facility for reading dirty bits. Only
2282 * works under some SVR4 variants. Even then, it may be
2283 * too slow to be entirely satisfactory. Requires reading
2284 * dirty bits for entire address space. Implementations tend
2285 * to assume that the client is a (slow) debugger.
2286 * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
2287 * dirtied pages. The implementation (and implementability)
2288 * is highly system dependent. This usually fails when system
2289 * calls write to a protected page. We prevent the read system
2290 * call from doing so. It is the clients responsibility to
2291 * make sure that other system calls are similarly protected
2292 * or write only to the stack.
2294 GC_bool GC_dirty_maintained
= FALSE
;
2298 /* All of the following assume the allocation lock is held, and */
2299 /* signals are disabled. */
2301 /* The client asserts that unallocated pages in the heap are never */
2304 /* Initialize virtual dirty bit implementation. */
2305 void GC_dirty_init()
2308 GC_printf0("Initializing DEFAULT_VDB...\n");
2310 GC_dirty_maintained
= TRUE
;
2313 /* Retrieve system dirty bits for heap to a local buffer. */
2314 /* Restore the systems notion of which pages are dirty. */
2315 void GC_read_dirty()
2318 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */
2319 /* If the actual page size is different, this returns TRUE if any */
2320 /* of the pages overlapping h are dirty. This routine may err on the */
2321 /* side of labelling pages as dirty (and this implementation does). */
2323 GC_bool
GC_page_was_dirty(h
)
2330 * The following two routines are typically less crucial. They matter
2331 * most with large dynamic libraries, or if we can't accurately identify
2332 * stacks, e.g. under Solaris 2.X. Otherwise the following default
2333 * versions are adequate.
2336 /* Could any valid GC heap pointer ever have been written to this page? */
2338 GC_bool
GC_page_was_ever_dirty(h
)
2344 /* Reset the n pages starting at h to "was never dirty" status. */
2345 void GC_is_fresh(h
, n
)
2352 /* I) hints that [h, h+nblocks) is about to be written. */
2353 /* II) guarantees that protection is removed. */
2354 /* (I) may speed up some dirty bit implementations. */
2355 /* (II) may be essential if we need to ensure that */
2356 /* pointer-free system call buffers in the heap are */
2357 /* not protected. */
2359 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
2366 # endif /* DEFAULT_VDB */
2369 # ifdef MPROTECT_VDB
2372 * See DEFAULT_VDB for interface descriptions.
2376 * This implementation maintains dirty bits itself by catching write
2377 * faults and keeping track of them. We assume nobody else catches
2378 * SIGBUS or SIGSEGV. We assume no write faults occur in system calls.
2379 * This means that clients must ensure that system calls don't write
2380 * to the write-protected heap. Probably the best way to do this is to
2381 * ensure that system calls write at most to POINTERFREE objects in the
2382 * heap, and do even that only if we are on a platform on which those
2383 * are not protected. Another alternative is to wrap system calls
2384 * (see example for read below), but the current implementation holds
2385 * a lock across blocking calls, making it problematic for multithreaded
2387 * We assume the page size is a multiple of HBLKSIZE.
2388 * We prefer them to be the same. We avoid protecting POINTERFREE
2389 * objects only if they are the same.
2392 # if !defined(MSWIN32) && !defined(MSWINCE) && !defined(DARWIN)
2394 # include <sys/mman.h>
2395 # include <signal.h>
2396 # include <sys/syscall.h>
2398 # define PROTECT(addr, len) \
2399 if (mprotect((caddr_t)(addr), (size_t)(len), \
2400 PROT_READ | OPT_PROT_EXEC) < 0) { \
2401 ABORT("mprotect failed"); \
2403 # define UNPROTECT(addr, len) \
2404 if (mprotect((caddr_t)(addr), (size_t)(len), \
2405 PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
2406 ABORT("un-mprotect failed"); \
2412 /* Using vm_protect (mach syscall) over mprotect (BSD syscall) seems to
2413 decrease the likelihood of some of the problems described below. */
2414 #include <mach/vm_map.h>
2415 static mach_port_t GC_task_self
;
2416 #define PROTECT(addr,len) \
2417 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2418 FALSE,VM_PROT_READ) != KERN_SUCCESS) { \
2419 ABORT("vm_portect failed"); \
2421 #define UNPROTECT(addr,len) \
2422 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2423 FALSE,VM_PROT_READ|VM_PROT_WRITE) != KERN_SUCCESS) { \
2424 ABORT("vm_portect failed"); \
2429 # include <signal.h>
2432 static DWORD protect_junk
;
2433 # define PROTECT(addr, len) \
2434 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
2436 DWORD last_error = GetLastError(); \
2437 GC_printf1("Last error code: %lx\n", last_error); \
2438 ABORT("VirtualProtect failed"); \
2440 # define UNPROTECT(addr, len) \
2441 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
2443 ABORT("un-VirtualProtect failed"); \
2445 # endif /* !DARWIN */
2446 # endif /* MSWIN32 || MSWINCE || DARWIN */
2448 #if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2449 typedef void (* SIG_PF
)();
2450 #endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2452 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX) \
2455 typedef void (* SIG_PF
)(int);
2457 typedef void (* SIG_PF
)();
2459 #endif /* SUNOS5SIGS || OSF1 || LINUX || HURD */
2461 #if defined(MSWIN32)
2462 typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF
;
2464 # define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
2466 #if defined(MSWINCE)
2467 typedef LONG (WINAPI
*SIG_PF
)(struct _EXCEPTION_POINTERS
*);
2469 # define SIG_DFL (SIG_PF) (-1)
2472 #if defined(IRIX5) || defined(OSF1) || defined(HURD)
2473 typedef void (* REAL_SIG_PF
)(int, int, struct sigcontext
*);
2474 #endif /* IRIX5 || OSF1 || HURD */
2476 #if defined(SUNOS5SIGS)
2477 # if defined(HPUX) || defined(FREEBSD)
2478 # define SIGINFO_T siginfo_t
2480 # define SIGINFO_T struct siginfo
2483 typedef void (* REAL_SIG_PF
)(int, SIGINFO_T
*, void *);
2485 typedef void (* REAL_SIG_PF
)();
2487 #endif /* SUNOS5SIGS */
2490 # if __GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ >= 2
2491 typedef struct sigcontext s_c
;
2492 # else /* glibc < 2.2 */
2493 # include <linux/version.h>
2494 # if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA) || defined(ARM32)
2495 typedef struct sigcontext s_c
;
2497 typedef struct sigcontext_struct s_c
;
2499 # endif /* glibc < 2.2 */
2500 # if defined(ALPHA) || defined(M68K)
2501 typedef void (* REAL_SIG_PF
)(int, int, s_c
*);
2503 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2504 typedef void (* REAL_SIG_PF
)(int, siginfo_t
*, s_c
*);
2506 /* According to SUSV3, the last argument should have type */
2507 /* void * or ucontext_t * */
2509 typedef void (* REAL_SIG_PF
)(int, s_c
);
2513 /* Retrieve fault address from sigcontext structure by decoding */
2515 char * get_fault_addr(s_c
*sc
) {
2519 instr
= *((unsigned *)(sc
->sc_pc
));
2520 faultaddr
= sc
->sc_regs
[(instr
>> 16) & 0x1f];
2521 faultaddr
+= (word
) (((int)instr
<< 16) >> 16);
2522 return (char *)faultaddr
;
2524 # endif /* !ALPHA */
2528 SIG_PF GC_old_bus_handler
;
2529 SIG_PF GC_old_segv_handler
; /* Also old MSWIN32 ACCESS_VIOLATION filter */
2530 #endif /* !DARWIN */
2532 #if defined(THREADS)
2533 /* We need to lock around the bitmap update in the write fault handler */
2534 /* in order to avoid the risk of losing a bit. We do this with a */
2535 /* test-and-set spin lock if we know how to do that. Otherwise we */
2536 /* check whether we are already in the handler and use the dumb but */
2537 /* safe fallback algorithm of setting all bits in the word. */
2538 /* Contention should be very rare, so we do the minimum to handle it */
2540 #ifdef GC_TEST_AND_SET_DEFINED
2541 static VOLATILE
unsigned int fault_handler_lock
= 0;
2542 void async_set_pht_entry_from_index(VOLATILE page_hash_table db
, int index
) {
2543 while (GC_test_and_set(&fault_handler_lock
)) {}
2544 /* Could also revert to set_pht_entry_from_index_safe if initial */
2545 /* GC_test_and_set fails. */
2546 set_pht_entry_from_index(db
, index
);
2547 GC_clear(&fault_handler_lock
);
2549 #else /* !GC_TEST_AND_SET_DEFINED */
2550 /* THIS IS INCORRECT! The dirty bit vector may be temporarily wrong, */
2551 /* just before we notice the conflict and correct it. We may end up */
2552 /* looking at it while it's wrong. But this requires contention */
2553 /* exactly when a GC is triggered, which seems far less likely to */
2554 /* fail than the old code, which had no reported failures. Thus we */
2555 /* leave it this way while we think of something better, or support */
2556 /* GC_test_and_set on the remaining platforms. */
2557 static VOLATILE word currently_updating
= 0;
2558 void async_set_pht_entry_from_index(VOLATILE page_hash_table db
, int index
) {
2559 unsigned int update_dummy
;
2560 currently_updating
= (word
)(&update_dummy
);
2561 set_pht_entry_from_index(db
, index
);
2562 /* If we get contention in the 10 or so instruction window here, */
2563 /* and we get stopped by a GC between the two updates, we lose! */
2564 if (currently_updating
!= (word
)(&update_dummy
)) {
2565 set_pht_entry_from_index_safe(db
, index
);
2566 /* We claim that if two threads concurrently try to update the */
2567 /* dirty bit vector, the first one to execute UPDATE_START */
2568 /* will see it changed when UPDATE_END is executed. (Note that */
2569 /* &update_dummy must differ in two distinct threads.) It */
2570 /* will then execute set_pht_entry_from_index_safe, thus */
2571 /* returning us to a safe state, though not soon enough. */
2574 #endif /* !GC_TEST_AND_SET_DEFINED */
2575 #else /* !THREADS */
2576 # define async_set_pht_entry_from_index(db, index) \
2577 set_pht_entry_from_index(db, index)
2578 #endif /* !THREADS */
2581 #if !defined(DARWIN)
2582 # if defined (SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2583 void GC_write_fault_handler(sig
, code
, scp
, addr
)
2585 struct sigcontext
*scp
;
2588 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2589 # define CODE_OK (FC_CODE(code) == FC_PROT \
2590 || (FC_CODE(code) == FC_OBJERR \
2591 && FC_ERRNO(code) == FC_PROT))
2594 # define SIG_OK (sig == SIGBUS)
2595 # define CODE_OK TRUE
2597 # endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2599 # if defined(IRIX5) || defined(OSF1) || defined(HURD)
2601 void GC_write_fault_handler(int sig
, int code
, struct sigcontext
*scp
)
2603 # define SIG_OK (sig == SIGSEGV)
2604 # define CODE_OK (code == 2 /* experimentally determined */)
2607 # define SIG_OK (sig == SIGSEGV)
2608 # define CODE_OK (code == EACCES)
2611 # define SIG_OK (sig == SIGBUS || sig == SIGSEGV)
2612 # define CODE_OK TRUE
2614 # endif /* IRIX5 || OSF1 || HURD */
2617 # if defined(ALPHA) || defined(M68K)
2618 void GC_write_fault_handler(int sig
, int code
, s_c
* sc
)
2620 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2621 void GC_write_fault_handler(int sig
, siginfo_t
* si
, s_c
* scp
)
2624 void GC_write_fault_handler(int sig
, int a2
, int a3
, int a4
, s_c sc
)
2626 void GC_write_fault_handler(int sig
, s_c sc
)
2630 # define SIG_OK (sig == SIGSEGV)
2631 # define CODE_OK TRUE
2632 /* Empirically c.trapno == 14, on IA32, but is that useful? */
2633 /* Should probably consider alignment issues on other */
2634 /* architectures. */
2637 # if defined(SUNOS5SIGS)
2639 void GC_write_fault_handler(int sig
, SIGINFO_T
*scp
, void * context
)
2641 void GC_write_fault_handler(sig
, scp
, context
)
2647 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2648 # define CODE_OK (scp -> si_code == SEGV_ACCERR) \
2649 || (scp -> si_code == BUS_ADRERR) \
2650 || (scp -> si_code == BUS_UNKNOWN) \
2651 || (scp -> si_code == SEGV_UNKNOWN) \
2652 || (scp -> si_code == BUS_OBJERR)
2655 # define SIG_OK (sig == SIGBUS)
2656 # define CODE_OK (scp -> si_code == BUS_PAGE_FAULT)
2658 # define SIG_OK (sig == SIGSEGV)
2659 # define CODE_OK (scp -> si_code == SEGV_ACCERR)
2662 # endif /* SUNOS5SIGS */
2664 # if defined(MSWIN32) || defined(MSWINCE)
2665 LONG WINAPI
GC_write_fault_handler(struct _EXCEPTION_POINTERS
*exc_info
)
2666 # define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
2667 STATUS_ACCESS_VIOLATION)
2668 # define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
2670 # endif /* MSWIN32 || MSWINCE */
2672 register unsigned i
;
2674 char *addr
= (char *) code
;
2677 char * addr
= (char *) (size_t) (scp
-> sc_badvaddr
);
2679 # if defined(OSF1) && defined(ALPHA)
2680 char * addr
= (char *) (scp
-> sc_traparg_a0
);
2683 char * addr
= (char *) (scp
-> si_addr
);
2687 char * addr
= (char *) (sc
.cr2
);
2692 struct sigcontext
*scp
= (struct sigcontext
*)(sc
);
2694 int format
= (scp
->sc_formatvec
>> 12) & 0xf;
2695 unsigned long *framedata
= (unsigned long *)(scp
+ 1);
2698 if (format
== 0xa || format
== 0xb) {
2701 } else if (format
== 7) {
2704 if (framedata
[1] & 0x08000000) {
2705 /* correct addr on misaligned access */
2706 ea
= (ea
+4095)&(~4095);
2708 } else if (format
== 4) {
2711 if (framedata
[1] & 0x08000000) {
2712 /* correct addr on misaligned access */
2713 ea
= (ea
+4095)&(~4095);
2719 char * addr
= get_fault_addr(sc
);
2721 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2722 char * addr
= si
-> si_addr
;
2723 /* I believe this is claimed to work on all platforms for */
2724 /* Linux 2.3.47 and later. Hopefully we don't have to */
2725 /* worry about earlier kernels on IA64. */
2727 # if defined(POWERPC)
2728 char * addr
= (char *) (sc
.regs
->dar
);
2731 char * addr
= (char *)sc
.fault_address
;
2734 char * addr
= (char *)sc
.regs
.csraddr
;
2736 --> architecture
not supported
2745 # if defined(MSWIN32) || defined(MSWINCE)
2746 char * addr
= (char *) (exc_info
-> ExceptionRecord
2747 -> ExceptionInformation
[1]);
2748 # define sig SIGSEGV
2751 if (SIG_OK
&& CODE_OK
) {
2752 register struct hblk
* h
=
2753 (struct hblk
*)((word
)addr
& ~(GC_page_size
-1));
2754 GC_bool in_allocd_block
;
2757 /* Address is only within the correct physical page. */
2758 in_allocd_block
= FALSE
;
2759 for (i
= 0; i
< divHBLKSZ(GC_page_size
); i
++) {
2760 if (HDR(h
+i
) != 0) {
2761 in_allocd_block
= TRUE
;
2765 in_allocd_block
= (HDR(addr
) != 0);
2767 if (!in_allocd_block
) {
2768 /* FIXME - We should make sure that we invoke the */
2769 /* old handler with the appropriate calling */
2770 /* sequence, which often depends on SA_SIGINFO. */
2772 /* Heap blocks now begin and end on page boundaries */
2775 if (sig
== SIGSEGV
) {
2776 old_handler
= GC_old_segv_handler
;
2778 old_handler
= GC_old_bus_handler
;
2780 if (old_handler
== SIG_DFL
) {
2781 # if !defined(MSWIN32) && !defined(MSWINCE)
2782 GC_err_printf1("Segfault at 0x%lx\n", addr
);
2783 ABORT("Unexpected bus error or segmentation fault");
2785 return(EXCEPTION_CONTINUE_SEARCH
);
2788 # if defined (SUNOS4) \
2789 || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2790 (*old_handler
) (sig
, code
, scp
, addr
);
2793 # if defined (SUNOS5SIGS)
2795 * FIXME: For FreeBSD, this code should check if the
2796 * old signal handler used the traditional BSD style and
2797 * if so call it using that style.
2799 (*(REAL_SIG_PF
)old_handler
) (sig
, scp
, context
);
2802 # if defined (LINUX)
2803 # if defined(ALPHA) || defined(M68K)
2804 (*(REAL_SIG_PF
)old_handler
) (sig
, code
, sc
);
2806 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2807 (*(REAL_SIG_PF
)old_handler
) (sig
, si
, scp
);
2809 (*(REAL_SIG_PF
)old_handler
) (sig
, sc
);
2814 # if defined (IRIX5) || defined(OSF1) || defined(HURD)
2815 (*(REAL_SIG_PF
)old_handler
) (sig
, code
, scp
);
2819 return((*old_handler
)(exc_info
));
2823 UNPROTECT(h
, GC_page_size
);
2824 /* We need to make sure that no collection occurs between */
2825 /* the UNPROTECT and the setting of the dirty bit. Otherwise */
2826 /* a write by a third thread might go unnoticed. Reversing */
2827 /* the order is just as bad, since we would end up unprotecting */
2828 /* a page in a GC cycle during which it's not marked. */
2829 /* Currently we do this by disabling the thread stopping */
2830 /* signals while this handler is running. An alternative might */
2831 /* be to record the fact that we're about to unprotect, or */
2832 /* have just unprotected a page in the GC's thread structure, */
2833 /* and then to have the thread stopping code set the dirty */
2834 /* flag, if necessary. */
2835 for (i
= 0; i
< divHBLKSZ(GC_page_size
); i
++) {
2836 register int index
= PHT_HASH(h
+i
);
2838 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
2841 /* These reset the signal handler each time by default. */
2842 signal(SIGSEGV
, (SIG_PF
) GC_write_fault_handler
);
2844 /* The write may not take place before dirty bits are read. */
2845 /* But then we'll fault again ... */
2846 # if defined(MSWIN32) || defined(MSWINCE)
2847 return(EXCEPTION_CONTINUE_EXECUTION
);
2852 #if defined(MSWIN32) || defined(MSWINCE)
2853 return EXCEPTION_CONTINUE_SEARCH
;
2855 GC_err_printf1("Segfault at 0x%lx\n", addr
);
2856 ABORT("Unexpected bus error or segmentation fault");
2859 #endif /* !DARWIN */
2862 * We hold the allocation lock. We expect block h to be written
2863 * shortly. Ensure that all pages containing any part of the n hblks
2864 * starting at h are no longer protected. If is_ptrfree is false,
2865 * also ensure that they will subsequently appear to be dirty.
2867 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
2872 struct hblk
* h_trunc
; /* Truncated to page boundary */
2873 struct hblk
* h_end
; /* Page boundary following block end */
2874 struct hblk
* current
;
2875 GC_bool found_clean
;
2877 if (!GC_dirty_maintained
) return;
2878 h_trunc
= (struct hblk
*)((word
)h
& ~(GC_page_size
-1));
2879 h_end
= (struct hblk
*)(((word
)(h
+ nblocks
) + GC_page_size
-1)
2880 & ~(GC_page_size
-1));
2881 found_clean
= FALSE
;
2882 for (current
= h_trunc
; current
< h_end
; ++current
) {
2883 int index
= PHT_HASH(current
);
2885 if (!is_ptrfree
|| current
< h
|| current
>= h
+ nblocks
) {
2886 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
2889 UNPROTECT(h_trunc
, (ptr_t
)h_end
- (ptr_t
)h_trunc
);
2892 #if !defined(DARWIN)
2893 void GC_dirty_init()
2895 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(LINUX) || \
2896 defined(OSF1) || defined(HURD)
2897 struct sigaction act
, oldact
;
2898 /* We should probably specify SA_SIGINFO for Linux, and handle */
2899 /* the different architectures more uniformly. */
2900 # if defined(IRIX5) || defined(LINUX) && !defined(X86_64) \
2901 || defined(OSF1) || defined(HURD)
2902 act
.sa_flags
= SA_RESTART
;
2903 act
.sa_handler
= (SIG_PF
)GC_write_fault_handler
;
2905 act
.sa_flags
= SA_RESTART
| SA_SIGINFO
;
2906 act
.sa_sigaction
= GC_write_fault_handler
;
2908 (void)sigemptyset(&act
.sa_mask
);
2910 /* Arrange to postpone SIG_SUSPEND while we're in a write fault */
2911 /* handler. This effectively makes the handler atomic w.r.t. */
2912 /* stopping the world for GC. */
2913 (void)sigaddset(&act
.sa_mask
, SIG_SUSPEND
);
2914 # endif /* SIG_SUSPEND */
2917 GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2919 GC_dirty_maintained
= TRUE
;
2920 if (GC_page_size
% HBLKSIZE
!= 0) {
2921 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
2922 ABORT("Page size not multiple of HBLKSIZE");
2924 # if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2925 GC_old_bus_handler
= signal(SIGBUS
, GC_write_fault_handler
);
2926 if (GC_old_bus_handler
== SIG_IGN
) {
2927 GC_err_printf0("Previously ignored bus error!?");
2928 GC_old_bus_handler
= SIG_DFL
;
2930 if (GC_old_bus_handler
!= SIG_DFL
) {
2932 GC_err_printf0("Replaced other SIGBUS handler\n");
2936 # if defined(SUNOS4)
2937 GC_old_segv_handler
= signal(SIGSEGV
, (SIG_PF
)GC_write_fault_handler
);
2938 if (GC_old_segv_handler
== SIG_IGN
) {
2939 GC_err_printf0("Previously ignored segmentation violation!?");
2940 GC_old_segv_handler
= SIG_DFL
;
2942 if (GC_old_segv_handler
!= SIG_DFL
) {
2944 GC_err_printf0("Replaced other SIGSEGV handler\n");
2948 # if (defined(SUNOS5SIGS) && !defined(FREEBSD)) || defined(IRIX5) \
2949 || defined(LINUX) || defined(OSF1) || defined(HURD)
2950 /* SUNOS5SIGS includes HPUX */
2951 # if defined(GC_IRIX_THREADS)
2952 sigaction(SIGSEGV
, 0, &oldact
);
2953 sigaction(SIGSEGV
, &act
, 0);
2956 int res
= sigaction(SIGSEGV
, &act
, &oldact
);
2957 if (res
!= 0) ABORT("Sigaction failed");
2960 # if defined(_sigargs) || defined(HURD) || !defined(SA_SIGINFO)
2961 /* This is Irix 5.x, not 6.x. Irix 5.x does not have */
2963 GC_old_segv_handler
= oldact
.sa_handler
;
2964 # else /* Irix 6.x or SUNOS5SIGS or LINUX */
2965 if (oldact
.sa_flags
& SA_SIGINFO
) {
2966 GC_old_segv_handler
= (SIG_PF
)(oldact
.sa_sigaction
);
2968 GC_old_segv_handler
= oldact
.sa_handler
;
2971 if (GC_old_segv_handler
== SIG_IGN
) {
2972 GC_err_printf0("Previously ignored segmentation violation!?");
2973 GC_old_segv_handler
= SIG_DFL
;
2975 if (GC_old_segv_handler
!= SIG_DFL
) {
2977 GC_err_printf0("Replaced other SIGSEGV handler\n");
2980 # endif /* (SUNOS5SIGS && !FREEBSD) || IRIX5 || LINUX || OSF1 || HURD */
2981 # if defined(HPUX) || defined(LINUX) || defined(HURD) \
2982 || (defined(FREEBSD) && defined(SUNOS5SIGS))
2983 sigaction(SIGBUS
, &act
, &oldact
);
2984 GC_old_bus_handler
= oldact
.sa_handler
;
2985 if (GC_old_bus_handler
== SIG_IGN
) {
2986 GC_err_printf0("Previously ignored bus error!?");
2987 GC_old_bus_handler
= SIG_DFL
;
2989 if (GC_old_bus_handler
!= SIG_DFL
) {
2991 GC_err_printf0("Replaced other SIGBUS handler\n");
2994 # endif /* HPUX || LINUX || HURD || (FREEBSD && SUNOS5SIGS) */
2995 # if defined(MSWIN32)
2996 GC_old_segv_handler
= SetUnhandledExceptionFilter(GC_write_fault_handler
);
2997 if (GC_old_segv_handler
!= NULL
) {
2999 GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
3002 GC_old_segv_handler
= SIG_DFL
;
3006 #endif /* !DARWIN */
3008 int GC_incremental_protection_needs()
3010 if (GC_page_size
== HBLKSIZE
) {
3011 return GC_PROTECTS_POINTER_HEAP
;
3013 return GC_PROTECTS_POINTER_HEAP
| GC_PROTECTS_PTRFREE_HEAP
;
3017 #define HAVE_INCREMENTAL_PROTECTION_NEEDS
3019 #define IS_PTRFREE(hhdr) ((hhdr)->hb_descr == 0)
3021 #define PAGE_ALIGNED(x) !((word)(x) & (GC_page_size - 1))
3022 void GC_protect_heap()
3026 struct hblk
* current
;
3027 struct hblk
* current_start
; /* Start of block to be protected. */
3028 struct hblk
* limit
;
3030 GC_bool protect_all
=
3031 (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP
));
3032 for (i
= 0; i
< GC_n_heap_sects
; i
++) {
3033 start
= GC_heap_sects
[i
].hs_start
;
3034 len
= GC_heap_sects
[i
].hs_bytes
;
3036 PROTECT(start
, len
);
3038 GC_ASSERT(PAGE_ALIGNED(len
))
3039 GC_ASSERT(PAGE_ALIGNED(start
))
3040 current_start
= current
= (struct hblk
*)start
;
3041 limit
= (struct hblk
*)(start
+ len
);
3042 while (current
< limit
) {
3047 GC_ASSERT(PAGE_ALIGNED(current
));
3048 GET_HDR(current
, hhdr
);
3049 if (IS_FORWARDING_ADDR_OR_NIL(hhdr
)) {
3050 /* This can happen only if we're at the beginning of a */
3051 /* heap segment, and a block spans heap segments. */
3052 /* We will handle that block as part of the preceding */
3054 GC_ASSERT(current_start
== current
);
3055 current_start
= ++current
;
3058 if (HBLK_IS_FREE(hhdr
)) {
3059 GC_ASSERT(PAGE_ALIGNED(hhdr
-> hb_sz
));
3060 nhblks
= divHBLKSZ(hhdr
-> hb_sz
);
3061 is_ptrfree
= TRUE
; /* dirty on alloc */
3063 nhblks
= OBJ_SZ_TO_BLOCKS(hhdr
-> hb_sz
);
3064 is_ptrfree
= IS_PTRFREE(hhdr
);
3067 if (current_start
< current
) {
3068 PROTECT(current_start
, (ptr_t
)current
- (ptr_t
)current_start
);
3070 current_start
= (current
+= nhblks
);
3075 if (current_start
< current
) {
3076 PROTECT(current_start
, (ptr_t
)current
- (ptr_t
)current_start
);
3082 /* We assume that either the world is stopped or its OK to lose dirty */
3083 /* bits while this is happenning (as in GC_enable_incremental). */
3084 void GC_read_dirty()
3086 BCOPY((word
*)GC_dirty_pages
, GC_grungy_pages
,
3087 (sizeof GC_dirty_pages
));
3088 BZERO((word
*)GC_dirty_pages
, (sizeof GC_dirty_pages
));
3092 GC_bool
GC_page_was_dirty(h
)
3095 register word index
= PHT_HASH(h
);
3097 return(HDR(h
) == 0 || get_pht_entry_from_index(GC_grungy_pages
, index
));
3101 * Acquiring the allocation lock here is dangerous, since this
3102 * can be called from within GC_call_with_alloc_lock, and the cord
3103 * package does so. On systems that allow nested lock acquisition, this
3105 * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
3108 static GC_bool syscall_acquired_lock
= FALSE
; /* Protected by GC lock. */
3110 void GC_begin_syscall()
3112 if (!I_HOLD_LOCK()) {
3114 syscall_acquired_lock
= TRUE
;
3118 void GC_end_syscall()
3120 if (syscall_acquired_lock
) {
3121 syscall_acquired_lock
= FALSE
;
3126 void GC_unprotect_range(addr
, len
)
3130 struct hblk
* start_block
;
3131 struct hblk
* end_block
;
3132 register struct hblk
*h
;
3135 if (!GC_dirty_maintained
) return;
3136 obj_start
= GC_base(addr
);
3137 if (obj_start
== 0) return;
3138 if (GC_base(addr
+ len
- 1) != obj_start
) {
3139 ABORT("GC_unprotect_range(range bigger than object)");
3141 start_block
= (struct hblk
*)((word
)addr
& ~(GC_page_size
- 1));
3142 end_block
= (struct hblk
*)((word
)(addr
+ len
- 1) & ~(GC_page_size
- 1));
3143 end_block
+= GC_page_size
/HBLKSIZE
- 1;
3144 for (h
= start_block
; h
<= end_block
; h
++) {
3145 register word index
= PHT_HASH(h
);
3147 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
3149 UNPROTECT(start_block
,
3150 ((ptr_t
)end_block
- (ptr_t
)start_block
) + HBLKSIZE
);
3155 /* We no longer wrap read by default, since that was causing too many */
3156 /* problems. It is preferred that the client instead avoids writing */
3157 /* to the write-protected heap with a system call. */
3158 /* This still serves as sample code if you do want to wrap system calls.*/
3160 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(GC_USE_LD_WRAP)
3161 /* Replacement for UNIX system call. */
3162 /* Other calls that write to the heap should be handled similarly. */
3163 /* Note that this doesn't work well for blocking reads: It will hold */
3164 /* the allocation lock for the entire duration of the call. Multithreaded */
3165 /* clients should really ensure that it won't block, either by setting */
3166 /* the descriptor nonblocking, or by calling select or poll first, to */
3167 /* make sure that input is available. */
3168 /* Another, preferred alternative is to ensure that system calls never */
3169 /* write to the protected heap (see above). */
3170 # if defined(__STDC__) && !defined(SUNOS4)
3171 # include <unistd.h>
3172 # include <sys/uio.h>
3173 ssize_t
read(int fd
, void *buf
, size_t nbyte
)
3176 int read(fd
, buf
, nbyte
)
3178 int GC_read(fd
, buf
, nbyte
)
3188 GC_unprotect_range(buf
, (word
)nbyte
);
3189 # if defined(IRIX5) || defined(GC_LINUX_THREADS)
3190 /* Indirect system call may not always be easily available. */
3191 /* We could call _read, but that would interfere with the */
3192 /* libpthread interception of read. */
3193 /* On Linux, we have to be careful with the linuxthreads */
3194 /* read interception. */
3199 iov
.iov_len
= nbyte
;
3200 result
= readv(fd
, &iov
, 1);
3204 result
= __read(fd
, buf
, nbyte
);
3206 /* The two zero args at the end of this list are because one
3207 IA-64 syscall() implementation actually requires six args
3208 to be passed, even though they aren't always used. */
3209 result
= syscall(SYS_read
, fd
, buf
, nbyte
, 0, 0);
3215 #endif /* !MSWIN32 && !MSWINCE && !GC_LINUX_THREADS */
3217 #if defined(GC_USE_LD_WRAP) && !defined(THREADS)
3218 /* We use the GNU ld call wrapping facility. */
3219 /* This requires that the linker be invoked with "--wrap read". */
3220 /* This can be done by passing -Wl,"--wrap read" to gcc. */
3221 /* I'm not sure that this actually wraps whatever version of read */
3222 /* is called by stdio. That code also mentions __read. */
3223 # include <unistd.h>
3224 ssize_t
__wrap_read(int fd
, void *buf
, size_t nbyte
)
3229 GC_unprotect_range(buf
, (word
)nbyte
);
3230 result
= __real_read(fd
, buf
, nbyte
);
3235 /* We should probably also do this for __read, or whatever stdio */
3236 /* actually calls. */
3242 GC_bool
GC_page_was_ever_dirty(h
)
3248 /* Reset the n pages starting at h to "was never dirty" status. */
3250 void GC_is_fresh(h
, n
)
3256 # endif /* MPROTECT_VDB */
3261 * See DEFAULT_VDB for interface descriptions.
3265 * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
3266 * from which we can read page modified bits. This facility is far from
3267 * optimal (e.g. we would like to get the info for only some of the
3268 * address space), but it avoids intercepting system calls.
3272 #include <sys/types.h>
3273 #include <sys/signal.h>
3274 #include <sys/fault.h>
3275 #include <sys/syscall.h>
3276 #include <sys/procfs.h>
3277 #include <sys/stat.h>
3279 #define INITIAL_BUF_SZ 16384
3280 word GC_proc_buf_size
= INITIAL_BUF_SZ
;
3283 #ifdef GC_SOLARIS_THREADS
3284 /* We don't have exact sp values for threads. So we count on */
3285 /* occasionally declaring stack pages to be fresh. Thus we */
3286 /* need a real implementation of GC_is_fresh. We can't clear */
3287 /* entries in GC_written_pages, since that would declare all */
3288 /* pages with the given hash address to be fresh. */
3289 # define MAX_FRESH_PAGES 8*1024 /* Must be power of 2 */
3290 struct hblk
** GC_fresh_pages
; /* A direct mapped cache. */
3291 /* Collisions are dropped. */
3293 # define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
3294 # define ADD_FRESH_PAGE(h) \
3295 GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
3296 # define PAGE_IS_FRESH(h) \
3297 (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
3300 /* Add all pages in pht2 to pht1 */
3301 void GC_or_pages(pht1
, pht2
)
3302 page_hash_table pht1
, pht2
;
3306 for (i
= 0; i
< PHT_SIZE
; i
++) pht1
[i
] |= pht2
[i
];
3311 void GC_dirty_init()
3316 GC_dirty_maintained
= TRUE
;
3317 if (GC_words_allocd
!= 0 || GC_words_allocd_before_gc
!= 0) {
3320 for (i
= 0; i
< PHT_SIZE
; i
++) GC_written_pages
[i
] = (word
)(-1);
3322 GC_printf1("Allocated words:%lu:all pages may have been written\n",
3324 (GC_words_allocd
+ GC_words_allocd_before_gc
));
3327 sprintf(buf
, "/proc/%d", getpid());
3328 fd
= open(buf
, O_RDONLY
);
3330 ABORT("/proc open failed");
3332 GC_proc_fd
= syscall(SYS_ioctl
, fd
, PIOCOPENPD
, 0);
3334 syscall(SYS_fcntl
, GC_proc_fd
, F_SETFD
, FD_CLOEXEC
);
3335 if (GC_proc_fd
< 0) {
3336 ABORT("/proc ioctl failed");
3338 GC_proc_buf
= GC_scratch_alloc(GC_proc_buf_size
);
3339 # ifdef GC_SOLARIS_THREADS
3340 GC_fresh_pages
= (struct hblk
**)
3341 GC_scratch_alloc(MAX_FRESH_PAGES
* sizeof (struct hblk
*));
3342 if (GC_fresh_pages
== 0) {
3343 GC_err_printf0("No space for fresh pages\n");
3346 BZERO(GC_fresh_pages
, MAX_FRESH_PAGES
* sizeof (struct hblk
*));
3350 /* Ignore write hints. They don't help us here. */
3352 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
3359 #ifdef GC_SOLARIS_THREADS
3360 # define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
3362 # define READ(fd,buf,nbytes) read(fd, buf, nbytes)
3365 void GC_read_dirty()
3367 unsigned long ps
, np
;
3370 struct prasmap
* map
;
3372 ptr_t current_addr
, limit
;
3376 BZERO(GC_grungy_pages
, (sizeof GC_grungy_pages
));
3379 if (READ(GC_proc_fd
, bufp
, GC_proc_buf_size
) <= 0) {
3381 GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
3385 /* Retry with larger buffer. */
3386 word new_size
= 2 * GC_proc_buf_size
;
3387 char * new_buf
= GC_scratch_alloc(new_size
);
3390 GC_proc_buf
= bufp
= new_buf
;
3391 GC_proc_buf_size
= new_size
;
3393 if (READ(GC_proc_fd
, bufp
, GC_proc_buf_size
) <= 0) {
3394 WARN("Insufficient space for /proc read\n", 0);
3396 memset(GC_grungy_pages
, 0xff, sizeof (page_hash_table
));
3397 memset(GC_written_pages
, 0xff, sizeof(page_hash_table
));
3398 # ifdef GC_SOLARIS_THREADS
3399 BZERO(GC_fresh_pages
,
3400 MAX_FRESH_PAGES
* sizeof (struct hblk
*));
3406 /* Copy dirty bits into GC_grungy_pages */
3407 nmaps
= ((struct prpageheader
*)bufp
) -> pr_nmap
;
3408 /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
3409 nmaps, PG_REFERENCED, PG_MODIFIED); */
3410 bufp
= bufp
+ sizeof(struct prpageheader
);
3411 for (i
= 0; i
< nmaps
; i
++) {
3412 map
= (struct prasmap
*)bufp
;
3413 vaddr
= (ptr_t
)(map
-> pr_vaddr
);
3414 ps
= map
-> pr_pagesize
;
3415 np
= map
-> pr_npage
;
3416 /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
3417 limit
= vaddr
+ ps
* np
;
3418 bufp
+= sizeof (struct prasmap
);
3419 for (current_addr
= vaddr
;
3420 current_addr
< limit
; current_addr
+= ps
){
3421 if ((*bufp
++) & PG_MODIFIED
) {
3422 register struct hblk
* h
= (struct hblk
*) current_addr
;
3424 while ((ptr_t
)h
< current_addr
+ ps
) {
3425 register word index
= PHT_HASH(h
);
3427 set_pht_entry_from_index(GC_grungy_pages
, index
);
3428 # ifdef GC_SOLARIS_THREADS
3430 register int slot
= FRESH_PAGE_SLOT(h
);
3432 if (GC_fresh_pages
[slot
] == h
) {
3433 GC_fresh_pages
[slot
] = 0;
3441 bufp
+= sizeof(long) - 1;
3442 bufp
= (char *)((unsigned long)bufp
& ~(sizeof(long)-1));
3444 /* Update GC_written_pages. */
3445 GC_or_pages(GC_written_pages
, GC_grungy_pages
);
3446 # ifdef GC_SOLARIS_THREADS
3447 /* Make sure that old stacks are considered completely clean */
3448 /* unless written again. */
3449 GC_old_stacks_are_fresh();
3455 GC_bool
GC_page_was_dirty(h
)
3458 register word index
= PHT_HASH(h
);
3459 register GC_bool result
;
3461 result
= get_pht_entry_from_index(GC_grungy_pages
, index
);
3462 # ifdef GC_SOLARIS_THREADS
3463 if (result
&& PAGE_IS_FRESH(h
)) result
= FALSE
;
3464 /* This happens only if page was declared fresh since */
3465 /* the read_dirty call, e.g. because it's in an unused */
3466 /* thread stack. It's OK to treat it as clean, in */
3467 /* that case. And it's consistent with */
3468 /* GC_page_was_ever_dirty. */
3473 GC_bool
GC_page_was_ever_dirty(h
)
3476 register word index
= PHT_HASH(h
);
3477 register GC_bool result
;
3479 result
= get_pht_entry_from_index(GC_written_pages
, index
);
3480 # ifdef GC_SOLARIS_THREADS
3481 if (result
&& PAGE_IS_FRESH(h
)) result
= FALSE
;
3486 /* Caller holds allocation lock. */
3487 void GC_is_fresh(h
, n
)
3492 register word index
;
3494 # ifdef GC_SOLARIS_THREADS
3497 if (GC_fresh_pages
!= 0) {
3498 for (i
= 0; i
< n
; i
++) {
3499 ADD_FRESH_PAGE(h
+ i
);
3505 # endif /* PROC_VDB */
3510 # include "vd/PCR_VD.h"
3512 # define NPAGES (32*1024) /* 128 MB */
3514 PCR_VD_DB GC_grungy_bits
[NPAGES
];
3516 ptr_t GC_vd_base
; /* Address corresponding to GC_grungy_bits[0] */
3517 /* HBLKSIZE aligned. */
3519 void GC_dirty_init()
3521 GC_dirty_maintained
= TRUE
;
3522 /* For the time being, we assume the heap generally grows up */
3523 GC_vd_base
= GC_heap_sects
[0].hs_start
;
3524 if (GC_vd_base
== 0) {
3525 ABORT("Bad initial heap segment");
3527 if (PCR_VD_Start(HBLKSIZE
, GC_vd_base
, NPAGES
*HBLKSIZE
)
3529 ABORT("dirty bit initialization failed");
3533 void GC_read_dirty()
3535 /* lazily enable dirty bits on newly added heap sects */
3537 static int onhs
= 0;
3538 int nhs
= GC_n_heap_sects
;
3539 for( ; onhs
< nhs
; onhs
++ ) {
3540 PCR_VD_WriteProtectEnable(
3541 GC_heap_sects
[onhs
].hs_start
,
3542 GC_heap_sects
[onhs
].hs_bytes
);
3547 if (PCR_VD_Clear(GC_vd_base
, NPAGES
*HBLKSIZE
, GC_grungy_bits
)
3549 ABORT("dirty bit read failed");
3553 GC_bool
GC_page_was_dirty(h
)
3556 if((ptr_t
)h
< GC_vd_base
|| (ptr_t
)h
>= GC_vd_base
+ NPAGES
*HBLKSIZE
) {
3559 return(GC_grungy_bits
[h
- (struct hblk
*)GC_vd_base
] & PCR_VD_DB_dirtyBit
);
3563 void GC_remove_protection(h
, nblocks
, is_ptrfree
)
3568 PCR_VD_WriteProtectDisable(h
, nblocks
*HBLKSIZE
);
3569 PCR_VD_WriteProtectEnable(h
, nblocks
*HBLKSIZE
);
3572 # endif /* PCR_VDB */
3574 #if defined(MPROTECT_VDB) && defined(DARWIN)
3575 /* The following sources were used as a *reference* for this exception handling
3577 1. Apple's mach/xnu documentation
3578 2. Timothy J. Wood's "Mach Exception Handlers 101" post to the
3579 omnigroup's macosx-dev list.
3580 www.omnigroup.com/mailman/archive/macosx-dev/2000-June/002030.html
3581 3. macosx-nat.c from Apple's GDB source code.
3584 /* The bug that caused all this trouble should now be fixed. This should
3585 eventually be removed if all goes well. */
3586 /* define BROKEN_EXCEPTION_HANDLING */
3588 #include <mach/mach.h>
3589 #include <mach/mach_error.h>
3590 #include <mach/thread_status.h>
3591 #include <mach/exception.h>
3592 #include <mach/task.h>
3593 #include <pthread.h>
3595 /* These are not defined in any header, although they are documented */
3596 extern boolean_t
exc_server(mach_msg_header_t
*,mach_msg_header_t
*);
3597 extern kern_return_t
exception_raise(
3598 mach_port_t
,mach_port_t
,mach_port_t
,
3599 exception_type_t
,exception_data_t
,mach_msg_type_number_t
);
3600 extern kern_return_t
exception_raise_state(
3601 mach_port_t
,mach_port_t
,mach_port_t
,
3602 exception_type_t
,exception_data_t
,mach_msg_type_number_t
,
3603 thread_state_flavor_t
*,thread_state_t
,mach_msg_type_number_t
,
3604 thread_state_t
,mach_msg_type_number_t
*);
3605 extern kern_return_t
exception_raise_state_identity(
3606 mach_port_t
,mach_port_t
,mach_port_t
,
3607 exception_type_t
,exception_data_t
,mach_msg_type_number_t
,
3608 thread_state_flavor_t
*,thread_state_t
,mach_msg_type_number_t
,
3609 thread_state_t
,mach_msg_type_number_t
*);
3612 #define MAX_EXCEPTION_PORTS 16
3615 mach_msg_type_number_t count
;
3616 exception_mask_t masks
[MAX_EXCEPTION_PORTS
];
3617 exception_handler_t ports
[MAX_EXCEPTION_PORTS
];
3618 exception_behavior_t behaviors
[MAX_EXCEPTION_PORTS
];
3619 thread_state_flavor_t flavors
[MAX_EXCEPTION_PORTS
];
3623 mach_port_t exception
;
3624 #if defined(THREADS)
3630 mach_msg_header_t head
;
3634 GC_MP_NORMAL
, GC_MP_DISCARDING
, GC_MP_STOPPED
3635 } GC_mprotect_state_t
;
3637 /* FIXME: 1 and 2 seem to be safe to use in the msgh_id field,
3638 but it isn't documented. Use the source and see if they
3643 /* These values are only used on the reply port */
3646 #if defined(THREADS)
3648 GC_mprotect_state_t GC_mprotect_state
;
3650 /* The following should ONLY be called when the world is stopped */
3651 static void GC_mprotect_thread_notify(mach_msg_id_t id
) {
3654 mach_msg_trailer_t trailer
;
3656 mach_msg_return_t r
;
3658 buf
.msg
.head
.msgh_bits
=
3659 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
,0);
3660 buf
.msg
.head
.msgh_size
= sizeof(buf
.msg
);
3661 buf
.msg
.head
.msgh_remote_port
= GC_ports
.exception
;
3662 buf
.msg
.head
.msgh_local_port
= MACH_PORT_NULL
;
3663 buf
.msg
.head
.msgh_id
= id
;
3667 MACH_SEND_MSG
|MACH_RCV_MSG
|MACH_RCV_LARGE
,
3671 MACH_MSG_TIMEOUT_NONE
,
3673 if(r
!= MACH_MSG_SUCCESS
)
3674 ABORT("mach_msg failed in GC_mprotect_thread_notify");
3675 if(buf
.msg
.head
.msgh_id
!= ID_ACK
)
3676 ABORT("invalid ack in GC_mprotect_thread_notify");
3679 /* Should only be called by the mprotect thread */
3680 static void GC_mprotect_thread_reply() {
3682 mach_msg_return_t r
;
3684 msg
.head
.msgh_bits
=
3685 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND
,0);
3686 msg
.head
.msgh_size
= sizeof(msg
);
3687 msg
.head
.msgh_remote_port
= GC_ports
.reply
;
3688 msg
.head
.msgh_local_port
= MACH_PORT_NULL
;
3689 msg
.head
.msgh_id
= ID_ACK
;
3697 MACH_MSG_TIMEOUT_NONE
,
3699 if(r
!= MACH_MSG_SUCCESS
)
3700 ABORT("mach_msg failed in GC_mprotect_thread_reply");
3703 void GC_mprotect_stop() {
3704 GC_mprotect_thread_notify(ID_STOP
);
3706 void GC_mprotect_resume() {
3707 GC_mprotect_thread_notify(ID_RESUME
);
3710 #else /* !THREADS */
3711 /* The compiler should optimize away any GC_mprotect_state computations */
3712 #define GC_mprotect_state GC_MP_NORMAL
3715 static void *GC_mprotect_thread(void *arg
) {
3716 mach_msg_return_t r
;
3717 /* These two structures contain some private kernel data. We don't need to
3718 access any of it so we don't bother defining a proper struct. The
3719 correct definitions are in the xnu source code. */
3721 mach_msg_header_t head
;
3725 mach_msg_header_t head
;
3726 mach_msg_body_t msgh_body
;
3732 GC_darwin_register_mach_handler_thread(mach_thread_self());
3737 MACH_RCV_MSG
|MACH_RCV_LARGE
|
3738 (GC_mprotect_state
== GC_MP_DISCARDING
? MACH_RCV_TIMEOUT
: 0),
3742 GC_mprotect_state
== GC_MP_DISCARDING
? 0 : MACH_MSG_TIMEOUT_NONE
,
3745 id
= r
== MACH_MSG_SUCCESS
? msg
.head
.msgh_id
: -1;
3747 #if defined(THREADS)
3748 if(GC_mprotect_state
== GC_MP_DISCARDING
) {
3749 if(r
== MACH_RCV_TIMED_OUT
) {
3750 GC_mprotect_state
= GC_MP_STOPPED
;
3751 GC_mprotect_thread_reply();
3754 if(r
== MACH_MSG_SUCCESS
&& (id
== ID_STOP
|| id
== ID_RESUME
))
3755 ABORT("out of order mprotect thread request");
3759 if(r
!= MACH_MSG_SUCCESS
) {
3760 GC_err_printf2("mach_msg failed with %d %s\n",
3761 (int)r
,mach_error_string(r
));
3762 ABORT("mach_msg failed");
3766 #if defined(THREADS)
3768 if(GC_mprotect_state
!= GC_MP_NORMAL
)
3769 ABORT("Called mprotect_stop when state wasn't normal");
3770 GC_mprotect_state
= GC_MP_DISCARDING
;
3773 if(GC_mprotect_state
!= GC_MP_STOPPED
)
3774 ABORT("Called mprotect_resume when state wasn't stopped");
3775 GC_mprotect_state
= GC_MP_NORMAL
;
3776 GC_mprotect_thread_reply();
3778 #endif /* THREADS */
3780 /* Handle the message (calls catch_exception_raise) */
3781 if(!exc_server(&msg
.head
,&reply
.head
))
3782 ABORT("exc_server failed");
3783 /* Send the reply */
3787 reply
.head
.msgh_size
,
3790 MACH_MSG_TIMEOUT_NONE
,
3792 if(r
!= MACH_MSG_SUCCESS
) {
3793 /* This will fail if the thread dies, but the thread shouldn't
3795 #ifdef BROKEN_EXCEPTION_HANDLING
3797 "mach_msg failed with %d %s while sending exc reply\n",
3798 (int)r
,mach_error_string(r
));
3800 ABORT("mach_msg failed while sending exception reply");
3809 /* All this SIGBUS code shouldn't be necessary. All protection faults should
3810 be going throught the mach exception handler. However, it seems a SIGBUS is
3811 occasionally sent for some unknown reason. Even more odd, it seems to be
3812 meaningless and safe to ignore. */
3813 #ifdef BROKEN_EXCEPTION_HANDLING
3815 typedef void (* SIG_PF
)();
3816 static SIG_PF GC_old_bus_handler
;
3818 /* Updates to this aren't atomic, but the SIGBUSs seem pretty rare.
3819 Even if this doesn't get updated property, it isn't really a problem */
3820 static int GC_sigbus_count
;
3822 static void GC_darwin_sigbus(int num
,siginfo_t
*sip
,void *context
) {
3823 if(num
!= SIGBUS
) ABORT("Got a non-sigbus signal in the sigbus handler");
3825 /* Ugh... some seem safe to ignore, but too many in a row probably means
3826 trouble. GC_sigbus_count is reset for each mach exception that is
3828 if(GC_sigbus_count
>= 8) {
3829 ABORT("Got more than 8 SIGBUSs in a row!");
3832 GC_err_printf0("GC: WARNING: Ignoring SIGBUS.\n");
3835 #endif /* BROKEN_EXCEPTION_HANDLING */
3837 void GC_dirty_init() {
3841 pthread_attr_t attr
;
3842 exception_mask_t mask
;
3845 GC_printf0("Inititalizing mach/darwin mprotect virtual dirty bit "
3846 "implementation\n");
3848 # ifdef BROKEN_EXCEPTION_HANDLING
3849 GC_err_printf0("GC: WARNING: Enabling workarounds for various darwin "
3850 "exception handling bugs.\n");
3852 GC_dirty_maintained
= TRUE
;
3853 if (GC_page_size
% HBLKSIZE
!= 0) {
3854 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
3855 ABORT("Page size not multiple of HBLKSIZE");
3858 GC_task_self
= me
= mach_task_self();
3860 r
= mach_port_allocate(me
,MACH_PORT_RIGHT_RECEIVE
,&GC_ports
.exception
);
3861 if(r
!= KERN_SUCCESS
) ABORT("mach_port_allocate failed (exception port)");
3863 r
= mach_port_insert_right(me
,GC_ports
.exception
,GC_ports
.exception
,
3864 MACH_MSG_TYPE_MAKE_SEND
);
3865 if(r
!= KERN_SUCCESS
)
3866 ABORT("mach_port_insert_right failed (exception port)");
3868 #if defined(THREADS)
3869 r
= mach_port_allocate(me
,MACH_PORT_RIGHT_RECEIVE
,&GC_ports
.reply
);
3870 if(r
!= KERN_SUCCESS
) ABORT("mach_port_allocate failed (reply port)");
3873 /* The exceptions we want to catch */
3874 mask
= EXC_MASK_BAD_ACCESS
;
3876 r
= task_get_exception_ports(
3879 GC_old_exc_ports
.masks
,
3880 &GC_old_exc_ports
.count
,
3881 GC_old_exc_ports
.ports
,
3882 GC_old_exc_ports
.behaviors
,
3883 GC_old_exc_ports
.flavors
3885 if(r
!= KERN_SUCCESS
) ABORT("task_get_exception_ports failed");
3887 r
= task_set_exception_ports(
3892 GC_MACH_THREAD_STATE_FLAVOR
3894 if(r
!= KERN_SUCCESS
) ABORT("task_set_exception_ports failed");
3896 if(pthread_attr_init(&attr
) != 0) ABORT("pthread_attr_init failed");
3897 if(pthread_attr_setdetachstate(&attr
,PTHREAD_CREATE_DETACHED
) != 0)
3898 ABORT("pthread_attr_setdetachedstate failed");
3900 # undef pthread_create
3901 /* This will call the real pthread function, not our wrapper */
3902 if(pthread_create(&thread
,&attr
,GC_mprotect_thread
,NULL
) != 0)
3903 ABORT("pthread_create failed");
3904 pthread_attr_destroy(&attr
);
3906 /* Setup the sigbus handler for ignoring the meaningless SIGBUSs */
3907 #ifdef BROKEN_EXCEPTION_HANDLING
3909 struct sigaction sa
, oldsa
;
3910 sa
.sa_handler
= (SIG_PF
)GC_darwin_sigbus
;
3911 sigemptyset(&sa
.sa_mask
);
3912 sa
.sa_flags
= SA_RESTART
|SA_SIGINFO
;
3913 if(sigaction(SIGBUS
,&sa
,&oldsa
) < 0) ABORT("sigaction");
3914 GC_old_bus_handler
= (SIG_PF
)oldsa
.sa_handler
;
3915 if (GC_old_bus_handler
!= SIG_DFL
) {
3917 GC_err_printf0("Replaced other SIGBUS handler\n");
3921 #endif /* BROKEN_EXCEPTION_HANDLING */
3924 /* The source code for Apple's GDB was used as a reference for the exception
3925 forwarding code. This code is similar to be GDB code only because there is
3926 only one way to do it. */
3927 static kern_return_t
GC_forward_exception(
3930 exception_type_t exception
,
3931 exception_data_t data
,
3932 mach_msg_type_number_t data_count
3937 exception_behavior_t behavior
;
3938 thread_state_flavor_t flavor
;
3940 thread_state_t thread_state
;
3941 mach_msg_type_number_t thread_state_count
= THREAD_STATE_MAX
;
3943 for(i
=0;i
<GC_old_exc_ports
.count
;i
++)
3944 if(GC_old_exc_ports
.masks
[i
] & (1 << exception
))
3946 if(i
==GC_old_exc_ports
.count
) ABORT("No handler for exception!");
3948 port
= GC_old_exc_ports
.ports
[i
];
3949 behavior
= GC_old_exc_ports
.behaviors
[i
];
3950 flavor
= GC_old_exc_ports
.flavors
[i
];
3952 if(behavior
!= EXCEPTION_DEFAULT
) {
3953 r
= thread_get_state(thread
,flavor
,thread_state
,&thread_state_count
);
3954 if(r
!= KERN_SUCCESS
)
3955 ABORT("thread_get_state failed in forward_exception");
3959 case EXCEPTION_DEFAULT
:
3960 r
= exception_raise(port
,thread
,task
,exception
,data
,data_count
);
3962 case EXCEPTION_STATE
:
3963 r
= exception_raise_state(port
,thread
,task
,exception
,data
,
3964 data_count
,&flavor
,thread_state
,thread_state_count
,
3965 thread_state
,&thread_state_count
);
3967 case EXCEPTION_STATE_IDENTITY
:
3968 r
= exception_raise_state_identity(port
,thread
,task
,exception
,data
,
3969 data_count
,&flavor
,thread_state
,thread_state_count
,
3970 thread_state
,&thread_state_count
);
3973 r
= KERN_FAILURE
; /* make gcc happy */
3974 ABORT("forward_exception: unknown behavior");
3978 if(behavior
!= EXCEPTION_DEFAULT
) {
3979 r
= thread_set_state(thread
,flavor
,thread_state
,thread_state_count
);
3980 if(r
!= KERN_SUCCESS
)
3981 ABORT("thread_set_state failed in forward_exception");
3987 #define FWD() GC_forward_exception(thread,task,exception,code,code_count)
3989 /* This violates the namespace rules but there isn't anything that can be done
3990 about it. The exception handling stuff is hard coded to call this */
3992 catch_exception_raise(
3993 mach_port_t exception_port
,mach_port_t thread
,mach_port_t task
,
3994 exception_type_t exception
,exception_data_t code
,
3995 mach_msg_type_number_t code_count
4001 # if defined(POWERPC)
4002 # if CPP_WORDSZ == 32
4003 thread_state_flavor_t flavor
= PPC_EXCEPTION_STATE
;
4004 mach_msg_type_number_t exc_state_count
= PPC_EXCEPTION_STATE_COUNT
;
4005 ppc_exception_state_t exc_state
;
4007 thread_state_flavor_t flavor
= PPC_EXCEPTION_STATE64
;
4008 mach_msg_type_number_t exc_state_count
= PPC_EXCEPTION_STATE64_COUNT
;
4009 ppc_exception_state64_t exc_state
;
4011 # elif defined(I386)
4012 thread_state_flavor_t flavor
= i386_EXCEPTION_STATE
;
4013 mach_msg_type_number_t exc_state_count
= i386_EXCEPTION_STATE_COUNT
;
4014 i386_exception_state_t exc_state
;
4016 # error FIXME for non-ppc darwin
4020 if(exception
!= EXC_BAD_ACCESS
|| code
[0] != KERN_PROTECTION_FAILURE
) {
4021 #ifdef DEBUG_EXCEPTION_HANDLING
4022 /* We aren't interested, pass it on to the old handler */
4023 GC_printf3("Exception: 0x%x Code: 0x%x 0x%x in catch....\n",
4025 code_count
> 0 ? code
[0] : -1,
4026 code_count
> 1 ? code
[1] : -1);
4031 r
= thread_get_state(thread
,flavor
,
4032 (natural_t
*)&exc_state
,&exc_state_count
);
4033 if(r
!= KERN_SUCCESS
) {
4034 /* The thread is supposed to be suspended while the exception handler
4035 is called. This shouldn't fail. */
4036 #ifdef BROKEN_EXCEPTION_HANDLING
4037 GC_err_printf0("thread_get_state failed in "
4038 "catch_exception_raise\n");
4039 return KERN_SUCCESS
;
4041 ABORT("thread_get_state failed in catch_exception_raise");
4045 /* This is the address that caused the fault */
4046 #if defined(POWERPC)
4047 addr
= (char*) exc_state
.dar
;
4048 #elif defined (I386)
4049 addr
= (char*) exc_state
.faultvaddr
;
4051 # error FIXME for non POWERPC/I386
4054 if((HDR(addr
)) == 0) {
4055 /* Ugh... just like the SIGBUS problem above, it seems we get a bogus
4056 KERN_PROTECTION_FAILURE every once and a while. We wait till we get
4057 a bunch in a row before doing anything about it. If a "real" fault
4058 ever occurres it'll just keep faulting over and over and we'll hit
4059 the limit pretty quickly. */
4060 #ifdef BROKEN_EXCEPTION_HANDLING
4061 static char *last_fault
;
4062 static int last_fault_count
;
4064 if(addr
!= last_fault
) {
4066 last_fault_count
= 0;
4068 if(++last_fault_count
< 32) {
4069 if(last_fault_count
== 1)
4071 "GC: WARNING: Ignoring KERN_PROTECTION_FAILURE at %p\n",
4073 return KERN_SUCCESS
;
4076 GC_err_printf1("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr
);
4077 /* Can't pass it along to the signal handler because that is
4078 ignoring SIGBUS signals. We also shouldn't call ABORT here as
4079 signals don't always work too well from the exception handler. */
4080 GC_err_printf0("Aborting\n");
4082 #else /* BROKEN_EXCEPTION_HANDLING */
4083 /* Pass it along to the next exception handler
4084 (which should call SIGBUS/SIGSEGV) */
4086 #endif /* !BROKEN_EXCEPTION_HANDLING */
4089 #ifdef BROKEN_EXCEPTION_HANDLING
4090 /* Reset the number of consecutive SIGBUSs */
4091 GC_sigbus_count
= 0;
4094 if(GC_mprotect_state
== GC_MP_NORMAL
) { /* common case */
4095 h
= (struct hblk
*)((word
)addr
& ~(GC_page_size
-1));
4096 UNPROTECT(h
, GC_page_size
);
4097 for (i
= 0; i
< divHBLKSZ(GC_page_size
); i
++) {
4098 register int index
= PHT_HASH(h
+i
);
4099 async_set_pht_entry_from_index(GC_dirty_pages
, index
);
4101 } else if(GC_mprotect_state
== GC_MP_DISCARDING
) {
4102 /* Lie to the thread for now. No sense UNPROTECT()ing the memory
4103 when we're just going to PROTECT() it again later. The thread
4104 will just fault again once it resumes */
4106 /* Shouldn't happen, i don't think */
4107 GC_printf0("KERN_PROTECTION_FAILURE while world is stopped\n");
4110 return KERN_SUCCESS
;
4114 /* These should never be called, but just in case... */
4115 kern_return_t
catch_exception_raise_state(mach_port_name_t exception_port
,
4116 int exception
, exception_data_t code
, mach_msg_type_number_t codeCnt
,
4117 int flavor
, thread_state_t old_state
, int old_stateCnt
,
4118 thread_state_t new_state
, int new_stateCnt
)
4120 ABORT("catch_exception_raise_state");
4121 return(KERN_INVALID_ARGUMENT
);
4123 kern_return_t
catch_exception_raise_state_identity(
4124 mach_port_name_t exception_port
, mach_port_t thread
, mach_port_t task
,
4125 int exception
, exception_data_t code
, mach_msg_type_number_t codeCnt
,
4126 int flavor
, thread_state_t old_state
, int old_stateCnt
,
4127 thread_state_t new_state
, int new_stateCnt
)
4129 ABORT("catch_exception_raise_state_identity");
4130 return(KERN_INVALID_ARGUMENT
);
4134 #endif /* DARWIN && MPROTECT_VDB */
4136 # ifndef HAVE_INCREMENTAL_PROTECTION_NEEDS
4137 int GC_incremental_protection_needs()
4139 return GC_PROTECTS_NONE
;
4141 # endif /* !HAVE_INCREMENTAL_PROTECTION_NEEDS */
4144 * Call stack save code for debugging.
4145 * Should probably be in mach_dep.c, but that requires reorganization.
4148 /* I suspect the following works for most X86 *nix variants, so */
4149 /* long as the frame pointer is explicitly stored. In the case of gcc, */
4150 /* compiler flags (e.g. -fomit-frame-pointer) determine whether it is. */
4151 #if defined(I386) && defined(LINUX) && defined(SAVE_CALL_CHAIN)
4152 # include <features.h>
4155 struct frame
*fr_savfp
;
4157 long fr_arg
[NARGS
]; /* All the arguments go here. */
4163 # include <features.h>
4168 struct frame
*fr_savfp
;
4177 # if defined(SUNOS4)
4178 # include <machine/frame.h>
4180 # if defined (DRSNX)
4181 # include <sys/sparc/frame.h>
4183 # if defined(OPENBSD)
4186 # if defined(FREEBSD) || defined(NETBSD)
4187 # include <machine/frame.h>
4189 # include <sys/frame.h>
4196 --> We only know how to to get the first
6 arguments
4200 #ifdef NEED_CALLINFO
4201 /* Fill in the pc and argument information for up to NFRAMES of my */
4202 /* callers. Ignore my frame and my callers frame. */
4205 # include <unistd.h>
4208 #endif /* NEED_CALLINFO */
4210 #if defined(GC_HAVE_BUILTIN_BACKTRACE)
4211 # include <execinfo.h>
4214 #ifdef SAVE_CALL_CHAIN
4216 #if NARGS == 0 && NFRAMES % 2 == 0 /* No padding */ \
4217 && defined(GC_HAVE_BUILTIN_BACKTRACE)
4219 #ifdef REDIRECT_MALLOC
4220 /* Deal with possible malloc calls in backtrace by omitting */
4221 /* the infinitely recursing backtrace. */
4223 __thread
/* If your compiler doesn't understand this */
4224 /* you could use something like pthread_getspecific. */
4226 GC_in_save_callers
= FALSE
;
4229 void GC_save_callers (info
)
4230 struct callinfo info
[NFRAMES
];
4232 void * tmp_info
[NFRAMES
+ 1];
4234 # define IGNORE_FRAMES 1
4236 /* We retrieve NFRAMES+1 pc values, but discard the first, since it */
4237 /* points to our own frame. */
4238 # ifdef REDIRECT_MALLOC
4239 if (GC_in_save_callers
) {
4240 info
[0].ci_pc
= (word
)(&GC_save_callers
);
4241 for (i
= 1; i
< NFRAMES
; ++i
) info
[i
].ci_pc
= 0;
4244 GC_in_save_callers
= TRUE
;
4246 GC_ASSERT(sizeof(struct callinfo
) == sizeof(void *));
4247 npcs
= backtrace((void **)tmp_info
, NFRAMES
+ IGNORE_FRAMES
);
4248 BCOPY(tmp_info
+IGNORE_FRAMES
, info
, (npcs
- IGNORE_FRAMES
) * sizeof(void *));
4249 for (i
= npcs
- IGNORE_FRAMES
; i
< NFRAMES
; ++i
) info
[i
].ci_pc
= 0;
4250 # ifdef REDIRECT_MALLOC
4251 GC_in_save_callers
= FALSE
;
4255 #else /* No builtin backtrace; do it ourselves */
4257 #if (defined(OPENBSD) || defined(NETBSD) || defined(FREEBSD)) && defined(SPARC)
4258 # define FR_SAVFP fr_fp
4259 # define FR_SAVPC fr_pc
4261 # define FR_SAVFP fr_savfp
4262 # define FR_SAVPC fr_savpc
4265 #if defined(SPARC) && (defined(__arch64__) || defined(__sparcv9))
4271 void GC_save_callers (info
)
4272 struct callinfo info
[NFRAMES
];
4274 struct frame
*frame
;
4278 /* We assume this is turned on only with gcc as the compiler. */
4279 asm("movl %%ebp,%0" : "=r"(frame
));
4282 frame
= (struct frame
*) GC_save_regs_in_stack ();
4283 fp
= (struct frame
*)((long) frame
-> FR_SAVFP
+ BIAS
);
4286 for (; (!(fp HOTTER_THAN frame
) && !(GC_stackbottom
HOTTER_THAN (ptr_t
)fp
)
4287 && (nframes
< NFRAMES
));
4288 fp
= (struct frame
*)((long) fp
-> FR_SAVFP
+ BIAS
), nframes
++) {
4291 info
[nframes
].ci_pc
= fp
->FR_SAVPC
;
4293 for (i
= 0; i
< NARGS
; i
++) {
4294 info
[nframes
].ci_arg
[i
] = ~(fp
->fr_arg
[i
]);
4296 # endif /* NARGS > 0 */
4298 if (nframes
< NFRAMES
) info
[nframes
].ci_pc
= 0;
4301 #endif /* No builtin backtrace */
4303 #endif /* SAVE_CALL_CHAIN */
4305 #ifdef NEED_CALLINFO
4307 /* Print info to stderr. We do NOT hold the allocation lock */
4308 void GC_print_callers (info
)
4309 struct callinfo info
[NFRAMES
];
4312 static int reentry_count
= 0;
4313 GC_bool stop
= FALSE
;
4315 /* FIXME: This should probably use a different lock, so that we */
4316 /* become callable with or without the allocation lock. */
4322 GC_err_printf0("\tCaller at allocation:\n");
4324 GC_err_printf0("\tCall chain at allocation:\n");
4326 for (i
= 0; i
< NFRAMES
&& !stop
; i
++) {
4327 if (info
[i
].ci_pc
== 0) break;
4332 GC_err_printf0("\t\targs: ");
4333 for (j
= 0; j
< NARGS
; j
++) {
4334 if (j
!= 0) GC_err_printf0(", ");
4335 GC_err_printf2("%d (0x%X)", ~(info
[i
].ci_arg
[j
]),
4336 ~(info
[i
].ci_arg
[j
]));
4338 GC_err_printf0("\n");
4341 if (reentry_count
> 1) {
4342 /* We were called during an allocation during */
4343 /* a previous GC_print_callers call; punt. */
4344 GC_err_printf1("\t\t##PC##= 0x%lx\n", info
[i
].ci_pc
);
4351 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4352 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4354 backtrace_symbols((void **)(&(info
[i
].ci_pc
)), 1);
4355 char *name
= sym_name
[0];
4359 sprintf(buf
, "##PC##= 0x%lx", info
[i
].ci_pc
);
4361 # if defined(LINUX) && !defined(SMALL_CONFIG)
4362 /* Try for a line number. */
4365 static char exe_name
[EXE_SZ
];
4367 char cmd_buf
[CMD_SZ
];
4368 # define RESULT_SZ 200
4369 static char result_buf
[RESULT_SZ
];
4372 # define PRELOAD_SZ 200
4373 char preload_buf
[PRELOAD_SZ
];
4374 static GC_bool found_exe_name
= FALSE
;
4375 static GC_bool will_fail
= FALSE
;
4377 /* Try to get it via a hairy and expensive scheme. */
4378 /* First we get the name of the executable: */
4379 if (will_fail
) goto out
;
4380 if (!found_exe_name
) {
4381 ret_code
= readlink("/proc/self/exe", exe_name
, EXE_SZ
);
4382 if (ret_code
< 0 || ret_code
>= EXE_SZ
4383 || exe_name
[0] != '/') {
4384 will_fail
= TRUE
; /* Dont try again. */
4387 exe_name
[ret_code
] = '\0';
4388 found_exe_name
= TRUE
;
4390 /* Then we use popen to start addr2line -e <exe> <addr> */
4391 /* There are faster ways to do this, but hopefully this */
4392 /* isn't time critical. */
4393 sprintf(cmd_buf
, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name
,
4394 (unsigned long)info
[i
].ci_pc
);
4395 old_preload
= getenv ("LD_PRELOAD");
4396 if (0 != old_preload
) {
4397 if (strlen (old_preload
) >= PRELOAD_SZ
) {
4401 strcpy (preload_buf
, old_preload
);
4402 unsetenv ("LD_PRELOAD");
4404 pipe
= popen(cmd_buf
, "r");
4405 if (0 != old_preload
4406 && 0 != setenv ("LD_PRELOAD", preload_buf
, 0)) {
4407 WARN("Failed to reset LD_PRELOAD\n", 0);
4410 || (result_len
= fread(result_buf
, 1, RESULT_SZ
- 1, pipe
))
4412 if (pipe
!= NULL
) pclose(pipe
);
4416 if (result_buf
[result_len
- 1] == '\n') --result_len
;
4417 result_buf
[result_len
] = 0;
4418 if (result_buf
[0] == '?'
4419 || result_buf
[result_len
-2] == ':'
4420 && result_buf
[result_len
-1] == '0') {
4424 /* Get rid of embedded newline, if any. Test for "main" */
4426 char * nl
= strchr(result_buf
, '\n');
4427 if (nl
!= NULL
&& nl
< result_buf
+ result_len
) {
4430 if (strncmp(result_buf
, "main", nl
- result_buf
) == 0) {
4434 if (result_len
< RESULT_SZ
- 25) {
4435 /* Add in hex address */
4436 sprintf(result_buf
+ result_len
, " [0x%lx]",
4437 (unsigned long)info
[i
].ci_pc
);
4444 GC_err_printf1("\t\t%s\n", name
);
4445 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4446 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4447 free(sym_name
); /* May call GC_free; that's OK */
4456 #endif /* NEED_CALLINFO */
4460 #if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
4462 /* Dump /proc/self/maps to GC_stderr, to enable looking up names for
4463 addresses in FIND_LEAK output. */
4465 static word
dump_maps(char *maps
)
4467 GC_err_write(maps
, strlen(maps
));
4471 void GC_print_address_map()
4473 GC_err_printf0("---------- Begin address map ----------\n");
4474 GC_apply_to_maps(dump_maps
);
4475 GC_err_printf0("---------- End address map ----------\n");