strip.c revision 6d93c8c46d9b2b381c889e5f176451996845b055
1/* Discard section not used at runtime from object files.
2   Copyright (C) 2000-2012, 2014, 2015 Red Hat, Inc.
3   This file is part of elfutils.
4   Written by Ulrich Drepper <drepper@redhat.com>, 2000.
5
6   This file is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 3 of the License, or
9   (at your option) any later version.
10
11   elfutils is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19#ifdef HAVE_CONFIG_H
20# include <config.h>
21#endif
22
23#include <argp.h>
24#include <assert.h>
25#include <byteswap.h>
26#include <endian.h>
27#include <error.h>
28#include <fcntl.h>
29#include <gelf.h>
30#include <libelf.h>
31#include <libintl.h>
32#include <locale.h>
33#include <stdbool.h>
34#include <stdio.h>
35#include <stdio_ext.h>
36#include <stdlib.h>
37#include <string.h>
38#include <unistd.h>
39#include <sys/param.h>
40#include <sys/stat.h>
41#include <sys/time.h>
42
43#include <elf-knowledge.h>
44#include <libebl.h>
45#include <system.h>
46
47typedef uint8_t GElf_Byte;
48
49/* Name and version of program.  */
50static void print_version (FILE *stream, struct argp_state *state);
51ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
52
53/* Bug report address.  */
54ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
55
56
57/* Values for the parameters which have no short form.  */
58#define OPT_REMOVE_COMMENT	0x100
59#define OPT_PERMISSIVE		0x101
60#define OPT_STRIP_SECTIONS	0x102
61#define OPT_RELOC_DEBUG 	0x103
62
63
64/* Definitions of arguments for argp functions.  */
65static const struct argp_option options[] =
66{
67  { NULL, 0, NULL, 0, N_("Output selection:"), 0 },
68  { "output", 'o', "FILE", 0, N_("Place stripped output into FILE"), 0 },
69  { NULL, 'f', "FILE", 0, N_("Extract the removed sections into FILE"), 0 },
70  { NULL, 'F', "FILE", 0, N_("Embed name FILE instead of -f argument"), 0 },
71
72  { NULL, 0, NULL, 0, N_("Output options:"), 0 },
73  { "strip-all", 's', NULL, OPTION_HIDDEN, NULL, 0 },
74  { "strip-debug", 'g', NULL, 0, N_("Remove all debugging symbols"), 0 },
75  { NULL, 'd', NULL, OPTION_ALIAS, NULL, 0 },
76  { NULL, 'S', NULL, OPTION_ALIAS, NULL, 0 },
77  { "strip-sections", OPT_STRIP_SECTIONS, NULL, 0,
78    N_("Remove section headers (not recommended)"), 0 },
79  { "preserve-dates", 'p', NULL, 0,
80    N_("Copy modified/access timestamps to the output"), 0 },
81  { "reloc-debug-sections", OPT_RELOC_DEBUG, NULL, 0,
82    N_("Resolve all trivial relocations between debug sections if the removed sections are placed in a debug file (only relevant for ET_REL files, operation is not reversable, needs -f)"), 0 },
83  { "remove-comment", OPT_REMOVE_COMMENT, NULL, 0,
84    N_("Remove .comment section"), 0 },
85  { "remove-section", 'R', "SECTION", OPTION_HIDDEN, NULL, 0 },
86  { "permissive", OPT_PERMISSIVE, NULL, 0,
87    N_("Relax a few rules to handle slightly broken ELF files"), 0 },
88  { NULL, 0, NULL, 0, NULL, 0 }
89};
90
91/* Short description of program.  */
92static const char doc[] = N_("Discard symbols from object files.");
93
94/* Strings for arguments in help texts.  */
95static const char args_doc[] = N_("[FILE...]");
96
97/* Prototype for option handler.  */
98static error_t parse_opt (int key, char *arg, struct argp_state *state);
99
100/* Data structure to communicate with argp functions.  */
101static struct argp argp =
102{
103  options, parse_opt, args_doc, doc, NULL, NULL, NULL
104};
105
106
107/* Print symbols in file named FNAME.  */
108static int process_file (const char *fname);
109
110/* Handle one ELF file.  */
111static int handle_elf (int fd, Elf *elf, const char *prefix,
112		       const char *fname, mode_t mode, struct timespec tvp[2]);
113
114/* Handle all files contained in the archive.  */
115static int handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
116		      struct timespec tvp[2]);
117
118static int debug_fd = -1;
119static char *tmp_debug_fname = NULL;
120
121/* Close debug file descriptor, if opened. And remove temporary debug file.  */
122static void cleanup_debug ();
123
124#define INTERNAL_ERROR(fname) \
125  do { \
126    cleanup_debug (); \
127    error (EXIT_FAILURE, 0, gettext ("%s: INTERNAL ERROR %d (%s): %s"),      \
128	   fname, __LINE__, PACKAGE_VERSION, elf_errmsg (-1)); \
129  } while (0)
130
131
132/* Name of the output file.  */
133static const char *output_fname;
134
135/* Name of the debug output file.  */
136static const char *debug_fname;
137
138/* Name to pretend the debug output file has.  */
139static const char *debug_fname_embed;
140
141/* If true output files shall have same date as the input file.  */
142static bool preserve_dates;
143
144/* If true .comment sections will be removed.  */
145static bool remove_comment;
146
147/* If true remove all debug sections.  */
148static bool remove_debug;
149
150/* If true remove all section headers.  */
151static bool remove_shdrs;
152
153/* If true relax some ELF rules for input files.  */
154static bool permissive;
155
156/* If true perform relocations between debug sections.  */
157static bool reloc_debug;
158
159
160int
161main (int argc, char *argv[])
162{
163  int remaining;
164  int result = 0;
165
166  /* We use no threads here which can interfere with handling a stream.  */
167  __fsetlocking (stdin, FSETLOCKING_BYCALLER);
168  __fsetlocking (stdout, FSETLOCKING_BYCALLER);
169  __fsetlocking (stderr, FSETLOCKING_BYCALLER);
170
171  /* Set locale.  */
172  setlocale (LC_ALL, "");
173
174  /* Make sure the message catalog can be found.  */
175  bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
176
177  /* Initialize the message catalog.  */
178  textdomain (PACKAGE_TARNAME);
179
180  /* Parse and process arguments.  */
181  if (argp_parse (&argp, argc, argv, 0, &remaining, NULL) != 0)
182    return EXIT_FAILURE;
183
184  if (reloc_debug && debug_fname == NULL)
185    error (EXIT_FAILURE, 0,
186	   gettext ("--reloc-debug-sections used without -f"));
187
188  /* Tell the library which version we are expecting.  */
189  elf_version (EV_CURRENT);
190
191  if (remaining == argc)
192    /* The user didn't specify a name so we use a.out.  */
193    result = process_file ("a.out");
194  else
195    {
196      /* If we have seen the '-o' or '-f' option there must be exactly one
197	 input file.  */
198      if ((output_fname != NULL || debug_fname != NULL)
199	  && remaining + 1 < argc)
200	error (EXIT_FAILURE, 0, gettext ("\
201Only one input file allowed together with '-o' and '-f'"));
202
203      /* Process all the remaining files.  */
204      do
205	result |= process_file (argv[remaining]);
206      while (++remaining < argc);
207    }
208
209  return result;
210}
211
212
213/* Print the version information.  */
214static void
215print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
216{
217  fprintf (stream, "strip (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
218  fprintf (stream, gettext ("\
219Copyright (C) %s Red Hat, Inc.\n\
220This is free software; see the source for copying conditions.  There is NO\n\
221warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
222"), "2012");
223  fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
224}
225
226
227/* Handle program arguments.  */
228static error_t
229parse_opt (int key, char *arg, struct argp_state *state)
230{
231  switch (key)
232    {
233    case 'f':
234      if (debug_fname != NULL)
235	{
236	  error (0, 0, gettext ("-f option specified twice"));
237	  return EINVAL;
238	}
239      debug_fname = arg;
240      break;
241
242    case 'F':
243      if (debug_fname_embed != NULL)
244	{
245	  error (0, 0, gettext ("-F option specified twice"));
246	  return EINVAL;
247	}
248      debug_fname_embed = arg;
249      break;
250
251    case 'o':
252      if (output_fname != NULL)
253	{
254	  error (0, 0, gettext ("-o option specified twice"));
255	  return EINVAL;
256	}
257      output_fname = arg;
258      break;
259
260    case 'p':
261      preserve_dates = true;
262      break;
263
264    case OPT_RELOC_DEBUG:
265      reloc_debug = true;
266      break;
267
268    case OPT_REMOVE_COMMENT:
269      remove_comment = true;
270      break;
271
272    case 'R':
273      if (!strcmp (arg, ".comment"))
274	remove_comment = true;
275      else
276	{
277	  argp_error (state,
278		      gettext ("-R option supports only .comment section"));
279	  return EINVAL;
280	}
281      break;
282
283    case 'g':
284    case 'd':
285    case 'S':
286      remove_debug = true;
287      break;
288
289    case OPT_STRIP_SECTIONS:
290      remove_shdrs = true;
291      break;
292
293    case OPT_PERMISSIVE:
294      permissive = true;
295      break;
296
297    case 's':			/* Ignored for compatibility.  */
298      break;
299
300    default:
301      return ARGP_ERR_UNKNOWN;
302    }
303  return 0;
304}
305
306
307static int
308process_file (const char *fname)
309{
310  /* If we have to preserve the modify and access timestamps get them
311     now.  We cannot use fstat() after opening the file since the open
312     would change the access time.  */
313  struct stat64 pre_st;
314  struct timespec tv[2];
315 again:
316  if (preserve_dates)
317    {
318      if (stat64 (fname, &pre_st) != 0)
319	{
320	  error (0, errno, gettext ("cannot stat input file '%s'"), fname);
321	  return 1;
322	}
323
324      /* If we have to preserve the timestamp, we need it in the
325	 format utimes() understands.  */
326      tv[0] = pre_st.st_atim;
327      tv[1] = pre_st.st_mtim;
328    }
329
330  /* Open the file.  */
331  int fd = open (fname, output_fname == NULL ? O_RDWR : O_RDONLY);
332  if (fd == -1)
333    {
334      error (0, errno, gettext ("while opening '%s'"), fname);
335      return 1;
336    }
337
338  /* We always use fstat() even if we called stat() before.  This is
339     done to make sure the information returned by stat() is for the
340     same file.  */
341  struct stat64 st;
342  if (fstat64 (fd, &st) != 0)
343    {
344      error (0, errno, gettext ("cannot stat input file '%s'"), fname);
345      return 1;
346    }
347  /* Paranoid mode on.  */
348  if (preserve_dates
349      && (st.st_ino != pre_st.st_ino || st.st_dev != pre_st.st_dev))
350    {
351      /* We detected a race.  Try again.  */
352      close (fd);
353      goto again;
354    }
355
356  /* Now get the ELF descriptor.  */
357  Elf *elf = elf_begin (fd, output_fname == NULL ? ELF_C_RDWR : ELF_C_READ,
358			NULL);
359  int result;
360  switch (elf_kind (elf))
361    {
362    case ELF_K_ELF:
363      result = handle_elf (fd, elf, NULL, fname, st.st_mode & ACCESSPERMS,
364			   preserve_dates ? tv : NULL);
365      break;
366
367    case ELF_K_AR:
368      /* It is not possible to strip the content of an archive direct
369	 the output to a specific file.  */
370      if (unlikely (output_fname != NULL || debug_fname != NULL))
371	{
372	  error (0, 0, gettext ("%s: cannot use -o or -f when stripping archive"),
373		 fname);
374	  result = 1;
375	}
376      else
377	result = handle_ar (fd, elf, NULL, fname, preserve_dates ? tv : NULL);
378      break;
379
380    default:
381      error (0, 0, gettext ("%s: File format not recognized"), fname);
382      result = 1;
383      break;
384    }
385
386  if (unlikely (elf_end (elf) != 0))
387    INTERNAL_ERROR (fname);
388
389  close (fd);
390
391  return result;
392}
393
394
395/* Maximum size of array allocated on stack.  */
396#define MAX_STACK_ALLOC	(400 * 1024)
397
398static int
399handle_elf (int fd, Elf *elf, const char *prefix, const char *fname,
400	    mode_t mode, struct timespec tvp[2])
401{
402  size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
403  size_t fname_len = strlen (fname) + 1;
404  char *fullname = alloca (prefix_len + 1 + fname_len);
405  char *cp = fullname;
406  Elf *debugelf = NULL;
407  tmp_debug_fname = NULL;
408  int result = 0;
409  size_t shdridx = 0;
410  size_t shstrndx;
411  struct shdr_info
412  {
413    Elf_Scn *scn;
414    GElf_Shdr shdr;
415    Elf_Data *data;
416    Elf_Data *debug_data;
417    const char *name;
418    Elf32_Word idx;		/* Index in new file.  */
419    Elf32_Word old_sh_link;	/* Original value of shdr.sh_link.  */
420    Elf32_Word symtab_idx;
421    Elf32_Word version_idx;
422    Elf32_Word group_idx;
423    Elf32_Word group_cnt;
424    Elf_Scn *newscn;
425    struct Ebl_Strent *se;
426    Elf32_Word *newsymidx;
427  } *shdr_info = NULL;
428  Elf_Scn *scn;
429  size_t cnt;
430  size_t idx;
431  bool changes;
432  GElf_Ehdr newehdr_mem;
433  GElf_Ehdr *newehdr;
434  GElf_Ehdr debugehdr_mem;
435  GElf_Ehdr *debugehdr;
436  struct Ebl_Strtab *shst = NULL;
437  Elf_Data debuglink_crc_data;
438  bool any_symtab_changes = false;
439  Elf_Data *shstrtab_data = NULL;
440  void *debuglink_buf = NULL;
441
442  /* Create the full name of the file.  */
443  if (prefix != NULL)
444    {
445      cp = mempcpy (cp, prefix, prefix_len);
446      *cp++ = ':';
447    }
448  memcpy (cp, fname, fname_len);
449
450  /* If we are not replacing the input file open a new file here.  */
451  if (output_fname != NULL)
452    {
453      fd = open (output_fname, O_RDWR | O_CREAT, mode);
454      if (unlikely (fd == -1))
455	{
456	  error (0, errno, gettext ("cannot open '%s'"), output_fname);
457	  return 1;
458	}
459    }
460
461  debug_fd = -1;
462
463  /* Get the EBL handling.  Removing all debugging symbols with the -g
464     option or resolving all relocations between debug sections with
465     the --reloc-debug-sections option are currently the only reasons
466     we need EBL so don't open the backend unless necessary.  */
467  Ebl *ebl = NULL;
468  if (remove_debug || reloc_debug)
469    {
470      ebl = ebl_openbackend (elf);
471      if (ebl == NULL)
472	{
473	  error (0, errno, gettext ("cannot open EBL backend"));
474	  result = 1;
475	  goto fail;
476	}
477    }
478
479  /* Open the additional file the debug information will be stored in.  */
480  if (debug_fname != NULL)
481    {
482      /* Create a temporary file name.  We do not want to overwrite
483	 the debug file if the file would not contain any
484	 information.  */
485      size_t debug_fname_len = strlen (debug_fname);
486      tmp_debug_fname = (char *) xmalloc (debug_fname_len + sizeof (".XXXXXX"));
487      strcpy (mempcpy (tmp_debug_fname, debug_fname, debug_fname_len),
488	      ".XXXXXX");
489
490      debug_fd = mkstemp (tmp_debug_fname);
491      if (unlikely (debug_fd == -1))
492	{
493	  error (0, errno, gettext ("cannot open '%s'"), debug_fname);
494	  result = 1;
495	  goto fail;
496	}
497    }
498
499  /* Get the information from the old file.  */
500  GElf_Ehdr ehdr_mem;
501  GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
502  if (ehdr == NULL)
503    INTERNAL_ERROR (fname);
504
505  /* Get the section header string table index.  */
506  if (unlikely (elf_getshdrstrndx (elf, &shstrndx) < 0))
507    {
508      cleanup_debug ();
509      error (EXIT_FAILURE, 0,
510	     gettext ("cannot get section header string table index"));
511    }
512
513  /* Get the number of phdrs in the old file.  */
514  size_t phnum;
515  if (elf_getphdrnum (elf, &phnum) != 0)
516    {
517      cleanup_debug ();
518      error (EXIT_FAILURE, 0, gettext ("cannot get number of phdrs"));
519    }
520
521  /* We now create a new ELF descriptor for the same file.  We
522     construct it almost exactly in the same way with some information
523     dropped.  */
524  Elf *newelf;
525  if (output_fname != NULL)
526    newelf = elf_begin (fd, ELF_C_WRITE_MMAP, NULL);
527  else
528    newelf = elf_clone (elf, ELF_C_EMPTY);
529
530  if (unlikely (gelf_newehdr (newelf, gelf_getclass (elf)) == 0)
531      || (ehdr->e_type != ET_REL
532	  && unlikely (gelf_newphdr (newelf, phnum) == 0)))
533    {
534      error (0, 0, gettext ("cannot create new file '%s': %s"),
535	     output_fname ?: fname, elf_errmsg (-1));
536      goto fail;
537    }
538
539  /* Copy over the old program header if needed.  */
540  if (ehdr->e_type != ET_REL)
541    for (cnt = 0; cnt < phnum; ++cnt)
542      {
543	GElf_Phdr phdr_mem;
544	GElf_Phdr *phdr = gelf_getphdr (elf, cnt, &phdr_mem);
545	if (phdr == NULL
546	    || unlikely (gelf_update_phdr (newelf, cnt, phdr) == 0))
547	  INTERNAL_ERROR (fname);
548      }
549
550  if (debug_fname != NULL)
551    {
552      /* Also create an ELF descriptor for the debug file */
553      debugelf = elf_begin (debug_fd, ELF_C_WRITE_MMAP, NULL);
554      if (unlikely (gelf_newehdr (debugelf, gelf_getclass (elf)) == 0)
555	  || (ehdr->e_type != ET_REL
556	      && unlikely (gelf_newphdr (debugelf, phnum) == 0)))
557	{
558	  error (0, 0, gettext ("cannot create new file '%s': %s"),
559		 debug_fname, elf_errmsg (-1));
560	  goto fail_close;
561	}
562
563      /* Copy over the old program header if needed.  */
564      if (ehdr->e_type != ET_REL)
565	for (cnt = 0; cnt < phnum; ++cnt)
566	  {
567	    GElf_Phdr phdr_mem;
568	    GElf_Phdr *phdr = gelf_getphdr (elf, cnt, &phdr_mem);
569	    if (phdr == NULL
570		|| unlikely (gelf_update_phdr (debugelf, cnt, phdr) == 0))
571	      INTERNAL_ERROR (fname);
572	  }
573    }
574
575  /* Number of sections.  */
576  size_t shnum;
577  if (unlikely (elf_getshdrnum (elf, &shnum) < 0))
578    {
579      error (0, 0, gettext ("cannot determine number of sections: %s"),
580	     elf_errmsg (-1));
581      goto fail_close;
582    }
583
584  if (shstrndx >= shnum)
585    goto illformed;
586
587#define elf_assert(test) do { if (!(test)) goto illformed; } while (0)
588
589  /* Storage for section information.  We leave room for two more
590     entries since we unconditionally create a section header string
591     table.  Maybe some weird tool created an ELF file without one.
592     The other one is used for the debug link section.  */
593  if ((shnum + 2) * sizeof (struct shdr_info) > MAX_STACK_ALLOC)
594    shdr_info = (struct shdr_info *) xcalloc (shnum + 2,
595					      sizeof (struct shdr_info));
596  else
597    {
598      shdr_info = (struct shdr_info *) alloca ((shnum + 2)
599					       * sizeof (struct shdr_info));
600      memset (shdr_info, '\0', (shnum + 2) * sizeof (struct shdr_info));
601    }
602
603  /* Prepare section information data structure.  */
604  scn = NULL;
605  cnt = 1;
606  while ((scn = elf_nextscn (elf, scn)) != NULL)
607    {
608      /* This should always be true (i.e., there should not be any
609	 holes in the numbering).  */
610      elf_assert (elf_ndxscn (scn) == cnt);
611
612      shdr_info[cnt].scn = scn;
613
614      /* Get the header.  */
615      if (gelf_getshdr (scn, &shdr_info[cnt].shdr) == NULL)
616	INTERNAL_ERROR (fname);
617
618      /* Get the name of the section.  */
619      shdr_info[cnt].name = elf_strptr (elf, shstrndx,
620					shdr_info[cnt].shdr.sh_name);
621      if (shdr_info[cnt].name == NULL)
622	{
623	illformed:
624	  error (0, 0, gettext ("illformed file '%s'"), fname);
625	  goto fail_close;
626	}
627
628      /* Mark them as present but not yet investigated.  */
629      shdr_info[cnt].idx = 1;
630
631      /* Remember the shdr.sh_link value.  */
632      shdr_info[cnt].old_sh_link = shdr_info[cnt].shdr.sh_link;
633      if (shdr_info[cnt].old_sh_link >= shnum)
634	goto illformed;
635
636      /* Sections in files other than relocatable object files which
637	 don't contain any file content or are not loaded can be freely
638	 moved by us.  In relocatable object files everything can be moved.  */
639      if (ehdr->e_type == ET_REL
640	  || shdr_info[cnt].shdr.sh_type == SHT_NOBITS
641	  || (shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) == 0)
642	shdr_info[cnt].shdr.sh_offset = 0;
643
644      /* If this is an extended section index table store an
645	 appropriate reference.  */
646      if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB_SHNDX))
647	{
648	  elf_assert (shdr_info[shdr_info[cnt].shdr.sh_link].symtab_idx == 0);
649	  shdr_info[shdr_info[cnt].shdr.sh_link].symtab_idx = cnt;
650	}
651      else if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_GROUP))
652	{
653	  /* Cross-reference the sections contained in the section
654	     group.  */
655	  shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
656	  if (shdr_info[cnt].data == NULL
657	      || shdr_info[cnt].data->d_size < sizeof (Elf32_Word))
658	    INTERNAL_ERROR (fname);
659
660	  /* XXX Fix for unaligned access.  */
661	  Elf32_Word *grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
662	  size_t inner;
663	  for (inner = 1;
664	       inner < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
665	       ++inner)
666	    {
667	      if (grpref[inner] < shnum)
668		shdr_info[grpref[inner]].group_idx = cnt;
669	      else
670		goto illformed;
671	    }
672
673	  if (inner == 1 || (inner == 2 && (grpref[0] & GRP_COMDAT) == 0))
674	    /* If the section group contains only one element and this
675	       is n COMDAT section we can drop it right away.  */
676	    shdr_info[cnt].idx = 0;
677	  else
678	    shdr_info[cnt].group_cnt = inner - 1;
679	}
680      else if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_GNU_versym))
681	{
682	  elf_assert (shdr_info[shdr_info[cnt].shdr.sh_link].version_idx == 0);
683	  shdr_info[shdr_info[cnt].shdr.sh_link].version_idx = cnt;
684	}
685
686      /* If this section is part of a group make sure it is not
687	 discarded right away.  */
688      if ((shdr_info[cnt].shdr.sh_flags & SHF_GROUP) != 0)
689	{
690	  elf_assert (shdr_info[cnt].group_idx != 0);
691
692	  if (shdr_info[shdr_info[cnt].group_idx].idx == 0)
693	    {
694	      /* The section group section will be removed.  */
695	      shdr_info[cnt].group_idx = 0;
696	      shdr_info[cnt].shdr.sh_flags &= ~SHF_GROUP;
697	    }
698	}
699
700      /* Increment the counter.  */
701      ++cnt;
702    }
703
704  /* Now determine which sections can go away.  The general rule is that
705     all sections which are not used at runtime are stripped out.  But
706     there are a few exceptions:
707
708     - special sections named ".comment" and ".note" are kept
709     - OS or architecture specific sections are kept since we might not
710       know how to handle them
711     - if a section is referred to from a section which is not removed
712       in the sh_link or sh_info element it cannot be removed either
713  */
714  for (cnt = 1; cnt < shnum; ++cnt)
715    /* Check whether the section can be removed.  */
716    if (remove_shdrs ? !(shdr_info[cnt].shdr.sh_flags & SHF_ALLOC)
717	: ebl_section_strip_p (ebl, ehdr, &shdr_info[cnt].shdr,
718			       shdr_info[cnt].name, remove_comment,
719			       remove_debug))
720      {
721	/* For now assume this section will be removed.  */
722	shdr_info[cnt].idx = 0;
723
724	idx = shdr_info[cnt].group_idx;
725	while (idx != 0)
726	  {
727	    /* The section group data is already loaded.  */
728	    elf_assert (shdr_info[idx].data != NULL
729			&& shdr_info[idx].data->d_buf != NULL
730			&& shdr_info[idx].data->d_size >= sizeof (Elf32_Word));
731
732	    /* If the references section group is a normal section
733	       group and has one element remaining, or if it is an
734	       empty COMDAT section group it is removed.  */
735	    bool is_comdat = (((Elf32_Word *) shdr_info[idx].data->d_buf)[0]
736			      & GRP_COMDAT) != 0;
737
738	    --shdr_info[idx].group_cnt;
739	    if ((!is_comdat && shdr_info[idx].group_cnt == 1)
740		|| (is_comdat && shdr_info[idx].group_cnt == 0))
741	      {
742		shdr_info[idx].idx = 0;
743		/* Continue recursively.  */
744		idx = shdr_info[idx].group_idx;
745	      }
746	    else
747	      break;
748	  }
749      }
750
751  /* Mark the SHT_NULL section as handled.  */
752  shdr_info[0].idx = 2;
753
754
755  /* Handle exceptions: section groups and cross-references.  We might
756     have to repeat this a few times since the resetting of the flag
757     might propagate.  */
758  do
759    {
760      changes = false;
761
762      for (cnt = 1; cnt < shnum; ++cnt)
763	{
764	  if (shdr_info[cnt].idx == 0)
765	    {
766	      /* If a relocation section is marked as being removed make
767		 sure the section it is relocating is removed, too.  */
768	      if (shdr_info[cnt].shdr.sh_type == SHT_REL
769		   || shdr_info[cnt].shdr.sh_type == SHT_RELA)
770		{
771		  if (shdr_info[cnt].shdr.sh_info >= shnum)
772		    goto illformed;
773		  else if (shdr_info[shdr_info[cnt].shdr.sh_info].idx != 0)
774		    shdr_info[cnt].idx = 1;
775		}
776
777	      /* If a group section is marked as being removed make
778		 sure all the sections it contains are being removed, too.  */
779	      if (shdr_info[cnt].shdr.sh_type == SHT_GROUP)
780		{
781		  Elf32_Word *grpref;
782		  grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
783		  for (size_t in = 1;
784		       in < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
785		       ++in)
786		    if (grpref[in] < shnum)
787		      {
788			if (shdr_info[grpref[in]].idx != 0)
789			  {
790			    shdr_info[cnt].idx = 1;
791			    break;
792			  }
793		      }
794		    else
795		      goto illformed;
796		}
797	    }
798
799	  if (shdr_info[cnt].idx == 1)
800	    {
801	      /* The content of symbol tables we don't remove must not
802		 reference any section which we do remove.  Otherwise
803		 we cannot remove the section.  */
804	      if (debug_fname != NULL
805		  && shdr_info[cnt].debug_data == NULL
806		  && (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM
807		      || shdr_info[cnt].shdr.sh_type == SHT_SYMTAB))
808		{
809		  /* Make sure the data is loaded.  */
810		  if (shdr_info[cnt].data == NULL)
811		    {
812		      shdr_info[cnt].data
813			= elf_getdata (shdr_info[cnt].scn, NULL);
814		      if (shdr_info[cnt].data == NULL)
815			INTERNAL_ERROR (fname);
816		    }
817		  Elf_Data *symdata = shdr_info[cnt].data;
818
819		  /* If there is an extended section index table load it
820		     as well.  */
821		  if (shdr_info[cnt].symtab_idx != 0
822		      && shdr_info[shdr_info[cnt].symtab_idx].data == NULL)
823		    {
824		      elf_assert (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB);
825
826		      shdr_info[shdr_info[cnt].symtab_idx].data
827			= elf_getdata (shdr_info[shdr_info[cnt].symtab_idx].scn,
828				       NULL);
829		      if (shdr_info[shdr_info[cnt].symtab_idx].data == NULL)
830			INTERNAL_ERROR (fname);
831		    }
832		  Elf_Data *xndxdata
833		    = shdr_info[shdr_info[cnt].symtab_idx].data;
834
835		  /* Go through all symbols and make sure the section they
836		     reference is not removed.  */
837		  size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
838
839		  for (size_t inner = 0;
840		       inner < shdr_info[cnt].data->d_size / elsize;
841		       ++inner)
842		    {
843		      GElf_Sym sym_mem;
844		      Elf32_Word xndx;
845		      GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
846							inner, &sym_mem,
847							&xndx);
848		      if (sym == NULL)
849			INTERNAL_ERROR (fname);
850
851		      size_t scnidx = sym->st_shndx;
852		      if (scnidx == SHN_UNDEF || scnidx >= shnum
853			  || (scnidx >= SHN_LORESERVE
854			      && scnidx <= SHN_HIRESERVE
855			      && scnidx != SHN_XINDEX)
856			  /* Don't count in the section symbols.  */
857			  || GELF_ST_TYPE (sym->st_info) == STT_SECTION)
858			/* This is no section index, leave it alone.  */
859			continue;
860		      else if (scnidx == SHN_XINDEX)
861			scnidx = xndx;
862
863		      if (scnidx >= shnum)
864			goto illformed;
865
866		      if (shdr_info[scnidx].idx == 0)
867			/* This symbol table has a real symbol in
868			   a discarded section.  So preserve the
869			   original table in the debug file.  */
870			shdr_info[cnt].debug_data = symdata;
871		    }
872		}
873
874	      /* Cross referencing happens:
875		 - for the cases the ELF specification says.  That are
876		   + SHT_DYNAMIC in sh_link to string table
877		   + SHT_HASH in sh_link to symbol table
878		   + SHT_REL and SHT_RELA in sh_link to symbol table
879		   + SHT_SYMTAB and SHT_DYNSYM in sh_link to string table
880		   + SHT_GROUP in sh_link to symbol table
881		   + SHT_SYMTAB_SHNDX in sh_link to symbol table
882		   Other (OS or architecture-specific) sections might as
883		   well use this field so we process it unconditionally.
884		 - references inside section groups
885		 - specially marked references in sh_info if the SHF_INFO_LINK
886		 flag is set
887	      */
888
889	      if (shdr_info[shdr_info[cnt].shdr.sh_link].idx == 0)
890		{
891		  shdr_info[shdr_info[cnt].shdr.sh_link].idx = 1;
892		  changes |= shdr_info[cnt].shdr.sh_link < cnt;
893		}
894
895	      /* Handle references through sh_info.  */
896	      if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
897		{
898		  if (shdr_info[cnt].shdr.sh_info >= shnum)
899		    goto illformed;
900		  else if ( shdr_info[shdr_info[cnt].shdr.sh_info].idx == 0)
901		    {
902		      shdr_info[shdr_info[cnt].shdr.sh_info].idx = 1;
903		      changes |= shdr_info[cnt].shdr.sh_info < cnt;
904		    }
905		}
906
907	      /* Mark the section as investigated.  */
908	      shdr_info[cnt].idx = 2;
909	    }
910
911	  if (debug_fname != NULL
912	      && (shdr_info[cnt].idx == 0 || shdr_info[cnt].debug_data != NULL))
913	    {
914	      /* This section is being preserved in the debug file.
915		 Sections it refers to must be preserved there too.
916
917		 In this pass we mark sections to be preserved in both
918		 files by setting the .debug_data pointer to the original
919		 file's .data pointer.  Below, we'll copy the section
920		 contents.  */
921
922	      inline void check_preserved (size_t i)
923	      {
924		if (i != 0 && i < shnum + 2 && shdr_info[i].idx != 0
925		    && shdr_info[i].debug_data == NULL)
926		  {
927		    if (shdr_info[i].data == NULL)
928		      shdr_info[i].data = elf_getdata (shdr_info[i].scn, NULL);
929		    if (shdr_info[i].data == NULL)
930		      INTERNAL_ERROR (fname);
931
932		    shdr_info[i].debug_data = shdr_info[i].data;
933		    changes |= i < cnt;
934		  }
935	      }
936
937	      check_preserved (shdr_info[cnt].shdr.sh_link);
938	      if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
939		check_preserved (shdr_info[cnt].shdr.sh_info);
940	    }
941	}
942    }
943  while (changes);
944
945  /* Copy the removed sections to the debug output file.
946     The ones that are not removed in the stripped file are SHT_NOBITS.  */
947  if (debug_fname != NULL)
948    {
949      for (cnt = 1; cnt < shnum; ++cnt)
950	{
951	  scn = elf_newscn (debugelf);
952	  if (scn == NULL)
953	    {
954	      cleanup_debug ();
955	      error (EXIT_FAILURE, 0,
956		     gettext ("while generating output file: %s"),
957		     elf_errmsg (-1));
958	    }
959
960	  bool discard_section = (shdr_info[cnt].idx > 0
961				  && shdr_info[cnt].debug_data == NULL
962				  && shdr_info[cnt].shdr.sh_type != SHT_NOTE
963				  && shdr_info[cnt].shdr.sh_type != SHT_GROUP
964				  && cnt != ehdr->e_shstrndx);
965
966	  /* Set the section header in the new file.  */
967	  GElf_Shdr debugshdr = shdr_info[cnt].shdr;
968	  if (discard_section)
969	    debugshdr.sh_type = SHT_NOBITS;
970
971	  if (unlikely (gelf_update_shdr (scn, &debugshdr) == 0))
972	    /* There cannot be any overflows.  */
973	    INTERNAL_ERROR (fname);
974
975	  /* Get the data from the old file if necessary. */
976	  if (shdr_info[cnt].data == NULL)
977	    {
978	      shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
979	      if (shdr_info[cnt].data == NULL)
980		INTERNAL_ERROR (fname);
981	    }
982
983	  /* Set the data.  This is done by copying from the old file.  */
984	  Elf_Data *debugdata = elf_newdata (scn);
985	  if (debugdata == NULL)
986	    INTERNAL_ERROR (fname);
987
988	  /* Copy the structure.  This data may be modified in place
989	     before we write out the file.  */
990	  *debugdata = *shdr_info[cnt].data;
991	  if (discard_section)
992	    debugdata->d_buf = NULL;
993	  else if (shdr_info[cnt].debug_data != NULL
994		   || shdr_info[cnt].shdr.sh_type == SHT_GROUP)
995	    {
996	      /* Copy the original data before it gets modified.  */
997	      shdr_info[cnt].debug_data = debugdata;
998	      if (debugdata->d_buf == NULL)
999		INTERNAL_ERROR (fname);
1000	      debugdata->d_buf = memcpy (xmalloc (debugdata->d_size),
1001					 debugdata->d_buf, debugdata->d_size);
1002	    }
1003	}
1004
1005      /* Finish the ELF header.  Fill in the fields not handled by
1006	 libelf from the old file.  */
1007      debugehdr = gelf_getehdr (debugelf, &debugehdr_mem);
1008      if (debugehdr == NULL)
1009	INTERNAL_ERROR (fname);
1010
1011      memcpy (debugehdr->e_ident, ehdr->e_ident, EI_NIDENT);
1012      debugehdr->e_type = ehdr->e_type;
1013      debugehdr->e_machine = ehdr->e_machine;
1014      debugehdr->e_version = ehdr->e_version;
1015      debugehdr->e_entry = ehdr->e_entry;
1016      debugehdr->e_flags = ehdr->e_flags;
1017      debugehdr->e_shstrndx = ehdr->e_shstrndx;
1018
1019      if (unlikely (gelf_update_ehdr (debugelf, debugehdr) == 0))
1020	{
1021	  error (0, 0, gettext ("%s: error while creating ELF header: %s"),
1022		 debug_fname, elf_errmsg (-1));
1023	  result = 1;
1024	  goto fail_close;
1025	}
1026    }
1027
1028  /* Mark the section header string table as unused, we will create
1029     a new one.  */
1030  shdr_info[shstrndx].idx = 0;
1031
1032  /* We need a string table for the section headers.  */
1033  shst = ebl_strtabinit (true);
1034  if (shst == NULL)
1035    {
1036      cleanup_debug ();
1037      error (EXIT_FAILURE, errno, gettext ("while preparing output for '%s'"),
1038	     output_fname ?: fname);
1039    }
1040
1041  /* Assign new section numbers.  */
1042  shdr_info[0].idx = 0;
1043  for (cnt = idx = 1; cnt < shnum; ++cnt)
1044    if (shdr_info[cnt].idx > 0)
1045      {
1046	shdr_info[cnt].idx = idx++;
1047
1048	/* Create a new section.  */
1049	shdr_info[cnt].newscn = elf_newscn (newelf);
1050	if (shdr_info[cnt].newscn == NULL)
1051	  {
1052	    cleanup_debug ();
1053	    error (EXIT_FAILURE, 0,
1054		   gettext ("while generating output file: %s"),
1055		   elf_errmsg (-1));
1056	  }
1057
1058	elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == shdr_info[cnt].idx);
1059
1060	/* Add this name to the section header string table.  */
1061	shdr_info[cnt].se = ebl_strtabadd (shst, shdr_info[cnt].name, 0);
1062      }
1063
1064  /* Test whether we are doing anything at all.  */
1065  if (cnt == idx)
1066    /* Nope, all removable sections are already gone.  */
1067    goto fail_close;
1068
1069  /* Create the reference to the file with the debug info.  */
1070  if (debug_fname != NULL && !remove_shdrs)
1071    {
1072      /* Add the section header string table section name.  */
1073      shdr_info[cnt].se = ebl_strtabadd (shst, ".gnu_debuglink", 15);
1074      shdr_info[cnt].idx = idx++;
1075
1076      /* Create the section header.  */
1077      shdr_info[cnt].shdr.sh_type = SHT_PROGBITS;
1078      shdr_info[cnt].shdr.sh_flags = 0;
1079      shdr_info[cnt].shdr.sh_addr = 0;
1080      shdr_info[cnt].shdr.sh_link = SHN_UNDEF;
1081      shdr_info[cnt].shdr.sh_info = SHN_UNDEF;
1082      shdr_info[cnt].shdr.sh_entsize = 0;
1083      shdr_info[cnt].shdr.sh_addralign = 4;
1084      /* We set the offset to zero here.  Before we write the ELF file the
1085	 field must have the correct value.  This is done in the final
1086	 loop over all section.  Then we have all the information needed.  */
1087      shdr_info[cnt].shdr.sh_offset = 0;
1088
1089      /* Create the section.  */
1090      shdr_info[cnt].newscn = elf_newscn (newelf);
1091      if (shdr_info[cnt].newscn == NULL)
1092	{
1093	  cleanup_debug ();
1094	  error (EXIT_FAILURE, 0,
1095		 gettext ("while create section header section: %s"),
1096		 elf_errmsg (-1));
1097	}
1098      elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == shdr_info[cnt].idx);
1099
1100      shdr_info[cnt].data = elf_newdata (shdr_info[cnt].newscn);
1101      if (shdr_info[cnt].data == NULL)
1102	{
1103	  cleanup_debug ();
1104	  error (EXIT_FAILURE, 0, gettext ("cannot allocate section data: %s"),
1105		 elf_errmsg (-1));
1106	}
1107
1108      char *debug_basename = basename (debug_fname_embed ?: debug_fname);
1109      off_t crc_offset = strlen (debug_basename) + 1;
1110      /* Align to 4 byte boundary */
1111      crc_offset = ((crc_offset - 1) & ~3) + 4;
1112
1113      shdr_info[cnt].data->d_align = 4;
1114      shdr_info[cnt].shdr.sh_size = shdr_info[cnt].data->d_size
1115	= crc_offset + 4;
1116      debuglink_buf = xcalloc (1, shdr_info[cnt].data->d_size);
1117      shdr_info[cnt].data->d_buf = debuglink_buf;
1118
1119      strcpy (shdr_info[cnt].data->d_buf, debug_basename);
1120
1121      /* Cache this Elf_Data describing the CRC32 word in the section.
1122	 We'll fill this in when we have written the debug file.  */
1123      debuglink_crc_data = *shdr_info[cnt].data;
1124      debuglink_crc_data.d_buf = ((char *) debuglink_crc_data.d_buf
1125				  + crc_offset);
1126      debuglink_crc_data.d_size = 4;
1127
1128      /* One more section done.  */
1129      ++cnt;
1130    }
1131
1132  /* Index of the section header table in the shdr_info array.  */
1133  shdridx = cnt;
1134
1135  /* Add the section header string table section name.  */
1136  shdr_info[cnt].se = ebl_strtabadd (shst, ".shstrtab", 10);
1137  shdr_info[cnt].idx = idx;
1138
1139  /* Create the section header.  */
1140  shdr_info[cnt].shdr.sh_type = SHT_STRTAB;
1141  shdr_info[cnt].shdr.sh_flags = 0;
1142  shdr_info[cnt].shdr.sh_addr = 0;
1143  shdr_info[cnt].shdr.sh_link = SHN_UNDEF;
1144  shdr_info[cnt].shdr.sh_info = SHN_UNDEF;
1145  shdr_info[cnt].shdr.sh_entsize = 0;
1146  /* We set the offset to zero here.  Before we write the ELF file the
1147     field must have the correct value.  This is done in the final
1148     loop over all section.  Then we have all the information needed.  */
1149  shdr_info[cnt].shdr.sh_offset = 0;
1150  shdr_info[cnt].shdr.sh_addralign = 1;
1151
1152  /* Create the section.  */
1153  shdr_info[cnt].newscn = elf_newscn (newelf);
1154  if (shdr_info[cnt].newscn == NULL)
1155    {
1156      cleanup_debug ();
1157      error (EXIT_FAILURE, 0,
1158	     gettext ("while create section header section: %s"),
1159	     elf_errmsg (-1));
1160    }
1161  elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == idx);
1162
1163  /* Finalize the string table and fill in the correct indices in the
1164     section headers.  */
1165  shstrtab_data = elf_newdata (shdr_info[cnt].newscn);
1166  if (shstrtab_data == NULL)
1167    {
1168      cleanup_debug ();
1169      error (EXIT_FAILURE, 0,
1170	     gettext ("while create section header string table: %s"),
1171	     elf_errmsg (-1));
1172    }
1173  ebl_strtabfinalize (shst, shstrtab_data);
1174
1175  /* We have to set the section size.  */
1176  shdr_info[cnt].shdr.sh_size = shstrtab_data->d_size;
1177
1178  /* Update the section information.  */
1179  GElf_Off lastoffset = 0;
1180  for (cnt = 1; cnt <= shdridx; ++cnt)
1181    if (shdr_info[cnt].idx > 0)
1182      {
1183	Elf_Data *newdata;
1184
1185	scn = elf_getscn (newelf, shdr_info[cnt].idx);
1186	elf_assert (scn != NULL);
1187
1188	/* Update the name.  */
1189	shdr_info[cnt].shdr.sh_name = ebl_strtaboffset (shdr_info[cnt].se);
1190
1191	/* Update the section header from the input file.  Some fields
1192	   might be section indeces which now have to be adjusted.  */
1193	if (shdr_info[cnt].shdr.sh_link != 0)
1194	  shdr_info[cnt].shdr.sh_link =
1195	    shdr_info[shdr_info[cnt].shdr.sh_link].idx;
1196
1197	if (shdr_info[cnt].shdr.sh_type == SHT_GROUP)
1198	  {
1199	    elf_assert (shdr_info[cnt].data != NULL
1200			&& shdr_info[cnt].data->d_buf != NULL);
1201
1202	    Elf32_Word *grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
1203	    for (size_t inner = 0;
1204		 inner < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
1205		 ++inner)
1206	      if (grpref[inner] < shnum)
1207		grpref[inner] = shdr_info[grpref[inner]].idx;
1208	      else
1209		goto illformed;
1210	  }
1211
1212	/* Handle the SHT_REL, SHT_RELA, and SHF_INFO_LINK flag.  */
1213	if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
1214	  shdr_info[cnt].shdr.sh_info =
1215	    shdr_info[shdr_info[cnt].shdr.sh_info].idx;
1216
1217	/* Get the data from the old file if necessary.  We already
1218	   created the data for the section header string table.  */
1219	if (cnt < shnum)
1220	  {
1221	    if (shdr_info[cnt].data == NULL)
1222	      {
1223		shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
1224		if (shdr_info[cnt].data == NULL)
1225		  INTERNAL_ERROR (fname);
1226	      }
1227
1228	    /* Set the data.  This is done by copying from the old file.  */
1229	    newdata = elf_newdata (scn);
1230	    if (newdata == NULL)
1231	      INTERNAL_ERROR (fname);
1232
1233	    /* Copy the structure.  */
1234	    *newdata = *shdr_info[cnt].data;
1235
1236	    /* We know the size.  */
1237	    shdr_info[cnt].shdr.sh_size = shdr_info[cnt].data->d_size;
1238
1239	    /* We have to adjust symbol tables.  The st_shndx member might
1240	       have to be updated.  */
1241	    if (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM
1242		|| shdr_info[cnt].shdr.sh_type == SHT_SYMTAB)
1243	      {
1244		Elf_Data *versiondata = NULL;
1245		Elf_Data *shndxdata = NULL;
1246
1247		size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1248
1249		if (shdr_info[cnt].symtab_idx != 0)
1250		  {
1251		    elf_assert (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB_SHNDX);
1252		    /* This section has extended section information.
1253		       We have to modify that information, too.  */
1254		    shndxdata = elf_getdata (shdr_info[shdr_info[cnt].symtab_idx].scn,
1255					     NULL);
1256
1257		    elf_assert ((versiondata->d_size / sizeof (Elf32_Word))
1258				>= shdr_info[cnt].data->d_size / elsize);
1259		  }
1260
1261		if (shdr_info[cnt].version_idx != 0)
1262		  {
1263		    elf_assert (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM);
1264		    /* This section has associated version
1265		       information.  We have to modify that
1266		       information, too.  */
1267		    versiondata = elf_getdata (shdr_info[shdr_info[cnt].version_idx].scn,
1268					       NULL);
1269
1270		    elf_assert (versiondata != NULL
1271				&& versiondata->d_buf != NULL
1272				&& ((versiondata->d_size / sizeof (GElf_Versym))
1273				    >= shdr_info[cnt].data->d_size / elsize));
1274		  }
1275
1276		shdr_info[cnt].newsymidx
1277		  = (Elf32_Word *) xcalloc (shdr_info[cnt].data->d_size
1278					    / elsize, sizeof (Elf32_Word));
1279
1280		bool last_was_local = true;
1281		size_t destidx;
1282		size_t inner;
1283		for (destidx = inner = 1;
1284		     inner < shdr_info[cnt].data->d_size / elsize;
1285		     ++inner)
1286		  {
1287		    Elf32_Word sec;
1288		    GElf_Sym sym_mem;
1289		    Elf32_Word xshndx;
1290		    GElf_Sym *sym = gelf_getsymshndx (shdr_info[cnt].data,
1291						      shndxdata, inner,
1292						      &sym_mem, &xshndx);
1293		    if (sym == NULL)
1294		      INTERNAL_ERROR (fname);
1295
1296		    if (sym->st_shndx == SHN_UNDEF
1297			|| (sym->st_shndx >= shnum
1298			    && sym->st_shndx != SHN_XINDEX))
1299		      {
1300			/* This is no section index, leave it alone
1301			   unless it is moved.  */
1302			if (destidx != inner
1303			    && gelf_update_symshndx (shdr_info[cnt].data,
1304						     shndxdata,
1305						     destidx, sym,
1306						     xshndx) == 0)
1307			  INTERNAL_ERROR (fname);
1308
1309			shdr_info[cnt].newsymidx[inner] = destidx++;
1310
1311			if (last_was_local
1312			    && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
1313			  {
1314			    last_was_local = false;
1315			    shdr_info[cnt].shdr.sh_info = destidx - 1;
1316			  }
1317
1318			continue;
1319		      }
1320
1321		    /* Get the full section index, if necessary from the
1322		       XINDEX table.  */
1323		    if (sym->st_shndx != SHN_XINDEX)
1324		      sec = shdr_info[sym->st_shndx].idx;
1325		    else
1326		      {
1327			elf_assert (shndxdata != NULL
1328				    && shndxdata->d_buf != NULL);
1329
1330			sec = shdr_info[xshndx].idx;
1331		      }
1332
1333		    if (sec != 0)
1334		      {
1335			GElf_Section nshndx;
1336			Elf32_Word nxshndx;
1337
1338			if (sec < SHN_LORESERVE)
1339			  {
1340			    nshndx = sec;
1341			    nxshndx = 0;
1342			  }
1343			else
1344			  {
1345			    nshndx = SHN_XINDEX;
1346			    nxshndx = sec;
1347			  }
1348
1349			elf_assert (sec < SHN_LORESERVE || shndxdata != NULL);
1350
1351			if ((inner != destidx || nshndx != sym->st_shndx
1352			     || (shndxdata != NULL && nxshndx != xshndx))
1353			    && (sym->st_shndx = nshndx,
1354				gelf_update_symshndx (shdr_info[cnt].data,
1355						      shndxdata,
1356						      destidx, sym,
1357						      nxshndx) == 0))
1358			  INTERNAL_ERROR (fname);
1359
1360			shdr_info[cnt].newsymidx[inner] = destidx++;
1361
1362			if (last_was_local
1363			    && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
1364			  {
1365			    last_was_local = false;
1366			    shdr_info[cnt].shdr.sh_info = destidx - 1;
1367			  }
1368		      }
1369		    else if (debug_fname == NULL
1370			     || shdr_info[cnt].debug_data == NULL)
1371		      /* This is a section or group signature symbol
1372			 for a section which has been removed.  */
1373		      {
1374			size_t sidx = (sym->st_shndx != SHN_XINDEX
1375					? sym->st_shndx : xshndx);
1376			elf_assert (GELF_ST_TYPE (sym->st_info) == STT_SECTION
1377				    || ((shdr_info[sidx].shdr.sh_type
1378					 == SHT_GROUP)
1379					&& (shdr_info[sidx].shdr.sh_info
1380					    == inner)));
1381		      }
1382		  }
1383
1384		if (destidx != inner)
1385		  {
1386		    /* The size of the symbol table changed.  */
1387		    shdr_info[cnt].shdr.sh_size = newdata->d_size
1388		      = destidx * elsize;
1389		    any_symtab_changes = true;
1390		  }
1391		else
1392		  {
1393		    /* The symbol table didn't really change.  */
1394		    free (shdr_info[cnt].newsymidx);
1395		    shdr_info[cnt].newsymidx = NULL;
1396		  }
1397	      }
1398	  }
1399
1400	/* If we have to, compute the offset of the section.  */
1401	if (shdr_info[cnt].shdr.sh_offset == 0)
1402	  shdr_info[cnt].shdr.sh_offset
1403	    = ((lastoffset + shdr_info[cnt].shdr.sh_addralign - 1)
1404	       & ~((GElf_Off) (shdr_info[cnt].shdr.sh_addralign - 1)));
1405
1406	/* Set the section header in the new file.  */
1407	if (unlikely (gelf_update_shdr (scn, &shdr_info[cnt].shdr) == 0))
1408	  /* There cannot be any overflows.  */
1409	  INTERNAL_ERROR (fname);
1410
1411	/* Remember the last section written so far.  */
1412	GElf_Off filesz = (shdr_info[cnt].shdr.sh_type != SHT_NOBITS
1413			   ? shdr_info[cnt].shdr.sh_size : 0);
1414	if (lastoffset < shdr_info[cnt].shdr.sh_offset + filesz)
1415	  lastoffset = shdr_info[cnt].shdr.sh_offset + filesz;
1416      }
1417
1418  /* Adjust symbol references if symbol tables changed.  */
1419  if (any_symtab_changes)
1420    /* Find all relocation sections which use this symbol table.  */
1421    for (cnt = 1; cnt <= shdridx; ++cnt)
1422      {
1423	/* Update section headers when the data size has changed.
1424	   We also update the SHT_NOBITS section in the debug
1425	   file so that the section headers match in sh_size.  */
1426	inline void update_section_size (const Elf_Data *newdata)
1427	{
1428	  GElf_Shdr shdr_mem;
1429	  GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1430	  shdr->sh_size = newdata->d_size;
1431	  (void) gelf_update_shdr (scn, shdr);
1432	  if (debugelf != NULL)
1433	    {
1434	      /* libelf will use d_size to set sh_size.  */
1435	      Elf_Data *debugdata = elf_getdata (elf_getscn (debugelf,
1436							     cnt), NULL);
1437	      if (debugdata == NULL)
1438		INTERNAL_ERROR (fname);
1439	      debugdata->d_size = newdata->d_size;
1440	    }
1441	}
1442
1443	if (shdr_info[cnt].idx == 0 && debug_fname == NULL)
1444	  /* Ignore sections which are discarded.  When we are saving a
1445	     relocation section in a separate debug file, we must fix up
1446	     the symbol table references.  */
1447	  continue;
1448
1449	const Elf32_Word symtabidx = shdr_info[cnt].old_sh_link;
1450	elf_assert (symtabidx < shnum + 2);
1451	const Elf32_Word *const newsymidx = shdr_info[symtabidx].newsymidx;
1452	switch (shdr_info[cnt].shdr.sh_type)
1453	  {
1454	    inline bool no_symtab_updates (void)
1455	    {
1456	      /* If the symbol table hasn't changed, do not do anything.  */
1457	      if (shdr_info[symtabidx].newsymidx == NULL)
1458		return true;
1459
1460	      /* If the symbol table is not discarded, but additionally
1461		 duplicated in the separate debug file and this section
1462		 is discarded, don't adjust anything.  */
1463	      return (shdr_info[cnt].idx == 0
1464		      && shdr_info[symtabidx].debug_data != NULL);
1465	    }
1466
1467	  case SHT_REL:
1468	  case SHT_RELA:
1469	    if (no_symtab_updates ())
1470	      break;
1471
1472	    Elf_Data *d = elf_getdata (shdr_info[cnt].idx == 0
1473				       ? elf_getscn (debugelf, cnt)
1474				       : elf_getscn (newelf,
1475						     shdr_info[cnt].idx),
1476				       NULL);
1477	    elf_assert (d != NULL && d->d_buf != NULL
1478			&& shdr_info[cnt].shdr.sh_entsize != 0);
1479	    size_t nrels = (shdr_info[cnt].shdr.sh_size
1480			    / shdr_info[cnt].shdr.sh_entsize);
1481
1482	    size_t symsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1483	    const Elf32_Word symidxn = (shdr_info[symtabidx].data->d_size
1484					/ symsize);
1485	    if (shdr_info[cnt].shdr.sh_type == SHT_REL)
1486	      for (size_t relidx = 0; relidx < nrels; ++relidx)
1487		{
1488		  GElf_Rel rel_mem;
1489		  if (gelf_getrel (d, relidx, &rel_mem) == NULL)
1490		    INTERNAL_ERROR (fname);
1491
1492		  size_t symidx = GELF_R_SYM (rel_mem.r_info);
1493		  elf_assert (symidx < symidxn);
1494		  if (newsymidx[symidx] != symidx)
1495		    {
1496		      rel_mem.r_info
1497			= GELF_R_INFO (newsymidx[symidx],
1498				       GELF_R_TYPE (rel_mem.r_info));
1499
1500		      if (gelf_update_rel (d, relidx, &rel_mem) == 0)
1501			INTERNAL_ERROR (fname);
1502		    }
1503		}
1504	    else
1505	      for (size_t relidx = 0; relidx < nrels; ++relidx)
1506		{
1507		  GElf_Rela rel_mem;
1508		  if (gelf_getrela (d, relidx, &rel_mem) == NULL)
1509		    INTERNAL_ERROR (fname);
1510
1511		  size_t symidx = GELF_R_SYM (rel_mem.r_info);
1512		  elf_assert (symidx < symidxn);
1513		  if (newsymidx[symidx] != symidx)
1514		    {
1515		      rel_mem.r_info
1516			= GELF_R_INFO (newsymidx[symidx],
1517				       GELF_R_TYPE (rel_mem.r_info));
1518
1519		      if (gelf_update_rela (d, relidx, &rel_mem) == 0)
1520			INTERNAL_ERROR (fname);
1521		    }
1522		}
1523	    break;
1524
1525	  case SHT_HASH:
1526	    if (no_symtab_updates ())
1527	      break;
1528
1529	    /* We have to recompute the hash table.  */
1530
1531	    elf_assert (shdr_info[cnt].idx > 0);
1532
1533	    /* The hash section in the new file.  */
1534	    scn = elf_getscn (newelf, shdr_info[cnt].idx);
1535
1536	    /* The symbol table data.  */
1537	    Elf_Data *symd = elf_getdata (elf_getscn (newelf,
1538						      shdr_info[symtabidx].idx),
1539					  NULL);
1540	    elf_assert (symd != NULL && symd->d_buf != NULL);
1541
1542	    /* The hash table data.  */
1543	    Elf_Data *hashd = elf_getdata (scn, NULL);
1544	    elf_assert (hashd != NULL && hashd->d_buf != NULL);
1545
1546	    if (shdr_info[cnt].shdr.sh_entsize == sizeof (Elf32_Word))
1547	      {
1548		/* Sane arches first.  */
1549		elf_assert (hashd->d_size >= 2 * sizeof (Elf32_Word));
1550		Elf32_Word *bucket = (Elf32_Word *) hashd->d_buf;
1551
1552		size_t strshndx = shdr_info[symtabidx].old_sh_link;
1553		size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1554
1555		Elf32_Word nchain = bucket[1];
1556		Elf32_Word nbucket = bucket[0];
1557		uint64_t used_buf = ((2ULL + nchain + nbucket)
1558				     * sizeof (Elf32_Word));
1559		elf_assert (used_buf <= hashd->d_size);
1560
1561		/* Adjust the nchain value.  The symbol table size
1562		   changed.  We keep the same size for the bucket array.  */
1563		bucket[1] = symd->d_size / elsize;
1564		bucket += 2;
1565		Elf32_Word *chain = bucket + nbucket;
1566
1567		/* New size of the section.  */
1568		size_t n_size = ((2 + symd->d_size / elsize + nbucket)
1569				 * sizeof (Elf32_Word));
1570		elf_assert (n_size <= hashd->d_size);
1571		hashd->d_size = n_size;
1572		update_section_size (hashd);
1573
1574		/* Clear the arrays.  */
1575		memset (bucket, '\0',
1576			(symd->d_size / elsize + nbucket)
1577			* sizeof (Elf32_Word));
1578
1579		for (size_t inner = shdr_info[symtabidx].shdr.sh_info;
1580		     inner < symd->d_size / elsize; ++inner)
1581		  {
1582		    GElf_Sym sym_mem;
1583		    GElf_Sym *sym = gelf_getsym (symd, inner, &sym_mem);
1584		    elf_assert (sym != NULL);
1585
1586		    const char *name = elf_strptr (elf, strshndx,
1587						   sym->st_name);
1588		    elf_assert (name != NULL && nbucket != 0);
1589		    size_t hidx = elf_hash (name) % nbucket;
1590
1591		    if (bucket[hidx] == 0)
1592		      bucket[hidx] = inner;
1593		    else
1594		      {
1595			hidx = bucket[hidx];
1596
1597			while (chain[hidx] != 0 && chain[hidx] < nchain)
1598			  hidx = chain[hidx];
1599
1600			chain[hidx] = inner;
1601		      }
1602		  }
1603	      }
1604	    else
1605	      {
1606		/* Alpha and S390 64-bit use 64-bit SHT_HASH entries.  */
1607		elf_assert (shdr_info[cnt].shdr.sh_entsize
1608			    == sizeof (Elf64_Xword));
1609
1610		Elf64_Xword *bucket = (Elf64_Xword *) hashd->d_buf;
1611
1612		size_t strshndx = shdr_info[symtabidx].old_sh_link;
1613		size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1614
1615		elf_assert (symd->d_size >= 2 * sizeof (Elf64_Xword));
1616		Elf64_Xword nbucket = bucket[0];
1617		Elf64_Xword nchain = bucket[1];
1618		uint64_t maxwords = hashd->d_size / sizeof (Elf64_Xword);
1619		elf_assert (maxwords >= 2
1620			    && maxwords - 2 >= nbucket
1621			    && maxwords - 2 - nbucket >= nchain);
1622
1623		/* Adjust the nchain value.  The symbol table size
1624		   changed.  We keep the same size for the bucket array.  */
1625		bucket[1] = symd->d_size / elsize;
1626		bucket += 2;
1627		Elf64_Xword *chain = bucket + nbucket;
1628
1629		/* New size of the section.  */
1630		size_t n_size = ((2 + symd->d_size / elsize + nbucket)
1631				 * sizeof (Elf64_Xword));
1632		elf_assert (n_size <= hashd->d_size);
1633		hashd->d_size = n_size;
1634		update_section_size (hashd);
1635
1636		/* Clear the arrays.  */
1637		memset (bucket, '\0',
1638			(symd->d_size / elsize + nbucket)
1639			* sizeof (Elf64_Xword));
1640
1641		for (size_t inner = shdr_info[symtabidx].shdr.sh_info;
1642		     inner < symd->d_size / elsize; ++inner)
1643		  {
1644		    GElf_Sym sym_mem;
1645		    GElf_Sym *sym = gelf_getsym (symd, inner, &sym_mem);
1646		    elf_assert (sym != NULL);
1647
1648		    const char *name = elf_strptr (elf, strshndx,
1649						   sym->st_name);
1650		    elf_assert (name != NULL && nbucket != 0);
1651		    size_t hidx = elf_hash (name) % nbucket;
1652
1653		    if (bucket[hidx] == 0)
1654		      bucket[hidx] = inner;
1655		    else
1656		      {
1657			hidx = bucket[hidx];
1658
1659			while (chain[hidx] != 0 && chain[hidx] < nchain)
1660			  hidx = chain[hidx];
1661
1662			chain[hidx] = inner;
1663		      }
1664		  }
1665	      }
1666	    break;
1667
1668	  case SHT_GNU_versym:
1669	    /* If the symbol table changed we have to adjust the entries.  */
1670	    if (no_symtab_updates ())
1671	      break;
1672
1673	    elf_assert (shdr_info[cnt].idx > 0);
1674
1675	    /* The symbol version section in the new file.  */
1676	    scn = elf_getscn (newelf, shdr_info[cnt].idx);
1677
1678	    /* The symbol table data.  */
1679	    symd = elf_getdata (elf_getscn (newelf, shdr_info[symtabidx].idx),
1680				NULL);
1681	    elf_assert (symd != NULL && symd->d_buf != NULL);
1682	    size_t symz = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1683	    const Elf32_Word syms = (shdr_info[symtabidx].data->d_size / symz);
1684
1685	    /* The version symbol data.  */
1686	    Elf_Data *verd = elf_getdata (scn, NULL);
1687	    elf_assert (verd != NULL && verd->d_buf != NULL);
1688
1689	    /* The symbol version array.  */
1690	    GElf_Half *verstab = (GElf_Half *) verd->d_buf;
1691
1692	    /* Walk through the list and */
1693	    size_t elsize = gelf_fsize (elf, verd->d_type, 1, EV_CURRENT);
1694	    Elf32_Word vers = verd->d_size / elsize;
1695	    for (size_t inner = 1; inner < vers && inner < syms; ++inner)
1696	      if (newsymidx[inner] != 0 && newsymidx[inner] < vers)
1697		/* Overwriting the same array works since the
1698		   reordering can only move entries to lower indices
1699		   in the array.  */
1700		verstab[newsymidx[inner]] = verstab[inner];
1701
1702	    /* New size of the section.  */
1703	    verd->d_size = gelf_fsize (newelf, verd->d_type,
1704				       symd->d_size
1705				       / gelf_fsize (elf, symd->d_type, 1,
1706						     EV_CURRENT),
1707				       EV_CURRENT);
1708	    update_section_size (verd);
1709	    break;
1710
1711	  case SHT_GROUP:
1712	    if (no_symtab_updates ())
1713	      break;
1714
1715	    /* Yes, the symbol table changed.
1716	       Update the section header of the section group.  */
1717	    scn = elf_getscn (newelf, shdr_info[cnt].idx);
1718	    GElf_Shdr shdr_mem;
1719	    GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1720	    elf_assert (shdr != NULL);
1721
1722	    size_t symsz = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1723	    const Elf32_Word symn = (shdr_info[symtabidx].data->d_size
1724				     / symsz);
1725	    elf_assert (shdr->sh_info < symn);
1726	    shdr->sh_info = newsymidx[shdr->sh_info];
1727
1728	    (void) gelf_update_shdr (scn, shdr);
1729	    break;
1730	  }
1731      }
1732
1733  /* Remove any relocations between debug sections in ET_REL
1734     for the debug file when requested.  These relocations are always
1735     zero based between the unallocated sections.  */
1736  if (debug_fname != NULL && reloc_debug && ehdr->e_type == ET_REL)
1737    {
1738      scn = NULL;
1739      cnt = 0;
1740      while ((scn = elf_nextscn (debugelf, scn)) != NULL)
1741	{
1742	  cnt++;
1743	  /* We need the actual section and header from the debugelf
1744	     not just the cached original in shdr_info because we
1745	     might want to change the size.  */
1746	  GElf_Shdr shdr_mem;
1747	  GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1748	  if (shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
1749	    {
1750	      /* Make sure that this relocation section points to a
1751		 section to relocate with contents, that isn't
1752		 allocated and that is a debug section.  */
1753	      Elf_Scn *tscn = elf_getscn (debugelf, shdr->sh_info);
1754	      GElf_Shdr tshdr_mem;
1755	      GElf_Shdr *tshdr = gelf_getshdr (tscn, &tshdr_mem);
1756	      if (tshdr->sh_type == SHT_NOBITS
1757		  || tshdr->sh_size == 0
1758		  || (tshdr->sh_flags & SHF_ALLOC) != 0)
1759		continue;
1760
1761	      const char *tname =  elf_strptr (debugelf, shstrndx,
1762					       tshdr->sh_name);
1763	      if (! tname || ! ebl_debugscn_p (ebl, tname))
1764		continue;
1765
1766	      /* OK, lets relocate all trivial cross debug section
1767		 relocations. */
1768	      Elf_Data *reldata = elf_getdata (scn, NULL);
1769	      if (reldata == NULL || reldata->d_buf == NULL)
1770		INTERNAL_ERROR (fname);
1771	      /* We actually wanted the rawdata, but since we already
1772		 accessed it earlier as elf_getdata () that won't
1773		 work. But debug sections are all ELF_T_BYTE, so it
1774		 doesn't really matter.  */
1775	      Elf_Data *tdata = elf_getdata (tscn, NULL);
1776	      if (tdata == NULL || tdata->d_buf == NULL
1777		  || tdata->d_type != ELF_T_BYTE)
1778		INTERNAL_ERROR (fname);
1779
1780	      /* Pick up the symbol table and shndx table to
1781		 resolve relocation symbol indexes.  */
1782	      Elf64_Word symt = shdr->sh_link;
1783	      Elf_Data *symdata, *xndxdata;
1784	      elf_assert (symt < shnum + 2);
1785	      elf_assert (shdr_info[symt].symtab_idx < shnum + 2);
1786	      symdata = (shdr_info[symt].debug_data
1787			 ?: shdr_info[symt].data);
1788	      xndxdata = (shdr_info[shdr_info[symt].symtab_idx].debug_data
1789			  ?: shdr_info[shdr_info[symt].symtab_idx].data);
1790
1791	      /* Apply one relocation.  Returns true when trivial
1792		 relocation actually done.  */
1793	      bool relocate (GElf_Addr offset, const GElf_Sxword addend,
1794			     bool is_rela, int rtype, int symndx)
1795	      {
1796		/* R_*_NONE relocs can always just be removed.  */
1797		if (rtype == 0)
1798		  return true;
1799
1800		/* We only do simple absolute relocations.  */
1801		Elf_Type type = ebl_reloc_simple_type (ebl, rtype);
1802		if (type == ELF_T_NUM)
1803		  return false;
1804
1805		/* These are the types we can relocate.  */
1806#define TYPES   DO_TYPE (BYTE, Byte); DO_TYPE (HALF, Half);		\
1807		DO_TYPE (WORD, Word); DO_TYPE (SWORD, Sword);		\
1808		DO_TYPE (XWORD, Xword); DO_TYPE (SXWORD, Sxword)
1809
1810		/* And only for relocations against other debug sections.  */
1811		GElf_Sym sym_mem;
1812		Elf32_Word xndx;
1813		GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
1814						  symndx, &sym_mem,
1815						  &xndx);
1816		Elf32_Word sec = (sym->st_shndx == SHN_XINDEX
1817				  ? xndx : sym->st_shndx);
1818		if (sec >= shnum + 2)
1819		  INTERNAL_ERROR (fname);
1820
1821		if (ebl_debugscn_p (ebl, shdr_info[sec].name))
1822		  {
1823		    size_t size;
1824
1825#define DO_TYPE(NAME, Name) GElf_##Name Name;
1826		    union { TYPES; } tmpbuf;
1827#undef DO_TYPE
1828
1829		    switch (type)
1830		      {
1831#define DO_TYPE(NAME, Name)				\
1832			case ELF_T_##NAME:		\
1833			  size = sizeof (GElf_##Name);	\
1834			  tmpbuf.Name = 0;		\
1835			  break;
1836			TYPES;
1837#undef DO_TYPE
1838		      default:
1839			return false;
1840		      }
1841
1842		    if (offset > tdata->d_size
1843			|| tdata->d_size - offset < size)
1844		      {
1845			cleanup_debug ();
1846			error (EXIT_FAILURE, 0, gettext ("bad relocation"));
1847		      }
1848
1849		    /* When the symbol value is zero then for SHT_REL
1850		       sections this is all that needs to be checked.
1851		       The addend is contained in the original data at
1852		       the offset already.  So if the (section) symbol
1853		       address is zero and the given addend is zero
1854		       just remove the relocation, it isn't needed
1855		       anymore.  */
1856		    if (addend == 0 && sym->st_value == 0)
1857		      return true;
1858
1859		    Elf_Data tmpdata =
1860		      {
1861			.d_type = type,
1862			.d_buf = &tmpbuf,
1863			.d_size = size,
1864			.d_version = EV_CURRENT,
1865		      };
1866		    Elf_Data rdata =
1867		      {
1868			.d_type = type,
1869			.d_buf = tdata->d_buf + offset,
1870			.d_size = size,
1871			.d_version = EV_CURRENT,
1872		      };
1873
1874		    GElf_Addr value = sym->st_value;
1875		    if (is_rela)
1876		      {
1877			/* For SHT_RELA sections we just take the
1878			   given addend and add it to the value.  */
1879			value += addend;
1880		      }
1881		    else
1882		      {
1883			/* For SHT_REL sections we have to peek at
1884			   what is already in the section at the given
1885			   offset to get the addend.  */
1886			Elf_Data *d = gelf_xlatetom (debugelf, &tmpdata,
1887						     &rdata,
1888						     ehdr->e_ident[EI_DATA]);
1889			if (d == NULL)
1890			  INTERNAL_ERROR (fname);
1891			assert (d == &tmpdata);
1892		      }
1893
1894		    switch (type)
1895		      {
1896#define DO_TYPE(NAME, Name)					\
1897			case ELF_T_##NAME:			\
1898			  tmpbuf.Name += (GElf_##Name) value;	\
1899			  break;
1900			TYPES;
1901#undef DO_TYPE
1902		      default:
1903			abort ();
1904		      }
1905
1906		    /* Now finally put in the new value.  */
1907		    Elf_Data *s = gelf_xlatetof (debugelf, &rdata,
1908						 &tmpdata,
1909						 ehdr->e_ident[EI_DATA]);
1910		    if (s == NULL)
1911		      INTERNAL_ERROR (fname);
1912		    assert (s == &rdata);
1913
1914		    return true;
1915		  }
1916		return false;
1917	      }
1918
1919	      if (shdr->sh_entsize == 0)
1920		INTERNAL_ERROR (fname);
1921
1922	      size_t nrels = shdr->sh_size / shdr->sh_entsize;
1923	      size_t next = 0;
1924	      if (shdr->sh_type == SHT_REL)
1925		for (size_t relidx = 0; relidx < nrels; ++relidx)
1926		  {
1927		    GElf_Rel rel_mem;
1928		    GElf_Rel *r = gelf_getrel (reldata, relidx, &rel_mem);
1929		    if (! relocate (r->r_offset, 0, false,
1930				    GELF_R_TYPE (r->r_info),
1931				    GELF_R_SYM (r->r_info)))
1932		      {
1933			if (relidx != next)
1934			  gelf_update_rel (reldata, next, r);
1935			++next;
1936		      }
1937		  }
1938	      else
1939		for (size_t relidx = 0; relidx < nrels; ++relidx)
1940		  {
1941		    GElf_Rela rela_mem;
1942		    GElf_Rela *r = gelf_getrela (reldata, relidx, &rela_mem);
1943		    if (! relocate (r->r_offset, r->r_addend, true,
1944				    GELF_R_TYPE (r->r_info),
1945				    GELF_R_SYM (r->r_info)))
1946		      {
1947			if (relidx != next)
1948			  gelf_update_rela (reldata, next, r);
1949			++next;
1950		      }
1951		  }
1952
1953	      nrels = next;
1954	      shdr->sh_size = reldata->d_size = nrels * shdr->sh_entsize;
1955	      gelf_update_shdr (scn, shdr);
1956	    }
1957	}
1958    }
1959
1960  /* Now that we have done all adjustments to the data,
1961     we can actually write out the debug file.  */
1962  if (debug_fname != NULL)
1963    {
1964      /* Finally write the file.  */
1965      if (unlikely (elf_update (debugelf, ELF_C_WRITE) == -1))
1966	{
1967	  error (0, 0, gettext ("while writing '%s': %s"),
1968		 tmp_debug_fname, elf_errmsg (-1));
1969	  result = 1;
1970	  goto fail_close;
1971	}
1972
1973      /* Create the real output file.  First rename, then change the
1974	 mode.  */
1975      if (rename (tmp_debug_fname, debug_fname) != 0
1976	  || fchmod (debug_fd, mode) != 0)
1977	{
1978	  error (0, errno, gettext ("while creating '%s'"), debug_fname);
1979	  result = 1;
1980	  goto fail_close;
1981	}
1982
1983      /* The temporary file does not exist anymore.  */
1984      free (tmp_debug_fname);
1985      tmp_debug_fname = NULL;
1986
1987      if (!remove_shdrs)
1988	{
1989	  uint32_t debug_crc;
1990	  Elf_Data debug_crc_data =
1991	    {
1992	      .d_type = ELF_T_WORD,
1993	      .d_buf = &debug_crc,
1994	      .d_size = sizeof (debug_crc),
1995	      .d_version = EV_CURRENT
1996	    };
1997
1998	  /* Compute the checksum which we will add to the executable.  */
1999	  if (crc32_file (debug_fd, &debug_crc) != 0)
2000	    {
2001	      error (0, errno, gettext ("\
2002while computing checksum for debug information"));
2003	      unlink (debug_fname);
2004	      result = 1;
2005	      goto fail_close;
2006	    }
2007
2008	  /* Store it in the debuglink section data.  */
2009	  if (unlikely (gelf_xlatetof (newelf, &debuglink_crc_data,
2010				       &debug_crc_data, ehdr->e_ident[EI_DATA])
2011			!= &debuglink_crc_data))
2012	    INTERNAL_ERROR (fname);
2013	}
2014    }
2015
2016  /* Finally finish the ELF header.  Fill in the fields not handled by
2017     libelf from the old file.  */
2018  newehdr = gelf_getehdr (newelf, &newehdr_mem);
2019  if (newehdr == NULL)
2020    INTERNAL_ERROR (fname);
2021
2022  memcpy (newehdr->e_ident, ehdr->e_ident, EI_NIDENT);
2023  newehdr->e_type = ehdr->e_type;
2024  newehdr->e_machine = ehdr->e_machine;
2025  newehdr->e_version = ehdr->e_version;
2026  newehdr->e_entry = ehdr->e_entry;
2027  newehdr->e_flags = ehdr->e_flags;
2028  newehdr->e_phoff = ehdr->e_phoff;
2029
2030  /* We need to position the section header table.  */
2031  const size_t offsize = gelf_fsize (elf, ELF_T_OFF, 1, EV_CURRENT);
2032  newehdr->e_shoff = ((shdr_info[shdridx].shdr.sh_offset
2033		       + shdr_info[shdridx].shdr.sh_size + offsize - 1)
2034		      & ~((GElf_Off) (offsize - 1)));
2035  newehdr->e_shentsize = gelf_fsize (elf, ELF_T_SHDR, 1, EV_CURRENT);
2036
2037  /* The new section header string table index.  */
2038  if (likely (idx < SHN_HIRESERVE) && likely (idx != SHN_XINDEX))
2039    newehdr->e_shstrndx = idx;
2040  else
2041    {
2042      /* The index does not fit in the ELF header field.  */
2043      shdr_info[0].scn = elf_getscn (elf, 0);
2044
2045      if (gelf_getshdr (shdr_info[0].scn, &shdr_info[0].shdr) == NULL)
2046	INTERNAL_ERROR (fname);
2047
2048      shdr_info[0].shdr.sh_link = idx;
2049      (void) gelf_update_shdr (shdr_info[0].scn, &shdr_info[0].shdr);
2050
2051      newehdr->e_shstrndx = SHN_XINDEX;
2052    }
2053
2054  if (gelf_update_ehdr (newelf, newehdr) == 0)
2055    {
2056      error (0, 0, gettext ("%s: error while creating ELF header: %s"),
2057	     output_fname ?: fname, elf_errmsg (-1));
2058      cleanup_debug ();
2059      return 1;
2060    }
2061
2062  /* We have everything from the old file.  */
2063  if (elf_cntl (elf, ELF_C_FDDONE) != 0)
2064    {
2065      error (0, 0, gettext ("%s: error while reading the file: %s"),
2066	     fname, elf_errmsg (-1));
2067      cleanup_debug ();
2068      return 1;
2069    }
2070
2071  /* The ELF library better follows our layout when this is not a
2072     relocatable object file.  */
2073  elf_flagelf (newelf, ELF_C_SET,
2074	       (ehdr->e_type != ET_REL ? ELF_F_LAYOUT : 0)
2075	       | (permissive ? ELF_F_PERMISSIVE : 0));
2076
2077  /* Finally write the file.  */
2078  if (elf_update (newelf, ELF_C_WRITE) == -1)
2079    {
2080      error (0, 0, gettext ("while writing '%s': %s"),
2081	     output_fname ?: fname, elf_errmsg (-1));
2082      result = 1;
2083    }
2084
2085  if (remove_shdrs)
2086    {
2087      /* libelf can't cope without the section headers being properly intact.
2088	 So we just let it write them normally, and then we nuke them later.  */
2089
2090      if (newehdr->e_ident[EI_CLASS] == ELFCLASS32)
2091	{
2092	  assert (offsetof (Elf32_Ehdr, e_shentsize) + sizeof (Elf32_Half)
2093		  == offsetof (Elf32_Ehdr, e_shnum));
2094	  assert (offsetof (Elf32_Ehdr, e_shnum) + sizeof (Elf32_Half)
2095		  == offsetof (Elf32_Ehdr, e_shstrndx));
2096	  const Elf32_Off zero_off = 0;
2097	  const Elf32_Half zero[3] = { 0, 0, SHN_UNDEF };
2098	  if (pwrite_retry (fd, &zero_off, sizeof zero_off,
2099			    offsetof (Elf32_Ehdr, e_shoff)) != sizeof zero_off
2100	      || (pwrite_retry (fd, zero, sizeof zero,
2101				offsetof (Elf32_Ehdr, e_shentsize))
2102		  != sizeof zero)
2103	      || ftruncate64 (fd, shdr_info[shdridx].shdr.sh_offset) < 0)
2104	    {
2105	      error (0, errno, gettext ("while writing '%s'"),
2106		     output_fname ?: fname);
2107	      result = 1;
2108	    }
2109	}
2110      else
2111	{
2112	  assert (offsetof (Elf64_Ehdr, e_shentsize) + sizeof (Elf64_Half)
2113		  == offsetof (Elf64_Ehdr, e_shnum));
2114	  assert (offsetof (Elf64_Ehdr, e_shnum) + sizeof (Elf64_Half)
2115		  == offsetof (Elf64_Ehdr, e_shstrndx));
2116	  const Elf64_Off zero_off = 0;
2117	  const Elf64_Half zero[3] = { 0, 0, SHN_UNDEF };
2118	  if (pwrite_retry (fd, &zero_off, sizeof zero_off,
2119			    offsetof (Elf64_Ehdr, e_shoff)) != sizeof zero_off
2120	      || (pwrite_retry (fd, zero, sizeof zero,
2121				offsetof (Elf64_Ehdr, e_shentsize))
2122		  != sizeof zero)
2123	      || ftruncate64 (fd, shdr_info[shdridx].shdr.sh_offset) < 0)
2124	    {
2125	      error (0, errno, gettext ("while writing '%s'"),
2126		     output_fname ?: fname);
2127	      result = 1;
2128	    }
2129	}
2130    }
2131
2132 fail_close:
2133  if (shdr_info != NULL)
2134    {
2135      /* For some sections we might have created an table to map symbol
2136	 table indices.  */
2137      if (any_symtab_changes)
2138	for (cnt = 1; cnt <= shdridx; ++cnt)
2139	  {
2140	    free (shdr_info[cnt].newsymidx);
2141	    if (shdr_info[cnt].debug_data != NULL)
2142	      free (shdr_info[cnt].debug_data->d_buf);
2143	  }
2144
2145      /* Free data we allocated for the .gnu_debuglink section. */
2146      free (debuglink_buf);
2147
2148      /* Free the memory.  */
2149      if ((shnum + 2) * sizeof (struct shdr_info) > MAX_STACK_ALLOC)
2150	free (shdr_info);
2151    }
2152
2153  /* Free other resources.  */
2154  if (shstrtab_data != NULL)
2155    free (shstrtab_data->d_buf);
2156  if (shst != NULL)
2157    ebl_strtabfree (shst);
2158
2159  /* That was it.  Close the descriptors.  */
2160  if (elf_end (newelf) != 0)
2161    {
2162      error (0, 0, gettext ("error while finishing '%s': %s"),
2163	     output_fname ?: fname, elf_errmsg (-1));
2164      result = 1;
2165    }
2166
2167  if (debugelf != NULL && elf_end (debugelf) != 0)
2168    {
2169      error (0, 0, gettext ("error while finishing '%s': %s"), debug_fname,
2170	     elf_errmsg (-1));
2171      result = 1;
2172    }
2173
2174 fail:
2175  /* Close the EBL backend.  */
2176  if (ebl != NULL)
2177    ebl_closebackend (ebl);
2178
2179  cleanup_debug ();
2180
2181  /* If requested, preserve the timestamp.  */
2182  if (tvp != NULL)
2183    {
2184      if (futimens (fd, tvp) != 0)
2185	{
2186	  error (0, errno, gettext ("\
2187cannot set access and modification date of '%s'"),
2188		 output_fname ?: fname);
2189	  result = 1;
2190	}
2191    }
2192
2193  /* Close the file descriptor if we created a new file.  */
2194  if (output_fname != NULL)
2195    close (fd);
2196
2197  return result;
2198}
2199
2200static void
2201cleanup_debug ()
2202{
2203  if (debug_fd >= 0)
2204    {
2205      if (tmp_debug_fname != NULL)
2206	{
2207	  unlink (tmp_debug_fname);
2208	  free (tmp_debug_fname);
2209	  tmp_debug_fname = NULL;
2210	}
2211      close (debug_fd);
2212      debug_fd = -1;
2213    }
2214}
2215
2216static int
2217handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
2218	   struct timespec tvp[2])
2219{
2220  size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
2221  size_t fname_len = strlen (fname) + 1;
2222  char new_prefix[prefix_len + 1 + fname_len];
2223  char *cp = new_prefix;
2224
2225  /* Create the full name of the file.  */
2226  if (prefix != NULL)
2227    {
2228      cp = mempcpy (cp, prefix, prefix_len);
2229      *cp++ = ':';
2230    }
2231  memcpy (cp, fname, fname_len);
2232
2233
2234  /* Process all the files contained in the archive.  */
2235  Elf *subelf;
2236  Elf_Cmd cmd = ELF_C_RDWR;
2237  int result = 0;
2238  while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
2239    {
2240      /* The the header for this element.  */
2241      Elf_Arhdr *arhdr = elf_getarhdr (subelf);
2242
2243      if (elf_kind (subelf) == ELF_K_ELF)
2244	result |= handle_elf (fd, subelf, new_prefix, arhdr->ar_name, 0, NULL);
2245      else if (elf_kind (subelf) == ELF_K_AR)
2246	result |= handle_ar (fd, subelf, new_prefix, arhdr->ar_name, NULL);
2247
2248      /* Get next archive element.  */
2249      cmd = elf_next (subelf);
2250      if (unlikely (elf_end (subelf) != 0))
2251	INTERNAL_ERROR (fname);
2252    }
2253
2254  if (tvp != NULL)
2255    {
2256      if (unlikely (futimens (fd, tvp) != 0))
2257	{
2258	  error (0, errno, gettext ("\
2259cannot set access and modification date of '%s'"), fname);
2260	  result = 1;
2261	}
2262    }
2263
2264  if (unlikely (close (fd) != 0))
2265    error (EXIT_FAILURE, errno, gettext ("while closing '%s'"), fname);
2266
2267  return result;
2268}
2269
2270
2271#include "debugpred.h"
2272