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