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