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