Revert "[aot] Improve error checking when setting up class vtable."
[mono-project.git] / libgc / os_dep.c
blob8c8e0981dd6e236f531abd538290c5cd11865bed
1 /*
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. */
26 # define __KERNEL__
27 # include <asm/signal.h>
28 # undef __KERNEL__
29 # else
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>
35 # if 2 <= __GLIBC__
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__ */
46 # endif
47 # endif
48 # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) && !defined(MACOS) \
49 && !defined(MSWINCE)
50 # include <sys/types.h>
51 # if !defined(MSWIN32) && !defined(SUNOS4)
52 # include <unistd.h>
53 # endif
54 # endif
56 # include <stdio.h>
57 # if defined(MSWINCE) || defined (SN_TARGET_PS3)
58 # define SIGSEGV 0 /* value is irrelevant */
59 # else
60 # include <signal.h>
61 # endif
63 #if defined(LINUX) || defined(LINUX_STACKBOTTOM)
64 # include <ctype.h>
65 #endif
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
72 # endif
74 # if !defined(STACKBOTTOM) && defined(HEURISTIC2)
75 # define NEED_FIND_LIMIT
76 # endif
78 # if (defined(SUNOS4) && defined(DYNAMIC_LOADING)) && !defined(PCR)
79 # define NEED_FIND_LIMIT
80 # endif
82 # if (defined(SVR4) || defined(AUX) || defined(DGUX) \
83 || (defined(LINUX) && defined(SPARC))) && !defined(PCR)
84 # define NEED_FIND_LIMIT
85 # endif
87 #if defined(FREEBSD) && (defined(I386) || defined(powerpc) || defined(__powerpc__))
88 # include <machine/trap.h>
89 # if !defined(PCR)
90 # define NEED_FIND_LIMIT
91 # endif
92 #endif
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
98 #endif
100 #ifdef NEED_FIND_LIMIT
101 # include <setjmp.h>
102 #endif
104 #ifdef AMIGA
105 # define GC_AMIGA_DEF
106 # include "AmigaOS.c"
107 # undef GC_AMIGA_DEF
108 #endif
110 #if defined(MSWIN32) || defined(MSWINCE)
111 # define WIN32_LEAN_AND_MEAN
112 # define NOSERVICE
113 # include <windows.h>
114 #endif
116 #ifdef MACOS
117 # include <Processes.h>
118 #endif
120 #ifdef IRIX5
121 # include <sys/uio.h>
122 # include <malloc.h> /* for locking */
123 #endif
124 #if defined(USE_MUNMAP)
125 # ifndef USE_MMAP
126 --> USE_MUNMAP requires USE_MMAP
127 # endif
128 #endif
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>
133 # include <errno.h>
134 #endif
136 #if defined( UNIX_LIKE ) || defined(NACL)
137 # include <fcntl.h>
138 #endif
140 #if (defined(SUNOS5SIGS) || defined (HURD) || defined(LINUX) || defined(NETBSD)) && !defined(FREEBSD)
141 # ifdef SUNOS5SIGS
142 # include <sys/siginfo.h>
143 # endif
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
149 #else
150 # define SETJMP(env) setjmp(env)
151 # define LONGJMP(env, val) longjmp(env, val)
152 # define JMP_BUF jmp_buf
153 #endif
155 #ifdef DARWIN
156 /* for get_etext and friends */
157 #include <mach-o/getsect.h>
158 #endif
160 #ifdef DJGPP
161 /* Apparently necessary for djgpp 2.01. May cause problems with */
162 /* other versions. */
163 typedef long unsigned int caddr_t;
164 #endif
166 #ifdef PCR
167 # include "il/PCR_IL.h"
168 # include "th/PCR_ThCtl.h"
169 # include "mm/PCR_MM.h"
170 #endif
172 #if !defined(NO_EXECUTE_PERMISSION)
173 # define OPT_PROT_EXEC PROT_EXEC
174 #else
175 # define OPT_PROT_EXEC 0
176 #endif
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 */
183 /* here. */
185 #define READ read
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;
192 ssize_t result;
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;
198 num_read += result;
200 return num_read;
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
208 * ahead of time.
211 word GC_apply_to_maps(word (*fn)(char *))
213 int f;
214 int result;
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. */
223 do {
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;
232 maps_size = 0;
233 do {
234 result = GC_repeat_read(f, maps_buf, maps_buf_sz-1);
235 if (result <= 0) return 0;
236 maps_size += result;
237 } while (result == maps_buf_sz-1);
238 close(f);
239 } while (maps_size >= maps_buf_sz);
240 maps_buf[maps_size] = '\0';
242 /* Apply fn to result. */
243 return fn(maps_buf);
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
253 // is as follows:
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;
271 char *p;
272 char *endp;
274 if (buf_ptr == NULL || *buf_ptr == '\0') {
275 return NULL;
278 p = buf_ptr;
279 while (isspace(*p)) ++p;
280 start_start = p;
281 GC_ASSERT(isxdigit(*start_start));
282 *start = strtoul(start_start, &endp, 16); p = endp;
283 GC_ASSERT(*p=='-');
285 ++p;
286 end_start = p;
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;
292 prot_start = p;
293 GC_ASSERT(*prot_start == 'r' || *prot_start == '-');
294 memcpy(prot_buf, prot_start, 4);
295 prot_buf[4] = '\0';
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;
302 maj_dev_start = p;
303 GC_ASSERT(isxdigit(*maj_dev_start));
304 *maj_dev = strtoul(maj_dev_start, NULL, 16);
307 while (*p && *p++ != '\n');
309 return p;
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. */
320 # ifdef LINUX
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[];
330 # endif /* LINUX */
331 extern int _end[];
333 ptr_t GC_data_start;
335 void GC_init_linux_data_start()
337 extern ptr_t GC_find_limit();
339 if (GC_no_dls)
341 * Not needed, avoids the SIGSEGV caused by GC_find_limit which
342 * complicates debugging.
344 return;
346 # ifdef LINUX
347 /* Try the easy approaches first: */
348 if ((ptr_t)__data_start != 0) {
349 GC_data_start = (ptr_t)(__data_start);
350 return;
352 if ((ptr_t)data_start != 0) {
353 GC_data_start = (ptr_t)(data_start);
354 return;
356 # endif /* LINUX */
357 GC_data_start = GC_find_limit((ptr_t)(_end), FALSE);
359 #endif
361 # ifdef ECOS
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
368 #undef SETJMP
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)
380 void *p = brk;
382 brk += increment;
384 if (brk > memory + sizeof memory)
386 brk -= increment;
387 return NULL;
390 return p;
392 #define sbrk tiny_sbrk
393 # endif /* ECOS */
395 #if defined(NETBSD) && defined(__ELF__)
396 ptr_t GC_data_start;
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 */
403 /* some versions. */
404 GC_data_start = GC_find_limit((ptr_t)&environ, FALSE);
406 #endif
408 #if defined(OPENBSD)
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, ...);
415 # endif
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.
424 /*ARGSUSED*/
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));
451 for (;;) {
452 result += pgsz;
453 if (result >= bound) {
454 result = bound;
455 break;
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));
464 # endif
466 sigaction(SIGSEGV, &old_segv_act, 0);
468 return(result);
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);
487 firstpass = 1;
488 result = (ptr_t)(((word)(p)) & ~(pgsz-1));
489 if (sigsetjmp(GC_jmp_buf_openbsd, 1) != 0 || firstpass) {
490 firstpass = 0;
491 result += pgsz;
492 if (result >= bound) {
493 result = bound;
494 } else
495 GC_noop1((word)(*result));
498 sigaction(SIGSEGV, &old_segv_act, 0);
500 return(result);
502 #endif
504 # ifdef OS2
506 # include <stddef.h>
508 # if !defined(__IBMC__) && !defined(__WATCOMC__) /* e.g. EMX */
510 struct exe_hdr {
511 unsigned short magic_number;
512 unsigned short padding[29];
513 long new_exe_offset;
516 #define E_MAGIC(x) (x).magic_number
517 #define EMAGIC 0x5A4D
518 #define E_LFANEW(x) (x).new_exe_offset
520 struct e32_exe {
521 unsigned char magic_number[2];
522 unsigned char byte_order;
523 unsigned char word_order;
524 unsigned long exe_format_level;
525 unsigned short cpu;
526 unsigned short os;
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
538 #define E32LEBO 0
539 #define E32_WORDER(x) (x).word_order
540 #define E32LEWO 0
541 #define E32_CPU(x) (x).cpu
542 #define E32CPU286 1
543 #define E32_OBJTAB(x) (x).object_table_offset
544 #define E32_OBJCNT(x) (x).object_count
546 struct o32_obj {
547 unsigned long size;
548 unsigned long base;
549 unsigned long flags;
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 */
565 # ifndef WORD
566 # define WORD unsigned short
567 # endif
568 # ifndef DWORD
569 # define DWORD unsigned long
570 # endif
572 # define EXE386 1
573 # include <newexe.h>
574 # include <exe386.h>
576 # endif /* __IBMC__ */
578 # define INCL_DOSEXCEPTIONS
579 # define INCL_DOSPROCESS
580 # define INCL_DOSERRORS
581 # define INCL_DOSMODULEMGR
582 # define INCL_DOSMEMMGR
583 # include <os2.h>
586 /* Disable and enable signals during nontrivial allocations */
588 void GC_disable_signals(void)
590 ULONG nest;
592 DosEnterMustComplete(&nest);
593 if (nest != 1) ABORT("nested GC_disable_signals");
596 void GC_enable_signals(void)
598 ULONG nest;
600 DosExitMustComplete(&nest);
601 if (nest != 0) ABORT("GC_enable_signals");
605 # else
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 */
619 /* a signal 32. */
620 # define SIGSETMASK(old, new) (old) = sigsetmask(new)
621 # elif defined(NACL)
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)
627 # else
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))
633 # endif
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;
646 #endif
648 void GC_disable_signals()
650 if (!mask_initialized) {
651 SIG_FILL(new_mask);
653 SIG_DEL(new_mask, SIGSEGV);
654 SIG_DEL(new_mask, SIGILL);
655 SIG_DEL(new_mask, SIGQUIT);
656 # ifdef SIGBUS
657 SIG_DEL(new_mask, SIGBUS);
658 # endif
659 # ifdef SIGIOT
660 SIG_DEL(new_mask, SIGIOT);
661 # endif
662 # ifdef SIGEMT
663 SIG_DEL(new_mask, SIGEMT);
664 # endif
665 # ifdef SIGTRAP
666 SIG_DEL(new_mask, SIGTRAP);
667 # endif
668 mask_initialized = TRUE;
670 # ifdef CHECK_SIGNALS
671 if (GC_sig_disabled != 0) ABORT("Nested disables");
672 GC_sig_disabled++;
673 # endif
674 SIGSETMASK(old_mask,new_mask);
677 void GC_enable_signals()
679 # ifdef CHECK_SIGNALS
680 if (GC_sig_disabled != 1) ABORT("Unmatched enable");
681 GC_sig_disabled--;
682 # endif
683 SIGSETMASK(dummy,old_mask);
686 # endif /* !PCR */
688 # endif /*!OS/2 */
690 /* Ivan Demakov: simplest way (to me) */
691 #if defined (DOS4GW)
692 void GC_disable_signals() { }
693 void GC_enable_signals() { }
694 #endif
696 /* Find the page size */
697 word GC_page_size;
699 # if defined(MSWIN32) || defined(MSWINCE)
700 void GC_setpagesize()
702 GetSystemInfo(&GC_sysinfo);
703 GC_page_size = GC_sysinfo.dwPageSize;
706 # else
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();
713 # else
714 /* It's acceptable to fake it. */
715 void GC_setpagesize()
717 GC_page_size = HBLKSIZE;
719 # endif
720 # endif
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;
740 word result;
741 word protect;
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)) {
748 return(0);
750 if (buf.State != MEM_COMMIT) return(0);
751 return(buf.RegionSize);
754 ptr_t GC_get_stack_base()
756 int dummy;
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 */
767 # ifdef BEOS
768 # include <kernel/OS.h>
769 ptr_t GC_get_stack_base(){
770 thread_info th;
771 get_thread_info(find_thread(NULL),&th);
772 return th.stack_end;
774 # endif /* BEOS */
777 # ifdef OS2
779 ptr_t GC_get_stack_base()
781 PTIB ptib;
782 PPIB ppib;
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));
791 # endif /* OS2 */
793 # ifdef AMIGA
794 # define GC_AMIGA_SB
795 # include "AmigaOS.c"
796 # undef GC_AMIGA_SB
797 # endif /* AMIGA */
799 # if defined(NEED_FIND_LIMIT) || defined(UNIX_LIKE)
801 # ifdef __STDC__
802 typedef void (*handler)(int);
803 # else
804 typedef void (*handler)();
805 # endif
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;
813 # endif
814 # else
815 static handler old_segv_handler, old_bus_handler;
816 # endif
818 # ifdef __STDC__
819 void GC_set_and_save_fault_handler(handler h)
820 # else
821 void GC_set_and_save_fault_handler(h)
822 handler h;
823 # endif
825 # if defined(SUNOS5SIGS) || defined(IRIX5) \
826 || defined(OSF1) || defined(HURD) || defined(NETBSD) || defined(FREEBSD)
827 struct sigaction act;
829 act.sa_handler = h;
830 # if 0 /* Was necessary for Solaris 2.3 and very temporary */
831 /* NetBSD bugs. */
832 act.sa_flags = SA_RESTART | SA_NODEFER;
833 # else
834 act.sa_flags = SA_RESTART;
835 # endif
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);
845 # else
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);
853 # endif
854 # endif /* GC_IRIX_THREADS */
855 # else
856 old_segv_handler = signal(SIGSEGV, h);
857 # ifdef SIGBUS
858 old_bus_handler = signal(SIGBUS, h);
859 # endif
860 # endif
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;
869 /*ARGSUSED*/
870 void GC_fault_handler(sig)
871 int 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);
889 # endif
890 # else
891 (void) signal(SIGSEGV, old_segv_handler);
892 # ifdef SIGBUS
893 (void) signal(SIGBUS, old_bus_handler);
894 # endif
895 # endif
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)
902 ptr_t p;
903 GC_bool 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));
916 for (;;) {
917 if (up) {
918 result += MIN_PAGE_SIZE;
919 } else {
920 result -= MIN_PAGE_SIZE;
922 GC_noop1((word)(*result));
925 GC_reset_fault_handler();
926 if (!up) {
927 result += MIN_PAGE_SIZE;
929 return(result);
931 # endif
933 #if defined(ECOS) || defined(NOSYS)
934 ptr_t GC_get_stack_base()
936 return STACKBOTTOM;
938 #endif
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;
949 int i = 0;
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;
974 #endif
976 # ifdef IA64
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)
982 char prot_buf[5];
983 char *buf_ptr = maps;
984 word start, end;
985 unsigned int maj_dev;
986 word current_best = 0;
987 word dummy;
989 for (;;) {
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;
996 return current_best;
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;
1007 # endif
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;
1020 # endif
1021 word result = backing_store_base_from_proc();
1022 if (0 == result) {
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;
1032 # endif
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];
1045 int f;
1046 char c;
1047 word result = 0;
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 */
1054 /* this. */
1055 # ifdef USE_LIBC_PRIVATES
1056 if (0 != &__libc_stack_end && 0 != __libc_stack_end ) {
1057 # ifdef IA64
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. */
1064 # else
1065 # ifdef SPARC
1066 /* Older versions of glibc for 64-bit Sparc do not set
1067 * this variable correctly, it gets set to either zero
1068 * or one.
1070 if (__libc_stack_end != (ptr_t) (unsigned long)0x1)
1071 return __libc_stack_end;
1072 # else
1073 return __libc_stack_end;
1074 # endif
1075 # endif
1077 # endif
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)) {
1091 result *= 10;
1092 result += c - '0';
1093 c = stat_buf[buf_offset++];
1095 close(f);
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. */
1107 #include <unistd.h>
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};
1114 ptr_t base;
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");
1120 return 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)
1133 word dummy;
1134 ptr_t result;
1135 # endif
1137 # define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1)
1139 # ifdef STACKBOTTOM
1140 return(STACKBOTTOM);
1141 # else
1142 # ifdef HEURISTIC1
1143 # ifdef STACK_GROWS_DOWN
1144 result = (ptr_t)((((word)(&dummy))
1145 + STACKBOTTOM_ALIGNMENT_M1)
1146 & ~STACKBOTTOM_ALIGNMENT_M1);
1147 # else
1148 result = (ptr_t)(((word)(&dummy))
1149 & ~STACKBOTTOM_ALIGNMENT_M1);
1150 # endif
1151 # endif /* HEURISTIC1 */
1152 # ifdef LINUX_STACKBOTTOM
1153 result = GC_linux_stack_base();
1154 # endif
1155 # ifdef FREEBSD_STACKBOTTOM
1156 result = GC_freebsd_stack_base();
1157 # endif
1158 # ifdef HEURISTIC2
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;
1166 # endif
1167 # else
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;
1174 # endif
1175 # endif
1177 # endif /* HEURISTIC2 */
1178 # ifdef STACK_GROWS_DOWN
1179 if (result == 0) result = (ptr_t)(signed_word)(-sizeof(ptr_t));
1180 # endif
1181 return(result);
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()
1199 stack_t stack;
1200 pthread_stackseg_np(pthread_self(), &stack);
1201 return stack.ss_sp;
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.
1214 # ifdef OS2
1216 void GC_register_data_segments()
1218 PTIB ptib;
1219 PPIB ppib;
1220 HMODULE module_handle;
1221 # define PBUFSIZ 512
1222 UCHAR path[PBUFSIZ];
1223 FILE * myexefile;
1224 struct exe_hdr hdrdos; /* MSDOS header. */
1225 struct e32_exe hdr386; /* Real header for my executable */
1226 struct o32_obj seg; /* Currrent segment */
1227 int nsegs;
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");
1278 EXIT();
1280 if (fseek(myexefile, E_LFANEW(hdrdos) + E32_OBJTAB(hdr386),
1281 SEEK_SET) != 0) {
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--) {
1287 int flags;
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");
1298 continue;
1300 GC_add_roots_inner(O32_BASE(seg), O32_BASE(seg)+O32_SIZE(seg), FALSE);
1304 # else /* !OS2 */
1306 # if defined(MSWIN32) || defined(MSWINCE)
1308 # ifdef MSWIN32
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;
1334 DWORD result;
1335 LPVOID limit;
1336 ptr_t p;
1337 LPVOID q;
1339 limit = GC_sysinfo.lpMinimumApplicationAddress;
1340 p = (ptr_t)((word)start & ~(GC_page_size - 1));
1341 for (;;) {
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);
1348 return(p);
1350 # endif
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 */
1369 /* about? */
1370 GC_bool GC_is_malloc_heap_base(ptr_t p)
1372 struct GC_malloc_heap_list *q = GC_malloc_heap_l;
1374 while (0 != q) {
1375 if (q -> allocation_base == p) return TRUE;
1376 q = q -> next;
1378 return FALSE;
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;
1403 do {
1404 void *p = malloc(req_size);
1405 if (0 == p) { free(new_l); return; }
1406 candidate = GC_get_allocation_base(p);
1407 free(p);
1408 req_size *= 2;
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;
1415 # ifdef CONDPRINT
1416 if (GC_print_stats)
1417 GC_printf1("Found new system malloc AllocationBase at 0x%lx\n",
1418 candidate);
1419 # endif
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)
1431 unsigned i;
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;
1442 # endif
1443 for (i = 0; i < GC_n_heap_bases; i++) {
1444 if (GC_heap_bases[i] == p) return TRUE;
1446 return FALSE ;
1449 # ifdef MSWIN32
1450 void GC_register_root_section(ptr_t static_root)
1452 MEMORY_BASIC_INFORMATION buf;
1453 DWORD result;
1454 DWORD protect;
1455 LPVOID p;
1456 char * base;
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) {
1470 limit = new_limit;
1471 } else {
1472 if (base != limit) GC_add_roots_inner(base, limit, FALSE);
1473 base = p;
1474 limit = new_limit;
1477 if (p > (LPVOID)new_limit /* overflow */) break;
1478 p = (LPVOID)new_limit;
1480 if (base != limit) GC_add_roots_inner(base, limit, FALSE);
1482 #endif
1484 void GC_register_data_segments()
1486 # ifdef MSWIN32
1487 static char dummy;
1488 GC_register_root_section((ptr_t)(&dummy));
1489 # endif
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)
1497 int max_page_size;
1498 int * 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. */
1513 *result = *result;
1514 GC_reset_fault_handler();
1515 } else {
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);
1526 # endif
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)
1535 int max_page_size;
1536 int * 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();
1551 } else {
1552 GC_reset_fault_handler();
1553 /* As above, we go to plan B */
1554 result = GC_find_limit((ptr_t)(DATAEND), FALSE);
1556 return(result);
1559 # endif
1562 #ifdef AMIGA
1564 # define GC_AMIGA_DS
1565 # include "AmigaOS.c"
1566 # undef GC_AMIGA_DS
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;
1583 for(;;) {
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);
1588 else
1589 break;
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);
1608 # else
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);
1613 # endif
1614 # endif
1615 # endif
1616 # if defined(MACOS)
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);
1623 # else
1624 # if defined(__MWERKS__)
1625 # if !__POWERPC__
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);
1630 # endif
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);
1639 # endif
1640 # else
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 */
1648 # endif /* MACOS */
1650 /* Dynamic libraries are added at every collection, since they may */
1651 /* change. */
1654 # endif /* ! OPENBSD */
1655 # endif /* ! AMIGA */
1656 # endif /* ! MSWIN32 && ! MSWINCE*/
1657 # endif /* ! OS2 */
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)
1667 # ifdef SUNOS4
1668 extern caddr_t sbrk();
1669 # endif
1670 # ifdef __STDC__
1671 # define SBRK_ARG_T ptrdiff_t
1672 # else
1673 # define SBRK_ARG_T int
1674 # endif
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)
1682 word bytes;
1684 caddr_t cur_brk = (caddr_t)sbrk(0);
1685 caddr_t result;
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 */
1690 if (lsbs != 0) {
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;
1698 } else {
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. */
1714 #else
1715 # define GC_MMAP_FLAGS MAP_PRIVATE
1716 #endif
1718 #ifdef USE_MMAP_ANON
1719 # define zero_fd -1
1720 # if defined(MAP_ANONYMOUS)
1721 # define OPT_MAP_ANON MAP_ANONYMOUS
1722 # else
1723 # define OPT_MAP_ANON MAP_ANON
1724 # endif
1725 #else
1726 static int zero_fd;
1727 # define OPT_MAP_ANON 0
1728 #endif
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 */
1735 #ifndef HEAP_START
1736 # define HEAP_START 0
1737 #endif
1739 #ifdef FALLBACK_TO_MMAP
1740 static ptr_t GC_unix_get_mem_mmap(bytes)
1741 #else
1742 ptr_t GC_unix_get_mem(bytes)
1743 #endif
1744 word bytes;
1746 void *result;
1747 static ptr_t last_addr = HEAP_START;
1749 # ifndef USE_MMAP_ANON
1750 static GC_bool initialized = FALSE;
1752 if (!initialized) {
1753 zero_fd = open("/dev/zero", O_RDONLY);
1754 fcntl(zero_fd, F_SETFD, FD_CLOEXEC);
1755 initialized = TRUE;
1757 # endif
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);
1774 # else
1775 GC_ASSERT(last_addr != 0);
1776 # endif
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);
1782 #endif
1784 #ifndef USE_MMAP
1786 ptr_t GC_unix_get_mem(bytes)
1787 word bytes;
1789 ptr_t result;
1790 # ifdef IRIX5
1791 /* Bare sbrk isn't thread safe. Play by malloc rules. */
1792 /* The equivalent may be needed on other systems as well. */
1793 __LOCK_MALLOC();
1794 # endif
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 */
1800 if (lsbs != 0) {
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);
1807 #else
1808 result = 0;
1809 #endif
1812 # ifdef IRIX5
1813 __UNLOCK_MALLOC();
1814 # endif
1815 return(result);
1818 #endif /* Not USE_MMAP */
1819 #endif /* Not RS6000 */
1821 # endif /* UN*X */
1823 # ifdef OS2
1825 void * os2_alloc(size_t bytes)
1827 void * result;
1829 if (DosAllocMem(&result, bytes, PAG_EXECUTE | PAG_READ |
1830 PAG_WRITE | PAG_COMMIT)
1831 != NO_ERROR) {
1832 return(0);
1834 if (result == 0) return(os2_alloc(bytes));
1835 return(result);
1838 # endif /* OS2 */
1841 # if defined(MSWIN32) || defined(MSWINCE)
1842 SYSTEM_INFO GC_sysinfo;
1843 # endif
1845 # ifdef MSWIN32
1847 # ifdef USE_GLOBAL_ALLOC
1848 # define GLOBAL_ALLOC_TEST 1
1849 # else
1850 # define GLOBAL_ALLOC_TEST GC_no_win32_dlls
1851 # endif
1853 word GC_n_heap_bases = 0;
1855 ptr_t GC_win32_get_mem(bytes)
1856 word bytes;
1858 ptr_t result;
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));
1866 } else {
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;
1884 return(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;
1896 # endif
1898 #ifdef AMIGA
1899 # define GC_AMIGA_AM
1900 # include "AmigaOS.c"
1901 # undef GC_AMIGA_AM
1902 #endif
1905 # ifdef MSWINCE
1906 word GC_n_heap_bases = 0;
1908 ptr_t GC_wince_get_mem(bytes)
1909 word bytes;
1911 ptr_t result;
1912 word i;
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))
1921 >= bytes) {
1922 result = GC_heap_bases[i] + GC_heap_lengths[i];
1923 break;
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;
1944 GC_n_heap_bases++;
1947 /* Commit pages */
1948 result = (ptr_t) VirtualAlloc(result, bytes,
1949 MEM_COMMIT,
1950 PAGE_EXECUTE_READWRITE);
1951 if (result != NULL) {
1952 if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result");
1953 GC_heap_lengths[i] += bytes;
1956 return(result);
1958 # endif
1960 #ifdef USE_MUNMAP
1962 /* For now, this only works on Win32/WinCE and some Unix-like */
1963 /* systems. If you have something else, don't define */
1964 /* USE_MUNMAP. */
1965 /* We assume ANSI C to support this feature. */
1967 #if !defined(MSWIN32) && !defined(MSWINCE)
1969 #include <unistd.h>
1970 #include <sys/mman.h>
1971 #include <sys/stat.h>
1972 #include <sys/types.h>
1974 #endif
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;
1986 return result;
1989 /* Compute end address for an unmap operation on the indicated */
1990 /* block. */
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));
1995 return end_addr;
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)
2016 while (len != 0) {
2017 MEMORY_BASIC_INFORMATION mem_info;
2018 GC_word free_len;
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;
2027 len -= free_len;
2029 # else
2030 /* We immediately remap it to prevent an intervening mmap from */
2031 /* accidentally grabbing the same address space. */
2033 void * result;
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;
2040 # endif
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)
2051 ptr_t result;
2053 if (0 == start_addr) return;
2054 while (len != 0) {
2055 MEMORY_BASIC_INFORMATION mem_info;
2056 GC_word alloc_len;
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,
2062 MEM_COMMIT,
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;
2069 len -= alloc_len;
2071 # else
2072 /* It was already remapped with PROT_NONE. */
2073 int result;
2075 if (0 == start_addr) return;
2076 #ifdef NACL
2078 /* NaCl doesn't expose mprotect, but mmap should work fine */
2079 void * mmap_result;
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. */
2085 result = 0;
2087 #else /* NACL */
2088 result = mprotect(start_addr, len,
2089 PROT_READ | PROT_WRITE | OPT_PROT_EXEC);
2090 #endif /* NACL */
2091 if (result != 0) {
2092 GC_err_printf3(
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;
2098 # endif
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;
2113 word len;
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)
2120 while (len != 0) {
2121 MEMORY_BASIC_INFORMATION mem_info;
2122 GC_word free_len;
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;
2131 len -= free_len;
2133 # else
2134 if (len != 0) {
2135 /* Immediately remap as above. */
2136 void * result;
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;
2143 # endif
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. */
2151 #ifndef THREADS
2152 void (*GC_push_other_roots)() = 0;
2153 #else /* THREADS */
2155 # ifdef PCR
2156 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
2158 struct PCR_ThCtl_TInfoRep info;
2159 PCR_ERes result;
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));
2164 return(result);
2167 /* Push the contents of an old object. We treat this as stack */
2168 /* data only becasue that makes it robust against mark stack */
2169 /* overflow. */
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,
2184 GC_push_old_obj, 0)
2185 != PCR_ERes_okay) {
2186 ABORT("Old object enumeration failed");
2189 /* Traverse all thread stacks. */
2190 if (PCR_ERes_IsErr(
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");
2197 # endif /* PCR */
2199 # ifdef SRC_M3
2201 # ifdef ALL_INTERIOR_POINTERS
2202 --> misconfigured
2203 # endif
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)
2213 word 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)
2220 word *p;
2221 ptr_t dummy1, dummy2;
2222 int dummy3;
2224 word q = *p;
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");
2268 #endif
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;
2296 # ifdef DEFAULT_VDB
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 */
2302 /* written. */
2304 /* Initialize virtual dirty bit implementation. */
2305 void GC_dirty_init()
2307 # ifdef PRINTSTATS
2308 GC_printf0("Initializing DEFAULT_VDB...\n");
2309 # endif
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). */
2322 /*ARGSUSED*/
2323 GC_bool GC_page_was_dirty(h)
2324 struct hblk *h;
2326 return(TRUE);
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? */
2337 /*ARGSUSED*/
2338 GC_bool GC_page_was_ever_dirty(h)
2339 struct hblk *h;
2341 return(TRUE);
2344 /* Reset the n pages starting at h to "was never dirty" status. */
2345 void GC_is_fresh(h, n)
2346 struct hblk *h;
2347 word n;
2351 /* A call that: */
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. */
2358 /*ARGSUSED*/
2359 void GC_remove_protection(h, nblocks, is_ptrfree)
2360 struct hblk *h;
2361 word nblocks;
2362 GC_bool 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
2386 * applications.
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"); \
2409 # else
2411 # ifdef DARWIN
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"); \
2426 # else
2428 # ifndef MSWINCE
2429 # include <signal.h>
2430 # endif
2432 static DWORD protect_junk;
2433 # define PROTECT(addr, len) \
2434 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
2435 &protect_junk)) { \
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, \
2442 &protect_junk)) { \
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) \
2453 || defined(HURD)
2454 # ifdef __STDC__
2455 typedef void (* SIG_PF)(int);
2456 # else
2457 typedef void (* SIG_PF)();
2458 # endif
2459 #endif /* SUNOS5SIGS || OSF1 || LINUX || HURD */
2461 #if defined(MSWIN32)
2462 typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
2463 # undef SIG_DFL
2464 # define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
2465 #endif
2466 #if defined(MSWINCE)
2467 typedef LONG (WINAPI *SIG_PF)(struct _EXCEPTION_POINTERS *);
2468 # undef SIG_DFL
2469 # define SIG_DFL (SIG_PF) (-1)
2470 #endif
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
2479 # else
2480 # define SIGINFO_T struct siginfo
2481 # endif
2482 # ifdef __STDC__
2483 typedef void (* REAL_SIG_PF)(int, SIGINFO_T *, void *);
2484 # else
2485 typedef void (* REAL_SIG_PF)();
2486 # endif
2487 #endif /* SUNOS5SIGS */
2489 #if defined(LINUX)
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;
2496 # else
2497 typedef struct sigcontext_struct s_c;
2498 # endif
2499 # endif /* glibc < 2.2 */
2500 # if defined(ALPHA) || defined(M68K)
2501 typedef void (* REAL_SIG_PF)(int, int, s_c *);
2502 # else
2503 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2504 typedef void (* REAL_SIG_PF)(int, siginfo_t *, s_c *);
2505 /* FIXME: */
2506 /* According to SUSV3, the last argument should have type */
2507 /* void * or ucontext_t * */
2508 # else
2509 typedef void (* REAL_SIG_PF)(int, s_c);
2510 # endif
2511 # endif
2512 # ifdef ALPHA
2513 /* Retrieve fault address from sigcontext structure by decoding */
2514 /* instruction. */
2515 char * get_fault_addr(s_c *sc) {
2516 unsigned instr;
2517 word faultaddr;
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 */
2525 # endif /* LINUX */
2527 #ifndef DARWIN
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 */
2539 /* correctly. */
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 */
2580 /*ARGSUSED*/
2581 #if !defined(DARWIN)
2582 # if defined (SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2583 void GC_write_fault_handler(sig, code, scp, addr)
2584 int sig, code;
2585 struct sigcontext *scp;
2586 char * addr;
2587 # ifdef SUNOS4
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))
2592 # endif
2593 # ifdef FREEBSD
2594 # define SIG_OK (sig == SIGBUS)
2595 # define CODE_OK TRUE
2596 # endif
2597 # endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2599 # if defined(IRIX5) || defined(OSF1) || defined(HURD)
2600 # include <errno.h>
2601 void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
2602 # ifdef OSF1
2603 # define SIG_OK (sig == SIGSEGV)
2604 # define CODE_OK (code == 2 /* experimentally determined */)
2605 # endif
2606 # ifdef IRIX5
2607 # define SIG_OK (sig == SIGSEGV)
2608 # define CODE_OK (code == EACCES)
2609 # endif
2610 # ifdef HURD
2611 # define SIG_OK (sig == SIGBUS || sig == SIGSEGV)
2612 # define CODE_OK TRUE
2613 # endif
2614 # endif /* IRIX5 || OSF1 || HURD */
2616 # if defined(LINUX)
2617 # if defined(ALPHA) || defined(M68K)
2618 void GC_write_fault_handler(int sig, int code, s_c * sc)
2619 # else
2620 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2621 void GC_write_fault_handler(int sig, siginfo_t * si, s_c * scp)
2622 # else
2623 # if defined(ARM32)
2624 void GC_write_fault_handler(int sig, int a2, int a3, int a4, s_c sc)
2625 # else
2626 void GC_write_fault_handler(int sig, s_c sc)
2627 # endif
2628 # endif
2629 # endif
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. */
2635 # endif /* LINUX */
2637 # if defined(SUNOS5SIGS)
2638 # ifdef __STDC__
2639 void GC_write_fault_handler(int sig, SIGINFO_T *scp, void * context)
2640 # else
2641 void GC_write_fault_handler(sig, scp, context)
2642 int sig;
2643 SIGINFO_T *scp;
2644 void * context;
2645 # endif
2646 # ifdef HPUX
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)
2653 # else
2654 # ifdef FREEBSD
2655 # define SIG_OK (sig == SIGBUS)
2656 # define CODE_OK (scp -> si_code == BUS_PAGE_FAULT)
2657 # else
2658 # define SIG_OK (sig == SIGSEGV)
2659 # define CODE_OK (scp -> si_code == SEGV_ACCERR)
2660 # endif
2661 # endif
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)
2669 /* Write fault */
2670 # endif /* MSWIN32 || MSWINCE */
2672 register unsigned i;
2673 # if defined(HURD)
2674 char *addr = (char *) code;
2675 # endif
2676 # ifdef IRIX5
2677 char * addr = (char *) (size_t) (scp -> sc_badvaddr);
2678 # endif
2679 # if defined(OSF1) && defined(ALPHA)
2680 char * addr = (char *) (scp -> sc_traparg_a0);
2681 # endif
2682 # ifdef SUNOS5SIGS
2683 char * addr = (char *) (scp -> si_addr);
2684 # endif
2685 # ifdef LINUX
2686 # if defined(I386)
2687 char * addr = (char *) (sc.cr2);
2688 # else
2689 # if defined(M68K)
2690 char * addr = NULL;
2692 struct sigcontext *scp = (struct sigcontext *)(sc);
2694 int format = (scp->sc_formatvec >> 12) & 0xf;
2695 unsigned long *framedata = (unsigned long *)(scp + 1);
2696 unsigned long ea;
2698 if (format == 0xa || format == 0xb) {
2699 /* 68020/030 */
2700 ea = framedata[2];
2701 } else if (format == 7) {
2702 /* 68040 */
2703 ea = framedata[3];
2704 if (framedata[1] & 0x08000000) {
2705 /* correct addr on misaligned access */
2706 ea = (ea+4095)&(~4095);
2708 } else if (format == 4) {
2709 /* 68060 */
2710 ea = framedata[0];
2711 if (framedata[1] & 0x08000000) {
2712 /* correct addr on misaligned access */
2713 ea = (ea+4095)&(~4095);
2716 addr = (char *)ea;
2717 # else
2718 # ifdef ALPHA
2719 char * addr = get_fault_addr(sc);
2720 # else
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. */
2726 # else
2727 # if defined(POWERPC)
2728 char * addr = (char *) (sc.regs->dar);
2729 # else
2730 # if defined(ARM32)
2731 char * addr = (char *)sc.fault_address;
2732 # else
2733 # if defined(CRIS)
2734 char * addr = (char *)sc.regs.csraddr;
2735 # else
2736 --> architecture not supported
2737 # endif
2738 # endif
2739 # endif
2740 # endif
2741 # endif
2742 # endif
2743 # endif
2744 # endif
2745 # if defined(MSWIN32) || defined(MSWINCE)
2746 char * addr = (char *) (exc_info -> ExceptionRecord
2747 -> ExceptionInformation[1]);
2748 # define sig SIGSEGV
2749 # endif
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;
2756 # ifdef SUNOS5SIGS
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;
2764 # else
2765 in_allocd_block = (HDR(addr) != 0);
2766 # endif
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 */
2773 SIG_PF old_handler;
2775 if (sig == SIGSEGV) {
2776 old_handler = GC_old_segv_handler;
2777 } else {
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");
2784 # else
2785 return(EXCEPTION_CONTINUE_SEARCH);
2786 # endif
2787 } else {
2788 # if defined (SUNOS4) \
2789 || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2790 (*old_handler) (sig, code, scp, addr);
2791 return;
2792 # endif
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);
2800 return;
2801 # endif
2802 # if defined (LINUX)
2803 # if defined(ALPHA) || defined(M68K)
2804 (*(REAL_SIG_PF)old_handler) (sig, code, sc);
2805 # else
2806 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2807 (*(REAL_SIG_PF)old_handler) (sig, si, scp);
2808 # else
2809 (*(REAL_SIG_PF)old_handler) (sig, sc);
2810 # endif
2811 # endif
2812 return;
2813 # endif
2814 # if defined (IRIX5) || defined(OSF1) || defined(HURD)
2815 (*(REAL_SIG_PF)old_handler) (sig, code, scp);
2816 return;
2817 # endif
2818 # ifdef MSWIN32
2819 return((*old_handler)(exc_info));
2820 # endif
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);
2840 # if defined(OSF1)
2841 /* These reset the signal handler each time by default. */
2842 signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
2843 # endif
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);
2848 # else
2849 return;
2850 # endif
2852 #if defined(MSWIN32) || defined(MSWINCE)
2853 return EXCEPTION_CONTINUE_SEARCH;
2854 #else
2855 GC_err_printf1("Segfault at 0x%lx\n", addr);
2856 ABORT("Unexpected bus error or segmentation fault");
2857 #endif
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)
2868 struct hblk *h;
2869 word nblocks;
2870 GC_bool 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;
2904 # else
2905 act.sa_flags = SA_RESTART | SA_SIGINFO;
2906 act.sa_sigaction = GC_write_fault_handler;
2907 # endif
2908 (void)sigemptyset(&act.sa_mask);
2909 # ifdef SIG_SUSPEND
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 */
2915 # endif
2916 # ifdef PRINTSTATS
2917 GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2918 # endif
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) {
2931 # ifdef PRINTSTATS
2932 GC_err_printf0("Replaced other SIGBUS handler\n");
2933 # endif
2935 # endif
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) {
2943 # ifdef PRINTSTATS
2944 GC_err_printf0("Replaced other SIGSEGV handler\n");
2945 # endif
2947 # endif
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);
2954 # else
2956 int res = sigaction(SIGSEGV, &act, &oldact);
2957 if (res != 0) ABORT("Sigaction failed");
2959 # endif
2960 # if defined(_sigargs) || defined(HURD) || !defined(SA_SIGINFO)
2961 /* This is Irix 5.x, not 6.x. Irix 5.x does not have */
2962 /* sa_sigaction. */
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);
2967 } else {
2968 GC_old_segv_handler = oldact.sa_handler;
2970 # endif
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) {
2976 # ifdef PRINTSTATS
2977 GC_err_printf0("Replaced other SIGSEGV handler\n");
2978 # endif
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) {
2990 # ifdef PRINTSTATS
2991 GC_err_printf0("Replaced other SIGBUS handler\n");
2992 # endif
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) {
2998 # ifdef PRINTSTATS
2999 GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
3000 # endif
3001 } else {
3002 GC_old_segv_handler = SIG_DFL;
3004 # endif
3006 #endif /* !DARWIN */
3008 int GC_incremental_protection_needs()
3010 if (GC_page_size == HBLKSIZE) {
3011 return GC_PROTECTS_POINTER_HEAP;
3012 } else {
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()
3024 ptr_t start;
3025 word len;
3026 struct hblk * current;
3027 struct hblk * current_start; /* Start of block to be protected. */
3028 struct hblk * limit;
3029 unsigned i;
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;
3035 if (protect_all) {
3036 PROTECT(start, len);
3037 } else {
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) {
3043 hdr * hhdr;
3044 word nhblks;
3045 GC_bool is_ptrfree;
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 */
3053 /* segment. */
3054 GC_ASSERT(current_start == current);
3055 current_start = ++current;
3056 continue;
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 */
3062 } else {
3063 nhblks = OBJ_SZ_TO_BLOCKS(hhdr -> hb_sz);
3064 is_ptrfree = IS_PTRFREE(hhdr);
3066 if (is_ptrfree) {
3067 if (current_start < current) {
3068 PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
3070 current_start = (current += nhblks);
3071 } else {
3072 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));
3089 GC_protect_heap();
3092 GC_bool GC_page_was_dirty(h)
3093 struct hblk * 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
3104 * happens to work.
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()) {
3113 LOCK();
3114 syscall_acquired_lock = TRUE;
3118 void GC_end_syscall()
3120 if (syscall_acquired_lock) {
3121 syscall_acquired_lock = FALSE;
3122 UNLOCK();
3126 void GC_unprotect_range(addr, len)
3127 ptr_t addr;
3128 word len;
3130 struct hblk * start_block;
3131 struct hblk * end_block;
3132 register struct hblk *h;
3133 ptr_t obj_start;
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);
3153 #if 0
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)
3174 # else
3175 # ifndef LINT
3176 int read(fd, buf, nbyte)
3177 # else
3178 int GC_read(fd, buf, nbyte)
3179 # endif
3180 int fd;
3181 char *buf;
3182 int nbyte;
3183 # endif
3185 int result;
3187 GC_begin_syscall();
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. */
3196 struct iovec iov;
3198 iov.iov_base = buf;
3199 iov.iov_len = nbyte;
3200 result = readv(fd, &iov, 1);
3202 # else
3203 # if defined(HURD)
3204 result = __read(fd, buf, nbyte);
3205 # else
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);
3210 # endif /* !HURD */
3211 # endif
3212 GC_end_syscall();
3213 return(result);
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)
3226 int result;
3228 GC_begin_syscall();
3229 GC_unprotect_range(buf, (word)nbyte);
3230 result = __real_read(fd, buf, nbyte);
3231 GC_end_syscall();
3232 return(result);
3235 /* We should probably also do this for __read, or whatever stdio */
3236 /* actually calls. */
3237 #endif
3239 #endif /* 0 */
3241 /*ARGSUSED*/
3242 GC_bool GC_page_was_ever_dirty(h)
3243 struct hblk *h;
3245 return(TRUE);
3248 /* Reset the n pages starting at h to "was never dirty" status. */
3249 /*ARGSUSED*/
3250 void GC_is_fresh(h, n)
3251 struct hblk *h;
3252 word n;
3256 # endif /* MPROTECT_VDB */
3258 # ifdef PROC_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.
3271 #include <errno.h>
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;
3281 char *GC_proc_buf;
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)
3298 #endif
3300 /* Add all pages in pht2 to pht1 */
3301 void GC_or_pages(pht1, pht2)
3302 page_hash_table pht1, pht2;
3304 register int i;
3306 for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
3309 int GC_proc_fd;
3311 void GC_dirty_init()
3313 int fd;
3314 char buf[30];
3316 GC_dirty_maintained = TRUE;
3317 if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
3318 register int i;
3320 for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
3321 # ifdef PRINTSTATS
3322 GC_printf1("Allocated words:%lu:all pages may have been written\n",
3323 (unsigned long)
3324 (GC_words_allocd + GC_words_allocd_before_gc));
3325 # endif
3327 sprintf(buf, "/proc/%d", getpid());
3328 fd = open(buf, O_RDONLY);
3329 if (fd < 0) {
3330 ABORT("/proc open failed");
3332 GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
3333 close(fd);
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");
3344 EXIT();
3346 BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
3347 # endif
3350 /* Ignore write hints. They don't help us here. */
3351 /*ARGSUSED*/
3352 void GC_remove_protection(h, nblocks, is_ptrfree)
3353 struct hblk *h;
3354 word nblocks;
3355 GC_bool is_ptrfree;
3359 #ifdef GC_SOLARIS_THREADS
3360 # define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
3361 #else
3362 # define READ(fd,buf,nbytes) read(fd, buf, nbytes)
3363 #endif
3365 void GC_read_dirty()
3367 unsigned long ps, np;
3368 int nmaps;
3369 ptr_t vaddr;
3370 struct prasmap * map;
3371 char * bufp;
3372 ptr_t current_addr, limit;
3373 int i;
3374 int dummy;
3376 BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
3378 bufp = GC_proc_buf;
3379 if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3380 # ifdef PRINTSTATS
3381 GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
3382 GC_proc_buf_size);
3383 # endif
3385 /* Retry with larger buffer. */
3386 word new_size = 2 * GC_proc_buf_size;
3387 char * new_buf = GC_scratch_alloc(new_size);
3389 if (new_buf != 0) {
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);
3395 /* Punt: */
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 *));
3401 # endif
3402 return;
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;
3436 # endif
3437 h++;
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();
3450 # endif
3453 #undef READ
3455 GC_bool GC_page_was_dirty(h)
3456 struct hblk *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. */
3469 # endif
3470 return(result);
3473 GC_bool GC_page_was_ever_dirty(h)
3474 struct hblk *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;
3482 # endif
3483 return(result);
3486 /* Caller holds allocation lock. */
3487 void GC_is_fresh(h, n)
3488 struct hblk *h;
3489 word n;
3492 register word index;
3494 # ifdef GC_SOLARIS_THREADS
3495 register word i;
3497 if (GC_fresh_pages != 0) {
3498 for (i = 0; i < n; i++) {
3499 ADD_FRESH_PAGE(h + i);
3502 # endif
3505 # endif /* PROC_VDB */
3508 # ifdef PCR_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)
3528 != PCR_ERes_okay) {
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)
3548 != PCR_ERes_okay) {
3549 ABORT("dirty bit read failed");
3553 GC_bool GC_page_was_dirty(h)
3554 struct hblk *h;
3556 if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
3557 return(TRUE);
3559 return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
3562 /*ARGSUSED*/
3563 void GC_remove_protection(h, nblocks, is_ptrfree)
3564 struct hblk *h;
3565 word nblocks;
3566 GC_bool 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
3576 code:
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
3614 static struct {
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];
3620 } GC_old_exc_ports;
3622 static struct {
3623 mach_port_t exception;
3624 #if defined(THREADS)
3625 mach_port_t reply;
3626 #endif
3627 } GC_ports;
3629 typedef struct {
3630 mach_msg_header_t head;
3631 } GC_msg_t;
3633 typedef enum {
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
3639 should be ok. */
3640 #define ID_STOP 1
3641 #define ID_RESUME 2
3643 /* These values are only used on the reply port */
3644 #define ID_ACK 3
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) {
3652 struct {
3653 GC_msg_t msg;
3654 mach_msg_trailer_t trailer;
3655 } buf;
3656 mach_msg_return_t r;
3657 /* remote, local */
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;
3665 r = mach_msg(
3666 &buf.msg.head,
3667 MACH_SEND_MSG|MACH_RCV_MSG|MACH_RCV_LARGE,
3668 sizeof(buf.msg),
3669 sizeof(buf),
3670 GC_ports.reply,
3671 MACH_MSG_TIMEOUT_NONE,
3672 MACH_PORT_NULL);
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() {
3681 GC_msg_t msg;
3682 mach_msg_return_t r;
3683 /* remote, local */
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;
3691 r = mach_msg(
3692 &msg.head,
3693 MACH_SEND_MSG,
3694 sizeof(msg),
3696 MACH_PORT_NULL,
3697 MACH_MSG_TIMEOUT_NONE,
3698 MACH_PORT_NULL);
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
3713 #endif
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. */
3720 struct {
3721 mach_msg_header_t head;
3722 char data[256];
3723 } reply;
3724 struct {
3725 mach_msg_header_t head;
3726 mach_msg_body_t msgh_body;
3727 char data[1024];
3728 } msg;
3730 mach_msg_id_t id;
3732 GC_darwin_register_mach_handler_thread(mach_thread_self());
3734 for(;;) {
3735 r = mach_msg(
3736 &msg.head,
3737 MACH_RCV_MSG|MACH_RCV_LARGE|
3738 (GC_mprotect_state == GC_MP_DISCARDING ? MACH_RCV_TIMEOUT : 0),
3740 sizeof(msg),
3741 GC_ports.exception,
3742 GC_mprotect_state == GC_MP_DISCARDING ? 0 : MACH_MSG_TIMEOUT_NONE,
3743 MACH_PORT_NULL);
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();
3752 continue;
3754 if(r == MACH_MSG_SUCCESS && (id == ID_STOP || id == ID_RESUME))
3755 ABORT("out of order mprotect thread request");
3757 #endif
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");
3765 switch(id) {
3766 #if defined(THREADS)
3767 case ID_STOP:
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;
3771 break;
3772 case ID_RESUME:
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();
3777 break;
3778 #endif /* THREADS */
3779 default:
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 */
3784 r = mach_msg(
3785 &reply.head,
3786 MACH_SEND_MSG,
3787 reply.head.msgh_size,
3789 MACH_PORT_NULL,
3790 MACH_MSG_TIMEOUT_NONE,
3791 MACH_PORT_NULL);
3792 if(r != MACH_MSG_SUCCESS) {
3793 /* This will fail if the thread dies, but the thread shouldn't
3794 die... */
3795 #ifdef BROKEN_EXCEPTION_HANDLING
3796 GC_err_printf2(
3797 "mach_msg failed with %d %s while sending exc reply\n",
3798 (int)r,mach_error_string(r));
3799 #else
3800 ABORT("mach_msg failed while sending exception reply");
3801 #endif
3803 } /* switch */
3804 } /* for(;;) */
3805 /* NOT REACHED */
3806 return NULL;
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
3827 handled */
3828 if(GC_sigbus_count >= 8) {
3829 ABORT("Got more than 8 SIGBUSs in a row!");
3830 } else {
3831 GC_sigbus_count++;
3832 GC_err_printf0("GC: WARNING: Ignoring SIGBUS.\n");
3835 #endif /* BROKEN_EXCEPTION_HANDLING */
3837 void GC_dirty_init() {
3838 kern_return_t r;
3839 mach_port_t me;
3840 pthread_t thread;
3841 pthread_attr_t attr;
3842 exception_mask_t mask;
3844 # ifdef PRINTSTATS
3845 GC_printf0("Inititalizing mach/darwin mprotect virtual dirty bit "
3846 "implementation\n");
3847 # endif
3848 # ifdef BROKEN_EXCEPTION_HANDLING
3849 GC_err_printf0("GC: WARNING: Enabling workarounds for various darwin "
3850 "exception handling bugs.\n");
3851 # endif
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)");
3871 #endif
3873 /* The exceptions we want to catch */
3874 mask = EXC_MASK_BAD_ACCESS;
3876 r = task_get_exception_ports(
3878 mask,
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(
3889 mask,
3890 GC_ports.exception,
3891 EXCEPTION_DEFAULT,
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) {
3916 # ifdef PRINTSTATS
3917 GC_err_printf0("Replaced other SIGBUS handler\n");
3918 # endif
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(
3928 mach_port_t thread,
3929 mach_port_t task,
3930 exception_type_t exception,
3931 exception_data_t data,
3932 mach_msg_type_number_t data_count
3934 int i;
3935 kern_return_t r;
3936 mach_port_t port;
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))
3945 break;
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");
3958 switch(behavior) {
3959 case EXCEPTION_DEFAULT:
3960 r = exception_raise(port,thread,task,exception,data,data_count);
3961 break;
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);
3966 break;
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);
3971 break;
3972 default:
3973 r = KERN_FAILURE; /* make gcc happy */
3974 ABORT("forward_exception: unknown behavior");
3975 break;
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");
3984 return r;
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 */
3991 kern_return_t
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
3997 kern_return_t r;
3998 char *addr;
3999 struct hblk *h;
4000 int i;
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;
4006 # else
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;
4010 # endif
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;
4015 # else
4016 # error FIXME for non-ppc darwin
4017 # endif
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",
4024 exception,
4025 code_count > 0 ? code[0] : -1,
4026 code_count > 1 ? code[1] : -1);
4027 #endif
4028 return FWD();
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;
4040 #else
4041 ABORT("thread_get_state failed in catch_exception_raise");
4042 #endif
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;
4050 #else
4051 # error FIXME for non POWERPC/I386
4052 #endif
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) {
4065 last_fault = addr;
4066 last_fault_count = 0;
4068 if(++last_fault_count < 32) {
4069 if(last_fault_count == 1)
4070 GC_err_printf1(
4071 "GC: WARNING: Ignoring KERN_PROTECTION_FAILURE at %p\n",
4072 addr);
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");
4081 exit(EXIT_FAILURE);
4082 #else /* BROKEN_EXCEPTION_HANDLING */
4083 /* Pass it along to the next exception handler
4084 (which should call SIGBUS/SIGSEGV) */
4085 return FWD();
4086 #endif /* !BROKEN_EXCEPTION_HANDLING */
4089 #ifdef BROKEN_EXCEPTION_HANDLING
4090 /* Reset the number of consecutive SIGBUSs */
4091 GC_sigbus_count = 0;
4092 #endif
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 */
4105 } else {
4106 /* Shouldn't happen, i don't think */
4107 GC_printf0("KERN_PROTECTION_FAILURE while world is stopped\n");
4108 return FWD();
4110 return KERN_SUCCESS;
4112 #undef FWD
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>
4154 struct frame {
4155 struct frame *fr_savfp;
4156 long fr_savpc;
4157 long fr_arg[NARGS]; /* All the arguments go here. */
4159 #endif
4161 #if defined(SPARC)
4162 # if defined(LINUX)
4163 # include <features.h>
4165 struct frame {
4166 long fr_local[8];
4167 long fr_arg[6];
4168 struct frame *fr_savfp;
4169 long fr_savpc;
4170 # ifndef __arch64__
4171 char *fr_stret;
4172 # endif
4173 long fr_argd[6];
4174 long fr_argx[0];
4176 # else
4177 # if defined(SUNOS4)
4178 # include <machine/frame.h>
4179 # else
4180 # if defined (DRSNX)
4181 # include <sys/sparc/frame.h>
4182 # else
4183 # if defined(OPENBSD)
4184 # include <frame.h>
4185 # else
4186 # if defined(FREEBSD) || defined(NETBSD)
4187 # include <machine/frame.h>
4188 # else
4189 # include <sys/frame.h>
4190 # endif
4191 # endif
4192 # endif
4193 # endif
4194 # endif
4195 # if NARGS > 6
4196 --> We only know how to to get the first 6 arguments
4197 # endif
4198 #endif /* SPARC */
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. */
4204 #ifdef LINUX
4205 # include <unistd.h>
4206 #endif
4208 #endif /* NEED_CALLINFO */
4210 #if defined(GC_HAVE_BUILTIN_BACKTRACE)
4211 # include <execinfo.h>
4212 #endif
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. */
4222 # ifdef THREADS
4223 __thread /* If your compiler doesn't understand this */
4224 /* you could use something like pthread_getspecific. */
4225 # endif
4226 GC_in_save_callers = FALSE;
4227 #endif
4229 void GC_save_callers (info)
4230 struct callinfo info[NFRAMES];
4232 void * tmp_info[NFRAMES + 1];
4233 int npcs, i;
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;
4242 return;
4244 GC_in_save_callers = TRUE;
4245 # endif
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;
4252 # endif
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
4260 #else
4261 # define FR_SAVFP fr_savfp
4262 # define FR_SAVPC fr_savpc
4263 #endif
4265 #if defined(SPARC) && (defined(__arch64__) || defined(__sparcv9))
4266 # define BIAS 2047
4267 #else
4268 # define BIAS 0
4269 #endif
4271 void GC_save_callers (info)
4272 struct callinfo info[NFRAMES];
4274 struct frame *frame;
4275 struct frame *fp;
4276 int nframes = 0;
4277 # ifdef I386
4278 /* We assume this is turned on only with gcc as the compiler. */
4279 asm("movl %%ebp,%0" : "=r"(frame));
4280 fp = frame;
4281 # else
4282 frame = (struct frame *) GC_save_regs_in_stack ();
4283 fp = (struct frame *)((long) frame -> FR_SAVFP + BIAS);
4284 #endif
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++) {
4289 register int i;
4291 info[nframes].ci_pc = fp->FR_SAVPC;
4292 # if NARGS > 0
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];
4311 register int i;
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. */
4317 LOCK();
4318 ++reentry_count;
4319 UNLOCK();
4321 # if NFRAMES == 1
4322 GC_err_printf0("\tCaller at allocation:\n");
4323 # else
4324 GC_err_printf0("\tCall chain at allocation:\n");
4325 # endif
4326 for (i = 0; i < NFRAMES && !stop ; i++) {
4327 if (info[i].ci_pc == 0) break;
4328 # if NARGS > 0
4330 int j;
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");
4340 # endif
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);
4345 continue;
4348 # ifdef LINUX
4349 FILE *pipe;
4350 # endif
4351 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4352 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4353 char **sym_name =
4354 backtrace_symbols((void **)(&(info[i].ci_pc)), 1);
4355 char *name = sym_name[0];
4356 # else
4357 char buf[40];
4358 char *name = buf;
4359 sprintf(buf, "##PC##= 0x%lx", info[i].ci_pc);
4360 # endif
4361 # if defined(LINUX) && !defined(SMALL_CONFIG)
4362 /* Try for a line number. */
4364 # define EXE_SZ 100
4365 static char exe_name[EXE_SZ];
4366 # define CMD_SZ 200
4367 char cmd_buf[CMD_SZ];
4368 # define RESULT_SZ 200
4369 static char result_buf[RESULT_SZ];
4370 size_t result_len;
4371 char *old_preload;
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;
4376 int ret_code;
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. */
4385 goto out;
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) {
4398 will_fail = TRUE;
4399 goto out;
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);
4409 if (pipe == NULL
4410 || (result_len = fread(result_buf, 1, RESULT_SZ - 1, pipe))
4411 == 0) {
4412 if (pipe != NULL) pclose(pipe);
4413 will_fail = TRUE;
4414 goto out;
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') {
4421 pclose(pipe);
4422 goto out;
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) {
4428 *nl = ':';
4430 if (strncmp(result_buf, "main", nl - result_buf) == 0) {
4431 stop = TRUE;
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);
4439 name = result_buf;
4440 pclose(pipe);
4441 out:;
4443 # endif /* LINUX */
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 */
4448 # endif
4451 LOCK();
4452 --reentry_count;
4453 UNLOCK();
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));
4468 return 1;
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");
4478 #endif