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