1//===- DbiStream.cpp - PDB Dbi Stream (Stream 3) Access -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
10#include "llvm/ADT/StringRef.h"
11#include "llvm/DebugInfo/MSF/MappedBlockStream.h"
12#include "llvm/DebugInfo/PDB/Native/ISectionContribVisitor.h"
13#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
14#include "llvm/DebugInfo/PDB/Native/RawConstants.h"
15#include "llvm/DebugInfo/PDB/Native/RawError.h"
16#include "llvm/DebugInfo/PDB/Native/RawTypes.h"
17#include "llvm/DebugInfo/PDB/PDBTypes.h"
18#include "llvm/Object/COFF.h"
19#include "llvm/Support/BinaryStreamArray.h"
20#include "llvm/Support/BinaryStreamReader.h"
21#include "llvm/Support/Error.h"
22#include <cstddef>
23#include <cstdint>
24
25using namespace llvm;
26using namespace llvm::codeview;
27using namespace llvm::msf;
28using namespace llvm::pdb;
29using namespace llvm::support;
30
31template <typename ContribType>
32static Error loadSectionContribs(FixedStreamArray<ContribType> &Output,
33 BinaryStreamReader &Reader) {
34 if (Reader.bytesRemaining() % sizeof(ContribType) != 0)
35 return make_error<RawError>(
36 Args: raw_error_code::corrupt_file,
37 Args: "Invalid number of bytes of section contributions");
38
39 uint32_t Count = Reader.bytesRemaining() / sizeof(ContribType);
40 if (auto EC = Reader.readArray(Output, Count))
41 return EC;
42 return Error::success();
43}
44
45DbiStream::DbiStream(std::unique_ptr<BinaryStream> Stream)
46 : Stream(std::move(Stream)), Header(nullptr) {}
47
48DbiStream::~DbiStream() = default;
49
50Error DbiStream::reload(PDBFile *Pdb) {
51 BinaryStreamReader Reader(*Stream);
52
53 if (Stream->getLength() < sizeof(DbiStreamHeader))
54 return make_error<RawError>(Args: raw_error_code::corrupt_file,
55 Args: "DBI Stream does not contain a header.");
56 if (auto EC = Reader.readObject(Dest&: Header))
57 return make_error<RawError>(Args: raw_error_code::corrupt_file,
58 Args: "DBI Stream does not contain a header.");
59
60 if (Header->VersionSignature != -1)
61 return make_error<RawError>(Args: raw_error_code::corrupt_file,
62 Args: "Invalid DBI version signature.");
63
64 // Require at least version 7, which should be present in all PDBs
65 // produced in the last decade and allows us to avoid having to
66 // special case all kinds of complicated arcane formats.
67 if (Header->VersionHeader < PdbDbiV70)
68 return make_error<RawError>(Args: raw_error_code::feature_unsupported,
69 Args: "Unsupported DBI version.");
70
71 if (Stream->getLength() !=
72 sizeof(DbiStreamHeader) + Header->ModiSubstreamSize +
73 Header->SecContrSubstreamSize + Header->SectionMapSize +
74 Header->FileInfoSize + Header->TypeServerSize +
75 Header->OptionalDbgHdrSize + Header->ECSubstreamSize)
76 return make_error<RawError>(Args: raw_error_code::corrupt_file,
77 Args: "DBI Length does not equal sum of substreams.");
78
79 // Only certain substreams are guaranteed to be aligned. Validate
80 // them here.
81 if (Header->ModiSubstreamSize % sizeof(uint32_t) != 0)
82 return make_error<RawError>(Args: raw_error_code::corrupt_file,
83 Args: "DBI MODI substream not aligned.");
84 if (Header->SecContrSubstreamSize % sizeof(uint32_t) != 0)
85 return make_error<RawError>(
86 Args: raw_error_code::corrupt_file,
87 Args: "DBI section contribution substream not aligned.");
88 if (Header->SectionMapSize % sizeof(uint32_t) != 0)
89 return make_error<RawError>(Args: raw_error_code::corrupt_file,
90 Args: "DBI section map substream not aligned.");
91 if (Header->FileInfoSize % sizeof(uint32_t) != 0)
92 return make_error<RawError>(Args: raw_error_code::corrupt_file,
93 Args: "DBI file info substream not aligned.");
94 if (Header->TypeServerSize % sizeof(uint32_t) != 0)
95 return make_error<RawError>(Args: raw_error_code::corrupt_file,
96 Args: "DBI type server substream not aligned.");
97
98 if (auto EC = Reader.readSubstream(Ref&: ModiSubstream, Length: Header->ModiSubstreamSize))
99 return EC;
100
101 if (auto EC = Reader.readSubstream(Ref&: SecContrSubstream,
102 Length: Header->SecContrSubstreamSize))
103 return EC;
104 if (auto EC = Reader.readSubstream(Ref&: SecMapSubstream, Length: Header->SectionMapSize))
105 return EC;
106 if (auto EC = Reader.readSubstream(Ref&: FileInfoSubstream, Length: Header->FileInfoSize))
107 return EC;
108 if (auto EC =
109 Reader.readSubstream(Ref&: TypeServerMapSubstream, Length: Header->TypeServerSize))
110 return EC;
111 if (auto EC = Reader.readSubstream(Ref&: ECSubstream, Length: Header->ECSubstreamSize))
112 return EC;
113 if (auto EC = Reader.readArray(
114 Array&: DbgStreams, NumItems: Header->OptionalDbgHdrSize / sizeof(ulittle16_t)))
115 return EC;
116
117 if (auto EC = Modules.initialize(ModInfo: ModiSubstream.StreamData,
118 FileInfo: FileInfoSubstream.StreamData))
119 return EC;
120
121 if (auto EC = initializeSectionContributionData())
122 return EC;
123 if (auto EC = initializeSectionHeadersData(Pdb))
124 return EC;
125 if (auto EC = initializeSectionMapData())
126 return EC;
127 if (auto EC = initializeOldFpoRecords(Pdb))
128 return EC;
129 if (auto EC = initializeNewFpoRecords(Pdb))
130 return EC;
131
132 if (Reader.bytesRemaining() > 0)
133 return make_error<RawError>(Args: raw_error_code::corrupt_file,
134 Args: "Found unexpected bytes in DBI Stream.");
135
136 if (!ECSubstream.empty()) {
137 BinaryStreamReader ECReader(ECSubstream.StreamData);
138 if (auto EC = ECNames.reload(Reader&: ECReader))
139 return EC;
140 }
141
142 return Error::success();
143}
144
145PdbRaw_DbiVer DbiStream::getDbiVersion() const {
146 uint32_t Value = Header->VersionHeader;
147 return static_cast<PdbRaw_DbiVer>(Value);
148}
149
150uint32_t DbiStream::getAge() const { return Header->Age; }
151
152uint16_t DbiStream::getPublicSymbolStreamIndex() const {
153 return Header->PublicSymbolStreamIndex;
154}
155
156uint16_t DbiStream::getGlobalSymbolStreamIndex() const {
157 return Header->GlobalSymbolStreamIndex;
158}
159
160uint16_t DbiStream::getFlags() const { return Header->Flags; }
161
162bool DbiStream::isIncrementallyLinked() const {
163 return (Header->Flags & DbiFlags::FlagIncrementalMask) != 0;
164}
165
166bool DbiStream::hasCTypes() const {
167 return (Header->Flags & DbiFlags::FlagHasCTypesMask) != 0;
168}
169
170bool DbiStream::isStripped() const {
171 return (Header->Flags & DbiFlags::FlagStrippedMask) != 0;
172}
173
174uint16_t DbiStream::getBuildNumber() const { return Header->BuildNumber; }
175
176uint16_t DbiStream::getBuildMajorVersion() const {
177 return (Header->BuildNumber & DbiBuildNo::BuildMajorMask) >>
178 DbiBuildNo::BuildMajorShift;
179}
180
181uint16_t DbiStream::getBuildMinorVersion() const {
182 return (Header->BuildNumber & DbiBuildNo::BuildMinorMask) >>
183 DbiBuildNo::BuildMinorShift;
184}
185
186uint16_t DbiStream::getPdbDllRbld() const { return Header->PdbDllRbld; }
187
188uint32_t DbiStream::getPdbDllVersion() const { return Header->PdbDllVersion; }
189
190uint32_t DbiStream::getSymRecordStreamIndex() const {
191 return Header->SymRecordStreamIndex;
192}
193
194PDB_Machine DbiStream::getMachineType() const {
195 uint16_t Machine = Header->MachineType;
196 return static_cast<PDB_Machine>(Machine);
197}
198
199FixedStreamArray<object::coff_section> DbiStream::getSectionHeaders() const {
200 return SectionHeaders;
201}
202
203bool DbiStream::hasOldFpoRecords() const { return OldFpoStream != nullptr; }
204
205FixedStreamArray<object::FpoData> DbiStream::getOldFpoRecords() const {
206 return OldFpoRecords;
207}
208
209bool DbiStream::hasNewFpoRecords() const { return NewFpoStream != nullptr; }
210
211const DebugFrameDataSubsectionRef &DbiStream::getNewFpoRecords() const {
212 return NewFpoRecords;
213}
214
215const DbiModuleList &DbiStream::modules() const { return Modules; }
216
217FixedStreamArray<SecMapEntry> DbiStream::getSectionMap() const {
218 return SectionMap;
219}
220
221void DbiStream::visitSectionContributions(
222 ISectionContribVisitor &Visitor) const {
223 if (!SectionContribs.empty()) {
224 assert(SectionContribVersion == DbiSecContribVer60);
225 for (auto &SC : SectionContribs)
226 Visitor.visit(C: SC);
227 } else if (!SectionContribs2.empty()) {
228 assert(SectionContribVersion == DbiSecContribV2);
229 for (auto &SC : SectionContribs2)
230 Visitor.visit(C: SC);
231 }
232}
233
234PdbRaw_DbiSecContribVer DbiStream::getSectionContributionsVersion() const {
235 return SectionContribVersion;
236}
237
238Expected<StringRef> DbiStream::getECName(uint32_t NI) const {
239 return ECNames.getStringForID(ID: NI);
240}
241
242Error DbiStream::initializeSectionContributionData() {
243 if (SecContrSubstream.empty())
244 return Error::success();
245
246 BinaryStreamReader SCReader(SecContrSubstream.StreamData);
247 if (auto EC = SCReader.readEnum(Dest&: SectionContribVersion))
248 return EC;
249
250 if (SectionContribVersion == DbiSecContribVer60)
251 return loadSectionContribs<SectionContrib>(Output&: SectionContribs, Reader&: SCReader);
252 if (SectionContribVersion == DbiSecContribV2)
253 return loadSectionContribs<SectionContrib2>(Output&: SectionContribs2, Reader&: SCReader);
254
255 return make_error<RawError>(Args: raw_error_code::feature_unsupported,
256 Args: "Unsupported DBI Section Contribution version");
257}
258
259// Initializes this->SectionHeaders.
260Error DbiStream::initializeSectionHeadersData(PDBFile *Pdb) {
261 Expected<std::unique_ptr<msf::MappedBlockStream>> ExpectedStream =
262 createIndexedStreamForHeaderType(Pdb, Type: DbgHeaderType::SectionHdr);
263 if (auto EC = ExpectedStream.takeError())
264 return EC;
265
266 auto &SHS = *ExpectedStream;
267 if (!SHS)
268 return Error::success();
269
270 size_t StreamLen = SHS->getLength();
271 if (StreamLen % sizeof(object::coff_section))
272 return make_error<RawError>(Args: raw_error_code::corrupt_file,
273 Args: "Corrupted section header stream.");
274
275 size_t NumSections = StreamLen / sizeof(object::coff_section);
276 BinaryStreamReader Reader(*SHS);
277 if (auto EC = Reader.readArray(Array&: SectionHeaders, NumItems: NumSections))
278 return make_error<RawError>(Args: raw_error_code::corrupt_file,
279 Args: "Could not read a bitmap.");
280
281 SectionHeaderStream = std::move(SHS);
282 return Error::success();
283}
284
285// Initializes this->Fpos.
286Error DbiStream::initializeOldFpoRecords(PDBFile *Pdb) {
287 Expected<std::unique_ptr<msf::MappedBlockStream>> ExpectedStream =
288 createIndexedStreamForHeaderType(Pdb, Type: DbgHeaderType::FPO);
289 if (auto EC = ExpectedStream.takeError())
290 return EC;
291
292 auto &FS = *ExpectedStream;
293 if (!FS)
294 return Error::success();
295
296 size_t StreamLen = FS->getLength();
297 if (StreamLen % sizeof(object::FpoData))
298 return make_error<RawError>(Args: raw_error_code::corrupt_file,
299 Args: "Corrupted Old FPO stream.");
300
301 size_t NumRecords = StreamLen / sizeof(object::FpoData);
302 BinaryStreamReader Reader(*FS);
303 if (auto EC = Reader.readArray(Array&: OldFpoRecords, NumItems: NumRecords))
304 return make_error<RawError>(Args: raw_error_code::corrupt_file,
305 Args: "Corrupted Old FPO stream.");
306 OldFpoStream = std::move(FS);
307 return Error::success();
308}
309
310Error DbiStream::initializeNewFpoRecords(PDBFile *Pdb) {
311 Expected<std::unique_ptr<msf::MappedBlockStream>> ExpectedStream =
312 createIndexedStreamForHeaderType(Pdb, Type: DbgHeaderType::NewFPO);
313 if (auto EC = ExpectedStream.takeError())
314 return EC;
315
316 auto &FS = *ExpectedStream;
317 if (!FS)
318 return Error::success();
319
320 if (auto EC = NewFpoRecords.initialize(Stream: *FS))
321 return EC;
322
323 NewFpoStream = std::move(FS);
324 return Error::success();
325}
326
327Expected<std::unique_ptr<msf::MappedBlockStream>>
328DbiStream::createIndexedStreamForHeaderType(PDBFile *Pdb,
329 DbgHeaderType Type) const {
330 if (!Pdb)
331 return nullptr;
332
333 if (DbgStreams.empty())
334 return nullptr;
335
336 uint32_t StreamNum = getDebugStreamIndex(Type);
337
338 // This means there is no such stream.
339 if (StreamNum == kInvalidStreamIndex)
340 return nullptr;
341
342 return Pdb->safelyCreateIndexedStream(StreamIndex: StreamNum);
343}
344
345BinarySubstreamRef DbiStream::getSectionContributionData() const {
346 return SecContrSubstream;
347}
348
349BinarySubstreamRef DbiStream::getSecMapSubstreamData() const {
350 return SecMapSubstream;
351}
352
353BinarySubstreamRef DbiStream::getModiSubstreamData() const {
354 return ModiSubstream;
355}
356
357BinarySubstreamRef DbiStream::getFileInfoSubstreamData() const {
358 return FileInfoSubstream;
359}
360
361BinarySubstreamRef DbiStream::getTypeServerMapSubstreamData() const {
362 return TypeServerMapSubstream;
363}
364
365BinarySubstreamRef DbiStream::getECSubstreamData() const { return ECSubstream; }
366
367Error DbiStream::initializeSectionMapData() {
368 if (SecMapSubstream.empty())
369 return Error::success();
370
371 BinaryStreamReader SMReader(SecMapSubstream.StreamData);
372 const SecMapHeader *Header;
373 if (auto EC = SMReader.readObject(Dest&: Header))
374 return EC;
375 if (auto EC = SMReader.readArray(Array&: SectionMap, NumItems: Header->SecCount))
376 return EC;
377 return Error::success();
378}
379
380uint32_t DbiStream::getDebugStreamIndex(DbgHeaderType Type) const {
381 uint16_t T = static_cast<uint16_t>(Type);
382 if (T >= DbgStreams.size())
383 return kInvalidStreamIndex;
384 return DbgStreams[T];
385}
386