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 Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type,
53 ArrayRef<uint8_t> Data) {
54 if (DbgStreams[(int)Type].StreamNumber)
55 return make_error<RawError>(raw_error_code::duplicate_entry,
56 "The specified stream type already exists");
57 auto ExpectedIndex = Msf.addStream(Data.size());
59 return ExpectedIndex.takeError();
60 uint32_t Index = std::move(*ExpectedIndex);
61 DbgStreams[(int)Type].Data = Data;
62 DbgStreams[(int)Type].StreamNumber = Index;
63 return Error::success();
66 uint32_t DbiStreamBuilder::calculateSerializedLength() const {
67 // For now we only support serializing the header.
68 return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
69 calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
70 calculateSectionMapStreamSize() + calculateDbgStreamsSize();
73 Expected<DbiModuleDescriptorBuilder &>
74 DbiStreamBuilder::addModuleInfo(StringRef ModuleName) {
75 uint32_t Index = ModiList.size();
77 llvm::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf);
79 auto Result = ModiMap.insert(std::make_pair(ModuleName, std::move(MIB)));
82 return make_error<RawError>(raw_error_code::duplicate_entry,
83 "The specified module already exists");
84 ModiList.push_back(M);
88 Error DbiStreamBuilder::addModuleSourceFile(StringRef Module, StringRef File) {
89 auto ModIter = ModiMap.find(Module);
90 if (ModIter == ModiMap.end())
91 return make_error<RawError>(raw_error_code::no_entry,
92 "The specified module was not found");
93 uint32_t Index = SourceFileNames.size();
94 SourceFileNames.insert(std::make_pair(File, Index));
95 auto &ModEntry = *ModIter;
96 ModEntry.second->addSourceFile(File);
97 return Error::success();
100 Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) {
101 auto NameIter = SourceFileNames.find(File);
102 if (NameIter == SourceFileNames.end())
103 return make_error<RawError>(raw_error_code::no_entry,
104 "The specified source file was not found");
105 return NameIter->getValue();
108 uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
110 for (const auto &M : ModiList)
111 Size += M->calculateSerializedLength();
115 uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
116 if (SectionContribs.empty())
118 return sizeof(enum PdbRaw_DbiSecContribVer) +
119 sizeof(SectionContribs[0]) * SectionContribs.size();
122 uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
123 if (SectionMap.empty())
125 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
128 uint32_t DbiStreamBuilder::calculateNamesOffset() const {
130 Offset += sizeof(ulittle16_t); // NumModules
131 Offset += sizeof(ulittle16_t); // NumSourceFiles
132 Offset += ModiList.size() * sizeof(ulittle16_t); // ModIndices
133 Offset += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts
134 uint32_t NumFileInfos = 0;
135 for (const auto &M : ModiList)
136 NumFileInfos += M->source_files().size();
137 Offset += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
141 uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
142 uint32_t Size = calculateNamesOffset();
143 Size += calculateNamesBufferSize();
144 return alignTo(Size, sizeof(uint32_t));
147 uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
149 for (const auto &F : SourceFileNames) {
150 Size += F.getKeyLength() + 1; // Names[I];
155 uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
156 return DbgStreams.size() * sizeof(uint16_t);
159 Error DbiStreamBuilder::generateFileInfoSubstream() {
160 uint32_t Size = calculateFileInfoSubstreamSize();
161 auto Data = Allocator.Allocate<uint8_t>(Size);
162 uint32_t NamesOffset = calculateNamesOffset();
164 FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size),
165 llvm::support::little);
167 WritableBinaryStreamRef MetadataBuffer =
168 WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
169 BinaryStreamWriter MetadataWriter(MetadataBuffer);
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
175 if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
177 for (uint16_t I = 0; I < ModiCount; ++I) {
178 if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
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
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()))
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))
210 if (auto EC = NameBufferWriter.padToAlignment(sizeof(uint32_t)))
213 if (NameBufferWriter.bytesRemaining() > 0)
214 return make_error<RawError>(raw_error_code::invalid_format,
215 "The names buffer contained unexpected data.");
217 if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
218 return make_error<RawError>(
219 raw_error_code::invalid_format,
220 "The metadata buffer contained unexpected data.");
222 return Error::success();
225 Error DbiStreamBuilder::finalize() {
227 return Error::success();
229 for (auto &MI : ModiList)
232 if (auto EC = generateFileInfoSubstream())
235 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
236 H->VersionHeader = *VerHeader;
237 H->VersionSignature = -1;
239 H->BuildNumber = BuildNumber;
241 H->PdbDllRbld = PdbDllRbld;
242 H->PdbDllVersion = PdbDllVersion;
243 H->MachineType = static_cast<uint16_t>(MachineType);
245 H->ECSubstreamSize = 0;
246 H->FileInfoSize = FileInfoBuffer.getLength();
247 H->ModiSubstreamSize = calculateModiSubstreamSize();
248 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
249 H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
250 H->SectionMapSize = calculateSectionMapStreamSize();
251 H->TypeServerSize = 0;
252 H->SymRecordStreamIndex = kInvalidStreamIndex;
253 H->PublicSymbolStreamIndex = kInvalidStreamIndex;
254 H->MFCTypeServerIndex = kInvalidStreamIndex;
255 H->GlobalSymbolStreamIndex = kInvalidStreamIndex;
258 return Error::success();
261 Error DbiStreamBuilder::finalizeMsfLayout() {
262 for (auto &MI : ModiList) {
263 if (auto EC = MI->finalizeMsfLayout())
267 uint32_t Length = calculateSerializedLength();
268 if (auto EC = Msf.setStreamSize(StreamDBI, Length))
270 return Error::success();
273 static uint16_t toSecMapFlags(uint32_t Flags) {
275 if (Flags & COFF::IMAGE_SCN_MEM_READ)
276 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
277 if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
278 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
279 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
280 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
281 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
282 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
283 if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
284 Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
286 // This seems always 1.
287 Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
292 void DbiStreamBuilder::addSectionContrib(DbiModuleDescriptorBuilder *ModuleDbi,
293 const object::coff_section *SecHdr) {
295 memset(&SC, 0, sizeof(SC));
296 SC.ISect = (uint16_t)~0U; // This represents nil.
297 SC.Off = SecHdr->PointerToRawData;
298 SC.Size = SecHdr->SizeOfRawData;
299 SC.Characteristics = SecHdr->Characteristics;
300 // Use the module index in the module dbi stream or nil (-1).
301 SC.Imod = ModuleDbi ? ModuleDbi->getModuleIndex() : (uint16_t)~0U;
302 SectionContribs.emplace_back(SC);
305 // A utility function to create a Section Map for a given list of COFF sections.
307 // A Section Map seem to be a copy of a COFF section list in other format.
308 // I don't know why a PDB file contains both a COFF section header and
309 // a Section Map, but it seems it must be present in a PDB.
310 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
311 ArrayRef<llvm::object::coff_section> SecHdrs) {
312 std::vector<SecMapEntry> Ret;
315 auto Add = [&]() -> SecMapEntry & {
317 auto &Entry = Ret.back();
318 memset(&Entry, 0, sizeof(Entry));
320 Entry.Frame = Idx + 1;
322 // We don't know the meaning of these fields yet.
323 Entry.SecName = UINT16_MAX;
324 Entry.ClassName = UINT16_MAX;
329 for (auto &Hdr : SecHdrs) {
331 Entry.Flags = toSecMapFlags(Hdr.Characteristics);
332 Entry.SecByteLength = Hdr.VirtualSize;
336 // The last entry is for absolute symbols.
338 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
339 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
340 Entry.SecByteLength = UINT32_MAX;
345 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
346 WritableBinaryStreamRef MsfBuffer) {
347 if (auto EC = finalize())
350 auto DbiS = WritableMappedBlockStream::createIndexedStream(
351 Layout, MsfBuffer, StreamDBI, Allocator);
353 BinaryStreamWriter Writer(*DbiS);
354 if (auto EC = Writer.writeObject(*Header))
357 for (auto &M : ModiList) {
358 if (auto EC = M->commit(Writer, Layout, MsfBuffer))
362 if (!SectionContribs.empty()) {
363 if (auto EC = Writer.writeEnum(DbiSecContribVer60))
365 if (auto EC = Writer.writeArray(makeArrayRef(SectionContribs)))
369 if (!SectionMap.empty()) {
370 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
371 SecMapHeader SMHeader = {Size, Size};
372 if (auto EC = Writer.writeObject(SMHeader))
374 if (auto EC = Writer.writeArray(SectionMap))
378 if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
381 for (auto &Stream : DbgStreams)
382 if (auto EC = Writer.writeInteger(Stream.StreamNumber))
385 for (auto &Stream : DbgStreams) {
386 if (Stream.StreamNumber == kInvalidStreamIndex)
388 auto WritableStream = WritableMappedBlockStream::createIndexedStream(
389 Layout, MsfBuffer, Stream.StreamNumber, Allocator);
390 BinaryStreamWriter DbgStreamWriter(*WritableStream);
391 if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
395 if (Writer.bytesRemaining() > 0)
396 return make_error<RawError>(raw_error_code::invalid_format,
397 "Unexpected bytes found in DBI Stream");
398 return Error::success();