COFFDumper.cpp 84 KB

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