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