Index: contrib/elftoolchain/elfcopy/sections.c =================================================================== --- contrib/elftoolchain/elfcopy/sections.c +++ contrib/elftoolchain/elfcopy/sections.c @@ -340,7 +340,9 @@ GElf_Shdr ish; size_t indx; uint64_t oldndx, newndx; - int elferr, sec_flags, reorder; + int elferr, sec_flags, shstrtab_exist, reorder; + + shstrtab_exist = 0; /* * Insert a pseudo section that contains the ELF header @@ -438,12 +440,15 @@ oldndx = newndx = SHN_UNDEF; if (strcmp(name, ".symtab") != 0 && strcmp(name, ".strtab") != 0) { + /* Add sections before .shstrtab OR before last section + * if .shstrtab hasn't been added yet */ if (!strcmp(name, ".shstrtab")) { /* * Add sections specified by --add-section and * gnu debuglink. we want these sections have * smaller index than .shstrtab section. */ + shstrtab_exist = 1; if (ecp->debuglink != NULL) add_gnu_debuglink(ecp); if (ecp->flags & SEC_ADD) @@ -505,6 +510,13 @@ insert_to_sec_list(ecp, s, 0); } + + if (!shstrtab_exist) { + if (ecp->debuglink != NULL) + add_gnu_debuglink(ecp); + if (ecp->flags & SEC_ADD) + insert_sections(ecp); + } elferr = elf_errno(); if (elferr != 0) errx(EXIT_FAILURE, "elf_nextscn failed: %s", @@ -1444,10 +1456,13 @@ init_shstrtab(struct elfcopy *ecp) { Elf_Scn *shstrtab; + Elf *e; GElf_Shdr shdr; struct section *s; size_t indx, sizehint; + e = ecp->ein; + if (elf_getshdrstrndx(ecp->ein, &indx) == 0) { shstrtab = elf_getscn(ecp->ein, indx); if (shstrtab == NULL)