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/BinaryStreamWriter.h"
14 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
15 #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
16 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
17 #include "llvm/DebugInfo/PDB/Native/RawError.h"
18 #include "llvm/Object/COFF.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 
158   BinaryStreamWriter ModiWriter(ModInfoBuffer);
159   for (const auto &M : ModuleInfoList) {
160     ModuleInfoHeader Layout = {};
161     Layout.ModDiStream = kInvalidStreamIndex;
162     Layout.NumFiles = M->SourceFiles.size();
163     if (auto EC = ModiWriter.writeObject(Layout))
164       return EC;
165     if (auto EC = ModiWriter.writeCString(M->Mod))
166       return EC;
167     if (auto EC = ModiWriter.writeCString(M->Obj))
168       return EC;
169   }
170   if (ModiWriter.bytesRemaining() > sizeof(uint32_t))
171     return make_error<RawError>(raw_error_code::invalid_format,
172                                 "Unexpected bytes in Modi Stream Data");
173   return Error::success();
174 }
175 
176 Error DbiStreamBuilder::generateFileInfoSubstream() {
177   uint32_t Size = calculateFileInfoSubstreamSize();
178   uint32_t NameSize = calculateNamesBufferSize();
179   auto Data = Allocator.Allocate<uint8_t>(Size);
180   uint32_t NamesOffset = Size - NameSize;
181 
182   FileInfoBuffer =
183       MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size));
184 
185   WritableBinaryStreamRef MetadataBuffer =
186       WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
187   BinaryStreamWriter MetadataWriter(MetadataBuffer);
188 
189   uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModuleInfos.size());
190   uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
191   if (auto EC = MetadataWriter.writeInteger(
192           ModiCount, llvm::support::little)) // NumModules
193     return EC;
194   if (auto EC = MetadataWriter.writeInteger(
195           FileCount, llvm::support::little)) // NumSourceFiles
196     return EC;
197   for (uint16_t I = 0; I < ModiCount; ++I) {
198     if (auto EC = MetadataWriter.writeInteger(
199             I, llvm::support::little)) // Mod Indices
200       return EC;
201   }
202   for (const auto MI : ModuleInfoList) {
203     FileCount = static_cast<uint16_t>(MI->SourceFiles.size());
204     if (auto EC = MetadataWriter.writeInteger(
205             FileCount, llvm::support::little)) // Mod File Counts
206       return EC;
207   }
208 
209   // Before writing the FileNameOffsets array, write the NamesBuffer array.
210   // A side effect of this is that this will actually compute the various
211   // file name offsets, so we can then go back and write the FileNameOffsets
212   // array to the other substream.
213   NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset);
214   BinaryStreamWriter NameBufferWriter(NamesBuffer);
215   for (auto &Name : SourceFileNames) {
216     Name.second = NameBufferWriter.getOffset();
217     if (auto EC = NameBufferWriter.writeCString(Name.getKey()))
218       return EC;
219   }
220 
221   for (const auto MI : ModuleInfoList) {
222     for (StringRef Name : MI->SourceFiles) {
223       auto Result = SourceFileNames.find(Name);
224       if (Result == SourceFileNames.end())
225         return make_error<RawError>(raw_error_code::no_entry,
226                                     "The source file was not found.");
227       if (auto EC = MetadataWriter.writeInteger(Result->second,
228                                                 llvm::support::little))
229         return EC;
230     }
231   }
232 
233   if (NameBufferWriter.bytesRemaining() > 0)
234     return make_error<RawError>(raw_error_code::invalid_format,
235                                 "The names buffer contained unexpected data.");
236 
237   if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
238     return make_error<RawError>(
239         raw_error_code::invalid_format,
240         "The metadata buffer contained unexpected data.");
241 
242   return Error::success();
243 }
244 
245 Error DbiStreamBuilder::finalize() {
246   if (Header)
247     return Error::success();
248 
249   DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
250 
251   if (auto EC = generateModiSubstream())
252     return EC;
253   if (auto EC = generateFileInfoSubstream())
254     return EC;
255 
256   H->VersionHeader = *VerHeader;
257   H->VersionSignature = -1;
258   H->Age = Age;
259   H->BuildNumber = BuildNumber;
260   H->Flags = Flags;
261   H->PdbDllRbld = PdbDllRbld;
262   H->PdbDllVersion = PdbDllVersion;
263   H->MachineType = static_cast<uint16_t>(MachineType);
264 
265   H->ECSubstreamSize = 0;
266   H->FileInfoSize = FileInfoBuffer.getLength();
267   H->ModiSubstreamSize = ModInfoBuffer.getLength();
268   H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
269   H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
270   H->SectionMapSize = calculateSectionMapStreamSize();
271   H->TypeServerSize = 0;
272   H->SymRecordStreamIndex = kInvalidStreamIndex;
273   H->PublicSymbolStreamIndex = kInvalidStreamIndex;
274   H->MFCTypeServerIndex = kInvalidStreamIndex;
275   H->GlobalSymbolStreamIndex = kInvalidStreamIndex;
276 
277   Header = H;
278   return Error::success();
279 }
280 
281 Error DbiStreamBuilder::finalizeMsfLayout() {
282   uint32_t Length = calculateSerializedLength();
283   if (auto EC = Msf.setStreamSize(StreamDBI, Length))
284     return EC;
285   return Error::success();
286 }
287 
288 static uint16_t toSecMapFlags(uint32_t Flags) {
289   uint16_t Ret = 0;
290   if (Flags & COFF::IMAGE_SCN_MEM_READ)
291     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
292   if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
293     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
294   if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
295     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
296   if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
297     Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
298   if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
299     Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
300 
301   // This seems always 1.
302   Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
303 
304   return Ret;
305 }
306 
307 // A utility function to create Section Contributions
308 // for a given input sections.
309 std::vector<SectionContrib> DbiStreamBuilder::createSectionContribs(
310     ArrayRef<object::coff_section> SecHdrs) {
311   std::vector<SectionContrib> Ret;
312 
313   // Create a SectionContrib for each input section.
314   for (auto &Sec : SecHdrs) {
315     Ret.emplace_back();
316     auto &Entry = Ret.back();
317     memset(&Entry, 0, sizeof(Entry));
318 
319     Entry.Off = Sec.PointerToRawData;
320     Entry.Size = Sec.SizeOfRawData;
321     Entry.Characteristics = Sec.Characteristics;
322   }
323   return Ret;
324 }
325 
326 // A utility function to create a Section Map for a given list of COFF sections.
327 //
328 // A Section Map seem to be a copy of a COFF section list in other format.
329 // I don't know why a PDB file contains both a COFF section header and
330 // a Section Map, but it seems it must be present in a PDB.
331 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
332     ArrayRef<llvm::object::coff_section> SecHdrs) {
333   std::vector<SecMapEntry> Ret;
334   int Idx = 0;
335 
336   auto Add = [&]() -> SecMapEntry & {
337     Ret.emplace_back();
338     auto &Entry = Ret.back();
339     memset(&Entry, 0, sizeof(Entry));
340 
341     Entry.Frame = Idx + 1;
342 
343     // We don't know the meaning of these fields yet.
344     Entry.SecName = UINT16_MAX;
345     Entry.ClassName = UINT16_MAX;
346 
347     return Entry;
348   };
349 
350   for (auto &Hdr : SecHdrs) {
351     auto &Entry = Add();
352     Entry.Flags = toSecMapFlags(Hdr.Characteristics);
353     Entry.SecByteLength = Hdr.VirtualSize;
354     ++Idx;
355   }
356 
357   // The last entry is for absolute symbols.
358   auto &Entry = Add();
359   Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
360                 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
361   Entry.SecByteLength = UINT32_MAX;
362 
363   return Ret;
364 }
365 
366 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
367                                WritableBinaryStreamRef Buffer) {
368   if (auto EC = finalize())
369     return EC;
370 
371   auto InfoS =
372       WritableMappedBlockStream::createIndexedStream(Layout, Buffer, StreamDBI);
373 
374   BinaryStreamWriter Writer(*InfoS);
375   if (auto EC = Writer.writeObject(*Header))
376     return EC;
377 
378   if (auto EC = Writer.writeStreamRef(ModInfoBuffer))
379     return EC;
380 
381   if (!SectionContribs.empty()) {
382     if (auto EC = Writer.writeEnum(DbiSecContribVer60, llvm::support::little))
383       return EC;
384     if (auto EC = Writer.writeArray(SectionContribs))
385       return EC;
386   }
387 
388   if (!SectionMap.empty()) {
389     ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
390     SecMapHeader SMHeader = {Size, Size};
391     if (auto EC = Writer.writeObject(SMHeader))
392       return EC;
393     if (auto EC = Writer.writeArray(SectionMap))
394       return EC;
395   }
396 
397   if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
398     return EC;
399 
400   for (auto &Stream : DbgStreams)
401     if (auto EC =
402             Writer.writeInteger(Stream.StreamNumber, llvm::support::little))
403       return EC;
404 
405   for (auto &Stream : DbgStreams) {
406     if (Stream.StreamNumber == kInvalidStreamIndex)
407       continue;
408     auto WritableBinaryStream = WritableMappedBlockStream::createIndexedStream(
409         Layout, Buffer, Stream.StreamNumber);
410     BinaryStreamWriter DbgStreamWriter(*WritableBinaryStream);
411     if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
412       return EC;
413   }
414 
415   if (Writer.bytesRemaining() > 0)
416     return make_error<RawError>(raw_error_code::invalid_format,
417                                 "Unexpected bytes found in DBI Stream");
418   return Error::success();
419 }
420