Collected tested types into a new file.
[mono-project.git] / libgc / dyn_load.c
bloba42efd4e25d7264d6d4a93f26051cf614b8ca0ca
1 /*
2 * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
3 * Copyright (c) 1997 by Silicon Graphics. All rights reserved.
5 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
6 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
8 * Permission is hereby granted to use or copy this program
9 * for any purpose, provided the above notices are retained on all copies.
10 * Permission to modify the code and to distribute modified code is granted,
11 * provided the above notices are retained, and a notice that the code was
12 * modified is included with the above copyright notice.
14 * Original author: Bill Janssen
15 * Heavily modified by Hans Boehm and others
19 * This is incredibly OS specific code for tracking down data sections in
20 * dynamic libraries. There appears to be no way of doing this quickly
21 * without groveling through undocumented data structures. We would argue
22 * that this is a bug in the design of the dlopen interface. THIS CODE
23 * MAY BREAK IN FUTURE OS RELEASES. If this matters to you, don't hesitate
24 * to let your vendor know ...
26 * None of this is safe with dlclose and incremental collection.
27 * But then not much of anything is safe in the presence of dlclose.
29 #if defined(__linux__) && !defined(_GNU_SOURCE)
30 /* Can't test LINUX, since this must be define before other includes */
31 # define _GNU_SOURCE
32 #endif
33 #if !defined(MACOS) && !defined(_WIN32_WCE)
34 # include <sys/types.h>
35 #endif
36 #include "private/gc_priv.h"
38 /* BTL: avoid circular redefinition of dlopen if GC_SOLARIS_THREADS defined */
39 # if (defined(GC_PTHREADS) || defined(GC_SOLARIS_THREADS)) \
40 && defined(dlopen) && !defined(GC_USE_LD_WRAP)
41 /* To support threads in Solaris, gc.h interposes on dlopen by */
42 /* defining "dlopen" to be "GC_dlopen", which is implemented below. */
43 /* However, both GC_FirstDLOpenedLinkMap() and GC_dlopen() use the */
44 /* real system dlopen() in their implementation. We first remove */
45 /* gc.h's dlopen definition and restore it later, after GC_dlopen(). */
46 # undef dlopen
47 # define GC_must_restore_redefined_dlopen
48 # else
49 # undef GC_must_restore_redefined_dlopen
50 # endif
52 #if (defined(DYNAMIC_LOADING) || defined(MSWIN32) || defined(MSWINCE)) \
53 && !defined(PCR)
54 #if !defined(SUNOS4) && !defined(SUNOS5DL) && !defined(IRIX5) && \
55 !defined(MSWIN32) && !defined(MSWINCE) && \
56 !(defined(ALPHA) && defined(OSF1)) && \
57 !defined(HPUX) && !(defined(LINUX) && defined(__ELF__)) && \
58 !defined(RS6000) && !defined(SCO_ELF) && !defined(DGUX) && \
59 !(defined(FREEBSD) && defined(__ELF__)) && \
60 !(defined(NETBSD) && defined(__ELF__)) && !defined(HURD) && \
61 !defined(DARWIN)
62 --> We only know how to find data segments of dynamic libraries for the
63 --> above. Additional SVR4 variants might not be too
64 --> hard to add.
65 #endif
67 #include <stdio.h>
68 #ifdef SUNOS5DL
69 /* Avoid #error "large files are not supported by libelf" errors */
70 #if defined(_ILP32) && (_FILE_OFFSET_BITS != 32)
71 #undef _FILE_OFFSET_BITS
72 #define _FILE_OFFSET_BITS 32
73 #endif
74 # include <sys/elf.h>
75 # include <dlfcn.h>
76 # include <link.h>
77 #endif
78 #ifdef SUNOS4
79 # include <dlfcn.h>
80 # include <link.h>
81 # include <a.out.h>
82 /* struct link_map field overrides */
83 # define l_next lm_next
84 # define l_addr lm_addr
85 # define l_name lm_name
86 #endif
88 #if defined(NETBSD)
89 # include <machine/elf_machdep.h>
90 # define ELFSIZE ARCH_ELFSIZE
91 #endif
93 #if defined(LINUX) && defined(__ELF__) || defined(SCO_ELF) || \
94 (defined(FREEBSD) && defined(__ELF__)) || defined(DGUX) || \
95 (defined(NETBSD) && defined(__ELF__)) || defined(HURD)
96 # include <stddef.h>
97 # include <elf.h>
98 # include <link.h>
99 #endif
101 /* Newer versions of GNU/Linux define this macro. We
102 * define it similarly for any ELF systems that don't. */
103 # ifndef ElfW
104 # if defined(FREEBSD)
105 # if __ELF_WORD_SIZE == 32
106 # define ElfW(type) Elf32_##type
107 # else
108 # define ElfW(type) Elf64_##type
109 # endif
110 # else
111 # ifdef NETBSD
112 # if ELFSIZE == 32
113 # define ElfW(type) Elf32_##type
114 # else
115 # define ElfW(type) Elf64_##type
116 # endif
117 # else
118 # if !defined(ELF_CLASS) || ELF_CLASS == ELFCLASS32
119 # define ElfW(type) Elf32_##type
120 # else
121 # define ElfW(type) Elf64_##type
122 # endif
123 # endif
124 # endif
125 # endif
127 #if defined(SUNOS5DL) && !defined(USE_PROC_FOR_LIBRARIES)
129 #ifdef LINT
130 Elf32_Dyn _DYNAMIC;
131 #endif
133 static struct link_map *
134 GC_FirstDLOpenedLinkMap()
136 extern ElfW(Dyn) _DYNAMIC;
137 ElfW(Dyn) *dp;
138 struct r_debug *r;
139 static struct link_map * cachedResult = 0;
140 static ElfW(Dyn) *dynStructureAddr = 0;
141 /* BTL: added to avoid Solaris 5.3 ld.so _DYNAMIC bug */
143 # ifdef SUNOS53_SHARED_LIB
144 /* BTL: Avoid the Solaris 5.3 bug that _DYNAMIC isn't being set */
145 /* up properly in dynamically linked .so's. This means we have */
146 /* to use its value in the set of original object files loaded */
147 /* at program startup. */
148 if( dynStructureAddr == 0 ) {
149 void* startupSyms = dlopen(0, RTLD_LAZY);
150 dynStructureAddr = (ElfW(Dyn)*)dlsym(startupSyms, "_DYNAMIC");
152 # else
153 dynStructureAddr = &_DYNAMIC;
154 # endif
156 if( dynStructureAddr == 0) {
157 return(0);
159 if( cachedResult == 0 ) {
160 int tag;
161 for( dp = ((ElfW(Dyn) *)(&_DYNAMIC)); (tag = dp->d_tag) != 0; dp++ ) {
162 if( tag == DT_DEBUG ) {
163 struct link_map *lm
164 = ((struct r_debug *)(dp->d_un.d_ptr))->r_map;
165 if( lm != 0 ) cachedResult = lm->l_next; /* might be NIL */
166 break;
170 return cachedResult;
173 #endif /* SUNOS5DL ... */
175 /* BTL: added to fix circular dlopen definition if GC_SOLARIS_THREADS defined */
176 # if defined(GC_must_restore_redefined_dlopen)
177 # define dlopen GC_dlopen
178 # endif
180 #if defined(SUNOS4) && !defined(USE_PROC_FOR_LIBRARIES)
182 #ifdef LINT
183 struct link_dynamic _DYNAMIC;
184 #endif
186 static struct link_map *
187 GC_FirstDLOpenedLinkMap()
189 extern struct link_dynamic _DYNAMIC;
191 if( &_DYNAMIC == 0) {
192 return(0);
194 return(_DYNAMIC.ld_un.ld_1->ld_loaded);
197 /* Return the address of the ld.so allocated common symbol */
198 /* with the least address, or 0 if none. */
199 static ptr_t GC_first_common()
201 ptr_t result = 0;
202 extern struct link_dynamic _DYNAMIC;
203 struct rtc_symb * curr_symbol;
205 if( &_DYNAMIC == 0) {
206 return(0);
208 curr_symbol = _DYNAMIC.ldd -> ldd_cp;
209 for (; curr_symbol != 0; curr_symbol = curr_symbol -> rtc_next) {
210 if (result == 0
211 || (ptr_t)(curr_symbol -> rtc_sp -> n_value) < result) {
212 result = (ptr_t)(curr_symbol -> rtc_sp -> n_value);
215 return(result);
218 #endif /* SUNOS4 ... */
220 # if defined(SUNOS4) || defined(SUNOS5DL)
221 /* Add dynamic library data sections to the root set. */
222 # if !defined(PCR) && !defined(GC_SOLARIS_THREADS) && defined(THREADS)
223 # ifndef SRC_M3
224 --> fix mutual exclusion with dlopen
225 # endif /* We assume M3 programs don't call dlopen for now */
226 # endif
228 # ifndef USE_PROC_FOR_LIBRARIES
229 void GC_register_dynamic_libraries()
231 struct link_map *lm = GC_FirstDLOpenedLinkMap();
234 for (lm = GC_FirstDLOpenedLinkMap();
235 lm != (struct link_map *) 0; lm = lm->l_next)
237 # ifdef SUNOS4
238 struct exec *e;
240 e = (struct exec *) lm->lm_addr;
241 GC_add_roots_inner(
242 ((char *) (N_DATOFF(*e) + lm->lm_addr)),
243 ((char *) (N_BSSADDR(*e) + e->a_bss + lm->lm_addr)),
244 TRUE);
245 # endif
246 # ifdef SUNOS5DL
247 ElfW(Ehdr) * e;
248 ElfW(Phdr) * p;
249 unsigned long offset;
250 char * start;
251 register int i;
253 e = (ElfW(Ehdr) *) lm->l_addr;
254 if (e == NULL)
255 continue;
257 p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
258 offset = ((unsigned long)(lm->l_addr));
259 for( i = 0; i < (int)(e->e_phnum); ((i++),(p++)) ) {
260 switch( p->p_type ) {
261 case PT_LOAD:
263 if( !(p->p_flags & PF_W) ) break;
264 start = ((char *)(p->p_vaddr)) + offset;
265 GC_add_roots_inner(
266 start,
267 start + p->p_memsz,
268 TRUE
271 break;
272 default:
273 break;
276 # endif
278 # ifdef SUNOS4
280 static ptr_t common_start = 0;
281 ptr_t common_end;
282 extern ptr_t GC_find_limit();
284 if (common_start == 0) common_start = GC_first_common();
285 if (common_start != 0) {
286 common_end = GC_find_limit(common_start, TRUE);
287 GC_add_roots_inner((char *)common_start, (char *)common_end, TRUE);
290 # endif
293 # endif /* !USE_PROC ... */
294 # endif /* SUNOS */
296 #if defined(LINUX) && defined(__ELF__) || defined(SCO_ELF) || \
297 (defined(FREEBSD) && defined(__ELF__)) || defined(DGUX) || \
298 (defined(NETBSD) && defined(__ELF__)) || defined(HURD)
301 #ifdef USE_PROC_FOR_LIBRARIES
303 #include <string.h>
305 #include <sys/stat.h>
306 #include <fcntl.h>
307 #include <unistd.h>
309 #define MAPS_BUF_SIZE (32*1024)
311 extern ssize_t GC_repeat_read(int fd, char *buf, size_t count);
312 /* Repeatedly read until buffer is filled, or EOF is encountered */
313 /* Defined in os_dep.c. */
315 char *GC_parse_map_entry(char *buf_ptr, word *start, word *end,
316 char *prot_buf, unsigned int *maj_dev);
317 word GC_apply_to_maps(word (*fn)(char *));
318 /* From os_dep.c */
320 word GC_register_map_entries(char *maps)
322 char prot_buf[5];
323 char *buf_ptr = maps;
324 int count;
325 word start, end;
326 unsigned int maj_dev;
327 word least_ha, greatest_ha;
328 unsigned i;
329 word datastart = (word)(DATASTART);
331 /* Compute heap bounds. FIXME: Should be done by add_to_heap? */
332 least_ha = (word)(-1);
333 greatest_ha = 0;
334 for (i = 0; i < GC_n_heap_sects; ++i) {
335 word sect_start = (word)GC_heap_sects[i].hs_start;
336 word sect_end = sect_start + GC_heap_sects[i].hs_bytes;
337 if (sect_start < least_ha) least_ha = sect_start;
338 if (sect_end > greatest_ha) greatest_ha = sect_end;
340 if (greatest_ha < (word)GC_scratch_last_end_ptr)
341 greatest_ha = (word)GC_scratch_last_end_ptr;
343 for (;;) {
344 buf_ptr = GC_parse_map_entry(buf_ptr, &start, &end, prot_buf, &maj_dev);
345 if (buf_ptr == NULL) return 1;
346 if (prot_buf[1] == 'w') {
347 /* This is a writable mapping. Add it to */
348 /* the root set unless it is already otherwise */
349 /* accounted for. */
350 if (start <= (word)GC_stackbottom && end >= (word)GC_stackbottom) {
351 /* Stack mapping; discard */
352 continue;
354 # ifdef THREADS
355 if (GC_segment_is_thread_stack(start, end)) continue;
356 # endif
357 /* We no longer exclude the main data segment. */
358 if (start < least_ha && end > least_ha) {
359 end = least_ha;
361 if (start < greatest_ha && end > greatest_ha) {
362 start = greatest_ha;
364 if (start >= least_ha && end <= greatest_ha) continue;
365 GC_add_roots_inner((char *)start, (char *)end, TRUE);
368 return 1;
371 void GC_register_dynamic_libraries()
373 if (!GC_apply_to_maps(GC_register_map_entries))
374 ABORT("Failed to read /proc for library registration.");
377 /* We now take care of the main data segment ourselves: */
378 GC_bool GC_register_main_static_data()
380 return FALSE;
383 # define HAVE_REGISTER_MAIN_STATIC_DATA
385 #endif /* USE_PROC_FOR_LIBRARIES */
387 #if !defined(USE_PROC_FOR_LIBRARIES)
388 /* The following is the preferred way to walk dynamic libraries */
389 /* For glibc 2.2.4+. Unfortunately, it doesn't work for older */
390 /* versions. Thanks to Jakub Jelinek for most of the code. */
392 # if defined(LINUX) /* Are others OK here, too? */ \
393 && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) \
394 || (__GLIBC__ == 2 && __GLIBC_MINOR__ == 2 && defined(DT_CONFIG)))
396 /* We have the header files for a glibc that includes dl_iterate_phdr. */
397 /* It may still not be available in the library on the target system. */
398 /* Thus we also treat it as a weak symbol. */
399 #define HAVE_DL_ITERATE_PHDR
401 static int GC_register_dynlib_callback(info, size, ptr)
402 struct dl_phdr_info * info;
403 size_t size;
404 void * ptr;
406 const ElfW(Phdr) * p;
407 char * start;
408 register int i;
410 /* Make sure struct dl_phdr_info is at least as big as we need. */
411 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
412 + sizeof (info->dlpi_phnum))
413 return -1;
415 p = info->dlpi_phdr;
416 for( i = 0; i < (int)(info->dlpi_phnum); ((i++),(p++)) ) {
417 switch( p->p_type ) {
418 case PT_LOAD:
420 if( !(p->p_flags & PF_W) ) break;
421 start = ((char *)(p->p_vaddr)) + info->dlpi_addr;
422 GC_add_roots_inner(start, start + p->p_memsz, TRUE);
424 break;
425 default:
426 break;
430 * (int *)ptr = 1; /* Signal that we were called */
431 return 0;
434 /* Return TRUE if we succeed, FALSE if dl_iterate_phdr wasn't there. */
436 #pragma weak dl_iterate_phdr
438 GC_bool GC_register_dynamic_libraries_dl_iterate_phdr()
440 if (dl_iterate_phdr) {
441 int did_something = 0;
442 dl_iterate_phdr(GC_register_dynlib_callback, &did_something);
443 if (!did_something) {
444 /* dl_iterate_phdr may forget the static data segment in */
445 /* statically linked executables. */
446 GC_add_roots_inner(DATASTART, (char *)(DATAEND), TRUE);
447 # if defined(DATASTART2)
448 GC_add_roots_inner(DATASTART2, (char *)(DATAEND2), TRUE);
449 # endif
452 return TRUE;
453 } else {
454 return FALSE;
458 /* Do we need to separately register the main static data segment? */
459 GC_bool GC_register_main_static_data()
461 return (dl_iterate_phdr == 0);
464 #define HAVE_REGISTER_MAIN_STATIC_DATA
466 # else /* !LINUX || version(glibc) < 2.2.4 */
468 /* Dynamic loading code for Linux running ELF. Somewhat tested on
469 * Linux/x86, untested but hopefully should work on Linux/Alpha.
470 * This code was derived from the Solaris/ELF support. Thanks to
471 * whatever kind soul wrote that. - Patrick Bridges */
473 /* This doesn't necessarily work in all cases, e.g. with preloaded
474 * dynamic libraries. */
476 #if defined(NETBSD)
477 # include <sys/exec_elf.h>
478 /* for compatibility with 1.4.x */
479 # ifndef DT_DEBUG
480 # define DT_DEBUG 21
481 # endif
482 # ifndef PT_LOAD
483 # define PT_LOAD 1
484 # endif
485 # ifndef PF_W
486 # define PF_W 2
487 # endif
488 #else
489 # include <elf.h>
490 #endif
491 #include <link.h>
493 # endif
495 #ifdef __GNUC__
496 # pragma weak _DYNAMIC
497 #endif
498 extern ElfW(Dyn) _DYNAMIC[];
500 static struct link_map *
501 GC_FirstDLOpenedLinkMap()
503 ElfW(Dyn) *dp;
504 static struct link_map *cachedResult = 0;
506 if( _DYNAMIC == 0) {
507 return(0);
509 if( cachedResult == 0 ) {
510 int tag;
511 for( dp = _DYNAMIC; (tag = dp->d_tag) != 0; dp++ ) {
512 /* FIXME: The DT_DEBUG header is not mandated by the */
513 /* ELF spec. This code appears to be dependent on */
514 /* idiosynchracies of older GNU tool chains. If this code */
515 /* fails for you, the real problem is probably that it is */
516 /* being used at all. You should be getting the */
517 /* dl_iterate_phdr version. */
518 if( tag == DT_DEBUG ) {
519 struct link_map *lm
520 = ((struct r_debug *)(dp->d_un.d_ptr))->r_map;
521 if( lm != 0 ) cachedResult = lm->l_next; /* might be NIL */
522 break;
526 return cachedResult;
530 void GC_register_dynamic_libraries()
532 struct link_map *lm;
535 # ifdef HAVE_DL_ITERATE_PHDR
536 if (GC_register_dynamic_libraries_dl_iterate_phdr()) {
537 return;
539 # endif
540 lm = GC_FirstDLOpenedLinkMap();
541 for (lm = GC_FirstDLOpenedLinkMap();
542 lm != (struct link_map *) 0; lm = lm->l_next)
544 ElfW(Ehdr) * e;
545 ElfW(Phdr) * p;
546 unsigned long offset;
547 char * start;
548 register int i;
550 e = (ElfW(Ehdr) *) lm->l_addr;
551 if (e == NULL)
552 continue;
554 p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
555 offset = ((unsigned long)(lm->l_addr));
556 for( i = 0; i < (int)(e->e_phnum); ((i++),(p++)) ) {
557 switch( p->p_type ) {
558 case PT_LOAD:
560 if( !(p->p_flags & PF_W) ) break;
561 start = ((char *)(p->p_vaddr)) + offset;
562 GC_add_roots_inner(start, start + p->p_memsz, TRUE);
564 break;
565 default:
566 break;
572 #endif /* !USE_PROC_FOR_LIBRARIES */
574 #endif /* LINUX */
576 #if defined(IRIX5) || (defined(USE_PROC_FOR_LIBRARIES) && !defined(LINUX))
578 #include <sys/procfs.h>
579 #include <sys/stat.h>
580 #include <fcntl.h>
581 #include <elf.h>
582 #include <errno.h>
583 #include <signal.h> /* Only for the following test. */
584 #ifndef _sigargs
585 # define IRIX6
586 #endif
588 extern void * GC_roots_present();
589 /* The type is a lie, since the real type doesn't make sense here, */
590 /* and we only test for NULL. */
593 /* We use /proc to track down all parts of the address space that are */
594 /* mapped by the process, and throw out regions we know we shouldn't */
595 /* worry about. This may also work under other SVR4 variants. */
596 void GC_register_dynamic_libraries()
598 static int fd = -1;
599 char buf[30];
600 static prmap_t * addr_map = 0;
601 static int current_sz = 0; /* Number of records currently in addr_map */
602 static int needed_sz; /* Required size of addr_map */
603 register int i;
604 register long flags;
605 register ptr_t start;
606 register ptr_t limit;
607 ptr_t heap_start = (ptr_t)HEAP_START;
608 ptr_t heap_end = heap_start;
610 # ifdef SUNOS5DL
611 # define MA_PHYS 0
612 # endif /* SUNOS5DL */
614 if (fd < 0) {
615 sprintf(buf, "/proc/%d", getpid());
616 /* The above generates a lint complaint, since pid_t varies. */
617 /* It's unclear how to improve this. */
618 fd = open(buf, O_RDONLY);
619 if (fd < 0) {
620 ABORT("/proc open failed");
623 if (ioctl(fd, PIOCNMAP, &needed_sz) < 0) {
624 GC_err_printf2("fd = %d, errno = %d\n", fd, errno);
625 ABORT("/proc PIOCNMAP ioctl failed");
627 if (needed_sz >= current_sz) {
628 current_sz = needed_sz * 2 + 1;
629 /* Expansion, plus room for 0 record */
630 addr_map = (prmap_t *)GC_scratch_alloc((word)
631 (current_sz * sizeof(prmap_t)));
633 if (ioctl(fd, PIOCMAP, addr_map) < 0) {
634 GC_err_printf4("fd = %d, errno = %d, needed_sz = %d, addr_map = 0x%X\n",
635 fd, errno, needed_sz, addr_map);
636 ABORT("/proc PIOCMAP ioctl failed");
638 if (GC_n_heap_sects > 0) {
639 heap_end = GC_heap_sects[GC_n_heap_sects-1].hs_start
640 + GC_heap_sects[GC_n_heap_sects-1].hs_bytes;
641 if (heap_end < GC_scratch_last_end_ptr) heap_end = GC_scratch_last_end_ptr;
643 for (i = 0; i < needed_sz; i++) {
644 flags = addr_map[i].pr_mflags;
645 if ((flags & (MA_BREAK | MA_STACK | MA_PHYS
646 | MA_FETCHOP | MA_NOTCACHED)) != 0) goto irrelevant;
647 if ((flags & (MA_READ | MA_WRITE)) != (MA_READ | MA_WRITE))
648 goto irrelevant;
649 /* The latter test is empirically useless in very old Irix */
650 /* versions. Other than the */
651 /* main data and stack segments, everything appears to be */
652 /* mapped readable, writable, executable, and shared(!!). */
653 /* This makes no sense to me. - HB */
654 start = (ptr_t)(addr_map[i].pr_vaddr);
655 if (GC_roots_present(start)) goto irrelevant;
656 if (start < heap_end && start >= heap_start)
657 goto irrelevant;
658 # ifdef MMAP_STACKS
659 if (GC_is_thread_stack(start)) goto irrelevant;
660 # endif /* MMAP_STACKS */
662 limit = start + addr_map[i].pr_size;
663 /* The following seemed to be necessary for very old versions */
664 /* of Irix, but it has been reported to discard relevant */
665 /* segments under Irix 6.5. */
666 # ifndef IRIX6
667 if (addr_map[i].pr_off == 0 && strncmp(start, ELFMAG, 4) == 0) {
668 /* Discard text segments, i.e. 0-offset mappings against */
669 /* executable files which appear to have ELF headers. */
670 caddr_t arg;
671 int obj;
672 # define MAP_IRR_SZ 10
673 static ptr_t map_irr[MAP_IRR_SZ];
674 /* Known irrelevant map entries */
675 static int n_irr = 0;
676 struct stat buf;
677 register int i;
679 for (i = 0; i < n_irr; i++) {
680 if (map_irr[i] == start) goto irrelevant;
682 arg = (caddr_t)start;
683 obj = ioctl(fd, PIOCOPENM, &arg);
684 if (obj >= 0) {
685 fstat(obj, &buf);
686 close(obj);
687 if ((buf.st_mode & 0111) != 0) {
688 if (n_irr < MAP_IRR_SZ) {
689 map_irr[n_irr++] = start;
691 goto irrelevant;
695 # endif /* !IRIX6 */
696 GC_add_roots_inner(start, limit, TRUE);
697 irrelevant: ;
699 /* Dont keep cached descriptor, for now. Some kernels don't like us */
700 /* to keep a /proc file descriptor around during kill -9. */
701 if (close(fd) < 0) ABORT("Couldnt close /proc file");
702 fd = -1;
705 # endif /* USE_PROC || IRIX5 */
707 # if defined(MSWIN32) || defined(MSWINCE)
709 # define WIN32_LEAN_AND_MEAN
710 # define NOSERVICE
711 # include <windows.h>
712 # include <stdlib.h>
714 /* We traverse the entire address space and register all segments */
715 /* that could possibly have been written to. */
717 extern GC_bool GC_is_heap_base (ptr_t p);
719 # ifdef GC_WIN32_THREADS
720 extern void GC_get_next_stack(char *start, char **lo, char **hi);
721 void GC_cond_add_roots(char *base, char * limit)
723 char * curr_base = base;
724 char * next_stack_lo;
725 char * next_stack_hi;
727 if (base == limit) return;
728 for(;;) {
729 GC_get_next_stack(curr_base, &next_stack_lo, &next_stack_hi);
730 if (next_stack_lo >= limit) break;
731 GC_add_roots_inner(curr_base, next_stack_lo, TRUE);
732 curr_base = next_stack_hi;
734 if (curr_base < limit) GC_add_roots_inner(curr_base, limit, TRUE);
736 # else
737 void GC_cond_add_roots(char *base, char * limit)
739 char dummy;
740 char * stack_top
741 = (char *) ((word)(&dummy) & ~(GC_sysinfo.dwAllocationGranularity-1));
742 if (base == limit) return;
743 if (limit > stack_top && base < GC_stackbottom) {
744 /* Part of the stack; ignore it. */
745 return;
747 GC_add_roots_inner(base, limit, TRUE);
749 # endif
751 # ifdef MSWINCE
752 /* Do we need to separately register the main static data segment? */
753 GC_bool GC_register_main_static_data()
755 return FALSE;
757 # else /* win32 */
758 extern GC_bool GC_no_win32_dlls;
760 GC_bool GC_register_main_static_data()
762 return GC_no_win32_dlls;
764 # endif /* win32 */
766 # define HAVE_REGISTER_MAIN_STATIC_DATA
768 /* The frame buffer testing code is dead in this version. */
769 /* We leave it here temporarily in case the switch to just */
770 /* testing for MEM_IMAGE sections causes un expected */
771 /* problems. */
772 GC_bool GC_warn_fb = TRUE; /* Warn about traced likely */
773 /* graphics memory. */
774 GC_bool GC_disallow_ignore_fb = FALSE;
775 int GC_ignore_fb_mb; /* Ignore mappings bigger than the */
776 /* specified number of MB. */
777 GC_bool GC_ignore_fb = FALSE; /* Enable frame buffer */
778 /* checking. */
780 /* Issue warning if tracing apparent framebuffer. */
781 /* This limits us to one warning, and it's a back door to */
782 /* disable that. */
784 /* Should [start, start+len) be treated as a frame buffer */
785 /* and ignored? */
786 /* Unfortunately, we currently are not quite sure how to tell */
787 /* this automatically, and rely largely on user input. */
788 /* We expect that any mapping with type MEM_MAPPED (which */
789 /* apparently excludes library data sections) can be safely */
790 /* ignored. But we're too chicken to do that in this */
791 /* version. */
792 /* Based on a very limited sample, it appears that: */
793 /* - Frame buffer mappings appear as mappings of large */
794 /* length, usually a bit less than a power of two. */
795 /* - The definition of "a bit less" in the above cannot */
796 /* be made more precise. */
797 /* - Have a starting address at best 64K aligned. */
798 /* - Have type == MEM_MAPPED. */
799 static GC_bool is_frame_buffer(ptr_t start, size_t len, DWORD tp)
801 static GC_bool initialized = FALSE;
802 # define MB (1024*1024)
803 # define DEFAULT_FB_MB 15
804 # define MIN_FB_MB 3
806 if (GC_disallow_ignore_fb || tp != MEM_MAPPED) return FALSE;
807 if (!initialized) {
808 char * ignore_fb_string = GETENV("GC_IGNORE_FB");
810 if (0 != ignore_fb_string) {
811 while (*ignore_fb_string == ' ' || *ignore_fb_string == '\t')
812 ++ignore_fb_string;
813 if (*ignore_fb_string == '\0') {
814 GC_ignore_fb_mb = DEFAULT_FB_MB;
815 } else {
816 GC_ignore_fb_mb = atoi(ignore_fb_string);
817 if (GC_ignore_fb_mb < MIN_FB_MB) {
818 WARN("Bad GC_IGNORE_FB value. Using %ld\n", DEFAULT_FB_MB);
819 GC_ignore_fb_mb = DEFAULT_FB_MB;
822 GC_ignore_fb = TRUE;
823 } else {
824 GC_ignore_fb_mb = DEFAULT_FB_MB; /* For warning */
826 initialized = TRUE;
828 if (len >= ((size_t)GC_ignore_fb_mb << 20)) {
829 if (GC_ignore_fb) {
830 return TRUE;
831 } else {
832 if (GC_warn_fb) {
833 WARN("Possible frame buffer mapping at 0x%lx: \n"
834 "\tConsider setting GC_IGNORE_FB to improve performance.\n",
835 start);
836 GC_warn_fb = FALSE;
838 return FALSE;
840 } else {
841 return FALSE;
845 # ifdef DEBUG_VIRTUALQUERY
846 void GC_dump_meminfo(MEMORY_BASIC_INFORMATION *buf)
848 GC_printf4("BaseAddress = %lx, AllocationBase = %lx, RegionSize = %lx(%lu)\n",
849 buf -> BaseAddress, buf -> AllocationBase, buf -> RegionSize,
850 buf -> RegionSize);
851 GC_printf4("\tAllocationProtect = %lx, State = %lx, Protect = %lx, "
852 "Type = %lx\n",
853 buf -> AllocationProtect, buf -> State, buf -> Protect,
854 buf -> Type);
856 # endif /* DEBUG_VIRTUALQUERY */
858 void GC_register_dynamic_libraries()
860 MEMORY_BASIC_INFORMATION buf;
861 DWORD result;
862 DWORD protect;
863 LPVOID p;
864 char * base;
865 char * limit, * new_limit;
867 # ifdef MSWIN32
868 if (GC_no_win32_dlls) return;
869 # endif
870 base = limit = p = GC_sysinfo.lpMinimumApplicationAddress;
871 # if defined(MSWINCE) && !defined(_WIN32_WCE_EMULATION)
872 /* Only the first 32 MB of address space belongs to the current process */
873 while (p < (LPVOID)0x02000000) {
874 result = VirtualQuery(p, &buf, sizeof(buf));
875 if (result == 0) {
876 /* Page is free; advance to the next possible allocation base */
877 new_limit = (char *)
878 (((DWORD) p + GC_sysinfo.dwAllocationGranularity)
879 & ~(GC_sysinfo.dwAllocationGranularity-1));
880 } else
881 # else
882 while (p < GC_sysinfo.lpMaximumApplicationAddress) {
883 result = VirtualQuery(p, &buf, sizeof(buf));
884 # endif
886 if (result != sizeof(buf)) {
887 ABORT("Weird VirtualQuery result");
889 new_limit = (char *)p + buf.RegionSize;
890 protect = buf.Protect;
891 if (buf.State == MEM_COMMIT
892 && (protect == PAGE_EXECUTE_READWRITE
893 || protect == PAGE_READWRITE)
894 && !GC_is_heap_base(buf.AllocationBase)
895 /* This used to check for
896 * !is_frame_buffer(p, buf.RegionSize, buf.Type)
897 * instead of just checking for MEM_IMAGE.
898 * If something breaks, change it back. */
899 && buf.Type == MEM_IMAGE) {
900 # ifdef DEBUG_VIRTUALQUERY
901 GC_dump_meminfo(&buf);
902 # endif
903 if ((char *)p != limit) {
904 GC_cond_add_roots(base, limit);
905 base = p;
907 limit = new_limit;
910 if (p > (LPVOID)new_limit /* overflow */) break;
911 p = (LPVOID)new_limit;
913 GC_cond_add_roots(base, limit);
916 #endif /* MSWIN32 || MSWINCE */
918 #if defined(ALPHA) && defined(OSF1)
920 #include <loader.h>
922 void GC_register_dynamic_libraries()
924 int status;
925 ldr_process_t mypid;
927 /* module */
928 ldr_module_t moduleid = LDR_NULL_MODULE;
929 ldr_module_info_t moduleinfo;
930 size_t moduleinfosize = sizeof(moduleinfo);
931 size_t modulereturnsize;
933 /* region */
934 ldr_region_t region;
935 ldr_region_info_t regioninfo;
936 size_t regioninfosize = sizeof(regioninfo);
937 size_t regionreturnsize;
939 /* Obtain id of this process */
940 mypid = ldr_my_process();
942 /* For each module */
943 while (TRUE) {
945 /* Get the next (first) module */
946 status = ldr_next_module(mypid, &moduleid);
948 /* Any more modules? */
949 if (moduleid == LDR_NULL_MODULE)
950 break; /* No more modules */
952 /* Check status AFTER checking moduleid because */
953 /* of a bug in the non-shared ldr_next_module stub */
954 if (status != 0 ) {
955 GC_printf1("dynamic_load: status = %ld\n", (long)status);
957 extern char *sys_errlist[];
958 extern int sys_nerr;
959 extern int errno;
960 if (errno <= sys_nerr) {
961 GC_printf1("dynamic_load: %s\n", (long)sys_errlist[errno]);
962 } else {
963 GC_printf1("dynamic_load: %d\n", (long)errno);
966 ABORT("ldr_next_module failed");
969 /* Get the module information */
970 status = ldr_inq_module(mypid, moduleid, &moduleinfo,
971 moduleinfosize, &modulereturnsize);
972 if (status != 0 )
973 ABORT("ldr_inq_module failed");
975 /* is module for the main program (i.e. nonshared portion)? */
976 if (moduleinfo.lmi_flags & LDR_MAIN)
977 continue; /* skip the main module */
979 # ifdef VERBOSE
980 GC_printf("---Module---\n");
981 GC_printf("Module ID = %16ld\n", moduleinfo.lmi_modid);
982 GC_printf("Count of regions = %16d\n", moduleinfo.lmi_nregion);
983 GC_printf("flags for module = %16lx\n", moduleinfo.lmi_flags);
984 GC_printf("pathname of module = \"%s\"\n", moduleinfo.lmi_name);
985 # endif
987 /* For each region in this module */
988 for (region = 0; region < moduleinfo.lmi_nregion; region++) {
990 /* Get the region information */
991 status = ldr_inq_region(mypid, moduleid, region, &regioninfo,
992 regioninfosize, &regionreturnsize);
993 if (status != 0 )
994 ABORT("ldr_inq_region failed");
996 /* only process writable (data) regions */
997 if (! (regioninfo.lri_prot & LDR_W))
998 continue;
1000 # ifdef VERBOSE
1001 GC_printf("--- Region ---\n");
1002 GC_printf("Region number = %16ld\n",
1003 regioninfo.lri_region_no);
1004 GC_printf("Protection flags = %016x\n", regioninfo.lri_prot);
1005 GC_printf("Virtual address = %16p\n", regioninfo.lri_vaddr);
1006 GC_printf("Mapped address = %16p\n", regioninfo.lri_mapaddr);
1007 GC_printf("Region size = %16ld\n", regioninfo.lri_size);
1008 GC_printf("Region name = \"%s\"\n", regioninfo.lri_name);
1009 # endif
1011 /* register region as a garbage collection root */
1012 GC_add_roots_inner (
1013 (char *)regioninfo.lri_mapaddr,
1014 (char *)regioninfo.lri_mapaddr + regioninfo.lri_size,
1015 TRUE);
1020 #endif
1022 #if defined(HPUX)
1024 #include <errno.h>
1025 #include <dl.h>
1027 extern int errno;
1028 extern char *sys_errlist[];
1029 extern int sys_nerr;
1031 void GC_register_dynamic_libraries()
1033 int status;
1034 int index = 1; /* Ordinal position in shared library search list */
1035 struct shl_descriptor *shl_desc; /* Shared library info, see dl.h */
1037 /* For each dynamic library loaded */
1038 while (TRUE) {
1040 /* Get info about next shared library */
1041 status = shl_get(index, &shl_desc);
1043 /* Check if this is the end of the list or if some error occured */
1044 if (status != 0) {
1045 # ifdef GC_HPUX_THREADS
1046 /* I've seen errno values of 0. The man page is not clear */
1047 /* as to whether errno should get set on a -1 return. */
1048 break;
1049 # else
1050 if (errno == EINVAL) {
1051 break; /* Moved past end of shared library list --> finished */
1052 } else {
1053 if (errno <= sys_nerr) {
1054 GC_printf1("dynamic_load: %s\n", (long) sys_errlist[errno]);
1055 } else {
1056 GC_printf1("dynamic_load: %d\n", (long) errno);
1058 ABORT("shl_get failed");
1060 # endif
1063 # ifdef VERBOSE
1064 GC_printf0("---Shared library---\n");
1065 GC_printf1("\tfilename = \"%s\"\n", shl_desc->filename);
1066 GC_printf1("\tindex = %d\n", index);
1067 GC_printf1("\thandle = %08x\n",
1068 (unsigned long) shl_desc->handle);
1069 GC_printf1("\ttext seg. start = %08x\n", shl_desc->tstart);
1070 GC_printf1("\ttext seg. end = %08x\n", shl_desc->tend);
1071 GC_printf1("\tdata seg. start = %08x\n", shl_desc->dstart);
1072 GC_printf1("\tdata seg. end = %08x\n", shl_desc->dend);
1073 GC_printf1("\tref. count = %lu\n", shl_desc->ref_count);
1074 # endif
1076 /* register shared library's data segment as a garbage collection root */
1077 GC_add_roots_inner((char *) shl_desc->dstart,
1078 (char *) shl_desc->dend, TRUE);
1080 index++;
1083 #endif /* HPUX */
1085 #ifdef RS6000
1086 #pragma alloca
1087 #include <sys/ldr.h>
1088 #include <sys/errno.h>
1089 void GC_register_dynamic_libraries()
1091 int len;
1092 char *ldibuf;
1093 int ldibuflen;
1094 struct ld_info *ldi;
1096 ldibuf = alloca(ldibuflen = 8192);
1098 while ( (len = loadquery(L_GETINFO,ldibuf,ldibuflen)) < 0) {
1099 if (errno != ENOMEM) {
1100 ABORT("loadquery failed");
1102 ldibuf = alloca(ldibuflen *= 2);
1105 ldi = (struct ld_info *)ldibuf;
1106 while (ldi) {
1107 len = ldi->ldinfo_next;
1108 GC_add_roots_inner(
1109 ldi->ldinfo_dataorg,
1110 (ptr_t)(unsigned long)ldi->ldinfo_dataorg
1111 + ldi->ldinfo_datasize,
1112 TRUE);
1113 ldi = len ? (struct ld_info *)((char *)ldi + len) : 0;
1116 #endif /* RS6000 */
1118 #ifdef DARWIN
1120 /* __private_extern__ hack required for pre-3.4 gcc versions. */
1121 #ifndef __private_extern__
1122 # define __private_extern__ extern
1123 # include <mach-o/dyld.h>
1124 # undef __private_extern__
1125 #else
1126 # include <mach-o/dyld.h>
1127 #endif
1128 #include <mach-o/getsect.h>
1130 /*#define DARWIN_DEBUG*/
1132 const static struct {
1133 const char *seg;
1134 const char *sect;
1135 } GC_dyld_sections[] = {
1136 { SEG_DATA, SECT_DATA },
1137 { SEG_DATA, SECT_BSS },
1138 { SEG_DATA, SECT_COMMON }
1141 #ifdef DARWIN_DEBUG
1142 static const char *GC_dyld_name_for_hdr(struct mach_header *hdr) {
1143 unsigned long i,c;
1144 c = _dyld_image_count();
1145 for(i=0;i<c;i++) if(_dyld_get_image_header(i) == hdr)
1146 return _dyld_get_image_name(i);
1147 return NULL;
1149 #endif
1151 /* This should never be called by a thread holding the lock */
1152 static void GC_dyld_image_add(struct mach_header* hdr, unsigned long slide) {
1153 unsigned long start,end,i;
1154 const struct section *sec;
1155 if (GC_no_dls) return;
1156 for(i=0;i<sizeof(GC_dyld_sections)/sizeof(GC_dyld_sections[0]);i++) {
1157 sec = getsectbynamefromheader(
1158 hdr,GC_dyld_sections[i].seg,GC_dyld_sections[i].sect);
1159 if(sec == NULL || sec->size == 0) continue;
1160 start = slide + sec->addr;
1161 end = start + sec->size;
1162 # ifdef DARWIN_DEBUG
1163 GC_printf4("Adding section at %p-%p (%lu bytes) from image %s\n",
1164 start,end,sec->size,GC_dyld_name_for_hdr(hdr));
1165 # endif
1166 GC_add_roots((char*)start,(char*)end);
1168 # ifdef DARWIN_DEBUG
1169 GC_print_static_roots();
1170 # endif
1173 /* This should never be called by a thread holding the lock */
1174 static void GC_dyld_image_remove(struct mach_header* hdr, unsigned long slide) {
1175 unsigned long start,end,i;
1176 const struct section *sec;
1177 for(i=0;i<sizeof(GC_dyld_sections)/sizeof(GC_dyld_sections[0]);i++) {
1178 sec = getsectbynamefromheader(
1179 hdr,GC_dyld_sections[i].seg,GC_dyld_sections[i].sect);
1180 if(sec == NULL || sec->size == 0) continue;
1181 start = slide + sec->addr;
1182 end = start + sec->size;
1183 # ifdef DARWIN_DEBUG
1184 GC_printf4("Removing section at %p-%p (%lu bytes) from image %s\n",
1185 start,end,sec->size,GC_dyld_name_for_hdr(hdr));
1186 # endif
1187 GC_remove_roots((char*)start,(char*)end);
1189 # ifdef DARWIN_DEBUG
1190 GC_print_static_roots();
1191 # endif
1194 void GC_register_dynamic_libraries() {
1195 /* Currently does nothing. The callbacks are setup by GC_init_dyld()
1196 The dyld library takes it from there. */
1199 /* The _dyld_* functions have an internal lock so no _dyld functions
1200 can be called while the world is stopped without the risk of a deadlock.
1201 Because of this we MUST setup callbacks BEFORE we ever stop the world.
1202 This should be called BEFORE any thread in created and WITHOUT the
1203 allocation lock held. */
1205 void GC_init_dyld() {
1206 static GC_bool initialized = FALSE;
1207 char *bind_fully_env = NULL;
1209 if(initialized) return;
1211 # ifdef DARWIN_DEBUG
1212 GC_printf0("Registering dyld callbacks...\n");
1213 # endif
1215 /* Apple's Documentation:
1216 When you call _dyld_register_func_for_add_image, the dynamic linker runtime
1217 calls the specified callback (func) once for each of the images that is
1218 currently loaded into the program. When a new image is added to the program,
1219 your callback is called again with the mach_header for the new image, and the
1220 virtual memory slide amount of the new image.
1222 This WILL properly register already linked libraries and libraries
1223 linked in the future
1226 _dyld_register_func_for_add_image(GC_dyld_image_add);
1227 _dyld_register_func_for_remove_image(GC_dyld_image_remove);
1229 /* Set this early to avoid reentrancy issues. */
1230 initialized = TRUE;
1232 bind_fully_env = getenv("DYLD_BIND_AT_LAUNCH");
1234 if (bind_fully_env == NULL) {
1235 # ifdef DARWIN_DEBUG
1236 GC_printf0("Forcing full bind of GC code...\n");
1237 # endif
1239 if(!_dyld_bind_fully_image_containing_address((unsigned long*)GC_malloc))
1240 GC_abort("_dyld_bind_fully_image_containing_address failed");
1245 #define HAVE_REGISTER_MAIN_STATIC_DATA
1246 GC_bool GC_register_main_static_data()
1248 /* Already done through dyld callbacks */
1249 return FALSE;
1252 #endif /* DARWIN */
1254 #else /* !DYNAMIC_LOADING */
1256 #ifdef PCR
1258 # include "il/PCR_IL.h"
1259 # include "th/PCR_ThCtl.h"
1260 # include "mm/PCR_MM.h"
1262 void GC_register_dynamic_libraries()
1264 /* Add new static data areas of dynamically loaded modules. */
1266 PCR_IL_LoadedFile * p = PCR_IL_GetLastLoadedFile();
1267 PCR_IL_LoadedSegment * q;
1269 /* Skip uncommited files */
1270 while (p != NIL && !(p -> lf_commitPoint)) {
1271 /* The loading of this file has not yet been committed */
1272 /* Hence its description could be inconsistent. */
1273 /* Furthermore, it hasn't yet been run. Hence its data */
1274 /* segments can't possibly reference heap allocated */
1275 /* objects. */
1276 p = p -> lf_prev;
1278 for (; p != NIL; p = p -> lf_prev) {
1279 for (q = p -> lf_ls; q != NIL; q = q -> ls_next) {
1280 if ((q -> ls_flags & PCR_IL_SegFlags_Traced_MASK)
1281 == PCR_IL_SegFlags_Traced_on) {
1282 GC_add_roots_inner
1283 ((char *)(q -> ls_addr),
1284 (char *)(q -> ls_addr) + q -> ls_bytes,
1285 TRUE);
1293 #else /* !PCR */
1295 void GC_register_dynamic_libraries(){}
1297 int GC_no_dynamic_loading;
1299 #endif /* !PCR */
1301 #endif /* !DYNAMIC_LOADING */
1303 #ifndef HAVE_REGISTER_MAIN_STATIC_DATA
1305 /* Do we need to separately register the main static data segment? */
1306 GC_bool GC_register_main_static_data()
1308 return TRUE;
1310 #endif /* HAVE_REGISTER_MAIN_STATIC_DATA */