home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / zip / gnu / utlsrc33.lzh / UTLSRC33 / SYM-LD.C < prev    next >
C/C++ Source or Header  |  1993-07-30  |  135KB  |  4,976 lines

  1. /* Linker `ld' for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Richard Stallman with some help from Eric Albert.
  19.    Set, indirect, and warning symbol features added by Randy Smith.  */
  20.  
  21. #ifdef CROSSATARI
  22. #  ifdef atarist
  23. #    undef atarist
  24. #  endif
  25. #  ifdef atariminix
  26. #    undef atariminix
  27. #  endif
  28. #endif
  29.  
  30. #include "PatchLev.h"
  31.  
  32. #if (!(defined(CROSSATARI) || defined(atarist) || defined(atariminix)))
  33.  
  34. #include <ar.h>
  35. #include <stdio.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. #include <sys/file.h>
  39. #include <fcntl.h>
  40.  
  41. #ifdef COFF_ENCAPSULATE
  42. #include "a.out.encap.h"
  43. #else
  44. #include <a.out.h>
  45. #endif
  46.  
  47. #else
  48.  
  49. #ifdef CROSSATARI
  50. #  include "gnu-out.h"
  51. #  include "gnu-ar.h"
  52. #  ifdef MINIX
  53. #    include "minix-out.h"
  54. #  else
  55. #    include "st-out.h"
  56. #  endif /* MINIX */
  57. #  include <stdio.h>
  58. #  include <sys/types.h>
  59. #  include <string.h>
  60. #  include <sys/stat.h>
  61. #  include <sys/file.h>
  62. #  include <ctype.h>
  63. #else
  64. #  ifdef atariminix
  65. #    include <stdio.h>
  66. #    include <sys/types.h>
  67. #    include <string.h>
  68. #    include <sys/stat.h>
  69. #    include <ctype.h>
  70. #    if 0            /* if you are *not* using a kernel with */
  71.             /* simon poole fs patches use this      */
  72. #      define EMUL_OPEN3
  73. #      include "open3.h"
  74. #    else
  75. #      include <fcntl.h>
  76. #    endif
  77. #    include "gnu-out.h"
  78. #    include "minix-out.h"
  79. #    include "gnu-ar.h"    /* we use the Gnu ar for minix, not the minix */
  80. #  else
  81. #    include "gnu-out.h"
  82. #    include <st-out.h>
  83. #    include "gnu-ar.h"
  84. #    include <stdio.h>
  85. #    include <types.h>
  86. #    include <string.h>
  87. #    include <stat.h>
  88. #    include <file.h>
  89. #    include <ctype.h>
  90. #    include <unistd.h>
  91. #  endif
  92. #endif        /* atarist */
  93.  
  94. #define ONLY_SYMBOLS
  95.  
  96. #endif
  97.  
  98. /* If compiled with GNU C, use the built-in alloca */
  99. #ifdef __GNUC__
  100. #  ifndef atariminix
  101. #    define alloca __builtin_alloca
  102. #  endif
  103. #endif
  104.  
  105. /* Always use the GNU version of debugging symbol type codes, if possible.  */
  106.  
  107. #include "stab.h"
  108. #define CORE_ADDR unsigned long    /* For symseg.h */
  109. #include "symseg.h"
  110.  
  111. #ifdef USG
  112. #include <string.h>
  113. #else
  114. #include <strings.h>
  115. #endif
  116.  
  117. #if __STDC__
  118. #  include <stdarg.h>
  119. #else
  120. #  include <varargs.h>
  121. #endif
  122.  
  123. /* Determine whether we should attempt to handle (minimally)
  124.    N_BINCL and N_EINCL.  */
  125.  
  126. #if (!(defined(atarist) || defined(atariminix) || defined(CROSSATARI)))
  127. #if defined (__GNU_STAB__) || defined (N_BINCL)
  128. #define HAVE_SUN_STABS
  129. #endif
  130. #endif
  131.  
  132. #ifdef atarist        /* and a stack */
  133. long _stksize = -1L;
  134. #endif
  135.  
  136. #ifdef min
  137. #undef min
  138. #endif
  139. #define min(a,b) ((a) < (b) ? (a) : (b))
  140.  
  141. /* Macro to control the number of undefined references printed */
  142. #define MAX_UREFS_PRINTED    10
  143.  
  144. /* Size of a page; obtained from the operating system.  */
  145.  
  146. int page_size;
  147.  
  148. /* Name this program was invoked by.  */
  149.  
  150. char *progname;
  151.  
  152. /* System dependencies */
  153.  
  154. /* Define this if names etext, edata and end should not start with `_'.  */
  155. /* #define nounderscore 1 */
  156.  
  157. /* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
  158.    whose native format is different.  */
  159. /* #define NON_NATIVE */
  160.  
  161. /* Define this to specify the default executable format.  */
  162.  
  163. #ifndef CROSSHPUX
  164. #ifdef hpux
  165. #define DEFAULT_MAGIC NMAGIC  /* hpux bugs screw ZMAGIC */
  166. #endif
  167. #endif
  168.  
  169. #ifndef DEFAULT_MAGIC
  170. #define DEFAULT_MAGIC ZMAGIC
  171. #endif
  172.  
  173. /* Ordinary 4.3bsd lacks these macros in a.out.h.  */
  174.  
  175. #ifndef N_TXTADDR
  176. #ifdef vax
  177. #define N_TXTADDR(X) 0
  178. #endif
  179. #ifdef is68k
  180. #define N_TXTADDR(x)  (sizeof (struct exec))
  181. #endif
  182. #endif
  183.  
  184. #ifndef N_DATADDR
  185. #ifdef vax
  186. #define N_DATADDR(x) \
  187.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  188.     : (page_size+((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  189. #endif
  190. #ifdef is68k
  191. #define SEGMENT_SIZE 0x20000
  192. #define N_DATADDR(x) \
  193.     (((x).a_magic==Omagic)? (N_TXTADDR(x)+(x).a_text) \
  194.      : (SEGMENT_SIZE + ((N_TXTADDR(x)+(x).a_text-1) & ~(SEGMENT_SIZE-1))))
  195. #endif
  196. #endif
  197.  
  198. #ifndef CROSSHPUX
  199. #ifdef hpux
  200. #define getpagesize() EXEC_PAGESIZE
  201. #endif
  202. #endif
  203.  
  204. #if (defined(atarist) || defined(atariminix) || defined(CROSSATARI))
  205. /* kludgerama, not really used */
  206. #define getpagesize() 2
  207. #endif
  208.  
  209. /* Define how to initialize system-dependent header fields.  */
  210. #ifndef CROSSATARI
  211. #ifdef sun
  212. #ifdef sparc
  213. #define INITIALIZE_HEADER \
  214.   {outheader.a_machtype = M_SPARC; outheader.a_toolversion = 1;}
  215. #endif
  216. #if defined(mc68010) || defined(m68010) || (TARGET == SUN2)
  217. #define INITIALIZE_HEADER outheader.a_machtype = M_68010
  218. #endif
  219. #ifndef INITIALIZE_HEADER
  220. #define INITIALIZE_HEADER outheader.a_machtype = M_68020
  221. #endif
  222. #endif
  223. #ifdef is68k
  224. #ifdef M_68020
  225. /* ISI rel 4.0D doesn't use it, and rel 3.05 doesn't have an
  226.    a_machtype field and so won't recognize the magic number.  To keep
  227.    binary compatibility for now, just ignore it */
  228. #define INITIALIZE_HEADER outheader.a_machtype = 0;
  229. #endif
  230. #endif
  231. #ifndef CROSSHPUX
  232. #ifdef hpux
  233. #define INITIALIZE_HEADER outheader.a_machtype = HP9000S200_ID
  234. #endif
  235. #endif
  236. #ifdef i386
  237. #define INITIALIZE_HEADER outheader.a_machtype = M_386
  238. #endif
  239. #endif /* CROSSATARI */
  240.  
  241. #ifdef is68k
  242. /* This enables code to take care of an ugly hack in the ISI OS.
  243.    If a symbol beings with _$, then the object file is included only
  244.    if the rest of the symbol name has been referenced. */
  245. #define DOLLAR_KLUDGE
  246. #endif
  247.  
  248. /*
  249.  * Alloca include.
  250.  */
  251. #if defined(sun) && defined(sparc)
  252. #ifdef alloca
  253. #undef alloca
  254. #endif
  255. #include <alloca.h>
  256. #endif
  257.  
  258. #ifndef L_SET
  259. #define L_SET 0
  260. #endif
  261.  
  262. /*
  263.  * Ok.  Following are the relocation information macros.  If your
  264.  * system should not be able to use the default set (below), you must
  265.  * define the following:
  266.  
  267.  *   relocation_info: This must be typedef'd (or #define'd to the type
  268.  * of structure that is stored in the relocation info section of your
  269.  * a.out files.  Often this is defined in the a.out.h for your system.
  270.  *
  271.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  272.  * <whatever> to be relocated.  *Must be an lvalue*.
  273.  *
  274.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  275.  * external symbol (1), or was it fully resolved upon entering the
  276.  * loader (0) in which case some combination of the value in memory
  277.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  278.  * what the value of the relocation actually was.  *Must be an lvalue*.
  279.  *
  280.  *   RELOC_TYPE (rval): If this entry was fully resolved upon
  281.  * entering the loader, what type should it be relocated as?
  282.  *
  283.  *   RELOC_SYMBOL (rval): If this entry was not fully resolved upon
  284.  * entering the loader, what is the index of it's symbol in the symbol
  285.  * table?  *Must be a lvalue*.
  286.  *
  287.  *   RELOC_MEMORY_ADD_P (rval): This should return true if the final
  288.  * relocation value output here should be added to memory, or if the
  289.  * section of memory described should simply be set to the relocation
  290.  * value.
  291.  *
  292.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  293.  * an extra value to be added to the relocation value based on the
  294.  * individual relocation entry.
  295.  *
  296.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  297.  * pc relative.
  298.  *
  299.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  300.  * final relocation value before putting it where it belongs.
  301.  *
  302.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  303.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  304.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  305.  * do everything in terms of the bit operators below), but having this
  306.  * macro could end up producing better code on machines without fancy
  307.  * bit twiddling.  Also, it's easier to understand/code big/little
  308.  * endian distinctions with this macro.
  309.  *
  310.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  311.  * object described in RELOC_TARGET_SIZE in which the relocation value
  312.  * will go.
  313.  *
  314.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  315.  * with the bits of the relocation value.  It may be assumed by the
  316.  * code that the relocation value will fit into this many bits.  This
  317.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  318.  *
  319.  *
  320.  *        Things I haven't implemented
  321.  *        ----------------------------
  322.  *
  323.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  324.  *
  325.  *    Pc relative relocation for External references.
  326.  *
  327.  *
  328.  */
  329.  
  330. #if defined(sun) && defined(sparc) && !defined(CROSSATARI)
  331. /* Sparc (Sun 4) macros */
  332. #undef relocation_info
  333. #define relocation_info                    reloc_info_sparc
  334. #define RELOC_ADDRESS(r)        ((r)->r_address)                 
  335. #define RELOC_EXTERN_P(r)               ((r)->r_extern)      
  336. #define RELOC_TYPE(r)                   ((r)->r_index)  
  337. #define RELOC_SYMBOL(r)                 ((r)->r_index)   
  338. #define RELOC_MEMORY_ADD_P(r)           0                          
  339. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)       
  340. #define RELOC_PCREL_P(r)             \
  341.         ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22)
  342. #define RELOC_VALUE_RIGHTSHIFT(r)       (reloc_target_rightshift[(r)->r_type])
  343. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(r)->r_type])
  344. #define RELOC_TARGET_BITPOS(r)          0
  345. #define RELOC_TARGET_BITSIZE(r)         (reloc_target_bitsize[(r)->r_type])
  346.  
  347. /* Note that these are very dependent on the order of the enums in
  348.    enum reloc_type (in a.out.h); if they change the following must be
  349.    changed */
  350. /* Also note that the last few may be incorrect; I have no information */
  351. static int reloc_target_rightshift[] = {
  352.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  353. };
  354. static int reloc_target_size[] = {
  355.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  356. };
  357. static int reloc_target_bitsize[] = {
  358.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  359. };
  360. #endif
  361.  
  362. /* Default macros */
  363. #ifndef RELOC_ADDRESS
  364. #define RELOC_ADDRESS(r)        ((r)->r_address)
  365. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  366. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  367. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  368. #define RELOC_MEMORY_ADD_P(r)    1
  369. /* #define RELOC_ADD_EXTRA(r)        0       /* Don't need to define */
  370. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  371. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  372. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  373. #define RELOC_TARGET_BITPOS(r)    0
  374. #define RELOC_TARGET_BITSIZE(r)    32
  375. #endif
  376.  
  377. /* Special global symbol types understood by GNU LD.  */
  378.  
  379. /* The following type indicates the definition of a symbol as being
  380.    an indirect reference to another symbol.  The other symbol
  381.    appears as an undefined reference, immediately following this symbol.
  382.  
  383.    Indirection is asymmetrical.  The other symbol's value will be used
  384.    to satisfy requests for the indirect symbol, but not vice versa.
  385.    If the other symbol does not have a definition, libraries will
  386.    be searched to find a definition.  */
  387. #ifndef N_INDR
  388. #define N_INDR 0xa
  389. #endif
  390.  
  391. /* The following symbols refer to set elements.  These are expected
  392.    only in input to the loader; they should not appear in loader
  393.    output (unless relocatable output is requested).  To be recognized
  394.    by the loader, the input symbols must have their N_EXT bit set.
  395.    All the N_SET[ATDB] symbols with the same name form one set.  The
  396.    loader collects all of these elements at load time and outputs a
  397.    vector for each name.
  398.    Space (an array of 32 bit words) is allocated for the set in the
  399.    data section, and the n_value field of each set element value is
  400.    stored into one word of the array.
  401.    The first word of the array is the length of the set (number of
  402.    elements).  The last word of the vector is set to zero for possible
  403.    use by incremental loaders.  The array is ordered by the linkage
  404.    order; the first symbols which the linker encounters will be first
  405.    in the array.
  406.  
  407.    In C syntax this looks like:
  408.  
  409.     struct set_vector {
  410.       unsigned int length;
  411.       unsigned int vector[length];
  412.       unsigned int always_zero;
  413.     };
  414.  
  415.    Before being placed into the array, each element is relocated
  416.    according to its type.  This allows the loader to create an array
  417.    of pointers to objects automatically.  N_SETA type symbols will not
  418.    be relocated.
  419.  
  420.    The address of the set is made into an N_SETV symbol
  421.    whose name is the same as the name of the set.
  422.    This symbol acts like a N_DATA global symbol
  423.    in that it can satisfy undefined external references.
  424.  
  425.    For the purposes of determining whether or not to load in a library
  426.    file, set element definitions are not considered "real
  427.    definitions"; they will not cause the loading of a library
  428.    member.
  429.  
  430.    If relocatable output is requested, none of this processing is
  431.    done.  The symbols are simply relocated and passed through to the
  432.    output file.
  433.  
  434.    So, for example, the following three lines of assembler code
  435.    (whether in one file or scattered between several different ones)
  436.    will produce a three element vector (total length is five words;
  437.    see above), referenced by the symbol "_xyzzy", which will have the
  438.    addresses of the routines _init1, _init2, and _init3.
  439.  
  440.    *NOTE*: If symbolic addresses are used in the n_value field of the
  441.    defining .stabs, those symbols must be defined in the same file as
  442.    that containing the .stabs.
  443.  
  444.     .stabs "_xyzzy",23,0,0,_init1
  445.     .stabs "_xyzzy",23,0,0,_init2
  446.     .stabs "_xyzzy",23,0,0,_init3
  447.  
  448.    Note that (23 == (N_SETT | N_EXT)).  */
  449.  
  450. #ifndef N_SETA
  451. #define    N_SETA    0x14        /* Absolute set element symbol */
  452. #endif                /* This is input to LD, in a .o file.  */
  453.  
  454. #ifndef N_SETT
  455. #define    N_SETT    0x16        /* Text set element symbol */
  456. #endif                /* This is input to LD, in a .o file.  */
  457.  
  458. #ifndef N_SETD
  459. #define    N_SETD    0x18        /* Data set element symbol */
  460. #endif                /* This is input to LD, in a .o file.  */
  461.  
  462. #ifndef N_SETB
  463. #define    N_SETB    0x1A        /* Bss set element symbol */
  464. #endif                /* This is input to LD, in a .o file.  */
  465.  
  466. /* Macros dealing with the set element symbols defined in a.out.h */
  467. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  468. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  469.  
  470. #ifndef N_SETV
  471. #define N_SETV    0x1C        /* Pointer to set vector in text area.  */
  472. #endif                /* This is output from LD.  */
  473.  
  474. /* If a this type of symbol is encountered, its name is a warning
  475.    message to print each time the symbol referenced by the next symbol
  476.    table entry is referenced.
  477.  
  478.    This feature may be used to allow backwards compatibility with
  479.    certain functions (eg. gets) but to discourage programmers from
  480.    their use.
  481.  
  482.    So if, for example, you wanted to have ld print a warning whenever
  483.    the function "gets" was used in their C program, you would add the
  484.    following to the assembler file in which gets is defined:
  485.  
  486.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  487.     .stabs "_gets",1,0,0,0
  488.  
  489.    These .stabs do not necessarily have to be in the same file as the
  490.    gets function, they simply must exist somewhere in the compilation.  */
  491.  
  492. #ifndef N_WARNING
  493. #define N_WARNING 0x1E        /* Warning message to print if file included */
  494. #endif                /* This is input to ld */
  495.  
  496. #ifndef __GNU_STAB__
  497.  
  498. /* Line number for the data section.  This is to be used to describe
  499.    the source location of a variable declaration.  */
  500. #ifndef N_DSLINE
  501. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  502. #endif
  503.  
  504. /* Line number for the bss section.  This is to be used to describe
  505.    the source location of a variable declaration.  */
  506. #ifndef N_BSLINE
  507. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  508. #endif
  509.  
  510. #endif /* not __GNU_STAB__ */
  511.  
  512. /* Symbol table */
  513.  
  514. /* Global symbol data is recorded in these structures,
  515.    one for each global symbol.
  516.    They are found via hashing in 'symtab', which points to a vector of buckets.
  517.    Each bucket is a chain of these structures through the link field.  */
  518.  
  519. typedef
  520.   struct glosym
  521.     {
  522.       /* Pointer to next symbol in this symbol's hash bucket.  */
  523.       struct glosym *link;
  524.       /* Name of this symbol.  */
  525.       char *name;
  526.       /* Value of this symbol as a global symbol.  */
  527.       long value;
  528.       /* Chain of external 'nlist's in files for this symbol, both defs
  529.      and refs.  */
  530.       struct nlist *refs;
  531.       /* Any warning message that might be associated with this symbol
  532.          from an N_WARNING symbol encountered. */
  533.       char *warning;
  534.       /* Nonzero means definitions of this symbol as common have been seen,
  535.      and the value here is the largest size specified by any of them.  */
  536.       int max_common_size;
  537.       /* For relocatable_output, records the index of this global sym in the
  538.      symbol table to be written, with the first global sym given index 0.*/
  539.       int def_count;
  540.       /* Nonzero means a definition of this global symbol is known to exist.
  541.      Library members should not be loaded on its account.  */
  542.       char defined;
  543.       /* Nonzero means a reference to this global symbol has been seen
  544.      in a file that is surely being loaded.
  545.      A value higher than 1 is the n_type code for the symbol's
  546.      definition.  */
  547.       char referenced;
  548.       /* A count of the number of undefined references printed for a
  549.      specific symbol.  If a symbol is unresolved at the end of
  550.      digest_symbols (and the loading run is supposed to produce
  551.      relocatable output) do_file_warnings keeps track of how many
  552.      unresolved reference error messages have been printed for
  553.      each symbol here.  When the number hits MAX_UREFS_PRINTED,
  554.      messages stop. */
  555.       unsigned char undef_refs;
  556.       /* Nonzero means print a message at all refs or defs of this symbol */
  557.       char trace;
  558.     }
  559.   symbol;
  560.  
  561. /* Demangler for C++. */
  562. extern char *cplus_demangle ();
  563.  
  564. /* Demangler function to use. */
  565. char *(*demangler)() = cplus_demangle;
  566.  
  567. /* Number of buckets in symbol hash table */
  568. #define    TABSIZE    1009
  569.  
  570. /* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  571. symbol *symtab[TABSIZE];
  572.  
  573. /* Number of symbols in symbol hash table. */
  574. int num_hash_tab_syms = 0;
  575.  
  576. /* Count the number of nlist entries that are for local symbols.
  577.    This count and the three following counts
  578.    are incremented as as symbols are entered in the symbol table.  */
  579. int local_sym_count;
  580.  
  581. /* Count number of nlist entries that are for local symbols
  582.    whose names don't start with L. */
  583. int non_L_local_sym_count;
  584.  
  585. /* Count the number of nlist entries for debugger info.  */
  586. int debugger_sym_count;
  587.  
  588. /* Count the number of global symbols referenced and not defined.  */
  589. int undefined_global_sym_count;
  590.  
  591. /* Count the number of defined global symbols.
  592.    Each symbol is counted only once
  593.    regardless of how many different nlist entries refer to it,
  594.    since the output file will need only one nlist entry for it.
  595.    This count is computed by `digest_symbols';
  596.    it is undefined while symbols are being loaded. */
  597. int defined_global_sym_count;
  598.  
  599. /* Count the number of symbols defined through common declarations.
  600.    This count is kept in symdef_library, linear_library, and
  601.    enter_global_ref.  It is incremented when the defined flag is set
  602.    in a symbol because of a common definition, and decremented when
  603.    the symbol is defined "for real" (ie. by something besides a common
  604.    definition).  */
  605. int common_defined_global_count;
  606.  
  607. /* Count the number of set element type symbols and the number of
  608.    separate vectors which these symbols will fit into.  See the
  609.    GNU a.out.h for more info.
  610.    This count is computed by 'enter_file_symbols' */
  611. int set_symbol_count;
  612. int set_vector_count;
  613.  
  614. /* Count the number of definitions done indirectly (ie. done relative
  615.    to the value of some other symbol. */
  616. int global_indirect_count;
  617.  
  618. /* Count the number of warning symbols encountered. */
  619. int warning_count;
  620.  
  621. /* Total number of symbols to be written in the output file.
  622.    Computed by digest_symbols from the variables above.  */
  623. int nsyms;
  624.  
  625.  
  626. /* Nonzero means ptr to symbol entry for symbol to use as start addr.
  627.    -e sets this.  */
  628. symbol *entry_symbol;
  629.  
  630. symbol *edata_symbol;   /* the symbol _edata */
  631. symbol *etext_symbol;   /* the symbol _etext */
  632. symbol *end_symbol;    /* the symbol _end */
  633.  
  634. /* Each input file, and each library member ("subfile") being loaded,
  635.    has a `file_entry' structure for it.
  636.  
  637.    For files specified by command args, these are contained in the vector
  638.    which `file_table' points to.
  639.  
  640.    For library members, they are dynamically allocated,
  641.    and chained through the `chain' field.
  642.    The chain is found in the `subfiles' field of the `file_entry'.
  643.    The `file_entry' objects for the members have `superfile' fields pointing
  644.    to the one for the library.  */
  645.  
  646. struct file_entry {
  647.   /* Name of this file.  */
  648.   char *filename;
  649.   /* Name to use for the symbol giving address of text start */
  650.   /* Usually the same as filename, but for a file spec'd with -l
  651.      this is the -l switch itself rather than the filename.  */
  652.   char *local_sym_name;
  653.  
  654.   /* Describe the layout of the contents of the file */
  655.  
  656.   /* The file's a.out header.  */
  657.   struct exec header;
  658.   /* Offset in file of GDB symbol segment, or 0 if there is none.  */
  659.   int symseg_offset;
  660.  
  661.   /* Describe data from the file loaded into core */
  662.  
  663.   /* Symbol table of the file.  */
  664.   struct nlist *symbols;
  665.   /* Size in bytes of string table.  */
  666.   int string_size;
  667.   /* Pointer to the string table.
  668.      The string table is not kept in core all the time,
  669.      but when it is in core, its address is here.  */
  670.   char *strings;
  671.   /* Pointer to any warning specified in this file by an N_WARNING
  672.      type symbol */
  673.   char *warning;
  674.  
  675.   /* Next two used only if `relocatable_output' or if needed for */
  676.   /* output of undefined reference line numbers. */
  677.  
  678.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  679.   struct relocation_info *textrel;
  680.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  681.   struct relocation_info *datarel;
  682.  
  683.   /* Relation of this file's segments to the output file */
  684.  
  685.   /* Start of this file's text seg in the output file core image.  */
  686.   int text_start_address;
  687.   /* Start of this file's data seg in the output file core image.  */
  688.   int data_start_address;
  689.   /* Start of this file's bss seg in the output file core image.  */
  690.   int bss_start_address;
  691.   /* Offset in bytes in the output file symbol table
  692.      of the first local symbol for this file.  Set by `write_file_symbols'.  */
  693.   int local_syms_offset;
  694.  
  695.   /* For library members only */
  696.  
  697.   /* For a library, points to chain of entries for the library members.  */
  698.   struct file_entry *subfiles;
  699.   /* For a library member, offset of the member within the archive.
  700.      Zero for files that are not library members.  */
  701.   int starting_offset;
  702.   /* Size of contents of this file, if library member.  */
  703.   int total_size;
  704.   /* For library member, points to the library's own entry.  */
  705.   struct file_entry *superfile;
  706.   /* For library member, points to next entry for next member.  */
  707.   struct file_entry *chain;
  708.  
  709.   /* 1 if file is a library. */
  710.   char library_flag;
  711.  
  712.   /* 1 if file's header has been read into this structure.  */
  713.   char header_read_flag;
  714.  
  715.   /* 1 means search a set of directories for this file.  */
  716.   char search_dirs_flag;
  717.  
  718.   /* 1 means this is base file of incremental load.
  719.      Do not load this file's text or data.
  720.      Also default text_start to after this file's bss. */
  721.   char just_syms_flag;
  722. };
  723.  
  724. /* Vector of entries for input files specified by arguments.
  725.    These are all the input files except for members of specified libraries.  */
  726. struct file_entry *file_table;
  727.  
  728. /* Length of that vector.  */
  729. int number_of_files;
  730.  
  731. /* When loading the text and data, we can avoid doing a close
  732.    and another open between members of the same library.
  733.  
  734.    These two variables remember the file that is currently open.
  735.    Both are zero if no file is open.
  736.  
  737.    See `each_file' and `file_close'.  */
  738.  
  739. struct file_entry *input_file;
  740. int input_desc;
  741.  
  742. /* The name of the file to write; "a.out" by default.  */
  743.  
  744. char *output_filename;
  745.  
  746. /* Descriptor for writing that file with `mywrite'.  */
  747.  
  748. int outdesc;
  749.  
  750. /* Header for that file (filled in by `write_header').  */
  751.  
  752. struct exec outheader;
  753.  
  754. #ifdef COFF_ENCAPSULATE
  755. struct coffheader coffheader;
  756. int need_coff_header;
  757. #endif
  758.  
  759. /* The following are computed by `digest_symbols'.  */
  760.  
  761. int text_size;        /* total size of text of all input files.  */
  762. int data_size;        /* total size of data of all input files.  */
  763. int bss_size;        /* total size of bss of all input files.  */
  764. int text_reloc_size;    /* total size of text relocation of all input files.  */
  765. int data_reloc_size;    /* total size of data relocation of all input */
  766.             /* files.  */
  767.  
  768. /* Specifications of start and length of the area reserved at the end
  769.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  770. int set_sect_start;
  771. int set_sect_size;
  772.  
  773. /* Pointer for in core storage for the above vectors, before they are
  774.    written. */
  775. unsigned long *set_vectors;
  776.  
  777. /* Amount of cleared space to leave between the text and data segments.  */
  778.  
  779. int text_pad;
  780.  
  781. /* Amount of bss segment to include as part of the data segment.  */
  782.  
  783. int data_pad;
  784.  
  785. /* Format of __.SYMDEF:
  786.    First, a longword containing the size of the 'symdef' data that follows.
  787.    Second, zero or more 'symdef' structures.
  788.    Third, a word containing the length of symbol name strings.
  789.    Fourth, zero or more symbol name strings (each followed by a zero).  */
  790.  
  791. struct symdef {
  792.   int symbol_name_string_index;
  793.   int library_member_offset;
  794. };
  795.  
  796. /* Record most of the command options.  */
  797.  
  798. /* Address we assume the text section will be loaded at.
  799.    We relocate symbols and text and data for this, but we do not
  800.    write any padding in the output file for it.  */
  801. int text_start;
  802.  
  803. /* Offset of default entry-pc within the text section.  */
  804. int entry_offset;
  805.  
  806. /* Address we decide the data section will be loaded at.  */
  807. int data_start;
  808.  
  809. /* `text-start' address is normally this much plus a page boundary.
  810.    This is not a user option; it is fixed for each system.  */
  811. int text_start_alignment;
  812.  
  813. /* Nonzero if -T was specified in the command line.
  814.    This prevents text_start from being set later to default values.  */
  815. int T_flag_specified;
  816.  
  817. /* Nonzero if -Tdata was specified in the command line.
  818.    This prevents data_start from being set later to default values.  */
  819. int Tdata_flag_specified;
  820.  
  821. /* Size to pad data section up to.
  822.    We simply increase the size of the data section, padding with zeros,
  823.    and reduce the size of the bss section to match.  */
  824. int specified_data_size;
  825.  
  826. /* Magic number to use for the output file, set by switch.  */
  827. int magic;
  828.  
  829. /* Nonzero means print names of input files as processed.  */
  830. int trace_files;
  831.  
  832. /* Which symbols should be stripped (omitted from the output):
  833.    none, all, or debugger symbols.  */
  834. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  835.  
  836. /* Which local symbols should be omitted:
  837.    none, all, or those starting with L.
  838.    This is irrelevant if STRIP_NONE.  */
  839. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  840.  
  841. /* 1 => write load map.  */
  842. int write_map;
  843.  
  844. /* 1 => write relocation into output file so can re-input it later.  */
  845. int relocatable_output;
  846.  
  847. /* 1 => assign space to common symbols even if `relocatable_output'.  */
  848. int force_common_definition;
  849.  
  850. /* Standard directories to search for files specified by -l.  */
  851. #ifdef atarist
  852. char *standard_search_dirs[] = {"\\gnu\\lib", "\\gnu"};
  853. #else
  854. #ifdef CROSSATARI
  855. char *standard_search_dirs[] = {CROSSLIB};
  856. #else
  857. #ifdef atariminix
  858. char *standard_search_dirs[] = {"/usr/local/lib"};
  859. #else
  860. char *standard_search_dirs[] = {"/lib", "/usr/lib", "/usr/local/lib"};
  861. #endif
  862. #endif
  863. #endif
  864.  
  865. /* Actual vector of directories to search;
  866.    this contains those specified with -L plus the standard ones.  */
  867. char **search_dirs;
  868.  
  869. /* Length of the vector `search_dirs'.  */
  870. int n_search_dirs;
  871.  
  872. /* Non zero means to create the output executable. */
  873. /* Cleared by nonfatal errors.  */
  874. int make_executable;
  875.  
  876. /* Force the executable to be output, even if there are non-fatal
  877.    errors */
  878. int force_executable;
  879.  
  880. /* Keep a list of any symbols referenced from the command line (so
  881.    that error messages for these guys can be generated). This list is
  882.    zero terminated. */
  883. struct glosym **cmdline_references;
  884. int cl_refs_allocated;
  885.  
  886. void bcopy (), bzero ();
  887. int malloc (), realloc ();
  888. #ifndef alloca
  889. int alloca ();
  890. #endif
  891. int free ();
  892.  
  893. int xmalloc ();
  894. int xrealloc ();
  895. #if __STDC__
  896. void fatal (char *string, ...);
  897. #else
  898. void fatal ();
  899. #endif
  900. void fatal_with_file ();
  901. void perror_name ();
  902. void perror_file ();
  903. void error ();
  904.  
  905. void digest_symbols ();
  906. void print_symbols ();
  907. void load_symbols ();
  908. void decode_command ();
  909. void list_undefined_symbols ();
  910. void list_unresolved_references ();
  911. void write_output ();
  912. void write_header ();
  913. void write_text ();
  914. void read_file_relocation ();
  915. void write_data ();
  916. void write_rel ();
  917. void write_syms ();
  918. void write_symsegs ();
  919. void mywrite ();
  920. void symtab_init ();
  921. void padfile ();
  922. char *concat ();
  923. char *get_file_name ();
  924. symbol *getsym (), *getsym_soft ();
  925.  
  926. int
  927. main (argc, argv)
  928.      char **argv;
  929.      int argc;
  930. {
  931. #ifdef atarist
  932.   _binmode(1);
  933. #endif
  934.  
  935.   page_size = getpagesize ();
  936.   progname = argv[0];
  937.  
  938.   /* Clear the cumulative info on the output file.  */
  939.  
  940.   text_size = 0;
  941.   data_size = 0;
  942.   bss_size = 0;
  943.   text_reloc_size = 0;
  944.   data_reloc_size = 0;
  945.  
  946.   data_pad = 0;
  947.   text_pad = 0;
  948.  
  949.   /* Initialize the data about options.  */
  950.  
  951.   specified_data_size = 0;
  952.   strip_symbols = STRIP_NONE;
  953.   trace_files = 0;
  954.   discard_locals = DISCARD_NONE;
  955.   entry_symbol = 0;
  956.   write_map = 0;
  957.   relocatable_output = 0;
  958.   force_common_definition = 0;
  959.   T_flag_specified = 0;
  960.   Tdata_flag_specified = 0;
  961.   magic = DEFAULT_MAGIC;
  962.   make_executable = 1;
  963.   force_executable = 0;
  964.  
  965.   /* Initialize the cumulative counts of symbols.  */
  966.  
  967.   local_sym_count = 0;
  968.   non_L_local_sym_count = 0;
  969.   debugger_sym_count = 0;
  970.   undefined_global_sym_count = 0;
  971.   set_symbol_count = 0;
  972.   set_vector_count = 0;
  973.   global_indirect_count = 0;
  974.   warning_count = 0;
  975.   common_defined_global_count = 0;
  976.  
  977.   /* Keep a list of symbols referenced from the command line */
  978.   cl_refs_allocated = 10;
  979.   cmdline_references =
  980.     (struct glosym **) xmalloc (cl_refs_allocated
  981.                 * sizeof(struct glosym *));
  982.   *cmdline_references = 0;
  983.  
  984.   /* Completely decode ARGV.  */
  985.  
  986.   decode_command (argc, argv);
  987.  
  988.   /* Create the symbols `etext', `edata' and `end'.  */
  989.  
  990.   if (!relocatable_output)
  991.     symtab_init ();
  992.  
  993.   /* Determine whether to count the header as part of
  994.      the text size, and initialize the text size accordingly.
  995.      This depends on the kind of system and on the output format selected.  */
  996.  
  997.   outheader.a_info = magic;
  998.  
  999. #if (!(defined(CROSSATARI) || defined(atarist) || defined(atariminix)))
  1000. #ifdef INITIALIZE_HEADER
  1001.   INITIALIZE_HEADER;
  1002. #endif
  1003. #endif
  1004.  
  1005.   text_size = sizeof (struct exec);
  1006. #ifdef COFF_ENCAPSULATE
  1007.   if (relocatable_output == 0)
  1008.     {
  1009.       need_coff_header = 1;
  1010.       /* set A_ENCAP now, since it will change the values of N_TXTOFF, etc */
  1011.       outheader.a_flags |= A_ENCAP;
  1012.       text_size += sizeof (struct coffheader);
  1013.     }
  1014. #endif
  1015.  
  1016.   text_size -= N_TXTOFF (outheader);
  1017.  
  1018.   if (text_size < 0)
  1019.     text_size = 0;
  1020.   entry_offset = text_size;
  1021.  
  1022.   if (!T_flag_specified && !relocatable_output)
  1023.     text_start = N_TXTADDR (outheader);
  1024.  
  1025.   /* The text-start address is normally this far past a page boundary.  */
  1026.   text_start_alignment = text_start % page_size;
  1027.  
  1028.   /* Load symbols of all input files.
  1029.      Also search all libraries and decide which library members to load.  */
  1030.  
  1031.   load_symbols ();
  1032.  
  1033.   /* Compute where each file's sections go, and relocate symbols.  */
  1034.  
  1035.   digest_symbols ();
  1036.  
  1037.   /* Print error messages for any missing symbols, for any warning
  1038.      symbols, and possibly multiple definitions */
  1039.  
  1040.   do_warnings (stderr);
  1041.  
  1042.   /* Print a map, if requested.  */
  1043.  
  1044.   if (write_map) print_symbols (stdout);
  1045.  
  1046.   /* Write the output file.  */
  1047.  
  1048.   if (make_executable || force_executable)
  1049.     write_output ();
  1050.  
  1051.   exit(! make_executable);
  1052. }
  1053.  
  1054. void decode_option ();
  1055.  
  1056. /* Analyze a command line argument.
  1057.    Return 0 if the argument is a filename.
  1058.    Return 1 if the argument is a option complete in itself.
  1059.    Return 2 if the argument is a option which uses an argument.
  1060.  
  1061.    Thus, the value is the number of consecutive arguments
  1062.    that are part of options.  */
  1063.  
  1064. int
  1065. classify_arg (arg)
  1066.      register char *arg;
  1067. {
  1068.   if (*arg != '-') return 0;
  1069.   switch (arg[1])
  1070.     {
  1071.     case 'A':
  1072.     case 'D':
  1073.     case 'e':
  1074.     case 'L':
  1075.     case 'o':
  1076.     case 'u':
  1077.     case 'y':
  1078.       if (arg[2])
  1079.     return 1;
  1080.       return 2;
  1081.  
  1082.     case 'l':
  1083.       if (arg[2])
  1084.     return 1;
  1085.       return 2;
  1086.  
  1087.     case 'T':
  1088.       if (arg[2] == 0)
  1089.     return 2;
  1090.       if (! strcmp (&arg[2], "text"))
  1091.     return 2;
  1092.       if (! strcmp (&arg[2], "data"))
  1093.     return 2;
  1094.       return 1;
  1095.     }
  1096.  
  1097.   return 1;
  1098. }
  1099.  
  1100. #if (defined(CROSSATARI) || defined(atarist) || defined(atariminix))
  1101. /* things to grok indirect files */
  1102.  
  1103. int next_indirect_name(f, buf)
  1104. FILE * f;
  1105. char * buf;
  1106. {
  1107.   char c;
  1108.   char * s = buf;
  1109.  
  1110.   for (*buf = '\0' ; (((c = fgetc(f)) != EOF) && (isspace(c))) ; )
  1111.     ;            /* skip whitespace */
  1112.   if (c == EOF) return(0);    /* lose */
  1113.   *s++ = c;
  1114.   for ( ; (((c = fgetc(f)) != EOF) && (!isspace(c))) ; )
  1115.     *s++ = c;
  1116.   *s = '\0';            /* finish it */
  1117.   return((strlen(buf) > 0));    /* win if saw any */
  1118. }
  1119.  
  1120. int decode_indirect_file(iname)
  1121. /* (declare (values n-new-files)) */
  1122. char * iname;
  1123. {
  1124.   char fn[80];        /* name buffer */
  1125.   int i;
  1126.   FILE * ifile;
  1127.  
  1128. #ifdef DEBUG
  1129.   fprintf(stderr, "decode_indirect_file('%s')\n", iname);
  1130. #endif
  1131.   if ((ifile = fopen(iname, "r")) == NULL)
  1132.     {
  1133.     fprintf (stderr, "Can't open indirect file '%s'\n", iname);
  1134.     return(0);
  1135.     }
  1136.   for (i = 0 ; next_indirect_name(ifile, fn) ; )
  1137.     i++;        /* count files */
  1138.   fclose(ifile);
  1139. #ifdef DEBUG
  1140.   fprintf(stderr, "  ->%d\n", i);
  1141. #endif
  1142.   return(i);        /* return file count */
  1143. }
  1144.  
  1145. struct file_entry * process_indirect_file(p, iname)
  1146. /* (declare (values updated_pointer)) */
  1147. struct file_entry * p;
  1148. char * iname;
  1149. {
  1150.   char fn[80];        /* name buffer */
  1151.   FILE * ifile;
  1152.  
  1153. #ifdef DEBUG
  1154.   fprintf(stderr, "process_indirect_file(%X, '%s')\n", p, iname);
  1155. #endif
  1156.   if ((ifile = fopen(iname, "r")) == NULL)
  1157.     {
  1158.     fprintf (stderr, "Can't open indirect file '%s'\n", iname);
  1159.     return(0);
  1160.     }
  1161.   for ( ; next_indirect_name(ifile, fn) ; )
  1162.     {
  1163. #ifdef DEBUG
  1164.     fprintf(stderr, "  file '%s'\n", fn);
  1165. #endif
  1166.     p->filename = concat(fn, "", "");
  1167.     p->local_sym_name = p->filename;
  1168.     p++;
  1169.     }
  1170.   fclose(ifile);
  1171. #ifdef DEBUG
  1172.   fprintf(stderr, "  ->%X\n", p);
  1173. #endif
  1174.   return(p);        /* return new pointer */
  1175. }
  1176.  
  1177. #endif
  1178.  
  1179. /* Process the command arguments,
  1180.    setting up file_table with an entry for each input file,
  1181.    and setting variables according to the options.  */
  1182.  
  1183. void
  1184. decode_command (argc, argv)
  1185.      char **argv;
  1186.      int argc;
  1187. {
  1188.   register int i;
  1189.   register struct file_entry *p;
  1190.  
  1191.   number_of_files = 0;
  1192.   output_filename = "a.out";
  1193.  
  1194.   n_search_dirs = 0;
  1195.   search_dirs = (char **) xmalloc (sizeof (char *));
  1196.  
  1197.   /* First compute number_of_files so we know how long to make file_table.  */
  1198.   /* Also process most options completely.  */
  1199.  
  1200.   for (i = 1; i < argc; i++)
  1201.     {
  1202.       register int code = classify_arg (argv[i]);
  1203.       if (code)
  1204.     {
  1205.       if (i + code > argc)
  1206.         fatal ("no argument following %s\n", argv[i]);
  1207.  
  1208.       decode_option (argv[i], argv[i+1]);
  1209.  
  1210.       if (argv[i][1] == 'l' || argv[i][1] == 'A')
  1211.         number_of_files++;
  1212.  
  1213.       i += code - 1;
  1214.     }
  1215.       else
  1216. #if (defined(CROSSATARI) || defined(atarist) || defined(atariminix))
  1217.     if (argv[i][0] == '@')        /* indirect file? */
  1218.       number_of_files += decode_indirect_file(&argv[i][1]);
  1219.      else
  1220. #endif
  1221.     number_of_files++;
  1222.     }
  1223.  
  1224.   if (!number_of_files)
  1225.     fatal ("no input files", 0);
  1226.  
  1227.   p = file_table
  1228.     = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  1229.   bzero (p, number_of_files * sizeof (struct file_entry));
  1230.  
  1231.   /* Now scan again and fill in file_table.  */
  1232.   /* All options except -A and -l are ignored here.  */
  1233.  
  1234.   for (i = 1; i < argc; i++)
  1235.     {
  1236.       register int code = classify_arg (argv[i]);
  1237.  
  1238.       if (code)
  1239.     {
  1240.       char *string;
  1241.       if (code == 2)
  1242.         string = argv[i+1];
  1243.       else
  1244.         string = &argv[i][2];
  1245.  
  1246.       if (argv[i][1] == 'A')
  1247.         {
  1248.           if (p != file_table)
  1249.         fatal ("-A specified before an input file other than the first");
  1250.  
  1251.           p->filename = string;
  1252.           p->local_sym_name = string;
  1253.           p->just_syms_flag = 1;
  1254.           p++;
  1255.         }
  1256.       if (argv[i][1] == 'l')
  1257.         {
  1258. #if (defined(atarist) || (defined(CROSSATARI) && (!defined(MINIX))))
  1259.           {
  1260.             char * ext = rindex(string, '.');
  1261.         
  1262.         if (ext)
  1263.             p->filename = concat(string, "", "");    /* just use it */
  1264.             else
  1265.             p->filename = concat(string, ".olb", "");
  1266.           }
  1267. #else
  1268.           p->filename = concat ("lib", string, ".a");
  1269. #endif
  1270.           p->local_sym_name = concat ("-l", string, "");
  1271.           p->search_dirs_flag = 1;
  1272.           p++;
  1273.         }
  1274.       i += code - 1;
  1275.     }
  1276.       else
  1277. #if (defined(CROSSATARI) || defined(atarist) || defined(atariminix))
  1278.     if (argv[i][0] == '@')
  1279.       p = process_indirect_file(p, &argv[i][1]);
  1280.      else
  1281. #endif
  1282.     {
  1283.       p->filename = argv[i];
  1284.       p->local_sym_name = argv[i];
  1285.       p++;
  1286.     }
  1287.     }
  1288.  
  1289.   /* Now check some option settings for consistency.  */
  1290.  
  1291.   if ((magic == ZMAGIC || magic == NMAGIC)
  1292.       && (text_start - text_start_alignment) & (page_size - 1))
  1293.     fatal ("-T argument not multiple of page size, with sharable output", 0);
  1294.  
  1295. #if (defined(atarist) || defined(atariminix) || defined(CROSSATARI))
  1296.   {
  1297. /* see if there's an env var that says where to search for things */
  1298.  
  1299.      extern char *getenv();
  1300.      char *value = getenv("GNULIB");
  1301.  
  1302.  
  1303.      /* Allow GNULIB to contain more than one directory, so you can take
  1304.       * advantage to your lib RAM-Disk/Harddisk/Floppy(;-)
  1305.       * The dirs are delimited by ';' or ','.        [br]
  1306.       */
  1307. #ifdef DEBUG
  1308.     fprintf(stderr, "env->%X\n", value);
  1309. #endif
  1310.      if (value) {
  1311.      char *glib = (char *)alloca(strlen(value) + 1), *cp, *cpp;
  1312.      
  1313.      strcpy(glib, value);
  1314. #ifdef DEBUG
  1315.      fprintf(stderr, "glib->'%s'\n", glib);
  1316. #endif
  1317.      cp = cpp = glib;
  1318.      while( *cpp != '\0' ) {
  1319. #ifdef atarist
  1320.          while( (*cp != ';') && (*cp != ',') && (*cp != '\0') )
  1321. #else
  1322.          while( (*cp != ':') && (*cp != '\0') )
  1323. #endif
  1324.          cp++;
  1325.          if( *cp != '\0' )
  1326.          *cp++ = '\0';    /* terminate string and advance to next    */
  1327.                  /* else  "*(cpp = cp) = '\0'"  =>> end */
  1328.          n_search_dirs++;
  1329.          search_dirs =
  1330.          (char **) xrealloc(search_dirs, n_search_dirs*sizeof(char *));
  1331.          search_dirs[n_search_dirs-1] = concat(cpp, "", "");
  1332. #ifdef DEBUG
  1333.          fprintf(stderr, "... '%s'\n", search_dirs[n_search_dirs-1]);
  1334. #endif
  1335.  
  1336.          cpp = cp;        /* ptr to next entry or '\0' (see above) */
  1337.      }
  1338.      }
  1339.   }
  1340. #endif  /* Atari ST special */
  1341.  
  1342.   /* Append the standard search directories to the user-specified ones.  */
  1343.   {
  1344.     int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
  1345.     n_search_dirs += n;
  1346.     search_dirs
  1347.       = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1348.     bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
  1349.        n * sizeof (char *));
  1350.   }
  1351. }
  1352.  
  1353.  
  1354. void
  1355. add_cmdline_ref (sp)
  1356.      struct glosym *sp;
  1357. {
  1358.   struct glosym **ptr;
  1359.  
  1360.   for (ptr = cmdline_references;
  1361.        ptr < cmdline_references + cl_refs_allocated && *ptr;
  1362.        ptr++)
  1363.     ;
  1364.  
  1365.   if (ptr == cmdline_references + cl_refs_allocated)
  1366.     {
  1367.       int diff = ptr - cmdline_references;
  1368.       
  1369.       cl_refs_allocated *= 2;
  1370.       cmdline_references = (struct glosym **)
  1371.     xrealloc (cmdline_references,
  1372.          cl_refs_allocated * sizeof (struct glosym *));
  1373.       ptr = cmdline_references + diff;
  1374.     }
  1375.   
  1376.   *ptr++ = sp;
  1377.   *ptr = (struct glosym *) 0;
  1378. }
  1379.     
  1380. int parse ();
  1381.  
  1382. /* Record an option and arrange to act on it later.
  1383.    ARG should be the following command argument,
  1384.    which may or may not be used by this option.
  1385.  
  1386.    The `l' and `A' options are ignored here since they actually
  1387.    specify input files.  */
  1388.  
  1389. void
  1390. decode_option (swt, arg)
  1391.      register char *swt, *arg;
  1392. {
  1393.   if (! strcmp (swt + 1, "Ttext"))
  1394.     {
  1395.       text_start = parse (arg, "%x", "invalid argument to -Ttext");
  1396.       T_flag_specified = 1;
  1397.       return;
  1398.     }
  1399.   if (! strcmp (swt + 1, "Tdata"))
  1400.     {
  1401.       data_start = parse (arg, "%x", "invalid argument to -Tdata");
  1402.       Tdata_flag_specified = 1;
  1403.       return;
  1404.     }
  1405.   if (! strcmp (swt + 1, "noinhibit-exec"))
  1406.     {
  1407.       force_executable = 1;
  1408.       return;
  1409.     }
  1410.  
  1411.   if (swt[2] != 0)
  1412.     arg = &swt[2];
  1413.  
  1414.   switch (swt[1])
  1415.     {
  1416.     case 'A':
  1417.       return;
  1418.  
  1419.     case 'D':
  1420.       specified_data_size = parse (arg, "%x", "invalid argument to -D");
  1421.       return;
  1422.  
  1423.     case 'd':
  1424.       force_common_definition = 1;
  1425.       return;
  1426.  
  1427.     case 'e':
  1428.       entry_symbol = getsym (arg);
  1429.       if (!entry_symbol->defined && !entry_symbol->referenced)
  1430.     undefined_global_sym_count++;
  1431.       entry_symbol->referenced = 1;
  1432.       add_cmdline_ref (entry_symbol);
  1433.       return;
  1434.  
  1435.     case 'l':
  1436.       return;
  1437.  
  1438.     case 'L':
  1439.       n_search_dirs++;
  1440.       search_dirs
  1441.     = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1442.       search_dirs[n_search_dirs - 1] = arg;
  1443.       return;
  1444.  
  1445.     case 'M':
  1446.       write_map = 1;
  1447.       return;
  1448.  
  1449.     case 'N':
  1450.       magic = OMAGIC;
  1451.       return;
  1452.  
  1453.     case 'n':
  1454.       magic = NMAGIC;
  1455.       return;
  1456.  
  1457.     case 'o':
  1458.       output_filename = arg;
  1459.       return;
  1460.  
  1461.     case 'r':
  1462.       relocatable_output = 1;
  1463.       magic = OMAGIC;
  1464.       text_start = 0;
  1465.       return;
  1466.  
  1467.     case 'S':
  1468.       strip_symbols = STRIP_DEBUGGER;
  1469.       return;
  1470.  
  1471.     case 's':
  1472.       strip_symbols = STRIP_ALL;
  1473.       return;
  1474.  
  1475.     case 'T':
  1476.       text_start = parse (arg, "%x", "invalid argument to -T");
  1477.       T_flag_specified = 1;
  1478.       return;
  1479.  
  1480.     case 't':
  1481.       trace_files = 1;
  1482.       return;
  1483.  
  1484.     case 'u':
  1485.       {
  1486.     register symbol *sp = getsym (arg);
  1487.     if (!sp->defined && !sp->referenced)
  1488.       undefined_global_sym_count++;
  1489.     sp->referenced = 1;
  1490.     add_cmdline_ref (sp);
  1491.       }
  1492.       return;
  1493.  
  1494. #if defined(atarist) || defined(CROSSATARI)
  1495.     case 'v':
  1496. #ifndef __GNUC__
  1497.     {
  1498.       extern time_t time();
  1499.       extern char *ctime();
  1500.       time_t t = time(0L);
  1501.  
  1502.       fprintf (stderr, "`sym-ld' cross-linker Patchlevel %s for GNU, Atari ST version (%s)\n",
  1503.            PatchLevel, ctime(&t));
  1504.     }
  1505. #else
  1506.       fprintf (stderr, "`sym-ld' linker Patchlevel %s for GNU, Atari ST version (%s %s)\n",
  1507.            PatchLevel, __DATE__, __TIME__);
  1508. #endif
  1509.       return;
  1510. #endif /* atarist */
  1511.  
  1512.     case 'X':
  1513.       discard_locals = DISCARD_L;
  1514.       return;
  1515.  
  1516.     case 'x':
  1517.       discard_locals = DISCARD_ALL;
  1518.       return;
  1519.  
  1520.     case 'y':
  1521.       {
  1522.     register symbol *sp = getsym (&swt[2]);
  1523.     sp->trace = 1;
  1524.       }
  1525.       return;
  1526.  
  1527.     case 'z':
  1528.       magic = ZMAGIC;
  1529.       return;
  1530.  
  1531.     default:
  1532.       fatal ("invalid command option `%s'", swt);
  1533.     }
  1534. }
  1535.  
  1536. /** Convenient functions for operating on one or all files being */
  1537.  /** loaded.  */
  1538. void print_file_name ();
  1539.  
  1540. /* Call FUNCTION on each input file entry.
  1541.    Do not call for entries for libraries;
  1542.    instead, call once for each library member that is being loaded.
  1543.  
  1544.    FUNCTION receives two arguments: the entry, and ARG.  */
  1545.  
  1546. void
  1547. each_file (function, arg)
  1548.      register void (*function)();
  1549.      register int arg;
  1550. {
  1551.   register int i;
  1552.  
  1553.   for (i = 0; i < number_of_files; i++)
  1554.     {
  1555.       register struct file_entry *entry = &file_table[i];
  1556.       if (entry->library_flag)
  1557.         {
  1558.       register struct file_entry *subentry = entry->subfiles;
  1559.       for (; subentry; subentry = subentry->chain)
  1560.         (*function) (subentry, arg);
  1561.     }
  1562.       else
  1563.     (*function) (entry, arg);
  1564.     }
  1565. }
  1566.  
  1567. /* Call FUNCTION on each input file entry until it returns a non-zero
  1568.    value.  Return this value.
  1569.    Do not call for entries for libraries;
  1570.    instead, call once for each library member that is being loaded.
  1571.  
  1572.    FUNCTION receives two arguments: the entry, and ARG.  It must be a
  1573.    function returning unsigned long (though this can probably be fudged). */
  1574.  
  1575. unsigned long
  1576. check_each_file (function, arg)
  1577.      register unsigned long (*function)();
  1578.      register int arg;
  1579. {
  1580.   register int i;
  1581.   register unsigned long return_val;
  1582.  
  1583.   for (i = 0; i < number_of_files; i++)
  1584.     {
  1585.       register struct file_entry *entry = &file_table[i];
  1586.       if (entry->library_flag)
  1587.         {
  1588.       register struct file_entry *subentry = entry->subfiles;
  1589.       for (; subentry; subentry = subentry->chain)
  1590.         if (return_val = (*function) (subentry, arg))
  1591.           return return_val;
  1592.     }
  1593.       else
  1594.     if (return_val = (*function) (entry, arg))
  1595.       return return_val;
  1596.     }
  1597.   return 0;
  1598. }
  1599.  
  1600. /* Like `each_file' but ignore files that were just for symbol definitions.  */
  1601.  
  1602. void
  1603. each_full_file (function, arg)
  1604.      register void (*function)();
  1605.      register int arg;
  1606. {
  1607.   register int i;
  1608.  
  1609.   for (i = 0; i < number_of_files; i++)
  1610.     {
  1611.       register struct file_entry *entry = &file_table[i];
  1612.       if (entry->just_syms_flag)
  1613.     continue;
  1614.       if (entry->library_flag)
  1615.         {
  1616.       register struct file_entry *subentry = entry->subfiles;
  1617.       for (; subentry; subentry = subentry->chain)
  1618.         (*function) (subentry, arg);
  1619.     }
  1620.       else
  1621.     (*function) (entry, arg);
  1622.     }
  1623. }
  1624.  
  1625. /* Close the input file that is now open.  */
  1626.  
  1627. void
  1628. file_close ()
  1629. {
  1630.   close (input_desc);
  1631.   input_desc = 0;
  1632.   input_file = 0;
  1633. }
  1634.  
  1635. /* Open the input file specified by 'entry', and return a descriptor.
  1636.    The open file is remembered; if the same file is opened twice in a row,
  1637.    a new open is not actually done.  */
  1638.  
  1639. int
  1640. file_open (entry)
  1641.      register struct file_entry *entry;
  1642. {
  1643.   register int desc;
  1644.  
  1645.   if (entry->superfile)
  1646.     return file_open (entry->superfile);
  1647.  
  1648.   if (entry == input_file)
  1649.     return input_desc;
  1650.  
  1651.   if (input_file) file_close ();
  1652.  
  1653.   if (entry->search_dirs_flag && n_search_dirs)
  1654.     {
  1655.       register char **p = search_dirs;
  1656.       int i;
  1657.  
  1658.       for (i = 0; i < n_search_dirs; i++)
  1659.     {
  1660.       register char *string
  1661. #ifndef atarist
  1662.         = concat (search_dirs[i], "/", entry->filename);
  1663. #else
  1664.         = concat (search_dirs[i], "\\", entry->filename);
  1665. #endif
  1666.       desc = open (string, O_RDONLY, 0);
  1667.       if (desc > 0)
  1668.         {
  1669.           entry->filename = string;
  1670.           entry->search_dirs_flag = 0;
  1671.           break;
  1672.         }
  1673.       free (string);
  1674.     }
  1675.     }
  1676.   else
  1677.     desc = open (entry->filename, O_RDONLY, 0);
  1678.  
  1679.   if (desc > 0)
  1680.     {
  1681.       input_file = entry;
  1682.       input_desc = desc;
  1683.       return desc;
  1684.     }
  1685.  
  1686.   perror_file (entry);
  1687.   /* NOTREACHED */
  1688. }
  1689.  
  1690. /* Print the filename of ENTRY on OUTFILE (a stdio stream),
  1691.    and then a newline.  */
  1692.  
  1693. void
  1694. prline_file_name (entry, outfile)
  1695.      struct file_entry *entry;
  1696.      FILE *outfile;
  1697. {
  1698.   print_file_name (entry, outfile);
  1699.   fprintf (outfile, "\n");
  1700. }
  1701.  
  1702. /* Print the filename of ENTRY on OUTFILE (a stdio stream).  */
  1703.  
  1704. void
  1705. print_file_name (entry, outfile)
  1706.      struct file_entry *entry;
  1707.      FILE *outfile;
  1708. {
  1709.   if (entry->superfile)
  1710.     {
  1711.       print_file_name (entry->superfile, outfile);
  1712.       fprintf (outfile, "(%s)", entry->filename);
  1713.     }
  1714.   else
  1715.     fprintf (outfile, "%s", entry->filename);
  1716. }
  1717.  
  1718. /* Return the filename of entry as a string (malloc'd for the purpose) */
  1719.  
  1720. char *
  1721. get_file_name (entry)
  1722.      struct file_entry *entry;
  1723. {
  1724.   char *result, *supfile;
  1725.   if (entry->superfile)
  1726.     {
  1727.       supfile = get_file_name (entry->superfile);
  1728.       result = (char *) xmalloc (strlen (supfile)
  1729.                  + strlen (entry->filename) + 3);
  1730.       sprintf (result, "%s(%s)", supfile, entry->filename);
  1731.       free (supfile);
  1732.     }
  1733.   else
  1734.     {
  1735.       result = (char *) xmalloc (strlen (entry->filename) + 1);
  1736.       strcpy (result, entry->filename);
  1737.     }
  1738.   return result;
  1739. }
  1740.  
  1741. /* Medium-level input routines for rel files.  */
  1742.  
  1743. /* Read a file's header into the proper place in the file_entry.
  1744.    DESC is the descriptor on which the file is open.
  1745.    ENTRY is the file's entry.  */
  1746.  
  1747. void
  1748. read_header (desc, entry)
  1749.      int desc;
  1750.      register struct file_entry *entry;
  1751. {
  1752.   register int len;
  1753.   struct exec *loc = (struct exec *) &entry->header;
  1754.  
  1755.   lseek (desc, entry->starting_offset, 0);
  1756.   len = read (desc, loc, sizeof (struct exec));
  1757.   if (len != sizeof (struct exec))
  1758.     fatal_with_file ("failure reading header of ", entry);
  1759.   if (N_BADMAG (*loc))
  1760.     fatal_with_file ("bad magic number in ", entry);
  1761.  
  1762.   entry->header_read_flag = 1;
  1763. }
  1764.  
  1765. /* Read the symbols of file ENTRY into core.
  1766.    Assume it is already open, on descriptor DESC.
  1767.    Also read the length of the string table, which follows the symbol table,
  1768.    but don't read the contents of the string table.  */
  1769.  
  1770. void
  1771. read_entry_symbols (desc, entry)
  1772.      struct file_entry *entry;
  1773.      int desc;
  1774. {
  1775.   int str_size;
  1776.  
  1777.   if (!entry->header_read_flag)
  1778.     read_header (desc, entry);
  1779.  
  1780.   entry->symbols = (struct nlist *) xmalloc (entry->header.a_syms);
  1781.  
  1782.   lseek (desc, N_SYMOFF (entry->header) + entry->starting_offset, 0);
  1783.   if (entry->header.a_syms != read (desc, entry->symbols, entry->header.a_syms))
  1784.     fatal_with_file ("premature end of file in symbols of ", entry);
  1785.  
  1786.   lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  1787.   if (sizeof str_size != read (desc, &str_size, sizeof str_size))
  1788.     fatal_with_file ("bad string table size in ", entry);
  1789.  
  1790.   entry->string_size = str_size;
  1791. }
  1792.  
  1793. /* Read the string table of file ENTRY into core.
  1794.    Assume it is already open, on descriptor DESC.
  1795.    Also record whether a GDB symbol segment follows the string table.  */
  1796.  
  1797. void
  1798. read_entry_strings (desc, entry)
  1799.      struct file_entry *entry;
  1800.      int desc;
  1801. {
  1802.   int buffer;
  1803.  
  1804.   if (!entry->header_read_flag)
  1805.     read_header (desc, entry);
  1806.  
  1807.   lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  1808.   if (entry->string_size != read (desc, entry->strings, entry->string_size))
  1809.     fatal_with_file ("premature end of file in strings of ", entry);
  1810.  
  1811.   /* While we are here, see if the file has a symbol segment at the end.
  1812.      For a separate file, just try reading some more.
  1813.      For a library member, compare current pos against total size.  */
  1814.   if (entry->superfile)
  1815.     {
  1816.       if (entry->total_size == N_STROFF (entry->header) + entry->string_size)
  1817.     return;
  1818.     }
  1819.   else
  1820.     {
  1821.       buffer = read (desc, &buffer, sizeof buffer);
  1822.       if (buffer == 0)
  1823.     return;
  1824.       if (buffer != sizeof buffer)
  1825.     fatal_with_file ("premature end of file in GDB symbol segment of ", entry);
  1826.     }
  1827.  
  1828.   entry->symseg_offset = N_STROFF (entry->header) + entry->string_size;
  1829. }
  1830.  
  1831. /* Read in the symbols of all input files.  */
  1832.  
  1833. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  1834. void enter_file_symbols (), enter_global_ref (), search_library ();
  1835.  
  1836. void
  1837. load_symbols ()
  1838. {
  1839.   register int i;
  1840.  
  1841.   if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
  1842.  
  1843.   for (i = 0; i < number_of_files; i++)
  1844.     {
  1845.       register struct file_entry *entry = &file_table[i];
  1846.       read_file_symbols (entry);
  1847.     }
  1848.  
  1849.   if (trace_files) fprintf (stderr, "\n");
  1850. }
  1851.  
  1852. /* If ENTRY is a rel file, read its symbol and string sections into core.
  1853.    If it is a library, search it and load the appropriate members
  1854.    (which means calling this function recursively on those members).  */
  1855.  
  1856. void
  1857. read_file_symbols (entry)
  1858.      register struct file_entry *entry;
  1859. {
  1860.   register int desc;
  1861.   register int len;
  1862.   int magicnum;
  1863.  
  1864.   desc = file_open (entry);
  1865.  
  1866.   len = read (desc, &magicnum, sizeof magicnum);
  1867.   if (len != sizeof magicnum)
  1868.     fatal_with_file ("failure reading header of ", entry);
  1869.  
  1870.   if (!N_BADMAG (*((struct exec *)&magicnum)))
  1871.     {
  1872.       read_entry_symbols (desc, entry);
  1873.       entry->strings = (char *) alloca (entry->string_size);
  1874.       read_entry_strings (desc, entry);
  1875.       enter_file_symbols (entry);
  1876.       entry->strings = 0;
  1877.     }
  1878.   else
  1879.     {
  1880.       char armag[SARMAG];
  1881.  
  1882.       lseek (desc, 0, 0);
  1883.       if (SARMAG != read (desc, armag, SARMAG) || strncmp (armag, ARMAG, SARMAG))
  1884.     fatal_with_file ("malformed input file (not rel or archive) ", entry);
  1885.       entry->library_flag = 1;
  1886.       search_library (desc, entry);
  1887.     }
  1888.  
  1889.   file_close ();
  1890. }
  1891.  
  1892. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  1893.  
  1894. void
  1895. enter_file_symbols (entry)
  1896.      struct file_entry *entry;
  1897. {
  1898.    register struct nlist
  1899.      *p,
  1900.      *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  1901. #if 0
  1902.    int lowest_set_vector = -1;
  1903. #endif
  1904.  
  1905.   if (trace_files) prline_file_name (entry, stderr);
  1906.  
  1907.   for (p = entry->symbols; p < end; p++)
  1908. #if 0
  1909.     /* Currently N_SETV symbols shouldn't be in input to the loader, */
  1910.     /* but I'll leave this here in case they ever are */
  1911.     if ((p->n_type & ~N_EXT) == N_SETV &&
  1912.     (lowest_set_vector = -1 || lowest_set_vector > p->n_value))
  1913.       lowest_set_vector = p->n_value;
  1914.     else
  1915. #endif
  1916.     if (SET_ELEMENT_P (p->n_type))
  1917.       {
  1918.     set_symbol_count++;
  1919.     if (!relocatable_output)
  1920.       enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1921.       }
  1922.     else if (p->n_type == N_WARNING)
  1923.       {
  1924.       char *name = p->n_un.n_strx + entry->strings;
  1925.  
  1926.       /* Grab the next entry.  */
  1927.       p++;
  1928.       if (p->n_type != (N_UNDF | N_EXT))
  1929.         {
  1930.           fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
  1931.                progname, entry->filename);
  1932.           make_executable = 0;
  1933.           p--;        /* Process normally.  */
  1934.         }
  1935.       else
  1936.         {
  1937.           symbol *sp;
  1938.           char *sname = p->n_un.n_strx + entry->strings;
  1939.           /* Deal with the warning symbol.  */
  1940.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1941.           sp = getsym (sname);
  1942.           sp->warning = (char *) xmalloc (strlen(name) + 1);
  1943.           strcpy (sp->warning, name);
  1944.           warning_count++;
  1945.         }
  1946.       }
  1947.     else if (p->n_type & N_EXT)
  1948.       enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1949.     else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  1950.       {
  1951.     if ((p->n_un.n_strx + entry->strings)[0] != 'L')
  1952.       non_L_local_sym_count++;
  1953.     local_sym_count++;
  1954.       }
  1955.     else debugger_sym_count++;
  1956.  
  1957. #if 0
  1958.   entry->set_vector_offset = lowest_set_vector;
  1959. #endif
  1960.  
  1961.    /* Count one for the local symbol that we generate,
  1962.       whose name is the file's name (usually) and whose address
  1963.       is the start of the file's text.  */
  1964.  
  1965.   local_sym_count++;
  1966.   non_L_local_sym_count++;
  1967. }
  1968.  
  1969. /* Enter one global symbol in the hash table.
  1970.    NLIST_P points to the `struct nlist' read from the file
  1971.    that describes the global symbol.  NAME is the symbol's name.
  1972.    ENTRY is the file entry for the file the symbol comes from.
  1973.  
  1974.    The `struct nlist' is modified by placing it on a chain of
  1975.    all such structs that refer to the same global symbol.
  1976.    This chain starts in the `refs' field of the symbol table entry
  1977.    and is chained through the `n_name'.  */
  1978.  
  1979. void
  1980. enter_global_ref (nlist_p, name, entry)
  1981.      register struct nlist *nlist_p;
  1982.      char *name;
  1983.      struct file_entry *entry;
  1984. {
  1985.   register symbol *sp = getsym (name);
  1986.   register int type = nlist_p->n_type;
  1987.   int oldref = sp->referenced;
  1988.   int olddef = sp->defined;
  1989.  
  1990.   nlist_p->n_un.n_name = (char *) sp->refs;
  1991.   sp->refs = nlist_p;
  1992.  
  1993.   sp->referenced = 1;
  1994.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  1995.     {
  1996.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  1997.     sp->defined = type;
  1998.  
  1999.       if (oldref && !olddef)
  2000.     /* It used to be undefined and we're defining it.  */
  2001.     undefined_global_sym_count--;
  2002.  
  2003. #if 0
  2004.       /* If this is a common definition, keep track of largest
  2005.      common definition seen for this symbol.  */
  2006.       if (type == (N_UNDF | N_EXT)
  2007.       && sp->max_common_size < nlist_p->n_value)
  2008.     sp->max_common_size = nlist_p->n_value;
  2009. #endif
  2010.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  2011.     {
  2012.       /* First definition and it's common.  */
  2013.       common_defined_global_count++;
  2014.       sp->max_common_size = nlist_p->n_value;
  2015.     }
  2016.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  2017.     {
  2018.       /* It used to be common and we're defining it as
  2019.          something else.  */
  2020.       common_defined_global_count--;
  2021.       sp->max_common_size = 0;
  2022.     }
  2023.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  2024.       && sp->max_common_size < nlist_p->n_value)
  2025.     /* It used to be common and this is a new common entry to
  2026.        which we need to pay attention.  */
  2027.     sp->max_common_size = nlist_p->n_value;
  2028.  
  2029.  
  2030.       /* Are we defining it as a set element?  */
  2031. #if 0
  2032.       if (SET_ELEMENT_P (type)) /* potential fix but i dont see why ++jrb */
  2033. #endif
  2034.       if (SET_ELEMENT_P (type)
  2035.       && (!olddef || (olddef && sp->max_common_size)))
  2036.     set_vector_count++;
  2037.       /* Indirect symbols value should be modified to point
  2038.      a symbol being equivalenced to. */
  2039.       if (type == (N_INDR | N_EXT))
  2040.     {
  2041.       nlist_p->n_value =
  2042.         (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  2043.                    + entry->strings);
  2044.       if ((symbol *) nlist_p->n_value == sp)
  2045.         {
  2046.           /* Somebody redefined a symbol to be itself.  */
  2047.           fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
  2048.                entry->filename, name);
  2049.           /* Rewrite this symbol as being a global text symbol
  2050.          with value 0.  */
  2051.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  2052.           nlist_p->n_value = 0;
  2053.           /* Don't make the output executable.  */
  2054.           make_executable = 0;
  2055.         }
  2056.       else
  2057.             global_indirect_count++;
  2058.     }
  2059.     }
  2060.   else
  2061.     if (!oldref)
  2062. #ifndef DOLLAR_KLUDGE
  2063.       undefined_global_sym_count++;
  2064. #else
  2065.       {
  2066.     if (entry->superfile && type == (N_UNDF | N_EXT) && name[1] == '$')
  2067.       {
  2068.         /* This is an (ISI?) $-conditional; skip it */
  2069.         sp->referenced = 0;
  2070.         if (sp->trace)
  2071.           {
  2072.         fprintf (stderr, "symbol %s is a $-conditional ignored in ", sp->name);
  2073.         print_file_name (entry, stderr);
  2074.         fprintf (stderr, "\n");
  2075.           }
  2076.         return;
  2077.       }
  2078.     else
  2079.       undefined_global_sym_count++;
  2080.       }
  2081. #endif
  2082.  
  2083.   if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
  2084.     text_start = nlist_p->n_value;
  2085.  
  2086.   if (sp->trace)
  2087.     {
  2088.       register char *reftype;
  2089.       switch (type & ~N_EXT)
  2090.     {
  2091.     case N_UNDF:
  2092.       if (nlist_p->n_value)
  2093.         reftype = "defined as common";
  2094.       else reftype = "referenced";
  2095.       break;
  2096.  
  2097.     case N_ABS:
  2098.       reftype = "defined as absolute";
  2099.       break;
  2100.  
  2101.     case N_TEXT:
  2102.       reftype = "defined in text section";
  2103.       break;
  2104.  
  2105.     case N_DATA:
  2106.       reftype = "defined in data section";
  2107.       break;
  2108.  
  2109.     case N_BSS:
  2110.       reftype = "defined in BSS section";
  2111.       break;
  2112.  
  2113.     case N_SETT:
  2114.       reftype = "is a text set element";
  2115.       break;
  2116.  
  2117.     case N_SETD:
  2118.       reftype = "is a data set element";
  2119.       break;
  2120.  
  2121.     case N_SETB:
  2122.       reftype = "is a BSS set element";
  2123.       break;
  2124.  
  2125.     case N_SETA:
  2126.       reftype = "is an absolute set element";
  2127.       break;
  2128.  
  2129.     case N_SETV:
  2130.       reftype = "defined in text section as vector";
  2131.       break;
  2132.  
  2133.     case N_INDR:
  2134.       reftype = (char *) alloca (23
  2135.                      + strlen ((nlist_p + 1)->n_un.n_strx
  2136.                            + entry->strings));
  2137.       sprintf (reftype, "defined equivalent to %s",
  2138.            (nlist_p + 1)->n_un.n_strx + entry->strings);
  2139.       break;
  2140.  
  2141.     default:
  2142.       reftype = "I don't know this type";
  2143.       break;
  2144.     }
  2145.  
  2146.       fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
  2147.       print_file_name (entry, stderr);
  2148.       fprintf (stderr, "\n");
  2149.     }
  2150. }
  2151.  
  2152. /* This return 0 if the given file entry's symbol table does *not*
  2153.    contain the nlist point entry, and it returns the files entry
  2154.    pointer (cast to unsigned long) if it does. */
  2155.  
  2156. unsigned long
  2157. contains_symbol (entry, n_ptr)
  2158.      struct file_entry *entry;
  2159.      register struct nlist *n_ptr;
  2160. {
  2161.   if (n_ptr >= entry->symbols &&
  2162.       n_ptr < (entry->symbols
  2163.            + (entry->header.a_syms / sizeof (struct nlist))))
  2164.     return (unsigned long) entry;
  2165.   return 0;
  2166. }
  2167.  
  2168.  
  2169. /* Searching libraries */
  2170.  
  2171. struct file_entry *decode_library_subfile ();
  2172. void linear_library (), symdef_library ();
  2173.  
  2174. /* Search the library ENTRY, already open on descriptor DESC.
  2175.    This means deciding which library members to load,
  2176.    making a chain of `struct file_entry' for those members,
  2177.    and entering their global symbols in the hash table.  */
  2178.  
  2179. void
  2180. search_library (desc, entry)
  2181.      int desc;
  2182.      struct file_entry *entry;
  2183. {
  2184.   int member_length;
  2185.   register char *name;
  2186.   register struct file_entry *subentry;
  2187.  
  2188.   if (!undefined_global_sym_count) return;
  2189.  
  2190.   /* Examine its first member, which starts SARMAG bytes in.  */
  2191.   subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  2192.   if (!subentry) return;
  2193.  
  2194.   name = subentry->filename;
  2195.   free (subentry);
  2196.  
  2197.   /* Search via __.SYMDEF if that exists, else linearly.  */
  2198.  
  2199.   if (!strcmp (name, "__.SYMDEF"))
  2200.     symdef_library (desc, entry, member_length);
  2201.   else
  2202.     linear_library (desc, entry);
  2203. }
  2204.  
  2205. /* Construct and return a file_entry for a library member.
  2206.    The library's file_entry is library_entry, and the library is open on DESC.
  2207.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  2208.    We store the length of the member into *LENGTH_LOC.  */
  2209.  
  2210. struct file_entry *
  2211. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  2212.      int desc;
  2213.      struct file_entry *library_entry;
  2214.      int subfile_offset;
  2215.      int *length_loc;
  2216. {
  2217.   int bytes_read;
  2218.   register int namelen;
  2219.   int member_length;
  2220.   register char *name;
  2221.   struct ar_hdr hdr1;
  2222.   register struct file_entry *subentry;
  2223.  
  2224.   lseek (desc, subfile_offset, 0);
  2225.  
  2226. #if (defined(WORD_ALIGNED) && defined(CROSSATARI))
  2227.   bytes_read =  read (desc, hdr1.ar_name,
  2228.              sizeof (hdr1.ar_name));
  2229.   bytes_read += read (desc, hdr1.ar_size, 
  2230.               sizeof (hdr1.ar_size));
  2231.   bytes_read += read (desc, hdr1.ar_date, 
  2232.               sizeof (hdr1.ar_date));
  2233.   bytes_read += read (desc, hdr1.ar_mode, 
  2234.               sizeof (hdr1.ar_mode));
  2235.   bytes_read += read (desc, hdr1.ar_uid, 
  2236.               sizeof (hdr1.ar_uid));
  2237.   bytes_read += read (desc, hdr1.ar_gid, 
  2238.               sizeof (hdr1.ar_gid));
  2239.   bytes_read += read (desc, hdr1.ar_fmag, 
  2240.               sizeof (hdr1.ar_fmag));
  2241. #else
  2242.   bytes_read = read (desc, &hdr1, sizeof hdr1);
  2243. #endif
  2244.   if (!bytes_read)
  2245.     return 0;        /* end of archive */
  2246.  
  2247. #if (defined(WORD_ALIGNED) && defined(CROSSATARI))
  2248.   if (bytes_read  != (sizeof (hdr1.ar_name) +
  2249.               sizeof (hdr1.ar_size) +
  2250.               sizeof (hdr1.ar_date) +
  2251.               sizeof (hdr1.ar_mode) +
  2252.               sizeof (hdr1.ar_uid) +
  2253.               sizeof (hdr1.ar_gid) +
  2254.               sizeof (hdr1.ar_fmag)))
  2255.     fatal_with_file ("malformed library archive ", library_entry);
  2256. #else
  2257.   if (sizeof hdr1 != bytes_read)
  2258.     fatal_with_file ("malformed library archive ", library_entry);
  2259. #endif
  2260.  
  2261.   if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  2262.     fatal_with_file ("malformatted header of archive member in ", library_entry);
  2263.  
  2264.   subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  2265.   bzero (subentry, sizeof (struct file_entry));
  2266.  
  2267.   for (namelen = 0;
  2268.        namelen < sizeof hdr1.ar_name
  2269.        && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
  2270.        && hdr1.ar_name[namelen] != '/';
  2271.        namelen++);
  2272.  
  2273.   name = (char *) xmalloc (namelen+1);
  2274.   strncpy (name, hdr1.ar_name, namelen);
  2275.   name[namelen] = 0;
  2276.  
  2277.   subentry->filename = name;
  2278.   subentry->local_sym_name = name;
  2279.   subentry->symbols = 0;
  2280.   subentry->strings = 0;
  2281.   subentry->subfiles = 0;
  2282. #if (defined(WORD_ALIGNED) && defined(CROSSATARI))
  2283.   subentry->starting_offset = subfile_offset + (sizeof (hdr1.ar_name) +
  2284.                         sizeof (hdr1.ar_size) +
  2285.                         sizeof (hdr1.ar_date) +
  2286.                         sizeof (hdr1.ar_mode) +
  2287.                         sizeof (hdr1.ar_uid) +
  2288.                         sizeof (hdr1.ar_gid) +
  2289.                         sizeof (hdr1.ar_fmag)) ;
  2290. #else
  2291.   subentry->starting_offset = subfile_offset + sizeof hdr1;
  2292. #endif
  2293.   subentry->superfile = library_entry;
  2294.   subentry->library_flag = 0;
  2295.   subentry->header_read_flag = 0;
  2296.   subentry->just_syms_flag = 0;
  2297.   subentry->chain = 0;
  2298.   subentry->total_size = member_length;
  2299.  
  2300.   (*length_loc) = member_length;
  2301.  
  2302.   return subentry;
  2303. }
  2304.  
  2305. int subfile_wanted_p ();
  2306.  
  2307. /* Search a library that has a __.SYMDEF member.
  2308.    DESC is a descriptor on which the library is open.
  2309.      The file pointer is assumed to point at the __.SYMDEF data.
  2310.    ENTRY is the library's file_entry.
  2311.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  2312.  
  2313. void
  2314. symdef_library (desc, entry, member_length)
  2315.      int desc;
  2316.      struct file_entry *entry;
  2317.      int member_length;
  2318. {
  2319.   int *symdef_data = (int *) xmalloc (member_length);
  2320.   register struct symdef *symdef_base;
  2321.   char *sym_name_base;
  2322.   int number_of_symdefs;
  2323.   int length_of_strings;
  2324.   int not_finished;
  2325.   int bytes_read;
  2326.   register int i;
  2327.   struct file_entry *prev = 0;
  2328.   int prev_offset = 0;
  2329.  
  2330.   bytes_read = read (desc, symdef_data, member_length);
  2331.   if (bytes_read != member_length)
  2332.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2333.  
  2334.   number_of_symdefs = *symdef_data / sizeof (struct symdef);
  2335.   if (number_of_symdefs < 0 ||
  2336.        number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
  2337.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2338.  
  2339.   symdef_base = (struct symdef *) (symdef_data + 1);
  2340.   length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  2341.  
  2342.   if (length_of_strings < 0
  2343.       || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  2344.       + 2 * sizeof (int) != member_length)
  2345.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2346.  
  2347.   sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  2348.  
  2349.   /* Check all the string indexes for validity.  */
  2350.  
  2351.   for (i = 0; i < number_of_symdefs; i++)
  2352.     {
  2353.       register int index = symdef_base[i].symbol_name_string_index;
  2354.       if (index < 0 || index >= length_of_strings
  2355.       || (index && *(sym_name_base + index - 1)))
  2356.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2357.     }
  2358.  
  2359.   /* Search the symdef data for members to load.
  2360.      Do this until one whole pass finds nothing to load.  */
  2361.  
  2362.   not_finished = 1;
  2363.   while (not_finished)
  2364.     {
  2365.       not_finished = 0;
  2366.  
  2367.       /* Scan all the symbols mentioned in the symdef for ones that we need.
  2368.      Load the library members that contain such symbols.  */
  2369.  
  2370.       for (i = 0;
  2371.        (i < number_of_symdefs
  2372.         && (undefined_global_sym_count || common_defined_global_count));
  2373.        i++)
  2374.     if (symdef_base[i].symbol_name_string_index >= 0)
  2375.       {
  2376.         register symbol *sp;
  2377.  
  2378.         sp = getsym_soft (sym_name_base
  2379.                   + symdef_base[i].symbol_name_string_index);
  2380.  
  2381.         /* If we find a symbol that appears to be needed, think carefully
  2382.            about the archive member that the symbol is in.  */
  2383.  
  2384.         if (sp && ((sp->referenced && !sp->defined)
  2385.                || (sp->defined && sp->max_common_size)))
  2386.           {
  2387.         int junk;
  2388.         register int j;
  2389.         register int offset = symdef_base[i].library_member_offset;
  2390.         struct file_entry *subentry;
  2391.  
  2392.         /* Don't think carefully about any archive member
  2393.            more than once in a given pass.  */
  2394.  
  2395.         if (prev_offset == offset)
  2396.           continue;
  2397.         prev_offset = offset;
  2398.  
  2399.         /* Read the symbol table of the archive member.  */
  2400.  
  2401.         subentry = decode_library_subfile (desc, entry, offset, &junk);
  2402.         if (subentry == 0)
  2403.           fatal ("invalid offset for %s in symbol table of %s",
  2404.              sym_name_base
  2405.              + symdef_base[i].symbol_name_string_index,
  2406.              entry->filename);
  2407.         read_entry_symbols (desc, subentry);
  2408.         subentry->strings = (char *) malloc (subentry->string_size);
  2409.         read_entry_strings (desc, subentry);
  2410.  
  2411.         /* Now scan the symbol table and decide whether to load.  */
  2412.  
  2413.         if (!subfile_wanted_p (subentry))
  2414.           {
  2415.             free (subentry->symbols);
  2416.             free (subentry->strings);
  2417.             free (subentry);
  2418.           }
  2419.         else
  2420.           {
  2421.             /* This member is needed; load it.
  2422.                Since we are loading something on this pass,
  2423.                we must make another pass through the symdef data.  */
  2424.  
  2425.             not_finished = 1;
  2426.  
  2427.             enter_file_symbols (subentry);
  2428.  
  2429.             if (prev)
  2430.               prev->chain = subentry;
  2431.             else entry->subfiles = subentry;
  2432.             prev = subentry;
  2433.  
  2434.             /* Clear out this member's symbols from the symdef data
  2435.                so that following passes won't waste time on them.  */
  2436.  
  2437.             for (j = 0; j < number_of_symdefs; j++)
  2438.               {
  2439.             if (symdef_base[j].library_member_offset == offset)
  2440.               symdef_base[j].symbol_name_string_index = -1;
  2441.               }
  2442.             /* We'll read the strings again if we need them again.  */
  2443.             free (subentry->strings);
  2444.             subentry->strings = 0;
  2445.           }
  2446.           }
  2447.       }
  2448.     }
  2449.  
  2450.   free (symdef_data);
  2451. }
  2452.  
  2453. /* Search a library that has no __.SYMDEF.
  2454.    ENTRY is the library's file_entry.
  2455.    DESC is the descriptor it is open on.  */
  2456.  
  2457. void
  2458. linear_library (desc, entry)
  2459.      int desc;
  2460.      struct file_entry *entry;
  2461. {
  2462.   register struct file_entry *prev = 0;
  2463.   register int this_subfile_offset = SARMAG;
  2464.  
  2465.   while (undefined_global_sym_count || common_defined_global_count)
  2466.     {
  2467.       int member_length;
  2468.       register struct file_entry *subentry;
  2469.  
  2470.       subentry = decode_library_subfile (desc, entry, this_subfile_offset, &member_length);
  2471.  
  2472.       if (!subentry) return;
  2473.  
  2474.       read_entry_symbols (desc, subentry);
  2475.       subentry->strings = (char *) alloca (subentry->string_size);
  2476.       read_entry_strings (desc, subentry);
  2477.  
  2478.       if (!subfile_wanted_p (subentry))
  2479.     {
  2480.       free (subentry->symbols);
  2481.       free (subentry);
  2482.     }
  2483.       else
  2484.     {
  2485.       enter_file_symbols (subentry);
  2486.  
  2487.       if (prev)
  2488.         prev->chain = subentry;
  2489.       else
  2490.             entry->subfiles = subentry;
  2491.       prev = subentry;
  2492.           subentry->strings = 0; /* Since space will dissapear on return */
  2493.     }
  2494.  
  2495.       this_subfile_offset += member_length + sizeof (struct ar_hdr);
  2496.       if (this_subfile_offset & 1) this_subfile_offset++;
  2497.     }
  2498. }
  2499.  
  2500. /* ENTRY is an entry for a library member.
  2501.    Its symbols have been read into core, but not entered.
  2502.    Return nonzero if we ought to load this member.  */
  2503.  
  2504. int
  2505. subfile_wanted_p (entry)
  2506.      struct file_entry *entry;
  2507. {
  2508.   register struct nlist *p;
  2509.   register struct nlist *end
  2510.     = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  2511. #ifdef DOLLAR_KLUDGE
  2512.   register int dollar_cond = 0;
  2513. #endif
  2514.  
  2515.   for (p = entry->symbols; p < end; p++)
  2516.     {
  2517.       register int type = p->n_type;
  2518.       register char *name = p->n_un.n_strx + entry->strings;
  2519.  
  2520.       if (type & N_EXT && (type != (N_UNDF | N_EXT) || p->n_value
  2521. #ifdef DOLLAR_KLUDGE
  2522.                || name[1] == '$'
  2523. #endif
  2524.                ))
  2525.     {
  2526.       register symbol *sp = getsym_soft (name);
  2527.  
  2528. #ifdef DOLLAR_KLUDGE
  2529.       if (name[1] == '$')
  2530.         {
  2531.           sp = getsym_soft (&name[2]);
  2532.           dollar_cond = 1;
  2533.           if (!sp) continue;
  2534.           if (sp->referenced)
  2535.         {
  2536.           if (write_map)
  2537.             {
  2538.               print_file_name (entry, stdout);
  2539.               fprintf (stdout, " needed due to $-conditional %s\n", name);
  2540.             }
  2541.           return 1;
  2542.         }
  2543.           continue;
  2544.         }
  2545. #endif
  2546.  
  2547.       /* If this symbol has not been hashed, we can't be looking for it. */
  2548.  
  2549.       if (!sp) continue;
  2550.  
  2551.       /* Note: There has been a lot of discussion about what to
  2552.          when a common definition was previously seen (i.e. when
  2553.          sp->max_common_size > 0).
  2554.          The latest solution is to treat a previous common definition
  2555.          (wrt to subfile_wanted_p) no differently from a real definition.
  2556.          This has the advantage of simplicity and consistency: a common
  2557.          definition is just like a common definition (consistent
  2558.          with strict ANSI C) except that we allow duplicate definitions.
  2559.          Possible disadvantage: May not be the best choice for Fortran,
  2560.          though it is consistent with the standard.
  2561.  
  2562.          An earlier solution:
  2563.          We wanted to see a common definition in the subfile,
  2564.          and note its size, but ignore any other definition
  2565.          if the symbol was already defined (even as a common).
  2566.          This meant that if there were multiple common definitions,
  2567.          the final definition would use the largest size of any of them,
  2568.          as it should.  But if there was a common definition and another
  2569.          definition, like "int pipe;" in a program and "int pipe() {}"
  2570.          in the library, only the common would be used.
  2571.          Disadvantage: a poorly justified kludge.
  2572.  
  2573.          Another previous solution:
  2574.          If the symbol already had a definition as a common symbol,
  2575.          we would want this subfile if some other subfile of the
  2576.          same library that we already need anyway also used the symbol.
  2577.          This seemed like an even more ad hoc decision.
  2578.          It would also cause subfiles to be pulled in that would
  2579.          then conflict with previous entries. I.e. you couldn't
  2580.          have: ld ... start.o libc.a ... if libc.a contained start.o.
  2581.  
  2582.          Other hybrid solutions were also considered.
  2583.       */
  2584.  
  2585.       if (sp->referenced && !sp->defined)
  2586.         {
  2587.           /* This is a symbol we are looking for.  */
  2588. #ifdef DOLLAR_KLUDGE
  2589.           if (dollar_cond) continue;
  2590. #endif
  2591.           if (type == (N_UNDF | N_EXT))
  2592.         {
  2593.           /* Symbol being defined as common.
  2594.              Remember this, but don't load subfile just for this.  */
  2595.  
  2596.           common_defined_global_count++;
  2597.           sp->max_common_size = p->n_value;
  2598.           undefined_global_sym_count--;
  2599.           sp->defined = 1;
  2600.           continue;
  2601.         }
  2602.  
  2603.           if (write_map)
  2604.         {
  2605.           char *nm;
  2606.           if (demangler == NULL || (nm = (*demangler)(sp->name)) == NULL)
  2607.             nm = sp->name;
  2608.           print_file_name (entry, stdout);
  2609.           fprintf (stdout, " needed due to %s\n", nm);
  2610.           if(nm != sp->name)
  2611.               free(nm);
  2612.         }
  2613.           return 1;
  2614.         }
  2615.     }
  2616.     }
  2617.  
  2618.   return 0;
  2619. }
  2620.  
  2621. void consider_file_section_lengths (), relocate_file_addresses ();
  2622. void print_files_defining_symbol ();
  2623.  
  2624. /* Having entered all the global symbols and found the sizes of sections
  2625.    of all files to be linked, make all appropriate deductions from this data.
  2626.  
  2627.    We propagate global symbol values from definitions to references.
  2628.    We compute the layout of the output file and where each input file's
  2629.    contents fit into it.  */
  2630.  
  2631. void
  2632. digest_symbols ()
  2633. {
  2634.   register int i;
  2635.   int setv_fill_count;
  2636.  
  2637.   if (trace_files)
  2638.     fprintf (stderr, "Digesting symbol information:\n\n");
  2639.  
  2640.   /* Compute total size of sections */
  2641.  
  2642.   each_file (consider_file_section_lengths, 0);
  2643.  
  2644.   /* Setup the set element vector */
  2645.  
  2646.   if (!relocatable_output)
  2647.     {
  2648.       set_sect_size =
  2649.     (set_symbol_count + 2 * set_vector_count) * sizeof (unsigned long);
  2650.       set_sect_start = text_start + text_size;
  2651.       text_size += set_sect_size;
  2652.       set_vectors = (unsigned long *) xmalloc (set_sect_size);
  2653.       setv_fill_count = 0;
  2654.     }
  2655.   /* If necessary, pad text section to full page in the file.
  2656.      Include the padding in the text segment size.  */
  2657.  
  2658.   if (magic == NMAGIC || magic == ZMAGIC)
  2659.     {
  2660.       int text_end = text_size + N_TXTOFF (outheader);
  2661.       text_pad = ((text_end + page_size - 1) & (- page_size)) - text_end;
  2662.       text_size += text_pad;
  2663.     }
  2664.  
  2665.   outheader.a_text = text_size;
  2666.  
  2667.   /* Make the data segment address start in memory on a suitable boundary.  */
  2668.  
  2669.   if (! Tdata_flag_specified)
  2670.     data_start = N_DATADDR (outheader) + text_start - N_TXTADDR (outheader);
  2671.  
  2672.   /* Compute start addresses of each file's sections and symbols.  */
  2673.  
  2674.   each_full_file (relocate_file_addresses, 0);
  2675.  
  2676.   /* Now, for each symbol, verify that it is defined globally at most once.
  2677.      Put the global value into the symbol entry.
  2678.      Common symbols are allocated here, in the BSS section.
  2679.      Each defined symbol is given a '->defined' field
  2680.       which is the correct N_ code for its definition,
  2681.       except in the case of common symbols with -r.
  2682.      Then make all the references point at the symbol entry
  2683.      instead of being chained together. */
  2684.  
  2685.   defined_global_sym_count = 0;
  2686.  
  2687.   for (i = 0; i < TABSIZE; i++)
  2688.     {
  2689.       register symbol *sp;
  2690.       for (sp = symtab[i]; sp; sp = sp->link)
  2691.     {
  2692.       /* For each symbol */
  2693.       register struct nlist *p, *next;
  2694.       int defs = 0, com = sp->max_common_size, erred = 0;
  2695.       struct nlist *first_definition;
  2696.       for (p = sp->refs; p; p = next)
  2697.         {
  2698.           register int type = p->n_type;
  2699.  
  2700. #if 0
  2701.           if ((type & ~N_EXT) == N_SETV) continue;
  2702. #endif
  2703.           if (SET_ELEMENT_P (type))
  2704.         {
  2705.           if (relocatable_output)
  2706.             fatal ("internal: global ref to set element with -r");
  2707.           if (!defs++)
  2708.             {
  2709.               sp->value = set_sect_start
  2710.             + setv_fill_count++ * sizeof (unsigned long);
  2711.               sp->defined = N_SETV | N_EXT;
  2712.               first_definition = p;
  2713.             }
  2714.           else if ((sp->defined & ~N_EXT) != N_SETV)
  2715.             {
  2716.               make_executable = 0;
  2717.               error ("text symbol `%s' redefined as set vector.  Files:",
  2718.                  sp->name);
  2719.               print_files_defining_symbol (first_definition, p);
  2720.             }
  2721.           set_vectors[setv_fill_count++] = p->n_value;
  2722.         }
  2723.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  2724.         {
  2725.           /* non-common definition */
  2726.           if (defs++ && sp->value != p->n_value)
  2727.             if (!erred++)
  2728.               {
  2729.                 make_executable = 0;
  2730.             error ("multiple definitions of symbol `%s'.  Files:",
  2731.                    sp->name);
  2732.             print_files_defining_symbol (first_definition, p);
  2733.               }
  2734.           sp->value = p->n_value;
  2735.           sp->defined = type;
  2736.           first_definition = p;
  2737.         }
  2738.           next = (struct nlist *) p->n_un.n_name;
  2739.           p->n_un.n_name = (char *) sp;
  2740.         }
  2741.       /* Allocate as common if defined as common and not defined for real */
  2742.       if (com && !defs)
  2743.         {
  2744.           if (!relocatable_output || force_common_definition)
  2745.         {
  2746.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  2747.  
  2748.           sp->value = data_start + data_size + bss_size;
  2749.           sp->defined = N_BSS | N_EXT;
  2750.           bss_size += com;
  2751.           if (write_map)
  2752.             printf ("Allocating common %s: %x at %x\n",
  2753.                 sp->name, com, sp->value);
  2754.         }
  2755.           else
  2756.         {
  2757.           sp->defined = 0;
  2758.           undefined_global_sym_count++;
  2759.         }
  2760.         }
  2761.       /* Set length word at front of vector and add zero at the end.
  2762.              Also reverse the vector to put it in file order. */
  2763.       if ((sp->defined & ~N_EXT) == N_SETV)
  2764.         {
  2765.           unsigned long length_word_index =
  2766.         (sp->value - set_sect_start) / sizeof (unsigned long);
  2767.               unsigned long i, tmp;
  2768.  
  2769.           set_vectors[length_word_index]
  2770.             = setv_fill_count - 1 - length_word_index;
  2771.             
  2772.           /* Reverse the vector. */
  2773.           for (i = 1;
  2774.                i < (setv_fill_count - length_word_index - 1) / 2 + 1;
  2775.                i++)
  2776.             {
  2777.               tmp = set_vectors[length_word_index + i];
  2778.               set_vectors[length_word_index + i]
  2779.                 = set_vectors[setv_fill_count - i];
  2780.               set_vectors[setv_fill_count - i] = tmp;
  2781.             }
  2782.             
  2783.           set_vectors[setv_fill_count++] = 0;
  2784.         }
  2785.       if (sp->defined)
  2786.         defined_global_sym_count++;
  2787.     }
  2788.     }
  2789.  
  2790.   if (end_symbol)        /* These are null if -r.  */
  2791.     {
  2792.       etext_symbol->value = text_size + text_start;
  2793.       edata_symbol->value = data_start + data_size;
  2794.       end_symbol->value = data_start + data_size + bss_size;
  2795.     }
  2796.  
  2797.   /* Figure the data_pad now, so that it overlaps with the bss addresses.  */
  2798.  
  2799.   if (specified_data_size && specified_data_size > data_size)
  2800.     data_pad = specified_data_size - data_size;
  2801.  
  2802.   if (magic == ZMAGIC)
  2803.     data_pad = ((data_pad + data_size + page_size - 1) & (- page_size))
  2804.                - data_size;
  2805.  
  2806.   bss_size -= data_pad;
  2807.   if (bss_size < 0) bss_size = 0;
  2808.  
  2809.   data_size += data_pad;
  2810. }
  2811.  
  2812. /* Accumulate the section sizes of input file ENTRY
  2813.    into the section sizes of the output file.  */
  2814.  
  2815. void
  2816. consider_file_section_lengths (entry)
  2817.      register struct file_entry *entry;
  2818. {
  2819.   if (entry->just_syms_flag)
  2820.     return;
  2821.  
  2822.   entry->text_start_address = text_size;
  2823.   /* If there were any vectors, we need to chop them off */
  2824. #if 0
  2825.   /* There should never be set vectors in input to the loader */
  2826.   if (entry->set_vector_offset == -1)
  2827. #endif
  2828.   text_size += entry->header.a_text;
  2829. #if 0
  2830.   else
  2831.     text_size += entry->set_vector_offset - N_TXTOFF (entry->header);
  2832. #endif
  2833.   entry->data_start_address = data_size;
  2834.   data_size += entry->header.a_data;
  2835.   entry->bss_start_address = bss_size;
  2836.   bss_size += entry->header.a_bss;
  2837.  
  2838.   text_reloc_size += entry->header.a_trsize;
  2839.   data_reloc_size += entry->header.a_drsize;
  2840. }
  2841.  
  2842. /* Determine where the sections of ENTRY go into the output file,
  2843.    whose total section sizes are already known.
  2844.    Also relocate the addresses of the file's local and debugger symbols.  */
  2845.  
  2846. void
  2847. relocate_file_addresses (entry)
  2848.      register struct file_entry *entry;
  2849. {
  2850.   entry->text_start_address += text_start;
  2851.   /* Note that `data_start' and `data_size' have not yet been
  2852.      adjusted for `data_pad'.  If they had been, we would get the wrong
  2853.      results here.  */
  2854.   entry->data_start_address += data_start;
  2855.   entry->bss_start_address += data_start + data_size;
  2856.  
  2857.   {
  2858.     register struct nlist *p;
  2859.     register struct nlist *end
  2860.       = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  2861.  
  2862.     for (p = entry->symbols; p < end; p++)
  2863.       {
  2864.     /* If this belongs to a section, update it by the section's start address */
  2865.     register int type = p->n_type & N_TYPE;
  2866.  
  2867.     switch (type)
  2868.       {
  2869.       case N_TEXT:
  2870.       case N_SETT:
  2871.         p->n_value += entry->text_start_address;
  2872.         break;
  2873.       case N_DATA:
  2874.       case N_SETV:
  2875.       case N_SETD:
  2876.         /* A symbol whose value is in the data section
  2877.            is present in the input file as if the data section
  2878.            started at an address equal to the length of the file's text.  */
  2879.         p->n_value += entry->data_start_address - entry->header.a_text;
  2880.         break;
  2881.       case N_BSS:
  2882.       case N_SETB:
  2883.         /* likewise for symbols with value in BSS.  */
  2884.         p->n_value += entry->bss_start_address
  2885.           - entry->header.a_text - entry->header.a_data;
  2886.         break;
  2887.       }
  2888.       }
  2889.   }
  2890. }
  2891.  
  2892. void describe_file_sections (), list_file_locals ();
  2893.  
  2894. /* Print a complete or partial map of the output file.  */
  2895.  
  2896. void
  2897. print_symbols (outfile)
  2898.      FILE *outfile;
  2899. {
  2900.   register int i;
  2901.  
  2902.   fprintf (outfile, "\nFiles:\n\n");
  2903.  
  2904.   each_file (describe_file_sections, outfile);
  2905.  
  2906.   fprintf (outfile, "\nGlobal symbols:\n\n");
  2907.  
  2908.   for (i = 0; i < TABSIZE; i++)
  2909.     {
  2910.       register symbol *sp;
  2911.       for (sp = symtab[i]; sp; sp = sp->link)
  2912.     {
  2913.       char *nm = NULL;
  2914.       if ((sp->defined || sp->referenced) && (demangler != NULL))
  2915.         nm = (*demangler)(sp->name);
  2916.       if(nm == NULL)
  2917.           nm = sp->name;
  2918.       if (sp->defined == 1)
  2919.         fprintf (outfile, "  %s: common, length 0x%x\n", nm, sp->max_common_size);
  2920.       if (sp->defined)
  2921.         fprintf (outfile, "  %s: 0x%x\n", nm, sp->value);
  2922.       else if (sp->referenced)
  2923.         fprintf (outfile, "  %s: undefined\n", nm);
  2924.       if(nm != sp->name)
  2925.         free(nm);
  2926.     }
  2927.     }
  2928.  
  2929.   each_file (list_file_locals, outfile);
  2930. }
  2931.  
  2932. void
  2933. describe_file_sections (entry, outfile)
  2934.      struct file_entry *entry;
  2935.      FILE *outfile;
  2936. {
  2937.   fprintf (outfile, "  ");
  2938.   print_file_name (entry, outfile);
  2939.   if (entry->just_syms_flag)
  2940.     fprintf (outfile, " symbols only\n", 0);
  2941.   else
  2942.     fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
  2943.          entry->text_start_address, entry->header.a_text,
  2944.          entry->data_start_address, entry->header.a_data,
  2945.          entry->bss_start_address, entry->header.a_bss);
  2946. }
  2947.  
  2948. void
  2949. list_file_locals (entry, outfile)
  2950.      struct file_entry *entry;
  2951.      FILE *outfile;
  2952. {
  2953.   register struct nlist *p, *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  2954.  
  2955.   entry->strings = (char *) alloca (entry->string_size);
  2956.   read_entry_strings (file_open (entry), entry);
  2957.  
  2958.   fprintf (outfile, "\nLocal symbols of ");
  2959.   print_file_name (entry, outfile);
  2960.   fprintf (outfile, ":\n\n");
  2961.  
  2962.   for (p = entry->symbols; p < end; p++)
  2963.     /* If this is a definition,
  2964.        update it if necessary by this file's start address.  */
  2965.     if (!((p->n_type & (N_STAB | N_EXT)) || SET_ELEMENT_P(p->n_type)))
  2966.     {
  2967.       char *s = entry->strings + p->n_un.n_strx;
  2968.       char *nm;
  2969.  
  2970.       if (demangler == NULL || (nm = (*demangler)(s)) == NULL)
  2971.           nm = s;
  2972.       fprintf (outfile, "  %s: 0x%x\n", nm, p->n_value);
  2973.       if(nm != s)
  2974.     free(nm);
  2975.       }
  2976.  
  2977.   entry->strings = 0;        /* All done with them.  */
  2978. }
  2979.  
  2980.  
  2981. /* Static vars for do_warnings and subroutines of it */
  2982. int list_unresolved_refs;    /* List unresolved refs */
  2983. int list_warning_symbols;    /* List warning syms */
  2984. int list_multple_defs;        /* List multiple definitions */
  2985.  
  2986. /*
  2987.  * Structure for communication between do_file_warnings and it's
  2988.  * helper routines.  Will in practice be an array of three of these:
  2989.  * 0) Current line, 1) Next line, 2) Source file info.
  2990.  */
  2991. struct line_debug_entry
  2992. {
  2993.   int line;
  2994.   char *filename;
  2995.   struct nlist *sym;
  2996. };
  2997.  
  2998. void qsort ();
  2999.  
  3000. struct line_debug_entry *init_debug_scan ();
  3001. int next_debug_entry ();
  3002. int address_to_line ();
  3003. int relocation_entries_relation ();
  3004.  
  3005. /* Print on OUTFILE a list of all warnings generated by references
  3006.    and/or definitions in the file ENTRY.  List source file and line
  3007.    number if possible, just the .o file if not. */
  3008.  
  3009. void
  3010. do_file_warnings (entry, outfile)
  3011.      struct file_entry *entry;
  3012.      FILE *outfile;
  3013. {
  3014.   struct relocation_info *txt_reloc, *data_reloc;
  3015.   struct line_debug_entry *state_pointer;
  3016.   register struct line_debug_entry *current, *next, *source;
  3017.   char *errfmt;                /* Assigned to generally */
  3018.                     /* static values; should not */
  3019.                     /* be written into */
  3020.   char *errmsg;                /* Assigned to malloc'd values */
  3021.                     /* and copied into; should be */
  3022.                     /* freed when done */
  3023.   int invalidate_line_number;
  3024.  
  3025.   /* Read in the files strings if they aren't available */
  3026.   if (!entry->strings)
  3027.     {
  3028.       int desc;
  3029.  
  3030.       entry->strings = (char *) alloca (entry->string_size);
  3031.       desc = file_open (entry);
  3032.       read_entry_strings (desc, entry);
  3033.     }
  3034.  
  3035.   state_pointer = init_debug_scan (0, entry);
  3036.   current = state_pointer;
  3037.   next = state_pointer + 1;
  3038.   source = state_pointer + 2;
  3039.  
  3040.   read_file_relocation (entry);
  3041.  
  3042.   /* We need to sort the relocation info here.  Sheesh, so much effort
  3043.      for one lousy error optimization. */
  3044.  
  3045.   qsort (entry->textrel,
  3046.      entry->header.a_trsize/sizeof (struct relocation_info),
  3047.      sizeof (struct relocation_info),
  3048.      relocation_entries_relation);
  3049.  
  3050.   for (txt_reloc = entry->textrel;
  3051.        txt_reloc < (entry->textrel
  3052.             + entry->header.a_trsize/sizeof (struct relocation_info));
  3053.        txt_reloc++)
  3054.     {
  3055.       register struct nlist *s;
  3056.       register symbol *g;
  3057.       int s_index;
  3058.  
  3059.       /* If the relocation isn't resolved through a symbol, continue */
  3060.       if (!RELOC_EXTERN_P(txt_reloc))
  3061.     continue;
  3062.  
  3063.       s_index = RELOC_SYMBOL(txt_reloc);
  3064.       if (s_index < 0 )
  3065.     fatal_with_file ("bad symbol in relocation table of ", entry);
  3066.       s = &entry->symbols[s_index];
  3067.  
  3068.       /* Local symbols shouldn't ever be used by relocation info, so
  3069.      the next should be safe.
  3070.      This is, of course, wrong.  References to local BSS symbols can be
  3071.      the targets of relocation info, and they can (must) be
  3072.      resolved through symbols.  However, these must be defined properly,
  3073.      (the compiler would have caught it otherwise), so we can
  3074.      ignore these cases.  */
  3075.       if (!(s->n_type & N_EXT))
  3076.     continue;
  3077.  
  3078.       g = (symbol *) s->n_un.n_name;
  3079.  
  3080.       if (!g->defined)                 /* Reference */
  3081.     {
  3082.       if (!list_unresolved_refs ||             /* Don't list any */
  3083.           g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3084.         continue;
  3085.  
  3086.       /* Undefined symbol which we should mention */
  3087.  
  3088.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3089.         {
  3090.           errfmt = "More undefined symbol %s refs follow";
  3091.           invalidate_line_number = 1;
  3092.         }
  3093.       else
  3094.         {
  3095.           errfmt = "Undefined symbol %s referenced from text";
  3096.           invalidate_line_number = 0;
  3097.         }
  3098.     }
  3099.       else                         /* Defined */
  3100.     {
  3101.       /* Potential symbol warning here */
  3102.       if (!g->warning) continue;
  3103.  
  3104.       errfmt = g->warning;
  3105.       invalidate_line_number = 0;
  3106.     }
  3107.     
  3108.  
  3109.       /* If errfmt == 0, errmsg has already been defined.  */
  3110.       if (errfmt != 0)
  3111.     {
  3112.       char *nm;
  3113.  
  3114.       if (demangler == NULL || (nm = (*demangler)(g->name)) == NULL)
  3115.         nm = g->name;
  3116.       errmsg = (char *) xmalloc (strlen (errfmt) + strlen (nm) + 1);
  3117.       sprintf (errmsg, errfmt, nm);
  3118.       if (nm != g->name)
  3119.         free (nm);
  3120.     }
  3121.  
  3122.       address_to_line ( (RELOC_ADDRESS (txt_reloc)
  3123.              + entry->text_start_address),
  3124.                state_pointer);
  3125.  
  3126.       if (current->line >=0)
  3127.     fprintf (outfile, "%s:%d: %s\n", current->filename,
  3128.          invalidate_line_number ? 0 : current->line, errmsg);
  3129.       else
  3130.     fprintf (outfile, "%s: %s\n", current->filename, errmsg);
  3131.  
  3132.       free (errmsg);
  3133.     }
  3134.  
  3135.   free (state_pointer);
  3136.   state_pointer = init_debug_scan (1, entry);
  3137.   current = state_pointer;
  3138.   next = state_pointer + 1;
  3139.   source = state_pointer + 2;
  3140.  
  3141.   /*
  3142.    * Once again, time to sort the relocation info.
  3143.    */
  3144.  
  3145.   qsort (entry->datarel,
  3146.      entry->header.a_drsize/sizeof (struct relocation_info),
  3147.      sizeof (struct relocation_info),
  3148.      relocation_entries_relation);
  3149.  
  3150.   for (data_reloc = entry->datarel;
  3151.        data_reloc < (entry->datarel
  3152.              + entry->header.a_drsize/sizeof (struct relocation_info));
  3153.        data_reloc++)
  3154.     {
  3155.       register struct nlist *s;
  3156.       register symbol *g;
  3157.       int s_index;
  3158.       
  3159.       /* If the relocation isn't resolved through a symbol, continue */
  3160.       if (!RELOC_EXTERN_P(data_reloc))
  3161.     continue;
  3162.  
  3163.       s_index = RELOC_SYMBOL(data_reloc);
  3164.       if (s_index < 0 )
  3165.     fatal_with_file ("bad symbol in relocation table of ", entry);
  3166.       s = &entry->symbols[s_index];
  3167.  
  3168.       g = (symbol *) s->n_un.n_name;
  3169.  
  3170.       if (!g->defined)                 /* Reference */
  3171.     {
  3172.       if (!list_unresolved_refs ||             /* Don't list any */
  3173.           g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3174.         continue;
  3175.  
  3176.       /* Undefined symbol which we should mention */
  3177.  
  3178.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3179.         {
  3180.           errfmt = "More undefined symbol %s refs follow";
  3181.           invalidate_line_number = 1;
  3182.         }
  3183.       else
  3184.         {
  3185.           errfmt = "Undefined symbol %s referenced from data";
  3186.           invalidate_line_number = 0;
  3187.         }
  3188.     }
  3189.       else                         /* Defined */
  3190.     {
  3191.       /* Potential symbol warning here */
  3192.       if (!g->warning) continue;
  3193.  
  3194.       errfmt = g->warning;
  3195.       invalidate_line_number = 0;
  3196.     }
  3197.       
  3198.       errmsg = (char *) xmalloc (strlen (errfmt) + strlen (g->name) + 1);
  3199.       sprintf(errmsg, errfmt, g->name);
  3200.       address_to_line ( (RELOC_ADDRESS (data_reloc)
  3201.              + entry->text_start_address),
  3202.                state_pointer);
  3203.  
  3204.       if (current->line >=0)
  3205.     fprintf (outfile, "%s:%d: %s\n", current->filename,
  3206.          invalidate_line_number ? 0 : current->line, errmsg);
  3207.       else
  3208.     fprintf (outfile, "%s: %s\n", current->filename, errmsg);
  3209.  
  3210.       free (errmsg);
  3211.     }
  3212.  
  3213.   /* now scan in the non-tex/data sections for undefs */
  3214.   {  
  3215.       struct nlist *s,
  3216.       *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  3217.       symbol *g;
  3218.       
  3219.       for (s = entry->symbols; s < end; s++)
  3220.       {
  3221.           if (!(s->n_type & N_EXT))
  3222.               continue;
  3223.  
  3224.           g = (symbol *) s->n_un.n_name;
  3225.  
  3226.           if(g->defined)
  3227.               continue;
  3228.  
  3229.           if (g->referenced && (g->undef_refs == 0))
  3230.           {
  3231.               char *nm = NULL;
  3232.               if(demangler)
  3233.                   nm = (*demangler)(g->name);
  3234.               if(nm == NULL)
  3235.                   nm = g->name;
  3236.               print_file_name (entry, outfile);
  3237.               fprintf (outfile, ": Undefined symbol \"%s\"\n", nm);
  3238.               if(nm != g->name) free(nm);
  3239.           }
  3240.       }
  3241.   }
  3242.  
  3243.   entry->strings = 0;
  3244. }
  3245. /*
  3246.  * Helper routines for do_file_warnings.
  3247.  */
  3248.  
  3249. /*
  3250.  * Return an integer less than, equal to, or greater than 0 as per the
  3251.  * relation between the two relocation entries.
  3252.  * Used by qsort.
  3253.  */
  3254. int
  3255. relocation_entries_relation (rel1, rel2)
  3256.      struct relocation_info *rel1, *rel2;
  3257. {
  3258.   return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
  3259. }
  3260.  
  3261. /*
  3262.  * Takes the values in state_pointer and moves onward to the next
  3263.  * debug line symbol.  It assumes that state_pointer[1] is valid; ie
  3264.  * that it.sym points into some entry in the symbol table.  If
  3265.  * state_pointer[1].sym == 0, this routine should not be called.
  3266.  */
  3267.  
  3268. int
  3269. next_debug_entry (use_data_symbols, state_pointer)
  3270.      register int use_data_symbols;
  3271.      struct line_debug_entry state_pointer[3]; /* Must be passed by reference! */
  3272. {
  3273.   register struct line_debug_entry
  3274.     *current = state_pointer,
  3275.     *next = state_pointer + 1,
  3276.     *source = state_pointer + 2; /* Used to store source file */
  3277.   struct file_entry *entry = (struct file_entry *) source->sym;
  3278.  
  3279.   current->sym = next->sym;
  3280.   current->line = next->line;
  3281.   current->filename = next->filename;
  3282.  
  3283.   while (++(next->sym) < (entry->symbols
  3284.               + entry->header.a_syms/sizeof (struct nlist)))
  3285.     {
  3286.       switch (next->sym->n_type)
  3287.     {
  3288.     case N_SLINE:
  3289.       if (use_data_symbols) continue;
  3290.       next->line = next->sym->n_desc;
  3291.       return 1;
  3292.     case N_DSLINE:
  3293.       if (!use_data_symbols) continue;
  3294.       next->line = next->sym->n_desc;
  3295.       return 1;
  3296. #ifdef HAVE_SUN_STABS
  3297.     case N_EINCL:
  3298.       next->filename = source->filename;
  3299.       continue;
  3300. #endif
  3301.     case N_SO:
  3302.       source->filename = next->sym->n_un.n_strx + entry->strings;
  3303.       source->line++;
  3304. #ifdef HAVE_SUN_STABS
  3305.     case N_BINCL:
  3306. #endif
  3307.     case N_SOL:
  3308.       next->filename =
  3309.         next->sym->n_un.n_strx + entry->strings;
  3310.     default:
  3311.       continue;
  3312.     }
  3313.     }
  3314.   next->sym = (struct nlist *) 0;
  3315.   return 0;
  3316. }
  3317.  
  3318. int
  3319. address_to_line (address, state_pointer)
  3320.      unsigned long address;
  3321.      /* Next must be passed by reference! */
  3322.      struct line_debug_entry state_pointer[3];
  3323. {
  3324.   struct line_debug_entry
  3325.     *current = state_pointer,
  3326.     *next = state_pointer + 1;
  3327.   struct line_debug_entry *tmp_pointer;
  3328.  
  3329.   int use_data_symbols;
  3330.  
  3331.   if (next->sym)
  3332.     use_data_symbols = (next->sym->n_type & ~N_EXT) == N_DATA;
  3333.   else
  3334.     return current->line;
  3335.  
  3336.   /* Go back to the beginning if we've already passed it.  */
  3337.   if (current->sym->n_value > address)
  3338.     {
  3339.       tmp_pointer = init_debug_scan (use_data_symbols,
  3340.                      (struct file_entry *)
  3341.                      ((state_pointer + 2)->sym));
  3342.       state_pointer[0] = tmp_pointer[0];
  3343.       state_pointer[1] = tmp_pointer[1];
  3344.       state_pointer[2] = tmp_pointer[2];
  3345.       free (tmp_pointer);
  3346.     }
  3347.  
  3348.   /* If we're still in a bad way, return -1, meaning invalid line.  */
  3349.   if (current->sym->n_value > address)
  3350.     return -1;
  3351.  
  3352.   while (next->sym
  3353.      && next->sym->n_value <= address
  3354.      && next_debug_entry (use_data_symbols, state_pointer))
  3355.     ;
  3356.   return current->line;
  3357. }
  3358.  
  3359. struct line_debug_entry *
  3360. init_debug_scan (use_data_symbols, entry)
  3361.      int use_data_symbols;
  3362.      struct file_entry *entry;
  3363. {
  3364.   struct line_debug_entry
  3365.     *state_pointer =
  3366.       (struct line_debug_entry *) xmalloc (3 * sizeof (struct line_debug_entry));
  3367.   register struct line_debug_entry
  3368.     *current = state_pointer,
  3369.     *next = state_pointer + 1,
  3370.     *source = state_pointer + 2; /* Used to store source file */
  3371.  
  3372.   struct nlist *tmp;
  3373.  
  3374.   for (tmp = entry->symbols;
  3375.        tmp < (entry->symbols
  3376.           + entry->header.a_syms/sizeof (struct nlist));
  3377.        tmp++)
  3378.     if (tmp->n_type == (int) N_SO) break;
  3379.  
  3380.   if (tmp >= (entry->symbols
  3381.           + entry->header.a_syms/sizeof (struct nlist)))
  3382.     {
  3383.       /* I believe this translates to "We lose" */
  3384.       current->filename = next->filename = entry->filename;
  3385.       current->line = next->line = -1;
  3386.       current->sym = next->sym = (struct nlist *) 0;
  3387.       return state_pointer;
  3388.     }
  3389.  
  3390.   next->line = source->line = 0;
  3391.   next->filename = source->filename
  3392.     = (tmp->n_un.n_strx + entry->strings);
  3393.   source->sym = (struct nlist *) entry;
  3394.   next->sym = tmp;
  3395.  
  3396.   next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
  3397.  
  3398.   if (!next->sym)        /* No line numbers for this section; */
  3399.                 /* setup output results as appropriate */
  3400.     {
  3401.       if (source->line)
  3402.     {
  3403.       current->filename = source->filename = entry->filename;
  3404.       current->line = -1;    /* Don't print lineno */
  3405.     }
  3406.       else
  3407.     {
  3408.       current->filename = source->filename;
  3409.       current->line = 0;
  3410.     }
  3411.       return state_pointer;
  3412.     }
  3413.  
  3414.  
  3415.   next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
  3416.  
  3417.   return state_pointer;
  3418. }
  3419.  
  3420. void 
  3421. mark_flagged_symbols (entry, outfile)
  3422.      struct file_entry *entry;
  3423.      FILE *outfile;
  3424. {
  3425.   struct nlist *p;
  3426.   
  3427.   if (!entry->warning) return;
  3428.  
  3429.   for (p = entry->symbols;
  3430.        p < entry->symbols + (entry->header.a_syms / sizeof(struct nlist));
  3431.        p++)
  3432.     {
  3433.       unsigned char type = p->n_type;
  3434.       struct glosym *sym;
  3435.       
  3436.      /* Ignore locals and references */
  3437.       if (!(type & N_EXT) || type == N_EXT) continue;
  3438.  
  3439.       sym = (struct glosym *) p->n_un.n_name;
  3440.       if (sym->referenced)
  3441.     ((struct glosym *) p->n_un.n_name)->warning = entry->warning;
  3442.     }
  3443. }
  3444.  
  3445. do_warnings (outfile)
  3446.      FILE *outfile;
  3447. {
  3448.   struct glosym **clrefs;
  3449.  
  3450.   list_unresolved_refs = !relocatable_output && undefined_global_sym_count;
  3451.   list_warning_symbols = warning_count;
  3452.   list_multple_defs = 0;        /* Not currently done here */
  3453.  
  3454.   if (!(list_unresolved_refs ||
  3455.     list_warning_symbols ||
  3456.     list_multple_defs      ))
  3457.     /* No need to run this routine */
  3458.     return;
  3459.  
  3460.   if (list_warning_symbols)
  3461.     each_full_file (mark_flagged_symbols, outfile);
  3462.  
  3463.   each_full_file (do_file_warnings, outfile);
  3464.  
  3465.   if (!relocatable_output)
  3466.     for (clrefs = cmdline_references;
  3467.      clrefs < cmdline_references + cl_refs_allocated && *clrefs;
  3468.      clrefs++)
  3469.       if ((*clrefs)->referenced && !(*clrefs)->defined)
  3470.     fprintf(stderr, "Error: Unresolved reference to symbol %s\n",
  3471.         (*clrefs)->name);
  3472.  
  3473.   if (entry_symbol && !entry_symbol->defined) 
  3474.     fprintf(stderr, "%s: error: Entry symbol `%s' never defined.\n",
  3475.         progname, entry_symbol->name);
  3476.   
  3477.   fprintf (outfile, "\n");
  3478.  
  3479.   if (list_unresolved_refs || list_multple_defs)
  3480.     make_executable = 0;
  3481. }
  3482.  
  3483. /* Print the files which have the definitions for a given symbol.
  3484.    FIRST_DEF is the first nlist entry which defines the symbol, and
  3485.    REST_OF_REFS is a chain of nlist entries which may or may not be
  3486.    definitions for this symbol, but which are all references for the
  3487.    symbol.
  3488.  
  3489.    We do the job in this clumsy fashion because of the state our data
  3490.    structures are in in the middle of digest_symbols (from which this
  3491.    is called). */
  3492.  
  3493. void
  3494. print_files_defining_symbol (first_def, rest_of_refs)
  3495.      struct nlist *first_def, *rest_of_refs;
  3496. {
  3497.   struct file_entry *holder;
  3498.   struct nlist *n_ptr;
  3499.  
  3500.   if (holder =
  3501.       (struct file_entry *) check_each_file (contains_symbol, first_def))
  3502.     {
  3503.       fprintf (stderr, " ");
  3504.       prline_file_name (holder, stderr);
  3505.     }
  3506.   else
  3507.     fatal ("internal: file not found containing nlist entry");
  3508.  
  3509.   for (n_ptr = rest_of_refs;
  3510.        n_ptr;
  3511.        n_ptr = (struct nlist *) n_ptr->n_un.n_name)
  3512.     if (n_ptr->n_type & ~N_EXT)
  3513.       if (holder =
  3514.       (struct file_entry *) check_each_file (contains_symbol, n_ptr))
  3515.     {
  3516.       fprintf (stderr, " ");
  3517.       prline_file_name (holder, stderr);
  3518.     }
  3519.       else
  3520.     fatal ("internal: file not found containing nlist entry");
  3521. }
  3522.  
  3523. /* Write the output file */
  3524.  
  3525. void
  3526. write_output ()
  3527. {
  3528.   struct stat statbuf;
  3529.   int filemode;
  3530.  
  3531.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  3532.   if (outdesc < 0) perror_name (output_filename);
  3533.  
  3534. #ifdef atarist
  3535.   if (stat (output_filename, &statbuf) < 0)
  3536. #else
  3537.   if (fstat (outdesc, &statbuf) < 0)
  3538. #endif
  3539.     perror_name (output_filename);
  3540.  
  3541.   filemode = statbuf.st_mode;
  3542.  
  3543. #ifndef atarist
  3544.   chmod (output_filename, filemode & ~0111);
  3545. #endif
  3546.  
  3547.   /* Output the a.out header.  */
  3548.   write_header ();
  3549.  
  3550.   /* for the atari, we only want the symbols */
  3551. #if !defined(ONLY_SYMBOLS)
  3552.   /* Output the text and data segments, relocating as we go.  */
  3553.   write_text ();
  3554.   write_data ();
  3555.  
  3556.   /* Output the merged relocation info, if requested with `-r'.  */
  3557.   if (relocatable_output)
  3558.     write_rel ();
  3559. #endif
  3560.  
  3561.   /* Output the symbol table (both globals and locals).  */
  3562.   write_syms ();
  3563.  
  3564.   /* Copy any GDB symbol segments from input files.  */
  3565.   write_symsegs ();
  3566.  
  3567.   close (outdesc);
  3568.  
  3569. #ifndef atarist
  3570.   chmod (output_filename, filemode | 0111);
  3571. #endif
  3572. }
  3573.  
  3574. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  3575.  
  3576. void
  3577. write_header ()
  3578. {
  3579.   outheader.a_info = magic;
  3580. #if defined(ONLY_SYMBOLS)
  3581.   outheader.a_text = 0;
  3582.   outheader.a_data = 0;
  3583.   outheader.a_bss = 0;
  3584. #else
  3585.   outheader.a_text = text_size;
  3586.   outheader.a_data = data_size;
  3587.   outheader.a_bss = bss_size;
  3588. #endif
  3589.   outheader.a_entry = (entry_symbol ? entry_symbol->value
  3590.                : text_start + entry_offset);
  3591. #ifdef COFF_ENCAPSULATE
  3592.   if (need_coff_header)
  3593.     {
  3594.       /* We are encapsulating BSD format within COFF format.  */
  3595.       struct coffscn *tp, *dp, *bp;
  3596.  
  3597.       tp = &coffheader.scns[0];
  3598.       dp = &coffheader.scns[1];
  3599.       bp = &coffheader.scns[2];
  3600.  
  3601.       strcpy (tp->s_name, ".text");
  3602.       tp->s_paddr = text_start;
  3603.       tp->s_vaddr = text_start;
  3604.       tp->s_size = text_size;
  3605.       tp->s_scnptr = sizeof (struct coffheader) + sizeof (struct exec);
  3606.       tp->s_relptr = 0;
  3607.       tp->s_lnnoptr = 0;
  3608.       tp->s_nreloc = 0;
  3609.       tp->s_nlnno = 0;
  3610.       tp->s_flags = 0x20;
  3611.       strcpy (dp->s_name, ".data");
  3612.       dp->s_paddr = data_start;
  3613.       dp->s_vaddr = data_start;
  3614.       dp->s_size = data_size;
  3615.       dp->s_scnptr = tp->s_scnptr + tp->s_size;
  3616.       dp->s_relptr = 0;
  3617.       dp->s_lnnoptr = 0;
  3618.       dp->s_nreloc = 0;
  3619.       dp->s_nlnno = 0;
  3620.       dp->s_flags = 0x40;
  3621.       strcpy (bp->s_name, ".bss");
  3622.       bp->s_paddr = dp->s_vaddr + dp->s_size;
  3623.       bp->s_vaddr = bp->s_paddr;
  3624.       bp->s_size = bss_size;
  3625.       bp->s_scnptr = 0;
  3626.       bp->s_relptr = 0;
  3627.       bp->s_lnnoptr = 0;
  3628.       bp->s_nreloc = 0;
  3629.       bp->s_nlnno = 0;
  3630.       bp->s_flags = 0x80;
  3631.  
  3632.       coffheader.f_magic = COFF_MAGIC;
  3633.       coffheader.f_nscns = 3;
  3634.       coffheader.f_timdat = 0;
  3635.       coffheader.f_symptr = 0;
  3636.       coffheader.f_nsyms = 0;
  3637.       coffheader.f_opthdr = 28;
  3638.       coffheader.f_flags = 0x103;
  3639.       /* aouthdr */
  3640.       coffheader.magic = ZMAGIC;
  3641.       coffheader.vstamp = 0;
  3642.       coffheader.tsize = tp->s_size;
  3643.       coffheader.dsize = dp->s_size;
  3644.       coffheader.bsize = bp->s_size;
  3645.       coffheader.entry = outheader.a_entry;
  3646.       coffheader.text_start = tp->s_vaddr;
  3647.       coffheader.data_start = dp->s_vaddr;
  3648.     }
  3649. #endif
  3650.  
  3651. #if (!(defined(CROSSATARI) || defined(atarist) || defined(atariminix)))
  3652. #ifdef INITIALIZE_HEADER
  3653.   INITIALIZE_HEADER;
  3654. #endif
  3655. #endif
  3656.  
  3657.   if (strip_symbols == STRIP_ALL)
  3658.     nsyms = 0;
  3659.   else
  3660.     {
  3661.       nsyms = (defined_global_sym_count
  3662.            + undefined_global_sym_count);
  3663.       if (discard_locals == DISCARD_L)
  3664.     nsyms += non_L_local_sym_count;
  3665.       else if (discard_locals == DISCARD_NONE)
  3666.     nsyms += local_sym_count;
  3667.       /* One extra for following reference on indirects */
  3668.       if (relocatable_output)
  3669.     nsyms += set_symbol_count + global_indirect_count;
  3670. #if 0 /* DONT define this cause we dont emit symbols in the gnu format for
  3671.      setvectors when !-r
  3672.      defined(atarist) || defined(CROSSATARI) */
  3673.       nsyms += set_symbol_count;  /* Cos we dont output them */
  3674. #endif
  3675.     }
  3676.  
  3677.   if (strip_symbols == STRIP_NONE)
  3678.     nsyms += debugger_sym_count;
  3679.  
  3680. #ifdef WORD_ALIGNED
  3681.   outheader.a_syms = nsyms * (2 * sizeof(long) + 2 * sizeof(char)
  3682.                   + sizeof(short));
  3683. #else
  3684.   outheader.a_syms = nsyms * sizeof (struct nlist);
  3685. #endif
  3686.  
  3687.   if (relocatable_output)
  3688.     {
  3689.       outheader.a_trsize = text_reloc_size;
  3690.       outheader.a_drsize = data_reloc_size;
  3691.     }
  3692.   else
  3693.     {
  3694.       outheader.a_trsize = 0;
  3695.       outheader.a_drsize = 0;
  3696.     }
  3697.  
  3698. #ifdef COFF_ENCAPSULATE
  3699.   if (need_coff_header)
  3700.     mywrite (&coffheader, sizeof coffheader, 1, outdesc);
  3701. #endif
  3702.   mywrite (&outheader, sizeof (struct exec), 1, outdesc);
  3703.  
  3704.   /* Output whatever padding is required in the executable file
  3705.      between the header and the start of the text.  */
  3706.  
  3707. #ifndef COFF_ENCAPSULATE
  3708.   padfile (N_TXTOFF (outheader) - sizeof outheader, outdesc);
  3709. #endif
  3710. }
  3711.  
  3712. #if !defined(ONLY_SYMBOLS)
  3713. /* Relocate the text segment of each input file
  3714.    and write to the output file.  */
  3715.  
  3716. void
  3717. write_text ()
  3718. {
  3719.   if (trace_files)
  3720.     fprintf (stderr, "Copying and relocating text:\n\n");
  3721.  
  3722.   each_full_file (copy_text);
  3723.   file_close ();
  3724.  
  3725.   /* Write out the set element vectors */
  3726.  
  3727.   if (set_vector_count)
  3728.     mywrite (set_vectors, set_symbol_count + 2 * set_vector_count, sizeof (unsigned long), outdesc);
  3729.  
  3730.   if (trace_files)
  3731.     fprintf (stderr, "\n");
  3732.  
  3733.   padfile (text_pad, outdesc);
  3734. }
  3735. #endif /* !ONLY_SYMBOLS */
  3736.  
  3737. int
  3738. text_offset (entry)
  3739.      struct file_entry *entry;
  3740. {
  3741.   return entry->starting_offset + N_TXTOFF (entry->header);
  3742. }
  3743.  
  3744. /* Read in all of the relocation information */
  3745.  
  3746. void
  3747. read_relocation ()
  3748. {
  3749.   each_full_file (read_file_relocation);
  3750. }
  3751.  
  3752. /* Read in the relocation sections of ENTRY if necessary */
  3753.  
  3754. void
  3755. read_file_relocation (entry)
  3756.      struct file_entry *entry;
  3757. {
  3758.   register struct relocation_info *reloc;
  3759.   int desc;
  3760.   int read_return;
  3761.  
  3762.   desc = -1;
  3763.   if (!entry->textrel)
  3764.     {
  3765.       reloc = (struct relocation_info *) xmalloc (entry->header.a_trsize);
  3766.       desc = file_open (entry);
  3767.       lseek (desc,
  3768.          text_offset (entry) + entry->header.a_text + entry->header.a_data,
  3769.          L_SET);
  3770.       if (entry->header.a_trsize != (read_return = read (desc, reloc, entry->header.a_trsize)))
  3771.     {
  3772.       fprintf (stderr, "Return from read: %d\n", read_return);
  3773.       fatal_with_file ("premature eof in text relocatino of ", entry);
  3774.     }
  3775.       entry->textrel = reloc;
  3776.     }
  3777.  
  3778.   if (!entry->datarel)
  3779.     {
  3780.       reloc = (struct relocation_info *) xmalloc (entry->header.a_drsize);
  3781.       if (desc == -1) desc = file_open (entry);
  3782.       lseek (desc,
  3783.          text_offset (entry) + entry->header.a_text
  3784.          + entry->header.a_data + entry->header.a_trsize,
  3785.          L_SET);
  3786.       if (entry->header.a_drsize != read (desc, reloc, entry->header.a_drsize))
  3787.     fatal_with_file ("premature eof in text relocation of ", entry);
  3788.       entry->datarel = reloc;
  3789.     }
  3790. }
  3791.  
  3792. #if !defined(ONLY_SYMBOLS)
  3793.  
  3794. /* Read the text segment contents of ENTRY, relocate them,
  3795.    and write the result to the output file.
  3796.    If `-r', save the text relocation for later reuse.  */
  3797.  
  3798. void
  3799. copy_text (entry)
  3800.      struct file_entry *entry;
  3801. {
  3802.   register char *bytes;
  3803.   register int desc;
  3804.   register struct relocation_info *reloc;
  3805.  
  3806.   if (trace_files)
  3807.     prline_file_name (entry, stderr);
  3808.  
  3809.   desc = file_open (entry);
  3810.  
  3811.   /* Allocate space for the file's text section */
  3812.  
  3813.   bytes = (char *) alloca (entry->header.a_text);
  3814.  
  3815.   /* Deal with relocation information however is appropriate */
  3816.  
  3817.   if (entry->textrel)  reloc = entry->textrel;
  3818.   else if (relocatable_output)
  3819.     {
  3820.       read_file_relocation (entry);
  3821.       reloc = entry->textrel;
  3822.     }
  3823.   else
  3824.     {
  3825.       reloc = (struct relocation_info *) alloca (entry->header.a_trsize);
  3826.       lseek (desc, text_offset (entry) + entry->header.a_text + entry->header.a_data, 0);
  3827.       if (entry->header.a_trsize != read (desc, reloc, entry->header.a_trsize))
  3828.     fatal_with_file ("premature eof in text relocation of ", entry);
  3829.     }
  3830.  
  3831.   /* Read the text section into core.  */
  3832.  
  3833.   lseek (desc, text_offset (entry), 0);
  3834.   if (entry->header.a_text != read (desc, bytes, entry->header.a_text))
  3835.     fatal_with_file ("premature eof in text section of ", entry);
  3836.  
  3837.  
  3838.   /* Relocate the text according to the text relocation.  */
  3839.  
  3840.   perform_relocation (bytes, entry->text_start_address, entry->header.a_text,
  3841.               reloc, entry->header.a_trsize, entry);
  3842.  
  3843.   /* Write the relocated text to the output file.  */
  3844.  
  3845.   mywrite (bytes, 1, entry->header.a_text, outdesc);
  3846. }
  3847.  
  3848. /* Relocate the data segment of each input file
  3849.    and write to the output file.  */
  3850.  
  3851. void
  3852. write_data ()
  3853. {
  3854.   if (trace_files)
  3855.     fprintf (stderr, "Copying and relocating data:\n\n");
  3856.  
  3857.   each_full_file (copy_data);
  3858.   file_close ();
  3859.  
  3860.   if (trace_files)
  3861.     fprintf (stderr, "\n");
  3862.  
  3863.   padfile (data_pad, outdesc);
  3864. }
  3865.  
  3866. /* Read the data segment contents of ENTRY, relocate them,
  3867.    and write the result to the output file.
  3868.    If `-r', save the data relocation for later reuse.
  3869.    See comments in `copy_text'.  */
  3870.  
  3871. void
  3872. copy_data (entry)
  3873.      struct file_entry *entry;
  3874. {
  3875.   register struct relocation_info *reloc;
  3876.   register char *bytes;
  3877.   register int desc;
  3878.  
  3879.   if (trace_files)
  3880.     prline_file_name (entry, stderr);
  3881.  
  3882.   desc = file_open (entry);
  3883.  
  3884.   bytes = (char *) alloca (entry->header.a_data);
  3885.  
  3886.   if (entry->datarel) reloc = entry->datarel;
  3887.   else if (relocatable_output)    /* Will need this again */
  3888.     {
  3889.       read_file_relocation (entry);
  3890.       reloc = entry->datarel;
  3891.     }
  3892.   else
  3893.     {
  3894.       reloc = (struct relocation_info *) alloca (entry->header.a_drsize);
  3895.       lseek (desc, text_offset (entry) + entry->header.a_text
  3896.          + entry->header.a_data + entry->header.a_trsize,
  3897.          0);
  3898.       if (entry->header.a_drsize != read (desc, reloc, entry->header.a_drsize))
  3899.     fatal_with_file ("premature eof in data relocation of ", entry);
  3900.     }
  3901.  
  3902.   lseek (desc, text_offset (entry) + entry->header.a_text, 0);
  3903.   if (entry->header.a_data != read (desc, bytes, entry->header.a_data))
  3904.     fatal_with_file ("premature eof in data section of ", entry);
  3905.  
  3906.   perform_relocation (bytes, entry->data_start_address - entry->header.a_text,
  3907.               entry->header.a_data, reloc, entry->header.a_drsize, entry);
  3908.  
  3909.   mywrite (bytes, 1, entry->header.a_data, outdesc);
  3910. }
  3911.  
  3912. /* Relocate ENTRY's text or data section contents.
  3913.    DATA is the address of the contents, in core.
  3914.    DATA_SIZE is the length of the contents.
  3915.    PC_RELOCATION is the difference between the address of the contents
  3916.      in the output file and its address in the input file.
  3917.    RELOC_INFO is the address of the relocation info, in core.
  3918.    RELOC_SIZE is its length in bytes.  */
  3919. /* This version is about to be severley hacked by Randy.  Hope it
  3920.    works afterwards. */
  3921. void
  3922. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  3923.      char *data;
  3924.      struct relocation_info *reloc_info;
  3925.      struct file_entry *entry;
  3926.      int pc_relocation;
  3927.      int data_size;
  3928.      int reloc_size;
  3929. {
  3930.   register struct relocation_info *p = reloc_info;
  3931.   struct relocation_info *end
  3932.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  3933.   int text_relocation = entry->text_start_address;
  3934.   int data_relocation = entry->data_start_address - entry->header.a_text;
  3935.   int bss_relocation
  3936.     = entry->bss_start_address - entry->header.a_text - entry->header.a_data;
  3937.  
  3938.   for (; p < end; p++)
  3939.     {
  3940.       register int relocation = 0;
  3941.       register int addr = RELOC_ADDRESS(p);
  3942.       register unsigned int mask = 0;
  3943.  
  3944.       if (addr >= data_size)
  3945.     fatal_with_file ("relocation address out of range in ", entry);
  3946.  
  3947.       if (RELOC_EXTERN_P(p))
  3948.     {
  3949.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  3950.       symbol *sp = ((symbol *)
  3951.             (((struct nlist *)
  3952.               (((char *)entry->symbols) + symindex))
  3953.              ->n_un.n_name));
  3954.  
  3955. #ifdef N_INDR
  3956.       /* Resolve indirection */
  3957.       if ((sp->defined & ~N_EXT) == N_INDR)
  3958.         sp = (symbol *) sp->value;
  3959. #endif
  3960.  
  3961.       if (symindex >= entry->header.a_syms)
  3962.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  3963.  
  3964.       /* If the symbol is undefined, leave it at zero.  */
  3965.       if (! sp->defined)
  3966.         relocation = 0;
  3967.       else
  3968.         relocation = sp->value;
  3969.     }
  3970.       else switch (RELOC_TYPE(p))
  3971.     {
  3972.     case N_TEXT:
  3973.     case N_TEXT | N_EXT:
  3974.       relocation = text_relocation;
  3975.       break;
  3976.  
  3977.     case N_DATA:
  3978.     case N_DATA | N_EXT:
  3979.       /* A word that points to beginning of the the data section
  3980.          initially contains not 0 but rather the "address" of that section
  3981.          in the input file, which is the length of the file's text.  */
  3982.       relocation = data_relocation;
  3983.       break;
  3984.  
  3985.     case N_BSS:
  3986.     case N_BSS | N_EXT:
  3987.       /* Similarly, an input word pointing to the beginning of the bss
  3988.          initially contains the length of text plus data of the file.  */
  3989.       relocation = bss_relocation;
  3990.       break;
  3991.  
  3992.     case N_ABS:
  3993.     case N_ABS | N_EXT:
  3994.       /* Don't know why this code would occur, but apparently it does.  */
  3995.       break;
  3996.  
  3997.     default:
  3998.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  3999.     }
  4000.  
  4001.       if (RELOC_PCREL_P(p))
  4002.     relocation -= pc_relocation;
  4003.  
  4004. #ifdef RELOC_ADD_EXTRA
  4005.       relocation += RELOC_ADD_EXTRA(p);
  4006. #endif
  4007.  
  4008.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  4009.  
  4010.       /* Unshifted mask for relocation */
  4011.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  4012.       mask |= mask - 1;
  4013.       relocation &= mask;
  4014.  
  4015.       /* Shift everything up to where it's going to be used */
  4016.       relocation <<= RELOC_TARGET_BITPOS(p);
  4017.       mask <<= RELOC_TARGET_BITPOS(p);
  4018.  
  4019.       switch (RELOC_TARGET_SIZE(p))
  4020.     {
  4021.     case 0:
  4022.       if (RELOC_MEMORY_ADD_P(p))
  4023.         relocation += mask & *(char *) (data + addr);
  4024.       *(char *) (data + addr) &= ~mask;
  4025.       *(char *) (data + addr) |= relocation;
  4026.       break;
  4027.  
  4028.     case 1:
  4029.       if (RELOC_MEMORY_ADD_P(p))
  4030.         relocation += mask & *(short *) (data + addr);
  4031.       *(short *) (data + addr) &= ~mask;
  4032.       *(short *) (data + addr) |= relocation;
  4033.       break;
  4034.  
  4035.     case 2:
  4036. #ifndef WORD_ALIGNED
  4037.       if (RELOC_MEMORY_ADD_P(p))
  4038.         relocation += mask & *(long *) (data + addr);
  4039.       *(long *) (data + addr) &= ~mask;
  4040.       *(long *) (data + addr) |= relocation;
  4041. #else
  4042.       {
  4043.       register unsigned long word = 0;
  4044.  
  4045.       word |= (unsigned char)(data[addr]) << 24;
  4046.       word |= (unsigned char)(data[addr+1]) << 16;
  4047.       word |= (unsigned char)(data[addr+2]) << 8;
  4048.       word |= (unsigned char)(data[addr+3]);
  4049.  
  4050.       if (RELOC_MEMORY_ADD_P(p))
  4051.         relocation += mask & word;
  4052.       word &= ~mask;
  4053.       word |= relocation;
  4054.       data[addr] = word >> 24;
  4055.       data[addr+1] = (word >> 16) & 0xff;
  4056.       data[addr+2] = (word >> 8) & 0xff;
  4057.       data[addr+3] = word & 0xff;
  4058.       }
  4059. #endif
  4060.       break;
  4061.  
  4062.     default:
  4063.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  4064.     }
  4065.     }
  4066. }
  4067.  
  4068. /* For relocatable_output only: write out the relocation,
  4069.    relocating the addresses-to-be-relocated.  */
  4070.  
  4071. void coptxtrel (), copdatrel ();
  4072.  
  4073. void
  4074. write_rel ()
  4075. {
  4076.   register int i;
  4077.   register int count = 0;
  4078.  
  4079.   if (trace_files)
  4080.     fprintf (stderr, "Writing text relocation:\n\n");
  4081.  
  4082.   /* Assign each global symbol a sequence number, giving the order
  4083.      in which `write_syms' will write it.
  4084.      This is so we can store the proper symbolnum fields
  4085.      in relocation entries we write.  */
  4086.  
  4087.   for (i = 0; i < TABSIZE; i++)
  4088.     {
  4089.       symbol *sp;
  4090.       for (sp = symtab[i]; sp; sp = sp->link)
  4091.     if (sp->referenced || sp->defined)
  4092.       sp->def_count = count++;
  4093.     }
  4094.   if (count != defined_global_sym_count + undefined_global_sym_count)
  4095.     fatal ("internal error");
  4096.  
  4097.   /* Write out the relocations of all files, remembered from copy_text.  */
  4098.  
  4099.   each_full_file (coptxtrel);
  4100.  
  4101.   if (trace_files)
  4102.     fprintf (stderr, "\nWriting data relocation:\n\n");
  4103.  
  4104.   each_full_file (copdatrel);
  4105.  
  4106.   if (trace_files)
  4107.     fprintf (stderr, "\n");
  4108. }
  4109.  
  4110. void
  4111. coptxtrel (entry)
  4112.      struct file_entry *entry;
  4113. {
  4114.   register struct relocation_info *p, *end;
  4115.   register int reloc = entry->text_start_address;
  4116.  
  4117.   p = entry->textrel;
  4118.   end = (struct relocation_info *) (entry->header.a_trsize + (char *) p);
  4119.   while (p < end)
  4120.     {
  4121.       RELOC_ADDRESS(p) += reloc;
  4122.       if (RELOC_EXTERN_P(p))
  4123.     {
  4124.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  4125.       symbol *symptr = ((symbol *)
  4126.                 (((struct nlist *)
  4127.                   (((char *)entry->symbols) + symindex))
  4128.                  ->n_un.n_name));
  4129.  
  4130.       if (symindex >= entry->header.a_syms)
  4131.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  4132.  
  4133.       /* If the symbol is now defined, change the external relocation
  4134.          to an internal one.  */
  4135.  
  4136.       if (symptr->defined)
  4137.         {
  4138.           RELOC_EXTERN_P(p) = 0;
  4139.           RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
  4140.         }
  4141.       else
  4142.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  4143.                  - defined_global_sym_count
  4144.                  - undefined_global_sym_count);
  4145.     }
  4146.       p++;
  4147.     }
  4148.   mywrite (entry->textrel, 1, entry->header.a_trsize, outdesc);
  4149. }
  4150.  
  4151. void
  4152. copdatrel (entry)
  4153.      struct file_entry *entry;
  4154. {
  4155.   register struct relocation_info *p, *end;
  4156.   /* Relocate the address of the relocation.
  4157.      Old address is relative to start of the input file's data section.
  4158.      New address is relative to start of the output file's data section.  */
  4159.   register int reloc = entry->data_start_address - text_size;
  4160.  
  4161.   p = entry->datarel;
  4162.   end = (struct relocation_info *) (entry->header.a_drsize + (char *) p);
  4163.   while (p < end)
  4164.     {
  4165.       RELOC_ADDRESS(p) += reloc;
  4166.       if (RELOC_EXTERN_P(p))
  4167.     {
  4168.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  4169.       symbol *symptr = ((symbol *)
  4170.                 (((struct nlist *)
  4171.                   (((char *)entry->symbols) + symindex))
  4172.                  ->n_un.n_name));
  4173.       int symtype = symptr->defined & ~N_EXT;
  4174.  
  4175.       if (symindex >= entry->header.a_syms)
  4176.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  4177.       if (force_common_definition
  4178.           || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
  4179.         {
  4180.           RELOC_EXTERN_P(p) = 0;
  4181.           RELOC_SYMBOL(p) = symtype;
  4182.         }
  4183.       else
  4184.         RELOC_SYMBOL(p)
  4185.           = (((symbol *)
  4186.           (((struct nlist *)
  4187.             (((char *)entry->symbols) + symindex))
  4188.            ->n_un.n_name))
  4189.          ->def_count
  4190.          + nsyms - defined_global_sym_count
  4191.          - undefined_global_sym_count);
  4192.     }
  4193.       p++;
  4194.     }
  4195.   mywrite (entry->datarel, 1, entry->header.a_drsize, outdesc);
  4196. }
  4197.  
  4198. #endif /* !ONLY_SYMBOLS */
  4199.  
  4200. void write_file_syms ();
  4201. void write_string_table ();
  4202.  
  4203. /* Offsets and current lengths of symbol and string tables in output file. */
  4204.  
  4205. int symbol_table_offset;
  4206. int symbol_table_len;
  4207.  
  4208. /* Address in output file where string table starts.  */
  4209. int string_table_offset;
  4210.  
  4211. /* Offset within string table
  4212.    where the strings in `strtab_vector' should be written.  */
  4213. int string_table_len;
  4214.  
  4215. /* Total size of string table strings allocated so far,
  4216.    including strings in `strtab_vector'.  */
  4217. int strtab_size;
  4218.  
  4219. /* Vector whose elements are strings to be added to the string table.  */
  4220. char **strtab_vector;
  4221.  
  4222. /* Vector whose elements are the lengths of those strings.  */
  4223. int *strtab_lens;
  4224.  
  4225. /* Index in `strtab_vector' at which the next string will be stored.  */
  4226. int strtab_index;
  4227.  
  4228. /* Add the string NAME to the output file string table.
  4229.    Record it in `strtab_vector' to be output later.
  4230.    Return the index within the string table that this string will have.  */
  4231.  
  4232. int
  4233. assign_string_table_index (name)
  4234.      char *name;
  4235. {
  4236.   register int index = strtab_size;
  4237.   register int len = strlen (name) + 1;
  4238.  
  4239.   strtab_size += len;
  4240.   strtab_vector[strtab_index] = name;
  4241.   strtab_lens[strtab_index++] = len;
  4242.  
  4243.   return index;
  4244. }
  4245.  
  4246. FILE *outstream = (FILE *) 0;
  4247.  
  4248. /* Write the contents of `strtab_vector' into the string table.
  4249.    This is done once for each file's local&debugger symbols
  4250.    and once for the global symbols.  */
  4251.  
  4252. void
  4253. write_string_table ()
  4254. {
  4255.   register int i;
  4256.  
  4257.   lseek (outdesc, string_table_offset + string_table_len, 0);
  4258.  
  4259.   if (!outstream)
  4260. #ifdef atarist
  4261.     outstream = fdopen (outdesc, "wb");
  4262. #else
  4263.     outstream = fdopen (outdesc, "w");
  4264. #endif
  4265.  
  4266.   for (i = 0; i < strtab_index; i++)
  4267.     {
  4268.       fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
  4269.       string_table_len += strtab_lens[i];
  4270.     }
  4271.  
  4272.   fflush (outstream);
  4273.  
  4274.   /* Report I/O error such as disk full.  */
  4275.   if (ferror (outstream))
  4276.     perror_name (output_filename);
  4277. }
  4278.  
  4279. /* Write the symbol table and string table of the output file.  */
  4280.  
  4281. void
  4282. write_syms ()
  4283. {
  4284.   /* Number of symbols written so far.  */
  4285.   int syms_written = 0;
  4286.   register int i;
  4287.   register symbol *sp;
  4288.  
  4289.   /* Buffer big enough for all the global symbols.  One
  4290.      extra struct for each indirect symbol to hold the extra reference
  4291.      following. */
  4292.   struct nlist *buf
  4293.     = (struct nlist *) alloca ((defined_global_sym_count
  4294.                 + undefined_global_sym_count
  4295.                 + global_indirect_count)
  4296.                    * sizeof (struct nlist));
  4297.   /* Pointer for storing into BUF.  */
  4298.   register struct nlist *bufp = buf;
  4299.  
  4300.   /* Size of string table includes the bytes that store the size.  */
  4301.   strtab_size = sizeof strtab_size;
  4302.  
  4303.   symbol_table_offset = N_SYMOFF (outheader);
  4304.   symbol_table_len = 0;
  4305.   string_table_offset = N_STROFF (outheader);
  4306.   string_table_len = strtab_size;
  4307.  
  4308.   if (strip_symbols == STRIP_ALL)
  4309.     return;
  4310.  
  4311.   /* Write the local symbols defined by the various files.  */
  4312.  
  4313.   each_file (write_file_syms, &syms_written);
  4314.   file_close ();
  4315.  
  4316.   /* Now write out the global symbols.  */
  4317.  
  4318.   /* Allocate two vectors that record the data to generate the string
  4319.      table from the global symbols written so far.  This must include
  4320.      extra space for the references following indirect outputs. */
  4321.  
  4322.   strtab_vector = (char **) alloca ((num_hash_tab_syms
  4323.                      + global_indirect_count) * sizeof (char *));
  4324.   strtab_lens = (int *) alloca ((num_hash_tab_syms
  4325.                  + global_indirect_count) * sizeof (int));
  4326.   strtab_index = 0;
  4327.  
  4328.   /* Scan the symbol hash table, bucket by bucket.  */
  4329.  
  4330.   for (i = 0; i < TABSIZE; i++)
  4331.     for (sp = symtab[i]; sp; sp = sp->link)
  4332.       {
  4333.     struct nlist nl;
  4334.  
  4335.     nl.n_other = 0;
  4336.     nl.n_desc = 0;
  4337.  
  4338.     /* Compute a `struct nlist' for the symbol.  */
  4339.  
  4340.     if (sp->defined || sp->referenced)
  4341.       {
  4342.         /* common condition needs to be before undefined condition */
  4343.         /* because unallocated commons are set undefined in */
  4344.         /* digest_symbols */
  4345.         if (sp->defined > 1) /* defined with known type */
  4346.           {
  4347.         /* If the target of an indirect symbol has been
  4348.            defined and we are outputting an executable,
  4349.            resolve the indirection; it's no longer needed */
  4350.         if (!relocatable_output
  4351.             && ((sp->defined & ~N_EXT) == N_INDR)
  4352.             && (((symbol *) sp->value)->defined > 1))
  4353.           {
  4354.             symbol *newsp = (symbol *) sp->value;
  4355.             nl.n_type = newsp->defined;
  4356.             nl.n_value = newsp->value;
  4357.           }
  4358.         else
  4359.           {
  4360.             nl.n_type = sp->defined;
  4361.             if (sp->defined != (N_INDR | N_EXT))
  4362.               nl.n_value = sp->value;
  4363.             else
  4364.               nl.n_value = 0;
  4365.           }
  4366.           }
  4367.         else if (sp->max_common_size) /* defined as common but not allocated. */
  4368.           {
  4369.         /* happens only with -r and not -d */
  4370.         /* write out a common definition */
  4371.         nl.n_type = N_UNDF | N_EXT;
  4372.         nl.n_value = sp->max_common_size;
  4373.           }
  4374.         else if (!sp->defined)          /* undefined -- legit only if -r */
  4375.           {
  4376.         nl.n_type = N_UNDF | N_EXT;
  4377.         nl.n_value = 0;
  4378.           }
  4379.         else
  4380.           fatal ("internal error: %s defined in mysterious way", sp->name);
  4381.  
  4382.         /* Allocate string table space for the symbol name.  */
  4383.  
  4384.         nl.n_un.n_strx = assign_string_table_index (sp->name);
  4385.  
  4386.         /* Output to the buffer and count it.  */
  4387.  
  4388.         *bufp++ = nl;
  4389.         syms_written++;
  4390.         if (nl.n_type == (N_INDR | N_EXT))
  4391.           {
  4392.         struct nlist xtra_ref;
  4393.         xtra_ref.n_type = N_EXT | N_UNDF;
  4394.         xtra_ref.n_un.n_strx =
  4395.           assign_string_table_index (((symbol *) sp->value)->name);
  4396.         xtra_ref.n_other = 0;
  4397.         xtra_ref.n_desc = 0;
  4398.         xtra_ref.n_value = 0;
  4399.         *bufp++ = xtra_ref;
  4400.         syms_written++;
  4401.           }
  4402.       }
  4403.       }
  4404.  
  4405.   /* Output the buffer full of `struct nlist's.  */
  4406.  
  4407.   lseek (outdesc, symbol_table_offset + symbol_table_len, 0);
  4408. #ifdef WORD_ALIGNED
  4409.   {
  4410.     struct nlist *bp;
  4411.     
  4412.     for(bp = buf; bp < bufp; bp++)
  4413.     {
  4414.     mywrite(&(bp->n_un.n_strx), sizeof(long), 1, outdesc);
  4415.     mywrite(&(bp->n_type), sizeof(short), 1, outdesc); /* align to short */
  4416.     mywrite(&(bp->n_other), sizeof(short), 1, outdesc); /* align to short */
  4417.     mywrite(&(bp->n_value), sizeof(long), 1, outdesc);
  4418.     }
  4419.   }
  4420. #else
  4421.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  4422. #endif
  4423.   symbol_table_len += sizeof (struct nlist) * (bufp - buf);
  4424.  
  4425.   if (syms_written != nsyms)
  4426.     fatal ("internal error: wrong number of symbols written into output file", 0);
  4427.  
  4428.   if (symbol_table_offset + symbol_table_len != string_table_offset)
  4429.     fatal ("internal error: inconsistent symbol table length", 0);
  4430.  
  4431.   /* Now the total string table size is known, so write it.
  4432.      We are already positioned at the right place in the file.  */
  4433.  
  4434.   mywrite (&strtab_size, sizeof (int), 1, outdesc);  /* we're at right place */
  4435.  
  4436.   /* Write the strings for the global symbols.  */
  4437.  
  4438.   write_string_table ();
  4439. }
  4440.  
  4441. /* Write the local and debugger symbols of file ENTRY.
  4442.    Increment *SYMS_WRITTEN_ADDR for each symbol that is written.  */
  4443.  
  4444. /* Note that we do not combine identical names of local symbols.
  4445.    dbx or gdb would be confused if we did that.  */
  4446.  
  4447. void
  4448. write_file_syms (entry, syms_written_addr)
  4449.      struct file_entry *entry;
  4450.      int *syms_written_addr;
  4451. {
  4452.   register struct nlist *p = entry->symbols;
  4453.   register struct nlist *end = p + entry->header.a_syms / sizeof (struct nlist);
  4454.  
  4455.   /* Buffer to accumulate all the syms before writing them.
  4456.      It has one extra slot for the local symbol we generate here.  */
  4457.   struct nlist *buf
  4458.     = (struct nlist *) alloca (entry->header.a_syms + sizeof (struct nlist));
  4459.   register struct nlist *bufp = buf;
  4460.  
  4461.   /* Upper bound on number of syms to be written here.  */
  4462.   int max_syms = (entry->header.a_syms / sizeof (struct nlist)) + 1;
  4463.  
  4464.   /* Make tables that record, for each symbol, its name and its name's length.
  4465.      The elements are filled in by `assign_string_table_index'.  */
  4466.  
  4467.   strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  4468.   strtab_lens = (int *) alloca (max_syms * sizeof (int));
  4469.   strtab_index = 0;
  4470.  
  4471.   /* Generate a local symbol for the start of this file's text.  */
  4472.  
  4473.   if (discard_locals != DISCARD_ALL)
  4474.     {
  4475.       struct nlist nl;
  4476.  
  4477.       nl.n_type = N_TEXT;
  4478.       nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
  4479.       nl.n_value = entry->text_start_address;
  4480.       nl.n_desc = 0;
  4481.       nl.n_other = 0;
  4482.       *bufp++ = nl;
  4483.       (*syms_written_addr)++;
  4484.       entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
  4485.     }
  4486.  
  4487.   /* Read the file's string table.  */
  4488.  
  4489.   entry->strings = (char *) alloca (entry->string_size);
  4490.   read_entry_strings (file_open (entry), entry);
  4491.  
  4492.   for (; p < end; p++)
  4493.     {
  4494.       register int type = p->n_type;
  4495.       register int write = 0;
  4496.  
  4497.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  4498.  
  4499.  
  4500.       if (SET_ELEMENT_P (type))     /* This occurs even if global.  These */
  4501.                 /* types of symbols are never written */
  4502.                 /* globally, though they are stored */
  4503.                 /* globally.  */
  4504.         write = relocatable_output;
  4505.       else if (!(type & (N_STAB | N_EXT)))
  4506.         /* ordinary local symbol */
  4507.     write = ((discard_locals != DISCARD_ALL)
  4508.          && !(discard_locals == DISCARD_L &&
  4509.               (p->n_un.n_strx + entry->strings)[0] == 'L')
  4510.          && type != N_WARNING);
  4511.       else if (!(type & N_EXT))
  4512.     /* debugger symbol */
  4513.         write = (strip_symbols == STRIP_NONE);
  4514.  
  4515.       if (write)
  4516.     {
  4517.       /* If this symbol has a name,
  4518.          allocate space for it in the output string table.  */
  4519.  
  4520. /* #if 0                /* Following no longer true  */
  4521. #if 1 /* yes it is ++jrb */
  4522.       /* Sigh.  If this is a set element, it has been entered in */
  4523.       /* the global symbol table *and* is being output as a */
  4524.       /* local.  This means that p->n_un.n_strx has been */
  4525.       /* trashed.  */
  4526.       if (SET_ELEMENT_P (type))
  4527.         p->n_un.n_strx =
  4528.           assign_string_table_index (((symbol *) p->n_un.n_name)->name);
  4529.       else
  4530. #endif
  4531.       if (p->n_un.n_strx)
  4532.         p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
  4533.                             + entry->strings);
  4534.  
  4535.       /* Output this symbol to the buffer and count it.  */
  4536.  
  4537.       *bufp++ = *p;
  4538.       (*syms_written_addr)++;
  4539.     }
  4540.     }
  4541.  
  4542.   /* All the symbols are now in BUF; write them.  */
  4543.  
  4544.   lseek (outdesc, symbol_table_offset + symbol_table_len, 0);
  4545. #ifdef WORD_ALIGNED
  4546.   {
  4547.     struct nlist *bp;
  4548.     
  4549.     for(bp = buf; bp < bufp; bp++)
  4550.     {
  4551.     mywrite(&(bp->n_un.n_strx), sizeof(long), 1, outdesc);
  4552.     mywrite(&(bp->n_type), sizeof(short), 1, outdesc); /* align to short */
  4553.     mywrite(&(bp->n_other), sizeof(short), 1, outdesc); /* align to short */
  4554.     mywrite(&(bp->n_value), sizeof(long), 1, outdesc);
  4555.     }
  4556.   }
  4557. #else
  4558.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  4559. #endif
  4560.   symbol_table_len += sizeof (struct nlist) * (bufp - buf);
  4561.  
  4562.   /* Write the string-table data for the symbols just written,
  4563.      using the data in vectors `strtab_vector' and `strtab_lens'.  */
  4564.  
  4565.   write_string_table ();
  4566.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  4567. }
  4568.  
  4569. /* Copy any GDB symbol segments from the input files to the output file.
  4570.    The contents of the symbol segment is copied without change
  4571.    except that we store some information into the beginning of it.  */
  4572.  
  4573. void write_file_symseg ();
  4574.  
  4575. void
  4576. write_symsegs ()
  4577. {
  4578.   each_file (write_file_symseg, 0);
  4579. }
  4580.  
  4581. void
  4582. write_file_symseg (entry)
  4583.      struct file_entry *entry;
  4584. {
  4585.   char buffer[4096];
  4586.   struct symbol_root root;
  4587.   int indesc;
  4588.   int len;
  4589.  
  4590.   if (entry->symseg_offset == 0)
  4591.     return;
  4592.  
  4593.   /* This entry has a symbol segment.  Read the root of the segment.  */
  4594.  
  4595.   indesc = file_open (entry);
  4596.   lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  4597.   if (sizeof root != read (indesc, &root, sizeof root))
  4598.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  4599.  
  4600.   /* Store some relocation info into the root.  */
  4601.  
  4602.   root.ldsymoff = entry->local_syms_offset;
  4603.   root.textrel = entry->text_start_address;
  4604.   root.datarel = entry->data_start_address - entry->header.a_text;
  4605.   root.bssrel = entry->bss_start_address
  4606.     - entry->header.a_text - entry->header.a_data;
  4607.   root.databeg = entry->data_start_address - root.datarel;
  4608.   root.bssbeg = entry->bss_start_address - root.bssrel;
  4609.  
  4610.   /* Write the modified root into the output file.  */
  4611.  
  4612.   mywrite (&root, sizeof root, 1, outdesc);
  4613.  
  4614.   /* Copy the rest of the symbol segment unchanged.  */
  4615.  
  4616.   if (entry->superfile)
  4617.     {
  4618.       /* Library member: number of bytes to copy is determined
  4619.      from the member's total size.  */
  4620.  
  4621.       int total = entry->total_size - entry->symseg_offset - sizeof root;
  4622.  
  4623.       while (total > 0)
  4624.     {
  4625.       len = read (indesc, buffer, min (sizeof buffer, total));
  4626.  
  4627.       if (len != min (sizeof buffer, total))
  4628.         fatal_with_file ("premature end of file in symbol segment of ", entry);
  4629.       total -= len;
  4630.       mywrite (buffer, len, 1, outdesc);
  4631.     }
  4632.     }
  4633.   else
  4634.     {
  4635.       /* A separate file: copy until end of file.  */
  4636.  
  4637.       while (len = read (indesc, buffer, sizeof buffer))
  4638.     {
  4639.       mywrite (buffer, len, 1, outdesc);
  4640.       if (len < sizeof buffer)
  4641.         break;
  4642.     }
  4643.     }
  4644.  
  4645.   file_close ();
  4646. }
  4647.  
  4648. /* Create the symbol table entries for `etext', `edata' and `end'.  */
  4649.  
  4650. void
  4651. symtab_init ()
  4652. {
  4653. #ifndef nounderscore
  4654.   edata_symbol = getsym ("_edata");
  4655.   etext_symbol = getsym ("_etext");
  4656.   end_symbol = getsym ("_end");
  4657. #else
  4658.   edata_symbol = getsym ("edata");
  4659.   etext_symbol = getsym ("etext");
  4660.   end_symbol = getsym ("end");
  4661. #endif
  4662.  
  4663.   edata_symbol->defined = N_DATA | N_EXT;
  4664.   etext_symbol->defined = N_TEXT | N_EXT;
  4665.   end_symbol->defined = N_BSS | N_EXT;
  4666.  
  4667.   edata_symbol->referenced = 1;
  4668.   etext_symbol->referenced = 1;
  4669.   end_symbol->referenced = 1;
  4670. }
  4671.  
  4672. /* Compute the hash code for symbol name KEY.  */
  4673.  
  4674. int
  4675. hash_string (key)
  4676.      char *key;
  4677. {
  4678.   register char *cp;
  4679.   register int k;
  4680.  
  4681.   cp = key;
  4682.   k = 0;
  4683.   while (*cp)
  4684.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  4685.  
  4686.   return k;
  4687. }
  4688.  
  4689. /* Get the symbol table entry for the global symbol named KEY.
  4690.    Create one if there is none.  */
  4691.  
  4692. symbol *
  4693. getsym (key)
  4694.      char *key;
  4695. {
  4696.   register int hashval;
  4697.   register symbol *bp;
  4698.  
  4699.   /* Determine the proper bucket.  */
  4700.  
  4701.   hashval = hash_string (key) % TABSIZE;
  4702.  
  4703.   /* Search the bucket.  */
  4704.  
  4705.   for (bp = symtab[hashval]; bp; bp = bp->link)
  4706.     if (! strcmp (key, bp->name))
  4707.       return bp;
  4708.  
  4709.   /* Nothing was found; create a new symbol table entry.  */
  4710.  
  4711.   bp = (symbol *) xmalloc (sizeof (symbol));
  4712.   bp->refs = 0;
  4713.   bp->name = (char *) xmalloc (strlen (key) + 1);
  4714.   strcpy (bp->name, key);
  4715.   bp->defined = 0;
  4716.   bp->referenced = 0;
  4717.   bp->trace = 0;
  4718.   bp->value = 0;
  4719.   bp->max_common_size = 0;
  4720.   bp->warning = 0;
  4721.   bp->undef_refs = 0;
  4722.   bp->def_count = 0;
  4723.  
  4724.   /* Add the entry to the bucket.  */
  4725.  
  4726.   bp->link = symtab[hashval];
  4727.   symtab[hashval] = bp;
  4728.  
  4729.   ++num_hash_tab_syms;
  4730.  
  4731.   return bp;
  4732. }
  4733.  
  4734. /* Like `getsym' but return 0 if the symbol is not already known.  */
  4735.  
  4736. symbol *
  4737. getsym_soft (key)
  4738.      char *key;
  4739. {
  4740.   register int hashval;
  4741.   register symbol *bp;
  4742.  
  4743.   /* Determine which bucket.  */
  4744.  
  4745.   hashval = hash_string (key) % TABSIZE;
  4746.  
  4747.   /* Search the bucket.  */
  4748.  
  4749.   for (bp = symtab[hashval]; bp; bp = bp->link)
  4750.     if (! strcmp (key, bp->name))
  4751.       return bp;
  4752.  
  4753.   return 0;
  4754. }
  4755.  
  4756. /* Report a fatal error.
  4757.    STRING is a printf format string and ARG is one arg for it.  */
  4758.  
  4759. #if __STDC__
  4760. void
  4761. fatal (char *string, ...)
  4762. {
  4763.     va_list ap;
  4764.     
  4765.     va_start(ap, string);
  4766.     fprintf (stderr, "ld: ");
  4767.     vfprintf (stderr, string, ap);
  4768.     fprintf (stderr, "\n");
  4769.     va_end(ap);
  4770.     exit (1);
  4771. }
  4772. #else
  4773. void
  4774. fatal (va_alist)
  4775. va_dcl
  4776. {
  4777.     va_list ap;
  4778.     char *string;
  4779.  
  4780.     va_start(ap);
  4781.     string = va_arg(ap, char *);
  4782.     fprintf (stderr, "ld: ");
  4783.     vfprintf (stderr, string, ap);
  4784.     fprintf (stderr, "\n");
  4785.     va_end(ap);
  4786.     exit (1);
  4787. }
  4788. #endif
  4789.  
  4790.  
  4791. /* Report a fatal error.  The error message is STRING
  4792.    followed by the filename of ENTRY.  */
  4793.  
  4794. void
  4795. fatal_with_file (string, entry)
  4796.      char *string;
  4797.      struct file_entry *entry;
  4798. {
  4799.   fprintf (stderr, "ld: ");
  4800.   fprintf (stderr, string);
  4801.   print_file_name (entry, stderr);
  4802.   fprintf (stderr, "\n");
  4803.   exit (1);
  4804. }
  4805.  
  4806. /* Report a fatal error using the message for the last failed system call,
  4807.    followed by the string NAME.  */
  4808.  
  4809. void
  4810. perror_name (name)
  4811.      char *name;
  4812. {
  4813.   extern int errno, sys_nerr;
  4814.   extern char *sys_errlist[];
  4815.   char *s;
  4816.  
  4817.   if (errno < sys_nerr)
  4818.     s = concat ("", sys_errlist[errno], " for %s");
  4819.   else
  4820.     s = "cannot open %s";
  4821.   fatal (s, name);
  4822. }
  4823.  
  4824. /* Report a fatal error using the message for the last failed system call,
  4825.    followed by the name of file ENTRY.  */
  4826.  
  4827. void
  4828. perror_file (entry)
  4829.      struct file_entry *entry;
  4830. {
  4831.   extern int errno, sys_nerr;
  4832.   extern char *sys_errlist[];
  4833.   char *s;
  4834.  
  4835.   if (errno < sys_nerr)
  4836.     s = concat ("", sys_errlist[errno], " for ");
  4837.   else
  4838.     s = "cannot open ";
  4839.   fatal_with_file (s, entry);
  4840. }
  4841.  
  4842. /* Report a nonfatal error.
  4843.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  4844.  
  4845. void
  4846. error (string, arg1, arg2, arg3)
  4847.      char *string, *arg1, *arg2, *arg3;
  4848. {
  4849.   fprintf (stderr, "%s: ", progname);
  4850.   fprintf (stderr, string, arg1, arg2, arg3);
  4851.   fprintf (stderr, "\n");
  4852. }
  4853.  
  4854.  
  4855. /* Output COUNT*ELTSIZE bytes of data at BUF
  4856.    to the descriptor DESC.  */
  4857.  
  4858. void
  4859. mywrite (buf, count, eltsize, desc)
  4860.      char *buf;
  4861.      int count;
  4862.      int eltsize;
  4863.      int desc;
  4864. {
  4865.   register int val;
  4866.   register int bytes = count * eltsize;
  4867.  
  4868.   while (bytes > 0)
  4869.     {
  4870.       val = write (desc, buf, bytes);
  4871.       if (val <= 0)
  4872.     perror_name (output_filename);
  4873.       buf += val;
  4874.       bytes -= val;
  4875.     }
  4876. }
  4877.  
  4878. /* Output PADDING zero-bytes to descriptor OUTDESC.
  4879.    PADDING may be negative; in that case, do nothing.  */
  4880.  
  4881. void
  4882. padfile (padding, outdesc)
  4883.      int padding;
  4884.      int outdesc;
  4885. {
  4886.   register char *buf;
  4887.   if (padding <= 0)
  4888.     return;
  4889.  
  4890.   buf = (char *) alloca (padding);
  4891.   bzero (buf, padding);
  4892.   mywrite (buf, padding, 1, outdesc);
  4893. }
  4894.  
  4895. /* Return a newly-allocated string
  4896.    whose contents concatenate the strings S1, S2, S3.  */
  4897.  
  4898. char *
  4899. concat (s1, s2, s3)
  4900.      char *s1, *s2, *s3;
  4901. {
  4902.   register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  4903.   register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  4904.  
  4905.   strcpy (result, s1);
  4906.   strcpy (result + len1, s2);
  4907.   strcpy (result + len1 + len2, s3);
  4908.   result[len1 + len2 + len3] = 0;
  4909.  
  4910.   return result;
  4911. }
  4912.  
  4913. /* Parse the string ARG using scanf format FORMAT, and return the result.
  4914.    If it does not parse, report fatal error
  4915.    generating the error message using format string ERROR and ARG as arg.  */
  4916.  
  4917. int
  4918. parse (arg, format, error)
  4919.      char *arg, *format, *error;
  4920. {
  4921.   int x;
  4922.   if (1 != sscanf (arg, format, &x))
  4923.     fatal (error, arg);
  4924.   return x;
  4925. }
  4926.  
  4927. /* Like malloc but get fatal error if memory is exhausted.  */
  4928.  
  4929. int
  4930. xmalloc (size)
  4931.      int size;
  4932. {
  4933.   register int result = malloc (size);
  4934.   if (!result)
  4935.     fatal ("virtual memory exhausted", 0);
  4936.   return result;
  4937. }
  4938.  
  4939. /* Like realloc but get fatal error if memory is exhausted.  */
  4940.  
  4941. int
  4942. xrealloc (ptr, size)
  4943.      char *ptr;
  4944.      int size;
  4945. {
  4946.   register int result = realloc (ptr, size);
  4947.   if (!result)
  4948.     fatal ("virtual memory exhausted", 0);
  4949.   return result;
  4950. }
  4951.  
  4952. #ifdef USG
  4953.  
  4954. void
  4955. bzero (p, n)
  4956.      char *p;
  4957. {
  4958.   memset (p, 0, n);
  4959. }
  4960.  
  4961. void
  4962. bcopy (from, to, n)
  4963.      char *from, *to;
  4964. {
  4965.   memcpy (to, from, n);
  4966. }
  4967.  
  4968. #ifndef pyr
  4969. getpagesize ()
  4970. {
  4971.   return (4096);
  4972. }
  4973. #endif
  4974.  
  4975. #endif
  4976.