1 /* Discard section not used at runtime from object files.
2 Copyright (C) 2000-2012, 2014, 2015 Red Hat, Inc.
3 This file is part of elfutils.
4 Written by Ulrich Drepper <drepper@redhat.com>, 2000.
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>
39 #include <sys/param.h>
43 #include <elf-knowledge.h>
47 typedef uint8_t GElf_Byte;
49 /* Name and version of program. */
50 static void print_version (FILE *stream, struct argp_state *state);
51 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
53 /* Bug report address. */
54 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
57 /* Values for the parameters which have no short form. */
58 #define OPT_REMOVE_COMMENT 0x100
59 #define OPT_PERMISSIVE 0x101
60 #define OPT_STRIP_SECTIONS 0x102
61 #define OPT_RELOC_DEBUG 0x103
64 /* Definitions of arguments for argp functions. */
65 static const struct argp_option options[] =
67 { NULL, 0, NULL, 0, N_("Output selection:"), 0 },
68 { "output", 'o', "FILE", 0, N_("Place stripped output into FILE"), 0 },
69 { NULL, 'f', "FILE", 0, N_("Extract the removed sections into FILE"), 0 },
70 { NULL, 'F', "FILE", 0, N_("Embed name FILE instead of -f argument"), 0 },
72 { NULL, 0, NULL, 0, N_("Output options:"), 0 },
73 { "strip-all", 's', NULL, OPTION_HIDDEN, NULL, 0 },
74 { "strip-debug", 'g', NULL, 0, N_("Remove all debugging symbols"), 0 },
75 { NULL, 'd', NULL, OPTION_ALIAS, NULL, 0 },
76 { NULL, 'S', NULL, OPTION_ALIAS, NULL, 0 },
77 { "strip-sections", OPT_STRIP_SECTIONS, NULL, 0,
78 N_("Remove section headers (not recommended)"), 0 },
79 { "preserve-dates", 'p', NULL, 0,
80 N_("Copy modified/access timestamps to the output"), 0 },
81 { "reloc-debug-sections", OPT_RELOC_DEBUG, NULL, 0,
82 N_("Resolve all trivial relocations between debug sections if the removed sections are placed in a debug file (only relevant for ET_REL files, operation is not reversable, needs -f)"), 0 },
83 { "remove-comment", OPT_REMOVE_COMMENT, NULL, 0,
84 N_("Remove .comment section"), 0 },
85 { "remove-section", 'R', "SECTION", OPTION_HIDDEN, NULL, 0 },
86 { "permissive", OPT_PERMISSIVE, NULL, 0,
87 N_("Relax a few rules to handle slightly broken ELF files"), 0 },
88 { NULL, 0, NULL, 0, NULL, 0 }
91 /* Short description of program. */
92 static const char doc[] = N_("Discard symbols from object files.");
94 /* Strings for arguments in help texts. */
95 static const char args_doc[] = N_("[FILE...]");
97 /* Prototype for option handler. */
98 static error_t parse_opt (int key, char *arg, struct argp_state *state);
100 /* Data structure to communicate with argp functions. */
101 static struct argp argp =
103 options, parse_opt, args_doc, doc, NULL, NULL, NULL
107 /* Print symbols in file named FNAME. */
108 static int process_file (const char *fname);
110 /* Handle one ELF file. */
111 static int handle_elf (int fd, Elf *elf, const char *prefix,
112 const char *fname, mode_t mode, struct timespec tvp[2]);
114 /* Handle all files contained in the archive. */
115 static int handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
116 struct timespec tvp[2]) __attribute__ ((unused));
118 static int debug_fd = -1;
119 static char *tmp_debug_fname = NULL;
121 /* Close debug file descriptor, if opened. And remove temporary debug file. */
122 static void cleanup_debug (void);
124 #define INTERNAL_ERROR(fname) \
127 error (EXIT_FAILURE, 0, gettext ("%s: INTERNAL ERROR %d (%s): %s"), \
128 fname, __LINE__, PACKAGE_VERSION, elf_errmsg (-1)); \
132 /* Name of the output file. */
133 static const char *output_fname;
135 /* Name of the debug output file. */
136 static const char *debug_fname;
138 /* Name to pretend the debug output file has. */
139 static const char *debug_fname_embed;
141 /* If true output files shall have same date as the input file. */
142 static bool preserve_dates;
144 /* If true .comment sections will be removed. */
145 static bool remove_comment;
147 /* If true remove all debug sections. */
148 static bool remove_debug;
150 /* If true remove all section headers. */
151 static bool remove_shdrs;
153 /* If true relax some ELF rules for input files. */
154 static bool permissive;
156 /* If true perform relocations between debug sections. */
157 static bool reloc_debug;
161 main (int argc, char *argv[])
166 /* We use no threads here which can interfere with handling a stream. */
167 __fsetlocking (stdin, FSETLOCKING_BYCALLER);
168 __fsetlocking (stdout, FSETLOCKING_BYCALLER);
169 __fsetlocking (stderr, FSETLOCKING_BYCALLER);
172 setlocale (LC_ALL, "");
174 /* Make sure the message catalog can be found. */
175 bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
177 /* Initialize the message catalog. */
178 textdomain (PACKAGE_TARNAME);
180 /* Parse and process arguments. */
181 if (argp_parse (&argp, argc, argv, 0, &remaining, NULL) != 0)
184 if (reloc_debug && debug_fname == NULL)
185 error (EXIT_FAILURE, 0,
186 gettext ("--reloc-debug-sections used without -f"));
188 /* Tell the library which version we are expecting. */
189 elf_version (EV_CURRENT);
191 if (remaining == argc)
192 /* The user didn't specify a name so we use a.out. */
193 result = process_file ("a.out");
196 /* If we have seen the '-o' or '-f' option there must be exactly one
198 if ((output_fname != NULL || debug_fname != NULL)
199 && remaining + 1 < argc)
200 error (EXIT_FAILURE, 0, gettext ("\
201 Only one input file allowed together with '-o' and '-f'"));
203 /* Process all the remaining files. */
205 result |= process_file (argv[remaining]);
206 while (++remaining < argc);
213 /* Print the version information. */
215 print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
217 fprintf (stream, "strip (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
218 fprintf (stream, gettext ("\
219 Copyright (C) %s Red Hat, Inc.\n\
220 This is free software; see the source for copying conditions. There is NO\n\
221 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
223 fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
227 /* Handle program arguments. */
229 parse_opt (int key, char *arg, struct argp_state *state)
234 if (debug_fname != NULL)
236 error (0, 0, gettext ("-f option specified twice"));
243 if (debug_fname_embed != NULL)
245 error (0, 0, gettext ("-F option specified twice"));
248 debug_fname_embed = arg;
252 if (output_fname != NULL)
254 error (0, 0, gettext ("-o option specified twice"));
261 preserve_dates = true;
264 case OPT_RELOC_DEBUG:
268 case OPT_REMOVE_COMMENT:
269 remove_comment = true;
273 if (!strcmp (arg, ".comment"))
274 remove_comment = true;
278 gettext ("-R option supports only .comment section"));
289 case OPT_STRIP_SECTIONS:
297 case 's': /* Ignored for compatibility. */
301 return ARGP_ERR_UNKNOWN;
308 process_file (const char *fname)
310 /* If we have to preserve the modify and access timestamps get them
311 now. We cannot use fstat() after opening the file since the open
312 would change the access time. */
314 struct timespec tv[2];
318 if (stat (fname, &pre_st) != 0)
320 error (0, errno, gettext ("cannot stat input file '%s'"), fname);
324 /* If we have to preserve the timestamp, we need it in the
325 format utimes() understands. */
326 tv[0] = pre_st.st_atim;
327 tv[1] = pre_st.st_mtim;
331 int fd = open (fname, output_fname == NULL ? O_RDWR : O_RDONLY);
334 error (0, errno, gettext ("while opening '%s'"), fname);
338 /* We always use fstat() even if we called stat() before. This is
339 done to make sure the information returned by stat() is for the
342 if (fstat (fd, &st) != 0)
344 error (0, errno, gettext ("cannot stat input file '%s'"), fname);
347 /* Paranoid mode on. */
349 && (st.st_ino != pre_st.st_ino || st.st_dev != pre_st.st_dev))
351 /* We detected a race. Try again. */
356 /* Now get the ELF descriptor. */
357 Elf *elf = elf_begin (fd, output_fname == NULL ? ELF_C_RDWR : ELF_C_READ,
360 switch (elf_kind (elf))
363 result = handle_elf (fd, elf, NULL, fname, st.st_mode & ACCESSPERMS,
364 preserve_dates ? tv : NULL);
368 /* It is not possible to strip the content of an archive direct
369 the output to a specific file. */
370 if (unlikely (output_fname != NULL || debug_fname != NULL))
372 error (0, 0, gettext ("%s: cannot use -o or -f when stripping archive"),
378 /* We would like to support ar archives, but currently it just
379 doesn't work at all since we call elf_clone on the members
380 which doesn't really support ar members.
381 result = handle_ar (fd, elf, NULL, fname,
382 preserve_dates ? tv : NULL);
384 error (0, 0, gettext ("%s: no support for stripping archive"),
391 error (0, 0, gettext ("%s: File format not recognized"), fname);
396 if (unlikely (elf_end (elf) != 0))
397 INTERNAL_ERROR (fname);
405 /* Maximum size of array allocated on stack. */
406 #define MAX_STACK_ALLOC (400 * 1024)
409 handle_elf (int fd, Elf *elf, const char *prefix, const char *fname,
410 mode_t mode, struct timespec tvp[2])
412 size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
413 size_t fname_len = strlen (fname) + 1;
414 char *fullname = alloca (prefix_len + 1 + fname_len);
416 Elf *debugelf = NULL;
417 tmp_debug_fname = NULL;
426 Elf_Data *debug_data;
428 Elf32_Word idx; /* Index in new file. */
429 Elf32_Word old_sh_link; /* Original value of shdr.sh_link. */
430 Elf32_Word symtab_idx;
431 Elf32_Word version_idx;
432 Elf32_Word group_idx;
433 Elf32_Word group_cnt;
435 struct Ebl_Strent *se;
436 Elf32_Word *newsymidx;
442 GElf_Ehdr newehdr_mem;
444 GElf_Ehdr debugehdr_mem;
445 GElf_Ehdr *debugehdr;
446 struct Ebl_Strtab *shst = NULL;
447 Elf_Data debuglink_crc_data;
448 bool any_symtab_changes = false;
449 Elf_Data *shstrtab_data = NULL;
450 void *debuglink_buf = NULL;
452 /* Create the full name of the file. */
455 cp = mempcpy (cp, prefix, prefix_len);
458 memcpy (cp, fname, fname_len);
460 /* If we are not replacing the input file open a new file here. */
461 if (output_fname != NULL)
463 fd = open (output_fname, O_RDWR | O_CREAT, mode);
464 if (unlikely (fd == -1))
466 error (0, errno, gettext ("cannot open '%s'"), output_fname);
473 /* Get the EBL handling. Removing all debugging symbols with the -g
474 option or resolving all relocations between debug sections with
475 the --reloc-debug-sections option are currently the only reasons
476 we need EBL so don't open the backend unless necessary. */
478 if (remove_debug || reloc_debug)
480 ebl = ebl_openbackend (elf);
483 error (0, errno, gettext ("cannot open EBL backend"));
489 /* Open the additional file the debug information will be stored in. */
490 if (debug_fname != NULL)
492 /* Create a temporary file name. We do not want to overwrite
493 the debug file if the file would not contain any
495 size_t debug_fname_len = strlen (debug_fname);
496 tmp_debug_fname = (char *) xmalloc (debug_fname_len + sizeof (".XXXXXX"));
497 strcpy (mempcpy (tmp_debug_fname, debug_fname, debug_fname_len),
500 debug_fd = mkstemp (tmp_debug_fname);
501 if (unlikely (debug_fd == -1))
503 error (0, errno, gettext ("cannot open '%s'"), debug_fname);
509 /* Get the information from the old file. */
511 GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
513 INTERNAL_ERROR (fname);
515 /* Get the section header string table index. */
516 if (unlikely (elf_getshdrstrndx (elf, &shstrndx) < 0))
519 error (EXIT_FAILURE, 0,
520 gettext ("cannot get section header string table index"));
523 /* Get the number of phdrs in the old file. */
525 if (elf_getphdrnum (elf, &phnum) != 0)
528 error (EXIT_FAILURE, 0, gettext ("cannot get number of phdrs"));
531 /* We now create a new ELF descriptor for the same file. We
532 construct it almost exactly in the same way with some information
535 if (output_fname != NULL)
536 newelf = elf_begin (fd, ELF_C_WRITE_MMAP, NULL);
538 newelf = elf_clone (elf, ELF_C_EMPTY);
540 if (unlikely (gelf_newehdr (newelf, gelf_getclass (elf)) == 0)
541 || (ehdr->e_type != ET_REL
542 && unlikely (gelf_newphdr (newelf, phnum) == 0)))
544 error (0, 0, gettext ("cannot create new file '%s': %s"),
545 output_fname ?: fname, elf_errmsg (-1));
549 /* Copy over the old program header if needed. */
550 if (ehdr->e_type != ET_REL)
551 for (cnt = 0; cnt < phnum; ++cnt)
554 GElf_Phdr *phdr = gelf_getphdr (elf, cnt, &phdr_mem);
556 || unlikely (gelf_update_phdr (newelf, cnt, phdr) == 0))
557 INTERNAL_ERROR (fname);
560 if (debug_fname != NULL)
562 /* Also create an ELF descriptor for the debug file */
563 debugelf = elf_begin (debug_fd, ELF_C_WRITE_MMAP, NULL);
564 if (unlikely (gelf_newehdr (debugelf, gelf_getclass (elf)) == 0)
565 || (ehdr->e_type != ET_REL
566 && unlikely (gelf_newphdr (debugelf, phnum) == 0)))
568 error (0, 0, gettext ("cannot create new file '%s': %s"),
569 debug_fname, elf_errmsg (-1));
573 /* Copy over the old program header if needed. */
574 if (ehdr->e_type != ET_REL)
575 for (cnt = 0; cnt < phnum; ++cnt)
578 GElf_Phdr *phdr = gelf_getphdr (elf, cnt, &phdr_mem);
580 || unlikely (gelf_update_phdr (debugelf, cnt, phdr) == 0))
581 INTERNAL_ERROR (fname);
585 /* Number of sections. */
587 if (unlikely (elf_getshdrnum (elf, &shnum) < 0))
589 error (0, 0, gettext ("cannot determine number of sections: %s"),
594 if (shstrndx >= shnum)
597 #define elf_assert(test) do { if (!(test)) goto illformed; } while (0)
599 /* Storage for section information. We leave room for two more
600 entries since we unconditionally create a section header string
601 table. Maybe some weird tool created an ELF file without one.
602 The other one is used for the debug link section. */
603 if ((shnum + 2) * sizeof (struct shdr_info) > MAX_STACK_ALLOC)
604 shdr_info = (struct shdr_info *) xcalloc (shnum + 2,
605 sizeof (struct shdr_info));
608 shdr_info = (struct shdr_info *) alloca ((shnum + 2)
609 * sizeof (struct shdr_info));
610 memset (shdr_info, '\0', (shnum + 2) * sizeof (struct shdr_info));
613 /* Prepare section information data structure. */
616 while ((scn = elf_nextscn (elf, scn)) != NULL)
618 /* This should always be true (i.e., there should not be any
619 holes in the numbering). */
620 elf_assert (elf_ndxscn (scn) == cnt);
622 shdr_info[cnt].scn = scn;
624 /* Get the header. */
625 if (gelf_getshdr (scn, &shdr_info[cnt].shdr) == NULL)
626 INTERNAL_ERROR (fname);
628 /* Get the name of the section. */
629 shdr_info[cnt].name = elf_strptr (elf, shstrndx,
630 shdr_info[cnt].shdr.sh_name);
631 if (shdr_info[cnt].name == NULL)
634 error (0, 0, gettext ("illformed file '%s'"), fname);
638 /* Mark them as present but not yet investigated. */
639 shdr_info[cnt].idx = 1;
641 /* Remember the shdr.sh_link value. */
642 shdr_info[cnt].old_sh_link = shdr_info[cnt].shdr.sh_link;
643 if (shdr_info[cnt].old_sh_link >= shnum)
646 /* Sections in files other than relocatable object files which
647 not loaded can be freely moved by us. In theory we can also
648 freely move around allocated nobits sections. But we don't
649 to keep the layout of all allocated sections as similar as
650 possible to the original file. In relocatable object files
651 everything can be moved. */
652 if (ehdr->e_type == ET_REL
653 || (shdr_info[cnt].shdr.sh_flags & SHF_ALLOC) == 0)
654 shdr_info[cnt].shdr.sh_offset = 0;
656 /* If this is an extended section index table store an
657 appropriate reference. */
658 if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB_SHNDX))
660 elf_assert (shdr_info[shdr_info[cnt].shdr.sh_link].symtab_idx == 0);
661 shdr_info[shdr_info[cnt].shdr.sh_link].symtab_idx = cnt;
663 else if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_GROUP))
665 /* Cross-reference the sections contained in the section
667 shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
668 if (shdr_info[cnt].data == NULL
669 || shdr_info[cnt].data->d_size < sizeof (Elf32_Word))
670 INTERNAL_ERROR (fname);
672 /* XXX Fix for unaligned access. */
673 Elf32_Word *grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
676 inner < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
679 if (grpref[inner] < shnum)
680 shdr_info[grpref[inner]].group_idx = cnt;
685 if (inner == 1 || (inner == 2 && (grpref[0] & GRP_COMDAT) == 0))
686 /* If the section group contains only one element and this
687 is n COMDAT section we can drop it right away. */
688 shdr_info[cnt].idx = 0;
690 shdr_info[cnt].group_cnt = inner - 1;
692 else if (unlikely (shdr_info[cnt].shdr.sh_type == SHT_GNU_versym))
694 elf_assert (shdr_info[shdr_info[cnt].shdr.sh_link].version_idx == 0);
695 shdr_info[shdr_info[cnt].shdr.sh_link].version_idx = cnt;
698 /* If this section is part of a group make sure it is not
699 discarded right away. */
700 if ((shdr_info[cnt].shdr.sh_flags & SHF_GROUP) != 0)
702 elf_assert (shdr_info[cnt].group_idx != 0);
704 if (shdr_info[shdr_info[cnt].group_idx].idx == 0)
706 /* The section group section will be removed. */
707 shdr_info[cnt].group_idx = 0;
708 shdr_info[cnt].shdr.sh_flags &= ~SHF_GROUP;
712 /* Increment the counter. */
716 /* Now determine which sections can go away. The general rule is that
717 all sections which are not used at runtime are stripped out. But
718 there are a few exceptions:
720 - special sections named ".comment" and ".note" are kept
721 - OS or architecture specific sections are kept since we might not
722 know how to handle them
723 - if a section is referred to from a section which is not removed
724 in the sh_link or sh_info element it cannot be removed either
726 for (cnt = 1; cnt < shnum; ++cnt)
727 /* Check whether the section can be removed. */
728 if (remove_shdrs ? !(shdr_info[cnt].shdr.sh_flags & SHF_ALLOC)
729 : ebl_section_strip_p (ebl, ehdr, &shdr_info[cnt].shdr,
730 shdr_info[cnt].name, remove_comment,
733 /* For now assume this section will be removed. */
734 shdr_info[cnt].idx = 0;
736 idx = shdr_info[cnt].group_idx;
739 /* The section group data is already loaded. */
740 elf_assert (shdr_info[idx].data != NULL
741 && shdr_info[idx].data->d_buf != NULL
742 && shdr_info[idx].data->d_size >= sizeof (Elf32_Word));
744 /* If the references section group is a normal section
745 group and has one element remaining, or if it is an
746 empty COMDAT section group it is removed. */
747 bool is_comdat = (((Elf32_Word *) shdr_info[idx].data->d_buf)[0]
750 --shdr_info[idx].group_cnt;
751 if ((!is_comdat && shdr_info[idx].group_cnt == 1)
752 || (is_comdat && shdr_info[idx].group_cnt == 0))
754 shdr_info[idx].idx = 0;
755 /* Continue recursively. */
756 idx = shdr_info[idx].group_idx;
763 /* Mark the SHT_NULL section as handled. */
764 shdr_info[0].idx = 2;
767 /* Handle exceptions: section groups and cross-references. We might
768 have to repeat this a few times since the resetting of the flag
774 for (cnt = 1; cnt < shnum; ++cnt)
776 if (shdr_info[cnt].idx == 0)
778 /* If a relocation section is marked as being removed make
779 sure the section it is relocating is removed, too. */
780 if (shdr_info[cnt].shdr.sh_type == SHT_REL
781 || shdr_info[cnt].shdr.sh_type == SHT_RELA)
783 if (shdr_info[cnt].shdr.sh_info >= shnum)
785 else if (shdr_info[shdr_info[cnt].shdr.sh_info].idx != 0)
786 shdr_info[cnt].idx = 1;
789 /* If a group section is marked as being removed make
790 sure all the sections it contains are being removed, too. */
791 if (shdr_info[cnt].shdr.sh_type == SHT_GROUP)
794 grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
796 in < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
798 if (grpref[in] < shnum)
800 if (shdr_info[grpref[in]].idx != 0)
802 shdr_info[cnt].idx = 1;
811 if (shdr_info[cnt].idx == 1)
813 /* The content of symbol tables we don't remove must not
814 reference any section which we do remove. Otherwise
815 we cannot remove the section. */
816 if (debug_fname != NULL
817 && shdr_info[cnt].debug_data == NULL
818 && (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM
819 || shdr_info[cnt].shdr.sh_type == SHT_SYMTAB))
821 /* Make sure the data is loaded. */
822 if (shdr_info[cnt].data == NULL)
825 = elf_getdata (shdr_info[cnt].scn, NULL);
826 if (shdr_info[cnt].data == NULL)
827 INTERNAL_ERROR (fname);
829 Elf_Data *symdata = shdr_info[cnt].data;
831 /* If there is an extended section index table load it
833 if (shdr_info[cnt].symtab_idx != 0
834 && shdr_info[shdr_info[cnt].symtab_idx].data == NULL)
836 elf_assert (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB);
838 shdr_info[shdr_info[cnt].symtab_idx].data
839 = elf_getdata (shdr_info[shdr_info[cnt].symtab_idx].scn,
841 if (shdr_info[shdr_info[cnt].symtab_idx].data == NULL)
842 INTERNAL_ERROR (fname);
845 = shdr_info[shdr_info[cnt].symtab_idx].data;
847 /* Go through all symbols and make sure the section they
848 reference is not removed. */
849 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
851 for (size_t inner = 0;
852 inner < shdr_info[cnt].data->d_size / elsize;
857 GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
861 INTERNAL_ERROR (fname);
863 size_t scnidx = sym->st_shndx;
864 if (scnidx == SHN_UNDEF || scnidx >= shnum
865 || (scnidx >= SHN_LORESERVE
866 && scnidx <= SHN_HIRESERVE
867 && scnidx != SHN_XINDEX)
868 /* Don't count in the section symbols. */
869 || GELF_ST_TYPE (sym->st_info) == STT_SECTION)
870 /* This is no section index, leave it alone. */
872 else if (scnidx == SHN_XINDEX)
878 if (shdr_info[scnidx].idx == 0)
879 /* This symbol table has a real symbol in
880 a discarded section. So preserve the
881 original table in the debug file. */
882 shdr_info[cnt].debug_data = symdata;
886 /* Cross referencing happens:
887 - for the cases the ELF specification says. That are
888 + SHT_DYNAMIC in sh_link to string table
889 + SHT_HASH in sh_link to symbol table
890 + SHT_REL and SHT_RELA in sh_link to symbol table
891 + SHT_SYMTAB and SHT_DYNSYM in sh_link to string table
892 + SHT_GROUP in sh_link to symbol table
893 + SHT_SYMTAB_SHNDX in sh_link to symbol table
894 Other (OS or architecture-specific) sections might as
895 well use this field so we process it unconditionally.
896 - references inside section groups
897 - specially marked references in sh_info if the SHF_INFO_LINK
901 if (shdr_info[shdr_info[cnt].shdr.sh_link].idx == 0)
903 shdr_info[shdr_info[cnt].shdr.sh_link].idx = 1;
904 changes |= shdr_info[cnt].shdr.sh_link < cnt;
907 /* Handle references through sh_info. */
908 if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
910 if (shdr_info[cnt].shdr.sh_info >= shnum)
912 else if ( shdr_info[shdr_info[cnt].shdr.sh_info].idx == 0)
914 shdr_info[shdr_info[cnt].shdr.sh_info].idx = 1;
915 changes |= shdr_info[cnt].shdr.sh_info < cnt;
919 /* Mark the section as investigated. */
920 shdr_info[cnt].idx = 2;
923 if (debug_fname != NULL
924 && (shdr_info[cnt].idx == 0 || shdr_info[cnt].debug_data != NULL))
926 /* This section is being preserved in the debug file.
927 Sections it refers to must be preserved there too.
929 In this pass we mark sections to be preserved in both
930 files by setting the .debug_data pointer to the original
931 file's .data pointer. Below, we'll copy the section
934 inline void check_preserved (size_t i)
936 if (i != 0 && i < shnum + 2 && shdr_info[i].idx != 0
937 && shdr_info[i].debug_data == NULL)
939 if (shdr_info[i].data == NULL)
940 shdr_info[i].data = elf_getdata (shdr_info[i].scn, NULL);
941 if (shdr_info[i].data == NULL)
942 INTERNAL_ERROR (fname);
944 shdr_info[i].debug_data = shdr_info[i].data;
949 check_preserved (shdr_info[cnt].shdr.sh_link);
950 if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
951 check_preserved (shdr_info[cnt].shdr.sh_info);
957 /* Copy the removed sections to the debug output file.
958 The ones that are not removed in the stripped file are SHT_NOBITS. */
959 if (debug_fname != NULL)
961 for (cnt = 1; cnt < shnum; ++cnt)
963 scn = elf_newscn (debugelf);
967 error (EXIT_FAILURE, 0,
968 gettext ("while generating output file: %s"),
972 bool discard_section = (shdr_info[cnt].idx > 0
973 && shdr_info[cnt].debug_data == NULL
974 && shdr_info[cnt].shdr.sh_type != SHT_NOTE
975 && shdr_info[cnt].shdr.sh_type != SHT_GROUP
976 && cnt != ehdr->e_shstrndx);
978 /* Set the section header in the new file. */
979 GElf_Shdr debugshdr = shdr_info[cnt].shdr;
981 debugshdr.sh_type = SHT_NOBITS;
983 if (unlikely (gelf_update_shdr (scn, &debugshdr) == 0))
984 /* There cannot be any overflows. */
985 INTERNAL_ERROR (fname);
987 /* Get the data from the old file if necessary. */
988 if (shdr_info[cnt].data == NULL)
990 shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
991 if (shdr_info[cnt].data == NULL)
992 INTERNAL_ERROR (fname);
995 /* Set the data. This is done by copying from the old file. */
996 Elf_Data *debugdata = elf_newdata (scn);
997 if (debugdata == NULL)
998 INTERNAL_ERROR (fname);
1000 /* Copy the structure. This data may be modified in place
1001 before we write out the file. */
1002 *debugdata = *shdr_info[cnt].data;
1003 if (discard_section)
1004 debugdata->d_buf = NULL;
1005 else if (shdr_info[cnt].debug_data != NULL
1006 || shdr_info[cnt].shdr.sh_type == SHT_GROUP)
1008 /* Copy the original data before it gets modified. */
1009 shdr_info[cnt].debug_data = debugdata;
1010 if (debugdata->d_buf == NULL)
1011 INTERNAL_ERROR (fname);
1012 debugdata->d_buf = memcpy (xmalloc (debugdata->d_size),
1013 debugdata->d_buf, debugdata->d_size);
1017 /* Finish the ELF header. Fill in the fields not handled by
1018 libelf from the old file. */
1019 debugehdr = gelf_getehdr (debugelf, &debugehdr_mem);
1020 if (debugehdr == NULL)
1021 INTERNAL_ERROR (fname);
1023 memcpy (debugehdr->e_ident, ehdr->e_ident, EI_NIDENT);
1024 debugehdr->e_type = ehdr->e_type;
1025 debugehdr->e_machine = ehdr->e_machine;
1026 debugehdr->e_version = ehdr->e_version;
1027 debugehdr->e_entry = ehdr->e_entry;
1028 debugehdr->e_flags = ehdr->e_flags;
1029 debugehdr->e_shstrndx = ehdr->e_shstrndx;
1031 if (unlikely (gelf_update_ehdr (debugelf, debugehdr) == 0))
1033 error (0, 0, gettext ("%s: error while creating ELF header: %s"),
1034 debug_fname, elf_errmsg (-1));
1040 /* Although we always create a new section header string table we
1041 don't explicitly mark the existing one as unused. It can still
1042 be used through a symbol table section we are keeping. If not it
1043 will already be marked as unused. */
1045 /* We need a string table for the section headers. */
1046 shst = ebl_strtabinit (true);
1050 error (EXIT_FAILURE, errno, gettext ("while preparing output for '%s'"),
1051 output_fname ?: fname);
1054 /* Assign new section numbers. */
1055 shdr_info[0].idx = 0;
1056 for (cnt = idx = 1; cnt < shnum; ++cnt)
1057 if (shdr_info[cnt].idx > 0)
1059 shdr_info[cnt].idx = idx++;
1061 /* Create a new section. */
1062 shdr_info[cnt].newscn = elf_newscn (newelf);
1063 if (shdr_info[cnt].newscn == NULL)
1066 error (EXIT_FAILURE, 0,
1067 gettext ("while generating output file: %s"),
1071 elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == shdr_info[cnt].idx);
1073 /* Add this name to the section header string table. */
1074 shdr_info[cnt].se = ebl_strtabadd (shst, shdr_info[cnt].name, 0);
1077 /* Test whether we are doing anything at all. */
1079 /* Nope, all removable sections are already gone. */
1082 /* Create the reference to the file with the debug info. */
1083 if (debug_fname != NULL && !remove_shdrs)
1085 /* Add the section header string table section name. */
1086 shdr_info[cnt].se = ebl_strtabadd (shst, ".gnu_debuglink", 15);
1087 shdr_info[cnt].idx = idx++;
1089 /* Create the section header. */
1090 shdr_info[cnt].shdr.sh_type = SHT_PROGBITS;
1091 shdr_info[cnt].shdr.sh_flags = 0;
1092 shdr_info[cnt].shdr.sh_addr = 0;
1093 shdr_info[cnt].shdr.sh_link = SHN_UNDEF;
1094 shdr_info[cnt].shdr.sh_info = SHN_UNDEF;
1095 shdr_info[cnt].shdr.sh_entsize = 0;
1096 shdr_info[cnt].shdr.sh_addralign = 4;
1097 /* We set the offset to zero here. Before we write the ELF file the
1098 field must have the correct value. This is done in the final
1099 loop over all section. Then we have all the information needed. */
1100 shdr_info[cnt].shdr.sh_offset = 0;
1102 /* Create the section. */
1103 shdr_info[cnt].newscn = elf_newscn (newelf);
1104 if (shdr_info[cnt].newscn == NULL)
1107 error (EXIT_FAILURE, 0,
1108 gettext ("while create section header section: %s"),
1111 elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == shdr_info[cnt].idx);
1113 shdr_info[cnt].data = elf_newdata (shdr_info[cnt].newscn);
1114 if (shdr_info[cnt].data == NULL)
1117 error (EXIT_FAILURE, 0, gettext ("cannot allocate section data: %s"),
1121 char *debug_basename = basename (debug_fname_embed ?: debug_fname);
1122 off_t crc_offset = strlen (debug_basename) + 1;
1123 /* Align to 4 byte boundary */
1124 crc_offset = ((crc_offset - 1) & ~3) + 4;
1126 shdr_info[cnt].data->d_align = 4;
1127 shdr_info[cnt].shdr.sh_size = shdr_info[cnt].data->d_size
1129 debuglink_buf = xcalloc (1, shdr_info[cnt].data->d_size);
1130 shdr_info[cnt].data->d_buf = debuglink_buf;
1132 strcpy (shdr_info[cnt].data->d_buf, debug_basename);
1134 /* Cache this Elf_Data describing the CRC32 word in the section.
1135 We'll fill this in when we have written the debug file. */
1136 debuglink_crc_data = *shdr_info[cnt].data;
1137 debuglink_crc_data.d_buf = ((char *) debuglink_crc_data.d_buf
1139 debuglink_crc_data.d_size = 4;
1141 /* One more section done. */
1145 /* Index of the section header table in the shdr_info array. */
1148 /* Add the section header string table section name. */
1149 shdr_info[cnt].se = ebl_strtabadd (shst, ".shstrtab", 10);
1150 shdr_info[cnt].idx = idx;
1152 /* Create the section header. */
1153 shdr_info[cnt].shdr.sh_type = SHT_STRTAB;
1154 shdr_info[cnt].shdr.sh_flags = 0;
1155 shdr_info[cnt].shdr.sh_addr = 0;
1156 shdr_info[cnt].shdr.sh_link = SHN_UNDEF;
1157 shdr_info[cnt].shdr.sh_info = SHN_UNDEF;
1158 shdr_info[cnt].shdr.sh_entsize = 0;
1159 /* We set the offset to zero here. Before we write the ELF file the
1160 field must have the correct value. This is done in the final
1161 loop over all section. Then we have all the information needed. */
1162 shdr_info[cnt].shdr.sh_offset = 0;
1163 shdr_info[cnt].shdr.sh_addralign = 1;
1165 /* Create the section. */
1166 shdr_info[cnt].newscn = elf_newscn (newelf);
1167 if (shdr_info[cnt].newscn == NULL)
1170 error (EXIT_FAILURE, 0,
1171 gettext ("while create section header section: %s"),
1174 elf_assert (elf_ndxscn (shdr_info[cnt].newscn) == idx);
1176 /* Finalize the string table and fill in the correct indices in the
1178 shstrtab_data = elf_newdata (shdr_info[cnt].newscn);
1179 if (shstrtab_data == NULL)
1182 error (EXIT_FAILURE, 0,
1183 gettext ("while create section header string table: %s"),
1186 ebl_strtabfinalize (shst, shstrtab_data);
1188 /* We have to set the section size. */
1189 shdr_info[cnt].shdr.sh_size = shstrtab_data->d_size;
1191 /* Update the section information. */
1192 GElf_Off lastoffset = 0;
1193 for (cnt = 1; cnt <= shdridx; ++cnt)
1194 if (shdr_info[cnt].idx > 0)
1198 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1199 elf_assert (scn != NULL);
1201 /* Update the name. */
1202 shdr_info[cnt].shdr.sh_name = ebl_strtaboffset (shdr_info[cnt].se);
1204 /* Update the section header from the input file. Some fields
1205 might be section indeces which now have to be adjusted. */
1206 if (shdr_info[cnt].shdr.sh_link != 0)
1207 shdr_info[cnt].shdr.sh_link =
1208 shdr_info[shdr_info[cnt].shdr.sh_link].idx;
1210 if (shdr_info[cnt].shdr.sh_type == SHT_GROUP)
1212 elf_assert (shdr_info[cnt].data != NULL
1213 && shdr_info[cnt].data->d_buf != NULL);
1215 Elf32_Word *grpref = (Elf32_Word *) shdr_info[cnt].data->d_buf;
1216 for (size_t inner = 0;
1217 inner < shdr_info[cnt].data->d_size / sizeof (Elf32_Word);
1219 if (grpref[inner] < shnum)
1220 grpref[inner] = shdr_info[grpref[inner]].idx;
1225 /* Handle the SHT_REL, SHT_RELA, and SHF_INFO_LINK flag. */
1226 if (SH_INFO_LINK_P (&shdr_info[cnt].shdr))
1227 shdr_info[cnt].shdr.sh_info =
1228 shdr_info[shdr_info[cnt].shdr.sh_info].idx;
1230 /* Get the data from the old file if necessary. We already
1231 created the data for the section header string table. */
1234 if (shdr_info[cnt].data == NULL)
1236 shdr_info[cnt].data = elf_getdata (shdr_info[cnt].scn, NULL);
1237 if (shdr_info[cnt].data == NULL)
1238 INTERNAL_ERROR (fname);
1241 /* Set the data. This is done by copying from the old file. */
1242 newdata = elf_newdata (scn);
1243 if (newdata == NULL)
1244 INTERNAL_ERROR (fname);
1246 /* Copy the structure. */
1247 *newdata = *shdr_info[cnt].data;
1249 /* We know the size. */
1250 shdr_info[cnt].shdr.sh_size = shdr_info[cnt].data->d_size;
1252 /* We have to adjust symbol tables. The st_shndx member might
1253 have to be updated. */
1254 if (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM
1255 || shdr_info[cnt].shdr.sh_type == SHT_SYMTAB)
1257 Elf_Data *versiondata = NULL;
1258 Elf_Data *shndxdata = NULL;
1260 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1262 if (shdr_info[cnt].symtab_idx != 0)
1264 elf_assert (shdr_info[cnt].shdr.sh_type == SHT_SYMTAB_SHNDX);
1265 /* This section has extended section information.
1266 We have to modify that information, too. */
1267 shndxdata = elf_getdata (shdr_info[shdr_info[cnt].symtab_idx].scn,
1270 elf_assert ((versiondata->d_size / sizeof (Elf32_Word))
1271 >= shdr_info[cnt].data->d_size / elsize);
1274 if (shdr_info[cnt].version_idx != 0)
1276 elf_assert (shdr_info[cnt].shdr.sh_type == SHT_DYNSYM);
1277 /* This section has associated version
1278 information. We have to modify that
1279 information, too. */
1280 versiondata = elf_getdata (shdr_info[shdr_info[cnt].version_idx].scn,
1283 elf_assert (versiondata != NULL
1284 && versiondata->d_buf != NULL
1285 && ((versiondata->d_size / sizeof (GElf_Versym))
1286 >= shdr_info[cnt].data->d_size / elsize));
1289 shdr_info[cnt].newsymidx
1290 = (Elf32_Word *) xcalloc (shdr_info[cnt].data->d_size
1291 / elsize, sizeof (Elf32_Word));
1293 bool last_was_local = true;
1296 for (destidx = inner = 1;
1297 inner < shdr_info[cnt].data->d_size / elsize;
1303 GElf_Sym *sym = gelf_getsymshndx (shdr_info[cnt].data,
1307 INTERNAL_ERROR (fname);
1309 if (sym->st_shndx == SHN_UNDEF
1310 || (sym->st_shndx >= shnum
1311 && sym->st_shndx != SHN_XINDEX))
1313 /* This is no section index, leave it alone
1314 unless it is moved. */
1315 if (destidx != inner
1316 && gelf_update_symshndx (shdr_info[cnt].data,
1320 INTERNAL_ERROR (fname);
1322 shdr_info[cnt].newsymidx[inner] = destidx++;
1325 && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
1327 last_was_local = false;
1328 shdr_info[cnt].shdr.sh_info = destidx - 1;
1334 /* Get the full section index, if necessary from the
1336 if (sym->st_shndx != SHN_XINDEX)
1337 sec = shdr_info[sym->st_shndx].idx;
1340 elf_assert (shndxdata != NULL
1341 && shndxdata->d_buf != NULL);
1343 sec = shdr_info[xshndx].idx;
1348 GElf_Section nshndx;
1351 if (sec < SHN_LORESERVE)
1358 nshndx = SHN_XINDEX;
1362 elf_assert (sec < SHN_LORESERVE || shndxdata != NULL);
1364 if ((inner != destidx || nshndx != sym->st_shndx
1365 || (shndxdata != NULL && nxshndx != xshndx))
1366 && (sym->st_shndx = nshndx,
1367 gelf_update_symshndx (shdr_info[cnt].data,
1371 INTERNAL_ERROR (fname);
1373 shdr_info[cnt].newsymidx[inner] = destidx++;
1376 && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
1378 last_was_local = false;
1379 shdr_info[cnt].shdr.sh_info = destidx - 1;
1382 else if (debug_fname != NULL
1383 && shdr_info[cnt].debug_data == NULL)
1384 /* The symbol points to a section that is discarded
1385 but isn't preserved in the debug file. Check that
1386 this is a section or group signature symbol
1387 for a section which has been removed. */
1389 size_t sidx = (sym->st_shndx != SHN_XINDEX
1390 ? sym->st_shndx : xshndx);
1391 elf_assert (GELF_ST_TYPE (sym->st_info) == STT_SECTION
1392 || ((shdr_info[sidx].shdr.sh_type
1394 && (shdr_info[sidx].shdr.sh_info
1399 if (destidx != inner)
1401 /* The size of the symbol table changed. */
1402 shdr_info[cnt].shdr.sh_size = newdata->d_size
1404 any_symtab_changes = true;
1408 /* The symbol table didn't really change. */
1409 free (shdr_info[cnt].newsymidx);
1410 shdr_info[cnt].newsymidx = NULL;
1415 /* If we have to, compute the offset of the section. */
1416 if (shdr_info[cnt].shdr.sh_offset == 0)
1417 shdr_info[cnt].shdr.sh_offset
1418 = ((lastoffset + shdr_info[cnt].shdr.sh_addralign - 1)
1419 & ~((GElf_Off) (shdr_info[cnt].shdr.sh_addralign - 1)));
1421 /* Set the section header in the new file. */
1422 if (unlikely (gelf_update_shdr (scn, &shdr_info[cnt].shdr) == 0))
1423 /* There cannot be any overflows. */
1424 INTERNAL_ERROR (fname);
1426 /* Remember the last section written so far. */
1427 GElf_Off filesz = (shdr_info[cnt].shdr.sh_type != SHT_NOBITS
1428 ? shdr_info[cnt].shdr.sh_size : 0);
1429 if (lastoffset < shdr_info[cnt].shdr.sh_offset + filesz)
1430 lastoffset = shdr_info[cnt].shdr.sh_offset + filesz;
1433 /* Adjust symbol references if symbol tables changed. */
1434 if (any_symtab_changes)
1435 /* Find all relocation sections which use this symbol table. */
1436 for (cnt = 1; cnt <= shdridx; ++cnt)
1438 /* Update section headers when the data size has changed.
1439 We also update the SHT_NOBITS section in the debug
1440 file so that the section headers match in sh_size. */
1441 inline void update_section_size (const Elf_Data *newdata)
1444 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1445 shdr->sh_size = newdata->d_size;
1446 (void) gelf_update_shdr (scn, shdr);
1447 if (debugelf != NULL)
1449 /* libelf will use d_size to set sh_size. */
1450 Elf_Data *debugdata = elf_getdata (elf_getscn (debugelf,
1452 if (debugdata == NULL)
1453 INTERNAL_ERROR (fname);
1454 debugdata->d_size = newdata->d_size;
1458 if (shdr_info[cnt].idx == 0 && debug_fname == NULL)
1459 /* Ignore sections which are discarded. When we are saving a
1460 relocation section in a separate debug file, we must fix up
1461 the symbol table references. */
1464 const Elf32_Word symtabidx = shdr_info[cnt].old_sh_link;
1465 elf_assert (symtabidx < shnum + 2);
1466 const Elf32_Word *const newsymidx = shdr_info[symtabidx].newsymidx;
1467 switch (shdr_info[cnt].shdr.sh_type)
1469 inline bool no_symtab_updates (void)
1471 /* If the symbol table hasn't changed, do not do anything. */
1472 if (shdr_info[symtabidx].newsymidx == NULL)
1475 /* If the symbol table is not discarded, but additionally
1476 duplicated in the separate debug file and this section
1477 is discarded, don't adjust anything. */
1478 return (shdr_info[cnt].idx == 0
1479 && shdr_info[symtabidx].debug_data != NULL);
1484 if (no_symtab_updates ())
1487 Elf_Data *d = elf_getdata (shdr_info[cnt].idx == 0
1488 ? elf_getscn (debugelf, cnt)
1489 : elf_getscn (newelf,
1490 shdr_info[cnt].idx),
1492 elf_assert (d != NULL && d->d_buf != NULL
1493 && shdr_info[cnt].shdr.sh_entsize != 0);
1494 size_t nrels = (shdr_info[cnt].shdr.sh_size
1495 / shdr_info[cnt].shdr.sh_entsize);
1497 size_t symsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1498 const Elf32_Word symidxn = (shdr_info[symtabidx].data->d_size
1500 if (shdr_info[cnt].shdr.sh_type == SHT_REL)
1501 for (size_t relidx = 0; relidx < nrels; ++relidx)
1504 if (gelf_getrel (d, relidx, &rel_mem) == NULL)
1505 INTERNAL_ERROR (fname);
1507 size_t symidx = GELF_R_SYM (rel_mem.r_info);
1508 elf_assert (symidx < symidxn);
1509 if (newsymidx[symidx] != symidx)
1512 = GELF_R_INFO (newsymidx[symidx],
1513 GELF_R_TYPE (rel_mem.r_info));
1515 if (gelf_update_rel (d, relidx, &rel_mem) == 0)
1516 INTERNAL_ERROR (fname);
1520 for (size_t relidx = 0; relidx < nrels; ++relidx)
1523 if (gelf_getrela (d, relidx, &rel_mem) == NULL)
1524 INTERNAL_ERROR (fname);
1526 size_t symidx = GELF_R_SYM (rel_mem.r_info);
1527 elf_assert (symidx < symidxn);
1528 if (newsymidx[symidx] != symidx)
1531 = GELF_R_INFO (newsymidx[symidx],
1532 GELF_R_TYPE (rel_mem.r_info));
1534 if (gelf_update_rela (d, relidx, &rel_mem) == 0)
1535 INTERNAL_ERROR (fname);
1541 if (no_symtab_updates ())
1544 /* We have to recompute the hash table. */
1546 elf_assert (shdr_info[cnt].idx > 0);
1548 /* The hash section in the new file. */
1549 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1551 /* The symbol table data. */
1552 Elf_Data *symd = elf_getdata (elf_getscn (newelf,
1553 shdr_info[symtabidx].idx),
1555 elf_assert (symd != NULL && symd->d_buf != NULL);
1557 /* The hash table data. */
1558 Elf_Data *hashd = elf_getdata (scn, NULL);
1559 elf_assert (hashd != NULL && hashd->d_buf != NULL);
1561 if (shdr_info[cnt].shdr.sh_entsize == sizeof (Elf32_Word))
1563 /* Sane arches first. */
1564 elf_assert (hashd->d_size >= 2 * sizeof (Elf32_Word));
1565 Elf32_Word *bucket = (Elf32_Word *) hashd->d_buf;
1567 size_t strshndx = shdr_info[symtabidx].old_sh_link;
1568 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1570 Elf32_Word nchain = bucket[1];
1571 Elf32_Word nbucket = bucket[0];
1572 uint64_t used_buf = ((2ULL + nchain + nbucket)
1573 * sizeof (Elf32_Word));
1574 elf_assert (used_buf <= hashd->d_size);
1576 /* Adjust the nchain value. The symbol table size
1577 changed. We keep the same size for the bucket array. */
1578 bucket[1] = symd->d_size / elsize;
1580 Elf32_Word *chain = bucket + nbucket;
1582 /* New size of the section. */
1583 size_t n_size = ((2 + symd->d_size / elsize + nbucket)
1584 * sizeof (Elf32_Word));
1585 elf_assert (n_size <= hashd->d_size);
1586 hashd->d_size = n_size;
1587 update_section_size (hashd);
1589 /* Clear the arrays. */
1590 memset (bucket, '\0',
1591 (symd->d_size / elsize + nbucket)
1592 * sizeof (Elf32_Word));
1594 for (size_t inner = shdr_info[symtabidx].shdr.sh_info;
1595 inner < symd->d_size / elsize; ++inner)
1598 GElf_Sym *sym = gelf_getsym (symd, inner, &sym_mem);
1599 elf_assert (sym != NULL);
1601 const char *name = elf_strptr (elf, strshndx,
1603 elf_assert (name != NULL && nbucket != 0);
1604 size_t hidx = elf_hash (name) % nbucket;
1606 if (bucket[hidx] == 0)
1607 bucket[hidx] = inner;
1610 hidx = bucket[hidx];
1612 while (chain[hidx] != 0 && chain[hidx] < nchain)
1615 chain[hidx] = inner;
1621 /* Alpha and S390 64-bit use 64-bit SHT_HASH entries. */
1622 elf_assert (shdr_info[cnt].shdr.sh_entsize
1623 == sizeof (Elf64_Xword));
1625 Elf64_Xword *bucket = (Elf64_Xword *) hashd->d_buf;
1627 size_t strshndx = shdr_info[symtabidx].old_sh_link;
1628 size_t elsize = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1630 elf_assert (symd->d_size >= 2 * sizeof (Elf64_Xword));
1631 Elf64_Xword nbucket = bucket[0];
1632 Elf64_Xword nchain = bucket[1];
1633 uint64_t maxwords = hashd->d_size / sizeof (Elf64_Xword);
1634 elf_assert (maxwords >= 2
1635 && maxwords - 2 >= nbucket
1636 && maxwords - 2 - nbucket >= nchain);
1638 /* Adjust the nchain value. The symbol table size
1639 changed. We keep the same size for the bucket array. */
1640 bucket[1] = symd->d_size / elsize;
1642 Elf64_Xword *chain = bucket + nbucket;
1644 /* New size of the section. */
1645 size_t n_size = ((2 + symd->d_size / elsize + nbucket)
1646 * sizeof (Elf64_Xword));
1647 elf_assert (n_size <= hashd->d_size);
1648 hashd->d_size = n_size;
1649 update_section_size (hashd);
1651 /* Clear the arrays. */
1652 memset (bucket, '\0',
1653 (symd->d_size / elsize + nbucket)
1654 * sizeof (Elf64_Xword));
1656 for (size_t inner = shdr_info[symtabidx].shdr.sh_info;
1657 inner < symd->d_size / elsize; ++inner)
1660 GElf_Sym *sym = gelf_getsym (symd, inner, &sym_mem);
1661 elf_assert (sym != NULL);
1663 const char *name = elf_strptr (elf, strshndx,
1665 elf_assert (name != NULL && nbucket != 0);
1666 size_t hidx = elf_hash (name) % nbucket;
1668 if (bucket[hidx] == 0)
1669 bucket[hidx] = inner;
1672 hidx = bucket[hidx];
1674 while (chain[hidx] != 0 && chain[hidx] < nchain)
1677 chain[hidx] = inner;
1683 case SHT_GNU_versym:
1684 /* If the symbol table changed we have to adjust the entries. */
1685 if (no_symtab_updates ())
1688 elf_assert (shdr_info[cnt].idx > 0);
1690 /* The symbol version section in the new file. */
1691 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1693 /* The symbol table data. */
1694 symd = elf_getdata (elf_getscn (newelf, shdr_info[symtabidx].idx),
1696 elf_assert (symd != NULL && symd->d_buf != NULL);
1697 size_t symz = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1698 const Elf32_Word syms = (shdr_info[symtabidx].data->d_size / symz);
1700 /* The version symbol data. */
1701 Elf_Data *verd = elf_getdata (scn, NULL);
1702 elf_assert (verd != NULL && verd->d_buf != NULL);
1704 /* The symbol version array. */
1705 GElf_Half *verstab = (GElf_Half *) verd->d_buf;
1707 /* Walk through the list and */
1708 size_t elsize = gelf_fsize (elf, verd->d_type, 1, EV_CURRENT);
1709 Elf32_Word vers = verd->d_size / elsize;
1710 for (size_t inner = 1; inner < vers && inner < syms; ++inner)
1711 if (newsymidx[inner] != 0 && newsymidx[inner] < vers)
1712 /* Overwriting the same array works since the
1713 reordering can only move entries to lower indices
1715 verstab[newsymidx[inner]] = verstab[inner];
1717 /* New size of the section. */
1718 verd->d_size = gelf_fsize (newelf, verd->d_type,
1720 / gelf_fsize (elf, symd->d_type, 1,
1723 update_section_size (verd);
1727 if (no_symtab_updates ())
1730 /* Yes, the symbol table changed.
1731 Update the section header of the section group. */
1732 scn = elf_getscn (newelf, shdr_info[cnt].idx);
1734 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1735 elf_assert (shdr != NULL);
1737 size_t symsz = gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT);
1738 const Elf32_Word symn = (shdr_info[symtabidx].data->d_size
1740 elf_assert (shdr->sh_info < symn);
1741 shdr->sh_info = newsymidx[shdr->sh_info];
1743 (void) gelf_update_shdr (scn, shdr);
1748 /* Remove any relocations between debug sections in ET_REL
1749 for the debug file when requested. These relocations are always
1750 zero based between the unallocated sections. */
1751 if (debug_fname != NULL && reloc_debug && ehdr->e_type == ET_REL)
1755 while ((scn = elf_nextscn (debugelf, scn)) != NULL)
1758 /* We need the actual section and header from the debugelf
1759 not just the cached original in shdr_info because we
1760 might want to change the size. */
1762 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
1763 if (shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
1765 /* Make sure that this relocation section points to a
1766 section to relocate with contents, that isn't
1767 allocated and that is a debug section. */
1768 Elf_Scn *tscn = elf_getscn (debugelf, shdr->sh_info);
1769 GElf_Shdr tshdr_mem;
1770 GElf_Shdr *tshdr = gelf_getshdr (tscn, &tshdr_mem);
1771 if (tshdr->sh_type == SHT_NOBITS
1772 || tshdr->sh_size == 0
1773 || (tshdr->sh_flags & SHF_ALLOC) != 0)
1776 const char *tname = elf_strptr (debugelf, shstrndx,
1778 if (! tname || ! ebl_debugscn_p (ebl, tname))
1781 /* OK, lets relocate all trivial cross debug section
1783 Elf_Data *reldata = elf_getdata (scn, NULL);
1784 if (reldata == NULL || reldata->d_buf == NULL)
1785 INTERNAL_ERROR (fname);
1786 /* We actually wanted the rawdata, but since we already
1787 accessed it earlier as elf_getdata () that won't
1788 work. But debug sections are all ELF_T_BYTE, so it
1789 doesn't really matter. */
1790 Elf_Data *tdata = elf_getdata (tscn, NULL);
1791 if (tdata == NULL || tdata->d_buf == NULL
1792 || tdata->d_type != ELF_T_BYTE)
1793 INTERNAL_ERROR (fname);
1795 /* Pick up the symbol table and shndx table to
1796 resolve relocation symbol indexes. */
1797 Elf64_Word symt = shdr->sh_link;
1798 Elf_Data *symdata, *xndxdata;
1799 elf_assert (symt < shnum + 2);
1800 elf_assert (shdr_info[symt].symtab_idx < shnum + 2);
1801 symdata = (shdr_info[symt].debug_data
1802 ?: shdr_info[symt].data);
1803 xndxdata = (shdr_info[shdr_info[symt].symtab_idx].debug_data
1804 ?: shdr_info[shdr_info[symt].symtab_idx].data);
1806 /* Apply one relocation. Returns true when trivial
1807 relocation actually done. */
1808 bool relocate (GElf_Addr offset, const GElf_Sxword addend,
1809 bool is_rela, int rtype, int symndx)
1811 /* R_*_NONE relocs can always just be removed. */
1815 /* We only do simple absolute relocations. */
1816 Elf_Type type = ebl_reloc_simple_type (ebl, rtype);
1817 if (type == ELF_T_NUM)
1820 /* These are the types we can relocate. */
1821 #define TYPES DO_TYPE (BYTE, Byte); DO_TYPE (HALF, Half); \
1822 DO_TYPE (WORD, Word); DO_TYPE (SWORD, Sword); \
1823 DO_TYPE (XWORD, Xword); DO_TYPE (SXWORD, Sxword)
1825 /* And only for relocations against other debug sections. */
1828 GElf_Sym *sym = gelf_getsymshndx (symdata, xndxdata,
1831 Elf32_Word sec = (sym->st_shndx == SHN_XINDEX
1832 ? xndx : sym->st_shndx);
1833 if (sec >= shnum + 2)
1834 INTERNAL_ERROR (fname);
1836 if (ebl_debugscn_p (ebl, shdr_info[sec].name))
1840 #define DO_TYPE(NAME, Name) GElf_##Name Name;
1841 union { TYPES; } tmpbuf;
1846 #define DO_TYPE(NAME, Name) \
1847 case ELF_T_##NAME: \
1848 size = sizeof (GElf_##Name); \
1857 if (offset > tdata->d_size
1858 || tdata->d_size - offset < size)
1861 error (EXIT_FAILURE, 0, gettext ("bad relocation"));
1864 /* When the symbol value is zero then for SHT_REL
1865 sections this is all that needs to be checked.
1866 The addend is contained in the original data at
1867 the offset already. So if the (section) symbol
1868 address is zero and the given addend is zero
1869 just remove the relocation, it isn't needed
1871 if (addend == 0 && sym->st_value == 0)
1879 .d_version = EV_CURRENT,
1884 .d_buf = tdata->d_buf + offset,
1886 .d_version = EV_CURRENT,
1889 GElf_Addr value = sym->st_value;
1892 /* For SHT_RELA sections we just take the
1893 given addend and add it to the value. */
1898 /* For SHT_REL sections we have to peek at
1899 what is already in the section at the given
1900 offset to get the addend. */
1901 Elf_Data *d = gelf_xlatetom (debugelf, &tmpdata,
1903 ehdr->e_ident[EI_DATA]);
1905 INTERNAL_ERROR (fname);
1906 assert (d == &tmpdata);
1911 #define DO_TYPE(NAME, Name) \
1912 case ELF_T_##NAME: \
1913 tmpbuf.Name += (GElf_##Name) value; \
1921 /* Now finally put in the new value. */
1922 Elf_Data *s = gelf_xlatetof (debugelf, &rdata,
1924 ehdr->e_ident[EI_DATA]);
1926 INTERNAL_ERROR (fname);
1927 assert (s == &rdata);
1934 if (shdr->sh_entsize == 0)
1935 INTERNAL_ERROR (fname);
1937 size_t nrels = shdr->sh_size / shdr->sh_entsize;
1939 if (shdr->sh_type == SHT_REL)
1940 for (size_t relidx = 0; relidx < nrels; ++relidx)
1943 GElf_Rel *r = gelf_getrel (reldata, relidx, &rel_mem);
1944 if (! relocate (r->r_offset, 0, false,
1945 GELF_R_TYPE (r->r_info),
1946 GELF_R_SYM (r->r_info)))
1949 gelf_update_rel (reldata, next, r);
1954 for (size_t relidx = 0; relidx < nrels; ++relidx)
1957 GElf_Rela *r = gelf_getrela (reldata, relidx, &rela_mem);
1958 if (! relocate (r->r_offset, r->r_addend, true,
1959 GELF_R_TYPE (r->r_info),
1960 GELF_R_SYM (r->r_info)))
1963 gelf_update_rela (reldata, next, r);
1969 shdr->sh_size = reldata->d_size = nrels * shdr->sh_entsize;
1970 gelf_update_shdr (scn, shdr);
1975 /* Now that we have done all adjustments to the data,
1976 we can actually write out the debug file. */
1977 if (debug_fname != NULL)
1979 /* Finally write the file. */
1980 if (unlikely (elf_update (debugelf, ELF_C_WRITE) == -1))
1982 error (0, 0, gettext ("while writing '%s': %s"),
1983 tmp_debug_fname, elf_errmsg (-1));
1988 /* Create the real output file. First rename, then change the
1990 if (rename (tmp_debug_fname, debug_fname) != 0
1991 || fchmod (debug_fd, mode) != 0)
1993 error (0, errno, gettext ("while creating '%s'"), debug_fname);
1998 /* The temporary file does not exist anymore. */
1999 free (tmp_debug_fname);
2000 tmp_debug_fname = NULL;
2005 Elf_Data debug_crc_data =
2007 .d_type = ELF_T_WORD,
2008 .d_buf = &debug_crc,
2009 .d_size = sizeof (debug_crc),
2010 .d_version = EV_CURRENT
2013 /* Compute the checksum which we will add to the executable. */
2014 if (crc32_file (debug_fd, &debug_crc) != 0)
2016 error (0, errno, gettext ("\
2017 while computing checksum for debug information"));
2018 unlink (debug_fname);
2023 /* Store it in the debuglink section data. */
2024 if (unlikely (gelf_xlatetof (newelf, &debuglink_crc_data,
2025 &debug_crc_data, ehdr->e_ident[EI_DATA])
2026 != &debuglink_crc_data))
2027 INTERNAL_ERROR (fname);
2031 /* Finally finish the ELF header. Fill in the fields not handled by
2032 libelf from the old file. */
2033 newehdr = gelf_getehdr (newelf, &newehdr_mem);
2034 if (newehdr == NULL)
2035 INTERNAL_ERROR (fname);
2037 memcpy (newehdr->e_ident, ehdr->e_ident, EI_NIDENT);
2038 newehdr->e_type = ehdr->e_type;
2039 newehdr->e_machine = ehdr->e_machine;
2040 newehdr->e_version = ehdr->e_version;
2041 newehdr->e_entry = ehdr->e_entry;
2042 newehdr->e_flags = ehdr->e_flags;
2043 newehdr->e_phoff = ehdr->e_phoff;
2045 /* We need to position the section header table. */
2046 const size_t offsize = gelf_fsize (elf, ELF_T_OFF, 1, EV_CURRENT);
2047 newehdr->e_shoff = ((shdr_info[shdridx].shdr.sh_offset
2048 + shdr_info[shdridx].shdr.sh_size + offsize - 1)
2049 & ~((GElf_Off) (offsize - 1)));
2050 newehdr->e_shentsize = gelf_fsize (elf, ELF_T_SHDR, 1, EV_CURRENT);
2052 /* The new section header string table index. */
2053 if (likely (idx < SHN_HIRESERVE) && likely (idx != SHN_XINDEX))
2054 newehdr->e_shstrndx = idx;
2057 /* The index does not fit in the ELF header field. */
2058 shdr_info[0].scn = elf_getscn (elf, 0);
2060 if (gelf_getshdr (shdr_info[0].scn, &shdr_info[0].shdr) == NULL)
2061 INTERNAL_ERROR (fname);
2063 shdr_info[0].shdr.sh_link = idx;
2064 (void) gelf_update_shdr (shdr_info[0].scn, &shdr_info[0].shdr);
2066 newehdr->e_shstrndx = SHN_XINDEX;
2069 if (gelf_update_ehdr (newelf, newehdr) == 0)
2071 error (0, 0, gettext ("%s: error while creating ELF header: %s"),
2072 output_fname ?: fname, elf_errmsg (-1));
2077 /* We have everything from the old file. */
2078 if (elf_cntl (elf, ELF_C_FDDONE) != 0)
2080 error (0, 0, gettext ("%s: error while reading the file: %s"),
2081 fname, elf_errmsg (-1));
2086 /* The ELF library better follows our layout when this is not a
2087 relocatable object file. */
2088 elf_flagelf (newelf, ELF_C_SET,
2089 (ehdr->e_type != ET_REL ? ELF_F_LAYOUT : 0)
2090 | (permissive ? ELF_F_PERMISSIVE : 0));
2092 /* Finally write the file. */
2093 if (elf_update (newelf, ELF_C_WRITE) == -1)
2095 error (0, 0, gettext ("while writing '%s': %s"),
2096 output_fname ?: fname, elf_errmsg (-1));
2102 /* libelf can't cope without the section headers being properly intact.
2103 So we just let it write them normally, and then we nuke them later. */
2105 if (newehdr->e_ident[EI_CLASS] == ELFCLASS32)
2107 assert (offsetof (Elf32_Ehdr, e_shentsize) + sizeof (Elf32_Half)
2108 == offsetof (Elf32_Ehdr, e_shnum));
2109 assert (offsetof (Elf32_Ehdr, e_shnum) + sizeof (Elf32_Half)
2110 == offsetof (Elf32_Ehdr, e_shstrndx));
2111 const Elf32_Off zero_off = 0;
2112 const Elf32_Half zero[3] = { 0, 0, SHN_UNDEF };
2113 if (pwrite_retry (fd, &zero_off, sizeof zero_off,
2114 offsetof (Elf32_Ehdr, e_shoff)) != sizeof zero_off
2115 || (pwrite_retry (fd, zero, sizeof zero,
2116 offsetof (Elf32_Ehdr, e_shentsize))
2118 || ftruncate (fd, shdr_info[shdridx].shdr.sh_offset) < 0)
2120 error (0, errno, gettext ("while writing '%s'"),
2121 output_fname ?: fname);
2127 assert (offsetof (Elf64_Ehdr, e_shentsize) + sizeof (Elf64_Half)
2128 == offsetof (Elf64_Ehdr, e_shnum));
2129 assert (offsetof (Elf64_Ehdr, e_shnum) + sizeof (Elf64_Half)
2130 == offsetof (Elf64_Ehdr, e_shstrndx));
2131 const Elf64_Off zero_off = 0;
2132 const Elf64_Half zero[3] = { 0, 0, SHN_UNDEF };
2133 if (pwrite_retry (fd, &zero_off, sizeof zero_off,
2134 offsetof (Elf64_Ehdr, e_shoff)) != sizeof zero_off
2135 || (pwrite_retry (fd, zero, sizeof zero,
2136 offsetof (Elf64_Ehdr, e_shentsize))
2138 || ftruncate (fd, shdr_info[shdridx].shdr.sh_offset) < 0)
2140 error (0, errno, gettext ("while writing '%s'"),
2141 output_fname ?: fname);
2148 if (shdr_info != NULL)
2150 /* For some sections we might have created an table to map symbol
2152 if (any_symtab_changes)
2153 for (cnt = 1; cnt <= shdridx; ++cnt)
2155 free (shdr_info[cnt].newsymidx);
2156 if (shdr_info[cnt].debug_data != NULL)
2157 free (shdr_info[cnt].debug_data->d_buf);
2160 /* Free data we allocated for the .gnu_debuglink section. */
2161 free (debuglink_buf);
2163 /* Free the memory. */
2164 if ((shnum + 2) * sizeof (struct shdr_info) > MAX_STACK_ALLOC)
2168 /* Free other resources. */
2169 if (shstrtab_data != NULL)
2170 free (shstrtab_data->d_buf);
2172 ebl_strtabfree (shst);
2174 /* That was it. Close the descriptors. */
2175 if (elf_end (newelf) != 0)
2177 error (0, 0, gettext ("error while finishing '%s': %s"),
2178 output_fname ?: fname, elf_errmsg (-1));
2182 if (debugelf != NULL && elf_end (debugelf) != 0)
2184 error (0, 0, gettext ("error while finishing '%s': %s"), debug_fname,
2190 /* Close the EBL backend. */
2192 ebl_closebackend (ebl);
2196 /* If requested, preserve the timestamp. */
2199 if (futimens (fd, tvp) != 0)
2201 error (0, errno, gettext ("\
2202 cannot set access and modification date of '%s'"),
2203 output_fname ?: fname);
2208 /* Close the file descriptor if we created a new file. */
2209 if (output_fname != NULL)
2216 cleanup_debug (void)
2220 if (tmp_debug_fname != NULL)
2222 unlink (tmp_debug_fname);
2223 free (tmp_debug_fname);
2224 tmp_debug_fname = NULL;
2232 handle_ar (int fd, Elf *elf, const char *prefix, const char *fname,
2233 struct timespec tvp[2])
2235 size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
2236 size_t fname_len = strlen (fname) + 1;
2237 char new_prefix[prefix_len + 1 + fname_len];
2238 char *cp = new_prefix;
2240 /* Create the full name of the file. */
2243 cp = mempcpy (cp, prefix, prefix_len);
2246 memcpy (cp, fname, fname_len);
2249 /* Process all the files contained in the archive. */
2251 Elf_Cmd cmd = ELF_C_RDWR;
2253 while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
2255 /* The the header for this element. */
2256 Elf_Arhdr *arhdr = elf_getarhdr (subelf);
2258 if (elf_kind (subelf) == ELF_K_ELF)
2259 result |= handle_elf (fd, subelf, new_prefix, arhdr->ar_name, 0, NULL);
2260 else if (elf_kind (subelf) == ELF_K_AR)
2261 result |= handle_ar (fd, subelf, new_prefix, arhdr->ar_name, NULL);
2263 /* Get next archive element. */
2264 cmd = elf_next (subelf);
2265 if (unlikely (elf_end (subelf) != 0))
2266 INTERNAL_ERROR (fname);
2271 if (unlikely (futimens (fd, tvp) != 0))
2273 error (0, errno, gettext ("\
2274 cannot set access and modification date of '%s'"), fname);
2279 if (unlikely (close (fd) != 0))
2280 error (EXIT_FAILURE, errno, gettext ("while closing '%s'"), fname);
2286 #include "debugpred.h"