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/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"
23 using namespace llvm::codeview;
24 using namespace llvm::msf;
25 using namespace llvm::pdb;
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) {}
32 DbiStreamBuilder::~DbiStreamBuilder() {}
34 void DbiStreamBuilder::setVersionHeader(PdbRaw_DbiVer V) { VerHeader = V; }
36 void DbiStreamBuilder::setAge(uint32_t A) { Age = A; }
38 void DbiStreamBuilder::setBuildNumber(uint16_t B) { BuildNumber = B; }
40 void DbiStreamBuilder::setPdbDllVersion(uint16_t V) { PdbDllVersion = V; }
42 void DbiStreamBuilder::setPdbDllRbld(uint16_t R) { PdbDllRbld = R; }
44 void DbiStreamBuilder::setFlags(uint16_t F) { Flags = F; }
46 void DbiStreamBuilder::setMachineType(PDB_Machine M) { MachineType = M; }
48 void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) {
52 void DbiStreamBuilder::setSymbolRecordStreamIndex(uint32_t Index) {
53 SymRecordStreamIndex = Index;
56 void DbiStreamBuilder::setPublicsStreamIndex(uint32_t Index) {
57 PublicsStreamIndex = Index;
60 Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type,
61 ArrayRef<uint8_t> Data) {
62 if (DbgStreams[(int)Type].StreamNumber != kInvalidStreamIndex)
63 return make_error<RawError>(raw_error_code::duplicate_entry,
64 "The specified stream type already exists");
65 auto ExpectedIndex = Msf.addStream(Data.size());
67 return ExpectedIndex.takeError();
68 uint32_t Index = std::move(*ExpectedIndex);
69 DbgStreams[(int)Type].Data = Data;
70 DbgStreams[(int)Type].StreamNumber = Index;
71 return Error::success();
74 uint32_t DbiStreamBuilder::addECName(StringRef Name) {
75 return ECNamesBuilder.insert(Name);
78 uint32_t DbiStreamBuilder::calculateSerializedLength() const {
79 // For now we only support serializing the header.
80 return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
81 calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
82 calculateSectionMapStreamSize() + calculateDbgStreamsSize() +
83 ECNamesBuilder.calculateSerializedSize();
86 Expected<DbiModuleDescriptorBuilder &>
87 DbiStreamBuilder::addModuleInfo(StringRef ModuleName) {
88 uint32_t Index = ModiList.size();
90 llvm::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf);
92 auto Result = ModiMap.insert(std::make_pair(ModuleName, std::move(MIB)));
95 return make_error<RawError>(raw_error_code::duplicate_entry,
96 "The specified module already exists");
97 ModiList.push_back(M);
101 Error DbiStreamBuilder::addModuleSourceFile(StringRef Module, StringRef File) {
102 auto ModIter = ModiMap.find(Module);
103 if (ModIter == ModiMap.end())
104 return make_error<RawError>(raw_error_code::no_entry,
105 "The specified module was not found");
106 return addModuleSourceFile(*ModIter->second, File);
109 Error DbiStreamBuilder::addModuleSourceFile(DbiModuleDescriptorBuilder &Module,
111 uint32_t Index = SourceFileNames.size();
112 SourceFileNames.insert(std::make_pair(File, Index));
113 Module.addSourceFile(File);
114 return Error::success();
117 Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) {
118 auto NameIter = SourceFileNames.find(File);
119 if (NameIter == SourceFileNames.end())
120 return make_error<RawError>(raw_error_code::no_entry,
121 "The specified source file was not found");
122 return NameIter->getValue();
125 uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
127 for (const auto &M : ModiList)
128 Size += M->calculateSerializedLength();
132 uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
133 if (SectionContribs.empty())
135 return sizeof(enum PdbRaw_DbiSecContribVer) +
136 sizeof(SectionContribs[0]) * SectionContribs.size();
139 uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
140 if (SectionMap.empty())
142 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
145 uint32_t DbiStreamBuilder::calculateNamesOffset() const {
147 Offset += sizeof(ulittle16_t); // NumModules
148 Offset += sizeof(ulittle16_t); // NumSourceFiles
149 Offset += ModiList.size() * sizeof(ulittle16_t); // ModIndices
150 Offset += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts
151 uint32_t NumFileInfos = 0;
152 for (const auto &M : ModiList)
153 NumFileInfos += M->source_files().size();
154 Offset += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
158 uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
159 uint32_t Size = calculateNamesOffset();
160 Size += calculateNamesBufferSize();
161 return alignTo(Size, sizeof(uint32_t));
164 uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
166 for (const auto &F : SourceFileNames) {
167 Size += F.getKeyLength() + 1; // Names[I];
172 uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
173 return DbgStreams.size() * sizeof(uint16_t);
176 Error DbiStreamBuilder::generateFileInfoSubstream() {
177 uint32_t Size = calculateFileInfoSubstreamSize();
178 auto Data = Allocator.Allocate<uint8_t>(Size);
179 uint32_t NamesOffset = calculateNamesOffset();
181 FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size),
182 llvm::support::little);
184 WritableBinaryStreamRef MetadataBuffer =
185 WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
186 BinaryStreamWriter MetadataWriter(MetadataBuffer);
188 uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModiList.size());
189 uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
190 if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
192 if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
194 for (uint16_t I = 0; I < ModiCount; ++I) {
195 if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
198 for (const auto &MI : ModiList) {
199 FileCount = static_cast<uint16_t>(MI->source_files().size());
200 if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
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.
208 NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset);
209 BinaryStreamWriter NameBufferWriter(NamesBuffer);
210 for (auto &Name : SourceFileNames) {
211 Name.second = NameBufferWriter.getOffset();
212 if (auto EC = NameBufferWriter.writeCString(Name.getKey()))
216 for (const auto &MI : ModiList) {
217 for (StringRef Name : MI->source_files()) {
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))
227 if (auto EC = NameBufferWriter.padToAlignment(sizeof(uint32_t)))
230 if (NameBufferWriter.bytesRemaining() > 0)
231 return make_error<RawError>(raw_error_code::invalid_format,
232 "The names buffer contained unexpected data.");
234 if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
235 return make_error<RawError>(
236 raw_error_code::invalid_format,
237 "The metadata buffer contained unexpected data.");
239 return Error::success();
242 Error DbiStreamBuilder::finalize() {
244 return Error::success();
246 for (auto &MI : ModiList)
249 if (auto EC = generateFileInfoSubstream())
252 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
253 ::memset(H, 0, sizeof(DbiStreamHeader));
254 H->VersionHeader = *VerHeader;
255 H->VersionSignature = -1;
257 H->BuildNumber = BuildNumber;
259 H->PdbDllRbld = PdbDllRbld;
260 H->PdbDllVersion = PdbDllVersion;
261 H->MachineType = static_cast<uint16_t>(MachineType);
263 H->ECSubstreamSize = ECNamesBuilder.calculateSerializedSize();
264 H->FileInfoSize = FileInfoBuffer.getLength();
265 H->ModiSubstreamSize = calculateModiSubstreamSize();
266 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
267 H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
268 H->SectionMapSize = calculateSectionMapStreamSize();
269 H->TypeServerSize = 0;
270 H->SymRecordStreamIndex = SymRecordStreamIndex;
271 H->PublicSymbolStreamIndex = PublicsStreamIndex;
272 H->MFCTypeServerIndex = kInvalidStreamIndex;
273 H->GlobalSymbolStreamIndex = kInvalidStreamIndex;
276 return Error::success();
279 Error DbiStreamBuilder::finalizeMsfLayout() {
280 for (auto &MI : ModiList) {
281 if (auto EC = MI->finalizeMsfLayout())
285 uint32_t Length = calculateSerializedLength();
286 if (auto EC = Msf.setStreamSize(StreamDBI, Length))
288 return Error::success();
291 static uint16_t toSecMapFlags(uint32_t Flags) {
293 if (Flags & COFF::IMAGE_SCN_MEM_READ)
294 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
295 if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
296 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
297 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
298 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
299 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
300 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
301 if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
302 Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
304 // This seems always 1.
305 Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
310 void DbiStreamBuilder::addSectionContrib(DbiModuleDescriptorBuilder *ModuleDbi,
311 const object::coff_section *SecHdr) {
313 memset(&SC, 0, sizeof(SC));
314 SC.ISect = (uint16_t)~0U; // This represents nil.
315 SC.Off = SecHdr->PointerToRawData;
316 SC.Size = SecHdr->SizeOfRawData;
317 SC.Characteristics = SecHdr->Characteristics;
318 // Use the module index in the module dbi stream or nil (-1).
319 SC.Imod = ModuleDbi ? ModuleDbi->getModuleIndex() : (uint16_t)~0U;
320 SectionContribs.emplace_back(SC);
323 // A utility function to create a Section Map for a given list of COFF sections.
325 // A Section Map seem to be a copy of a COFF section list in other format.
326 // I don't know why a PDB file contains both a COFF section header and
327 // a Section Map, but it seems it must be present in a PDB.
328 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
329 ArrayRef<llvm::object::coff_section> SecHdrs) {
330 std::vector<SecMapEntry> Ret;
333 auto Add = [&]() -> SecMapEntry & {
335 auto &Entry = Ret.back();
336 memset(&Entry, 0, sizeof(Entry));
338 Entry.Frame = Idx + 1;
340 // We don't know the meaning of these fields yet.
341 Entry.SecName = UINT16_MAX;
342 Entry.ClassName = UINT16_MAX;
347 for (auto &Hdr : SecHdrs) {
349 Entry.Flags = toSecMapFlags(Hdr.Characteristics);
350 Entry.SecByteLength = Hdr.VirtualSize;
354 // The last entry is for absolute symbols.
356 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
357 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
358 Entry.SecByteLength = UINT32_MAX;
363 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
364 WritableBinaryStreamRef MsfBuffer) {
365 if (auto EC = finalize())
368 auto DbiS = WritableMappedBlockStream::createIndexedStream(
369 Layout, MsfBuffer, StreamDBI, Allocator);
371 BinaryStreamWriter Writer(*DbiS);
372 if (auto EC = Writer.writeObject(*Header))
375 for (auto &M : ModiList) {
376 if (auto EC = M->commit(Writer, Layout, MsfBuffer))
380 if (!SectionContribs.empty()) {
381 if (auto EC = Writer.writeEnum(DbiSecContribVer60))
383 if (auto EC = Writer.writeArray(makeArrayRef(SectionContribs)))
387 if (!SectionMap.empty()) {
388 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
389 SecMapHeader SMHeader = {Size, Size};
390 if (auto EC = Writer.writeObject(SMHeader))
392 if (auto EC = Writer.writeArray(SectionMap))
396 if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
399 if (auto EC = ECNamesBuilder.commit(Writer))
402 for (auto &Stream : DbgStreams)
403 if (auto EC = Writer.writeInteger(Stream.StreamNumber))
406 for (auto &Stream : DbgStreams) {
407 if (Stream.StreamNumber == kInvalidStreamIndex)
409 auto WritableStream = WritableMappedBlockStream::createIndexedStream(
410 Layout, MsfBuffer, Stream.StreamNumber, Allocator);
411 BinaryStreamWriter DbgStreamWriter(*WritableStream);
412 if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
416 if (Writer.bytesRemaining() > 0)
417 return make_error<RawError>(raw_error_code::invalid_format,
418 "Unexpected bytes found in DBI Stream");
419 return Error::success();