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