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.
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.
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.
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/>. */
35 #include <stdio_ext.h>
42 #include <elf-knowledge.h>
47 #include <printversion.h>
49 typedef uint8_t GElf_Byte;
51 /* Name and version of program. */
52 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
54 /* Bug report address. */
55 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
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
66 /* Definitions of arguments for argp functions. */
67 static const struct argp_option options[] =
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 },
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 }
94 /* Short description of program. */
95 static const char doc[] = N_("Discard symbols from object files.");
97 /* Strings for arguments in help texts. */
98 static const char args_doc[] = N_("[FILE...]");
100 /* Prototype for option handler. */
101 static error_t parse_opt (int key, char *arg, struct argp_state *state);
103 /* Data structure to communicate with argp functions. */
104 static struct argp argp =
106 options, parse_opt, args_doc, doc, NULL, NULL, NULL
110 /* Print symbols in file named FNAME. */
111 static int process_file (const char *fname);
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]);
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));
121 static int debug_fd = -1;
122 static char *tmp_debug_fname = NULL;
124 /* Close debug file descriptor, if opened. And remove temporary debug file. */
125 static void cleanup_debug (void);
127 #define INTERNAL_ERROR(fname) \
130 error (EXIT_FAILURE, 0, gettext ("%s: INTERNAL ERROR %d (%s): %s"), \
131 fname, __LINE__, PACKAGE_VERSION, elf_errmsg (-1)); \
135 /* Name of the output file. */
136 static const char *output_fname;
138 /* Name of the debug output file. */
139 static const char *debug_fname;
141 /* Name to pretend the debug output file has. */
142 static const char *debug_fname_embed;
144 /* If true output files shall have same date as the input file. */
145 static bool preserve_dates;
147 /* If true .comment sections will be removed. */
148 static bool remove_comment;
150 /* If true remove all debug sections. */
151 static bool remove_debug;
153 /* If true remove all section headers. */
154 static bool remove_shdrs;
156 /* If true relax some ELF rules for input files. */
157 static bool permissive;
159 /* If true perform relocations between debug sections. */
160 static bool reloc_debug;
162 /* Sections the user explicitly wants to keep or remove. */
163 struct section_pattern
166 struct section_pattern *next;
169 static struct section_pattern *keep_secs = NULL;
170 static struct section_pattern *remove_secs = NULL;
173 add_pattern (struct section_pattern **patterns, const char *pattern)
175 struct section_pattern *p = xmalloc (sizeof *p);
176 p->pattern = xstrdup (pattern);
182 free_sec_patterns (struct section_pattern *patterns)
184 struct section_pattern *pattern = patterns;
185 while (pattern != NULL)
187 struct section_pattern *p = pattern;
197 free_sec_patterns (keep_secs);
198 free_sec_patterns (remove_secs);
202 section_name_matches (struct section_pattern *patterns, const char *name)
204 struct section_pattern *pattern = patterns;
205 while (pattern != NULL)
207 if (fnmatch (pattern->pattern, name, FNM_EXTMATCH) == 0)
209 pattern = pattern->next;
216 main (int argc, char *argv[])
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);
227 setlocale (LC_ALL, "");
229 /* Make sure the message catalog can be found. */
230 bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
232 /* Initialize the message catalog. */
233 textdomain (PACKAGE_TARNAME);
235 /* Parse and process arguments. */
236 if (argp_parse (&argp, argc, argv, 0, &remaining, NULL) != 0)
239 if (reloc_debug && debug_fname == NULL)
240 error (EXIT_FAILURE, 0,
241 gettext ("--reloc-debug-sections used without -f"));
243 /* Tell the library which version we are expecting. */
244 elf_version (EV_CURRENT);
246 if (remaining == argc)
247 /* The user didn't specify a name so we use a.out. */
248 result = process_file ("a.out");
251 /* If we have seen the '-o' or '-f' option there must be exactly one
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'"));
258 /* Process all the remaining files. */
260 result |= process_file (argv[remaining]);
261 while (++remaining < argc);
269 /* Handle program arguments. */
271 parse_opt (int key, char *arg, struct argp_state *state)
276 if (debug_fname != NULL)
278 error (0, 0, gettext ("-f option specified twice"));
285 if (debug_fname_embed != NULL)
287 error (0, 0, gettext ("-F option specified twice"));
290 debug_fname_embed = arg;
294 if (output_fname != NULL)
296 error (0, 0, gettext ("-o option specified twice"));
303 preserve_dates = true;
306 case OPT_RELOC_DEBUG:
310 case OPT_REMOVE_COMMENT:
311 remove_comment = true;
315 if (fnmatch (arg, ".comment", FNM_EXTMATCH) == 0)
316 remove_comment = true;
317 add_pattern (&remove_secs, arg);
320 case OPT_KEEP_SECTION:
321 add_pattern (&keep_secs, arg);
330 case OPT_STRIP_SECTIONS:
338 case 's': /* Ignored for compatibility. */
341 case ARGP_KEY_SUCCESS:
342 if (remove_comment == true
343 && section_name_matches (keep_secs, ".comment"))
346 gettext ("cannot both keep and remove .comment section"));
352 return ARGP_ERR_UNKNOWN;
359 process_file (const char *fname)
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. */
365 struct timespec tv[2];
369 if (stat (fname, &pre_st) != 0)
371 error (0, errno, gettext ("cannot stat input file '%s'"), fname);
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;
382 int fd = open (fname, output_fname == NULL ? O_RDWR : O_RDONLY);
385 error (0, errno, gettext ("while opening '%s'"), fname);
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
393 if (fstat (fd, &st) != 0)
395 error (0, errno, gettext ("cannot stat input file '%s'"), fname);
398 /* Paranoid mode on. */
400 && (st.st_ino != pre_st.st_ino || st.st_dev != pre_st.st_dev))
402 /* We detected a race. Try again. */
407 /* Now get the ELF descriptor. */
408 Elf *elf = elf_begin (fd, output_fname == NULL ? ELF_C_RDWR : ELF_C_READ,
411 switch (elf_kind (elf))
414 result = handle_elf (fd, elf, NULL, fname, st.st_mode & ACCESSPERMS,
415 preserve_dates ? tv : NULL);
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))
423 error (0, 0, gettext ("%s: cannot use -o or -f when stripping archive"),
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);
435 error (0, 0, gettext ("%s: no support for stripping archive"),
442 error (0, 0, gettext ("%s: File format not recognized"), fname);
447 if (unlikely (elf_end (elf) != 0))
448 INTERNAL_ERROR (fname);
456 /* Maximum size of array allocated on stack. */
457 #define MAX_STACK_ALLOC (400 * 1024)
460 handle_elf (int fd, Elf *elf, const char *prefix, const char *fname,
461 mode_t mode, struct timespec tvp[2])
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);
467 Elf *debugelf = NULL;
468 tmp_debug_fname = NULL;
477 Elf_Data *debug_data;
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;
487 Elf32_Word *newsymidx;
493 GElf_Ehdr newehdr_mem;
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;
503 /* Create the full name of the file. */
506 cp = mempcpy (cp, prefix, prefix_len);
509 memcpy (cp, fname, fname_len);
511 /* If we are not replacing the input file open a new file here. */
512 if (output_fname != NULL)
514 fd = open (output_fname, O_RDWR | O_CREAT, mode);
515 if (unlikely (fd == -1))
517 error (0, errno, gettext ("cannot open '%s'"), output_fname);
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. */
529 if (remove_debug || reloc_debug)
531 ebl = ebl_openbackend (elf);
534 error (0, errno, gettext ("cannot open EBL backend"));
540 /* Open the additional file the debug information will be stored in. */
541 if (debug_fname != NULL)
543 /* Create a temporary file name. We do not want to overwrite
544 the debug file if the file would not contain any
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),
551 debug_fd = mkstemp (tmp_debug_fname);
552 if (unlikely (debug_fd == -1))
554 error (0, errno, gettext ("cannot open '%s'"), debug_fname);
560 /* Get the information from the old file. */
562 GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
564 INTERNAL_ERROR (fname);
566 /* Get the section header string table index. */
567 if (unlikely (elf_getshdrstrndx (elf, &shstrndx) < 0))
570 error (EXIT_FAILURE, 0,
571 gettext ("cannot get section header string table index"));
574 /* Get the number of phdrs in the old file. */
576 if (elf_getphdrnum (elf, &phnum) != 0)
579 error (EXIT_FAILURE, 0, gettext ("cannot get number of phdrs"));
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
586 if (output_fname != NULL)
587 newelf = elf_begin (fd, ELF_C_WRITE_MMAP, NULL);
589 newelf = elf_clone (elf, ELF_C_EMPTY);
591 if (unlikely (gelf_newehdr (newelf, gelf_getclass (elf)) == 0)
592 || (ehdr->e_type != ET_REL
593 && unlikely (gelf_newphdr (newelf, phnum) == 0)))
595 error (0, 0, gettext ("cannot create new file '%s': %s"),
596 output_fname ?: fname, elf_errmsg (-1));
600 /* Copy over the old program header if needed. */
601 if (ehdr->e_type != ET_REL)
602 for (cnt = 0; cnt < phnum; ++cnt)
605 GElf_Phdr *phdr = gelf_getphdr (elf, cnt, &phdr_mem);
607 || unlikely (gelf_update_phdr (newelf, cnt, phdr) == 0))
608 INTERNAL_ERROR (fname);
611 if (debug_fname != NULL)
613 /* Also create an ELF descriptor for the debug file */
614 debugelf = elf_begin (debug_fd, ELF_C_WRITE_MMAP, NULL);
615 if (unlikely (gelf_newehdr (debugelf, gelf_getclass (elf)) == 0)
616 || (ehdr->e_type != ET_REL
617 && unlikely (gelf_newphdr (debugelf, phnum) == 0)))
619 error (0, 0, gettext ("cannot create new file '%s': %s"),
620 debug_fname, elf_errmsg (-1));
624 /* Copy over the old program header if needed. */
625 if (ehdr->e_type != ET_REL)
626 for (cnt = 0; cnt < phnum; ++cnt)
629 GElf_Phdr *phdr = gelf_getphdr (elf, cnt, &phdr_mem);
631 || unlikely (gelf_update_phdr (debugelf, cnt, phdr) == 0))
632 INTERNAL_ERROR (fname);
636 /* Number of sections. */
638 if (unlikely (elf_getshdrnum (elf, &shnum) < 0))
640 error (0, 0, gettext ("cannot determine number of sections: %s"),
645 if (shstrndx >= shnum)
648 #define elf_assert(test) do { if (!(test)) goto illformed; } while (0)
650 /* Storage for section information. We leave room for two more
651 entries since we unconditionally create a section header string
652 table. Maybe some weird tool created an ELF file without one.
653 The other one is used for the debug link section. */
654 if ((shnum + 2) * sizeof (struct shdr_info) > MAX_STACK_ALLOC)
655 shdr_info = (struct shdr_info *) xcalloc (shnum + 2,
656 sizeof (struct shdr_info));
659 shdr_info = (struct shdr_info *) alloca ((shnum + 2)
660 * sizeof (struct shdr_info));
661 memset (shdr_info, '\0', (shnum + 2) * sizeof (struct shdr_info));
664 /* Track whether allocated sections all come before non-allocated ones. */
665 bool seen_allocated = false;
666 bool seen_unallocated = false;
667 bool mixed_allocated_unallocated = false;
669 /* Prepare section information data structure. */
672 while ((scn = elf_nextscn (elf, scn)) != NULL)
674 /* This should always be true (i.e., there should not be any
675 holes in the numbering). */
676 elf_assert (elf_ndxscn (scn) == cnt);
678 shdr_info[cnt].scn = scn;
680 /* Get the header. */
681 if (gelf_getshdr (scn, &shdr_info[cnt].shdr) == NULL)
682 INTERNAL_ERROR (fname);
684 /* Normally (in non-ET_REL files) we see all allocated sections first,
685 then all non-allocated. */
686 if ((shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) == 0)
687 seen_unallocated = true;
690 if (seen_unallocated && seen_allocated)
691 mixed_allocated_unallocated = true;
692 seen_allocated = true;
695 /* Get the name of the section. */
696 shdr_info[cnt].name = elf_strptr (elf, shstrndx,
697 shdr_info[cnt].shdr.sh_name);
698 if (shdr_info[cnt].name == NULL)
701 error (0, 0, gettext ("illformed file '%s'"), fname);
705 /* Sanity check the user. */
706 if (section_name_matches (remove_secs, shdr_info[cnt].name))
708 if ((shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) != 0)
711 gettext ("Cannot remove allocated section '%s'"),
712 shdr_info[cnt].name);
717 if (section_name_matches (keep_secs, shdr_info[cnt].name))
720 gettext ("Cannot both keep and remove section '%s'"),
721 shdr_info[cnt].name);
727 /* Mark them as present but not yet investigated. */
728 shdr_info[cnt].idx = 1;
730 /* Remember the shdr.sh_link value. */
731 shdr_info[cnt].old_sh_link = shdr_info[cnt].shdr.sh_link;
732 if (shdr_info[cnt].old_sh_link >= shnum)
735 /* Sections in files other than relocatable object files which
736 not loaded can be freely moved by us. In theory we can also
737 freely move around allocated nobits sections. But we don't
738 to keep the layout of all allocated sections as similar as
739 possible to the original file. In relocatable object files
740 everything can be moved. */
741 if (ehdr->e_type == ET_REL
742 || (shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) == 0)
743 shdr_info[cnt].shdr.sh_offset = 0;
745 /* If this is an extended section index table store an
746 appropriate reference. */
747 if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB_SHNDX))
749 elf_assert (shdr_info[shdr_info[cnt].shdr.sh_link].symtab_idx == 0);
750 shdr_info[shdr_info[cnt].shdr.sh_link].symtab_idx = cnt;
752 else if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_GROUP))
754 /* Cross-reference the sections contained in the section
756 shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
757 if (shdr_info[cnt].data == NULL
758 || shdr_info[cnt].data->d_size < sizeof (Elf32_Word))
759 INTERNAL_ERROR (fname);
761 /* XXX Fix for unaligned access. */
762 Elf32_Word *grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
765 inner < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
768 if (grpref[inner] < shnum)
769 shdr_info[grpref[inner]].group_idx = cnt;
774 if (inner == 1 || (inner == 2 && (grpref[0] & GRP_COMDAT) == 0))
775 /* If the section group contains only one element and this
776 is n COMDAT section we can drop it right away. */
777 shdr_info[cnt].idx = 0;
779 shdr_info[cnt].group_cnt = inner - 1;
781 else if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_GNU_versym))
783 elf_assert (shdr_info[shdr_info[cnt].shdr.sh_link].version_idx == 0);
784 shdr_info[shdr_info[cnt].shdr.sh_link].version_idx = cnt;
787 /* If this section is part of a group make sure it is not
788 discarded right away. */
789 if ((shdr_info[cnt].shdr.sh_flags & SHF_GROUP) != 0)
791 elf_assert (shdr_info[cnt].group_idx != 0);
793 if (shdr_info[shdr_info[cnt].group_idx].idx == 0)
795 /* The section group section will be removed. */
796 shdr_info[cnt].group_idx = 0;
797 shdr_info[cnt].shdr.sh_flags &= ~SHF_GROUP;
801 /* Increment the counter. */
805 /* Now determine which sections can go away. The general rule is that
806 all sections which are not used at runtime are stripped out. But
807 there are a few exceptions:
809 - special sections named ".comment" and ".note" are kept
810 - OS or architecture specific sections are kept since we might not
811 know how to handle them
812 - if a section is referred to from a section which is not removed
813 in the sh_link or sh_info element it cannot be removed either
814 - the user might have explicitly said to remove or keep a section
816 for (cnt = 1; cnt < shnum; ++cnt)
817 /* Check whether the section can be removed. Since we will create
818 a new .shstrtab assume it will be removed too. */
819 if (remove_shdrs ? !(shdr_info[cnt].shdr.sh_flags & SHF_ALLOC)
820 : (ebl_section_strip_p (ebl, &shdr_info[cnt].shdr,
821 shdr_info[cnt].name, remove_comment,
824 || section_name_matches (remove_secs, shdr_info[cnt].name)))
826 /* The user might want to explicitly keep this one. */
827 if (section_name_matches (keep_secs, shdr_info[cnt].name))
830 /* For now assume this section will be removed. */
831 shdr_info[cnt].idx = 0;
833 idx = shdr_info[cnt].group_idx;
836 /* The section group data is already loaded. */
837 elf_assert (shdr_info[idx].data != NULL
838 && shdr_info[idx].data->d_buf != NULL
839 && shdr_info[idx].data->d_size >= sizeof (Elf32_Word));
841 /* If the references section group is a normal section
842 group and has one element remaining, or if it is an
843 empty COMDAT section group it is removed. */
844 bool is_comdat = (((Elf32_Word *) shdr_info[idx].data->d_buf)[0]
847 --shdr_info[idx].group_cnt;
848 if ((!is_comdat && shdr_info[idx].group_cnt == 1)
849 || (is_comdat && shdr_info[idx].group_cnt == 0))
851 shdr_info[idx].idx = 0;
852 /* Continue recursively. */
853 idx = shdr_info[idx].group_idx;
860 /* Mark the SHT_NULL section as handled. */
861 shdr_info[0].idx = 2;
864 /* Handle exceptions: section groups and cross-references. We might
865 have to repeat this a few times since the resetting of the flag
871 for (cnt = 1; cnt < shnum; ++cnt)
873 if (shdr_info[cnt].idx == 0)
875 /* If a relocation section is marked as being removed make
876 sure the section it is relocating is removed, too. */
877 if (shdr_info[cnt].shdr.sh_type == SHT_REL
878 || shdr_info[cnt].shdr.sh_type == SHT_RELA)
880 if (shdr_info[cnt].shdr.sh_info >= shnum)
882 else if (shdr_info[shdr_info[cnt].shdr.sh_info].idx != 0)
883 shdr_info[cnt].idx = 1;
886 /* If a group section is marked as being removed make
887 sure all the sections it contains are being removed, too. */
888 if (shdr_info[cnt].shdr.sh_type == SHT_GROUP)
891 grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
893 in < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
895 if (grpref[in] < shnum)
897 if (shdr_info[grpref[in]].idx != 0)
899 shdr_info[cnt].idx = 1;
908 if (shdr_info[cnt].idx == 1)
910 /* The content of symbol tables we don't remove must not
911 reference any section which we do remove. Otherwise
912 we cannot remove the section. */
913 if (debug_fname != NULL
914 && shdr_info[cnt].debug_data == NULL
915 && (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM
916 || shdr_info[cnt].shdr.sh_type == SHT_SYMTAB))
918 /* Make sure the data is loaded. */
919 if (shdr_info[cnt].data == NULL)
922 = elf_getdata (shdr_info[cnt].scn, NULL);
923 if (shdr_info[cnt].data == NULL)
924 INTERNAL_ERROR (fname);
926 Elf_Data *symdata = shdr_info[cnt].data;
928 /* If there is an extended section index table load it
930 if (shdr_info[cnt].symtab_idx != 0
931 && shdr_info[shdr_info[cnt].symtab_idx].data == NULL)
933 elf_assert (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB);
935 shdr_info[shdr_info[cnt].symtab_idx].data
936 = elf_getdata (shdr_info[shdr_info[cnt].symtab_idx].scn,
938 if (shdr_info[shdr_info[cnt].symtab_idx].data == NULL)
939 INTERNAL_ERROR (fname);
942 = shdr_info[shdr_info[cnt].symtab_idx].data;
944 /* Go through all symbols and make sure the section they
945 reference is not removed. */
946 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
948 for (size_t inner = 0;
949 inner < shdr_info[cnt].data->d_size / elsize;
954 GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
958 INTERNAL_ERROR (fname);
960 size_t scnidx = sym->st_shndx;
961 if (scnidx == SHN_UNDEF || scnidx >= shnum
962 || (scnidx >= SHN_LORESERVE
963 && scnidx <= SHN_HIRESERVE
964 && scnidx != SHN_XINDEX)
965 /* Don't count in the section symbols. */
966 || GELF_ST_TYPE (sym->st_info) == STT_SECTION)
967 /* This is no section index, leave it alone. */
969 else if (scnidx == SHN_XINDEX)
975 if (shdr_info[scnidx].idx == 0)
976 /* This symbol table has a real symbol in
977 a discarded section. So preserve the
978 original table in the debug file. Unless
979 it is a redundant data marker to a debug
980 (data only) section. */
981 if (! (ebl_section_strip_p (ebl,
982 &shdr_info[scnidx].shdr,
983 shdr_info[scnidx].name,
986 && ebl_data_marker_symbol (ebl, sym,
988 shdr_info[cnt].shdr.sh_link,
990 shdr_info[cnt].debug_data = symdata;
994 /* Cross referencing happens:
995 - for the cases the ELF specification says. That are
996 + SHT_DYNAMIC in sh_link to string table
997 + SHT_HASH in sh_link to symbol table
998 + SHT_REL and SHT_RELA in sh_link to symbol table
999 + SHT_SYMTAB and SHT_DYNSYM in sh_link to string table
1000 + SHT_GROUP in sh_link to symbol table
1001 + SHT_SYMTAB_SHNDX in sh_link to symbol table
1002 Other (OS or architecture-specific) sections might as
1003 well use this field so we process it unconditionally.
1004 - references inside section groups
1005 - specially marked references in sh_info if the SHF_INFO_LINK
1009 if (shdr_info[shdr_info[cnt].shdr.sh_link].idx == 0)
1011 shdr_info[shdr_info[cnt].shdr.sh_link].idx = 1;
1012 changes |= shdr_info[cnt].shdr.sh_link < cnt;
1015 /* Handle references through sh_info. */
1016 if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
1018 if (shdr_info[cnt].shdr.sh_info >= shnum)
1020 else if ( shdr_info[shdr_info[cnt].shdr.sh_info].idx == 0)
1022 shdr_info[shdr_info[cnt].shdr.sh_info].idx = 1;
1023 changes |= shdr_info[cnt].shdr.sh_info < cnt;
1027 /* Mark the section as investigated. */
1028 shdr_info[cnt].idx = 2;
1031 if (debug_fname != NULL
1032 && (shdr_info[cnt].idx == 0 || shdr_info[cnt].debug_data != NULL))
1034 /* This section is being preserved in the debug file.
1035 Sections it refers to must be preserved there too.
1037 In this pass we mark sections to be preserved in both
1038 files by setting the .debug_data pointer to the original
1039 file's .data pointer. Below, we'll copy the section
1042 inline void check_preserved (size_t i)
1044 if (i != 0 && i < shnum + 2 && shdr_info[i].idx != 0
1045 && shdr_info[i].debug_data == NULL)
1047 if (shdr_info[i].data == NULL)
1048 shdr_info[i].data = elf_getdata (shdr_info[i].scn, NULL);
1049 if (shdr_info[i].data == NULL)
1050 INTERNAL_ERROR (fname);
1052 shdr_info[i].debug_data = shdr_info[i].data;
1057 check_preserved (shdr_info[cnt].shdr.sh_link);
1058 if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
1059 check_preserved (shdr_info[cnt].shdr.sh_info);
1065 /* Copy the removed sections to the debug output file.
1066 The ones that are not removed in the stripped file are SHT_NOBITS. */
1067 if (debug_fname != NULL)
1069 for (cnt = 1; cnt < shnum; ++cnt)
1071 scn = elf_newscn (debugelf);
1075 error (EXIT_FAILURE, 0,
1076 gettext ("while generating output file: %s"),
1080 bool discard_section = (shdr_info[cnt].idx > 0
1081 && shdr_info[cnt].debug_data == NULL
1082 && shdr_info[cnt].shdr.sh_type != SHT_NOTE
1083 && shdr_info[cnt].shdr.sh_type != SHT_GROUP
1084 && cnt != shstrndx);
1086 /* Set the section header in the new file. */
1087 GElf_Shdr debugshdr = shdr_info[cnt].shdr;
1088 if (discard_section)
1089 debugshdr.sh_type = SHT_NOBITS;
1091 if (unlikely (gelf_update_shdr (scn, &debugshdr) == 0))
1092 /* There cannot be any overflows. */
1093 INTERNAL_ERROR (fname);
1095 /* Get the data from the old file if necessary. */
1096 if (shdr_info[cnt].data == NULL)
1098 shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
1099 if (shdr_info[cnt].data == NULL)
1100 INTERNAL_ERROR (fname);
1103 /* Set the data. This is done by copying from the old file. */
1104 Elf_Data *debugdata = elf_newdata (scn);
1105 if (debugdata == NULL)
1106 INTERNAL_ERROR (fname);
1108 /* Copy the structure. This data may be modified in place
1109 before we write out the file. */
1110 *debugdata = *shdr_info[cnt].data;
1111 if (discard_section)
1112 debugdata->d_buf = NULL;
1113 else if (shdr_info[cnt].debug_data != NULL
1114 || shdr_info[cnt].shdr.sh_type == SHT_GROUP)
1116 /* Copy the original data before it gets modified. */
1117 shdr_info[cnt].debug_data = debugdata;
1118 if (debugdata->d_buf == NULL)
1119 INTERNAL_ERROR (fname);
1120 debugdata->d_buf = memcpy (xmalloc (debugdata->d_size),
1121 debugdata->d_buf, debugdata->d_size);
1125 /* Finish the ELF header. Fill in the fields not handled by
1126 libelf from the old file. */
1127 debugehdr = gelf_getehdr (debugelf, &debugehdr_mem);
1128 if (debugehdr == NULL)
1129 INTERNAL_ERROR (fname);
1131 memcpy (debugehdr->e_ident, ehdr->e_ident, EI_NIDENT);
1132 debugehdr->e_type = ehdr->e_type;
1133 debugehdr->e_machine = ehdr->e_machine;
1134 debugehdr->e_version = ehdr->e_version;
1135 debugehdr->e_entry = ehdr->e_entry;
1136 debugehdr->e_flags = ehdr->e_flags;
1139 if (elf_getshdrstrndx (elf, &shdrstrndx) < 0)
1141 error (0, 0, gettext ("%s: error while getting shdrstrndx: %s"),
1142 fname, elf_errmsg (-1));
1147 if (shstrndx < SHN_LORESERVE)
1148 debugehdr->e_shstrndx = shdrstrndx;
1151 debugehdr->e_shstrndx = SHN_XINDEX;
1152 Elf_Scn *scn0 = elf_getscn (debugelf, 0);
1153 GElf_Shdr shdr0_mem;
1154 GElf_Shdr *shdr0 = gelf_getshdr (scn0, &shdr0_mem);
1157 error (0, 0, gettext ("%s: error getting zero section: %s"),
1158 debug_fname, elf_errmsg (-1));
1163 shdr0->sh_link = shdrstrndx;
1164 if (gelf_update_shdr (scn0, shdr0) == 0)
1166 error (0, 0, gettext ("%s: error while updating zero section: %s"),
1167 debug_fname, elf_errmsg (-1));
1174 if (unlikely (gelf_update_ehdr (debugelf, debugehdr) == 0))
1176 error (0, 0, gettext ("%s: error while creating ELF header: %s"),
1177 debug_fname, elf_errmsg (-1));
1183 /* Although we always create a new section header string table we
1184 don't explicitly mark the existing one as unused. It can still
1185 be used through a symbol table section we are keeping. If not it
1186 will already be marked as unused. */
1188 /* We need a string table for the section headers. */
1189 shst = dwelf_strtab_init (true);
1193 error (EXIT_FAILURE, errno, gettext ("while preparing output for '%s'"),
1194 output_fname ?: fname);
1197 /* Assign new section numbers. */
1198 shdr_info[0].idx = 0;
1199 for (cnt = idx = 1; cnt < shnum; ++cnt)
1200 if (shdr_info[cnt].idx > 0)
1202 shdr_info[cnt].idx = idx++;
1204 /* Create a new section. */
1205 shdr_info[cnt].newscn = elf_newscn (newelf);
1206 if (shdr_info[cnt].newscn == NULL)
1209 error (EXIT_FAILURE, 0,
1210 gettext ("while generating output file: %s"),
1214 elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == shdr_info[cnt].idx);
1216 /* Add this name to the section header string table. */
1217 shdr_info[cnt].se = dwelf_strtab_add (shst, shdr_info[cnt].name);
1220 /* Test whether we are doing anything at all. Either all removable
1221 sections are already gone. Or the only section we would remove is
1222 the .shstrtab section which we would add again. */
1223 bool removing_sections = !(cnt == idx
1225 && shdr_info[shstrndx].idx == 0));
1226 if (output_fname == NULL && !removing_sections)
1229 /* Create the reference to the file with the debug info (if any). */
1230 if (debug_fname != NULL && !remove_shdrs && removing_sections)
1232 /* Add the section header string table section name. */
1233 shdr_info[cnt].se = dwelf_strtab_add_len (shst, ".gnu_debuglink", 15);
1234 shdr_info[cnt].idx = idx++;
1236 /* Create the section header. */
1237 shdr_info[cnt].shdr.sh_type = SHT_PROGBITS;
1238 shdr_info[cnt].shdr.sh_flags = 0;
1239 shdr_info[cnt].shdr.sh_addr = 0;
1240 shdr_info[cnt].shdr.sh_link = SHN_UNDEF;
1241 shdr_info[cnt].shdr.sh_info = SHN_UNDEF;
1242 shdr_info[cnt].shdr.sh_entsize = 0;
1243 shdr_info[cnt].shdr.sh_addralign = 4;
1244 /* We set the offset to zero here. Before we write the ELF file the
1245 field must have the correct value. This is done in the final
1246 loop over all section. Then we have all the information needed. */
1247 shdr_info[cnt].shdr.sh_offset = 0;
1249 /* Create the section. */
1250 shdr_info[cnt].newscn = elf_newscn (newelf);
1251 if (shdr_info[cnt].newscn == NULL)
1254 error (EXIT_FAILURE, 0,
1255 gettext ("while create section header section: %s"),
1258 elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == shdr_info[cnt].idx);
1260 shdr_info[cnt].data = elf_newdata (shdr_info[cnt].newscn);
1261 if (shdr_info[cnt].data == NULL)
1264 error (EXIT_FAILURE, 0, gettext ("cannot allocate section data: %s"),
1268 char *debug_basename = basename (debug_fname_embed ?: debug_fname);
1269 off_t crc_offset = strlen (debug_basename) + 1;
1270 /* Align to 4 byte boundary */
1271 crc_offset = ((crc_offset - 1) & ~3) + 4;
1273 shdr_info[cnt].data->d_align = 4;
1274 shdr_info[cnt].shdr.sh_size = shdr_info[cnt].data->d_size
1276 debuglink_buf = xcalloc (1, shdr_info[cnt].data->d_size);
1277 shdr_info[cnt].data->d_buf = debuglink_buf;
1279 strcpy (shdr_info[cnt].data->d_buf, debug_basename);
1281 /* Cache this Elf_Data describing the CRC32 word in the section.
1282 We'll fill this in when we have written the debug file. */
1283 debuglink_crc_data = *shdr_info[cnt].data;
1284 debuglink_crc_data.d_buf = ((char *) debuglink_crc_data.d_buf
1286 debuglink_crc_data.d_size = 4;
1288 /* One more section done. */
1292 /* Index of the section header table in the shdr_info array. */
1295 /* Add the section header string table section name. */
1296 shdr_info[cnt].se = dwelf_strtab_add_len (shst, ".shstrtab", 10);
1297 shdr_info[cnt].idx = idx;
1299 /* Create the section header. */
1300 shdr_info[cnt].shdr.sh_type = SHT_STRTAB;
1301 shdr_info[cnt].shdr.sh_flags = 0;
1302 shdr_info[cnt].shdr.sh_addr = 0;
1303 shdr_info[cnt].shdr.sh_link = SHN_UNDEF;
1304 shdr_info[cnt].shdr.sh_info = SHN_UNDEF;
1305 shdr_info[cnt].shdr.sh_entsize = 0;
1306 /* We set the offset to zero here. Before we write the ELF file the
1307 field must have the correct value. This is done in the final
1308 loop over all section. Then we have all the information needed. */
1309 shdr_info[cnt].shdr.sh_offset = 0;
1310 shdr_info[cnt].shdr.sh_addralign = 1;
1312 /* Create the section. */
1313 shdr_info[cnt].newscn = elf_newscn (newelf);
1314 if (shdr_info[cnt].newscn == NULL)
1317 error (EXIT_FAILURE, 0,
1318 gettext ("while create section header section: %s"),
1321 elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == idx);
1323 /* Finalize the string table and fill in the correct indices in the
1325 shstrtab_data = elf_newdata (shdr_info[cnt].newscn);
1326 if (shstrtab_data == NULL)
1329 error (EXIT_FAILURE, 0,
1330 gettext ("while create section header string table: %s"),
1333 if (dwelf_strtab_finalize (shst, shstrtab_data) == NULL)
1336 error (EXIT_FAILURE, 0,
1337 gettext ("no memory to create section header string table"));
1340 /* We have to set the section size. */
1341 shdr_info[cnt].shdr.sh_size = shstrtab_data->d_size;
1343 /* Update the section information. */
1344 GElf_Off lastoffset = 0;
1345 for (cnt = 1; cnt <= shdridx; ++cnt)
1346 if (shdr_info[cnt].idx > 0)
1350 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1351 elf_assert (scn != NULL);
1353 /* Update the name. */
1354 shdr_info[cnt].shdr.sh_name = dwelf_strent_off (shdr_info[cnt].se);
1356 /* Update the section header from the input file. Some fields
1357 might be section indeces which now have to be adjusted. Keep
1358 the index to the "current" sh_link in case we need it to lookup
1359 symbol table names. */
1360 size_t sh_link = shdr_info[cnt].shdr.sh_link;
1361 if (shdr_info[cnt].shdr.sh_link != 0)
1362 shdr_info[cnt].shdr.sh_link =
1363 shdr_info[shdr_info[cnt].shdr.sh_link].idx;
1365 if (shdr_info[cnt].shdr.sh_type == SHT_GROUP)
1367 elf_assert (shdr_info[cnt].data != NULL
1368 && shdr_info[cnt].data->d_buf != NULL);
1370 Elf32_Word *grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
1371 for (size_t inner = 0;
1372 inner < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
1374 if (grpref[inner] < shnum)
1375 grpref[inner] = shdr_info[grpref[inner]].idx;
1380 /* Handle the SHT_REL, SHT_RELA, and SHF_INFO_LINK flag. */
1381 if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
1382 shdr_info[cnt].shdr.sh_info =
1383 shdr_info[shdr_info[cnt].shdr.sh_info].idx;
1385 /* Get the data from the old file if necessary. We already
1386 created the data for the section header string table. */
1389 if (shdr_info[cnt].data == NULL)
1391 shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
1392 if (shdr_info[cnt].data == NULL)
1393 INTERNAL_ERROR (fname);
1396 /* Set the data. This is done by copying from the old file. */
1397 newdata = elf_newdata (scn);
1398 if (newdata == NULL)
1399 INTERNAL_ERROR (fname);
1401 /* Copy the structure. */
1402 *newdata = *shdr_info[cnt].data;
1404 /* We know the size. */
1405 shdr_info[cnt].shdr.sh_size = shdr_info[cnt].data->d_size;
1407 /* We have to adjust symbol tables. The st_shndx member might
1408 have to be updated. */
1409 if (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM
1410 || shdr_info[cnt].shdr.sh_type == SHT_SYMTAB)
1412 Elf_Data *versiondata = NULL;
1413 Elf_Data *shndxdata = NULL;
1415 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1417 if (shdr_info[cnt].symtab_idx != 0)
1419 elf_assert (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB_SHNDX);
1420 /* This section has extended section information.
1421 We have to modify that information, too. */
1422 shndxdata = elf_getdata (shdr_info[shdr_info[cnt].symtab_idx].scn,
1425 elf_assert (shndxdata != NULL
1426 && shndxdata->d_buf != NULL
1427 && ((shndxdata->d_size / sizeof (Elf32_Word))
1428 >= shdr_info[cnt].data->d_size / elsize));
1431 if (shdr_info[cnt].version_idx != 0)
1433 elf_assert (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM);
1434 /* This section has associated version
1435 information. We have to modify that
1436 information, too. */
1437 versiondata = elf_getdata (shdr_info[shdr_info[cnt].version_idx].scn,
1440 elf_assert (versiondata != NULL
1441 && versiondata->d_buf != NULL
1442 && ((versiondata->d_size / sizeof (GElf_Versym))
1443 >= shdr_info[cnt].data->d_size / elsize));
1446 shdr_info[cnt].newsymidx
1447 = (Elf32_Word *) xcalloc (shdr_info[cnt].data->d_size
1448 / elsize, sizeof (Elf32_Word));
1450 bool last_was_local = true;
1453 for (destidx = inner = 1;
1454 inner < shdr_info[cnt].data->d_size / elsize;
1460 GElf_Sym *sym = gelf_getsymshndx (shdr_info[cnt].data,
1464 INTERNAL_ERROR (fname);
1466 if (sym->st_shndx == SHN_UNDEF
1467 || (sym->st_shndx >= shnum
1468 && sym->st_shndx != SHN_XINDEX))
1470 /* This is no section index, leave it alone
1471 unless it is moved. */
1472 if (destidx != inner
1473 && gelf_update_symshndx (shdr_info[cnt].data,
1477 INTERNAL_ERROR (fname);
1479 shdr_info[cnt].newsymidx[inner] = destidx++;
1482 && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
1484 last_was_local = false;
1485 shdr_info[cnt].shdr.sh_info = destidx - 1;
1491 /* Get the full section index, if necessary from the
1493 if (sym->st_shndx == SHN_XINDEX)
1494 elf_assert (shndxdata != NULL
1495 && shndxdata->d_buf != NULL);
1496 size_t sidx = (sym->st_shndx != SHN_XINDEX
1497 ? sym->st_shndx : xshndx);
1498 sec = shdr_info[sidx].idx;
1502 GElf_Section nshndx;
1505 if (sec < SHN_LORESERVE)
1512 nshndx = SHN_XINDEX;
1516 elf_assert (sec < SHN_LORESERVE || shndxdata != NULL);
1518 if ((inner != destidx || nshndx != sym->st_shndx
1519 || (shndxdata != NULL && nxshndx != xshndx))
1520 && (sym->st_shndx = nshndx,
1521 gelf_update_symshndx (shdr_info[cnt].data,
1525 INTERNAL_ERROR (fname);
1527 shdr_info[cnt].newsymidx[inner] = destidx++;
1530 && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
1532 last_was_local = false;
1533 shdr_info[cnt].shdr.sh_info = destidx - 1;
1536 else if ((shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) != 0
1537 && GELF_ST_TYPE (sym->st_info) != STT_SECTION
1538 && shdr_info[sidx].shdr.sh_type != SHT_GROUP)
1540 /* Removing a real symbol from an allocated
1541 symbol table is hard and probably a
1542 mistake. Really removing it means
1543 rewriting the dynamic segment and hash
1544 sections. Just warn and set the symbol
1545 section to UNDEF. */
1547 gettext ("Cannot remove symbol [%zd] from allocated symbol table [%zd]"), inner, cnt);
1548 sym->st_shndx = SHN_UNDEF;
1549 if (gelf_update_sym (shdr_info[cnt].data, destidx,
1551 INTERNAL_ERROR (fname);
1552 shdr_info[cnt].newsymidx[inner] = destidx++;
1554 else if (debug_fname != NULL
1555 && shdr_info[cnt].debug_data == NULL)
1556 /* The symbol points to a section that is discarded
1557 but isn't preserved in the debug file. Check that
1558 this is a section or group signature symbol
1559 for a section which has been removed. Or a special
1560 data marker symbol to a debug section. */
1562 elf_assert (GELF_ST_TYPE (sym->st_info) == STT_SECTION
1563 || ((shdr_info[sidx].shdr.sh_type
1565 && (shdr_info[sidx].shdr.sh_info
1567 || ebl_data_marker_symbol (ebl, sym,
1568 elf_strptr (elf, sh_link,
1573 if (destidx != inner)
1575 /* The size of the symbol table changed. */
1576 shdr_info[cnt].shdr.sh_size = newdata->d_size
1578 any_symtab_changes = true;
1582 /* The symbol table didn't really change. */
1583 free (shdr_info[cnt].newsymidx);
1584 shdr_info[cnt].newsymidx = NULL;
1589 /* If we have to, compute the offset of the section.
1590 If allocate and unallocated sections are mixed, we only update
1591 the allocated ones now. The unallocated ones come second. */
1592 if (! mixed_allocated_unallocated
1593 || (shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) != 0)
1595 if (shdr_info[cnt].shdr.sh_offset == 0)
1596 shdr_info[cnt].shdr.sh_offset
1597 = ((lastoffset + shdr_info[cnt].shdr.sh_addralign - 1)
1598 & ~((GElf_Off) (shdr_info[cnt].shdr.sh_addralign - 1)));
1600 /* Set the section header in the new file. */
1601 if (unlikely (gelf_update_shdr (scn, &shdr_info[cnt].shdr) == 0))
1602 /* There cannot be any overflows. */
1603 INTERNAL_ERROR (fname);
1605 /* Remember the last section written so far. */
1606 GElf_Off filesz = (shdr_info[cnt].shdr.sh_type != SHT_NOBITS
1607 ? shdr_info[cnt].shdr.sh_size : 0);
1608 if (lastoffset < shdr_info[cnt].shdr.sh_offset + filesz)
1609 lastoffset = shdr_info[cnt].shdr.sh_offset + filesz;
1613 /* We might have to update the unallocated sections after we done the
1614 allocated ones. lastoffset is set to right after the last allocated
1616 if (mixed_allocated_unallocated)
1617 for (cnt = 1; cnt <= shdridx; ++cnt)
1618 if (shdr_info[cnt].idx > 0)
1620 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1621 if ((shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) == 0)
1623 if (shdr_info[cnt].shdr.sh_offset == 0)
1624 shdr_info[cnt].shdr.sh_offset
1625 = ((lastoffset + shdr_info[cnt].shdr.sh_addralign - 1)
1626 & ~((GElf_Off) (shdr_info[cnt].shdr.sh_addralign - 1)));
1628 /* Set the section header in the new file. */
1629 if (unlikely (gelf_update_shdr (scn, &shdr_info[cnt].shdr) == 0))
1630 /* There cannot be any overflows. */
1631 INTERNAL_ERROR (fname);
1633 /* Remember the last section written so far. */
1634 GElf_Off filesz = (shdr_info[cnt].shdr.sh_type != SHT_NOBITS
1635 ? shdr_info[cnt].shdr.sh_size : 0);
1636 if (lastoffset < shdr_info[cnt].shdr.sh_offset + filesz)
1637 lastoffset = shdr_info[cnt].shdr.sh_offset + filesz;
1641 /* Adjust symbol references if symbol tables changed. */
1642 if (any_symtab_changes)
1643 /* Find all relocation sections which use this symbol table. */
1644 for (cnt = 1; cnt <= shdridx; ++cnt)
1646 /* Update section headers when the data size has changed.
1647 We also update the SHT_NOBITS section in the debug
1648 file so that the section headers match in sh_size. */
1649 inline void update_section_size (const Elf_Data *newdata)
1652 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1653 shdr->sh_size = newdata->d_size;
1654 (void) gelf_update_shdr (scn, shdr);
1655 if (debugelf != NULL)
1657 /* libelf will use d_size to set sh_size. */
1658 Elf_Data *debugdata = elf_getdata (elf_getscn (debugelf,
1660 if (debugdata == NULL)
1661 INTERNAL_ERROR (fname);
1662 debugdata->d_size = newdata->d_size;
1666 if (shdr_info[cnt].idx == 0 && debug_fname == NULL)
1667 /* Ignore sections which are discarded. When we are saving a
1668 relocation section in a separate debug file, we must fix up
1669 the symbol table references. */
1672 const Elf32_Word symtabidx = shdr_info[cnt].old_sh_link;
1673 elf_assert (symtabidx < shnum + 2);
1674 const Elf32_Word *const newsymidx = shdr_info[symtabidx].newsymidx;
1675 switch (shdr_info[cnt].shdr.sh_type)
1677 inline bool no_symtab_updates (void)
1679 /* If the symbol table hasn't changed, do not do anything. */
1680 if (shdr_info[symtabidx].newsymidx == NULL)
1683 /* If the symbol table is not discarded, but additionally
1684 duplicated in the separate debug file and this section
1685 is discarded, don't adjust anything. */
1686 return (shdr_info[cnt].idx == 0
1687 && shdr_info[symtabidx].debug_data != NULL);
1692 if (no_symtab_updates ())
1695 Elf_Data *d = elf_getdata (shdr_info[cnt].idx == 0
1696 ? elf_getscn (debugelf, cnt)
1697 : elf_getscn (newelf,
1698 shdr_info[cnt].idx),
1700 elf_assert (d != NULL && d->d_buf != NULL
1701 && shdr_info[cnt].shdr.sh_entsize != 0);
1702 size_t nrels = (shdr_info[cnt].shdr.sh_size
1703 / shdr_info[cnt].shdr.sh_entsize);
1705 size_t symsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1706 const Elf32_Word symidxn = (shdr_info[symtabidx].data->d_size
1708 if (shdr_info[cnt].shdr.sh_type == SHT_REL)
1709 for (size_t relidx = 0; relidx < nrels; ++relidx)
1712 if (gelf_getrel (d, relidx, &rel_mem) == NULL)
1713 INTERNAL_ERROR (fname);
1715 size_t symidx = GELF_R_SYM (rel_mem.r_info);
1716 elf_assert (symidx < symidxn);
1717 if (newsymidx[symidx] != symidx)
1720 = GELF_R_INFO (newsymidx[symidx],
1721 GELF_R_TYPE (rel_mem.r_info));
1723 if (gelf_update_rel (d, relidx, &rel_mem) == 0)
1724 INTERNAL_ERROR (fname);
1728 for (size_t relidx = 0; relidx < nrels; ++relidx)
1731 if (gelf_getrela (d, relidx, &rel_mem) == NULL)
1732 INTERNAL_ERROR (fname);
1734 size_t symidx = GELF_R_SYM (rel_mem.r_info);
1735 elf_assert (symidx < symidxn);
1736 if (newsymidx[symidx] != symidx)
1739 = GELF_R_INFO (newsymidx[symidx],
1740 GELF_R_TYPE (rel_mem.r_info));
1742 if (gelf_update_rela (d, relidx, &rel_mem) == 0)
1743 INTERNAL_ERROR (fname);
1749 if (no_symtab_updates ())
1752 /* We have to recompute the hash table. */
1754 elf_assert (shdr_info[cnt].idx > 0);
1756 /* The hash section in the new file. */
1757 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1759 /* The symbol table data. */
1760 Elf_Data *symd = elf_getdata (elf_getscn (newelf,
1761 shdr_info[symtabidx].idx),
1763 elf_assert (symd != NULL && symd->d_buf != NULL);
1765 /* The hash table data. */
1766 Elf_Data *hashd = elf_getdata (scn, NULL);
1767 elf_assert (hashd != NULL && hashd->d_buf != NULL);
1769 if (shdr_info[cnt].shdr.sh_entsize == sizeof (Elf32_Word))
1771 /* Sane arches first. */
1772 elf_assert (hashd->d_size >= 2 * sizeof (Elf32_Word));
1773 Elf32_Word *bucket = (Elf32_Word *) hashd->d_buf;
1775 size_t strshndx = shdr_info[symtabidx].old_sh_link;
1776 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1778 Elf32_Word nchain = bucket[1];
1779 Elf32_Word nbucket = bucket[0];
1780 uint64_t used_buf = ((2ULL + nchain + nbucket)
1781 * sizeof (Elf32_Word));
1782 elf_assert (used_buf <= hashd->d_size);
1784 /* Adjust the nchain value. The symbol table size
1785 changed. We keep the same size for the bucket array. */
1786 bucket[1] = symd->d_size / elsize;
1788 Elf32_Word *chain = bucket + nbucket;
1790 /* New size of the section. */
1791 size_t n_size = ((2 + symd->d_size / elsize + nbucket)
1792 * sizeof (Elf32_Word));
1793 elf_assert (n_size <= hashd->d_size);
1794 hashd->d_size = n_size;
1795 update_section_size (hashd);
1797 /* Clear the arrays. */
1798 memset (bucket, '\0',
1799 (symd->d_size / elsize + nbucket)
1800 * sizeof (Elf32_Word));
1802 for (size_t inner = shdr_info[symtabidx].shdr.sh_info;
1803 inner < symd->d_size / elsize; ++inner)
1806 GElf_Sym *sym = gelf_getsym (symd, inner, &sym_mem);
1807 elf_assert (sym != NULL);
1809 const char *name = elf_strptr (elf, strshndx,
1811 elf_assert (name != NULL && nbucket != 0);
1812 size_t hidx = elf_hash (name) % nbucket;
1814 if (bucket[hidx] == 0)
1815 bucket[hidx] = inner;
1818 hidx = bucket[hidx];
1820 while (chain[hidx] != 0 && chain[hidx] < nchain)
1823 chain[hidx] = inner;
1829 /* Alpha and S390 64-bit use 64-bit SHT_HASH entries. */
1830 elf_assert (shdr_info[cnt].shdr.sh_entsize
1831 == sizeof (Elf64_Xword));
1833 Elf64_Xword *bucket = (Elf64_Xword *) hashd->d_buf;
1835 size_t strshndx = shdr_info[symtabidx].old_sh_link;
1836 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1838 elf_assert (symd->d_size >= 2 * sizeof (Elf64_Xword));
1839 Elf64_Xword nbucket = bucket[0];
1840 Elf64_Xword nchain = bucket[1];
1841 uint64_t maxwords = hashd->d_size / sizeof (Elf64_Xword);
1842 elf_assert (maxwords >= 2
1843 && maxwords - 2 >= nbucket
1844 && maxwords - 2 - nbucket >= nchain);
1846 /* Adjust the nchain value. The symbol table size
1847 changed. We keep the same size for the bucket array. */
1848 bucket[1] = symd->d_size / elsize;
1850 Elf64_Xword *chain = bucket + nbucket;
1852 /* New size of the section. */
1853 size_t n_size = ((2 + symd->d_size / elsize + nbucket)
1854 * sizeof (Elf64_Xword));
1855 elf_assert (n_size <= hashd->d_size);
1856 hashd->d_size = n_size;
1857 update_section_size (hashd);
1859 /* Clear the arrays. */
1860 memset (bucket, '\0',
1861 (symd->d_size / elsize + nbucket)
1862 * sizeof (Elf64_Xword));
1864 for (size_t inner = shdr_info[symtabidx].shdr.sh_info;
1865 inner < symd->d_size / elsize; ++inner)
1868 GElf_Sym *sym = gelf_getsym (symd, inner, &sym_mem);
1869 elf_assert (sym != NULL);
1871 const char *name = elf_strptr (elf, strshndx,
1873 elf_assert (name != NULL && nbucket != 0);
1874 size_t hidx = elf_hash (name) % nbucket;
1876 if (bucket[hidx] == 0)
1877 bucket[hidx] = inner;
1880 hidx = bucket[hidx];
1882 while (chain[hidx] != 0 && chain[hidx] < nchain)
1885 chain[hidx] = inner;
1891 case SHT_GNU_versym:
1892 /* If the symbol table changed we have to adjust the entries. */
1893 if (no_symtab_updates ())
1896 elf_assert (shdr_info[cnt].idx > 0);
1898 /* The symbol version section in the new file. */
1899 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1901 /* The symbol table data. */
1902 symd = elf_getdata (elf_getscn (newelf, shdr_info[symtabidx].idx),
1904 elf_assert (symd != NULL && symd->d_buf != NULL);
1905 size_t symz = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1906 const Elf32_Word syms = (shdr_info[symtabidx].data->d_size / symz);
1908 /* The version symbol data. */
1909 Elf_Data *verd = elf_getdata (scn, NULL);
1910 elf_assert (verd != NULL && verd->d_buf != NULL);
1912 /* The symbol version array. */
1913 GElf_Half *verstab = (GElf_Half *) verd->d_buf;
1915 /* Walk through the list and */
1916 size_t elsize = gelf_fsize (elf, verd->d_type, 1, EV_CURRENT);
1917 Elf32_Word vers = verd->d_size / elsize;
1918 for (size_t inner = 1; inner < vers && inner < syms; ++inner)
1919 if (newsymidx[inner] != 0 && newsymidx[inner] < vers)
1920 /* Overwriting the same array works since the
1921 reordering can only move entries to lower indices
1923 verstab[newsymidx[inner]] = verstab[inner];
1925 /* New size of the section. */
1926 verd->d_size = gelf_fsize (newelf, verd->d_type,
1928 / gelf_fsize (elf, symd->d_type, 1,
1931 update_section_size (verd);
1935 if (no_symtab_updates ())
1938 /* Yes, the symbol table changed.
1939 Update the section header of the section group. */
1940 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1942 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1943 elf_assert (shdr != NULL);
1945 size_t symsz = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1946 const Elf32_Word symn = (shdr_info[symtabidx].data->d_size
1948 elf_assert (shdr->sh_info < symn);
1949 shdr->sh_info = newsymidx[shdr->sh_info];
1951 (void) gelf_update_shdr (scn, shdr);
1956 /* Remove any relocations between debug sections in ET_REL
1957 for the debug file when requested. These relocations are always
1958 zero based between the unallocated sections. */
1959 if (debug_fname != NULL && removing_sections
1960 && reloc_debug && ehdr->e_type == ET_REL)
1964 while ((scn = elf_nextscn (debugelf, scn)) != NULL)
1967 /* We need the actual section and header from the debugelf
1968 not just the cached original in shdr_info because we
1969 might want to change the size. */
1971 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1972 if (shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
1974 /* Make sure that this relocation section points to a
1975 section to relocate with contents, that isn't
1976 allocated and that is a debug section. */
1977 Elf_Scn *tscn = elf_getscn (debugelf, shdr->sh_info);
1978 GElf_Shdr tshdr_mem;
1979 GElf_Shdr *tshdr = gelf_getshdr (tscn, &tshdr_mem);
1980 if (tshdr->sh_type == SHT_NOBITS
1981 || tshdr->sh_size == 0
1982 || (tshdr->sh_flags & SHF_ALLOC) != 0)
1985 const char *tname = elf_strptr (debugelf, shstrndx,
1987 if (! tname || ! ebl_debugscn_p (ebl, tname))
1990 /* OK, lets relocate all trivial cross debug section
1992 Elf_Data *reldata = elf_getdata (scn, NULL);
1993 if (reldata == NULL || reldata->d_buf == NULL)
1994 INTERNAL_ERROR (fname);
1996 /* Make sure we adjust the uncompressed debug data
1997 (and recompress if necessary at the end). */
1999 int tcompress_type = 0;
2000 if (gelf_getchdr (tscn, &tchdr) != NULL)
2002 tcompress_type = tchdr.ch_type;
2003 if (elf_compress (tscn, 0, 0) != 1)
2004 INTERNAL_ERROR (fname);
2007 Elf_Data *tdata = elf_getdata (tscn, NULL);
2008 if (tdata == NULL || tdata->d_buf == NULL
2009 || tdata->d_type != ELF_T_BYTE)
2010 INTERNAL_ERROR (fname);
2012 /* Pick up the symbol table and shndx table to
2013 resolve relocation symbol indexes. */
2014 Elf64_Word symt = shdr->sh_link;
2015 Elf_Data *symdata, *xndxdata;
2016 elf_assert (symt < shnum + 2);
2017 elf_assert (shdr_info[symt].symtab_idx < shnum + 2);
2018 symdata = (shdr_info[symt].debug_data
2019 ?: shdr_info[symt].data);
2020 xndxdata = (shdr_info[shdr_info[symt].symtab_idx].debug_data
2021 ?: shdr_info[shdr_info[symt].symtab_idx].data);
2023 /* Apply one relocation. Returns true when trivial
2024 relocation actually done. */
2025 bool relocate (GElf_Addr offset, const GElf_Sxword addend,
2026 bool is_rela, int rtype, int symndx)
2028 /* R_*_NONE relocs can always just be removed. */
2032 /* We only do simple absolute relocations. */
2034 Elf_Type type = ebl_reloc_simple_type (ebl, rtype, &addsub);
2035 if (type == ELF_T_NUM)
2038 /* These are the types we can relocate. */
2039 #define TYPES DO_TYPE (BYTE, Byte); DO_TYPE (HALF, Half); \
2040 DO_TYPE (WORD, Word); DO_TYPE (SWORD, Sword); \
2041 DO_TYPE (XWORD, Xword); DO_TYPE (SXWORD, Sxword)
2043 /* And only for relocations against other debug sections. */
2046 GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
2049 Elf32_Word sec = (sym->st_shndx == SHN_XINDEX
2050 ? xndx : sym->st_shndx);
2051 if (sec >= shnum + 2)
2052 INTERNAL_ERROR (fname);
2054 if (ebl_debugscn_p (ebl, shdr_info[sec].name))
2058 #define DO_TYPE(NAME, Name) GElf_##Name Name;
2059 union { TYPES; } tmpbuf;
2064 #define DO_TYPE(NAME, Name) \
2065 case ELF_T_##NAME: \
2066 size = sizeof (GElf_##Name); \
2075 if (offset > tdata->d_size
2076 || tdata->d_size - offset < size)
2079 error (EXIT_FAILURE, 0, gettext ("bad relocation"));
2082 /* When the symbol value is zero then for SHT_REL
2083 sections this is all that needs to be checked.
2084 The addend is contained in the original data at
2085 the offset already. So if the (section) symbol
2086 address is zero and the given addend is zero
2087 just remove the relocation, it isn't needed
2089 if (addend == 0 && sym->st_value == 0)
2097 .d_version = EV_CURRENT,
2102 .d_buf = tdata->d_buf + offset,
2104 .d_version = EV_CURRENT,
2107 GElf_Addr value = sym->st_value;
2110 /* For SHT_RELA sections we just take the
2111 given addend and add it to the value. */
2113 /* For ADD/SUB relocations we need to fetch the
2114 current section contents. */
2117 Elf_Data *d = gelf_xlatetom (debugelf, &tmpdata,
2119 ehdr->e_ident[EI_DATA]);
2121 INTERNAL_ERROR (fname);
2122 assert (d == &tmpdata);
2127 /* For SHT_REL sections we have to peek at
2128 what is already in the section at the given
2129 offset to get the addend. */
2130 Elf_Data *d = gelf_xlatetom (debugelf, &tmpdata,
2132 ehdr->e_ident[EI_DATA]);
2134 INTERNAL_ERROR (fname);
2135 assert (d == &tmpdata);
2140 #define DO_TYPE(NAME, Name) \
2141 case ELF_T_##NAME: \
2143 tmpbuf.Name -= (GElf_##Name) value; \
2145 tmpbuf.Name += (GElf_##Name) value; \
2153 /* Now finally put in the new value. */
2154 Elf_Data *s = gelf_xlatetof (debugelf, &rdata,
2156 ehdr->e_ident[EI_DATA]);
2158 INTERNAL_ERROR (fname);
2159 assert (s == &rdata);
2166 if (shdr->sh_entsize == 0)
2167 INTERNAL_ERROR (fname);
2169 size_t nrels = shdr->sh_size / shdr->sh_entsize;
2171 if (shdr->sh_type == SHT_REL)
2172 for (size_t relidx = 0; relidx < nrels; ++relidx)
2175 GElf_Rel *r = gelf_getrel (reldata, relidx, &rel_mem);
2176 if (! relocate (r->r_offset, 0, false,
2177 GELF_R_TYPE (r->r_info),
2178 GELF_R_SYM (r->r_info)))
2181 gelf_update_rel (reldata, next, r);
2186 for (size_t relidx = 0; relidx < nrels; ++relidx)
2189 GElf_Rela *r = gelf_getrela (reldata, relidx, &rela_mem);
2190 if (! relocate (r->r_offset, r->r_addend, true,
2191 GELF_R_TYPE (r->r_info),
2192 GELF_R_SYM (r->r_info)))
2195 gelf_update_rela (reldata, next, r);
2201 shdr->sh_size = reldata->d_size = nrels * shdr->sh_entsize;
2202 gelf_update_shdr (scn, shdr);
2204 if (tcompress_type != 0)
2205 if (elf_compress (tscn, tcompress_type, ELF_CHF_FORCE) != 1)
2206 INTERNAL_ERROR (fname);
2211 /* Now that we have done all adjustments to the data,
2212 we can actually write out the debug file. */
2213 if (debug_fname != NULL && removing_sections)
2215 /* Finally write the file. */
2216 if (unlikely (elf_update (debugelf, ELF_C_WRITE) == -1))
2218 error (0, 0, gettext ("while writing '%s': %s"),
2219 tmp_debug_fname, elf_errmsg (-1));
2224 /* Create the real output file. First rename, then change the
2226 if (rename (tmp_debug_fname, debug_fname) != 0
2227 || fchmod (debug_fd, mode) != 0)
2229 error (0, errno, gettext ("while creating '%s'"), debug_fname);
2234 /* The temporary file does not exist anymore. */
2235 free (tmp_debug_fname);
2236 tmp_debug_fname = NULL;
2241 Elf_Data debug_crc_data =
2243 .d_type = ELF_T_WORD,
2244 .d_buf = &debug_crc,
2245 .d_size = sizeof (debug_crc),
2246 .d_version = EV_CURRENT
2249 /* Compute the checksum which we will add to the executable. */
2250 if (crc32_file (debug_fd, &debug_crc) != 0)
2252 error (0, errno, gettext ("\
2253 while computing checksum for debug information"));
2254 unlink (debug_fname);
2259 /* Store it in the debuglink section data. */
2260 if (unlikely (gelf_xlatetof (newelf, &debuglink_crc_data,
2261 &debug_crc_data, ehdr->e_ident[EI_DATA])
2262 != &debuglink_crc_data))
2263 INTERNAL_ERROR (fname);
2267 /* Finally finish the ELF header. Fill in the fields not handled by
2268 libelf from the old file. */
2269 newehdr = gelf_getehdr (newelf, &newehdr_mem);
2270 if (newehdr == NULL)
2271 INTERNAL_ERROR (fname);
2273 memcpy (newehdr->e_ident, ehdr->e_ident, EI_NIDENT);
2274 newehdr->e_type = ehdr->e_type;
2275 newehdr->e_machine = ehdr->e_machine;
2276 newehdr->e_version = ehdr->e_version;
2277 newehdr->e_entry = ehdr->e_entry;
2278 newehdr->e_flags = ehdr->e_flags;
2279 newehdr->e_phoff = ehdr->e_phoff;
2281 /* We need to position the section header table. */
2282 const size_t offsize = gelf_fsize (elf, ELF_T_OFF, 1, EV_CURRENT);
2283 newehdr->e_shoff = ((shdr_info[shdridx].shdr.sh_offset
2284 + shdr_info[shdridx].shdr.sh_size + offsize - 1)
2285 & ~((GElf_Off) (offsize - 1)));
2286 newehdr->e_shentsize = gelf_fsize (elf, ELF_T_SHDR, 1, EV_CURRENT);
2288 /* The new section header string table index. */
2289 if (likely (idx < SHN_HIRESERVE) && likely (idx != SHN_XINDEX))
2290 newehdr->e_shstrndx = idx;
2293 /* The index does not fit in the ELF header field. */
2294 shdr_info[0].scn = elf_getscn (elf, 0);
2296 if (gelf_getshdr (shdr_info[0].scn, &shdr_info[0].shdr) == NULL)
2297 INTERNAL_ERROR (fname);
2299 shdr_info[0].shdr.sh_link = idx;
2300 (void) gelf_update_shdr (shdr_info[0].scn, &shdr_info[0].shdr);
2302 newehdr->e_shstrndx = SHN_XINDEX;
2305 if (gelf_update_ehdr (newelf, newehdr) == 0)
2307 error (0, 0, gettext ("%s: error while creating ELF header: %s"),
2308 output_fname ?: fname, elf_errmsg (-1));
2313 /* We have everything from the old file. */
2314 if (elf_cntl (elf, ELF_C_FDDONE) != 0)
2316 error (0, 0, gettext ("%s: error while reading the file: %s"),
2317 fname, elf_errmsg (-1));
2322 /* The ELF library better follows our layout when this is not a
2323 relocatable object file. */
2324 elf_flagelf (newelf, ELF_C_SET,
2325 (ehdr->e_type != ET_REL ? ELF_F_LAYOUT : 0)
2326 | (permissive ? ELF_F_PERMISSIVE : 0));
2328 /* Finally write the file. */
2329 if (elf_update (newelf, ELF_C_WRITE) == -1)
2331 error (0, 0, gettext ("while writing '%s': %s"),
2332 output_fname ?: fname, elf_errmsg (-1));
2338 /* libelf can't cope without the section headers being properly intact.
2339 So we just let it write them normally, and then we nuke them later. */
2341 if (newehdr->e_ident[EI_CLASS] == ELFCLASS32)
2343 assert (offsetof (Elf32_Ehdr, e_shentsize) + sizeof (Elf32_Half)
2344 == offsetof (Elf32_Ehdr, e_shnum));
2345 assert (offsetof (Elf32_Ehdr, e_shnum) + sizeof (Elf32_Half)
2346 == offsetof (Elf32_Ehdr, e_shstrndx));
2347 const Elf32_Off zero_off = 0;
2348 const Elf32_Half zero[3] = { 0, 0, SHN_UNDEF };
2349 if (pwrite_retry (fd, &zero_off, sizeof zero_off,
2350 offsetof (Elf32_Ehdr, e_shoff)) != sizeof zero_off
2351 || (pwrite_retry (fd, zero, sizeof zero,
2352 offsetof (Elf32_Ehdr, e_shentsize))
2354 || ftruncate (fd, shdr_info[shdridx].shdr.sh_offset) < 0)
2356 error (0, errno, gettext ("while writing '%s'"),
2357 output_fname ?: fname);
2363 assert (offsetof (Elf64_Ehdr, e_shentsize) + sizeof (Elf64_Half)
2364 == offsetof (Elf64_Ehdr, e_shnum));
2365 assert (offsetof (Elf64_Ehdr, e_shnum) + sizeof (Elf64_Half)
2366 == offsetof (Elf64_Ehdr, e_shstrndx));
2367 const Elf64_Off zero_off = 0;
2368 const Elf64_Half zero[3] = { 0, 0, SHN_UNDEF };
2369 if (pwrite_retry (fd, &zero_off, sizeof zero_off,
2370 offsetof (Elf64_Ehdr, e_shoff)) != sizeof zero_off
2371 || (pwrite_retry (fd, zero, sizeof zero,
2372 offsetof (Elf64_Ehdr, e_shentsize))
2374 || ftruncate (fd, shdr_info[shdridx].shdr.sh_offset) < 0)
2376 error (0, errno, gettext ("while writing '%s'"),
2377 output_fname ?: fname);
2384 if (shdr_info != NULL)
2386 /* For some sections we might have created an table to map symbol
2387 table indices. Or we might kept (original) data around to put
2388 into the .debug file. */
2389 for (cnt = 1; cnt <= shdridx; ++cnt)
2391 free (shdr_info[cnt].newsymidx);
2392 if (shdr_info[cnt].debug_data != NULL)
2393 free (shdr_info[cnt].debug_data->d_buf);
2396 /* Free data we allocated for the .gnu_debuglink section. */
2397 free (debuglink_buf);
2399 /* Free the memory. */
2400 if ((shnum + 2) * sizeof (struct shdr_info) > MAX_STACK_ALLOC)
2404 /* Free other resources. */
2405 if (shstrtab_data != NULL)
2406 free (shstrtab_data->d_buf);
2408 dwelf_strtab_free (shst);
2410 /* That was it. Close the descriptors. */
2411 if (elf_end (newelf) != 0)
2413 error (0, 0, gettext ("error while finishing '%s': %s"),
2414 output_fname ?: fname, elf_errmsg (-1));
2418 if (debugelf != NULL && elf_end (debugelf) != 0)
2420 error (0, 0, gettext ("error while finishing '%s': %s"), debug_fname,
2426 /* Close the EBL backend. */
2428 ebl_closebackend (ebl);
2432 /* If requested, preserve the timestamp. */
2435 if (futimens (fd, tvp) != 0)
2437 error (0, errno, gettext ("\
2438 cannot set access and modification date of '%s'"),
2439 output_fname ?: fname);
2444 /* Close the file descriptor if we created a new file. */
2445 if (output_fname != NULL)
2449 unlink (output_fname);
2456 cleanup_debug (void)
2460 if (tmp_debug_fname != NULL)
2462 unlink (tmp_debug_fname);
2463 free (tmp_debug_fname);
2464 tmp_debug_fname = NULL;
2472 handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
2473 struct timespec tvp[2])
2475 size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
2476 size_t fname_len = strlen (fname) + 1;
2477 char new_prefix[prefix_len + 1 + fname_len];
2478 char *cp = new_prefix;
2480 /* Create the full name of the file. */
2483 cp = mempcpy (cp, prefix, prefix_len);
2486 memcpy (cp, fname, fname_len);
2489 /* Process all the files contained in the archive. */
2491 Elf_Cmd cmd = ELF_C_RDWR;
2493 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
2495 /* The the header for this element. */
2496 Elf_Arhdr *arhdr = elf_getarhdr (subelf);
2498 if (elf_kind (subelf) == ELF_K_ELF)
2499 result |= handle_elf (fd, subelf, new_prefix, arhdr->ar_name, 0, NULL);
2500 else if (elf_kind (subelf) == ELF_K_AR)
2501 result |= handle_ar (fd, subelf, new_prefix, arhdr->ar_name, NULL);
2503 /* Get next archive element. */
2504 cmd = elf_next (subelf);
2505 if (unlikely (elf_end (subelf) != 0))
2506 INTERNAL_ERROR (fname);
2511 if (unlikely (futimens (fd, tvp) != 0))
2513 error (0, errno, gettext ("\
2514 cannot set access and modification date of '%s'"), fname);
2519 if (unlikely (close (fd) != 0))
2520 error (EXIT_FAILURE, errno, gettext ("while closing '%s'"), fname);
2526 #include "debugpred.h"