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