[runtime] Implement mono_verifier_class_is_valid_generic_instantiation () etc. even...
[mono-project.git] / libgc / os_dep.c
blobdca79850754069953233f0376304a45583a842ec
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 # elif defined(__GLIBC__)
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) && !defined(HAIKU)
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 HAIKU
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 /* HAIKU */
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(HAIKU) && !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, !HAIKU, !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 #if defined(HAIKU)
1961 #include <stdlib.h>
1963 ptr_t GC_haiku_get_mem(word bytes)
1965 void* mem;
1966 if (posix_memalign(&mem, GC_page_size, bytes) == 0)
1967 return mem;
1968 else
1969 return NULL;
1971 #endif
1973 #ifdef USE_MUNMAP
1975 /* For now, this only works on Win32/WinCE and some Unix-like */
1976 /* systems. If you have something else, don't define */
1977 /* USE_MUNMAP. */
1978 /* We assume ANSI C to support this feature. */
1980 #if !defined(MSWIN32) && !defined(MSWINCE)
1982 #include <unistd.h>
1983 #include <sys/mman.h>
1984 #include <sys/stat.h>
1985 #include <sys/types.h>
1987 #endif
1989 /* Compute a page aligned starting address for the unmap */
1990 /* operation on a block of size bytes starting at start. */
1991 /* Return 0 if the block is too small to make this feasible. */
1992 ptr_t GC_unmap_start(ptr_t start, word bytes)
1994 ptr_t result = start;
1995 /* Round start to next page boundary. */
1996 result += GC_page_size - 1;
1997 result = (ptr_t)((word)result & ~(GC_page_size - 1));
1998 if (result + GC_page_size > start + bytes) return 0;
1999 return result;
2002 /* Compute end address for an unmap operation on the indicated */
2003 /* block. */
2004 ptr_t GC_unmap_end(ptr_t start, word bytes)
2006 ptr_t end_addr = start + bytes;
2007 end_addr = (ptr_t)((word)end_addr & ~(GC_page_size - 1));
2008 return end_addr;
2011 /* Under Win32/WinCE we commit (map) and decommit (unmap) */
2012 /* memory using VirtualAlloc and VirtualFree. These functions */
2013 /* work on individual allocations of virtual memory, made */
2014 /* previously using VirtualAlloc with the MEM_RESERVE flag. */
2015 /* The ranges we need to (de)commit may span several of these */
2016 /* allocations; therefore we use VirtualQuery to check */
2017 /* allocation lengths, and split up the range as necessary. */
2019 /* We assume that GC_remap is called on exactly the same range */
2020 /* as a previous call to GC_unmap. It is safe to consistently */
2021 /* round the endpoints in both places. */
2022 void GC_unmap(ptr_t start, word bytes)
2024 ptr_t start_addr = GC_unmap_start(start, bytes);
2025 ptr_t end_addr = GC_unmap_end(start, bytes);
2026 word len = end_addr - start_addr;
2027 if (0 == start_addr) return;
2028 # if defined(MSWIN32) || defined(MSWINCE)
2029 while (len != 0) {
2030 MEMORY_BASIC_INFORMATION mem_info;
2031 GC_word free_len;
2032 if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
2033 != sizeof(mem_info))
2034 ABORT("Weird VirtualQuery result");
2035 free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
2036 if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT))
2037 ABORT("VirtualFree failed");
2038 GC_unmapped_bytes += free_len;
2039 start_addr += free_len;
2040 len -= free_len;
2042 # else
2043 /* We immediately remap it to prevent an intervening mmap from */
2044 /* accidentally grabbing the same address space. */
2046 void * result;
2047 result = mmap(start_addr, len, PROT_NONE,
2048 MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON,
2049 zero_fd, 0/* offset */);
2050 if (result != (void *)start_addr) ABORT("mmap(...PROT_NONE...) failed");
2052 GC_unmapped_bytes += len;
2053 # endif
2057 void GC_remap(ptr_t start, word bytes)
2059 ptr_t start_addr = GC_unmap_start(start, bytes);
2060 ptr_t end_addr = GC_unmap_end(start, bytes);
2061 word len = end_addr - start_addr;
2063 # if defined(MSWIN32) || defined(MSWINCE)
2064 ptr_t result;
2066 if (0 == start_addr) return;
2067 while (len != 0) {
2068 MEMORY_BASIC_INFORMATION mem_info;
2069 GC_word alloc_len;
2070 if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
2071 != sizeof(mem_info))
2072 ABORT("Weird VirtualQuery result");
2073 alloc_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
2074 result = VirtualAlloc(start_addr, alloc_len,
2075 MEM_COMMIT,
2076 PAGE_EXECUTE_READWRITE);
2077 if (result != start_addr) {
2078 ABORT("VirtualAlloc remapping failed");
2080 GC_unmapped_bytes -= alloc_len;
2081 start_addr += alloc_len;
2082 len -= alloc_len;
2084 # else
2085 /* It was already remapped with PROT_NONE. */
2086 int result;
2088 if (0 == start_addr) return;
2089 #ifdef NACL
2091 /* NaCl doesn't expose mprotect, but mmap should work fine */
2092 void * mmap_result;
2093 mmap_result = mmap(start_addr, len, PROT_READ | PROT_WRITE | OPT_PROT_EXEC,
2094 MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON,
2095 zero_fd, 0/* offset */);
2096 if (mmap_result != (void *)start_addr) ABORT("mmap as mprotect failed");
2097 /* Fake the return value as if mprotect succeeded. */
2098 result = 0;
2100 #else /* NACL */
2101 result = mprotect(start_addr, len,
2102 PROT_READ | PROT_WRITE | OPT_PROT_EXEC);
2103 #endif /* NACL */
2104 if (result != 0) {
2105 GC_err_printf3(
2106 "Mprotect failed at 0x%lx (length %ld) with errno %ld\n",
2107 start_addr, len, errno);
2108 ABORT("Mprotect remapping failed");
2110 GC_unmapped_bytes -= len;
2111 # endif
2114 /* Two adjacent blocks have already been unmapped and are about to */
2115 /* be merged. Unmap the whole block. This typically requires */
2116 /* that we unmap a small section in the middle that was not previously */
2117 /* unmapped due to alignment constraints. */
2118 void GC_unmap_gap(ptr_t start1, word bytes1, ptr_t start2, word bytes2)
2120 ptr_t start1_addr = GC_unmap_start(start1, bytes1);
2121 ptr_t end1_addr = GC_unmap_end(start1, bytes1);
2122 ptr_t start2_addr = GC_unmap_start(start2, bytes2);
2123 ptr_t end2_addr = GC_unmap_end(start2, bytes2);
2124 ptr_t start_addr = end1_addr;
2125 ptr_t end_addr = start2_addr;
2126 word len;
2127 GC_ASSERT(start1 + bytes1 == start2);
2128 if (0 == start1_addr) start_addr = GC_unmap_start(start1, bytes1 + bytes2);
2129 if (0 == start2_addr) end_addr = GC_unmap_end(start1, bytes1 + bytes2);
2130 if (0 == start_addr) return;
2131 len = end_addr - start_addr;
2132 # if defined(MSWIN32) || defined(MSWINCE)
2133 while (len != 0) {
2134 MEMORY_BASIC_INFORMATION mem_info;
2135 GC_word free_len;
2136 if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info))
2137 != sizeof(mem_info))
2138 ABORT("Weird VirtualQuery result");
2139 free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize;
2140 if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT))
2141 ABORT("VirtualFree failed");
2142 GC_unmapped_bytes += free_len;
2143 start_addr += free_len;
2144 len -= free_len;
2146 # else
2147 if (len != 0) {
2148 /* Immediately remap as above. */
2149 void * result;
2150 result = mmap(start_addr, len, PROT_NONE,
2151 MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON,
2152 zero_fd, 0/* offset */);
2153 if (result != (void *)start_addr) ABORT("mmap(...PROT_NONE...) failed");
2155 GC_unmapped_bytes += len;
2156 # endif
2159 #endif /* USE_MUNMAP */
2161 /* Routine for pushing any additional roots. In THREADS */
2162 /* environment, this is also responsible for marking from */
2163 /* thread stacks. */
2164 #ifndef THREADS
2165 void (*GC_push_other_roots)() = 0;
2166 #else /* THREADS */
2168 # ifdef PCR
2169 PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy)
2171 struct PCR_ThCtl_TInfoRep info;
2172 PCR_ERes result;
2174 info.ti_stkLow = info.ti_stkHi = 0;
2175 result = PCR_ThCtl_GetInfo(t, &info);
2176 GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi));
2177 return(result);
2180 /* Push the contents of an old object. We treat this as stack */
2181 /* data only becasue that makes it robust against mark stack */
2182 /* overflow. */
2183 PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data)
2185 GC_push_all_stack((ptr_t)p, (ptr_t)p + size);
2186 return(PCR_ERes_okay);
2190 void GC_default_push_other_roots GC_PROTO((void))
2192 /* Traverse data allocated by previous memory managers. */
2194 extern struct PCR_MM_ProcsRep * GC_old_allocator;
2196 if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false,
2197 GC_push_old_obj, 0)
2198 != PCR_ERes_okay) {
2199 ABORT("Old object enumeration failed");
2202 /* Traverse all thread stacks. */
2203 if (PCR_ERes_IsErr(
2204 PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0))
2205 || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) {
2206 ABORT("Thread stack marking failed\n");
2210 # endif /* PCR */
2212 # ifdef SRC_M3
2214 # ifdef ALL_INTERIOR_POINTERS
2215 --> misconfigured
2216 # endif
2218 void GC_push_thread_structures GC_PROTO((void))
2220 /* Not our responsibibility. */
2223 extern void ThreadF__ProcessStacks();
2225 void GC_push_thread_stack(start, stop)
2226 word start, stop;
2228 GC_push_all_stack((ptr_t)start, (ptr_t)stop + sizeof(word));
2231 /* Push routine with M3 specific calling convention. */
2232 GC_m3_push_root(dummy1, p, dummy2, dummy3)
2233 word *p;
2234 ptr_t dummy1, dummy2;
2235 int dummy3;
2237 word q = *p;
2239 GC_PUSH_ONE_STACK(q, p);
2242 /* M3 set equivalent to RTHeap.TracedRefTypes */
2243 typedef struct { int elts[1]; } RefTypeSet;
2244 RefTypeSet GC_TracedRefTypes = {{0x1}};
2246 void GC_default_push_other_roots GC_PROTO((void))
2248 /* Use the M3 provided routine for finding static roots. */
2249 /* This is a bit dubious, since it presumes no C roots. */
2250 /* We handle the collector roots explicitly in GC_push_roots */
2251 RTMain__GlobalMapProc(GC_m3_push_root, 0, GC_TracedRefTypes);
2252 if (GC_words_allocd > 0) {
2253 ThreadF__ProcessStacks(GC_push_thread_stack);
2255 /* Otherwise this isn't absolutely necessary, and we have */
2256 /* startup ordering problems. */
2259 # endif /* SRC_M3 */
2261 # if defined(GC_SOLARIS_THREADS) || defined(GC_PTHREADS) || \
2262 defined(GC_WIN32_THREADS)
2264 extern void GC_push_all_stacks();
2266 void GC_default_push_other_roots GC_PROTO((void))
2268 GC_push_all_stacks();
2271 # endif /* GC_SOLARIS_THREADS || GC_PTHREADS */
2272 #ifdef SN_TARGET_PS3
2273 void GC_default_push_other_roots GC_PROTO((void))
2275 printf ("WARNING WARNING WARNING\nGC_default_push_other_roots is not implemented\n");
2277 void GC_push_thread_structures GC_PROTO((void))
2279 printf ("WARNING WARNING WARNING\nGC_default_push_thread_structures is not implemented\n");
2281 #endif
2283 void (*GC_push_other_roots) GC_PROTO((void)) = GC_default_push_other_roots;
2285 #endif /* THREADS */
2288 * Routines for accessing dirty bits on virtual pages.
2289 * We plan to eventually implement four strategies for doing so:
2290 * DEFAULT_VDB: A simple dummy implementation that treats every page
2291 * as possibly dirty. This makes incremental collection
2292 * useless, but the implementation is still correct.
2293 * PCR_VDB: Use PPCRs virtual dirty bit facility.
2294 * PROC_VDB: Use the /proc facility for reading dirty bits. Only
2295 * works under some SVR4 variants. Even then, it may be
2296 * too slow to be entirely satisfactory. Requires reading
2297 * dirty bits for entire address space. Implementations tend
2298 * to assume that the client is a (slow) debugger.
2299 * MPROTECT_VDB:Protect pages and then catch the faults to keep track of
2300 * dirtied pages. The implementation (and implementability)
2301 * is highly system dependent. This usually fails when system
2302 * calls write to a protected page. We prevent the read system
2303 * call from doing so. It is the clients responsibility to
2304 * make sure that other system calls are similarly protected
2305 * or write only to the stack.
2307 GC_bool GC_dirty_maintained = FALSE;
2309 # ifdef DEFAULT_VDB
2311 /* All of the following assume the allocation lock is held, and */
2312 /* signals are disabled. */
2314 /* The client asserts that unallocated pages in the heap are never */
2315 /* written. */
2317 /* Initialize virtual dirty bit implementation. */
2318 void GC_dirty_init()
2320 # ifdef PRINTSTATS
2321 GC_printf0("Initializing DEFAULT_VDB...\n");
2322 # endif
2323 GC_dirty_maintained = TRUE;
2326 /* Retrieve system dirty bits for heap to a local buffer. */
2327 /* Restore the systems notion of which pages are dirty. */
2328 void GC_read_dirty()
2331 /* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */
2332 /* If the actual page size is different, this returns TRUE if any */
2333 /* of the pages overlapping h are dirty. This routine may err on the */
2334 /* side of labelling pages as dirty (and this implementation does). */
2335 /*ARGSUSED*/
2336 GC_bool GC_page_was_dirty(h)
2337 struct hblk *h;
2339 return(TRUE);
2343 * The following two routines are typically less crucial. They matter
2344 * most with large dynamic libraries, or if we can't accurately identify
2345 * stacks, e.g. under Solaris 2.X. Otherwise the following default
2346 * versions are adequate.
2349 /* Could any valid GC heap pointer ever have been written to this page? */
2350 /*ARGSUSED*/
2351 GC_bool GC_page_was_ever_dirty(h)
2352 struct hblk *h;
2354 return(TRUE);
2357 /* Reset the n pages starting at h to "was never dirty" status. */
2358 void GC_is_fresh(h, n)
2359 struct hblk *h;
2360 word n;
2364 /* A call that: */
2365 /* I) hints that [h, h+nblocks) is about to be written. */
2366 /* II) guarantees that protection is removed. */
2367 /* (I) may speed up some dirty bit implementations. */
2368 /* (II) may be essential if we need to ensure that */
2369 /* pointer-free system call buffers in the heap are */
2370 /* not protected. */
2371 /*ARGSUSED*/
2372 void GC_remove_protection(h, nblocks, is_ptrfree)
2373 struct hblk *h;
2374 word nblocks;
2375 GC_bool is_ptrfree;
2379 # endif /* DEFAULT_VDB */
2382 # ifdef MPROTECT_VDB
2385 * See DEFAULT_VDB for interface descriptions.
2389 * This implementation maintains dirty bits itself by catching write
2390 * faults and keeping track of them. We assume nobody else catches
2391 * SIGBUS or SIGSEGV. We assume no write faults occur in system calls.
2392 * This means that clients must ensure that system calls don't write
2393 * to the write-protected heap. Probably the best way to do this is to
2394 * ensure that system calls write at most to POINTERFREE objects in the
2395 * heap, and do even that only if we are on a platform on which those
2396 * are not protected. Another alternative is to wrap system calls
2397 * (see example for read below), but the current implementation holds
2398 * a lock across blocking calls, making it problematic for multithreaded
2399 * applications.
2400 * We assume the page size is a multiple of HBLKSIZE.
2401 * We prefer them to be the same. We avoid protecting POINTERFREE
2402 * objects only if they are the same.
2405 # if !defined(MSWIN32) && !defined(MSWINCE) && !defined(DARWIN)
2407 # include <sys/mman.h>
2408 # include <signal.h>
2409 # if !defined(HAIKU)
2410 # include <sys/syscall.h>
2411 # endif
2413 # define PROTECT(addr, len) \
2414 if (mprotect((caddr_t)(addr), (size_t)(len), \
2415 PROT_READ | OPT_PROT_EXEC) < 0) { \
2416 ABORT("mprotect failed"); \
2418 # define UNPROTECT(addr, len) \
2419 if (mprotect((caddr_t)(addr), (size_t)(len), \
2420 PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \
2421 ABORT("un-mprotect failed"); \
2424 # else
2426 # ifdef DARWIN
2427 /* Using vm_protect (mach syscall) over mprotect (BSD syscall) seems to
2428 decrease the likelihood of some of the problems described below. */
2429 #include <mach/vm_map.h>
2430 static mach_port_t GC_task_self;
2431 #define PROTECT(addr,len) \
2432 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2433 FALSE,VM_PROT_READ) != KERN_SUCCESS) { \
2434 ABORT("vm_portect failed"); \
2436 #define UNPROTECT(addr,len) \
2437 if(vm_protect(GC_task_self,(vm_address_t)(addr),(vm_size_t)(len), \
2438 FALSE,VM_PROT_READ|VM_PROT_WRITE) != KERN_SUCCESS) { \
2439 ABORT("vm_portect failed"); \
2441 # else
2443 # ifndef MSWINCE
2444 # include <signal.h>
2445 # endif
2447 static DWORD protect_junk;
2448 # define PROTECT(addr, len) \
2449 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \
2450 &protect_junk)) { \
2451 DWORD last_error = GetLastError(); \
2452 GC_printf1("Last error code: %lx\n", last_error); \
2453 ABORT("VirtualProtect failed"); \
2455 # define UNPROTECT(addr, len) \
2456 if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \
2457 &protect_junk)) { \
2458 ABORT("un-VirtualProtect failed"); \
2460 # endif /* !DARWIN */
2461 # endif /* MSWIN32 || MSWINCE || DARWIN */
2463 #if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2464 typedef void (* SIG_PF)();
2465 #endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2467 #if defined(SUNOS5SIGS) || defined(OSF1) || defined(LINUX) \
2468 || defined(HURD) || defined(HAIKU)
2469 # ifdef __STDC__
2470 typedef void (* SIG_PF)(int);
2471 # else
2472 typedef void (* SIG_PF)();
2473 # endif
2474 #endif /* SUNOS5SIGS || OSF1 || LINUX || HURD || HAIKU */
2476 #if defined(MSWIN32)
2477 typedef LPTOP_LEVEL_EXCEPTION_FILTER SIG_PF;
2478 # undef SIG_DFL
2479 # define SIG_DFL (LPTOP_LEVEL_EXCEPTION_FILTER) (-1)
2480 #endif
2481 #if defined(MSWINCE)
2482 typedef LONG (WINAPI *SIG_PF)(struct _EXCEPTION_POINTERS *);
2483 # undef SIG_DFL
2484 # define SIG_DFL (SIG_PF) (-1)
2485 #endif
2487 #if defined(IRIX5) || defined(OSF1) || defined(HURD)
2488 typedef void (* REAL_SIG_PF)(int, int, struct sigcontext *);
2489 #endif /* IRIX5 || OSF1 || HURD */
2491 #if defined(SUNOS5SIGS)
2492 # if defined(HPUX) || defined(FREEBSD)
2493 # define SIGINFO_T siginfo_t
2494 # else
2495 # define SIGINFO_T struct siginfo
2496 # endif
2497 # ifdef __STDC__
2498 typedef void (* REAL_SIG_PF)(int, SIGINFO_T *, void *);
2499 # else
2500 typedef void (* REAL_SIG_PF)();
2501 # endif
2502 #endif /* SUNOS5SIGS */
2504 #if defined(LINUX)
2505 # if __GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ >= 2
2506 typedef struct sigcontext s_c;
2507 # else /* glibc < 2.2 */
2508 # include <linux/version.h>
2509 # if (LINUX_VERSION_CODE >= 0x20100) && !defined(M68K) || defined(ALPHA) || defined(ARM32)
2510 typedef struct sigcontext s_c;
2511 # else
2512 typedef struct sigcontext_struct s_c;
2513 # endif
2514 # endif /* glibc < 2.2 */
2515 # if defined(ALPHA) || defined(M68K)
2516 typedef void (* REAL_SIG_PF)(int, int, s_c *);
2517 # else
2518 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2519 typedef void (* REAL_SIG_PF)(int, siginfo_t *, s_c *);
2520 /* FIXME: */
2521 /* According to SUSV3, the last argument should have type */
2522 /* void * or ucontext_t * */
2523 # else
2524 typedef void (* REAL_SIG_PF)(int, s_c);
2525 # endif
2526 # endif
2527 # ifdef ALPHA
2528 /* Retrieve fault address from sigcontext structure by decoding */
2529 /* instruction. */
2530 char * get_fault_addr(s_c *sc) {
2531 unsigned instr;
2532 word faultaddr;
2534 instr = *((unsigned *)(sc->sc_pc));
2535 faultaddr = sc->sc_regs[(instr >> 16) & 0x1f];
2536 faultaddr += (word) (((int)instr << 16) >> 16);
2537 return (char *)faultaddr;
2539 # endif /* !ALPHA */
2540 # endif /* LINUX */
2542 #ifndef DARWIN
2543 SIG_PF GC_old_bus_handler;
2544 SIG_PF GC_old_segv_handler; /* Also old MSWIN32 ACCESS_VIOLATION filter */
2545 #endif /* !DARWIN */
2547 #if defined(THREADS)
2548 /* We need to lock around the bitmap update in the write fault handler */
2549 /* in order to avoid the risk of losing a bit. We do this with a */
2550 /* test-and-set spin lock if we know how to do that. Otherwise we */
2551 /* check whether we are already in the handler and use the dumb but */
2552 /* safe fallback algorithm of setting all bits in the word. */
2553 /* Contention should be very rare, so we do the minimum to handle it */
2554 /* correctly. */
2555 #ifdef GC_TEST_AND_SET_DEFINED
2556 static VOLATILE unsigned int fault_handler_lock = 0;
2557 void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2558 while (GC_test_and_set(&fault_handler_lock)) {}
2559 /* Could also revert to set_pht_entry_from_index_safe if initial */
2560 /* GC_test_and_set fails. */
2561 set_pht_entry_from_index(db, index);
2562 GC_clear(&fault_handler_lock);
2564 #else /* !GC_TEST_AND_SET_DEFINED */
2565 /* THIS IS INCORRECT! The dirty bit vector may be temporarily wrong, */
2566 /* just before we notice the conflict and correct it. We may end up */
2567 /* looking at it while it's wrong. But this requires contention */
2568 /* exactly when a GC is triggered, which seems far less likely to */
2569 /* fail than the old code, which had no reported failures. Thus we */
2570 /* leave it this way while we think of something better, or support */
2571 /* GC_test_and_set on the remaining platforms. */
2572 static VOLATILE word currently_updating = 0;
2573 void async_set_pht_entry_from_index(VOLATILE page_hash_table db, int index) {
2574 unsigned int update_dummy;
2575 currently_updating = (word)(&update_dummy);
2576 set_pht_entry_from_index(db, index);
2577 /* If we get contention in the 10 or so instruction window here, */
2578 /* and we get stopped by a GC between the two updates, we lose! */
2579 if (currently_updating != (word)(&update_dummy)) {
2580 set_pht_entry_from_index_safe(db, index);
2581 /* We claim that if two threads concurrently try to update the */
2582 /* dirty bit vector, the first one to execute UPDATE_START */
2583 /* will see it changed when UPDATE_END is executed. (Note that */
2584 /* &update_dummy must differ in two distinct threads.) It */
2585 /* will then execute set_pht_entry_from_index_safe, thus */
2586 /* returning us to a safe state, though not soon enough. */
2589 #endif /* !GC_TEST_AND_SET_DEFINED */
2590 #else /* !THREADS */
2591 # define async_set_pht_entry_from_index(db, index) \
2592 set_pht_entry_from_index(db, index)
2593 #endif /* !THREADS */
2595 /*ARGSUSED*/
2596 #if !defined(DARWIN)
2597 # if defined (SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2598 void GC_write_fault_handler(sig, code, scp, addr)
2599 int sig, code;
2600 struct sigcontext *scp;
2601 char * addr;
2602 # ifdef SUNOS4
2603 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2604 # define CODE_OK (FC_CODE(code) == FC_PROT \
2605 || (FC_CODE(code) == FC_OBJERR \
2606 && FC_ERRNO(code) == FC_PROT))
2607 # endif
2608 # ifdef FREEBSD
2609 # define SIG_OK (sig == SIGBUS)
2610 # define CODE_OK TRUE
2611 # endif
2612 # endif /* SUNOS4 || (FREEBSD && !SUNOS5SIGS) */
2614 # if defined(IRIX5) || defined(OSF1) || defined(HURD)
2615 # include <errno.h>
2616 void GC_write_fault_handler(int sig, int code, struct sigcontext *scp)
2617 # ifdef OSF1
2618 # define SIG_OK (sig == SIGSEGV)
2619 # define CODE_OK (code == 2 /* experimentally determined */)
2620 # endif
2621 # ifdef IRIX5
2622 # define SIG_OK (sig == SIGSEGV)
2623 # define CODE_OK (code == EACCES)
2624 # endif
2625 # ifdef HURD
2626 # define SIG_OK (sig == SIGBUS || sig == SIGSEGV)
2627 # define CODE_OK TRUE
2628 # endif
2629 # endif /* IRIX5 || OSF1 || HURD */
2631 # if defined(LINUX)
2632 # if defined(ALPHA) || defined(M68K)
2633 void GC_write_fault_handler(int sig, int code, s_c * sc)
2634 # else
2635 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2636 void GC_write_fault_handler(int sig, siginfo_t * si, s_c * scp)
2637 # else
2638 # if defined(ARM32)
2639 void GC_write_fault_handler(int sig, int a2, int a3, int a4, s_c sc)
2640 # else
2641 void GC_write_fault_handler(int sig, s_c sc)
2642 # endif
2643 # endif
2644 # endif
2645 # define SIG_OK (sig == SIGSEGV)
2646 # define CODE_OK TRUE
2647 /* Empirically c.trapno == 14, on IA32, but is that useful? */
2648 /* Should probably consider alignment issues on other */
2649 /* architectures. */
2650 # endif /* LINUX */
2652 # if defined(HAIKU)
2653 # include <errno.h>
2654 # define CODE_OK TRUE
2655 # define SIG_OK (sig == SIGSEGV)
2656 void GC_write_failt_handler(int sig, siginfo_t *scp, void * context)
2657 #endif /* HAIKU */
2659 # if defined(SUNOS5SIGS)
2660 # ifdef __STDC__
2661 void GC_write_fault_handler(int sig, SIGINFO_T *scp, void * context)
2662 # else
2663 void GC_write_fault_handler(sig, scp, context)
2664 int sig;
2665 SIGINFO_T *scp;
2666 void * context;
2667 # endif
2668 # ifdef HPUX
2669 # define SIG_OK (sig == SIGSEGV || sig == SIGBUS)
2670 # define CODE_OK (scp -> si_code == SEGV_ACCERR) \
2671 || (scp -> si_code == BUS_ADRERR) \
2672 || (scp -> si_code == BUS_UNKNOWN) \
2673 || (scp -> si_code == SEGV_UNKNOWN) \
2674 || (scp -> si_code == BUS_OBJERR)
2675 # else
2676 # ifdef FREEBSD
2677 # define SIG_OK (sig == SIGBUS)
2678 # define CODE_OK (scp -> si_code == BUS_PAGE_FAULT)
2679 # else
2680 # define SIG_OK (sig == SIGSEGV)
2681 # define CODE_OK (scp -> si_code == SEGV_ACCERR)
2682 # endif
2683 # endif
2684 # endif /* SUNOS5SIGS */
2686 # if defined(MSWIN32) || defined(MSWINCE)
2687 LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info)
2688 # define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode == \
2689 STATUS_ACCESS_VIOLATION)
2690 # define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] == 1)
2691 /* Write fault */
2692 # endif /* MSWIN32 || MSWINCE */
2694 register unsigned i;
2695 # if defined(HURD)
2696 char *addr = (char *) code;
2697 # endif
2698 # ifdef IRIX5
2699 char * addr = (char *) (size_t) (scp -> sc_badvaddr);
2700 # endif
2701 # if defined(OSF1) && defined(ALPHA)
2702 char * addr = (char *) (scp -> sc_traparg_a0);
2703 # endif
2704 # if defined(SUNOS5SIGS) || defined(HAIKU)
2705 char * addr = (char *) (scp -> si_addr);
2706 # endif
2707 # ifdef LINUX
2708 # if defined(I386)
2709 char * addr = (char *) (sc.cr2);
2710 # else
2711 # if defined(M68K)
2712 char * addr = NULL;
2714 struct sigcontext *scp = (struct sigcontext *)(sc);
2716 int format = (scp->sc_formatvec >> 12) & 0xf;
2717 unsigned long *framedata = (unsigned long *)(scp + 1);
2718 unsigned long ea;
2720 if (format == 0xa || format == 0xb) {
2721 /* 68020/030 */
2722 ea = framedata[2];
2723 } else if (format == 7) {
2724 /* 68040 */
2725 ea = framedata[3];
2726 if (framedata[1] & 0x08000000) {
2727 /* correct addr on misaligned access */
2728 ea = (ea+4095)&(~4095);
2730 } else if (format == 4) {
2731 /* 68060 */
2732 ea = framedata[0];
2733 if (framedata[1] & 0x08000000) {
2734 /* correct addr on misaligned access */
2735 ea = (ea+4095)&(~4095);
2738 addr = (char *)ea;
2739 # else
2740 # ifdef ALPHA
2741 char * addr = get_fault_addr(sc);
2742 # else
2743 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2744 char * addr = si -> si_addr;
2745 /* I believe this is claimed to work on all platforms for */
2746 /* Linux 2.3.47 and later. Hopefully we don't have to */
2747 /* worry about earlier kernels on IA64. */
2748 # else
2749 # if defined(POWERPC)
2750 char * addr = (char *) (sc.regs->dar);
2751 # else
2752 # if defined(ARM32)
2753 char * addr = (char *)sc.fault_address;
2754 # else
2755 # if defined(CRIS)
2756 char * addr = (char *)sc.regs.csraddr;
2757 # else
2758 --> architecture not supported
2759 # endif
2760 # endif
2761 # endif
2762 # endif
2763 # endif
2764 # endif
2765 # endif
2766 # endif
2767 # if defined(MSWIN32) || defined(MSWINCE)
2768 char * addr = (char *) (exc_info -> ExceptionRecord
2769 -> ExceptionInformation[1]);
2770 # define sig SIGSEGV
2771 # endif
2773 if (SIG_OK && CODE_OK) {
2774 register struct hblk * h =
2775 (struct hblk *)((word)addr & ~(GC_page_size-1));
2776 GC_bool in_allocd_block;
2778 # ifdef SUNOS5SIGS
2779 /* Address is only within the correct physical page. */
2780 in_allocd_block = FALSE;
2781 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2782 if (HDR(h+i) != 0) {
2783 in_allocd_block = TRUE;
2786 # else
2787 in_allocd_block = (HDR(addr) != 0);
2788 # endif
2789 if (!in_allocd_block) {
2790 /* FIXME - We should make sure that we invoke the */
2791 /* old handler with the appropriate calling */
2792 /* sequence, which often depends on SA_SIGINFO. */
2794 /* Heap blocks now begin and end on page boundaries */
2795 SIG_PF old_handler;
2797 if (sig == SIGSEGV) {
2798 old_handler = GC_old_segv_handler;
2799 } else {
2800 old_handler = GC_old_bus_handler;
2802 if (old_handler == SIG_DFL) {
2803 # if !defined(MSWIN32) && !defined(MSWINCE)
2804 GC_err_printf1("Segfault at 0x%lx\n", addr);
2805 ABORT("Unexpected bus error or segmentation fault");
2806 # else
2807 return(EXCEPTION_CONTINUE_SEARCH);
2808 # endif
2809 } else {
2810 # if defined (SUNOS4) \
2811 || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2812 (*old_handler) (sig, code, scp, addr);
2813 return;
2814 # endif
2815 # if defined (SUNOS5SIGS)
2817 * FIXME: For FreeBSD, this code should check if the
2818 * old signal handler used the traditional BSD style and
2819 * if so call it using that style.
2821 (*(REAL_SIG_PF)old_handler) (sig, scp, context);
2822 return;
2823 # endif
2824 # if defined (LINUX)
2825 # if defined(ALPHA) || defined(M68K)
2826 (*(REAL_SIG_PF)old_handler) (sig, code, sc);
2827 # else
2828 # if defined(IA64) || defined(HP_PA) || defined(X86_64)
2829 (*(REAL_SIG_PF)old_handler) (sig, si, scp);
2830 # else
2831 (*(REAL_SIG_PF)old_handler) (sig, sc);
2832 # endif
2833 # endif
2834 return;
2835 # endif
2836 # if defined (IRIX5) || defined(OSF1) || defined(HURD)
2837 (*(REAL_SIG_PF)old_handler) (sig, code, scp);
2838 return;
2839 # endif
2840 # ifdef MSWIN32
2841 return((*old_handler)(exc_info));
2842 # endif
2845 UNPROTECT(h, GC_page_size);
2846 /* We need to make sure that no collection occurs between */
2847 /* the UNPROTECT and the setting of the dirty bit. Otherwise */
2848 /* a write by a third thread might go unnoticed. Reversing */
2849 /* the order is just as bad, since we would end up unprotecting */
2850 /* a page in a GC cycle during which it's not marked. */
2851 /* Currently we do this by disabling the thread stopping */
2852 /* signals while this handler is running. An alternative might */
2853 /* be to record the fact that we're about to unprotect, or */
2854 /* have just unprotected a page in the GC's thread structure, */
2855 /* and then to have the thread stopping code set the dirty */
2856 /* flag, if necessary. */
2857 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
2858 register int index = PHT_HASH(h+i);
2860 async_set_pht_entry_from_index(GC_dirty_pages, index);
2862 # if defined(OSF1)
2863 /* These reset the signal handler each time by default. */
2864 signal(SIGSEGV, (SIG_PF) GC_write_fault_handler);
2865 # endif
2866 /* The write may not take place before dirty bits are read. */
2867 /* But then we'll fault again ... */
2868 # if defined(MSWIN32) || defined(MSWINCE)
2869 return(EXCEPTION_CONTINUE_EXECUTION);
2870 # else
2871 return;
2872 # endif
2874 #if defined(MSWIN32) || defined(MSWINCE)
2875 return EXCEPTION_CONTINUE_SEARCH;
2876 #else
2877 GC_err_printf1("Segfault at 0x%lx\n", addr);
2878 ABORT("Unexpected bus error or segmentation fault");
2879 #endif
2881 #endif /* !DARWIN */
2884 * We hold the allocation lock. We expect block h to be written
2885 * shortly. Ensure that all pages containing any part of the n hblks
2886 * starting at h are no longer protected. If is_ptrfree is false,
2887 * also ensure that they will subsequently appear to be dirty.
2889 void GC_remove_protection(h, nblocks, is_ptrfree)
2890 struct hblk *h;
2891 word nblocks;
2892 GC_bool is_ptrfree;
2894 struct hblk * h_trunc; /* Truncated to page boundary */
2895 struct hblk * h_end; /* Page boundary following block end */
2896 struct hblk * current;
2897 GC_bool found_clean;
2899 if (!GC_dirty_maintained) return;
2900 h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1));
2901 h_end = (struct hblk *)(((word)(h + nblocks) + GC_page_size-1)
2902 & ~(GC_page_size-1));
2903 found_clean = FALSE;
2904 for (current = h_trunc; current < h_end; ++current) {
2905 int index = PHT_HASH(current);
2907 if (!is_ptrfree || current < h || current >= h + nblocks) {
2908 async_set_pht_entry_from_index(GC_dirty_pages, index);
2911 UNPROTECT(h_trunc, (ptr_t)h_end - (ptr_t)h_trunc);
2914 #if !defined(DARWIN)
2915 void GC_dirty_init()
2917 # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(LINUX) || \
2918 defined(OSF1) || defined(HURD)
2919 struct sigaction act, oldact;
2920 /* We should probably specify SA_SIGINFO for Linux, and handle */
2921 /* the different architectures more uniformly. */
2922 # if defined(IRIX5) || defined(LINUX) && !defined(X86_64) \
2923 || defined(OSF1) || defined(HURD)
2924 act.sa_flags = SA_RESTART;
2925 act.sa_handler = (SIG_PF)GC_write_fault_handler;
2926 # else
2927 act.sa_flags = SA_RESTART | SA_SIGINFO;
2928 act.sa_sigaction = GC_write_fault_handler;
2929 # endif
2930 (void)sigemptyset(&act.sa_mask);
2931 # ifdef SIG_SUSPEND
2932 /* Arrange to postpone SIG_SUSPEND while we're in a write fault */
2933 /* handler. This effectively makes the handler atomic w.r.t. */
2934 /* stopping the world for GC. */
2935 (void)sigaddset(&act.sa_mask, SIG_SUSPEND);
2936 # endif /* SIG_SUSPEND */
2937 # endif
2938 # ifdef PRINTSTATS
2939 GC_printf0("Inititalizing mprotect virtual dirty bit implementation\n");
2940 # endif
2941 GC_dirty_maintained = TRUE;
2942 if (GC_page_size % HBLKSIZE != 0) {
2943 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
2944 ABORT("Page size not multiple of HBLKSIZE");
2946 # if defined(SUNOS4) || (defined(FREEBSD) && !defined(SUNOS5SIGS))
2947 GC_old_bus_handler = signal(SIGBUS, GC_write_fault_handler);
2948 if (GC_old_bus_handler == SIG_IGN) {
2949 GC_err_printf0("Previously ignored bus error!?");
2950 GC_old_bus_handler = SIG_DFL;
2952 if (GC_old_bus_handler != SIG_DFL) {
2953 # ifdef PRINTSTATS
2954 GC_err_printf0("Replaced other SIGBUS handler\n");
2955 # endif
2957 # endif
2958 # if defined(SUNOS4)
2959 GC_old_segv_handler = signal(SIGSEGV, (SIG_PF)GC_write_fault_handler);
2960 if (GC_old_segv_handler == SIG_IGN) {
2961 GC_err_printf0("Previously ignored segmentation violation!?");
2962 GC_old_segv_handler = SIG_DFL;
2964 if (GC_old_segv_handler != SIG_DFL) {
2965 # ifdef PRINTSTATS
2966 GC_err_printf0("Replaced other SIGSEGV handler\n");
2967 # endif
2969 # endif
2970 # if (defined(SUNOS5SIGS) && !defined(FREEBSD)) || defined(IRIX5) \
2971 || defined(LINUX) || defined(OSF1) || defined(HURD)
2972 /* SUNOS5SIGS includes HPUX */
2973 # if defined(GC_IRIX_THREADS)
2974 sigaction(SIGSEGV, 0, &oldact);
2975 sigaction(SIGSEGV, &act, 0);
2976 # else
2978 int res = sigaction(SIGSEGV, &act, &oldact);
2979 if (res != 0) ABORT("Sigaction failed");
2981 # endif
2982 # if defined(_sigargs) || defined(HURD) || !defined(SA_SIGINFO)
2983 /* This is Irix 5.x, not 6.x. Irix 5.x does not have */
2984 /* sa_sigaction. */
2985 GC_old_segv_handler = oldact.sa_handler;
2986 # else /* Irix 6.x or SUNOS5SIGS or LINUX */
2987 if (oldact.sa_flags & SA_SIGINFO) {
2988 GC_old_segv_handler = (SIG_PF)(oldact.sa_sigaction);
2989 } else {
2990 GC_old_segv_handler = oldact.sa_handler;
2992 # endif
2993 if (GC_old_segv_handler == SIG_IGN) {
2994 GC_err_printf0("Previously ignored segmentation violation!?");
2995 GC_old_segv_handler = SIG_DFL;
2997 if (GC_old_segv_handler != SIG_DFL) {
2998 # ifdef PRINTSTATS
2999 GC_err_printf0("Replaced other SIGSEGV handler\n");
3000 # endif
3002 # endif /* (SUNOS5SIGS && !FREEBSD) || IRIX5 || LINUX || OSF1 || HURD */
3003 # if defined(HPUX) || defined(LINUX) || defined(HURD) \
3004 || (defined(FREEBSD) && defined(SUNOS5SIGS))
3005 sigaction(SIGBUS, &act, &oldact);
3006 GC_old_bus_handler = oldact.sa_handler;
3007 if (GC_old_bus_handler == SIG_IGN) {
3008 GC_err_printf0("Previously ignored bus error!?");
3009 GC_old_bus_handler = SIG_DFL;
3011 if (GC_old_bus_handler != SIG_DFL) {
3012 # ifdef PRINTSTATS
3013 GC_err_printf0("Replaced other SIGBUS handler\n");
3014 # endif
3016 # endif /* HPUX || LINUX || HURD || (FREEBSD && SUNOS5SIGS) */
3017 # if defined(MSWIN32)
3018 GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler);
3019 if (GC_old_segv_handler != NULL) {
3020 # ifdef PRINTSTATS
3021 GC_err_printf0("Replaced other UnhandledExceptionFilter\n");
3022 # endif
3023 } else {
3024 GC_old_segv_handler = SIG_DFL;
3026 # endif
3028 #endif /* !DARWIN */
3030 int GC_incremental_protection_needs()
3032 if (GC_page_size == HBLKSIZE) {
3033 return GC_PROTECTS_POINTER_HEAP;
3034 } else {
3035 return GC_PROTECTS_POINTER_HEAP | GC_PROTECTS_PTRFREE_HEAP;
3039 #define HAVE_INCREMENTAL_PROTECTION_NEEDS
3041 #define IS_PTRFREE(hhdr) ((hhdr)->hb_descr == 0)
3043 #define PAGE_ALIGNED(x) !((word)(x) & (GC_page_size - 1))
3044 void GC_protect_heap()
3046 ptr_t start;
3047 word len;
3048 struct hblk * current;
3049 struct hblk * current_start; /* Start of block to be protected. */
3050 struct hblk * limit;
3051 unsigned i;
3052 GC_bool protect_all =
3053 (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP));
3054 for (i = 0; i < GC_n_heap_sects; i++) {
3055 start = GC_heap_sects[i].hs_start;
3056 len = GC_heap_sects[i].hs_bytes;
3057 if (protect_all) {
3058 PROTECT(start, len);
3059 } else {
3060 GC_ASSERT(PAGE_ALIGNED(len))
3061 GC_ASSERT(PAGE_ALIGNED(start))
3062 current_start = current = (struct hblk *)start;
3063 limit = (struct hblk *)(start + len);
3064 while (current < limit) {
3065 hdr * hhdr;
3066 word nhblks;
3067 GC_bool is_ptrfree;
3069 GC_ASSERT(PAGE_ALIGNED(current));
3070 GET_HDR(current, hhdr);
3071 if (IS_FORWARDING_ADDR_OR_NIL(hhdr)) {
3072 /* This can happen only if we're at the beginning of a */
3073 /* heap segment, and a block spans heap segments. */
3074 /* We will handle that block as part of the preceding */
3075 /* segment. */
3076 GC_ASSERT(current_start == current);
3077 current_start = ++current;
3078 continue;
3080 if (HBLK_IS_FREE(hhdr)) {
3081 GC_ASSERT(PAGE_ALIGNED(hhdr -> hb_sz));
3082 nhblks = divHBLKSZ(hhdr -> hb_sz);
3083 is_ptrfree = TRUE; /* dirty on alloc */
3084 } else {
3085 nhblks = OBJ_SZ_TO_BLOCKS(hhdr -> hb_sz);
3086 is_ptrfree = IS_PTRFREE(hhdr);
3088 if (is_ptrfree) {
3089 if (current_start < current) {
3090 PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
3092 current_start = (current += nhblks);
3093 } else {
3094 current += nhblks;
3097 if (current_start < current) {
3098 PROTECT(current_start, (ptr_t)current - (ptr_t)current_start);
3104 /* We assume that either the world is stopped or its OK to lose dirty */
3105 /* bits while this is happenning (as in GC_enable_incremental). */
3106 void GC_read_dirty()
3108 BCOPY((word *)GC_dirty_pages, GC_grungy_pages,
3109 (sizeof GC_dirty_pages));
3110 BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages));
3111 GC_protect_heap();
3114 GC_bool GC_page_was_dirty(h)
3115 struct hblk * h;
3117 register word index = PHT_HASH(h);
3119 return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index));
3123 * Acquiring the allocation lock here is dangerous, since this
3124 * can be called from within GC_call_with_alloc_lock, and the cord
3125 * package does so. On systems that allow nested lock acquisition, this
3126 * happens to work.
3127 * On other systems, SET_LOCK_HOLDER and friends must be suitably defined.
3130 static GC_bool syscall_acquired_lock = FALSE; /* Protected by GC lock. */
3132 void GC_begin_syscall()
3134 if (!I_HOLD_LOCK()) {
3135 LOCK();
3136 syscall_acquired_lock = TRUE;
3140 void GC_end_syscall()
3142 if (syscall_acquired_lock) {
3143 syscall_acquired_lock = FALSE;
3144 UNLOCK();
3148 void GC_unprotect_range(addr, len)
3149 ptr_t addr;
3150 word len;
3152 struct hblk * start_block;
3153 struct hblk * end_block;
3154 register struct hblk *h;
3155 ptr_t obj_start;
3157 if (!GC_dirty_maintained) return;
3158 obj_start = GC_base(addr);
3159 if (obj_start == 0) return;
3160 if (GC_base(addr + len - 1) != obj_start) {
3161 ABORT("GC_unprotect_range(range bigger than object)");
3163 start_block = (struct hblk *)((word)addr & ~(GC_page_size - 1));
3164 end_block = (struct hblk *)((word)(addr + len - 1) & ~(GC_page_size - 1));
3165 end_block += GC_page_size/HBLKSIZE - 1;
3166 for (h = start_block; h <= end_block; h++) {
3167 register word index = PHT_HASH(h);
3169 async_set_pht_entry_from_index(GC_dirty_pages, index);
3171 UNPROTECT(start_block,
3172 ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE);
3175 #if 0
3177 /* We no longer wrap read by default, since that was causing too many */
3178 /* problems. It is preferred that the client instead avoids writing */
3179 /* to the write-protected heap with a system call. */
3180 /* This still serves as sample code if you do want to wrap system calls.*/
3182 #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(GC_USE_LD_WRAP)
3183 /* Replacement for UNIX system call. */
3184 /* Other calls that write to the heap should be handled similarly. */
3185 /* Note that this doesn't work well for blocking reads: It will hold */
3186 /* the allocation lock for the entire duration of the call. Multithreaded */
3187 /* clients should really ensure that it won't block, either by setting */
3188 /* the descriptor nonblocking, or by calling select or poll first, to */
3189 /* make sure that input is available. */
3190 /* Another, preferred alternative is to ensure that system calls never */
3191 /* write to the protected heap (see above). */
3192 # if defined(__STDC__) && !defined(SUNOS4)
3193 # include <unistd.h>
3194 # include <sys/uio.h>
3195 ssize_t read(int fd, void *buf, size_t nbyte)
3196 # else
3197 # ifndef LINT
3198 int read(fd, buf, nbyte)
3199 # else
3200 int GC_read(fd, buf, nbyte)
3201 # endif
3202 int fd;
3203 char *buf;
3204 int nbyte;
3205 # endif
3207 int result;
3209 GC_begin_syscall();
3210 GC_unprotect_range(buf, (word)nbyte);
3211 # if defined(IRIX5) || defined(GC_LINUX_THREADS)
3212 /* Indirect system call may not always be easily available. */
3213 /* We could call _read, but that would interfere with the */
3214 /* libpthread interception of read. */
3215 /* On Linux, we have to be careful with the linuxthreads */
3216 /* read interception. */
3218 struct iovec iov;
3220 iov.iov_base = buf;
3221 iov.iov_len = nbyte;
3222 result = readv(fd, &iov, 1);
3224 # else
3225 # if defined(HURD)
3226 result = __read(fd, buf, nbyte);
3227 # else
3228 /* The two zero args at the end of this list are because one
3229 IA-64 syscall() implementation actually requires six args
3230 to be passed, even though they aren't always used. */
3231 result = syscall(SYS_read, fd, buf, nbyte, 0, 0);
3232 # endif /* !HURD */
3233 # endif
3234 GC_end_syscall();
3235 return(result);
3237 #endif /* !MSWIN32 && !MSWINCE && !GC_LINUX_THREADS */
3239 #if defined(GC_USE_LD_WRAP) && !defined(THREADS)
3240 /* We use the GNU ld call wrapping facility. */
3241 /* This requires that the linker be invoked with "--wrap read". */
3242 /* This can be done by passing -Wl,"--wrap read" to gcc. */
3243 /* I'm not sure that this actually wraps whatever version of read */
3244 /* is called by stdio. That code also mentions __read. */
3245 # include <unistd.h>
3246 ssize_t __wrap_read(int fd, void *buf, size_t nbyte)
3248 int result;
3250 GC_begin_syscall();
3251 GC_unprotect_range(buf, (word)nbyte);
3252 result = __real_read(fd, buf, nbyte);
3253 GC_end_syscall();
3254 return(result);
3257 /* We should probably also do this for __read, or whatever stdio */
3258 /* actually calls. */
3259 #endif
3261 #endif /* 0 */
3263 /*ARGSUSED*/
3264 GC_bool GC_page_was_ever_dirty(h)
3265 struct hblk *h;
3267 return(TRUE);
3270 /* Reset the n pages starting at h to "was never dirty" status. */
3271 /*ARGSUSED*/
3272 void GC_is_fresh(h, n)
3273 struct hblk *h;
3274 word n;
3278 # endif /* MPROTECT_VDB */
3280 # ifdef PROC_VDB
3283 * See DEFAULT_VDB for interface descriptions.
3287 * This implementaion assumes a Solaris 2.X like /proc pseudo-file-system
3288 * from which we can read page modified bits. This facility is far from
3289 * optimal (e.g. we would like to get the info for only some of the
3290 * address space), but it avoids intercepting system calls.
3293 #include <errno.h>
3294 #include <sys/types.h>
3295 #include <sys/signal.h>
3296 #include <sys/fault.h>
3297 #include <sys/syscall.h>
3298 #include <sys/procfs.h>
3299 #include <sys/stat.h>
3301 #define INITIAL_BUF_SZ 16384
3302 word GC_proc_buf_size = INITIAL_BUF_SZ;
3303 char *GC_proc_buf;
3305 #ifdef GC_SOLARIS_THREADS
3306 /* We don't have exact sp values for threads. So we count on */
3307 /* occasionally declaring stack pages to be fresh. Thus we */
3308 /* need a real implementation of GC_is_fresh. We can't clear */
3309 /* entries in GC_written_pages, since that would declare all */
3310 /* pages with the given hash address to be fresh. */
3311 # define MAX_FRESH_PAGES 8*1024 /* Must be power of 2 */
3312 struct hblk ** GC_fresh_pages; /* A direct mapped cache. */
3313 /* Collisions are dropped. */
3315 # define FRESH_PAGE_SLOT(h) (divHBLKSZ((word)(h)) & (MAX_FRESH_PAGES-1))
3316 # define ADD_FRESH_PAGE(h) \
3317 GC_fresh_pages[FRESH_PAGE_SLOT(h)] = (h)
3318 # define PAGE_IS_FRESH(h) \
3319 (GC_fresh_pages[FRESH_PAGE_SLOT(h)] == (h) && (h) != 0)
3320 #endif
3322 /* Add all pages in pht2 to pht1 */
3323 void GC_or_pages(pht1, pht2)
3324 page_hash_table pht1, pht2;
3326 register int i;
3328 for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i];
3331 int GC_proc_fd;
3333 void GC_dirty_init()
3335 int fd;
3336 char buf[30];
3338 GC_dirty_maintained = TRUE;
3339 if (GC_words_allocd != 0 || GC_words_allocd_before_gc != 0) {
3340 register int i;
3342 for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1);
3343 # ifdef PRINTSTATS
3344 GC_printf1("Allocated words:%lu:all pages may have been written\n",
3345 (unsigned long)
3346 (GC_words_allocd + GC_words_allocd_before_gc));
3347 # endif
3349 sprintf(buf, "/proc/%d", getpid());
3350 fd = open(buf, O_RDONLY);
3351 if (fd < 0) {
3352 ABORT("/proc open failed");
3354 GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0);
3355 close(fd);
3356 syscall(SYS_fcntl, GC_proc_fd, F_SETFD, FD_CLOEXEC);
3357 if (GC_proc_fd < 0) {
3358 ABORT("/proc ioctl failed");
3360 GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size);
3361 # ifdef GC_SOLARIS_THREADS
3362 GC_fresh_pages = (struct hblk **)
3363 GC_scratch_alloc(MAX_FRESH_PAGES * sizeof (struct hblk *));
3364 if (GC_fresh_pages == 0) {
3365 GC_err_printf0("No space for fresh pages\n");
3366 EXIT();
3368 BZERO(GC_fresh_pages, MAX_FRESH_PAGES * sizeof (struct hblk *));
3369 # endif
3372 /* Ignore write hints. They don't help us here. */
3373 /*ARGSUSED*/
3374 void GC_remove_protection(h, nblocks, is_ptrfree)
3375 struct hblk *h;
3376 word nblocks;
3377 GC_bool is_ptrfree;
3381 #ifdef GC_SOLARIS_THREADS
3382 # define READ(fd,buf,nbytes) syscall(SYS_read, fd, buf, nbytes)
3383 #else
3384 # define READ(fd,buf,nbytes) read(fd, buf, nbytes)
3385 #endif
3387 void GC_read_dirty()
3389 unsigned long ps, np;
3390 int nmaps;
3391 ptr_t vaddr;
3392 struct prasmap * map;
3393 char * bufp;
3394 ptr_t current_addr, limit;
3395 int i;
3396 int dummy;
3398 BZERO(GC_grungy_pages, (sizeof GC_grungy_pages));
3400 bufp = GC_proc_buf;
3401 if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3402 # ifdef PRINTSTATS
3403 GC_printf1("/proc read failed: GC_proc_buf_size = %lu\n",
3404 GC_proc_buf_size);
3405 # endif
3407 /* Retry with larger buffer. */
3408 word new_size = 2 * GC_proc_buf_size;
3409 char * new_buf = GC_scratch_alloc(new_size);
3411 if (new_buf != 0) {
3412 GC_proc_buf = bufp = new_buf;
3413 GC_proc_buf_size = new_size;
3415 if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) {
3416 WARN("Insufficient space for /proc read\n", 0);
3417 /* Punt: */
3418 memset(GC_grungy_pages, 0xff, sizeof (page_hash_table));
3419 memset(GC_written_pages, 0xff, sizeof(page_hash_table));
3420 # ifdef GC_SOLARIS_THREADS
3421 BZERO(GC_fresh_pages,
3422 MAX_FRESH_PAGES * sizeof (struct hblk *));
3423 # endif
3424 return;
3428 /* Copy dirty bits into GC_grungy_pages */
3429 nmaps = ((struct prpageheader *)bufp) -> pr_nmap;
3430 /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n",
3431 nmaps, PG_REFERENCED, PG_MODIFIED); */
3432 bufp = bufp + sizeof(struct prpageheader);
3433 for (i = 0; i < nmaps; i++) {
3434 map = (struct prasmap *)bufp;
3435 vaddr = (ptr_t)(map -> pr_vaddr);
3436 ps = map -> pr_pagesize;
3437 np = map -> pr_npage;
3438 /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */
3439 limit = vaddr + ps * np;
3440 bufp += sizeof (struct prasmap);
3441 for (current_addr = vaddr;
3442 current_addr < limit; current_addr += ps){
3443 if ((*bufp++) & PG_MODIFIED) {
3444 register struct hblk * h = (struct hblk *) current_addr;
3446 while ((ptr_t)h < current_addr + ps) {
3447 register word index = PHT_HASH(h);
3449 set_pht_entry_from_index(GC_grungy_pages, index);
3450 # ifdef GC_SOLARIS_THREADS
3452 register int slot = FRESH_PAGE_SLOT(h);
3454 if (GC_fresh_pages[slot] == h) {
3455 GC_fresh_pages[slot] = 0;
3458 # endif
3459 h++;
3463 bufp += sizeof(long) - 1;
3464 bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1));
3466 /* Update GC_written_pages. */
3467 GC_or_pages(GC_written_pages, GC_grungy_pages);
3468 # ifdef GC_SOLARIS_THREADS
3469 /* Make sure that old stacks are considered completely clean */
3470 /* unless written again. */
3471 GC_old_stacks_are_fresh();
3472 # endif
3475 #undef READ
3477 GC_bool GC_page_was_dirty(h)
3478 struct hblk *h;
3480 register word index = PHT_HASH(h);
3481 register GC_bool result;
3483 result = get_pht_entry_from_index(GC_grungy_pages, index);
3484 # ifdef GC_SOLARIS_THREADS
3485 if (result && PAGE_IS_FRESH(h)) result = FALSE;
3486 /* This happens only if page was declared fresh since */
3487 /* the read_dirty call, e.g. because it's in an unused */
3488 /* thread stack. It's OK to treat it as clean, in */
3489 /* that case. And it's consistent with */
3490 /* GC_page_was_ever_dirty. */
3491 # endif
3492 return(result);
3495 GC_bool GC_page_was_ever_dirty(h)
3496 struct hblk *h;
3498 register word index = PHT_HASH(h);
3499 register GC_bool result;
3501 result = get_pht_entry_from_index(GC_written_pages, index);
3502 # ifdef GC_SOLARIS_THREADS
3503 if (result && PAGE_IS_FRESH(h)) result = FALSE;
3504 # endif
3505 return(result);
3508 /* Caller holds allocation lock. */
3509 void GC_is_fresh(h, n)
3510 struct hblk *h;
3511 word n;
3514 register word index;
3516 # ifdef GC_SOLARIS_THREADS
3517 register word i;
3519 if (GC_fresh_pages != 0) {
3520 for (i = 0; i < n; i++) {
3521 ADD_FRESH_PAGE(h + i);
3524 # endif
3527 # endif /* PROC_VDB */
3530 # ifdef PCR_VDB
3532 # include "vd/PCR_VD.h"
3534 # define NPAGES (32*1024) /* 128 MB */
3536 PCR_VD_DB GC_grungy_bits[NPAGES];
3538 ptr_t GC_vd_base; /* Address corresponding to GC_grungy_bits[0] */
3539 /* HBLKSIZE aligned. */
3541 void GC_dirty_init()
3543 GC_dirty_maintained = TRUE;
3544 /* For the time being, we assume the heap generally grows up */
3545 GC_vd_base = GC_heap_sects[0].hs_start;
3546 if (GC_vd_base == 0) {
3547 ABORT("Bad initial heap segment");
3549 if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE)
3550 != PCR_ERes_okay) {
3551 ABORT("dirty bit initialization failed");
3555 void GC_read_dirty()
3557 /* lazily enable dirty bits on newly added heap sects */
3559 static int onhs = 0;
3560 int nhs = GC_n_heap_sects;
3561 for( ; onhs < nhs; onhs++ ) {
3562 PCR_VD_WriteProtectEnable(
3563 GC_heap_sects[onhs].hs_start,
3564 GC_heap_sects[onhs].hs_bytes );
3569 if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits)
3570 != PCR_ERes_okay) {
3571 ABORT("dirty bit read failed");
3575 GC_bool GC_page_was_dirty(h)
3576 struct hblk *h;
3578 if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) {
3579 return(TRUE);
3581 return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit);
3584 /*ARGSUSED*/
3585 void GC_remove_protection(h, nblocks, is_ptrfree)
3586 struct hblk *h;
3587 word nblocks;
3588 GC_bool is_ptrfree;
3590 PCR_VD_WriteProtectDisable(h, nblocks*HBLKSIZE);
3591 PCR_VD_WriteProtectEnable(h, nblocks*HBLKSIZE);
3594 # endif /* PCR_VDB */
3596 #if defined(MPROTECT_VDB) && defined(DARWIN)
3597 /* The following sources were used as a *reference* for this exception handling
3598 code:
3599 1. Apple's mach/xnu documentation
3600 2. Timothy J. Wood's "Mach Exception Handlers 101" post to the
3601 omnigroup's macosx-dev list.
3602 www.omnigroup.com/mailman/archive/macosx-dev/2000-June/002030.html
3603 3. macosx-nat.c from Apple's GDB source code.
3606 /* The bug that caused all this trouble should now be fixed. This should
3607 eventually be removed if all goes well. */
3608 /* define BROKEN_EXCEPTION_HANDLING */
3610 #include <mach/mach.h>
3611 #include <mach/mach_error.h>
3612 #include <mach/thread_status.h>
3613 #include <mach/exception.h>
3614 #include <mach/task.h>
3615 #include <pthread.h>
3617 /* These are not defined in any header, although they are documented */
3618 extern boolean_t exc_server(mach_msg_header_t *,mach_msg_header_t *);
3619 extern kern_return_t exception_raise(
3620 mach_port_t,mach_port_t,mach_port_t,
3621 exception_type_t,exception_data_t,mach_msg_type_number_t);
3622 extern kern_return_t exception_raise_state(
3623 mach_port_t,mach_port_t,mach_port_t,
3624 exception_type_t,exception_data_t,mach_msg_type_number_t,
3625 thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3626 thread_state_t,mach_msg_type_number_t*);
3627 extern kern_return_t exception_raise_state_identity(
3628 mach_port_t,mach_port_t,mach_port_t,
3629 exception_type_t,exception_data_t,mach_msg_type_number_t,
3630 thread_state_flavor_t*,thread_state_t,mach_msg_type_number_t,
3631 thread_state_t,mach_msg_type_number_t*);
3634 #define MAX_EXCEPTION_PORTS 16
3636 static struct {
3637 mach_msg_type_number_t count;
3638 exception_mask_t masks[MAX_EXCEPTION_PORTS];
3639 exception_handler_t ports[MAX_EXCEPTION_PORTS];
3640 exception_behavior_t behaviors[MAX_EXCEPTION_PORTS];
3641 thread_state_flavor_t flavors[MAX_EXCEPTION_PORTS];
3642 } GC_old_exc_ports;
3644 static struct {
3645 mach_port_t exception;
3646 #if defined(THREADS)
3647 mach_port_t reply;
3648 #endif
3649 } GC_ports;
3651 typedef struct {
3652 mach_msg_header_t head;
3653 } GC_msg_t;
3655 typedef enum {
3656 GC_MP_NORMAL, GC_MP_DISCARDING, GC_MP_STOPPED
3657 } GC_mprotect_state_t;
3659 /* FIXME: 1 and 2 seem to be safe to use in the msgh_id field,
3660 but it isn't documented. Use the source and see if they
3661 should be ok. */
3662 #define ID_STOP 1
3663 #define ID_RESUME 2
3665 /* These values are only used on the reply port */
3666 #define ID_ACK 3
3668 #if defined(THREADS)
3670 GC_mprotect_state_t GC_mprotect_state;
3672 /* The following should ONLY be called when the world is stopped */
3673 static void GC_mprotect_thread_notify(mach_msg_id_t id) {
3674 struct {
3675 GC_msg_t msg;
3676 mach_msg_trailer_t trailer;
3677 } buf;
3678 mach_msg_return_t r;
3679 /* remote, local */
3680 buf.msg.head.msgh_bits =
3681 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3682 buf.msg.head.msgh_size = sizeof(buf.msg);
3683 buf.msg.head.msgh_remote_port = GC_ports.exception;
3684 buf.msg.head.msgh_local_port = MACH_PORT_NULL;
3685 buf.msg.head.msgh_id = id;
3687 r = mach_msg(
3688 &buf.msg.head,
3689 MACH_SEND_MSG|MACH_RCV_MSG|MACH_RCV_LARGE,
3690 sizeof(buf.msg),
3691 sizeof(buf),
3692 GC_ports.reply,
3693 MACH_MSG_TIMEOUT_NONE,
3694 MACH_PORT_NULL);
3695 if(r != MACH_MSG_SUCCESS)
3696 ABORT("mach_msg failed in GC_mprotect_thread_notify");
3697 if(buf.msg.head.msgh_id != ID_ACK)
3698 ABORT("invalid ack in GC_mprotect_thread_notify");
3701 /* Should only be called by the mprotect thread */
3702 static void GC_mprotect_thread_reply() {
3703 GC_msg_t msg;
3704 mach_msg_return_t r;
3705 /* remote, local */
3706 msg.head.msgh_bits =
3707 MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND,0);
3708 msg.head.msgh_size = sizeof(msg);
3709 msg.head.msgh_remote_port = GC_ports.reply;
3710 msg.head.msgh_local_port = MACH_PORT_NULL;
3711 msg.head.msgh_id = ID_ACK;
3713 r = mach_msg(
3714 &msg.head,
3715 MACH_SEND_MSG,
3716 sizeof(msg),
3718 MACH_PORT_NULL,
3719 MACH_MSG_TIMEOUT_NONE,
3720 MACH_PORT_NULL);
3721 if(r != MACH_MSG_SUCCESS)
3722 ABORT("mach_msg failed in GC_mprotect_thread_reply");
3725 void GC_mprotect_stop() {
3726 GC_mprotect_thread_notify(ID_STOP);
3728 void GC_mprotect_resume() {
3729 GC_mprotect_thread_notify(ID_RESUME);
3732 #else /* !THREADS */
3733 /* The compiler should optimize away any GC_mprotect_state computations */
3734 #define GC_mprotect_state GC_MP_NORMAL
3735 #endif
3737 static void *GC_mprotect_thread(void *arg) {
3738 mach_msg_return_t r;
3739 /* These two structures contain some private kernel data. We don't need to
3740 access any of it so we don't bother defining a proper struct. The
3741 correct definitions are in the xnu source code. */
3742 struct {
3743 mach_msg_header_t head;
3744 char data[256];
3745 } reply;
3746 struct {
3747 mach_msg_header_t head;
3748 mach_msg_body_t msgh_body;
3749 char data[1024];
3750 } msg;
3752 mach_msg_id_t id;
3754 GC_darwin_register_mach_handler_thread(mach_thread_self());
3756 for(;;) {
3757 r = mach_msg(
3758 &msg.head,
3759 MACH_RCV_MSG|MACH_RCV_LARGE|
3760 (GC_mprotect_state == GC_MP_DISCARDING ? MACH_RCV_TIMEOUT : 0),
3762 sizeof(msg),
3763 GC_ports.exception,
3764 GC_mprotect_state == GC_MP_DISCARDING ? 0 : MACH_MSG_TIMEOUT_NONE,
3765 MACH_PORT_NULL);
3767 id = r == MACH_MSG_SUCCESS ? msg.head.msgh_id : -1;
3769 #if defined(THREADS)
3770 if(GC_mprotect_state == GC_MP_DISCARDING) {
3771 if(r == MACH_RCV_TIMED_OUT) {
3772 GC_mprotect_state = GC_MP_STOPPED;
3773 GC_mprotect_thread_reply();
3774 continue;
3776 if(r == MACH_MSG_SUCCESS && (id == ID_STOP || id == ID_RESUME))
3777 ABORT("out of order mprotect thread request");
3779 #endif
3781 if(r != MACH_MSG_SUCCESS) {
3782 GC_err_printf2("mach_msg failed with %d %s\n",
3783 (int)r,mach_error_string(r));
3784 ABORT("mach_msg failed");
3787 switch(id) {
3788 #if defined(THREADS)
3789 case ID_STOP:
3790 if(GC_mprotect_state != GC_MP_NORMAL)
3791 ABORT("Called mprotect_stop when state wasn't normal");
3792 GC_mprotect_state = GC_MP_DISCARDING;
3793 break;
3794 case ID_RESUME:
3795 if(GC_mprotect_state != GC_MP_STOPPED)
3796 ABORT("Called mprotect_resume when state wasn't stopped");
3797 GC_mprotect_state = GC_MP_NORMAL;
3798 GC_mprotect_thread_reply();
3799 break;
3800 #endif /* THREADS */
3801 default:
3802 /* Handle the message (calls catch_exception_raise) */
3803 if(!exc_server(&msg.head,&reply.head))
3804 ABORT("exc_server failed");
3805 /* Send the reply */
3806 r = mach_msg(
3807 &reply.head,
3808 MACH_SEND_MSG,
3809 reply.head.msgh_size,
3811 MACH_PORT_NULL,
3812 MACH_MSG_TIMEOUT_NONE,
3813 MACH_PORT_NULL);
3814 if(r != MACH_MSG_SUCCESS) {
3815 /* This will fail if the thread dies, but the thread shouldn't
3816 die... */
3817 #ifdef BROKEN_EXCEPTION_HANDLING
3818 GC_err_printf2(
3819 "mach_msg failed with %d %s while sending exc reply\n",
3820 (int)r,mach_error_string(r));
3821 #else
3822 ABORT("mach_msg failed while sending exception reply");
3823 #endif
3825 } /* switch */
3826 } /* for(;;) */
3827 /* NOT REACHED */
3828 return NULL;
3831 /* All this SIGBUS code shouldn't be necessary. All protection faults should
3832 be going throught the mach exception handler. However, it seems a SIGBUS is
3833 occasionally sent for some unknown reason. Even more odd, it seems to be
3834 meaningless and safe to ignore. */
3835 #ifdef BROKEN_EXCEPTION_HANDLING
3837 typedef void (* SIG_PF)();
3838 static SIG_PF GC_old_bus_handler;
3840 /* Updates to this aren't atomic, but the SIGBUSs seem pretty rare.
3841 Even if this doesn't get updated property, it isn't really a problem */
3842 static int GC_sigbus_count;
3844 static void GC_darwin_sigbus(int num,siginfo_t *sip,void *context) {
3845 if(num != SIGBUS) ABORT("Got a non-sigbus signal in the sigbus handler");
3847 /* Ugh... some seem safe to ignore, but too many in a row probably means
3848 trouble. GC_sigbus_count is reset for each mach exception that is
3849 handled */
3850 if(GC_sigbus_count >= 8) {
3851 ABORT("Got more than 8 SIGBUSs in a row!");
3852 } else {
3853 GC_sigbus_count++;
3854 GC_err_printf0("GC: WARNING: Ignoring SIGBUS.\n");
3857 #endif /* BROKEN_EXCEPTION_HANDLING */
3859 void GC_dirty_init() {
3860 kern_return_t r;
3861 mach_port_t me;
3862 pthread_t thread;
3863 pthread_attr_t attr;
3864 exception_mask_t mask;
3866 # ifdef PRINTSTATS
3867 GC_printf0("Inititalizing mach/darwin mprotect virtual dirty bit "
3868 "implementation\n");
3869 # endif
3870 # ifdef BROKEN_EXCEPTION_HANDLING
3871 GC_err_printf0("GC: WARNING: Enabling workarounds for various darwin "
3872 "exception handling bugs.\n");
3873 # endif
3874 GC_dirty_maintained = TRUE;
3875 if (GC_page_size % HBLKSIZE != 0) {
3876 GC_err_printf0("Page size not multiple of HBLKSIZE\n");
3877 ABORT("Page size not multiple of HBLKSIZE");
3880 GC_task_self = me = mach_task_self();
3882 r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.exception);
3883 if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (exception port)");
3885 r = mach_port_insert_right(me,GC_ports.exception,GC_ports.exception,
3886 MACH_MSG_TYPE_MAKE_SEND);
3887 if(r != KERN_SUCCESS)
3888 ABORT("mach_port_insert_right failed (exception port)");
3890 #if defined(THREADS)
3891 r = mach_port_allocate(me,MACH_PORT_RIGHT_RECEIVE,&GC_ports.reply);
3892 if(r != KERN_SUCCESS) ABORT("mach_port_allocate failed (reply port)");
3893 #endif
3895 /* The exceptions we want to catch */
3896 mask = EXC_MASK_BAD_ACCESS;
3898 r = task_get_exception_ports(
3900 mask,
3901 GC_old_exc_ports.masks,
3902 &GC_old_exc_ports.count,
3903 GC_old_exc_ports.ports,
3904 GC_old_exc_ports.behaviors,
3905 GC_old_exc_ports.flavors
3907 if(r != KERN_SUCCESS) ABORT("task_get_exception_ports failed");
3909 r = task_set_exception_ports(
3911 mask,
3912 GC_ports.exception,
3913 EXCEPTION_DEFAULT,
3914 GC_MACH_THREAD_STATE_FLAVOR
3916 if(r != KERN_SUCCESS) ABORT("task_set_exception_ports failed");
3918 if(pthread_attr_init(&attr) != 0) ABORT("pthread_attr_init failed");
3919 if(pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED) != 0)
3920 ABORT("pthread_attr_setdetachedstate failed");
3922 # undef pthread_create
3923 /* This will call the real pthread function, not our wrapper */
3924 if(pthread_create(&thread,&attr,GC_mprotect_thread,NULL) != 0)
3925 ABORT("pthread_create failed");
3926 pthread_attr_destroy(&attr);
3928 /* Setup the sigbus handler for ignoring the meaningless SIGBUSs */
3929 #ifdef BROKEN_EXCEPTION_HANDLING
3931 struct sigaction sa, oldsa;
3932 sa.sa_handler = (SIG_PF)GC_darwin_sigbus;
3933 sigemptyset(&sa.sa_mask);
3934 sa.sa_flags = SA_RESTART|SA_SIGINFO;
3935 if(sigaction(SIGBUS,&sa,&oldsa) < 0) ABORT("sigaction");
3936 GC_old_bus_handler = (SIG_PF)oldsa.sa_handler;
3937 if (GC_old_bus_handler != SIG_DFL) {
3938 # ifdef PRINTSTATS
3939 GC_err_printf0("Replaced other SIGBUS handler\n");
3940 # endif
3943 #endif /* BROKEN_EXCEPTION_HANDLING */
3946 /* The source code for Apple's GDB was used as a reference for the exception
3947 forwarding code. This code is similar to be GDB code only because there is
3948 only one way to do it. */
3949 static kern_return_t GC_forward_exception(
3950 mach_port_t thread,
3951 mach_port_t task,
3952 exception_type_t exception,
3953 exception_data_t data,
3954 mach_msg_type_number_t data_count
3956 int i;
3957 kern_return_t r;
3958 mach_port_t port;
3959 exception_behavior_t behavior;
3960 thread_state_flavor_t flavor;
3962 thread_state_t thread_state;
3963 mach_msg_type_number_t thread_state_count = THREAD_STATE_MAX;
3965 for(i=0;i<GC_old_exc_ports.count;i++)
3966 if(GC_old_exc_ports.masks[i] & (1 << exception))
3967 break;
3968 if(i==GC_old_exc_ports.count) ABORT("No handler for exception!");
3970 port = GC_old_exc_ports.ports[i];
3971 behavior = GC_old_exc_ports.behaviors[i];
3972 flavor = GC_old_exc_ports.flavors[i];
3974 if(behavior != EXCEPTION_DEFAULT) {
3975 r = thread_get_state(thread,flavor,thread_state,&thread_state_count);
3976 if(r != KERN_SUCCESS)
3977 ABORT("thread_get_state failed in forward_exception");
3980 switch(behavior) {
3981 case EXCEPTION_DEFAULT:
3982 r = exception_raise(port,thread,task,exception,data,data_count);
3983 break;
3984 case EXCEPTION_STATE:
3985 r = exception_raise_state(port,thread,task,exception,data,
3986 data_count,&flavor,thread_state,thread_state_count,
3987 thread_state,&thread_state_count);
3988 break;
3989 case EXCEPTION_STATE_IDENTITY:
3990 r = exception_raise_state_identity(port,thread,task,exception,data,
3991 data_count,&flavor,thread_state,thread_state_count,
3992 thread_state,&thread_state_count);
3993 break;
3994 default:
3995 r = KERN_FAILURE; /* make gcc happy */
3996 ABORT("forward_exception: unknown behavior");
3997 break;
4000 if(behavior != EXCEPTION_DEFAULT) {
4001 r = thread_set_state(thread,flavor,thread_state,thread_state_count);
4002 if(r != KERN_SUCCESS)
4003 ABORT("thread_set_state failed in forward_exception");
4006 return r;
4009 #define FWD() GC_forward_exception(thread,task,exception,code,code_count)
4011 /* This violates the namespace rules but there isn't anything that can be done
4012 about it. The exception handling stuff is hard coded to call this */
4013 kern_return_t
4014 catch_exception_raise(
4015 mach_port_t exception_port,mach_port_t thread,mach_port_t task,
4016 exception_type_t exception,exception_data_t code,
4017 mach_msg_type_number_t code_count
4019 kern_return_t r;
4020 char *addr;
4021 struct hblk *h;
4022 int i;
4023 # if defined(POWERPC)
4024 # if CPP_WORDSZ == 32
4025 thread_state_flavor_t flavor = PPC_EXCEPTION_STATE;
4026 mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE_COUNT;
4027 ppc_exception_state_t exc_state;
4028 # else
4029 thread_state_flavor_t flavor = PPC_EXCEPTION_STATE64;
4030 mach_msg_type_number_t exc_state_count = PPC_EXCEPTION_STATE64_COUNT;
4031 ppc_exception_state64_t exc_state;
4032 # endif
4033 # elif defined(I386)
4034 thread_state_flavor_t flavor = i386_EXCEPTION_STATE;
4035 mach_msg_type_number_t exc_state_count = i386_EXCEPTION_STATE_COUNT;
4036 i386_exception_state_t exc_state;
4037 # else
4038 # error FIXME for non-ppc darwin
4039 # endif
4042 if(exception != EXC_BAD_ACCESS || code[0] != KERN_PROTECTION_FAILURE) {
4043 #ifdef DEBUG_EXCEPTION_HANDLING
4044 /* We aren't interested, pass it on to the old handler */
4045 GC_printf3("Exception: 0x%x Code: 0x%x 0x%x in catch....\n",
4046 exception,
4047 code_count > 0 ? code[0] : -1,
4048 code_count > 1 ? code[1] : -1);
4049 #endif
4050 return FWD();
4053 r = thread_get_state(thread,flavor,
4054 (natural_t*)&exc_state,&exc_state_count);
4055 if(r != KERN_SUCCESS) {
4056 /* The thread is supposed to be suspended while the exception handler
4057 is called. This shouldn't fail. */
4058 #ifdef BROKEN_EXCEPTION_HANDLING
4059 GC_err_printf0("thread_get_state failed in "
4060 "catch_exception_raise\n");
4061 return KERN_SUCCESS;
4062 #else
4063 ABORT("thread_get_state failed in catch_exception_raise");
4064 #endif
4067 /* This is the address that caused the fault */
4068 #if defined(POWERPC)
4069 addr = (char*) exc_state.dar;
4070 #elif defined (I386)
4071 addr = (char*) exc_state.faultvaddr;
4072 #else
4073 # error FIXME for non POWERPC/I386
4074 #endif
4076 if((HDR(addr)) == 0) {
4077 /* Ugh... just like the SIGBUS problem above, it seems we get a bogus
4078 KERN_PROTECTION_FAILURE every once and a while. We wait till we get
4079 a bunch in a row before doing anything about it. If a "real" fault
4080 ever occurres it'll just keep faulting over and over and we'll hit
4081 the limit pretty quickly. */
4082 #ifdef BROKEN_EXCEPTION_HANDLING
4083 static char *last_fault;
4084 static int last_fault_count;
4086 if(addr != last_fault) {
4087 last_fault = addr;
4088 last_fault_count = 0;
4090 if(++last_fault_count < 32) {
4091 if(last_fault_count == 1)
4092 GC_err_printf1(
4093 "GC: WARNING: Ignoring KERN_PROTECTION_FAILURE at %p\n",
4094 addr);
4095 return KERN_SUCCESS;
4098 GC_err_printf1("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr);
4099 /* Can't pass it along to the signal handler because that is
4100 ignoring SIGBUS signals. We also shouldn't call ABORT here as
4101 signals don't always work too well from the exception handler. */
4102 GC_err_printf0("Aborting\n");
4103 exit(EXIT_FAILURE);
4104 #else /* BROKEN_EXCEPTION_HANDLING */
4105 /* Pass it along to the next exception handler
4106 (which should call SIGBUS/SIGSEGV) */
4107 return FWD();
4108 #endif /* !BROKEN_EXCEPTION_HANDLING */
4111 #ifdef BROKEN_EXCEPTION_HANDLING
4112 /* Reset the number of consecutive SIGBUSs */
4113 GC_sigbus_count = 0;
4114 #endif
4116 if(GC_mprotect_state == GC_MP_NORMAL) { /* common case */
4117 h = (struct hblk*)((word)addr & ~(GC_page_size-1));
4118 UNPROTECT(h, GC_page_size);
4119 for (i = 0; i < divHBLKSZ(GC_page_size); i++) {
4120 register int index = PHT_HASH(h+i);
4121 async_set_pht_entry_from_index(GC_dirty_pages, index);
4123 } else if(GC_mprotect_state == GC_MP_DISCARDING) {
4124 /* Lie to the thread for now. No sense UNPROTECT()ing the memory
4125 when we're just going to PROTECT() it again later. The thread
4126 will just fault again once it resumes */
4127 } else {
4128 /* Shouldn't happen, i don't think */
4129 GC_printf0("KERN_PROTECTION_FAILURE while world is stopped\n");
4130 return FWD();
4132 return KERN_SUCCESS;
4134 #undef FWD
4136 /* These should never be called, but just in case... */
4137 kern_return_t catch_exception_raise_state(mach_port_name_t exception_port,
4138 int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
4139 int flavor, thread_state_t old_state, int old_stateCnt,
4140 thread_state_t new_state, int new_stateCnt)
4142 ABORT("catch_exception_raise_state");
4143 return(KERN_INVALID_ARGUMENT);
4145 kern_return_t catch_exception_raise_state_identity(
4146 mach_port_name_t exception_port, mach_port_t thread, mach_port_t task,
4147 int exception, exception_data_t code, mach_msg_type_number_t codeCnt,
4148 int flavor, thread_state_t old_state, int old_stateCnt,
4149 thread_state_t new_state, int new_stateCnt)
4151 ABORT("catch_exception_raise_state_identity");
4152 return(KERN_INVALID_ARGUMENT);
4156 #endif /* DARWIN && MPROTECT_VDB */
4158 # ifndef HAVE_INCREMENTAL_PROTECTION_NEEDS
4159 int GC_incremental_protection_needs()
4161 return GC_PROTECTS_NONE;
4163 # endif /* !HAVE_INCREMENTAL_PROTECTION_NEEDS */
4166 * Call stack save code for debugging.
4167 * Should probably be in mach_dep.c, but that requires reorganization.
4170 /* I suspect the following works for most X86 *nix variants, so */
4171 /* long as the frame pointer is explicitly stored. In the case of gcc, */
4172 /* compiler flags (e.g. -fomit-frame-pointer) determine whether it is. */
4173 #if defined(I386) && defined(LINUX) && defined(SAVE_CALL_CHAIN)
4174 # include <features.h>
4176 struct frame {
4177 struct frame *fr_savfp;
4178 long fr_savpc;
4179 long fr_arg[NARGS]; /* All the arguments go here. */
4181 #endif
4183 #if defined(SPARC)
4184 # if defined(LINUX)
4185 # include <features.h>
4187 struct frame {
4188 long fr_local[8];
4189 long fr_arg[6];
4190 struct frame *fr_savfp;
4191 long fr_savpc;
4192 # ifndef __arch64__
4193 char *fr_stret;
4194 # endif
4195 long fr_argd[6];
4196 long fr_argx[0];
4198 # else
4199 # if defined(SUNOS4)
4200 # include <machine/frame.h>
4201 # else
4202 # if defined (DRSNX)
4203 # include <sys/sparc/frame.h>
4204 # else
4205 # if defined(OPENBSD)
4206 # include <frame.h>
4207 # else
4208 # if defined(FREEBSD) || defined(NETBSD)
4209 # include <machine/frame.h>
4210 # else
4211 # include <sys/frame.h>
4212 # endif
4213 # endif
4214 # endif
4215 # endif
4216 # endif
4217 # if NARGS > 6
4218 --> We only know how to to get the first 6 arguments
4219 # endif
4220 #endif /* SPARC */
4222 #ifdef NEED_CALLINFO
4223 /* Fill in the pc and argument information for up to NFRAMES of my */
4224 /* callers. Ignore my frame and my callers frame. */
4226 #ifdef LINUX
4227 # include <unistd.h>
4228 #endif
4230 #endif /* NEED_CALLINFO */
4232 #if defined(GC_HAVE_BUILTIN_BACKTRACE)
4233 # include <execinfo.h>
4234 #endif
4236 #ifdef SAVE_CALL_CHAIN
4238 #if NARGS == 0 && NFRAMES % 2 == 0 /* No padding */ \
4239 && defined(GC_HAVE_BUILTIN_BACKTRACE)
4241 #ifdef REDIRECT_MALLOC
4242 /* Deal with possible malloc calls in backtrace by omitting */
4243 /* the infinitely recursing backtrace. */
4244 # ifdef THREADS
4245 __thread /* If your compiler doesn't understand this */
4246 /* you could use something like pthread_getspecific. */
4247 # endif
4248 GC_in_save_callers = FALSE;
4249 #endif
4251 void GC_save_callers (info)
4252 struct callinfo info[NFRAMES];
4254 void * tmp_info[NFRAMES + 1];
4255 int npcs, i;
4256 # define IGNORE_FRAMES 1
4258 /* We retrieve NFRAMES+1 pc values, but discard the first, since it */
4259 /* points to our own frame. */
4260 # ifdef REDIRECT_MALLOC
4261 if (GC_in_save_callers) {
4262 info[0].ci_pc = (word)(&GC_save_callers);
4263 for (i = 1; i < NFRAMES; ++i) info[i].ci_pc = 0;
4264 return;
4266 GC_in_save_callers = TRUE;
4267 # endif
4268 GC_ASSERT(sizeof(struct callinfo) == sizeof(void *));
4269 npcs = backtrace((void **)tmp_info, NFRAMES + IGNORE_FRAMES);
4270 BCOPY(tmp_info+IGNORE_FRAMES, info, (npcs - IGNORE_FRAMES) * sizeof(void *));
4271 for (i = npcs - IGNORE_FRAMES; i < NFRAMES; ++i) info[i].ci_pc = 0;
4272 # ifdef REDIRECT_MALLOC
4273 GC_in_save_callers = FALSE;
4274 # endif
4277 #else /* No builtin backtrace; do it ourselves */
4279 #if (defined(OPENBSD) || defined(NETBSD) || defined(FREEBSD)) && defined(SPARC)
4280 # define FR_SAVFP fr_fp
4281 # define FR_SAVPC fr_pc
4282 #else
4283 # define FR_SAVFP fr_savfp
4284 # define FR_SAVPC fr_savpc
4285 #endif
4287 #if defined(SPARC) && (defined(__arch64__) || defined(__sparcv9))
4288 # define BIAS 2047
4289 #else
4290 # define BIAS 0
4291 #endif
4293 void GC_save_callers (info)
4294 struct callinfo info[NFRAMES];
4296 struct frame *frame;
4297 struct frame *fp;
4298 int nframes = 0;
4299 # ifdef I386
4300 /* We assume this is turned on only with gcc as the compiler. */
4301 asm("movl %%ebp,%0" : "=r"(frame));
4302 fp = frame;
4303 # else
4304 frame = (struct frame *) GC_save_regs_in_stack ();
4305 fp = (struct frame *)((long) frame -> FR_SAVFP + BIAS);
4306 #endif
4308 for (; (!(fp HOTTER_THAN frame) && !(GC_stackbottom HOTTER_THAN (ptr_t)fp)
4309 && (nframes < NFRAMES));
4310 fp = (struct frame *)((long) fp -> FR_SAVFP + BIAS), nframes++) {
4311 register int i;
4313 info[nframes].ci_pc = fp->FR_SAVPC;
4314 # if NARGS > 0
4315 for (i = 0; i < NARGS; i++) {
4316 info[nframes].ci_arg[i] = ~(fp->fr_arg[i]);
4318 # endif /* NARGS > 0 */
4320 if (nframes < NFRAMES) info[nframes].ci_pc = 0;
4323 #endif /* No builtin backtrace */
4325 #endif /* SAVE_CALL_CHAIN */
4327 #ifdef NEED_CALLINFO
4329 /* Print info to stderr. We do NOT hold the allocation lock */
4330 void GC_print_callers (info)
4331 struct callinfo info[NFRAMES];
4333 register int i;
4334 static int reentry_count = 0;
4335 GC_bool stop = FALSE;
4337 /* FIXME: This should probably use a different lock, so that we */
4338 /* become callable with or without the allocation lock. */
4339 LOCK();
4340 ++reentry_count;
4341 UNLOCK();
4343 # if NFRAMES == 1
4344 GC_err_printf0("\tCaller at allocation:\n");
4345 # else
4346 GC_err_printf0("\tCall chain at allocation:\n");
4347 # endif
4348 for (i = 0; i < NFRAMES && !stop ; i++) {
4349 if (info[i].ci_pc == 0) break;
4350 # if NARGS > 0
4352 int j;
4354 GC_err_printf0("\t\targs: ");
4355 for (j = 0; j < NARGS; j++) {
4356 if (j != 0) GC_err_printf0(", ");
4357 GC_err_printf2("%d (0x%X)", ~(info[i].ci_arg[j]),
4358 ~(info[i].ci_arg[j]));
4360 GC_err_printf0("\n");
4362 # endif
4363 if (reentry_count > 1) {
4364 /* We were called during an allocation during */
4365 /* a previous GC_print_callers call; punt. */
4366 GC_err_printf1("\t\t##PC##= 0x%lx\n", info[i].ci_pc);
4367 continue;
4370 # ifdef LINUX
4371 FILE *pipe;
4372 # endif
4373 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4374 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4375 char **sym_name =
4376 backtrace_symbols((void **)(&(info[i].ci_pc)), 1);
4377 char *name = sym_name[0];
4378 # else
4379 char buf[40];
4380 char *name = buf;
4381 sprintf(buf, "##PC##= 0x%lx", info[i].ci_pc);
4382 # endif
4383 # if defined(LINUX) && !defined(SMALL_CONFIG)
4384 /* Try for a line number. */
4386 # define EXE_SZ 100
4387 static char exe_name[EXE_SZ];
4388 # define CMD_SZ 200
4389 char cmd_buf[CMD_SZ];
4390 # define RESULT_SZ 200
4391 static char result_buf[RESULT_SZ];
4392 size_t result_len;
4393 char *old_preload;
4394 # define PRELOAD_SZ 200
4395 char preload_buf[PRELOAD_SZ];
4396 static GC_bool found_exe_name = FALSE;
4397 static GC_bool will_fail = FALSE;
4398 int ret_code;
4399 /* Try to get it via a hairy and expensive scheme. */
4400 /* First we get the name of the executable: */
4401 if (will_fail) goto out;
4402 if (!found_exe_name) {
4403 ret_code = readlink("/proc/self/exe", exe_name, EXE_SZ);
4404 if (ret_code < 0 || ret_code >= EXE_SZ
4405 || exe_name[0] != '/') {
4406 will_fail = TRUE; /* Dont try again. */
4407 goto out;
4409 exe_name[ret_code] = '\0';
4410 found_exe_name = TRUE;
4412 /* Then we use popen to start addr2line -e <exe> <addr> */
4413 /* There are faster ways to do this, but hopefully this */
4414 /* isn't time critical. */
4415 sprintf(cmd_buf, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name,
4416 (unsigned long)info[i].ci_pc);
4417 old_preload = getenv ("LD_PRELOAD");
4418 if (0 != old_preload) {
4419 if (strlen (old_preload) >= PRELOAD_SZ) {
4420 will_fail = TRUE;
4421 goto out;
4423 strcpy (preload_buf, old_preload);
4424 unsetenv ("LD_PRELOAD");
4426 pipe = popen(cmd_buf, "r");
4427 if (0 != old_preload
4428 && 0 != setenv ("LD_PRELOAD", preload_buf, 0)) {
4429 WARN("Failed to reset LD_PRELOAD\n", 0);
4431 if (pipe == NULL
4432 || (result_len = fread(result_buf, 1, RESULT_SZ - 1, pipe))
4433 == 0) {
4434 if (pipe != NULL) pclose(pipe);
4435 will_fail = TRUE;
4436 goto out;
4438 if (result_buf[result_len - 1] == '\n') --result_len;
4439 result_buf[result_len] = 0;
4440 if (result_buf[0] == '?'
4441 || result_buf[result_len-2] == ':'
4442 && result_buf[result_len-1] == '0') {
4443 pclose(pipe);
4444 goto out;
4446 /* Get rid of embedded newline, if any. Test for "main" */
4448 char * nl = strchr(result_buf, '\n');
4449 if (nl != NULL && nl < result_buf + result_len) {
4450 *nl = ':';
4452 if (strncmp(result_buf, "main", nl - result_buf) == 0) {
4453 stop = TRUE;
4456 if (result_len < RESULT_SZ - 25) {
4457 /* Add in hex address */
4458 sprintf(result_buf + result_len, " [0x%lx]",
4459 (unsigned long)info[i].ci_pc);
4461 name = result_buf;
4462 pclose(pipe);
4463 out:;
4465 # endif /* LINUX */
4466 GC_err_printf1("\t\t%s\n", name);
4467 # if defined(GC_HAVE_BUILTIN_BACKTRACE) \
4468 && !defined(GC_BACKTRACE_SYMBOLS_BROKEN)
4469 free(sym_name); /* May call GC_free; that's OK */
4470 # endif
4473 LOCK();
4474 --reentry_count;
4475 UNLOCK();
4478 #endif /* NEED_CALLINFO */
4482 #if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
4484 /* Dump /proc/self/maps to GC_stderr, to enable looking up names for
4485 addresses in FIND_LEAK output. */
4487 static word dump_maps(char *maps)
4489 GC_err_write(maps, strlen(maps));
4490 return 1;
4493 void GC_print_address_map()
4495 GC_err_printf0("---------- Begin address map ----------\n");
4496 GC_apply_to_maps(dump_maps);
4497 GC_err_printf0("---------- End address map ----------\n");
4500 #endif