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