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