1 //===- PDBFileBuilder.cpp - PDB File 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/PDBFileBuilder.h"
11 
12 #include "llvm/ADT/BitVector.h"
13 
14 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
15 #include "llvm/DebugInfo/PDB/GenericError.h"
16 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
17 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
18 #include "llvm/DebugInfo/PDB/Native/GSIStreamBuilder.h"
19 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
20 #include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
21 #include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
22 #include "llvm/DebugInfo/PDB/Native/RawError.h"
23 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
24 #include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
25 #include "llvm/Support/BinaryStream.h"
26 #include "llvm/Support/BinaryStreamWriter.h"
27 #include "llvm/Support/JamCRC.h"
28 #include "llvm/Support/Path.h"
29 
30 using namespace llvm;
31 using namespace llvm::codeview;
32 using namespace llvm::msf;
33 using namespace llvm::pdb;
34 using namespace llvm::support;
35 
36 PDBFileBuilder::PDBFileBuilder(BumpPtrAllocator &Allocator)
37     : Allocator(Allocator), InjectedSourceHashTraits(Strings),
38       InjectedSourceTable(2, InjectedSourceHashTraits) {}
39 
40 PDBFileBuilder::~PDBFileBuilder() {}
41 
42 Error PDBFileBuilder::initialize(uint32_t BlockSize) {
43   auto ExpectedMsf = MSFBuilder::create(Allocator, BlockSize);
44   if (!ExpectedMsf)
45     return ExpectedMsf.takeError();
46   Msf = llvm::make_unique<MSFBuilder>(std::move(*ExpectedMsf));
47   return Error::success();
48 }
49 
50 MSFBuilder &PDBFileBuilder::getMsfBuilder() { return *Msf; }
51 
52 InfoStreamBuilder &PDBFileBuilder::getInfoBuilder() {
53   if (!Info)
54     Info = llvm::make_unique<InfoStreamBuilder>(*Msf, NamedStreams);
55   return *Info;
56 }
57 
58 DbiStreamBuilder &PDBFileBuilder::getDbiBuilder() {
59   if (!Dbi)
60     Dbi = llvm::make_unique<DbiStreamBuilder>(*Msf);
61   return *Dbi;
62 }
63 
64 TpiStreamBuilder &PDBFileBuilder::getTpiBuilder() {
65   if (!Tpi)
66     Tpi = llvm::make_unique<TpiStreamBuilder>(*Msf, StreamTPI);
67   return *Tpi;
68 }
69 
70 TpiStreamBuilder &PDBFileBuilder::getIpiBuilder() {
71   if (!Ipi)
72     Ipi = llvm::make_unique<TpiStreamBuilder>(*Msf, StreamIPI);
73   return *Ipi;
74 }
75 
76 PDBStringTableBuilder &PDBFileBuilder::getStringTableBuilder() {
77   return Strings;
78 }
79 
80 GSIStreamBuilder &PDBFileBuilder::getGsiBuilder() {
81   if (!Gsi)
82     Gsi = llvm::make_unique<GSIStreamBuilder>(*Msf);
83   return *Gsi;
84 }
85 
86 Expected<uint32_t> PDBFileBuilder::allocateNamedStream(StringRef Name,
87                                                        uint32_t Size) {
88   auto ExpectedStream = Msf->addStream(Size);
89   if (ExpectedStream)
90     NamedStreams.set(Name, *ExpectedStream);
91   return ExpectedStream;
92 }
93 
94 Error PDBFileBuilder::addNamedStream(StringRef Name, StringRef Data) {
95   Expected<uint32_t> ExpectedIndex = allocateNamedStream(Name, Data.size());
96   if (!ExpectedIndex)
97     return ExpectedIndex.takeError();
98   assert(NamedStreamData.count(*ExpectedIndex) == 0);
99   NamedStreamData[*ExpectedIndex] = Data;
100   return Error::success();
101 }
102 
103 void PDBFileBuilder::addInjectedSource(StringRef Name,
104                                        std::unique_ptr<MemoryBuffer> Buffer) {
105   // Stream names must be exact matches, since they get looked up in a hash
106   // table and the hash value is dependent on the exact contents of the string.
107   // link.exe lowercases a path and converts / to \, so we must do the same.
108   SmallString<64> VName;
109   sys::path::native(Name.lower(), VName);
110 
111   uint32_t NI = getStringTableBuilder().insert(Name);
112   uint32_t VNI = getStringTableBuilder().insert(VName);
113 
114   InjectedSourceDescriptor Desc;
115   Desc.Content = std::move(Buffer);
116   Desc.NameIndex = NI;
117   Desc.VNameIndex = VNI;
118   Desc.StreamName = "/src/files/";
119 
120   Desc.StreamName += VName;
121 
122   InjectedSources.push_back(std::move(Desc));
123 }
124 
125 Expected<msf::MSFLayout> PDBFileBuilder::finalizeMsfLayout() {
126 
127   if (Ipi && Ipi->getRecordCount() > 0) {
128     // In theory newer PDBs always have an ID stream, but by saying that we're
129     // only going to *really* have an ID stream if there is at least one ID
130     // record, we leave open the opportunity to test older PDBs such as those
131     // that don't have an ID stream.
132     auto &Info = getInfoBuilder();
133     Info.addFeature(PdbRaw_FeatureSig::VC140);
134   }
135 
136   uint32_t StringsLen = Strings.calculateSerializedSize();
137 
138   Expected<uint32_t> SN = allocateNamedStream("/names", StringsLen);
139   if (!SN)
140     return SN.takeError();
141   SN = allocateNamedStream("/LinkInfo", 0);
142   if (!SN)
143     return SN.takeError();
144 
145   if (Dbi) {
146     if (auto EC = Dbi->finalizeMsfLayout())
147       return std::move(EC);
148   }
149   if (Tpi) {
150     if (auto EC = Tpi->finalizeMsfLayout())
151       return std::move(EC);
152   }
153   if (Ipi) {
154     if (auto EC = Ipi->finalizeMsfLayout())
155       return std::move(EC);
156   }
157   if (Gsi) {
158     if (auto EC = Gsi->finalizeMsfLayout())
159       return std::move(EC);
160     if (Dbi) {
161       Dbi->setPublicsStreamIndex(Gsi->getPublicsStreamIndex());
162       Dbi->setGlobalsStreamIndex(Gsi->getGlobalsStreamIndex());
163       Dbi->setSymbolRecordStreamIndex(Gsi->getRecordStreamIdx());
164     }
165   }
166 
167   if (!InjectedSources.empty()) {
168     for (const auto &IS : InjectedSources) {
169       JamCRC CRC(0);
170       CRC.update(makeArrayRef(IS.Content->getBufferStart(),
171                               IS.Content->getBufferSize()));
172 
173       SrcHeaderBlockEntry Entry;
174       ::memset(&Entry, 0, sizeof(SrcHeaderBlockEntry));
175       Entry.Size = sizeof(SrcHeaderBlockEntry);
176       Entry.FileSize = IS.Content->getBufferSize();
177       Entry.FileNI = IS.NameIndex;
178       Entry.VFileNI = IS.VNameIndex;
179       Entry.IsVirtual = 0;
180       Entry.Version =
181           static_cast<uint32_t>(PdbRaw_SrcHeaderBlockVer::SrcVerOne);
182       Entry.CRC = CRC.getCRC();
183       StringRef VName = getStringTableBuilder().getStringForId(IS.VNameIndex);
184       InjectedSourceTable.set_as(VName, std::move(Entry));
185     }
186 
187     uint32_t SrcHeaderBlockSize =
188         sizeof(SrcHeaderBlockHeader) +
189         InjectedSourceTable.calculateSerializedLength();
190     SN = allocateNamedStream("/src/headerblock", SrcHeaderBlockSize);
191     if (!SN)
192       return SN.takeError();
193     for (const auto &IS : InjectedSources) {
194       SN = allocateNamedStream(IS.StreamName, IS.Content->getBufferSize());
195       if (!SN)
196         return SN.takeError();
197     }
198   }
199 
200   // Do this last, since it relies on the named stream map being complete, and
201   // that can be updated by previous steps in the finalization.
202   if (Info) {
203     if (auto EC = Info->finalizeMsfLayout())
204       return std::move(EC);
205   }
206 
207   return Msf->build();
208 }
209 
210 Expected<uint32_t> PDBFileBuilder::getNamedStreamIndex(StringRef Name) const {
211   uint32_t SN = 0;
212   if (!NamedStreams.get(Name, SN))
213     return llvm::make_error<pdb::RawError>(raw_error_code::no_stream);
214   return SN;
215 }
216 
217 void PDBFileBuilder::commitFpm(WritableBinaryStream &MsfBuffer,
218                                const MSFLayout &Layout) {
219   auto FpmStream =
220       WritableMappedBlockStream::createFpmStream(Layout, MsfBuffer, Allocator);
221 
222   // We only need to create the alt fpm stream so that it gets initialized.
223   WritableMappedBlockStream::createFpmStream(Layout, MsfBuffer, Allocator,
224                                              true);
225 
226   uint32_t BI = 0;
227   BinaryStreamWriter FpmWriter(*FpmStream);
228   while (BI < Layout.SB->NumBlocks) {
229     uint8_t ThisByte = 0;
230     for (uint32_t I = 0; I < 8; ++I) {
231       bool IsFree =
232           (BI < Layout.SB->NumBlocks) ? Layout.FreePageMap.test(BI) : true;
233       uint8_t Mask = uint8_t(IsFree) << I;
234       ThisByte |= Mask;
235       ++BI;
236     }
237     cantFail(FpmWriter.writeObject(ThisByte));
238   }
239   assert(FpmWriter.bytesRemaining() == 0);
240 }
241 
242 void PDBFileBuilder::commitSrcHeaderBlock(WritableBinaryStream &MsfBuffer,
243                                           const msf::MSFLayout &Layout) {
244   assert(!InjectedSourceTable.empty());
245 
246   uint32_t SN = cantFail(getNamedStreamIndex("/src/headerblock"));
247   auto Stream = WritableMappedBlockStream::createIndexedStream(
248       Layout, MsfBuffer, SN, Allocator);
249   BinaryStreamWriter Writer(*Stream);
250 
251   SrcHeaderBlockHeader Header;
252   ::memset(&Header, 0, sizeof(Header));
253   Header.Version = static_cast<uint32_t>(PdbRaw_SrcHeaderBlockVer::SrcVerOne);
254   Header.Size = Writer.bytesRemaining();
255 
256   cantFail(Writer.writeObject(Header));
257   cantFail(InjectedSourceTable.commit(Writer));
258 
259   assert(Writer.bytesRemaining() == 0);
260 }
261 
262 void PDBFileBuilder::commitInjectedSources(WritableBinaryStream &MsfBuffer,
263                                            const msf::MSFLayout &Layout) {
264   if (InjectedSourceTable.empty())
265     return;
266 
267   commitSrcHeaderBlock(MsfBuffer, Layout);
268 
269   for (const auto &IS : InjectedSources) {
270     uint32_t SN = cantFail(getNamedStreamIndex(IS.StreamName));
271 
272     auto SourceStream = WritableMappedBlockStream::createIndexedStream(
273         Layout, MsfBuffer, SN, Allocator);
274     BinaryStreamWriter SourceWriter(*SourceStream);
275     assert(SourceWriter.bytesRemaining() == IS.Content->getBufferSize());
276     cantFail(SourceWriter.writeBytes(
277         arrayRefFromStringRef(IS.Content->getBuffer())));
278   }
279 }
280 
281 Error PDBFileBuilder::commit(StringRef Filename) {
282   assert(!Filename.empty());
283   auto ExpectedLayout = finalizeMsfLayout();
284   if (!ExpectedLayout)
285     return ExpectedLayout.takeError();
286   auto &Layout = *ExpectedLayout;
287 
288   uint64_t Filesize = Layout.SB->BlockSize * Layout.SB->NumBlocks;
289   auto OutFileOrError = FileOutputBuffer::create(Filename, Filesize);
290   if (auto E = OutFileOrError.takeError())
291     return E;
292   FileOutputBuffer *FOB = OutFileOrError->get();
293 
294   FileBufferByteStream Buffer(std::move(*OutFileOrError),
295                               llvm::support::little);
296   BinaryStreamWriter Writer(Buffer);
297 
298   if (auto EC = Writer.writeObject(*Layout.SB))
299     return EC;
300 
301   commitFpm(Buffer, Layout);
302 
303   uint32_t BlockMapOffset =
304       msf::blockToOffset(Layout.SB->BlockMapAddr, Layout.SB->BlockSize);
305   Writer.setOffset(BlockMapOffset);
306   if (auto EC = Writer.writeArray(Layout.DirectoryBlocks))
307     return EC;
308 
309   auto DirStream = WritableMappedBlockStream::createDirectoryStream(
310       Layout, Buffer, Allocator);
311   BinaryStreamWriter DW(*DirStream);
312   if (auto EC = DW.writeInteger<uint32_t>(Layout.StreamSizes.size()))
313     return EC;
314 
315   if (auto EC = DW.writeArray(Layout.StreamSizes))
316     return EC;
317 
318   for (const auto &Blocks : Layout.StreamMap) {
319     if (auto EC = DW.writeArray(Blocks))
320       return EC;
321   }
322 
323   auto ExpectedSN = getNamedStreamIndex("/names");
324   if (!ExpectedSN)
325     return ExpectedSN.takeError();
326 
327   auto NS = WritableMappedBlockStream::createIndexedStream(
328       Layout, Buffer, *ExpectedSN, Allocator);
329   BinaryStreamWriter NSWriter(*NS);
330   if (auto EC = Strings.commit(NSWriter))
331     return EC;
332 
333   for (const auto &NSE : NamedStreamData) {
334     if (NSE.second.empty())
335       continue;
336 
337     auto NS = WritableMappedBlockStream::createIndexedStream(
338         Layout, Buffer, NSE.first, Allocator);
339     BinaryStreamWriter NSW(*NS);
340     if (auto EC = NSW.writeBytes(arrayRefFromStringRef(NSE.second)))
341       return EC;
342   }
343 
344   if (Info) {
345     if (auto EC = Info->commit(Layout, Buffer))
346       return EC;
347   }
348 
349   if (Dbi) {
350     if (auto EC = Dbi->commit(Layout, Buffer))
351       return EC;
352   }
353 
354   if (Tpi) {
355     if (auto EC = Tpi->commit(Layout, Buffer))
356       return EC;
357   }
358 
359   if (Ipi) {
360     if (auto EC = Ipi->commit(Layout, Buffer))
361       return EC;
362   }
363 
364   if (Gsi) {
365     if (auto EC = Gsi->commit(Layout, Buffer))
366       return EC;
367   }
368 
369   auto InfoStreamBlocks = Layout.StreamMap[StreamPDB];
370   assert(!InfoStreamBlocks.empty());
371   uint64_t InfoStreamFileOffset =
372       blockToOffset(InfoStreamBlocks.front(), Layout.SB->BlockSize);
373   InfoStreamHeader *H = reinterpret_cast<InfoStreamHeader *>(
374       FOB->getBufferStart() + InfoStreamFileOffset);
375 
376   commitInjectedSources(Buffer, Layout);
377 
378   // Set the build id at the very end, after every other byte of the PDB
379   // has been written.
380   // FIXME: Use a hash of the PDB rather than time(nullptr) for the signature.
381   H->Age = Info->getAge();
382   H->Guid = Info->getGuid();
383   Optional<uint32_t> Sig = Info->getSignature();
384   H->Signature = Sig.hasValue() ? *Sig : time(nullptr);
385 
386   return Buffer.commit();
387 }
388