xref: /llvm-project/llvm/lib/DebugInfo/PDB/Native/PDBFile.cpp (revision 9fb9d71d3e6a0515cb0ad416bc4400d47801888a)
1 //===- PDBFile.cpp - Low level interface to a PDB file ----------*- 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/PDBFile.h"
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/DebugInfo/MSF/MSFCommon.h"
14 #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
15 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
16 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
17 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
18 #include "llvm/DebugInfo/PDB/Native/PDBStringTable.h"
19 #include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
20 #include "llvm/DebugInfo/PDB/Native/RawError.h"
21 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
22 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
23 #include "llvm/Support/BinaryStream.h"
24 #include "llvm/Support/BinaryStreamArray.h"
25 #include "llvm/Support/BinaryStreamReader.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/Path.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstdint>
32 
33 using namespace llvm;
34 using namespace llvm::codeview;
35 using namespace llvm::msf;
36 using namespace llvm::pdb;
37 
38 namespace {
39 typedef FixedStreamArray<support::ulittle32_t> ulittle_array;
40 } // end anonymous namespace
41 
42 PDBFile::PDBFile(StringRef Path, std::unique_ptr<BinaryStream> PdbFileBuffer,
43                  BumpPtrAllocator &Allocator)
44     : FilePath(Path), Allocator(Allocator), Buffer(std::move(PdbFileBuffer)) {}
45 
46 PDBFile::~PDBFile() = default;
47 
48 StringRef PDBFile::getFilePath() const { return FilePath; }
49 
50 StringRef PDBFile::getFileDirectory() const {
51   return sys::path::parent_path(FilePath);
52 }
53 
54 uint32_t PDBFile::getBlockSize() const { return ContainerLayout.SB->BlockSize; }
55 
56 uint32_t PDBFile::getFreeBlockMapBlock() const {
57   return ContainerLayout.SB->FreeBlockMapBlock;
58 }
59 
60 uint32_t PDBFile::getBlockCount() const {
61   return ContainerLayout.SB->NumBlocks;
62 }
63 
64 uint32_t PDBFile::getNumDirectoryBytes() const {
65   return ContainerLayout.SB->NumDirectoryBytes;
66 }
67 
68 uint32_t PDBFile::getBlockMapIndex() const {
69   return ContainerLayout.SB->BlockMapAddr;
70 }
71 
72 uint32_t PDBFile::getUnknown1() const { return ContainerLayout.SB->Unknown1; }
73 
74 uint32_t PDBFile::getNumDirectoryBlocks() const {
75   return msf::bytesToBlocks(ContainerLayout.SB->NumDirectoryBytes,
76                             ContainerLayout.SB->BlockSize);
77 }
78 
79 uint64_t PDBFile::getBlockMapOffset() const {
80   return (uint64_t)ContainerLayout.SB->BlockMapAddr *
81          ContainerLayout.SB->BlockSize;
82 }
83 
84 uint32_t PDBFile::getNumStreams() const {
85   return ContainerLayout.StreamSizes.size();
86 }
87 
88 uint32_t PDBFile::getStreamByteSize(uint32_t StreamIndex) const {
89   return ContainerLayout.StreamSizes[StreamIndex];
90 }
91 
92 ArrayRef<support::ulittle32_t>
93 PDBFile::getStreamBlockList(uint32_t StreamIndex) const {
94   return ContainerLayout.StreamMap[StreamIndex];
95 }
96 
97 uint32_t PDBFile::getFileSize() const { return Buffer->getLength(); }
98 
99 Expected<ArrayRef<uint8_t>> PDBFile::getBlockData(uint32_t BlockIndex,
100                                                   uint32_t NumBytes) const {
101   uint64_t StreamBlockOffset = msf::blockToOffset(BlockIndex, getBlockSize());
102 
103   ArrayRef<uint8_t> Result;
104   if (auto EC = Buffer->readBytes(StreamBlockOffset, NumBytes, Result))
105     return std::move(EC);
106   return Result;
107 }
108 
109 Error PDBFile::setBlockData(uint32_t BlockIndex, uint32_t Offset,
110                             ArrayRef<uint8_t> Data) const {
111   return make_error<RawError>(raw_error_code::not_writable,
112                               "PDBFile is immutable");
113 }
114 
115 Error PDBFile::parseFileHeaders() {
116   BinaryStreamReader Reader(*Buffer);
117 
118   // Initialize SB.
119   const msf::SuperBlock *SB = nullptr;
120   if (auto EC = Reader.readObject(SB)) {
121     consumeError(std::move(EC));
122     return make_error<RawError>(raw_error_code::corrupt_file,
123                                 "Does not contain superblock");
124   }
125 
126   if (auto EC = msf::validateSuperBlock(*SB))
127     return EC;
128 
129   if (Buffer->getLength() % SB->BlockSize != 0)
130     return make_error<RawError>(raw_error_code::corrupt_file,
131                                 "File size is not a multiple of block size");
132   ContainerLayout.SB = SB;
133 
134   // Initialize Free Page Map.
135   ContainerLayout.FreePageMap.resize(SB->NumBlocks);
136   // The Fpm exists either at block 1 or block 2 of the MSF.  However, this
137   // allows for a maximum of getBlockSize() * 8 blocks bits in the Fpm, and
138   // thusly an equal number of total blocks in the file.  For a block size
139   // of 4KiB (very common), this would yield 32KiB total blocks in file, for a
140   // maximum file size of 32KiB * 4KiB = 128MiB.  Obviously this won't do, so
141   // the Fpm is split across the file at `getBlockSize()` intervals.  As a
142   // result, every block whose index is of the form |{1,2} + getBlockSize() * k|
143   // for any non-negative integer k is an Fpm block.  In theory, we only really
144   // need to reserve blocks of the form |{1,2} + getBlockSize() * 8 * k|, but
145   // current versions of the MSF format already expect the Fpm to be arranged
146   // at getBlockSize() intervals, so we have to be compatible.
147   // See the function fpmPn() for more information:
148   // https://github.com/Microsoft/microsoft-pdb/blob/master/PDB/msf/msf.cpp#L489
149   auto FpmStream =
150       MappedBlockStream::createFpmStream(ContainerLayout, *Buffer, Allocator);
151   BinaryStreamReader FpmReader(*FpmStream);
152   ArrayRef<uint8_t> FpmBytes;
153   if (auto EC = FpmReader.readBytes(FpmBytes, FpmReader.bytesRemaining()))
154     return EC;
155   uint32_t BlocksRemaining = getBlockCount();
156   uint32_t BI = 0;
157   for (auto Byte : FpmBytes) {
158     uint32_t BlocksThisByte = std::min(BlocksRemaining, 8U);
159     for (uint32_t I = 0; I < BlocksThisByte; ++I) {
160       if (Byte & (1 << I))
161         ContainerLayout.FreePageMap[BI] = true;
162       --BlocksRemaining;
163       ++BI;
164     }
165   }
166 
167   Reader.setOffset(getBlockMapOffset());
168   if (auto EC = Reader.readArray(ContainerLayout.DirectoryBlocks,
169                                  getNumDirectoryBlocks()))
170     return EC;
171 
172   return Error::success();
173 }
174 
175 Error PDBFile::parseStreamData() {
176   assert(ContainerLayout.SB);
177   if (DirectoryStream)
178     return Error::success();
179 
180   uint32_t NumStreams = 0;
181 
182   // Normally you can't use a MappedBlockStream without having fully parsed the
183   // PDB file, because it accesses the directory and various other things, which
184   // is exactly what we are attempting to parse.  By specifying a custom
185   // subclass of IPDBStreamData which only accesses the fields that have already
186   // been parsed, we can avoid this and reuse MappedBlockStream.
187   auto DS = MappedBlockStream::createDirectoryStream(ContainerLayout, *Buffer,
188                                                      Allocator);
189   BinaryStreamReader Reader(*DS);
190   if (auto EC = Reader.readInteger(NumStreams))
191     return EC;
192 
193   if (auto EC = Reader.readArray(ContainerLayout.StreamSizes, NumStreams))
194     return EC;
195   for (uint32_t I = 0; I < NumStreams; ++I) {
196     uint32_t StreamSize = getStreamByteSize(I);
197     // FIXME: What does StreamSize ~0U mean?
198     uint64_t NumExpectedStreamBlocks =
199         StreamSize == UINT32_MAX
200             ? 0
201             : msf::bytesToBlocks(StreamSize, ContainerLayout.SB->BlockSize);
202 
203     // For convenience, we store the block array contiguously.  This is because
204     // if someone calls setStreamMap(), it is more convenient to be able to call
205     // it with an ArrayRef instead of setting up a StreamRef.  Since the
206     // DirectoryStream is cached in the class and thus lives for the life of the
207     // class, we can be guaranteed that readArray() will return a stable
208     // reference, even if it has to allocate from its internal pool.
209     ArrayRef<support::ulittle32_t> Blocks;
210     if (auto EC = Reader.readArray(Blocks, NumExpectedStreamBlocks))
211       return EC;
212     for (uint32_t Block : Blocks) {
213       uint64_t BlockEndOffset =
214           (uint64_t)(Block + 1) * ContainerLayout.SB->BlockSize;
215       if (BlockEndOffset > getFileSize())
216         return make_error<RawError>(raw_error_code::corrupt_file,
217                                     "Stream block map is corrupt.");
218     }
219     ContainerLayout.StreamMap.push_back(Blocks);
220   }
221 
222   // We should have read exactly SB->NumDirectoryBytes bytes.
223   assert(Reader.bytesRemaining() == 0);
224   DirectoryStream = std::move(DS);
225   return Error::success();
226 }
227 
228 ArrayRef<support::ulittle32_t> PDBFile::getDirectoryBlockArray() const {
229   return ContainerLayout.DirectoryBlocks;
230 }
231 
232 MSFStreamLayout PDBFile::getStreamLayout(uint32_t StreamIdx) const {
233   MSFStreamLayout Result;
234   auto Blocks = getStreamBlockList(StreamIdx);
235   Result.Blocks.assign(Blocks.begin(), Blocks.end());
236   Result.Length = getStreamByteSize(StreamIdx);
237   return Result;
238 }
239 
240 msf::MSFStreamLayout PDBFile::getFpmStreamLayout() const {
241   return msf::getFpmStreamLayout(ContainerLayout);
242 }
243 
244 Expected<GlobalsStream &> PDBFile::getPDBGlobalsStream() {
245   if (!Globals) {
246     auto DbiS = getPDBDbiStream();
247     if (!DbiS)
248       return DbiS.takeError();
249 
250     auto GlobalS = safelyCreateIndexedStream(
251         ContainerLayout, *Buffer, DbiS->getGlobalSymbolStreamIndex());
252     if (!GlobalS)
253       return GlobalS.takeError();
254     auto TempGlobals = llvm::make_unique<GlobalsStream>(std::move(*GlobalS));
255     if (auto EC = TempGlobals->reload())
256       return std::move(EC);
257     Globals = std::move(TempGlobals);
258   }
259   return *Globals;
260 }
261 
262 Expected<InfoStream &> PDBFile::getPDBInfoStream() {
263   if (!Info) {
264     auto InfoS = safelyCreateIndexedStream(ContainerLayout, *Buffer, StreamPDB);
265     if (!InfoS)
266       return InfoS.takeError();
267     auto TempInfo = llvm::make_unique<InfoStream>(std::move(*InfoS));
268     if (auto EC = TempInfo->reload())
269       return std::move(EC);
270     Info = std::move(TempInfo);
271   }
272   return *Info;
273 }
274 
275 Expected<DbiStream &> PDBFile::getPDBDbiStream() {
276   if (!Dbi) {
277     auto DbiS = safelyCreateIndexedStream(ContainerLayout, *Buffer, StreamDBI);
278     if (!DbiS)
279       return DbiS.takeError();
280     auto TempDbi = llvm::make_unique<DbiStream>(*this, std::move(*DbiS));
281     if (auto EC = TempDbi->reload())
282       return std::move(EC);
283     Dbi = std::move(TempDbi);
284   }
285   return *Dbi;
286 }
287 
288 Expected<TpiStream &> PDBFile::getPDBTpiStream() {
289   if (!Tpi) {
290     auto TpiS = safelyCreateIndexedStream(ContainerLayout, *Buffer, StreamTPI);
291     if (!TpiS)
292       return TpiS.takeError();
293     auto TempTpi = llvm::make_unique<TpiStream>(*this, std::move(*TpiS));
294     if (auto EC = TempTpi->reload())
295       return std::move(EC);
296     Tpi = std::move(TempTpi);
297   }
298   return *Tpi;
299 }
300 
301 Expected<TpiStream &> PDBFile::getPDBIpiStream() {
302   if (!Ipi) {
303     auto IpiS = safelyCreateIndexedStream(ContainerLayout, *Buffer, StreamIPI);
304     if (!IpiS)
305       return IpiS.takeError();
306     auto TempIpi = llvm::make_unique<TpiStream>(*this, std::move(*IpiS));
307     if (auto EC = TempIpi->reload())
308       return std::move(EC);
309     Ipi = std::move(TempIpi);
310   }
311   return *Ipi;
312 }
313 
314 Expected<PublicsStream &> PDBFile::getPDBPublicsStream() {
315   if (!Publics) {
316     auto DbiS = getPDBDbiStream();
317     if (!DbiS)
318       return DbiS.takeError();
319 
320     auto PublicS = safelyCreateIndexedStream(
321         ContainerLayout, *Buffer, DbiS->getPublicSymbolStreamIndex());
322     if (!PublicS)
323       return PublicS.takeError();
324     auto TempPublics = llvm::make_unique<PublicsStream>(std::move(*PublicS));
325     if (auto EC = TempPublics->reload())
326       return std::move(EC);
327     Publics = std::move(TempPublics);
328   }
329   return *Publics;
330 }
331 
332 Expected<SymbolStream &> PDBFile::getPDBSymbolStream() {
333   if (!Symbols) {
334     auto DbiS = getPDBDbiStream();
335     if (!DbiS)
336       return DbiS.takeError();
337 
338     uint32_t SymbolStreamNum = DbiS->getSymRecordStreamIndex();
339     auto SymbolS =
340         safelyCreateIndexedStream(ContainerLayout, *Buffer, SymbolStreamNum);
341     if (!SymbolS)
342       return SymbolS.takeError();
343 
344     auto TempSymbols = llvm::make_unique<SymbolStream>(std::move(*SymbolS));
345     if (auto EC = TempSymbols->reload())
346       return std::move(EC);
347     Symbols = std::move(TempSymbols);
348   }
349   return *Symbols;
350 }
351 
352 Expected<PDBStringTable &> PDBFile::getStringTable() {
353   if (!Strings) {
354     auto IS = getPDBInfoStream();
355     if (!IS)
356       return IS.takeError();
357 
358     uint32_t NameStreamIndex = IS->getNamedStreamIndex("/names");
359 
360     auto NS =
361         safelyCreateIndexedStream(ContainerLayout, *Buffer, NameStreamIndex);
362     if (!NS)
363       return NS.takeError();
364 
365     auto N = llvm::make_unique<PDBStringTable>();
366     BinaryStreamReader Reader(**NS);
367     if (auto EC = N->reload(Reader))
368       return std::move(EC);
369     assert(Reader.bytesRemaining() == 0);
370     StringTableStream = std::move(*NS);
371     Strings = std::move(N);
372   }
373   return *Strings;
374 }
375 
376 uint32_t PDBFile::getPointerSize() {
377   auto DbiS = getPDBDbiStream();
378   if (!DbiS)
379     return 0;
380   PDB_Machine Machine = DbiS->getMachineType();
381   if (Machine == PDB_Machine::Amd64)
382     return 8;
383   return 4;
384 }
385 
386 bool PDBFile::hasPDBDbiStream() const { return StreamDBI < getNumStreams(); }
387 
388 bool PDBFile::hasPDBGlobalsStream() {
389   auto DbiS = getPDBDbiStream();
390   if (!DbiS) {
391     consumeError(DbiS.takeError());
392     return false;
393   }
394 
395   return DbiS->getGlobalSymbolStreamIndex() < getNumStreams();
396 }
397 
398 bool PDBFile::hasPDBInfoStream() { return StreamPDB < getNumStreams(); }
399 
400 bool PDBFile::hasPDBIpiStream() const { return StreamIPI < getNumStreams(); }
401 
402 bool PDBFile::hasPDBPublicsStream() {
403   auto DbiS = getPDBDbiStream();
404   if (!DbiS) {
405     consumeError(DbiS.takeError());
406     return false;
407   }
408   return DbiS->getPublicSymbolStreamIndex() < getNumStreams();
409 }
410 
411 bool PDBFile::hasPDBSymbolStream() {
412   auto DbiS = getPDBDbiStream();
413   if (!DbiS)
414     return false;
415   return DbiS->getSymRecordStreamIndex() < getNumStreams();
416 }
417 
418 bool PDBFile::hasPDBTpiStream() const { return StreamTPI < getNumStreams(); }
419 
420 bool PDBFile::hasPDBStringTable() {
421   auto IS = getPDBInfoStream();
422   if (!IS)
423     return false;
424   return IS->getNamedStreamIndex("/names") < getNumStreams();
425 }
426 
427 /// Wrapper around MappedBlockStream::createIndexedStream() that checks if a
428 /// stream with that index actually exists.  If it does not, the return value
429 /// will have an MSFError with code msf_error_code::no_stream.  Else, the return
430 /// value will contain the stream returned by createIndexedStream().
431 Expected<std::unique_ptr<MappedBlockStream>>
432 PDBFile::safelyCreateIndexedStream(const MSFLayout &Layout,
433                                    BinaryStreamRef MsfData,
434                                    uint32_t StreamIndex) const {
435   if (StreamIndex >= getNumStreams())
436     return make_error<RawError>(raw_error_code::no_stream);
437   return MappedBlockStream::createIndexedStream(Layout, MsfData, StreamIndex,
438                                                 Allocator);
439 }
440