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/DbiStream.h"
16 #include "llvm/DebugInfo/PDB/Native/ModInfoBuilder.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<ModInfoBuilder &>
78 DbiStreamBuilder::addModuleInfo(StringRef ModuleName) {
79 uint32_t Index = ModiList.size();
80 auto MIB = llvm::make_unique<ModInfoBuilder>(ModuleName, Index, Msf);
82 auto Result = ModiMap.insert(std::make_pair(ModuleName, std::move(MIB)));
85 return make_error<RawError>(raw_error_code::duplicate_entry,
86 "The specified module already exists");
87 ModiList.push_back(M);
91 Error DbiStreamBuilder::addModuleSourceFile(StringRef Module, StringRef File) {
92 auto ModIter = ModiMap.find(Module);
93 if (ModIter == ModiMap.end())
94 return make_error<RawError>(raw_error_code::no_entry,
95 "The specified module was not found");
96 uint32_t Index = SourceFileNames.size();
97 SourceFileNames.insert(std::make_pair(File, Index));
98 auto &ModEntry = *ModIter;
99 ModEntry.second->addSourceFile(File);
100 return Error::success();
103 uint32_t DbiStreamBuilder::calculateModiSubstreamSize() const {
105 for (const auto &M : ModiList)
106 Size += M->calculateSerializedLength();
110 uint32_t DbiStreamBuilder::calculateSectionContribsStreamSize() const {
111 if (SectionContribs.empty())
113 return sizeof(enum PdbRaw_DbiSecContribVer) +
114 sizeof(SectionContribs[0]) * SectionContribs.size();
117 uint32_t DbiStreamBuilder::calculateSectionMapStreamSize() const {
118 if (SectionMap.empty())
120 return sizeof(SecMapHeader) + sizeof(SecMapEntry) * SectionMap.size();
123 uint32_t DbiStreamBuilder::calculateFileInfoSubstreamSize() const {
125 Size += sizeof(ulittle16_t); // NumModules
126 Size += sizeof(ulittle16_t); // NumSourceFiles
127 Size += ModiList.size() * sizeof(ulittle16_t); // ModIndices
128 Size += ModiList.size() * sizeof(ulittle16_t); // ModFileCounts
129 uint32_t NumFileInfos = 0;
130 for (const auto &M : ModiList)
131 NumFileInfos += M->source_files().size();
132 Size += NumFileInfos * sizeof(ulittle32_t); // FileNameOffsets
133 Size += calculateNamesBufferSize();
134 return alignTo(Size, sizeof(uint32_t));
137 uint32_t DbiStreamBuilder::calculateNamesBufferSize() const {
139 for (const auto &F : SourceFileNames) {
140 Size += F.getKeyLength() + 1; // Names[I];
145 uint32_t DbiStreamBuilder::calculateDbgStreamsSize() const {
146 return DbgStreams.size() * sizeof(uint16_t);
149 Error DbiStreamBuilder::generateFileInfoSubstream() {
150 uint32_t Size = calculateFileInfoSubstreamSize();
151 uint32_t NameSize = calculateNamesBufferSize();
152 auto Data = Allocator.Allocate<uint8_t>(Size);
153 uint32_t NamesOffset = Size - NameSize;
155 FileInfoBuffer = MutableBinaryByteStream(MutableArrayRef<uint8_t>(Data, Size),
156 llvm::support::little);
158 WritableBinaryStreamRef MetadataBuffer =
159 WritableBinaryStreamRef(FileInfoBuffer).keep_front(NamesOffset);
160 BinaryStreamWriter MetadataWriter(MetadataBuffer);
162 uint16_t ModiCount = std::min<uint32_t>(UINT16_MAX, ModiList.size());
163 uint16_t FileCount = std::min<uint32_t>(UINT16_MAX, SourceFileNames.size());
164 if (auto EC = MetadataWriter.writeInteger(ModiCount)) // NumModules
166 if (auto EC = MetadataWriter.writeInteger(FileCount)) // NumSourceFiles
168 for (uint16_t I = 0; I < ModiCount; ++I) {
169 if (auto EC = MetadataWriter.writeInteger(I)) // Mod Indices
172 for (const auto &MI : ModiList) {
173 FileCount = static_cast<uint16_t>(MI->source_files().size());
174 if (auto EC = MetadataWriter.writeInteger(FileCount)) // Mod File Counts
178 // Before writing the FileNameOffsets array, write the NamesBuffer array.
179 // A side effect of this is that this will actually compute the various
180 // file name offsets, so we can then go back and write the FileNameOffsets
181 // array to the other substream.
182 NamesBuffer = WritableBinaryStreamRef(FileInfoBuffer).drop_front(NamesOffset);
183 BinaryStreamWriter NameBufferWriter(NamesBuffer);
184 for (auto &Name : SourceFileNames) {
185 Name.second = NameBufferWriter.getOffset();
186 if (auto EC = NameBufferWriter.writeCString(Name.getKey()))
190 for (const auto &MI : ModiList) {
191 for (StringRef Name : MI->source_files()) {
192 auto Result = SourceFileNames.find(Name);
193 if (Result == SourceFileNames.end())
194 return make_error<RawError>(raw_error_code::no_entry,
195 "The source file was not found.");
196 if (auto EC = MetadataWriter.writeInteger(Result->second))
201 if (NameBufferWriter.bytesRemaining() > 0)
202 return make_error<RawError>(raw_error_code::invalid_format,
203 "The names buffer contained unexpected data.");
205 if (MetadataWriter.bytesRemaining() > sizeof(uint32_t))
206 return make_error<RawError>(
207 raw_error_code::invalid_format,
208 "The metadata buffer contained unexpected data.");
210 return Error::success();
213 Error DbiStreamBuilder::finalize() {
215 return Error::success();
217 for (auto &MI : ModiList)
220 if (auto EC = generateFileInfoSubstream())
223 DbiStreamHeader *H = Allocator.Allocate<DbiStreamHeader>();
224 H->VersionHeader = *VerHeader;
225 H->VersionSignature = -1;
227 H->BuildNumber = BuildNumber;
229 H->PdbDllRbld = PdbDllRbld;
230 H->PdbDllVersion = PdbDllVersion;
231 H->MachineType = static_cast<uint16_t>(MachineType);
233 H->ECSubstreamSize = 0;
234 H->FileInfoSize = FileInfoBuffer.getLength();
235 H->ModiSubstreamSize = calculateModiSubstreamSize();
236 H->OptionalDbgHdrSize = DbgStreams.size() * sizeof(uint16_t);
237 H->SecContrSubstreamSize = calculateSectionContribsStreamSize();
238 H->SectionMapSize = calculateSectionMapStreamSize();
239 H->TypeServerSize = 0;
240 H->SymRecordStreamIndex = kInvalidStreamIndex;
241 H->PublicSymbolStreamIndex = kInvalidStreamIndex;
242 H->MFCTypeServerIndex = kInvalidStreamIndex;
243 H->GlobalSymbolStreamIndex = kInvalidStreamIndex;
246 return Error::success();
249 Error DbiStreamBuilder::finalizeMsfLayout() {
250 for (auto &MI : ModiList) {
251 if (auto EC = MI->finalizeMsfLayout())
255 uint32_t Length = calculateSerializedLength();
256 if (auto EC = Msf.setStreamSize(StreamDBI, Length))
258 return Error::success();
261 static uint16_t toSecMapFlags(uint32_t Flags) {
263 if (Flags & COFF::IMAGE_SCN_MEM_READ)
264 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Read);
265 if (Flags & COFF::IMAGE_SCN_MEM_WRITE)
266 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Write);
267 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
268 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
269 if (Flags & COFF::IMAGE_SCN_MEM_EXECUTE)
270 Ret |= static_cast<uint16_t>(OMFSegDescFlags::Execute);
271 if (!(Flags & COFF::IMAGE_SCN_MEM_16BIT))
272 Ret |= static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit);
274 // This seems always 1.
275 Ret |= static_cast<uint16_t>(OMFSegDescFlags::IsSelector);
280 // A utility function to create Section Contributions
281 // for a given input sections.
282 std::vector<SectionContrib> DbiStreamBuilder::createSectionContribs(
283 ArrayRef<object::coff_section> SecHdrs) {
284 std::vector<SectionContrib> Ret;
286 // Create a SectionContrib for each input section.
287 for (auto &Sec : SecHdrs) {
289 auto &Entry = Ret.back();
290 memset(&Entry, 0, sizeof(Entry));
292 Entry.Off = Sec.PointerToRawData;
293 Entry.Size = Sec.SizeOfRawData;
294 Entry.Characteristics = Sec.Characteristics;
299 // A utility function to create a Section Map for a given list of COFF sections.
301 // A Section Map seem to be a copy of a COFF section list in other format.
302 // I don't know why a PDB file contains both a COFF section header and
303 // a Section Map, but it seems it must be present in a PDB.
304 std::vector<SecMapEntry> DbiStreamBuilder::createSectionMap(
305 ArrayRef<llvm::object::coff_section> SecHdrs) {
306 std::vector<SecMapEntry> Ret;
309 auto Add = [&]() -> SecMapEntry & {
311 auto &Entry = Ret.back();
312 memset(&Entry, 0, sizeof(Entry));
314 Entry.Frame = Idx + 1;
316 // We don't know the meaning of these fields yet.
317 Entry.SecName = UINT16_MAX;
318 Entry.ClassName = UINT16_MAX;
323 for (auto &Hdr : SecHdrs) {
325 Entry.Flags = toSecMapFlags(Hdr.Characteristics);
326 Entry.SecByteLength = Hdr.VirtualSize;
330 // The last entry is for absolute symbols.
332 Entry.Flags = static_cast<uint16_t>(OMFSegDescFlags::AddressIs32Bit) |
333 static_cast<uint16_t>(OMFSegDescFlags::IsAbsoluteAddress);
334 Entry.SecByteLength = UINT32_MAX;
339 Error DbiStreamBuilder::commit(const msf::MSFLayout &Layout,
340 WritableBinaryStreamRef MsfBuffer) {
341 if (auto EC = finalize())
344 auto DbiS = WritableMappedBlockStream::createIndexedStream(Layout, MsfBuffer,
347 BinaryStreamWriter Writer(*DbiS);
348 if (auto EC = Writer.writeObject(*Header))
351 for (auto &M : ModiList) {
352 if (auto EC = M->commit(Writer, Layout, MsfBuffer))
356 if (!SectionContribs.empty()) {
357 if (auto EC = Writer.writeEnum(DbiSecContribVer60))
359 if (auto EC = Writer.writeArray(SectionContribs))
363 if (!SectionMap.empty()) {
364 ulittle16_t Size = static_cast<ulittle16_t>(SectionMap.size());
365 SecMapHeader SMHeader = {Size, Size};
366 if (auto EC = Writer.writeObject(SMHeader))
368 if (auto EC = Writer.writeArray(SectionMap))
372 if (auto EC = Writer.writeStreamRef(FileInfoBuffer))
375 for (auto &Stream : DbgStreams)
376 if (auto EC = Writer.writeInteger(Stream.StreamNumber))
379 for (auto &Stream : DbgStreams) {
380 if (Stream.StreamNumber == kInvalidStreamIndex)
382 auto WritableStream = WritableMappedBlockStream::createIndexedStream(
383 Layout, MsfBuffer, Stream.StreamNumber);
384 BinaryStreamWriter DbgStreamWriter(*WritableStream);
385 if (auto EC = DbgStreamWriter.writeArray(Stream.Data))
389 if (Writer.bytesRemaining() > 0)
390 return make_error<RawError>(raw_error_code::invalid_format,
391 "Unexpected bytes found in DBI Stream");
392 return Error::success();