1 /* Copyright (C) 2001-2010, 2012 Red Hat, Inc.
2 This file is part of Red Hat elfutils.
3 Written by Ulrich Drepper <drepper@redhat.com>, 2001.
5 Red Hat elfutils is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by the
7 Free Software Foundation; version 2 of the License.
9 Red Hat elfutils is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with Red Hat elfutils; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA.
18 Red Hat elfutils is an included package of the Open Invention Network.
19 An included package of the Open Invention Network is a package for which
20 Open Invention Network licensees cross-license their patents. No patent
21 license is granted, either expressly or impliedly, by designation as an
22 included package. Should you wish to participate in the Open Invention
23 Network licensing program, please visit www.openinventionnetwork.com
24 <http://www.openinventionnetwork.com>. */
39 #include <stdio_ext.h>
49 /* Name and version of program. */
50 static void print_version (FILE *stream, struct argp_state *state);
51 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
53 /* Bug report address. */
54 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
57 /* Values for the various options. */
60 ARGP_whole_archive = 300,
61 ARGP_no_whole_archive,
84 /* Definitions of arguments for argp functions. */
85 static const struct argp_option options[] =
87 { NULL, 0, NULL, 0, N_("Input File Control:"), 0 },
88 { "whole-archive", ARGP_whole_archive, NULL, 0,
89 N_("Include whole archives in the output from now on."), 0 },
90 { "no-whole-archive", ARGP_no_whole_archive, NULL, 0,
91 N_("Stop including the whole archives in the output."), 0 },
92 { NULL, 'l', N_("FILE"), OPTION_HIDDEN, NULL, 0 },
93 { "start-group", '(', NULL, 0, N_("Start a group."), 0 },
94 { "end-group", ')', NULL, 0, N_("End a group."), 0 },
95 { NULL, 'L', N_("PATH"), 0,
96 N_("Add PATH to list of directories files are searched in."), 0 },
97 { "as-needed", ARGP_as_needed, NULL, 0,
98 N_("Only set DT_NEEDED for following dynamic libs if actually used"), 0 },
99 { "no-as-needed", ARGP_no_as_needed, NULL, 0,
100 N_("Always set DT_NEEDED for following dynamic libs"), 0 },
101 { "rpath-link", ARGP_rpath_link, "PATH", OPTION_HIDDEN, NULL, 0 },
102 { NULL, 'i', NULL, 0, N_("Ignore LD_LIBRARY_PATH environment variable."),
105 { NULL, 0, NULL, 0, N_("Output File Control:"), 0 },
106 { "output", 'o', N_("FILE"), 0, N_("Place output in FILE."), 0 },
107 { NULL, 'z', "KEYWORD", OPTION_HIDDEN, NULL, 0 },
108 { "-z nodefaultlib", '\0', NULL, OPTION_DOC,
109 N_("Object is marked to not use default search path at runtime."), 0 },
110 { "-z allextract", '\0', NULL, OPTION_DOC,
111 N_("Same as --whole-archive."), 0 },
112 { "-z defaultextract", '\0', NULL, OPTION_DOC, N_("\
113 Default rules of extracting from archive; weak references are not enough."),
115 { "-z weakextract", '\0', NULL, OPTION_DOC,
116 N_("Weak references cause extraction from archive."), 0 },
117 { "-z muldefs", '\0', NULL, OPTION_DOC,
118 N_("Allow multiple definitions; first is used."), 0 },
119 { "-z defs | nodefs", '\0', NULL, OPTION_DOC,
120 N_("Disallow/allow undefined symbols in DSOs."), 0 },
121 { "no-undefined", ARGP_no_undefined, NULL, OPTION_HIDDEN, NULL, 0 },
122 { "-z origin", '\0', NULL, OPTION_DOC,
123 N_("Object requires immediate handling of $ORIGIN."), 0 },
124 { "-z now", '\0', NULL, OPTION_DOC,
125 N_("Relocation will not be processed lazily."), 0 },
126 { "-z nodelete", '\0', NULL, OPTION_DOC,
127 N_("Object cannot be unloaded at runtime."), 0 },
128 { "-z initfirst", '\0', NULL, OPTION_DOC,
129 N_("Mark object to be initialized first."), 0 },
130 { "-z lazyload | nolazyload", '\0', NULL, OPTION_DOC,
131 N_("Enable/disable lazy-loading flag for following dependencies."), 0 },
132 { "-z nodlopen", '\0', NULL, OPTION_DOC,
133 N_("Mark object as not loadable with 'dlopen'."), 0 },
134 { "-z ignore | record", '\0', NULL, OPTION_DOC,
135 N_("Ignore/record dependencies on unused DSOs."), 0 },
136 { "-z systemlibrary", '\0', NULL, OPTION_DOC,
137 N_("Generated DSO will be a system library."), 0 },
138 { "entry", 'e', N_("ADDRESS"), 0, N_("Set entry point address."), 0 },
139 { "static", ARGP_static, NULL, OPTION_HIDDEN, NULL, 0 },
140 { "-B static", ARGP_static, NULL, OPTION_DOC,
141 N_("Do not link against shared libraries."), 0 },
142 { "dynamic", ARGP_dynamic, NULL, OPTION_HIDDEN, NULL, 0 },
143 { "-B dynamic", ARGP_dynamic, NULL, OPTION_DOC,
144 N_("Prefer linking against shared libraries."), 0 },
145 { "export-dynamic", 'E', NULL, 0, N_("Export all dynamic symbols."), 0 },
146 { "strip-all", 's', NULL, 0, N_("Strip all symbols."), 0 },
147 { "strip-debug", 'S', NULL, 0, N_("Strip debugging symbols."), 0 },
148 { "pagesize", ARGP_pagesize, "SIZE", 0,
149 N_("Assume pagesize for the target system to be SIZE."), 0 },
150 { "rpath", 'R', "PATH", OPTION_HIDDEN, NULL, 0 },
151 { "runpath", ARGP_runpath, "PATH", 0, N_("Set runtime DSO search path."),
153 { "runpath-link", ARGP_runpath_link, "PATH", 0,
154 N_("Set link time DSO search path."), 0 },
155 { "shared", 'G', NULL, 0, N_("Generate dynamic shared object."), 0 },
156 { NULL, 'r', NULL, 0L, N_("Generate relocatable object."), 0 },
157 { NULL, 'B', "KEYWORD", OPTION_HIDDEN, "", 0 },
158 { "-B local", 'B', NULL, OPTION_DOC,
159 N_("Causes symbol not assigned to a version be reduced to local."), 0 },
160 { "gc-sections", ARGP_gc_sections, NULL, 0, N_("Remove unused sections."),
162 { "no-gc-sections", ARGP_no_gc_sections, NULL, 0,
163 N_("Don't remove unused sections."), 0 },
164 { "soname", 'h', "NAME", 0, N_("Set soname of shared object."), 0 },
165 { "dynamic-linker", 'I', "NAME", 0, N_("Set the dynamic linker name."), 0 },
166 { NULL, 'Q', "YN", OPTION_HIDDEN, NULL, 0 },
167 { "-Q y | n", 'Q', NULL, OPTION_DOC,
168 N_("Add/suppress addition indentifying link-editor to .comment section."),
170 { "eh-frame-hdr", ARGP_eh_frame_hdr, NULL, 0,
171 N_("Create .eh_frame_hdr section"), 0 },
172 { "hash-style", ARGP_hash_style, "STYLE", 0,
173 N_("Set hash style to sysv, gnu or both."), 0 },
174 { "build-id", ARGP_build_id, "STYLE", OPTION_ARG_OPTIONAL,
175 N_("Generate build ID note (md5, sha1 (default), uuid)."), 0 },
177 { NULL, 0, NULL, 0, N_("Linker Operation Control:"), 0 },
178 { "verbose", 'v', NULL, 0, N_("Verbose messages."), 0 },
179 { "trace", 't', NULL, 0, N_("Trace file opens."), 0 },
180 { "conserve-memory", ARGP_conserve, NULL, 0,
181 N_("Trade speed for less memory usage"), 0 },
182 { NULL, 'O', N_("LEVEL"), OPTION_ARG_OPTIONAL,
183 N_("Set optimization level to LEVEL."), 0 },
184 { NULL, 'c', N_("FILE"), 0, N_("Use linker script in FILE."), 0 },
186 { "yydebug", ARGP_yydebug, NULL, 0,
187 N_("Select to get parser debug information"), 0 },
189 { "version-script", ARGP_version_script, "FILE", 0,
190 N_("Read version information from FILE."), 0 },
191 { "emulation", 'm', "NAME", 0, N_("Set emulation to NAME."), 0 },
193 { NULL, 0, NULL, 0, NULL, 0 }
196 /* Short description of program. */
197 static const char doc[] = N_("Combine object and archive files.");
199 /* Strings for arguments in help texts. */
200 static const char args_doc[] = N_("[FILE]...");
202 /* Prototype for option handler. */
203 static void replace_args (int argc, char *argv[]);
204 static error_t parse_opt_1st (int key, char *arg, struct argp_state *state);
205 static error_t parse_opt_2nd (int key, char *arg, struct argp_state *state);
207 /* Data structure to communicate with argp functions. */
208 static struct argp argp_1st =
210 options, parse_opt_1st, args_doc, doc, NULL, NULL, NULL
212 static struct argp argp_2nd =
214 options, parse_opt_2nd, args_doc, doc, NULL, NULL, NULL
218 /* Linker state. This contains all global information. */
219 struct ld_state ld_state;
221 /* List of the input files. */
222 static struct file_list
225 struct file_list *next;
228 /* If nonzero be verbose. */
231 /* If nonzero, trade speed for less memory/address space usage. */
234 /* The emulation name to use. */
235 static const char *emulation;
237 /* Keep track of the nesting level. Even though we don't handle nested
238 groups we still keep track to improve the error messages. */
239 static int group_level;
241 /* The last file we processed. */
242 static struct usedfiles *last_file;
244 /* The default linker script. */
245 /* XXX We'll do this a bit different in the real solution. */
246 static const char *linker_script = SRCDIR "/elf32-i386.script";
248 /* Nonzero if an error occurred while loading the input files. */
249 static int error_loading;
252 /* Intermediate storage for the LD_LIBRARY_PATH information from the
254 static char *ld_library_path1;
256 /* Flag used to communicate with the scanner. */
257 int ld_scan_version_script;
259 /* Name of the input file. */
260 const char *ldin_fname;
262 /* Define by parser if required. */
266 /* Prototypes for local functions. */
267 static void parse_z_option (const char *arg);
268 static void parse_z_option_2 (const char *arg);
269 static void parse_B_option (const char *arg);
270 static void parse_B_option_2 (const char *arg);
271 static void determine_output_format (void);
272 static void load_needed (void);
273 static void collect_sections (void);
274 static void add_rxxpath (struct pathelement **pathp, const char *str);
275 static void gen_rxxpath_data (void);
276 static void read_version_script (const char *fname);
277 static void create_lscript_symbols (void);
278 static void create_special_section_symbol (struct symbol **symp,
283 main (int argc, char *argv[])
289 /* Enable memory debugging. */
293 /* Sanity check. We always want to use the LFS functionality. */
294 if (sizeof (off_t) != sizeof (off64_t))
297 /* We use no threads here which can interfere with handling a stream. */
298 __fsetlocking (stdin, FSETLOCKING_BYCALLER);
299 __fsetlocking (stdout, FSETLOCKING_BYCALLER);
300 __fsetlocking (stderr, FSETLOCKING_BYCALLER);
303 setlocale (LC_ALL, "");
305 /* Make sure the message catalog can be found. */
306 bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
308 /* Initialize the message catalog. */
309 textdomain (PACKAGE_TARNAME);
311 /* Before we start tell the ELF library which version we are using. */
312 elf_version (EV_CURRENT);
314 /* The user can use the LD_LIBRARY_PATH environment variable to add
315 additional lookup directories. */
316 ld_library_path1 = getenv ("LD_LIBRARY_PATH");
318 /* Initialize the memory handling. */
319 #define obstack_chunk_alloc xmalloc
320 #define obstack_chunk_free free
321 obstack_init (&ld_state.smem);
323 /* Recognize old-style parameters for compatibility. */
324 replace_args (argc, argv);
326 /* One quick pass over the parameters which allows us to scan for options
327 with global effect which influence the rest of the processing. */
328 argp_parse (&argp_1st, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
330 /* We need at least one input file. */
331 if (input_file_list == NULL)
333 error (0, 0, gettext ("At least one input file needed"));
334 argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
338 /* Determine which ELF backend to use. */
339 determine_output_format ();
341 /* If no hash style was specific default to the oldand slow SysV
343 if (unlikely (ld_state.hash_style == hash_style_none))
344 ld_state.hash_style = hash_style_sysv;
347 err = ld_prepare_state (emulation);
349 error (EXIT_FAILURE, 0, gettext ("error while preparing linking"));
351 /* XXX Read the linker script now. Since we later will have the linker
352 script built in we don't go into trouble to make sure we handle GROUP
353 statements in the script. This simply must not happen. */
354 ldin = fopen (linker_script, "r");
356 error (EXIT_FAILURE, errno, gettext ("cannot open linker script '%s'"),
358 /* No need for locking. */
359 __fsetlocking (ldin, FSETLOCKING_BYCALLER);
361 ld_state.srcfiles = NULL;
363 ld_scan_version_script = 0;
364 ldin_fname = linker_script;
366 /* Something went wrong during parsing. */
370 /* We now might have a list of directories to look for libraries in
371 named by the linker script. Put them in a different list so that
372 they are searched after all paths given by the user on the
374 ld_state.default_paths = ld_state.paths;
375 ld_state.paths = ld_state.tailpaths = NULL;
377 /* Get runpath/rpath information in usable form. */
380 /* Parse and process arguments for real. */
381 argp_parse (&argp_2nd, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
382 /* All options should have been processed by the argp parser. */
383 assert (remaining == argc);
385 /* Process the last file. */
386 while (last_file != NULL)
387 /* Try to open the file. */
388 error_loading |= FILE_PROCESS (-1, last_file, &ld_state, &last_file);
390 /* Stop if there has been a problem while reading the input files. */
392 exit (error_loading);
394 /* See whether all opened -( were closed. */
397 error (0, 0, gettext ("-( without matching -)"));
398 argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
402 /* When we create a relocatable file we don't have to look for the
403 DT_NEEDED DSOs and we also don't test for undefined symbols. */
404 if (ld_state.file_type != relocatable_file_type)
406 /* At this point we have loaded all the direct dependencies. What
407 remains to be done is find the indirect dependencies. These are
408 DSOs which are referenced by the DT_NEEDED entries in the DSOs
409 which are direct dependencies. We have to transitively find and
410 load all these dependencies. */
413 /* At this point all object files and DSOs are read. If there
414 are still undefined symbols left they might have to be
415 synthesized from the linker script. */
416 create_lscript_symbols ();
418 /* Now that we have loaded all the object files we can determine
419 whether we have any non-weak unresolved references left. If
420 there are any we stop. If the user used the '-z nodefs' option
421 and we are creating a DSO don't perform the tests. */
422 if (FLAG_UNRESOLVED (&ld_state) != 0)
426 /* Collect information about the relocations which will be carried
427 forward into the output. We have to do this here and now since
428 we need to know which sections have to be created. */
429 if (ld_state.file_type != relocatable_file_type)
435 while ((h = ld_section_tab_iterate (&ld_state.section_tab, &p)) != NULL)
436 if (h->type == SHT_REL || h->type == SHT_RELA)
438 struct scninfo *runp = h->last;
441 /* If we are processing the relocations determine how
442 many will be in the output file. Also determine
443 how many GOT entries are needed. */
444 COUNT_RELOCATIONS (&ld_state, runp);
446 ld_state.relsize_total += runp->relsize;
448 while ((runp = runp->next) != h->last);
452 /* Not part of the gABI, but part of every psABI: the symbols for the
453 GOT section. Add the symbol if necessary. */
454 if (ld_state.need_got)
455 create_special_section_symbol (&ld_state.got_symbol,
456 "_GLOBAL_OFFSET_TABLE_");
457 /* Similarly for the _DYNAMIC symbol which points to the dynamic
459 if (dynamically_linked_p ())
460 create_special_section_symbol (&ld_state.dyn_symbol, "_DYNAMIC");
462 /* We are ready to start working on the output file. Not all
463 information has been gather or created yet. This will be done as
464 we go. Open the file now. */
465 if (OPEN_OUTFILE (&ld_state, EM_NONE, ELFCLASSNONE, ELFDATANONE) != 0)
468 /* Create the sections which are generated by the linker and are not
469 present in the input file. The output file must already have
470 been opened since we need the ELF descriptor to deduce type
472 GENERATE_SECTIONS (&ld_state);
474 /* At this point we have read all the files and know all the
475 sections which have to be linked into the application. We do now
476 create an array listing all the sections. We will than pass this
477 array to a system specific function which can reorder it at will.
478 The functions can also merge sections if this is what is
482 /* Create the output sections now. This may requires sorting them
484 CREATE_SECTIONS (&ld_state);
486 /* Create the output file data. Appropriate code for the selected
487 output file type is called. */
488 if (CREATE_OUTFILE (&ld_state) != 0)
491 /* Finalize the output file, write the data out. */
492 err |= FINALIZE (&ld_state);
494 /* Return with an non-zero exit status also if any error message has
496 return err | (error_message_count != 0);
501 replace_args (int argc, char *argv[])
509 { "-export-dynamic", "--export-dynamic" },
510 { "-dynamic-linker", "--dynamic-linker" },
511 { "-static", "--static" },
513 const size_t nargs = sizeof (args) / sizeof (args[0]);
515 for (int i = 1; i < argc; ++i)
516 if (argv[i][0] == '-' && islower (argv[i][1]) && argv[i][2] != '\0')
517 for (size_t j = 0; j < nargs; ++j)
518 if (strcmp (argv[i], args[j].from) == 0)
520 argv[i] = (char *) args[j].to;
527 valid_hexarg (const char *arg)
529 if (strncasecmp (arg, "0x", 2) != 0)
535 if (isxdigit (arg[0]) && isxdigit (arg[1]))
538 if (arg[0] == '-' || arg[0] == ':')
544 while (*arg != '\0');
550 /* Quick scan of the parameter list for options with global effect. */
552 parse_opt_1st (int key, char *arg,
553 struct argp_state *state __attribute__ ((unused)))
558 parse_B_option (arg);
566 ld_state.export_all_dynamic = true;
570 if (ld_state.file_type != no_file_type)
571 error (EXIT_FAILURE, 0,
572 gettext ("only one option of -G and -r is allowed"));
573 ld_state.file_type = dso_file_type;
575 /* If we generate a DSO we have to export all symbols. */
576 ld_state.export_all_dynamic = true;
580 ld_state.soname = arg;
584 /* Discard the LD_LIBRARY_PATH value we found. */
585 ld_library_path1 = NULL;
589 ld_state.interp = arg;
593 if (emulation != NULL)
594 error (EXIT_FAILURE, 0, gettext ("more than one '-m' parameter"));
599 if (arg[1] == '\0' && (arg[0] == 'y' || arg[0] == 'Y'))
600 ld_state.add_ld_comment = true;
601 else if (arg[1] == '\0' && (arg[0] == 'n' || arg[0] == 'N'))
602 ld_state.add_ld_comment = true;
604 error (EXIT_FAILURE, 0, gettext ("unknown option `-%c %s'"), 'Q', arg);
608 if (ld_state.file_type != no_file_type)
609 error (EXIT_FAILURE, 0,
610 gettext ("only one option of -G and -r is allowed"));
611 ld_state.file_type = relocatable_file_type;
615 ld_state.strip = strip_debug;
619 ld_state.trace_files = true;
627 /* The SysV linker used 'z' to pass various flags to the linker.
628 We follow this. See 'parse_z_option' for the options we
630 parse_z_option (arg);
636 ld_state.pagesize = strtoul (arg, &endp, 0);
639 if (endp[1] == '\0' && tolower (*endp) == 'k')
640 ld_state.pagesize *= 1024;
641 else if (endp[1] == '\0' && tolower (*endp) == 'm')
642 ld_state.pagesize *= 1024 * 1024;
646 gettext ("invalid page size value '%s': ignored"),
648 ld_state.pagesize = 0;
655 add_rxxpath (&ld_state.rpath, arg);
658 case ARGP_rpath_link:
659 add_rxxpath (&ld_state.rpath_link, arg);
663 add_rxxpath (&ld_state.runpath, arg);
666 case ARGP_runpath_link:
667 add_rxxpath (&ld_state.runpath_link, arg);
670 case ARGP_gc_sections:
671 case ARGP_no_gc_sections:
672 ld_state.gc_sections = key == ARGP_gc_sections;
675 case ARGP_eh_frame_hdr:
676 ld_state.eh_frame_hdr = true;
679 case ARGP_hash_style:
680 if (strcmp (arg, "gnu") == 0)
681 ld_state.hash_style = hash_style_gnu;
682 else if (strcmp (arg, "both") == 0)
683 ld_state.hash_style = hash_style_gnu | hash_style_sysv;
684 else if (strcmp (arg, "sysv") == 0)
685 ld_state.hash_style = hash_style_sysv;
687 error (EXIT_FAILURE, 0, gettext ("invalid hash style '%s'"), arg);
692 ld_state.build_id = "sha1";
693 else if (strcmp (arg, "uuid") != 0
694 && strcmp (arg, "md5") != 0
695 && strcmp (arg, "sha1") != 0
696 && !valid_hexarg (arg))
697 error (EXIT_FAILURE, 0, gettext ("invalid build-ID style '%s'"), arg);
699 ld_state.build_id = arg;
705 if (ld_state.strip == strip_all)
706 ld_state.strip = strip_everything;
708 ld_state.strip = strip_all;
716 case ARGP_whole_archive:
717 case ARGP_no_whole_archive:
719 case ARGP_no_as_needed:
726 case ARGP_version_script:
727 /* We'll handle these in the second pass. */
732 struct file_list *newp;
734 newp = (struct file_list *) xmalloc (sizeof (struct file_list));
739 CSNGL_LIST_ADD_REAR (input_file_list, newp);
749 case ARGP_no_undefined:
750 ld_state.nodefs = false;
758 return ARGP_ERR_UNKNOWN;
764 /* Handle program arguments for real. */
766 parse_opt_2nd (int key, char *arg,
767 struct argp_state *state __attribute__ ((unused)))
769 static bool group_start_requested;
770 static bool group_end_requested;
775 parse_B_option_2 (arg);
779 ld_state.entry = arg;
783 if (ld_state.outfname != NULL)
785 error (0, 0, gettext ("More than one output file name given."));
787 argp_help (&argp_2nd, stderr, ARGP_HELP_SEE, "ld");
790 ld_state.outfname = arg;
795 ld_state.optlevel = 1;
799 unsigned long int level = strtoul (arg, &endp, 10);
802 error (0, 0, gettext ("Invalid optimization level `%s'"), arg);
805 ld_state.optlevel = level;
809 case ARGP_whole_archive:
810 ld_state.extract_rule = allextract;
812 case ARGP_no_whole_archive:
813 ld_state.extract_rule = defaultextract;
817 ld_state.as_needed = true;
819 case ARGP_no_as_needed:
820 ld_state.as_needed = false;
825 /* Enable/disable use for DSOs. */
826 ld_state.statically = key == ARGP_static;
830 /* The SysV linker used 'z' to pass various flags to the linker.
831 We follow this. See 'parse_z_option' for the options we
833 parse_z_option_2 (arg);
836 case ARGP_version_script:
837 read_version_script (arg);
841 /* Add a new search directory. */
842 ld_new_searchdir (arg);
846 /* Start a link group. We have to be able to determine the object
847 file which is named next. Do this by remembering a pointer to
848 the pointer which will point to the next object. */
849 if (verbose && (group_start_requested || !group_end_requested))
850 error (0, 0, gettext ("nested -( -) groups are not allowed"));
852 /* Increment the nesting level. */
855 /* Record group start. */
856 group_start_requested = true;
857 group_end_requested = false;
861 /* End a link group. If there is no group open this is clearly
862 a bug. If there is a group open insert a back reference
863 pointer in the record for the last object of the group. If
864 there is no new object or just one don't do anything. */
865 if (!group_end_requested)
867 if (group_level == 0)
869 error (0, 0, gettext ("-) without matching -("));
874 last_file->group_end = true;
883 while (last_file != NULL)
884 /* Try to open the file. */
885 error_loading |= FILE_PROCESS (-1, last_file, &ld_state, &last_file);
887 last_file = ld_new_inputfile (arg,
890 : relocatable_file_type);
891 if (group_start_requested)
893 last_file->group_start = true;
895 group_start_requested = false;
896 group_end_requested = true;
902 /* We can catch all other options here. They either have
903 already been handled or, if the parameter was not correct,
904 the error has been reported. */
911 /* Load all the DSOs named as dependencies in other DSOs we already
916 struct usedfiles *first;
917 struct usedfiles *runp;
919 /* XXX There is one problem here: do we allow references from
920 regular object files to be satisfied by these implicit
921 dependencies? The old linker allows this and several libraries
922 depend on this. Solaris' linker does not allow this; it provides
923 the user with a comprehensive error message explaining the
926 XXX IMO the old ld behavior is correct since this is also how the
927 dynamic linker will work. It will look for unresolved references
930 XXX Should we add an option to get Solaris compatibility? */
931 if (ld_state.needed == NULL)
934 runp = first = ld_state.needed->next;
937 struct usedfiles *ignore;
938 struct usedfiles *next = runp->next;
941 err = FILE_PROCESS (-1, runp, &ld_state, &ignore);
943 /* Something went wrong. */
948 while (runp != first);
952 /* Print the version information. */
954 print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
956 fprintf (stream, "ld (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
957 fprintf (stream, gettext ("\
958 Copyright (C) %s Red Hat, Inc.\n\
959 This is free software; see the source for copying conditions. There is NO\n\
960 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
962 fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
966 /* There are a lot of -z options, parse them here. Some of them have
967 to be parsed in the first pass, others must be handled in the
970 parse_z_option (const char *arg)
972 if (strcmp (arg, "nodefaultlib") == 0
973 /* This is only meaningful if we create a DSO. */
974 && ld_state.file_type == dso_file_type)
975 ld_state.dt_flags_1 |= DF_1_NODEFLIB;
976 else if (strcmp (arg, "muldefs") == 0)
977 ld_state.muldefs = true;
978 else if (strcmp (arg, "nodefs") == 0)
979 ld_state.nodefs = true;
980 else if (strcmp (arg, "defs") == 0)
981 ld_state.nodefs = false;
982 else if (strcmp (arg, "now") == 0)
983 /* We could also set the DF_1_NOW flag in DT_FLAGS_1 but this isn't
985 ld_state.dt_flags |= DF_BIND_NOW;
986 else if (strcmp (arg, "origin") == 0)
987 /* We could also set the DF_1_ORIGIN flag in DT_FLAGS_1 but this isn't
989 ld_state.dt_flags |= DF_ORIGIN;
990 else if (strcmp (arg, "nodelete") == 0
991 /* This is only meaningful if we create a DSO. */
992 && ld_state.file_type == dso_file_type)
993 ld_state.dt_flags_1 |= DF_1_NODELETE;
994 else if (strcmp (arg, "initfirst") == 0)
995 ld_state.dt_flags_1 |= DF_1_INITFIRST;
996 else if (strcmp (arg, "nodlopen") == 0
997 /* This is only meaningful if we create a DSO. */
998 && ld_state.file_type == dso_file_type)
999 ld_state.dt_flags_1 |= DF_1_NOOPEN;
1000 else if (strcmp (arg, "systemlibrary") == 0)
1001 ld_state.is_system_library = true;
1002 else if (strcmp (arg, "execstack") == 0)
1003 ld_state.execstack = execstack_true;
1004 else if (strcmp (arg, "noexecstack") == 0)
1005 ld_state.execstack = execstack_false_force;
1006 else if (strcmp (arg, "allextract") != 0
1007 && strcmp (arg, "defaultextract") != 0
1008 && strcmp (arg, "weakextract") != 0
1009 && strcmp (arg, "lazyload") != 0
1010 && strcmp (arg, "nolazyload") != 0
1011 && strcmp (arg, "ignore") != 0
1012 && strcmp (arg, "record") != 0)
1013 error (0, 0, gettext ("unknown option `-%c %s'"), 'z', arg);
1018 parse_z_option_2 (const char *arg)
1020 if (strcmp (arg, "allextract") == 0)
1021 ld_state.extract_rule = allextract;
1022 else if (strcmp (arg, "defaultextract") == 0)
1023 ld_state.extract_rule = defaultextract;
1024 else if (strcmp (arg, "weakextract") == 0)
1025 ld_state.extract_rule = weakextract;
1026 else if (strcmp (arg, "lazyload") == 0)
1027 ld_state.lazyload = true;
1028 else if (strcmp (arg, "nolazyload") == 0)
1029 ld_state.lazyload = false;
1030 else if (strcmp (arg, "ignore") == 0)
1031 ld_state.as_needed = true;
1032 else if (strcmp (arg, "record") == 0)
1033 ld_state.as_needed = false;
1037 /* There are a lot of -B options, parse them here. */
1039 parse_B_option (const char *arg)
1041 if (strcmp (arg, "local") == 0)
1042 ld_state.default_bind_local = true;
1043 else if (strcmp (arg, "symbolic") != 0
1044 && strcmp (arg, "static") != 0
1045 && strcmp (arg, "dynamic") != 0)
1046 error (0, 0, gettext ("unknown option '-%c %s'"), 'B', arg);
1050 /* The same functionality, but called in the second pass over the
1053 parse_B_option_2 (const char *arg)
1055 if (strcmp (arg, "static") == 0)
1056 ld_state.statically = true;
1057 else if (strcmp (arg, "dynamic") == 0)
1058 ld_state.statically = false;
1059 else if (strcmp (arg, "symbolic") == 0
1060 /* This is only meaningful if we create a DSO. */
1061 && ld_state.file_type == dso_file_type)
1062 ld_state.dt_flags |= DF_SYMBOLIC;
1067 determine_output_format (void)
1069 /* First change the 'input_file_list' variable in a simple
1070 single-linked list. */
1071 struct file_list *last = input_file_list;
1072 input_file_list = input_file_list->next;
1075 /* Determine the target configuration which we are supposed to use.
1076 The user can use the '-m' option to select one. If this is
1077 missing we are trying to load one file and determine the
1078 architecture from that. */
1079 if (emulation != NULL)
1081 ld_state.ebl = ebl_openbackend_emulation (emulation);
1083 assert (ld_state.ebl != NULL);
1087 /* Find an ELF input file and let it determine the ELf backend. */
1088 struct file_list *runp = input_file_list;
1090 while (runp != NULL)
1092 int fd = open (runp->name, O_RDONLY);
1102 if (elf_kind (elf) == ELF_K_ELF)
1104 /* We have an ELF file. We now can find out
1105 what the output format should be. */
1106 XElf_Ehdr_vardef(ehdr);
1108 /* Get the ELF header of the object. */
1109 xelf_getehdr (elf, ehdr);
1112 ebl_openbackend_machine (ehdr->e_machine);
1116 else if (elf_kind (elf) == ELF_K_AR)
1118 /* Try the archive members. This could
1119 potentially lead to wrong results if the
1120 archive contains files for more than one
1121 architecture. But this is the user's
1124 Elf_Cmd cmd = ELF_C_READ_MMAP;
1126 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
1128 cmd = elf_next (subelf);
1130 if (try (subelf) != 0)
1140 if (try (elf_begin (fd, ELF_C_READ_MMAP, NULL)) != 0)
1148 if (ld_state.ebl == NULL)
1150 error (0, 0, gettext ("\
1151 could not find input file to determine output file format"));
1152 error (EXIT_FAILURE, 0, gettext ("\
1153 try again with an appropriate '-m' parameter"));
1157 /* We don't need the list of input files anymore. The second run over
1158 the parameters will handle them. */
1159 while (input_file_list != NULL)
1161 struct file_list *oldp = input_file_list;
1162 input_file_list = input_file_list->next;
1166 /* We also know now what kind of file we are supposed to create. If
1167 the user hasn't selected anythign we create and executable. */
1168 if (ld_state.file_type == no_file_type)
1169 ld_state.file_type = executable_file_type;
1172 /* Add DIR to the list of directories searched for object files and
1175 ld_new_searchdir (const char *dir)
1177 struct pathelement *newpath;
1179 newpath = (struct pathelement *)
1180 obstack_calloc (&ld_state.smem, sizeof (struct pathelement));
1182 newpath->pname = dir;
1184 /* Enqueue the file. */
1185 if (ld_state.tailpaths == NULL)
1186 ld_state.paths = ld_state.tailpaths = newpath->next = newpath;
1189 ld_state.tailpaths->next = newpath;
1190 ld_state.tailpaths = newpath;
1191 newpath->next = ld_state.paths;
1197 ld_new_inputfile (const char *fname, enum file_type type)
1199 struct usedfiles *newfile = (struct usedfiles *)
1200 obstack_calloc (&ld_state.smem, sizeof (struct usedfiles));
1202 newfile->soname = newfile->fname = newfile->rfname = fname;
1203 newfile->file_type = type;
1204 newfile->extract_rule = ld_state.extract_rule;
1205 newfile->as_needed = ld_state.as_needed;
1206 newfile->lazyload = ld_state.lazyload;
1207 newfile->status = not_opened;
1213 /* Create an array listing all the sections. We will than pass this
1214 array to a system specific function which can reorder it at will.
1215 The functions can also merge sections if this is what is
1218 collect_sections (void)
1224 /* We have that many sections. At least for now. */
1225 ld_state.nallsections = ld_state.section_tab.filled;
1227 /* Allocate the array. We allocate one more entry than computed so
1228 far since we might need a new section for the copy relocations. */
1229 ld_state.allsections =
1230 (struct scnhead **) obstack_alloc (&ld_state.smem,
1231 (ld_state.nallsections + 1)
1232 * sizeof (struct scnhead *));
1234 /* Fill the array. We rely here on the hash table iterator to
1235 return the entries in the order they were added. */
1238 while ((h = ld_section_tab_iterate (&ld_state.section_tab, &p)) != NULL)
1240 struct scninfo *runp;
1243 if (h->kind == scn_normal)
1248 if (h->type == SHT_REL || h->type == SHT_RELA)
1251 /* This is a relocation section. If the section
1252 it is relocating is used in the result so must
1253 the relocation section. */
1255 = runp->fileinfo->scninfo[SCNINFO_SHDR (runp->shdr).sh_info].used;
1258 /* Accumulate the result. */
1261 /* Next input section. */
1264 while (runp != h->last);
1269 ld_state.allsections[cnt++] = h;
1271 ld_state.nusedsections = cnt;
1273 assert (cnt == ld_state.nallsections);
1277 /* Add given path to the end of list. */
1279 add_rxxpath (struct pathelement **pathp, const char *str)
1281 struct pathelement *newp;
1283 /* The path elements can in theory be freed after we read all the
1284 files. But the amount of memory we are talking about is small
1285 and the cost of free() calls is not neglectable. */
1286 newp = (struct pathelement *) obstack_alloc (&ld_state.smem, sizeof (*newp));
1293 CSNGL_LIST_ADD_REAR (*pathp, newp);
1297 /* Convert lists of possibly colon-separated directory lists into lists
1298 where each entry is for a single directory. */
1300 normalize_dirlist (struct pathelement **pathp)
1302 struct pathelement *firstp = *pathp;
1306 const char *pname = (*pathp)->pname;
1307 const char *colonp = strchrnul (pname, ':');
1311 struct pathelement *lastp = *pathp;
1312 struct pathelement *newp;
1316 if (colonp == pname)
1319 lastp->pname = obstack_strndup (&ld_state.smem, pname,
1322 if (*colonp == '\0')
1326 newp = (struct pathelement *) obstack_alloc (&ld_state.smem,
1328 newp->next = lastp->next;
1330 lastp = lastp->next = newp;
1332 colonp = strchrnul (pname, ':');
1335 pathp = &lastp->next;
1338 pathp = &(*pathp)->next;
1340 while (*pathp != firstp);
1344 /* Called after all parameters are parsed to bring the runpath/rpath
1345 information into a usable form. */
1347 gen_rxxpath_data (void)
1349 char *ld_library_path2;
1351 /* Convert the information in true single-linked lists for easy use.
1352 At this point we also discard the rpath information if runpath
1353 information is provided. rpath is deprecated and should not be
1354 used (or ever be invented for that matter). */
1355 if (ld_state.rpath != NULL)
1357 struct pathelement *endp = ld_state.rpath;
1358 ld_state.rpath = ld_state.rpath->next;
1361 if (ld_state.rpath_link != NULL)
1363 struct pathelement *endp = ld_state.rpath_link;
1364 ld_state.rpath_link = ld_state.rpath_link->next;
1368 if (ld_state.runpath != NULL)
1370 struct pathelement *endp = ld_state.runpath;
1371 ld_state.runpath = ld_state.runpath->next;
1374 /* If rpath information is also available discard it.
1375 XXX Should there be a possibility to avoid this? */
1376 while (ld_state.rpath != NULL)
1378 struct pathelement *old = ld_state.rpath;
1379 ld_state.rpath = ld_state.rpath->next;
1383 if (ld_state.runpath_link != NULL)
1385 struct pathelement *endp = ld_state.runpath_link;
1386 ld_state.runpath_link = ld_state.runpath_link->next;
1389 /* If rpath information is also available discard it.
1390 XXX Should there be a possibility to avoid this? */
1391 while (ld_state.rpath_link != NULL)
1393 struct pathelement *old = ld_state.rpath_link;
1394 ld_state.rpath_link = ld_state.rpath_link->next;
1398 /* The information in the strings in the list can actually be
1399 directory lists themselves, with entries separated by colons.
1400 Convert the list now to a list with one list entry for each
1402 normalize_dirlist (&ld_state.runpath_link);
1404 else if (ld_state.rpath_link != NULL)
1405 /* Same as for the runpath_link above. */
1406 normalize_dirlist (&ld_state.rpath_link);
1409 /* As a related task, handle the LD_LIBRARY_PATH value here. First
1410 we have to possibly split the value found (if it contains a
1411 semicolon). Then we have to split the value in list of
1412 directories, i.e., split at the colons. */
1413 if (ld_library_path1 != NULL)
1415 ld_library_path2 = strchr (ld_library_path1, ';');
1416 if (ld_library_path2 == NULL)
1418 /* If no semicolon is present the directories are looked at
1419 after the -L parameters (-> ld_library_path2). */
1420 ld_library_path2 = ld_library_path1;
1421 ld_library_path1 = NULL;
1425 /* NUL terminate the first part. */
1426 *ld_library_path2++ = '\0';
1428 /* Convert the string value in a list. */
1429 add_rxxpath (&ld_state.ld_library_path1, ld_library_path1);
1430 normalize_dirlist (&ld_state.ld_library_path1);
1433 add_rxxpath (&ld_state.ld_library_path2, ld_library_path2);
1434 normalize_dirlist (&ld_state.ld_library_path2);
1440 read_version_script (const char *fname)
1442 /* Open the file. The name is supposed to be the complete (relative
1443 or absolute) path. No search along a path will be performed. */
1444 ldin = fopen (fname, "r");
1446 error (EXIT_FAILURE, errno, gettext ("cannot read version script '%s'"),
1448 /* No need for locking. */
1449 __fsetlocking (ldin, FSETLOCKING_BYCALLER);
1451 /* Tell the parser that this is a version script. */
1452 ld_scan_version_script = 1;
1456 if (ldparse () != 0)
1457 /* Something went wrong during parsing. */
1458 exit (EXIT_FAILURE);
1465 create_lscript_symbols (void)
1467 /* Walk through the data from the linker script and generate all the
1468 symbols which are required to be present and those marked
1469 with PROVIDE if there is a undefined reference. */
1470 if (ld_state.output_segments == NULL)
1473 struct output_segment *segment = ld_state.output_segments->next;
1476 struct output_rule *orule;
1478 for (orule = segment->output_rules; orule != NULL; orule = orule->next)
1479 if (orule->tag == output_assignment
1480 /* The assignments to "." (i.e., the PC) have to be
1482 && strcmp (orule->val.assignment->variable, ".") != 0)
1484 struct symbol *s = ld_state.unresolved;
1486 /* Check whether the symbol is needed. */
1487 if (likely (s != NULL))
1489 struct symbol *first = s;
1490 const char *providename = orule->val.assignment->variable;
1492 /* Determine whether the provided symbol is still
1494 // XXX TODO Loop inside a loop. Gag! Must rewrite. */
1496 if (strcmp (s->name, providename) == 0)
1498 /* Not defined but referenced. */
1499 if (unlikely (!s->defined))
1501 /* Put on the list of symbols. First remove it from
1502 whatever list it currently is on. */
1503 CDBL_LIST_DEL (ld_state.unresolved, s);
1504 --ld_state.nunresolved;
1508 if (unlikely (!orule->val.assignment->provide_flag))
1510 /* The symbol is already defined and now again
1511 in the linker script. This is an error. */
1512 error (0, 0, gettext ("\
1513 duplicate definition of '%s' in linker script"),
1518 while ((s = s->next) != first);
1521 /* If the symbol only has to be provided if it is needed,
1522 ignore it here since it is not undefined. */
1523 if (orule->val.assignment->provide_flag)
1526 /* Allocate memory for this new symbol. */
1527 s = (struct symbol *)
1528 obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1530 /* Initialize it. */
1531 s->name = orule->val.assignment->variable;
1533 /* Insert it into the symbol hash table. */
1534 unsigned long int hval = elf_hash (s->name);
1535 if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
1538 /* This means the symbol is defined somewhere else.
1539 Maybe it comes from a DSO or so. Get the
1542 struct symbol *old = ld_symbol_tab_find (&ld_state.symbol_tab,
1544 assert (old != NULL);
1547 /* If this is a definition from the application itself
1548 this means a duplicate definition. */
1551 error (0, 0, gettext ("\
1552 duplicate definition of '%s' in linker script"),
1557 /* We use the definition from the linker script. */
1562 /* The symbol is (now) defined. */
1564 s->type = STT_NOTYPE;
1566 /* Add a reference to the symbol record. We will come
1567 across it when creating the output file. */
1568 orule->val.assignment->sym = s;
1570 SNGL_LIST_PUSH (ld_state.lscript_syms, s);
1571 ++ld_state.nlscript_syms;
1577 segment = segment->next;
1579 while (segment != ld_state.output_segments->next);
1583 /* Create creation of spection section symbols representing sections in the
1584 output file. This is done for symbols like _GLOBAL_OFFSET_TABLE_ and
1587 create_special_section_symbol (struct symbol **symp, const char *name)
1591 /* No symbol defined found yet. Create one. */
1592 struct symbol *newsym = (struct symbol *)
1593 obstack_calloc (&ld_state.smem, sizeof (*newsym));
1595 newsym->name = name;
1596 // XXX Should we mark the symbol hidden? They are hardly useful
1597 // used outside the current object.
1599 /* Add to the symbol table. */
1600 if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
1601 elf_hash (name), newsym) != 0))
1606 else if ((*symp)->defined)
1607 /* Cannot happen. We do use this symbol from any input file. */
1610 (*symp)->defined = 1;
1612 (*symp)->hidden = 1;
1613 (*symp)->type = STT_OBJECT;
1619 #include "debugpred.h"