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