diff --git a/llvm/lib/BinaryFormat/Magic.cpp b/llvm/lib/BinaryFormat/Magic.cpp index e9b8df93b902..db8e9526e647 100644 --- a/llvm/lib/BinaryFormat/Magic.cpp +++ b/llvm/lib/BinaryFormat/Magic.cpp @@ -185,7 +185,7 @@ file_magic llvm::identify_magic(StringRef Magic) { if (startswith(Magic, "MZ") && Magic.size() >= 0x3c + 4) { uint32_t off = read32le(Magic.data() + 0x3c); // PE/COFF file, either EXE or DLL. - if (off < Magic.size() && + if (off + sizeof(COFF::PEMagic) <= Magic.size() && memcmp(Magic.data() + off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0) return file_magic::pecoff_executable; } diff --git a/llvm/test/Object/Inputs/invalid-coff-header-too-small b/llvm/test/Object/Inputs/invalid-coff-header-too-small new file mode 100644 index 000000000000..c9f0c965b766 Binary files /dev/null and b/llvm/test/Object/Inputs/invalid-coff-header-too-small differ diff --git a/llvm/test/Object/invalid.test b/llvm/test/Object/invalid.test index b0b5528ab05b..6899f5ab0572 100644 --- a/llvm/test/Object/invalid.test +++ b/llvm/test/Object/invalid.test @@ -86,3 +86,6 @@ INVALID-REL-SYM: invalid section offset RUN: not llvm-readobj -r %p/Inputs/invalid-buffer.elf 2>&1 | FileCheck --check-prefix=INVALID-BUFFER %s INVALID-BUFFER: Invalid buffer + +RUN: not llvm-readobj %p/Inputs/invalid-coff-header-too-small 2>&1 | FileCheck --check-prefix=COFF-HEADER %s +COFF-HEADER: The file was not recognized as a valid object file