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