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.
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.
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.
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/>. */
31 #include <stdio_ext.h>
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;
45 /* Bug report address. */
46 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
49 /* Values for the various options. */
52 ARGP_whole_archive = 300,
53 ARGP_no_whole_archive,
76 /* Definitions of arguments for argp functions. */
77 static const struct argp_option options[] =
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."),
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."),
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."),
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."),
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."),
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 },
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 },
178 { "yydebug", ARGP_yydebug, NULL, 0,
179 N_("Select to get parser debug information"), 0 },
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 },
185 { NULL, 0, NULL, 0, NULL, 0 }
188 /* Short description of program. */
189 static const char doc[] = N_("Combine object and archive files.");
191 /* Strings for arguments in help texts. */
192 static const char args_doc[] = N_("[FILE]...");
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);
199 /* Data structure to communicate with argp functions. */
200 static struct argp argp_1st =
202 options, parse_opt_1st, args_doc, doc, NULL, NULL, NULL
204 static struct argp argp_2nd =
206 options, parse_opt_2nd, args_doc, doc, NULL, NULL, NULL
210 /* Linker state. This contains all global information. */
211 struct ld_state ld_state;
213 /* List of the input files. */
214 static struct file_list
217 struct file_list *next;
220 /* If nonzero be verbose. */
223 /* If nonzero, trade speed for less memory/address space usage. */
226 /* The emulation name to use. */
227 static const char *emulation;
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;
233 /* The last file we processed. */
234 static struct usedfiles *last_file;
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";
240 /* Nonzero if an error occurred while loading the input files. */
241 static int error_loading;
244 /* Intermediate storage for the LD_LIBRARY_PATH information from the
246 static char *ld_library_path1;
248 /* Flag used to communicate with the scanner. */
249 int ld_scan_version_script;
251 /* Name of the input file. */
252 const char *ldin_fname;
254 /* Define by parser if required. */
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,
275 main (int argc, char *argv[])
281 /* Enable memory debugging. */
285 /* Sanity check. We always want to use the LFS functionality. */
286 if (sizeof (off_t) != sizeof (off64_t))
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);
295 setlocale (LC_ALL, "");
297 /* Make sure the message catalog can be found. */
298 bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
300 /* Initialize the message catalog. */
301 textdomain (PACKAGE_TARNAME);
303 /* Before we start tell the ELF library which version we are using. */
304 elf_version (EV_CURRENT);
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");
310 /* Initialize the memory handling. */
311 #define obstack_chunk_alloc xmalloc
312 #define obstack_chunk_free free
313 obstack_init (&ld_state.smem);
315 /* Recognize old-style parameters for compatibility. */
316 replace_args (argc, argv);
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);
322 /* We need at least one input file. */
323 if (input_file_list == NULL)
325 error (0, 0, gettext ("At least one input file needed"));
326 argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
330 /* Determine which ELF backend to use. */
331 determine_output_format ();
333 /* If no hash style was specific default to the oldand slow SysV
335 if (unlikely (ld_state.hash_style == hash_style_none))
336 ld_state.hash_style = hash_style_sysv;
339 err = ld_prepare_state (emulation);
341 error (EXIT_FAILURE, 0, gettext ("error while preparing linking"));
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");
348 error (EXIT_FAILURE, errno, gettext ("cannot open linker script '%s'"),
350 /* No need for locking. */
351 __fsetlocking (ldin, FSETLOCKING_BYCALLER);
353 ld_state.srcfiles = NULL;
355 ld_scan_version_script = 0;
356 ldin_fname = linker_script;
358 /* Something went wrong during parsing. */
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
366 ld_state.default_paths = ld_state.paths;
367 ld_state.paths = ld_state.tailpaths = NULL;
369 /* Get runpath/rpath information in usable form. */
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);
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);
382 /* Stop if there has been a problem while reading the input files. */
384 exit (error_loading);
386 /* See whether all opened -( were closed. */
389 error (0, 0, gettext ("-( without matching -)"));
390 argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
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)
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. */
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 ();
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)
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)
427 while ((h = ld_section_tab_iterate (&ld_state.section_tab, &p)) != NULL)
428 if (h->type == SHT_REL || h->type == SHT_RELA)
430 struct scninfo *runp = h->last;
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);
438 ld_state.relsize_total += runp->relsize;
440 while ((runp = runp->next) != h->last);
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
451 if (dynamically_linked_p ())
452 create_special_section_symbol (&ld_state.dyn_symbol, "_DYNAMIC");
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)
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
464 GENERATE_SECTIONS (&ld_state);
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
474 /* Create the output sections now. This may requires sorting them
476 CREATE_SECTIONS (&ld_state);
478 /* Create the output file data. Appropriate code for the selected
479 output file type is called. */
480 if (CREATE_OUTFILE (&ld_state) != 0)
483 /* Finalize the output file, write the data out. */
484 err |= FINALIZE (&ld_state);
486 /* Return with an non-zero exit status also if any error message has
488 return err | (error_message_count != 0);
493 replace_args (int argc, char *argv[])
501 { "-export-dynamic", "--export-dynamic" },
502 { "-dynamic-linker", "--dynamic-linker" },
503 { "-static", "--static" },
505 const size_t nargs = sizeof (args) / sizeof (args[0]);
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)
512 argv[i] = (char *) args[j].to;
519 valid_hexarg (const char *arg)
521 if (strncasecmp (arg, "0x", 2) != 0)
527 if (isxdigit (arg[0]) && isxdigit (arg[1]))
530 if (arg[0] == '-' || arg[0] == ':')
536 while (*arg != '\0');
542 /* Quick scan of the parameter list for options with global effect. */
544 parse_opt_1st (int key, char *arg,
545 struct argp_state *state __attribute__ ((unused)))
550 parse_B_option (arg);
558 ld_state.export_all_dynamic = true;
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;
567 /* If we generate a DSO we have to export all symbols. */
568 ld_state.export_all_dynamic = true;
572 ld_state.soname = arg;
576 /* Discard the LD_LIBRARY_PATH value we found. */
577 ld_library_path1 = NULL;
581 ld_state.interp = arg;
585 if (emulation != NULL)
586 error (EXIT_FAILURE, 0, gettext ("more than one '-m' parameter"));
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;
596 error (EXIT_FAILURE, 0, gettext ("unknown option `-%c %s'"), 'Q', arg);
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;
607 ld_state.strip = strip_debug;
611 ld_state.trace_files = true;
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
622 parse_z_option (arg);
628 ld_state.pagesize = strtoul (arg, &endp, 0);
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;
638 gettext ("invalid page size value '%s': ignored"),
640 ld_state.pagesize = 0;
647 add_rxxpath (&ld_state.rpath, arg);
650 case ARGP_rpath_link:
651 add_rxxpath (&ld_state.rpath_link, arg);
655 add_rxxpath (&ld_state.runpath, arg);
658 case ARGP_runpath_link:
659 add_rxxpath (&ld_state.runpath_link, arg);
662 case ARGP_gc_sections:
663 case ARGP_no_gc_sections:
664 ld_state.gc_sections = key == ARGP_gc_sections;
667 case ARGP_eh_frame_hdr:
668 ld_state.eh_frame_hdr = true;
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;
679 error (EXIT_FAILURE, 0, gettext ("invalid hash style '%s'"), arg);
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);
691 ld_state.build_id = arg;
697 if (ld_state.strip == strip_all)
698 ld_state.strip = strip_everything;
700 ld_state.strip = strip_all;
708 case ARGP_whole_archive:
709 case ARGP_no_whole_archive:
711 case ARGP_no_as_needed:
718 case ARGP_version_script:
719 /* We'll handle these in the second pass. */
724 struct file_list *newp;
726 newp = (struct file_list *) xmalloc (sizeof (struct file_list));
731 CSNGL_LIST_ADD_REAR (input_file_list, newp);
741 case ARGP_no_undefined:
742 ld_state.nodefs = false;
750 return ARGP_ERR_UNKNOWN;
756 /* Handle program arguments for real. */
758 parse_opt_2nd (int key, char *arg,
759 struct argp_state *state __attribute__ ((unused)))
761 static bool group_start_requested;
762 static bool group_end_requested;
767 parse_B_option_2 (arg);
771 ld_state.entry = arg;
775 if (ld_state.outfname != NULL)
777 error (0, 0, gettext ("More than one output file name given."));
779 argp_help (&argp_2nd, stderr, ARGP_HELP_SEE, "ld");
782 ld_state.outfname = arg;
787 ld_state.optlevel = 1;
791 unsigned long int level = strtoul (arg, &endp, 10);
794 error (0, 0, gettext ("Invalid optimization level `%s'"), arg);
797 ld_state.optlevel = level;
801 case ARGP_whole_archive:
802 ld_state.extract_rule = allextract;
804 case ARGP_no_whole_archive:
805 ld_state.extract_rule = defaultextract;
809 ld_state.as_needed = true;
811 case ARGP_no_as_needed:
812 ld_state.as_needed = false;
817 /* Enable/disable use for DSOs. */
818 ld_state.statically = key == ARGP_static;
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
825 parse_z_option_2 (arg);
828 case ARGP_version_script:
829 read_version_script (arg);
833 /* Add a new search directory. */
834 ld_new_searchdir (arg);
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"));
844 /* Increment the nesting level. */
847 /* Record group start. */
848 group_start_requested = true;
849 group_end_requested = false;
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)
859 if (group_level == 0)
861 error (0, 0, gettext ("-) without matching -("));
866 last_file->group_end = true;
875 while (last_file != NULL)
876 /* Try to open the file. */
877 error_loading |= FILE_PROCESS (-1, last_file, &ld_state, &last_file);
879 last_file = ld_new_inputfile (arg,
882 : relocatable_file_type);
883 if (group_start_requested)
885 last_file->group_start = true;
887 group_start_requested = false;
888 group_end_requested = true;
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. */
903 /* Load all the DSOs named as dependencies in other DSOs we already
908 struct usedfiles *first;
909 struct usedfiles *runp;
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
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
922 XXX Should we add an option to get Solaris compatibility? */
923 if (ld_state.needed == NULL)
926 runp = first = ld_state.needed->next;
929 struct usedfiles *ignore;
930 struct usedfiles *next = runp->next;
933 err = FILE_PROCESS (-1, runp, &ld_state, &ignore);
935 /* Something went wrong. */
940 while (runp != first);
944 /* Print the version information. */
946 print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
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\
954 fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
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
962 parse_z_option (const char *arg)
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
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
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);
1010 parse_z_option_2 (const char *arg)
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;
1029 /* There are a lot of -B options, parse them here. */
1031 parse_B_option (const char *arg)
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);
1042 /* The same functionality, but called in the second pass over the
1045 parse_B_option_2 (const char *arg)
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;
1059 determine_output_format (void)
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;
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)
1073 ld_state.ebl = ebl_openbackend_emulation (emulation);
1075 assert (ld_state.ebl != NULL);
1079 /* Find an ELF input file and let it determine the ELf backend. */
1080 struct file_list *runp = input_file_list;
1082 while (runp != NULL)
1084 int fd = open (runp->name, O_RDONLY);
1094 if (elf_kind (elf) == ELF_K_ELF)
1096 /* We have an ELF file. We now can find out
1097 what the output format should be. */
1098 XElf_Ehdr_vardef(ehdr);
1100 /* Get the ELF header of the object. */
1101 xelf_getehdr (elf, ehdr);
1104 ebl_openbackend_machine (ehdr->e_machine);
1108 else if (elf_kind (elf) == ELF_K_AR)
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
1116 Elf_Cmd cmd = ELF_C_READ_MMAP;
1118 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
1120 cmd = elf_next (subelf);
1122 if (try (subelf) != 0)
1132 if (try (elf_begin (fd, ELF_C_READ_MMAP, NULL)) != 0)
1140 if (ld_state.ebl == NULL)
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"));
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)
1153 struct file_list *oldp = input_file_list;
1154 input_file_list = input_file_list->next;
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;
1164 /* Add DIR to the list of directories searched for object files and
1167 ld_new_searchdir (const char *dir)
1169 struct pathelement *newpath;
1171 newpath = (struct pathelement *)
1172 obstack_calloc (&ld_state.smem, sizeof (struct pathelement));
1174 newpath->pname = dir;
1176 /* Enqueue the file. */
1177 if (ld_state.tailpaths == NULL)
1178 ld_state.paths = ld_state.tailpaths = newpath->next = newpath;
1181 ld_state.tailpaths->next = newpath;
1182 ld_state.tailpaths = newpath;
1183 newpath->next = ld_state.paths;
1189 ld_new_inputfile (const char *fname, enum file_type type)
1191 struct usedfiles *newfile = (struct usedfiles *)
1192 obstack_calloc (&ld_state.smem, sizeof (struct usedfiles));
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;
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
1210 collect_sections (void)
1216 /* We have that many sections. At least for now. */
1217 ld_state.nallsections = ld_state.section_tab.filled;
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 *));
1226 /* Fill the array. We rely here on the hash table iterator to
1227 return the entries in the order they were added. */
1230 while ((h = ld_section_tab_iterate (&ld_state.section_tab, &p)) != NULL)
1232 struct scninfo *runp;
1235 if (h->kind == scn_normal)
1240 if (h->type == SHT_REL || h->type == SHT_RELA)
1243 /* This is a relocation section. If the section
1244 it is relocating is used in the result so must
1245 the relocation section. */
1247 = runp->fileinfo->scninfo[SCNINFO_SHDR (runp->shdr).sh_info].used;
1250 /* Accumulate the result. */
1253 /* Next input section. */
1256 while (runp != h->last);
1261 ld_state.allsections[cnt++] = h;
1263 ld_state.nusedsections = cnt;
1265 assert (cnt == ld_state.nallsections);
1269 /* Add given path to the end of list. */
1271 add_rxxpath (struct pathelement **pathp, const char *str)
1273 struct pathelement *newp;
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));
1285 CSNGL_LIST_ADD_REAR (*pathp, newp);
1289 /* Convert lists of possibly colon-separated directory lists into lists
1290 where each entry is for a single directory. */
1292 normalize_dirlist (struct pathelement **pathp)
1294 struct pathelement *firstp = *pathp;
1298 const char *pname = (*pathp)->pname;
1299 const char *colonp = strchrnul (pname, ':');
1303 struct pathelement *lastp = *pathp;
1304 struct pathelement *newp;
1308 if (colonp == pname)
1311 lastp->pname = obstack_strndup (&ld_state.smem, pname,
1314 if (*colonp == '\0')
1318 newp = (struct pathelement *) obstack_alloc (&ld_state.smem,
1320 newp->next = lastp->next;
1322 lastp = lastp->next = newp;
1324 colonp = strchrnul (pname, ':');
1327 pathp = &lastp->next;
1330 pathp = &(*pathp)->next;
1332 while (*pathp != firstp);
1336 /* Called after all parameters are parsed to bring the runpath/rpath
1337 information into a usable form. */
1339 gen_rxxpath_data (void)
1341 char *ld_library_path2;
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)
1349 struct pathelement *endp = ld_state.rpath;
1350 ld_state.rpath = ld_state.rpath->next;
1353 if (ld_state.rpath_link != NULL)
1355 struct pathelement *endp = ld_state.rpath_link;
1356 ld_state.rpath_link = ld_state.rpath_link->next;
1360 if (ld_state.runpath != NULL)
1362 struct pathelement *endp = ld_state.runpath;
1363 ld_state.runpath = ld_state.runpath->next;
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)
1370 struct pathelement *old = ld_state.rpath;
1371 ld_state.rpath = ld_state.rpath->next;
1375 if (ld_state.runpath_link != NULL)
1377 struct pathelement *endp = ld_state.runpath_link;
1378 ld_state.runpath_link = ld_state.runpath_link->next;
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)
1385 struct pathelement *old = ld_state.rpath_link;
1386 ld_state.rpath_link = ld_state.rpath_link->next;
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
1394 normalize_dirlist (&ld_state.runpath_link);
1396 else if (ld_state.rpath_link != NULL)
1397 /* Same as for the runpath_link above. */
1398 normalize_dirlist (&ld_state.rpath_link);
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)
1407 ld_library_path2 = strchr (ld_library_path1, ';');
1408 if (ld_library_path2 == NULL)
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;
1417 /* NUL terminate the first part. */
1418 *ld_library_path2++ = '\0';
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);
1425 add_rxxpath (&ld_state.ld_library_path2, ld_library_path2);
1426 normalize_dirlist (&ld_state.ld_library_path2);
1432 read_version_script (const char *fname)
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");
1438 error (EXIT_FAILURE, errno, gettext ("cannot read version script '%s'"),
1440 /* No need for locking. */
1441 __fsetlocking (ldin, FSETLOCKING_BYCALLER);
1443 /* Tell the parser that this is a version script. */
1444 ld_scan_version_script = 1;
1448 if (ldparse () != 0)
1449 /* Something went wrong during parsing. */
1450 exit (EXIT_FAILURE);
1457 create_lscript_symbols (void)
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)
1465 struct output_segment *segment = ld_state.output_segments->next;
1468 struct output_rule *orule;
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
1474 && strcmp (orule->val.assignment->variable, ".") != 0)
1476 struct symbol *s = ld_state.unresolved;
1478 /* Check whether the symbol is needed. */
1479 if (likely (s != NULL))
1481 struct symbol *first = s;
1482 const char *providename = orule->val.assignment->variable;
1484 /* Determine whether the provided symbol is still
1486 // XXX TODO Loop inside a loop. Gag! Must rewrite. */
1488 if (strcmp (s->name, providename) == 0)
1490 /* Not defined but referenced. */
1491 if (unlikely (!s->defined))
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;
1500 if (unlikely (!orule->val.assignment->provide_flag))
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"),
1510 while ((s = s->next) != first);
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)
1518 /* Allocate memory for this new symbol. */
1519 s = (struct symbol *)
1520 obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1522 /* Initialize it. */
1523 s->name = orule->val.assignment->variable;
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,
1530 /* This means the symbol is defined somewhere else.
1531 Maybe it comes from a DSO or so. Get the
1534 struct symbol *old = ld_symbol_tab_find (&ld_state.symbol_tab,
1536 assert (old != NULL);
1539 /* If this is a definition from the application itself
1540 this means a duplicate definition. */
1543 error (0, 0, gettext ("\
1544 duplicate definition of '%s' in linker script"),
1549 /* We use the definition from the linker script. */
1554 /* The symbol is (now) defined. */
1556 s->type = STT_NOTYPE;
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;
1562 SNGL_LIST_PUSH (ld_state.lscript_syms, s);
1563 ++ld_state.nlscript_syms;
1569 segment = segment->next;
1571 while (segment != ld_state.output_segments->next);
1575 /* Create creation of spection section symbols representing sections in the
1576 output file. This is done for symbols like _GLOBAL_OFFSET_TABLE_ and
1579 create_special_section_symbol (struct symbol **symp, const char *name)
1583 /* No symbol defined found yet. Create one. */
1584 struct symbol *newsym = (struct symbol *)
1585 obstack_calloc (&ld_state.smem, sizeof (*newsym));
1587 newsym->name = name;
1588 // XXX Should we mark the symbol hidden? They are hardly useful
1589 // used outside the current object.
1591 /* Add to the symbol table. */
1592 if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
1593 elf_hash (name), newsym) != 0))
1598 else if ((*symp)->defined)
1599 /* Cannot happen. We do use this symbol from any input file. */
1602 (*symp)->defined = 1;
1604 (*symp)->hidden = 1;
1605 (*symp)->type = STT_OBJECT;
1611 #include "debugpred.h"