blob: 4ee28c7d81185c15983610cd772d84877fdcc2da [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 Ueyamaddc79222016-10-31 17:38:56 +000049void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) {
50 SectionMap = SecMap;
51}
52
Rui Ueyamaf9904042016-10-11 19:43:12 +000053Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type,
54 ArrayRef<uint8_t> Data) {
55 if (DbgStreams[(int)Type].StreamNumber)
56 return make_error<RawError>(raw_error_code::duplicate_entry,
57 "The specified stream type already exists");
58 auto ExpectedIndex = Msf.addStream(Data.size());
59 if (!ExpectedIndex)
60 return ExpectedIndex.takeError();
61 uint32_t Index = std::move(*ExpectedIndex);
62 DbgStreams[(int)Type].Data = Data;
63 DbgStreams[(int)Type].StreamNumber = Index;
64 return Error::success();
65}
66
Zachary Turnerfaa554b2016-07-15 22:16:56 +000067uint32_t DbiStreamBuilder::calculateSerializedLength() const {
68 // For now we only support serializing the header.
Zachary Turnerb383d622016-07-22 15:46:46 +000069 return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
Rui Ueyamaddc79222016-10-31 17:38:56 +000070 calculateModiSubstreamSize() + calculateSectionMapStreamSize() +
71 calculateDbgStreamsSize();
Zachary Turnerd218c262016-07-22 15:46:37 +000072}
73
74Error DbiStreamBuilder::addModuleInfo(StringRef ObjFile, StringRef Module) {
75 auto Entry = llvm::make_unique<ModuleInfo>();
76 ModuleInfo *M = Entry.get();
77 Entry->Mod = Module;
78 Entry->Obj = ObjFile;
79 auto Result = ModuleInfos.insert(std::make_pair(Module, std::move(Entry)));
80 if (!Result.second)
81 return make_error<RawError>(raw_error_code::duplicate_entry,
82 "The specified module already exists");
83 ModuleInfoList.push_back(M);
84 return Error::success();
85}
86
87Error DbiStreamBuilder::addModuleSourceFile(StringRef Module, StringRef File) {
88 auto ModIter = ModuleInfos.find(Module);
89 if (ModIter == ModuleInfos.end())
90 return make_error<RawError>(raw_error_code::no_entry,
91 "The specified module was not found");
92 uint32_t Index = SourceFileNames.size();
93 SourceFileNames.insert(std::make_pair(File, Index));
94 auto &ModEntry = *ModIter;
95 ModEntry.second->SourceFiles.push_back(File);
96 return Error::success();
97}
98
99uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
100 uint32_t Size = 0;
101 for (const auto &M : ModuleInfoList) {
Zachary Turnerb383d622016-07-22 15:46:46 +0000102 Size += sizeof(ModuleInfoHeader);
Zachary Turnerd218c262016-07-22 15:46:37 +0000103 Size += M->Mod.size() + 1;
104 Size += M->Obj.size() + 1;
105 }
106 return Size;
107}
108
Rui Ueyamaddc79222016-10-31 17:38:56 +0000109uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
110 if (SectionMap.empty())
111 return 0;
112 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
113}
114
Zachary Turnerd218c262016-07-22 15:46:37 +0000115uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
Zachary Turnerd218c262016-07-22 15:46:37 +0000116 uint32_t Size = 0;
117 Size += sizeof(ulittle16_t); // NumModules
118 Size += sizeof(ulittle16_t); // NumSourceFiles
119 Size += ModuleInfoList.size() * sizeof(ulittle16_t); // ModIndices
120 Size += ModuleInfoList.size() * sizeof(ulittle16_t); // ModFileCounts
121 uint32_t NumFileInfos = 0;
122 for (const auto &M : ModuleInfoList)
123 NumFileInfos += M->SourceFiles.size();
124 Size += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
125 Size += calculateNamesBufferSize();
126 return Size;
127}
128
129uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
130 uint32_t Size = 0;
131 for (const auto &F : SourceFileNames) {
132 Size += F.getKeyLength() + 1; // Names[I];
133 }
134 return Size;
135}
136
Rui Ueyama77be2402016-10-29 00:56:44 +0000137uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
138 return DbgStreams.size() * sizeof(uint16_t);
139}
140
Zachary Turnerd218c262016-07-22 15:46:37 +0000141Error DbiStreamBuilder::generateModiSubstream() {
142 uint32_t Size = calculateModiSubstreamSize();
143 auto Data = Allocator.Allocate<uint8_t>(Size);
144
Zachary Turnerd66889c2016-07-28 19:12:28 +0000145 ModInfoBuffer = MutableByteStream(MutableArrayRef<uint8_t>(Data, Size));
Zachary Turnerd218c262016-07-22 15:46:37 +0000146
147 StreamWriter ModiWriter(ModInfoBuffer);
148 for (const auto &M : ModuleInfoList) {
Zachary Turnerb383d622016-07-22 15:46:46 +0000149 ModuleInfoHeader Layout = {};
150 Layout.ModDiStream = kInvalidStreamIndex;
Zachary Turnerd218c262016-07-22 15:46:37 +0000151 Layout.NumFiles = M->SourceFiles.size();
152 if (auto EC = ModiWriter.writeObject(Layout))
153 return EC;
154 if (auto EC = ModiWriter.writeZeroString(M->Mod))
155 return EC;
156 if (auto EC = ModiWriter.writeZeroString(M->Obj))
157 return EC;
158 }
159 if (ModiWriter.bytesRemaining() != 0)
160 return make_error<RawError>(raw_error_code::invalid_format,
161 "Unexpected bytes in Modi Stream Data");
162 return Error::success();
163}
164
165Error DbiStreamBuilder::generateFileInfoSubstream() {
166 uint32_t Size = calculateFileInfoSubstreamSize();
167 uint32_t NameSize = calculateNamesBufferSize();
168 auto Data = Allocator.Allocate<uint8_t>(Size);
169 uint32_t NamesOffset = Size - NameSize;
170
Zachary Turnerd66889c2016-07-28 19:12:28 +0000171 FileInfoBuffer = MutableByteStream(MutableArrayRef<uint8_t>(Data, Size));
Zachary Turnerd218c262016-07-22 15:46:37 +0000172
Zachary Turnerd66889c2016-07-28 19:12:28 +0000173 WritableStreamRef MetadataBuffer =
174 WritableStreamRef(FileInfoBuffer).keep_front(NamesOffset);
Zachary Turnerd218c262016-07-22 15:46:37 +0000175 StreamWriter MetadataWriter(MetadataBuffer);
176
177 uint16_t ModiCount = std::min<uint16_t>(UINT16_MAX, ModuleInfos.size());
178 uint16_t FileCount = std::min<uint16_t>(UINT16_MAX, SourceFileNames.size());
179 if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
180 return EC;
181 if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
182 return EC;
183 for (uint16_t I = 0; I < ModiCount; ++I) {
184 if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
185 return EC;
186 }
187 for (const auto MI : ModuleInfoList) {
188 FileCount = static_cast<uint16_t>(MI->SourceFiles.size());
189 if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
190 return EC;
191 }
192
193 // Before writing the FileNameOffsets array, write the NamesBuffer array.
194 // A side effect of this is that this will actually compute the various
195 // file name offsets, so we can then go back and write the FileNameOffsets
196 // array to the other substream.
Zachary Turnerd66889c2016-07-28 19:12:28 +0000197 NamesBuffer = WritableStreamRef(FileInfoBuffer).drop_front(NamesOffset);
Zachary Turnerd218c262016-07-22 15:46:37 +0000198 StreamWriter NameBufferWriter(NamesBuffer);
199 for (auto &Name : SourceFileNames) {
200 Name.second = NameBufferWriter.getOffset();
201 if (auto EC = NameBufferWriter.writeZeroString(Name.getKey()))
202 return EC;
203 }
204
205 for (const auto MI : ModuleInfoList) {
206 for (StringRef Name : MI->SourceFiles) {
207 auto Result = SourceFileNames.find(Name);
208 if (Result == SourceFileNames.end())
209 return make_error<RawError>(raw_error_code::no_entry,
210 "The source file was not found.");
211 if (auto EC = MetadataWriter.writeInteger(Result->second))
212 return EC;
213 }
214 }
215
216 if (NameBufferWriter.bytesRemaining() > 0)
217 return make_error<RawError>(raw_error_code::invalid_format,
218 "The names buffer contained unexpected data.");
219
220 if (MetadataWriter.bytesRemaining() > 0)
221 return make_error<RawError>(
222 raw_error_code::invalid_format,
223 "The metadata buffer contained unexpected data.");
224
225 return Error::success();
Zachary Turnerfaa554b2016-07-15 22:16:56 +0000226}
227
Zachary Turnerd66889c2016-07-28 19:12:28 +0000228Error DbiStreamBuilder::finalize() {
229 if (Header)
230 return Error::success();
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000231
Zachary Turnerd66889c2016-07-28 19:12:28 +0000232 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
Zachary Turnerd218c262016-07-22 15:46:37 +0000233
234 if (auto EC = generateModiSubstream())
Zachary Turnere98137c2016-07-28 19:18:02 +0000235 return EC;
Zachary Turnerd218c262016-07-22 15:46:37 +0000236 if (auto EC = generateFileInfoSubstream())
Zachary Turnere98137c2016-07-28 19:18:02 +0000237 return EC;
Zachary Turnerd218c262016-07-22 15:46:37 +0000238
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000239 H->VersionHeader = *VerHeader;
240 H->VersionSignature = -1;
241 H->Age = Age;
242 H->BuildNumber = BuildNumber;
243 H->Flags = Flags;
244 H->PdbDllRbld = PdbDllRbld;
245 H->PdbDllVersion = PdbDllVersion;
246 H->MachineType = static_cast<uint16_t>(MachineType);
247
248 H->ECSubstreamSize = 0;
Zachary Turnerd218c262016-07-22 15:46:37 +0000249 H->FileInfoSize = FileInfoBuffer.getLength();
250 H->ModiSubstreamSize = ModInfoBuffer.getLength();
Rui Ueyamaf9904042016-10-11 19:43:12 +0000251 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000252 H->SecContrSubstreamSize = 0;
Rui Ueyamaddc79222016-10-31 17:38:56 +0000253 H->SectionMapSize = calculateSectionMapStreamSize();
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000254 H->TypeServerSize = 0;
Zachary Turnerb383d622016-07-22 15:46:46 +0000255 H->SymRecordStreamIndex = kInvalidStreamIndex;
256 H->PublicSymbolStreamIndex = kInvalidStreamIndex;
257 H->MFCTypeServerIndex = kInvalidStreamIndex;
258 H->GlobalSymbolStreamIndex = kInvalidStreamIndex;
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000259
Zachary Turnerd66889c2016-07-28 19:12:28 +0000260 Header = H;
261 return Error::success();
262}
263
Zachary Turner620961d2016-09-14 23:00:02 +0000264Error DbiStreamBuilder::finalizeMsfLayout() {
265 uint32_t Length = calculateSerializedLength();
266 if (auto EC = Msf.setStreamSize(StreamDBI, Length))
267 return EC;
268 return Error::success();
269}
270
Rui Ueyamaddc79222016-10-31 17:38:56 +0000271static uint16_t toSecMapFlags(uint32_t Flags) {
272 uint16_t Ret = 0;
273 if (Flags & COFF::IMAGE_SCN_MEM_READ)
274 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
275 if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
276 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
277 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
278 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
279 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
280 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
281 if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
282 Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
283
284 // This seems always 1.
285 Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
286
287 return Ret;
288}
289
290// A utility function to create a Section Map for a given list of COFF sections.
291//
292// A Section Map seem to be a copy of a COFF section list in other format.
293// I don't know why a PDB file contains both a COFF section header and
294// a Section Map, but it seems it must be present in a PDB.
295std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
296 ArrayRef<llvm::object::coff_section> SecHdrs) {
297 std::vector<SecMapEntry> Ret;
298 int Idx = 0;
299
300 auto Add = [&]() -> SecMapEntry & {
301 Ret.emplace_back();
302 auto &Entry = Ret.back();
303 memset(&Entry, 0, sizeof(Entry));
304
305 Entry.Frame = Idx + 1;
306
307 // We don't know the meaning of these fields yet.
308 Entry.SecName = UINT16_MAX;
309 Entry.ClassName = UINT16_MAX;
310
311 return Entry;
312 };
313
314 for (auto &Hdr : SecHdrs) {
315 auto &Entry = Add();
316 Entry.Flags = toSecMapFlags(Hdr.Characteristics);
317 Entry.SecByteLength = Hdr.VirtualSize;
318 ++Idx;
319 }
320
321 // The last entry is for absolute symbols.
322 auto &Entry = Add();
323 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
324 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
325 Entry.SecByteLength = UINT32_MAX;
326
327 return Ret;
328}
329
Zachary Turnerd66889c2016-07-28 19:12:28 +0000330Expected<std::unique_ptr<DbiStream>>
331DbiStreamBuilder::build(PDBFile &File, const msf::WritableStream &Buffer) {
332 if (!VerHeader.hasValue())
333 return make_error<RawError>(raw_error_code::unspecified,
334 "Missing DBI Stream Version");
335 if (auto EC = finalize())
336 return std::move(EC);
337
338 auto StreamData = MappedBlockStream::createIndexedStream(File.getMsfLayout(),
339 Buffer, StreamDBI);
340 auto Dbi = llvm::make_unique<DbiStream>(File, std::move(StreamData));
341 Dbi->Header = Header;
342 Dbi->FileInfoSubstream = ReadableStreamRef(FileInfoBuffer);
343 Dbi->ModInfoSubstream = ReadableStreamRef(ModInfoBuffer);
Zachary Turnerd218c262016-07-22 15:46:37 +0000344 if (auto EC = Dbi->initializeModInfoArray())
345 return std::move(EC);
346 if (auto EC = Dbi->initializeFileInfo())
347 return std::move(EC);
Zachary Turnerdbeaea72016-07-11 21:45:26 +0000348 return std::move(Dbi);
349}
Zachary Turnerd66889c2016-07-28 19:12:28 +0000350
Zachary Turnera3225b02016-07-29 20:56:36 +0000351Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
Rui Ueyamad1d8c8312016-08-03 23:43:23 +0000352 const msf::WritableStream &Buffer) {
353 if (auto EC = finalize())
354 return EC;
355
Zachary Turnerd66889c2016-07-28 19:12:28 +0000356 auto InfoS =
357 WritableMappedBlockStream::createIndexedStream(Layout, Buffer, StreamDBI);
358
359 StreamWriter Writer(*InfoS);
360 if (auto EC = Writer.writeObject(*Header))
361 return EC;
362
363 if (auto EC = Writer.writeStreamRef(ModInfoBuffer))
364 return EC;
Rui Ueyamaddc79222016-10-31 17:38:56 +0000365
366 if (!SectionMap.empty()) {
367 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
368 SecMapHeader SMHeader = {Size, Size};
369 if (auto EC = Writer.writeObject(SMHeader))
370 return EC;
371 if (auto EC = Writer.writeArray(SectionMap))
372 return EC;
373 }
374
Zachary Turnerd66889c2016-07-28 19:12:28 +0000375 if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
376 return EC;
Rui Ueyamaddc79222016-10-31 17:38:56 +0000377
Rui Ueyamaf9904042016-10-11 19:43:12 +0000378 for (auto &Stream : DbgStreams)
379 if (auto EC = Writer.writeInteger(Stream.StreamNumber))
380 return EC;
381
382 for (auto &Stream : DbgStreams) {
383 if (Stream.StreamNumber == kInvalidStreamIndex)
384 continue;
385 auto WritableStream = WritableMappedBlockStream::createIndexedStream(
386 Layout, Buffer, Stream.StreamNumber);
387 StreamWriter DbgStreamWriter(*WritableStream);
388 if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
389 return EC;
390 }
Zachary Turnerd66889c2016-07-28 19:12:28 +0000391
392 if (Writer.bytesRemaining() > 0)
393 return make_error<RawError>(raw_error_code::invalid_format,
394 "Unexpected bytes found in DBI Stream");
395 return Error::success();
396}