home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / sa104os2.zip / SATHR104.ZIP / SATHER / SYSTEM / GC / DYN_LOAD.C < prev    next >
C/C++ Source or Header  |  1994-09-13  |  17KB  |  567 lines

  1. /*
  2.  * Copyright (c) 1991-1994 by Xerox Corporation.  All rights reserved.
  3.  *
  4.  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
  5.  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
  6.  *
  7.  * Permission is hereby granted to use or copy this program
  8.  * for any purpose,  provided the above notices are retained on all copies.
  9.  * Permission to modify the code and to distribute modified code is granted,
  10.  * provided the above notices are retained, and a notice that the code was
  11.  * modified is included with the above copyright notice.
  12.  *
  13.  * Original author: Bill Janssen
  14.  * Heavily modified by Hans Boehm and others
  15.  */
  16. /* Boehm, September 12, 1994 4:27 pm PDT */
  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. #ifndef MACOS
  30. #  include <sys/types.h>
  31. #endif
  32. #include "gc_priv.h"
  33.  
  34. /* BTL: avoid circular redefinition of dlopen if SOLARIS_THREADS defined */
  35. # if defined(SOLARIS_THREADS) && defined(dlopen)
  36.     /* To support threads in Solaris, gc.h interposes on dlopen by       */
  37.     /* defining "dlopen" to be "GC_dlopen", which is implemented below.  */
  38.     /* However, both GC_FirstDLOpenedLinkMap() and GC_dlopen() use the   */
  39.     /* real system dlopen() in their implementation. We first remove     */
  40.     /* gc.h's dlopen definition and restore it later, after GC_dlopen(). */
  41. #   undef dlopen
  42. #   define GC_must_restore_redefined_dlopen
  43. # else
  44. #   undef GC_must_restore_redefined_dlopen
  45. # endif
  46.  
  47. #if (defined(DYNAMIC_LOADING) || defined(MSWIN32)) && !defined(PCR)
  48. #if !defined(SUNOS4) && !defined(SUNOS5DL) && !defined(IRIX5) && !defined(MSWIN32)
  49.  --> We only know how to find data segments of dynamic libraries under SunOS,
  50.  --> IRIX5, DRSNX and Win32.  Additional SVR4 variants might not be too
  51.  --> hard to add.
  52. #endif
  53.  
  54. #include <stdio.h>
  55. #ifdef SUNOS5DL
  56. #   include <sys/elf.h>
  57. #   include <dlfcn.h>
  58. #   include <link.h>
  59. #endif
  60. #ifdef SUNOS4
  61. #   include <dlfcn.h>
  62. #   include <link.h>
  63. #   include <a.out.h>
  64.   /* struct link_map field overrides */
  65. #   define l_next    lm_next
  66. #   define l_addr    lm_addr
  67. #   define l_name    lm_name
  68. #endif
  69.  
  70.  
  71. #ifdef SUNOS5DL
  72.  
  73. #ifdef LINT
  74.     Elf32_Dyn _DYNAMIC;
  75. #endif
  76.  
  77. static struct link_map *
  78. GC_FirstDLOpenedLinkMap()
  79. {
  80.     extern Elf32_Dyn _DYNAMIC;
  81.     Elf32_Dyn *dp;
  82.     struct r_debug *r;
  83.     static struct link_map * cachedResult = 0;
  84.     static Elf32_Dyn *dynStructureAddr = 0;
  85.                 /* BTL: added to avoid Solaris 5.3 ld.so _DYNAMIC bug */
  86.  
  87. #   ifdef SUNOS53_SHARED_LIB
  88.     /* BTL: Avoid the Solaris 5.3 bug that _DYNAMIC isn't being set    */
  89.     /* up properly in dynamically linked .so's. This means we have    */
  90.     /* to use its value in the set of original object files loaded    */
  91.     /* at program startup.                        */
  92.     if( dynStructureAddr == 0 ) {
  93.       void* startupSyms = dlopen(0, RTLD_LAZY);
  94.       dynStructureAddr = (Elf32_Dyn*)dlsym(startupSyms, "_DYNAMIC");
  95.         }
  96. #   else
  97.     dynStructureAddr = &_DYNAMIC;
  98. #   endif
  99.  
  100.     if( dynStructureAddr == 0) {
  101.         return(0);
  102.     }
  103.     if( cachedResult == 0 ) {
  104.         int tag;
  105.         for( dp = ((Elf32_Dyn *)(&_DYNAMIC)); (tag = dp->d_tag) != 0; dp++ ) {
  106.             if( tag == DT_DEBUG ) {
  107.                 struct link_map *lm
  108.                         = ((struct r_debug *)(dp->d_un.d_ptr))->r_map;
  109.                 if( lm != 0 ) cachedResult = lm->l_next; /* might be NIL */
  110.                 break;
  111.             }
  112.         }
  113.     }
  114.     return cachedResult;
  115. }
  116.  
  117. #endif
  118.  
  119. #ifdef SUNOS4
  120.  
  121. #ifdef LINT
  122.     struct link_dynamic _DYNAMIC;
  123. #endif
  124.  
  125. static struct link_map *
  126. GC_FirstDLOpenedLinkMap()
  127. {
  128.     extern struct link_dynamic _DYNAMIC;
  129.  
  130.     if( &_DYNAMIC == 0) {
  131.         return(0);
  132.     }
  133.     return(_DYNAMIC.ld_un.ld_1->ld_loaded);
  134. }
  135.  
  136. /* Return the address of the ld.so allocated common symbol    */
  137. /* with the least address, or 0 if none.            */
  138. static ptr_t GC_first_common()
  139. {
  140.     ptr_t result = 0;
  141.     extern struct link_dynamic _DYNAMIC;
  142.     struct rtc_symb * curr_symbol;
  143.     
  144.     if( &_DYNAMIC == 0) {
  145.         return(0);
  146.     }
  147.     curr_symbol = _DYNAMIC.ldd -> ldd_cp;
  148.     for (; curr_symbol != 0; curr_symbol = curr_symbol -> rtc_next) {
  149.         if (result == 0
  150.             || (ptr_t)(curr_symbol -> rtc_sp -> n_value) < result) {
  151.             result = (ptr_t)(curr_symbol -> rtc_sp -> n_value);
  152.         }
  153.     }
  154.     return(result);
  155. }
  156.  
  157. #endif
  158.  
  159. # if defined(SUNOS4) || defined(SUNOS5DL)
  160. /* Add dynamic library data sections to the root set.        */
  161. # if !defined(PCR) && !defined(SOLARIS_THREADS) && defined(THREADS)
  162. #   ifndef SRC_M3
  163.     --> fix mutual exclusion with dlopen
  164. #   endif  /* We assume M3 programs don't call dlopen for now */
  165. # endif
  166.  
  167. # ifdef SOLARIS_THREADS
  168.   /* Redefine dlopen to guarantee mutual exclusion with    */
  169.   /* GC_register_dynamic_libraries.            */
  170.   /* assumes that dlopen doesn't need to call GC_malloc    */
  171.   /* and friends.                    */
  172. # include <thread.h>
  173. # include <synch.h>
  174.   
  175. void * GC_dlopen(const char *path, int mode)
  176. {
  177.     void * result;
  178.     
  179.     mutex_lock(&GC_allocate_ml);
  180.     result = dlopen(path, mode);
  181.     mutex_unlock(&GC_allocate_ml);
  182.     return(result);
  183. }
  184. # endif
  185.  
  186. /* BTL: added to fix circular dlopen definition if SOLARIS_THREADS defined */
  187. # if defined(GC_must_restore_redefined_dlopen)
  188. #   define dlopen GC_dlopen
  189. # endif
  190.  
  191. void GC_register_dynamic_libraries()
  192. {
  193.   struct link_map *lm = GC_FirstDLOpenedLinkMap();
  194.   
  195.  
  196.   for (lm = GC_FirstDLOpenedLinkMap();
  197.        lm != (struct link_map *) 0;  lm = lm->l_next)
  198.     {
  199. #     ifdef SUNOS4
  200.     struct exec *e;
  201.      
  202.         e = (struct exec *) lm->lm_addr;
  203.         GC_add_roots_inner(
  204.                   ((char *) (N_DATOFF(*e) + lm->lm_addr)),
  205.             ((char *) (N_BSSADDR(*e) + e->a_bss + lm->lm_addr)));
  206. #     endif
  207. #     ifdef SUNOS5DL
  208.     Elf32_Ehdr * e;
  209.         Elf32_Phdr * p;
  210.         unsigned long offset;
  211.         char * start;
  212.         register int i;
  213.         
  214.     e = (Elf32_Ehdr *) lm->l_addr;
  215.         p = ((Elf32_Phdr *)(((char *)(e)) + e->e_phoff));
  216.         offset = ((unsigned long)(lm->l_addr));
  217.         for( i = 0; i < (int)(e->e_phnum); ((i++),(p++)) ) {
  218.           switch( p->p_type ) {
  219.             case PT_LOAD:
  220.               {
  221.                 if( !(p->p_flags & PF_W) ) break;
  222.                 start = ((char *)(p->p_vaddr)) + offset;
  223.                 GC_add_roots_inner(
  224.                   start,
  225.                   start + p->p_memsz
  226.                 );
  227.               }
  228.               break;
  229.             default:
  230.               break;
  231.           }
  232.     }
  233. #     endif
  234.     }
  235. #   ifdef SUNOS4
  236.       {
  237.           static ptr_t common_start = 0;
  238.           ptr_t common_end;
  239.           extern ptr_t GC_find_limit();
  240.           
  241.           if (common_start == 0) common_start = GC_first_common();
  242.           if (common_start != 0) {
  243.               common_end = GC_find_limit(common_start, TRUE);
  244.               GC_add_roots_inner((char *)common_start, (char *)common_end);
  245.           }
  246.       }
  247. #   endif
  248. }
  249.  
  250. # endif /* SUNOS */
  251.  
  252. #ifdef IRIX5
  253.  
  254. #include <sys/procfs.h>
  255. #include <sys/stat.h>
  256. #include <fcntl.h>
  257. #include <elf.h>
  258.  
  259. extern void * GC_roots_present();
  260.  
  261. extern ptr_t GC_scratch_end_ptr;   /* End of GC_scratch_alloc arena    */
  262.  
  263. /* We use /proc to track down all parts of the address space that are    */
  264. /* mapped by the process, and throw out regions we know we shouldn't    */
  265. /* worry about.  This may also work under other SVR4 variants.        */
  266. void GC_register_dynamic_libraries()
  267. {
  268.     static int fd = -1;
  269.     char buf[30];
  270.     static prmap_t * addr_map = 0;
  271.     static int current_sz = 0;    /* Number of records currently in addr_map */
  272.     static int needed_sz;    /* Required size of addr_map        */
  273.     register int i;
  274.     register long flags;
  275.     register ptr_t start;
  276.     register ptr_t limit;
  277.     ptr_t heap_end = (ptr_t)DATASTART;
  278.  
  279.     if (fd < 0) {
  280.       sprintf(buf, "/proc/%d", getpid());
  281.       fd = open(buf, O_RDONLY);
  282.       if (fd < 0) {
  283.         ABORT("/proc open failed");
  284.       }
  285.     }
  286.     if (ioctl(fd, PIOCNMAP, &needed_sz) < 0) {
  287.         ABORT("/proc PIOCNMAP ioctl failed");
  288.     }
  289.     if (needed_sz >= current_sz) {
  290.         current_sz = needed_sz * 2 + 1;
  291.                 /* Expansion, plus room for 0 record */
  292.         addr_map = (prmap_t *)GC_scratch_alloc(current_sz * sizeof(prmap_t));
  293.     }
  294.     if (ioctl(fd, PIOCMAP, addr_map) < 0) {
  295.         ABORT("/proc PIOCMAP ioctl failed");
  296.     };
  297.     if (GC_n_heap_sects > 0) {
  298.         heap_end = GC_heap_sects[GC_n_heap_sects-1].hs_start
  299.                 + GC_heap_sects[GC_n_heap_sects-1].hs_bytes;
  300.         if (heap_end < GC_scratch_end_ptr) heap_end = GC_scratch_end_ptr; 
  301.     }
  302.     for (i = 0; i < needed_sz; i++) {
  303.         flags = addr_map[i].pr_mflags;
  304.         if ((flags & (MA_BREAK | MA_STACK | MA_PHYS)) != 0) goto irrelevant;
  305.         if ((flags & (MA_READ | MA_WRITE)) != (MA_READ | MA_WRITE))
  306.             goto irrelevant;
  307.           /* The latter test is empirically useless.  Other than the    */
  308.           /* main data and stack segments, everything appears to be    */
  309.           /* mapped readable, writable, executable, and shared(!!).    */
  310.           /* This makes no sense to me.    - HB                */
  311.         start = (ptr_t)(addr_map[i].pr_vaddr);
  312.         if (GC_roots_present(start)) goto irrelevant;
  313.         if (start < heap_end && start >= (ptr_t)DATASTART)
  314.             goto irrelevant;
  315.         limit = start + addr_map[i].pr_size;
  316.     if (addr_map[i].pr_off == 0 && strncmp(start, ELFMAG, 4) == 0) {
  317.         /* Discard text segments, i.e. 0-offset mappings against    */
  318.         /* executable files which appear to have ELF headers.    */
  319.         caddr_t arg;
  320.         int obj;
  321. #        define MAP_IRR_SZ 10
  322.         static ptr_t map_irr[MAP_IRR_SZ];
  323.                         /* Known irrelevant map entries    */
  324.         static int n_irr = 0;
  325.         struct stat buf;
  326.         register int i;
  327.         
  328.         for (i = 0; i < n_irr; i++) {
  329.             if (map_irr[i] == start) goto irrelevant;
  330.         }
  331.         arg = (caddr_t)start;
  332.         obj = ioctl(fd, PIOCOPENM, &arg);
  333.         if (obj >= 0) {
  334.             fstat(obj, &buf);
  335.             close(obj);
  336.             if ((buf.st_mode & 0111) != 0) {
  337.                 if (n_irr < MAP_IRR_SZ) {
  338.                     map_irr[n_irr++] = start;
  339.                 }
  340.                 goto irrelevant;
  341.             }
  342.         }
  343.     }
  344.         GC_add_roots_inner(start, limit);
  345.       irrelevant: ;
  346.     }
  347. }
  348.  
  349. #endif  /* IRIX5 */
  350.  
  351. # ifdef MSWIN32
  352.  
  353. # define WIN32_LEAN_AND_MEAN
  354. # define NOSERVICE
  355. # include <windows.h>
  356. # include <stdlib.h>
  357.  
  358.   /* We traverse the entire address space and register all segments     */
  359.   /* that could possibly have been written to.                */
  360.   DWORD GC_allocation_granularity;
  361.   
  362.   extern bool GC_is_heap_base (ptr_t p);
  363.   
  364.   void GC_cond_add_roots(char *base, char * limit)
  365.   {
  366.     char dummy;
  367.     char * stack_top
  368.            = (char *) ((word)(&dummy) & ~(GC_allocation_granularity-1));
  369.     if (base == limit) return;
  370.     if (limit > stack_top && base < GC_stackbottom) {
  371.         /* Part of the stack; ignore it. */
  372.         return;
  373.     }
  374.     GC_add_roots_inner(base, limit);
  375.   }
  376.   
  377.   extern bool GC_win32s;
  378.   
  379.   void GC_register_dynamic_libraries()
  380.   {
  381.     MEMORY_BASIC_INFORMATION buf;
  382.     SYSTEM_INFO sysinfo;
  383.     DWORD result;
  384.     DWORD protect;
  385.     LPVOID p;
  386.     char * base;
  387.     char * limit, * new_limit;
  388.     
  389.     if (GC_win32s) return;
  390.     GetSystemInfo(&sysinfo);
  391.     base = limit = p = sysinfo.lpMinimumApplicationAddress;
  392.     GC_allocation_granularity = sysinfo.dwAllocationGranularity;
  393.     while (p < sysinfo.lpMaximumApplicationAddress) {
  394.         result = VirtualQuery(p, &buf, sizeof(buf));
  395.         if (result != sizeof(buf)) {
  396.             ABORT("Weird VirtualQuery result");
  397.         }
  398.         new_limit = (char *)p + buf.RegionSize;
  399.         protect = buf.Protect;
  400.         if (buf.State == MEM_COMMIT
  401.             && (protect == PAGE_EXECUTE_READWRITE
  402.                 || protect == PAGE_READWRITE)
  403.             && !GC_is_heap_base(buf.AllocationBase)) {
  404.             if ((char *)p == limit) {
  405.                 limit = new_limit;
  406.             } else {
  407.                 GC_cond_add_roots(base, limit);
  408.                 base = p;
  409.                 limit = new_limit;
  410.             }
  411.         }
  412.         if (p > (LPVOID)new_limit /* overflow */) break;
  413.         p = (LPVOID)new_limit;
  414.     }
  415.     GC_cond_add_roots(base, limit);
  416.   }
  417.  
  418. #endif /* MSWIN32 */
  419.  
  420. #if defined(ALPHA)
  421. void GC_register_dynamic_libraries()
  422. {
  423.   int status;
  424.   ldr_process_t mypid;
  425.  
  426.   /* module */
  427.     ldr_module_t moduleid = LDR_NULL_MODULE;
  428.     ldr_module_info_t moduleinfo;
  429.     size_t moduleinfosize = sizeof(moduleinfo);
  430.     size_t modulereturnsize;    
  431.  
  432.   /* region */
  433.     ldr_region_t region; 
  434.     ldr_region_info_t regioninfo;
  435.     size_t regioninfosize = sizeof(regioninfo);
  436.     size_t regionreturnsize;
  437.  
  438.   /* Obtain id of this process */
  439.     mypid = ldr_my_process();
  440.   
  441.   /* For each module */
  442.     while (TRUE) {
  443.  
  444.       /* Get the next (first) module */
  445.         status = ldr_next_module(mypid, &moduleid);
  446.  
  447.       /* Any more modules? */
  448.         if (moduleid == LDR_NULL_MODULE)
  449.             break;    /* No more modules */
  450.  
  451.       /* Check status AFTER checking moduleid because */
  452.       /* of a bug in the non-shared ldr_next_module stub */
  453.         if (status != 0 ) {
  454.             GC_printf("dynamic_load: status = %ld\n", (long)status);
  455.             {
  456.                 extern char *sys_errlist[];
  457.                 extern int sys_nerr;
  458.                 extern int errno;
  459.                 if (errno <= sys_nerr) {
  460.                     GC_printf("dynamic_load: %s\n", sys_errlist[errno]);
  461.                } else {
  462.                     GC_printf("dynamic_load: %d\n", errno);
  463.                 }
  464.         }
  465.             ABORT("ldr_next_module failed");
  466.          }
  467.  
  468.       /* Get the module information */
  469.         status = ldr_inq_module(mypid, moduleid, &moduleinfo,
  470.                                 moduleinfosize, &modulereturnsize); 
  471.         if (status != 0 )
  472.             ABORT("ldr_inq_module failed");
  473.  
  474.       /* is module for the main program (i.e. nonshared portion)? */
  475.           if (moduleinfo.lmi_flags & LDR_MAIN)
  476.               continue;    /* skip the main module */
  477.  
  478. #     ifdef VERBOSE
  479.           GC_printf("---Module---\n");
  480.           GC_printf("Module ID            = %16ld\n", moduleinfo.lmi_modid);
  481.           GC_printf("Count of regions     = %16d\n", moduleinfo.lmi_nregion);
  482.           GC_printf("flags for module     = %16lx\n", moduleinfo.lmi_flags); 
  483.           GC_printf("pathname of module   = \"%s\"\n", moduleinfo.lmi_name);
  484. #     endif
  485.  
  486.       /* For each region in this module */
  487.         for (region = 0; region < moduleinfo.lmi_nregion; region++) {
  488.  
  489.           /* Get the region information */
  490.             status = ldr_inq_region(mypid, moduleid, region, ®ioninfo,
  491.                                     regioninfosize, ®ionreturnsize);
  492.             if (status != 0 )
  493.                 ABORT("ldr_inq_region failed");
  494.  
  495.           /* only process writable (data) regions */
  496.             if (! (regioninfo.lri_prot & LDR_W))
  497.                 continue;
  498.  
  499. #         ifdef VERBOSE
  500.               GC_printf("--- Region ---\n");
  501.               GC_printf("Region number    = %16ld\n",
  502.                           regioninfo.lri_region_no);
  503.               GC_printf("Protection flags = %016x\n",  regioninfo.lri_prot);
  504.               GC_printf("Virtual address  = %16p\n",   regioninfo.lri_vaddr);
  505.               GC_printf("Mapped address   = %16p\n",   regioninfo.lri_mapaddr);
  506.               GC_printf("Region size      = %16ld\n",  regioninfo.lri_size);
  507.               GC_printf("Region name      = \"%s\"\n", regioninfo.lri_name);
  508. #         endif
  509.  
  510.           /* register region as a garbage collection root */
  511.             GC_add_roots_inner (
  512.                 (char *)regioninfo.lri_mapaddr,
  513.                 (char *)regioninfo.lri_mapaddr + regioninfo.lri_size);
  514.  
  515.         }
  516.     }
  517. }
  518. #endif
  519.  
  520.  
  521. #else /* !DYNAMIC_LOADING */
  522.  
  523. #ifdef PCR
  524.  
  525. #   include "il/PCR_IL.h"
  526. #   include "th/PCR_ThCtl.h"
  527. #   include "mm/PCR_MM.h"
  528.  
  529. void GC_register_dynamic_libraries()
  530. {
  531.     /* Add new static data areas of dynamically loaded modules.    */
  532.         {
  533.           PCR_IL_LoadedFile * p = PCR_IL_GetLastLoadedFile();
  534.           PCR_IL_LoadedSegment * q;
  535.           
  536.           /* Skip uncommited files */
  537.           while (p != NIL && !(p -> lf_commitPoint)) {
  538.               /* The loading of this file has not yet been committed    */
  539.               /* Hence its description could be inconsistent.          */
  540.               /* Furthermore, it hasn't yet been run.  Hence its data    */
  541.               /* segments can't possibly reference heap allocated    */
  542.               /* objects.                        */
  543.               p = p -> lf_prev;
  544.           }
  545.           for (; p != NIL; p = p -> lf_prev) {
  546.             for (q = p -> lf_ls; q != NIL; q = q -> ls_next) {
  547.               if ((q -> ls_flags & PCR_IL_SegFlags_Traced_MASK)
  548.                   == PCR_IL_SegFlags_Traced_on) {
  549.                 GC_add_roots_inner
  550.                     ((char *)(q -> ls_addr), 
  551.                      (char *)(q -> ls_addr) + q -> ls_bytes);
  552.               }
  553.             }
  554.           }
  555.         }
  556. }
  557.  
  558.  
  559. #else /* !PCR */
  560.  
  561. void GC_register_dynamic_libraries(){}
  562.  
  563. int GC_no_dynamic_loading;
  564.  
  565. #endif /* !PCR */
  566. #endif /* !DYNAMIC_LOADING */
  567.