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

Last change on this file since 3232 was 2673, checked in by bird, 19 years ago
  • *:

o Synced over changed from 0.6.1 bugfixing.

  • emxbind:

o #38: Fixed truncation bug writing to the LX nametable. (Yuri)
o #38: Imports and exports are limited to 255 not 127 chars. (Yuri)
o #28: Use DLL name from the .def file when present.

  • emxomf:

o #70: Demangle symbol names in debug info. (thanks to Yuri)

  • emxomfld:

o #55: delete the response file when reinit the args.
o #46: specify .map file extension to the linker.
o #34: Removed all the silliness trying to deal with truncated symbols.
o Don't display usage() on failure, just the error message.
o #20: use mkstemp + close instead of mktemp for the response file.

  • ld:

o #20: use make_temp_file instead of mktemp. This involved including

libiberty.h which required some adjustments of duplicate code to work.

o #27: Applied fix from Yuri.

  • libmoddef:

o Allow '.' and '@' in LIBRARY/NAME names.

  • Property cvs2svn:cvs-rev set to 1.21
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 156.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#include "libiberty.h"
46
47#if !defined(A_OUT)
48#define A_OUT
49#endif
50
51#ifdef A_OUT
52#include <a_out.h>
53#endif
54
55#ifndef _System
56#define _System
57#endif
58extern int _System DosCopy (char *, char *, int);
59
60/* We need .data of every module aligned to at least 16 bound
61 in order to support the alignments required by SSE */
62#define SECTION_ALIGN 16
63#define SECTION_ALIGN_MASK (SECTION_ALIGN-1)
64
65/* If compiled with GNU C, use the built-in alloca */
66#ifdef USE_ALLOCA
67#include "alloca.h"
68#define ALLOCA(size) alloca (size)
69#define FREEA(ptr) do { (ptr) = NULL; } while (0)
70#else
71#define ALLOCA(size) malloc (size)
72#define FREEA(ptr) do { free(ptr); (ptr) = NULL; } while (0)
73#endif
74#include "getopt.h"
75
76/* Always use the GNU version of debugging symbol type codes, if possible. */
77
78#include "stab.h"
79#define CORE_ADDR unsigned long /* For symseg.h */
80#include "symseg.h"
81
82#include <strings.h>
83
84/* Determine whether we should attempt to handle (minimally)
85 N_BINCL and N_EINCL. */
86
87#if defined (__GNU_STAB__) || defined (N_BINCL)
88#define HAVE_SUN_STABS
89#endif
90
91#define min(a,b) ((a) < (b) ? (a) : (b))
92
93/* Macro to control the number of undefined references printed */
94#define MAX_UREFS_PRINTED 10
95
96/* Size of a page; obtained from the operating system. */
97
98int page_size;
99
100/* Name this program was invoked by. */
101
102char *progname;
103
104
105/* System dependencies */
106
107/* Define this if names etext, edata and end should not start with `_'. */
108/* #define nounderscore 1 */
109
110/* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
111 whose native format is different. */
112/* #define NON_NATIVE */
113
114/* The "address" of the data segment in a relocatable file.
115 The text address of a relocatable file is always
116 considered to be zero (instead of the value of N_TXTADDR, which
117 is what the address is in an executable), so we need to subtract
118 N_TXTADDR from N_DATADDR to get the "address" for the input file. */
119#define DATA_ADDR_DOT_O(hdr) (N_DATADDR(hdr) - N_TXTADDR(hdr))
120
121/* Values for 3rd argument to lseek(). */
122#ifndef L_SET
123#define L_SET 0
124#endif
125/* This is called L_INCR in BSD, but SEEK_CUR in POSIX. */
126#ifndef SEEK_CUR
127#define SEEK_CUR 1
128#endif
129
130/*
131 * Ok. Following are the relocation information macros. If your
132 * system cannot use the default set (below), you must define all of these:
133
134 * relocation_info: This must be typedef'd (or #define'd) to the type
135 * of structure that is stored in the relocation info section of your
136 * a.out files. Often this is defined in the a.out.h for your system.
137 *
138 * RELOC_ADDRESS (rval): Offset into the current section of the
139 * <whatever> to be relocated. *Must be an lvalue*.
140 *
141 * RELOC_EXTERN_P (rval): Is this relocation entry based on an
142 * external symbol (1), or was it fully resolved upon entering the
143 * loader (0) in which case some combination of the value in memory
144 * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
145 * what the value of the relocation actually was. *Must be an lvalue*.
146 *
147 * RELOC_TYPE (rval): For a non-external relocation, this is the
148 * segment to relocate for. *Must be an lvalue.*
149 *
150 * RELOC_SYMBOL (rval): For an external relocation, this is the
151 * index of its symbol in the symbol table. *Must be an lvalue*.
152 *
153 * RELOC_MEMORY_ADD_P (rval): This should be 1 if the final
154 * relocation value output here should be added to memory; 0, if the
155 * section of memory described should simply be set to the relocation
156 * value.
157 *
158 * RELOC_MEMORY_ADD_P (rval): If this is nonzero, the value previously
159 * present in the memory location to be relocated is *added*
160 * to the relocation value, to produce the final result.
161 * Otherwise, the relocation value is stored in the memory location
162 * and the value previously found there is ignored.
163 * By default, this is always 1.
164 *
165 * RELOC_MEMORY_SUB_P (rval): If this is nonzero, the value previously
166 * present in the memory location to be relocated is *subtracted*
167 * from the relocation value, to produce the final result.
168 * By default, this is always 0.
169 *
170 * RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
171 * an extra value to be added to the relocation value based on the
172 * individual relocation entry. *Must be an lvalue if defined*.
173 *
174 * RELOC_PCREL_P (rval): True if the relocation value described is
175 * pc relative.
176 *
177 * RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
178 * final relocation value before putting it where it belongs.
179 *
180 * RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
181 * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
182 * == 1; 4 bytes == 2, and etc. This is somewhat redundant (we could
183 * do everything in terms of the bit operators below), but having this
184 * macro could end up producing better code on machines without fancy
185 * bit twiddling. Also, it's easier to understand/code big/little
186 * endian distinctions with this macro.
187 *
188 * RELOC_TARGET_BITPOS (rval): The starting bit position within the
189 * object described in RELOC_TARGET_SIZE in which the relocation value
190 * will go.
191 *
192 * RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
193 * with the bits of the relocation value. It may be assumed by the
194 * code that the relocation value will fit into this many bits. This
195 * may be larger than RELOC_TARGET_SIZE if such be useful.
196 *
197 *
198 * Things I haven't implemented
199 * ----------------------------
200 *
201 * Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
202 *
203 * Pc relative relocation for External references.
204 *
205 *
206 */
207
208/* Default macros */
209#ifndef RELOC_ADDRESS
210#define RELOC_ADDRESS(r) ((r)->r_address)
211#define RELOC_EXTERN_P(r) ((r)->r_extern)
212#define RELOC_TYPE(r) ((r)->r_symbolnum)
213#define RELOC_SYMBOL(r) ((r)->r_symbolnum)
214#define RELOC_MEMORY_SUB_P(r) 0
215#define RELOC_MEMORY_ADD_P(r) 1
216#undef RELOC_ADD_EXTRA
217#define RELOC_PCREL_P(r) ((r)->r_pcrel)
218#define RELOC_VALUE_RIGHTSHIFT(r) 0
219#define RELOC_TARGET_SIZE(r) ((r)->r_length)
220#define RELOC_TARGET_BITPOS(r) 0
221#define RELOC_TARGET_BITSIZE(r) 32
222#endif
223
224#ifndef MAX_ALIGNMENT
225#define MAX_ALIGNMENT (sizeof (int))
226#endif
227
228#ifdef nounderscore
229#define LPREFIX '.'
230#else
231#define LPREFIX 'L'
232#endif
233
234
235
236/* Special global symbol types understood by GNU LD. */
237
238/* The following type indicates the definition of a symbol as being
239 an indirect reference to another symbol. The other symbol
240 appears as an undefined reference, immediately following this symbol.
241
242 Indirection is asymmetrical. The other symbol's value will be used
243 to satisfy requests for the indirect symbol, but not vice versa.
244 If the other symbol does not have a definition, libraries will
245 be searched to find a definition.
246
247 So, for example, the following two lines placed in an assembler
248 input file would result in an object file which would direct gnu ld
249 to resolve all references to symbol "foo" as references to symbol
250 "bar".
251
252 .stabs "_foo",11,0,0,0
253 .stabs "_bar",1,0,0,0
254
255 Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)). */
256
257#ifndef N_INDR
258#define N_INDR 0xa
259#endif
260
261/* The following symbols refer to set elements. These are expected
262 only in input to the loader; they should not appear in loader
263 output (unless relocatable output is requested). To be recognized
264 by the loader, the input symbols must have their N_EXT bit set.
265 All the N_SET[ATDB] symbols with the same name form one set. The
266 loader collects all of these elements at load time and outputs a
267 vector for each name.
268 Space (an array of 32 bit words) is allocated for the set in the
269 data section, and the n_value field of each set element value is
270 stored into one word of the array.
271 The first word of the array is the length of the set (number of
272 elements). The last word of the vector is set to zero for possible
273 use by incremental loaders. The array is ordered by the linkage
274 order; the first symbols which the linker encounters will be first
275 in the array.
276
277 In C syntax this looks like:
278
279 struct set_vector {
280 unsigned int length;
281 unsigned int vector[length];
282 unsigned int always_zero;
283 };
284
285 Before being placed into the array, each element is relocated
286 according to its type. This allows the loader to create an array
287 of pointers to objects automatically. N_SETA type symbols will not
288 be relocated.
289
290 The address of the set is made into an N_SETV symbol
291 whose name is the same as the name of the set.
292 This symbol acts like a N_DATA global symbol
293 in that it can satisfy undefined external references.
294
295 For the purposes of determining whether or not to load in a library
296 file, set element definitions are not considered "real
297 definitions"; they will not cause the loading of a library
298 member.
299
300 If relocatable output is requested, none of this processing is
301 done. The symbols are simply relocated and passed through to the
302 output file.
303
304 So, for example, the following three lines of assembler code
305 (whether in one file or scattered between several different ones)
306 will produce a three element vector (total length is five words;
307 see above), referenced by the symbol "_xyzzy", which will have the
308 addresses of the routines _init1, _init2, and _init3.
309
310 *NOTE*: If symbolic addresses are used in the n_value field of the
311 defining .stabs, those symbols must be defined in the same file as
312 that containing the .stabs.
313
314 .stabs "_xyzzy",23,0,0,_init1
315 .stabs "_xyzzy",23,0,0,_init2
316 .stabs "_xyzzy",23,0,0,_init3
317
318 Note that (23 == (N_SETT | N_EXT)). */
319
320#ifndef N_SETA
321#define N_SETA 0x14 /* Absolute set element symbol */
322#endif /* This is input to LD, in a .o file. */
323
324#ifndef N_SETT
325#define N_SETT 0x16 /* Text set element symbol */
326#endif /* This is input to LD, in a .o file. */
327
328#ifndef N_SETD
329#define N_SETD 0x18 /* Data set element symbol */
330#endif /* This is input to LD, in a .o file. */
331
332#ifndef N_SETB
333#define N_SETB 0x1A /* Bss set element symbol */
334#endif /* This is input to LD, in a .o file. */
335
336/* Macros dealing with the set element symbols defined in a.out.h */
337#define SET_ELEMENT_P(x) ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
338#define TYPE_OF_SET_ELEMENT(x) ((x)-N_SETA+N_ABS)
339
340#ifndef N_SETV
341#define N_SETV 0x1C /* Pointer to set vector in data area. */
342#endif /* This is output from LD. */
343
344/* Check if a symbol is weak */
345#define WEAK_SYMBOL(t) (((t) >= N_WEAKU) && ((t) <= N_WEAKB))
346
347/* If a this type of symbol is encountered, its name is a warning
348 message to print each time the symbol referenced by the next symbol
349 table entry is referenced.
350
351 This feature may be used to allow backwards compatibility with
352 certain functions (eg. gets) but to discourage programmers from
353 their use.
354
355 So if, for example, you wanted to have ld print a warning whenever
356 the function "gets" was used in their C program, you would add the
357 following to the assembler file in which gets is defined:
358
359 .stabs "Obsolete function \"gets\" referenced",30,0,0,0
360 .stabs "_gets",1,0,0,0
361
362 These .stabs do not necessarily have to be in the same file as the
363 gets function, they simply must exist somewhere in the compilation. */
364
365#ifndef N_WARNING
366#define N_WARNING 0x1E /* Warning message to print if symbol
367 included */
368#endif /* This is input to ld */
369
370#ifndef __GNU_STAB__
371
372/* Line number for the data section. This is to be used to describe
373 the source location of a variable declaration. */
374#ifndef N_DSLINE
375#define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
376#endif
377
378/* Line number for the bss section. This is to be used to describe
379 the source location of a variable declaration. */
380#ifndef N_BSLINE
381#define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
382#endif
383
384#endif /* not __GNU_STAB__ */
385
386
387/* Symbol table */
388
389/* Global symbol data is recorded in these structures,
390 one for each global symbol.
391 They are found via hashing in 'symtab', which points to a vector of buckets.
392 Each bucket is a chain of these structures through the link field. */
393
394typedef
395 struct glosym
396 {
397 /* Pointer to next symbol in this symbol's hash bucket. */
398 struct glosym *link;
399 /* Name of this symbol. */
400 char *name;
401 /* Value of this symbol as a global symbol. */
402 long value;
403 /* Chain of external 'nlist's in files for this symbol, both defs
404 and refs. */
405 struct nlist *refs;
406 /* Any warning message that might be associated with this symbol
407 from an N_WARNING symbol encountered. */
408 char *warning;
409 /* Nonzero means definitions of this symbol as common have been seen,
410 and the value here is the largest size specified by any of them. */
411 int max_common_size;
412 /* For OUTPUT_RELOCATABLE, records the index of this global sym in the
413 symbol table to be written, with the first global sym given index 0.*/
414 int def_count;
415 /* Nonzero means a definition of this global symbol is known to exist.
416 Library members should not be loaded on its account. */
417 char defined;
418 /* Nonzero means a reference to this global symbol has been seen
419 in a file that is surely being loaded.
420 A value higher than 1 is the n_type code for the symbol's
421 definition. */
422 char referenced;
423 /* A count of the number of undefined references printed for a
424 specific symbol. If a symbol is unresolved at the end of
425 digest_symbols (and the loading run is supposed to produce
426 relocatable output) do_file_warnings keeps track of how many
427 unresolved reference error messages have been printed for
428 each symbol here. When the number hits MAX_UREFS_PRINTED,
429 messages stop. */
430 unsigned char undef_refs;
431 /* 1 means that this symbol has multiple definitions. 2 means
432 that it has multiple definitions, and some of them are set
433 elements, one of which has been printed out already. */
434 unsigned char multiply_defined;
435 /* Nonzero means print a message at all refs or defs of this symbol */
436 char trace;
437 /* One of N_WEAKX values */
438 char weak;
439 }
440 symbol;
441
442/* Demangler for C++. */
443#include "demangle.h"
444static char *my_cplus_demangle (const char *);
445int demangle_options;
446
447/* Demangler function to use. We unconditionally enable the C++ demangler
448 because we assume any name it successfully demangles was probably produced
449 by the C++ compiler. Enabling it only if -lg++ was specified seems too
450 much of a kludge. */
451char *(*demangler)() = my_cplus_demangle;
452
453/* Number of buckets in symbol hash table */
454#define TABSIZE 1009
455
456/* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
457symbol *symtab[TABSIZE];
458
459/* Number of symbols in symbol hash table. */
460int num_hash_tab_syms = 0;
461
462/* Count the number of nlist entries that are for local symbols.
463 This count and the three following counts
464 are incremented as as symbols are entered in the symbol table. */
465int local_sym_count;
466
467/* Count number of nlist entries that are for local symbols
468 whose names don't start with L. */
469int non_L_local_sym_count;
470
471/* Count the number of nlist entries for debugger info. */
472int debugger_sym_count;
473
474/* Count the number of global symbols referenced and not defined. */
475int undefined_global_sym_count;
476
477/* Count the number of global symbols multiply defined. */
478int multiple_def_count;
479
480/* Count the number of defined global symbols.
481 Each symbol is counted only once
482 regardless of how many different nlist entries refer to it,
483 since the output file will need only one nlist entry for it.
484 This count is computed by `digest_symbols';
485 it is undefined while symbols are being loaded. */
486int defined_global_sym_count;
487
488/* Count the number of symbols defined through common declarations.
489 This count is kept in symdef_library, linear_library, and
490 enter_global_ref. It is incremented when the defined flag is set
491 in a symbol because of a common definition, and decremented when
492 the symbol is defined "for real" (ie. by something besides a common
493 definition). */
494int common_defined_global_count;
495
496/* Count the number of set element type symbols and the number of
497 separate vectors which these symbols will fit into. See the
498 GNU a.out.h for more info.
499 This count is computed by 'enter_file_symbols' */
500int set_symbol_count;
501int set_vector_count;
502
503/* Define a linked list of strings which define symbols which should
504 be treated as set elements even though they aren't. Any symbol
505 with a prefix matching one of these should be treated as a set
506 element.
507
508 This is to make up for deficiencies in many assemblers which aren't
509 willing to pass any stabs through to the loader which they don't
510 understand. */
511struct string_list_element {
512 char *str;
513 struct string_list_element *next;
514};
515
516struct string_list_element *set_element_prefixes;
517
518/* Count the number of definitions done indirectly (ie. done relative
519 to the value of some other symbol. */
520int global_indirect_count;
521
522/* Count the number of warning symbols encountered. */
523int warning_count;
524
525/* Total number of symbols to be written in the output file.
526 Computed by digest_symbols from the variables above. */
527int nsyms;
528
529
530/* Nonzero means ptr to symbol entry for symbol to use as start addr.
531 -e sets this. */
532symbol *entry_symbol;
533
534/* These can be NULL if we don't actually have such a symbol. */
535symbol *edata_symbol; /* the symbol _edata */
536symbol *etext_symbol; /* the symbol _etext */
537symbol *end_symbol; /* the symbol _end */
538/* We also need __{edata,etext,end} so that they can safely
539 be used from an ANSI library. */
540symbol *edata_symbol_alt;
541symbol *etext_symbol_alt;
542symbol *end_symbol_alt;
543
544
545/* Kinds of files potentially understood by the linker. */
546
547enum file_type { IS_UNKNOWN, IS_ARCHIVE, IS_A_OUT, IS_MACH_O };
548
549/* Each input file, and each library member ("subfile") being loaded,
550 has a `file_entry' structure for it.
551
552 For files specified by command args, these are contained in the vector
553 which `file_table' points to.
554
555 For library members, they are dynamically allocated,
556 and chained through the `chain' field.
557 The chain is found in the `subfiles' field of the `file_entry'.
558 The `file_entry' objects for the members have `superfile' fields pointing
559 to the one for the library. */
560
561struct file_entry {
562 /* Name of this file. */
563 char *filename;
564
565 /* What kind of file this is. */
566 enum file_type file_type;
567
568 /* Name to use for the symbol giving address of text start */
569 /* Usually the same as filename, but for a file spec'd with -l
570 this is the -l switch itself rather than the filename. */
571 char *local_sym_name;
572
573 /* Describe the layout of the contents of the file. */
574
575 /* The text section. */
576 unsigned long int orig_text_address;
577 unsigned long int text_size;
578 long int text_offset;
579
580 /* Text relocation. */
581 unsigned long int text_reloc_size;
582 long int text_reloc_offset;
583
584 /* The data section. */
585 unsigned long int orig_data_address;
586 unsigned long int data_size;
587 long int data_offset;
588
589 /* Data relocation. */
590 unsigned long int data_reloc_size;
591 long int data_reloc_offset;
592
593 /* The bss section. */
594 unsigned long int orig_bss_address;
595 unsigned long int bss_size;
596
597 /* The symbol and string tables. */
598 unsigned long int syms_size;
599 long int syms_offset;
600 unsigned long int strs_size;
601 long int strs_offset;
602
603 /* The GDB symbol segment, if any. */
604 unsigned long int symseg_size;
605 long int symseg_offset;
606
607 /* Describe data from the file loaded into core */
608
609 /* Symbol table of the file. */
610 struct nlist *symbols;
611
612 /* Pointer to the string table.
613 The string table is not kept in core all the time,
614 but when it is in core, its address is here. */
615 char *strings;
616
617 /* Next two used only if OUTPUT_RELOCATABLE or if needed for */
618 /* output of undefined reference line numbers. */
619
620 /* Text reloc info saved by `write_text' for `coptxtrel'. */
621 struct relocation_info *textrel;
622 /* Data reloc info saved by `write_data' for `copdatrel'. */
623 struct relocation_info *datarel;
624
625 /* Relation of this file's segments to the output file */
626
627 /* Start of this file's text seg in the output file core image. */
628 int text_start_address;
629 /* Start of this file's data seg in the output file core image. */
630 int data_start_address;
631 /* Start of this file's bss seg in the output file core image. */
632 int bss_start_address;
633 /* Offset in bytes in the output file symbol table
634 of the first local symbol for this file. Set by `write_file_symbols'. */
635 int local_syms_offset;
636
637 /* For library members only */
638
639 /* For a library, points to chain of entries for the library members. */
640 struct file_entry *subfiles;
641 /* For a library member, offset of the member within the archive.
642 Zero for files that are not library members. */
643 int starting_offset;
644 /* Size of contents of this file, if library member. */
645 int total_size;
646 /* For library member, points to the library's own entry. */
647 struct file_entry *superfile;
648 /* For library member, points to next entry for next member. */
649 struct file_entry *chain;
650
651 /* 1 if file is a library. */
652 char library_flag;
653
654 /* 1 if file's header has been read into this structure. */
655 char header_read_flag;
656
657 /* 1 means search a set of directories for this file. */
658 char search_dirs_flag;
659
660 /* 1 means this is base file of incremental load.
661 Do not load this file's text or data.
662 Also default text_start to after this file's bss. */
663 char just_syms_flag;
664
665 /* 1 means search for dynamic libs before static.
666 0 means search only static libs. */
667 char dynamic;
668};
669
670/* Vector of entries for input files specified by arguments.
671 These are all the input files except for members of specified libraries. */
672struct file_entry *file_table;
673
674/* Length of that vector. */
675int number_of_files;
676
677
678/* When loading the text and data, we can avoid doing a close
679 and another open between members of the same library.
680
681 These two variables remember the file that is currently open.
682 Both are zero if no file is open.
683
684 See `each_file' and `file_close'. */
685
686struct file_entry *input_file;
687int input_desc;
688
689/* The name of the file to write; "a.out" by default. */
690
691char *output_filename;
692char *exe_filename;
693char *def_filename = NULL;
694char *res_filename = NULL;
695char *map_filename = NULL;
696char *touch_filename = NULL;
697int reloc_flag = 0;
698int dll_flag = 0;
699int exe_flag = 0;
700int map_flag = 0;
701int stack_size = 0;
702int emxbind_strip = 0;
703enum exe_bind_type
704{
705 EMX_DEFAULT, RSXNT_WIN32, RSXNT_RSX, RSXNT_EMX
706} rsxnt_linked = EMX_DEFAULT;
707
708/* What kind of output file to write. */
709
710enum file_type output_file_type;
711
712#ifndef DEFAULT_OUTPUT_FILE_TYPE
713#define DEFAULT_OUTPUT_FILE_TYPE IS_A_OUT
714#endif
715
716/* What `style' of output file to write. For BSD a.out files
717 this specifies OMAGIC, NMAGIC, or ZMAGIC. For Mach-O files
718 this switches between MH_OBJECT and two flavors of MH_EXECUTE. */
719
720enum output_style
721 {
722 OUTPUT_UNSPECIFIED,
723 OUTPUT_RELOCATABLE, /* -r */
724 OUTPUT_WRITABLE_TEXT, /* -N */
725 OUTPUT_READONLY_TEXT, /* -n */
726 OUTPUT_DEMAND_PAGED /* -Z (default) */
727 };
728
729enum output_style output_style;
730
731#ifndef DEFAULT_OUTPUT_STYLE
732#define DEFAULT_OUTPUT_STYLE OUTPUT_DEMAND_PAGED
733#endif
734
735/* Descriptor for writing that file with `mywrite'. */
736
737int outdesc;
738
739/* The following are computed by `digest_symbols'. */
740
741int text_size; /* total size of text of all input files. */
742int text_header_size; /* size of the file header if included in the
743 text size. */
744int data_size; /* total size of data of all input files. */
745int bss_size; /* total size of bss of all input files. */
746int text_reloc_size; /* total size of text relocation of all input files. */
747int data_reloc_size; /* total size of data relocation of all input
748 files. */
749
750/* The following are computed by write_header(). */
751long int output_text_offset; /* file offset of the text section. */
752long int output_data_offset; /* file offset of the data section. */
753long int output_trel_offset; /* file offset of the text relocation info. */
754long int output_drel_offset; /* file offset of the data relocation info. */
755long int output_syms_offset; /* file offset of the symbol table. */
756long int output_strs_offset; /* file offset of the string table. */
757
758/* The following are incrementally computed by write_syms(); we keep
759 them here so we can examine their values afterwards. */
760unsigned int output_syms_size; /* total bytes of symbol table output. */
761unsigned int output_strs_size; /* total bytes of string table output. */
762
763/* This can only be computed after the size of the string table is known. */
764long int output_symseg_offset; /* file offset of the symbol segment (if any). */
765
766/* Incrementally computed by write_file_symseg(). */
767unsigned int output_symseg_size;
768
769/* Specifications of start and length of the area reserved at the end
770 of the text segment for the set vectors. Computed in 'digest_symbols' */
771int set_sect_start;
772int set_sect_size;
773
774/* Pointer for in core storage for the above vectors, before they are
775 written. */
776unsigned long *set_vectors;
777
778int *set_reloc;
779
780/* Amount of cleared space to leave at the end of the text segment. */
781
782int text_pad;
783
784/* Amount of padding between data segment and set vectors. */
785int set_sect_pad;
786
787/* Amount of padding at end of data segment. This has two parts:
788 That which is before the bss segment, and that which overlaps
789 with the bss segment. */
790int data_pad;
791
792/* Format of __.SYMDEF:
793 First, a longword containing the size of the 'symdef' data that follows.
794 Second, zero or more 'symdef' structures.
795 Third, a longword containing the length of symbol name strings.
796 Fourth, zero or more symbol name strings (each followed by a null). */
797
798struct symdef {
799 int symbol_name_string_index;
800 int library_member_offset;
801};
802
803
804/* Record most of the command options. */
805
806/* Address we assume the text section will be loaded at.
807 We relocate symbols and text and data for this, but we do not
808 write any padding in the output file for it. */
809int text_start;
810
811/* Address we decide the data section will be loaded at. */
812int data_start;
813
814/* Nonzero if -T was specified in the command line.
815 This prevents text_start from being set later to default values. */
816int T_flag_specified;
817
818/* Nonzero if -Tdata was specified in the command line.
819 This prevents data_start from being set later to default values. */
820int Tdata_flag_specified;
821
822/* Size to pad data section up to.
823 We simply increase the size of the data section, padding with zeros,
824 and reduce the size of the bss section to match. */
825int specified_data_size;
826
827/* Nonzero means print names of input files as processed. */
828int trace_files;
829
830/* Which symbols should be stripped (omitted from the output):
831 none, all, or debugger symbols. */
832enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
833
834/* Which local symbols should be omitted:
835 none, all, or those starting with L.
836 This is irrelevant if STRIP_NONE. */
837enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
838
839/* 1 => write load map. */
840int write_map;
841
842/* 1 => assign space to common symbols even if OUTPUT_RELOCATABLE. */
843int force_common_definition;
844
845/* Standard directories to search for files specified by -l. */
846char *standard_search_dirs[] = { "/usr/lib" };
847
848/* If set STANDARD_SEARCH_DIRS is not searched. */
849int no_standard_dirs;
850
851/* Actual vector of directories to search;
852 this contains those specified with -L plus the standard ones. */
853char **search_dirs;
854
855/* Length of the vector `search_dirs'. */
856int n_search_dirs;
857
858/* Non zero means to create the output executable.
859 Cleared by nonfatal errors. */
860int make_executable;
861
862/* Force the executable to be output, even if there are non-fatal
863 errors */
864int force_executable;
865
866/* Whether or not to include .dll in the shared library searching. */
867int opt_dll_search;
868
869/* Keep a list of any symbols referenced from the command line (so
870 that error messages for these guys can be generated). This list is
871 zero terminated. */
872struct glosym **cmdline_references;
873int cl_refs_allocated;
874
875void *xmalloc (size_t);
876void *xrealloc (void *, size_t);
877void usage (char *, char *);
878void fatal (char *, ...);
879void fatal_with_file (char *, struct file_entry *);
880void perror_name (char *);
881void perror_file (struct file_entry *);
882void error (char *, char *, char *, char *);
883
884int parse (char *, char *, char *);
885void initialize_text_start (void);
886void initialize_data_start (void);
887void digest_symbols (void);
888void print_symbols (FILE *);
889void load_symbols (void);
890void decode_command (int, char **);
891void write_output (void);
892void write_header (void);
893void write_text (void);
894void read_file_relocation (struct file_entry *);
895void write_data (void);
896void write_rel (void);
897void write_syms (void);
898void write_symsegs (void);
899void mywrite (void *, int, int, int);
900void symtab_init (void);
901void padfile (int, int);
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, "", NULL);
1395 p->local_sym_name = concat ("-l", optarg, "", NULL);
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 = (char *) 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 = (char *) 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 = (char *) 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;
3857
3858 if (exe_flag)
3859 {
3860 ext = _getext (output_filename);
3861 if ((ext != NULL) && (stricmp (ext, ".exe") == 0))
3862 {
3863 exe_filename = output_filename;
3864 exe_flag = 0;
3865 } else
3866 {
3867 touch_filename = output_filename;
3868 exe_filename = concat (output_filename, ".exe", NULL);
3869 }
3870 }
3871 else
3872 {
3873 ext = _getext2 (output_filename);
3874 if (stricmp (ext, ".dll") == 0)
3875 {
3876 reloc_flag = 1; dll_flag = 1;
3877 }
3878 else if (stricmp (ext, ".exe") != 0)
3879 {
3880 exe_filename = NULL;
3881 return;
3882 }
3883 exe_filename = output_filename;
3884 }
3885
3886 /* Create a temporary a.out executable file. */
3887
3888 output_filename = make_temp_file ("ldXXXXXX");
3889
3890 if (rsxnt_linked != EMX_DEFAULT && strip_symbols != STRIP_NONE) /* RSXNT */
3891 {
3892 strip_symbols = STRIP_NONE;
3893 emxbind_strip = 1;
3894 }
3895 else if (strip_symbols == STRIP_ALL)
3896 {
3897 strip_symbols = STRIP_DEBUGGER;
3898 emxbind_strip = 1;
3899 }
3900 unlink (exe_filename);
3901 if (touch_filename != NULL)
3902 unlink (touch_filename);
3903}
3904
3905/* Write the output file */
3906
3907void
3908write_output (void)
3909{
3910 struct stat statbuf;
3911 int filemode, mask;
3912
3913 /* Remove the old file in case it is owned by someone else.
3914 This prevents spurious "not owner" error messages.
3915 Don't check for errors from unlink; we don't really care
3916 whether it worked.
3917
3918 Note that this means that if the output file is hard linked,
3919 the other names will still have the old contents. This is
3920 the way Unix ld works; I'm going to consider it a feature. */
3921 (void) unlink (output_filename);
3922
3923 outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
3924 if (outdesc < 0) perror_name (output_filename);
3925
3926 if (fstat (outdesc, &statbuf) < 0)
3927 perror_name (output_filename);
3928
3929 filemode = statbuf.st_mode;
3930
3931 chmod (output_filename, filemode & ~0111);
3932
3933 if (reloc_flag)
3934 global_indirect_count = 0;
3935
3936 /* Calculate the offsets of the various pieces of the output file. */
3937 compute_section_offsets ();
3938
3939 /* Output the text and data segments, relocating as we go. */
3940 write_text ();
3941 write_data ();
3942
3943 /* Output the merged relocation info, if requested with `-r'. */
3944 if (output_style == OUTPUT_RELOCATABLE || reloc_flag)
3945 write_rel ();
3946
3947 /* Output the symbol table (both globals and locals). */
3948 write_syms ();
3949
3950 /* At this point the total size of the symbol table and string table
3951 are finalized. */
3952 compute_more_section_offsets ();
3953
3954 /* Copy any GDB symbol segments from input files. */
3955 write_symsegs ();
3956
3957 /* Now that everything is known about the output file, write its header. */
3958 write_header ();
3959
3960 close (outdesc);
3961
3962 mask = umask (0);
3963 umask (mask);
3964
3965 if (chmod (output_filename, filemode | (0111 & ~mask)) == -1)
3966 perror_name (output_filename);
3967
3968 if (rsxnt_linked == EMX_DEFAULT && exe_filename != NULL)
3969 {
3970 char *nargv[11];
3971 char *freeav[11];
3972 int i, j, saved_errno;
3973
3974 i = j = 0;
3975 nargv[i++] = "emxbind";
3976 nargv[i++] = "-bq";
3977 if (emxbind_strip)
3978 nargv[i++] = "-s";
3979 if (dll_flag && !def_filename)
3980 gen_deffile();
3981 if (def_filename != NULL)
3982 {
3983 freeav[j++] = nargv[i] = ALLOCA (strlen (def_filename) + 3);
3984 strcpy (nargv[i], "-d");
3985 strcat (nargv[i], def_filename);
3986 i++;
3987 }
3988 else if (dll_flag)
3989 nargv[i++] = "-d";
3990 if (stack_size != 0)
3991 {
3992 freeav[j++] = nargv[i] = ALLOCA (20);
3993 sprintf (nargv[i], "-k0x%x", stack_size);
3994 i++;
3995 }
3996 if (map_flag)
3997 {
3998 if (map_filename == NULL)
3999 {
4000 freeav[j++] = map_filename = ALLOCA (strlen (exe_filename) + 5);
4001 strcpy (map_filename, exe_filename);
4002 _remext (map_filename);
4003 strcat (map_filename, ".map");
4004 }
4005 freeav[j++] = nargv[i] = ALLOCA (strlen (map_filename) + 3);
4006 strcpy (nargv[i], "-m");
4007 strcat (nargv[i], map_filename);
4008 i++;
4009 }
4010 if (res_filename != NULL)
4011 {
4012 freeav[j++] = nargv[i] = ALLOCA (strlen (res_filename) + 3);
4013 strcpy (nargv[i], "-r");
4014 strcat (nargv[i], res_filename);
4015 i++;
4016 }
4017 nargv[i++] = "-o";
4018 nargv[i++] = exe_filename;
4019 nargv[i++] = output_filename;
4020 nargv[i] = NULL;
4021 if (trace_files)
4022 {
4023 fprintf(stderr, "Invoking emxbind:");
4024 for (i = 0; nargv[i]; i++)
4025 fprintf(stderr, " %s", nargv[i]);
4026 fprintf(stderr, "\n");
4027 }
4028 i = spawnvp (P_WAIT, "emxbind", nargv);
4029 saved_errno = errno; unlink (output_filename); errno = saved_errno;
4030 if (i < 0)
4031 perror_name ("emxbind");
4032 else if (i != 0)
4033 fatal ("emxbind failed\n", NULL);
4034 if (chmod (exe_filename, filemode | (0111 & ~mask)) == -1)
4035 perror_name (exe_filename);
4036 if (touch_filename != NULL)
4037 {
4038 char execname[512];
4039 _execname(execname, sizeof (execname));
4040 strcpy(_getname(execname), "ldstub.bin");
4041 /* Copy stub into file */
4042 if (DosCopy(execname, touch_filename, 4))
4043 {
4044 errno = EACCES;
4045 perror_name (execname);
4046 }
4047 /* Now touch it */
4048 if (utime(touch_filename, NULL))
4049 perror_name (touch_filename);
4050 }
4051 while (j-- > 0)
4052 FREEA (freeav[j]);
4053 }
4054 else if (exe_filename != NULL) /* RSXNT */
4055 {
4056 char *nargv[10];
4057 char *freea = NULL;
4058 int i, saved_errno;
4059
4060 i = 0;
4061 nargv[i++] = "ntbind";
4062 nargv[i++] = output_filename;
4063 nargv[i++] = "-o";
4064 nargv[i++] = exe_filename;
4065 nargv[i++] = "-s";
4066 if (rsxnt_linked == RSXNT_WIN32)
4067 nargv[i++] = (emxbind_strip) ? "dosstub.dos" : "dosstub.dbg";
4068 else
4069 {
4070 nargv[i++] = "dosstub.rsx";
4071 if (emxbind_strip)
4072 nargv[i++] = "-strip";
4073 }
4074 if (def_filename != NULL)
4075 {
4076 nargv[i++] = "-d";
4077 freea = nargv[i] = ALLOCA (strlen (def_filename) + 3);
4078 strcpy(nargv[i], def_filename);
4079 i++;
4080 }
4081 nargv[i] = NULL;
4082
4083 i = spawnvp (P_WAIT, "ntbind", nargv);
4084 saved_errno = errno; unlink (output_filename); errno = saved_errno;
4085 if (i < 0)
4086 perror_name ("ntbind");
4087 else if (i != 0)
4088 fatal ("ntbind failed\n", NULL);
4089 if (chmod (exe_filename, filemode | (0111 & ~mask)) == -1)
4090 perror_name (exe_filename);
4091 if (touch_filename != NULL)
4092 {
4093 i = open (touch_filename,
4094 O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
4095 if (i < 0)
4096 perror_name (touch_filename);
4097 close (i);
4098 }
4099 FREEA (freea);
4100 }
4101}
4102
4103
4104void copy_text (struct file_entry *entry);
4105void copy_data (struct file_entry *entry);
4106void perform_relocation ( char *data, int pc_relocation, int data_size,
4107 struct relocation_info *reloc_info, int reloc_size, struct file_entry *entry);
4108#ifdef DEBUG_BIRD
4109void dbg_dump_rel(struct file_entry *entry, struct relocation_info * rel,
4110 size_t reloc_size, const char *desc);
4111#endif
4112
4113/* Relocate the text segment of each input file
4114 and write to the output file. */
4115
4116void
4117write_text ()
4118{
4119 if (trace_files)
4120 fprintf (stderr, "Copying and relocating text:\n\n");
4121
4122 lseek (outdesc, output_text_offset + text_header_size, 0);
4123
4124 each_full_file (copy_text, 0);
4125 file_close ();
4126
4127 if (trace_files)
4128 fprintf (stderr, "\n");
4129
4130 padfile (text_pad, outdesc);
4131}
4132
4133/* Read in all of the relocation information */
4134
4135void
4136read_relocation (void)
4137{
4138 each_full_file (read_file_relocation, 0);
4139}
4140
4141/* Read in the relocation sections of ENTRY if necessary */
4142
4143void
4144read_file_relocation (entry)
4145 struct file_entry *entry;
4146{
4147 register struct relocation_info *reloc;
4148 int desc;
4149 int read_return;
4150
4151 desc = -1;
4152 if (!entry->textrel)
4153 {
4154 reloc = (struct relocation_info *) xmalloc (entry->text_reloc_size);
4155 desc = file_open (entry);
4156 lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
4157 if (entry->text_reloc_size != (read_return = read (desc, reloc, entry->text_reloc_size)))
4158 {
4159 fprintf (stderr, "Return from read: %d\n", read_return);
4160 fatal_with_file ("premature eof in text relocation of ", entry);
4161 }
4162 entry->textrel = reloc;
4163 }
4164
4165 if (!entry->datarel)
4166 {
4167 reloc = (struct relocation_info *) xmalloc (entry->data_reloc_size);
4168 if (desc == -1) desc = file_open (entry);
4169 lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
4170 if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
4171 fatal_with_file ("premature eof in data relocation of ", entry);
4172 entry->datarel = reloc;
4173 }
4174#ifdef DEBUG_BIRD
4175 dbg_dump_rel(entry, entry->textrel, entry->text_reloc_size, "text");
4176 dbg_dump_rel(entry, entry->datarel, entry->data_reloc_size, "data");
4177#endif
4178}
4179
4180/* Read the text segment contents of ENTRY, relocate them,
4181 and write the result to the output file.
4182 If `-r', save the text relocation for later reuse. */
4183
4184void
4185copy_text (entry)
4186 struct file_entry *entry;
4187{
4188 register char *bytes;
4189 register int desc;
4190 register struct relocation_info *reloc;
4191 int free_reloc = 0;
4192
4193 if (trace_files)
4194 prline_file_name (entry, stderr);
4195
4196 desc = file_open (entry);
4197
4198 /* Allocate space for the file's text section */
4199
4200 bytes = (char *) ALLOCA (entry->text_size);
4201
4202 /* Deal with relocation information however is appropriate */
4203
4204 if (entry->textrel) reloc = entry->textrel;
4205 else if (output_style == OUTPUT_RELOCATABLE || reloc_flag)
4206 {
4207 read_file_relocation (entry);
4208 reloc = entry->textrel;
4209 }
4210 else
4211 {
4212 free_reloc = 1;
4213 reloc = (struct relocation_info *) ALLOCA (entry->text_reloc_size);
4214 lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
4215 if (entry->text_reloc_size != read (desc, reloc, entry->text_reloc_size))
4216 fatal_with_file ("premature eof in text relocation of ", entry);
4217 }
4218
4219 /* Read the text section into core. */
4220
4221 lseek (desc, entry->starting_offset + entry->text_offset, L_SET);
4222 if (entry->text_size != read (desc, bytes, entry->text_size))
4223 fatal_with_file ("premature eof in text section of ", entry);
4224
4225 /* Relocate the text according to the text relocation. */
4226
4227 perform_relocation (bytes, entry->text_start_address - entry->orig_text_address,
4228 entry->text_size, reloc, entry->text_reloc_size, entry);
4229
4230 /* Write the relocated text to the output file. */
4231
4232 mywrite (bytes, 1, entry->text_size, outdesc);
4233
4234 FREEA (bytes);
4235 if (free_reloc)
4236 FREEA (reloc);
4237}
4238
4239#ifdef DEBUG_BIRD
4240void dbg_dump_rel(struct file_entry *entry, struct relocation_info * rel,
4241 size_t reloc_size, const char *desc)
4242{
4243 struct relocation_info *relend = (struct relocation_info *)((char*)rel + reloc_size);
4244 int i;
4245
4246 fprintf(stderr,
4247 "dbg: %s relocations %s:\n"
4248 "dbg: rel - Address len sym# attrs\n",
4249 desc, entry->filename);
4250 i = 0;
4251 while (rel < relend)
4252 {
4253 fprintf(stderr, "dbg: %3d - %08x 2^%d %06x %s%s",
4254 i,
4255 rel->r_address,
4256 rel->r_length,
4257 rel->r_symbolnum,
4258 rel->r_extern ? "Extrn " : " ",
4259 rel->r_pcrel ? "PCRel " : " "
4260 );
4261 if (rel->r_extern)
4262 { /* find the symbol. */
4263 struct nlist *s = &entry->symbols[rel->r_symbolnum];
4264 fprintf(stderr, " s.val:%08lx s.typ:%02x s.des:%04x s.oth:%02x",
4265 s->n_value,
4266 (unsigned)s->n_type,
4267 s->n_desc,
4268 (unsigned)s->n_other);
4269 if (s->n_un.n_strx < 0x20000)
4270 fprintf(stderr, " !!bad symbol ptr %p", s->n_un.n_name);
4271 else
4272 {
4273 struct glosym *sym = (struct glosym *)s->n_un.n_name;
4274 fprintf(stderr, " %s", sym->name);
4275 }
4276 }
4277 fprintf(stderr, "\n");
4278 /* next */
4279 i++;
4280 rel++;
4281 }
4282}
4283#endif
4284
4285
4286/* Relocate the data segment of each input file
4287 and write to the output file. */
4288
4289void
4290write_data ()
4291{
4292 if (trace_files)
4293 fprintf (stderr, "Copying and relocating data:\n\n");
4294
4295 lseek (outdesc, output_data_offset, 0);
4296
4297 each_full_file (copy_data, 0);
4298 file_close ();
4299
4300 /* Write out the set element vectors. See digest symbols for
4301 description of length of the set vector section. */
4302
4303 padfile (set_sect_pad, outdesc);
4304
4305 if (set_vector_count)
4306 mywrite (set_vectors, set_symbol_count + 2 * set_vector_count,
4307 sizeof (unsigned long), outdesc);
4308
4309 if (trace_files)
4310 fprintf (stderr, "\n");
4311
4312 padfile (data_pad, outdesc);
4313}
4314
4315/* Read the data segment contents of ENTRY, relocate them,
4316 and write the result to the output file.
4317 If `-r', save the data relocation for later reuse.
4318 See comments in `copy_text'. */
4319
4320void
4321copy_data (entry)
4322 struct file_entry *entry;
4323{
4324 register struct relocation_info *reloc;
4325 register char *bytes;
4326 register int desc;
4327 int free_reloc = 0;
4328
4329 if (trace_files)
4330 prline_file_name (entry, stderr);
4331
4332 desc = file_open (entry);
4333
4334 bytes = (char *) ALLOCA (entry->data_size);
4335
4336 if (entry->datarel) reloc = entry->datarel;
4337 else if (output_style == OUTPUT_RELOCATABLE || reloc_flag) /* Will need this again */
4338 {
4339 read_file_relocation (entry);
4340 reloc = entry->datarel;
4341 }
4342 else
4343 {
4344 free_reloc = 1;
4345 reloc = (struct relocation_info *) ALLOCA (entry->data_reloc_size);
4346 lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
4347 if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
4348 fatal_with_file ("premature eof in data relocation of ", entry);
4349 }
4350
4351 lseek (desc, entry->starting_offset + entry->data_offset, L_SET);
4352 if (entry->data_size != read (desc, bytes, entry->data_size))
4353 fatal_with_file ("premature eof in data section of ", entry);
4354
4355 perform_relocation (bytes, entry->data_start_address - entry->orig_data_address,
4356 entry->data_size, reloc, entry->data_reloc_size, entry);
4357
4358 mywrite (bytes, 1, entry->data_size, outdesc);
4359 padfile ((SECTION_ALIGN - entry->data_size) & SECTION_ALIGN_MASK, outdesc);
4360
4361 FREEA (bytes);
4362 if (free_reloc)
4363 FREEA (reloc);
4364}
4365
4366
4367/* Relocate ENTRY's text or data section contents.
4368 DATA is the address of the contents, in core.
4369 DATA_SIZE is the length of the contents.
4370 PC_RELOCATION is the difference between the address of the contents
4371 in the output file and its address in the input file.
4372 RELOC_INFO is the address of the relocation info, in core.
4373 RELOC_SIZE is its length in bytes. */
4374/* This version is about to be severly hacked by Randy. Hope it
4375 works afterwards. */
4376void
4377perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
4378 char *data;
4379 struct relocation_info *reloc_info;
4380 struct file_entry *entry;
4381 int pc_relocation;
4382 int data_size;
4383 int reloc_size;
4384{
4385 register struct relocation_info *p = reloc_info;
4386 struct relocation_info *end
4387 = reloc_info + reloc_size / sizeof (struct relocation_info);
4388 int text_relocation = entry->text_start_address - entry->orig_text_address;
4389 int data_relocation = entry->data_start_address - entry->orig_data_address;
4390 int bss_relocation = entry->bss_start_address - entry->orig_bss_address;
4391
4392 for (; p < end; p++)
4393 {
4394 register int relocation = 0;
4395 register int addr = RELOC_ADDRESS(p);
4396 register unsigned int mask = 0;
4397
4398 if (addr >= data_size)
4399 fatal_with_file ("relocation address out of range in ", entry);
4400
4401 if (RELOC_EXTERN_P(p))
4402 {
4403 int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
4404 symbol *sp = ((symbol *)
4405 (((struct nlist *)
4406 (((char *)entry->symbols) + symindex))
4407 ->n_un.n_name));
4408
4409#ifdef N_INDR
4410 /* Resolve indirection */
4411 if ((sp->defined & ~N_EXT) == N_INDR)
4412 sp = (symbol *) sp->value;
4413#endif
4414
4415 if (symindex >= entry->syms_size)
4416 fatal_with_file ("relocation symbolnum out of range in ", entry);
4417
4418 /* If the symbol is undefined, leave it at zero. */
4419 if (! sp->defined)
4420 relocation = 0;
4421 else
4422 relocation = sp->value;
4423 }
4424 else switch (RELOC_TYPE(p))
4425 {
4426 case N_TEXT:
4427 case N_TEXT | N_EXT:
4428 relocation = text_relocation;
4429 break;
4430
4431 case N_DATA:
4432 case N_DATA | N_EXT:
4433 relocation = data_relocation;
4434 break;
4435
4436 case N_BSS:
4437 case N_BSS | N_EXT:
4438 relocation = bss_relocation;
4439 break;
4440
4441 case N_ABS:
4442 case N_ABS | N_EXT:
4443 /* Don't know why this code would occur, but apparently it does. */
4444 break;
4445
4446 default:
4447 fatal_with_file ("nonexternal relocation code invalid in ", entry);
4448 }
4449
4450 if (RELOC_PCREL_P(p))
4451 relocation -= pc_relocation;
4452
4453#ifdef RELOC_ADD_EXTRA
4454 relocation += RELOC_ADD_EXTRA(p);
4455 if (output_style == OUTPUT_RELOCATABLE)
4456 {
4457 /* If this RELOC_ADD_EXTRA is 0, it means that the
4458 symbol was external and the relocation does not
4459 need a fixup here. */
4460 if (RELOC_ADD_EXTRA (p))
4461 {
4462 if (! RELOC_PCREL_P (p))
4463 RELOC_ADD_EXTRA (p) = relocation;
4464 else
4465 RELOC_ADD_EXTRA (p) -= pc_relocation;
4466 }
4467#if 0
4468 if (! RELOC_PCREL_P (p))
4469 {
4470 if ((int)p->r_type <= RELOC_32
4471 || RELOC_EXTERN_P (p) == 0)
4472 RELOC_ADD_EXTRA (p) = relocation;
4473 }
4474 else if (RELOC_EXTERN_P (p))
4475 RELOC_ADD_EXTRA (p) -= pc_relocation;
4476#endif
4477 continue;
4478 }
4479#endif
4480
4481 relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
4482
4483 /* Unshifted mask for relocation */
4484 mask = (1 << RELOC_TARGET_BITSIZE(p)) - 1;
4485 relocation &= mask;
4486
4487 /* Shift everything up to where it's going to be used */
4488 relocation <<= RELOC_TARGET_BITPOS(p);
4489 mask <<= RELOC_TARGET_BITPOS(p);
4490
4491 switch (RELOC_TARGET_SIZE(p))
4492 {
4493 case 0:
4494 if (RELOC_MEMORY_SUB_P(p))
4495 relocation -= mask & *(char *) (data + addr);
4496 else if (RELOC_MEMORY_ADD_P(p))
4497 relocation += mask & *(char *) (data + addr);
4498 *(char *) (data + addr) &= ~mask;
4499 *(char *) (data + addr) |= relocation;
4500 break;
4501
4502 case 1:
4503 if (RELOC_MEMORY_SUB_P(p))
4504 relocation -= mask & *(short *) (data + addr);
4505 else if (RELOC_MEMORY_ADD_P(p))
4506 relocation += mask & *(short *) (data + addr);
4507 *(short *) (data + addr) &= ~mask;
4508 *(short *) (data + addr) |= relocation;
4509 break;
4510
4511 case 2:
4512#ifdef CROSS_LINKER
4513 /* This is necessary if the host has stricter alignment
4514 than the target. Too slow to use all the time.
4515 Also doesn't deal with differing byte-order. */
4516 {
4517 /* Thing to relocate. */
4518 long thing;
4519 bcopy (data + addr, &thing, sizeof (thing));
4520 if (RELOC_MEMORY_SUB_P (p))
4521 relocation -= mask & thing;
4522 else if (RELOC_MEMORY_ADD_P (p))
4523 relocation += mask & thing;
4524 thing = (thing & ~mask) | relocation;
4525 bcopy (&thing, data + addr, sizeof (thing));
4526 }
4527#else /* not CROSS_LINKER */
4528 if (RELOC_MEMORY_SUB_P(p))
4529 relocation -= mask & *(long *) (data + addr);
4530 else if (RELOC_MEMORY_ADD_P(p))
4531 relocation += mask & *(long *) (data + addr);
4532 *(long *) (data + addr) &= ~mask;
4533 *(long *) (data + addr) |= relocation;
4534#endif /* not CROSS_LINKER */
4535 break;
4536
4537 default:
4538 fatal_with_file ("Unimplemented relocation field length in ", entry);
4539 }
4540 }
4541}
4542
4543
4544/* For OUTPUT_RELOCATABLE only: write out the relocation,
4545 relocating the addresses-to-be-relocated. */
4546
4547void coptxtrel (struct file_entry *entry);
4548void copdatrel (struct file_entry *entry);
4549
4550void
4551write_rel ()
4552{
4553 register int i;
4554 register int count = 0;
4555
4556 if (trace_files)
4557 fprintf (stderr, "Writing text relocation:\n\n");
4558
4559 /* Assign each global symbol a sequence number, giving the order
4560 in which `write_syms' will write it.
4561 This is so we can store the proper symbolnum fields
4562 in relocation entries we write. */
4563
4564 for (i = 0; i < TABSIZE; i++)
4565 {
4566 symbol *sp;
4567 for (sp = symtab[i]; sp; sp = sp->link)
4568 if (sp->referenced || sp->defined)
4569 {
4570 sp->def_count = count++;
4571 /* Leave room for the reference required by N_INDR, if
4572 necessary. */
4573 if ((sp->defined & ~N_EXT) == N_INDR)
4574 if (!reloc_flag)
4575 count++;
4576 }
4577 }
4578 /* Correct, because if (OUTPUT_RELOCATABLE), we will also be writing
4579 whatever indirect blocks we have. */
4580 if (count != defined_global_sym_count
4581 + undefined_global_sym_count + global_indirect_count)
4582 fatal ("internal error");
4583
4584 /* Write out the relocations of all files, remembered from copy_text. */
4585
4586 lseek (outdesc, output_trel_offset, 0);
4587 each_full_file (coptxtrel, 0);
4588
4589 if (trace_files)
4590 fprintf (stderr, "\nWriting data relocation:\n\n");
4591
4592 lseek (outdesc, output_drel_offset, 0);
4593 each_full_file (copdatrel, 0);
4594 if (reloc_flag)
4595 {
4596 int i;
4597 int n = set_sect_size / sizeof (unsigned long);
4598 struct relocation_info reloc;
4599
4600 memset (&reloc, 0, sizeof (reloc));
4601 RELOC_PCREL_P (&reloc) = 0;
4602 RELOC_TARGET_SIZE (&reloc) = 2;
4603 RELOC_EXTERN_P (&reloc) = 0;
4604 for (i = 0; i < n; ++i)
4605 switch (set_reloc[i] & ~N_EXT)
4606 {
4607 case N_TEXT:
4608 case N_DATA:
4609 RELOC_SYMBOL (&reloc) = set_reloc[i] & ~N_EXT;
4610 RELOC_ADDRESS (&reloc)
4611 = set_sect_start + i * sizeof (unsigned long) - data_start;
4612 mywrite (&reloc, sizeof (reloc), 1, outdesc);
4613 break;
4614 case N_ABS:
4615 break;
4616 default:
4617 fatal ("N_SETB not supported", (char *)0);
4618 }
4619 }
4620
4621 if (trace_files)
4622 fprintf (stderr, "\n");
4623}
4624
4625void
4626coptxtrel (entry)
4627 struct file_entry *entry;
4628{
4629 register struct relocation_info *p, *end;
4630 register int reloc = entry->text_start_address - text_start;
4631
4632 p = entry->textrel;
4633 end = (struct relocation_info *) (entry->text_reloc_size + (char *) p);
4634 while (p < end)
4635 {
4636 RELOC_ADDRESS(p) += reloc;
4637 if (RELOC_EXTERN_P(p))
4638 {
4639 register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
4640 symbol *symptr = ((symbol *)
4641 (((struct nlist *)
4642 (((char *)entry->symbols) + symindex))
4643 ->n_un.n_name));
4644
4645 if (symindex >= entry->syms_size)
4646 fatal_with_file ("relocation symbolnum out of range in ", entry);
4647
4648#ifdef N_INDR
4649 /* Resolve indirection. */
4650 if ((symptr->defined & ~N_EXT) == N_INDR)
4651 symptr = (symbol *) symptr->value;
4652#endif
4653
4654 /* If the symbol is now defined, change the external relocation
4655 to an internal one. */
4656
4657 if (symptr->defined && symptr->defined != (N_IMP1 | N_EXT))
4658 {
4659 RELOC_EXTERN_P(p) = 0;
4660 RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
4661 if (RELOC_SYMBOL (p) == N_SETV)
4662 RELOC_SYMBOL (p) = N_DATA;
4663#ifdef RELOC_ADD_EXTRA
4664 /* If we aren't going to be adding in the value in
4665 memory on the next pass of the loader, then we need
4666 to add it in from the relocation entry. Otherwise
4667 the work we did in this pass is lost. */
4668 if (!RELOC_MEMORY_ADD_P(p))
4669 RELOC_ADD_EXTRA (p) += symptr->value;
4670#endif
4671 }
4672 else
4673 /* Debugger symbols come first, so have to start this
4674 after them. */
4675 RELOC_SYMBOL(p) = (symptr->def_count + nsyms
4676 - defined_global_sym_count
4677 - undefined_global_sym_count
4678 - global_indirect_count);
4679 }
4680 p++;
4681 }
4682
4683 mywrite (entry->textrel, 1, entry->text_reloc_size, outdesc);
4684}
4685
4686void
4687copdatrel (entry)
4688 struct file_entry *entry;
4689{
4690 register struct relocation_info *p, *end;
4691 /* Relocate the address of the relocation.
4692 Old address is relative to start of the input file's data section.
4693 New address is relative to start of the output file's data section.
4694
4695 So the amount we need to relocate it by is the offset of this
4696 input file's data section within the output file's data section. */
4697 register int reloc = entry->data_start_address - data_start;
4698
4699 p = entry->datarel;
4700 end = (struct relocation_info *) (entry->data_reloc_size + (char *) p);
4701 while (p < end)
4702 {
4703 RELOC_ADDRESS(p) += reloc;
4704 if (RELOC_EXTERN_P(p))
4705 {
4706 register int symindex = RELOC_SYMBOL(p);
4707 symbol *symptr = (symbol *)(entry->symbols [symindex].n_un.n_name);
4708 int symtype;
4709
4710 if (symindex >= (entry->syms_size / sizeof (struct nlist)))
4711 fatal_with_file ("relocation symbolnum out of range in ", entry);
4712
4713#ifdef N_INDR
4714 /* Resolve indirection. */
4715 if ((symptr->defined & ~N_EXT) == N_INDR)
4716 symptr = (symbol *) symptr->value;
4717#endif
4718
4719 symtype = symptr->defined & ~N_EXT;
4720
4721 if (force_common_definition
4722 || (reloc_flag && symtype != N_IMP1)
4723 || symtype == N_DATA || symtype == N_TEXT
4724 || symtype == N_ABS || symtype == N_BSS)
4725 {
4726 if (symtype == N_SETV)
4727 symtype = N_DATA;
4728 RELOC_EXTERN_P(p) = 0;
4729 RELOC_SYMBOL(p) = symtype;
4730 }
4731 else
4732 /* Debugger symbols come first, so have to start this
4733 after them. */
4734 RELOC_SYMBOL(p) = (symptr->def_count
4735 + nsyms - defined_global_sym_count
4736 - undefined_global_sym_count
4737 - global_indirect_count);
4738
4739#if 0
4740 if ((symtype = symptr->defined) != (N_IMP1 | N_EXT))
4741 symtype = symptr->defined & ~N_EXT;
4742
4743 if ((force_common_definition || reloc_flag)
4744 && (symtype != (N_IMP1 | N_EXT)))
4745 {
4746 if (force_common_definition
4747 || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
4748 {
4749 if (symtype == N_SETV)
4750 symtype = N_DATA;
4751 RELOC_EXTERN_P(p) = 0;
4752 RELOC_SYMBOL(p) = symtype;
4753 }
4754 else
4755 /* Debugger symbols come first, so have to start this
4756 after them. */
4757 RELOC_SYMBOL(p) = (symptr->def_count
4758 + nsyms - defined_global_sym_count
4759 - undefined_global_sym_count
4760 - global_indirect_count);
4761 }
4762#endif
4763 }
4764 p++;
4765 }
4766
4767 mywrite (entry->datarel, 1, entry->data_reloc_size, outdesc);
4768}
4769
4770
4771void write_file_syms (struct file_entry *entry, int *syms_written_addr);
4772void write_string_table (void);
4773
4774/* Total size of string table strings allocated so far,
4775 including strings in `strtab_vector'. */
4776int strtab_size;
4777
4778/* Vector whose elements are strings to be added to the string table. */
4779char **strtab_vector;
4780
4781/* Vector whose elements are the lengths of those strings. */
4782int *strtab_lens;
4783
4784/* Index in `strtab_vector' at which the next string will be stored. */
4785int strtab_index;
4786
4787/* Add the string NAME to the output file string table.
4788 Record it in `strtab_vector' to be output later.
4789 Return the index within the string table that this string will have. */
4790
4791int
4792assign_string_table_index (name)
4793 char *name;
4794{
4795 register int index = strtab_size;
4796 register int len = strlen (name) + 1;
4797
4798 strtab_size += len;
4799 strtab_vector[strtab_index] = name;
4800 strtab_lens[strtab_index++] = len;
4801
4802 return index;
4803}
4804
4805FILE *outstream = (FILE *) 0;
4806
4807/* Write the contents of `strtab_vector' into the string table.
4808 This is done once for each file's local&debugger symbols
4809 and once for the global symbols. */
4810
4811void
4812write_string_table (void)
4813{
4814 register int i;
4815
4816 lseek (outdesc, output_strs_offset + output_strs_size, 0);
4817
4818 if (!outstream)
4819 outstream = fdopen (outdesc, "wb");
4820
4821 for (i = 0; i < strtab_index; i++)
4822 {
4823 fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
4824 output_strs_size += strtab_lens[i];
4825 }
4826
4827 fflush (outstream);
4828
4829 /* Report I/O error such as disk full. */
4830 if (ferror (outstream))
4831 perror_name (output_filename);
4832}
4833
4834
4835/* Write the symbol table and string table of the output file. */
4836
4837void
4838write_syms ()
4839{
4840 /* Number of symbols written so far. */
4841 int syms_written = 0;
4842 register int i;
4843 register symbol *sp;
4844
4845 /* Buffer big enough for all the global symbols. One
4846 extra struct for each indirect symbol to hold the extra reference
4847 following. */
4848 struct nlist *buf = (struct nlist *) ALLOCA ((defined_global_sym_count
4849 + undefined_global_sym_count
4850 + global_indirect_count)
4851 * sizeof (struct nlist));
4852 /* Pointer for storing into BUF. */
4853 register struct nlist *bufp = buf;
4854
4855 /* Size of string table includes the bytes that store the size. */
4856 strtab_size = sizeof strtab_size;
4857
4858 output_syms_size = 0;
4859 output_strs_size = strtab_size;
4860
4861 if (strip_symbols == STRIP_ALL)
4862 return;
4863
4864 /* Write the local symbols defined by the various files. */
4865
4866 each_file (write_file_syms, (int)&syms_written);
4867 file_close ();
4868
4869 /* Now write out the global symbols. */
4870
4871 /* Allocate two vectors that record the data to generate the string
4872 table from the global symbols written so far. This must include
4873 extra space for the references following indirect outputs. */
4874
4875 strtab_vector = (char **) ALLOCA ((num_hash_tab_syms
4876 + global_indirect_count) * sizeof (char *));
4877 strtab_lens = (int *) ALLOCA ((num_hash_tab_syms
4878 + global_indirect_count) * sizeof (int));
4879 strtab_index = 0;
4880
4881 /* Scan the symbol hash table, bucket by bucket. */
4882
4883 for (i = 0; i < TABSIZE; i++)
4884 for (sp = symtab[i]; sp; sp = sp->link)
4885 {
4886 struct nlist nl;
4887
4888#ifdef N_SECT
4889 nl.n_sect = 0;
4890#else
4891 nl.n_other = 0;
4892#endif
4893 nl.n_desc = 0;
4894
4895 /* Compute a `struct nlist' for the symbol. */
4896
4897 if (sp->defined || sp->referenced)
4898 {
4899 /* common condition needs to be before undefined condition */
4900 /* because unallocated commons are set undefined in */
4901 /* digest_symbols */
4902 if (sp->defined > 1) /* defined with known type */
4903 {
4904 /* If the target of an indirect symbol has been
4905 defined and we are outputting an executable,
4906 resolve the indirection; it's no longer needed */
4907 if (output_style != OUTPUT_RELOCATABLE
4908 && ((sp->defined & ~N_EXT) == N_INDR)
4909 && (((symbol *) sp->value)->defined > 1))
4910 {
4911 symbol *newsp = (symbol *) sp->value;
4912 nl.n_type = newsp->defined;
4913 nl.n_value = newsp->value;
4914 }
4915 else
4916 {
4917 nl.n_type = sp->defined;
4918 if (sp->defined != (N_INDR | N_EXT))
4919 nl.n_value = sp->value;
4920 else
4921 nl.n_value = 0;
4922 }
4923 }
4924 else if (sp->max_common_size) /* defined as common but not allocated. */
4925 {
4926 /* happens only with -r and not -d */
4927 /* write out a common definition */
4928 nl.n_type = N_UNDF | N_EXT;
4929 nl.n_value = sp->max_common_size;
4930 }
4931 else if (!sp->defined && sp->weak)
4932 {
4933 nl.n_type = sp->weak;
4934 nl.n_value = 0;
4935 }
4936 else if (!sp->defined) /* undefined -- legit only if -r */
4937 {
4938 nl.n_type = N_UNDF | N_EXT;
4939 nl.n_value = 0;
4940 }
4941 else
4942 fatal ("internal error: %s defined in mysterious way", sp->name);
4943
4944 /* Allocate string table space for the symbol name. */
4945
4946 nl.n_un.n_strx = assign_string_table_index (sp->name);
4947
4948 /* Output to the buffer and count it. */
4949
4950 *bufp++ = nl;
4951 syms_written++;
4952 if (nl.n_type == (N_INDR | N_EXT))
4953 {
4954 struct nlist xtra_ref;
4955 xtra_ref.n_type = N_EXT | N_UNDF;
4956 xtra_ref.n_un.n_strx
4957 = assign_string_table_index (((symbol *) sp->value)->name);
4958#ifdef N_SECT
4959 xtra_ref.n_sect = 0;
4960#else
4961 xtra_ref.n_other = 0;
4962#endif
4963 xtra_ref.n_desc = 0;
4964 xtra_ref.n_value = 0;
4965 *bufp++ = xtra_ref;
4966 syms_written++;
4967 }
4968 }
4969 }
4970
4971 /* Output the buffer full of `struct nlist's. */
4972
4973 lseek (outdesc, output_syms_offset + output_syms_size, 0);
4974 mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
4975 output_syms_size += sizeof (struct nlist) * (bufp - buf);
4976
4977 if (syms_written != nsyms)
4978 fatal ("internal error: wrong number of symbols written into output file", 0);
4979
4980 /* Now the total string table size is known, so write it into the
4981 first word of the string table. */
4982
4983 lseek (outdesc, output_strs_offset, 0);
4984 mywrite (&strtab_size, sizeof (int), 1, outdesc);
4985
4986 /* Write the strings for the global symbols. */
4987
4988 write_string_table ();
4989 FREEA (strtab_vector);
4990 FREEA (strtab_lens);
4991 FREEA (buf);
4992}
4993
4994
4995/* Write the local and debugger symbols of file ENTRY.
4996 Increment *SYMS_WRITTEN_ADDR for each symbol that is written. */
4997
4998/* Note that we do not combine identical names of local symbols.
4999 dbx or gdb would be confused if we did that. */
5000
5001void
5002write_file_syms (entry, syms_written_addr)
5003 struct file_entry *entry;
5004 int *syms_written_addr;
5005{
5006 register struct nlist *p = entry->symbols;
5007 register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
5008
5009 /* Buffer to accumulate all the syms before writing them.
5010 It has one extra slot for the local symbol we generate here. */
5011 struct nlist *buf
5012 = (struct nlist *) ALLOCA (entry->syms_size + sizeof (struct nlist));
5013 register struct nlist *bufp = buf;
5014
5015 /* Upper bound on number of syms to be written here. */
5016 int max_syms = (entry->syms_size / sizeof (struct nlist)) + 1;
5017
5018 /* Make tables that record, for each symbol, its name and its name's length.
5019 The elements are filled in by `assign_string_table_index'. */
5020
5021 strtab_vector = (char **) ALLOCA (max_syms * sizeof (char *));
5022 strtab_lens = (int *) ALLOCA (max_syms * sizeof (int));
5023 strtab_index = 0;
5024
5025 /* Generate a local symbol for the start of this file's text. */
5026
5027 if (discard_locals != DISCARD_ALL)
5028 {
5029 struct nlist nl;
5030
5031 nl.n_type = N_TEXT;
5032#ifdef EMX /* fix GCC/ld/GDB problem */
5033 {
5034 char *tmp;
5035 int len;
5036
5037 tmp = entry->local_sym_name;
5038 len = strlen (tmp);
5039 if (strncmp (tmp, "-l", 2) != 0
5040 && (len < 2 || strcmp (tmp+len-2, ".o") != 0))
5041 tmp = concat (tmp, ".o", NULL); /* Needed by GDB */
5042 nl.n_un.n_strx = assign_string_table_index (tmp);
5043 }
5044#else /* !EMX */
5045 nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
5046#endif /* !EMX */
5047 nl.n_value = entry->text_start_address;
5048 nl.n_desc = 0;
5049#ifdef N_SECT
5050 nl.n_sect = 0;
5051#else
5052 nl.n_other = 0;
5053#endif
5054 *bufp++ = nl;
5055 (*syms_written_addr)++;
5056 entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
5057 }
5058
5059 /* Read the file's string table. */
5060
5061 entry->strings = (char *) ALLOCA (entry->strs_size);
5062 read_entry_strings (file_open (entry), entry);
5063
5064 for (; p < end; p++)
5065 {
5066 register int type = p->n_type;
5067 register int write = 0;
5068
5069 /* WRITE gets 1 for a non-global symbol that should be written. */
5070
5071 if (SET_ELEMENT_P (type)) /* This occurs even if global. These */
5072 /* types of symbols are never written */
5073 /* globally, though they are stored */
5074 /* globally. */
5075 write = output_style == OUTPUT_RELOCATABLE;
5076 else if (WEAK_SYMBOL (type))
5077 ;
5078 else if (!(type & (N_STAB | N_EXT)))
5079 /* ordinary local symbol */
5080 write = ((discard_locals != DISCARD_ALL)
5081 && !(discard_locals == DISCARD_L &&
5082 (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
5083 && type != N_WARNING);
5084 else if (!(type & N_EXT))
5085 /* debugger symbol */
5086 write = (strip_symbols == STRIP_NONE);
5087
5088 if (write)
5089 {
5090 /* If this symbol has a name,
5091 allocate space for it in the output string table. */
5092
5093 if (p->n_un.n_strx)
5094 p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
5095 + entry->strings);
5096
5097 /* Output this symbol to the buffer and count it. */
5098
5099 *bufp++ = *p;
5100 (*syms_written_addr)++;
5101 }
5102 }
5103
5104 /* All the symbols are now in BUF; write them. */
5105
5106 lseek (outdesc, output_syms_offset + output_syms_size, 0);
5107 mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
5108 output_syms_size += sizeof (struct nlist) * (bufp - buf);
5109
5110 /* Write the string-table data for the symbols just written,
5111 using the data in vectors `strtab_vector' and `strtab_lens'. */
5112
5113 write_string_table ();
5114 FREEA (entry->strings);
5115 FREEA (strtab_vector);
5116 FREEA (strtab_lens);
5117 FREEA (buf);
5118}
5119
5120
5121/* Copy any GDB symbol segments from the input files to the output file.
5122 The contents of the symbol segment is copied without change
5123 except that we store some information into the beginning of it. */
5124
5125void write_file_symseg (struct file_entry *entry);
5126
5127void
5128write_symsegs ()
5129{
5130 lseek (outdesc, output_symseg_offset, 0);
5131 each_file (write_file_symseg, 0);
5132}
5133
5134void
5135write_file_symseg (entry)
5136 struct file_entry *entry;
5137{
5138 char buffer[4096];
5139 struct symbol_root root;
5140 int indesc, len, total;
5141
5142 if (entry->symseg_size == 0)
5143 return;
5144
5145 output_symseg_size += entry->symseg_size;
5146
5147 /* This entry has a symbol segment. Read the root of the segment. */
5148
5149 indesc = file_open (entry);
5150 lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
5151 if (sizeof root != read (indesc, &root, sizeof root))
5152 fatal_with_file ("premature end of file in symbol segment of ", entry);
5153
5154 /* Store some relocation info into the root. */
5155
5156 root.ldsymoff = entry->local_syms_offset;
5157 root.textrel = entry->text_start_address - entry->orig_text_address;
5158 root.datarel = entry->data_start_address - entry->orig_data_address;
5159 root.bssrel = entry->bss_start_address - entry->orig_bss_address;
5160 root.databeg = entry->data_start_address - root.datarel;
5161 root.bssbeg = entry->bss_start_address - root.bssrel;
5162
5163 /* Write the modified root into the output file. */
5164
5165 mywrite (&root, sizeof root, 1, outdesc);
5166
5167 /* Copy the rest of the symbol segment unchanged. */
5168
5169 total = entry->symseg_size - sizeof root;
5170
5171 while (total > 0)
5172 {
5173 len = read (indesc, buffer, min (sizeof buffer, total));
5174
5175 if (len != min (sizeof buffer, total))
5176 fatal_with_file ("premature end of file in symbol segment of ", entry);
5177 total -= len;
5178 mywrite (buffer, len, 1, outdesc);
5179 }
5180
5181 file_close ();
5182}
5183
5184
5185/* Define a special symbol (etext, edata, or end). NAME is the
5186 name of the symbol, with a leading underscore (whether or not this
5187 system uses such underscores). TYPE is its type (e.g. N_DATA | N_EXT).
5188 Store a symbol * for the symbol in *SYM if SYM is non-NULL. */
5189static void
5190symbol_define (name, type, sym)
5191 /* const */ char *name;
5192 int type;
5193 symbol **sym;
5194{
5195 symbol *thesym;
5196
5197#if defined(nounderscore)
5198 /* Skip the leading underscore. */
5199 name++;
5200#endif
5201
5202 thesym = getsym (name);
5203 if (thesym->defined)
5204 {
5205 /* The symbol is defined in some input file. Don't mess with it. */
5206 if (sym)
5207 *sym = 0;
5208 }
5209 else
5210 {
5211 if (thesym->referenced)
5212 /* The symbol was not defined, and we are defining it now. */
5213 undefined_global_sym_count--;
5214 thesym->defined = type;
5215 thesym->referenced = 1;
5216 if (sym)
5217 *sym = thesym;
5218 }
5219}
5220
5221/* Create the symbol table entries for `etext', `edata' and `end'. */
5222
5223void
5224symtab_init ()
5225{
5226 symbol_define ("_edata", N_DATA | N_EXT, &edata_symbol);
5227 symbol_define ("_etext", N_TEXT | N_EXT, &etext_symbol);
5228 symbol_define ("_end", N_BSS | N_EXT, &end_symbol);
5229
5230 /* Either _edata or __edata (C names) is OK as far as ANSI is concerned
5231 (see section 4.1.2.1). In general, it is best to use __foo and
5232 not worry about the confusing rules for the _foo namespace.
5233 But HPUX 7.0 uses _edata, so we might as weel be consistent. */
5234 symbol_define ("__edata", N_DATA | N_EXT, &edata_symbol_alt);
5235 symbol_define ("__etext", N_TEXT | N_EXT, &etext_symbol_alt);
5236 symbol_define ("__end", N_BSS | N_EXT, &end_symbol_alt);
5237}
5238
5239/* Compute the hash code for symbol name KEY. */
5240
5241int
5242hash_string (key)
5243 char *key;
5244{
5245 register char *cp;
5246 register int k;
5247
5248 cp = key;
5249 k = 0;
5250 while (*cp)
5251 k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
5252
5253 return k;
5254}
5255
5256
5257/* Get the symbol table entry for the global symbol named KEY.
5258 Create one if there is none. */
5259
5260symbol *
5261getsym (key)
5262 char *key;
5263{
5264 register int hashval;
5265 register symbol *bp;
5266
5267 /* Determine the proper bucket. */
5268
5269 hashval = hash_string (key) % TABSIZE;
5270
5271 /* Search the bucket. */
5272
5273 for (bp = symtab[hashval]; bp; bp = bp->link)
5274 if (! strcmp (key, bp->name))
5275 return bp;
5276
5277 /* Nothing was found; create a new symbol table entry. */
5278
5279 bp = (symbol *) xmalloc (sizeof (symbol));
5280 bp->refs = 0;
5281 bp->name = (char *) xmalloc (strlen (key) + 1);
5282 strcpy (bp->name, key);
5283 bp->defined = 0;
5284 bp->referenced = 0;
5285 bp->trace = 0;
5286 bp->value = 0;
5287 bp->max_common_size = 0;
5288 bp->warning = 0;
5289 bp->undef_refs = 0;
5290 bp->multiply_defined = 0;
5291 bp->weak = 0;
5292
5293 /* Add the entry to the bucket. */
5294
5295 bp->link = symtab[hashval];
5296 symtab[hashval] = bp;
5297
5298 ++num_hash_tab_syms;
5299
5300 return bp;
5301}
5302
5303/* Like `getsym' but return 0 if the symbol is not already known. */
5304
5305symbol *
5306getsym_soft (key)
5307 char *key;
5308{
5309 register int hashval;
5310 register symbol *bp;
5311
5312 /* Determine which bucket. */
5313
5314 hashval = hash_string (key) % TABSIZE;
5315
5316 /* Search the bucket. */
5317
5318 for (bp = symtab[hashval]; bp; bp = bp->link)
5319 if (! strcmp (key, bp->name))
5320 return bp;
5321
5322 return 0;
5323}
5324
5325
5326/* Report a usage error.
5327 Like fatal except prints a usage summary. */
5328
5329void
5330usage (string, arg)
5331 char *string, *arg;
5332{
5333 if (string)
5334 {
5335 fprintf (stderr, "%s: ", progname);
5336 fprintf (stderr, string, arg);
5337 fprintf (stderr, "\n");
5338 }
5339 fprintf (stderr, "\
5340Usage: %s [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
5341 [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
5342 [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
5343 [-S] [-T[{text,data}] addr] [-V prefix] [-X] [-Zdll-search]\n\
5344 [file...]\n", progname);
5345 exit (1);
5346}
5347
5348/* Report a fatal error.
5349 STRING is a printf format string and ARG is one arg for it. */
5350
5351void fatal (char *string, ...)
5352{
5353 va_list args;
5354 fprintf (stderr, "%s: ", progname);
5355 va_start (args, string);
5356 vfprintf (stderr, string, args);
5357 va_end (args);
5358 fprintf (stderr, "\n");
5359 exit (1);
5360}
5361
5362/* Report a fatal error. The error message is STRING
5363 followed by the filename of ENTRY. */
5364
5365void
5366fatal_with_file (string, entry)
5367 char *string;
5368 struct file_entry *entry;
5369{
5370 fprintf (stderr, "%s: ", progname);
5371 fprintf (stderr, string);
5372 print_file_name (entry, stderr);
5373 fprintf (stderr, "\n");
5374 exit (1);
5375}
5376
5377/* Report a fatal error using the message for the last failed system call,
5378 followed by the string NAME. */
5379
5380void
5381perror_name (name)
5382 char *name;
5383{
5384 char *s;
5385
5386 if (errno < sys_nerr)
5387 s = concat ("", sys_errlist[errno], " for %s", NULL);
5388 else
5389 s = "cannot open %s";
5390 fatal (s, name);
5391}
5392
5393/* Report a fatal error using the message for the last failed system call,
5394 followed by the name of file ENTRY. */
5395
5396void
5397perror_file (entry)
5398 struct file_entry *entry;
5399{
5400 char *s;
5401
5402 if (errno < sys_nerr)
5403 s = concat ("", sys_errlist[errno], " for ", NULL);
5404 else
5405 s = "cannot open ";
5406 fatal_with_file (s, entry);
5407}
5408
5409/* Report a nonfatal error.
5410 STRING is a format for printf, and ARG1 ... ARG3 are args for it. */
5411
5412void
5413error (string, arg1, arg2, arg3)
5414 char *string, *arg1, *arg2, *arg3;
5415{
5416 fprintf (stderr, "%s: ", progname);
5417 fprintf (stderr, string, arg1, arg2, arg3);
5418 fprintf (stderr, "\n");
5419}
5420
5421
5422
5423/* Output COUNT*ELTSIZE bytes of data at BUF
5424 to the descriptor DESC. */
5425
5426void
5427mywrite (buf, count, eltsize, desc)
5428 void *buf;
5429 int count;
5430 int eltsize;
5431 int desc;
5432{
5433 register int val;
5434 register int bytes = count * eltsize;
5435
5436 while (bytes > 0)
5437 {
5438 val = write (desc, buf, bytes);
5439 if (val <= 0)
5440 perror_name (output_filename);
5441 buf = (char*)buf + val;
5442 bytes -= val;
5443 }
5444}
5445
5446/* Output PADDING zero-bytes to descriptor OUTDESC.
5447 PADDING may be negative; in that case, do nothing. */
5448
5449void
5450padfile (padding, outdesc)
5451 int padding;
5452 int outdesc;
5453{
5454 register char *buf;
5455 if (padding <= 0)
5456 return;
5457
5458 buf = (char *) ALLOCA (padding);
5459 bzero (buf, padding);
5460 mywrite (buf, padding, 1, outdesc);
5461 FREEA (buf);
5462}
5463
5464/* Parse the string ARG using scanf format FORMAT, and return the result.
5465 If it does not parse, report fatal error
5466 generating the error message using format string ERROR and ARG as arg. */
5467
5468int
5469parse (arg, format, error)
5470 char *arg, *format, *error;
5471{
5472 int x;
5473 if (1 != sscanf (arg, format, &x))
5474 fatal (error, arg);
5475 return x;
5476}
5477
5478/* Like malloc but get fatal error if memory is exhausted. */
5479
5480void *
5481xmalloc (size)
5482 size_t size;
5483{
5484 register char *result = malloc (size);
5485 if (!result)
5486 fatal ("virtual memory exhausted", 0);
5487 return result;
5488}
5489
5490/* Like realloc but get fatal error if memory is exhausted. */
5491
5492void *
5493xrealloc (ptr, size)
5494 void *ptr;
5495 size_t size;
5496{
5497 register char *result = realloc (ptr, size);
5498 if (!result)
5499 fatal ("virtual memory exhausted", 0);
5500 return result;
5501}
5502
5503
5504char *my_cplus_demangle (const char *mangled)
5505{
5506 if (*mangled == '_')
5507 ++mangled;
5508 return cplus_demangle (mangled, demangle_options);
5509}
5510
5511
5512
5513/**
5514 * Generates an unique temporary file.
5515 *
5516 * @returns 0 on success.
5517 * @returns -1 on failure.
5518 * @param pszFile Where to put the filename.
5519 * @param pszPrefix Prefix.
5520 * @param pszSuffix Suffix.
5521 * @remark The code is nicked from the weak linker.
5522 * @remark sorry about the convention here, this is borrowed from elsewhere.
5523 */
5524static int make_tempfile(char *pszFile, const char *pszPrefix, const char *pszSuffix)
5525{
5526 struct stat s;
5527 unsigned c = 0;
5528 pid_t pid = getpid();
5529 const char * pszTmp = getenv("TMP");
5530 if (!pszTmp) pszTmp = getenv("TMPDIR");
5531 if (!pszTmp) pszTmp = getenv("TEMP");
5532 if (!pszTmp) pszTmp = ".";
5533
5534 do
5535 {
5536 struct timeval tv = {0,0};
5537 if (c++ >= 200)
5538 return -1;
5539 gettimeofday(&tv, NULL);
5540 sprintf(pszFile, "%s\\%s%x%lx%d%lx%s", pszTmp, pszPrefix, pid, tv.tv_sec, c, tv.tv_usec, pszSuffix);
5541 } while (!stat(pszFile, &s));
5542
5543 return 0;
5544}
5545
5546/* list of converted libraries and objects which must be removed upon exit. */
5547struct lx_tmp
5548{
5549 struct lx_tmp *next;
5550 char *name;
5551} *conv_list = NULL;
5552
5553/** Converts a .DLL to an temporary import library.
5554 * @remark sorry about the convention here, this is borrowed from elsewhere.
5555 */
5556char *lx_to_aout (const char *pszFilename)
5557{
5558 int rc;
5559 char * pszNewFile;
5560 struct lx_tmp *pName;
5561
5562 /*
5563 * Make temporary file.
5564 */
5565 pName = (struct lx_tmp *)xmalloc(sizeof(*pName));
5566 pName->name = pszNewFile = xmalloc(_MAX_PATH);
5567 if (make_tempfile(pszNewFile, "ldconv", ".a"))
5568 {
5569 free(pszNewFile);
5570 return NULL;
5571 }
5572
5573 /*
5574 * Do the conversion.
5575 */
5576 rc = spawnlp(P_WAIT, "emximp.exe", "emximp.exe",
5577 "-o", pszNewFile, pszFilename, NULL);
5578 if (!rc)
5579 {
5580 /* add to auto delete list for removal on exit(). */
5581 pName->next = conv_list;
5582 conv_list = pName;
5583 return pName->name;
5584
5585 }
5586 free(pszNewFile);
5587 free(pName);
5588
5589 fprintf (stderr, "emxomfld: a.out to omf conversion failed for '%s'.\n",
5590 pszFilename);
5591 exit (2);
5592 return NULL;
5593}
5594
5595
5596/**
5597 * Checks if the file FD is an LX DLL.
5598 *
5599 * @returns 1 if LX DLL.
5600 * @returns 0 if not LX DLL.
5601 * @param fd Handle to file to check.
5602 */
5603int check_lx_dll(int fd)
5604{
5605 unsigned long ul;
5606 char achMagic[2];
5607
5608 if ( lseek(fd, 0, SEEK_SET)
5609 || read(fd, &achMagic, 2) != 2)
5610 goto thats_not_it;
5611
5612 if (!memcmp(achMagic, "MZ", 2))
5613 {
5614 if ( lseek(fd, 0x3c, SEEK_SET)
5615 || read(fd, &ul, 4) != 4 /* offset of the 'new' header */
5616 || ul < 0x40
5617 || ul >= 0x10000000 /* 512MB stubs sure */
5618 || lseek(fd, ul, SEEK_SET)
5619 || read(fd, &achMagic, 2) != 2)
5620 goto thats_not_it;
5621 }
5622
5623 if ( memcmp(achMagic, "LX", 2)
5624 || lseek(fd, 14, SEEK_CUR)
5625 || read(fd, &ul, 4) != 4) /*e32_mflags*/
5626 goto thats_not_it;
5627
5628#define E32MODDLL 0x08000L
5629#define E32MODPROTDLL 0x18000L
5630#define E32MODMASK 0x38000L
5631 if ( (ul & E32MODMASK) != E32MODDLL
5632 && (ul & E32MODMASK) != E32MODPROTDLL)
5633 goto thats_not_it;
5634
5635 /* it's a LX DLL! */
5636 lseek(fd, 0, SEEK_SET);
5637 return 1;
5638
5639
5640thats_not_it:
5641 lseek(fd, 0, SEEK_SET);
5642 return 0;
5643}
5644
5645/* Generates a definition file for a dll which doesn't have one. */
5646
5647static void gen_deffile(void)
5648{
5649 char * psz;
5650 struct lx_tmp *pName;
5651
5652 /*
5653 * Make temporary file.
5654 */
5655 pName = (struct lx_tmp *)xmalloc(sizeof(*pName));
5656 pName->name = psz = (char *)xmalloc(_MAX_PATH);
5657 if (!make_tempfile(psz, "lddef", ".def"))
5658 {
5659 FILE *pFile = fopen(psz, "w");
5660 if (pFile)
5661 {
5662 const char *pszName = _getname(exe_filename);
5663 size_t cchName = strlen(pszName);
5664 if (cchName > 4 && !stricmp(pszName + cchName - 4, ".dll"))
5665 cchName -= 4;
5666 fprintf(pFile,
5667 ";; Autogenerated by ld\n"
5668 "LIBRARY %.*s INITINSTANCE TERMINSTANCE\n"
5669 "DATA MULTIPLE\n"
5670 "CODE SHARED\n"
5671 "\n",
5672 cchName, pszName);
5673 if (trace_files)
5674 fprintf(stderr,
5675 "--- Generated def-file %s:\n"
5676 ";; Autogenerated by ld\n"
5677 "LIBRARY %.*s INITINSTANCE TERMINSTANCE\n"
5678 "DATA MULTIPLE NONSHARED\n"
5679 "CODE SINGLE SHARED\n"
5680 "---- End of generated def-file.\n",
5681 psz, cchName, pszName);
5682 fclose(pFile);
5683 def_filename = psz;
5684
5685 /* add to auto delete list for removal on exit(). */
5686 pName->next = conv_list;
5687 conv_list = pName;
5688 return;
5689 }
5690 }
5691 free(psz);
5692 free(pName);
5693}
5694
5695
5696/* atexit worker */
5697void cleanup (void)
5698{
5699 for (; conv_list; conv_list = conv_list->next)
5700 unlink (conv_list->name);
5701}
Note: See TracBrowser for help on using the repository browser.