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