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