COFFDumper.cpp 80 KB

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