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