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