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/DebugInfo/MSF/MSFBuilder.h"
14 #include "llvm/DebugInfo/MSF/MappedBlockStream.h"
15 #include "llvm/DebugInfo/PDB/Native/DbiModuleDescriptorBuilder.h"
16 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
17 #include "llvm/DebugInfo/PDB/Native/RawError.h"
18 #include "llvm/Object/COFF.h"
19 #include "llvm/Support/BinaryStreamWriter.h"
20 #include "llvm/Support/COFF.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::setSectionContribs(ArrayRef<SectionContrib> Arr) {
49 SectionContribs = Arr;
52 void DbiStreamBuilder::setSectionMap(ArrayRef<SecMapEntry> SecMap) {
56 Error DbiStreamBuilder::addDbgStream(pdb::DbgHeaderType Type,
57 ArrayRef<uint8_t> Data) {
58 if (DbgStreams[(int)Type].StreamNumber)
59 return make_error<RawError>(raw_error_code::duplicate_entry,
60 "The specified stream type already exists");
61 auto ExpectedIndex = Msf.addStream(Data.size());
63 return ExpectedIndex.takeError();
64 uint32_t Index = std::move(*ExpectedIndex);
65 DbgStreams[(int)Type].Data = Data;
66 DbgStreams[(int)Type].StreamNumber = Index;
67 return Error::success();
70 uint32_t DbiStreamBuilder::calculateSerializedLength() const {
71 // For now we only support serializing the header.
72 return sizeof(DbiStreamHeader) + calculateFileInfoSubstreamSize() +
73 calculateModiSubstreamSize() + calculateSectionContribsStreamSize() +
74 calculateSectionMapStreamSize() + calculateDbgStreamsSize();
77 Expected<DbiModuleDescriptorBuilder &>
78 DbiStreamBuilder::addModuleInfo(StringRef ModuleName) {
79 uint32_t Index = ModiList.size();
81 llvm::make_unique<DbiModuleDescriptorBuilder>(ModuleName, Index, Msf);
83 auto Result = ModiMap.insert(std::make_pair(ModuleName, std::move(MIB)));
86 return make_error<RawError>(raw_error_code::duplicate_entry,
87 "The specified module already exists");
88 ModiList.push_back(M);
92 Error DbiStreamBuilder::addModuleSourceFile(StringRef Module, StringRef File) {
93 auto ModIter = ModiMap.find(Module);
94 if (ModIter == ModiMap.end())
95 return make_error<RawError>(raw_error_code::no_entry,
96 "The specified module was not found");
97 uint32_t Index = SourceFileNames.size();
98 SourceFileNames.insert(std::make_pair(File, Index));
99 auto &ModEntry = *ModIter;
100 ModEntry.second->addSourceFile(File);
101 return Error::success();
104 Expected<uint32_t> DbiStreamBuilder::getSourceFileNameIndex(StringRef File) {
105 auto NameIter = SourceFileNames.find(File);
106 if (NameIter == SourceFileNames.end())
107 return make_error<RawError>(raw_error_code::no_entry,
108 "The specified source file was not found");
109 return NameIter->getValue();
112 uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
114 for (const auto &M : ModiList)
115 Size += M->calculateSerializedLength();
119 uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
120 if (SectionContribs.empty())
122 return sizeof(enum PdbRaw_DbiSecContribVer) +
123 sizeof(SectionContribs[0]) * SectionContribs.size();
126 uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
127 if (SectionMap.empty())
129 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
132 uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
134 Size += sizeof(ulittle16_t); // NumModules
135 Size += sizeof(ulittle16_t); // NumSourceFiles
136 Size += ModiList.size() * sizeof(ulittle16_t); // ModIndices
137 Size += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts
138 uint32_t NumFileInfos = 0;
139 for (const auto &M : ModiList)
140 NumFileInfos += M->source_files().size();
141 Size += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
142 Size += calculateNamesBufferSize();
143 return alignTo(Size, sizeof(uint32_t));
146 uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
148 for (const auto &F : SourceFileNames) {
149 Size += F.getKeyLength() + 1; // Names[I];
154 uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
155 return DbgStreams.size() * sizeof(uint16_t);
158 Error DbiStreamBuilder::generateFileInfoSubstream() {
159 uint32_t Size = calculateFileInfoSubstreamSize();
160 uint32_t NameSize = calculateNamesBufferSize();
161 auto Data = Allocator.Allocate<uint8_t>(Size);
162 uint32_t NamesOffset = Size - NameSize;
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 (NameBufferWriter.bytesRemaining() > 0)
211 return make_error<RawError>(raw_error_code::invalid_format,
212 "The names buffer contained unexpected data.");
214 if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
215 return make_error<RawError>(
216 raw_error_code::invalid_format,
217 "The metadata buffer contained unexpected data.");
219 return Error::success();
222 Error DbiStreamBuilder::finalize() {
224 return Error::success();
226 for (auto &MI : ModiList)
229 if (auto EC = generateFileInfoSubstream())
232 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
233 H->VersionHeader = *VerHeader;
234 H->VersionSignature = -1;
236 H->BuildNumber = BuildNumber;
238 H->PdbDllRbld = PdbDllRbld;
239 H->PdbDllVersion = PdbDllVersion;
240 H->MachineType = static_cast<uint16_t>(MachineType);
242 H->ECSubstreamSize = 0;
243 H->FileInfoSize = FileInfoBuffer.getLength();
244 H->ModiSubstreamSize = calculateModiSubstreamSize();
245 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
246 H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
247 H->SectionMapSize = calculateSectionMapStreamSize();
248 H->TypeServerSize = 0;
249 H->SymRecordStreamIndex = kInvalidStreamIndex;
250 H->PublicSymbolStreamIndex = kInvalidStreamIndex;
251 H->MFCTypeServerIndex = kInvalidStreamIndex;
252 H->GlobalSymbolStreamIndex = kInvalidStreamIndex;
255 return Error::success();
258 Error DbiStreamBuilder::finalizeMsfLayout() {
259 for (auto &MI : ModiList) {
260 if (auto EC = MI->finalizeMsfLayout())
264 uint32_t Length = calculateSerializedLength();
265 if (auto EC = Msf.setStreamSize(StreamDBI, Length))
267 return Error::success();
270 static uint16_t toSecMapFlags(uint32_t Flags) {
272 if (Flags & COFF::IMAGE_SCN_MEM_READ)
273 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
274 if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
275 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
276 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
277 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
278 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
279 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
280 if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
281 Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
283 // This seems always 1.
284 Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
289 // A utility function to create Section Contributions
290 // for a given input sections.
291 std::vector<SectionContrib> DbiStreamBuilder::createSectionContribs(
292 ArrayRef<object::coff_section> SecHdrs) {
293 std::vector<SectionContrib> Ret;
295 // Create a SectionContrib for each input section.
296 for (auto &Sec : SecHdrs) {
298 auto &Entry = Ret.back();
299 memset(&Entry, 0, sizeof(Entry));
301 Entry.Off = Sec.PointerToRawData;
302 Entry.Size = Sec.SizeOfRawData;
303 Entry.Characteristics = Sec.Characteristics;
308 // A utility function to create a Section Map for a given list of COFF sections.
310 // A Section Map seem to be a copy of a COFF section list in other format.
311 // I don't know why a PDB file contains both a COFF section header and
312 // a Section Map, but it seems it must be present in a PDB.
313 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
314 ArrayRef<llvm::object::coff_section> SecHdrs) {
315 std::vector<SecMapEntry> Ret;
318 auto Add = [&]() -> SecMapEntry & {
320 auto &Entry = Ret.back();
321 memset(&Entry, 0, sizeof(Entry));
323 Entry.Frame = Idx + 1;
325 // We don't know the meaning of these fields yet.
326 Entry.SecName = UINT16_MAX;
327 Entry.ClassName = UINT16_MAX;
332 for (auto &Hdr : SecHdrs) {
334 Entry.Flags = toSecMapFlags(Hdr.Characteristics);
335 Entry.SecByteLength = Hdr.VirtualSize;
339 // The last entry is for absolute symbols.
341 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
342 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
343 Entry.SecByteLength = UINT32_MAX;
348 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
349 WritableBinaryStreamRef MsfBuffer) {
350 if (auto EC = finalize())
353 auto DbiS = WritableMappedBlockStream::createIndexedStream(Layout, MsfBuffer,
356 BinaryStreamWriter Writer(*DbiS);
357 if (auto EC = Writer.writeObject(*Header))
360 for (auto &M : ModiList) {
361 if (auto EC = M->commit(Writer, Layout, MsfBuffer))
365 if (!SectionContribs.empty()) {
366 if (auto EC = Writer.writeEnum(DbiSecContribVer60))
368 if (auto EC = Writer.writeArray(SectionContribs))
372 if (!SectionMap.empty()) {
373 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
374 SecMapHeader SMHeader = {Size, Size};
375 if (auto EC = Writer.writeObject(SMHeader))
377 if (auto EC = Writer.writeArray(SectionMap))
381 if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
384 for (auto &Stream : DbgStreams)
385 if (auto EC = Writer.writeInteger(Stream.StreamNumber))
388 for (auto &Stream : DbgStreams) {
389 if (Stream.StreamNumber == kInvalidStreamIndex)
391 auto WritableStream = WritableMappedBlockStream::createIndexedStream(
392 Layout, MsfBuffer, Stream.StreamNumber);
393 BinaryStreamWriter DbgStreamWriter(*WritableStream);
394 if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
398 if (Writer.bytesRemaining() > 0)
399 return make_error<RawError>(raw_error_code::invalid_format,
400 "Unexpected bytes found in DBI Stream");
401 return Error::success();