Fix loading from volatile base addresses in the LLVM backend. Fixes #690020.
[mono-project/dkf.git] / libgc / os_dep.c
blobecaa27c7d825318756c853bba76ca0e82d6e19ed
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 && munmap(start_addr, len) != 0) ABORT("munmap failed");
2135 GC_unmapped_bytes += len;
2136 # endif
2139 #endif /* USE_MUNMAP */
2141 /* Routine for pushing any additional roots. In THREADS */
2142 /* environment, this is also responsible for marking from */
2143 /* thread stacks. */
2144 #ifndef THREADS
2145 void (*GC_push_other_roots)() = 0;
2146 #else /* THREADS */
2148 # ifdef PCR
2149 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
2151 struct PCR_ThCtl_TInfoRep info;
2152 PCR_ERes result;
2154 info.ti_stkLow = info.ti_stkHi = 0;
2155 result = PCR_ThCtl_GetInfo(t, &info);
2156 GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi));
2157 return(result);
2160 /* Push the contents of an old object. We treat this as stack */
2161 /* data only becasue that makes it robust against mark stack */
2162 /* overflow. */
2163 PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data)
2165 GC_push_all_stack((ptr_t)p, (ptr_t)p + size);
2166 return(PCR_ERes_okay);
2170 void GC_default_push_other_roots GC_PROTO((void))
2172 /* Traverse data allocated by previous memory managers. */
2174 extern struct PCR_MM_ProcsRep * GC_old_allocator;
2176 if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false,
2177 GC_push_old_obj, 0)
2178 != PCR_ERes_okay) {
2179 ABORT("Old object enumeration failed");
2182 /* Traverse all thread stacks. */
2183 if (PCR_ERes_IsErr(
2184 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0))
2185 || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
2186 ABORT("Thread stack marking failed\n");
2190 # endif /* PCR */
2192 # ifdef SRC_M3
2194 # ifdef ALL_INTERIOR_POINTERS
2195 --> misconfigured
2196 # endif
2198 void GC_push_thread_structures GC_PROTO((void))
2200 /* Not our responsibibility. */
2203 extern void ThreadF__ProcessStacks();
2205 void GC_push_thread_stack(start, stop)
2206 word start, stop;
2208 GC_push_all_stack((ptr_t)start, (ptr_t)stop + sizeof(word));
2211 /* Push routine with M3 specific calling convention. */
2212 GC_m3_push_root(dummy1, p, dummy2, dummy3)
2213 word *p;
2214 ptr_t dummy1, dummy2;
2215 int dummy3;
2217 word q = *p;
2219 GC_PUSH_ONE_STACK(q, p);
2222 /* M3 set equivalent to RTHeap.TracedRefTypes */
2223 typedef struct { int elts[1]; } RefTypeSet;
2224 RefTypeSet GC_TracedRefTypes = {{0x1}};
2226 void GC_default_push_other_roots GC_PROTO((void))
2228 /* Use the M3 provided routine for finding static roots. */
2229 /* This is a bit dubious, since it presumes no C roots. */
2230 /* We handle the collector roots explicitly in GC_push_roots */
2231 RTMain__GlobalMapProc(GC_m3_push_root, 0, GC_TracedRefTypes);
2232 if (GC_words_allocd > 0) {
2233 ThreadF__ProcessStacks(GC_push_thread_stack);
2235 /* Otherwise this isn't absolutely necessary, and we have */
2236 /* startup ordering problems. */
2239 # endif /* SRC_M3 */
2241 # if defined(GC_SOLARIS_THREADS) || defined(GC_PTHREADS) || \
2242 defined(GC_WIN32_THREADS)
2244 extern void GC_push_all_stacks();
2246 void GC_default_push_other_roots GC_PROTO((void))
2248 GC_push_all_stacks();
2251 # endif /* GC_SOLARIS_THREADS || GC_PTHREADS */
2252 #ifdef SN_TARGET_PS3
2253 void GC_default_push_other_roots GC_PROTO((void))
2255 printf ("WARNING WARNING WARNING\nGC_default_push_other_roots is not implemented\n");
2257 void GC_push_thread_structures GC_PROTO((void))
2259 printf ("WARNING WARNING WARNING\nGC_default_push_thread_structures is not implemented\n");
2261 #endif
2263 void (*GC_push_other_roots) GC_PROTO((void)) = GC_default_push_other_roots;
2265 #endif /* THREADS */
2268 * Routines for accessing dirty bits on virtual pages.
2269 * We plan to eventually implement four strategies for doing so:
2270 * DEFAULT_VDB: A simple dummy implementation that treats every page
2271 * as possibly dirty. This makes incremental collection
2272 * useless, but the implementation is still correct.
2273 * PCR_VDB: Use PPCRs virtual dirty bit facility.
2274 * PROC_VDB: Use the /proc facility for reading dirty bits. Only
2275 * works under some SVR4 variants. Even then, it may be
2276 * too slow to be entirely satisfactory. Requires reading
2277 * dirty bits for entire address space. Implementations tend
2278 * to assume that the client is a (slow) debugger.
2279 * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
2280 * dirtied pages. The implementation (and implementability)
2281 * is highly system dependent. This usually fails when system
2282 * calls write to a protected page. We prevent the read system
2283 * call from doing so. It is the clients responsibility to
2284 * make sure that other system calls are similarly protected
2285 * or write only to the stack.
2287 GC_bool GC_dirty_maintained = FALSE;
2289 # ifdef DEFAULT_VDB
2291 /* All of the following assume the allocation lock is held, and */
2292 /* signals are disabled. */
2294 /* The client asserts that unallocated pages in the heap are never */
2295 /* written. */
2297 /* Initialize virtual dirty bit implementation. */
2298 void GC_dirty_init()
2300 # ifdef PRINTSTATS
2301 GC_printf0("Initializing DEFAULT_VDB...\n");
2302 # endif
2303 GC_dirty_maintained = TRUE;
2306 /* Retrieve system dirty bits for heap to a local buffer. */
2307 /* Restore the systems notion of which pages are dirty. */
2308 void GC_read_dirty()
2311 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */
2312 /* If the actual page size is different, this returns TRUE if any */
2313 /* of the pages overlapping h are dirty. This routine may err on the */
2314 /* side of labelling pages as dirty (and this implementation does). */
2315 /*ARGSUSED*/
2316 GC_bool GC_page_was_dirty(h)
2317 struct hblk *h;
2319 return(TRUE);
2323 * The following two routines are typically less crucial. They matter
2324 * most with large dynamic libraries, or if we can't accurately identify
2325 * stacks, e.g. under Solaris 2.X. Otherwise the following default
2326 * versions are adequate.
2329 /* Could any valid GC heap pointer ever have been written to this page? */
2330 /*ARGSUSED*/
2331 GC_bool GC_page_was_ever_dirty(h)
2332 struct hblk *h;
2334 return(TRUE);
2337 /* Reset the n pages starting at h to "was never dirty" status. */
2338 void GC_is_fresh(h, n)
2339 struct hblk *h;
2340 word n;
2344 /* A call that: */
2345 /* I) hints that [h, h+nblocks) is about to be written. */
2346 /* II) guarantees that protection is removed. */
2347 /* (I) may speed up some dirty bit implementations. */
2348 /* (II) may be essential if we need to ensure that */
2349 /* pointer-free system call buffers in the heap are */
2350 /* not protected. */
2351 /*ARGSUSED*/
2352 void GC_remove_protection(h, nblocks, is_ptrfree)
2353 struct hblk *h;
2354 word nblocks;
2355 GC_bool is_ptrfree;
2359 # endif /* DEFAULT_VDB */
2362 # ifdef MPROTECT_VDB
2365 * See DEFAULT_VDB for interface descriptions.
2369 * This implementation maintains dirty bits itself by catching write
2370 * faults and keeping track of them. We assume nobody else catches
2371 * SIGBUS or SIGSEGV. We assume no write faults occur in system calls.
2372 * This means that clients must ensure that system calls don't write
2373 * to the write-protected heap. Probably the best way to do this is to
2374 * ensure that system calls write at most to POINTERFREE objects in the
2375 * heap, and do even that only if we are on a platform on which those
2376 * are not protected. Another alternative is to wrap system calls
2377 * (see example for read below), but the current implementation holds
2378 * a lock across blocking calls, making it problematic for multithreaded
2379 * applications.
2380 * We assume the page size is a multiple of HBLKSIZE.
2381 * We prefer them to be the same. We avoid protecting POINTERFREE
2382 * objects only if they are the same.
2385 # if !defined(MSWIN32) && !defined(MSWINCE) && !defined(DARWIN)
2387 # include <sys/mman.h>
2388 # include <signal.h>
2389 # include <sys/syscall.h>
2391 # define PROTECT(addr, len) \
2392 if (mprotect((caddr_t)(addr), (size_t)(len), \
2393 PROT_READ | OPT_PROT_EXEC) < 0) { \
2394 ABORT("mprotect failed"); \
2396 # define UNPROTECT(addr, len) \
2397 if (mprotect((caddr_t)(addr), (size_t)(len), \
2398 PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
2399 ABORT("un-mprotect failed"); \
2402 # else
2404 # ifdef DARWIN
2405 /* Using vm_protect (mach syscall) over mprotect (BSD syscall) seems to
2406 decrease the likelihood of some of the problems described below. */
2407 #include <mach/vm_map.h>
2408 static mach_port_t GC_task_self;
2409 #define PROTECT(addr,len) \
2410 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2411 FALSE,VM_PROT_READ) != KERN_SUCCESS) { \
2412 ABORT("vm_portect failed"); \
2414 #define UNPROTECT(addr,len) \
2415 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2416 FALSE,VM_PROT_READ|VM_PROT_WRITE) != KERN_SUCCESS) { \
2417 ABORT("vm_portect failed"); \
2419 # else
2421 # ifndef MSWINCE
2422 # include <signal.h>
2423 # endif
2425 static DWORD protect_junk;
2426 # define PROTECT(addr, len) \
2427 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
2428 &protect_junk)) { \
2429 DWORD last_error = GetLastError(); \
2430 GC_printf1("Last error code: %lx\n", last_error); \
2431 ABORT("VirtualProtect failed"); \
2433 # define UNPROTECT(addr, len) \
2434 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
2435 &protect_junk)) { \
2436 ABORT("un-VirtualProtect failed"); \
2438 # endif /* !DARWIN */
2439 # endif /* MSWIN32 || MSWINCE || DARWIN */
2441 #if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2442 typedef void (* SIG_PF)();
2443 #endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2445 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX) \
2446 || defined(HURD)
2447 # ifdef __STDC__
2448 typedef void (* SIG_PF)(int);
2449 # else
2450 typedef void (* SIG_PF)();
2451 # endif
2452 #endif /* SUNOS5SIGS || OSF1 || LINUX || HURD */
2454 #if defined(MSWIN32)
2455 typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
2456 # undef SIG_DFL
2457 # define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
2458 #endif
2459 #if defined(MSWINCE)
2460 typedef LONG (WINAPI *SIG_PF)(struct _EXCEPTION_POINTERS *);
2461 # undef SIG_DFL
2462 # define SIG_DFL (SIG_PF) (-1)
2463 #endif
2465 #if defined(IRIX5) || defined(OSF1) || defined(HURD)
2466 typedef void (* REAL_SIG_PF)(int, int, struct sigcontext *);
2467 #endif /* IRIX5 || OSF1 || HURD */
2469 #if defined(SUNOS5SIGS)
2470 # if defined(HPUX) || defined(FREEBSD)
2471 # define SIGINFO_T siginfo_t
2472 # else
2473 # define SIGINFO_T struct siginfo
2474 # endif
2475 # ifdef __STDC__
2476 typedef void (* REAL_SIG_PF)(int, SIGINFO_T *, void *);
2477 # else
2478 typedef void (* REAL_SIG_PF)();
2479 # endif
2480 #endif /* SUNOS5SIGS */
2482 #if defined(LINUX)
2483 # if __GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ >= 2
2484 typedef struct sigcontext s_c;
2485 # else /* glibc < 2.2 */
2486 # include <linux/version.h>
2487 # if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA) || defined(ARM32)
2488 typedef struct sigcontext s_c;
2489 # else
2490 typedef struct sigcontext_struct s_c;
2491 # endif
2492 # endif /* glibc < 2.2 */
2493 # if defined(ALPHA) || defined(M68K)
2494 typedef void (* REAL_SIG_PF)(int, int, s_c *);
2495 # else
2496 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2497 typedef void (* REAL_SIG_PF)(int, siginfo_t *, s_c *);
2498 /* FIXME: */
2499 /* According to SUSV3, the last argument should have type */
2500 /* void * or ucontext_t * */
2501 # else
2502 typedef void (* REAL_SIG_PF)(int, s_c);
2503 # endif
2504 # endif
2505 # ifdef ALPHA
2506 /* Retrieve fault address from sigcontext structure by decoding */
2507 /* instruction. */
2508 char * get_fault_addr(s_c *sc) {
2509 unsigned instr;
2510 word faultaddr;
2512 instr = *((unsigned *)(sc->sc_pc));
2513 faultaddr = sc->sc_regs[(instr >> 16) & 0x1f];
2514 faultaddr += (word) (((int)instr << 16) >> 16);
2515 return (char *)faultaddr;
2517 # endif /* !ALPHA */
2518 # endif /* LINUX */
2520 #ifndef DARWIN
2521 SIG_PF GC_old_bus_handler;
2522 SIG_PF GC_old_segv_handler; /* Also old MSWIN32 ACCESS_VIOLATION filter */
2523 #endif /* !DARWIN */
2525 #if defined(THREADS)
2526 /* We need to lock around the bitmap update in the write fault handler */
2527 /* in order to avoid the risk of losing a bit. We do this with a */
2528 /* test-and-set spin lock if we know how to do that. Otherwise we */
2529 /* check whether we are already in the handler and use the dumb but */
2530 /* safe fallback algorithm of setting all bits in the word. */
2531 /* Contention should be very rare, so we do the minimum to handle it */
2532 /* correctly. */
2533 #ifdef GC_TEST_AND_SET_DEFINED
2534 static VOLATILE unsigned int fault_handler_lock = 0;
2535 void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2536 while (GC_test_and_set(&fault_handler_lock)) {}
2537 /* Could also revert to set_pht_entry_from_index_safe if initial */
2538 /* GC_test_and_set fails. */
2539 set_pht_entry_from_index(db, index);
2540 GC_clear(&fault_handler_lock);
2542 #else /* !GC_TEST_AND_SET_DEFINED */
2543 /* THIS IS INCORRECT! The dirty bit vector may be temporarily wrong, */
2544 /* just before we notice the conflict and correct it. We may end up */
2545 /* looking at it while it's wrong. But this requires contention */
2546 /* exactly when a GC is triggered, which seems far less likely to */
2547 /* fail than the old code, which had no reported failures. Thus we */
2548 /* leave it this way while we think of something better, or support */
2549 /* GC_test_and_set on the remaining platforms. */
2550 static VOLATILE word currently_updating = 0;
2551 void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2552 unsigned int update_dummy;
2553 currently_updating = (word)(&update_dummy);
2554 set_pht_entry_from_index(db, index);
2555 /* If we get contention in the 10 or so instruction window here, */
2556 /* and we get stopped by a GC between the two updates, we lose! */
2557 if (currently_updating != (word)(&update_dummy)) {
2558 set_pht_entry_from_index_safe(db, index);
2559 /* We claim that if two threads concurrently try to update the */
2560 /* dirty bit vector, the first one to execute UPDATE_START */
2561 /* will see it changed when UPDATE_END is executed. (Note that */
2562 /* &update_dummy must differ in two distinct threads.) It */
2563 /* will then execute set_pht_entry_from_index_safe, thus */
2564 /* returning us to a safe state, though not soon enough. */
2567 #endif /* !GC_TEST_AND_SET_DEFINED */
2568 #else /* !THREADS */
2569 # define async_set_pht_entry_from_index(db, index) \
2570 set_pht_entry_from_index(db, index)
2571 #endif /* !THREADS */
2573 /*ARGSUSED*/
2574 #if !defined(DARWIN)
2575 # if defined (SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2576 void GC_write_fault_handler(sig, code, scp, addr)
2577 int sig, code;
2578 struct sigcontext *scp;
2579 char * addr;
2580 # ifdef SUNOS4
2581 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2582 # define CODE_OK (FC_CODE(code) == FC_PROT \
2583 || (FC_CODE(code) == FC_OBJERR \
2584 && FC_ERRNO(code) == FC_PROT))
2585 # endif
2586 # ifdef FREEBSD
2587 # define SIG_OK (sig == SIGBUS)
2588 # define CODE_OK TRUE
2589 # endif
2590 # endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2592 # if defined(IRIX5) || defined(OSF1) || defined(HURD)
2593 # include <errno.h>
2594 void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
2595 # ifdef OSF1
2596 # define SIG_OK (sig == SIGSEGV)
2597 # define CODE_OK (code == 2 /* experimentally determined */)
2598 # endif
2599 # ifdef IRIX5
2600 # define SIG_OK (sig == SIGSEGV)
2601 # define CODE_OK (code == EACCES)
2602 # endif
2603 # ifdef HURD
2604 # define SIG_OK (sig == SIGBUS || sig == SIGSEGV)
2605 # define CODE_OK TRUE
2606 # endif
2607 # endif /* IRIX5 || OSF1 || HURD */
2609 # if defined(LINUX)
2610 # if defined(ALPHA) || defined(M68K)
2611 void GC_write_fault_handler(int sig, int code, s_c * sc)
2612 # else
2613 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2614 void GC_write_fault_handler(int sig, siginfo_t * si, s_c * scp)
2615 # else
2616 # if defined(ARM32)
2617 void GC_write_fault_handler(int sig, int a2, int a3, int a4, s_c sc)
2618 # else
2619 void GC_write_fault_handler(int sig, s_c sc)
2620 # endif
2621 # endif
2622 # endif
2623 # define SIG_OK (sig == SIGSEGV)
2624 # define CODE_OK TRUE
2625 /* Empirically c.trapno == 14, on IA32, but is that useful? */
2626 /* Should probably consider alignment issues on other */
2627 /* architectures. */
2628 # endif /* LINUX */
2630 # if defined(SUNOS5SIGS)
2631 # ifdef __STDC__
2632 void GC_write_fault_handler(int sig, SIGINFO_T *scp, void * context)
2633 # else
2634 void GC_write_fault_handler(sig, scp, context)
2635 int sig;
2636 SIGINFO_T *scp;
2637 void * context;
2638 # endif
2639 # ifdef HPUX
2640 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2641 # define CODE_OK (scp -> si_code == SEGV_ACCERR) \
2642 || (scp -> si_code == BUS_ADRERR) \
2643 || (scp -> si_code == BUS_UNKNOWN) \
2644 || (scp -> si_code == SEGV_UNKNOWN) \
2645 || (scp -> si_code == BUS_OBJERR)
2646 # else
2647 # ifdef FREEBSD
2648 # define SIG_OK (sig == SIGBUS)
2649 # define CODE_OK (scp -> si_code == BUS_PAGE_FAULT)
2650 # else
2651 # define SIG_OK (sig == SIGSEGV)
2652 # define CODE_OK (scp -> si_code == SEGV_ACCERR)
2653 # endif
2654 # endif
2655 # endif /* SUNOS5SIGS */
2657 # if defined(MSWIN32) || defined(MSWINCE)
2658 LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info)
2659 # define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
2660 STATUS_ACCESS_VIOLATION)
2661 # define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
2662 /* Write fault */
2663 # endif /* MSWIN32 || MSWINCE */
2665 register unsigned i;
2666 # if defined(HURD)
2667 char *addr = (char *) code;
2668 # endif
2669 # ifdef IRIX5
2670 char * addr = (char *) (size_t) (scp -> sc_badvaddr);
2671 # endif
2672 # if defined(OSF1) && defined(ALPHA)
2673 char * addr = (char *) (scp -> sc_traparg_a0);
2674 # endif
2675 # ifdef SUNOS5SIGS
2676 char * addr = (char *) (scp -> si_addr);
2677 # endif
2678 # ifdef LINUX
2679 # if defined(I386)
2680 char * addr = (char *) (sc.cr2);
2681 # else
2682 # if defined(M68K)
2683 char * addr = NULL;
2685 struct sigcontext *scp = (struct sigcontext *)(sc);
2687 int format = (scp->sc_formatvec >> 12) & 0xf;
2688 unsigned long *framedata = (unsigned long *)(scp + 1);
2689 unsigned long ea;
2691 if (format == 0xa || format == 0xb) {
2692 /* 68020/030 */
2693 ea = framedata[2];
2694 } else if (format == 7) {
2695 /* 68040 */
2696 ea = framedata[3];
2697 if (framedata[1] & 0x08000000) {
2698 /* correct addr on misaligned access */
2699 ea = (ea+4095)&(~4095);
2701 } else if (format == 4) {
2702 /* 68060 */
2703 ea = framedata[0];
2704 if (framedata[1] & 0x08000000) {
2705 /* correct addr on misaligned access */
2706 ea = (ea+4095)&(~4095);
2709 addr = (char *)ea;
2710 # else
2711 # ifdef ALPHA
2712 char * addr = get_fault_addr(sc);
2713 # else
2714 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2715 char * addr = si -> si_addr;
2716 /* I believe this is claimed to work on all platforms for */
2717 /* Linux 2.3.47 and later. Hopefully we don't have to */
2718 /* worry about earlier kernels on IA64. */
2719 # else
2720 # if defined(POWERPC)
2721 char * addr = (char *) (sc.regs->dar);
2722 # else
2723 # if defined(ARM32)
2724 char * addr = (char *)sc.fault_address;
2725 # else
2726 # if defined(CRIS)
2727 char * addr = (char *)sc.regs.csraddr;
2728 # else
2729 --> architecture not supported
2730 # endif
2731 # endif
2732 # endif
2733 # endif
2734 # endif
2735 # endif
2736 # endif
2737 # endif
2738 # if defined(MSWIN32) || defined(MSWINCE)
2739 char * addr = (char *) (exc_info -> ExceptionRecord
2740 -> ExceptionInformation[1]);
2741 # define sig SIGSEGV
2742 # endif
2744 if (SIG_OK && CODE_OK) {
2745 register struct hblk * h =
2746 (struct hblk *)((word)addr & ~(GC_page_size-1));
2747 GC_bool in_allocd_block;
2749 # ifdef SUNOS5SIGS
2750 /* Address is only within the correct physical page. */
2751 in_allocd_block = FALSE;
2752 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2753 if (HDR(h+i) != 0) {
2754 in_allocd_block = TRUE;
2757 # else
2758 in_allocd_block = (HDR(addr) != 0);
2759 # endif
2760 if (!in_allocd_block) {
2761 /* FIXME - We should make sure that we invoke the */
2762 /* old handler with the appropriate calling */
2763 /* sequence, which often depends on SA_SIGINFO. */
2765 /* Heap blocks now begin and end on page boundaries */
2766 SIG_PF old_handler;
2768 if (sig == SIGSEGV) {
2769 old_handler = GC_old_segv_handler;
2770 } else {
2771 old_handler = GC_old_bus_handler;
2773 if (old_handler == SIG_DFL) {
2774 # if !defined(MSWIN32) && !defined(MSWINCE)
2775 GC_err_printf1("Segfault at 0x%lx\n", addr);
2776 ABORT("Unexpected bus error or segmentation fault");
2777 # else
2778 return(EXCEPTION_CONTINUE_SEARCH);
2779 # endif
2780 } else {
2781 # if defined (SUNOS4) \
2782 || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2783 (*old_handler) (sig, code, scp, addr);
2784 return;
2785 # endif
2786 # if defined (SUNOS5SIGS)
2788 * FIXME: For FreeBSD, this code should check if the
2789 * old signal handler used the traditional BSD style and
2790 * if so call it using that style.
2792 (*(REAL_SIG_PF)old_handler) (sig, scp, context);
2793 return;
2794 # endif
2795 # if defined (LINUX)
2796 # if defined(ALPHA) || defined(M68K)
2797 (*(REAL_SIG_PF)old_handler) (sig, code, sc);
2798 # else
2799 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2800 (*(REAL_SIG_PF)old_handler) (sig, si, scp);
2801 # else
2802 (*(REAL_SIG_PF)old_handler) (sig, sc);
2803 # endif
2804 # endif
2805 return;
2806 # endif
2807 # if defined (IRIX5) || defined(OSF1) || defined(HURD)
2808 (*(REAL_SIG_PF)old_handler) (sig, code, scp);
2809 return;
2810 # endif
2811 # ifdef MSWIN32
2812 return((*old_handler)(exc_info));
2813 # endif
2816 UNPROTECT(h, GC_page_size);
2817 /* We need to make sure that no collection occurs between */
2818 /* the UNPROTECT and the setting of the dirty bit. Otherwise */
2819 /* a write by a third thread might go unnoticed. Reversing */
2820 /* the order is just as bad, since we would end up unprotecting */
2821 /* a page in a GC cycle during which it's not marked. */
2822 /* Currently we do this by disabling the thread stopping */
2823 /* signals while this handler is running. An alternative might */
2824 /* be to record the fact that we're about to unprotect, or */
2825 /* have just unprotected a page in the GC's thread structure, */
2826 /* and then to have the thread stopping code set the dirty */
2827 /* flag, if necessary. */
2828 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2829 register int index = PHT_HASH(h+i);
2831 async_set_pht_entry_from_index(GC_dirty_pages, index);
2833 # if defined(OSF1)
2834 /* These reset the signal handler each time by default. */
2835 signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
2836 # endif
2837 /* The write may not take place before dirty bits are read. */
2838 /* But then we'll fault again ... */
2839 # if defined(MSWIN32) || defined(MSWINCE)
2840 return(EXCEPTION_CONTINUE_EXECUTION);
2841 # else
2842 return;
2843 # endif
2845 #if defined(MSWIN32) || defined(MSWINCE)
2846 return EXCEPTION_CONTINUE_SEARCH;
2847 #else
2848 GC_err_printf1("Segfault at 0x%lx\n", addr);
2849 ABORT("Unexpected bus error or segmentation fault");
2850 #endif
2852 #endif /* !DARWIN */
2855 * We hold the allocation lock. We expect block h to be written
2856 * shortly. Ensure that all pages containing any part of the n hblks
2857 * starting at h are no longer protected. If is_ptrfree is false,
2858 * also ensure that they will subsequently appear to be dirty.
2860 void GC_remove_protection(h, nblocks, is_ptrfree)
2861 struct hblk *h;
2862 word nblocks;
2863 GC_bool is_ptrfree;
2865 struct hblk * h_trunc; /* Truncated to page boundary */
2866 struct hblk * h_end; /* Page boundary following block end */
2867 struct hblk * current;
2868 GC_bool found_clean;
2870 if (!GC_dirty_maintained) return;
2871 h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1));
2872 h_end = (struct hblk *)(((word)(h + nblocks) + GC_page_size-1)
2873 & ~(GC_page_size-1));
2874 found_clean = FALSE;
2875 for (current = h_trunc; current < h_end; ++current) {
2876 int index = PHT_HASH(current);
2878 if (!is_ptrfree || current < h || current >= h + nblocks) {
2879 async_set_pht_entry_from_index(GC_dirty_pages, index);
2882 UNPROTECT(h_trunc, (ptr_t)h_end - (ptr_t)h_trunc);
2885 #if !defined(DARWIN)
2886 void GC_dirty_init()
2888 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(LINUX) || \
2889 defined(OSF1) || defined(HURD)
2890 struct sigaction act, oldact;
2891 /* We should probably specify SA_SIGINFO for Linux, and handle */
2892 /* the different architectures more uniformly. */
2893 # if defined(IRIX5) || defined(LINUX) && !defined(X86_64) \
2894 || defined(OSF1) || defined(HURD)
2895 act.sa_flags = SA_RESTART;
2896 act.sa_handler = (SIG_PF)GC_write_fault_handler;
2897 # else
2898 act.sa_flags = SA_RESTART | SA_SIGINFO;
2899 act.sa_sigaction = GC_write_fault_handler;
2900 # endif
2901 (void)sigemptyset(&act.sa_mask);
2902 # ifdef SIG_SUSPEND
2903 /* Arrange to postpone SIG_SUSPEND while we're in a write fault */
2904 /* handler. This effectively makes the handler atomic w.r.t. */
2905 /* stopping the world for GC. */
2906 (void)sigaddset(&act.sa_mask, SIG_SUSPEND);
2907 # endif /* SIG_SUSPEND */
2908 # endif
2909 # ifdef PRINTSTATS
2910 GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2911 # endif
2912 GC_dirty_maintained = TRUE;
2913 if (GC_page_size % HBLKSIZE != 0) {
2914 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
2915 ABORT("Page size not multiple of HBLKSIZE");
2917 # if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2918 GC_old_bus_handler = signal(SIGBUS, GC_write_fault_handler);
2919 if (GC_old_bus_handler == SIG_IGN) {
2920 GC_err_printf0("Previously ignored bus error!?");
2921 GC_old_bus_handler = SIG_DFL;
2923 if (GC_old_bus_handler != SIG_DFL) {
2924 # ifdef PRINTSTATS
2925 GC_err_printf0("Replaced other SIGBUS handler\n");
2926 # endif
2928 # endif
2929 # if defined(SUNOS4)
2930 GC_old_segv_handler = signal(SIGSEGV, (SIG_PF)GC_write_fault_handler);
2931 if (GC_old_segv_handler == SIG_IGN) {
2932 GC_err_printf0("Previously ignored segmentation violation!?");
2933 GC_old_segv_handler = SIG_DFL;
2935 if (GC_old_segv_handler != SIG_DFL) {
2936 # ifdef PRINTSTATS
2937 GC_err_printf0("Replaced other SIGSEGV handler\n");
2938 # endif
2940 # endif
2941 # if (defined(SUNOS5SIGS) && !defined(FREEBSD)) || defined(IRIX5) \
2942 || defined(LINUX) || defined(OSF1) || defined(HURD)
2943 /* SUNOS5SIGS includes HPUX */
2944 # if defined(GC_IRIX_THREADS)
2945 sigaction(SIGSEGV, 0, &oldact);
2946 sigaction(SIGSEGV, &act, 0);
2947 # else
2949 int res = sigaction(SIGSEGV, &act, &oldact);
2950 if (res != 0) ABORT("Sigaction failed");
2952 # endif
2953 # if defined(_sigargs) || defined(HURD) || !defined(SA_SIGINFO)
2954 /* This is Irix 5.x, not 6.x. Irix 5.x does not have */
2955 /* sa_sigaction. */
2956 GC_old_segv_handler = oldact.sa_handler;
2957 # else /* Irix 6.x or SUNOS5SIGS or LINUX */
2958 if (oldact.sa_flags & SA_SIGINFO) {
2959 GC_old_segv_handler = (SIG_PF)(oldact.sa_sigaction);
2960 } else {
2961 GC_old_segv_handler = oldact.sa_handler;
2963 # endif
2964 if (GC_old_segv_handler == SIG_IGN) {
2965 GC_err_printf0("Previously ignored segmentation violation!?");
2966 GC_old_segv_handler = SIG_DFL;
2968 if (GC_old_segv_handler != SIG_DFL) {
2969 # ifdef PRINTSTATS
2970 GC_err_printf0("Replaced other SIGSEGV handler\n");
2971 # endif
2973 # endif /* (SUNOS5SIGS && !FREEBSD) || IRIX5 || LINUX || OSF1 || HURD */
2974 # if defined(HPUX) || defined(LINUX) || defined(HURD) \
2975 || (defined(FREEBSD) && defined(SUNOS5SIGS))
2976 sigaction(SIGBUS, &act, &oldact);
2977 GC_old_bus_handler = oldact.sa_handler;
2978 if (GC_old_bus_handler == SIG_IGN) {
2979 GC_err_printf0("Previously ignored bus error!?");
2980 GC_old_bus_handler = SIG_DFL;
2982 if (GC_old_bus_handler != SIG_DFL) {
2983 # ifdef PRINTSTATS
2984 GC_err_printf0("Replaced other SIGBUS handler\n");
2985 # endif
2987 # endif /* HPUX || LINUX || HURD || (FREEBSD && SUNOS5SIGS) */
2988 # if defined(MSWIN32)
2989 GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler);
2990 if (GC_old_segv_handler != NULL) {
2991 # ifdef PRINTSTATS
2992 GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
2993 # endif
2994 } else {
2995 GC_old_segv_handler = SIG_DFL;
2997 # endif
2999 #endif /* !DARWIN */
3001 int GC_incremental_protection_needs()
3003 if (GC_page_size == HBLKSIZE) {
3004 return GC_PROTECTS_POINTER_HEAP;
3005 } else {
3006 return GC_PROTECTS_POINTER_HEAP | GC_PROTECTS_PTRFREE_HEAP;
3010 #define HAVE_INCREMENTAL_PROTECTION_NEEDS
3012 #define IS_PTRFREE(hhdr) ((hhdr)->hb_descr == 0)
3014 #define PAGE_ALIGNED(x) !((word)(x) & (GC_page_size - 1))
3015 void GC_protect_heap()
3017 ptr_t start;
3018 word len;
3019 struct hblk * current;
3020 struct hblk * current_start; /* Start of block to be protected. */
3021 struct hblk * limit;
3022 unsigned i;
3023 GC_bool protect_all =
3024 (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP));
3025 for (i = 0; i < GC_n_heap_sects; i++) {
3026 start = GC_heap_sects[i].hs_start;
3027 len = GC_heap_sects[i].hs_bytes;
3028 if (protect_all) {
3029 PROTECT(start, len);
3030 } else {
3031 GC_ASSERT(PAGE_ALIGNED(len))
3032 GC_ASSERT(PAGE_ALIGNED(start))
3033 current_start = current = (struct hblk *)start;
3034 limit = (struct hblk *)(start + len);
3035 while (current < limit) {
3036 hdr * hhdr;
3037 word nhblks;
3038 GC_bool is_ptrfree;
3040 GC_ASSERT(PAGE_ALIGNED(current));
3041 GET_HDR(current, hhdr);
3042 if (IS_FORWARDING_ADDR_OR_NIL(hhdr)) {
3043 /* This can happen only if we're at the beginning of a */
3044 /* heap segment, and a block spans heap segments. */
3045 /* We will handle that block as part of the preceding */
3046 /* segment. */
3047 GC_ASSERT(current_start == current);
3048 current_start = ++current;
3049 continue;
3051 if (HBLK_IS_FREE(hhdr)) {
3052 GC_ASSERT(PAGE_ALIGNED(hhdr -> hb_sz));
3053 nhblks = divHBLKSZ(hhdr -> hb_sz);
3054 is_ptrfree = TRUE; /* dirty on alloc */
3055 } else {
3056 nhblks = OBJ_SZ_TO_BLOCKS(hhdr -> hb_sz);
3057 is_ptrfree = IS_PTRFREE(hhdr);
3059 if (is_ptrfree) {
3060 if (current_start < current) {
3061 PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
3063 current_start = (current += nhblks);
3064 } else {
3065 current += nhblks;
3068 if (current_start < current) {
3069 PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
3075 /* We assume that either the world is stopped or its OK to lose dirty */
3076 /* bits while this is happenning (as in GC_enable_incremental). */
3077 void GC_read_dirty()
3079 BCOPY((word *)GC_dirty_pages, GC_grungy_pages,
3080 (sizeof GC_dirty_pages));
3081 BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages));
3082 GC_protect_heap();
3085 GC_bool GC_page_was_dirty(h)
3086 struct hblk * h;
3088 register word index = PHT_HASH(h);
3090 return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index));
3094 * Acquiring the allocation lock here is dangerous, since this
3095 * can be called from within GC_call_with_alloc_lock, and the cord
3096 * package does so. On systems that allow nested lock acquisition, this
3097 * happens to work.
3098 * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
3101 static GC_bool syscall_acquired_lock = FALSE; /* Protected by GC lock. */
3103 void GC_begin_syscall()
3105 if (!I_HOLD_LOCK()) {
3106 LOCK();
3107 syscall_acquired_lock = TRUE;
3111 void GC_end_syscall()
3113 if (syscall_acquired_lock) {
3114 syscall_acquired_lock = FALSE;
3115 UNLOCK();
3119 void GC_unprotect_range(addr, len)
3120 ptr_t addr;
3121 word len;
3123 struct hblk * start_block;
3124 struct hblk * end_block;
3125 register struct hblk *h;
3126 ptr_t obj_start;
3128 if (!GC_dirty_maintained) return;
3129 obj_start = GC_base(addr);
3130 if (obj_start == 0) return;
3131 if (GC_base(addr + len - 1) != obj_start) {
3132 ABORT("GC_unprotect_range(range bigger than object)");
3134 start_block = (struct hblk *)((word)addr & ~(GC_page_size - 1));
3135 end_block = (struct hblk *)((word)(addr + len - 1) & ~(GC_page_size - 1));
3136 end_block += GC_page_size/HBLKSIZE - 1;
3137 for (h = start_block; h <= end_block; h++) {
3138 register word index = PHT_HASH(h);
3140 async_set_pht_entry_from_index(GC_dirty_pages, index);
3142 UNPROTECT(start_block,
3143 ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE);
3146 #if 0
3148 /* We no longer wrap read by default, since that was causing too many */
3149 /* problems. It is preferred that the client instead avoids writing */
3150 /* to the write-protected heap with a system call. */
3151 /* This still serves as sample code if you do want to wrap system calls.*/
3153 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(GC_USE_LD_WRAP)
3154 /* Replacement for UNIX system call. */
3155 /* Other calls that write to the heap should be handled similarly. */
3156 /* Note that this doesn't work well for blocking reads: It will hold */
3157 /* the allocation lock for the entire duration of the call. Multithreaded */
3158 /* clients should really ensure that it won't block, either by setting */
3159 /* the descriptor nonblocking, or by calling select or poll first, to */
3160 /* make sure that input is available. */
3161 /* Another, preferred alternative is to ensure that system calls never */
3162 /* write to the protected heap (see above). */
3163 # if defined(__STDC__) && !defined(SUNOS4)
3164 # include <unistd.h>
3165 # include <sys/uio.h>
3166 ssize_t read(int fd, void *buf, size_t nbyte)
3167 # else
3168 # ifndef LINT
3169 int read(fd, buf, nbyte)
3170 # else
3171 int GC_read(fd, buf, nbyte)
3172 # endif
3173 int fd;
3174 char *buf;
3175 int nbyte;
3176 # endif
3178 int result;
3180 GC_begin_syscall();
3181 GC_unprotect_range(buf, (word)nbyte);
3182 # if defined(IRIX5) || defined(GC_LINUX_THREADS)
3183 /* Indirect system call may not always be easily available. */
3184 /* We could call _read, but that would interfere with the */
3185 /* libpthread interception of read. */
3186 /* On Linux, we have to be careful with the linuxthreads */
3187 /* read interception. */
3189 struct iovec iov;
3191 iov.iov_base = buf;
3192 iov.iov_len = nbyte;
3193 result = readv(fd, &iov, 1);
3195 # else
3196 # if defined(HURD)
3197 result = __read(fd, buf, nbyte);
3198 # else
3199 /* The two zero args at the end of this list are because one
3200 IA-64 syscall() implementation actually requires six args
3201 to be passed, even though they aren't always used. */
3202 result = syscall(SYS_read, fd, buf, nbyte, 0, 0);
3203 # endif /* !HURD */
3204 # endif
3205 GC_end_syscall();
3206 return(result);
3208 #endif /* !MSWIN32 && !MSWINCE && !GC_LINUX_THREADS */
3210 #if defined(GC_USE_LD_WRAP) && !defined(THREADS)
3211 /* We use the GNU ld call wrapping facility. */
3212 /* This requires that the linker be invoked with "--wrap read". */
3213 /* This can be done by passing -Wl,"--wrap read" to gcc. */
3214 /* I'm not sure that this actually wraps whatever version of read */
3215 /* is called by stdio. That code also mentions __read. */
3216 # include <unistd.h>
3217 ssize_t __wrap_read(int fd, void *buf, size_t nbyte)
3219 int result;
3221 GC_begin_syscall();
3222 GC_unprotect_range(buf, (word)nbyte);
3223 result = __real_read(fd, buf, nbyte);
3224 GC_end_syscall();
3225 return(result);
3228 /* We should probably also do this for __read, or whatever stdio */
3229 /* actually calls. */
3230 #endif
3232 #endif /* 0 */
3234 /*ARGSUSED*/
3235 GC_bool GC_page_was_ever_dirty(h)
3236 struct hblk *h;
3238 return(TRUE);
3241 /* Reset the n pages starting at h to "was never dirty" status. */
3242 /*ARGSUSED*/
3243 void GC_is_fresh(h, n)
3244 struct hblk *h;
3245 word n;
3249 # endif /* MPROTECT_VDB */
3251 # ifdef PROC_VDB
3254 * See DEFAULT_VDB for interface descriptions.
3258 * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
3259 * from which we can read page modified bits. This facility is far from
3260 * optimal (e.g. we would like to get the info for only some of the
3261 * address space), but it avoids intercepting system calls.
3264 #include <errno.h>
3265 #include <sys/types.h>
3266 #include <sys/signal.h>
3267 #include <sys/fault.h>
3268 #include <sys/syscall.h>
3269 #include <sys/procfs.h>
3270 #include <sys/stat.h>
3272 #define INITIAL_BUF_SZ 16384
3273 word GC_proc_buf_size = INITIAL_BUF_SZ;
3274 char *GC_proc_buf;
3276 #ifdef GC_SOLARIS_THREADS
3277 /* We don't have exact sp values for threads. So we count on */
3278 /* occasionally declaring stack pages to be fresh. Thus we */
3279 /* need a real implementation of GC_is_fresh. We can't clear */
3280 /* entries in GC_written_pages, since that would declare all */
3281 /* pages with the given hash address to be fresh. */
3282 # define MAX_FRESH_PAGES 8*1024 /* Must be power of 2 */
3283 struct hblk ** GC_fresh_pages; /* A direct mapped cache. */
3284 /* Collisions are dropped. */
3286 # define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
3287 # define ADD_FRESH_PAGE(h) \
3288 GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
3289 # define PAGE_IS_FRESH(h) \
3290 (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
3291 #endif
3293 /* Add all pages in pht2 to pht1 */
3294 void GC_or_pages(pht1, pht2)
3295 page_hash_table pht1, pht2;
3297 register int i;
3299 for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
3302 int GC_proc_fd;
3304 void GC_dirty_init()
3306 int fd;
3307 char buf[30];
3309 GC_dirty_maintained = TRUE;
3310 if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
3311 register int i;
3313 for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
3314 # ifdef PRINTSTATS
3315 GC_printf1("Allocated words:%lu:all pages may have been written\n",
3316 (unsigned long)
3317 (GC_words_allocd + GC_words_allocd_before_gc));
3318 # endif
3320 sprintf(buf, "/proc/%d", getpid());
3321 fd = open(buf, O_RDONLY);
3322 if (fd < 0) {
3323 ABORT("/proc open failed");
3325 GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
3326 close(fd);
3327 syscall(SYS_fcntl, GC_proc_fd, F_SETFD, FD_CLOEXEC);
3328 if (GC_proc_fd < 0) {
3329 ABORT("/proc ioctl failed");
3331 GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size);
3332 # ifdef GC_SOLARIS_THREADS
3333 GC_fresh_pages = (struct hblk **)
3334 GC_scratch_alloc(MAX_FRESH_PAGES * sizeof (struct hblk *));
3335 if (GC_fresh_pages == 0) {
3336 GC_err_printf0("No space for fresh pages\n");
3337 EXIT();
3339 BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
3340 # endif
3343 /* Ignore write hints. They don't help us here. */
3344 /*ARGSUSED*/
3345 void GC_remove_protection(h, nblocks, is_ptrfree)
3346 struct hblk *h;
3347 word nblocks;
3348 GC_bool is_ptrfree;
3352 #ifdef GC_SOLARIS_THREADS
3353 # define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
3354 #else
3355 # define READ(fd,buf,nbytes) read(fd, buf, nbytes)
3356 #endif
3358 void GC_read_dirty()
3360 unsigned long ps, np;
3361 int nmaps;
3362 ptr_t vaddr;
3363 struct prasmap * map;
3364 char * bufp;
3365 ptr_t current_addr, limit;
3366 int i;
3367 int dummy;
3369 BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
3371 bufp = GC_proc_buf;
3372 if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3373 # ifdef PRINTSTATS
3374 GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
3375 GC_proc_buf_size);
3376 # endif
3378 /* Retry with larger buffer. */
3379 word new_size = 2 * GC_proc_buf_size;
3380 char * new_buf = GC_scratch_alloc(new_size);
3382 if (new_buf != 0) {
3383 GC_proc_buf = bufp = new_buf;
3384 GC_proc_buf_size = new_size;
3386 if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3387 WARN("Insufficient space for /proc read\n", 0);
3388 /* Punt: */
3389 memset(GC_grungy_pages, 0xff, sizeof (page_hash_table));
3390 memset(GC_written_pages, 0xff, sizeof(page_hash_table));
3391 # ifdef GC_SOLARIS_THREADS
3392 BZERO(GC_fresh_pages,
3393 MAX_FRESH_PAGES * sizeof (struct hblk *));
3394 # endif
3395 return;
3399 /* Copy dirty bits into GC_grungy_pages */
3400 nmaps = ((struct prpageheader *)bufp) -> pr_nmap;
3401 /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
3402 nmaps, PG_REFERENCED, PG_MODIFIED); */
3403 bufp = bufp + sizeof(struct prpageheader);
3404 for (i = 0; i < nmaps; i++) {
3405 map = (struct prasmap *)bufp;
3406 vaddr = (ptr_t)(map -> pr_vaddr);
3407 ps = map -> pr_pagesize;
3408 np = map -> pr_npage;
3409 /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
3410 limit = vaddr + ps * np;
3411 bufp += sizeof (struct prasmap);
3412 for (current_addr = vaddr;
3413 current_addr < limit; current_addr += ps){
3414 if ((*bufp++) & PG_MODIFIED) {
3415 register struct hblk * h = (struct hblk *) current_addr;
3417 while ((ptr_t)h < current_addr + ps) {
3418 register word index = PHT_HASH(h);
3420 set_pht_entry_from_index(GC_grungy_pages, index);
3421 # ifdef GC_SOLARIS_THREADS
3423 register int slot = FRESH_PAGE_SLOT(h);
3425 if (GC_fresh_pages[slot] == h) {
3426 GC_fresh_pages[slot] = 0;
3429 # endif
3430 h++;
3434 bufp += sizeof(long) - 1;
3435 bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1));
3437 /* Update GC_written_pages. */
3438 GC_or_pages(GC_written_pages, GC_grungy_pages);
3439 # ifdef GC_SOLARIS_THREADS
3440 /* Make sure that old stacks are considered completely clean */
3441 /* unless written again. */
3442 GC_old_stacks_are_fresh();
3443 # endif
3446 #undef READ
3448 GC_bool GC_page_was_dirty(h)
3449 struct hblk *h;
3451 register word index = PHT_HASH(h);
3452 register GC_bool result;
3454 result = get_pht_entry_from_index(GC_grungy_pages, index);
3455 # ifdef GC_SOLARIS_THREADS
3456 if (result && PAGE_IS_FRESH(h)) result = FALSE;
3457 /* This happens only if page was declared fresh since */
3458 /* the read_dirty call, e.g. because it's in an unused */
3459 /* thread stack. It's OK to treat it as clean, in */
3460 /* that case. And it's consistent with */
3461 /* GC_page_was_ever_dirty. */
3462 # endif
3463 return(result);
3466 GC_bool GC_page_was_ever_dirty(h)
3467 struct hblk *h;
3469 register word index = PHT_HASH(h);
3470 register GC_bool result;
3472 result = get_pht_entry_from_index(GC_written_pages, index);
3473 # ifdef GC_SOLARIS_THREADS
3474 if (result && PAGE_IS_FRESH(h)) result = FALSE;
3475 # endif
3476 return(result);
3479 /* Caller holds allocation lock. */
3480 void GC_is_fresh(h, n)
3481 struct hblk *h;
3482 word n;
3485 register word index;
3487 # ifdef GC_SOLARIS_THREADS
3488 register word i;
3490 if (GC_fresh_pages != 0) {
3491 for (i = 0; i < n; i++) {
3492 ADD_FRESH_PAGE(h + i);
3495 # endif
3498 # endif /* PROC_VDB */
3501 # ifdef PCR_VDB
3503 # include "vd/PCR_VD.h"
3505 # define NPAGES (32*1024) /* 128 MB */
3507 PCR_VD_DB GC_grungy_bits[NPAGES];
3509 ptr_t GC_vd_base; /* Address corresponding to GC_grungy_bits[0] */
3510 /* HBLKSIZE aligned. */
3512 void GC_dirty_init()
3514 GC_dirty_maintained = TRUE;
3515 /* For the time being, we assume the heap generally grows up */
3516 GC_vd_base = GC_heap_sects[0].hs_start;
3517 if (GC_vd_base == 0) {
3518 ABORT("Bad initial heap segment");
3520 if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE)
3521 != PCR_ERes_okay) {
3522 ABORT("dirty bit initialization failed");
3526 void GC_read_dirty()
3528 /* lazily enable dirty bits on newly added heap sects */
3530 static int onhs = 0;
3531 int nhs = GC_n_heap_sects;
3532 for( ; onhs < nhs; onhs++ ) {
3533 PCR_VD_WriteProtectEnable(
3534 GC_heap_sects[onhs].hs_start,
3535 GC_heap_sects[onhs].hs_bytes );
3540 if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits)
3541 != PCR_ERes_okay) {
3542 ABORT("dirty bit read failed");
3546 GC_bool GC_page_was_dirty(h)
3547 struct hblk *h;
3549 if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
3550 return(TRUE);
3552 return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
3555 /*ARGSUSED*/
3556 void GC_remove_protection(h, nblocks, is_ptrfree)
3557 struct hblk *h;
3558 word nblocks;
3559 GC_bool is_ptrfree;
3561 PCR_VD_WriteProtectDisable(h, nblocks*HBLKSIZE);
3562 PCR_VD_WriteProtectEnable(h, nblocks*HBLKSIZE);
3565 # endif /* PCR_VDB */
3567 #if defined(MPROTECT_VDB) && defined(DARWIN)
3568 /* The following sources were used as a *reference* for this exception handling
3569 code:
3570 1. Apple's mach/xnu documentation
3571 2. Timothy J. Wood's "Mach Exception Handlers 101" post to the
3572 omnigroup's macosx-dev list.
3573 www.omnigroup.com/mailman/archive/macosx-dev/2000-June/002030.html
3574 3. macosx-nat.c from Apple's GDB source code.
3577 /* The bug that caused all this trouble should now be fixed. This should
3578 eventually be removed if all goes well. */
3579 /* define BROKEN_EXCEPTION_HANDLING */
3581 #include <mach/mach.h>
3582 #include <mach/mach_error.h>
3583 #include <mach/thread_status.h>
3584 #include <mach/exception.h>
3585 #include <mach/task.h>
3586 #include <pthread.h>
3588 /* These are not defined in any header, although they are documented */
3589 extern boolean_t exc_server(mach_msg_header_t *,mach_msg_header_t *);
3590 extern kern_return_t exception_raise(
3591 mach_port_t,mach_port_t,mach_port_t,
3592 exception_type_t,exception_data_t,mach_msg_type_number_t);
3593 extern kern_return_t exception_raise_state(
3594 mach_port_t,mach_port_t,mach_port_t,
3595 exception_type_t,exception_data_t,mach_msg_type_number_t,
3596 thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3597 thread_state_t,mach_msg_type_number_t*);
3598 extern kern_return_t exception_raise_state_identity(
3599 mach_port_t,mach_port_t,mach_port_t,
3600 exception_type_t,exception_data_t,mach_msg_type_number_t,
3601 thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3602 thread_state_t,mach_msg_type_number_t*);
3605 #define MAX_EXCEPTION_PORTS 16
3607 static struct {
3608 mach_msg_type_number_t count;
3609 exception_mask_t masks[MAX_EXCEPTION_PORTS];
3610 exception_handler_t ports[MAX_EXCEPTION_PORTS];
3611 exception_behavior_t behaviors[MAX_EXCEPTION_PORTS];
3612 thread_state_flavor_t flavors[MAX_EXCEPTION_PORTS];
3613 } GC_old_exc_ports;
3615 static struct {
3616 mach_port_t exception;
3617 #if defined(THREADS)
3618 mach_port_t reply;
3619 #endif
3620 } GC_ports;
3622 typedef struct {
3623 mach_msg_header_t head;
3624 } GC_msg_t;
3626 typedef enum {
3627 GC_MP_NORMAL, GC_MP_DISCARDING, GC_MP_STOPPED
3628 } GC_mprotect_state_t;
3630 /* FIXME: 1 and 2 seem to be safe to use in the msgh_id field,
3631 but it isn't documented. Use the source and see if they
3632 should be ok. */
3633 #define ID_STOP 1
3634 #define ID_RESUME 2
3636 /* These values are only used on the reply port */
3637 #define ID_ACK 3
3639 #if defined(THREADS)
3641 GC_mprotect_state_t GC_mprotect_state;
3643 /* The following should ONLY be called when the world is stopped */
3644 static void GC_mprotect_thread_notify(mach_msg_id_t id) {
3645 struct {
3646 GC_msg_t msg;
3647 mach_msg_trailer_t trailer;
3648 } buf;
3649 mach_msg_return_t r;
3650 /* remote, local */
3651 buf.msg.head.msgh_bits =
3652 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3653 buf.msg.head.msgh_size = sizeof(buf.msg);
3654 buf.msg.head.msgh_remote_port = GC_ports.exception;
3655 buf.msg.head.msgh_local_port = MACH_PORT_NULL;
3656 buf.msg.head.msgh_id = id;
3658 r = mach_msg(
3659 &buf.msg.head,
3660 MACH_SEND_MSG|MACH_RCV_MSG|MACH_RCV_LARGE,
3661 sizeof(buf.msg),
3662 sizeof(buf),
3663 GC_ports.reply,
3664 MACH_MSG_TIMEOUT_NONE,
3665 MACH_PORT_NULL);
3666 if(r != MACH_MSG_SUCCESS)
3667 ABORT("mach_msg failed in GC_mprotect_thread_notify");
3668 if(buf.msg.head.msgh_id != ID_ACK)
3669 ABORT("invalid ack in GC_mprotect_thread_notify");
3672 /* Should only be called by the mprotect thread */
3673 static void GC_mprotect_thread_reply() {
3674 GC_msg_t msg;
3675 mach_msg_return_t r;
3676 /* remote, local */
3677 msg.head.msgh_bits =
3678 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3679 msg.head.msgh_size = sizeof(msg);
3680 msg.head.msgh_remote_port = GC_ports.reply;
3681 msg.head.msgh_local_port = MACH_PORT_NULL;
3682 msg.head.msgh_id = ID_ACK;
3684 r = mach_msg(
3685 &msg.head,
3686 MACH_SEND_MSG,
3687 sizeof(msg),
3689 MACH_PORT_NULL,
3690 MACH_MSG_TIMEOUT_NONE,
3691 MACH_PORT_NULL);
3692 if(r != MACH_MSG_SUCCESS)
3693 ABORT("mach_msg failed in GC_mprotect_thread_reply");
3696 void GC_mprotect_stop() {
3697 GC_mprotect_thread_notify(ID_STOP);
3699 void GC_mprotect_resume() {
3700 GC_mprotect_thread_notify(ID_RESUME);
3703 #else /* !THREADS */
3704 /* The compiler should optimize away any GC_mprotect_state computations */
3705 #define GC_mprotect_state GC_MP_NORMAL
3706 #endif
3708 static void *GC_mprotect_thread(void *arg) {
3709 mach_msg_return_t r;
3710 /* These two structures contain some private kernel data. We don't need to
3711 access any of it so we don't bother defining a proper struct. The
3712 correct definitions are in the xnu source code. */
3713 struct {
3714 mach_msg_header_t head;
3715 char data[256];
3716 } reply;
3717 struct {
3718 mach_msg_header_t head;
3719 mach_msg_body_t msgh_body;
3720 char data[1024];
3721 } msg;
3723 mach_msg_id_t id;
3725 GC_darwin_register_mach_handler_thread(mach_thread_self());
3727 for(;;) {
3728 r = mach_msg(
3729 &msg.head,
3730 MACH_RCV_MSG|MACH_RCV_LARGE|
3731 (GC_mprotect_state == GC_MP_DISCARDING ? MACH_RCV_TIMEOUT : 0),
3733 sizeof(msg),
3734 GC_ports.exception,
3735 GC_mprotect_state == GC_MP_DISCARDING ? 0 : MACH_MSG_TIMEOUT_NONE,
3736 MACH_PORT_NULL);
3738 id = r == MACH_MSG_SUCCESS ? msg.head.msgh_id : -1;
3740 #if defined(THREADS)
3741 if(GC_mprotect_state == GC_MP_DISCARDING) {
3742 if(r == MACH_RCV_TIMED_OUT) {
3743 GC_mprotect_state = GC_MP_STOPPED;
3744 GC_mprotect_thread_reply();
3745 continue;
3747 if(r == MACH_MSG_SUCCESS && (id == ID_STOP || id == ID_RESUME))
3748 ABORT("out of order mprotect thread request");
3750 #endif
3752 if(r != MACH_MSG_SUCCESS) {
3753 GC_err_printf2("mach_msg failed with %d %s\n",
3754 (int)r,mach_error_string(r));
3755 ABORT("mach_msg failed");
3758 switch(id) {
3759 #if defined(THREADS)
3760 case ID_STOP:
3761 if(GC_mprotect_state != GC_MP_NORMAL)
3762 ABORT("Called mprotect_stop when state wasn't normal");
3763 GC_mprotect_state = GC_MP_DISCARDING;
3764 break;
3765 case ID_RESUME:
3766 if(GC_mprotect_state != GC_MP_STOPPED)
3767 ABORT("Called mprotect_resume when state wasn't stopped");
3768 GC_mprotect_state = GC_MP_NORMAL;
3769 GC_mprotect_thread_reply();
3770 break;
3771 #endif /* THREADS */
3772 default:
3773 /* Handle the message (calls catch_exception_raise) */
3774 if(!exc_server(&msg.head,&reply.head))
3775 ABORT("exc_server failed");
3776 /* Send the reply */
3777 r = mach_msg(
3778 &reply.head,
3779 MACH_SEND_MSG,
3780 reply.head.msgh_size,
3782 MACH_PORT_NULL,
3783 MACH_MSG_TIMEOUT_NONE,
3784 MACH_PORT_NULL);
3785 if(r != MACH_MSG_SUCCESS) {
3786 /* This will fail if the thread dies, but the thread shouldn't
3787 die... */
3788 #ifdef BROKEN_EXCEPTION_HANDLING
3789 GC_err_printf2(
3790 "mach_msg failed with %d %s while sending exc reply\n",
3791 (int)r,mach_error_string(r));
3792 #else
3793 ABORT("mach_msg failed while sending exception reply");
3794 #endif
3796 } /* switch */
3797 } /* for(;;) */
3798 /* NOT REACHED */
3799 return NULL;
3802 /* All this SIGBUS code shouldn't be necessary. All protection faults should
3803 be going throught the mach exception handler. However, it seems a SIGBUS is
3804 occasionally sent for some unknown reason. Even more odd, it seems to be
3805 meaningless and safe to ignore. */
3806 #ifdef BROKEN_EXCEPTION_HANDLING
3808 typedef void (* SIG_PF)();
3809 static SIG_PF GC_old_bus_handler;
3811 /* Updates to this aren't atomic, but the SIGBUSs seem pretty rare.
3812 Even if this doesn't get updated property, it isn't really a problem */
3813 static int GC_sigbus_count;
3815 static void GC_darwin_sigbus(int num,siginfo_t *sip,void *context) {
3816 if(num != SIGBUS) ABORT("Got a non-sigbus signal in the sigbus handler");
3818 /* Ugh... some seem safe to ignore, but too many in a row probably means
3819 trouble. GC_sigbus_count is reset for each mach exception that is
3820 handled */
3821 if(GC_sigbus_count >= 8) {
3822 ABORT("Got more than 8 SIGBUSs in a row!");
3823 } else {
3824 GC_sigbus_count++;
3825 GC_err_printf0("GC: WARNING: Ignoring SIGBUS.\n");
3828 #endif /* BROKEN_EXCEPTION_HANDLING */
3830 void GC_dirty_init() {
3831 kern_return_t r;
3832 mach_port_t me;
3833 pthread_t thread;
3834 pthread_attr_t attr;
3835 exception_mask_t mask;
3837 # ifdef PRINTSTATS
3838 GC_printf0("Inititalizing mach/darwin mprotect virtual dirty bit "
3839 "implementation\n");
3840 # endif
3841 # ifdef BROKEN_EXCEPTION_HANDLING
3842 GC_err_printf0("GC: WARNING: Enabling workarounds for various darwin "
3843 "exception handling bugs.\n");
3844 # endif
3845 GC_dirty_maintained = TRUE;
3846 if (GC_page_size % HBLKSIZE != 0) {
3847 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
3848 ABORT("Page size not multiple of HBLKSIZE");
3851 GC_task_self = me = mach_task_self();
3853 r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.exception);
3854 if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (exception port)");
3856 r = mach_port_insert_right(me,GC_ports.exception,GC_ports.exception,
3857 MACH_MSG_TYPE_MAKE_SEND);
3858 if(r != KERN_SUCCESS)
3859 ABORT("mach_port_insert_right failed (exception port)");
3861 #if defined(THREADS)
3862 r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.reply);
3863 if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (reply port)");
3864 #endif
3866 /* The exceptions we want to catch */
3867 mask = EXC_MASK_BAD_ACCESS;
3869 r = task_get_exception_ports(
3871 mask,
3872 GC_old_exc_ports.masks,
3873 &GC_old_exc_ports.count,
3874 GC_old_exc_ports.ports,
3875 GC_old_exc_ports.behaviors,
3876 GC_old_exc_ports.flavors
3878 if(r != KERN_SUCCESS) ABORT("task_get_exception_ports failed");
3880 r = task_set_exception_ports(
3882 mask,
3883 GC_ports.exception,
3884 EXCEPTION_DEFAULT,
3885 GC_MACH_THREAD_STATE_FLAVOR
3887 if(r != KERN_SUCCESS) ABORT("task_set_exception_ports failed");
3889 if(pthread_attr_init(&attr) != 0) ABORT("pthread_attr_init failed");
3890 if(pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED) != 0)
3891 ABORT("pthread_attr_setdetachedstate failed");
3893 # undef pthread_create
3894 /* This will call the real pthread function, not our wrapper */
3895 if(pthread_create(&thread,&attr,GC_mprotect_thread,NULL) != 0)
3896 ABORT("pthread_create failed");
3897 pthread_attr_destroy(&attr);
3899 /* Setup the sigbus handler for ignoring the meaningless SIGBUSs */
3900 #ifdef BROKEN_EXCEPTION_HANDLING
3902 struct sigaction sa, oldsa;
3903 sa.sa_handler = (SIG_PF)GC_darwin_sigbus;
3904 sigemptyset(&sa.sa_mask);
3905 sa.sa_flags = SA_RESTART|SA_SIGINFO;
3906 if(sigaction(SIGBUS,&sa,&oldsa) < 0) ABORT("sigaction");
3907 GC_old_bus_handler = (SIG_PF)oldsa.sa_handler;
3908 if (GC_old_bus_handler != SIG_DFL) {
3909 # ifdef PRINTSTATS
3910 GC_err_printf0("Replaced other SIGBUS handler\n");
3911 # endif
3914 #endif /* BROKEN_EXCEPTION_HANDLING */
3917 /* The source code for Apple's GDB was used as a reference for the exception
3918 forwarding code. This code is similar to be GDB code only because there is
3919 only one way to do it. */
3920 static kern_return_t GC_forward_exception(
3921 mach_port_t thread,
3922 mach_port_t task,
3923 exception_type_t exception,
3924 exception_data_t data,
3925 mach_msg_type_number_t data_count
3927 int i;
3928 kern_return_t r;
3929 mach_port_t port;
3930 exception_behavior_t behavior;
3931 thread_state_flavor_t flavor;
3933 thread_state_t thread_state;
3934 mach_msg_type_number_t thread_state_count = THREAD_STATE_MAX;
3936 for(i=0;i<GC_old_exc_ports.count;i++)
3937 if(GC_old_exc_ports.masks[i] & (1 << exception))
3938 break;
3939 if(i==GC_old_exc_ports.count) ABORT("No handler for exception!");
3941 port = GC_old_exc_ports.ports[i];
3942 behavior = GC_old_exc_ports.behaviors[i];
3943 flavor = GC_old_exc_ports.flavors[i];
3945 if(behavior != EXCEPTION_DEFAULT) {
3946 r = thread_get_state(thread,flavor,thread_state,&thread_state_count);
3947 if(r != KERN_SUCCESS)
3948 ABORT("thread_get_state failed in forward_exception");
3951 switch(behavior) {
3952 case EXCEPTION_DEFAULT:
3953 r = exception_raise(port,thread,task,exception,data,data_count);
3954 break;
3955 case EXCEPTION_STATE:
3956 r = exception_raise_state(port,thread,task,exception,data,
3957 data_count,&flavor,thread_state,thread_state_count,
3958 thread_state,&thread_state_count);
3959 break;
3960 case EXCEPTION_STATE_IDENTITY:
3961 r = exception_raise_state_identity(port,thread,task,exception,data,
3962 data_count,&flavor,thread_state,thread_state_count,
3963 thread_state,&thread_state_count);
3964 break;
3965 default:
3966 r = KERN_FAILURE; /* make gcc happy */
3967 ABORT("forward_exception: unknown behavior");
3968 break;
3971 if(behavior != EXCEPTION_DEFAULT) {
3972 r = thread_set_state(thread,flavor,thread_state,thread_state_count);
3973 if(r != KERN_SUCCESS)
3974 ABORT("thread_set_state failed in forward_exception");
3977 return r;
3980 #define FWD() GC_forward_exception(thread,task,exception,code,code_count)
3982 /* This violates the namespace rules but there isn't anything that can be done
3983 about it. The exception handling stuff is hard coded to call this */
3984 kern_return_t
3985 catch_exception_raise(
3986 mach_port_t exception_port,mach_port_t thread,mach_port_t task,
3987 exception_type_t exception,exception_data_t code,
3988 mach_msg_type_number_t code_count
3990 kern_return_t r;
3991 char *addr;
3992 struct hblk *h;
3993 int i;
3994 # if defined(POWERPC)
3995 # if CPP_WORDSZ == 32
3996 thread_state_flavor_t flavor = PPC_EXCEPTION_STATE;
3997 mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE_COUNT;
3998 ppc_exception_state_t exc_state;
3999 # else
4000 thread_state_flavor_t flavor = PPC_EXCEPTION_STATE64;
4001 mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE64_COUNT;
4002 ppc_exception_state64_t exc_state;
4003 # endif
4004 # elif defined(I386)
4005 thread_state_flavor_t flavor = i386_EXCEPTION_STATE;
4006 mach_msg_type_number_t exc_state_count = i386_EXCEPTION_STATE_COUNT;
4007 i386_exception_state_t exc_state;
4008 # else
4009 # error FIXME for non-ppc darwin
4010 # endif
4013 if(exception != EXC_BAD_ACCESS || code[0] != KERN_PROTECTION_FAILURE) {
4014 #ifdef DEBUG_EXCEPTION_HANDLING
4015 /* We aren't interested, pass it on to the old handler */
4016 GC_printf3("Exception: 0x%x Code: 0x%x 0x%x in catch....\n",
4017 exception,
4018 code_count > 0 ? code[0] : -1,
4019 code_count > 1 ? code[1] : -1);
4020 #endif
4021 return FWD();
4024 r = thread_get_state(thread,flavor,
4025 (natural_t*)&exc_state,&exc_state_count);
4026 if(r != KERN_SUCCESS) {
4027 /* The thread is supposed to be suspended while the exception handler
4028 is called. This shouldn't fail. */
4029 #ifdef BROKEN_EXCEPTION_HANDLING
4030 GC_err_printf0("thread_get_state failed in "
4031 "catch_exception_raise\n");
4032 return KERN_SUCCESS;
4033 #else
4034 ABORT("thread_get_state failed in catch_exception_raise");
4035 #endif
4038 /* This is the address that caused the fault */
4039 #if defined(POWERPC)
4040 addr = (char*) exc_state.dar;
4041 #elif defined (I386)
4042 addr = (char*) exc_state.faultvaddr;
4043 #else
4044 # error FIXME for non POWERPC/I386
4045 #endif
4047 if((HDR(addr)) == 0) {
4048 /* Ugh... just like the SIGBUS problem above, it seems we get a bogus
4049 KERN_PROTECTION_FAILURE every once and a while. We wait till we get
4050 a bunch in a row before doing anything about it. If a "real" fault
4051 ever occurres it'll just keep faulting over and over and we'll hit
4052 the limit pretty quickly. */
4053 #ifdef BROKEN_EXCEPTION_HANDLING
4054 static char *last_fault;
4055 static int last_fault_count;
4057 if(addr != last_fault) {
4058 last_fault = addr;
4059 last_fault_count = 0;
4061 if(++last_fault_count < 32) {
4062 if(last_fault_count == 1)
4063 GC_err_printf1(
4064 "GC: WARNING: Ignoring KERN_PROTECTION_FAILURE at %p\n",
4065 addr);
4066 return KERN_SUCCESS;
4069 GC_err_printf1("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr);
4070 /* Can't pass it along to the signal handler because that is
4071 ignoring SIGBUS signals. We also shouldn't call ABORT here as
4072 signals don't always work too well from the exception handler. */
4073 GC_err_printf0("Aborting\n");
4074 exit(EXIT_FAILURE);
4075 #else /* BROKEN_EXCEPTION_HANDLING */
4076 /* Pass it along to the next exception handler
4077 (which should call SIGBUS/SIGSEGV) */
4078 return FWD();
4079 #endif /* !BROKEN_EXCEPTION_HANDLING */
4082 #ifdef BROKEN_EXCEPTION_HANDLING
4083 /* Reset the number of consecutive SIGBUSs */
4084 GC_sigbus_count = 0;
4085 #endif
4087 if(GC_mprotect_state == GC_MP_NORMAL) { /* common case */
4088 h = (struct hblk*)((word)addr & ~(GC_page_size-1));
4089 UNPROTECT(h, GC_page_size);
4090 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
4091 register int index = PHT_HASH(h+i);
4092 async_set_pht_entry_from_index(GC_dirty_pages, index);
4094 } else if(GC_mprotect_state == GC_MP_DISCARDING) {
4095 /* Lie to the thread for now. No sense UNPROTECT()ing the memory
4096 when we're just going to PROTECT() it again later. The thread
4097 will just fault again once it resumes */
4098 } else {
4099 /* Shouldn't happen, i don't think */
4100 GC_printf0("KERN_PROTECTION_FAILURE while world is stopped\n");
4101 return FWD();
4103 return KERN_SUCCESS;
4105 #undef FWD
4107 /* These should never be called, but just in case... */
4108 kern_return_t catch_exception_raise_state(mach_port_name_t exception_port,
4109 int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
4110 int flavor, thread_state_t old_state, int old_stateCnt,
4111 thread_state_t new_state, int new_stateCnt)
4113 ABORT("catch_exception_raise_state");
4114 return(KERN_INVALID_ARGUMENT);
4116 kern_return_t catch_exception_raise_state_identity(
4117 mach_port_name_t exception_port, mach_port_t thread, mach_port_t task,
4118 int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
4119 int flavor, thread_state_t old_state, int old_stateCnt,
4120 thread_state_t new_state, int new_stateCnt)
4122 ABORT("catch_exception_raise_state_identity");
4123 return(KERN_INVALID_ARGUMENT);
4127 #endif /* DARWIN && MPROTECT_VDB */
4129 # ifndef HAVE_INCREMENTAL_PROTECTION_NEEDS
4130 int GC_incremental_protection_needs()
4132 return GC_PROTECTS_NONE;
4134 # endif /* !HAVE_INCREMENTAL_PROTECTION_NEEDS */
4137 * Call stack save code for debugging.
4138 * Should probably be in mach_dep.c, but that requires reorganization.
4141 /* I suspect the following works for most X86 *nix variants, so */
4142 /* long as the frame pointer is explicitly stored. In the case of gcc, */
4143 /* compiler flags (e.g. -fomit-frame-pointer) determine whether it is. */
4144 #if defined(I386) && defined(LINUX) && defined(SAVE_CALL_CHAIN)
4145 # include <features.h>
4147 struct frame {
4148 struct frame *fr_savfp;
4149 long fr_savpc;
4150 long fr_arg[NARGS]; /* All the arguments go here. */
4152 #endif
4154 #if defined(SPARC)
4155 # if defined(LINUX)
4156 # include <features.h>
4158 struct frame {
4159 long fr_local[8];
4160 long fr_arg[6];
4161 struct frame *fr_savfp;
4162 long fr_savpc;
4163 # ifndef __arch64__
4164 char *fr_stret;
4165 # endif
4166 long fr_argd[6];
4167 long fr_argx[0];
4169 # else
4170 # if defined(SUNOS4)
4171 # include <machine/frame.h>
4172 # else
4173 # if defined (DRSNX)
4174 # include <sys/sparc/frame.h>
4175 # else
4176 # if defined(OPENBSD)
4177 # include <frame.h>
4178 # else
4179 # if defined(FREEBSD) || defined(NETBSD)
4180 # include <machine/frame.h>
4181 # else
4182 # include <sys/frame.h>
4183 # endif
4184 # endif
4185 # endif
4186 # endif
4187 # endif
4188 # if NARGS > 6
4189 --> We only know how to to get the first 6 arguments
4190 # endif
4191 #endif /* SPARC */
4193 #ifdef NEED_CALLINFO
4194 /* Fill in the pc and argument information for up to NFRAMES of my */
4195 /* callers. Ignore my frame and my callers frame. */
4197 #ifdef LINUX
4198 # include <unistd.h>
4199 #endif
4201 #endif /* NEED_CALLINFO */
4203 #if defined(GC_HAVE_BUILTIN_BACKTRACE)
4204 # include <execinfo.h>
4205 #endif
4207 #ifdef SAVE_CALL_CHAIN
4209 #if NARGS == 0 && NFRAMES % 2 == 0 /* No padding */ \
4210 && defined(GC_HAVE_BUILTIN_BACKTRACE)
4212 #ifdef REDIRECT_MALLOC
4213 /* Deal with possible malloc calls in backtrace by omitting */
4214 /* the infinitely recursing backtrace. */
4215 # ifdef THREADS
4216 __thread /* If your compiler doesn't understand this */
4217 /* you could use something like pthread_getspecific. */
4218 # endif
4219 GC_in_save_callers = FALSE;
4220 #endif
4222 void GC_save_callers (info)
4223 struct callinfo info[NFRAMES];
4225 void * tmp_info[NFRAMES + 1];
4226 int npcs, i;
4227 # define IGNORE_FRAMES 1
4229 /* We retrieve NFRAMES+1 pc values, but discard the first, since it */
4230 /* points to our own frame. */
4231 # ifdef REDIRECT_MALLOC
4232 if (GC_in_save_callers) {
4233 info[0].ci_pc = (word)(&GC_save_callers);
4234 for (i = 1; i < NFRAMES; ++i) info[i].ci_pc = 0;
4235 return;
4237 GC_in_save_callers = TRUE;
4238 # endif
4239 GC_ASSERT(sizeof(struct callinfo) == sizeof(void *));
4240 npcs = backtrace((void **)tmp_info, NFRAMES + IGNORE_FRAMES);
4241 BCOPY(tmp_info+IGNORE_FRAMES, info, (npcs - IGNORE_FRAMES) * sizeof(void *));
4242 for (i = npcs - IGNORE_FRAMES; i < NFRAMES; ++i) info[i].ci_pc = 0;
4243 # ifdef REDIRECT_MALLOC
4244 GC_in_save_callers = FALSE;
4245 # endif
4248 #else /* No builtin backtrace; do it ourselves */
4250 #if (defined(OPENBSD) || defined(NETBSD) || defined(FREEBSD)) && defined(SPARC)
4251 # define FR_SAVFP fr_fp
4252 # define FR_SAVPC fr_pc
4253 #else
4254 # define FR_SAVFP fr_savfp
4255 # define FR_SAVPC fr_savpc
4256 #endif
4258 #if defined(SPARC) && (defined(__arch64__) || defined(__sparcv9))
4259 # define BIAS 2047
4260 #else
4261 # define BIAS 0
4262 #endif
4264 void GC_save_callers (info)
4265 struct callinfo info[NFRAMES];
4267 struct frame *frame;
4268 struct frame *fp;
4269 int nframes = 0;
4270 # ifdef I386
4271 /* We assume this is turned on only with gcc as the compiler. */
4272 asm("movl %%ebp,%0" : "=r"(frame));
4273 fp = frame;
4274 # else
4275 frame = (struct frame *) GC_save_regs_in_stack ();
4276 fp = (struct frame *)((long) frame -> FR_SAVFP + BIAS);
4277 #endif
4279 for (; (!(fp HOTTER_THAN frame) && !(GC_stackbottom HOTTER_THAN (ptr_t)fp)
4280 && (nframes < NFRAMES));
4281 fp = (struct frame *)((long) fp -> FR_SAVFP + BIAS), nframes++) {
4282 register int i;
4284 info[nframes].ci_pc = fp->FR_SAVPC;
4285 # if NARGS > 0
4286 for (i = 0; i < NARGS; i++) {
4287 info[nframes].ci_arg[i] = ~(fp->fr_arg[i]);
4289 # endif /* NARGS > 0 */
4291 if (nframes < NFRAMES) info[nframes].ci_pc = 0;
4294 #endif /* No builtin backtrace */
4296 #endif /* SAVE_CALL_CHAIN */
4298 #ifdef NEED_CALLINFO
4300 /* Print info to stderr. We do NOT hold the allocation lock */
4301 void GC_print_callers (info)
4302 struct callinfo info[NFRAMES];
4304 register int i;
4305 static int reentry_count = 0;
4306 GC_bool stop = FALSE;
4308 /* FIXME: This should probably use a different lock, so that we */
4309 /* become callable with or without the allocation lock. */
4310 LOCK();
4311 ++reentry_count;
4312 UNLOCK();
4314 # if NFRAMES == 1
4315 GC_err_printf0("\tCaller at allocation:\n");
4316 # else
4317 GC_err_printf0("\tCall chain at allocation:\n");
4318 # endif
4319 for (i = 0; i < NFRAMES && !stop ; i++) {
4320 if (info[i].ci_pc == 0) break;
4321 # if NARGS > 0
4323 int j;
4325 GC_err_printf0("\t\targs: ");
4326 for (j = 0; j < NARGS; j++) {
4327 if (j != 0) GC_err_printf0(", ");
4328 GC_err_printf2("%d (0x%X)", ~(info[i].ci_arg[j]),
4329 ~(info[i].ci_arg[j]));
4331 GC_err_printf0("\n");
4333 # endif
4334 if (reentry_count > 1) {
4335 /* We were called during an allocation during */
4336 /* a previous GC_print_callers call; punt. */
4337 GC_err_printf1("\t\t##PC##= 0x%lx\n", info[i].ci_pc);
4338 continue;
4341 # ifdef LINUX
4342 FILE *pipe;
4343 # endif
4344 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4345 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4346 char **sym_name =
4347 backtrace_symbols((void **)(&(info[i].ci_pc)), 1);
4348 char *name = sym_name[0];
4349 # else
4350 char buf[40];
4351 char *name = buf;
4352 sprintf(buf, "##PC##= 0x%lx", info[i].ci_pc);
4353 # endif
4354 # if defined(LINUX) && !defined(SMALL_CONFIG)
4355 /* Try for a line number. */
4357 # define EXE_SZ 100
4358 static char exe_name[EXE_SZ];
4359 # define CMD_SZ 200
4360 char cmd_buf[CMD_SZ];
4361 # define RESULT_SZ 200
4362 static char result_buf[RESULT_SZ];
4363 size_t result_len;
4364 char *old_preload;
4365 # define PRELOAD_SZ 200
4366 char preload_buf[PRELOAD_SZ];
4367 static GC_bool found_exe_name = FALSE;
4368 static GC_bool will_fail = FALSE;
4369 int ret_code;
4370 /* Try to get it via a hairy and expensive scheme. */
4371 /* First we get the name of the executable: */
4372 if (will_fail) goto out;
4373 if (!found_exe_name) {
4374 ret_code = readlink("/proc/self/exe", exe_name, EXE_SZ);
4375 if (ret_code < 0 || ret_code >= EXE_SZ
4376 || exe_name[0] != '/') {
4377 will_fail = TRUE; /* Dont try again. */
4378 goto out;
4380 exe_name[ret_code] = '\0';
4381 found_exe_name = TRUE;
4383 /* Then we use popen to start addr2line -e <exe> <addr> */
4384 /* There are faster ways to do this, but hopefully this */
4385 /* isn't time critical. */
4386 sprintf(cmd_buf, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name,
4387 (unsigned long)info[i].ci_pc);
4388 old_preload = getenv ("LD_PRELOAD");
4389 if (0 != old_preload) {
4390 if (strlen (old_preload) >= PRELOAD_SZ) {
4391 will_fail = TRUE;
4392 goto out;
4394 strcpy (preload_buf, old_preload);
4395 unsetenv ("LD_PRELOAD");
4397 pipe = popen(cmd_buf, "r");
4398 if (0 != old_preload
4399 && 0 != setenv ("LD_PRELOAD", preload_buf, 0)) {
4400 WARN("Failed to reset LD_PRELOAD\n", 0);
4402 if (pipe == NULL
4403 || (result_len = fread(result_buf, 1, RESULT_SZ - 1, pipe))
4404 == 0) {
4405 if (pipe != NULL) pclose(pipe);
4406 will_fail = TRUE;
4407 goto out;
4409 if (result_buf[result_len - 1] == '\n') --result_len;
4410 result_buf[result_len] = 0;
4411 if (result_buf[0] == '?'
4412 || result_buf[result_len-2] == ':'
4413 && result_buf[result_len-1] == '0') {
4414 pclose(pipe);
4415 goto out;
4417 /* Get rid of embedded newline, if any. Test for "main" */
4419 char * nl = strchr(result_buf, '\n');
4420 if (nl != NULL && nl < result_buf + result_len) {
4421 *nl = ':';
4423 if (strncmp(result_buf, "main", nl - result_buf) == 0) {
4424 stop = TRUE;
4427 if (result_len < RESULT_SZ - 25) {
4428 /* Add in hex address */
4429 sprintf(result_buf + result_len, " [0x%lx]",
4430 (unsigned long)info[i].ci_pc);
4432 name = result_buf;
4433 pclose(pipe);
4434 out:;
4436 # endif /* LINUX */
4437 GC_err_printf1("\t\t%s\n", name);
4438 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4439 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4440 free(sym_name); /* May call GC_free; that's OK */
4441 # endif
4444 LOCK();
4445 --reentry_count;
4446 UNLOCK();
4449 #endif /* NEED_CALLINFO */
4453 #if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
4455 /* Dump /proc/self/maps to GC_stderr, to enable looking up names for
4456 addresses in FIND_LEAK output. */
4458 static word dump_maps(char *maps)
4460 GC_err_write(maps, strlen(maps));
4461 return 1;
4464 void GC_print_address_map()
4466 GC_err_printf0("---------- Begin address map ----------\n");
4467 GC_apply_to_maps(dump_maps);
4468 GC_err_printf0("---------- End address map ----------\n");
4471 #endif