c089e0bac4394c9952b932c4176d6655d87f5a53
[platform/upstream/elfutils.git] / src / ldgeneric.c
1 /* Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 Red Hat, Inc.
2    This file is part of Red Hat elfutils.
3    Written by Ulrich Drepper <drepper@redhat.com>, 2001.
4
5    Red Hat elfutils is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by the
7    Free Software Foundation; version 2 of the License.
8
9    Red Hat elfutils is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    General Public License for more details.
13
14    You should have received a copy of the GNU General Public License along
15    with Red Hat elfutils; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA.
17
18    Red Hat elfutils is an included package of the Open Invention Network.
19    An included package of the Open Invention Network is a package for which
20    Open Invention Network licensees cross-license their patents.  No patent
21    license is granted, either expressly or impliedly, by designation as an
22    included package.  Should you wish to participate in the Open Invention
23    Network licensing program, please visit www.openinventionnetwork.com
24    <http://www.openinventionnetwork.com>.  */
25
26 #ifdef HAVE_CONFIG_H
27 # include <config.h>
28 #endif
29
30 #include <assert.h>
31 #include <dlfcn.h>
32 #include <errno.h>
33 #include <error.h>
34 #include <fcntl.h>
35 #include <fnmatch.h>
36 #include <gelf.h>
37 #include <inttypes.h>
38 #include <libintl.h>
39 #include <stdbool.h>
40 #include <stdio_ext.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <sys/param.h>
45 #include <sys/stat.h>
46
47 #include <system.h>
48 #include "ld.h"
49 #include "list.h"
50
51
52 /* Header of .eh_frame_hdr section.  */
53 struct unw_eh_frame_hdr
54 {
55   unsigned char version;
56   unsigned char eh_frame_ptr_enc;
57   unsigned char fde_count_enc;
58   unsigned char table_enc;
59 };
60 #define EH_FRAME_HDR_VERSION 1
61
62
63 /* Prototypes for local functions.  */
64 static const char **ld_generic_lib_extensions (struct ld_state *)
65      __attribute__ ((__const__));
66 static int ld_generic_file_close (struct usedfiles *fileinfo,
67                                   struct ld_state *statep);
68 static int ld_generic_file_process (int fd, struct usedfiles *fileinfo,
69                                     struct ld_state *statep,
70                                     struct usedfiles **nextp);
71 static void ld_generic_generate_sections (struct ld_state *statep);
72 static void ld_generic_create_sections (struct ld_state *statep);
73 static int ld_generic_flag_unresolved (struct ld_state *statep);
74 static int ld_generic_open_outfile (struct ld_state *statep, int machine,
75                                     int class, int data);
76 static int ld_generic_create_outfile (struct ld_state *statep);
77 static void ld_generic_relocate_section (struct ld_state *statep,
78                                          Elf_Scn *outscn,
79                                          struct scninfo *firstp,
80                                          const Elf32_Word *dblindirect);
81 static int ld_generic_finalize (struct ld_state *statep);
82 static bool ld_generic_special_section_number_p (struct ld_state *statep,
83                                                  size_t number);
84 static bool ld_generic_section_type_p (struct ld_state *statep,
85                                        XElf_Word type);
86 static XElf_Xword ld_generic_dynamic_section_flags (struct ld_state *statep);
87 static void ld_generic_initialize_plt (struct ld_state *statep, Elf_Scn *scn);
88 static void ld_generic_initialize_pltrel (struct ld_state *statep,
89                                           Elf_Scn *scn);
90 static void ld_generic_initialize_got (struct ld_state *statep, Elf_Scn *scn);
91 static void ld_generic_finalize_plt (struct ld_state *statep, size_t nsym,
92                                      size_t nsym_dyn);
93 static int ld_generic_rel_type (struct ld_state *statep);
94 static void ld_generic_count_relocations (struct ld_state *statep,
95                                           struct scninfo *scninfo);
96 static void ld_generic_create_relocations (struct ld_state *statep,
97                                            const Elf32_Word *dblindirect);
98
99 static int file_process2 (struct usedfiles *fileinfo);
100 static void mark_section_used (struct scninfo *scninfo, Elf32_Word shndx,
101                                struct scninfo **grpscnp);
102
103
104 /* Map symbol index to struct symbol record.  */
105 static struct symbol **ndxtosym;
106
107 /* String table reference to all symbols in the symbol table.  */
108 static struct Ebl_Strent **symstrent;
109
110
111 /* Check whether file associated with FD is a DSO.  */
112 static bool
113 is_dso_p (int fd)
114 {
115   /* We have to read the 'e_type' field.  It has the same size (16
116      bits) in 32- and 64-bit ELF.  */
117   XElf_Half e_type;
118
119   return (pread (fd, &e_type, sizeof (e_type), offsetof (XElf_Ehdr, e_type))
120           == sizeof (e_type)
121           && e_type == ET_DYN);
122 }
123
124
125 /* Print the complete name of a file, including the archive it is
126    contained in.  */
127 static int
128 print_file_name (FILE *s, struct usedfiles *fileinfo, int first_level,
129                  int newline)
130 {
131   int npar = 0;
132
133   if (fileinfo->archive_file != NULL)
134     {
135       npar = print_file_name (s, fileinfo->archive_file, 0, 0) + 1;
136       fputc_unlocked ('(', s);
137       fputs_unlocked (fileinfo->rfname, s);
138
139       if (first_level)
140         while (npar-- > 0)
141           fputc_unlocked (')', s);
142     }
143   else
144     fputs_unlocked (fileinfo->rfname, s);
145
146   if (first_level && newline)
147     fputc_unlocked ('\n', s);
148
149   return npar;
150 }
151
152
153 /* Function to determine whether an object will be dynamically linked.  */
154 bool
155 dynamically_linked_p (void)
156 {
157   return (ld_state.file_type == dso_file_type || ld_state.nplt > 0
158           || ld_state.ngot > 0);
159 }
160
161
162 bool
163 linked_from_dso_p (struct scninfo *scninfo, size_t symidx)
164 {
165   struct usedfiles *file = scninfo->fileinfo;
166
167   /* If this symbol is not undefined in this file it cannot come from
168      a DSO.  */
169   if (symidx < file->nlocalsymbols)
170     return false;
171
172   struct symbol *sym = file->symref[symidx];
173
174   return sym->defined && sym->in_dso;
175 }
176
177
178 /* Initialize state object.  This callback function is called after the
179    parameters are parsed but before any file is searched for.  */
180 int
181 ld_prepare_state (const char *emulation)
182 {
183   /* When generating DSO we normally allow undefined symbols.  */
184   ld_state.nodefs = true;
185
186   /* To be able to detect problems we add a .comment section entry by
187      default.  */
188   ld_state.add_ld_comment = true;
189
190   /* XXX We probably should find a better place for this.  The index
191      of the first user-defined version is 2.  */
192   ld_state.nextveridx = 2;
193
194   /* Pick an not too small number for the initial size of the tables.  */
195   ld_symbol_tab_init (&ld_state.symbol_tab, 1027);
196   ld_section_tab_init (&ld_state.section_tab, 67);
197   ld_version_str_tab_init (&ld_state.version_str_tab, 67);
198
199   /* Initialize the section header string table.  */
200   ld_state.shstrtab = ebl_strtabinit (true);
201   if (ld_state.shstrtab == NULL)
202     error (EXIT_FAILURE, errno, gettext ("cannot create string table"));
203
204   /* Initialize the callbacks.  These are the defaults, the appropriate
205      backend can later install its own callbacks.  */
206   ld_state.callbacks.lib_extensions = ld_generic_lib_extensions;
207   ld_state.callbacks.file_process = ld_generic_file_process;
208   ld_state.callbacks.file_close = ld_generic_file_close;
209   ld_state.callbacks.generate_sections = ld_generic_generate_sections;
210   ld_state.callbacks.create_sections = ld_generic_create_sections;
211   ld_state.callbacks.flag_unresolved = ld_generic_flag_unresolved;
212   ld_state.callbacks.open_outfile = ld_generic_open_outfile;
213   ld_state.callbacks.create_outfile = ld_generic_create_outfile;
214   ld_state.callbacks.relocate_section = ld_generic_relocate_section;
215   ld_state.callbacks.finalize = ld_generic_finalize;
216   ld_state.callbacks.special_section_number_p =
217     ld_generic_special_section_number_p;
218   ld_state.callbacks.section_type_p = ld_generic_section_type_p;
219   ld_state.callbacks.dynamic_section_flags = ld_generic_dynamic_section_flags;
220   ld_state.callbacks.initialize_plt = ld_generic_initialize_plt;
221   ld_state.callbacks.initialize_pltrel = ld_generic_initialize_pltrel;
222   ld_state.callbacks.initialize_got = ld_generic_initialize_got;
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;
227
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)
232     {
233       emulation = ebl_backend_name (ld_state.ebl);
234       assert (emulation != NULL);
235     }
236   size_t emulation_len = strlen (emulation);
237
238   /* Construct the file name.  */
239   char *fname = (char *) alloca (sizeof "libld_" - 1 + emulation_len
240                                  + sizeof ".so");
241   strcpy (mempcpy (stpcpy (fname, "libld_"), emulation, emulation_len), ".so");
242
243   /* Try loading.  */
244   void *h = dlopen (fname, RTLD_LAZY);
245   if (h == NULL)
246     error (EXIT_FAILURE, 0,
247            gettext ("cannot load ld backend library '%s': %s"),
248            fname, dlerror ());
249
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);
255
256   if (initfct == NULL)
257     error (EXIT_FAILURE, 0, gettext ("\
258 cannot find init function in ld backend library '%s': %s"),
259            fname, dlerror ());
260
261   /* Store the handle.  */
262   ld_state.ldlib = h;
263
264   /* Call the init function.  */
265   return initfct (&ld_state);
266 #else
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);
272 #endif
273 }
274
275
276 static int
277 check_for_duplicate2 (struct usedfiles *newp, struct usedfiles *list)
278 {
279   struct usedfiles *first;
280   struct usedfiles *prevp;
281
282   if (list == NULL)
283     return 0;
284
285   prevp = list;
286   list = first = list->next;
287   do
288     {
289       /* When searching the needed list we might come across entries
290          for files which are not yet opened.  Stop then, there is
291          nothing more to test.  */
292       if (likely (list->status == not_opened))
293         break;
294
295       if (unlikely (list->ino == newp->ino)
296           && unlikely (list->dev == newp->dev))
297         {
298           close (newp->fd);
299           newp->fd = -1;
300           newp->status = closed;
301           if (newp->file_type == relocatable_file_type)
302             error (0, 0, gettext ("%s listed more than once as input"),
303                    newp->rfname);
304
305           return 1;
306         }
307       list = list->next;
308     }
309   while (likely (list != first));
310
311   return 0;
312 }
313
314
315 static int
316 check_for_duplicate (struct usedfiles *newp)
317 {
318   struct stat st;
319
320   if (unlikely (fstat (newp->fd, &st) < 0))
321     {
322       close (newp->fd);
323       return errno;
324     }
325
326   newp->dev = st.st_dev;
327   newp->ino = st.st_ino;
328
329   return (check_for_duplicate2 (newp, ld_state.relfiles)
330           || check_for_duplicate2 (newp, ld_state.dsofiles)
331           || check_for_duplicate2 (newp, ld_state.needed));
332 }
333
334
335 /* Find a file along the path described in the state.  */
336 static int
337 open_along_path2 (struct usedfiles *fileinfo, struct pathelement *path)
338 {
339   const char *fname = fileinfo->fname;
340   size_t fnamelen = strlen (fname);
341   int err = ENOENT;
342   struct pathelement *firstp = path;
343
344   if (path == NULL)
345     /* Cannot find anything since we have no path.  */
346     return ENOENT;
347
348   do
349     {
350       if (likely (path->exist >= 0))
351         {
352           /* Create the file name.  */
353           char *rfname = NULL;
354           size_t dirlen = strlen (path->pname);
355           int fd = -1;
356
357           if (fileinfo->file_type == archive_file_type)
358             {
359               const char **exts = (ld_state.statically
360                                    ? (const char *[2]) { ".a", NULL }
361                                    : LIB_EXTENSION (&ld_state));
362
363               /* We have to create the actual file name.  We prepend "lib"
364                  and add one of the extensions the platform has.  */
365               while (*exts != NULL)
366                 {
367                   size_t extlen = strlen (*exts);
368                   rfname = (char *) alloca (dirlen + 5 + fnamelen + extlen);
369                   memcpy (mempcpy (stpcpy (mempcpy (rfname, path->pname,
370                                                     dirlen),
371                                            "/lib"),
372                                    fname, fnamelen),
373                           *exts, extlen + 1);
374
375                   fd = open (rfname, O_RDONLY);
376                   if (likely (fd != -1) || errno != ENOENT)
377                     {
378                       err = fd == -1 ? errno : 0;
379                       break;
380                     }
381
382                   /* Next extension.  */
383                   ++exts;
384                 }
385             }
386           else
387             {
388               assert (fileinfo->file_type == dso_file_type
389                       || fileinfo->file_type == dso_needed_file_type);
390
391               rfname = (char *) alloca (dirlen + 1 + fnamelen + 1);
392               memcpy (stpcpy (mempcpy (rfname, path->pname, dirlen), "/"),
393                       fname, fnamelen + 1);
394
395               fd = open (rfname, O_RDONLY);
396               if (unlikely (fd == -1))
397                 err = errno;
398             }
399
400           if (likely (fd != -1))
401             {
402               /* We found the file.  This also means the directory
403                  exists.  */
404               fileinfo->fd = fd;
405               path->exist = 1;
406
407               /* Check whether we have this file already loaded.  */
408               if (unlikely (check_for_duplicate (fileinfo) != 0))
409                 return EAGAIN;
410
411               /* Make a copy of the name.  */
412               fileinfo->rfname = obstack_strdup (&ld_state.smem, rfname);
413
414               if (unlikely (ld_state.trace_files))
415                 printf (fileinfo->file_type == archive_file_type
416                         ? gettext ("%s (for -l%s)\n")
417                         : gettext ("%s (for DT_NEEDED %s)\n"),
418                         rfname, fname);
419
420               return 0;
421             }
422
423           /* The file does not exist.  Maybe the whole directory doesn't.
424              Check it unless we know it exists.  */
425           if (unlikely (path->exist == 0))
426             {
427               struct stat st;
428
429               /* Keep only the directory name.  Note that the path
430                  might be relative.  This doesn't matter here.  We do
431                  the test in any case even if there is the chance that
432                  somebody wants to change the programs working
433                  directory at some point which would make the result
434                  of this test void.  Since changing the working
435                  directory is completely wrong we are not taking this
436                  case into account.  */
437               rfname[dirlen] = '\0';
438               if (unlikely (stat (rfname, &st) < 0) || ! S_ISDIR (st.st_mode))
439                 /* The directory does not exist or the named file is no
440                    directory.  */
441                 path->exist = -1;
442               else
443                 path->exist = 1;
444             }
445         }
446
447       /* Next path element.  */
448       path = path->next;
449     }
450   while (likely (err == ENOENT && path != firstp));
451
452   return err;
453 }
454
455
456 static int
457 open_along_path (struct usedfiles *fileinfo)
458 {
459   const char *fname = fileinfo->fname;
460   int err = ENOENT;
461
462   if (fileinfo->file_type == relocatable_file_type)
463     {
464       /* Only libraries are searched along the path.  */
465       fileinfo->fd = open (fname, O_RDONLY);
466
467       if (likely (fileinfo->fd != -1))
468         {
469           /* We found the file.  */
470           if (unlikely (ld_state.trace_files))
471             print_file_name (stdout, fileinfo, 1, 1);
472
473           return check_for_duplicate (fileinfo);
474         }
475
476       /* If the name is an absolute path we are done.  */
477       err = errno;
478     }
479   else
480     {
481       /* If the user specified two parts to the LD_LIBRARY_PATH variable
482          try the first part now.  */
483       err = open_along_path2 (fileinfo, ld_state.ld_library_path1);
484
485       /* Try the user-specified path next.  */
486       if (err == ENOENT)
487         err = open_along_path2 (fileinfo,
488                                 fileinfo->file_type == archive_file_type
489                                 ? ld_state.paths : ld_state.rpath_link);
490
491       /* Then the second part of the LD_LIBRARY_PATH value.  */
492       if (unlikely (err == ENOENT))
493         {
494           err = open_along_path2 (fileinfo, ld_state.ld_library_path2);
495
496           /* In case we look for a DSO handle now the RUNPATH.  */
497           if (err == ENOENT)
498             {
499               if (fileinfo->file_type == dso_file_type)
500                 err = open_along_path2 (fileinfo, ld_state.runpath_link);
501
502               /* Finally the path from the default linker script.  */
503               if (err == ENOENT)
504                 err = open_along_path2 (fileinfo, ld_state.default_paths);
505             }
506         }
507     }
508
509   if (unlikely (err != 0)
510       && (err != EAGAIN || fileinfo->file_type == relocatable_file_type))
511     error (0, err, gettext ("cannot open %s"), fileinfo->fname);
512
513   return err;
514 }
515
516
517 static void
518 check_type_and_size (const XElf_Sym *sym, struct usedfiles *fileinfo,
519                      struct symbol *oldp)
520 {
521   /* We check the type and size of the symbols.  In both cases the
522      information can be missing (size is zero, type is STT_NOTYPE) in
523      which case we issue no warnings.  Otherwise everything must
524      match.  If the type does not match there is no point in checking
525      the size.  */
526
527   if (XELF_ST_TYPE (sym->st_info) != STT_NOTYPE && oldp->type != STT_NOTYPE
528       && unlikely (oldp->type != XELF_ST_TYPE (sym->st_info)))
529     {
530       char buf1[64];
531       char buf2[64];
532
533       error (0, 0, gettext ("\
534 Warning: type of `%s' changed from %s in %s to %s in %s"),
535              oldp->name,
536              ebl_symbol_type_name (ld_state.ebl, oldp->type,
537                                    buf1, sizeof (buf1)),
538              oldp->file->rfname,
539              ebl_symbol_type_name (ld_state.ebl, XELF_ST_TYPE (sym->st_info),
540                                    buf2, sizeof (buf2)),
541              fileinfo->rfname);
542     }
543   else if (XELF_ST_TYPE (sym->st_info) == STT_OBJECT
544            && oldp->size != 0
545            && unlikely (oldp->size != sym->st_size))
546     error (0, 0, gettext ("\
547 Warning: size of `%s' changed from %" PRIu64 " in %s to %" PRIu64 " in %s"),
548            oldp->name, (uint64_t) oldp->size, oldp->file->rfname,
549            (uint64_t) sym->st_size, fileinfo->rfname);
550 }
551
552
553 static int
554 check_definition (const XElf_Sym *sym, size_t symidx,
555                   struct usedfiles *fileinfo, struct symbol *oldp)
556 {
557   int result = 0;
558   bool old_in_dso = FILEINFO_EHDR (oldp->file->ehdr).e_type == ET_DYN;
559   bool new_in_dso = FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_DYN;
560   bool use_new_def = false;
561
562   if (sym->st_shndx != SHN_UNDEF
563       && (! oldp->defined
564           || (sym->st_shndx != SHN_COMMON && oldp->common && ! new_in_dso)
565           || (old_in_dso && ! new_in_dso)))
566     {
567       /* We found a definition for a previously undefined symbol or a
568          real definition for a previous common-only definition or a
569          redefinition of a symbol definition in an object file
570          previously defined in a DSO.  First perform some tests which
571          will show whether the common is really matching the
572          definition.  */
573       check_type_and_size (sym, fileinfo, oldp);
574
575       /* We leave the next element intact to not interrupt the list
576          with the unresolved symbols.  Whoever walks the list will
577          have to check the `defined' flag.  But we remember that this
578          list element is not unresolved anymore.  */
579       if (! oldp->defined)
580         {
581           /* Remove from the list.  */
582           --ld_state.nunresolved;
583           if (! oldp->weak)
584             --ld_state.nunresolved_nonweak;
585           CDBL_LIST_DEL (ld_state.unresolved, oldp);
586         }
587       else if (oldp->common)
588         /* Remove from the list.  */
589         CDBL_LIST_DEL (ld_state.common_syms, oldp);
590
591       /* Use the values of the definition from now on.  */
592       use_new_def = true;
593     }
594   else if (sym->st_shndx != SHN_UNDEF
595            && unlikely (! oldp->common)
596            && oldp->defined
597            && sym->st_shndx != SHN_COMMON
598            /* Multiple definitions are no fatal errors if the -z muldefs flag
599               is used.  We don't warn about the multiple definition unless we
600               are told to be verbose.  */
601            && (!ld_state.muldefs || verbose)
602            && ! old_in_dso && fileinfo->file_type == relocatable_file_type)
603     {
604       /* We have a double definition.  This is a problem.  */
605       char buf[64];
606       XElf_Sym_vardef (oldsym);
607       struct usedfiles *oldfile;
608       const char *scnname;
609       Elf32_Word xndx;
610       size_t shndx;
611       size_t shnum;
612
613       if (elf_getshnum (fileinfo->elf, &shnum) < 0)
614         error (EXIT_FAILURE, 0,
615                gettext ("cannot determine number of sections: %s"),
616                elf_errmsg (-1));
617
618       /* XXX Use only ebl_section_name.  */
619       if (sym->st_shndx < SHN_LORESERVE // || sym->st_shndx > SHN_HIRESERVE
620           && sym->st_shndx < shnum)
621         scnname = elf_strptr (fileinfo->elf,
622                               fileinfo->shstrndx,
623                               SCNINFO_SHDR (fileinfo->scninfo[sym->st_shndx].shdr).sh_name);
624       else
625         // XXX extended section
626         scnname = ebl_section_name (ld_state.ebl, sym->st_shndx, 0,
627                                     buf, sizeof (buf), NULL, shnum);
628
629       /* XXX Print source file and line number.  */
630       print_file_name (stderr, fileinfo, 1, 0);
631       fprintf (stderr,
632                gettext ("(%s+%#" PRIx64 "): multiple definition of %s `%s'\n"),
633                scnname,
634                (uint64_t) sym->st_value,
635                ebl_symbol_type_name (ld_state.ebl, XELF_ST_TYPE (sym->st_info),
636                                      buf, sizeof (buf)),
637                oldp->name);
638
639       oldfile = oldp->file;
640       xelf_getsymshndx (oldfile->symtabdata, oldfile->xndxdata, oldp->symidx,
641                         oldsym, xndx);
642       if (oldsym == NULL)
643         /* This should never happen since the same call
644            succeeded before.  */
645         abort ();
646
647       shndx = oldsym->st_shndx;
648       if (unlikely (oldsym->st_shndx == SHN_XINDEX))
649         shndx = xndx;
650
651       /* XXX Use only ebl_section_name.  */
652       if (shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE)
653         scnname = elf_strptr (oldfile->elf,
654                               oldfile->shstrndx,
655                               SCNINFO_SHDR (oldfile->scninfo[shndx].shdr).sh_name);
656       else
657         scnname = ebl_section_name (ld_state.ebl, oldsym->st_shndx, shndx, buf,
658                                     sizeof (buf), NULL, shnum);
659
660       /* XXX Print source file and line number.  */
661       print_file_name (stderr, oldfile, 1, 0);
662       fprintf (stderr, gettext ("(%s+%#" PRIx64 "): first defined here\n"),
663                scnname, (uint64_t) oldsym->st_value);
664
665       if (likely (!ld_state.muldefs))
666         result = 1;
667     }
668   else if (old_in_dso && fileinfo->file_type == relocatable_file_type
669            && sym->st_shndx != SHN_UNDEF)
670     /* We use the definition from a normal relocatable file over the
671        definition in a DSO.  This is what the dynamic linker would
672        do, too.  */
673     use_new_def = true;
674   else if (old_in_dso && !new_in_dso && oldp->defined && !oldp->on_dsolist)
675     {
676       CDBL_LIST_ADD_REAR (ld_state.from_dso, oldp);
677       ++ld_state.nfrom_dso;
678
679       /* If the object is a function we allocate a PLT entry,
680          otherwise only a GOT entry.  */
681       if (oldp->type == STT_FUNC)
682         ++ld_state.nplt;
683       else
684         ++ld_state.ngot;
685
686       oldp->on_dsolist = 1;
687     }
688   else if (oldp->common && sym->st_shndx == SHN_COMMON)
689     {
690       /* The symbol size is the largest of all common definitions.  */
691       oldp->size = MAX (oldp->size, sym->st_size);
692       /* Similarly for the alignment.  */
693       oldp->merge.value = MAX (oldp->merge.value, sym->st_value);
694     }
695
696   if (unlikely (use_new_def))
697     {
698       /* Adjust the symbol record appropriately and remove
699          the symbol from the list of symbols which are taken from DSOs.  */
700       if (old_in_dso && fileinfo->file_type == relocatable_file_type)
701         {
702           CDBL_LIST_DEL (ld_state.from_dso, oldp);
703           --ld_state.nfrom_dso;
704
705           if (likely (oldp->type == STT_FUNC))
706             --ld_state.nplt;
707           else
708             --ld_state.ngot;
709
710           oldp->on_dsolist = 0;
711         }
712
713       /* Use the values of the definition from now on.  */
714       oldp->size = sym->st_size;
715       oldp->type = XELF_ST_TYPE (sym->st_info);
716       oldp->symidx = symidx;
717       oldp->scndx = sym->st_shndx;
718       //oldp->symscndx = THESYMSCNDX must be passed;
719       oldp->file = fileinfo;
720       oldp->defined = 1;
721       oldp->in_dso = new_in_dso;
722       oldp->common = sym->st_shndx == SHN_COMMON;
723       if (likely (fileinfo->file_type == relocatable_file_type))
724         {
725           /* If the definition comes from a DSO we pertain the weak flag
726              and it's indicating whether the reference is weak or not.  */
727           oldp->weak = XELF_ST_BIND (sym->st_info) == STB_WEAK;
728
729           if (sym->st_shndx != SHN_COMMON)
730             {
731               struct scninfo *ignore;
732               mark_section_used (&fileinfo->scninfo[sym->st_shndx],
733                                  sym->st_shndx, &ignore);
734             }
735         }
736
737       /* Add to the list of symbols used from DSOs if necessary.  */
738       if (new_in_dso && !old_in_dso)
739         {
740           CDBL_LIST_ADD_REAR (ld_state.from_dso, oldp);
741           ++ld_state.nfrom_dso;
742
743           /* If the object is a function we allocate a PLT entry,
744              otherwise only a GOT entry.  */
745           if (oldp->type == STT_FUNC)
746             ++ld_state.nplt;
747           else
748             ++ld_state.ngot;
749
750           oldp->on_dsolist = 1;
751         }
752       else if (sym->st_shndx == SHN_COMMON)
753         {
754           /* Store the alignment.  */
755           oldp->merge.value = sym->st_value;
756
757           CDBL_LIST_ADD_REAR (ld_state.common_syms, oldp);
758         }
759     }
760
761   return result;
762 }
763
764
765 static struct scninfo *
766 find_section_group (struct usedfiles *fileinfo, Elf32_Word shndx,
767                     Elf_Data **datap)
768 {
769   struct scninfo *runp;
770
771   for (runp = fileinfo->groups; runp != NULL; runp = runp->next)
772     if (!runp->used)
773       {
774         Elf32_Word *grpref;
775         size_t cnt;
776         Elf_Data *data;
777
778         data = elf_getdata (runp->scn, NULL);
779         if (data == NULL)
780           error (EXIT_FAILURE, 0,
781                  gettext ("%s: cannot get section group data: %s"),
782                  fileinfo->fname, elf_errmsg (-1));
783
784         /* There cannot be another data block.  */
785         assert (elf_getdata (runp->scn, data) == NULL);
786
787         grpref = (Elf32_Word *) data->d_buf;
788         cnt = data->d_size / sizeof (Elf32_Word);
789         /* Note that we stop after looking at index 1 since index 0
790            contains the flags for the section group.  */
791         while (cnt > 1)
792           if (grpref[--cnt] == shndx)
793             {
794               *datap = data;
795               return runp;
796             }
797       }
798
799   /* If we come here no section group contained the given section
800      despite the SHF_GROUP flag.  This is an error in the input
801      file.  */
802   error (EXIT_FAILURE, 0, gettext ("\
803 %s: section '%s' with group flag set does not belong to any group"),
804          fileinfo->fname,
805          elf_strptr (fileinfo->elf, fileinfo->shstrndx,
806                      SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_name));
807   return NULL;
808 }
809
810
811 /* Mark all sections which belong to the same group as section SHNDX
812    as used.  */
813 static void
814 mark_section_group (struct usedfiles *fileinfo, Elf32_Word shndx,
815                     struct scninfo **grpscnp)
816 {
817   /* First locate the section group.  There can be several (many) of
818      them.  */
819   size_t cnt;
820   Elf32_Word *grpref;
821   Elf_Data *data;
822   struct scninfo *grpscn = find_section_group (fileinfo, shndx, &data);
823   *grpscnp = grpscn;
824
825   /* Mark all the sections as used.
826
827      XXX Two possible problems here:
828
829      - the gABI says "The section must be referenced by a section of type
830        SHT_GROUP".  I hope everybody reads this as "exactly one section".
831
832      - section groups are also useful to mark the debugging section which
833        belongs to a text section.  Unconditionally adding debugging sections
834        is therefore probably not what is wanted if stripping is required.  */
835
836   /* Mark the section group as handled.  */
837   grpscn->used = true;
838
839   grpref = (Elf32_Word *) data->d_buf;
840   cnt = data->d_size / sizeof (Elf32_Word);
841   while (cnt > 1)
842     {
843       Elf32_Word idx = grpref[--cnt];
844       XElf_Shdr *shdr = &SCNINFO_SHDR (fileinfo->scninfo[idx].shdr);
845
846       if (fileinfo->scninfo[idx].grpid != 0)
847         error (EXIT_FAILURE, 0, gettext ("\
848 %s: section [%2d] '%s' is in more than one section group"),
849                fileinfo->fname, (int) idx,
850                elf_strptr (fileinfo->elf, fileinfo->shstrndx, shdr->sh_name));
851
852       fileinfo->scninfo[idx].grpid = grpscn->grpid;
853
854       if (ld_state.strip == strip_none
855           /* If we are stripping, remove debug sections.  */
856           || (!ebl_debugscn_p (ld_state.ebl,
857                                elf_strptr (fileinfo->elf, fileinfo->shstrndx,
858                                            shdr->sh_name))
859               /* And the relocation sections for the debug sections.  */
860               && ((shdr->sh_type != SHT_RELA && shdr->sh_type != SHT_REL)
861                   || !ebl_debugscn_p (ld_state.ebl,
862                                       elf_strptr (fileinfo->elf,
863                                                   fileinfo->shstrndx,
864                                                   SCNINFO_SHDR (fileinfo->scninfo[shdr->sh_info].shdr).sh_name)))))
865         {
866           struct scninfo *ignore;
867
868           mark_section_used (&fileinfo->scninfo[idx], idx, &ignore);
869         }
870     }
871 }
872
873
874 static void
875 mark_section_used (struct scninfo *scninfo, Elf32_Word shndx,
876                    struct scninfo **grpscnp)
877 {
878   if (likely (scninfo->used))
879     /* Nothing to be done.  */
880     return;
881
882   /* We need this section.  */
883   scninfo->used = true;
884
885   /* Make sure the section header has been read from the file.  */
886   XElf_Shdr *shdr = &SCNINFO_SHDR (scninfo->shdr);
887 #if NATIVE_ELF
888   if (unlikely (scninfo->shdr == NULL))
889 #else
890   if (unlikely (scninfo->shdr.sh_type == SHT_NULL))
891 #endif
892     {
893 #if NATIVE_ELF != 0
894       shdr = xelf_getshdr (scninfo->scn, scninfo->shdr);
895 #else
896       xelf_getshdr_copy (scninfo->scn, shdr, scninfo->shdr);
897 #endif
898       if (unlikely (shdr == NULL))
899         /* Something is very wrong.  The calling code will notice it
900            soon and print a message.  */
901         return;
902     }
903
904   /* Handle section linked by 'sh_link'.  */
905   if (unlikely (shdr->sh_link != 0))
906     {
907       struct scninfo *ignore;
908       mark_section_used (&scninfo->fileinfo->scninfo[shdr->sh_link],
909                          shdr->sh_link, &ignore);
910     }
911
912   /* Handle section linked by 'sh_info'.  */
913   if (unlikely (shdr->sh_info != 0) && (shdr->sh_flags & SHF_INFO_LINK))
914     {
915       struct scninfo *ignore;
916       mark_section_used (&scninfo->fileinfo->scninfo[shdr->sh_info],
917                          shdr->sh_info, &ignore);
918     }
919
920   if (unlikely (shdr->sh_flags & SHF_GROUP) && ld_state.gc_sections)
921     /* Find the section group which contains this section.  */
922     mark_section_group (scninfo->fileinfo, shndx, grpscnp);
923 }
924
925
926 /* We collect all sections in a hashing table.  All sections with the
927    same name are collected in a list.  Note that we do not determine
928    which sections are finally collected in the same output section
929    here.  This would be terribly inefficient.  It will be done later.  */
930 static void
931 add_section (struct usedfiles *fileinfo, struct scninfo *scninfo)
932 {
933   struct scnhead *queued;
934   struct scnhead search;
935   unsigned long int hval;
936   XElf_Shdr *shdr = &SCNINFO_SHDR (scninfo->shdr);
937   struct scninfo *grpscn = NULL;
938   Elf_Data *grpscndata = NULL;
939
940   /* See whether we can determine right away whether we need this
941      section in the output.
942
943      XXX I assume here that --gc-sections only affects extraction
944      from an archive.  If it also affects objects files given on
945      the command line then somebody must explain to me how the
946      dependency analysis should work.  Should the entry point be
947      the root?  What if it is a numeric value?  */
948   if (!scninfo->used
949       && (ld_state.strip == strip_none
950           || (shdr->sh_flags & SHF_ALLOC) != 0
951           || shdr->sh_type == SHT_NOTE
952           || (shdr->sh_type == SHT_PROGBITS
953               && strcmp (elf_strptr (fileinfo->elf,
954                                      fileinfo->shstrndx,
955                                      shdr->sh_name), ".comment") == 0))
956       && (fileinfo->status != in_archive || !ld_state.gc_sections))
957     /* Mark as used and handle reference recursively if necessary.  */
958     mark_section_used (scninfo, elf_ndxscn (scninfo->scn), &grpscn);
959
960   if ((shdr->sh_flags & SHF_GROUP) && grpscn == NULL)
961     /* Determine the symbol which name constitutes the signature
962        for the section group.  */
963     grpscn = find_section_group (fileinfo, elf_ndxscn (scninfo->scn),
964                                  &grpscndata);
965   assert (grpscn == NULL || grpscn->symbols->name != NULL);
966
967   /* Determine the section name.  */
968   search.name = elf_strptr (fileinfo->elf, fileinfo->shstrndx, shdr->sh_name);
969   search.type = shdr->sh_type;
970   search.flags = shdr->sh_flags;
971   search.entsize = shdr->sh_entsize;
972   search.grp_signature = grpscn != NULL ? grpscn->symbols->name : NULL;
973   search.kind = scn_normal;
974   hval = elf_hash (search.name);
975
976   /* Find already queued sections.  */
977   queued = ld_section_tab_find (&ld_state.section_tab, hval, &search);
978   if (queued != NULL)
979     {
980       bool is_comdat = false;
981
982       /* If this section is part of a COMDAT section group we simply
983          ignore it since we already have a copy.  */
984       if (unlikely (shdr->sh_flags & SHF_GROUP))
985         {
986           /* Get the data of the section group section.  */
987           if (grpscndata == NULL)
988             {
989               grpscndata = elf_getdata (grpscn->scn, NULL);
990               assert (grpscndata != NULL);
991             }
992
993           /* XXX Possibly unaligned memory access.  */
994           is_comdat = ((Elf32_Word *) grpscndata->d_buf)[0] & GRP_COMDAT;
995         }
996
997       if (!is_comdat)
998         {
999           /* No COMDAT section, we use the data.  */
1000           scninfo->next = queued->last->next;
1001           queued->last = queued->last->next = scninfo;
1002
1003           queued->flags = ebl_sh_flags_combine (ld_state.ebl, queued->flags,
1004                                                 shdr->sh_flags);
1005           queued->align = MAX (queued->align, shdr->sh_addralign);
1006         }
1007     }
1008   else
1009     {
1010       /* We do not use obstacks here since the memory might be
1011          deallocated.  */
1012       queued = (struct scnhead *) xcalloc (sizeof (struct scnhead), 1);
1013       queued->kind = scn_normal;
1014       queued->name = search.name;
1015       queued->type = shdr->sh_type;
1016       queued->flags = shdr->sh_flags;
1017       queued->align = shdr->sh_addralign;
1018       queued->entsize = shdr->sh_entsize;
1019       queued->grp_signature = grpscn != NULL ? grpscn->symbols->name : NULL;
1020       queued->segment_nr = ~0;
1021       queued->last = scninfo->next = scninfo;
1022
1023       /* Add to the hash table and possibly overwrite existing value.  */
1024       ld_section_tab_insert (&ld_state.section_tab, hval, queued);
1025     }
1026 }
1027
1028
1029 static int
1030 add_relocatable_file (struct usedfiles *fileinfo, GElf_Word secttype)
1031 {
1032   size_t scncnt;
1033   size_t cnt;
1034   Elf_Data *symtabdata = NULL;
1035   Elf_Data *xndxdata = NULL;
1036   Elf_Data *versymdata = NULL;
1037   Elf_Data *verdefdata = NULL;
1038   Elf_Data *verneeddata = NULL;
1039   size_t symstridx = 0;
1040   size_t nsymbols = 0;
1041   size_t nlocalsymbols = 0;
1042   bool has_merge_sections = false;
1043   /* Unless we have different information we assume the code needs
1044      an executable stack.  */
1045   enum execstack execstack = execstack_true;
1046
1047   /* Prerequisites.  */
1048   assert (fileinfo->elf != NULL);
1049
1050   /* Allocate memory for the sections.  */
1051   if (unlikely (elf_getshnum (fileinfo->elf, &scncnt) < 0))
1052     error (EXIT_FAILURE, 0,
1053            gettext ("cannot determine number of sections: %s"),
1054            elf_errmsg (-1));
1055
1056   fileinfo->scninfo = (struct scninfo *)
1057     obstack_calloc (&ld_state.smem, scncnt * sizeof (struct scninfo));
1058
1059   /* Read all the section headers and find the symbol table.  Note
1060      that we don't skip the section with index zero.  Even though the
1061      section itself is always empty the section header contains
1062      informaton for the case when the section index for the section
1063      header string table is too large to fit in the ELF header.  */
1064   for (cnt = 0; cnt < scncnt; ++cnt)
1065     {
1066       /* Store the handle for the section.  */
1067       fileinfo->scninfo[cnt].scn = elf_getscn (fileinfo->elf, cnt);
1068
1069       /* Get the ELF section header and data.  */
1070       XElf_Shdr *shdr;
1071 #if NATIVE_ELF != 0
1072       if (fileinfo->scninfo[cnt].shdr == NULL)
1073 #else
1074       if (fileinfo->scninfo[cnt].shdr.sh_type == SHT_NULL)
1075 #endif
1076         {
1077 #if NATIVE_ELF != 0
1078           shdr = xelf_getshdr (fileinfo->scninfo[cnt].scn,
1079                                fileinfo->scninfo[cnt].shdr);
1080 #else
1081           xelf_getshdr_copy (fileinfo->scninfo[cnt].scn, shdr,
1082                              fileinfo->scninfo[cnt].shdr);
1083 #endif
1084           if (shdr == NULL)
1085             {
1086               /* This should never happen.  */
1087               fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1088                        fileinfo->rfname, __FILE__, __LINE__);
1089               return 1;
1090             }
1091         }
1092       else
1093         shdr = &SCNINFO_SHDR (fileinfo->scninfo[cnt].shdr);
1094
1095       Elf_Data *data = elf_getdata (fileinfo->scninfo[cnt].scn, NULL);
1096
1097       /* Check whether this section is marked as merge-able.  */
1098       has_merge_sections |= (shdr->sh_flags & SHF_MERGE) != 0;
1099
1100       /* Get the ELF section header and data.  */
1101       /* Make the file structure available.  */
1102       fileinfo->scninfo[cnt].fileinfo = fileinfo;
1103
1104       if (unlikely (shdr->sh_type == SHT_SYMTAB)
1105           || unlikely (shdr->sh_type == SHT_DYNSYM))
1106         {
1107           if (shdr->sh_type == SHT_SYMTAB)
1108             {
1109               assert (fileinfo->symtabdata == NULL);
1110               fileinfo->symtabdata = data;
1111               fileinfo->nsymtab = shdr->sh_size / shdr->sh_entsize;
1112               fileinfo->nlocalsymbols = shdr->sh_info;
1113               fileinfo->symstridx = shdr->sh_link;
1114             }
1115           else
1116             {
1117               assert (fileinfo->dynsymtabdata == NULL);
1118               fileinfo->dynsymtabdata = data;
1119               fileinfo->ndynsymtab = shdr->sh_size / shdr->sh_entsize;
1120               fileinfo->dynsymstridx = shdr->sh_link;
1121             }
1122
1123           /* If we are looking for the normal symbol table we just
1124              found it.  */
1125           if (secttype == shdr->sh_type)
1126             {
1127               assert (symtabdata == NULL);
1128               symtabdata = data;
1129               symstridx = shdr->sh_link;
1130               nsymbols = shdr->sh_size / shdr->sh_entsize;
1131               nlocalsymbols = shdr->sh_info;
1132             }
1133         }
1134       else if (unlikely (shdr->sh_type == SHT_SYMTAB_SHNDX))
1135         {
1136           assert (xndxdata == NULL);
1137           fileinfo->xndxdata = xndxdata = data;
1138         }
1139       else if (unlikely (shdr->sh_type == SHT_GNU_versym))
1140         {
1141           assert (versymdata == 0);
1142           fileinfo->versymdata = versymdata = data;
1143         }
1144       else if (unlikely (shdr->sh_type == SHT_GNU_verdef))
1145         {
1146           size_t nversions;
1147
1148           assert (verdefdata == 0);
1149           fileinfo->verdefdata = verdefdata = data;
1150
1151           /* Allocate the arrays flagging the use of the version and
1152              to track of allocated names.  */
1153           fileinfo->nverdef = nversions = shdr->sh_info;
1154           /* We have NVERSIONS + 1 because the indeces used to access the
1155              sectino start with one; zero represents local binding.  */
1156           fileinfo->verdefused = (XElf_Versym *)
1157             obstack_calloc (&ld_state.smem,
1158                             sizeof (XElf_Versym) * (nversions + 1));
1159           fileinfo->verdefent = (struct Ebl_Strent **)
1160             obstack_alloc (&ld_state.smem,
1161                            sizeof (struct Ebl_Strent *) * (nversions + 1));
1162         }
1163       else if (unlikely (shdr->sh_type == SHT_GNU_verneed))
1164         {
1165           assert (verneeddata == 0);
1166           fileinfo->verneeddata = verneeddata = data;
1167         }
1168       else if (unlikely (shdr->sh_type == SHT_DYNAMIC))
1169         {
1170           assert (fileinfo->dynscn == NULL);
1171           fileinfo->dynscn = fileinfo->scninfo[cnt].scn;
1172         }
1173       else if (unlikely (shdr->sh_type == SHT_GROUP))
1174         {
1175           Elf_Scn *symscn;
1176           XElf_Shdr_vardef (symshdr);
1177           Elf_Data *symdata;
1178
1179           if (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_REL)
1180             error (EXIT_FAILURE, 0, gettext ("\
1181 %s: only files of type ET_REL might contain section groups"),
1182                    fileinfo->fname);
1183
1184           fileinfo->scninfo[cnt].next = fileinfo->groups;
1185           fileinfo->scninfo[cnt].grpid = cnt;
1186           fileinfo->groups = &fileinfo->scninfo[cnt];
1187
1188           /* Determine the signature.  We create a symbol record for
1189              it.  Only the name element is important.  */
1190           fileinfo->scninfo[cnt].symbols = (struct symbol *)
1191             obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1192
1193           symscn = elf_getscn (fileinfo->elf, shdr->sh_link);
1194           xelf_getshdr (symscn, symshdr);
1195           symdata = elf_getdata (symscn, NULL);
1196           if (symshdr != NULL)
1197             {
1198               XElf_Sym_vardef (sym);
1199
1200               /* We don't need the section index and therefore we don't
1201                  have to use 'xelf_getsymshndx'.  */
1202               xelf_getsym (symdata, shdr->sh_info, sym);
1203               if (sym != NULL)
1204                 {
1205                   struct symbol *symbol = fileinfo->scninfo[cnt].symbols;
1206
1207                   symbol->name = elf_strptr (fileinfo->elf, symshdr->sh_link,
1208                                              sym->st_name);
1209                   symbol->symidx = shdr->sh_info;
1210                   symbol->file = fileinfo;
1211                 }
1212             }
1213           if (fileinfo->scninfo[cnt].symbols->name == NULL)
1214             error (EXIT_FAILURE, 0, gettext ("\
1215 %s: cannot determine signature of section group [%2zd] '%s': %s"),
1216                    fileinfo->fname,
1217                    elf_ndxscn (fileinfo->scninfo[cnt].scn),
1218                    elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1219                                shdr->sh_name),
1220                    elf_errmsg (-1));
1221
1222           /* The 'used' flag is used to indicate when the information
1223              in the section group is used to mark all other sections
1224              as used.  So it must not be true yet.  */
1225           assert (fileinfo->scninfo[cnt].used == false);
1226         }
1227       else if (! SECTION_TYPE_P (&ld_state, shdr->sh_type)
1228                && unlikely ((shdr->sh_flags & SHF_OS_NONCONFORMING) != 0))
1229         /* According to the gABI it is a fatal error if the file contains
1230            a section with unknown type and the SHF_OS_NONCONFORMING flag
1231            set.  */
1232         error (EXIT_FAILURE, 0,
1233                gettext ("%s: section '%s' has unknown type: %d"),
1234                fileinfo->fname,
1235                elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1236                            shdr->sh_name),
1237                (int) shdr->sh_type);
1238       /* We don't have to add a few section types here.  These will be
1239          generated from scratch for the new output file.  We also
1240          don't add the sections of DSOs here since these sections are
1241          not used in the resulting object file.  */
1242       else if (likely (fileinfo->file_type == relocatable_file_type)
1243                && likely (cnt > 0)
1244                && likely (shdr->sh_type == SHT_PROGBITS
1245                           || shdr->sh_type == SHT_RELA
1246                           || shdr->sh_type == SHT_REL
1247                           || shdr->sh_type == SHT_NOTE
1248                           || shdr->sh_type == SHT_NOBITS
1249                           || shdr->sh_type == SHT_INIT_ARRAY
1250                           || shdr->sh_type == SHT_FINI_ARRAY
1251                           || shdr->sh_type == SHT_PREINIT_ARRAY))
1252         {
1253           /* Check whether the check needs to be executable.  */
1254           if (shdr->sh_type == SHT_PROGBITS
1255               && (shdr->sh_flags & SHF_EXECINSTR) == 0
1256               && strcmp (elf_strptr (fileinfo->elf, fileinfo->shstrndx,
1257                                      shdr->sh_name),
1258                          ".note.GNU-stack") == 0)
1259             execstack = execstack_false;
1260
1261           add_section (fileinfo, &fileinfo->scninfo[cnt]);
1262         }
1263     }
1264
1265   /* Now we know more about the requirements for an executable stack
1266      of the result.  */
1267   if (fileinfo->file_type == relocatable_file_type
1268       && execstack == execstack_true
1269       && ld_state.execstack != execstack_false_force)
1270     ld_state.execstack = execstack_true;
1271
1272   /* Handle the symbols.  Record defined and undefined symbols in the
1273      hash table.  In theory there can be a file without any symbol
1274      table.  */
1275   if (likely (symtabdata != NULL))
1276     {
1277       /* In case this file contains merge-able sections we have to
1278          locate the symbols which are in these sections.  */
1279       fileinfo->has_merge_sections = has_merge_sections;
1280       if (likely (has_merge_sections))
1281         {
1282           fileinfo->symref = (struct symbol **)
1283             obstack_calloc (&ld_state.smem,
1284                             nsymbols * sizeof (struct symbol *));
1285
1286           /* Only handle the local symbols here.  */
1287           for (cnt = 0; cnt < nlocalsymbols; ++cnt)
1288             {
1289               Elf32_Word shndx;
1290               XElf_Sym_vardef (sym);
1291
1292               xelf_getsymshndx (symtabdata, xndxdata, cnt, sym, shndx);
1293               if (sym == NULL)
1294                 {
1295                   /* This should never happen.  */
1296                   fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1297                            fileinfo->rfname, __FILE__, __LINE__);
1298                   return 1;
1299                 }
1300
1301               if (likely (shndx != SHN_XINDEX))
1302                 shndx = sym->st_shndx;
1303               else if (unlikely (shndx == 0))
1304                 {
1305                   fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1306                            fileinfo->rfname, __FILE__, __LINE__);
1307                   return 1;
1308                 }
1309
1310               if (XELF_ST_TYPE (sym->st_info) != STT_SECTION
1311                   && (shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE)
1312                   && (SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_flags
1313                       & SHF_MERGE))
1314                 {
1315                   /* Create a symbol record for this symbol and add it
1316                      to the list for this section.  */
1317                   struct symbol *newp;
1318
1319                   newp = (struct symbol *)
1320                     obstack_calloc (&ld_state.smem, sizeof (struct symbol));
1321
1322                   newp->symidx = cnt;
1323                   newp->scndx = shndx;
1324                   newp->file = fileinfo;
1325                   fileinfo->symref[cnt] = newp;
1326
1327                   if (fileinfo->scninfo[shndx].symbols == NULL)
1328                     fileinfo->scninfo[shndx].symbols = newp->next_in_scn
1329                       = newp;
1330                   else
1331                     {
1332                       newp->next_in_scn
1333                         = fileinfo->scninfo[shndx].symbols->next_in_scn;
1334                       fileinfo->scninfo[shndx].symbols
1335                         = fileinfo->scninfo[shndx].symbols->next_in_scn = newp;
1336                     }
1337                 }
1338             }
1339         }
1340       else
1341         /* Create array with pointers to the symbol definitions.  Note
1342            that we only allocate memory for the non-local symbols
1343            since we have no merge-able sections.  But we store the
1344            pointer as if it was for the whole symbol table.  This
1345            saves some memory.  */
1346         fileinfo->symref = (struct symbol **)
1347           obstack_calloc (&ld_state.smem, ((nsymbols - nlocalsymbols)
1348                                            * sizeof (struct symbol *)))
1349           - nlocalsymbols;
1350
1351       /* Don't handle local symbols here.  It's either not necessary
1352          at all or has already happened.  */
1353       for (cnt = nlocalsymbols; cnt < nsymbols; ++cnt)
1354         {
1355           XElf_Sym_vardef (sym);
1356           Elf32_Word shndx;
1357           xelf_getsymshndx (symtabdata, xndxdata, cnt, sym, shndx);
1358
1359           if (sym == NULL)
1360             {
1361               /* This should never happen.  */
1362               fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1363                        fileinfo->rfname, __FILE__, __LINE__);
1364               return 1;
1365             }
1366
1367           if (likely (shndx != SHN_XINDEX))
1368             shndx = sym->st_shndx;
1369           else if (unlikely (shndx == 0))
1370             {
1371               fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1372                        fileinfo->rfname, __FILE__, __LINE__);
1373               return 1;
1374             }
1375
1376           /* We ignore ABS symbols from DSOs.  */
1377           // XXX Is this correct?
1378           if (unlikely (shndx == SHN_ABS) && secttype == SHT_DYNSYM)
1379             continue;
1380
1381           /* If the DSO uses symbols determine whether this is the default
1382              version.  Otherwise we'll ignore the symbol.  */
1383           if (versymdata != NULL)
1384             {
1385               XElf_Versym versym;
1386
1387               if (xelf_getversym_copy (versymdata, cnt, versym) == NULL)
1388                 /* XXX Should we handle faulty input files more graceful?  */
1389                 assert (! "xelf_getversym failed");
1390
1391               if ((versym & 0x8000) != 0)
1392                 /* Ignore the symbol, it's not the default version.  */
1393                 continue;
1394             }
1395
1396           /* See whether we know anything about this symbol.  */
1397           struct symbol search;
1398           search.name = elf_strptr (fileinfo->elf, symstridx, sym->st_name);
1399           unsigned long int hval = elf_hash (search.name);
1400
1401           /* We ignore the symbols the linker generates.  This are
1402              _GLOBAL_OFFSET_TABLE_, _DYNAMIC.  */
1403           // XXX This loop is hot and the following tests hardly ever match.
1404           // XXX Maybe move the tests somewhere they are executed less often.
1405           if (((unlikely (hval == 165832675)
1406                 && strcmp (search.name, "_DYNAMIC") == 0)
1407                || (unlikely (hval == 102264335)
1408                    && strcmp (search.name, "_GLOBAL_OFFSET_TABLE_") == 0))
1409               && sym->st_shndx != SHN_UNDEF
1410               /* If somebody defines such a variable in a relocatable we
1411                  don't ignore it.  Let the user get what s/he deserves.  */
1412               && fileinfo->file_type != relocatable_file_type)
1413             continue;
1414
1415           struct symbol *oldp = ld_symbol_tab_find (&ld_state.symbol_tab,
1416                                                     hval, &search);
1417           struct symbol *newp;
1418           if (likely (oldp == NULL))
1419             {
1420               /* No symbol of this name know.  Add it.  */
1421               newp = (struct symbol *) obstack_alloc (&ld_state.smem,
1422                                                       sizeof (*newp));
1423               newp->name = search.name;
1424               newp->size = sym->st_size;
1425               newp->type = XELF_ST_TYPE (sym->st_info);
1426               newp->symidx = cnt;
1427               newp->outsymidx = 0;
1428               newp->outdynsymidx = 0;
1429               newp->scndx = shndx;
1430               newp->file = fileinfo;
1431               newp->defined = newp->scndx != SHN_UNDEF;
1432               newp->common = newp->scndx == SHN_COMMON;
1433               newp->weak = XELF_ST_BIND (sym->st_info) == STB_WEAK;
1434               newp->added = 0;
1435               newp->merged = 0;
1436               newp->need_copy = 0;
1437               newp->on_dsolist = 0;
1438               newp->in_dso = secttype == SHT_DYNSYM;
1439               newp->next_in_scn = NULL;
1440 #ifndef NDEBUG
1441               newp->next = NULL;
1442               newp->previous = NULL;
1443 #endif
1444
1445               if (newp->scndx == SHN_UNDEF)
1446                 {
1447                   CDBL_LIST_ADD_REAR (ld_state.unresolved, newp);
1448                   ++ld_state.nunresolved;
1449                   if (! newp->weak)
1450                     ++ld_state.nunresolved_nonweak;
1451                 }
1452               else if (newp->scndx == SHN_COMMON)
1453                 {
1454                   /* Store the alignment requirement.  */
1455                   newp->merge.value = sym->st_value;
1456
1457                   CDBL_LIST_ADD_REAR (ld_state.common_syms, newp);
1458                 }
1459
1460               /* Insert the new symbol.  */
1461               if (unlikely (ld_symbol_tab_insert (&ld_state.symbol_tab,
1462                                                   hval, newp) != 0))
1463                 /* This cannot happen.  */
1464                 abort ();
1465
1466               fileinfo->symref[cnt] = newp;
1467
1468               /* We have a few special symbols to recognize.  The symbols
1469                  _init and _fini are the initialization and finalization
1470                  functions respectively.  They have to be made known in
1471                  the dynamic section and therefore we have to find out
1472                  now whether these functions exist or not.  */
1473               if (hval == 6685956 && strcmp (newp->name, "_init") == 0)
1474                 ld_state.init_symbol = newp;
1475               else if (hval == 6672457 && strcmp (newp->name, "_fini") == 0)
1476                 ld_state.fini_symbol = newp;
1477             }
1478           else if (unlikely (check_definition (sym, cnt, fileinfo, oldp) != 0))
1479             /* A fatal error (multiple definition of a symbol)
1480                occurred, no need to continue.  */
1481             return 1;
1482           else
1483             /* Use the previously allocated symbol record.  It has
1484                been updated in check_definition(), if necessary.  */
1485             newp = fileinfo->symref[cnt] = oldp;
1486
1487           /* Mark the section the symbol we need comes from as used.  */
1488           if (shndx != SHN_UNDEF
1489               && (shndx < SHN_LORESERVE || shndx > SHN_HIRESERVE))
1490             {
1491               struct scninfo *ignore;
1492
1493 #ifndef NDEBUG
1494               size_t shnum;
1495               assert (elf_getshnum (fileinfo->elf, &shnum) == 0);
1496               assert (shndx < shnum);
1497 #endif
1498
1499               /* Mark section (and all dependencies) as used.  */
1500               mark_section_used (&fileinfo->scninfo[shndx], shndx, &ignore);
1501
1502               /* Check whether the section is merge-able.  In this case we
1503                  have to record the symbol.  */
1504               if (SCNINFO_SHDR (fileinfo->scninfo[shndx].shdr).sh_flags
1505                   & SHF_MERGE)
1506                 {
1507                   if (fileinfo->scninfo[shndx].symbols == NULL)
1508                     fileinfo->scninfo[shndx].symbols = newp->next_in_scn
1509                       = newp;
1510                   else
1511                     {
1512                       newp->next_in_scn
1513                         = fileinfo->scninfo[shndx].symbols->next_in_scn;
1514                       fileinfo->scninfo[shndx].symbols
1515                         = fileinfo->scninfo[shndx].symbols->next_in_scn = newp;
1516                     }
1517                 }
1518             }
1519         }
1520
1521       /* This file is used.  */
1522       if (likely (fileinfo->file_type == relocatable_file_type))
1523         {
1524           if (unlikely (ld_state.relfiles == NULL))
1525             ld_state.relfiles = fileinfo->next = fileinfo;
1526           else
1527             {
1528               fileinfo->next = ld_state.relfiles->next;
1529               ld_state.relfiles = ld_state.relfiles->next = fileinfo;
1530             }
1531
1532           /* Update some summary information in the state structure.  */
1533           ld_state.nsymtab += fileinfo->nsymtab;
1534           ld_state.nlocalsymbols += fileinfo->nlocalsymbols;
1535         }
1536       else if (likely (fileinfo->file_type == dso_file_type))
1537         {
1538           CSNGL_LIST_ADD_REAR (ld_state.dsofiles, fileinfo);
1539           ++ld_state.ndsofiles;
1540
1541           if (fileinfo->lazyload)
1542             /* We have to create another dynamic section entry for the
1543                DT_POSFLAG_1 entry.
1544
1545                XXX Once more functionality than the lazyloading flag
1546                are suppported the test must be extended.  */
1547             ++ld_state.ndsofiles;
1548         }
1549     }
1550
1551   return 0;
1552 }
1553
1554
1555 int
1556 ld_handle_filename_list (struct filename_list *fnames)
1557 {
1558   struct filename_list *runp;
1559   int res = 0;
1560
1561   for (runp = fnames; runp != NULL; runp = runp->next)
1562     {
1563       struct usedfiles *curp;
1564
1565       /* Create a record for the new file.  */
1566       curp = runp->real = ld_new_inputfile (runp->name, relocatable_file_type);
1567
1568       /* Set flags for group handling.  */
1569       curp->group_start = runp->group_start;
1570       curp->group_end = runp->group_end;
1571
1572       /* Set as-needed flag from the file, not the command line.  */
1573       curp->as_needed = runp->as_needed;
1574
1575       /* Read the file and everything else which comes up, including
1576          handling groups.  */
1577       do
1578         res |= FILE_PROCESS (-1, curp, &ld_state, &curp);
1579       while (curp != NULL);
1580     }
1581
1582   /* Free the list.  */
1583   while (fnames != NULL)
1584     {
1585       runp = fnames;
1586       fnames = fnames->next;
1587       free (runp);
1588     }
1589
1590   return res;
1591 }
1592
1593
1594 /* Handle opening of the given file with ELF descriptor.  */
1595 static int
1596 open_elf (struct usedfiles *fileinfo, Elf *elf)
1597 {
1598   int res = 0;
1599
1600   if (elf == NULL)
1601     error (EXIT_FAILURE, 0,
1602            gettext ("cannot get descriptor for ELF file (%s:%d): %s\n"),
1603            __FILE__, __LINE__, elf_errmsg (-1));
1604
1605   if (unlikely (elf_kind (elf) == ELF_K_NONE))
1606     {
1607       struct filename_list *fnames;
1608
1609       /* We don't have to look at this file again.  */
1610       fileinfo->status = closed;
1611
1612       /* Let's see whether this is a linker script.  */
1613       if (fileinfo->fd != -1)
1614         /* Create a stream from the file handle we know.  */
1615         ldin = fdopen (fileinfo->fd, "r");
1616       else
1617         {
1618           /* Get the memory for the archive member.  */
1619           char *content;
1620           size_t contentsize;
1621
1622           /* Get the content of the file.  */
1623           content = elf_rawfile (elf, &contentsize);
1624           if (content == NULL)
1625             {
1626               fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1627                        fileinfo->rfname, __FILE__, __LINE__);
1628               return 1;
1629             }
1630
1631           /* The content of the file is available in memory.  Read the
1632              memory region as a stream.  */
1633           ldin = fmemopen (content, contentsize, "r");
1634         }
1635
1636       /* No need for locking.  */
1637       __fsetlocking (ldin, FSETLOCKING_BYCALLER);
1638
1639       if (ldin == NULL)
1640         error (EXIT_FAILURE, errno, gettext ("cannot open '%s'"),
1641                fileinfo->rfname);
1642
1643       /* Parse the file.  If it is a linker script no problems will be
1644          reported.  */
1645       ld_state.srcfiles = NULL;
1646       ldlineno = 1;
1647       ld_scan_version_script = 0;
1648       ldin_fname = fileinfo->rfname;
1649       res = ldparse ();
1650
1651       fclose (ldin);
1652       if (fileinfo->fd != -1 && !fileinfo->fd_passed)
1653         {
1654           /* We won't need the file descriptor again.  */
1655           close (fileinfo->fd);
1656           fileinfo->fd = -1;
1657         }
1658
1659       elf_end (elf);
1660
1661       if (unlikely (res != 0))
1662         /* Something went wrong during parsing.  */
1663         return 1;
1664
1665       /* This is no ELF file.  */
1666       fileinfo->elf = NULL;
1667
1668       /* Now we have to handle eventual INPUT and GROUP statements in
1669          the script.  Read the files mentioned.  */
1670       fnames = ld_state.srcfiles;
1671       if (fnames != NULL)
1672         {
1673           struct filename_list *oldp;
1674
1675           /* Convert the list into a normal single-linked list.  */
1676           oldp = fnames;
1677           fnames = fnames->next;
1678           oldp->next = NULL;
1679
1680           /* Remove the list from the state structure.  */
1681           ld_state.srcfiles = NULL;
1682
1683           if (unlikely (ld_handle_filename_list (fnames) != 0))
1684             return 1;
1685         }
1686
1687       return 0;
1688     }
1689
1690   /* Store the file info.  */
1691   fileinfo->elf = elf;
1692
1693   /* The file is ready for action.  */
1694   fileinfo->status = opened;
1695
1696   return 0;
1697 }
1698
1699
1700 static int
1701 add_whole_archive (struct usedfiles *fileinfo)
1702 {
1703   Elf *arelf;
1704   Elf_Cmd cmd = ELF_C_READ_MMAP_PRIVATE;
1705   int res = 0;
1706
1707   while ((arelf = elf_begin (fileinfo->fd, cmd, fileinfo->elf)) != NULL)
1708     {
1709       Elf_Arhdr *arhdr = elf_getarhdr (arelf);
1710       struct usedfiles *newp;
1711
1712       if (arhdr == NULL)
1713         abort ();
1714
1715       /* Just to be sure; since these are no files in the archive
1716          these names should never be returned.  */
1717       assert (strcmp (arhdr->ar_name, "/") != 0);
1718       assert (strcmp (arhdr->ar_name, "//") != 0);
1719
1720       newp = ld_new_inputfile (arhdr->ar_name, relocatable_file_type);
1721       newp->archive_file = fileinfo;
1722
1723       if (unlikely (ld_state.trace_files))
1724         print_file_name (stdout, newp, 1, 1);
1725
1726       /* This shows that this file is contained in an archive.  */
1727       newp->fd = -1;
1728       /* Store the ELF descriptor.  */
1729       newp->elf = arelf;
1730       /* Show that we are open for business.  */
1731       newp->status = opened;
1732
1733       /* Proces the file, add all the symbols etc.  */
1734       res = file_process2 (newp);
1735       if (unlikely (res != 0))
1736             break;
1737
1738       /* Advance to the next archive element.  */
1739       cmd = elf_next (arelf);
1740     }
1741
1742   return res;
1743 }
1744
1745
1746 static int
1747 extract_from_archive (struct usedfiles *fileinfo)
1748 {
1749   static int archive_seq;
1750   int res = 0;
1751
1752   /* This is an archive we are not using completely.  Give it a
1753      unique number.  */
1754   fileinfo->archive_seq = ++archive_seq;
1755
1756   /* If there are no unresolved symbols don't do anything.  */
1757   if ((likely (ld_state.extract_rule == defaultextract)
1758        && ld_state.nunresolved_nonweak == 0)
1759       || (unlikely (ld_state.extract_rule == weakextract)
1760           && ld_state.nunresolved == 0))
1761     return 0;
1762
1763   Elf_Arsym *syms;
1764   size_t nsyms;
1765
1766   /* Get all the symbols.  */
1767   syms = elf_getarsym (fileinfo->elf, &nsyms);
1768   if (syms == NULL)
1769     {
1770     cannot_read_archive:
1771       error (0, 0, gettext ("cannot read archive `%s': %s"),
1772              fileinfo->rfname, elf_errmsg (-1));
1773
1774       /* We cannot use this archive anymore.  */
1775       fileinfo->status = closed;
1776
1777       return 1;
1778     }
1779
1780   /* Now add all the symbols to the hash table.  Note that there
1781      can potentially be duplicate definitions.  We'll always use
1782      the first definition.  */
1783   // XXX Is this a compatible behavior?
1784   bool any_used;
1785   int nround = 0;
1786   do
1787     {
1788       any_used = false;
1789
1790       size_t cnt;
1791       for (cnt = 0; cnt < nsyms; ++cnt)
1792         {
1793           struct symbol search = { .name = syms[cnt].as_name };
1794           struct symbol *sym = ld_symbol_tab_find (&ld_state.symbol_tab,
1795                                                    syms[cnt].as_hash, &search);
1796           if (sym != NULL && ! sym->defined)
1797             {
1798               /* The symbol is referenced and not defined.  */
1799               Elf *arelf;
1800               Elf_Arhdr *arhdr;
1801               struct usedfiles *newp;
1802
1803               /* Find the archive member for this symbol.  */
1804               if (unlikely (elf_rand (fileinfo->elf, syms[cnt].as_off)
1805                             != syms[cnt].as_off))
1806                 goto cannot_read_archive;
1807
1808               /* Note: no test of a failing 'elf_begin' call.  That's fine
1809                  since 'elf'getarhdr' will report the problem.  */
1810               arelf = elf_begin (fileinfo->fd, ELF_C_READ_MMAP_PRIVATE,
1811                                  fileinfo->elf);
1812               arhdr = elf_getarhdr (arelf);
1813               if (arhdr == NULL)
1814                 goto cannot_read_archive;
1815
1816               /* We have all the information and an ELF handle for the
1817                  archive member.  Create the normal data structure for
1818                  a file now.  */
1819               newp = ld_new_inputfile (obstack_strdup (&ld_state.smem,
1820                                                        arhdr->ar_name),
1821                                        relocatable_file_type);
1822               newp->archive_file = fileinfo;
1823
1824               if (unlikely (ld_state.trace_files))
1825                 print_file_name (stdout, newp, 1, 1);
1826
1827               /* This shows that this file is contained in an archive.  */
1828               newp->fd = -1;
1829               /* Store the ELF descriptor.  */
1830               newp->elf = arelf;
1831               /* Show that we are open for business.  */
1832               newp->status = in_archive;
1833
1834               /* Now read the file and add all the symbols.  */
1835               res = file_process2 (newp);
1836               if (unlikely (res != 0))
1837                 return res;
1838
1839               any_used = true;
1840             }
1841         }
1842
1843       if (++nround == 1)
1844         {
1845           /* This is an archive therefore it must have a number.  */
1846           assert (fileinfo->archive_seq != 0);
1847           ld_state.last_archive_used = fileinfo->archive_seq;
1848         }
1849     }
1850   while (any_used);
1851
1852   return res;
1853 }
1854
1855
1856 static int
1857 file_process2 (struct usedfiles *fileinfo)
1858 {
1859   int res;
1860
1861   if (likely (elf_kind (fileinfo->elf) == ELF_K_ELF))
1862     {
1863       /* The first time we get here we read the ELF header.  */
1864 #if NATIVE_ELF != 0
1865       if (likely (fileinfo->ehdr == NULL))
1866 #else
1867       if (likely (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_NONE))
1868 #endif
1869         {
1870           XElf_Ehdr *ehdr;
1871 #if NATIVE_ELF != 0
1872           ehdr = xelf_getehdr (fileinfo->elf, fileinfo->ehdr);
1873 #else
1874           xelf_getehdr_copy (fileinfo->elf, ehdr, fileinfo->ehdr);
1875 #endif
1876           if (ehdr == NULL)
1877             {
1878               fprintf (stderr, gettext ("%s: invalid ELF file (%s:%d)\n"),
1879                        fileinfo->rfname, __FILE__, __LINE__);
1880               fileinfo->status = closed;
1881               return 1;
1882             }
1883
1884           if (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_REL
1885               && unlikely (FILEINFO_EHDR (fileinfo->ehdr).e_type != ET_DYN))
1886             /* XXX Add ebl* function to query types which are allowed
1887                to link in.  */
1888             {
1889               char buf[64];
1890
1891               print_file_name (stderr, fileinfo, 1, 0);
1892               fprintf (stderr,
1893                        gettext ("file of type %s cannot be linked in\n"),
1894                        ebl_object_type_name (ld_state.ebl,
1895                                              FILEINFO_EHDR (fileinfo->ehdr).e_type,
1896                                              buf, sizeof (buf)));
1897               fileinfo->status = closed;
1898               return 1;
1899             }
1900
1901           /* Determine the section header string table section index.  */
1902           if (unlikely (elf_getshstrndx (fileinfo->elf, &fileinfo->shstrndx)
1903                         < 0))
1904             {
1905               fprintf (stderr, gettext ("\
1906 %s: cannot get section header string table index: %s\n"),
1907                        fileinfo->rfname, elf_errmsg (-1));
1908               fileinfo->status = closed;
1909               return 1;
1910             }
1911         }
1912
1913       /* Now handle the different types of files.  */
1914       if (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_REL)
1915         {
1916           /* Add all the symbol.  Relocatable files have symbol
1917              tables.  */
1918           res = add_relocatable_file (fileinfo, SHT_SYMTAB);
1919         }
1920       else
1921         {
1922           bool has_l_name = fileinfo->file_type == archive_file_type;
1923
1924           assert (FILEINFO_EHDR (fileinfo->ehdr).e_type == ET_DYN);
1925
1926           /* If the file is a DT_NEEDED dependency then the type is
1927              already correctly specified.  */
1928           if (fileinfo->file_type != dso_needed_file_type)
1929             fileinfo->file_type = dso_file_type;
1930
1931           /* We cannot use DSOs when generating relocatable objects.  */
1932           if (ld_state.file_type == relocatable_file_type)
1933             {
1934               error (0, 0, gettext ("\
1935 cannot use DSO '%s' when generating relocatable object file"),
1936                      fileinfo->fname);
1937               return 1;
1938             }
1939
1940           /* Add all the symbols.  For DSOs we are looking at the
1941              dynamic symbol table.  */
1942           res = add_relocatable_file (fileinfo, SHT_DYNSYM);
1943
1944           /* We always have to have a dynamic section.  */
1945           assert (fileinfo->dynscn != NULL);
1946
1947           /* We have to remember the dependencies for this object.  It
1948              is necessary to look them up.  */
1949           XElf_Shdr_vardef (dynshdr);
1950           xelf_getshdr (fileinfo->dynscn, dynshdr);
1951
1952           Elf_Data *dyndata = elf_getdata (fileinfo->dynscn, NULL);
1953           /* XXX Should we flag the failure to get the dynamic section?  */
1954           if (dynshdr != NULL)
1955             {
1956               int cnt = dynshdr->sh_size / dynshdr->sh_entsize;
1957               XElf_Dyn_vardef (dyn);
1958
1959               while (--cnt >= 0)
1960                 {
1961                   xelf_getdyn (dyndata, cnt, dyn);
1962                   if (dyn != NULL)
1963                     {
1964                       if(dyn->d_tag == DT_NEEDED)
1965                         {
1966                           struct usedfiles *newp;
1967
1968                           newp = ld_new_inputfile (elf_strptr (fileinfo->elf,
1969                                                                dynshdr->sh_link,
1970                                                                dyn->d_un.d_val),
1971                                                    dso_needed_file_type);
1972
1973                           /* Enqueue the newly found dependencies.  */
1974                           // XXX Check that there not already a file with the
1975                           // same name.
1976                           CSNGL_LIST_ADD_REAR (ld_state.needed, newp);
1977                         }
1978                       else if (dyn->d_tag == DT_SONAME)
1979                         {
1980                           /* We use the DT_SONAME (this is what's there
1981                              for).  */
1982                           fileinfo->soname = elf_strptr (fileinfo->elf,
1983                                                          dynshdr->sh_link,
1984                                                          dyn->d_un.d_val);
1985                           has_l_name = false;
1986                         }
1987                     }
1988                 }
1989             }
1990
1991           /* Construct the file name if the DSO has no SONAME and the
1992              file name comes from a -lXX parameter on the comment
1993              line.  */
1994           if (unlikely (has_l_name))
1995             {
1996               /* The FNAME is the parameter the user specified on the
1997                  command line.  We prepend "lib" and append ".so".  */
1998               size_t len = strlen (fileinfo->fname) + 7;
1999               char *newp;
2000
2001               newp = (char *) obstack_alloc (&ld_state.smem, len);
2002               strcpy (stpcpy (stpcpy (newp, "lib"), fileinfo->fname), ".so");
2003
2004               fileinfo->soname = newp;
2005             }
2006         }
2007     }
2008   else if (likely (elf_kind (fileinfo->elf) == ELF_K_AR))
2009     {
2010       if (unlikely (ld_state.extract_rule == allextract))
2011         /* Which this option enabled we have to add all the object
2012            files in the archive.  */
2013         res = add_whole_archive (fileinfo);
2014       else if (ld_state.file_type == relocatable_file_type)
2015         {
2016           /* When generating a relocatable object we don't find files
2017              in archives.  */
2018           if (verbose)
2019             error (0, 0, gettext ("input file '%s' ignored"), fileinfo->fname);
2020
2021           res = 0;
2022         }
2023       else
2024         /* Extract only the members from the archive which are
2025            currently referenced by unresolved symbols.  */
2026         res = extract_from_archive (fileinfo);
2027     }
2028   else
2029     /* This should never happen, we know about no other types.  */
2030     abort ();
2031
2032   return res;
2033 }
2034
2035
2036 /* Process a given file.  The first parameter is a file descriptor for
2037    the file which can be -1 to indicate the file has not yet been
2038    found.  The second parameter describes the file to be opened, the
2039    last one is the state of the linker which among other information
2040    contain the paths we look at.  */
2041 static int
2042 ld_generic_file_process (int fd, struct usedfiles *fileinfo,
2043                          struct ld_state *statep, struct usedfiles **nextp)
2044 {
2045   int res = 0;
2046
2047   /* By default we go to the next file in the list.  */
2048   *nextp = fileinfo->next;
2049
2050   /* Set the flag to signal we are looking for a group start.  */
2051   if (unlikely (fileinfo->group_start))
2052     {
2053       ld_state.group_start_requested = true;
2054       fileinfo->group_start = false;
2055     }
2056
2057   /* If the file isn't open yet, open it now.  */
2058   if (likely (fileinfo->status == not_opened))
2059     {
2060       bool fd_passed = true;
2061
2062       if (likely (fd == -1))
2063         {
2064           /* Find the file ourselves.  */
2065           int err = open_along_path (fileinfo);
2066           if (unlikely (err != 0))
2067             /* We allow libraries and DSOs to be named more than once.
2068                Don't report an error to the caller.  */
2069             return err == EAGAIN ? 0 : err;
2070
2071           fd_passed = false;
2072         }
2073       else
2074         fileinfo->fd = fd;
2075
2076       /* Remember where we got the descriptor from.  */
2077       fileinfo->fd_passed = fd_passed;
2078
2079       /* We found the file.  Now test whether it is a file type we can
2080          handle.
2081
2082          XXX Do we have to have the ability to start from a given
2083          position in the search path again to look for another file if
2084          the one found has not the right type?  */
2085       res = open_elf (fileinfo, elf_begin (fileinfo->fd,
2086                                            is_dso_p (fileinfo->fd)
2087                                            ? ELF_C_READ_MMAP
2088                                            : ELF_C_READ_MMAP_PRIVATE, NULL));
2089       if (unlikely (res != 0))
2090         return res;
2091     }
2092
2093   /* Now that we have opened the file start processing it.  */
2094   if (likely (fileinfo->status != closed))
2095     res = file_process2 (fileinfo);
2096
2097   /* Determine which file to look at next.  */
2098   if (unlikely (fileinfo->group_backref != NULL))
2099     {
2100       /* We only go back if an archive other than the one we would go
2101          back to has been used in the last round.  */
2102       if (ld_state.last_archive_used > fileinfo->group_backref->archive_seq)
2103         {
2104           *nextp = fileinfo->group_backref;
2105           ld_state.last_archive_used = 0;
2106         }
2107       else
2108         {
2109           /* If we come here this means that the archives we read so
2110              far are not needed anymore.  We can free some of the data
2111              now.  */
2112           struct usedfiles *runp = ld_state.archives;
2113
2114           do
2115             {
2116               /* We don't need the ELF descriptor anymore.  Unless there
2117                  are no files from the archive used this will not free
2118                  the whole file but only some data structures.  */
2119               elf_end (runp->elf);
2120               runp->elf = NULL;
2121
2122               runp = runp->next;
2123             }
2124           while (runp != fileinfo->next);
2125         }
2126     }
2127   else if (unlikely (fileinfo->group_end))
2128     {
2129       /* This is the end of a group.  We possibly of to go back.
2130          Determine which file we would go back to and see whether it
2131          makes sense.  If there has not been an archive we don't have
2132          to do anything.  */
2133       if (!ld_state.group_start_requested)
2134         {
2135           if (ld_state.group_start_archive != ld_state.tailarchives)
2136             /* The loop would include more than one archive, add the
2137                pointer.  */
2138             {
2139               *nextp = ld_state.tailarchives->group_backref =
2140                 ld_state.group_start_archive;
2141               ld_state.last_archive_used = 0;
2142             }
2143           else
2144             /* We might still have to go back to the beginning of the
2145                group if since the last archive other files have been
2146                added.  But we go back exactly once.  */
2147             if (ld_state.tailarchives != fileinfo)
2148               {
2149                 *nextp = ld_state.group_start_archive;
2150                 ld_state.last_archive_used = 0;
2151               }
2152         }
2153
2154       /* Clear the flags.  */
2155       ld_state.group_start_requested = false;
2156       fileinfo->group_end = false;
2157     }
2158
2159   return res;
2160 }
2161
2162
2163 /* Library names passed to the linker as -lXX represent files named
2164    libXX.YY.  The YY part can have different forms, depending on the
2165    platform.  The generic set is .so and .a (in this order).  */
2166 static const char **
2167 ld_generic_lib_extensions (struct ld_state *statep __attribute__ ((__unused__)))
2168 {
2169   static const char *exts[] =
2170     {
2171       ".so", ".a", NULL
2172     };
2173
2174   return exts;
2175 }
2176
2177
2178 /* Flag unresolved symbols.  */
2179 static int
2180 ld_generic_flag_unresolved (struct ld_state *statep)
2181 {
2182   int retval = 0;
2183
2184   if (ld_state.nunresolved_nonweak > 0)
2185     {
2186       /* Go through the list and determine the unresolved symbols.  */
2187       struct symbol *first;
2188       struct symbol *s;
2189
2190       s = first = ld_state.unresolved->next;
2191       do
2192         {
2193           if (! s->defined && ! s->weak)
2194             {
2195               /* Two special symbol we recognize: the symbol for the
2196                  GOT and the dynamic section.  */
2197               if (strcmp (s->name, "_GLOBAL_OFFSET_TABLE_") == 0
2198                   || strcmp (s->name, "_DYNAMIC") == 0)
2199                 {
2200                   /* We will have to fill in more information later.  */
2201                   ld_state.need_got = true;
2202
2203                   /* Remember that we found it.  */
2204                   if (s->name[1] == 'G')
2205                     ld_state.got_symbol = s;
2206                   else
2207                     ld_state.dyn_symbol = s;
2208                 }
2209               else if (ld_state.file_type != dso_file_type || !ld_state.nodefs)
2210                 {
2211                   /* XXX The error message should get better.  It should use
2212                      the debugging information if present to tell where in the
2213                      sources the undefined reference is.  */
2214                   error (0, 0, gettext ("undefined symbol `%s' in %s"),
2215                          s->name, s->file->fname);
2216
2217                   retval = 1;
2218                 }
2219             }
2220
2221           /* We cannot decide here what to do with undefined
2222              references which will come from DSO since we do not know
2223              what kind of symbol we expect.  Only when looking at the
2224              relocations we can see whether we need a PLT entry or
2225              only a GOT entry.  */
2226
2227           s = s->next;
2228         }
2229       while (s != first);
2230     }
2231
2232   return retval;
2233 }
2234
2235
2236 /* Close the given file.  */
2237 static int
2238 ld_generic_file_close (struct usedfiles *fileinfo, struct ld_state *statep)
2239 {
2240   /* Close the ELF descriptor.  */
2241   elf_end (fileinfo->elf);
2242
2243   /* If we have opened the file descriptor close it.  But we might
2244      have done this already in which case FD is -1.  */
2245   if (!fileinfo->fd_passed && fileinfo->fd != -1)
2246     close (fileinfo->fd);
2247
2248   /* We allocated the resolved file name.  */
2249   if (fileinfo->fname != fileinfo->rfname)
2250     free ((char *) fileinfo->rfname);
2251
2252   return 0;
2253 }
2254
2255
2256 static void
2257 new_generated_scn (enum scn_kind kind, const char *name, int type, int flags,
2258                    int entsize, int align)
2259 {
2260   struct scnhead *newp;
2261
2262   newp = (struct scnhead *) obstack_calloc (&ld_state.smem,
2263                                             sizeof (struct scnhead));
2264   newp->kind = kind;
2265   newp->name = name;
2266   newp->nameent = ebl_strtabadd (ld_state.shstrtab, name, 0);
2267   newp->type = type;
2268   newp->flags = flags;
2269   newp->entsize = entsize;
2270   newp->align = align;
2271   newp->grp_signature = NULL;
2272   newp->used = true;
2273
2274   /* All is well.  Create now the data for the section and insert it
2275      into the section table.  */
2276   ld_section_tab_insert (&ld_state.section_tab, elf_hash (name), newp);
2277 }
2278
2279
2280 /* Create the sections which are generated by the linker and are not
2281    present in the input file.  */
2282 static void
2283 ld_generic_generate_sections (struct ld_state *statep)
2284 {
2285   /* The relocation section type.  */
2286   int rel_type = REL_TYPE (&ld_state) == DT_REL ? SHT_REL : SHT_RELA;
2287
2288   /* When building dynamically linked object we have to include a
2289      section containing a string describing the interpreter.  This
2290      should be at the very beginning of the file together with the
2291      other information the ELF loader (kernel or wherever) has to look
2292      at.  We put it as the first section in the file.
2293
2294      We also have to create the dynamic segment which is a special
2295      section the dynamic linker locates through an entry in the
2296      program header.  */
2297   if (dynamically_linked_p ())
2298     {
2299       /* Use any versioning (defined or required)?  */
2300       bool use_versioning = false;
2301       /* Use version requirements?  */
2302       bool need_version = false;
2303
2304       /* First the .interp section.  */
2305       new_generated_scn (scn_dot_interp, ".interp", SHT_PROGBITS, SHF_ALLOC,
2306                          0, 1);
2307
2308       /* Now the .dynamic section.  */
2309       new_generated_scn (scn_dot_dynamic, ".dynamic", SHT_DYNAMIC,
2310                          DYNAMIC_SECTION_FLAGS (&ld_state),
2311                          xelf_fsize (ld_state.outelf, ELF_T_DYN, 1),
2312                          xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2313
2314       /* We will need in any case the dynamic symbol table (even in
2315          the unlikely case that no symbol is exported or referenced
2316          from a DSO).  */
2317       ld_state.need_dynsym = true;
2318       new_generated_scn (scn_dot_dynsym, ".dynsym", SHT_DYNSYM, SHF_ALLOC,
2319                          xelf_fsize (ld_state.outelf, ELF_T_SYM, 1),
2320                          xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2321       /* It comes with a string table.  */
2322       new_generated_scn (scn_dot_dynstr, ".dynstr", SHT_STRTAB, SHF_ALLOC,
2323                          0, 1);
2324       /* And a hashing table.  */
2325       // XXX For Linux/Alpha we need other sizes unless they change...
2326       new_generated_scn (scn_dot_hash, ".hash", SHT_HASH, SHF_ALLOC,
2327                          sizeof (Elf32_Word), sizeof (Elf32_Word));
2328
2329       /* Create the section associated with the PLT if necessary.  */
2330       if (ld_state.nplt > 0)
2331         {
2332           /* Create the .plt section.  */
2333           /* XXX We might need a function which returns the section flags.  */
2334           new_generated_scn (scn_dot_plt, ".plt", SHT_PROGBITS,
2335                              SHF_ALLOC | SHF_EXECINSTR,
2336                              /* XXX Is the size correct?  */
2337                              xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2338                              xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2339
2340           /* Create the relocation section for the .plt.  This is always
2341              separate even if the other relocation sections are combined.  */
2342           new_generated_scn (scn_dot_pltrel, ".rel.plt", rel_type, SHF_ALLOC,
2343                              rel_type == SHT_REL
2344                              ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
2345                              : xelf_fsize (ld_state.outelf, ELF_T_RELA, 1),
2346                              xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2347
2348           /* This means we will also need the .got section.  */
2349           ld_state.need_got = true;
2350
2351           /* Mark all used DSOs as used.  Determine whether any referenced
2352              object uses symbol versioning.  */
2353           if (ld_state.from_dso != NULL)
2354             {
2355               struct symbol *srunp = ld_state.from_dso;
2356
2357               do
2358                 {
2359                   srunp->file->used = true;
2360
2361                   if (srunp->file->verdefdata != NULL)
2362                     {
2363                       XElf_Versym versym;
2364
2365                       /* The input DSO uses versioning.  */
2366                       use_versioning = true;
2367                       /* We reference versions.  */
2368                       need_version = true;
2369
2370                       if (xelf_getversym_copy (srunp->file->versymdata,
2371                                                srunp->symidx, versym) == NULL)
2372                         assert (! "xelf_getversym failed");
2373
2374                       /* We cannot link explicitly with an older
2375                          version of a symbol.  */
2376                       assert ((versym & 0x8000) == 0);
2377                       /* We cannot reference local (index 0) or plain
2378                          global (index 1) versions.  */
2379                       assert (versym > 1);
2380
2381                       /* Check whether we have already seen the
2382                          version and if not add it to the referenced
2383                          versions in the output file.  */
2384                       if (! srunp->file->verdefused[versym])
2385                         {
2386                           srunp->file->verdefused[versym] = 1;
2387
2388                           if (++srunp->file->nverdefused == 1)
2389                             /* Count the file if it is using versioning.  */
2390                             ++ld_state.nverdeffile;
2391                           ++ld_state.nverdefused;
2392                         }
2393                     }
2394                 }
2395               while ((srunp = srunp->next) != ld_state.from_dso);
2396             }
2397
2398           /* Create the sections used to record version dependencies.  */
2399           if (need_version)
2400             new_generated_scn (scn_dot_version_r, ".gnu.version_r",
2401                                SHT_GNU_verneed, SHF_ALLOC, 0,
2402                                xelf_fsize (ld_state.outelf, ELF_T_WORD, 1));
2403         }
2404
2405       /* Now count the used DSOs since this is what the user
2406          wants.  */
2407       int ndt_needed = 0;
2408       if (ld_state.ndsofiles > 0)
2409         {
2410           struct usedfiles *frunp = ld_state.dsofiles;
2411
2412           do
2413             if (! frunp->as_needed || frunp->used)
2414               {
2415                 ++ndt_needed;
2416                 if (frunp->lazyload)
2417                   /* We have to create another dynamic section
2418                      entry for the DT_POSFLAG_1 entry.
2419
2420                      XXX Once more functionality than the lazyloading
2421                      flag are suppported the test must be
2422                      extended.  */
2423                   ++ndt_needed;
2424               }
2425           while ((frunp = frunp->next) != ld_state.dsofiles);
2426         }
2427
2428       if (use_versioning)
2429         new_generated_scn (scn_dot_version, ".gnu.version", SHT_GNU_versym,
2430                            SHF_ALLOC,
2431                            xelf_fsize (ld_state.outelf, ELF_T_HALF, 1),
2432                            xelf_fsize (ld_state.outelf, ELF_T_HALF, 1));
2433
2434       /* We need some entries all the time.  */
2435       ld_state.ndynamic = (7 + (ld_state.runpath != NULL
2436                                 || ld_state.rpath != NULL)
2437                            + ndt_needed
2438                            + (ld_state.init_symbol != NULL ? 1 : 0)
2439                            + (ld_state.fini_symbol != NULL ? 1 : 0)
2440                            + (use_versioning ? 1 : 0)
2441                            + (need_version ? 2 : 0)
2442                            + (ld_state.nplt > 0 ? 4 : 0)
2443                            + (ld_state.relsize_total > 0 ? 3 : 0));
2444     }
2445
2446   /* When creating a relocatable file or when we are not stripping the
2447      output file we create a symbol table.  */
2448   ld_state.need_symtab = (ld_state.file_type == relocatable_file_type
2449                           || ld_state.strip == strip_none);
2450
2451   /* Add the .got section if needed.  */
2452   if (ld_state.need_got)
2453     /* XXX We might need a function which returns the section flags.  */
2454     new_generated_scn (scn_dot_got, ".got", SHT_PROGBITS,
2455                        SHF_ALLOC | SHF_WRITE,
2456                        xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1),
2457                        xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2458
2459   /* Add the .rel.dyn section.  */
2460   if (ld_state.relsize_total > 0)
2461     new_generated_scn (scn_dot_dynrel, ".rel.dyn", rel_type, SHF_ALLOC,
2462                        rel_type == SHT_REL
2463                        ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
2464                        : xelf_fsize (ld_state.outelf, ELF_T_RELA, 1),
2465                        xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1));
2466 }
2467
2468
2469 /* Callback function registered with on_exit to make sure the temporary
2470    files gets removed if something goes wrong.  */
2471 static void
2472 remove_tempfile (int status, void *arg)
2473 {
2474   if (status != 0 && ld_state.tempfname != NULL)
2475     unlink (ld_state.tempfname);
2476 }
2477
2478
2479 /* Create the output file.  The file name is given or "a.out".  We
2480    create as much of the ELF structure as possible.  */
2481 static int
2482 ld_generic_open_outfile (struct ld_state *statep, int machine, int klass,
2483                          int data)
2484 {
2485   /* We do not create the new file right away with the final name.
2486      This would destroy an existing file with this name before a
2487      replacement is finalized.  We create instead a temporary file in
2488      the same directory.  */
2489   if (ld_state.outfname == NULL)
2490     ld_state.outfname = "a.out";
2491
2492   size_t outfname_len = strlen (ld_state.outfname);
2493   char *tempfname = (char *) obstack_alloc (&ld_state.smem,
2494                                             outfname_len + sizeof (".XXXXXX"));
2495   ld_state.tempfname = tempfname;
2496
2497   int fd;
2498   int try = 0;
2499   while (1)
2500     {
2501       strcpy (mempcpy (tempfname, ld_state.outfname, outfname_len), ".XXXXXX");
2502
2503       /* The useof mktemp() here is fine.  We do not want to use
2504          mkstemp() since then the umask isn't used.  And the output
2505          file will have these permissions anyhow.  Any intruder could
2506          change the file later if it would be possible now.  */
2507       if (mktemp (tempfname) != NULL
2508           && (fd = open (tempfname, O_RDWR | O_EXCL | O_CREAT | O_NOFOLLOW,
2509                          ld_state.file_type == relocatable_file_type
2510                          ? DEFFILEMODE : ACCESSPERMS)) != -1)
2511         break;
2512
2513       /* Failed this round.  We keep trying a number of times.  */
2514       if (++try >= 10)
2515         error (EXIT_FAILURE, errno, gettext ("cannot create output file"));
2516     }
2517   ld_state.outfd = fd;
2518
2519   /* Make sure we remove the temporary file in case something goes
2520      wrong.  */
2521   on_exit (remove_tempfile, NULL);
2522
2523   /* Create the ELF file data for the output file.  */
2524   Elf *elf = ld_state.outelf = elf_begin (fd,
2525                                           conserve_memory
2526                                           ? ELF_C_WRITE : ELF_C_WRITE_MMAP,
2527                                           NULL);
2528   if (elf == NULL)
2529     error (EXIT_FAILURE, 0,
2530            gettext ("cannot create ELF descriptor for output file: %s"),
2531            elf_errmsg (-1));
2532
2533   /* Create the basic data structures.  */
2534   if (! xelf_newehdr (elf, klass))
2535     /* Couldn't create the ELF header.  Very bad.  */
2536     error (EXIT_FAILURE, 0,
2537            gettext ("could not create ELF header for output file: %s"),
2538            elf_errmsg (-1));
2539
2540   /* And get the current header so that we can modify it.  */
2541   XElf_Ehdr_vardef (ehdr);
2542   xelf_getehdr (elf, ehdr);
2543   assert (ehdr != NULL);
2544
2545   /* Set the machine type.  */
2546   ehdr->e_machine = machine;
2547
2548   /* Modify it according to the info we have here and now.  */
2549   if (ld_state.file_type == executable_file_type)
2550     ehdr->e_type = ET_EXEC;
2551   else if (ld_state.file_type == dso_file_type)
2552     ehdr->e_type = ET_DYN;
2553   else
2554     {
2555       assert (ld_state.file_type == relocatable_file_type);
2556       ehdr->e_type = ET_REL;
2557     }
2558
2559   /* Set the ELF version.  */
2560   ehdr->e_version = EV_CURRENT;
2561
2562   /* Set the endianness.  */
2563   ehdr->e_ident[EI_DATA] = data;
2564
2565   /* Write the ELF header information back.  */
2566   (void) xelf_update_ehdr (elf, ehdr);
2567
2568   return 0;
2569 }
2570
2571
2572 /* We compute the offsets of the various copied objects and the total
2573    size of the memory needed.  */
2574 // XXX The method used here is simple: go from front to back and pack
2575 // the objects in this order.  A more space efficient way would
2576 // actually trying to pack the objects as dense as possible.  But this
2577 // is more expensive.
2578 static void
2579 compute_copy_reloc_offset (XElf_Shdr *shdr)
2580 {
2581   struct symbol *runp = ld_state.from_dso;
2582   assert (runp != NULL);
2583
2584   XElf_Off maxalign = 1;
2585   XElf_Off offset = 0;
2586
2587   do
2588     if (runp->need_copy)
2589       {
2590         /* Determine alignment for the symbol.  */
2591         // XXX The question is how?  The symbol record itself does not
2592         // have the information.  So we have to be conservative and
2593         // assume the alignment of the section the symbol is in.
2594
2595         // XXX We can be more precise.  Use the offset from the beginning
2596         // of the section and determine the largest power of two with
2597         // module zero.
2598         XElf_Off symalign = MAX (SCNINFO_SHDR (runp->file->scninfo[runp->scndx].shdr).sh_addralign, 1);
2599         /* Keep track of the maximum alignment requirement.  */
2600         maxalign = MAX (maxalign, symalign);
2601
2602         /* Align current position.  */
2603         offset = (offset + symalign - 1) & ~(symalign - 1);
2604
2605         runp->merge.value = offset;
2606
2607         offset += runp->size;
2608       }
2609   while ((runp = runp->next) != ld_state.from_dso);
2610
2611   shdr->sh_type = SHT_NOBITS;
2612   shdr->sh_size = offset;
2613   shdr->sh_addralign = maxalign;
2614 }
2615
2616
2617 static void
2618 compute_common_symbol_offset (XElf_Shdr *shdr)
2619 {
2620   struct symbol *runp = ld_state.common_syms;
2621   assert (runp != NULL);
2622
2623   XElf_Off maxalign = 1;
2624   XElf_Off offset = 0;
2625
2626   do
2627     {
2628       /* Determine alignment for the symbol.  */
2629       XElf_Off symalign = runp->merge.value;
2630
2631       /* Keep track of the maximum alignment requirement.  */
2632       maxalign = MAX (maxalign, symalign);
2633
2634       /* Align current position.  */
2635       offset = (offset + symalign - 1) & ~(symalign - 1);
2636
2637       runp->merge.value = offset;
2638
2639       offset += runp->size;
2640     }
2641   while ((runp = runp->next) != ld_state.common_syms);
2642
2643   shdr->sh_type = SHT_NOBITS;
2644   shdr->sh_size = offset;
2645   shdr->sh_addralign = maxalign;
2646 }
2647
2648
2649 static void
2650 sort_sections_generic (void)
2651 {
2652   /* XXX TBI */
2653   abort ();
2654 }
2655
2656
2657 static int
2658 match_section (const char *osectname, struct filemask_section_name *sectmask,
2659                struct scnhead **scnhead, bool new_section, size_t segment_nr)
2660 {
2661   struct scninfo *prevp;
2662   struct scninfo *runp;
2663   struct scninfo *notused;
2664
2665   if (fnmatch (sectmask->section_name->name, (*scnhead)->name, 0) != 0)
2666     /* The section name does not match.  */
2667     return new_section;
2668
2669   /* If this is a section generated by the linker it doesn't contain
2670      the regular information (i.e., input section data etc) and must
2671      be handle special.  */
2672   if ((*scnhead)->kind != scn_normal)
2673     {
2674       (*scnhead)->name = osectname;
2675       (*scnhead)->segment_nr = segment_nr;
2676
2677       /* We have to count note section since they get their own
2678          program header entry.  */
2679       if ((*scnhead)->type == SHT_NOTE)
2680         ++ld_state.nnotesections;
2681
2682       ld_state.allsections[ld_state.nallsections++] = (*scnhead);
2683       return true;
2684     }
2685
2686   /* Now we have to match the file names of the input files.  Some of
2687      the sections here might not match.    */
2688   runp = (*scnhead)->last->next;
2689   prevp = (*scnhead)->last;
2690   notused = NULL;
2691
2692   do
2693     {
2694       /* Base of the file name the section comes from.  */
2695       const char *brfname = basename (runp->fileinfo->rfname);
2696
2697       /* If the section isn't used, the name doesn't match the positive
2698          inclusion list, or the name does match the negative inclusion
2699          list, ignore the section.  */
2700       if (!runp->used
2701           || (sectmask->filemask != NULL
2702               && fnmatch (sectmask->filemask, brfname, 0) != 0)
2703           || (sectmask->excludemask != NULL
2704               && fnmatch (sectmask->excludemask, brfname, 0) == 0))
2705         {
2706           /* This file does not match the file name masks.  */
2707           if (notused == NULL)
2708             notused = runp;
2709
2710           prevp = runp;
2711           runp = runp->next;
2712           if (runp == notused)
2713             runp = NULL;
2714         }
2715       /* The section fulfills all requirements, add it to the output
2716          file with the correct section name etc.  */
2717       else
2718         {
2719           struct scninfo *found = runp;
2720
2721           /* Remove this input section data buffer from the list.  */
2722           if (prevp != runp)
2723             runp = prevp->next = runp->next;
2724           else
2725             {
2726               free (*scnhead);
2727               *scnhead = NULL;
2728               runp = NULL;
2729             }
2730
2731           /* Create a new section for the output file if the 'new_section'
2732              flag says so.  Otherwise append the buffer to the last
2733              section which we created in one of the last calls.  */
2734           if (new_section)
2735             {
2736               struct scnhead *newp;
2737
2738               newp = (struct scnhead *) obstack_calloc (&ld_state.smem,
2739                                                         sizeof (*newp));
2740               newp->kind = scn_normal;
2741               newp->name = osectname;
2742               newp->type = SCNINFO_SHDR (found->shdr).sh_type;
2743               /* Executable or DSO do not have section groups.  Drop that
2744                  information.  */
2745               newp->flags = SCNINFO_SHDR (found->shdr).sh_flags & ~SHF_GROUP;
2746               newp->segment_nr = segment_nr;
2747               newp->last = found->next = found;
2748               newp->used = true;
2749               newp->relsize = found->relsize;
2750               newp->entsize = SCNINFO_SHDR (found->shdr).sh_entsize;
2751
2752               /* We have to count note section since they get their own
2753                  program header entry.  */
2754               if (newp->type == SHT_NOTE)
2755                 ++ld_state.nnotesections;
2756
2757               ld_state.allsections[ld_state.nallsections++] = newp;
2758               new_section = false;
2759             }
2760           else
2761             {
2762               struct scnhead *queued;
2763
2764               queued = ld_state.allsections[ld_state.nallsections - 1];
2765
2766               found->next = queued->last->next;
2767               queued->last = queued->last->next = found;
2768
2769               /* If the linker script forces us to add incompatible
2770                  sections together do so.  But reflect this in the
2771                  type and flags of the resulting file.  */
2772               if (queued->type != SCNINFO_SHDR (found->shdr).sh_type)
2773                 /* XXX Any better choice?  */
2774                 queued->type = SHT_PROGBITS;
2775               if (queued->flags != SCNINFO_SHDR (found->shdr).sh_flags)
2776                 /* Executable or DSO do not have section groups.  Drop that
2777                    information.  */
2778                 queued->flags = ebl_sh_flags_combine (ld_state.ebl,
2779                                                       queued->flags,
2780                                                       SCNINFO_SHDR (found->shdr).sh_flags
2781                                                       & ~SHF_GROUP);
2782
2783               /* Accumulate the relocation section size.  */
2784               queued->relsize += found->relsize;
2785             }
2786         }
2787     }
2788   while (runp != NULL);
2789
2790   return new_section;
2791 }
2792
2793
2794 static void
2795 sort_sections_lscript (void)
2796 {
2797   struct scnhead *temp[ld_state.nallsections];
2798
2799   /* Make a copy of the section head pointer array.  */
2800   memcpy (temp, ld_state.allsections,
2801           ld_state.nallsections * sizeof (temp[0]));
2802   size_t nallsections = ld_state.nallsections;
2803
2804   /* Convert the output segment list in a single-linked list.  */
2805   struct output_segment *segment = ld_state.output_segments->next;
2806   ld_state.output_segments->next = NULL;
2807   ld_state.output_segments = segment;
2808
2809   /* Put the sections in the correct order in the array in the state
2810      structure.  This might involve merging of sections and also
2811      renaming the containing section in the output file.  */
2812   ld_state.nallsections = 0;
2813   size_t segment_nr;
2814   size_t last_writable = ~0ul;
2815   for (segment_nr = 0; segment != NULL; segment = segment->next, ++segment_nr)
2816     {
2817       struct output_rule *orule;
2818
2819       for (orule = segment->output_rules; orule != NULL; orule = orule->next)
2820         if (orule->tag == output_section)
2821           {
2822             struct input_rule *irule;
2823             bool new_section = true;
2824
2825             for (irule = orule->val.section.input; irule != NULL;
2826                  irule = irule->next)
2827               if (irule->tag == input_section)
2828                 {
2829                   size_t cnt;
2830
2831                   for (cnt = 0; cnt < nallsections; ++cnt)
2832                     if (temp[cnt] != NULL)
2833                       new_section =
2834                         match_section (orule->val.section.name,
2835                                        irule->val.section, &temp[cnt],
2836                                        new_section, segment_nr);
2837                 }
2838           }
2839
2840       if ((segment->mode & PF_W) != 0)
2841         last_writable = ld_state.nallsections - 1;
2842     }
2843
2844   /* In case we have to create copy relocations or we have common
2845      symbols, find the last writable segment and add one more data
2846      block.  It will be a NOBITS block and take up no disk space.
2847      This is why it is important to get the last block.  */
2848   if (ld_state.ncopy > 0 || ld_state.common_syms !=  NULL)
2849     {
2850       if (last_writable == ~0ul)
2851         error (EXIT_FAILURE, 0, "no writable segment");
2852
2853       if (ld_state.allsections[last_writable]->type != SHT_NOBITS)
2854         {
2855           /* Make room in the ALLSECTIONS array for a new section.
2856              There is guaranteed room in the array.  We add the new
2857              entry after the last writable section.  */
2858           ++last_writable;
2859           memmove (&ld_state.allsections[last_writable + 1],
2860                    &ld_state.allsections[last_writable],
2861                    (ld_state.nallsections - last_writable)
2862                    * sizeof (ld_state.allsections[0]));
2863
2864           ld_state.allsections[last_writable] = (struct scnhead *)
2865             obstack_calloc (&ld_state.smem, sizeof (struct scnhead));
2866
2867           /* Name for the new section.  */
2868           ld_state.allsections[last_writable]->name = ".bss";
2869           /* Type: NOBITS.  */
2870           ld_state.allsections[last_writable]->type = SHT_NOBITS;
2871           /* Same segment as the last writable section.  */
2872           ld_state.allsections[last_writable]->segment_nr
2873             = ld_state.allsections[last_writable - 1]->segment_nr;
2874         }
2875     }
2876
2877   /* Create common symbol data block.  */
2878   if (ld_state.ncopy > 0)
2879     {
2880 #if NATIVE_ELF
2881       struct scninfo *si = (struct scninfo *)
2882         obstack_calloc (&ld_state.smem, sizeof (*si) + sizeof (XElf_Shdr));
2883       si->shdr = (XElf_Shdr *) (si + 1);
2884 #else
2885       struct scninfo *si = (struct scninfo *) obstack_calloc (&ld_state.smem,
2886                                                               sizeof (*si));
2887 #endif
2888
2889       /* Get the information regarding the symbols with copy relocations.  */
2890       compute_copy_reloc_offset (&SCNINFO_SHDR (si->shdr));
2891
2892       /* This section is needed.  */
2893       si->used = true;
2894       /* Remember for later the section data structure.  */
2895       ld_state.copy_section = si;
2896
2897       if (likely (ld_state.allsections[last_writable]->last != NULL))
2898         {
2899           si->next = ld_state.allsections[last_writable]->last->next;
2900           ld_state.allsections[last_writable]->last->next = si;
2901           ld_state.allsections[last_writable]->last = si;
2902         }
2903       else
2904         ld_state.allsections[last_writable]->last = si->next = si;
2905     }
2906
2907   /* Create common symbol data block.  */
2908   if (ld_state.common_syms != NULL)
2909     {
2910 #if NATIVE_ELF
2911       struct scninfo *si = (struct scninfo *)
2912         obstack_calloc (&ld_state.smem, sizeof (*si) + sizeof (XElf_Shdr));
2913       si->shdr = (XElf_Shdr *) (si + 1);
2914 #else
2915       struct scninfo *si = (struct scninfo *) obstack_calloc (&ld_state.smem,
2916                                                               sizeof (*si));
2917 #endif
2918
2919       /* Get the information regarding the symbols with copy relocations.  */
2920       compute_common_symbol_offset (&SCNINFO_SHDR (si->shdr));
2921
2922       /* This section is needed.  */
2923       si->used = true;
2924       /* Remember for later the section data structure.  */
2925       ld_state.common_section = si;
2926
2927       if (likely (ld_state.allsections[last_writable]->last != NULL))
2928         {
2929           si->next = ld_state.allsections[last_writable]->last->next;
2930           ld_state.allsections[last_writable]->last->next = si;
2931           ld_state.allsections[last_writable]->last = si;
2932         }
2933       else
2934         ld_state.allsections[last_writable]->last = si->next = si;
2935     }
2936 }
2937
2938
2939 /* Create the output sections now.  This requires knowledge about all
2940    the sections we will need.  It may be necessary to sort sections in
2941    the order they are supposed to appear in the executable.  The
2942    sorting use many different kinds of information to optimize the
2943    resulting binary.  Important is to respect segment boundaries and
2944    the needed alignment.  The mode of the segments will be determined
2945    afterwards automatically by the output routines.
2946
2947    The generic sorting routines work in one of two possible ways:
2948
2949    - if a linker script specifies the sections to be used in the
2950      output and assigns them to a segment this information is used;
2951
2952    - otherwise the linker will order the sections based on permissions
2953      and some special knowledge about section names.*/
2954 static void
2955 ld_generic_create_sections (struct ld_state *statep)
2956 {
2957   struct scngroup *groups;
2958   size_t cnt;
2959
2960   /* For relocatable object we don't have to bother sorting the
2961      sections and we do want to preserve the relocation sections as
2962      they appear in the input files.  */
2963   if (ld_state.file_type != relocatable_file_type)
2964     {
2965       /* Collect all the relocation sections.  They are handled
2966          separately.  */
2967       struct scninfo *list = NULL;
2968       for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
2969         if ((ld_state.allsections[cnt]->type == SHT_REL
2970              || ld_state.allsections[cnt]->type == SHT_RELA)
2971             /* The generated relocation sections are not of any
2972                interest here.  */
2973             && ld_state.allsections[cnt]->last != NULL)
2974           {
2975             if (list == NULL)
2976               list = ld_state.allsections[cnt]->last;
2977             else
2978               {
2979                 /* Merge the sections list.  */
2980                 struct scninfo *first = list->next;
2981                 list->next = ld_state.allsections[cnt]->last->next;
2982                 ld_state.allsections[cnt]->last->next = first;
2983                 list = ld_state.allsections[cnt]->last;
2984               }
2985
2986             /* Remove the entry from the section list.  */
2987             ld_state.allsections[cnt] = NULL;
2988           }
2989       ld_state.rellist = list;
2990
2991       if (ld_state.output_segments == NULL)
2992         /* Sort using builtin rules.  */
2993         sort_sections_generic ();
2994       else
2995         sort_sections_lscript ();
2996     }
2997
2998   /* Now iterate over the input sections and create the sections in the
2999      order they are required in the output file.  */
3000   for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
3001     {
3002       struct scnhead *head = ld_state.allsections[cnt];
3003       Elf_Scn *scn;
3004       XElf_Shdr_vardef (shdr);
3005
3006       /* Don't handle unused sections.  */
3007       if (!head->used)
3008         continue;
3009
3010       /* We first have to create the section group if necessary.
3011          Section group sections must come (in section index order)
3012          before any of the section contained.  This all is necessary
3013          only for relocatable object as other object types are not
3014          allowed to contain section groups.  */
3015       if (ld_state.file_type == relocatable_file_type
3016           && unlikely (head->flags & SHF_GROUP))
3017         {
3018           /* There is at least one section which is contained in a
3019              section group in the input file.  This means we must
3020              create a section group here as well.  The only problem is
3021              that not all input files have to have to same kind of
3022              partitioning of the sections.  I.e., sections A and B in
3023              one input file and sections B and C in another input file
3024              can be in one group.  That will result in a group
3025              containing the sections A, B, and C in the output
3026              file.  */
3027           struct scninfo *runp;
3028           Elf32_Word here_groupidx = 0;
3029           struct scngroup *here_group;
3030           struct member *newp;
3031
3032           /* First check whether any section is already in a group.
3033              In this case we have to add this output section, too.  */
3034           runp = head->last;
3035           do
3036             {
3037               assert (runp->grpid != 0);
3038
3039               here_groupidx = runp->fileinfo->scninfo[runp->grpid].outscnndx;
3040               if (here_groupidx != 0)
3041                 break;
3042             }
3043           while ((runp = runp->next) != head->last);
3044
3045           if (here_groupidx == 0)
3046             {
3047               /* We need a new section group section.  */
3048               scn = elf_newscn (ld_state.outelf);
3049               xelf_getshdr (scn, shdr);
3050               if (shdr == NULL)
3051                 error (EXIT_FAILURE, 0,
3052                        gettext ("cannot create section for output file: %s"),
3053                        elf_errmsg (-1));
3054
3055               here_group = (struct scngroup *) xmalloc (sizeof (*here_group));
3056               here_group->outscnidx = here_groupidx = elf_ndxscn (scn);
3057               here_group->nscns = 0;
3058               here_group->member = NULL;
3059               here_group->next = ld_state.groups;
3060               /* Pick a name for the section.  To keep it meaningful
3061                  we use a name used in the input files.  If the
3062                  section group in the output file should contain
3063                  section which were in section groups of different
3064                  names in the input files this is the users
3065                  problem.  */
3066               here_group->nameent
3067                 = ebl_strtabadd (ld_state.shstrtab,
3068                                  elf_strptr (runp->fileinfo->elf,
3069                                              runp->fileinfo->shstrndx,
3070                                              SCNINFO_SHDR (runp->shdr).sh_name),
3071                                  0);
3072               /* Signature symbol.  */
3073               here_group->symbol
3074                 = runp->fileinfo->scninfo[runp->grpid].symbols;
3075
3076               ld_state.groups = here_group;
3077             }
3078           else
3079             {
3080               /* Search for the group with this index.  */
3081               here_group = ld_state.groups;
3082               while (here_group->outscnidx != here_groupidx)
3083                 here_group = here_group->next;
3084             }
3085
3086           /* Add the new output section.  */
3087           newp = (struct member *) alloca (sizeof (*newp));
3088           newp->scn = head;
3089 #ifndef NDT_NEEDED
3090           newp->next = NULL;
3091 #endif
3092           CSNGL_LIST_ADD_REAR (here_group->member, newp);
3093           ++here_group->nscns;
3094
3095           /* Store the section group index in all input files.  */
3096           runp = head->last;
3097           do
3098             {
3099               assert (runp->grpid != 0);
3100
3101               if (runp->fileinfo->scninfo[runp->grpid].outscnndx == 0)
3102                 runp->fileinfo->scninfo[runp->grpid].outscnndx = here_groupidx;
3103               else
3104                 assert (runp->fileinfo->scninfo[runp->grpid].outscnndx
3105                         == here_groupidx);
3106             }
3107           while ((runp = runp->next) != head->last);
3108         }
3109
3110       /* We'll use this section so get it's name in the section header
3111          string table.  */
3112       if (head->kind == scn_normal)
3113         head->nameent = ebl_strtabadd (ld_state.shstrtab, head->name, 0);
3114
3115       /* Create a new section in the output file and add all data
3116          from all the sections we read.  */
3117       scn = elf_newscn (ld_state.outelf);
3118       head->scnidx = elf_ndxscn (scn);
3119       xelf_getshdr (scn, shdr);
3120       if (shdr == NULL)
3121         error (EXIT_FAILURE, 0,
3122                gettext ("cannot create section for output file: %s"),
3123                elf_errmsg (-1));
3124
3125       assert (head->type != SHT_NULL);
3126       assert (head->type != SHT_SYMTAB);
3127       assert (head->type != SHT_DYNSYM || head->kind != scn_normal);
3128       assert (head->type != SHT_STRTAB || head->kind != scn_normal);
3129       assert (head->type != SHT_GROUP);
3130       shdr->sh_type = head->type;
3131       shdr->sh_flags = head->flags;
3132       shdr->sh_addralign = head->align;
3133       shdr->sh_entsize = head->entsize;
3134       assert (shdr->sh_entsize != 0 || (shdr->sh_flags & SHF_MERGE) == 0);
3135       (void) xelf_update_shdr (scn, shdr);
3136
3137       /* We have to know the section index of the dynamic symbol table
3138          right away.  */
3139       if (head->kind == scn_dot_dynsym)
3140         ld_state.dynsymscnidx = elf_ndxscn (scn);
3141     }
3142
3143   /* Actually create the section group sections.  */
3144   groups = ld_state.groups;
3145   while (groups != NULL)
3146     {
3147       Elf_Scn *scn;
3148       Elf_Data *data;
3149       Elf32_Word *grpdata;
3150       struct member *runp;
3151
3152       scn = elf_getscn (ld_state.outelf, groups->outscnidx);
3153       assert (scn != NULL);
3154
3155       data = elf_newdata (scn);
3156       if (data == NULL)
3157         error (EXIT_FAILURE, 0,
3158                gettext ("cannot create section for output file: %s"),
3159                elf_errmsg (-1));
3160
3161       data->d_size = (groups->nscns + 1) * sizeof (Elf32_Word);
3162       data->d_buf = grpdata = (Elf32_Word *) xmalloc (data->d_size);
3163       data->d_type = ELF_T_WORD;
3164       data->d_version = EV_CURRENT;
3165       data->d_off = 0;
3166       /* XXX What better to use?  */
3167       data->d_align = sizeof (Elf32_Word);
3168
3169       /* The first word in the section is the flag word.  */
3170       /* XXX Set COMDATA flag is necessary.  */
3171       grpdata[0] = 0;
3172
3173       runp = groups->member->next;
3174       cnt = 1;
3175       do
3176         /* Fill in the index of the section.  */
3177         grpdata[cnt++] = runp->scn->scnidx;
3178       while ((runp = runp->next) != groups->member->next);
3179
3180       groups = groups->next;
3181     }
3182 }
3183
3184
3185 static bool
3186 reduce_symbol_p (XElf_Sym *sym, struct Ebl_Strent *strent)
3187 {
3188   const char *str;
3189   const char *version;
3190   struct id_list search;
3191   struct id_list *verp;
3192   bool result = ld_state.default_bind_local;
3193
3194   if (XELF_ST_BIND (sym->st_info) == STB_LOCAL || sym->st_shndx == SHN_UNDEF)
3195     /* We don't have to do anything to local symbols here.  */
3196     /* XXX Any section value in [SHN_LORESERVER,SHN_XINDEX) need
3197        special treatment?  */
3198     return false;
3199
3200   /* XXX Handle other symbol bindings.  */
3201   assert (XELF_ST_BIND (sym->st_info) == STB_GLOBAL
3202           || XELF_ST_BIND (sym->st_info) == STB_WEAK);
3203
3204   str = ebl_string (strent);
3205   version = strchr (str, VER_CHR);
3206   if (version != NULL)
3207     {
3208       search.id = strndupa (str, version - str);
3209       if (*++version == VER_CHR)
3210         /* Skip the second '@' signalling a default definition.  */
3211         ++version;
3212     }
3213   else
3214     {
3215       search.id = str;
3216       version = "";
3217     }
3218
3219   verp = ld_version_str_tab_find (&ld_state.version_str_tab,
3220                                   elf_hash (search.id), &search);
3221   while (verp != NULL)
3222     {
3223       /* We have this symbol in the version hash table.  Now match the
3224          version name.  */
3225       if (strcmp (verp->u.s.versionname, version) == 0)
3226         /* Match!  */
3227         return verp->u.s.local;
3228
3229       verp = verp->next;
3230     }
3231
3232   /* XXX Add test for wildcard version symbols.  */
3233
3234   return result;
3235 }
3236
3237
3238 static XElf_Addr
3239 eval_expression (struct expression *expr, XElf_Addr addr)
3240 {
3241   XElf_Addr val = ~((XElf_Addr) 0);
3242
3243   switch (expr->tag)
3244     {
3245     case exp_num:
3246       val = expr->val.num;
3247       break;
3248
3249     case exp_sizeof_headers:
3250       {
3251         /* The 'elf_update' call determine the offset of the first
3252            section.  The the size of the header.  */
3253         XElf_Shdr_vardef (shdr);
3254
3255         xelf_getshdr (elf_getscn (ld_state.outelf, 1), shdr);
3256         assert (shdr != NULL);
3257
3258         val = shdr->sh_offset;
3259       }
3260       break;
3261
3262     case exp_pagesize:
3263       val = ld_state.pagesize;
3264       break;
3265
3266     case exp_id:
3267       /* We are here computing only address expressions.  It seems not
3268          to be necessary to handle any variable but ".".  Let's avoid
3269          the complication.  If it turns up to be needed we can add
3270          it.  */
3271       if (strcmp (expr->val.str, ".") != 0)
3272         error (EXIT_FAILURE, 0, gettext ("\
3273 address computation expression contains variable '%s'"),
3274                expr->val.str);
3275
3276       val = addr;
3277       break;
3278
3279     case exp_mult:
3280       val = (eval_expression (expr->val.binary.left, addr)
3281              * eval_expression (expr->val.binary.right, addr));
3282       break;
3283
3284     case exp_div:
3285       val = (eval_expression (expr->val.binary.left, addr)
3286              / eval_expression (expr->val.binary.right, addr));
3287       break;
3288
3289     case exp_mod:
3290       val = (eval_expression (expr->val.binary.left, addr)
3291              % eval_expression (expr->val.binary.right, addr));
3292       break;
3293
3294     case exp_plus:
3295       val = (eval_expression (expr->val.binary.left, addr)
3296              + eval_expression (expr->val.binary.right, addr));
3297       break;
3298
3299     case exp_minus:
3300       val = (eval_expression (expr->val.binary.left, addr)
3301              - eval_expression (expr->val.binary.right, addr));
3302       break;
3303
3304     case exp_and:
3305       val = (eval_expression (expr->val.binary.left, addr)
3306              & eval_expression (expr->val.binary.right, addr));
3307       break;
3308
3309     case exp_or:
3310       val = (eval_expression (expr->val.binary.left, addr)
3311              | eval_expression (expr->val.binary.right, addr));
3312       break;
3313
3314     case exp_align:
3315       val = eval_expression (expr->val.child, addr);
3316       if ((val & (val - 1)) != 0)
3317         error (EXIT_FAILURE, 0, gettext ("argument '%" PRIuMAX "' of ALIGN in address computation expression is no power of two"),
3318                (uintmax_t) val);
3319       val = (addr + val - 1) & ~(val - 1);
3320       break;
3321     }
3322
3323   return val;
3324 }
3325
3326
3327 /* Find a good as possible size for the hash table so that all the
3328    non-zero entries in HASHCODES don't collide too much and the table
3329    isn't too large.  There is no exact formular for this so we use a
3330    heuristic.  Depending on the optimization level the search is
3331    longer or shorter.  */
3332 static size_t
3333 optimal_bucket_size (Elf32_Word *hashcodes, size_t maxcnt, int optlevel)
3334 {
3335   size_t minsize;
3336   size_t maxsize;
3337   size_t bestsize;
3338   uint64_t bestcost;
3339   size_t size;
3340   uint32_t *counts;
3341   uint32_t *lengths;
3342
3343   if (maxcnt == 0)
3344     return 0;
3345
3346   /* When we are not optimizing we run only very few tests.  */
3347   if (optlevel <= 0)
3348     {
3349       minsize = maxcnt;
3350       maxsize = maxcnt + 10000 / maxcnt;
3351     }
3352   else
3353     {
3354       /* Does not make much sense to start with a smaller table than
3355          one which has at least four collisions.  */
3356       minsize = MAX (1, maxcnt / 4);
3357       /* We look for a best fit in the range of up to eigth times the
3358          number of elements.  */
3359       maxsize = 2 * maxcnt + (6 * MIN (optlevel, 100) * maxcnt) / 100;
3360     }
3361   bestsize = maxcnt;
3362   bestcost = UINT_MAX;
3363
3364   /* Array for counting the collisions and chain lengths.  */
3365   counts = (uint32_t *) xmalloc ((maxcnt + 1 + maxsize) * sizeof (uint32_t));
3366   lengths = &counts[maxcnt + 1];
3367
3368   for (size = minsize; size <= maxsize; ++size)
3369     {
3370       size_t inner;
3371       uint64_t cost;
3372       uint32_t maxlength;
3373       uint64_t success;
3374       uint32_t acc;
3375       double factor;
3376
3377       memset (lengths, '\0', size * sizeof (uint32_t));
3378       memset (counts, '\0', (maxcnt + 1) * sizeof (uint32_t));
3379
3380       /* Determine how often each hash bucket is used.  */
3381       for (inner = 0; inner < maxcnt; ++inner)
3382         ++lengths[hashcodes[inner] % size];
3383
3384       /* Determine the lengths.  */
3385       maxlength = 0;
3386       for (inner = 0; inner < size; ++inner)
3387         {
3388           ++counts[lengths[inner]];
3389
3390           if (lengths[inner] > maxlength)
3391             maxlength = lengths[inner];
3392         }
3393
3394       /* Determine successful lookup length.  */
3395       acc = 0;
3396       success = 0;
3397       for (inner = 0; inner <= maxlength; ++inner)
3398         {
3399           acc += inner;
3400           success += counts[inner] * acc;
3401         }
3402
3403       /* We can compute two factors now: the average length of a
3404          positive search and the average length of a negative search.
3405          We count the number of comparisons which have to look at the
3406          names themselves.  Recognizing that the chain ended is not
3407          accounted for since it's almost for free.
3408
3409          Which lookup is more important depends on the kind of DSO.
3410          If it is a system DSO like libc it is expected that most
3411          lookups succeed.  Otherwise most lookups fail.  */
3412       if (ld_state.is_system_library)
3413         factor = (1.0 * (double) success / (double) maxcnt
3414                   + 0.3 * (double) maxcnt / (double) size);
3415       else
3416         factor = (0.3 * (double) success / (double) maxcnt
3417                   + 1.0 * (double) maxcnt / (double) size);
3418
3419       /* Combine the lookup cost factor.  The 1/16th addend adds
3420          penalties for too large table sizes.  */
3421       cost = (2 + maxcnt + size) * (factor + 1.0 / 16.0);
3422
3423 #if 0
3424       printf ("maxcnt = %d, size = %d, cost = %Ld, success = %g, fail = %g, factor = %g\n",
3425               maxcnt, size, cost, (double) success / (double) maxcnt, (double) maxcnt / (double) size, factor);
3426 #endif
3427
3428       /* Compare with current best results.  */
3429       if (cost < bestcost)
3430         {
3431           bestcost = cost;
3432           bestsize = size;
3433         }
3434     }
3435
3436   free (counts);
3437
3438   return bestsize;
3439 }
3440
3441
3442 static XElf_Addr
3443 find_entry_point (void)
3444 {
3445   XElf_Addr result;
3446
3447   if (ld_state.entry != NULL)
3448     {
3449       struct symbol search = { .name = ld_state.entry };
3450       struct symbol *syment;
3451
3452       syment = ld_symbol_tab_find (&ld_state.symbol_tab,
3453                                    elf_hash (ld_state.entry), &search);
3454       if (syment != NULL && syment->defined)
3455         {
3456           /* We found the symbol.  */
3457           Elf_Data *data = elf_getdata (elf_getscn (ld_state.outelf,
3458                                                     ld_state.symscnidx), NULL);
3459
3460           XElf_Sym_vardef (sym);
3461
3462           sym = NULL;
3463           if (data != NULL)
3464             xelf_getsym (data, ld_state.dblindirect[syment->outsymidx], sym);
3465
3466           if (sym == NULL && ld_state.need_dynsym && syment->outdynsymidx != 0)
3467             {
3468               /* Use the dynamic symbol table if available.  */
3469               data = elf_getdata (elf_getscn (ld_state.outelf,
3470                                               ld_state.dynsymscnidx), NULL);
3471
3472               sym = NULL;
3473               if (data != NULL)
3474                 xelf_getsym (data, syment->outdynsymidx, sym);
3475             }
3476
3477           if (sym != NULL)
3478             return sym->st_value;
3479
3480           /* XXX What to do if the output has no non-dynamic symbol
3481              table and the dynamic symbol table does not contain the
3482              symbol?  */
3483           assert (ld_state.need_symtab);
3484           assert (ld_state.symscnidx != 0);
3485         }
3486     }
3487
3488   /* We couldn't find the symbol or none was given.  Use the first
3489      address of the ".text" section then.  */
3490
3491
3492   result = 0;
3493
3494   /* In DSOs this is no fatal error.  They usually have no entry
3495      points.  In this case we set the entry point to zero, which makes
3496      sure it will always fail.  */
3497   if (ld_state.file_type == executable_file_type)
3498     {
3499       if (ld_state.entry != NULL)
3500         error (0, 0, gettext ("\
3501 cannot find entry symbol '%s': defaulting to %#0*" PRIx64),
3502                ld_state.entry,
3503                xelf_getclass (ld_state.outelf) == ELFCLASS32 ? 10 : 18,
3504                (uint64_t) result);
3505       else
3506         error (0, 0, gettext ("\
3507 no entry symbol specified: defaulting to %#0*" PRIx64),
3508                xelf_getclass (ld_state.outelf) == ELFCLASS32 ? 10 : 18,
3509                (uint64_t) result);
3510     }
3511
3512   return result;
3513 }
3514
3515
3516 static void
3517 fillin_special_symbol (struct symbol *symst, size_t scnidx, size_t nsym,
3518                        Elf_Data *symdata, struct Ebl_Strtab *strtab)
3519 {
3520   assert (ld_state.file_type != relocatable_file_type);
3521
3522   XElf_Sym_vardef (sym);
3523   xelf_getsym_ptr (symdata, nsym, sym);
3524
3525   /* The name offset will be filled in later.  */
3526   sym->st_name = 0;
3527   /* Traditionally: globally visible.  */
3528   sym->st_info = XELF_ST_INFO (STB_GLOBAL, symst->type);
3529   /* No special visibility or so.  */
3530   sym->st_other = 0;
3531   /* Reference to the GOT or dynamic section.  Since the GOT and
3532      dynamic section are only created for executables and DSOs it
3533      cannot be that the section index is too large.  */
3534   assert (scnidx != 0);
3535   assert (scnidx < SHN_LORESERVE || scnidx == SHN_ABS);
3536   sym->st_shndx = scnidx;
3537   /* We want the beginning of the section.  */
3538   sym->st_value = 0;
3539
3540   /* Determine the size of the section.  */
3541   if (scnidx != SHN_ABS)
3542     {
3543       Elf_Data *data = elf_getdata (elf_getscn (ld_state.outelf, scnidx),
3544                                     NULL);
3545       assert (data != NULL);
3546       sym->st_size = data->d_size;
3547       /* Make sure there is no second data block.  */
3548       assert (elf_getdata (elf_getscn (ld_state.outelf, scnidx), data)
3549               == NULL);
3550     }
3551
3552   /* Insert symbol into the symbol table.  Note that we do not have to
3553      use xelf_update_symshdx.  */
3554   (void) xelf_update_sym (symdata, nsym, sym);
3555
3556   /* Cross-references.  */
3557   ndxtosym[nsym] = symst;
3558   symst->outsymidx = nsym;
3559
3560   /* Add the name to the string table.  */
3561   symstrent[nsym] = ebl_strtabadd (strtab, symst->name, 0);
3562 }
3563
3564
3565 static void
3566 new_dynamic_entry (Elf_Data *data, int idx, XElf_Sxword tag, XElf_Addr val)
3567 {
3568   XElf_Dyn_vardef (dyn);
3569   xelf_getdyn_ptr (data, idx, dyn);
3570   dyn->d_tag = tag;
3571   dyn->d_un.d_ptr = val;
3572   (void) xelf_update_dyn (data, idx, dyn);
3573 }
3574
3575
3576 static void
3577 allocate_version_names (struct usedfiles *runp, struct Ebl_Strtab *dynstrtab)
3578 {
3579   /* If this DSO has no versions skip it.  */
3580   if (runp->status != opened || runp->verdefdata == NULL)
3581     return;
3582
3583   /* Add the object name.  */
3584   int offset = 0;
3585   while (1)
3586     {
3587       XElf_Verdef_vardef (def);
3588       XElf_Verdaux_vardef (aux);
3589
3590       /* Get data at the next offset.  */
3591       xelf_getverdef (runp->verdefdata, offset, def);
3592       assert (def != NULL);
3593       xelf_getverdaux (runp->verdefdata, offset + def->vd_aux, aux);
3594       assert (aux != NULL);
3595
3596       assert (def->vd_ndx <= runp->nverdef);
3597       if (def->vd_ndx == 1 || runp->verdefused[def->vd_ndx] != 0)
3598         {
3599           runp->verdefent[def->vd_ndx]
3600             = ebl_strtabadd (dynstrtab, elf_strptr (runp->elf,
3601                                                     runp->dynsymstridx,
3602                                                     aux->vda_name), 0);
3603
3604           if (def->vd_ndx > 1)
3605             runp->verdefused[def->vd_ndx] = ld_state.nextveridx++;
3606         }
3607
3608       if (def->vd_next == 0)
3609         /* That were all versions.  */
3610         break;
3611
3612       offset += def->vd_next;
3613     }
3614 }
3615
3616
3617 XElf_Off
3618 create_verneed_data (XElf_Off offset, Elf_Data *verneeddata,
3619                      struct usedfiles *runp, int *ntotal)
3620 {
3621           size_t verneed_size = xelf_fsize (ld_state.outelf, ELF_T_VNEED, 1);
3622           size_t vernaux_size = xelf_fsize (ld_state.outelf, ELF_T_VNAUX, 1);
3623               int need_offset;
3624               bool filled = false;
3625               GElf_Verneed verneed;
3626               GElf_Vernaux vernaux;
3627               int ndef = 0;
3628 size_t cnt;
3629
3630               /* If this DSO has no versions skip it.  */
3631               if (runp->nverdefused == 0)
3632                 return offset;
3633
3634               /* We fill in the Verneed record last.  Remember the
3635                  offset.  */
3636               need_offset = offset;
3637               offset += verneed_size;
3638
3639               for (cnt = 2; cnt <= runp->nverdef; ++cnt)
3640                 if (runp->verdefused[cnt] != 0)
3641                   {
3642                     assert (runp->verdefent[cnt] != NULL);
3643
3644                     if (filled)
3645                       {
3646                         vernaux.vna_next = vernaux_size;
3647                         (void) gelf_update_vernaux (verneeddata, offset,
3648                                                     &vernaux);
3649                         offset += vernaux_size;
3650                       }
3651
3652                     vernaux.vna_hash
3653                       = elf_hash (ebl_string (runp->verdefent[cnt]));
3654                     vernaux.vna_flags = 0;
3655                     vernaux.vna_other = runp->verdefused[cnt];
3656                     vernaux.vna_name = ebl_strtaboffset (runp->verdefent[cnt]);
3657                     filled = true;
3658                     ++ndef;
3659                   }
3660
3661               assert (filled);
3662               vernaux.vna_next = 0;
3663               (void) gelf_update_vernaux (verneeddata, offset, &vernaux);
3664               offset += vernaux_size;
3665
3666               verneed.vn_version = VER_NEED_CURRENT;
3667               verneed.vn_cnt = ndef;
3668               verneed.vn_file = ebl_strtaboffset (runp->verdefent[1]);
3669               /* The first auxiliary entry is always found directly
3670                  after the verneed entry.  */
3671               verneed.vn_aux = verneed_size;
3672               verneed.vn_next = --*ntotal > 0 ? offset - need_offset : 0;
3673               (void) gelf_update_verneed (verneeddata, need_offset,
3674                                           &verneed);
3675
3676               return offset;
3677 }
3678
3679
3680 /* Create the output file.
3681
3682    For relocatable files what basically has to happen is that all
3683    sections from all input files are written into the output file.
3684    Sections with the same name are combined (offsets adjusted
3685    accordingly).  The symbol tables are combined in one single table.
3686    When stripping certain symbol table entries are omitted.
3687
3688    For executables (shared or not) we have to create the program header,
3689    additional sections like the .interp, eventually (in addition) create
3690    a dynamic symbol table and a dynamic section.  Also the relocations
3691 have to be processed differently.  */
3692 static int
3693 ld_generic_create_outfile (struct ld_state *statep)
3694 {
3695   struct scnlist
3696   {
3697     size_t scnidx;
3698     struct scninfo *scninfo;
3699     struct scnlist *next;
3700   };
3701   struct scnlist *rellist = NULL;
3702   size_t cnt;
3703   Elf_Scn *symscn = NULL;
3704   Elf_Scn *xndxscn = NULL;
3705   Elf_Scn *strscn = NULL;
3706   struct Ebl_Strtab *strtab = NULL;
3707   struct Ebl_Strtab *dynstrtab = NULL;
3708   XElf_Shdr_vardef (shdr);
3709   Elf_Data *data;
3710   Elf_Data *symdata = NULL;
3711   Elf_Data *xndxdata = NULL;
3712   struct usedfiles *file;
3713   size_t nsym;
3714   size_t nsym_local;
3715   size_t nsym_allocated;
3716   size_t nsym_dyn = 0;
3717   Elf32_Word *dblindirect = NULL;
3718 #ifndef NDEBUG
3719   bool need_xndx;
3720 #endif
3721   Elf_Scn *shstrtab_scn;
3722   size_t shstrtab_ndx;
3723   XElf_Ehdr_vardef (ehdr);
3724   struct Ebl_Strent *symtab_ent = NULL;
3725   struct Ebl_Strent *xndx_ent = NULL;
3726   struct Ebl_Strent *strtab_ent = NULL;
3727   struct Ebl_Strent *shstrtab_ent;
3728   struct scngroup *groups;
3729   Elf_Scn *dynsymscn = NULL;
3730   Elf_Data *dynsymdata = NULL;
3731   Elf_Data *dynstrdata = NULL;
3732   Elf32_Word *hashcodes = NULL;
3733   size_t nsym_dyn_allocated = 0;
3734   Elf_Scn *versymscn = NULL;
3735   Elf_Data *versymdata = NULL;
3736
3737   if (ld_state.need_symtab)
3738     {
3739       /* First create the symbol table.  We need the symbol section itself
3740          and the string table for it.  */
3741       symscn = elf_newscn (ld_state.outelf);
3742       ld_state.symscnidx = elf_ndxscn (symscn);
3743       symdata = elf_newdata (symscn);
3744       if (symdata == NULL)
3745         error (EXIT_FAILURE, 0,
3746                gettext ("cannot create symbol table for output file: %s"),
3747                elf_errmsg (-1));
3748
3749       symdata->d_type = ELF_T_SYM;
3750       /* This is an estimated size, but it will definitely cap the real value.
3751          We might have to adjust the number later.  */
3752       nsym_allocated = (1 + ld_state.nsymtab + ld_state.nplt + ld_state.ngot
3753                         + ld_state.nusedsections + ld_state.nlscript_syms);
3754       symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
3755                                     nsym_allocated);
3756
3757       /* Optionally the extended section table.  */
3758       /* XXX Is SHN_LORESERVE correct?  Do we need some other sections?  */
3759       if (unlikely (ld_state.nusedsections >= SHN_LORESERVE))
3760         {
3761           xndxscn = elf_newscn (ld_state.outelf);
3762           ld_state.xndxscnidx = elf_ndxscn (xndxscn);
3763
3764           xndxdata = elf_newdata (xndxscn);
3765           if (xndxdata == NULL)
3766             error (EXIT_FAILURE, 0,
3767                    gettext ("cannot create symbol table for output file: %s"),
3768                    elf_errmsg (-1));
3769
3770           /* The following relies on the fact that Elf32_Word and Elf64_Word
3771              have the same size.  */
3772           xndxdata->d_type = ELF_T_WORD;
3773           /* This is an estimated size, but it will definitely cap the
3774              real value.  we might have to adjust the number later.  */
3775           xndxdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_WORD,
3776                                          nsym_allocated);
3777           /* The first entry is left empty, clear it here and now.  */
3778           xndxdata->d_buf = memset (xmalloc (xndxdata->d_size), '\0',
3779                                     xelf_fsize (ld_state.outelf, ELF_T_WORD,
3780                                                 1));
3781           xndxdata->d_off = 0;
3782           /* XXX Should use an ebl function.  */
3783           xndxdata->d_align = sizeof (Elf32_Word);
3784         }
3785     }
3786   else
3787     {
3788       assert (ld_state.need_dynsym);
3789
3790       /* First create the symbol table.  We need the symbol section itself
3791          and the string table for it.  */
3792       symscn = elf_getscn (ld_state.outelf, ld_state.dynsymscnidx);
3793       symdata = elf_newdata (symscn);
3794       if (symdata == NULL)
3795         error (EXIT_FAILURE, 0,
3796                gettext ("cannot create symbol table for output file: %s"),
3797                elf_errmsg (-1));
3798
3799       symdata->d_version = EV_CURRENT;
3800       symdata->d_type = ELF_T_SYM;
3801       /* This is an estimated size, but it will definitely cap the real value.
3802          We might have to adjust the number later.  */
3803       nsym_allocated = (1 + ld_state.nsymtab + ld_state.nplt + ld_state.ngot
3804                         - ld_state.nlocalsymbols + ld_state.nlscript_syms);
3805       symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
3806                                     nsym_allocated);
3807     }
3808
3809   /* The first entry is left empty, clear it here and now.  */
3810   symdata->d_buf = memset (xmalloc (symdata->d_size), '\0',
3811                            xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
3812   symdata->d_off = 0;
3813   /* XXX This is ugly but how else can it be done.  */
3814   symdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
3815
3816   /* Allocate another array to keep track of the handles for the symbol
3817      names.  */
3818   symstrent = (struct Ebl_Strent **) xcalloc (nsym_allocated,
3819                                               sizeof (struct Ebl_Strent *));
3820
3821   /* By starting at 1 we effectively add a null entry.  */
3822   nsym = 1;
3823
3824   /* Iteration over all sections.  */
3825   for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
3826     {
3827       struct scnhead *head = ld_state.allsections[cnt];
3828       Elf_Scn *scn;
3829       struct scninfo *runp;
3830       XElf_Off offset;
3831       Elf32_Word xndx;
3832
3833       /* Don't handle unused sections at all.  */
3834       if (!head->used)
3835         continue;
3836
3837       /* Get the section handle.  */
3838       scn = elf_getscn (ld_state.outelf, head->scnidx);
3839
3840       if (unlikely (head->kind == scn_dot_interp))
3841         {
3842           Elf_Data *outdata = elf_newdata (scn);
3843           if (outdata == NULL)
3844             error (EXIT_FAILURE, 0,
3845                    gettext ("cannot create section for output file: %s"),
3846                    elf_errmsg (-1));
3847
3848           /* This is the string we'll put in the section.  */
3849           const char *interp = ld_state.interp ?: "/lib/ld.so.1";
3850
3851           /* Create the section data.  */
3852           outdata->d_buf = (void *) interp;
3853           outdata->d_size = strlen (interp) + 1;
3854           outdata->d_type = ELF_T_BYTE;
3855           outdata->d_off = 0;
3856           outdata->d_align = 1;
3857           outdata->d_version = EV_CURRENT;
3858
3859           /* Remember the index of this section.  */
3860           ld_state.interpscnidx = head->scnidx;
3861
3862           continue;
3863         }
3864
3865       if (unlikely (head->kind == scn_dot_got))
3866         {
3867           /* Remember the index of this section.  */
3868           ld_state.gotscnidx = elf_ndxscn (scn);
3869
3870           /* Give the backend the change to initialize the section.  */
3871           INITIALIZE_GOT (&ld_state, scn);
3872
3873           continue;
3874         }
3875
3876       if (unlikely (head->kind == scn_dot_dynrel))
3877         {
3878           Elf_Data *outdata;
3879
3880           outdata = elf_newdata (scn);
3881           if (outdata == NULL)
3882             error (EXIT_FAILURE, 0,
3883                    gettext ("cannot create section for output file: %s"),
3884                    elf_errmsg (-1));
3885
3886           outdata->d_size = ld_state.relsize_total;
3887           outdata->d_buf = xmalloc (outdata->d_size);
3888           outdata->d_type = (REL_TYPE (&ld_state) == DT_REL
3889                              ? ELF_T_REL : ELF_T_RELA);
3890           outdata->d_off = 0;
3891           outdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
3892
3893           /* Remember the index of this section.  */
3894           ld_state.reldynscnidx = elf_ndxscn (scn);
3895
3896           continue;
3897         }
3898
3899       if (unlikely (head->kind == scn_dot_dynamic))
3900         {
3901           /* Only create the data for now.  */
3902           Elf_Data *outdata;
3903
3904           /* Account for a few more entries we have to add.  */
3905           if (ld_state.dt_flags != 0)
3906             ++ld_state.ndynamic;
3907           if (ld_state.dt_flags_1 != 0)
3908             ++ld_state.ndynamic;
3909           if (ld_state.dt_feature_1 != 0)
3910             ++ld_state.ndynamic;
3911
3912           outdata = elf_newdata (scn);
3913           if (outdata == NULL)
3914             error (EXIT_FAILURE, 0,
3915                    gettext ("cannot create section for output file: %s"),
3916                    elf_errmsg (-1));
3917
3918           /* Create the section data.  */
3919           outdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_DYN,
3920                                         ld_state.ndynamic);
3921           outdata->d_buf = xcalloc (1, outdata->d_size);
3922           outdata->d_type = ELF_T_DYN;
3923           outdata->d_off = 0;
3924           outdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
3925
3926           /* Remember the index of this section.  */
3927           ld_state.dynamicscnidx = elf_ndxscn (scn);
3928
3929           continue;
3930         }
3931
3932       if (unlikely (head->kind == scn_dot_dynsym))
3933         {
3934           /* We already know the section index.  */
3935           assert (ld_state.dynsymscnidx == elf_ndxscn (scn));
3936
3937           continue;
3938         }
3939
3940       if (unlikely (head->kind == scn_dot_dynstr))
3941         {
3942           /* Remember the index of this section.  */
3943           ld_state.dynstrscnidx = elf_ndxscn (scn);
3944
3945           /* Create the string table.  */
3946           dynstrtab = ebl_strtabinit (true);
3947
3948           /* XXX TBI
3949              We have to add all the strings which are needed in the
3950              dynamic section here.  This means DT_FILTER,
3951              DT_AUXILIARY, ... entries.  */
3952           if (ld_state.ndsofiles > 0)
3953             {
3954               struct usedfiles *frunp = ld_state.dsofiles;
3955
3956               do
3957                 if (! frunp->as_needed || frunp->used)
3958                   frunp->sonameent = ebl_strtabadd (dynstrtab, frunp->soname,
3959                                                     0);
3960               while ((frunp = frunp->next) != ld_state.dsofiles);
3961             }
3962
3963
3964           /* Add the runtime path information.  The strings are stored
3965              in the .dynstr section.  If both rpath and runpath are defined
3966              the runpath information is used.  */
3967           if (ld_state.runpath != NULL || ld_state.rpath != NULL)
3968             {
3969               struct pathelement *startp;
3970               struct pathelement *prunp;
3971               int tag;
3972               size_t len;
3973               char *str;
3974               char *cp;
3975
3976               if (ld_state.runpath != NULL)
3977                 {
3978                   startp = ld_state.runpath;
3979                   tag = DT_RUNPATH;
3980                 }
3981               else
3982                 {
3983                   startp = ld_state.rpath;
3984                   tag = DT_RPATH;
3985                 }
3986
3987               /* Determine how long the string will be.  */
3988               for (len = 0, prunp = startp; prunp != NULL; prunp = prunp->next)
3989                 len += strlen (prunp->pname) + 1;
3990
3991               cp = str = (char *) obstack_alloc (&ld_state.smem, len);
3992               /* Copy the string.  */
3993               for (prunp = startp; prunp != NULL; prunp = prunp->next)
3994                 {
3995                   cp = stpcpy (cp, prunp->pname);
3996                   *cp++ = ':';
3997                 }
3998               /* Remove the last colon.  */
3999               cp[-1] = '\0';
4000
4001               /* Remember the values until we can generate the dynamic
4002                  section.  */
4003               ld_state.rxxpath_strent = ebl_strtabadd (dynstrtab, str, len);
4004               ld_state.rxxpath_tag = tag;
4005             }
4006
4007           continue;
4008         }
4009
4010       if (unlikely (head->kind == scn_dot_hash))
4011         {
4012           /* Remember the index of this section.  */
4013           ld_state.hashscnidx = elf_ndxscn (scn);
4014
4015           continue;
4016         }
4017
4018       if (unlikely (head->kind == scn_dot_plt))
4019         {
4020           /* Remember the index of this section.  */
4021           ld_state.pltscnidx = elf_ndxscn (scn);
4022
4023           /* Give the backend the change to initialize the section.  */
4024           INITIALIZE_PLT (&ld_state, scn);
4025
4026           continue;
4027         }
4028
4029       if (unlikely (head->kind == scn_dot_pltrel))
4030         {
4031           /* Remember the index of this section.  */
4032           ld_state.pltrelscnidx = elf_ndxscn (scn);
4033
4034           /* Give the backend the change to initialize the section.  */
4035           INITIALIZE_PLTREL (&ld_state, scn);
4036
4037           continue;
4038         }
4039
4040       if (unlikely (head->kind == scn_dot_version))
4041         {
4042           /* Remember the index of this section.  */
4043           ld_state.versymscnidx = elf_ndxscn (scn);
4044
4045           continue;
4046         }
4047
4048       if (unlikely (head->kind == scn_dot_version_r))
4049         {
4050           /* Remember the index of this section.  */
4051           ld_state.verneedscnidx = elf_ndxscn (scn);
4052
4053           continue;
4054         }
4055
4056       /* If we come here we must be handling a normal section.  */
4057       assert (head->kind == scn_normal);
4058
4059       /* Create an STT_SECTION entry in the symbol table.  But not for
4060          the symbolic symbol table.  */
4061       if (ld_state.need_symtab)
4062         {
4063           /* XXX Can we be cleverer and do this only if needed?  */
4064           XElf_Sym_vardef (sym);
4065
4066           /* Optimization ahead: in the native linker we get a pointer
4067              to the final location so that the following code writes
4068              directly in the correct place.  Otherwise we write into
4069              the local variable first.  */
4070           xelf_getsym_ptr (symdata, nsym, sym);
4071
4072           /* Usual section symbol: local, no specific information,
4073              except the section index.  The offset here is zero, the
4074              start address will later be added.  */
4075           sym->st_name = 0;
4076           sym->st_info = XELF_ST_INFO (STB_LOCAL, STT_SECTION);
4077           sym->st_other = 0;
4078           sym->st_value = 0;
4079           sym->st_size = 0;
4080           /* In relocatable files the section index can be too big for
4081              the ElfXX_Sym struct.  we have to deal with the extended
4082              symbol table.  */
4083           if (likely (head->scnidx < SHN_LORESERVE))
4084             {
4085               sym->st_shndx = head->scnidx;
4086               xndx = 0;
4087             }
4088           else
4089             {
4090               sym->st_shndx = SHN_XINDEX;
4091               xndx = head->scnidx;
4092             }
4093           /* Commit the change.  See the optimization above, this does
4094              not change the symbol table entry.  But the extended
4095              section index table entry is always written, if there is
4096              such a table.  */
4097           assert (nsym < nsym_allocated);
4098           xelf_update_symshndx (symdata, xndxdata, nsym, sym, xndx, 0);
4099
4100           /* Remember the symbol's index in the symbol table.  */
4101           head->scnsymidx = nsym++;
4102         }
4103
4104       if (head->type == SHT_REL || head->type == SHT_RELA)
4105         {
4106           /* Remember that we have to fill in the symbol table section
4107              index.  */
4108           if (ld_state.file_type == relocatable_file_type)
4109             {
4110               struct scnlist *newp;
4111
4112               newp = (struct scnlist *) alloca (sizeof (*newp));
4113               newp->scnidx = head->scnidx;
4114               newp->scninfo = head->last->next;
4115 #ifndef NDEBUG
4116               newp->next = NULL;
4117 #endif
4118               SNGL_LIST_PUSH (rellist, newp);
4119             }
4120           else
4121             {
4122               /* When we create an executable or a DSO we don't simply
4123                  copy the existing relocations.  Instead many will be
4124                  resolved, others will be converted.  Create a data buffer
4125                  large enough to contain the contents which we will fill
4126                  in later.  */
4127               int type = head->type == SHT_REL ? ELF_T_REL : ELF_T_RELA;
4128
4129               data = elf_newdata (scn);
4130               if (data == NULL)
4131                 error (EXIT_FAILURE, 0,
4132                        gettext ("cannot create section for output file: %s"),
4133                        elf_errmsg (-1));
4134
4135               data->d_size = xelf_fsize (ld_state.outelf, type, head->relsize);
4136               data->d_buf = xcalloc (data->d_size, 1);
4137               data->d_type = type;
4138               data->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
4139               data->d_off = 0;
4140
4141               continue;
4142             }
4143         }
4144
4145       /* Recognize string and merge flag and handle them.  */
4146       if (head->flags & SHF_MERGE)
4147         {
4148           /* We merge the contents of the sections.  For this we do
4149              not look at the contents of section directly.  Instead we
4150              look at the symbols of the section.  */
4151           Elf_Data *outdata;
4152
4153           /* Concatenate the lists of symbols for all sections.
4154
4155              XXX In case any input section has no symbols associated
4156              (this happens for debug sections) we cannot use this
4157              method.  Implement parsing the other debug sections and
4158              find the string pointers.  For now we don't merge.  */
4159           runp = head->last->next;
4160           if (runp->symbols == NULL)
4161             {
4162               head->flags &= ~SHF_MERGE;
4163               goto no_merge;
4164             }
4165           head->symbols = runp->symbols;
4166
4167           while ((runp = runp->next) != head->last->next)
4168             {
4169               if (runp->symbols == NULL)
4170                 {
4171                   head->flags &= ~SHF_MERGE;
4172                   head->symbols = NULL;
4173                   goto no_merge;
4174                 }
4175
4176               struct symbol *oldhead = head->symbols->next_in_scn;
4177
4178               head->symbols->next_in_scn = runp->symbols->next_in_scn;
4179               runp->symbols->next_in_scn = oldhead;
4180               head->symbols = runp->symbols;
4181             }
4182
4183           /* Create the output section.  */
4184           outdata = elf_newdata (scn);
4185           if (outdata == NULL)
4186             error (EXIT_FAILURE, 0,
4187                    gettext ("cannot create section for output file: %s"),
4188                    elf_errmsg (-1));
4189
4190           /* We use different merging algorithms for performance
4191              reasons.  We can easily handle single-byte and
4192              wchar_t-wide character strings.  All other cases (which
4193              really should happen in real life) are handled by the
4194              generic code.  */
4195           if (SCNINFO_SHDR (head->last->shdr).sh_entsize == 1
4196               && (head->flags & SHF_STRINGS))
4197             {
4198               /* Simple, single-byte string matching.  */
4199               struct Ebl_Strtab *mergestrtab;
4200               struct symbol *symrunp;
4201               Elf_Data *locsymdata = NULL;
4202               Elf_Data *locdata = NULL;
4203
4204               mergestrtab = ebl_strtabinit (false);
4205
4206               symrunp = head->symbols->next_in_scn;
4207               file = NULL;
4208               do
4209                 {
4210                   /* Accelarate the loop.  We cache the file
4211                      information since it might very well be the case
4212                      that the previous entry was from the same
4213                      file.  */
4214                   if (symrunp->file != file)
4215                     {
4216                       /* Remember the file.  */
4217                       file = symrunp->file;
4218                       /* Symbol table data from that file.  */
4219                       locsymdata = file->symtabdata;
4220                       /* String section data.  */
4221                       locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
4222                                              NULL);
4223                       assert (locdata != NULL);
4224                       /* While we are at it, remember the output
4225                          section.  If we don't access the string data
4226                          section the section won't be in the output
4227                          file.  So it is sufficient to do the work
4228                          here.  */
4229                       file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
4230                     }
4231
4232                   /* Get the symbol information.  This provides us the
4233                      offset into the string data section.  */
4234                   XElf_Sym_vardef (sym);
4235                   xelf_getsym (locsymdata, symrunp->symidx, sym);
4236                   assert (sym != NULL);
4237
4238                   /* Get the data from the file.  Note that we access
4239                      the raw section data; no endian-ness issues with
4240                      single-byte strings.  */
4241                   symrunp->merge.handle
4242                     = ebl_strtabadd (mergestrtab,
4243                                      (char *) locdata->d_buf + sym->st_value,
4244                                      0);
4245                 }
4246               while ((symrunp = symrunp->next_in_scn)
4247                      != head->symbols->next_in_scn);
4248
4249               /* All strings have been added.  Create the final table.  */
4250               ebl_strtabfinalize (mergestrtab, outdata);
4251
4252               /* Compute the final offsets in the section.  */
4253               symrunp = runp->symbols;
4254               do
4255                 {
4256                   symrunp->merge.value
4257                     = ebl_strtaboffset (symrunp->merge.handle);
4258                   symrunp->merged = 1;
4259                 }
4260               while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4261
4262               /* We don't need the string table anymore.  */
4263               ebl_strtabfree (mergestrtab);
4264             }
4265           else if (likely (SCNINFO_SHDR (head->last->shdr).sh_entsize
4266                            == sizeof (wchar_t))
4267                    && likely (head->flags & SHF_STRINGS))
4268             {
4269               /* Simple, wchar_t string merging.  */
4270               struct Ebl_WStrtab *mergestrtab;
4271               struct symbol *symrunp;
4272               Elf_Data *locsymdata = NULL;
4273               Elf_Data *locdata = NULL;
4274
4275               mergestrtab = ebl_wstrtabinit (false);
4276
4277               symrunp = runp->symbols;
4278               file = NULL;
4279               do
4280                 {
4281                   /* Accelarate the loop.  We cache the file
4282                      information since it might very well be the case
4283                      that the previous entry was from the same
4284                      file.  */
4285                   if (symrunp->file != file)
4286                     {
4287                       /* Remember the file.  */
4288                       file = symrunp->file;
4289                       /* Symbol table data from that file.  */
4290                       locsymdata = file->symtabdata;
4291                       /* String section data.  */
4292                       locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
4293                                              NULL);
4294                       assert (locdata != NULL);
4295
4296                       /* While we are at it, remember the output
4297                          section.  If we don't access the string data
4298                          section the section won't be in the output
4299                          file.  So it is sufficient to do the work
4300                          here.  */
4301                       file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
4302                     }
4303
4304                   /* Get the symbol information.  This provides us the
4305                      offset into the string data section.  */
4306                   XElf_Sym_vardef (sym);
4307                   xelf_getsym (locsymdata, symrunp->symidx, sym);
4308                   assert (sym != NULL);
4309
4310                   /* Get the data from the file.  Using the raw
4311                      section data here is possible since we don't
4312                      interpret the string themselves except for
4313                      looking for the wide NUL character.  The NUL
4314                      character has fortunately the same representation
4315                      regardless of the byte order.  */
4316                   symrunp->merge.handle
4317                     = ebl_wstrtabadd (mergestrtab,
4318                                       (wchar_t *) ((char *) locdata->d_buf
4319                                                    + sym->st_value), 0);
4320                 }
4321               while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4322
4323               /* All strings have been added.  Create the final table.  */
4324               ebl_wstrtabfinalize (mergestrtab, outdata);
4325
4326               /* Compute the final offsets in the section.  */
4327               symrunp = runp->symbols;
4328               do
4329                 {
4330                   symrunp->merge.value
4331                     = ebl_wstrtaboffset (symrunp->merge.handle);
4332                   symrunp->merged = 1;
4333                 }
4334               while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4335
4336               /* We don't need the string table anymore.  */
4337               ebl_wstrtabfree (mergestrtab);
4338             }
4339           else
4340             {
4341               /* Non-standard merging.  */
4342               struct Ebl_GStrtab *mergestrtab;
4343               struct symbol *symrunp;
4344               Elf_Data *locsymdata = NULL;
4345               Elf_Data *locdata = NULL;
4346               /* If this is no string section the length of each "string"
4347                  is always one.  */
4348               unsigned int len = (head->flags & SHF_STRINGS) ? 0 : 1;
4349
4350               /* This is the generic string table functionality.  Much
4351                  slower than the specialized code.  */
4352               mergestrtab
4353                 = ebl_gstrtabinit (SCNINFO_SHDR (head->last->shdr).sh_entsize,
4354                                    false);
4355
4356               symrunp = runp->symbols;
4357               file = NULL;
4358               do
4359                 {
4360                   /* Accelarate the loop.  We cache the file
4361                      information since it might very well be the case
4362                      that the previous entry was from the same
4363                      file.  */
4364                   if (symrunp->file != file)
4365                     {
4366                       /* Remember the file.  */
4367                       file = symrunp->file;
4368                       /* Symbol table data from that file.  */
4369                       locsymdata = file->symtabdata;
4370                       /* String section data.  */
4371                       locdata = elf_rawdata (file->scninfo[symrunp->scndx].scn,
4372                                              NULL);
4373                       assert (locdata != NULL);
4374
4375                       /* While we are at it, remember the output
4376                          section.  If we don't access the string data
4377                          section the section won't be in the output
4378                          file.  So it is sufficient to do the work
4379                          here.  */
4380                       file->scninfo[symrunp->scndx].outscnndx = head->scnidx;
4381                     }
4382
4383                   /* Get the symbol information.  This provides us the
4384                      offset into the string data section.  */
4385                   XElf_Sym_vardef (sym);
4386                   xelf_getsym (locsymdata, symrunp->symidx, sym);
4387                   assert (sym != NULL);
4388
4389                   /* Get the data from the file.  Using the raw
4390                      section data here is possible since we don't
4391                      interpret the string themselves except for
4392                      looking for the wide NUL character.  The NUL
4393                      character has fortunately the same representation
4394                      regardless of the byte order.  */
4395                   symrunp->merge.handle
4396                     = ebl_gstrtabadd (mergestrtab,
4397                                       (char *) locdata->d_buf + sym->st_value,
4398                                       len);
4399                 }
4400               while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4401
4402               /* Create the final table.  */
4403               ebl_gstrtabfinalize (mergestrtab, outdata);
4404
4405               /* Compute the final offsets in the section.  */
4406               symrunp = runp->symbols;
4407               do
4408                 {
4409                   symrunp->merge.value
4410                     = ebl_gstrtaboffset (symrunp->merge.handle);
4411                   symrunp->merged = 1;
4412                 }
4413               while ((symrunp = symrunp->next_in_scn) != runp->symbols);
4414
4415               /* We don't need the string table anymore.  */
4416               ebl_gstrtabfree (mergestrtab);
4417             }
4418         }
4419       else
4420         {
4421         no_merge:
4422           assert (head->scnidx == elf_ndxscn (scn));
4423
4424           /* It is important to start with the first list entry (and
4425              not just any one) to add the sections in the correct
4426              order.  */
4427           runp = head->last->next;
4428           offset = 0;
4429           do
4430             {
4431               Elf_Data *outdata = elf_newdata (scn);
4432               if (outdata == NULL)
4433                 error (EXIT_FAILURE, 0,
4434                        gettext ("cannot create section for output file: %s"),
4435                        elf_errmsg (-1));
4436
4437               /* Exceptional case: if we synthesize a data block SCN
4438                  is NULL and the sectio header info must be for a
4439                  SHT_NOBITS block and the size and alignment are
4440                  filled in.  */
4441               if (likely (runp->scn != NULL))
4442                 {
4443                   data = elf_getdata (runp->scn, NULL);
4444                   assert (data != NULL);
4445
4446                   /* We reuse the data buffer in the input file.  */
4447                   *outdata = *data;
4448
4449                   /* Given that we read the input file from disk we know there
4450                      cannot be another data part.  */
4451                   assert (elf_getdata (runp->scn, data) == NULL);
4452                 }
4453               else
4454                 {
4455                   /* Must be a NOBITS section.  */
4456                   assert  (SCNINFO_SHDR (runp->shdr).sh_type == SHT_NOBITS);
4457
4458                   outdata->d_buf = NULL;        /* Not needed.  */
4459                   outdata->d_type = ELF_T_BYTE;
4460                   outdata->d_version = EV_CURRENT;
4461                   outdata->d_size = SCNINFO_SHDR (runp->shdr).sh_size;
4462                   outdata->d_align = SCNINFO_SHDR (runp->shdr).sh_addralign;
4463                 }
4464
4465               XElf_Off align =  MAX (1, outdata->d_align);
4466               assert (powerof2 (align));
4467               offset = ((offset + align - 1) & ~(align - 1));
4468
4469               runp->offset = offset;
4470               runp->outscnndx = head->scnidx;
4471               runp->allsectionsidx = cnt;
4472
4473               outdata->d_off = offset;
4474
4475               offset += outdata->d_size;
4476             }
4477           while ((runp = runp->next) != head->last->next);
4478
4479           /* If necessary add the additional line to the .comment section.  */
4480           if (ld_state.add_ld_comment
4481               && head->flags == 0
4482               && head->type == SHT_PROGBITS
4483               && strcmp (head->name, ".comment") == 0
4484               && head->entsize == 0)
4485             {
4486               Elf_Data *outdata = elf_newdata (scn);
4487
4488               if (outdata == NULL)
4489                 error (EXIT_FAILURE, 0,
4490                        gettext ("cannot create section for output file: %s"),
4491                        elf_errmsg (-1));
4492
4493               outdata->d_buf = (void *) "\0ld (Red Hat " PACKAGE ") " VERSION;
4494               outdata->d_size = strlen ((char *) outdata->d_buf + 1) + 2;
4495               outdata->d_off = offset;
4496               outdata->d_type = ELF_T_BYTE;
4497               outdata->d_align = 1;
4498             }
4499           /* XXX We should create a .comment section if none exists.
4500              This requires that we early on detect that no such
4501              section exists.  This should probably be implemented
4502              together with some merging of the section contents.
4503              Currently identical entries are not merged.  */
4504         }
4505     }
4506
4507   /* The table we collect the strings in.  */
4508   strtab = ebl_strtabinit (true);
4509   if (strtab == NULL)
4510     error (EXIT_FAILURE, errno, gettext ("cannot create string table"));
4511
4512
4513 #ifndef NDEBUG
4514   /* Keep track of the use of the XINDEX.  */
4515   need_xndx = false;
4516 #endif
4517
4518   /* We we generate a normal symbol table for an executable and the
4519      --export-dynamic option is not given, we need an extra table
4520      which keeps track of the symbol entry belonging to the symbol
4521      table entry.  Note that EXPORT_ALL_DYNAMIC is always set if we
4522      generate a DSO so we do not have to test this separately.  */
4523   ndxtosym = (struct symbol **) xcalloc (nsym_allocated,
4524                                          sizeof (struct symbol));
4525
4526   /* Create the special symbol for the GOT section.  */
4527   if (ld_state.got_symbol != NULL)
4528     {
4529       assert (nsym < nsym_allocated);
4530       fillin_special_symbol (ld_state.got_symbol, ld_state.gotscnidx,
4531                              nsym++, symdata, strtab);
4532     }
4533
4534   /* Similarly for the dynamic section symbol.  */
4535   if (ld_state.dyn_symbol != NULL)
4536     {
4537       assert (nsym < nsym_allocated);
4538       fillin_special_symbol (ld_state.dyn_symbol, ld_state.dynamicscnidx,
4539                              nsym++, symdata, strtab);
4540     }
4541
4542   /* Create symbol table entries for the symbols defined in the linker
4543      script.  */
4544   if (ld_state.lscript_syms != NULL)
4545     {
4546       struct symbol *rsym = ld_state.lscript_syms;
4547       do
4548         {
4549           assert (nsym < nsym_allocated);
4550           fillin_special_symbol (rsym, SHN_ABS, nsym++, symdata, strtab);
4551         }
4552       while ((rsym = rsym->next) != NULL);
4553     }
4554
4555   /* Iterate over all input files to collect the symbols.  */
4556   file = ld_state.relfiles->next;
4557   symdata = elf_getdata (elf_getscn (ld_state.outelf, ld_state.symscnidx),
4558                          NULL);
4559   do
4560     {
4561       size_t maxcnt;
4562       Elf_Data *insymdata;
4563       Elf_Data *inxndxdata;
4564
4565       /* There must be no dynamic symbol table when creating
4566          relocatable files.  */
4567       assert (ld_state.file_type != relocatable_file_type
4568               || file->dynsymtabdata == NULL);
4569
4570       insymdata = file->symtabdata;
4571       assert (insymdata != NULL);
4572       inxndxdata = file->xndxdata;
4573
4574       maxcnt = file->nsymtab;
4575
4576       file->symindirect = (Elf32_Word *) xcalloc (maxcnt, sizeof (Elf32_Word));
4577
4578       /* The dynamic symbol table does not contain local symbols.  So
4579          we skip those entries.  */
4580       for (cnt = ld_state.need_symtab ? 1 : file->nlocalsymbols; cnt < maxcnt;
4581            ++cnt)
4582         {
4583           XElf_Sym_vardef (sym);
4584           Elf32_Word xndx;
4585           struct symbol *defp = NULL;
4586
4587           xelf_getsymshndx (insymdata, inxndxdata, cnt, sym, xndx);
4588           assert (sym != NULL);
4589
4590           if (unlikely (XELF_ST_TYPE (sym->st_info) == STT_SECTION))
4591             {
4592               /* Section symbols should always be local but who knows...  */
4593               if (ld_state.need_symtab)
4594                 {
4595                   /* Determine the real section index in the source file.
4596                      Use the XINDEX section content if necessary.  We don't
4597                      add this information to the dynamic symbol table.  */
4598                   if (sym->st_shndx != SHN_XINDEX)
4599                     xndx = sym->st_shndx;
4600
4601                   assert (file->scninfo[xndx].allsectionsidx
4602                           < ld_state.nallsections);
4603                   file->symindirect[cnt] = ld_state.allsections[file->scninfo[xndx].allsectionsidx]->scnsymidx;
4604                   /* Note that the resulting index can be zero here.  There is
4605                      no guarantee that the output file will contain all the
4606                      sections the input file did.  */
4607                 }
4608               continue;
4609             }
4610
4611           if ((ld_state.strip >= strip_all || !ld_state.need_symtab)
4612               /* XXX Do we need these entries?  */
4613               && XELF_ST_TYPE (sym->st_info) == STT_FILE)
4614             continue;
4615
4616 #if NATIVE_ELF != 0
4617           /* Copy old data.  */
4618           XElf_Sym *sym2 = sym;
4619           assert (nsym < nsym_allocated);
4620           xelf_getsym (symdata, nsym, sym);
4621           *sym = *sym2;
4622 #endif
4623
4624           if (sym->st_shndx != SHN_UNDEF
4625               && (sym->st_shndx < SHN_LORESERVE
4626                   || sym->st_shndx == SHN_XINDEX))
4627             {
4628               /* If we are creating an executable with no normal
4629                  symbol table and we do not export all symbols and
4630                  this symbol is not defined in a DSO as well, ignore
4631                  it.  */
4632               if (!ld_state.export_all_dynamic && !ld_state.need_symtab)
4633                 {
4634                   assert (cnt >= file->nlocalsymbols);
4635                   defp = file->symref[cnt];
4636                   assert (defp != NULL);
4637
4638                   if (!defp->in_dso)
4639                     /* Ignore it.  */
4640                     continue;
4641                 }
4642
4643               /* Determine the real section index in the source file.  Use
4644                  the XINDEX section content if necessary.  */
4645               if (sym->st_shndx != SHN_XINDEX)
4646                 xndx = sym->st_shndx;
4647
4648               sym->st_value += file->scninfo[xndx].offset;
4649
4650               assert (file->scninfo[xndx].outscnndx < SHN_LORESERVE
4651                       || file->scninfo[xndx].outscnndx > SHN_HIRESERVE);
4652               if (unlikely (file->scninfo[xndx].outscnndx > SHN_LORESERVE))
4653                 {
4654                   /* It is not possible to have an extended section index
4655                      table for the dynamic symbol table.  */
4656                   if (!ld_state.need_symtab)
4657                     error (EXIT_FAILURE, 0, gettext ("\
4658 section index too large in dynamic symbol table"));
4659
4660                   assert (xndxdata != NULL);
4661                   sym->st_shndx = SHN_XINDEX;
4662                   xndx = file->scninfo[xndx].outscnndx;
4663 #ifndef NDEBUG
4664                   need_xndx = true;
4665 #endif
4666                 }
4667               else
4668                 {
4669                   sym->st_shndx = file->scninfo[xndx].outscnndx;
4670                   xndx = 0;
4671                 }
4672             }
4673           else if (sym->st_shndx == SHN_COMMON || sym->st_shndx == SHN_UNDEF)
4674             {
4675               /* Check whether we have a (real) definition for this
4676                  symbol.  If this is the case we skip this symbol
4677                  table entry.  */
4678               assert (cnt >= file->nlocalsymbols);
4679               defp = file->symref[cnt];
4680               assert (defp != NULL);
4681
4682               assert (sym->st_shndx != SHN_COMMON || defp->defined);
4683
4684               if ((sym->st_shndx == SHN_COMMON && !defp->common)
4685                   || (sym->st_shndx == SHN_UNDEF && defp->defined)
4686                   || defp->added)
4687                 /* Ignore this symbol table entry, there is a
4688                    "better" one or we already added it.  */
4689                 continue;
4690
4691               /* Remember that we already added this symbol.  */
4692               defp->added = 1;
4693
4694               /* Adjust the section number for common symbols.  */
4695               if (sym->st_shndx == SHN_COMMON)
4696                 {
4697                   sym->st_value = (ld_state.common_section->offset
4698                                    + file->symref[cnt]->merge.value);
4699                   assert (ld_state.common_section->outscnndx < SHN_LORESERVE);
4700                   sym->st_shndx = ld_state.common_section->outscnndx;
4701                   xndx = 0;
4702                 }
4703             }
4704           else if (unlikely (sym->st_shndx != SHN_ABS))
4705             {
4706               if (SPECIAL_SECTION_NUMBER_P (&ld_state, sym->st_shndx))
4707                 /* XXX Add code to handle machine specific special
4708                    sections.  */
4709                 abort ();
4710             }
4711
4712           /* Add the symbol name to the string table.  If the user
4713              chooses the highest level of stripping avoid adding names
4714              for local symbols in the string table.  */
4715           if (sym->st_name != 0
4716               && (ld_state.strip < strip_everything
4717                   || XELF_ST_BIND (sym->st_info) != STB_LOCAL))
4718             symstrent[nsym] = ebl_strtabadd (strtab,
4719                                              elf_strptr (file->elf,
4720                                                          file->symstridx,
4721                                                          sym->st_name), 0);
4722
4723           /* Once we know the name this field will get the correct
4724              offset.  For now set it to zero which means no name
4725              associated.  */
4726           sym->st_name = 0;
4727
4728           /* If we had to merge sections we have a completely new
4729              offset for the symbol.  */
4730           if (file->has_merge_sections && file->symref[cnt] != NULL
4731               && file->symref[cnt]->merged)
4732             sym->st_value = file->symref[cnt]->merge.value;
4733
4734           /* Create the record in the output sections.  */
4735           assert (nsym < nsym_allocated);
4736           xelf_update_symshndx (symdata, xndxdata, nsym, sym, xndx, 0);
4737
4738           /* Add the reference to the symbol record in case we need it.
4739              Find the symbol if this has not happened yet.  We do
4740              not need the information for local symbols.  */
4741           if (defp == NULL && cnt >= file->nlocalsymbols)
4742             {
4743               defp = file->symref[cnt];
4744               assert (defp != NULL);
4745             }
4746
4747           /* Store the reference to the symbol record.  The
4748              sorting code will have to keep this array in the
4749              correct order, too.  */
4750           ndxtosym[nsym] = defp;
4751
4752           /* One more entry finished.  */
4753           if (cnt >= file->nlocalsymbols)
4754             {
4755               assert (file->symref[cnt]->outsymidx == 0);
4756               file->symref[cnt]->outsymidx = nsym;
4757             }
4758           file->symindirect[cnt] = nsym++;
4759         }
4760     }
4761   while ((file = file->next) != ld_state.relfiles->next);
4762   /* Make sure we didn't create the extended section index table for
4763      nothing.  */
4764   assert (xndxdata == NULL || need_xndx);
4765
4766
4767   /* Create the version related sections.  */
4768   if (ld_state.verneedscnidx != 0)
4769     {
4770       /* We know the number of input files and total number of
4771          referenced versions.  This allows us to allocate the memory
4772          and then we iterate over the DSOs to get the version
4773          information.  */
4774       struct usedfiles *runp;
4775
4776       runp = ld_state.dsofiles->next;
4777       do
4778         allocate_version_names (runp, dynstrtab);
4779       while ((runp = runp->next) != ld_state.dsofiles->next);
4780
4781       if (ld_state.needed != NULL)
4782         {
4783           runp = ld_state.needed->next;
4784           do
4785             allocate_version_names (runp, dynstrtab);
4786           while ((runp = runp->next) != ld_state.needed->next);
4787         }
4788     }
4789
4790   /* At this point we should hide symbols and so on.  */
4791   if (ld_state.default_bind_local || ld_state.version_str_tab.filled > 0)
4792     /* XXX Add one more test when handling of wildcard symbol names
4793        is supported.  */
4794     {
4795     /* Check all non-local symbols whether they are on the export list.  */
4796       bool any_reduced = false;
4797
4798       for (cnt = 1; cnt < nsym; ++cnt)
4799         {
4800           XElf_Sym_vardef (sym);
4801
4802           /* Note that we don't have to use 'xelf_getsymshndx' since we
4803              only need the binding and the symbol name.  */
4804           xelf_getsym (symdata, cnt, sym);
4805           assert (sym != NULL);
4806
4807           if (reduce_symbol_p (sym, symstrent[cnt]))
4808             {
4809               sym->st_info = XELF_ST_INFO (STB_LOCAL,
4810                                            XELF_ST_TYPE (sym->st_info));
4811               (void) xelf_update_sym (symdata, cnt, sym);
4812
4813               /* Show that we don't need this string anymore.  */
4814               if (ld_state.strip == strip_everything)
4815                 {
4816                   symstrent[cnt] = NULL;
4817                   any_reduced = true;
4818                 }
4819             }
4820         }
4821
4822       if (unlikely (any_reduced))
4823         {
4824           /* Since we will not write names of local symbols in the
4825              output file and we have reduced the binding of some
4826              symbols the string table previously constructed contains
4827              too many string.  Correct it.  */
4828           struct Ebl_Strtab *newp = ebl_strtabinit (true);
4829
4830           for (cnt = 1; cnt < nsym; ++cnt)
4831             if (symstrent[cnt] != NULL)
4832               symstrent[cnt] = ebl_strtabadd (newp,
4833                                               ebl_string (symstrent[cnt]), 0);
4834
4835           ebl_strtabfree (strtab);
4836           strtab = newp;
4837         }
4838     }
4839
4840   /* Add the references to DSOs.  We can add these entries this late
4841      (after sorting out versioning) because references to DSOs are not
4842      effected.  */
4843   if (ld_state.from_dso != NULL)
4844     {
4845       struct symbol *runp;
4846       size_t plt_base = nsym + ld_state.nfrom_dso - ld_state.nplt;
4847       size_t plt_idx = 0;
4848       size_t obj_idx = 0;
4849
4850       assert (ld_state.nfrom_dso >= ld_state.nplt);
4851       runp = ld_state.from_dso;
4852       do
4853         {
4854           // XXX What about functions which are only referenced via
4855           // pointers and not PLT entries?  Can we distinguish such uses?
4856           size_t idx;
4857           if (runp->type == STT_FUNC)
4858             {
4859               /* Store the PLT entry number.  */
4860               runp->merge.value = plt_idx + 1;
4861               idx = plt_base + plt_idx++;
4862             }
4863           else
4864             idx = nsym + obj_idx++;
4865
4866           XElf_Sym_vardef (sym);
4867           xelf_getsym_ptr (symdata, idx, sym);
4868
4869           sym->st_value = 0;
4870           sym->st_size = runp->size;
4871           sym->st_info = XELF_ST_INFO (runp->weak ? STB_WEAK : STB_GLOBAL,
4872                                        runp->type);
4873           sym->st_other = STV_DEFAULT;
4874           sym->st_shndx = SHN_UNDEF;
4875
4876           /* Create the record in the output sections.  */
4877           xelf_update_symshndx (symdata, xndxdata, idx, sym, 0, 0);
4878
4879           const char *name = runp->name;
4880           size_t namelen = 0;
4881
4882           if (runp->file->verdefdata != NULL)
4883             {
4884               // XXX Is it useful to add the versym value to struct symbol?
4885               XElf_Versym versym;
4886
4887               (void) xelf_getversym_copy (runp->file->versymdata, runp->symidx,
4888                                           versym);
4889
4890               /* One can only link with the default version.  */
4891               assert ((versym & 0x8000) == 0);
4892
4893               const char *versname
4894                 = ebl_string (runp->file->verdefent[versym]);
4895
4896               size_t versname_len = strlen (versname) + 1;
4897               namelen = strlen (name) + versname_len + 2;
4898               char *newp = (char *) obstack_alloc (&ld_state.smem, namelen);
4899               memcpy (stpcpy (stpcpy (newp, name), "@@"),
4900                       versname, versname_len);
4901               name = newp;
4902             }
4903
4904           symstrent[idx] = ebl_strtabadd (strtab, name, namelen);
4905
4906           /* Record the initial index in the symbol table.  */
4907           runp->outsymidx = idx;
4908
4909           /* Remember the symbol record this ELF symbol came from.  */
4910           ndxtosym[idx] = runp;
4911         }
4912       while ((runp = runp->next) != ld_state.from_dso);
4913
4914       assert (nsym + obj_idx == plt_base);
4915       assert (plt_idx == ld_state.nplt);
4916       nsym = plt_base + plt_idx;
4917     }
4918
4919   /* Now we know how many symbols will be in the output file.  Adjust
4920      the count in the section data.  */
4921   symdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym);
4922   if (unlikely (xndxdata != NULL))
4923     xndxdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_WORD, nsym);
4924
4925   /* Create the symbol string table section.  */
4926   strscn = elf_newscn (ld_state.outelf);
4927   ld_state.strscnidx = elf_ndxscn (strscn);
4928   data = elf_newdata (strscn);
4929   xelf_getshdr (strscn, shdr);
4930   if (data == NULL || shdr == NULL)
4931     error (EXIT_FAILURE, 0,
4932            gettext ("cannot create section for output file: %s"),
4933            elf_errmsg (-1));
4934
4935   /* Create a compact string table, allocate the memory for it, and
4936      fill in the section data information.  */
4937   ebl_strtabfinalize (strtab, data);
4938
4939   shdr->sh_type = SHT_STRTAB;
4940   assert (shdr->sh_entsize == 0);
4941
4942   if (unlikely (xelf_update_shdr (strscn, shdr) == 0))
4943     error (EXIT_FAILURE, 0,
4944            gettext ("cannot create section for output file: %s"),
4945            elf_errmsg (-1));
4946
4947   /* Fill in the offsets of the symbol names.  */
4948   for (cnt = 1; cnt < nsym; ++cnt)
4949     if (symstrent[cnt] != NULL)
4950       {
4951         XElf_Sym_vardef (sym);
4952
4953         /* Note that we don't have to use 'xelf_getsymshndx' since we don't
4954            modify the section index.  */
4955         xelf_getsym (symdata, cnt, sym);
4956         /* This better worked, we did it before.  */
4957         assert (sym != NULL);
4958         sym->st_name = ebl_strtaboffset (symstrent[cnt]);
4959         (void) xelf_update_sym (symdata, cnt, sym);
4960       }
4961
4962   /* Since we are going to reorder the symbol table but still have to
4963      be able to find the new position based on the old one (since the
4964      latter is stored in 'symindirect' information of the input file
4965      data structure) we have to create yet another indirection
4966      table.  */
4967   ld_state.dblindirect = dblindirect
4968     = (Elf32_Word *) xmalloc (nsym * sizeof (Elf32_Word));
4969
4970   /* Sort the symbol table so that the local symbols come first.  */
4971   /* XXX We don't use stable sorting here.  It seems not necessary and
4972      would be more expensive.  If it turns out to be necessary this can
4973      be fixed easily.  */
4974   nsym_local = 1;
4975   cnt = nsym - 1;
4976   while (nsym_local < cnt)
4977     {
4978       XElf_Sym_vardef (locsym);
4979       Elf32_Word locxndx;
4980       XElf_Sym_vardef (globsym);
4981       Elf32_Word globxndx;
4982
4983       do
4984         {
4985           xelf_getsymshndx (symdata, xndxdata, nsym_local, locsym, locxndx);
4986           /* This better works.  */
4987           assert (locsym != NULL);
4988
4989           if (XELF_ST_BIND (locsym->st_info) != STB_LOCAL
4990               && (ld_state.need_symtab || ld_state.export_all_dynamic))
4991             {
4992               do
4993                 {
4994                   xelf_getsymshndx (symdata, xndxdata, cnt, globsym, globxndx);
4995                   /* This better works.  */
4996                   assert (globsym != NULL);
4997
4998                   if (unlikely (XELF_ST_BIND (globsym->st_info) == STB_LOCAL))
4999                     {
5000                       /* We swap the two entries.  */
5001 #if NATIVE_ELF != 0
5002                       /* Since we directly modify the data in the ELF
5003                          data structure we have to make a copy of one
5004                          of the entries.  */
5005                       XElf_Sym locsym_copy = *locsym;
5006                       locsym = &locsym_copy;
5007 #endif
5008                       xelf_update_symshndx (symdata, xndxdata, nsym_local,
5009                                             globsym, globxndx, 1);
5010                       xelf_update_symshndx (symdata, xndxdata, cnt,
5011                                             locsym, locxndx, 1);
5012
5013                       /* Also swap the cross references.  */
5014                       dblindirect[nsym_local] = cnt;
5015                       dblindirect[cnt] = nsym_local;
5016
5017                       /* And the entries for the symbol names.  */
5018                       struct Ebl_Strent *strtmp = symstrent[nsym_local];
5019                       symstrent[nsym_local] = symstrent[cnt];
5020                       symstrent[cnt] = strtmp;
5021
5022                       /* And the mapping from symbol table entry to
5023                          struct symbol record.  */
5024                       struct symbol *symtmp = ndxtosym[nsym_local];
5025                       ndxtosym[nsym_local] = ndxtosym[cnt];
5026                       ndxtosym[cnt] = symtmp;
5027
5028                       /* Go to the next entry.  */
5029                       ++nsym_local;
5030                       --cnt;
5031
5032                       break;
5033                     }
5034
5035                   dblindirect[cnt] = cnt;
5036                 }
5037               while (nsym_local < --cnt);
5038
5039               break;
5040             }
5041
5042           dblindirect[nsym_local] = nsym_local;
5043         }
5044       while (++nsym_local < cnt);
5045     }
5046
5047   /* The symbol 'nsym_local' is currently pointing to might be local,
5048      too.  Check and increment the variable if this is the case.  */
5049   if (likely (nsym_local < nsym))
5050     {
5051       XElf_Sym_vardef (locsym);
5052
5053       /* This entry isn't moved.  */
5054       dblindirect[nsym_local] = nsym_local;
5055
5056       /* Note that it is OK to not use 'xelf_getsymshndx' here.  */
5057       xelf_getsym (symdata, nsym_local, locsym);
5058       /* This better works.  */
5059       assert (locsym != NULL);
5060
5061       if (XELF_ST_BIND (locsym->st_info) == STB_LOCAL)
5062         ++nsym_local;
5063     }
5064
5065
5066   /* We need the versym array right away to keep track of the version
5067      symbols.  */
5068   if (ld_state.versymscnidx != 0)
5069     {
5070       /* We allocate more memory than we need since the array is morroring
5071          the dynamic symbol table and not the normal symbol table.  I.e.,
5072          no local symbols are present.  */
5073       versymscn = elf_getscn (ld_state.outelf, ld_state.versymscnidx);
5074       versymdata = elf_newdata (versymscn);
5075       if (versymdata == NULL)
5076         error (EXIT_FAILURE, 0,
5077                gettext ("cannot create versioning section: %s"),
5078                elf_errmsg (-1));
5079
5080       versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
5081                                        nsym - nsym_local + 1);
5082       versymdata->d_buf = xcalloc (1, versymdata->d_size);
5083       versymdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_HALF, 1);
5084       versymdata->d_off = 0;
5085       versymdata->d_type = ELF_T_HALF;
5086     }
5087
5088
5089   /* If we have to construct the dynamic symbol table we must not include
5090      the local symbols.  If the normal symbol has to be emitted as well
5091      we haven't done anything else yet and we can construct it from
5092      scratch now.  */
5093   if (unlikely (!ld_state.need_symtab))
5094     {
5095       /* Note that the following code works even if there is no entry
5096          to remove since the zeroth entry is always local.  */
5097       size_t reduce = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym_local - 1);
5098
5099       XElf_Sym_vardef (nullsym);
5100       xelf_getsym_ptr (symdata, nsym_local - 1, nullsym);
5101
5102       /* Note that we don't have to use 'xelf_update_symshndx' since
5103          this is the dynamic symbol table we write.  */
5104       (void) xelf_update_sym (symdata, nsym_local - 1,
5105                               memset (nullsym, '\0', sizeof (*nullsym)));
5106
5107       /* Update the buffer pointer and size in the output data.  */
5108       symdata->d_buf = (char *) symdata->d_buf + reduce;
5109       symdata->d_size -= reduce;
5110
5111       /* Add the version symbol information.  */
5112       if (versymdata != NULL)
5113         {
5114           nsym_dyn = 1;
5115           for (cnt = nsym_local; cnt < nsym; ++cnt, ++nsym_dyn)
5116             {
5117               struct symbol *symp = ndxtosym[cnt];
5118
5119               if (symp->file->versymdata != NULL)
5120                 {
5121                   GElf_Versym versym;
5122
5123                   gelf_getversym (symp->file->versymdata, symp->symidx,
5124                                   &versym);
5125
5126                   (void) gelf_update_versym (versymdata, nsym_dyn,
5127                                              &symp->file->verdefused[versym]);
5128                 }
5129               }
5130         }
5131
5132       /* Since we only created the dynamic symbol table the number of
5133          dynamic symbols is the total number of symbols.  */
5134       nsym_dyn = nsym - nsym_local + 1;
5135
5136       /* XXX TBI.  Create whatever data structure is missing.  */
5137       abort ();
5138     }
5139   else if (ld_state.need_dynsym)
5140     {
5141       /* Create the dynamic symbol table section data along with the
5142          string table.  We look at all non-local symbols we found for
5143          the normal symbol table and add those.  */
5144       dynsymscn = elf_getscn (ld_state.outelf, ld_state.dynsymscnidx);
5145       dynsymdata = elf_newdata (dynsymscn);
5146
5147       dynstrdata = elf_newdata (elf_getscn (ld_state.outelf,
5148                                             ld_state.dynstrscnidx));
5149       if (dynsymdata == NULL || dynstrdata == NULL)
5150         error (EXIT_FAILURE, 0, gettext ("\
5151 cannot create dynamic symbol table for output file: %s"),
5152                elf_errmsg (-1));
5153
5154       nsym_dyn_allocated = nsym - nsym_local + 1;
5155       dynsymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM,
5156                                        nsym_dyn_allocated);
5157       dynsymdata->d_buf = memset (xmalloc (dynsymdata->d_size), '\0',
5158                                   xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
5159       dynsymdata->d_type = ELF_T_SYM;
5160       dynsymdata->d_off = 0;
5161       dynsymdata->d_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
5162
5163       /* We need one more array which contains the hash codes of the
5164          symbol names.  */
5165       hashcodes = (Elf32_Word *) xcalloc (nsym_dyn_allocated,
5166                                           sizeof (Elf32_Word));
5167
5168       /* We have and empty entry at the beginning.  */
5169       nsym_dyn = 1;
5170
5171       /* We don't mix PLT symbols and others.  */
5172       size_t plt_idx = 1;
5173       size_t obj_idx = 1 + ld_state.nplt;
5174
5175       /* Populate the table.  */
5176       for (cnt = nsym_local; cnt < nsym; ++cnt)
5177         {
5178           XElf_Sym_vardef (sym);
5179
5180           xelf_getsym (symdata, cnt, sym);
5181           assert (sym != NULL);
5182
5183           if (sym->st_shndx == SHN_XINDEX)
5184             error (EXIT_FAILURE, 0, gettext ("\
5185 section index too large in dynamic symbol table"));
5186
5187           /* We do not add the symbol to the dynamic symbol table if
5188
5189              - the symbol is for a file
5190              - it is not externally visible (internal, hidden)
5191              - if export_all_dynamic is not set and is only defined in
5192                the executable (i.e., it is defined, but not (also) in
5193                in DSO)
5194
5195              Set symstrent[cnt] to NULL in case an entry is ignored.  */
5196           if (XELF_ST_TYPE (sym->st_info) == STT_FILE
5197               || XELF_ST_VISIBILITY (sym->st_other) == STV_INTERNAL
5198               || XELF_ST_VISIBILITY (sym->st_other) == STV_HIDDEN
5199               || (!ndxtosym[cnt]->in_dso && ndxtosym[cnt]->defined))
5200             {
5201               symstrent[cnt] = NULL;
5202               continue;
5203             }
5204
5205           size_t idx;
5206           if (ndxtosym[cnt]->in_dso && ndxtosym[cnt]->type == STT_FUNC)
5207             {
5208               idx = plt_idx++;
5209               assert (idx < 1 + ld_state.nplt);
5210             }
5211           else
5212             {
5213               idx = obj_idx++;
5214               assert (idx < nsym_dyn_allocated);
5215             }
5216
5217           /* Add the version information.  */
5218           if (versymdata != NULL)
5219             {
5220               struct symbol *symp = ndxtosym[cnt];
5221
5222               if (symp->file->verdefdata != NULL)
5223                 {
5224                   GElf_Versym versym;
5225
5226                   gelf_getversym (symp->file->versymdata, symp->symidx,
5227                                   &versym);
5228
5229                   (void) gelf_update_versym (versymdata, idx,
5230                                              &symp->file->verdefused[versym]);
5231                 }
5232               else
5233                 {
5234                   /* XXX Add support for version definitions.  */
5235                   GElf_Versym global = VER_NDX_GLOBAL;
5236                   (void) gelf_update_versym (versymdata, idx, &global);
5237                 }
5238             }
5239
5240           /* Store the index of the symbol in the dynamic symbol table.  */
5241           ndxtosym[cnt]->outdynsymidx = idx;
5242
5243           /* Create a new string table entry.  */
5244           const char *str = ndxtosym[cnt]->name;
5245           symstrent[cnt] = ebl_strtabadd (dynstrtab, str, 0);
5246           hashcodes[idx] = elf_hash (str);
5247           ++nsym_dyn;
5248         }
5249       assert (nsym_dyn == obj_idx);
5250       assert (ld_state.nplt + 1 == plt_idx);
5251
5252       /* Update the information about the symbol section.  */
5253       if (versymdata != NULL)
5254         {
5255           /* Correct the size now that we know how many entries the
5256              dynamic symbol table has.  */
5257           versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
5258                                            nsym_dyn);
5259
5260           /* Add the reference to the symbol table.  */
5261           xelf_getshdr (versymscn, shdr);
5262           assert (shdr != NULL);
5263
5264           shdr->sh_link = ld_state.dynsymscnidx;
5265
5266           (void) xelf_update_shdr (versymscn, shdr);
5267         }
5268     }
5269
5270   if (ld_state.file_type != relocatable_file_type)
5271     {
5272       size_t nbucket;
5273       Elf32_Word *bucket;
5274       Elf32_Word *chain;
5275       size_t nchain;
5276       Elf_Scn *hashscn;
5277       Elf_Data *hashdata;
5278
5279       /* Finalize the dynamic string table.  */
5280       ebl_strtabfinalize (dynstrtab, dynstrdata);
5281
5282       /* Determine the "optimal" bucket size.  */
5283       nbucket = optimal_bucket_size (hashcodes, nsym_dyn, ld_state.optlevel);
5284
5285       /* Create the .hash section data structures.  */
5286       assert (ld_state.hashscnidx != 0);
5287       hashscn = elf_getscn (ld_state.outelf, ld_state.hashscnidx);
5288       xelf_getshdr (hashscn, shdr);
5289       hashdata = elf_newdata (hashscn);
5290       if (shdr == NULL || hashdata == NULL)
5291         error (EXIT_FAILURE, 0, gettext ("\
5292 cannot create hash table section for output file: %s"),
5293                elf_errmsg (-1));
5294
5295       shdr->sh_link = ld_state.dynsymscnidx;
5296       (void) xelf_update_shdr (hashscn, shdr);
5297
5298       hashdata->d_size = (2 + nsym_dyn + nbucket) * sizeof (Elf32_Word);
5299       hashdata->d_buf = xcalloc (1, hashdata->d_size);
5300       hashdata->d_align = sizeof (Elf32_Word);
5301       hashdata->d_type = ELF_T_WORD;
5302       hashdata->d_off = 0;
5303
5304       ((Elf32_Word *) hashdata->d_buf)[0] = nbucket;
5305       ((Elf32_Word *) hashdata->d_buf)[1] = nsym_dyn;
5306       bucket = &((Elf32_Word *) hashdata->d_buf)[2];
5307       chain = &((Elf32_Word *) hashdata->d_buf)[2 + nbucket];
5308
5309       /* Haven't yet filled in any chain value.  */
5310       nchain = 0;
5311
5312       /* Now put the names in.  */
5313       for (cnt = nsym_local; cnt < nsym; ++cnt)
5314         if (symstrent[cnt] != NULL)
5315           {
5316             XElf_Sym_vardef (sym);
5317             size_t dynidx = ndxtosym[cnt]->outdynsymidx;
5318
5319 #if NATIVE_ELF != 0
5320             XElf_Sym *osym;
5321             memcpy (xelf_getsym (dynsymdata, dynidx, sym),
5322                     xelf_getsym (symdata, cnt, osym),
5323                     sizeof (XElf_Sym));
5324 #else
5325             xelf_getsym (symdata, cnt, sym);
5326             assert (sym != NULL);
5327 #endif
5328
5329             sym->st_name = ebl_strtaboffset (symstrent[cnt]);
5330
5331             (void) xelf_update_sym (dynsymdata, dynidx, sym);
5332
5333             /* Add to the hash table.  */
5334             size_t hashidx = hashcodes[dynidx] % nbucket;
5335             if (bucket[hashidx] == 0)
5336               bucket[hashidx] = dynidx;
5337             else
5338               {
5339                 hashidx = bucket[hashidx];
5340                 while (chain[hashidx] != 0)
5341                   hashidx = chain[hashidx];
5342
5343                 chain[hashidx] = dynidx;
5344               }
5345           }
5346
5347       free (hashcodes);
5348
5349       /* We don't need the map from the symbol table index to the symbol
5350          structure anymore.  */
5351       free (ndxtosym);
5352
5353       /* Create the required version section.  */
5354       if (ld_state.verneedscnidx != 0)
5355         {
5356           Elf_Scn *verneedscn;
5357           Elf_Data *verneeddata;
5358           struct usedfiles *runp;
5359           size_t verneed_size = xelf_fsize (ld_state.outelf, ELF_T_VNEED, 1);
5360           size_t vernaux_size = xelf_fsize (ld_state.outelf, ELF_T_VNAUX, 1);
5361           size_t offset;
5362           int ntotal;
5363
5364           verneedscn = elf_getscn (ld_state.outelf, ld_state.verneedscnidx);
5365           xelf_getshdr (verneedscn, shdr);
5366           verneeddata = elf_newdata (verneedscn);
5367           if (shdr == NULL || verneeddata == NULL)
5368             error (EXIT_FAILURE, 0,
5369                    gettext ("cannot create versioning data: %s"),
5370                    elf_errmsg (-1));
5371
5372           verneeddata->d_size = (ld_state.nverdeffile * verneed_size
5373                                  + ld_state.nverdefused * vernaux_size);
5374           verneeddata->d_buf = xmalloc (verneeddata->d_size);
5375           verneeddata->d_type = ELF_T_VNEED;
5376           verneeddata->d_align = xelf_fsize (ld_state.outelf, ELF_T_WORD, 1);
5377           verneeddata->d_off = 0;
5378
5379           offset = 0;
5380           ntotal = ld_state.nverdeffile;
5381           runp = ld_state.dsofiles->next;
5382           do
5383             {
5384               offset = create_verneed_data (offset, verneeddata, runp,
5385                                             &ntotal);
5386               runp = runp->next;
5387             }
5388           while (ntotal > 0 && runp != ld_state.dsofiles->next);
5389
5390           if (ntotal > 0)
5391             {
5392               runp = ld_state.needed->next;
5393               do
5394                 {
5395                   offset = create_verneed_data (offset, verneeddata, runp,
5396                                                 &ntotal);
5397                   runp = runp->next;
5398                 }
5399               while (ntotal > 0 && runp != ld_state.needed->next);
5400             }
5401
5402           assert (offset == verneeddata->d_size);
5403
5404           /* Add the needed information to the section header.  */
5405           shdr->sh_link = ld_state.dynstrscnidx;
5406           shdr->sh_info = ld_state.nverdeffile;
5407           (void) xelf_update_shdr (verneedscn, shdr);
5408         }
5409
5410       /* Adjust the section size.  */
5411       dynsymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_SYM, nsym_dyn);
5412       if (versymdata != NULL)
5413         versymdata->d_size = xelf_fsize (ld_state.outelf, ELF_T_HALF,
5414                                          nsym_dyn);
5415
5416       /* Add the remaining information to the section header.  */
5417       xelf_getshdr (dynsymscn, shdr);
5418       /* There is always exactly one local symbol.  */
5419       shdr->sh_info = 1;
5420       /* Reference the string table.  */
5421       shdr->sh_link = ld_state.dynstrscnidx;
5422       /* Write the updated info back.  */
5423       (void) xelf_update_shdr (dynsymscn, shdr);
5424     }
5425   else
5426     /* We don't need the map from the symbol table index to the symbol
5427        structure anymore.  */
5428     free (ndxtosym);
5429
5430   /* We don't need the string table anymore.  */
5431   free (symstrent);
5432
5433   /* Remember the total number of symbols in the dynamic symbol table.  */
5434   ld_state.ndynsym = nsym_dyn;
5435
5436   /* Fill in the section header information.  */
5437   symscn = elf_getscn (ld_state.outelf, ld_state.symscnidx);
5438   xelf_getshdr (symscn, shdr);
5439   if (shdr == NULL)
5440     error (EXIT_FAILURE, 0,
5441            gettext ("cannot create symbol table for output file: %s"),
5442            elf_errmsg (-1));
5443
5444   shdr->sh_type = SHT_SYMTAB;
5445   shdr->sh_link = ld_state.strscnidx;
5446   shdr->sh_info = nsym_local;
5447   shdr->sh_entsize = xelf_fsize (ld_state.outelf, ELF_T_SYM, 1);
5448
5449   (void) xelf_update_shdr (symscn, shdr);
5450
5451
5452   /* Add names for the generated sections.  */
5453   if (ld_state.symscnidx != 0)
5454       symtab_ent = ebl_strtabadd (ld_state.shstrtab, ".symtab", 8);
5455   if (ld_state.xndxscnidx != 0)
5456     xndx_ent = ebl_strtabadd (ld_state.shstrtab, ".symtab_shndx", 14);
5457   if (ld_state.strscnidx != 0)
5458     strtab_ent = ebl_strtabadd (ld_state.shstrtab, ".strtab", 8);
5459   /* At this point we would have to test for failures in the
5460      allocation.  But we skip this.  First, the problem will be caught
5461      later when doing more allocations for the section header table.
5462      Even if this would not be the case all that would happen is that
5463      the section names are empty.  The binary would still be usable if
5464      it is an executable or a DSO.  Not adding the test here saves
5465      quite a bit of code.  */
5466
5467
5468   /* Finally create the section for the section header string table.  */
5469   shstrtab_scn = elf_newscn (ld_state.outelf);
5470   shstrtab_ndx = elf_ndxscn (shstrtab_scn);
5471   if (unlikely (shstrtab_ndx == SHN_UNDEF))
5472     error (EXIT_FAILURE, 0,
5473            gettext ("cannot create section header string section: %s"),
5474            elf_errmsg (-1));
5475
5476   /* Add the name of the section to the string table.  */
5477   shstrtab_ent = ebl_strtabadd (ld_state.shstrtab, ".shstrtab", 10);
5478   if (unlikely (shstrtab_ent == NULL))
5479     error (EXIT_FAILURE, errno,
5480            gettext ("cannot create section header string section"));
5481
5482   /* Finalize the section header string table.  */
5483   data = elf_newdata (shstrtab_scn);
5484   if (data == NULL)
5485     error (EXIT_FAILURE, 0,
5486            gettext ("cannot create section header string section: %s"),
5487            elf_errmsg (-1));
5488   ebl_strtabfinalize (ld_state.shstrtab, data);
5489
5490   /* Now we know the string offsets for all section names.  */
5491   for (cnt = 0; cnt < ld_state.nallsections; ++cnt)
5492     if (ld_state.allsections[cnt]->scnidx != 0)
5493       {
5494         Elf_Scn *scn;
5495
5496         scn = elf_getscn (ld_state.outelf, ld_state.allsections[cnt]->scnidx);
5497
5498         xelf_getshdr (scn, shdr);
5499         assert (shdr != NULL);
5500
5501         shdr->sh_name = ebl_strtaboffset (ld_state.allsections[cnt]->nameent);
5502
5503         if (xelf_update_shdr (scn, shdr) == 0)
5504           assert (0);
5505       }
5506
5507   /* Add the names for the generated sections to the respective
5508      section headers.  */
5509   if (symtab_ent != NULL)
5510     {
5511       Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.symscnidx);
5512
5513       xelf_getshdr (scn, shdr);
5514       /* This cannot fail, we already accessed the header before.  */
5515       assert (shdr != NULL);
5516
5517       shdr->sh_name = ebl_strtaboffset (symtab_ent);
5518
5519       (void) xelf_update_shdr (scn, shdr);
5520     }
5521   if (xndx_ent != NULL)
5522     {
5523       Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.xndxscnidx);
5524
5525       xelf_getshdr (scn, shdr);
5526       /* This cannot fail, we already accessed the header before.  */
5527       assert (shdr != NULL);
5528
5529       shdr->sh_name = ebl_strtaboffset (xndx_ent);
5530
5531       (void) xelf_update_shdr (scn, shdr);
5532     }
5533   if (strtab_ent != NULL)
5534     {
5535       Elf_Scn *scn = elf_getscn (ld_state.outelf, ld_state.strscnidx);
5536
5537       xelf_getshdr (scn, shdr);
5538       /* This cannot fail, we already accessed the header before.  */
5539       assert (shdr != NULL);
5540
5541       shdr->sh_name = ebl_strtaboffset (strtab_ent);
5542
5543       (void) xelf_update_shdr (scn, shdr);
5544     }
5545
5546   /* And the section header table section itself.  */
5547   xelf_getshdr (shstrtab_scn, shdr);
5548   if (shdr == NULL)
5549     error (EXIT_FAILURE, 0,
5550            gettext ("cannot create section header string section: %s"),
5551            elf_errmsg (-1));
5552
5553   shdr->sh_name = ebl_strtaboffset (shstrtab_ent);
5554   shdr->sh_type = SHT_STRTAB;
5555
5556   if (unlikely (xelf_update_shdr (shstrtab_scn, shdr) == 0))
5557     error (EXIT_FAILURE, 0,
5558            gettext ("cannot create section header string section: %s"),
5559            elf_errmsg (-1));
5560
5561
5562   /* Add the correct section header info to the section group sections.  */
5563   groups = ld_state.groups;
5564   while (groups != NULL)
5565     {
5566       Elf_Scn *scn = elf_getscn (ld_state.outelf, groups->outscnidx);
5567       xelf_getshdr (scn, shdr);
5568       assert (shdr != NULL);
5569
5570       shdr->sh_name = ebl_strtaboffset (groups->nameent);
5571       shdr->sh_type = SHT_GROUP;
5572       shdr->sh_flags = 0;
5573       shdr->sh_link = ld_state.symscnidx;
5574       shdr->sh_entsize = sizeof (Elf32_Word);
5575
5576       /* Determine the index for the signature symbol.  */
5577       Elf32_Word si
5578         = groups->symbol->file->symindirect[groups->symbol->symidx];
5579       if (si == 0)
5580         {
5581           assert (groups->symbol->file->symref[groups->symbol->symidx]
5582                   != NULL);
5583           si = groups->symbol->file->symref[groups->symbol->symidx]->outsymidx;
5584           assert (si != 0);
5585         }
5586       shdr->sh_info = ld_state.dblindirect[si];
5587
5588       (void) xelf_update_shdr (scn, shdr);
5589
5590       struct scngroup *oldp = groups;
5591       groups = groups->next;
5592       free (oldp);
5593     }
5594
5595
5596   if (ld_state.file_type != relocatable_file_type)
5597     {
5598       size_t nphdr;
5599       XElf_Addr addr;
5600       struct output_segment *segment;
5601       Elf_Scn *scn;
5602       Elf32_Word nsec;
5603       XElf_Phdr_vardef (phdr);
5604
5605       /* Every executable needs a program header.  The number of entries
5606          varies.  One exists for each segment.  Each SHT_NOTE section gets
5607          one, too.  For dynamically linked executables we have to create
5608          one for the program header, the interpreter, and the dynamic
5609          section.  First count the number of segments.
5610
5611          XXX Determine whether the segment is non-empty.  */
5612       nphdr = 0;
5613
5614       /* We always add a PT_GNU_stack entry.  */
5615       ++nphdr;
5616
5617       segment = ld_state.output_segments;
5618       while (segment != NULL)
5619         {
5620           ++nphdr;
5621           segment = segment->next;
5622         }
5623
5624       /* Add the number of SHT_NOTE sections.  We counted them earlier.  */
5625       nphdr += ld_state.nnotesections;
5626
5627       /* If we create a DSO or the file is linked against DSOs we have three
5628          more entries: INTERP, PHDR, DYNAMIC.  */
5629       if (dynamically_linked_p ())
5630         nphdr += 3;
5631
5632       /* Create the program header structure.  */
5633       if (xelf_newphdr (ld_state.outelf, nphdr) == 0)
5634         error (EXIT_FAILURE, 0, gettext ("cannot create program header: %s"),
5635                elf_errmsg (-1));
5636
5637
5638       /* Determine the section sizes and offsets.  We have to do this
5639          to be able to determine the memory layout (which normally
5640          differs from the file layout).  */
5641       if (elf_update (ld_state.outelf, ELF_C_NULL) == -1)
5642         error (EXIT_FAILURE, 0, gettext ("while determining file layout: %s"),
5643                elf_errmsg (-1));
5644
5645
5646       /* Now determine the memory addresses of all the sections and
5647          segments.  */
5648       nsec = 0;
5649       scn = elf_getscn (ld_state.outelf, ld_state.allsections[nsec]->scnidx);
5650       xelf_getshdr (scn, shdr);
5651       assert (shdr != NULL);
5652
5653       /* The address we start with is the offset of the first (not
5654          zeroth) section.  */
5655       addr = shdr->sh_offset;
5656
5657       /* The index of the first loadable segment.  */
5658       nphdr = 1 + (dynamically_linked_p () == true) * 2;
5659
5660       segment = ld_state.output_segments;
5661       while (segment != NULL)
5662         {
5663           struct output_rule *orule;
5664           bool first_section = true;
5665           XElf_Off nobits_size = 0;
5666           XElf_Off memsize = 0;
5667
5668           /* the minimum alignment is a page size.  */
5669           segment->align = ld_state.pagesize;
5670
5671           for (orule = segment->output_rules; orule != NULL;
5672                orule = orule->next)
5673             if (orule->tag == output_section)
5674               {
5675                 XElf_Off oldoff;
5676
5677                 /* See whether this output rule corresponds to the next
5678                    section.  Yes, this is a pointer comparison.  */
5679                 if (ld_state.allsections[nsec]->name
5680                     != orule->val.section.name)
5681                   /* No, ignore this output rule.  */
5682                   continue;
5683
5684                 /* We assign addresses only in segments which are actually
5685                    loaded.  */
5686                 if (segment->mode != 0)
5687                   {
5688                     /* Adjust the offset of the input sections.  */
5689                     struct scninfo *isect;
5690                     struct scninfo *first;
5691
5692                     isect = first = ld_state.allsections[nsec]->last;
5693                     if (isect != NULL)
5694                       do
5695                         isect->offset += addr;
5696                       while ((isect = isect->next) != first);
5697
5698                     /* Set the address of current section.  */
5699                     shdr->sh_addr = addr;
5700
5701                     /* Write the result back.  */
5702                     (void) xelf_update_shdr (scn, shdr);
5703
5704                     /* Remember the address.  */
5705                     ld_state.allsections[nsec]->addr = addr;
5706                   }
5707
5708                 if (first_section)
5709                   {
5710                     /* The first segment starts at offset zero.  */
5711                     if (segment == ld_state.output_segments)
5712                       {
5713                         segment->offset = 0;
5714                         segment->addr = addr - shdr->sh_offset;
5715                       }
5716                     else
5717                       {
5718                         segment->offset = shdr->sh_offset;
5719                         segment->addr = addr;
5720                       }
5721
5722                     /* Determine the maximum alignment requirement.  */
5723                     segment->align = MAX (segment->align, shdr->sh_addralign);
5724
5725                     first_section = false;
5726                   }
5727
5728                 memsize = shdr->sh_offset - segment->offset + shdr->sh_size;
5729                 if (nobits_size != 0 && shdr->sh_type != SHT_NOTE)
5730                   error (EXIT_FAILURE, 0, gettext ("\
5731 internal error: nobits section follows nobits section"));
5732                 if (shdr->sh_type == SHT_NOBITS)
5733                   nobits_size += shdr->sh_size;
5734
5735                 /* Determine the new address which is computed using
5736                    the difference of the offsets on the sections.  Note
5737                    that this assumes that the sections following each
5738                    other in the section header table are also
5739                    consecutive in the file.  This is true here because
5740                    libelf constructs files this way.  */
5741                 oldoff = shdr->sh_offset;
5742
5743                 if (++nsec >= ld_state.nallsections)
5744                   break;
5745
5746                 scn = elf_getscn (ld_state.outelf,
5747                                   ld_state.allsections[nsec]->scnidx);
5748                 xelf_getshdr (scn, shdr);
5749                 assert (shdr != NULL);
5750
5751                 /* This is the new address resulting from the offsets
5752                    in the file.  */
5753                 assert (oldoff <= shdr->sh_offset);
5754                 addr += shdr->sh_offset - oldoff;
5755               }
5756             else
5757               {
5758                 assert (orule->tag == output_assignment);
5759
5760                 if (strcmp (orule->val.assignment->variable, ".") == 0)
5761                   /* This is a change of the address.  */
5762                   addr = eval_expression (orule->val.assignment->expression,
5763                                           addr);
5764                 else if (orule->val.assignment->sym != NULL)
5765                   {
5766                     /* This symbol is used.  Update the symbol table
5767                        entry.  */
5768                     XElf_Sym_vardef (sym);
5769                     size_t idx;
5770
5771                     /* Note that we do not have to use
5772                        xelf_getsymshndx since we only update the
5773                        symbol address, not the section
5774                        information.  */
5775                     idx = dblindirect[orule->val.assignment->sym->outsymidx];
5776                     xelf_getsym (symdata, idx, sym);
5777                     sym->st_value = addr;
5778                     (void) xelf_update_sym (symdata, idx, sym);
5779
5780                     idx = orule->val.assignment->sym->outdynsymidx;
5781                     if (idx != 0)
5782                       {
5783                         assert (dynsymdata != NULL);
5784                         xelf_getsym (dynsymdata, idx, sym);
5785                         sym->st_value = addr;
5786                         (void) xelf_update_sym (dynsymdata, idx, sym);
5787                       }
5788                   }
5789               }
5790
5791           /* Store the segment parameter for loadable segments.  */
5792           if (segment->mode != 0)
5793             {
5794               xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
5795
5796               phdr->p_type = PT_LOAD;
5797               phdr->p_offset = segment->offset;
5798               phdr->p_vaddr = segment->addr;
5799               phdr->p_paddr = phdr->p_vaddr;
5800               phdr->p_filesz = memsize - nobits_size;
5801               phdr->p_memsz = memsize;
5802               phdr->p_flags = segment->mode;
5803               phdr->p_align = segment->align;
5804
5805               (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
5806               ++nphdr;
5807             }
5808
5809           segment = segment->next;
5810         }
5811
5812       /* Create the other program header entries.  */
5813       xelf_getehdr (ld_state.outelf, ehdr);
5814       assert (ehdr != NULL);
5815
5816       xelf_getphdr_ptr (ld_state.outelf, 0, phdr);
5817       phdr->p_type = PT_PHDR;
5818       phdr->p_offset = ehdr->e_phoff;
5819       phdr->p_vaddr = ld_state.output_segments->addr + phdr->p_offset;
5820       phdr->p_paddr = phdr->p_vaddr;
5821       phdr->p_filesz = ehdr->e_phnum * ehdr->e_phentsize;
5822       phdr->p_memsz = phdr->p_filesz;
5823       phdr->p_flags = 0;                /* No need to set PF_R or so.  */
5824       phdr->p_align = xelf_fsize (ld_state.outelf, ELF_T_ADDR, 1);
5825       (void) xelf_update_phdr (ld_state.outelf, 0, phdr);
5826
5827
5828       /* Add the stack information.  */
5829       xelf_getphdr_ptr (ld_state.outelf, nphdr, phdr);
5830       phdr->p_type = PT_GNU_STACK;
5831       phdr->p_offset = 0;
5832       phdr->p_vaddr = 0;
5833       phdr->p_paddr = 0;
5834       phdr->p_filesz = 0;
5835       phdr->p_memsz = 0;
5836       phdr->p_flags = ld_state.execstack == execstack_true ? PF_X : 0;
5837       phdr->p_align = 0;
5838
5839       (void) xelf_update_phdr (ld_state.outelf, nphdr, phdr);
5840       ++nphdr;
5841
5842
5843       /* Adjust the addresses in the address fields of the symbol
5844          records according to the load addresses of the sections.  */
5845       if (ld_state.need_symtab)
5846         for (cnt = 1; cnt < nsym; ++cnt)
5847           {
5848             XElf_Sym_vardef (sym);
5849             Elf32_Word shndx;
5850
5851             xelf_getsymshndx (symdata, xndxdata, cnt, sym, shndx);
5852             assert (sym != NULL);
5853
5854             if (sym->st_shndx != SHN_XINDEX)
5855               shndx = sym->st_shndx;
5856
5857             if ((shndx > SHN_UNDEF && shndx < SHN_LORESERVE)
5858                 || shndx > SHN_HIRESERVE)
5859               {
5860                 /* Note we subtract 1 from the section index since ALLSECTIONS
5861                    does not store the dummy section with offset zero.  */
5862                 sym->st_value += ld_state.allsections[shndx - 1]->addr;
5863
5864                 /* We don't have to use 'xelf_update_symshndx' since the
5865                    section number doesn't change.  */
5866                 (void) xelf_update_sym (symdata, cnt, sym);
5867               }
5868           }
5869
5870       if (ld_state.need_dynsym)
5871         for (cnt = 1; cnt < nsym_dyn; ++cnt)
5872           {
5873             XElf_Sym_vardef (sym);
5874
5875             xelf_getsym (dynsymdata, cnt, sym);
5876             assert (sym != NULL);
5877
5878             if (sym->st_shndx > SHN_UNDEF && sym->st_shndx < SHN_LORESERVE)
5879               {
5880                 /* Note we subtract 1 from the section index since ALLSECTIONS
5881                    does not store the dummy section with offset zero.  */
5882                 sym->st_value += ld_state.allsections[sym->st_shndx - 1]->addr;
5883
5884                 /* We don't have to use 'xelf_update_symshndx' since the
5885                    section number doesn't change.  */
5886                 (void) xelf_update_sym (dynsymdata, cnt, sym);
5887               }
5888           }
5889
5890
5891       /* Now is a good time to determine the values of all the symbols
5892          we encountered.  */
5893       // XXX This loop is very inefficient.  The hash tab iterator also
5894       // returns all symbols in DSOs.
5895       struct symbol *se;
5896       void *p = NULL;
5897       while ((se = ld_symbol_tab_iterate (&ld_state.symbol_tab, &p)) != NULL)
5898         if (! se->in_dso)
5899           {
5900             XElf_Sym_vardef (sym);
5901
5902             addr = 0;
5903
5904             if (se->outdynsymidx != 0)
5905               {
5906                 xelf_getsym (dynsymdata, se->outdynsymidx, sym);
5907                 assert (sym != NULL);
5908                 addr = sym->st_value;
5909               }
5910             else if (se->outsymidx != 0)
5911               {
5912                 assert (dblindirect[se->outsymidx] != 0);
5913                 xelf_getsym (symdata, dblindirect[se->outsymidx], sym);
5914                 assert (sym != NULL);
5915                 addr = sym->st_value;
5916               }
5917             else
5918               abort ();
5919
5920             se->merge.value = addr;
5921           }
5922
5923       /* Complete the header of the .rel.dyn/.rela.dyn section.  Point
5924          to the symbol table.  The sh_info field is left zero since
5925          there is no specific section the contained relocations are
5926          for.  */
5927       if (ld_state.reldynscnidx != 0)
5928         {
5929           assert (ld_state.dynsymscnidx != 0);
5930           scn = elf_getscn (ld_state.outelf, ld_state.reldynscnidx);
5931           xelf_getshdr (scn, shdr);
5932           assert (shdr != NULL);
5933
5934           shdr->sh_link = ld_state.dynsymscnidx;
5935
5936           (void) xelf_update_shdr (scn, shdr);
5937         }
5938
5939       /* Fill in the dynamic segment/section.  */
5940       if (dynamically_linked_p ())
5941         {
5942           Elf_Scn *outscn;
5943
5944           assert (ld_state.interpscnidx != 0);
5945           xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.interpscnidx),
5946                         shdr);
5947           assert (shdr != NULL);
5948
5949           /* The interpreter string.  */
5950           // XXX Do we need to support files (DSOs) without interpreters?
5951           xelf_getphdr_ptr (ld_state.outelf, 1, phdr);
5952           phdr->p_type = PT_INTERP;
5953           phdr->p_offset = shdr->sh_offset;
5954           phdr->p_vaddr = shdr->sh_addr;
5955           phdr->p_paddr = phdr->p_vaddr;
5956           phdr->p_filesz = shdr->sh_size;
5957           phdr->p_memsz = phdr->p_filesz;
5958           phdr->p_flags = 0;            /* No need to set PF_R or so.  */
5959           phdr->p_align = 1;            /* It's a string.  */
5960
5961           (void) xelf_update_phdr (ld_state.outelf, 1, phdr);
5962
5963           /* The pointer to the dynamic section.  We this we need to
5964              get the information for the dynamic section first.  */
5965           assert (ld_state.dynamicscnidx);
5966           outscn = elf_getscn (ld_state.outelf, ld_state.dynamicscnidx);
5967           xelf_getshdr (outscn, shdr);
5968           assert (shdr != NULL);
5969
5970           xelf_getphdr_ptr (ld_state.outelf, 2, phdr);
5971           phdr->p_type = PT_DYNAMIC;
5972           phdr->p_offset = shdr->sh_offset;
5973           phdr->p_vaddr = shdr->sh_addr;
5974           phdr->p_paddr = phdr->p_vaddr;
5975           phdr->p_filesz = shdr->sh_size;
5976           phdr->p_memsz = phdr->p_filesz;
5977           phdr->p_flags = 0;            /* No need to set PF_R or so.  */
5978           phdr->p_align = shdr->sh_addralign;
5979
5980           (void) xelf_update_phdr (ld_state.outelf, 2, phdr);
5981
5982           /* Fill in the reference to the .dynstr section.  */
5983           assert (ld_state.dynstrscnidx != 0);
5984           shdr->sh_link = ld_state.dynstrscnidx;
5985           (void) xelf_update_shdr (outscn, shdr);
5986
5987           /* And fill the remaining entries.  */
5988           Elf_Data *dyndata = elf_getdata (outscn, NULL);
5989           assert (dyndata != NULL);
5990
5991           /* Add the DT_NEEDED entries.  */
5992           if (ld_state.ndsofiles > 0)
5993             {
5994               struct usedfiles *runp = ld_state.dsofiles->next;
5995
5996               do
5997                 if (runp->used || !runp->as_needed)
5998                   {
5999                     /* Add the position-dependent flag if necessary.  */
6000                     if (runp->lazyload)
6001                       new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6002                                          DT_POSFLAG_1, DF_P1_LAZYLOAD);
6003
6004                     new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6005                                        DT_NEEDED,
6006                                        ebl_strtaboffset (runp->sonameent));
6007                   }
6008               while ((runp = runp->next) != ld_state.dsofiles->next);
6009             }
6010
6011           /* We can finish the DT_RUNPATH/DT_RPATH entries now.  */
6012           if (ld_state.rxxpath_strent != NULL)
6013             new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6014                                ld_state.rxxpath_tag,
6015                                ebl_strtaboffset (ld_state.rxxpath_strent));
6016
6017           /* Reference to initialization and finalization functions.  */
6018           // XXX This code depends on symbol table being relocated.
6019           if (ld_state.init_symbol != NULL)
6020             {
6021               XElf_Sym_vardef (sym);
6022
6023               if (ld_state.need_symtab)
6024                 xelf_getsym (symdata,
6025                              dblindirect[ld_state.init_symbol->outsymidx],
6026                              sym);
6027               else
6028                 xelf_getsym (dynsymdata, ld_state.init_symbol->outdynsymidx,
6029                              sym);
6030               assert (sym != NULL);
6031
6032               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6033                                  DT_INIT, sym->st_value);
6034             }
6035           if (ld_state.fini_symbol != NULL)
6036             {
6037               XElf_Sym_vardef (sym);
6038
6039               if (ld_state.need_symtab)
6040                 xelf_getsym (symdata,
6041                              dblindirect[ld_state.fini_symbol->outsymidx],
6042                              sym);
6043               else
6044                 xelf_getsym (dynsymdata, ld_state.fini_symbol->outdynsymidx,
6045                              sym);
6046               assert (sym != NULL);
6047
6048               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6049                                  DT_FINI, sym->st_value);
6050             }
6051           // XXX Support init,fini,preinit arrays
6052
6053           /* The hash table which comes with dynamic symbol table.  */
6054           xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.hashscnidx),
6055                         shdr);
6056           assert (shdr != NULL);
6057           new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_HASH,
6058                              shdr->sh_addr);
6059
6060           /* Reference to the symbol table section.  */
6061           assert (ld_state.dynsymscnidx != 0);
6062           xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.dynsymscnidx),
6063                         shdr);
6064           assert (shdr != NULL);
6065           new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_SYMTAB,
6066                              shdr->sh_addr);
6067
6068           new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_SYMENT,
6069                              xelf_fsize (ld_state.outelf, ELF_T_SYM, 1));
6070
6071           /* And the string table which comes with it.  */
6072           xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.dynstrscnidx),
6073                         shdr);
6074           assert (shdr != NULL);
6075           new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_STRTAB,
6076                              shdr->sh_addr);
6077
6078           new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_STRSZ,
6079                              shdr->sh_size);
6080
6081           /* Add the entries related to the .plt.  */
6082           if (ld_state.nplt > 0)
6083             {
6084               xelf_getshdr (elf_getscn (ld_state.outelf, ld_state.gotscnidx),
6085                             shdr);
6086               assert (shdr != NULL);
6087               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6088                                  // XXX This should probably be machine
6089                                  // dependent.
6090                                  DT_PLTGOT, shdr->sh_addr);
6091
6092               xelf_getshdr (elf_getscn (ld_state.outelf,
6093                                         ld_state.pltrelscnidx), shdr);
6094               assert (shdr != NULL);
6095               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6096                                  DT_PLTRELSZ, shdr->sh_size);
6097
6098               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6099                                  DT_JMPREL, shdr->sh_addr);
6100
6101               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6102                                  DT_PLTREL, REL_TYPE (statep));
6103             }
6104
6105           if (ld_state.relsize_total > 0)
6106             {
6107               int rel = REL_TYPE (statep);
6108               xelf_getshdr (elf_getscn (ld_state.outelf,
6109                                         ld_state.reldynscnidx), shdr);
6110               assert (shdr != NULL);
6111               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6112                                  rel, shdr->sh_addr);
6113
6114               /* Trick ahead.  Use arithmetic to get the right tag.
6115                  We check the validity of this assumption in the asserts.  */
6116               assert (DT_RELASZ - DT_RELA == 1);
6117               assert (DT_RELSZ - DT_REL == 1);
6118               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6119                                  rel + 1, shdr->sh_size);
6120
6121               /* Similar for the entry size tag.  */
6122               assert (DT_RELAENT - DT_RELA == 2);
6123               assert (DT_RELENT - DT_REL == 2);
6124               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6125                                  rel + 2,
6126                                  rel == DT_REL
6127                                  ? xelf_fsize (ld_state.outelf, ELF_T_REL, 1)
6128                                  : xelf_fsize (ld_state.outelf, ELF_T_RELA,
6129                                                1));
6130             }
6131
6132           if (ld_state.verneedscnidx != 0)
6133             {
6134               xelf_getshdr (elf_getscn (ld_state.outelf,
6135                                         ld_state.verneedscnidx), shdr);
6136               assert (shdr != NULL);
6137               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6138                                  DT_VERNEED, shdr->sh_addr);
6139
6140               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6141                                  DT_VERNEEDNUM, ld_state.nverdeffile);
6142             }
6143
6144           if (ld_state.versymscnidx != 0)
6145             {
6146               xelf_getshdr (elf_getscn (ld_state.outelf,
6147                                         ld_state.versymscnidx), shdr);
6148               assert (shdr != NULL);
6149               new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6150                                  DT_VERSYM, shdr->sh_addr);
6151             }
6152
6153           /* We always create the DT_DEBUG entry.  */
6154           new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_DEBUG, 0);
6155           assert (ld_state.ndynamic_filled < ld_state.ndynamic);
6156
6157           /* Add the flag words if necessary.  */
6158           if (ld_state.dt_flags != 0)
6159             new_dynamic_entry (dyndata, ld_state.ndynamic_filled++, DT_FLAGS,
6160                                ld_state.dt_flags);
6161
6162           /* Create entry for the DT_FLAGS_1 flag.  */
6163           if (ld_state.dt_flags_1 != 0)
6164             new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6165                                DT_FLAGS_1, ld_state.dt_flags_1);
6166
6167           /* Create entry for the DT_FEATURE_1 flag.  */
6168           if (ld_state.dt_feature_1 != 0)
6169             new_dynamic_entry (dyndata, ld_state.ndynamic_filled++,
6170                                DT_FEATURE_1, ld_state.dt_feature_1);
6171
6172           assert (ld_state.ndynamic_filled <= ld_state.ndynamic);
6173         }
6174     }
6175
6176
6177   // XXX The following code isn't nice.  We use two different
6178   // mechanisms to handle relocations, one for relocatable files, one
6179   // for executables and DSOs.  Maybe this is the best method but also
6180   // maybe it can be somewhat unified.
6181
6182   /* Now that we created the symbol table we can add the reference to
6183      it in the sh_link field of the section headers of the relocation
6184      sections.  */
6185   while (rellist != NULL)
6186     {
6187       assert (ld_state.file_type == relocatable_file_type);
6188       Elf_Scn *outscn;
6189
6190       outscn = elf_getscn (ld_state.outelf, rellist->scnidx);
6191       xelf_getshdr (outscn, shdr);
6192       /* This must not fail since we did it before.  */
6193       assert (shdr != NULL);
6194
6195       /* Remember the symbol table which belongs to the relocation section.  */
6196       shdr->sh_link = ld_state.symscnidx;
6197
6198       /* And the reference to the section which is relocated by this
6199          relocation section.  We use the info from the first input
6200          section but all records should have the same information.  */
6201       shdr->sh_info =
6202         rellist->scninfo->fileinfo->scninfo[SCNINFO_SHDR (rellist->scninfo->shdr).sh_info].outscnndx;
6203
6204
6205       /* Perform the actual relocations.  We only have to adjust
6206          offsets and symbol indices.  */
6207       RELOCATE_SECTION (statep, outscn, rellist->scninfo, dblindirect);
6208
6209       /* Store the changes.  */
6210       (void) xelf_update_shdr (outscn, shdr);
6211
6212       /* Up to the next relocation section.  */
6213       rellist = rellist->next;
6214     }
6215
6216   if (ld_state.rellist != NULL)
6217     {
6218       assert (ld_state.file_type != relocatable_file_type);
6219       /* Create the relocations for the output file.  */
6220       CREATE_RELOCATIONS (statep, dblindirect);
6221     }
6222
6223
6224   /* We need the ELF header once more.  */
6225   xelf_getehdr (ld_state.outelf, ehdr);
6226   assert (ehdr != NULL);
6227
6228   /* Set the section header string table index.  */
6229   if (likely (shstrtab_ndx < SHN_HIRESERVE)
6230       && likely (shstrtab_ndx != SHN_XINDEX))
6231     ehdr->e_shstrndx = shstrtab_ndx;
6232   else
6233     {
6234       /* We have to put the section index in the sh_link field of the
6235          zeroth section header.  */
6236       Elf_Scn *scn = elf_getscn (ld_state.outelf, 0);
6237
6238       xelf_getshdr (scn, shdr);
6239       if (unlikely (shdr == NULL))
6240         error (EXIT_FAILURE, 0,
6241                gettext ("cannot get header of 0th section: %s"),
6242                elf_errmsg (-1));
6243
6244       shdr->sh_link = shstrtab_ndx;
6245
6246       (void) xelf_update_shdr (scn, shdr);
6247
6248       ehdr->e_shstrndx = SHN_XINDEX;
6249     }
6250
6251   if (ld_state.file_type != relocatable_file_type)
6252     /* DSOs and executables have to define the entry point symbol.  */
6253     ehdr->e_entry = find_entry_point ();
6254
6255   if (unlikely (xelf_update_ehdr (ld_state.outelf, ehdr) == 0))
6256     error (EXIT_FAILURE, 0,
6257            gettext ("cannot update ELF header: %s"),
6258            elf_errmsg (-1));
6259
6260
6261   /* Free the data which we don't need anymore.  */
6262   free (ld_state.dblindirect);
6263
6264
6265   /* Finalize the .plt section the what belongs to them.  */
6266   FINALIZE_PLT (statep, nsym, nsym_dyn);
6267
6268   return 0;
6269 }
6270
6271
6272 /* This is a function which must be specified in all backends.  */
6273 static void
6274 ld_generic_relocate_section (struct ld_state *statep, Elf_Scn *outscn,
6275                              struct scninfo *firstp,
6276                              const Elf32_Word *dblindirect)
6277 {
6278   error (EXIT_FAILURE, 0, gettext ("\
6279 linker backend didn't specify function to relocate section"));
6280   /* NOTREACHED */
6281 }
6282
6283
6284 /* Finalize the output file.  */
6285 static int
6286 ld_generic_finalize (struct ld_state *statep)
6287 {
6288   /* Write out the ELF file data.  */
6289   if (elf_update (ld_state.outelf, ELF_C_WRITE) == -1)
6290       error (EXIT_FAILURE, 0, gettext ("while writing output file: %s"),
6291              elf_errmsg (-1));
6292
6293   /* Free the resources.  */
6294   if (elf_end (ld_state.outelf) != 0)
6295     error (EXIT_FAILURE, 0, gettext ("while finishing output file: %s"),
6296            elf_errmsg (-1));
6297
6298   /* Get the file status of the temporary file.  */
6299   struct stat temp_st;
6300   if (fstat (ld_state.outfd, &temp_st) != 0)
6301     error (EXIT_FAILURE, errno, gettext ("cannot stat output file"));
6302
6303   /* Now it's time to rename the file.  Remove an old existing file
6304      first.  */
6305   if (rename (ld_state.tempfname, ld_state.outfname) != 0)
6306     /* Something went wrong.  */
6307     error (EXIT_FAILURE, errno, gettext ("cannot rename output file"));
6308
6309   /* Make sure the output file is really the one we created.  */
6310   struct stat new_st;
6311   if (stat (ld_state.outfname, &new_st) != 0
6312       || new_st.st_ino != temp_st.st_ino
6313       || new_st.st_dev != temp_st.st_dev)
6314     {
6315       /* Wow, somebody overwrote the output file, probably some intruder.  */
6316       unlink (ld_state.outfname);
6317       error (EXIT_FAILURE, 0, gettext ("\
6318 WARNING: temporary output file overwritten before linking finished"));
6319     }
6320
6321   /* Close the file descriptor.  */
6322   (void) close (ld_state.outfd);
6323
6324   /* Signal the cleanup handler that the file is correctly created.  */
6325   ld_state.tempfname = NULL;
6326
6327   return 0;
6328 }
6329
6330
6331 static bool
6332 ld_generic_special_section_number_p (struct ld_state *statep, size_t number)
6333 {
6334   /* There are no special section numbers in the gABI.  */
6335   return false;
6336 }
6337
6338
6339 static bool
6340 ld_generic_section_type_p (struct ld_state *statep, GElf_Word type)
6341 {
6342   if (type < SHT_NUM
6343       /* XXX Enable the following two when implemented.  */
6344       // || type == SHT_GNU_LIBLIST
6345       // || type == SHT_CHECKSUM
6346       /* XXX Eventually include SHT_SUNW_move, SHT_SUNW_COMDAT, and
6347          SHT_SUNW_syminfo.  */
6348       || (type >= SHT_GNU_verdef && type <= SHT_GNU_versym))
6349     return true;
6350
6351   return false;
6352 }
6353
6354
6355 static XElf_Xword
6356 ld_generic_dynamic_section_flags (struct ld_state *statep)
6357 {
6358   /* By default the .dynamic section is writable (and is of course
6359      loaded).  Few architecture differ from this.  */
6360   return SHF_ALLOC | SHF_WRITE;
6361 }
6362
6363
6364 static void
6365 ld_generic_initialize_plt (struct ld_state *statep, Elf_Scn *scn)
6366 {
6367   /* This cannot be implemented generally.  There should have been a
6368      machine dependent implementation and we should never have arrived
6369      here.  */
6370   error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
6371          "initialize_plt");
6372 }
6373
6374
6375 static void
6376 ld_generic_initialize_pltrel (struct ld_state *statep, Elf_Scn *scn)
6377 {
6378   /* This cannot be implemented generally.  There should have been a
6379      machine dependent implementation and we should never have arrived
6380      here.  */
6381   error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
6382          "initialize_pltrel");
6383 }
6384
6385
6386 static void
6387 ld_generic_initialize_got (struct ld_state *statep, Elf_Scn *scn)
6388 {
6389   /* This cannot be implemented generally.  There should have been a
6390      machine dependent implementation and we should never have arrived
6391      here.  */
6392   error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
6393          "initialize_got");
6394 }
6395
6396
6397 static void
6398 ld_generic_finalize_plt (struct ld_state *statep, size_t nsym, size_t nsym_dyn)
6399 {
6400   /* By default we assume that nothing has to be done.  */
6401 }
6402
6403
6404 static int
6405 ld_generic_rel_type (struct ld_state *statep)
6406 {
6407   /* This cannot be implemented generally.  There should have been a
6408      machine dependent implementation and we should never have arrived
6409      here.  */
6410   error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
6411          "rel_type");
6412   /* Just to keep the compiler calm.  */
6413   return 0;
6414 }
6415
6416
6417 static void
6418 ld_generic_count_relocations (struct ld_state *statep, struct scninfo *scninfo)
6419 {
6420   /* This cannot be implemented generally.  There should have been a
6421      machine dependent implementation and we should never have arrived
6422      here.  */
6423   error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
6424          "count_relocations");
6425 }
6426
6427
6428 static void
6429 ld_generic_create_relocations (struct ld_state *statep,
6430                                const Elf32_Word *dblindirect)
6431 {
6432   /* This cannot be implemented generally.  There should have been a
6433      machine dependent implementation and we should never have arrived
6434      here.  */
6435   error (EXIT_FAILURE, 0, gettext ("no machine specific '%s' implementation"),
6436          "create_relocations");
6437 }