Index: test/tools/llvm-objcopy/ELF/invalid-p_filesz.test =================================================================== --- /dev/null +++ test/tools/llvm-objcopy/ELF/invalid-p_filesz.test @@ -0,0 +1,22 @@ +## In this case, we have a program header with a file size that +## overflows the binary size. Check llvm-objcopy doesn't crash +## and report this error properly. + +# RUN: yaml2obj %s -o %t.o +# RUN: not llvm-objcopy %t.o 2>&1 | FIleCheck %s +# CHECK: error: program header at offset 440 of size 1048576 is mailformed. + +--- !ELF +FileHeader: + Class: ELFCLASS64 + Data: ELFDATA2LSB + Type: ET_EXEC + Machine: EM_X86_64 +Sections: + - Name: .foo + Type: SHT_PROGBITS +ProgramHeaders: + - Type: PT_LOAD + FileSize: 0x100000 + Sections: + - Section: .foo Index: tools/llvm-objcopy/ELF/Object.cpp =================================================================== --- tools/llvm-objcopy/ELF/Object.cpp +++ tools/llvm-objcopy/ELF/Object.cpp @@ -1104,6 +1104,10 @@ template void ELFBuilder::readProgramHeaders() { uint32_t Index = 0; for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) { + if (Phdr.p_offset + Phdr.p_filesz > ElfFile.getBufSize()) + error("program header at offset " + Twine(Phdr.p_offset) + " of size " + + Twine(Phdr.p_filesz) + " is mailformed"); + ArrayRef Data{ElfFile.base() + Phdr.p_offset, (size_t)Phdr.p_filesz}; Segment &Seg = Obj.addSegment(Data);