/* Linker `ld' for GNU, copyright (C) 1986 Richard M. Stallman

		       NO WARRANTY

  BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.

		GENERAL PUBLIC LICENSE TO COPY

  1. You may copy and distribute verbatim copies of this source file
as you receive it, in any medium, provided that you conspicuously
and appropriately publish on each copy a valid copyright notice
"Copyright (C) 1986 Richard M. Stallman"; and include following the
copyright notice a verbatim copy of the above disclaimer of warranty
and of this License.

  2. You may modify your copy or copies of this source file or
any portion of it, and copy and distribute such modifications under
the terms of Paragraph 1 above, provided that you also do the following:

    a) cause the modified files to carry prominent notices stating
    that you changed the files and the date of any change; and

    b) cause the whole of any work that you distribute or publish,
    that in whole or in part contains or is a derivative of this
    program or any part thereof, to be freely distributed
    and licensed to all third parties on terms identical to those
    contained in this License Agreement (except that you may choose
    to grant more extensive warranty protection to third parties,
    at your option).

  3. You may copy and distribute this program or any portion of it in
compiled, executable or object code form under the terms of Paragraphs
1 and 2 above provided that you do the following:

    a) cause each such copy to be accompanied by the
    corresponding machine-readable source code, which must
    be distributed under the terms of Paragraphs 1 and 2 above; or,

    b) cause each such copy to be accompanied by a
    written offer, with no time limit, to give any third party
    free (except for a nominal shipping charge) a machine readable
    copy of the corresponding source code, to be distributed
    under the terms of Paragraphs 1 and 2 above; or,

    c) in the case of a recipient of this program in compiled, executable
    or object code form (without the corresponding source code) you
    shall cause copies you distribute to be accompanied by a copy
    of the written offer of source code which you received along
    with the copy you received.

  4. You may not copy, sublicense, distribute or transfer this program
except as expressly provided under this License Agreement.  Any attempt
otherwise to copy, sublicense, distribute or transfer this program is void and
your rights to use the program under this License agreement shall be
automatically terminated.  However, parties who have received computer
software programs from you with this License Agreement will not have
their licenses terminated so long as such parties remain in full compliance.

 In other words, you are welcome to use, share and improve this program.
 You are forbidden to forbid anyone else to use, share and improve
 what you give them.   Help stamp out software-hoarding!  */

/* define this if on a system 
 where the names etext, edata and end should not have underscores.  */
/* #define nounderscore 1 */

/* define this for a linker for the TI NU machine.
 Slightly different defaults.  */

/* #define numachine 1 */

#ifdef numachine
#define O_RDONLY 0
#endif

#include <a.out.h>
#include <ar.h>
#include <stdio.h>
#include <sys/types.h>
#include <strings.h>
#include <sys/stat.h>
#include <symseg.h>

#ifndef numachine
#include <sys/file.h>
#endif

#define min(a,b) ((a) < (b) ? (a) : (b))

#define PAGE_SIZE 1024

/* number of buckets in symbol hash table */

#define	TABSIZE	1009

/* Global symbol data is recorded in these structures, one for each global symbol.  */
/* They are found via hashing in 'symtab', which points to a vector of buckets.
 Each bucket is a chain of these structurs, chained through the link field.  */

typedef
  struct glosym
    {
	/* pointer to next symbol in this symbol's hash bucket.  */
      struct glosym *link;
	/* name of this symbol.  */
      char *name;
	/* value of this symbol as a global symbol.  */
      long value;
	/* chain of external 'nlist's in files for this symbol, both defs and refs.  */
      struct nlist *refs;
	/* nonzero means definitions of this symbol as common have been seen,
	  and the value here is the largest size specified by any of them.  */
      int max_common_size;
	/* for relocatable_output, records the index of this global sym in the
	   symbol table to be written, with the first global sym given index 0.  */
      int def_count;
	/* nonzero means a definition of this global symbol is known to exist.
	  Library members should not be loaded on its account.  */
      char defined;
	/* nonzero means a reference to this global symbol has been seen in a file
	 that is surely being loaded.
	  A value higher than 1 is the n_type code for the symbol's definition.  */
      char referenced;
	/* nonzero means print a message at all references or definitions of this symbol */
      char trace;
    }
  symbol;

/* the symbol hash table: a vector of TABSIZE pointers to struct glosym. */
symbol **symtab;

/* number of symbols in symbol hash table. */
int num_hash_tab_syms = 0;



/* format of __.SYMDEF:
  first, a longword containing the size of the 'symdef' data that follows.
  second, zero or more 'symdef' structures
  third, a word containing the length of symbol name strings,
  fourth, zero or more symbol name strings (each followed by a zero).
*/

struct symdef {
  int symbol_name_string_index;
  int library_member_offset;
};



 /* count the number of nlist entries that are for local symbols.
   This and the following 3 are counted as symbols are entered in the symbol table.  */
int local_sym_count;

 /* count number of nlist entries that are for local symbols whose names don't start with L. */
int non_L_local_sym_count;

 /* count the number of nlist entries for debugger info.  */
int debugger_sym_count;

 /* count the number of global symbols referenced and not defined.  */
int undefined_global_sym_count;

 /* count the number of defined global symbols.  Each symbol is counted only once
   regardless of how many different nlist entries refer to it,
   since the output file will need only one nlist entry for it.
  This count is computed by digest_symbols;
  it is not defined while symbols are being loaded. */
int defined_global_sym_count;

 /* Total number of symbols to be written in the output file.
  Computed by digest_symbols from the variables above.  */
int nsyms;


 /* nonzero means ptr to symbol entry for symbol to use as start addr.
   -e sets this.  */
symbol *entry_symbol;

symbol *edata_symbol;   /* the symbol _edata */
symbol *etext_symbol;   /* the symbol _etext */
symbol *end_symbol;	/* the symbol _end */

/* Number of input files specified in the command line. */

int number_of_files;

/* Each input file, and each library member ("subfile") being loaded,
 has a file_entry structure for it.

For files specified in the command line, these are contained in the vector
which file_table points to.

For library members, they are dynamically allocated, chained through the 'chain' field.
The chain is found in the 'subfiles' field of the file_entry for the library itself.
The file_entry objects for the members have 'superfile' fields pointing
to the one for the library.
*/

struct file_entry {
  char *filename;
  char *local_sym_name;		/* name to use for the symbol giving address of text start */
				/* usually the same as filename, but for a file spec'd with -l
				   this is the -l switch itself rather than the filename */
  struct exec header;		/* the file's header */
  struct nlist *symbols;
  int total_size;		/* Size of data of this file, if library member */
  int string_size;              /* size, in bytes of string data */
  char *strings;
  int text_start_address;
  int data_start_address;
  int bss_start_address;
  int local_syms_offset;	/* Offset in bytes within output sym tab
				   of first local symbol from this file.
				   Set up by write_file_symbols.  */
  int symseg_offset;		/* Offset in file of GDB symbol segment,
				   or 0 if there is none.  */
  struct file_entry *subfiles;  /* For a library, points to entries for subfiles to load. */
  int starting_offset;		/* offset of logical file within file system file. */
				/* zero except for archive subfiles. */
  struct file_entry *superfile; /* for library subfile, points to the library's own entry */
  struct file_entry *chain;	/* for library subfile, points to next subfile in library */
    /* Next two used only if relocatable_output */
  struct relocation_info *textrel; /* text reloc info saved by write_text for wrtxtrel */
  struct relocation_info *datarel; /* data reloc info saved by write_data for wrdatrel */
  char library_flag;		/* 1 if file is a library. */
  char header_read_flag;	/* 1 if file's header has been read into this structure */
  char search_dirs_flag;	/* 1 means search a set of directories for this file.  */
				/* the search list is /lib, /usr/lib, /usr/local/lib */
  char just_syms_flag;	/* 1 means this is base file of incremental load.
				   Do not load this file's text or data.
				   Also default text_start to after this file's bss. */
};

struct file_entry *file_table;

/* When loading the text and data, we can avoid doing a close and another open
 between members of the same library.  These two variables remember the
 file that is currently open.  If the one we want is the same one, we just keep using it.  */

struct file_entry *input_file;
int input_desc;

/* The name of the file to write; "a.out" by default.  */

char *output_filename;

/* Descriptor for writing that file with mywrite.  */

int outdesc;

/* Header for that file (filled in by write_header). */

struct exec outheader;

/* The following are computed by digest_symbols.  */
int text_size;		/* total size of text of all input files.  */
int data_size;		/* total size of data of all input files.  */
int bss_size;		/* total size of bss of all input files.  */
int text_reloc_size;	/* total size of text relocation of all input files.  */
int data_reloc_size;	/* total size of data relocation of all input files.  */

int text_pad;
int data_pad;

/* The following are controlled by command switches.  */

 /* Address we assume the text section will be loaded at.
    We relocate symbols and text and data for this, but we do not
    write any padding in the output file for it.  */
int text_start;

 /* nonzero if -T was specified in the command line.
    This prevents text_start from being set later to default values.  */
int T_flag_specified;

 /* Size to pad data section up to.
    We simply increase the size of the data section, padding with zeros,
    and reduce the size of the bss section to match.  */
int specified_data_size;

 /* magic number to use for the output file, set by switch */
int magic;

 /* nonzero means print names of input files as processed */
int trace_files;

 /* 1 => strip all symbols; 2 => strip all but locals and globals */
int strip_symbols;

 /* 1 => discard locals starting with L; 2 => discard all locals */
int discard_locals;

 /* 1 => write load map */
int write_map;

 /* 1 => write relocation into output file so can re-input it later */
int relocatable_output;

 /* 1 => define common even if relocatable_output.  */
int force_common_definition;

/* directories to search for libraries specified by -l */
char *search_dirs[] = {"/lib/", "/usr/lib/", "/usr/local/lib/", 0};

/* nonzero means should make the output file executable when done.  */
/* cleared by nonfatal errors */
int make_executable;

void digest_symbols ();
void print_symbols ();
void load_symbols ();
void decode_command ();
void list_undefined_symbols ();
void write_header ();
void write_text ();
void write_data ();
void wrtxtrel (); /* should be write_text_relocation (); */
void wrdatrel (); /* should be write_data_relocation (); */
void write_syms ();
void padfile ();
char *concat ();
symbol *getsym (), *getsym_soft ();

main(argc, argv)
     char **argv;
     int argc;
{
  text_size = 0;
  data_size = 0;
  bss_size = 0;
  text_reloc_size = 0;
  data_reloc_size = 0;

  data_pad = 0;
  text_pad = 0;

#ifdef numachine
  text_start = 0x400;
#else
  text_start = 0;
#endif
  specified_data_size = 0;

  strip_symbols = 0;
  trace_files = 0;
  discard_locals = 0;
  entry_symbol = 0;
  write_map = 0;
  relocatable_output = 0;
  force_common_definition = 0;
  T_flag_specified = 0;

#ifdef numachine
  magic = NMAGIC;
#else
  magic = ZMAGIC;
#endif

  make_executable = 1;

  symtab_init ();

#ifndef nounderscore
  edata_symbol = getsym ("_edata");
  etext_symbol = getsym ("_etext");
  end_symbol = getsym ("_end");
#else
  edata_symbol = getsym ("edata");
  etext_symbol = getsym ("etext");
  end_symbol = getsym ("end");
#endif

  edata_symbol->defined = N_DATA | N_EXT;
  etext_symbol->defined = N_TEXT | N_EXT;
  end_symbol->defined = N_BSS | N_EXT;

  edata_symbol->referenced = 1;
  etext_symbol->referenced = 1;
  end_symbol->referenced = 1;

  local_sym_count = 0;
  non_L_local_sym_count = 0;
  debugger_sym_count = 0;
  undefined_global_sym_count = 0;

  decode_command (argc, argv);

  /* Load symbols of all input files, and search libraries.  */
  load_symbols ();

  /* Compute where each file's sections go, and relocate symbols.  */
  digest_symbols ();

  if (!relocatable_output)
    list_undefined_symbols (stderr);

  if (write_map) print_symbols (stdout);

  /* Write the output file */ 
  {
    struct stat statbuf;
    int filemode;

    outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if (outdesc < 0) perror_name (output_filename);

    if (fstat (outdesc, &statbuf) < 0)
      perror_name (output_filename);

    filemode = statbuf.st_mode;

    chmod (output_filename, filemode & ~0111);

    write_header ();

    write_text ();
    write_data ();

    if (relocatable_output)
      {
	wrtxtrel ();
	wrdatrel ();
      }

    /* Output the loader symbol table.  */
    write_syms ();

    /* Copy any GDB symbol segments from input files.  */
    write_symsegs ();

    close (outdesc);

    if (make_executable)
      chmod (output_filename, filemode | 0111);
  }
  return 0;
}

void decode_switch ();

/* analyze a command line argument.
 Returns 0 if the argument is a filename.
 Returns 1 if the argument is a switch complete in itself.
 Returns 2 if the argument is a switch which gobbles the following argument. */

int
decode_arg(arg)
     register char *arg;
{
  if (*arg != '-') return 0;
  if (!strcmp (arg, "-D")) return 2;
  if (!strcmp (arg, "-e")) return 2;
  if (!strcmp (arg, "-o")) return 2;
  if (!strcmp (arg, "-T")) return 2;
  if (!strcmp (arg, "-u")) return 2;
  return 1;
}

/* Process the command arguments, setting up file_table with an entry for
 each input file, and setting variables according to the switches.  */

void
decode_command(argc, argv)
     char **argv;
     int argc;
{
  register int i;
  register struct file_entry *p;
  register int syms_only = 0;

  number_of_files = 0;
  output_filename = "a.out";

  /* First compute number_of_files so we know how long to make file_table */
  /* Also process most switches completely */

  for (i = 1; i < argc; i++)
    {
      register int code = decode_arg (argv[i]);
      if (code)
	{
	  if (i + code > argc)
	    fatal ("no argument following %s\n", argv[i]);
	  decode_switch (argv[i], argv[i+1]);
	  if (argv[i][1] == 'l')
	    number_of_files++;
	  i += code - 1;
	}
      else
	number_of_files++;
    }

  if (!number_of_files)
    fatal ("no input files", 0);

  p = file_table
    = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  bzero (p, number_of_files * sizeof (struct file_entry));

  /* Now scan again and fill in file_table */
  /* All switches except -A and -l need only be skipped, here */

  for (i = 1; i < argc; i++)
    {
      register int code = decode_arg (argv[i]);

      if (code)
	{
	  if (!strcmp (argv[i], "-A"))
	    {
	      syms_only = 1;
	      if (p != file_table)
		fatal ("-A specified before an input file other than the first");
	    }
	  if (argv[i][1] == 'l')
	    {
	      p->filename = concat ("lib", &argv[i][2], ".a");
	      p->local_sym_name = argv[i];
	      p->library_flag = 0;	/* we'll find the truth later */
	      p->search_dirs_flag = 1;
	      p->header_read_flag = 0;
	      p->starting_offset = 0;
	      p->subfiles = 0;
	      p->superfile = 0;
	      p->symbols = 0;
	      p->strings = 0;
	      p->just_syms_flag = 0;
	      p++;
	    }
	  i += code - 1;
	}
      else
	{
	  p->filename = argv[i];
	  p->local_sym_name = argv[i];
	  p->library_flag = 0;
	  p->search_dirs_flag = 0;
	  p->header_read_flag = 0;
	  p->starting_offset = 0;
	  p->subfiles = 0;
	  p->superfile = 0;
	  p->symbols = 0;
	  p->strings = 0;
	  p->just_syms_flag = syms_only;
	  p++;
	}
      syms_only = 0;
    }

  /* Now check some switch settings for consistency.  */

  if ((magic == ZMAGIC || magic == NMAGIC)
      && text_start & (PAGE_SIZE - 1))
    fatal ("-T argument not multiple of page size, with sharable output", 0);
    
}

void
decode_switch (swt, arg)
     register char *swt, *arg;
{
  if (!strcmp (swt, "-A"))
    ;
  else if (!strcmp (swt, "-D"))
    specified_data_size = parse (arg, "%x", "invalid argument to -D");
  else if (!strcmp (swt, "-d"))
    force_common_definition = 1;
  else if (!strcmp (swt, "-e"))
    {
      entry_symbol = getsym (arg);
      if (!entry_symbol->defined && !entry_symbol->referenced) undefined_global_sym_count++;
      entry_symbol->referenced = 1;
    }
  else if (swt[1] == 'l')
    ;
  else if (!strcmp (swt, "-M"))
    write_map = 1;
  else if (!strcmp (swt, "-N"))
    magic = OMAGIC;
  else if (!strcmp (swt, "-n"))
    magic = NMAGIC;
  else if (!strcmp (swt, "-o"))
    output_filename = arg;
  else if (!strcmp (swt, "-r"))
    {
      relocatable_output = 1;
      magic = OMAGIC;
      text_start = 0;
    }
  else if (!strcmp (swt, "-S"))
    strip_symbols = 2;
  else if (!strcmp (swt, "-s"))
    strip_symbols = 1;
  else if (!strcmp (swt, "-T"))
    text_start = parse (arg, "%x", "invalid argument to -T");
  else if (!strcmp (swt, "-t"))
    trace_files = 1;
  else if (!strcmp (swt, "-u"))
    {
      register symbol *sp = getsym (arg);
      if (!sp->defined && !sp->referenced) undefined_global_sym_count++;
      sp->referenced = 1;
    }
  else if (!strcmp (swt, "-X"))
    discard_locals = 1;
  else if (!strcmp (swt, "-x"))
    discard_locals = 2;
  else if (swt[1] == 'y')
    {
      register symbol *sp = getsym (&swt[2]);
      sp->trace = 1;
    }
  else if (!strcmp (swt, "-z"))
    magic = ZMAGIC;
  else
    fatal ("invalid command switch %s", swt);
}

/** Convenient functions for operating on one or all files being loaded.  */

/* Call 'function' on each input file entry.
 Do not call for entries for libraries;
 instead, call once for each library member that is being loaded.

 'function' receives two arguments: the entry, and 'arg'.  */

void
each_file (function, arg)
     register void (*function)();
     register int arg;
{
  register int i;

  for (i = 0; i < number_of_files; i++)
    {
      register struct file_entry *entry = &file_table[i];
      if (entry->library_flag)
        {
	  register struct file_entry *subentry = entry->subfiles;
	  for (; subentry; subentry = subentry->chain)
	    {
	      (*function) (subentry, arg);
	    }
	}
      else
	{
	  (*function) (entry, arg);
	}
    }
}

/* Close the input file that is now open.  */

void
file_close ()
{
  close (input_desc);
  input_desc = 0;
  input_file = 0;
}

/* open the input file specified by 'entry', and return a descriptor.
 The open file is remembered; if the same file is opened twice in a row,
 a new open is not actually done.  */

int
file_open (entry)
     register struct file_entry *entry;
{
  register int desc;

  if (entry->superfile)
    return file_open (entry->superfile);

  if (entry == input_file)
    return input_desc;

  if (input_file) file_close ();

  if (entry->search_dirs_flag)
    {
      register char **p = search_dirs;

      while (*p)
	{
	  register char *string = concat (*p, entry->filename, "");
	  desc = open (string, O_RDONLY, 0);
	  if (desc > 0)
	    {
	      entry->filename = string;
	      entry->search_dirs_flag = 0;
	      break;
	    }
	  free (string);
	  p++;
	}
    }
  else
    desc = open (entry->filename, O_RDONLY, 0);

  if (desc > 0)
    {
      input_file = entry;
      input_desc = desc;
      return desc;
    }

  perror_file (entry);
}

/* Print the filename of 'entry' on 'outfile' (a stdio stream), and then a newline.  */

prline_file_name (entry, outfile)
     struct file_entry *entry;
     FILE *outfile;
{
  print_file_name (entry, outfile);
  fprintf (outfile, "\n");
}

/* Print the filename of 'entry' on 'outfile' (a stdio stream).  */

print_file_name (entry, outfile)
     struct file_entry *entry;
     FILE *outfile;
{
  if (entry->superfile)
    {
      print_file_name (entry->superfile, outfile);
      fprintf (outfile, ":");
    }
  fprintf (outfile, "%s", entry->filename);
}

/* read in the symbols of all input files */

void read_file_symbols (), read_entry_symbols(), read_entry_strings(), enter_global_ref (), search_library();
void enter_file_symbols ();

void
load_symbols ()
{
  register int i;

  if (trace_files) fprintf (stderr, "Loading symbols:\n\n");

  for (i = 0; i < number_of_files; i++)
    {
      register struct file_entry *entry = &file_table[i];
      read_file_symbols (entry);
    }

  if (trace_files) fprintf (stderr, "\n");
}

/* read a file's header into the proper place in the file_entry.  */

void
read_header (desc, loc, entry)
     int desc;
     struct exec *loc;
     register struct file_entry *entry;
{
  register int len;
  lseek (desc, entry->starting_offset, 0);
  len = read (desc, loc, sizeof (struct exec));
  if (len != sizeof (struct exec))
    fatal_with_file ("failure reading header of ", entry);
  if (N_BADMAG(*loc))
    fatal_with_file ("bad magic number in ", entry);

  entry->header_read_flag = 1;
}

/* If file 'entry' is a rel file, read its symbol and string sections into core.
 If it is a library, search it and load the appropriate members.  */

void
read_file_symbols (entry)
     register struct file_entry *entry;
{
  register int desc;
  register int len;
  int magicnum;

  desc = file_open (entry);

  len = read (desc, &magicnum, sizeof magicnum);
  if (len != sizeof magicnum)
    fatal_with_file ("failure reading header of ", entry);
  if (!N_BADMAG(*((struct exec *)&magicnum)))
    {
      read_entry_symbols (desc, entry);
      entry->strings = (char *) alloca (entry->string_size);
      read_entry_strings (desc, entry);
      enter_file_symbols (entry);
    }
  else
    {
      char armag[SARMAG];

      lseek (desc, 0, 0);
      if (SARMAG != read (desc, armag, SARMAG) || strncmp (armag, ARMAG, SARMAG))
	fatal_with_file ("malformed input file (not rel or archive) ", entry);
      entry->library_flag = 1;
      search_library (desc, entry);
    }

  file_close ();
}


/* Read the symbols of file 'entry' into core.
 Assume it is already open, on descriptor 'desc'.  */

void
read_entry_symbols (desc, entry)
     struct file_entry *entry;
     int desc;
{
  int str_size;

  if (!entry->header_read_flag)
    read_header (desc, &entry->header, entry);

  entry->symbols = (struct nlist *) xmalloc (entry->header.a_syms);

  lseek (desc, N_SYMOFF (entry->header) + entry->starting_offset, 0);
  if (entry->header.a_syms != read (desc, entry->symbols, entry->header.a_syms))
    fatal_with_file ("premature end of file in symbols of ", entry);

  lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  if (sizeof str_size != read (desc, &str_size, sizeof str_size))
    fatal_with_file ("bad string table size in ", entry);

  entry->string_size = str_size;
}

/* Read the strings of file 'entry' into core.
 Assume it is already open, on descriptor 'desc'.  */

void
read_entry_strings (desc, entry)
     struct file_entry *entry;
     int desc;
{
  int buffer;

  if (!entry->header_read_flag)
    read_header (desc, &entry->header, entry);

  lseek (desc, N_STROFF (entry->header) + entry->starting_offset, 0);
  if (entry->string_size != read (desc, entry->strings, entry->string_size))
    fatal_with_file ("premature end of file in strings of ", entry);

  /* While we are here, see if the file has a symbol segment at the end.
     For a separate file, just try reading some more.
     For a library member, compare current pos against total size.  */
  if (entry->superfile)
    {
      if (entry->total_size == N_STROFF (entry->header) + entry->string_size)
	return;
    }
  else
    {
      buffer = read (desc, &buffer, sizeof buffer);
      if (buffer == 0)
	return;
      if (buffer != sizeof buffer)
	fatal_with_file ("premature end of file in GDB symbol segment of ", entry);
    }

  entry->symseg_offset = N_STROFF (entry->header) + entry->string_size;
}

/* enter the external symbol defs and refs of file 'entry' in the hash table  */

void
enter_file_symbols (entry)
     struct file_entry *entry;
{
   register struct nlist *p, *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);

  if (trace_files) prline_file_name (entry, stderr);

  for (p = entry->symbols; p < end; p++)
    if (p->n_type & N_EXT)
      enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
    else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
      {
	if ((p->n_un.n_strx + entry->strings)[0] != 'L')
	  non_L_local_sym_count++;
	local_sym_count++;
      }
    else debugger_sym_count++;

/* count one for the local symbol that we generate,
 whose name is the file's name (usually) and whose address
 is the start of the file's text.  */

  local_sym_count++;
  non_L_local_sym_count++;
}

void
enter_global_ref (nlist_p, name, entry)
     register struct nlist *nlist_p;
     char *name;
     struct file_entry *entry;
{
  register symbol *sp = getsym (name);
  register int type = nlist_p->n_type;
  int oldref = sp->referenced;
  int olddef = sp->defined;

  nlist_p->n_un.n_name = (char *) sp->refs;
  sp->refs = nlist_p;

  sp->referenced = 1;

  if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
    {
      sp->defined = 1;
      if (oldref && !olddef) undefined_global_sym_count--;
    }
  else
    if (!oldref) undefined_global_sym_count++;

  if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
    text_start = nlist_p->n_value;

  if (sp->trace)
    {
      register char *reftype;
      switch (type & N_TYPE)
	{
	case N_UNDF:
	  if (nlist_p->n_value)
	    reftype = "defined as common";
	  else reftype = "referenced";
	  break;

	case N_ABS:
	  reftype = "defined as absolute";
	  break;

	case N_TEXT:
	  reftype = "defined in text section";
	  break;

	case N_DATA:
	  reftype = "defined in data section";
	  break;

	case N_BSS:
	  reftype = "defined in BSS section";
	  break;
	}

      fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
      print_file_name (entry, stderr);
      fprintf (stderr, "\n");
    }
}

/* Searching libraries */

struct file_entry *decode_library_subfile ();
void linear_library (), symdef_library ();

/* Search the library of 'entry', already open on descriptor 'desc'  */

void
search_library (desc, entry)
     int desc;
     struct file_entry *entry;
{
  int member_length;
  register char *name;
  register struct file_entry *subentry;

  if (!undefined_global_sym_count) return;

  /* Examine its first member, which starts SARMAG bytes in.  */
  subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  if (!subentry) return;

  name = subentry->filename;
  free (subentry);

  /* Search via __.SYMDEF if that exists, else linearly.  */

  if (!strcmp (name, "__.SYMDEF"))
    symdef_library (desc, entry, member_length);
  else
    linear_library (desc, entry);
}

/* Construct and return a file_entry for a library member.
  The library's file_entry is library_entry, and the library is open on 'desc'.
  'subfile_offset' is the byte index in the library at which this member's header is.
  The length of the member is stored into the integer addressed by 'length_loc'.  */

struct file_entry *
decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
     int desc;
     struct file_entry *library_entry;
     int subfile_offset;
     int *length_loc;
{
  int bytes_read;
  register int namelen;
  int member_length;
  register char *name;
  struct ar_hdr hdr1;
  register struct file_entry *subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));

  lseek (desc, subfile_offset, 0);

  bytes_read = read (desc, &hdr1, sizeof hdr1);
  if (!bytes_read)
    return 0;		/* end of archive */

  if (sizeof hdr1 != bytes_read)
    fatal_with_file ("malformed library archive ", library_entry);

  if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
    fatal_with_file ("malformatted header of archive member in ", library_entry);

  namelen = index (hdr1.ar_name, ' ') - hdr1.ar_name;
  name = (char *) xmalloc (namelen+1);
  strncpy (name, hdr1.ar_name, namelen);
  *(name + namelen) = 0;

  subentry->filename = name;
  subentry->local_sym_name = name;
  subentry->symbols = 0;
  subentry->strings = 0;
  subentry->subfiles = 0;
  subentry->starting_offset = subfile_offset + sizeof hdr1;
  subentry->superfile = library_entry;
  subentry->library_flag = 0;
  subentry->header_read_flag = 0;
  subentry->just_syms_flag = 0;
  subentry->chain = 0;
  subentry->total_size = member_length;

  (*length_loc) = member_length;

  return subentry;
}

/* search a library that has a __.SYMDEF member.
  'desc' is a descriptor on which the library is open.
    The file pointer is assumed to point at the __.SYMDEF data.
  'entry' is the library's file_entry.
  'member_length' is the length of the __.SYMDEF data.
*/

void
symdef_library (desc, entry, member_length)
     int desc;
     struct file_entry *entry;
     int member_length;
{
  int *symdef_data = (int *) xmalloc (member_length);
  register struct symdef *symdef_base;
  char *sym_name_base;
  int number_of_symdefs;
  int length_of_strings;
  int not_finished;
  int bytes_read;
  register int i;
  struct file_entry *prev = 0;

  bytes_read = read (desc, symdef_data, member_length);
  if (bytes_read != member_length)
    fatal_with_file ("malformatted __.SYMDEF in ", entry);

  number_of_symdefs = *symdef_data / sizeof (struct symdef);
  if (number_of_symdefs < 0 ||
       number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) >= member_length)
    fatal_with_file ("malformatted __.SYMDEF in ", entry);

  symdef_base = (struct symdef *) (symdef_data + 1);
  length_of_strings = *(int *) (symdef_base + number_of_symdefs);

  if (length_of_strings < 0
      || number_of_symdefs * sizeof (struct symdef) + length_of_strings
	  + 2 * sizeof (int) != member_length)
    fatal_with_file ("malformatted __.SYMDEF in ", entry);

  sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);

  /* check all the string indexes for validity */

  for (i = 0; i < number_of_symdefs; i++)
    {
      register int index = symdef_base[i].symbol_name_string_index;
      if (index < 0 || index >= length_of_strings
	  || (index && *(sym_name_base + index - 1)))
	fatal_with_file ("malformatted __.SYMDEF in ", entry);
    }

  /* Search the symdef data for members to load.
     Do this until one whole pass finds nothing to load.  */

  not_finished = 1;
  while (not_finished && undefined_global_sym_count)
    {
      not_finished = 0;

      /* scan all the symbols mentioned in the symdef for ones that we need.
	 load the library members that contain such symbols.  */

      for (i = 0; i < number_of_symdefs; i++)
	{
	  register symbol *sp;

	  if (!undefined_global_sym_count) break;
	  if (symdef_base[i].symbol_name_string_index < 0) continue;

	  sp = getsym_soft (sym_name_base + symdef_base[i].symbol_name_string_index);
	  if (sp && sp->referenced && !sp->defined)
	    {
	      int junk;
	      register int j;
	      register int offset = symdef_base[i].library_member_offset;
	      struct file_entry *subentry;

	      subentry = decode_library_subfile (desc, entry, offset, &junk);
	      read_entry_symbols (desc, subentry);
	      subentry->strings = (char *) alloca (subentry->string_size);
	      read_entry_strings (desc, subentry);

	      if (!subfile_wanted_p (subentry))
		{
		  free (subentry->symbols);
		  free (subentry);
		}
	      else
		{
		  /* we need the member at offset 'offset' in the library, so load it.  */

		  not_finished = 1;

		  enter_file_symbols (subentry);

		  if (prev)
		    prev->chain = subentry;
		  else entry->subfiles = subentry;
		  prev = subentry;

		  /* don't bother considering the symbols this member defined
		     if we have to scan the symdef data again. */

		  for (j = 0; j < number_of_symdefs; j++)
		    {
		      if (symdef_base[j].library_member_offset == offset)
			symdef_base[j].symbol_name_string_index = -1;
		    }
		}
	    }
	}
    }

  free (symdef_data);
}

/* Search a library that has no __.SYMDEF.
 'entry' is the library's file_entry, and 'desc' is the descriptor it is open on.  */

void
linear_library (desc, entry)
     int desc;
     struct file_entry *entry;
{
  register struct file_entry *prev = 0;
  register int this_subfile_offset = SARMAG;

  while (undefined_global_sym_count)
    {
      int member_length;
      register struct file_entry *subentry;

      subentry = decode_library_subfile (desc, entry, this_subfile_offset, &member_length);

      if (!subentry) return;

      read_entry_symbols (desc, subentry);
      subentry->strings = (char *) alloca (subentry->string_size);
      read_entry_strings (desc, subentry);

      if (!subfile_wanted_p (subentry))
	{
	  free (subentry->symbols);
	  free (subentry);
	}
      else
	{
	  enter_file_symbols (subentry);

	  if (prev)
	    prev->chain = subentry;
	  else entry->subfiles = subentry;
	  prev = subentry;
	}

      this_subfile_offset += member_length + sizeof (struct ar_hdr);
      if (this_subfile_offset & 1) this_subfile_offset++;
    }
}

/* 'entry' is an entry for a library member.
 Its symbols have been read into core, but not entered.
 Return nonzero if we ought to load this member.  */

int
subfile_wanted_p (entry)
     struct file_entry *entry;
{
  register struct nlist *p, *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  for (p = entry->symbols; p < end; p++)
    {
      register int type = p->n_type;

      if (type & N_EXT && (type != (N_UNDF | N_EXT) || p->n_value))
	{
	  register char *name = p->n_un.n_strx + entry->strings;
	  register symbol *sp = getsym_soft (name);

	  /* If this symbol has not been hashed, we can't be looking for it. */

	  if (!sp) continue;

	  if (sp->referenced && !sp->defined)
	    {
	      /* This is a symbol we are looking for.  */
	      if (type == (N_UNDF | N_EXT))
		{
		  /* Symbol being defined as common.
		     Remember this, but don't load subfile just for this.  */

		  if (sp->max_common_size < p->n_value)
		    sp->max_common_size = p->n_value;
		  if (!sp->defined)
		    undefined_global_sym_count--;
		  sp->defined = 1;
		  continue;
		}

	      if (write_map)
		{
		  print_file_name (entry, stdout);
		  fprintf (stdout, " needed due to %s\n", sp->name);
		}
	      return 1;
	    }
	}
    }

  return 0;
}

void consider_file_section_lengths (), relocate_file_addresses ();

void
digest_symbols ()
{
  register int i;

  if (trace_files)
    fprintf (stderr, "Digesting symbol information:\n\n");

  /* compute total size of sections */

  each_file (consider_file_section_lengths, 0);

  /* If necessary, pad text section to page boundary.  */

  if (magic == NMAGIC || magic == ZMAGIC)
    {
      text_pad = ((text_size + PAGE_SIZE - 1) & (- PAGE_SIZE)) - text_size;
      text_size += text_pad;
    }

  /* compute start addresses of each file's sections and symbols.  */

  each_file (relocate_file_addresses, 0);

  /* Now, for each symbol, verify that it is defined globally at most once.
     Put the global value into the symbol entry.
     Common symbols are allocated here, in the BSS section.
     Each defined symbol is given a '->defined' field
      which is the correct N_ code for its definition,
      except in the case of common symbols with -r.
     Then make all the references point at the symbol entry
     instead of being chained together. */

  defined_global_sym_count = 0;

  for (i = 0; i < TABSIZE; i++)
    {
      register symbol *sp;
      for (sp = symtab[i]; sp; sp = sp->link)
	{
	  register struct nlist *p, *next;
	  int defs = 0, com = sp->max_common_size, erred = 0;
	  for (p = sp->refs; p; p = next)
	    {
	      register int type = p->n_type;
	      if (type == (N_UNDF | N_EXT))
		{
		  /* common symbol definition */
		  if (p->n_value > com)
		    {
		      com = p->n_value;
		    }
		}
	      else if (type & N_EXT)
		{
		  /* non-common definition */
		  if (defs++ && sp->value != p->n_value)
		    if (!erred++)
		      {
		        make_executable = 0;
			error ("multiple definitions of symbol %s", sp->name);
		      }
		  sp->value = p->n_value;
		  sp->defined = type;
		}
	      next = (struct nlist *) p->n_un.n_name;
	      p->n_un.n_name = (char *) sp;
	    }
	  /* Allocate as common if defined as common and not defined for real */
	  if (com && !defs)
	    {
	      sp->max_common_size = com;
	      if (!relocatable_output || force_common_definition)
		{
		  com = (com + sizeof (int) - 1) & (- sizeof (int));
    
		  sp->value = text_start + text_size + data_size + bss_size;
		  sp->defined = N_BSS | N_EXT;
		  bss_size += com;
		  if (write_map)
		    printf ("Allocating common %s: %x at %x\n",
			    sp->name, com, sp->value);
		}
	    }
	  if (sp->defined)
	    defined_global_sym_count++;
	}
    }

  etext_symbol->value = text_size + text_start;
  edata_symbol->value = text_size + text_start + data_size;
  end_symbol->value = text_start + text_size + data_size + bss_size;

  /* For sharable output, relable the last unfinished text page as data */

  if (magic == NMAGIC || magic == ZMAGIC)
    {
      register int text_ovfl = text_size % PAGE_SIZE;

      if (text_start % PAGE_SIZE)
	fatal ("-T argument not multiple of page size", 0);

      text_size -= text_ovfl;
      data_size += text_ovfl;
    }

  /* figure the data_pad now, so that it overlaps with the bss addresses.  */

  if (specified_data_size && specified_data_size > data_size)
    data_pad = specified_data_size - data_size;

  if (magic == ZMAGIC)
    data_pad = ((data_pad + data_size + PAGE_SIZE - 1) & (- PAGE_SIZE))
               - data_size;

  bss_size -= data_pad;
  if (bss_size < 0) bss_size = 0;

  data_size += data_pad;
}

void
consider_file_section_lengths (entry)
     register struct file_entry *entry;
{
  if (entry->just_syms_flag)
    return;

  entry->text_start_address = text_size;
  text_size += entry->header.a_text;
  entry->data_start_address = data_size;
  data_size += entry->header.a_data;
  entry->bss_start_address = bss_size;
  bss_size += entry->header.a_bss;

  text_reloc_size += entry->header.a_trsize;
  data_reloc_size += entry->header.a_drsize;
}

void
relocate_file_addresses (entry)
     register struct file_entry *entry;
{
  entry->text_start_address += text_start;
  entry->data_start_address += text_start + text_size;
  entry->bss_start_address += text_start + text_size + data_size;

  {
    register struct nlist *p, *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
    for (p = entry->symbols; p < end; p++)
      {
	/* if this belongs to a section, update it by the section's start address */
	register int type = p->n_type & N_TYPE;

	if (type == N_TEXT)
	  p->n_value += entry->text_start_address;
	else if (type == N_DATA)
	  /* A symbol whose value is in the data section
	     is present in the input file as if the data section
	     started at an address equal to the length of the file's text.  */
	  p->n_value += entry->data_start_address - entry->header.a_text;
	else if (type == N_BSS)
	  /* likewise for symbols with value in BSS.  */
	  p->n_value += entry->bss_start_address
			 - entry->header.a_text - entry->header.a_data;
      }
  }
}

void describe_file_sections (), list_file_locals ();

void
print_symbols (outfile)
     FILE *outfile;
{
  register int i;

  fprintf (outfile, "\nFiles:\n\n");

  each_file (describe_file_sections, outfile);

  fprintf (outfile, "\nGlobal symbols:\n\n");

  for (i = 0; i < TABSIZE; i++)
    {
      register symbol *sp;
      for (sp = symtab[i]; sp; sp = sp->link)
	{
	  if (sp->defined == 1)
	    fprintf (outfile, "  %s: common, length 0x%x\n", sp->name, sp->max_common_size);
	  if (sp->defined)
	    fprintf (outfile, "  %s: 0x%x\n", sp->name, sp->value);
	  else if (sp->referenced)
	    fprintf (outfile, "  %s: undefined\n", sp->name);
	}
    }

  each_file (list_file_locals, outfile);
}

void
describe_file_sections (entry, outfile)
     struct file_entry *entry;
     FILE *outfile;
{
  fprintf (outfile, "  ");
  print_file_name (entry, outfile);
  if (entry->just_syms_flag)
    fprintf (outfile, " symbols only\n", 0);
  else
    fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
	     entry->text_start_address, entry->header.a_text,
	     entry->data_start_address, entry->header.a_data,
	     entry->bss_start_address, entry->header.a_bss);
}

void
list_file_locals (entry, outfile)
     struct file_entry *entry;
     FILE *outfile;
{
  register struct nlist *p, *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);

  entry->strings = (char *) alloca (entry->string_size);
  read_entry_strings (file_open (entry), entry);

  fprintf (outfile, "\nLocal symbols of ");
  print_file_name (entry, outfile);
  fprintf (outfile, ":\n\n");

  for (p = entry->symbols; p < end; p++)
    /* if this is a definition, update it if necessary by this file's start address */
    if (!(p->n_type & (N_STAB | N_EXT)))
      fprintf (outfile, "  %s: 0x%x\n",
	       entry->strings + p->n_un.n_strx, p->n_value);
}

void
list_undefined_symbols (outfile)
     FILE *outfile;
{
  register int i;
  register int count = 0;

  for (i = 0; i < TABSIZE; i++)
    {
      register symbol *sp;
      for (sp = symtab[i]; sp; sp = sp->link)
	{
	  if (sp->referenced && !sp->defined)
	    {
	      if (!count++)
		fprintf (outfile, "Undefined symbols:\n");
	      fprintf (outfile, " %s\n", sp->name);
	    }
	}
    }

  if (count)
    fprintf (outfile, "\n");
  if (count)
    make_executable = 0;
}

void modify_location (), perform_relocation (), copy_text (), copy_data ();

void
write_header ()
{
  outheader.a_magic = magic;
  outheader.a_text = text_size;
  outheader.a_data = data_size;
  outheader.a_bss = bss_size;
  outheader.a_entry = entry_symbol ? entry_symbol->value : text_start;

  if (strip_symbols == 1)
    nsyms = 0;
  else
    {
      nsyms = defined_global_sym_count + undefined_global_sym_count;
      if (discard_locals == 1)
	nsyms += non_L_local_sym_count;
      else if (discard_locals == 0)
	nsyms += local_sym_count;
    }

  if (strip_symbols == 0)
    nsyms += debugger_sym_count;

  outheader.a_syms = nsyms * sizeof (struct nlist);

  if (relocatable_output)
    {
      outheader.a_trsize = text_reloc_size;
      outheader.a_drsize = data_reloc_size;
    }
  else
    {
      outheader.a_trsize = 0;
      outheader.a_drsize = 0;
    }

  mywrite (&outheader, sizeof(struct exec), 1, outdesc);

  if (magic == ZMAGIC)
    padfile (PAGE_SIZE - sizeof outheader, outdesc);
}

void
write_text ()
{
  if (trace_files)
    fprintf (stderr, "Copying and relocating text:\n\n");

  each_file (copy_text);
  file_close ();

  if (trace_files)
    fprintf (stderr, "\n");

  padfile (text_pad, outdesc);
}

int
text_offset (entry)
     struct file_entry *entry;
{
  return entry->starting_offset + N_TXTOFF (entry->header);
}

void
copy_text (entry)
     struct file_entry *entry;
{
  register char *bytes = (char *) alloca (entry->header.a_text);
  register int desc;
  register struct relocation_info *reloc;

  if (relocatable_output)
    reloc = (struct relocation_info *) xmalloc (entry->header.a_trsize);
  else
    reloc = (struct relocation_info *) alloca (entry->header.a_trsize);

  if (trace_files)
    prline_file_name (entry, stderr);

  desc = file_open (entry);

  lseek (desc, text_offset (entry), 0);
  if (entry->header.a_text != read (desc, bytes, entry->header.a_text))
    fatal_with_file ("premature eof in text section of ", entry);

  lseek (desc, text_offset (entry) + entry->header.a_text + entry->header.a_data, 0);
  if (entry->header.a_trsize != read (desc, reloc, entry->header.a_trsize))
    fatal_with_file ("premature eof in text relocation of ", entry);

  perform_relocation (bytes, entry->text_start_address, entry->header.a_text,
		      reloc, entry->header.a_trsize, entry);

  mywrite (bytes, 1, entry->header.a_text, outdesc);

  if (relocatable_output)
    entry->textrel = reloc;
}

void
write_data ()
{
  if (trace_files)
    fprintf (stderr, "Copying and relocating data:\n\n");

  each_file (copy_data);
  file_close ();

  if (trace_files)
    fprintf (stderr, "\n");

  padfile (data_pad, outdesc);
}

void
copy_data (entry)
     struct file_entry *entry;
{
  register struct relocation_info *reloc;
  register char *bytes = (char *) alloca (entry->header.a_data);
  register int desc;

  if (relocatable_output)
    reloc = (struct relocation_info *) xmalloc (entry->header.a_drsize);
  else
    reloc = (struct relocation_info *) alloca (entry->header.a_drsize);

  if (trace_files)
    prline_file_name (entry, stderr);

  desc = file_open (entry);

  lseek (desc, text_offset (entry) + entry->header.a_text, 0);
  if (entry->header.a_data != read (desc, bytes, entry->header.a_data))
    fatal_with_file ("premature eof in data section of ", entry);

  lseek (desc, text_offset (entry) + entry->header.a_text
		 + entry->header.a_data + entry->header.a_trsize,
	       0);
  if (entry->header.a_drsize != read (desc, reloc, entry->header.a_drsize))
    fatal_with_file ("premature eof in data relocation of ", entry);

  perform_relocation (bytes, entry->data_start_address - entry->header.a_text,
		      entry->header.a_data, reloc, entry->header.a_drsize, entry);

  mywrite (bytes, 1, entry->header.a_data, outdesc);

  if (relocatable_output)
    entry->datarel = reloc;
}

/* Relocate file 'entry''s text or data section contents.
 'data' is the address of the contents, in core.
 'data_size' is the length of the contents.
 'pc_relocation' is the difference between the address of the contents
  in the output file and its address in the input file.
 'reloc_info' is the address of the relocation info, in core.
 'reloc_size' is its length in bytes.  */

void
perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
     char *data;
     struct relocation_info *reloc_info;
     struct file_entry *entry;
     int pc_relocation;
     int data_size;
     int reloc_size;
{
  register struct relocation_info *p = reloc_info;
  struct relocation_info *end = reloc_info + reloc_size / sizeof (struct relocation_info);
  int text_relocation = entry->text_start_address;
  int data_relocation = entry->data_start_address - entry->header.a_text;
  int bss_relocation = entry->bss_start_address
			   - entry->header.a_text - entry->header.a_data;

  for (; p < end; p++)
    {
      register int relocation = 0;
      register int addr = p->r_address;
      register int symbolnum = p->r_symbolnum;
      register int length = p->r_length;

      if (addr >= data_size)
	fatal_with_file ("relocation address out of range in ", entry);
      if (p->r_extern)
	{
	  int symindex = symbolnum * sizeof (struct nlist);
	  if (symindex >= entry->header.a_syms)
	    fatal_with_file ("relocation symbolnum out of range in ", entry);

	  /* Don't perform external relocations if making relocatable output.
	     Leave them for the final link.  */

	  if (relocatable_output) continue;

	  relocation = ((symbol *)
			(((struct nlist *)
			  (((char *)entry->symbols) + symindex))
			 ->n_un.n_name))
		       ->value;
	}
      else switch (symbolnum)
	{
	case N_TEXT:
	case N_TEXT | N_EXT:
	  relocation = text_relocation;
	  break;

	case N_DATA:
	case N_DATA | N_EXT:
	  /* a word that points to beginning of the the data section
	    contains initially not zero but rather the "address" of that section
	    in the input file, which is the length of the file's text.  */
	  relocation = data_relocation;
	  break;

	case N_BSS:
	case N_BSS | N_EXT:
	  /* similarly, an input word pointing to the beginning of the bss
	     contains initially the length of the text and data of the file.  */
	  relocation = bss_relocation;
	  break;

	default:
	  fatal_with_file ("nonexternal relocation code invalid in ", entry);
	}

      if (p->r_pcrel)
	relocation -= pc_relocation;

      switch (length)
	{
	case 0:
	  *(char *) (data + addr) += relocation;
	  break;

	case 1:
	  *(short *) (data + addr) += relocation;
	  break;

	case 2:
	  *(int *) (data + addr) += relocation;
	  break;

	default:
	  fatal_with_file ("invalid relocation field length in ", entry);
	}
    }
}

/* For relocatable_output only: write out the relocation,
 relocating the addresses-to-be-relocated.  */

void coptxtrel (), copdatrel ();

void
wrtxtrel ()
{
  register int i;
  register int count = 0;

  if (trace_files)
    fprintf (stderr, "Writing text relocation:\n\n");

  /* Assign counts to all global syms in the order write_syms will write them.  */
  /* This is so we can store the proper symbolnum fields in relocation we write.  */

  for (i = 0; i < TABSIZE; i++)
    {
      symbol *sp;
      for (sp = symtab[i]; sp; sp = sp->link)
	if (sp->referenced || sp->defined)
	  sp->def_count = count++;
    }
  if (count != defined_global_sym_count + undefined_global_sym_count)
    fatal ("internal error");

  /* Write out the relocations of all files, remembered from copy_text.  */

  each_file (coptxtrel);
  file_close ();

  if (trace_files)
    fprintf (stderr, "\n");
}

void
coptxtrel (entry)
     struct file_entry *entry;
{
  register struct relocation_info *p, *end;
  register int reloc = entry->text_start_address;

  p = entry->textrel;
  end = (struct relocation_info *) (entry->header.a_trsize + (char *) p);
  while (p < end)
    {
      p->r_address += reloc;
      if (p->r_extern)
	{
	  register int symindex = p->r_symbolnum * sizeof (struct nlist);
	  if (symindex >= entry->header.a_syms)
	    fatal_with_file ("relocation symbolnum out of range in ", entry);
	  p->r_symbolnum = ((symbol *)
			    (((struct nlist *)
			      (((char *)entry->symbols) + symindex))
			     ->n_un.n_name))
			   ->def_count
			 + nsyms - defined_global_sym_count - undefined_global_sym_count;
	}
      p++;
    }
  mywrite (entry->textrel, 1, entry->header.a_trsize, outdesc);
}

void
wrdatrel ()
{
  if (trace_files)
    fprintf (stderr, "Writing data relocation:\n\n");

  each_file (copdatrel);
  file_close ();

  if (trace_files)
    fprintf (stderr, "\n");
}

void
copdatrel (entry)
     struct file_entry *entry;
{
  register struct relocation_info *p, *end;
  register int reloc = entry->data_start_address - entry->header.a_text;

  p = entry->datarel;
  end = (struct relocation_info *) (entry->header.a_drsize + (char *) p);
  while (p < end)
    {
      p->r_address += reloc;
      if (p->r_extern)
	{
	  register int symindex = p->r_symbolnum * sizeof (struct nlist);
	  if (symindex >= entry->header.a_syms)
	    fatal_with_file ("relocation symbolnum out of range in ", entry);
	  p->r_symbolnum = ((symbol *)
			    (((struct nlist *)
			      (((char *)entry->symbols) + symindex))
			     ->n_un.n_name))
			   ->def_count
			 + nsyms - defined_global_sym_count - undefined_global_sym_count;
	}
      p++;
    }
  mywrite (entry->datarel, 1, entry->header.a_drsize, outdesc);
}

void write_file_syms ();
void write_string_table ();

/* Offsets and current lengths of symbol and string tables in output file. */

int symbol_table_offset;
int symbol_table_len;
int string_table_offset;
int string_table_len;

/* total size of string table strings allocated so far */
int strtab_size;

/* Vector whose elements are the strings to go in the string table */
char **strtab_vector;

/* Vector whose elements are the lengths of the strings in the string table */
int *strtab_lens;

/* Index in strtab_vector at which the next string will be stored */
int strtab_index;

int
assign_string_table_index (name)
     char *name;
{
  register int index = strtab_size;
  register int len = strlen (name) + 1;

  strtab_size += len;
  strtab_vector[strtab_index] = name;
  strtab_lens[strtab_index++] = len;

  return index;
}

FILE *outstream = (FILE *) 0;

void
write_string_table ()
{
  register int i;

  lseek (outdesc, string_table_offset + string_table_len, 0);

  if (!outstream)
    outstream = fdopen (outdesc, "w");

  for (i = 0; i < strtab_index; i++)
    {
    fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
    string_table_len += strtab_lens[i];
  }

  fflush (outstream);
}

void
write_syms ()
{
  int syms_written = 0;
  register int i;
  struct nlist *buf = (struct nlist *) alloca ((defined_global_sym_count + undefined_global_sym_count) * sizeof (struct nlist));
  register struct nlist *bufp = buf;

  strtab_size = sizeof strtab_size; /* for the size, which will be prepended */

  symbol_table_offset = N_SYMOFF (outheader);
  symbol_table_len = 0;
  string_table_offset = N_STROFF (outheader);
  string_table_len = strtab_size;

  if (strip_symbols == 1)
    return;

  /* Write the local symbols defined by the various files.  */

  each_file (write_file_syms, &syms_written);

  /* Now write out the global symbols.  */

  strtab_vector = (char **) alloca (num_hash_tab_syms * sizeof (char *));
  strtab_lens = (int *) alloca (num_hash_tab_syms * sizeof (int));
  strtab_index = 0;

  for (i = 0; i < TABSIZE; i++)
    {
      register symbol *sp;
      for (sp = symtab[i]; sp; sp = sp->link)
	{
	  struct nlist nl;

	  nl.n_other = 0;
	  nl.n_desc = 0;

	  if (sp->defined || sp->referenced)
	    {
	      if (!sp->defined)		     /* undefined -- legit only if -r */
		{
		  nl.n_type = N_UNDF | N_EXT;
		  nl.n_value = 0;
		}
	      else if (sp->defined > 1)	     /* defined with known type */
		{
		  nl.n_type = sp->defined;
		  nl.n_value = sp->value;
		}
	      else if (sp->max_common_size)  /* happens only with -r and not -d */
		{			     /* defined as common but not allocated. */
		  nl.n_type = N_UNDF | N_EXT;  /* write out a common definition */
		  nl.n_value = sp->max_common_size;
		}
	      else
		fatal ("internal error: %s defined in mysterious way", sp->name);
	      nl.n_un.n_strx = assign_string_table_index (sp->name);
	      *bufp++ = nl;
	      syms_written++;
	    }
	}
    }

  lseek (outdesc, symbol_table_offset + symbol_table_len, 0);
  mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  symbol_table_len += sizeof (struct nlist) * (bufp - buf);

  if (syms_written != nsyms)
    fatal ("internal error: wrong number of symbols written into output file", 0);

  if (symbol_table_offset + symbol_table_len != string_table_offset)
    fatal ("internal error: inconsistent symbol table length", 0);

  /* now write the rest of the string table.  */

  mywrite (&strtab_size, sizeof (int), 1, outdesc);  /* we're at right place */
  write_string_table ();

}

/* write the local and debugger symbols of file 'entry' */

/* Note that we do not combine identical names of local symbols.
 dbx would be confused if we did that.  */

void
write_file_syms (entry, syms_written_addr)
     struct file_entry *entry;
     int *syms_written_addr;          /* Address of syms_written - so we can increment it */
{
  register struct nlist *p = entry->symbols;
  register struct nlist *end = p + entry->header.a_syms / sizeof (struct nlist);
  struct nlist *buf = (struct nlist *) alloca (entry->header.a_syms);
  register struct nlist *bufp = buf;
  int max_syms = (entry->header.a_syms / sizeof (struct nlist)) + 1;

  /* Add 1 to skip the "foo.o" symbol ld puts before the file's locals.  */
  entry->local_syms_offset = (*syms_written_addr + 1) * sizeof (struct nlist);

  entry->strings = (char *) alloca (entry->string_size);
  read_entry_strings (file_open (entry), entry);

  strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  strtab_lens = (int *) alloca (max_syms * sizeof (int));
  strtab_index = 0;

  /* If we want local symbols output, generate one for the start of this file's text.  */
  if (discard_locals != 2)
    {
      struct nlist nl;

      nl.n_type = N_TEXT;
      nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
      nl.n_value = entry->text_start_address;
      nl.n_desc = 0;
      nl.n_other = 0;
      *bufp++ = nl;
      (*syms_written_addr)++;
    }

  for (; p < end; p++)
    {
      register int type = p->n_type;
      register int write = 0;

      if (!(type & (N_STAB | N_EXT)))
        /* ordinary local symbol */
	write = (discard_locals != 2)
		&& !(discard_locals == 1 &&
		     (p->n_un.n_strx + entry->strings)[0] == 'L');
      else if (!(type & N_EXT))
	/* debugger symbol */
        write = (strip_symbols == 0);

      if (write)
	{
	  if (p->n_un.n_strx)
	    p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx +
							entry->strings);

	  *bufp++ = *p;
	  (*syms_written_addr)++;
	}
    }

  lseek (outdesc, symbol_table_offset + symbol_table_len, 0); 
  mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  symbol_table_len += sizeof (struct nlist) * (bufp - buf);

  write_string_table ();
}

void write_file_symseg ();

write_symsegs ()
{
  each_file (write_file_symseg, 0);
}

void
write_file_symseg (entry)
     struct file_entry *entry;
{
  char buffer[4096];
  struct symbol_root root;
  int indesc;
  int len;
  int total;

  if (entry->symseg_offset == 0)
    return;

  indesc = file_open (entry);
  lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  if (sizeof root != read (indesc, &root, sizeof root))
    fatal_with_file ("premature end of file in symbol segment of ", entry);

  root.ldsymoff = entry->local_syms_offset;
  root.textrel = entry->text_start_address;
  root.datarel = entry->data_start_address - entry->header.a_text;
  root.bssrel = entry->bss_start_address
    - entry->header.a_text - entry->header.a_data;

  mywrite (&root, sizeof root, 1, outdesc);

  if (entry->superfile)
    {
      total = entry->total_size - entry->symseg_offset - sizeof root;

      while (total > 0 && (len = read (indesc, buffer, min (sizeof buffer, total))))
	{
	  if (len != min (sizeof buffer, total))
	    fatal_with_file ("premature end of file in symbol segment of ", entry);
	  total -= len;
	  mywrite (buffer, len, 1, outdesc);
	}
    }
  else
    {
      while (len = read (indesc, buffer, sizeof buffer))
	{
	  mywrite (buffer, len, 1, outdesc);
	  if (len < sizeof buffer)
	    break;
	}
    }

  file_close (indesc);
}

/* create and initialize the symbol hash table */

symtab_init()
{
  register int *p, *endp;
  symtab = (symbol **) xmalloc (TABSIZE * sizeof (symbol *));

  p = (int *) symtab;
  endp = (int *) (symtab + TABSIZE);

  while (p < endp) *p++ = 0;
}


/* compute a hash code for a string */

int
hash_string(key)
char *key;
{
  register char *cp;
  register int k;

  cp = key;
  k = 0;
  while (*cp)
    k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;

  return k;
}


/* get the symbol entry for a given string.  Create one if there is none.  */

symbol *
getsym(key)
     char *key;
{
  register int hashval;
  register symbol *bp;
  register int found;

  hashval = hash_string (key) % TABSIZE;
  bp = symtab[hashval];

  found = 0;
  while (bp != NULL && found == 0)
    {
      if (strcmp (key, bp->name) == 0)
	found = 1;
      else
	bp = bp->link;
    }

  if (found == 0)
    {
      bp = (symbol *) xmalloc (sizeof (symbol));
      bp->link = symtab[hashval];
      bp->refs = 0;
      bp->name = (char *) xmalloc (strlen (key) + 1);
      strcpy (bp->name, key);
      bp->defined = 0;
      bp->referenced = 0;
      bp->trace = 0;
      bp->value = 0;
      bp->max_common_size = 0;

      symtab[hashval] = bp;

      ++num_hash_tab_syms;
    }

  return (bp);
}

/* Like getsym but return 0 if the symbol is not already known.  */

symbol *
getsym_soft(key)
     char *key;
{
  register int hashval;
  register symbol *bp;
  register int found;

  hashval = hash_string (key) % TABSIZE;
  bp = symtab[hashval];

  found = 0;
  while (bp != NULL && found == 0)
    {
      if (strcmp (key, bp->name) == 0)
	found = 1;
      else
	bp = bp->link;
    }

  if (found) return (bp);
  return 0;
}

/* Report a fatal error.  'string' is a printf format string and 'arg' is one arg for it.  */

fatal (string, arg)
     char *string, *arg;
{
  fprintf (stderr, "ld: ");
  fprintf (stderr, string, arg);
  fprintf (stderr, "\n");
  exit (1);
}

/* Report a fatal error.  'string' is printed, followed by the filename of 'entry'.  */

fatal_with_file (string, entry)
     char *string;
     struct file_entry *entry;
{
  fprintf (stderr, "ld: ");
  fprintf (stderr, string);
  print_file_name (entry, stderr);
  fprintf (stderr, "\n");
  exit (1);
}

/* Report a fatal error using the message for the last failed system call,
 followed by the string 'name'.  */

perror_name (name)
     char *name;
{
  extern int errno, sys_nerr;
  extern char *sys_errlist[];
  char *s;

  if (errno < sys_nerr)
    s = concat ("", sys_errlist[errno], " for %s");
  else
    s = "cannot open %s";
  fatal (s, name);
}

/* Report a fatal error using the message for the last failed system call,
 followed by the name of file 'entry'.  */

perror_file (entry)
     struct file_entry *entry;
{
  extern int errno, sys_nerr;
  extern char *sys_errlist[];
  char *s;

  if (errno < sys_nerr)
    s = concat ("", sys_errlist[errno], " for ");
  else
    s = "cannot open ";
  fatal_with_file (s, entry);
}

/* Report a nonfatal error.
 'string' is a format for printf, and 'arg1' ... 'arg3' are args for it.  */

error (string, arg1, arg2, arg3)
     char *string, *arg1, *arg2, *arg3;
{
  fprintf (stderr, string, arg1, arg2, arg3);
  fprintf (stderr, "\n");
}

/* Output data, compatible calling sequence with fwrite */

mywrite (buf, count, eltsize, desc)
     char *buf;
     int count;
     int eltsize;
     int desc;
{
  register int val;
  register int bytes = count * eltsize;

  while (bytes > 0)
    {
      val = write (desc, buf, bytes);
      if (val <= 0)
	perror_name (output_filename);
      buf += val;
      bytes -= val;
    }
}

/* Output 'padding' zero-bytes to 'outdesc' */

void
padfile (padding, outdesc)
     int padding;
     int outdesc;
{
  register char *buf = (char *) alloca (padding);
  bzero (buf, padding);
  mywrite (buf, padding, 1, outdesc);
}

/* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */

char *
concat (s1, s2, s3)
     char *s1, *s2, *s3;
{
  register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);

  strcpy (result, s1);
  strcpy (result + len1, s2);
  strcpy (result + len1 + len2, s3);
  *(result + len1 + len2 + len3) = 0;

  return result;
}

/* parse the string 'arg' using scanf format 'format', and return the result.
 If it does not parse, report fatal error with format string 'error' and 'arg' as arg.  */

int
parse (arg, format, error)
     char *arg, *format;
{
  int x;
  if (1 != sscanf (arg, format, &x))
    fatal (error, arg);
  return x;
}

/* Like malloc but get fatal error if memory is exhausted.  */
int
xmalloc (size)
     int size;
{
  register int result = malloc (size);
  if (!result)
    fatal ("virtual memory exhausted", 0);
  return result;

}

/*
Local variables:
compile-command: "cc -g -o ld ld.c"
End:
*/
