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.
30 # include <sys/types.h>
34 /* BTL: avoid circular redefinition of dlopen if SOLARIS_THREADS defined */
35 # if defined(SOLARIS_THREADS) && defined(dlopen)
36 /* To support threads in Solaris, gc.h interposes on dlopen by */
37 /* defining "dlopen" to be "GC_dlopen", which is implemented below. */
38 /* However, both GC_FirstDLOpenedLinkMap() and GC_dlopen() use the */
39 /* real system dlopen() in their implementation. We first remove */
40 /* gc.h's dlopen definition and restore it later, after GC_dlopen(). */
42 # define GC_must_restore_redefined_dlopen
44 # undef GC_must_restore_redefined_dlopen
47 #if (defined(DYNAMIC_LOADING) || defined(MSWIN32)) && !defined(PCR)
48 #if !defined(SUNOS4) && !defined(SUNOS5DL) && !defined(IRIX5) && \
49 !defined(MSWIN32) && !(defined(ALPHA) && defined(OSF1)) && \
50 !defined(HP_PA) && (!defined(LINUX) && !defined(__ELF__)) && \
51 !defined(RS6000) && !defined(SCO_ELF)
52 --> We only know how to find data segments of dynamic libraries for the
53 --> above. Additional SVR4 variants might not be too
67 /* struct link_map field overrides */
68 # define l_next lm_next
69 # define l_addr lm_addr
70 # define l_name lm_name
74 #if defined(SUNOS5DL) && !defined(USE_PROC_FOR_LIBRARIES)
80 static struct link_map *
81 GC_FirstDLOpenedLinkMap()
83 extern Elf32_Dyn _DYNAMIC;
86 static struct link_map * cachedResult = 0;
87 static Elf32_Dyn *dynStructureAddr = 0;
88 /* BTL: added to avoid Solaris 5.3 ld.so _DYNAMIC bug */
90 # ifdef SUNOS53_SHARED_LIB
91 /* BTL: Avoid the Solaris 5.3 bug that _DYNAMIC isn't being set */
92 /* up properly in dynamically linked .so's. This means we have */
93 /* to use its value in the set of original object files loaded */
94 /* at program startup. */
95 if( dynStructureAddr == 0 ) {
96 void* startupSyms = dlopen(0, RTLD_LAZY);
97 dynStructureAddr = (Elf32_Dyn*)dlsym(startupSyms, "_DYNAMIC");
100 dynStructureAddr = &_DYNAMIC;
103 if( dynStructureAddr == 0) {
106 if( cachedResult == 0 ) {
108 for( dp = ((Elf32_Dyn *)(&_DYNAMIC)); (tag = dp->d_tag) != 0; dp++ ) {
109 if( tag == DT_DEBUG ) {
111 = ((struct r_debug *)(dp->d_un.d_ptr))->r_map;
112 if( lm != 0 ) cachedResult = lm->l_next; /* might be NIL */
120 #endif /* SUNOS5DL ... */
122 #if defined(SUNOS4) && !defined(USE_PROC_FOR_LIBRARIES)
125 struct link_dynamic _DYNAMIC;
128 static struct link_map *
129 GC_FirstDLOpenedLinkMap()
131 extern struct link_dynamic _DYNAMIC;
133 if( &_DYNAMIC == 0) {
136 return(_DYNAMIC.ld_un.ld_1->ld_loaded);
139 /* Return the address of the ld.so allocated common symbol */
140 /* with the least address, or 0 if none. */
141 static ptr_t GC_first_common()
144 extern struct link_dynamic _DYNAMIC;
145 struct rtc_symb * curr_symbol;
147 if( &_DYNAMIC == 0) {
150 curr_symbol = _DYNAMIC.ldd -> ldd_cp;
151 for (; curr_symbol != 0; curr_symbol = curr_symbol -> rtc_next) {
153 || (ptr_t)(curr_symbol -> rtc_sp -> n_value) < result) {
154 result = (ptr_t)(curr_symbol -> rtc_sp -> n_value);
160 #endif /* SUNOS4 ... */
162 # if defined(SUNOS4) || defined(SUNOS5DL)
163 /* Add dynamic library data sections to the root set. */
164 # if !defined(PCR) && !defined(SOLARIS_THREADS) && defined(THREADS)
166 --> fix mutual exclusion with dlopen
167 # endif /* We assume M3 programs don't call dlopen for now */
170 # ifdef SOLARIS_THREADS
171 /* Redefine dlopen to guarantee mutual exclusion with */
172 /* GC_register_dynamic_libraries. */
173 /* assumes that dlopen doesn't need to call GC_malloc */
178 void * GC_dlopen(const char *path, int mode)
182 # ifndef USE_PROC_FOR_LIBRARIES
183 mutex_lock(&GC_allocate_ml);
185 result = dlopen(path, mode);
186 # ifndef USE_PROC_FOR_LIBRARIES
187 mutex_unlock(&GC_allocate_ml);
191 # endif /* SOLARIS_THREADS */
193 /* BTL: added to fix circular dlopen definition if SOLARIS_THREADS defined */
194 # if defined(GC_must_restore_redefined_dlopen)
195 # define dlopen GC_dlopen
198 # ifndef USE_PROC_FOR_LIBRARIES
199 void GC_register_dynamic_libraries()
201 struct link_map *lm = GC_FirstDLOpenedLinkMap();
204 for (lm = GC_FirstDLOpenedLinkMap();
205 lm != (struct link_map *) 0; lm = lm->l_next)
210 e = (struct exec *) lm->lm_addr;
212 ((char *) (N_DATOFF(*e) + lm->lm_addr)),
213 ((char *) (N_BSSADDR(*e) + e->a_bss + lm->lm_addr)),
219 unsigned long offset;
223 e = (Elf32_Ehdr *) lm->l_addr;
224 p = ((Elf32_Phdr *)(((char *)(e)) + e->e_phoff));
225 offset = ((unsigned long)(lm->l_addr));
226 for( i = 0; i < (int)(e->e_phnum); ((i++),(p++)) ) {
227 switch( p->p_type ) {
230 if( !(p->p_flags & PF_W) ) break;
231 start = ((char *)(p->p_vaddr)) + offset;
247 static ptr_t common_start = 0;
249 extern ptr_t GC_find_limit();
251 if (common_start == 0) common_start = GC_first_common();
252 if (common_start != 0) {
253 common_end = GC_find_limit(common_start, TRUE);
254 GC_add_roots_inner((char *)common_start, (char *)common_end, TRUE);
260 # endif /* !USE_PROC ... */
263 #if defined(LINUX) && defined(__ELF__) || defined(SCO_ELF)
265 /* Dynamic loading code for Linux running ELF. Somewhat tested on
266 * Linux/x86, untested but hopefully should work on Linux/Alpha.
267 * This code was derived from the Solaris/ELF support. Thanks to
268 * whatever kind soul wrote that. - Patrick Bridges */
273 /* Newer versions of Linux/Alpha and Linux/x86 define this macro. We
274 * define it for those older versions that don't. */
276 # if !defined(ELF_CLASS) || ELF_CLASS == ELFCLASS32
277 # define ElfW(type) Elf32_##type
279 # define ElfW(type) Elf64_##type
283 static struct link_map *
284 GC_FirstDLOpenedLinkMap()
286 extern ElfW(Dyn) _DYNAMIC[];
289 static struct link_map *cachedResult = 0;
294 if( cachedResult == 0 ) {
296 for( dp = _DYNAMIC; (tag = dp->d_tag) != 0; dp++ ) {
297 if( tag == DT_DEBUG ) {
299 = ((struct r_debug *)(dp->d_un.d_ptr))->r_map;
300 if( lm != 0 ) cachedResult = lm->l_next; /* might be NIL */
309 void GC_register_dynamic_libraries()
311 struct link_map *lm = GC_FirstDLOpenedLinkMap();
314 for (lm = GC_FirstDLOpenedLinkMap();
315 lm != (struct link_map *) 0; lm = lm->l_next)
319 unsigned long offset;
323 e = (ElfW(Ehdr) *) lm->l_addr;
324 p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
325 offset = ((unsigned long)(lm->l_addr));
326 for( i = 0; i < (int)(e->e_phnum); ((i++),(p++)) ) {
327 switch( p->p_type ) {
330 if( !(p->p_flags & PF_W) ) break;
331 start = ((char *)(p->p_vaddr)) + offset;
332 GC_add_roots_inner(start, start + p->p_memsz, TRUE);
344 #if defined(IRIX5) || defined(USE_PROC_FOR_LIBRARIES)
346 #include <sys/procfs.h>
347 #include <sys/stat.h>
352 extern void * GC_roots_present();
354 extern ptr_t GC_scratch_last_end_ptr; /* End of GC_scratch_alloc arena */
356 /* We use /proc to track down all parts of the address space that are */
357 /* mapped by the process, and throw out regions we know we shouldn't */
358 /* worry about. This may also work under other SVR4 variants. */
359 void GC_register_dynamic_libraries()
363 static prmap_t * addr_map = 0;
364 static int current_sz = 0; /* Number of records currently in addr_map */
365 static int needed_sz; /* Required size of addr_map */
368 register ptr_t start;
369 register ptr_t limit;
370 ptr_t heap_start = (ptr_t)HEAP_START;
371 ptr_t heap_end = heap_start;
375 # endif /* SUNOS5DL */
378 sprintf(buf, "/proc/%d", getpid());
379 fd = open(buf, O_RDONLY);
381 ABORT("/proc open failed");
384 if (ioctl(fd, PIOCNMAP, &needed_sz) < 0) {
385 GC_err_printf2("fd = %d, errno = %d\n", fd, errno);
386 ABORT("/proc PIOCNMAP ioctl failed");
388 if (needed_sz >= current_sz) {
389 current_sz = needed_sz * 2 + 1;
390 /* Expansion, plus room for 0 record */
391 addr_map = (prmap_t *)GC_scratch_alloc(current_sz * sizeof(prmap_t));
393 if (ioctl(fd, PIOCMAP, addr_map) < 0) {
394 GC_err_printf4("fd = %d, errno = %d, needed_sz = %d, addr_map = 0x%X\n",
395 fd, errno, needed_sz, addr_map);
396 ABORT("/proc PIOCMAP ioctl failed");
398 if (GC_n_heap_sects > 0) {
399 heap_end = GC_heap_sects[GC_n_heap_sects-1].hs_start
400 + GC_heap_sects[GC_n_heap_sects-1].hs_bytes;
401 if (heap_end < GC_scratch_last_end_ptr) heap_end = GC_scratch_last_end_ptr;
403 for (i = 0; i < needed_sz; i++) {
404 flags = addr_map[i].pr_mflags;
405 if ((flags & (MA_BREAK | MA_STACK | MA_PHYS)) != 0) goto irrelevant;
406 if ((flags & (MA_READ | MA_WRITE)) != (MA_READ | MA_WRITE))
408 /* The latter test is empirically useless. Other than the */
409 /* main data and stack segments, everything appears to be */
410 /* mapped readable, writable, executable, and shared(!!). */
411 /* This makes no sense to me. - HB */
412 start = (ptr_t)(addr_map[i].pr_vaddr);
413 if (GC_roots_present(start)) goto irrelevant;
414 if (start < heap_end && start >= heap_start)
417 if (GC_is_thread_stack(start)) goto irrelevant;
418 # endif /* MMAP_STACKS */
420 limit = start + addr_map[i].pr_size;
421 if (addr_map[i].pr_off == 0 && strncmp(start, ELFMAG, 4) == 0) {
422 /* Discard text segments, i.e. 0-offset mappings against */
423 /* executable files which appear to have ELF headers. */
426 # define MAP_IRR_SZ 10
427 static ptr_t map_irr[MAP_IRR_SZ];
428 /* Known irrelevant map entries */
429 static int n_irr = 0;
433 for (i = 0; i < n_irr; i++) {
434 if (map_irr[i] == start) goto irrelevant;
436 arg = (caddr_t)start;
437 obj = ioctl(fd, PIOCOPENM, &arg);
441 if ((buf.st_mode & 0111) != 0) {
442 if (n_irr < MAP_IRR_SZ) {
443 map_irr[n_irr++] = start;
449 GC_add_roots_inner(start, limit, TRUE);
452 /* Dont keep cached descriptor, for now. Some kernels don't like us */
453 /* to keep a /proc file descriptor around during kill -9. */
454 if (close(fd) < 0) ABORT("Couldnt close /proc file");
458 # endif /* USE_PROC || IRIX5 */
462 # define WIN32_LEAN_AND_MEAN
464 # include <windows.h>
467 /* We traverse the entire address space and register all segments */
468 /* that could possibly have been written to. */
469 DWORD GC_allocation_granularity;
471 extern GC_bool GC_is_heap_base (ptr_t p);
473 # ifdef WIN32_THREADS
474 extern void GC_get_next_stack(char *start, char **lo, char **hi);
477 void GC_cond_add_roots(char *base, char * limit)
481 = (char *) ((word)(&dummy) & ~(GC_allocation_granularity-1));
482 if (base == limit) return;
483 # ifdef WIN32_THREADS
485 char * curr_base = base;
486 char * next_stack_lo;
487 char * next_stack_hi;
490 GC_get_next_stack(curr_base, &next_stack_lo, &next_stack_hi);
491 if (next_stack_lo >= limit) break;
492 GC_add_roots_inner(curr_base, next_stack_lo, TRUE);
493 curr_base = next_stack_hi;
495 if (curr_base < limit) GC_add_roots_inner(curr_base, limit, TRUE);
498 if (limit > stack_top && base < GC_stackbottom) {
499 /* Part of the stack; ignore it. */
502 GC_add_roots_inner(base, limit, TRUE);
506 extern GC_bool GC_win32s;
508 void GC_register_dynamic_libraries()
510 MEMORY_BASIC_INFORMATION buf;
516 char * limit, * new_limit;
518 if (GC_win32s) return;
519 GetSystemInfo(&sysinfo);
520 base = limit = p = sysinfo.lpMinimumApplicationAddress;
521 GC_allocation_granularity = sysinfo.dwAllocationGranularity;
522 while (p < sysinfo.lpMaximumApplicationAddress) {
523 result = VirtualQuery(p, &buf, sizeof(buf));
524 if (result != sizeof(buf)) {
525 ABORT("Weird VirtualQuery result");
527 new_limit = (char *)p + buf.RegionSize;
528 protect = buf.Protect;
529 if (buf.State == MEM_COMMIT
530 && (protect == PAGE_EXECUTE_READWRITE
531 || protect == PAGE_READWRITE)
532 && !GC_is_heap_base(buf.AllocationBase)) {
533 if ((char *)p == limit) {
536 GC_cond_add_roots(base, limit);
541 if (p > (LPVOID)new_limit /* overflow */) break;
542 p = (LPVOID)new_limit;
544 GC_cond_add_roots(base, limit);
549 #if defined(ALPHA) && defined(OSF1)
553 void GC_register_dynamic_libraries()
559 ldr_module_t moduleid = LDR_NULL_MODULE;
560 ldr_module_info_t moduleinfo;
561 size_t moduleinfosize = sizeof(moduleinfo);
562 size_t modulereturnsize;
566 ldr_region_info_t regioninfo;
567 size_t regioninfosize = sizeof(regioninfo);
568 size_t regionreturnsize;
570 /* Obtain id of this process */
571 mypid = ldr_my_process();
573 /* For each module */
576 /* Get the next (first) module */
577 status = ldr_next_module(mypid, &moduleid);
579 /* Any more modules? */
580 if (moduleid == LDR_NULL_MODULE)
581 break; /* No more modules */
583 /* Check status AFTER checking moduleid because */
584 /* of a bug in the non-shared ldr_next_module stub */
586 GC_printf1("dynamic_load: status = %ld\n", (long)status);
588 extern char *sys_errlist[];
591 if (errno <= sys_nerr) {
592 GC_printf1("dynamic_load: %s\n", (long)sys_errlist[errno]);
594 GC_printf1("dynamic_load: %d\n", (long)errno);
597 ABORT("ldr_next_module failed");
600 /* Get the module information */
601 status = ldr_inq_module(mypid, moduleid, &moduleinfo,
602 moduleinfosize, &modulereturnsize);
604 ABORT("ldr_inq_module failed");
606 /* is module for the main program (i.e. nonshared portion)? */
607 if (moduleinfo.lmi_flags & LDR_MAIN)
608 continue; /* skip the main module */
611 GC_printf("---Module---\n");
612 GC_printf("Module ID = %16ld\n", moduleinfo.lmi_modid);
613 GC_printf("Count of regions = %16d\n", moduleinfo.lmi_nregion);
614 GC_printf("flags for module = %16lx\n", moduleinfo.lmi_flags);
615 GC_printf("pathname of module = \"%s\"\n", moduleinfo.lmi_name);
618 /* For each region in this module */
619 for (region = 0; region < moduleinfo.lmi_nregion; region++) {
621 /* Get the region information */
622 status = ldr_inq_region(mypid, moduleid, region, ®ioninfo,
623 regioninfosize, ®ionreturnsize);
625 ABORT("ldr_inq_region failed");
627 /* only process writable (data) regions */
628 if (! (regioninfo.lri_prot & LDR_W))
632 GC_printf("--- Region ---\n");
633 GC_printf("Region number = %16ld\n",
634 regioninfo.lri_region_no);
635 GC_printf("Protection flags = %016x\n", regioninfo.lri_prot);
636 GC_printf("Virtual address = %16p\n", regioninfo.lri_vaddr);
637 GC_printf("Mapped address = %16p\n", regioninfo.lri_mapaddr);
638 GC_printf("Region size = %16ld\n", regioninfo.lri_size);
639 GC_printf("Region name = \"%s\"\n", regioninfo.lri_name);
642 /* register region as a garbage collection root */
644 (char *)regioninfo.lri_mapaddr,
645 (char *)regioninfo.lri_mapaddr + regioninfo.lri_size,
659 extern char *sys_errlist[];
662 void GC_register_dynamic_libraries()
665 int index = 1; /* Ordinal position in shared library search list */
666 struct shl_descriptor *shl_desc; /* Shared library info, see dl.h */
668 /* For each dynamic library loaded */
671 /* Get info about next shared library */
672 status = shl_get(index, &shl_desc);
674 /* Check if this is the end of the list or if some error occured */
676 if (errno == EINVAL) {
677 break; /* Moved past end of shared library list --> finished */
679 if (errno <= sys_nerr) {
680 GC_printf1("dynamic_load: %s\n", (long) sys_errlist[errno]);
682 GC_printf1("dynamic_load: %d\n", (long) errno);
684 ABORT("shl_get failed");
689 GC_printf0("---Shared library---\n");
690 GC_printf1("\tfilename = \"%s\"\n", shl_desc->filename);
691 GC_printf1("\tindex = %d\n", index);
692 GC_printf1("\thandle = %08x\n",
693 (unsigned long) shl_desc->handle);
694 GC_printf1("\ttext seg. start = %08x\n", shl_desc->tstart);
695 GC_printf1("\ttext seg. end = %08x\n", shl_desc->tend);
696 GC_printf1("\tdata seg. start = %08x\n", shl_desc->dstart);
697 GC_printf1("\tdata seg. end = %08x\n", shl_desc->dend);
698 GC_printf1("\tref. count = %lu\n", shl_desc->ref_count);
701 /* register shared library's data segment as a garbage collection root */
702 GC_add_roots_inner((char *) shl_desc->dstart,
703 (char *) shl_desc->dend, TRUE);
713 #include <sys/errno.h>
714 void GC_register_dynamic_libraries()
721 ldibuf = alloca(ldibuflen = 8192);
723 while ( (len = loadquery(L_GETINFO,ldibuf,ldibuflen)) < 0) {
724 if (errno != ENOMEM) {
725 ABORT("loadquery failed");
727 ldibuf = alloca(ldibuflen *= 2);
730 ldi = (struct ld_info *)ldibuf;
732 len = ldi->ldinfo_next;
735 (unsigned long)ldi->ldinfo_dataorg
736 + ldi->ldinfo_datasize,
738 ldi = len ? (struct ld_info *)((char *)ldi + len) : 0;
745 #else /* !DYNAMIC_LOADING */
749 # include "il/PCR_IL.h"
750 # include "th/PCR_ThCtl.h"
751 # include "mm/PCR_MM.h"
753 void GC_register_dynamic_libraries()
755 /* Add new static data areas of dynamically loaded modules. */
757 PCR_IL_LoadedFile * p = PCR_IL_GetLastLoadedFile();
758 PCR_IL_LoadedSegment * q;
760 /* Skip uncommited files */
761 while (p != NIL && !(p -> lf_commitPoint)) {
762 /* The loading of this file has not yet been committed */
763 /* Hence its description could be inconsistent. */
764 /* Furthermore, it hasn't yet been run. Hence its data */
765 /* segments can't possibly reference heap allocated */
769 for (; p != NIL; p = p -> lf_prev) {
770 for (q = p -> lf_ls; q != NIL; q = q -> ls_next) {
771 if ((q -> ls_flags & PCR_IL_SegFlags_Traced_MASK)
772 == PCR_IL_SegFlags_Traced_on) {
774 ((char *)(q -> ls_addr),
775 (char *)(q -> ls_addr) + q -> ls_bytes,
786 void GC_register_dynamic_libraries(){}
788 int GC_no_dynamic_loading;
791 #endif /* !DYNAMIC_LOADING */