Path: blob/main/contrib/llvm-project/llvm/tools/llvm-pdbutil/ExplainOutputStyle.cpp
35260 views
//===- ExplainOutputStyle.cpp --------------------------------- *- C++ --*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "ExplainOutputStyle.h"910#include "StreamUtil.h"11#include "llvm-pdbutil.h"1213#include "llvm/DebugInfo/CodeView/Formatters.h"14#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"15#include "llvm/DebugInfo/MSF/MappedBlockStream.h"16#include "llvm/DebugInfo/PDB/Native/DbiStream.h"17#include "llvm/DebugInfo/PDB/Native/FormatUtil.h"18#include "llvm/DebugInfo/PDB/Native/InfoStream.h"19#include "llvm/DebugInfo/PDB/Native/InputFile.h"20#include "llvm/DebugInfo/PDB/Native/NativeSession.h"21#include "llvm/DebugInfo/PDB/Native/PDBFile.h"22#include "llvm/DebugInfo/PDB/Native/RawTypes.h"23#include "llvm/Object/COFF.h"24#include "llvm/Support/BinaryByteStream.h"25#include "llvm/Support/BinaryStreamArray.h"26#include "llvm/Support/Error.h"2728using namespace llvm;29using namespace llvm::codeview;30using namespace llvm::msf;31using namespace llvm::pdb;3233ExplainOutputStyle::ExplainOutputStyle(InputFile &File, uint64_t FileOffset)34: File(File), FileOffset(FileOffset), P(2, false, outs(), opts::Filters) {}3536Error ExplainOutputStyle::dump() {37P.formatLine("Explaining file offset {0} of file '{1}'.", FileOffset,38File.getFilePath());3940if (File.isPdb())41return explainPdbFile();4243return explainBinaryFile();44}4546Error ExplainOutputStyle::explainPdbFile() {47bool IsAllocated = explainPdbBlockStatus();48if (!IsAllocated)49return Error::success();5051AutoIndent Indent(P);52if (isPdbSuperBlock())53explainPdbSuperBlockOffset();54else if (isPdbFpmBlock())55explainPdbFpmBlockOffset();56else if (isPdbBlockMapBlock())57explainPdbBlockMapOffset();58else if (isPdbStreamDirectoryBlock())59explainPdbStreamDirectoryOffset();60else if (auto Index = getPdbBlockStreamIndex())61explainPdbStreamOffset(*Index);62else63explainPdbUnknownBlock();64return Error::success();65}6667Error ExplainOutputStyle::explainBinaryFile() {68std::unique_ptr<BinaryByteStream> Stream = std::make_unique<BinaryByteStream>(69File.unknown().getBuffer(), llvm::endianness::little);70switch (opts::explain::InputType) {71case opts::explain::InputFileType::DBIStream: {72DbiStream Dbi(std::move(Stream));73if (auto EC = Dbi.reload(nullptr))74return EC;75explainStreamOffset(Dbi, FileOffset);76break;77}78case opts::explain::InputFileType::PDBStream: {79InfoStream Info(std::move(Stream));80if (auto EC = Info.reload())81return EC;82explainStreamOffset(Info, FileOffset);83break;84}85default:86llvm_unreachable("Invalid input file type!");87}88return Error::success();89}9091uint32_t ExplainOutputStyle::pdbBlockIndex() const {92return FileOffset / File.pdb().getBlockSize();93}9495uint32_t ExplainOutputStyle::pdbBlockOffset() const {96uint64_t BlockStart = pdbBlockIndex() * File.pdb().getBlockSize();97assert(FileOffset >= BlockStart);98return FileOffset - BlockStart;99}100101bool ExplainOutputStyle::isPdbSuperBlock() const {102return pdbBlockIndex() == 0;103}104105bool ExplainOutputStyle::isPdbFpm1() const {106return ((pdbBlockIndex() - 1) % File.pdb().getBlockSize() == 0);107}108bool ExplainOutputStyle::isPdbFpm2() const {109return ((pdbBlockIndex() - 2) % File.pdb().getBlockSize() == 0);110}111112bool ExplainOutputStyle::isPdbFpmBlock() const {113return isPdbFpm1() || isPdbFpm2();114}115116bool ExplainOutputStyle::isPdbBlockMapBlock() const {117return pdbBlockIndex() == File.pdb().getBlockMapIndex();118}119120bool ExplainOutputStyle::isPdbStreamDirectoryBlock() const {121const auto &Layout = File.pdb().getMsfLayout();122return llvm::is_contained(Layout.DirectoryBlocks, pdbBlockIndex());123}124125std::optional<uint32_t> ExplainOutputStyle::getPdbBlockStreamIndex() const {126const auto &Layout = File.pdb().getMsfLayout();127for (const auto &Entry : enumerate(Layout.StreamMap)) {128if (!llvm::is_contained(Entry.value(), pdbBlockIndex()))129continue;130return Entry.index();131}132return std::nullopt;133}134135bool ExplainOutputStyle::explainPdbBlockStatus() {136if (FileOffset >= File.pdb().getFileSize()) {137P.formatLine("Address {0} is not in the file (file size = {1}).",138FileOffset, File.pdb().getFileSize());139return false;140}141P.formatLine("Block:Offset = {2:X-}:{1:X-4}.", FileOffset, pdbBlockOffset(),142pdbBlockIndex());143144bool IsFree = File.pdb().getMsfLayout().FreePageMap[pdbBlockIndex()];145P.formatLine("Address is in block {0} ({1}allocated).", pdbBlockIndex(),146IsFree ? "un" : "");147return !IsFree;148}149150#define endof(Class, Field) (offsetof(Class, Field) + sizeof(Class::Field))151152void ExplainOutputStyle::explainPdbSuperBlockOffset() {153P.formatLine("This corresponds to offset {0} of the MSF super block, ",154pdbBlockOffset());155if (pdbBlockOffset() < endof(SuperBlock, MagicBytes))156P.printLine("which is part of the MSF file magic.");157else if (pdbBlockOffset() < endof(SuperBlock, BlockSize)) {158P.printLine("which contains the block size of the file.");159P.formatLine("The current value is {0}.",160uint32_t(File.pdb().getMsfLayout().SB->BlockSize));161} else if (pdbBlockOffset() < endof(SuperBlock, FreeBlockMapBlock)) {162P.printLine("which contains the index of the FPM block (e.g. 1 or 2).");163P.formatLine("The current value is {0}.",164uint32_t(File.pdb().getMsfLayout().SB->FreeBlockMapBlock));165} else if (pdbBlockOffset() < endof(SuperBlock, NumBlocks)) {166P.printLine("which contains the number of blocks in the file.");167P.formatLine("The current value is {0}.",168uint32_t(File.pdb().getMsfLayout().SB->NumBlocks));169} else if (pdbBlockOffset() < endof(SuperBlock, NumDirectoryBytes)) {170P.printLine("which contains the number of bytes in the stream directory.");171P.formatLine("The current value is {0}.",172uint32_t(File.pdb().getMsfLayout().SB->NumDirectoryBytes));173} else if (pdbBlockOffset() < endof(SuperBlock, Unknown1)) {174P.printLine("whose purpose is unknown.");175P.formatLine("The current value is {0}.",176uint32_t(File.pdb().getMsfLayout().SB->Unknown1));177} else if (pdbBlockOffset() < endof(SuperBlock, BlockMapAddr)) {178P.printLine("which contains the file offset of the block map.");179P.formatLine("The current value is {0}.",180uint32_t(File.pdb().getMsfLayout().SB->BlockMapAddr));181} else {182assert(pdbBlockOffset() > sizeof(SuperBlock));183P.printLine(184"which is outside the range of valid data for the super block.");185}186}187188static std::string toBinaryString(uint8_t Byte) {189char Result[9] = {0};190for (int I = 0; I < 8; ++I) {191char C = (Byte & 1) ? '1' : '0';192Result[I] = C;193Byte >>= 1;194}195return std::string(Result);196}197198void ExplainOutputStyle::explainPdbFpmBlockOffset() {199const MSFLayout &Layout = File.pdb().getMsfLayout();200uint32_t MainFpm = Layout.mainFpmBlock();201uint32_t AltFpm = Layout.alternateFpmBlock();202203assert(isPdbFpmBlock());204uint32_t Fpm = isPdbFpm1() ? 1 : 2;205uint32_t FpmChunk = pdbBlockIndex() / File.pdb().getBlockSize();206assert((Fpm == MainFpm) || (Fpm == AltFpm));207(void)AltFpm;208bool IsMain = (Fpm == MainFpm);209P.formatLine("Address is in FPM{0} ({1} FPM)", Fpm, IsMain ? "Main" : "Alt");210uint32_t DescribedBlockStart =2118 * (FpmChunk * File.pdb().getBlockSize() + pdbBlockOffset());212if (DescribedBlockStart > File.pdb().getBlockCount()) {213P.printLine("Address is in extraneous FPM space.");214return;215}216217P.formatLine("Address describes the allocation status of blocks [{0},{1})",218DescribedBlockStart, DescribedBlockStart + 8);219ArrayRef<uint8_t> Bytes;220cantFail(File.pdb().getMsfBuffer().readBytes(FileOffset, 1, Bytes));221P.formatLine("Status = {0} (Note: 0 = allocated, 1 = free)",222toBinaryString(Bytes[0]));223}224225void ExplainOutputStyle::explainPdbBlockMapOffset() {226uint64_t BlockMapOffset = File.pdb().getBlockMapOffset();227uint32_t OffsetInBlock = FileOffset - BlockMapOffset;228P.formatLine("Address is at offset {0} of the directory block list",229OffsetInBlock);230}231232static uint32_t getOffsetInStream(ArrayRef<support::ulittle32_t> StreamBlocks,233uint64_t FileOffset, uint32_t BlockSize) {234uint32_t BlockIndex = FileOffset / BlockSize;235uint32_t OffsetInBlock = FileOffset - BlockIndex * BlockSize;236237auto Iter = llvm::find(StreamBlocks, BlockIndex);238assert(Iter != StreamBlocks.end());239uint32_t StreamBlockIndex = std::distance(StreamBlocks.begin(), Iter);240return StreamBlockIndex * BlockSize + OffsetInBlock;241}242243void ExplainOutputStyle::explainPdbStreamOffset(uint32_t Stream) {244SmallVector<StreamInfo, 12> Streams;245discoverStreamPurposes(File.pdb(), Streams);246247assert(Stream <= Streams.size());248const StreamInfo &S = Streams[Stream];249const auto &Layout = File.pdb().getStreamLayout(Stream);250uint32_t StreamOff =251getOffsetInStream(Layout.Blocks, FileOffset, File.pdb().getBlockSize());252P.formatLine("Address is at offset {0}/{1} of Stream {2} ({3}){4}.",253StreamOff, Layout.Length, Stream, S.getLongName(),254(StreamOff > Layout.Length) ? " in unused space" : "");255switch (S.getPurpose()) {256case StreamPurpose::DBI: {257DbiStream &Dbi = cantFail(File.pdb().getPDBDbiStream());258explainStreamOffset(Dbi, StreamOff);259break;260}261case StreamPurpose::PDB: {262InfoStream &Info = cantFail(File.pdb().getPDBInfoStream());263explainStreamOffset(Info, StreamOff);264break;265}266case StreamPurpose::IPI:267case StreamPurpose::TPI:268case StreamPurpose::ModuleStream:269case StreamPurpose::NamedStream:270default:271break;272}273}274275void ExplainOutputStyle::explainPdbStreamDirectoryOffset() {276auto DirectoryBlocks = File.pdb().getDirectoryBlockArray();277const auto &Layout = File.pdb().getMsfLayout();278uint32_t StreamOff =279getOffsetInStream(DirectoryBlocks, FileOffset, File.pdb().getBlockSize());280P.formatLine("Address is at offset {0}/{1} of Stream Directory{2}.",281StreamOff, uint32_t(Layout.SB->NumDirectoryBytes),282uint32_t(StreamOff > Layout.SB->NumDirectoryBytes)283? " in unused space"284: "");285}286287void ExplainOutputStyle::explainPdbUnknownBlock() {288P.formatLine("Address has unknown purpose.");289}290291template <typename T>292static void printStructField(LinePrinter &P, StringRef Label, T Value) {293P.formatLine("which contains {0}.", Label);294P.formatLine("The current value is {0}.", Value);295}296297static void explainDbiHeaderOffset(LinePrinter &P, DbiStream &Dbi,298uint32_t Offset) {299const DbiStreamHeader *Header = Dbi.getHeader();300assert(Header != nullptr);301302if (Offset < endof(DbiStreamHeader, VersionSignature))303printStructField(P, "the DBI Stream Version Signature",304int32_t(Header->VersionSignature));305else if (Offset < endof(DbiStreamHeader, VersionHeader))306printStructField(P, "the DBI Stream Version Header",307uint32_t(Header->VersionHeader));308else if (Offset < endof(DbiStreamHeader, Age))309printStructField(P, "the age of the DBI Stream", uint32_t(Header->Age));310else if (Offset < endof(DbiStreamHeader, GlobalSymbolStreamIndex))311printStructField(P, "the index of the Global Symbol Stream",312uint16_t(Header->GlobalSymbolStreamIndex));313else if (Offset < endof(DbiStreamHeader, BuildNumber))314printStructField(P, "the build number", uint16_t(Header->BuildNumber));315else if (Offset < endof(DbiStreamHeader, PublicSymbolStreamIndex))316printStructField(P, "the index of the Public Symbol Stream",317uint16_t(Header->PublicSymbolStreamIndex));318else if (Offset < endof(DbiStreamHeader, PdbDllVersion))319printStructField(P, "the version of mspdb.dll",320uint16_t(Header->PdbDllVersion));321else if (Offset < endof(DbiStreamHeader, SymRecordStreamIndex))322printStructField(P, "the index of the Symbol Record Stream",323uint16_t(Header->SymRecordStreamIndex));324else if (Offset < endof(DbiStreamHeader, PdbDllRbld))325printStructField(P, "the rbld of mspdb.dll", uint16_t(Header->PdbDllRbld));326else if (Offset < endof(DbiStreamHeader, ModiSubstreamSize))327printStructField(P, "the size of the Module Info Substream",328int32_t(Header->ModiSubstreamSize));329else if (Offset < endof(DbiStreamHeader, SecContrSubstreamSize))330printStructField(P, "the size of the Section Contribution Substream",331int32_t(Header->SecContrSubstreamSize));332else if (Offset < endof(DbiStreamHeader, SectionMapSize))333printStructField(P, "the size of the Section Map Substream",334int32_t(Header->SectionMapSize));335else if (Offset < endof(DbiStreamHeader, FileInfoSize))336printStructField(P, "the size of the File Info Substream",337int32_t(Header->FileInfoSize));338else if (Offset < endof(DbiStreamHeader, TypeServerSize))339printStructField(P, "the size of the Type Server Map",340int32_t(Header->TypeServerSize));341else if (Offset < endof(DbiStreamHeader, MFCTypeServerIndex))342printStructField(P, "the index of the MFC Type Server stream",343uint32_t(Header->MFCTypeServerIndex));344else if (Offset < endof(DbiStreamHeader, OptionalDbgHdrSize))345printStructField(P, "the size of the Optional Debug Stream array",346int32_t(Header->OptionalDbgHdrSize));347else if (Offset < endof(DbiStreamHeader, ECSubstreamSize))348printStructField(P, "the size of the Edit & Continue Substream",349int32_t(Header->ECSubstreamSize));350else if (Offset < endof(DbiStreamHeader, Flags))351printStructField(P, "the DBI Stream flags", uint16_t(Header->Flags));352else if (Offset < endof(DbiStreamHeader, MachineType))353printStructField(P, "the machine type", uint16_t(Header->MachineType));354else if (Offset < endof(DbiStreamHeader, Reserved))355printStructField(P, "reserved data", uint32_t(Header->Reserved));356}357358static void explainDbiModiSubstreamOffset(LinePrinter &P, DbiStream &Dbi,359uint32_t Offset) {360VarStreamArray<DbiModuleDescriptor> ModuleDescriptors;361BinaryStreamRef ModiSubstreamData = Dbi.getModiSubstreamData().StreamData;362BinaryStreamReader Reader(ModiSubstreamData);363364cantFail(Reader.readArray(ModuleDescriptors, ModiSubstreamData.getLength()));365auto Prev = ModuleDescriptors.begin();366assert(Prev.offset() == 0);367auto Current = Prev;368uint32_t Index = 0;369while (true) {370Prev = Current;371++Current;372if (Current == ModuleDescriptors.end() || Offset < Current.offset())373break;374++Index;375}376377const DbiModuleDescriptor &Descriptor = *Prev;378P.formatLine("which contains the descriptor for module {0} ({1}).", Index,379Descriptor.getModuleName());380}381382template <typename T>383static void dontExplain(LinePrinter &Printer, T &Stream, uint32_t Offset) {}384385template <typename T, typename SubstreamRangeT>386static void explainSubstreamOffset(LinePrinter &P, uint32_t OffsetInStream,387T &Stream,388const SubstreamRangeT &Substreams) {389uint32_t SubOffset = OffsetInStream;390for (const auto &Entry : Substreams) {391if (Entry.Size <= 0)392continue;393uint32_t S = static_cast<uint32_t>(Entry.Size);394if (SubOffset < S) {395P.formatLine("address is at offset {0}/{1} of the {2}.", SubOffset, S,396Entry.Label);397Entry.Explain(P, Stream, SubOffset);398return;399}400SubOffset -= S;401}402}403404void ExplainOutputStyle::explainStreamOffset(DbiStream &Dbi,405uint32_t OffsetInStream) {406P.printLine("Within the DBI stream:");407AutoIndent Indent(P);408const DbiStreamHeader *Header = Dbi.getHeader();409assert(Header != nullptr);410411struct SubstreamInfo {412int32_t Size;413StringRef Label;414void (*Explain)(LinePrinter &, DbiStream &, uint32_t);415} Substreams[] = {416{sizeof(DbiStreamHeader), "DBI Stream Header", explainDbiHeaderOffset},417{int32_t(Header->ModiSubstreamSize), "Module Info Substream",418explainDbiModiSubstreamOffset},419{int32_t(Header->SecContrSubstreamSize), "Section Contribution Substream",420dontExplain<DbiStream>},421{int32_t(Header->SectionMapSize), "Section Map", dontExplain<DbiStream>},422{int32_t(Header->FileInfoSize), "File Info Substream",423dontExplain<DbiStream>},424{int32_t(Header->TypeServerSize), "Type Server Map Substream",425dontExplain<DbiStream>},426{int32_t(Header->ECSubstreamSize), "Edit & Continue Substream",427dontExplain<DbiStream>},428{int32_t(Header->OptionalDbgHdrSize), "Optional Debug Stream Array",429dontExplain<DbiStream>},430};431432explainSubstreamOffset(P, OffsetInStream, Dbi, Substreams);433}434435static void explainPdbStreamHeaderOffset(LinePrinter &P, InfoStream &Info,436uint32_t Offset) {437const InfoStreamHeader *Header = Info.getHeader();438assert(Header != nullptr);439440if (Offset < endof(InfoStreamHeader, Version))441printStructField(P, "the PDB Stream Version Signature",442uint32_t(Header->Version));443else if (Offset < endof(InfoStreamHeader, Signature))444printStructField(P, "the signature of the PDB Stream",445uint32_t(Header->Signature));446else if (Offset < endof(InfoStreamHeader, Age))447printStructField(P, "the age of the PDB", uint32_t(Header->Age));448else if (Offset < endof(InfoStreamHeader, Guid))449printStructField(P, "the guid of the PDB", fmt_guid(Header->Guid.Guid));450}451452void ExplainOutputStyle::explainStreamOffset(InfoStream &Info,453uint32_t OffsetInStream) {454P.printLine("Within the PDB stream:");455AutoIndent Indent(P);456457struct SubstreamInfo {458uint32_t Size;459StringRef Label;460void (*Explain)(LinePrinter &, InfoStream &, uint32_t);461} Substreams[] = {{sizeof(InfoStreamHeader), "PDB Stream Header",462explainPdbStreamHeaderOffset},463{Info.getNamedStreamMapByteSize(), "Named Stream Map",464dontExplain<InfoStream>},465{Info.getStreamSize(), "PDB Feature Signatures",466dontExplain<InfoStream>}};467468explainSubstreamOffset(P, OffsetInStream, Info, Substreams);469}470471472