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