home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / GCC 1.37.1r14 / usr / lib / (loader.π) / loader.cp next >
Encoding:
Text File  |  1993-10-07  |  71.7 KB  |  2,381 lines  |  [TEXT/CPED]

  1. #define SystemSixOrLater 1
  2. #include <Types.h>
  3. #include <Errors.h>
  4. #include <Memory.h>
  5. #include <OSUtils.h>
  6. #include <SegLoad.h>
  7. #include <Quickdraw.h>
  8. #include <Files.h>
  9. #include <Menus.h>
  10. #include <Fonts.h>
  11. #include <Resources.h>
  12. #include <GestaltEqu.h>
  13. #include <Traps.h>
  14.  
  15. #define TrapMask 0x0800
  16.  
  17. short NumToolboxTraps( void )
  18. {
  19.     if (NGetTrapAddress(_InitGraf, ToolTrap) ==
  20.             NGetTrapAddress(0xAA6E, ToolTrap))
  21.         return(0x0200);
  22.     else
  23.         return(0x0400);
  24. }
  25.  
  26. TrapType GetTrapType(short theTrap)
  27. {
  28.  
  29.     if ((theTrap & TrapMask) > 0)
  30.         return(ToolTrap);
  31.     else
  32.         return(OSTrap);
  33.  
  34. }
  35.  
  36. Boolean TrapAvailable(short theTrap)
  37. {
  38.  
  39.     TrapType    tType;
  40.  
  41.     tType = GetTrapType(theTrap);
  42.     if (tType == ToolTrap)
  43.     theTrap = theTrap & 0x07FF;
  44.     if (theTrap >= NumToolboxTraps())
  45.         theTrap = _Unimplemented;
  46.  
  47.     return (NGetTrapAddress(theTrap, tType) !=
  48.             NGetTrapAddress(_Unimplemented, ToolTrap));
  49. }
  50.  
  51. // FlushCache
  52. // Flush the CPU cache(s). This is required on the 68040 after modifying
  53. // code.
  54.  
  55. #define _CacheFlushTrap    0xA0BD
  56.  
  57. void FlushCache(void)
  58. {
  59.     if (TrapAvailable( _CacheFlushTrap))
  60.         asm
  61.         {
  62.             dc.w _CacheFlushTrap
  63.         }
  64. }
  65.  
  66. /* Linker `ld' for GNU
  67.    Copyright (C) 1988 Free Software Foundation, Inc.
  68.  
  69.    This program is free software; you can redistribute it and/or modify
  70.    it under the terms of the GNU General Public License as published by
  71.    the Free Software Foundation; either version 1, or (at your option)
  72.    any later version.
  73.  
  74.    This program is distributed in the hope that it will be useful,
  75.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  76.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  77.    GNU General Public License for more details.
  78.  
  79.    You should have received a copy of the GNU General Public License
  80.    along with this program; if not, write to the Free Software
  81.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  82.  
  83. /* Written by Richard Stallman with some help from Eric Albert.
  84.    Set, indirect, and warning ld_symbol features added by Randy Smith.  */
  85.    
  86. /* Define how to initialize system-dependent header fields.  */
  87. #ifdef sun
  88. /* Use Sun's TARGET convention.  */
  89. #ifndef TARGET
  90. #define SUN2 2
  91. #define SUN3 3
  92. #define SUN4 4
  93. #if defined(sparc)
  94. #define TARGET SUN4
  95. #else
  96. #if defined(mc68020) || defined(m68020)
  97. #define TARGET SUN3
  98. #else
  99. #define TARGET SUN2
  100. #endif
  101. #endif
  102. #else
  103. #define _CROSS_TARGET_ARCH TARGET  /* locate the correct a.out.h file */
  104. #endif
  105. #endif
  106.  
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <sys/file.h>
  110. #ifndef sony_news
  111. #include <sys/fcntl.h>
  112. #endif
  113.  
  114. #ifdef COFF_ENCAPSULATE
  115. #include "a.out.encap.h"
  116. #else
  117. #include <a.out.h>
  118. #endif
  119.  
  120. #ifndef N_SET_MAGIC
  121. #define N_SET_MAGIC(exec, val)  ((exec).a_magic = val)
  122. #endif
  123.  
  124. /* Always use the GNU version of debugging ld_symbol type codes, if possible.  */
  125.  
  126. #include "stab.h"
  127. #define CORE_ADDR unsigned long    /* For symseg.h */
  128. /* GDB symbol table format definitions.
  129.    Copyright (C) 1986, 1989 Free Software Foundation, Inc.
  130.    Hacked by Michael Tiemann (tiemann@mcc.com)
  131.  
  132. This file is part of GDB.
  133.  
  134. GDB is free software; you can redistribute it and/or modify
  135. it under the terms of the GNU General Public License as published by
  136. the Free Software Foundation; either version 1, or (at your option)
  137. any later version.
  138.  
  139. GDB is distributed in the hope that it will be useful,
  140. but WITHOUT ANY WARRANTY; without even the implied warranty of
  141. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  142. GNU General Public License for more details.
  143.  
  144. You should have received a copy of the GNU General Public License
  145. along with GDB; see the file COPYING.  If not, write to
  146. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  147.  
  148. /* Format of GDB symbol table data.
  149.    There is one symbol segment for each source file or
  150.    independant compilation.  These segments are simply concatenated
  151.    to form the GDB symbol table.  A zero word where the beginning
  152.    of a segment is expected indicates there are no more segments.
  153.  
  154. Format of a symbol segment:
  155.  
  156.    The symbol segment begins with a word containing 1
  157.    if it is in the format described here.  Other formats may
  158.    be designed, with other code numbers.
  159.  
  160.    The segment contains many objects which point at each other.
  161.    The pointers are offsets in bytes from the beginning of the segment.
  162.    Thus, each segment can be loaded into core and its pointers relocated
  163.    to make valid in-core pointers.
  164.  
  165.    All the data objects in the segment can be found indirectly from
  166.    one of them, the root object, of type `struct symbol_root'.
  167.    It appears at the beginning of the segment.
  168.  
  169.    The total size of the segment, in bytes, appears as the `length'
  170.    field of this object.  This size includes the size of the
  171.    root object.
  172.  
  173.    All the object data types are defined here to contain pointer types
  174.    appropriate for in-core use on a relocated symbol segment.
  175.    Casts to and from type int are required for working with
  176.    unrelocated symbol segments such as are found in the file.
  177.  
  178.    The ldsymaddr word is filled in by the loader to contain
  179.    the offset (in bytes) within the ld symbol table
  180.    of the first nonglobal symbol from this compilation.
  181.    This makes it possible to match those symbols
  182.    (which contain line number information) reliably with
  183.    the segment they go with.
  184.  
  185.    Core addresses within the program that appear in the symbol segment
  186.    are not relocated by the loader.  They are inserted by the assembler
  187.    and apply to addresses as output by the assembler, so GDB must
  188.    relocate them when it loads the symbol segment.  It gets the information
  189.    on how to relocate from the textrel, datarel, bssrel, databeg and bssbeg
  190.    words of the root object.
  191.  
  192.    The words textrel, datarel and bssrel
  193.    are filled in by ld with the amounts to relocate within-the-file
  194.    text, data and bss addresses by; databeg and bssbeg can be
  195.    used to tell which kind of relocation an address needs.  */
  196.  
  197. enum language {language_c};
  198.  
  199. struct symbol_root
  200. {
  201.   int format;            /* Data format version */
  202.   int length;            /* # bytes in this symbol segment */
  203.   int ldsymoff;            /* Offset in ld symtab of this file's syms */
  204.   int textrel;            /* Relocation for text addresses */
  205.   int datarel;            /* Relocation for data addresses */
  206.   int bssrel;            /* Relocation for bss addresses */
  207.   char *filename;        /* Name of main source file compiled */
  208.   char *filedir;        /* Name of directory it was reached from */
  209.   struct blockvector *blockvector; /* Vector of all symbol-naming blocks */
  210.   struct typevector *typevector; /* Vector of all data types */
  211.   enum language language;    /* Code identifying the language used */
  212.   char *version;        /* Version info.  Not fully specified */
  213.   char *compilation;        /* Compilation info.  Not fully specified */
  214.   int databeg;            /* Address within the file of data start */
  215.   int bssbeg;            /* Address within the file of bss start */
  216.   struct sourcevector *sourcevector; /* Vector of line-number info */
  217. };
  218.  
  219. /* All data types of symbols in the compiled program
  220.    are represented by `struct type' objects.
  221.    All of these objects are pointed to by the typevector.
  222.    The type vector may have empty slots that contain zero.  */
  223.  
  224. struct typevector
  225. {
  226.   int length;            /* Number of types described */
  227.   struct type *type[1];
  228. };
  229.  
  230. /* Different kinds of data types are distinguished by the `code' field.  */
  231.  
  232. enum type_code
  233. {
  234.   TYPE_CODE_UNDEF,        /* Not used; catches errors */
  235.   TYPE_CODE_PTR,        /* Pointer type */
  236.   TYPE_CODE_ARRAY,        /* Array type, lower bound zero */
  237.   TYPE_CODE_STRUCT,        /* C struct or Pascal record */
  238.   TYPE_CODE_UNION,        /* C union or Pascal variant part */
  239.   TYPE_CODE_ENUM,        /* Enumeration type */
  240.   TYPE_CODE_FUNC,        /* Function type */
  241.   TYPE_CODE_INT,        /* Integer type */
  242.   TYPE_CODE_FLT,        /* Floating type */
  243.   TYPE_CODE_VOID,        /* Void type (values zero length) */
  244.   TYPE_CODE_SET,        /* Pascal sets */
  245.   TYPE_CODE_RANGE,        /* Range (integers within spec'd bounds) */
  246.   TYPE_CODE_PASCAL_ARRAY,    /* Array with explicit type of index */
  247.  
  248.   /* C++ */
  249.   TYPE_CODE_MEMBER,        /* Member type */
  250.   TYPE_CODE_METHOD,        /* Method type */
  251.   TYPE_CODE_REF        /* C++ Reference types */
  252. };
  253.  
  254. /* This appears in a type's flags word for an unsigned integer type.  */
  255. #define TYPE_FLAG_UNSIGNED 1
  256. /* This appears in a type's flags word
  257.    if it is a (pointer to a|function returning a)* built in scalar type.
  258.    These types are never freed.  */
  259. #define TYPE_FLAG_PERM 4
  260. /* This appears in a type's flags word if it is a stub type (eg. if
  261.    someone referenced a type that wasn't definined in a source file
  262.    via (struct sir_not_appearing_in_this_film *)).  */
  263. #define TYPE_FLAG_STUB 8
  264. /* Set when a classic has a constructor defined */
  265. #define    TYPE_FLAG_HAS_CONSTRUCTOR    256
  266. /* Set when a classic has a destructor defined */
  267. #define    TYPE_FLAG_HAS_DESTRUCTOR    512
  268. /* Indicates that this type is a public baseclass of another classic,
  269.    i.e. that all its public methods are available in the derived
  270.    classic. */
  271. #define    TYPE_FLAG_VIA_PUBLIC        1024
  272. /* Indicates that this type is a virtual baseclass of another classic,
  273.    i.e. that if this classic is inherited more than once by another
  274.    classic, only one set of member variables will be included. */ 
  275. #define    TYPE_FLAG_VIA_VIRTUAL        2048
  276.  
  277. struct type
  278. {
  279.   /* Code for kind of type */
  280.   enum type_code code;
  281.   /* Name of this type, or zero if none.
  282.      This is used for printing only.
  283.      Type names specified as input are defined by symbols.  */
  284.   char *name;
  285.   /* Length in bytes of storage for a value of this type */
  286.   int length;
  287.   /* For a pointer type, describes the type of object pointed to.
  288.      For an array type, describes the type of the elements.
  289.      For a function or method type, describes the type of the value.
  290.      For a range type, describes the type of the full range.
  291.      Unused otherwise.  */
  292.   struct type *target_type;
  293.   /* Type that is a pointer to this type.
  294.      Zero if no such pointer-to type is known yet.
  295.      The debugger may add the address of such a type
  296.      if it has to construct one later.  */ 
  297.   struct type *pointer_type;
  298.   /* C++: also need a reference type.  */
  299.   struct type *reference_type;
  300.   struct type **arg_types;
  301.   
  302.   /* Type that is a function returning this type.
  303.      Zero if no such function type is known here.
  304.      The debugger may add the address of such a type
  305.      if it has to construct one later.  */
  306.   struct type *function_type;
  307.  
  308. /* Handling of pointers to members:
  309.    TYPE_MAIN_VARIANT is used for pointer and pointer
  310.    to member types.  Normally it the value of the address of its
  311.    containing type.  However, for pointers to members, we must be
  312.    able to allocate pointer to member types and look them up
  313.    from some place of reference.
  314.    NEXT_VARIANT is the next element in the chain. */
  315.   struct type *main_variant, *next_variant;
  316.  
  317.   /* Flags about this type.  */
  318.   short flags;
  319.   /* Number of fields described for this type */
  320.   short nfields;
  321.   /* For structure and union types, a description of each field.
  322.      For set and pascal array types, there is one "field",
  323.      whose type is the domain type of the set or array.
  324.      For range types, there are two "fields",
  325.      the minimum and maximum values (both inclusive).
  326.      For enum types, each possible value is described by one "field".
  327.  
  328.      Using a pointer to a separate array of fields
  329.      allows all types to have the same size, which is useful
  330.      because we can allocate the space for a type before
  331.      we know what to put in it.  */
  332.   struct field
  333.     {
  334.       /* Position of this field, counting in bits from start of
  335.      containing structure.  For a function type, this is the
  336.      position in the argument list of this argument.
  337.      For a range bound or enum value, this is the value itself.  */
  338.       int bitpos;
  339.       /* Size of this field, in bits, or zero if not packed.
  340.      For an unpacked field, the field's type's length
  341.      says how many bytes the field occupies.  */
  342.       int bitsize;
  343.       /* In a struct or enum type, type of this field.
  344.      In a function type, type of this argument.
  345.      In an array type, the domain-type of the array.  */
  346.       struct type *type;
  347.       /* Name of field, value or argument.
  348.      Zero for range bounds and array domains.  */
  349.       char *name;
  350.     } *fields;
  351.  
  352.   /* C++ */
  353.   int *private_field_bits;
  354.   int *protected_field_bits;
  355.  
  356.   /* Number of methods described for this type */
  357.   short nfn_fields;
  358.   /* Number of base classes this type derives from. */
  359.   short n_baseclasses;
  360.  
  361.   /* Number of methods described for this type plus all the
  362.      methods that it derives from.  */
  363.   int nfn_fields_total;
  364.  
  365.   /* For classes, structures, and unions, a description of each field,
  366.      which consists of an overloaded name, followed by the types of
  367.      arguments that the method expects, and then the name after it
  368.      has been renamed to make it distinct.  */
  369.   struct fn_fieldlist
  370.     {
  371.       /* The overloaded name.  */
  372.       char *name;
  373.       /* The number of methods with this name.  */
  374.       int length;
  375.       /* The list of methods.  */
  376.       struct fn_field
  377.     {
  378. #if 0
  379.       /* The overloaded name */
  380.       char *name;
  381. #endif
  382.       /* The return value of the method */
  383.       struct type *type;
  384.       /* The argument list */
  385.       struct type **args;
  386.       /* The name after it has been processed */
  387.       char *physname;
  388.       /* If this is a virtual function, the offset into the vtbl-1,
  389.          else 0.  */
  390.       int voffset;
  391.     } *fn_fields;
  392.  
  393.       int *private_fn_field_bits;
  394.       int *protected_fn_field_bits;
  395.  
  396.     } *fn_fieldlists;
  397.  
  398.   unsigned char via_protected;
  399.   unsigned char via_public;
  400.  
  401.   /* For types with virtual functions, VPTR_BASETYPE is the base classic which
  402.      defined the virtual function table pointer.  VPTR_FIELDNO is
  403.      the field number of that pointer in the structure.
  404.  
  405.      For types that are pointer to member types, VPTR_BASETYPE
  406.      ifs the type that this pointer is a member of.
  407.  
  408.      Unused otherwise.  */
  409.   struct type *vptr_basetype;
  410.  
  411.   int vptr_fieldno;
  412.  
  413.   /* If this type has a base classic, put it here.
  414.      If this type is a pointer type, the chain of member pointer
  415.      types goes here.
  416.      Unused otherwise.
  417.      
  418.      Contrary to all maxims of C style and common sense, the baseclasses
  419.      are indexed from 1 to N_BASECLASSES rather than 0 to N_BASECLASSES-1
  420.      (i.e. BASECLASSES points to one *before* the first element of
  421.      the array).  */
  422.   struct type **baseclasses;
  423. };
  424.  
  425. /* All of the name-scope contours of the program
  426.    are represented by `struct block' objects.
  427.    All of these objects are pointed to by the blockvector.
  428.  
  429.    Each block represents one name scope.
  430.    Each lexical context has its own block.
  431.  
  432.    The first two blocks in the blockvector are special.
  433.    The first one contains all the symbols defined in this compilation
  434.    whose scope is the entire program linked together.
  435.    The second one contains all the symbols whose scope is the
  436.    entire compilation excluding other separate compilations.
  437.    In C, these correspond to global symbols and static symbols.
  438.  
  439.    Each block records a range of core addresses for the code that
  440.    is in the scope of the block.  The first two special blocks
  441.    give, for the range of code, the entire range of code produced
  442.    by the compilation that the symbol segment belongs to.
  443.  
  444.    The blocks appear in the blockvector
  445.    in order of increasing starting-address,
  446.    and, within that, in order of decreasing ending-address.
  447.  
  448.    This implies that within the body of one function
  449.    the blocks appear in the order of a depth-first tree walk.  */
  450.  
  451. struct blockvector
  452. {
  453.   /* Number of blocks in the list.  */
  454.   int nblocks;
  455.   /* The blocks themselves.  */
  456.   struct block *block[1];
  457. };
  458.  
  459. struct block
  460. {
  461.   /* Addresses in the executable code that are in this block.
  462.      Note: in an unrelocated symbol segment in a file,
  463.      these are always zero.  They can be filled in from the
  464.      N_LBRAC and N_RBRAC symbols in the loader symbol table.  */
  465.   int startaddr, endaddr;
  466.   /* The symbol that names this block,
  467.      if the block is the body of a function;
  468.      otherwise, zero.
  469.      Note: In an unrelocated symbol segment in an object file,
  470.      this field may be zero even when the block has a name.
  471.      That is because the block is output before the name
  472.      (since the name resides in a higher block).
  473.      Since the symbol does point to the block (as its value),
  474.      it is possible to find the block and set its name properly.  */
  475.   struct symbol *function;
  476.   /* The `struct block' for the containing block, or 0 if none.  */
  477.   /* Note that in an unrelocated symbol segment in an object file
  478.      this pointer may be zero when the correct value should be
  479.      the second special block (for symbols whose scope is one compilation).
  480.      This is because the compiler ouptuts the special blocks at the
  481.      very end, after the other blocks.   */
  482.   struct block *superblock;
  483.   /* A flag indicating whether or not the fucntion corresponding
  484.      to this block was compiled with gcc or not.  If there is no
  485.      function corresponding to this block, this meaning of this flag
  486.      is undefined.  (In practice it will be 1 if the block was created
  487.      while processing a file compiled with gcc and 0 when not). */
  488.   unsigned char gcc_compile_flag;
  489.   /* Number of local symbols.  */
  490.   int nsyms;
  491.   /* The symbols.  */
  492.   struct symbol *sym[1];
  493. };
  494.  
  495. /* Represent one symbol name; a variable, constant, function or typedef.  */
  496.  
  497. /* Different name spaces for symbols.  Looking up a symbol specifies
  498.    a namespace and ignores symbol definitions in other name spaces.
  499.  
  500.    VAR_NAMESPACE is the usual namespace.
  501.    In C, this contains variables, function names, typedef names
  502.    and enum type values.
  503.  
  504.    STRUCT_NAMESPACE is used in C to hold struct, union and enum type names.
  505.    Thus, if `struct foo' is used in a C program,
  506.    it produces a symbol named `foo' in the STRUCT_NAMESPACE.
  507.  
  508.    LABEL_NAMESPACE may be used for names of labels (for gotos);
  509.    currently it is not used and labels are not recorded at all.  */
  510.  
  511. /* For a non-global symbol allocated statically,
  512.    the correct core address cannot be determined by the compiler.
  513.    The compiler puts an index number into the symbol's value field.
  514.    This index number can be matched with the "desc" field of
  515.    an entry in the loader symbol table.  */
  516.  
  517. enum namespace
  518. {
  519.   UNDEF_NAMESPACE, VAR_NAMESPACE, STRUCT_NAMESPACE, LABEL_NAMESPACE
  520. };
  521.  
  522. /* An address-classic says where to find the value of the symbol in core.  */
  523.  
  524. enum address_class
  525. {
  526.   LOC_UNDEF,        /* Not used; catches errors */
  527.   LOC_CONST,        /* Value is constant int */
  528.   LOC_STATIC,        /* Value is at fixed address */
  529.   LOC_REGISTER,        /* Value is in register */
  530.   LOC_ARG,        /* Value is at spec'd position in arglist */
  531.   LOC_REF_ARG,        /* Value address is at spec'd position in */
  532.             /* arglist.  */
  533.   LOC_REGPARM,        /* Value is at spec'd position in  register window */
  534.   LOC_LOCAL,        /* Value is at spec'd pos in stack frame */
  535.   LOC_TYPEDEF,        /* Value not used; definition in SYMBOL_TYPE
  536.                Symbols in the namespace STRUCT_NAMESPACE
  537.                all have this classic.  */
  538.   LOC_LABEL,        /* Value is address in the code */
  539.   LOC_BLOCK,        /* Value is address of a `struct block'.
  540.                Function names have this classic.  */
  541.   LOC_EXTERNAL,        /* Value is at address not in this compilation.
  542.                This is used for .comm symbols
  543.                and for extern symbols within functions.
  544.                Inside GDB, this is changed to LOC_STATIC once the
  545.                real address is obtained from a loader symbol.  */
  546.   LOC_CONST_BYTES    /* Value is a constant byte-sequence.   */
  547. };
  548.  
  549. struct symbol
  550. {
  551.   /* Symbol name */
  552.   char *name;
  553.   /* Name space code.  */
  554.   enum namespace namespace;
  555.   /* Address classic */
  556.   enum address_class classic;
  557.   /* Data type of value */
  558.   struct type *type;
  559.   /* constant value, or address if static, or register number,
  560.      or offset in arguments, or offset in stack frame.  */
  561.   union
  562.     {
  563.       long value;
  564.       struct block *block;      /* for LOC_BLOCK */
  565.       char *bytes;        /* for LOC_CONST_BYTES */
  566.     }
  567.   value;
  568. };
  569.  
  570. struct partial_symbol
  571. {
  572.   /* Symbol name */
  573.   char *name;
  574.   /* Name space code.  */
  575.   enum namespace namespace;
  576.   /* Address classic (for info_symbols) */
  577.   enum address_class classic;
  578.   /* Value (only used for static functions currently).  Done this
  579.      way so that we can use the struct symbol macros.
  580.      Note that the address of a function is SYMBOL_VALUE (pst)
  581.      in a partial symbol table, but BLOCK_START (SYMBOL_BLOCK_VALUE (st))
  582.      in a symbol table.  */
  583.   union
  584.     {
  585.       long value;
  586.     }
  587.   value;
  588. };
  589.  
  590. /* 
  591.  * Vectors of all partial symbols read in from file; actually declared
  592.  * and used in dbxread.c.
  593.  */
  594. extern struct psymbol_allocation_list {
  595.   struct partial_symbol *list, *next;
  596.   int size;
  597. } global_psymbols, static_psymbols;
  598.  
  599.  
  600. /* Source-file information.
  601.    This describes the relation between source files and line numbers
  602.    and addresses in the program text.  */
  603.  
  604. struct sourcevector
  605. {
  606.   int length;            /* Number of source files described */
  607.   struct source *source[1];    /* Descriptions of the files */
  608. };
  609.  
  610. /* Each item represents a line-->pc (or the reverse) mapping.  This is
  611.    somewhat more wasteful of space than one might wish, but since only
  612.    the files which are actually debugged are read in to core, we don't
  613.    waste much space.
  614.  
  615.    Each item used to be an int; either minus a line number, or a
  616.    program counter.  If it represents a line number, that is the line
  617.    described by the next program counter value.  If it is positive, it
  618.    is the program counter at which the code for the next line starts.  */
  619.  
  620. struct linetable_entry
  621. {
  622.   int line;
  623.   CORE_ADDR pc;
  624. };
  625.  
  626. struct linetable
  627. {
  628.   int nitems;
  629.   struct linetable_entry item[1];
  630. };
  631.  
  632. /* All the information on one source file.  */
  633.  
  634. struct source
  635. {
  636.   char *name;            /* Name of file */
  637.   struct linetable contents;
  638. };
  639.  
  640. /*
  641. #ifdef USG
  642. #include <string.h>
  643. #else
  644. #include <strings.h>
  645. #endif
  646. */
  647.  
  648. #define min(a,b) ((a) < (b) ? (a) : (b))
  649.  
  650. /* Macro to control the number of undefined references printed */
  651. #define MAX_UREFS_PRINTED    10
  652.  
  653. /*
  654.  * Ok.  Following are the relocation information macros.  If your
  655.  * system should not be able to use the default set (below), you must
  656.  * define the following:
  657.  
  658.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  659.  * of structure that is stored in the relocation info section of your
  660.  * a.out files.  Often this is defined in the a.out.h for your system.
  661.  *
  662.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  663.  * <whatever> to be relocated.  *Must be an lvalue*.
  664.  *
  665.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  666.  * external ld_symbol (1), or was it fully resolved upon entering the
  667.  * loader (0) in which case some combination of the value in memory
  668.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  669.  * what the value of the relocation actually was.  *Must be an lvalue*.
  670.  *
  671.  *   RELOC_TYPE (rval): If this entry was fully resolved upon
  672.  * entering the loader, what type should it be relocated as?
  673.  *
  674.  *   RELOC_SYMBOL (rval): If this entry was not fully resolved upon
  675.  * entering the loader, what is the index of it's ld_symbol in the ld_symbol
  676.  * table?  *Must be a lvalue*.
  677.  *
  678.  *   RELOC_MEMORY_ADD_P (rval): This should return true if the final
  679.  * relocation value output here should be added to memory, or if the
  680.  * section of memory described should simply be set to the relocation
  681.  * value.
  682.  *
  683.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  684.  * an extra value to be added to the relocation value based on the
  685.  * individual relocation entry.  *Must be an lvalue if defined*.
  686.  *
  687.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  688.  * pc relative.
  689.  *
  690.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  691.  * final relocation value before putting it where it belongs.
  692.  *
  693.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  694.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  695.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  696.  * do everything in terms of the bit operators below), but having this
  697.  * macro could end up producing better code on machines without fancy
  698.  * bit twiddling.  Also, it's easier to understand/code big/little
  699.  * endian distinctions with this macro.
  700.  *
  701.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  702.  * object described in RELOC_TARGET_SIZE in which the relocation value
  703.  * will go.
  704.  *
  705.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  706.  * with the bits of the relocation value.  It may be assumed by the
  707.  * code that the relocation value will fit into this many bits.  This
  708.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  709.  *
  710.  *
  711.  *        Things I haven't implemented
  712.  *        ----------------------------
  713.  *
  714.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  715.  *
  716.  *    Pc relative relocation for External references.
  717.  *
  718.  *
  719.  */
  720.  
  721. /* The following #if has been modifed for cross compilation */
  722. /* It originally ld_read:  #if defined(sun) && defined(sparc)  */
  723. /* Marc Ullman, Stanford University    Nov. 1 1989  */
  724. #if defined(sun) && (TARGET == SUN4)
  725. /* Sparc (Sun 4) macros */
  726. #undef relocation_info
  727. #define relocation_info                    reloc_info_sparc
  728. #define RELOC_ADDRESS(r)        ((r)->r_address)
  729. #define RELOC_EXTERN_P(r)               ((r)->r_extern)
  730. #define RELOC_TYPE(r)                   ((r)->r_index)
  731. #define RELOC_SYMBOL(r)                 ((r)->r_index)
  732. #define RELOC_MEMORY_SUB_P(r)        0
  733. #define RELOC_MEMORY_ADD_P(r)           0
  734. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)
  735. #define RELOC_PCREL_P(r)             \
  736.         ((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22)
  737. #define RELOC_VALUE_RIGHTSHIFT(r)       (reloc_target_rightshift[(r)->r_type])
  738. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(r)->r_type])
  739. #define RELOC_TARGET_BITPOS(r)          0
  740. #define RELOC_TARGET_BITSIZE(r)         (reloc_target_bitsize[(r)->r_type])
  741.  
  742. /* Note that these are very dependent on the order of the enums in
  743.    enum reloc_type (in a.out.h); if they change the following must be
  744.    changed */
  745. /* Also note that the last few may be incorrect; I have no information */
  746. static int reloc_target_rightshift[] = {
  747.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  748. };
  749. static int reloc_target_size[] = {
  750.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  751. };
  752. static int reloc_target_bitsize[] = {
  753.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  754. };
  755.  
  756. #define    MAX_ALIGNMENT    (sizeof (double))
  757. #endif
  758. #ifdef sequent
  759. #define RELOC_ADDRESS(r)        ((r)->r_address)
  760. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  761. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  762. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  763. #define RELOC_MEMORY_SUB_P(r)    ((r)->r_bsr)
  764. #define RELOC_MEMORY_ADD_P(r)    1
  765. #undef RELOC_ADD_EXTRA
  766. #define RELOC_PCREL_P(r)        ((r)->r_pcrel || (r)->r_bsr)
  767. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  768. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  769. #define RELOC_TARGET_BITPOS(r)    0
  770. #define RELOC_TARGET_BITSIZE(r)    32
  771. #endif
  772.  
  773. /* Default macros */
  774. #ifndef RELOC_ADDRESS
  775. #define RELOC_ADDRESS(r)        ((r)->r_address)
  776. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  777. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  778. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  779. #define RELOC_MEMORY_SUB_P(r)    0
  780. #define RELOC_MEMORY_ADD_P(r)    1
  781. #undef RELOC_ADD_EXTRA
  782. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  783. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  784. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  785. #define RELOC_TARGET_BITPOS(r)    0
  786. #define RELOC_TARGET_BITSIZE(r)    32
  787. #endif
  788.  
  789. #ifndef MAX_ALIGNMENT
  790. #define    MAX_ALIGNMENT    (sizeof (int))
  791. #endif
  792.  
  793. #ifdef nounderscore
  794. #define LPREFIX '.'
  795. #else
  796. #define LPREFIX 'L'
  797. #endif
  798.  
  799. #ifndef TEXT_START
  800. #define TEXT_START(x) N_TXTADDR(x)
  801. #endif
  802.  
  803. /* Special global ld_symbol types understood by GNU LD.  */
  804.  
  805. /* The following type indicates the definition of a ld_symbol as being
  806.    an indirect reference to another ld_symbol.  The other ld_symbol
  807.    appears as an undefined reference, immediately following this ld_symbol.
  808.  
  809.    Indirection is asymmetrical.  The other ld_symbol's value will be used
  810.    to satisfy requests for the indirect ld_symbol, but not vice versa.
  811.    If the other ld_symbol does not have a definition, libraries will
  812.    be searched to find a definition.
  813.  
  814.    So, for example, the following two lines placed in an assembler
  815.    input file would result in an object file which would direct gnu ld
  816.    to resolve all references to ld_symbol "foo" as references to ld_symbol
  817.    "bar".
  818.  
  819.     .stabs "_foo",11,0,0,0
  820.     .stabs "_bar",1,0,0,0
  821.  
  822.    Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)).  */
  823.  
  824. #ifndef N_INDR
  825. #define N_INDR 0xa
  826. #endif
  827.  
  828. /* The following symbols refer to set elements.  These are expected
  829.    only in input to the loader; they should not appear in loader
  830.    output (unless relocatable output is requested).  To be recognized
  831.    by the loader, the input symbols must have their N_EXT bit set.
  832.    All the N_SET[ATDB] symbols with the same name form one set.  The
  833.    loader collects all of these elements at load time and outputs a
  834.    vector for each name.
  835.    Space (an array of 32 bit words) is allocated for the set in the
  836.    data section, and the n_value field of each set element value is
  837.    stored into one word of the array.
  838.    The first word of the array is the length of the set (number of
  839.    elements).  The last word of the vector is set to zero for possible
  840.    use by incremental loaders.  The array is ordered by the linkage
  841.    order; the first symbols which the linker encounters will be first
  842.    in the array.
  843.  
  844.    In C syntax this looks like:
  845.  
  846.     struct set_vector {
  847.       unsigned int length;
  848.       unsigned int vector[length];
  849.       unsigned int always_zero;
  850.     };
  851.  
  852.    Before being placed into the array, each element is relocated
  853.    according to its type.  This allows the loader to create an array
  854.    of pointers to objects automatically.  N_SETA type symbols will not
  855.    be relocated.
  856.  
  857.    The address of the set is made into an N_SETV ld_symbol
  858.    whose name is the same as the name of the set.
  859.    This ld_symbol acts like a N_DATA global ld_symbol
  860.    in that it can satisfy undefined external references.
  861.  
  862.    For the purposes of determining whether or not to load in a library
  863.    file, set element definitions are not considered "real
  864.    definitions"; they will not cause the loading of a library
  865.    member.
  866.  
  867.    If relocatable output is requested, none of this processing is
  868.    done.  The symbols are simply relocated and passed through to the
  869.    output file.
  870.  
  871.    So, for example, the following three lines of assembler code
  872.    (whether in one file or scattered between several different ones)
  873.    will produce a three element vector (total length is five words;
  874.    see above), referenced by the ld_symbol "_xyzzy", which will have the
  875.    addresses of the routines _init1, _init2, and _init3.
  876.  
  877.    *NOTE*: If symbolic addresses are used in the n_value field of the
  878.    defining .stabs, those symbols must be defined in the same file as
  879.    that containing the .stabs.
  880.  
  881.     .stabs "_xyzzy",23,0,0,_init1
  882.     .stabs "_xyzzy",23,0,0,_init2
  883.     .stabs "_xyzzy",23,0,0,_init3
  884.  
  885.    Note that (23 == (N_SETT | N_EXT)).  */
  886.  
  887. #ifndef N_SETA
  888. #define    N_SETA    0x14        /* Absolute set element ld_symbol */
  889. #endif                /* This is input to LD, in a .o file.  */
  890.  
  891. #ifndef N_SETT
  892. #define    N_SETT    0x16        /* Text set element ld_symbol */
  893. #endif                /* This is input to LD, in a .o file.  */
  894.  
  895. #ifndef N_SETD
  896. #define    N_SETD    0x18        /* Data set element ld_symbol */
  897. #endif                /* This is input to LD, in a .o file.  */
  898.  
  899. #ifndef N_SETB
  900. #define    N_SETB    0x1A        /* Bss set element ld_symbol */
  901. #endif                /* This is input to LD, in a .o file.  */
  902.  
  903. /* Macros dealing with the set element symbols defined in a.out.h */
  904. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  905. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  906.  
  907. #ifndef N_SETV
  908. #define N_SETV    0x1C        /* Pointer to set vector in data area.  */
  909. #endif                /* This is output from LD.  */
  910.  
  911. /* If a this type of ld_symbol is encountered, its name is a warning
  912.    message to print each time the ld_symbol referenced by the next ld_symbol
  913.    table entry is referenced.
  914.  
  915.    This feature may be used to allow backwards compatibility with
  916.    certain functions (eg. gets) but to discourage programmers from
  917.    their use.
  918.  
  919.    So if, for example, you wanted to have ld print a warning whenever
  920.    the function "gets" was used in their C program, you would add the
  921.    following to the assembler file in which gets is defined:
  922.  
  923.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  924.     .stabs "_gets",1,0,0,0
  925.  
  926.    These .stabs do not necessarily have to be in the same file as the
  927.    gets function, they simply must exist somewhere in the compilation.  */
  928.  
  929. #ifndef N_WARNING
  930. #define N_WARNING 0x1E        /* Warning message to print if ld_symbol
  931.                    included */
  932. #endif                /* This is input to ld */
  933.  
  934. #ifndef __GNU_STAB__
  935.  
  936. /* Line number for the data section.  This is to be used to describe
  937.    the source location of a variable declaration.  */
  938. #ifndef N_DSLINE
  939. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  940. #endif
  941.  
  942. /* Line number for the bss section.  This is to be used to describe
  943.    the source location of a variable declaration.  */
  944. #ifndef N_BSLINE
  945. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  946. #endif
  947.  
  948. #endif /* not __GNU_STAB__ */
  949.  
  950. /* Symbol table */
  951.  
  952. /* Global ld_symbol data is recorded in these structures,
  953.    one for each global ld_symbol.
  954.    They are found via hashing in 'symtab', which points to a vector of buckets.
  955.    Each bucket is a chain of these structures through the link field.  */
  956.  
  957. typedef
  958.   struct glosym
  959.     {
  960.       /* Pointer to next ld_symbol in this ld_symbol's hash bucket.  */
  961.       struct glosym *link;
  962.       /* Name of this ld_symbol.  */
  963.       char *name;
  964.       /* Value of this ld_symbol as a global ld_symbol.  */
  965.       long value;
  966.       /* Chain of external 'nlist's in files for this ld_symbol, both defs
  967.      and refs.  */
  968.       struct nlist *refs;
  969.       /* Any warning message that might be associated with this ld_symbol
  970.          from an N_WARNING ld_symbol encountered. */
  971.       char *warning;
  972.       /* Nonzero means definitions of this ld_symbol as common have been seen,
  973.      and the value here is the largest size specified by any of them.  */
  974.       int max_common_size;
  975.       /* For relocatable_output, records the index of this global sym in the
  976.      ld_symbol table to be written, with the first global sym given index 0.*/
  977.       int def_count;
  978.       /* Nonzero means a definition of this global ld_symbol is known to exist.
  979.      Library members should not be loaded on its account.  */
  980.       char defined;
  981.       /* Nonzero means a reference to this global ld_symbol has been seen
  982.      in a file that is surely being loaded.
  983.      A value higher than 1 is the n_type code for the ld_symbol's
  984.      definition.  */
  985.       char referenced;
  986.       /* A count of the number of undefined references printed for a
  987.      specific ld_symbol.  If a ld_symbol is unresolved at the end of
  988.      digest_symbols (and the loading run is supposed to produce
  989.      relocatable output) do_file_warnings keeps track of how many
  990.      unresolved reference error messages have been printed for
  991.      each ld_symbol here.  When the number hits MAX_UREFS_PRINTED,
  992.      messages stop. */
  993.       unsigned char undef_refs;
  994.       /* 1 means that this ld_symbol has multiple definitions.  2 means
  995.          that it has multiple definitions, and some of them are set
  996.      elements, one of which has been printed out already.  */
  997.       unsigned char multiply_defined;
  998.       /* Nonzero means print a message at all refs or defs of this ld_symbol */
  999.       char trace;
  1000.     }
  1001.   ld_symbol;
  1002.  
  1003. /* Demangler for C++. */
  1004. extern char *cplus_demangle ();
  1005.  
  1006. /* Demangler function to use. */
  1007. char *(*demangler)() = NULL;
  1008.  
  1009. /* Number of buckets in ld_symbol hash table */
  1010. #define    TABSIZE    1009
  1011.  
  1012. /* The ld_symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  1013. ld_symbol *symtab[TABSIZE];
  1014.  
  1015. /* Number of symbols in ld_symbol hash table. */
  1016. int num_hash_tab_syms = 0;
  1017.  
  1018. /* Count the number of nlist entries that are for local symbols.
  1019.    This count and the three following counts
  1020.    are incremented as as symbols are entered in the ld_symbol table.  */
  1021. int local_sym_count;
  1022.  
  1023. /* Count number of nlist entries that are for local symbols
  1024.    whose names don't start with L. */
  1025. int non_L_local_sym_count;
  1026.  
  1027. /* Count the number of nlist entries for debugger info.  */
  1028. int debugger_sym_count;
  1029.  
  1030. /* Count the number of global symbols referenced and not defined.  */
  1031. int undefined_global_sym_count;
  1032.  
  1033. /* Count the number of global symbols multiply defined.  */
  1034. int multiple_def_count;
  1035.  
  1036. /* Count the number of defined global symbols.
  1037.    Each ld_symbol is counted only once
  1038.    regardless of how many different nlist entries refer to it,
  1039.    since the output file will need only one nlist entry for it.
  1040.    This count is computed by `digest_symbols';
  1041.    it is undefined while symbols are being loaded. */
  1042. int defined_global_sym_count;
  1043.  
  1044. /* Count the number of symbols defined through common declarations.
  1045.    This count is kept in symdef_library, linear_library, and
  1046.    enter_global_ref.  It is incremented when the defined flag is set
  1047.    in a ld_symbol because of a common definition, and decremented when
  1048.    the ld_symbol is defined "for real" (ie. by something besides a common
  1049.    definition).  */
  1050. int common_defined_global_count;
  1051.  
  1052. /* Count the number of set element type symbols and the number of
  1053.    separate vectors which these symbols will fit into.  See the
  1054.    GNU a.out.h for more info.
  1055.    This count is computed by 'enter_file_symbols' */
  1056. int set_symbol_count;
  1057. int set_vector_count;
  1058.  
  1059. /* Define a linked list of strings which define symbols which should
  1060.    be treated as set elements even though they aren't.  Any ld_symbol
  1061.    with a prefix matching one of these should be treated as a set
  1062.    element.
  1063.  
  1064.    This is to make up for deficiencies in many assemblers which aren't
  1065.    willing to pass any stabs through to the loader which they don't
  1066.    understand.  */
  1067. struct string_list_element {
  1068.   char *str;
  1069.   struct string_list_element *next;
  1070. };
  1071.  
  1072. struct string_list_element *set_element_prefixes;
  1073.  
  1074. /* Count the number of definitions done indirectly (ie. done relative
  1075.    to the value of some other ld_symbol. */
  1076. int global_indirect_count;
  1077.  
  1078. /* Count the number of warning symbols encountered. */
  1079. int warning_count;
  1080.  
  1081. /* Total number of symbols to be written in the output file.
  1082.    Computed by digest_symbols from the variables above.  */
  1083. int nsyms;
  1084.  
  1085.  
  1086. /* Nonzero means ptr to ld_symbol entry for ld_symbol to use as start addr.
  1087.    -e sets this.  */
  1088. ld_symbol *entry_symbol;
  1089. ld_symbol *edata_symbol;   /* the ld_symbol _edata */
  1090. ld_symbol *etext_symbol;   /* the ld_symbol _etext */
  1091. ld_symbol *end_symbol;    /* the ld_symbol _end */
  1092. ld_symbol *qd_symbol;
  1093.  
  1094. /* Each input file, and each library member ("subfile") being loaded,
  1095.    has a `file_entry' structure for it.
  1096.  
  1097.    For files specified by command args, these are contained in the vector
  1098.    which `file_table' points to.
  1099.  
  1100.    For library members, they are dynamically allocated,
  1101.    and chained through the `chain' field.
  1102.    The chain is found in the `subfiles' field of the `file_entry'.
  1103.    The `file_entry' objects for the members have `superfile' fields pointing
  1104.    to the one for the library.  */
  1105.  
  1106. struct file_entry {
  1107.   /* Name of this file.  */
  1108.   char *filename;
  1109.   /* Name to use for the ld_symbol giving address of text start */
  1110.   /* Usually the same as filename, but for a file spec'd with -l
  1111.      this is the -l switch itself rather than the filename.  */
  1112.   char *local_sym_name;
  1113.  
  1114.   /* Describe the layout of the contents of the file */
  1115.  
  1116.   /* The file's a.out header.  */
  1117.   struct exec header;
  1118.   /* Offset in file of GDB ld_symbol segment, or 0 if there is none.  */
  1119.   int symseg_offset;
  1120.  
  1121.   /* Describe data from the file loaded into core */
  1122.  
  1123.   /* Symbol table of the file.  */
  1124.   struct nlist *symbols;
  1125.   /* Size in bytes of string table.  */
  1126.   int string_size;
  1127.   /* Pointer to the string table.
  1128.      The string table is not kept in core all the time,
  1129.      but when it is in core, its address is here.  */
  1130.   char *strings;
  1131.  
  1132.   /* Next two used only if `relocatable_output' or if needed for */
  1133.   /* output of undefined reference line numbers. */
  1134.  
  1135.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  1136.   struct relocation_info *textrel;
  1137.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  1138.   struct relocation_info *datarel;
  1139.  
  1140.   /* Relation of this file's segments to the output file */
  1141.  
  1142.   /* Start of this file's text seg in the output file core image.  */
  1143.   int text_start_address;
  1144.   /* Start of this file's data seg in the output file core image.  */
  1145.   int data_start_address;
  1146.   /* Start of this file's bss seg in the output file core image.  */
  1147.   int bss_start_address;
  1148.   /* Offset in bytes in the output file ld_symbol table
  1149.      of the first local ld_symbol for this file.  Set by `write_file_symbols'.  */
  1150.   int local_syms_offset;
  1151.  
  1152.   /* For library members only */
  1153.  
  1154.   /* For a library, points to chain of entries for the library members.  */
  1155.   struct file_entry *subfiles;
  1156.   /* For a library member, offset of the member within the archive.
  1157.      Zero for files that are not library members.  */
  1158.   int starting_offset;
  1159.   /* Size of contents of this file, if library member.  */
  1160.   int total_size;
  1161.   /* For library member, points to the library's own entry.  */
  1162.   struct file_entry *superfile;
  1163.   /* For library member, points to next entry for next member.  */
  1164.   struct file_entry *chain;
  1165.  
  1166.   /* 1 if file is a library. */
  1167.   char library_flag;
  1168.  
  1169.   /* 1 if file's header has been ld_read into this structure.  */
  1170.   char header_read_flag;
  1171.  
  1172.   /* 1 means search a set of directories for this file.  */
  1173.   char search_dirs_flag;
  1174.  
  1175.   /* 1 means this is base file of incremental load.
  1176.      Do not load this file's text or data.
  1177.      Also default text_start to after this file's bss. */
  1178.   char just_syms_flag;
  1179. };
  1180.  
  1181. /* Vector of entries for input files specified by arguments.
  1182.    These are all the input files except for members of specified libraries.  */
  1183. struct file_entry *file_table;
  1184.  
  1185. /* When loading the text and data, we can avoid doing a close
  1186.    and another open between members of the same library.
  1187.  
  1188.    These two variables remember the file that is currently open.
  1189.    Both are zero if no file is open.
  1190.  
  1191.    See `each_file' and `file_close'.  */
  1192.  
  1193. struct file_entry *input_file;
  1194. int input_desc;
  1195.  
  1196. /* The following are computed by `digest_symbols'.  */
  1197.  
  1198. int text_size;        /* total size of text of all input files.  */
  1199. int data_size;        /* total size of data of all input files.  */
  1200. int bss_size;        /* total size of bss of all input files.  */
  1201. int text_reloc_size;    /* total size of text relocation of all input files.  */
  1202. int data_reloc_size;    /* total size of data relocation of all input */
  1203.             /* files.  */
  1204.  
  1205. /* Specifications of start and length of the area reserved at the end
  1206.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  1207. int set_sect_start;
  1208. int set_sect_size;
  1209.  
  1210. /* Amount of cleared space to leave between the text and data segments.  */
  1211.  
  1212. int text_pad;
  1213.  
  1214. /* Amount of bss segment to include as part of the data segment.  */
  1215.  
  1216. int data_pad;
  1217.  
  1218. /* Format of __.SYMDEF:
  1219.    First, a longword containing the size of the 'symdef' data that follows.
  1220.    Second, zero or more 'symdef' structures.
  1221.    Third, a longword containing the length of ld_symbol name strings.
  1222.    Fourth, zero or more ld_symbol name strings (each followed by a null).  */
  1223.  
  1224. struct symdef {
  1225.   int symbol_name_string_index;
  1226.   int library_member_offset;
  1227. };
  1228.  
  1229. /* Record most of the command options.  */
  1230.  
  1231. /* Address we assume the text section will be loaded at.
  1232.    We relocate symbols and text and data for this, but we do not
  1233.    write any padding in the output file for it.  */
  1234. int text_start;
  1235.  
  1236. /* Offset of default entry-pc within the text section.  */
  1237. int entry_offset;
  1238.  
  1239. /* Address we decide the data section will be loaded at.  */
  1240. int data_start;
  1241.  
  1242. /* Size to pad data section up to.
  1243.    We simply increase the size of the data section, padding with zeros,
  1244.    and reduce the size of the bss section to match.  */
  1245. int specified_data_size;
  1246.  
  1247. /* Magic number to use for the output file, set by switch.  */
  1248. int magic;
  1249.  
  1250. /* Which symbols should be stripped (omitted from the output):
  1251.    none, all, or debugger symbols.  */
  1252. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  1253.  
  1254. /* Which local symbols should be omitted:
  1255.    none, all, or those starting with L.
  1256.    This is irrelevant if STRIP_NONE.  */
  1257. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  1258.  
  1259. /* Non zero means to create the output executable. */
  1260. /* Cleared by nonfatal errors.  */
  1261. int make_executable;
  1262.  
  1263. /* Force the executable to be output, even if there are non-fatal
  1264.    errors */
  1265. int force_executable;
  1266.  
  1267. void bcopy (), bzero ();
  1268.  
  1269. int xmalloc ();
  1270. void fatal ();
  1271. void fatal_with_file ();
  1272. void error ();
  1273.  
  1274. void digest_symbols ();
  1275. void print_symbols ();
  1276. void load_symbols ();
  1277. void decode_command ();
  1278. void list_undefined_symbols ();
  1279. void list_unresolved_references ();
  1280. void write_output ();
  1281. void write_header ();
  1282. void write_text ();
  1283. void write_data ();
  1284. void write_rel ();
  1285. void write_syms ();
  1286. void write_symsegs ();
  1287. void mywrite ();
  1288. void symtab_init ();
  1289. void padfile ();
  1290. char *get_file_name ();
  1291. ld_symbol *getsym (), *getsym_soft ();
  1292.  
  1293. Handle resource_text;
  1294.  
  1295. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  1296. void enter_file_symbols (), enter_global_ref (), search_library ();
  1297. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  1298.  
  1299. int main (void)
  1300. {
  1301.   register char *bytes;
  1302.   register int desc;
  1303.   struct file_entry fe;
  1304.   register int len,coresize,resource_size;
  1305.   struct exec hdr;
  1306.   register int i;
  1307.   
  1308.   /* Clear the cumulative info on the output file.  */
  1309.  
  1310.   text_size = 0;
  1311.   data_size = 0;
  1312.   bss_size = 0;
  1313.   text_reloc_size = 0;
  1314.   data_reloc_size = 0;
  1315.  
  1316.   data_pad = 0;
  1317.   text_pad = 0;
  1318.  
  1319.   /* Initialize the data about options.  */
  1320.  
  1321.   specified_data_size = 0;
  1322.   strip_symbols = STRIP_NONE;
  1323.   discard_locals = DISCARD_NONE;
  1324.   entry_symbol = 0;
  1325.   magic = OMAGIC;
  1326.   make_executable = 1;
  1327.   force_executable = 0;
  1328.   set_element_prefixes = 0;
  1329.  
  1330.   /* Initialize the cumulative counts of symbols.  */
  1331.  
  1332.   local_sym_count = 0;
  1333.   non_L_local_sym_count = 0;
  1334.   debugger_sym_count = 0;
  1335.   undefined_global_sym_count = 0;
  1336.   set_symbol_count = 0;
  1337.   set_vector_count = 0;
  1338.   global_indirect_count = 0;
  1339.   warning_count = 0;
  1340.   multiple_def_count = 0;
  1341.   common_defined_global_count = 0;
  1342.  
  1343.   file_table = &fe;
  1344.   bzero (file_table, sizeof (struct file_entry));
  1345.  
  1346.   file_table->filename = "a.out";
  1347.   file_table->local_sym_name = "a.out";
  1348.  
  1349.     
  1350.     resource_text = GetResource('UNIX', 128);
  1351.     resource_size = SizeResource(resource_text);
  1352.  
  1353.     if (!resource_text) ExitToShell();
  1354.     
  1355.     bcopy( *resource_text, &file_table->header, sizeof (struct exec));
  1356.     if (N_BADMAG(file_table->header))
  1357.         fatal_with_file ("bad magic number in ", file_table);
  1358.  
  1359.     coresize = N_DATOFF(file_table->header) + 
  1360.             (file_table->header).a_data + 
  1361.             (file_table->header).a_bss;
  1362.  
  1363.     if (coresize > resource_size) resource_size = coresize;
  1364.     
  1365.     HPurge(resource_text);
  1366.     PurgeMem((Size) (1<<23));
  1367.     
  1368.     ResrvMem(resource_size);
  1369.     LoadResource(resource_text);
  1370.     HNoPurge(resource_text);    
  1371.  
  1372.     DetachResource(resource_text);
  1373.  
  1374.     SetHandleSize(resource_text, resource_size);
  1375.         
  1376.     if (MemError()) ExitToShell();
  1377.             
  1378.     HLock(resource_text);
  1379.  
  1380.   /* Create the symbols `etext', `edata' and `end'.  */
  1381.  
  1382.     symtab_init ();
  1383.             
  1384.     text_start = sizeof(struct exec) + ((long) StripAddress(*resource_text));
  1385.     data_start = text_start + file_table->header.a_text;
  1386.     
  1387.   file_table->header_read_flag = 1;
  1388.   file_table->symbols = N_SYMOFF (file_table->header)  + (char *)*resource_text;
  1389.   file_table->string_size = *(int *)( N_STROFF (file_table->header) + (char *)*resource_text);
  1390.   file_table->strings = N_STROFF (file_table->header) + (char *)*resource_text;
  1391.   file_table->textrel = text_offset (file_table) + file_table->header.a_text + file_table->header.a_data + (char *)*resource_text;
  1392.   file_table->datarel = text_offset (file_table) + file_table->header.a_text + file_table->header.a_data + file_table->header.a_trsize + (char *)*resource_text;
  1393.   enter_file_symbols (file_table);
  1394.   file_table->text_start_address = text_size;
  1395.   text_size += file_table->header.a_text;
  1396.   file_table->data_start_address = data_size;
  1397.   data_size += file_table->header.a_data;
  1398.   file_table->bss_start_address = bss_size;
  1399.   bss_size += file_table->header.a_bss;
  1400.   text_reloc_size += file_table->header.a_trsize;
  1401.   data_reloc_size += file_table->header.a_drsize;
  1402.  
  1403.   digest_symbols ();
  1404.  
  1405.   /* Print error messages for any missing symbols, for any warning
  1406.      symbols, and possibly multiple definitions */
  1407.  
  1408.   bytes = text_offset (file_table) + (char *)*resource_text;
  1409.  
  1410.   perform_relocation (bytes, file_table->text_start_address, file_table->header.a_text,
  1411.               file_table->textrel, file_table->header.a_trsize, file_table);
  1412.  
  1413.   bytes = text_offset (file_table) + file_table->header.a_text + (char *)*resource_text;
  1414.  
  1415.   perform_relocation (bytes, file_table->data_start_address - file_table->header.a_text,
  1416.               file_table->header.a_data, file_table->datarel, file_table->header.a_drsize, file_table);
  1417.               
  1418.   bzero((void *)file_table->bss_start_address, (file_table->header).a_bss);
  1419.   SetHandleSize(resource_text, coresize);
  1420.   
  1421.   if (make_executable && entry_symbol->value)
  1422.           {
  1423.           long type;
  1424.           Size    FreeBytes,growBytes;
  1425.           int addr = entry_symbol->value;
  1426.           malloc_free_all();
  1427.           FreeBytes = MaxMem(&growBytes);
  1428.  
  1429.         FlushCache();
  1430.         
  1431.           ((void (*)(void))((addr)))();
  1432.           }
  1433.   
  1434.   ExitToShell ();
  1435. }
  1436.  
  1437. void decode_option ();
  1438.  
  1439. /* Analyze a command line argument.
  1440.    Return 0 if the argument is a filename.
  1441.    Return 1 if the argument is a option complete in itself.
  1442.    Return 2 if the argument is a option which uses an argument.
  1443.  
  1444.    Thus, the value is the number of consecutive arguments
  1445.    that are part of options.  */
  1446.  
  1447. int
  1448. classify_arg (arg)
  1449.      register char *arg;
  1450. {
  1451.   if (*arg != '-') return 0;
  1452.   switch (arg[1])
  1453.     {
  1454.     case 'A':
  1455.     case 'D':
  1456.     case 'e':
  1457.     case 'L':
  1458.     case 'l':
  1459.     case 'o':
  1460.     case 'u':
  1461.     case 'V':
  1462.     case 'y':
  1463.       if (arg[2])
  1464.     return 1;
  1465.       return 2;
  1466.  
  1467.     case 'B':
  1468.       if (! strcmp (&arg[2], "static"))
  1469.     return 1;
  1470.  
  1471.     case 'T':
  1472.       if (arg[2] == 0)
  1473.     return 2;
  1474.       if (! strcmp (&arg[2], "text"))
  1475.     return 2;
  1476.       if (! strcmp (&arg[2], "data"))
  1477.     return 2;
  1478.       return 1;
  1479.     }
  1480.  
  1481.   return 1;
  1482. }
  1483.  
  1484.  
  1485.  
  1486. int
  1487. set_element_prefixed_p (name)
  1488.      char *name;
  1489. {
  1490.   struct string_list_element *p;
  1491.   int i;
  1492.  
  1493.   for (p = set_element_prefixes; p; p = p->next)
  1494.     {
  1495.       for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
  1496.     ;
  1497.  
  1498.       if (p->str[i] == '\0')
  1499.     return 1;
  1500.     }
  1501.   return 0;
  1502. }
  1503.  
  1504. /* Record an option and arrange to act on it later.
  1505.    ARG should be the following command argument,
  1506.    which may or may not be used by this option.
  1507.  
  1508.    The `l' and `A' options are ignored here since they actually
  1509.    specify input files.  */
  1510.  
  1511.  
  1512. /** Convenient functions for operating on one or all files being */
  1513.  /** loaded.  */
  1514. void print_file_name ();
  1515.  
  1516.  
  1517. /* Close the input file that is now open.  */
  1518.  
  1519. void
  1520. file_close ()
  1521. {
  1522.   input_file = 0;
  1523. }
  1524.  
  1525. /* Open the input file specified by 'entry', and return a descriptor.
  1526.    The open file is remembered; if the same file is opened twice in a row,
  1527.    a new open is not actually done.  */
  1528.  
  1529. int
  1530. file_open (entry)
  1531.      register struct file_entry *entry;
  1532. {
  1533.     return input_desc;
  1534. }
  1535.  
  1536.  
  1537. /* Medium-level input routines for rel files.  */
  1538.  
  1539. /* Read a file's header into the proper place in the file_entry.
  1540.    DESC is the descriptor on which the file is open.
  1541.    ENTRY is the file's entry.  */
  1542. /* Read the string table of file ENTRY into core.
  1543.    Assume it is already open, on descriptor DESC.
  1544.    Also record whether a GDB ld_symbol segment follows the string table.  */
  1545.  
  1546.  
  1547. /* Enter the external ld_symbol defs and refs of ENTRY in the hash table.  */
  1548.  
  1549. void
  1550. enter_file_symbols (entry)
  1551.      struct file_entry *entry;
  1552. {
  1553.   register struct nlist
  1554.     *p,
  1555.     *end = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  1556.  
  1557.   for (p = entry->symbols; p < end; p++)
  1558.     {
  1559.       if (p->n_type == (N_SETV | N_EXT)) continue;
  1560.       if (set_element_prefixes
  1561.       && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
  1562.     p->n_type += (N_SETA - N_ABS);
  1563.  
  1564.       if (SET_ELEMENT_P (p->n_type))
  1565.     {
  1566.       set_symbol_count++;
  1567.         enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1568.     }
  1569.       else if (p->n_type == N_WARNING)
  1570.     {
  1571.       char *name = p->n_un.n_strx + entry->strings;
  1572.  
  1573.       /* Grab the next entry.  */
  1574.       p++;
  1575.       if (p->n_type != (N_UNDF | N_EXT))
  1576.         {
  1577.           make_executable = 0;
  1578.           p--;        /* Process normally.  */
  1579.         }
  1580.       else
  1581.         {
  1582.           ld_symbol *sp;
  1583.           char *sname = p->n_un.n_strx + entry->strings;
  1584.           /* Deal with the warning ld_symbol.  */
  1585.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1586.           sp = getsym (sname);
  1587.           sp->warning = name;
  1588.           warning_count++;
  1589.         }
  1590.     }
  1591.       else if (p->n_type & N_EXT)
  1592.     enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  1593.       else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  1594.     {
  1595.       if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
  1596.         non_L_local_sym_count++;
  1597.       local_sym_count++;
  1598.     }
  1599.       else debugger_sym_count++;
  1600.     }
  1601.  
  1602.    /* Count one for the local ld_symbol that we generate,
  1603.       whose name is the file's name (usually) and whose address
  1604.       is the start of the file's text.  */
  1605.  
  1606.   local_sym_count++;
  1607.   non_L_local_sym_count++;
  1608. }
  1609.  
  1610. /* Enter one global ld_symbol in the hash table.
  1611.    NLIST_P points to the `struct nlist' ld_read from the file
  1612.    that describes the global ld_symbol.  NAME is the ld_symbol's name.
  1613.    ENTRY is the file entry for the file the ld_symbol comes from.
  1614.  
  1615.    The `struct nlist' is modified by placing it on a chain of
  1616.    all such structs that refer to the same global ld_symbol.
  1617.    This chain starts in the `refs' field of the ld_symbol table entry
  1618.    and is chained through the `n_name'.  */
  1619.  
  1620. void
  1621. enter_global_ref (nlist_p, name, entry)
  1622.      register struct nlist *nlist_p;
  1623.      char *name;
  1624.      struct file_entry *entry;
  1625. {
  1626.   register ld_symbol *sp = getsym (name);
  1627.   register int type = nlist_p->n_type;
  1628.   int oldref = sp->referenced;
  1629.   int olddef = sp->defined;
  1630.  
  1631.   nlist_p->n_un.n_name = (char *) sp->refs;
  1632.   sp->refs = nlist_p;
  1633.  
  1634.   sp->referenced = 1;
  1635.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  1636.     {
  1637.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  1638.     sp->defined = type;
  1639.  
  1640.       if (oldref && !olddef)
  1641.     /* It used to be undefined and we're defining it.  */
  1642.     undefined_global_sym_count--;
  1643.  
  1644.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  1645.     {
  1646.       /* First definition and it's common.  */
  1647.       common_defined_global_count++;
  1648.       sp->max_common_size = nlist_p->n_value;
  1649.     }
  1650.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  1651.     {
  1652.       /* It used to be common and we're defining it as
  1653.          something else.  */
  1654.       common_defined_global_count--;
  1655.       sp->max_common_size = 0;
  1656.     }
  1657.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  1658.       && sp->max_common_size < nlist_p->n_value)
  1659.     /* It used to be common and this is a new common entry to
  1660.        which we need to pay attention.  */
  1661.     sp->max_common_size = nlist_p->n_value;
  1662.  
  1663.       /* Are we defining it as a set element?  */
  1664.       if (SET_ELEMENT_P (type)
  1665.       && (!olddef || (olddef && sp->max_common_size)))
  1666.     set_vector_count++;
  1667.       /* As an indirection?  */
  1668.       else if (type == (N_INDR | N_EXT))
  1669.     {
  1670.       /* Indirect symbols value should be modified to point
  1671.          a ld_symbol being equivalenced to. */
  1672.       nlist_p->n_value
  1673.         = (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  1674.                      + entry->strings);
  1675.       if ((ld_symbol *) nlist_p->n_value == sp)
  1676.         {
  1677.           /* Rewrite this ld_symbol as being a global text ld_symbol
  1678.          with value 0.  */
  1679.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  1680.           nlist_p->n_value = 0;
  1681.           /* Don't make the output executable.  */
  1682.           make_executable = 0;
  1683.         }
  1684.       else
  1685.         global_indirect_count++;
  1686.     }
  1687.     }
  1688.   else
  1689.     if (!oldref)
  1690.       undefined_global_sym_count++;
  1691.  
  1692.   if (sp->trace)
  1693.     {
  1694.       register char *reftype;
  1695.       switch (type & N_TYPE)
  1696.     {
  1697.     case N_UNDF:
  1698.       if (nlist_p->n_value)
  1699.         reftype = "defined as common";
  1700.       else reftype = "referenced";
  1701.       break;
  1702.  
  1703.     case N_ABS:
  1704.       reftype = "defined as absolute";
  1705.       break;
  1706.  
  1707.     case N_TEXT:
  1708.       reftype = "defined in text section";
  1709.       break;
  1710.  
  1711.     case N_DATA:
  1712.       reftype = "defined in data section";
  1713.       break;
  1714.  
  1715.     case N_BSS:
  1716.       reftype = "defined in BSS section";
  1717.       break;
  1718.  
  1719.     case N_SETT:
  1720.       reftype = "is a text set element";
  1721.       break;
  1722.  
  1723.     case N_SETD:
  1724.       reftype = "is a data set element";
  1725.       break;
  1726.  
  1727.     case N_SETB:
  1728.       reftype = "is a BSS set element";
  1729.       break;
  1730.  
  1731.     case N_SETA:
  1732.       reftype = "is an absolute set element";
  1733.       break;
  1734.  
  1735.     case N_SETV:
  1736.       reftype = "defined in data section as vector";
  1737.       break;
  1738.  
  1739.     case N_INDR:
  1740.       reftype = "defined equivalent";
  1741.       break;
  1742.  
  1743.     }
  1744.  
  1745.     }
  1746. }
  1747.  
  1748. /* This return 0 if the given file entry's ld_symbol table does *not*
  1749.    contain the nlist point entry, and it returns the files entry
  1750.    pointer (cast to unsigned long) if it does. */
  1751.  
  1752. unsigned long
  1753. contains_symbol (entry, n_ptr)
  1754.      struct file_entry *entry;
  1755.      register struct nlist *n_ptr;
  1756. {
  1757.   if (n_ptr >= entry->symbols &&
  1758.       n_ptr < (entry->symbols
  1759.            + (entry->header.a_syms / sizeof (struct nlist))))
  1760.     return (unsigned long) entry;
  1761.   return 0;
  1762. }
  1763.  
  1764.  
  1765.  
  1766.  
  1767. void consider_file_section_lengths (), relocate_file_addresses ();
  1768.  
  1769. /* Having entered all the global symbols and found the sizes of sections
  1770.    of all files to be linked, make all appropriate deductions from this data.
  1771.  
  1772.    We propagate global ld_symbol values from definitions to references.
  1773.    We compute the layout of the output file and where each input file's
  1774.    contents fit into it.  */
  1775.  
  1776. void
  1777. digest_symbols ()
  1778. {
  1779.   register int i;
  1780.   int setv_fill_count;
  1781.  
  1782.   /* Set up the set element vector */
  1783.  
  1784.     {
  1785.       /* The set sector size is the number of set elements + a word
  1786.          for each ld_symbol for the length word at the beginning of the
  1787.      vector, plus a word for each ld_symbol for a zero at the end of
  1788.      the vector (for incremental linking).  */
  1789.       set_sect_size
  1790.     = (2 * set_symbol_count + set_vector_count) * sizeof (unsigned long);
  1791.       set_sect_start = data_start + data_size;
  1792.       data_size += set_sect_size;
  1793.       setv_fill_count = 0;
  1794.     }
  1795.  
  1796.   /* Compute start addresses of each file's sections and symbols.  */
  1797.  
  1798.   relocate_file_addresses ( file_table, 0);
  1799.  
  1800.   /* Now, for each ld_symbol, verify that it is defined globally at most once.
  1801.      Put the global value into the ld_symbol entry.
  1802.      Common symbols are allocated here, in the BSS section.
  1803.      Each defined ld_symbol is given a '->defined' field
  1804.       which is the correct N_ code for its definition,
  1805.       except in the case of common symbols with -r.
  1806.      Then make all the references point at the ld_symbol entry
  1807.      instead of being chained together. */
  1808.  
  1809.   defined_global_sym_count = 0;
  1810.  
  1811.   for (i = 0; i < TABSIZE; i++)
  1812.     {
  1813.       register ld_symbol *sp;
  1814.       for (sp = symtab[i]; sp; sp = sp->link)
  1815.     {
  1816.       /* For each ld_symbol */
  1817.       register struct nlist *p, *next;
  1818.       int defs = 0, com = sp->max_common_size;
  1819.       struct nlist *first_definition;
  1820.       for (p = sp->refs; p; p = next)
  1821.         {
  1822.           register int type = p->n_type;
  1823.  
  1824.           if (SET_ELEMENT_P (type))
  1825.         {
  1826.           if (!defs++)
  1827.             {
  1828.               sp->value = set_sect_start
  1829.             + setv_fill_count++ * sizeof (unsigned long);
  1830.               sp->defined = N_SETV | N_EXT;
  1831.               first_definition = p;
  1832.             }
  1833.           else if ((sp->defined & ~N_EXT) != N_SETV)
  1834.             {
  1835.               sp->multiply_defined = 1;
  1836.               multiple_def_count++;
  1837.             }
  1838.           setv_fill_count++;
  1839.         }
  1840.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  1841.         {
  1842.           /* non-common definition */
  1843.           if (defs++ && sp->value != p->n_value)
  1844.             {
  1845.               sp->multiply_defined = 1;
  1846.               multiple_def_count++;
  1847.             }
  1848.           sp->value = p->n_value;
  1849.           sp->defined = type;
  1850.           first_definition = p;
  1851.         }
  1852.           next = (struct nlist *) p->n_un.n_name;
  1853.           p->n_un.n_name = (char *) sp;
  1854.         }
  1855.       /* Allocate as common if defined as common and not defined for real */
  1856.       if (com && !defs)
  1857.         {
  1858.         {
  1859.           int align = sizeof (int);
  1860.  
  1861.           /* Round up to nearest sizeof (int).  I don't know
  1862.              whether this is necessary or not (given that
  1863.              alignment is taken care of later), but it's
  1864.              traditional, so I'll leave it in.  Note that if
  1865.              this size alignment is ever removed, ALIGN above
  1866.              will have to be initialized to 1 instead of
  1867.              sizeof (int).  */
  1868.  
  1869.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  1870.  
  1871.           while (!(com & align))
  1872.             align <<= 1;
  1873.  
  1874.           align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
  1875.  
  1876.           bss_size = ((((bss_size + data_size + data_start)
  1877.                   + (align - 1)) & (- align))
  1878.                   - data_size - data_start);
  1879.  
  1880.           sp->value = data_start + data_size + bss_size;
  1881.           sp->defined = N_BSS | N_EXT;
  1882.           bss_size += com;
  1883.         }
  1884.         }
  1885.       /* Set length word at front of vector and zero byte at end.
  1886.          Reverse the vector itself to put it in file order.  */
  1887.       if ((sp->defined & ~N_EXT) == N_SETV)
  1888.         {
  1889.           unsigned long length_word_index
  1890.         = (sp->value - set_sect_start) / sizeof (unsigned long);
  1891.           unsigned long i, tmp;
  1892.  
  1893.           setv_fill_count++;
  1894.         }
  1895.       if (sp->defined)
  1896.         defined_global_sym_count++;
  1897.     }
  1898.     }
  1899.  
  1900.   if (end_symbol)        /* These are null if -r.  */
  1901.     {
  1902.       etext_symbol->value = text_size + text_start;
  1903.       edata_symbol->value = data_start + data_size;
  1904.       end_symbol->value = data_start + data_size + bss_size;
  1905.     }
  1906. }
  1907.  
  1908. /* Determine where the sections of ENTRY go into the output file,
  1909.    whose total section sizes are already known.
  1910.    Also relocate the addresses of the file's local and debugger symbols.  */
  1911.  
  1912. void
  1913. relocate_file_addresses (entry)
  1914.      register struct file_entry *entry;
  1915. {
  1916.   entry->text_start_address += text_start;
  1917.   /* Note that `data_start' and `data_size' have not yet been
  1918.      adjusted for `data_pad'.  If they had been, we would get the wrong
  1919.      results here.  */
  1920.   entry->data_start_address += data_start;
  1921.   entry->bss_start_address += data_start + data_size;
  1922.  
  1923.   {
  1924.     register struct nlist *p;
  1925.     register struct nlist *end
  1926.       = entry->symbols + entry->header.a_syms / sizeof (struct nlist);
  1927.  
  1928.     for (p = entry->symbols; p < end; p++)
  1929.       {
  1930.     /* If this belongs to a section, update it by the section's start address */
  1931.     register int type = p->n_type & N_TYPE;
  1932.  
  1933.     switch (type)
  1934.       {
  1935.       case N_TEXT:
  1936.       case N_SETT:
  1937.         p->n_value += entry->text_start_address;
  1938.         break;
  1939.       case N_DATA:
  1940.       case N_SETV:
  1941.       case N_SETD:
  1942.         /* A ld_symbol whose value is in the data section
  1943.            is present in the input file as if the data section
  1944.            started at an address equal to the length of the file's text.  */
  1945.         p->n_value += entry->data_start_address - entry->header.a_text;
  1946.         break;
  1947.       case N_BSS:
  1948.       case N_SETB:
  1949.         /* likewise for symbols with value in BSS.  */
  1950.         p->n_value += entry->bss_start_address
  1951.           - entry->header.a_text - entry->header.a_data;
  1952.         break;
  1953.       }
  1954.       }
  1955.   }
  1956. }
  1957.  
  1958.  
  1959.  
  1960.  
  1961. int
  1962. text_offset (entry)
  1963.      struct file_entry *entry;
  1964. {
  1965.   return entry->starting_offset + N_TXTOFF (entry->header);
  1966. }
  1967.  
  1968. /* Relocate ENTRY's text or data section contents.
  1969.    DATA is the address of the contents, in core.
  1970.    DATA_SIZE is the length of the contents.
  1971.    PC_RELOCATION is the difference between the address of the contents
  1972.      in the output file and its address in the input file.
  1973.    RELOC_INFO is the address of the relocation info, in core.
  1974.    RELOC_SIZE is its length in bytes.  */
  1975. /* This version is about to be severly hacked by Randy.  Hope it
  1976.    works afterwards. */
  1977. void
  1978. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  1979.      char *data;
  1980.      struct relocation_info *reloc_info;
  1981.      struct file_entry *entry;
  1982.      int pc_relocation;
  1983.      int data_size;
  1984.      int reloc_size;
  1985. {
  1986.   register struct relocation_info *p = reloc_info;
  1987.   struct relocation_info *end
  1988.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  1989.   int text_relocation = entry->text_start_address;
  1990.   int data_relocation = entry->data_start_address - entry->header.a_text;
  1991.   int bss_relocation
  1992.     = entry->bss_start_address - entry->header.a_text - entry->header.a_data;
  1993.  
  1994.   for (; p < end; p++)
  1995.     {
  1996.       register int relocation = 0;
  1997.       register int addr = RELOC_ADDRESS(p);
  1998.       register unsigned int mask = 0;
  1999.  
  2000.       if (addr >= data_size)
  2001.     fatal_with_file ("relocation address out of range in ", entry);
  2002.  
  2003.       if (RELOC_EXTERN_P(p))
  2004.     {
  2005.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  2006.       ld_symbol *sp = ((ld_symbol *)
  2007.             (((struct nlist *)
  2008.               (((char *)entry->symbols) + symindex))
  2009.              ->n_un.n_name));
  2010.  
  2011. #ifdef N_INDR
  2012.       /* Resolve indirection */
  2013.       if ((sp->defined & ~N_EXT) == N_INDR)
  2014.         sp = (ld_symbol *) sp->value;
  2015. #endif
  2016.  
  2017.       if (symindex >= entry->header.a_syms)
  2018.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  2019.  
  2020.       /* If the ld_symbol is undefined, leave it at zero.  */
  2021.       if (! sp->defined)
  2022.         relocation = 0;
  2023.       else
  2024.         relocation = sp->value;
  2025.     }
  2026.       else switch (RELOC_TYPE(p))
  2027.     {
  2028.     case N_TEXT:
  2029.     case N_TEXT | N_EXT:
  2030.       relocation = text_relocation;
  2031.       break;
  2032.  
  2033.     case N_DATA:
  2034.     case N_DATA | N_EXT:
  2035.       /* A word that points to beginning of the the data section
  2036.          initially contains not 0 but rather the "address" of that section
  2037.          in the input file, which is the length of the file's text.  */
  2038.       relocation = data_relocation;
  2039.       break;
  2040.  
  2041.     case N_BSS:
  2042.     case N_BSS | N_EXT:
  2043.       /* Similarly, an input word pointing to the beginning of the bss
  2044.          initially contains the length of text plus data of the file.  */
  2045.       relocation = bss_relocation;
  2046.       break;
  2047.  
  2048.     case N_ABS:
  2049.     case N_ABS | N_EXT:
  2050.       /* Don't know why this code would occur, but apparently it does.  */
  2051.       break;
  2052.  
  2053.     case 0:
  2054.     /* bodge */
  2055.     break;
  2056.  
  2057.     default:
  2058.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  2059.     }
  2060.  
  2061. #ifdef RELOC_ADD_EXTRA
  2062.       relocation += RELOC_ADD_EXTRA(p);
  2063.       if (relocatable_output)
  2064.     {
  2065.       /* Non-PC relative relocations which are absolute
  2066.          or which have become non-external now have fixed
  2067.          relocations.  Set the ADD_EXTRA of this relocation
  2068.          to be the relocation we have now determined.  */
  2069.       if (! RELOC_PCREL_P (p))
  2070.         {
  2071.           if ((int)p->r_type <= RELOC_32
  2072.           || RELOC_EXTERN_P (p) == 0)
  2073.         RELOC_ADD_EXTRA (p) = relocation;
  2074.         }
  2075.       /* External PC-relative relocations continue to move around;
  2076.          update their relocations by the amount they have moved
  2077.          so far.  */
  2078.       else if (RELOC_EXTERN_P (p))
  2079.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  2080.       continue;
  2081.     }
  2082. #endif
  2083.  
  2084.       if (RELOC_PCREL_P(p))
  2085.     relocation -= pc_relocation;
  2086.  
  2087.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  2088.  
  2089.       /* Unshifted mask for relocation */
  2090.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  2091.       mask |= mask - 1;
  2092.       relocation &= mask;
  2093.  
  2094.       /* Shift everything up to where it's going to be used */
  2095.       relocation <<= RELOC_TARGET_BITPOS(p);
  2096.       mask <<= RELOC_TARGET_BITPOS(p);
  2097.  
  2098.       switch (RELOC_TARGET_SIZE(p))
  2099.     {
  2100.     case 0:
  2101.       if (RELOC_MEMORY_SUB_P(p))
  2102.         relocation -= mask & *(char *) (data + addr);
  2103.       else if (RELOC_MEMORY_ADD_P(p))
  2104.         relocation += mask & *(char *) (data + addr);
  2105.       *(char *) (data + addr) &= ~mask;
  2106.       *(char *) (data + addr) |= relocation;
  2107.       break;
  2108.  
  2109.     case 1:
  2110.       if (RELOC_MEMORY_SUB_P(p))
  2111.         relocation -= mask & *(short *) (data + addr);
  2112.       else if (RELOC_MEMORY_ADD_P(p))
  2113.         relocation += mask & *(short *) (data + addr);
  2114.       *(short *) (data + addr) &= ~mask;
  2115.       *(short *) (data + addr) |= relocation;
  2116.       break;
  2117.  
  2118.     case 2:
  2119. #ifndef _CROSS_TARGET_ARCH
  2120.       if (RELOC_MEMORY_SUB_P(p))
  2121.         relocation -= mask & *(long *) (data + addr);
  2122.       else if (RELOC_MEMORY_ADD_P(p))
  2123.         relocation += mask & *(long *) (data + addr);
  2124.       *(long *) (data + addr) &= ~mask;
  2125.       *(long *) (data + addr) |= relocation;
  2126. #else
  2127.     /* Handle long word alignment requirements of SPARC architecture */
  2128.     /* WARNING:  This fix makes an assumption on byte ordering */
  2129.     /* Marc Ullman, Stanford University    Nov. 1 1989  */
  2130.       if (RELOC_MEMORY_SUB_P(p)) {
  2131.         relocation -= mask & 
  2132.           ((*(unsigned short *) (data + addr) << 16) |
  2133.         *(unsigned short *) (data + addr + 2));
  2134.       } else if (RELOC_MEMORY_ADD_P(p)) {
  2135.         relocation += mask &
  2136.           ((*(unsigned short *) (data + addr) << 16) |
  2137.         *(unsigned short *) (data + addr + 2));
  2138.       }
  2139.       *(unsigned short *) (data + addr)     &= (~mask >> 16);
  2140.       *(unsigned short *) (data + addr + 2) &= (~mask & 0xffff);
  2141.       *(unsigned short *) (data + addr)     |= (relocation >> 16);
  2142.       *(unsigned short *) (data + addr + 2) |= (relocation & 0xffff);
  2143. #endif
  2144.       break;
  2145.  
  2146.     default:
  2147.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  2148.     }
  2149.     }
  2150. }
  2151.  
  2152.  
  2153. void write_file_syms ();
  2154. void write_string_table ();
  2155.  
  2156. /* Offsets and current lengths of ld_symbol and string tables in output file. */
  2157.  
  2158. int symbol_table_offset;
  2159. int symbol_table_len;
  2160.  
  2161. /* Address in output file where string table starts.  */
  2162. int string_table_offset;
  2163.  
  2164. /* Offset within string table
  2165.    where the strings in `strtab_vector' should be written.  */
  2166. int string_table_len;
  2167.  
  2168. /* Total size of string table strings allocated so far,
  2169.    including strings in `strtab_vector'.  */
  2170. int strtab_size;
  2171.  
  2172. /* Vector whose elements are strings to be added to the string table.  */
  2173. char **strtab_vector;
  2174.  
  2175. /* Vector whose elements are the lengths of those strings.  */
  2176. int *strtab_lens;
  2177.  
  2178. /* Index in `strtab_vector' at which the next string will be stored.  */
  2179. int strtab_index;
  2180.  
  2181. /* Add the string NAME to the output file string table.
  2182.    Record it in `strtab_vector' to be output later.
  2183.    Return the index within the string table that this string will have.  */
  2184.  
  2185. int
  2186. assign_string_table_index (name)
  2187.      char *name;
  2188. {
  2189.   register int index = strtab_size;
  2190.   register int len = strlen (name) + 1;
  2191.  
  2192.   strtab_size += len;
  2193.   strtab_vector[strtab_index] = name;
  2194.   strtab_lens[strtab_index++] = len;
  2195.  
  2196.   return index;
  2197. }
  2198.  
  2199. /* Create the ld_symbol table entries for `etext', `edata' and `end'.  */
  2200.  
  2201. void
  2202. symtab_init ()
  2203.     {
  2204.     entry_symbol = getsym ("ENTRY_SYMBOL");
  2205.     if (!entry_symbol->defined && !entry_symbol->referenced)
  2206.         undefined_global_sym_count++;
  2207.     entry_symbol->referenced = 1;
  2208. #ifndef nounderscore
  2209.   edata_symbol = getsym ("_edata");
  2210.   etext_symbol = getsym ("_etext");
  2211.   end_symbol = getsym ("_end");
  2212. #else
  2213.   edata_symbol = getsym ("edata");
  2214.   etext_symbol = getsym ("etext");
  2215.   end_symbol = getsym ("end");
  2216. #endif
  2217.  
  2218.   edata_symbol->defined = N_DATA | N_EXT;
  2219.   etext_symbol->defined = N_TEXT | N_EXT;
  2220.   end_symbol->defined = N_BSS | N_EXT;
  2221.  
  2222.   edata_symbol->referenced = 1;
  2223.   etext_symbol->referenced = 1;
  2224.   end_symbol->referenced = 1;
  2225. }
  2226.  
  2227. /* Compute the hash code for ld_symbol name KEY.  */
  2228.  
  2229. int
  2230. hash_string (key)
  2231.      char *key;
  2232. {
  2233.   register char *cp;
  2234.   register int k;
  2235.  
  2236.   cp = key;
  2237.   k = 0;
  2238.   while (*cp)
  2239.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  2240.  
  2241.   return k;
  2242. }
  2243.  
  2244. /* Get the ld_symbol table entry for the global ld_symbol named KEY.
  2245.    Create one if there is none.  */
  2246.  
  2247. ld_symbol *
  2248. getsym (key)
  2249.      char *key;
  2250. {
  2251.   register int hashval;
  2252.   register ld_symbol *bp;
  2253.  
  2254.   /* Determine the proper bucket.  */
  2255.  
  2256.   hashval = hash_string (key) % TABSIZE;
  2257.  
  2258.   /* Search the bucket.  */
  2259.  
  2260.   for (bp = symtab[hashval]; bp; bp = bp->link)
  2261.     if (! strcmp (key, bp->name))
  2262.       return bp;
  2263.  
  2264.   /* Nothing was found; create a new ld_symbol table entry.  */
  2265.  
  2266.   bp = (ld_symbol *) xmalloc (sizeof (ld_symbol));
  2267.   bp->refs = 0;
  2268.   bp->name = (char *) xmalloc (strlen (key) + 1);
  2269.   strcpy (bp->name, key);
  2270.   bp->defined = 0;
  2271.   bp->referenced = 0;
  2272.   bp->trace = 0;
  2273.   bp->value = 0;
  2274.   bp->max_common_size = 0;
  2275.   bp->warning = 0;
  2276.   bp->undef_refs = 0;
  2277.   bp->multiply_defined = 0;
  2278.  
  2279.   /* Add the entry to the bucket.  */
  2280.  
  2281.   bp->link = symtab[hashval];
  2282.   symtab[hashval] = bp;
  2283.  
  2284.   ++num_hash_tab_syms;
  2285.  
  2286.   return bp;
  2287. }
  2288.  
  2289. /* Like `getsym' but return 0 if the ld_symbol is not already known.  */
  2290.  
  2291. ld_symbol *
  2292. getsym_soft (key)
  2293.      char *key;
  2294. {
  2295.   register int hashval;
  2296.   register ld_symbol *bp;
  2297.  
  2298.   /* Determine which bucket.  */
  2299.  
  2300.   hashval = hash_string (key) % TABSIZE;
  2301.  
  2302.   /* Search the bucket.  */
  2303.  
  2304.   for (bp = symtab[hashval]; bp; bp = bp->link)
  2305.     if (! strcmp (key, bp->name))
  2306.       return bp;
  2307.  
  2308.   return 0;
  2309. }
  2310.  
  2311. /* Report a fatal error.
  2312.    STRING is a printf format string and ARG is one arg for it.  */
  2313.  
  2314. void
  2315. fatal (string, arg)
  2316.      char *string, *arg;
  2317. {
  2318.   error(string);
  2319.   ExitToShell();
  2320. }
  2321.  
  2322. /* Report a fatal error.  The error message is STRING
  2323.    followed by the filename of ENTRY.  */
  2324.  
  2325. void
  2326. fatal_with_file (string, entry)
  2327.      char *string;
  2328.      struct file_entry *entry;
  2329. {
  2330.   error(string);
  2331.   ExitToShell();
  2332. }
  2333.  
  2334. /* Report a nonfatal error.
  2335.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  2336.  
  2337. void
  2338. error (string, arg1, arg2, arg3)
  2339.      char *string, *arg1, *arg2, *arg3;
  2340. {
  2341.   Str255    err;
  2342.   for (*err = 0; *string; string++)
  2343.           {
  2344.           *err += 1;
  2345.           err[*err] = *string;
  2346.           }
  2347.  
  2348.   DebugStr(err);
  2349. }
  2350.  
  2351. /* Like malloc but get fatal error if memory is exhausted.  */
  2352.  
  2353. int
  2354. xmalloc (size)
  2355. {
  2356.   register int result = (int)malloc (size);
  2357.   if (!result)
  2358.     fatal ("virtual memory exhausted", 0);
  2359.   return result;
  2360. }
  2361.  
  2362. int
  2363. xrealloc (ptr, size)
  2364. {
  2365.   register int result = (int)realloc (ptr, size);
  2366.   if (!result)
  2367.     fatal ("virtual memory exhausted", 0);
  2368.   return result;
  2369. }
  2370.  
  2371. void *emptyblock(size_t sz)
  2372.     {
  2373.     void *ptr = NewPtrClear(sz);
  2374.     return ptr;
  2375.     }
  2376.     
  2377. int getpagesize(void)
  2378.     {
  2379.     return 8192;
  2380.     }
  2381.