1 /* Copyright (C) 2001-2011 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>. */
41 #include <stdio_ext.h>
45 #include <sys/param.h>
48 #include <elf-knowledge.h>
56 /* Header of .eh_frame_hdr section. */
57 struct unw_eh_frame_hdr
59 unsigned char version;
60 unsigned char eh_frame_ptr_enc;
61 unsigned char fde_count_enc;
62 unsigned char table_enc;
64 #define EH_FRAME_HDR_VERSION 1
67 /* Prototypes for local functions. */
68 static const char **ld_generic_lib_extensions (struct ld_state *)
69 __attribute__ ((__const__));
70 static int ld_generic_file_close (struct usedfiles *fileinfo,
71 struct ld_state *statep);
72 static int ld_generic_file_process (int fd, struct usedfiles *fileinfo,
73 struct ld_state *statep,
74 struct usedfiles **nextp);
75 static void ld_generic_generate_sections (struct ld_state *statep);
76 static void ld_generic_create_sections (struct ld_state *statep);
77 static int ld_generic_flag_unresolved (struct ld_state *statep);
78 static int ld_generic_open_outfile (struct ld_state *statep, int machine,
80 static int ld_generic_create_outfile (struct ld_state *statep);
81 static void ld_generic_relocate_section (struct ld_state *statep,
83 struct scninfo *firstp,
84 const Elf32_Word *dblindirect);
85 static int ld_generic_finalize (struct ld_state *statep);
86 static bool ld_generic_special_section_number_p (struct ld_state *statep,
88 static bool ld_generic_section_type_p (struct ld_state *statep,
90 static XElf_Xword ld_generic_dynamic_section_flags (struct ld_state *statep);
91 static void ld_generic_initialize_plt (struct ld_state *statep, Elf_Scn *scn);
92 static void ld_generic_initialize_pltrel (struct ld_state *statep,
94 static void ld_generic_initialize_got (struct ld_state *statep, Elf_Scn *scn);
95 static void ld_generic_initialize_gotplt (struct ld_state *statep,
97 static void ld_generic_finalize_plt (struct ld_state *statep, size_t nsym,
99 struct symbol **ndxtosymp);
100 static int ld_generic_rel_type (struct ld_state *statep);
101 static void ld_generic_count_relocations (struct ld_state *statep,
102 struct scninfo *scninfo);
103 static void ld_generic_create_relocations (struct ld_state *statep,
104 const Elf32_Word *dblindirect);
106 static int file_process2 (struct usedfiles *fileinfo);
107 static void mark_section_used (struct scninfo *scninfo, Elf32_Word shndx,
108 struct scninfo **grpscnp);
111 /* Map symbol index to struct symbol record. */
112 static struct symbol **ndxtosym;
114 /* String table reference to all symbols in the symbol table. */
115 static struct Ebl_Strent **symstrent;
118 /* Check whether file associated with FD is a DSO. */
122 /* We have to read the 'e_type' field. It has the same size (16
123 bits) in 32- and 64-bit ELF. */
126 return (pread (fd, &e_type, sizeof (e_type), offsetof (XElf_Ehdr, e_type))
128 && e_type == ET_DYN);
132 /* Print the complete name of a file, including the archive it is
135 print_file_name (FILE *s, struct usedfiles *fileinfo, int first_level,
140 if (fileinfo->archive_file != NULL)
142 npar = print_file_name (s, fileinfo->archive_file, 0, 0) + 1;
143 fputc_unlocked ('(', s);
144 fputs_unlocked (fileinfo->rfname, s);
148 fputc_unlocked (')', s);
151 fputs_unlocked (fileinfo->rfname, s);
153 if (first_level && newline)
154 fputc_unlocked ('\n', s);
160 /* Function to determine whether an object will be dynamically linked. */
162 dynamically_linked_p (void)
164 return (ld_state.file_type == dso_file_type || ld_state.nplt > 0
165 || ld_state.ngot > 0);
170 linked_from_dso_p (struct scninfo *scninfo, size_t symidx)
172 struct usedfiles *file = scninfo->fileinfo;
174 /* If this symbol is not undefined in this file it cannot come from
176 if (symidx < file->nlocalsymbols)
179 struct symbol *sym = file->symref[symidx];
181 return sym->defined && sym->in_dso;
185 /* Initialize state object. This callback function is called after the
186 parameters are parsed but before any file is searched for. */
188 ld_prepare_state (const char *emulation)
190 /* When generating DSO we normally allow undefined symbols. */
191 ld_state.nodefs = true;
193 /* To be able to detect problems we add a .comment section entry by
195 ld_state.add_ld_comment = true;
197 /* XXX We probably should find a better place for this. The index
198 of the first user-defined version is 2. */
199 ld_state.nextveridx = 2;
201 /* Pick an not too small number for the initial size of the tables. */
202 ld_symbol_tab_init (&ld_state.symbol_tab, 1027);
203 ld_section_tab_init (&ld_state.section_tab, 67);
204 ld_version_str_tab_init (&ld_state.version_str_tab, 67);
206 /* Initialize the section header string table. */
207 ld_state.shstrtab = ebl_strtabinit (true);
208 if (ld_state.shstrtab == NULL)
209 error (EXIT_FAILURE, errno, gettext ("cannot create string table"));
211 /* Initialize the callbacks. These are the defaults, the appropriate
212 backend can later install its own callbacks. */
213 ld_state.callbacks.lib_extensions = ld_generic_lib_extensions;
214 ld_state.callbacks.file_process = ld_generic_file_process;
215 ld_state.callbacks.file_close = ld_generic_file_close;
216 ld_state.callbacks.generate_sections = ld_generic_generate_sections;
217 ld_state.callbacks.create_sections = ld_generic_create_sections;
218 ld_state.callbacks.flag_unresolved = ld_generic_flag_unresolved;
219 ld_state.callbacks.open_outfile = ld_generic_open_outfile;
220 ld_state.callbacks.create_outfile = ld_generic_create_outfile;
221 ld_state.callbacks.relocate_section = ld_generic_relocate_section;
222 ld_state.callbacks.finalize = ld_generic_finalize;
223 ld_state.callbacks.special_section_number_p =
224 ld_generic_special_section_number_p;
225 ld_state.callbacks.section_type_p = ld_generic_section_type_p;
226 ld_state.callbacks.dynamic_section_flags = ld_generic_dynamic_section_flags;
227 ld_state.callbacks.initialize_plt = ld_generic_initialize_plt;
228 ld_state.callbacks.initialize_pltrel = ld_generic_initialize_pltrel;
229 ld_state.callbacks.initialize_got = ld_generic_initialize_got;
230 ld_state.callbacks.initialize_gotplt = ld_generic_initialize_gotplt;
231 ld_state.callbacks.finalize_plt = ld_generic_finalize_plt;
232 ld_state.callbacks.rel_type = ld_generic_rel_type;
233 ld_state.callbacks.count_relocations = ld_generic_count_relocations;
234 ld_state.callbacks.create_relocations = ld_generic_create_relocations;
236 #ifndef BASE_ELF_NAME
237 /* Find the ld backend library. Use EBL to determine the name if
238 the user hasn't provided one on the command line. */
239 if (emulation == NULL)
241 emulation = ebl_backend_name (ld_state.ebl);
242 assert (emulation != NULL);
244 size_t emulation_len = strlen (emulation);
246 /* Construct the file name. */
247 char *fname = (char *) alloca (sizeof "libld_" - 1 + emulation_len
249 strcpy (mempcpy (stpcpy (fname, "libld_"), emulation, emulation_len), ".so");
252 void *h = dlopen (fname, RTLD_LAZY);
254 error (EXIT_FAILURE, 0,
255 gettext ("cannot load ld backend library '%s': %s"),
258 /* Find the initializer. It must be present. */
259 char *initname = (char *) alloca (emulation_len + sizeof "_ld_init");
260 strcpy (mempcpy (initname, emulation, emulation_len), "_ld_init");
261 int (*initfct) (struct ld_state *)
262 = (int (*) (struct ld_state *)) dlsym (h, initname);
265 error (EXIT_FAILURE, 0, gettext ("\
266 cannot find init function in ld backend library '%s': %s"),
269 /* Store the handle. */
272 /* Call the init function. */
273 return initfct (&ld_state);
275 # define INIT_FCT_NAME(base) _INIT_FCT_NAME(base)
276 # define _INIT_FCT_NAME(base) base##_ld_init
277 /* Declare and call the initialization function. */
278 extern int INIT_FCT_NAME(BASE_ELF_NAME) (struct ld_state *);
279 return INIT_FCT_NAME(BASE_ELF_NAME) (&ld_state);
285 check_for_duplicate2 (struct usedfiles *newp, struct usedfiles *list)
287 struct usedfiles *first;
292 list = first = list->next;
295 /* When searching the needed list we might come across entries
296 for files which are not yet opened. Stop then, there is
297 nothing more to test. */
298 if (likely (list->status == not_opened))
301 if (unlikely (list->ino == newp->ino)
302 && unlikely (list->dev == newp->dev))
306 newp->status = closed;
307 if (newp->file_type == relocatable_file_type)
308 error (0, 0, gettext ("%s listed more than once as input"),
315 while (likely (list != first));
322 check_for_duplicate (struct usedfiles *newp)
326 if (unlikely (fstat (newp->fd, &st) < 0))
332 newp->dev = st.st_dev;
333 newp->ino = st.st_ino;
335 return (check_for_duplicate2 (newp, ld_state.relfiles)
336 || check_for_duplicate2 (newp, ld_state.dsofiles)
337 || check_for_duplicate2 (newp, ld_state.needed));
341 /* Find a file along the path described in the state. */
343 open_along_path2 (struct usedfiles *fileinfo, struct pathelement *path)
345 const char *fname = fileinfo->fname;
346 size_t fnamelen = strlen (fname);
348 struct pathelement *firstp = path;
351 /* Cannot find anything since we have no path. */
356 if (likely (path->exist >= 0))
358 /* Create the file name. */
360 size_t dirlen = strlen (path->pname);
363 if (fileinfo->file_type == archive_file_type)
365 const char **exts = (ld_state.statically
366 ? (const char *[2]) { ".a", NULL }
367 : LIB_EXTENSION (&ld_state));
369 /* We have to create the actual file name. We prepend "lib"
370 and add one of the extensions the platform has. */
371 while (*exts != NULL)
373 size_t extlen = strlen (*exts);
374 rfname = (char *) alloca (dirlen + 5 + fnamelen + extlen);
375 memcpy (mempcpy (stpcpy (mempcpy (rfname, path->pname,
381 fd = open (rfname, O_RDONLY);
382 if (likely (fd != -1) || errno != ENOENT)
384 err = fd == -1 ? errno : 0;
388 /* Next extension. */
394 assert (fileinfo->file_type == dso_file_type
395 || fileinfo->file_type == dso_needed_file_type);
397 rfname = (char *) alloca (dirlen + 1 + fnamelen + 1);
398 memcpy (stpcpy (mempcpy (rfname, path->pname, dirlen), "/"),
399 fname, fnamelen + 1);
401 fd = open (rfname, O_RDONLY);
402 if (unlikely (fd == -1))
406 if (likely (fd != -1))
408 /* We found the file. This also means the directory
413 /* Check whether we have this file already loaded. */
414 if (unlikely (check_for_duplicate (fileinfo) != 0))
417 /* Make a copy of the name. */
418 fileinfo->rfname = obstack_strdup (&ld_state.smem, rfname);
420 if (unlikely (ld_state.trace_files))
421 printf (fileinfo->file_type == archive_file_type
422 ? gettext ("%s (for -l%s)\n")
423 : gettext ("%s (for DT_NEEDED %s)\n"),
429 /* The file does not exist. Maybe the whole directory doesn't.
430 Check it unless we know it exists. */
431 if (unlikely (path->exist == 0))
435 /* Keep only the directory name. Note that the path
436 might be relative. This doesn't matter here. We do
437 the test in any case even if there is the chance that
438 somebody wants to change the programs working
439 directory at some point which would make the result
440 of this test void. Since changing the working
441 directory is completely wrong we are not taking this
442 case into account. */
443 rfname[dirlen] = '\0';
444 if (unlikely (stat (rfname, &st) < 0) || ! S_ISDIR (st.st_mode))
445 /* The directory does not exist or the named file is no
453 /* Next path element. */
456 while (likely (err == ENOENT && path != firstp));
463 open_along_path (struct usedfiles *fileinfo)
465 const char *fname = fileinfo->fname;
468 if (fileinfo->file_type == relocatable_file_type)
470 /* Only libraries are searched along the path. */
471 fileinfo->fd = open (fname, O_RDONLY);
473 if (likely (fileinfo->fd != -1))
475 /* We found the file. */
476 if (unlikely (ld_state.trace_files))
477 print_file_name (stdout, fileinfo, 1, 1);
479 return check_for_duplicate (fileinfo);
482 /* If the name is an absolute path we are done. */
487 /* If the user specified two parts to the LD_LIBRARY_PATH variable
488 try the first part now. */
489 err = open_along_path2 (fileinfo, ld_state.ld_library_path1);
491 /* Try the user-specified path next. */
493 err = open_along_path2 (fileinfo,
494 fileinfo->file_type == archive_file_type
495 ? ld_state.paths : ld_state.rpath_link);
497 /* Then the second part of the LD_LIBRARY_PATH value. */
498 if (unlikely (err == ENOENT))
500 err = open_along_path2 (fileinfo, ld_state.ld_library_path2);
502 /* In case we look for a DSO handle now the RUNPATH. */
505 if (fileinfo->file_type == dso_file_type)
506 err = open_along_path2 (fileinfo, ld_state.runpath_link);
508 /* Finally the path from the default linker script. */
510 err = open_along_path2 (fileinfo, ld_state.default_paths);
515 if (unlikely (err != 0)
516 && (err != EAGAIN || fileinfo->file_type == relocatable_file_type))
517 error (0, err, gettext ("cannot open %s"), fileinfo->fname);
524 matching_group_comdat_scn (const XElf_Sym *sym, size_t shndx,
525 struct usedfiles *fileinfo, struct symbol *oldp)
527 if ((shndx >= SHN_LORESERVE && shndx <= SHN_HIRESERVE)
528 || (oldp->scndx >= SHN_LORESERVE && oldp->scndx <= SHN_HIRESERVE))
529 /* Cannot be a group COMDAT section. */
532 size_t newgrpid = fileinfo->scninfo[shndx].grpid;
533 size_t oldgrpid = oldp->file->scninfo[oldp->scndx].grpid;
534 if (newgrpid == 0 || oldgrpid == 0)
537 assert (SCNINFO_SHDR (fileinfo->scninfo[newgrpid].shdr).sh_type
539 assert (SCNINFO_SHDR (oldp->file->scninfo[oldgrpid].shdr).sh_type
542 if (! fileinfo->scninfo[newgrpid].comdat_group
543 || ! oldp->file->scninfo[oldgrpid].comdat_group)
546 if (strcmp (fileinfo->scninfo[newgrpid].symbols->name,
547 oldp->file->scninfo[oldgrpid].symbols->name) != 0)
550 /* This is a matching, duplicate COMDAT group section. Ignore it. */
556 check_type_and_size (const XElf_Sym *sym, struct usedfiles *fileinfo,
559 /* We check the type and size of the symbols. In both cases the
560 information can be missing (size is zero, type is STT_NOTYPE) in
561 which case we issue no warnings. Otherwise everything must
562 match. If the type does not match there is no point in checking
565 if (XELF_ST_TYPE (sym->st_info) != STT_NOTYPE && oldp->type != STT_NOTYPE
566 && unlikely (oldp->type != XELF_ST_TYPE (sym->st_info)))
571 error (0, 0, gettext ("\
572 Warning: type of `%s' changed from %s in %s to %s in %s"),
574 ebl_symbol_type_name (ld_state.ebl, oldp->type,
575 buf1, sizeof (buf1)),
577 ebl_symbol_type_name (ld_state.ebl, XELF_ST_TYPE (sym->st_info),
578 buf2, sizeof (buf2)),
581 else if (XELF_ST_TYPE (sym->st_info) == STT_OBJECT
583 && unlikely (oldp->size != sym->st_size))
584 error (0, 0, gettext ("\
585 Warning: size of `%s' changed from %" PRIu64 " in %s to %" PRIu64 " in %s"),
586 oldp->name, (uint64_t) oldp->size, oldp->file->rfname,
587 (uint64_t) sym->st_size, fileinfo->rfname);
592 check_definition (const XElf_Sym *sym, size_t shndx, size_t symidx,
593 struct usedfiles *fileinfo, struct symbol *oldp)
596 bool old_in_dso = FILEINFO_EHDR (oldp->file->ehdr).e_type == ET_DYN;
597 bool new_in_dso = FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_DYN;
598 bool use_new_def = false;
600 if (shndx != SHN_UNDEF
602 || (shndx != SHN_COMMON && oldp->common && ! new_in_dso)
603 || (old_in_dso && ! new_in_dso)))
605 /* We found a definition for a previously undefined symbol or a
606 real definition for a previous common-only definition or a
607 redefinition of a symbol definition in an object file
608 previously defined in a DSO. First perform some tests which
609 will show whether the common is really matching the
611 check_type_and_size (sym, fileinfo, oldp);
613 /* We leave the next element intact to not interrupt the list
614 with the unresolved symbols. Whoever walks the list will
615 have to check the `defined' flag. But we remember that this
616 list element is not unresolved anymore. */
619 /* Remove from the list. */
620 --ld_state.nunresolved;
622 --ld_state.nunresolved_nonweak;
623 CDBL_LIST_DEL (ld_state.unresolved, oldp);
625 else if (oldp->common)
626 /* Remove from the list. */
627 CDBL_LIST_DEL (ld_state.common_syms, oldp);
629 /* Use the values of the definition from now on. */
632 else if (shndx != SHN_UNDEF
634 && matching_group_comdat_scn (sym, shndx, fileinfo, oldp))
635 /* The duplicate symbol is in a group COMDAT section with the same
636 signature as the one containing the original definition.
637 Just ignore the second definition. */
639 else if (shndx != SHN_UNDEF
640 && unlikely (! oldp->common)
642 && shndx != SHN_COMMON
643 /* Multiple definitions are no fatal errors if the -z muldefs flag
644 is used. We don't warn about the multiple definition unless we
645 are told to be verbose. */
646 && (!ld_state.muldefs || verbose)
647 && ! old_in_dso && fileinfo->file_type == relocatable_file_type)
649 /* We have a double definition. This is a problem. */
651 XElf_Sym_vardef (oldsym);
652 struct usedfiles *oldfile;
657 if (elf_getshdrnum (fileinfo->elf, &shnum) < 0)
658 error (EXIT_FAILURE, 0,
659 gettext ("cannot determine number of sections: %s"),
662 /* XXX Use only ebl_section_name. */
663 if (shndx < SHN_LORESERVE || (shndx > SHN_HIRESERVE && shndx < shnum))
664 scnname = elf_strptr (fileinfo->elf,
666 SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_name);
668 // XXX extended section
669 scnname = ebl_section_name (ld_state.ebl, shndx, 0, buf, sizeof (buf),
672 /* XXX Print source file and line number. */
673 print_file_name (stderr, fileinfo, 1, 0);
675 gettext ("(%s+%#" PRIx64 "): multiple definition of %s `%s'\n"),
677 (uint64_t) sym->st_value,
678 ebl_symbol_type_name (ld_state.ebl, XELF_ST_TYPE (sym->st_info),
682 oldfile = oldp->file;
683 xelf_getsymshndx (oldfile->symtabdata, oldfile->xndxdata, oldp->symidx,
685 assert (oldsym != NULL);
687 /* XXX Use only ebl_section_name. */
688 if (oldp->scndx < SHN_LORESERVE || oldp->scndx > SHN_HIRESERVE)
689 scnname = elf_strptr (oldfile->elf,
691 SCNINFO_SHDR (oldfile->scninfo[shndx].shdr).sh_name);
693 scnname = ebl_section_name (ld_state.ebl, oldp->scndx, oldp->scndx,
694 buf, sizeof (buf), NULL, shnum);
696 /* XXX Print source file and line number. */
697 print_file_name (stderr, oldfile, 1, 0);
698 fprintf (stderr, gettext ("(%s+%#" PRIx64 "): first defined here\n"),
699 scnname, (uint64_t) oldsym->st_value);
701 if (likely (!ld_state.muldefs))
704 else if (old_in_dso && fileinfo->file_type == relocatable_file_type
705 && shndx != SHN_UNDEF)
706 /* We use the definition from a normal relocatable file over the
707 definition in a DSO. This is what the dynamic linker would
710 else if (old_in_dso && !new_in_dso && oldp->defined && !oldp->on_dsolist)
712 CDBL_LIST_ADD_REAR (ld_state.from_dso, oldp);
713 ++ld_state.nfrom_dso;
715 /* If the object is a function we allocate a PLT entry,
716 otherwise only a GOT entry. */
717 if (oldp->type == STT_FUNC)
722 oldp->on_dsolist = 1;
724 else if (oldp->common && shndx == SHN_COMMON)
726 /* The symbol size is the largest of all common definitions. */
727 oldp->size = MAX (oldp->size, sym->st_size);
728 /* Similarly for the alignment. */
729 oldp->merge.value = MAX (oldp->merge.value, sym->st_value);
732 if (unlikely (use_new_def))
734 /* Adjust the symbol record appropriately and remove
735 the symbol from the list of symbols which are taken from DSOs. */
736 if (old_in_dso && fileinfo->file_type == relocatable_file_type)
738 CDBL_LIST_DEL (ld_state.from_dso, oldp);
739 --ld_state.nfrom_dso;
741 if (likely (oldp->type == STT_FUNC))
746 oldp->on_dsolist = 0;
749 /* Use the values of the definition from now on. */
750 oldp->size = sym->st_size;
751 oldp->type = XELF_ST_TYPE (sym->st_info);
752 oldp->symidx = symidx;
754 //oldp->symscndx = THESYMSCNDX must be passed;
755 oldp->file = fileinfo;
757 oldp->in_dso = new_in_dso;
758 oldp->common = shndx == SHN_COMMON;
759 if (likely (fileinfo->file_type == relocatable_file_type))
761 /* If the definition comes from a DSO we pertain the weak flag
762 and it's indicating whether the reference is weak or not. */
763 oldp->weak = XELF_ST_BIND (sym->st_info) == STB_WEAK;
765 // XXX Really exclude SHN_ABS?
766 if (shndx != SHN_COMMON && shndx != SHN_ABS)
768 struct scninfo *ignore;
769 mark_section_used (&fileinfo->scninfo[shndx], shndx, &ignore);
773 /* Add to the list of symbols used from DSOs if necessary. */
774 if (new_in_dso && !old_in_dso)
776 CDBL_LIST_ADD_REAR (ld_state.from_dso, oldp);
777 ++ld_state.nfrom_dso;
779 /* If the object is a function we allocate a PLT entry,
780 otherwise only a GOT entry. */
781 if (oldp->type == STT_FUNC)
786 oldp->on_dsolist = 1;
788 else if (shndx == SHN_COMMON)
790 /* Store the alignment. */
791 oldp->merge.value = sym->st_value;
793 CDBL_LIST_ADD_REAR (ld_state.common_syms, oldp);
801 static struct scninfo *
802 find_section_group (struct usedfiles *fileinfo, Elf32_Word shndx,
805 struct scninfo *runp;
807 for (runp = fileinfo->groups; runp != NULL; runp = runp->next)
814 data = elf_getdata (runp->scn, NULL);
816 error (EXIT_FAILURE, 0,
817 gettext ("%s: cannot get section group data: %s"),
818 fileinfo->fname, elf_errmsg (-1));
820 /* There cannot be another data block. */
821 assert (elf_getdata (runp->scn, data) == NULL);
823 grpref = (Elf32_Word *) data->d_buf;
824 cnt = data->d_size / sizeof (Elf32_Word);
825 /* Note that we stop after looking at index 1 since index 0
826 contains the flags for the section group. */
828 if (grpref[--cnt] == shndx)
835 /* If we come here no section group contained the given section
836 despite the SHF_GROUP flag. This is an error in the input
838 error (EXIT_FAILURE, 0, gettext ("\
839 %s: section '%s' with group flag set does not belong to any group"),
841 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
842 SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_name));
847 /* Mark all sections which belong to the same group as section SHNDX
850 mark_section_group (struct usedfiles *fileinfo, Elf32_Word shndx,
851 struct scninfo **grpscnp)
853 /* First locate the section group. There can be several (many) of
858 struct scninfo *grpscn = find_section_group (fileinfo, shndx, &data);
861 /* Mark all the sections as used.
863 XXX Two possible problems here:
865 - the gABI says "The section must be referenced by a section of type
866 SHT_GROUP". I hope everybody reads this as "exactly one section".
868 - section groups are also useful to mark the debugging section which
869 belongs to a text section. Unconditionally adding debugging sections
870 is therefore probably not what is wanted if stripping is required. */
872 /* Mark the section group as handled. */
875 grpref = (Elf32_Word *) data->d_buf;
876 cnt = data->d_size / sizeof (Elf32_Word);
879 Elf32_Word idx = grpref[--cnt];
880 XElf_Shdr *shdr = &SCNINFO_SHDR (fileinfo->scninfo[idx].shdr);
882 if (fileinfo->scninfo[idx].grpid != grpscn->grpid)
883 error (EXIT_FAILURE, 0, gettext ("\
884 %s: section [%2d] '%s' is not in the correct section group"),
885 fileinfo->fname, (int) idx,
886 elf_strptr (fileinfo->elf, fileinfo->shstrndx, shdr->sh_name));
888 if (ld_state.strip == strip_none
889 /* If we are stripping, remove debug sections. */
890 || (!ebl_debugscn_p (ld_state.ebl,
891 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
893 /* And the relocation sections for the debug sections. */
894 && ((shdr->sh_type != SHT_RELA && shdr->sh_type != SHT_REL)
895 || !ebl_debugscn_p (ld_state.ebl,
896 elf_strptr (fileinfo->elf,
898 SCNINFO_SHDR (fileinfo->scninfo[shdr->sh_info].shdr).sh_name)))))
900 struct scninfo *ignore;
902 mark_section_used (&fileinfo->scninfo[idx], idx, &ignore);
909 mark_section_used (struct scninfo *scninfo, Elf32_Word shndx,
910 struct scninfo **grpscnp)
912 if (likely (scninfo->used))
913 /* Nothing to be done. */
916 /* We need this section. */
917 scninfo->used = true;
919 /* Make sure the section header has been read from the file. */
920 XElf_Shdr *shdr = &SCNINFO_SHDR (scninfo->shdr);
922 if (unlikely (scninfo->shdr == NULL))
924 if (unlikely (scninfo->shdr.sh_type == SHT_NULL))
928 shdr = xelf_getshdr (scninfo->scn, scninfo->shdr);
930 xelf_getshdr_copy (scninfo->scn, shdr, scninfo->shdr);
932 if (unlikely (shdr == NULL))
933 /* Something is very wrong. The calling code will notice it
934 soon and print a message. */
938 /* Handle section linked by 'sh_link'. */
939 if (unlikely (shdr->sh_link != 0))
941 struct scninfo *ignore;
942 mark_section_used (&scninfo->fileinfo->scninfo[shdr->sh_link],
943 shdr->sh_link, &ignore);
946 /* Handle section linked by 'sh_info'. */
947 if (unlikely (shdr->sh_info != 0) && (shdr->sh_flags & SHF_INFO_LINK))
949 struct scninfo *ignore;
950 mark_section_used (&scninfo->fileinfo->scninfo[shdr->sh_info],
951 shdr->sh_info, &ignore);
954 if (unlikely (shdr->sh_flags & SHF_GROUP) && ld_state.gc_sections)
955 /* Find the section group which contains this section. */
956 mark_section_group (scninfo->fileinfo, shndx, grpscnp);
960 /* We collect all sections in a hashing table. All sections with the
961 same name are collected in a list. Note that we do not determine
962 which sections are finally collected in the same output section
963 here. This would be terribly inefficient. It will be done later. */
965 add_section (struct usedfiles *fileinfo, struct scninfo *scninfo)
967 struct scnhead *queued;
968 struct scnhead search;
969 unsigned long int hval;
970 XElf_Shdr *shdr = &SCNINFO_SHDR (scninfo->shdr);
971 struct scninfo *grpscn = NULL;
972 Elf_Data *grpscndata = NULL;
974 /* See whether we can determine right away whether we need this
975 section in the output.
977 XXX I assume here that --gc-sections only affects extraction
978 from an archive. If it also affects objects files given on
979 the command line then somebody must explain to me how the
980 dependency analysis should work. Should the entry point be
981 the root? What if it is a numeric value? */
983 && (ld_state.strip == strip_none
984 || (shdr->sh_flags & SHF_ALLOC) != 0
985 || shdr->sh_type == SHT_NOTE
986 || (shdr->sh_type == SHT_PROGBITS
987 && strcmp (elf_strptr (fileinfo->elf,
989 shdr->sh_name), ".comment") == 0))
990 && (fileinfo->status != in_archive || !ld_state.gc_sections))
991 /* Mark as used and handle reference recursively if necessary. */
992 mark_section_used (scninfo, elf_ndxscn (scninfo->scn), &grpscn);
994 if ((shdr->sh_flags & SHF_GROUP) && grpscn == NULL)
995 /* Determine the symbol which name constitutes the signature
996 for the section group. */
997 grpscn = find_section_group (fileinfo, elf_ndxscn (scninfo->scn),
999 assert (grpscn == NULL || grpscn->symbols->name != NULL);
1001 /* Determine the section name. */
1002 search.name = elf_strptr (fileinfo->elf, fileinfo->shstrndx, shdr->sh_name);
1003 search.type = shdr->sh_type;
1004 search.flags = shdr->sh_flags;
1005 search.entsize = shdr->sh_entsize;
1006 search.grp_signature = grpscn != NULL ? grpscn->symbols->name : NULL;
1007 search.kind = scn_normal;
1008 hval = elf_hash (search.name);
1010 /* Find already queued sections. */
1011 queued = ld_section_tab_find (&ld_state.section_tab, hval, &search);
1014 bool is_comdat = false;
1016 /* If this section is part of a COMDAT section group we simply
1017 ignore it since we already have a copy. */
1018 if (unlikely (shdr->sh_flags & SHF_GROUP))
1020 /* Get the data of the section group section. */
1021 if (grpscndata == NULL)
1023 grpscndata = elf_getdata (grpscn->scn, NULL);
1024 assert (grpscndata != NULL);
1027 /* XXX Possibly unaligned memory access. */
1028 if ((((Elf32_Word *) grpscndata->d_buf)[0] & GRP_COMDAT) != 0)
1030 /* We have to compare the group signatures. There might
1031 be sections with the same name but belonging to
1032 groups with different signatures. This means we have
1033 to compare the new group signature with all those
1034 already collected. There might also be some
1035 non-group sections in the mix. */
1036 struct scninfo *runp = queued->last;
1039 if (SCNINFO_SHDR (runp->shdr).sh_flags & SHF_GROUP)
1041 struct scninfo *grpscn2
1042 = find_section_group (runp->fileinfo,
1043 elf_ndxscn (runp->scn),
1046 if (strcmp (grpscn->symbols->name,
1047 grpscn2->symbols->name) == 0)
1049 scninfo->unused_comdat = is_comdat = true;
1056 while (runp != queued->last);
1062 /* No COMDAT section, we use the data. */
1063 scninfo->next = queued->last->next;
1064 queued->last = queued->last->next = scninfo;
1066 queued->flags = ebl_sh_flags_combine (ld_state.ebl, queued->flags,
1068 queued->align = MAX (queued->align, shdr->sh_addralign);
1073 /* We do not use obstacks here since the memory might be
1075 queued = (struct scnhead *) xcalloc (sizeof (struct scnhead), 1);
1076 queued->kind = scn_normal;
1077 queued->name = search.name;
1078 queued->type = shdr->sh_type;
1079 queued->flags = shdr->sh_flags;
1080 queued->align = shdr->sh_addralign;
1081 queued->entsize = shdr->sh_entsize;
1082 queued->grp_signature = grpscn != NULL ? grpscn->symbols->name : NULL;
1083 queued->segment_nr = ~0;
1084 queued->last = scninfo->next = scninfo;
1086 /* Check whether we need a TLS segment. */
1087 ld_state.need_tls |= (shdr->sh_flags & SHF_TLS) != 0;
1089 /* Add to the hash table and possibly overwrite existing value. */
1090 ld_section_tab_insert (&ld_state.section_tab, hval, queued);
1096 add_relocatable_file (struct usedfiles *fileinfo, GElf_Word secttype)
1100 Elf_Data *symtabdata = NULL;
1101 Elf_Data *xndxdata = NULL;
1102 Elf_Data *versymdata = NULL;
1103 Elf_Data *verdefdata = NULL;
1104 Elf_Data *verneeddata = NULL;
1105 size_t symstridx = 0;
1106 size_t nsymbols = 0;
1107 size_t nlocalsymbols = 0;
1108 bool has_merge_sections = false;
1109 bool has_tls_symbols = false;
1110 /* Unless we have different information we assume the code needs
1111 an executable stack. */
1112 enum execstack execstack = execstack_true;
1114 /* Prerequisites. */
1115 assert (fileinfo->elf != NULL);
1117 /* Allocate memory for the sections. */
1118 if (unlikely (elf_getshdrnum (fileinfo->elf, &scncnt) < 0))
1119 error (EXIT_FAILURE, 0,
1120 gettext ("cannot determine number of sections: %s"),
1123 fileinfo->scninfo = (struct scninfo *)
1124 obstack_calloc (&ld_state.smem, scncnt * sizeof (struct scninfo));
1126 /* Read all the section headers and find the symbol table. Note
1127 that we don't skip the section with index zero. Even though the
1128 section itself is always empty the section header contains
1129 informaton for the case when the section index for the section
1130 header string table is too large to fit in the ELF header. */
1131 for (cnt = 0; cnt < scncnt; ++cnt)
1133 /* Store the handle for the section. */
1134 fileinfo->scninfo[cnt].scn = elf_getscn (fileinfo->elf, cnt);
1136 /* Get the ELF section header and data. */
1139 if (fileinfo->scninfo[cnt].shdr == NULL)
1141 if (fileinfo->scninfo[cnt].shdr.sh_type == SHT_NULL)
1145 shdr = xelf_getshdr (fileinfo->scninfo[cnt].scn,
1146 fileinfo->scninfo[cnt].shdr);
1148 xelf_getshdr_copy (fileinfo->scninfo[cnt].scn, shdr,
1149 fileinfo->scninfo[cnt].shdr);
1153 /* This should never happen. */
1154 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1155 fileinfo->rfname, __FILE__, __LINE__);
1160 shdr = &SCNINFO_SHDR (fileinfo->scninfo[cnt].shdr);
1162 Elf_Data *data = elf_getdata (fileinfo->scninfo[cnt].scn, NULL);
1164 /* Check whether this section is marked as merge-able. */
1165 has_merge_sections |= (shdr->sh_flags & SHF_MERGE) != 0;
1166 has_tls_symbols |= (shdr->sh_flags & SHF_TLS) != 0;
1168 /* Get the ELF section header and data. */
1169 /* Make the file structure available. */
1170 fileinfo->scninfo[cnt].fileinfo = fileinfo;
1172 if (unlikely (shdr->sh_type == SHT_SYMTAB)
1173 || unlikely (shdr->sh_type == SHT_DYNSYM))
1175 if (shdr->sh_type == SHT_SYMTAB)
1177 assert (fileinfo->symtabdata == NULL);
1178 fileinfo->symtabdata = data;
1179 fileinfo->nsymtab = shdr->sh_size / shdr->sh_entsize;
1180 fileinfo->nlocalsymbols = shdr->sh_info;
1181 fileinfo->symstridx = shdr->sh_link;
1185 assert (fileinfo->dynsymtabdata == NULL);
1186 fileinfo->dynsymtabdata = data;
1187 fileinfo->ndynsymtab = shdr->sh_size / shdr->sh_entsize;
1188 fileinfo->dynsymstridx = shdr->sh_link;
1191 /* If we are looking for the normal symbol table we just
1193 if (secttype == shdr->sh_type)
1195 assert (symtabdata == NULL);
1197 symstridx = shdr->sh_link;
1198 nsymbols = shdr->sh_size / shdr->sh_entsize;
1199 nlocalsymbols = shdr->sh_info;
1202 else if (unlikely (shdr->sh_type == SHT_SYMTAB_SHNDX))
1204 assert (xndxdata == NULL);
1205 fileinfo->xndxdata = xndxdata = data;
1207 else if (unlikely (shdr->sh_type == SHT_GNU_versym))
1209 assert (versymdata == 0);
1210 fileinfo->versymdata = versymdata = data;
1212 else if (unlikely (shdr->sh_type == SHT_GNU_verdef))
1216 assert (verdefdata == 0);
1217 fileinfo->verdefdata = verdefdata = data;
1219 /* Allocate the arrays flagging the use of the version and
1220 to track of allocated names. */
1221 fileinfo->nverdef = nversions = shdr->sh_info;
1222 /* We have NVERSIONS + 1 because the indeces used to access the
1223 sectino start with one; zero represents local binding. */
1224 fileinfo->verdefused = (XElf_Versym *)
1225 obstack_calloc (&ld_state.smem,
1226 sizeof (XElf_Versym) * (nversions + 1));
1227 fileinfo->verdefent = (struct Ebl_Strent **)
1228 obstack_alloc (&ld_state.smem,
1229 sizeof (struct Ebl_Strent *) * (nversions + 1));
1231 else if (unlikely (shdr->sh_type == SHT_GNU_verneed))
1233 assert (verneeddata == 0);
1234 fileinfo->verneeddata = verneeddata = data;
1236 else if (unlikely (shdr->sh_type == SHT_DYNAMIC))
1238 assert (fileinfo->dynscn == NULL);
1239 fileinfo->dynscn = fileinfo->scninfo[cnt].scn;
1241 else if (unlikely (shdr->sh_type == SHT_GROUP))
1244 XElf_Shdr_vardef (symshdr);
1247 if (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_REL)
1248 error (EXIT_FAILURE, 0, gettext ("\
1249 %s: only files of type ET_REL might contain section groups"),
1252 fileinfo->scninfo[cnt].next = fileinfo->groups;
1253 fileinfo->scninfo[cnt].grpid = cnt;
1254 fileinfo->groups = &fileinfo->scninfo[cnt];
1256 /* Determine the signature. We create a symbol record for
1257 it. Only the name element is important. */
1258 fileinfo->scninfo[cnt].symbols = (struct symbol *)
1259 obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1261 symscn = elf_getscn (fileinfo->elf, shdr->sh_link);
1262 xelf_getshdr (symscn, symshdr);
1263 symdata = elf_getdata (symscn, NULL);
1265 if (symshdr != NULL)
1267 XElf_Sym_vardef (sym);
1269 /* We don't need the section index and therefore we don't
1270 have to use 'xelf_getsymshndx'. */
1271 xelf_getsym (symdata, shdr->sh_info, sym);
1274 struct symbol *symbol = fileinfo->scninfo[cnt].symbols;
1277 if (XELF_ST_TYPE (sym->st_info) == STT_SECTION)
1279 XElf_Shdr_vardef (buggyshdr);
1280 xelf_getshdr (elf_getscn (fileinfo->elf, sym->st_shndx),
1283 symbol->name = elf_strptr (fileinfo->elf,
1284 FILEINFO_EHDR (fileinfo->ehdr).e_shstrndx,
1285 buggyshdr->sh_name);
1286 symbol->symidx = -1;
1291 symbol->name = elf_strptr (fileinfo->elf,
1294 symbol->symidx = shdr->sh_info;
1296 symbol->file = fileinfo;
1299 if (fileinfo->scninfo[cnt].symbols->name == NULL)
1300 error (EXIT_FAILURE, 0, gettext ("\
1301 %s: cannot determine signature of section group [%2zd] '%s': %s"),
1303 elf_ndxscn (fileinfo->scninfo[cnt].scn),
1304 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1309 /* For all the sections which are part of this group, add
1312 error (EXIT_FAILURE, 0, gettext ("\
1313 %s: cannot get content of section group [%2zd] '%s': %s'"),
1314 fileinfo->fname, elf_ndxscn (fileinfo->scninfo[cnt].scn),
1315 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1319 Elf32_Word *grpdata = (Elf32_Word *) data->d_buf;
1320 if (grpdata[0] & GRP_COMDAT)
1321 fileinfo->scninfo[cnt].comdat_group = true;
1322 for (size_t inner = 1; inner < data->d_size / sizeof (Elf32_Word);
1325 if (grpdata[inner] >= scncnt)
1326 error (EXIT_FAILURE, 0, gettext ("\
1327 %s: group member %zu of section group [%2zd] '%s' has too high index: %" PRIu32),
1329 inner, elf_ndxscn (fileinfo->scninfo[cnt].scn),
1330 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1334 fileinfo->scninfo[grpdata[inner]].grpid = cnt;
1337 /* The 'used' flag is used to indicate when the information
1338 in the section group is used to mark all other sections
1339 as used. So it must not be true yet. */
1340 assert (fileinfo->scninfo[cnt].used == false);
1342 else if (! SECTION_TYPE_P (&ld_state, shdr->sh_type)
1343 && unlikely ((shdr->sh_flags & SHF_OS_NONCONFORMING) != 0))
1344 /* According to the gABI it is a fatal error if the file contains
1345 a section with unknown type and the SHF_OS_NONCONFORMING flag
1347 error (EXIT_FAILURE, 0,
1348 gettext ("%s: section '%s' has unknown type: %d"),
1350 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1352 (int) shdr->sh_type);
1353 /* We don't have to add a few section types here. These will be
1354 generated from scratch for the new output file. We also
1355 don't add the sections of DSOs here since these sections are
1356 not used in the resulting object file. */
1357 else if (likely (fileinfo->file_type == relocatable_file_type)
1359 && likely (shdr->sh_type == SHT_PROGBITS
1360 || shdr->sh_type == SHT_RELA
1361 || shdr->sh_type == SHT_REL
1362 || shdr->sh_type == SHT_NOTE
1363 || shdr->sh_type == SHT_NOBITS
1364 || shdr->sh_type == SHT_INIT_ARRAY
1365 || shdr->sh_type == SHT_FINI_ARRAY
1366 || shdr->sh_type == SHT_PREINIT_ARRAY))
1368 /* Check whether the section needs to be executable. */
1369 if (shdr->sh_type == SHT_PROGBITS
1370 && (shdr->sh_flags & SHF_EXECINSTR) == 0
1371 && strcmp (elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1373 ".note.GNU-stack") == 0)
1374 execstack = execstack_false;
1376 add_section (fileinfo, &fileinfo->scninfo[cnt]);
1380 /* Now we know more about the requirements for an executable stack
1382 if (fileinfo->file_type == relocatable_file_type
1383 && execstack == execstack_true
1384 && ld_state.execstack != execstack_false_force)
1385 ld_state.execstack = execstack_true;
1387 /* Handle the symbols. Record defined and undefined symbols in the
1388 hash table. In theory there can be a file without any symbol
1390 if (likely (symtabdata != NULL))
1392 /* In case this file contains merge-able sections we have to
1393 locate the symbols which are in these sections. */
1394 fileinfo->has_merge_sections = has_merge_sections;
1395 if (likely (has_merge_sections || has_tls_symbols))
1397 fileinfo->symref = (struct symbol **)
1398 obstack_calloc (&ld_state.smem,
1399 nsymbols * sizeof (struct symbol *));
1401 /* Only handle the local symbols here. */
1402 for (cnt = 0; cnt < nlocalsymbols; ++cnt)
1405 XElf_Sym_vardef (sym);
1407 xelf_getsymshndx (symtabdata, xndxdata, cnt, sym, shndx);
1410 /* This should never happen. */
1411 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1412 fileinfo->rfname, __FILE__, __LINE__);
1416 if (likely (shndx != SHN_XINDEX))
1417 shndx = sym->st_shndx;
1418 else if (unlikely (shndx == 0))
1420 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1421 fileinfo->rfname, __FILE__, __LINE__);
1425 if (XELF_ST_TYPE (sym->st_info) != STT_SECTION
1426 && (shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE)
1427 && ((SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_flags
1429 || XELF_ST_TYPE (sym->st_info) == STT_TLS))
1431 /* Create a symbol record for this symbol and add it
1432 to the list for this section. */
1433 struct symbol *newp;
1435 newp = (struct symbol *)
1436 obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1439 newp->scndx = shndx;
1440 newp->file = fileinfo;
1442 fileinfo->symref[cnt] = newp;
1444 if (fileinfo->scninfo[shndx].symbols == NULL)
1445 fileinfo->scninfo[shndx].symbols = newp->next_in_scn
1450 = fileinfo->scninfo[shndx].symbols->next_in_scn;
1451 fileinfo->scninfo[shndx].symbols
1452 = fileinfo->scninfo[shndx].symbols->next_in_scn = newp;
1458 /* Create array with pointers to the symbol definitions. Note
1459 that we only allocate memory for the non-local symbols
1460 since we have no merge-able sections. But we store the
1461 pointer as if it was for the whole symbol table. This
1462 saves some memory. */
1463 fileinfo->symref = (struct symbol **)
1464 obstack_calloc (&ld_state.smem, ((nsymbols - nlocalsymbols)
1465 * sizeof (struct symbol *)))
1468 /* Don't handle local symbols here. It's either not necessary
1469 at all or has already happened. */
1470 for (cnt = nlocalsymbols; cnt < nsymbols; ++cnt)
1472 XElf_Sym_vardef (sym);
1474 xelf_getsymshndx (symtabdata, xndxdata, cnt, sym, shndx);
1478 /* This should never happen. */
1479 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1480 fileinfo->rfname, __FILE__, __LINE__);
1484 if (likely (shndx != SHN_XINDEX))
1485 shndx = sym->st_shndx;
1486 else if (unlikely (shndx == 0))
1488 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1489 fileinfo->rfname, __FILE__, __LINE__);
1493 /* We ignore ABS symbols from DSOs. */
1494 // XXX Is this correct?
1495 if (unlikely (shndx == SHN_ABS) && secttype == SHT_DYNSYM)
1498 if ((shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE)
1499 && fileinfo->scninfo[shndx].unused_comdat)
1500 /* The symbol is not used. */
1503 /* If the DSO uses symbol versions determine whether this is
1504 the default version. Otherwise we'll ignore the symbol. */
1505 if (versymdata != NULL)
1509 if (xelf_getversym_copy (versymdata, cnt, versym) == NULL)
1510 /* XXX Should we handle faulty input files more graceful? */
1511 assert (! "xelf_getversym failed");
1513 if ((versym & 0x8000) != 0)
1514 /* Ignore the symbol, it's not the default version. */
1518 /* See whether we know anything about this symbol. */
1519 struct symbol search;
1520 search.name = elf_strptr (fileinfo->elf, symstridx, sym->st_name);
1521 unsigned long int hval = elf_hash (search.name);
1523 /* We ignore the symbols the linker generates. This are
1524 _GLOBAL_OFFSET_TABLE_, _DYNAMIC. */
1525 // XXX This loop is hot and the following tests hardly ever match.
1526 // XXX Maybe move the tests somewhere they are executed less often.
1527 if (((unlikely (hval == 165832675ul)
1528 && strcmp (search.name, "_DYNAMIC") == 0)
1529 || (unlikely (hval == 102264335ul)
1530 && strcmp (search.name, "_GLOBAL_OFFSET_TABLE_") == 0))
1531 && sym->st_shndx != SHN_UNDEF
1532 /* If somebody defines such a variable in a relocatable we
1533 don't ignore it. Let the user get what s/he deserves. */
1534 && fileinfo->file_type != relocatable_file_type)
1537 struct symbol *oldp = ld_symbol_tab_find (&ld_state.symbol_tab,
1539 struct symbol *newp;
1540 if (likely (oldp == NULL))
1542 /* No symbol of this name known. Add it. */
1543 newp = (struct symbol *) obstack_alloc (&ld_state.smem,
1545 newp->name = search.name;
1546 newp->size = sym->st_size;
1547 newp->type = XELF_ST_TYPE (sym->st_info);
1549 newp->outsymidx = 0;
1550 newp->outdynsymidx = 0;
1551 newp->scndx = shndx;
1552 newp->file = fileinfo;
1553 newp->defined = newp->scndx != SHN_UNDEF;
1554 newp->common = newp->scndx == SHN_COMMON;
1555 newp->weak = XELF_ST_BIND (sym->st_info) == STB_WEAK;
1560 newp->need_copy = 0;
1561 newp->on_dsolist = 0;
1562 newp->in_dso = secttype == SHT_DYNSYM;
1563 newp->next_in_scn = NULL;
1566 newp->previous = NULL;
1569 if (newp->scndx == SHN_UNDEF)
1571 CDBL_LIST_ADD_REAR (ld_state.unresolved, newp);
1572 ++ld_state.nunresolved;
1574 ++ld_state.nunresolved_nonweak;
1576 else if (newp->scndx == SHN_COMMON)
1578 /* Store the alignment requirement. */
1579 newp->merge.value = sym->st_value;
1581 CDBL_LIST_ADD_REAR (ld_state.common_syms, newp);
1584 /* Insert the new symbol. */
1585 if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
1587 /* This cannot happen. */
1590 fileinfo->symref[cnt] = newp;
1592 /* We have a few special symbols to recognize. The symbols
1593 _init and _fini are the initialization and finalization
1594 functions respectively. They have to be made known in
1595 the dynamic section and therefore we have to find out
1596 now whether these functions exist or not. */
1597 if (hval == 6685956 && strcmp (newp->name, "_init") == 0)
1598 ld_state.init_symbol = newp;
1599 else if (hval == 6672457 && strcmp (newp->name, "_fini") == 0)
1600 ld_state.fini_symbol = newp;
1602 else if (unlikely (check_definition (sym, shndx, cnt, fileinfo, oldp)
1604 /* A fatal error (multiple definition of a symbol)
1605 occurred, no need to continue. */
1608 /* Use the previously allocated symbol record. It has
1609 been updated in check_definition(), if necessary. */
1610 newp = fileinfo->symref[cnt] = oldp;
1612 /* Mark the section the symbol we need comes from as used. */
1613 if (shndx != SHN_UNDEF
1614 && (shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE))
1616 struct scninfo *ignore;
1620 assert (elf_getshdrnum (fileinfo->elf, &shnum) == 0);
1621 assert (shndx < shnum);
1624 /* Mark section (and all dependencies) as used. */
1625 mark_section_used (&fileinfo->scninfo[shndx], shndx, &ignore);
1627 /* Check whether the section is merge-able. In this case we
1628 have to record the symbol. */
1629 if (SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_flags
1632 if (fileinfo->scninfo[shndx].symbols == NULL)
1633 fileinfo->scninfo[shndx].symbols = newp->next_in_scn
1638 = fileinfo->scninfo[shndx].symbols->next_in_scn;
1639 fileinfo->scninfo[shndx].symbols
1640 = fileinfo->scninfo[shndx].symbols->next_in_scn = newp;
1646 /* This file is used. */
1647 if (likely (fileinfo->file_type == relocatable_file_type))
1649 if (unlikely (ld_state.relfiles == NULL))
1650 ld_state.relfiles = fileinfo->next = fileinfo;
1653 fileinfo->next = ld_state.relfiles->next;
1654 ld_state.relfiles = ld_state.relfiles->next = fileinfo;
1657 /* Update some summary information in the state structure. */
1658 ld_state.nsymtab += fileinfo->nsymtab;
1659 ld_state.nlocalsymbols += fileinfo->nlocalsymbols;
1661 else if (likely (fileinfo->file_type == dso_file_type))
1663 CSNGL_LIST_ADD_REAR (ld_state.dsofiles, fileinfo);
1664 ++ld_state.ndsofiles;
1666 if (fileinfo->lazyload)
1667 /* We have to create another dynamic section entry for the
1670 XXX Once more functionality than the lazyloading flag
1671 are suppported the test must be extended. */
1672 ++ld_state.ndsofiles;
1681 ld_handle_filename_list (struct filename_list *fnames)
1683 struct filename_list *runp;
1686 for (runp = fnames; runp != NULL; runp = runp->next)
1688 struct usedfiles *curp;
1690 /* Create a record for the new file. */
1691 curp = runp->real = ld_new_inputfile (runp->name, relocatable_file_type);
1693 /* Set flags for group handling. */
1694 curp->group_start = runp->group_start;
1695 curp->group_end = runp->group_end;
1697 /* Set as-needed flag from the file, not the command line. */
1698 curp->as_needed = runp->as_needed;
1700 /* Read the file and everything else which comes up, including
1703 res |= FILE_PROCESS (-1, curp, &ld_state, &curp);
1704 while (curp != NULL);
1707 /* Free the list. */
1708 while (fnames != NULL)
1711 fnames = fnames->next;
1719 /* Handle opening of the given file with ELF descriptor. */
1721 open_elf (struct usedfiles *fileinfo, Elf *elf)
1726 error (EXIT_FAILURE, 0,
1727 gettext ("cannot get descriptor for ELF file (%s:%d): %s\n"),
1728 __FILE__, __LINE__, elf_errmsg (-1));
1730 if (unlikely (elf_kind (elf) == ELF_K_NONE))
1732 struct filename_list *fnames;
1734 /* We don't have to look at this file again. */
1735 fileinfo->status = closed;
1737 /* Let's see whether this is a linker script. */
1738 if (fileinfo->fd != -1)
1739 /* Create a stream from the file handle we know. */
1740 ldin = fdopen (fileinfo->fd, "r");
1743 /* Get the memory for the archive member. */
1747 /* Get the content of the file. */
1748 content = elf_rawfile (elf, &contentsize);
1749 if (content == NULL)
1751 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1752 fileinfo->rfname, __FILE__, __LINE__);
1756 /* The content of the file is available in memory. Read the
1757 memory region as a stream. */
1758 ldin = fmemopen (content, contentsize, "r");
1761 /* No need for locking. */
1762 __fsetlocking (ldin, FSETLOCKING_BYCALLER);
1765 error (EXIT_FAILURE, errno, gettext ("cannot open '%s'"),
1768 /* Parse the file. If it is a linker script no problems will be
1770 ld_state.srcfiles = NULL;
1772 ld_scan_version_script = 0;
1773 ldin_fname = fileinfo->rfname;
1777 if (fileinfo->fd != -1 && !fileinfo->fd_passed)
1779 /* We won't need the file descriptor again. */
1780 close (fileinfo->fd);
1786 if (unlikely (res != 0))
1787 /* Something went wrong during parsing. */
1790 /* This is no ELF file. */
1791 fileinfo->elf = NULL;
1793 /* Now we have to handle eventual INPUT and GROUP statements in
1794 the script. Read the files mentioned. */
1795 fnames = ld_state.srcfiles;
1798 struct filename_list *oldp;
1800 /* Convert the list into a normal single-linked list. */
1802 fnames = fnames->next;
1805 /* Remove the list from the state structure. */
1806 ld_state.srcfiles = NULL;
1808 if (unlikely (ld_handle_filename_list (fnames) != 0))
1815 /* Store the file info. */
1816 fileinfo->elf = elf;
1818 /* The file is ready for action. */
1819 fileinfo->status = opened;
1826 add_whole_archive (struct usedfiles *fileinfo)
1829 Elf_Cmd cmd = ELF_C_READ_MMAP_PRIVATE;
1832 while ((arelf = elf_begin (fileinfo->fd, cmd, fileinfo->elf)) != NULL)
1834 Elf_Arhdr *arhdr = elf_getarhdr (arelf);
1835 struct usedfiles *newp;
1840 /* Just to be sure; since these are no files in the archive
1841 these names should never be returned. */
1842 assert (strcmp (arhdr->ar_name, "/") != 0);
1843 assert (strcmp (arhdr->ar_name, "//") != 0);
1845 newp = ld_new_inputfile (arhdr->ar_name, relocatable_file_type);
1846 newp->archive_file = fileinfo;
1848 if (unlikely (ld_state.trace_files))
1849 print_file_name (stdout, newp, 1, 1);
1851 /* This shows that this file is contained in an archive. */
1853 /* Store the ELF descriptor. */
1855 /* Show that we are open for business. */
1856 newp->status = opened;
1858 /* Proces the file, add all the symbols etc. */
1859 res = file_process2 (newp);
1860 if (unlikely (res != 0))
1863 /* Advance to the next archive element. */
1864 cmd = elf_next (arelf);
1872 extract_from_archive (struct usedfiles *fileinfo)
1874 static int archive_seq;
1877 if (fileinfo->archive_seq == 0)
1878 /* This is an archive we are not using completely. Give it a
1880 fileinfo->archive_seq = ++archive_seq;
1882 /* If there are no unresolved symbols don't do anything. */
1883 assert (ld_state.extract_rule == defaultextract
1884 || ld_state.extract_rule == weakextract);
1885 if ((likely (ld_state.extract_rule == defaultextract)
1886 ? ld_state.nunresolved_nonweak : ld_state.nunresolved) == 0)
1892 /* Get all the symbols. */
1893 syms = elf_getarsym (fileinfo->elf, &nsyms);
1896 cannot_read_archive:
1897 error (0, 0, gettext ("cannot read archive `%s': %s"),
1898 fileinfo->rfname, elf_errmsg (-1));
1900 /* We cannot use this archive anymore. */
1901 fileinfo->status = closed;
1906 /* Now add all the symbols to the hash table. Note that there
1907 can potentially be duplicate definitions. We'll always use
1908 the first definition. */
1909 // XXX Is this a compatible behavior?
1916 for (cnt = 0; cnt < nsyms; ++cnt)
1918 struct symbol search = { .name = syms[cnt].as_name };
1919 struct symbol *sym = ld_symbol_tab_find (&ld_state.symbol_tab,
1920 syms[cnt].as_hash, &search);
1921 if (sym != NULL && ! sym->defined)
1923 /* The symbol is referenced and not defined. */
1926 struct usedfiles *newp;
1928 /* Find the archive member for this symbol. */
1929 if (unlikely (elf_rand (fileinfo->elf, syms[cnt].as_off)
1930 != syms[cnt].as_off))
1931 goto cannot_read_archive;
1933 /* Note: no test of a failing 'elf_begin' call. That's fine
1934 since 'elf'getarhdr' will report the problem. */
1935 arelf = elf_begin (fileinfo->fd, ELF_C_READ_MMAP_PRIVATE,
1937 arhdr = elf_getarhdr (arelf);
1939 goto cannot_read_archive;
1941 /* We have all the information and an ELF handle for the
1942 archive member. Create the normal data structure for
1944 newp = ld_new_inputfile (obstack_strdup (&ld_state.smem,
1946 relocatable_file_type);
1947 newp->archive_file = fileinfo;
1949 if (unlikely (ld_state.trace_files))
1950 print_file_name (stdout, newp, 1, 1);
1952 /* This shows that this file is contained in an archive. */
1954 /* Store the ELF descriptor. */
1956 /* Show that we are open for business. */
1957 newp->status = in_archive;
1959 /* Now read the file and add all the symbols. */
1960 res = file_process2 (newp);
1961 if (unlikely (res != 0))
1970 /* This is an archive therefore it must have a number. */
1971 assert (fileinfo->archive_seq != 0);
1972 ld_state.last_archive_used = fileinfo->archive_seq;
1982 file_process2 (struct usedfiles *fileinfo)
1986 if (likely (elf_kind (fileinfo->elf) == ELF_K_ELF))
1988 /* The first time we get here we read the ELF header. */
1990 if (likely (fileinfo->ehdr == NULL))
1992 if (likely (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_NONE))
1997 ehdr = xelf_getehdr (fileinfo->elf, fileinfo->ehdr);
1999 xelf_getehdr_copy (fileinfo->elf, ehdr, fileinfo->ehdr);
2003 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
2004 fileinfo->rfname, __FILE__, __LINE__);
2005 fileinfo->status = closed;
2009 if (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_REL
2010 && unlikely (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_DYN))
2011 /* XXX Add ebl* function to query types which are allowed
2016 print_file_name (stderr, fileinfo, 1, 0);
2018 gettext ("file of type %s cannot be linked in\n"),
2019 ebl_object_type_name (ld_state.ebl,
2020 FILEINFO_EHDR (fileinfo->ehdr).e_type,
2021 buf, sizeof (buf)));
2022 fileinfo->status = closed;
2026 /* Make sure the file type matches the backend. */
2027 if (FILEINFO_EHDR (fileinfo->ehdr).e_machine
2028 != ebl_get_elfmachine (ld_state.ebl))
2030 fprintf (stderr, gettext ("\
2031 %s: input file incompatible with ELF machine type %s\n"),
2033 ebl_backend_name (ld_state.ebl));
2034 fileinfo->status = closed;
2038 /* Determine the section header string table section index. */
2039 if (unlikely (elf_getshdrstrndx (fileinfo->elf, &fileinfo->shstrndx)
2042 fprintf (stderr, gettext ("\
2043 %s: cannot get section header string table index: %s\n"),
2044 fileinfo->rfname, elf_errmsg (-1));
2045 fileinfo->status = closed;
2050 /* Now handle the different types of files. */
2051 if (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_REL)
2053 /* Add all the symbol. Relocatable files have symbol
2055 res = add_relocatable_file (fileinfo, SHT_SYMTAB);
2059 bool has_l_name = fileinfo->file_type == archive_file_type;
2061 assert (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_DYN);
2063 /* If the file is a DT_NEEDED dependency then the type is
2064 already correctly specified. */
2065 if (fileinfo->file_type != dso_needed_file_type)
2066 fileinfo->file_type = dso_file_type;
2068 /* We cannot use DSOs when generating relocatable objects. */
2069 if (ld_state.file_type == relocatable_file_type)
2071 error (0, 0, gettext ("\
2072 cannot use DSO '%s' when generating relocatable object file"),
2077 /* Add all the symbols. For DSOs we are looking at the
2078 dynamic symbol table. */
2079 res = add_relocatable_file (fileinfo, SHT_DYNSYM);
2081 /* We always have to have a dynamic section. */
2082 assert (fileinfo->dynscn != NULL);
2084 /* We have to remember the dependencies for this object. It
2085 is necessary to look them up. */
2086 XElf_Shdr_vardef (dynshdr);
2087 xelf_getshdr (fileinfo->dynscn, dynshdr);
2089 Elf_Data *dyndata = elf_getdata (fileinfo->dynscn, NULL);
2090 /* XXX Should we flag the failure to get the dynamic section? */
2091 if (dynshdr != NULL)
2093 int cnt = dynshdr->sh_size / dynshdr->sh_entsize;
2094 XElf_Dyn_vardef (dyn);
2098 xelf_getdyn (dyndata, cnt, dyn);
2101 if(dyn->d_tag == DT_NEEDED)
2103 struct usedfiles *newp;
2105 newp = ld_new_inputfile (elf_strptr (fileinfo->elf,
2108 dso_needed_file_type);
2110 /* Enqueue the newly found dependencies. */
2111 // XXX Check that there not already a file with the
2113 CSNGL_LIST_ADD_REAR (ld_state.needed, newp);
2115 else if (dyn->d_tag == DT_SONAME)
2117 /* We use the DT_SONAME (this is what's there
2119 fileinfo->soname = elf_strptr (fileinfo->elf,
2128 /* Construct the file name if the DSO has no SONAME and the
2129 file name comes from a -lXX parameter on the comment
2131 if (unlikely (has_l_name))
2133 /* The FNAME is the parameter the user specified on the
2134 command line. We prepend "lib" and append ".so". */
2135 size_t len = strlen (fileinfo->fname) + 7;
2138 newp = (char *) obstack_alloc (&ld_state.smem, len);
2139 strcpy (stpcpy (stpcpy (newp, "lib"), fileinfo->fname), ".so");
2141 fileinfo->soname = newp;
2145 else if (likely (elf_kind (fileinfo->elf) == ELF_K_AR))
2147 if (unlikely (ld_state.extract_rule == allextract))
2148 /* Which this option enabled we have to add all the object
2149 files in the archive. */
2150 res = add_whole_archive (fileinfo);
2151 else if (ld_state.file_type == relocatable_file_type)
2153 /* When generating a relocatable object we don't find files
2156 error (0, 0, gettext ("input file '%s' ignored"), fileinfo->fname);
2162 if (ld_state.group_start_requested
2163 && ld_state.group_start_archive == NULL)
2164 ld_state.group_start_archive = fileinfo;
2166 if (ld_state.archives == NULL)
2167 ld_state.archives = fileinfo;
2169 if (ld_state.tailarchives != NULL)
2170 ld_state.tailarchives->next = fileinfo;
2171 ld_state.tailarchives = fileinfo;
2173 /* Extract only the members from the archive which are
2174 currently referenced by unresolved symbols. */
2175 res = extract_from_archive (fileinfo);
2179 /* This should never happen, we know about no other types. */
2186 /* Process a given file. The first parameter is a file descriptor for
2187 the file which can be -1 to indicate the file has not yet been
2188 found. The second parameter describes the file to be opened, the
2189 last one is the state of the linker which among other information
2190 contain the paths we look at. */
2192 ld_generic_file_process (int fd, struct usedfiles *fileinfo,
2193 struct ld_state *statep, struct usedfiles **nextp)
2197 /* By default we go to the next file in the list. */
2198 *nextp = fileinfo->next;
2200 /* Set the flag to signal we are looking for a group start. */
2201 if (unlikely (fileinfo->group_start))
2203 ld_state.group_start_requested = true;
2204 fileinfo->group_start = false;
2207 /* If the file isn't open yet, open it now. */
2208 if (likely (fileinfo->status == not_opened))
2210 bool fd_passed = true;
2212 if (likely (fd == -1))
2214 /* Find the file ourselves. */
2215 int err = open_along_path (fileinfo);
2216 if (unlikely (err != 0))
2217 /* We allow libraries and DSOs to be named more than once.
2218 Don't report an error to the caller. */
2219 return err == EAGAIN ? 0 : err;
2226 /* Remember where we got the descriptor from. */
2227 fileinfo->fd_passed = fd_passed;
2229 /* We found the file. Now test whether it is a file type we can
2232 XXX Do we need to have the ability to start from a given
2233 position in the search path again to look for another file if
2234 the one found has not the right type? */
2235 res = open_elf (fileinfo, elf_begin (fileinfo->fd,
2236 is_dso_p (fileinfo->fd)
2238 : ELF_C_READ_MMAP_PRIVATE, NULL));
2239 if (unlikely (res != 0))
2243 /* Now that we have opened the file start processing it. */
2244 if (likely (fileinfo->status != closed))
2245 res = file_process2 (fileinfo);
2247 /* Determine which file to look at next. */
2248 if (unlikely (fileinfo->group_backref != NULL))
2250 /* We only go back if an archive other than the one we would go
2251 back to has been used in the last round. */
2252 if (ld_state.last_archive_used > fileinfo->group_backref->archive_seq)
2254 *nextp = fileinfo->group_backref;
2255 ld_state.last_archive_used = 0;
2259 /* If we come here this means that the archives we read so
2260 far are not needed anymore. We can free some of the data
2262 struct usedfiles *runp = ld_state.archives;
2266 /* We don't need the ELF descriptor anymore. Unless there
2267 are no files from the archive used this will not free
2268 the whole file but only some data structures. */
2269 elf_end (runp->elf);
2274 while (runp != fileinfo->next);
2276 /* Do not do this again. */
2277 ld_state.archives = NULL;
2279 /* Do not move on to the next archive. */
2280 *nextp = fileinfo->next = NULL;
2283 else if (unlikely (fileinfo->group_end))
2285 /* This is the end of a group. We possibly have to go back.
2286 Determine which file we would go back to and see whether it
2287 makes sense. If there has not been an archive we don't have
2289 if (ld_state.group_start_requested)
2291 if (ld_state.group_start_archive != ld_state.tailarchives)
2292 /* The loop includes more than one archive, add the pointer. */
2294 *nextp = ld_state.tailarchives->group_backref =
2295 ld_state.group_start_archive;
2296 ld_state.last_archive_used = 0;
2299 /* We might still have to go back to the beginning of the
2300 group if since the last archive other files have been
2301 added. But we go back exactly once. */
2302 if (ld_state.tailarchives != fileinfo)
2304 *nextp = ld_state.group_start_archive;
2305 ld_state.last_archive_used = 0;
2309 /* Clear the flags. */
2310 ld_state.group_start_requested = false;
2311 ld_state.group_start_archive = NULL;
2312 fileinfo->group_end = false;
2319 /* Library names passed to the linker as -lXX represent files named
2320 libXX.YY. The YY part can have different forms, depending on the
2321 platform. The generic set is .so and .a (in this order). */
2322 static const char **
2323 ld_generic_lib_extensions (struct ld_state *statep __attribute__ ((__unused__)))
2325 static const char *exts[] =
2334 /* Flag unresolved symbols. */
2336 ld_generic_flag_unresolved (struct ld_state *statep)
2340 if (ld_state.nunresolved_nonweak > 0)
2342 /* Go through the list and determine the unresolved symbols. */
2343 struct symbol *first;
2346 s = first = ld_state.unresolved->next;
2349 if (! s->defined && ! s->weak)
2351 /* Two special symbol we recognize: the symbol for the
2352 GOT and the dynamic section. */
2353 if (strcmp (s->name, "_GLOBAL_OFFSET_TABLE_") == 0
2354 || strcmp (s->name, "_DYNAMIC") == 0)
2356 /* We will have to fill in more information later. */
2357 ld_state.need_got = true;
2359 /* Remember that we found it. */
2360 if (s->name[1] == 'G')
2361 ld_state.got_symbol = s;
2363 ld_state.dyn_symbol = s;
2365 else if (ld_state.file_type != dso_file_type || !ld_state.nodefs)
2367 /* XXX The error message should get better. It should use
2368 the debugging information if present to tell where in the
2369 sources the undefined reference is. */
2370 error (0, 0, gettext ("undefined symbol `%s' in %s"),
2371 s->name, s->file->fname);
2377 /* We cannot decide here what to do with undefined
2378 references which will come from DSO since we do not know
2379 what kind of symbol we expect. Only when looking at the
2380 relocations we can see whether we need a PLT entry or
2381 only a GOT entry. */
2392 /* Close the given file. */
2394 ld_generic_file_close (struct usedfiles *fileinfo, struct ld_state *statep)
2396 /* Close the ELF descriptor. */
2397 elf_end (fileinfo->elf);
2399 /* If we have opened the file descriptor close it. But we might
2400 have done this already in which case FD is -1. */
2401 if (!fileinfo->fd_passed && fileinfo->fd != -1)
2402 close (fileinfo->fd);
2404 /* We allocated the resolved file name. */
2405 if (fileinfo->fname != fileinfo->rfname)
2406 free ((char *) fileinfo->rfname);
2413 new_generated_scn (enum scn_kind kind, const char *name, int type, int flags,
2414 int entsize, int align)
2416 struct scnhead *newp;
2418 newp = (struct scnhead *) obstack_calloc (&ld_state.smem,
2419 sizeof (struct scnhead));
2422 newp->nameent = ebl_strtabadd (ld_state.shstrtab, name, 0);
2424 newp->flags = flags;
2425 newp->entsize = entsize;
2426 newp->align = align;
2427 newp->grp_signature = NULL;
2430 /* All is well. Create now the data for the section and insert it
2431 into the section table. */
2432 ld_section_tab_insert (&ld_state.section_tab, elf_hash (name), newp);
2436 /* Create the sections which are generated by the linker and are not
2437 present in the input file. */
2439 ld_generic_generate_sections (struct ld_state *statep)
2441 /* The relocation section type. */
2442 int rel_type = REL_TYPE (&ld_state) == DT_REL ? SHT_REL : SHT_RELA;
2444 /* When requested, every output file will have a build ID section. */
2445 if (statep->build_id != NULL)
2446 new_generated_scn (scn_dot_note_gnu_build_id, ".note.gnu.build-id",
2447 SHT_NOTE, SHF_ALLOC, 0, 4);
2449 /* When building dynamically linked object we have to include a
2450 section containing a string describing the interpreter. This
2451 should be at the very beginning of the file together with the
2452 other information the ELF loader (kernel or wherever) has to look
2453 at. We put it as the first section in the file.
2455 We also have to create the dynamic segment which is a special
2456 section the dynamic linker locates through an entry in the
2458 if (dynamically_linked_p ())
2460 /* Use any versioning (defined or required)? */
2461 bool use_versioning = false;
2462 /* Use version requirements? */
2463 bool need_version = false;
2465 /* First the .interp section. */
2466 if (ld_state.interp != NULL || ld_state.file_type != dso_file_type)
2467 new_generated_scn (scn_dot_interp, ".interp", SHT_PROGBITS, SHF_ALLOC,
2470 /* Now the .dynamic section. */
2471 new_generated_scn (scn_dot_dynamic, ".dynamic", SHT_DYNAMIC,
2472 DYNAMIC_SECTION_FLAGS (&ld_state),
2473 xelf_fsize (ld_state.outelf, ELF_T_DYN, 1),
2474 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2476 /* We will need in any case the dynamic symbol table (even in
2477 the unlikely case that no symbol is exported or referenced
2479 ld_state.need_dynsym = true;
2480 new_generated_scn (scn_dot_dynsym, ".dynsym", SHT_DYNSYM, SHF_ALLOC,
2481 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1),
2482 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2483 /* It comes with a string table. */
2484 new_generated_scn (scn_dot_dynstr, ".dynstr", SHT_STRTAB, SHF_ALLOC,
2486 /* And a hashing table. */
2487 // XXX For Linux/Alpha we need other sizes unless they change...
2488 if (GENERATE_SYSV_HASH)
2489 new_generated_scn (scn_dot_hash, ".hash", SHT_HASH, SHF_ALLOC,
2490 sizeof (Elf32_Word), sizeof (Elf32_Word));
2491 if (GENERATE_GNU_HASH)
2492 new_generated_scn (scn_dot_gnu_hash, ".gnu.hash", SHT_GNU_HASH,
2493 SHF_ALLOC, sizeof (Elf32_Word),
2494 sizeof (Elf32_Word));
2496 /* Create the section associated with the PLT if necessary. */
2497 if (ld_state.nplt > 0)
2499 /* Create the .plt section. */
2500 /* XXX We might need a function which returns the section flags. */
2501 new_generated_scn (scn_dot_plt, ".plt", SHT_PROGBITS,
2502 SHF_ALLOC | SHF_EXECINSTR,
2503 /* XXX Is the size correct? */
2504 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2505 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2507 /* Create the relocation section for the .plt. This is always
2508 separate even if the other relocation sections are combined. */
2509 new_generated_scn (scn_dot_pltrel, ".rel.plt", rel_type, SHF_ALLOC,
2511 ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
2512 : xelf_fsize (ld_state.outelf, ELF_T_RELA, 1),
2513 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2515 /* XXX We might need a function which returns the section flags. */
2516 new_generated_scn (scn_dot_gotplt, ".got.plt", SHT_PROGBITS,
2517 SHF_ALLOC | SHF_WRITE,
2518 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2519 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2521 /* Mark all used DSOs as used. Determine whether any referenced
2522 object uses symbol versioning. */
2523 if (ld_state.from_dso != NULL)
2525 struct symbol *srunp = ld_state.from_dso;
2529 srunp->file->used = true;
2531 if (srunp->file->verdefdata != NULL)
2535 /* The input DSO uses versioning. */
2536 use_versioning = true;
2537 /* We reference versions. */
2538 need_version = true;
2540 if (xelf_getversym_copy (srunp->file->versymdata,
2541 srunp->symidx, versym) == NULL)
2542 assert (! "xelf_getversym failed");
2544 /* We cannot link explicitly with an older
2545 version of a symbol. */
2546 assert ((versym & 0x8000) == 0);
2547 /* We cannot reference local (index 0) or plain
2548 global (index 1) versions. */
2549 assert (versym > 1);
2551 /* Check whether we have already seen the
2552 version and if not add it to the referenced
2553 versions in the output file. */
2554 if (! srunp->file->verdefused[versym])
2556 srunp->file->verdefused[versym] = 1;
2558 if (++srunp->file->nverdefused == 1)
2559 /* Count the file if it is using versioning. */
2560 ++ld_state.nverdeffile;
2561 ++ld_state.nverdefused;
2565 while ((srunp = srunp->next) != ld_state.from_dso);
2568 /* Create the sections used to record version dependencies. */
2570 new_generated_scn (scn_dot_version_r, ".gnu.version_r",
2571 SHT_GNU_verneed, SHF_ALLOC, 0,
2572 xelf_fsize (ld_state.outelf, ELF_T_WORD, 1));
2575 /* Now count the used DSOs since this is what the user
2578 if (ld_state.ndsofiles > 0)
2580 struct usedfiles *frunp = ld_state.dsofiles;
2583 if (! frunp->as_needed || frunp->used)
2586 if (frunp->lazyload)
2587 /* We have to create another dynamic section
2588 entry for the DT_POSFLAG_1 entry.
2590 XXX Once more functionality than the lazyloading
2591 flag are suppported the test must be
2595 while ((frunp = frunp->next) != ld_state.dsofiles);
2599 new_generated_scn (scn_dot_version, ".gnu.version", SHT_GNU_versym,
2601 xelf_fsize (ld_state.outelf, ELF_T_HALF, 1),
2602 xelf_fsize (ld_state.outelf, ELF_T_HALF, 1));
2604 /* We need some entries all the time. */
2605 ld_state.ndynamic = (7 + (ld_state.runpath != NULL
2606 || ld_state.rpath != NULL)
2608 + (ld_state.init_symbol != NULL ? 1 : 0)
2609 + (ld_state.fini_symbol != NULL ? 1 : 0)
2610 + (use_versioning ? 1 : 0)
2611 + (need_version ? 2 : 0)
2612 + (ld_state.nplt > 0 ? 4 : 0)
2613 + (ld_state.relsize_total > 0 ? 3 : 0));
2616 /* When creating a relocatable file or when we are not stripping the
2617 output file we create a symbol table. */
2618 ld_state.need_symtab = (ld_state.file_type == relocatable_file_type
2619 || ld_state.strip == strip_none);
2621 /* Add the .got section if needed. */
2622 if (ld_state.need_got)
2623 /* XXX We might need a function which returns the section flags. */
2624 new_generated_scn (scn_dot_got, ".got", SHT_PROGBITS,
2625 SHF_ALLOC | SHF_WRITE,
2626 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2627 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2629 /* Add the .rel.dyn section. */
2630 if (ld_state.relsize_total > 0)
2631 new_generated_scn (scn_dot_dynrel, ".rel.dyn", rel_type, SHF_ALLOC,
2633 ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
2634 : xelf_fsize (ld_state.outelf, ELF_T_RELA, 1),
2635 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2639 /* Callback function registered with on_exit to make sure the temporary
2640 files gets removed if something goes wrong. */
2642 remove_tempfile (int status, void *arg)
2644 if (status != 0 && ld_state.tempfname != NULL)
2645 unlink (ld_state.tempfname);
2649 /* Create the output file. The file name is given or "a.out". We
2650 create as much of the ELF structure as possible. */
2652 ld_generic_open_outfile (struct ld_state *statep, int machine, int klass,
2655 /* We do not create the new file right away with the final name.
2656 This would destroy an existing file with this name before a
2657 replacement is finalized. We create instead a temporary file in
2658 the same directory. */
2659 if (ld_state.outfname == NULL)
2660 ld_state.outfname = "a.out";
2662 size_t outfname_len = strlen (ld_state.outfname);
2663 char *tempfname = (char *) obstack_alloc (&ld_state.smem,
2664 outfname_len + sizeof (".XXXXXX"));
2665 ld_state.tempfname = tempfname;
2671 strcpy (mempcpy (tempfname, ld_state.outfname, outfname_len), ".XXXXXX");
2673 /* The use of mktemp() here is fine. We do not want to use
2674 mkstemp() since then the umask isn't used. And the output
2675 file will have these permissions anyhow. Any intruder could
2676 change the file later if it would be possible now. */
2677 if (mktemp (tempfname) != NULL
2678 && (fd = open (tempfname, O_RDWR | O_EXCL | O_CREAT | O_NOFOLLOW,
2679 ld_state.file_type == relocatable_file_type
2680 ? DEFFILEMODE : ACCESSPERMS)) != -1)
2683 /* Failed this round. We keep trying a number of times. */
2685 error (EXIT_FAILURE, errno, gettext ("cannot create output file"));
2687 ld_state.outfd = fd;
2689 /* Make sure we remove the temporary file in case something goes
2691 on_exit (remove_tempfile, NULL);
2693 /* Create the ELF file data for the output file. */
2694 Elf *elf = ld_state.outelf = elf_begin (fd,
2696 ? ELF_C_WRITE : ELF_C_WRITE_MMAP,
2699 error (EXIT_FAILURE, 0,
2700 gettext ("cannot create ELF descriptor for output file: %s"),
2703 /* Create the basic data structures. */
2704 if (! xelf_newehdr (elf, klass))
2705 /* Couldn't create the ELF header. Very bad. */
2706 error (EXIT_FAILURE, 0,
2707 gettext ("could not create ELF header for output file: %s"),
2710 /* And get the current header so that we can modify it. */
2711 XElf_Ehdr_vardef (ehdr);
2712 xelf_getehdr (elf, ehdr);
2713 assert (ehdr != NULL);
2715 /* Set the machine type. */
2716 ehdr->e_machine = machine;
2718 /* Modify it according to the info we have here and now. */
2719 if (ld_state.file_type == executable_file_type)
2720 ehdr->e_type = ET_EXEC;
2721 else if (ld_state.file_type == dso_file_type)
2722 ehdr->e_type = ET_DYN;
2725 assert (ld_state.file_type == relocatable_file_type);
2726 ehdr->e_type = ET_REL;
2729 /* Set the ELF version. */
2730 ehdr->e_version = EV_CURRENT;
2732 /* Set the endianness. */
2733 ehdr->e_ident[EI_DATA] = data;
2735 /* Write the ELF header information back. */
2736 (void) xelf_update_ehdr (elf, ehdr);
2742 /* We compute the offsets of the various copied objects and the total
2743 size of the memory needed. */
2744 // XXX The method used here is simple: go from front to back and pack
2745 // the objects in this order. A more space efficient way would
2746 // actually trying to pack the objects as dense as possible. But this
2747 // is more expensive.
2749 compute_copy_reloc_offset (XElf_Shdr *shdr)
2751 struct symbol *runp = ld_state.from_dso;
2752 assert (runp != NULL);
2754 XElf_Off maxalign = 1;
2755 XElf_Off offset = 0;
2758 if (runp->need_copy)
2760 /* Determine alignment for the symbol. */
2761 // XXX The question is how? The symbol record itself does not
2762 // have the information. So we have to be conservative and
2763 // assume the alignment of the section the symbol is in.
2765 // XXX We can be more precise. Use the offset from the beginning
2766 // of the section and determine the largest power of two with
2768 XElf_Off symalign = MAX (SCNINFO_SHDR (runp->file->scninfo[runp->scndx].shdr).sh_addralign, 1);
2769 /* Keep track of the maximum alignment requirement. */
2770 maxalign = MAX (maxalign, symalign);
2772 /* Align current position. */
2773 offset = (offset + symalign - 1) & ~(symalign - 1);
2775 runp->merge.value = offset;
2777 offset += runp->size;
2779 while ((runp = runp->next) != ld_state.from_dso);
2781 shdr->sh_type = SHT_NOBITS;
2782 shdr->sh_size = offset;
2783 shdr->sh_addralign = maxalign;
2788 compute_common_symbol_offset (XElf_Shdr *shdr)
2790 struct symbol *runp = ld_state.common_syms;
2791 assert (runp != NULL);
2793 XElf_Off maxalign = 1;
2794 XElf_Off offset = 0;
2798 /* Determine alignment for the symbol. */
2799 XElf_Off symalign = runp->merge.value;
2801 /* Keep track of the maximum alignment requirement. */
2802 maxalign = MAX (maxalign, symalign);
2804 /* Align current position. */
2805 offset = (offset + symalign - 1) & ~(symalign - 1);
2807 runp->merge.value = offset;
2809 offset += runp->size;
2811 while ((runp = runp->next) != ld_state.common_syms);
2813 shdr->sh_type = SHT_NOBITS;
2814 shdr->sh_size = offset;
2815 shdr->sh_addralign = maxalign;
2820 sort_sections_generic (void)
2828 match_section (const char *osectname, struct filemask_section_name *sectmask,
2829 struct scnhead **scnhead, bool new_section, size_t segment_nr)
2831 struct scninfo *prevp;
2832 struct scninfo *runp;
2833 struct scninfo *notused;
2835 if (fnmatch (sectmask->section_name->name, (*scnhead)->name, 0) != 0)
2836 /* The section name does not match. */
2839 /* If this is a section generated by the linker it doesn't contain
2840 the regular information (i.e., input section data etc) and must
2841 be handle special. */
2842 if ((*scnhead)->kind != scn_normal)
2844 (*scnhead)->name = osectname;
2845 (*scnhead)->segment_nr = segment_nr;
2847 /* We have to count note section since they get their own
2848 program header entry. */
2849 if ((*scnhead)->type == SHT_NOTE)
2850 ++ld_state.nnotesections;
2852 ld_state.allsections[ld_state.nallsections++] = (*scnhead);
2856 /* Now we have to match the file names of the input files. Some of
2857 the sections here might not match. */
2858 runp = (*scnhead)->last->next;
2859 prevp = (*scnhead)->last;
2864 /* Base of the file name the section comes from. */
2865 const char *brfname = basename (runp->fileinfo->rfname);
2867 /* If the section isn't used, the name doesn't match the positive
2868 inclusion list, or the name does match the negative inclusion
2869 list, ignore the section. */
2871 || (sectmask->filemask != NULL
2872 && fnmatch (sectmask->filemask, brfname, 0) != 0)
2873 || (sectmask->excludemask != NULL
2874 && fnmatch (sectmask->excludemask, brfname, 0) == 0))
2876 /* This file does not match the file name masks. */
2877 if (notused == NULL)
2882 if (runp == notused)
2885 /* The section fulfills all requirements, add it to the output
2886 file with the correct section name etc. */
2889 struct scninfo *found = runp;
2891 /* Remove this input section data buffer from the list. */
2893 runp = prevp->next = runp->next;
2901 /* Create a new section for the output file if the 'new_section'
2902 flag says so. Otherwise append the buffer to the last
2903 section which we created in one of the last calls. */
2906 struct scnhead *newp;
2908 newp = (struct scnhead *) obstack_calloc (&ld_state.smem,
2910 newp->kind = scn_normal;
2911 newp->name = osectname;
2912 newp->type = SCNINFO_SHDR (found->shdr).sh_type;
2913 /* Executable or DSO do not have section groups. Drop that
2915 newp->flags = SCNINFO_SHDR (found->shdr).sh_flags & ~SHF_GROUP;
2916 newp->segment_nr = segment_nr;
2917 newp->last = found->next = found;
2919 newp->relsize = found->relsize;
2920 newp->entsize = SCNINFO_SHDR (found->shdr).sh_entsize;
2922 /* We have to count note section since they get their own
2923 program header entry. */
2924 if (newp->type == SHT_NOTE)
2925 ++ld_state.nnotesections;
2927 ld_state.allsections[ld_state.nallsections++] = newp;
2928 new_section = false;
2932 struct scnhead *queued;
2934 queued = ld_state.allsections[ld_state.nallsections - 1];
2936 found->next = queued->last->next;
2937 queued->last = queued->last->next = found;
2939 /* If the linker script forces us to add incompatible
2940 sections together do so. But reflect this in the
2941 type and flags of the resulting file. */
2942 if (queued->type != SCNINFO_SHDR (found->shdr).sh_type)
2943 /* XXX Any better choice? */
2944 queued->type = SHT_PROGBITS;
2945 if (queued->flags != SCNINFO_SHDR (found->shdr).sh_flags)
2946 /* Executable or DSO do not have section groups. Drop that
2948 queued->flags = ebl_sh_flags_combine (ld_state.ebl,
2950 SCNINFO_SHDR (found->shdr).sh_flags
2953 /* Accumulate the relocation section size. */
2954 queued->relsize += found->relsize;
2958 while (runp != NULL);
2965 sort_sections_lscript (void)
2967 struct scnhead *temp[ld_state.nallsections];
2969 /* Make a copy of the section head pointer array. */
2970 memcpy (temp, ld_state.allsections,
2971 ld_state.nallsections * sizeof (temp[0]));
2972 size_t nallsections = ld_state.nallsections;
2974 /* Convert the output segment list in a single-linked list. */
2975 struct output_segment *segment = ld_state.output_segments->next;
2976 ld_state.output_segments->next = NULL;
2977 ld_state.output_segments = segment;
2979 /* Put the sections in the correct order in the array in the state
2980 structure. This might involve merging of sections and also
2981 renaming the containing section in the output file. */
2982 ld_state.nallsections = 0;
2984 size_t last_writable = ~0ul;
2985 for (segment_nr = 0; segment != NULL; segment = segment->next, ++segment_nr)
2987 struct output_rule *orule;
2989 for (orule = segment->output_rules; orule != NULL; orule = orule->next)
2990 if (orule->tag == output_section)
2992 struct input_rule *irule;
2993 bool new_section = true;
2995 for (irule = orule->val.section.input; irule != NULL;
2996 irule = irule->next)
2997 if (irule->tag == input_section)
3001 for (cnt = 0; cnt < nallsections; ++cnt)
3002 if (temp[cnt] != NULL)
3004 match_section (orule->val.section.name,
3005 irule->val.section, &temp[cnt],
3006 new_section, segment_nr);
3010 if ((segment->mode & PF_W) != 0)
3011 last_writable = ld_state.nallsections - 1;
3014 /* In case we have to create copy relocations or we have common
3015 symbols, find the last writable segment and add one more data
3016 block. It will be a NOBITS block and take up no disk space.
3017 This is why it is important to get the last block. */
3018 if (ld_state.ncopy > 0 || ld_state.common_syms != NULL)
3020 if (last_writable == ~0ul)
3021 error (EXIT_FAILURE, 0, "no writable segment");
3023 if (ld_state.allsections[last_writable]->type != SHT_NOBITS)
3025 /* Make room in the ALLSECTIONS array for a new section.
3026 There is guaranteed room in the array. We add the new
3027 entry after the last writable section. */
3029 memmove (&ld_state.allsections[last_writable + 1],
3030 &ld_state.allsections[last_writable],
3031 (ld_state.nallsections - last_writable)
3032 * sizeof (ld_state.allsections[0]));
3034 ld_state.allsections[last_writable] = (struct scnhead *)
3035 obstack_calloc (&ld_state.smem, sizeof (struct scnhead));
3037 /* Name for the new section. */
3038 ld_state.allsections[last_writable]->name = ".bss";
3040 ld_state.allsections[last_writable]->type = SHT_NOBITS;
3041 /* Same segment as the last writable section. */
3042 ld_state.allsections[last_writable]->segment_nr
3043 = ld_state.allsections[last_writable - 1]->segment_nr;
3047 /* Create common symbol data block. */
3048 if (ld_state.ncopy > 0)
3051 struct scninfo *si = (struct scninfo *)
3052 obstack_calloc (&ld_state.smem, sizeof (*si) + sizeof (XElf_Shdr));
3053 si->shdr = (XElf_Shdr *) (si + 1);
3055 struct scninfo *si = (struct scninfo *) obstack_calloc (&ld_state.smem,
3059 /* Get the information regarding the symbols with copy relocations. */
3060 compute_copy_reloc_offset (&SCNINFO_SHDR (si->shdr));
3062 /* This section is needed. */
3064 /* Remember for later the section data structure. */
3065 ld_state.copy_section = si;
3067 if (likely (ld_state.allsections[last_writable]->last != NULL))
3069 si->next = ld_state.allsections[last_writable]->last->next;
3070 ld_state.allsections[last_writable]->last->next = si;
3071 ld_state.allsections[last_writable]->last = si;
3074 ld_state.allsections[last_writable]->last = si->next = si;
3077 /* Create common symbol data block. */
3078 if (ld_state.common_syms != NULL)
3081 struct scninfo *si = (struct scninfo *)
3082 obstack_calloc (&ld_state.smem, sizeof (*si) + sizeof (XElf_Shdr));
3083 si->shdr = (XElf_Shdr *) (si + 1);
3085 struct scninfo *si = (struct scninfo *) obstack_calloc (&ld_state.smem,
3089 /* Get the information regarding the symbols with copy relocations. */
3090 compute_common_symbol_offset (&SCNINFO_SHDR (si->shdr));
3092 /* This section is needed. */
3094 /* Remember for later the section data structure. */
3095 ld_state.common_section = si;
3097 if (likely (ld_state.allsections[last_writable]->last != NULL))
3099 si->next = ld_state.allsections[last_writable]->last->next;
3100 ld_state.allsections[last_writable]->last->next = si;
3101 ld_state.allsections[last_writable]->last = si;
3104 ld_state.allsections[last_writable]->last = si->next = si;
3109 /* Create the output sections now. This requires knowledge about all
3110 the sections we will need. It may be necessary to sort sections in
3111 the order they are supposed to appear in the executable. The
3112 sorting use many different kinds of information to optimize the
3113 resulting binary. Important is to respect segment boundaries and
3114 the needed alignment. The mode of the segments will be determined
3115 afterwards automatically by the output routines.
3117 The generic sorting routines work in one of two possible ways:
3119 - if a linker script specifies the sections to be used in the
3120 output and assigns them to a segment this information is used;
3122 - otherwise the linker will order the sections based on permissions
3123 and some special knowledge about section names.*/
3125 ld_generic_create_sections (struct ld_state *statep)
3127 struct scngroup *groups;
3130 /* For relocatable object we don't have to bother sorting the
3131 sections and we do want to preserve the relocation sections as
3132 they appear in the input files. */
3133 if (ld_state.file_type != relocatable_file_type)
3135 /* Collect all the relocation sections. They are handled
3137 struct scninfo *list = NULL;
3138 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
3139 if ((ld_state.allsections[cnt]->type == SHT_REL
3140 || ld_state.allsections[cnt]->type == SHT_RELA)
3141 /* The generated relocation sections are not of any
3143 && ld_state.allsections[cnt]->last != NULL)
3146 list = ld_state.allsections[cnt]->last;
3149 /* Merge the sections list. */
3150 struct scninfo *first = list->next;
3151 list->next = ld_state.allsections[cnt]->last->next;
3152 ld_state.allsections[cnt]->last->next = first;
3153 list = ld_state.allsections[cnt]->last;
3156 /* Remove the entry from the section list. */
3157 ld_state.allsections[cnt] = NULL;
3159 ld_state.rellist = list;
3161 if (ld_state.output_segments == NULL)
3162 /* Sort using builtin rules. */
3163 sort_sections_generic ();
3165 sort_sections_lscript ();
3168 /* Now iterate over the input sections and create the sections in the
3169 order they are required in the output file. */
3170 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
3172 struct scnhead *head = ld_state.allsections[cnt];
3174 XElf_Shdr_vardef (shdr);
3176 /* Don't handle unused sections. */
3180 /* We first have to create the section group if necessary.
3181 Section group sections must come (in section index order)
3182 before any of the section contained. This all is necessary
3183 only for relocatable object as other object types are not
3184 allowed to contain section groups. */
3185 if (ld_state.file_type == relocatable_file_type
3186 && unlikely (head->flags & SHF_GROUP))
3188 /* There is at least one section which is contained in a
3189 section group in the input file. This means we must
3190 create a section group here as well. The only problem is
3191 that not all input files have to have to same kind of
3192 partitioning of the sections. I.e., sections A and B in
3193 one input file and sections B and C in another input file
3194 can be in one group. That will result in a group
3195 containing the sections A, B, and C in the output
3197 struct scninfo *runp;
3198 Elf32_Word here_groupidx = 0;
3199 struct scngroup *here_group;
3200 struct member *newp;
3202 /* First check whether any section is already in a group.
3203 In this case we have to add this output section, too. */
3207 assert (runp->grpid != 0);
3209 here_groupidx = runp->fileinfo->scninfo[runp->grpid].outscnndx;
3210 if (here_groupidx != 0)
3213 while ((runp = runp->next) != head->last);
3215 if (here_groupidx == 0)
3217 /* We need a new section group section. */
3218 scn = elf_newscn (ld_state.outelf);
3219 xelf_getshdr (scn, shdr);
3221 error (EXIT_FAILURE, 0,
3222 gettext ("cannot create section for output file: %s"),
3225 here_group = (struct scngroup *) xmalloc (sizeof (*here_group));
3226 here_group->outscnidx = here_groupidx = elf_ndxscn (scn);
3227 here_group->nscns = 0;
3228 here_group->member = NULL;
3229 here_group->next = ld_state.groups;
3230 /* Pick a name for the section. To keep it meaningful
3231 we use a name used in the input files. If the
3232 section group in the output file should contain
3233 section which were in section groups of different
3234 names in the input files this is the users
3237 = ebl_strtabadd (ld_state.shstrtab,
3238 elf_strptr (runp->fileinfo->elf,
3239 runp->fileinfo->shstrndx,
3240 SCNINFO_SHDR (runp->shdr).sh_name),
3242 /* Signature symbol. */
3244 = runp->fileinfo->scninfo[runp->grpid].symbols;
3246 ld_state.groups = here_group;
3250 /* Search for the group with this index. */
3251 here_group = ld_state.groups;
3252 while (here_group->outscnidx != here_groupidx)
3253 here_group = here_group->next;
3256 /* Add the new output section. */
3257 newp = (struct member *) alloca (sizeof (*newp));
3262 CSNGL_LIST_ADD_REAR (here_group->member, newp);
3263 ++here_group->nscns;
3265 /* Store the section group index in all input files. */
3269 assert (runp->grpid != 0);
3271 if (runp->fileinfo->scninfo[runp->grpid].outscnndx == 0)
3272 runp->fileinfo->scninfo[runp->grpid].outscnndx = here_groupidx;
3274 assert (runp->fileinfo->scninfo[runp->grpid].outscnndx
3277 while ((runp = runp->next) != head->last);
3280 /* We'll use this section so get it's name in the section header
3282 if (head->kind == scn_normal)
3283 head->nameent = ebl_strtabadd (ld_state.shstrtab, head->name, 0);
3285 /* Create a new section in the output file and add all data
3286 from all the sections we read. */
3287 scn = elf_newscn (ld_state.outelf);
3288 head->scnidx = elf_ndxscn (scn);
3289 xelf_getshdr (scn, shdr);
3291 error (EXIT_FAILURE, 0,
3292 gettext ("cannot create section for output file: %s"),
3295 assert (head->type != SHT_NULL);
3296 assert (head->type != SHT_SYMTAB);
3297 assert (head->type != SHT_DYNSYM || head->kind != scn_normal);
3298 assert (head->type != SHT_STRTAB || head->kind != scn_normal);
3299 assert (head->type != SHT_GROUP);
3300 shdr->sh_type = head->type;
3301 shdr->sh_flags = head->flags;
3302 shdr->sh_addralign = head->align;
3303 shdr->sh_entsize = head->entsize;
3304 assert (shdr->sh_entsize != 0 || (shdr->sh_flags & SHF_MERGE) == 0);
3305 (void) xelf_update_shdr (scn, shdr);
3307 /* We have to know the section index of the dynamic symbol table
3309 if (head->kind == scn_dot_dynsym)
3310 ld_state.dynsymscnidx = elf_ndxscn (scn);
3313 /* Actually create the section group sections. */
3314 groups = ld_state.groups;
3315 while (groups != NULL)
3319 Elf32_Word *grpdata;
3320 struct member *runp;
3322 scn = elf_getscn (ld_state.outelf, groups->outscnidx);
3323 assert (scn != NULL);
3325 data = elf_newdata (scn);
3327 error (EXIT_FAILURE, 0,
3328 gettext ("cannot create section for output file: %s"),
3331 data->d_size = (groups->nscns + 1) * sizeof (Elf32_Word);
3332 data->d_buf = grpdata = (Elf32_Word *) xmalloc (data->d_size);
3333 data->d_type = ELF_T_WORD;
3334 data->d_version = EV_CURRENT;
3336 /* XXX What better to use? */
3337 data->d_align = sizeof (Elf32_Word);
3339 /* The first word in the section is the flag word. */
3340 /* XXX Set COMDATA flag is necessary. */
3343 runp = groups->member->next;
3346 /* Fill in the index of the section. */
3347 grpdata[cnt++] = runp->scn->scnidx;
3348 while ((runp = runp->next) != groups->member->next);
3350 groups = groups->next;
3356 reduce_symbol_p (XElf_Sym *sym, struct Ebl_Strent *strent)
3359 const char *version;
3360 struct id_list search;
3361 struct id_list *verp;
3362 bool result = ld_state.default_bind_local;
3364 if (XELF_ST_BIND (sym->st_info) == STB_LOCAL || sym->st_shndx == SHN_UNDEF)
3365 /* We don't have to do anything to local symbols here. */
3366 /* XXX Any section value in [SHN_LORESERVER,SHN_XINDEX) need
3367 special treatment? */
3370 /* XXX Handle other symbol bindings. */
3371 assert (XELF_ST_BIND (sym->st_info) == STB_GLOBAL
3372 || XELF_ST_BIND (sym->st_info) == STB_WEAK);
3374 str = ebl_string (strent);
3375 version = strchr (str, VER_CHR);
3376 if (version != NULL)
3378 search.id = strndupa (str, version - str);
3379 if (*++version == VER_CHR)
3380 /* Skip the second '@' signaling a default definition. */
3389 verp = ld_version_str_tab_find (&ld_state.version_str_tab,
3390 elf_hash (search.id), &search);
3391 while (verp != NULL)
3393 /* We have this symbol in the version hash table. Now match the
3395 if (strcmp (verp->u.s.versionname, version) == 0)
3397 return verp->u.s.local;
3402 /* XXX Add test for wildcard version symbols. */
3409 eval_expression (struct expression *expr, XElf_Addr addr)
3411 XElf_Addr val = ~((XElf_Addr) 0);
3416 val = expr->val.num;
3419 case exp_sizeof_headers:
3421 /* The 'elf_update' call determine the offset of the first
3422 section. The the size of the header. */
3423 XElf_Shdr_vardef (shdr);
3425 xelf_getshdr (elf_getscn (ld_state.outelf, 1), shdr);
3426 assert (shdr != NULL);
3428 val = shdr->sh_offset;
3433 val = ld_state.pagesize;
3437 /* We are here computing only address expressions. It seems not
3438 to be necessary to handle any variable but ".". Let's avoid
3439 the complication. If it turns up to be needed we can add
3441 if (strcmp (expr->val.str, ".") != 0)
3442 error (EXIT_FAILURE, 0, gettext ("\
3443 address computation expression contains variable '%s'"),
3450 val = (eval_expression (expr->val.binary.left, addr)
3451 * eval_expression (expr->val.binary.right, addr));
3455 val = (eval_expression (expr->val.binary.left, addr)
3456 / eval_expression (expr->val.binary.right, addr));
3460 val = (eval_expression (expr->val.binary.left, addr)
3461 % eval_expression (expr->val.binary.right, addr));
3465 val = (eval_expression (expr->val.binary.left, addr)
3466 + eval_expression (expr->val.binary.right, addr));
3470 val = (eval_expression (expr->val.binary.left, addr)
3471 - eval_expression (expr->val.binary.right, addr));
3475 val = (eval_expression (expr->val.binary.left, addr)
3476 & eval_expression (expr->val.binary.right, addr));
3480 val = (eval_expression (expr->val.binary.left, addr)
3481 | eval_expression (expr->val.binary.right, addr));
3485 val = eval_expression (expr->val.child, addr);
3486 if ((val & (val - 1)) != 0)
3487 error (EXIT_FAILURE, 0, gettext ("argument '%" PRIuMAX "' of ALIGN in address computation expression is no power of two"),
3489 val = (addr + val - 1) & ~(val - 1);
3497 /* Find a good as possible size for the hash table so that all the
3498 non-zero entries in HASHCODES don't collide too much and the table
3499 isn't too large. There is no exact formular for this so we use a
3500 heuristic. Depending on the optimization level the search is
3501 longer or shorter. */
3503 optimal_bucket_size (Elf32_Word *hashcodes, size_t maxcnt, int optlevel)
3516 /* When we are not optimizing we run only very few tests. */
3520 maxsize = maxcnt + 10000 / maxcnt;
3524 /* Does not make much sense to start with a smaller table than
3525 one which has at least four collisions. */
3526 minsize = MAX (1, maxcnt / 4);
3527 /* We look for a best fit in the range of up to eigth times the
3528 number of elements. */
3529 maxsize = 2 * maxcnt + (6 * MIN (optlevel, 100) * maxcnt) / 100;
3532 bestcost = UINT_MAX;
3534 /* Array for counting the collisions and chain lengths. */
3535 counts = (uint32_t *) xmalloc ((maxcnt + 1 + maxsize) * sizeof (uint32_t));
3536 lengths = &counts[maxcnt + 1];
3538 for (size = minsize; size <= maxsize; ++size)
3547 memset (lengths, '\0', size * sizeof (uint32_t));
3548 memset (counts, '\0', (maxcnt + 1) * sizeof (uint32_t));
3550 /* Determine how often each hash bucket is used. */
3551 assert (hashcodes[0] == 0);
3552 for (inner = 1; inner < maxcnt; ++inner)
3553 ++lengths[hashcodes[inner] % size];
3555 /* Determine the lengths. */
3557 for (inner = 0; inner < size; ++inner)
3559 ++counts[lengths[inner]];
3561 if (lengths[inner] > maxlength)
3562 maxlength = lengths[inner];
3565 /* Determine successful lookup length. */
3568 for (inner = 0; inner <= maxlength; ++inner)
3571 success += counts[inner] * acc;
3574 /* We can compute two factors now: the average length of a
3575 positive search and the average length of a negative search.
3576 We count the number of comparisons which have to look at the
3577 names themselves. Recognizing that the chain ended is not
3578 accounted for since it's almost for free.
3580 Which lookup is more important depends on the kind of DSO.
3581 If it is a system DSO like libc it is expected that most
3582 lookups succeed. Otherwise most lookups fail. */
3583 if (ld_state.is_system_library)
3584 factor = (1.0 * (double) success / (double) maxcnt
3585 + 0.3 * (double) maxcnt / (double) size);
3587 factor = (0.3 * (double) success / (double) maxcnt
3588 + 1.0 * (double) maxcnt / (double) size);
3590 /* Combine the lookup cost factor. The 1/16th addend adds
3591 penalties for too large table sizes. */
3592 cost = (2 + maxcnt + size) * (factor + 1.0 / 16.0);
3595 printf ("maxcnt = %d, size = %d, cost = %Ld, success = %g, fail = %g, factor = %g\n",
3596 maxcnt, size, cost, (double) success / (double) maxcnt, (double) maxcnt / (double) size, factor);
3599 /* Compare with current best results. */
3600 if (cost < bestcost)
3614 optimal_gnu_hash_size (Elf32_Word *hashcodes, size_t maxcnt, int optlevel,
3615 size_t *bitmask_nwords, size_t *shift, size_t *nbuckets)
3617 // XXX Implement something real
3618 *bitmask_nwords = 256;
3620 *nbuckets = 3 * maxcnt / 2;
3625 find_entry_point (void)
3629 if (ld_state.entry != NULL)
3631 struct symbol search = { .name = ld_state.entry };
3632 struct symbol *syment;
3634 syment = ld_symbol_tab_find (&ld_state.symbol_tab,
3635 elf_hash (ld_state.entry), &search);
3636 if (syment != NULL && syment->defined)
3638 /* We found the symbol. */
3639 Elf_Data *data = elf_getdata (elf_getscn (ld_state.outelf,
3640 ld_state.symscnidx), NULL);
3642 XElf_Sym_vardef (sym);
3646 xelf_getsym (data, ld_state.dblindirect[syment->outsymidx], sym);
3648 if (sym == NULL && ld_state.need_dynsym && syment->outdynsymidx != 0)
3650 /* Use the dynamic symbol table if available. */
3651 data = elf_getdata (elf_getscn (ld_state.outelf,
3652 ld_state.dynsymscnidx), NULL);
3656 xelf_getsym (data, syment->outdynsymidx, sym);
3660 return sym->st_value;
3662 /* XXX What to do if the output has no non-dynamic symbol
3663 table and the dynamic symbol table does not contain the
3665 assert (ld_state.need_symtab);
3666 assert (ld_state.symscnidx != 0);
3670 /* We couldn't find the symbol or none was given. Use the first
3671 address of the ".text" section then. */
3676 /* In DSOs this is no fatal error. They usually have no entry
3677 points. In this case we set the entry point to zero, which makes
3678 sure it will always fail. */
3679 if (ld_state.file_type == executable_file_type)
3681 if (ld_state.entry != NULL)
3682 error (0, 0, gettext ("\
3683 cannot find entry symbol '%s': defaulting to %#0*" PRIx64),
3685 xelf_getclass (ld_state.outelf) == ELFCLASS32 ? 10 : 18,
3688 error (0, 0, gettext ("\
3689 no entry symbol specified: defaulting to %#0*" PRIx64),
3690 xelf_getclass (ld_state.outelf) == ELFCLASS32 ? 10 : 18,
3699 fillin_special_symbol (struct symbol *symst, size_t scnidx, size_t nsym,
3700 Elf_Data *symdata, struct Ebl_Strtab *strtab)
3702 assert (ld_state.file_type != relocatable_file_type);
3704 XElf_Sym_vardef (sym);
3705 xelf_getsym_ptr (symdata, nsym, sym);
3707 /* The name offset will be filled in later. */
3709 /* Traditionally: globally visible. */
3710 sym->st_info = XELF_ST_INFO (symst->local ? STB_LOCAL : STB_GLOBAL,
3712 sym->st_other = symst->hidden ? STV_HIDDEN : STV_DEFAULT;
3713 /* Reference to the GOT or dynamic section. Since the GOT and
3714 dynamic section are only created for executables and DSOs it
3715 cannot be that the section index is too large. */
3716 assert (scnidx != 0);
3717 assert (scnidx < SHN_LORESERVE || scnidx == SHN_ABS);
3718 sym->st_shndx = scnidx;
3719 /* We want the beginning of the section. */
3724 /* Determine the size of the section. */
3725 if (scnidx != SHN_ABS)
3727 Elf_Data *data = elf_getdata (elf_getscn (ld_state.outelf, scnidx),
3729 assert (data != NULL);
3730 sym->st_size = data->d_size;
3731 /* Make sure there is no second data block. */
3732 assert (elf_getdata (elf_getscn (ld_state.outelf, scnidx), data)
3736 /* Insert symbol into the symbol table. Note that we do not have to
3737 use xelf_update_symshdx. */
3738 (void) xelf_update_sym (symdata, nsym, sym);
3740 /* Cross-references. */
3741 ndxtosym[nsym] = symst;
3742 symst->outsymidx = nsym;
3744 /* Add the name to the string table. */
3745 symstrent[nsym] = ebl_strtabadd (strtab, symst->name, 0);
3750 new_dynamic_entry (Elf_Data *data, int idx, XElf_Sxword tag, XElf_Addr val)
3752 XElf_Dyn_vardef (dyn);
3753 xelf_getdyn_ptr (data, idx, dyn);
3755 dyn->d_un.d_ptr = val;
3756 (void) xelf_update_dyn (data, idx, dyn);
3761 allocate_version_names (struct usedfiles *runp, struct Ebl_Strtab *dynstrtab)
3763 /* If this DSO has no versions skip it. */
3764 if (runp->status != opened || runp->verdefdata == NULL)
3767 /* Add the object name. */
3771 XElf_Verdef_vardef (def);
3772 XElf_Verdaux_vardef (aux);
3774 /* Get data at the next offset. */
3775 xelf_getverdef (runp->verdefdata, offset, def);
3776 assert (def != NULL);
3777 xelf_getverdaux (runp->verdefdata, offset + def->vd_aux, aux);
3778 assert (aux != NULL);
3780 assert (def->vd_ndx <= runp->nverdef);
3781 if (def->vd_ndx == 1 || runp->verdefused[def->vd_ndx] != 0)
3783 runp->verdefent[def->vd_ndx]
3784 = ebl_strtabadd (dynstrtab, elf_strptr (runp->elf,
3788 if (def->vd_ndx > 1)
3789 runp->verdefused[def->vd_ndx] = ld_state.nextveridx++;
3792 if (def->vd_next == 0)
3793 /* That were all versions. */
3796 offset += def->vd_next;
3802 create_verneed_data (XElf_Off offset, Elf_Data *verneeddata,
3803 struct usedfiles *runp, int *ntotal)
3805 size_t verneed_size = xelf_fsize (ld_state.outelf, ELF_T_VNEED, 1);
3806 size_t vernaux_size = xelf_fsize (ld_state.outelf, ELF_T_VNAUX, 1);
3808 bool filled = false;
3809 GElf_Verneed verneed;
3810 GElf_Vernaux vernaux;
3814 /* If this DSO has no versions skip it. */
3815 if (runp->nverdefused == 0)
3818 /* We fill in the Verneed record last. Remember the offset. */
3819 need_offset = offset;
3820 offset += verneed_size;
3822 for (cnt = 2; cnt <= runp->nverdef; ++cnt)
3823 if (runp->verdefused[cnt] != 0)
3825 assert (runp->verdefent[cnt] != NULL);
3829 vernaux.vna_next = vernaux_size;
3830 (void) gelf_update_vernaux (verneeddata, offset, &vernaux);
3831 offset += vernaux_size;
3834 vernaux.vna_hash = elf_hash (ebl_string (runp->verdefent[cnt]));
3835 vernaux.vna_flags = 0;
3836 vernaux.vna_other = runp->verdefused[cnt];
3837 vernaux.vna_name = ebl_strtaboffset (runp->verdefent[cnt]);
3843 vernaux.vna_next = 0;
3844 (void) gelf_update_vernaux (verneeddata, offset, &vernaux);
3845 offset += vernaux_size;
3847 verneed.vn_version = VER_NEED_CURRENT;
3848 verneed.vn_cnt = ndef;
3849 verneed.vn_file = ebl_strtaboffset (runp->verdefent[1]);
3850 /* The first auxiliary entry is always found directly
3851 after the verneed entry. */
3852 verneed.vn_aux = verneed_size;
3853 verneed.vn_next = --*ntotal > 0 ? offset - need_offset : 0;
3854 (void) gelf_update_verneed (verneeddata, need_offset, &verneed);
3860 /* Callback for qsort to sort dynamic string table. */
3861 static Elf32_Word *global_hashcodes;
3862 static size_t global_nbuckets;
3864 sortfct_hashval (const void *p1, const void *p2)
3866 size_t idx1 = *(size_t *) p1;
3867 size_t idx2 = *(size_t *) p2;
3869 int def1 = ndxtosym[idx1]->defined && !ndxtosym[idx1]->in_dso;
3870 int def2 = ndxtosym[idx2]->defined && !ndxtosym[idx2]->in_dso;
3879 Elf32_Word hval1 = (global_hashcodes[ndxtosym[idx1]->outdynsymidx]
3881 Elf32_Word hval2 = (global_hashcodes[ndxtosym[idx2]->outdynsymidx]
3892 /* Sort the dynamic symbol table. The GNU hash table lookup assumes
3893 that all symbols with the same hash value module the bucket table
3894 size follow one another. This avoids the extra hash chain table.
3895 There is no need (and no way) to perform this operation if we do
3896 not use the new hash table format. */
3898 create_gnu_hash (size_t nsym_local, size_t nsym, size_t nsym_dyn,
3899 Elf32_Word *gnuhashcodes)
3901 size_t gnu_bitmask_nwords = 0;
3902 size_t gnu_shift = 0;
3903 size_t gnu_nbuckets = 0;
3904 Elf32_Word *gnu_bitmask = NULL;
3905 Elf32_Word *gnu_buckets = NULL;
3906 Elf32_Word *gnu_chain = NULL;
3907 XElf_Shdr_vardef (shdr);
3909 /* Determine the "optimal" bucket size. */
3910 optimal_gnu_hash_size (gnuhashcodes, nsym_dyn, ld_state.optlevel,
3911 &gnu_bitmask_nwords, &gnu_shift, &gnu_nbuckets);
3913 /* Create the .gnu.hash section data structures. */
3914 Elf_Scn *hashscn = elf_getscn (ld_state.outelf, ld_state.gnuhashscnidx);
3915 xelf_getshdr (hashscn, shdr);
3916 Elf_Data *hashdata = elf_newdata (hashscn);
3917 if (shdr == NULL || hashdata == NULL)
3918 error (EXIT_FAILURE, 0, gettext ("\
3919 cannot create GNU hash table section for output file: %s"),
3922 shdr->sh_link = ld_state.dynsymscnidx;
3923 (void) xelf_update_shdr (hashscn, shdr);
3925 hashdata->d_size = (xelf_fsize (ld_state.outelf, ELF_T_ADDR,
3927 + (4 + gnu_nbuckets + nsym_dyn) * sizeof (Elf32_Word));
3928 hashdata->d_buf = xcalloc (1, hashdata->d_size);
3929 hashdata->d_align = sizeof (Elf32_Word);
3930 hashdata->d_type = ELF_T_WORD;
3931 hashdata->d_off = 0;
3933 ((Elf32_Word *) hashdata->d_buf)[0] = gnu_nbuckets;
3934 ((Elf32_Word *) hashdata->d_buf)[2] = gnu_bitmask_nwords;
3935 ((Elf32_Word *) hashdata->d_buf)[3] = gnu_shift;
3936 gnu_bitmask = &((Elf32_Word *) hashdata->d_buf)[4];
3937 gnu_buckets = &gnu_bitmask[xelf_fsize (ld_state.outelf, ELF_T_ADDR,
3939 / sizeof (*gnu_buckets)];
3940 gnu_chain = &gnu_buckets[gnu_nbuckets];
3942 void *endp = &gnu_chain[nsym_dyn];
3944 assert (endp == (void *) ((char *) hashdata->d_buf + hashdata->d_size));
3947 size_t *remap = xmalloc (nsym_dyn * sizeof (size_t));
3949 size_t nsym_dyn_cnt = 1;
3951 for (size_t cnt = nsym_local; cnt < nsym; ++cnt)
3952 if (symstrent[cnt] != NULL)
3954 assert (ndxtosym[cnt]->outdynsymidx > 0);
3955 assert (ndxtosym[cnt]->outdynsymidx < nsym_dyn);
3956 remap[ndxtosym[cnt]->outdynsymidx] = cnt;
3961 assert (nsym_dyn_cnt == nsym_dyn);
3963 // XXX Until we can rely on qsort_r use global variables.
3964 global_hashcodes = gnuhashcodes;
3965 global_nbuckets = gnu_nbuckets;
3966 qsort (remap + 1, nsym_dyn - 1, sizeof (size_t), sortfct_hashval);
3968 bool bm32 = (xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1)
3969 == sizeof (Elf32_Word));
3971 size_t first_defined = 0;
3972 Elf64_Word bitmask_idxbits = gnu_bitmask_nwords - 1;
3973 Elf32_Word last_bucket = 0;
3974 for (size_t cnt = 1; cnt < nsym_dyn; ++cnt)
3976 if (first_defined == 0)
3978 if (! ndxtosym[remap[cnt]]->defined
3979 || ndxtosym[remap[cnt]]->in_dso)
3982 ((Elf32_Word *) hashdata->d_buf)[1] = first_defined = cnt;
3985 Elf32_Word hval = gnuhashcodes[ndxtosym[remap[cnt]]->outdynsymidx];
3989 Elf32_Word *bsw = &gnu_bitmask[(hval / 32) & bitmask_idxbits];
3990 assert ((void *) gnu_bitmask <= (void *) bsw);
3991 assert ((void *) bsw < (void *) gnu_buckets);
3992 *bsw |= 1 << (hval & 31);
3993 *bsw |= 1 << ((hval >> gnu_shift) & 31);
3997 Elf64_Word *bsw = &((Elf64_Word *) gnu_bitmask)[(hval / 64)
3999 assert ((void *) gnu_bitmask <= (void *) bsw);
4000 assert ((void *) bsw < (void *) gnu_buckets);
4001 *bsw |= 1 << (hval & 63);
4002 *bsw |= 1 << ((hval >> gnu_shift) & 63);
4005 size_t this_bucket = hval % gnu_nbuckets;
4006 if (cnt == first_defined || this_bucket != last_bucket)
4008 if (cnt != first_defined)
4010 /* Terminate the previous chain. */
4011 assert ((void *) &gnu_chain[cnt - first_defined - 1] < endp);
4012 gnu_chain[cnt - first_defined - 1] |= 1;
4015 assert (this_bucket < gnu_nbuckets);
4016 gnu_buckets[this_bucket] = cnt;
4017 last_bucket = this_bucket;
4020 assert (cnt >= first_defined);
4021 assert (cnt - first_defined < nsym_dyn);
4022 gnu_chain[cnt - first_defined] = hval & ~1u;
4025 ndxtosym[remap[cnt]]->outdynsymidx = cnt;
4028 /* Terminate the last chain. */
4029 if (first_defined != 0)
4031 assert (nsym_dyn > first_defined);
4032 assert (nsym_dyn - first_defined - 1 < nsym_dyn);
4033 gnu_chain[nsym_dyn - first_defined - 1] |= 1;
4035 hashdata->d_size -= first_defined * sizeof (Elf32_Word);
4038 /* We do not need any hash table. */
4046 /* Create the SysV-style hash table. */
4048 create_hash (size_t nsym_local, size_t nsym, size_t nsym_dyn,
4049 Elf32_Word *hashcodes)
4052 Elf32_Word *bucket = NULL;
4053 Elf32_Word *chain = NULL;
4054 XElf_Shdr_vardef (shdr);
4056 /* Determine the "optimal" bucket size. If we also generate the
4057 new-style hash function there is no need to waste effort and
4058 space on the old one which should not be used. Make it as small
4060 if (GENERATE_GNU_HASH)
4063 nbucket = optimal_bucket_size (hashcodes, nsym_dyn, ld_state.optlevel);
4064 /* Create the .hash section data structures. */
4065 Elf_Scn *hashscn = elf_getscn (ld_state.outelf, ld_state.hashscnidx);
4066 xelf_getshdr (hashscn, shdr);
4067 Elf_Data *hashdata = elf_newdata (hashscn);
4068 if (shdr == NULL || hashdata == NULL)
4069 error (EXIT_FAILURE, 0, gettext ("\
4070 cannot create hash table section for output file: %s"),
4073 shdr->sh_link = ld_state.dynsymscnidx;
4074 (void) xelf_update_shdr (hashscn, shdr);
4076 hashdata->d_size = (2 + nsym_dyn + nbucket) * sizeof (Elf32_Word);
4077 hashdata->d_buf = xcalloc (1, hashdata->d_size);
4078 hashdata->d_align = sizeof (Elf32_Word);
4079 hashdata->d_type = ELF_T_WORD;
4080 hashdata->d_off = 0;
4082 ((Elf32_Word *) hashdata->d_buf)[0] = nbucket;
4083 ((Elf32_Word *) hashdata->d_buf)[1] = nsym_dyn;
4084 bucket = &((Elf32_Word *) hashdata->d_buf)[2];
4085 chain = &((Elf32_Word *) hashdata->d_buf)[2 + nbucket];
4087 for (size_t cnt = nsym_local; cnt < nsym; ++cnt)
4088 if (symstrent[cnt] != NULL)
4090 size_t dynidx = ndxtosym[cnt]->outdynsymidx;
4091 size_t hashidx = hashcodes[dynidx] % nbucket;
4092 if (bucket[hashidx] == 0)
4093 bucket[hashidx] = dynidx;
4096 hashidx = bucket[hashidx];
4097 while (chain[hashidx] != 0)
4098 hashidx = chain[hashidx];
4100 chain[hashidx] = dynidx;
4107 create_build_id_section (Elf_Scn *scn)
4109 /* We know how large the section will be so we can create it now. */
4110 Elf_Data *d = elf_newdata (scn);
4112 error (EXIT_FAILURE, 0, gettext ("cannot create build ID section: %s"),
4115 d->d_type = ELF_T_BYTE;
4116 d->d_version = EV_CURRENT;
4118 /* The note section header. */
4119 assert (sizeof (Elf32_Nhdr) == sizeof (Elf64_Nhdr));
4120 d->d_size = sizeof (GElf_Nhdr);
4121 /* The string is four bytes long. */
4122 d->d_size += sizeof (ELF_NOTE_GNU);
4123 assert (d->d_size % 4 == 0);
4125 if (strcmp (ld_state.build_id, "md5") == 0
4126 || strcmp (ld_state.build_id, "uuid") == 0)
4128 else if (strcmp (ld_state.build_id, "sha1") == 0)
4132 assert (ld_state.build_id[0] == '0' && ld_state.build_id[1] == 'x');
4133 /* Use an upper limit of the possible number of bytes generated
4135 d->d_size += strlen (ld_state.build_id) / 2;
4138 d->d_buf = xcalloc (d->d_size, 1);
4145 compute_hash_sum (void (*hashfct) (const void *, size_t, void *), void *ctx)
4147 /* The call cannot fail. */
4149 (void) elf_getshdrstrndx (ld_state.outelf, &shstrndx);
4151 const char *ident = elf_getident (ld_state.outelf, NULL);
4152 bool same_byte_order = ((ident[EI_DATA] == ELFDATA2LSB
4153 && __BYTE_ORDER == __LITTLE_ENDIAN)
4154 || (ident[EI_DATA] == ELFDATA2MSB
4155 && __BYTE_ORDER == __BIG_ENDIAN));
4157 /* Iterate over all sections to find those which are not strippable. */
4158 Elf_Scn *scn = NULL;
4159 while ((scn = elf_nextscn (ld_state.outelf, scn)) != NULL)
4161 /* Get the section header. */
4163 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
4164 assert (shdr != NULL);
4166 if (SECTION_STRIP_P (shdr, elf_strptr (ld_state.outelf, shstrndx,
4167 shdr->sh_name), true))
4168 /* The section can be stripped. Don't use it. */
4171 /* Do not look at NOBITS sections. */
4172 if (shdr->sh_type == SHT_NOBITS)
4175 /* Iterate through the list of data blocks. */
4176 Elf_Data *data = NULL;
4177 while ((data = INTUSE(elf_getdata) (scn, data)) != NULL)
4178 /* If the file byte order is the same as the host byte order
4179 process the buffer directly. If the data is just a stream
4180 of bytes which the library will not convert we can use it
4182 if (likely (same_byte_order) || data->d_type == ELF_T_BYTE)
4183 hashfct (data->d_buf, data->d_size, ctx);
4186 /* Convert the data to file byte order. */
4187 if (gelf_xlatetof (ld_state.outelf, data, data, ident[EI_DATA])
4189 error (EXIT_FAILURE, 0, gettext ("\
4190 cannot convert section data to file format: %s"),
4193 hashfct (data->d_buf, data->d_size, ctx);
4195 /* And convert it back. */
4196 if (gelf_xlatetom (ld_state.outelf, data, data, ident[EI_DATA])
4198 error (EXIT_FAILURE, 0, gettext ("\
4199 cannot convert section data to memory format: %s"),
4206 /* Iterate over the sections */
4208 compute_build_id (void)
4210 Elf_Data *d = elf_getdata (elf_getscn (ld_state.outelf,
4211 ld_state.buildidscnidx), NULL);
4214 GElf_Nhdr *hdr = d->d_buf;
4215 hdr->n_namesz = sizeof (ELF_NOTE_GNU);
4216 hdr->n_type = NT_GNU_BUILD_ID;
4217 char *dp = mempcpy (hdr + 1, ELF_NOTE_GNU, sizeof (ELF_NOTE_GNU));
4219 if (strcmp (ld_state.build_id, "sha1") == 0)
4221 /* Compute the SHA1 sum of various parts of the generated file.
4222 We compute the hash sum over the external representation. */
4223 struct sha1_ctx ctx;
4224 sha1_init_ctx (&ctx);
4226 /* Compute the hash sum by running over all sections. */
4227 compute_hash_sum ((void (*) (const void *, size_t, void *)) sha1_process_bytes,
4230 /* We are done computing the checksum. */
4231 (void) sha1_finish_ctx (&ctx, dp);
4233 hdr->n_descsz = SHA1_DIGEST_SIZE;
4235 else if (strcmp (ld_state.build_id, "md5") == 0)
4237 /* Compute the MD5 sum of various parts of the generated file.
4238 We compute the hash sum over the external representation. */
4240 md5_init_ctx (&ctx);
4242 /* Compute the hash sum by running over all sections. */
4243 compute_hash_sum ((void (*) (const void *, size_t, void *)) md5_process_bytes,
4246 /* We are done computing the checksum. */
4247 (void) md5_finish_ctx (&ctx, dp);
4249 hdr->n_descsz = MD5_DIGEST_SIZE;
4251 else if (strcmp (ld_state.build_id, "uuid") == 0)
4253 int fd = open ("/dev/urandom", O_RDONLY);
4255 error (EXIT_FAILURE, errno, gettext ("cannot open '%s'"),
4258 if (TEMP_FAILURE_RETRY (read (fd, dp, 16)) != 16)
4259 error (EXIT_FAILURE, 0, gettext ("cannot read enough data for UUID"));
4267 const char *cp = ld_state.build_id + 2;
4269 /* The form of the string has been verified before so here we can
4270 simplify the scanning. */
4273 if (isxdigit (cp[0]))
4275 char ch1 = tolower (cp[0]);
4276 char ch2 = tolower (cp[1]);
4278 *dp++ = (((isdigit (ch1) ? ch1 - '0' : ch1 - 'a' + 10) << 4)
4279 | (isdigit (ch2) ? ch2 - '0' : ch2 - 'a' + 10));
4284 while (*cp != '\0');
4289 /* Create the output file.
4291 For relocatable files what basically has to happen is that all
4292 sections from all input files are written into the output file.
4293 Sections with the same name are combined (offsets adjusted
4294 accordingly). The symbol tables are combined in one single table.
4295 When stripping certain symbol table entries are omitted.
4297 For executables (shared or not) we have to create the program header,
4298 additional sections like the .interp, eventually (in addition) create
4299 a dynamic symbol table and a dynamic section. Also the relocations
4300 have to be processed differently. */
4302 ld_generic_create_outfile (struct ld_state *statep)
4307 struct scninfo *scninfo;
4308 struct scnlist *next;
4310 struct scnlist *rellist = NULL;
4312 Elf_Scn *symscn = NULL;
4313 Elf_Scn *xndxscn = NULL;
4314 Elf_Scn *strscn = NULL;
4315 struct Ebl_Strtab *strtab = NULL;
4316 struct Ebl_Strtab *dynstrtab = NULL;
4317 XElf_Shdr_vardef (shdr);
4319 Elf_Data *symdata = NULL;
4320 Elf_Data *xndxdata = NULL;
4321 struct usedfiles *file;
4324 size_t nsym_allocated;
4325 size_t nsym_dyn = 0;
4326 Elf32_Word *dblindirect = NULL;
4330 Elf_Scn *shstrtab_scn;
4331 size_t shstrtab_ndx;
4332 XElf_Ehdr_vardef (ehdr);
4333 struct Ebl_Strent *symtab_ent = NULL;
4334 struct Ebl_Strent *xndx_ent = NULL;
4335 struct Ebl_Strent *strtab_ent = NULL;
4336 struct Ebl_Strent *shstrtab_ent;
4337 struct scngroup *groups;
4338 Elf_Scn *dynsymscn = NULL;
4339 Elf_Data *dynsymdata = NULL;
4340 Elf_Data *dynstrdata = NULL;
4341 Elf32_Word *hashcodes = NULL;
4342 Elf32_Word *gnuhashcodes = NULL;
4343 size_t nsym_dyn_allocated = 0;
4344 Elf_Scn *versymscn = NULL;
4345 Elf_Data *versymdata = NULL;
4347 if (ld_state.need_symtab)
4349 /* First create the symbol table. We need the symbol section itself
4350 and the string table for it. */
4351 symscn = elf_newscn (ld_state.outelf);
4352 ld_state.symscnidx = elf_ndxscn (symscn);
4353 symdata = elf_newdata (symscn);
4354 if (symdata == NULL)
4355 error (EXIT_FAILURE, 0,
4356 gettext ("cannot create symbol table for output file: %s"),
4359 symdata->d_type = ELF_T_SYM;
4360 /* This is an estimated size, but it will definitely cap the real value.
4361 We might have to adjust the number later. */
4362 nsym_allocated = (1 + ld_state.nsymtab + ld_state.nplt + ld_state.ngot
4363 + ld_state.nusedsections + ld_state.nlscript_syms);
4364 symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
4367 /* Optionally the extended section table. */
4368 /* XXX Is SHN_LORESERVE correct? Do we need some other sections? */
4369 if (unlikely (ld_state.nusedsections >= SHN_LORESERVE))
4371 xndxscn = elf_newscn (ld_state.outelf);
4372 ld_state.xndxscnidx = elf_ndxscn (xndxscn);
4374 xndxdata = elf_newdata (xndxscn);
4375 if (xndxdata == NULL)
4376 error (EXIT_FAILURE, 0,
4377 gettext ("cannot create symbol table for output file: %s"),
4380 /* The following relies on the fact that Elf32_Word and Elf64_Word
4381 have the same size. */
4382 xndxdata->d_type = ELF_T_WORD;
4383 /* This is an estimated size, but it will definitely cap the
4384 real value. we might have to adjust the number later. */
4385 xndxdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_WORD,
4387 /* The first entry is left empty, clear it here and now. */
4388 xndxdata->d_buf = memset (xmalloc (xndxdata->d_size), '\0',
4389 xelf_fsize (ld_state.outelf, ELF_T_WORD,
4391 xndxdata->d_off = 0;
4392 /* XXX Should use an ebl function. */
4393 xndxdata->d_align = sizeof (Elf32_Word);
4398 assert (ld_state.need_dynsym);
4400 /* First create the symbol table. We need the symbol section itself
4401 and the string table for it. */
4402 symscn = elf_getscn (ld_state.outelf, ld_state.dynsymscnidx);
4403 symdata = elf_newdata (symscn);
4404 if (symdata == NULL)
4405 error (EXIT_FAILURE, 0,
4406 gettext ("cannot create symbol table for output file: %s"),
4409 symdata->d_version = EV_CURRENT;
4410 symdata->d_type = ELF_T_SYM;
4411 /* This is an estimated size, but it will definitely cap the real value.
4412 We might have to adjust the number later. */
4413 nsym_allocated = (1 + ld_state.nsymtab + ld_state.nplt + ld_state.ngot
4414 - ld_state.nlocalsymbols + ld_state.nlscript_syms);
4415 symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
4419 /* The first entry is left empty, clear it here and now. */
4420 symdata->d_buf = memset (xmalloc (symdata->d_size), '\0',
4421 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
4423 /* XXX This is ugly but how else can it be done. */
4424 symdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4426 /* Allocate another array to keep track of the handles for the symbol
4428 symstrent = (struct Ebl_Strent **) xcalloc (nsym_allocated,
4429 sizeof (struct Ebl_Strent *));
4431 /* By starting at 1 we effectively add a null entry. */
4434 /* Iteration over all sections. */
4435 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
4437 struct scnhead *head = ld_state.allsections[cnt];
4439 struct scninfo *runp;
4443 /* Don't handle unused sections at all. */
4447 /* Get the section handle. */
4448 scn = elf_getscn (ld_state.outelf, head->scnidx);
4450 if (unlikely (head->kind == scn_dot_interp))
4452 Elf_Data *outdata = elf_newdata (scn);
4453 if (outdata == NULL)
4454 error (EXIT_FAILURE, 0,
4455 gettext ("cannot create section for output file: %s"),
4458 /* This is the string we'll put in the section. */
4459 const char *interp = ld_state.interp ?: "/lib/ld.so.1";
4461 /* Create the section data. */
4462 outdata->d_buf = (void *) interp;
4463 outdata->d_size = strlen (interp) + 1;
4464 outdata->d_type = ELF_T_BYTE;
4466 outdata->d_align = 1;
4467 outdata->d_version = EV_CURRENT;
4469 /* Remember the index of this section. */
4470 ld_state.interpscnidx = head->scnidx;
4475 if (unlikely (head->kind == scn_dot_got))
4477 /* Remember the index of this section. */
4478 ld_state.gotscnidx = elf_ndxscn (scn);
4480 /* Give the backend the change to initialize the section. */
4481 INITIALIZE_GOT (&ld_state, scn);
4486 if (unlikely (head->kind == scn_dot_gotplt))
4488 /* Remember the index of this section. */
4489 ld_state.gotpltscnidx = elf_ndxscn (scn);
4491 /* Give the backend the change to initialize the section. */
4492 INITIALIZE_GOTPLT (&ld_state, scn);
4497 if (unlikely (head->kind == scn_dot_dynrel))
4501 outdata = elf_newdata (scn);
4502 if (outdata == NULL)
4503 error (EXIT_FAILURE, 0,
4504 gettext ("cannot create section for output file: %s"),
4507 outdata->d_size = ld_state.relsize_total;
4508 outdata->d_buf = xmalloc (outdata->d_size);
4509 outdata->d_type = (REL_TYPE (&ld_state) == DT_REL
4510 ? ELF_T_REL : ELF_T_RELA);
4512 outdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4514 /* Remember the index of this section. */
4515 ld_state.reldynscnidx = elf_ndxscn (scn);
4520 if (unlikely (head->kind == scn_dot_dynamic))
4522 /* Only create the data for now. */
4525 /* Account for a few more entries we have to add. */
4526 if (ld_state.dt_flags != 0)
4527 ++ld_state.ndynamic;
4528 if (ld_state.dt_flags_1 != 0)
4529 ++ld_state.ndynamic;
4530 if (ld_state.dt_feature_1 != 0)
4531 ++ld_state.ndynamic;
4533 outdata = elf_newdata (scn);
4534 if (outdata == NULL)
4535 error (EXIT_FAILURE, 0,
4536 gettext ("cannot create section for output file: %s"),
4539 /* Create the section data. */
4540 outdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_DYN,
4542 outdata->d_buf = xcalloc (1, outdata->d_size);
4543 outdata->d_type = ELF_T_DYN;
4545 outdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4547 /* Remember the index of this section. */
4548 ld_state.dynamicscnidx = elf_ndxscn (scn);
4553 if (unlikely (head->kind == scn_dot_dynsym))
4555 /* We already know the section index. */
4556 assert (ld_state.dynsymscnidx == elf_ndxscn (scn));
4561 if (unlikely (head->kind == scn_dot_dynstr))
4563 /* Remember the index of this section. */
4564 ld_state.dynstrscnidx = elf_ndxscn (scn);
4566 /* Create the string table. */
4567 dynstrtab = ebl_strtabinit (true);
4570 We have to add all the strings which are needed in the
4571 dynamic section here. This means DT_FILTER,
4572 DT_AUXILIARY, ... entries. */
4573 if (ld_state.ndsofiles > 0)
4575 struct usedfiles *frunp = ld_state.dsofiles;
4578 if (! frunp->as_needed || frunp->used)
4579 frunp->sonameent = ebl_strtabadd (dynstrtab, frunp->soname,
4581 while ((frunp = frunp->next) != ld_state.dsofiles);
4585 /* Add the runtime path information. The strings are stored
4586 in the .dynstr section. If both rpath and runpath are defined
4587 the runpath information is used. */
4588 if (ld_state.runpath != NULL || ld_state.rpath != NULL)
4590 struct pathelement *startp;
4591 struct pathelement *prunp;
4597 if (ld_state.runpath != NULL)
4599 startp = ld_state.runpath;
4604 startp = ld_state.rpath;
4608 /* Determine how long the string will be. */
4609 for (len = 0, prunp = startp; prunp != NULL; prunp = prunp->next)
4610 len += strlen (prunp->pname) + 1;
4612 cp = str = (char *) obstack_alloc (&ld_state.smem, len);
4613 /* Copy the string. */
4614 for (prunp = startp; prunp != NULL; prunp = prunp->next)
4616 cp = stpcpy (cp, prunp->pname);
4619 /* Remove the last colon. */
4622 /* Remember the values until we can generate the dynamic
4624 ld_state.rxxpath_strent = ebl_strtabadd (dynstrtab, str, len);
4625 ld_state.rxxpath_tag = tag;
4631 if (unlikely (head->kind == scn_dot_hash))
4633 /* Remember the index of this section. */
4634 ld_state.hashscnidx = elf_ndxscn (scn);
4639 if (unlikely (head->kind == scn_dot_gnu_hash))
4641 /* Remember the index of this section. */
4642 ld_state.gnuhashscnidx = elf_ndxscn (scn);
4647 if (unlikely (head->kind == scn_dot_plt))
4649 /* Remember the index of this section. */
4650 ld_state.pltscnidx = elf_ndxscn (scn);
4652 /* Give the backend the change to initialize the section. */
4653 INITIALIZE_PLT (&ld_state, scn);
4658 if (unlikely (head->kind == scn_dot_pltrel))
4660 /* Remember the index of this section. */
4661 ld_state.pltrelscnidx = elf_ndxscn (scn);
4663 /* Give the backend the change to initialize the section. */
4664 INITIALIZE_PLTREL (&ld_state, scn);
4669 if (unlikely (head->kind == scn_dot_version))
4671 /* Remember the index of this section. */
4672 ld_state.versymscnidx = elf_ndxscn (scn);
4677 if (unlikely (head->kind == scn_dot_version_r))
4679 /* Remember the index of this section. */
4680 ld_state.verneedscnidx = elf_ndxscn (scn);
4685 if (unlikely (head->kind == scn_dot_note_gnu_build_id))
4687 /* Remember the index of this section. */
4688 ld_state.buildidscnidx = elf_ndxscn (scn);
4690 create_build_id_section (scn);
4695 /* If we come here we must be handling a normal section. */
4696 assert (head->kind == scn_normal);
4698 /* Create an STT_SECTION entry in the symbol table. But not for
4699 the symbolic symbol table. */
4700 if (ld_state.need_symtab)
4702 /* XXX Can we be cleverer and do this only if needed? */
4703 XElf_Sym_vardef (sym);
4705 /* Optimization ahead: in the native linker we get a pointer
4706 to the final location so that the following code writes
4707 directly in the correct place. Otherwise we write into
4708 the local variable first. */
4709 xelf_getsym_ptr (symdata, nsym, sym);
4711 /* Usual section symbol: local, no specific information,
4712 except the section index. The offset here is zero, the
4713 start address will later be added. */
4715 sym->st_info = XELF_ST_INFO (STB_LOCAL, STT_SECTION);
4719 /* In relocatable files the section index can be too big for
4720 the ElfXX_Sym struct. we have to deal with the extended
4722 if (likely (head->scnidx < SHN_LORESERVE))
4724 sym->st_shndx = head->scnidx;
4729 sym->st_shndx = SHN_XINDEX;
4730 xndx = head->scnidx;
4732 /* Commit the change. See the optimization above, this does
4733 not change the symbol table entry. But the extended
4734 section index table entry is always written, if there is
4736 assert (nsym < nsym_allocated);
4737 xelf_update_symshndx (symdata, xndxdata, nsym, sym, xndx, 0);
4739 /* Remember the symbol's index in the symbol table. */
4740 head->scnsymidx = nsym++;
4743 if (head->type == SHT_REL || head->type == SHT_RELA)
4745 /* Remember that we have to fill in the symbol table section
4747 if (ld_state.file_type == relocatable_file_type)
4749 struct scnlist *newp;
4751 newp = (struct scnlist *) alloca (sizeof (*newp));
4752 newp->scnidx = head->scnidx;
4753 newp->scninfo = head->last->next;
4757 SNGL_LIST_PUSH (rellist, newp);
4761 /* When we create an executable or a DSO we don't simply
4762 copy the existing relocations. Instead many will be
4763 resolved, others will be converted. Create a data buffer
4764 large enough to contain the contents which we will fill
4766 int type = head->type == SHT_REL ? ELF_T_REL : ELF_T_RELA;
4768 data = elf_newdata (scn);
4770 error (EXIT_FAILURE, 0,
4771 gettext ("cannot create section for output file: %s"),
4774 data->d_size = xelf_fsize (ld_state.outelf, type, head->relsize);
4775 data->d_buf = xcalloc (data->d_size, 1);
4776 data->d_type = type;
4777 data->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4784 /* Recognize string and merge flag and handle them. */
4785 if (head->flags & SHF_MERGE)
4787 /* We merge the contents of the sections. For this we do
4788 not look at the contents of section directly. Instead we
4789 look at the symbols of the section. */
4792 /* Concatenate the lists of symbols for all sections.
4794 XXX In case any input section has no symbols associated
4795 (this happens for debug sections) we cannot use this
4796 method. Implement parsing the other debug sections and
4797 find the string pointers. For now we don't merge. */
4798 runp = head->last->next;
4799 if (runp->symbols == NULL)
4801 head->flags &= ~SHF_MERGE;
4804 head->symbols = runp->symbols;
4806 while ((runp = runp->next) != head->last->next)
4808 if (runp->symbols == NULL)
4810 head->flags &= ~SHF_MERGE;
4811 head->symbols = NULL;
4815 struct symbol *oldhead = head->symbols->next_in_scn;
4817 head->symbols->next_in_scn = runp->symbols->next_in_scn;
4818 runp->symbols->next_in_scn = oldhead;
4819 head->symbols = runp->symbols;
4822 /* Create the output section. */
4823 outdata = elf_newdata (scn);
4824 if (outdata == NULL)
4825 error (EXIT_FAILURE, 0,
4826 gettext ("cannot create section for output file: %s"),
4829 /* We use different merging algorithms for performance
4830 reasons. We can easily handle single-byte and
4831 wchar_t-wide character strings. All other cases (which
4832 really should happen in real life) are handled by the
4834 if (SCNINFO_SHDR (head->last->shdr).sh_entsize == 1
4835 && (head->flags & SHF_STRINGS))
4837 /* Simple, single-byte string matching. */
4838 struct Ebl_Strtab *mergestrtab;
4839 struct symbol *symrunp;
4840 Elf_Data *locsymdata = NULL;
4841 Elf_Data *locdata = NULL;
4843 mergestrtab = ebl_strtabinit (false);
4845 symrunp = head->symbols->next_in_scn;
4849 /* Accelarate the loop. We cache the file
4850 information since it might very well be the case
4851 that the previous entry was from the same
4853 if (symrunp->file != file)
4855 /* Remember the file. */
4856 file = symrunp->file;
4857 /* Symbol table data from that file. */
4858 locsymdata = file->symtabdata;
4859 /* String section data. */
4860 locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
4862 assert (locdata != NULL);
4863 /* While we are at it, remember the output
4864 section. If we don't access the string data
4865 section the section won't be in the output
4866 file. So it is sufficient to do the work
4868 file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
4871 /* Get the symbol information. This provides us the
4872 offset into the string data section. */
4873 XElf_Sym_vardef (sym);
4874 xelf_getsym (locsymdata, symrunp->symidx, sym);
4875 assert (sym != NULL);
4877 /* Get the data from the file. Note that we access
4878 the raw section data; no endian-ness issues with
4879 single-byte strings. */
4880 symrunp->merge.handle
4881 = ebl_strtabadd (mergestrtab,
4882 (char *) locdata->d_buf + sym->st_value,
4885 while ((symrunp = symrunp->next_in_scn)
4886 != head->symbols->next_in_scn);
4888 /* All strings have been added. Create the final table. */
4889 ebl_strtabfinalize (mergestrtab, outdata);
4891 /* Compute the final offsets in the section. */
4892 symrunp = runp->symbols;
4895 symrunp->merge.value
4896 = ebl_strtaboffset (symrunp->merge.handle);
4897 symrunp->merged = 1;
4899 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4901 /* We don't need the string table anymore. */
4902 ebl_strtabfree (mergestrtab);
4904 else if (likely (SCNINFO_SHDR (head->last->shdr).sh_entsize
4905 == sizeof (wchar_t))
4906 && likely (head->flags & SHF_STRINGS))
4908 /* Simple, wchar_t string merging. */
4909 struct Ebl_WStrtab *mergestrtab;
4910 struct symbol *symrunp;
4911 Elf_Data *locsymdata = NULL;
4912 Elf_Data *locdata = NULL;
4914 mergestrtab = ebl_wstrtabinit (false);
4916 symrunp = runp->symbols;
4920 /* Accelarate the loop. We cache the file
4921 information since it might very well be the case
4922 that the previous entry was from the same
4924 if (symrunp->file != file)
4926 /* Remember the file. */
4927 file = symrunp->file;
4928 /* Symbol table data from that file. */
4929 locsymdata = file->symtabdata;
4930 /* String section data. */
4931 locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
4933 assert (locdata != NULL);
4935 /* While we are at it, remember the output
4936 section. If we don't access the string data
4937 section the section won't be in the output
4938 file. So it is sufficient to do the work
4940 file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
4943 /* Get the symbol information. This provides us the
4944 offset into the string data section. */
4945 XElf_Sym_vardef (sym);
4946 xelf_getsym (locsymdata, symrunp->symidx, sym);
4947 assert (sym != NULL);
4949 /* Get the data from the file. Using the raw
4950 section data here is possible since we don't
4951 interpret the string themselves except for
4952 looking for the wide NUL character. The NUL
4953 character has fortunately the same representation
4954 regardless of the byte order. */
4955 symrunp->merge.handle
4956 = ebl_wstrtabadd (mergestrtab,
4957 (wchar_t *) ((char *) locdata->d_buf
4958 + sym->st_value), 0);
4960 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4962 /* All strings have been added. Create the final table. */
4963 ebl_wstrtabfinalize (mergestrtab, outdata);
4965 /* Compute the final offsets in the section. */
4966 symrunp = runp->symbols;
4969 symrunp->merge.value
4970 = ebl_wstrtaboffset (symrunp->merge.handle);
4971 symrunp->merged = 1;
4973 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4975 /* We don't need the string table anymore. */
4976 ebl_wstrtabfree (mergestrtab);
4980 /* Non-standard merging. */
4981 struct Ebl_GStrtab *mergestrtab;
4982 struct symbol *symrunp;
4983 Elf_Data *locsymdata = NULL;
4984 Elf_Data *locdata = NULL;
4985 /* If this is no string section the length of each "string"
4987 unsigned int len = (head->flags & SHF_STRINGS) ? 0 : 1;
4989 /* This is the generic string table functionality. Much
4990 slower than the specialized code. */
4992 = ebl_gstrtabinit (SCNINFO_SHDR (head->last->shdr).sh_entsize,
4995 symrunp = runp->symbols;
4999 /* Accelarate the loop. We cache the file
5000 information since it might very well be the case
5001 that the previous entry was from the same
5003 if (symrunp->file != file)
5005 /* Remember the file. */
5006 file = symrunp->file;
5007 /* Symbol table data from that file. */
5008 locsymdata = file->symtabdata;
5009 /* String section data. */
5010 locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
5012 assert (locdata != NULL);
5014 /* While we are at it, remember the output
5015 section. If we don't access the string data
5016 section the section won't be in the output
5017 file. So it is sufficient to do the work
5019 file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
5022 /* Get the symbol information. This provides us the
5023 offset into the string data section. */
5024 XElf_Sym_vardef (sym);
5025 xelf_getsym (locsymdata, symrunp->symidx, sym);
5026 assert (sym != NULL);
5028 /* Get the data from the file. Using the raw
5029 section data here is possible since we don't
5030 interpret the string themselves except for
5031 looking for the wide NUL character. The NUL
5032 character has fortunately the same representation
5033 regardless of the byte order. */
5034 symrunp->merge.handle
5035 = ebl_gstrtabadd (mergestrtab,
5036 (char *) locdata->d_buf + sym->st_value,
5039 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
5041 /* Create the final table. */
5042 ebl_gstrtabfinalize (mergestrtab, outdata);
5044 /* Compute the final offsets in the section. */
5045 symrunp = runp->symbols;
5048 symrunp->merge.value
5049 = ebl_gstrtaboffset (symrunp->merge.handle);
5050 symrunp->merged = 1;
5052 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
5054 /* We don't need the string table anymore. */
5055 ebl_gstrtabfree (mergestrtab);
5061 assert (head->scnidx == elf_ndxscn (scn));
5063 /* It is important to start with the first list entry (and
5064 not just any one) to add the sections in the correct
5066 runp = head->last->next;
5070 Elf_Data *outdata = elf_newdata (scn);
5071 if (outdata == NULL)
5072 error (EXIT_FAILURE, 0,
5073 gettext ("cannot create section for output file: %s"),
5076 /* Exceptional case: if we synthesize a data block SCN
5077 is NULL and the sectio header info must be for a
5078 SHT_NOBITS block and the size and alignment are
5080 if (likely (runp->scn != NULL))
5082 data = elf_getdata (runp->scn, NULL);
5083 assert (data != NULL);
5085 /* We reuse the data buffer in the input file. */
5088 /* Given that we read the input file from disk we know there
5089 cannot be another data part. */
5090 assert (elf_getdata (runp->scn, data) == NULL);
5094 /* Must be a NOBITS section. */
5095 assert (SCNINFO_SHDR (runp->shdr).sh_type == SHT_NOBITS);
5097 outdata->d_buf = NULL; /* Not needed. */
5098 outdata->d_type = ELF_T_BYTE;
5099 outdata->d_version = EV_CURRENT;
5100 outdata->d_size = SCNINFO_SHDR (runp->shdr).sh_size;
5101 outdata->d_align = SCNINFO_SHDR (runp->shdr).sh_addralign;
5104 XElf_Off align = MAX (1, outdata->d_align);
5105 assert (powerof2 (align));
5106 offset = ((offset + align - 1) & ~(align - 1));
5108 runp->offset = offset;
5109 runp->outscnndx = head->scnidx;
5110 runp->allsectionsidx = cnt;
5112 outdata->d_off = offset;
5114 offset += outdata->d_size;
5116 while ((runp = runp->next) != head->last->next);
5118 /* If necessary add the additional line to the .comment section. */
5119 if (ld_state.add_ld_comment
5121 && head->type == SHT_PROGBITS
5122 && strcmp (head->name, ".comment") == 0
5123 && head->entsize == 0)
5125 Elf_Data *outdata = elf_newdata (scn);
5127 if (outdata == NULL)
5128 error (EXIT_FAILURE, 0,
5129 gettext ("cannot create section for output file: %s"),
5132 outdata->d_buf = (void *) "\0ld (" PACKAGE_NAME ") " PACKAGE_VERSION;
5133 outdata->d_size = strlen ((char *) outdata->d_buf + 1) + 2;
5134 outdata->d_off = offset;
5135 outdata->d_type = ELF_T_BYTE;
5136 outdata->d_align = 1;
5138 /* XXX We should create a .comment section if none exists.
5139 This requires that we early on detect that no such
5140 section exists. This should probably be implemented
5141 together with some merging of the section contents.
5142 Currently identical entries are not merged. */
5146 /* The table we collect the strings in. */
5147 strtab = ebl_strtabinit (true);
5149 error (EXIT_FAILURE, errno, gettext ("cannot create string table"));
5153 /* Keep track of the use of the XINDEX. */
5157 /* We we generate a normal symbol table for an executable and the
5158 --export-dynamic option is not given, we need an extra table
5159 which keeps track of the symbol entry belonging to the symbol
5160 table entry. Note that EXPORT_ALL_DYNAMIC is always set if we
5161 generate a DSO so we do not have to test this separately. */
5162 ndxtosym = (struct symbol **) xcalloc (nsym_allocated,
5163 sizeof (struct symbol));
5165 /* Create the special symbol for the GOT section. */
5166 if (ld_state.got_symbol != NULL)
5168 assert (nsym < nsym_allocated);
5169 // XXX Fix so that it works even if no PLT is needed.
5170 fillin_special_symbol (ld_state.got_symbol, ld_state.gotpltscnidx,
5171 nsym++, symdata, strtab);
5174 /* Similarly for the dynamic section symbol. */
5175 if (ld_state.dyn_symbol != NULL)
5177 assert (nsym < nsym_allocated);
5178 fillin_special_symbol (ld_state.dyn_symbol, ld_state.dynamicscnidx,
5179 nsym++, symdata, strtab);
5182 /* Create symbol table entries for the symbols defined in the linker
5184 if (ld_state.lscript_syms != NULL)
5186 struct symbol *rsym = ld_state.lscript_syms;
5189 assert (nsym < nsym_allocated);
5190 fillin_special_symbol (rsym, SHN_ABS, nsym++, symdata, strtab);
5192 while ((rsym = rsym->next) != NULL);
5195 /* Iterate over all input files to collect the symbols. */
5196 file = ld_state.relfiles->next;
5197 symdata = elf_getdata (elf_getscn (ld_state.outelf, ld_state.symscnidx),
5203 Elf_Data *insymdata;
5204 Elf_Data *inxndxdata;
5206 /* There must be no dynamic symbol table when creating
5207 relocatable files. */
5208 assert (ld_state.file_type != relocatable_file_type
5209 || file->dynsymtabdata == NULL);
5211 insymdata = file->symtabdata;
5212 assert (insymdata != NULL);
5213 inxndxdata = file->xndxdata;
5215 maxcnt = file->nsymtab;
5217 file->symindirect = (Elf32_Word *) xcalloc (maxcnt, sizeof (Elf32_Word));
5219 /* The dynamic symbol table does not contain local symbols. So
5220 we skip those entries. */
5221 for (cnt = ld_state.need_symtab ? 1 : file->nlocalsymbols; cnt < maxcnt;
5224 XElf_Sym_vardef (sym);
5226 struct symbol *defp = NULL;
5228 xelf_getsymshndx (insymdata, inxndxdata, cnt, sym, xndx);
5229 assert (sym != NULL);
5231 if (unlikely (XELF_ST_TYPE (sym->st_info) == STT_SECTION))
5233 /* Section symbols should always be local but who knows... */
5234 if (ld_state.need_symtab)
5236 /* Determine the real section index in the source file.
5237 Use the XINDEX section content if necessary. We don't
5238 add this information to the dynamic symbol table. */
5239 if (sym->st_shndx != SHN_XINDEX)
5240 xndx = sym->st_shndx;
5242 assert (file->scninfo[xndx].allsectionsidx
5243 < ld_state.nallsections);
5244 file->symindirect[cnt] = ld_state.allsections[file->scninfo[xndx].allsectionsidx]->scnsymidx;
5245 /* Note that the resulting index can be zero here. There is
5246 no guarantee that the output file will contain all the
5247 sections the input file did. */
5252 if ((ld_state.strip >= strip_all || !ld_state.need_symtab)
5253 /* XXX Do we need these entries? */
5254 && XELF_ST_TYPE (sym->st_info) == STT_FILE)
5258 /* Copy old data. We create a temporary copy because the
5259 symbol might still be discarded. */
5265 if (sym->st_shndx != SHN_UNDEF
5266 && (sym->st_shndx < SHN_LORESERVE
5267 || sym->st_shndx == SHN_XINDEX))
5269 /* If we are creating an executable with no normal
5270 symbol table and we do not export all symbols and
5271 this symbol is not defined in a DSO as well, ignore
5273 if (!ld_state.export_all_dynamic && !ld_state.need_symtab)
5275 assert (cnt >= file->nlocalsymbols);
5276 defp = file->symref[cnt];
5277 assert (defp != NULL);
5284 /* Determine the real section index in the source file. Use
5285 the XINDEX section content if necessary. */
5286 if (sym->st_shndx != SHN_XINDEX)
5287 xndx = sym->st_shndx;
5289 sym->st_value += file->scninfo[xndx].offset;
5291 assert (file->scninfo[xndx].outscnndx < SHN_LORESERVE
5292 || file->scninfo[xndx].outscnndx > SHN_HIRESERVE);
5293 if (unlikely (file->scninfo[xndx].outscnndx > SHN_LORESERVE))
5295 /* It is not possible to have an extended section index
5296 table for the dynamic symbol table. */
5297 if (!ld_state.need_symtab)
5298 error (EXIT_FAILURE, 0, gettext ("\
5299 section index too large in dynamic symbol table"));
5301 assert (xndxdata != NULL);
5302 sym->st_shndx = SHN_XINDEX;
5303 xndx = file->scninfo[xndx].outscnndx;
5310 sym->st_shndx = file->scninfo[xndx].outscnndx;
5314 else if (sym->st_shndx == SHN_COMMON || sym->st_shndx == SHN_UNDEF)
5316 /* Check whether we have a (real) definition for this
5317 symbol. If this is the case we skip this symbol
5319 assert (cnt >= file->nlocalsymbols);
5320 defp = file->symref[cnt];
5321 assert (defp != NULL);
5323 assert (sym->st_shndx != SHN_COMMON || defp->defined);
5325 if ((sym->st_shndx == SHN_COMMON && !defp->common)
5326 || (sym->st_shndx == SHN_UNDEF && defp->defined)
5328 /* Ignore this symbol table entry, there is a
5329 "better" one or we already added it. */
5332 /* Remember that we already added this symbol. */
5335 /* Adjust the section number for common symbols. */
5336 if (sym->st_shndx == SHN_COMMON)
5338 sym->st_value = (ld_state.common_section->offset
5339 + file->symref[cnt]->merge.value);
5340 assert (ld_state.common_section->outscnndx < SHN_LORESERVE);
5341 sym->st_shndx = ld_state.common_section->outscnndx;
5345 else if (unlikely (sym->st_shndx != SHN_ABS))
5347 if (SPECIAL_SECTION_NUMBER_P (&ld_state, sym->st_shndx))
5348 /* XXX Add code to handle machine specific special
5353 /* Add the symbol name to the string table. If the user
5354 chooses the highest level of stripping avoid adding names
5355 for local symbols in the string table. */
5356 if (sym->st_name != 0
5357 && (ld_state.strip < strip_everything
5358 || XELF_ST_BIND (sym->st_info) != STB_LOCAL))
5359 symstrent[nsym] = ebl_strtabadd (strtab,
5360 elf_strptr (file->elf,
5364 /* Once we know the name this field will get the correct
5365 offset. For now set it to zero which means no name
5367 GElf_Word st_name = sym->st_name;
5370 /* If we had to merge sections we have a completely new
5371 offset for the symbol. */
5372 if (file->has_merge_sections && file->symref[cnt] != NULL
5373 && file->symref[cnt]->merged)
5374 sym->st_value = file->symref[cnt]->merge.value;
5376 /* Create the record in the output sections. */
5377 assert (nsym < nsym_allocated);
5378 xelf_update_symshndx (symdata, xndxdata, nsym, sym, xndx, 1);
5380 /* Add the reference to the symbol record in case we need it.
5381 Find the symbol if this has not happened yet. We do
5382 not need the information for local symbols. */
5383 if (defp == NULL && cnt >= file->nlocalsymbols)
5385 defp = file->symref[cnt];
5389 /* This is a symbol in a discarded COMDAT section.
5390 Find the definition we actually use. */
5391 // XXX The question is: do we have to do this here
5392 // XXX or can we do it earlier when we discard the
5394 struct symbol search;
5395 search.name = elf_strptr (file->elf, file->symstridx,
5397 struct symbol *realp
5398 = ld_symbol_tab_find (&ld_state.symbol_tab,
5399 elf_hash (search.name), &search);
5401 // XXX What to do here?
5402 error (EXIT_FAILURE, 0,
5403 "couldn't find symbol from COMDAT section");
5405 file->symref[cnt] = realp;
5411 /* Store the reference to the symbol record. The sorting
5412 code will have to keep this array in the correct order, too. */
5413 ndxtosym[nsym] = defp;
5415 /* One more entry finished. */
5416 if (cnt >= file->nlocalsymbols)
5418 assert (file->symref[cnt]->outsymidx == 0);
5419 file->symref[cnt]->outsymidx = nsym;
5421 file->symindirect[cnt] = nsym++;
5424 while ((file = file->next) != ld_state.relfiles->next);
5425 /* Make sure we didn't create the extended section index table for
5427 assert (xndxdata == NULL || need_xndx);
5429 /* Create the version related sections. */
5430 if (ld_state.verneedscnidx != 0)
5432 /* We know the number of input files and total number of
5433 referenced versions. This allows us to allocate the memory
5434 and then we iterate over the DSOs to get the version
5436 struct usedfiles *runp;
5438 runp = ld_state.dsofiles->next;
5440 allocate_version_names (runp, dynstrtab);
5441 while ((runp = runp->next) != ld_state.dsofiles->next);
5443 if (ld_state.needed != NULL)
5445 runp = ld_state.needed->next;
5447 allocate_version_names (runp, dynstrtab);
5448 while ((runp = runp->next) != ld_state.needed->next);
5452 /* At this point we should hide symbols and so on. */
5453 if (ld_state.default_bind_local || ld_state.version_str_tab.filled > 0)
5454 /* XXX Add one more test when handling of wildcard symbol names
5457 /* Check all non-local symbols whether they are on the export list. */
5458 bool any_reduced = false;
5460 for (cnt = 1; cnt < nsym; ++cnt)
5462 XElf_Sym_vardef (sym);
5464 /* Note that we don't have to use 'xelf_getsymshndx' since we
5465 only need the binding and the symbol name. */
5466 xelf_getsym (symdata, cnt, sym);
5467 assert (sym != NULL);
5469 if (reduce_symbol_p (sym, symstrent[cnt]))
5471 // XXX Check whether this is correct...
5472 assert (ndxtosym[cnt]->outdynsymidx != 0);
5473 ndxtosym[cnt]->outdynsymidx = 0;
5475 sym->st_info = XELF_ST_INFO (STB_LOCAL,
5476 XELF_ST_TYPE (sym->st_info));
5477 (void) xelf_update_sym (symdata, cnt, sym);
5479 /* Show that we don't need this string anymore. */
5480 if (ld_state.strip == strip_everything)
5482 symstrent[cnt] = NULL;
5488 if (unlikely (any_reduced))
5490 /* Since we will not write names of local symbols in the
5491 output file and we have reduced the binding of some
5492 symbols the string table previously constructed contains
5493 too many string. Correct it. */
5494 struct Ebl_Strtab *newp = ebl_strtabinit (true);
5496 for (cnt = 1; cnt < nsym; ++cnt)
5497 if (symstrent[cnt] != NULL)
5498 symstrent[cnt] = ebl_strtabadd (newp,
5499 ebl_string (symstrent[cnt]), 0);
5501 ebl_strtabfree (strtab);
5506 /* Add the references to DSOs. We can add these entries this late
5507 (after sorting out versioning) because references to DSOs are not
5509 if (ld_state.from_dso != NULL)
5511 struct symbol *runp;
5512 size_t plt_base = nsym + ld_state.nfrom_dso - ld_state.nplt;
5516 assert (ld_state.nfrom_dso >= ld_state.nplt);
5517 runp = ld_state.from_dso;
5520 // XXX What about functions which are only referenced via
5521 // pointers and not PLT entries? Can we distinguish such uses?
5523 if (runp->type == STT_FUNC)
5525 /* Store the PLT entry number. */
5526 runp->merge.value = plt_idx + 1;
5527 idx = plt_base + plt_idx++;
5530 idx = nsym + obj_idx++;
5532 XElf_Sym_vardef (sym);
5533 xelf_getsym_ptr (symdata, idx, sym);
5536 sym->st_size = runp->size;
5537 sym->st_info = XELF_ST_INFO (runp->weak ? STB_WEAK : STB_GLOBAL,
5539 sym->st_other = STV_DEFAULT;
5540 sym->st_shndx = SHN_UNDEF;
5542 /* Create the record in the output sections. */
5543 xelf_update_symshndx (symdata, xndxdata, idx, sym, 0, 0);
5545 const char *name = runp->name;
5548 if (runp->file->verdefdata != NULL)
5550 // XXX Is it useful to add the versym value to struct symbol?
5553 (void) xelf_getversym_copy (runp->file->versymdata, runp->symidx,
5556 /* One can only link with the default version. */
5557 assert ((versym & 0x8000) == 0);
5559 const char *versname
5560 = ebl_string (runp->file->verdefent[versym]);
5562 size_t versname_len = strlen (versname) + 1;
5563 namelen = strlen (name) + versname_len + 2;
5564 char *newp = (char *) obstack_alloc (&ld_state.smem, namelen);
5565 memcpy (stpcpy (stpcpy (newp, name), "@@"),
5566 versname, versname_len);
5570 symstrent[idx] = ebl_strtabadd (strtab, name, namelen);
5572 /* Record the initial index in the symbol table. */
5573 runp->outsymidx = idx;
5575 /* Remember the symbol record this ELF symbol came from. */
5576 ndxtosym[idx] = runp;
5578 while ((runp = runp->next) != ld_state.from_dso);
5580 assert (nsym + obj_idx == plt_base);
5581 assert (plt_idx == ld_state.nplt);
5582 nsym = plt_base + plt_idx;
5585 /* Now we know how many symbols will be in the output file. Adjust
5586 the count in the section data. */
5587 symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym);
5588 if (unlikely (xndxdata != NULL))
5589 xndxdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_WORD, nsym);
5591 /* Create the symbol string table section. */
5592 strscn = elf_newscn (ld_state.outelf);
5593 ld_state.strscnidx = elf_ndxscn (strscn);
5594 data = elf_newdata (strscn);
5595 xelf_getshdr (strscn, shdr);
5596 if (data == NULL || shdr == NULL)
5597 error (EXIT_FAILURE, 0,
5598 gettext ("cannot create section for output file: %s"),
5601 /* Create a compact string table, allocate the memory for it, and
5602 fill in the section data information. */
5603 ebl_strtabfinalize (strtab, data);
5605 shdr->sh_type = SHT_STRTAB;
5606 assert (shdr->sh_entsize == 0);
5608 if (unlikely (xelf_update_shdr (strscn, shdr) == 0))
5609 error (EXIT_FAILURE, 0,
5610 gettext ("cannot create section for output file: %s"),
5613 /* Fill in the offsets of the symbol names. */
5614 for (cnt = 1; cnt < nsym; ++cnt)
5615 if (symstrent[cnt] != NULL)
5617 XElf_Sym_vardef (sym);
5619 /* Note that we don't have to use 'xelf_getsymshndx' since we don't
5620 modify the section index. */
5621 xelf_getsym (symdata, cnt, sym);
5622 /* This better worked, we did it before. */
5623 assert (sym != NULL);
5624 sym->st_name = ebl_strtaboffset (symstrent[cnt]);
5625 (void) xelf_update_sym (symdata, cnt, sym);
5628 /* Since we are going to reorder the symbol table but still have to
5629 be able to find the new position based on the old one (since the
5630 latter is stored in 'symindirect' information of the input file
5631 data structure) we have to create yet another indirection
5633 ld_state.dblindirect = dblindirect
5634 = (Elf32_Word *) xmalloc (nsym * sizeof (Elf32_Word));
5636 /* Sort the symbol table so that the local symbols come first. */
5637 /* XXX We don't use stable sorting here. It seems not necessary and
5638 would be more expensive. If it turns out to be necessary this can
5642 while (nsym_local < cnt)
5644 XElf_Sym_vardef (locsym);
5646 XElf_Sym_vardef (globsym);
5647 Elf32_Word globxndx;
5651 xelf_getsymshndx (symdata, xndxdata, nsym_local, locsym, locxndx);
5652 /* This better works. */
5653 assert (locsym != NULL);
5655 if (XELF_ST_BIND (locsym->st_info) != STB_LOCAL
5656 && (ld_state.need_symtab || ld_state.export_all_dynamic))
5660 xelf_getsymshndx (symdata, xndxdata, cnt, globsym, globxndx);
5661 /* This better works. */
5662 assert (globsym != NULL);
5664 if (unlikely (XELF_ST_BIND (globsym->st_info) == STB_LOCAL))
5666 /* We swap the two entries. */
5668 /* Since we directly modify the data in the ELF
5669 data structure we have to make a copy of one
5671 XElf_Sym locsym_copy = *locsym;
5672 locsym = &locsym_copy;
5674 xelf_update_symshndx (symdata, xndxdata, nsym_local,
5675 globsym, globxndx, 1);
5676 xelf_update_symshndx (symdata, xndxdata, cnt,
5677 locsym, locxndx, 1);
5679 /* Also swap the cross references. */
5680 dblindirect[nsym_local] = cnt;
5681 dblindirect[cnt] = nsym_local;
5683 /* And the entries for the symbol names. */
5684 struct Ebl_Strent *strtmp = symstrent[nsym_local];
5685 symstrent[nsym_local] = symstrent[cnt];
5686 symstrent[cnt] = strtmp;
5688 /* And the mapping from symbol table entry to
5689 struct symbol record. */
5690 struct symbol *symtmp = ndxtosym[nsym_local];
5691 ndxtosym[nsym_local] = ndxtosym[cnt];
5692 ndxtosym[cnt] = symtmp;
5694 /* Go to the next entry. */
5701 dblindirect[cnt] = cnt;
5703 while (nsym_local < --cnt);
5708 dblindirect[nsym_local] = nsym_local;
5710 while (++nsym_local < cnt);
5713 /* The symbol 'nsym_local' is currently pointing to might be local,
5714 too. Check and increment the variable if this is the case. */
5715 if (likely (nsym_local < nsym))
5717 XElf_Sym_vardef (locsym);
5719 /* This entry isn't moved. */
5720 dblindirect[nsym_local] = nsym_local;
5722 /* Note that it is OK to not use 'xelf_getsymshndx' here. */
5723 xelf_getsym (symdata, nsym_local, locsym);
5724 /* This better works. */
5725 assert (locsym != NULL);
5727 if (XELF_ST_BIND (locsym->st_info) == STB_LOCAL)
5732 /* We need the versym array right away to keep track of the version
5734 if (ld_state.versymscnidx != 0)
5736 /* We allocate more memory than we need since the array is morroring
5737 the dynamic symbol table and not the normal symbol table. I.e.,
5738 no local symbols are present. */
5739 versymscn = elf_getscn (ld_state.outelf, ld_state.versymscnidx);
5740 versymdata = elf_newdata (versymscn);
5741 if (versymdata == NULL)
5742 error (EXIT_FAILURE, 0,
5743 gettext ("cannot create versioning section: %s"),
5746 versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
5747 nsym - nsym_local + 1);
5748 versymdata->d_buf = xcalloc (1, versymdata->d_size);
5749 versymdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_HALF, 1);
5750 versymdata->d_off = 0;
5751 versymdata->d_type = ELF_T_HALF;
5755 /* If we have to construct the dynamic symbol table we must not include
5756 the local symbols. If the normal symbol has to be emitted as well
5757 we haven't done anything else yet and we can construct it from
5759 if (unlikely (!ld_state.need_symtab))
5761 /* Note that the following code works even if there is no entry
5762 to remove since the zeroth entry is always local. */
5763 size_t reduce = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym_local - 1);
5765 XElf_Sym_vardef (nullsym);
5766 xelf_getsym_ptr (symdata, nsym_local - 1, nullsym);
5768 /* Note that we don't have to use 'xelf_update_symshndx' since
5769 this is the dynamic symbol table we write. */
5770 (void) xelf_update_sym (symdata, nsym_local - 1,
5771 memset (nullsym, '\0', sizeof (*nullsym)));
5773 /* Update the buffer pointer and size in the output data. */
5774 symdata->d_buf = (char *) symdata->d_buf + reduce;
5775 symdata->d_size -= reduce;
5777 /* Add the version symbol information. */
5778 if (versymdata != NULL)
5781 for (cnt = nsym_local; cnt < nsym; ++cnt, ++nsym_dyn)
5783 struct symbol *symp = ndxtosym[cnt];
5785 if (symp->file->versymdata != NULL)
5789 gelf_getversym (symp->file->versymdata, symp->symidx,
5792 (void) gelf_update_versym (versymdata, symp->outdynsymidx,
5793 &symp->file->verdefused[versym]);
5798 /* Since we only created the dynamic symbol table the number of
5799 dynamic symbols is the total number of symbols. */
5800 nsym_dyn = nsym - nsym_local + 1;
5802 /* XXX TBI. Create whatever data structure is missing. */
5805 else if (ld_state.need_dynsym)
5807 /* Create the dynamic symbol table section data along with the
5808 string table. We look at all non-local symbols we found for
5809 the normal symbol table and add those. */
5810 dynsymscn = elf_getscn (ld_state.outelf, ld_state.dynsymscnidx);
5811 dynsymdata = elf_newdata (dynsymscn);
5813 dynstrdata = elf_newdata (elf_getscn (ld_state.outelf,
5814 ld_state.dynstrscnidx));
5815 if (dynsymdata == NULL || dynstrdata == NULL)
5816 error (EXIT_FAILURE, 0, gettext ("\
5817 cannot create dynamic symbol table for output file: %s"),
5820 nsym_dyn_allocated = nsym - nsym_local + 1;
5821 dynsymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
5822 nsym_dyn_allocated);
5823 dynsymdata->d_buf = memset (xmalloc (dynsymdata->d_size), '\0',
5824 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
5825 dynsymdata->d_type = ELF_T_SYM;
5826 dynsymdata->d_off = 0;
5827 dynsymdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
5829 /* We need one more array which contains the hash codes of the
5831 hashcodes = (Elf32_Word *) xcalloc (__builtin_popcount ((int) ld_state.hash_style)
5832 * nsym_dyn_allocated,
5833 sizeof (Elf32_Word));
5834 gnuhashcodes = hashcodes;
5835 if (GENERATE_SYSV_HASH)
5836 gnuhashcodes += nsym_dyn_allocated;
5838 /* We have and empty entry at the beginning. */
5841 /* Populate the table. */
5842 for (cnt = nsym_local; cnt < nsym; ++cnt)
5844 XElf_Sym_vardef (sym);
5846 xelf_getsym (symdata, cnt, sym);
5847 assert (sym != NULL);
5849 if (sym->st_shndx == SHN_XINDEX)
5850 error (EXIT_FAILURE, 0, gettext ("\
5851 section index too large in dynamic symbol table"));
5853 /* We do not add the symbol to the dynamic symbol table if
5855 - the symbol is for a file
5856 - it is not externally visible (internal, hidden)
5857 - export_all_dynamic is not set and the symbol is only defined
5858 in the executable (i.e., it is defined, but not (also) in DSO)
5860 Set symstrent[cnt] to NULL in case an entry is ignored. */
5861 if (XELF_ST_TYPE (sym->st_info) == STT_FILE
5862 || XELF_ST_VISIBILITY (sym->st_other) == STV_INTERNAL
5863 || XELF_ST_VISIBILITY (sym->st_other) == STV_HIDDEN
5864 || (!ld_state.export_all_dynamic
5865 && !ndxtosym[cnt]->in_dso && ndxtosym[cnt]->defined))
5867 symstrent[cnt] = NULL;
5871 /* Store the index of the symbol in the dynamic symbol
5872 table. This is a preliminary value in case we use the
5873 GNU-style hash table. */
5874 ndxtosym[cnt]->outdynsymidx = nsym_dyn;
5876 /* Create a new string table entry. */
5877 const char *str = ndxtosym[cnt]->name;
5878 symstrent[cnt] = ebl_strtabadd (dynstrtab, str, 0);
5879 if (GENERATE_SYSV_HASH)
5880 hashcodes[nsym_dyn] = elf_hash (str);
5881 if (GENERATE_GNU_HASH)
5882 gnuhashcodes[nsym_dyn] = elf_gnu_hash (str);
5886 if (ld_state.file_type != relocatable_file_type)
5888 /* Finalize the dynamic string table. */
5889 ebl_strtabfinalize (dynstrtab, dynstrdata);
5891 assert (ld_state.hashscnidx != 0 || ld_state.gnuhashscnidx != 0);
5893 /* Create the GNU-style hash table. */
5894 if (GENERATE_GNU_HASH)
5895 create_gnu_hash (nsym_local, nsym, nsym_dyn, gnuhashcodes);
5897 /* Create the SysV-style hash table. This has to happen
5898 after the GNU-style table is created since
5899 CREATE-GNU-HASH might reorder the dynamic symbol table. */
5900 if (GENERATE_SYSV_HASH)
5901 create_hash (nsym_local, nsym, nsym_dyn, hashcodes);
5904 /* Add the version information. */
5905 if (versymdata != NULL)
5906 for (cnt = nsym_local; cnt < nsym; ++cnt)
5907 if (symstrent[cnt] != NULL)
5909 struct symbol *symp = ndxtosym[cnt];
5911 /* Synthetic symbols (i.e., those with no file attached)
5912 have no version information. */
5913 if (symp->file != NULL && symp->file->verdefdata != NULL)
5917 gelf_getversym (symp->file->versymdata, symp->symidx,
5920 (void) gelf_update_versym (versymdata, symp->outdynsymidx,
5921 &symp->file->verdefused[versym]);
5925 /* XXX Add support for version definitions. */
5926 GElf_Versym global = VER_NDX_GLOBAL;
5927 (void) gelf_update_versym (versymdata, nsym_dyn, &global);
5931 /* Update the information about the symbol section. */
5932 if (versymdata != NULL)
5934 /* Correct the size now that we know how many entries the
5935 dynamic symbol table has. */
5936 versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
5939 /* Add the reference to the symbol table. */
5940 xelf_getshdr (versymscn, shdr);
5941 assert (shdr != NULL);
5943 shdr->sh_link = ld_state.dynsymscnidx;
5945 (void) xelf_update_shdr (versymscn, shdr);
5949 if (ld_state.file_type != relocatable_file_type)
5951 /* Now put the names in. */
5952 for (cnt = nsym_local; cnt < nsym; ++cnt)
5953 if (symstrent[cnt] != NULL)
5955 XElf_Sym_vardef (sym);
5956 size_t dynidx = ndxtosym[cnt]->outdynsymidx;
5960 memcpy (xelf_getsym (dynsymdata, dynidx, sym),
5961 xelf_getsym (symdata, cnt, osym),
5964 xelf_getsym (symdata, cnt, sym);
5965 assert (sym != NULL);
5968 sym->st_name = ebl_strtaboffset (symstrent[cnt]);
5970 (void) xelf_update_sym (dynsymdata, dynidx, sym);
5975 /* Create the required version section. */
5976 if (ld_state.verneedscnidx != 0)
5978 Elf_Scn *verneedscn;
5979 Elf_Data *verneeddata;
5980 struct usedfiles *runp;
5981 size_t verneed_size = xelf_fsize (ld_state.outelf, ELF_T_VNEED, 1);
5982 size_t vernaux_size = xelf_fsize (ld_state.outelf, ELF_T_VNAUX, 1);
5986 verneedscn = elf_getscn (ld_state.outelf, ld_state.verneedscnidx);
5987 xelf_getshdr (verneedscn, shdr);
5988 verneeddata = elf_newdata (verneedscn);
5989 if (shdr == NULL || verneeddata == NULL)
5990 error (EXIT_FAILURE, 0,
5991 gettext ("cannot create versioning data: %s"),
5994 verneeddata->d_size = (ld_state.nverdeffile * verneed_size
5995 + ld_state.nverdefused * vernaux_size);
5996 verneeddata->d_buf = xmalloc (verneeddata->d_size);
5997 verneeddata->d_type = ELF_T_VNEED;
5998 verneeddata->d_align = xelf_fsize (ld_state.outelf, ELF_T_WORD, 1);
5999 verneeddata->d_off = 0;
6002 ntotal = ld_state.nverdeffile;
6003 runp = ld_state.dsofiles->next;
6006 offset = create_verneed_data (offset, verneeddata, runp,
6010 while (ntotal > 0 && runp != ld_state.dsofiles->next);
6014 runp = ld_state.needed->next;
6017 offset = create_verneed_data (offset, verneeddata, runp,
6021 while (ntotal > 0 && runp != ld_state.needed->next);
6024 assert (offset == verneeddata->d_size);
6026 /* Add the needed information to the section header. */
6027 shdr->sh_link = ld_state.dynstrscnidx;
6028 shdr->sh_info = ld_state.nverdeffile;
6029 (void) xelf_update_shdr (verneedscn, shdr);
6032 /* Adjust the section size. */
6033 dynsymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym_dyn);
6034 if (versymdata != NULL)
6035 versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
6038 /* Add the remaining information to the section header. */
6039 xelf_getshdr (dynsymscn, shdr);
6040 /* There is always exactly one local symbol. */
6042 /* Reference the string table. */
6043 shdr->sh_link = ld_state.dynstrscnidx;
6044 /* Write the updated info back. */
6045 (void) xelf_update_shdr (dynsymscn, shdr);
6048 /* We don't need the string table anymore. */
6051 /* Remember the total number of symbols in the dynamic symbol table. */
6052 ld_state.ndynsym = nsym_dyn;
6054 /* Fill in the section header information. */
6055 symscn = elf_getscn (ld_state.outelf, ld_state.symscnidx);
6056 xelf_getshdr (symscn, shdr);
6058 error (EXIT_FAILURE, 0,
6059 gettext ("cannot create symbol table for output file: %s"),
6062 shdr->sh_type = SHT_SYMTAB;
6063 shdr->sh_link = ld_state.strscnidx;
6064 shdr->sh_info = nsym_local;
6065 shdr->sh_entsize = xelf_fsize (ld_state.outelf, ELF_T_SYM, 1);
6067 (void) xelf_update_shdr (symscn, shdr);
6070 /* Add names for the generated sections. */
6071 if (ld_state.symscnidx != 0)
6072 symtab_ent = ebl_strtabadd (ld_state.shstrtab, ".symtab", 8);
6073 if (ld_state.xndxscnidx != 0)
6074 xndx_ent = ebl_strtabadd (ld_state.shstrtab, ".symtab_shndx", 14);
6075 if (ld_state.strscnidx != 0)
6076 strtab_ent = ebl_strtabadd (ld_state.shstrtab, ".strtab", 8);
6077 /* At this point we would have to test for failures in the
6078 allocation. But we skip this. First, the problem will be caught
6079 later when doing more allocations for the section header table.
6080 Even if this would not be the case all that would happen is that
6081 the section names are empty. The binary would still be usable if
6082 it is an executable or a DSO. Not adding the test here saves
6083 quite a bit of code. */
6086 /* Finally create the section for the section header string table. */
6087 shstrtab_scn = elf_newscn (ld_state.outelf);
6088 shstrtab_ndx = elf_ndxscn (shstrtab_scn);
6089 if (unlikely (shstrtab_ndx == SHN_UNDEF))
6090 error (EXIT_FAILURE, 0,
6091 gettext ("cannot create section header string section: %s"),
6094 /* Add the name of the section to the string table. */
6095 shstrtab_ent = ebl_strtabadd (ld_state.shstrtab, ".shstrtab", 10);
6096 if (unlikely (shstrtab_ent == NULL))
6097 error (EXIT_FAILURE, errno,
6098 gettext ("cannot create section header string section"));
6100 /* Finalize the section header string table. */
6101 data = elf_newdata (shstrtab_scn);
6103 error (EXIT_FAILURE, 0,
6104 gettext ("cannot create section header string section: %s"),
6106 ebl_strtabfinalize (ld_state.shstrtab, data);
6108 /* Now we know the string offsets for all section names. */
6109 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
6110 if (ld_state.allsections[cnt]->scnidx != 0)
6114 scn = elf_getscn (ld_state.outelf, ld_state.allsections[cnt]->scnidx);
6116 xelf_getshdr (scn, shdr);
6117 assert (shdr != NULL);
6119 shdr->sh_name = ebl_strtaboffset (ld_state.allsections[cnt]->nameent);
6121 if (xelf_update_shdr (scn, shdr) == 0)
6125 /* Add the names for the generated sections to the respective
6127 if (symtab_ent != NULL)
6129 Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.symscnidx);
6131 xelf_getshdr (scn, shdr);
6132 /* This cannot fail, we already accessed the header before. */
6133 assert (shdr != NULL);
6135 shdr->sh_name = ebl_strtaboffset (symtab_ent);
6137 (void) xelf_update_shdr (scn, shdr);
6139 if (xndx_ent != NULL)
6141 Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.xndxscnidx);
6143 xelf_getshdr (scn, shdr);
6144 /* This cannot fail, we already accessed the header before. */
6145 assert (shdr != NULL);
6147 shdr->sh_name = ebl_strtaboffset (xndx_ent);
6149 (void) xelf_update_shdr (scn, shdr);
6151 if (strtab_ent != NULL)
6153 Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.strscnidx);
6155 xelf_getshdr (scn, shdr);
6156 /* This cannot fail, we already accessed the header before. */
6157 assert (shdr != NULL);
6159 shdr->sh_name = ebl_strtaboffset (strtab_ent);
6161 (void) xelf_update_shdr (scn, shdr);
6164 /* And the section header table section itself. */
6165 xelf_getshdr (shstrtab_scn, shdr);
6167 error (EXIT_FAILURE, 0,
6168 gettext ("cannot create section header string section: %s"),
6171 shdr->sh_name = ebl_strtaboffset (shstrtab_ent);
6172 shdr->sh_type = SHT_STRTAB;
6174 if (unlikely (xelf_update_shdr (shstrtab_scn, shdr) == 0))
6175 error (EXIT_FAILURE, 0,
6176 gettext ("cannot create section header string section: %s"),
6180 /* Add the correct section header info to the section group sections. */
6181 groups = ld_state.groups;
6182 while (groups != NULL)
6184 Elf_Scn *scn = elf_getscn (ld_state.outelf, groups->outscnidx);
6185 xelf_getshdr (scn, shdr);
6186 assert (shdr != NULL);
6188 shdr->sh_name = ebl_strtaboffset (groups->nameent);
6189 shdr->sh_type = SHT_GROUP;
6191 shdr->sh_link = ld_state.symscnidx;
6192 shdr->sh_entsize = sizeof (Elf32_Word);
6194 /* Determine the index for the signature symbol. */
6196 = groups->symbol->file->symindirect[groups->symbol->symidx];
6199 assert (groups->symbol->file->symref[groups->symbol->symidx]
6201 si = groups->symbol->file->symref[groups->symbol->symidx]->outsymidx;
6204 shdr->sh_info = ld_state.dblindirect[si];
6206 (void) xelf_update_shdr (scn, shdr);
6208 struct scngroup *oldp = groups;
6209 groups = groups->next;
6214 if (ld_state.file_type != relocatable_file_type)
6216 /* Every executable needs a program header. The number of entries
6217 varies. One exists for each segment. Each SHT_NOTE section gets
6218 one, too. For dynamically linked executables we have to create
6219 one for the program header, the interpreter, and the dynamic
6220 section. First count the number of segments.
6222 XXX Determine whether the segment is non-empty. */
6225 /* We always add a PT_GNU_stack entry. */
6228 struct output_segment *segment = ld_state.output_segments;
6229 while (segment != NULL)
6232 segment = segment->next;
6235 /* Add the number of SHT_NOTE sections. We counted them earlier. */
6236 nphdr += ld_state.nnotesections;
6238 /* If we create a DSO or the file is linked against DSOs we have
6239 at least one more entry: DYNAMIC. If an interpreter is
6240 specified we add PHDR and INTERP, too. */
6241 if (dynamically_linked_p ())
6245 if (ld_state.interp != NULL || ld_state.file_type != dso_file_type)
6249 /* If we need a TLS segment we need an entry for that. */
6250 if (ld_state.need_tls)
6253 /* Create the program header structure. */
6254 XElf_Phdr_vardef (phdr);
6255 if (xelf_newphdr (ld_state.outelf, nphdr) == 0)
6256 error (EXIT_FAILURE, 0, gettext ("cannot create program header: %s"),
6260 /* Determine the section sizes and offsets. We have to do this
6261 to be able to determine the memory layout (which normally
6262 differs from the file layout). */
6263 if (elf_update (ld_state.outelf, ELF_C_NULL) == -1)
6264 error (EXIT_FAILURE, 0, gettext ("while determining file layout: %s"),
6268 /* Now determine the memory addresses of all the sections and
6270 Elf32_Word nsec = 0;
6271 Elf_Scn *scn = elf_getscn (ld_state.outelf,
6272 ld_state.allsections[nsec]->scnidx);
6273 xelf_getshdr (scn, shdr);
6274 assert (shdr != NULL);
6276 /* The address we start with is the offset of the first (not
6278 XElf_Addr addr = shdr->sh_offset;
6279 XElf_Addr tls_offset = 0;
6280 XElf_Addr tls_start = ~((XElf_Addr) 0);
6281 XElf_Addr tls_end = 0;
6282 XElf_Off tls_filesize = 0;
6283 XElf_Addr tls_align = 0;
6285 /* The index of the first loadable segment. */
6287 if (dynamically_linked_p ())
6290 if (ld_state.interp != NULL
6291 || ld_state.file_type != dso_file_type)
6295 segment = ld_state.output_segments;
6296 while (segment != NULL)
6298 struct output_rule *orule;
6299 bool first_section = true;
6300 XElf_Off nobits_size = 0;
6301 XElf_Off memsize = 0;
6303 /* The minimum alignment is a page size. */
6304 segment->align = ld_state.pagesize;
6306 for (orule = segment->output_rules; orule != NULL;
6307 orule = orule->next)
6308 if (orule->tag == output_section)
6310 /* See whether this output rule corresponds to the next
6311 section. Yes, this is a pointer comparison. */
6312 if (ld_state.allsections[nsec]->name
6313 != orule->val.section.name)
6314 /* No, ignore this output rule. */
6317 /* We assign addresses only in segments which are actually
6319 if (segment->mode != 0)
6321 /* Adjust the offset of the input sections. */
6322 struct scninfo *isect;
6323 struct scninfo *first;
6325 isect = first = ld_state.allsections[nsec]->last;
6328 isect->offset += addr;
6329 while ((isect = isect->next) != first);
6331 /* Set the address of current section. */
6332 shdr->sh_addr = addr;
6334 /* Write the result back. */
6335 (void) xelf_update_shdr (scn, shdr);
6337 /* Remember the address. */
6338 ld_state.allsections[nsec]->addr = addr;
6340 /* Handle TLS sections. */
6341 if (unlikely (shdr->sh_flags & SHF_TLS))
6343 if (tls_start > addr)
6346 tls_offset = shdr->sh_offset;
6348 if (tls_end < addr + shdr->sh_size)
6349 tls_end = addr + shdr->sh_size;
6350 if (shdr->sh_type != SHT_NOBITS)
6351 tls_filesize += shdr->sh_size;
6352 if (shdr->sh_addralign > tls_align)
6353 tls_align = shdr->sh_addralign;
6359 /* The first segment starts at offset zero. */
6360 if (segment == ld_state.output_segments)
6362 segment->offset = 0;
6363 segment->addr = addr - shdr->sh_offset;
6367 segment->offset = shdr->sh_offset;
6368 segment->addr = addr;
6371 /* Determine the maximum alignment requirement. */
6372 segment->align = MAX (segment->align, shdr->sh_addralign);
6374 first_section = false;
6377 /* NOBITS TLS sections are not laid out in address space
6378 along with the other sections. */
6379 if (shdr->sh_type != SHT_NOBITS
6380 || (shdr->sh_flags & SHF_TLS) == 0)
6382 memsize = (shdr->sh_offset - segment->offset
6384 if (nobits_size != 0 && shdr->sh_type != SHT_NOTE)
6385 error (EXIT_FAILURE, 0, gettext ("\
6386 internal error: non-nobits section follows nobits section"));
6387 if (shdr->sh_type == SHT_NOBITS)
6388 nobits_size += shdr->sh_size;
6391 /* Determine the new address which is computed using
6392 the difference of the offsets on the sections. Note
6393 that this assumes that the sections following each
6394 other in the section header table are also
6395 consecutive in the file. This is true here because
6396 libelf constructs files this way. */
6397 XElf_Off oldoff = shdr->sh_offset;
6399 if (++nsec >= ld_state.nallsections)
6402 scn = elf_getscn (ld_state.outelf,
6403 ld_state.allsections[nsec]->scnidx);
6404 xelf_getshdr (scn, shdr);
6405 assert (shdr != NULL);
6407 /* This is the new address resulting from the offsets
6409 assert (oldoff <= shdr->sh_offset);
6410 addr += shdr->sh_offset - oldoff;
6414 assert (orule->tag == output_assignment);
6416 if (strcmp (orule->val.assignment->variable, ".") == 0)
6417 /* This is a change of the address. */
6418 addr = eval_expression (orule->val.assignment->expression,
6420 else if (orule->val.assignment->sym != NULL)
6422 /* This symbol is used. Update the symbol table
6424 XElf_Sym_vardef (sym);
6427 /* Note that we do not have to use
6428 xelf_getsymshndx since we only update the
6429 symbol address, not the section
6431 idx = dblindirect[orule->val.assignment->sym->outsymidx];
6432 xelf_getsym (symdata, idx, sym);
6433 sym->st_value = addr;
6434 (void) xelf_update_sym (symdata, idx, sym);
6436 idx = orule->val.assignment->sym->outdynsymidx;
6439 assert (dynsymdata != NULL);
6440 xelf_getsym (dynsymdata, idx, sym);
6441 sym->st_value = addr;
6442 (void) xelf_update_sym (dynsymdata, idx, sym);
6447 /* Store the segment parameter for loadable segments. */
6448 if (segment->mode != 0)
6450 xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
6452 phdr->p_type = PT_LOAD;
6453 phdr->p_offset = segment->offset;
6454 phdr->p_vaddr = segment->addr;
6455 phdr->p_paddr = phdr->p_vaddr;
6456 phdr->p_filesz = memsize - nobits_size;
6457 phdr->p_memsz = memsize;
6458 phdr->p_flags = segment->mode;
6459 phdr->p_align = segment->align;
6461 (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
6465 segment = segment->next;
6468 /* Create the other program header entries. */
6469 xelf_getehdr (ld_state.outelf, ehdr);
6470 assert (ehdr != NULL);
6472 /* Add the TLS information. */
6473 if (ld_state.need_tls)
6475 xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
6476 phdr->p_type = PT_TLS;
6477 phdr->p_offset = tls_offset;
6478 phdr->p_vaddr = tls_start;
6479 phdr->p_paddr = tls_start;
6480 phdr->p_filesz = tls_filesize;
6481 phdr->p_memsz = tls_end - tls_start;
6482 phdr->p_flags = PF_R;
6483 phdr->p_align = tls_align;
6484 ld_state.tls_tcb = tls_end;
6485 ld_state.tls_start = tls_start;
6487 (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
6491 /* Add the stack information. */
6492 xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
6493 phdr->p_type = PT_GNU_STACK;
6499 phdr->p_flags = (PF_R | PF_W
6500 | (ld_state.execstack == execstack_true ? PF_X : 0));
6501 phdr->p_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
6503 (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
6507 /* Adjust the addresses in the address fields of the symbol
6508 records according to the load addresses of the sections. */
6509 if (ld_state.need_symtab)
6510 for (cnt = 1; cnt < nsym; ++cnt)
6512 XElf_Sym_vardef (sym);
6515 xelf_getsymshndx (symdata, xndxdata, cnt, sym, shndx);
6516 assert (sym != NULL);
6518 if (sym->st_shndx != SHN_XINDEX)
6519 shndx = sym->st_shndx;
6521 if ((shndx > SHN_UNDEF && shndx < SHN_LORESERVE)
6522 || shndx > SHN_HIRESERVE)
6524 /* Note we subtract 1 from the section index since ALLSECTIONS
6525 does not store the dummy section with offset zero. */
6526 sym->st_value += ld_state.allsections[shndx - 1]->addr;
6528 /* We don't have to use 'xelf_update_symshndx' since the
6529 section number doesn't change. */
6530 (void) xelf_update_sym (symdata, cnt, sym);
6534 if (ld_state.need_dynsym)
6535 for (cnt = 1; cnt < nsym_dyn; ++cnt)
6537 XElf_Sym_vardef (sym);
6539 xelf_getsym (dynsymdata, cnt, sym);
6540 assert (sym != NULL);
6542 if (sym->st_shndx > SHN_UNDEF && sym->st_shndx < SHN_LORESERVE)
6544 /* Note we subtract 1 from the section index since ALLSECTIONS
6545 does not store the dummy section with offset zero. */
6546 sym->st_value += ld_state.allsections[sym->st_shndx - 1]->addr;
6548 /* We don't have to use 'xelf_update_symshndx' since the
6549 section number doesn't change. */
6550 (void) xelf_update_sym (dynsymdata, cnt, sym);
6554 /* Now is a good time to determine the values of all the symbols
6556 // XXX This loop is very inefficient. The hash tab iterator also
6557 // returns all symbols in DSOs.
6560 while ((se = ld_symbol_tab_iterate (&ld_state.symbol_tab, &p)) != NULL)
6563 XElf_Sym_vardef (sym);
6567 if (se->outdynsymidx != 0)
6569 xelf_getsym (dynsymdata, se->outdynsymidx, sym);
6570 assert (sym != NULL);
6571 addr = sym->st_value;
6573 else if (se->outsymidx != 0)
6575 assert (dblindirect[se->outsymidx] != 0);
6576 xelf_getsym (symdata, dblindirect[se->outsymidx], sym);
6577 assert (sym != NULL);
6578 addr = sym->st_value;
6583 se->merge.value = addr;
6586 /* Complete the header of the .rel.dyn/.rela.dyn section. Point
6587 to the symbol table. The sh_info field is left zero since
6588 there is no specific section the contained relocations are
6590 if (ld_state.reldynscnidx != 0)
6592 assert (ld_state.dynsymscnidx != 0);
6593 scn = elf_getscn (ld_state.outelf, ld_state.reldynscnidx);
6594 xelf_getshdr (scn, shdr);
6595 assert (shdr != NULL);
6597 shdr->sh_link = ld_state.dynsymscnidx;
6599 (void) xelf_update_shdr (scn, shdr);
6602 /* Fill in the dynamic segment/section. */
6603 if (dynamically_linked_p ())
6608 if (ld_state.interp != NULL || ld_state.file_type != dso_file_type)
6610 assert (ld_state.interpscnidx != 0);
6611 xelf_getshdr (elf_getscn (ld_state.outelf,
6612 ld_state.interpscnidx), shdr);
6613 assert (shdr != NULL);
6615 xelf_getphdr_ptr (ld_state.outelf, idx, phdr);
6616 phdr->p_type = PT_PHDR;
6617 phdr->p_offset = ehdr->e_phoff;
6618 phdr->p_vaddr = ld_state.output_segments->addr + phdr->p_offset;
6619 phdr->p_paddr = phdr->p_vaddr;
6620 phdr->p_filesz = ehdr->e_phnum * ehdr->e_phentsize;
6621 phdr->p_memsz = phdr->p_filesz;
6622 phdr->p_flags = 0; /* No need to set PF_R or so. */
6623 phdr->p_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
6625 (void) xelf_update_phdr (ld_state.outelf, idx, phdr);
6628 /* The interpreter string. */
6629 xelf_getphdr_ptr (ld_state.outelf, idx, phdr);
6630 phdr->p_type = PT_INTERP;
6631 phdr->p_offset = shdr->sh_offset;
6632 phdr->p_vaddr = shdr->sh_addr;
6633 phdr->p_paddr = phdr->p_vaddr;
6634 phdr->p_filesz = shdr->sh_size;
6635 phdr->p_memsz = phdr->p_filesz;
6636 phdr->p_flags = 0; /* No need to set PF_R or so. */
6637 phdr->p_align = 1; /* It's a string. */
6639 (void) xelf_update_phdr (ld_state.outelf, idx, phdr);
6643 /* The pointer to the dynamic section. We this we need to
6644 get the information for the dynamic section first. */
6645 assert (ld_state.dynamicscnidx);
6646 outscn = elf_getscn (ld_state.outelf, ld_state.dynamicscnidx);
6647 xelf_getshdr (outscn, shdr);
6648 assert (shdr != NULL);
6650 xelf_getphdr_ptr (ld_state.outelf, idx, phdr);
6651 phdr->p_type = PT_DYNAMIC;
6652 phdr->p_offset = shdr->sh_offset;
6653 phdr->p_vaddr = shdr->sh_addr;
6654 phdr->p_paddr = phdr->p_vaddr;
6655 phdr->p_filesz = shdr->sh_size;
6656 phdr->p_memsz = phdr->p_filesz;
6657 phdr->p_flags = 0; /* No need to set PF_R or so. */
6658 phdr->p_align = shdr->sh_addralign;
6660 (void) xelf_update_phdr (ld_state.outelf, idx, phdr);
6662 /* Fill in the reference to the .dynstr section. */
6663 assert (ld_state.dynstrscnidx != 0);
6664 shdr->sh_link = ld_state.dynstrscnidx;
6665 (void) xelf_update_shdr (outscn, shdr);
6667 /* And fill the remaining entries. */
6668 Elf_Data *dyndata = elf_getdata (outscn, NULL);
6669 assert (dyndata != NULL);
6671 /* Add the DT_NEEDED entries. */
6672 if (ld_state.ndsofiles > 0)
6674 struct usedfiles *runp = ld_state.dsofiles->next;
6677 if (runp->used || !runp->as_needed)
6679 /* Add the position-dependent flag if necessary. */
6681 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6682 DT_POSFLAG_1, DF_P1_LAZYLOAD);
6684 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6686 ebl_strtaboffset (runp->sonameent));
6688 while ((runp = runp->next) != ld_state.dsofiles->next);
6691 /* We can finish the DT_RUNPATH/DT_RPATH entries now. */
6692 if (ld_state.rxxpath_strent != NULL)
6693 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6694 ld_state.rxxpath_tag,
6695 ebl_strtaboffset (ld_state.rxxpath_strent));
6697 /* Reference to initialization and finalization functions. */
6698 // XXX This code depends on symbol table being relocated.
6699 if (ld_state.init_symbol != NULL)
6701 XElf_Sym_vardef (sym);
6703 if (ld_state.need_symtab)
6704 xelf_getsym (symdata,
6705 dblindirect[ld_state.init_symbol->outsymidx],
6708 xelf_getsym (dynsymdata, ld_state.init_symbol->outdynsymidx,
6710 assert (sym != NULL);
6712 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6713 DT_INIT, sym->st_value);
6715 if (ld_state.fini_symbol != NULL)
6717 XElf_Sym_vardef (sym);
6719 if (ld_state.need_symtab)
6720 xelf_getsym (symdata,
6721 dblindirect[ld_state.fini_symbol->outsymidx],
6724 xelf_getsym (dynsymdata, ld_state.fini_symbol->outdynsymidx,
6726 assert (sym != NULL);
6728 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6729 DT_FINI, sym->st_value);
6731 // XXX Support init,fini,preinit arrays
6733 /* The hash table which comes with dynamic symbol table. */
6734 xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.hashscnidx),
6736 assert (shdr != NULL);
6737 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_HASH,
6740 /* Reference to the symbol table section. */
6741 assert (ld_state.dynsymscnidx != 0);
6742 xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.dynsymscnidx),
6744 assert (shdr != NULL);
6745 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_SYMTAB,
6748 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_SYMENT,
6749 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
6751 /* And the string table which comes with it. */
6752 xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.dynstrscnidx),
6754 assert (shdr != NULL);
6755 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_STRTAB,
6758 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_STRSZ,
6761 /* Add the entries related to the .plt. */
6762 if (ld_state.nplt > 0)
6764 // XXX Make this work if there is no PLT
6765 xelf_getshdr (elf_getscn (ld_state.outelf,
6766 ld_state.gotpltscnidx), shdr);
6767 assert (shdr != NULL);
6768 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6769 // XXX This should probably be machine
6771 DT_PLTGOT, shdr->sh_addr);
6773 xelf_getshdr (elf_getscn (ld_state.outelf,
6774 ld_state.pltrelscnidx), shdr);
6775 assert (shdr != NULL);
6776 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6777 DT_PLTRELSZ, shdr->sh_size);
6779 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6780 DT_JMPREL, shdr->sh_addr);
6782 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6783 DT_PLTREL, REL_TYPE (statep));
6786 if (ld_state.relsize_total > 0)
6788 int rel = REL_TYPE (statep);
6789 xelf_getshdr (elf_getscn (ld_state.outelf,
6790 ld_state.reldynscnidx), shdr);
6791 assert (shdr != NULL);
6792 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6793 rel, shdr->sh_addr);
6795 /* Trick ahead. Use arithmetic to get the right tag.
6796 We check the validity of this assumption in the asserts. */
6797 assert (DT_RELASZ - DT_RELA == 1);
6798 assert (DT_RELSZ - DT_REL == 1);
6799 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6800 rel + 1, shdr->sh_size);
6802 /* Similar for the entry size tag. */
6803 assert (DT_RELAENT - DT_RELA == 2);
6804 assert (DT_RELENT - DT_REL == 2);
6805 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6808 ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
6809 : xelf_fsize (ld_state.outelf, ELF_T_RELA,
6813 if (ld_state.verneedscnidx != 0)
6815 xelf_getshdr (elf_getscn (ld_state.outelf,
6816 ld_state.verneedscnidx), shdr);
6817 assert (shdr != NULL);
6818 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6819 DT_VERNEED, shdr->sh_addr);
6821 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6822 DT_VERNEEDNUM, ld_state.nverdeffile);
6825 if (ld_state.versymscnidx != 0)
6827 xelf_getshdr (elf_getscn (ld_state.outelf,
6828 ld_state.versymscnidx), shdr);
6829 assert (shdr != NULL);
6830 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6831 DT_VERSYM, shdr->sh_addr);
6834 /* We always create the DT_DEBUG entry. */
6835 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_DEBUG, 0);
6836 assert (ld_state.ndynamic_filled < ld_state.ndynamic);
6838 /* Add the flag words if necessary. */
6839 if (ld_state.dt_flags != 0)
6840 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_FLAGS,
6843 /* Create entry for the DT_FLAGS_1 flag. */
6844 if (ld_state.dt_flags_1 != 0)
6845 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6846 DT_FLAGS_1, ld_state.dt_flags_1);
6848 /* Create entry for the DT_FEATURE_1 flag. */
6849 if (ld_state.dt_feature_1 != 0)
6850 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6851 DT_FEATURE_1, ld_state.dt_feature_1);
6853 assert (ld_state.ndynamic_filled <= ld_state.ndynamic);
6858 // XXX The following code isn't nice. We use two different
6859 // mechanisms to handle relocations, one for relocatable files, one
6860 // for executables and DSOs. Maybe this is the best method but also
6861 // maybe it can be somewhat unified.
6863 /* Now that we created the symbol table we can add the reference to
6864 it in the sh_link field of the section headers of the relocation
6866 while (rellist != NULL)
6868 assert (ld_state.file_type == relocatable_file_type);
6871 outscn = elf_getscn (ld_state.outelf, rellist->scnidx);
6872 xelf_getshdr (outscn, shdr);
6873 /* This must not fail since we did it before. */
6874 assert (shdr != NULL);
6876 /* Remember the symbol table which belongs to the relocation section. */
6877 shdr->sh_link = ld_state.symscnidx;
6879 /* And the reference to the section which is relocated by this
6880 relocation section. We use the info from the first input
6881 section but all records should have the same information. */
6883 rellist->scninfo->fileinfo->scninfo[SCNINFO_SHDR (rellist->scninfo->shdr).sh_info].outscnndx;
6886 /* Perform the actual relocations. We only have to adjust
6887 offsets and symbol indices. */
6888 RELOCATE_SECTION (statep, outscn, rellist->scninfo, dblindirect);
6890 /* Store the changes. */
6891 (void) xelf_update_shdr (outscn, shdr);
6893 /* Up to the next relocation section. */
6894 rellist = rellist->next;
6897 if (ld_state.rellist != NULL)
6899 assert (ld_state.file_type != relocatable_file_type);
6900 /* Create the relocations for the output file. */
6901 CREATE_RELOCATIONS (statep, dblindirect);
6905 /* We need the ELF header once more. */
6906 xelf_getehdr (ld_state.outelf, ehdr);
6907 assert (ehdr != NULL);
6909 /* Set the section header string table index. */
6910 if (likely (shstrtab_ndx < SHN_HIRESERVE)
6911 && likely (shstrtab_ndx != SHN_XINDEX))
6912 ehdr->e_shstrndx = shstrtab_ndx;
6915 /* We have to put the section index in the sh_link field of the
6916 zeroth section header. */
6917 Elf_Scn *scn = elf_getscn (ld_state.outelf, 0);
6919 xelf_getshdr (scn, shdr);
6920 if (unlikely (shdr == NULL))
6921 error (EXIT_FAILURE, 0,
6922 gettext ("cannot get header of 0th section: %s"),
6925 shdr->sh_link = shstrtab_ndx;
6927 (void) xelf_update_shdr (scn, shdr);
6929 ehdr->e_shstrndx = SHN_XINDEX;
6932 if (ld_state.file_type != relocatable_file_type)
6933 /* DSOs and executables have to define the entry point symbol. */
6934 ehdr->e_entry = find_entry_point ();
6936 if (unlikely (xelf_update_ehdr (ld_state.outelf, ehdr) == 0))
6937 error (EXIT_FAILURE, 0,
6938 gettext ("cannot update ELF header: %s"),
6942 /* Free the data which we don't need anymore. */
6943 free (ld_state.dblindirect);
6946 /* Finalize the .plt section and what else belongs to it. */
6947 FINALIZE_PLT (statep, nsym, nsym_local, ndxtosym);
6950 /* Finally, if we have to compute the build ID. */
6951 if (ld_state.build_id != NULL)
6952 compute_build_id ();
6955 /* We don't need the map from the symbol table index to the symbol
6956 structure anymore. */
6963 /* This is a function which must be specified in all backends. */
6965 ld_generic_relocate_section (struct ld_state *statep, Elf_Scn *outscn,
6966 struct scninfo *firstp,
6967 const Elf32_Word *dblindirect)
6969 error (EXIT_FAILURE, 0, gettext ("\
6970 linker backend didn't specify function to relocate section"));
6975 /* Finalize the output file. */
6977 ld_generic_finalize (struct ld_state *statep)
6979 /* Write out the ELF file data. */
6980 if (elf_update (ld_state.outelf, ELF_C_WRITE) == -1)
6981 error (EXIT_FAILURE, 0, gettext ("while writing output file: %s"),
6984 /* Free the resources. */
6985 if (elf_end (ld_state.outelf) != 0)
6986 error (EXIT_FAILURE, 0, gettext ("while finishing output file: %s"),
6989 /* Get the file status of the temporary file. */
6990 struct stat temp_st;
6991 if (fstat (ld_state.outfd, &temp_st) != 0)
6992 error (EXIT_FAILURE, errno, gettext ("cannot stat output file"));
6994 /* Now it's time to rename the file. Remove an old existing file
6996 if (rename (ld_state.tempfname, ld_state.outfname) != 0)
6997 /* Something went wrong. */
6998 error (EXIT_FAILURE, errno, gettext ("cannot rename output file"));
7000 /* Make sure the output file is really the one we created. */
7002 if (stat (ld_state.outfname, &new_st) != 0
7003 || new_st.st_ino != temp_st.st_ino
7004 || new_st.st_dev != temp_st.st_dev)
7006 /* Wow, somebody overwrote the output file, probably some intruder. */
7007 unlink (ld_state.outfname);
7008 error (EXIT_FAILURE, 0, gettext ("\
7009 WARNING: temporary output file overwritten before linking finished"));
7012 /* Close the file descriptor. */
7013 (void) close (ld_state.outfd);
7015 /* Signal the cleanup handler that the file is correctly created. */
7016 ld_state.tempfname = NULL;
7023 ld_generic_special_section_number_p (struct ld_state *statep, size_t number)
7025 /* There are no special section numbers in the gABI. */
7031 ld_generic_section_type_p (struct ld_state *statep, GElf_Word type)
7034 /* XXX Enable the following two when implemented. */
7035 // || type == SHT_GNU_LIBLIST
7036 // || type == SHT_CHECKSUM
7037 /* XXX Eventually include SHT_SUNW_move, SHT_SUNW_COMDAT, and
7038 SHT_SUNW_syminfo. */
7039 || (type >= SHT_GNU_verdef && type <= SHT_GNU_versym))
7047 ld_generic_dynamic_section_flags (struct ld_state *statep)
7049 /* By default the .dynamic section is writable (and is of course
7050 loaded). Few architecture differ from this. */
7051 return SHF_ALLOC | SHF_WRITE;
7056 ld_generic_initialize_plt (struct ld_state *statep, Elf_Scn *scn)
7058 /* This cannot be implemented generally. There should have been a
7059 machine dependent implementation and we should never have arrived
7061 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7067 ld_generic_initialize_pltrel (struct ld_state *statep, Elf_Scn *scn)
7069 /* This cannot be implemented generally. There should have been a
7070 machine dependent implementation and we should never have arrived
7072 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7073 "initialize_pltrel");
7078 ld_generic_initialize_got (struct ld_state *statep, Elf_Scn *scn)
7080 /* This cannot be implemented generally. There should have been a
7081 machine dependent implementation and we should never have arrived
7083 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7089 ld_generic_initialize_gotplt (struct ld_state *statep, Elf_Scn *scn)
7091 /* This cannot be implemented generally. There should have been a
7092 machine dependent implementation and we should never have arrived
7094 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7095 "initialize_gotplt");
7100 ld_generic_finalize_plt (struct ld_state *statep, size_t nsym, size_t nsym_dyn,
7101 struct symbol **ndxtosymp)
7103 /* By default we assume that nothing has to be done. */
7108 ld_generic_rel_type (struct ld_state *statep)
7110 /* This cannot be implemented generally. There should have been a
7111 machine dependent implementation and we should never have arrived
7113 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7115 /* Just to keep the compiler calm. */
7121 ld_generic_count_relocations (struct ld_state *statep, struct scninfo *scninfo)
7123 /* This cannot be implemented generally. There should have been a
7124 machine dependent implementation and we should never have arrived
7126 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7127 "count_relocations");
7132 ld_generic_create_relocations (struct ld_state *statep,
7133 const Elf32_Word *dblindirect)
7135 /* This cannot be implemented generally. There should have been a
7136 machine dependent implementation and we should never have arrived
7138 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7139 "create_relocations");