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