1 //===- DbiStreamBuilder.cpp - PDB Dbi Stream Creation -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/BinaryFormat/COFF.h"
14 #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
15 #include "llvm/DebugInfo/MSF/MSFBuilder.h"
16 #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
17 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
18 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
19 #include "llvm/DebugInfo/PDB/Native/RawError.h"
20 #include "llvm/Object/COFF.h"
21 #include "llvm/Support/BinaryStreamWriter.h"
24 using namespace llvm::codeview;
25 using namespace llvm::msf;
26 using namespace llvm::pdb;
28 DbiStreamBuilder::DbiStreamBuilder(msf::MSFBuilder &Msf)
29 : Msf(Msf), Allocator(Msf.getAllocator()), Age(1), BuildNumber(0),
30 PdbDllVersion(0), PdbDllRbld(0), Flags(0), MachineType(PDB_Machine::x86),
33 DbiStreamBuilder::~DbiStreamBuilder() {}
35 void DbiStreamBuilder::setVersionHeader(PdbRaw_DbiVer V) { VerHeader = V; }
37 void DbiStreamBuilder::setAge(uint32_t A) { Age = A; }
39 void DbiStreamBuilder::setBuildNumber(uint16_t B) { BuildNumber = B; }
41 void DbiStreamBuilder::setBuildNumber(uint8_t Major, uint8_t Minor) {
42 BuildNumber = (uint16_t(Major) << DbiBuildNo::BuildMajorShift) &
43 DbiBuildNo::BuildMajorMask;
44 BuildNumber |= (uint16_t(Minor) << DbiBuildNo::BuildMinorShift) &
45 DbiBuildNo::BuildMinorMask;
46 BuildNumber |= DbiBuildNo::NewVersionFormatMask;
49 void DbiStreamBuilder::setPdbDllVersion(uint16_t V) { PdbDllVersion = V; }
51 void DbiStreamBuilder::setPdbDllRbld(uint16_t R) { PdbDllRbld = R; }
53 void DbiStreamBuilder::setFlags(uint16_t F) { Flags = F; }
55 void DbiStreamBuilder::setMachineType(PDB_Machine M) { MachineType = M; }
57 void DbiStreamBuilder::setMachineType(COFF::MachineTypes M) {
58 // These enums are mirrors of each other, so we can just cast the value.
59 MachineType = static_cast<pdb::PDB_Machine>(static_cast<unsigned>(M));
62 void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) {
66 void DbiStreamBuilder::setGlobalsStreamIndex(uint32_t Index) {
67 GlobalsStreamIndex = Index;
70 void DbiStreamBuilder::setSymbolRecordStreamIndex(uint32_t Index) {
71 SymRecordStreamIndex = Index;
74 void DbiStreamBuilder::setPublicsStreamIndex(uint32_t Index) {
75 PublicsStreamIndex = Index;
78 void DbiStreamBuilder::addNewFpoData(const codeview::FrameData &FD) {
79 if (!NewFpoData.hasValue())
80 NewFpoData.emplace(false);
82 NewFpoData->addFrameData(FD);
85 void DbiStreamBuilder::addOldFpoData(const object::FpoData &FD) {
86 OldFpoData.push_back(FD);
89 Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type,
90 ArrayRef<uint8_t> Data) {
91 assert(Type != DbgHeaderType::NewFPO &&
92 "NewFPO data should be written via addFrameData()!");
94 DbgStreams[(int)Type].emplace();
95 DbgStreams[(int)Type]->Size = Data.size();
96 DbgStreams[(int)Type]->WriteFn = [Data](BinaryStreamWriter &Writer) {
97 return Writer.writeArray(Data);
99 return Error::success();
102 uint32_t DbiStreamBuilder::addECName(StringRef Name) {
103 return ECNamesBuilder.insert(Name);
106 uint32_t DbiStreamBuilder::calculateSerializedLength() const {
107 // For now we only support serializing the header.
108 return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
109 calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
110 calculateSectionMapStreamSize() + calculateDbgStreamsSize() +
111 ECNamesBuilder.calculateSerializedSize();
114 Expected<DbiModuleDescriptorBuilder &>
115 DbiStreamBuilder::addModuleInfo(StringRef ModuleName) {
116 uint32_t Index = ModiList.size();
118 llvm::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf));
119 return *ModiList.back();
122 Error DbiStreamBuilder::addModuleSourceFile(DbiModuleDescriptorBuilder &Module,
124 uint32_t Index = SourceFileNames.size();
125 SourceFileNames.insert(std::make_pair(File, Index));
126 Module.addSourceFile(File);
127 return Error::success();
130 Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) {
131 auto NameIter = SourceFileNames.find(File);
132 if (NameIter == SourceFileNames.end())
133 return make_error<RawError>(raw_error_code::no_entry,
134 "The specified source file was not found");
135 return NameIter->getValue();
138 uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
140 for (const auto &M : ModiList)
141 Size += M->calculateSerializedLength();
145 uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
146 if (SectionContribs.empty())
148 return sizeof(enum PdbRaw_DbiSecContribVer) +
149 sizeof(SectionContribs[0]) * SectionContribs.size();
152 uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
153 if (SectionMap.empty())
155 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
158 uint32_t DbiStreamBuilder::calculateNamesOffset() const {
160 Offset += sizeof(ulittle16_t); // NumModules
161 Offset += sizeof(ulittle16_t); // NumSourceFiles
162 Offset += ModiList.size() * sizeof(ulittle16_t); // ModIndices
163 Offset += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts
164 uint32_t NumFileInfos = 0;
165 for (const auto &M : ModiList)
166 NumFileInfos += M->source_files().size();
167 Offset += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
171 uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
172 uint32_t Size = calculateNamesOffset();
173 Size += calculateNamesBufferSize();
174 return alignTo(Size, sizeof(uint32_t));
177 uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
179 for (const auto &F : SourceFileNames) {
180 Size += F.getKeyLength() + 1; // Names[I];
185 uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
186 return DbgStreams.size() * sizeof(uint16_t);
189 Error DbiStreamBuilder::generateFileInfoSubstream() {
190 uint32_t Size = calculateFileInfoSubstreamSize();
191 auto Data = Allocator.Allocate<uint8_t>(Size);
192 uint32_t NamesOffset = calculateNamesOffset();
194 FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size),
195 llvm::support::little);
197 WritableBinaryStreamRef MetadataBuffer =
198 WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
199 BinaryStreamWriter MetadataWriter(MetadataBuffer);
201 uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModiList.size());
202 uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
203 if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
205 if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
207 for (uint16_t I = 0; I < ModiCount; ++I) {
208 if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
211 for (const auto &MI : ModiList) {
212 FileCount = static_cast<uint16_t>(MI->source_files().size());
213 if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
217 // Before writing the FileNameOffsets array, write the NamesBuffer array.
218 // A side effect of this is that this will actually compute the various
219 // file name offsets, so we can then go back and write the FileNameOffsets
220 // array to the other substream.
221 NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset);
222 BinaryStreamWriter NameBufferWriter(NamesBuffer);
223 for (auto &Name : SourceFileNames) {
224 Name.second = NameBufferWriter.getOffset();
225 if (auto EC = NameBufferWriter.writeCString(Name.getKey()))
229 for (const auto &MI : ModiList) {
230 for (StringRef Name : MI->source_files()) {
231 auto Result = SourceFileNames.find(Name);
232 if (Result == SourceFileNames.end())
233 return make_error<RawError>(raw_error_code::no_entry,
234 "The source file was not found.");
235 if (auto EC = MetadataWriter.writeInteger(Result->second))
240 if (auto EC = NameBufferWriter.padToAlignment(sizeof(uint32_t)))
243 if (NameBufferWriter.bytesRemaining() > 0)
244 return make_error<RawError>(raw_error_code::invalid_format,
245 "The names buffer contained unexpected data.");
247 if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
248 return make_error<RawError>(
249 raw_error_code::invalid_format,
250 "The metadata buffer contained unexpected data.");
252 return Error::success();
255 Error DbiStreamBuilder::finalize() {
257 return Error::success();
259 for (auto &MI : ModiList)
262 if (auto EC = generateFileInfoSubstream())
265 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
266 ::memset(H, 0, sizeof(DbiStreamHeader));
267 H->VersionHeader = *VerHeader;
268 H->VersionSignature = -1;
270 H->BuildNumber = BuildNumber;
272 H->PdbDllRbld = PdbDllRbld;
273 H->PdbDllVersion = PdbDllVersion;
274 H->MachineType = static_cast<uint16_t>(MachineType);
276 H->ECSubstreamSize = ECNamesBuilder.calculateSerializedSize();
277 H->FileInfoSize = FileInfoBuffer.getLength();
278 H->ModiSubstreamSize = calculateModiSubstreamSize();
279 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
280 H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
281 H->SectionMapSize = calculateSectionMapStreamSize();
282 H->TypeServerSize = 0;
283 H->SymRecordStreamIndex = SymRecordStreamIndex;
284 H->PublicSymbolStreamIndex = PublicsStreamIndex;
285 H->MFCTypeServerIndex = 0; // Not sure what this is, but link.exe writes 0.
286 H->GlobalSymbolStreamIndex = GlobalsStreamIndex;
289 return Error::success();
292 Error DbiStreamBuilder::finalizeMsfLayout() {
293 if (NewFpoData.hasValue()) {
294 DbgStreams[(int)DbgHeaderType::NewFPO].emplace();
295 DbgStreams[(int)DbgHeaderType::NewFPO]->Size =
296 NewFpoData->calculateSerializedSize();
297 DbgStreams[(int)DbgHeaderType::NewFPO]->WriteFn =
298 [this](BinaryStreamWriter &Writer) {
299 return NewFpoData->commit(Writer);
303 if (!OldFpoData.empty()) {
304 DbgStreams[(int)DbgHeaderType::FPO].emplace();
305 DbgStreams[(int)DbgHeaderType::FPO]->Size =
306 sizeof(object::FpoData) * OldFpoData.size();
307 DbgStreams[(int)DbgHeaderType::FPO]->WriteFn =
308 [this](BinaryStreamWriter &Writer) {
309 return Writer.writeArray(makeArrayRef(OldFpoData));
313 for (auto &S : DbgStreams) {
316 auto ExpectedIndex = Msf.addStream(S->Size);
318 return ExpectedIndex.takeError();
319 S->StreamNumber = *ExpectedIndex;
322 for (auto &MI : ModiList) {
323 if (auto EC = MI->finalizeMsfLayout())
327 uint32_t Length = calculateSerializedLength();
328 if (auto EC = Msf.setStreamSize(StreamDBI, Length))
330 return Error::success();
333 static uint16_t toSecMapFlags(uint32_t Flags) {
335 if (Flags & COFF::IMAGE_SCN_MEM_READ)
336 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
337 if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
338 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
339 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
340 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
341 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
342 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
343 if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
344 Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
346 // This seems always 1.
347 Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
352 // A utility function to create a Section Map for a given list of COFF sections.
354 // A Section Map seem to be a copy of a COFF section list in other format.
355 // I don't know why a PDB file contains both a COFF section header and
356 // a Section Map, but it seems it must be present in a PDB.
357 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
358 ArrayRef<llvm::object::coff_section> SecHdrs) {
359 std::vector<SecMapEntry> Ret;
362 auto Add = [&]() -> SecMapEntry & {
364 auto &Entry = Ret.back();
365 memset(&Entry, 0, sizeof(Entry));
367 Entry.Frame = Idx + 1;
369 // We don't know the meaning of these fields yet.
370 Entry.SecName = UINT16_MAX;
371 Entry.ClassName = UINT16_MAX;
376 for (auto &Hdr : SecHdrs) {
378 Entry.Flags = toSecMapFlags(Hdr.Characteristics);
379 Entry.SecByteLength = Hdr.VirtualSize;
383 // The last entry is for absolute symbols.
385 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
386 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
387 Entry.SecByteLength = UINT32_MAX;
392 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
393 WritableBinaryStreamRef MsfBuffer) {
394 if (auto EC = finalize())
397 auto DbiS = WritableMappedBlockStream::createIndexedStream(
398 Layout, MsfBuffer, StreamDBI, Allocator);
400 BinaryStreamWriter Writer(*DbiS);
401 if (auto EC = Writer.writeObject(*Header))
404 for (auto &M : ModiList) {
405 if (auto EC = M->commit(Writer, Layout, MsfBuffer))
409 if (!SectionContribs.empty()) {
410 if (auto EC = Writer.writeEnum(DbiSecContribVer60))
412 if (auto EC = Writer.writeArray(makeArrayRef(SectionContribs)))
416 if (!SectionMap.empty()) {
417 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
418 SecMapHeader SMHeader = {Size, Size};
419 if (auto EC = Writer.writeObject(SMHeader))
421 if (auto EC = Writer.writeArray(SectionMap))
425 if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
428 if (auto EC = ECNamesBuilder.commit(Writer))
431 for (auto &Stream : DbgStreams) {
432 uint16_t StreamNumber = kInvalidStreamIndex;
433 if (Stream.hasValue())
434 StreamNumber = Stream->StreamNumber;
435 if (auto EC = Writer.writeInteger(StreamNumber))
439 for (auto &Stream : DbgStreams) {
440 if (!Stream.hasValue())
442 assert(Stream->StreamNumber != kInvalidStreamIndex);
444 auto WritableStream = WritableMappedBlockStream::createIndexedStream(
445 Layout, MsfBuffer, Stream->StreamNumber, Allocator);
446 BinaryStreamWriter DbgStreamWriter(*WritableStream);
448 if (auto EC = Stream->WriteFn(DbgStreamWriter))
452 if (Writer.bytesRemaining() > 0)
453 return make_error<RawError>(raw_error_code::invalid_format,
454 "Unexpected bytes found in DBI Stream");
455 return Error::success();