COFFDumper.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079
  1. //===-- COFFDumper.cpp - COFF-specific dumper -------------------*- 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. ///
  9. /// \file
  10. /// This file implements the COFF-specific dumper for llvm-readobj.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "ARMWinEHPrinter.h"
  14. #include "ObjDumper.h"
  15. #include "StackMapPrinter.h"
  16. #include "Win64EHDumper.h"
  17. #include "llvm-readobj.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/BinaryFormat/COFF.h"
  22. #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
  23. #include "llvm/DebugInfo/CodeView/CodeView.h"
  24. #include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
  25. #include "llvm/DebugInfo/CodeView/DebugFrameDataSubsection.h"
  26. #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
  27. #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
  28. #include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
  29. #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
  30. #include "llvm/DebugInfo/CodeView/Line.h"
  31. #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
  32. #include "llvm/DebugInfo/CodeView/RecordSerialization.h"
  33. #include "llvm/DebugInfo/CodeView/SymbolDumpDelegate.h"
  34. #include "llvm/DebugInfo/CodeView/SymbolDumper.h"
  35. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  36. #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
  37. #include "llvm/DebugInfo/CodeView/TypeHashing.h"
  38. #include "llvm/DebugInfo/CodeView/TypeIndex.h"
  39. #include "llvm/DebugInfo/CodeView/TypeRecord.h"
  40. #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
  41. #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
  42. #include "llvm/Object/COFF.h"
  43. #include "llvm/Object/ObjectFile.h"
  44. #include "llvm/Object/WindowsResource.h"
  45. #include "llvm/Support/BinaryStreamReader.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/Compiler.h"
  48. #include "llvm/Support/ConvertUTF.h"
  49. #include "llvm/Support/FormatVariadic.h"
  50. #include "llvm/Support/LEB128.h"
  51. #include "llvm/Support/ScopedPrinter.h"
  52. #include "llvm/Support/Win64EH.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include <ctime>
  55. using namespace llvm;
  56. using namespace llvm::object;
  57. using namespace llvm::codeview;
  58. using namespace llvm::support;
  59. using namespace llvm::Win64EH;
  60. namespace {
  61. struct LoadConfigTables {
  62. uint64_t SEHTableVA = 0;
  63. uint64_t SEHTableCount = 0;
  64. uint32_t GuardFlags = 0;
  65. uint64_t GuardFidTableVA = 0;
  66. uint64_t GuardFidTableCount = 0;
  67. uint64_t GuardIatTableVA = 0;
  68. uint64_t GuardIatTableCount = 0;
  69. uint64_t GuardLJmpTableVA = 0;
  70. uint64_t GuardLJmpTableCount = 0;
  71. uint64_t GuardEHContTableVA = 0;
  72. uint64_t GuardEHContTableCount = 0;
  73. };
  74. class COFFDumper : public ObjDumper {
  75. public:
  76. friend class COFFObjectDumpDelegate;
  77. COFFDumper(const llvm::object::COFFObjectFile *Obj, ScopedPrinter &Writer)
  78. : ObjDumper(Writer, Obj->getFileName()), Obj(Obj), Writer(Writer),
  79. Types(100) {}
  80. void printFileHeaders() override;
  81. void printSectionHeaders() override;
  82. void printRelocations() override;
  83. void printUnwindInfo() override;
  84. void printNeededLibraries() override;
  85. void printCOFFImports() override;
  86. void printCOFFExports() override;
  87. void printCOFFDirectives() override;
  88. void printCOFFBaseReloc() override;
  89. void printCOFFDebugDirectory() override;
  90. void printCOFFTLSDirectory() override;
  91. void printCOFFResources() override;
  92. void printCOFFLoadConfig() override;
  93. void printCodeViewDebugInfo() override;
  94. void mergeCodeViewTypes(llvm::codeview::MergingTypeTableBuilder &CVIDs,
  95. llvm::codeview::MergingTypeTableBuilder &CVTypes,
  96. llvm::codeview::GlobalTypeTableBuilder &GlobalCVIDs,
  97. llvm::codeview::GlobalTypeTableBuilder &GlobalCVTypes,
  98. bool GHash) override;
  99. void printStackMap() const override;
  100. void printAddrsig() override;
  101. void printCGProfile() override;
  102. private:
  103. StringRef getSymbolName(uint32_t Index);
  104. void printSymbols() override;
  105. void printDynamicSymbols() override;
  106. void printSymbol(const SymbolRef &Sym);
  107. void printRelocation(const SectionRef &Section, const RelocationRef &Reloc,
  108. uint64_t Bias = 0);
  109. void printDataDirectory(uint32_t Index, const std::string &FieldName);
  110. void printDOSHeader(const dos_header *DH);
  111. template <class PEHeader> void printPEHeader(const PEHeader *Hdr);
  112. void printBaseOfDataField(const pe32_header *Hdr);
  113. void printBaseOfDataField(const pe32plus_header *Hdr);
  114. template <typename T>
  115. void printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables);
  116. template <typename IntTy>
  117. void printCOFFTLSDirectory(const coff_tls_directory<IntTy> *TlsTable);
  118. typedef void (*PrintExtraCB)(raw_ostream &, const uint8_t *);
  119. void printRVATable(uint64_t TableVA, uint64_t Count, uint64_t EntrySize,
  120. PrintExtraCB PrintExtra = nullptr);
  121. void printCodeViewSymbolSection(StringRef SectionName, const SectionRef &Section);
  122. void printCodeViewTypeSection(StringRef SectionName, const SectionRef &Section);
  123. StringRef getFileNameForFileOffset(uint32_t FileOffset);
  124. void printFileNameForOffset(StringRef Label, uint32_t FileOffset);
  125. void printTypeIndex(StringRef FieldName, TypeIndex TI) {
  126. // Forward to CVTypeDumper for simplicity.
  127. codeview::printTypeIndex(Writer, FieldName, TI, Types);
  128. }
  129. void printCodeViewSymbolsSubsection(StringRef Subsection,
  130. const SectionRef &Section,
  131. StringRef SectionContents);
  132. void printCodeViewFileChecksums(StringRef Subsection);
  133. void printCodeViewInlineeLines(StringRef Subsection);
  134. void printRelocatedField(StringRef Label, const coff_section *Sec,
  135. uint32_t RelocOffset, uint32_t Offset,
  136. StringRef *RelocSym = nullptr);
  137. uint32_t countTotalTableEntries(ResourceSectionRef RSF,
  138. const coff_resource_dir_table &Table,
  139. StringRef Level);
  140. void printResourceDirectoryTable(ResourceSectionRef RSF,
  141. const coff_resource_dir_table &Table,
  142. StringRef Level);
  143. void printBinaryBlockWithRelocs(StringRef Label, const SectionRef &Sec,
  144. StringRef SectionContents, StringRef Block);
  145. /// Given a .debug$S section, find the string table and file checksum table.
  146. void initializeFileAndStringTables(BinaryStreamReader &Reader);
  147. void cacheRelocations();
  148. std::error_code resolveSymbol(const coff_section *Section, uint64_t Offset,
  149. SymbolRef &Sym);
  150. std::error_code resolveSymbolName(const coff_section *Section,
  151. uint64_t Offset, StringRef &Name);
  152. std::error_code resolveSymbolName(const coff_section *Section,
  153. StringRef SectionContents,
  154. const void *RelocPtr, StringRef &Name);
  155. void printImportedSymbols(iterator_range<imported_symbol_iterator> Range);
  156. void printDelayImportedSymbols(
  157. const DelayImportDirectoryEntryRef &I,
  158. iterator_range<imported_symbol_iterator> Range);
  159. typedef DenseMap<const coff_section*, std::vector<RelocationRef> > RelocMapTy;
  160. const llvm::object::COFFObjectFile *Obj;
  161. bool RelocCached = false;
  162. RelocMapTy RelocMap;
  163. DebugChecksumsSubsectionRef CVFileChecksumTable;
  164. DebugStringTableSubsectionRef CVStringTable;
  165. /// Track the compilation CPU type. S_COMPILE3 symbol records typically come
  166. /// first, but if we don't see one, just assume an X64 CPU type. It is common.
  167. CPUType CompilationCPUType = CPUType::X64;
  168. ScopedPrinter &Writer;
  169. BinaryByteStream TypeContents;
  170. LazyRandomTypeCollection Types;
  171. };
  172. class COFFObjectDumpDelegate : public SymbolDumpDelegate {
  173. public:
  174. COFFObjectDumpDelegate(COFFDumper &CD, const SectionRef &SR,
  175. const COFFObjectFile *Obj, StringRef SectionContents)
  176. : CD(CD), SR(SR), SectionContents(SectionContents) {
  177. Sec = Obj->getCOFFSection(SR);
  178. }
  179. uint32_t getRecordOffset(BinaryStreamReader Reader) override {
  180. ArrayRef<uint8_t> Data;
  181. if (auto EC = Reader.readLongestContiguousChunk(Data)) {
  182. llvm::consumeError(std::move(EC));
  183. return 0;
  184. }
  185. return Data.data() - SectionContents.bytes_begin();
  186. }
  187. void printRelocatedField(StringRef Label, uint32_t RelocOffset,
  188. uint32_t Offset, StringRef *RelocSym) override {
  189. CD.printRelocatedField(Label, Sec, RelocOffset, Offset, RelocSym);
  190. }
  191. void printBinaryBlockWithRelocs(StringRef Label,
  192. ArrayRef<uint8_t> Block) override {
  193. StringRef SBlock(reinterpret_cast<const char *>(Block.data()),
  194. Block.size());
  195. if (opts::CodeViewSubsectionBytes)
  196. CD.printBinaryBlockWithRelocs(Label, SR, SectionContents, SBlock);
  197. }
  198. StringRef getFileNameForFileOffset(uint32_t FileOffset) override {
  199. return CD.getFileNameForFileOffset(FileOffset);
  200. }
  201. DebugStringTableSubsectionRef getStringTable() override {
  202. return CD.CVStringTable;
  203. }
  204. private:
  205. COFFDumper &CD;
  206. const SectionRef &SR;
  207. const coff_section *Sec;
  208. StringRef SectionContents;
  209. };
  210. } // end namespace
  211. namespace llvm {
  212. std::unique_ptr<ObjDumper> createCOFFDumper(const object::COFFObjectFile &Obj,
  213. ScopedPrinter &Writer) {
  214. return std::make_unique<COFFDumper>(&Obj, Writer);
  215. }
  216. } // namespace llvm
  217. // Given a section and an offset into this section the function returns the
  218. // symbol used for the relocation at the offset.
  219. std::error_code COFFDumper::resolveSymbol(const coff_section *Section,
  220. uint64_t Offset, SymbolRef &Sym) {
  221. cacheRelocations();
  222. const auto &Relocations = RelocMap[Section];
  223. auto SymI = Obj->symbol_end();
  224. for (const auto &Relocation : Relocations) {
  225. uint64_t RelocationOffset = Relocation.getOffset();
  226. if (RelocationOffset == Offset) {
  227. SymI = Relocation.getSymbol();
  228. break;
  229. }
  230. }
  231. if (SymI == Obj->symbol_end())
  232. return inconvertibleErrorCode();
  233. Sym = *SymI;
  234. return std::error_code();
  235. }
  236. // Given a section and an offset into this section the function returns the name
  237. // of the symbol used for the relocation at the offset.
  238. std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
  239. uint64_t Offset,
  240. StringRef &Name) {
  241. SymbolRef Symbol;
  242. if (std::error_code EC = resolveSymbol(Section, Offset, Symbol))
  243. return EC;
  244. Expected<StringRef> NameOrErr = Symbol.getName();
  245. if (!NameOrErr)
  246. return errorToErrorCode(NameOrErr.takeError());
  247. Name = *NameOrErr;
  248. return std::error_code();
  249. }
  250. // Helper for when you have a pointer to real data and you want to know about
  251. // relocations against it.
  252. std::error_code COFFDumper::resolveSymbolName(const coff_section *Section,
  253. StringRef SectionContents,
  254. const void *RelocPtr,
  255. StringRef &Name) {
  256. assert(SectionContents.data() < RelocPtr &&
  257. RelocPtr < SectionContents.data() + SectionContents.size() &&
  258. "pointer to relocated object is not in section");
  259. uint64_t Offset = ptrdiff_t(reinterpret_cast<const char *>(RelocPtr) -
  260. SectionContents.data());
  261. return resolveSymbolName(Section, Offset, Name);
  262. }
  263. void COFFDumper::printRelocatedField(StringRef Label, const coff_section *Sec,
  264. uint32_t RelocOffset, uint32_t Offset,
  265. StringRef *RelocSym) {
  266. StringRef SymStorage;
  267. StringRef &Symbol = RelocSym ? *RelocSym : SymStorage;
  268. if (!resolveSymbolName(Sec, RelocOffset, Symbol))
  269. W.printSymbolOffset(Label, Symbol, Offset);
  270. else
  271. W.printHex(Label, RelocOffset);
  272. }
  273. void COFFDumper::printBinaryBlockWithRelocs(StringRef Label,
  274. const SectionRef &Sec,
  275. StringRef SectionContents,
  276. StringRef Block) {
  277. W.printBinaryBlock(Label, Block);
  278. assert(SectionContents.begin() < Block.begin() &&
  279. SectionContents.end() >= Block.end() &&
  280. "Block is not contained in SectionContents");
  281. uint64_t OffsetStart = Block.data() - SectionContents.data();
  282. uint64_t OffsetEnd = OffsetStart + Block.size();
  283. W.flush();
  284. cacheRelocations();
  285. ListScope D(W, "BlockRelocations");
  286. const coff_section *Section = Obj->getCOFFSection(Sec);
  287. const auto &Relocations = RelocMap[Section];
  288. for (const auto &Relocation : Relocations) {
  289. uint64_t RelocationOffset = Relocation.getOffset();
  290. if (OffsetStart <= RelocationOffset && RelocationOffset < OffsetEnd)
  291. printRelocation(Sec, Relocation, OffsetStart);
  292. }
  293. }
  294. const EnumEntry<COFF::MachineTypes> ImageFileMachineType[] = {
  295. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_UNKNOWN ),
  296. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AM33 ),
  297. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_AMD64 ),
  298. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM ),
  299. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARM64 ),
  300. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_ARMNT ),
  301. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_EBC ),
  302. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_I386 ),
  303. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_IA64 ),
  304. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_M32R ),
  305. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPS16 ),
  306. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU ),
  307. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_MIPSFPU16),
  308. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPC ),
  309. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_POWERPCFP),
  310. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_R4000 ),
  311. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3 ),
  312. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH3DSP ),
  313. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH4 ),
  314. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_SH5 ),
  315. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_THUMB ),
  316. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_MACHINE_WCEMIPSV2)
  317. };
  318. const EnumEntry<COFF::Characteristics> ImageFileCharacteristics[] = {
  319. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_RELOCS_STRIPPED ),
  320. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_EXECUTABLE_IMAGE ),
  321. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LINE_NUMS_STRIPPED ),
  322. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LOCAL_SYMS_STRIPPED ),
  323. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_AGGRESSIVE_WS_TRIM ),
  324. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_LARGE_ADDRESS_AWARE ),
  325. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_LO ),
  326. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_32BIT_MACHINE ),
  327. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DEBUG_STRIPPED ),
  328. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP),
  329. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_NET_RUN_FROM_SWAP ),
  330. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_SYSTEM ),
  331. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_DLL ),
  332. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_UP_SYSTEM_ONLY ),
  333. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_FILE_BYTES_REVERSED_HI )
  334. };
  335. const EnumEntry<COFF::WindowsSubsystem> PEWindowsSubsystem[] = {
  336. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_UNKNOWN ),
  337. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_NATIVE ),
  338. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_GUI ),
  339. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CUI ),
  340. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_POSIX_CUI ),
  341. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI ),
  342. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_APPLICATION ),
  343. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER),
  344. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER ),
  345. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_EFI_ROM ),
  346. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SUBSYSTEM_XBOX ),
  347. };
  348. const EnumEntry<COFF::DLLCharacteristics> PEDLLCharacteristics[] = {
  349. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA ),
  350. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE ),
  351. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY ),
  352. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NX_COMPAT ),
  353. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION ),
  354. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_SEH ),
  355. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_NO_BIND ),
  356. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_APPCONTAINER ),
  357. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER ),
  358. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_GUARD_CF ),
  359. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE),
  360. };
  361. static const EnumEntry<COFF::ExtendedDLLCharacteristics>
  362. PEExtendedDLLCharacteristics[] = {
  363. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_DLL_CHARACTERISTICS_EX_CET_COMPAT),
  364. };
  365. static const EnumEntry<COFF::SectionCharacteristics>
  366. ImageSectionCharacteristics[] = {
  367. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NOLOAD ),
  368. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_TYPE_NO_PAD ),
  369. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_CODE ),
  370. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_INITIALIZED_DATA ),
  371. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_CNT_UNINITIALIZED_DATA),
  372. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_OTHER ),
  373. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_INFO ),
  374. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_REMOVE ),
  375. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_COMDAT ),
  376. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_GPREL ),
  377. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PURGEABLE ),
  378. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_16BIT ),
  379. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_LOCKED ),
  380. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_PRELOAD ),
  381. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1BYTES ),
  382. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2BYTES ),
  383. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4BYTES ),
  384. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8BYTES ),
  385. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_16BYTES ),
  386. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_32BYTES ),
  387. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_64BYTES ),
  388. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_128BYTES ),
  389. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_256BYTES ),
  390. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_512BYTES ),
  391. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_1024BYTES ),
  392. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_2048BYTES ),
  393. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_4096BYTES ),
  394. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_ALIGN_8192BYTES ),
  395. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_LNK_NRELOC_OVFL ),
  396. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_DISCARDABLE ),
  397. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_CACHED ),
  398. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_NOT_PAGED ),
  399. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_SHARED ),
  400. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_EXECUTE ),
  401. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_READ ),
  402. LLVM_READOBJ_ENUM_ENT(COFF, IMAGE_SCN_MEM_WRITE )
  403. };
  404. const EnumEntry<COFF::SymbolBaseType> ImageSymType[] = {
  405. { "Null" , COFF::IMAGE_SYM_TYPE_NULL },
  406. { "Void" , COFF::IMAGE_SYM_TYPE_VOID },
  407. { "Char" , COFF::IMAGE_SYM_TYPE_CHAR },
  408. { "Short" , COFF::IMAGE_SYM_TYPE_SHORT },
  409. { "Int" , COFF::IMAGE_SYM_TYPE_INT },
  410. { "Long" , COFF::IMAGE_SYM_TYPE_LONG },
  411. { "Float" , COFF::IMAGE_SYM_TYPE_FLOAT },
  412. { "Double", COFF::IMAGE_SYM_TYPE_DOUBLE },
  413. { "Struct", COFF::IMAGE_SYM_TYPE_STRUCT },
  414. { "Union" , COFF::IMAGE_SYM_TYPE_UNION },
  415. { "Enum" , COFF::IMAGE_SYM_TYPE_ENUM },
  416. { "MOE" , COFF::IMAGE_SYM_TYPE_MOE },
  417. { "Byte" , COFF::IMAGE_SYM_TYPE_BYTE },
  418. { "Word" , COFF::IMAGE_SYM_TYPE_WORD },
  419. { "UInt" , COFF::IMAGE_SYM_TYPE_UINT },
  420. { "DWord" , COFF::IMAGE_SYM_TYPE_DWORD }
  421. };
  422. const EnumEntry<COFF::SymbolComplexType> ImageSymDType[] = {
  423. { "Null" , COFF::IMAGE_SYM_DTYPE_NULL },
  424. { "Pointer" , COFF::IMAGE_SYM_DTYPE_POINTER },
  425. { "Function", COFF::IMAGE_SYM_DTYPE_FUNCTION },
  426. { "Array" , COFF::IMAGE_SYM_DTYPE_ARRAY }
  427. };
  428. const EnumEntry<COFF::SymbolStorageClass> ImageSymClass[] = {
  429. { "EndOfFunction" , COFF::IMAGE_SYM_CLASS_END_OF_FUNCTION },
  430. { "Null" , COFF::IMAGE_SYM_CLASS_NULL },
  431. { "Automatic" , COFF::IMAGE_SYM_CLASS_AUTOMATIC },
  432. { "External" , COFF::IMAGE_SYM_CLASS_EXTERNAL },
  433. { "Static" , COFF::IMAGE_SYM_CLASS_STATIC },
  434. { "Register" , COFF::IMAGE_SYM_CLASS_REGISTER },
  435. { "ExternalDef" , COFF::IMAGE_SYM_CLASS_EXTERNAL_DEF },
  436. { "Label" , COFF::IMAGE_SYM_CLASS_LABEL },
  437. { "UndefinedLabel" , COFF::IMAGE_SYM_CLASS_UNDEFINED_LABEL },
  438. { "MemberOfStruct" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT },
  439. { "Argument" , COFF::IMAGE_SYM_CLASS_ARGUMENT },
  440. { "StructTag" , COFF::IMAGE_SYM_CLASS_STRUCT_TAG },
  441. { "MemberOfUnion" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_UNION },
  442. { "UnionTag" , COFF::IMAGE_SYM_CLASS_UNION_TAG },
  443. { "TypeDefinition" , COFF::IMAGE_SYM_CLASS_TYPE_DEFINITION },
  444. { "UndefinedStatic", COFF::IMAGE_SYM_CLASS_UNDEFINED_STATIC },
  445. { "EnumTag" , COFF::IMAGE_SYM_CLASS_ENUM_TAG },
  446. { "MemberOfEnum" , COFF::IMAGE_SYM_CLASS_MEMBER_OF_ENUM },
  447. { "RegisterParam" , COFF::IMAGE_SYM_CLASS_REGISTER_PARAM },
  448. { "BitField" , COFF::IMAGE_SYM_CLASS_BIT_FIELD },
  449. { "Block" , COFF::IMAGE_SYM_CLASS_BLOCK },
  450. { "Function" , COFF::IMAGE_SYM_CLASS_FUNCTION },
  451. { "EndOfStruct" , COFF::IMAGE_SYM_CLASS_END_OF_STRUCT },
  452. { "File" , COFF::IMAGE_SYM_CLASS_FILE },
  453. { "Section" , COFF::IMAGE_SYM_CLASS_SECTION },
  454. { "WeakExternal" , COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL },
  455. { "CLRToken" , COFF::IMAGE_SYM_CLASS_CLR_TOKEN }
  456. };
  457. const EnumEntry<COFF::COMDATType> ImageCOMDATSelect[] = {
  458. { "NoDuplicates", COFF::IMAGE_COMDAT_SELECT_NODUPLICATES },
  459. { "Any" , COFF::IMAGE_COMDAT_SELECT_ANY },
  460. { "SameSize" , COFF::IMAGE_COMDAT_SELECT_SAME_SIZE },
  461. { "ExactMatch" , COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH },
  462. { "Associative" , COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE },
  463. { "Largest" , COFF::IMAGE_COMDAT_SELECT_LARGEST },
  464. { "Newest" , COFF::IMAGE_COMDAT_SELECT_NEWEST }
  465. };
  466. const EnumEntry<COFF::DebugType> ImageDebugType[] = {
  467. {"Unknown", COFF::IMAGE_DEBUG_TYPE_UNKNOWN},
  468. {"COFF", COFF::IMAGE_DEBUG_TYPE_COFF},
  469. {"CodeView", COFF::IMAGE_DEBUG_TYPE_CODEVIEW},
  470. {"FPO", COFF::IMAGE_DEBUG_TYPE_FPO},
  471. {"Misc", COFF::IMAGE_DEBUG_TYPE_MISC},
  472. {"Exception", COFF::IMAGE_DEBUG_TYPE_EXCEPTION},
  473. {"Fixup", COFF::IMAGE_DEBUG_TYPE_FIXUP},
  474. {"OmapToSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_TO_SRC},
  475. {"OmapFromSrc", COFF::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC},
  476. {"Borland", COFF::IMAGE_DEBUG_TYPE_BORLAND},
  477. {"Reserved10", COFF::IMAGE_DEBUG_TYPE_RESERVED10},
  478. {"CLSID", COFF::IMAGE_DEBUG_TYPE_CLSID},
  479. {"VCFeature", COFF::IMAGE_DEBUG_TYPE_VC_FEATURE},
  480. {"POGO", COFF::IMAGE_DEBUG_TYPE_POGO},
  481. {"ILTCG", COFF::IMAGE_DEBUG_TYPE_ILTCG},
  482. {"MPX", COFF::IMAGE_DEBUG_TYPE_MPX},
  483. {"Repro", COFF::IMAGE_DEBUG_TYPE_REPRO},
  484. {"ExtendedDLLCharacteristics",
  485. COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS},
  486. };
  487. static const EnumEntry<COFF::WeakExternalCharacteristics>
  488. WeakExternalCharacteristics[] = {
  489. { "NoLibrary", COFF::IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY },
  490. { "Library" , COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY },
  491. { "Alias" , COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS }
  492. };
  493. const EnumEntry<uint32_t> SubSectionTypes[] = {
  494. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Symbols),
  495. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, Lines),
  496. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, StringTable),
  497. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FileChecksums),
  498. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FrameData),
  499. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, InlineeLines),
  500. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeImports),
  501. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CrossScopeExports),
  502. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, ILLines),
  503. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, FuncMDTokenMap),
  504. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, TypeMDTokenMap),
  505. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, MergedAssemblyInput),
  506. LLVM_READOBJ_ENUM_CLASS_ENT(DebugSubsectionKind, CoffSymbolRVA),
  507. };
  508. const EnumEntry<uint32_t> FrameDataFlags[] = {
  509. LLVM_READOBJ_ENUM_ENT(FrameData, HasSEH),
  510. LLVM_READOBJ_ENUM_ENT(FrameData, HasEH),
  511. LLVM_READOBJ_ENUM_ENT(FrameData, IsFunctionStart),
  512. };
  513. const EnumEntry<uint8_t> FileChecksumKindNames[] = {
  514. LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, None),
  515. LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, MD5),
  516. LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA1),
  517. LLVM_READOBJ_ENUM_CLASS_ENT(FileChecksumKind, SHA256),
  518. };
  519. template <typename T>
  520. static std::error_code getSymbolAuxData(const COFFObjectFile *Obj,
  521. COFFSymbolRef Symbol,
  522. uint8_t AuxSymbolIdx, const T *&Aux) {
  523. ArrayRef<uint8_t> AuxData = Obj->getSymbolAuxData(Symbol);
  524. AuxData = AuxData.slice(AuxSymbolIdx * Obj->getSymbolTableEntrySize());
  525. Aux = reinterpret_cast<const T*>(AuxData.data());
  526. return std::error_code();
  527. }
  528. void COFFDumper::cacheRelocations() {
  529. if (RelocCached)
  530. return;
  531. RelocCached = true;
  532. for (const SectionRef &S : Obj->sections()) {
  533. const coff_section *Section = Obj->getCOFFSection(S);
  534. append_range(RelocMap[Section], S.relocations());
  535. // Sort relocations by address.
  536. llvm::sort(RelocMap[Section], [](RelocationRef L, RelocationRef R) {
  537. return L.getOffset() < R.getOffset();
  538. });
  539. }
  540. }
  541. void COFFDumper::printDataDirectory(uint32_t Index,
  542. const std::string &FieldName) {
  543. const data_directory *Data = Obj->getDataDirectory(Index);
  544. if (!Data)
  545. return;
  546. W.printHex(FieldName + "RVA", Data->RelativeVirtualAddress);
  547. W.printHex(FieldName + "Size", Data->Size);
  548. }
  549. void COFFDumper::printFileHeaders() {
  550. time_t TDS = Obj->getTimeDateStamp();
  551. char FormattedTime[20] = { };
  552. strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
  553. {
  554. DictScope D(W, "ImageFileHeader");
  555. W.printEnum ("Machine", Obj->getMachine(),
  556. makeArrayRef(ImageFileMachineType));
  557. W.printNumber("SectionCount", Obj->getNumberOfSections());
  558. W.printHex ("TimeDateStamp", FormattedTime, Obj->getTimeDateStamp());
  559. W.printHex ("PointerToSymbolTable", Obj->getPointerToSymbolTable());
  560. W.printNumber("SymbolCount", Obj->getNumberOfSymbols());
  561. W.printNumber("StringTableSize", Obj->getStringTableSize());
  562. W.printNumber("OptionalHeaderSize", Obj->getSizeOfOptionalHeader());
  563. W.printFlags ("Characteristics", Obj->getCharacteristics(),
  564. makeArrayRef(ImageFileCharacteristics));
  565. }
  566. // Print PE header. This header does not exist if this is an object file and
  567. // not an executable.
  568. if (const pe32_header *PEHeader = Obj->getPE32Header())
  569. printPEHeader<pe32_header>(PEHeader);
  570. if (const pe32plus_header *PEPlusHeader = Obj->getPE32PlusHeader())
  571. printPEHeader<pe32plus_header>(PEPlusHeader);
  572. if (const dos_header *DH = Obj->getDOSHeader())
  573. printDOSHeader(DH);
  574. }
  575. void COFFDumper::printDOSHeader(const dos_header *DH) {
  576. DictScope D(W, "DOSHeader");
  577. W.printString("Magic", StringRef(DH->Magic, sizeof(DH->Magic)));
  578. W.printNumber("UsedBytesInTheLastPage", DH->UsedBytesInTheLastPage);
  579. W.printNumber("FileSizeInPages", DH->FileSizeInPages);
  580. W.printNumber("NumberOfRelocationItems", DH->NumberOfRelocationItems);
  581. W.printNumber("HeaderSizeInParagraphs", DH->HeaderSizeInParagraphs);
  582. W.printNumber("MinimumExtraParagraphs", DH->MinimumExtraParagraphs);
  583. W.printNumber("MaximumExtraParagraphs", DH->MaximumExtraParagraphs);
  584. W.printNumber("InitialRelativeSS", DH->InitialRelativeSS);
  585. W.printNumber("InitialSP", DH->InitialSP);
  586. W.printNumber("Checksum", DH->Checksum);
  587. W.printNumber("InitialIP", DH->InitialIP);
  588. W.printNumber("InitialRelativeCS", DH->InitialRelativeCS);
  589. W.printNumber("AddressOfRelocationTable", DH->AddressOfRelocationTable);
  590. W.printNumber("OverlayNumber", DH->OverlayNumber);
  591. W.printNumber("OEMid", DH->OEMid);
  592. W.printNumber("OEMinfo", DH->OEMinfo);
  593. W.printNumber("AddressOfNewExeHeader", DH->AddressOfNewExeHeader);
  594. }
  595. template <class PEHeader>
  596. void COFFDumper::printPEHeader(const PEHeader *Hdr) {
  597. DictScope D(W, "ImageOptionalHeader");
  598. W.printHex ("Magic", Hdr->Magic);
  599. W.printNumber("MajorLinkerVersion", Hdr->MajorLinkerVersion);
  600. W.printNumber("MinorLinkerVersion", Hdr->MinorLinkerVersion);
  601. W.printNumber("SizeOfCode", Hdr->SizeOfCode);
  602. W.printNumber("SizeOfInitializedData", Hdr->SizeOfInitializedData);
  603. W.printNumber("SizeOfUninitializedData", Hdr->SizeOfUninitializedData);
  604. W.printHex ("AddressOfEntryPoint", Hdr->AddressOfEntryPoint);
  605. W.printHex ("BaseOfCode", Hdr->BaseOfCode);
  606. printBaseOfDataField(Hdr);
  607. W.printHex ("ImageBase", Hdr->ImageBase);
  608. W.printNumber("SectionAlignment", Hdr->SectionAlignment);
  609. W.printNumber("FileAlignment", Hdr->FileAlignment);
  610. W.printNumber("MajorOperatingSystemVersion",
  611. Hdr->MajorOperatingSystemVersion);
  612. W.printNumber("MinorOperatingSystemVersion",
  613. Hdr->MinorOperatingSystemVersion);
  614. W.printNumber("MajorImageVersion", Hdr->MajorImageVersion);
  615. W.printNumber("MinorImageVersion", Hdr->MinorImageVersion);
  616. W.printNumber("MajorSubsystemVersion", Hdr->MajorSubsystemVersion);
  617. W.printNumber("MinorSubsystemVersion", Hdr->MinorSubsystemVersion);
  618. W.printNumber("SizeOfImage", Hdr->SizeOfImage);
  619. W.printNumber("SizeOfHeaders", Hdr->SizeOfHeaders);
  620. W.printEnum ("Subsystem", Hdr->Subsystem, makeArrayRef(PEWindowsSubsystem));
  621. W.printFlags ("Characteristics", Hdr->DLLCharacteristics,
  622. makeArrayRef(PEDLLCharacteristics));
  623. W.printNumber("SizeOfStackReserve", Hdr->SizeOfStackReserve);
  624. W.printNumber("SizeOfStackCommit", Hdr->SizeOfStackCommit);
  625. W.printNumber("SizeOfHeapReserve", Hdr->SizeOfHeapReserve);
  626. W.printNumber("SizeOfHeapCommit", Hdr->SizeOfHeapCommit);
  627. W.printNumber("NumberOfRvaAndSize", Hdr->NumberOfRvaAndSize);
  628. if (Hdr->NumberOfRvaAndSize > 0) {
  629. DictScope D(W, "DataDirectory");
  630. static const char * const directory[] = {
  631. "ExportTable", "ImportTable", "ResourceTable", "ExceptionTable",
  632. "CertificateTable", "BaseRelocationTable", "Debug", "Architecture",
  633. "GlobalPtr", "TLSTable", "LoadConfigTable", "BoundImport", "IAT",
  634. "DelayImportDescriptor", "CLRRuntimeHeader", "Reserved"
  635. };
  636. for (uint32_t i = 0; i < Hdr->NumberOfRvaAndSize; ++i)
  637. if (i < sizeof(directory) / sizeof(char *))
  638. printDataDirectory(i, directory[i]);
  639. else
  640. printDataDirectory(i, "Unknown");
  641. }
  642. }
  643. void COFFDumper::printCOFFDebugDirectory() {
  644. ListScope LS(W, "DebugDirectory");
  645. for (const debug_directory &D : Obj->debug_directories()) {
  646. char FormattedTime[20] = {};
  647. time_t TDS = D.TimeDateStamp;
  648. strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
  649. DictScope S(W, "DebugEntry");
  650. W.printHex("Characteristics", D.Characteristics);
  651. W.printHex("TimeDateStamp", FormattedTime, D.TimeDateStamp);
  652. W.printHex("MajorVersion", D.MajorVersion);
  653. W.printHex("MinorVersion", D.MinorVersion);
  654. W.printEnum("Type", D.Type, makeArrayRef(ImageDebugType));
  655. W.printHex("SizeOfData", D.SizeOfData);
  656. W.printHex("AddressOfRawData", D.AddressOfRawData);
  657. W.printHex("PointerToRawData", D.PointerToRawData);
  658. // Ideally, if D.AddressOfRawData == 0, we should try to load the payload
  659. // using D.PointerToRawData instead.
  660. if (D.AddressOfRawData == 0)
  661. continue;
  662. if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) {
  663. const codeview::DebugInfo *DebugInfo;
  664. StringRef PDBFileName;
  665. if (Error E = Obj->getDebugPDBInfo(&D, DebugInfo, PDBFileName))
  666. reportError(std::move(E), Obj->getFileName());
  667. DictScope PDBScope(W, "PDBInfo");
  668. W.printHex("PDBSignature", DebugInfo->Signature.CVSignature);
  669. if (DebugInfo->Signature.CVSignature == OMF::Signature::PDB70) {
  670. W.printBinary("PDBGUID", makeArrayRef(DebugInfo->PDB70.Signature));
  671. W.printNumber("PDBAge", DebugInfo->PDB70.Age);
  672. W.printString("PDBFileName", PDBFileName);
  673. }
  674. } else if (D.SizeOfData != 0) {
  675. // FIXME: Data visualization for IMAGE_DEBUG_TYPE_VC_FEATURE and
  676. // IMAGE_DEBUG_TYPE_POGO?
  677. ArrayRef<uint8_t> RawData;
  678. if (Error E = Obj->getRvaAndSizeAsBytes(D.AddressOfRawData,
  679. D.SizeOfData, RawData))
  680. reportError(std::move(E), Obj->getFileName());
  681. if (D.Type == COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS) {
  682. // FIXME right now the only possible value would fit in 8 bits,
  683. // but that might change in the future
  684. uint16_t Characteristics = RawData[0];
  685. W.printFlags("ExtendedCharacteristics", Characteristics,
  686. makeArrayRef(PEExtendedDLLCharacteristics));
  687. }
  688. W.printBinaryBlock("RawData", RawData);
  689. }
  690. }
  691. }
  692. void COFFDumper::printRVATable(uint64_t TableVA, uint64_t Count,
  693. uint64_t EntrySize, PrintExtraCB PrintExtra) {
  694. uintptr_t TableStart, TableEnd;
  695. if (Error E = Obj->getVaPtr(TableVA, TableStart))
  696. reportError(std::move(E), Obj->getFileName());
  697. if (Error E =
  698. Obj->getVaPtr(TableVA + Count * EntrySize - 1, TableEnd))
  699. reportError(std::move(E), Obj->getFileName());
  700. TableEnd++;
  701. for (uintptr_t I = TableStart; I < TableEnd; I += EntrySize) {
  702. uint32_t RVA = *reinterpret_cast<const ulittle32_t *>(I);
  703. raw_ostream &OS = W.startLine();
  704. OS << W.hex(Obj->getImageBase() + RVA);
  705. if (PrintExtra)
  706. PrintExtra(OS, reinterpret_cast<const uint8_t *>(I));
  707. OS << '\n';
  708. }
  709. }
  710. void COFFDumper::printCOFFLoadConfig() {
  711. LoadConfigTables Tables;
  712. if (Obj->is64())
  713. printCOFFLoadConfig(Obj->getLoadConfig64(), Tables);
  714. else
  715. printCOFFLoadConfig(Obj->getLoadConfig32(), Tables);
  716. if (Tables.SEHTableVA) {
  717. ListScope LS(W, "SEHTable");
  718. printRVATable(Tables.SEHTableVA, Tables.SEHTableCount, 4);
  719. }
  720. auto PrintGuardFlags = [](raw_ostream &OS, const uint8_t *Entry) {
  721. uint8_t Flags = *reinterpret_cast<const uint8_t *>(Entry + 4);
  722. if (Flags)
  723. OS << " flags " << utohexstr(Flags);
  724. };
  725. if (Tables.GuardFidTableVA) {
  726. ListScope LS(W, "GuardFidTable");
  727. if (Tables.GuardFlags & uint32_t(coff_guard_flags::FidTableHasFlags))
  728. printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 5,
  729. PrintGuardFlags);
  730. else
  731. printRVATable(Tables.GuardFidTableVA, Tables.GuardFidTableCount, 4);
  732. }
  733. if (Tables.GuardIatTableVA) {
  734. ListScope LS(W, "GuardIatTable");
  735. printRVATable(Tables.GuardIatTableVA, Tables.GuardIatTableCount, 4);
  736. }
  737. if (Tables.GuardLJmpTableVA) {
  738. ListScope LS(W, "GuardLJmpTable");
  739. printRVATable(Tables.GuardLJmpTableVA, Tables.GuardLJmpTableCount, 4);
  740. }
  741. if (Tables.GuardEHContTableVA) {
  742. ListScope LS(W, "GuardEHContTable");
  743. printRVATable(Tables.GuardEHContTableVA, Tables.GuardEHContTableCount, 5,
  744. PrintGuardFlags);
  745. }
  746. }
  747. template <typename T>
  748. void COFFDumper::printCOFFLoadConfig(const T *Conf, LoadConfigTables &Tables) {
  749. if (!Conf)
  750. return;
  751. ListScope LS(W, "LoadConfig");
  752. char FormattedTime[20] = {};
  753. time_t TDS = Conf->TimeDateStamp;
  754. strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
  755. W.printHex("Size", Conf->Size);
  756. // Print everything before SecurityCookie. The vast majority of images today
  757. // have all these fields.
  758. if (Conf->Size < offsetof(T, SEHandlerTable))
  759. return;
  760. W.printHex("TimeDateStamp", FormattedTime, TDS);
  761. W.printHex("MajorVersion", Conf->MajorVersion);
  762. W.printHex("MinorVersion", Conf->MinorVersion);
  763. W.printHex("GlobalFlagsClear", Conf->GlobalFlagsClear);
  764. W.printHex("GlobalFlagsSet", Conf->GlobalFlagsSet);
  765. W.printHex("CriticalSectionDefaultTimeout",
  766. Conf->CriticalSectionDefaultTimeout);
  767. W.printHex("DeCommitFreeBlockThreshold", Conf->DeCommitFreeBlockThreshold);
  768. W.printHex("DeCommitTotalFreeThreshold", Conf->DeCommitTotalFreeThreshold);
  769. W.printHex("LockPrefixTable", Conf->LockPrefixTable);
  770. W.printHex("MaximumAllocationSize", Conf->MaximumAllocationSize);
  771. W.printHex("VirtualMemoryThreshold", Conf->VirtualMemoryThreshold);
  772. W.printHex("ProcessHeapFlags", Conf->ProcessHeapFlags);
  773. W.printHex("ProcessAffinityMask", Conf->ProcessAffinityMask);
  774. W.printHex("CSDVersion", Conf->CSDVersion);
  775. W.printHex("DependentLoadFlags", Conf->DependentLoadFlags);
  776. W.printHex("EditList", Conf->EditList);
  777. W.printHex("SecurityCookie", Conf->SecurityCookie);
  778. // Print the safe SEH table if present.
  779. if (Conf->Size < offsetof(coff_load_configuration32, GuardCFCheckFunction))
  780. return;
  781. W.printHex("SEHandlerTable", Conf->SEHandlerTable);
  782. W.printNumber("SEHandlerCount", Conf->SEHandlerCount);
  783. Tables.SEHTableVA = Conf->SEHandlerTable;
  784. Tables.SEHTableCount = Conf->SEHandlerCount;
  785. // Print everything before CodeIntegrity. (2015)
  786. if (Conf->Size < offsetof(T, CodeIntegrity))
  787. return;
  788. W.printHex("GuardCFCheckFunction", Conf->GuardCFCheckFunction);
  789. W.printHex("GuardCFCheckDispatch", Conf->GuardCFCheckDispatch);
  790. W.printHex("GuardCFFunctionTable", Conf->GuardCFFunctionTable);
  791. W.printNumber("GuardCFFunctionCount", Conf->GuardCFFunctionCount);
  792. W.printHex("GuardFlags", Conf->GuardFlags);
  793. Tables.GuardFidTableVA = Conf->GuardCFFunctionTable;
  794. Tables.GuardFidTableCount = Conf->GuardCFFunctionCount;
  795. Tables.GuardFlags = Conf->GuardFlags;
  796. // Print everything before Reserved3. (2017)
  797. if (Conf->Size < offsetof(T, Reserved3))
  798. return;
  799. W.printHex("GuardAddressTakenIatEntryTable",
  800. Conf->GuardAddressTakenIatEntryTable);
  801. W.printNumber("GuardAddressTakenIatEntryCount",
  802. Conf->GuardAddressTakenIatEntryCount);
  803. W.printHex("GuardLongJumpTargetTable", Conf->GuardLongJumpTargetTable);
  804. W.printNumber("GuardLongJumpTargetCount", Conf->GuardLongJumpTargetCount);
  805. W.printHex("DynamicValueRelocTable", Conf->DynamicValueRelocTable);
  806. W.printHex("CHPEMetadataPointer", Conf->CHPEMetadataPointer);
  807. W.printHex("GuardRFFailureRoutine", Conf->GuardRFFailureRoutine);
  808. W.printHex("GuardRFFailureRoutineFunctionPointer",
  809. Conf->GuardRFFailureRoutineFunctionPointer);
  810. W.printHex("DynamicValueRelocTableOffset",
  811. Conf->DynamicValueRelocTableOffset);
  812. W.printNumber("DynamicValueRelocTableSection",
  813. Conf->DynamicValueRelocTableSection);
  814. W.printHex("GuardRFVerifyStackPointerFunctionPointer",
  815. Conf->GuardRFVerifyStackPointerFunctionPointer);
  816. W.printHex("HotPatchTableOffset", Conf->HotPatchTableOffset);
  817. Tables.GuardIatTableVA = Conf->GuardAddressTakenIatEntryTable;
  818. Tables.GuardIatTableCount = Conf->GuardAddressTakenIatEntryCount;
  819. Tables.GuardLJmpTableVA = Conf->GuardLongJumpTargetTable;
  820. Tables.GuardLJmpTableCount = Conf->GuardLongJumpTargetCount;
  821. // Print the rest. (2019)
  822. if (Conf->Size < sizeof(T))
  823. return;
  824. W.printHex("EnclaveConfigurationPointer", Conf->EnclaveConfigurationPointer);
  825. W.printHex("VolatileMetadataPointer", Conf->VolatileMetadataPointer);
  826. W.printHex("GuardEHContinuationTable", Conf->GuardEHContinuationTable);
  827. W.printNumber("GuardEHContinuationCount", Conf->GuardEHContinuationCount);
  828. Tables.GuardEHContTableVA = Conf->GuardEHContinuationTable;
  829. Tables.GuardEHContTableCount = Conf->GuardEHContinuationCount;
  830. }
  831. void COFFDumper::printBaseOfDataField(const pe32_header *Hdr) {
  832. W.printHex("BaseOfData", Hdr->BaseOfData);
  833. }
  834. void COFFDumper::printBaseOfDataField(const pe32plus_header *) {}
  835. void COFFDumper::printCodeViewDebugInfo() {
  836. // Print types first to build CVUDTNames, then print symbols.
  837. for (const SectionRef &S : Obj->sections()) {
  838. StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
  839. // .debug$T is a standard CodeView type section, while .debug$P is the same
  840. // format but used for MSVC precompiled header object files.
  841. if (SectionName == ".debug$T" || SectionName == ".debug$P")
  842. printCodeViewTypeSection(SectionName, S);
  843. }
  844. for (const SectionRef &S : Obj->sections()) {
  845. StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
  846. if (SectionName == ".debug$S")
  847. printCodeViewSymbolSection(SectionName, S);
  848. }
  849. }
  850. void COFFDumper::initializeFileAndStringTables(BinaryStreamReader &Reader) {
  851. while (Reader.bytesRemaining() > 0 &&
  852. (!CVFileChecksumTable.valid() || !CVStringTable.valid())) {
  853. // The section consists of a number of subsection in the following format:
  854. // |SubSectionType|SubSectionSize|Contents...|
  855. uint32_t SubType, SubSectionSize;
  856. if (Error E = Reader.readInteger(SubType))
  857. reportError(std::move(E), Obj->getFileName());
  858. if (Error E = Reader.readInteger(SubSectionSize))
  859. reportError(std::move(E), Obj->getFileName());
  860. StringRef Contents;
  861. if (Error E = Reader.readFixedString(Contents, SubSectionSize))
  862. reportError(std::move(E), Obj->getFileName());
  863. BinaryStreamRef ST(Contents, support::little);
  864. switch (DebugSubsectionKind(SubType)) {
  865. case DebugSubsectionKind::FileChecksums:
  866. if (Error E = CVFileChecksumTable.initialize(ST))
  867. reportError(std::move(E), Obj->getFileName());
  868. break;
  869. case DebugSubsectionKind::StringTable:
  870. if (Error E = CVStringTable.initialize(ST))
  871. reportError(std::move(E), Obj->getFileName());
  872. break;
  873. default:
  874. break;
  875. }
  876. uint32_t PaddedSize = alignTo(SubSectionSize, 4);
  877. if (Error E = Reader.skip(PaddedSize - SubSectionSize))
  878. reportError(std::move(E), Obj->getFileName());
  879. }
  880. }
  881. void COFFDumper::printCodeViewSymbolSection(StringRef SectionName,
  882. const SectionRef &Section) {
  883. StringRef SectionContents =
  884. unwrapOrError(Obj->getFileName(), Section.getContents());
  885. StringRef Data = SectionContents;
  886. SmallVector<StringRef, 10> FunctionNames;
  887. StringMap<StringRef> FunctionLineTables;
  888. ListScope D(W, "CodeViewDebugInfo");
  889. // Print the section to allow correlation with printSectionHeaders.
  890. W.printNumber("Section", SectionName, Obj->getSectionID(Section));
  891. uint32_t Magic;
  892. if (Error E = consume(Data, Magic))
  893. reportError(std::move(E), Obj->getFileName());
  894. W.printHex("Magic", Magic);
  895. if (Magic != COFF::DEBUG_SECTION_MAGIC)
  896. reportError(errorCodeToError(object_error::parse_failed),
  897. Obj->getFileName());
  898. BinaryStreamReader FSReader(Data, support::little);
  899. initializeFileAndStringTables(FSReader);
  900. // TODO: Convert this over to using ModuleSubstreamVisitor.
  901. while (!Data.empty()) {
  902. // The section consists of a number of subsection in the following format:
  903. // |SubSectionType|SubSectionSize|Contents...|
  904. uint32_t SubType, SubSectionSize;
  905. if (Error E = consume(Data, SubType))
  906. reportError(std::move(E), Obj->getFileName());
  907. if (Error E = consume(Data, SubSectionSize))
  908. reportError(std::move(E), Obj->getFileName());
  909. ListScope S(W, "Subsection");
  910. // Dump the subsection as normal even if the ignore bit is set.
  911. if (SubType & SubsectionIgnoreFlag) {
  912. W.printHex("IgnoredSubsectionKind", SubType);
  913. SubType &= ~SubsectionIgnoreFlag;
  914. }
  915. W.printEnum("SubSectionType", SubType, makeArrayRef(SubSectionTypes));
  916. W.printHex("SubSectionSize", SubSectionSize);
  917. // Get the contents of the subsection.
  918. if (SubSectionSize > Data.size())
  919. return reportError(errorCodeToError(object_error::parse_failed),
  920. Obj->getFileName());
  921. StringRef Contents = Data.substr(0, SubSectionSize);
  922. // Add SubSectionSize to the current offset and align that offset to find
  923. // the next subsection.
  924. size_t SectionOffset = Data.data() - SectionContents.data();
  925. size_t NextOffset = SectionOffset + SubSectionSize;
  926. NextOffset = alignTo(NextOffset, 4);
  927. if (NextOffset > SectionContents.size())
  928. return reportError(errorCodeToError(object_error::parse_failed),
  929. Obj->getFileName());
  930. Data = SectionContents.drop_front(NextOffset);
  931. // Optionally print the subsection bytes in case our parsing gets confused
  932. // later.
  933. if (opts::CodeViewSubsectionBytes)
  934. printBinaryBlockWithRelocs("SubSectionContents", Section, SectionContents,
  935. Contents);
  936. switch (DebugSubsectionKind(SubType)) {
  937. case DebugSubsectionKind::Symbols:
  938. printCodeViewSymbolsSubsection(Contents, Section, SectionContents);
  939. break;
  940. case DebugSubsectionKind::InlineeLines:
  941. printCodeViewInlineeLines(Contents);
  942. break;
  943. case DebugSubsectionKind::FileChecksums:
  944. printCodeViewFileChecksums(Contents);
  945. break;
  946. case DebugSubsectionKind::Lines: {
  947. // Holds a PC to file:line table. Some data to parse this subsection is
  948. // stored in the other subsections, so just check sanity and store the
  949. // pointers for deferred processing.
  950. if (SubSectionSize < 12) {
  951. // There should be at least three words to store two function
  952. // relocations and size of the code.
  953. reportError(errorCodeToError(object_error::parse_failed),
  954. Obj->getFileName());
  955. return;
  956. }
  957. StringRef LinkageName;
  958. if (std::error_code EC = resolveSymbolName(Obj->getCOFFSection(Section),
  959. SectionOffset, LinkageName))
  960. reportError(errorCodeToError(EC), Obj->getFileName());
  961. W.printString("LinkageName", LinkageName);
  962. if (FunctionLineTables.count(LinkageName) != 0) {
  963. // Saw debug info for this function already?
  964. reportError(errorCodeToError(object_error::parse_failed),
  965. Obj->getFileName());
  966. return;
  967. }
  968. FunctionLineTables[LinkageName] = Contents;
  969. FunctionNames.push_back(LinkageName);
  970. break;
  971. }
  972. case DebugSubsectionKind::FrameData: {
  973. // First four bytes is a relocation against the function.
  974. BinaryStreamReader SR(Contents, llvm::support::little);
  975. DebugFrameDataSubsectionRef FrameData;
  976. if (Error E = FrameData.initialize(SR))
  977. reportError(std::move(E), Obj->getFileName());
  978. StringRef LinkageName;
  979. if (std::error_code EC =
  980. resolveSymbolName(Obj->getCOFFSection(Section), SectionContents,
  981. FrameData.getRelocPtr(), LinkageName))
  982. reportError(errorCodeToError(EC), Obj->getFileName());
  983. W.printString("LinkageName", LinkageName);
  984. // To find the active frame description, search this array for the
  985. // smallest PC range that includes the current PC.
  986. for (const auto &FD : FrameData) {
  987. StringRef FrameFunc = unwrapOrError(
  988. Obj->getFileName(), CVStringTable.getString(FD.FrameFunc));
  989. DictScope S(W, "FrameData");
  990. W.printHex("RvaStart", FD.RvaStart);
  991. W.printHex("CodeSize", FD.CodeSize);
  992. W.printHex("LocalSize", FD.LocalSize);
  993. W.printHex("ParamsSize", FD.ParamsSize);
  994. W.printHex("MaxStackSize", FD.MaxStackSize);
  995. W.printHex("PrologSize", FD.PrologSize);
  996. W.printHex("SavedRegsSize", FD.SavedRegsSize);
  997. W.printFlags("Flags", FD.Flags, makeArrayRef(FrameDataFlags));
  998. // The FrameFunc string is a small RPN program. It can be broken up into
  999. // statements that end in the '=' operator, which assigns the value on
  1000. // the top of the stack to the previously pushed variable. Variables can
  1001. // be temporary values ($T0) or physical registers ($esp). Print each
  1002. // assignment on its own line to make these programs easier to read.
  1003. {
  1004. ListScope FFS(W, "FrameFunc");
  1005. while (!FrameFunc.empty()) {
  1006. size_t EqOrEnd = FrameFunc.find('=');
  1007. if (EqOrEnd == StringRef::npos)
  1008. EqOrEnd = FrameFunc.size();
  1009. else
  1010. ++EqOrEnd;
  1011. StringRef Stmt = FrameFunc.substr(0, EqOrEnd);
  1012. W.printString(Stmt);
  1013. FrameFunc = FrameFunc.drop_front(EqOrEnd).trim();
  1014. }
  1015. }
  1016. }
  1017. break;
  1018. }
  1019. // Do nothing for unrecognized subsections.
  1020. default:
  1021. break;
  1022. }
  1023. W.flush();
  1024. }
  1025. // Dump the line tables now that we've read all the subsections and know all
  1026. // the required information.
  1027. for (unsigned I = 0, E = FunctionNames.size(); I != E; ++I) {
  1028. StringRef Name = FunctionNames[I];
  1029. ListScope S(W, "FunctionLineTable");
  1030. W.printString("LinkageName", Name);
  1031. BinaryStreamReader Reader(FunctionLineTables[Name], support::little);
  1032. DebugLinesSubsectionRef LineInfo;
  1033. if (Error E = LineInfo.initialize(Reader))
  1034. reportError(std::move(E), Obj->getFileName());
  1035. W.printHex("Flags", LineInfo.header()->Flags);
  1036. W.printHex("CodeSize", LineInfo.header()->CodeSize);
  1037. for (const auto &Entry : LineInfo) {
  1038. ListScope S(W, "FilenameSegment");
  1039. printFileNameForOffset("Filename", Entry.NameIndex);
  1040. uint32_t ColumnIndex = 0;
  1041. for (const auto &Line : Entry.LineNumbers) {
  1042. if (Line.Offset >= LineInfo.header()->CodeSize) {
  1043. reportError(errorCodeToError(object_error::parse_failed),
  1044. Obj->getFileName());
  1045. return;
  1046. }
  1047. std::string PC = std::string(formatv("+{0:X}", uint32_t(Line.Offset)));
  1048. ListScope PCScope(W, PC);
  1049. codeview::LineInfo LI(Line.Flags);
  1050. if (LI.isAlwaysStepInto())
  1051. W.printString("StepInto", StringRef("Always"));
  1052. else if (LI.isNeverStepInto())
  1053. W.printString("StepInto", StringRef("Never"));
  1054. else
  1055. W.printNumber("LineNumberStart", LI.getStartLine());
  1056. W.printNumber("LineNumberEndDelta", LI.getLineDelta());
  1057. W.printBoolean("IsStatement", LI.isStatement());
  1058. if (LineInfo.hasColumnInfo()) {
  1059. W.printNumber("ColStart", Entry.Columns[ColumnIndex].StartColumn);
  1060. W.printNumber("ColEnd", Entry.Columns[ColumnIndex].EndColumn);
  1061. ++ColumnIndex;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. }
  1067. void COFFDumper::printCodeViewSymbolsSubsection(StringRef Subsection,
  1068. const SectionRef &Section,
  1069. StringRef SectionContents) {
  1070. ArrayRef<uint8_t> BinaryData(Subsection.bytes_begin(),
  1071. Subsection.bytes_end());
  1072. auto CODD = std::make_unique<COFFObjectDumpDelegate>(*this, Section, Obj,
  1073. SectionContents);
  1074. CVSymbolDumper CVSD(W, Types, CodeViewContainer::ObjectFile, std::move(CODD),
  1075. CompilationCPUType, opts::CodeViewSubsectionBytes);
  1076. CVSymbolArray Symbols;
  1077. BinaryStreamReader Reader(BinaryData, llvm::support::little);
  1078. if (Error E = Reader.readArray(Symbols, Reader.getLength())) {
  1079. W.flush();
  1080. reportError(std::move(E), Obj->getFileName());
  1081. }
  1082. if (Error E = CVSD.dump(Symbols)) {
  1083. W.flush();
  1084. reportError(std::move(E), Obj->getFileName());
  1085. }
  1086. CompilationCPUType = CVSD.getCompilationCPUType();
  1087. W.flush();
  1088. }
  1089. void COFFDumper::printCodeViewFileChecksums(StringRef Subsection) {
  1090. BinaryStreamRef Stream(Subsection, llvm::support::little);
  1091. DebugChecksumsSubsectionRef Checksums;
  1092. if (Error E = Checksums.initialize(Stream))
  1093. reportError(std::move(E), Obj->getFileName());
  1094. for (auto &FC : Checksums) {
  1095. DictScope S(W, "FileChecksum");
  1096. StringRef Filename = unwrapOrError(
  1097. Obj->getFileName(), CVStringTable.getString(FC.FileNameOffset));
  1098. W.printHex("Filename", Filename, FC.FileNameOffset);
  1099. W.printHex("ChecksumSize", FC.Checksum.size());
  1100. W.printEnum("ChecksumKind", uint8_t(FC.Kind),
  1101. makeArrayRef(FileChecksumKindNames));
  1102. W.printBinary("ChecksumBytes", FC.Checksum);
  1103. }
  1104. }
  1105. void COFFDumper::printCodeViewInlineeLines(StringRef Subsection) {
  1106. BinaryStreamReader SR(Subsection, llvm::support::little);
  1107. DebugInlineeLinesSubsectionRef Lines;
  1108. if (Error E = Lines.initialize(SR))
  1109. reportError(std::move(E), Obj->getFileName());
  1110. for (auto &Line : Lines) {
  1111. DictScope S(W, "InlineeSourceLine");
  1112. printTypeIndex("Inlinee", Line.Header->Inlinee);
  1113. printFileNameForOffset("FileID", Line.Header->FileID);
  1114. W.printNumber("SourceLineNum", Line.Header->SourceLineNum);
  1115. if (Lines.hasExtraFiles()) {
  1116. W.printNumber("ExtraFileCount", Line.ExtraFiles.size());
  1117. ListScope ExtraFiles(W, "ExtraFiles");
  1118. for (const auto &FID : Line.ExtraFiles) {
  1119. printFileNameForOffset("FileID", FID);
  1120. }
  1121. }
  1122. }
  1123. }
  1124. StringRef COFFDumper::getFileNameForFileOffset(uint32_t FileOffset) {
  1125. // The file checksum subsection should precede all references to it.
  1126. if (!CVFileChecksumTable.valid() || !CVStringTable.valid())
  1127. reportError(errorCodeToError(object_error::parse_failed),
  1128. Obj->getFileName());
  1129. auto Iter = CVFileChecksumTable.getArray().at(FileOffset);
  1130. // Check if the file checksum table offset is valid.
  1131. if (Iter == CVFileChecksumTable.end())
  1132. reportError(errorCodeToError(object_error::parse_failed),
  1133. Obj->getFileName());
  1134. return unwrapOrError(Obj->getFileName(),
  1135. CVStringTable.getString(Iter->FileNameOffset));
  1136. }
  1137. void COFFDumper::printFileNameForOffset(StringRef Label, uint32_t FileOffset) {
  1138. W.printHex(Label, getFileNameForFileOffset(FileOffset), FileOffset);
  1139. }
  1140. void COFFDumper::mergeCodeViewTypes(MergingTypeTableBuilder &CVIDs,
  1141. MergingTypeTableBuilder &CVTypes,
  1142. GlobalTypeTableBuilder &GlobalCVIDs,
  1143. GlobalTypeTableBuilder &GlobalCVTypes,
  1144. bool GHash) {
  1145. for (const SectionRef &S : Obj->sections()) {
  1146. StringRef SectionName = unwrapOrError(Obj->getFileName(), S.getName());
  1147. if (SectionName == ".debug$T") {
  1148. StringRef Data = unwrapOrError(Obj->getFileName(), S.getContents());
  1149. uint32_t Magic;
  1150. if (Error E = consume(Data, Magic))
  1151. reportError(std::move(E), Obj->getFileName());
  1152. if (Magic != 4)
  1153. reportError(errorCodeToError(object_error::parse_failed),
  1154. Obj->getFileName());
  1155. CVTypeArray Types;
  1156. BinaryStreamReader Reader(Data, llvm::support::little);
  1157. if (auto EC = Reader.readArray(Types, Reader.getLength())) {
  1158. consumeError(std::move(EC));
  1159. W.flush();
  1160. reportError(errorCodeToError(object_error::parse_failed),
  1161. Obj->getFileName());
  1162. }
  1163. SmallVector<TypeIndex, 128> SourceToDest;
  1164. Optional<uint32_t> PCHSignature;
  1165. if (GHash) {
  1166. std::vector<GloballyHashedType> Hashes =
  1167. GloballyHashedType::hashTypes(Types);
  1168. if (Error E =
  1169. mergeTypeAndIdRecords(GlobalCVIDs, GlobalCVTypes, SourceToDest,
  1170. Types, Hashes, PCHSignature))
  1171. return reportError(std::move(E), Obj->getFileName());
  1172. } else {
  1173. if (Error E = mergeTypeAndIdRecords(CVIDs, CVTypes, SourceToDest, Types,
  1174. PCHSignature))
  1175. return reportError(std::move(E), Obj->getFileName());
  1176. }
  1177. }
  1178. }
  1179. }
  1180. void COFFDumper::printCodeViewTypeSection(StringRef SectionName,
  1181. const SectionRef &Section) {
  1182. ListScope D(W, "CodeViewTypes");
  1183. W.printNumber("Section", SectionName, Obj->getSectionID(Section));
  1184. StringRef Data = unwrapOrError(Obj->getFileName(), Section.getContents());
  1185. if (opts::CodeViewSubsectionBytes)
  1186. W.printBinaryBlock("Data", Data);
  1187. uint32_t Magic;
  1188. if (Error E = consume(Data, Magic))
  1189. reportError(std::move(E), Obj->getFileName());
  1190. W.printHex("Magic", Magic);
  1191. if (Magic != COFF::DEBUG_SECTION_MAGIC)
  1192. reportError(errorCodeToError(object_error::parse_failed),
  1193. Obj->getFileName());
  1194. Types.reset(Data, 100);
  1195. TypeDumpVisitor TDV(Types, &W, opts::CodeViewSubsectionBytes);
  1196. if (Error E = codeview::visitTypeStream(Types, TDV))
  1197. reportError(std::move(E), Obj->getFileName());
  1198. W.flush();
  1199. }
  1200. void COFFDumper::printSectionHeaders() {
  1201. ListScope SectionsD(W, "Sections");
  1202. int SectionNumber = 0;
  1203. for (const SectionRef &Sec : Obj->sections()) {
  1204. ++SectionNumber;
  1205. const coff_section *Section = Obj->getCOFFSection(Sec);
  1206. StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
  1207. DictScope D(W, "Section");
  1208. W.printNumber("Number", SectionNumber);
  1209. W.printBinary("Name", Name, Section->Name);
  1210. W.printHex ("VirtualSize", Section->VirtualSize);
  1211. W.printHex ("VirtualAddress", Section->VirtualAddress);
  1212. W.printNumber("RawDataSize", Section->SizeOfRawData);
  1213. W.printHex ("PointerToRawData", Section->PointerToRawData);
  1214. W.printHex ("PointerToRelocations", Section->PointerToRelocations);
  1215. W.printHex ("PointerToLineNumbers", Section->PointerToLinenumbers);
  1216. W.printNumber("RelocationCount", Section->NumberOfRelocations);
  1217. W.printNumber("LineNumberCount", Section->NumberOfLinenumbers);
  1218. W.printFlags ("Characteristics", Section->Characteristics,
  1219. makeArrayRef(ImageSectionCharacteristics),
  1220. COFF::SectionCharacteristics(0x00F00000));
  1221. if (opts::SectionRelocations) {
  1222. ListScope D(W, "Relocations");
  1223. for (const RelocationRef &Reloc : Sec.relocations())
  1224. printRelocation(Sec, Reloc);
  1225. }
  1226. if (opts::SectionSymbols) {
  1227. ListScope D(W, "Symbols");
  1228. for (const SymbolRef &Symbol : Obj->symbols()) {
  1229. if (!Sec.containsSymbol(Symbol))
  1230. continue;
  1231. printSymbol(Symbol);
  1232. }
  1233. }
  1234. if (opts::SectionData &&
  1235. !(Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
  1236. StringRef Data = unwrapOrError(Obj->getFileName(), Sec.getContents());
  1237. W.printBinaryBlock("SectionData", Data);
  1238. }
  1239. }
  1240. }
  1241. void COFFDumper::printRelocations() {
  1242. ListScope D(W, "Relocations");
  1243. int SectionNumber = 0;
  1244. for (const SectionRef &Section : Obj->sections()) {
  1245. ++SectionNumber;
  1246. StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
  1247. bool PrintedGroup = false;
  1248. for (const RelocationRef &Reloc : Section.relocations()) {
  1249. if (!PrintedGroup) {
  1250. W.startLine() << "Section (" << SectionNumber << ") " << Name << " {\n";
  1251. W.indent();
  1252. PrintedGroup = true;
  1253. }
  1254. printRelocation(Section, Reloc);
  1255. }
  1256. if (PrintedGroup) {
  1257. W.unindent();
  1258. W.startLine() << "}\n";
  1259. }
  1260. }
  1261. }
  1262. void COFFDumper::printRelocation(const SectionRef &Section,
  1263. const RelocationRef &Reloc, uint64_t Bias) {
  1264. uint64_t Offset = Reloc.getOffset() - Bias;
  1265. uint64_t RelocType = Reloc.getType();
  1266. SmallString<32> RelocName;
  1267. StringRef SymbolName;
  1268. Reloc.getTypeName(RelocName);
  1269. symbol_iterator Symbol = Reloc.getSymbol();
  1270. int64_t SymbolIndex = -1;
  1271. if (Symbol != Obj->symbol_end()) {
  1272. Expected<StringRef> SymbolNameOrErr = Symbol->getName();
  1273. if (!SymbolNameOrErr)
  1274. reportError(SymbolNameOrErr.takeError(), Obj->getFileName());
  1275. SymbolName = *SymbolNameOrErr;
  1276. SymbolIndex = Obj->getSymbolIndex(Obj->getCOFFSymbol(*Symbol));
  1277. }
  1278. if (opts::ExpandRelocs) {
  1279. DictScope Group(W, "Relocation");
  1280. W.printHex("Offset", Offset);
  1281. W.printNumber("Type", RelocName, RelocType);
  1282. W.printString("Symbol", SymbolName.empty() ? "-" : SymbolName);
  1283. W.printNumber("SymbolIndex", SymbolIndex);
  1284. } else {
  1285. raw_ostream& OS = W.startLine();
  1286. OS << W.hex(Offset)
  1287. << " " << RelocName
  1288. << " " << (SymbolName.empty() ? "-" : SymbolName)
  1289. << " (" << SymbolIndex << ")"
  1290. << "\n";
  1291. }
  1292. }
  1293. void COFFDumper::printSymbols() {
  1294. ListScope Group(W, "Symbols");
  1295. for (const SymbolRef &Symbol : Obj->symbols())
  1296. printSymbol(Symbol);
  1297. }
  1298. void COFFDumper::printDynamicSymbols() { ListScope Group(W, "DynamicSymbols"); }
  1299. static Expected<StringRef>
  1300. getSectionName(const llvm::object::COFFObjectFile *Obj, int32_t SectionNumber,
  1301. const coff_section *Section) {
  1302. if (Section)
  1303. return Obj->getSectionName(Section);
  1304. if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
  1305. return StringRef("IMAGE_SYM_DEBUG");
  1306. if (SectionNumber == llvm::COFF::IMAGE_SYM_ABSOLUTE)
  1307. return StringRef("IMAGE_SYM_ABSOLUTE");
  1308. if (SectionNumber == llvm::COFF::IMAGE_SYM_UNDEFINED)
  1309. return StringRef("IMAGE_SYM_UNDEFINED");
  1310. return StringRef("");
  1311. }
  1312. void COFFDumper::printSymbol(const SymbolRef &Sym) {
  1313. DictScope D(W, "Symbol");
  1314. COFFSymbolRef Symbol = Obj->getCOFFSymbol(Sym);
  1315. Expected<const coff_section *> SecOrErr =
  1316. Obj->getSection(Symbol.getSectionNumber());
  1317. if (!SecOrErr) {
  1318. W.startLine() << "Invalid section number: " << Symbol.getSectionNumber()
  1319. << "\n";
  1320. W.flush();
  1321. consumeError(SecOrErr.takeError());
  1322. return;
  1323. }
  1324. const coff_section *Section = *SecOrErr;
  1325. StringRef SymbolName;
  1326. if (Expected<StringRef> SymNameOrErr = Obj->getSymbolName(Symbol))
  1327. SymbolName = *SymNameOrErr;
  1328. StringRef SectionName;
  1329. if (Expected<StringRef> SecNameOrErr =
  1330. getSectionName(Obj, Symbol.getSectionNumber(), Section))
  1331. SectionName = *SecNameOrErr;
  1332. W.printString("Name", SymbolName);
  1333. W.printNumber("Value", Symbol.getValue());
  1334. W.printNumber("Section", SectionName, Symbol.getSectionNumber());
  1335. W.printEnum ("BaseType", Symbol.getBaseType(), makeArrayRef(ImageSymType));
  1336. W.printEnum ("ComplexType", Symbol.getComplexType(),
  1337. makeArrayRef(ImageSymDType));
  1338. W.printEnum ("StorageClass", Symbol.getStorageClass(),
  1339. makeArrayRef(ImageSymClass));
  1340. W.printNumber("AuxSymbolCount", Symbol.getNumberOfAuxSymbols());
  1341. for (uint8_t I = 0; I < Symbol.getNumberOfAuxSymbols(); ++I) {
  1342. if (Symbol.isFunctionDefinition()) {
  1343. const coff_aux_function_definition *Aux;
  1344. if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
  1345. reportError(errorCodeToError(EC), Obj->getFileName());
  1346. DictScope AS(W, "AuxFunctionDef");
  1347. W.printNumber("TagIndex", Aux->TagIndex);
  1348. W.printNumber("TotalSize", Aux->TotalSize);
  1349. W.printHex("PointerToLineNumber", Aux->PointerToLinenumber);
  1350. W.printHex("PointerToNextFunction", Aux->PointerToNextFunction);
  1351. } else if (Symbol.isAnyUndefined()) {
  1352. const coff_aux_weak_external *Aux;
  1353. if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
  1354. reportError(errorCodeToError(EC), Obj->getFileName());
  1355. DictScope AS(W, "AuxWeakExternal");
  1356. W.printNumber("Linked", getSymbolName(Aux->TagIndex), Aux->TagIndex);
  1357. W.printEnum ("Search", Aux->Characteristics,
  1358. makeArrayRef(WeakExternalCharacteristics));
  1359. } else if (Symbol.isFileRecord()) {
  1360. const char *FileName;
  1361. if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, FileName))
  1362. reportError(errorCodeToError(EC), Obj->getFileName());
  1363. DictScope AS(W, "AuxFileRecord");
  1364. StringRef Name(FileName, Symbol.getNumberOfAuxSymbols() *
  1365. Obj->getSymbolTableEntrySize());
  1366. W.printString("FileName", Name.rtrim(StringRef("\0", 1)));
  1367. break;
  1368. } else if (Symbol.isSectionDefinition()) {
  1369. const coff_aux_section_definition *Aux;
  1370. if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
  1371. reportError(errorCodeToError(EC), Obj->getFileName());
  1372. int32_t AuxNumber = Aux->getNumber(Symbol.isBigObj());
  1373. DictScope AS(W, "AuxSectionDef");
  1374. W.printNumber("Length", Aux->Length);
  1375. W.printNumber("RelocationCount", Aux->NumberOfRelocations);
  1376. W.printNumber("LineNumberCount", Aux->NumberOfLinenumbers);
  1377. W.printHex("Checksum", Aux->CheckSum);
  1378. W.printNumber("Number", AuxNumber);
  1379. W.printEnum("Selection", Aux->Selection, makeArrayRef(ImageCOMDATSelect));
  1380. if (Section && Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT
  1381. && Aux->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
  1382. Expected<const coff_section *> Assoc = Obj->getSection(AuxNumber);
  1383. if (!Assoc)
  1384. reportError(Assoc.takeError(), Obj->getFileName());
  1385. Expected<StringRef> AssocName = getSectionName(Obj, AuxNumber, *Assoc);
  1386. if (!AssocName)
  1387. reportError(AssocName.takeError(), Obj->getFileName());
  1388. W.printNumber("AssocSection", *AssocName, AuxNumber);
  1389. }
  1390. } else if (Symbol.isCLRToken()) {
  1391. const coff_aux_clr_token *Aux;
  1392. if (std::error_code EC = getSymbolAuxData(Obj, Symbol, I, Aux))
  1393. reportError(errorCodeToError(EC), Obj->getFileName());
  1394. DictScope AS(W, "AuxCLRToken");
  1395. W.printNumber("AuxType", Aux->AuxType);
  1396. W.printNumber("Reserved", Aux->Reserved);
  1397. W.printNumber("SymbolTableIndex", getSymbolName(Aux->SymbolTableIndex),
  1398. Aux->SymbolTableIndex);
  1399. } else {
  1400. W.startLine() << "<unhandled auxiliary record>\n";
  1401. }
  1402. }
  1403. }
  1404. void COFFDumper::printUnwindInfo() {
  1405. ListScope D(W, "UnwindInformation");
  1406. switch (Obj->getMachine()) {
  1407. case COFF::IMAGE_FILE_MACHINE_AMD64: {
  1408. Win64EH::Dumper Dumper(W);
  1409. Win64EH::Dumper::SymbolResolver
  1410. Resolver = [](const object::coff_section *Section, uint64_t Offset,
  1411. SymbolRef &Symbol, void *user_data) -> std::error_code {
  1412. COFFDumper *Dumper = reinterpret_cast<COFFDumper *>(user_data);
  1413. return Dumper->resolveSymbol(Section, Offset, Symbol);
  1414. };
  1415. Win64EH::Dumper::Context Ctx(*Obj, Resolver, this);
  1416. Dumper.printData(Ctx);
  1417. break;
  1418. }
  1419. case COFF::IMAGE_FILE_MACHINE_ARM64:
  1420. case COFF::IMAGE_FILE_MACHINE_ARMNT: {
  1421. ARM::WinEH::Decoder Decoder(W, Obj->getMachine() ==
  1422. COFF::IMAGE_FILE_MACHINE_ARM64);
  1423. // TODO Propagate the error.
  1424. consumeError(Decoder.dumpProcedureData(*Obj));
  1425. break;
  1426. }
  1427. default:
  1428. W.printEnum("unsupported Image Machine", Obj->getMachine(),
  1429. makeArrayRef(ImageFileMachineType));
  1430. break;
  1431. }
  1432. }
  1433. void COFFDumper::printNeededLibraries() {
  1434. ListScope D(W, "NeededLibraries");
  1435. using LibsTy = std::vector<StringRef>;
  1436. LibsTy Libs;
  1437. for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
  1438. StringRef Name;
  1439. if (!DirRef.getName(Name))
  1440. Libs.push_back(Name);
  1441. }
  1442. llvm::stable_sort(Libs);
  1443. for (const auto &L : Libs) {
  1444. W.startLine() << L << "\n";
  1445. }
  1446. }
  1447. void COFFDumper::printImportedSymbols(
  1448. iterator_range<imported_symbol_iterator> Range) {
  1449. for (const ImportedSymbolRef &I : Range) {
  1450. StringRef Sym;
  1451. if (Error E = I.getSymbolName(Sym))
  1452. reportError(std::move(E), Obj->getFileName());
  1453. uint16_t Ordinal;
  1454. if (Error E = I.getOrdinal(Ordinal))
  1455. reportError(std::move(E), Obj->getFileName());
  1456. W.printNumber("Symbol", Sym, Ordinal);
  1457. }
  1458. }
  1459. void COFFDumper::printDelayImportedSymbols(
  1460. const DelayImportDirectoryEntryRef &I,
  1461. iterator_range<imported_symbol_iterator> Range) {
  1462. int Index = 0;
  1463. for (const ImportedSymbolRef &S : Range) {
  1464. DictScope Import(W, "Import");
  1465. StringRef Sym;
  1466. if (Error E = S.getSymbolName(Sym))
  1467. reportError(std::move(E), Obj->getFileName());
  1468. uint16_t Ordinal;
  1469. if (Error E = S.getOrdinal(Ordinal))
  1470. reportError(std::move(E), Obj->getFileName());
  1471. W.printNumber("Symbol", Sym, Ordinal);
  1472. uint64_t Addr;
  1473. if (Error E = I.getImportAddress(Index++, Addr))
  1474. reportError(std::move(E), Obj->getFileName());
  1475. W.printHex("Address", Addr);
  1476. }
  1477. }
  1478. void COFFDumper::printCOFFImports() {
  1479. // Regular imports
  1480. for (const ImportDirectoryEntryRef &I : Obj->import_directories()) {
  1481. DictScope Import(W, "Import");
  1482. StringRef Name;
  1483. if (Error E = I.getName(Name))
  1484. reportError(std::move(E), Obj->getFileName());
  1485. W.printString("Name", Name);
  1486. uint32_t ILTAddr;
  1487. if (Error E = I.getImportLookupTableRVA(ILTAddr))
  1488. reportError(std::move(E), Obj->getFileName());
  1489. W.printHex("ImportLookupTableRVA", ILTAddr);
  1490. uint32_t IATAddr;
  1491. if (Error E = I.getImportAddressTableRVA(IATAddr))
  1492. reportError(std::move(E), Obj->getFileName());
  1493. W.printHex("ImportAddressTableRVA", IATAddr);
  1494. // The import lookup table can be missing with certain older linkers, so
  1495. // fall back to the import address table in that case.
  1496. if (ILTAddr)
  1497. printImportedSymbols(I.lookup_table_symbols());
  1498. else
  1499. printImportedSymbols(I.imported_symbols());
  1500. }
  1501. // Delay imports
  1502. for (const DelayImportDirectoryEntryRef &I : Obj->delay_import_directories()) {
  1503. DictScope Import(W, "DelayImport");
  1504. StringRef Name;
  1505. if (Error E = I.getName(Name))
  1506. reportError(std::move(E), Obj->getFileName());
  1507. W.printString("Name", Name);
  1508. const delay_import_directory_table_entry *Table;
  1509. if (Error E = I.getDelayImportTable(Table))
  1510. reportError(std::move(E), Obj->getFileName());
  1511. W.printHex("Attributes", Table->Attributes);
  1512. W.printHex("ModuleHandle", Table->ModuleHandle);
  1513. W.printHex("ImportAddressTable", Table->DelayImportAddressTable);
  1514. W.printHex("ImportNameTable", Table->DelayImportNameTable);
  1515. W.printHex("BoundDelayImportTable", Table->BoundDelayImportTable);
  1516. W.printHex("UnloadDelayImportTable", Table->UnloadDelayImportTable);
  1517. printDelayImportedSymbols(I, I.imported_symbols());
  1518. }
  1519. }
  1520. void COFFDumper::printCOFFExports() {
  1521. for (const ExportDirectoryEntryRef &Exp : Obj->export_directories()) {
  1522. DictScope Export(W, "Export");
  1523. StringRef Name;
  1524. uint32_t Ordinal, RVA;
  1525. if (Error E = Exp.getSymbolName(Name))
  1526. reportError(std::move(E), Obj->getFileName());
  1527. if (Error E = Exp.getOrdinal(Ordinal))
  1528. reportError(std::move(E), Obj->getFileName());
  1529. if (Error E = Exp.getExportRVA(RVA))
  1530. reportError(std::move(E), Obj->getFileName());
  1531. W.printNumber("Ordinal", Ordinal);
  1532. W.printString("Name", Name);
  1533. W.printHex("RVA", RVA);
  1534. }
  1535. }
  1536. void COFFDumper::printCOFFDirectives() {
  1537. for (const SectionRef &Section : Obj->sections()) {
  1538. StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
  1539. if (Name != ".drectve")
  1540. continue;
  1541. StringRef Contents =
  1542. unwrapOrError(Obj->getFileName(), Section.getContents());
  1543. W.printString("Directive(s)", Contents);
  1544. }
  1545. }
  1546. static std::string getBaseRelocTypeName(uint8_t Type) {
  1547. switch (Type) {
  1548. case COFF::IMAGE_REL_BASED_ABSOLUTE: return "ABSOLUTE";
  1549. case COFF::IMAGE_REL_BASED_HIGH: return "HIGH";
  1550. case COFF::IMAGE_REL_BASED_LOW: return "LOW";
  1551. case COFF::IMAGE_REL_BASED_HIGHLOW: return "HIGHLOW";
  1552. case COFF::IMAGE_REL_BASED_HIGHADJ: return "HIGHADJ";
  1553. case COFF::IMAGE_REL_BASED_ARM_MOV32T: return "ARM_MOV32(T)";
  1554. case COFF::IMAGE_REL_BASED_DIR64: return "DIR64";
  1555. default: return "unknown (" + llvm::utostr(Type) + ")";
  1556. }
  1557. }
  1558. void COFFDumper::printCOFFBaseReloc() {
  1559. ListScope D(W, "BaseReloc");
  1560. for (const BaseRelocRef &I : Obj->base_relocs()) {
  1561. uint8_t Type;
  1562. uint32_t RVA;
  1563. if (Error E = I.getRVA(RVA))
  1564. reportError(std::move(E), Obj->getFileName());
  1565. if (Error E = I.getType(Type))
  1566. reportError(std::move(E), Obj->getFileName());
  1567. DictScope Import(W, "Entry");
  1568. W.printString("Type", getBaseRelocTypeName(Type));
  1569. W.printHex("Address", RVA);
  1570. }
  1571. }
  1572. void COFFDumper::printCOFFResources() {
  1573. ListScope ResourcesD(W, "Resources");
  1574. for (const SectionRef &S : Obj->sections()) {
  1575. StringRef Name = unwrapOrError(Obj->getFileName(), S.getName());
  1576. if (!Name.startswith(".rsrc"))
  1577. continue;
  1578. StringRef Ref = unwrapOrError(Obj->getFileName(), S.getContents());
  1579. if ((Name == ".rsrc") || (Name == ".rsrc$01")) {
  1580. ResourceSectionRef RSF;
  1581. Error E = RSF.load(Obj, S);
  1582. if (E)
  1583. reportError(std::move(E), Obj->getFileName());
  1584. auto &BaseTable = unwrapOrError(Obj->getFileName(), RSF.getBaseTable());
  1585. W.printNumber("Total Number of Resources",
  1586. countTotalTableEntries(RSF, BaseTable, "Type"));
  1587. W.printHex("Base Table Address",
  1588. Obj->getCOFFSection(S)->PointerToRawData);
  1589. W.startLine() << "\n";
  1590. printResourceDirectoryTable(RSF, BaseTable, "Type");
  1591. }
  1592. if (opts::SectionData)
  1593. W.printBinaryBlock(Name.str() + " Data", Ref);
  1594. }
  1595. }
  1596. uint32_t
  1597. COFFDumper::countTotalTableEntries(ResourceSectionRef RSF,
  1598. const coff_resource_dir_table &Table,
  1599. StringRef Level) {
  1600. uint32_t TotalEntries = 0;
  1601. for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
  1602. i++) {
  1603. auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
  1604. if (Entry.Offset.isSubDir()) {
  1605. StringRef NextLevel;
  1606. if (Level == "Name")
  1607. NextLevel = "Language";
  1608. else
  1609. NextLevel = "Name";
  1610. auto &NextTable =
  1611. unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
  1612. TotalEntries += countTotalTableEntries(RSF, NextTable, NextLevel);
  1613. } else {
  1614. TotalEntries += 1;
  1615. }
  1616. }
  1617. return TotalEntries;
  1618. }
  1619. void COFFDumper::printResourceDirectoryTable(
  1620. ResourceSectionRef RSF, const coff_resource_dir_table &Table,
  1621. StringRef Level) {
  1622. W.printNumber("Number of String Entries", Table.NumberOfNameEntries);
  1623. W.printNumber("Number of ID Entries", Table.NumberOfIDEntries);
  1624. // Iterate through level in resource directory tree.
  1625. for (int i = 0; i < Table.NumberOfNameEntries + Table.NumberOfIDEntries;
  1626. i++) {
  1627. auto Entry = unwrapOrError(Obj->getFileName(), RSF.getTableEntry(Table, i));
  1628. StringRef Name;
  1629. SmallString<20> IDStr;
  1630. raw_svector_ostream OS(IDStr);
  1631. if (i < Table.NumberOfNameEntries) {
  1632. ArrayRef<UTF16> RawEntryNameString =
  1633. unwrapOrError(Obj->getFileName(), RSF.getEntryNameString(Entry));
  1634. std::vector<UTF16> EndianCorrectedNameString;
  1635. if (llvm::sys::IsBigEndianHost) {
  1636. EndianCorrectedNameString.resize(RawEntryNameString.size() + 1);
  1637. std::copy(RawEntryNameString.begin(), RawEntryNameString.end(),
  1638. EndianCorrectedNameString.begin() + 1);
  1639. EndianCorrectedNameString[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
  1640. RawEntryNameString = makeArrayRef(EndianCorrectedNameString);
  1641. }
  1642. std::string EntryNameString;
  1643. if (!llvm::convertUTF16ToUTF8String(RawEntryNameString, EntryNameString))
  1644. reportError(errorCodeToError(object_error::parse_failed),
  1645. Obj->getFileName());
  1646. OS << ": ";
  1647. OS << EntryNameString;
  1648. } else {
  1649. if (Level == "Type") {
  1650. OS << ": ";
  1651. printResourceTypeName(Entry.Identifier.ID, OS);
  1652. } else {
  1653. OS << ": (ID " << Entry.Identifier.ID << ")";
  1654. }
  1655. }
  1656. Name = IDStr;
  1657. ListScope ResourceType(W, Level.str() + Name.str());
  1658. if (Entry.Offset.isSubDir()) {
  1659. W.printHex("Table Offset", Entry.Offset.value());
  1660. StringRef NextLevel;
  1661. if (Level == "Name")
  1662. NextLevel = "Language";
  1663. else
  1664. NextLevel = "Name";
  1665. auto &NextTable =
  1666. unwrapOrError(Obj->getFileName(), RSF.getEntrySubDir(Entry));
  1667. printResourceDirectoryTable(RSF, NextTable, NextLevel);
  1668. } else {
  1669. W.printHex("Entry Offset", Entry.Offset.value());
  1670. char FormattedTime[20] = {};
  1671. time_t TDS = time_t(Table.TimeDateStamp);
  1672. strftime(FormattedTime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&TDS));
  1673. W.printHex("Time/Date Stamp", FormattedTime, Table.TimeDateStamp);
  1674. W.printNumber("Major Version", Table.MajorVersion);
  1675. W.printNumber("Minor Version", Table.MinorVersion);
  1676. W.printNumber("Characteristics", Table.Characteristics);
  1677. ListScope DataScope(W, "Data");
  1678. auto &DataEntry =
  1679. unwrapOrError(Obj->getFileName(), RSF.getEntryData(Entry));
  1680. W.printHex("DataRVA", DataEntry.DataRVA);
  1681. W.printNumber("DataSize", DataEntry.DataSize);
  1682. W.printNumber("Codepage", DataEntry.Codepage);
  1683. W.printNumber("Reserved", DataEntry.Reserved);
  1684. StringRef Contents =
  1685. unwrapOrError(Obj->getFileName(), RSF.getContents(DataEntry));
  1686. W.printBinaryBlock("Data", Contents);
  1687. }
  1688. }
  1689. }
  1690. void COFFDumper::printStackMap() const {
  1691. SectionRef StackMapSection;
  1692. for (auto Sec : Obj->sections()) {
  1693. StringRef Name;
  1694. if (Expected<StringRef> NameOrErr = Sec.getName())
  1695. Name = *NameOrErr;
  1696. else
  1697. consumeError(NameOrErr.takeError());
  1698. if (Name == ".llvm_stackmaps") {
  1699. StackMapSection = Sec;
  1700. break;
  1701. }
  1702. }
  1703. if (StackMapSection == SectionRef())
  1704. return;
  1705. StringRef StackMapContents =
  1706. unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
  1707. ArrayRef<uint8_t> StackMapContentsArray =
  1708. arrayRefFromStringRef(StackMapContents);
  1709. if (Obj->isLittleEndian())
  1710. prettyPrintStackMap(
  1711. W, StackMapParser<support::little>(StackMapContentsArray));
  1712. else
  1713. prettyPrintStackMap(
  1714. W, StackMapParser<support::big>(StackMapContentsArray));
  1715. }
  1716. void COFFDumper::printAddrsig() {
  1717. SectionRef AddrsigSection;
  1718. for (auto Sec : Obj->sections()) {
  1719. StringRef Name;
  1720. if (Expected<StringRef> NameOrErr = Sec.getName())
  1721. Name = *NameOrErr;
  1722. else
  1723. consumeError(NameOrErr.takeError());
  1724. if (Name == ".llvm_addrsig") {
  1725. AddrsigSection = Sec;
  1726. break;
  1727. }
  1728. }
  1729. if (AddrsigSection == SectionRef())
  1730. return;
  1731. StringRef AddrsigContents =
  1732. unwrapOrError(Obj->getFileName(), AddrsigSection.getContents());
  1733. ArrayRef<uint8_t> AddrsigContentsArray(AddrsigContents.bytes_begin(),
  1734. AddrsigContents.size());
  1735. ListScope L(W, "Addrsig");
  1736. const uint8_t *Cur = AddrsigContents.bytes_begin();
  1737. const uint8_t *End = AddrsigContents.bytes_end();
  1738. while (Cur != End) {
  1739. unsigned Size;
  1740. const char *Err;
  1741. uint64_t SymIndex = decodeULEB128(Cur, &Size, End, &Err);
  1742. if (Err)
  1743. reportError(createError(Err), Obj->getFileName());
  1744. W.printNumber("Sym", getSymbolName(SymIndex), SymIndex);
  1745. Cur += Size;
  1746. }
  1747. }
  1748. void COFFDumper::printCGProfile() {
  1749. SectionRef CGProfileSection;
  1750. for (SectionRef Sec : Obj->sections()) {
  1751. StringRef Name = unwrapOrError(Obj->getFileName(), Sec.getName());
  1752. if (Name == ".llvm.call-graph-profile") {
  1753. CGProfileSection = Sec;
  1754. break;
  1755. }
  1756. }
  1757. if (CGProfileSection == SectionRef())
  1758. return;
  1759. StringRef CGProfileContents =
  1760. unwrapOrError(Obj->getFileName(), CGProfileSection.getContents());
  1761. BinaryStreamReader Reader(CGProfileContents, llvm::support::little);
  1762. ListScope L(W, "CGProfile");
  1763. while (!Reader.empty()) {
  1764. uint32_t FromIndex, ToIndex;
  1765. uint64_t Count;
  1766. if (Error Err = Reader.readInteger(FromIndex))
  1767. reportError(std::move(Err), Obj->getFileName());
  1768. if (Error Err = Reader.readInteger(ToIndex))
  1769. reportError(std::move(Err), Obj->getFileName());
  1770. if (Error Err = Reader.readInteger(Count))
  1771. reportError(std::move(Err), Obj->getFileName());
  1772. DictScope D(W, "CGProfileEntry");
  1773. W.printNumber("From", getSymbolName(FromIndex), FromIndex);
  1774. W.printNumber("To", getSymbolName(ToIndex), ToIndex);
  1775. W.printNumber("Weight", Count);
  1776. }
  1777. }
  1778. StringRef COFFDumper::getSymbolName(uint32_t Index) {
  1779. Expected<COFFSymbolRef> Sym = Obj->getSymbol(Index);
  1780. if (!Sym)
  1781. reportError(Sym.takeError(), Obj->getFileName());
  1782. Expected<StringRef> SymName = Obj->getSymbolName(*Sym);
  1783. if (!SymName)
  1784. reportError(SymName.takeError(), Obj->getFileName());
  1785. return *SymName;
  1786. }
  1787. void llvm::dumpCodeViewMergedTypes(ScopedPrinter &Writer,
  1788. ArrayRef<ArrayRef<uint8_t>> IpiRecords,
  1789. ArrayRef<ArrayRef<uint8_t>> TpiRecords) {
  1790. TypeTableCollection TpiTypes(TpiRecords);
  1791. {
  1792. ListScope S(Writer, "MergedTypeStream");
  1793. TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
  1794. if (Error Err = codeview::visitTypeStream(TpiTypes, TDV))
  1795. reportError(std::move(Err), "<?>");
  1796. Writer.flush();
  1797. }
  1798. // Flatten the id stream and print it next. The ID stream refers to names from
  1799. // the type stream.
  1800. TypeTableCollection IpiTypes(IpiRecords);
  1801. {
  1802. ListScope S(Writer, "MergedIDStream");
  1803. TypeDumpVisitor TDV(TpiTypes, &Writer, opts::CodeViewSubsectionBytes);
  1804. TDV.setIpiTypes(IpiTypes);
  1805. if (Error Err = codeview::visitTypeStream(IpiTypes, TDV))
  1806. reportError(std::move(Err), "<?>");
  1807. Writer.flush();
  1808. }
  1809. }
  1810. void COFFDumper::printCOFFTLSDirectory() {
  1811. if (Obj->is64())
  1812. printCOFFTLSDirectory(Obj->getTLSDirectory64());
  1813. else
  1814. printCOFFTLSDirectory(Obj->getTLSDirectory32());
  1815. }
  1816. template <typename IntTy>
  1817. void COFFDumper::printCOFFTLSDirectory(
  1818. const coff_tls_directory<IntTy> *TlsTable) {
  1819. DictScope D(W, "TLSDirectory");
  1820. if (!TlsTable)
  1821. return;
  1822. W.printHex("StartAddressOfRawData", TlsTable->StartAddressOfRawData);
  1823. W.printHex("EndAddressOfRawData", TlsTable->EndAddressOfRawData);
  1824. W.printHex("AddressOfIndex", TlsTable->AddressOfIndex);
  1825. W.printHex("AddressOfCallBacks", TlsTable->AddressOfCallBacks);
  1826. W.printHex("SizeOfZeroFill", TlsTable->SizeOfZeroFill);
  1827. W.printFlags("Characteristics", TlsTable->Characteristics,
  1828. makeArrayRef(ImageSectionCharacteristics),
  1829. COFF::SectionCharacteristics(COFF::IMAGE_SCN_ALIGN_MASK));
  1830. }