1 //===- InputFile.cpp ------------------------------------------ *- 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 "InputFile.h"
12 #include "FormatUtil.h"
13 #include "LinePrinter.h"
15 #include "llvm/BinaryFormat/Magic.h"
16 #include "llvm/DebugInfo/CodeView/CodeView.h"
17 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
18 #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
19 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
20 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
21 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
22 #include "llvm/DebugInfo/PDB/Native/PDBStringTable.h"
23 #include "llvm/DebugInfo/PDB/Native/RawError.h"
24 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
25 #include "llvm/DebugInfo/PDB/PDB.h"
26 #include "llvm/Object/COFF.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/FormatVariadic.h"
31 using namespace llvm::codeview;
32 using namespace llvm::object;
33 using namespace llvm::pdb;
35 InputFile::InputFile() {}
36 InputFile::~InputFile() {}
38 static Expected<ModuleDebugStreamRef>
39 getModuleDebugStream(PDBFile &File, StringRef &ModuleName, uint32_t Index) {
40 ExitOnError Err("Unexpected error: ");
42 auto &Dbi = Err(File.getPDBDbiStream());
43 const auto &Modules = Dbi.modules();
44 auto Modi = Modules.getModuleDescriptor(Index);
46 ModuleName = Modi.getModuleName();
48 uint16_t ModiStream = Modi.getModuleStreamIndex();
49 if (ModiStream == kInvalidStreamIndex)
50 return make_error<RawError>(raw_error_code::no_stream,
51 "Module stream not present");
53 auto ModStreamData = File.createIndexedStream(ModiStream);
55 ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
56 if (auto EC = ModS.reload())
57 return make_error<RawError>(raw_error_code::corrupt_file,
58 "Invalid module stream");
60 return std::move(ModS);
63 static inline bool isCodeViewDebugSubsection(object::SectionRef Section,
65 BinaryStreamReader &Reader) {
66 StringRef SectionName, Contents;
67 if (Section.getName(SectionName))
70 if (SectionName != Name)
73 if (Section.getContents(Contents))
76 Reader = BinaryStreamReader(Contents, support::little);
78 if (Reader.bytesRemaining() < sizeof(uint32_t))
80 cantFail(Reader.readInteger(Magic));
81 if (Magic != COFF::DEBUG_SECTION_MAGIC)
86 static inline bool isDebugSSection(object::SectionRef Section,
87 DebugSubsectionArray &Subsections) {
88 BinaryStreamReader Reader;
89 if (!isCodeViewDebugSubsection(Section, ".debug$S", Reader))
92 cantFail(Reader.readArray(Subsections, Reader.bytesRemaining()));
96 static bool isDebugTSection(SectionRef Section, CVTypeArray &Types) {
97 BinaryStreamReader Reader;
98 if (!isCodeViewDebugSubsection(Section, ".debug$T", Reader) &&
99 !isCodeViewDebugSubsection(Section, ".debug$P", Reader))
101 cantFail(Reader.readArray(Types, Reader.bytesRemaining()));
105 static std::string formatChecksumKind(FileChecksumKind Kind) {
107 RETURN_CASE(FileChecksumKind, None, "None");
108 RETURN_CASE(FileChecksumKind, MD5, "MD5");
109 RETURN_CASE(FileChecksumKind, SHA1, "SHA-1");
110 RETURN_CASE(FileChecksumKind, SHA256, "SHA-256");
112 return formatUnknownEnum(Kind);
115 static const DebugStringTableSubsectionRef &extractStringTable(PDBFile &File) {
116 return cantFail(File.getStringTable()).getStringTable();
119 template <typename... Args>
120 static void formatInternal(LinePrinter &Printer, bool Append, Args &&... args) {
122 Printer.format(std::forward<Args>(args)...);
124 Printer.formatLine(std::forward<Args>(args)...);
127 SymbolGroup::SymbolGroup(InputFile *File, uint32_t GroupIndex) : File(File) {
132 initializeForPdb(GroupIndex);
136 for (const auto &S : File->obj().sections()) {
137 DebugSubsectionArray SS;
138 if (!isDebugSSection(S, SS))
141 if (!SC.hasChecksums() || !SC.hasStrings())
147 if (SC.hasChecksums() && SC.hasStrings())
150 rebuildChecksumMap();
154 StringRef SymbolGroup::name() const { return Name; }
156 void SymbolGroup::updateDebugS(const codeview::DebugSubsectionArray &SS) {
160 void SymbolGroup::updatePdbModi(uint32_t Modi) { initializeForPdb(Modi); }
162 void SymbolGroup::initializeForPdb(uint32_t Modi) {
163 assert(File && File->isPdb());
165 // PDB always uses the same string table, but each module has its own
166 // checksums. So we only set the strings if they're not already set.
167 if (!SC.hasStrings())
168 SC.setStrings(extractStringTable(File->pdb()));
171 auto MDS = getModuleDebugStream(File->pdb(), Name, Modi);
173 consumeError(MDS.takeError());
177 DebugStream = std::make_shared<ModuleDebugStreamRef>(std::move(*MDS));
178 Subsections = DebugStream->getSubsectionsArray();
179 SC.initialize(Subsections);
180 rebuildChecksumMap();
183 void SymbolGroup::rebuildChecksumMap() {
184 if (!SC.hasChecksums())
187 for (const auto &Entry : SC.checksums()) {
188 auto S = SC.strings().getString(Entry.FileNameOffset);
191 ChecksumsByFile[*S] = Entry;
195 const ModuleDebugStreamRef &SymbolGroup::getPdbModuleStream() const {
196 assert(File && File->isPdb() && DebugStream);
200 Expected<StringRef> SymbolGroup::getNameFromStringTable(uint32_t Offset) const {
201 return SC.strings().getString(Offset);
204 void SymbolGroup::formatFromFileName(LinePrinter &Printer, StringRef File,
206 auto FC = ChecksumsByFile.find(File);
207 if (FC == ChecksumsByFile.end()) {
208 formatInternal(Printer, Append, "- (no checksum) {0}", File);
212 formatInternal(Printer, Append, "- ({0}: {1}) {2}",
213 formatChecksumKind(FC->getValue().Kind),
214 toHex(FC->getValue().Checksum), File);
217 void SymbolGroup::formatFromChecksumsOffset(LinePrinter &Printer,
220 if (!SC.hasChecksums()) {
221 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
225 auto Iter = SC.checksums().getArray().at(Offset);
226 if (Iter == SC.checksums().getArray().end()) {
227 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
231 uint32_t FO = Iter->FileNameOffset;
232 auto ExpectedFile = getNameFromStringTable(FO);
234 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
235 consumeError(ExpectedFile.takeError());
238 if (Iter->Kind == FileChecksumKind::None) {
239 formatInternal(Printer, Append, "{0} (no checksum)", *ExpectedFile);
241 formatInternal(Printer, Append, "{0} ({1}: {2})", *ExpectedFile,
242 formatChecksumKind(Iter->Kind), toHex(Iter->Checksum));
246 Expected<InputFile> InputFile::open(StringRef Path, bool AllowUnknownFile) {
248 if (!llvm::sys::fs::exists(Path))
249 return make_error<StringError>(formatv("File {0} not found", Path),
250 inconvertibleErrorCode());
253 if (auto EC = identify_magic(Path, Magic))
254 return make_error<StringError>(
255 formatv("Unable to identify file type for file {0}", Path), EC);
257 if (Magic == file_magic::coff_object) {
258 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
260 return BinaryOrErr.takeError();
262 IF.CoffObject = std::move(*BinaryOrErr);
263 IF.PdbOrObj = llvm::cast<COFFObjectFile>(IF.CoffObject.getBinary());
264 return std::move(IF);
267 if (Magic == file_magic::pdb) {
268 std::unique_ptr<IPDBSession> Session;
269 if (auto Err = loadDataForPDB(PDB_ReaderType::Native, Path, Session))
270 return std::move(Err);
272 IF.PdbSession.reset(static_cast<NativeSession *>(Session.release()));
273 IF.PdbOrObj = &IF.PdbSession->getPDBFile();
275 return std::move(IF);
278 if (!AllowUnknownFile)
279 return make_error<StringError>(
280 formatv("File {0} is not a supported file type", Path),
281 inconvertibleErrorCode());
283 auto Result = MemoryBuffer::getFile(Path, -1LL, false);
285 return make_error<StringError>(
286 formatv("File {0} could not be opened", Path), Result.getError());
288 IF.UnknownFile = std::move(*Result);
289 IF.PdbOrObj = IF.UnknownFile.get();
290 return std::move(IF);
293 PDBFile &InputFile::pdb() {
295 return *PdbOrObj.get<PDBFile *>();
298 const PDBFile &InputFile::pdb() const {
300 return *PdbOrObj.get<PDBFile *>();
303 object::COFFObjectFile &InputFile::obj() {
305 return *PdbOrObj.get<object::COFFObjectFile *>();
308 const object::COFFObjectFile &InputFile::obj() const {
310 return *PdbOrObj.get<object::COFFObjectFile *>();
313 MemoryBuffer &InputFile::unknown() {
315 return *PdbOrObj.get<MemoryBuffer *>();
318 const MemoryBuffer &InputFile::unknown() const {
320 return *PdbOrObj.get<MemoryBuffer *>();
323 StringRef InputFile::getFilePath() const {
325 return pdb().getFilePath();
327 return obj().getFileName();
329 return unknown().getBufferIdentifier();
332 bool InputFile::hasTypes() const {
334 return pdb().hasPDBTpiStream();
336 for (const auto &Section : obj().sections()) {
338 if (isDebugTSection(Section, Types))
344 bool InputFile::hasIds() const {
347 return pdb().hasPDBIpiStream();
350 bool InputFile::isPdb() const { return PdbOrObj.is<PDBFile *>(); }
352 bool InputFile::isObj() const {
353 return PdbOrObj.is<object::COFFObjectFile *>();
356 bool InputFile::isUnknown() const { return PdbOrObj.is<MemoryBuffer *>(); }
358 codeview::LazyRandomTypeCollection &
359 InputFile::getOrCreateTypeCollection(TypeCollectionKind Kind) {
360 if (Types && Kind == kTypes)
362 if (Ids && Kind == kIds)
366 assert(isPdb() && pdb().hasPDBIpiStream());
369 // If the collection was already initialized, we should have just returned it
372 TypeCollectionPtr &Collection = (Kind == kIds) ? Ids : Types;
373 auto &Stream = cantFail((Kind == kIds) ? pdb().getPDBIpiStream()
374 : pdb().getPDBTpiStream());
376 auto &Array = Stream.typeArray();
377 uint32_t Count = Stream.getNumTypeRecords();
378 auto Offsets = Stream.getTypeIndexOffsets();
380 llvm::make_unique<LazyRandomTypeCollection>(Array, Count, Offsets);
385 assert(Kind == kTypes);
388 for (const auto &Section : obj().sections()) {
390 if (!isDebugTSection(Section, Records))
393 Types = llvm::make_unique<LazyRandomTypeCollection>(Records, 100);
397 Types = llvm::make_unique<LazyRandomTypeCollection>(100);
401 codeview::LazyRandomTypeCollection &InputFile::types() {
402 return getOrCreateTypeCollection(kTypes);
405 codeview::LazyRandomTypeCollection &InputFile::ids() {
406 // Object files have only one type stream that contains both types and ids.
407 // Similarly, some PDBs don't contain an IPI stream, and for those both types
408 // and IDs are in the same stream.
409 if (isObj() || !pdb().hasPDBIpiStream())
412 return getOrCreateTypeCollection(kIds);
415 iterator_range<SymbolGroupIterator> InputFile::symbol_groups() {
416 return make_range<SymbolGroupIterator>(symbol_groups_begin(),
417 symbol_groups_end());
420 SymbolGroupIterator InputFile::symbol_groups_begin() {
421 return SymbolGroupIterator(*this);
424 SymbolGroupIterator InputFile::symbol_groups_end() {
425 return SymbolGroupIterator();
428 SymbolGroupIterator::SymbolGroupIterator() : Value(nullptr) {}
430 SymbolGroupIterator::SymbolGroupIterator(InputFile &File) : Value(&File) {
432 SectionIter = File.obj().section_begin();
437 bool SymbolGroupIterator::operator==(const SymbolGroupIterator &R) const {
443 if (Value.File != R.Value.File)
445 return Index == R.Index;
448 const SymbolGroup &SymbolGroupIterator::operator*() const {
452 SymbolGroup &SymbolGroupIterator::operator*() {
457 SymbolGroupIterator &SymbolGroupIterator::operator++() {
458 assert(Value.File && !isEnd());
463 if (Value.File->isPdb()) {
464 Value.updatePdbModi(Index);
472 void SymbolGroupIterator::scanToNextDebugS() {
473 assert(SectionIter.hasValue());
474 auto End = Value.File->obj().section_end();
475 auto &Iter = *SectionIter;
478 while (++Iter != End) {
479 DebugSubsectionArray SS;
480 SectionRef SR = *Iter;
481 if (!isDebugSSection(SR, SS))
484 Value.updateDebugS(SS);
489 bool SymbolGroupIterator::isEnd() const {
492 if (Value.File->isPdb()) {
493 auto &Dbi = cantFail(Value.File->pdb().getPDBDbiStream());
494 uint32_t Count = Dbi.modules().getModuleCount();
495 assert(Index <= Count);
496 return Index == Count;
499 assert(SectionIter.hasValue());
500 return *SectionIter == Value.File->obj().section_end();