home *** CD-ROM | disk | FTP | other *** search
/ Frozen Fish 1: Amiga / FrozenFish-Apr94.iso / bbs / gnu / binutils-1.8.x.tar.gz / binutils-1.8.x.tar / binutils / ld.c < prev    next >
C/C++ Source or Header  |  1991-11-27  |  165KB  |  5,955 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. #include <ar.h>
  22. #include <stdio.h>
  23. #include <sys/types.h>
  24. #include <sys/stat.h>
  25. #include <sys/file.h>
  26. #ifndef USG
  27. #include <sys/time.h>
  28. #include <sys/resource.h>
  29. #endif
  30. #ifndef sony_news
  31. #include <fcntl.h>
  32. #endif
  33.  
  34. #if !defined(A_OUT) && !defined(MACH_O)
  35. #define A_OUT
  36. #endif
  37.  
  38. #ifdef A_OUT
  39. #ifdef COFF_ENCAPSULATE
  40. #include "a.out.encap.h"
  41. #else
  42. #include <a.out.h>
  43. #endif
  44. #endif
  45.  
  46. #ifdef MACH_O
  47. #ifndef A_OUT
  48. #include <nlist.h>
  49. #include <reloc.h>
  50. #endif
  51. #ifndef N_TEXT
  52. #define N_TEXT 0x04
  53. #define N_DATA 0x06
  54. #define N_BSS 0x08
  55. #endif
  56. #include <sys/loader.h>
  57. #endif
  58.  
  59. #ifndef N_SET_MAGIC
  60. #define N_SET_MAGIC(exec, val)  ((exec).a_magic = val)
  61. #endif
  62.  
  63. /* If compiled with GNU C, use the built-in alloca */
  64. #ifdef __GNUC__
  65. # define alloca __builtin_alloca
  66. #else
  67. # if defined(sun) && defined(sparc)
  68. #  include "alloca.h"
  69. # else
  70. char *alloca ();
  71. # endif
  72. #endif
  73.  
  74. #include "getopt.h"
  75.  
  76. /* Always use the GNU version of debugging symbol type codes, if possible.  */
  77.  
  78. #include "stab.h"
  79. #define CORE_ADDR unsigned long    /* For symseg.h */
  80. #include "symseg.h"
  81.  
  82. #ifdef USG
  83. #include <string.h>
  84. #else
  85. #include <strings.h>
  86. #endif
  87.  
  88. /* Determine whether we should attempt to handle (minimally)
  89.    N_BINCL and N_EINCL.  */
  90.  
  91. #if defined (__GNU_STAB__) || defined (N_BINCL)
  92. #define HAVE_SUN_STABS
  93. #endif
  94.  
  95. #define min(a,b) ((a) < (b) ? (a) : (b))
  96.  
  97. /* Macro to control the number of undefined references printed */
  98. #define MAX_UREFS_PRINTED    10
  99.  
  100. /* Size of a page; obtained from the operating system.  */
  101.  
  102. int page_size;
  103.  
  104. /* Name this program was invoked by.  */
  105.  
  106. char *progname;
  107.  
  108. /* System dependencies */
  109.  
  110. /* Define this if names etext, edata and end should not start with `_'.  */
  111. /* #define nounderscore 1 */
  112.  
  113. /* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
  114.    whose native format is different.  */
  115. /* #define NON_NATIVE */
  116.  
  117. /* Define this to specify the default executable format.  */
  118.  
  119. #ifdef hpux
  120. #define DEFAULT_OUTPUT_STYLE OUTPUT_READONLY_TEXT
  121. #endif
  122.  
  123. /* Ordinary 4.3bsd lacks these macros in a.out.h.  */
  124.  
  125. #ifndef N_TXTADDR
  126. #if defined(vax) || defined(sony_news) || defined(hp300) || defined(pyr)
  127. #define N_TXTADDR(X) 0
  128. #endif
  129. #ifdef is68k
  130. #define N_TXTADDR(x)  (sizeof (struct exec))
  131. #endif
  132. #ifdef sequent
  133. #define    N_TXTADDR(x) (N_ADDRADJ(x))
  134. #endif
  135. #ifdef NeXT
  136. #define N_TXTADDR(X) ((X).a_magic == ZMAGIC ? page_size : 0)
  137. #endif
  138. #endif
  139.  
  140. #ifndef N_DATADDR
  141. #if defined(vax) || defined(sony_news) || defined(hp300) || defined(pyr)
  142. #define N_DATADDR(x) \
  143.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  144.     : (page_size+((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  145. #endif
  146. #ifdef is68k
  147. #define SEGMENT_SIZE 0x20000
  148. #define N_DATADDR(x) \
  149.     (((x).a_magic==Omagic)? (N_TXTADDR(x)+(x).a_text) \
  150.      : (SEGMENT_SIZE + ((N_TXTADDR(x)+(x).a_text-1) & ~(SEGMENT_SIZE-1))))
  151. #endif
  152. #ifdef sequent
  153. #define N_DATADDR(x) \
  154.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  155.     : (page_size+(((x).a_text-1) & ~(page_size-1))))
  156. #endif
  157. #ifdef NeXT
  158. #define N_DATADDR(X) \
  159.     (((X).a_magic==ZMAGIC)?(N_TXTADDR(X)+(X).a_text+0xFFFF)&~0xFFFF \
  160.      :N_TXTADDR(X)+(X).a_text)
  161. #endif
  162. #endif
  163.  
  164. /* The "address" of the data segment in a relocatable file.
  165.    The text address of a relocatable file is always
  166.    considered to be zero (instead of the value of N_TXTADDR, which
  167.    is what the address is in an executable), so we need to subtract
  168.    N_TXTADDR from N_DATADDR to get the "address" for the input file.  */
  169. #define DATA_ADDR_DOT_O(hdr) (N_DATADDR(hdr) - N_TXTADDR(hdr))
  170.  
  171. /* Define how to initialize system-dependent header fields.  */
  172. #ifdef sun
  173. #ifdef sparc
  174. #define INITIALIZE_HEADER \
  175.   {outheader.a_machtype = M_SPARC; outheader.a_toolversion = 1;}
  176. #endif /* sparc.  */
  177. #if defined(mc68000)
  178. /* Set the machine type according to the machine type of the .o files.
  179.    If they are all sun2 (68010), then the type of the executable is sun2.
  180.    If any is sun3 (68020), then the type of the executable is sun3.
  181.    This is consistent with the Sun loader and more useful than having
  182.    it depend on which machine you are on when you run ld.  */
  183. static int sun_machtype = M_68010;
  184. #define INITIALIZE_HEADER outheader.a_machtype = sun_machtype
  185. #define READ_HEADER_HOOK(machtype) \
  186.   if (machtype == M_68020)           \
  187.     {                     \
  188.       sun_machtype = M_68020;         \
  189.     }
  190. #endif /* mc68000.  */
  191. #endif /* Sun.  */
  192.  
  193. #ifdef ALTOS
  194. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_68020)
  195. #endif
  196. #ifdef is68k
  197. #ifdef M_68020
  198. /* ISI rel 4.0D doesn't use it, and rel 3.05 doesn't have an
  199.    a_machtype field and so won't recognize the magic number.  To keep
  200.    binary compatibility for now, just ignore it */
  201. #define INITIALIZE_HEADER outheader.a_machtype = 0;
  202. #endif
  203. #endif
  204. #ifdef hpux
  205. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, HP9000S200_ID)
  206. #endif
  207. #if defined(i386) && !defined(sequent)
  208. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_386)
  209. #endif /* Sequent symmetry.  */
  210. #if defined(hp300)
  211. #define INITIALIZE_HEADER outheader.a_mid = MID_HP300
  212. #endif /* hp300.  */
  213. #ifdef pyr
  214. #define INITIALIZE_HEADER outheader.a_machid = PYR90X
  215. #endif /* Pyramid.  */
  216.  
  217. #ifdef is68k
  218. /* This enables code to take care of an ugly hack in the ISI OS.
  219.    If a symbol beings with _$, then the object file is included only
  220.    if the rest of the symbol name has been referenced. */
  221. #define DOLLAR_KLUDGE
  222. #endif
  223.  
  224. /* Values for 3rd argument to lseek().  */
  225. #ifndef L_SET
  226. #define L_SET 0
  227. #endif
  228. /* This is called L_INCR in BSD, but SEEK_CUR in POSIX.  */
  229. #ifndef SEEK_CUR
  230. #define SEEK_CUR 1
  231. #endif
  232.  
  233. /*
  234.  * Ok.  Following are the relocation information macros.  If your
  235.  * system cannot use the default set (below), you must define all of these:
  236.  
  237.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  238.  * of structure that is stored in the relocation info section of your
  239.  * a.out files.  Often this is defined in the a.out.h for your system.
  240.  *
  241.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  242.  * <whatever> to be relocated.  *Must be an lvalue*.
  243.  *
  244.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  245.  * external symbol (1), or was it fully resolved upon entering the
  246.  * loader (0) in which case some combination of the value in memory
  247.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  248.  * what the value of the relocation actually was.  *Must be an lvalue*.
  249.  *
  250.  *   RELOC_TYPE (rval): For a non-external relocation, this is the
  251.  * segment to relocate for.  *Must be an lvalue.*
  252.  *
  253.  *   RELOC_SYMBOL (rval): For an external relocation, this is the
  254.  * index of its symbol in the symbol table.  *Must be an lvalue*.
  255.  *
  256.  *   RELOC_MEMORY_ADD_P (rval): This should be 1 if the final
  257.  * relocation value output here should be added to memory; 0, if the
  258.  * section of memory described should simply be set to the relocation
  259.  * value.
  260.  *
  261.  *   RELOC_MEMORY_ADD_P (rval): If this is nonzero, the value previously
  262.  * present in the memory location to be relocated is *added*
  263.  * to the relocation value, to produce the final result.
  264.  * Otherwise, the relocation value is stored in the memory location
  265.  * and the value previously found there is ignored.
  266.  * By default, this is always 1.
  267.  *
  268.  *   RELOC_MEMORY_SUB_P (rval): If this is nonzero, the value previously
  269.  * present in the memory location to be relocated is *subtracted*
  270.  * from the relocation value, to produce the final result.
  271.  * By default, this is always 0.
  272.  *
  273.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  274.  * an extra value to be added to the relocation value based on the
  275.  * individual relocation entry.  *Must be an lvalue if defined*.
  276.  *
  277.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  278.  * pc relative.
  279.  *
  280.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  281.  * final relocation value before putting it where it belongs.
  282.  *
  283.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  284.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  285.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  286.  * do everything in terms of the bit operators below), but having this
  287.  * macro could end up producing better code on machines without fancy
  288.  * bit twiddling.  Also, it's easier to understand/code big/little
  289.  * endian distinctions with this macro.
  290.  *
  291.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  292.  * object described in RELOC_TARGET_SIZE in which the relocation value
  293.  * will go.
  294.  *
  295.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  296.  * with the bits of the relocation value.  It may be assumed by the
  297.  * code that the relocation value will fit into this many bits.  This
  298.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  299.  *
  300.  *
  301.  *        Things I haven't implemented
  302.  *        ----------------------------
  303.  *
  304.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  305.  *
  306.  *    Pc relative relocation for External references.
  307.  *
  308.  *
  309.  */
  310.  
  311. #if defined(sun) && defined(sparc)
  312. /* Sparc (Sun 4) macros */
  313. #undef relocation_info
  314. #define relocation_info                    reloc_info_sparc
  315. #define RELOC_ADDRESS(r)        ((r)->r_address)
  316. #define RELOC_EXTERN_P(r)               ((r)->r_extern)
  317. #define RELOC_TYPE(r)                   ((r)->r_index)
  318. #define RELOC_SYMBOL(r)                 ((r)->r_index)
  319. #define RELOC_MEMORY_SUB_P(r)        0
  320. #define RELOC_MEMORY_ADD_P(r)           0
  321. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)
  322. #define RELOC_PCREL_P(r)             \
  323.         ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22)
  324. #define RELOC_VALUE_RIGHTSHIFT(r)       (reloc_target_rightshift[(r)->r_type])
  325. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(r)->r_type])
  326. #define RELOC_TARGET_BITPOS(r)          0
  327. #define RELOC_TARGET_BITSIZE(r)         (reloc_target_bitsize[(r)->r_type])
  328.  
  329. /* Note that these are very dependent on the order of the enums in
  330.    enum reloc_type (in a.out.h); if they change the following must be
  331.    changed */
  332. /* Also note that the last few may be incorrect; I have no information */
  333. static int reloc_target_rightshift[] = {
  334.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  335. };
  336. static int reloc_target_size[] = {
  337.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  338. };
  339. static int reloc_target_bitsize[] = {
  340.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  341. };
  342.  
  343. #define    MAX_ALIGNMENT    (sizeof (double))
  344. #endif
  345.  
  346. #ifdef sequent
  347. #define RELOC_ADDRESS(r)        ((r)->r_address)
  348. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  349. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  350. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  351. #define RELOC_MEMORY_SUB_P(r)    ((r)->r_bsr)
  352. #define RELOC_MEMORY_ADD_P(r)    1
  353. #undef RELOC_ADD_EXTRA
  354. #define RELOC_PCREL_P(r)        ((r)->r_pcrel || (r)->r_bsr)
  355. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  356. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  357. #define RELOC_TARGET_BITPOS(r)    0
  358. #define RELOC_TARGET_BITSIZE(r)    32
  359. #endif
  360.  
  361. /* Default macros */
  362. #ifndef RELOC_ADDRESS
  363. #define RELOC_ADDRESS(r)        ((r)->r_address)
  364. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  365. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  366. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  367. #define RELOC_MEMORY_SUB_P(r)    0
  368. #define RELOC_MEMORY_ADD_P(r)    1
  369. #undef RELOC_ADD_EXTRA
  370. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  371. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  372. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  373. #define RELOC_TARGET_BITPOS(r)    0
  374. #define RELOC_TARGET_BITSIZE(r)    32
  375. #endif
  376.  
  377. #ifndef MAX_ALIGNMENT
  378. #define    MAX_ALIGNMENT    (sizeof (int))
  379. #endif
  380.  
  381. #ifdef nounderscore
  382. #define LPREFIX '.'
  383. #else
  384. #define LPREFIX 'L'
  385. #endif
  386.  
  387.  
  388. /* Special global symbol types understood by GNU LD.  */
  389.  
  390. /* The following type indicates the definition of a symbol as being
  391.    an indirect reference to another symbol.  The other symbol
  392.    appears as an undefined reference, immediately following this symbol.
  393.  
  394.    Indirection is asymmetrical.  The other symbol's value will be used
  395.    to satisfy requests for the indirect symbol, but not vice versa.
  396.    If the other symbol does not have a definition, libraries will
  397.    be searched to find a definition.
  398.  
  399.    So, for example, the following two lines placed in an assembler
  400.    input file would result in an object file which would direct gnu ld
  401.    to resolve all references to symbol "foo" as references to symbol
  402.    "bar".
  403.  
  404.     .stabs "_foo",11,0,0,0
  405.     .stabs "_bar",1,0,0,0
  406.  
  407.    Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)).  */
  408.  
  409. #ifndef N_INDR
  410. #define N_INDR 0xa
  411. #endif
  412.  
  413. /* The following symbols refer to set elements.  These are expected
  414.    only in input to the loader; they should not appear in loader
  415.    output (unless relocatable output is requested).  To be recognized
  416.    by the loader, the input symbols must have their N_EXT bit set.
  417.    All the N_SET[ATDB] symbols with the same name form one set.  The
  418.    loader collects all of these elements at load time and outputs a
  419.    vector for each name.
  420.    Space (an array of 32 bit words) is allocated for the set in the
  421.    data section, and the n_value field of each set element value is
  422.    stored into one word of the array.
  423.    The first word of the array is the length of the set (number of
  424.    elements).  The last word of the vector is set to zero for possible
  425.    use by incremental loaders.  The array is ordered by the linkage
  426.    order; the first symbols which the linker encounters will be first
  427.    in the array.
  428.  
  429.    In C syntax this looks like:
  430.  
  431.     struct set_vector {
  432.       unsigned int length;
  433.       unsigned int vector[length];
  434.       unsigned int always_zero;
  435.     };
  436.  
  437.    Before being placed into the array, each element is relocated
  438.    according to its type.  This allows the loader to create an array
  439.    of pointers to objects automatically.  N_SETA type symbols will not
  440.    be relocated.
  441.  
  442.    The address of the set is made into an N_SETV symbol
  443.    whose name is the same as the name of the set.
  444.    This symbol acts like a N_DATA global symbol
  445.    in that it can satisfy undefined external references.
  446.  
  447.    For the purposes of determining whether or not to load in a library
  448.    file, set element definitions are not considered "real
  449.    definitions"; they will not cause the loading of a library
  450.    member.
  451.  
  452.    If relocatable output is requested, none of this processing is
  453.    done.  The symbols are simply relocated and passed through to the
  454.    output file.
  455.  
  456.    So, for example, the following three lines of assembler code
  457.    (whether in one file or scattered between several different ones)
  458.    will produce a three element vector (total length is five words;
  459.    see above), referenced by the symbol "_xyzzy", which will have the
  460.    addresses of the routines _init1, _init2, and _init3.
  461.  
  462.    *NOTE*: If symbolic addresses are used in the n_value field of the
  463.    defining .stabs, those symbols must be defined in the same file as
  464.    that containing the .stabs.
  465.  
  466.     .stabs "_xyzzy",23,0,0,_init1
  467.     .stabs "_xyzzy",23,0,0,_init2
  468.     .stabs "_xyzzy",23,0,0,_init3
  469.  
  470.    Note that (23 == (N_SETT | N_EXT)).  */
  471.  
  472. #ifndef N_SETA
  473. #define    N_SETA    0x14        /* Absolute set element symbol */
  474. #endif                /* This is input to LD, in a .o file.  */
  475.  
  476. #ifndef N_SETT
  477. #define    N_SETT    0x16        /* Text set element symbol */
  478. #endif                /* This is input to LD, in a .o file.  */
  479.  
  480. #ifndef N_SETD
  481. #define    N_SETD    0x18        /* Data set element symbol */
  482. #endif                /* This is input to LD, in a .o file.  */
  483.  
  484. #ifndef N_SETB
  485. #define    N_SETB    0x1A        /* Bss set element symbol */
  486. #endif                /* This is input to LD, in a .o file.  */
  487.  
  488. /* Macros dealing with the set element symbols defined in a.out.h */
  489. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  490. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  491.  
  492. #ifndef N_SETV
  493. #define N_SETV    0x1C        /* Pointer to set vector in data area.  */
  494. #endif                /* This is output from LD.  */
  495.  
  496. /* If a this type of symbol is encountered, its name is a warning
  497.    message to print each time the symbol referenced by the next symbol
  498.    table entry is referenced.
  499.  
  500.    This feature may be used to allow backwards compatibility with
  501.    certain functions (eg. gets) but to discourage programmers from
  502.    their use.
  503.  
  504.    So if, for example, you wanted to have ld print a warning whenever
  505.    the function "gets" was used in their C program, you would add the
  506.    following to the assembler file in which gets is defined:
  507.  
  508.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  509.     .stabs "_gets",1,0,0,0
  510.  
  511.    These .stabs do not necessarily have to be in the same file as the
  512.    gets function, they simply must exist somewhere in the compilation.  */
  513.  
  514. #ifndef N_WARNING
  515. #define N_WARNING 0x1E        /* Warning message to print if symbol
  516.                    included */
  517. #endif                /* This is input to ld */
  518.  
  519. #ifndef __GNU_STAB__
  520.  
  521. /* Line number for the data section.  This is to be used to describe
  522.    the source location of a variable declaration.  */
  523. #ifndef N_DSLINE
  524. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  525. #endif
  526.  
  527. /* Line number for the bss section.  This is to be used to describe
  528.    the source location of a variable declaration.  */
  529. #ifndef N_BSLINE
  530. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  531. #endif
  532.  
  533. #endif /* not __GNU_STAB__ */
  534.  
  535. /* Symbol table */
  536.  
  537. /* Global symbol data is recorded in these structures,
  538.    one for each global symbol.
  539.    They are found via hashing in 'symtab', which points to a vector of buckets.
  540.    Each bucket is a chain of these structures through the link field.  */
  541.  
  542. typedef
  543.   struct glosym
  544.     {
  545.       /* Pointer to next symbol in this symbol's hash bucket.  */
  546.       struct glosym *link;
  547.       /* Name of this symbol.  */
  548.       char *name;
  549.       /* Value of this symbol as a global symbol.  */
  550.       long value;
  551.       /* Chain of external 'nlist's in files for this symbol, both defs
  552.      and refs.  */
  553.       struct nlist *refs;
  554.       /* Any warning message that might be associated with this symbol
  555.          from an N_WARNING symbol encountered. */
  556.       char *warning;
  557.       /* Nonzero means definitions of this symbol as common have been seen,
  558.      and the value here is the largest size specified by any of them.  */
  559.       int max_common_size;
  560.       /* For OUTPUT_RELOCATABLE, records the index of this global sym in the
  561.      symbol table to be written, with the first global sym given index 0.*/
  562.       int def_count;
  563.       /* Nonzero means a definition of this global symbol is known to exist.
  564.      Library members should not be loaded on its account.  */
  565.       char defined;
  566.       /* Nonzero means a reference to this global symbol has been seen
  567.      in a file that is surely being loaded.
  568.      A value higher than 1 is the n_type code for the symbol's
  569.      definition.  */
  570.       char referenced;
  571.       /* A count of the number of undefined references printed for a
  572.      specific symbol.  If a symbol is unresolved at the end of
  573.      digest_symbols (and the loading run is supposed to produce
  574.      relocatable output) do_file_warnings keeps track of how many
  575.      unresolved reference error messages have been printed for
  576.      each symbol here.  When the number hits MAX_UREFS_PRINTED,
  577.      messages stop. */
  578.       unsigned char undef_refs;
  579.       /* 1 means that this symbol has multiple definitions.  2 means
  580.          that it has multiple definitions, and some of them are set
  581.      elements, one of which has been printed out already.  */
  582.       unsigned char multiply_defined;
  583.       /* Nonzero means print a message at all refs or defs of this symbol */
  584.       char trace;
  585.     }
  586.   symbol;
  587.  
  588. /* Demangler for C++.  */
  589. extern char *cplus_demangle ();
  590.  
  591. /* Demangler function to use.  We unconditionally enable the C++ demangler
  592.    because we assume any name it successfully demangles was probably produced
  593.    by the C++ compiler.  Enabling it only if -lg++ was specified seems too
  594.    much of a kludge.  */
  595. char *(*demangler)() = cplus_demangle;
  596.  
  597. /* Number of buckets in symbol hash table */
  598. #define    TABSIZE    1009
  599.  
  600. /* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  601. symbol *symtab[TABSIZE];
  602.  
  603. /* Number of symbols in symbol hash table. */
  604. int num_hash_tab_syms = 0;
  605.  
  606. /* Count the number of nlist entries that are for local symbols.
  607.    This count and the three following counts
  608.    are incremented as as symbols are entered in the symbol table.  */
  609. int local_sym_count;
  610.  
  611. /* Count number of nlist entries that are for local symbols
  612.    whose names don't start with L. */
  613. int non_L_local_sym_count;
  614.  
  615. /* Count the number of nlist entries for debugger info.  */
  616. int debugger_sym_count;
  617.  
  618. /* Count the number of global symbols referenced and not defined.  */
  619. int undefined_global_sym_count;
  620.  
  621. /* Count the number of global symbols multiply defined.  */
  622. int multiple_def_count;
  623.  
  624. /* Count the number of defined global symbols.
  625.    Each symbol is counted only once
  626.    regardless of how many different nlist entries refer to it,
  627.    since the output file will need only one nlist entry for it.
  628.    This count is computed by `digest_symbols';
  629.    it is undefined while symbols are being loaded. */
  630. int defined_global_sym_count;
  631.  
  632. /* Count the number of symbols defined through common declarations.
  633.    This count is kept in symdef_library, linear_library, and
  634.    enter_global_ref.  It is incremented when the defined flag is set
  635.    in a symbol because of a common definition, and decremented when
  636.    the symbol is defined "for real" (ie. by something besides a common
  637.    definition).  */
  638. int common_defined_global_count;
  639.  
  640. /* Count the number of set element type symbols and the number of
  641.    separate vectors which these symbols will fit into.  See the
  642.    GNU a.out.h for more info.
  643.    This count is computed by 'enter_file_symbols' */
  644. int set_symbol_count;
  645. int set_vector_count;
  646.  
  647. /* Define a linked list of strings which define symbols which should
  648.    be treated as set elements even though they aren't.  Any symbol
  649.    with a prefix matching one of these should be treated as a set
  650.    element.
  651.  
  652.    This is to make up for deficiencies in many assemblers which aren't
  653.    willing to pass any stabs through to the loader which they don't
  654.    understand.  */
  655. struct string_list_element {
  656.   char *str;
  657.   struct string_list_element *next;
  658. };
  659.  
  660. struct string_list_element *set_element_prefixes;
  661.  
  662. /* Count the number of definitions done indirectly (ie. done relative
  663.    to the value of some other symbol. */
  664. int global_indirect_count;
  665.  
  666. /* Count the number of warning symbols encountered. */
  667. int warning_count;
  668.  
  669. /* Total number of symbols to be written in the output file.
  670.    Computed by digest_symbols from the variables above.  */
  671. int nsyms;
  672.  
  673.  
  674. /* Nonzero means ptr to symbol entry for symbol to use as start addr.
  675.    -e sets this.  */
  676. symbol *entry_symbol;
  677.  
  678. /* These can be NULL if we don't actually have such a symbol.  */
  679. symbol *edata_symbol;   /* the symbol _edata */
  680. symbol *etext_symbol;   /* the symbol _etext */
  681. symbol *end_symbol;    /* the symbol _end */
  682. /* We also need __{edata,etext,end} so that they can safely
  683.    be used from an ANSI library.  */
  684. symbol *edata_symbol_alt;
  685. symbol *etext_symbol_alt;
  686. symbol *end_symbol_alt;
  687.  
  688. /* Kinds of files potentially understood by the linker. */
  689.  
  690. enum file_type { IS_UNKNOWN, IS_ARCHIVE, IS_A_OUT, IS_MACH_O };
  691.  
  692. /* Each input file, and each library member ("subfile") being loaded,
  693.    has a `file_entry' structure for it.
  694.  
  695.    For files specified by command args, these are contained in the vector
  696.    which `file_table' points to.
  697.  
  698.    For library members, they are dynamically allocated,
  699.    and chained through the `chain' field.
  700.    The chain is found in the `subfiles' field of the `file_entry'.
  701.    The `file_entry' objects for the members have `superfile' fields pointing
  702.    to the one for the library.  */
  703.  
  704. struct file_entry {
  705.   /* Name of this file.  */
  706.   char *filename;
  707.  
  708.   /* What kind of file this is. */
  709.   enum file_type file_type;
  710.  
  711.   /* Name to use for the symbol giving address of text start */
  712.   /* Usually the same as filename, but for a file spec'd with -l
  713.      this is the -l switch itself rather than the filename.  */
  714.   char *local_sym_name;
  715.  
  716.   /* Describe the layout of the contents of the file.  */
  717.  
  718.   /* The text section. */
  719.   unsigned long int orig_text_address;
  720.   unsigned long int text_size;
  721.   long int text_offset;
  722.  
  723.   /* Text relocation. */
  724.   unsigned long int text_reloc_size;
  725.   long int text_reloc_offset;
  726.  
  727.   /* The data section. */
  728.   unsigned long int orig_data_address;
  729.   unsigned long int data_size;
  730.   long int data_offset;
  731.  
  732.   /* Data relocation. */
  733.   unsigned long int data_reloc_size;
  734.   long int data_reloc_offset;
  735.  
  736.   /* The bss section. */
  737.   unsigned long int orig_bss_address;
  738.   unsigned long int bss_size;
  739.  
  740.   /* The symbol and string tables. */
  741.   unsigned long int syms_size;
  742.   long int syms_offset;
  743.   unsigned long int strs_size;
  744.   long int strs_offset;
  745.  
  746.   /* The GDB symbol segment, if any. */
  747.   unsigned long int symseg_size;
  748.   long int symseg_offset;
  749.  
  750. #ifdef MACH_O
  751.   /* Section ordinals from the Mach-O load commands.  These
  752.      are compared with the n_sect fields of symbols.  */
  753.   int text_ordinal;
  754.   int data_ordinal;
  755.   int bss_ordinal;
  756. #endif
  757.  
  758.   /* Describe data from the file loaded into core */
  759.  
  760.   /* Symbol table of the file.  */
  761.   struct nlist *symbols;
  762.  
  763.   /* Pointer to the string table.
  764.      The string table is not kept in core all the time,
  765.      but when it is in core, its address is here.  */
  766.   char *strings;
  767.  
  768.   /* Next two used only if OUTPUT_RELOCATABLE or if needed for */
  769.   /* output of undefined reference line numbers. */
  770.  
  771.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  772.   struct relocation_info *textrel;
  773.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  774.   struct relocation_info *datarel;
  775.  
  776.   /* Relation of this file's segments to the output file */
  777.  
  778.   /* Start of this file's text seg in the output file core image.  */
  779.   int text_start_address;
  780.   /* Start of this file's data seg in the output file core image.  */
  781.   int data_start_address;
  782.   /* Start of this file's bss seg in the output file core image.  */
  783.   int bss_start_address;
  784.   /* Offset in bytes in the output file symbol table
  785.      of the first local symbol for this file.  Set by `write_file_symbols'.  */
  786.   int local_syms_offset;
  787.  
  788.   /* For library members only */
  789.  
  790.   /* For a library, points to chain of entries for the library members.  */
  791.   struct file_entry *subfiles;
  792.   /* For a library member, offset of the member within the archive.
  793.      Zero for files that are not library members.  */
  794.   int starting_offset;
  795.   /* Size of contents of this file, if library member.  */
  796.   int total_size;
  797.   /* For library member, points to the library's own entry.  */
  798.   struct file_entry *superfile;
  799.   /* For library member, points to next entry for next member.  */
  800.   struct file_entry *chain;
  801.  
  802.   /* 1 if file is a library. */
  803.   char library_flag;
  804.  
  805.   /* 1 if file's header has been read into this structure.  */
  806.   char header_read_flag;
  807.  
  808.   /* 1 means search a set of directories for this file.  */
  809.   char search_dirs_flag;
  810.  
  811.   /* 1 means this is base file of incremental load.
  812.      Do not load this file's text or data.
  813.      Also default text_start to after this file's bss. */
  814.   char just_syms_flag;
  815. };
  816.  
  817. /* Vector of entries for input files specified by arguments.
  818.    These are all the input files except for members of specified libraries.  */
  819. struct file_entry *file_table;
  820.  
  821. /* Length of that vector.  */
  822. int number_of_files;
  823.  
  824. /* When loading the text and data, we can avoid doing a close
  825.    and another open between members of the same library.
  826.  
  827.    These two variables remember the file that is currently open.
  828.    Both are zero if no file is open.
  829.  
  830.    See `each_file' and `file_close'.  */
  831.  
  832. struct file_entry *input_file;
  833. int input_desc;
  834.  
  835. /* The name of the file to write; "a.out" by default.  */
  836.  
  837. char *output_filename;
  838.  
  839. /* What kind of output file to write.  */
  840.  
  841. enum file_type output_file_type;
  842.  
  843. #ifndef DEFAULT_OUTPUT_FILE_TYPE
  844. #ifdef MACH_O
  845. #define DEFAULT_OUTPUT_FILE_TYPE IS_MACH_O
  846. #else
  847. #define DEFAULT_OUTPUT_FILE_TYPE IS_A_OUT
  848. #endif
  849. #endif
  850.  
  851. /* What `style' of output file to write.  For BSD a.out files
  852.    this specifies OMAGIC, NMAGIC, or ZMAGIC.  For Mach-O files
  853.    this switches between MH_OBJECT and two flavors of MH_EXECUTE.  */
  854.  
  855. enum output_style
  856.   {
  857.     OUTPUT_UNSPECIFIED,
  858.     OUTPUT_RELOCATABLE,        /* -r */
  859.     OUTPUT_WRITABLE_TEXT,    /* -N */
  860.     OUTPUT_READONLY_TEXT,    /* -n */
  861.     OUTPUT_DEMAND_PAGED        /* -Z (default) */
  862.   };
  863.  
  864. enum output_style output_style;
  865.  
  866. #ifndef DEFAULT_OUTPUT_STYLE
  867. #define DEFAULT_OUTPUT_STYLE OUTPUT_DEMAND_PAGED
  868. #endif
  869.  
  870. /* Descriptor for writing that file with `mywrite'.  */
  871.  
  872. int outdesc;
  873.  
  874. /* The following are computed by `digest_symbols'.  */
  875.  
  876. int text_size;            /* total size of text of all input files.  */
  877. int text_header_size;        /* size of the file header if included in the
  878.                    text size.  */
  879. int data_size;            /* total size of data of all input files.  */
  880. int bss_size;            /* total size of bss of all input files.  */
  881. int text_reloc_size;        /* total size of text relocation of all input files.  */
  882. int data_reloc_size;        /* total size of data relocation of all input
  883.                    files.  */
  884.   
  885. /* The following are computed by write_header().  */
  886. long int output_text_offset;    /* file offset of the text section.  */
  887. long int output_data_offset;    /* file offset of the data section.  */
  888. long int output_trel_offset;    /* file offset of the text relocation info.  */
  889. long int output_drel_offset;    /* file offset of the data relocation info.  */
  890. long int output_syms_offset;    /* file offset of the symbol table.  */
  891. long int output_strs_offset;    /* file offset of the string table.  */
  892.  
  893. /* The following are incrementally computed by write_syms(); we keep
  894.    them here so we can examine their values afterwards.  */
  895. unsigned int output_syms_size;    /* total bytes of symbol table output. */
  896. unsigned int output_strs_size;    /* total bytes of string table output. */
  897.  
  898. /* This can only be computed after the size of the string table is known.  */
  899. long int output_symseg_offset;    /* file offset of the symbol segment (if any).  */
  900.  
  901. /* Incrementally computed by write_file_symseg().  */
  902. unsigned int output_symseg_size;
  903.  
  904. /* Specifications of start and length of the area reserved at the end
  905.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  906. int set_sect_start;
  907. int set_sect_size;
  908.  
  909. /* Pointer for in core storage for the above vectors, before they are
  910.    written. */
  911. unsigned long *set_vectors;
  912.  
  913. /* Amount of cleared space to leave at the end of the text segment.  */
  914.  
  915. int text_pad;
  916.  
  917. /* Amount of padding at end of data segment.  This has two parts:
  918.    That which is before the bss segment, and that which overlaps
  919.    with the bss segment.  */
  920. int data_pad;
  921.  
  922. /* Format of __.SYMDEF:
  923.    First, a longword containing the size of the 'symdef' data that follows.
  924.    Second, zero or more 'symdef' structures.
  925.    Third, a longword containing the length of symbol name strings.
  926.    Fourth, zero or more symbol name strings (each followed by a null).  */
  927.  
  928. struct symdef {
  929.   int symbol_name_string_index;
  930.   int library_member_offset;
  931. };
  932.  
  933. /* Record most of the command options.  */
  934.  
  935. /* Address we assume the text section will be loaded at.
  936.    We relocate symbols and text and data for this, but we do not
  937.    write any padding in the output file for it.  */
  938. int text_start;
  939.  
  940. /* Address we decide the data section will be loaded at.  */
  941. int data_start;
  942.  
  943. /* Nonzero if -T was specified in the command line.
  944.    This prevents text_start from being set later to default values.  */
  945. int T_flag_specified;
  946.  
  947. /* Nonzero if -Tdata was specified in the command line.
  948.    This prevents data_start from being set later to default values.  */
  949. int Tdata_flag_specified;
  950.  
  951. /* Size to pad data section up to.
  952.    We simply increase the size of the data section, padding with zeros,
  953.    and reduce the size of the bss section to match.  */
  954. int specified_data_size;
  955.  
  956. /* Nonzero means print names of input files as processed.  */
  957. int trace_files;
  958.  
  959. /* Which symbols should be stripped (omitted from the output):
  960.    none, all, or debugger symbols.  */
  961. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  962.  
  963. /* Which local symbols should be omitted:
  964.    none, all, or those starting with L.
  965.    This is irrelevant if STRIP_NONE.  */
  966. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  967.  
  968. /* 1 => write load map.  */
  969. int write_map;
  970.  
  971. /* 1 => assign space to common symbols even if OUTPUT_RELOCATABLE. */
  972. int force_common_definition;
  973.  
  974. /* Standard directories to search for files specified by -l.  */
  975. char *standard_search_dirs[] =
  976. #ifdef STANDARD_SEARCH_DIRS
  977.   {STANDARD_SEARCH_DIRS};
  978. #else
  979. #ifdef NON_NATIVE
  980.   {"/usr/local/lib/gnu"};
  981. #else
  982.   {"/lib", "/usr/lib", "/usr/local/lib"};
  983. #endif
  984. #endif
  985.  
  986. /* If set STANDARD_SEARCH_DIRS is not searched.  */
  987. int no_standard_dirs;
  988.  
  989. /* Actual vector of directories to search;
  990.    this contains those specified with -L plus the standard ones.  */
  991. char **search_dirs;
  992.  
  993. /* Length of the vector `search_dirs'.  */
  994. int n_search_dirs;
  995.  
  996. /* Non zero means to create the output executable.
  997.    Cleared by nonfatal errors.  */
  998. int make_executable;
  999.  
  1000. /* Force the executable to be output, even if there are non-fatal
  1001.    errors */
  1002. int force_executable;
  1003.  
  1004. /* Keep a list of any symbols referenced from the command line (so
  1005.    that error messages for these guys can be generated). This list is
  1006.    zero terminated. */
  1007. struct glosym **cmdline_references;
  1008. int cl_refs_allocated;
  1009.  
  1010. #ifndef bcopy
  1011. void bcopy (), bzero ();
  1012. #endif
  1013. char *malloc (), *realloc ();
  1014. void free ();
  1015.  
  1016. char *xmalloc ();
  1017. char *xrealloc ();
  1018. void usage ();
  1019. void fatal ();
  1020. void fatal_with_file ();
  1021. void perror_name ();
  1022. void perror_file ();
  1023. void error ();
  1024.  
  1025. int parse ();
  1026. void initialize_text_start ();
  1027. void initialize_data_start ();
  1028. void digest_symbols ();
  1029. void print_symbols ();
  1030. void load_symbols ();
  1031. void decode_command ();
  1032. void list_undefined_symbols ();
  1033. void list_unresolved_references ();
  1034. void write_output ();
  1035. void write_header ();
  1036. void write_text ();
  1037. void read_file_relocation ();
  1038. void write_data ();
  1039. void write_rel ();
  1040. void write_syms ();
  1041. void write_symsegs ();
  1042. void mywrite ();
  1043. void symtab_init ();
  1044. void padfile ();
  1045. char *concat ();
  1046. char *get_file_name ();
  1047. symbol *getsym (), *getsym_soft ();
  1048.  
  1049. int
  1050. main (argc, argv)
  1051.      char **argv;
  1052.      int argc;
  1053. {
  1054.   page_size = getpagesize ();
  1055.   progname = argv[0];
  1056.  
  1057. #ifdef RLIMIT_STACK
  1058.   /* Avoid dumping core on large .o files.  */
  1059.   {
  1060.     struct rlimit rl;
  1061.  
  1062.     getrlimit (RLIMIT_STACK, &rl);
  1063.     rl.rlim_cur = rl.rlim_max;
  1064.     setrlimit (RLIMIT_STACK, &rl);
  1065.   }
  1066. #endif
  1067.  
  1068.   /* Clear the cumulative info on the output file.  */
  1069.  
  1070.   text_size = 0;
  1071.   data_size = 0;
  1072.   bss_size = 0;
  1073.   text_reloc_size = 0;
  1074.   data_reloc_size = 0;
  1075.  
  1076.   data_pad = 0;
  1077.   text_pad = 0;
  1078.  
  1079.   /* Initialize the data about options.  */
  1080.  
  1081.   specified_data_size = 0;
  1082.   strip_symbols = STRIP_NONE;
  1083.   trace_files = 0;
  1084.   discard_locals = DISCARD_NONE;
  1085.   entry_symbol = 0;
  1086.   write_map = 0;
  1087.   force_common_definition = 0;
  1088.   T_flag_specified = 0;
  1089.   Tdata_flag_specified = 0;
  1090.   make_executable = 1;
  1091.   force_executable = 0;
  1092.   set_element_prefixes = 0;
  1093.  
  1094.   /* Initialize the cumulative counts of symbols.  */
  1095.  
  1096.   local_sym_count = 0;
  1097.   non_L_local_sym_count = 0;
  1098.   debugger_sym_count = 0;
  1099.   undefined_global_sym_count = 0;
  1100.   set_symbol_count = 0;
  1101.   set_vector_count = 0;
  1102.   global_indirect_count = 0;
  1103.   warning_count = 0;
  1104.   multiple_def_count = 0;
  1105.   common_defined_global_count = 0;
  1106.  
  1107.   /* Keep a list of symbols referenced from the command line */
  1108.  
  1109.   cl_refs_allocated = 10;
  1110.   cmdline_references
  1111.     = (struct glosym **) xmalloc (cl_refs_allocated
  1112.                   * sizeof(struct glosym *));
  1113.   *cmdline_references = 0;
  1114.  
  1115.   /* Completely decode ARGV.  */
  1116.  
  1117.   decode_command (argc, argv);
  1118.  
  1119.   /* Load symbols of all input files.
  1120.      Also search all libraries and decide which library members to load.  */
  1121.  
  1122.   load_symbols ();
  1123.  
  1124.   /* Create various built-in symbols.  This must occur after
  1125.      all input files are loaded so that a user program can have a
  1126.      symbol named etext (for example).  */
  1127.  
  1128.   if (output_style != OUTPUT_RELOCATABLE)
  1129.     symtab_init ();
  1130.  
  1131.   /* Compute where each file's sections go, and relocate symbols.  */
  1132.  
  1133.   digest_symbols ();
  1134.  
  1135.   /* Print error messages for any missing symbols, for any warning
  1136.      symbols, and possibly multiple definitions */
  1137.  
  1138.   do_warnings (stderr);
  1139.  
  1140.   /* Print a map, if requested.  */
  1141.  
  1142.   if (write_map) print_symbols (stdout);
  1143.  
  1144.   /* Write the output file.  */
  1145.  
  1146.   if (make_executable || force_executable)
  1147.     write_output ();
  1148.  
  1149.   exit (!make_executable);
  1150. }
  1151.  
  1152. void add_cmdline_ref ();
  1153.  
  1154. static struct option longopts[] =
  1155. {
  1156.   {"d", 0, 0, 'd'},
  1157.   {"dc", 0, 0, 'd'},        /* For Sun compatibility. */
  1158.   {"dp", 0, 0, 'd'},        /* For Sun compatibility. */
  1159.   {"e", 1, 0, 'e'},
  1160.   {"n", 0, 0, 'n'},
  1161.   {"noinhibit-exec", 0, 0, 130},
  1162.   {"nostdlib", 0, 0, 133},
  1163.   {"o", 1, 0, 'o'},
  1164.   {"r", 0, 0, 'r'},
  1165.   {"s", 0, 0, 's'},
  1166.   {"t", 0, 0, 't'},
  1167.   {"u", 1, 0, 'u'},
  1168.   {"x", 0, 0, 'x'},
  1169.   {"z", 0, 0, 'z'},
  1170.   {"A", 1, 0, 'A'},
  1171.   {"Bstatic", 0, 0, 129},    /* For Sun compatibility. */
  1172.   {"D", 1, 0, 'D'},
  1173.   {"M", 0, 0, 'M'},
  1174.   {"N", 0, 0, 'N'},
  1175.   {"S", 0, 0, 'S'},
  1176.   {"T", 1, 0, 'T'},
  1177.   {"Ttext", 1, 0, 'T'},
  1178.   {"Tdata", 1, 0, 132},
  1179.   {"V", 1, 0, 'V'},
  1180.   {"X", 0, 0, 'X'},
  1181.   {0, 0, 0, 0}
  1182. };
  1183.  
  1184. /* Since the Unix ld accepts -lfoo, -Lfoo, and -yfoo, we must also.
  1185.    This effectively prevents any long options from starting with
  1186.    one of these letters. */
  1187. #define SHORTOPTS "-l:y:L:"
  1188.  
  1189. /* Process the command arguments,
  1190.    setting up file_table with an entry for each input file,
  1191.    and setting variables according to the options.  */
  1192.  
  1193. void
  1194. decode_command (argc, argv)
  1195.      char **argv;
  1196.      int argc;
  1197. {
  1198.   int optc, longind;
  1199.   register struct file_entry *p;
  1200.  
  1201.   number_of_files = 0;
  1202.   output_filename = "a.out";
  1203.  
  1204.   n_search_dirs = 0;
  1205.   search_dirs = (char **) xmalloc (sizeof (char *));
  1206.  
  1207.   /* First compute number_of_files so we know how long to make file_table.
  1208.      Also process most options completely.  */
  1209.  
  1210.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1211.      != EOF)
  1212.     {
  1213.       if (optc == 0)
  1214.     optc = longopts[longind].val;
  1215.  
  1216.       switch (optc)
  1217.     {
  1218.     case '?':
  1219.       usage (0, 0);
  1220.       break;
  1221.  
  1222.     case 1:
  1223.       /* Non-option argument. */
  1224.       number_of_files++;
  1225.       break;
  1226.  
  1227.     case 'd':
  1228.       force_common_definition = 1;
  1229.       break;
  1230.  
  1231.     case 'e':
  1232.       entry_symbol = getsym (optarg);
  1233.       if (!entry_symbol->defined && !entry_symbol->referenced)
  1234.         undefined_global_sym_count++;
  1235.       entry_symbol->referenced = 1;
  1236.       add_cmdline_ref (entry_symbol);
  1237.       break;
  1238.  
  1239.     case 'l':
  1240.       number_of_files++;
  1241.       break;
  1242.  
  1243.     case 'n':
  1244.       if (output_style && output_style != OUTPUT_READONLY_TEXT)
  1245.         fatal ("illegal combination of -n with -N, -r, or -z", (char *) 0);
  1246.       output_style = OUTPUT_READONLY_TEXT;
  1247.       break;
  1248.  
  1249.     case 130:        /* -noinhibit-exec */
  1250.       force_executable = 1;
  1251.       break;
  1252.  
  1253.     case 133:        /* -nostdlib */
  1254.       no_standard_dirs = 1;
  1255.       break;
  1256.  
  1257.     case 'o':
  1258.       output_filename = optarg;
  1259.       break;
  1260.  
  1261.     case 'r':
  1262.       if (output_style && output_style != OUTPUT_RELOCATABLE)
  1263.         fatal ("illegal combination of -r with -N, -n, or -z", (char *) 0);
  1264.       output_style = OUTPUT_RELOCATABLE;
  1265.       text_start = 0;
  1266.       break;
  1267.  
  1268.     case 's':
  1269.       strip_symbols = STRIP_ALL;
  1270.       break;
  1271.  
  1272.     case 't':
  1273.       trace_files = 1;
  1274.       break;
  1275.  
  1276.     case 'u':
  1277.       {
  1278.         register symbol *sp = getsym (optarg);
  1279.  
  1280.         if (!sp->defined && !sp->referenced)
  1281.           undefined_global_sym_count++;
  1282.         sp->referenced = 1;
  1283.         add_cmdline_ref (sp);
  1284.       }
  1285.       break;
  1286.  
  1287.     case 'x':
  1288.       discard_locals = DISCARD_ALL;
  1289.       break;
  1290.       
  1291.     case 'y':
  1292.       {
  1293.         register symbol *sp = getsym (optarg);
  1294.  
  1295.         sp->trace = 1;
  1296.       }
  1297.       break;
  1298.  
  1299.     case 'z':
  1300.       if (output_style && output_style != OUTPUT_DEMAND_PAGED)
  1301.         fatal ("illegal combination of -z with -N, -n, or -r", (char *) 0);
  1302.       output_style = OUTPUT_DEMAND_PAGED;
  1303.       break;
  1304.  
  1305.     case 'A':
  1306.       number_of_files++;
  1307.       break;
  1308.  
  1309.     case 129:        /* -Bstatic. */
  1310.       /* Ignore. */
  1311.       break;
  1312.  
  1313.     case 'D':
  1314.       specified_data_size = parse (optarg, "%x", "invalid argument to -D");
  1315.       break;
  1316.  
  1317.     case 'L':
  1318.       n_search_dirs++;
  1319.       search_dirs = (char **)
  1320.         xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1321.       search_dirs[n_search_dirs - 1] = optarg;
  1322.       break;
  1323.       
  1324.     case 'M':
  1325.       write_map = 1;
  1326.       break;
  1327.  
  1328.     case 'N':
  1329.       if (output_style && output_style != OUTPUT_WRITABLE_TEXT)
  1330.         fatal ("illegal combination of -N with -n, -r, or -z", (char *) 0);
  1331.       output_style = OUTPUT_WRITABLE_TEXT;
  1332.       break;
  1333.  
  1334.     case 'S':
  1335.       strip_symbols = STRIP_DEBUGGER;
  1336.       break;
  1337.  
  1338.     case 'T':
  1339.       text_start = parse (optarg, "%x", "invalid argument to -Ttext");
  1340.       T_flag_specified = 1;
  1341.       break;
  1342.  
  1343.     case 132:        /* -Tdata addr */
  1344.       data_start = parse (optarg, "%x", "invalid argument to -Tdata");
  1345.       Tdata_flag_specified = 1;
  1346.       break;
  1347.  
  1348.     case 'V':
  1349.       {
  1350.         struct string_list_element *new
  1351.           = (struct string_list_element *)
  1352.         xmalloc (sizeof (struct string_list_element));
  1353.         
  1354.         new->str = optarg;
  1355.         new->next = set_element_prefixes;
  1356.         set_element_prefixes = new;
  1357.       }
  1358.       break;
  1359.  
  1360.     case 'X':
  1361.       discard_locals = DISCARD_L;
  1362.       break;
  1363.     }
  1364.     }
  1365.  
  1366.   if (!number_of_files)
  1367.     usage ("no input files", 0);
  1368.  
  1369.   p = file_table
  1370.     = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  1371.   bzero (p, number_of_files * sizeof (struct file_entry));
  1372.  
  1373.   /* Now scan again and fill in file_table.
  1374.      All options except -A and -l are ignored here.  */
  1375.  
  1376.   optind = 0;            /* Reset getopt. */
  1377.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1378.      != EOF)
  1379.     {
  1380.       if (optc == 0)
  1381.     optc = longopts[longind].val;
  1382.  
  1383.       switch (optc)
  1384.     {
  1385.     case 1:
  1386.       /* Non-option argument. */
  1387.       p->filename = optarg;
  1388.       p->local_sym_name = optarg;
  1389.       p++;
  1390.       break;
  1391.  
  1392.     case 'A':
  1393.       if (p != file_table)
  1394.         usage ("-A specified before an input file other than the first");
  1395.       p->filename = optarg;
  1396.       p->local_sym_name = optarg;
  1397.       p->just_syms_flag = 1;
  1398.       p++;
  1399.       break;
  1400.  
  1401.     case 'l':
  1402.       p->filename = concat ("lib", optarg, ".a");
  1403.       p->local_sym_name = concat ("-l", optarg, "");
  1404.       p->search_dirs_flag = 1;
  1405.       p++;
  1406.       break;
  1407.     }
  1408.     }
  1409.  
  1410.   if (!output_file_type)
  1411.     output_file_type = DEFAULT_OUTPUT_FILE_TYPE;
  1412.  
  1413.   if (!output_style)
  1414.     output_style = DEFAULT_OUTPUT_STYLE;
  1415.  
  1416. #if 0
  1417.   /* THIS CONSISTENCY CHECK BELONGS SOMEWHERE ELSE.  */
  1418.   /* Now check some option settings for consistency.  */
  1419.  
  1420.   if ((output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  1421.       && (text_start - text_start_alignment) & (page_size - 1))
  1422.     usage ("-T argument not multiple of page size, with sharable output", 0);
  1423. #endif
  1424.  
  1425.   /* Append the standard search directories to the user-specified ones.  */
  1426.   if (!no_standard_dirs)
  1427.     {
  1428.       int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
  1429.       n_search_dirs += n;
  1430.       search_dirs
  1431.     = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1432.       bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
  1433.          n * sizeof (char *));
  1434.     }
  1435. }
  1436.  
  1437.  
  1438. void
  1439. add_cmdline_ref (sp)
  1440.      struct glosym *sp;
  1441. {
  1442.   struct glosym **ptr;
  1443.  
  1444.   for (ptr = cmdline_references;
  1445.        ptr < cmdline_references + cl_refs_allocated && *ptr;
  1446.        ptr++)
  1447.     ;
  1448.  
  1449.   if (ptr >= cmdline_references + cl_refs_allocated - 1)
  1450.     {
  1451.       int diff = ptr - cmdline_references;
  1452.  
  1453.       cl_refs_allocated *= 2;
  1454.       cmdline_references = (struct glosym **)
  1455.     xrealloc (cmdline_references,
  1456.          cl_refs_allocated * sizeof (struct glosym *));
  1457.       ptr = cmdline_references + diff;
  1458.     }
  1459.  
  1460.   *ptr++ = sp;
  1461.   *ptr = (struct glosym *) 0;
  1462. }
  1463.  
  1464. int
  1465. set_element_prefixed_p (name)
  1466.      char *name;
  1467. {
  1468.   struct string_list_element *p;
  1469.   int i;
  1470.  
  1471.   for (p = set_element_prefixes; p; p = p->next)
  1472.     {
  1473.       for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
  1474.     ;
  1475.  
  1476.       if (p->str[i] == '\0')
  1477.     return 1;
  1478.     }
  1479.   return 0;
  1480. }
  1481.  
  1482. /* Convenient functions for operating on one or all files being
  1483.    loaded.  */
  1484. void print_file_name ();
  1485.  
  1486. /* Call FUNCTION on each input file entry.
  1487.    Do not call for entries for libraries;
  1488.    instead, call once for each library member that is being loaded.
  1489.  
  1490.    FUNCTION receives two arguments: the entry, and ARG.  */
  1491.  
  1492. void
  1493. each_file (function, arg)
  1494.      register void (*function)();
  1495.      register int arg;
  1496. {
  1497.   register int i;
  1498.  
  1499.   for (i = 0; i < number_of_files; i++)
  1500.     {
  1501.       register struct file_entry *entry = &file_table[i];
  1502.       if (entry->library_flag)
  1503.         {
  1504.       register struct file_entry *subentry = entry->subfiles;
  1505.       for (; subentry; subentry = subentry->chain)
  1506.         (*function) (subentry, arg);
  1507.     }
  1508.       else
  1509.     (*function) (entry, arg);
  1510.     }
  1511. }
  1512.  
  1513. /* Call FUNCTION on each input file entry until it returns a non-zero
  1514.    value.  Return this value.
  1515.    Do not call for entries for libraries;
  1516.    instead, call once for each library member that is being loaded.
  1517.  
  1518.    FUNCTION receives two arguments: the entry, and ARG.  It must be a
  1519.    function returning unsigned long (though this can probably be fudged). */
  1520.  
  1521. unsigned long
  1522. check_each_file (function, arg)
  1523.      register unsigned long (*function)();
  1524.      register int arg;
  1525. {
  1526.   register int i;
  1527.   register unsigned long return_val;
  1528.  
  1529.   for (i = 0; i < number_of_files; i++)
  1530.     {
  1531.       register struct file_entry *entry = &file_table[i];
  1532.       if (entry->library_flag)
  1533.         {
  1534.       register struct file_entry *subentry = entry->subfiles;
  1535.       for (; subentry; subentry = subentry->chain)
  1536.         if (return_val = (*function) (subentry, arg))
  1537.           return return_val;
  1538.     }
  1539.       else
  1540.     if (return_val = (*function) (entry, arg))
  1541.       return return_val;
  1542.     }
  1543.   return 0;
  1544. }
  1545.  
  1546. /* Like `each_file' but ignore files that were just for symbol definitions.  */
  1547.  
  1548. void
  1549. each_full_file (function, arg)
  1550.      register void (*function)();
  1551.      register int arg;
  1552. {
  1553.   register int i;
  1554.  
  1555.   for (i = 0; i < number_of_files; i++)
  1556.     {
  1557.       register struct file_entry *entry = &file_table[i];
  1558.       if (entry->just_syms_flag)
  1559.     continue;
  1560.       if (entry->library_flag)
  1561.         {
  1562.       register struct file_entry *subentry = entry->subfiles;
  1563.       for (; subentry; subentry = subentry->chain)
  1564.         (*function) (subentry, arg);
  1565.     }
  1566.       else
  1567.     (*function) (entry, arg);
  1568.     }
  1569. }
  1570.  
  1571. /* Close the input file that is now open.  */
  1572.  
  1573. void
  1574. file_close ()
  1575. {
  1576.   close (input_desc);
  1577.   input_desc = 0;
  1578.   input_file = 0;
  1579. }
  1580.  
  1581. /* Open the input file specified by 'entry', and return a descriptor.
  1582.    The open file is remembered; if the same file is opened twice in a row,
  1583.    a new open is not actually done.  */
  1584.  
  1585. int
  1586. file_open (entry)
  1587.      register struct file_entry *entry;
  1588. {
  1589.   register int desc;
  1590.  
  1591.   if (entry->superfile)
  1592.     return file_open (entry->superfile);
  1593.  
  1594.   if (entry == input_file)
  1595.     return input_desc;
  1596.  
  1597.   if (input_file) file_close ();
  1598.  
  1599.   if (entry->search_dirs_flag && n_search_dirs)
  1600.     {
  1601.       int i;
  1602.  
  1603.       for (i = 0; i < n_search_dirs; i++)
  1604.     {
  1605.       register char *string
  1606.         = concat (search_dirs[i], "/", entry->filename);
  1607.       desc = open (string, O_RDONLY, 0);
  1608.       if (desc > 0)
  1609.         {
  1610.           entry->filename = string;
  1611.           entry->search_dirs_flag = 0;
  1612.           break;
  1613.         }
  1614.       free (string);
  1615.     }
  1616.     }
  1617.   else
  1618.     desc = open (entry->filename, O_RDONLY, 0);
  1619.  
  1620.   if (desc > 0)
  1621.     {
  1622.       input_file = entry;
  1623.       input_desc = desc;
  1624.       return desc;
  1625.     }
  1626.  
  1627.   perror_file (entry);
  1628.   /* NOTREACHED */
  1629. }
  1630.  
  1631. /* Print the filename of ENTRY on OUTFILE (a stdio stream),
  1632.    and then a newline.  */
  1633.  
  1634. void
  1635. prline_file_name (entry, outfile)
  1636.      struct file_entry *entry;
  1637.      FILE *outfile;
  1638. {
  1639.   print_file_name (entry, outfile);
  1640.   fprintf (outfile, "\n");
  1641. }
  1642.  
  1643. /* Print the filename of ENTRY on OUTFILE (a stdio stream).  */
  1644.  
  1645. void
  1646. print_file_name (entry, outfile)
  1647.      struct file_entry *entry;
  1648.      FILE *outfile;
  1649. {
  1650.   if (entry->superfile)
  1651.     {
  1652.       print_file_name (entry->superfile, outfile);
  1653.       fprintf (outfile, "(%s)", entry->filename);
  1654.     }
  1655.   else
  1656.     fprintf (outfile, "%s", entry->filename);
  1657. }
  1658.  
  1659. /* Return the filename of entry as a string (malloc'd for the purpose) */
  1660.  
  1661. char *
  1662. get_file_name (entry)
  1663.      struct file_entry *entry;
  1664. {
  1665.   char *result, *supfile;
  1666.   if (entry->superfile)
  1667.     {
  1668.       supfile = get_file_name (entry->superfile);
  1669.       result = (char *) xmalloc (strlen (supfile)
  1670.                  + strlen (entry->filename) + 3);
  1671.       sprintf (result, "%s(%s)", supfile, entry->filename);
  1672.       free (supfile);
  1673.     }
  1674.   else
  1675.     {
  1676.       result = (char *) xmalloc (strlen (entry->filename) + 1);
  1677.       strcpy (result, entry->filename);
  1678.     }
  1679.   return result;
  1680. }
  1681.  
  1682. /* Medium-level input routines for rel files.  */
  1683.  
  1684. /* Determine whether the given ENTRY is an archive, a BSD a.out file,
  1685.    a Mach-O file, or whatever.  DESC is the descriptor on which the
  1686.    file is open.  */
  1687. void
  1688. deduce_file_type(desc, entry)
  1689.      int desc;
  1690.      struct file_entry *entry;
  1691. {
  1692.   int len;
  1693.  
  1694.   {
  1695.     char magic[SARMAG];
  1696.     
  1697.     lseek (desc, entry->starting_offset, 0);
  1698.     len = read (desc, magic, SARMAG);
  1699.     if (len == SARMAG && !strncmp(magic, ARMAG, SARMAG))
  1700.       {
  1701.     entry->file_type = IS_ARCHIVE;
  1702.     return;
  1703.       }
  1704.   }
  1705.  
  1706. #ifdef A_OUT
  1707.   {
  1708.     struct exec hdr;
  1709.  
  1710.     lseek (desc, entry->starting_offset, 0);
  1711. #ifdef COFF_ENCAPSULATE
  1712.     if (entry->just_syms_flag)
  1713.       /* Since a file given with -A will have a coff header, unlike normal
  1714.     input files, we need to skip over it.  */
  1715.       lseek (desc, sizeof (coffheader), SEEK_CUR);
  1716. #endif
  1717.     len = read (desc, (char *) &hdr, sizeof (struct exec));
  1718.     if (len == sizeof (struct exec) && !N_BADMAG (hdr))
  1719.       {
  1720.     entry->file_type = IS_A_OUT;
  1721.     return;
  1722.       }
  1723.   }
  1724. #endif
  1725.  
  1726. #ifdef MACH_O
  1727.   {
  1728.     struct mach_header hdr;
  1729.  
  1730.     lseek (desc, entry->starting_offset, 0);
  1731.     len = read (desc, (char *) &hdr, sizeof (struct mach_header));
  1732.     if (len == sizeof (struct mach_header) && hdr.magic == MH_MAGIC)
  1733.       {
  1734.     entry->file_type = IS_MACH_O;
  1735.     return;
  1736.       }
  1737.   }
  1738. #endif
  1739.  
  1740.   fatal_with_file ("malformed input file (not rel or archive) ", entry);
  1741. }
  1742.  
  1743. #ifdef A_OUT
  1744. /* Read an a.out file's header and set up the fields of
  1745.    the ENTRY accordingly.  DESC is the descriptor on which
  1746.    the file is open.  */
  1747. void
  1748. read_a_out_header (desc, entry)
  1749.      int desc;
  1750.      struct file_entry *entry;
  1751. {
  1752.   register int len;
  1753.   struct exec hdr;
  1754.   struct stat st;
  1755.  
  1756.   lseek (desc, entry->starting_offset, 0);
  1757.  
  1758. #ifdef COFF_ENCAPSULATE
  1759.   if (entry->just_syms_flag)
  1760.     /* Since a file given with -A will have a coff header, unlike normal
  1761.        input files, we need to skip over it.  */
  1762.     lseek (desc, sizeof (coffheader), SEEK_CUR);
  1763. #endif
  1764.  
  1765.   read (desc, (char *) &hdr, sizeof (struct exec));
  1766.  
  1767. #ifdef READ_HEADER_HOOK
  1768.   READ_HEADER_HOOK(hdr.a_machtype);
  1769. #endif
  1770.  
  1771.   if (entry->just_syms_flag)
  1772.     entry->orig_text_address = N_TXTADDR(hdr);
  1773.   else
  1774.     entry->orig_text_address = 0;
  1775.   entry->text_size = hdr.a_text;
  1776.   entry->text_offset = N_TXTOFF(hdr);
  1777.  
  1778.   entry->text_reloc_size = hdr.a_trsize;
  1779. #ifdef N_TRELOFF
  1780.   entry->text_reloc_offset = N_TRELOFF(hdr);
  1781. #else
  1782. #ifdef N_DATOFF
  1783.   entry->text_reloc_offset = N_DATOFF(hdr) + hdr.a_data;
  1784. #else
  1785.   entry->text_reloc_offset = N_TXTOFF(hdr) + hdr.a_text + hdr.a_data;
  1786. #endif
  1787. #endif
  1788.  
  1789.   if (entry->just_syms_flag)
  1790.     entry->orig_data_address = N_DATADDR(hdr);
  1791.   else
  1792.     entry->orig_data_address = entry->text_size;
  1793.   entry->data_size = hdr.a_data;
  1794. #ifdef N_DATOFF
  1795.   entry->data_offset = N_DATOFF(hdr);
  1796. #else
  1797.   entry->data_offset = N_TXTOFF(hdr) + hdr.a_text;
  1798. #endif
  1799.  
  1800.   entry->data_reloc_size = hdr.a_drsize;
  1801. #ifdef N_DRELOFF
  1802.   entry->data_reloc_offset = N_DRELOFF(hdr);
  1803. #else
  1804.   entry->data_reloc_offset = entry->text_reloc_offset + entry->text_reloc_size;
  1805. #endif
  1806.  
  1807. #ifdef N_BSSADDR
  1808.   if (entry->just_syms_flag)
  1809.     entry->orig_bss_address = N_BSSADDR(hdr);
  1810.   else
  1811. #endif
  1812.   entry->orig_bss_address = entry->orig_data_address + entry->data_size;
  1813.   entry->bss_size = hdr.a_bss;
  1814.  
  1815.   entry->syms_size = hdr.a_syms;
  1816.   entry->syms_offset = N_SYMOFF(hdr);
  1817.   entry->strs_offset = N_STROFF(hdr);
  1818.   lseek(desc, entry->starting_offset + entry->strs_offset, 0);
  1819.   if (read(desc, (char *) &entry->strs_size, sizeof (unsigned long int))
  1820.       != sizeof (unsigned long int))
  1821.     fatal_with_file ("failure reading string table size of ", entry);
  1822.  
  1823.   if (!entry->superfile)
  1824.     {
  1825.       fstat(desc, &st);
  1826.       if (st.st_size > entry->strs_offset + entry->strs_size)
  1827.     {
  1828.       entry->symseg_size = st.st_size - (entry->strs_offset + entry->strs_size);
  1829.       entry->symseg_offset = entry->strs_offset + entry->strs_size;
  1830.     }
  1831.     }
  1832.   else
  1833.     if (entry->total_size > entry->strs_offset + entry->strs_size)
  1834.       {
  1835.     entry->symseg_size = entry->total_size - (entry->strs_offset + entry->strs_size);
  1836.     entry->symseg_offset = entry->strs_offset + entry->strs_size;
  1837.       }
  1838. }
  1839. #endif
  1840.  
  1841. #ifdef MACH_O
  1842. /* Read a Mach-O file's header.  DESC is the descriptor on which the
  1843.    file is open, and ENTRY is the file's entry.  */
  1844. void
  1845. read_mach_o_header (desc, entry)
  1846.      int desc;
  1847.      struct file_entry *entry;
  1848. {
  1849.   struct mach_header mach_header;
  1850.   char *hdrbuf;
  1851.   struct load_command *load_command;
  1852.   struct segment_command *segment_command;
  1853.   struct section *section;
  1854.   struct symtab_command *symtab_command;
  1855. #ifdef LC_SYMSEG
  1856.   struct symseg_command *symseg_command;
  1857. #endif;
  1858.   int ordinal;
  1859.   int symtab_seen, symseg_seen;
  1860.   int len, cmd, seg;
  1861.  
  1862.   entry->text_ordinal = entry->data_ordinal = entry->bss_ordinal = 0;
  1863.   symtab_seen = symseg_seen = 0;
  1864.   ordinal = 1;
  1865.  
  1866.   lseek (desc, entry->starting_offset, 0);
  1867.   len = read (desc, (char *) &mach_header, sizeof (struct mach_header));
  1868.   if (len != sizeof (struct mach_header))
  1869.     fatal_with_file ("failure reading Mach-O header of ", entry);
  1870.   if (mach_header.filetype != MH_OBJECT && mach_header.filetype != MH_EXECUTE)
  1871.     fatal_with_file ("unsupported Mach-O file type (not MH_OBJECT or MH_EXECUTE) in ", entry);
  1872.   hdrbuf = xmalloc (mach_header.sizeofcmds);
  1873.   len = read (desc, hdrbuf, mach_header.sizeofcmds);
  1874.   if (len != mach_header.sizeofcmds)
  1875.     fatal_with_file ("failure reading Mach-O load commands of ", entry);
  1876.   load_command = (struct load_command *) hdrbuf;
  1877.   for (cmd = 0; cmd < mach_header.ncmds; ++cmd)
  1878.     {
  1879.       switch (load_command->cmd)
  1880.     {
  1881.     case LC_SEGMENT:
  1882.       segment_command = (struct segment_command *) load_command;
  1883.       section = (struct section *) ((char *) (segment_command + 1));
  1884.       for (seg = 0; seg < segment_command->nsects; ++seg, ++section, ++ordinal)
  1885.         {
  1886.           if (!strncmp(SECT_TEXT, section->sectname, sizeof section->sectname))
  1887.         if (entry->text_ordinal)
  1888.           fatal_with_file ("more than one __text section in ", entry);
  1889.         else
  1890.           {
  1891.             entry->text_ordinal = ordinal;
  1892.             entry->orig_text_address = section->addr;
  1893.             entry->text_size = section->size;
  1894.             entry->text_offset = section->offset;
  1895.             entry->text_reloc_size = section->nreloc * sizeof (struct relocation_info);
  1896.             entry->text_reloc_offset = section->reloff;
  1897.           }
  1898.           else if (!strncmp(SECT_DATA, section->sectname, sizeof section->sectname))
  1899.         if (entry->data_ordinal)
  1900.           fatal_with_file ("more than one __data section in ", entry);
  1901.         else
  1902.           {
  1903.             entry->data_ordinal = ordinal;
  1904.             entry->orig_data_address = section->addr;
  1905.             entry->data_size = section->size;
  1906.             entry->data_offset = section->offset;
  1907.             entry->data_reloc_size = section->nreloc * sizeof (struct relocation_info);
  1908.             entry->data_reloc_offset = section->reloff;
  1909.           }
  1910.           else if (!strncmp(SECT_BSS, section->sectname, sizeof section->sectname))
  1911.         if (entry->bss_ordinal)
  1912.           fatal_with_file ("more than one __bss section in ", entry);
  1913.         else
  1914.           {
  1915.             entry->bss_ordinal = ordinal;
  1916.             entry->orig_bss_address = section->addr;
  1917.             entry->bss_size = section->size;
  1918.           }
  1919.           else
  1920.         if (section->size != 0)
  1921.           fprintf (stderr, "%s: warning: unknown section `%.*s' in %s\n",
  1922.                progname, sizeof section->sectname, section->sectname,
  1923.                entry->filename);
  1924.         }
  1925.       break;
  1926.     case LC_SYMTAB:
  1927.       if (symtab_seen)
  1928.           fatal_with_file ("more than one LC_SYMTAB in ", entry);
  1929.       else
  1930.         {
  1931.           symtab_seen = 1;
  1932.           symtab_command = (struct symtab_command *) load_command;
  1933.           entry->syms_size = symtab_command->nsyms * sizeof (struct nlist);
  1934.           entry->syms_offset = symtab_command->symoff;
  1935.           entry->strs_size = symtab_command->strsize;
  1936.           entry->strs_offset = symtab_command->stroff;
  1937.         }
  1938.       break;
  1939. #ifdef LC_SYMSEG
  1940.     case LC_SYMSEG:
  1941.       if (symseg_seen)
  1942.         fatal_with_file ("more than one LC_SYMSEG in ", entry);
  1943.       else
  1944.         {
  1945.           symseg_seen = 1;
  1946.           symseg_command = (struct symseg_command *) load_command;
  1947.           entry->symseg_size = symseg_command->size;
  1948.           entry->symseg_offset = symseg_command->offset;
  1949.         }
  1950.       break;
  1951. #endif
  1952.     }
  1953.       load_command = (struct load_command *)
  1954.     ((char *) load_command + load_command->cmdsize);
  1955.     }
  1956.  
  1957.   free (hdrbuf);
  1958.  
  1959.   if (!symtab_seen)
  1960.     fprintf (stderr, "%s: no symbol table in %s\n", progname, entry->filename);
  1961. }
  1962. #endif
  1963.  
  1964. /* Read a file's header info into the proper place in the file_entry.
  1965.    DESC is the descriptor on which the file is open.
  1966.    ENTRY is the file's entry.
  1967.    Switch in the file_type to determine the appropriate actual
  1968.    header reading routine to call.  */
  1969.  
  1970. void
  1971. read_header (desc, entry)
  1972.      int desc;
  1973.      register struct file_entry *entry;
  1974. {
  1975.   if (!entry->file_type)
  1976.     deduce_file_type (desc, entry);
  1977.  
  1978.   switch (entry->file_type)
  1979.     {
  1980.     case IS_ARCHIVE:
  1981.     default:
  1982.       /* Should never happen. */
  1983.       abort ();
  1984.  
  1985. #ifdef A_OUT
  1986.     case IS_A_OUT:
  1987.       read_a_out_header (desc, entry);
  1988.       break;
  1989. #endif
  1990.  
  1991. #ifdef MACH_O
  1992.     case IS_MACH_O:
  1993.       read_mach_o_header (desc, entry);
  1994.       break;
  1995. #endif
  1996.     }
  1997.  
  1998.   entry->header_read_flag = 1;
  1999. }
  2000.  
  2001. #ifdef MACH_O
  2002. void translate_mach_o_symbols ();
  2003. #endif
  2004.  
  2005. /* Read the symbols of file ENTRY into core.
  2006.    Assume it is already open, on descriptor DESC.  */
  2007.  
  2008. void
  2009. read_entry_symbols (desc, entry)
  2010.      struct file_entry *entry;
  2011.      int desc;
  2012. {
  2013.   int str_size;
  2014.  
  2015.   if (!entry->header_read_flag)
  2016.     read_header (desc, entry);
  2017.  
  2018.   entry->symbols = (struct nlist *) xmalloc (entry->syms_size);
  2019.  
  2020.   lseek (desc, entry->syms_offset + entry->starting_offset, 0);
  2021.   if (entry->syms_size != read (desc, entry->symbols, entry->syms_size))
  2022.     fatal_with_file ("premature end of file in symbols of ", entry);
  2023.  
  2024. #ifdef MACH_O
  2025.   if (entry->file_type == IS_MACH_O)
  2026.     translate_mach_o_symbols (entry);
  2027. #endif
  2028. }
  2029.  
  2030. /* Read the string table of file ENTRY into core.
  2031.    Assume it is already open, on descriptor DESC.  */
  2032.  
  2033. void
  2034. read_entry_strings (desc, entry)
  2035.      struct file_entry *entry;
  2036.      int desc;
  2037. {
  2038.   int buffer;
  2039.  
  2040.   if (!entry->header_read_flag)
  2041.     read_header (desc, entry);
  2042.  
  2043.   lseek (desc, entry->strs_offset + entry->starting_offset, 0);
  2044.   if (entry->strs_size != read (desc, entry->strings, entry->strs_size))
  2045.     fatal_with_file ("premature end of file in strings of ", entry);
  2046. }
  2047.  
  2048. /* Read in the symbols of all input files.  */
  2049.  
  2050. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  2051. void enter_file_symbols (), enter_global_ref (), search_library ();
  2052.  
  2053. void
  2054. load_symbols ()
  2055. {
  2056.   register int i;
  2057.  
  2058.   if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
  2059.  
  2060.   for (i = 0; i < number_of_files; i++)
  2061.     {
  2062.       register struct file_entry *entry = &file_table[i];
  2063.       read_file_symbols (entry);
  2064.     }
  2065.  
  2066.   if (trace_files) fprintf (stderr, "\n");
  2067. }
  2068.  
  2069. /* If ENTRY is a rel file, read its symbol and string sections into core.
  2070.    If it is a library, search it and load the appropriate members
  2071.    (which means calling this function recursively on those members).  */
  2072.  
  2073. void
  2074. read_file_symbols (entry)
  2075.      register struct file_entry *entry;
  2076. {
  2077.   register int desc;
  2078.  
  2079.   desc = file_open (entry);
  2080.  
  2081.   if (!entry->file_type)
  2082.     deduce_file_type (desc, entry);
  2083.  
  2084.   if (entry->file_type == IS_ARCHIVE)
  2085.     {
  2086.       entry->library_flag = 1;
  2087.       search_library (desc, entry);
  2088.     }
  2089.   else
  2090.     {
  2091.       read_entry_symbols (desc, entry);
  2092.       entry->strings = (char *) alloca (entry->strs_size);
  2093.       read_entry_strings (desc, entry);
  2094.       enter_file_symbols (entry);
  2095.       entry->strings = 0;
  2096.     }
  2097.  
  2098.   file_close ();
  2099. }
  2100.  
  2101. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  2102.  
  2103. void
  2104. enter_file_symbols (entry)
  2105.      struct file_entry *entry;
  2106. {
  2107.   register struct nlist
  2108.     *p,
  2109.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2110.  
  2111.   if (trace_files) prline_file_name (entry, stderr);
  2112.  
  2113.   for (p = entry->symbols; p < end; p++)
  2114.     {
  2115.       if (p->n_type == (N_SETV | N_EXT)) continue;
  2116.       if (set_element_prefixes
  2117.       && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
  2118.     p->n_type += (N_SETA - N_ABS);
  2119.  
  2120.       if (SET_ELEMENT_P (p->n_type))
  2121.     {
  2122.       set_symbol_count++;
  2123.       if (output_style != OUTPUT_RELOCATABLE)
  2124.         enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2125.     }
  2126.       else if (p->n_type == N_WARNING)
  2127.     {
  2128.       char *name = p->n_un.n_strx + entry->strings;
  2129.  
  2130.       /* Grab the next entry.  */
  2131.       p++;
  2132.       if (p->n_type != (N_UNDF | N_EXT))
  2133.         {
  2134.           fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
  2135.                progname, entry->filename);
  2136.           make_executable = 0;
  2137.           p--;        /* Process normally.  */
  2138.         }
  2139.       else
  2140.         {
  2141.           symbol *sp;
  2142.           char *sname = p->n_un.n_strx + entry->strings;
  2143.           /* Deal with the warning symbol.  */
  2144.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2145.           sp = getsym (sname);
  2146.           sp->warning = (char *) xmalloc (strlen(name) + 1);
  2147.           strcpy (sp->warning, name);
  2148.           warning_count++;
  2149.         }
  2150.     }
  2151.       else if (p->n_type & N_EXT)
  2152.     enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2153.       else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  2154.     {
  2155.       if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
  2156.         non_L_local_sym_count++;
  2157.       local_sym_count++;
  2158.     }
  2159.       else debugger_sym_count++;
  2160.     }
  2161.  
  2162.    /* Count one for the local symbol that we generate,
  2163.       whose name is the file's name (usually) and whose address
  2164.       is the start of the file's text.  */
  2165.  
  2166.   local_sym_count++;
  2167.   non_L_local_sym_count++;
  2168. }
  2169.  
  2170. /* Enter one global symbol in the hash table.
  2171.    NLIST_P points to the `struct nlist' read from the file
  2172.    that describes the global symbol.  NAME is the symbol's name.
  2173.    ENTRY is the file entry for the file the symbol comes from.
  2174.  
  2175.    The `struct nlist' is modified by placing it on a chain of
  2176.    all such structs that refer to the same global symbol.
  2177.    This chain starts in the `refs' field of the symbol table entry
  2178.    and is chained through the `n_name'.  */
  2179.  
  2180. void
  2181. enter_global_ref (nlist_p, name, entry)
  2182.      register struct nlist *nlist_p;
  2183.      char *name;
  2184.      struct file_entry *entry;
  2185. {
  2186.   register symbol *sp = getsym (name);
  2187.   register int type = nlist_p->n_type;
  2188.   int oldref = sp->referenced;
  2189.   int olddef = sp->defined;
  2190.  
  2191.   nlist_p->n_un.n_name = (char *) sp->refs;
  2192.   sp->refs = nlist_p;
  2193.  
  2194.   sp->referenced = 1;
  2195.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  2196.     {
  2197.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  2198.     sp->defined = type;
  2199.  
  2200.       if (oldref && !olddef)
  2201.     /* It used to be undefined and we're defining it.  */
  2202.     undefined_global_sym_count--;
  2203.  
  2204.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  2205.     {
  2206.       /* First definition and it's common.  */
  2207.       common_defined_global_count++;
  2208.       sp->max_common_size = nlist_p->n_value;
  2209.     }
  2210.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  2211.     {
  2212.       /* It used to be common and we're defining it as
  2213.          something else.  */
  2214.       common_defined_global_count--;
  2215.       sp->max_common_size = 0;
  2216.     }
  2217.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  2218.       && sp->max_common_size < nlist_p->n_value)
  2219.     /* It used to be common and this is a new common entry to
  2220.        which we need to pay attention.  */
  2221.     sp->max_common_size = nlist_p->n_value;
  2222.  
  2223.       /* Are we defining it as a set element?  */
  2224.       if (SET_ELEMENT_P (type)
  2225.       && (!olddef || (olddef && sp->max_common_size)))
  2226.     set_vector_count++;
  2227.       /* As an indirection?  */
  2228.       else if (type == (N_INDR | N_EXT))
  2229.     {
  2230.       /* Indirect symbols value should be modified to point
  2231.          a symbol being equivalenced to. */
  2232.       nlist_p->n_value
  2233. #ifndef NeXT
  2234.         = (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  2235.                      + entry->strings);
  2236. #else
  2237.         /* NeXT also has indirection but they do it weirdly. */
  2238.         = (unsigned int) getsym (nlist_p->n_value + entry->strings);
  2239. #endif
  2240.       if ((symbol *) nlist_p->n_value == sp)
  2241.         {
  2242.           /* Somebody redefined a symbol to be itself.  */
  2243.           fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
  2244.                entry->filename, name);
  2245.           /* Rewrite this symbol as being a global text symbol
  2246.          with value 0.  */
  2247.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  2248.           nlist_p->n_value = 0;
  2249.           /* Don't make the output executable.  */
  2250.           make_executable = 0;
  2251.         }
  2252.       else
  2253.         global_indirect_count++;
  2254.     }
  2255.     }
  2256.   else
  2257.     if (!oldref)
  2258. #ifndef DOLLAR_KLUDGE
  2259.       undefined_global_sym_count++;
  2260. #else
  2261.       {
  2262.     if (entry->superfile && type == (N_UNDF | N_EXT) && name[1] == '$')
  2263.       {
  2264.         /* This is an (ISI?) $-conditional; skip it */
  2265.         sp->referenced = 0;
  2266.         if (sp->trace)
  2267.           {
  2268.         fprintf (stderr, "symbol %s is a $-conditional ignored in ", sp->name);
  2269.         print_file_name (entry, stderr);
  2270.         fprintf (stderr, "\n");
  2271.           }
  2272.         return;
  2273.       }
  2274.     else
  2275.       undefined_global_sym_count++;
  2276.       }
  2277. #endif
  2278.  
  2279.   if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
  2280.     text_start = nlist_p->n_value;
  2281.  
  2282.   if (sp->trace)
  2283.     {
  2284.       register char *reftype;
  2285.       switch (type & ~N_EXT)
  2286.     {
  2287.     case N_UNDF:
  2288.       if (nlist_p->n_value)
  2289.         reftype = "defined as common";
  2290.       else reftype = "referenced";
  2291.       break;
  2292.  
  2293.     case N_ABS:
  2294.       reftype = "defined as absolute";
  2295.       break;
  2296.  
  2297.     case N_TEXT:
  2298.       reftype = "defined in text section";
  2299.       break;
  2300.  
  2301.     case N_DATA:
  2302.       reftype = "defined in data section";
  2303.       break;
  2304.  
  2305.     case N_BSS:
  2306.       reftype = "defined in BSS section";
  2307.       break;
  2308.  
  2309.     case N_SETT:
  2310.       reftype = "is a text set element";
  2311.       break;
  2312.  
  2313.     case N_SETD:
  2314.       reftype = "is a data set element";
  2315.       break;
  2316.  
  2317.     case N_SETB:
  2318.       reftype = "is a BSS set element";
  2319.       break;
  2320.  
  2321.     case N_SETA:
  2322.       reftype = "is an absolute set element";
  2323.       break;
  2324.  
  2325.     case N_SETV:
  2326.       reftype = "defined in data section as vector";
  2327.       break;
  2328.  
  2329.     case N_INDR:
  2330.       reftype = (char *) alloca (23 + strlen (((symbol *) nlist_p->n_value)->name));
  2331.       sprintf (reftype, "defined equivalent to %s",
  2332.            ((symbol *) nlist_p->n_value)->name);
  2333.       break;
  2334.  
  2335. #ifdef sequent
  2336.     case N_SHUNDF:
  2337.       reftype = "shared undf";
  2338.       break;
  2339.  
  2340. /* These conflict with cases above.
  2341.     case N_SHDATA:
  2342.       reftype = "shared data";
  2343.       break;
  2344.  
  2345.     case N_SHBSS:
  2346.       reftype = "shared BSS";
  2347.       break;
  2348. */
  2349. #endif
  2350.  
  2351.     default:
  2352.       reftype = "I don't know this type";
  2353.       break;
  2354.     }
  2355.  
  2356.       fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
  2357.       print_file_name (entry, stderr);
  2358.       fprintf (stderr, "\n");
  2359.     }
  2360. }
  2361.  
  2362. /* This return 0 if the given file entry's symbol table does *not*
  2363.    contain the nlist point entry, and it returns the files entry
  2364.    pointer (cast to unsigned long) if it does. */
  2365.  
  2366. unsigned long
  2367. contains_symbol (entry, n_ptr)
  2368.      struct file_entry *entry;
  2369.      register struct nlist *n_ptr;
  2370. {
  2371.   if (n_ptr >= entry->symbols &&
  2372.       n_ptr < (entry->symbols
  2373.            + (entry->syms_size / sizeof (struct nlist))))
  2374.     return (unsigned long) entry;
  2375.   return 0;
  2376. }
  2377.  
  2378.  
  2379. /* Searching libraries */
  2380.  
  2381. struct file_entry *decode_library_subfile ();
  2382. void linear_library (), symdef_library ();
  2383.  
  2384. /* Search the library ENTRY, already open on descriptor DESC.
  2385.    This means deciding which library members to load,
  2386.    making a chain of `struct file_entry' for those members,
  2387.    and entering their global symbols in the hash table.  */
  2388.  
  2389. void
  2390. search_library (desc, entry)
  2391.      int desc;
  2392.      struct file_entry *entry;
  2393. {
  2394.   int member_length;
  2395.   register char *name;
  2396.   register struct file_entry *subentry;
  2397.  
  2398.   if (!undefined_global_sym_count) return;
  2399.  
  2400.   /* Examine its first member, which starts SARMAG bytes in.  */
  2401.   subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  2402.   if (!subentry) return;
  2403.  
  2404.   name = subentry->filename;
  2405.   free (subentry);
  2406.  
  2407.   /* Search via __.SYMDEF if that exists, else linearly.  */
  2408.  
  2409.   if (!strcmp (name, "__.SYMDEF"))
  2410.     symdef_library (desc, entry, member_length);
  2411.   else
  2412.     linear_library (desc, entry);
  2413. }
  2414.  
  2415. /* Construct and return a file_entry for a library member.
  2416.    The library's file_entry is library_entry, and the library is open on DESC.
  2417.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  2418.    We store the length of the member into *LENGTH_LOC.  */
  2419.  
  2420. struct file_entry *
  2421. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  2422.      int desc;
  2423.      struct file_entry *library_entry;
  2424.      int subfile_offset;
  2425.      int *length_loc;
  2426. {
  2427.   int bytes_read;
  2428.   register int namelen;
  2429.   int member_length;
  2430.   register char *name;
  2431.   struct ar_hdr hdr1;
  2432.   register struct file_entry *subentry;
  2433.  
  2434.   lseek (desc, subfile_offset, 0);
  2435.  
  2436.   bytes_read = read (desc, &hdr1, sizeof hdr1);
  2437.   if (!bytes_read)
  2438.     return 0;        /* end of archive */
  2439.  
  2440.   if (sizeof hdr1 != bytes_read)
  2441.     fatal_with_file ("malformed library archive ", library_entry);
  2442.  
  2443.   if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  2444.     fatal_with_file ("malformatted header of archive member in ", library_entry);
  2445.  
  2446.   subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  2447.   bzero (subentry, sizeof (struct file_entry));
  2448.  
  2449.   for (namelen = 0;
  2450.        namelen < sizeof hdr1.ar_name
  2451.        && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
  2452.        && hdr1.ar_name[namelen] != '/';
  2453.        namelen++);
  2454.  
  2455.   name = (char *) xmalloc (namelen+1);
  2456.   strncpy (name, hdr1.ar_name, namelen);
  2457.   name[namelen] = 0;
  2458.  
  2459.   subentry->filename = name;
  2460.   subentry->local_sym_name = name;
  2461.   subentry->symbols = 0;
  2462.   subentry->strings = 0;
  2463.   subentry->subfiles = 0;
  2464.   subentry->starting_offset = subfile_offset + sizeof hdr1;
  2465.   subentry->superfile = library_entry;
  2466.   subentry->library_flag = 0;
  2467.   subentry->header_read_flag = 0;
  2468.   subentry->just_syms_flag = 0;
  2469.   subentry->chain = 0;
  2470.   subentry->total_size = member_length;
  2471.  
  2472.   (*length_loc) = member_length;
  2473.  
  2474.   return subentry;
  2475. }
  2476.  
  2477. int subfile_wanted_p ();
  2478.  
  2479. /* Search a library that has a __.SYMDEF member.
  2480.    DESC is a descriptor on which the library is open.
  2481.      The file pointer is assumed to point at the __.SYMDEF data.
  2482.    ENTRY is the library's file_entry.
  2483.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  2484.  
  2485. void
  2486. symdef_library (desc, entry, member_length)
  2487.      int desc;
  2488.      struct file_entry *entry;
  2489.      int member_length;
  2490. {
  2491.   int *symdef_data = (int *) xmalloc (member_length);
  2492.   register struct symdef *symdef_base;
  2493.   char *sym_name_base;
  2494.   int number_of_symdefs;
  2495.   int length_of_strings;
  2496.   int not_finished;
  2497.   int bytes_read;
  2498.   register int i;
  2499.   struct file_entry *prev = 0;
  2500.   int prev_offset = 0;
  2501.  
  2502.   bytes_read = read (desc, symdef_data, member_length);
  2503.   if (bytes_read != member_length)
  2504.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2505.  
  2506.   number_of_symdefs = *symdef_data / sizeof (struct symdef);
  2507.   if (number_of_symdefs < 0 ||
  2508.        number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
  2509.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2510.  
  2511.   symdef_base = (struct symdef *) (symdef_data + 1);
  2512.   length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  2513.  
  2514.   if (length_of_strings < 0
  2515.       || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  2516.       + 2 * sizeof (int) != member_length)
  2517.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2518.  
  2519.   sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  2520.  
  2521.   /* Check all the string indexes for validity.  */
  2522.  
  2523.   for (i = 0; i < number_of_symdefs; i++)
  2524.     {
  2525.       register int index = symdef_base[i].symbol_name_string_index;
  2526.       if (index < 0 || index >= length_of_strings
  2527.       || (index && *(sym_name_base + index - 1)))
  2528.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2529.     }
  2530.  
  2531.   /* Search the symdef data for members to load.
  2532.      Do this until one whole pass finds nothing to load.  */
  2533.  
  2534.   not_finished = 1;
  2535.   while (not_finished)
  2536.     {
  2537.       not_finished = 0;
  2538.  
  2539.       /* Scan all the symbols mentioned in the symdef for ones that we need.
  2540.      Load the library members that contain such symbols.  */
  2541.  
  2542.       for (i = 0;
  2543.        (i < number_of_symdefs
  2544.         && (undefined_global_sym_count || common_defined_global_count));
  2545.        i++)
  2546.     if (symdef_base[i].symbol_name_string_index >= 0)
  2547.       {
  2548.         register symbol *sp;
  2549.  
  2550.         sp = getsym_soft (sym_name_base
  2551.                   + symdef_base[i].symbol_name_string_index);
  2552.  
  2553.         /* If we find a symbol that appears to be needed, think carefully
  2554.            about the archive member that the symbol is in.  */
  2555.  
  2556.         if (sp && ((sp->referenced && !sp->defined)
  2557.                || (sp->defined && sp->max_common_size)))
  2558.           {
  2559.         int junk;
  2560.         register int j;
  2561.         register int offset = symdef_base[i].library_member_offset;
  2562.         struct file_entry *subentry;
  2563.  
  2564.         /* Don't think carefully about any archive member
  2565.            more than once in a given pass.  */
  2566.  
  2567.         if (prev_offset == offset)
  2568.           continue;
  2569.         prev_offset = offset;
  2570.  
  2571.         /* Read the symbol table of the archive member.  */
  2572.  
  2573.         subentry = decode_library_subfile (desc, entry, offset, &junk);
  2574.         if (subentry == 0)
  2575.           fatal ("invalid offset for %s in symbol table of %s",
  2576.              sym_name_base
  2577.              + symdef_base[i].symbol_name_string_index,
  2578.              entry->filename);
  2579.         read_entry_symbols (desc, subentry);
  2580.         subentry->strings = xmalloc (subentry->strs_size);
  2581.         read_entry_strings (desc, subentry);
  2582.  
  2583.         /* Now scan the symbol table and decide whether to load.  */
  2584.  
  2585.         if (!subfile_wanted_p (subentry))
  2586.           {
  2587.             free (subentry->symbols);
  2588.             free (subentry->strings);
  2589.             free (subentry);
  2590.           }
  2591.         else
  2592.           {
  2593.             /* This member is needed; load it.
  2594.                Since we are loading something on this pass,
  2595.                we must make another pass through the symdef data.  */
  2596.  
  2597.             not_finished = 1;
  2598.  
  2599.             enter_file_symbols (subentry);
  2600.  
  2601.             if (prev)
  2602.               prev->chain = subentry;
  2603.             else entry->subfiles = subentry;
  2604.             prev = subentry;
  2605.  
  2606.             /* Clear out this member's symbols from the symdef data
  2607.                so that following passes won't waste time on them.  */
  2608.  
  2609.             for (j = 0; j < number_of_symdefs; j++)
  2610.               {
  2611.             if (symdef_base[j].library_member_offset == offset)
  2612.               symdef_base[j].symbol_name_string_index = -1;
  2613.               }
  2614.  
  2615.             /* We'll read the strings again if we need them again.  */
  2616.             free (subentry->strings);
  2617.             subentry->strings = 0;
  2618.           }
  2619.           }
  2620.       }
  2621.     }
  2622.  
  2623.   free (symdef_data);
  2624. }
  2625.  
  2626.  
  2627. /* Handle a subentry for a file with no __.SYMDEF. */
  2628.  
  2629. process_subentry (desc, subentry, entry, prev_addr)
  2630.      int desc;
  2631.      register struct file_entry *subentry;
  2632.      struct file_entry **prev_addr, *entry;
  2633. {
  2634.   read_entry_symbols (desc, subentry);
  2635.   subentry->strings = (char *) alloca (subentry->strs_size);
  2636.   read_entry_strings (desc, subentry);
  2637.  
  2638.   if (!subfile_wanted_p (subentry))
  2639.     {
  2640.       free (subentry->symbols);
  2641.       free (subentry);
  2642.     }
  2643.   else
  2644.     {
  2645.       enter_file_symbols (subentry);
  2646.  
  2647.       if (*prev_addr)
  2648.     (*prev_addr)->chain = subentry;
  2649.       else
  2650.     entry->subfiles = subentry;
  2651.       *prev_addr = subentry;
  2652.       subentry->strings = 0; /* Since space will dissapear on return */
  2653.     }
  2654. }
  2655.  
  2656. /* Search a library that has no __.SYMDEF.
  2657.    ENTRY is the library's file_entry.
  2658.    DESC is the descriptor it is open on.  */
  2659.  
  2660. void
  2661. linear_library (desc, entry)
  2662.      int desc;
  2663.      struct file_entry *entry;
  2664. {
  2665.   struct file_entry *prev = 0;
  2666.   register int this_subfile_offset = SARMAG;
  2667.  
  2668.   while (undefined_global_sym_count || common_defined_global_count)
  2669.     {
  2670.       int member_length;
  2671.       register struct file_entry *subentry;
  2672.  
  2673.       subentry = decode_library_subfile (desc, entry, this_subfile_offset,
  2674.                      &member_length);
  2675.       if (!subentry) return;
  2676.  
  2677.       process_subentry (desc, subentry, entry, &prev);
  2678.       this_subfile_offset += member_length + sizeof (struct ar_hdr);
  2679.       if (this_subfile_offset & 1) this_subfile_offset++;
  2680.     }
  2681. }
  2682.  
  2683. /* ENTRY is an entry for a library member.
  2684.    Its symbols have been read into core, but not entered.
  2685.    Return nonzero if we ought to load this member.  */
  2686.  
  2687. int
  2688. subfile_wanted_p (entry)
  2689.      struct file_entry *entry;
  2690. {
  2691.   register struct nlist *p;
  2692.   register struct nlist *end
  2693.     = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2694. #ifdef DOLLAR_KLUDGE
  2695.   register int dollar_cond = 0;
  2696. #endif
  2697.  
  2698.   for (p = entry->symbols; p < end; p++)
  2699.     {
  2700.       register int type = p->n_type;
  2701.       register char *name = p->n_un.n_strx + entry->strings;
  2702.  
  2703.       /* If the symbol has an interesting definition, we could
  2704.      potentially want it.  */
  2705.       if (type & N_EXT
  2706.       && (type != (N_UNDF | N_EXT) || p->n_value
  2707.  
  2708. #ifdef DOLLAR_KLUDGE
  2709.            || name[1] == '$'
  2710. #endif
  2711.           )
  2712.       && !SET_ELEMENT_P (type)
  2713.       && !set_element_prefixed_p (name))
  2714.     {
  2715.       register symbol *sp = getsym_soft (name);
  2716.  
  2717. #ifdef DOLLAR_KLUDGE
  2718.       if (name[1] == '$')
  2719.         {
  2720.           sp = getsym_soft (&name[2]);
  2721.           dollar_cond = 1;
  2722.           if (!sp) continue;
  2723.           if (sp->referenced)
  2724.         {
  2725.           if (write_map)
  2726.             {
  2727.               print_file_name (entry, stdout);
  2728.               fprintf (stdout, " needed due to $-conditional %s\n", name);
  2729.             }
  2730.           return 1;
  2731.         }
  2732.           continue;
  2733.         }
  2734. #endif
  2735.  
  2736.       /* If this symbol has not been hashed, we can't be looking for it. */
  2737.  
  2738.       if (!sp) continue;
  2739.  
  2740.       if ((sp->referenced && !sp->defined)
  2741.           /* NB.  This needs to be changed so that, e.g., "int pipe;" won't import
  2742.          pipe() from the library.  But the bug fix kingdon made was wrong.  */
  2743.           || (sp->defined && sp->max_common_size))
  2744.         {
  2745.           /* This is a symbol we are looking for.  It is either
  2746.              not yet defined or defined as a common.  */
  2747. #ifdef DOLLAR_KLUDGE
  2748.           if (dollar_cond) continue;
  2749. #endif
  2750.           if (type == (N_UNDF | N_EXT))
  2751.         {
  2752.           /* Symbol being defined as common.
  2753.              Remember this, but don't load subfile just for this.  */
  2754.  
  2755.           /* If it didn't used to be common, up the count of
  2756.              common symbols.  */
  2757.           if (!sp->max_common_size)
  2758.             common_defined_global_count++;
  2759.  
  2760.           if (sp->max_common_size < p->n_value)
  2761.             sp->max_common_size = p->n_value;
  2762.           if (!sp->defined)
  2763.             undefined_global_sym_count--;
  2764.           sp->defined = 1;
  2765.           continue;
  2766.         }
  2767.  
  2768.           if (write_map)
  2769.         {
  2770.           print_file_name (entry, stdout);
  2771.           fprintf (stdout, " needed due to %s\n", sp->name);
  2772.         }
  2773.           return 1;
  2774.         }
  2775.     }
  2776.     }
  2777.  
  2778.   return 0;
  2779. }
  2780.  
  2781. void consider_file_section_lengths (), relocate_file_addresses ();
  2782.  
  2783. /* Having entered all the global symbols and found the sizes of sections
  2784.    of all files to be linked, make all appropriate deductions from this data.
  2785.  
  2786.    We propagate global symbol values from definitions to references.
  2787.    We compute the layout of the output file and where each input file's
  2788.    contents fit into it.  */
  2789.  
  2790. void
  2791. digest_symbols ()
  2792. {
  2793.   register int i;
  2794.   int setv_fill_count;
  2795.  
  2796.   if (trace_files)
  2797.     fprintf (stderr, "Digesting symbol information:\n\n");
  2798.  
  2799.   /* Initialize the text_start address; this depends on the output file formats.  */
  2800.  
  2801.   initialize_text_start ();
  2802.  
  2803.   text_size = text_header_size;
  2804.  
  2805.   /* Compute total size of sections */
  2806.  
  2807.   each_file (consider_file_section_lengths, 0);
  2808.  
  2809.   /* If necessary, pad text section to full page in the file.
  2810.      Include the padding in the text segment size.  */
  2811.  
  2812.   if (output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  2813.     {
  2814.       text_pad = ((text_size + page_size - 1) & (- page_size)) - text_size;
  2815.       text_size += text_pad;
  2816.     }
  2817.  
  2818.   /* Now that the text_size is known, initialize the data start address;
  2819.      this depends on text_size as well as the output file format.  */
  2820.  
  2821.   initialize_data_start ();
  2822.  
  2823.   /* Make sure bss starts out aligned as much as anyone can want.  */
  2824.   {
  2825.     int new_data_size = (data_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  2826.  
  2827.     data_pad += new_data_size - data_size;
  2828.     data_size = new_data_size;
  2829.   }
  2830.  
  2831.   /* Set up the set element vector */
  2832.  
  2833.   if (output_style != OUTPUT_RELOCATABLE)
  2834.     {
  2835.       /* The set sector size is the number of set elements + a word
  2836.          for each symbol for the length word at the beginning of the
  2837.      vector, plus a word for each symbol for a zero at the end of
  2838.      the vector (for incremental linking).  */
  2839.       set_sect_size
  2840.     = (2 * set_symbol_count + set_vector_count) * sizeof (unsigned long);
  2841.       set_sect_start = data_start + data_size;
  2842.       data_size += set_sect_size;
  2843.       set_vectors = (unsigned long *) xmalloc (set_sect_size);
  2844.       setv_fill_count = 0;
  2845.     }
  2846.  
  2847.   /* Compute start addresses of each file's sections and symbols.  */
  2848.  
  2849.   each_full_file (relocate_file_addresses, 0);
  2850.  
  2851.   /* Now, for each symbol, verify that it is defined globally at most once.
  2852.      Put the global value into the symbol entry.
  2853.      Common symbols are allocated here, in the BSS section.
  2854.      Each defined symbol is given a '->defined' field
  2855.       which is the correct N_ code for its definition,
  2856.       except in the case of common symbols with -r.
  2857.      Then make all the references point at the symbol entry
  2858.      instead of being chained together. */
  2859.  
  2860.   defined_global_sym_count = 0;
  2861.  
  2862.   for (i = 0; i < TABSIZE; i++)
  2863.     {
  2864.       register symbol *sp;
  2865.       for (sp = symtab[i]; sp; sp = sp->link)
  2866.     {
  2867.       /* For each symbol */
  2868.       register struct nlist *p, *next;
  2869.       int defs = 0, com = sp->max_common_size;
  2870.       struct nlist *first_definition;
  2871.       for (p = sp->refs; p; p = next)
  2872.         {
  2873.           register int type = p->n_type;
  2874.  
  2875.           if (SET_ELEMENT_P (type))
  2876.         {
  2877.           if (output_style == OUTPUT_RELOCATABLE)
  2878.             fatal ("internal: global ref to set element with -r");
  2879.           if (!defs++)
  2880.             {
  2881.               sp->value = set_sect_start
  2882.             + setv_fill_count++ * sizeof (unsigned long);
  2883.               sp->defined = N_SETV | N_EXT;
  2884.               first_definition = p;
  2885.             }
  2886.           else if ((sp->defined & ~N_EXT) != N_SETV)
  2887.             {
  2888.               sp->multiply_defined = 1;
  2889.               multiple_def_count++;
  2890.             }
  2891.           set_vectors[setv_fill_count++] = p->n_value;
  2892.         }
  2893.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  2894.         {
  2895.           /* non-common definition */
  2896.           if (defs++ && sp->value != p->n_value)
  2897.             {
  2898.               sp->multiply_defined = 1;
  2899.               multiple_def_count++;
  2900.             }
  2901.           sp->value = p->n_value;
  2902.           sp->defined = type;
  2903.           first_definition = p;
  2904.         }
  2905.           next = (struct nlist *) p->n_un.n_name;
  2906.           p->n_un.n_name = (char *) sp;
  2907.         }
  2908.       /* Allocate as common if defined as common and not defined for real */
  2909.       if (com && !defs)
  2910.         {
  2911.           if (output_style != OUTPUT_RELOCATABLE || force_common_definition)
  2912.         {
  2913.           int align = sizeof (int);
  2914.  
  2915.           /* Round up to nearest sizeof (int).  I don't know
  2916.              whether this is necessary or not (given that
  2917.              alignment is taken care of later), but it's
  2918.              traditional, so I'll leave it in.  Note that if
  2919.              this size alignment is ever removed, ALIGN above
  2920.              will have to be initialized to 1 instead of
  2921.              sizeof (int).  */
  2922.  
  2923.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  2924.  
  2925.           while (!(com & align))
  2926.             align <<= 1;
  2927.  
  2928.           align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
  2929.  
  2930.           bss_size = ((((bss_size + data_size + data_start)
  2931.                   + (align - 1)) & (- align))
  2932.                   - data_size - data_start);
  2933.  
  2934.           sp->value = data_start + data_size + bss_size;
  2935.           sp->defined = N_BSS | N_EXT;
  2936.           bss_size += com;
  2937.           if (write_map)
  2938.             printf ("Allocating common %s: %x at %x\n",
  2939.                 sp->name, com, sp->value);
  2940.         }
  2941.           else
  2942.         {
  2943.           sp->defined = 0;
  2944.           undefined_global_sym_count++;
  2945.         }
  2946.         }
  2947.       /* Set length word at front of vector and zero byte at end.
  2948.          Reverse the vector itself to put it in file order.  */
  2949.       if ((sp->defined & ~N_EXT) == N_SETV)
  2950.         {
  2951.           unsigned long length_word_index
  2952.         = (sp->value - set_sect_start) / sizeof (unsigned long);
  2953.           unsigned long i, tmp;
  2954.  
  2955.           set_vectors[length_word_index]
  2956.         = setv_fill_count - 1 - length_word_index;
  2957.  
  2958.           /* Reverse the vector.  */
  2959.           for (i = 1;
  2960.            i < (setv_fill_count - length_word_index - 1) / 2 + 1;
  2961.            i++)
  2962.         {
  2963.           tmp = set_vectors[length_word_index + i];
  2964.           set_vectors[length_word_index + i]
  2965.             = set_vectors[setv_fill_count - i];
  2966.           set_vectors[setv_fill_count - i] = tmp;
  2967.         }
  2968.  
  2969.           set_vectors[setv_fill_count++] = 0;
  2970.         }
  2971.       if (sp->defined)
  2972.         defined_global_sym_count++;
  2973.     }
  2974.     }
  2975.  
  2976.   /* Make sure end of bss is aligned as much as anyone can want.  */
  2977.  
  2978.   bss_size = (bss_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  2979.  
  2980.   /* Give values to _end and friends.  */
  2981.   {
  2982.     int end_value = data_start + data_size + bss_size;
  2983.     if (end_symbol)
  2984.       end_symbol->value = end_value;
  2985.     if (end_symbol_alt)
  2986.       end_symbol_alt->value = end_value;
  2987.   }
  2988.  
  2989.   {
  2990.     int etext_value = text_size + text_start;
  2991.     if (etext_symbol)
  2992.       etext_symbol->value = etext_value;
  2993.     if (etext_symbol_alt)
  2994.       etext_symbol_alt->value = etext_value;
  2995.   }
  2996.  
  2997.   {
  2998.     int edata_value = data_start + data_size;
  2999.     if (edata_symbol)
  3000.       edata_symbol->value = edata_value;
  3001.     if (edata_symbol_alt)
  3002.       edata_symbol_alt->value = edata_value;
  3003.   }
  3004.  
  3005.   /* Figure the data_pad now, so that it overlaps with the bss addresses.  */
  3006.  
  3007.   {
  3008.     /* The amount of data_pad that we are computing now.  This is the
  3009.        part which overlaps with bss.  What was computed previously
  3010.        goes before bss.  */
  3011.     int data_pad_additional = 0;
  3012.     
  3013.     if (specified_data_size && specified_data_size > data_size)
  3014.       data_pad_additional = specified_data_size - data_size;
  3015.  
  3016.     if (output_style == OUTPUT_DEMAND_PAGED)
  3017.       data_pad_additional =
  3018.     ((data_pad_additional + data_size + page_size - 1) & (- page_size)) - data_size;
  3019.  
  3020.     bss_size -= data_pad_additional;
  3021.     if (bss_size < 0) bss_size = 0;
  3022.  
  3023.     data_size += data_pad_additional;
  3024.  
  3025.     data_pad += data_pad_additional;
  3026.   }
  3027. }
  3028.  
  3029. /* Accumulate the section sizes of input file ENTRY
  3030.    into the section sizes of the output file.  */
  3031.  
  3032. void
  3033. consider_file_section_lengths (entry)
  3034.      register struct file_entry *entry;
  3035. {
  3036.   if (entry->just_syms_flag)
  3037.     return;
  3038.  
  3039.   entry->text_start_address = text_size;
  3040.   /* If there were any vectors, we need to chop them off */
  3041.   text_size += entry->text_size;
  3042.   entry->data_start_address = data_size;
  3043.   data_size += entry->data_size;
  3044.   entry->bss_start_address = bss_size;
  3045.   bss_size += entry->bss_size;
  3046.  
  3047.   text_reloc_size += entry->text_reloc_size;
  3048.   data_reloc_size += entry->data_reloc_size;
  3049. }
  3050.  
  3051. /* Determine where the sections of ENTRY go into the output file,
  3052.    whose total section sizes are already known.
  3053.    Also relocate the addresses of the file's local and debugger symbols.  */
  3054.  
  3055. void
  3056. relocate_file_addresses (entry)
  3057.      register struct file_entry *entry;
  3058. {
  3059.   entry->text_start_address += text_start;
  3060.  
  3061.   /* Note that `data_start' and `data_size' have not yet been adjusted
  3062.      for the portion of data_pad which overlaps with bss.  If they had
  3063.      been, we would get the wrong results here.  */
  3064.   entry->data_start_address += data_start;
  3065.   entry->bss_start_address += data_start + data_size;
  3066.  
  3067.   {
  3068.     register struct nlist *p;
  3069.     register struct nlist *end
  3070.       = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3071.  
  3072.     for (p = entry->symbols; p < end; p++)
  3073.       {
  3074.     /* If this belongs to a section, update it by the section's start address */
  3075.     register int type = p->n_type & N_TYPE;
  3076.  
  3077.     switch (type)
  3078.       {
  3079.       case N_TEXT:
  3080.       case N_SETT:
  3081.         p->n_value += entry->text_start_address - entry->orig_text_address;
  3082.         break;
  3083.       case N_DATA:
  3084.       case N_SETV:
  3085.       case N_SETD:
  3086.         /* Data segment symbol.  Subtract the address of the
  3087.            data segment in the input file, and add the address
  3088.            of this input file's data segment in the output file.  */
  3089.         p->n_value +=
  3090.           entry->data_start_address - entry->orig_data_address;
  3091.         break;
  3092.       case N_BSS:
  3093.       case N_SETB:
  3094.         /* likewise for symbols with value in BSS.  */
  3095.         p->n_value += entry->bss_start_address - entry->orig_bss_address;
  3096.         break;
  3097.       }
  3098.       }
  3099.   }
  3100. }
  3101.  
  3102. void describe_file_sections (), list_file_locals ();
  3103.  
  3104. /* Print a complete or partial map of the output file.  */
  3105.  
  3106. void
  3107. print_symbols (outfile)
  3108.      FILE *outfile;
  3109. {
  3110.   register int i;
  3111.  
  3112.   fprintf (outfile, "\nFiles:\n\n");
  3113.  
  3114.   each_file (describe_file_sections, outfile);
  3115.  
  3116.   fprintf (outfile, "\nGlobal symbols:\n\n");
  3117.  
  3118.   for (i = 0; i < TABSIZE; i++)
  3119.     {
  3120.       register symbol *sp;
  3121.       for (sp = symtab[i]; sp; sp = sp->link)
  3122.     {
  3123.       if (sp->defined == 1)
  3124.         fprintf (outfile, "  %s: common, length 0x%x\n", sp->name, sp->max_common_size);
  3125.       if (sp->defined)
  3126.         fprintf (outfile, "  %s: 0x%x\n", sp->name, sp->value);
  3127.       else if (sp->referenced)
  3128.         fprintf (outfile, "  %s: undefined\n", sp->name);
  3129.     }
  3130.     }
  3131.  
  3132.   each_file (list_file_locals, outfile);
  3133. }
  3134.  
  3135. void
  3136. describe_file_sections (entry, outfile)
  3137.      struct file_entry *entry;
  3138.      FILE *outfile;
  3139. {
  3140.   fprintf (outfile, "  ");
  3141.   print_file_name (entry, outfile);
  3142.   if (entry->just_syms_flag)
  3143.     fprintf (outfile, " symbols only\n", 0);
  3144.   else
  3145.     fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
  3146.          entry->text_start_address, entry->text_size,
  3147.          entry->data_start_address, entry->data_size,
  3148.          entry->bss_start_address, entry->bss_size);
  3149. }
  3150.  
  3151. void
  3152. list_file_locals (entry, outfile)
  3153.      struct file_entry *entry;
  3154.      FILE *outfile;
  3155. {
  3156.   register struct nlist
  3157.     *p,
  3158.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3159.  
  3160.   entry->strings = (char *) alloca (entry->strs_size);
  3161.   read_entry_strings (file_open (entry), entry);
  3162.  
  3163.   fprintf (outfile, "\nLocal symbols of ");
  3164.   print_file_name (entry, outfile);
  3165.   fprintf (outfile, ":\n\n");
  3166.  
  3167.   for (p = entry->symbols; p < end; p++)
  3168.     /* If this is a definition,
  3169.        update it if necessary by this file's start address.  */
  3170.     if (!(p->n_type & (N_STAB | N_EXT)))
  3171.       fprintf (outfile, "  %s: 0x%x\n",
  3172.            entry->strings + p->n_un.n_strx, p->n_value);
  3173.  
  3174.   entry->strings = 0;        /* All done with them.  */
  3175. }
  3176.  
  3177.  
  3178. /* Static vars for do_warnings and subroutines of it */
  3179. int list_unresolved_refs;    /* List unresolved refs */
  3180. int list_warning_symbols;    /* List warning syms */
  3181. int list_multiple_defs;        /* List multiple definitions */
  3182.  
  3183. /*
  3184.  * Structure for communication between do_file_warnings and it's
  3185.  * helper routines.  Will in practice be an array of three of these:
  3186.  * 0) Current line, 1) Next line, 2) Source file info.
  3187.  */
  3188. struct line_debug_entry
  3189. {
  3190.   int line;
  3191.   char *filename;
  3192.   struct nlist *sym;
  3193. };
  3194.  
  3195. void qsort ();
  3196. /*
  3197.  * Helper routines for do_file_warnings.
  3198.  */
  3199.  
  3200. /* Return an integer less than, equal to, or greater than 0 as per the
  3201.    relation between the two relocation entries.  Used by qsort.  */
  3202.  
  3203. int
  3204. relocation_entries_relation (rel1, rel2)
  3205.      struct relocation_info *rel1, *rel2;
  3206. {
  3207.   return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
  3208. }
  3209.  
  3210. /* Moves to the next debugging symbol in the file.  USE_DATA_SYMBOLS
  3211.    determines the type of the debugging symbol to look for (DSLINE or
  3212.    SLINE).  STATE_POINTER keeps track of the old and new locatiosn in
  3213.    the file.  It assumes that state_pointer[1] is valid; ie
  3214.    that it.sym points into some entry in the symbol table.  If
  3215.    state_pointer[1].sym == 0, this routine should not be called.  */
  3216.  
  3217. int
  3218. next_debug_entry (use_data_symbols, state_pointer)
  3219.      register int use_data_symbols;
  3220.      /* Next must be passed by reference! */
  3221.      struct line_debug_entry state_pointer[3];
  3222. {
  3223.   register struct line_debug_entry
  3224.     *current = state_pointer,
  3225.     *next = state_pointer + 1,
  3226.     /* Used to store source file */
  3227.     *source = state_pointer + 2;
  3228.   struct file_entry *entry = (struct file_entry *) source->sym;
  3229.  
  3230.   current->sym = next->sym;
  3231.   current->line = next->line;
  3232.   current->filename = next->filename;
  3233.  
  3234.   while (++(next->sym) < (entry->symbols
  3235.               + entry->syms_size/sizeof (struct nlist)))
  3236.     {
  3237.       /* n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, so
  3238.        * may look negative...therefore, must mask to low bits
  3239.        */
  3240.       switch (next->sym->n_type & 0xff)
  3241.     {
  3242.     case N_SLINE:
  3243.       if (use_data_symbols) continue;
  3244.       next->line = next->sym->n_desc;
  3245.       return 1;
  3246.     case N_DSLINE:
  3247.       if (!use_data_symbols) continue;
  3248.       next->line = next->sym->n_desc;
  3249.       return 1;
  3250. #ifdef HAVE_SUN_STABS
  3251.     case N_EINCL:
  3252.       next->filename = source->filename;
  3253.       continue;
  3254. #endif
  3255.     case N_SO:
  3256.       source->filename = next->sym->n_un.n_strx + entry->strings;
  3257.       source->line++;
  3258. #ifdef HAVE_SUN_STABS
  3259.     case N_BINCL:
  3260. #endif
  3261.     case N_SOL:
  3262.       next->filename
  3263.         = next->sym->n_un.n_strx + entry->strings;
  3264.     default:
  3265.       continue;
  3266.     }
  3267.     }
  3268.   next->sym = (struct nlist *) 0;
  3269.   return 0;
  3270. }
  3271.  
  3272. /* Create a structure to save the state of a scan through the debug
  3273.    symbols.  USE_DATA_SYMBOLS is set if we should be scanning for
  3274.    DSLINE's instead of SLINE's.  entry is the file entry which points
  3275.    at the symbols to use.  */
  3276.  
  3277. struct line_debug_entry *
  3278. init_debug_scan (use_data_symbols, entry)
  3279.      int use_data_symbols;
  3280.      struct file_entry *entry;
  3281. {
  3282.   struct line_debug_entry
  3283.     *state_pointer
  3284.       = (struct line_debug_entry *)
  3285.     xmalloc (3 * sizeof (struct line_debug_entry));
  3286.   register struct line_debug_entry
  3287.     *current = state_pointer,
  3288.     *next = state_pointer + 1,
  3289.     *source = state_pointer + 2; /* Used to store source file */
  3290.  
  3291.   struct nlist *tmp;
  3292.  
  3293.   for (tmp = entry->symbols;
  3294.        tmp < (entry->symbols
  3295.           + entry->syms_size/sizeof (struct nlist));
  3296.        tmp++)
  3297.     if (tmp->n_type == (int) N_SO)
  3298.       break;
  3299.  
  3300.   if (tmp >= (entry->symbols
  3301.           + entry->syms_size/sizeof (struct nlist)))
  3302.     {
  3303.       /* I believe this translates to "We lose" */
  3304.       current->filename = next->filename = entry->filename;
  3305.       current->line = next->line = -1;
  3306.       current->sym = next->sym = (struct nlist *) 0;
  3307.       return state_pointer;
  3308.     }
  3309.  
  3310.   next->line = source->line = 0;
  3311.   next->filename = source->filename
  3312.     = (tmp->n_un.n_strx + entry->strings);
  3313.   source->sym = (struct nlist *) entry;
  3314.   next->sym = tmp;
  3315.  
  3316.   next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
  3317.  
  3318.   if (!next->sym)        /* No line numbers for this section; */
  3319.                 /* setup output results as appropriate */
  3320.     {
  3321.       if (source->line)
  3322.     {
  3323.       current->filename = source->filename = entry->filename;
  3324.       current->line = -1;    /* Don't print lineno */
  3325.     }
  3326.       else
  3327.     {
  3328.       current->filename = source->filename;
  3329.       current->line = 0;
  3330.     }
  3331.       return state_pointer;
  3332.     }
  3333.  
  3334.  
  3335.   next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
  3336.  
  3337.   return state_pointer;
  3338. }
  3339.  
  3340. /* Takes an ADDRESS (in either text or data space) and a STATE_POINTER
  3341.    which describes the current location in the implied scan through
  3342.    the debug symbols within the file which ADDRESS is within, and
  3343.    returns the source line number which corresponds to ADDRESS.  */
  3344.  
  3345. int
  3346. address_to_line (address, state_pointer)
  3347.      unsigned long address;
  3348.      /* Next must be passed by reference! */
  3349.      struct line_debug_entry state_pointer[3];
  3350. {
  3351.   struct line_debug_entry
  3352.     *current = state_pointer,
  3353.     *next = state_pointer + 1;
  3354.   struct line_debug_entry *tmp_pointer;
  3355.  
  3356.   int use_data_symbols;
  3357.  
  3358.   if (next->sym)
  3359.     use_data_symbols = (next->sym->n_type & ~N_EXT) == N_DATA;
  3360.   else
  3361.     return current->line;
  3362.  
  3363.   /* Go back to the beginning if we've already passed it.  */
  3364.   if (current->sym->n_value > address)
  3365.     {
  3366.       tmp_pointer = init_debug_scan (use_data_symbols,
  3367.                      (struct file_entry *)
  3368.                      ((state_pointer + 2)->sym));
  3369.       state_pointer[0] = tmp_pointer[0];
  3370.       state_pointer[1] = tmp_pointer[1];
  3371.       state_pointer[2] = tmp_pointer[2];
  3372.       free (tmp_pointer);
  3373.     }
  3374.  
  3375.   /* If we're still in a bad way, return -1, meaning invalid line.  */
  3376.   if (current->sym->n_value > address)
  3377.     return -1;
  3378.  
  3379.   while (next->sym
  3380.      && next->sym->n_value <= address
  3381.      && next_debug_entry (use_data_symbols, state_pointer))
  3382.     ;
  3383.   return current->line;
  3384. }
  3385.  
  3386.  
  3387. /* Macros for manipulating bitvectors.  */
  3388. #define    BIT_SET_P(bv, index)    ((bv)[(index) >> 3] & 1 << ((index) & 0x7))
  3389. #define    SET_BIT(bv, index)    ((bv)[(index) >> 3] |= 1 << ((index) & 0x7))
  3390.  
  3391. /* This routine will scan through the relocation data of file ENTRY,
  3392.    printing out references to undefined symbols and references to
  3393.    symbols defined in files with N_WARNING symbols.  If DATA_SEGMENT
  3394.    is non-zero, it will scan the data relocation segment (and use
  3395.    N_DSLINE symbols to track line number); otherwise it will scan the
  3396.    text relocation segment.  Warnings will be printed on the output
  3397.    stream OUTFILE.  Eventually, every nlist symbol mapped through will
  3398.    be marked in the NLIST_BITVECTOR, so we don't repeat ourselves when
  3399.    we scan the nlists themselves.  */
  3400.  
  3401. do_relocation_warnings (entry, data_segment, outfile, nlist_bitvector)
  3402.      struct file_entry *entry;
  3403.      int data_segment;
  3404.      FILE *outfile;
  3405.      unsigned char *nlist_bitvector;
  3406. {
  3407.   struct relocation_info
  3408.     *reloc_start = data_segment ? entry->datarel : entry->textrel,
  3409.     *reloc;
  3410.   int reloc_size
  3411.     = ((data_segment ? entry->data_reloc_size : entry->text_reloc_size)
  3412.        / sizeof (struct relocation_info));
  3413.   int start_of_segment
  3414.     = (data_segment ? entry->data_start_address : entry->text_start_address);
  3415.   struct nlist *start_of_syms = entry->symbols;
  3416.   struct line_debug_entry *state_pointer
  3417.     = init_debug_scan (data_segment != 0, entry);
  3418.   register struct line_debug_entry *current = state_pointer;
  3419.   /* Assigned to generally static values; should not be written into.  */
  3420.   char *errfmt;
  3421.   /* Assigned to alloca'd values cand copied into; should be freed
  3422.      when done.  */
  3423.   char *errmsg;
  3424.   int invalidate_line_number;
  3425.  
  3426.   /* We need to sort the relocation info here.  Sheesh, so much effort
  3427.      for one lousy error optimization. */
  3428.  
  3429.   qsort (reloc_start, reloc_size, sizeof (struct relocation_info),
  3430.      relocation_entries_relation);
  3431.  
  3432.   for (reloc = reloc_start;
  3433.        reloc < (reloc_start + reloc_size);
  3434.        reloc++)
  3435.     {
  3436.       register struct nlist *s;
  3437.       register symbol *g;
  3438.  
  3439.       /* If the relocation isn't resolved through a symbol, continue */
  3440.       if (!RELOC_EXTERN_P(reloc))
  3441.     continue;
  3442.  
  3443.       s = &(entry->symbols[RELOC_SYMBOL(reloc)]);
  3444.  
  3445.       /* Local symbols shouldn't ever be used by relocation info, so
  3446.      the next should be safe.
  3447.      This is, of course, wrong.  References to local BSS symbols can be
  3448.      the targets of relocation info, and they can (must) be
  3449.      resolved through symbols.  However, these must be defined properly,
  3450.      (the assembler would have caught it otherwise), so we can
  3451.      ignore these cases.  */
  3452.       if (!(s->n_type & N_EXT))
  3453.     continue;
  3454.  
  3455.       g = (symbol *) s->n_un.n_name;
  3456.       errmsg = 0;
  3457.  
  3458.       if (!g->defined && list_unresolved_refs) /* Reference */
  3459.     {
  3460.       /* Mark as being noted by relocation warning pass.  */
  3461.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3462.  
  3463.       if (g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3464.         continue;
  3465.  
  3466.       /* Undefined symbol which we should mention */
  3467.  
  3468.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3469.         {
  3470.           errfmt = "More undefined symbol %s refs follow";
  3471.           invalidate_line_number = 1;
  3472.         }
  3473.       else
  3474.         {
  3475.           errfmt = "Undefined symbol %s referenced from %s segment";
  3476.           invalidate_line_number = 0;
  3477.         }
  3478.     }
  3479.       else                         /* Defined */
  3480.     {
  3481.       /* Potential symbol warning here */
  3482.       if (!g->warning) continue;
  3483.  
  3484.       /* Mark as being noted by relocation warning pass.  */
  3485.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3486.  
  3487.       errfmt = 0;
  3488.       errmsg = g->warning;
  3489.       invalidate_line_number = 0;
  3490.     }
  3491.  
  3492.  
  3493.       /* If errfmt == 0, errmsg has already been defined.  */
  3494.       if (errfmt != 0)
  3495.     {
  3496.       char *nm;
  3497.  
  3498.       if (!demangler || !(nm = (*demangler)(g->name)))
  3499.         nm = g->name;
  3500.       errmsg = xmalloc (strlen (errfmt) + strlen (nm) + 1);
  3501.       sprintf (errmsg, errfmt, nm, data_segment ? "data" : "text");
  3502.       if (nm != g->name)
  3503.         free (nm);
  3504.     }
  3505.  
  3506.       address_to_line (RELOC_ADDRESS (reloc) + start_of_segment,
  3507.                state_pointer);
  3508.  
  3509.       if (current->line >=0)
  3510.     {
  3511.       fprintf (outfile, "%s:%d (", current->filename,
  3512.            invalidate_line_number ? 0 : current->line);
  3513.       print_file_name (entry, outfile);
  3514.       fprintf (outfile, "): %s\n", errmsg);
  3515.     }
  3516.       else
  3517.     {
  3518.       print_file_name(entry, outfile);
  3519.       fprintf(outfile, ": %s\n", errmsg);
  3520.     }
  3521.  
  3522.       if (errfmt != 0)
  3523.     free (errmsg);
  3524.     }
  3525.  
  3526.   free (state_pointer);
  3527. }
  3528.  
  3529. /* Print on OUTFILE a list of all warnings generated by references
  3530.    and/or definitions in the file ENTRY.  List source file and line
  3531.    number if possible, just the .o file if not. */
  3532.  
  3533. void
  3534. do_file_warnings (entry, outfile)
  3535.      struct file_entry *entry;
  3536.      FILE *outfile;
  3537. {
  3538.   int number_of_syms = entry->syms_size / sizeof (struct nlist);
  3539.   unsigned char *nlist_bitvector
  3540.     = (unsigned char *) alloca ((number_of_syms >> 3) + 1);
  3541.   struct line_debug_entry *text_scan, *data_scan;
  3542.   int i;
  3543.   char *errfmt, *file_name;
  3544.   int line_number;
  3545.   int dont_allow_symbol_name;
  3546.  
  3547.   bzero (nlist_bitvector, (number_of_syms >> 3) + 1);
  3548.  
  3549.   /* Read in the files strings if they aren't available */
  3550.   if (!entry->strings)
  3551.     {
  3552.       int desc;
  3553.  
  3554.       entry->strings = (char *) alloca (entry->strs_size);
  3555.       desc = file_open (entry);
  3556.       read_entry_strings (desc, entry);
  3557.     }
  3558.  
  3559.   read_file_relocation (entry);
  3560.  
  3561.   /* Do text warnings based on a scan through the relocation info.  */
  3562.   do_relocation_warnings (entry, 0, outfile, nlist_bitvector);
  3563.  
  3564.   /* Do data warnings based on a scan through the relocation info.  */
  3565.   do_relocation_warnings (entry, 1, outfile, nlist_bitvector);
  3566.  
  3567.   /* Scan through all of the nlist entries in this file and pick up
  3568.      anything that the scan through the relocation stuff didn't.  */
  3569.  
  3570.   text_scan = init_debug_scan (0, entry);
  3571.   data_scan = init_debug_scan (1, entry);
  3572.  
  3573.   for (i = 0; i < number_of_syms; i++)
  3574.     {
  3575.       struct nlist *s;
  3576.       struct glosym *g;
  3577.  
  3578.       s = entry->symbols + i;
  3579.  
  3580.       if (!(s->n_type & N_EXT))
  3581.     continue;
  3582.  
  3583.       g = (symbol *) s->n_un.n_name;
  3584.       dont_allow_symbol_name = 0;
  3585.  
  3586.       if (list_multiple_defs && g->multiply_defined)
  3587.     {
  3588.       errfmt = "Definition of symbol %s (multiply defined)";
  3589.       switch (s->n_type)
  3590.         {
  3591.         case N_TEXT | N_EXT:
  3592.           line_number = address_to_line (s->n_value, text_scan);
  3593.           file_name = text_scan[0].filename;
  3594.           break;
  3595.         case N_DATA | N_EXT:
  3596.           line_number = address_to_line (s->n_value, data_scan);
  3597.           file_name = data_scan[0].filename;
  3598.           break;
  3599.         case N_SETA | N_EXT:
  3600.         case N_SETT | N_EXT:
  3601.         case N_SETD | N_EXT:
  3602.         case N_SETB | N_EXT:
  3603.           if (g->multiply_defined == 2)
  3604.         continue;
  3605.           errfmt = "First set element definition of symbol %s (multiply defined)";
  3606.           break;
  3607.         default:
  3608.           continue;        /* Don't print out multiple defs
  3609.                    at references.  */
  3610.         }
  3611.     }
  3612.       else if (BIT_SET_P (nlist_bitvector, i))
  3613.     continue;
  3614.       else if (list_unresolved_refs && !g->defined)
  3615.     {
  3616.       if (g->undef_refs >= MAX_UREFS_PRINTED)
  3617.         continue;
  3618.  
  3619.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3620.         errfmt = "More undefined \"%s\" refs follow";
  3621.       else
  3622.         errfmt = "Undefined symbol \"%s\" referenced";
  3623.       line_number = -1;
  3624.     }
  3625.       else if (g->warning)
  3626.     {
  3627.       /* There are two cases in which we don't want to
  3628.          do this.  The first is if this is a definition instead of
  3629.          a reference.  The second is if it's the reference used by
  3630.          the warning stabs itself.  */
  3631.       if (s->n_type != (N_EXT | N_UNDF)
  3632.           || (i && (s-1)->n_type == N_WARNING))
  3633.         continue;
  3634.  
  3635.       errfmt = g->warning;
  3636.       line_number = -1;
  3637.       dont_allow_symbol_name = 1;
  3638.     }
  3639.       else
  3640.     continue;
  3641.  
  3642.       if (line_number == -1)
  3643.     {
  3644.       print_file_name (entry, outfile);
  3645.       fprintf (outfile, ": ");
  3646.     }
  3647.       else
  3648.     {
  3649.       fprintf (outfile, "%s:%d (", file_name, line_number);
  3650.       print_file_name (entry, outfile);
  3651.       fprintf (outfile, "): ");
  3652.     }
  3653.  
  3654.       if (dont_allow_symbol_name)
  3655.     fprintf (outfile, "%s", errfmt);
  3656.       else
  3657.     {
  3658.       char *nm;
  3659.  
  3660.       if (!demangler || !(nm = (*demangler)(g->name)))
  3661.         fprintf (outfile, errfmt, g->name);
  3662.       else
  3663.         {
  3664.           fprintf (outfile, errfmt, nm);
  3665.           free (nm);
  3666.         }
  3667.     }
  3668.  
  3669.       fputc ('\n', outfile);
  3670.     }
  3671.   free (text_scan);
  3672.   free (data_scan);
  3673.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  3674. }
  3675.  
  3676. do_warnings (outfile)
  3677.      FILE *outfile;
  3678. {
  3679.   list_unresolved_refs = output_style != OUTPUT_RELOCATABLE && undefined_global_sym_count;
  3680.   list_warning_symbols = warning_count;
  3681.   list_multiple_defs = multiple_def_count != 0;
  3682.  
  3683.   if (!(list_unresolved_refs ||
  3684.     list_warning_symbols ||
  3685.     list_multiple_defs      ))
  3686.     /* No need to run this routine */
  3687.     return;
  3688.  
  3689.   each_file (do_file_warnings, outfile);
  3690.  
  3691.   if (list_unresolved_refs || list_multiple_defs)
  3692.     make_executable = 0;
  3693. }
  3694.  
  3695. #ifdef A_OUT
  3696.  
  3697. /* Stuff pertaining to creating a.out files. */
  3698.  
  3699. /* The a.out header. */
  3700.  
  3701. struct exec outheader;
  3702.  
  3703. #ifdef COFF_ENCAPSULATE
  3704. int need_coff_header;
  3705. struct coffheader coffheader;
  3706. #endif
  3707.  
  3708. /* Compute text_start and text_header_size for an a.out file.  */
  3709.  
  3710. void
  3711. initialize_a_out_text_start ()
  3712. {
  3713.   int magic;
  3714.  
  3715.   switch (output_style)
  3716.     {
  3717.     case OUTPUT_RELOCATABLE:
  3718.     case OUTPUT_WRITABLE_TEXT:
  3719.       magic = OMAGIC;
  3720.       break;
  3721.     case OUTPUT_READONLY_TEXT:
  3722. #ifdef NMAGIC
  3723.       magic = NMAGIC;
  3724.       break;
  3725. #endif
  3726.     case OUTPUT_DEMAND_PAGED:
  3727.       magic = ZMAGIC;
  3728.       break;
  3729.     default:
  3730.       fatal ("unknown output style found (bug in ld)", (char *) 0);
  3731.       break;
  3732.     }
  3733.  
  3734.   /* Determine whether to count the header as part of
  3735.      the text size, and initialize the text size accordingly.
  3736.      This depends on the kind of system and on the output format selected.  */
  3737.   N_SET_MAGIC (outheader, magic);
  3738. #ifdef INITIALIZE_HEADER
  3739.   INITIALIZE_HEADER;
  3740. #endif
  3741.  
  3742.   text_header_size = sizeof (struct exec);
  3743. #ifdef COFF_ENCAPSULATE
  3744.   /* Don't write the coff header for the output of ld -A (since
  3745.      it is not executable by the kernel anyway).  */
  3746.   if (output_style != OUTPUT_RELOCATABLE && !file_table[0].just_syms_flag)
  3747.     {
  3748.       need_coff_header = 1;
  3749.       /* set this flag now, since it will change the values of N_TXTOFF, etc */
  3750.       N_SET_FLAGS (outheader, N_FLAGS_COFF_ENCAPSULATE);
  3751.       text_header_size += sizeof (struct coffheader);
  3752.     }
  3753. #endif
  3754.   if (text_header_size <= N_TXTOFF (outheader))
  3755.     text_header_size = 0;
  3756.   else
  3757.     text_header_size -= N_TXTOFF (outheader);
  3758.  
  3759. #ifdef _N_BASEADDR
  3760.   /* SunOS 4.1 N_TXTADDR depends on the value of outheader.a_entry. */
  3761.   outheader.a_entry = N_PAGSIZ(outheader);
  3762. #endif
  3763.  
  3764.   if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  3765.     text_start = N_TXTADDR (outheader);
  3766. }
  3767.  
  3768. /* Compute data_start once text_size is known. */
  3769.  
  3770. void
  3771. initialize_a_out_data_start ()
  3772. {
  3773.   outheader.a_text = text_size;
  3774. #ifdef sequent
  3775.   outheader.a_text += N_ADDRADJ (outheader);
  3776.   if (entry_symbol == 0)
  3777.     entry_symbol = getsym ("start");
  3778. #endif
  3779.   if (! Tdata_flag_specified)
  3780.     data_start = N_DATADDR (outheader) + text_start - N_TXTADDR (outheader);
  3781. }
  3782.  
  3783. /* Compute offsets of various pieces of the a.out output file.  */
  3784.  
  3785. void
  3786. compute_a_out_section_offsets ()
  3787. {
  3788.   outheader.a_data = data_size;
  3789.   outheader.a_bss = bss_size;
  3790.   outheader.a_entry = (entry_symbol ? entry_symbol->value
  3791.                : text_start + text_header_size);
  3792.  
  3793. #ifdef COFF_ENCAPSULATE
  3794.   if (need_coff_header)
  3795.     {
  3796.       /* We are encapsulating BSD format within COFF format.  */
  3797.       struct coffscn *tp, *dp, *bp;
  3798.  
  3799.       tp = &coffheader.scns[0];
  3800.       dp = &coffheader.scns[1];
  3801.       bp = &coffheader.scns[2];
  3802.  
  3803.       strcpy (tp->s_name, ".text");
  3804.       tp->s_paddr = text_start;
  3805.       tp->s_vaddr = text_start;
  3806.       tp->s_size = text_size;
  3807.       tp->s_scnptr = sizeof (struct coffheader) + sizeof (struct exec);
  3808.       tp->s_relptr = 0;
  3809.       tp->s_lnnoptr = 0;
  3810.       tp->s_nreloc = 0;
  3811.       tp->s_nlnno = 0;
  3812.       tp->s_flags = 0x20;
  3813.       strcpy (dp->s_name, ".data");
  3814.       dp->s_paddr = data_start;
  3815.       dp->s_vaddr = data_start;
  3816.       dp->s_size = data_size;
  3817.       dp->s_scnptr = tp->s_scnptr + tp->s_size;
  3818.       dp->s_relptr = 0;
  3819.       dp->s_lnnoptr = 0;
  3820.       dp->s_nreloc = 0;
  3821.       dp->s_nlnno = 0;
  3822.       dp->s_flags = 0x40;
  3823.       strcpy (bp->s_name, ".bss");
  3824.       bp->s_paddr = dp->s_vaddr + dp->s_size;
  3825.       bp->s_vaddr = bp->s_paddr;
  3826.       bp->s_size = bss_size;
  3827.       bp->s_scnptr = 0;
  3828.       bp->s_relptr = 0;
  3829.       bp->s_lnnoptr = 0;
  3830.       bp->s_nreloc = 0;
  3831.       bp->s_nlnno = 0;
  3832.       bp->s_flags = 0x80;
  3833.  
  3834.       coffheader.f_magic = COFF_MAGIC;
  3835.       coffheader.f_nscns = 3;
  3836.       /* store an unlikely time so programs can
  3837.        * tell that there is a bsd header
  3838.        */
  3839.       coffheader.f_timdat = 1;
  3840.       coffheader.f_symptr = 0;
  3841.       coffheader.f_nsyms = 0;
  3842.       coffheader.f_opthdr = 28;
  3843.       coffheader.f_flags = 0x103;
  3844.       /* aouthdr */
  3845.       coffheader.magic = ZMAGIC;
  3846.       coffheader.vstamp = 0;
  3847.       coffheader.tsize = tp->s_size;
  3848.       coffheader.dsize = dp->s_size;
  3849.       coffheader.bsize = bp->s_size;
  3850.       coffheader.entry = outheader.a_entry;
  3851.       coffheader.text_start = tp->s_vaddr;
  3852.       coffheader.data_start = dp->s_vaddr;
  3853.     }
  3854. #endif
  3855.  
  3856.   if (strip_symbols == STRIP_ALL)
  3857.     nsyms = 0;
  3858.   else
  3859.     {
  3860.       nsyms = (defined_global_sym_count
  3861.            + undefined_global_sym_count);
  3862.       if (discard_locals == DISCARD_L)
  3863.     nsyms += non_L_local_sym_count;
  3864.       else if (discard_locals == DISCARD_NONE)
  3865.     nsyms += local_sym_count;
  3866.       /* One extra for following reference on indirects */
  3867.       if (output_style == OUTPUT_RELOCATABLE)
  3868. #ifndef NeXT
  3869.     nsyms += set_symbol_count + global_indirect_count;
  3870. #else
  3871.         nsyms += set_symbol_count;
  3872. #endif
  3873.     }
  3874.  
  3875.   if (strip_symbols == STRIP_NONE)
  3876.     nsyms += debugger_sym_count;
  3877.  
  3878.   outheader.a_syms = nsyms * sizeof (struct nlist);
  3879.  
  3880.   if (output_style == OUTPUT_RELOCATABLE)
  3881.     {
  3882.       outheader.a_trsize = text_reloc_size;
  3883.       outheader.a_drsize = data_reloc_size;
  3884.     }
  3885.   else
  3886.     {
  3887.       outheader.a_trsize = 0;
  3888.       outheader.a_drsize = 0;
  3889.     }
  3890.  
  3891.   /* Initialize the various file offsets.  */
  3892.  
  3893.   output_text_offset = N_TXTOFF (outheader);
  3894. #ifdef N_DATOFF
  3895.   output_data_offset = N_DATOFF (outheader);
  3896. #else
  3897.   output_data_offset = output_text_offset + text_size;
  3898. #endif
  3899. #ifdef N_TRELOFF
  3900.   output_trel_offset = N_TRELOFF (outheader);
  3901. #else
  3902.   output_trel_offset = output_data_offset + data_size;
  3903. #endif
  3904. #ifdef N_DRELOFF
  3905.   output_drel_offset = N_DRELOFF (outheader);
  3906. #else
  3907.   output_drel_offset = output_trel_offset + text_reloc_size;
  3908. #endif
  3909.   output_syms_offset = N_SYMOFF (outheader);
  3910.   output_strs_offset = N_STROFF (outheader);
  3911. }
  3912.  
  3913. /* Compute more section offsets once the size of the string table is known.  */
  3914.  
  3915. void
  3916. compute_more_a_out_section_offsets ()
  3917. {
  3918.   output_symseg_offset = output_strs_offset + output_strs_size;
  3919. }
  3920.  
  3921. /* Write the a.out header once everything else is known.  */
  3922.  
  3923. void
  3924. write_a_out_header ()
  3925. {
  3926.   lseek (outdesc, 0L, 0);
  3927.  
  3928. #ifdef COFF_ENCAPSULATE
  3929.   if (need_coff_header)
  3930.     mywrite (&coffheader, sizeof coffheader, 1, outdesc);
  3931. #endif
  3932.  
  3933.   mywrite (&outheader, sizeof (struct exec), 1, outdesc);
  3934.  
  3935.   /* Output whatever padding is required in the executable file
  3936.      between the header and the start of the text.  */
  3937.  
  3938. #ifndef COFF_ENCAPSULATE
  3939.   padfile (N_TXTOFF (outheader) - sizeof outheader, outdesc);
  3940. #endif
  3941. }
  3942.  
  3943. #endif
  3944.  
  3945. #ifdef MACH_O
  3946.  
  3947. /* Stuff pertaining to creating Mach-O files. */
  3948.  
  3949. /* Convert the Mach-O style n_sect references into something the rest
  3950.    of the loader can understand.  */
  3951.  
  3952. void
  3953. translate_mach_o_symbols (entry)
  3954.      struct file_entry *entry;
  3955. {
  3956.   int i, n, g;
  3957.   struct nlist *sym;
  3958.  
  3959.   n = entry->syms_size / sizeof (struct nlist);
  3960.   for (i = 0; i < n; ++i)
  3961.     if (((sym = &entry->symbols[i])->n_type & ~N_EXT) == N_SECT)
  3962.       {
  3963.     if (sym->n_sect == entry->text_ordinal)
  3964.       sym->n_type = (sym->n_type & N_EXT) | N_TEXT;
  3965.     else if (sym->n_sect == entry->data_ordinal)
  3966.       sym->n_type = (sym->n_type & N_EXT) | N_DATA;
  3967.     else if (sym->n_sect == entry->bss_ordinal)
  3968.       sym->n_type = (sym->n_type & N_EXT) | N_BSS;
  3969.     else
  3970.       fatal_with_file ("unknown section referenced in symbols of ", entry);
  3971.     sym->n_sect = 0;
  3972.       }
  3973.     else if ((sym = &entry->symbols[i])->n_type == N_SLINE)
  3974.       {
  3975.     if (sym->n_sect == entry->text_ordinal)
  3976.       sym->n_type = N_SLINE;
  3977.     else if (sym->n_sect == entry->data_ordinal)
  3978.       sym->n_type = N_DSLINE;
  3979.     else if (sym->n_sect == entry->bss_ordinal)
  3980.       sym->n_type = N_BSLINE;
  3981.     else
  3982.       fatal_with_file ("unknown section referenced in debugging symbols of ", entry);
  3983.       }
  3984. }
  3985.  
  3986. /* Convert Mach-O style relocation info into a.out style relocation
  3987.    info internally.  */
  3988. void
  3989. translate_mach_o_relocation (entry, reloc, count)
  3990.      struct file_entry *entry;
  3991.      struct relocation_info *reloc;
  3992.      int count;
  3993. {
  3994.   int i;
  3995.  
  3996.   for (i = 0; i < count; ++i)
  3997.     if (!RELOC_EXTERN_P(&reloc[i]))
  3998.       if (RELOC_TYPE(&reloc[i]) == R_ABS)
  3999.     RELOC_TYPE(&reloc[i]) = N_ABS;
  4000.       else if (RELOC_TYPE(&reloc[i]) == entry->text_ordinal)
  4001.     RELOC_TYPE(&reloc[i]) = N_TEXT;
  4002.       else if (RELOC_TYPE(&reloc[i]) == entry->data_ordinal)
  4003.     RELOC_TYPE(&reloc[i]) = N_DATA;
  4004.       else if (RELOC_TYPE(&reloc[i]) == entry->bss_ordinal)
  4005.     RELOC_TYPE(&reloc[i]) = N_BSS;
  4006.       else
  4007.     fatal_with_file ("unknown section ordinal in relocation info of ", entry);
  4008. }
  4009.  
  4010. /* Header structure for OUTPUT_RELOCATABLE.  */
  4011.  
  4012. struct
  4013. {
  4014.   struct mach_header header;
  4015.   struct segment_command segment;
  4016.   struct section text;
  4017.   struct section data;
  4018.   struct section bss;
  4019.   struct symtab_command symtab;
  4020. #ifdef LC_SYMSEG
  4021.   struct symseg_command symseg;
  4022. #endif
  4023. } m_object;
  4024.  
  4025. #ifdef NeXT
  4026. #define CPU_TYPE CPU_TYPE_MC68030
  4027. #define CPU_SUBTYPE CPU_SUBTYPE_NeXT
  4028. #define THREAD_FLAVOR NeXT_THREAD_STATE_REGS
  4029. #define THREAD_COUNT NeXT_THREAD_STATE_REGS_COUNT
  4030. typedef struct NeXT_thread_state_regs thread_state;
  4031. #define thread_state_entry_field pc
  4032. #endif
  4033.  
  4034. /* Header structure for all executable output forms.  */
  4035.  
  4036. struct
  4037. {
  4038.   struct mach_header header;
  4039.   struct segment_command pagezero;
  4040.   struct segment_command text_segment;
  4041.   struct section text;
  4042.   struct segment_command data_segment;
  4043.   struct section data;
  4044.   struct section bss;
  4045.   struct thread_command unixthread;
  4046.   unsigned long int flavor;
  4047.   unsigned long int count;
  4048.   thread_state state;
  4049.   struct symtab_command symtab;
  4050. #ifdef LC_SYMSEG
  4051.   struct symseg_command symseg;
  4052. #endif
  4053. } m_exec;
  4054.  
  4055. /* Compute text_start and text_header_size for an a.out file.  */
  4056.  
  4057. void
  4058. initialize_mach_o_text_start ()
  4059. {
  4060.   if (output_style != OUTPUT_RELOCATABLE)
  4061.     {
  4062.       text_header_size = sizeof m_exec;
  4063.       if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  4064.     /* We reserve the first page of an executable to trap NULL dereferences.  */
  4065.     text_start = page_size;
  4066.     }
  4067. }
  4068.  
  4069. /* Compute data_start once text_size is known.  */
  4070.  
  4071. void
  4072. initialize_mach_o_data_start ()
  4073. {
  4074.   if (! Tdata_flag_specified)
  4075.     data_start = text_start + text_size;
  4076. }
  4077.  
  4078. /* Compute offsets of various pieces of the Mach-O output file.  */
  4079. void
  4080. compute_mach_o_section_offsets ()
  4081. {
  4082.   int header_size, trsize, drsize;
  4083.  
  4084.   switch (output_style)
  4085.     {
  4086.     case OUTPUT_RELOCATABLE:
  4087.       header_size = sizeof m_object;
  4088.       break;
  4089.     default:
  4090.       header_size = sizeof m_exec;
  4091.       break;
  4092.     }
  4093.  
  4094.   if (strip_symbols == STRIP_ALL)
  4095.     nsyms = 0;
  4096.   else
  4097.     {
  4098.       nsyms = (defined_global_sym_count
  4099.            + undefined_global_sym_count);
  4100.       if (discard_locals == DISCARD_L)
  4101.     nsyms += non_L_local_sym_count;
  4102.       else if (discard_locals == DISCARD_NONE)
  4103.     nsyms += local_sym_count;
  4104.       /* One extra for following reference on indirects */
  4105.       if (output_style == OUTPUT_RELOCATABLE)
  4106. #ifndef NeXT
  4107.     nsyms += set_symbol_count + global_indirect_count;
  4108. #else
  4109.         nsyms += set_symbol_count;
  4110. #endif
  4111.     }
  4112.  
  4113.   if (strip_symbols == STRIP_NONE)
  4114.     nsyms += debugger_sym_count;
  4115.  
  4116.   output_text_offset = header_size;
  4117.   output_data_offset = output_text_offset + text_size;
  4118.   output_trel_offset = output_data_offset + data_size;
  4119.   if (output_style == OUTPUT_RELOCATABLE)
  4120.     trsize = text_reloc_size, drsize = data_reloc_size;
  4121.   else
  4122.     trsize = drsize = 0;
  4123.   output_drel_offset = output_trel_offset + trsize;
  4124.   output_syms_offset = output_drel_offset + drsize;
  4125.   output_strs_offset = output_syms_offset + nsyms * sizeof (struct nlist);
  4126. }
  4127.  
  4128. /* Compute more section offsets once the size of the string table is known.  */
  4129. void
  4130. compute_more_mach_o_section_offsets ()
  4131. {
  4132.   output_symseg_offset = output_strs_offset + output_strs_size;
  4133. }
  4134.  
  4135. /* Write the Mach-O header once everything else is known.  */
  4136.  
  4137. void
  4138. write_mach_o_header ()
  4139. {
  4140.   struct mach_header header;
  4141.   struct section text, data, bss;
  4142.   struct symtab_command symtab;
  4143. #ifdef LC_SYMSEG
  4144.   struct symseg_command symseg;
  4145. #endif
  4146.   thread_state state;
  4147.  
  4148.   lseek (outdesc, 0L, 0);
  4149.  
  4150.  
  4151.   header.magic = MH_MAGIC;
  4152.   header.cputype = CPU_TYPE;
  4153.   header.cpusubtype = CPU_SUBTYPE;
  4154.   header.filetype = output_style == OUTPUT_RELOCATABLE ? MH_OBJECT : MH_EXECUTE;
  4155. #ifdef LC_SYMSEG
  4156.   switch (output_style)
  4157.     {
  4158.     case OUTPUT_RELOCATABLE:
  4159.       header.ncmds = 3;
  4160.       header.sizeofcmds = sizeof m_object - sizeof header;
  4161.       break;
  4162.     default:
  4163.       header.ncmds = 6;
  4164.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4165.       break;
  4166.     }
  4167. #else
  4168.   switch (output_style)
  4169.     {
  4170.     case OUTPUT_RELOCATABLE:
  4171.       header.ncmds = 2;
  4172.       header.sizeofcmds = sizeof m_object - sizeof header;
  4173.       break;
  4174.     default:
  4175.       header.ncmds = 5;
  4176.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4177.       break;
  4178.     }
  4179. #endif
  4180.   header.flags = undefined_global_sym_count ? 0 : MH_NOUNDEFS;
  4181.  
  4182.   bzero((char *) &text, sizeof text);
  4183.   strncpy(text.sectname, SECT_TEXT, sizeof text.sectname);
  4184.   strncpy(text.segname, SEG_TEXT, sizeof text.segname);
  4185.   text.addr = text_start;
  4186.   text.size = text_size;
  4187.   text.offset = output_text_offset;
  4188.   text.align = text.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4189.   text.reloff = output_trel_offset;
  4190.   text.nreloc = output_style == OUTPUT_RELOCATABLE
  4191.     ? text_reloc_size / sizeof (struct relocation_info) : 0;
  4192.   text.flags = 0;
  4193.  
  4194.   bzero((char *) &data, sizeof data);
  4195.   strncpy(data.sectname, SECT_DATA, sizeof data.sectname);
  4196.   strncpy(data.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4197.       sizeof data.segname);
  4198.   data.addr = data_start;
  4199.   data.size = data_size;
  4200.   data.offset = output_data_offset;
  4201.   data.align = data.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4202.   data.reloff = output_drel_offset;
  4203.   data.nreloc = output_style == OUTPUT_RELOCATABLE
  4204.     ? data_reloc_size / sizeof (struct relocation_info) : 0;
  4205.   data.flags = 0;
  4206.  
  4207.   bzero((char *) &bss, sizeof bss);
  4208.   strncpy(bss.sectname, SECT_BSS, sizeof data.sectname);
  4209.   strncpy(bss.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4210.       sizeof bss.segname);
  4211.   bss.addr = data_start + data_size;
  4212.   bss.size = bss_size;
  4213.   bss.align = bss.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4214.   bss.reloff = 0;
  4215.   bss.nreloc = 0;
  4216.   bss.flags = S_ZEROFILL;
  4217.  
  4218.   symtab.cmd = LC_SYMTAB;
  4219.   symtab.cmdsize = sizeof symtab;
  4220.   symtab.symoff = output_syms_offset;
  4221.   symtab.nsyms = output_syms_size / sizeof (struct nlist);
  4222.   symtab.stroff = output_strs_offset;
  4223.   symtab.strsize = output_strs_size;
  4224.  
  4225. #ifdef LC_SYMSEG
  4226.   symseg.cmd = LC_SYMSEG;
  4227.   symseg.cmdsize = sizeof symseg;
  4228.   symseg.offset = output_symseg_offset;
  4229.   symseg.size = output_symseg_size;
  4230. #endif
  4231.  
  4232.   switch (output_style)
  4233.     {
  4234.     case OUTPUT_RELOCATABLE:
  4235.       m_object.header = header;
  4236.       m_object.segment.cmd = LC_SEGMENT;
  4237.       m_object.segment.cmdsize = sizeof (struct segment_command) + 3 * sizeof (struct section);
  4238.       strncpy(m_object.segment.segname, SEG_TEXT, sizeof m_object.segment.segname);
  4239.       m_object.segment.vmaddr = 0;
  4240.       m_object.segment.vmsize = text.size + data.size + bss.size;
  4241.       m_object.segment.fileoff = text.offset;
  4242.       m_object.segment.filesize = text.size + data.size;
  4243.       m_object.segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4244.       m_object.segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4245.       m_object.segment.nsects = 3;
  4246.       m_object.segment.flags = 0;
  4247.       m_object.text = text;
  4248.       m_object.data = data;
  4249.       m_object.bss = bss;
  4250.       m_object.symtab = symtab;
  4251. #ifdef LC_SYMSEG
  4252.       m_object.symseg = symseg;
  4253. #endif
  4254.       mywrite((char *) &m_object, 1, sizeof m_object, outdesc);
  4255.       break;
  4256.  
  4257.     default:
  4258.       m_exec.header = header;
  4259.       m_exec.pagezero.cmd = LC_SEGMENT;
  4260.       m_exec.pagezero.cmdsize = sizeof (struct segment_command);
  4261.       strncpy(m_exec.pagezero.segname, SEG_PAGEZERO, sizeof m_exec.pagezero.segname);
  4262.       m_exec.pagezero.vmaddr = 0;
  4263.       m_exec.pagezero.vmsize = page_size;
  4264.       m_exec.pagezero.fileoff = 0;
  4265.       m_exec.pagezero.filesize = 0;
  4266.       m_exec.pagezero.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4267.       m_exec.pagezero.initprot = 0;
  4268.       m_exec.pagezero.nsects = 0;
  4269.       m_exec.pagezero.flags = 0;
  4270.       m_exec.text_segment.cmd = LC_SEGMENT;
  4271.       m_exec.text_segment.cmdsize = sizeof (struct segment_command) + sizeof (struct section);
  4272.       strncpy(m_exec.text_segment.segname, SEG_TEXT, sizeof m_exec.text_segment.segname);
  4273.       m_exec.text_segment.vmaddr = text_start;
  4274.       m_exec.text_segment.vmsize = text_size;
  4275.       m_exec.text_segment.fileoff = output_text_offset;
  4276.       m_exec.text_segment.filesize = text_size;
  4277.       m_exec.text_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4278.       m_exec.text_segment.initprot = VM_PROT_READ | VM_PROT_EXECUTE;
  4279.       if (output_style == OUTPUT_WRITABLE_TEXT)
  4280.     m_exec.text_segment.initprot |= VM_PROT_WRITE;
  4281.       m_exec.text_segment.nsects = 1;
  4282.       m_exec.text_segment.flags = 0;
  4283.       m_exec.text = text;
  4284.       m_exec.data_segment.cmd = LC_SEGMENT;
  4285.       m_exec.data_segment.cmdsize = sizeof (struct segment_command) + 2 * sizeof (struct section);
  4286.       strncpy(m_exec.data_segment.segname, SEG_DATA, sizeof m_exec.data_segment.segname);
  4287.       m_exec.data_segment.vmaddr = data_start;
  4288.       m_exec.data_segment.vmsize = data_size + bss_size;
  4289.       m_exec.data_segment.fileoff = output_data_offset;
  4290.       m_exec.data_segment.filesize = data_size;
  4291.       m_exec.data_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4292.       m_exec.data_segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4293.       m_exec.data_segment.nsects = 2;
  4294.       m_exec.data_segment.flags = 0;
  4295.       m_exec.data = data;
  4296.       m_exec.bss = bss;
  4297.       m_exec.unixthread.cmd = LC_UNIXTHREAD;
  4298.       m_exec.unixthread.cmdsize
  4299.     = sizeof (struct thread_command) + 2 * sizeof (long int) + sizeof (thread_state);
  4300.       m_exec.flavor = THREAD_FLAVOR;
  4301.       m_exec.count = THREAD_COUNT;
  4302.       m_exec.state.thread_state_entry_field = entry_symbol
  4303.     ? entry_symbol->value : text_start + text_header_size;
  4304.       m_exec.symtab = symtab;
  4305. #ifdef LC_SYMSEG
  4306.       m_exec.symseg = symseg;
  4307. #endif
  4308.       mywrite((char *) &m_exec, 1, sizeof m_exec, outdesc);
  4309.       break;
  4310.     }
  4311. }
  4312.  
  4313. /* Translate a.out style symbols into Mach-O style symbols.  */
  4314.  
  4315. void
  4316. generate_mach_o_symbols (syms, nsyms)
  4317.      struct nlist *syms;
  4318.      int nsyms;
  4319. {
  4320.   int i;
  4321.  
  4322.   for (i = 0; i < nsyms; ++i)
  4323.     switch (syms[i].n_type)
  4324.       {
  4325.       case N_TEXT:
  4326.       case N_TEXT | N_EXT:
  4327.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4328.     syms[i].n_sect = 1;    /* text section ordinal */
  4329.     break;
  4330.       case N_DATA:
  4331.       case N_DATA | N_EXT:
  4332.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4333.     syms[i].n_sect = 2;    /* data section ordinal */
  4334.     break;
  4335.       case N_BSS:
  4336.       case N_BSS | N_EXT:
  4337.     syms[i].n_type = syms[i].n_type & N_EXT | N_BSS;
  4338.     syms[i].n_sect = 3;    /* bss section ordinal */
  4339.     break;
  4340.       case N_SLINE:
  4341.     syms[i].n_type = N_SLINE;
  4342.     syms[i].n_sect = 1;    /* text section ordinal */
  4343.     break;
  4344.       case N_DSLINE:
  4345.     syms[i].n_type = N_SLINE;
  4346.     syms[i].n_sect = 2;    /* data section ordinal */
  4347.     break;
  4348.       case N_BSLINE:
  4349.     syms[i].n_type = N_SLINE;
  4350.     syms[i].n_sect = 3;    /* bss section ordinal */
  4351.     break;
  4352.       }
  4353. }
  4354.  
  4355. /* Translate a.out style relocation info into Mach-O style relocation
  4356.    info.  */
  4357.  
  4358. void
  4359. generate_mach_o_relocations (reloc, nreloc)
  4360.      struct relocation_info *reloc;
  4361.      int nreloc;
  4362. {
  4363.   int i;
  4364.  
  4365.   for (i = 0; i < nreloc; ++i)
  4366.     if (!RELOC_EXTERN_P (&reloc[i]))
  4367.       switch (RELOC_TYPE (&reloc[i]))
  4368.     {
  4369.     case N_ABS:
  4370.     case N_ABS | N_EXT:
  4371.       RELOC_TYPE (&reloc[i]) = R_ABS;
  4372.       break;
  4373.     case N_TEXT:
  4374.     case N_TEXT | N_EXT:
  4375.       RELOC_TYPE (&reloc[i]) = 1; /* output text section ordinal */
  4376.       break;
  4377.     case N_DATA:
  4378.     case N_DATA | N_EXT:
  4379.       RELOC_TYPE (&reloc[i]) = 2; /* output data section ordinal */
  4380.       break;
  4381.     case N_BSS:
  4382.     case N_BSS | N_EXT:
  4383.       RELOC_TYPE (&reloc[i]) = 3; /* output bss section ordinal */
  4384.       break;
  4385.     }
  4386. }
  4387.  
  4388. #endif
  4389.  
  4390. /* The following functions are simple switches according to the
  4391.    output style.  */
  4392.  
  4393. /* Compute text_start and text_header_size as appropriate for the
  4394.    output format.  */
  4395.  
  4396. void
  4397. initialize_text_start ()
  4398. {
  4399. #ifdef A_OUT
  4400.   if (output_file_type == IS_A_OUT)
  4401.     {
  4402.       initialize_a_out_text_start ();
  4403.       return;
  4404.     }
  4405. #endif
  4406. #ifdef MACH_O
  4407.   if (output_file_type == IS_MACH_O)
  4408.     {
  4409.       initialize_mach_o_text_start ();
  4410.       return;
  4411.     }
  4412. #endif
  4413.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4414. }
  4415.  
  4416. /* Initialize data_start as appropriate to the output format, once text_size
  4417.    is known.  */
  4418.  
  4419. void
  4420. initialize_data_start ()
  4421. {
  4422. #ifdef A_OUT
  4423.   if (output_file_type == IS_A_OUT)
  4424.     {
  4425.       initialize_a_out_data_start ();
  4426.       return;
  4427.     }
  4428. #endif
  4429. #ifdef MACH_O
  4430.   if (output_file_type == IS_MACH_O)
  4431.     {
  4432.       initialize_mach_o_data_start ();
  4433.       return;
  4434.     }
  4435. #endif
  4436.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4437. }
  4438.  
  4439. /* Compute offsets of the various sections within the output file.  */
  4440.  
  4441. void
  4442. compute_section_offsets ()
  4443. {
  4444. #ifdef A_OUT
  4445.   if (output_file_type == IS_A_OUT)
  4446.     {
  4447.       compute_a_out_section_offsets ();
  4448.       return;
  4449.     }
  4450. #endif
  4451. #ifdef MACH_O
  4452.   if (output_file_type == IS_MACH_O)
  4453.     {
  4454.       compute_mach_o_section_offsets ();
  4455.       return;
  4456.     }
  4457. #endif
  4458.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4459. }
  4460.  
  4461. /* Compute more section offsets, once the size of the string table
  4462.    is finalized.  */
  4463. void
  4464. compute_more_section_offsets ()
  4465. {
  4466. #ifdef A_OUT
  4467.   if (output_file_type == IS_A_OUT)
  4468.     {
  4469.       compute_more_a_out_section_offsets ();
  4470.       return;
  4471.     }
  4472. #endif
  4473. #ifdef MACH_O
  4474.   if (output_file_type == IS_MACH_O)
  4475.     {
  4476.       compute_more_mach_o_section_offsets ();
  4477.       return;
  4478.     }
  4479. #endif
  4480.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4481. }
  4482.  
  4483. /* Write the output file header, once everything is known.  */
  4484. void
  4485. write_header ()
  4486. {
  4487. #ifdef A_OUT
  4488.   if (output_file_type == IS_A_OUT)
  4489.     {
  4490.       write_a_out_header ();
  4491.       return;
  4492.     }
  4493. #endif
  4494. #ifdef MACH_O
  4495.   if (output_file_type == IS_MACH_O)
  4496.     {
  4497.       write_mach_o_header ();
  4498.       return;
  4499.     }
  4500. #endif
  4501.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4502. }
  4503.  
  4504. /* Write the output file */
  4505.  
  4506. void
  4507. write_output ()
  4508. {
  4509.   struct stat statbuf;
  4510.   int filemode, mask;
  4511.  
  4512.   /* Remove the old file in case it is owned by someone else.
  4513.      This prevents spurious "not owner" error messages.
  4514.      Don't check for errors from unlink; we don't really care
  4515.      whether it worked.
  4516.  
  4517.      Note that this means that if the output file is hard linked,
  4518.      the other names will still have the old contents.  This is
  4519.      the way Unix ld works; I'm going to consider it a feature.  */
  4520.   (void) unlink (output_filename);
  4521.   
  4522.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4523.   if (outdesc < 0) perror_name (output_filename);
  4524.  
  4525.   if (fstat (outdesc, &statbuf) < 0)
  4526.     perror_name (output_filename);
  4527.  
  4528.   filemode = statbuf.st_mode;
  4529.  
  4530.   chmod (output_filename, filemode & ~0111);
  4531.  
  4532.   /* Calculate the offsets of the various pieces of the output file.  */
  4533.   compute_section_offsets ();
  4534.  
  4535.   /* Output the text and data segments, relocating as we go.  */
  4536.   write_text ();
  4537.   write_data ();
  4538.  
  4539.   /* Output the merged relocation info, if requested with `-r'.  */
  4540.   if (output_style == OUTPUT_RELOCATABLE)
  4541.     write_rel ();
  4542.  
  4543.   /* Output the symbol table (both globals and locals).  */
  4544.   write_syms ();
  4545.  
  4546.   /* At this point the total size of the symbol table and string table
  4547.      are finalized.  */
  4548.   compute_more_section_offsets ();
  4549.  
  4550.   /* Copy any GDB symbol segments from input files.  */
  4551.   write_symsegs ();
  4552.  
  4553.   /* Now that everything is known about the output file, write its header.  */
  4554.   write_header ();
  4555.  
  4556.   close (outdesc);
  4557.  
  4558.   mask = umask (0);
  4559.   umask (mask);
  4560.  
  4561.   if (chmod (output_filename, filemode | (0111 & ~mask)) == -1)
  4562.     perror_name (output_filename);
  4563. }
  4564.  
  4565. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  4566.  
  4567. /* Relocate the text segment of each input file
  4568.    and write to the output file.  */
  4569.  
  4570. void
  4571. write_text ()
  4572. {
  4573.   if (trace_files)
  4574.     fprintf (stderr, "Copying and relocating text:\n\n");
  4575.  
  4576.   lseek (outdesc, output_text_offset + text_header_size, 0);
  4577.  
  4578.   each_full_file (copy_text, 0);
  4579.   file_close ();
  4580.  
  4581.   if (trace_files)
  4582.     fprintf (stderr, "\n");
  4583.  
  4584.   padfile (text_pad, outdesc);
  4585. }
  4586.  
  4587. /* Read in all of the relocation information */
  4588.  
  4589. void
  4590. read_relocation ()
  4591. {
  4592.   each_full_file (read_file_relocation, 0);
  4593. }
  4594.  
  4595. /* Read in the relocation sections of ENTRY if necessary */
  4596.  
  4597. void
  4598. read_file_relocation (entry)
  4599.      struct file_entry *entry;
  4600. {
  4601.   register struct relocation_info *reloc;
  4602.   int desc;
  4603.   int read_return;
  4604.  
  4605.   desc = -1;
  4606.   if (!entry->textrel)
  4607.     {
  4608.       reloc = (struct relocation_info *) xmalloc (entry->text_reloc_size);
  4609.       desc = file_open (entry);
  4610.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4611.       if (entry->text_reloc_size != (read_return = read (desc, reloc, entry->text_reloc_size)))
  4612.     {
  4613.       fprintf (stderr, "Return from read: %d\n", read_return);
  4614.       fatal_with_file ("premature eof in text relocation of ", entry);
  4615.     }
  4616.       entry->textrel = reloc;
  4617.     }
  4618.  
  4619.   if (!entry->datarel)
  4620.     {
  4621.       reloc = (struct relocation_info *) xmalloc (entry->data_reloc_size);
  4622.       if (desc == -1) desc = file_open (entry);
  4623.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  4624.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  4625.     fatal_with_file ("premature eof in data relocation of ", entry);
  4626.       entry->datarel = reloc;
  4627.     }
  4628.  
  4629. #ifdef MACH_O
  4630.   if (entry->file_type == IS_MACH_O)
  4631.     {
  4632.       translate_mach_o_relocation (entry, entry->textrel,
  4633.                    entry->text_reloc_size / sizeof (struct relocation_info));
  4634.       translate_mach_o_relocation (entry, entry->datarel,
  4635.                    entry->data_reloc_size / sizeof (struct relocation_info));
  4636.     }
  4637. #endif
  4638. }
  4639.  
  4640. /* Read the text segment contents of ENTRY, relocate them,
  4641.    and write the result to the output file.
  4642.    If `-r', save the text relocation for later reuse.  */
  4643.  
  4644. void
  4645. copy_text (entry)
  4646.      struct file_entry *entry;
  4647. {
  4648.   register char *bytes;
  4649.   register int desc;
  4650.   register struct relocation_info *reloc;
  4651.  
  4652.   if (trace_files)
  4653.     prline_file_name (entry, stderr);
  4654.  
  4655.   desc = file_open (entry);
  4656.  
  4657.   /* Allocate space for the file's text section */
  4658.  
  4659.   bytes = (char *) alloca (entry->text_size);
  4660.  
  4661.   /* Deal with relocation information however is appropriate */
  4662.  
  4663.   if (entry->textrel)  reloc = entry->textrel;
  4664.   else if (output_style == OUTPUT_RELOCATABLE)
  4665.     {
  4666.       read_file_relocation (entry);
  4667.       reloc = entry->textrel;
  4668.     }
  4669.   else
  4670.     {
  4671.       reloc = (struct relocation_info *) alloca (entry->text_reloc_size);
  4672.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4673.       if (entry->text_reloc_size != read (desc, reloc, entry->text_reloc_size))
  4674.     fatal_with_file ("premature eof in text relocation of ", entry);
  4675. #ifdef MACH_O
  4676.       if (entry->file_type == IS_MACH_O)
  4677.     translate_mach_o_relocation (entry, reloc,
  4678.                      entry->text_reloc_size / sizeof (struct relocation_info));
  4679. #endif
  4680.     }
  4681.  
  4682.   /* Read the text section into core.  */
  4683.  
  4684.   lseek (desc, entry->starting_offset + entry->text_offset, L_SET);
  4685.   if (entry->text_size != read (desc, bytes, entry->text_size))
  4686.     fatal_with_file ("premature eof in text section of ", entry);
  4687.  
  4688.   /* Relocate the text according to the text relocation.  */
  4689.  
  4690.   perform_relocation (bytes, entry->text_start_address - entry->orig_text_address,
  4691.               entry->text_size, reloc, entry->text_reloc_size, entry);
  4692.  
  4693.   /* Write the relocated text to the output file.  */
  4694.  
  4695.   mywrite (bytes, 1, entry->text_size, outdesc);
  4696. }
  4697.  
  4698. /* Relocate the data segment of each input file
  4699.    and write to the output file.  */
  4700.  
  4701. void
  4702. write_data ()
  4703. {
  4704.   if (trace_files)
  4705.     fprintf (stderr, "Copying and relocating data:\n\n");
  4706.  
  4707.   lseek (outdesc, output_data_offset, 0);
  4708.  
  4709.   each_full_file (copy_data, 0);
  4710.   file_close ();
  4711.  
  4712.   /* Write out the set element vectors.  See digest symbols for
  4713.      description of length of the set vector section.  */
  4714.  
  4715.   if (set_vector_count)
  4716.     mywrite (set_vectors, 2 * set_symbol_count + set_vector_count,
  4717.          sizeof (unsigned long), outdesc);
  4718.  
  4719.   if (trace_files)
  4720.     fprintf (stderr, "\n");
  4721.  
  4722.   padfile (data_pad, outdesc);
  4723. }
  4724.  
  4725. /* Read the data segment contents of ENTRY, relocate them,
  4726.    and write the result to the output file.
  4727.    If `-r', save the data relocation for later reuse.
  4728.    See comments in `copy_text'.  */
  4729.  
  4730. void
  4731. copy_data (entry)
  4732.      struct file_entry *entry;
  4733. {
  4734.   register struct relocation_info *reloc;
  4735.   register char *bytes;
  4736.   register int desc;
  4737.  
  4738.   if (trace_files)
  4739.     prline_file_name (entry, stderr);
  4740.  
  4741.   desc = file_open (entry);
  4742.  
  4743.   bytes = (char *) alloca (entry->data_size);
  4744.  
  4745.   if (entry->datarel) reloc = entry->datarel;
  4746.   else if (output_style == OUTPUT_RELOCATABLE)    /* Will need this again */
  4747.     {
  4748.       read_file_relocation (entry);
  4749.       reloc = entry->datarel;
  4750.     }
  4751.   else
  4752.     {
  4753.       reloc = (struct relocation_info *) alloca (entry->data_reloc_size);
  4754.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  4755.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  4756.     fatal_with_file ("premature eof in data relocation of ", entry);
  4757. #ifdef MACH_O
  4758.       if (entry->file_type == IS_MACH_O)
  4759.     translate_mach_o_relocation (entry, reloc,
  4760.                      entry->data_reloc_size / sizeof (struct relocation_info));
  4761. #endif
  4762.     }
  4763.  
  4764.   lseek (desc, entry->starting_offset + entry->data_offset, L_SET);
  4765.   if (entry->data_size != read (desc, bytes, entry->data_size))
  4766.     fatal_with_file ("premature eof in data section of ", entry);
  4767.  
  4768.   perform_relocation (bytes, entry->data_start_address - entry->orig_data_address,
  4769.               entry->data_size, reloc, entry->data_reloc_size, entry);
  4770.  
  4771.   mywrite (bytes, 1, entry->data_size, outdesc);
  4772. }
  4773.  
  4774. /* Relocate ENTRY's text or data section contents.
  4775.    DATA is the address of the contents, in core.
  4776.    DATA_SIZE is the length of the contents.
  4777.    PC_RELOCATION is the difference between the address of the contents
  4778.      in the output file and its address in the input file.
  4779.    RELOC_INFO is the address of the relocation info, in core.
  4780.    RELOC_SIZE is its length in bytes.  */
  4781. /* This version is about to be severly hacked by Randy.  Hope it
  4782.    works afterwards. */
  4783. void
  4784. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  4785.      char *data;
  4786.      struct relocation_info *reloc_info;
  4787.      struct file_entry *entry;
  4788.      int pc_relocation;
  4789.      int data_size;
  4790.      int reloc_size;
  4791. {
  4792.   register struct relocation_info *p = reloc_info;
  4793.   struct relocation_info *end
  4794.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  4795.   int text_relocation = entry->text_start_address - entry->orig_text_address;
  4796.   int data_relocation = entry->data_start_address - entry->orig_data_address;
  4797.   int bss_relocation = entry->bss_start_address - entry->orig_bss_address;
  4798.  
  4799.   for (; p < end; p++)
  4800.     {
  4801.       register int relocation = 0;
  4802.       register int addr = RELOC_ADDRESS(p);
  4803.       register unsigned int mask = 0;
  4804.  
  4805.       if (addr >= data_size)
  4806.     fatal_with_file ("relocation address out of range in ", entry);
  4807.  
  4808.       if (RELOC_EXTERN_P(p))
  4809.     {
  4810.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  4811.       symbol *sp = ((symbol *)
  4812.             (((struct nlist *)
  4813.               (((char *)entry->symbols) + symindex))
  4814.              ->n_un.n_name));
  4815.  
  4816. #ifdef N_INDR
  4817.       /* Resolve indirection */
  4818.       if ((sp->defined & ~N_EXT) == N_INDR)
  4819.         sp = (symbol *) sp->value;
  4820. #endif
  4821.  
  4822.       if (symindex >= entry->syms_size)
  4823.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  4824.  
  4825.       /* If the symbol is undefined, leave it at zero.  */
  4826.       if (! sp->defined)
  4827.         relocation = 0;
  4828.       else
  4829.         relocation = sp->value;
  4830.     }
  4831.       else switch (RELOC_TYPE(p))
  4832.     {
  4833.     case N_TEXT:
  4834.     case N_TEXT | N_EXT:
  4835.       relocation = text_relocation;
  4836.       break;
  4837.  
  4838.     case N_DATA:
  4839.     case N_DATA | N_EXT:
  4840.       relocation = data_relocation;
  4841.       break;
  4842.  
  4843.     case N_BSS:
  4844.     case N_BSS | N_EXT:
  4845.       relocation = bss_relocation;
  4846.       break;
  4847.  
  4848.     case N_ABS:
  4849.     case N_ABS | N_EXT:
  4850.       /* Don't know why this code would occur, but apparently it does.  */
  4851.       break;
  4852.  
  4853.     default:
  4854.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  4855.     }
  4856.  
  4857.       if (RELOC_PCREL_P(p))
  4858.     relocation -= pc_relocation;
  4859.  
  4860. #ifdef RELOC_ADD_EXTRA
  4861.       relocation += RELOC_ADD_EXTRA(p);
  4862.       if (output_style == OUTPUT_RELOCATABLE)
  4863.     {
  4864.       /* If this RELOC_ADD_EXTRA is 0, it means that the
  4865.          symbol was external and the relocation does not
  4866.          need a fixup here.  */
  4867.       if (RELOC_ADD_EXTRA (p))
  4868.         {
  4869.           if (! RELOC_PCREL_P (p))
  4870.         RELOC_ADD_EXTRA (p) = relocation;
  4871.           else
  4872.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  4873.         }
  4874. #if 0
  4875.       if (! RELOC_PCREL_P (p))
  4876.         {
  4877.           if ((int)p->r_type <= RELOC_32
  4878.           || RELOC_EXTERN_P (p) == 0)
  4879.         RELOC_ADD_EXTRA (p) = relocation;
  4880.         }
  4881.       else if (RELOC_EXTERN_P (p))
  4882.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  4883. #endif
  4884.       continue;
  4885.     }
  4886. #endif
  4887.  
  4888.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  4889.  
  4890.       /* Unshifted mask for relocation */
  4891.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  4892.       mask |= mask - 1;
  4893.       relocation &= mask;
  4894.  
  4895.       /* Shift everything up to where it's going to be used */
  4896.       relocation <<= RELOC_TARGET_BITPOS(p);
  4897.       mask <<= RELOC_TARGET_BITPOS(p);
  4898.  
  4899.       switch (RELOC_TARGET_SIZE(p))
  4900.     {
  4901.     case 0:
  4902.       if (RELOC_MEMORY_SUB_P(p))
  4903.         relocation -= mask & *(char *) (data + addr);
  4904.       else if (RELOC_MEMORY_ADD_P(p))
  4905.         relocation += mask & *(char *) (data + addr);
  4906.       *(char *) (data + addr) &= ~mask;
  4907.       *(char *) (data + addr) |= relocation;
  4908.       break;
  4909.  
  4910.     case 1:
  4911.       if (RELOC_MEMORY_SUB_P(p))
  4912.         relocation -= mask & *(short *) (data + addr);
  4913.       else if (RELOC_MEMORY_ADD_P(p))
  4914.         relocation += mask & *(short *) (data + addr);
  4915.       *(short *) (data + addr) &= ~mask;
  4916.       *(short *) (data + addr) |= relocation;
  4917.       break;
  4918.  
  4919.     case 2:
  4920. #ifdef CROSS_LINKER
  4921.       /* This is necessary if the host has stricter alignment
  4922.          than the target.  Too slow to use all the time.
  4923.          Also doesn't deal with differing byte-order.  */
  4924.       {
  4925.         /* Thing to relocate.  */
  4926.         long thing;
  4927.         bcopy (data + addr, &thing, sizeof (thing));
  4928.         if (RELOC_MEMORY_SUB_P (p))
  4929.           relocation -= mask & thing;
  4930.         else if (RELOC_MEMORY_ADD_P (p))
  4931.           relocation += mask & thing;
  4932.         thing = (thing & ~mask) | relocation;
  4933.         bcopy (&thing, data + addr, sizeof (thing));
  4934.       }
  4935. #else /* not CROSS_LINKER */
  4936.       if (RELOC_MEMORY_SUB_P(p))
  4937.         relocation -= mask & *(long *) (data + addr);
  4938.       else if (RELOC_MEMORY_ADD_P(p))
  4939.         relocation += mask & *(long *) (data + addr);
  4940.       *(long *) (data + addr) &= ~mask;
  4941.       *(long *) (data + addr) |= relocation;
  4942. #endif /* not CROSS_LINKER */
  4943.       break;
  4944.  
  4945.     default:
  4946.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  4947.     }
  4948.     }
  4949. }
  4950.  
  4951. /* For OUTPUT_RELOCATABLE only: write out the relocation,
  4952.    relocating the addresses-to-be-relocated.  */
  4953.  
  4954. void coptxtrel (), copdatrel ();
  4955.  
  4956. void
  4957. write_rel ()
  4958. {
  4959.   register int i;
  4960.   register int count = 0;
  4961.  
  4962.   if (trace_files)
  4963.     fprintf (stderr, "Writing text relocation:\n\n");
  4964.  
  4965.   /* Assign each global symbol a sequence number, giving the order
  4966.      in which `write_syms' will write it.
  4967.      This is so we can store the proper symbolnum fields
  4968.      in relocation entries we write.  */
  4969.  
  4970.   for (i = 0; i < TABSIZE; i++)
  4971.     {
  4972.       symbol *sp;
  4973.       for (sp = symtab[i]; sp; sp = sp->link)
  4974.     if (sp->referenced || sp->defined)
  4975.       {
  4976.         sp->def_count = count++;
  4977. #ifndef NeXT
  4978.         /* Leave room for the reference required by N_INDR, if
  4979.            necessary.  */
  4980.         if ((sp->defined & ~N_EXT) == N_INDR)
  4981.           count++;
  4982. #endif
  4983.       }
  4984.     }
  4985.   /* Correct, because if (OUTPUT_RELOCATABLE), we will also be writing
  4986.      whatever indirect blocks we have.  */
  4987. #ifndef NeXT
  4988.   if (count != defined_global_sym_count
  4989.       + undefined_global_sym_count + global_indirect_count)
  4990. #else
  4991.   if (count != defined_global_sym_count
  4992.       + undefined_global_sym_count)
  4993. #endif
  4994.     fatal ("internal error");
  4995.  
  4996.   /* Write out the relocations of all files, remembered from copy_text.  */
  4997.  
  4998.   lseek (outdesc, output_trel_offset, 0);
  4999.   each_full_file (coptxtrel, 0);
  5000.  
  5001.   if (trace_files)
  5002.     fprintf (stderr, "\nWriting data relocation:\n\n");
  5003.  
  5004.   lseek (outdesc, output_drel_offset, 0);
  5005.   each_full_file (copdatrel, 0);
  5006.  
  5007.   if (trace_files)
  5008.     fprintf (stderr, "\n");
  5009. }
  5010.  
  5011. void
  5012. coptxtrel (entry)
  5013.      struct file_entry *entry;
  5014. {
  5015.   register struct relocation_info *p, *end;
  5016.   register int reloc = entry->text_start_address - text_start;
  5017.  
  5018.   p = entry->textrel;
  5019.   end = (struct relocation_info *) (entry->text_reloc_size + (char *) p);
  5020.   while (p < end)
  5021.     {
  5022.       RELOC_ADDRESS(p) += reloc;
  5023.       if (RELOC_EXTERN_P(p))
  5024.     {
  5025.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5026.       symbol *symptr = ((symbol *)
  5027.                 (((struct nlist *)
  5028.                   (((char *)entry->symbols) + symindex))
  5029.                  ->n_un.n_name));
  5030.  
  5031.       if (symindex >= entry->syms_size)
  5032.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5033.  
  5034. #ifdef N_INDR
  5035.       /* Resolve indirection.  */
  5036.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5037.         symptr = (symbol *) symptr->value;
  5038. #endif
  5039.  
  5040.       /* If the symbol is now defined, change the external relocation
  5041.          to an internal one.  */
  5042.  
  5043.       if (symptr->defined)
  5044.         {
  5045.           RELOC_EXTERN_P(p) = 0;
  5046.           RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
  5047. #ifdef RELOC_ADD_EXTRA
  5048.           /* If we aren't going to be adding in the value in
  5049.              memory on the next pass of the loader, then we need
  5050.          to add it in from the relocation entry.  Otherwise
  5051.              the work we did in this pass is lost.  */
  5052.           if (!RELOC_MEMORY_ADD_P(p))
  5053.         RELOC_ADD_EXTRA (p) += symptr->value;
  5054. #endif
  5055.         }
  5056.       else
  5057.         /* Debugger symbols come first, so have to start this
  5058.            after them.  */
  5059. #ifndef NeXT
  5060.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5061.                  - defined_global_sym_count
  5062.                  - undefined_global_sym_count
  5063.                  - global_indirect_count);
  5064. #else
  5065.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5066.                  - defined_global_sym_count
  5067.                  - undefined_global_sym_count);
  5068. #endif
  5069.     }
  5070.       p++;
  5071.     }
  5072.  
  5073. #ifdef MACH_O
  5074.   if (output_file_type == IS_MACH_O)
  5075.     generate_mach_o_relocations(entry->textrel,
  5076.                 entry->text_reloc_size / sizeof (struct relocation_info));
  5077. #endif
  5078.  
  5079.   mywrite (entry->textrel, 1, entry->text_reloc_size, outdesc);
  5080. }
  5081.  
  5082. void
  5083. copdatrel (entry)
  5084.      struct file_entry *entry;
  5085. {
  5086.   register struct relocation_info *p, *end;
  5087.   /* Relocate the address of the relocation.
  5088.      Old address is relative to start of the input file's data section.
  5089.      New address is relative to start of the output file's data section.
  5090.  
  5091.      So the amount we need to relocate it by is the offset of this
  5092.      input file's data section within the output file's data section.  */
  5093.   register int reloc = entry->data_start_address - data_start;
  5094.  
  5095.   p = entry->datarel;
  5096.   end = (struct relocation_info *) (entry->data_reloc_size + (char *) p);
  5097.   while (p < end)
  5098.     {
  5099.       RELOC_ADDRESS(p) += reloc;
  5100.       if (RELOC_EXTERN_P(p))
  5101.     {
  5102.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5103.       symbol *symptr = ((symbol *)
  5104.                 (((struct nlist *)
  5105.                   (((char *)entry->symbols) + symindex))
  5106.                  ->n_un.n_name));
  5107.       int symtype;
  5108.  
  5109.       if (symindex >= entry->syms_size)
  5110.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5111.  
  5112. #ifdef N_INDR
  5113.       /* Resolve indirection.  */
  5114.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5115.         symptr = (symbol *) symptr->value;
  5116. #endif
  5117.  
  5118.       symtype = symptr->defined & ~N_EXT;
  5119.  
  5120.       if (force_common_definition
  5121.           || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
  5122.         {
  5123.           RELOC_EXTERN_P(p) = 0;
  5124.           RELOC_SYMBOL(p) = symtype;
  5125.         }
  5126.       else
  5127.         /* Debugger symbols come first, so have to start this
  5128.            after them.  */
  5129. #ifndef NeXT
  5130.         RELOC_SYMBOL(p)
  5131.           = (((symbol *)
  5132.           (((struct nlist *)
  5133.             (((char *)entry->symbols) + symindex))
  5134.            ->n_un.n_name))
  5135.          ->def_count
  5136.          + nsyms - defined_global_sym_count
  5137.          - undefined_global_sym_count
  5138.          - global_indirect_count);
  5139. #else
  5140.         RELOC_SYMBOL(p)
  5141.           = (((symbol *)
  5142.           (((struct nlist *)
  5143.             (((char *)entry->symbols) + symindex))
  5144.            ->n_un.n_name))
  5145.          ->def_count
  5146.          + nsyms - defined_global_sym_count
  5147.          - undefined_global_sym_count);
  5148. #endif
  5149.     }
  5150.       p++;
  5151.     }
  5152. #ifdef MACH_O
  5153.   if (output_file_type == IS_MACH_O)
  5154.     generate_mach_o_relocations(entry->datarel,
  5155.                 entry->data_reloc_size / sizeof (struct relocation_info));
  5156. #endif
  5157.  
  5158.   mywrite (entry->datarel, 1, entry->data_reloc_size, outdesc);
  5159. }
  5160.  
  5161. void write_file_syms ();
  5162. void write_string_table ();
  5163.  
  5164. /* Total size of string table strings allocated so far,
  5165.    including strings in `strtab_vector'.  */
  5166. int strtab_size;
  5167.  
  5168. /* Vector whose elements are strings to be added to the string table.  */
  5169. char **strtab_vector;
  5170.  
  5171. /* Vector whose elements are the lengths of those strings.  */
  5172. int *strtab_lens;
  5173.  
  5174. /* Index in `strtab_vector' at which the next string will be stored.  */
  5175. int strtab_index;
  5176.  
  5177. /* Add the string NAME to the output file string table.
  5178.    Record it in `strtab_vector' to be output later.
  5179.    Return the index within the string table that this string will have.  */
  5180.  
  5181. int
  5182. assign_string_table_index (name)
  5183.      char *name;
  5184. {
  5185.   register int index = strtab_size;
  5186.   register int len = strlen (name) + 1;
  5187.  
  5188.   strtab_size += len;
  5189.   strtab_vector[strtab_index] = name;
  5190.   strtab_lens[strtab_index++] = len;
  5191.  
  5192.   return index;
  5193. }
  5194.  
  5195. FILE *outstream = (FILE *) 0;
  5196.  
  5197. /* Write the contents of `strtab_vector' into the string table.
  5198.    This is done once for each file's local&debugger symbols
  5199.    and once for the global symbols.  */
  5200.  
  5201. void
  5202. write_string_table ()
  5203. {
  5204.   register int i;
  5205.  
  5206.   lseek (outdesc, output_strs_offset + output_strs_size, 0);
  5207.  
  5208.   if (!outstream)
  5209.     outstream = fdopen (outdesc, "w");
  5210.  
  5211.   for (i = 0; i < strtab_index; i++)
  5212.     {
  5213.       fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
  5214.       output_strs_size += strtab_lens[i];
  5215.     }
  5216.  
  5217.   fflush (outstream);
  5218.  
  5219.   /* Report I/O error such as disk full.  */
  5220.   if (ferror (outstream))
  5221.     perror_name (output_filename);
  5222. }
  5223.  
  5224. /* Write the symbol table and string table of the output file.  */
  5225.  
  5226. void
  5227. write_syms ()
  5228. {
  5229.   /* Number of symbols written so far.  */
  5230.   int syms_written = 0;
  5231.   register int i;
  5232.   register symbol *sp;
  5233.  
  5234.   /* Buffer big enough for all the global symbols.  One
  5235.      extra struct for each indirect symbol to hold the extra reference
  5236.      following. */
  5237.   struct nlist *buf
  5238. #ifndef NeXT
  5239.     = (struct nlist *) alloca ((defined_global_sym_count
  5240.                 + undefined_global_sym_count
  5241.                 + global_indirect_count)
  5242.                    * sizeof (struct nlist));
  5243. #else
  5244.     = (struct nlist *) alloca ((defined_global_sym_count
  5245.                 + undefined_global_sym_count)
  5246.                    * sizeof (struct nlist));
  5247. #endif
  5248.   /* Pointer for storing into BUF.  */
  5249.   register struct nlist *bufp = buf;
  5250.  
  5251.   /* Size of string table includes the bytes that store the size.  */
  5252.   strtab_size = sizeof strtab_size;
  5253.  
  5254.   output_syms_size = 0;
  5255.   output_strs_size = strtab_size;
  5256.  
  5257.   if (strip_symbols == STRIP_ALL)
  5258.     return;
  5259.  
  5260.   /* Write the local symbols defined by the various files.  */
  5261.  
  5262.   each_file (write_file_syms, &syms_written);
  5263.   file_close ();
  5264.  
  5265.   /* Now write out the global symbols.  */
  5266.  
  5267.   /* Allocate two vectors that record the data to generate the string
  5268.      table from the global symbols written so far.  This must include
  5269.      extra space for the references following indirect outputs. */
  5270.  
  5271.   strtab_vector = (char **) alloca ((num_hash_tab_syms
  5272.                      + global_indirect_count) * sizeof (char *));
  5273.   strtab_lens = (int *) alloca ((num_hash_tab_syms
  5274.                  + global_indirect_count) * sizeof (int));
  5275.   strtab_index = 0;
  5276.  
  5277.   /* Scan the symbol hash table, bucket by bucket.  */
  5278.  
  5279.   for (i = 0; i < TABSIZE; i++)
  5280.     for (sp = symtab[i]; sp; sp = sp->link)
  5281.       {
  5282.     struct nlist nl;
  5283.  
  5284. #ifdef N_SECT
  5285.     nl.n_sect = 0;
  5286. #else
  5287.     nl.n_other = 0;
  5288. #endif
  5289.     nl.n_desc = 0;
  5290.  
  5291.     /* Compute a `struct nlist' for the symbol.  */
  5292.  
  5293.     if (sp->defined || sp->referenced)
  5294.       {
  5295.         /* common condition needs to be before undefined condition */
  5296.         /* because unallocated commons are set undefined in */
  5297.         /* digest_symbols */
  5298.         if (sp->defined > 1) /* defined with known type */
  5299.           {
  5300.         /* If the target of an indirect symbol has been
  5301.            defined and we are outputting an executable,
  5302.            resolve the indirection; it's no longer needed */
  5303.         if (output_style != OUTPUT_RELOCATABLE
  5304.             && ((sp->defined & ~N_EXT) == N_INDR)
  5305.             && (((symbol *) sp->value)->defined > 1))
  5306.           {
  5307.             symbol *newsp = (symbol *) sp->value;
  5308.             nl.n_type = newsp->defined;
  5309.             nl.n_value = newsp->value;
  5310.           }
  5311.         else
  5312.           {
  5313.             nl.n_type = sp->defined;
  5314.             if (sp->defined != (N_INDR | N_EXT))
  5315.               nl.n_value = sp->value;
  5316.             else
  5317.               nl.n_value = 0;
  5318.           }
  5319.           }
  5320.         else if (sp->max_common_size) /* defined as common but not allocated. */
  5321.           {
  5322.         /* happens only with -r and not -d */
  5323.         /* write out a common definition */
  5324.         nl.n_type = N_UNDF | N_EXT;
  5325.         nl.n_value = sp->max_common_size;
  5326.           }
  5327.         else if (!sp->defined)          /* undefined -- legit only if -r */
  5328.           {
  5329.         nl.n_type = N_UNDF | N_EXT;
  5330.         nl.n_value = 0;
  5331.           }
  5332.         else
  5333.           fatal ("internal error: %s defined in mysterious way", sp->name);
  5334.  
  5335.         /* Allocate string table space for the symbol name.  */
  5336.  
  5337.         nl.n_un.n_strx = assign_string_table_index (sp->name);
  5338.  
  5339.         /* Output to the buffer and count it.  */
  5340.  
  5341.         *bufp++ = nl;
  5342.         syms_written++;
  5343.         if (nl.n_type == (N_INDR | N_EXT))
  5344. #ifndef NeXT
  5345.           {
  5346.         struct nlist xtra_ref;
  5347.         xtra_ref.n_type == N_EXT | N_UNDF;
  5348.         xtra_ref.n_un.n_strx
  5349.           = assign_string_table_index (((symbol *) sp->value)->name);
  5350. #ifdef N_SECT
  5351.         xtra_ref.n_sect = 0;
  5352. #else
  5353.         xtra_ref.n_other = 0;
  5354. #endif
  5355.         xtra_ref.n_desc = 0;
  5356.         xtra_ref.n_value = 0;
  5357.         *bufp++ = xtra_ref;
  5358.         syms_written++;
  5359.           }
  5360. #else
  5361.         nl.n_value = assign_string_table_index (((symbol *) sp->value)->name);
  5362. #endif
  5363.       }
  5364.       }
  5365.  
  5366. #ifdef MACH_O
  5367.   if (output_file_type == IS_MACH_O)
  5368.     generate_mach_o_symbols(buf, bufp - buf);
  5369. #endif
  5370.  
  5371.   /* Output the buffer full of `struct nlist's.  */
  5372.  
  5373.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  5374.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5375.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  5376.  
  5377.   if (syms_written != nsyms)
  5378.     fatal ("internal error: wrong number of symbols written into output file", 0);
  5379.  
  5380.   /* Now the total string table size is known, so write it into the
  5381.      first word of the string table.  */
  5382.  
  5383.   lseek (outdesc, output_strs_offset, 0);
  5384.   mywrite (&strtab_size, sizeof (int), 1, outdesc);
  5385.  
  5386.   /* Write the strings for the global symbols.  */
  5387.  
  5388.   write_string_table ();
  5389. }
  5390.  
  5391. /* Write the local and debugger symbols of file ENTRY.
  5392.    Increment *SYMS_WRITTEN_ADDR for each symbol that is written.  */
  5393.  
  5394. /* Note that we do not combine identical names of local symbols.
  5395.    dbx or gdb would be confused if we did that.  */
  5396.  
  5397. void
  5398. write_file_syms (entry, syms_written_addr)
  5399.      struct file_entry *entry;
  5400.      int *syms_written_addr;
  5401. {
  5402.   register struct nlist *p = entry->symbols;
  5403.   register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
  5404.  
  5405.   /* Buffer to accumulate all the syms before writing them.
  5406.      It has one extra slot for the local symbol we generate here.  */
  5407.   struct nlist *buf
  5408.     = (struct nlist *) alloca (entry->syms_size + sizeof (struct nlist));
  5409.   register struct nlist *bufp = buf;
  5410.  
  5411.   /* Upper bound on number of syms to be written here.  */
  5412.   int max_syms = (entry->syms_size / sizeof (struct nlist)) + 1;
  5413.  
  5414.   /* Make tables that record, for each symbol, its name and its name's length.
  5415.      The elements are filled in by `assign_string_table_index'.  */
  5416.  
  5417.   strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  5418.   strtab_lens = (int *) alloca (max_syms * sizeof (int));
  5419.   strtab_index = 0;
  5420.  
  5421.   /* Generate a local symbol for the start of this file's text.  */
  5422.  
  5423.   if (discard_locals != DISCARD_ALL)
  5424.     {
  5425.       struct nlist nl;
  5426.  
  5427.       nl.n_type = N_TEXT;
  5428.       nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
  5429.       nl.n_value = entry->text_start_address;
  5430.       nl.n_desc = 0;
  5431. #ifdef N_SECT
  5432.       nl.n_sect = 0;
  5433. #else
  5434.       nl.n_other = 0;
  5435. #endif
  5436.       *bufp++ = nl;
  5437.       (*syms_written_addr)++;
  5438.       entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
  5439.     }
  5440.  
  5441.   /* Read the file's string table.  */
  5442.  
  5443.   entry->strings = (char *) alloca (entry->strs_size);
  5444.   read_entry_strings (file_open (entry), entry);
  5445.  
  5446.   for (; p < end; p++)
  5447.     {
  5448.       register int type = p->n_type;
  5449.       register int write = 0;
  5450.  
  5451.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  5452.  
  5453.  
  5454.       if (SET_ELEMENT_P (type))    /* This occurs even if global.  These */
  5455.                 /* types of symbols are never written */
  5456.                 /* globally, though they are stored */
  5457.                 /* globally.  */
  5458.         write = output_style == OUTPUT_RELOCATABLE;
  5459.       else if (!(type & (N_STAB | N_EXT)))
  5460.         /* ordinary local symbol */
  5461.     write = ((discard_locals != DISCARD_ALL)
  5462.          && !(discard_locals == DISCARD_L &&
  5463.               (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
  5464.          && type != N_WARNING);
  5465.       else if (!(type & N_EXT))
  5466.     /* debugger symbol */
  5467.         write = (strip_symbols == STRIP_NONE);
  5468.  
  5469.       if (write)
  5470.     {
  5471.       /* If this symbol has a name,
  5472.          allocate space for it in the output string table.  */
  5473.  
  5474.       if (p->n_un.n_strx)
  5475.         p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
  5476.                             + entry->strings);
  5477.  
  5478.       /* Output this symbol to the buffer and count it.  */
  5479.  
  5480.       *bufp++ = *p;
  5481.       (*syms_written_addr)++;
  5482.     }
  5483.     }
  5484.  
  5485. #ifdef MACH_O
  5486.   if (output_file_type == IS_MACH_O)
  5487.     generate_mach_o_symbols(buf, bufp - buf);
  5488. #endif
  5489.  
  5490.   /* All the symbols are now in BUF; write them.  */
  5491.  
  5492.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  5493.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5494.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  5495.  
  5496.   /* Write the string-table data for the symbols just written,
  5497.      using the data in vectors `strtab_vector' and `strtab_lens'.  */
  5498.  
  5499.   write_string_table ();
  5500.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  5501. }
  5502.  
  5503. /* Copy any GDB symbol segments from the input files to the output file.
  5504.    The contents of the symbol segment is copied without change
  5505.    except that we store some information into the beginning of it.  */
  5506.  
  5507. void write_file_symseg ();
  5508.  
  5509. void
  5510. write_symsegs ()
  5511. {
  5512.   lseek (outdesc, output_symseg_offset, 0);
  5513.   each_file (write_file_symseg, 0);
  5514. }
  5515.  
  5516. void
  5517. write_file_symseg (entry)
  5518.      struct file_entry *entry;
  5519. {
  5520.   char buffer[4096];
  5521.   struct symbol_root root;
  5522.   int indesc, len, total;
  5523.  
  5524.   if (entry->symseg_size == 0)
  5525.     return;
  5526.  
  5527.   output_symseg_size += entry->symseg_size;
  5528.  
  5529.   /* This entry has a symbol segment.  Read the root of the segment.  */
  5530.  
  5531.   indesc = file_open (entry);
  5532.   lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  5533.   if (sizeof root != read (indesc, &root, sizeof root))
  5534.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  5535.  
  5536.   /* Store some relocation info into the root.  */
  5537.  
  5538.   root.ldsymoff = entry->local_syms_offset;
  5539.   root.textrel = entry->text_start_address - entry->orig_text_address;
  5540.   root.datarel = entry->data_start_address - entry->orig_data_address;
  5541.   root.bssrel = entry->bss_start_address - entry->orig_bss_address;
  5542.   root.databeg = entry->data_start_address - root.datarel;
  5543.   root.bssbeg = entry->bss_start_address - root.bssrel;
  5544.  
  5545.   /* Write the modified root into the output file.  */
  5546.  
  5547.   mywrite (&root, sizeof root, 1, outdesc);
  5548.  
  5549.   /* Copy the rest of the symbol segment unchanged.  */
  5550.  
  5551.   total = entry->symseg_size - sizeof root;
  5552.  
  5553.   while (total > 0)
  5554.     {
  5555.       len = read (indesc, buffer, min (sizeof buffer, total));
  5556.  
  5557.       if (len != min (sizeof buffer, total))
  5558.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  5559.       total -= len;
  5560.       mywrite (buffer, len, 1, outdesc);
  5561.     }
  5562.  
  5563.   file_close ();
  5564. }
  5565.  
  5566. /* Define a special symbol (etext, edata, or end).  NAME is the
  5567.    name of the symbol, with a leading underscore (whether or not this
  5568.    system uses such underscores).  TYPE is its type (e.g. N_DATA | N_EXT).
  5569.    Store a symbol * for the symbol in *SYM if SYM is non-NULL.  */
  5570. static void
  5571. symbol_define (name, type, sym)
  5572.      /* const */ char *name;
  5573.      int type;
  5574.      symbol **sym;
  5575. {
  5576.   symbol *thesym;
  5577.  
  5578. #if defined(nounderscore)
  5579.   /* Skip the leading underscore.  */
  5580.   name++;
  5581. #endif
  5582.  
  5583.   thesym = getsym (name);
  5584.   if (thesym->defined)
  5585.     {
  5586.       /* The symbol is defined in some input file.  Don't mess with it.  */
  5587.       if (sym)
  5588.     *sym = 0;
  5589.     }
  5590.   else
  5591.     {
  5592.       if (thesym->referenced)
  5593.     /* The symbol was not defined, and we are defining it now.  */
  5594.     undefined_global_sym_count--;
  5595.       thesym->defined = type;
  5596.       thesym->referenced = 1;
  5597.       if (sym)
  5598.     *sym = thesym;
  5599.     }
  5600. }
  5601.  
  5602. /* Create the symbol table entries for `etext', `edata' and `end'.  */
  5603.  
  5604. void
  5605. symtab_init ()
  5606. {
  5607.   symbol_define ("_edata", N_DATA | N_EXT, &edata_symbol);
  5608.   symbol_define ("_etext", N_TEXT | N_EXT, &etext_symbol);
  5609.   symbol_define ("_end", N_BSS | N_EXT, &end_symbol);
  5610.  
  5611.   /* Either _edata or __edata (C names) is OK as far as ANSI is concerned
  5612.      (see section 4.1.2.1).  In general, it is best to use __foo and
  5613.      not worry about the confusing rules for the _foo namespace.
  5614.      But HPUX 7.0 uses _edata, so we might as weel be consistent.  */
  5615.   symbol_define ("__edata", N_DATA | N_EXT, &edata_symbol_alt);
  5616.   symbol_define ("__etext", N_TEXT | N_EXT, &etext_symbol_alt);
  5617.   symbol_define ("__end", N_BSS | N_EXT, &end_symbol_alt);
  5618.  
  5619. #ifdef sun
  5620.   {
  5621.     symbol *dynamic_symbol;
  5622.     symbol_define ("__DYNAMIC", N_ABS | N_EXT, &dynamic_symbol);
  5623.     if (dynamic_symbol)
  5624.       dynamic_symbol->value = 0;
  5625.   }
  5626. #endif
  5627. #ifdef sequent
  5628.   {
  5629.     symbol *i387_flt_symbol;
  5630.     symbol_define ("_387_flt", N_ABS | N_EXT, &i387_flt_symbol);
  5631.     if (i387_flt_symbol)
  5632.       i387_flt_symbol->value = 0;
  5633.   }
  5634. #endif
  5635. #ifdef NeXT
  5636.   {
  5637.     symbol *shlib_init_symbol;
  5638.     symbol_define ("__shared_library_initialization", N_UNDF | N_EXT, &shlib_init_symbol);
  5639.     if (shlib_init_symbol)
  5640.       shlib_init_symbol->max_common_size = sizeof (long int);
  5641.   }
  5642. #endif
  5643. }
  5644.  
  5645. /* Compute the hash code for symbol name KEY.  */
  5646.  
  5647. int
  5648. hash_string (key)
  5649.      char *key;
  5650. {
  5651.   register char *cp;
  5652.   register int k;
  5653.  
  5654.   cp = key;
  5655.   k = 0;
  5656.   while (*cp)
  5657.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  5658.  
  5659.   return k;
  5660. }
  5661.  
  5662. /* Get the symbol table entry for the global symbol named KEY.
  5663.    Create one if there is none.  */
  5664.  
  5665. symbol *
  5666. getsym (key)
  5667.      char *key;
  5668. {
  5669.   register int hashval;
  5670.   register symbol *bp;
  5671.  
  5672.   /* Determine the proper bucket.  */
  5673.  
  5674.   hashval = hash_string (key) % TABSIZE;
  5675.  
  5676.   /* Search the bucket.  */
  5677.  
  5678.   for (bp = symtab[hashval]; bp; bp = bp->link)
  5679.     if (! strcmp (key, bp->name))
  5680.       return bp;
  5681.  
  5682.   /* Nothing was found; create a new symbol table entry.  */
  5683.  
  5684.   bp = (symbol *) xmalloc (sizeof (symbol));
  5685.   bp->refs = 0;
  5686.   bp->name = (char *) xmalloc (strlen (key) + 1);
  5687.   strcpy (bp->name, key);
  5688.   bp->defined = 0;
  5689.   bp->referenced = 0;
  5690.   bp->trace = 0;
  5691.   bp->value = 0;
  5692.   bp->max_common_size = 0;
  5693.   bp->warning = 0;
  5694.   bp->undef_refs = 0;
  5695.   bp->multiply_defined = 0;
  5696.  
  5697.   /* Add the entry to the bucket.  */
  5698.  
  5699.   bp->link = symtab[hashval];
  5700.   symtab[hashval] = bp;
  5701.  
  5702.   ++num_hash_tab_syms;
  5703.  
  5704.   return bp;
  5705. }
  5706.  
  5707. /* Like `getsym' but return 0 if the symbol is not already known.  */
  5708.  
  5709. symbol *
  5710. getsym_soft (key)
  5711.      char *key;
  5712. {
  5713.   register int hashval;
  5714.   register symbol *bp;
  5715.  
  5716.   /* Determine which bucket.  */
  5717.  
  5718.   hashval = hash_string (key) % TABSIZE;
  5719.  
  5720.   /* Search the bucket.  */
  5721.  
  5722.   for (bp = symtab[hashval]; bp; bp = bp->link)
  5723.     if (! strcmp (key, bp->name))
  5724.       return bp;
  5725.  
  5726.   return 0;
  5727. }
  5728.  
  5729. /* Report a usage error.
  5730.    Like fatal except prints a usage summary.  */
  5731.  
  5732. void
  5733. usage (string, arg)
  5734.      char *string, *arg;
  5735. {
  5736.   if (string)
  5737.     {
  5738.       fprintf (stderr, "%s: ", progname);
  5739.       fprintf (stderr, string, arg);
  5740.       fprintf (stderr, "\n");
  5741.     }
  5742.   fprintf (stderr, "\
  5743. Usage: %s [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
  5744.        [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
  5745.        [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
  5746.        [-S] [-T[{text,data}] addr] [-V prefix] [-X] [file...]\n",
  5747.        progname);
  5748.   exit (1);
  5749. }
  5750.  
  5751. /* Report a fatal error.
  5752.    STRING is a printf format string and ARG is one arg for it.  */
  5753.  
  5754. void
  5755. fatal (string, arg)
  5756.      char *string, *arg;
  5757. {
  5758.   fprintf (stderr, "%s: ", progname);
  5759.   fprintf (stderr, string, arg);
  5760.   fprintf (stderr, "\n");
  5761.   exit (1);
  5762. }
  5763.  
  5764. /* Report a fatal error.  The error message is STRING
  5765.    followed by the filename of ENTRY.  */
  5766.  
  5767. void
  5768. fatal_with_file (string, entry)
  5769.      char *string;
  5770.      struct file_entry *entry;
  5771. {
  5772.   fprintf (stderr, "%s: ", progname);
  5773.   fprintf (stderr, string);
  5774.   print_file_name (entry, stderr);
  5775.   fprintf (stderr, "\n");
  5776.   exit (1);
  5777. }
  5778.  
  5779. /* Report a fatal error using the message for the last failed system call,
  5780.    followed by the string NAME.  */
  5781.  
  5782. void
  5783. perror_name (name)
  5784.      char *name;
  5785. {
  5786.   extern int errno, sys_nerr;
  5787.   extern char *sys_errlist[];
  5788.   char *s;
  5789.  
  5790.   if (errno < sys_nerr)
  5791.     s = concat ("", sys_errlist[errno], " for %s");
  5792.   else
  5793.     s = "cannot open %s";
  5794.   fatal (s, name);
  5795. }
  5796.  
  5797. /* Report a fatal error using the message for the last failed system call,
  5798.    followed by the name of file ENTRY.  */
  5799.  
  5800. void
  5801. perror_file (entry)
  5802.      struct file_entry *entry;
  5803. {
  5804.   extern int errno, sys_nerr;
  5805.   extern char *sys_errlist[];
  5806.   char *s;
  5807.  
  5808.   if (errno < sys_nerr)
  5809.     s = concat ("", sys_errlist[errno], " for ");
  5810.   else
  5811.     s = "cannot open ";
  5812.   fatal_with_file (s, entry);
  5813. }
  5814.  
  5815. /* Report a nonfatal error.
  5816.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  5817.  
  5818. void
  5819. error (string, arg1, arg2, arg3)
  5820.      char *string, *arg1, *arg2, *arg3;
  5821. {
  5822.   fprintf (stderr, "%s: ", progname);
  5823.   fprintf (stderr, string, arg1, arg2, arg3);
  5824.   fprintf (stderr, "\n");
  5825. }
  5826.  
  5827.  
  5828. /* Output COUNT*ELTSIZE bytes of data at BUF
  5829.    to the descriptor DESC.  */
  5830.  
  5831. void
  5832. mywrite (buf, count, eltsize, desc)
  5833.      char *buf;
  5834.      int count;
  5835.      int eltsize;
  5836.      int desc;
  5837. {
  5838.   register int val;
  5839.   register int bytes = count * eltsize;
  5840.  
  5841.   while (bytes > 0)
  5842.     {
  5843.       val = write (desc, buf, bytes);
  5844.       if (val <= 0)
  5845.     perror_name (output_filename);
  5846.       buf += val;
  5847.       bytes -= val;
  5848.     }
  5849. }
  5850.  
  5851. /* Output PADDING zero-bytes to descriptor OUTDESC.
  5852.    PADDING may be negative; in that case, do nothing.  */
  5853.  
  5854. void
  5855. padfile (padding, outdesc)
  5856.      int padding;
  5857.      int outdesc;
  5858. {
  5859.   register char *buf;
  5860.   if (padding <= 0)
  5861.     return;
  5862.  
  5863.   buf = (char *) alloca (padding);
  5864.   bzero (buf, padding);
  5865.   mywrite (buf, padding, 1, outdesc);
  5866. }
  5867.  
  5868. /* Return a newly-allocated string
  5869.    whose contents concatenate the strings S1, S2, S3.  */
  5870.  
  5871. char *
  5872. concat (s1, s2, s3)
  5873.      char *s1, *s2, *s3;
  5874. {
  5875.   register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  5876.   register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  5877.  
  5878.   strcpy (result, s1);
  5879.   strcpy (result + len1, s2);
  5880.   strcpy (result + len1 + len2, s3);
  5881.   result[len1 + len2 + len3] = 0;
  5882.  
  5883.   return result;
  5884. }
  5885.  
  5886. /* Parse the string ARG using scanf format FORMAT, and return the result.
  5887.    If it does not parse, report fatal error
  5888.    generating the error message using format string ERROR and ARG as arg.  */
  5889.  
  5890. int
  5891. parse (arg, format, error)
  5892.      char *arg, *format;
  5893. {
  5894.   int x;
  5895.   if (1 != sscanf (arg, format, &x))
  5896.     fatal (error, arg);
  5897.   return x;
  5898. }
  5899.  
  5900. /* Like malloc but get fatal error if memory is exhausted.  */
  5901.  
  5902. char *
  5903. xmalloc (size)
  5904.      int size;
  5905. {
  5906.   register char *result = malloc (size);
  5907.   if (!result)
  5908.     fatal ("virtual memory exhausted", 0);
  5909.   return result;
  5910. }
  5911.  
  5912. /* Like realloc but get fatal error if memory is exhausted.  */
  5913.  
  5914. char *
  5915. xrealloc (ptr, size)
  5916.      char *ptr;
  5917.      int size;
  5918. {
  5919.   register char *result = realloc (ptr, size);
  5920.   if (!result)
  5921.     fatal ("virtual memory exhausted", 0);
  5922.   return result;
  5923. }
  5924.  
  5925. #ifdef USG
  5926.  
  5927. void
  5928. bzero (p, n)
  5929.      char *p;
  5930. {
  5931.   memset (p, 0, n);
  5932. }
  5933.  
  5934. void
  5935. bcopy (from, to, n)
  5936.      char *from, *to;
  5937. {
  5938.   memcpy (to, from, n);
  5939. }
  5940.  
  5941. getpagesize ()
  5942. {
  5943.   return (4096);
  5944. }
  5945.  
  5946. #endif
  5947.  
  5948. #if defined(sun) && defined(sparc)
  5949. int
  5950. getpagesize ()
  5951. {
  5952.   return 8192;
  5953. }
  5954. #endif
  5955.