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