Home | History | Annotate | Download | only in src
      1 /* Copyright (C) 2001, 2002, 2003, 2004 Red Hat, Inc.
      2    Written by Ulrich Drepper <drepper (at) redhat.com>, 2001.
      3 
      4    This program is Open Source software; you can redistribute it and/or
      5    modify it under the terms of the Open Software License version 1.0 as
      6    published by the Open Source Initiative.
      7 
      8    You should have received a copy of the Open Software License along
      9    with this program; if not, you may obtain a copy of the Open Software
     10    License version 1.0 from http://www.opensource.org/licenses/osl.php or
     11    by writing the Open Source Initiative c/o Lawrence Rosen, Esq.,
     12    3001 King Ranch Road, Ukiah, CA 95482.   */
     13 
     14 #ifdef HAVE_CONFIG_H
     15 # include <config.h>
     16 #endif
     17 
     18 #include <argp.h>
     19 #include <assert.h>
     20 #include <error.h>
     21 #include <fcntl.h>
     22 #include <libelf.h>
     23 #include <libintl.h>
     24 #include <locale.h>
     25 #include <mcheck.h>
     26 #include <stdio.h>
     27 #include <stdio_ext.h>
     28 #include <stdlib.h>
     29 #include <string.h>
     30 #include <unistd.h>
     31 
     32 #include <system.h>
     33 #include "ld.h"
     34 #include "list.h"
     35 
     36 
     37 /* Name and version of program.  */
     38 static void print_version (FILE *stream, struct argp_state *state);
     39 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
     40 
     41 
     42 /* Values for the various options.  */
     43 enum
     44   {
     45     ARGP_whole_archive = 300,
     46     ARGP_no_whole_archive,
     47     ARGP_static,
     48     ARGP_dynamic,
     49     ARGP_pagesize,
     50     ARGP_rpath,
     51     ARGP_rpath_link,
     52     ARGP_runpath,
     53     ARGP_runpath_link,
     54     ARGP_version_script,
     55     ARGP_gc_sections,
     56     ARGP_no_gc_sections,
     57     ARGP_no_undefined,
     58     ARGP_conserve,
     59 #if YYDEBUG
     60     ARGP_yydebug,
     61 #endif
     62   };
     63 
     64 
     65 /* Definitions of arguments for argp functions.  */
     66 static const struct argp_option options[] =
     67 {
     68   /* XXX This list will be reordered and section names will be added.
     69      Just not right now.  */
     70   { "whole-archive", ARGP_whole_archive, NULL, 0,
     71     N_("Include whole archives in the output from now on.") },
     72   { "no-whole-archive", ARGP_no_whole_archive, NULL, 0,
     73     N_("Stop including the whole arhives in the output.") },
     74 
     75   { "output", 'o', N_("FILE"), 0, N_("Place output in FILE.") },
     76 
     77   { NULL, 'O', N_("LEVEL"), OPTION_ARG_OPTIONAL,
     78     N_("Set optimization level to LEVEL.") },
     79 
     80   { "verbose", 'v', NULL, 0, N_("Verbose messages.") },
     81   { "trace", 't', NULL, 0, N_("Trace file opens.") },
     82   { "conserve-memory", ARGP_conserve, NULL, 0,
     83     N_("Trade speed for less memory usage") },
     84 
     85   { NULL, 'z', "KEYWORD", OPTION_HIDDEN, NULL },
     86   { "-z nodefaultlib", '\0', NULL, OPTION_DOC,
     87     N_("Object is marked to not use default search path at runtime.") },
     88   { "-z allextract", '\0', NULL, OPTION_DOC,
     89     N_("Same as --whole-archive.") },
     90   { "-z defaultextract", '\0', NULL, OPTION_DOC, N_("\
     91 Default rules of extracting from archive; weak references are not enough.") },
     92   { "-z weakextract", '\0', NULL, OPTION_DOC,
     93     N_("Weak references cause extraction from archive.") },
     94   { "-z muldefs", '\0', NULL, OPTION_DOC,
     95     N_("Allow multiple definitions; first is used.") },
     96   { "-z defs | nodefs", '\0', NULL, OPTION_DOC,
     97     N_("Disallow/allow undefined symbols in DSOs.") },
     98     { "no-undefined", ARGP_no_undefined, NULL, OPTION_HIDDEN, NULL },
     99   { "-z origin", '\0', NULL, OPTION_DOC,
    100     N_("Object requires immediate handling of $ORIGIN.") },
    101   { "-z now", '\0', NULL, OPTION_DOC,
    102     N_("Relocation will not be processed lazily.") },
    103   { "-z nodelete", '\0', NULL, OPTION_DOC,
    104     N_("Object cannot be unloaded at runtime.") },
    105   { "-z initfirst", '\0', NULL, OPTION_DOC,
    106     N_("Mark object to be initialized first.") },
    107   { "-z lazyload | nolazyload", '\0', NULL, OPTION_DOC,
    108     N_("Enable/disable lazy-loading flag for following dependencies.") },
    109   { "-z nodlopen", '\0', NULL, OPTION_DOC,
    110     N_("Mark object as not loadable with 'dlopen'.") },
    111   { "-z ignore | record", '\0', NULL, OPTION_DOC,
    112     N_("Ignore/record dependencies on unused DSOs.") },
    113   { "-z systemlibrary", '\0', NULL, OPTION_DOC,
    114     N_("Generated DSO will be a system library.") },
    115 
    116   { NULL, 'l', N_("FILE"), OPTION_HIDDEN, NULL },
    117 
    118   { NULL, '(', NULL, 0, N_("Start a group.") },
    119   { NULL, ')', NULL, 0, N_("End a group.") },
    120 
    121   { NULL, 'L', N_("PATH"), 0,
    122     N_("Add PATH to list of directories files are searched in.") },
    123 
    124   { NULL, 'c', N_("FILE"), 0, N_("Use linker script in FILE.") },
    125 
    126   { "entry", 'e', N_("ADDRESS"), 0, N_("Set entry point address.") },
    127 
    128   { "static", ARGP_static, NULL, OPTION_HIDDEN, NULL },
    129   { "-B static", ARGP_static, NULL, OPTION_DOC,
    130     N_("Do not link against shared libraries.") },
    131   { "dynamic", ARGP_dynamic, NULL, OPTION_HIDDEN, NULL },
    132   { "-B dynamic", ARGP_dynamic, NULL, OPTION_DOC,
    133     N_("Prefer linking against shared libraries.") },
    134 
    135   { "export-dynamic", 'E', NULL, 0, N_("Export all dynamic symbols.") },
    136 
    137   { "strip-all", 's', NULL, 0, N_("Strip all symbols.") },
    138   { "strip-debug", 'S', NULL, 0, N_("Strip debugging symbols.") },
    139 
    140   { "pagesize", ARGP_pagesize, "SIZE", 0,
    141     N_("Assume pagesize for the target system to be SIZE.") },
    142 
    143   { "rpath", ARGP_rpath, "PATH", OPTION_HIDDEN, NULL },
    144   { "rpath-link", ARGP_rpath_link, "PATH", OPTION_HIDDEN, NULL },
    145 
    146   { "runpath", ARGP_runpath, "PATH", 0, N_("Set runtime DSO search path.") },
    147   { "runpath-link", ARGP_runpath_link, "PATH", 0,
    148     N_("Set link time DSO search path.") },
    149 
    150   { NULL, 'i', NULL, 0, N_("Ignore LD_LIBRARY_PATH environment variable.") },
    151 
    152   { "version-script", ARGP_version_script, "FILE", 0,
    153     N_("Read version information from FILE.") },
    154 
    155   { "emulation", 'm', "NAME", 0, N_("Set emulation to NAME.") },
    156 
    157   { "shared", 'G', NULL, 0, N_("Generate dynamic shared object.") },
    158   { NULL, 'r', NULL, 0L, N_("Generate relocatable object.") },
    159 
    160   { NULL, 'B', "KEYWORD", OPTION_HIDDEN, "" },
    161   { "-B local", 'B', NULL, OPTION_DOC,
    162     N_("Causes symbol not assigned to a version be reduced to local.") },
    163 
    164   { "gc-sections", ARGP_gc_sections, NULL, 0, N_("Remove unused sections.") },
    165   { "no-gc-sections", ARGP_no_gc_sections, NULL, 0,
    166     N_("Don't remove unused sections.") },
    167 
    168   { "soname", 'h', "NAME", 0, N_("Set soname of shared object.") },
    169   { "dynamic-linker", 'I', "NAME", 0, N_("Set the dynamic linker name.") },
    170 
    171   { NULL, 'Q', "YN", OPTION_HIDDEN, NULL },
    172   { "-Q y | n", 'Q', NULL, OPTION_DOC,
    173     N_("Add/suppress addition indentifying link-editor to .comment section") },
    174 
    175 #if YYDEBUG
    176   { "yydebug", ARGP_yydebug, NULL, 0,
    177     N_("Select to get parser debug information") },
    178 #endif
    179 
    180   { NULL, 0, NULL, 0, NULL }
    181 };
    182 
    183 /* Short description of program.  */
    184 static const char doc[] = N_("Combine object and archive files.");
    185 
    186 /* Strings for arguments in help texts.  */
    187 static const char args_doc[] = N_("[FILE]...");
    188 
    189 /* Prototype for option handler.  */
    190 static error_t parse_opt_1st (int key, char *arg, struct argp_state *state);
    191 static error_t parse_opt_2nd (int key, char *arg, struct argp_state *state);
    192 
    193 /* Function to print some extra text in the help message.  */
    194 static char *more_help (int key, const char *text, void *input);
    195 
    196 /* Data structure to communicate with argp functions.  */
    197 static struct argp argp_1st =
    198 {
    199   options, parse_opt_1st, args_doc, doc, NULL, more_help
    200 };
    201 static struct argp argp_2nd =
    202 {
    203   options, parse_opt_2nd, args_doc, doc, NULL, more_help
    204 };
    205 
    206 
    207 /* Linker state.  This contains all global information.  */
    208 struct ld_state ld_state;
    209 
    210 /* List of the input files.  */
    211 static struct file_list
    212 {
    213   const char *name;
    214   struct file_list *next;
    215 } *input_file_list;
    216 
    217 /* If nonzero be verbose.  */
    218 int verbose;
    219 
    220 /* If nonzero, trade speed for less memory/address space usage.  */
    221 int conserve_memory;
    222 
    223 /* The emulation name to use.  */
    224 static const char *emulation;
    225 
    226 /* Keep track of the nesting level.  Even though we don't handle nested
    227    groups we still keep track to improve the error messages.  */
    228 static int group_level;
    229 
    230 /* The last file we processed.  */
    231 static struct usedfiles *last_file;
    232 
    233 /* The default linker script.  */
    234 /* XXX We'll do this a bit different in the real solution.  */
    235 static const char *linker_script = SRCDIR "/elf32-i386.script";
    236 
    237 /* Nonzero if an error occurred while loading the input files.  */
    238 static int error_loading;
    239 
    240 
    241 /* Intermediate storage for the LD_LIBRARY_PATH information from the
    242    environment.  */
    243 static char *ld_library_path1;
    244 
    245 /* Flag used to communicate with the scanner.  */
    246 int ld_scan_version_script;
    247 
    248 /* Name of the input file.  */
    249 const char *ldin_fname;
    250 
    251 /* Define by parser if required.  */
    252 extern int lddebug;
    253 
    254 
    255 /* Prototypes for local functions.  */
    256 static void parse_z_option (const char *arg);
    257 static void parse_z_option_2 (const char *arg);
    258 static void parse_B_option (const char *arg);
    259 static void parse_B_option_2 (const char *arg);
    260 static void determine_output_format (void);
    261 static void load_needed (void);
    262 static void collect_sections (void);
    263 static void add_rxxpath (struct pathelement **pathp, const char *str);
    264 static void gen_rxxpath_data (void);
    265 static void read_version_script (const char *fname);
    266 static void create_lscript_symbols (void);
    267 static void create_special_section_symbol (struct symbol **symp,
    268 					   const char *name);
    269 
    270 
    271 int
    272 main (int argc, char *argv[])
    273 {
    274   int remaining;
    275   int err;
    276 
    277 #ifndef NDEBUG
    278   /* Enable memory debugging.  */
    279   mtrace ();
    280 #endif
    281 
    282   /* Sanity check.  We always want to use the LFS functionality.  */
    283   if (sizeof (off_t) != sizeof (off64_t))
    284     abort ();
    285 
    286   /* We use no threads here which can interfere with handling a stream.  */
    287   __fsetlocking (stdin, FSETLOCKING_BYCALLER);
    288   __fsetlocking (stdout, FSETLOCKING_BYCALLER);
    289   __fsetlocking (stderr, FSETLOCKING_BYCALLER);
    290 
    291   /* Set locale.  */
    292   setlocale (LC_ALL, "");
    293 
    294   /* Make sure the message catalog can be found.  */
    295   bindtextdomain (PACKAGE, LOCALEDIR);
    296 
    297   /* Initialize the message catalog.  */
    298   textdomain (PACKAGE);
    299 
    300   /* Before we start tell the ELF library which version we are using.  */
    301   elf_version (EV_CURRENT);
    302 
    303   /* The user can use the LD_LIBRARY_PATH environment variable to add
    304      additional lookup directories.  */
    305   ld_library_path1 = getenv ("LD_LIBRARY_PATH");
    306 
    307   /* Initialize the memory handling.  */
    308 #define obstack_chunk_alloc xmalloc
    309 #define obstack_chunk_free free
    310   obstack_init (&ld_state.smem);
    311 
    312   /* One quick pass over the parameters which allows us to scan for options
    313      with global effect which influence the rest of the processing.  */
    314   argp_parse (&argp_1st, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
    315 
    316   /* We need at least one input file.  */
    317   if (input_file_list == NULL)
    318     {
    319       error (0, 0, gettext ("At least one input file needed"));
    320       argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
    321       exit (EXIT_FAILURE);
    322     }
    323 
    324   /* Determine which ELF backend to use.  */
    325   determine_output_format ();
    326 
    327   /* Prepare state.  */
    328   err = ld_prepare_state (emulation);
    329   if (err != 0)
    330     error (EXIT_FAILURE, 0, gettext ("error while preparing linking"));
    331 
    332   /* XXX Read the linker script now.  Since we later will have the linker
    333      script built in we don't go into trouble to make sure we handle GROUP
    334      statements in the script.  This simply must not happen.  */
    335   ldin = fopen (linker_script, "r");
    336   if (ldin == NULL)
    337     error (EXIT_FAILURE, errno, gettext ("cannot open linker script \"%s\""),
    338 	   linker_script);
    339   /* No need for locking.  */
    340   __fsetlocking (ldin, FSETLOCKING_BYCALLER);
    341 
    342   ld_state.srcfiles = NULL;
    343   ldlineno = 1;
    344   ld_scan_version_script = 0;
    345   ldin_fname = linker_script;
    346   if (ldparse () != 0)
    347     /* Something went wrong during parsing.  */
    348     exit (EXIT_FAILURE);
    349   fclose (ldin);
    350 
    351   /* We now might have a list of directories to look for libraries in
    352      named by the linker script.  Put them in a different list so that
    353      they are searched after all paths given by the user on the
    354      command line.  */
    355   ld_state.default_paths = ld_state.paths;
    356   ld_state.paths = ld_state.tailpaths = NULL;
    357 
    358   /* Get runpath/rpath information in usable form.  */
    359   gen_rxxpath_data ();
    360 
    361   /* Parse and process arguments for real.  */
    362   argp_parse (&argp_2nd, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
    363   /* All options should have been processed by the argp parser.  */
    364   assert (remaining == argc);
    365 
    366   /* Process the last file.  */
    367   while (last_file != NULL)
    368     /* Try to open the file.  */
    369     error_loading |= FILE_PROCESS (-1, last_file, &ld_state, &last_file);
    370 
    371   /* Stop if there has been a problem while reading the input files.  */
    372   if (error_loading)
    373     exit (error_loading);
    374 
    375   /* See whether all opened -( were closed.  */
    376   if (group_level > 0)
    377     {
    378       error (0, 0, gettext ("-( without matching -)"));
    379       argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
    380       exit (EXIT_FAILURE);
    381     }
    382 
    383   /* When we create a relocatable file we don't have to look for the
    384      DT_NEEDED DSOs and we also don't test for undefined symbols.  */
    385   if (ld_state.file_type != relocatable_file_type)
    386     {
    387       /* At this point we have loaded all the direct dependencies.  What
    388 	 remains to be done is find the indirect dependencies.  These are
    389 	 DSOs which are referenced by the DT_NEEDED entries in the DSOs
    390 	 which are direct dependencies.  We have to transitively find and
    391 	 load all these dependencies.  */
    392       load_needed ();
    393 
    394       /* At this point all object files and DSOs are read.  If there
    395          are still undefined symbols left they might have to be
    396          synthesized from the linker script.  */
    397       create_lscript_symbols ();
    398 
    399       /* Now that we have loaded all the object files we can determine
    400 	 whether we have any non-weak unresolved references left.  If
    401 	 there are any we stop.  If the user used the '-z nodefs' option
    402 	 and we are creating a DSO don't perform the tests.  */
    403       if (FLAG_UNRESOLVED (&ld_state) != 0)
    404 	exit (1);
    405     }
    406 
    407   /* Collect information about the relocations which will be carried
    408      forward into the output.  We have to do this here and now since
    409      we need to know which sections have to be created.  */
    410   if (ld_state.file_type != relocatable_file_type)
    411     {
    412       void *p ;
    413       struct scnhead *h;
    414 
    415       p = NULL;
    416       while ((h = ld_section_tab_iterate (&ld_state.section_tab, &p)) != NULL)
    417 	if (h->type == SHT_REL || h->type == SHT_RELA)
    418 	  {
    419 	    struct scninfo *runp = h->last;
    420 	    do
    421 	      {
    422 		/* If we are processing the relocations determine how
    423 		   many will be in the output file.  Also determine
    424 		   how many GOT entries are needed.  */
    425 		COUNT_RELOCATIONS (&ld_state, runp);
    426 
    427 		ld_state.relsize_total += runp->relsize;
    428 	      }
    429 	    while ((runp = runp->next) != h->last);
    430 	  }
    431     }
    432 
    433   /* Not part of the gABI, but part of every psABI: the symbols for the
    434      GOT section.  Add the symbol if necessary.  */
    435   if (ld_state.need_got)
    436     create_special_section_symbol (&ld_state.got_symbol,
    437 				   "_GLOBAL_OFFSET_TABLE_");
    438   /* Similarly for the _DYNAMIC symbol which points to the dynamic
    439      section.  */
    440   if (dynamically_linked_p ())
    441     create_special_section_symbol (&ld_state.dyn_symbol, "_DYNAMIC");
    442 
    443   /* We are ready to start working on the output file.  Not all
    444      information has been gather or created yet.  This will be done as
    445      we go.  Open the file now.  */
    446   if (OPEN_OUTFILE (&ld_state, EM_NONE, ELFCLASSNONE, ELFDATANONE) != 0)
    447     exit (1);
    448 
    449   /* Create the sections which are generated by the linker and are not
    450      present in the input file.  The output file must already have
    451      been opened since we need the ELF descriptor to deduce type
    452      sizes.  */
    453   GENERATE_SECTIONS (&ld_state);
    454 
    455   /* At this point we have read all the files and know all the
    456      sections which have to be linked into the application.  We do now
    457      create an array listing all the sections.  We will than pass this
    458      array to a system specific function which can reorder it at will.
    459      The functions can also merge sections if this is what is
    460      wanted.  */
    461   collect_sections ();
    462 
    463   /* Create the output sections now.  This may requires sorting them
    464      first.  */
    465   CREATE_SECTIONS (&ld_state);
    466 
    467   /* Create the output file data.  Appropriate code for the selected
    468      output file type is called.  */
    469   if (CREATE_OUTFILE (&ld_state) != 0)
    470     exit (1);
    471 
    472   /* Finalize the output file, write the data out.  */
    473   err |= FINALIZE (&ld_state);
    474 
    475   /* Return with an non-zero exit status also if any error message has
    476      been printed.  */
    477   return err | (error_message_count != 0);
    478 }
    479 
    480 
    481 static char *
    482 more_help (int key, const char *text, void *input)
    483 {
    484   char *buf;
    485 
    486   switch (key)
    487     {
    488     case ARGP_KEY_HELP_EXTRA:
    489       /* We print some extra information.  */
    490       if (asprintf (&buf, gettext ("Please report bugs to %s.\n"),
    491 		    PACKAGE_BUGREPORT) < 0)
    492 	buf = NULL;
    493       return buf;
    494 
    495     default:
    496       break;
    497     }
    498   return (char *) text;
    499 }
    500 
    501 
    502 /* Quick scan of the parameter list for options with global effect.  */
    503 static error_t
    504 parse_opt_1st (int key, char *arg, struct argp_state *state)
    505 {
    506   switch (key)
    507     {
    508     case 'B':
    509       parse_B_option (arg);
    510       break;
    511 
    512     case 'c':
    513       linker_script = arg;
    514       break;
    515 
    516     case 'E':
    517       ld_state.export_all_dynamic = true;
    518       break;
    519 
    520     case 'G':
    521       if (ld_state.file_type != no_file_type)
    522 	error (EXIT_FAILURE, 0,
    523 	       gettext ("only one option of -G and -r is allowed"));
    524       ld_state.file_type = dso_file_type;
    525 
    526       /* If we generate a DSO we have to export all symbols.  */
    527       ld_state.export_all_dynamic = true;
    528       break;
    529 
    530     case 'h':
    531       ld_state.soname = arg;
    532       break;
    533 
    534     case 'i':
    535       /* Discard the LD_LIBRARY_PATH value we found.  */
    536       ld_library_path1 = NULL;
    537       break;
    538 
    539     case 'I':
    540       ld_state.interp = arg;
    541       break;
    542 
    543     case 'm':
    544       if (emulation != NULL)
    545 	error (EXIT_FAILURE, 0, gettext ("more than one '-m' parameter"));
    546       emulation = arg;
    547       break;
    548 
    549     case 'Q':
    550       if (arg[1] == '\0' && (arg[0] == 'y' || arg[0] == 'Y'))
    551 	ld_state.add_ld_comment = true;
    552       else if (arg[1] == '\0' && (arg[0] == 'n' || arg[0] == 'N'))
    553 	ld_state.add_ld_comment = true;
    554       else
    555 	error (EXIT_FAILURE, 0, gettext ("unknown option `-%c %s'"), 'Q', arg);
    556       break;
    557 
    558     case 'r':
    559       if (ld_state.file_type != no_file_type)
    560 	error (EXIT_FAILURE, 0,
    561 	       gettext ("only one option of -G and -r is allowed"));
    562       ld_state.file_type = relocatable_file_type;
    563       break;
    564 
    565     case 'S':
    566       ld_state.strip = strip_debug;
    567       break;
    568 
    569     case 't':
    570       ld_state.trace_files = true;
    571       break;
    572 
    573     case 'v':
    574       verbose = 1;
    575       break;
    576 
    577     case 'z':
    578       /* The SysV linker used 'z' to pass various flags to the linker.
    579 	 We follow this.  See 'parse_z_option' for the options we
    580 	 recognize.  */
    581       parse_z_option (arg);
    582       break;
    583 
    584     case ARGP_pagesize:
    585       {
    586 	char *endp;
    587 	ld_state.pagesize = strtoul (arg, &endp, 0);
    588 	if (*endp != '\0')
    589 	  {
    590 	    if (endp[1] == '\0' && tolower (*endp) == 'k')
    591 	      ld_state.pagesize *= 1024;
    592 	    else if (endp[1] == '\0' && tolower (*endp) == 'm')
    593 	      ld_state.pagesize *= 1024 * 1024;
    594 	    else
    595 	      {
    596 		error (0, 0,
    597 		       gettext ("invalid page size value \"%s\": ignored"),
    598 		       arg);
    599 		ld_state.pagesize = 0;
    600 	      }
    601 	  }
    602       }
    603       break;
    604 
    605     case ARGP_rpath:
    606       add_rxxpath (&ld_state.rpath, arg);
    607       break;
    608 
    609     case ARGP_rpath_link:
    610       add_rxxpath (&ld_state.rpath_link, arg);
    611       break;
    612 
    613     case ARGP_runpath:
    614       add_rxxpath (&ld_state.runpath, arg);
    615       break;
    616 
    617     case ARGP_runpath_link:
    618       add_rxxpath (&ld_state.runpath_link, arg);
    619       break;
    620 
    621     case ARGP_gc_sections:
    622     case ARGP_no_gc_sections:
    623       ld_state.gc_sections = key == ARGP_gc_sections;
    624       break;
    625 
    626     case 's':
    627       if (arg == NULL)
    628 	{
    629 	  if (ld_state.strip == strip_all)
    630 	    ld_state.strip = strip_everything;
    631 	  else
    632 	    ld_state.strip = strip_all;
    633 	  break;
    634 	}
    635       /* FALLTHROUGH */
    636 
    637     case 'e':
    638     case 'o':
    639     case 'O':
    640     case ARGP_whole_archive:
    641     case ARGP_no_whole_archive:
    642     case 'L':
    643     case '(':
    644     case ')':
    645     case 'l':
    646     case ARGP_static:
    647     case ARGP_dynamic:
    648     case ARGP_version_script:
    649       /* We'll handle these in the second pass.  */
    650       break;
    651 
    652     case ARGP_KEY_ARG:
    653       {
    654 	struct file_list *newp;
    655 
    656 	newp = (struct file_list *) xmalloc (sizeof (struct file_list));
    657 	newp->name = arg;
    658 #ifndef NDEBUG
    659 	newp->next = NULL;
    660 #endif
    661 	CSNGL_LIST_ADD_REAR (input_file_list, newp);
    662       }
    663       break;
    664 
    665 #if YYDEBUG
    666     case ARGP_yydebug:
    667       lddebug = 1;
    668       break;
    669 #endif
    670 
    671     case ARGP_no_undefined:
    672       ld_state.nodefs = false;
    673       break;
    674 
    675     case ARGP_conserve:
    676       conserve_memory = 1;
    677       break;
    678 
    679     default:
    680       return ARGP_ERR_UNKNOWN;
    681     }
    682   return 0;
    683 }
    684 
    685 
    686 /* Handle program arguments for real.  */
    687 static error_t
    688 parse_opt_2nd (int key, char *arg, struct argp_state *state)
    689 {
    690   static bool group_start_requested;
    691   static bool group_end_requested;
    692 
    693   switch (key)
    694     {
    695     case 'B':
    696       parse_B_option_2 (arg);
    697       break;
    698 
    699     case 'e':
    700       ld_state.entry = arg;
    701       break;
    702 
    703     case 'o':
    704       if (ld_state.outfname != NULL)
    705 	{
    706 	  error (0, 0, gettext ("More than one output file name given."));
    707 	see_help:
    708 	  argp_help (&argp_2nd, stderr, ARGP_HELP_SEE, "ld");
    709 	  exit (EXIT_FAILURE);
    710 	}
    711       ld_state.outfname = arg;
    712       break;
    713 
    714     case 'O':
    715       if (arg == NULL)
    716 	ld_state.optlevel = 1;
    717       else
    718 	{
    719 	  char *endp;
    720 	  unsigned long int level = strtoul (arg, &endp, 10);
    721 	  if (*endp != '\0')
    722 	    {
    723 	      error (0, 0, gettext ("Invalid optimization level `%s'"), arg);
    724 	      goto see_help;
    725 	    }
    726 	  ld_state.optlevel = level;
    727 	}
    728       break;
    729 
    730     case ARGP_whole_archive:
    731       ld_state.extract_rule = allextract;
    732       break;
    733     case ARGP_no_whole_archive:
    734       ld_state.extract_rule = defaultextract;
    735       break;
    736 
    737     case ARGP_static:
    738     case ARGP_dynamic:
    739       /* Enable/disable use for DSOs.  */
    740       ld_state.statically = key == ARGP_static;
    741       break;
    742 
    743     case 'z':
    744       /* The SysV linker used 'z' to pass various flags to the linker.
    745 	 We follow this.  See 'parse_z_option' for the options we
    746 	 recognize.  */
    747       parse_z_option_2 (arg);
    748       break;
    749 
    750     case ARGP_version_script:
    751       read_version_script (arg);
    752       break;
    753 
    754     case 'L':
    755       /* Add a new search directory.  */
    756       ld_new_searchdir (arg);
    757       break;
    758 
    759     case '(':
    760       /* Start a link group.  We have to be able to determine the object
    761 	 file which is named next.  Do this by remembering a pointer to
    762 	 the pointer which will point to the next object.  */
    763       if (verbose && (group_start_requested || !group_end_requested))
    764 	error (0, 0, gettext ("nested -( -) groups are not allowed"));
    765 
    766       /* Increment the nesting level.  */
    767       ++group_level;
    768 
    769       /* Record group start.  */
    770       group_start_requested = true;
    771       group_end_requested = false;
    772       break;
    773 
    774     case ')':
    775       /* End a link group.  If there is no group open this is clearly
    776 	 a bug.  If there is a group open insert a back reference
    777 	 pointer in the record for the last object of the group.  If
    778 	 there is no new object or just one don't do anything.  */
    779       if (!group_end_requested)
    780 	{
    781 	  if (group_level == 0)
    782 	    {
    783 	      error (0, 0, gettext ("-) without matching -("));
    784 	      goto see_help;
    785 	    }
    786 	}
    787       else
    788 	last_file->group_end = true;
    789 
    790       if (group_level > 0)
    791 	--group_level;
    792       break;
    793 
    794     case 'l':
    795     case ARGP_KEY_ARG:
    796       {
    797 	while (last_file != NULL)
    798 	  /* Try to open the file.  */
    799 	  error_loading |= FILE_PROCESS (-1, last_file, &ld_state, &last_file);
    800 
    801 	last_file = ld_new_inputfile (arg,
    802 				      key == 'l'
    803 				      ? archive_file_type
    804 				      : relocatable_file_type);
    805 	if (group_start_requested)
    806 	  {
    807 	    last_file->group_start = true;
    808 
    809 	    group_start_requested = false;
    810 	    group_end_requested = true;
    811 	  }
    812       }
    813       break;
    814 
    815     default:
    816       /* We can catch all other options here.  They either have
    817 	 already been handled or, if the parameter was not correct,
    818 	 the error has been reported.  */
    819       break;
    820     }
    821   return 0;
    822 }
    823 
    824 
    825 /* Load all the DSOs named as dependencies in other DSOs we already
    826    loaded.  */
    827 static void
    828 load_needed (void)
    829 {
    830   struct usedfiles *first;
    831   struct usedfiles *runp;
    832 
    833   /* XXX There is one problem here: do we allow references from
    834      regular object files to be satisfied by these implicit
    835      dependencies?  The old linker allows this and several libraries
    836      depend on this.  Solaris' linker does not allow this; it provides
    837      the user with a comprehensive error message explaining the
    838      situation.
    839 
    840      XXX IMO the old ld behavior is correct since this is also how the
    841      dynamic linker will work.  It will look for unresolved references
    842      in all loaded DSOs.
    843 
    844      XXX Should we add an option to get Solaris compatibility?  */
    845   if (ld_state.needed == NULL)
    846     return;
    847 
    848   runp = first = ld_state.needed->next;
    849   do
    850     {
    851       struct usedfiles *ignore;
    852       struct usedfiles *next = runp->next;
    853       int err;
    854 
    855       err = FILE_PROCESS (-1, runp, &ld_state, &ignore);
    856       if (err != 0)
    857 	/* Something went wrong.  */
    858 	exit (err);
    859 
    860       runp = next;
    861     }
    862   while (runp != first);
    863 }
    864 
    865 
    866 /* Print the version information.  */
    867 static void
    868 print_version (FILE *stream, struct argp_state *state)
    869 {
    870   fprintf (stream, "ld (%s) %s\n", PACKAGE_NAME, VERSION);
    871   fprintf (stream, gettext ("\
    872 Copyright (C) %s Red Hat, Inc.\n\
    873 This is free software; see the source for copying conditions.  There is NO\n\
    874 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
    875 "), "2004");
    876   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
    877 }
    878 
    879 
    880 /* There are a lot of -z options, parse them here.  Some of them have
    881    to be parsed in the first pass, others must be handled in the
    882    second pass.  */
    883 static void
    884 parse_z_option (const char *arg)
    885 {
    886   if (strcmp (arg, "nodefaultlib") == 0
    887       /* This is only meaningful if we create a DSO.  */
    888       && ld_state.file_type == dso_file_type)
    889     ld_state.dt_flags_1 |= DF_1_NODEFLIB;
    890   else if (strcmp (arg, "muldefs") == 0)
    891     ld_state.muldefs = true;
    892   else if (strcmp (arg, "nodefs") == 0)
    893     ld_state.nodefs = true;
    894   else if (strcmp (arg, "defs") == 0)
    895     ld_state.nodefs = false;
    896   else if (strcmp (arg, "now") == 0)
    897     /* We could also set the DF_1_NOW flag in DT_FLAGS_1 but this isn't
    898        necessary.  */
    899     ld_state.dt_flags |= DF_BIND_NOW;
    900   else if (strcmp (arg, "origin") == 0)
    901     /* We could also set the DF_1_ORIGIN flag in DT_FLAGS_1 but this isn't
    902        necessary.  */
    903     ld_state.dt_flags |= DF_ORIGIN;
    904   else if (strcmp (arg, "nodelete") == 0
    905 	   /* This is only meaningful if we create a DSO.  */
    906 	   && ld_state.file_type == dso_file_type)
    907     ld_state.dt_flags_1 |= DF_1_NODELETE;
    908   else if (strcmp (arg, "initfirst") == 0)
    909     ld_state.dt_flags_1 |= DF_1_INITFIRST;
    910   else if (strcmp (arg, "nodlopen") == 0
    911 	   /* This is only meaningful if we create a DSO.  */
    912 	   && ld_state.file_type == dso_file_type)
    913     ld_state.dt_flags_1 |= DF_1_NOOPEN;
    914   else if (strcmp (arg, "ignore") == 0)
    915     ld_state.ignore_unused_dsos = true;
    916   else if (strcmp (arg, "record") == 0)
    917     ld_state.ignore_unused_dsos = false;
    918   else if (strcmp (arg, "systemlibrary") == 0)
    919     ld_state.is_system_library = true;
    920   else if (strcmp (arg, "allextract") != 0
    921 	   && strcmp (arg, "defaultextract") != 0
    922 	   && strcmp (arg, "weakextract") != 0
    923 	   && strcmp (arg, "lazyload") != 0
    924 	   && strcmp (arg, "nolazyload") != 0)
    925     error (0, 0, gettext ("unknown option `-%c %s'"), 'z', arg);
    926 }
    927 
    928 
    929 static void
    930 parse_z_option_2 (const char *arg)
    931 {
    932   if (strcmp (arg, "allextract") == 0)
    933     ld_state.extract_rule = allextract;
    934   else if (strcmp (arg, "defaultextract") == 0)
    935     ld_state.extract_rule = defaultextract;
    936   else if (strcmp (arg, "weakextract") == 0)
    937     ld_state.extract_rule = weakextract;
    938   else if (strcmp (arg, "lazyload") == 0)
    939     ld_state.lazyload = true;
    940   else if (strcmp (arg, "nolazyload") == 0)
    941     ld_state.lazyload = false;
    942 }
    943 
    944 
    945 /* There are a lot of -B options, parse them here.  */
    946 static void
    947 parse_B_option (const char *arg)
    948 {
    949   if (strcmp (arg, "local") == 0)
    950     ld_state.default_bind_local = true;
    951   else if (strcmp (arg, "symbolic") != 0
    952 	   && strcmp (arg, "static") != 0
    953 	   && strcmp (arg, "dynamic") != 0)
    954     error (0, 0, gettext ("unknown option '-%c %s'"), 'B', arg);
    955 }
    956 
    957 
    958 /* The same functionality, but called in the second pass over the
    959    parameters.  */
    960 static void
    961 parse_B_option_2 (const char *arg)
    962 {
    963   if (strcmp (arg, "static") == 0)
    964     ld_state.statically = true;
    965   else if (strcmp (arg, "dynamic") == 0)
    966     ld_state.statically = false;
    967   else if (strcmp (arg, "symbolic") == 0
    968 	   /* This is only meaningful if we create a DSO.  */
    969 	   && ld_state.file_type == dso_file_type)
    970     ld_state.dt_flags |= DF_SYMBOLIC;
    971 }
    972 
    973 
    974 static void
    975 determine_output_format (void)
    976 {
    977   /* First change the 'input_file_list' variable in a simple
    978      single-linked list.  */
    979   struct file_list *last = input_file_list;
    980   input_file_list = input_file_list->next;
    981   last->next = NULL;
    982 
    983   /* Determine the target configuration which we are supposed to use.
    984      The user can use the '-m' option to select one.  If this is
    985      missing we are trying to load one file and determine the
    986      architecture from that.  */
    987   if (emulation != NULL)
    988     {
    989       ld_state.ebl = ebl_openbackend_emulation (emulation);
    990 
    991       assert (ld_state.ebl != NULL);
    992     }
    993   else
    994     {
    995       /* Find an ELF input file and let it determine the ELf backend.  */
    996       struct file_list *runp = input_file_list;
    997 
    998       while (runp != NULL)
    999 	{
   1000 	  int fd = open (runp->name, O_RDONLY);
   1001 	  if (fd != -1)
   1002 	    {
   1003 	      int try (Elf *elf)
   1004 		{
   1005 		  int result = 0;
   1006 
   1007 		  if (elf == NULL)
   1008 		    return 0;
   1009 
   1010 		  if (elf_kind (elf) == ELF_K_ELF)
   1011 		    {
   1012 		      /* We have an ELF file.  We now can find out
   1013 			 what the output format should be.  */
   1014 		      XElf_Ehdr_vardef(ehdr);
   1015 
   1016 		      /* Get the ELF header of the object.  */
   1017 		      xelf_getehdr (elf, ehdr);
   1018 		      if (ehdr != NULL)
   1019 			ld_state.ebl =
   1020 			  ebl_openbackend_machine (ehdr->e_machine);
   1021 
   1022 		      result = 1;
   1023 		    }
   1024 		  else if (elf_kind (elf) == ELF_K_AR)
   1025 		    {
   1026 		      /* Try the archive members.  This could
   1027 			 potentially lead to wrong results if the
   1028 			 archive contains files for more than one
   1029 			 architecture.  But this is the user's
   1030 			 problem.  */
   1031 		      Elf *subelf;
   1032 		      Elf_Cmd cmd = ELF_C_READ_MMAP;
   1033 
   1034 		      while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
   1035 			{
   1036 			  cmd = elf_next (subelf);
   1037 
   1038 			  if (try (subelf) != 0)
   1039 			    break;
   1040 			}
   1041 		    }
   1042 
   1043 		  elf_end (elf);
   1044 
   1045 		  return result;
   1046 		}
   1047 
   1048 	      if (try (elf_begin (fd, ELF_C_READ_MMAP, NULL)) != 0)
   1049 		/* Found a file.  */
   1050 		break;
   1051 	    }
   1052 
   1053 	  runp = runp->next;
   1054 	}
   1055 
   1056       if (ld_state.ebl == NULL)
   1057 	{
   1058 	  error (0, 0, gettext ("\
   1059 could not find input file to determine output file format"));
   1060 	  error (EXIT_FAILURE, 0, gettext ("\
   1061 try again with an appropriate '-m' parameter"));
   1062 	}
   1063     }
   1064 
   1065   /* We don't need the list of input files anymore.  The second run over
   1066      the parameters will handle them.  */
   1067   while (input_file_list != NULL)
   1068     {
   1069       struct file_list *oldp = input_file_list;
   1070       input_file_list = input_file_list->next;
   1071       free (oldp);
   1072     }
   1073 
   1074   /* We also know now what kind of file we are supposed to create.  If
   1075      the user hasn't selected anythign we create and executable.  */
   1076   if (ld_state.file_type == no_file_type)
   1077     ld_state.file_type = executable_file_type;
   1078 }
   1079 
   1080 /* Add DIR to the list of directories searched for object files and
   1081    libraries.  */
   1082 void
   1083 ld_new_searchdir (const char *dir)
   1084 {
   1085   struct pathelement *newpath;
   1086 
   1087   newpath = (struct pathelement *)
   1088     obstack_calloc (&ld_state.smem, sizeof (struct pathelement));
   1089 
   1090   newpath->pname = dir;
   1091 
   1092   /* Enqueue the file.  */
   1093   if (ld_state.tailpaths == NULL)
   1094     ld_state.paths = ld_state.tailpaths = newpath;
   1095   else
   1096     {
   1097       ld_state.tailpaths->next = newpath;
   1098       ld_state.tailpaths = newpath;
   1099     }
   1100 }
   1101 
   1102 
   1103 struct usedfiles *
   1104 ld_new_inputfile (const char *fname, enum file_type type)
   1105 {
   1106   struct usedfiles *newfile = (struct usedfiles *)
   1107     obstack_calloc (&ld_state.smem, sizeof (struct usedfiles));
   1108 
   1109   newfile->soname = newfile->fname = newfile->rfname = fname;
   1110   newfile->file_type = type;
   1111   newfile->extract_rule = ld_state.extract_rule;
   1112   newfile->lazyload = ld_state.lazyload;
   1113   newfile->status = not_opened;
   1114 
   1115   return newfile;
   1116 }
   1117 
   1118 
   1119 /* Create an array listing all the sections.  We will than pass this
   1120    array to a system specific function which can reorder it at will.
   1121    The functions can also merge sections if this is what is
   1122    wanted.  */
   1123 static void
   1124 collect_sections (void)
   1125 {
   1126   void *p ;
   1127   struct scnhead *h;
   1128   size_t cnt;
   1129 
   1130   /* We have that many sections.  At least for now.  */
   1131   ld_state.nallsections = ld_state.section_tab.filled;
   1132 
   1133   /* Allocate the array.  We allocate one more entry than computed so
   1134      far since we might need a new section for the copy relocations.  */
   1135   ld_state.allsections =
   1136     (struct scnhead **) obstack_alloc (&ld_state.smem,
   1137 				       (ld_state.nallsections + 1)
   1138 				       * sizeof (struct scnhead *));
   1139 
   1140   /* Fill the array.  We rely here on the hash table iterator to
   1141      return the entries in the order they were added.  */
   1142   cnt = 0;
   1143   p = NULL;
   1144   while ((h = ld_section_tab_iterate (&ld_state.section_tab, &p)) != NULL)
   1145     {
   1146       struct scninfo *runp;
   1147       bool used = false;
   1148 
   1149       if (h->kind == scn_normal)
   1150 	{
   1151 	  runp = h->last;
   1152 	  do
   1153 	    {
   1154 	      if (h->type == SHT_REL || h->type == SHT_RELA)
   1155 		{
   1156 		  if (runp->used)
   1157 		    /* This is a relocation section.  If the section
   1158 		       it is relocating is used in the result so must
   1159 		       the relocation section.  */
   1160 		    runp->used
   1161 		      = runp->fileinfo->scninfo[SCNINFO_SHDR (runp->shdr).sh_info].used;
   1162 		}
   1163 
   1164 	      /* Accumulate the result.  */
   1165 	      used |= runp->used;
   1166 
   1167 	      /* Next input section.  */
   1168 	      runp = runp->next;
   1169 	    }
   1170 	  while (runp != h->last);
   1171 
   1172 	  h->used = used;
   1173 	}
   1174 
   1175       ld_state.allsections[cnt++] = h;
   1176     }
   1177   ld_state.nusedsections = cnt;
   1178 
   1179   assert (cnt == ld_state.nallsections);
   1180 }
   1181 
   1182 
   1183 /* Add given path to the end of list.  */
   1184 static void
   1185 add_rxxpath (struct pathelement **pathp, const char *str)
   1186 {
   1187   struct pathelement *newp;
   1188 
   1189   /* The path elements can in theory be freed after we read all the
   1190      files.  But the amount of memory we are talking about is small
   1191      and the cost of free() calls is not neglectable.  */
   1192   newp = (struct pathelement *) obstack_alloc (&ld_state.smem, sizeof (*newp));
   1193   newp->pname = str;
   1194   newp->exist = 0;
   1195 #ifndef NDEBUG
   1196   newp->next = NULL;
   1197 #endif
   1198 
   1199   CSNGL_LIST_ADD_REAR (*pathp, newp);
   1200 }
   1201 
   1202 
   1203 /* Convert lists of possibly colon-separated directory lists into lists
   1204    where each entry is for a single directory.  */
   1205 static void
   1206 normalize_dirlist (struct pathelement **pathp)
   1207 {
   1208   struct pathelement *firstp = *pathp;
   1209 
   1210   do
   1211     {
   1212       const char *pname = (*pathp)->pname;
   1213       const char *colonp = strchrnul (pname, ':');
   1214 
   1215       if (colonp != NULL)
   1216 	{
   1217 	  struct pathelement *lastp = *pathp;
   1218 	  struct pathelement *newp;
   1219 
   1220 	  while (1)
   1221 	    {
   1222 	      if (colonp == pname)
   1223 		lastp->pname = ".";
   1224 	      else
   1225 		lastp->pname = obstack_strndup (&ld_state.smem, pname,
   1226 						colonp - pname);
   1227 
   1228 	      if (*colonp == '\0')
   1229 		break;
   1230 	      pname = colonp + 1;
   1231 
   1232 	      newp = (struct pathelement *) obstack_alloc (&ld_state.smem,
   1233 							   sizeof (*newp));
   1234 	      newp->next = lastp->next;
   1235 	      newp->exist = 0;
   1236 	      lastp = lastp->next = newp;
   1237 
   1238 	      colonp = strchrnul (pname, ':');
   1239 	    }
   1240 
   1241 	  pathp = &lastp->next;
   1242 	}
   1243       else
   1244 	pathp = &(*pathp)->next;
   1245     }
   1246   while (*pathp != firstp);
   1247 }
   1248 
   1249 
   1250 /* Called after all parameters are parsed to bring the runpath/rpath
   1251    information into a usable form.  */
   1252 static void
   1253 gen_rxxpath_data (void)
   1254 {
   1255   char *ld_library_path2;
   1256 
   1257   /* Convert the information in true single-linked lists for easy use.
   1258      At this point we also discard the rpath information if runpath
   1259      information is provided.  rpath is deprecated and should not be
   1260      used (or ever be invented for that matter).  */
   1261   if (ld_state.rpath != NULL)
   1262     {
   1263       struct pathelement *endp = ld_state.rpath;
   1264       ld_state.rpath = ld_state.rpath->next;
   1265       endp->next = NULL;
   1266     }
   1267   if (ld_state.rpath_link != NULL)
   1268     {
   1269       struct pathelement *endp = ld_state.rpath_link;
   1270       ld_state.rpath_link = ld_state.rpath_link->next;
   1271       endp->next = NULL;
   1272     }
   1273 
   1274   if (ld_state.runpath != NULL)
   1275     {
   1276       struct pathelement *endp = ld_state.runpath;
   1277       ld_state.runpath = ld_state.runpath->next;
   1278       endp->next = NULL;
   1279 
   1280       /* If rpath information is also available discard it.
   1281 	 XXX Should there be a possibility to avoid this?  */
   1282       while (ld_state.rpath != NULL)
   1283 	{
   1284 	  struct pathelement *old = ld_state.rpath;
   1285 	  ld_state.rpath = ld_state.rpath->next;
   1286 	  free (old);
   1287 	}
   1288     }
   1289   if (ld_state.runpath_link != NULL)
   1290     {
   1291       struct pathelement *endp = ld_state.runpath_link;
   1292       ld_state.runpath_link = ld_state.runpath_link->next;
   1293       endp->next = NULL;
   1294 
   1295       /* If rpath information is also available discard it.
   1296 	 XXX Should there be a possibility to avoid this?  */
   1297       while (ld_state.rpath_link != NULL)
   1298 	{
   1299 	  struct pathelement *old = ld_state.rpath_link;
   1300 	  ld_state.rpath_link = ld_state.rpath_link->next;
   1301 	  free (old);
   1302 	}
   1303 
   1304       /* The information in the strings in the list can actually be
   1305 	 directory lists themselves, with entries separated by colons.
   1306 	 Convert the list now to a list with one list entry for each
   1307 	 directory.  */
   1308       normalize_dirlist (&ld_state.runpath_link);
   1309     }
   1310   else if (ld_state.rpath_link != NULL)
   1311     /* Same as for the runpath_link above.  */
   1312     normalize_dirlist (&ld_state.rpath_link);
   1313 
   1314 
   1315   /* As a related task, handle the LD_LIBRARY_PATH value here.  First
   1316      we have to possibly split the value found (if it contains a
   1317      semicolon).  Then we have to split the value in list of
   1318      directories, i.e., split at the colons.  */
   1319   if (ld_library_path1 != NULL)
   1320     {
   1321       ld_library_path2 = strchr (ld_library_path1, ';');
   1322       if (ld_library_path2 == NULL)
   1323 	{
   1324 	  /* If no semicolon is present the directories are looked at
   1325 	     after the -L parameters (-> ld_library_path2).  */
   1326 	  ld_library_path2 = ld_library_path1;
   1327 	  ld_library_path1 = NULL;
   1328 	}
   1329       else
   1330 	{
   1331 	  /* NUL terminate the first part.  */
   1332 	  *ld_library_path2++ = '\0';
   1333 
   1334 	  /* Convert the string value in a list.  */
   1335 	  add_rxxpath (&ld_state.ld_library_path1, ld_library_path1);
   1336 	  normalize_dirlist (&ld_state.ld_library_path1);
   1337 	}
   1338 
   1339       add_rxxpath (&ld_state.ld_library_path2, ld_library_path2);
   1340       normalize_dirlist (&ld_state.ld_library_path2);
   1341     }
   1342 }
   1343 
   1344 
   1345 static void
   1346 read_version_script (const char *fname)
   1347 {
   1348   /* Open the file.  The name is supposed to be the complete (relative
   1349      or absolute) path.  No search along a path will be performed.  */
   1350   ldin = fopen (fname, "r");
   1351   if (ldin == NULL)
   1352     error (EXIT_FAILURE, errno, gettext ("cannot read version script \"%s\""),
   1353 	   fname);
   1354   /* No need for locking.  */
   1355   __fsetlocking (ldin, FSETLOCKING_BYCALLER);
   1356 
   1357   /* Tell the parser that this is a version script.  */
   1358   ld_scan_version_script = 1;
   1359 
   1360   ldlineno = 1;
   1361   ldin_fname = fname;
   1362   if (ldparse () != 0)
   1363     /* Something went wrong during parsing.  */
   1364     exit (EXIT_FAILURE);
   1365 
   1366   fclose (ldin);
   1367 }
   1368 
   1369 
   1370 static void
   1371 create_lscript_symbols (void)
   1372 {
   1373   /* Walk through the data from the linker script and generate all the
   1374      symbols which are required to be present and and those marked
   1375      with PROVIDE if there is a undefined reference.  */
   1376   if (ld_state.output_segments == NULL)
   1377     return;
   1378 
   1379   struct output_segment *segment = ld_state.output_segments->next;
   1380   do
   1381     {
   1382       struct output_rule *orule;
   1383 
   1384       for (orule = segment->output_rules; orule != NULL; orule = orule->next)
   1385 	if (orule->tag == output_assignment
   1386 	    /* The assignments to "." (i.e., the PC) have to be
   1387                ignored here.  */
   1388 	    && strcmp (orule->val.assignment->variable, ".") != 0)
   1389 	  {
   1390 	    struct symbol *s = ld_state.unresolved;
   1391 
   1392 	    /* Check whether the symbol is needed.  */
   1393 	    if (likely (s != NULL))
   1394 	      {
   1395 		struct symbol *first = s;
   1396 		const char *providename = orule->val.assignment->variable;
   1397 
   1398 		/* Determine whether the provided symbol is still
   1399 		   undefined.  */
   1400 		// XXX TODO Loop inside a loop.  Gag!  Must rewrite.  */
   1401 		do
   1402 		  if (strcmp (s->name, providename) == 0)
   1403 		    {
   1404 		      /* Not defined but referenced.  */
   1405 		      if (unlikely (!s->defined))
   1406 			{
   1407 			  /* Put on the list of symbols.  First remove it from
   1408 			     whatever list it currently is on.  */
   1409 			  CDBL_LIST_DEL (ld_state.unresolved, s);
   1410 			  --ld_state.nunresolved;
   1411 			  goto use_it;
   1412 			}
   1413 
   1414 		      if (unlikely (!orule->val.assignment->provide_flag))
   1415 			{
   1416 			  /* The symbol is already defined and now again
   1417 			     in the linker script.  This is an error.  */
   1418 			  error (0, 0, gettext ("\
   1419 duplicate definition of '%s' in linker script"),
   1420 				 providename);
   1421 			  goto next_rule;
   1422 			}
   1423 		    }
   1424 		while ((s = s->next) != first);
   1425 	      }
   1426 
   1427 	    /* If the symbol only has to be provided if it is needed,
   1428                ignore it here since it is not undefined.  */
   1429 	    if (orule->val.assignment->provide_flag)
   1430 	      continue;
   1431 
   1432 	    /* Allocate memory for this new symbol.  */
   1433 	    s = (struct symbol *)
   1434 	      obstack_calloc (&ld_state.smem, sizeof (struct symbol));
   1435 
   1436 	    /* Initialize it.  */
   1437 	    s->name = orule->val.assignment->variable;
   1438 
   1439 	    /* Insert it into the symbol hash table.  */
   1440 	    unsigned long int hval = elf_hash (s->name);
   1441 	    if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
   1442 						hval, s) != 0))
   1443 	      {
   1444 		/* This means the symbol is defined somewhere else.
   1445 		   Maybe it comes from a DSO or so.  Get the
   1446 		   definition.  */
   1447 		free (s);
   1448 		struct symbol *old = ld_symbol_tab_find (&ld_state.symbol_tab,
   1449 							 hval, s);
   1450 		assert (old != NULL);
   1451 		free (s);
   1452 
   1453 		/* If this is a definition from the application itself
   1454 		   this means a duplicate definition.  */
   1455 		if (! old->in_dso)
   1456 		  {
   1457 		    error (0, 0, gettext ("\
   1458 duplicate definition of '%s' in linker script"),
   1459 			   s->name);
   1460 		    goto next_rule;
   1461 		  }
   1462 
   1463 		/* We use the definition from the linker script.  */
   1464 		s = old;
   1465 	      }
   1466 
   1467 	  use_it:
   1468 	    /* The symbol is (now) defined.  */
   1469 	    s->defined = 1;
   1470 	    s->type = STT_NOTYPE;
   1471 
   1472 	    /* Add a reference to the symbol record.  We will come
   1473 	       across it when creating the output file.  */
   1474 	    orule->val.assignment->sym = s;
   1475 
   1476 	    SNGL_LIST_PUSH (ld_state.lscript_syms, s);
   1477 	    ++ld_state.nlscript_syms;
   1478 
   1479 	  next_rule:
   1480 	    ;
   1481 	  }
   1482 
   1483       segment = segment->next;
   1484     }
   1485   while (segment != ld_state.output_segments->next);
   1486 }
   1487 
   1488 
   1489 /* Create creation of spection section symbols representing sections in the
   1490    output file.  This is done for symbols like _GLOBAL_OFFSET_TABLE_ and
   1491    _DYNAMIC.  */
   1492 static void
   1493 create_special_section_symbol (struct symbol **symp, const char *name)
   1494 {
   1495   if (*symp == NULL)
   1496     {
   1497       /* No symbol defined found yet.  Create one.  */
   1498       struct symbol *newsym = (struct symbol *)
   1499 	obstack_calloc (&ld_state.smem, sizeof (*newsym));
   1500 
   1501       newsym->name = name;
   1502       // XXX Should we mark the symbol hidden?  They are hardly useful
   1503       // used outside the current object.
   1504 
   1505       /* Add to the symbol table.  */
   1506       if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
   1507 					  elf_hash (name), newsym) != 0))
   1508 	abort ();
   1509 
   1510       *symp = newsym;
   1511     }
   1512   else if ((*symp)->defined)
   1513     /* Cannot happen.  We do use this symbol from any input file.  */
   1514     abort ();
   1515 
   1516   (*symp)->defined = 1;
   1517   (*symp)->type = STT_OBJECT;
   1518 
   1519   ++ld_state.nsymtab;
   1520 }
   1521