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