source: trunk/emx/src/ld/ld.c@ 2446

Last change on this file since 2446 was 2275, checked in by bird, 20 years ago

Switched back to alloca and adding 23 MB of stack.

  • Property cvs2svn:cvs-rev set to 1.21
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 157.1 KB
Line 
1/* ld.c -- changed for emx by Eberhard Mattes -- Sep 1998
2 changed for Innotek GCC by Andrew Zabolotny -- 2003
3 changed for Innotek GCC by knut st. osmundsen -- 2004
4 changed for RSX by Rainer Schnitker -- Feb 1996 */
5
6/* Linker `ld' for GNU
7 Copyright (C) 1988 Free Software Foundation, Inc.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 1, or (at your option)
12 any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
22
23/* Written by Richard Stallman with some help from Eric Albert.
24 Set, indirect, and warning symbol features added by Randy Smith. */
25
26#include <ar.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <stdarg.h>
30#include <io.h>
31#include <process.h>
32#include <errno.h>
33#include <utime.h>
34#include <ctype.h>
35#include <sys/types.h>
36#include <sys/stat.h>
37#include <sys/file.h>
38#ifndef USG
39#include <sys/time.h>
40#include <sys/resource.h>
41#endif
42#ifdef __EMX__
43#include <string.h>
44#endif
45
46#if !defined(A_OUT)
47#define A_OUT
48#endif
49
50#ifdef A_OUT
51#include <a_out.h>
52#endif
53
54#ifndef _System
55#define _System
56#endif
57extern int _System DosCopy (char *, char *, int);
58
59/* We need .data of every module aligned to at least 16 bound
60 in order to support the alignments required by SSE */
61#define SECTION_ALIGN 16
62#define SECTION_ALIGN_MASK (SECTION_ALIGN-1)
63
64/* If compiled with GNU C, use the built-in alloca */
65#ifdef USE_ALLOCA
66#include "alloca.h"
67#define ALLOCA(size) alloca (size)
68#define FREEA(ptr) do { (ptr) = NULL; } while (0)
69#else
70#define ALLOCA(size) malloc (size)
71#define FREEA(ptr) do { free(ptr); (ptr) = NULL; } while (0)
72#endif
73#include "getopt.h"
74
75/* Always use the GNU version of debugging symbol type codes, if possible. */
76
77#include "stab.h"
78#define CORE_ADDR unsigned long /* For symseg.h */
79#include "symseg.h"
80
81#include <strings.h>
82
83/* Determine whether we should attempt to handle (minimally)
84 N_BINCL and N_EINCL. */
85
86#if defined (__GNU_STAB__) || defined (N_BINCL)
87#define HAVE_SUN_STABS
88#endif
89
90#define min(a,b) ((a) < (b) ? (a) : (b))
91
92/* Macro to control the number of undefined references printed */
93#define MAX_UREFS_PRINTED 10
94
95/* Size of a page; obtained from the operating system. */
96
97int page_size;
98
99/* Name this program was invoked by. */
100
101char *progname;
102
103
104/* System dependencies */
105
106/* Define this if names etext, edata and end should not start with `_'. */
107/* #define nounderscore 1 */
108
109/* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
110 whose native format is different. */
111/* #define NON_NATIVE */
112
113/* The "address" of the data segment in a relocatable file.
114 The text address of a relocatable file is always
115 considered to be zero (instead of the value of N_TXTADDR, which
116 is what the address is in an executable), so we need to subtract
117 N_TXTADDR from N_DATADDR to get the "address" for the input file. */
118#define DATA_ADDR_DOT_O(hdr) (N_DATADDR(hdr) - N_TXTADDR(hdr))
119
120/* Values for 3rd argument to lseek(). */
121#ifndef L_SET
122#define L_SET 0
123#endif
124/* This is called L_INCR in BSD, but SEEK_CUR in POSIX. */
125#ifndef SEEK_CUR
126#define SEEK_CUR 1
127#endif
128
129/*
130 * Ok. Following are the relocation information macros. If your
131 * system cannot use the default set (below), you must define all of these:
132
133 * relocation_info: This must be typedef'd (or #define'd) to the type
134 * of structure that is stored in the relocation info section of your
135 * a.out files. Often this is defined in the a.out.h for your system.
136 *
137 * RELOC_ADDRESS (rval): Offset into the current section of the
138 * <whatever> to be relocated. *Must be an lvalue*.
139 *
140 * RELOC_EXTERN_P (rval): Is this relocation entry based on an
141 * external symbol (1), or was it fully resolved upon entering the
142 * loader (0) in which case some combination of the value in memory
143 * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
144 * what the value of the relocation actually was. *Must be an lvalue*.
145 *
146 * RELOC_TYPE (rval): For a non-external relocation, this is the
147 * segment to relocate for. *Must be an lvalue.*
148 *
149 * RELOC_SYMBOL (rval): For an external relocation, this is the
150 * index of its symbol in the symbol table. *Must be an lvalue*.
151 *
152 * RELOC_MEMORY_ADD_P (rval): This should be 1 if the final
153 * relocation value output here should be added to memory; 0, if the
154 * section of memory described should simply be set to the relocation
155 * value.
156 *
157 * RELOC_MEMORY_ADD_P (rval): If this is nonzero, the value previously
158 * present in the memory location to be relocated is *added*
159 * to the relocation value, to produce the final result.
160 * Otherwise, the relocation value is stored in the memory location
161 * and the value previously found there is ignored.
162 * By default, this is always 1.
163 *
164 * RELOC_MEMORY_SUB_P (rval): If this is nonzero, the value previously
165 * present in the memory location to be relocated is *subtracted*
166 * from the relocation value, to produce the final result.
167 * By default, this is always 0.
168 *
169 * RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
170 * an extra value to be added to the relocation value based on the
171 * individual relocation entry. *Must be an lvalue if defined*.
172 *
173 * RELOC_PCREL_P (rval): True if the relocation value described is
174 * pc relative.
175 *
176 * RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
177 * final relocation value before putting it where it belongs.
178 *
179 * RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
180 * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
181 * == 1; 4 bytes == 2, and etc. This is somewhat redundant (we could
182 * do everything in terms of the bit operators below), but having this
183 * macro could end up producing better code on machines without fancy
184 * bit twiddling. Also, it's easier to understand/code big/little
185 * endian distinctions with this macro.
186 *
187 * RELOC_TARGET_BITPOS (rval): The starting bit position within the
188 * object described in RELOC_TARGET_SIZE in which the relocation value
189 * will go.
190 *
191 * RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
192 * with the bits of the relocation value. It may be assumed by the
193 * code that the relocation value will fit into this many bits. This
194 * may be larger than RELOC_TARGET_SIZE if such be useful.
195 *
196 *
197 * Things I haven't implemented
198 * ----------------------------
199 *
200 * Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
201 *
202 * Pc relative relocation for External references.
203 *
204 *
205 */
206
207/* Default macros */
208#ifndef RELOC_ADDRESS
209#define RELOC_ADDRESS(r) ((r)->r_address)
210#define RELOC_EXTERN_P(r) ((r)->r_extern)
211#define RELOC_TYPE(r) ((r)->r_symbolnum)
212#define RELOC_SYMBOL(r) ((r)->r_symbolnum)
213#define RELOC_MEMORY_SUB_P(r) 0
214#define RELOC_MEMORY_ADD_P(r) 1
215#undef RELOC_ADD_EXTRA
216#define RELOC_PCREL_P(r) ((r)->r_pcrel)
217#define RELOC_VALUE_RIGHTSHIFT(r) 0
218#define RELOC_TARGET_SIZE(r) ((r)->r_length)
219#define RELOC_TARGET_BITPOS(r) 0
220#define RELOC_TARGET_BITSIZE(r) 32
221#endif
222
223#ifndef MAX_ALIGNMENT
224#define MAX_ALIGNMENT (sizeof (int))
225#endif
226
227#ifdef nounderscore
228#define LPREFIX '.'
229#else
230#define LPREFIX 'L'
231#endif
232
233
234
235/* Special global symbol types understood by GNU LD. */
236
237/* The following type indicates the definition of a symbol as being
238 an indirect reference to another symbol. The other symbol
239 appears as an undefined reference, immediately following this symbol.
240
241 Indirection is asymmetrical. The other symbol's value will be used
242 to satisfy requests for the indirect symbol, but not vice versa.
243 If the other symbol does not have a definition, libraries will
244 be searched to find a definition.
245
246 So, for example, the following two lines placed in an assembler
247 input file would result in an object file which would direct gnu ld
248 to resolve all references to symbol "foo" as references to symbol
249 "bar".
250
251 .stabs "_foo",11,0,0,0
252 .stabs "_bar",1,0,0,0
253
254 Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)). */
255
256#ifndef N_INDR
257#define N_INDR 0xa
258#endif
259
260/* The following symbols refer to set elements. These are expected
261 only in input to the loader; they should not appear in loader
262 output (unless relocatable output is requested). To be recognized
263 by the loader, the input symbols must have their N_EXT bit set.
264 All the N_SET[ATDB] symbols with the same name form one set. The
265 loader collects all of these elements at load time and outputs a
266 vector for each name.
267 Space (an array of 32 bit words) is allocated for the set in the
268 data section, and the n_value field of each set element value is
269 stored into one word of the array.
270 The first word of the array is the length of the set (number of
271 elements). The last word of the vector is set to zero for possible
272 use by incremental loaders. The array is ordered by the linkage
273 order; the first symbols which the linker encounters will be first
274 in the array.
275
276 In C syntax this looks like:
277
278 struct set_vector {
279 unsigned int length;
280 unsigned int vector[length];
281 unsigned int always_zero;
282 };
283
284 Before being placed into the array, each element is relocated
285 according to its type. This allows the loader to create an array
286 of pointers to objects automatically. N_SETA type symbols will not
287 be relocated.
288
289 The address of the set is made into an N_SETV symbol
290 whose name is the same as the name of the set.
291 This symbol acts like a N_DATA global symbol
292 in that it can satisfy undefined external references.
293
294 For the purposes of determining whether or not to load in a library
295 file, set element definitions are not considered "real
296 definitions"; they will not cause the loading of a library
297 member.
298
299 If relocatable output is requested, none of this processing is
300 done. The symbols are simply relocated and passed through to the
301 output file.
302
303 So, for example, the following three lines of assembler code
304 (whether in one file or scattered between several different ones)
305 will produce a three element vector (total length is five words;
306 see above), referenced by the symbol "_xyzzy", which will have the
307 addresses of the routines _init1, _init2, and _init3.
308
309 *NOTE*: If symbolic addresses are used in the n_value field of the
310 defining .stabs, those symbols must be defined in the same file as
311 that containing the .stabs.
312
313 .stabs "_xyzzy",23,0,0,_init1
314 .stabs "_xyzzy",23,0,0,_init2
315 .stabs "_xyzzy",23,0,0,_init3
316
317 Note that (23 == (N_SETT | N_EXT)). */
318
319#ifndef N_SETA
320#define N_SETA 0x14 /* Absolute set element symbol */
321#endif /* This is input to LD, in a .o file. */
322
323#ifndef N_SETT
324#define N_SETT 0x16 /* Text set element symbol */
325#endif /* This is input to LD, in a .o file. */
326
327#ifndef N_SETD
328#define N_SETD 0x18 /* Data set element symbol */
329#endif /* This is input to LD, in a .o file. */
330
331#ifndef N_SETB
332#define N_SETB 0x1A /* Bss set element symbol */
333#endif /* This is input to LD, in a .o file. */
334
335/* Macros dealing with the set element symbols defined in a.out.h */
336#define SET_ELEMENT_P(x) ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
337#define TYPE_OF_SET_ELEMENT(x) ((x)-N_SETA+N_ABS)
338
339#ifndef N_SETV
340#define N_SETV 0x1C /* Pointer to set vector in data area. */
341#endif /* This is output from LD. */
342
343/* Check if a symbol is weak */
344#define WEAK_SYMBOL(t) (((t) >= N_WEAKU) && ((t) <= N_WEAKB))
345
346/* If a this type of symbol is encountered, its name is a warning
347 message to print each time the symbol referenced by the next symbol
348 table entry is referenced.
349
350 This feature may be used to allow backwards compatibility with
351 certain functions (eg. gets) but to discourage programmers from
352 their use.
353
354 So if, for example, you wanted to have ld print a warning whenever
355 the function "gets" was used in their C program, you would add the
356 following to the assembler file in which gets is defined:
357
358 .stabs "Obsolete function \"gets\" referenced",30,0,0,0
359 .stabs "_gets",1,0,0,0
360
361 These .stabs do not necessarily have to be in the same file as the
362 gets function, they simply must exist somewhere in the compilation. */
363
364#ifndef N_WARNING
365#define N_WARNING 0x1E /* Warning message to print if symbol
366 included */
367#endif /* This is input to ld */
368
369#ifndef __GNU_STAB__
370
371/* Line number for the data section. This is to be used to describe
372 the source location of a variable declaration. */
373#ifndef N_DSLINE
374#define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
375#endif
376
377/* Line number for the bss section. This is to be used to describe
378 the source location of a variable declaration. */
379#ifndef N_BSLINE
380#define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
381#endif
382
383#endif /* not __GNU_STAB__ */
384
385
386/* Symbol table */
387
388/* Global symbol data is recorded in these structures,
389 one for each global symbol.
390 They are found via hashing in 'symtab', which points to a vector of buckets.
391 Each bucket is a chain of these structures through the link field. */
392
393typedef
394 struct glosym
395 {
396 /* Pointer to next symbol in this symbol's hash bucket. */
397 struct glosym *link;
398 /* Name of this symbol. */
399 char *name;
400 /* Value of this symbol as a global symbol. */
401 long value;
402 /* Chain of external 'nlist's in files for this symbol, both defs
403 and refs. */
404 struct nlist *refs;
405 /* Any warning message that might be associated with this symbol
406 from an N_WARNING symbol encountered. */
407 char *warning;
408 /* Nonzero means definitions of this symbol as common have been seen,
409 and the value here is the largest size specified by any of them. */
410 int max_common_size;
411 /* For OUTPUT_RELOCATABLE, records the index of this global sym in the
412 symbol table to be written, with the first global sym given index 0.*/
413 int def_count;
414 /* Nonzero means a definition of this global symbol is known to exist.
415 Library members should not be loaded on its account. */
416 char defined;
417 /* Nonzero means a reference to this global symbol has been seen
418 in a file that is surely being loaded.
419 A value higher than 1 is the n_type code for the symbol's
420 definition. */
421 char referenced;
422 /* A count of the number of undefined references printed for a
423 specific symbol. If a symbol is unresolved at the end of
424 digest_symbols (and the loading run is supposed to produce
425 relocatable output) do_file_warnings keeps track of how many
426 unresolved reference error messages have been printed for
427 each symbol here. When the number hits MAX_UREFS_PRINTED,
428 messages stop. */
429 unsigned char undef_refs;
430 /* 1 means that this symbol has multiple definitions. 2 means
431 that it has multiple definitions, and some of them are set
432 elements, one of which has been printed out already. */
433 unsigned char multiply_defined;
434 /* Nonzero means print a message at all refs or defs of this symbol */
435 char trace;
436 /* One of N_WEAKX values */
437 char weak;
438 }
439 symbol;
440
441/* Demangler for C++. */
442#include "demangle.h"
443static char *my_cplus_demangle (const char *);
444int demangle_options;
445
446/* Demangler function to use. We unconditionally enable the C++ demangler
447 because we assume any name it successfully demangles was probably produced
448 by the C++ compiler. Enabling it only if -lg++ was specified seems too
449 much of a kludge. */
450char *(*demangler)() = my_cplus_demangle;
451
452/* Number of buckets in symbol hash table */
453#define TABSIZE 1009
454
455/* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
456symbol *symtab[TABSIZE];
457
458/* Number of symbols in symbol hash table. */
459int num_hash_tab_syms = 0;
460
461/* Count the number of nlist entries that are for local symbols.
462 This count and the three following counts
463 are incremented as as symbols are entered in the symbol table. */
464int local_sym_count;
465
466/* Count number of nlist entries that are for local symbols
467 whose names don't start with L. */
468int non_L_local_sym_count;
469
470/* Count the number of nlist entries for debugger info. */
471int debugger_sym_count;
472
473/* Count the number of global symbols referenced and not defined. */
474int undefined_global_sym_count;
475
476/* Count the number of global symbols multiply defined. */
477int multiple_def_count;
478
479/* Count the number of defined global symbols.
480 Each symbol is counted only once
481 regardless of how many different nlist entries refer to it,
482 since the output file will need only one nlist entry for it.
483 This count is computed by `digest_symbols';
484 it is undefined while symbols are being loaded. */
485int defined_global_sym_count;
486
487/* Count the number of symbols defined through common declarations.
488 This count is kept in symdef_library, linear_library, and
489 enter_global_ref. It is incremented when the defined flag is set
490 in a symbol because of a common definition, and decremented when
491 the symbol is defined "for real" (ie. by something besides a common
492 definition). */
493int common_defined_global_count;
494
495/* Count the number of set element type symbols and the number of
496 separate vectors which these symbols will fit into. See the
497 GNU a.out.h for more info.
498 This count is computed by 'enter_file_symbols' */
499int set_symbol_count;
500int set_vector_count;
501
502/* Define a linked list of strings which define symbols which should
503 be treated as set elements even though they aren't. Any symbol
504 with a prefix matching one of these should be treated as a set
505 element.
506
507 This is to make up for deficiencies in many assemblers which aren't
508 willing to pass any stabs through to the loader which they don't
509 understand. */
510struct string_list_element {
511 char *str;
512 struct string_list_element *next;
513};
514
515struct string_list_element *set_element_prefixes;
516
517/* Count the number of definitions done indirectly (ie. done relative
518 to the value of some other symbol. */
519int global_indirect_count;
520
521/* Count the number of warning symbols encountered. */
522int warning_count;
523
524/* Total number of symbols to be written in the output file.
525 Computed by digest_symbols from the variables above. */
526int nsyms;
527
528
529/* Nonzero means ptr to symbol entry for symbol to use as start addr.
530 -e sets this. */
531symbol *entry_symbol;
532
533/* These can be NULL if we don't actually have such a symbol. */
534symbol *edata_symbol; /* the symbol _edata */
535symbol *etext_symbol; /* the symbol _etext */
536symbol *end_symbol; /* the symbol _end */
537/* We also need __{edata,etext,end} so that they can safely
538 be used from an ANSI library. */
539symbol *edata_symbol_alt;
540symbol *etext_symbol_alt;
541symbol *end_symbol_alt;
542
543
544/* Kinds of files potentially understood by the linker. */
545
546enum file_type { IS_UNKNOWN, IS_ARCHIVE, IS_A_OUT, IS_MACH_O };
547
548/* Each input file, and each library member ("subfile") being loaded,
549 has a `file_entry' structure for it.
550
551 For files specified by command args, these are contained in the vector
552 which `file_table' points to.
553
554 For library members, they are dynamically allocated,
555 and chained through the `chain' field.
556 The chain is found in the `subfiles' field of the `file_entry'.
557 The `file_entry' objects for the members have `superfile' fields pointing
558 to the one for the library. */
559
560struct file_entry {
561 /* Name of this file. */
562 char *filename;
563
564 /* What kind of file this is. */
565 enum file_type file_type;
566
567 /* Name to use for the symbol giving address of text start */
568 /* Usually the same as filename, but for a file spec'd with -l
569 this is the -l switch itself rather than the filename. */
570 char *local_sym_name;
571
572 /* Describe the layout of the contents of the file. */
573
574 /* The text section. */
575 unsigned long int orig_text_address;
576 unsigned long int text_size;
577 long int text_offset;
578
579 /* Text relocation. */
580 unsigned long int text_reloc_size;
581 long int text_reloc_offset;
582
583 /* The data section. */
584 unsigned long int orig_data_address;
585 unsigned long int data_size;
586 long int data_offset;
587
588 /* Data relocation. */
589 unsigned long int data_reloc_size;
590 long int data_reloc_offset;
591
592 /* The bss section. */
593 unsigned long int orig_bss_address;
594 unsigned long int bss_size;
595
596 /* The symbol and string tables. */
597 unsigned long int syms_size;
598 long int syms_offset;
599 unsigned long int strs_size;
600 long int strs_offset;
601
602 /* The GDB symbol segment, if any. */
603 unsigned long int symseg_size;
604 long int symseg_offset;
605
606 /* Describe data from the file loaded into core */
607
608 /* Symbol table of the file. */
609 struct nlist *symbols;
610
611 /* Pointer to the string table.
612 The string table is not kept in core all the time,
613 but when it is in core, its address is here. */
614 char *strings;
615
616 /* Next two used only if OUTPUT_RELOCATABLE or if needed for */
617 /* output of undefined reference line numbers. */
618
619 /* Text reloc info saved by `write_text' for `coptxtrel'. */
620 struct relocation_info *textrel;
621 /* Data reloc info saved by `write_data' for `copdatrel'. */
622 struct relocation_info *datarel;
623
624 /* Relation of this file's segments to the output file */
625
626 /* Start of this file's text seg in the output file core image. */
627 int text_start_address;
628 /* Start of this file's data seg in the output file core image. */
629 int data_start_address;
630 /* Start of this file's bss seg in the output file core image. */
631 int bss_start_address;
632 /* Offset in bytes in the output file symbol table
633 of the first local symbol for this file. Set by `write_file_symbols'. */
634 int local_syms_offset;
635
636 /* For library members only */
637
638 /* For a library, points to chain of entries for the library members. */
639 struct file_entry *subfiles;
640 /* For a library member, offset of the member within the archive.
641 Zero for files that are not library members. */
642 int starting_offset;
643 /* Size of contents of this file, if library member. */
644 int total_size;
645 /* For library member, points to the library's own entry. */
646 struct file_entry *superfile;
647 /* For library member, points to next entry for next member. */
648 struct file_entry *chain;
649
650 /* 1 if file is a library. */
651 char library_flag;
652
653 /* 1 if file's header has been read into this structure. */
654 char header_read_flag;
655
656 /* 1 means search a set of directories for this file. */
657 char search_dirs_flag;
658
659 /* 1 means this is base file of incremental load.
660 Do not load this file's text or data.
661 Also default text_start to after this file's bss. */
662 char just_syms_flag;
663
664 /* 1 means search for dynamic libs before static.
665 0 means search only static libs. */
666 char dynamic;
667};
668
669/* Vector of entries for input files specified by arguments.
670 These are all the input files except for members of specified libraries. */
671struct file_entry *file_table;
672
673/* Length of that vector. */
674int number_of_files;
675
676
677/* When loading the text and data, we can avoid doing a close
678 and another open between members of the same library.
679
680 These two variables remember the file that is currently open.
681 Both are zero if no file is open.
682
683 See `each_file' and `file_close'. */
684
685struct file_entry *input_file;
686int input_desc;
687
688/* The name of the file to write; "a.out" by default. */
689
690char *output_filename;
691char *exe_filename;
692char *def_filename = NULL;
693char *res_filename = NULL;
694char *map_filename = NULL;
695char *touch_filename = NULL;
696int reloc_flag = 0;
697int dll_flag = 0;
698int exe_flag = 0;
699int map_flag = 0;
700int stack_size = 0;
701int emxbind_strip = 0;
702enum exe_bind_type
703{
704 EMX_DEFAULT, RSXNT_WIN32, RSXNT_RSX, RSXNT_EMX
705} rsxnt_linked = EMX_DEFAULT;
706
707/* What kind of output file to write. */
708
709enum file_type output_file_type;
710
711#ifndef DEFAULT_OUTPUT_FILE_TYPE
712#define DEFAULT_OUTPUT_FILE_TYPE IS_A_OUT
713#endif
714
715/* What `style' of output file to write. For BSD a.out files
716 this specifies OMAGIC, NMAGIC, or ZMAGIC. For Mach-O files
717 this switches between MH_OBJECT and two flavors of MH_EXECUTE. */
718
719enum output_style
720 {
721 OUTPUT_UNSPECIFIED,
722 OUTPUT_RELOCATABLE, /* -r */
723 OUTPUT_WRITABLE_TEXT, /* -N */
724 OUTPUT_READONLY_TEXT, /* -n */
725 OUTPUT_DEMAND_PAGED /* -Z (default) */
726 };
727
728enum output_style output_style;
729
730#ifndef DEFAULT_OUTPUT_STYLE
731#define DEFAULT_OUTPUT_STYLE OUTPUT_DEMAND_PAGED
732#endif
733
734/* Descriptor for writing that file with `mywrite'. */
735
736int outdesc;
737
738/* The following are computed by `digest_symbols'. */
739
740int text_size; /* total size of text of all input files. */
741int text_header_size; /* size of the file header if included in the
742 text size. */
743int data_size; /* total size of data of all input files. */
744int bss_size; /* total size of bss of all input files. */
745int text_reloc_size; /* total size of text relocation of all input files. */
746int data_reloc_size; /* total size of data relocation of all input
747 files. */
748
749/* The following are computed by write_header(). */
750long int output_text_offset; /* file offset of the text section. */
751long int output_data_offset; /* file offset of the data section. */
752long int output_trel_offset; /* file offset of the text relocation info. */
753long int output_drel_offset; /* file offset of the data relocation info. */
754long int output_syms_offset; /* file offset of the symbol table. */
755long int output_strs_offset; /* file offset of the string table. */
756
757/* The following are incrementally computed by write_syms(); we keep
758 them here so we can examine their values afterwards. */
759unsigned int output_syms_size; /* total bytes of symbol table output. */
760unsigned int output_strs_size; /* total bytes of string table output. */
761
762/* This can only be computed after the size of the string table is known. */
763long int output_symseg_offset; /* file offset of the symbol segment (if any). */
764
765/* Incrementally computed by write_file_symseg(). */
766unsigned int output_symseg_size;
767
768/* Specifications of start and length of the area reserved at the end
769 of the text segment for the set vectors. Computed in 'digest_symbols' */
770int set_sect_start;
771int set_sect_size;
772
773/* Pointer for in core storage for the above vectors, before they are
774 written. */
775unsigned long *set_vectors;
776
777int *set_reloc;
778
779/* Amount of cleared space to leave at the end of the text segment. */
780
781int text_pad;
782
783/* Amount of padding between data segment and set vectors. */
784int set_sect_pad;
785
786/* Amount of padding at end of data segment. This has two parts:
787 That which is before the bss segment, and that which overlaps
788 with the bss segment. */
789int data_pad;
790
791/* Format of __.SYMDEF:
792 First, a longword containing the size of the 'symdef' data that follows.
793 Second, zero or more 'symdef' structures.
794 Third, a longword containing the length of symbol name strings.
795 Fourth, zero or more symbol name strings (each followed by a null). */
796
797struct symdef {
798 int symbol_name_string_index;
799 int library_member_offset;
800};
801
802
803/* Record most of the command options. */
804
805/* Address we assume the text section will be loaded at.
806 We relocate symbols and text and data for this, but we do not
807 write any padding in the output file for it. */
808int text_start;
809
810/* Address we decide the data section will be loaded at. */
811int data_start;
812
813/* Nonzero if -T was specified in the command line.
814 This prevents text_start from being set later to default values. */
815int T_flag_specified;
816
817/* Nonzero if -Tdata was specified in the command line.
818 This prevents data_start from being set later to default values. */
819int Tdata_flag_specified;
820
821/* Size to pad data section up to.
822 We simply increase the size of the data section, padding with zeros,
823 and reduce the size of the bss section to match. */
824int specified_data_size;
825
826/* Nonzero means print names of input files as processed. */
827int trace_files;
828
829/* Which symbols should be stripped (omitted from the output):
830 none, all, or debugger symbols. */
831enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
832
833/* Which local symbols should be omitted:
834 none, all, or those starting with L.
835 This is irrelevant if STRIP_NONE. */
836enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
837
838/* 1 => write load map. */
839int write_map;
840
841/* 1 => assign space to common symbols even if OUTPUT_RELOCATABLE. */
842int force_common_definition;
843
844/* Standard directories to search for files specified by -l. */
845char *standard_search_dirs[] = { "/usr/lib" };
846
847/* If set STANDARD_SEARCH_DIRS is not searched. */
848int no_standard_dirs;
849
850/* Actual vector of directories to search;
851 this contains those specified with -L plus the standard ones. */
852char **search_dirs;
853
854/* Length of the vector `search_dirs'. */
855int n_search_dirs;
856
857/* Non zero means to create the output executable.
858 Cleared by nonfatal errors. */
859int make_executable;
860
861/* Force the executable to be output, even if there are non-fatal
862 errors */
863int force_executable;
864
865/* Whether or not to include .dll in the shared library searching. */
866int opt_dll_search;
867
868/* Keep a list of any symbols referenced from the command line (so
869 that error messages for these guys can be generated). This list is
870 zero terminated. */
871struct glosym **cmdline_references;
872int cl_refs_allocated;
873
874char *xmalloc (int);
875void *xrealloc (void *, int);
876void usage (char *, char *);
877void fatal (char *, ...);
878void fatal_with_file (char *, struct file_entry *);
879void perror_name (char *);
880void perror_file (struct file_entry *);
881void error (char *, char *, char *, char *);
882
883int parse (char *, char *, char *);
884void initialize_text_start (void);
885void initialize_data_start (void);
886void digest_symbols (void);
887void print_symbols (FILE *);
888void load_symbols (void);
889void decode_command (int, char **);
890void write_output (void);
891void write_header (void);
892void write_text (void);
893void read_file_relocation (struct file_entry *);
894void write_data (void);
895void write_rel (void);
896void write_syms (void);
897void write_symsegs (void);
898void mywrite (void *, int, int, int);
899void symtab_init (void);
900void padfile (int, int);
901char *concat (const char *, const char *, const char *);
902char *get_file_name (struct file_entry *);
903symbol *getsym (char *), *getsym_soft (char *);
904void do_warnings (FILE *);
905void check_exe (void);
906char *lx_to_aout (const char *pszFilename);
907int check_lx_dll(int fd);
908void cleanup (void);
909
910void add_cmdline_ref (struct glosym *sp);
911void prline_file_name (struct file_entry *entry, FILE *outfile);
912void deduce_file_type(int desc, struct file_entry *entry);
913void read_a_out_header (int desc, struct file_entry *entry);
914void read_header (int desc, struct file_entry *entry);
915void read_entry_symbols (int desc, struct file_entry *entry);
916void read_entry_strings (int desc, struct file_entry *entry);
917unsigned long contains_symbol (struct file_entry *entry, struct nlist *n_ptr);
918void process_subentry (int desc, struct file_entry *subentry, struct file_entry *entry, struct file_entry **prev_addr);
919void consider_file_section_lengths (struct file_entry *entry);
920void relocate_file_addresses (struct file_entry *entry);
921void describe_file_sections (struct file_entry *entry, FILE *outfile);
922void list_file_locals (struct file_entry *entry, FILE *outfile);
923int relocation_entries_relation (struct relocation_info *rel1, struct relocation_info *rel2);
924void do_relocation_warnings (struct file_entry *entry, int data_segment, FILE *outfile, unsigned char *nlist_bitvector);
925void do_file_warnings (struct file_entry *entry, FILE *outfile);
926void initialize_a_out_text_start (void);
927void initialize_a_out_data_start (void);
928void compute_a_out_section_offsets (void);
929void compute_more_a_out_section_offsets (void);
930void write_a_out_header (void);
931int hash_string (char *key);
932void read_file_symbols (struct file_entry *entry);
933void compute_section_offsets (void);
934void compute_more_section_offsets (void);
935void read_relocation (void);
936int assign_string_table_index (char *name);
937unsigned long check_each_file (register unsigned long (*function)(), register int arg);
938static void gen_deffile (void);
939
940
941
942
943
944int
945main (argc, argv)
946 char **argv;
947 int argc;
948{
949 _response (&argc, &argv);
950 _wildcard (&argc, &argv);
951 page_size = getpagesize ();
952 progname = argv[0];
953
954#ifdef RLIMIT_STACK
955 /* Avoid dumping core on large .o files. */
956 {
957 struct rlimit rl;
958
959 getrlimit (RLIMIT_STACK, &rl);
960 rl.rlim_cur = rl.rlim_max;
961 setrlimit (RLIMIT_STACK, &rl);
962 }
963#endif
964
965 /* Clear the cumulative info on the output file. */
966
967 text_size = 0;
968 data_size = 0;
969 bss_size = 0;
970 text_reloc_size = 0;
971 data_reloc_size = 0;
972
973 set_sect_pad = 0;
974 data_pad = 0;
975 text_pad = 0;
976
977 /* Initialize the data about options. */
978
979 specified_data_size = 0;
980 strip_symbols = STRIP_NONE;
981 trace_files = 0;
982 discard_locals = DISCARD_NONE;
983 entry_symbol = 0;
984 write_map = 0;
985 force_common_definition = 0;
986 T_flag_specified = 0;
987 Tdata_flag_specified = 0;
988 make_executable = 1;
989 force_executable = 0;
990 set_element_prefixes = 0;
991
992 /* Initialize the cumulative counts of symbols. */
993
994 local_sym_count = 0;
995 non_L_local_sym_count = 0;
996 debugger_sym_count = 0;
997 undefined_global_sym_count = 0;
998 set_symbol_count = 0;
999 set_vector_count = 0;
1000 global_indirect_count = 0;
1001 warning_count = 0;
1002 multiple_def_count = 0;
1003 common_defined_global_count = 0;
1004
1005 /* Keep a list of symbols referenced from the command line */
1006
1007 cl_refs_allocated = 10;
1008 cmdline_references
1009 = (struct glosym **) xmalloc (cl_refs_allocated
1010 * sizeof(struct glosym *));
1011 *cmdline_references = 0;
1012
1013 /* Cleanup converted file on exit. */
1014
1015 atexit (cleanup);
1016
1017 /* Completely decode ARGV. */
1018
1019 decode_command (argc, argv);
1020
1021 check_exe ();
1022
1023 /* Load symbols of all input files.
1024 Also search all libraries and decide which library members to load. */
1025
1026 load_symbols ();
1027
1028 /* Create various built-in symbols. This must occur after
1029 all input files are loaded so that a user program can have a
1030 symbol named etext (for example). */
1031
1032 if (output_style != OUTPUT_RELOCATABLE)
1033 symtab_init ();
1034
1035 /* Compute where each file's sections go, and relocate symbols. */
1036
1037 digest_symbols ();
1038
1039 /* Print error messages for any missing symbols, for any warning
1040 symbols, and possibly multiple definitions */
1041
1042 do_warnings (stderr);
1043
1044 /* Print a map, if requested. */
1045
1046 if (write_map) print_symbols (stdout);
1047
1048 /* Write the output file. */
1049
1050 if (make_executable || force_executable)
1051 write_output ();
1052
1053 exit (!make_executable);
1054}
1055
1056
1057void add_cmdline_ref ();
1058
1059static struct option longopts[] =
1060{
1061 {"d", 0, 0, 'd'},
1062 {"dc", 0, 0, 'd'}, /* For Sun compatibility. */
1063 {"dp", 0, 0, 'd'}, /* For Sun compatibility. */
1064 {"e", 1, 0, 'e'},
1065 {"n", 0, 0, 'n'},
1066 {"noinhibit-exec", 0, 0, 130},
1067 {"nostdlib", 0, 0, 133},
1068 {"o", 1, 0, 'o'},
1069 {"r", 0, 0, 'r'},
1070 {"s", 0, 0, 's'},
1071 {"t", 0, 0, 't'},
1072 {"u", 1, 0, 'u'},
1073 {"x", 0, 0, 'x'},
1074 {"z", 0, 0, 'z'},
1075 {"A", 1, 0, 'A'},
1076 {"D", 1, 0, 'D'},
1077 {"M", 0, 0, 'M'},
1078 {"N", 0, 0, 'N'},
1079 {"R", 0, 0, 'R'}, /* Create relocatable executable */
1080 {"Zexe", 0, 0, 135}, /* Create .exe file, touch `output file' */
1081 {"Zstack", 1, 0, 136}, /* Set stack size */
1082 {"Zmap", 2, 0, 137}, /* Create .map file */
1083 {"Zno-demangle", 0, 0, 138}, /* Don't demangle symbols */
1084 {"Zdemangle-proto", 0, 0, 139}, /* Demangle symbols complete */
1085 {"Zwin32", 0, 0, 140}, /* Create GUI, CUI Win32 */
1086 {"Zrsx32", 0, 0, 141}, /* Create Win32/DOS win32 base */
1087 {"Zemx32", 0, 0, 142}, /* Create Win32/DOS emx base */
1088 {"S", 0, 0, 'S'},
1089 {"T", 1, 0, 'T'},
1090 {"Ttext", 1, 0, 'T'},
1091 {"Tdata", 1, 0, 132},
1092 {"V", 1, 0, 'V'},
1093 {"X", 0, 0, 'X'},
1094#define OPT_LIBS_STATIC 0x1000
1095 {"Bstatic", 0, 0, OPT_LIBS_STATIC},
1096 {"non_shared", 0, 0, OPT_LIBS_STATIC},
1097 {"dn", 0, 0, OPT_LIBS_STATIC},
1098 {"static", 0, 0, OPT_LIBS_STATIC},
1099#define OPT_LIBS_SHARED 0x1001
1100 {"Bshared", 0, 0, OPT_LIBS_SHARED},
1101 {"call_shared", 0, 0, OPT_LIBS_SHARED},
1102 {"dy", 0, 0, OPT_LIBS_SHARED},
1103#define OPT_ZDLL_SEARCH 0x1008
1104 {"Zdll-search",0, 0, OPT_ZDLL_SEARCH},
1105 {0, 0, 0, 0}
1106};
1107
1108/* Since the Unix ld accepts -lfoo, -Lfoo, and -yfoo, we must also.
1109 This effectively prevents any long options from starting with
1110 one of these letters. */
1111#define SHORTOPTS "-l:y:L:"
1112
1113/* Process the command arguments,
1114 setting up file_table with an entry for each input file,
1115 and setting variables according to the options. */
1116
1117void
1118decode_command (argc, argv)
1119 char **argv;
1120 int argc;
1121{
1122 int optc, longind;
1123 register struct file_entry *p;
1124 int opt_libs_static = 0;
1125
1126 number_of_files = 0;
1127 output_filename = "a.out";
1128
1129 n_search_dirs = 0;
1130 search_dirs = (char **) xmalloc (sizeof (char *));
1131
1132 /* First compute number_of_files so we know how long to make file_table.
1133 Also process most options completely. */
1134
1135 while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
1136 != EOF)
1137 {
1138 if (optc == 0)
1139 optc = longopts[longind].val;
1140
1141 switch (optc)
1142 {
1143 case '?':
1144 usage (0, 0);
1145 break;
1146
1147 case 1:
1148 /* Non-option argument. */
1149 number_of_files++;
1150 break;
1151
1152 case 'd':
1153 force_common_definition = 1;
1154 break;
1155
1156 case 'e':
1157 entry_symbol = getsym (optarg);
1158 if (!entry_symbol->defined && !entry_symbol->referenced)
1159 undefined_global_sym_count++;
1160 entry_symbol->referenced = 1;
1161 add_cmdline_ref (entry_symbol);
1162 break;
1163
1164 case 'l':
1165 number_of_files++;
1166 break;
1167
1168 case 'n':
1169 if (output_style && output_style != OUTPUT_READONLY_TEXT)
1170 fatal ("illegal combination of -n with -N, -r, or -z", (char *) 0);
1171 output_style = OUTPUT_READONLY_TEXT;
1172 break;
1173
1174 case 130: /* -noinhibit-exec */
1175 force_executable = 1;
1176 break;
1177
1178 case 133: /* -nostdlib */
1179 no_standard_dirs = 1;
1180 break;
1181
1182 case 'o':
1183 output_filename = optarg;
1184 break;
1185
1186 case 'r':
1187 if (output_style && output_style != OUTPUT_RELOCATABLE)
1188 fatal ("illegal combination of -r with -N, -n, or -z", (char *) 0);
1189 output_style = OUTPUT_RELOCATABLE;
1190 text_start = 0;
1191 break;
1192
1193 case 's':
1194 strip_symbols = STRIP_ALL;
1195 break;
1196
1197 case 't':
1198 trace_files = 1;
1199 break;
1200
1201 case 'u':
1202 {
1203 register symbol *sp = getsym (optarg);
1204
1205 if (!sp->defined && !sp->referenced)
1206 undefined_global_sym_count++;
1207 sp->referenced = 1;
1208 add_cmdline_ref (sp);
1209 }
1210 break;
1211
1212 case 'x':
1213 discard_locals = DISCARD_ALL;
1214 break;
1215
1216 case 'y':
1217 {
1218 register symbol *sp = getsym (optarg);
1219
1220 sp->trace = 1;
1221 }
1222 break;
1223
1224 case 'z':
1225 if (output_style && output_style != OUTPUT_DEMAND_PAGED)
1226 fatal ("illegal combination of -z with -N, -n, or -r", (char *) 0);
1227 output_style = OUTPUT_DEMAND_PAGED;
1228 break;
1229
1230 case 'A':
1231 number_of_files++;
1232 break;
1233
1234 case 'D':
1235 specified_data_size = parse (optarg, "%x", "invalid argument to -D");
1236 break;
1237
1238 case 'L':
1239 n_search_dirs++;
1240 search_dirs = (char **)
1241 xrealloc (search_dirs, n_search_dirs * sizeof (char *));
1242 search_dirs[n_search_dirs - 1] = optarg;
1243 break;
1244
1245 case 'M':
1246 write_map = 1;
1247 break;
1248
1249 case 'N':
1250 if (output_style && output_style != OUTPUT_WRITABLE_TEXT)
1251 fatal ("illegal combination of -N with -n, -r, or -z", (char *) 0);
1252 output_style = OUTPUT_WRITABLE_TEXT;
1253 break;
1254
1255 case 135: /* -Zexe */
1256 exe_flag = 1;
1257 break;
1258
1259 case 136: /* -Zstack */
1260 stack_size = parse (optarg, "%i", "invalid argument to -Zstack");
1261 break;
1262
1263 case 137: /* -Zmap */
1264 map_filename = optarg;
1265 map_flag = 1;
1266 break;
1267
1268 case 138: /* -Zno-demangle */
1269 demangler = 0;
1270 break;
1271
1272 case 139: /* -Zdemangle-proto */
1273 demangle_options = DMGL_PARAMS | DMGL_ANSI;
1274 break;
1275
1276 case 140: /* -Zwin32: GUI,CUI Win32 */
1277 rsxnt_linked = RSXNT_WIN32;
1278 break;
1279
1280 case 141: /* -Zrsx32: Win32/DOS win32 base */
1281 rsxnt_linked = RSXNT_RSX;
1282 break;
1283
1284 case 142: /* -Zemx32: Win32/DOS emx base */
1285 rsxnt_linked = RSXNT_EMX;
1286 break;
1287
1288 case 'R':
1289 reloc_flag = 1;
1290 break;
1291
1292 case 'S':
1293 strip_symbols = STRIP_DEBUGGER;
1294 break;
1295
1296 case 'T':
1297 text_start = parse (optarg, "%x", "invalid argument to -Ttext");
1298 T_flag_specified = 1;
1299 break;
1300
1301 case 132: /* -Tdata addr */
1302 data_start = parse (optarg, "%x", "invalid argument to -Tdata");
1303 Tdata_flag_specified = 1;
1304 break;
1305
1306 case 'V':
1307 {
1308 struct string_list_element *new
1309 = (struct string_list_element *)
1310 xmalloc (sizeof (struct string_list_element));
1311
1312 new->str = optarg;
1313 new->next = set_element_prefixes;
1314 set_element_prefixes = new;
1315 }
1316 break;
1317
1318 case 'X':
1319 discard_locals = DISCARD_L;
1320 break;
1321
1322 case OPT_ZDLL_SEARCH:
1323 opt_dll_search = 1;
1324 break;
1325
1326 case OPT_LIBS_STATIC:
1327 case OPT_LIBS_SHARED:
1328 /* processed later */
1329 break;
1330 }
1331 }
1332
1333 if (!number_of_files)
1334 usage ("no input files", 0);
1335
1336 p = file_table
1337 = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
1338 bzero (p, number_of_files * sizeof (struct file_entry));
1339
1340 /* Now scan again and fill in file_table.
1341 All options except -A and -l are ignored here. */
1342
1343 optind = 0; /* Reset getopt. */
1344 while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
1345 != EOF)
1346 {
1347 if (optc == 0)
1348 optc = longopts[longind].val;
1349
1350 switch (optc)
1351 {
1352 case 1:
1353 /* Non-option argument. */
1354 {
1355 char *ext = _getext (optarg);
1356 if (ext != NULL && stricmp (ext, ".def") == 0
1357 && def_filename == NULL)
1358 {
1359 def_filename = optarg;
1360 --number_of_files;
1361 break;
1362 }
1363 else if (ext != NULL && stricmp (ext, ".res") == 0
1364 && res_filename == NULL)
1365 {
1366 res_filename = optarg;
1367 --number_of_files;
1368 break;
1369 }
1370 else if (ext != NULL && stricmp (ext, ".dll") == 0
1371 && res_filename == NULL)
1372 { /* convert .dll to temporary import library. */
1373 p->filename = lx_to_aout (optarg);
1374 p->local_sym_name = optarg;
1375 p++;
1376 break;
1377 }
1378 }
1379 p->filename = optarg;
1380 p->local_sym_name = optarg;
1381 p++;
1382 break;
1383
1384 case 'A':
1385 if (p != file_table)
1386 usage ("-A specified before an input file other than the first", NULL);
1387 p->filename = optarg;
1388 p->local_sym_name = optarg;
1389 p->just_syms_flag = 1;
1390 p++;
1391 break;
1392
1393 case 'l':
1394 p->filename = concat ("", optarg, "");
1395 p->local_sym_name = concat ("-l", optarg, "");
1396 p->search_dirs_flag = 1;
1397 p->dynamic = !opt_libs_static;
1398 p++;
1399 break;
1400
1401 case OPT_LIBS_STATIC:
1402 opt_libs_static = 1;
1403 break;
1404 case OPT_LIBS_SHARED:
1405 opt_libs_static = 0;
1406 break;
1407 }
1408 }
1409
1410 if (!output_file_type)
1411 output_file_type = DEFAULT_OUTPUT_FILE_TYPE;
1412
1413 if (!output_style)
1414 output_style = DEFAULT_OUTPUT_STYLE;
1415
1416#if 0
1417 /* THIS CONSISTENCY CHECK BELONGS SOMEWHERE ELSE. */
1418 /* Now check some option settings for consistency. */
1419
1420 if ((output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
1421 && (text_start - text_start_alignment) & (page_size - 1))
1422 usage ("-T argument not multiple of page size, with sharable output", 0);
1423#endif
1424
1425 /* Append the standard search directories to the user-specified ones. */
1426 if (!no_standard_dirs)
1427 {
1428 int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
1429 n_search_dirs += n;
1430 search_dirs
1431 = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
1432 bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
1433 n * sizeof (char *));
1434 }
1435}
1436
1437
1438
1439void
1440add_cmdline_ref (sp)
1441 struct glosym *sp;
1442{
1443 struct glosym **ptr;
1444
1445 for (ptr = cmdline_references;
1446 ptr < cmdline_references + cl_refs_allocated && *ptr;
1447 ptr++)
1448 ;
1449
1450 if (ptr >= cmdline_references + cl_refs_allocated - 1)
1451 {
1452 int diff = ptr - cmdline_references;
1453
1454 cl_refs_allocated *= 2;
1455 cmdline_references = (struct glosym **)
1456 xrealloc (cmdline_references,
1457 cl_refs_allocated * sizeof (struct glosym *));
1458 ptr = cmdline_references + diff;
1459 }
1460
1461 *ptr++ = sp;
1462 *ptr = (struct glosym *) 0;
1463}
1464
1465static int
1466set_element_prefixed_p (name)
1467 char *name;
1468{
1469 struct string_list_element *p;
1470 int i;
1471
1472 for (p = set_element_prefixes; p; p = p->next)
1473 {
1474 for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
1475 ;
1476
1477 if (p->str[i] == '\0')
1478 return 1;
1479 }
1480 return 0;
1481}
1482
1483
1484/* Convenient functions for operating on one or all files being
1485 loaded. */
1486void print_file_name (struct file_entry *entry, FILE *outfile);
1487
1488/* Call FUNCTION on each input file entry.
1489 Do not call for entries for libraries;
1490 instead, call once for each library member that is being loaded.
1491
1492 FUNCTION receives two arguments: the entry, and ARG. */
1493
1494static void
1495each_file (function, arg)
1496 register void (*function)();
1497 register int arg;
1498{
1499 register int i;
1500
1501 for (i = 0; i < number_of_files; i++)
1502 {
1503 register struct file_entry *entry = &file_table[i];
1504 if (entry->library_flag)
1505 {
1506 register struct file_entry *subentry = entry->subfiles;
1507 for (; subentry; subentry = subentry->chain)
1508 (*function) (subentry, arg);
1509 }
1510 else
1511 (*function) (entry, arg);
1512 }
1513}
1514
1515/* Call FUNCTION on each input file entry until it returns a non-zero
1516 value. Return this value.
1517 Do not call for entries for libraries;
1518 instead, call once for each library member that is being loaded.
1519
1520 FUNCTION receives two arguments: the entry, and ARG. It must be a
1521 function returning unsigned long (though this can probably be fudged). */
1522
1523unsigned long
1524check_each_file (function, arg)
1525 register unsigned long (*function)();
1526 register int arg;
1527{
1528 register int i;
1529 register unsigned long return_val;
1530
1531 for (i = 0; i < number_of_files; i++)
1532 {
1533 register struct file_entry *entry = &file_table[i];
1534 if (entry->library_flag)
1535 {
1536 register struct file_entry *subentry = entry->subfiles;
1537 for (; subentry; subentry = subentry->chain)
1538 if ((return_val = (*function) (subentry, arg)))
1539 return return_val;
1540 }
1541 else
1542 if ((return_val = (*function) (entry, arg)))
1543 return return_val;
1544 }
1545 return 0;
1546}
1547
1548/* Like `each_file' but ignore files that were just for symbol definitions. */
1549
1550static void
1551each_full_file (function, arg)
1552 register void (*function)();
1553 register int arg;
1554{
1555 register int i;
1556
1557 for (i = 0; i < number_of_files; i++)
1558 {
1559 register struct file_entry *entry = &file_table[i];
1560 if (entry->just_syms_flag)
1561 continue;
1562 if (entry->library_flag)
1563 {
1564 register struct file_entry *subentry = entry->subfiles;
1565 for (; subentry; subentry = subentry->chain)
1566 (*function) (subentry, arg);
1567 }
1568 else
1569 (*function) (entry, arg);
1570 }
1571}
1572
1573/* Close the input file that is now open. */
1574
1575static void
1576file_close ()
1577{
1578 close (input_desc);
1579 input_desc = 0;
1580 input_file = 0;
1581}
1582
1583/* Open the input file specified by 'entry', and return a descriptor.
1584 The open file is remembered; if the same file is opened twice in a row,
1585 a new open is not actually done. */
1586
1587static int
1588file_open (entry)
1589 register struct file_entry *entry;
1590{
1591 register int desc = -1;
1592
1593 if (entry->superfile)
1594 return file_open (entry->superfile);
1595
1596 if (entry == input_file)
1597 return input_desc;
1598
1599 if (input_file) file_close ();
1600
1601 if (entry->search_dirs_flag && n_search_dirs)
1602 {
1603 /* !we're searching for libraries here! */
1604 static const char *dynamic_dll_suffs[] = { "_dll.a", ".a", ".dll", "_s.a", NULL };
1605 static const char *dynamic_suffs[] = { "_dll.a", ".a", "_s.a", NULL };
1606 static const char *static_suffs[] = { "_s.a", ".a", NULL };
1607 const char **suffs = entry->dynamic ? opt_dll_search ? dynamic_dll_suffs : dynamic_suffs : static_suffs;
1608 int lenname = strlen (entry->filename);
1609 int i;
1610
1611 for (i = 0; i < n_search_dirs; i++)
1612 {
1613 int lendir = strlen (search_dirs[i]);
1614 register char *string = xmalloc (lendir + lenname + 4 + 6 + 1);
1615 int j;
1616
1617 memcpy (string, search_dirs[i], lendir);
1618 string[lendir++] = '/';
1619 for (j = 0; suffs[j]; j++)
1620 {
1621 static const char *prefixes[] = { "lib", ""};
1622 int k;
1623 for (k = 0; k < sizeof(prefixes) / sizeof(prefixes[0]); k++)
1624 {
1625 int len = strlen (prefixes[k]);
1626 memcpy (string + lendir, prefixes[k], len);
1627 len += lendir;
1628 memcpy (string + len, entry->filename, lenname);
1629 len += lenname;
1630 strcpy (string + len, suffs[j]);
1631
1632 desc = open (string, O_RDONLY|O_BINARY, 0);
1633 if (desc > 0)
1634 {
1635 /* convert? */
1636 if (check_lx_dll (desc))
1637 {
1638 string = lx_to_aout (string);
1639 if (!string || (desc = open (string, O_RDONLY|O_BINARY, 0)) < 0)
1640 perror_file (entry);
1641 }
1642 entry->filename = string;
1643 entry->search_dirs_flag = 0;
1644 input_file = entry;
1645 input_desc = desc;
1646 return desc;
1647 }
1648 } /* prefix loop */
1649 } /* suffix loop */
1650 free (string);
1651 } /* dir loop */
1652 }
1653 else
1654 desc = open (entry->filename, O_RDONLY|O_BINARY, 0);
1655
1656 if (desc > 0)
1657 {
1658 input_file = entry;
1659 input_desc = desc;
1660 return desc;
1661 }
1662
1663 perror_file (entry);
1664 /* NOTREACHED */
1665 return -1;
1666}
1667
1668/* Print the filename of ENTRY on OUTFILE (a stdio stream),
1669 and then a newline. */
1670
1671void
1672prline_file_name (entry, outfile)
1673 struct file_entry *entry;
1674 FILE *outfile;
1675{
1676 print_file_name (entry, outfile);
1677 fprintf (outfile, "\n");
1678}
1679
1680/* Print the filename of ENTRY on OUTFILE (a stdio stream). */
1681
1682void
1683print_file_name (entry, outfile)
1684 struct file_entry *entry;
1685 FILE *outfile;
1686{
1687 if (entry->superfile)
1688 {
1689 print_file_name (entry->superfile, outfile);
1690 fprintf (outfile, "(%s)", entry->filename);
1691 }
1692 else
1693 fprintf (outfile, "%s", entry->filename);
1694}
1695
1696/* Return the filename of entry as a string (malloc'd for the purpose) */
1697
1698char *
1699get_file_name (entry)
1700 struct file_entry *entry;
1701{
1702 char *result, *supfile;
1703 if (entry->superfile)
1704 {
1705 supfile = get_file_name (entry->superfile);
1706 result = (char *) xmalloc (strlen (supfile)
1707 + strlen (entry->filename) + 3);
1708 sprintf (result, "%s(%s)", supfile, entry->filename);
1709 free (supfile);
1710 }
1711 else
1712 {
1713 result = (char *) xmalloc (strlen (entry->filename) + 1);
1714 strcpy (result, entry->filename);
1715 }
1716 return result;
1717}
1718
1719
1720/* Medium-level input routines for rel files. */
1721
1722/* Determine whether the given ENTRY is an archive, a BSD a.out file,
1723 a Mach-O file, or whatever. DESC is the descriptor on which the
1724 file is open. */
1725void
1726deduce_file_type(desc, entry)
1727 int desc;
1728 struct file_entry *entry;
1729{
1730 int len;
1731
1732 {
1733 char magic[SARMAG];
1734
1735 lseek (desc, entry->starting_offset, 0);
1736 len = read (desc, magic, SARMAG);
1737 if (len == SARMAG && !strncmp(magic, ARMAG, SARMAG))
1738 {
1739 entry->file_type = IS_ARCHIVE;
1740 return;
1741 }
1742 }
1743
1744#ifdef A_OUT
1745 {
1746 struct exec hdr;
1747
1748 lseek (desc, entry->starting_offset, 0);
1749 len = read (desc, (char *) &hdr, sizeof (struct exec));
1750 if (len == sizeof (struct exec) && !N_BADMAG (hdr))
1751 {
1752 entry->file_type = IS_A_OUT;
1753 return;
1754 }
1755 }
1756#endif
1757
1758 fatal_with_file ("malformed input file (not rel or archive) ", entry);
1759}
1760
1761#ifdef A_OUT
1762/* Read an a.out file's header and set up the fields of
1763 the ENTRY accordingly. DESC is the descriptor on which
1764 the file is open. */
1765void
1766read_a_out_header (desc, entry)
1767 int desc;
1768 struct file_entry *entry;
1769{
1770 struct exec hdr;
1771 struct stat st;
1772
1773 lseek (desc, entry->starting_offset, 0);
1774 read (desc, (char *) &hdr, sizeof (struct exec));
1775
1776#ifdef READ_HEADER_HOOK
1777 READ_HEADER_HOOK(hdr.a_machtype);
1778#endif
1779
1780 if (entry->just_syms_flag)
1781 entry->orig_text_address = N_TXTADDR(hdr);
1782 else
1783 entry->orig_text_address = 0;
1784 entry->text_size = hdr.a_text;
1785 entry->text_offset = N_TXTOFF(hdr);
1786
1787 entry->text_reloc_size = hdr.a_trsize;
1788#ifdef N_TRELOFF
1789 entry->text_reloc_offset = N_TRELOFF(hdr);
1790#else
1791#ifdef N_DATOFF
1792 entry->text_reloc_offset = N_DATOFF(hdr) + hdr.a_data;
1793#else
1794 entry->text_reloc_offset = N_TXTOFF(hdr) + hdr.a_text + hdr.a_data;
1795#endif
1796#endif
1797
1798 if (entry->just_syms_flag)
1799 entry->orig_data_address = N_DATADDR(hdr);
1800 else
1801 entry->orig_data_address = entry->text_size;
1802 entry->data_size = hdr.a_data;
1803#ifdef N_DATOFF
1804 entry->data_offset = N_DATOFF(hdr);
1805#else
1806 entry->data_offset = N_TXTOFF(hdr) + hdr.a_text;
1807#endif
1808
1809 entry->data_reloc_size = hdr.a_drsize;
1810#ifdef N_DRELOFF
1811 entry->data_reloc_offset = N_DRELOFF(hdr);
1812#else
1813 entry->data_reloc_offset = entry->text_reloc_offset + entry->text_reloc_size;
1814#endif
1815
1816#ifdef N_BSSADDR
1817 if (entry->just_syms_flag)
1818 entry->orig_bss_address = N_BSSADDR(hdr);
1819 else
1820#endif
1821 entry->orig_bss_address = entry->orig_data_address + entry->data_size;
1822 entry->bss_size = hdr.a_bss;
1823
1824 entry->syms_size = hdr.a_syms;
1825 entry->syms_offset = N_SYMOFF(hdr);
1826 entry->strs_offset = N_STROFF(hdr);
1827 lseek(desc, entry->starting_offset + entry->strs_offset, 0);
1828 if (entry->syms_size &&
1829 read(desc, (char *) &entry->strs_size, sizeof (unsigned long int))
1830 != sizeof (unsigned long int))
1831 fatal_with_file ("failure reading string table size of ", entry);
1832
1833 if (!entry->superfile)
1834 {
1835 fstat(desc, &st);
1836 if (st.st_size > entry->strs_offset + entry->strs_size)
1837 {
1838 entry->symseg_size = st.st_size - (entry->strs_offset + entry->strs_size);
1839 entry->symseg_offset = entry->strs_offset + entry->strs_size;
1840 }
1841 }
1842 else
1843 if (entry->total_size > entry->strs_offset + entry->strs_size)
1844 {
1845 entry->symseg_size = entry->total_size - (entry->strs_offset + entry->strs_size);
1846 entry->symseg_offset = entry->strs_offset + entry->strs_size;
1847 }
1848}
1849#endif
1850
1851/* Read a file's header info into the proper place in the file_entry.
1852 DESC is the descriptor on which the file is open.
1853 ENTRY is the file's entry.
1854 Switch in the file_type to determine the appropriate actual
1855 header reading routine to call. */
1856
1857void
1858read_header (desc, entry)
1859 int desc;
1860 register struct file_entry *entry;
1861{
1862 if (!entry->file_type)
1863 deduce_file_type (desc, entry);
1864
1865 switch (entry->file_type)
1866 {
1867 case IS_ARCHIVE:
1868 default:
1869 /* Should never happen. */
1870 abort ();
1871
1872#ifdef A_OUT
1873 case IS_A_OUT:
1874 read_a_out_header (desc, entry);
1875 break;
1876#endif
1877 }
1878
1879 entry->header_read_flag = 1;
1880}
1881
1882/* Read the symbols of file ENTRY into core.
1883 Assume it is already open, on descriptor DESC. */
1884
1885void
1886read_entry_symbols (desc, entry)
1887 struct file_entry *entry;
1888 int desc;
1889{
1890 if (!entry->header_read_flag)
1891 read_header (desc, entry);
1892
1893 entry->symbols = (struct nlist *) xmalloc (entry->syms_size);
1894
1895 lseek (desc, entry->syms_offset + entry->starting_offset, 0);
1896 if (entry->syms_size != read (desc, entry->symbols, entry->syms_size))
1897 fatal_with_file ("premature end of file in symbols of ", entry);
1898}
1899
1900/* Read the string table of file ENTRY into core.
1901 Assume it is already open, on descriptor DESC. */
1902
1903void
1904read_entry_strings (desc, entry)
1905 int desc;
1906 struct file_entry *entry;
1907{
1908 if (!entry->header_read_flag)
1909 read_header (desc, entry);
1910
1911 lseek (desc, entry->strs_offset + entry->starting_offset, 0);
1912 if (entry->strs_size != read (desc, entry->strings, entry->strs_size))
1913 fatal_with_file ("premature end of file in strings of ", entry);
1914}
1915
1916
1917/* Read in the symbols of all input files. */
1918
1919void enter_file_symbols (struct file_entry *entry);
1920void enter_global_ref (register struct nlist *nlist_p, char *name, struct file_entry *entry);
1921void search_library (int desc, struct file_entry *entry);
1922
1923void
1924load_symbols (void)
1925{
1926 register int i;
1927
1928 if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
1929
1930 for (i = 0; i < number_of_files; i++)
1931 {
1932 register struct file_entry *entry = &file_table[i];
1933 read_file_symbols (entry);
1934 }
1935
1936 if (trace_files) fprintf (stderr, "\n");
1937}
1938
1939/* If ENTRY is a rel file, read its symbol and string sections into core.
1940 If it is a library, search it and load the appropriate members
1941 (which means calling this function recursively on those members). */
1942
1943void
1944read_file_symbols (entry)
1945 register struct file_entry *entry;
1946{
1947 register int desc;
1948
1949 desc = file_open (entry);
1950
1951 if (!entry->file_type)
1952 deduce_file_type (desc, entry);
1953
1954 if (entry->file_type == IS_ARCHIVE)
1955 {
1956 entry->library_flag = 1;
1957 search_library (desc, entry);
1958 }
1959 else
1960 {
1961 read_entry_symbols (desc, entry);
1962 entry->strings = (char *) ALLOCA (entry->strs_size);
1963 read_entry_strings (desc, entry);
1964 enter_file_symbols (entry);
1965 FREEA (entry->strings);
1966 }
1967
1968 file_close ();
1969}
1970
1971
1972/* Enter the external symbol defs and refs of ENTRY in the hash table. */
1973
1974void
1975enter_file_symbols (entry)
1976 struct file_entry *entry;
1977{
1978 register struct nlist
1979 *p,
1980 *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
1981
1982 if (trace_files) prline_file_name (entry, stderr);
1983
1984 for (p = entry->symbols; p < end; p++)
1985 {
1986 if (p->n_type == (N_SETV | N_EXT)) continue;
1987 if (p->n_type == (N_IMP1 | N_EXT))
1988 reloc_flag = 1;
1989 if (set_element_prefixes
1990 && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
1991 p->n_type += (N_SETA - N_ABS);
1992
1993 if (SET_ELEMENT_P (p->n_type))
1994 {
1995 set_symbol_count++;
1996 if (output_style != OUTPUT_RELOCATABLE)
1997 enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
1998 }
1999 else if (p->n_type == N_WARNING)
2000 {
2001 char *name = p->n_un.n_strx + entry->strings;
2002
2003 /* Grab the next entry. */
2004 p++;
2005 if (p->n_type != (N_UNDF | N_EXT))
2006 {
2007 fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
2008 progname, entry->filename);
2009 make_executable = 0;
2010 p--; /* Process normally. */
2011 }
2012 else
2013 {
2014 symbol *sp;
2015 char *sname = p->n_un.n_strx + entry->strings;
2016 /* Deal with the warning symbol. */
2017 enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
2018 sp = getsym (sname);
2019 sp->warning = (char *) xmalloc (strlen(name) + 1);
2020 strcpy (sp->warning, name);
2021 warning_count++;
2022 }
2023 }
2024 else if (WEAK_SYMBOL (p->n_type))
2025 {
2026 /* Enter the symbol into the symbol hash table only if it
2027 has not already been defined */
2028 symbol *s = getsym_soft (p->n_un.n_strx + entry->strings);
2029 if (!s || !s->defined)
2030 enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
2031 else if (s) /* hack! */
2032 p->n_un.n_name = (char*)s;
2033#ifdef DEBUG
2034 else fprintf(stderr, "dbg-warning: %s - sym %d: '%s' no such symbol...\n",
2035 entry->filename,
2036 p - entry->symbols,
2037 p->n_un.n_strx + entry->strings);
2038#endif
2039 }
2040 else if (p->n_type & N_EXT)
2041 enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
2042 else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
2043 {
2044 if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
2045 non_L_local_sym_count++;
2046 local_sym_count++;
2047 }
2048 else debugger_sym_count++;
2049#ifdef DEBUG_BIRD
2050 fprintf(stderr, "dbg: %s sym #%3d: un=%08lx typ=%02x\n",
2051 entry->filename,
2052 p - entry->symbols,
2053 p->n_un.n_strx,
2054 p->n_type);
2055#endif
2056 }
2057
2058 /* Count one for the local symbol that we generate,
2059 whose name is the file's name (usually) and whose address
2060 is the start of the file's text. */
2061
2062 local_sym_count++;
2063 non_L_local_sym_count++;
2064}
2065
2066/* Enter one global symbol in the hash table.
2067 NLIST_P points to the `struct nlist' read from the file
2068 that describes the global symbol. NAME is the symbol's name.
2069 ENTRY is the file entry for the file the symbol comes from.
2070
2071 The `struct nlist' is modified by placing it on a chain of
2072 all such structs that refer to the same global symbol.
2073 This chain starts in the `refs' field of the symbol table entry
2074 and is chained through the `n_name'. */
2075
2076void
2077enter_global_ref (nlist_p, name, entry)
2078 register struct nlist *nlist_p;
2079 char *name;
2080 struct file_entry *entry;
2081{
2082 register symbol *sp = getsym (name);
2083 register int type = nlist_p->n_type;
2084 const int realtype = type;
2085 int oldref = sp->referenced;
2086 int olddef = sp->defined;
2087
2088 nlist_p->n_un.n_name = (char *) sp->refs;
2089 sp->refs = nlist_p;
2090
2091 sp->referenced = 1;
2092
2093 if (WEAK_SYMBOL (type))
2094 {
2095 sp->weak = type;
2096 /* Switch symbol type so that it can be processed like regular symbols */
2097 type = nlist_p->n_type =
2098 (type == N_WEAKU) ? N_UNDF | N_EXT :
2099 (type == N_WEAKA) ? N_ABS | N_EXT :
2100 (type == N_WEAKT) ? N_TEXT | N_EXT :
2101 (type == N_WEAKD) ? N_DATA | N_EXT :
2102 /*(type == N_WEAKB)*/ N_BSS | N_EXT;
2103 }
2104
2105 if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
2106 {
2107 if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
2108 sp->defined = type;
2109
2110 if (oldref && !olddef)
2111 /* It used to be undefined and we're defining it. */
2112 undefined_global_sym_count--;
2113
2114 if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
2115 {
2116 /* First definition and it's common. */
2117 common_defined_global_count++;
2118 sp->max_common_size = nlist_p->n_value;
2119 }
2120 else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
2121 {
2122 /* It used to be common and we're defining it as
2123 something else. */
2124 common_defined_global_count--;
2125 sp->max_common_size = 0;
2126
2127 fprintf (stderr, "%s: symbol `%s' defined more than once in ",
2128 progname, name);
2129 print_file_name (entry, stderr);
2130 fprintf (stderr, "\n");
2131 exit (1);
2132 }
2133 else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
2134 && sp->max_common_size < nlist_p->n_value)
2135 /* It used to be common and this is a new common entry to
2136 which we need to pay attention. */
2137 sp->max_common_size = nlist_p->n_value;
2138
2139 /* Are we defining it as a set element? */
2140 if (SET_ELEMENT_P (type)
2141 && (!olddef || (olddef && sp->max_common_size)))
2142 set_vector_count++;
2143 /* As an indirection? */
2144 else if (type == (N_INDR | N_EXT))
2145 {
2146 /* Indirect symbols value should be modified to point
2147 a symbol being equivalenced to. */
2148 nlist_p->n_value
2149 = (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
2150 + entry->strings);
2151 if ((symbol *) nlist_p->n_value == sp)
2152 {
2153 /* Somebody redefined a symbol to be itself. */
2154 fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
2155 entry->filename, name);
2156 /* Rewrite this symbol as being a global text symbol
2157 with value 0. */
2158 nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
2159 nlist_p->n_value = 0;
2160 /* Don't make the output executable. */
2161 make_executable = 0;
2162 }
2163 else
2164 global_indirect_count++;
2165 }
2166 }
2167 else
2168 if (!oldref)
2169 undefined_global_sym_count++;
2170
2171 if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
2172 text_start = nlist_p->n_value;
2173
2174#ifdef DEBUG_BIRD
2175 sp->trace = 1;
2176#endif
2177 if (sp->trace)
2178 {
2179 register char *reftype;
2180 int free_reftype = 0;
2181 switch (realtype & ~N_EXT)
2182 {
2183 case N_UNDF:
2184 if (nlist_p->n_value)
2185 reftype = "defined as common";
2186 else reftype = "referenced";
2187 break;
2188
2189 case N_ABS:
2190 reftype = "defined as absolute";
2191 break;
2192
2193 case N_TEXT:
2194 reftype = "defined in text section";
2195 break;
2196
2197 case N_DATA:
2198 reftype = "defined in data section";
2199 break;
2200
2201 case N_BSS:
2202 reftype = "defined in BSS section";
2203 break;
2204
2205 case N_SETT:
2206 reftype = "is a text set element";
2207 break;
2208
2209 case N_SETD:
2210 reftype = "is a data set element";
2211 break;
2212
2213 case N_SETB:
2214 reftype = "is a BSS set element";
2215 break;
2216
2217 case N_SETA:
2218 reftype = "is an absolute set element";
2219 break;
2220
2221 case N_SETV:
2222 reftype = "defined in data section as vector";
2223 break;
2224
2225 case N_INDR:
2226 reftype = (char *) ALLOCA (23 + strlen (((symbol *) nlist_p->n_value)->name));
2227 sprintf (reftype, "defined equivalent to %s",
2228 ((symbol *) nlist_p->n_value)->name);
2229 free_reftype = 1;
2230 break;
2231
2232 case N_IMP1:
2233 reftype = "imported";
2234 break;
2235
2236 case N_WEAKU & ~N_EXT:
2237 reftype = "weak";
2238 break;
2239
2240 case N_WEAKT & ~N_EXT:
2241 reftype = "weak text";
2242 break;
2243
2244 case N_WEAKD & ~N_EXT:
2245 reftype = "weak data";
2246 break;
2247
2248 default:
2249 reftype = "I don't know this type";
2250 break;
2251 }
2252
2253
2254 fprintf (stderr, "symbol in ");
2255 print_file_name (entry, stderr);
2256 fprintf (stderr, ": %3d %s %s\n",
2257 nlist_p - entry->symbols, sp->name, reftype);
2258 if (free_reftype)
2259 FREEA (reftype);
2260 }
2261}
2262
2263/* This return 0 if the given file entry's symbol table does *not*
2264 contain the nlist point entry, and it returns the files entry
2265 pointer (cast to unsigned long) if it does. */
2266
2267unsigned long
2268contains_symbol (entry, n_ptr)
2269 struct file_entry *entry;
2270 register struct nlist *n_ptr;
2271{
2272 if (n_ptr >= entry->symbols &&
2273 n_ptr < (entry->symbols
2274 + (entry->syms_size / sizeof (struct nlist))))
2275 return (unsigned long) entry;
2276 return 0;
2277}
2278
2279
2280
2281/* Searching libraries */
2282
2283struct file_entry * decode_library_subfile (int desc, struct file_entry *library_entry, int subfile_offset, int *length_loc);
2284void symdef_library (int desc, struct file_entry *entry, int member_length);
2285void linear_library (int desc, struct file_entry *entry);
2286
2287/* Search the library ENTRY, already open on descriptor DESC.
2288 This means deciding which library members to load,
2289 making a chain of `struct file_entry' for those members,
2290 and entering their global symbols in the hash table. */
2291
2292void
2293search_library (desc, entry)
2294 int desc;
2295 struct file_entry *entry;
2296{
2297 int member_length;
2298 register char *name;
2299 register struct file_entry *subentry;
2300
2301 if (!undefined_global_sym_count) return;
2302
2303 /* Examine its first member, which starts SARMAG bytes in. */
2304 subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
2305 if (!subentry) return;
2306
2307 name = subentry->filename;
2308 free (subentry);
2309
2310 /* Search via __.SYMDEF if that exists, else linearly. */
2311
2312 if (!strcmp (name, "__.SYMDEF"))
2313 symdef_library (desc, entry, member_length);
2314 else
2315 linear_library (desc, entry);
2316}
2317
2318/* Construct and return a file_entry for a library member.
2319 The library's file_entry is library_entry, and the library is open on DESC.
2320 SUBFILE_OFFSET is the byte index in the library of this member's header.
2321 We store the length of the member into *LENGTH_LOC. */
2322
2323struct file_entry *
2324decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
2325 int desc;
2326 struct file_entry *library_entry;
2327 int subfile_offset;
2328 int *length_loc;
2329{
2330 int bytes_read;
2331 register int namelen;
2332 int member_length;
2333 register char *name;
2334 struct ar_hdr hdr1;
2335 register struct file_entry *subentry;
2336
2337 lseek (desc, subfile_offset, 0);
2338
2339 bytes_read = read (desc, &hdr1, sizeof hdr1);
2340 if (!bytes_read)
2341 return 0; /* end of archive */
2342
2343 if (sizeof hdr1 != bytes_read)
2344 fatal_with_file ("malformed library archive ", library_entry);
2345
2346 if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
2347 fatal_with_file ("malformatted header of archive member in ", library_entry);
2348
2349 subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
2350 bzero (subentry, sizeof (struct file_entry));
2351
2352 for (namelen = 0;
2353 namelen < sizeof hdr1.ar_name
2354 && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
2355 && hdr1.ar_name[namelen] != '/';
2356 namelen++);
2357
2358 name = (char *) xmalloc (namelen+1);
2359 strncpy (name, hdr1.ar_name, namelen);
2360 name[namelen] = 0;
2361
2362 subentry->filename = name;
2363 subentry->local_sym_name = name;
2364 subentry->symbols = 0;
2365 subentry->strings = 0;
2366 subentry->subfiles = 0;
2367 subentry->starting_offset = subfile_offset + sizeof hdr1;
2368 subentry->superfile = library_entry;
2369 subentry->library_flag = 0;
2370 subentry->header_read_flag = 0;
2371 subentry->just_syms_flag = 0;
2372 subentry->chain = 0;
2373 subentry->total_size = member_length;
2374
2375 (*length_loc) = member_length;
2376
2377 return subentry;
2378}
2379
2380
2381int subfile_wanted_p (struct file_entry *);
2382
2383/* Search a library that has a __.SYMDEF member.
2384 DESC is a descriptor on which the library is open.
2385 The file pointer is assumed to point at the __.SYMDEF data.
2386 ENTRY is the library's file_entry.
2387 MEMBER_LENGTH is the length of the __.SYMDEF data. */
2388
2389void
2390symdef_library (desc, entry, member_length)
2391 int desc;
2392 struct file_entry *entry;
2393 int member_length;
2394{
2395 int *symdef_data = (int *) xmalloc (member_length);
2396 register struct symdef *symdef_base;
2397 char *sym_name_base;
2398 int number_of_symdefs;
2399 int length_of_strings;
2400 int not_finished;
2401 int bytes_read;
2402 register int i;
2403 struct file_entry *prev = 0;
2404 int prev_offset = 0;
2405
2406 bytes_read = read (desc, symdef_data, member_length);
2407 if (bytes_read != member_length)
2408 fatal_with_file ("malformatted __.SYMDEF in ", entry);
2409
2410 number_of_symdefs = *symdef_data / sizeof (struct symdef);
2411 if (number_of_symdefs < 0 ||
2412 number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
2413 fatal_with_file ("malformatted __.SYMDEF in ", entry);
2414
2415 symdef_base = (struct symdef *) (symdef_data + 1);
2416 length_of_strings = *(int *) (symdef_base + number_of_symdefs);
2417
2418 if (length_of_strings < 0
2419 || number_of_symdefs * sizeof (struct symdef) + length_of_strings
2420 + 2 * sizeof (int) != member_length)
2421 fatal_with_file ("malformatted __.SYMDEF in ", entry);
2422
2423 sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
2424
2425 /* Check all the string indexes for validity. */
2426
2427 for (i = 0; i < number_of_symdefs; i++)
2428 {
2429 register int index = symdef_base[i].symbol_name_string_index;
2430 if (index < 0 || index >= length_of_strings
2431 || (index && *(sym_name_base + index - 1)))
2432 fatal_with_file ("malformatted __.SYMDEF in ", entry);
2433 }
2434
2435 /* Search the symdef data for members to load.
2436 Do this until one whole pass finds nothing to load. */
2437
2438 not_finished = 1;
2439 while (not_finished)
2440 {
2441 not_finished = 0;
2442
2443 /* Scan all the symbols mentioned in the symdef for ones that we need.
2444 Load the library members that contain such symbols. */
2445
2446 for (i = 0;
2447 (i < number_of_symdefs
2448 && (undefined_global_sym_count || common_defined_global_count));
2449 i++)
2450 if (symdef_base[i].symbol_name_string_index >= 0)
2451 {
2452 register symbol *sp;
2453
2454 sp = getsym_soft (sym_name_base
2455 + symdef_base[i].symbol_name_string_index);
2456
2457 /* If we find a symbol that appears to be needed, think carefully
2458 about the archive member that the symbol is in. */
2459
2460 if (sp && ((sp->referenced && !sp->defined)
2461 || (sp->defined && sp->max_common_size))
2462 )
2463 {
2464 int junk;
2465 register int j;
2466 register int offset = symdef_base[i].library_member_offset;
2467 struct file_entry *subentry;
2468
2469 /* Don't think carefully about any archive member
2470 more than once in a given pass. */
2471
2472 if (prev_offset == offset)
2473 continue;
2474 prev_offset = offset;
2475
2476 /* Read the symbol table of the archive member. */
2477
2478 subentry = decode_library_subfile (desc, entry, offset, &junk);
2479 if (subentry == 0)
2480 fatal ("invalid offset for %s in symbol table of %s",
2481 sym_name_base
2482 + symdef_base[i].symbol_name_string_index,
2483 entry->filename);
2484 read_entry_symbols (desc, subentry);
2485 subentry->strings = xmalloc (subentry->strs_size);
2486 read_entry_strings (desc, subentry);
2487
2488 /* Now scan the symbol table and decide whether to load. */
2489
2490 if (!subfile_wanted_p (subentry))
2491 {
2492 free (subentry->symbols);
2493 free (subentry->strings);
2494 free (subentry);
2495 }
2496 else
2497 {
2498 /* This member is needed; load it.
2499 Since we are loading something on this pass,
2500 we must make another pass through the symdef data. */
2501
2502 not_finished = 1;
2503
2504 enter_file_symbols (subentry);
2505
2506 if (prev)
2507 prev->chain = subentry;
2508 else entry->subfiles = subentry;
2509 prev = subentry;
2510
2511 /* Clear out this member's symbols from the symdef data
2512 so that following passes won't waste time on them. */
2513
2514 for (j = 0; j < number_of_symdefs; j++)
2515 {
2516 if (symdef_base[j].library_member_offset == offset)
2517 symdef_base[j].symbol_name_string_index = -1;
2518 }
2519
2520 /* We'll read the strings again if we need them again. */
2521 free (subentry->strings);
2522 subentry->strings = 0;
2523 }
2524 }
2525 }
2526 }
2527
2528 free (symdef_data);
2529}
2530
2531
2532
2533/* Handle a subentry for a file with no __.SYMDEF. */
2534
2535void
2536process_subentry (desc, subentry, entry, prev_addr)
2537 int desc;
2538 register struct file_entry *subentry;
2539 struct file_entry **prev_addr, *entry;
2540{
2541 read_entry_symbols (desc, subentry);
2542 subentry->strings = (char *) ALLOCA (subentry->strs_size);
2543 read_entry_strings (desc, subentry);
2544
2545 if (!subfile_wanted_p (subentry))
2546 {
2547 FREEA (subentry->strings);
2548 free (subentry->symbols);
2549 free (subentry);
2550 }
2551 else
2552 {
2553 enter_file_symbols (subentry);
2554
2555 if (*prev_addr)
2556 (*prev_addr)->chain = subentry;
2557 else
2558 entry->subfiles = subentry;
2559 *prev_addr = subentry;
2560 FREEA (subentry->strings);
2561 }
2562}
2563
2564/* Search a library that has no __.SYMDEF.
2565 ENTRY is the library's file_entry.
2566 DESC is the descriptor it is open on. */
2567
2568void
2569linear_library (desc, entry)
2570 int desc;
2571 struct file_entry *entry;
2572{
2573 struct file_entry *prev = 0;
2574 register int this_subfile_offset = SARMAG;
2575
2576 while (undefined_global_sym_count || common_defined_global_count)
2577 {
2578 int member_length;
2579 register struct file_entry *subentry;
2580
2581 subentry = decode_library_subfile (desc, entry, this_subfile_offset,
2582 &member_length);
2583 if (!subentry) return;
2584
2585 process_subentry (desc, subentry, entry, &prev);
2586 this_subfile_offset += member_length + sizeof (struct ar_hdr);
2587 if (this_subfile_offset & 1) this_subfile_offset++;
2588 }
2589}
2590
2591
2592/* ENTRY is an entry for a library member.
2593 Its symbols have been read into core, but not entered.
2594 Return nonzero if we ought to load this member. */
2595
2596int
2597subfile_wanted_p (entry)
2598 struct file_entry *entry;
2599{
2600 register struct nlist *p;
2601 register struct nlist *end
2602 = entry->symbols + entry->syms_size / sizeof (struct nlist);
2603
2604 for (p = entry->symbols; p < end; p++)
2605 {
2606 register int type = p->n_type;
2607 register char *name = p->n_un.n_strx + entry->strings;
2608
2609 /* If the symbol has an interesting definition, we could
2610 potentially want it. */
2611 if (((type & N_EXT) || WEAK_SYMBOL (type))
2612 && (type != (N_UNDF | N_EXT) || p->n_value)
2613 && (type != (N_WEAKU | N_EXT) || p->n_value)
2614 && !SET_ELEMENT_P (type)
2615 && !set_element_prefixed_p (name))
2616 {
2617 register symbol *sp = getsym_soft (name);
2618
2619 /* If this symbol has not been hashed, we can't be looking for it. */
2620
2621 if (!sp) continue;
2622
2623 if ((sp->referenced && !sp->defined)
2624 /* NB. This needs to be changed so that, e.g., "int pipe;" won't import
2625 pipe() from the library. But the bug fix kingdon made was wrong. */
2626 || (sp->defined && sp->max_common_size
2627 && type != (N_INDR | N_EXT)))
2628 {
2629 /* This is a symbol we are looking for. It is either
2630 not yet defined or defined as a common. */
2631 if (type == (N_UNDF | N_EXT))
2632 {
2633 /* Symbol being defined as common.
2634 Remember this, but don't load subfile just for this. */
2635
2636 /* If it didn't used to be common, up the count of
2637 common symbols. */
2638 if (!sp->max_common_size)
2639 common_defined_global_count++;
2640
2641 if (sp->max_common_size < p->n_value)
2642 sp->max_common_size = p->n_value;
2643 if (!sp->defined)
2644 undefined_global_sym_count--;
2645 sp->defined = 1;
2646 continue;
2647 }
2648
2649 if (write_map)
2650 {
2651 print_file_name (entry, stdout);
2652 fprintf (stdout, " needed due to %s\n", sp->name);
2653 }
2654 return 1;
2655 }
2656 }
2657 }
2658
2659 return 0;
2660}
2661
2662
2663void consider_file_section_lengths (), relocate_file_addresses ();
2664
2665/* Having entered all the global symbols and found the sizes of sections
2666 of all files to be linked, make all appropriate deductions from this data.
2667
2668 We propagate global symbol values from definitions to references.
2669 We compute the layout of the output file and where each input file's
2670 contents fit into it. */
2671
2672void
2673digest_symbols (void)
2674{
2675 register int i;
2676 int setv_fill_count = 0;
2677
2678 if (trace_files)
2679 fprintf (stderr, "Digesting symbol information:\n\n");
2680
2681 /* Initialize the text_start address; this depends on the output file formats. */
2682
2683 initialize_text_start ();
2684
2685 text_size = text_header_size;
2686
2687 /* Compute total size of sections */
2688
2689 each_file (consider_file_section_lengths, 0);
2690
2691 /* If necessary, pad text section to full page in the file.
2692 Include the padding in the text segment size. */
2693
2694 if (output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
2695 {
2696 text_pad = ((text_size + page_size - 1) & (- page_size)) - text_size;
2697 text_size += text_pad;
2698 }
2699
2700 /* Now that the text_size is known, initialize the data start address;
2701 this depends on text_size as well as the output file format. */
2702
2703 initialize_data_start ();
2704
2705 /* Make sure the set vectors are aligned properly. */
2706 {
2707 int new_data_size = ((data_size + sizeof(unsigned long) - 1)
2708 & ~(sizeof(unsigned long)-1));
2709
2710 set_sect_pad += new_data_size - data_size;
2711 data_size = new_data_size;
2712 }
2713
2714 /* Set up the set element vector */
2715
2716 if (output_style != OUTPUT_RELOCATABLE)
2717 {
2718 /* The set sector size is the number of set elements + a word
2719 for each symbol for the length word at the beginning of the
2720 vector, plus a word for each symbol for a zero at the end of
2721 the vector (for incremental linking). */
2722 set_sect_size
2723 = (set_symbol_count + 2 * set_vector_count) * sizeof (unsigned long);
2724 set_sect_start = data_start + data_size;
2725 data_size += set_sect_size;
2726 set_vectors = (unsigned long *) xmalloc (set_sect_size);
2727 set_reloc = (int *) xmalloc (set_sect_size / sizeof (unsigned long)
2728 * sizeof (int));
2729 setv_fill_count = 0;
2730 }
2731
2732 /* Make sure bss starts out aligned as much as anyone can want. */
2733 {
2734 int new_data_size = (data_size + SECTION_ALIGN_MASK) & ~SECTION_ALIGN_MASK;
2735
2736 data_pad += new_data_size - data_size;
2737 data_size = new_data_size;
2738 }
2739
2740 /* Compute start addresses of each file's sections and symbols. */
2741
2742 each_full_file (relocate_file_addresses, 0);
2743
2744 /* Now, for each symbol, verify that it is defined globally at most once.
2745 Put the global value into the symbol entry.
2746 Common symbols are allocated here, in the BSS section.
2747 Each defined symbol is given a '->defined' field
2748 which is the correct N_ code for its definition,
2749 except in the case of common symbols with -r.
2750 Then make all the references point at the symbol entry
2751 instead of being chained together. */
2752
2753 defined_global_sym_count = 0;
2754
2755 for (i = 0; i < TABSIZE; i++)
2756 {
2757 register symbol *sp;
2758 for (sp = symtab[i]; sp; sp = sp->link)
2759 {
2760 /* For each symbol */
2761 register struct nlist *p, *next;
2762 int defs = 0, com = sp->max_common_size;
2763 struct nlist *first_definition;
2764 for (p = sp->refs; p; p = next)
2765 {
2766 register int type = p->n_type;
2767
2768 if (SET_ELEMENT_P (type))
2769 {
2770 if (output_style == OUTPUT_RELOCATABLE)
2771 fatal ("internal: global ref to set element with -r");
2772 if (!defs++)
2773 {
2774 sp->value = set_sect_start
2775 + setv_fill_count++ * sizeof (unsigned long);
2776 sp->defined = N_SETV | N_EXT;
2777 first_definition = p;
2778 }
2779 else if ((sp->defined & ~N_EXT) != N_SETV)
2780 {
2781 sp->multiply_defined = 1;
2782 multiple_def_count++;
2783 }
2784 set_reloc[setv_fill_count] = TYPE_OF_SET_ELEMENT (type);
2785 if ((type & ~N_EXT) != N_SETA)
2786 data_reloc_size += sizeof (struct relocation_info);
2787 set_vectors[setv_fill_count++] = p->n_value;
2788 }
2789 else if ((type & N_EXT) && type != (N_UNDF | N_EXT)
2790 && type != (N_IMP1 | N_EXT))
2791 {
2792 /* non-common definition */
2793 if (defs++ && sp->value != p->n_value)
2794 {
2795 sp->multiply_defined = 1;
2796 multiple_def_count++;
2797 }
2798 sp->value = p->n_value;
2799 sp->defined = type;
2800 first_definition = p;
2801 }
2802 next = (struct nlist *) p->n_un.n_name;
2803 p->n_un.n_name = (char *) sp;
2804 }
2805 /* Allocate as common if defined as common and not defined for real */
2806 if (com && !defs)
2807 {
2808 if (output_style != OUTPUT_RELOCATABLE || force_common_definition)
2809 {
2810 int align = sizeof (int);
2811
2812 /* Round up to nearest sizeof (int). I don't know
2813 whether this is necessary or not (given that
2814 alignment is taken care of later), but it's
2815 traditional, so I'll leave it in. Note that if
2816 this size alignment is ever removed, ALIGN above
2817 will have to be initialized to 1 instead of
2818 sizeof (int). */
2819
2820 com = (com + sizeof (int) - 1) & (- sizeof (int));
2821
2822 while (!(com & align))
2823 align <<= 1;
2824
2825 align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
2826
2827 bss_size = ((((bss_size + data_size + data_start)
2828 + (align - 1)) & (- align))
2829 - data_size - data_start);
2830
2831 sp->value = data_start + data_size + bss_size;
2832 sp->defined = N_BSS | N_EXT;
2833 bss_size += com;
2834 if (write_map)
2835 printf ("Allocating common %s: %x at %lx\n",
2836 sp->name, com, sp->value);
2837 }
2838 else
2839 {
2840 sp->defined = 0;
2841 undefined_global_sym_count++;
2842 }
2843 }
2844 /* Set length word at front of vector and zero byte at end.
2845 Reverse the vector itself to put it in file order. */
2846 if ((sp->defined & ~N_EXT) == N_SETV)
2847 {
2848 unsigned long length_word_index
2849 = (sp->value - set_sect_start) / sizeof (unsigned long);
2850 unsigned long i, tmp;
2851
2852 set_reloc[length_word_index] = N_ABS;
2853 set_vectors[length_word_index]
2854 = setv_fill_count - 1 - length_word_index;
2855
2856 /* Reverse the vector. */
2857 for (i = 1;
2858 i < (setv_fill_count - length_word_index - 1) / 2 + 1;
2859 i++)
2860 {
2861 tmp = set_reloc[length_word_index + i];
2862 set_reloc[length_word_index + i]
2863 = set_reloc[setv_fill_count - i];
2864 set_reloc[setv_fill_count - i] = (int)tmp;
2865
2866 tmp = set_vectors[length_word_index + i];
2867 set_vectors[length_word_index + i]
2868 = set_vectors[setv_fill_count - i];
2869 set_vectors[setv_fill_count - i] = tmp;
2870 }
2871
2872 set_reloc[setv_fill_count] = N_ABS;
2873 set_vectors[setv_fill_count++] = 0;
2874 }
2875 if (!sp->defined && WEAK_SYMBOL (sp->weak))
2876 {
2877 sp->defined = N_ABS;
2878 sp->value = 0;
2879 undefined_global_sym_count--;
2880 }
2881 if (sp->defined)
2882 defined_global_sym_count++;
2883 }
2884 }
2885
2886 /* Make sure end of bss is aligned as much as anyone can want. */
2887
2888 bss_size = (bss_size + SECTION_ALIGN_MASK) & ~SECTION_ALIGN_MASK;
2889
2890 /* Give values to _end and friends. */
2891 {
2892 int end_value = data_start + data_size + bss_size;
2893 if (end_symbol)
2894 end_symbol->value = end_value;
2895 if (end_symbol_alt)
2896 end_symbol_alt->value = end_value;
2897 }
2898
2899 {
2900 int etext_value = text_size + text_start;
2901 if (etext_symbol)
2902 etext_symbol->value = etext_value;
2903 if (etext_symbol_alt)
2904 etext_symbol_alt->value = etext_value;
2905 }
2906
2907 {
2908 int edata_value = data_start + data_size;
2909 if (edata_symbol)
2910 edata_symbol->value = edata_value;
2911 if (edata_symbol_alt)
2912 edata_symbol_alt->value = edata_value;
2913 }
2914
2915 /* Figure the data_pad now, so that it overlaps with the bss addresses. */
2916
2917 {
2918 /* The amount of data_pad that we are computing now. This is the
2919 part which overlaps with bss. What was computed previously
2920 goes before bss. */
2921 int data_pad_additional = 0;
2922
2923 if (specified_data_size && specified_data_size > data_size)
2924 data_pad_additional = specified_data_size - data_size;
2925
2926 if (output_style == OUTPUT_DEMAND_PAGED)
2927 data_pad_additional =
2928 ((data_pad_additional + data_size + page_size - 1) & (- page_size)) - data_size;
2929
2930 bss_size -= data_pad_additional;
2931 if (bss_size < 0) bss_size = 0;
2932
2933 data_size += data_pad_additional;
2934
2935 data_pad += data_pad_additional;
2936 }
2937}
2938
2939
2940/* Accumulate the section sizes of input file ENTRY
2941 into the section sizes of the output file. */
2942
2943void
2944consider_file_section_lengths (entry)
2945 register struct file_entry *entry;
2946{
2947 if (entry->just_syms_flag)
2948 return;
2949
2950 entry->text_start_address = text_size;
2951 /* If there were any vectors, we need to chop them off */
2952 text_size += entry->text_size;
2953 entry->data_start_address = data_size;
2954 data_size += (entry->data_size + SECTION_ALIGN_MASK) & ~SECTION_ALIGN_MASK;
2955 entry->bss_start_address = bss_size;
2956 bss_size += (entry->bss_size + SECTION_ALIGN_MASK) & ~SECTION_ALIGN_MASK;
2957
2958 text_reloc_size += entry->text_reloc_size;
2959 data_reloc_size += entry->data_reloc_size;
2960}
2961
2962/* Determine where the sections of ENTRY go into the output file,
2963 whose total section sizes are already known.
2964 Also relocate the addresses of the file's local and debugger symbols. */
2965
2966void
2967relocate_file_addresses (entry)
2968 register struct file_entry *entry;
2969{
2970 entry->text_start_address += text_start;
2971
2972 /* Note that `data_start' and `data_size' have not yet been adjusted
2973 for the portion of data_pad which overlaps with bss. If they had
2974 been, we would get the wrong results here. */
2975 entry->data_start_address += data_start;
2976 entry->bss_start_address += data_start + data_size;
2977
2978 {
2979 register struct nlist *p;
2980 register struct nlist *end
2981 = entry->symbols + entry->syms_size / sizeof (struct nlist);
2982
2983 for (p = entry->symbols; p < end; p++)
2984 {
2985 /* If this belongs to a section, update it by the section's start address */
2986 register int type = p->n_type & N_TYPE;
2987
2988 switch (type)
2989 {
2990 case N_TEXT:
2991 case N_SETT:
2992 p->n_value += entry->text_start_address - entry->orig_text_address;
2993 break;
2994 case N_DATA:
2995 case N_SETV:
2996 case N_SETD:
2997 /* Data segment symbol. Subtract the address of the
2998 data segment in the input file, and add the address
2999 of this input file's data segment in the output file. */
3000 p->n_value +=
3001 entry->data_start_address - entry->orig_data_address;
3002 break;
3003 case N_BSS:
3004 case N_SETB:
3005 /* likewise for symbols with value in BSS. */
3006 p->n_value += entry->bss_start_address - entry->orig_bss_address;
3007 break;
3008 }
3009 }
3010 }
3011}
3012
3013
3014void describe_file_sections (), list_file_locals ();
3015
3016/* Print a complete or partial map of the output file. */
3017
3018void
3019print_symbols (outfile)
3020 FILE *outfile;
3021{
3022 register int i;
3023
3024 fprintf (outfile, "\nFiles:\n\n");
3025
3026 each_file (describe_file_sections, (int)outfile);
3027
3028 fprintf (outfile, "\nGlobal symbols:\n\n");
3029
3030 for (i = 0; i < TABSIZE; i++)
3031 {
3032 register symbol *sp;
3033 for (sp = symtab[i]; sp; sp = sp->link)
3034 {
3035 if (sp->defined == 1)
3036 fprintf (outfile, " %s: common, length 0x%x\n", sp->name, sp->max_common_size);
3037 if (sp->defined)
3038 fprintf (outfile, " %s: 0x%lx\n", sp->name, sp->value);
3039 else if (sp->referenced)
3040 fprintf (outfile, " %s: undefined\n", sp->name);
3041 }
3042 }
3043
3044 each_file (list_file_locals, (int)outfile);
3045}
3046
3047void
3048describe_file_sections (entry, outfile)
3049 struct file_entry *entry;
3050 FILE *outfile;
3051{
3052 fprintf (outfile, " ");
3053 print_file_name (entry, outfile);
3054 if (entry->just_syms_flag)
3055 fprintf (outfile, " symbols only\n");
3056 else
3057 fprintf (outfile, " text %x(%lx), data %x(%lx), bss %x(%lx) hex\n",
3058 entry->text_start_address, entry->text_size,
3059 entry->data_start_address, entry->data_size,
3060 entry->bss_start_address, entry->bss_size);
3061}
3062
3063void
3064list_file_locals (entry, outfile)
3065 struct file_entry *entry;
3066 FILE *outfile;
3067{
3068 register struct nlist
3069 *p,
3070 *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
3071
3072 entry->strings = (char *) ALLOCA (entry->strs_size);
3073 read_entry_strings (file_open (entry), entry);
3074
3075 fprintf (outfile, "\nLocal symbols of ");
3076 print_file_name (entry, outfile);
3077 fprintf (outfile, ":\n\n");
3078
3079 for (p = entry->symbols; p < end; p++)
3080 /* If this is a definition,
3081 update it if necessary by this file's start address. */
3082 if (((output_style == OUTPUT_RELOCATABLE) && SET_ELEMENT_P (p->n_type))
3083 || (!(p->n_type & (N_STAB | N_EXT)) && !SET_ELEMENT_P (p->n_type)))
3084 fprintf (outfile, " %s: 0x%lx\n",
3085 entry->strings + p->n_un.n_strx, p->n_value);
3086 else if (SET_ELEMENT_P (p->n_type))
3087 fprintf (outfile, " [set element] %s: 0x%lx\n",
3088 ((symbol *)p->n_un.n_name)->name, p->n_value);
3089
3090 FREEA (entry->strings);
3091}
3092
3093
3094
3095/* Static vars for do_warnings and subroutines of it */
3096int list_unresolved_refs; /* List unresolved refs */
3097int list_warning_symbols; /* List warning syms */
3098int list_multiple_defs; /* List multiple definitions */
3099
3100/*
3101 * Structure for communication between do_file_warnings and it's
3102 * helper routines. Will in practice be an array of three of these:
3103 * 0) Current line, 1) Next line, 2) Source file info.
3104 */
3105struct line_debug_entry
3106{
3107 int line;
3108 char *filename;
3109 struct nlist *sym;
3110};
3111
3112int next_debug_entry (int use_data_symbols, struct line_debug_entry state_pointer[3]);
3113struct line_debug_entry * init_debug_scan (int use_data_symbols, struct file_entry *entry);
3114int address_to_line (unsigned long address, struct line_debug_entry state_pointer[3]);
3115void qsort ();
3116/*
3117 * Helper routines for do_file_warnings.
3118 */
3119
3120/* Return an integer less than, equal to, or greater than 0 as per the
3121 relation between the two relocation entries. Used by qsort. */
3122
3123int
3124relocation_entries_relation (rel1, rel2)
3125 struct relocation_info *rel1, *rel2;
3126{
3127 return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
3128}
3129
3130/* Moves to the next debugging symbol in the file. USE_DATA_SYMBOLS
3131 determines the type of the debugging symbol to look for (DSLINE or
3132 SLINE). STATE_POINTER keeps track of the old and new locatiosn in
3133 the file. It assumes that state_pointer[1] is valid; ie
3134 that it.sym points into some entry in the symbol table. If
3135 state_pointer[1].sym == 0, this routine should not be called. */
3136
3137int
3138next_debug_entry (use_data_symbols, state_pointer)
3139 register int use_data_symbols;
3140 /* Next must be passed by reference! */
3141 struct line_debug_entry state_pointer[3];
3142{
3143 register struct line_debug_entry
3144 *current = state_pointer,
3145 *next = state_pointer + 1,
3146 /* Used to store source file */
3147 *source = state_pointer + 2;
3148 struct file_entry *entry = (struct file_entry *) source->sym;
3149
3150 current->sym = next->sym;
3151 current->line = next->line;
3152 current->filename = next->filename;
3153
3154 while (++(next->sym) < (entry->symbols
3155 + entry->syms_size/sizeof (struct nlist)))
3156 {
3157 /* n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, so
3158 * may look negative...therefore, must mask to low bits
3159 */
3160 switch (next->sym->n_type & 0xff)
3161 {
3162 case N_SLINE:
3163 if (use_data_symbols) continue;
3164 next->line = next->sym->n_desc;
3165 return 1;
3166 case N_DSLINE:
3167 if (!use_data_symbols) continue;
3168 next->line = next->sym->n_desc;
3169 return 1;
3170#ifdef HAVE_SUN_STABS
3171 case N_EINCL:
3172 next->filename = source->filename;
3173 continue;
3174#endif
3175 case N_SO:
3176 source->filename = next->sym->n_un.n_strx + entry->strings;
3177 source->line++;
3178#ifdef HAVE_SUN_STABS
3179 case N_BINCL:
3180#endif
3181 case N_SOL:
3182 next->filename
3183 = next->sym->n_un.n_strx + entry->strings;
3184 default:
3185 continue;
3186 }
3187 }
3188 next->sym = (struct nlist *) 0;
3189 return 0;
3190}
3191
3192/* Create a structure to save the state of a scan through the debug
3193 symbols. USE_DATA_SYMBOLS is set if we should be scanning for
3194 DSLINE's instead of SLINE's. entry is the file entry which points
3195 at the symbols to use. */
3196
3197struct line_debug_entry *
3198init_debug_scan (use_data_symbols, entry)
3199 int use_data_symbols;
3200 struct file_entry *entry;
3201{
3202 struct line_debug_entry
3203 *state_pointer
3204 = (struct line_debug_entry *)
3205 xmalloc (3 * sizeof (struct line_debug_entry));
3206 register struct line_debug_entry
3207 *current = state_pointer,
3208 *next = state_pointer + 1,
3209 *source = state_pointer + 2; /* Used to store source file */
3210
3211 struct nlist *tmp;
3212
3213 for (tmp = entry->symbols;
3214 tmp < (entry->symbols
3215 + entry->syms_size/sizeof (struct nlist));
3216 tmp++)
3217 if (tmp->n_type == (int) N_SO)
3218 break;
3219
3220 if (tmp >= (entry->symbols
3221 + entry->syms_size/sizeof (struct nlist)))
3222 {
3223 /* I believe this translates to "We lose" */
3224 current->filename = next->filename = entry->filename;
3225 current->line = next->line = -1;
3226 current->sym = next->sym = (struct nlist *) 0;
3227 return state_pointer;
3228 }
3229
3230 next->line = source->line = 0;
3231 next->filename = source->filename
3232 = (tmp->n_un.n_strx + entry->strings);
3233 source->sym = (struct nlist *) entry;
3234 next->sym = tmp;
3235
3236 next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
3237
3238 if (!next->sym) /* No line numbers for this section; */
3239 /* setup output results as appropriate */
3240 {
3241 if (source->line)
3242 {
3243 current->filename = source->filename = entry->filename;
3244 current->line = -1; /* Don't print lineno */
3245 }
3246 else
3247 {
3248 current->filename = source->filename;
3249 current->line = 0;
3250 }
3251 return state_pointer;
3252 }
3253
3254
3255 next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
3256
3257 return state_pointer;
3258}
3259
3260/* Takes an ADDRESS (in either text or data space) and a STATE_POINTER
3261 which describes the current location in the implied scan through
3262 the debug symbols within the file which ADDRESS is within, and
3263 returns the source line number which corresponds to ADDRESS. */
3264
3265int
3266address_to_line (address, state_pointer)
3267 unsigned long address;
3268 /* Next must be passed by reference! */
3269 struct line_debug_entry state_pointer[3];
3270{
3271 struct line_debug_entry
3272 *current = state_pointer,
3273 *next = state_pointer + 1;
3274 struct line_debug_entry *tmp_pointer;
3275
3276 int use_data_symbols;
3277
3278 if (next->sym)
3279 use_data_symbols = (next->sym->n_type & ~N_EXT) == N_DATA;
3280 else
3281 return current->line;
3282
3283 /* Go back to the beginning if we've already passed it. */
3284 if (current->sym->n_value > address)
3285 {
3286 tmp_pointer = init_debug_scan (use_data_symbols,
3287 (struct file_entry *)
3288 ((state_pointer + 2)->sym));
3289 state_pointer[0] = tmp_pointer[0];
3290 state_pointer[1] = tmp_pointer[1];
3291 state_pointer[2] = tmp_pointer[2];
3292 free (tmp_pointer);
3293 }
3294
3295 /* If we're still in a bad way, return -1, meaning invalid line. */
3296 if (current->sym->n_value > address)
3297 return -1;
3298
3299 while (next->sym
3300 && next->sym->n_value <= address
3301 && next_debug_entry (use_data_symbols, state_pointer))
3302 ;
3303 return current->line;
3304}
3305
3306
3307/* Macros for manipulating bitvectors. */
3308#define BIT_SET_P(bv, index) ((bv)[(index) >> 3] & 1 << ((index) & 0x7))
3309#define SET_BIT(bv, index) ((bv)[(index) >> 3] |= 1 << ((index) & 0x7))
3310
3311/* This routine will scan through the relocation data of file ENTRY,
3312 printing out references to undefined symbols and references to
3313 symbols defined in files with N_WARNING symbols. If DATA_SEGMENT
3314 is non-zero, it will scan the data relocation segment (and use
3315 N_DSLINE symbols to track line number); otherwise it will scan the
3316 text relocation segment. Warnings will be printed on the output
3317 stream OUTFILE. Eventually, every nlist symbol mapped through will
3318 be marked in the NLIST_BITVECTOR, so we don't repeat ourselves when
3319 we scan the nlists themselves. */
3320
3321void
3322do_relocation_warnings (entry, data_segment, outfile, nlist_bitvector)
3323 struct file_entry *entry;
3324 int data_segment;
3325 FILE *outfile;
3326 unsigned char *nlist_bitvector;
3327{
3328 struct relocation_info
3329 *reloc_start = data_segment ? entry->datarel : entry->textrel,
3330 *reloc;
3331 int reloc_size
3332 = ((data_segment ? entry->data_reloc_size : entry->text_reloc_size)
3333 / sizeof (struct relocation_info));
3334 int start_of_segment
3335 = (data_segment ? entry->data_start_address : entry->text_start_address);
3336 struct nlist *start_of_syms = entry->symbols;
3337 struct line_debug_entry *state_pointer
3338 = init_debug_scan (data_segment != 0, entry);
3339 register struct line_debug_entry *current = state_pointer;
3340 /* Assigned to generally static values; should not be written into. */
3341 char *errfmt;
3342 /* Assigned to alloca'd values cand copied into; should be freed
3343 when done. */
3344 char *errmsg;
3345 int invalidate_line_number;
3346
3347 /* We need to sort the relocation info here. Sheesh, so much effort
3348 for one lousy error optimization. */
3349
3350 qsort (reloc_start, reloc_size, sizeof (struct relocation_info),
3351 (int (*)(const void *, const void *))relocation_entries_relation);
3352
3353 for (reloc = reloc_start;
3354 reloc < (reloc_start + reloc_size);
3355 reloc++)
3356 {
3357 register struct nlist *s;
3358 register symbol *g;
3359
3360 /* If the relocation isn't resolved through a symbol, continue */
3361 if (!RELOC_EXTERN_P(reloc))
3362 continue;
3363
3364 s = &(entry->symbols[RELOC_SYMBOL(reloc)]);
3365
3366 /* Local symbols shouldn't ever be used by relocation info, so
3367 the next should be safe.
3368 This is, of course, wrong. References to local BSS symbols can be
3369 the targets of relocation info, and they can (must) be
3370 resolved through symbols. However, these must be defined properly,
3371 (the assembler would have caught it otherwise), so we can
3372 ignore these cases. */
3373 if (!(s->n_type & N_EXT))
3374 continue;
3375
3376 g = (symbol *) s->n_un.n_name;
3377 errmsg = 0;
3378
3379 if (!g->defined && list_unresolved_refs) /* Reference */
3380 {
3381 /* Mark as being noted by relocation warning pass. */
3382 SET_BIT (nlist_bitvector, s - start_of_syms);
3383
3384 if (g->undef_refs >= MAX_UREFS_PRINTED) /* Listed too many */
3385 continue;
3386
3387 /* Undefined symbol which we should mention */
3388
3389 if (++(g->undef_refs) == MAX_UREFS_PRINTED)
3390 {
3391 errfmt = "More undefined symbol %s refs follow";
3392 invalidate_line_number = 1;
3393 }
3394 else
3395 {
3396 errfmt = "Undefined symbol %s referenced from %s segment";
3397 invalidate_line_number = 0;
3398 }
3399 }
3400 else /* Defined */
3401 {
3402 /* Potential symbol warning here */
3403 if (!g->warning) continue;
3404
3405 /* Mark as being noted by relocation warning pass. */
3406 SET_BIT (nlist_bitvector, s - start_of_syms);
3407
3408 errfmt = 0;
3409 errmsg = g->warning;
3410 invalidate_line_number = 0;
3411 }
3412
3413
3414 /* If errfmt == 0, errmsg has already been defined. */
3415 if (errfmt != 0)
3416 {
3417 char *nm;
3418
3419 if (!demangler || !(nm = (*demangler)(g->name)))
3420 nm = g->name;
3421 errmsg = xmalloc (strlen (errfmt) + strlen (nm) + 1);
3422 sprintf (errmsg, errfmt, nm, data_segment ? "data" : "text");
3423 if (nm != g->name)
3424 free (nm);
3425 }
3426
3427 address_to_line (RELOC_ADDRESS (reloc) + start_of_segment,
3428 state_pointer);
3429
3430 if (current->line >=0)
3431 {
3432 fprintf (outfile, "%s:%d (", current->filename,
3433 invalidate_line_number ? 0 : current->line);
3434 print_file_name (entry, outfile);
3435 fprintf (outfile, "): %s\n", errmsg);
3436 }
3437 else
3438 {
3439 print_file_name(entry, outfile);
3440 fprintf(outfile, ": %s\n", errmsg);
3441 }
3442
3443 if (errfmt != 0)
3444 free (errmsg);
3445 }
3446
3447 free (state_pointer);
3448}
3449
3450/* Print on OUTFILE a list of all warnings generated by references
3451 and/or definitions in the file ENTRY. List source file and line
3452 number if possible, just the .o file if not. */
3453
3454void
3455do_file_warnings (entry, outfile)
3456 struct file_entry *entry;
3457 FILE *outfile;
3458{
3459 int number_of_syms = entry->syms_size / sizeof (struct nlist);
3460 unsigned char *nlist_bitvector
3461 = (unsigned char *) ALLOCA ((number_of_syms >> 3) + 1);
3462 struct line_debug_entry *text_scan, *data_scan;
3463 int i;
3464 char *errfmt, *file_name = NULL;
3465 int line_number = 0;
3466 int dont_allow_symbol_name;
3467
3468 bzero (nlist_bitvector, (number_of_syms >> 3) + 1);
3469
3470 /* Read in the files strings if they aren't available */
3471 if (!entry->strings)
3472 {
3473 int desc;
3474
3475 entry->strings = (char *) ALLOCA (entry->strs_size);
3476 desc = file_open (entry);
3477 read_entry_strings (desc, entry);
3478 }
3479
3480 read_file_relocation (entry);
3481
3482 /* Do text warnings based on a scan through the relocation info. */
3483 do_relocation_warnings (entry, 0, outfile, nlist_bitvector);
3484
3485 /* Do data warnings based on a scan through the relocation info. */
3486 do_relocation_warnings (entry, 1, outfile, nlist_bitvector);
3487
3488 /* Scan through all of the nlist entries in this file and pick up
3489 anything that the scan through the relocation stuff didn't. */
3490
3491 text_scan = init_debug_scan (0, entry);
3492 data_scan = init_debug_scan (1, entry);
3493
3494 for (i = 0; i < number_of_syms; i++)
3495 {
3496 struct nlist *s;
3497 struct glosym *g;
3498
3499 s = entry->symbols + i;
3500
3501 if (WEAK_SYMBOL (s->n_type) || !(s->n_type & N_EXT))
3502 continue;
3503
3504 g = (symbol *) s->n_un.n_name;
3505 dont_allow_symbol_name = 0;
3506
3507 if (list_multiple_defs && g->multiply_defined)
3508 {
3509 errfmt = "Definition of symbol %s (multiply defined)";
3510 switch (s->n_type)
3511 {
3512 case N_TEXT | N_EXT:
3513 line_number = address_to_line (s->n_value, text_scan);
3514 file_name = text_scan[0].filename;
3515 break;
3516 case N_BSS | N_EXT:
3517 case N_DATA | N_EXT:
3518 line_number = address_to_line (s->n_value, data_scan);
3519 file_name = data_scan[0].filename;
3520 break;
3521 case N_SETA | N_EXT:
3522 case N_SETT | N_EXT:
3523 case N_SETD | N_EXT:
3524 case N_SETB | N_EXT:
3525 if (g->multiply_defined == 2)
3526 continue;
3527 errfmt = "First set element definition of symbol %s (multiply defined)";
3528 break;
3529 default:
3530 continue; /* Don't print out multiple defs
3531 at references. */
3532 }
3533 }
3534 else if (BIT_SET_P (nlist_bitvector, i))
3535 continue;
3536 else if (list_unresolved_refs && !g->defined)
3537 {
3538 if (g->undef_refs >= MAX_UREFS_PRINTED)
3539 continue;
3540
3541 if (++(g->undef_refs) == MAX_UREFS_PRINTED)
3542 errfmt = "More undefined \"%s\" refs follow";
3543 else
3544 errfmt = "Undefined symbol \"%s\" referenced";
3545 line_number = -1;
3546 }
3547 else if (g->warning)
3548 {
3549 /* There are two cases in which we don't want to
3550 do this. The first is if this is a definition instead of
3551 a reference. The second is if it's the reference used by
3552 the warning stabs itself. */
3553 if (s->n_type != (N_EXT | N_UNDF)
3554 || (i && (s-1)->n_type == N_WARNING))
3555 continue;
3556
3557 errfmt = g->warning;
3558 line_number = -1;
3559 dont_allow_symbol_name = 1;
3560 }
3561 else
3562 continue;
3563
3564 if (line_number == -1)
3565 {
3566 print_file_name (entry, outfile);
3567 fprintf (outfile, ": ");
3568 }
3569 else
3570 {
3571 fprintf (outfile, "%s:%d (", file_name, line_number);
3572 print_file_name (entry, outfile);
3573 fprintf (outfile, "): ");
3574 }
3575
3576 if (dont_allow_symbol_name)
3577 fprintf (outfile, "%s", errfmt);
3578 else
3579 {
3580 char *nm;
3581
3582 if (!demangler || !(nm = (*demangler)(g->name)))
3583 fprintf (outfile, errfmt, g->name);
3584 else
3585 {
3586 fprintf (outfile, errfmt, nm);
3587 free (nm);
3588 }
3589 }
3590
3591 fputc ('\n', outfile);
3592 }
3593 free (text_scan);
3594 free (data_scan);
3595 FREEA (entry->strings);
3596 FREEA (nlist_bitvector);
3597}
3598
3599
3600void
3601do_warnings (outfile)
3602 FILE *outfile;
3603{
3604 list_unresolved_refs = output_style != OUTPUT_RELOCATABLE && undefined_global_sym_count;
3605 list_warning_symbols = warning_count;
3606 list_multiple_defs = multiple_def_count != 0;
3607
3608 if (!(list_unresolved_refs ||
3609 list_warning_symbols ||
3610 list_multiple_defs ))
3611 /* No need to run this routine */
3612 return;
3613
3614 each_file (do_file_warnings, (int)outfile);
3615
3616 if (list_unresolved_refs || list_multiple_defs)
3617 make_executable = 0;
3618}
3619
3620
3621#ifdef A_OUT
3622
3623/* Stuff pertaining to creating a.out files. */
3624
3625/* The a.out header. */
3626
3627struct exec outheader;
3628
3629/* Compute text_start and text_header_size for an a.out file. */
3630
3631void
3632initialize_a_out_text_start (void)
3633{
3634 int magic = 0;
3635
3636 switch (output_style)
3637 {
3638 case OUTPUT_RELOCATABLE:
3639 case OUTPUT_WRITABLE_TEXT:
3640 magic = OMAGIC;
3641 break;
3642 case OUTPUT_READONLY_TEXT:
3643#ifdef NMAGIC
3644 magic = NMAGIC;
3645 break;
3646#endif
3647 case OUTPUT_DEMAND_PAGED:
3648 magic = ZMAGIC;
3649 break;
3650 default:
3651 fatal ("unknown output style found (bug in ld)", (char *) 0);
3652 break;
3653 }
3654
3655 /* Determine whether to count the header as part of
3656 the text size, and initialize the text size accordingly.
3657 This depends on the kind of system and on the output format selected. */
3658 N_SET_MAGIC (outheader, magic);
3659 N_SET_MACHTYPE (outheader, M_386);
3660#ifdef INITIALIZE_HEADER
3661 INITIALIZE_HEADER;
3662#endif
3663
3664 text_header_size = sizeof (struct exec);
3665 if (text_header_size <= N_TXTOFF (outheader))
3666 text_header_size = 0;
3667 else
3668 text_header_size -= N_TXTOFF (outheader);
3669
3670#ifdef _N_BASEADDR
3671 /* SunOS 4.1 N_TXTADDR depends on the value of outheader.a_entry. */
3672 outheader.a_entry = N_PAGSIZ(outheader);
3673#endif
3674
3675 if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
3676 text_start = N_TXTADDR (outheader);
3677}
3678
3679/* Compute data_start once text_size is known. */
3680
3681void
3682initialize_a_out_data_start (void)
3683{
3684 outheader.a_text = text_size;
3685 if (! Tdata_flag_specified)
3686 data_start = N_DATADDR (outheader) + text_start - N_TXTADDR (outheader);
3687}
3688
3689/* Compute offsets of various pieces of the a.out output file. */
3690
3691void
3692compute_a_out_section_offsets (void)
3693{
3694 outheader.a_data = data_size;
3695 outheader.a_bss = bss_size;
3696 outheader.a_entry = (entry_symbol ? entry_symbol->value
3697 : text_start + text_header_size);
3698
3699 if (strip_symbols == STRIP_ALL)
3700 nsyms = 0;
3701 else
3702 {
3703 nsyms = (defined_global_sym_count
3704 + undefined_global_sym_count);
3705 if (discard_locals == DISCARD_L)
3706 nsyms += non_L_local_sym_count;
3707 else if (discard_locals == DISCARD_NONE)
3708 nsyms += local_sym_count;
3709 /* One extra for following reference on indirects */
3710 if (output_style == OUTPUT_RELOCATABLE)
3711 nsyms += set_symbol_count + global_indirect_count;
3712 }
3713
3714 if (strip_symbols == STRIP_NONE)
3715 nsyms += debugger_sym_count;
3716
3717 outheader.a_syms = nsyms * sizeof (struct nlist);
3718
3719 if (output_style == OUTPUT_RELOCATABLE || reloc_flag)
3720 {
3721 outheader.a_trsize = text_reloc_size;
3722 outheader.a_drsize = data_reloc_size;
3723 }
3724 else
3725 {
3726 outheader.a_trsize = 0;
3727 outheader.a_drsize = 0;
3728 }
3729
3730 /* Initialize the various file offsets. */
3731
3732 output_text_offset = N_TXTOFF (outheader);
3733#ifdef N_DATOFF
3734 output_data_offset = N_DATOFF (outheader);
3735#else
3736 output_data_offset = output_text_offset + text_size;
3737#endif
3738#ifdef N_TRELOFF
3739 output_trel_offset = N_TRELOFF (outheader);
3740#else
3741 output_trel_offset = output_data_offset + data_size;
3742#endif
3743#ifdef N_DRELOFF
3744 output_drel_offset = N_DRELOFF (outheader);
3745#else
3746 output_drel_offset = output_trel_offset + text_reloc_size;
3747#endif
3748 output_syms_offset = N_SYMOFF (outheader);
3749 output_strs_offset = N_STROFF (outheader);
3750}
3751
3752/* Compute more section offsets once the size of the string table is known. */
3753
3754void
3755compute_more_a_out_section_offsets (void)
3756{
3757 output_symseg_offset = output_strs_offset + output_strs_size;
3758}
3759
3760/* Write the a.out header once everything else is known. */
3761
3762void
3763write_a_out_header (void)
3764{
3765 lseek (outdesc, 0L, 0);
3766 mywrite (&outheader, sizeof (struct exec), 1, outdesc);
3767}
3768
3769#endif
3770
3771
3772/* The following functions are simple switches according to the
3773 output style. */
3774
3775/* Compute text_start and text_header_size as appropriate for the
3776 output format. */
3777
3778void
3779initialize_text_start (void)
3780{
3781#ifdef A_OUT
3782 if (output_file_type == IS_A_OUT)
3783 {
3784 initialize_a_out_text_start ();
3785 return;
3786 }
3787#endif
3788 fatal ("unknown output file type (enum file_type)", (char *) 0);
3789}
3790
3791/* Initialize data_start as appropriate to the output format, once text_size
3792 is known. */
3793
3794void
3795initialize_data_start (void)
3796{
3797#ifdef A_OUT
3798 if (output_file_type == IS_A_OUT)
3799 {
3800 initialize_a_out_data_start ();
3801 return;
3802 }
3803#endif
3804 fatal ("unknown output file type (enum file_type)", (char *) 0);
3805}
3806
3807/* Compute offsets of the various sections within the output file. */
3808
3809void
3810compute_section_offsets (void)
3811{
3812#ifdef A_OUT
3813 if (output_file_type == IS_A_OUT)
3814 {
3815 compute_a_out_section_offsets ();
3816 return;
3817 }
3818#endif
3819 fatal ("unknown output file type (enum file_type)", (char *) 0);
3820}
3821
3822/* Compute more section offsets, once the size of the string table
3823 is finalized. */
3824void
3825compute_more_section_offsets (void)
3826{
3827#ifdef A_OUT
3828 if (output_file_type == IS_A_OUT)
3829 {
3830 compute_more_a_out_section_offsets ();
3831 return;
3832 }
3833#endif
3834 fatal ("unknown output file type (enum file_type)", (char *) 0);
3835}
3836
3837/* Write the output file header, once everything is known. */
3838void
3839write_header (void)
3840{
3841#ifdef A_OUT
3842 if (output_file_type == IS_A_OUT)
3843 {
3844 write_a_out_header ();
3845 return;
3846 }
3847#endif
3848 fatal ("unknown output file type (enum file_type)", (char *) 0);
3849}
3850
3851
3852/* Parse output_filename and decide whether to create an exe file or not */
3853
3854void check_exe (void)
3855{
3856 char *ext, *tmp_dir;
3857 size_t tmp_dir_len;
3858
3859 if (exe_flag)
3860 {
3861 ext = _getext (output_filename);
3862 if ((ext != NULL) && (stricmp (ext, ".exe") == 0))
3863 {
3864 exe_filename = output_filename;
3865 exe_flag = 0;
3866 } else
3867 {
3868 touch_filename = output_filename;
3869 exe_filename = concat (output_filename, ".exe", "");
3870 }
3871 }
3872 else
3873 {
3874 ext = _getext2 (output_filename);
3875 if (stricmp (ext, ".dll") == 0)
3876 {
3877 reloc_flag = 1; dll_flag = 1;
3878 }
3879 else if (stricmp (ext, ".exe") != 0)
3880 {
3881 exe_filename = NULL;
3882 return;
3883 }
3884 exe_filename = output_filename;
3885 }
3886
3887 /* Create a temporary a.out executable file. */
3888
3889 tmp_dir = getenv ("TMPDIR");
3890 if (tmp_dir == NULL) tmp_dir = getenv ("TMP");
3891 if (tmp_dir == NULL) tmp_dir = getenv ("TEMP");
3892 if (tmp_dir == NULL) tmp_dir = ".";
3893 tmp_dir_len = strlen (tmp_dir);
3894 output_filename = xmalloc (tmp_dir_len + 10);
3895 memcpy (output_filename, tmp_dir, tmp_dir_len);
3896 if (tmp_dir_len != 0 && strchr ("\\/:", tmp_dir[tmp_dir_len-1]) == NULL)
3897 output_filename[tmp_dir_len++] = '\\';
3898 strcpy (output_filename + tmp_dir_len, "ldXXXXXX");
3899 if (mktemp (output_filename) == NULL)
3900 fatal ("mktemp(\"%s\") failed", output_filename);
3901
3902 if (rsxnt_linked != EMX_DEFAULT && strip_symbols != STRIP_NONE) /* RSXNT */
3903 {
3904 strip_symbols = STRIP_NONE;
3905 emxbind_strip = 1;
3906 }
3907 else if (strip_symbols == STRIP_ALL)
3908 {
3909 strip_symbols = STRIP_DEBUGGER;
3910 emxbind_strip = 1;
3911 }
3912 unlink (exe_filename);
3913 if (touch_filename != NULL)
3914 unlink (touch_filename);
3915}
3916
3917/* Write the output file */
3918
3919void
3920write_output (void)
3921{
3922 struct stat statbuf;
3923 int filemode, mask;
3924
3925 /* Remove the old file in case it is owned by someone else.
3926 This prevents spurious "not owner" error messages.
3927 Don't check for errors from unlink; we don't really care
3928 whether it worked.
3929
3930 Note that this means that if the output file is hard linked,
3931 the other names will still have the old contents. This is
3932 the way Unix ld works; I'm going to consider it a feature. */
3933 (void) unlink (output_filename);
3934
3935 outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
3936 if (outdesc < 0) perror_name (output_filename);
3937
3938 if (fstat (outdesc, &statbuf) < 0)
3939 perror_name (output_filename);
3940
3941 filemode = statbuf.st_mode;
3942
3943 chmod (output_filename, filemode & ~0111);
3944
3945 if (reloc_flag)
3946 global_indirect_count = 0;
3947
3948 /* Calculate the offsets of the various pieces of the output file. */
3949 compute_section_offsets ();
3950
3951 /* Output the text and data segments, relocating as we go. */
3952 write_text ();
3953 write_data ();
3954
3955 /* Output the merged relocation info, if requested with `-r'. */
3956 if (output_style == OUTPUT_RELOCATABLE || reloc_flag)
3957 write_rel ();
3958
3959 /* Output the symbol table (both globals and locals). */
3960 write_syms ();
3961
3962 /* At this point the total size of the symbol table and string table
3963 are finalized. */
3964 compute_more_section_offsets ();
3965
3966 /* Copy any GDB symbol segments from input files. */
3967 write_symsegs ();
3968
3969 /* Now that everything is known about the output file, write its header. */
3970 write_header ();
3971
3972 close (outdesc);
3973
3974 mask = umask (0);
3975 umask (mask);
3976
3977 if (chmod (output_filename, filemode | (0111 & ~mask)) == -1)
3978 perror_name (output_filename);
3979
3980 if (rsxnt_linked == EMX_DEFAULT && exe_filename != NULL)
3981 {
3982 char *nargv[11];
3983 char *freeav[11];
3984 int i, j, saved_errno;
3985
3986 i = j = 0;
3987 nargv[i++] = "emxbind";
3988 nargv[i++] = "-bq";
3989 if (emxbind_strip)
3990 nargv[i++] = "-s";
3991 if (dll_flag && !def_filename)
3992 gen_deffile();
3993 if (def_filename != NULL)
3994 {
3995 freeav[j++] = nargv[i] = ALLOCA (strlen (def_filename) + 3);
3996 strcpy (nargv[i], "-d");
3997 strcat (nargv[i], def_filename);
3998 i++;
3999 }
4000 else if (dll_flag)
4001 nargv[i++] = "-d";
4002 if (stack_size != 0)
4003 {
4004 freeav[j++] = nargv[i] = ALLOCA (20);
4005 sprintf (nargv[i], "-k0x%x", stack_size);
4006 i++;
4007 }
4008 if (map_flag)
4009 {
4010 if (map_filename == NULL)
4011 {
4012 freeav[j++] = map_filename = ALLOCA (strlen (output_filename) + 5);
4013 strcpy (map_filename, exe_filename);
4014 _remext (map_filename);
4015 strcat (map_filename, ".map");
4016 }
4017 freeav[j++] = nargv[i] = ALLOCA (strlen (map_filename) + 3);
4018 strcpy (nargv[i], "-m");
4019 strcat (nargv[i], map_filename);
4020 i++;
4021 }
4022 if (res_filename != NULL)
4023 {
4024 freeav[j++] = nargv[i] = ALLOCA (strlen (res_filename) + 3);
4025 strcpy (nargv[i], "-r");
4026 strcat (nargv[i], res_filename);
4027 i++;
4028 }
4029 nargv[i++] = "-o";
4030 nargv[i++] = exe_filename;
4031 nargv[i++] = output_filename;
4032 nargv[i] = NULL;
4033 if (trace_files)
4034 {
4035 fprintf(stderr, "Invoking emxbind:");
4036 for (i = 0; nargv[i]; i++)
4037 fprintf(stderr, " %s", nargv[i]);
4038 fprintf(stderr, "\n");
4039 }
4040 i = spawnvp (P_WAIT, "emxbind", nargv);
4041 saved_errno = errno; unlink (output_filename); errno = saved_errno;
4042 if (i < 0)
4043 perror_name ("emxbind");
4044 else if (i != 0)
4045 fatal ("emxbind failed\n", NULL);
4046 if (chmod (exe_filename, filemode | (0111 & ~mask)) == -1)
4047 perror_name (exe_filename);
4048 if (touch_filename != NULL)
4049 {
4050 char execname[512];
4051 _execname(execname, sizeof (execname));
4052 strcpy(_getname(execname), "ldstub.bin");
4053 /* Copy stub into file */
4054 if (DosCopy(execname, touch_filename, 4))
4055 {
4056 errno = EACCES;
4057 perror_name (execname);
4058 }
4059 /* Now touch it */
4060 if (utime(touch_filename, NULL))
4061 perror_name (touch_filename);
4062 }
4063 while (j-- > 0)
4064 FREEA (freeav[j]);
4065 }
4066 else if (exe_filename != NULL) /* RSXNT */
4067 {
4068 char *nargv[10];
4069 char *freea = NULL;
4070 int i, saved_errno;
4071
4072 i = 0;
4073 nargv[i++] = "ntbind";
4074 nargv[i++] = output_filename;
4075 nargv[i++] = "-o";
4076 nargv[i++] = exe_filename;
4077 nargv[i++] = "-s";
4078 if (rsxnt_linked == RSXNT_WIN32)
4079 nargv[i++] = (emxbind_strip) ? "dosstub.dos" : "dosstub.dbg";
4080 else
4081 {
4082 nargv[i++] = "dosstub.rsx";
4083 if (emxbind_strip)
4084 nargv[i++] = "-strip";
4085 }
4086 if (def_filename != NULL)
4087 {
4088 nargv[i++] = "-d";
4089 freea = nargv[i] = ALLOCA (strlen (def_filename) + 3);
4090 strcpy(nargv[i], def_filename);
4091 i++;
4092 }
4093 nargv[i] = NULL;
4094
4095 i = spawnvp (P_WAIT, "ntbind", nargv);
4096 saved_errno = errno; unlink (output_filename); errno = saved_errno;
4097 if (i < 0)
4098 perror_name ("ntbind");
4099 else if (i != 0)
4100 fatal ("ntbind failed\n", NULL);
4101 if (chmod (exe_filename, filemode | (0111 & ~mask)) == -1)
4102 perror_name (exe_filename);
4103 if (touch_filename != NULL)
4104 {
4105 i = open (touch_filename,
4106 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
4107 if (i < 0)
4108 perror_name (touch_filename);
4109 close (i);
4110 }
4111 FREEA (freea);
4112 }
4113}
4114
4115
4116void copy_text (struct file_entry *entry);
4117void copy_data (struct file_entry *entry);
4118void perform_relocation ( char *data, int pc_relocation, int data_size,
4119 struct relocation_info *reloc_info, int reloc_size, struct file_entry *entry);
4120#ifdef DEBUG_BIRD
4121void dbg_dump_rel(struct file_entry *entry, struct relocation_info * rel,
4122 size_t reloc_size, const char *desc);
4123#endif
4124
4125/* Relocate the text segment of each input file
4126 and write to the output file. */
4127
4128void
4129write_text ()
4130{
4131 if (trace_files)
4132 fprintf (stderr, "Copying and relocating text:\n\n");
4133
4134 lseek (outdesc, output_text_offset + text_header_size, 0);
4135
4136 each_full_file (copy_text, 0);
4137 file_close ();
4138
4139 if (trace_files)
4140 fprintf (stderr, "\n");
4141
4142 padfile (text_pad, outdesc);
4143}
4144
4145/* Read in all of the relocation information */
4146
4147void
4148read_relocation (void)
4149{
4150 each_full_file (read_file_relocation, 0);
4151}
4152
4153/* Read in the relocation sections of ENTRY if necessary */
4154
4155void
4156read_file_relocation (entry)
4157 struct file_entry *entry;
4158{
4159 register struct relocation_info *reloc;
4160 int desc;
4161 int read_return;
4162
4163 desc = -1;
4164 if (!entry->textrel)
4165 {
4166 reloc = (struct relocation_info *) xmalloc (entry->text_reloc_size);
4167 desc = file_open (entry);
4168 lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
4169 if (entry->text_reloc_size != (read_return = read (desc, reloc, entry->text_reloc_size)))
4170 {
4171 fprintf (stderr, "Return from read: %d\n", read_return);
4172 fatal_with_file ("premature eof in text relocation of ", entry);
4173 }
4174 entry->textrel = reloc;
4175 }
4176
4177 if (!entry->datarel)
4178 {
4179 reloc = (struct relocation_info *) xmalloc (entry->data_reloc_size);
4180 if (desc == -1) desc = file_open (entry);
4181 lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
4182 if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
4183 fatal_with_file ("premature eof in data relocation of ", entry);
4184 entry->datarel = reloc;
4185 }
4186#ifdef DEBUG_BIRD
4187 dbg_dump_rel(entry, entry->textrel, entry->text_reloc_size, "text");
4188 dbg_dump_rel(entry, entry->datarel, entry->data_reloc_size, "data");
4189#endif
4190}
4191
4192/* Read the text segment contents of ENTRY, relocate them,
4193 and write the result to the output file.
4194 If `-r', save the text relocation for later reuse. */
4195
4196void
4197copy_text (entry)
4198 struct file_entry *entry;
4199{
4200 register char *bytes;
4201 register int desc;
4202 register struct relocation_info *reloc;
4203 int free_reloc = 0;
4204
4205 if (trace_files)
4206 prline_file_name (entry, stderr);
4207
4208 desc = file_open (entry);
4209
4210 /* Allocate space for the file's text section */
4211
4212 bytes = (char *) ALLOCA (entry->text_size);
4213
4214 /* Deal with relocation information however is appropriate */
4215
4216 if (entry->textrel) reloc = entry->textrel;
4217 else if (output_style == OUTPUT_RELOCATABLE || reloc_flag)
4218 {
4219 read_file_relocation (entry);
4220 reloc = entry->textrel;
4221 }
4222 else
4223 {
4224 free_reloc = 1;
4225 reloc = (struct relocation_info *) ALLOCA (entry->text_reloc_size);
4226 lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
4227 if (entry->text_reloc_size != read (desc, reloc, entry->text_reloc_size))
4228 fatal_with_file ("premature eof in text relocation of ", entry);
4229 }
4230
4231 /* Read the text section into core. */
4232
4233 lseek (desc, entry->starting_offset + entry->text_offset, L_SET);
4234 if (entry->text_size != read (desc, bytes, entry->text_size))
4235 fatal_with_file ("premature eof in text section of ", entry);
4236
4237 /* Relocate the text according to the text relocation. */
4238
4239 perform_relocation (bytes, entry->text_start_address - entry->orig_text_address,
4240 entry->text_size, reloc, entry->text_reloc_size, entry);
4241
4242 /* Write the relocated text to the output file. */
4243
4244 mywrite (bytes, 1, entry->text_size, outdesc);
4245
4246 FREEA (bytes);
4247 if (free_reloc)
4248 FREEA (reloc);
4249}
4250
4251#ifdef DEBUG_BIRD
4252void dbg_dump_rel(struct file_entry *entry, struct relocation_info * rel,
4253 size_t reloc_size, const char *desc)
4254{
4255 struct relocation_info *relend = (struct relocation_info *)((char*)rel + reloc_size);
4256 int i;
4257
4258 fprintf(stderr,
4259 "dbg: %s relocations %s:\n"
4260 "dbg: rel - Address len sym# attrs\n",
4261 desc, entry->filename);
4262 i = 0;
4263 while (rel < relend)
4264 {
4265 fprintf(stderr, "dbg: %3d - %08x 2^%d %06x %s%s",
4266 i,
4267 rel->r_address,
4268 rel->r_length,
4269 rel->r_symbolnum,
4270 rel->r_extern ? "Extrn " : " ",
4271 rel->r_pcrel ? "PCRel " : " "
4272 );
4273 if (rel->r_extern)
4274 { /* find the symbol. */
4275 struct nlist *s = &entry->symbols[rel->r_symbolnum];
4276 fprintf(stderr, " s.val:%08lx s.typ:%02x s.des:%04x s.oth:%02x",
4277 s->n_value,
4278 (unsigned)s->n_type,
4279 s->n_desc,
4280 (unsigned)s->n_other);
4281 if (s->n_un.n_strx < 0x20000)
4282 fprintf(stderr, " !!bad symbol ptr %p", s->n_un.n_name);
4283 else
4284 {
4285 struct glosym *sym = (struct glosym *)s->n_un.n_name;
4286 fprintf(stderr, " %s", sym->name);
4287 }
4288 }
4289 fprintf(stderr, "\n");
4290 /* next */
4291 i++;
4292 rel++;
4293 }
4294}
4295#endif
4296
4297
4298/* Relocate the data segment of each input file
4299 and write to the output file. */
4300
4301void
4302write_data ()
4303{
4304 if (trace_files)
4305 fprintf (stderr, "Copying and relocating data:\n\n");
4306
4307 lseek (outdesc, output_data_offset, 0);
4308
4309 each_full_file (copy_data, 0);
4310 file_close ();
4311
4312 /* Write out the set element vectors. See digest symbols for
4313 description of length of the set vector section. */
4314
4315 padfile (set_sect_pad, outdesc);
4316
4317 if (set_vector_count)
4318 mywrite (set_vectors, set_symbol_count + 2 * set_vector_count,
4319 sizeof (unsigned long), outdesc);
4320
4321 if (trace_files)
4322 fprintf (stderr, "\n");
4323
4324 padfile (data_pad, outdesc);
4325}
4326
4327/* Read the data segment contents of ENTRY, relocate them,
4328 and write the result to the output file.
4329 If `-r', save the data relocation for later reuse.
4330 See comments in `copy_text'. */
4331
4332void
4333copy_data (entry)
4334 struct file_entry *entry;
4335{
4336 register struct relocation_info *reloc;
4337 register char *bytes;
4338 register int desc;
4339 int free_reloc = 0;
4340
4341 if (trace_files)
4342 prline_file_name (entry, stderr);
4343
4344 desc = file_open (entry);
4345
4346 bytes = (char *) ALLOCA (entry->data_size);
4347
4348 if (entry->datarel) reloc = entry->datarel;
4349 else if (output_style == OUTPUT_RELOCATABLE || reloc_flag) /* Will need this again */
4350 {
4351 read_file_relocation (entry);
4352 reloc = entry->datarel;
4353 }
4354 else
4355 {
4356 free_reloc = 1;
4357 reloc = (struct relocation_info *) ALLOCA (entry->data_reloc_size);
4358 lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
4359 if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
4360 fatal_with_file ("premature eof in data relocation of ", entry);
4361 }
4362
4363 lseek (desc, entry->starting_offset + entry->data_offset, L_SET);
4364 if (entry->data_size != read (desc, bytes, entry->data_size))
4365 fatal_with_file ("premature eof in data section of ", entry);
4366
4367 perform_relocation (bytes, entry->data_start_address - entry->orig_data_address,
4368 entry->data_size, reloc, entry->data_reloc_size, entry);
4369
4370 mywrite (bytes, 1, entry->data_size, outdesc);
4371 padfile ((SECTION_ALIGN - entry->data_size) & SECTION_ALIGN_MASK, outdesc);
4372
4373 FREEA (bytes);
4374 if (free_reloc)
4375 FREEA (reloc);
4376}
4377
4378
4379/* Relocate ENTRY's text or data section contents.
4380 DATA is the address of the contents, in core.
4381 DATA_SIZE is the length of the contents.
4382 PC_RELOCATION is the difference between the address of the contents
4383 in the output file and its address in the input file.
4384 RELOC_INFO is the address of the relocation info, in core.
4385 RELOC_SIZE is its length in bytes. */
4386/* This version is about to be severly hacked by Randy. Hope it
4387 works afterwards. */
4388void
4389perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
4390 char *data;
4391 struct relocation_info *reloc_info;
4392 struct file_entry *entry;
4393 int pc_relocation;
4394 int data_size;
4395 int reloc_size;
4396{
4397 register struct relocation_info *p = reloc_info;
4398 struct relocation_info *end
4399 = reloc_info + reloc_size / sizeof (struct relocation_info);
4400 int text_relocation = entry->text_start_address - entry->orig_text_address;
4401 int data_relocation = entry->data_start_address - entry->orig_data_address;
4402 int bss_relocation = entry->bss_start_address - entry->orig_bss_address;
4403
4404 for (; p < end; p++)
4405 {
4406 register int relocation = 0;
4407 register int addr = RELOC_ADDRESS(p);
4408 register unsigned int mask = 0;
4409
4410 if (addr >= data_size)
4411 fatal_with_file ("relocation address out of range in ", entry);
4412
4413 if (RELOC_EXTERN_P(p))
4414 {
4415 int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
4416 symbol *sp = ((symbol *)
4417 (((struct nlist *)
4418 (((char *)entry->symbols) + symindex))
4419 ->n_un.n_name));
4420
4421#ifdef N_INDR
4422 /* Resolve indirection */
4423 if ((sp->defined & ~N_EXT) == N_INDR)
4424 sp = (symbol *) sp->value;
4425#endif
4426
4427 if (symindex >= entry->syms_size)
4428 fatal_with_file ("relocation symbolnum out of range in ", entry);
4429
4430 /* If the symbol is undefined, leave it at zero. */
4431 if (! sp->defined)
4432 relocation = 0;
4433 else
4434 relocation = sp->value;
4435 }
4436 else switch (RELOC_TYPE(p))
4437 {
4438 case N_TEXT:
4439 case N_TEXT | N_EXT:
4440 relocation = text_relocation;
4441 break;
4442
4443 case N_DATA:
4444 case N_DATA | N_EXT:
4445 relocation = data_relocation;
4446 break;
4447
4448 case N_BSS:
4449 case N_BSS | N_EXT:
4450 relocation = bss_relocation;
4451 break;
4452
4453 case N_ABS:
4454 case N_ABS | N_EXT:
4455 /* Don't know why this code would occur, but apparently it does. */
4456 break;
4457
4458 default:
4459 fatal_with_file ("nonexternal relocation code invalid in ", entry);
4460 }
4461
4462 if (RELOC_PCREL_P(p))
4463 relocation -= pc_relocation;
4464
4465#ifdef RELOC_ADD_EXTRA
4466 relocation += RELOC_ADD_EXTRA(p);
4467 if (output_style == OUTPUT_RELOCATABLE)
4468 {
4469 /* If this RELOC_ADD_EXTRA is 0, it means that the
4470 symbol was external and the relocation does not
4471 need a fixup here. */
4472 if (RELOC_ADD_EXTRA (p))
4473 {
4474 if (! RELOC_PCREL_P (p))
4475 RELOC_ADD_EXTRA (p) = relocation;
4476 else
4477 RELOC_ADD_EXTRA (p) -= pc_relocation;
4478 }
4479#if 0
4480 if (! RELOC_PCREL_P (p))
4481 {
4482 if ((int)p->r_type <= RELOC_32
4483 || RELOC_EXTERN_P (p) == 0)
4484 RELOC_ADD_EXTRA (p) = relocation;
4485 }
4486 else if (RELOC_EXTERN_P (p))
4487 RELOC_ADD_EXTRA (p) -= pc_relocation;
4488#endif
4489 continue;
4490 }
4491#endif
4492
4493 relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
4494
4495 /* Unshifted mask for relocation */
4496 mask = (1 << RELOC_TARGET_BITSIZE(p)) - 1;
4497 relocation &= mask;
4498
4499 /* Shift everything up to where it's going to be used */
4500 relocation <<= RELOC_TARGET_BITPOS(p);
4501 mask <<= RELOC_TARGET_BITPOS(p);
4502
4503 switch (RELOC_TARGET_SIZE(p))
4504 {
4505 case 0:
4506 if (RELOC_MEMORY_SUB_P(p))
4507 relocation -= mask & *(char *) (data + addr);
4508 else if (RELOC_MEMORY_ADD_P(p))
4509 relocation += mask & *(char *) (data + addr);
4510 *(char *) (data + addr) &= ~mask;
4511 *(char *) (data + addr) |= relocation;
4512 break;
4513
4514 case 1:
4515 if (RELOC_MEMORY_SUB_P(p))
4516 relocation -= mask & *(short *) (data + addr);
4517 else if (RELOC_MEMORY_ADD_P(p))
4518 relocation += mask & *(short *) (data + addr);
4519 *(short *) (data + addr) &= ~mask;
4520 *(short *) (data + addr) |= relocation;
4521 break;
4522
4523 case 2:
4524#ifdef CROSS_LINKER
4525 /* This is necessary if the host has stricter alignment
4526 than the target. Too slow to use all the time.
4527 Also doesn't deal with differing byte-order. */
4528 {
4529 /* Thing to relocate. */
4530 long thing;
4531 bcopy (data + addr, &thing, sizeof (thing));
4532 if (RELOC_MEMORY_SUB_P (p))
4533 relocation -= mask & thing;
4534 else if (RELOC_MEMORY_ADD_P (p))
4535 relocation += mask & thing;
4536 thing = (thing & ~mask) | relocation;
4537 bcopy (&thing, data + addr, sizeof (thing));
4538 }
4539#else /* not CROSS_LINKER */
4540 if (RELOC_MEMORY_SUB_P(p))
4541 relocation -= mask & *(long *) (data + addr);
4542 else if (RELOC_MEMORY_ADD_P(p))
4543 relocation += mask & *(long *) (data + addr);
4544 *(long *) (data + addr) &= ~mask;
4545 *(long *) (data + addr) |= relocation;
4546#endif /* not CROSS_LINKER */
4547 break;
4548
4549 default:
4550 fatal_with_file ("Unimplemented relocation field length in ", entry);
4551 }
4552 }
4553}
4554
4555
4556/* For OUTPUT_RELOCATABLE only: write out the relocation,
4557 relocating the addresses-to-be-relocated. */
4558
4559void coptxtrel (struct file_entry *entry);
4560void copdatrel (struct file_entry *entry);
4561
4562void
4563write_rel ()
4564{
4565 register int i;
4566 register int count = 0;
4567
4568 if (trace_files)
4569 fprintf (stderr, "Writing text relocation:\n\n");
4570
4571 /* Assign each global symbol a sequence number, giving the order
4572 in which `write_syms' will write it.
4573 This is so we can store the proper symbolnum fields
4574 in relocation entries we write. */
4575
4576 for (i = 0; i < TABSIZE; i++)
4577 {
4578 symbol *sp;
4579 for (sp = symtab[i]; sp; sp = sp->link)
4580 if (sp->referenced || sp->defined)
4581 {
4582 sp->def_count = count++;
4583 /* Leave room for the reference required by N_INDR, if
4584 necessary. */
4585 if ((sp->defined & ~N_EXT) == N_INDR)
4586 if (!reloc_flag)
4587 count++;
4588 }
4589 }
4590 /* Correct, because if (OUTPUT_RELOCATABLE), we will also be writing
4591 whatever indirect blocks we have. */
4592 if (count != defined_global_sym_count
4593 + undefined_global_sym_count + global_indirect_count)
4594 fatal ("internal error");
4595
4596 /* Write out the relocations of all files, remembered from copy_text. */
4597
4598 lseek (outdesc, output_trel_offset, 0);
4599 each_full_file (coptxtrel, 0);
4600
4601 if (trace_files)
4602 fprintf (stderr, "\nWriting data relocation:\n\n");
4603
4604 lseek (outdesc, output_drel_offset, 0);
4605 each_full_file (copdatrel, 0);
4606 if (reloc_flag)
4607 {
4608 int i;
4609 int n = set_sect_size / sizeof (unsigned long);
4610 struct relocation_info reloc;
4611
4612 memset (&reloc, 0, sizeof (reloc));
4613 RELOC_PCREL_P (&reloc) = 0;
4614 RELOC_TARGET_SIZE (&reloc) = 2;
4615 RELOC_EXTERN_P (&reloc) = 0;
4616 for (i = 0; i < n; ++i)
4617 switch (set_reloc[i] & ~N_EXT)
4618 {
4619 case N_TEXT:
4620 case N_DATA:
4621 RELOC_SYMBOL (&reloc) = set_reloc[i] & ~N_EXT;
4622 RELOC_ADDRESS (&reloc)
4623 = set_sect_start + i * sizeof (unsigned long) - data_start;
4624 mywrite (&reloc, sizeof (reloc), 1, outdesc);
4625 break;
4626 case N_ABS:
4627 break;
4628 default:
4629 fatal ("N_SETB not supported", (char *)0);
4630 }
4631 }
4632
4633 if (trace_files)
4634 fprintf (stderr, "\n");
4635}
4636
4637void
4638coptxtrel (entry)
4639 struct file_entry *entry;
4640{
4641 register struct relocation_info *p, *end;
4642 register int reloc = entry->text_start_address - text_start;
4643
4644 p = entry->textrel;
4645 end = (struct relocation_info *) (entry->text_reloc_size + (char *) p);
4646 while (p < end)
4647 {
4648 RELOC_ADDRESS(p) += reloc;
4649 if (RELOC_EXTERN_P(p))
4650 {
4651 register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
4652 symbol *symptr = ((symbol *)
4653 (((struct nlist *)
4654 (((char *)entry->symbols) + symindex))
4655 ->n_un.n_name));
4656
4657 if (symindex >= entry->syms_size)
4658 fatal_with_file ("relocation symbolnum out of range in ", entry);
4659
4660#ifdef N_INDR
4661 /* Resolve indirection. */
4662 if ((symptr->defined & ~N_EXT) == N_INDR)
4663 symptr = (symbol *) symptr->value;
4664#endif
4665
4666 /* If the symbol is now defined, change the external relocation
4667 to an internal one. */
4668
4669 if (symptr->defined && symptr->defined != (N_IMP1 | N_EXT))
4670 {
4671 RELOC_EXTERN_P(p) = 0;
4672 RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
4673 if (RELOC_SYMBOL (p) == N_SETV)
4674 RELOC_SYMBOL (p) = N_DATA;
4675#ifdef RELOC_ADD_EXTRA
4676 /* If we aren't going to be adding in the value in
4677 memory on the next pass of the loader, then we need
4678 to add it in from the relocation entry. Otherwise
4679 the work we did in this pass is lost. */
4680 if (!RELOC_MEMORY_ADD_P(p))
4681 RELOC_ADD_EXTRA (p) += symptr->value;
4682#endif
4683 }
4684 else
4685 /* Debugger symbols come first, so have to start this
4686 after them. */
4687 RELOC_SYMBOL(p) = (symptr->def_count + nsyms
4688 - defined_global_sym_count
4689 - undefined_global_sym_count
4690 - global_indirect_count);
4691 }
4692 p++;
4693 }
4694
4695 mywrite (entry->textrel, 1, entry->text_reloc_size, outdesc);
4696}
4697
4698void
4699copdatrel (entry)
4700 struct file_entry *entry;
4701{
4702 register struct relocation_info *p, *end;
4703 /* Relocate the address of the relocation.
4704 Old address is relative to start of the input file's data section.
4705 New address is relative to start of the output file's data section.
4706
4707 So the amount we need to relocate it by is the offset of this
4708 input file's data section within the output file's data section. */
4709 register int reloc = entry->data_start_address - data_start;
4710
4711 p = entry->datarel;
4712 end = (struct relocation_info *) (entry->data_reloc_size + (char *) p);
4713 while (p < end)
4714 {
4715 RELOC_ADDRESS(p) += reloc;
4716 if (RELOC_EXTERN_P(p))
4717 {
4718 register int symindex = RELOC_SYMBOL(p);
4719 symbol *symptr = (symbol *)(entry->symbols [symindex].n_un.n_name);
4720 int symtype;
4721
4722 if (symindex >= (entry->syms_size / sizeof (struct nlist)))
4723 fatal_with_file ("relocation symbolnum out of range in ", entry);
4724
4725#ifdef N_INDR
4726 /* Resolve indirection. */
4727 if ((symptr->defined & ~N_EXT) == N_INDR)
4728 symptr = (symbol *) symptr->value;
4729#endif
4730
4731 symtype = symptr->defined & ~N_EXT;
4732
4733 if (force_common_definition
4734 || (reloc_flag && symtype != N_IMP1)
4735 || symtype == N_DATA || symtype == N_TEXT
4736 || symtype == N_ABS || symtype == N_BSS)
4737 {
4738 if (symtype == N_SETV)
4739 symtype = N_DATA;
4740 RELOC_EXTERN_P(p) = 0;
4741 RELOC_SYMBOL(p) = symtype;
4742 }
4743 else
4744 /* Debugger symbols come first, so have to start this
4745 after them. */
4746 RELOC_SYMBOL(p) = (symptr->def_count
4747 + nsyms - defined_global_sym_count
4748 - undefined_global_sym_count
4749 - global_indirect_count);
4750
4751#if 0
4752 if ((symtype = symptr->defined) != (N_IMP1 | N_EXT))
4753 symtype = symptr->defined & ~N_EXT;
4754
4755 if ((force_common_definition || reloc_flag)
4756 && (symtype != (N_IMP1 | N_EXT)))
4757 {
4758 if (force_common_definition
4759 || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
4760 {
4761 if (symtype == N_SETV)
4762 symtype = N_DATA;
4763 RELOC_EXTERN_P(p) = 0;
4764 RELOC_SYMBOL(p) = symtype;
4765 }
4766 else
4767 /* Debugger symbols come first, so have to start this
4768 after them. */
4769 RELOC_SYMBOL(p) = (symptr->def_count
4770 + nsyms - defined_global_sym_count
4771 - undefined_global_sym_count
4772 - global_indirect_count);
4773 }
4774#endif
4775 }
4776 p++;
4777 }
4778
4779 mywrite (entry->datarel, 1, entry->data_reloc_size, outdesc);
4780}
4781
4782
4783void write_file_syms (struct file_entry *entry, int *syms_written_addr);
4784void write_string_table (void);
4785
4786/* Total size of string table strings allocated so far,
4787 including strings in `strtab_vector'. */
4788int strtab_size;
4789
4790/* Vector whose elements are strings to be added to the string table. */
4791char **strtab_vector;
4792
4793/* Vector whose elements are the lengths of those strings. */
4794int *strtab_lens;
4795
4796/* Index in `strtab_vector' at which the next string will be stored. */
4797int strtab_index;
4798
4799/* Add the string NAME to the output file string table.
4800 Record it in `strtab_vector' to be output later.
4801 Return the index within the string table that this string will have. */
4802
4803int
4804assign_string_table_index (name)
4805 char *name;
4806{
4807 register int index = strtab_size;
4808 register int len = strlen (name) + 1;
4809
4810 strtab_size += len;
4811 strtab_vector[strtab_index] = name;
4812 strtab_lens[strtab_index++] = len;
4813
4814 return index;
4815}
4816
4817FILE *outstream = (FILE *) 0;
4818
4819/* Write the contents of `strtab_vector' into the string table.
4820 This is done once for each file's local&debugger symbols
4821 and once for the global symbols. */
4822
4823void
4824write_string_table (void)
4825{
4826 register int i;
4827
4828 lseek (outdesc, output_strs_offset + output_strs_size, 0);
4829
4830 if (!outstream)
4831 outstream = fdopen (outdesc, "wb");
4832
4833 for (i = 0; i < strtab_index; i++)
4834 {
4835 fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
4836 output_strs_size += strtab_lens[i];
4837 }
4838
4839 fflush (outstream);
4840
4841 /* Report I/O error such as disk full. */
4842 if (ferror (outstream))
4843 perror_name (output_filename);
4844}
4845
4846
4847/* Write the symbol table and string table of the output file. */
4848
4849void
4850write_syms ()
4851{
4852 /* Number of symbols written so far. */
4853 int syms_written = 0;
4854 register int i;
4855 register symbol *sp;
4856
4857 /* Buffer big enough for all the global symbols. One
4858 extra struct for each indirect symbol to hold the extra reference
4859 following. */
4860 struct nlist *buf = (struct nlist *) ALLOCA ((defined_global_sym_count
4861 + undefined_global_sym_count
4862 + global_indirect_count)
4863 * sizeof (struct nlist));
4864 /* Pointer for storing into BUF. */
4865 register struct nlist *bufp = buf;
4866
4867 /* Size of string table includes the bytes that store the size. */
4868 strtab_size = sizeof strtab_size;
4869
4870 output_syms_size = 0;
4871 output_strs_size = strtab_size;
4872
4873 if (strip_symbols == STRIP_ALL)
4874 return;
4875
4876 /* Write the local symbols defined by the various files. */
4877
4878 each_file (write_file_syms, (int)&syms_written);
4879 file_close ();
4880
4881 /* Now write out the global symbols. */
4882
4883 /* Allocate two vectors that record the data to generate the string
4884 table from the global symbols written so far. This must include
4885 extra space for the references following indirect outputs. */
4886
4887 strtab_vector = (char **) ALLOCA ((num_hash_tab_syms
4888 + global_indirect_count) * sizeof (char *));
4889 strtab_lens = (int *) ALLOCA ((num_hash_tab_syms
4890 + global_indirect_count) * sizeof (int));
4891 strtab_index = 0;
4892
4893 /* Scan the symbol hash table, bucket by bucket. */
4894
4895 for (i = 0; i < TABSIZE; i++)
4896 for (sp = symtab[i]; sp; sp = sp->link)
4897 {
4898 struct nlist nl;
4899
4900#ifdef N_SECT
4901 nl.n_sect = 0;
4902#else
4903 nl.n_other = 0;
4904#endif
4905 nl.n_desc = 0;
4906
4907 /* Compute a `struct nlist' for the symbol. */
4908
4909 if (sp->defined || sp->referenced)
4910 {
4911 /* common condition needs to be before undefined condition */
4912 /* because unallocated commons are set undefined in */
4913 /* digest_symbols */
4914 if (sp->defined > 1) /* defined with known type */
4915 {
4916 /* If the target of an indirect symbol has been
4917 defined and we are outputting an executable,
4918 resolve the indirection; it's no longer needed */
4919 if (output_style != OUTPUT_RELOCATABLE
4920 && ((sp->defined & ~N_EXT) == N_INDR)
4921 && (((symbol *) sp->value)->defined > 1))
4922 {
4923 symbol *newsp = (symbol *) sp->value;
4924 nl.n_type = newsp->defined;
4925 nl.n_value = newsp->value;
4926 }
4927 else
4928 {
4929 nl.n_type = sp->defined;
4930 if (sp->defined != (N_INDR | N_EXT))
4931 nl.n_value = sp->value;
4932 else
4933 nl.n_value = 0;
4934 }
4935 }
4936 else if (sp->max_common_size) /* defined as common but not allocated. */
4937 {
4938 /* happens only with -r and not -d */
4939 /* write out a common definition */
4940 nl.n_type = N_UNDF | N_EXT;
4941 nl.n_value = sp->max_common_size;
4942 }
4943 else if (!sp->defined && sp->weak)
4944 {
4945 nl.n_type = sp->weak;
4946 nl.n_value = 0;
4947 }
4948 else if (!sp->defined) /* undefined -- legit only if -r */
4949 {
4950 nl.n_type = N_UNDF | N_EXT;
4951 nl.n_value = 0;
4952 }
4953 else
4954 fatal ("internal error: %s defined in mysterious way", sp->name);
4955
4956 /* Allocate string table space for the symbol name. */
4957
4958 nl.n_un.n_strx = assign_string_table_index (sp->name);
4959
4960 /* Output to the buffer and count it. */
4961
4962 *bufp++ = nl;
4963 syms_written++;
4964 if (nl.n_type == (N_INDR | N_EXT))
4965 {
4966 struct nlist xtra_ref;
4967 xtra_ref.n_type = N_EXT | N_UNDF;
4968 xtra_ref.n_un.n_strx
4969 = assign_string_table_index (((symbol *) sp->value)->name);
4970#ifdef N_SECT
4971 xtra_ref.n_sect = 0;
4972#else
4973 xtra_ref.n_other = 0;
4974#endif
4975 xtra_ref.n_desc = 0;
4976 xtra_ref.n_value = 0;
4977 *bufp++ = xtra_ref;
4978 syms_written++;
4979 }
4980 }
4981 }
4982
4983 /* Output the buffer full of `struct nlist's. */
4984
4985 lseek (outdesc, output_syms_offset + output_syms_size, 0);
4986 mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
4987 output_syms_size += sizeof (struct nlist) * (bufp - buf);
4988
4989 if (syms_written != nsyms)
4990 fatal ("internal error: wrong number of symbols written into output file", 0);
4991
4992 /* Now the total string table size is known, so write it into the
4993 first word of the string table. */
4994
4995 lseek (outdesc, output_strs_offset, 0);
4996 mywrite (&strtab_size, sizeof (int), 1, outdesc);
4997
4998 /* Write the strings for the global symbols. */
4999
5000 write_string_table ();
5001 FREEA (strtab_vector);
5002 FREEA (strtab_lens);
5003 FREEA (buf);
5004}
5005
5006
5007/* Write the local and debugger symbols of file ENTRY.
5008 Increment *SYMS_WRITTEN_ADDR for each symbol that is written. */
5009
5010/* Note that we do not combine identical names of local symbols.
5011 dbx or gdb would be confused if we did that. */
5012
5013void
5014write_file_syms (entry, syms_written_addr)
5015 struct file_entry *entry;
5016 int *syms_written_addr;
5017{
5018 register struct nlist *p = entry->symbols;
5019 register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
5020
5021 /* Buffer to accumulate all the syms before writing them.
5022 It has one extra slot for the local symbol we generate here. */
5023 struct nlist *buf
5024 = (struct nlist *) ALLOCA (entry->syms_size + sizeof (struct nlist));
5025 register struct nlist *bufp = buf;
5026
5027 /* Upper bound on number of syms to be written here. */
5028 int max_syms = (entry->syms_size / sizeof (struct nlist)) + 1;
5029
5030 /* Make tables that record, for each symbol, its name and its name's length.
5031 The elements are filled in by `assign_string_table_index'. */
5032
5033 strtab_vector = (char **) ALLOCA (max_syms * sizeof (char *));
5034 strtab_lens = (int *) ALLOCA (max_syms * sizeof (int));
5035 strtab_index = 0;
5036
5037 /* Generate a local symbol for the start of this file's text. */
5038
5039 if (discard_locals != DISCARD_ALL)
5040 {
5041 struct nlist nl;
5042
5043 nl.n_type = N_TEXT;
5044#ifdef EMX /* fix GCC/ld/GDB problem */
5045 {
5046 char *tmp;
5047 int len;
5048
5049 tmp = entry->local_sym_name;
5050 len = strlen (tmp);
5051 if (strncmp (tmp, "-l", 2) != 0
5052 && (len < 2 || strcmp (tmp+len-2, ".o") != 0))
5053 tmp = concat (tmp, ".o", ""); /* Needed by GDB */
5054 nl.n_un.n_strx = assign_string_table_index (tmp);
5055 }
5056#else /* !EMX */
5057 nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
5058#endif /* !EMX */
5059 nl.n_value = entry->text_start_address;
5060 nl.n_desc = 0;
5061#ifdef N_SECT
5062 nl.n_sect = 0;
5063#else
5064 nl.n_other = 0;
5065#endif
5066 *bufp++ = nl;
5067 (*syms_written_addr)++;
5068 entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
5069 }
5070
5071 /* Read the file's string table. */
5072
5073 entry->strings = (char *) ALLOCA (entry->strs_size);
5074 read_entry_strings (file_open (entry), entry);
5075
5076 for (; p < end; p++)
5077 {
5078 register int type = p->n_type;
5079 register int write = 0;
5080
5081 /* WRITE gets 1 for a non-global symbol that should be written. */
5082
5083 if (SET_ELEMENT_P (type)) /* This occurs even if global. These */
5084 /* types of symbols are never written */
5085 /* globally, though they are stored */
5086 /* globally. */
5087 write = output_style == OUTPUT_RELOCATABLE;
5088 else if (WEAK_SYMBOL (type))
5089 ;
5090 else if (!(type & (N_STAB | N_EXT)))
5091 /* ordinary local symbol */
5092 write = ((discard_locals != DISCARD_ALL)
5093 && !(discard_locals == DISCARD_L &&
5094 (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
5095 && type != N_WARNING);
5096 else if (!(type & N_EXT))
5097 /* debugger symbol */
5098 write = (strip_symbols == STRIP_NONE);
5099
5100 if (write)
5101 {
5102 /* If this symbol has a name,
5103 allocate space for it in the output string table. */
5104
5105 if (p->n_un.n_strx)
5106 p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
5107 + entry->strings);
5108
5109 /* Output this symbol to the buffer and count it. */
5110
5111 *bufp++ = *p;
5112 (*syms_written_addr)++;
5113 }
5114 }
5115
5116 /* All the symbols are now in BUF; write them. */
5117
5118 lseek (outdesc, output_syms_offset + output_syms_size, 0);
5119 mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
5120 output_syms_size += sizeof (struct nlist) * (bufp - buf);
5121
5122 /* Write the string-table data for the symbols just written,
5123 using the data in vectors `strtab_vector' and `strtab_lens'. */
5124
5125 write_string_table ();
5126 FREEA (entry->strings);
5127 FREEA (strtab_vector);
5128 FREEA (strtab_lens);
5129 FREEA (buf);
5130}
5131
5132
5133/* Copy any GDB symbol segments from the input files to the output file.
5134 The contents of the symbol segment is copied without change
5135 except that we store some information into the beginning of it. */
5136
5137void write_file_symseg (struct file_entry *entry);
5138
5139void
5140write_symsegs ()
5141{
5142 lseek (outdesc, output_symseg_offset, 0);
5143 each_file (write_file_symseg, 0);
5144}
5145
5146void
5147write_file_symseg (entry)
5148 struct file_entry *entry;
5149{
5150 char buffer[4096];
5151 struct symbol_root root;
5152 int indesc, len, total;
5153
5154 if (entry->symseg_size == 0)
5155 return;
5156
5157 output_symseg_size += entry->symseg_size;
5158
5159 /* This entry has a symbol segment. Read the root of the segment. */
5160
5161 indesc = file_open (entry);
5162 lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
5163 if (sizeof root != read (indesc, &root, sizeof root))
5164 fatal_with_file ("premature end of file in symbol segment of ", entry);
5165
5166 /* Store some relocation info into the root. */
5167
5168 root.ldsymoff = entry->local_syms_offset;
5169 root.textrel = entry->text_start_address - entry->orig_text_address;
5170 root.datarel = entry->data_start_address - entry->orig_data_address;
5171 root.bssrel = entry->bss_start_address - entry->orig_bss_address;
5172 root.databeg = entry->data_start_address - root.datarel;
5173 root.bssbeg = entry->bss_start_address - root.bssrel;
5174
5175 /* Write the modified root into the output file. */
5176
5177 mywrite (&root, sizeof root, 1, outdesc);
5178
5179 /* Copy the rest of the symbol segment unchanged. */
5180
5181 total = entry->symseg_size - sizeof root;
5182
5183 while (total > 0)
5184 {
5185 len = read (indesc, buffer, min (sizeof buffer, total));
5186
5187 if (len != min (sizeof buffer, total))
5188 fatal_with_file ("premature end of file in symbol segment of ", entry);
5189 total -= len;
5190 mywrite (buffer, len, 1, outdesc);
5191 }
5192
5193 file_close ();
5194}
5195
5196
5197/* Define a special symbol (etext, edata, or end). NAME is the
5198 name of the symbol, with a leading underscore (whether or not this
5199 system uses such underscores). TYPE is its type (e.g. N_DATA | N_EXT).
5200 Store a symbol * for the symbol in *SYM if SYM is non-NULL. */
5201static void
5202symbol_define (name, type, sym)
5203 /* const */ char *name;
5204 int type;
5205 symbol **sym;
5206{
5207 symbol *thesym;
5208
5209#if defined(nounderscore)
5210 /* Skip the leading underscore. */
5211 name++;
5212#endif
5213
5214 thesym = getsym (name);
5215 if (thesym->defined)
5216 {
5217 /* The symbol is defined in some input file. Don't mess with it. */
5218 if (sym)
5219 *sym = 0;
5220 }
5221 else
5222 {
5223 if (thesym->referenced)
5224 /* The symbol was not defined, and we are defining it now. */
5225 undefined_global_sym_count--;
5226 thesym->defined = type;
5227 thesym->referenced = 1;
5228 if (sym)
5229 *sym = thesym;
5230 }
5231}
5232
5233/* Create the symbol table entries for `etext', `edata' and `end'. */
5234
5235void
5236symtab_init ()
5237{
5238 symbol_define ("_edata", N_DATA | N_EXT, &edata_symbol);
5239 symbol_define ("_etext", N_TEXT | N_EXT, &etext_symbol);
5240 symbol_define ("_end", N_BSS | N_EXT, &end_symbol);
5241
5242 /* Either _edata or __edata (C names) is OK as far as ANSI is concerned
5243 (see section 4.1.2.1). In general, it is best to use __foo and
5244 not worry about the confusing rules for the _foo namespace.
5245 But HPUX 7.0 uses _edata, so we might as weel be consistent. */
5246 symbol_define ("__edata", N_DATA | N_EXT, &edata_symbol_alt);
5247 symbol_define ("__etext", N_TEXT | N_EXT, &etext_symbol_alt);
5248 symbol_define ("__end", N_BSS | N_EXT, &end_symbol_alt);
5249}
5250
5251/* Compute the hash code for symbol name KEY. */
5252
5253int
5254hash_string (key)
5255 char *key;
5256{
5257 register char *cp;
5258 register int k;
5259
5260 cp = key;
5261 k = 0;
5262 while (*cp)
5263 k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
5264
5265 return k;
5266}
5267
5268
5269/* Get the symbol table entry for the global symbol named KEY.
5270 Create one if there is none. */
5271
5272symbol *
5273getsym (key)
5274 char *key;
5275{
5276 register int hashval;
5277 register symbol *bp;
5278
5279 /* Determine the proper bucket. */
5280
5281 hashval = hash_string (key) % TABSIZE;
5282
5283 /* Search the bucket. */
5284
5285 for (bp = symtab[hashval]; bp; bp = bp->link)
5286 if (! strcmp (key, bp->name))
5287 return bp;
5288
5289 /* Nothing was found; create a new symbol table entry. */
5290
5291 bp = (symbol *) xmalloc (sizeof (symbol));
5292 bp->refs = 0;
5293 bp->name = (char *) xmalloc (strlen (key) + 1);
5294 strcpy (bp->name, key);
5295 bp->defined = 0;
5296 bp->referenced = 0;
5297 bp->trace = 0;
5298 bp->value = 0;
5299 bp->max_common_size = 0;
5300 bp->warning = 0;
5301 bp->undef_refs = 0;
5302 bp->multiply_defined = 0;
5303 bp->weak = 0;
5304
5305 /* Add the entry to the bucket. */
5306
5307 bp->link = symtab[hashval];
5308 symtab[hashval] = bp;
5309
5310 ++num_hash_tab_syms;
5311
5312 return bp;
5313}
5314
5315/* Like `getsym' but return 0 if the symbol is not already known. */
5316
5317symbol *
5318getsym_soft (key)
5319 char *key;
5320{
5321 register int hashval;
5322 register symbol *bp;
5323
5324 /* Determine which bucket. */
5325
5326 hashval = hash_string (key) % TABSIZE;
5327
5328 /* Search the bucket. */
5329
5330 for (bp = symtab[hashval]; bp; bp = bp->link)
5331 if (! strcmp (key, bp->name))
5332 return bp;
5333
5334 return 0;
5335}
5336
5337
5338/* Report a usage error.
5339 Like fatal except prints a usage summary. */
5340
5341void
5342usage (string, arg)
5343 char *string, *arg;
5344{
5345 if (string)
5346 {
5347 fprintf (stderr, "%s: ", progname);
5348 fprintf (stderr, string, arg);
5349 fprintf (stderr, "\n");
5350 }
5351 fprintf (stderr, "\
5352Usage: %s [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
5353 [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
5354 [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
5355 [-S] [-T[{text,data}] addr] [-V prefix] [-X] [-Zdll-search]\n\
5356 [file...]\n", progname);
5357 exit (1);
5358}
5359
5360/* Report a fatal error.
5361 STRING is a printf format string and ARG is one arg for it. */
5362
5363void fatal (char *string, ...)
5364{
5365 va_list args;
5366 fprintf (stderr, "%s: ", progname);
5367 va_start (args, string);
5368 vfprintf (stderr, string, args);
5369 va_end (args);
5370 fprintf (stderr, "\n");
5371 exit (1);
5372}
5373
5374/* Report a fatal error. The error message is STRING
5375 followed by the filename of ENTRY. */
5376
5377void
5378fatal_with_file (string, entry)
5379 char *string;
5380 struct file_entry *entry;
5381{
5382 fprintf (stderr, "%s: ", progname);
5383 fprintf (stderr, string);
5384 print_file_name (entry, stderr);
5385 fprintf (stderr, "\n");
5386 exit (1);
5387}
5388
5389/* Report a fatal error using the message for the last failed system call,
5390 followed by the string NAME. */
5391
5392void
5393perror_name (name)
5394 char *name;
5395{
5396 char *s;
5397
5398 if (errno < sys_nerr)
5399 s = concat ("", sys_errlist[errno], " for %s");
5400 else
5401 s = "cannot open %s";
5402 fatal (s, name);
5403}
5404
5405/* Report a fatal error using the message for the last failed system call,
5406 followed by the name of file ENTRY. */
5407
5408void
5409perror_file (entry)
5410 struct file_entry *entry;
5411{
5412 char *s;
5413
5414 if (errno < sys_nerr)
5415 s = concat ("", sys_errlist[errno], " for ");
5416 else
5417 s = "cannot open ";
5418 fatal_with_file (s, entry);
5419}
5420
5421/* Report a nonfatal error.
5422 STRING is a format for printf, and ARG1 ... ARG3 are args for it. */
5423
5424void
5425error (string, arg1, arg2, arg3)
5426 char *string, *arg1, *arg2, *arg3;
5427{
5428 fprintf (stderr, "%s: ", progname);
5429 fprintf (stderr, string, arg1, arg2, arg3);
5430 fprintf (stderr, "\n");
5431}
5432
5433
5434
5435/* Output COUNT*ELTSIZE bytes of data at BUF
5436 to the descriptor DESC. */
5437
5438void
5439mywrite (buf, count, eltsize, desc)
5440 void *buf;
5441 int count;
5442 int eltsize;
5443 int desc;
5444{
5445 register int val;
5446 register int bytes = count * eltsize;
5447
5448 while (bytes > 0)
5449 {
5450 val = write (desc, buf, bytes);
5451 if (val <= 0)
5452 perror_name (output_filename);
5453 buf = (char*)buf + val;
5454 bytes -= val;
5455 }
5456}
5457
5458/* Output PADDING zero-bytes to descriptor OUTDESC.
5459 PADDING may be negative; in that case, do nothing. */
5460
5461void
5462padfile (padding, outdesc)
5463 int padding;
5464 int outdesc;
5465{
5466 register char *buf;
5467 if (padding <= 0)
5468 return;
5469
5470 buf = (char *) ALLOCA (padding);
5471 bzero (buf, padding);
5472 mywrite (buf, padding, 1, outdesc);
5473 FREEA (buf);
5474}
5475
5476/* Return a newly-allocated string
5477 whose contents concatenate the strings S1, S2, S3. */
5478
5479char *
5480concat (s1, s2, s3)
5481 const char *s1, *s2, *s3;
5482{
5483 register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
5484 register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
5485
5486 strcpy (result, s1);
5487 strcpy (result + len1, s2);
5488 strcpy (result + len1 + len2, s3);
5489 result[len1 + len2 + len3] = 0;
5490
5491 return result;
5492}
5493
5494/* Parse the string ARG using scanf format FORMAT, and return the result.
5495 If it does not parse, report fatal error
5496 generating the error message using format string ERROR and ARG as arg. */
5497
5498int
5499parse (arg, format, error)
5500 char *arg, *format, *error;
5501{
5502 int x;
5503 if (1 != sscanf (arg, format, &x))
5504 fatal (error, arg);
5505 return x;
5506}
5507
5508/* Like malloc but get fatal error if memory is exhausted. */
5509
5510char *
5511xmalloc (size)
5512 int size;
5513{
5514 register char *result = malloc (size);
5515 if (!result)
5516 fatal ("virtual memory exhausted", 0);
5517 return result;
5518}
5519
5520/* Like realloc but get fatal error if memory is exhausted. */
5521
5522void *
5523xrealloc (ptr, size)
5524 void *ptr;
5525 int size;
5526{
5527 register char *result = realloc (ptr, size);
5528 if (!result)
5529 fatal ("virtual memory exhausted", 0);
5530 return result;
5531}
5532
5533
5534char *my_cplus_demangle (const char *mangled)
5535{
5536 if (*mangled == '_')
5537 ++mangled;
5538 return cplus_demangle (mangled, demangle_options);
5539}
5540
5541
5542
5543/**
5544 * Generates an unique temporary file.
5545 *
5546 * @returns 0 on success.
5547 * @returns -1 on failure.
5548 * @param pszFile Where to put the filename.
5549 * @param pszPrefix Prefix.
5550 * @param pszSuffix Suffix.
5551 * @remark The code is nicked from the weak linker.
5552 * @remark sorry about the convention here, this is borrowed from elsewhere.
5553 */
5554static int make_tempfile(char *pszFile, const char *pszPrefix, const char *pszSuffix)
5555{
5556 struct stat s;
5557 unsigned c = 0;
5558 pid_t pid = getpid();
5559 const char * pszTmp = getenv("TMP");
5560 if (!pszTmp) pszTmp = getenv("TMPDIR");
5561 if (!pszTmp) pszTmp = getenv("TEMP");
5562 if (!pszTmp) pszTmp = ".";
5563
5564 do
5565 {
5566 struct timeval tv = {0,0};
5567 if (c++ >= 200)
5568 return -1;
5569 gettimeofday(&tv, NULL);
5570 sprintf(pszFile, "%s\\%s%x%lx%d%lx%s", pszTmp, pszPrefix, pid, tv.tv_sec, c, tv.tv_usec, pszSuffix);
5571 } while (!stat(pszFile, &s));
5572
5573 return 0;
5574}
5575
5576/* list of converted libraries and objects which must be removed upon exit. */
5577struct lx_tmp
5578{
5579 struct lx_tmp *next;
5580 char *name;
5581} *conv_list = NULL;
5582
5583/** Converts a .DLL to an temporary import library.
5584 * @remark sorry about the convention here, this is borrowed from elsewhere.
5585 */
5586char *lx_to_aout (const char *pszFilename)
5587{
5588 int rc;
5589 char * pszNewFile;
5590 struct lx_tmp *pName;
5591
5592 /*
5593 * Make temporary file.
5594 */
5595 pName = (struct lx_tmp *)xmalloc(sizeof(*pName));
5596 pName->name = pszNewFile = xmalloc(_MAX_PATH);
5597 if (make_tempfile(pszNewFile, "ldconv", ".a"))
5598 {
5599 free(pszNewFile);
5600 return NULL;
5601 }
5602
5603 /*
5604 * Do the conversion.
5605 */
5606 rc = spawnlp(P_WAIT, "emximp.exe", "emximp.exe",
5607 "-o", pszNewFile, pszFilename, NULL);
5608 if (!rc)
5609 {
5610 /* add to auto delete list for removal on exit(). */
5611 pName->next = conv_list;
5612 conv_list = pName;
5613 return pName->name;
5614
5615 }
5616 free(pszNewFile);
5617 free(pName);
5618
5619 fprintf (stderr, "emxomfld: a.out to omf conversion failed for '%s'.\n",
5620 pszFilename);
5621 exit (2);
5622 return NULL;
5623}
5624
5625
5626/**
5627 * Checks if the file FD is an LX DLL.
5628 *
5629 * @returns 1 if LX DLL.
5630 * @returns 0 if not LX DLL.
5631 * @param fd Handle to file to check.
5632 */
5633int check_lx_dll(int fd)
5634{
5635 unsigned long ul;
5636 char achMagic[2];
5637
5638 if ( lseek(fd, 0, SEEK_SET)
5639 || read(fd, &achMagic, 2) != 2)
5640 goto thats_not_it;
5641
5642 if (!memcmp(achMagic, "MZ", 2))
5643 {
5644 if ( lseek(fd, 0x3c, SEEK_SET)
5645 || read(fd, &ul, 4) != 4 /* offset of the 'new' header */
5646 || ul < 0x40
5647 || ul >= 0x10000000 /* 512MB stubs sure */
5648 || lseek(fd, ul, SEEK_SET)
5649 || read(fd, &achMagic, 2) != 2)
5650 goto thats_not_it;
5651 }
5652
5653 if ( memcmp(achMagic, "LX", 2)
5654 || lseek(fd, 14, SEEK_CUR)
5655 || read(fd, &ul, 4) != 4) /*e32_mflags*/
5656 goto thats_not_it;
5657
5658#define E32MODDLL 0x08000L
5659#define E32MODPROTDLL 0x18000L
5660#define E32MODMASK 0x38000L
5661 if ( (ul & E32MODMASK) != E32MODDLL
5662 && (ul & E32MODMASK) != E32MODPROTDLL)
5663 goto thats_not_it;
5664
5665 /* it's a LX DLL! */
5666 lseek(fd, 0, SEEK_SET);
5667 return 1;
5668
5669
5670thats_not_it:
5671 lseek(fd, 0, SEEK_SET);
5672 return 0;
5673}
5674
5675/* Generates a definition file for a dll which doesn't have one. */
5676
5677static void gen_deffile(void)
5678{
5679 char * psz;
5680 struct lx_tmp *pName;
5681
5682 /*
5683 * Make temporary file.
5684 */
5685 pName = (struct lx_tmp *)xmalloc(sizeof(*pName));
5686 pName->name = psz = xmalloc(_MAX_PATH);
5687 if (!make_tempfile(psz, "lddef", ".def"))
5688 {
5689 FILE *pFile = fopen(psz, "w");
5690 if (pFile)
5691 {
5692 const char *pszName = _getname(exe_filename);
5693 size_t cchName = strlen(pszName);
5694 if (cchName > 4 && !stricmp(pszName + cchName - 4, ".dll"))
5695 cchName -= 4;
5696 fprintf(pFile,
5697 ";; Autogenerated by ld\n"
5698 "LIBRARY %.*s INITINSTANCE TERMINSTANCE\n"
5699 "DATA MULTIPLE\n"
5700 "CODE SHARED\n"
5701 "\n",
5702 cchName, pszName);
5703 if (trace_files)
5704 fprintf(stderr,
5705 "--- Generated def-file %s:\n"
5706 ";; Autogenerated by ld\n"
5707 "LIBRARY %.*s INITINSTANCE TERMINSTANCE\n"
5708 "DATA MULTIPLE NONSHARED\n"
5709 "CODE SINGLE SHARED\n"
5710 "---- End of generated def-file.\n",
5711 psz, cchName, pszName);
5712 fclose(pFile);
5713 def_filename = psz;
5714
5715 /* add to auto delete list for removal on exit(). */
5716 pName->next = conv_list;
5717 conv_list = pName;
5718 return;
5719 }
5720 }
5721 free(psz);
5722 free(pName);
5723}
5724
5725
5726/* atexit worker */
5727void cleanup (void)
5728{
5729 for (; conv_list; conv_list = conv_list->next)
5730 unlink (conv_list->name);
5731}
Note: See TracBrowser for help on using the repository browser.