diff --git a/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp b/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp index 8967a2eb1749e..49674b4c32de0 100644 --- a/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp +++ b/llvm/lib/DebugInfo/PDB/Native/NativeSession.cpp @@ -87,6 +87,19 @@ Error NativeSession::createFromPdb(std::unique_ptr Buffer, return Error::success(); } +static Error validatePdbMagic(StringRef PdbPath) { + file_magic Magic; + if (auto EC = identify_magic(PdbPath, Magic)) + return make_error(EC); + + if (Magic != file_magic::pdb) + return make_error( + raw_error_code::invalid_format, + "The input file did not contain the pdb file magic."); + + return Error::success(); +} + static Expected> loadPdbFile(StringRef PdbPath, std::unique_ptr &Allocator) { ErrorOr> ErrorOrBuffer = @@ -97,10 +110,8 @@ loadPdbFile(StringRef PdbPath, std::unique_ptr &Allocator) { std::unique_ptr Buffer = std::move(*ErrorOrBuffer); PdbPath = Buffer->getBufferIdentifier(); - file_magic Magic; - auto EC = identify_magic(PdbPath, Magic); - if (EC || Magic != file_magic::pdb) - return make_error(EC); + if (auto EC = validatePdbMagic(PdbPath)) + return std::move(EC); auto Stream = std::make_unique( std::move(Buffer), llvm::endianness::little); @@ -152,10 +163,8 @@ Error NativeSession::createFromExe(StringRef ExePath, if (!PdbPath) return PdbPath.takeError(); - file_magic Magic; - auto EC = identify_magic(PdbPath.get(), Magic); - if (EC || Magic != file_magic::pdb) - return make_error(EC); + if (auto EC = validatePdbMagic(PdbPath.get())) + return EC; auto Allocator = std::make_unique(); auto File = loadPdbFile(PdbPath.get(), Allocator); diff --git a/llvm/unittests/DebugInfo/PDB/NativeSessionTest.cpp b/llvm/unittests/DebugInfo/PDB/NativeSessionTest.cpp index cffaf7c9543fb..20ae253513f05 100644 --- a/llvm/unittests/DebugInfo/PDB/NativeSessionTest.cpp +++ b/llvm/unittests/DebugInfo/PDB/NativeSessionTest.cpp @@ -40,6 +40,18 @@ TEST(NativeSessionTest, TestCreateFromExe) { ASSERT_THAT_ERROR(std::move(E), Succeeded()); } +TEST(NativeSessionTest, TestInvalidPdbMagicError) { + SmallString<128> InputsDir = unittest::getInputFileDirectory(TestMainArgv0); + llvm::sys::path::append(InputsDir, "SimpleTest.cpp"); + std::string CppPath{InputsDir}; + std::unique_ptr S; + + Error E = NativeSession::createFromPdbPath(CppPath, S); + const char *FormatErr = "The record is in an unexpected format. " + "The input file did not contain the pdb file magic."; + ASSERT_THAT_ERROR(std::move(E), FailedWithMessage(FormatErr)); +} + TEST(NativeSessionTest, TestSetLoadAddress) { std::unique_ptr S; Error E = pdb::loadDataForEXE(PDB_ReaderType::Native, getExePath(), S);