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