1 /* Copyright (C) 2001-2011 Red Hat, Inc.
2 This file is part of elfutils.
3 Written by Ulrich Drepper <drepper@redhat.com>, 2001.
5 This file is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 elfutils is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
33 #include <stdio_ext.h>
37 #include <sys/param.h>
40 #include <elf-knowledge.h>
48 /* Header of .eh_frame_hdr section. */
49 struct unw_eh_frame_hdr
51 unsigned char version;
52 unsigned char eh_frame_ptr_enc;
53 unsigned char fde_count_enc;
54 unsigned char table_enc;
56 #define EH_FRAME_HDR_VERSION 1
59 /* Prototypes for local functions. */
60 static const char **ld_generic_lib_extensions (struct ld_state *)
61 __attribute__ ((__const__));
62 static int ld_generic_file_close (struct usedfiles *fileinfo,
63 struct ld_state *statep);
64 static int ld_generic_file_process (int fd, struct usedfiles *fileinfo,
65 struct ld_state *statep,
66 struct usedfiles **nextp);
67 static void ld_generic_generate_sections (struct ld_state *statep);
68 static void ld_generic_create_sections (struct ld_state *statep);
69 static int ld_generic_flag_unresolved (struct ld_state *statep);
70 static int ld_generic_open_outfile (struct ld_state *statep, int machine,
72 static int ld_generic_create_outfile (struct ld_state *statep);
73 static void ld_generic_relocate_section (struct ld_state *statep,
75 struct scninfo *firstp,
76 const Elf32_Word *dblindirect);
77 static int ld_generic_finalize (struct ld_state *statep);
78 static bool ld_generic_special_section_number_p (struct ld_state *statep,
80 static bool ld_generic_section_type_p (struct ld_state *statep,
82 static XElf_Xword ld_generic_dynamic_section_flags (struct ld_state *statep);
83 static void ld_generic_initialize_plt (struct ld_state *statep, Elf_Scn *scn);
84 static void ld_generic_initialize_pltrel (struct ld_state *statep,
86 static void ld_generic_initialize_got (struct ld_state *statep, Elf_Scn *scn);
87 static void ld_generic_initialize_gotplt (struct ld_state *statep,
89 static void ld_generic_finalize_plt (struct ld_state *statep, size_t nsym,
91 struct symbol **ndxtosymp);
92 static int ld_generic_rel_type (struct ld_state *statep);
93 static void ld_generic_count_relocations (struct ld_state *statep,
94 struct scninfo *scninfo);
95 static void ld_generic_create_relocations (struct ld_state *statep,
96 const Elf32_Word *dblindirect);
98 static int file_process2 (struct usedfiles *fileinfo);
99 static void mark_section_used (struct scninfo *scninfo, Elf32_Word shndx,
100 struct scninfo **grpscnp);
103 /* Map symbol index to struct symbol record. */
104 static struct symbol **ndxtosym;
106 /* String table reference to all symbols in the symbol table. */
107 static struct Ebl_Strent **symstrent;
110 /* Check whether file associated with FD is a DSO. */
114 /* We have to read the 'e_type' field. It has the same size (16
115 bits) in 32- and 64-bit ELF. */
118 return (pread (fd, &e_type, sizeof (e_type), offsetof (XElf_Ehdr, e_type))
120 && e_type == ET_DYN);
124 /* Print the complete name of a file, including the archive it is
127 print_file_name (FILE *s, struct usedfiles *fileinfo, int first_level,
132 if (fileinfo->archive_file != NULL)
134 npar = print_file_name (s, fileinfo->archive_file, 0, 0) + 1;
135 fputc_unlocked ('(', s);
136 fputs_unlocked (fileinfo->rfname, s);
140 fputc_unlocked (')', s);
143 fputs_unlocked (fileinfo->rfname, s);
145 if (first_level && newline)
146 fputc_unlocked ('\n', s);
152 /* Function to determine whether an object will be dynamically linked. */
154 dynamically_linked_p (void)
156 return (ld_state.file_type == dso_file_type || ld_state.nplt > 0
157 || ld_state.ngot > 0);
162 linked_from_dso_p (struct scninfo *scninfo, size_t symidx)
164 struct usedfiles *file = scninfo->fileinfo;
166 /* If this symbol is not undefined in this file it cannot come from
168 if (symidx < file->nlocalsymbols)
171 struct symbol *sym = file->symref[symidx];
173 return sym->defined && sym->in_dso;
177 /* Initialize state object. This callback function is called after the
178 parameters are parsed but before any file is searched for. */
180 ld_prepare_state (const char *emulation)
182 /* When generating DSO we normally allow undefined symbols. */
183 ld_state.nodefs = true;
185 /* To be able to detect problems we add a .comment section entry by
187 ld_state.add_ld_comment = true;
189 /* XXX We probably should find a better place for this. The index
190 of the first user-defined version is 2. */
191 ld_state.nextveridx = 2;
193 /* Pick an not too small number for the initial size of the tables. */
194 ld_symbol_tab_init (&ld_state.symbol_tab, 1027);
195 ld_section_tab_init (&ld_state.section_tab, 67);
196 ld_version_str_tab_init (&ld_state.version_str_tab, 67);
198 /* Initialize the section header string table. */
199 ld_state.shstrtab = ebl_strtabinit (true);
200 if (ld_state.shstrtab == NULL)
201 error (EXIT_FAILURE, errno, gettext ("cannot create string table"));
203 /* Initialize the callbacks. These are the defaults, the appropriate
204 backend can later install its own callbacks. */
205 ld_state.callbacks.lib_extensions = ld_generic_lib_extensions;
206 ld_state.callbacks.file_process = ld_generic_file_process;
207 ld_state.callbacks.file_close = ld_generic_file_close;
208 ld_state.callbacks.generate_sections = ld_generic_generate_sections;
209 ld_state.callbacks.create_sections = ld_generic_create_sections;
210 ld_state.callbacks.flag_unresolved = ld_generic_flag_unresolved;
211 ld_state.callbacks.open_outfile = ld_generic_open_outfile;
212 ld_state.callbacks.create_outfile = ld_generic_create_outfile;
213 ld_state.callbacks.relocate_section = ld_generic_relocate_section;
214 ld_state.callbacks.finalize = ld_generic_finalize;
215 ld_state.callbacks.special_section_number_p =
216 ld_generic_special_section_number_p;
217 ld_state.callbacks.section_type_p = ld_generic_section_type_p;
218 ld_state.callbacks.dynamic_section_flags = ld_generic_dynamic_section_flags;
219 ld_state.callbacks.initialize_plt = ld_generic_initialize_plt;
220 ld_state.callbacks.initialize_pltrel = ld_generic_initialize_pltrel;
221 ld_state.callbacks.initialize_got = ld_generic_initialize_got;
222 ld_state.callbacks.initialize_gotplt = ld_generic_initialize_gotplt;
223 ld_state.callbacks.finalize_plt = ld_generic_finalize_plt;
224 ld_state.callbacks.rel_type = ld_generic_rel_type;
225 ld_state.callbacks.count_relocations = ld_generic_count_relocations;
226 ld_state.callbacks.create_relocations = ld_generic_create_relocations;
228 #ifndef BASE_ELF_NAME
229 /* Find the ld backend library. Use EBL to determine the name if
230 the user hasn't provided one on the command line. */
231 if (emulation == NULL)
233 emulation = ebl_backend_name (ld_state.ebl);
234 assert (emulation != NULL);
236 size_t emulation_len = strlen (emulation);
238 /* Construct the file name. */
239 char *fname = (char *) alloca (sizeof "libld_" - 1 + emulation_len
241 strcpy (mempcpy (stpcpy (fname, "libld_"), emulation, emulation_len), ".so");
244 void *h = dlopen (fname, RTLD_LAZY);
246 error (EXIT_FAILURE, 0,
247 gettext ("cannot load ld backend library '%s': %s"),
250 /* Find the initializer. It must be present. */
251 char *initname = (char *) alloca (emulation_len + sizeof "_ld_init");
252 strcpy (mempcpy (initname, emulation, emulation_len), "_ld_init");
253 int (*initfct) (struct ld_state *)
254 = (int (*) (struct ld_state *)) dlsym (h, initname);
257 error (EXIT_FAILURE, 0, gettext ("\
258 cannot find init function in ld backend library '%s': %s"),
261 /* Store the handle. */
264 /* Call the init function. */
265 return initfct (&ld_state);
267 # define INIT_FCT_NAME(base) _INIT_FCT_NAME(base)
268 # define _INIT_FCT_NAME(base) base##_ld_init
269 /* Declare and call the initialization function. */
270 extern int INIT_FCT_NAME(BASE_ELF_NAME) (struct ld_state *);
271 return INIT_FCT_NAME(BASE_ELF_NAME) (&ld_state);
277 check_for_duplicate2 (struct usedfiles *newp, struct usedfiles *list)
279 struct usedfiles *first;
284 list = first = list->next;
287 /* When searching the needed list we might come across entries
288 for files which are not yet opened. Stop then, there is
289 nothing more to test. */
290 if (likely (list->status == not_opened))
293 if (unlikely (list->ino == newp->ino)
294 && unlikely (list->dev == newp->dev))
298 newp->status = closed;
299 if (newp->file_type == relocatable_file_type)
300 error (0, 0, gettext ("%s listed more than once as input"),
307 while (likely (list != first));
314 check_for_duplicate (struct usedfiles *newp)
318 if (unlikely (fstat (newp->fd, &st) < 0))
324 newp->dev = st.st_dev;
325 newp->ino = st.st_ino;
327 return (check_for_duplicate2 (newp, ld_state.relfiles)
328 || check_for_duplicate2 (newp, ld_state.dsofiles)
329 || check_for_duplicate2 (newp, ld_state.needed));
333 /* Find a file along the path described in the state. */
335 open_along_path2 (struct usedfiles *fileinfo, struct pathelement *path)
337 const char *fname = fileinfo->fname;
338 size_t fnamelen = strlen (fname);
340 struct pathelement *firstp = path;
343 /* Cannot find anything since we have no path. */
348 if (likely (path->exist >= 0))
350 /* Create the file name. */
352 size_t dirlen = strlen (path->pname);
355 if (fileinfo->file_type == archive_file_type)
357 const char **exts = (ld_state.statically
358 ? (const char *[2]) { ".a", NULL }
359 : LIB_EXTENSION (&ld_state));
361 /* We have to create the actual file name. We prepend "lib"
362 and add one of the extensions the platform has. */
363 while (*exts != NULL)
365 size_t extlen = strlen (*exts);
366 rfname = (char *) alloca (dirlen + 5 + fnamelen + extlen);
367 memcpy (mempcpy (stpcpy (mempcpy (rfname, path->pname,
373 fd = open (rfname, O_RDONLY);
374 if (likely (fd != -1) || errno != ENOENT)
376 err = fd == -1 ? errno : 0;
380 /* Next extension. */
386 assert (fileinfo->file_type == dso_file_type
387 || fileinfo->file_type == dso_needed_file_type);
389 rfname = (char *) alloca (dirlen + 1 + fnamelen + 1);
390 memcpy (stpcpy (mempcpy (rfname, path->pname, dirlen), "/"),
391 fname, fnamelen + 1);
393 fd = open (rfname, O_RDONLY);
394 if (unlikely (fd == -1))
398 if (likely (fd != -1))
400 /* We found the file. This also means the directory
405 /* Check whether we have this file already loaded. */
406 if (unlikely (check_for_duplicate (fileinfo) != 0))
409 /* Make a copy of the name. */
410 fileinfo->rfname = obstack_strdup (&ld_state.smem, rfname);
412 if (unlikely (ld_state.trace_files))
413 printf (fileinfo->file_type == archive_file_type
414 ? gettext ("%s (for -l%s)\n")
415 : gettext ("%s (for DT_NEEDED %s)\n"),
421 /* The file does not exist. Maybe the whole directory doesn't.
422 Check it unless we know it exists. */
423 if (unlikely (path->exist == 0))
427 /* Keep only the directory name. Note that the path
428 might be relative. This doesn't matter here. We do
429 the test in any case even if there is the chance that
430 somebody wants to change the programs working
431 directory at some point which would make the result
432 of this test void. Since changing the working
433 directory is completely wrong we are not taking this
434 case into account. */
435 rfname[dirlen] = '\0';
436 if (unlikely (stat (rfname, &st) < 0) || ! S_ISDIR (st.st_mode))
437 /* The directory does not exist or the named file is no
445 /* Next path element. */
448 while (likely (err == ENOENT && path != firstp));
455 open_along_path (struct usedfiles *fileinfo)
457 const char *fname = fileinfo->fname;
460 if (fileinfo->file_type == relocatable_file_type)
462 /* Only libraries are searched along the path. */
463 fileinfo->fd = open (fname, O_RDONLY);
465 if (likely (fileinfo->fd != -1))
467 /* We found the file. */
468 if (unlikely (ld_state.trace_files))
469 print_file_name (stdout, fileinfo, 1, 1);
471 return check_for_duplicate (fileinfo);
474 /* If the name is an absolute path we are done. */
479 /* If the user specified two parts to the LD_LIBRARY_PATH variable
480 try the first part now. */
481 err = open_along_path2 (fileinfo, ld_state.ld_library_path1);
483 /* Try the user-specified path next. */
485 err = open_along_path2 (fileinfo,
486 fileinfo->file_type == archive_file_type
487 ? ld_state.paths : ld_state.rpath_link);
489 /* Then the second part of the LD_LIBRARY_PATH value. */
490 if (unlikely (err == ENOENT))
492 err = open_along_path2 (fileinfo, ld_state.ld_library_path2);
494 /* In case we look for a DSO handle now the RUNPATH. */
497 if (fileinfo->file_type == dso_file_type)
498 err = open_along_path2 (fileinfo, ld_state.runpath_link);
500 /* Finally the path from the default linker script. */
502 err = open_along_path2 (fileinfo, ld_state.default_paths);
507 if (unlikely (err != 0)
508 && (err != EAGAIN || fileinfo->file_type == relocatable_file_type))
509 error (0, err, gettext ("cannot open %s"), fileinfo->fname);
516 matching_group_comdat_scn (const XElf_Sym *sym, size_t shndx,
517 struct usedfiles *fileinfo, struct symbol *oldp)
519 if ((shndx >= SHN_LORESERVE && shndx <= SHN_HIRESERVE)
520 || (oldp->scndx >= SHN_LORESERVE && oldp->scndx <= SHN_HIRESERVE))
521 /* Cannot be a group COMDAT section. */
524 size_t newgrpid = fileinfo->scninfo[shndx].grpid;
525 size_t oldgrpid = oldp->file->scninfo[oldp->scndx].grpid;
526 if (newgrpid == 0 || oldgrpid == 0)
529 assert (SCNINFO_SHDR (fileinfo->scninfo[newgrpid].shdr).sh_type
531 assert (SCNINFO_SHDR (oldp->file->scninfo[oldgrpid].shdr).sh_type
534 if (! fileinfo->scninfo[newgrpid].comdat_group
535 || ! oldp->file->scninfo[oldgrpid].comdat_group)
538 if (strcmp (fileinfo->scninfo[newgrpid].symbols->name,
539 oldp->file->scninfo[oldgrpid].symbols->name) != 0)
542 /* This is a matching, duplicate COMDAT group section. Ignore it. */
548 check_type_and_size (const XElf_Sym *sym, struct usedfiles *fileinfo,
551 /* We check the type and size of the symbols. In both cases the
552 information can be missing (size is zero, type is STT_NOTYPE) in
553 which case we issue no warnings. Otherwise everything must
554 match. If the type does not match there is no point in checking
557 if (XELF_ST_TYPE (sym->st_info) != STT_NOTYPE && oldp->type != STT_NOTYPE
558 && unlikely (oldp->type != XELF_ST_TYPE (sym->st_info)))
563 error (0, 0, gettext ("\
564 Warning: type of `%s' changed from %s in %s to %s in %s"),
566 ebl_symbol_type_name (ld_state.ebl, oldp->type,
567 buf1, sizeof (buf1)),
569 ebl_symbol_type_name (ld_state.ebl, XELF_ST_TYPE (sym->st_info),
570 buf2, sizeof (buf2)),
573 else if (XELF_ST_TYPE (sym->st_info) == STT_OBJECT
575 && unlikely (oldp->size != sym->st_size))
576 error (0, 0, gettext ("\
577 Warning: size of `%s' changed from %" PRIu64 " in %s to %" PRIu64 " in %s"),
578 oldp->name, (uint64_t) oldp->size, oldp->file->rfname,
579 (uint64_t) sym->st_size, fileinfo->rfname);
584 check_definition (const XElf_Sym *sym, size_t shndx, size_t symidx,
585 struct usedfiles *fileinfo, struct symbol *oldp)
588 bool old_in_dso = FILEINFO_EHDR (oldp->file->ehdr).e_type == ET_DYN;
589 bool new_in_dso = FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_DYN;
590 bool use_new_def = false;
592 if (shndx != SHN_UNDEF
594 || (shndx != SHN_COMMON && oldp->common && ! new_in_dso)
595 || (old_in_dso && ! new_in_dso)))
597 /* We found a definition for a previously undefined symbol or a
598 real definition for a previous common-only definition or a
599 redefinition of a symbol definition in an object file
600 previously defined in a DSO. First perform some tests which
601 will show whether the common is really matching the
603 check_type_and_size (sym, fileinfo, oldp);
605 /* We leave the next element intact to not interrupt the list
606 with the unresolved symbols. Whoever walks the list will
607 have to check the `defined' flag. But we remember that this
608 list element is not unresolved anymore. */
611 /* Remove from the list. */
612 --ld_state.nunresolved;
614 --ld_state.nunresolved_nonweak;
615 CDBL_LIST_DEL (ld_state.unresolved, oldp);
617 else if (oldp->common)
618 /* Remove from the list. */
619 CDBL_LIST_DEL (ld_state.common_syms, oldp);
621 /* Use the values of the definition from now on. */
624 else if (shndx != SHN_UNDEF
626 && matching_group_comdat_scn (sym, shndx, fileinfo, oldp))
627 /* The duplicate symbol is in a group COMDAT section with the same
628 signature as the one containing the original definition.
629 Just ignore the second definition. */
631 else if (shndx != SHN_UNDEF
632 && unlikely (! oldp->common)
634 && shndx != SHN_COMMON
635 /* Multiple definitions are no fatal errors if the -z muldefs flag
636 is used. We don't warn about the multiple definition unless we
637 are told to be verbose. */
638 && (!ld_state.muldefs || verbose)
639 && ! old_in_dso && fileinfo->file_type == relocatable_file_type)
641 /* We have a double definition. This is a problem. */
643 XElf_Sym_vardef (oldsym);
644 struct usedfiles *oldfile;
649 if (elf_getshdrnum (fileinfo->elf, &shnum) < 0)
650 error (EXIT_FAILURE, 0,
651 gettext ("cannot determine number of sections: %s"),
654 /* XXX Use only ebl_section_name. */
655 if (shndx < SHN_LORESERVE || (shndx > SHN_HIRESERVE && shndx < shnum))
656 scnname = elf_strptr (fileinfo->elf,
658 SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_name);
660 // XXX extended section
661 scnname = ebl_section_name (ld_state.ebl, shndx, 0, buf, sizeof (buf),
664 /* XXX Print source file and line number. */
665 print_file_name (stderr, fileinfo, 1, 0);
667 gettext ("(%s+%#" PRIx64 "): multiple definition of %s `%s'\n"),
669 (uint64_t) sym->st_value,
670 ebl_symbol_type_name (ld_state.ebl, XELF_ST_TYPE (sym->st_info),
674 oldfile = oldp->file;
675 xelf_getsymshndx (oldfile->symtabdata, oldfile->xndxdata, oldp->symidx,
677 assert (oldsym != NULL);
679 /* XXX Use only ebl_section_name. */
680 if (oldp->scndx < SHN_LORESERVE || oldp->scndx > SHN_HIRESERVE)
681 scnname = elf_strptr (oldfile->elf,
683 SCNINFO_SHDR (oldfile->scninfo[shndx].shdr).sh_name);
685 scnname = ebl_section_name (ld_state.ebl, oldp->scndx, oldp->scndx,
686 buf, sizeof (buf), NULL, shnum);
688 /* XXX Print source file and line number. */
689 print_file_name (stderr, oldfile, 1, 0);
690 fprintf (stderr, gettext ("(%s+%#" PRIx64 "): first defined here\n"),
691 scnname, (uint64_t) oldsym->st_value);
693 if (likely (!ld_state.muldefs))
696 else if (old_in_dso && fileinfo->file_type == relocatable_file_type
697 && shndx != SHN_UNDEF)
698 /* We use the definition from a normal relocatable file over the
699 definition in a DSO. This is what the dynamic linker would
702 else if (old_in_dso && !new_in_dso && oldp->defined && !oldp->on_dsolist)
704 CDBL_LIST_ADD_REAR (ld_state.from_dso, oldp);
705 ++ld_state.nfrom_dso;
707 /* If the object is a function we allocate a PLT entry,
708 otherwise only a GOT entry. */
709 if (oldp->type == STT_FUNC)
714 oldp->on_dsolist = 1;
716 else if (oldp->common && shndx == SHN_COMMON)
718 /* The symbol size is the largest of all common definitions. */
719 oldp->size = MAX (oldp->size, sym->st_size);
720 /* Similarly for the alignment. */
721 oldp->merge.value = MAX (oldp->merge.value, sym->st_value);
724 if (unlikely (use_new_def))
726 /* Adjust the symbol record appropriately and remove
727 the symbol from the list of symbols which are taken from DSOs. */
728 if (old_in_dso && fileinfo->file_type == relocatable_file_type)
730 CDBL_LIST_DEL (ld_state.from_dso, oldp);
731 --ld_state.nfrom_dso;
733 if (likely (oldp->type == STT_FUNC))
738 oldp->on_dsolist = 0;
741 /* Use the values of the definition from now on. */
742 oldp->size = sym->st_size;
743 oldp->type = XELF_ST_TYPE (sym->st_info);
744 oldp->symidx = symidx;
746 //oldp->symscndx = THESYMSCNDX must be passed;
747 oldp->file = fileinfo;
749 oldp->in_dso = new_in_dso;
750 oldp->common = shndx == SHN_COMMON;
751 if (likely (fileinfo->file_type == relocatable_file_type))
753 /* If the definition comes from a DSO we pertain the weak flag
754 and it's indicating whether the reference is weak or not. */
755 oldp->weak = XELF_ST_BIND (sym->st_info) == STB_WEAK;
757 // XXX Really exclude SHN_ABS?
758 if (shndx != SHN_COMMON && shndx != SHN_ABS)
760 struct scninfo *ignore;
761 mark_section_used (&fileinfo->scninfo[shndx], shndx, &ignore);
765 /* Add to the list of symbols used from DSOs if necessary. */
766 if (new_in_dso && !old_in_dso)
768 CDBL_LIST_ADD_REAR (ld_state.from_dso, oldp);
769 ++ld_state.nfrom_dso;
771 /* If the object is a function we allocate a PLT entry,
772 otherwise only a GOT entry. */
773 if (oldp->type == STT_FUNC)
778 oldp->on_dsolist = 1;
780 else if (shndx == SHN_COMMON)
782 /* Store the alignment. */
783 oldp->merge.value = sym->st_value;
785 CDBL_LIST_ADD_REAR (ld_state.common_syms, oldp);
793 static struct scninfo *
794 find_section_group (struct usedfiles *fileinfo, Elf32_Word shndx,
797 struct scninfo *runp;
799 for (runp = fileinfo->groups; runp != NULL; runp = runp->next)
806 data = elf_getdata (runp->scn, NULL);
808 error (EXIT_FAILURE, 0,
809 gettext ("%s: cannot get section group data: %s"),
810 fileinfo->fname, elf_errmsg (-1));
812 /* There cannot be another data block. */
813 assert (elf_getdata (runp->scn, data) == NULL);
815 grpref = (Elf32_Word *) data->d_buf;
816 cnt = data->d_size / sizeof (Elf32_Word);
817 /* Note that we stop after looking at index 1 since index 0
818 contains the flags for the section group. */
820 if (grpref[--cnt] == shndx)
827 /* If we come here no section group contained the given section
828 despite the SHF_GROUP flag. This is an error in the input
830 error (EXIT_FAILURE, 0, gettext ("\
831 %s: section '%s' with group flag set does not belong to any group"),
833 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
834 SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_name));
839 /* Mark all sections which belong to the same group as section SHNDX
842 mark_section_group (struct usedfiles *fileinfo, Elf32_Word shndx,
843 struct scninfo **grpscnp)
845 /* First locate the section group. There can be several (many) of
850 struct scninfo *grpscn = find_section_group (fileinfo, shndx, &data);
853 /* Mark all the sections as used.
855 XXX Two possible problems here:
857 - the gABI says "The section must be referenced by a section of type
858 SHT_GROUP". I hope everybody reads this as "exactly one section".
860 - section groups are also useful to mark the debugging section which
861 belongs to a text section. Unconditionally adding debugging sections
862 is therefore probably not what is wanted if stripping is required. */
864 /* Mark the section group as handled. */
867 grpref = (Elf32_Word *) data->d_buf;
868 cnt = data->d_size / sizeof (Elf32_Word);
871 Elf32_Word idx = grpref[--cnt];
872 XElf_Shdr *shdr = &SCNINFO_SHDR (fileinfo->scninfo[idx].shdr);
874 if (fileinfo->scninfo[idx].grpid != grpscn->grpid)
875 error (EXIT_FAILURE, 0, gettext ("\
876 %s: section [%2d] '%s' is not in the correct section group"),
877 fileinfo->fname, (int) idx,
878 elf_strptr (fileinfo->elf, fileinfo->shstrndx, shdr->sh_name));
880 if (ld_state.strip == strip_none
881 /* If we are stripping, remove debug sections. */
882 || (!ebl_debugscn_p (ld_state.ebl,
883 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
885 /* And the relocation sections for the debug sections. */
886 && ((shdr->sh_type != SHT_RELA && shdr->sh_type != SHT_REL)
887 || !ebl_debugscn_p (ld_state.ebl,
888 elf_strptr (fileinfo->elf,
890 SCNINFO_SHDR (fileinfo->scninfo[shdr->sh_info].shdr).sh_name)))))
892 struct scninfo *ignore;
894 mark_section_used (&fileinfo->scninfo[idx], idx, &ignore);
901 mark_section_used (struct scninfo *scninfo, Elf32_Word shndx,
902 struct scninfo **grpscnp)
904 if (likely (scninfo->used))
905 /* Nothing to be done. */
908 /* We need this section. */
909 scninfo->used = true;
911 /* Make sure the section header has been read from the file. */
912 XElf_Shdr *shdr = &SCNINFO_SHDR (scninfo->shdr);
914 if (unlikely (scninfo->shdr == NULL))
916 if (unlikely (scninfo->shdr.sh_type == SHT_NULL))
920 shdr = xelf_getshdr (scninfo->scn, scninfo->shdr);
922 xelf_getshdr_copy (scninfo->scn, shdr, scninfo->shdr);
924 if (unlikely (shdr == NULL))
925 /* Something is very wrong. The calling code will notice it
926 soon and print a message. */
930 /* Handle section linked by 'sh_link'. */
931 if (unlikely (shdr->sh_link != 0))
933 struct scninfo *ignore;
934 mark_section_used (&scninfo->fileinfo->scninfo[shdr->sh_link],
935 shdr->sh_link, &ignore);
938 /* Handle section linked by 'sh_info'. */
939 if (unlikely (shdr->sh_info != 0) && (shdr->sh_flags & SHF_INFO_LINK))
941 struct scninfo *ignore;
942 mark_section_used (&scninfo->fileinfo->scninfo[shdr->sh_info],
943 shdr->sh_info, &ignore);
946 if (unlikely (shdr->sh_flags & SHF_GROUP) && ld_state.gc_sections)
947 /* Find the section group which contains this section. */
948 mark_section_group (scninfo->fileinfo, shndx, grpscnp);
952 /* We collect all sections in a hashing table. All sections with the
953 same name are collected in a list. Note that we do not determine
954 which sections are finally collected in the same output section
955 here. This would be terribly inefficient. It will be done later. */
957 add_section (struct usedfiles *fileinfo, struct scninfo *scninfo)
959 struct scnhead *queued;
960 struct scnhead search;
961 unsigned long int hval;
962 XElf_Shdr *shdr = &SCNINFO_SHDR (scninfo->shdr);
963 struct scninfo *grpscn = NULL;
964 Elf_Data *grpscndata = NULL;
966 /* See whether we can determine right away whether we need this
967 section in the output.
969 XXX I assume here that --gc-sections only affects extraction
970 from an archive. If it also affects objects files given on
971 the command line then somebody must explain to me how the
972 dependency analysis should work. Should the entry point be
973 the root? What if it is a numeric value? */
975 && (ld_state.strip == strip_none
976 || (shdr->sh_flags & SHF_ALLOC) != 0
977 || shdr->sh_type == SHT_NOTE
978 || (shdr->sh_type == SHT_PROGBITS
979 && strcmp (elf_strptr (fileinfo->elf,
981 shdr->sh_name), ".comment") == 0))
982 && (fileinfo->status != in_archive || !ld_state.gc_sections))
983 /* Mark as used and handle reference recursively if necessary. */
984 mark_section_used (scninfo, elf_ndxscn (scninfo->scn), &grpscn);
986 if ((shdr->sh_flags & SHF_GROUP) && grpscn == NULL)
987 /* Determine the symbol which name constitutes the signature
988 for the section group. */
989 grpscn = find_section_group (fileinfo, elf_ndxscn (scninfo->scn),
991 assert (grpscn == NULL || grpscn->symbols->name != NULL);
993 /* Determine the section name. */
994 search.name = elf_strptr (fileinfo->elf, fileinfo->shstrndx, shdr->sh_name);
995 search.type = shdr->sh_type;
996 search.flags = shdr->sh_flags;
997 search.entsize = shdr->sh_entsize;
998 search.grp_signature = grpscn != NULL ? grpscn->symbols->name : NULL;
999 search.kind = scn_normal;
1000 hval = elf_hash (search.name);
1002 /* Find already queued sections. */
1003 queued = ld_section_tab_find (&ld_state.section_tab, hval, &search);
1006 bool is_comdat = false;
1008 /* If this section is part of a COMDAT section group we simply
1009 ignore it since we already have a copy. */
1010 if (unlikely (shdr->sh_flags & SHF_GROUP))
1012 /* Get the data of the section group section. */
1013 if (grpscndata == NULL)
1015 grpscndata = elf_getdata (grpscn->scn, NULL);
1016 assert (grpscndata != NULL);
1019 /* XXX Possibly unaligned memory access. */
1020 if ((((Elf32_Word *) grpscndata->d_buf)[0] & GRP_COMDAT) != 0)
1022 /* We have to compare the group signatures. There might
1023 be sections with the same name but belonging to
1024 groups with different signatures. This means we have
1025 to compare the new group signature with all those
1026 already collected. There might also be some
1027 non-group sections in the mix. */
1028 struct scninfo *runp = queued->last;
1031 if (SCNINFO_SHDR (runp->shdr).sh_flags & SHF_GROUP)
1033 struct scninfo *grpscn2
1034 = find_section_group (runp->fileinfo,
1035 elf_ndxscn (runp->scn),
1038 if (strcmp (grpscn->symbols->name,
1039 grpscn2->symbols->name) == 0)
1041 scninfo->unused_comdat = is_comdat = true;
1048 while (runp != queued->last);
1054 /* No COMDAT section, we use the data. */
1055 scninfo->next = queued->last->next;
1056 queued->last = queued->last->next = scninfo;
1058 queued->flags = ebl_sh_flags_combine (ld_state.ebl, queued->flags,
1060 queued->align = MAX (queued->align, shdr->sh_addralign);
1065 /* We do not use obstacks here since the memory might be
1067 queued = (struct scnhead *) xcalloc (sizeof (struct scnhead), 1);
1068 queued->kind = scn_normal;
1069 queued->name = search.name;
1070 queued->type = shdr->sh_type;
1071 queued->flags = shdr->sh_flags;
1072 queued->align = shdr->sh_addralign;
1073 queued->entsize = shdr->sh_entsize;
1074 queued->grp_signature = grpscn != NULL ? grpscn->symbols->name : NULL;
1075 queued->segment_nr = ~0;
1076 queued->last = scninfo->next = scninfo;
1078 /* Check whether we need a TLS segment. */
1079 ld_state.need_tls |= (shdr->sh_flags & SHF_TLS) != 0;
1081 /* Add to the hash table and possibly overwrite existing value. */
1082 ld_section_tab_insert (&ld_state.section_tab, hval, queued);
1088 add_relocatable_file (struct usedfiles *fileinfo, GElf_Word secttype)
1092 Elf_Data *symtabdata = NULL;
1093 Elf_Data *xndxdata = NULL;
1094 Elf_Data *versymdata = NULL;
1095 Elf_Data *verdefdata = NULL;
1096 Elf_Data *verneeddata = NULL;
1097 size_t symstridx = 0;
1098 size_t nsymbols = 0;
1099 size_t nlocalsymbols = 0;
1100 bool has_merge_sections = false;
1101 bool has_tls_symbols = false;
1102 /* Unless we have different information we assume the code needs
1103 an executable stack. */
1104 enum execstack execstack = execstack_true;
1106 /* Prerequisites. */
1107 assert (fileinfo->elf != NULL);
1109 /* Allocate memory for the sections. */
1110 if (unlikely (elf_getshdrnum (fileinfo->elf, &scncnt) < 0))
1111 error (EXIT_FAILURE, 0,
1112 gettext ("cannot determine number of sections: %s"),
1115 fileinfo->scninfo = (struct scninfo *)
1116 obstack_calloc (&ld_state.smem, scncnt * sizeof (struct scninfo));
1118 /* Read all the section headers and find the symbol table. Note
1119 that we don't skip the section with index zero. Even though the
1120 section itself is always empty the section header contains
1121 informaton for the case when the section index for the section
1122 header string table is too large to fit in the ELF header. */
1123 for (cnt = 0; cnt < scncnt; ++cnt)
1125 /* Store the handle for the section. */
1126 fileinfo->scninfo[cnt].scn = elf_getscn (fileinfo->elf, cnt);
1128 /* Get the ELF section header and data. */
1131 if (fileinfo->scninfo[cnt].shdr == NULL)
1133 if (fileinfo->scninfo[cnt].shdr.sh_type == SHT_NULL)
1137 shdr = xelf_getshdr (fileinfo->scninfo[cnt].scn,
1138 fileinfo->scninfo[cnt].shdr);
1140 xelf_getshdr_copy (fileinfo->scninfo[cnt].scn, shdr,
1141 fileinfo->scninfo[cnt].shdr);
1145 /* This should never happen. */
1146 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1147 fileinfo->rfname, __FILE__, __LINE__);
1152 shdr = &SCNINFO_SHDR (fileinfo->scninfo[cnt].shdr);
1154 Elf_Data *data = elf_getdata (fileinfo->scninfo[cnt].scn, NULL);
1156 /* Check whether this section is marked as merge-able. */
1157 has_merge_sections |= (shdr->sh_flags & SHF_MERGE) != 0;
1158 has_tls_symbols |= (shdr->sh_flags & SHF_TLS) != 0;
1160 /* Get the ELF section header and data. */
1161 /* Make the file structure available. */
1162 fileinfo->scninfo[cnt].fileinfo = fileinfo;
1164 if (unlikely (shdr->sh_type == SHT_SYMTAB)
1165 || unlikely (shdr->sh_type == SHT_DYNSYM))
1167 if (shdr->sh_type == SHT_SYMTAB)
1169 assert (fileinfo->symtabdata == NULL);
1170 fileinfo->symtabdata = data;
1171 fileinfo->nsymtab = shdr->sh_size / shdr->sh_entsize;
1172 fileinfo->nlocalsymbols = shdr->sh_info;
1173 fileinfo->symstridx = shdr->sh_link;
1177 assert (fileinfo->dynsymtabdata == NULL);
1178 fileinfo->dynsymtabdata = data;
1179 fileinfo->ndynsymtab = shdr->sh_size / shdr->sh_entsize;
1180 fileinfo->dynsymstridx = shdr->sh_link;
1183 /* If we are looking for the normal symbol table we just
1185 if (secttype == shdr->sh_type)
1187 assert (symtabdata == NULL);
1189 symstridx = shdr->sh_link;
1190 nsymbols = shdr->sh_size / shdr->sh_entsize;
1191 nlocalsymbols = shdr->sh_info;
1194 else if (unlikely (shdr->sh_type == SHT_SYMTAB_SHNDX))
1196 assert (xndxdata == NULL);
1197 fileinfo->xndxdata = xndxdata = data;
1199 else if (unlikely (shdr->sh_type == SHT_GNU_versym))
1201 assert (versymdata == 0);
1202 fileinfo->versymdata = versymdata = data;
1204 else if (unlikely (shdr->sh_type == SHT_GNU_verdef))
1208 assert (verdefdata == 0);
1209 fileinfo->verdefdata = verdefdata = data;
1211 /* Allocate the arrays flagging the use of the version and
1212 to track of allocated names. */
1213 fileinfo->nverdef = nversions = shdr->sh_info;
1214 /* We have NVERSIONS + 1 because the indeces used to access the
1215 sectino start with one; zero represents local binding. */
1216 fileinfo->verdefused = (XElf_Versym *)
1217 obstack_calloc (&ld_state.smem,
1218 sizeof (XElf_Versym) * (nversions + 1));
1219 fileinfo->verdefent = (struct Ebl_Strent **)
1220 obstack_alloc (&ld_state.smem,
1221 sizeof (struct Ebl_Strent *) * (nversions + 1));
1223 else if (unlikely (shdr->sh_type == SHT_GNU_verneed))
1225 assert (verneeddata == 0);
1226 fileinfo->verneeddata = verneeddata = data;
1228 else if (unlikely (shdr->sh_type == SHT_DYNAMIC))
1230 assert (fileinfo->dynscn == NULL);
1231 fileinfo->dynscn = fileinfo->scninfo[cnt].scn;
1233 else if (unlikely (shdr->sh_type == SHT_GROUP))
1236 XElf_Shdr_vardef (symshdr);
1239 if (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_REL)
1240 error (EXIT_FAILURE, 0, gettext ("\
1241 %s: only files of type ET_REL might contain section groups"),
1244 fileinfo->scninfo[cnt].next = fileinfo->groups;
1245 fileinfo->scninfo[cnt].grpid = cnt;
1246 fileinfo->groups = &fileinfo->scninfo[cnt];
1248 /* Determine the signature. We create a symbol record for
1249 it. Only the name element is important. */
1250 fileinfo->scninfo[cnt].symbols = (struct symbol *)
1251 obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1253 symscn = elf_getscn (fileinfo->elf, shdr->sh_link);
1254 xelf_getshdr (symscn, symshdr);
1255 symdata = elf_getdata (symscn, NULL);
1257 if (symshdr != NULL)
1259 XElf_Sym_vardef (sym);
1261 /* We don't need the section index and therefore we don't
1262 have to use 'xelf_getsymshndx'. */
1263 xelf_getsym (symdata, shdr->sh_info, sym);
1266 struct symbol *symbol = fileinfo->scninfo[cnt].symbols;
1269 if (XELF_ST_TYPE (sym->st_info) == STT_SECTION)
1271 XElf_Shdr_vardef (buggyshdr);
1272 xelf_getshdr (elf_getscn (fileinfo->elf, sym->st_shndx),
1275 symbol->name = elf_strptr (fileinfo->elf,
1276 FILEINFO_EHDR (fileinfo->ehdr).e_shstrndx,
1277 buggyshdr->sh_name);
1278 symbol->symidx = -1;
1283 symbol->name = elf_strptr (fileinfo->elf,
1286 symbol->symidx = shdr->sh_info;
1288 symbol->file = fileinfo;
1291 if (fileinfo->scninfo[cnt].symbols->name == NULL)
1292 error (EXIT_FAILURE, 0, gettext ("\
1293 %s: cannot determine signature of section group [%2zd] '%s': %s"),
1295 elf_ndxscn (fileinfo->scninfo[cnt].scn),
1296 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1301 /* For all the sections which are part of this group, add
1304 error (EXIT_FAILURE, 0, gettext ("\
1305 %s: cannot get content of section group [%2zd] '%s': %s'"),
1306 fileinfo->fname, elf_ndxscn (fileinfo->scninfo[cnt].scn),
1307 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1311 Elf32_Word *grpdata = (Elf32_Word *) data->d_buf;
1312 if (grpdata[0] & GRP_COMDAT)
1313 fileinfo->scninfo[cnt].comdat_group = true;
1314 for (size_t inner = 1; inner < data->d_size / sizeof (Elf32_Word);
1317 if (grpdata[inner] >= scncnt)
1318 error (EXIT_FAILURE, 0, gettext ("\
1319 %s: group member %zu of section group [%2zd] '%s' has too high index: %" PRIu32),
1321 inner, elf_ndxscn (fileinfo->scninfo[cnt].scn),
1322 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1326 fileinfo->scninfo[grpdata[inner]].grpid = cnt;
1329 /* The 'used' flag is used to indicate when the information
1330 in the section group is used to mark all other sections
1331 as used. So it must not be true yet. */
1332 assert (fileinfo->scninfo[cnt].used == false);
1334 else if (! SECTION_TYPE_P (&ld_state, shdr->sh_type)
1335 && unlikely ((shdr->sh_flags & SHF_OS_NONCONFORMING) != 0))
1336 /* According to the gABI it is a fatal error if the file contains
1337 a section with unknown type and the SHF_OS_NONCONFORMING flag
1339 error (EXIT_FAILURE, 0,
1340 gettext ("%s: section '%s' has unknown type: %d"),
1342 elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1344 (int) shdr->sh_type);
1345 /* We don't have to add a few section types here. These will be
1346 generated from scratch for the new output file. We also
1347 don't add the sections of DSOs here since these sections are
1348 not used in the resulting object file. */
1349 else if (likely (fileinfo->file_type == relocatable_file_type)
1351 && likely (shdr->sh_type == SHT_PROGBITS
1352 || shdr->sh_type == SHT_RELA
1353 || shdr->sh_type == SHT_REL
1354 || shdr->sh_type == SHT_NOTE
1355 || shdr->sh_type == SHT_NOBITS
1356 || shdr->sh_type == SHT_INIT_ARRAY
1357 || shdr->sh_type == SHT_FINI_ARRAY
1358 || shdr->sh_type == SHT_PREINIT_ARRAY))
1360 /* Check whether the section needs to be executable. */
1361 if (shdr->sh_type == SHT_PROGBITS
1362 && (shdr->sh_flags & SHF_EXECINSTR) == 0
1363 && strcmp (elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1365 ".note.GNU-stack") == 0)
1366 execstack = execstack_false;
1368 add_section (fileinfo, &fileinfo->scninfo[cnt]);
1372 /* Now we know more about the requirements for an executable stack
1374 if (fileinfo->file_type == relocatable_file_type
1375 && execstack == execstack_true
1376 && ld_state.execstack != execstack_false_force)
1377 ld_state.execstack = execstack_true;
1379 /* Handle the symbols. Record defined and undefined symbols in the
1380 hash table. In theory there can be a file without any symbol
1382 if (likely (symtabdata != NULL))
1384 /* In case this file contains merge-able sections we have to
1385 locate the symbols which are in these sections. */
1386 fileinfo->has_merge_sections = has_merge_sections;
1387 if (likely (has_merge_sections || has_tls_symbols))
1389 fileinfo->symref = (struct symbol **)
1390 obstack_calloc (&ld_state.smem,
1391 nsymbols * sizeof (struct symbol *));
1393 /* Only handle the local symbols here. */
1394 for (cnt = 0; cnt < nlocalsymbols; ++cnt)
1397 XElf_Sym_vardef (sym);
1399 xelf_getsymshndx (symtabdata, xndxdata, cnt, sym, shndx);
1402 /* This should never happen. */
1403 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1404 fileinfo->rfname, __FILE__, __LINE__);
1408 if (likely (shndx != SHN_XINDEX))
1409 shndx = sym->st_shndx;
1410 else if (unlikely (shndx == 0))
1412 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1413 fileinfo->rfname, __FILE__, __LINE__);
1417 if (XELF_ST_TYPE (sym->st_info) != STT_SECTION
1418 && (shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE)
1419 && ((SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_flags
1421 || XELF_ST_TYPE (sym->st_info) == STT_TLS))
1423 /* Create a symbol record for this symbol and add it
1424 to the list for this section. */
1425 struct symbol *newp;
1427 newp = (struct symbol *)
1428 obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1431 newp->scndx = shndx;
1432 newp->file = fileinfo;
1434 fileinfo->symref[cnt] = newp;
1436 if (fileinfo->scninfo[shndx].symbols == NULL)
1437 fileinfo->scninfo[shndx].symbols = newp->next_in_scn
1442 = fileinfo->scninfo[shndx].symbols->next_in_scn;
1443 fileinfo->scninfo[shndx].symbols
1444 = fileinfo->scninfo[shndx].symbols->next_in_scn = newp;
1450 /* Create array with pointers to the symbol definitions. Note
1451 that we only allocate memory for the non-local symbols
1452 since we have no merge-able sections. But we store the
1453 pointer as if it was for the whole symbol table. This
1454 saves some memory. */
1455 fileinfo->symref = (struct symbol **)
1456 obstack_calloc (&ld_state.smem, ((nsymbols - nlocalsymbols)
1457 * sizeof (struct symbol *)))
1460 /* Don't handle local symbols here. It's either not necessary
1461 at all or has already happened. */
1462 for (cnt = nlocalsymbols; cnt < nsymbols; ++cnt)
1464 XElf_Sym_vardef (sym);
1466 xelf_getsymshndx (symtabdata, xndxdata, cnt, sym, shndx);
1470 /* This should never happen. */
1471 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1472 fileinfo->rfname, __FILE__, __LINE__);
1476 if (likely (shndx != SHN_XINDEX))
1477 shndx = sym->st_shndx;
1478 else if (unlikely (shndx == 0))
1480 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1481 fileinfo->rfname, __FILE__, __LINE__);
1485 /* We ignore ABS symbols from DSOs. */
1486 // XXX Is this correct?
1487 if (unlikely (shndx == SHN_ABS) && secttype == SHT_DYNSYM)
1490 if ((shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE)
1491 && fileinfo->scninfo[shndx].unused_comdat)
1492 /* The symbol is not used. */
1495 /* If the DSO uses symbol versions determine whether this is
1496 the default version. Otherwise we'll ignore the symbol. */
1497 if (versymdata != NULL)
1501 if (xelf_getversym_copy (versymdata, cnt, versym) == NULL)
1502 /* XXX Should we handle faulty input files more graceful? */
1503 assert (! "xelf_getversym failed");
1505 if ((versym & 0x8000) != 0)
1506 /* Ignore the symbol, it's not the default version. */
1510 /* See whether we know anything about this symbol. */
1511 struct symbol search;
1512 search.name = elf_strptr (fileinfo->elf, symstridx, sym->st_name);
1513 unsigned long int hval = elf_hash (search.name);
1515 /* We ignore the symbols the linker generates. This are
1516 _GLOBAL_OFFSET_TABLE_, _DYNAMIC. */
1517 // XXX This loop is hot and the following tests hardly ever match.
1518 // XXX Maybe move the tests somewhere they are executed less often.
1519 if (((unlikely (hval == 165832675ul)
1520 && strcmp (search.name, "_DYNAMIC") == 0)
1521 || (unlikely (hval == 102264335ul)
1522 && strcmp (search.name, "_GLOBAL_OFFSET_TABLE_") == 0))
1523 && sym->st_shndx != SHN_UNDEF
1524 /* If somebody defines such a variable in a relocatable we
1525 don't ignore it. Let the user get what s/he deserves. */
1526 && fileinfo->file_type != relocatable_file_type)
1529 struct symbol *oldp = ld_symbol_tab_find (&ld_state.symbol_tab,
1531 struct symbol *newp;
1532 if (likely (oldp == NULL))
1534 /* No symbol of this name known. Add it. */
1535 newp = (struct symbol *) obstack_alloc (&ld_state.smem,
1537 newp->name = search.name;
1538 newp->size = sym->st_size;
1539 newp->type = XELF_ST_TYPE (sym->st_info);
1541 newp->outsymidx = 0;
1542 newp->outdynsymidx = 0;
1543 newp->scndx = shndx;
1544 newp->file = fileinfo;
1545 newp->defined = newp->scndx != SHN_UNDEF;
1546 newp->common = newp->scndx == SHN_COMMON;
1547 newp->weak = XELF_ST_BIND (sym->st_info) == STB_WEAK;
1552 newp->need_copy = 0;
1553 newp->on_dsolist = 0;
1554 newp->in_dso = secttype == SHT_DYNSYM;
1555 newp->next_in_scn = NULL;
1558 newp->previous = NULL;
1561 if (newp->scndx == SHN_UNDEF)
1563 CDBL_LIST_ADD_REAR (ld_state.unresolved, newp);
1564 ++ld_state.nunresolved;
1566 ++ld_state.nunresolved_nonweak;
1568 else if (newp->scndx == SHN_COMMON)
1570 /* Store the alignment requirement. */
1571 newp->merge.value = sym->st_value;
1573 CDBL_LIST_ADD_REAR (ld_state.common_syms, newp);
1576 /* Insert the new symbol. */
1577 if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
1579 /* This cannot happen. */
1582 fileinfo->symref[cnt] = newp;
1584 /* We have a few special symbols to recognize. The symbols
1585 _init and _fini are the initialization and finalization
1586 functions respectively. They have to be made known in
1587 the dynamic section and therefore we have to find out
1588 now whether these functions exist or not. */
1589 if (hval == 6685956 && strcmp (newp->name, "_init") == 0)
1590 ld_state.init_symbol = newp;
1591 else if (hval == 6672457 && strcmp (newp->name, "_fini") == 0)
1592 ld_state.fini_symbol = newp;
1594 else if (unlikely (check_definition (sym, shndx, cnt, fileinfo, oldp)
1596 /* A fatal error (multiple definition of a symbol)
1597 occurred, no need to continue. */
1600 /* Use the previously allocated symbol record. It has
1601 been updated in check_definition(), if necessary. */
1602 newp = fileinfo->symref[cnt] = oldp;
1604 /* Mark the section the symbol we need comes from as used. */
1605 if (shndx != SHN_UNDEF
1606 && (shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE))
1608 struct scninfo *ignore;
1612 assert (elf_getshdrnum (fileinfo->elf, &shnum) == 0);
1613 assert (shndx < shnum);
1616 /* Mark section (and all dependencies) as used. */
1617 mark_section_used (&fileinfo->scninfo[shndx], shndx, &ignore);
1619 /* Check whether the section is merge-able. In this case we
1620 have to record the symbol. */
1621 if (SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_flags
1624 if (fileinfo->scninfo[shndx].symbols == NULL)
1625 fileinfo->scninfo[shndx].symbols = newp->next_in_scn
1630 = fileinfo->scninfo[shndx].symbols->next_in_scn;
1631 fileinfo->scninfo[shndx].symbols
1632 = fileinfo->scninfo[shndx].symbols->next_in_scn = newp;
1638 /* This file is used. */
1639 if (likely (fileinfo->file_type == relocatable_file_type))
1641 if (unlikely (ld_state.relfiles == NULL))
1642 ld_state.relfiles = fileinfo->next = fileinfo;
1645 fileinfo->next = ld_state.relfiles->next;
1646 ld_state.relfiles = ld_state.relfiles->next = fileinfo;
1649 /* Update some summary information in the state structure. */
1650 ld_state.nsymtab += fileinfo->nsymtab;
1651 ld_state.nlocalsymbols += fileinfo->nlocalsymbols;
1653 else if (likely (fileinfo->file_type == dso_file_type))
1655 CSNGL_LIST_ADD_REAR (ld_state.dsofiles, fileinfo);
1656 ++ld_state.ndsofiles;
1658 if (fileinfo->lazyload)
1659 /* We have to create another dynamic section entry for the
1662 XXX Once more functionality than the lazyloading flag
1663 are suppported the test must be extended. */
1664 ++ld_state.ndsofiles;
1673 ld_handle_filename_list (struct filename_list *fnames)
1675 struct filename_list *runp;
1678 for (runp = fnames; runp != NULL; runp = runp->next)
1680 struct usedfiles *curp;
1682 /* Create a record for the new file. */
1683 curp = runp->real = ld_new_inputfile (runp->name, relocatable_file_type);
1685 /* Set flags for group handling. */
1686 curp->group_start = runp->group_start;
1687 curp->group_end = runp->group_end;
1689 /* Set as-needed flag from the file, not the command line. */
1690 curp->as_needed = runp->as_needed;
1692 /* Read the file and everything else which comes up, including
1695 res |= FILE_PROCESS (-1, curp, &ld_state, &curp);
1696 while (curp != NULL);
1699 /* Free the list. */
1700 while (fnames != NULL)
1703 fnames = fnames->next;
1711 /* Handle opening of the given file with ELF descriptor. */
1713 open_elf (struct usedfiles *fileinfo, Elf *elf)
1718 error (EXIT_FAILURE, 0,
1719 gettext ("cannot get descriptor for ELF file (%s:%d): %s\n"),
1720 __FILE__, __LINE__, elf_errmsg (-1));
1722 if (unlikely (elf_kind (elf) == ELF_K_NONE))
1724 struct filename_list *fnames;
1726 /* We don't have to look at this file again. */
1727 fileinfo->status = closed;
1729 /* Let's see whether this is a linker script. */
1730 if (fileinfo->fd != -1)
1731 /* Create a stream from the file handle we know. */
1732 ldin = fdopen (fileinfo->fd, "r");
1735 /* Get the memory for the archive member. */
1739 /* Get the content of the file. */
1740 content = elf_rawfile (elf, &contentsize);
1741 if (content == NULL)
1743 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1744 fileinfo->rfname, __FILE__, __LINE__);
1748 /* The content of the file is available in memory. Read the
1749 memory region as a stream. */
1750 ldin = fmemopen (content, contentsize, "r");
1753 /* No need for locking. */
1754 __fsetlocking (ldin, FSETLOCKING_BYCALLER);
1757 error (EXIT_FAILURE, errno, gettext ("cannot open '%s'"),
1760 /* Parse the file. If it is a linker script no problems will be
1762 ld_state.srcfiles = NULL;
1764 ld_scan_version_script = 0;
1765 ldin_fname = fileinfo->rfname;
1769 if (fileinfo->fd != -1 && !fileinfo->fd_passed)
1771 /* We won't need the file descriptor again. */
1772 close (fileinfo->fd);
1778 if (unlikely (res != 0))
1779 /* Something went wrong during parsing. */
1782 /* This is no ELF file. */
1783 fileinfo->elf = NULL;
1785 /* Now we have to handle eventual INPUT and GROUP statements in
1786 the script. Read the files mentioned. */
1787 fnames = ld_state.srcfiles;
1790 struct filename_list *oldp;
1792 /* Convert the list into a normal single-linked list. */
1794 fnames = fnames->next;
1797 /* Remove the list from the state structure. */
1798 ld_state.srcfiles = NULL;
1800 if (unlikely (ld_handle_filename_list (fnames) != 0))
1807 /* Store the file info. */
1808 fileinfo->elf = elf;
1810 /* The file is ready for action. */
1811 fileinfo->status = opened;
1818 add_whole_archive (struct usedfiles *fileinfo)
1821 Elf_Cmd cmd = ELF_C_READ_MMAP_PRIVATE;
1824 while ((arelf = elf_begin (fileinfo->fd, cmd, fileinfo->elf)) != NULL)
1826 Elf_Arhdr *arhdr = elf_getarhdr (arelf);
1827 struct usedfiles *newp;
1832 /* Just to be sure; since these are no files in the archive
1833 these names should never be returned. */
1834 assert (strcmp (arhdr->ar_name, "/") != 0);
1835 assert (strcmp (arhdr->ar_name, "//") != 0);
1837 newp = ld_new_inputfile (arhdr->ar_name, relocatable_file_type);
1838 newp->archive_file = fileinfo;
1840 if (unlikely (ld_state.trace_files))
1841 print_file_name (stdout, newp, 1, 1);
1843 /* This shows that this file is contained in an archive. */
1845 /* Store the ELF descriptor. */
1847 /* Show that we are open for business. */
1848 newp->status = opened;
1850 /* Proces the file, add all the symbols etc. */
1851 res = file_process2 (newp);
1852 if (unlikely (res != 0))
1855 /* Advance to the next archive element. */
1856 cmd = elf_next (arelf);
1864 extract_from_archive (struct usedfiles *fileinfo)
1866 static int archive_seq;
1869 if (fileinfo->archive_seq == 0)
1870 /* This is an archive we are not using completely. Give it a
1872 fileinfo->archive_seq = ++archive_seq;
1874 /* If there are no unresolved symbols don't do anything. */
1875 assert (ld_state.extract_rule == defaultextract
1876 || ld_state.extract_rule == weakextract);
1877 if ((likely (ld_state.extract_rule == defaultextract)
1878 ? ld_state.nunresolved_nonweak : ld_state.nunresolved) == 0)
1884 /* Get all the symbols. */
1885 syms = elf_getarsym (fileinfo->elf, &nsyms);
1888 cannot_read_archive:
1889 error (0, 0, gettext ("cannot read archive `%s': %s"),
1890 fileinfo->rfname, elf_errmsg (-1));
1892 /* We cannot use this archive anymore. */
1893 fileinfo->status = closed;
1898 /* Now add all the symbols to the hash table. Note that there
1899 can potentially be duplicate definitions. We'll always use
1900 the first definition. */
1901 // XXX Is this a compatible behavior?
1908 for (cnt = 0; cnt < nsyms; ++cnt)
1910 struct symbol search = { .name = syms[cnt].as_name };
1911 struct symbol *sym = ld_symbol_tab_find (&ld_state.symbol_tab,
1912 syms[cnt].as_hash, &search);
1913 if (sym != NULL && ! sym->defined)
1915 /* The symbol is referenced and not defined. */
1918 struct usedfiles *newp;
1920 /* Find the archive member for this symbol. */
1921 if (unlikely (elf_rand (fileinfo->elf, syms[cnt].as_off)
1922 != syms[cnt].as_off))
1923 goto cannot_read_archive;
1925 /* Note: no test of a failing 'elf_begin' call. That's fine
1926 since 'elf'getarhdr' will report the problem. */
1927 arelf = elf_begin (fileinfo->fd, ELF_C_READ_MMAP_PRIVATE,
1929 arhdr = elf_getarhdr (arelf);
1931 goto cannot_read_archive;
1933 /* We have all the information and an ELF handle for the
1934 archive member. Create the normal data structure for
1936 newp = ld_new_inputfile (obstack_strdup (&ld_state.smem,
1938 relocatable_file_type);
1939 newp->archive_file = fileinfo;
1941 if (unlikely (ld_state.trace_files))
1942 print_file_name (stdout, newp, 1, 1);
1944 /* This shows that this file is contained in an archive. */
1946 /* Store the ELF descriptor. */
1948 /* Show that we are open for business. */
1949 newp->status = in_archive;
1951 /* Now read the file and add all the symbols. */
1952 res = file_process2 (newp);
1953 if (unlikely (res != 0))
1962 /* This is an archive therefore it must have a number. */
1963 assert (fileinfo->archive_seq != 0);
1964 ld_state.last_archive_used = fileinfo->archive_seq;
1974 file_process2 (struct usedfiles *fileinfo)
1978 if (likely (elf_kind (fileinfo->elf) == ELF_K_ELF))
1980 /* The first time we get here we read the ELF header. */
1982 if (likely (fileinfo->ehdr == NULL))
1984 if (likely (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_NONE))
1989 ehdr = xelf_getehdr (fileinfo->elf, fileinfo->ehdr);
1991 xelf_getehdr_copy (fileinfo->elf, ehdr, fileinfo->ehdr);
1995 fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1996 fileinfo->rfname, __FILE__, __LINE__);
1997 fileinfo->status = closed;
2001 if (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_REL
2002 && unlikely (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_DYN))
2003 /* XXX Add ebl* function to query types which are allowed
2008 print_file_name (stderr, fileinfo, 1, 0);
2010 gettext ("file of type %s cannot be linked in\n"),
2011 ebl_object_type_name (ld_state.ebl,
2012 FILEINFO_EHDR (fileinfo->ehdr).e_type,
2013 buf, sizeof (buf)));
2014 fileinfo->status = closed;
2018 /* Make sure the file type matches the backend. */
2019 if (FILEINFO_EHDR (fileinfo->ehdr).e_machine
2020 != ebl_get_elfmachine (ld_state.ebl))
2022 fprintf (stderr, gettext ("\
2023 %s: input file incompatible with ELF machine type %s\n"),
2025 ebl_backend_name (ld_state.ebl));
2026 fileinfo->status = closed;
2030 /* Determine the section header string table section index. */
2031 if (unlikely (elf_getshdrstrndx (fileinfo->elf, &fileinfo->shstrndx)
2034 fprintf (stderr, gettext ("\
2035 %s: cannot get section header string table index: %s\n"),
2036 fileinfo->rfname, elf_errmsg (-1));
2037 fileinfo->status = closed;
2042 /* Now handle the different types of files. */
2043 if (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_REL)
2045 /* Add all the symbol. Relocatable files have symbol
2047 res = add_relocatable_file (fileinfo, SHT_SYMTAB);
2051 bool has_l_name = fileinfo->file_type == archive_file_type;
2053 assert (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_DYN);
2055 /* If the file is a DT_NEEDED dependency then the type is
2056 already correctly specified. */
2057 if (fileinfo->file_type != dso_needed_file_type)
2058 fileinfo->file_type = dso_file_type;
2060 /* We cannot use DSOs when generating relocatable objects. */
2061 if (ld_state.file_type == relocatable_file_type)
2063 error (0, 0, gettext ("\
2064 cannot use DSO '%s' when generating relocatable object file"),
2069 /* Add all the symbols. For DSOs we are looking at the
2070 dynamic symbol table. */
2071 res = add_relocatable_file (fileinfo, SHT_DYNSYM);
2073 /* We always have to have a dynamic section. */
2074 assert (fileinfo->dynscn != NULL);
2076 /* We have to remember the dependencies for this object. It
2077 is necessary to look them up. */
2078 XElf_Shdr_vardef (dynshdr);
2079 xelf_getshdr (fileinfo->dynscn, dynshdr);
2081 Elf_Data *dyndata = elf_getdata (fileinfo->dynscn, NULL);
2082 /* XXX Should we flag the failure to get the dynamic section? */
2083 if (dynshdr != NULL)
2085 int cnt = dynshdr->sh_size / dynshdr->sh_entsize;
2086 XElf_Dyn_vardef (dyn);
2090 xelf_getdyn (dyndata, cnt, dyn);
2093 if(dyn->d_tag == DT_NEEDED)
2095 struct usedfiles *newp;
2097 newp = ld_new_inputfile (elf_strptr (fileinfo->elf,
2100 dso_needed_file_type);
2102 /* Enqueue the newly found dependencies. */
2103 // XXX Check that there not already a file with the
2105 CSNGL_LIST_ADD_REAR (ld_state.needed, newp);
2107 else if (dyn->d_tag == DT_SONAME)
2109 /* We use the DT_SONAME (this is what's there
2111 fileinfo->soname = elf_strptr (fileinfo->elf,
2120 /* Construct the file name if the DSO has no SONAME and the
2121 file name comes from a -lXX parameter on the comment
2123 if (unlikely (has_l_name))
2125 /* The FNAME is the parameter the user specified on the
2126 command line. We prepend "lib" and append ".so". */
2127 size_t len = strlen (fileinfo->fname) + 7;
2130 newp = (char *) obstack_alloc (&ld_state.smem, len);
2131 strcpy (stpcpy (stpcpy (newp, "lib"), fileinfo->fname), ".so");
2133 fileinfo->soname = newp;
2137 else if (likely (elf_kind (fileinfo->elf) == ELF_K_AR))
2139 if (unlikely (ld_state.extract_rule == allextract))
2140 /* Which this option enabled we have to add all the object
2141 files in the archive. */
2142 res = add_whole_archive (fileinfo);
2143 else if (ld_state.file_type == relocatable_file_type)
2145 /* When generating a relocatable object we don't find files
2148 error (0, 0, gettext ("input file '%s' ignored"), fileinfo->fname);
2154 if (ld_state.group_start_requested
2155 && ld_state.group_start_archive == NULL)
2156 ld_state.group_start_archive = fileinfo;
2158 if (ld_state.archives == NULL)
2159 ld_state.archives = fileinfo;
2161 if (ld_state.tailarchives != NULL)
2162 ld_state.tailarchives->next = fileinfo;
2163 ld_state.tailarchives = fileinfo;
2165 /* Extract only the members from the archive which are
2166 currently referenced by unresolved symbols. */
2167 res = extract_from_archive (fileinfo);
2171 /* This should never happen, we know about no other types. */
2178 /* Process a given file. The first parameter is a file descriptor for
2179 the file which can be -1 to indicate the file has not yet been
2180 found. The second parameter describes the file to be opened, the
2181 last one is the state of the linker which among other information
2182 contain the paths we look at. */
2184 ld_generic_file_process (int fd, struct usedfiles *fileinfo,
2185 struct ld_state *statep, struct usedfiles **nextp)
2189 /* By default we go to the next file in the list. */
2190 *nextp = fileinfo->next;
2192 /* Set the flag to signal we are looking for a group start. */
2193 if (unlikely (fileinfo->group_start))
2195 ld_state.group_start_requested = true;
2196 fileinfo->group_start = false;
2199 /* If the file isn't open yet, open it now. */
2200 if (likely (fileinfo->status == not_opened))
2202 bool fd_passed = true;
2204 if (likely (fd == -1))
2206 /* Find the file ourselves. */
2207 int err = open_along_path (fileinfo);
2208 if (unlikely (err != 0))
2209 /* We allow libraries and DSOs to be named more than once.
2210 Don't report an error to the caller. */
2211 return err == EAGAIN ? 0 : err;
2218 /* Remember where we got the descriptor from. */
2219 fileinfo->fd_passed = fd_passed;
2221 /* We found the file. Now test whether it is a file type we can
2224 XXX Do we need to have the ability to start from a given
2225 position in the search path again to look for another file if
2226 the one found has not the right type? */
2227 res = open_elf (fileinfo, elf_begin (fileinfo->fd,
2228 is_dso_p (fileinfo->fd)
2230 : ELF_C_READ_MMAP_PRIVATE, NULL));
2231 if (unlikely (res != 0))
2235 /* Now that we have opened the file start processing it. */
2236 if (likely (fileinfo->status != closed))
2237 res = file_process2 (fileinfo);
2239 /* Determine which file to look at next. */
2240 if (unlikely (fileinfo->group_backref != NULL))
2242 /* We only go back if an archive other than the one we would go
2243 back to has been used in the last round. */
2244 if (ld_state.last_archive_used > fileinfo->group_backref->archive_seq)
2246 *nextp = fileinfo->group_backref;
2247 ld_state.last_archive_used = 0;
2251 /* If we come here this means that the archives we read so
2252 far are not needed anymore. We can free some of the data
2254 struct usedfiles *runp = ld_state.archives;
2258 /* We don't need the ELF descriptor anymore. Unless there
2259 are no files from the archive used this will not free
2260 the whole file but only some data structures. */
2261 elf_end (runp->elf);
2266 while (runp != fileinfo->next);
2268 /* Do not do this again. */
2269 ld_state.archives = NULL;
2271 /* Do not move on to the next archive. */
2272 *nextp = fileinfo->next = NULL;
2275 else if (unlikely (fileinfo->group_end))
2277 /* This is the end of a group. We possibly have to go back.
2278 Determine which file we would go back to and see whether it
2279 makes sense. If there has not been an archive we don't have
2281 if (ld_state.group_start_requested)
2283 if (ld_state.group_start_archive != ld_state.tailarchives)
2284 /* The loop includes more than one archive, add the pointer. */
2286 *nextp = ld_state.tailarchives->group_backref =
2287 ld_state.group_start_archive;
2288 ld_state.last_archive_used = 0;
2291 /* We might still have to go back to the beginning of the
2292 group if since the last archive other files have been
2293 added. But we go back exactly once. */
2294 if (ld_state.tailarchives != fileinfo)
2296 *nextp = ld_state.group_start_archive;
2297 ld_state.last_archive_used = 0;
2301 /* Clear the flags. */
2302 ld_state.group_start_requested = false;
2303 ld_state.group_start_archive = NULL;
2304 fileinfo->group_end = false;
2311 /* Library names passed to the linker as -lXX represent files named
2312 libXX.YY. The YY part can have different forms, depending on the
2313 platform. The generic set is .so and .a (in this order). */
2314 static const char **
2315 ld_generic_lib_extensions (struct ld_state *statep __attribute__ ((__unused__)))
2317 static const char *exts[] =
2326 /* Flag unresolved symbols. */
2328 ld_generic_flag_unresolved (struct ld_state *statep)
2332 if (ld_state.nunresolved_nonweak > 0)
2334 /* Go through the list and determine the unresolved symbols. */
2335 struct symbol *first;
2338 s = first = ld_state.unresolved->next;
2341 if (! s->defined && ! s->weak)
2343 /* Two special symbol we recognize: the symbol for the
2344 GOT and the dynamic section. */
2345 if (strcmp (s->name, "_GLOBAL_OFFSET_TABLE_") == 0
2346 || strcmp (s->name, "_DYNAMIC") == 0)
2348 /* We will have to fill in more information later. */
2349 ld_state.need_got = true;
2351 /* Remember that we found it. */
2352 if (s->name[1] == 'G')
2353 ld_state.got_symbol = s;
2355 ld_state.dyn_symbol = s;
2357 else if (ld_state.file_type != dso_file_type || !ld_state.nodefs)
2359 /* XXX The error message should get better. It should use
2360 the debugging information if present to tell where in the
2361 sources the undefined reference is. */
2362 error (0, 0, gettext ("undefined symbol `%s' in %s"),
2363 s->name, s->file->fname);
2369 /* We cannot decide here what to do with undefined
2370 references which will come from DSO since we do not know
2371 what kind of symbol we expect. Only when looking at the
2372 relocations we can see whether we need a PLT entry or
2373 only a GOT entry. */
2384 /* Close the given file. */
2386 ld_generic_file_close (struct usedfiles *fileinfo, struct ld_state *statep)
2388 /* Close the ELF descriptor. */
2389 elf_end (fileinfo->elf);
2391 /* If we have opened the file descriptor close it. But we might
2392 have done this already in which case FD is -1. */
2393 if (!fileinfo->fd_passed && fileinfo->fd != -1)
2394 close (fileinfo->fd);
2396 /* We allocated the resolved file name. */
2397 if (fileinfo->fname != fileinfo->rfname)
2398 free ((char *) fileinfo->rfname);
2405 new_generated_scn (enum scn_kind kind, const char *name, int type, int flags,
2406 int entsize, int align)
2408 struct scnhead *newp;
2410 newp = (struct scnhead *) obstack_calloc (&ld_state.smem,
2411 sizeof (struct scnhead));
2414 newp->nameent = ebl_strtabadd (ld_state.shstrtab, name, 0);
2416 newp->flags = flags;
2417 newp->entsize = entsize;
2418 newp->align = align;
2419 newp->grp_signature = NULL;
2422 /* All is well. Create now the data for the section and insert it
2423 into the section table. */
2424 ld_section_tab_insert (&ld_state.section_tab, elf_hash (name), newp);
2428 /* Create the sections which are generated by the linker and are not
2429 present in the input file. */
2431 ld_generic_generate_sections (struct ld_state *statep)
2433 /* The relocation section type. */
2434 int rel_type = REL_TYPE (&ld_state) == DT_REL ? SHT_REL : SHT_RELA;
2436 /* When requested, every output file will have a build ID section. */
2437 if (statep->build_id != NULL)
2438 new_generated_scn (scn_dot_note_gnu_build_id, ".note.gnu.build-id",
2439 SHT_NOTE, SHF_ALLOC, 0, 4);
2441 /* When building dynamically linked object we have to include a
2442 section containing a string describing the interpreter. This
2443 should be at the very beginning of the file together with the
2444 other information the ELF loader (kernel or wherever) has to look
2445 at. We put it as the first section in the file.
2447 We also have to create the dynamic segment which is a special
2448 section the dynamic linker locates through an entry in the
2450 if (dynamically_linked_p ())
2452 /* Use any versioning (defined or required)? */
2453 bool use_versioning = false;
2454 /* Use version requirements? */
2455 bool need_version = false;
2457 /* First the .interp section. */
2458 if (ld_state.interp != NULL || ld_state.file_type != dso_file_type)
2459 new_generated_scn (scn_dot_interp, ".interp", SHT_PROGBITS, SHF_ALLOC,
2462 /* Now the .dynamic section. */
2463 new_generated_scn (scn_dot_dynamic, ".dynamic", SHT_DYNAMIC,
2464 DYNAMIC_SECTION_FLAGS (&ld_state),
2465 xelf_fsize (ld_state.outelf, ELF_T_DYN, 1),
2466 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2468 /* We will need in any case the dynamic symbol table (even in
2469 the unlikely case that no symbol is exported or referenced
2471 ld_state.need_dynsym = true;
2472 new_generated_scn (scn_dot_dynsym, ".dynsym", SHT_DYNSYM, SHF_ALLOC,
2473 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1),
2474 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2475 /* It comes with a string table. */
2476 new_generated_scn (scn_dot_dynstr, ".dynstr", SHT_STRTAB, SHF_ALLOC,
2478 /* And a hashing table. */
2479 // XXX For Linux/Alpha we need other sizes unless they change...
2480 if (GENERATE_SYSV_HASH)
2481 new_generated_scn (scn_dot_hash, ".hash", SHT_HASH, SHF_ALLOC,
2482 sizeof (Elf32_Word), sizeof (Elf32_Word));
2483 if (GENERATE_GNU_HASH)
2484 new_generated_scn (scn_dot_gnu_hash, ".gnu.hash", SHT_GNU_HASH,
2485 SHF_ALLOC, sizeof (Elf32_Word),
2486 sizeof (Elf32_Word));
2488 /* Create the section associated with the PLT if necessary. */
2489 if (ld_state.nplt > 0)
2491 /* Create the .plt section. */
2492 /* XXX We might need a function which returns the section flags. */
2493 new_generated_scn (scn_dot_plt, ".plt", SHT_PROGBITS,
2494 SHF_ALLOC | SHF_EXECINSTR,
2495 /* XXX Is the size correct? */
2496 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2497 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2499 /* Create the relocation section for the .plt. This is always
2500 separate even if the other relocation sections are combined. */
2501 new_generated_scn (scn_dot_pltrel, ".rel.plt", rel_type, SHF_ALLOC,
2503 ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
2504 : xelf_fsize (ld_state.outelf, ELF_T_RELA, 1),
2505 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2507 /* XXX We might need a function which returns the section flags. */
2508 new_generated_scn (scn_dot_gotplt, ".got.plt", SHT_PROGBITS,
2509 SHF_ALLOC | SHF_WRITE,
2510 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2511 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2513 /* Mark all used DSOs as used. Determine whether any referenced
2514 object uses symbol versioning. */
2515 if (ld_state.from_dso != NULL)
2517 struct symbol *srunp = ld_state.from_dso;
2521 srunp->file->used = true;
2523 if (srunp->file->verdefdata != NULL)
2527 /* The input DSO uses versioning. */
2528 use_versioning = true;
2529 /* We reference versions. */
2530 need_version = true;
2532 if (xelf_getversym_copy (srunp->file->versymdata,
2533 srunp->symidx, versym) == NULL)
2534 assert (! "xelf_getversym failed");
2536 /* We cannot link explicitly with an older
2537 version of a symbol. */
2538 assert ((versym & 0x8000) == 0);
2539 /* We cannot reference local (index 0) or plain
2540 global (index 1) versions. */
2541 assert (versym > 1);
2543 /* Check whether we have already seen the
2544 version and if not add it to the referenced
2545 versions in the output file. */
2546 if (! srunp->file->verdefused[versym])
2548 srunp->file->verdefused[versym] = 1;
2550 if (++srunp->file->nverdefused == 1)
2551 /* Count the file if it is using versioning. */
2552 ++ld_state.nverdeffile;
2553 ++ld_state.nverdefused;
2557 while ((srunp = srunp->next) != ld_state.from_dso);
2560 /* Create the sections used to record version dependencies. */
2562 new_generated_scn (scn_dot_version_r, ".gnu.version_r",
2563 SHT_GNU_verneed, SHF_ALLOC, 0,
2564 xelf_fsize (ld_state.outelf, ELF_T_WORD, 1));
2567 /* Now count the used DSOs since this is what the user
2570 if (ld_state.ndsofiles > 0)
2572 struct usedfiles *frunp = ld_state.dsofiles;
2575 if (! frunp->as_needed || frunp->used)
2578 if (frunp->lazyload)
2579 /* We have to create another dynamic section
2580 entry for the DT_POSFLAG_1 entry.
2582 XXX Once more functionality than the lazyloading
2583 flag are suppported the test must be
2587 while ((frunp = frunp->next) != ld_state.dsofiles);
2591 new_generated_scn (scn_dot_version, ".gnu.version", SHT_GNU_versym,
2593 xelf_fsize (ld_state.outelf, ELF_T_HALF, 1),
2594 xelf_fsize (ld_state.outelf, ELF_T_HALF, 1));
2596 /* We need some entries all the time. */
2597 ld_state.ndynamic = (7 + (ld_state.runpath != NULL
2598 || ld_state.rpath != NULL)
2600 + (ld_state.init_symbol != NULL ? 1 : 0)
2601 + (ld_state.fini_symbol != NULL ? 1 : 0)
2602 + (use_versioning ? 1 : 0)
2603 + (need_version ? 2 : 0)
2604 + (ld_state.nplt > 0 ? 4 : 0)
2605 + (ld_state.relsize_total > 0 ? 3 : 0));
2608 /* When creating a relocatable file or when we are not stripping the
2609 output file we create a symbol table. */
2610 ld_state.need_symtab = (ld_state.file_type == relocatable_file_type
2611 || ld_state.strip == strip_none);
2613 /* Add the .got section if needed. */
2614 if (ld_state.need_got)
2615 /* XXX We might need a function which returns the section flags. */
2616 new_generated_scn (scn_dot_got, ".got", SHT_PROGBITS,
2617 SHF_ALLOC | SHF_WRITE,
2618 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2619 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2621 /* Add the .rel.dyn section. */
2622 if (ld_state.relsize_total > 0)
2623 new_generated_scn (scn_dot_dynrel, ".rel.dyn", rel_type, SHF_ALLOC,
2625 ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
2626 : xelf_fsize (ld_state.outelf, ELF_T_RELA, 1),
2627 xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2631 /* Callback function registered with on_exit to make sure the temporary
2632 files gets removed if something goes wrong. */
2634 remove_tempfile (int status, void *arg)
2636 if (status != 0 && ld_state.tempfname != NULL)
2637 unlink (ld_state.tempfname);
2641 /* Create the output file. The file name is given or "a.out". We
2642 create as much of the ELF structure as possible. */
2644 ld_generic_open_outfile (struct ld_state *statep, int machine, int klass,
2647 /* We do not create the new file right away with the final name.
2648 This would destroy an existing file with this name before a
2649 replacement is finalized. We create instead a temporary file in
2650 the same directory. */
2651 if (ld_state.outfname == NULL)
2652 ld_state.outfname = "a.out";
2654 size_t outfname_len = strlen (ld_state.outfname);
2655 char *tempfname = (char *) obstack_alloc (&ld_state.smem,
2656 outfname_len + sizeof (".XXXXXX"));
2657 ld_state.tempfname = tempfname;
2663 strcpy (mempcpy (tempfname, ld_state.outfname, outfname_len), ".XXXXXX");
2665 /* The use of mktemp() here is fine. We do not want to use
2666 mkstemp() since then the umask isn't used. And the output
2667 file will have these permissions anyhow. Any intruder could
2668 change the file later if it would be possible now. */
2669 if (mktemp (tempfname) != NULL
2670 && (fd = open (tempfname, O_RDWR | O_EXCL | O_CREAT | O_NOFOLLOW,
2671 ld_state.file_type == relocatable_file_type
2672 ? DEFFILEMODE : ACCESSPERMS)) != -1)
2675 /* Failed this round. We keep trying a number of times. */
2677 error (EXIT_FAILURE, errno, gettext ("cannot create output file"));
2679 ld_state.outfd = fd;
2681 /* Make sure we remove the temporary file in case something goes
2683 on_exit (remove_tempfile, NULL);
2685 /* Create the ELF file data for the output file. */
2686 Elf *elf = ld_state.outelf = elf_begin (fd,
2688 ? ELF_C_WRITE : ELF_C_WRITE_MMAP,
2691 error (EXIT_FAILURE, 0,
2692 gettext ("cannot create ELF descriptor for output file: %s"),
2695 /* Create the basic data structures. */
2696 if (! xelf_newehdr (elf, klass))
2697 /* Couldn't create the ELF header. Very bad. */
2698 error (EXIT_FAILURE, 0,
2699 gettext ("could not create ELF header for output file: %s"),
2702 /* And get the current header so that we can modify it. */
2703 XElf_Ehdr_vardef (ehdr);
2704 xelf_getehdr (elf, ehdr);
2705 assert (ehdr != NULL);
2707 /* Set the machine type. */
2708 ehdr->e_machine = machine;
2710 /* Modify it according to the info we have here and now. */
2711 if (ld_state.file_type == executable_file_type)
2712 ehdr->e_type = ET_EXEC;
2713 else if (ld_state.file_type == dso_file_type)
2714 ehdr->e_type = ET_DYN;
2717 assert (ld_state.file_type == relocatable_file_type);
2718 ehdr->e_type = ET_REL;
2721 /* Set the ELF version. */
2722 ehdr->e_version = EV_CURRENT;
2724 /* Set the endianness. */
2725 ehdr->e_ident[EI_DATA] = data;
2727 /* Write the ELF header information back. */
2728 (void) xelf_update_ehdr (elf, ehdr);
2734 /* We compute the offsets of the various copied objects and the total
2735 size of the memory needed. */
2736 // XXX The method used here is simple: go from front to back and pack
2737 // the objects in this order. A more space efficient way would
2738 // actually trying to pack the objects as dense as possible. But this
2739 // is more expensive.
2741 compute_copy_reloc_offset (XElf_Shdr *shdr)
2743 struct symbol *runp = ld_state.from_dso;
2744 assert (runp != NULL);
2746 XElf_Off maxalign = 1;
2747 XElf_Off offset = 0;
2750 if (runp->need_copy)
2752 /* Determine alignment for the symbol. */
2753 // XXX The question is how? The symbol record itself does not
2754 // have the information. So we have to be conservative and
2755 // assume the alignment of the section the symbol is in.
2757 // XXX We can be more precise. Use the offset from the beginning
2758 // of the section and determine the largest power of two with
2760 XElf_Off symalign = MAX (SCNINFO_SHDR (runp->file->scninfo[runp->scndx].shdr).sh_addralign, 1);
2761 /* Keep track of the maximum alignment requirement. */
2762 maxalign = MAX (maxalign, symalign);
2764 /* Align current position. */
2765 offset = (offset + symalign - 1) & ~(symalign - 1);
2767 runp->merge.value = offset;
2769 offset += runp->size;
2771 while ((runp = runp->next) != ld_state.from_dso);
2773 shdr->sh_type = SHT_NOBITS;
2774 shdr->sh_size = offset;
2775 shdr->sh_addralign = maxalign;
2780 compute_common_symbol_offset (XElf_Shdr *shdr)
2782 struct symbol *runp = ld_state.common_syms;
2783 assert (runp != NULL);
2785 XElf_Off maxalign = 1;
2786 XElf_Off offset = 0;
2790 /* Determine alignment for the symbol. */
2791 XElf_Off symalign = runp->merge.value;
2793 /* Keep track of the maximum alignment requirement. */
2794 maxalign = MAX (maxalign, symalign);
2796 /* Align current position. */
2797 offset = (offset + symalign - 1) & ~(symalign - 1);
2799 runp->merge.value = offset;
2801 offset += runp->size;
2803 while ((runp = runp->next) != ld_state.common_syms);
2805 shdr->sh_type = SHT_NOBITS;
2806 shdr->sh_size = offset;
2807 shdr->sh_addralign = maxalign;
2812 sort_sections_generic (void)
2820 match_section (const char *osectname, struct filemask_section_name *sectmask,
2821 struct scnhead **scnhead, bool new_section, size_t segment_nr)
2823 struct scninfo *prevp;
2824 struct scninfo *runp;
2825 struct scninfo *notused;
2827 if (fnmatch (sectmask->section_name->name, (*scnhead)->name, 0) != 0)
2828 /* The section name does not match. */
2831 /* If this is a section generated by the linker it doesn't contain
2832 the regular information (i.e., input section data etc) and must
2833 be handle special. */
2834 if ((*scnhead)->kind != scn_normal)
2836 (*scnhead)->name = osectname;
2837 (*scnhead)->segment_nr = segment_nr;
2839 /* We have to count note section since they get their own
2840 program header entry. */
2841 if ((*scnhead)->type == SHT_NOTE)
2842 ++ld_state.nnotesections;
2844 ld_state.allsections[ld_state.nallsections++] = (*scnhead);
2848 /* Now we have to match the file names of the input files. Some of
2849 the sections here might not match. */
2850 runp = (*scnhead)->last->next;
2851 prevp = (*scnhead)->last;
2856 /* Base of the file name the section comes from. */
2857 const char *brfname = basename (runp->fileinfo->rfname);
2859 /* If the section isn't used, the name doesn't match the positive
2860 inclusion list, or the name does match the negative inclusion
2861 list, ignore the section. */
2863 || (sectmask->filemask != NULL
2864 && fnmatch (sectmask->filemask, brfname, 0) != 0)
2865 || (sectmask->excludemask != NULL
2866 && fnmatch (sectmask->excludemask, brfname, 0) == 0))
2868 /* This file does not match the file name masks. */
2869 if (notused == NULL)
2874 if (runp == notused)
2877 /* The section fulfills all requirements, add it to the output
2878 file with the correct section name etc. */
2881 struct scninfo *found = runp;
2883 /* Remove this input section data buffer from the list. */
2885 runp = prevp->next = runp->next;
2893 /* Create a new section for the output file if the 'new_section'
2894 flag says so. Otherwise append the buffer to the last
2895 section which we created in one of the last calls. */
2898 struct scnhead *newp;
2900 newp = (struct scnhead *) obstack_calloc (&ld_state.smem,
2902 newp->kind = scn_normal;
2903 newp->name = osectname;
2904 newp->type = SCNINFO_SHDR (found->shdr).sh_type;
2905 /* Executable or DSO do not have section groups. Drop that
2907 newp->flags = SCNINFO_SHDR (found->shdr).sh_flags & ~SHF_GROUP;
2908 newp->segment_nr = segment_nr;
2909 newp->last = found->next = found;
2911 newp->relsize = found->relsize;
2912 newp->entsize = SCNINFO_SHDR (found->shdr).sh_entsize;
2914 /* We have to count note section since they get their own
2915 program header entry. */
2916 if (newp->type == SHT_NOTE)
2917 ++ld_state.nnotesections;
2919 ld_state.allsections[ld_state.nallsections++] = newp;
2920 new_section = false;
2924 struct scnhead *queued;
2926 queued = ld_state.allsections[ld_state.nallsections - 1];
2928 found->next = queued->last->next;
2929 queued->last = queued->last->next = found;
2931 /* If the linker script forces us to add incompatible
2932 sections together do so. But reflect this in the
2933 type and flags of the resulting file. */
2934 if (queued->type != SCNINFO_SHDR (found->shdr).sh_type)
2935 /* XXX Any better choice? */
2936 queued->type = SHT_PROGBITS;
2937 if (queued->flags != SCNINFO_SHDR (found->shdr).sh_flags)
2938 /* Executable or DSO do not have section groups. Drop that
2940 queued->flags = ebl_sh_flags_combine (ld_state.ebl,
2942 SCNINFO_SHDR (found->shdr).sh_flags
2945 /* Accumulate the relocation section size. */
2946 queued->relsize += found->relsize;
2950 while (runp != NULL);
2957 sort_sections_lscript (void)
2959 struct scnhead *temp[ld_state.nallsections];
2961 /* Make a copy of the section head pointer array. */
2962 memcpy (temp, ld_state.allsections,
2963 ld_state.nallsections * sizeof (temp[0]));
2964 size_t nallsections = ld_state.nallsections;
2966 /* Convert the output segment list in a single-linked list. */
2967 struct output_segment *segment = ld_state.output_segments->next;
2968 ld_state.output_segments->next = NULL;
2969 ld_state.output_segments = segment;
2971 /* Put the sections in the correct order in the array in the state
2972 structure. This might involve merging of sections and also
2973 renaming the containing section in the output file. */
2974 ld_state.nallsections = 0;
2976 size_t last_writable = ~0ul;
2977 for (segment_nr = 0; segment != NULL; segment = segment->next, ++segment_nr)
2979 struct output_rule *orule;
2981 for (orule = segment->output_rules; orule != NULL; orule = orule->next)
2982 if (orule->tag == output_section)
2984 struct input_rule *irule;
2985 bool new_section = true;
2987 for (irule = orule->val.section.input; irule != NULL;
2988 irule = irule->next)
2989 if (irule->tag == input_section)
2993 for (cnt = 0; cnt < nallsections; ++cnt)
2994 if (temp[cnt] != NULL)
2996 match_section (orule->val.section.name,
2997 irule->val.section, &temp[cnt],
2998 new_section, segment_nr);
3002 if ((segment->mode & PF_W) != 0)
3003 last_writable = ld_state.nallsections - 1;
3006 /* In case we have to create copy relocations or we have common
3007 symbols, find the last writable segment and add one more data
3008 block. It will be a NOBITS block and take up no disk space.
3009 This is why it is important to get the last block. */
3010 if (ld_state.ncopy > 0 || ld_state.common_syms != NULL)
3012 if (last_writable == ~0ul)
3013 error (EXIT_FAILURE, 0, "no writable segment");
3015 if (ld_state.allsections[last_writable]->type != SHT_NOBITS)
3017 /* Make room in the ALLSECTIONS array for a new section.
3018 There is guaranteed room in the array. We add the new
3019 entry after the last writable section. */
3021 memmove (&ld_state.allsections[last_writable + 1],
3022 &ld_state.allsections[last_writable],
3023 (ld_state.nallsections - last_writable)
3024 * sizeof (ld_state.allsections[0]));
3026 ld_state.allsections[last_writable] = (struct scnhead *)
3027 obstack_calloc (&ld_state.smem, sizeof (struct scnhead));
3029 /* Name for the new section. */
3030 ld_state.allsections[last_writable]->name = ".bss";
3032 ld_state.allsections[last_writable]->type = SHT_NOBITS;
3033 /* Same segment as the last writable section. */
3034 ld_state.allsections[last_writable]->segment_nr
3035 = ld_state.allsections[last_writable - 1]->segment_nr;
3039 /* Create common symbol data block. */
3040 if (ld_state.ncopy > 0)
3043 struct scninfo *si = (struct scninfo *)
3044 obstack_calloc (&ld_state.smem, sizeof (*si) + sizeof (XElf_Shdr));
3045 si->shdr = (XElf_Shdr *) (si + 1);
3047 struct scninfo *si = (struct scninfo *) obstack_calloc (&ld_state.smem,
3051 /* Get the information regarding the symbols with copy relocations. */
3052 compute_copy_reloc_offset (&SCNINFO_SHDR (si->shdr));
3054 /* This section is needed. */
3056 /* Remember for later the section data structure. */
3057 ld_state.copy_section = si;
3059 if (likely (ld_state.allsections[last_writable]->last != NULL))
3061 si->next = ld_state.allsections[last_writable]->last->next;
3062 ld_state.allsections[last_writable]->last->next = si;
3063 ld_state.allsections[last_writable]->last = si;
3066 ld_state.allsections[last_writable]->last = si->next = si;
3069 /* Create common symbol data block. */
3070 if (ld_state.common_syms != NULL)
3073 struct scninfo *si = (struct scninfo *)
3074 obstack_calloc (&ld_state.smem, sizeof (*si) + sizeof (XElf_Shdr));
3075 si->shdr = (XElf_Shdr *) (si + 1);
3077 struct scninfo *si = (struct scninfo *) obstack_calloc (&ld_state.smem,
3081 /* Get the information regarding the symbols with copy relocations. */
3082 compute_common_symbol_offset (&SCNINFO_SHDR (si->shdr));
3084 /* This section is needed. */
3086 /* Remember for later the section data structure. */
3087 ld_state.common_section = si;
3089 if (likely (ld_state.allsections[last_writable]->last != NULL))
3091 si->next = ld_state.allsections[last_writable]->last->next;
3092 ld_state.allsections[last_writable]->last->next = si;
3093 ld_state.allsections[last_writable]->last = si;
3096 ld_state.allsections[last_writable]->last = si->next = si;
3101 /* Create the output sections now. This requires knowledge about all
3102 the sections we will need. It may be necessary to sort sections in
3103 the order they are supposed to appear in the executable. The
3104 sorting use many different kinds of information to optimize the
3105 resulting binary. Important is to respect segment boundaries and
3106 the needed alignment. The mode of the segments will be determined
3107 afterwards automatically by the output routines.
3109 The generic sorting routines work in one of two possible ways:
3111 - if a linker script specifies the sections to be used in the
3112 output and assigns them to a segment this information is used;
3114 - otherwise the linker will order the sections based on permissions
3115 and some special knowledge about section names.*/
3117 ld_generic_create_sections (struct ld_state *statep)
3119 struct scngroup *groups;
3122 /* For relocatable object we don't have to bother sorting the
3123 sections and we do want to preserve the relocation sections as
3124 they appear in the input files. */
3125 if (ld_state.file_type != relocatable_file_type)
3127 /* Collect all the relocation sections. They are handled
3129 struct scninfo *list = NULL;
3130 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
3131 if ((ld_state.allsections[cnt]->type == SHT_REL
3132 || ld_state.allsections[cnt]->type == SHT_RELA)
3133 /* The generated relocation sections are not of any
3135 && ld_state.allsections[cnt]->last != NULL)
3138 list = ld_state.allsections[cnt]->last;
3141 /* Merge the sections list. */
3142 struct scninfo *first = list->next;
3143 list->next = ld_state.allsections[cnt]->last->next;
3144 ld_state.allsections[cnt]->last->next = first;
3145 list = ld_state.allsections[cnt]->last;
3148 /* Remove the entry from the section list. */
3149 ld_state.allsections[cnt] = NULL;
3151 ld_state.rellist = list;
3153 if (ld_state.output_segments == NULL)
3154 /* Sort using builtin rules. */
3155 sort_sections_generic ();
3157 sort_sections_lscript ();
3160 /* Now iterate over the input sections and create the sections in the
3161 order they are required in the output file. */
3162 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
3164 struct scnhead *head = ld_state.allsections[cnt];
3166 XElf_Shdr_vardef (shdr);
3168 /* Don't handle unused sections. */
3172 /* We first have to create the section group if necessary.
3173 Section group sections must come (in section index order)
3174 before any of the section contained. This all is necessary
3175 only for relocatable object as other object types are not
3176 allowed to contain section groups. */
3177 if (ld_state.file_type == relocatable_file_type
3178 && unlikely (head->flags & SHF_GROUP))
3180 /* There is at least one section which is contained in a
3181 section group in the input file. This means we must
3182 create a section group here as well. The only problem is
3183 that not all input files have to have to same kind of
3184 partitioning of the sections. I.e., sections A and B in
3185 one input file and sections B and C in another input file
3186 can be in one group. That will result in a group
3187 containing the sections A, B, and C in the output
3189 struct scninfo *runp;
3190 Elf32_Word here_groupidx = 0;
3191 struct scngroup *here_group;
3192 struct member *newp;
3194 /* First check whether any section is already in a group.
3195 In this case we have to add this output section, too. */
3199 assert (runp->grpid != 0);
3201 here_groupidx = runp->fileinfo->scninfo[runp->grpid].outscnndx;
3202 if (here_groupidx != 0)
3205 while ((runp = runp->next) != head->last);
3207 if (here_groupidx == 0)
3209 /* We need a new section group section. */
3210 scn = elf_newscn (ld_state.outelf);
3211 xelf_getshdr (scn, shdr);
3213 error (EXIT_FAILURE, 0,
3214 gettext ("cannot create section for output file: %s"),
3217 here_group = (struct scngroup *) xmalloc (sizeof (*here_group));
3218 here_group->outscnidx = here_groupidx = elf_ndxscn (scn);
3219 here_group->nscns = 0;
3220 here_group->member = NULL;
3221 here_group->next = ld_state.groups;
3222 /* Pick a name for the section. To keep it meaningful
3223 we use a name used in the input files. If the
3224 section group in the output file should contain
3225 section which were in section groups of different
3226 names in the input files this is the users
3229 = ebl_strtabadd (ld_state.shstrtab,
3230 elf_strptr (runp->fileinfo->elf,
3231 runp->fileinfo->shstrndx,
3232 SCNINFO_SHDR (runp->shdr).sh_name),
3234 /* Signature symbol. */
3236 = runp->fileinfo->scninfo[runp->grpid].symbols;
3238 ld_state.groups = here_group;
3242 /* Search for the group with this index. */
3243 here_group = ld_state.groups;
3244 while (here_group->outscnidx != here_groupidx)
3245 here_group = here_group->next;
3248 /* Add the new output section. */
3249 newp = (struct member *) alloca (sizeof (*newp));
3254 CSNGL_LIST_ADD_REAR (here_group->member, newp);
3255 ++here_group->nscns;
3257 /* Store the section group index in all input files. */
3261 assert (runp->grpid != 0);
3263 if (runp->fileinfo->scninfo[runp->grpid].outscnndx == 0)
3264 runp->fileinfo->scninfo[runp->grpid].outscnndx = here_groupidx;
3266 assert (runp->fileinfo->scninfo[runp->grpid].outscnndx
3269 while ((runp = runp->next) != head->last);
3272 /* We'll use this section so get it's name in the section header
3274 if (head->kind == scn_normal)
3275 head->nameent = ebl_strtabadd (ld_state.shstrtab, head->name, 0);
3277 /* Create a new section in the output file and add all data
3278 from all the sections we read. */
3279 scn = elf_newscn (ld_state.outelf);
3280 head->scnidx = elf_ndxscn (scn);
3281 xelf_getshdr (scn, shdr);
3283 error (EXIT_FAILURE, 0,
3284 gettext ("cannot create section for output file: %s"),
3287 assert (head->type != SHT_NULL);
3288 assert (head->type != SHT_SYMTAB);
3289 assert (head->type != SHT_DYNSYM || head->kind != scn_normal);
3290 assert (head->type != SHT_STRTAB || head->kind != scn_normal);
3291 assert (head->type != SHT_GROUP);
3292 shdr->sh_type = head->type;
3293 shdr->sh_flags = head->flags;
3294 shdr->sh_addralign = head->align;
3295 shdr->sh_entsize = head->entsize;
3296 assert (shdr->sh_entsize != 0 || (shdr->sh_flags & SHF_MERGE) == 0);
3297 (void) xelf_update_shdr (scn, shdr);
3299 /* We have to know the section index of the dynamic symbol table
3301 if (head->kind == scn_dot_dynsym)
3302 ld_state.dynsymscnidx = elf_ndxscn (scn);
3305 /* Actually create the section group sections. */
3306 groups = ld_state.groups;
3307 while (groups != NULL)
3311 Elf32_Word *grpdata;
3312 struct member *runp;
3314 scn = elf_getscn (ld_state.outelf, groups->outscnidx);
3315 assert (scn != NULL);
3317 data = elf_newdata (scn);
3319 error (EXIT_FAILURE, 0,
3320 gettext ("cannot create section for output file: %s"),
3323 data->d_size = (groups->nscns + 1) * sizeof (Elf32_Word);
3324 data->d_buf = grpdata = (Elf32_Word *) xmalloc (data->d_size);
3325 data->d_type = ELF_T_WORD;
3326 data->d_version = EV_CURRENT;
3328 /* XXX What better to use? */
3329 data->d_align = sizeof (Elf32_Word);
3331 /* The first word in the section is the flag word. */
3332 /* XXX Set COMDATA flag is necessary. */
3335 runp = groups->member->next;
3338 /* Fill in the index of the section. */
3339 grpdata[cnt++] = runp->scn->scnidx;
3340 while ((runp = runp->next) != groups->member->next);
3342 groups = groups->next;
3348 reduce_symbol_p (XElf_Sym *sym, struct Ebl_Strent *strent)
3351 const char *version;
3352 struct id_list search;
3353 struct id_list *verp;
3354 bool result = ld_state.default_bind_local;
3356 if (XELF_ST_BIND (sym->st_info) == STB_LOCAL || sym->st_shndx == SHN_UNDEF)
3357 /* We don't have to do anything to local symbols here. */
3358 /* XXX Any section value in [SHN_LORESERVER,SHN_XINDEX) need
3359 special treatment? */
3362 /* XXX Handle other symbol bindings. */
3363 assert (XELF_ST_BIND (sym->st_info) == STB_GLOBAL
3364 || XELF_ST_BIND (sym->st_info) == STB_WEAK);
3366 str = ebl_string (strent);
3367 version = strchr (str, VER_CHR);
3368 if (version != NULL)
3370 search.id = strndupa (str, version - str);
3371 if (*++version == VER_CHR)
3372 /* Skip the second '@' signaling a default definition. */
3381 verp = ld_version_str_tab_find (&ld_state.version_str_tab,
3382 elf_hash (search.id), &search);
3383 while (verp != NULL)
3385 /* We have this symbol in the version hash table. Now match the
3387 if (strcmp (verp->u.s.versionname, version) == 0)
3389 return verp->u.s.local;
3394 /* XXX Add test for wildcard version symbols. */
3401 eval_expression (struct expression *expr, XElf_Addr addr)
3403 XElf_Addr val = ~((XElf_Addr) 0);
3408 val = expr->val.num;
3411 case exp_sizeof_headers:
3413 /* The 'elf_update' call determine the offset of the first
3414 section. The the size of the header. */
3415 XElf_Shdr_vardef (shdr);
3417 xelf_getshdr (elf_getscn (ld_state.outelf, 1), shdr);
3418 assert (shdr != NULL);
3420 val = shdr->sh_offset;
3425 val = ld_state.pagesize;
3429 /* We are here computing only address expressions. It seems not
3430 to be necessary to handle any variable but ".". Let's avoid
3431 the complication. If it turns up to be needed we can add
3433 if (strcmp (expr->val.str, ".") != 0)
3434 error (EXIT_FAILURE, 0, gettext ("\
3435 address computation expression contains variable '%s'"),
3442 val = (eval_expression (expr->val.binary.left, addr)
3443 * eval_expression (expr->val.binary.right, addr));
3447 val = (eval_expression (expr->val.binary.left, addr)
3448 / eval_expression (expr->val.binary.right, addr));
3452 val = (eval_expression (expr->val.binary.left, addr)
3453 % eval_expression (expr->val.binary.right, addr));
3457 val = (eval_expression (expr->val.binary.left, addr)
3458 + eval_expression (expr->val.binary.right, addr));
3462 val = (eval_expression (expr->val.binary.left, addr)
3463 - eval_expression (expr->val.binary.right, addr));
3467 val = (eval_expression (expr->val.binary.left, addr)
3468 & eval_expression (expr->val.binary.right, addr));
3472 val = (eval_expression (expr->val.binary.left, addr)
3473 | eval_expression (expr->val.binary.right, addr));
3477 val = eval_expression (expr->val.child, addr);
3478 if ((val & (val - 1)) != 0)
3479 error (EXIT_FAILURE, 0, gettext ("argument '%" PRIuMAX "' of ALIGN in address computation expression is no power of two"),
3481 val = (addr + val - 1) & ~(val - 1);
3489 /* Find a good as possible size for the hash table so that all the
3490 non-zero entries in HASHCODES don't collide too much and the table
3491 isn't too large. There is no exact formular for this so we use a
3492 heuristic. Depending on the optimization level the search is
3493 longer or shorter. */
3495 optimal_bucket_size (Elf32_Word *hashcodes, size_t maxcnt, int optlevel)
3508 /* When we are not optimizing we run only very few tests. */
3512 maxsize = maxcnt + 10000 / maxcnt;
3516 /* Does not make much sense to start with a smaller table than
3517 one which has at least four collisions. */
3518 minsize = MAX (1, maxcnt / 4);
3519 /* We look for a best fit in the range of up to eigth times the
3520 number of elements. */
3521 maxsize = 2 * maxcnt + (6 * MIN (optlevel, 100) * maxcnt) / 100;
3524 bestcost = UINT_MAX;
3526 /* Array for counting the collisions and chain lengths. */
3527 counts = (uint32_t *) xmalloc ((maxcnt + 1 + maxsize) * sizeof (uint32_t));
3528 lengths = &counts[maxcnt + 1];
3530 for (size = minsize; size <= maxsize; ++size)
3539 memset (lengths, '\0', size * sizeof (uint32_t));
3540 memset (counts, '\0', (maxcnt + 1) * sizeof (uint32_t));
3542 /* Determine how often each hash bucket is used. */
3543 assert (hashcodes[0] == 0);
3544 for (inner = 1; inner < maxcnt; ++inner)
3545 ++lengths[hashcodes[inner] % size];
3547 /* Determine the lengths. */
3549 for (inner = 0; inner < size; ++inner)
3551 ++counts[lengths[inner]];
3553 if (lengths[inner] > maxlength)
3554 maxlength = lengths[inner];
3557 /* Determine successful lookup length. */
3560 for (inner = 0; inner <= maxlength; ++inner)
3563 success += counts[inner] * acc;
3566 /* We can compute two factors now: the average length of a
3567 positive search and the average length of a negative search.
3568 We count the number of comparisons which have to look at the
3569 names themselves. Recognizing that the chain ended is not
3570 accounted for since it's almost for free.
3572 Which lookup is more important depends on the kind of DSO.
3573 If it is a system DSO like libc it is expected that most
3574 lookups succeed. Otherwise most lookups fail. */
3575 if (ld_state.is_system_library)
3576 factor = (1.0 * (double) success / (double) maxcnt
3577 + 0.3 * (double) maxcnt / (double) size);
3579 factor = (0.3 * (double) success / (double) maxcnt
3580 + 1.0 * (double) maxcnt / (double) size);
3582 /* Combine the lookup cost factor. The 1/16th addend adds
3583 penalties for too large table sizes. */
3584 cost = (2 + maxcnt + size) * (factor + 1.0 / 16.0);
3587 printf ("maxcnt = %d, size = %d, cost = %Ld, success = %g, fail = %g, factor = %g\n",
3588 maxcnt, size, cost, (double) success / (double) maxcnt, (double) maxcnt / (double) size, factor);
3591 /* Compare with current best results. */
3592 if (cost < bestcost)
3606 optimal_gnu_hash_size (Elf32_Word *hashcodes, size_t maxcnt, int optlevel,
3607 size_t *bitmask_nwords, size_t *shift, size_t *nbuckets)
3609 // XXX Implement something real
3610 *bitmask_nwords = 256;
3612 *nbuckets = 3 * maxcnt / 2;
3617 find_entry_point (void)
3621 if (ld_state.entry != NULL)
3623 struct symbol search = { .name = ld_state.entry };
3624 struct symbol *syment;
3626 syment = ld_symbol_tab_find (&ld_state.symbol_tab,
3627 elf_hash (ld_state.entry), &search);
3628 if (syment != NULL && syment->defined)
3630 /* We found the symbol. */
3631 Elf_Data *data = elf_getdata (elf_getscn (ld_state.outelf,
3632 ld_state.symscnidx), NULL);
3634 XElf_Sym_vardef (sym);
3638 xelf_getsym (data, ld_state.dblindirect[syment->outsymidx], sym);
3640 if (sym == NULL && ld_state.need_dynsym && syment->outdynsymidx != 0)
3642 /* Use the dynamic symbol table if available. */
3643 data = elf_getdata (elf_getscn (ld_state.outelf,
3644 ld_state.dynsymscnidx), NULL);
3648 xelf_getsym (data, syment->outdynsymidx, sym);
3652 return sym->st_value;
3654 /* XXX What to do if the output has no non-dynamic symbol
3655 table and the dynamic symbol table does not contain the
3657 assert (ld_state.need_symtab);
3658 assert (ld_state.symscnidx != 0);
3662 /* We couldn't find the symbol or none was given. Use the first
3663 address of the ".text" section then. */
3668 /* In DSOs this is no fatal error. They usually have no entry
3669 points. In this case we set the entry point to zero, which makes
3670 sure it will always fail. */
3671 if (ld_state.file_type == executable_file_type)
3673 if (ld_state.entry != NULL)
3674 error (0, 0, gettext ("\
3675 cannot find entry symbol '%s': defaulting to %#0*" PRIx64),
3677 xelf_getclass (ld_state.outelf) == ELFCLASS32 ? 10 : 18,
3680 error (0, 0, gettext ("\
3681 no entry symbol specified: defaulting to %#0*" PRIx64),
3682 xelf_getclass (ld_state.outelf) == ELFCLASS32 ? 10 : 18,
3691 fillin_special_symbol (struct symbol *symst, size_t scnidx, size_t nsym,
3692 Elf_Data *symdata, struct Ebl_Strtab *strtab)
3694 assert (ld_state.file_type != relocatable_file_type);
3696 XElf_Sym_vardef (sym);
3697 xelf_getsym_ptr (symdata, nsym, sym);
3699 /* The name offset will be filled in later. */
3701 /* Traditionally: globally visible. */
3702 sym->st_info = XELF_ST_INFO (symst->local ? STB_LOCAL : STB_GLOBAL,
3704 sym->st_other = symst->hidden ? STV_HIDDEN : STV_DEFAULT;
3705 /* Reference to the GOT or dynamic section. Since the GOT and
3706 dynamic section are only created for executables and DSOs it
3707 cannot be that the section index is too large. */
3708 assert (scnidx != 0);
3709 assert (scnidx < SHN_LORESERVE || scnidx == SHN_ABS);
3710 sym->st_shndx = scnidx;
3711 /* We want the beginning of the section. */
3716 /* Determine the size of the section. */
3717 if (scnidx != SHN_ABS)
3719 Elf_Data *data = elf_getdata (elf_getscn (ld_state.outelf, scnidx),
3721 assert (data != NULL);
3722 sym->st_size = data->d_size;
3723 /* Make sure there is no second data block. */
3724 assert (elf_getdata (elf_getscn (ld_state.outelf, scnidx), data)
3728 /* Insert symbol into the symbol table. Note that we do not have to
3729 use xelf_update_symshdx. */
3730 (void) xelf_update_sym (symdata, nsym, sym);
3732 /* Cross-references. */
3733 ndxtosym[nsym] = symst;
3734 symst->outsymidx = nsym;
3736 /* Add the name to the string table. */
3737 symstrent[nsym] = ebl_strtabadd (strtab, symst->name, 0);
3742 new_dynamic_entry (Elf_Data *data, int idx, XElf_Sxword tag, XElf_Addr val)
3744 XElf_Dyn_vardef (dyn);
3745 xelf_getdyn_ptr (data, idx, dyn);
3747 dyn->d_un.d_ptr = val;
3748 (void) xelf_update_dyn (data, idx, dyn);
3753 allocate_version_names (struct usedfiles *runp, struct Ebl_Strtab *dynstrtab)
3755 /* If this DSO has no versions skip it. */
3756 if (runp->status != opened || runp->verdefdata == NULL)
3759 /* Add the object name. */
3763 XElf_Verdef_vardef (def);
3764 XElf_Verdaux_vardef (aux);
3766 /* Get data at the next offset. */
3767 xelf_getverdef (runp->verdefdata, offset, def);
3768 assert (def != NULL);
3769 xelf_getverdaux (runp->verdefdata, offset + def->vd_aux, aux);
3770 assert (aux != NULL);
3772 assert (def->vd_ndx <= runp->nverdef);
3773 if (def->vd_ndx == 1 || runp->verdefused[def->vd_ndx] != 0)
3775 runp->verdefent[def->vd_ndx]
3776 = ebl_strtabadd (dynstrtab, elf_strptr (runp->elf,
3780 if (def->vd_ndx > 1)
3781 runp->verdefused[def->vd_ndx] = ld_state.nextveridx++;
3784 if (def->vd_next == 0)
3785 /* That were all versions. */
3788 offset += def->vd_next;
3794 create_verneed_data (XElf_Off offset, Elf_Data *verneeddata,
3795 struct usedfiles *runp, int *ntotal)
3797 size_t verneed_size = xelf_fsize (ld_state.outelf, ELF_T_VNEED, 1);
3798 size_t vernaux_size = xelf_fsize (ld_state.outelf, ELF_T_VNAUX, 1);
3800 bool filled = false;
3801 GElf_Verneed verneed;
3802 GElf_Vernaux vernaux;
3806 /* If this DSO has no versions skip it. */
3807 if (runp->nverdefused == 0)
3810 /* We fill in the Verneed record last. Remember the offset. */
3811 need_offset = offset;
3812 offset += verneed_size;
3814 for (cnt = 2; cnt <= runp->nverdef; ++cnt)
3815 if (runp->verdefused[cnt] != 0)
3817 assert (runp->verdefent[cnt] != NULL);
3821 vernaux.vna_next = vernaux_size;
3822 (void) gelf_update_vernaux (verneeddata, offset, &vernaux);
3823 offset += vernaux_size;
3826 vernaux.vna_hash = elf_hash (ebl_string (runp->verdefent[cnt]));
3827 vernaux.vna_flags = 0;
3828 vernaux.vna_other = runp->verdefused[cnt];
3829 vernaux.vna_name = ebl_strtaboffset (runp->verdefent[cnt]);
3835 vernaux.vna_next = 0;
3836 (void) gelf_update_vernaux (verneeddata, offset, &vernaux);
3837 offset += vernaux_size;
3839 verneed.vn_version = VER_NEED_CURRENT;
3840 verneed.vn_cnt = ndef;
3841 verneed.vn_file = ebl_strtaboffset (runp->verdefent[1]);
3842 /* The first auxiliary entry is always found directly
3843 after the verneed entry. */
3844 verneed.vn_aux = verneed_size;
3845 verneed.vn_next = --*ntotal > 0 ? offset - need_offset : 0;
3846 (void) gelf_update_verneed (verneeddata, need_offset, &verneed);
3852 /* Callback for qsort to sort dynamic string table. */
3853 static Elf32_Word *global_hashcodes;
3854 static size_t global_nbuckets;
3856 sortfct_hashval (const void *p1, const void *p2)
3858 size_t idx1 = *(size_t *) p1;
3859 size_t idx2 = *(size_t *) p2;
3861 int def1 = ndxtosym[idx1]->defined && !ndxtosym[idx1]->in_dso;
3862 int def2 = ndxtosym[idx2]->defined && !ndxtosym[idx2]->in_dso;
3871 Elf32_Word hval1 = (global_hashcodes[ndxtosym[idx1]->outdynsymidx]
3873 Elf32_Word hval2 = (global_hashcodes[ndxtosym[idx2]->outdynsymidx]
3884 /* Sort the dynamic symbol table. The GNU hash table lookup assumes
3885 that all symbols with the same hash value module the bucket table
3886 size follow one another. This avoids the extra hash chain table.
3887 There is no need (and no way) to perform this operation if we do
3888 not use the new hash table format. */
3890 create_gnu_hash (size_t nsym_local, size_t nsym, size_t nsym_dyn,
3891 Elf32_Word *gnuhashcodes)
3893 size_t gnu_bitmask_nwords = 0;
3894 size_t gnu_shift = 0;
3895 size_t gnu_nbuckets = 0;
3896 Elf32_Word *gnu_bitmask = NULL;
3897 Elf32_Word *gnu_buckets = NULL;
3898 Elf32_Word *gnu_chain = NULL;
3899 XElf_Shdr_vardef (shdr);
3901 /* Determine the "optimal" bucket size. */
3902 optimal_gnu_hash_size (gnuhashcodes, nsym_dyn, ld_state.optlevel,
3903 &gnu_bitmask_nwords, &gnu_shift, &gnu_nbuckets);
3905 /* Create the .gnu.hash section data structures. */
3906 Elf_Scn *hashscn = elf_getscn (ld_state.outelf, ld_state.gnuhashscnidx);
3907 xelf_getshdr (hashscn, shdr);
3908 Elf_Data *hashdata = elf_newdata (hashscn);
3909 if (shdr == NULL || hashdata == NULL)
3910 error (EXIT_FAILURE, 0, gettext ("\
3911 cannot create GNU hash table section for output file: %s"),
3914 shdr->sh_link = ld_state.dynsymscnidx;
3915 (void) xelf_update_shdr (hashscn, shdr);
3917 hashdata->d_size = (xelf_fsize (ld_state.outelf, ELF_T_ADDR,
3919 + (4 + gnu_nbuckets + nsym_dyn) * sizeof (Elf32_Word));
3920 hashdata->d_buf = xcalloc (1, hashdata->d_size);
3921 hashdata->d_align = sizeof (Elf32_Word);
3922 hashdata->d_type = ELF_T_WORD;
3923 hashdata->d_off = 0;
3925 ((Elf32_Word *) hashdata->d_buf)[0] = gnu_nbuckets;
3926 ((Elf32_Word *) hashdata->d_buf)[2] = gnu_bitmask_nwords;
3927 ((Elf32_Word *) hashdata->d_buf)[3] = gnu_shift;
3928 gnu_bitmask = &((Elf32_Word *) hashdata->d_buf)[4];
3929 gnu_buckets = &gnu_bitmask[xelf_fsize (ld_state.outelf, ELF_T_ADDR,
3931 / sizeof (*gnu_buckets)];
3932 gnu_chain = &gnu_buckets[gnu_nbuckets];
3934 void *endp = &gnu_chain[nsym_dyn];
3936 assert (endp == (void *) ((char *) hashdata->d_buf + hashdata->d_size));
3939 size_t *remap = xmalloc (nsym_dyn * sizeof (size_t));
3941 size_t nsym_dyn_cnt = 1;
3943 for (size_t cnt = nsym_local; cnt < nsym; ++cnt)
3944 if (symstrent[cnt] != NULL)
3946 assert (ndxtosym[cnt]->outdynsymidx > 0);
3947 assert (ndxtosym[cnt]->outdynsymidx < nsym_dyn);
3948 remap[ndxtosym[cnt]->outdynsymidx] = cnt;
3953 assert (nsym_dyn_cnt == nsym_dyn);
3955 // XXX Until we can rely on qsort_r use global variables.
3956 global_hashcodes = gnuhashcodes;
3957 global_nbuckets = gnu_nbuckets;
3958 qsort (remap + 1, nsym_dyn - 1, sizeof (size_t), sortfct_hashval);
3960 bool bm32 = (xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1)
3961 == sizeof (Elf32_Word));
3963 size_t first_defined = 0;
3964 Elf64_Word bitmask_idxbits = gnu_bitmask_nwords - 1;
3965 Elf32_Word last_bucket = 0;
3966 for (size_t cnt = 1; cnt < nsym_dyn; ++cnt)
3968 if (first_defined == 0)
3970 if (! ndxtosym[remap[cnt]]->defined
3971 || ndxtosym[remap[cnt]]->in_dso)
3974 ((Elf32_Word *) hashdata->d_buf)[1] = first_defined = cnt;
3977 Elf32_Word hval = gnuhashcodes[ndxtosym[remap[cnt]]->outdynsymidx];
3981 Elf32_Word *bsw = &gnu_bitmask[(hval / 32) & bitmask_idxbits];
3982 assert ((void *) gnu_bitmask <= (void *) bsw);
3983 assert ((void *) bsw < (void *) gnu_buckets);
3984 *bsw |= 1 << (hval & 31);
3985 *bsw |= 1 << ((hval >> gnu_shift) & 31);
3989 Elf64_Word *bsw = &((Elf64_Word *) gnu_bitmask)[(hval / 64)
3991 assert ((void *) gnu_bitmask <= (void *) bsw);
3992 assert ((void *) bsw < (void *) gnu_buckets);
3993 *bsw |= 1 << (hval & 63);
3994 *bsw |= 1 << ((hval >> gnu_shift) & 63);
3997 size_t this_bucket = hval % gnu_nbuckets;
3998 if (cnt == first_defined || this_bucket != last_bucket)
4000 if (cnt != first_defined)
4002 /* Terminate the previous chain. */
4003 assert ((void *) &gnu_chain[cnt - first_defined - 1] < endp);
4004 gnu_chain[cnt - first_defined - 1] |= 1;
4007 assert (this_bucket < gnu_nbuckets);
4008 gnu_buckets[this_bucket] = cnt;
4009 last_bucket = this_bucket;
4012 assert (cnt >= first_defined);
4013 assert (cnt - first_defined < nsym_dyn);
4014 gnu_chain[cnt - first_defined] = hval & ~1u;
4017 ndxtosym[remap[cnt]]->outdynsymidx = cnt;
4020 /* Terminate the last chain. */
4021 if (first_defined != 0)
4023 assert (nsym_dyn > first_defined);
4024 assert (nsym_dyn - first_defined - 1 < nsym_dyn);
4025 gnu_chain[nsym_dyn - first_defined - 1] |= 1;
4027 hashdata->d_size -= first_defined * sizeof (Elf32_Word);
4030 /* We do not need any hash table. */
4038 /* Create the SysV-style hash table. */
4040 create_hash (size_t nsym_local, size_t nsym, size_t nsym_dyn,
4041 Elf32_Word *hashcodes)
4044 Elf32_Word *bucket = NULL;
4045 Elf32_Word *chain = NULL;
4046 XElf_Shdr_vardef (shdr);
4048 /* Determine the "optimal" bucket size. If we also generate the
4049 new-style hash function there is no need to waste effort and
4050 space on the old one which should not be used. Make it as small
4052 if (GENERATE_GNU_HASH)
4055 nbucket = optimal_bucket_size (hashcodes, nsym_dyn, ld_state.optlevel);
4056 /* Create the .hash section data structures. */
4057 Elf_Scn *hashscn = elf_getscn (ld_state.outelf, ld_state.hashscnidx);
4058 xelf_getshdr (hashscn, shdr);
4059 Elf_Data *hashdata = elf_newdata (hashscn);
4060 if (shdr == NULL || hashdata == NULL)
4061 error (EXIT_FAILURE, 0, gettext ("\
4062 cannot create hash table section for output file: %s"),
4065 shdr->sh_link = ld_state.dynsymscnidx;
4066 (void) xelf_update_shdr (hashscn, shdr);
4068 hashdata->d_size = (2 + nsym_dyn + nbucket) * sizeof (Elf32_Word);
4069 hashdata->d_buf = xcalloc (1, hashdata->d_size);
4070 hashdata->d_align = sizeof (Elf32_Word);
4071 hashdata->d_type = ELF_T_WORD;
4072 hashdata->d_off = 0;
4074 ((Elf32_Word *) hashdata->d_buf)[0] = nbucket;
4075 ((Elf32_Word *) hashdata->d_buf)[1] = nsym_dyn;
4076 bucket = &((Elf32_Word *) hashdata->d_buf)[2];
4077 chain = &((Elf32_Word *) hashdata->d_buf)[2 + nbucket];
4079 for (size_t cnt = nsym_local; cnt < nsym; ++cnt)
4080 if (symstrent[cnt] != NULL)
4082 size_t dynidx = ndxtosym[cnt]->outdynsymidx;
4083 size_t hashidx = hashcodes[dynidx] % nbucket;
4084 if (bucket[hashidx] == 0)
4085 bucket[hashidx] = dynidx;
4088 hashidx = bucket[hashidx];
4089 while (chain[hashidx] != 0)
4090 hashidx = chain[hashidx];
4092 chain[hashidx] = dynidx;
4099 create_build_id_section (Elf_Scn *scn)
4101 /* We know how large the section will be so we can create it now. */
4102 Elf_Data *d = elf_newdata (scn);
4104 error (EXIT_FAILURE, 0, gettext ("cannot create build ID section: %s"),
4107 d->d_type = ELF_T_BYTE;
4108 d->d_version = EV_CURRENT;
4110 /* The note section header. */
4111 assert (sizeof (Elf32_Nhdr) == sizeof (Elf64_Nhdr));
4112 d->d_size = sizeof (GElf_Nhdr);
4113 /* The string is four bytes long. */
4114 d->d_size += sizeof (ELF_NOTE_GNU);
4115 assert (d->d_size % 4 == 0);
4117 if (strcmp (ld_state.build_id, "md5") == 0
4118 || strcmp (ld_state.build_id, "uuid") == 0)
4120 else if (strcmp (ld_state.build_id, "sha1") == 0)
4124 assert (ld_state.build_id[0] == '0' && ld_state.build_id[1] == 'x');
4125 /* Use an upper limit of the possible number of bytes generated
4127 d->d_size += strlen (ld_state.build_id) / 2;
4130 d->d_buf = xcalloc (d->d_size, 1);
4137 compute_hash_sum (void (*hashfct) (const void *, size_t, void *), void *ctx)
4139 /* The call cannot fail. */
4141 (void) elf_getshdrstrndx (ld_state.outelf, &shstrndx);
4143 const char *ident = elf_getident (ld_state.outelf, NULL);
4144 bool same_byte_order = ((ident[EI_DATA] == ELFDATA2LSB
4145 && __BYTE_ORDER == __LITTLE_ENDIAN)
4146 || (ident[EI_DATA] == ELFDATA2MSB
4147 && __BYTE_ORDER == __BIG_ENDIAN));
4149 /* Iterate over all sections to find those which are not strippable. */
4150 Elf_Scn *scn = NULL;
4151 while ((scn = elf_nextscn (ld_state.outelf, scn)) != NULL)
4153 /* Get the section header. */
4155 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
4156 assert (shdr != NULL);
4158 if (SECTION_STRIP_P (shdr, elf_strptr (ld_state.outelf, shstrndx,
4159 shdr->sh_name), true))
4160 /* The section can be stripped. Don't use it. */
4163 /* Do not look at NOBITS sections. */
4164 if (shdr->sh_type == SHT_NOBITS)
4167 /* Iterate through the list of data blocks. */
4168 Elf_Data *data = NULL;
4169 while ((data = INTUSE(elf_getdata) (scn, data)) != NULL)
4170 /* If the file byte order is the same as the host byte order
4171 process the buffer directly. If the data is just a stream
4172 of bytes which the library will not convert we can use it
4174 if (likely (same_byte_order) || data->d_type == ELF_T_BYTE)
4175 hashfct (data->d_buf, data->d_size, ctx);
4178 /* Convert the data to file byte order. */
4179 if (gelf_xlatetof (ld_state.outelf, data, data, ident[EI_DATA])
4181 error (EXIT_FAILURE, 0, gettext ("\
4182 cannot convert section data to file format: %s"),
4185 hashfct (data->d_buf, data->d_size, ctx);
4187 /* And convert it back. */
4188 if (gelf_xlatetom (ld_state.outelf, data, data, ident[EI_DATA])
4190 error (EXIT_FAILURE, 0, gettext ("\
4191 cannot convert section data to memory format: %s"),
4198 /* Iterate over the sections */
4200 compute_build_id (void)
4202 Elf_Data *d = elf_getdata (elf_getscn (ld_state.outelf,
4203 ld_state.buildidscnidx), NULL);
4206 GElf_Nhdr *hdr = d->d_buf;
4207 hdr->n_namesz = sizeof (ELF_NOTE_GNU);
4208 hdr->n_type = NT_GNU_BUILD_ID;
4209 char *dp = mempcpy (hdr + 1, ELF_NOTE_GNU, sizeof (ELF_NOTE_GNU));
4211 if (strcmp (ld_state.build_id, "sha1") == 0)
4213 /* Compute the SHA1 sum of various parts of the generated file.
4214 We compute the hash sum over the external representation. */
4215 struct sha1_ctx ctx;
4216 sha1_init_ctx (&ctx);
4218 /* Compute the hash sum by running over all sections. */
4219 compute_hash_sum ((void (*) (const void *, size_t, void *)) sha1_process_bytes,
4222 /* We are done computing the checksum. */
4223 (void) sha1_finish_ctx (&ctx, dp);
4225 hdr->n_descsz = SHA1_DIGEST_SIZE;
4227 else if (strcmp (ld_state.build_id, "md5") == 0)
4229 /* Compute the MD5 sum of various parts of the generated file.
4230 We compute the hash sum over the external representation. */
4232 md5_init_ctx (&ctx);
4234 /* Compute the hash sum by running over all sections. */
4235 compute_hash_sum ((void (*) (const void *, size_t, void *)) md5_process_bytes,
4238 /* We are done computing the checksum. */
4239 (void) md5_finish_ctx (&ctx, dp);
4241 hdr->n_descsz = MD5_DIGEST_SIZE;
4243 else if (strcmp (ld_state.build_id, "uuid") == 0)
4245 int fd = open ("/dev/urandom", O_RDONLY);
4247 error (EXIT_FAILURE, errno, gettext ("cannot open '%s'"),
4250 if (TEMP_FAILURE_RETRY (read (fd, dp, 16)) != 16)
4251 error (EXIT_FAILURE, 0, gettext ("cannot read enough data for UUID"));
4259 const char *cp = ld_state.build_id + 2;
4261 /* The form of the string has been verified before so here we can
4262 simplify the scanning. */
4265 if (isxdigit (cp[0]))
4267 char ch1 = tolower (cp[0]);
4268 char ch2 = tolower (cp[1]);
4270 *dp++ = (((isdigit (ch1) ? ch1 - '0' : ch1 - 'a' + 10) << 4)
4271 | (isdigit (ch2) ? ch2 - '0' : ch2 - 'a' + 10));
4276 while (*cp != '\0');
4281 /* Create the output file.
4283 For relocatable files what basically has to happen is that all
4284 sections from all input files are written into the output file.
4285 Sections with the same name are combined (offsets adjusted
4286 accordingly). The symbol tables are combined in one single table.
4287 When stripping certain symbol table entries are omitted.
4289 For executables (shared or not) we have to create the program header,
4290 additional sections like the .interp, eventually (in addition) create
4291 a dynamic symbol table and a dynamic section. Also the relocations
4292 have to be processed differently. */
4294 ld_generic_create_outfile (struct ld_state *statep)
4299 struct scninfo *scninfo;
4300 struct scnlist *next;
4302 struct scnlist *rellist = NULL;
4304 Elf_Scn *symscn = NULL;
4305 Elf_Scn *xndxscn = NULL;
4306 Elf_Scn *strscn = NULL;
4307 struct Ebl_Strtab *strtab = NULL;
4308 struct Ebl_Strtab *dynstrtab = NULL;
4309 XElf_Shdr_vardef (shdr);
4311 Elf_Data *symdata = NULL;
4312 Elf_Data *xndxdata = NULL;
4313 struct usedfiles *file;
4316 size_t nsym_allocated;
4317 size_t nsym_dyn = 0;
4318 Elf32_Word *dblindirect = NULL;
4322 Elf_Scn *shstrtab_scn;
4323 size_t shstrtab_ndx;
4324 XElf_Ehdr_vardef (ehdr);
4325 struct Ebl_Strent *symtab_ent = NULL;
4326 struct Ebl_Strent *xndx_ent = NULL;
4327 struct Ebl_Strent *strtab_ent = NULL;
4328 struct Ebl_Strent *shstrtab_ent;
4329 struct scngroup *groups;
4330 Elf_Scn *dynsymscn = NULL;
4331 Elf_Data *dynsymdata = NULL;
4332 Elf_Data *dynstrdata = NULL;
4333 Elf32_Word *hashcodes = NULL;
4334 Elf32_Word *gnuhashcodes = NULL;
4335 size_t nsym_dyn_allocated = 0;
4336 Elf_Scn *versymscn = NULL;
4337 Elf_Data *versymdata = NULL;
4339 if (ld_state.need_symtab)
4341 /* First create the symbol table. We need the symbol section itself
4342 and the string table for it. */
4343 symscn = elf_newscn (ld_state.outelf);
4344 ld_state.symscnidx = elf_ndxscn (symscn);
4345 symdata = elf_newdata (symscn);
4346 if (symdata == NULL)
4347 error (EXIT_FAILURE, 0,
4348 gettext ("cannot create symbol table for output file: %s"),
4351 symdata->d_type = ELF_T_SYM;
4352 /* This is an estimated size, but it will definitely cap the real value.
4353 We might have to adjust the number later. */
4354 nsym_allocated = (1 + ld_state.nsymtab + ld_state.nplt + ld_state.ngot
4355 + ld_state.nusedsections + ld_state.nlscript_syms);
4356 symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
4359 /* Optionally the extended section table. */
4360 /* XXX Is SHN_LORESERVE correct? Do we need some other sections? */
4361 if (unlikely (ld_state.nusedsections >= SHN_LORESERVE))
4363 xndxscn = elf_newscn (ld_state.outelf);
4364 ld_state.xndxscnidx = elf_ndxscn (xndxscn);
4366 xndxdata = elf_newdata (xndxscn);
4367 if (xndxdata == NULL)
4368 error (EXIT_FAILURE, 0,
4369 gettext ("cannot create symbol table for output file: %s"),
4372 /* The following relies on the fact that Elf32_Word and Elf64_Word
4373 have the same size. */
4374 xndxdata->d_type = ELF_T_WORD;
4375 /* This is an estimated size, but it will definitely cap the
4376 real value. we might have to adjust the number later. */
4377 xndxdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_WORD,
4379 /* The first entry is left empty, clear it here and now. */
4380 xndxdata->d_buf = memset (xmalloc (xndxdata->d_size), '\0',
4381 xelf_fsize (ld_state.outelf, ELF_T_WORD,
4383 xndxdata->d_off = 0;
4384 /* XXX Should use an ebl function. */
4385 xndxdata->d_align = sizeof (Elf32_Word);
4390 assert (ld_state.need_dynsym);
4392 /* First create the symbol table. We need the symbol section itself
4393 and the string table for it. */
4394 symscn = elf_getscn (ld_state.outelf, ld_state.dynsymscnidx);
4395 symdata = elf_newdata (symscn);
4396 if (symdata == NULL)
4397 error (EXIT_FAILURE, 0,
4398 gettext ("cannot create symbol table for output file: %s"),
4401 symdata->d_version = EV_CURRENT;
4402 symdata->d_type = ELF_T_SYM;
4403 /* This is an estimated size, but it will definitely cap the real value.
4404 We might have to adjust the number later. */
4405 nsym_allocated = (1 + ld_state.nsymtab + ld_state.nplt + ld_state.ngot
4406 - ld_state.nlocalsymbols + ld_state.nlscript_syms);
4407 symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
4411 /* The first entry is left empty, clear it here and now. */
4412 symdata->d_buf = memset (xmalloc (symdata->d_size), '\0',
4413 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
4415 /* XXX This is ugly but how else can it be done. */
4416 symdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4418 /* Allocate another array to keep track of the handles for the symbol
4420 symstrent = (struct Ebl_Strent **) xcalloc (nsym_allocated,
4421 sizeof (struct Ebl_Strent *));
4423 /* By starting at 1 we effectively add a null entry. */
4426 /* Iteration over all sections. */
4427 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
4429 struct scnhead *head = ld_state.allsections[cnt];
4431 struct scninfo *runp;
4435 /* Don't handle unused sections at all. */
4439 /* Get the section handle. */
4440 scn = elf_getscn (ld_state.outelf, head->scnidx);
4442 if (unlikely (head->kind == scn_dot_interp))
4444 Elf_Data *outdata = elf_newdata (scn);
4445 if (outdata == NULL)
4446 error (EXIT_FAILURE, 0,
4447 gettext ("cannot create section for output file: %s"),
4450 /* This is the string we'll put in the section. */
4451 const char *interp = ld_state.interp ?: "/lib/ld.so.1";
4453 /* Create the section data. */
4454 outdata->d_buf = (void *) interp;
4455 outdata->d_size = strlen (interp) + 1;
4456 outdata->d_type = ELF_T_BYTE;
4458 outdata->d_align = 1;
4459 outdata->d_version = EV_CURRENT;
4461 /* Remember the index of this section. */
4462 ld_state.interpscnidx = head->scnidx;
4467 if (unlikely (head->kind == scn_dot_got))
4469 /* Remember the index of this section. */
4470 ld_state.gotscnidx = elf_ndxscn (scn);
4472 /* Give the backend the change to initialize the section. */
4473 INITIALIZE_GOT (&ld_state, scn);
4478 if (unlikely (head->kind == scn_dot_gotplt))
4480 /* Remember the index of this section. */
4481 ld_state.gotpltscnidx = elf_ndxscn (scn);
4483 /* Give the backend the change to initialize the section. */
4484 INITIALIZE_GOTPLT (&ld_state, scn);
4489 if (unlikely (head->kind == scn_dot_dynrel))
4493 outdata = elf_newdata (scn);
4494 if (outdata == NULL)
4495 error (EXIT_FAILURE, 0,
4496 gettext ("cannot create section for output file: %s"),
4499 outdata->d_size = ld_state.relsize_total;
4500 outdata->d_buf = xmalloc (outdata->d_size);
4501 outdata->d_type = (REL_TYPE (&ld_state) == DT_REL
4502 ? ELF_T_REL : ELF_T_RELA);
4504 outdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4506 /* Remember the index of this section. */
4507 ld_state.reldynscnidx = elf_ndxscn (scn);
4512 if (unlikely (head->kind == scn_dot_dynamic))
4514 /* Only create the data for now. */
4517 /* Account for a few more entries we have to add. */
4518 if (ld_state.dt_flags != 0)
4519 ++ld_state.ndynamic;
4520 if (ld_state.dt_flags_1 != 0)
4521 ++ld_state.ndynamic;
4522 if (ld_state.dt_feature_1 != 0)
4523 ++ld_state.ndynamic;
4525 outdata = elf_newdata (scn);
4526 if (outdata == NULL)
4527 error (EXIT_FAILURE, 0,
4528 gettext ("cannot create section for output file: %s"),
4531 /* Create the section data. */
4532 outdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_DYN,
4534 outdata->d_buf = xcalloc (1, outdata->d_size);
4535 outdata->d_type = ELF_T_DYN;
4537 outdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4539 /* Remember the index of this section. */
4540 ld_state.dynamicscnidx = elf_ndxscn (scn);
4545 if (unlikely (head->kind == scn_dot_dynsym))
4547 /* We already know the section index. */
4548 assert (ld_state.dynsymscnidx == elf_ndxscn (scn));
4553 if (unlikely (head->kind == scn_dot_dynstr))
4555 /* Remember the index of this section. */
4556 ld_state.dynstrscnidx = elf_ndxscn (scn);
4558 /* Create the string table. */
4559 dynstrtab = ebl_strtabinit (true);
4562 We have to add all the strings which are needed in the
4563 dynamic section here. This means DT_FILTER,
4564 DT_AUXILIARY, ... entries. */
4565 if (ld_state.ndsofiles > 0)
4567 struct usedfiles *frunp = ld_state.dsofiles;
4570 if (! frunp->as_needed || frunp->used)
4571 frunp->sonameent = ebl_strtabadd (dynstrtab, frunp->soname,
4573 while ((frunp = frunp->next) != ld_state.dsofiles);
4577 /* Add the runtime path information. The strings are stored
4578 in the .dynstr section. If both rpath and runpath are defined
4579 the runpath information is used. */
4580 if (ld_state.runpath != NULL || ld_state.rpath != NULL)
4582 struct pathelement *startp;
4583 struct pathelement *prunp;
4589 if (ld_state.runpath != NULL)
4591 startp = ld_state.runpath;
4596 startp = ld_state.rpath;
4600 /* Determine how long the string will be. */
4601 for (len = 0, prunp = startp; prunp != NULL; prunp = prunp->next)
4602 len += strlen (prunp->pname) + 1;
4604 cp = str = (char *) obstack_alloc (&ld_state.smem, len);
4605 /* Copy the string. */
4606 for (prunp = startp; prunp != NULL; prunp = prunp->next)
4608 cp = stpcpy (cp, prunp->pname);
4611 /* Remove the last colon. */
4614 /* Remember the values until we can generate the dynamic
4616 ld_state.rxxpath_strent = ebl_strtabadd (dynstrtab, str, len);
4617 ld_state.rxxpath_tag = tag;
4623 if (unlikely (head->kind == scn_dot_hash))
4625 /* Remember the index of this section. */
4626 ld_state.hashscnidx = elf_ndxscn (scn);
4631 if (unlikely (head->kind == scn_dot_gnu_hash))
4633 /* Remember the index of this section. */
4634 ld_state.gnuhashscnidx = elf_ndxscn (scn);
4639 if (unlikely (head->kind == scn_dot_plt))
4641 /* Remember the index of this section. */
4642 ld_state.pltscnidx = elf_ndxscn (scn);
4644 /* Give the backend the change to initialize the section. */
4645 INITIALIZE_PLT (&ld_state, scn);
4650 if (unlikely (head->kind == scn_dot_pltrel))
4652 /* Remember the index of this section. */
4653 ld_state.pltrelscnidx = elf_ndxscn (scn);
4655 /* Give the backend the change to initialize the section. */
4656 INITIALIZE_PLTREL (&ld_state, scn);
4661 if (unlikely (head->kind == scn_dot_version))
4663 /* Remember the index of this section. */
4664 ld_state.versymscnidx = elf_ndxscn (scn);
4669 if (unlikely (head->kind == scn_dot_version_r))
4671 /* Remember the index of this section. */
4672 ld_state.verneedscnidx = elf_ndxscn (scn);
4677 if (unlikely (head->kind == scn_dot_note_gnu_build_id))
4679 /* Remember the index of this section. */
4680 ld_state.buildidscnidx = elf_ndxscn (scn);
4682 create_build_id_section (scn);
4687 /* If we come here we must be handling a normal section. */
4688 assert (head->kind == scn_normal);
4690 /* Create an STT_SECTION entry in the symbol table. But not for
4691 the symbolic symbol table. */
4692 if (ld_state.need_symtab)
4694 /* XXX Can we be cleverer and do this only if needed? */
4695 XElf_Sym_vardef (sym);
4697 /* Optimization ahead: in the native linker we get a pointer
4698 to the final location so that the following code writes
4699 directly in the correct place. Otherwise we write into
4700 the local variable first. */
4701 xelf_getsym_ptr (symdata, nsym, sym);
4703 /* Usual section symbol: local, no specific information,
4704 except the section index. The offset here is zero, the
4705 start address will later be added. */
4707 sym->st_info = XELF_ST_INFO (STB_LOCAL, STT_SECTION);
4711 /* In relocatable files the section index can be too big for
4712 the ElfXX_Sym struct. we have to deal with the extended
4714 if (likely (head->scnidx < SHN_LORESERVE))
4716 sym->st_shndx = head->scnidx;
4721 sym->st_shndx = SHN_XINDEX;
4722 xndx = head->scnidx;
4724 /* Commit the change. See the optimization above, this does
4725 not change the symbol table entry. But the extended
4726 section index table entry is always written, if there is
4728 assert (nsym < nsym_allocated);
4729 xelf_update_symshndx (symdata, xndxdata, nsym, sym, xndx, 0);
4731 /* Remember the symbol's index in the symbol table. */
4732 head->scnsymidx = nsym++;
4735 if (head->type == SHT_REL || head->type == SHT_RELA)
4737 /* Remember that we have to fill in the symbol table section
4739 if (ld_state.file_type == relocatable_file_type)
4741 struct scnlist *newp;
4743 newp = (struct scnlist *) alloca (sizeof (*newp));
4744 newp->scnidx = head->scnidx;
4745 newp->scninfo = head->last->next;
4749 SNGL_LIST_PUSH (rellist, newp);
4753 /* When we create an executable or a DSO we don't simply
4754 copy the existing relocations. Instead many will be
4755 resolved, others will be converted. Create a data buffer
4756 large enough to contain the contents which we will fill
4758 int type = head->type == SHT_REL ? ELF_T_REL : ELF_T_RELA;
4760 data = elf_newdata (scn);
4762 error (EXIT_FAILURE, 0,
4763 gettext ("cannot create section for output file: %s"),
4766 data->d_size = xelf_fsize (ld_state.outelf, type, head->relsize);
4767 data->d_buf = xcalloc (data->d_size, 1);
4768 data->d_type = type;
4769 data->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4776 /* Recognize string and merge flag and handle them. */
4777 if (head->flags & SHF_MERGE)
4779 /* We merge the contents of the sections. For this we do
4780 not look at the contents of section directly. Instead we
4781 look at the symbols of the section. */
4784 /* Concatenate the lists of symbols for all sections.
4786 XXX In case any input section has no symbols associated
4787 (this happens for debug sections) we cannot use this
4788 method. Implement parsing the other debug sections and
4789 find the string pointers. For now we don't merge. */
4790 runp = head->last->next;
4791 if (runp->symbols == NULL)
4793 head->flags &= ~SHF_MERGE;
4796 head->symbols = runp->symbols;
4798 while ((runp = runp->next) != head->last->next)
4800 if (runp->symbols == NULL)
4802 head->flags &= ~SHF_MERGE;
4803 head->symbols = NULL;
4807 struct symbol *oldhead = head->symbols->next_in_scn;
4809 head->symbols->next_in_scn = runp->symbols->next_in_scn;
4810 runp->symbols->next_in_scn = oldhead;
4811 head->symbols = runp->symbols;
4814 /* Create the output section. */
4815 outdata = elf_newdata (scn);
4816 if (outdata == NULL)
4817 error (EXIT_FAILURE, 0,
4818 gettext ("cannot create section for output file: %s"),
4821 /* We use different merging algorithms for performance
4822 reasons. We can easily handle single-byte and
4823 wchar_t-wide character strings. All other cases (which
4824 really should happen in real life) are handled by the
4826 if (SCNINFO_SHDR (head->last->shdr).sh_entsize == 1
4827 && (head->flags & SHF_STRINGS))
4829 /* Simple, single-byte string matching. */
4830 struct Ebl_Strtab *mergestrtab;
4831 struct symbol *symrunp;
4832 Elf_Data *locsymdata = NULL;
4833 Elf_Data *locdata = NULL;
4835 mergestrtab = ebl_strtabinit (false);
4837 symrunp = head->symbols->next_in_scn;
4841 /* Accelarate the loop. We cache the file
4842 information since it might very well be the case
4843 that the previous entry was from the same
4845 if (symrunp->file != file)
4847 /* Remember the file. */
4848 file = symrunp->file;
4849 /* Symbol table data from that file. */
4850 locsymdata = file->symtabdata;
4851 /* String section data. */
4852 locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
4854 assert (locdata != NULL);
4855 /* While we are at it, remember the output
4856 section. If we don't access the string data
4857 section the section won't be in the output
4858 file. So it is sufficient to do the work
4860 file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
4863 /* Get the symbol information. This provides us the
4864 offset into the string data section. */
4865 XElf_Sym_vardef (sym);
4866 xelf_getsym (locsymdata, symrunp->symidx, sym);
4867 assert (sym != NULL);
4869 /* Get the data from the file. Note that we access
4870 the raw section data; no endian-ness issues with
4871 single-byte strings. */
4872 symrunp->merge.handle
4873 = ebl_strtabadd (mergestrtab,
4874 (char *) locdata->d_buf + sym->st_value,
4877 while ((symrunp = symrunp->next_in_scn)
4878 != head->symbols->next_in_scn);
4880 /* All strings have been added. Create the final table. */
4881 ebl_strtabfinalize (mergestrtab, outdata);
4883 /* Compute the final offsets in the section. */
4884 symrunp = runp->symbols;
4887 symrunp->merge.value
4888 = ebl_strtaboffset (symrunp->merge.handle);
4889 symrunp->merged = 1;
4891 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4893 /* We don't need the string table anymore. */
4894 ebl_strtabfree (mergestrtab);
4896 else if (likely (SCNINFO_SHDR (head->last->shdr).sh_entsize
4897 == sizeof (wchar_t))
4898 && likely (head->flags & SHF_STRINGS))
4900 /* Simple, wchar_t string merging. */
4901 struct Ebl_WStrtab *mergestrtab;
4902 struct symbol *symrunp;
4903 Elf_Data *locsymdata = NULL;
4904 Elf_Data *locdata = NULL;
4906 mergestrtab = ebl_wstrtabinit (false);
4908 symrunp = runp->symbols;
4912 /* Accelarate the loop. We cache the file
4913 information since it might very well be the case
4914 that the previous entry was from the same
4916 if (symrunp->file != file)
4918 /* Remember the file. */
4919 file = symrunp->file;
4920 /* Symbol table data from that file. */
4921 locsymdata = file->symtabdata;
4922 /* String section data. */
4923 locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
4925 assert (locdata != NULL);
4927 /* While we are at it, remember the output
4928 section. If we don't access the string data
4929 section the section won't be in the output
4930 file. So it is sufficient to do the work
4932 file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
4935 /* Get the symbol information. This provides us the
4936 offset into the string data section. */
4937 XElf_Sym_vardef (sym);
4938 xelf_getsym (locsymdata, symrunp->symidx, sym);
4939 assert (sym != NULL);
4941 /* Get the data from the file. Using the raw
4942 section data here is possible since we don't
4943 interpret the string themselves except for
4944 looking for the wide NUL character. The NUL
4945 character has fortunately the same representation
4946 regardless of the byte order. */
4947 symrunp->merge.handle
4948 = ebl_wstrtabadd (mergestrtab,
4949 (wchar_t *) ((char *) locdata->d_buf
4950 + sym->st_value), 0);
4952 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4954 /* All strings have been added. Create the final table. */
4955 ebl_wstrtabfinalize (mergestrtab, outdata);
4957 /* Compute the final offsets in the section. */
4958 symrunp = runp->symbols;
4961 symrunp->merge.value
4962 = ebl_wstrtaboffset (symrunp->merge.handle);
4963 symrunp->merged = 1;
4965 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4967 /* We don't need the string table anymore. */
4968 ebl_wstrtabfree (mergestrtab);
4972 /* Non-standard merging. */
4973 struct Ebl_GStrtab *mergestrtab;
4974 struct symbol *symrunp;
4975 Elf_Data *locsymdata = NULL;
4976 Elf_Data *locdata = NULL;
4977 /* If this is no string section the length of each "string"
4979 unsigned int len = (head->flags & SHF_STRINGS) ? 0 : 1;
4981 /* This is the generic string table functionality. Much
4982 slower than the specialized code. */
4984 = ebl_gstrtabinit (SCNINFO_SHDR (head->last->shdr).sh_entsize,
4987 symrunp = runp->symbols;
4991 /* Accelarate the loop. We cache the file
4992 information since it might very well be the case
4993 that the previous entry was from the same
4995 if (symrunp->file != file)
4997 /* Remember the file. */
4998 file = symrunp->file;
4999 /* Symbol table data from that file. */
5000 locsymdata = file->symtabdata;
5001 /* String section data. */
5002 locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
5004 assert (locdata != NULL);
5006 /* While we are at it, remember the output
5007 section. If we don't access the string data
5008 section the section won't be in the output
5009 file. So it is sufficient to do the work
5011 file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
5014 /* Get the symbol information. This provides us the
5015 offset into the string data section. */
5016 XElf_Sym_vardef (sym);
5017 xelf_getsym (locsymdata, symrunp->symidx, sym);
5018 assert (sym != NULL);
5020 /* Get the data from the file. Using the raw
5021 section data here is possible since we don't
5022 interpret the string themselves except for
5023 looking for the wide NUL character. The NUL
5024 character has fortunately the same representation
5025 regardless of the byte order. */
5026 symrunp->merge.handle
5027 = ebl_gstrtabadd (mergestrtab,
5028 (char *) locdata->d_buf + sym->st_value,
5031 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
5033 /* Create the final table. */
5034 ebl_gstrtabfinalize (mergestrtab, outdata);
5036 /* Compute the final offsets in the section. */
5037 symrunp = runp->symbols;
5040 symrunp->merge.value
5041 = ebl_gstrtaboffset (symrunp->merge.handle);
5042 symrunp->merged = 1;
5044 while ((symrunp = symrunp->next_in_scn) != runp->symbols);
5046 /* We don't need the string table anymore. */
5047 ebl_gstrtabfree (mergestrtab);
5053 assert (head->scnidx == elf_ndxscn (scn));
5055 /* It is important to start with the first list entry (and
5056 not just any one) to add the sections in the correct
5058 runp = head->last->next;
5062 Elf_Data *outdata = elf_newdata (scn);
5063 if (outdata == NULL)
5064 error (EXIT_FAILURE, 0,
5065 gettext ("cannot create section for output file: %s"),
5068 /* Exceptional case: if we synthesize a data block SCN
5069 is NULL and the sectio header info must be for a
5070 SHT_NOBITS block and the size and alignment are
5072 if (likely (runp->scn != NULL))
5074 data = elf_getdata (runp->scn, NULL);
5075 assert (data != NULL);
5077 /* We reuse the data buffer in the input file. */
5080 /* Given that we read the input file from disk we know there
5081 cannot be another data part. */
5082 assert (elf_getdata (runp->scn, data) == NULL);
5086 /* Must be a NOBITS section. */
5087 assert (SCNINFO_SHDR (runp->shdr).sh_type == SHT_NOBITS);
5089 outdata->d_buf = NULL; /* Not needed. */
5090 outdata->d_type = ELF_T_BYTE;
5091 outdata->d_version = EV_CURRENT;
5092 outdata->d_size = SCNINFO_SHDR (runp->shdr).sh_size;
5093 outdata->d_align = SCNINFO_SHDR (runp->shdr).sh_addralign;
5096 XElf_Off align = MAX (1, outdata->d_align);
5097 assert (powerof2 (align));
5098 offset = ((offset + align - 1) & ~(align - 1));
5100 runp->offset = offset;
5101 runp->outscnndx = head->scnidx;
5102 runp->allsectionsidx = cnt;
5104 outdata->d_off = offset;
5106 offset += outdata->d_size;
5108 while ((runp = runp->next) != head->last->next);
5110 /* If necessary add the additional line to the .comment section. */
5111 if (ld_state.add_ld_comment
5113 && head->type == SHT_PROGBITS
5114 && strcmp (head->name, ".comment") == 0
5115 && head->entsize == 0)
5117 Elf_Data *outdata = elf_newdata (scn);
5119 if (outdata == NULL)
5120 error (EXIT_FAILURE, 0,
5121 gettext ("cannot create section for output file: %s"),
5124 outdata->d_buf = (void *) "\0ld (" PACKAGE_NAME ") " PACKAGE_VERSION;
5125 outdata->d_size = strlen ((char *) outdata->d_buf + 1) + 2;
5126 outdata->d_off = offset;
5127 outdata->d_type = ELF_T_BYTE;
5128 outdata->d_align = 1;
5130 /* XXX We should create a .comment section if none exists.
5131 This requires that we early on detect that no such
5132 section exists. This should probably be implemented
5133 together with some merging of the section contents.
5134 Currently identical entries are not merged. */
5138 /* The table we collect the strings in. */
5139 strtab = ebl_strtabinit (true);
5141 error (EXIT_FAILURE, errno, gettext ("cannot create string table"));
5145 /* Keep track of the use of the XINDEX. */
5149 /* We we generate a normal symbol table for an executable and the
5150 --export-dynamic option is not given, we need an extra table
5151 which keeps track of the symbol entry belonging to the symbol
5152 table entry. Note that EXPORT_ALL_DYNAMIC is always set if we
5153 generate a DSO so we do not have to test this separately. */
5154 ndxtosym = (struct symbol **) xcalloc (nsym_allocated,
5155 sizeof (struct symbol));
5157 /* Create the special symbol for the GOT section. */
5158 if (ld_state.got_symbol != NULL)
5160 assert (nsym < nsym_allocated);
5161 // XXX Fix so that it works even if no PLT is needed.
5162 fillin_special_symbol (ld_state.got_symbol, ld_state.gotpltscnidx,
5163 nsym++, symdata, strtab);
5166 /* Similarly for the dynamic section symbol. */
5167 if (ld_state.dyn_symbol != NULL)
5169 assert (nsym < nsym_allocated);
5170 fillin_special_symbol (ld_state.dyn_symbol, ld_state.dynamicscnidx,
5171 nsym++, symdata, strtab);
5174 /* Create symbol table entries for the symbols defined in the linker
5176 if (ld_state.lscript_syms != NULL)
5178 struct symbol *rsym = ld_state.lscript_syms;
5181 assert (nsym < nsym_allocated);
5182 fillin_special_symbol (rsym, SHN_ABS, nsym++, symdata, strtab);
5184 while ((rsym = rsym->next) != NULL);
5187 /* Iterate over all input files to collect the symbols. */
5188 file = ld_state.relfiles->next;
5189 symdata = elf_getdata (elf_getscn (ld_state.outelf, ld_state.symscnidx),
5195 Elf_Data *insymdata;
5196 Elf_Data *inxndxdata;
5198 /* There must be no dynamic symbol table when creating
5199 relocatable files. */
5200 assert (ld_state.file_type != relocatable_file_type
5201 || file->dynsymtabdata == NULL);
5203 insymdata = file->symtabdata;
5204 assert (insymdata != NULL);
5205 inxndxdata = file->xndxdata;
5207 maxcnt = file->nsymtab;
5209 file->symindirect = (Elf32_Word *) xcalloc (maxcnt, sizeof (Elf32_Word));
5211 /* The dynamic symbol table does not contain local symbols. So
5212 we skip those entries. */
5213 for (cnt = ld_state.need_symtab ? 1 : file->nlocalsymbols; cnt < maxcnt;
5216 XElf_Sym_vardef (sym);
5218 struct symbol *defp = NULL;
5220 xelf_getsymshndx (insymdata, inxndxdata, cnt, sym, xndx);
5221 assert (sym != NULL);
5223 if (unlikely (XELF_ST_TYPE (sym->st_info) == STT_SECTION))
5225 /* Section symbols should always be local but who knows... */
5226 if (ld_state.need_symtab)
5228 /* Determine the real section index in the source file.
5229 Use the XINDEX section content if necessary. We don't
5230 add this information to the dynamic symbol table. */
5231 if (sym->st_shndx != SHN_XINDEX)
5232 xndx = sym->st_shndx;
5234 assert (file->scninfo[xndx].allsectionsidx
5235 < ld_state.nallsections);
5236 file->symindirect[cnt] = ld_state.allsections[file->scninfo[xndx].allsectionsidx]->scnsymidx;
5237 /* Note that the resulting index can be zero here. There is
5238 no guarantee that the output file will contain all the
5239 sections the input file did. */
5244 if ((ld_state.strip >= strip_all || !ld_state.need_symtab)
5245 /* XXX Do we need these entries? */
5246 && XELF_ST_TYPE (sym->st_info) == STT_FILE)
5250 /* Copy old data. We create a temporary copy because the
5251 symbol might still be discarded. */
5257 if (sym->st_shndx != SHN_UNDEF
5258 && (sym->st_shndx < SHN_LORESERVE
5259 || sym->st_shndx == SHN_XINDEX))
5261 /* If we are creating an executable with no normal
5262 symbol table and we do not export all symbols and
5263 this symbol is not defined in a DSO as well, ignore
5265 if (!ld_state.export_all_dynamic && !ld_state.need_symtab)
5267 assert (cnt >= file->nlocalsymbols);
5268 defp = file->symref[cnt];
5269 assert (defp != NULL);
5276 /* Determine the real section index in the source file. Use
5277 the XINDEX section content if necessary. */
5278 if (sym->st_shndx != SHN_XINDEX)
5279 xndx = sym->st_shndx;
5281 sym->st_value += file->scninfo[xndx].offset;
5283 assert (file->scninfo[xndx].outscnndx < SHN_LORESERVE
5284 || file->scninfo[xndx].outscnndx > SHN_HIRESERVE);
5285 if (unlikely (file->scninfo[xndx].outscnndx > SHN_LORESERVE))
5287 /* It is not possible to have an extended section index
5288 table for the dynamic symbol table. */
5289 if (!ld_state.need_symtab)
5290 error (EXIT_FAILURE, 0, gettext ("\
5291 section index too large in dynamic symbol table"));
5293 assert (xndxdata != NULL);
5294 sym->st_shndx = SHN_XINDEX;
5295 xndx = file->scninfo[xndx].outscnndx;
5302 sym->st_shndx = file->scninfo[xndx].outscnndx;
5306 else if (sym->st_shndx == SHN_COMMON || sym->st_shndx == SHN_UNDEF)
5308 /* Check whether we have a (real) definition for this
5309 symbol. If this is the case we skip this symbol
5311 assert (cnt >= file->nlocalsymbols);
5312 defp = file->symref[cnt];
5313 assert (defp != NULL);
5315 assert (sym->st_shndx != SHN_COMMON || defp->defined);
5317 if ((sym->st_shndx == SHN_COMMON && !defp->common)
5318 || (sym->st_shndx == SHN_UNDEF && defp->defined)
5320 /* Ignore this symbol table entry, there is a
5321 "better" one or we already added it. */
5324 /* Remember that we already added this symbol. */
5327 /* Adjust the section number for common symbols. */
5328 if (sym->st_shndx == SHN_COMMON)
5330 sym->st_value = (ld_state.common_section->offset
5331 + file->symref[cnt]->merge.value);
5332 assert (ld_state.common_section->outscnndx < SHN_LORESERVE);
5333 sym->st_shndx = ld_state.common_section->outscnndx;
5337 else if (unlikely (sym->st_shndx != SHN_ABS))
5339 if (SPECIAL_SECTION_NUMBER_P (&ld_state, sym->st_shndx))
5340 /* XXX Add code to handle machine specific special
5345 /* Add the symbol name to the string table. If the user
5346 chooses the highest level of stripping avoid adding names
5347 for local symbols in the string table. */
5348 if (sym->st_name != 0
5349 && (ld_state.strip < strip_everything
5350 || XELF_ST_BIND (sym->st_info) != STB_LOCAL))
5351 symstrent[nsym] = ebl_strtabadd (strtab,
5352 elf_strptr (file->elf,
5356 /* Once we know the name this field will get the correct
5357 offset. For now set it to zero which means no name
5359 GElf_Word st_name = sym->st_name;
5362 /* If we had to merge sections we have a completely new
5363 offset for the symbol. */
5364 if (file->has_merge_sections && file->symref[cnt] != NULL
5365 && file->symref[cnt]->merged)
5366 sym->st_value = file->symref[cnt]->merge.value;
5368 /* Create the record in the output sections. */
5369 assert (nsym < nsym_allocated);
5370 xelf_update_symshndx (symdata, xndxdata, nsym, sym, xndx, 1);
5372 /* Add the reference to the symbol record in case we need it.
5373 Find the symbol if this has not happened yet. We do
5374 not need the information for local symbols. */
5375 if (defp == NULL && cnt >= file->nlocalsymbols)
5377 defp = file->symref[cnt];
5381 /* This is a symbol in a discarded COMDAT section.
5382 Find the definition we actually use. */
5383 // XXX The question is: do we have to do this here
5384 // XXX or can we do it earlier when we discard the
5386 struct symbol search;
5387 search.name = elf_strptr (file->elf, file->symstridx,
5389 struct symbol *realp
5390 = ld_symbol_tab_find (&ld_state.symbol_tab,
5391 elf_hash (search.name), &search);
5393 // XXX What to do here?
5394 error (EXIT_FAILURE, 0,
5395 "couldn't find symbol from COMDAT section");
5397 file->symref[cnt] = realp;
5403 /* Store the reference to the symbol record. The sorting
5404 code will have to keep this array in the correct order, too. */
5405 ndxtosym[nsym] = defp;
5407 /* One more entry finished. */
5408 if (cnt >= file->nlocalsymbols)
5410 assert (file->symref[cnt]->outsymidx == 0);
5411 file->symref[cnt]->outsymidx = nsym;
5413 file->symindirect[cnt] = nsym++;
5416 while ((file = file->next) != ld_state.relfiles->next);
5417 /* Make sure we didn't create the extended section index table for
5419 assert (xndxdata == NULL || need_xndx);
5421 /* Create the version related sections. */
5422 if (ld_state.verneedscnidx != 0)
5424 /* We know the number of input files and total number of
5425 referenced versions. This allows us to allocate the memory
5426 and then we iterate over the DSOs to get the version
5428 struct usedfiles *runp;
5430 runp = ld_state.dsofiles->next;
5432 allocate_version_names (runp, dynstrtab);
5433 while ((runp = runp->next) != ld_state.dsofiles->next);
5435 if (ld_state.needed != NULL)
5437 runp = ld_state.needed->next;
5439 allocate_version_names (runp, dynstrtab);
5440 while ((runp = runp->next) != ld_state.needed->next);
5444 /* At this point we should hide symbols and so on. */
5445 if (ld_state.default_bind_local || ld_state.version_str_tab.filled > 0)
5446 /* XXX Add one more test when handling of wildcard symbol names
5449 /* Check all non-local symbols whether they are on the export list. */
5450 bool any_reduced = false;
5452 for (cnt = 1; cnt < nsym; ++cnt)
5454 XElf_Sym_vardef (sym);
5456 /* Note that we don't have to use 'xelf_getsymshndx' since we
5457 only need the binding and the symbol name. */
5458 xelf_getsym (symdata, cnt, sym);
5459 assert (sym != NULL);
5461 if (reduce_symbol_p (sym, symstrent[cnt]))
5463 // XXX Check whether this is correct...
5464 assert (ndxtosym[cnt]->outdynsymidx != 0);
5465 ndxtosym[cnt]->outdynsymidx = 0;
5467 sym->st_info = XELF_ST_INFO (STB_LOCAL,
5468 XELF_ST_TYPE (sym->st_info));
5469 (void) xelf_update_sym (symdata, cnt, sym);
5471 /* Show that we don't need this string anymore. */
5472 if (ld_state.strip == strip_everything)
5474 symstrent[cnt] = NULL;
5480 if (unlikely (any_reduced))
5482 /* Since we will not write names of local symbols in the
5483 output file and we have reduced the binding of some
5484 symbols the string table previously constructed contains
5485 too many string. Correct it. */
5486 struct Ebl_Strtab *newp = ebl_strtabinit (true);
5488 for (cnt = 1; cnt < nsym; ++cnt)
5489 if (symstrent[cnt] != NULL)
5490 symstrent[cnt] = ebl_strtabadd (newp,
5491 ebl_string (symstrent[cnt]), 0);
5493 ebl_strtabfree (strtab);
5498 /* Add the references to DSOs. We can add these entries this late
5499 (after sorting out versioning) because references to DSOs are not
5501 if (ld_state.from_dso != NULL)
5503 struct symbol *runp;
5504 size_t plt_base = nsym + ld_state.nfrom_dso - ld_state.nplt;
5508 assert (ld_state.nfrom_dso >= ld_state.nplt);
5509 runp = ld_state.from_dso;
5512 // XXX What about functions which are only referenced via
5513 // pointers and not PLT entries? Can we distinguish such uses?
5515 if (runp->type == STT_FUNC)
5517 /* Store the PLT entry number. */
5518 runp->merge.value = plt_idx + 1;
5519 idx = plt_base + plt_idx++;
5522 idx = nsym + obj_idx++;
5524 XElf_Sym_vardef (sym);
5525 xelf_getsym_ptr (symdata, idx, sym);
5528 sym->st_size = runp->size;
5529 sym->st_info = XELF_ST_INFO (runp->weak ? STB_WEAK : STB_GLOBAL,
5531 sym->st_other = STV_DEFAULT;
5532 sym->st_shndx = SHN_UNDEF;
5534 /* Create the record in the output sections. */
5535 xelf_update_symshndx (symdata, xndxdata, idx, sym, 0, 0);
5537 const char *name = runp->name;
5540 if (runp->file->verdefdata != NULL)
5542 // XXX Is it useful to add the versym value to struct symbol?
5545 (void) xelf_getversym_copy (runp->file->versymdata, runp->symidx,
5548 /* One can only link with the default version. */
5549 assert ((versym & 0x8000) == 0);
5551 const char *versname
5552 = ebl_string (runp->file->verdefent[versym]);
5554 size_t versname_len = strlen (versname) + 1;
5555 namelen = strlen (name) + versname_len + 2;
5556 char *newp = (char *) obstack_alloc (&ld_state.smem, namelen);
5557 memcpy (stpcpy (stpcpy (newp, name), "@@"),
5558 versname, versname_len);
5562 symstrent[idx] = ebl_strtabadd (strtab, name, namelen);
5564 /* Record the initial index in the symbol table. */
5565 runp->outsymidx = idx;
5567 /* Remember the symbol record this ELF symbol came from. */
5568 ndxtosym[idx] = runp;
5570 while ((runp = runp->next) != ld_state.from_dso);
5572 assert (nsym + obj_idx == plt_base);
5573 assert (plt_idx == ld_state.nplt);
5574 nsym = plt_base + plt_idx;
5577 /* Now we know how many symbols will be in the output file. Adjust
5578 the count in the section data. */
5579 symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym);
5580 if (unlikely (xndxdata != NULL))
5581 xndxdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_WORD, nsym);
5583 /* Create the symbol string table section. */
5584 strscn = elf_newscn (ld_state.outelf);
5585 ld_state.strscnidx = elf_ndxscn (strscn);
5586 data = elf_newdata (strscn);
5587 xelf_getshdr (strscn, shdr);
5588 if (data == NULL || shdr == NULL)
5589 error (EXIT_FAILURE, 0,
5590 gettext ("cannot create section for output file: %s"),
5593 /* Create a compact string table, allocate the memory for it, and
5594 fill in the section data information. */
5595 ebl_strtabfinalize (strtab, data);
5597 shdr->sh_type = SHT_STRTAB;
5598 assert (shdr->sh_entsize == 0);
5600 if (unlikely (xelf_update_shdr (strscn, shdr) == 0))
5601 error (EXIT_FAILURE, 0,
5602 gettext ("cannot create section for output file: %s"),
5605 /* Fill in the offsets of the symbol names. */
5606 for (cnt = 1; cnt < nsym; ++cnt)
5607 if (symstrent[cnt] != NULL)
5609 XElf_Sym_vardef (sym);
5611 /* Note that we don't have to use 'xelf_getsymshndx' since we don't
5612 modify the section index. */
5613 xelf_getsym (symdata, cnt, sym);
5614 /* This better worked, we did it before. */
5615 assert (sym != NULL);
5616 sym->st_name = ebl_strtaboffset (symstrent[cnt]);
5617 (void) xelf_update_sym (symdata, cnt, sym);
5620 /* Since we are going to reorder the symbol table but still have to
5621 be able to find the new position based on the old one (since the
5622 latter is stored in 'symindirect' information of the input file
5623 data structure) we have to create yet another indirection
5625 ld_state.dblindirect = dblindirect
5626 = (Elf32_Word *) xmalloc (nsym * sizeof (Elf32_Word));
5628 /* Sort the symbol table so that the local symbols come first. */
5629 /* XXX We don't use stable sorting here. It seems not necessary and
5630 would be more expensive. If it turns out to be necessary this can
5634 while (nsym_local < cnt)
5636 XElf_Sym_vardef (locsym);
5638 XElf_Sym_vardef (globsym);
5639 Elf32_Word globxndx;
5643 xelf_getsymshndx (symdata, xndxdata, nsym_local, locsym, locxndx);
5644 /* This better works. */
5645 assert (locsym != NULL);
5647 if (XELF_ST_BIND (locsym->st_info) != STB_LOCAL
5648 && (ld_state.need_symtab || ld_state.export_all_dynamic))
5652 xelf_getsymshndx (symdata, xndxdata, cnt, globsym, globxndx);
5653 /* This better works. */
5654 assert (globsym != NULL);
5656 if (unlikely (XELF_ST_BIND (globsym->st_info) == STB_LOCAL))
5658 /* We swap the two entries. */
5660 /* Since we directly modify the data in the ELF
5661 data structure we have to make a copy of one
5663 XElf_Sym locsym_copy = *locsym;
5664 locsym = &locsym_copy;
5666 xelf_update_symshndx (symdata, xndxdata, nsym_local,
5667 globsym, globxndx, 1);
5668 xelf_update_symshndx (symdata, xndxdata, cnt,
5669 locsym, locxndx, 1);
5671 /* Also swap the cross references. */
5672 dblindirect[nsym_local] = cnt;
5673 dblindirect[cnt] = nsym_local;
5675 /* And the entries for the symbol names. */
5676 struct Ebl_Strent *strtmp = symstrent[nsym_local];
5677 symstrent[nsym_local] = symstrent[cnt];
5678 symstrent[cnt] = strtmp;
5680 /* And the mapping from symbol table entry to
5681 struct symbol record. */
5682 struct symbol *symtmp = ndxtosym[nsym_local];
5683 ndxtosym[nsym_local] = ndxtosym[cnt];
5684 ndxtosym[cnt] = symtmp;
5686 /* Go to the next entry. */
5693 dblindirect[cnt] = cnt;
5695 while (nsym_local < --cnt);
5700 dblindirect[nsym_local] = nsym_local;
5702 while (++nsym_local < cnt);
5705 /* The symbol 'nsym_local' is currently pointing to might be local,
5706 too. Check and increment the variable if this is the case. */
5707 if (likely (nsym_local < nsym))
5709 XElf_Sym_vardef (locsym);
5711 /* This entry isn't moved. */
5712 dblindirect[nsym_local] = nsym_local;
5714 /* Note that it is OK to not use 'xelf_getsymshndx' here. */
5715 xelf_getsym (symdata, nsym_local, locsym);
5716 /* This better works. */
5717 assert (locsym != NULL);
5719 if (XELF_ST_BIND (locsym->st_info) == STB_LOCAL)
5724 /* We need the versym array right away to keep track of the version
5726 if (ld_state.versymscnidx != 0)
5728 /* We allocate more memory than we need since the array is morroring
5729 the dynamic symbol table and not the normal symbol table. I.e.,
5730 no local symbols are present. */
5731 versymscn = elf_getscn (ld_state.outelf, ld_state.versymscnidx);
5732 versymdata = elf_newdata (versymscn);
5733 if (versymdata == NULL)
5734 error (EXIT_FAILURE, 0,
5735 gettext ("cannot create versioning section: %s"),
5738 versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
5739 nsym - nsym_local + 1);
5740 versymdata->d_buf = xcalloc (1, versymdata->d_size);
5741 versymdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_HALF, 1);
5742 versymdata->d_off = 0;
5743 versymdata->d_type = ELF_T_HALF;
5747 /* If we have to construct the dynamic symbol table we must not include
5748 the local symbols. If the normal symbol has to be emitted as well
5749 we haven't done anything else yet and we can construct it from
5751 if (unlikely (!ld_state.need_symtab))
5753 /* Note that the following code works even if there is no entry
5754 to remove since the zeroth entry is always local. */
5755 size_t reduce = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym_local - 1);
5757 XElf_Sym_vardef (nullsym);
5758 xelf_getsym_ptr (symdata, nsym_local - 1, nullsym);
5760 /* Note that we don't have to use 'xelf_update_symshndx' since
5761 this is the dynamic symbol table we write. */
5762 (void) xelf_update_sym (symdata, nsym_local - 1,
5763 memset (nullsym, '\0', sizeof (*nullsym)));
5765 /* Update the buffer pointer and size in the output data. */
5766 symdata->d_buf = (char *) symdata->d_buf + reduce;
5767 symdata->d_size -= reduce;
5769 /* Add the version symbol information. */
5770 if (versymdata != NULL)
5773 for (cnt = nsym_local; cnt < nsym; ++cnt, ++nsym_dyn)
5775 struct symbol *symp = ndxtosym[cnt];
5777 if (symp->file->versymdata != NULL)
5781 gelf_getversym (symp->file->versymdata, symp->symidx,
5784 (void) gelf_update_versym (versymdata, symp->outdynsymidx,
5785 &symp->file->verdefused[versym]);
5790 /* Since we only created the dynamic symbol table the number of
5791 dynamic symbols is the total number of symbols. */
5792 nsym_dyn = nsym - nsym_local + 1;
5794 /* XXX TBI. Create whatever data structure is missing. */
5797 else if (ld_state.need_dynsym)
5799 /* Create the dynamic symbol table section data along with the
5800 string table. We look at all non-local symbols we found for
5801 the normal symbol table and add those. */
5802 dynsymscn = elf_getscn (ld_state.outelf, ld_state.dynsymscnidx);
5803 dynsymdata = elf_newdata (dynsymscn);
5805 dynstrdata = elf_newdata (elf_getscn (ld_state.outelf,
5806 ld_state.dynstrscnidx));
5807 if (dynsymdata == NULL || dynstrdata == NULL)
5808 error (EXIT_FAILURE, 0, gettext ("\
5809 cannot create dynamic symbol table for output file: %s"),
5812 nsym_dyn_allocated = nsym - nsym_local + 1;
5813 dynsymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
5814 nsym_dyn_allocated);
5815 dynsymdata->d_buf = memset (xmalloc (dynsymdata->d_size), '\0',
5816 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
5817 dynsymdata->d_type = ELF_T_SYM;
5818 dynsymdata->d_off = 0;
5819 dynsymdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
5821 /* We need one more array which contains the hash codes of the
5823 hashcodes = (Elf32_Word *) xcalloc (__builtin_popcount ((int) ld_state.hash_style)
5824 * nsym_dyn_allocated,
5825 sizeof (Elf32_Word));
5826 gnuhashcodes = hashcodes;
5827 if (GENERATE_SYSV_HASH)
5828 gnuhashcodes += nsym_dyn_allocated;
5830 /* We have and empty entry at the beginning. */
5833 /* Populate the table. */
5834 for (cnt = nsym_local; cnt < nsym; ++cnt)
5836 XElf_Sym_vardef (sym);
5838 xelf_getsym (symdata, cnt, sym);
5839 assert (sym != NULL);
5841 if (sym->st_shndx == SHN_XINDEX)
5842 error (EXIT_FAILURE, 0, gettext ("\
5843 section index too large in dynamic symbol table"));
5845 /* We do not add the symbol to the dynamic symbol table if
5847 - the symbol is for a file
5848 - it is not externally visible (internal, hidden)
5849 - export_all_dynamic is not set and the symbol is only defined
5850 in the executable (i.e., it is defined, but not (also) in DSO)
5852 Set symstrent[cnt] to NULL in case an entry is ignored. */
5853 if (XELF_ST_TYPE (sym->st_info) == STT_FILE
5854 || XELF_ST_VISIBILITY (sym->st_other) == STV_INTERNAL
5855 || XELF_ST_VISIBILITY (sym->st_other) == STV_HIDDEN
5856 || (!ld_state.export_all_dynamic
5857 && !ndxtosym[cnt]->in_dso && ndxtosym[cnt]->defined))
5859 symstrent[cnt] = NULL;
5863 /* Store the index of the symbol in the dynamic symbol
5864 table. This is a preliminary value in case we use the
5865 GNU-style hash table. */
5866 ndxtosym[cnt]->outdynsymidx = nsym_dyn;
5868 /* Create a new string table entry. */
5869 const char *str = ndxtosym[cnt]->name;
5870 symstrent[cnt] = ebl_strtabadd (dynstrtab, str, 0);
5871 if (GENERATE_SYSV_HASH)
5872 hashcodes[nsym_dyn] = elf_hash (str);
5873 if (GENERATE_GNU_HASH)
5874 gnuhashcodes[nsym_dyn] = elf_gnu_hash (str);
5878 if (ld_state.file_type != relocatable_file_type)
5880 /* Finalize the dynamic string table. */
5881 ebl_strtabfinalize (dynstrtab, dynstrdata);
5883 assert (ld_state.hashscnidx != 0 || ld_state.gnuhashscnidx != 0);
5885 /* Create the GNU-style hash table. */
5886 if (GENERATE_GNU_HASH)
5887 create_gnu_hash (nsym_local, nsym, nsym_dyn, gnuhashcodes);
5889 /* Create the SysV-style hash table. This has to happen
5890 after the GNU-style table is created since
5891 CREATE-GNU-HASH might reorder the dynamic symbol table. */
5892 if (GENERATE_SYSV_HASH)
5893 create_hash (nsym_local, nsym, nsym_dyn, hashcodes);
5896 /* Add the version information. */
5897 if (versymdata != NULL)
5898 for (cnt = nsym_local; cnt < nsym; ++cnt)
5899 if (symstrent[cnt] != NULL)
5901 struct symbol *symp = ndxtosym[cnt];
5903 /* Synthetic symbols (i.e., those with no file attached)
5904 have no version information. */
5905 if (symp->file != NULL && symp->file->verdefdata != NULL)
5909 gelf_getversym (symp->file->versymdata, symp->symidx,
5912 (void) gelf_update_versym (versymdata, symp->outdynsymidx,
5913 &symp->file->verdefused[versym]);
5917 /* XXX Add support for version definitions. */
5918 GElf_Versym global = VER_NDX_GLOBAL;
5919 (void) gelf_update_versym (versymdata, nsym_dyn, &global);
5923 /* Update the information about the symbol section. */
5924 if (versymdata != NULL)
5926 /* Correct the size now that we know how many entries the
5927 dynamic symbol table has. */
5928 versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
5931 /* Add the reference to the symbol table. */
5932 xelf_getshdr (versymscn, shdr);
5933 assert (shdr != NULL);
5935 shdr->sh_link = ld_state.dynsymscnidx;
5937 (void) xelf_update_shdr (versymscn, shdr);
5941 if (ld_state.file_type != relocatable_file_type)
5943 /* Now put the names in. */
5944 for (cnt = nsym_local; cnt < nsym; ++cnt)
5945 if (symstrent[cnt] != NULL)
5947 XElf_Sym_vardef (sym);
5948 size_t dynidx = ndxtosym[cnt]->outdynsymidx;
5952 memcpy (xelf_getsym (dynsymdata, dynidx, sym),
5953 xelf_getsym (symdata, cnt, osym),
5956 xelf_getsym (symdata, cnt, sym);
5957 assert (sym != NULL);
5960 sym->st_name = ebl_strtaboffset (symstrent[cnt]);
5962 (void) xelf_update_sym (dynsymdata, dynidx, sym);
5967 /* Create the required version section. */
5968 if (ld_state.verneedscnidx != 0)
5970 Elf_Scn *verneedscn;
5971 Elf_Data *verneeddata;
5972 struct usedfiles *runp;
5973 size_t verneed_size = xelf_fsize (ld_state.outelf, ELF_T_VNEED, 1);
5974 size_t vernaux_size = xelf_fsize (ld_state.outelf, ELF_T_VNAUX, 1);
5978 verneedscn = elf_getscn (ld_state.outelf, ld_state.verneedscnidx);
5979 xelf_getshdr (verneedscn, shdr);
5980 verneeddata = elf_newdata (verneedscn);
5981 if (shdr == NULL || verneeddata == NULL)
5982 error (EXIT_FAILURE, 0,
5983 gettext ("cannot create versioning data: %s"),
5986 verneeddata->d_size = (ld_state.nverdeffile * verneed_size
5987 + ld_state.nverdefused * vernaux_size);
5988 verneeddata->d_buf = xmalloc (verneeddata->d_size);
5989 verneeddata->d_type = ELF_T_VNEED;
5990 verneeddata->d_align = xelf_fsize (ld_state.outelf, ELF_T_WORD, 1);
5991 verneeddata->d_off = 0;
5994 ntotal = ld_state.nverdeffile;
5995 runp = ld_state.dsofiles->next;
5998 offset = create_verneed_data (offset, verneeddata, runp,
6002 while (ntotal > 0 && runp != ld_state.dsofiles->next);
6006 runp = ld_state.needed->next;
6009 offset = create_verneed_data (offset, verneeddata, runp,
6013 while (ntotal > 0 && runp != ld_state.needed->next);
6016 assert (offset == verneeddata->d_size);
6018 /* Add the needed information to the section header. */
6019 shdr->sh_link = ld_state.dynstrscnidx;
6020 shdr->sh_info = ld_state.nverdeffile;
6021 (void) xelf_update_shdr (verneedscn, shdr);
6024 /* Adjust the section size. */
6025 dynsymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym_dyn);
6026 if (versymdata != NULL)
6027 versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
6030 /* Add the remaining information to the section header. */
6031 xelf_getshdr (dynsymscn, shdr);
6032 /* There is always exactly one local symbol. */
6034 /* Reference the string table. */
6035 shdr->sh_link = ld_state.dynstrscnidx;
6036 /* Write the updated info back. */
6037 (void) xelf_update_shdr (dynsymscn, shdr);
6040 /* We don't need the string table anymore. */
6043 /* Remember the total number of symbols in the dynamic symbol table. */
6044 ld_state.ndynsym = nsym_dyn;
6046 /* Fill in the section header information. */
6047 symscn = elf_getscn (ld_state.outelf, ld_state.symscnidx);
6048 xelf_getshdr (symscn, shdr);
6050 error (EXIT_FAILURE, 0,
6051 gettext ("cannot create symbol table for output file: %s"),
6054 shdr->sh_type = SHT_SYMTAB;
6055 shdr->sh_link = ld_state.strscnidx;
6056 shdr->sh_info = nsym_local;
6057 shdr->sh_entsize = xelf_fsize (ld_state.outelf, ELF_T_SYM, 1);
6059 (void) xelf_update_shdr (symscn, shdr);
6062 /* Add names for the generated sections. */
6063 if (ld_state.symscnidx != 0)
6064 symtab_ent = ebl_strtabadd (ld_state.shstrtab, ".symtab", 8);
6065 if (ld_state.xndxscnidx != 0)
6066 xndx_ent = ebl_strtabadd (ld_state.shstrtab, ".symtab_shndx", 14);
6067 if (ld_state.strscnidx != 0)
6068 strtab_ent = ebl_strtabadd (ld_state.shstrtab, ".strtab", 8);
6069 /* At this point we would have to test for failures in the
6070 allocation. But we skip this. First, the problem will be caught
6071 later when doing more allocations for the section header table.
6072 Even if this would not be the case all that would happen is that
6073 the section names are empty. The binary would still be usable if
6074 it is an executable or a DSO. Not adding the test here saves
6075 quite a bit of code. */
6078 /* Finally create the section for the section header string table. */
6079 shstrtab_scn = elf_newscn (ld_state.outelf);
6080 shstrtab_ndx = elf_ndxscn (shstrtab_scn);
6081 if (unlikely (shstrtab_ndx == SHN_UNDEF))
6082 error (EXIT_FAILURE, 0,
6083 gettext ("cannot create section header string section: %s"),
6086 /* Add the name of the section to the string table. */
6087 shstrtab_ent = ebl_strtabadd (ld_state.shstrtab, ".shstrtab", 10);
6088 if (unlikely (shstrtab_ent == NULL))
6089 error (EXIT_FAILURE, errno,
6090 gettext ("cannot create section header string section"));
6092 /* Finalize the section header string table. */
6093 data = elf_newdata (shstrtab_scn);
6095 error (EXIT_FAILURE, 0,
6096 gettext ("cannot create section header string section: %s"),
6098 ebl_strtabfinalize (ld_state.shstrtab, data);
6100 /* Now we know the string offsets for all section names. */
6101 for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
6102 if (ld_state.allsections[cnt]->scnidx != 0)
6106 scn = elf_getscn (ld_state.outelf, ld_state.allsections[cnt]->scnidx);
6108 xelf_getshdr (scn, shdr);
6109 assert (shdr != NULL);
6111 shdr->sh_name = ebl_strtaboffset (ld_state.allsections[cnt]->nameent);
6113 if (xelf_update_shdr (scn, shdr) == 0)
6117 /* Add the names for the generated sections to the respective
6119 if (symtab_ent != NULL)
6121 Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.symscnidx);
6123 xelf_getshdr (scn, shdr);
6124 /* This cannot fail, we already accessed the header before. */
6125 assert (shdr != NULL);
6127 shdr->sh_name = ebl_strtaboffset (symtab_ent);
6129 (void) xelf_update_shdr (scn, shdr);
6131 if (xndx_ent != NULL)
6133 Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.xndxscnidx);
6135 xelf_getshdr (scn, shdr);
6136 /* This cannot fail, we already accessed the header before. */
6137 assert (shdr != NULL);
6139 shdr->sh_name = ebl_strtaboffset (xndx_ent);
6141 (void) xelf_update_shdr (scn, shdr);
6143 if (strtab_ent != NULL)
6145 Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.strscnidx);
6147 xelf_getshdr (scn, shdr);
6148 /* This cannot fail, we already accessed the header before. */
6149 assert (shdr != NULL);
6151 shdr->sh_name = ebl_strtaboffset (strtab_ent);
6153 (void) xelf_update_shdr (scn, shdr);
6156 /* And the section header table section itself. */
6157 xelf_getshdr (shstrtab_scn, shdr);
6159 error (EXIT_FAILURE, 0,
6160 gettext ("cannot create section header string section: %s"),
6163 shdr->sh_name = ebl_strtaboffset (shstrtab_ent);
6164 shdr->sh_type = SHT_STRTAB;
6166 if (unlikely (xelf_update_shdr (shstrtab_scn, shdr) == 0))
6167 error (EXIT_FAILURE, 0,
6168 gettext ("cannot create section header string section: %s"),
6172 /* Add the correct section header info to the section group sections. */
6173 groups = ld_state.groups;
6174 while (groups != NULL)
6176 Elf_Scn *scn = elf_getscn (ld_state.outelf, groups->outscnidx);
6177 xelf_getshdr (scn, shdr);
6178 assert (shdr != NULL);
6180 shdr->sh_name = ebl_strtaboffset (groups->nameent);
6181 shdr->sh_type = SHT_GROUP;
6183 shdr->sh_link = ld_state.symscnidx;
6184 shdr->sh_entsize = sizeof (Elf32_Word);
6186 /* Determine the index for the signature symbol. */
6188 = groups->symbol->file->symindirect[groups->symbol->symidx];
6191 assert (groups->symbol->file->symref[groups->symbol->symidx]
6193 si = groups->symbol->file->symref[groups->symbol->symidx]->outsymidx;
6196 shdr->sh_info = ld_state.dblindirect[si];
6198 (void) xelf_update_shdr (scn, shdr);
6200 struct scngroup *oldp = groups;
6201 groups = groups->next;
6206 if (ld_state.file_type != relocatable_file_type)
6208 /* Every executable needs a program header. The number of entries
6209 varies. One exists for each segment. Each SHT_NOTE section gets
6210 one, too. For dynamically linked executables we have to create
6211 one for the program header, the interpreter, and the dynamic
6212 section. First count the number of segments.
6214 XXX Determine whether the segment is non-empty. */
6217 /* We always add a PT_GNU_stack entry. */
6220 struct output_segment *segment = ld_state.output_segments;
6221 while (segment != NULL)
6224 segment = segment->next;
6227 /* Add the number of SHT_NOTE sections. We counted them earlier. */
6228 nphdr += ld_state.nnotesections;
6230 /* If we create a DSO or the file is linked against DSOs we have
6231 at least one more entry: DYNAMIC. If an interpreter is
6232 specified we add PHDR and INTERP, too. */
6233 if (dynamically_linked_p ())
6237 if (ld_state.interp != NULL || ld_state.file_type != dso_file_type)
6241 /* If we need a TLS segment we need an entry for that. */
6242 if (ld_state.need_tls)
6245 /* Create the program header structure. */
6246 XElf_Phdr_vardef (phdr);
6247 if (xelf_newphdr (ld_state.outelf, nphdr) == 0)
6248 error (EXIT_FAILURE, 0, gettext ("cannot create program header: %s"),
6252 /* Determine the section sizes and offsets. We have to do this
6253 to be able to determine the memory layout (which normally
6254 differs from the file layout). */
6255 if (elf_update (ld_state.outelf, ELF_C_NULL) == -1)
6256 error (EXIT_FAILURE, 0, gettext ("while determining file layout: %s"),
6260 /* Now determine the memory addresses of all the sections and
6262 Elf32_Word nsec = 0;
6263 Elf_Scn *scn = elf_getscn (ld_state.outelf,
6264 ld_state.allsections[nsec]->scnidx);
6265 xelf_getshdr (scn, shdr);
6266 assert (shdr != NULL);
6268 /* The address we start with is the offset of the first (not
6270 XElf_Addr addr = shdr->sh_offset;
6271 XElf_Addr tls_offset = 0;
6272 XElf_Addr tls_start = ~((XElf_Addr) 0);
6273 XElf_Addr tls_end = 0;
6274 XElf_Off tls_filesize = 0;
6275 XElf_Addr tls_align = 0;
6277 /* The index of the first loadable segment. */
6279 if (dynamically_linked_p ())
6282 if (ld_state.interp != NULL
6283 || ld_state.file_type != dso_file_type)
6287 segment = ld_state.output_segments;
6288 while (segment != NULL)
6290 struct output_rule *orule;
6291 bool first_section = true;
6292 XElf_Off nobits_size = 0;
6293 XElf_Off memsize = 0;
6295 /* The minimum alignment is a page size. */
6296 segment->align = ld_state.pagesize;
6298 for (orule = segment->output_rules; orule != NULL;
6299 orule = orule->next)
6300 if (orule->tag == output_section)
6302 /* See whether this output rule corresponds to the next
6303 section. Yes, this is a pointer comparison. */
6304 if (ld_state.allsections[nsec]->name
6305 != orule->val.section.name)
6306 /* No, ignore this output rule. */
6309 /* We assign addresses only in segments which are actually
6311 if (segment->mode != 0)
6313 /* Adjust the offset of the input sections. */
6314 struct scninfo *isect;
6315 struct scninfo *first;
6317 isect = first = ld_state.allsections[nsec]->last;
6320 isect->offset += addr;
6321 while ((isect = isect->next) != first);
6323 /* Set the address of current section. */
6324 shdr->sh_addr = addr;
6326 /* Write the result back. */
6327 (void) xelf_update_shdr (scn, shdr);
6329 /* Remember the address. */
6330 ld_state.allsections[nsec]->addr = addr;
6332 /* Handle TLS sections. */
6333 if (unlikely (shdr->sh_flags & SHF_TLS))
6335 if (tls_start > addr)
6338 tls_offset = shdr->sh_offset;
6340 if (tls_end < addr + shdr->sh_size)
6341 tls_end = addr + shdr->sh_size;
6342 if (shdr->sh_type != SHT_NOBITS)
6343 tls_filesize += shdr->sh_size;
6344 if (shdr->sh_addralign > tls_align)
6345 tls_align = shdr->sh_addralign;
6351 /* The first segment starts at offset zero. */
6352 if (segment == ld_state.output_segments)
6354 segment->offset = 0;
6355 segment->addr = addr - shdr->sh_offset;
6359 segment->offset = shdr->sh_offset;
6360 segment->addr = addr;
6363 /* Determine the maximum alignment requirement. */
6364 segment->align = MAX (segment->align, shdr->sh_addralign);
6366 first_section = false;
6369 /* NOBITS TLS sections are not laid out in address space
6370 along with the other sections. */
6371 if (shdr->sh_type != SHT_NOBITS
6372 || (shdr->sh_flags & SHF_TLS) == 0)
6374 memsize = (shdr->sh_offset - segment->offset
6376 if (nobits_size != 0 && shdr->sh_type != SHT_NOTE)
6377 error (EXIT_FAILURE, 0, gettext ("\
6378 internal error: non-nobits section follows nobits section"));
6379 if (shdr->sh_type == SHT_NOBITS)
6380 nobits_size += shdr->sh_size;
6383 /* Determine the new address which is computed using
6384 the difference of the offsets on the sections. Note
6385 that this assumes that the sections following each
6386 other in the section header table are also
6387 consecutive in the file. This is true here because
6388 libelf constructs files this way. */
6389 XElf_Off oldoff = shdr->sh_offset;
6391 if (++nsec >= ld_state.nallsections)
6394 scn = elf_getscn (ld_state.outelf,
6395 ld_state.allsections[nsec]->scnidx);
6396 xelf_getshdr (scn, shdr);
6397 assert (shdr != NULL);
6399 /* This is the new address resulting from the offsets
6401 assert (oldoff <= shdr->sh_offset);
6402 addr += shdr->sh_offset - oldoff;
6406 assert (orule->tag == output_assignment);
6408 if (strcmp (orule->val.assignment->variable, ".") == 0)
6409 /* This is a change of the address. */
6410 addr = eval_expression (orule->val.assignment->expression,
6412 else if (orule->val.assignment->sym != NULL)
6414 /* This symbol is used. Update the symbol table
6416 XElf_Sym_vardef (sym);
6419 /* Note that we do not have to use
6420 xelf_getsymshndx since we only update the
6421 symbol address, not the section
6423 idx = dblindirect[orule->val.assignment->sym->outsymidx];
6424 xelf_getsym (symdata, idx, sym);
6425 sym->st_value = addr;
6426 (void) xelf_update_sym (symdata, idx, sym);
6428 idx = orule->val.assignment->sym->outdynsymidx;
6431 assert (dynsymdata != NULL);
6432 xelf_getsym (dynsymdata, idx, sym);
6433 sym->st_value = addr;
6434 (void) xelf_update_sym (dynsymdata, idx, sym);
6439 /* Store the segment parameter for loadable segments. */
6440 if (segment->mode != 0)
6442 xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
6444 phdr->p_type = PT_LOAD;
6445 phdr->p_offset = segment->offset;
6446 phdr->p_vaddr = segment->addr;
6447 phdr->p_paddr = phdr->p_vaddr;
6448 phdr->p_filesz = memsize - nobits_size;
6449 phdr->p_memsz = memsize;
6450 phdr->p_flags = segment->mode;
6451 phdr->p_align = segment->align;
6453 (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
6457 segment = segment->next;
6460 /* Create the other program header entries. */
6461 xelf_getehdr (ld_state.outelf, ehdr);
6462 assert (ehdr != NULL);
6464 /* Add the TLS information. */
6465 if (ld_state.need_tls)
6467 xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
6468 phdr->p_type = PT_TLS;
6469 phdr->p_offset = tls_offset;
6470 phdr->p_vaddr = tls_start;
6471 phdr->p_paddr = tls_start;
6472 phdr->p_filesz = tls_filesize;
6473 phdr->p_memsz = tls_end - tls_start;
6474 phdr->p_flags = PF_R;
6475 phdr->p_align = tls_align;
6476 ld_state.tls_tcb = tls_end;
6477 ld_state.tls_start = tls_start;
6479 (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
6483 /* Add the stack information. */
6484 xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
6485 phdr->p_type = PT_GNU_STACK;
6491 phdr->p_flags = (PF_R | PF_W
6492 | (ld_state.execstack == execstack_true ? PF_X : 0));
6493 phdr->p_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
6495 (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
6499 /* Adjust the addresses in the address fields of the symbol
6500 records according to the load addresses of the sections. */
6501 if (ld_state.need_symtab)
6502 for (cnt = 1; cnt < nsym; ++cnt)
6504 XElf_Sym_vardef (sym);
6507 xelf_getsymshndx (symdata, xndxdata, cnt, sym, shndx);
6508 assert (sym != NULL);
6510 if (sym->st_shndx != SHN_XINDEX)
6511 shndx = sym->st_shndx;
6513 if ((shndx > SHN_UNDEF && shndx < SHN_LORESERVE)
6514 || shndx > SHN_HIRESERVE)
6516 /* Note we subtract 1 from the section index since ALLSECTIONS
6517 does not store the dummy section with offset zero. */
6518 sym->st_value += ld_state.allsections[shndx - 1]->addr;
6520 /* We don't have to use 'xelf_update_symshndx' since the
6521 section number doesn't change. */
6522 (void) xelf_update_sym (symdata, cnt, sym);
6526 if (ld_state.need_dynsym)
6527 for (cnt = 1; cnt < nsym_dyn; ++cnt)
6529 XElf_Sym_vardef (sym);
6531 xelf_getsym (dynsymdata, cnt, sym);
6532 assert (sym != NULL);
6534 if (sym->st_shndx > SHN_UNDEF && sym->st_shndx < SHN_LORESERVE)
6536 /* Note we subtract 1 from the section index since ALLSECTIONS
6537 does not store the dummy section with offset zero. */
6538 sym->st_value += ld_state.allsections[sym->st_shndx - 1]->addr;
6540 /* We don't have to use 'xelf_update_symshndx' since the
6541 section number doesn't change. */
6542 (void) xelf_update_sym (dynsymdata, cnt, sym);
6546 /* Now is a good time to determine the values of all the symbols
6548 // XXX This loop is very inefficient. The hash tab iterator also
6549 // returns all symbols in DSOs.
6552 while ((se = ld_symbol_tab_iterate (&ld_state.symbol_tab, &p)) != NULL)
6555 XElf_Sym_vardef (sym);
6559 if (se->outdynsymidx != 0)
6561 xelf_getsym (dynsymdata, se->outdynsymidx, sym);
6562 assert (sym != NULL);
6563 addr = sym->st_value;
6565 else if (se->outsymidx != 0)
6567 assert (dblindirect[se->outsymidx] != 0);
6568 xelf_getsym (symdata, dblindirect[se->outsymidx], sym);
6569 assert (sym != NULL);
6570 addr = sym->st_value;
6575 se->merge.value = addr;
6578 /* Complete the header of the .rel.dyn/.rela.dyn section. Point
6579 to the symbol table. The sh_info field is left zero since
6580 there is no specific section the contained relocations are
6582 if (ld_state.reldynscnidx != 0)
6584 assert (ld_state.dynsymscnidx != 0);
6585 scn = elf_getscn (ld_state.outelf, ld_state.reldynscnidx);
6586 xelf_getshdr (scn, shdr);
6587 assert (shdr != NULL);
6589 shdr->sh_link = ld_state.dynsymscnidx;
6591 (void) xelf_update_shdr (scn, shdr);
6594 /* Fill in the dynamic segment/section. */
6595 if (dynamically_linked_p ())
6600 if (ld_state.interp != NULL || ld_state.file_type != dso_file_type)
6602 assert (ld_state.interpscnidx != 0);
6603 xelf_getshdr (elf_getscn (ld_state.outelf,
6604 ld_state.interpscnidx), shdr);
6605 assert (shdr != NULL);
6607 xelf_getphdr_ptr (ld_state.outelf, idx, phdr);
6608 phdr->p_type = PT_PHDR;
6609 phdr->p_offset = ehdr->e_phoff;
6610 phdr->p_vaddr = ld_state.output_segments->addr + phdr->p_offset;
6611 phdr->p_paddr = phdr->p_vaddr;
6612 phdr->p_filesz = ehdr->e_phnum * ehdr->e_phentsize;
6613 phdr->p_memsz = phdr->p_filesz;
6614 phdr->p_flags = 0; /* No need to set PF_R or so. */
6615 phdr->p_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
6617 (void) xelf_update_phdr (ld_state.outelf, idx, phdr);
6620 /* The interpreter string. */
6621 xelf_getphdr_ptr (ld_state.outelf, idx, phdr);
6622 phdr->p_type = PT_INTERP;
6623 phdr->p_offset = shdr->sh_offset;
6624 phdr->p_vaddr = shdr->sh_addr;
6625 phdr->p_paddr = phdr->p_vaddr;
6626 phdr->p_filesz = shdr->sh_size;
6627 phdr->p_memsz = phdr->p_filesz;
6628 phdr->p_flags = 0; /* No need to set PF_R or so. */
6629 phdr->p_align = 1; /* It's a string. */
6631 (void) xelf_update_phdr (ld_state.outelf, idx, phdr);
6635 /* The pointer to the dynamic section. We this we need to
6636 get the information for the dynamic section first. */
6637 assert (ld_state.dynamicscnidx);
6638 outscn = elf_getscn (ld_state.outelf, ld_state.dynamicscnidx);
6639 xelf_getshdr (outscn, shdr);
6640 assert (shdr != NULL);
6642 xelf_getphdr_ptr (ld_state.outelf, idx, phdr);
6643 phdr->p_type = PT_DYNAMIC;
6644 phdr->p_offset = shdr->sh_offset;
6645 phdr->p_vaddr = shdr->sh_addr;
6646 phdr->p_paddr = phdr->p_vaddr;
6647 phdr->p_filesz = shdr->sh_size;
6648 phdr->p_memsz = phdr->p_filesz;
6649 phdr->p_flags = 0; /* No need to set PF_R or so. */
6650 phdr->p_align = shdr->sh_addralign;
6652 (void) xelf_update_phdr (ld_state.outelf, idx, phdr);
6654 /* Fill in the reference to the .dynstr section. */
6655 assert (ld_state.dynstrscnidx != 0);
6656 shdr->sh_link = ld_state.dynstrscnidx;
6657 (void) xelf_update_shdr (outscn, shdr);
6659 /* And fill the remaining entries. */
6660 Elf_Data *dyndata = elf_getdata (outscn, NULL);
6661 assert (dyndata != NULL);
6663 /* Add the DT_NEEDED entries. */
6664 if (ld_state.ndsofiles > 0)
6666 struct usedfiles *runp = ld_state.dsofiles->next;
6669 if (runp->used || !runp->as_needed)
6671 /* Add the position-dependent flag if necessary. */
6673 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6674 DT_POSFLAG_1, DF_P1_LAZYLOAD);
6676 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6678 ebl_strtaboffset (runp->sonameent));
6680 while ((runp = runp->next) != ld_state.dsofiles->next);
6683 /* We can finish the DT_RUNPATH/DT_RPATH entries now. */
6684 if (ld_state.rxxpath_strent != NULL)
6685 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6686 ld_state.rxxpath_tag,
6687 ebl_strtaboffset (ld_state.rxxpath_strent));
6689 /* Reference to initialization and finalization functions. */
6690 // XXX This code depends on symbol table being relocated.
6691 if (ld_state.init_symbol != NULL)
6693 XElf_Sym_vardef (sym);
6695 if (ld_state.need_symtab)
6696 xelf_getsym (symdata,
6697 dblindirect[ld_state.init_symbol->outsymidx],
6700 xelf_getsym (dynsymdata, ld_state.init_symbol->outdynsymidx,
6702 assert (sym != NULL);
6704 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6705 DT_INIT, sym->st_value);
6707 if (ld_state.fini_symbol != NULL)
6709 XElf_Sym_vardef (sym);
6711 if (ld_state.need_symtab)
6712 xelf_getsym (symdata,
6713 dblindirect[ld_state.fini_symbol->outsymidx],
6716 xelf_getsym (dynsymdata, ld_state.fini_symbol->outdynsymidx,
6718 assert (sym != NULL);
6720 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6721 DT_FINI, sym->st_value);
6723 // XXX Support init,fini,preinit arrays
6725 /* The hash table which comes with dynamic symbol table. */
6726 xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.hashscnidx),
6728 assert (shdr != NULL);
6729 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_HASH,
6732 /* Reference to the symbol table section. */
6733 assert (ld_state.dynsymscnidx != 0);
6734 xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.dynsymscnidx),
6736 assert (shdr != NULL);
6737 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_SYMTAB,
6740 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_SYMENT,
6741 xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
6743 /* And the string table which comes with it. */
6744 xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.dynstrscnidx),
6746 assert (shdr != NULL);
6747 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_STRTAB,
6750 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_STRSZ,
6753 /* Add the entries related to the .plt. */
6754 if (ld_state.nplt > 0)
6756 // XXX Make this work if there is no PLT
6757 xelf_getshdr (elf_getscn (ld_state.outelf,
6758 ld_state.gotpltscnidx), shdr);
6759 assert (shdr != NULL);
6760 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6761 // XXX This should probably be machine
6763 DT_PLTGOT, shdr->sh_addr);
6765 xelf_getshdr (elf_getscn (ld_state.outelf,
6766 ld_state.pltrelscnidx), shdr);
6767 assert (shdr != NULL);
6768 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6769 DT_PLTRELSZ, shdr->sh_size);
6771 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6772 DT_JMPREL, shdr->sh_addr);
6774 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6775 DT_PLTREL, REL_TYPE (statep));
6778 if (ld_state.relsize_total > 0)
6780 int rel = REL_TYPE (statep);
6781 xelf_getshdr (elf_getscn (ld_state.outelf,
6782 ld_state.reldynscnidx), shdr);
6783 assert (shdr != NULL);
6784 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6785 rel, shdr->sh_addr);
6787 /* Trick ahead. Use arithmetic to get the right tag.
6788 We check the validity of this assumption in the asserts. */
6789 assert (DT_RELASZ - DT_RELA == 1);
6790 assert (DT_RELSZ - DT_REL == 1);
6791 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6792 rel + 1, shdr->sh_size);
6794 /* Similar for the entry size tag. */
6795 assert (DT_RELAENT - DT_RELA == 2);
6796 assert (DT_RELENT - DT_REL == 2);
6797 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6800 ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
6801 : xelf_fsize (ld_state.outelf, ELF_T_RELA,
6805 if (ld_state.verneedscnidx != 0)
6807 xelf_getshdr (elf_getscn (ld_state.outelf,
6808 ld_state.verneedscnidx), shdr);
6809 assert (shdr != NULL);
6810 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6811 DT_VERNEED, shdr->sh_addr);
6813 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6814 DT_VERNEEDNUM, ld_state.nverdeffile);
6817 if (ld_state.versymscnidx != 0)
6819 xelf_getshdr (elf_getscn (ld_state.outelf,
6820 ld_state.versymscnidx), shdr);
6821 assert (shdr != NULL);
6822 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6823 DT_VERSYM, shdr->sh_addr);
6826 /* We always create the DT_DEBUG entry. */
6827 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_DEBUG, 0);
6828 assert (ld_state.ndynamic_filled < ld_state.ndynamic);
6830 /* Add the flag words if necessary. */
6831 if (ld_state.dt_flags != 0)
6832 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_FLAGS,
6835 /* Create entry for the DT_FLAGS_1 flag. */
6836 if (ld_state.dt_flags_1 != 0)
6837 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6838 DT_FLAGS_1, ld_state.dt_flags_1);
6840 /* Create entry for the DT_FEATURE_1 flag. */
6841 if (ld_state.dt_feature_1 != 0)
6842 new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6843 DT_FEATURE_1, ld_state.dt_feature_1);
6845 assert (ld_state.ndynamic_filled <= ld_state.ndynamic);
6850 // XXX The following code isn't nice. We use two different
6851 // mechanisms to handle relocations, one for relocatable files, one
6852 // for executables and DSOs. Maybe this is the best method but also
6853 // maybe it can be somewhat unified.
6855 /* Now that we created the symbol table we can add the reference to
6856 it in the sh_link field of the section headers of the relocation
6858 while (rellist != NULL)
6860 assert (ld_state.file_type == relocatable_file_type);
6863 outscn = elf_getscn (ld_state.outelf, rellist->scnidx);
6864 xelf_getshdr (outscn, shdr);
6865 /* This must not fail since we did it before. */
6866 assert (shdr != NULL);
6868 /* Remember the symbol table which belongs to the relocation section. */
6869 shdr->sh_link = ld_state.symscnidx;
6871 /* And the reference to the section which is relocated by this
6872 relocation section. We use the info from the first input
6873 section but all records should have the same information. */
6875 rellist->scninfo->fileinfo->scninfo[SCNINFO_SHDR (rellist->scninfo->shdr).sh_info].outscnndx;
6878 /* Perform the actual relocations. We only have to adjust
6879 offsets and symbol indices. */
6880 RELOCATE_SECTION (statep, outscn, rellist->scninfo, dblindirect);
6882 /* Store the changes. */
6883 (void) xelf_update_shdr (outscn, shdr);
6885 /* Up to the next relocation section. */
6886 rellist = rellist->next;
6889 if (ld_state.rellist != NULL)
6891 assert (ld_state.file_type != relocatable_file_type);
6892 /* Create the relocations for the output file. */
6893 CREATE_RELOCATIONS (statep, dblindirect);
6897 /* We need the ELF header once more. */
6898 xelf_getehdr (ld_state.outelf, ehdr);
6899 assert (ehdr != NULL);
6901 /* Set the section header string table index. */
6902 if (likely (shstrtab_ndx < SHN_HIRESERVE)
6903 && likely (shstrtab_ndx != SHN_XINDEX))
6904 ehdr->e_shstrndx = shstrtab_ndx;
6907 /* We have to put the section index in the sh_link field of the
6908 zeroth section header. */
6909 Elf_Scn *scn = elf_getscn (ld_state.outelf, 0);
6911 xelf_getshdr (scn, shdr);
6912 if (unlikely (shdr == NULL))
6913 error (EXIT_FAILURE, 0,
6914 gettext ("cannot get header of 0th section: %s"),
6917 shdr->sh_link = shstrtab_ndx;
6919 (void) xelf_update_shdr (scn, shdr);
6921 ehdr->e_shstrndx = SHN_XINDEX;
6924 if (ld_state.file_type != relocatable_file_type)
6925 /* DSOs and executables have to define the entry point symbol. */
6926 ehdr->e_entry = find_entry_point ();
6928 if (unlikely (xelf_update_ehdr (ld_state.outelf, ehdr) == 0))
6929 error (EXIT_FAILURE, 0,
6930 gettext ("cannot update ELF header: %s"),
6934 /* Free the data which we don't need anymore. */
6935 free (ld_state.dblindirect);
6938 /* Finalize the .plt section and what else belongs to it. */
6939 FINALIZE_PLT (statep, nsym, nsym_local, ndxtosym);
6942 /* Finally, if we have to compute the build ID. */
6943 if (ld_state.build_id != NULL)
6944 compute_build_id ();
6947 /* We don't need the map from the symbol table index to the symbol
6948 structure anymore. */
6955 /* This is a function which must be specified in all backends. */
6957 ld_generic_relocate_section (struct ld_state *statep, Elf_Scn *outscn,
6958 struct scninfo *firstp,
6959 const Elf32_Word *dblindirect)
6961 error (EXIT_FAILURE, 0, gettext ("\
6962 linker backend didn't specify function to relocate section"));
6967 /* Finalize the output file. */
6969 ld_generic_finalize (struct ld_state *statep)
6971 /* Write out the ELF file data. */
6972 if (elf_update (ld_state.outelf, ELF_C_WRITE) == -1)
6973 error (EXIT_FAILURE, 0, gettext ("while writing output file: %s"),
6976 /* Free the resources. */
6977 if (elf_end (ld_state.outelf) != 0)
6978 error (EXIT_FAILURE, 0, gettext ("while finishing output file: %s"),
6981 /* Get the file status of the temporary file. */
6982 struct stat temp_st;
6983 if (fstat (ld_state.outfd, &temp_st) != 0)
6984 error (EXIT_FAILURE, errno, gettext ("cannot stat output file"));
6986 /* Now it's time to rename the file. Remove an old existing file
6988 if (rename (ld_state.tempfname, ld_state.outfname) != 0)
6989 /* Something went wrong. */
6990 error (EXIT_FAILURE, errno, gettext ("cannot rename output file"));
6992 /* Make sure the output file is really the one we created. */
6994 if (stat (ld_state.outfname, &new_st) != 0
6995 || new_st.st_ino != temp_st.st_ino
6996 || new_st.st_dev != temp_st.st_dev)
6998 /* Wow, somebody overwrote the output file, probably some intruder. */
6999 unlink (ld_state.outfname);
7000 error (EXIT_FAILURE, 0, gettext ("\
7001 WARNING: temporary output file overwritten before linking finished"));
7004 /* Close the file descriptor. */
7005 (void) close (ld_state.outfd);
7007 /* Signal the cleanup handler that the file is correctly created. */
7008 ld_state.tempfname = NULL;
7015 ld_generic_special_section_number_p (struct ld_state *statep, size_t number)
7017 /* There are no special section numbers in the gABI. */
7023 ld_generic_section_type_p (struct ld_state *statep, GElf_Word type)
7026 /* XXX Enable the following two when implemented. */
7027 // || type == SHT_GNU_LIBLIST
7028 // || type == SHT_CHECKSUM
7029 /* XXX Eventually include SHT_SUNW_move, SHT_SUNW_COMDAT, and
7030 SHT_SUNW_syminfo. */
7031 || (type >= SHT_GNU_verdef && type <= SHT_GNU_versym))
7039 ld_generic_dynamic_section_flags (struct ld_state *statep)
7041 /* By default the .dynamic section is writable (and is of course
7042 loaded). Few architecture differ from this. */
7043 return SHF_ALLOC | SHF_WRITE;
7048 ld_generic_initialize_plt (struct ld_state *statep, Elf_Scn *scn)
7050 /* This cannot be implemented generally. There should have been a
7051 machine dependent implementation and we should never have arrived
7053 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7059 ld_generic_initialize_pltrel (struct ld_state *statep, Elf_Scn *scn)
7061 /* This cannot be implemented generally. There should have been a
7062 machine dependent implementation and we should never have arrived
7064 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7065 "initialize_pltrel");
7070 ld_generic_initialize_got (struct ld_state *statep, Elf_Scn *scn)
7072 /* This cannot be implemented generally. There should have been a
7073 machine dependent implementation and we should never have arrived
7075 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7081 ld_generic_initialize_gotplt (struct ld_state *statep, Elf_Scn *scn)
7083 /* This cannot be implemented generally. There should have been a
7084 machine dependent implementation and we should never have arrived
7086 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7087 "initialize_gotplt");
7092 ld_generic_finalize_plt (struct ld_state *statep, size_t nsym, size_t nsym_dyn,
7093 struct symbol **ndxtosymp)
7095 /* By default we assume that nothing has to be done. */
7100 ld_generic_rel_type (struct ld_state *statep)
7102 /* This cannot be implemented generally. There should have been a
7103 machine dependent implementation and we should never have arrived
7105 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7107 /* Just to keep the compiler calm. */
7113 ld_generic_count_relocations (struct ld_state *statep, struct scninfo *scninfo)
7115 /* This cannot be implemented generally. There should have been a
7116 machine dependent implementation and we should never have arrived
7118 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7119 "count_relocations");
7124 ld_generic_create_relocations (struct ld_state *statep,
7125 const Elf32_Word *dblindirect)
7127 /* This cannot be implemented generally. There should have been a
7128 machine dependent implementation and we should never have arrived
7130 error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
7131 "create_relocations");