diff --git a/llvm/test/tools/llvm-objcopy/strip-non-alloc.test b/llvm/test/tools/llvm-objcopy/strip-non-alloc.test new file mode 100644 index 0000000000000..270670cffd3c3 --- /dev/null +++ b/llvm/test/tools/llvm-objcopy/strip-non-alloc.test @@ -0,0 +1,26 @@ +# RUN: yaml2obj %s > %t +# RUN: llvm-objcopy --strip-non-alloc %t %t2 +# RUN: llvm-readobj -file-headers -sections %t2 | FileCheck %s + +!ELF +FileHeader: + Class: ELFCLASS64 + Data: ELFDATA2LSB + Type: ET_REL + Machine: EM_X86_64 +Sections: + - Name: .bss + Type: SHT_NOBITS + Flags: [ SHF_ALLOC ] + - Name: .text + Type: SHT_PROGBITS + Flags: [ SHF_ALLOC, SHF_EXECINSTR ] + - Name: .blarg + Type: SHT_PROGBITS + Flags: [ ] + +# CHECK: SectionHeaderCount: 4 + +# CHECK: Name: .bss +# CHECK: Name: .text +# CHECK: Name: .shstrtab diff --git a/llvm/tools/llvm-objcopy/llvm-objcopy.cpp b/llvm/tools/llvm-objcopy/llvm-objcopy.cpp index f7a94f5f891e2..812d27b403ffd 100644 --- a/llvm/tools/llvm-objcopy/llvm-objcopy.cpp +++ b/llvm/tools/llvm-objcopy/llvm-objcopy.cpp @@ -87,6 +87,8 @@ static cl::opt StripDebug("strip-debug", cl::desc("Removes all debug information")); static cl::opt StripSections("strip-sections", cl::desc("Remove all section headers")); +static cl::opt StripNonAlloc("strip-non-alloc", + cl::desc("Remove all non-allocated sections")); static cl::opt StripDWO("strip-dwo", cl::desc("remove all DWARF .dwo sections from file")); static cl::opt ExtractDWO( @@ -206,6 +208,15 @@ void CopyBinary(const ELFObjectFile &ObjFile) { }; } + if (StripNonAlloc) + RemovePred = [RemovePred, &Obj](const SectionBase &Sec) { + if (RemovePred(Sec)) + return true; + if (&Sec == Obj->getSectionHeaderStrTab()) + return false; + return (Sec.Flags & SHF_ALLOC) == 0; + }; + Obj->removeSections(RemovePred); Obj->finalize(); WriteObjectFile(*Obj, OutputFilename.getValue());