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