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 if (Index >= Modules.getModuleCount())
45 return make_error<RawError>(raw_error_code::index_out_of_bounds,
46 "Invalid module index");
48 auto Modi = Modules.getModuleDescriptor(Index);
50 ModuleName = Modi.getModuleName();
52 uint16_t ModiStream = Modi.getModuleStreamIndex();
53 if (ModiStream == kInvalidStreamIndex)
54 return make_error<RawError>(raw_error_code::no_stream,
55 "Module stream not present");
57 auto ModStreamData = File.createIndexedStream(ModiStream);
59 ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
60 if (auto EC = ModS.reload())
61 return make_error<RawError>(raw_error_code::corrupt_file,
62 "Invalid module stream");
64 return std::move(ModS);
67 static inline bool isCodeViewDebugSubsection(object::SectionRef Section,
69 BinaryStreamReader &Reader) {
70 StringRef SectionName, Contents;
71 if (Section.getName(SectionName))
74 if (SectionName != Name)
77 if (Section.getContents(Contents))
80 Reader = BinaryStreamReader(Contents, support::little);
82 if (Reader.bytesRemaining() < sizeof(uint32_t))
84 cantFail(Reader.readInteger(Magic));
85 if (Magic != COFF::DEBUG_SECTION_MAGIC)
90 static inline bool isDebugSSection(object::SectionRef Section,
91 DebugSubsectionArray &Subsections) {
92 BinaryStreamReader Reader;
93 if (!isCodeViewDebugSubsection(Section, ".debug$S", Reader))
96 cantFail(Reader.readArray(Subsections, Reader.bytesRemaining()));
100 static bool isDebugTSection(SectionRef Section, CVTypeArray &Types) {
101 BinaryStreamReader Reader;
102 if (!isCodeViewDebugSubsection(Section, ".debug$T", Reader) &&
103 !isCodeViewDebugSubsection(Section, ".debug$P", Reader))
105 cantFail(Reader.readArray(Types, Reader.bytesRemaining()));
109 static std::string formatChecksumKind(FileChecksumKind Kind) {
111 RETURN_CASE(FileChecksumKind, None, "None");
112 RETURN_CASE(FileChecksumKind, MD5, "MD5");
113 RETURN_CASE(FileChecksumKind, SHA1, "SHA-1");
114 RETURN_CASE(FileChecksumKind, SHA256, "SHA-256");
116 return formatUnknownEnum(Kind);
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 auto StringTable = File->pdb().getStringTable();
170 SC.setStrings(StringTable->getStringTable());
172 consumeError(StringTable.takeError());
176 auto MDS = getModuleDebugStream(File->pdb(), Name, Modi);
178 consumeError(MDS.takeError());
182 DebugStream = std::make_shared<ModuleDebugStreamRef>(std::move(*MDS));
183 Subsections = DebugStream->getSubsectionsArray();
184 SC.initialize(Subsections);
185 rebuildChecksumMap();
188 void SymbolGroup::rebuildChecksumMap() {
189 if (!SC.hasChecksums())
192 for (const auto &Entry : SC.checksums()) {
193 auto S = SC.strings().getString(Entry.FileNameOffset);
196 ChecksumsByFile[*S] = Entry;
200 const ModuleDebugStreamRef &SymbolGroup::getPdbModuleStream() const {
201 assert(File && File->isPdb() && DebugStream);
205 Expected<StringRef> SymbolGroup::getNameFromStringTable(uint32_t Offset) const {
206 return SC.strings().getString(Offset);
209 void SymbolGroup::formatFromFileName(LinePrinter &Printer, StringRef File,
211 auto FC = ChecksumsByFile.find(File);
212 if (FC == ChecksumsByFile.end()) {
213 formatInternal(Printer, Append, "- (no checksum) {0}", File);
217 formatInternal(Printer, Append, "- ({0}: {1}) {2}",
218 formatChecksumKind(FC->getValue().Kind),
219 toHex(FC->getValue().Checksum), File);
222 void SymbolGroup::formatFromChecksumsOffset(LinePrinter &Printer,
225 if (!SC.hasChecksums()) {
226 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
230 auto Iter = SC.checksums().getArray().at(Offset);
231 if (Iter == SC.checksums().getArray().end()) {
232 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
236 uint32_t FO = Iter->FileNameOffset;
237 auto ExpectedFile = getNameFromStringTable(FO);
239 formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
240 consumeError(ExpectedFile.takeError());
243 if (Iter->Kind == FileChecksumKind::None) {
244 formatInternal(Printer, Append, "{0} (no checksum)", *ExpectedFile);
246 formatInternal(Printer, Append, "{0} ({1}: {2})", *ExpectedFile,
247 formatChecksumKind(Iter->Kind), toHex(Iter->Checksum));
251 Expected<InputFile> InputFile::open(StringRef Path, bool AllowUnknownFile) {
253 if (!llvm::sys::fs::exists(Path))
254 return make_error<StringError>(formatv("File {0} not found", Path),
255 inconvertibleErrorCode());
258 if (auto EC = identify_magic(Path, Magic))
259 return make_error<StringError>(
260 formatv("Unable to identify file type for file {0}", Path), EC);
262 if (Magic == file_magic::coff_object) {
263 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
265 return BinaryOrErr.takeError();
267 IF.CoffObject = std::move(*BinaryOrErr);
268 IF.PdbOrObj = llvm::cast<COFFObjectFile>(IF.CoffObject.getBinary());
269 return std::move(IF);
272 if (Magic == file_magic::pdb) {
273 std::unique_ptr<IPDBSession> Session;
274 if (auto Err = loadDataForPDB(PDB_ReaderType::Native, Path, Session))
275 return std::move(Err);
277 IF.PdbSession.reset(static_cast<NativeSession *>(Session.release()));
278 IF.PdbOrObj = &IF.PdbSession->getPDBFile();
280 return std::move(IF);
283 if (!AllowUnknownFile)
284 return make_error<StringError>(
285 formatv("File {0} is not a supported file type", Path),
286 inconvertibleErrorCode());
288 auto Result = MemoryBuffer::getFile(Path, -1LL, false);
290 return make_error<StringError>(
291 formatv("File {0} could not be opened", Path), Result.getError());
293 IF.UnknownFile = std::move(*Result);
294 IF.PdbOrObj = IF.UnknownFile.get();
295 return std::move(IF);
298 PDBFile &InputFile::pdb() {
300 return *PdbOrObj.get<PDBFile *>();
303 const PDBFile &InputFile::pdb() const {
305 return *PdbOrObj.get<PDBFile *>();
308 object::COFFObjectFile &InputFile::obj() {
310 return *PdbOrObj.get<object::COFFObjectFile *>();
313 const object::COFFObjectFile &InputFile::obj() const {
315 return *PdbOrObj.get<object::COFFObjectFile *>();
318 MemoryBuffer &InputFile::unknown() {
320 return *PdbOrObj.get<MemoryBuffer *>();
323 const MemoryBuffer &InputFile::unknown() const {
325 return *PdbOrObj.get<MemoryBuffer *>();
328 StringRef InputFile::getFilePath() const {
330 return pdb().getFilePath();
332 return obj().getFileName();
334 return unknown().getBufferIdentifier();
337 bool InputFile::hasTypes() const {
339 return pdb().hasPDBTpiStream();
341 for (const auto &Section : obj().sections()) {
343 if (isDebugTSection(Section, Types))
349 bool InputFile::hasIds() const {
352 return pdb().hasPDBIpiStream();
355 bool InputFile::isPdb() const { return PdbOrObj.is<PDBFile *>(); }
357 bool InputFile::isObj() const {
358 return PdbOrObj.is<object::COFFObjectFile *>();
361 bool InputFile::isUnknown() const { return PdbOrObj.is<MemoryBuffer *>(); }
363 codeview::LazyRandomTypeCollection &
364 InputFile::getOrCreateTypeCollection(TypeCollectionKind Kind) {
365 if (Types && Kind == kTypes)
367 if (Ids && Kind == kIds)
371 assert(isPdb() && pdb().hasPDBIpiStream());
374 // If the collection was already initialized, we should have just returned it
377 TypeCollectionPtr &Collection = (Kind == kIds) ? Ids : Types;
378 auto &Stream = cantFail((Kind == kIds) ? pdb().getPDBIpiStream()
379 : pdb().getPDBTpiStream());
381 auto &Array = Stream.typeArray();
382 uint32_t Count = Stream.getNumTypeRecords();
383 auto Offsets = Stream.getTypeIndexOffsets();
385 llvm::make_unique<LazyRandomTypeCollection>(Array, Count, Offsets);
390 assert(Kind == kTypes);
393 for (const auto &Section : obj().sections()) {
395 if (!isDebugTSection(Section, Records))
398 Types = llvm::make_unique<LazyRandomTypeCollection>(Records, 100);
402 Types = llvm::make_unique<LazyRandomTypeCollection>(100);
406 codeview::LazyRandomTypeCollection &InputFile::types() {
407 return getOrCreateTypeCollection(kTypes);
410 codeview::LazyRandomTypeCollection &InputFile::ids() {
411 // Object files have only one type stream that contains both types and ids.
412 // Similarly, some PDBs don't contain an IPI stream, and for those both types
413 // and IDs are in the same stream.
414 if (isObj() || !pdb().hasPDBIpiStream())
417 return getOrCreateTypeCollection(kIds);
420 iterator_range<SymbolGroupIterator> InputFile::symbol_groups() {
421 return make_range<SymbolGroupIterator>(symbol_groups_begin(),
422 symbol_groups_end());
425 SymbolGroupIterator InputFile::symbol_groups_begin() {
426 return SymbolGroupIterator(*this);
429 SymbolGroupIterator InputFile::symbol_groups_end() {
430 return SymbolGroupIterator();
433 SymbolGroupIterator::SymbolGroupIterator() : Value(nullptr) {}
435 SymbolGroupIterator::SymbolGroupIterator(InputFile &File) : Value(&File) {
437 SectionIter = File.obj().section_begin();
442 bool SymbolGroupIterator::operator==(const SymbolGroupIterator &R) const {
448 if (Value.File != R.Value.File)
450 return Index == R.Index;
453 const SymbolGroup &SymbolGroupIterator::operator*() const {
457 SymbolGroup &SymbolGroupIterator::operator*() {
462 SymbolGroupIterator &SymbolGroupIterator::operator++() {
463 assert(Value.File && !isEnd());
468 if (Value.File->isPdb()) {
469 Value.updatePdbModi(Index);
477 void SymbolGroupIterator::scanToNextDebugS() {
478 assert(SectionIter.hasValue());
479 auto End = Value.File->obj().section_end();
480 auto &Iter = *SectionIter;
483 while (++Iter != End) {
484 DebugSubsectionArray SS;
485 SectionRef SR = *Iter;
486 if (!isDebugSSection(SR, SS))
489 Value.updateDebugS(SS);
494 bool SymbolGroupIterator::isEnd() const {
497 if (Value.File->isPdb()) {
498 auto &Dbi = cantFail(Value.File->pdb().getPDBDbiStream());
499 uint32_t Count = Dbi.modules().getModuleCount();
500 assert(Index <= Count);
501 return Index == Count;
504 assert(SectionIter.hasValue());
505 return *SectionIter == Value.File->obj().section_end();