LCOV - code coverage report
Current view: top level - lib/DebugInfo/PDB/Native - DbiStreamBuilder.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 209 242 86.4 %
Date: 2017-09-14 15:23:50 Functions: 32 33 97.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- DbiStreamBuilder.cpp - PDB Dbi Stream Creation -----------*- C++ -*-===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : 
      10             : #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
      11             : 
      12             : #include "llvm/ADT/ArrayRef.h"
      13             : #include "llvm/BinaryFormat/COFF.h"
      14             : #include "llvm/DebugInfo/MSF/MSFBuilder.h"
      15             : #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
      16             : #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
      17             : #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
      18             : #include "llvm/DebugInfo/PDB/Native/RawError.h"
      19             : #include "llvm/Object/COFF.h"
      20             : #include "llvm/Support/BinaryStreamWriter.h"
      21             : 
      22             : using namespace llvm;
      23             : using namespace llvm::codeview;
      24             : using namespace llvm::msf;
      25             : using namespace llvm::pdb;
      26             : 
      27          57 : DbiStreamBuilder::DbiStreamBuilder(msf::MSFBuilder &Msf)
      28          57 :     : Msf(Msf), Allocator(Msf.getAllocator()), Age(1), BuildNumber(0),
      29             :       PdbDllVersion(0), PdbDllRbld(0), Flags(0), MachineType(PDB_Machine::x86),
      30         684 :       Header(nullptr), DbgStreams((int)DbgHeaderType::Max) {}
      31             : 
      32         399 : DbiStreamBuilder::~DbiStreamBuilder() {}
      33             : 
      34         114 : void DbiStreamBuilder::setVersionHeader(PdbRaw_DbiVer V) { VerHeader = V; }
      35             : 
      36          57 : void DbiStreamBuilder::setAge(uint32_t A) { Age = A; }
      37             : 
      38          17 : void DbiStreamBuilder::setBuildNumber(uint16_t B) { BuildNumber = B; }
      39             : 
      40          17 : void DbiStreamBuilder::setPdbDllVersion(uint16_t V) { PdbDllVersion = V; }
      41             : 
      42          17 : void DbiStreamBuilder::setPdbDllRbld(uint16_t R) { PdbDllRbld = R; }
      43             : 
      44          17 : void DbiStreamBuilder::setFlags(uint16_t F) { Flags = F; }
      45             : 
      46          17 : void DbiStreamBuilder::setMachineType(PDB_Machine M) { MachineType = M; }
      47             : 
      48          40 : void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) {
      49          40 :   SectionMap = SecMap;
      50          40 : }
      51             : 
      52          40 : void DbiStreamBuilder::setGlobalsStreamIndex(uint32_t Index) {
      53          40 :   GlobalsStreamIndex = Index;
      54          40 : }
      55             : 
      56          40 : void DbiStreamBuilder::setSymbolRecordStreamIndex(uint32_t Index) {
      57          40 :   SymRecordStreamIndex = Index;
      58          40 : }
      59             : 
      60          40 : void DbiStreamBuilder::setPublicsStreamIndex(uint32_t Index) {
      61          40 :   PublicsStreamIndex = Index;
      62          40 : }
      63             : 
      64          80 : Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type,
      65             :                                      ArrayRef<uint8_t> Data) {
      66         160 :   if (DbgStreams[(int)Type].StreamNumber != kInvalidStreamIndex)
      67             :     return make_error<RawError>(raw_error_code::duplicate_entry,
      68           0 :                                 "The specified stream type already exists");
      69          80 :   auto ExpectedIndex = Msf.addStream(Data.size());
      70          80 :   if (!ExpectedIndex)
      71             :     return ExpectedIndex.takeError();
      72          80 :   uint32_t Index = std::move(*ExpectedIndex);
      73         160 :   DbgStreams[(int)Type].Data = Data;
      74         160 :   DbgStreams[(int)Type].StreamNumber = Index;
      75         240 :   return Error::success();
      76             : }
      77             : 
      78          40 : uint32_t DbiStreamBuilder::addECName(StringRef Name) {
      79          40 :   return ECNamesBuilder.insert(Name);
      80             : }
      81             : 
      82          57 : uint32_t DbiStreamBuilder::calculateSerializedLength() const {
      83             :   // For now we only support serializing the header.
      84         114 :   return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
      85         171 :          calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
      86         171 :          calculateSectionMapStreamSize() + calculateDbgStreamsSize() +
      87         114 :          ECNamesBuilder.calculateSerializedSize();
      88             : }
      89             : 
      90             : Expected<DbiModuleDescriptorBuilder &>
      91         108 : DbiStreamBuilder::addModuleInfo(StringRef ModuleName) {
      92         216 :   uint32_t Index = ModiList.size();
      93         216 :   ModiList.push_back(
      94         216 :       llvm::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf));
      95         432 :   return *ModiList.back();
      96             : }
      97             : 
      98          39 : Error DbiStreamBuilder::addModuleSourceFile(DbiModuleDescriptorBuilder &Module,
      99             :                                             StringRef File) {
     100          39 :   uint32_t Index = SourceFileNames.size();
     101         117 :   SourceFileNames.insert(std::make_pair(File, Index));
     102          39 :   Module.addSourceFile(File);
     103         117 :   return Error::success();
     104             : }
     105             : 
     106           0 : Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) {
     107           0 :   auto NameIter = SourceFileNames.find(File);
     108           0 :   if (NameIter == SourceFileNames.end())
     109           0 :     return make_error<RawError>(raw_error_code::no_entry,
     110           0 :                                 "The specified source file was not found");
     111           0 :   return NameIter->getValue();
     112             : }
     113             : 
     114         114 : uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
     115         114 :   uint32_t Size = 0;
     116         672 :   for (const auto &M : ModiList)
     117         216 :     Size += M->calculateSerializedLength();
     118         114 :   return Size;
     119             : }
     120             : 
     121         114 : uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
     122         228 :   if (SectionContribs.empty())
     123             :     return 0;
     124          80 :   return sizeof(enum PdbRaw_DbiSecContribVer) +
     125         160 :          sizeof(SectionContribs[0]) * SectionContribs.size();
     126             : }
     127             : 
     128         114 : uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
     129         114 :   if (SectionMap.empty())
     130             :     return 0;
     131          80 :   return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
     132             : }
     133             : 
     134         171 : uint32_t DbiStreamBuilder::calculateNamesOffset() const {
     135         171 :   uint32_t Offset = 0;
     136         171 :   Offset += sizeof(ulittle16_t);                         // NumModules
     137         171 :   Offset += sizeof(ulittle16_t);                         // NumSourceFiles
     138         342 :   Offset += ModiList.size() * sizeof(ulittle16_t);       // ModIndices
     139         171 :   Offset += ModiList.size() * sizeof(ulittle16_t);       // ModFileCounts
     140         171 :   uint32_t NumFileInfos = 0;
     141        1008 :   for (const auto &M : ModiList)
     142         648 :     NumFileInfos += M->source_files().size();
     143         171 :   Offset += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
     144         171 :   return Offset;
     145             : }
     146             : 
     147         114 : uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
     148         114 :   uint32_t Size = calculateNamesOffset();
     149         114 :   Size += calculateNamesBufferSize();
     150         228 :   return alignTo(Size, sizeof(uint32_t));
     151             : }
     152             : 
     153         114 : uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
     154         114 :   uint32_t Size = 0;
     155         604 :   for (const auto &F : SourceFileNames) {
     156         148 :     Size += F.getKeyLength() + 1; // Names[I];
     157             :   }
     158         114 :   return Size;
     159             : }
     160             : 
     161          57 : uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
     162         114 :   return DbgStreams.size() * sizeof(uint16_t);
     163             : }
     164             : 
     165          57 : Error DbiStreamBuilder::generateFileInfoSubstream() {
     166          57 :   uint32_t Size = calculateFileInfoSubstreamSize();
     167         114 :   auto Data = Allocator.Allocate<uint8_t>(Size);
     168          57 :   uint32_t NamesOffset = calculateNamesOffset();
     169             : 
     170         285 :   FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size),
     171          57 :                                            llvm::support::little);
     172             : 
     173             :   WritableBinaryStreamRef MetadataBuffer =
     174         228 :       WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
     175         171 :   BinaryStreamWriter MetadataWriter(MetadataBuffer);
     176             : 
     177         171 :   uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModiList.size());
     178         114 :   uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
     179         171 :   if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
     180           0 :     return EC;
     181         171 :   if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
     182           0 :     return EC;
     183         165 :   for (uint16_t I = 0; I < ModiCount; ++I) {
     184         324 :     if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
     185           0 :       return EC;
     186             :   }
     187         336 :   for (const auto &MI : ModiList) {
     188         216 :     FileCount = static_cast<uint16_t>(MI->source_files().size());
     189         324 :     if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
     190           0 :       return EC;
     191             :   }
     192             : 
     193             :   // Before writing the FileNameOffsets array, write the NamesBuffer array.
     194             :   // A side effect of this is that this will actually compute the various
     195             :   // file name offsets, so we can then go back and write the FileNameOffsets
     196             :   // array to the other substream.
     197         228 :   NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset);
     198         171 :   BinaryStreamWriter NameBufferWriter(NamesBuffer);
     199         302 :   for (auto &Name : SourceFileNames) {
     200          37 :     Name.second = NameBufferWriter.getOffset();
     201         111 :     if (auto EC = NameBufferWriter.writeCString(Name.getKey()))
     202           0 :       return EC;
     203             :   }
     204             : 
     205         336 :   for (const auto &MI : ModiList) {
     206         402 :     for (StringRef Name : MI->source_files()) {
     207          39 :       auto Result = SourceFileNames.find(Name);
     208          78 :       if (Result == SourceFileNames.end())
     209             :         return make_error<RawError>(raw_error_code::no_entry,
     210           0 :                                     "The source file was not found.");
     211         117 :       if (auto EC = MetadataWriter.writeInteger(Result->second))
     212           0 :         return EC;
     213             :     }
     214             :   }
     215             : 
     216         171 :   if (auto EC = NameBufferWriter.padToAlignment(sizeof(uint32_t)))
     217           0 :     return EC;
     218             : 
     219          57 :   if (NameBufferWriter.bytesRemaining() > 0)
     220             :     return make_error<RawError>(raw_error_code::invalid_format,
     221           0 :                                 "The names buffer contained unexpected data.");
     222             : 
     223          57 :   if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
     224             :     return make_error<RawError>(
     225             :         raw_error_code::invalid_format,
     226           0 :         "The metadata buffer contained unexpected data.");
     227             : 
     228         171 :   return Error::success();
     229             : }
     230             : 
     231          57 : Error DbiStreamBuilder::finalize() {
     232          57 :   if (Header)
     233           0 :     return Error::success();
     234             : 
     235         336 :   for (auto &MI : ModiList)
     236         108 :     MI->finalize();
     237             : 
     238         171 :   if (auto EC = generateFileInfoSubstream())
     239           0 :     return EC;
     240             : 
     241         114 :   DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
     242          57 :   ::memset(H, 0, sizeof(DbiStreamHeader));
     243         171 :   H->VersionHeader = *VerHeader;
     244         114 :   H->VersionSignature = -1;
     245         114 :   H->Age = Age;
     246         114 :   H->BuildNumber = BuildNumber;
     247         114 :   H->Flags = Flags;
     248         114 :   H->PdbDllRbld = PdbDllRbld;
     249         114 :   H->PdbDllVersion = PdbDllVersion;
     250         114 :   H->MachineType = static_cast<uint16_t>(MachineType);
     251             : 
     252         114 :   H->ECSubstreamSize = ECNamesBuilder.calculateSerializedSize();
     253         171 :   H->FileInfoSize = FileInfoBuffer.getLength();
     254         114 :   H->ModiSubstreamSize = calculateModiSubstreamSize();
     255         171 :   H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
     256         114 :   H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
     257         114 :   H->SectionMapSize = calculateSectionMapStreamSize();
     258         114 :   H->TypeServerSize = 0;
     259         114 :   H->SymRecordStreamIndex = SymRecordStreamIndex;
     260         114 :   H->PublicSymbolStreamIndex = PublicsStreamIndex;
     261         114 :   H->MFCTypeServerIndex = kInvalidStreamIndex;
     262         114 :   H->GlobalSymbolStreamIndex = GlobalsStreamIndex;
     263             : 
     264          57 :   Header = H;
     265         171 :   return Error::success();
     266             : }
     267             : 
     268          57 : Error DbiStreamBuilder::finalizeMsfLayout() {
     269         336 :   for (auto &MI : ModiList) {
     270         324 :     if (auto EC = MI->finalizeMsfLayout())
     271           0 :       return EC;
     272             :   }
     273             : 
     274          57 :   uint32_t Length = calculateSerializedLength();
     275         171 :   if (auto EC = Msf.setStreamSize(StreamDBI, Length))
     276           0 :     return EC;
     277         171 :   return Error::success();
     278             : }
     279             : 
     280         138 : static uint16_t toSecMapFlags(uint32_t Flags) {
     281         138 :   uint16_t Ret = 0;
     282         138 :   if (Flags & COFF::IMAGE_SCN_MEM_READ)
     283         138 :     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
     284         138 :   if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
     285          11 :     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
     286         138 :   if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
     287          42 :     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
     288         138 :   if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
     289          42 :     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
     290         138 :   if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
     291         138 :     Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
     292             : 
     293             :   // This seems always 1.
     294         138 :   Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
     295             : 
     296         138 :   return Ret;
     297             : }
     298             : 
     299             : // A utility function to create a Section Map for a given list of COFF sections.
     300             : //
     301             : // A Section Map seem to be a copy of a COFF section list in other format.
     302             : // I don't know why a PDB file contains both a COFF section header and
     303             : // a Section Map, but it seems it must be present in a PDB.
     304          40 : std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
     305             :     ArrayRef<llvm::object::coff_section> SecHdrs) {
     306          40 :   std::vector<SecMapEntry> Ret;
     307          40 :   int Idx = 0;
     308             : 
     309         178 :   auto Add = [&]() -> SecMapEntry & {
     310         178 :     Ret.emplace_back();
     311         178 :     auto &Entry = Ret.back();
     312         178 :     memset(&Entry, 0, sizeof(Entry));
     313             : 
     314         356 :     Entry.Frame = Idx + 1;
     315             : 
     316             :     // We don't know the meaning of these fields yet.
     317         356 :     Entry.SecName = UINT16_MAX;
     318         356 :     Entry.ClassName = UINT16_MAX;
     319             : 
     320         178 :     return Entry;
     321          40 :   };
     322             : 
     323         218 :   for (auto &Hdr : SecHdrs) {
     324         138 :     auto &Entry = Add();
     325         414 :     Entry.Flags = toSecMapFlags(Hdr.Characteristics);
     326         138 :     Entry.SecByteLength = Hdr.VirtualSize;
     327         138 :     ++Idx;
     328             :   }
     329             : 
     330             :   // The last entry is for absolute symbols.
     331          40 :   auto &Entry = Add();
     332          80 :   Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
     333             :                 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
     334          80 :   Entry.SecByteLength = UINT32_MAX;
     335             : 
     336          40 :   return Ret;
     337             : }
     338             : 
     339          57 : Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
     340             :                                WritableBinaryStreamRef MsfBuffer) {
     341         171 :   if (auto EC = finalize())
     342           0 :     return EC;
     343             : 
     344             :   auto DbiS = WritableMappedBlockStream::createIndexedStream(
     345         171 :       Layout, MsfBuffer, StreamDBI, Allocator);
     346             : 
     347         114 :   BinaryStreamWriter Writer(*DbiS);
     348         228 :   if (auto EC = Writer.writeObject(*Header))
     349           0 :     return EC;
     350             : 
     351         336 :   for (auto &M : ModiList) {
     352         540 :     if (auto EC = M->commit(Writer, Layout, MsfBuffer))
     353           0 :       return EC;
     354             :   }
     355             : 
     356         114 :   if (!SectionContribs.empty()) {
     357         120 :     if (auto EC = Writer.writeEnum(DbiSecContribVer60))
     358           0 :       return EC;
     359         160 :     if (auto EC = Writer.writeArray(makeArrayRef(SectionContribs)))
     360           0 :       return EC;
     361             :   }
     362             : 
     363          57 :   if (!SectionMap.empty()) {
     364          80 :     ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
     365          40 :     SecMapHeader SMHeader = {Size, Size};
     366         120 :     if (auto EC = Writer.writeObject(SMHeader))
     367           0 :       return EC;
     368         120 :     if (auto EC = Writer.writeArray(SectionMap))
     369           0 :       return EC;
     370             :   }
     371             : 
     372         228 :   if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
     373           0 :     return EC;
     374             : 
     375         171 :   if (auto EC = ECNamesBuilder.commit(Writer))
     376           0 :     return EC;
     377             : 
     378         798 :   for (auto &Stream : DbgStreams)
     379        1881 :     if (auto EC = Writer.writeInteger(Stream.StreamNumber))
     380           0 :       return EC;
     381             : 
     382         798 :   for (auto &Stream : DbgStreams) {
     383         627 :     if (Stream.StreamNumber == kInvalidStreamIndex)
     384         547 :       continue;
     385             :     auto WritableStream = WritableMappedBlockStream::createIndexedStream(
     386         320 :         Layout, MsfBuffer, Stream.StreamNumber, Allocator);
     387         160 :     BinaryStreamWriter DbgStreamWriter(*WritableStream);
     388         240 :     if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
     389           0 :       return EC;
     390             :   }
     391             : 
     392          57 :   if (Writer.bytesRemaining() > 0)
     393             :     return make_error<RawError>(raw_error_code::invalid_format,
     394           0 :                                 "Unexpected bytes found in DBI Stream");
     395         171 :   return Error::success();
     396             : }

Generated by: LCOV version 1.13