Index: llvm/lib/BinaryFormat/Magic.cpp =================================================================== --- llvm/lib/BinaryFormat/Magic.cpp +++ llvm/lib/BinaryFormat/Magic.cpp @@ -14,6 +14,7 @@ #include "llvm/BinaryFormat/MachO.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileSystem.h" +#include "llvm/Support/MemoryBuffer.h" #if !defined(_MSC_VER) && !defined(__MINGW32__) #include @@ -214,6 +215,22 @@ if (close(FD) != 0 || Length < 0) return std::error_code(errno, std::generic_category()); - Result = identify_magic(StringRef(Buffer, Length)); + std::unique_ptr FileBuffer; + StringRef BufferStr(Buffer, Length); + // If this might be a PE file, we need to read the whole file, because + // verification requires seeking to a certain offset, which is only determined + // by examining a field in the file. Since we don't know what that offset + // will be we have to assume it could be anywhere, and thus we need to read + // the entire file. + if (BufferStr.startswith("MZ")) { + auto FileOrError = MemoryBuffer::getFile(Path); + if (!FileOrError) + return FileOrError.getError(); + FileBuffer = std::move(*FileOrError); + BufferStr = FileBuffer->getBuffer(); + } + + Result = identify_magic(BufferStr); + return std::error_code(); }