home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / plbin.zip / pl / dld-3.2 / dld.c < prev    next >
C/C++ Source or Header  |  1992-05-26  |  67KB  |  2,485 lines

  1. /* dld -- dynamic link/unlink editor for C
  2.    Copyright (C) 1990 by W. Wilson Ho.
  3.  
  4.    The author can be reached electronically by how@ivy.ucdavis.edu or
  5.    through physical mail at:
  6.  
  7.    W. Wilson Ho
  8.    Division of Computer Science
  9.    University of California at Davis
  10.    Davis, CA 95616
  11.  */
  12.  
  13. /* MODIFIED
  14.  
  15.    DATE:
  16.     Sun Sep 16 16:46:52 MET DST 1990
  17.  
  18.    BUGFIX:
  19.     While allocating common symbols, clear their values to all ZERO.
  20.     For this I introduced xcalloc();
  21.  
  22.    BUGFIX:
  23.     Changed subfile_wanted_p() to consider files only holding common
  24.     symbols that are undefined sofar to be considered for loading.
  25.     Change indicated with (JW).
  26.  
  27.    ADDITION:
  28.         int dld_list_undefined()
  29.  
  30.     prints undefined symbols to stderr and returns the number of
  31.     undefined symbols found.
  32.  
  33.    CHANGE:
  34.     If a multiple definition is found its name is printed on
  35.     stderr.
  36.  
  37.    ADDITION:
  38.        char *dld_find_function(long address, int *percentage)
  39.  
  40.     Debugging tool.  Returns the name for the function which has
  41.     address in it and the percentage from the start of the function.
  42.     If the function cannot be found it returns the string "???" and
  43.     sets percentage to 0.  As this requires us to keep the symbol
  44.     table around, dld_init() has been given a second argument.  If
  45.     this is not equal to 0, the symbol tables are kept in core.
  46.  
  47.     This is an interface to the internal debugger of PCE.  It is a
  48.     better idea to write a function
  49.     
  50.     dld_dump_symbols(char *filename)
  51.  
  52.     that dumps a complete symbol table to filename.  Using the attaching
  53.     mechanism of dbx/gdb we can then normally debug the dynamic loaded
  54.     code.
  55.  
  56.    Jan Wielemaker
  57.    Social Science Informatics (SWI)
  58.    University of Amsterdam
  59.    Herengracht 196
  60.    1016 BS  Amsterdam
  61.    The Netherlands
  62.  
  63.    jan@swi.psy.uva.nl
  64. */
  65.  
  66. /* This program is free software; you can redistribute it and/or modify it
  67.    under the terms of the GNU General Public License as published by the
  68.    Free Software Foundation; either version 1, or (at your option) any
  69.    later version.
  70.  
  71.    This program borrows and modifies a number of functions and data
  72.    structures from the implementation of the GNU `ld' link editor.  The
  73.    original copyleft notice from the GNU `ld' is also included. */
  74.  
  75. /* Linker `ld' for GNU
  76.    Copyright (C) 1988 Free Software Foundation, Inc.
  77.  
  78.    This program is free software; you can redistribute it and/or modify
  79.    it under the terms of the GNU General Public License as published by
  80.    the Free Software Foundation; either version 1, or (at your option)
  81.    any later version.
  82.  
  83.    This program is distributed in the hope that it will be useful,
  84.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  85.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  86.    GNU General Public License for more details.
  87.  
  88.    You should have received a copy of the GNU General Public License
  89.    along with this program; if not, write to the Free Software
  90.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  91.  
  92. #include <a.out.h>
  93. #include <ar.h>
  94. #include <stdio.h>
  95. #include <sys/types.h>
  96. #include <strings.h>
  97. #include <sys/stat.h>
  98. #include <sys/file.h>
  99. #include <sys/param.h>
  100. #include <setjmp.h>
  101. #include "dld.h"
  102.  
  103. /* 
  104.  * Alloca include.
  105.  */
  106. /* If compiled with GNU C, use the built-in alloca */
  107. #ifdef __GNUC__
  108. #define alloca __builtin_alloca
  109. #endif
  110.  
  111. #if defined(sun) && defined(sparc) && !defined(__GNUC__)
  112. #include <alloca.h>
  113. #endif
  114.     
  115. /* this is commonly used in remove single linked-list elements. */
  116. #define del_link_list_elt(head, prev, current, next) { \
  117.     if (prev == 0) { \
  118.     head = current->next; \
  119.     free (current); \
  120.     current = head; \
  121.     } else { \
  122.     prev->next = current->next; \
  123.     free (current); \
  124.     current = prev->next; \
  125.     } }
  126.  
  127. /* System dependencies */
  128.  
  129. /* Ordinary 4.3 bsd lacks these macros in a.out.h */
  130.     
  131. #ifndef N_TXTADDR
  132. #ifdef vax
  133. #define N_TXTADDR(x) 0
  134. #endif
  135. #endif
  136.  
  137. #ifndef N_DATADDR
  138. #ifdef vax
  139. #define N_DATADDR(x) \
  140.     (((x).a_magic == OMAGIC) ? (N_TXTADDR(x)+(x).a_text) \
  141.      : (page_size + ((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  142. #endif
  143. #endif
  144.  
  145. #ifndef N_BSSADDR
  146. #ifdef vax
  147. #define N_BSSADDR(x) (N_DATADDR(x)+(x).a_data)
  148. #endif
  149. #endif
  150.  
  151. /*
  152.  * Ok.  Following are the relocation information macros.  If your
  153.  * system cannot use the default set (below), you must define all of these:
  154.  
  155.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  156.  * of structure that is stored in the relocation info section of your
  157.  * a.out files.  Often this is defined in the a.out.h for your system.
  158.  *
  159.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  160.  * <whatever> to be relocated.  *Must be an lvalue*.
  161.  *
  162.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  163.  * external symbol (1), or was it fully resolved upon entering the
  164.  * loader (0) in which case some combination of the value in memory
  165.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  166.  * what the value of the relocation actually was.  *Must be an lvalue*.
  167.  *
  168.  *   RELOC_SYMBOL (rval): For an external relocation, this is the
  169.  * index of its symbol in the symbol table.  *Must be an lvalue*.
  170.  *
  171.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  172.  * pc relative.
  173.  *
  174.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  175.  * an extra value to be added to the relocation value based on the
  176.  * individual relocation entry.  *Must be an lvalue if defined*.
  177.  *
  178.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  179.  * final relocation value before putting it where it belongs.
  180.  *
  181.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  182.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  183.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  184.  * do everything in terms of the bit operators below), but having this
  185.  * macro could end up producing better code on machines without fancy
  186.  * bit twiddling.  Also, it's easier to understand/code big/little
  187.  * endian distinctions with this macro.
  188.  *
  189.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  190.  * with the bits of the relocation value.  It may be assumed by the
  191.  * code that the relocation value will fit into this many bits.  This
  192.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  193.  *
  194.  *
  195.  *        Things I haven't implemented
  196.  *        ----------------------------
  197.  *
  198.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  199.  *
  200.  *    Pc relative relocation for External references.
  201.  *
  202.  *
  203.  */
  204.  
  205. #if defined(sun) && defined(sparc)
  206. /* Sparc (Sun 4) macros */
  207. #undef relocation_info
  208. #define relocation_info                    reloc_info_sparc
  209. #define RELOC_ADDRESS(r)        ((r)->r_address)                 
  210. #define RELOC_EXTERN_P(r)               ((r)->r_extern)      
  211. #define RELOC_SYMBOL(r)                 ((r)->r_index)   
  212. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)       
  213. #define RELOC_PCREL_P(r)             \
  214.         ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22)
  215. #define RELOC_VALUE_RIGHTSHIFT(r)       (reloc_target_rightshift[(r)->r_type])
  216. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(r)->r_type])
  217. #define RELOC_TARGET_BITSIZE(r)         (reloc_target_bitsize[(r)->r_type])
  218.  
  219. /* Note that these are very dependent on the order of the enums in
  220.    enum reloc_type (in a.out.h); if they change the following must be
  221.    changed */
  222. /* Also note that the last few may be incorrect; I have no information */
  223. static int reloc_target_rightshift[] = {
  224.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  225. };
  226. static int reloc_target_size[] = {
  227.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  228. };
  229. static int reloc_target_bitsize[] = {
  230.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  231. };
  232.  
  233. #endif
  234.  
  235. /* Default macros */
  236. #ifndef RELOC_ADDRESS
  237. #define RELOC_ADDRESS(r)        ((r)->r_address)
  238. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  239. #define RELOC_SYMBOL(r)            ((r)->r_symbolnum)
  240. #undef RELOC_ADD_EXTRA
  241. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  242. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  243. #endif
  244.  
  245. /* Size of a page; obtained from the operating system. */
  246.  
  247. static int page_size;
  248.  
  249. /* Each input file, and each library member ("subfile") being loaded,
  250.    has a `file_entry' structure for it.
  251.  
  252.    For files specified by command args, these are contained in the vector
  253.    which `file_table' points to.
  254.  
  255.    For library members, they are dynamically allocated,
  256.    and chained through the `chain' field.
  257.    The chain is found in the `subfiles' field of the `file_entry'.
  258.    The `file_entry' objects for the members have `superfile' fields pointing
  259.    to the one for the library.  */
  260.  
  261. struct file_entry {
  262.     /* Name of this file.  */
  263.     char *filename;
  264.     /* Name to use for the symbol giving address of text start */
  265.     /* Usually the same as filename, but for a file spec'd with -l
  266.        this is the -l switch itself rather than the filename.  */
  267.     char *local_sym_name;
  268.  
  269.     /* For library member, points to next entry for next member.
  270.        For object or library *file*, points to previously loaded entry */
  271.     struct file_entry *chain;
  272.  
  273.     /* number of undefined symbols referenced by this module */
  274.     int undefined_symbol_count;
  275.   
  276.     /* chain of file_entry that defines symbols this file references */
  277.     struct file_chain *refs;
  278.  
  279.     /* chain of file_entry that references symbols defined in this file */
  280.     struct file_chain *refs_by;
  281.   
  282.     /* reference count -- number of entries referenceing myself */
  283.     int ref_count;
  284.     
  285.     /* Describe the layout of the contents of the file */
  286.  
  287.     /* The file's a.out header.  */
  288.     struct exec header;
  289.  
  290.     /* Describe data from the file loaded into core */
  291.  
  292.     /* Symbol table of the file.  */
  293.     struct nlist *symbols;
  294.     /* Size in bytes of string table.  */
  295.     int string_size;
  296.     /* Pointer to the string table.
  297.        The string table is not kept in core all the time,
  298.        but when it is in core, its address is here.  */
  299.     char *strings;
  300.  
  301.     /* Relocation information of the file. */
  302.  
  303.     /* Start of this file's text relocation information. */
  304.     struct dld_reloc_info *text_reloc;
  305.     /* Start of this file's data relocation information. */
  306.     struct dld_reloc_info *data_reloc;
  307.     
  308.     /* Relation of this file's segments to the output buffer */
  309.  
  310.     /* Start of this file's text seg in the output file core image.  */
  311.     int text_start_address;
  312.     /* Start of this file's data seg in the output file core image.  */
  313.     int data_start_address;
  314.     /* Start of this file's bss seg in the output file core image.  */
  315.     int bss_start_address;
  316.  
  317.     /* For library members only */
  318.  
  319.     /* For a library, points to chain of entries for the library members.  */
  320.     struct file_entry *subfiles;
  321.     /* For a library member, offset of the member within the archive.
  322.        Zero for files that are not library members.  */
  323.     int starting_offset;
  324.     /* Size of contents of this file, if library member.  */
  325.     int total_size;
  326.     /* For library member, points to the library's own entry.  */
  327.     struct file_entry *superfile;
  328.  
  329.     /* 1 if file is a library. */
  330.     char library_flag;
  331.  
  332.     /* 1 if file's header has been read into this structure.  */
  333.     char header_read_flag;
  334.  
  335.     /* 1 if this module has all external references resolved */
  336.     char all_symbols_resolved_flag;
  337.   
  338.     /* 1 if functions in this module can be safely executed. */
  339.     char executable_flag;
  340.  
  341.     /* 1 if this module has already been (soft) unlinked. */
  342.     char already_unlink;
  343.     /* 1 means search a set of directories for this file.  */
  344.     /* char search_dirs_flag; */
  345. };
  346.  
  347.  
  348. /* format of file_entry chain */
  349. struct file_chain {
  350.     struct file_chain *next;
  351.     struct file_entry *entry;
  352. };
  353.  
  354. /* Symbol table */
  355.  
  356. /* Global symbol data is recorded in these structures,
  357.    one for each global symbol.
  358.    They are found via hashing in 'symtab', which points to a vector of buckets.
  359.    Each bucket is a chain of these structures through the link field.  */
  360.  
  361. typedef
  362.   struct glosym
  363.     {
  364.       /* Pointer to next symbol in this symbol's hash bucket.  */
  365.       struct glosym *link;
  366.       /* Name of this symbol.  */
  367.       char *name;
  368.       /* Value of this symbol as a global symbol.  */
  369.       long value;
  370.       /* Points to the file_entry that defines this symbol */
  371.       struct file_entry *defined_by;
  372.       /* chain of file_entry that contains reference to this symbol */
  373.       struct file_chain *referenced_by;
  374.       /* Nonzero means a definition of this global symbol is known to exist.
  375.      Library members should not be loaded on its account.  */
  376.       char defined;
  377.       /* Nonzero means a reference to this global symbol has been seen
  378.      in a file that is surely being loaded. */
  379.       char referenced;
  380.     }
  381.   symbol;
  382.  
  383. /* Number of buckets in symbol hash table */
  384. #define    TABSIZE    1009
  385.  
  386. /* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  387. static symbol *symtab[TABSIZE];
  388.  
  389. /* Count the number of global symbols referenced and not defined.  */
  390. static int undefined_global_sym_count = 0;
  391.  
  392. /* internal format of relocation info entry. */
  393. struct dld_reloc_info {
  394.     /* corresponding symbol table entry. */
  395.     symbol *sp;
  396.  
  397.     /* The real relocation info entry.
  398.        This is an ugly design.  In the original relocation_info structure.
  399.        The corresponding symbol definition is located by an index to the
  400.        nlist array.  This array is not kept online, and so this index
  401.        must be replace by the address of the corresponding symbol table
  402.        kept online.  However, on most machine this index takes only 24bits,
  403.        which is not large enough (in general) to hold a pointer.  So we
  404.        need a structure definition with a sp field as shown above.  The
  405.        complete original relocation info entry is kept here.  This is not
  406.        very space economical (24 bits are wasted).  But since different
  407.        system has different format for STRUCT RELOCATION_INFO, I'd rather
  408.        let the include file <a.out.h> take care of the difference, than
  409.        using a separate definition for each system. */
  410.     struct relocation_info reloc_info;
  411. };
  412.  
  413. /* Format of __.SYMDEF:
  414.    First, a longword containing the size of the 'symdef' data that follows.
  415.    Second, zero or more 'symdef' structures.
  416.    Third, a word containing the length of symbol name strings.
  417.    Fourth, zero or more symbol name strings (each followed by a zero).  */
  418.  
  419. struct symdef {
  420.   int symbol_name_string_index;
  421.   int library_member_offset;
  422. };
  423.  
  424. /* variable for saving the environment */
  425. static jmp_buf env;
  426.  
  427. /* pointer to the lastest (newest) file entry */
  428. static struct file_entry *latest_entry = 0;
  429.  
  430. /* To avoid close a file and then open the same file again, the following
  431.    two variables remember the file that is currently open.  Both are zero
  432.    if no file is open.
  433.  */
  434. static struct file_entry *input_file = 0;
  435. static int input_desc = 0;
  436.  
  437. /* global variables to return the error code to the caller */
  438. int dld_errno;
  439.  
  440. /* allow for debugging (e.g. keep symbol table and string table */
  441. static int allow_debugging;
  442.  
  443. /* true if the executable flags are up-to-date */
  444. static char executable_flags_up_to_date;
  445.  
  446. /* Miscellaneous routines */
  447.  
  448. /* save the error code in dld_errno */
  449. static void
  450. fatal (errno)
  451. register int errno;
  452. {
  453.     dld_errno = errno;
  454.     longjmp (env, 1);
  455. } /* fatal */
  456.  
  457.  
  458. /* Like malloc but get fatal error if memory is exhausted.  */
  459.  
  460. static int
  461. xmalloc (size)
  462. int size;
  463. {
  464.     register int result = malloc (size);
  465.     if (!result)
  466.     fatal (DLD_ENOMEMORY);
  467.     return result;
  468. } /* xmalloc */
  469.  
  470. static int
  471. xcalloc (nelem, size)
  472. int nelem, size;
  473. {
  474.     register int result = calloc (nelem, size);
  475.     if (!result)
  476.     fatal (DLD_ENOMEMORY);
  477.     return result;
  478. } /* xmalloc */
  479.  
  480.  
  481. /* Return a newly-allocated string
  482.    whose contents concatenate the strings S1, S2, S3.  */
  483.  
  484. static char *
  485. concat (s1, s2, s3)
  486. char *s1, *s2, *s3;
  487. {
  488.     register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  489.     register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  490.     
  491.     strcpy (result, s1);
  492.     strcpy (result + len1, s2);
  493.     strcpy (result + len1 + len2, s3);
  494.     result[len1 + len2 + len3] = 0;
  495.     
  496.     return result;
  497. } /* concat */
  498.  
  499.  
  500. /* Add a new entry to the file chain if it is not already there.
  501.    Return 0 if no actual insertion is needed, otherwise, return 1. */
  502. static
  503. insert_entry (head, entry)
  504. struct file_chain **head;
  505. register struct file_entry *entry;
  506. {
  507.     register struct file_chain *fc = *head;
  508.     
  509.     while (fc)  {
  510.         if (fc->entry == entry)
  511.             return 0;
  512.         else fc = fc->next;
  513.     }
  514.     
  515.     fc = (struct file_chain *) xmalloc (sizeof (struct file_chain));
  516.  
  517.     fc->next = *head;
  518.     fc->entry = entry;
  519.     *head = fc;
  520.     return 1;
  521. } /* insert_entry */
  522.  
  523.  
  524. /* Close the input file that is now open.  */
  525.  
  526. static void
  527. file_close ()
  528. {
  529.   if (input_desc) close (input_desc);
  530.   input_desc = 0;
  531.   input_file = 0;
  532. } /* file_close */
  533.  
  534. /* Open the input file specified by 'entry', and return a descriptor.
  535.    The open file is remembered; if the same file is opened twice in a row,
  536.    a new open is not actually done.  */
  537.  
  538. static int
  539. file_open (entry)
  540. register struct file_entry *entry;
  541. {
  542.     register int desc;
  543.     
  544.     if (entry == 0) fatal (DLD_ENOFILE);
  545.     
  546.     if (entry->superfile)
  547.     return file_open (entry->superfile);
  548.     
  549.     if (entry == input_file)
  550.     return input_desc;
  551.     
  552.     if (input_file) file_close ();
  553.     
  554.     desc = open (entry->filename, O_RDONLY, 0);
  555.     
  556.     if (desc > 0) {
  557.     input_file = entry;
  558.     input_desc = desc;
  559.     return desc;
  560.     }
  561.     
  562.     fatal (DLD_ENOFILE);
  563. } /* file_open */
  564.  
  565. /* Medium-level input routines for rel files.  */
  566.  
  567. /* Read a file's header into the proper place in the file_entry.
  568.    DESC is the descriptor on which the file is open.
  569.    ENTRY is the file's entry.  */
  570.  
  571. static void
  572. read_header (desc, entry)
  573. int desc;
  574. register struct file_entry *entry;
  575. {
  576.     register int len;
  577.     struct exec *loc = &entry->header;
  578.     
  579.     lseek (desc, entry->starting_offset, 0);
  580.     len = read (desc, loc, sizeof (struct exec));
  581.     if (len != sizeof (struct exec))
  582.     fatal (DLD_EBADHEADER);
  583.     if (N_BADMAG (*loc))
  584.     fatal (DLD_EBADMAGIC);
  585.     
  586.     entry->header_read_flag = 1;
  587. } /* read_header */
  588.  
  589.  
  590. /* Read the symbols of file ENTRY into core.
  591.    Assume it is already open, on descriptor DESC.
  592.    Also read the length of the string table, which follows the symbol table,
  593.    but don't read the contents of the string table.  */
  594.  
  595. static void
  596. read_entry_symbols (desc, entry)
  597. struct file_entry *entry;
  598. int desc;
  599. {
  600.     int str_size;
  601.     
  602.     if (!entry->header_read_flag)
  603.     read_header (desc, entry);
  604.     
  605.     if (entry->header.a_syms < 0)
  606.     fatal (DLD_ENOSYMBOLS);
  607.  
  608.     if (entry->header.a_syms == 0) {    /* added (JW) */
  609.         entry->symbols = (struct nlist *) xmalloc (sizeof(int));
  610.     entry->string_size = 0;
  611.     return;
  612.     }
  613.     
  614.     entry->symbols = (struct nlist *) xmalloc (entry->header.a_syms);
  615.     
  616.     lseek (desc, N_SYMOFF (entry->header) + entry->starting_offset, 0);
  617.     if (entry->header.a_syms !=
  618.     read (desc, entry->symbols, entry->header.a_syms)) {
  619.     free (entry->symbols);
  620.     entry->symbols = 0;
  621.     fatal (DLD_ENOSYMBOLS);
  622.     }
  623.     
  624.     lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  625.     if (sizeof str_size != read (desc, &str_size, sizeof str_size)) {
  626.     free (entry->symbols);
  627.     entry->symbols = 0;
  628.     fatal (DLD_ENOSTRINGS);
  629.     }
  630.     
  631.     entry->string_size = str_size;
  632. } /* read_entry_symbols */
  633.  
  634.  
  635. /* Read the string table of file ENTRY into core.
  636.    Assume it is already open, on descriptor DESC. */
  637.  
  638. static void
  639. read_entry_strings (desc, entry)
  640. struct file_entry *entry;
  641. int desc;
  642. {
  643.     if (!entry->header_read_flag)
  644.     read_header (desc, entry);
  645.     
  646.     lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  647.     if (entry->string_size != read (desc, entry->strings, entry->string_size))
  648.     fatal (DLD_ENOSTRINGS);
  649.     
  650. } /* read_entry_strings */
  651.  
  652.  
  653. /* Verify the validity of the relocation information.
  654.    DATA_SIZE is the length of the contents.
  655.    RELOC_INFO is the address of the relocation info, in core.
  656.    RELOC_SIZE is its length in bytes.
  657.    If everything is ok, return the number of external relocation entry.
  658.    Otherwise, return -1. */
  659. reloc_info_ok (data_size, reloc_info, reloc_size, sym_size)
  660. register int data_size;
  661. register struct relocation_info *reloc_info;
  662. register int reloc_size;
  663. register int sym_size;
  664. {
  665.     register struct relocation_info *p = reloc_info;
  666.     register struct relocation_info *end = p +
  667.     reloc_size / sizeof (struct relocation_info);
  668.     register int extern_count = 0;  /* number of external relocation */
  669.     
  670.     for (; p < end; p++) {
  671.     register int symbolnum = RELOC_SYMBOL(p);
  672.     
  673.     if (RELOC_ADDRESS(p) >= data_size)
  674.         return -1;
  675.     if (RELOC_EXTERN_P(p)) {
  676.         extern_count++;
  677.         if (symbolnum * sizeof (struct nlist) >= sym_size)
  678.         return -1;
  679.     } else if (symbolnum != N_TEXT && symbolnum != (N_TEXT | N_EXT) &&
  680.            symbolnum != N_DATA && symbolnum != (N_DATA | N_EXT) &&
  681.            symbolnum != N_BSS  && symbolnum != (N_BSS | N_EXT))
  682.         return -1;
  683.  
  684.     if (RELOC_TARGET_SIZE(p) > 2) return -1;
  685.     }
  686.     return extern_count++;
  687.     
  688. } /* reloc_info_ok */
  689.  
  690. /* symbol table management */
  691.  
  692. /* Compute the hash code for symbol name KEY.  */
  693.  
  694. static int
  695. hash_string (key)
  696. char *key;
  697. {
  698.     register char *cp;
  699.     register int k;
  700.     
  701.     cp = key;
  702.     k = 0;
  703.     while (*cp)
  704.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  705.     
  706.     return k;
  707. } /* hash_string */
  708.  
  709.  
  710. /* Get the symbol table entry for the global symbol named KEY.
  711.    Create one if there is none.  */
  712.  
  713. static symbol *
  714. getsym (key)
  715. char *key;
  716. {
  717.     register int hashval;
  718.     register symbol *bp;
  719.     
  720.     /* Determine the proper bucket.  */
  721.     
  722.     hashval = hash_string (key) % TABSIZE;
  723.     
  724.     /* Search the bucket.  */
  725.     
  726.     for (bp = symtab[hashval]; bp; bp = bp->link)
  727.     if (! strcmp (key, bp->name))
  728.         return bp;
  729.     
  730.     /* Nothing was found; create a new symbol table entry.  */
  731.     
  732.     bp = (symbol *) xmalloc (sizeof (symbol));
  733.     bzero (bp, sizeof (symbol));
  734.     bp->name = (char *) xmalloc (strlen (key) + 1);
  735.     strcpy (bp->name, key);
  736.     
  737.     /* Add the entry to the bucket.  */
  738.     
  739.     bp->link = symtab[hashval];
  740.     symtab[hashval] = bp;
  741.     
  742.     return bp;
  743. } /* getsym */
  744.  
  745.  
  746. /* Like `getsym' but return 0 if the symbol is not already known.  */
  747.  
  748. static symbol *
  749. getsym_soft (key)
  750. char *key;
  751. {
  752.     register int hashval;
  753.     register symbol *bp;
  754.     
  755.     /* Determine which bucket.  */
  756.     
  757.     hashval = hash_string (key) % TABSIZE;
  758.     
  759.     /* Search the bucket.  */
  760.     
  761.     for (bp = symtab[hashval]; bp; bp = bp->link)
  762.     if (! strcmp (key, bp->name))
  763.         return bp;
  764.     
  765.     return 0;
  766. } /* getsym_soft */
  767.  
  768. /* Enter one global symbol in the hash table.
  769.    NLIST_P points to the `struct nlist' read from the file
  770.    that describes the global symbol.  NAME is the symbol's name.
  771.    ENTRY is the file entry for the file the symbol comes from.
  772.  
  773.    The `struct nlist' is modified by making n_name point back to the
  774.    corresponding symbols.
  775.  
  776.    For the common definition, the symbol is considered defined by the
  777.    first entry that defines it.  The problem here is that uninitialized
  778.    global variables are all treated as common definitions.  Strictly
  779.    speacking, in a program there should be exactly one definition
  780.    (initialized or uninitialized) of any global variable and all other
  781.    files that reference that variable should declare it with the 'extern'
  782.    keyword.  However, most compiler allows the omission of the 'extern'
  783.    keyword, and let the linker map all these definitions to the same
  784.    location.  In other words, multiple definitions of the same symbol is
  785.    allowed.  Now, when one of the files that defines such symbol is to be
  786.    unlinked, should this symbol become undefined?  Or should it remain in
  787.    core?  The decision made is to treat the symbol defined by the first
  788.    file that defines it.  All subsequence definitions of the same symbol
  789.    will be treated as extern references.  However, if any of the
  790.    following definition defines the symbol as initialized global, it will
  791.    be considered multiple definition and be treated as an error.
  792.  
  793. */
  794. static void
  795. enter_global_ref (entry, nlist_p, name)
  796. struct file_entry *entry;
  797. register struct nlist *nlist_p;
  798. char *name;
  799. {
  800.     register symbol *sp = getsym (name);
  801.     register int type = nlist_p->n_type;
  802.     register int common = (type == (N_UNDF | N_EXT) && nlist_p->n_value);
  803.     int oldref = sp->referenced;
  804.     int olddef = sp->defined;
  805.  
  806.     nlist_p->n_un.n_name = (char *) sp;
  807.     
  808.     sp->referenced = 1;
  809.  
  810.     /* common definition */
  811.     if (common && !olddef)
  812.     type = N_COMM | N_EXT;
  813.  
  814.     if (type != (N_UNDF | N_EXT)) {
  815.     /* definition of a symbol */
  816.     
  817.     if (olddef) {
  818.         fprintf(stderr, "dld: multiple defined: %s\n", name);
  819.         fatal (DLD_EMULTDEFS);
  820.     } else {
  821.         sp->defined = type;
  822.         sp->value = common ? (long) xcalloc (1, nlist_p->n_value) :
  823.         nlist_p->n_value; 
  824.         sp->defined_by = entry;
  825.     }
  826.  
  827.     if (oldref && !olddef) {
  828.         register struct file_chain *p = sp->referenced_by;
  829.         
  830.         undefined_global_sym_count--;
  831.         
  832.         while (p) {
  833.         p->entry->undefined_symbol_count--;
  834.         if (insert_entry (&(p->entry->refs), entry) &&
  835.             insert_entry (&(entry->refs_by), p->entry) &&
  836.             p->entry != entry)
  837.             entry->ref_count++;
  838.         p = p->next;
  839.         }
  840.     }
  841.     } else {
  842.     /* this is just a reference */
  843.     if (sp->defined_by)
  844.         if (insert_entry (&(entry->refs), sp->defined_by) &&
  845.         entry != sp->defined_by)
  846.         sp->defined_by->ref_count++;
  847.     
  848.     if (insert_entry (&(sp->referenced_by), entry) && !sp->defined)
  849.         entry->undefined_symbol_count++;
  850.     
  851.     if (!oldref) {
  852.         undefined_global_sym_count++;
  853.         sp->defined = 0;
  854.         sp->value = 0;
  855.     }
  856.     }
  857. }
  858.  
  859.  
  860. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  861.  
  862. static void
  863. enter_file_symbols (entry)
  864. struct file_entry *entry;
  865. {
  866.     register struct nlist *p,
  867.     *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  868.     
  869.     for (p = entry->symbols; p < end; p++)
  870.     if (p->n_type & N_EXT)
  871.         enter_global_ref (entry, p, p->n_un.n_strx + entry->strings);
  872. }
  873.  
  874. /* remove all symbols that are no longer needed */
  875. static void
  876. cleanup_symtab ()
  877. {
  878.     register int i;
  879.  
  880.     for (i = 0; i < TABSIZE; i++) {
  881.     register symbol *sp = symtab[i];
  882.     register symbol *prev_sp = 0;
  883.  
  884.     while (sp) {
  885.         register struct file_chain *p = sp->referenced_by;
  886.         register struct file_chain *prev = 0;
  887.         register int obsolete = (sp->defined_by &&
  888.                      sp->defined_by->ref_count == 0);
  889.         
  890.         while (p)
  891.         if (p->entry->ref_count == 0) {
  892.             del_link_list_elt (sp->referenced_by, prev, p, next);
  893.         } else {
  894.             if (obsolete)
  895.             p->entry->undefined_symbol_count++;
  896.  
  897.             prev = p;
  898.             p = p->next;
  899.         }
  900.  
  901.         if (obsolete) {
  902.         if (sp->defined == (N_COMM | N_EXT) && sp->value)
  903.             free (sp->value);
  904.         if (sp->referenced_by == 0) {
  905.             free (sp->name);
  906.             del_link_list_elt (symtab[i], prev_sp, sp, link);
  907.             continue;
  908.         } else {
  909.             undefined_global_sym_count++;
  910.             sp->defined = 0;
  911.             sp->defined_by = 0;
  912.             sp->value = 0;
  913.         }
  914.         }
  915.  
  916.         if (sp->defined == 0 && sp->referenced_by == 0) {
  917.         undefined_global_sym_count--;
  918.         free (sp->name);
  919.         if (sp->defined == (N_COMM | N_EXT) && sp->value)
  920.             free (sp->value);
  921.         del_link_list_elt (symtab[i], prev_sp, sp, link);
  922.         continue;
  923.         }
  924.         
  925.         prev_sp = sp;
  926.         sp = sp->link;
  927.     }
  928.     }
  929. } /* cleanup_symtab */
  930.  
  931. /* Searching libraries */
  932.  
  933. static struct file_entry *decode_library_subfile ();
  934. static void linear_library (), symdef_library ();
  935. static int subfile_wanted_p ();
  936. static void read_text_and_data ();
  937.  
  938. /* Search the library ENTRY, already open on descriptor DESC.
  939.    This means deciding which library members to load,
  940.    making a chain of `struct file_entry' for those members,
  941.    and entering their global symbols in the hash table.  */
  942.  
  943. static void
  944. search_library (desc, entry)
  945. int desc;
  946. struct file_entry *entry;
  947. {
  948.     int member_length;
  949.     register char *name;
  950.     register struct file_entry *subentry;
  951.     
  952.     if (!undefined_global_sym_count) return;
  953.     
  954.     /* Examine its first member, which starts SARMAG bytes in.  */
  955.     subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  956.     if (!subentry) return;
  957.     
  958.     name = subentry->filename;
  959.     free (subentry);
  960.     
  961.     /* Search via __.SYMDEF if that exists, else linearly.  */
  962.     
  963.     if (!strcmp (name, "__.SYMDEF"))
  964.     symdef_library (desc, entry, member_length);
  965.     else
  966.     linear_library (desc, entry);
  967.     
  968.     free (name);
  969. } /* search_library */
  970.  
  971. /* Construct and return a file_entry for a library member.
  972.    The library's file_entry is library_entry, and the library is open on DESC.
  973.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  974.    We store the length of the member into *LENGTH_LOC.  */
  975.  
  976. static struct file_entry *
  977. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  978. int desc;
  979. struct file_entry *library_entry;
  980. int subfile_offset;
  981. int *length_loc;
  982. {
  983.     int bytes_read;
  984.     register int namelen;
  985.     int member_length;
  986.     register char *name;
  987.     struct ar_hdr hdr1;
  988.     register struct file_entry *subentry;
  989.     
  990.     lseek (desc, subfile_offset, 0);
  991.     
  992.     bytes_read = read (desc, &hdr1, sizeof hdr1);
  993.     if (!bytes_read)
  994.     return 0;        /* end of archive */
  995.     
  996.     if (sizeof hdr1 != bytes_read)
  997.     fatal (DLD_EBADLIBRARY);
  998.     
  999.     if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  1000.     fatal (DLD_EBADLIBRARY);
  1001.     
  1002.     subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  1003.     bzero (subentry, sizeof (struct file_entry));
  1004.     
  1005.     for (namelen = 0;
  1006.      namelen < sizeof hdr1.ar_name
  1007.      && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' ';
  1008.      namelen++);
  1009.     
  1010.     name = (char *) xmalloc (namelen+1);
  1011.     strncpy (name, hdr1.ar_name, namelen);
  1012.     name[namelen] = 0;
  1013.     
  1014.     subentry->filename = name;
  1015.     subentry->local_sym_name = name;
  1016.     subentry->starting_offset = subfile_offset + sizeof hdr1;
  1017.     subentry->superfile = library_entry;
  1018.     subentry->total_size = member_length;
  1019.     
  1020.     (*length_loc) = member_length;
  1021.     
  1022.     return subentry;
  1023. } /* decode_library_subfile */
  1024.  
  1025.  
  1026. /* Search a library that has a __.SYMDEF member.
  1027.    DESC is a descriptor on which the library is open.
  1028.      The file pointer is assumed to point at the __.SYMDEF data.
  1029.    ENTRY is the library's file_entry.
  1030.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  1031.  
  1032. static void
  1033. symdef_library (desc, entry, member_length)
  1034. int desc;
  1035. struct file_entry *entry;
  1036. int member_length;
  1037. {
  1038.     int *symdef_data = (int *) alloca (member_length);
  1039.     register struct symdef *symdef_base;
  1040.     char *sym_name_base;
  1041.     int number_of_symdefs;
  1042.     int length_of_strings;
  1043.     int not_finished;
  1044.     int bytes_read;
  1045.     register int i;
  1046.     struct file_entry *prev = 0;
  1047.     int prev_offset = 0;
  1048.     
  1049.     bytes_read = read (desc, symdef_data, member_length);
  1050.     if (bytes_read != member_length)
  1051.     fatal (DLD_EBADLIBRARY);
  1052.     
  1053.     number_of_symdefs = *symdef_data / sizeof (struct symdef);
  1054.     if (number_of_symdefs < 0 ||
  1055.     number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) >=
  1056.     member_length)
  1057.     fatal (DLD_EBADLIBRARY);
  1058.     
  1059.     symdef_base = (struct symdef *) (symdef_data + 1);
  1060.     length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  1061.     
  1062.     if (length_of_strings < 0
  1063.     || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  1064.     + 2 * sizeof (int) != member_length)
  1065.     fatal (DLD_EBADLIBRARY);
  1066.     
  1067.     sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  1068.     
  1069.     /* Check all the string indexes for validity.  */
  1070.     
  1071.     for (i = 0; i < number_of_symdefs; i++) {
  1072.     register int index = symdef_base[i].symbol_name_string_index;
  1073.     if (index < 0 || index >= length_of_strings
  1074.         || (index && *(sym_name_base + index - 1)))
  1075.         fatal (DLD_EBADLIBRARY);
  1076.     }
  1077.     
  1078.     /* Search the symdef data for members to load.
  1079.        Do this until one whole pass finds nothing to load.  */
  1080.     
  1081.     not_finished = 1;
  1082.     while (not_finished) {
  1083.     not_finished = 0;
  1084.         
  1085.     /* Scan all the symbols mentioned in the symdef for ones that we need.
  1086.        Load the library members that contain such symbols.  */
  1087.         
  1088.     for (i = 0; i < number_of_symdefs && undefined_global_sym_count; i++)
  1089.         if (symdef_base[i].symbol_name_string_index >= 0) {
  1090.         register symbol *sp;
  1091.             
  1092.         sp = getsym_soft (sym_name_base
  1093.                    + symdef_base[i].symbol_name_string_index);
  1094.             
  1095.         /* If we find a symbol that appears to be needed,
  1096.            think carefully about the archive member that
  1097.            the symbol is in.  */
  1098.             
  1099.         if (sp && sp->referenced && !sp->defined) {
  1100.             int junk;
  1101.             register int j;
  1102.             register int offset = symdef_base[i].library_member_offset;
  1103.             struct file_entry *subentry;
  1104.                 
  1105.             /* Don't think carefully about any archive member
  1106.                more than once in a given pass.  */
  1107.             
  1108.             if (prev_offset == offset)
  1109.             continue;
  1110.             prev_offset = offset;
  1111.             
  1112.             /* Read the symbol table of the archive member.  */
  1113.             
  1114.             subentry = decode_library_subfile (desc, entry, offset, &junk);
  1115.             if (prev)
  1116.             prev->chain = subentry;
  1117.             else entry->subfiles = subentry;
  1118.                 
  1119.             read_entry_symbols (desc, subentry);
  1120.             if ( allow_debugging )
  1121.                 subentry->strings =
  1122.                       (char *) xmalloc (subentry->string_size);
  1123.             else
  1124.                 subentry->strings =
  1125.                       (char *) alloca (subentry->string_size);
  1126.             read_entry_strings (desc, subentry);
  1127.                 
  1128.             /* Now scan the symbol table and decide whether to load.  */
  1129.             if (!subfile_wanted_p (subentry)) {
  1130.             if (prev)
  1131.                 prev->chain = 0;
  1132.             else entry->subfiles = 0;
  1133.             free (subentry->filename);
  1134.             free (subentry->symbols);
  1135.             free (subentry);
  1136.             } else {
  1137.             /* This member is needed; load it.
  1138.                Since we are loading something on this pass,
  1139.                we must make another pass through the symdef data.  */
  1140.             
  1141.             not_finished = 1;
  1142.                     
  1143.             enter_file_symbols (subentry);
  1144.                     
  1145.             read_text_and_data (desc, subentry);
  1146.             
  1147.             prev = subentry;
  1148.                     
  1149.             /* Clear out this member's symbols from the symdef data
  1150.                so that following passes won't waste time on them.  */
  1151.                     
  1152.             for (j = 0; j < number_of_symdefs; j++) {
  1153.                 if (symdef_base[j].library_member_offset == offset)
  1154.                 symdef_base[j].symbol_name_string_index = -1;
  1155.             }
  1156.             }
  1157.         }
  1158.         }
  1159.     }
  1160. } /* symdef_library */ 
  1161.  
  1162.  
  1163. /* Search a library that has no __.SYMDEF.
  1164.    ENTRY is the library's file_entry.
  1165.    DESC is the descriptor it is open on.  */
  1166.  
  1167. static void
  1168. linear_library (desc, entry)
  1169. int desc;
  1170. struct file_entry *entry;
  1171. {
  1172.     register struct file_entry *prev = 0;
  1173.     register int this_subfile_offset = SARMAG;
  1174.     
  1175.     while (undefined_global_sym_count) {
  1176.     int member_length;
  1177.     register struct file_entry *subentry;
  1178.         
  1179.     subentry = decode_library_subfile (desc, entry, this_subfile_offset, &member_length);
  1180.         
  1181.     if (!subentry) return;
  1182.         
  1183.     read_entry_symbols (desc, subentry);
  1184.     if ( allow_debugging )
  1185.         subentry->strings = (char *) xmalloc (subentry->string_size);
  1186.     else
  1187.         subentry->strings = (char *) alloca (subentry->string_size);
  1188.     read_entry_strings (desc, subentry);
  1189.         
  1190.     if (!subfile_wanted_p (subentry)) {
  1191.         free (subentry->filename);
  1192.         free (subentry->symbols);
  1193.         free (subentry);
  1194.     } else {
  1195.         enter_file_symbols (subentry);
  1196.             
  1197.         read_text_and_data (desc, subentry);
  1198.         
  1199.         if (prev)
  1200.         prev->chain = subentry;
  1201.         else entry->subfiles = subentry;
  1202.         prev = subentry;
  1203.     }
  1204.         
  1205.     this_subfile_offset += member_length + sizeof (struct ar_hdr);
  1206.     if (this_subfile_offset & 1) this_subfile_offset++;
  1207.     }
  1208. } /* linear_library */
  1209.  
  1210.  
  1211. /* ENTRY is an entry for a library member.
  1212.    Its symbols have been read into core, but not entered.
  1213.    Return nonzero if we ought to load this member.  */
  1214.  
  1215. static int
  1216. subfile_wanted_p (entry)
  1217. struct file_entry *entry;
  1218. {
  1219.     register struct nlist *p;
  1220.     register struct nlist *end
  1221.     = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  1222.     
  1223.     for (p = entry->symbols; p < end; p++) {
  1224.     register int type = p->n_type;
  1225.         
  1226.     if (type & N_EXT && (type != (N_UNDF | N_EXT) || p->n_value)) {
  1227.         register char *name = p->n_un.n_strx + entry->strings;
  1228.         register symbol *sp = getsym_soft (name);
  1229.             
  1230.         /* If this symbol has not been hashed, we can't be looking for it. */
  1231.             
  1232.         if (!sp) continue;
  1233.  
  1234.         if (sp->referenced && !sp->defined &&
  1235.         (type != (N_UNDF | N_EXT) || p->n_value))
  1236.         /* This is a symbol we are looking for.  */
  1237.         return 1;
  1238.     }
  1239.     }
  1240.     
  1241.     return 0;
  1242. } /* subfile_wanted_p */
  1243.  
  1244. /* Relocate the addresses of the file's symbols.  */
  1245. static void
  1246. relocate_symbol_address (desc, entry)
  1247. int desc;
  1248. register struct file_entry *entry;
  1249. {
  1250.     register struct nlist *p;
  1251.     register struct nlist *end
  1252.     = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  1253.     register int text_relocation, data_relocation, bss_relocation;
  1254.  
  1255.     text_relocation = entry->text_start_address;
  1256.     data_relocation = entry->data_start_address - entry->header.a_text;
  1257.     bss_relocation = entry->bss_start_address - entry->header.a_text -
  1258.     entry->header.a_data;
  1259.     
  1260.     for (p = entry->symbols; p < end; p++) {
  1261.     /* If this belongs to a section,
  1262.        update it by the section's start address */
  1263.         
  1264.     register int type = p->n_type;
  1265.     register symbol *sp;
  1266.     
  1267.     if ((type & N_EXT) == 0) continue;
  1268.     
  1269.     sp = (symbol *) p->n_un.n_name;
  1270.     if (type == (N_TEXT | N_EXT))
  1271.         sp->value += text_relocation;
  1272.     else if (type == (N_DATA | N_EXT))
  1273.         /* A symbol whose value is in the data section
  1274.            is present in the input file as if the data section
  1275.            started at an address equal to the length of the
  1276.            file's text.  */
  1277.         sp->value += data_relocation;
  1278.     else if (type == (N_BSS | N_EXT))
  1279.         /* likewise for symbols with value in BSS.  */
  1280.         sp->value += bss_relocation;
  1281.     }
  1282. } /* relocate_symbol_address */
  1283.  
  1284.  
  1285. /* Actually performs the relocation of local symbols.
  1286.    Do it once and for all for each entry.
  1287.    Then keep only those with external references online.
  1288.    This function is copied almost directly from perform_relocation (). */
  1289. static void
  1290. do_local_relocation (data, pc_relocation, reloc_info, dld_reloc_p, reloc_size,
  1291.              entry)
  1292. char *data;
  1293. struct relocation_info *reloc_info;
  1294. struct dld_reloc_info *dld_reloc_p;
  1295. struct file_entry *entry;
  1296. int pc_relocation;
  1297. int reloc_size;
  1298. {
  1299.     register struct relocation_info *p = reloc_info;
  1300.  
  1301.     struct relocation_info *end
  1302.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  1303.  
  1304.     int text_relocation = entry->text_start_address;
  1305.     int data_relocation = entry->data_start_address - entry->header.a_text;
  1306.     int bss_relocation
  1307.     = entry->bss_start_address - entry->header.a_text - entry->header.a_data;
  1308.     
  1309.     for (; p < end; p++) {
  1310.     register int relocation = 0;
  1311.     register int addr = RELOC_ADDRESS(p);
  1312.     register int symbolnum = RELOC_SYMBOL(p);
  1313.  
  1314. #if defined(sun) && defined(sparc)
  1315.     register unsigned int mask = 0;
  1316. #else
  1317.     register int length = RELOC_TARGET_SIZE(p);
  1318. #endif    
  1319.         
  1320.     if (RELOC_EXTERN_P(p)) {
  1321.         register int symindex = symbolnum * sizeof (struct nlist);
  1322.  
  1323.         dld_reloc_p->sp = ((symbol *)
  1324.                    (((struct nlist *)
  1325.                  (((char *)entry->symbols) + symindex))
  1326.                 ->n_un.n_name));
  1327.         bcopy (p, &(dld_reloc_p->reloc_info),
  1328.            sizeof (struct relocation_info));
  1329.         dld_reloc_p++;
  1330.         continue;
  1331.     } else switch (symbolnum) {
  1332.         case N_TEXT:
  1333.         case N_TEXT | N_EXT:
  1334.             relocation = text_relocation;
  1335.         break;
  1336.             
  1337.         case N_DATA:
  1338.         case N_DATA | N_EXT:
  1339.         /* A word that points to beginning of the the data section
  1340.            initially contains not 0 but rather the "address" of
  1341.            that section in the input file, which is the length of
  1342.            the file's text.  */
  1343.         relocation = data_relocation;
  1344.         break;
  1345.             
  1346.         case N_BSS:
  1347.         case N_BSS | N_EXT:
  1348.         /* Similarly, an input word pointing to the beginning of
  1349.            the bss initially contains the length of text plus data
  1350.            of the file.  */
  1351.         relocation = bss_relocation;
  1352.         break;
  1353.             
  1354.         case N_ABS:
  1355.         case N_ABS | N_EXT:
  1356.         /* just in case */
  1357.         break;
  1358.         
  1359.         default:
  1360.         break;
  1361.     }
  1362.  
  1363.     if (RELOC_PCREL_P(p))
  1364.         relocation -= pc_relocation;
  1365.  
  1366. #if defined(sun) && defined(sparc)
  1367.  
  1368.     relocation += RELOC_ADD_EXTRA(p);
  1369.  
  1370.     relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  1371.  
  1372.     /* Unshifted mask for relocation */
  1373.     mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  1374.     mask |= mask - 1;
  1375.     relocation &= mask;
  1376.  
  1377.     switch (RELOC_TARGET_SIZE(p)) {
  1378.         case 0:
  1379.             *(char *) (data + addr) &= ~mask;
  1380.         *(char *) (data + addr) |= relocation;
  1381.         break;
  1382.             
  1383.         case 1:
  1384.             *(short *) (data + addr) &= ~mask;
  1385.         *(short *) (data + addr) |= relocation;
  1386.         break;
  1387.             
  1388.         case 2:
  1389.             *(long *) (data + addr) &= ~mask;
  1390.         *(long *) (data + addr) |= relocation;
  1391.         break;
  1392.  
  1393.         default: break;
  1394.     }
  1395.  
  1396. #else    
  1397.     
  1398.     switch (length) {
  1399.         case 0: *(char *) (data + addr) += relocation;
  1400.             break;
  1401.             
  1402.         case 1: *(short *) (data + addr) += relocation;
  1403.             break;
  1404.             
  1405.         case 2: *(int *) (data + addr) += relocation;
  1406.             break;
  1407.  
  1408.         default: break;
  1409.     }
  1410. #endif
  1411.     }
  1412. } /* do_local_relocation */
  1413.  
  1414.  
  1415. /* Read the relocation information of file ENTRY into core.
  1416.    Assume it is already open, on descriptor DESC.
  1417.    Then relocate all the local (non-external) symbols.  Save only the
  1418.    relocation info for the external symbol references.
  1419.    Update entry->header.a_{trsize,drsize} to reflect the new relocation
  1420.    table size (in bytes).
  1421. */
  1422. static void
  1423. relocate_local_refs (desc, entry)
  1424. int desc;
  1425. struct file_entry *entry;
  1426. {
  1427.     int text_offset;
  1428.  
  1429.     /* number of relocation info that describes an external references. */
  1430.     int tr_entry_count = 0, dr_entry_count = 0;    
  1431.                      
  1432.     struct relocation_info *reloc_buf;
  1433.  
  1434.     if (!entry->header_read_flag)
  1435.     read_header (desc, entry);
  1436.  
  1437.     text_offset = entry->starting_offset + N_TXTOFF (entry->header);
  1438.  
  1439.     /* For the text segment */
  1440.     
  1441.     if (entry->header.a_trsize) {
  1442.     reloc_buf = (struct relocation_info *)
  1443.         xmalloc (entry->header.a_trsize);
  1444.  
  1445.     lseek (desc, text_offset + entry->header.a_text +
  1446.            entry->header.a_data, 0);
  1447.     if (entry->header.a_trsize !=
  1448.         read (desc, reloc_buf, entry->header.a_trsize)) {
  1449.         free (reloc_buf);
  1450.         fatal (DLD_ENOTXTRELOC);
  1451.     }
  1452.     if ((tr_entry_count =
  1453.          reloc_info_ok (entry->header.a_text, reloc_buf,
  1454.                 entry->header.a_trsize, entry->header.a_syms)
  1455.          ) == -1) {
  1456.         free (reloc_buf);
  1457.         fatal (DLD_EBADRELOC);
  1458.     } else {
  1459.         entry->text_reloc = (struct dld_reloc_info *)
  1460.         xmalloc (tr_entry_count * sizeof (struct dld_reloc_info));
  1461.         do_local_relocation (entry->text_start_address,
  1462.                  entry->text_start_address,
  1463.                  reloc_buf, entry->text_reloc,
  1464.                  entry->header.a_trsize, entry);
  1465.         free (reloc_buf);
  1466.     }
  1467.     }
  1468.  
  1469.     /* For the data segment */
  1470.     
  1471.     if (entry->header.a_drsize) {
  1472.     reloc_buf = (struct relocation_info *)
  1473.         xmalloc (entry->header.a_drsize);
  1474.  
  1475.     lseek (desc, text_offset + entry->header.a_text +
  1476.            entry->header.a_data + entry->header.a_trsize, 0);
  1477.     if (entry->header.a_drsize !=
  1478.         read (desc, reloc_buf, entry->header.a_drsize)) {
  1479.         free (reloc_buf);
  1480.         fatal (DLD_ENODATRELOC);
  1481.     }
  1482.     if ((dr_entry_count =
  1483.          reloc_info_ok (entry->header.a_data, reloc_buf,
  1484.                 entry->header.a_drsize, entry->header.a_syms)
  1485.          ) == -1) {
  1486.         free (reloc_buf);
  1487.         fatal (DLD_EBADRELOC);
  1488.     } else {
  1489.         entry->data_reloc = (struct dld_reloc_info *)
  1490.         xmalloc (dr_entry_count * sizeof (struct dld_reloc_info));
  1491.         do_local_relocation (entry->data_start_address,
  1492.                  entry->data_start_address -
  1493.                  entry->header.a_data, 
  1494.                  reloc_buf, entry->data_reloc,
  1495.                  entry->header.a_drsize, entry);
  1496.         free (reloc_buf);
  1497.     }
  1498.     }
  1499.  
  1500.     entry->header.a_trsize = tr_entry_count * sizeof (struct dld_reloc_info);
  1501.     entry->header.a_drsize = dr_entry_count * sizeof (struct dld_reloc_info);
  1502.  
  1503.     /* Free the nlist array. */
  1504.     if ( !allow_debugging && entry->symbols ) {
  1505.     free (entry->symbols);
  1506.     entry->symbols = 0;
  1507.     }
  1508.     
  1509. } /* relocate_local_refs */
  1510.  
  1511.  
  1512. /* Relocate ENTRY's text or data section contents.
  1513.    DATA is the address of the contents, in core.
  1514.    DATA_SIZE is the length of the contents.
  1515.    PC_RELOCATION is the difference between the address of the contents
  1516.      in the output file and its address in the input file.
  1517.    RELOC_INFO is the address of the relocation info, in core.
  1518.    RELOC_SIZE is its length in bytes.
  1519.    REVERSE is true when an 'un-relocation' is to be done.
  1520. */   
  1521.  
  1522. static void
  1523. perform_relocation (data, pc_relocation, reloc_info, reloc_size, entry,
  1524.             reverse)
  1525. char *data;
  1526. struct dld_reloc_info *reloc_info;
  1527. struct file_entry *entry;
  1528. int pc_relocation;
  1529. int reloc_size;
  1530. int reverse;
  1531. {
  1532.     register struct dld_reloc_info *p = reloc_info;
  1533.  
  1534.     struct dld_reloc_info *end
  1535.     = reloc_info + reloc_size / sizeof (struct dld_reloc_info);
  1536.     
  1537. #if defined(sun) && defined(sparc)
  1538.     if (reverse) return;
  1539. #endif
  1540.     
  1541.     for (; p < end; p++) {
  1542.     register int relocation = p->sp->value;
  1543.     register struct relocation_info *r = &(p->reloc_info);
  1544.     register int addr = RELOC_ADDRESS(r);
  1545.     
  1546. #if defined(sun) && defined(sparc)
  1547.     register unsigned int mask = 0;
  1548. #else
  1549.     register int length = RELOC_TARGET_SIZE(r);
  1550. #endif    
  1551.         
  1552.     if (RELOC_PCREL_P(r))
  1553.         relocation -= pc_relocation;
  1554.  
  1555. #if defined(sun) && defined(sparc)
  1556.  
  1557.     relocation += RELOC_ADD_EXTRA(r);
  1558.  
  1559.     relocation >>= RELOC_VALUE_RIGHTSHIFT(r);
  1560.  
  1561.     /* Unshifted mask for relocation */
  1562.     mask = 1 << RELOC_TARGET_BITSIZE(r) - 1;
  1563.     mask |= mask - 1;
  1564.     relocation &= mask;
  1565.  
  1566.     switch (RELOC_TARGET_SIZE(r)) {
  1567.         case 0:
  1568.             *(char *) (data + addr) &= ~mask;
  1569.         *(char *) (data + addr) |= relocation;
  1570.         break;
  1571.             
  1572.         case 1:
  1573.             *(short *) (data + addr) &= ~mask;
  1574.         *(short *) (data + addr) |= relocation;
  1575.         break;
  1576.             
  1577.         case 2:
  1578.             *(long *) (data + addr) &= ~mask;
  1579.         *(long *) (data + addr) |= relocation;
  1580.         break;
  1581.  
  1582.         default: break;
  1583.     }
  1584.  
  1585. #else    
  1586.     
  1587.     if (reverse) relocation = - relocation;
  1588.         
  1589.     switch (length) {
  1590.         case 0: *(char *) (data + addr) += relocation;
  1591.             break;
  1592.             
  1593.         case 1: *(short *) (data + addr) += relocation;
  1594.             break;
  1595.             
  1596.         case 2: *(int *) (data + addr) += relocation;
  1597.             break;
  1598.  
  1599.         default: break;
  1600.     }
  1601. #endif
  1602.     }
  1603. } /* perform_relocation */
  1604.  
  1605. /* given a file name, create an appropriate file_entry for it */
  1606. static struct file_entry *
  1607. make_entry (filename)
  1608. char *filename;
  1609. {
  1610.     register struct file_entry *entry =
  1611.     (struct file_entry *) xmalloc (sizeof (struct file_entry));
  1612.  
  1613.     bzero (entry, sizeof (struct file_entry));
  1614.     entry->filename = entry->local_sym_name =
  1615.     (char *) xmalloc (strlen (filename) + 1);
  1616.     strcpy (entry->local_sym_name, filename);
  1617.     
  1618.     if (filename[0] != '/') {
  1619.     char name[MAXPATHLEN];
  1620.     entry->filename = concat (getwd(name), "/", filename);
  1621.     }
  1622.     entry->chain = latest_entry;
  1623.     entry->ref_count = 1;
  1624.     return entry;
  1625. } /* make_entry */
  1626.  
  1627.  
  1628. /* If ENTRY is a rel file, read its symbol and string sections into core.
  1629.    If it is a library, search it and load the appropriate members
  1630.    (which means calling this function recursively on those members).  */
  1631.  
  1632. static void
  1633. read_file_symbols (desc, entry, load_text)
  1634. register int desc;
  1635. register struct file_entry *entry;
  1636. int load_text;                /* used only by dld_init */
  1637. {
  1638.     register int len;
  1639.     int magicnum;
  1640.     
  1641.     len = read (desc, &magicnum, sizeof magicnum);
  1642.     if (len != sizeof magicnum)
  1643.     fatal (DLD_EBADHEADER);
  1644.     
  1645.     if (!N_BADMAG (*((struct exec *)&magicnum))) {
  1646.     read_entry_symbols (desc, entry);
  1647.     if ( allow_debugging )
  1648.       entry->strings = (char *) xmalloc (entry->string_size);
  1649.     else
  1650.       entry->strings = (char *) alloca (entry->string_size);
  1651.     read_entry_strings (desc, entry);
  1652.     enter_file_symbols (entry);
  1653.     if ( !allow_debugging )
  1654.       entry->strings = 0;
  1655.     if (load_text) read_text_and_data (desc, entry);
  1656.     } else {
  1657.     char armag[SARMAG];
  1658.     
  1659.     lseek (desc, 0, 0);
  1660.     if (SARMAG != read (desc, armag, SARMAG) || strncmp (armag, ARMAG, SARMAG))
  1661.         fatal (DLD_EBADOBJECT);
  1662.     entry->library_flag = 1;
  1663.     search_library (desc, entry);
  1664.     }
  1665. } /* read_file_symbols */
  1666.  
  1667.  
  1668. /* Allocate memory for all text, data and bss segments and read them in
  1669.    from the file. */
  1670. static void
  1671. read_text_and_data (desc, entry)
  1672. int desc;
  1673. register struct file_entry *entry;
  1674. {
  1675.     register size = entry->header.a_text + entry->header.a_data +
  1676.     entry->header.a_bss;
  1677.  
  1678.     entry->text_start_address = xmalloc (size);
  1679.     if (size - entry->header.a_text > 0) {
  1680.     entry->data_start_address = entry->text_start_address +
  1681.         entry->header.a_text;
  1682.     entry->bss_start_address = entry->data_start_address +
  1683.         entry->header.a_data;
  1684.     } else entry->data_start_address = entry->bss_start_address = 0;
  1685.     
  1686.  
  1687.     /* Read text and data sections into core.
  1688.        Note that the bss segment does not actually take up space in the
  1689.        object file, so its size must be subtracted from SIZE */
  1690.     
  1691.     lseek (desc, entry->starting_offset + N_TXTOFF(entry->header), 0);
  1692.     size -= entry->header.a_bss;
  1693.     if (size != read (desc, entry->text_start_address, size)) {
  1694.     free (entry->text_start_address);
  1695.     entry->text_start_address = entry->data_start_address =
  1696.         entry->bss_start_address = 0;
  1697.     fatal (DLD_ENODATA);
  1698.     }
  1699.  
  1700.     /* zero the bss segment */
  1701.     if (entry->header.a_bss)
  1702.     bzero (entry->bss_start_address, entry->header.a_bss);
  1703. } /* read_text_and_data */
  1704.     
  1705.  
  1706. /* Allocate memory for the text and data segments and relocate all local
  1707.    symbols */
  1708. static void
  1709. relocate_entry_symbols (desc, entry)
  1710. int desc;
  1711. register struct file_entry *entry;
  1712. {
  1713.     /* Compute start addresses of each sections and symbols.  */
  1714.     
  1715.     if (entry->library_flag) {
  1716.     register struct file_entry *subentry = entry->subfiles;
  1717.     for (; subentry; subentry = subentry->chain) {
  1718.         relocate_symbol_address (desc, subentry);
  1719.         relocate_local_refs (desc, subentry);
  1720.     }
  1721.     } else {
  1722.     relocate_symbol_address (desc, entry);
  1723.     relocate_local_refs (desc, entry);
  1724.     }
  1725. } /* relocate_entry_symbols */
  1726.     
  1727.  
  1728. /*  Find all modules have all external references defined but not resolved. */
  1729. static void
  1730. patch_all_files (entry)
  1731. register struct file_entry *entry;
  1732. {
  1733.     while (entry) {
  1734.     if (entry->library_flag)
  1735.         patch_all_files (entry->subfiles);
  1736.     else if (!entry->all_symbols_resolved_flag &&
  1737.          entry->undefined_symbol_count == 0) {
  1738.         /* entry whose global references have just been resolved */
  1739.         perform_relocation (entry->text_start_address,
  1740.                 entry->text_start_address,
  1741.                 entry->text_reloc,
  1742.                 entry->header.a_trsize, entry, 0);
  1743.         perform_relocation (entry->data_start_address,
  1744.                 entry->data_start_address -
  1745.                 entry->header.a_data,
  1746.                 entry->data_reloc, entry->header.a_drsize,
  1747.                 entry, 0);
  1748.         entry->all_symbols_resolved_flag = 1;
  1749.     } else if (entry->all_symbols_resolved_flag &&
  1750.            entry->undefined_symbol_count != 0) {
  1751.         /* entry that has some of its global references being
  1752.            "un-defined" */
  1753.         perform_relocation (entry->text_start_address,
  1754.                 entry->text_start_address,
  1755.                 entry->text_reloc,
  1756.                 entry->header.a_trsize, entry, 1);
  1757.         perform_relocation (entry->data_start_address,
  1758.                 entry->data_start_address -
  1759.                 entry->header.a_data,
  1760.                 entry->data_reloc, entry->header.a_drsize,
  1761.                 entry, 1);
  1762.         entry->all_symbols_resolved_flag = 0;
  1763.     }
  1764.  
  1765.     entry = entry->chain;
  1766.     }
  1767. } /* patch_all_files */
  1768.  
  1769.  
  1770. /*
  1771.  * reset the executable_flag of the given entry, and then recursively
  1772.  * propagate this to all modules that reference symbols in this entry.
  1773.  */
  1774. static void
  1775. invalidate (entry)
  1776. struct file_entry *entry;
  1777. {
  1778.     register struct file_chain *p;
  1779.     
  1780.     if (entry == 0)
  1781.     return;
  1782.     
  1783.     entry->executable_flag = 0;
  1784.  
  1785.     for (p = entry->refs_by; p; p = p->next)
  1786.     if (p->entry->executable_flag)
  1787.         invalidate (p->entry);
  1788. } /* invalidate */
  1789.  
  1790. /*
  1791.  * For all modules loaded, determine which of them can be safely executed.
  1792.  * For those that can, set the flag executable_flag.
  1793.  */
  1794. static void
  1795. find_all_executable_modules ()
  1796. {
  1797.     register struct file_entry *p;
  1798.  
  1799.     /* set all executable flags */
  1800.     for (p = latest_entry; p ; p = p->chain) {
  1801.     if (p->library_flag) {
  1802.         register struct file_entry *q = p->subfiles;
  1803.         while (q) {
  1804.         q->executable_flag = q->all_symbols_resolved_flag;
  1805.         q = q->chain;
  1806.         }
  1807.     }
  1808.     p->executable_flag = p->all_symbols_resolved_flag;
  1809.     }
  1810.     
  1811.     /* invalidate those modules that are not (yet) executable. */
  1812.     for (p = latest_entry; p; p = p->chain) {
  1813.     if (p->library_flag) {
  1814.         register struct file_entry *q = p->subfiles;
  1815.         while (q) {
  1816.         if (!q->all_symbols_resolved_flag && q->refs_by)
  1817.             invalidate (q);
  1818.         q = q->chain;
  1819.         }
  1820.     } else if (!p->all_symbols_resolved_flag && p->refs_by)
  1821.         invalidate (p);
  1822.     }
  1823.     executable_flags_up_to_date = 1;
  1824. } /* find_all_executable_modules */
  1825.  
  1826.  
  1827. /* remove all reference pointers *TO* ENTRY */
  1828. static void 
  1829. remove_cross_references (head_of_chain, entry)
  1830. struct file_entry *head_of_chain, *entry;
  1831. {
  1832.     register struct file_entry *ep = head_of_chain;
  1833.     
  1834.     while (ep) {
  1835.     register struct file_chain *p = ep->refs;
  1836.     
  1837.     if (ep->library_flag)
  1838.         remove_cross_references (ep->subfiles, entry);
  1839.     else {
  1840.         register struct file_chain *prev = 0;
  1841.         
  1842.         while (p) {
  1843.         if (p->entry == entry || p->entry->superfile == entry) {
  1844.             del_link_list_elt (ep->refs, prev, p, next);
  1845.         } else {
  1846.             prev = p;
  1847.             p = p->next;
  1848.         }
  1849.         }
  1850.     }
  1851.     ep = ep->chain;
  1852.     }
  1853. } /* remove_cross_references */
  1854.  
  1855.  
  1856. /* remove all cross reference pointers related to an obsolete file entry.
  1857.    It is assumed that the ref_count of this entry is zero.
  1858.    Also clear up all other entries that become obsolete when this entry is
  1859.    removed. */
  1860. static void
  1861. cleanup_obsolete_entries (entry)
  1862. struct file_entry *entry;
  1863. {
  1864.     register struct file_chain *p;
  1865.  
  1866.     if (entry->ref_count != 0) return;
  1867.  
  1868.     if (entry->library_flag) {
  1869.     register struct file_entry *subentry = entry->subfiles;
  1870.  
  1871.     for (; subentry; subentry = subentry->chain)
  1872.         cleanup_obsolete_entries (subentry);
  1873.     }
  1874.  
  1875.     p = entry->refs;
  1876.     entry->refs = 0;            /* to prevent loop; might be redundant*/
  1877.  
  1878.     while (p) {
  1879.     register struct file_chain *next = p->next;
  1880.     
  1881.     if (p->entry->ref_count)    /* ref_count may already be set to zero */
  1882.         (p->entry->ref_count)--;
  1883.     if (p->entry->ref_count == 0)
  1884.         cleanup_obsolete_entries (p->entry);
  1885.     free (p);
  1886.     p = next;
  1887.     }
  1888. } /* cleanup_obsolete_entries */
  1889.  
  1890.  
  1891. /* remove all memory blocks assigned for ENTRY,
  1892.    return the pointers to the next entry in chain */
  1893. static struct file_entry *
  1894. kill_entry (entry)
  1895. register struct file_entry *entry;
  1896. {
  1897.     register struct file_chain *p;
  1898.  
  1899.     if (entry->library_flag) {
  1900.     register struct file_entry *subentry = entry->subfiles;
  1901.     while (subentry)
  1902.         subentry = kill_entry (subentry);
  1903.     }
  1904.     
  1905.     p = entry->refs;
  1906.     while (p) {
  1907.     register struct file_chain *next_chain = p->next;
  1908.     free (p);
  1909.     p = next_chain;
  1910.     }
  1911.  
  1912.     p = entry->refs_by;
  1913.     while (p) {
  1914.     register struct file_chain *next_chain = p->next;
  1915.     free (p);
  1916.     p = next_chain;
  1917.     }
  1918.  
  1919.     if (entry->local_sym_name) free (entry->local_sym_name);
  1920.  
  1921.     if (entry->filename != entry->local_sym_name && entry->filename)
  1922.     free (entry->filename);
  1923.  
  1924.     if (entry->symbols) free (entry->symbols);
  1925.  
  1926.     if (entry->text_reloc) free (entry->text_reloc);
  1927.  
  1928.     if (entry->data_reloc) free (entry->data_reloc);
  1929.  
  1930.     if (entry->text_start_address) free (entry->text_start_address);
  1931.  
  1932.     {
  1933.     register struct file_entry *next = entry->chain;
  1934.     free (entry);
  1935.     return (next);
  1936.     }
  1937. } /* kill_entry */
  1938.  
  1939.  
  1940. /* clean all data structures so that they return to the original states
  1941.    after last call to dld */
  1942. static void
  1943. clean_up ()
  1944. {
  1945.  
  1946.     if (!latest_entry)
  1947.     return;
  1948.  
  1949.     latest_entry->ref_count = 0;
  1950.     if (latest_entry->library_flag) {
  1951.     register struct file_entry *subentry = latest_entry->subfiles;
  1952.     for (; subentry; subentry = subentry->chain)
  1953.         subentry->ref_count = 0;
  1954.     }
  1955.     
  1956.     remove_cross_references (latest_entry, latest_entry);
  1957.  
  1958.     cleanup_obsolete_entries (latest_entry);
  1959.  
  1960.     cleanup_symtab ();
  1961.     
  1962.     latest_entry = kill_entry (latest_entry);
  1963. } /* clean_up */
  1964.  
  1965.  
  1966. /* Actually perform the unlink operation.
  1967.    Search through the list of file entries, unlink those whose ref_count is
  1968.    zero. */
  1969. static struct file_entry *
  1970. do_unlink (entry)
  1971. struct file_entry *entry;
  1972. {
  1973.     register struct file_entry *p = entry;
  1974.     register struct file_entry *prev = 0;
  1975.     
  1976.     if (p == 0) return p;
  1977.  
  1978.     while (p) {
  1979.     if (p->library_flag) {
  1980.         p->subfiles = do_unlink (p->subfiles);
  1981.  
  1982.         /* if all subentries are gone, remove itself */
  1983.         if (p->subfiles == 0)
  1984.         p->ref_count = 0;
  1985.     }
  1986.  
  1987.     if (p->ref_count == 0) {
  1988.         register struct file_entry *next;
  1989.         
  1990.         next = kill_entry (p);
  1991.     
  1992.         if (prev == 0) {
  1993.         entry = next;
  1994.         p = entry;
  1995.         } else {
  1996.         prev->chain = next;
  1997.         p = prev->chain;
  1998.         }
  1999.     } else {
  2000.         prev = p;
  2001.         p = p->chain;
  2002.     }
  2003.     }
  2004.     executable_flags_up_to_date = 0;
  2005.     return entry;
  2006. } /* do_unlink */
  2007.  
  2008. dld_init (myname, debug)
  2009. char *myname;
  2010. int debug;
  2011. {
  2012.     int desc;
  2013.     
  2014.     allow_debugging = debug;
  2015.     page_size = getpagesize ();
  2016.     bzero (symtab, TABSIZE * sizeof(symbol *));
  2017.     latest_entry = 0;
  2018.     undefined_global_sym_count = 0;
  2019.     executable_flags_up_to_date = 0;
  2020.     
  2021.     if (myname == 0) {
  2022.     dld_errno = DLD_ENOFILE;
  2023.     return dld_errno;
  2024.     }
  2025.     
  2026.     if (setjmp (env)) {
  2027.     clean_up ();
  2028.     file_close ();
  2029.     return dld_errno;
  2030.     }
  2031.     latest_entry = make_entry (myname);
  2032.     desc = file_open (latest_entry);
  2033.     read_file_symbols (desc, latest_entry, 0);
  2034.  
  2035.     if ( !allow_debugging && latest_entry->symbols ) {
  2036.     free (latest_entry->symbols);
  2037.     latest_entry->symbols = 0;
  2038.     }
  2039.     
  2040.     file_close ();
  2041.  
  2042.     latest_entry->undefined_symbol_count = 0;
  2043.     latest_entry->all_symbols_resolved_flag = 1;
  2044.     
  2045.     return 0;
  2046. } /* dld_init */
  2047.  
  2048.  
  2049. dld_link (object_file)
  2050. char *object_file;
  2051. {
  2052.     register int desc;
  2053.     struct file_entry *old_latest_entry = latest_entry;
  2054.  
  2055.     if (setjmp (env)) {
  2056.     if (old_latest_entry != latest_entry)
  2057.         clean_up ();
  2058.     file_close ();
  2059.     return dld_errno;
  2060.     }
  2061.  
  2062.     dld_errno = 0;
  2063.     file_close ();            /* file might be opened in the last
  2064.                        call */
  2065.     
  2066.     if (object_file == 0) {
  2067.     dld_errno = DLD_ENOFILE;
  2068.     return dld_errno;
  2069.     }
  2070.     
  2071.     latest_entry = make_entry (object_file);
  2072.  
  2073.     desc = file_open (latest_entry);
  2074.     
  2075.     read_file_symbols (desc, latest_entry, 1);
  2076.  
  2077.     if (latest_entry->library_flag && latest_entry->subfiles == 0) {
  2078.     free (latest_entry->local_sym_name);
  2079.     if (latest_entry->filename != latest_entry->local_sym_name)
  2080.         free (latest_entry->filename);
  2081.     
  2082.     latest_entry = kill_entry (latest_entry);
  2083.     file_close ();
  2084.     return 0;
  2085.     }
  2086.     
  2087.     relocate_entry_symbols (desc, latest_entry);
  2088.     
  2089.     file_close ();
  2090.     
  2091.     patch_all_files (latest_entry);
  2092.  
  2093.     executable_flags_up_to_date = 0;
  2094.     return 0;
  2095. } /* dld_link */
  2096.  
  2097.  
  2098. /* return the location of the given symbol without prepending a '_'. */
  2099. unsigned long
  2100. dld_get_bare_symbol (name)
  2101. char *name;
  2102. {
  2103.     register symbol *sp;
  2104.     
  2105.     if (name == 0)
  2106.     return 0;
  2107.  
  2108.     sp = getsym_soft (name);
  2109.  
  2110.     if (sp)
  2111.     if (sp->defined)
  2112.         return sp->value;
  2113.     return 0;
  2114. } /* dld_get_bare_symbol */
  2115.  
  2116.  
  2117. /* given a symbol name, return the location of that symbol (in core) */
  2118. unsigned long
  2119. dld_get_symbol (name)
  2120. char name[];
  2121. {
  2122.     register symbol *sp;
  2123.     register char *p;
  2124.  
  2125.     if (name == 0)
  2126.     return 0;
  2127.  
  2128.     /* prepend a '_' to name, as required by C's convention */
  2129.     p = (char *) alloca (strlen(name) + 2);
  2130.     *p = '_';
  2131.     strcpy (p+1, name);
  2132.  
  2133.     return dld_get_bare_symbol (p);
  2134. } /* dld_get_symbol */
  2135.  
  2136.     
  2137. /*  given a function name, return the location of that function (in core) */
  2138. unsigned long
  2139. dld_get_func (name)
  2140. char name[];
  2141. {
  2142.     register symbol *sp;
  2143.     register char *p;
  2144.  
  2145.     if (name == 0)
  2146.     return 0;
  2147.     
  2148.     /* prepend a '_' to name, as required by C's convention */
  2149.     p = (char *) alloca (strlen(name) + 2);
  2150.     *p = '_';
  2151.     strcpy (p+1, name);
  2152.  
  2153.     sp = getsym_soft (p);
  2154.  
  2155.     if (sp)
  2156.     if (sp->defined == (N_EXT | N_TEXT))
  2157.         return sp->value;
  2158.     return 0;
  2159. } /* dld_get_func */
  2160.  
  2161.  
  2162. /* given a file_entry, unlink that (and all its decendents).  Modules still
  2163.    referenced by the remainings will not be unlinked.
  2164.    ENTRY is assumed to be a valid pointer to a file_entry structure.
  2165.    if FORCE is true, remove this entry event regardless if it is still
  2166.    referenced by others */
  2167. static void
  2168. unlink_entry (entry, force)
  2169. struct file_entry *entry;
  2170. int force;
  2171. {
  2172.     if (force) {
  2173.     entry->ref_count = 0;
  2174.     if (entry->library_flag) {
  2175.         register struct file_entry *subentry = entry->subfiles;
  2176.         for (; subentry; subentry = subentry->chain)
  2177.         subentry->ref_count = 0;
  2178.     }
  2179.     } else {
  2180.     register struct file_entry *fe;
  2181.     register int found;
  2182.     
  2183.     if (entry->library_flag || entry->already_unlink) return;
  2184.     for (found = 0, fe = latest_entry; fe; fe = fe->chain)
  2185.         if (fe == entry) {
  2186.         entry->ref_count--;
  2187.         entry->already_unlink = 1;
  2188.         found = 1;
  2189.         break;
  2190.         }
  2191.     if (!found) return;
  2192.     }
  2193.  
  2194.     if (entry->ref_count == 0) {
  2195.     remove_cross_references (latest_entry, entry);
  2196.  
  2197.     cleanup_obsolete_entries (entry);
  2198.  
  2199.     cleanup_symtab ();
  2200.  
  2201.     latest_entry = do_unlink (latest_entry);
  2202.     }
  2203.  
  2204.     patch_all_files (latest_entry);
  2205.     executable_flags_up_to_date = 0;
  2206. } /* unlink_entry */
  2207.  
  2208.  
  2209. static struct file_entry *
  2210. search_files (entry, name)
  2211. register struct file_entry *entry;
  2212. register char *name;
  2213. {
  2214.     while (entry) {
  2215.     if (entry->library_flag) {
  2216.         register struct file_entry *subentry;
  2217.  
  2218.         if ((subentry = search_files (entry->subfiles, name)) != 0)
  2219.         return subentry;
  2220.     } else {
  2221.         if (!strcmp (entry->local_sym_name, name))
  2222.         return entry;
  2223.         if (entry->local_sym_name != entry->filename)
  2224.         if (!strcmp (entry->filename, name))
  2225.             return entry;
  2226.     }
  2227.  
  2228.     entry = entry->chain;
  2229.     }
  2230.     return 0;
  2231. } /* search_files */
  2232.  
  2233.  
  2234. dld_unlink_by_file (name, force)
  2235. char *name;
  2236. int force;
  2237. {
  2238.     register struct file_entry *entry;
  2239.  
  2240.     if (entry = search_files (latest_entry, name)) {
  2241.     unlink_entry (entry, force);
  2242.     return 0;
  2243.     }
  2244.  
  2245.     dld_errno = DLD_EUNDEFSYM;
  2246.     return dld_errno;
  2247. } /* dld_unlink_by_file */
  2248.  
  2249.  
  2250. dld_unlink_by_symbol (name, force)
  2251. char *name;
  2252. int force;
  2253. {
  2254.     register symbol *sp;
  2255.     register char *p;
  2256.  
  2257.     if (name == 0) {
  2258.     dld_errno = DLD_EUNDEFSYM;
  2259.     return dld_errno;
  2260.     }
  2261.  
  2262.     /* prepend a '_' to name, as required by C's convention */
  2263.     p = (char *) alloca (strlen(name) + 2);
  2264.     *p = '_';
  2265.     strcpy (p+1, name);
  2266.  
  2267.     sp = getsym_soft (p);
  2268.  
  2269.     if (sp && sp->defined_by) {
  2270.     unlink_entry (sp->defined_by, force);
  2271.     return 0;
  2272.     }
  2273.  
  2274.     dld_errno = DLD_EUNDEFSYM;
  2275.     return dld_errno;
  2276. } /* dld_unlink_by_symbol */
  2277.  
  2278.  
  2279. /*
  2280.  * return true if the named function can be safely exeucted.
  2281.  */
  2282. dld_function_executable_p (name)
  2283. char name[];
  2284. {
  2285.     register symbol *sp;
  2286.     register char *p;
  2287.  
  2288.     if (name == 0)
  2289.     return 0;
  2290.  
  2291.     /* prepend an '_' to name, as required by the C convention */
  2292.     p = (char *) alloca (strlen(name) + 2);
  2293.     *p = '_';
  2294.     strcpy (p+1, name);
  2295.     sp = getsym_soft (p);
  2296.  
  2297.     if (sp && sp->defined == (N_EXT | N_TEXT)) {
  2298.     register struct file_entry *fe = sp->defined_by;
  2299.  
  2300.     if (fe == 0) return 0;
  2301.     
  2302.     if (!executable_flags_up_to_date)
  2303.         find_all_executable_modules ();
  2304.  
  2305.     return fe->executable_flag;
  2306.     }
  2307.  
  2308.     return 0;
  2309. } /* dld_function_executable_p */
  2310.  
  2311.     
  2312. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  2313. Additions  from Jan Wielemaker  (jan@swi.psy.uva.nl).  These functions
  2314. are to provide some  elementary debugging facilities.   I do not claim
  2315. this to be a neat debugging interface; it's just  to help me finish my
  2316. program.
  2317. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  2318.  
  2319.  
  2320. int
  2321. dld_list_undefined()
  2322. { symbol *s;
  2323.   int n;
  2324.   int warned = 0;
  2325.  
  2326.   for(n=0; n<TABSIZE; n++)
  2327.   { for( s = symtab[n]; s; s = s->link )
  2328.       if ( !s->defined )
  2329.       { if ( warned++ == 0 )
  2330.       fprintf(stderr, "dld: undefined:\n");
  2331.     fprintf(stderr, "\t%s\n", s->name);
  2332.       }
  2333.   }
  2334.  
  2335.   return warned;
  2336. }
  2337.   
  2338.  
  2339. /* nlist_symbol_name() returns the name of a symbol.  This would have been
  2340.    simple but the global nlist entries are patched such that n_un.n_name points
  2341.    to a global symbol.  We simply check for one of the three reasonable
  2342.    representations.  As long as pointers start at addresses larger than the
  2343.    string table of the entry this is save.
  2344. */
  2345.  
  2346. static char *
  2347. nlist_symbol_name(entry, symb)
  2348. struct file_entry *entry;
  2349. struct nlist *symb;
  2350. { if ( symb->n_un.n_strx < entry->string_size )
  2351.     return entry->strings + symb->n_un.n_strx;
  2352.  
  2353.   if ( symb->n_un.n_name >= entry->strings &&
  2354.        symb->n_un.n_name  < entry->strings + entry->string_size )
  2355.     return symb->n_un.n_name;
  2356.  
  2357.   return ((symbol *)symb->n_un.n_name)->name;
  2358. }
  2359.  
  2360.  
  2361. /* find_function_in_entry() checks whether an address is in the text area
  2362.    the specified entry.  If so it scans the symbol table to find the
  2363.    text symbols with the highest value below and with the lowest value
  2364.    above the address.  From there it determines the name and percentage
  2365.    we are in the function.
  2366. */
  2367.  
  2368. static int
  2369. find_function_in_entry(entry, address, name, perc) 
  2370. struct file_entry *entry;
  2371. unsigned long address;
  2372. char **name;
  2373. int *perc;
  2374. { long start = entry->text_start_address;
  2375.   long end   = start + entry->header.a_text;
  2376.  
  2377.                     /* HACK; if it is the original file */
  2378.                     /* use etext for the end, so it */
  2379.                     /* cooperates nice with ld -A based */
  2380.                     /* foreign interfaces that loaded */
  2381.                     /* me. */
  2382.   if ( !entry->superfile && !entry->chain )
  2383.   { extern etext;
  2384.  
  2385.     end = (long) &etext;
  2386.   }
  2387.  
  2388.   if ( address >= start && address < end )
  2389.   { if ( !entry->symbols || !entry->strings )
  2390.     { *perc = 0;            /* no symbols */
  2391.       *name = "???";
  2392.     } else
  2393.     { struct nlist *symb = entry->symbols;
  2394.       struct nlist *target = NULL;
  2395.       int nsymbols = entry->header.a_syms / sizeof(struct nlist);
  2396.       int n;
  2397.       unsigned long below = 0;
  2398.       unsigned long above = end - start;
  2399.  
  2400.       address -= start;
  2401.  
  2402.       for(n=0; n<nsymbols; n++, symb++)
  2403.       { if ( symb->n_type & N_TEXT )    /* a function */
  2404.     { unsigned long value = symb->n_value;
  2405.  
  2406.       if ( value <= address && value >= below )
  2407.       { below = value;
  2408.         target = symb;
  2409.       } else if ( value > address && value < above )
  2410.         above = value;
  2411.     }
  2412.       }
  2413.  
  2414.       if ( target )
  2415.       { *name = nlist_symbol_name(entry, target) + 1; /* 1 for the '_' */
  2416.  
  2417.     if ( above > below )
  2418.       *perc = ((address - below) * 100) / (above - below);
  2419.     else
  2420.       *perc = 0;
  2421.       } else
  2422.       { *name = "???";
  2423.         *perc = 0;
  2424.       }
  2425.     }
  2426.  
  2427.     return 1;
  2428.   }
  2429.  
  2430.   return 0;
  2431. }
  2432.  
  2433.  
  2434. /* dld_find_function () is the entry point for this debugging stuff.  It
  2435.    returns the name for the function that contains text address address as
  2436.    well as the percentage from the beginning of the function.
  2437. */
  2438.  
  2439. char *
  2440. dld_find_function(address, perc)
  2441. unsigned long address;
  2442. int *perc;
  2443. { struct file_entry *entry = latest_entry;
  2444.   char *name;
  2445.  
  2446.   for( ; entry ; entry = entry->chain )
  2447.   { if ( entry->library_flag )
  2448.     { struct file_entry *subfile = entry->subfiles;
  2449.  
  2450.       for( ; subfile ; subfile = subfile->chain )
  2451.           if ( find_function_in_entry(subfile, address, &name, perc) )
  2452.       return name;
  2453.     } else
  2454.     { if ( find_function_in_entry(entry, address, &name, perc) )
  2455.     return name;
  2456.     }
  2457.   }
  2458.  
  2459.   *perc = 0;
  2460.  
  2461.   return "???";
  2462. }
  2463.  
  2464.  
  2465. long
  2466. dld_text_start(file)
  2467. char *file;
  2468. { struct file_entry *entry = latest_entry;
  2469.  
  2470.   for( ; entry ; entry = entry->chain )
  2471.   { if ( entry->library_flag )
  2472.     { struct file_entry *subfile = entry->subfiles;
  2473.  
  2474.       for( ; subfile ; subfile = subfile->chain )
  2475.           if ( strcmp(file, subfile->filename) )
  2476.       return subfile->text_start_address;
  2477.     } else
  2478.     { if ( strcmp(file, entry->filename) )
  2479.     return entry->text_start_address;
  2480.     }
  2481.   }
  2482.  
  2483.   return 0;
  2484. }
  2485.