dyn_load.c 53.2 KB
Newer Older
eg's avatar
eg committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * Copyright (c) 1991-1994 by Xerox Corporation.  All rights reserved.
 * Copyright (c) 1997 by Silicon Graphics.  All rights reserved.
 *
 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
 * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
 *
 * Permission is hereby granted to use or copy this program
 * for any purpose,  provided the above notices are retained on all copies.
 * Permission to modify the code and to distribute modified code is granted,
 * provided the above notices are retained, and a notice that the code was
 * modified is included with the above copyright notice.
 */

15 16
#include "private/gc_priv.h"

eg's avatar
eg committed
17 18 19 20 21 22 23 24 25 26 27
/*
 * This is incredibly OS specific code for tracking down data sections in
 * dynamic libraries.  There appears to be no way of doing this quickly
 * without groveling through undocumented data structures.  We would argue
 * that this is a bug in the design of the dlopen interface.  THIS CODE
 * MAY BREAK IN FUTURE OS RELEASES.  If this matters to you, don't hesitate
 * to let your vendor know ...
 *
 * None of this is safe with dlclose and incremental collection.
 * But then not much of anything is safe in the presence of dlclose.
 */
28 29 30

#if !defined(MACOS) && !defined(_WIN32_WCE) && !defined(__CC_ARM)
# include <sys/types.h>
eg's avatar
eg committed
31 32 33
#endif

/* BTL: avoid circular redefinition of dlopen if GC_SOLARIS_THREADS defined */
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#undef GC_MUST_RESTORE_REDEFINED_DLOPEN
#if defined(GC_PTHREADS) && !defined(GC_NO_DLOPEN) \
    && !defined(GC_NO_THREAD_REDIRECTS) && !defined(GC_USE_LD_WRAP)
  /* To support threads in Solaris, gc.h interposes on dlopen by        */
  /* defining "dlopen" to be "GC_dlopen", which is implemented below.   */
  /* However, both GC_FirstDLOpenedLinkMap() and GC_dlopen() use the    */
  /* real system dlopen() in their implementation. We first remove      */
  /* gc.h's dlopen definition and restore it later, after GC_dlopen().  */
# undef dlopen
# define GC_MUST_RESTORE_REDEFINED_DLOPEN
#endif /* !GC_NO_DLOPEN */

/* A user-supplied routine (custom filter) that might be called to      */
/* determine whether a DSO really needs to be scanned by the GC.        */
/* 0 means no filter installed.  May be unused on some platforms.       */
/* FIXME: Add filter support for more platforms.                        */
STATIC GC_has_static_roots_func GC_has_static_roots = 0;

#if (defined(DYNAMIC_LOADING) || defined(MSWIN32) || defined(MSWINCE) \
    || defined(CYGWIN32)) && !defined(PCR)

#if !defined(DARWIN) && !defined(SCO_ELF) && !defined(SOLARISDL) \
    && !defined(AIX) && !defined(DGUX) && !defined(IRIX5) && !defined(HPUX) \
    && !defined(CYGWIN32) && !defined(MSWIN32) && !defined(MSWINCE) \
    && !(defined(ALPHA) && defined(OSF1)) \
    && !(defined(FREEBSD) && defined(__ELF__)) \
    && !((defined(LINUX) || defined(NACL)) && defined(__ELF__)) \
    && !(defined(NETBSD) && defined(__ELF__)) && !defined(HURD) \
    && !(defined(OPENBSD) && (defined(__ELF__) || defined(M68K))) \
    && !defined(CPPCHECK)
# error We only know how to find data segments of dynamic libraries for above.
# error Additional SVR4 variants might not be too hard to add.
eg's avatar
eg committed
66 67 68
#endif

#include <stdio.h>
69
#ifdef SOLARISDL
eg's avatar
eg committed
70 71 72 73
#   include <sys/elf.h>
#   include <dlfcn.h>
#   include <link.h>
#endif
eg's avatar
eg committed
74 75

#if defined(NETBSD)
76 77
#   include <sys/param.h>
#   include <dlfcn.h>
eg's avatar
eg committed
78 79
#   include <machine/elf_machdep.h>
#   define ELFSIZE ARCH_ELFSIZE
eg's avatar
eg committed
80 81
#endif

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
#if defined(OPENBSD)
# include <sys/param.h>
# if (OpenBSD >= 200519) && !defined(HAVE_DL_ITERATE_PHDR)
#   define HAVE_DL_ITERATE_PHDR
# endif
#endif /* OPENBSD */

#if defined(SCO_ELF) || defined(DGUX) || defined(HURD) \
    || (defined(__ELF__) && (defined(LINUX) || defined(FREEBSD) \
                             || defined(NACL) || defined(NETBSD) \
                             || defined(OPENBSD)))
# include <stddef.h>
# if !defined(OPENBSD) && !defined(PLATFORM_ANDROID)
    /* OpenBSD does not have elf.h file; link.h below is sufficient.    */
    /* Exclude Android because linker.h below includes its own version. */
eg's avatar
eg committed
97
#   include <elf.h>
98 99 100 101 102 103 104 105 106 107 108 109 110
# endif
# ifdef PLATFORM_ANDROID
    /* If you don't need the "dynamic loading" feature, you may build   */
    /* the collector with -D IGNORE_DYNAMIC_LOADING.                    */
#   ifdef BIONIC_ELFDATA_REDEF_BUG
      /* Workaround a problem in Bionic (as of Android 4.2) which has   */
      /* mismatching ELF_DATA definitions in sys/exec_elf.h and         */
      /* asm/elf.h included from linker.h file (similar to EM_ALPHA).   */
#     include <asm/elf.h>
#     include <linux/elf-em.h>
#     undef ELF_DATA
#     undef EM_ALPHA
#   endif
eg's avatar
eg committed
111
#   include <link.h>
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
#   if !defined(GC_DONT_DEFINE_LINK_MAP) && !(__ANDROID_API__ >= 21)
      /* link_map and r_debug are defined in link.h of NDK r10+.        */
      /* bionic/linker/linker.h defines them too but the header         */
      /* itself is a C++ one starting from Android 4.3.                 */
      struct link_map {
        uintptr_t l_addr;
        char* l_name;
        uintptr_t l_ld;
        struct link_map* l_next;
        struct link_map* l_prev;
      };
      struct r_debug {
        int32_t r_version;
        struct link_map* r_map;
        void (*r_brk)(void);
        int32_t r_state;
        uintptr_t r_ldbase;
      };
#   endif
# else
#   include <link.h>
# endif
eg's avatar
eg committed
134 135 136 137 138
#endif

/* Newer versions of GNU/Linux define this macro.  We
 * define it similarly for any ELF systems that don't.  */
#  ifndef ElfW
eg's avatar
eg committed
139 140 141 142 143 144
#    if defined(FREEBSD)
#      if __ELF_WORD_SIZE == 32
#        define ElfW(type) Elf32_##type
#      else
#        define ElfW(type) Elf64_##type
#      endif
145
#    elif defined(NETBSD) || defined(OPENBSD)
eg's avatar
eg committed
146 147 148 149 150
#      if ELFSIZE == 32
#        define ElfW(type) Elf32_##type
#      else
#        define ElfW(type) Elf64_##type
#      endif
eg's avatar
eg committed
151
#    else
eg's avatar
eg committed
152 153 154 155 156
#      if !defined(ELF_CLASS) || ELF_CLASS == ELFCLASS32
#        define ElfW(type) Elf32_##type
#      else
#        define ElfW(type) Elf64_##type
#      endif
eg's avatar
eg committed
157 158 159
#    endif
#  endif

160
#if defined(SOLARISDL) && !defined(USE_PROC_FOR_LIBRARIES)
eg's avatar
eg committed
161 162 163 164 165

#ifdef LINT
    Elf32_Dyn _DYNAMIC;
#endif

166
STATIC struct link_map *
167
GC_FirstDLOpenedLinkMap(void)
eg's avatar
eg committed
168 169 170 171 172
{
    extern ElfW(Dyn) _DYNAMIC;
    ElfW(Dyn) *dp;
    static struct link_map * cachedResult = 0;
    static ElfW(Dyn) *dynStructureAddr = 0;
173
                /* BTL: added to avoid Solaris 5.3 ld.so _DYNAMIC bug   */
eg's avatar
eg committed
174 175

#   ifdef SUNOS53_SHARED_LIB
176 177 178 179 180 181 182 183
        /* BTL: Avoid the Solaris 5.3 bug that _DYNAMIC isn't being set */
        /* up properly in dynamically linked .so's. This means we have  */
        /* to use its value in the set of original object files loaded  */
        /* at program startup.                                          */
        if( dynStructureAddr == 0 ) {
          void* startupSyms = dlopen(0, RTLD_LAZY);
          dynStructureAddr = (ElfW(Dyn)*)(word)dlsym(startupSyms, "_DYNAMIC");
        }
eg's avatar
eg committed
184
#   else
185
        dynStructureAddr = &_DYNAMIC;
eg's avatar
eg committed
186 187
#   endif

188 189
    if (0 == COVERT_DATAFLOW(dynStructureAddr)) {
        /* _DYNAMIC symbol not resolved. */
eg's avatar
eg committed
190 191
        return(0);
    }
192
    if (cachedResult == 0) {
eg's avatar
eg committed
193 194
        int tag;
        for( dp = ((ElfW(Dyn) *)(&_DYNAMIC)); (tag = dp->d_tag) != 0; dp++ ) {
195 196 197 198 199 200 201
            if (tag == DT_DEBUG) {
                struct r_debug *rd = (struct r_debug *)dp->d_un.d_ptr;
                if (rd != NULL) {
                    struct link_map *lm = rd->r_map;
                    if (lm != NULL)
                        cachedResult = lm->l_next; /* might be NULL */
                }
eg's avatar
eg committed
202 203 204 205 206 207 208
                break;
            }
        }
    }
    return cachedResult;
}

209
#endif /* SOLARISDL ... */
eg's avatar
eg committed
210 211

/* BTL: added to fix circular dlopen definition if GC_SOLARIS_THREADS defined */
212
# ifdef GC_MUST_RESTORE_REDEFINED_DLOPEN
eg's avatar
eg committed
213 214 215
#   define dlopen GC_dlopen
# endif

216
# if defined(SOLARISDL)
217 218 219 220 221

/* Add dynamic library data sections to the root set.           */
# if !defined(PCR) && !defined(GC_SOLARIS_THREADS) && defined(THREADS) \
     && !defined(CPPCHECK)
#   error Fix mutual exclusion with dlopen
eg's avatar
eg committed
222 223 224
# endif

# ifndef USE_PROC_FOR_LIBRARIES
225
GC_INNER void GC_register_dynamic_libraries(void)
eg's avatar
eg committed
226
{
227
  struct link_map *lm;
eg's avatar
eg committed
228

229 230
  for (lm = GC_FirstDLOpenedLinkMap(); lm != 0; lm = lm->l_next) {
        ElfW(Ehdr) * e;
eg's avatar
eg committed
231 232 233
        ElfW(Phdr) * p;
        unsigned long offset;
        char * start;
234 235 236
        int i;

        e = (ElfW(Ehdr) *) lm->l_addr;
eg's avatar
eg committed
237 238
        p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
        offset = ((unsigned long)(lm->l_addr));
239
        for( i = 0; i < (int)e->e_phnum; i++, p++ ) {
eg's avatar
eg committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
          switch( p->p_type ) {
            case PT_LOAD:
              {
                if( !(p->p_flags & PF_W) ) break;
                start = ((char *)(p->p_vaddr)) + offset;
                GC_add_roots_inner(
                  start,
                  start + p->p_memsz,
                  TRUE
                );
              }
              break;
            default:
              break;
          }
255
        }
eg's avatar
eg committed
256 257 258 259
    }
}

# endif /* !USE_PROC ... */
260
# endif /* SOLARISDL */
eg's avatar
eg committed
261

262 263 264 265
#if defined(SCO_ELF) || defined(DGUX) || defined(HURD) \
    || (defined(__ELF__) && (defined(LINUX) || defined(FREEBSD) \
                             || defined(NACL) || defined(NETBSD) \
                             || defined(OPENBSD)))
eg's avatar
eg committed
266 267 268 269 270 271 272 273 274 275 276

#ifdef USE_PROC_FOR_LIBRARIES

#include <string.h>

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define MAPS_BUF_SIZE (32*1024)

277 278
/* Sort an array of HeapSects by start address.                         */
/* Unfortunately at least some versions of                              */
279
/* Linux qsort end up calling malloc by way of sysconf, and hence can't */
280 281 282
/* be used in the collector.  Hence we roll our own.  Should be         */
/* reasonably fast if the array is already mostly sorted, as we expect  */
/* it to be.                                                            */
283
static void sort_heap_sects(struct HeapSect *base, size_t number_of_elements)
284 285 286 287 288
{
    signed_word n = (signed_word)number_of_elements;
    signed_word nsorted = 1;

    while (nsorted < n) {
289 290
      signed_word i;

291
      while (nsorted < n &&
292
             (word)base[nsorted-1].hs_start < (word)base[nsorted].hs_start)
293 294
          ++nsorted;
      if (nsorted == n) break;
295
      GC_ASSERT((word)base[nsorted-1].hs_start > (word)base[nsorted].hs_start);
296
      i = nsorted - 1;
297
      while (i >= 0 && (word)base[i].hs_start > (word)base[i+1].hs_start) {
298
        struct HeapSect tmp = base[i];
299 300 301
        base[i] = base[i+1];
        base[i+1] = tmp;
        --i;
302
      }
303
      GC_ASSERT((word)base[nsorted-1].hs_start < (word)base[nsorted].hs_start);
304 305 306 307
      ++nsorted;
    }
}

308
STATIC word GC_register_map_entries(char *maps)
eg's avatar
eg committed
309
{
310
    char *prot;
eg's avatar
eg committed
311
    char *buf_ptr = maps;
312
    ptr_t start, end;
eg's avatar
eg committed
313
    unsigned int maj_dev;
314
    ptr_t least_ha, greatest_ha;
eg's avatar
eg committed
315 316
    unsigned i;

317 318 319 320
    GC_ASSERT(I_HOLD_LOCK());
    sort_heap_sects(GC_our_memory, GC_n_memory);
    least_ha = GC_our_memory[0].hs_start;
    greatest_ha = GC_our_memory[GC_n_memory-1].hs_start
321
                  + GC_our_memory[GC_n_memory-1].hs_bytes;
eg's avatar
eg committed
322

eg's avatar
eg committed
323
    for (;;) {
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
        buf_ptr = GC_parse_map_entry(buf_ptr, &start, &end, &prot,
                                     &maj_dev, 0);
        if (buf_ptr == NULL) return 1;
        if (prot[1] == 'w') {
            /* This is a writable mapping.  Add it to           */
            /* the root set unless it is already otherwise      */
            /* accounted for.                                   */
            if ((word)start <= (word)GC_stackbottom
                && (word)end >= (word)GC_stackbottom) {
                /* Stack mapping; discard       */
                continue;
            }
#           ifdef THREADS
              /* This may fail, since a thread may already be           */
              /* unregistered, but its thread stack may still be there. */
              /* That can fail because the stack may disappear while    */
              /* we're marking.  Thus the marker is, and has to be      */
              /* prepared to recover from segmentation faults.          */

              if (GC_segment_is_thread_stack(start, end)) continue;

              /* FIXME: NPTL squirrels                                  */
              /* away pointers in pieces of the stack segment that we   */
              /* don't scan.  We work around this                       */
              /* by treating anything allocated by libpthread as        */
              /* uncollectible, as we do in some other cases.           */
              /* A specifically identified problem is that              */
              /* thread stacks contain pointers to dynamic thread       */
              /* vectors, which may be reused due to thread caching.    */
              /* They may not be marked if the thread is still live.    */
              /* This specific instance should be addressed by          */
              /* INCLUDE_LINUX_THREAD_DESCR, but that doesn't quite     */
              /* seem to suffice.                                       */
              /* We currently trace entire thread stacks, if they are   */
              /* are currently cached but unused.  This is              */
              /* very suboptimal for performance reasons.               */
#           endif
            /* We no longer exclude the main data segment.              */
            if ((word)end <= (word)least_ha
                || (word)start >= (word)greatest_ha) {
              /* The easy case; just trace entire segment */
              GC_add_roots_inner((char *)start, (char *)end, TRUE);
              continue;
            }
            /* Add sections that don't belong to us. */
              i = 0;
              while ((word)(GC_our_memory[i].hs_start
                                + GC_our_memory[i].hs_bytes) < (word)start)
                  ++i;
              GC_ASSERT(i < GC_n_memory);
              if ((word)GC_our_memory[i].hs_start <= (word)start) {
                  start = GC_our_memory[i].hs_start
                          + GC_our_memory[i].hs_bytes;
                  ++i;
              }
              while (i < GC_n_memory
                     && (word)GC_our_memory[i].hs_start < (word)end
                     && (word)start < (word)end) {
                  if ((word)start < (word)GC_our_memory[i].hs_start)
                    GC_add_roots_inner((char *)start,
                                       GC_our_memory[i].hs_start, TRUE);
                  start = GC_our_memory[i].hs_start
                          + GC_our_memory[i].hs_bytes;
                  ++i;
              }
              if ((word)start < (word)end)
                  GC_add_roots_inner((char *)start, (char *)end, TRUE);
        }
eg's avatar
eg committed
392 393
    }
    return 1;
eg's avatar
eg committed
394 395
}

396
GC_INNER void GC_register_dynamic_libraries(void)
eg's avatar
eg committed
397
{
398
    if (!GC_register_map_entries(GC_get_maps()))
399
        ABORT("Failed to read /proc for library registration");
eg's avatar
eg committed
400
}
eg's avatar
eg committed
401

eg's avatar
eg committed
402
/* We now take care of the main data segment ourselves: */
403
GC_INNER GC_bool GC_register_main_static_data(void)
eg's avatar
eg committed
404
{
405
    return FALSE;
eg's avatar
eg committed
406 407
}

408
# define HAVE_REGISTER_MAIN_STATIC_DATA
eg's avatar
eg committed
409

410
#else /* !USE_PROC_FOR_LIBRARIES */
411

412 413 414
/* The following is the preferred way to walk dynamic libraries */
/* for glibc 2.2.4+.  Unfortunately, it doesn't work for older  */
/* versions.  Thanks to Jakub Jelinek for most of the code.     */
415

416 417 418 419 420 421 422 423 424 425 426 427
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) \
    || (__GLIBC__ == 2 && __GLIBC_MINOR__ == 2 && defined(DT_CONFIG)) \
    || defined(PLATFORM_ANDROID) /* Are others OK here, too? */
# ifndef HAVE_DL_ITERATE_PHDR
#   define HAVE_DL_ITERATE_PHDR
# endif
# ifdef PLATFORM_ANDROID
    /* Android headers might have no such definition for some targets.  */
    int dl_iterate_phdr(int (*cb)(struct dl_phdr_info *, size_t, void *),
                        void *data);
# endif
#endif /* __GLIBC__ >= 2 || PLATFORM_ANDROID */
428

429 430 431 432 433 434 435 436 437 438 439 440 441
#if (defined(FREEBSD) && __FreeBSD__ >= 7) || defined(__DragonFly__)
  /* On the FreeBSD system, any target system at major version 7 shall   */
  /* have dl_iterate_phdr; therefore, we need not make it weak as below. */
# ifndef HAVE_DL_ITERATE_PHDR
#   define HAVE_DL_ITERATE_PHDR
# endif
# define DL_ITERATE_PHDR_STRONG
#elif defined(HAVE_DL_ITERATE_PHDR)
  /* We have the header files for a glibc that includes dl_iterate_phdr.*/
  /* It may still not be available in the library on the target system. */
  /* Thus we also treat it as a weak symbol.                            */
# pragma weak dl_iterate_phdr
#endif
442

443
#if defined(HAVE_DL_ITERATE_PHDR)
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
# ifdef PT_GNU_RELRO
/* Instead of registering PT_LOAD sections directly, we keep them       */
/* in a temporary list, and filter them by excluding PT_GNU_RELRO       */
/* segments.  Processing PT_GNU_RELRO sections with                     */
/* GC_exclude_static_roots instead would be superficially cleaner.  But */
/* it runs into trouble if a client registers an overlapping segment,   */
/* which unfortunately seems quite possible.                            */

#   define MAX_LOAD_SEGS MAX_ROOT_SETS

    static struct load_segment {
      ptr_t start;
      ptr_t end;
      /* Room for a second segment if we remove a RELRO segment */
      /* from the middle.                                       */
      ptr_t start2;
      ptr_t end2;
    } load_segs[MAX_LOAD_SEGS];

    static int n_load_segs;
    static GC_bool load_segs_overflow;
466 467
# endif /* PT_GNU_RELRO */

468 469
STATIC int GC_register_dynlib_callback(struct dl_phdr_info * info,
                                       size_t size, void * ptr)
eg's avatar
eg committed
470 471
{
  const ElfW(Phdr) * p;
472 473
  ptr_t start, end;
  int i;
eg's avatar
eg committed
474 475 476 477 478 479 480

  /* Make sure struct dl_phdr_info is at least as big as we need.  */
  if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
      + sizeof (info->dlpi_phnum))
    return -1;

  p = info->dlpi_phdr;
481 482 483 484 485 486 487 488 489
  for (i = 0; i < (int)info->dlpi_phnum; i++, p++) {
    if (p->p_type == PT_LOAD) {
      GC_has_static_roots_func callback = GC_has_static_roots;
      if ((p->p_flags & PF_W) == 0) continue;

      start = (ptr_t)p->p_vaddr + info->dlpi_addr;
      end = start + p->p_memsz;
      if (callback != 0 && !callback(info->dlpi_name, start, p->p_memsz))
        continue;
490
#     ifdef PT_GNU_RELRO
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
#       if CPP_WORDSZ == 64
          /* TODO: GC_push_all eventually does the correct          */
          /* rounding to the next multiple of ALIGNMENT, so, most   */
          /* probably, we should remove the corresponding assertion */
          /* check in GC_add_roots_inner along with this code line. */
          /* start pointer value may require aligning.              */
          start = (ptr_t)((word)start & ~(word)(sizeof(word) - 1));
#       endif
        if (n_load_segs >= MAX_LOAD_SEGS) {
          if (!load_segs_overflow) {
            WARN("Too many PT_LOAD segments;"
                 " registering as roots directly...\n", 0);
            load_segs_overflow = TRUE;
          }
          GC_add_roots_inner(start, end, TRUE);
        } else {
          load_segs[n_load_segs].start = start;
          load_segs[n_load_segs].end = end;
          load_segs[n_load_segs].start2 = 0;
          load_segs[n_load_segs].end2 = 0;
          ++n_load_segs;
        }
#     else
        GC_add_roots_inner(start, end, TRUE);
#     endif /* !PT_GNU_RELRO */
eg's avatar
eg committed
516 517 518
    }
  }

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
# ifdef PT_GNU_RELRO
    p = info->dlpi_phdr;
    for (i = 0; i < (int)info->dlpi_phnum; i++, p++) {
      if (p->p_type == PT_GNU_RELRO) {
        /* This entry is known to be constant and will eventually be    */
        /* remapped as read-only.  However, the address range covered   */
        /* by this entry is typically a subset of a previously          */
        /* encountered "LOAD" segment, so we need to exclude it.        */
        int j;

        start = (ptr_t)p->p_vaddr + info->dlpi_addr;
        end = start + p->p_memsz;
        for (j = n_load_segs; --j >= 0; ) {
          if ((word)start >= (word)load_segs[j].start
              && (word)start < (word)load_segs[j].end) {
            if (load_segs[j].start2 != 0) {
              WARN("More than one GNU_RELRO segment per load one\n",0);
            } else {
              GC_ASSERT((word)end <= (word)load_segs[j].end);
              /* Remove from the existing load segment */
              load_segs[j].end2 = load_segs[j].end;
              load_segs[j].end = start;
              load_segs[j].start2 = end;
            }
            break;
          }
          if (0 == j && 0 == GC_has_static_roots)
            WARN("Failed to find PT_GNU_RELRO segment"
                 " inside PT_LOAD region\n", 0);
            /* No warning reported in case of the callback is present   */
            /* because most likely the segment has been excluded.       */
        }
      }
    }
# endif
eg's avatar
eg committed
554

555 556 557
  *(int *)ptr = 1;     /* Signal that we were called */
  return 0;
}
eg's avatar
eg committed
558

559 560 561 562 563 564 565 566 567 568 569
/* Do we need to separately register the main static data segment? */
GC_INNER GC_bool GC_register_main_static_data(void)
{
# ifdef DL_ITERATE_PHDR_STRONG
    /* If dl_iterate_phdr is not a weak symbol then don't test against  */
    /* zero (otherwise a compiler might issue a warning).               */
    return FALSE;
# else
    return 0 == COVERT_DATAFLOW(dl_iterate_phdr);
# endif
}
570

571 572
/* Return TRUE if we succeed, FALSE if dl_iterate_phdr wasn't there. */
STATIC GC_bool GC_register_dynamic_libraries_dl_iterate_phdr(void)
eg's avatar
eg committed
573
{
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
  int did_something;
  if (GC_register_main_static_data())
    return FALSE;

# ifdef PT_GNU_RELRO
    {
      static GC_bool excluded_segs = FALSE;
      n_load_segs = 0;
      load_segs_overflow = FALSE;
      if (!EXPECT(excluded_segs, TRUE)) {
        GC_exclude_static_roots_inner((ptr_t)load_segs,
                                      (ptr_t)load_segs + sizeof(load_segs));
        excluded_segs = TRUE;
      }
    }
# endif
590

591 592 593
  did_something = 0;
  dl_iterate_phdr(GC_register_dynlib_callback, &did_something);
  if (did_something) {
594
#   ifdef PT_GNU_RELRO
595 596 597 598 599 600 601 602
      int i;

      for (i = 0; i < n_load_segs; ++i) {
        if ((word)load_segs[i].end > (word)load_segs[i].start) {
          GC_add_roots_inner(load_segs[i].start, load_segs[i].end, TRUE);
        }
        if ((word)load_segs[i].end2 > (word)load_segs[i].start2) {
          GC_add_roots_inner(load_segs[i].start2, load_segs[i].end2, TRUE);
603
        }
604
      }
605
#   endif
606 607 608 609 610 611 612 613 614
  } else {
      char *datastart;
      char *dataend;
#     ifdef DATASTART_IS_FUNC
        static ptr_t datastart_cached = (ptr_t)(word)-1;

        /* Evaluate DATASTART only once.  */
        if (datastart_cached == (ptr_t)(word)-1) {
          datastart_cached = DATASTART;
615
        }
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
        datastart = (char *)datastart_cached;
#     else
        datastart = DATASTART;
#     endif
#     ifdef DATAEND_IS_FUNC
        {
          static ptr_t dataend_cached = 0;
          /* Evaluate DATAEND only once. */
          if (dataend_cached == 0) {
            dataend_cached = DATAEND;
          }
          dataend = (char *)dataend_cached;
        }
#     else
        dataend = DATAEND;
#     endif
      if (NULL == *(char * volatile *)&datastart
          || (word)datastart > (word)dataend)
        ABORT_ARG2("Wrong DATASTART/END pair",
                   ": %p .. %p", (void *)datastart, (void *)dataend);

      /* dl_iterate_phdr may forget the static data segment in  */
      /* statically linked executables.                         */
      GC_add_roots_inner(datastart, dataend, TRUE);
#     ifdef GC_HAVE_DATAREGION2
        if ((word)DATASTART2 - 1U >= (word)DATAEND2) {
                        /* Subtract one to check also for NULL  */
                        /* without a compiler warning.          */
          ABORT_ARG2("Wrong DATASTART/END2 pair",
                     ": %p .. %p", (void *)DATASTART2, (void *)DATAEND2);
        }
        GC_add_roots_inner(DATASTART2, DATAEND2, TRUE);
648
#     endif
eg's avatar
eg committed
649
  }
650
  return TRUE;
eg's avatar
eg committed
651 652
}

653
# define HAVE_REGISTER_MAIN_STATIC_DATA
eg's avatar
eg committed
654

655
#else /* !HAVE_DL_ITERATE_PHDR */
eg's avatar
eg committed
656 657

/* Dynamic loading code for Linux running ELF. Somewhat tested on
658
 * Linux/x86, untested but hopefully should work on Linux/Alpha.
eg's avatar
eg committed
659 660 661 662
 * This code was derived from the Solaris/ELF support. Thanks to
 * whatever kind soul wrote that.  - Patrick Bridges */

/* This doesn't necessarily work in all cases, e.g. with preloaded
663
 * dynamic libraries.                                           */
eg's avatar
eg committed
664

665 666 667 668 669 670 671 672 673 674 675 676 677
# if defined(NETBSD) || defined(OPENBSD)
#   include <sys/exec_elf.h>
   /* for compatibility with 1.4.x */
#   ifndef DT_DEBUG
#     define DT_DEBUG   21
#   endif
#   ifndef PT_LOAD
#     define PT_LOAD    1
#   endif
#   ifndef PF_W
#     define PF_W       2
#   endif
# elif !defined(PLATFORM_ANDROID)
eg's avatar
eg committed
678
#  include <elf.h>
679
# endif
eg's avatar
eg committed
680

681 682
# ifndef PLATFORM_ANDROID
#   include <link.h>
eg's avatar
eg committed
683 684
# endif

685 686
#endif /* !HAVE_DL_ITERATE_PHDR */

eg's avatar
eg committed
687 688 689 690 691
#ifdef __GNUC__
# pragma weak _DYNAMIC
#endif
extern ElfW(Dyn) _DYNAMIC[];

692
STATIC struct link_map *
693
GC_FirstDLOpenedLinkMap(void)
eg's avatar
eg committed
694 695 696
{
    static struct link_map *cachedResult = 0;

697 698
    if (0 == COVERT_DATAFLOW(_DYNAMIC)) {
        /* _DYNAMIC symbol not resolved. */
eg's avatar
eg committed
699 700 701
        return(0);
    }
    if( cachedResult == 0 ) {
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
#     if defined(NETBSD) && defined(RTLD_DI_LINKMAP)
#       if defined(CPPCHECK)
#         define GC_RTLD_DI_LINKMAP 2
#       else
#         define GC_RTLD_DI_LINKMAP RTLD_DI_LINKMAP
#       endif
        struct link_map *lm = NULL;
        if (!dlinfo(RTLD_SELF, GC_RTLD_DI_LINKMAP, &lm) && lm != NULL) {
            /* Now lm points link_map object of libgc.  Since it    */
            /* might not be the first dynamically linked object,    */
            /* try to find it (object next to the main object).     */
            while (lm->l_prev != NULL) {
                lm = lm->l_prev;
            }
            cachedResult = lm->l_next;
        }
#     else
        ElfW(Dyn) *dp;
eg's avatar
eg committed
720
        int tag;
721

eg's avatar
eg committed
722
        for( dp = _DYNAMIC; (tag = dp->d_tag) != 0; dp++ ) {
723 724 725 726 727 728 729 730
            if (tag == DT_DEBUG) {
                struct r_debug *rd = (struct r_debug *)dp->d_un.d_ptr;
                /* d_ptr could be null if libs are linked statically. */
                if (rd != NULL) {
                    struct link_map *lm = rd->r_map;
                    if (lm != NULL)
                        cachedResult = lm->l_next; /* might be NULL */
                }
eg's avatar
eg committed
731 732 733
                break;
            }
        }
734
#     endif /* !NETBSD || !RTLD_DI_LINKMAP */
eg's avatar
eg committed
735 736 737 738
    }
    return cachedResult;
}

739
GC_INNER void GC_register_dynamic_libraries(void)
eg's avatar
eg committed
740 741 742 743 744
{
  struct link_map *lm;

# ifdef HAVE_DL_ITERATE_PHDR
    if (GC_register_dynamic_libraries_dl_iterate_phdr()) {
745
        return;
eg's avatar
eg committed
746 747
    }
# endif
748
  for (lm = GC_FirstDLOpenedLinkMap(); lm != 0; lm = lm->l_next)
eg's avatar
eg committed
749
    {
750
        ElfW(Ehdr) * e;
eg's avatar
eg committed
751 752 753
        ElfW(Phdr) * p;
        unsigned long offset;
        char * start;
754 755 756 757 758 759 760
        int i;

        e = (ElfW(Ehdr) *) lm->l_addr;
#       ifdef PLATFORM_ANDROID
          if (e == NULL)
            continue;
#       endif
eg's avatar
eg committed
761 762
        p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
        offset = ((unsigned long)(lm->l_addr));
763
        for( i = 0; i < (int)e->e_phnum; i++, p++ ) {
eg's avatar
eg committed
764 765 766 767 768 769 770 771 772 773 774
          switch( p->p_type ) {
            case PT_LOAD:
              {
                if( !(p->p_flags & PF_W) ) break;
                start = ((char *)(p->p_vaddr)) + offset;
                GC_add_roots_inner(start, start + p->p_memsz, TRUE);
              }
              break;
            default:
              break;
          }
775
        }
eg's avatar
eg committed
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    }
}

#endif /* !USE_PROC_FOR_LIBRARIES */

#endif /* LINUX */

#if defined(IRIX5) || (defined(USE_PROC_FOR_LIBRARIES) && !defined(LINUX))

#include <sys/procfs.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <elf.h>
#include <errno.h>
#include <signal.h>  /* Only for the following test. */
#ifndef _sigargs
# define IRIX6
#endif

795 796 797 798
/* We use /proc to track down all parts of the address space that are   */
/* mapped by the process, and throw out regions we know we shouldn't    */
/* worry about.  This may also work under other SVR4 variants.          */
GC_INNER void GC_register_dynamic_libraries(void)
eg's avatar
eg committed
799 800 801 802
{
    static int fd = -1;
    char buf[30];
    static prmap_t * addr_map = 0;
803 804
    static int current_sz = 0;  /* Number of records currently in addr_map */
    int needed_sz = 0;          /* Required size of addr_map            */
eg's avatar
eg committed
805 806 807 808
    int i;
    long flags;
    ptr_t start;
    ptr_t limit;
809
    ptr_t heap_start = HEAP_START;
eg's avatar
eg committed
810 811
    ptr_t heap_end = heap_start;

812
#   ifdef SOLARISDL
eg's avatar
eg committed
813
#     define MA_PHYS 0
814
#   endif /* SOLARISDL */
eg's avatar
eg committed
815 816

    if (fd < 0) {
817 818 819 820
      (void)snprintf(buf, sizeof(buf), "/proc/%ld", (long)getpid());
      buf[sizeof(buf) - 1] = '\0';
        /* The above generates a lint complaint, since pid_t varies.    */
        /* It's unclear how to improve this.                            */
eg's avatar
eg committed
821 822
      fd = open(buf, O_RDONLY);
      if (fd < 0) {
823
        ABORT("/proc open failed");
eg's avatar
eg committed
824 825 826
      }
    }
    if (ioctl(fd, PIOCNMAP, &needed_sz) < 0) {
827 828
        ABORT_ARG2("/proc PIOCNMAP ioctl failed",
                   ": fd = %d, errno = %d", fd, errno);
eg's avatar
eg committed
829 830
    }
    if (needed_sz >= current_sz) {
831 832
        GC_scratch_recycle_no_gww(addr_map,
                                  (size_t)current_sz * sizeof(prmap_t));
eg's avatar
eg committed
833
        current_sz = needed_sz * 2 + 1;
834 835 836 837 838
                        /* Expansion, plus room for 0 record */
        addr_map = (prmap_t *)GC_scratch_alloc(
                                (size_t)current_sz * sizeof(prmap_t));
        if (addr_map == NULL)
          ABORT("Insufficient memory for address map");
eg's avatar
eg committed
839 840
    }
    if (ioctl(fd, PIOCMAP, addr_map) < 0) {
841 842 843
        ABORT_ARG3("/proc PIOCMAP ioctl failed",
                   ": errcode= %d, needed_sz= %d, addr_map= %p",
                   errno, needed_sz, (void *)addr_map);
eg's avatar
eg committed
844 845
    };
    if (GC_n_heap_sects > 0) {
846 847 848 849
        heap_end = GC_heap_sects[GC_n_heap_sects-1].hs_start
                        + GC_heap_sects[GC_n_heap_sects-1].hs_bytes;
        if ((word)heap_end < (word)GC_scratch_last_end_ptr)
          heap_end = GC_scratch_last_end_ptr;
eg's avatar
eg committed
850 851 852
    }
    for (i = 0; i < needed_sz; i++) {
        flags = addr_map[i].pr_mflags;
853 854
        if ((flags & (MA_BREAK | MA_STACK | MA_PHYS
                      | MA_FETCHOP | MA_NOTCACHED)) != 0) goto irrelevant;
eg's avatar
eg committed
855 856
        if ((flags & (MA_READ | MA_WRITE)) != (MA_READ | MA_WRITE))
            goto irrelevant;
857 858 859 860 861
          /* The latter test is empirically useless in very old Irix    */
          /* versions.  Other than the                                  */
          /* main data and stack segments, everything appears to be     */
          /* mapped readable, writable, executable, and shared(!!).     */
          /* This makes no sense to me. - HB                            */
eg's avatar
eg committed
862 863
        start = (ptr_t)(addr_map[i].pr_vaddr);
        if (GC_roots_present(start)) goto irrelevant;
864 865
        if ((word)start < (word)heap_end && (word)start >= (word)heap_start)
                goto irrelevant;
eg's avatar
eg committed
866 867

        limit = start + addr_map[i].pr_size;
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
        /* The following seemed to be necessary for very old versions   */
        /* of Irix, but it has been reported to discard relevant        */
        /* segments under Irix 6.5.                                     */
#       ifndef IRIX6
          if (addr_map[i].pr_off == 0 && strncmp(start, ELFMAG, 4) == 0) {
            /* Discard text segments, i.e. 0-offset mappings against    */
            /* executable files which appear to have ELF headers.       */
            caddr_t arg;
            int obj;
#           define MAP_IRR_SZ 10
            static ptr_t map_irr[MAP_IRR_SZ];
                                        /* Known irrelevant map entries */
            static int n_irr = 0;
            struct stat buf;
            register int j;

            for (j = 0; j < n_irr; j++) {
                if (map_irr[j] == start) goto irrelevant;
            }
            arg = (caddr_t)start;
            obj = ioctl(fd, PIOCOPENM, &arg);
            if (obj >= 0) {
                fstat(obj, &buf);
                close(obj);
                if ((buf.st_mode & 0111) != 0) {
                    if (n_irr < MAP_IRR_SZ) {
                        map_irr[n_irr++] = start;
                    }
                    goto irrelevant;
                }
            }
          }
#       endif /* !IRIX6 */
eg's avatar
eg committed
901 902 903
        GC_add_roots_inner(start, limit, TRUE);
      irrelevant: ;
    }
904 905 906 907
    /* Don't keep cached descriptor, for now.  Some kernels don't like us */
    /* to keep a /proc file descriptor around during kill -9.             */
        if (close(fd) < 0) ABORT("Couldn't close /proc file");
        fd = -1;
eg's avatar
eg committed
908 909 910 911
}

# endif /* USE_PROC || IRIX5 */

912
# if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
eg's avatar
eg committed
913

914 915 916
# ifndef WIN32_LEAN_AND_MEAN
#   define WIN32_LEAN_AND_MEAN 1
# endif
eg's avatar
eg committed
917 918 919 920
# define NOSERVICE
# include <windows.h>
# include <stdlib.h>

921 922 923 924 925
  /* We traverse the entire address space and register all segments     */
  /* that could possibly have been written to.                          */
  STATIC void GC_cond_add_roots(char *base, char * limit)
  {
#   ifdef GC_WIN32_THREADS
eg's avatar
eg committed
926 927 928
      char * curr_base = base;
      char * next_stack_lo;
      char * next_stack_hi;
929

eg's avatar
eg committed
930 931
      if (base == limit) return;
      for(;;) {
932 933 934 935 936
          GC_get_next_stack(curr_base, limit, &next_stack_lo, &next_stack_hi);
          if ((word)next_stack_lo >= (word)limit) break;
          if ((word)next_stack_lo > (word)curr_base)
            GC_add_roots_inner(curr_base, next_stack_lo, TRUE);
          curr_base = next_stack_hi;
eg's avatar
eg committed
937
      }
938 939 940
      if ((word)curr_base < (word)limit)
        GC_add_roots_inner(curr_base, limit, TRUE);
#   else
eg's avatar
eg committed
941
      char * stack_top
942 943 944
         = (char *)((word)GC_approx_sp() &
                    ~(word)(GC_sysinfo.dwAllocationGranularity - 1));

eg's avatar
eg committed
945
      if (base == limit) return;
946 947 948 949
      if ((word)limit > (word)stack_top
          && (word)base < (word)GC_stackbottom) {
          /* Part of the stack; ignore it. */
          return;
eg's avatar
eg committed
950 951
      }
      GC_add_roots_inner(base, limit, TRUE);
952
#   endif
953
  }
eg's avatar
eg committed
954

955 956 957
#ifdef DYNAMIC_LOADING
  /* GC_register_main_static_data is not needed unless DYNAMIC_LOADING. */
  GC_INNER GC_bool GC_register_main_static_data(void)
958
  {
959 960 961 962 963 964
#   if defined(MSWINCE) || defined(CYGWIN32)
      /* Do we need to separately register the main static data segment? */
      return FALSE;
#   else
      return GC_no_win32_dlls;
#   endif
965
  }
eg's avatar
eg committed
966
# define HAVE_REGISTER_MAIN_STATIC_DATA
967
#endif /* DYNAMIC_LOADING */
eg's avatar
eg committed
968 969 970 971

# ifdef DEBUG_VIRTUALQUERY
  void GC_dump_meminfo(MEMORY_BASIC_INFORMATION *buf)
  {
972 973 974 975 976 977
    GC_printf("BaseAddress = 0x%lx, AllocationBase = 0x%lx,"
              " RegionSize = 0x%lx(%lu)\n", buf -> BaseAddress,
              buf -> AllocationBase, buf -> RegionSize, buf -> RegionSize);
    GC_printf("\tAllocationProtect = 0x%lx, State = 0x%lx, Protect = 0x%lx, "
              "Type = 0x%lx\n", buf -> AllocationProtect, buf -> State,
              buf -> Protect, buf -> Type);
eg's avatar
eg committed
978 979 980
  }
# endif /* DEBUG_VIRTUALQUERY */

981 982 983 984 985 986 987 988 989
# if defined(MSWINCE) || defined(CYGWIN32)
    /* FIXME: Should we really need to scan MEM_PRIVATE sections?       */
    /* For now, we don't add MEM_PRIVATE sections to the data roots for */
    /* WinCE because otherwise SEGV fault sometimes happens to occur in */
    /* GC_mark_from() (and, even if we use WRAP_MARK_SOME, WinCE prints */
    /* a "Data Abort" message to the debugging console).                */
    /* To workaround that, use -DGC_REGISTER_MEM_PRIVATE.               */
#   define GC_wnt TRUE
# endif
990

991
  GC_INNER void GC_register_dynamic_libraries(void)
eg's avatar
eg committed
992 993 994 995 996 997 998 999 1000 1001 1002
  {
    MEMORY_BASIC_INFORMATION buf;
    DWORD protect;
    LPVOID p;
    char * base;
    char * limit, * new_limit;

#   ifdef MSWIN32
      if (GC_no_win32_dlls) return;
#   endif
    base = limit = p = GC_sysinfo.lpMinimumApplicationAddress;
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    while ((word)p < (word)GC_sysinfo.lpMaximumApplicationAddress) {
        size_t result = VirtualQuery(p, &buf, sizeof(buf));

#       ifdef MSWINCE
          if (result == 0) {
            /* Page is free; advance to the next possible allocation base */
            new_limit = (char *)
                (((DWORD) p + GC_sysinfo.dwAllocationGranularity)
                 & ~(GC_sysinfo.dwAllocationGranularity-1));
          } else
#       endif
        /* else */ {
            if (result != sizeof(buf)) {
                ABORT("Weird VirtualQuery result");
            }
            new_limit = (char *)p + buf.RegionSize;
            protect = buf.Protect;
            if (buf.State == MEM_COMMIT
                && (protect == PAGE_EXECUTE_READWRITE
                    || protect == PAGE_READWRITE)
                && (buf.Type == MEM_IMAGE
#                   ifdef GC_REGISTER_MEM_PRIVATE
                      || (protect == PAGE_READWRITE && buf.Type == MEM_PRIVATE)
#                   else
                      /* There is some evidence that we cannot always   */
                      /* ignore MEM_PRIVATE sections under Windows ME   */
                      /* and predecessors.  Hence we now also check for */
                      /* that case.                                     */
                      || (!GC_wnt && buf.Type == MEM_PRIVATE)
#                   endif
                   )
                && !GC_is_heap_base(buf.AllocationBase)) {
#               ifdef DEBUG_VIRTUALQUERY
                  GC_dump_meminfo(&buf);
#               endif
                if ((char *)p != limit) {
                    GC_cond_add_roots(base, limit);
                    base = p;
                }
                limit = new_limit;
            }
        }
        if ((word)p > (word)new_limit /* overflow */) break;
eg's avatar
eg committed
1046 1047 1048 1049 1050
        p = (LPVOID)new_limit;
    }
    GC_cond_add_roots(base, limit);
  }

1051
#endif /* MSWIN32 || MSWINCE || CYGWIN32 */
1052

eg's avatar
eg committed
1053 1054 1055 1056
#if defined(ALPHA) && defined(OSF1)

#include <loader.h>

1057 1058 1059 1060 1061
extern char *sys_errlist[];
extern int sys_nerr;
extern int errno;

GC_INNER void GC_register_dynamic_libraries(void)
eg's avatar
eg committed
1062
{
1063 1064 1065
  ldr_module_t moduleid = LDR_NULL_MODULE;
  ldr_process_t mypid = ldr_my_process(); /* obtain id of this process */

eg's avatar
eg committed
1066 1067
  /* For each module */
    while (TRUE) {
1068 1069 1070 1071 1072 1073 1074
      ldr_module_info_t moduleinfo;
      size_t modulereturnsize;
      ldr_region_t region;
      ldr_region_info_t regioninfo;
      size_t regionreturnsize;
      int status = ldr_next_module(mypid, &moduleid);
                                /* Get the next (first) module */
eg's avatar
eg committed
1075 1076 1077 1078 1079

      /* Any more modules? */
        if (moduleid == LDR_NULL_MODULE)
            break;    /* No more modules */

1080 1081 1082 1083 1084 1085
      /* Check status AFTER checking moduleid because       */
      /* of a bug in the non-shared ldr_next_module stub.   */
        if (status != 0) {
          ABORT_ARG3("ldr_next_module failed",
                     ": status= %d, errcode= %d (%s)", status, errno,
                     errno < sys_nerr ? sys_errlist[errno] : "");
eg's avatar
eg committed
1086 1087 1088 1089
        }

      /* Get the module information */
        status = ldr_inq_module(mypid, moduleid, &moduleinfo,
1090
                                sizeof(moduleinfo), &modulereturnsize);
eg's avatar
eg committed
1091 1092 1093 1094 1095 1096 1097
        if (status != 0 )
            ABORT("ldr_inq_module failed");

      /* is module for the main program (i.e. nonshared portion)? */
          if (moduleinfo.lmi_flags & LDR_MAIN)
              continue;    /* skip the main module */

eg's avatar
eg committed
1098
#     ifdef DL_VERBOSE
1099 1100 1101 1102 1103
        GC_log_printf("---Module---\n");
        GC_log_printf("Module ID\t = %16ld\n", moduleinfo.lmi_modid);
        GC_log_printf("Count of regions = %16d\n", moduleinfo.lmi_nregion);
        GC_log_printf("flags for module = %16lx\n", moduleinfo.lmi_flags);
        GC_log_printf("module pathname\t = \"%s\"\n", moduleinfo.lmi_name);
eg's avatar
eg committed
1104 1105 1106 1107 1108 1109
#     endif

      /* For each region in this module */
        for (region = 0; region < moduleinfo.lmi_nregion; region++) {
          /* Get the region information */
            status = ldr_inq_region(mypid, moduleid, region, &regioninfo,
1110
                                    sizeof(regioninfo), &regionreturnsize);
eg's avatar
eg committed
1111 1112 1113 1114 1115 1116 1117
            if (status != 0 )
                ABORT("ldr_inq_region failed");

          /* only process writable (data) regions */
            if (! (regioninfo.lri_prot & LDR_W))
                continue;

eg's avatar
eg committed
1118
#         ifdef DL_VERBOSE
1119 1120 1121 1122 1123 1124 1125 1126 1127
            GC_log_printf("--- Region ---\n");
            GC_log_printf("Region number\t = %16ld\n",
                          regioninfo.lri_region_no);
            GC_log_printf("Protection flags = %016x\n", regioninfo.lri_prot);
            GC_log_printf("Virtual address\t = %16p\n", regioninfo.lri_vaddr);
            GC_log_printf("Mapped address\t = %16p\n",
                          regioninfo.lri_mapaddr);
            GC_log_printf("Region size\t = %16ld\n", regioninfo.lri_size);
            GC_log_printf("Region name\t = \"%s\"\n", regioninfo.lri_name);
eg's avatar
eg committed
1128 1129 1130
#         endif

          /* register region as a garbage collection root */
1131 1132 1133
          GC_add_roots_inner((char *)regioninfo.lri_mapaddr,
                        (char *)regioninfo.lri_mapaddr + regioninfo.lri_size,
                        TRUE);
eg's avatar
eg committed
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

        }
    }
}
#endif

#if defined(HPUX)

#include <errno.h>
#include <dl.h>

extern char *sys_errlist[];
extern int sys_nerr;

1148
GC_INNER void GC_register_dynamic_libraries(void)
eg's avatar
eg committed
1149 1150 1151 1152 1153
{
  int index = 1; /* Ordinal position in shared library search list */

  /* For each dynamic library loaded */
    while (TRUE) {
1154 1155 1156
      struct shl_descriptor *shl_desc; /* Shared library info, see dl.h */
      int status = shl_get(index, &shl_desc);
                                /* Get info about next shared library   */
eg's avatar
eg committed
1157

1158
      /* Check if this is the end of the list or if some error occurred */
eg's avatar
eg committed
1159
        if (status != 0) {
1160 1161 1162 1163 1164
#        ifdef GC_HPUX_THREADS
           /* I've seen errno values of 0.  The man page is not clear   */
           /* as to whether errno should get set on a -1 return.        */
           break;
#        else
eg's avatar
eg committed
1165
          if (errno == EINVAL) {
1166
            break; /* Moved past end of shared library list --> finished */
eg's avatar
eg committed
1167
          } else {
1168 1169 1170
            ABORT_ARG3("shl_get failed",
                       ": status= %d, errcode= %d (%s)", status, errno,
                       errno < sys_nerr ? sys_errlist[errno] : "");
eg's avatar
eg committed
1171
          }
1172
#        endif
eg's avatar
eg committed
1173 1174
        }

eg's avatar
eg committed
1175
#     ifdef DL_VERBOSE
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
        GC_log_printf("---Shared library---\n");
        GC_log_printf("\tfilename\t= \"%s\"\n", shl_desc->filename);
        GC_log_printf("\tindex\t\t= %d\n", index);
        GC_log_printf("\thandle\t\t= %08x\n",
                      (unsigned long) shl_desc->handle);
        GC_log_printf("\ttext seg.start\t= %08x\n", shl_desc->tstart);
        GC_log_printf("\ttext seg.end\t= %08x\n", shl_desc->tend);
        GC_log_printf("\tdata seg.start\t= %08x\n", shl_desc->dstart);
        GC_log_printf("\tdata seg.end\t= %08x\n", shl_desc->dend);
        GC_log_printf("\tref.count\t= %lu\n", shl_desc->ref_count);
eg's avatar
eg committed
1186 1187 1188 1189
#     endif

      /* register shared library's data segment as a garbage collection root */
        GC_add_roots_inner((char *) shl_desc->dstart,
1190
                           (char *) shl_desc->dend, TRUE);
eg's avatar
eg committed
1191 1192 1193 1194 1195 1196

        index++;
    }
}
#endif /* HPUX */

eg's avatar
eg committed
1197
#ifdef AIX
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
# pragma alloca
# include <sys/ldr.h>
# include <sys/errno.h>
  GC_INNER void GC_register_dynamic_libraries(void)
  {
      int ldibuflen = 8192;

      for (;;) {
        int len;
        struct ld_info *ldi;
#       if defined(CPPCHECK)
          char ldibuf[ldibuflen];
#       else
          char *ldibuf = alloca(ldibuflen);
#       endif

        len = loadquery(L_GETINFO, ldibuf, ldibuflen);
        if (len < 0) {
                if (errno != ENOMEM) {
                        ABORT("loadquery failed");
                }
                ldibuflen *= 2;
                continue;
        }

        ldi = (struct ld_info *)ldibuf;
        while (ldi) {
                len = ldi->ldinfo_next;
                GC_add_roots_inner(
                                ldi->ldinfo_dataorg,
                                (ptr_t)(unsigned long)ldi->ldinfo_dataorg
                                + ldi->ldinfo_datasize,
                                TRUE);
                ldi = len ? (struct ld_info *)((char *)ldi + len) : 0;
        }
        break;
      }
  }
eg's avatar
eg committed
1236
#endif /* AIX */
eg's avatar
eg committed
1237

eg's avatar
eg committed
1238
#ifdef DARWIN
eg's avatar
eg committed
1239

1240
/* __private_extern__ hack required for pre-3.4 gcc versions.   */
eg's avatar
eg committed
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
#ifndef __private_extern__
# define __private_extern__ extern
# include <mach-o/dyld.h>
# undef __private_extern__
#else
# include <mach-o/dyld.h>
#endif
#include <mach-o/getsect.h>

/*#define DARWIN_DEBUG*/

1252 1253 1254 1255
/* Writable sections generally available on Darwin.     */
STATIC const struct {
    const char *seg;
    const char *sect;
eg's avatar
eg committed
1256
} GC_dyld_sections[] = {
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
    { SEG_DATA, SECT_DATA },
    /* Used by FSF GCC, but not by OS X system tools, so far.   */
    { SEG_DATA, "__static_data" },
    { SEG_DATA, SECT_BSS },
    { SEG_DATA, SECT_COMMON },
    /* FSF GCC - zero-sized object sections for targets         */
    /*supporting section anchors.                               */
    { SEG_DATA, "__zobj_data" },
    { SEG_DATA, "__zobj_bss" }
};

/* Additional writable sections:                                */
/* GCC on Darwin constructs aligned sections "on demand", where */
/* the alignment size is embedded in the section name.          */
/* Furthermore, there are distinctions between sections         */
/* containing private vs. public symbols.  It also constructs   */
/* sections specifically for zero-sized objects, when the       */
/* target supports section anchors.                             */
STATIC const char * const GC_dyld_add_sect_fmts[] = {
  "__bss%u",
  "__pu_bss%u",
  "__zo_bss%u",
  "__zo_pu_bss%u"
eg's avatar
eg committed
1280
};
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

/* Currently, mach-o will allow up to the max of 2^15 alignment */
/* in an object file.                                           */
#ifndef L2_MAX_OFILE_ALIGNMENT
# define L2_MAX_OFILE_ALIGNMENT 15
#endif

STATIC const char *GC_dyld_name_for_hdr(const struct GC_MACH_HEADER *hdr)
{
    unsigned long i, c;
eg's avatar
eg committed
1291
    c = _dyld_image_count();
1292 1293
    for (i = 0; i < c; i++)
      if ((const struct GC_MACH_HEADER *)_dyld_get_image_header(i) == hdr)
eg's avatar
eg committed
1294 1295 1296
        return _dyld_get_image_name(i);
    return NULL;
}
1297 1298 1299 1300

/* This should never be called by a thread holding the lock.    */
STATIC void GC_dyld_image_add(const struct GC_MACH_HEADER *hdr,
                              intptr_t slide)
1301
{
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
  unsigned long start, end;
  unsigned i, j;
  const struct GC_MACH_SECTION *sec;
  const char *name;
  GC_has_static_roots_func callback = GC_has_static_roots;
  DCL_LOCK_STATE;

  if (GC_no_dls) return;
# ifdef DARWIN_DEBUG
    name = GC_dyld_name_for_hdr(hdr);
# else
    name = callback != 0 ? GC_dyld_name_for_hdr(hdr) : NULL;
# endif
  for (i = 0; i < sizeof(GC_dyld_sections)/sizeof(GC_dyld_sections[0]); i++) {
    sec = GC_GETSECTBYNAME(hdr, GC_dyld_sections[i].seg,
                           GC_dyld_sections[i].sect);
    if (sec == NULL || sec->size < sizeof(word))
      continue;
    start = slide + sec->addr;
    end = start + sec->size;
    LOCK();
    /* The user callback is called holding the lock.    */
    if (callback == 0 || callback(name, (void*)start, (size_t)sec->size)) {
#     ifdef DARWIN_DEBUG
        GC_log_printf(
              "Adding section __DATA,%s at %p-%p (%lu bytes) from image %s\n",
               GC_dyld_sections[i].sect, (void*)start, (void*)end,
               (unsigned long)sec->size, name);
#     endif
      GC_add_roots_inner((ptr_t)start, (ptr_t)end, FALSE);
    }
    UNLOCK();
  }

  /* Sections constructed on demand.    */
  for (j = 0; j < sizeof(GC_dyld_add_sect_fmts) / sizeof(char *); j++) {
    const char *fmt = GC_dyld_add_sect_fmts[j];

    /* Add our manufactured aligned BSS sections.       */
    for (i = 0; i <= L2_MAX_OFILE_ALIGNMENT; i++) {
      char secnam[16];

      (void)snprintf(secnam, sizeof(secnam), fmt, (unsigned)i);
      secnam[sizeof(secnam) - 1] = '\0';
      sec = GC_GETSECTBYNAME(hdr, SEG_DATA, secnam);
      if (sec == NULL || sec->size == 0)
        continue;
1349 1350
      start = slide + sec->addr;
      end = start + sec->size;
1351 1352 1353 1354 1355 1356 1357
#     ifdef DARWIN_DEBUG
        GC_log_printf("Adding on-demand section __DATA,%s at"
                      " %p-%p (%lu bytes) from image %s\n",
                      secnam, (void*)start, (void*)end,
                      (unsigned long)sec->size, name);
#     endif
      GC_add_roots((char*)start, (char*)end);
eg's avatar
eg committed
1358
    }
1359 1360 1361 1362 1363
  }

# ifdef DARWIN_DEBUG
    GC_print_static_roots();
# endif
eg's avatar
eg committed
1364 1365
}

1366 1367 1368
/* This should never be called by a thread holding the lock.    */
STATIC void GC_dyld_image_remove(const struct GC_MACH_HEADER *hdr,
                                 intptr_t slide)
1369
{
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
  unsigned long start, end;
  unsigned i, j;
  const struct GC_MACH_SECTION *sec;

  for (i = 0; i < sizeof(GC_dyld_sections)/sizeof(GC_dyld_sections[0]); i++) {
    sec = GC_GETSECTBYNAME(hdr, GC_dyld_sections[i].seg,
                           GC_dyld_sections[i].sect);
    if (sec == NULL || sec->size == 0)
      continue;
    start = slide + sec->addr;
    end = start + sec->size;
1381
#   ifdef DARWIN_DEBUG
1382 1383 1384 1385
      GC_log_printf(
            "Removing section __DATA,%s at %p-%p (%lu bytes) from image %s\n",
            GC_dyld_sections[i].sect, (void*)start, (void*)end,
            (unsigned long)sec->size, GC_dyld_name_for_hdr(hdr));
1386
#   endif
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
    GC_remove_roots((char*)start, (char*)end);
  }

  /* Remove our on-demand sections.     */
  for (j = 0; j < sizeof(GC_dyld_add_sect_fmts) / sizeof(char *); j++) {
    const char *fmt = GC_dyld_add_sect_fmts[j];

    for (i = 0; i <= L2_MAX_OFILE_ALIGNMENT; i++) {
      char secnam[16];

      (void)snprintf(secnam, sizeof(secnam), fmt, (unsigned)i);
      secnam[sizeof(secnam) - 1] = '\0';
      sec = GC_GETSECTBYNAME(hdr, SEG_DATA, secnam);
      if (sec == NULL || sec->size == 0)
        continue;
      start = slide + sec->addr;
      end = start + sec->size;
#     ifdef DARWIN_DEBUG
        GC_log_printf("Removing on-demand section __DATA,%s at"
                      " %p-%p (%lu bytes) from image %s\n", secnam,
                      (void*)start, (void*)end, (unsigned long)sec->size,
                      GC_dyld_name_for_hdr(hdr));
#     endif
      GC_remove_roots((char*)start, (char*)end);
eg's avatar
eg committed
1411
    }
1412 1413 1414 1415 1416
  }

# ifdef DARWIN_DEBUG
    GC_print_static_roots();
# endif
eg's avatar
eg committed
1417 1418
}

1419 1420 1421
GC_INNER void GC_register_dynamic_libraries(void)
{
    /* Currently does nothing. The callbacks are setup by GC_init_dyld()
eg's avatar
eg committed
1422 1423 1424 1425 1426 1427 1428 1429
    The dyld library takes it from there. */
}

/* The _dyld_* functions have an internal lock so no _dyld functions
   can be called while the world is stopped without the risk of a deadlock.
   Because of this we MUST setup callbacks BEFORE we ever stop the world.
   This should be called BEFORE any thread in created and WITHOUT the
   allocation lock held. */
1430 1431 1432

GC_INNER void GC_init_dyld(void)
{
eg's avatar
eg committed
1433 1434
  static GC_bool initialized = FALSE;

1435
  if (initialized) return;
eg's avatar
eg committed
1436

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
# ifdef DARWIN_DEBUG
    GC_log_printf("Registering dyld callbacks...\n");
# endif

  /* Apple's Documentation:
     When you call _dyld_register_func_for_add_image, the dynamic linker
     runtime calls the specified callback (func) once for each of the images
     that is currently loaded into the program. When a new image is added to
     the program, your callback is called again with the mach_header for the
     new image, and the virtual memory slide amount of the new image.

     This WILL properly register already linked libraries and libraries
     linked in the future.
  */
  _dyld_register_func_for_add_image(
        (void (*)(const struct mach_header*, intptr_t))GC_dyld_image_add);
  _dyld_register_func_for_remove_image(
        (void (*)(const struct mach_header*, intptr_t))GC_dyld_image_remove);
                        /* Structure mach_header64 has the same fields  */
                        /* as mach_header except for the reserved one   */
                        /* at the end, so these casts are OK.           */

  /* Set this early to avoid reentrancy issues. */
  initialized = TRUE;

# ifdef NO_DYLD_BIND_FULLY_IMAGE
    /* FIXME: What should we do in this case?   */
# else
    if (GC_no_dls) return; /* skip main data segment registration */

    /* When the environment variable is set, the dynamic linker binds   */
    /* all undefined symbols the application needs at launch time.      */
    /* This includes function symbols that are normally bound lazily at */
    /* the time of their first invocation.                              */
    if (GETENV("DYLD_BIND_AT_LAUNCH") == 0) {
      /* The environment variable is unset, so we should bind manually. */
#     ifdef DARWIN_DEBUG
        GC_log_printf("Forcing full bind of GC code...\n");
#     endif
      /* FIXME: '_dyld_bind_fully_image_containing_address' is deprecated. */
      if (!_dyld_bind_fully_image_containing_address(
                                                  (unsigned long *)GC_malloc))
1479
        ABORT("_dyld_bind_fully_image_containing_address failed");
eg's avatar
eg committed
1480
    }
1481
# endif
eg's avatar
eg committed
1482 1483 1484
}

#define HAVE_REGISTER_MAIN_STATIC_DATA
1485
GC_INNER GC_bool GC_register_main_static_data(void)
eg's avatar
eg committed
1486 1487 1488 1489 1490 1491
{
  /* Already done through dyld callbacks */
  return FALSE;
}

#endif /* DARWIN */
eg's avatar
eg committed
1492

1493
#elif defined(PCR)
eg's avatar
eg committed
1494

1495 1496 1497
# include "il/PCR_IL.h"
# include "th/PCR_ThCtl.h"
# include "mm/PCR_MM.h"
eg's avatar
eg committed
1498

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
  GC_INNER void GC_register_dynamic_libraries(void)
  {
    /* Add new static data areas of dynamically loaded modules. */
    PCR_IL_LoadedFile * p = PCR_IL_GetLastLoadedFile();
    PCR_IL_LoadedSegment * q;

    /* Skip uncommitted files */
    while (p != NIL && !(p -> lf_commitPoint)) {
        /* The loading of this file has not yet been committed    */
        /* Hence its description could be inconsistent.           */
        /* Furthermore, it hasn't yet been run.  Hence its data   */
        /* segments can't possibly reference heap allocated       */
        /* objects.                                               */
        p = p -> lf_prev;
    }
    for (; p != NIL; p = p -> lf_prev) {
      for (q = p -> lf_ls; q != NIL; q = q -> ls_next) {
        if ((q -> ls_flags & PCR_IL_SegFlags_Traced_MASK)
            == PCR_IL_SegFlags_Traced_on) {
          GC_add_roots_inner((char *)(q -> ls_addr),
                             (char *)(q -> ls_addr) + q -> ls_bytes, TRUE);
eg's avatar
eg committed
1520
        }
1521 1522 1523 1524
      }
    }
  }
#endif /* PCR && !DYNAMIC_LOADING && !MSWIN32 */
eg's avatar
eg committed
1525

1526 1527 1528 1529 1530 1531 1532
#if !defined(HAVE_REGISTER_MAIN_STATIC_DATA) && defined(DYNAMIC_LOADING)
  /* Do we need to separately register the main static data segment? */
  GC_INNER GC_bool GC_register_main_static_data(void)
  {
    return TRUE;
  }
#endif /* HAVE_REGISTER_MAIN_STATIC_DATA */
1533

1534
/* Register a routine to filter dynamic library registration.  */
1535 1536 1537
GC_API void GC_CALL GC_register_has_static_roots_callback(
                                        GC_has_static_roots_func callback)
{
1538 1539
    GC_has_static_roots = callback;
}