OSDN Git Service

* dyn_load.c: Define ElfW (if needed) for all targets,
[pf3gnuchains/gcc-fork.git] / boehm-gc / dyn_load.c
1 /*
2  * Copyright (c) 1991-1994 by Xerox Corporation.  All rights reserved.
3  * Copyright (c) 1997 by Silicon Graphics.  All rights reserved.
4  *
5  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
6  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
7  *
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.
13  *
14  * Original author: Bill Janssen
15  * Heavily modified by Hans Boehm and others
16  */
17
18 /*
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 ...
25  *
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.
28  */
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"
37
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
51
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) && \
59     !(defined(FREEBSD) && defined(__ELF__)) && \
60     !(defined(NETBSD) && defined(__ELF__)) && !defined(HURD)
61  --> We only know how to find data segments of dynamic libraries for the
62  --> above.  Additional SVR4 variants might not be too
63  --> hard to add.
64 #endif
65
66 #include <stdio.h>
67 #ifdef SUNOS5DL
68 #   include <sys/elf.h>
69 #   include <dlfcn.h>
70 #   include <link.h>
71 #endif
72 #ifdef SUNOS4
73 #   include <dlfcn.h>
74 #   include <link.h>
75 #   include <a.out.h>
76   /* struct link_map field overrides */
77 #   define l_next       lm_next
78 #   define l_addr       lm_addr
79 #   define l_name       lm_name
80 #endif
81
82 /* Newer versions of GNU/Linux define this macro.  We
83  * define it similarly for any ELF systems that don't.  */
84 #  ifndef ElfW
85 #    if !defined(ELF_CLASS) || ELF_CLASS == ELFCLASS32
86 #      define ElfW(type) Elf32_##type
87 #    else
88 #      define ElfW(type) Elf64_##type
89 #    endif
90 #  endif
91
92 #if defined(SUNOS5DL) && !defined(USE_PROC_FOR_LIBRARIES)
93
94 #ifdef LINT
95     Elf32_Dyn _DYNAMIC;
96 #endif
97
98 static struct link_map *
99 GC_FirstDLOpenedLinkMap()
100 {
101     extern ElfW(Dyn) _DYNAMIC;
102     ElfW(Dyn) *dp;
103     struct r_debug *r;
104     static struct link_map * cachedResult = 0;
105     static ElfW(Dyn) *dynStructureAddr = 0;
106                         /* BTL: added to avoid Solaris 5.3 ld.so _DYNAMIC bug */
107
108 #   ifdef SUNOS53_SHARED_LIB
109         /* BTL: Avoid the Solaris 5.3 bug that _DYNAMIC isn't being set */
110         /* up properly in dynamically linked .so's. This means we have  */
111         /* to use its value in the set of original object files loaded  */
112         /* at program startup.                                          */
113         if( dynStructureAddr == 0 ) {
114           void* startupSyms = dlopen(0, RTLD_LAZY);
115           dynStructureAddr = (ElfW(Dyn)*)dlsym(startupSyms, "_DYNAMIC");
116                 }
117 #   else
118         dynStructureAddr = &_DYNAMIC;
119 #   endif
120
121     if( dynStructureAddr == 0) {
122         return(0);
123     }
124     if( cachedResult == 0 ) {
125         int tag;
126         for( dp = ((ElfW(Dyn) *)(&_DYNAMIC)); (tag = dp->d_tag) != 0; dp++ ) {
127             if( tag == DT_DEBUG ) {
128                 struct link_map *lm
129                         = ((struct r_debug *)(dp->d_un.d_ptr))->r_map;
130                 if( lm != 0 ) cachedResult = lm->l_next; /* might be NIL */
131                 break;
132             }
133         }
134     }
135     return cachedResult;
136 }
137
138 #endif /* SUNOS5DL ... */
139
140 /* BTL: added to fix circular dlopen definition if GC_SOLARIS_THREADS defined */
141 # if defined(GC_must_restore_redefined_dlopen)
142 #   define dlopen GC_dlopen
143 # endif
144
145 #if defined(SUNOS4) && !defined(USE_PROC_FOR_LIBRARIES)
146
147 #ifdef LINT
148     struct link_dynamic _DYNAMIC;
149 #endif
150
151 static struct link_map *
152 GC_FirstDLOpenedLinkMap()
153 {
154     extern struct link_dynamic _DYNAMIC;
155
156     if( &_DYNAMIC == 0) {
157         return(0);
158     }
159     return(_DYNAMIC.ld_un.ld_1->ld_loaded);
160 }
161
162 /* Return the address of the ld.so allocated common symbol      */
163 /* with the least address, or 0 if none.                        */
164 static ptr_t GC_first_common()
165 {
166     ptr_t result = 0;
167     extern struct link_dynamic _DYNAMIC;
168     struct rtc_symb * curr_symbol;
169     
170     if( &_DYNAMIC == 0) {
171         return(0);
172     }
173     curr_symbol = _DYNAMIC.ldd -> ldd_cp;
174     for (; curr_symbol != 0; curr_symbol = curr_symbol -> rtc_next) {
175         if (result == 0
176             || (ptr_t)(curr_symbol -> rtc_sp -> n_value) < result) {
177             result = (ptr_t)(curr_symbol -> rtc_sp -> n_value);
178         }
179     }
180     return(result);
181 }
182
183 #endif  /* SUNOS4 ... */
184
185 # if defined(SUNOS4) || defined(SUNOS5DL)
186 /* Add dynamic library data sections to the root set.           */
187 # if !defined(PCR) && !defined(GC_SOLARIS_THREADS) && defined(THREADS)
188 #   ifndef SRC_M3
189         --> fix mutual exclusion with dlopen
190 #   endif  /* We assume M3 programs don't call dlopen for now */
191 # endif
192
193 # ifndef USE_PROC_FOR_LIBRARIES
194 void GC_register_dynamic_libraries()
195 {
196   struct link_map *lm = GC_FirstDLOpenedLinkMap();
197   
198
199   for (lm = GC_FirstDLOpenedLinkMap();
200        lm != (struct link_map *) 0;  lm = lm->l_next)
201     {
202 #     ifdef SUNOS4
203         struct exec *e;
204          
205         e = (struct exec *) lm->lm_addr;
206         GC_add_roots_inner(
207                     ((char *) (N_DATOFF(*e) + lm->lm_addr)),
208                     ((char *) (N_BSSADDR(*e) + e->a_bss + lm->lm_addr)),
209                     TRUE);
210 #     endif
211 #     ifdef SUNOS5DL
212         ElfW(Ehdr) * e;
213         ElfW(Phdr) * p;
214         unsigned long offset;
215         char * start;
216         register int i;
217         
218         e = (ElfW(Ehdr) *) lm->l_addr;
219         p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
220         offset = ((unsigned long)(lm->l_addr));
221         for( i = 0; i < (int)(e->e_phnum); ((i++),(p++)) ) {
222           switch( p->p_type ) {
223             case PT_LOAD:
224               {
225                 if( !(p->p_flags & PF_W) ) break;
226                 start = ((char *)(p->p_vaddr)) + offset;
227                 GC_add_roots_inner(
228                   start,
229                   start + p->p_memsz,
230                   TRUE
231                 );
232               }
233               break;
234             default:
235               break;
236           }
237         }
238 #     endif
239     }
240 #   ifdef SUNOS4
241       {
242         static ptr_t common_start = 0;
243         ptr_t common_end;
244         extern ptr_t GC_find_limit();
245         
246         if (common_start == 0) common_start = GC_first_common();
247         if (common_start != 0) {
248             common_end = GC_find_limit(common_start, TRUE);
249             GC_add_roots_inner((char *)common_start, (char *)common_end, TRUE);
250         }
251       }
252 #   endif
253 }
254
255 # endif /* !USE_PROC ... */
256 # endif /* SUNOS */
257
258 #if defined(LINUX) && defined(__ELF__) || defined(SCO_ELF) || \
259     (defined(FREEBSD) && defined(__ELF__)) || \
260     (defined(NETBSD) && defined(__ELF__)) || defined(HURD)
261
262
263 #ifdef USE_PROC_FOR_LIBRARIES
264
265 #include <string.h>
266
267 #include <sys/stat.h>
268 #include <fcntl.h>
269 #include <unistd.h>
270
271 #define MAPS_BUF_SIZE (32*1024)
272
273 extern ssize_t GC_repeat_read(int fd, char *buf, size_t count);
274         /* Repeatedly read until buffer is filled, or EOF is encountered */
275         /* Defined in os_dep.c.                                          */
276
277 static char *parse_map_entry(char *buf_ptr, word *start, word *end,
278                              char *prot_buf, unsigned int *maj_dev);
279
280 void GC_register_dynamic_libraries()
281 {
282     int f;
283     int result;
284     char prot_buf[5];
285     int maps_size;
286     char maps_temp[32768];
287     char *maps_buf;
288     char *buf_ptr;
289     int count;
290     word start, end;
291     unsigned int maj_dev, min_dev;
292     word least_ha, greatest_ha;
293     unsigned i;
294     word datastart = (word)(DATASTART);
295
296     /* Read /proc/self/maps     */
297         /* Note that we may not allocate, and thus can't use stdio.     */
298         f = open("/proc/self/maps", O_RDONLY);
299         if (-1 == f) ABORT("Couldn't open /proc/self/maps");
300         /* stat() doesn't work for /proc/self/maps, so we have to
301            read it to find out how large it is... */
302         maps_size = 0;
303         do {
304             result = GC_repeat_read(f, maps_temp, sizeof(maps_temp));
305             if (result <= 0) ABORT("Couldn't read /proc/self/maps");
306             maps_size += result;
307         } while (result == sizeof(maps_temp));
308
309         if (maps_size > sizeof(maps_temp)) {
310             /* If larger than our buffer, close and re-read it. */
311             close(f);
312             f = open("/proc/self/maps", O_RDONLY);
313             if (-1 == f) ABORT("Couldn't open /proc/self/maps");
314             maps_buf = alloca(maps_size);
315             if (NULL == maps_buf) ABORT("/proc/self/maps alloca failed");
316             result = GC_repeat_read(f, maps_buf, maps_size);
317             if (result <= 0) ABORT("Couldn't read /proc/self/maps");
318         } else {
319             /* Otherwise use the fixed size buffer */
320             maps_buf = maps_temp;
321         }
322
323         close(f);
324         maps_buf[result] = '\0';
325         buf_ptr = maps_buf;
326     /* Compute heap bounds. Should be done by add_to_heap?      */
327         least_ha = (word)(-1);
328         greatest_ha = 0;
329         for (i = 0; i < GC_n_heap_sects; ++i) {
330             word sect_start = (word)GC_heap_sects[i].hs_start;
331             word sect_end = sect_start + GC_heap_sects[i].hs_bytes;
332             if (sect_start < least_ha) least_ha = sect_start;
333             if (sect_end > greatest_ha) greatest_ha = sect_end;
334         }
335         if (greatest_ha < (word)GC_scratch_last_end_ptr)
336             greatest_ha = (word)GC_scratch_last_end_ptr; 
337     for (;;) {
338
339         buf_ptr = parse_map_entry(buf_ptr, &start, &end, prot_buf, &maj_dev);
340         if (buf_ptr == NULL) return;
341
342         if (prot_buf[1] == 'w') {
343             /* This is a writable mapping.  Add it to           */
344             /* the root set unless it is already otherwise      */
345             /* accounted for.                                   */
346             if (start <= (word)GC_stackbottom && end >= (word)GC_stackbottom) {
347                 /* Stack mapping; discard       */
348                 continue;
349             }
350             if (start <= datastart && end > datastart && maj_dev != 0) {
351                 /* Main data segment; discard   */
352                 continue;
353             }
354 #           ifdef THREADS
355               if (GC_segment_is_thread_stack(start, end)) continue;
356 #           endif
357             /* The rest of this assumes that there is no mapping        */
358             /* spanning the beginning of the data segment, or extending */
359             /* beyond the entire heap at both ends.                     */
360             /* Empirically these assumptions hold.                      */
361             
362             if (start < (word)DATAEND && end > (word)DATAEND) {
363                 /* Rld may use space at the end of the main data        */
364                 /* segment.  Thus we add that in.                       */
365                 start = (word)DATAEND;
366             }
367             if (start < least_ha && end > least_ha) {
368                 end = least_ha;
369             }
370             if (start < greatest_ha && end > greatest_ha) {
371                 start = greatest_ha;
372             }
373             if (start >= least_ha && end <= greatest_ha) continue;
374             GC_add_roots_inner((char *)start, (char *)end, TRUE);
375         }
376      }
377 }
378
379 //
380 //  parse_map_entry parses an entry from /proc/self/maps so we can
381 //  locate all writable data segments that belong to shared libraries.
382 //  The format of one of these entries and the fields we care about
383 //  is as follows:
384 //  XXXXXXXX-XXXXXXXX r-xp 00000000 30:05 260537     name of mapping...\n
385 //  ^^^^^^^^ ^^^^^^^^ ^^^^          ^^
386 //  start    end      prot          maj_dev
387 //  0        9        18            32
388 //
389 //  The parser is called with a pointer to the entry and the return value
390 //  is either NULL or is advanced to the next entry(the byte after the
391 //  trailing '\n'.)
392 //
393 #define OFFSET_MAP_START   0
394 #define OFFSET_MAP_END     9
395 #define OFFSET_MAP_PROT   18
396 #define OFFSET_MAP_MAJDEV 32
397
398 static char *parse_map_entry(char *buf_ptr, word *start, word *end,
399                              char *prot_buf, unsigned int *maj_dev)
400 {
401     int i;
402     unsigned int val;
403     char *tok;
404
405     if (buf_ptr == NULL || *buf_ptr == '\0') {
406         return NULL;
407     }
408
409     memcpy(prot_buf, buf_ptr+OFFSET_MAP_PROT, 4); // do the protections first
410     prot_buf[4] = '\0';
411
412     if (prot_buf[1] == 'w') { // we can skip all of this if it's not writable
413
414         tok = buf_ptr;
415         buf_ptr[OFFSET_MAP_START+8] = '\0';
416         *start = strtoul(tok, NULL, 16);
417
418         tok = buf_ptr+OFFSET_MAP_END;
419         buf_ptr[OFFSET_MAP_END+8] = '\0';
420         *end = strtoul(tok, NULL, 16);
421
422         buf_ptr += OFFSET_MAP_MAJDEV;
423         tok = buf_ptr;
424         while (*buf_ptr != ':') buf_ptr++;
425         *buf_ptr++ = '\0';
426         *maj_dev = strtoul(tok, NULL, 16);
427     }
428
429     while (*buf_ptr && *buf_ptr++ != '\n');
430
431     return buf_ptr;
432 }
433
434 #endif /* USE_PROC_FOR_LIBRARIES */
435
436 #if !defined(USE_PROC_FOR_LIBRARIES)
437 /* The following is the preferred way to walk dynamic libraries */
438 /* For glibc 2.2.4+.  Unfortunately, it doesn't work for older  */
439 /* versions.  Thanks to Jakub Jelinek for most of the code.     */
440
441 #include <stddef.h>
442 #include <elf.h>
443 #include <link.h>
444
445 # if defined(LINUX) /* Are others OK here, too? */ \
446      && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) \
447          || (__GLIBC__ == 2 && __GLIBC_MINOR__ == 2 && defined(DT_CONFIG))) 
448
449 /* We have the header files for a glibc that includes dl_iterate_phdr.  */
450 /* It may still not be available in the library on the target system.   */
451 /* Thus we also treat it as a weak symbol.                              */
452 #define HAVE_DL_ITERATE_PHDR
453
454 static int GC_register_dynlib_callback(info, size, ptr)
455      struct dl_phdr_info * info;
456      size_t size;
457      void * ptr;
458 {
459   const ElfW(Phdr) * p;
460   char * start;
461   register int i;
462
463   /* Make sure struct dl_phdr_info is at least as big as we need.  */
464   if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
465       + sizeof (info->dlpi_phnum))
466     return -1;
467
468   /* Skip the first object - it is the main program.  */
469   if (*(int *)ptr == 0)
470     {
471       *(int *)ptr = 1;
472       return 0;
473     }
474
475   p = info->dlpi_phdr;
476   for( i = 0; i < (int)(info->dlpi_phnum); ((i++),(p++)) ) {
477     switch( p->p_type ) {
478       case PT_LOAD:
479         {
480           if( !(p->p_flags & PF_W) ) break;
481           start = ((char *)(p->p_vaddr)) + info->dlpi_addr;
482           GC_add_roots_inner(start, start + p->p_memsz, TRUE);
483         }
484       break;
485       default:
486         break;
487     }
488   }
489
490   return 0;
491 }     
492
493 /* Return TRUE if we succeed, FALSE if dl_iterate_phdr wasn't there. */
494
495 #pragma weak dl_iterate_phdr
496
497 GC_bool GC_register_dynamic_libraries_dl_iterate_phdr()
498 {
499   int tmp = 0;
500
501   if (dl_iterate_phdr) {
502     dl_iterate_phdr(GC_register_dynlib_callback, &tmp);
503     return TRUE;
504   } else {
505     return FALSE;
506   }
507 }
508
509 # else /* !LINUX || version(glibc) < 2.2.4 */
510
511 /* Dynamic loading code for Linux running ELF. Somewhat tested on
512  * Linux/x86, untested but hopefully should work on Linux/Alpha. 
513  * This code was derived from the Solaris/ELF support. Thanks to
514  * whatever kind soul wrote that.  - Patrick Bridges */
515
516 /* This doesn't necessarily work in all cases, e.g. with preloaded
517  * dynamic libraries.                                           */
518
519 #if defined(NETBSD)
520 #  include <sys/exec_elf.h>
521 #else
522 #  include <elf.h>
523 #endif
524 #include <link.h>
525
526 # endif
527
528 static struct link_map *
529 GC_FirstDLOpenedLinkMap()
530 {
531 #   ifdef __GNUC__
532 #     pragma weak _DYNAMIC
533 #   endif
534     extern ElfW(Dyn) _DYNAMIC[];
535     ElfW(Dyn) *dp;
536     struct r_debug *r;
537     static struct link_map *cachedResult = 0;
538
539     if( _DYNAMIC == 0) {
540         return(0);
541     }
542     if( cachedResult == 0 ) {
543         int tag;
544         for( dp = _DYNAMIC; (tag = dp->d_tag) != 0; dp++ ) {
545             if( tag == DT_DEBUG ) {
546                 struct link_map *lm
547                         = ((struct r_debug *)(dp->d_un.d_ptr))->r_map;
548                 if( lm != 0 ) cachedResult = lm->l_next; /* might be NIL */
549                 break;
550             }
551         }
552     }
553     return cachedResult;
554 }
555
556
557 void GC_register_dynamic_libraries()
558 {
559   struct link_map *lm;
560   
561
562 # ifdef HAVE_DL_ITERATE_PHDR
563     if (GC_register_dynamic_libraries_dl_iterate_phdr()) {
564         return;
565     }
566 # endif
567   lm = GC_FirstDLOpenedLinkMap();
568   for (lm = GC_FirstDLOpenedLinkMap();
569        lm != (struct link_map *) 0;  lm = lm->l_next)
570     {
571         ElfW(Ehdr) * e;
572         ElfW(Phdr) * p;
573         unsigned long offset;
574         char * start;
575         register int i;
576         
577         e = (ElfW(Ehdr) *) lm->l_addr;
578         p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
579         offset = ((unsigned long)(lm->l_addr));
580         for( i = 0; i < (int)(e->e_phnum); ((i++),(p++)) ) {
581           switch( p->p_type ) {
582             case PT_LOAD:
583               {
584                 if( !(p->p_flags & PF_W) ) break;
585                 start = ((char *)(p->p_vaddr)) + offset;
586                 GC_add_roots_inner(start, start + p->p_memsz, TRUE);
587               }
588               break;
589             default:
590               break;
591           }
592         }
593     }
594 }
595
596 #endif /* !USE_PROC_FOR_LIBRARIES */
597
598 #endif /* LINUX */
599
600 #if defined(IRIX5) || (defined(USE_PROC_FOR_LIBRARIES) && !defined(LINUX))
601
602 #include <sys/procfs.h>
603 #include <sys/stat.h>
604 #include <fcntl.h>
605 #include <elf.h>
606 #include <errno.h>
607 #include <signal.h>  /* Only for the following test. */
608 #ifndef _sigargs
609 # define IRIX6
610 #endif
611
612 extern void * GC_roots_present();
613         /* The type is a lie, since the real type doesn't make sense here, */
614         /* and we only test for NULL.                                      */
615
616 /* We use /proc to track down all parts of the address space that are   */
617 /* mapped by the process, and throw out regions we know we shouldn't    */
618 /* worry about.  This may also work under other SVR4 variants.          */
619 void GC_register_dynamic_libraries()
620 {
621     static int fd = -1;
622     char buf[30];
623     static prmap_t * addr_map = 0;
624     static int current_sz = 0;  /* Number of records currently in addr_map */
625     static int needed_sz;       /* Required size of addr_map            */
626     register int i;
627     register long flags;
628     register ptr_t start;
629     register ptr_t limit;
630     ptr_t heap_start = (ptr_t)HEAP_START;
631     ptr_t heap_end = heap_start;
632
633 #   ifdef SUNOS5DL
634 #     define MA_PHYS 0
635 #   endif /* SUNOS5DL */
636
637     if (fd < 0) {
638       sprintf(buf, "/proc/%d", getpid());
639         /* The above generates a lint complaint, since pid_t varies.    */
640         /* It's unclear how to improve this.                            */
641       fd = open(buf, O_RDONLY);
642       if (fd < 0) {
643         ABORT("/proc open failed");
644       }
645     }
646     if (ioctl(fd, PIOCNMAP, &needed_sz) < 0) {
647         GC_err_printf2("fd = %d, errno = %d\n", fd, errno);
648         ABORT("/proc PIOCNMAP ioctl failed");
649     }
650     if (needed_sz >= current_sz) {
651         current_sz = needed_sz * 2 + 1;
652                         /* Expansion, plus room for 0 record */
653         addr_map = (prmap_t *)GC_scratch_alloc((word)
654                                                 (current_sz * sizeof(prmap_t)));
655     }
656     if (ioctl(fd, PIOCMAP, addr_map) < 0) {
657         GC_err_printf4("fd = %d, errno = %d, needed_sz = %d, addr_map = 0x%X\n",
658                         fd, errno, needed_sz, addr_map);
659         ABORT("/proc PIOCMAP ioctl failed");
660     };
661     if (GC_n_heap_sects > 0) {
662         heap_end = GC_heap_sects[GC_n_heap_sects-1].hs_start
663                         + GC_heap_sects[GC_n_heap_sects-1].hs_bytes;
664         if (heap_end < GC_scratch_last_end_ptr) heap_end = GC_scratch_last_end_ptr; 
665     }
666     for (i = 0; i < needed_sz; i++) {
667         flags = addr_map[i].pr_mflags;
668         if ((flags & (MA_BREAK | MA_STACK | MA_PHYS)) != 0) goto irrelevant;
669         if ((flags & (MA_READ | MA_WRITE)) != (MA_READ | MA_WRITE))
670             goto irrelevant;
671           /* The latter test is empirically useless in very old Irix    */
672           /* versions.  Other than the                                  */
673           /* main data and stack segments, everything appears to be     */
674           /* mapped readable, writable, executable, and shared(!!).     */
675           /* This makes no sense to me. - HB                            */
676         start = (ptr_t)(addr_map[i].pr_vaddr);
677         if (GC_roots_present(start)) goto irrelevant;
678         if (start < heap_end && start >= heap_start)
679                 goto irrelevant;
680 #       ifdef MMAP_STACKS
681           if (GC_is_thread_stack(start)) goto irrelevant;
682 #       endif /* MMAP_STACKS */
683
684         limit = start + addr_map[i].pr_size;
685         /* The following seemed to be necessary for very old versions   */
686         /* of Irix, but it has been reported to discard relevant        */
687         /* segments under Irix 6.5.                                     */
688 #       ifndef IRIX6
689           if (addr_map[i].pr_off == 0 && strncmp(start, ELFMAG, 4) == 0) {
690             /* Discard text segments, i.e. 0-offset mappings against    */
691             /* executable files which appear to have ELF headers.       */
692             caddr_t arg;
693             int obj;
694 #           define MAP_IRR_SZ 10
695             static ptr_t map_irr[MAP_IRR_SZ];
696                                         /* Known irrelevant map entries */
697             static int n_irr = 0;
698             struct stat buf;
699             register int i;
700             
701             for (i = 0; i < n_irr; i++) {
702                 if (map_irr[i] == start) goto irrelevant;
703             }
704             arg = (caddr_t)start;
705             obj = ioctl(fd, PIOCOPENM, &arg);
706             if (obj >= 0) {
707                 fstat(obj, &buf);
708                 close(obj);
709                 if ((buf.st_mode & 0111) != 0) {
710                     if (n_irr < MAP_IRR_SZ) {
711                         map_irr[n_irr++] = start;
712                     }
713                     goto irrelevant;
714                 }
715             }
716           }
717 #       endif /* !IRIX6 */
718         GC_add_roots_inner(start, limit, TRUE);
719       irrelevant: ;
720     }
721     /* Dont keep cached descriptor, for now.  Some kernels don't like us */
722     /* to keep a /proc file descriptor around during kill -9.            */
723         if (close(fd) < 0) ABORT("Couldnt close /proc file");
724         fd = -1;
725 }
726
727 # endif /* USE_PROC || IRIX5 */
728
729 # if defined(MSWIN32) || defined(MSWINCE)
730
731 # define WIN32_LEAN_AND_MEAN
732 # define NOSERVICE
733 # include <windows.h>
734 # include <stdlib.h>
735
736   /* We traverse the entire address space and register all segments     */
737   /* that could possibly have been written to.                          */
738   
739   extern GC_bool GC_is_heap_base (ptr_t p);
740
741 # ifdef GC_WIN32_THREADS
742     extern void GC_get_next_stack(char *start, char **lo, char **hi);
743     void GC_cond_add_roots(char *base, char * limit)
744     {
745       char * curr_base = base;
746       char * next_stack_lo;
747       char * next_stack_hi;
748    
749       if (base == limit) return;
750       for(;;) {
751           GC_get_next_stack(curr_base, &next_stack_lo, &next_stack_hi);
752           if (next_stack_lo >= limit) break;
753           GC_add_roots_inner(curr_base, next_stack_lo, TRUE);
754           curr_base = next_stack_hi;
755       }
756       if (curr_base < limit) GC_add_roots_inner(curr_base, limit, TRUE);
757     }
758 # else
759     void GC_cond_add_roots(char *base, char * limit)
760     {
761       char dummy;
762       char * stack_top
763          = (char *) ((word)(&dummy) & ~(GC_sysinfo.dwAllocationGranularity-1));
764       if (base == limit) return;
765       if (limit > stack_top && base < GC_stackbottom) {
766           /* Part of the stack; ignore it. */
767           return;
768       }
769       GC_add_roots_inner(base, limit, TRUE);
770     }
771 # endif
772
773 # ifndef MSWINCE
774   extern GC_bool GC_win32s;
775 # endif
776   
777   void GC_register_dynamic_libraries()
778   {
779     MEMORY_BASIC_INFORMATION buf;
780     DWORD result;
781     DWORD protect;
782     LPVOID p;
783     char * base;
784     char * limit, * new_limit;
785
786 #   ifdef MSWIN32
787       if (GC_win32s) return;
788 #   endif
789     base = limit = p = GC_sysinfo.lpMinimumApplicationAddress;
790 #   if defined(MSWINCE) && !defined(_WIN32_WCE_EMULATION)
791     /* Only the first 32 MB of address space belongs to the current process */
792     while (p < (LPVOID)0x02000000) {
793         result = VirtualQuery(p, &buf, sizeof(buf));
794         if (result == 0) {
795             /* Page is free; advance to the next possible allocation base */
796             new_limit = (char *)
797                 (((DWORD) p + GC_sysinfo.dwAllocationGranularity)
798                  & ~(GC_sysinfo.dwAllocationGranularity-1));
799         } else
800 #   else
801     while (p < GC_sysinfo.lpMaximumApplicationAddress) {
802         result = VirtualQuery(p, &buf, sizeof(buf));
803 #   endif
804         {
805             if (result != sizeof(buf)) {
806                 ABORT("Weird VirtualQuery result");
807             }
808             new_limit = (char *)p + buf.RegionSize;
809             protect = buf.Protect;
810             if (buf.State == MEM_COMMIT
811                 && (protect == PAGE_EXECUTE_READWRITE
812                     || protect == PAGE_READWRITE)
813                 && !GC_is_heap_base(buf.AllocationBase)) {
814                 if ((char *)p != limit) {
815                     GC_cond_add_roots(base, limit);
816                     base = p;
817                 }
818                 limit = new_limit;
819             }
820         }
821         if (p > (LPVOID)new_limit /* overflow */) break;
822         p = (LPVOID)new_limit;
823     }
824     GC_cond_add_roots(base, limit);
825   }
826
827 #endif /* MSWIN32 || MSWINCE */
828   
829 #if defined(ALPHA) && defined(OSF1)
830
831 #include <loader.h>
832
833 void GC_register_dynamic_libraries()
834 {
835   int status;
836   ldr_process_t mypid;
837
838   /* module */
839     ldr_module_t moduleid = LDR_NULL_MODULE;
840     ldr_module_info_t moduleinfo;
841     size_t moduleinfosize = sizeof(moduleinfo);
842     size_t modulereturnsize;    
843
844   /* region */
845     ldr_region_t region; 
846     ldr_region_info_t regioninfo;
847     size_t regioninfosize = sizeof(regioninfo);
848     size_t regionreturnsize;
849
850   /* Obtain id of this process */
851     mypid = ldr_my_process();
852   
853   /* For each module */
854     while (TRUE) {
855
856       /* Get the next (first) module */
857         status = ldr_next_module(mypid, &moduleid);
858
859       /* Any more modules? */
860         if (moduleid == LDR_NULL_MODULE)
861             break;    /* No more modules */
862
863       /* Check status AFTER checking moduleid because */
864       /* of a bug in the non-shared ldr_next_module stub */
865         if (status != 0 ) {
866             GC_printf1("dynamic_load: status = %ld\n", (long)status);
867             {
868                 extern char *sys_errlist[];
869                 extern int sys_nerr;
870                 extern int errno;
871                 if (errno <= sys_nerr) {
872                     GC_printf1("dynamic_load: %s\n", (long)sys_errlist[errno]);
873                } else {
874                     GC_printf1("dynamic_load: %d\n", (long)errno);
875                 }
876         }
877             ABORT("ldr_next_module failed");
878          }
879
880       /* Get the module information */
881         status = ldr_inq_module(mypid, moduleid, &moduleinfo,
882                                 moduleinfosize, &modulereturnsize); 
883         if (status != 0 )
884             ABORT("ldr_inq_module failed");
885
886       /* is module for the main program (i.e. nonshared portion)? */
887           if (moduleinfo.lmi_flags & LDR_MAIN)
888               continue;    /* skip the main module */
889
890 #     ifdef VERBOSE
891           GC_printf("---Module---\n");
892           GC_printf("Module ID            = %16ld\n", moduleinfo.lmi_modid);
893           GC_printf("Count of regions     = %16d\n", moduleinfo.lmi_nregion);
894           GC_printf("flags for module     = %16lx\n", moduleinfo.lmi_flags); 
895           GC_printf("pathname of module   = \"%s\"\n", moduleinfo.lmi_name);
896 #     endif
897
898       /* For each region in this module */
899         for (region = 0; region < moduleinfo.lmi_nregion; region++) {
900
901           /* Get the region information */
902             status = ldr_inq_region(mypid, moduleid, region, &regioninfo,
903                                     regioninfosize, &regionreturnsize);
904             if (status != 0 )
905                 ABORT("ldr_inq_region failed");
906
907           /* only process writable (data) regions */
908             if (! (regioninfo.lri_prot & LDR_W))
909                 continue;
910
911 #         ifdef VERBOSE
912               GC_printf("--- Region ---\n");
913               GC_printf("Region number    = %16ld\n",
914                         regioninfo.lri_region_no);
915               GC_printf("Protection flags = %016x\n",  regioninfo.lri_prot);
916               GC_printf("Virtual address  = %16p\n",   regioninfo.lri_vaddr);
917               GC_printf("Mapped address   = %16p\n",   regioninfo.lri_mapaddr);
918               GC_printf("Region size      = %16ld\n",  regioninfo.lri_size);
919               GC_printf("Region name      = \"%s\"\n", regioninfo.lri_name);
920 #         endif
921
922           /* register region as a garbage collection root */
923             GC_add_roots_inner (
924                 (char *)regioninfo.lri_mapaddr,
925                 (char *)regioninfo.lri_mapaddr + regioninfo.lri_size,
926                 TRUE);
927
928         }
929     }
930 }
931 #endif
932
933 #if defined(HPUX)
934
935 #include <errno.h>
936 #include <dl.h>
937
938 extern int errno;
939 extern char *sys_errlist[];
940 extern int sys_nerr;
941
942 void GC_register_dynamic_libraries()
943 {
944   int status;
945   int index = 1; /* Ordinal position in shared library search list */
946   struct shl_descriptor *shl_desc; /* Shared library info, see dl.h */
947
948   /* For each dynamic library loaded */
949     while (TRUE) {
950
951       /* Get info about next shared library */
952         status = shl_get(index, &shl_desc);
953
954       /* Check if this is the end of the list or if some error occured */
955         if (status != 0) {
956 #        ifdef GC_HPUX_THREADS
957            /* I've seen errno values of 0.  The man page is not clear   */
958            /* as to whether errno should get set on a -1 return.        */
959            break;
960 #        else
961           if (errno == EINVAL) {
962               break; /* Moved past end of shared library list --> finished */
963           } else {
964               if (errno <= sys_nerr) {
965                     GC_printf1("dynamic_load: %s\n", (long) sys_errlist[errno]);
966               } else {
967                     GC_printf1("dynamic_load: %d\n", (long) errno);
968               }
969               ABORT("shl_get failed");
970           }
971 #        endif
972         }
973
974 #     ifdef VERBOSE
975           GC_printf0("---Shared library---\n");
976           GC_printf1("\tfilename        = \"%s\"\n", shl_desc->filename);
977           GC_printf1("\tindex           = %d\n", index);
978           GC_printf1("\thandle          = %08x\n",
979                                         (unsigned long) shl_desc->handle);
980           GC_printf1("\ttext seg. start = %08x\n", shl_desc->tstart);
981           GC_printf1("\ttext seg. end   = %08x\n", shl_desc->tend);
982           GC_printf1("\tdata seg. start = %08x\n", shl_desc->dstart);
983           GC_printf1("\tdata seg. end   = %08x\n", shl_desc->dend);
984           GC_printf1("\tref. count      = %lu\n", shl_desc->ref_count);
985 #     endif
986
987       /* register shared library's data segment as a garbage collection root */
988         GC_add_roots_inner((char *) shl_desc->dstart,
989                            (char *) shl_desc->dend, TRUE);
990
991         index++;
992     }
993 }
994 #endif /* HPUX */
995
996 #ifdef RS6000
997 #pragma alloca
998 #include <sys/ldr.h>
999 #include <sys/errno.h>
1000 void GC_register_dynamic_libraries()
1001 {
1002         int len;
1003         char *ldibuf;
1004         int ldibuflen;
1005         struct ld_info *ldi;
1006
1007         ldibuf = alloca(ldibuflen = 8192);
1008
1009         while ( (len = loadquery(L_GETINFO,ldibuf,ldibuflen)) < 0) {
1010                 if (errno != ENOMEM) {
1011                         ABORT("loadquery failed");
1012                 }
1013                 ldibuf = alloca(ldibuflen *= 2);
1014         }
1015
1016         ldi = (struct ld_info *)ldibuf;
1017         while (ldi) {
1018                 len = ldi->ldinfo_next;
1019                 GC_add_roots_inner(
1020                                 ldi->ldinfo_dataorg,
1021                                 (unsigned long)ldi->ldinfo_dataorg
1022                                 + ldi->ldinfo_datasize,
1023                                 TRUE);
1024                 ldi = len ? (struct ld_info *)((char *)ldi + len) : 0;
1025         }
1026 }
1027 #endif /* RS6000 */
1028
1029
1030
1031 #else /* !DYNAMIC_LOADING */
1032
1033 #ifdef PCR
1034
1035 #   include "il/PCR_IL.h"
1036 #   include "th/PCR_ThCtl.h"
1037 #   include "mm/PCR_MM.h"
1038
1039 void GC_register_dynamic_libraries()
1040 {
1041     /* Add new static data areas of dynamically loaded modules. */
1042         {
1043           PCR_IL_LoadedFile * p = PCR_IL_GetLastLoadedFile();
1044           PCR_IL_LoadedSegment * q;
1045           
1046           /* Skip uncommited files */
1047           while (p != NIL && !(p -> lf_commitPoint)) {
1048               /* The loading of this file has not yet been committed    */
1049               /* Hence its description could be inconsistent.           */
1050               /* Furthermore, it hasn't yet been run.  Hence its data   */
1051               /* segments can't possibly reference heap allocated       */
1052               /* objects.                                               */
1053               p = p -> lf_prev;
1054           }
1055           for (; p != NIL; p = p -> lf_prev) {
1056             for (q = p -> lf_ls; q != NIL; q = q -> ls_next) {
1057               if ((q -> ls_flags & PCR_IL_SegFlags_Traced_MASK)
1058                   == PCR_IL_SegFlags_Traced_on) {
1059                 GC_add_roots_inner
1060                         ((char *)(q -> ls_addr), 
1061                          (char *)(q -> ls_addr) + q -> ls_bytes,
1062                          TRUE);
1063               }
1064             }
1065           }
1066         }
1067 }
1068
1069
1070 #else /* !PCR */
1071
1072 void GC_register_dynamic_libraries(){}
1073
1074 int GC_no_dynamic_loading;
1075
1076 #endif /* !PCR */
1077 #endif /* !DYNAMIC_LOADING */