InputFile.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. //===- InputFile.cpp ------------------------------------------ *- C++ --*-===//
  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. #include "InputFile.h"
  9. #include "FormatUtil.h"
  10. #include "LinePrinter.h"
  11. #include "llvm/BinaryFormat/Magic.h"
  12. #include "llvm/DebugInfo/CodeView/CodeView.h"
  13. #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
  14. #include "llvm/DebugInfo/CodeView/StringsAndChecksums.h"
  15. #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
  16. #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
  17. #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
  18. #include "llvm/DebugInfo/PDB/Native/PDBStringTable.h"
  19. #include "llvm/DebugInfo/PDB/Native/RawError.h"
  20. #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
  21. #include "llvm/DebugInfo/PDB/PDB.h"
  22. #include "llvm/Object/COFF.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/FormatVariadic.h"
  25. using namespace llvm;
  26. using namespace llvm::codeview;
  27. using namespace llvm::object;
  28. using namespace llvm::pdb;
  29. InputFile::InputFile() {}
  30. InputFile::~InputFile() {}
  31. static Expected<ModuleDebugStreamRef>
  32. getModuleDebugStream(PDBFile &File, StringRef &ModuleName, uint32_t Index) {
  33. ExitOnError Err("Unexpected error: ");
  34. auto &Dbi = Err(File.getPDBDbiStream());
  35. const auto &Modules = Dbi.modules();
  36. if (Index >= Modules.getModuleCount())
  37. return make_error<RawError>(raw_error_code::index_out_of_bounds,
  38. "Invalid module index");
  39. auto Modi = Modules.getModuleDescriptor(Index);
  40. ModuleName = Modi.getModuleName();
  41. uint16_t ModiStream = Modi.getModuleStreamIndex();
  42. if (ModiStream == kInvalidStreamIndex)
  43. return make_error<RawError>(raw_error_code::no_stream,
  44. "Module stream not present");
  45. auto ModStreamData = File.createIndexedStream(ModiStream);
  46. ModuleDebugStreamRef ModS(Modi, std::move(ModStreamData));
  47. if (auto EC = ModS.reload())
  48. return make_error<RawError>(raw_error_code::corrupt_file,
  49. "Invalid module stream");
  50. return std::move(ModS);
  51. }
  52. static inline bool isCodeViewDebugSubsection(object::SectionRef Section,
  53. StringRef Name,
  54. BinaryStreamReader &Reader) {
  55. if (Expected<StringRef> NameOrErr = Section.getName()) {
  56. if (*NameOrErr != Name)
  57. return false;
  58. } else {
  59. consumeError(NameOrErr.takeError());
  60. return false;
  61. }
  62. Expected<StringRef> ContentsOrErr = Section.getContents();
  63. if (!ContentsOrErr) {
  64. consumeError(ContentsOrErr.takeError());
  65. return false;
  66. }
  67. Reader = BinaryStreamReader(*ContentsOrErr, support::little);
  68. uint32_t Magic;
  69. if (Reader.bytesRemaining() < sizeof(uint32_t))
  70. return false;
  71. cantFail(Reader.readInteger(Magic));
  72. if (Magic != COFF::DEBUG_SECTION_MAGIC)
  73. return false;
  74. return true;
  75. }
  76. static inline bool isDebugSSection(object::SectionRef Section,
  77. DebugSubsectionArray &Subsections) {
  78. BinaryStreamReader Reader;
  79. if (!isCodeViewDebugSubsection(Section, ".debug$S", Reader))
  80. return false;
  81. cantFail(Reader.readArray(Subsections, Reader.bytesRemaining()));
  82. return true;
  83. }
  84. static bool isDebugTSection(SectionRef Section, CVTypeArray &Types) {
  85. BinaryStreamReader Reader;
  86. if (!isCodeViewDebugSubsection(Section, ".debug$T", Reader) &&
  87. !isCodeViewDebugSubsection(Section, ".debug$P", Reader))
  88. return false;
  89. cantFail(Reader.readArray(Types, Reader.bytesRemaining()));
  90. return true;
  91. }
  92. static std::string formatChecksumKind(FileChecksumKind Kind) {
  93. switch (Kind) {
  94. RETURN_CASE(FileChecksumKind, None, "None");
  95. RETURN_CASE(FileChecksumKind, MD5, "MD5");
  96. RETURN_CASE(FileChecksumKind, SHA1, "SHA-1");
  97. RETURN_CASE(FileChecksumKind, SHA256, "SHA-256");
  98. }
  99. return formatUnknownEnum(Kind);
  100. }
  101. template <typename... Args>
  102. static void formatInternal(LinePrinter &Printer, bool Append, Args &&... args) {
  103. if (Append)
  104. Printer.format(std::forward<Args>(args)...);
  105. else
  106. Printer.formatLine(std::forward<Args>(args)...);
  107. }
  108. SymbolGroup::SymbolGroup(InputFile *File, uint32_t GroupIndex) : File(File) {
  109. if (!File)
  110. return;
  111. if (File->isPdb())
  112. initializeForPdb(GroupIndex);
  113. else {
  114. Name = ".debug$S";
  115. uint32_t I = 0;
  116. for (const auto &S : File->obj().sections()) {
  117. DebugSubsectionArray SS;
  118. if (!isDebugSSection(S, SS))
  119. continue;
  120. if (!SC.hasChecksums() || !SC.hasStrings())
  121. SC.initialize(SS);
  122. if (I == GroupIndex)
  123. Subsections = SS;
  124. if (SC.hasChecksums() && SC.hasStrings())
  125. break;
  126. }
  127. rebuildChecksumMap();
  128. }
  129. }
  130. StringRef SymbolGroup::name() const { return Name; }
  131. void SymbolGroup::updateDebugS(const codeview::DebugSubsectionArray &SS) {
  132. Subsections = SS;
  133. }
  134. void SymbolGroup::updatePdbModi(uint32_t Modi) { initializeForPdb(Modi); }
  135. void SymbolGroup::initializeForPdb(uint32_t Modi) {
  136. assert(File && File->isPdb());
  137. // PDB always uses the same string table, but each module has its own
  138. // checksums. So we only set the strings if they're not already set.
  139. if (!SC.hasStrings()) {
  140. auto StringTable = File->pdb().getStringTable();
  141. if (StringTable)
  142. SC.setStrings(StringTable->getStringTable());
  143. else
  144. consumeError(StringTable.takeError());
  145. }
  146. SC.resetChecksums();
  147. auto MDS = getModuleDebugStream(File->pdb(), Name, Modi);
  148. if (!MDS) {
  149. consumeError(MDS.takeError());
  150. return;
  151. }
  152. DebugStream = std::make_shared<ModuleDebugStreamRef>(std::move(*MDS));
  153. Subsections = DebugStream->getSubsectionsArray();
  154. SC.initialize(Subsections);
  155. rebuildChecksumMap();
  156. }
  157. void SymbolGroup::rebuildChecksumMap() {
  158. if (!SC.hasChecksums())
  159. return;
  160. for (const auto &Entry : SC.checksums()) {
  161. auto S = SC.strings().getString(Entry.FileNameOffset);
  162. if (!S)
  163. continue;
  164. ChecksumsByFile[*S] = Entry;
  165. }
  166. }
  167. const ModuleDebugStreamRef &SymbolGroup::getPdbModuleStream() const {
  168. assert(File && File->isPdb() && DebugStream);
  169. return *DebugStream;
  170. }
  171. Expected<StringRef> SymbolGroup::getNameFromStringTable(uint32_t Offset) const {
  172. return SC.strings().getString(Offset);
  173. }
  174. void SymbolGroup::formatFromFileName(LinePrinter &Printer, StringRef File,
  175. bool Append) const {
  176. auto FC = ChecksumsByFile.find(File);
  177. if (FC == ChecksumsByFile.end()) {
  178. formatInternal(Printer, Append, "- (no checksum) {0}", File);
  179. return;
  180. }
  181. formatInternal(Printer, Append, "- ({0}: {1}) {2}",
  182. formatChecksumKind(FC->getValue().Kind),
  183. toHex(FC->getValue().Checksum), File);
  184. }
  185. void SymbolGroup::formatFromChecksumsOffset(LinePrinter &Printer,
  186. uint32_t Offset,
  187. bool Append) const {
  188. if (!SC.hasChecksums()) {
  189. formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
  190. return;
  191. }
  192. auto Iter = SC.checksums().getArray().at(Offset);
  193. if (Iter == SC.checksums().getArray().end()) {
  194. formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
  195. return;
  196. }
  197. uint32_t FO = Iter->FileNameOffset;
  198. auto ExpectedFile = getNameFromStringTable(FO);
  199. if (!ExpectedFile) {
  200. formatInternal(Printer, Append, "(unknown file name offset {0})", Offset);
  201. consumeError(ExpectedFile.takeError());
  202. return;
  203. }
  204. if (Iter->Kind == FileChecksumKind::None) {
  205. formatInternal(Printer, Append, "{0} (no checksum)", *ExpectedFile);
  206. } else {
  207. formatInternal(Printer, Append, "{0} ({1}: {2})", *ExpectedFile,
  208. formatChecksumKind(Iter->Kind), toHex(Iter->Checksum));
  209. }
  210. }
  211. Expected<InputFile> InputFile::open(StringRef Path, bool AllowUnknownFile) {
  212. InputFile IF;
  213. if (!llvm::sys::fs::exists(Path))
  214. return make_error<StringError>(formatv("File {0} not found", Path),
  215. inconvertibleErrorCode());
  216. file_magic Magic;
  217. if (auto EC = identify_magic(Path, Magic))
  218. return make_error<StringError>(
  219. formatv("Unable to identify file type for file {0}", Path), EC);
  220. if (Magic == file_magic::coff_object) {
  221. Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
  222. if (!BinaryOrErr)
  223. return BinaryOrErr.takeError();
  224. IF.CoffObject = std::move(*BinaryOrErr);
  225. IF.PdbOrObj = llvm::cast<COFFObjectFile>(IF.CoffObject.getBinary());
  226. return std::move(IF);
  227. }
  228. if (Magic == file_magic::pdb) {
  229. std::unique_ptr<IPDBSession> Session;
  230. if (auto Err = loadDataForPDB(PDB_ReaderType::Native, Path, Session))
  231. return std::move(Err);
  232. IF.PdbSession.reset(static_cast<NativeSession *>(Session.release()));
  233. IF.PdbOrObj = &IF.PdbSession->getPDBFile();
  234. return std::move(IF);
  235. }
  236. if (!AllowUnknownFile)
  237. return make_error<StringError>(
  238. formatv("File {0} is not a supported file type", Path),
  239. inconvertibleErrorCode());
  240. auto Result = MemoryBuffer::getFile(Path, /*IsText=*/false,
  241. /*RequiresNullTerminator=*/false);
  242. if (!Result)
  243. return make_error<StringError>(
  244. formatv("File {0} could not be opened", Path), Result.getError());
  245. IF.UnknownFile = std::move(*Result);
  246. IF.PdbOrObj = IF.UnknownFile.get();
  247. return std::move(IF);
  248. }
  249. PDBFile &InputFile::pdb() {
  250. assert(isPdb());
  251. return *PdbOrObj.get<PDBFile *>();
  252. }
  253. const PDBFile &InputFile::pdb() const {
  254. assert(isPdb());
  255. return *PdbOrObj.get<PDBFile *>();
  256. }
  257. object::COFFObjectFile &InputFile::obj() {
  258. assert(isObj());
  259. return *PdbOrObj.get<object::COFFObjectFile *>();
  260. }
  261. const object::COFFObjectFile &InputFile::obj() const {
  262. assert(isObj());
  263. return *PdbOrObj.get<object::COFFObjectFile *>();
  264. }
  265. MemoryBuffer &InputFile::unknown() {
  266. assert(isUnknown());
  267. return *PdbOrObj.get<MemoryBuffer *>();
  268. }
  269. const MemoryBuffer &InputFile::unknown() const {
  270. assert(isUnknown());
  271. return *PdbOrObj.get<MemoryBuffer *>();
  272. }
  273. StringRef InputFile::getFilePath() const {
  274. if (isPdb())
  275. return pdb().getFilePath();
  276. if (isObj())
  277. return obj().getFileName();
  278. assert(isUnknown());
  279. return unknown().getBufferIdentifier();
  280. }
  281. bool InputFile::hasTypes() const {
  282. if (isPdb())
  283. return pdb().hasPDBTpiStream();
  284. for (const auto &Section : obj().sections()) {
  285. CVTypeArray Types;
  286. if (isDebugTSection(Section, Types))
  287. return true;
  288. }
  289. return false;
  290. }
  291. bool InputFile::hasIds() const {
  292. if (isObj())
  293. return false;
  294. return pdb().hasPDBIpiStream();
  295. }
  296. bool InputFile::isPdb() const { return PdbOrObj.is<PDBFile *>(); }
  297. bool InputFile::isObj() const {
  298. return PdbOrObj.is<object::COFFObjectFile *>();
  299. }
  300. bool InputFile::isUnknown() const { return PdbOrObj.is<MemoryBuffer *>(); }
  301. codeview::LazyRandomTypeCollection &
  302. InputFile::getOrCreateTypeCollection(TypeCollectionKind Kind) {
  303. if (Types && Kind == kTypes)
  304. return *Types;
  305. if (Ids && Kind == kIds)
  306. return *Ids;
  307. if (Kind == kIds) {
  308. assert(isPdb() && pdb().hasPDBIpiStream());
  309. }
  310. // If the collection was already initialized, we should have just returned it
  311. // in step 1.
  312. if (isPdb()) {
  313. TypeCollectionPtr &Collection = (Kind == kIds) ? Ids : Types;
  314. auto &Stream = cantFail((Kind == kIds) ? pdb().getPDBIpiStream()
  315. : pdb().getPDBTpiStream());
  316. auto &Array = Stream.typeArray();
  317. uint32_t Count = Stream.getNumTypeRecords();
  318. auto Offsets = Stream.getTypeIndexOffsets();
  319. Collection =
  320. std::make_unique<LazyRandomTypeCollection>(Array, Count, Offsets);
  321. return *Collection;
  322. }
  323. assert(isObj());
  324. assert(Kind == kTypes);
  325. assert(!Types);
  326. for (const auto &Section : obj().sections()) {
  327. CVTypeArray Records;
  328. if (!isDebugTSection(Section, Records))
  329. continue;
  330. Types = std::make_unique<LazyRandomTypeCollection>(Records, 100);
  331. return *Types;
  332. }
  333. Types = std::make_unique<LazyRandomTypeCollection>(100);
  334. return *Types;
  335. }
  336. codeview::LazyRandomTypeCollection &InputFile::types() {
  337. return getOrCreateTypeCollection(kTypes);
  338. }
  339. codeview::LazyRandomTypeCollection &InputFile::ids() {
  340. // Object files have only one type stream that contains both types and ids.
  341. // Similarly, some PDBs don't contain an IPI stream, and for those both types
  342. // and IDs are in the same stream.
  343. if (isObj() || !pdb().hasPDBIpiStream())
  344. return types();
  345. return getOrCreateTypeCollection(kIds);
  346. }
  347. iterator_range<SymbolGroupIterator> InputFile::symbol_groups() {
  348. return make_range<SymbolGroupIterator>(symbol_groups_begin(),
  349. symbol_groups_end());
  350. }
  351. SymbolGroupIterator InputFile::symbol_groups_begin() {
  352. return SymbolGroupIterator(*this);
  353. }
  354. SymbolGroupIterator InputFile::symbol_groups_end() {
  355. return SymbolGroupIterator();
  356. }
  357. SymbolGroupIterator::SymbolGroupIterator() : Value(nullptr) {}
  358. SymbolGroupIterator::SymbolGroupIterator(InputFile &File) : Value(&File) {
  359. if (File.isObj()) {
  360. SectionIter = File.obj().section_begin();
  361. scanToNextDebugS();
  362. }
  363. }
  364. bool SymbolGroupIterator::operator==(const SymbolGroupIterator &R) const {
  365. bool E = isEnd();
  366. bool RE = R.isEnd();
  367. if (E || RE)
  368. return E == RE;
  369. if (Value.File != R.Value.File)
  370. return false;
  371. return Index == R.Index;
  372. }
  373. const SymbolGroup &SymbolGroupIterator::operator*() const {
  374. assert(!isEnd());
  375. return Value;
  376. }
  377. SymbolGroup &SymbolGroupIterator::operator*() {
  378. assert(!isEnd());
  379. return Value;
  380. }
  381. SymbolGroupIterator &SymbolGroupIterator::operator++() {
  382. assert(Value.File && !isEnd());
  383. ++Index;
  384. if (isEnd())
  385. return *this;
  386. if (Value.File->isPdb()) {
  387. Value.updatePdbModi(Index);
  388. return *this;
  389. }
  390. scanToNextDebugS();
  391. return *this;
  392. }
  393. void SymbolGroupIterator::scanToNextDebugS() {
  394. assert(SectionIter.hasValue());
  395. auto End = Value.File->obj().section_end();
  396. auto &Iter = *SectionIter;
  397. assert(!isEnd());
  398. while (++Iter != End) {
  399. DebugSubsectionArray SS;
  400. SectionRef SR = *Iter;
  401. if (!isDebugSSection(SR, SS))
  402. continue;
  403. Value.updateDebugS(SS);
  404. return;
  405. }
  406. }
  407. bool SymbolGroupIterator::isEnd() const {
  408. if (!Value.File)
  409. return true;
  410. if (Value.File->isPdb()) {
  411. auto &Dbi = cantFail(Value.File->pdb().getPDBDbiStream());
  412. uint32_t Count = Dbi.modules().getModuleCount();
  413. assert(Index <= Count);
  414. return Index == Count;
  415. }
  416. assert(SectionIter.hasValue());
  417. return *SectionIter == Value.File->obj().section_end();
  418. }