blob: 9989c4c6dd77141c18f1eafc0b9605451dab7a58 [file] [log] [blame]
Zachary Turnerdbeaea72016-07-11 21:45:26 +00001//===- 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/Raw/DbiStreamBuilder.h"
11
Rui Ueyamaf9904042016-10-11 19:43:12 +000012#include "llvm/ADT/ArrayRef.h"
Zachary Turner620961d2016-09-14 23:00:02 +000013#include "llvm/DebugInfo/MSF/MSFBuilder.h"
Zachary Turnera3225b02016-07-29 20:56:36 +000014#include "llvm/DebugInfo/MSF/MappedBlockStream.h"
15#include "llvm/DebugInfo/MSF/StreamWriter.h"
Zachary Turnerdbeaea72016-07-11 21:45:26 +000016#include "llvm/DebugInfo/PDB/Raw/DbiStream.h"
Zachary Turnerdbeaea72016-07-11 21:45:26 +000017#include "llvm/DebugInfo/PDB/Raw/RawError.h"
Rui Ueyamaddc79222016-10-31 17:38:56 +000018#include "llvm/Object/COFF.h"
19#include "llvm/Support/COFF.h"
Zachary Turnerdbeaea72016-07-11 21:45:26 +000020
21using namespace llvm;
22using namespace llvm::codeview;
Zachary Turnerbac69d32016-07-22 19:56:05 +000023using namespace llvm::msf;
Zachary Turnerdbeaea72016-07-11 21:45:26 +000024using namespace llvm::pdb;
25
Zachary Turnerd218c262016-07-22 15:46:37 +000026namespace {
27class ModiSubstreamBuilder {};
28}
29
Zachary Turner620961d2016-09-14 23:00:02 +000030DbiStreamBuilder::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),
Reid Kleckner5d0bc632016-10-11 20:02:57 +000033 Header(nullptr), DbgStreams((int)DbgHeaderType::Max) {}
Zachary Turnerdbeaea72016-07-11 21:45:26 +000034
35void DbiStreamBuilder::setVersionHeader(PdbRaw_DbiVer V) { VerHeader = V; }
36
37void DbiStreamBuilder::setAge(uint32_t A) { Age = A; }
38
39void DbiStreamBuilder::setBuildNumber(uint16_t B) { BuildNumber = B; }
40
41void DbiStreamBuilder::setPdbDllVersion(uint16_t V) { PdbDllVersion = V; }
42
43void DbiStreamBuilder::setPdbDllRbld(uint16_t R) { PdbDllRbld = R; }
44
45void DbiStreamBuilder::setFlags(uint16_t F) { Flags = F; }
46
47void DbiStreamBuilder::setMachineType(PDB_Machine M) { MachineType = M; }
48
Rui Ueyamaf7c9c322016-11-11 23:41:13 +000049void DbiStreamBuilder::setSectionContribs(ArrayRef<SectionContrib> Arr) {
50 SectionContribs = Arr;
51}
52
Rui Ueyamaddc79222016-10-31 17:38:56 +000053void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) {
54 SectionMap = SecMap;
55}
56
Rui Ueyamaf9904042016-10-11 19:43:12 +000057Error 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
Zachary Turnerfaa554b2016-07-15 22:16:56 +000071uint32_t DbiStreamBuilder::calculateSerializedLength() const {
72 // For now we only support serializing the header.
Zachary Turnerb383d622016-07-22 15:46:46 +000073 return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
Rui Ueyamaf7c9c322016-11-11 23:41:13 +000074 calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
75 calculateSectionMapStreamSize() + calculateDbgStreamsSize();
Zachary Turnerd218c262016-07-22 15:46:37 +000076}
77
78Error 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
91Error 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
103uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
104 uint32_t Size = 0;
105 for (const auto &M : ModuleInfoList) {
Zachary Turnerb383d622016-07-22 15:46:46 +0000106 Size += sizeof(ModuleInfoHeader);
Zachary Turnerd218c262016-07-22 15:46:37 +0000107 Size += M->Mod.size() + 1;
108 Size += M->Obj.size() + 1;
109 }
110 return Size;
111}
112
Rui Ueyamaf7c9c322016-11-11 23:41:13 +0000113uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
114 if (SectionContribs.empty())
115 return 0;
116 return sizeof(enum PdbRaw_DbiSecContribVer) +
117 sizeof(SectionContribs[0]) * SectionContribs.size();
Rui Ueyamaa8a68a92016-11-12 00:23:32 +0000118}
Rui Ueyamaf7c9c322016-11-11 23:41:13 +0000119
Rui Ueyamaddc79222016-10-31 17:38:56 +0000120uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
121 if (SectionMap.empty())
122 return 0;
123 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
124}
125
Zachary Turnerd218c262016-07-22 15:46:37 +0000126uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
Zachary Turnerd218c262016-07-22 15:46:37 +0000127 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 Size;
138}
139
140uint32_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
Rui Ueyama77be2402016-10-29 00:56:44 +0000148uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
149 return DbgStreams.size() * sizeof(uint16_t);
150}
151
Zachary Turnerd218c262016-07-22 15:46:37 +0000152Error DbiStreamBuilder::generateModiSubstream() {
153 uint32_t Size = calculateModiSubstreamSize();
154 auto Data = Allocator.Allocate<uint8_t>(Size);
155
Zachary Turnerd66889c2016-07-28 19:12:28 +0000156 ModInfoBuffer = MutableByteStream(MutableArrayRef<uint8_t>(Data, Size));
Zachary Turnerd218c262016-07-22 15:46:37 +0000157
158 StreamWriter ModiWriter(ModInfoBuffer);
159 for (const auto &M : ModuleInfoList) {
Zachary Turnerb383d622016-07-22 15:46:46 +0000160 ModuleInfoHeader Layout = {};
161 Layout.ModDiStream = kInvalidStreamIndex;
Zachary Turnerd218c262016-07-22 15:46:37 +0000162 Layout.NumFiles = M->SourceFiles.size();
163 if (auto EC = ModiWriter.writeObject(Layout))
164 return EC;
165 if (auto EC = ModiWriter.writeZeroString(M->Mod))
166 return EC;
167 if (auto EC = ModiWriter.writeZeroString(M->Obj))
168 return EC;
169 }
170 if (ModiWriter.bytesRemaining() != 0)
171 return make_error<RawError>(raw_error_code::invalid_format,
172 "Unexpected bytes in Modi Stream Data");
173 return Error::success();
174}
175
176Error 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
Zachary Turnerd66889c2016-07-28 19:12:28 +0000182 FileInfoBuffer = MutableByteStream(MutableArrayRef<uint8_t>(Data, Size));
Zachary Turnerd218c262016-07-22 15:46:37 +0000183
Zachary Turnerd66889c2016-07-28 19:12:28 +0000184 WritableStreamRef MetadataBuffer =
185 WritableStreamRef(FileInfoBuffer).keep_front(NamesOffset);
Zachary Turnerd218c262016-07-22 15:46:37 +0000186 StreamWriter MetadataWriter(MetadataBuffer);
187
Rui Ueyama50701312016-11-16 00:38:33 +0000188 uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModuleInfos.size());
189 uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
Zachary Turnerd218c262016-07-22 15:46:37 +0000190 if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
191 return EC;
192 if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
193 return EC;
194 for (uint16_t I = 0; I < ModiCount; ++I) {
195 if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
196 return EC;
197 }
198 for (const auto MI : ModuleInfoList) {
199 FileCount = static_cast<uint16_t>(MI->SourceFiles.size());
200 if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
201 return EC;
202 }
203
204 // Before writing the FileNameOffsets array, write the NamesBuffer array.
205 // A side effect of this is that this will actually compute the various
206 // file name offsets, so we can then go back and write the FileNameOffsets
207 // array to the other substream.
Zachary Turnerd66889c2016-07-28 19:12:28 +0000208 NamesBuffer = WritableStreamRef(FileInfoBuffer).drop_front(NamesOffset);
Zachary Turnerd218c262016-07-22 15:46:37 +0000209 StreamWriter NameBufferWriter(NamesBuffer);
210 for (auto &Name : SourceFileNames) {
211 Name.second = NameBufferWriter.getOffset();
212 if (auto EC = NameBufferWriter.writeZeroString(Name.getKey()))
213 return EC;
214 }
215
216 for (const auto MI : ModuleInfoList) {
217 for (StringRef Name : MI->SourceFiles) {
218 auto Result = SourceFileNames.find(Name);
219 if (Result == SourceFileNames.end())
220 return make_error<RawError>(raw_error_code::no_entry,
221 "The source file was not found.");
222 if (auto EC = MetadataWriter.writeInteger(Result->second))
223 return EC;
224 }
225 }
226
227 if (NameBufferWriter.bytesRemaining() > 0)
228 return make_error<RawError>(raw_error_code::invalid_format,
229 "The names buffer contained unexpected data.");
230
231 if (MetadataWriter.bytesRemaining() > 0)
232 return make_error<RawError>(
233 raw_error_code::invalid_format,
234 "The metadata buffer contained unexpected data.");
235
236 return Error::success();
Zachary Turnerfaa554b2016-07-15 22:16:56 +0000237}
238
Zachary Turnerd66889c2016-07-28 19:12:28 +0000239Error DbiStreamBuilder::finalize() {
240 if (Header)
241 return Error::success();
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000242
Zachary Turnerd66889c2016-07-28 19:12:28 +0000243 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
Zachary Turnerd218c262016-07-22 15:46:37 +0000244
245 if (auto EC = generateModiSubstream())
Zachary Turnere98137c2016-07-28 19:18:02 +0000246 return EC;
Zachary Turnerd218c262016-07-22 15:46:37 +0000247 if (auto EC = generateFileInfoSubstream())
Zachary Turnere98137c2016-07-28 19:18:02 +0000248 return EC;
Zachary Turnerd218c262016-07-22 15:46:37 +0000249
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000250 H->VersionHeader = *VerHeader;
251 H->VersionSignature = -1;
252 H->Age = Age;
253 H->BuildNumber = BuildNumber;
254 H->Flags = Flags;
255 H->PdbDllRbld = PdbDllRbld;
256 H->PdbDllVersion = PdbDllVersion;
257 H->MachineType = static_cast<uint16_t>(MachineType);
258
259 H->ECSubstreamSize = 0;
Zachary Turnerd218c262016-07-22 15:46:37 +0000260 H->FileInfoSize = FileInfoBuffer.getLength();
261 H->ModiSubstreamSize = ModInfoBuffer.getLength();
Rui Ueyamaf9904042016-10-11 19:43:12 +0000262 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
Rui Ueyamaf7c9c322016-11-11 23:41:13 +0000263 H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
Rui Ueyamaddc79222016-10-31 17:38:56 +0000264 H->SectionMapSize = calculateSectionMapStreamSize();
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000265 H->TypeServerSize = 0;
Zachary Turnerb383d622016-07-22 15:46:46 +0000266 H->SymRecordStreamIndex = kInvalidStreamIndex;
267 H->PublicSymbolStreamIndex = kInvalidStreamIndex;
268 H->MFCTypeServerIndex = kInvalidStreamIndex;
269 H->GlobalSymbolStreamIndex = kInvalidStreamIndex;
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000270
Zachary Turnerd66889c2016-07-28 19:12:28 +0000271 Header = H;
272 return Error::success();
273}
274
Zachary Turner620961d2016-09-14 23:00:02 +0000275Error DbiStreamBuilder::finalizeMsfLayout() {
276 uint32_t Length = calculateSerializedLength();
277 if (auto EC = Msf.setStreamSize(StreamDBI, Length))
278 return EC;
279 return Error::success();
280}
281
Rui Ueyamaddc79222016-10-31 17:38:56 +0000282static 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
Rui Ueyamaf7c9c322016-11-11 23:41:13 +0000301// A utility function to create Section Contributions
302// for a given input sections.
303std::vector<SectionContrib> DbiStreamBuilder::createSectionContribs(
304 ArrayRef<object::coff_section> SecHdrs) {
305 std::vector<SectionContrib> Ret;
306
307 // Create a SectionContrib for each input section.
308 for (auto &Sec : SecHdrs) {
309 Ret.emplace_back();
310 auto &Entry = Ret.back();
311 memset(&Entry, 0, sizeof(Entry));
312
313 Entry.Off = Sec.PointerToRawData;
314 Entry.Size = Sec.SizeOfRawData;
315 Entry.Characteristics = Sec.Characteristics;
316 }
317 return Ret;
318}
319
Rui Ueyamaddc79222016-10-31 17:38:56 +0000320// A utility function to create a Section Map for a given list of COFF sections.
321//
322// A Section Map seem to be a copy of a COFF section list in other format.
323// I don't know why a PDB file contains both a COFF section header and
324// a Section Map, but it seems it must be present in a PDB.
325std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
326 ArrayRef<llvm::object::coff_section> SecHdrs) {
327 std::vector<SecMapEntry> Ret;
328 int Idx = 0;
329
330 auto Add = [&]() -> SecMapEntry & {
331 Ret.emplace_back();
332 auto &Entry = Ret.back();
333 memset(&Entry, 0, sizeof(Entry));
334
335 Entry.Frame = Idx + 1;
336
337 // We don't know the meaning of these fields yet.
338 Entry.SecName = UINT16_MAX;
339 Entry.ClassName = UINT16_MAX;
340
341 return Entry;
342 };
343
344 for (auto &Hdr : SecHdrs) {
345 auto &Entry = Add();
346 Entry.Flags = toSecMapFlags(Hdr.Characteristics);
347 Entry.SecByteLength = Hdr.VirtualSize;
348 ++Idx;
349 }
350
351 // The last entry is for absolute symbols.
352 auto &Entry = Add();
353 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
354 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
355 Entry.SecByteLength = UINT32_MAX;
356
357 return Ret;
358}
359
Zachary Turnerd66889c2016-07-28 19:12:28 +0000360Expected<std::unique_ptr<DbiStream>>
Justin Bognerf9fb2ab2016-11-03 18:28:04 +0000361DbiStreamBuilder::build(PDBFile &File) {
Zachary Turnerd66889c2016-07-28 19:12:28 +0000362 if (!VerHeader.hasValue())
363 return make_error<RawError>(raw_error_code::unspecified,
364 "Missing DBI Stream Version");
365 if (auto EC = finalize())
366 return std::move(EC);
367
Justin Bognerf9fb2ab2016-11-03 18:28:04 +0000368 auto StreamData = MappedBlockStream::createIndexedStream(
369 File.getMsfLayout(), File.getMsfBuffer(), StreamDBI);
Zachary Turnerd66889c2016-07-28 19:12:28 +0000370 auto Dbi = llvm::make_unique<DbiStream>(File, std::move(StreamData));
371 Dbi->Header = Header;
372 Dbi->FileInfoSubstream = ReadableStreamRef(FileInfoBuffer);
373 Dbi->ModInfoSubstream = ReadableStreamRef(ModInfoBuffer);
Zachary Turnerd218c262016-07-22 15:46:37 +0000374 if (auto EC = Dbi->initializeModInfoArray())
375 return std::move(EC);
376 if (auto EC = Dbi->initializeFileInfo())
377 return std::move(EC);
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000378 return std::move(Dbi);
379}
Zachary Turnerd66889c2016-07-28 19:12:28 +0000380
Zachary Turnera3225b02016-07-29 20:56:36 +0000381Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
Rui Ueyamad1d8c8312016-08-03 23:43:23 +0000382 const msf::WritableStream &Buffer) {
383 if (auto EC = finalize())
384 return EC;
385
Zachary Turnerd66889c2016-07-28 19:12:28 +0000386 auto InfoS =
387 WritableMappedBlockStream::createIndexedStream(Layout, Buffer, StreamDBI);
388
389 StreamWriter Writer(*InfoS);
390 if (auto EC = Writer.writeObject(*Header))
391 return EC;
392
393 if (auto EC = Writer.writeStreamRef(ModInfoBuffer))
394 return EC;
Rui Ueyamaddc79222016-10-31 17:38:56 +0000395
Rui Ueyamaf7c9c322016-11-11 23:41:13 +0000396 if (!SectionContribs.empty()) {
397 if (auto EC = Writer.writeEnum(DbiSecContribVer60))
398 return EC;
399 if (auto EC = Writer.writeArray(SectionContribs))
400 return EC;
401 }
402
Rui Ueyamaddc79222016-10-31 17:38:56 +0000403 if (!SectionMap.empty()) {
404 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
405 SecMapHeader SMHeader = {Size, Size};
406 if (auto EC = Writer.writeObject(SMHeader))
407 return EC;
408 if (auto EC = Writer.writeArray(SectionMap))
409 return EC;
410 }
411
Zachary Turnerd66889c2016-07-28 19:12:28 +0000412 if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
413 return EC;
Rui Ueyamaddc79222016-10-31 17:38:56 +0000414
Rui Ueyamaf9904042016-10-11 19:43:12 +0000415 for (auto &Stream : DbgStreams)
416 if (auto EC = Writer.writeInteger(Stream.StreamNumber))
417 return EC;
418
419 for (auto &Stream : DbgStreams) {
420 if (Stream.StreamNumber == kInvalidStreamIndex)
421 continue;
422 auto WritableStream = WritableMappedBlockStream::createIndexedStream(
423 Layout, Buffer, Stream.StreamNumber);
424 StreamWriter DbgStreamWriter(*WritableStream);
425 if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
426 return EC;
427 }
Zachary Turnerd66889c2016-07-28 19:12:28 +0000428
429 if (Writer.bytesRemaining() > 0)
430 return make_error<RawError>(raw_error_code::invalid_format,
431 "Unexpected bytes found in DBI Stream");
432 return Error::success();
433}