llvm-objdump.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  1. //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This program is a utility that works like binutils "objdump", that is, it
  11. // dumps out a plethora of information about an object file depending on the
  12. // flags.
  13. //
  14. // The flags and output of this program should be near identical to those of
  15. // binutils objdump.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm-objdump.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/ADT/Triple.h"
  23. #include "llvm/CodeGen/FaultMaps.h"
  24. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  25. #include "llvm/MC/MCAsmInfo.h"
  26. #include "llvm/MC/MCContext.h"
  27. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  28. #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
  29. #include "llvm/MC/MCInst.h"
  30. #include "llvm/MC/MCInstPrinter.h"
  31. #include "llvm/MC/MCInstrAnalysis.h"
  32. #include "llvm/MC/MCInstrInfo.h"
  33. #include "llvm/MC/MCObjectFileInfo.h"
  34. #include "llvm/MC/MCRegisterInfo.h"
  35. #include "llvm/MC/MCSubtargetInfo.h"
  36. #include "llvm/Object/Archive.h"
  37. #include "llvm/Object/COFF.h"
  38. #include "llvm/Object/ELFObjectFile.h"
  39. #include "llvm/Object/MachO.h"
  40. #include "llvm/Object/ObjectFile.h"
  41. #include "llvm/Support/Casting.h"
  42. #include "llvm/Support/CommandLine.h"
  43. #include "llvm/Support/Debug.h"
  44. #include "llvm/Support/Errc.h"
  45. #include "llvm/Support/FileSystem.h"
  46. #include "llvm/Support/Format.h"
  47. #include "llvm/Support/GraphWriter.h"
  48. #include "llvm/Support/Host.h"
  49. #include "llvm/Support/ManagedStatic.h"
  50. #include "llvm/Support/MemoryBuffer.h"
  51. #include "llvm/Support/PrettyStackTrace.h"
  52. #include "llvm/Support/Signals.h"
  53. #include "llvm/Support/SourceMgr.h"
  54. #include "llvm/Support/TargetRegistry.h"
  55. #include "llvm/Support/TargetSelect.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include <algorithm>
  58. #include <cctype>
  59. #include <cstring>
  60. #include <system_error>
  61. #include <utility>
  62. using namespace llvm;
  63. using namespace object;
  64. static cl::list<std::string>
  65. InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
  66. cl::opt<bool>
  67. llvm::Disassemble("disassemble",
  68. cl::desc("Display assembler mnemonics for the machine instructions"));
  69. static cl::alias
  70. Disassembled("d", cl::desc("Alias for --disassemble"),
  71. cl::aliasopt(Disassemble));
  72. cl::opt<bool>
  73. llvm::DisassembleAll("disassemble-all",
  74. cl::desc("Display assembler mnemonics for the machine instructions"));
  75. static cl::alias
  76. DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
  77. cl::aliasopt(DisassembleAll));
  78. cl::opt<bool>
  79. llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
  80. cl::opt<bool>
  81. llvm::SectionContents("s", cl::desc("Display the content of each section"));
  82. cl::opt<bool>
  83. llvm::SymbolTable("t", cl::desc("Display the symbol table"));
  84. cl::opt<bool>
  85. llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
  86. cl::opt<bool>
  87. llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
  88. cl::opt<bool>
  89. llvm::Bind("bind", cl::desc("Display mach-o binding info"));
  90. cl::opt<bool>
  91. llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
  92. cl::opt<bool>
  93. llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
  94. cl::opt<bool>
  95. llvm::RawClangAST("raw-clang-ast",
  96. cl::desc("Dump the raw binary contents of the clang AST section"));
  97. static cl::opt<bool>
  98. MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
  99. static cl::alias
  100. MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
  101. cl::opt<std::string>
  102. llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
  103. "see -version for available targets"));
  104. cl::opt<std::string>
  105. llvm::MCPU("mcpu",
  106. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  107. cl::value_desc("cpu-name"),
  108. cl::init(""));
  109. cl::opt<std::string>
  110. llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
  111. "see -version for available targets"));
  112. cl::opt<bool>
  113. llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
  114. "headers for each section."));
  115. static cl::alias
  116. SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
  117. cl::aliasopt(SectionHeaders));
  118. static cl::alias
  119. SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
  120. cl::aliasopt(SectionHeaders));
  121. cl::list<std::string>
  122. llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
  123. "With -macho dump segment,section"));
  124. cl::alias
  125. static FilterSectionsj("j", cl::desc("Alias for --section"),
  126. cl::aliasopt(llvm::FilterSections));
  127. cl::list<std::string>
  128. llvm::MAttrs("mattr",
  129. cl::CommaSeparated,
  130. cl::desc("Target specific attributes"),
  131. cl::value_desc("a1,+a2,-a3,..."));
  132. cl::opt<bool>
  133. llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
  134. "instructions, do not print "
  135. "the instruction bytes."));
  136. cl::opt<bool>
  137. llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
  138. static cl::alias
  139. UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
  140. cl::aliasopt(UnwindInfo));
  141. cl::opt<bool>
  142. llvm::PrivateHeaders("private-headers",
  143. cl::desc("Display format specific file headers"));
  144. cl::opt<bool>
  145. llvm::FirstPrivateHeader("private-header",
  146. cl::desc("Display only the first format specific file "
  147. "header"));
  148. static cl::alias
  149. PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
  150. cl::aliasopt(PrivateHeaders));
  151. cl::opt<bool>
  152. llvm::PrintImmHex("print-imm-hex",
  153. cl::desc("Use hex format for immediate values"));
  154. cl::opt<bool> PrintFaultMaps("fault-map-section",
  155. cl::desc("Display contents of faultmap section"));
  156. cl::opt<DIDumpType> llvm::DwarfDumpType(
  157. "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
  158. cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
  159. clEnumValEnd));
  160. static StringRef ToolName;
  161. namespace {
  162. typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
  163. class SectionFilterIterator {
  164. public:
  165. SectionFilterIterator(FilterPredicate P,
  166. llvm::object::section_iterator const &I,
  167. llvm::object::section_iterator const &E)
  168. : Predicate(std::move(P)), Iterator(I), End(E) {
  169. ScanPredicate();
  170. }
  171. const llvm::object::SectionRef &operator*() const { return *Iterator; }
  172. SectionFilterIterator &operator++() {
  173. ++Iterator;
  174. ScanPredicate();
  175. return *this;
  176. }
  177. bool operator!=(SectionFilterIterator const &Other) const {
  178. return Iterator != Other.Iterator;
  179. }
  180. private:
  181. void ScanPredicate() {
  182. while (Iterator != End && !Predicate(*Iterator)) {
  183. ++Iterator;
  184. }
  185. }
  186. FilterPredicate Predicate;
  187. llvm::object::section_iterator Iterator;
  188. llvm::object::section_iterator End;
  189. };
  190. class SectionFilter {
  191. public:
  192. SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
  193. : Predicate(std::move(P)), Object(O) {}
  194. SectionFilterIterator begin() {
  195. return SectionFilterIterator(Predicate, Object.section_begin(),
  196. Object.section_end());
  197. }
  198. SectionFilterIterator end() {
  199. return SectionFilterIterator(Predicate, Object.section_end(),
  200. Object.section_end());
  201. }
  202. private:
  203. FilterPredicate Predicate;
  204. llvm::object::ObjectFile const &Object;
  205. };
  206. SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
  207. return SectionFilter([](llvm::object::SectionRef const &S) {
  208. if(FilterSections.empty())
  209. return true;
  210. llvm::StringRef String;
  211. std::error_code error = S.getName(String);
  212. if (error)
  213. return false;
  214. return std::find(FilterSections.begin(),
  215. FilterSections.end(),
  216. String) != FilterSections.end();
  217. },
  218. O);
  219. }
  220. }
  221. void llvm::error(std::error_code EC) {
  222. if (!EC)
  223. return;
  224. errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
  225. errs().flush();
  226. exit(1);
  227. }
  228. LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
  229. errs() << ToolName << ": " << Message << ".\n";
  230. errs().flush();
  231. exit(1);
  232. }
  233. LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
  234. std::error_code EC) {
  235. assert(EC);
  236. errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
  237. exit(1);
  238. }
  239. LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
  240. llvm::Error E) {
  241. assert(E);
  242. std::string Buf;
  243. raw_string_ostream OS(Buf);
  244. logAllUnhandledErrors(std::move(E), OS, "");
  245. OS.flush();
  246. errs() << ToolName << ": '" << File << "': " << Buf;
  247. exit(1);
  248. }
  249. LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
  250. StringRef FileName,
  251. llvm::Error E,
  252. StringRef ArchitectureName) {
  253. assert(E);
  254. errs() << ToolName << ": ";
  255. if (ArchiveName != "")
  256. errs() << ArchiveName << "(" << FileName << ")";
  257. else
  258. errs() << FileName;
  259. if (!ArchitectureName.empty())
  260. errs() << " (for architecture " << ArchitectureName << ")";
  261. std::string Buf;
  262. raw_string_ostream OS(Buf);
  263. logAllUnhandledErrors(std::move(E), OS, "");
  264. OS.flush();
  265. errs() << " " << Buf;
  266. exit(1);
  267. }
  268. LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
  269. const object::Archive::Child &C,
  270. llvm::Error E,
  271. StringRef ArchitectureName) {
  272. ErrorOr<StringRef> NameOrErr = C.getName();
  273. // TODO: if we have a error getting the name then it would be nice to print
  274. // the index of which archive member this is and or its offset in the
  275. // archive instead of "???" as the name.
  276. if (NameOrErr.getError())
  277. llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
  278. else
  279. llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
  280. ArchitectureName);
  281. }
  282. static const Target *getTarget(const ObjectFile *Obj = nullptr) {
  283. // Figure out the target triple.
  284. llvm::Triple TheTriple("unknown-unknown-unknown");
  285. if (TripleName.empty()) {
  286. if (Obj) {
  287. TheTriple.setArch(Triple::ArchType(Obj->getArch()));
  288. // TheTriple defaults to ELF, and COFF doesn't have an environment:
  289. // the best we can do here is indicate that it is mach-o.
  290. if (Obj->isMachO())
  291. TheTriple.setObjectFormat(Triple::MachO);
  292. if (Obj->isCOFF()) {
  293. const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
  294. if (COFFObj->getArch() == Triple::thumb)
  295. TheTriple.setTriple("thumbv7-windows");
  296. }
  297. }
  298. } else
  299. TheTriple.setTriple(Triple::normalize(TripleName));
  300. // Get the target specific parser.
  301. std::string Error;
  302. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  303. Error);
  304. if (!TheTarget)
  305. report_fatal_error("can't find target: " + Error);
  306. // Update the triple name and return the found target.
  307. TripleName = TheTriple.getTriple();
  308. return TheTarget;
  309. }
  310. bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
  311. return a.getOffset() < b.getOffset();
  312. }
  313. namespace {
  314. class PrettyPrinter {
  315. public:
  316. virtual ~PrettyPrinter(){}
  317. virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
  318. ArrayRef<uint8_t> Bytes, uint64_t Address,
  319. raw_ostream &OS, StringRef Annot,
  320. MCSubtargetInfo const &STI) {
  321. OS << format("%8" PRIx64 ":", Address);
  322. if (!NoShowRawInsn) {
  323. OS << "\t";
  324. dumpBytes(Bytes, OS);
  325. }
  326. if (MI)
  327. IP.printInst(MI, OS, "", STI);
  328. else
  329. OS << " <unknown>";
  330. }
  331. };
  332. PrettyPrinter PrettyPrinterInst;
  333. class HexagonPrettyPrinter : public PrettyPrinter {
  334. public:
  335. void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
  336. raw_ostream &OS) {
  337. uint32_t opcode =
  338. (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
  339. OS << format("%8" PRIx64 ":", Address);
  340. if (!NoShowRawInsn) {
  341. OS << "\t";
  342. dumpBytes(Bytes.slice(0, 4), OS);
  343. OS << format("%08" PRIx32, opcode);
  344. }
  345. }
  346. void printInst(MCInstPrinter &IP, const MCInst *MI,
  347. ArrayRef<uint8_t> Bytes, uint64_t Address,
  348. raw_ostream &OS, StringRef Annot,
  349. MCSubtargetInfo const &STI) override {
  350. if (!MI) {
  351. printLead(Bytes, Address, OS);
  352. OS << " <unknown>";
  353. return;
  354. }
  355. std::string Buffer;
  356. {
  357. raw_string_ostream TempStream(Buffer);
  358. IP.printInst(MI, TempStream, "", STI);
  359. }
  360. StringRef Contents(Buffer);
  361. // Split off bundle attributes
  362. auto PacketBundle = Contents.rsplit('\n');
  363. // Split off first instruction from the rest
  364. auto HeadTail = PacketBundle.first.split('\n');
  365. auto Preamble = " { ";
  366. auto Separator = "";
  367. while(!HeadTail.first.empty()) {
  368. OS << Separator;
  369. Separator = "\n";
  370. printLead(Bytes, Address, OS);
  371. OS << Preamble;
  372. Preamble = " ";
  373. StringRef Inst;
  374. auto Duplex = HeadTail.first.split('\v');
  375. if(!Duplex.second.empty()){
  376. OS << Duplex.first;
  377. OS << "; ";
  378. Inst = Duplex.second;
  379. }
  380. else
  381. Inst = HeadTail.first;
  382. OS << Inst;
  383. Bytes = Bytes.slice(4);
  384. Address += 4;
  385. HeadTail = HeadTail.second.split('\n');
  386. }
  387. OS << " } " << PacketBundle.second;
  388. }
  389. };
  390. HexagonPrettyPrinter HexagonPrettyPrinterInst;
  391. class AMDGCNPrettyPrinter : public PrettyPrinter {
  392. public:
  393. void printInst(MCInstPrinter &IP,
  394. const MCInst *MI,
  395. ArrayRef<uint8_t> Bytes,
  396. uint64_t Address,
  397. raw_ostream &OS,
  398. StringRef Annot,
  399. MCSubtargetInfo const &STI) override {
  400. if (!MI) {
  401. OS << " <unknown>";
  402. return;
  403. }
  404. SmallString<40> InstStr;
  405. raw_svector_ostream IS(InstStr);
  406. IP.printInst(MI, IS, "", STI);
  407. OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
  408. typedef support::ulittle32_t U32;
  409. for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
  410. Bytes.size() / sizeof(U32)))
  411. // D should be explicitly casted to uint32_t here as it is passed
  412. // by format to snprintf as vararg.
  413. OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
  414. if (!Annot.empty())
  415. OS << "// " << Annot;
  416. }
  417. };
  418. AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
  419. PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
  420. switch(Triple.getArch()) {
  421. default:
  422. return PrettyPrinterInst;
  423. case Triple::hexagon:
  424. return HexagonPrettyPrinterInst;
  425. case Triple::amdgcn:
  426. return AMDGCNPrettyPrinterInst;
  427. }
  428. }
  429. }
  430. template <class ELFT>
  431. static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
  432. const RelocationRef &RelRef,
  433. SmallVectorImpl<char> &Result) {
  434. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  435. typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
  436. typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
  437. typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
  438. const ELFFile<ELFT> &EF = *Obj->getELFFile();
  439. ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
  440. if (std::error_code EC = SecOrErr.getError())
  441. return EC;
  442. const Elf_Shdr *Sec = *SecOrErr;
  443. ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
  444. if (std::error_code EC = SymTabOrErr.getError())
  445. return EC;
  446. const Elf_Shdr *SymTab = *SymTabOrErr;
  447. assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
  448. SymTab->sh_type == ELF::SHT_DYNSYM);
  449. ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
  450. if (std::error_code EC = StrTabSec.getError())
  451. return EC;
  452. ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
  453. if (std::error_code EC = StrTabOrErr.getError())
  454. return EC;
  455. StringRef StrTab = *StrTabOrErr;
  456. uint8_t type = RelRef.getType();
  457. StringRef res;
  458. int64_t addend = 0;
  459. switch (Sec->sh_type) {
  460. default:
  461. return object_error::parse_failed;
  462. case ELF::SHT_REL: {
  463. // TODO: Read implicit addend from section data.
  464. break;
  465. }
  466. case ELF::SHT_RELA: {
  467. const Elf_Rela *ERela = Obj->getRela(Rel);
  468. addend = ERela->r_addend;
  469. break;
  470. }
  471. }
  472. symbol_iterator SI = RelRef.getSymbol();
  473. const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
  474. StringRef Target;
  475. if (symb->getType() == ELF::STT_SECTION) {
  476. Expected<section_iterator> SymSI = SI->getSection();
  477. if (!SymSI)
  478. return errorToErrorCode(SymSI.takeError());
  479. const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
  480. ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
  481. if (std::error_code EC = SecName.getError())
  482. return EC;
  483. Target = *SecName;
  484. } else {
  485. Expected<StringRef> SymName = symb->getName(StrTab);
  486. if (!SymName)
  487. return errorToErrorCode(SymName.takeError());
  488. Target = *SymName;
  489. }
  490. switch (EF.getHeader()->e_machine) {
  491. case ELF::EM_X86_64:
  492. switch (type) {
  493. case ELF::R_X86_64_PC8:
  494. case ELF::R_X86_64_PC16:
  495. case ELF::R_X86_64_PC32: {
  496. std::string fmtbuf;
  497. raw_string_ostream fmt(fmtbuf);
  498. fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
  499. fmt.flush();
  500. Result.append(fmtbuf.begin(), fmtbuf.end());
  501. } break;
  502. case ELF::R_X86_64_8:
  503. case ELF::R_X86_64_16:
  504. case ELF::R_X86_64_32:
  505. case ELF::R_X86_64_32S:
  506. case ELF::R_X86_64_64: {
  507. std::string fmtbuf;
  508. raw_string_ostream fmt(fmtbuf);
  509. fmt << Target << (addend < 0 ? "" : "+") << addend;
  510. fmt.flush();
  511. Result.append(fmtbuf.begin(), fmtbuf.end());
  512. } break;
  513. default:
  514. res = "Unknown";
  515. }
  516. break;
  517. case ELF::EM_LANAI:
  518. case ELF::EM_AARCH64: {
  519. std::string fmtbuf;
  520. raw_string_ostream fmt(fmtbuf);
  521. fmt << Target;
  522. if (addend != 0)
  523. fmt << (addend < 0 ? "" : "+") << addend;
  524. fmt.flush();
  525. Result.append(fmtbuf.begin(), fmtbuf.end());
  526. break;
  527. }
  528. case ELF::EM_386:
  529. case ELF::EM_IAMCU:
  530. case ELF::EM_ARM:
  531. case ELF::EM_HEXAGON:
  532. case ELF::EM_MIPS:
  533. res = Target;
  534. break;
  535. case ELF::EM_WEBASSEMBLY:
  536. switch (type) {
  537. case ELF::R_WEBASSEMBLY_DATA: {
  538. std::string fmtbuf;
  539. raw_string_ostream fmt(fmtbuf);
  540. fmt << Target << (addend < 0 ? "" : "+") << addend;
  541. fmt.flush();
  542. Result.append(fmtbuf.begin(), fmtbuf.end());
  543. break;
  544. }
  545. case ELF::R_WEBASSEMBLY_FUNCTION:
  546. res = Target;
  547. break;
  548. default:
  549. res = "Unknown";
  550. }
  551. break;
  552. default:
  553. res = "Unknown";
  554. }
  555. if (Result.empty())
  556. Result.append(res.begin(), res.end());
  557. return std::error_code();
  558. }
  559. static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
  560. const RelocationRef &Rel,
  561. SmallVectorImpl<char> &Result) {
  562. if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
  563. return getRelocationValueString(ELF32LE, Rel, Result);
  564. if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
  565. return getRelocationValueString(ELF64LE, Rel, Result);
  566. if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
  567. return getRelocationValueString(ELF32BE, Rel, Result);
  568. auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
  569. return getRelocationValueString(ELF64BE, Rel, Result);
  570. }
  571. static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
  572. const RelocationRef &Rel,
  573. SmallVectorImpl<char> &Result) {
  574. symbol_iterator SymI = Rel.getSymbol();
  575. Expected<StringRef> SymNameOrErr = SymI->getName();
  576. if (!SymNameOrErr)
  577. return errorToErrorCode(SymNameOrErr.takeError());
  578. StringRef SymName = *SymNameOrErr;
  579. Result.append(SymName.begin(), SymName.end());
  580. return std::error_code();
  581. }
  582. static void printRelocationTargetName(const MachOObjectFile *O,
  583. const MachO::any_relocation_info &RE,
  584. raw_string_ostream &fmt) {
  585. bool IsScattered = O->isRelocationScattered(RE);
  586. // Target of a scattered relocation is an address. In the interest of
  587. // generating pretty output, scan through the symbol table looking for a
  588. // symbol that aligns with that address. If we find one, print it.
  589. // Otherwise, we just print the hex address of the target.
  590. if (IsScattered) {
  591. uint32_t Val = O->getPlainRelocationSymbolNum(RE);
  592. for (const SymbolRef &Symbol : O->symbols()) {
  593. std::error_code ec;
  594. Expected<uint64_t> Addr = Symbol.getAddress();
  595. if (!Addr) {
  596. std::string Buf;
  597. raw_string_ostream OS(Buf);
  598. logAllUnhandledErrors(Addr.takeError(), OS, "");
  599. OS.flush();
  600. report_fatal_error(Buf);
  601. }
  602. if (*Addr != Val)
  603. continue;
  604. Expected<StringRef> Name = Symbol.getName();
  605. if (!Name) {
  606. std::string Buf;
  607. raw_string_ostream OS(Buf);
  608. logAllUnhandledErrors(Name.takeError(), OS, "");
  609. OS.flush();
  610. report_fatal_error(Buf);
  611. }
  612. fmt << *Name;
  613. return;
  614. }
  615. // If we couldn't find a symbol that this relocation refers to, try
  616. // to find a section beginning instead.
  617. for (const SectionRef &Section : ToolSectionFilter(*O)) {
  618. std::error_code ec;
  619. StringRef Name;
  620. uint64_t Addr = Section.getAddress();
  621. if (Addr != Val)
  622. continue;
  623. if ((ec = Section.getName(Name)))
  624. report_fatal_error(ec.message());
  625. fmt << Name;
  626. return;
  627. }
  628. fmt << format("0x%x", Val);
  629. return;
  630. }
  631. StringRef S;
  632. bool isExtern = O->getPlainRelocationExternal(RE);
  633. uint64_t Val = O->getPlainRelocationSymbolNum(RE);
  634. if (isExtern) {
  635. symbol_iterator SI = O->symbol_begin();
  636. advance(SI, Val);
  637. Expected<StringRef> SOrErr = SI->getName();
  638. error(errorToErrorCode(SOrErr.takeError()));
  639. S = *SOrErr;
  640. } else {
  641. section_iterator SI = O->section_begin();
  642. // Adjust for the fact that sections are 1-indexed.
  643. advance(SI, Val - 1);
  644. SI->getName(S);
  645. }
  646. fmt << S;
  647. }
  648. static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
  649. const RelocationRef &RelRef,
  650. SmallVectorImpl<char> &Result) {
  651. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  652. MachO::any_relocation_info RE = Obj->getRelocation(Rel);
  653. unsigned Arch = Obj->getArch();
  654. std::string fmtbuf;
  655. raw_string_ostream fmt(fmtbuf);
  656. unsigned Type = Obj->getAnyRelocationType(RE);
  657. bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
  658. // Determine any addends that should be displayed with the relocation.
  659. // These require decoding the relocation type, which is triple-specific.
  660. // X86_64 has entirely custom relocation types.
  661. if (Arch == Triple::x86_64) {
  662. bool isPCRel = Obj->getAnyRelocationPCRel(RE);
  663. switch (Type) {
  664. case MachO::X86_64_RELOC_GOT_LOAD:
  665. case MachO::X86_64_RELOC_GOT: {
  666. printRelocationTargetName(Obj, RE, fmt);
  667. fmt << "@GOT";
  668. if (isPCRel)
  669. fmt << "PCREL";
  670. break;
  671. }
  672. case MachO::X86_64_RELOC_SUBTRACTOR: {
  673. DataRefImpl RelNext = Rel;
  674. Obj->moveRelocationNext(RelNext);
  675. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  676. // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
  677. // X86_64_RELOC_UNSIGNED.
  678. // NOTE: Scattered relocations don't exist on x86_64.
  679. unsigned RType = Obj->getAnyRelocationType(RENext);
  680. if (RType != MachO::X86_64_RELOC_UNSIGNED)
  681. report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
  682. "X86_64_RELOC_SUBTRACTOR.");
  683. // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
  684. // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
  685. printRelocationTargetName(Obj, RENext, fmt);
  686. fmt << "-";
  687. printRelocationTargetName(Obj, RE, fmt);
  688. break;
  689. }
  690. case MachO::X86_64_RELOC_TLV:
  691. printRelocationTargetName(Obj, RE, fmt);
  692. fmt << "@TLV";
  693. if (isPCRel)
  694. fmt << "P";
  695. break;
  696. case MachO::X86_64_RELOC_SIGNED_1:
  697. printRelocationTargetName(Obj, RE, fmt);
  698. fmt << "-1";
  699. break;
  700. case MachO::X86_64_RELOC_SIGNED_2:
  701. printRelocationTargetName(Obj, RE, fmt);
  702. fmt << "-2";
  703. break;
  704. case MachO::X86_64_RELOC_SIGNED_4:
  705. printRelocationTargetName(Obj, RE, fmt);
  706. fmt << "-4";
  707. break;
  708. default:
  709. printRelocationTargetName(Obj, RE, fmt);
  710. break;
  711. }
  712. // X86 and ARM share some relocation types in common.
  713. } else if (Arch == Triple::x86 || Arch == Triple::arm ||
  714. Arch == Triple::ppc) {
  715. // Generic relocation types...
  716. switch (Type) {
  717. case MachO::GENERIC_RELOC_PAIR: // prints no info
  718. return std::error_code();
  719. case MachO::GENERIC_RELOC_SECTDIFF: {
  720. DataRefImpl RelNext = Rel;
  721. Obj->moveRelocationNext(RelNext);
  722. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  723. // X86 sect diff's must be followed by a relocation of type
  724. // GENERIC_RELOC_PAIR.
  725. unsigned RType = Obj->getAnyRelocationType(RENext);
  726. if (RType != MachO::GENERIC_RELOC_PAIR)
  727. report_fatal_error("Expected GENERIC_RELOC_PAIR after "
  728. "GENERIC_RELOC_SECTDIFF.");
  729. printRelocationTargetName(Obj, RE, fmt);
  730. fmt << "-";
  731. printRelocationTargetName(Obj, RENext, fmt);
  732. break;
  733. }
  734. }
  735. if (Arch == Triple::x86 || Arch == Triple::ppc) {
  736. switch (Type) {
  737. case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
  738. DataRefImpl RelNext = Rel;
  739. Obj->moveRelocationNext(RelNext);
  740. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  741. // X86 sect diff's must be followed by a relocation of type
  742. // GENERIC_RELOC_PAIR.
  743. unsigned RType = Obj->getAnyRelocationType(RENext);
  744. if (RType != MachO::GENERIC_RELOC_PAIR)
  745. report_fatal_error("Expected GENERIC_RELOC_PAIR after "
  746. "GENERIC_RELOC_LOCAL_SECTDIFF.");
  747. printRelocationTargetName(Obj, RE, fmt);
  748. fmt << "-";
  749. printRelocationTargetName(Obj, RENext, fmt);
  750. break;
  751. }
  752. case MachO::GENERIC_RELOC_TLV: {
  753. printRelocationTargetName(Obj, RE, fmt);
  754. fmt << "@TLV";
  755. if (IsPCRel)
  756. fmt << "P";
  757. break;
  758. }
  759. default:
  760. printRelocationTargetName(Obj, RE, fmt);
  761. }
  762. } else { // ARM-specific relocations
  763. switch (Type) {
  764. case MachO::ARM_RELOC_HALF:
  765. case MachO::ARM_RELOC_HALF_SECTDIFF: {
  766. // Half relocations steal a bit from the length field to encode
  767. // whether this is an upper16 or a lower16 relocation.
  768. bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
  769. if (isUpper)
  770. fmt << ":upper16:(";
  771. else
  772. fmt << ":lower16:(";
  773. printRelocationTargetName(Obj, RE, fmt);
  774. DataRefImpl RelNext = Rel;
  775. Obj->moveRelocationNext(RelNext);
  776. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  777. // ARM half relocs must be followed by a relocation of type
  778. // ARM_RELOC_PAIR.
  779. unsigned RType = Obj->getAnyRelocationType(RENext);
  780. if (RType != MachO::ARM_RELOC_PAIR)
  781. report_fatal_error("Expected ARM_RELOC_PAIR after "
  782. "ARM_RELOC_HALF");
  783. // NOTE: The half of the target virtual address is stashed in the
  784. // address field of the secondary relocation, but we can't reverse
  785. // engineer the constant offset from it without decoding the movw/movt
  786. // instruction to find the other half in its immediate field.
  787. // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
  788. // symbol/section pointer of the follow-on relocation.
  789. if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  790. fmt << "-";
  791. printRelocationTargetName(Obj, RENext, fmt);
  792. }
  793. fmt << ")";
  794. break;
  795. }
  796. default: { printRelocationTargetName(Obj, RE, fmt); }
  797. }
  798. }
  799. } else
  800. printRelocationTargetName(Obj, RE, fmt);
  801. fmt.flush();
  802. Result.append(fmtbuf.begin(), fmtbuf.end());
  803. return std::error_code();
  804. }
  805. static std::error_code getRelocationValueString(const RelocationRef &Rel,
  806. SmallVectorImpl<char> &Result) {
  807. const ObjectFile *Obj = Rel.getObject();
  808. if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
  809. return getRelocationValueString(ELF, Rel, Result);
  810. if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
  811. return getRelocationValueString(COFF, Rel, Result);
  812. auto *MachO = cast<MachOObjectFile>(Obj);
  813. return getRelocationValueString(MachO, Rel, Result);
  814. }
  815. /// @brief Indicates whether this relocation should hidden when listing
  816. /// relocations, usually because it is the trailing part of a multipart
  817. /// relocation that will be printed as part of the leading relocation.
  818. static bool getHidden(RelocationRef RelRef) {
  819. const ObjectFile *Obj = RelRef.getObject();
  820. auto *MachO = dyn_cast<MachOObjectFile>(Obj);
  821. if (!MachO)
  822. return false;
  823. unsigned Arch = MachO->getArch();
  824. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  825. uint64_t Type = MachO->getRelocationType(Rel);
  826. // On arches that use the generic relocations, GENERIC_RELOC_PAIR
  827. // is always hidden.
  828. if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
  829. if (Type == MachO::GENERIC_RELOC_PAIR)
  830. return true;
  831. } else if (Arch == Triple::x86_64) {
  832. // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
  833. // an X86_64_RELOC_SUBTRACTOR.
  834. if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
  835. DataRefImpl RelPrev = Rel;
  836. RelPrev.d.a--;
  837. uint64_t PrevType = MachO->getRelocationType(RelPrev);
  838. if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
  839. return true;
  840. }
  841. }
  842. return false;
  843. }
  844. static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
  845. const Target *TheTarget = getTarget(Obj);
  846. // Package up features to be passed to target/subtarget
  847. SubtargetFeatures Features = Obj->getFeatures();
  848. if (MAttrs.size()) {
  849. for (unsigned i = 0; i != MAttrs.size(); ++i)
  850. Features.AddFeature(MAttrs[i]);
  851. }
  852. std::unique_ptr<const MCRegisterInfo> MRI(
  853. TheTarget->createMCRegInfo(TripleName));
  854. if (!MRI)
  855. report_fatal_error("error: no register info for target " + TripleName);
  856. // Set up disassembler.
  857. std::unique_ptr<const MCAsmInfo> AsmInfo(
  858. TheTarget->createMCAsmInfo(*MRI, TripleName));
  859. if (!AsmInfo)
  860. report_fatal_error("error: no assembly info for target " + TripleName);
  861. std::unique_ptr<const MCSubtargetInfo> STI(
  862. TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
  863. if (!STI)
  864. report_fatal_error("error: no subtarget info for target " + TripleName);
  865. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  866. if (!MII)
  867. report_fatal_error("error: no instruction info for target " + TripleName);
  868. std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
  869. MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
  870. std::unique_ptr<MCDisassembler> DisAsm(
  871. TheTarget->createMCDisassembler(*STI, Ctx));
  872. if (!DisAsm)
  873. report_fatal_error("error: no disassembler for target " + TripleName);
  874. std::unique_ptr<const MCInstrAnalysis> MIA(
  875. TheTarget->createMCInstrAnalysis(MII.get()));
  876. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  877. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  878. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
  879. if (!IP)
  880. report_fatal_error("error: no instruction printer for target " +
  881. TripleName);
  882. IP->setPrintImmHex(PrintImmHex);
  883. PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
  884. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
  885. "\t\t\t%08" PRIx64 ": ";
  886. // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
  887. // in RelocSecs contain the relocations for section S.
  888. std::error_code EC;
  889. std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
  890. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  891. section_iterator Sec2 = Section.getRelocatedSection();
  892. if (Sec2 != Obj->section_end())
  893. SectionRelocMap[*Sec2].push_back(Section);
  894. }
  895. // Create a mapping from virtual address to symbol name. This is used to
  896. // pretty print the symbols while disassembling.
  897. typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
  898. std::map<SectionRef, SectionSymbolsTy> AllSymbols;
  899. for (const SymbolRef &Symbol : Obj->symbols()) {
  900. Expected<uint64_t> AddressOrErr = Symbol.getAddress();
  901. error(errorToErrorCode(AddressOrErr.takeError()));
  902. uint64_t Address = *AddressOrErr;
  903. Expected<StringRef> Name = Symbol.getName();
  904. error(errorToErrorCode(Name.takeError()));
  905. if (Name->empty())
  906. continue;
  907. Expected<section_iterator> SectionOrErr = Symbol.getSection();
  908. error(errorToErrorCode(SectionOrErr.takeError()));
  909. section_iterator SecI = *SectionOrErr;
  910. if (SecI == Obj->section_end())
  911. continue;
  912. AllSymbols[*SecI].emplace_back(Address, *Name);
  913. }
  914. // Create a mapping from virtual address to section.
  915. std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
  916. for (SectionRef Sec : Obj->sections())
  917. SectionAddresses.emplace_back(Sec.getAddress(), Sec);
  918. array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
  919. // Linked executables (.exe and .dll files) typically don't include a real
  920. // symbol table but they might contain an export table.
  921. if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
  922. for (const auto &ExportEntry : COFFObj->export_directories()) {
  923. StringRef Name;
  924. error(ExportEntry.getSymbolName(Name));
  925. if (Name.empty())
  926. continue;
  927. uint32_t RVA;
  928. error(ExportEntry.getExportRVA(RVA));
  929. uint64_t VA = COFFObj->getImageBase() + RVA;
  930. auto Sec = std::upper_bound(
  931. SectionAddresses.begin(), SectionAddresses.end(), VA,
  932. [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
  933. return LHS < RHS.first;
  934. });
  935. if (Sec != SectionAddresses.begin())
  936. --Sec;
  937. else
  938. Sec = SectionAddresses.end();
  939. if (Sec != SectionAddresses.end())
  940. AllSymbols[Sec->second].emplace_back(VA, Name);
  941. }
  942. }
  943. // Sort all the symbols, this allows us to use a simple binary search to find
  944. // a symbol near an address.
  945. for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
  946. array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
  947. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  948. if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
  949. continue;
  950. uint64_t SectionAddr = Section.getAddress();
  951. uint64_t SectSize = Section.getSize();
  952. if (!SectSize)
  953. continue;
  954. // Get the list of all the symbols in this section.
  955. SectionSymbolsTy &Symbols = AllSymbols[Section];
  956. std::vector<uint64_t> DataMappingSymsAddr;
  957. std::vector<uint64_t> TextMappingSymsAddr;
  958. if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
  959. for (const auto &Symb : Symbols) {
  960. uint64_t Address = Symb.first;
  961. StringRef Name = Symb.second;
  962. if (Name.startswith("$d"))
  963. DataMappingSymsAddr.push_back(Address - SectionAddr);
  964. if (Name.startswith("$x"))
  965. TextMappingSymsAddr.push_back(Address - SectionAddr);
  966. }
  967. }
  968. std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
  969. std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
  970. // Make a list of all the relocations for this section.
  971. std::vector<RelocationRef> Rels;
  972. if (InlineRelocs) {
  973. for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
  974. for (const RelocationRef &Reloc : RelocSec.relocations()) {
  975. Rels.push_back(Reloc);
  976. }
  977. }
  978. }
  979. // Sort relocations by address.
  980. std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
  981. StringRef SegmentName = "";
  982. if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
  983. DataRefImpl DR = Section.getRawDataRefImpl();
  984. SegmentName = MachO->getSectionFinalSegmentName(DR);
  985. }
  986. StringRef name;
  987. error(Section.getName(name));
  988. outs() << "Disassembly of section ";
  989. if (!SegmentName.empty())
  990. outs() << SegmentName << ",";
  991. outs() << name << ':';
  992. // If the section has no symbol at the start, just insert a dummy one.
  993. if (Symbols.empty() || Symbols[0].first != 0)
  994. Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
  995. SmallString<40> Comments;
  996. raw_svector_ostream CommentStream(Comments);
  997. StringRef BytesStr;
  998. error(Section.getContents(BytesStr));
  999. ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
  1000. BytesStr.size());
  1001. uint64_t Size;
  1002. uint64_t Index;
  1003. std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
  1004. std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
  1005. // Disassemble symbol by symbol.
  1006. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
  1007. uint64_t Start = Symbols[si].first - SectionAddr;
  1008. // The end is either the section end or the beginning of the next
  1009. // symbol.
  1010. uint64_t End =
  1011. (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
  1012. // Don't try to disassemble beyond the end of section contents.
  1013. if (End > SectSize)
  1014. End = SectSize;
  1015. // If this symbol has the same address as the next symbol, then skip it.
  1016. if (Start >= End)
  1017. continue;
  1018. if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
  1019. // make size 4 bytes folded
  1020. End = Start + ((End - Start) & ~0x3ull);
  1021. Start += 256; // add sizeof(amd_kernel_code_t)
  1022. // cut trailing zeroes - up to 256 bytes (align)
  1023. const uint64_t EndAlign = 256;
  1024. const auto Limit = End - (std::min)(EndAlign, End - Start);
  1025. while (End > Limit &&
  1026. *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
  1027. End -= 4;
  1028. }
  1029. outs() << '\n' << Symbols[si].second << ":\n";
  1030. #ifndef NDEBUG
  1031. raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
  1032. #else
  1033. raw_ostream &DebugOut = nulls();
  1034. #endif
  1035. for (Index = Start; Index < End; Index += Size) {
  1036. MCInst Inst;
  1037. // AArch64 ELF binaries can interleave data and text in the
  1038. // same section. We rely on the markers introduced to
  1039. // understand what we need to dump.
  1040. if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
  1041. uint64_t Stride = 0;
  1042. auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
  1043. DataMappingSymsAddr.end(), Index);
  1044. if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
  1045. // Switch to data.
  1046. while (Index < End) {
  1047. outs() << format("%8" PRIx64 ":", SectionAddr + Index);
  1048. outs() << "\t";
  1049. if (Index + 4 <= End) {
  1050. Stride = 4;
  1051. dumpBytes(Bytes.slice(Index, 4), outs());
  1052. outs() << "\t.word";
  1053. } else if (Index + 2 <= End) {
  1054. Stride = 2;
  1055. dumpBytes(Bytes.slice(Index, 2), outs());
  1056. outs() << "\t.short";
  1057. } else {
  1058. Stride = 1;
  1059. dumpBytes(Bytes.slice(Index, 1), outs());
  1060. outs() << "\t.byte";
  1061. }
  1062. Index += Stride;
  1063. outs() << "\n";
  1064. auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
  1065. TextMappingSymsAddr.end(), Index);
  1066. if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. if (Index >= End)
  1072. break;
  1073. bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  1074. SectionAddr + Index, DebugOut,
  1075. CommentStream);
  1076. if (Size == 0)
  1077. Size = 1;
  1078. PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
  1079. Bytes.slice(Index, Size),
  1080. SectionAddr + Index, outs(), "", *STI);
  1081. outs() << CommentStream.str();
  1082. Comments.clear();
  1083. // Try to resolve the target of a call, tail call, etc. to a specific
  1084. // symbol.
  1085. if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
  1086. MIA->isConditionalBranch(Inst))) {
  1087. uint64_t Target;
  1088. if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
  1089. // In a relocatable object, the target's section must reside in
  1090. // the same section as the call instruction or it is accessed
  1091. // through a relocation.
  1092. //
  1093. // In a non-relocatable object, the target may be in any section.
  1094. //
  1095. // N.B. We don't walk the relocations in the relocatable case yet.
  1096. auto *TargetSectionSymbols = &Symbols;
  1097. if (!Obj->isRelocatableObject()) {
  1098. auto SectionAddress = std::upper_bound(
  1099. SectionAddresses.begin(), SectionAddresses.end(), Target,
  1100. [](uint64_t LHS,
  1101. const std::pair<uint64_t, SectionRef> &RHS) {
  1102. return LHS < RHS.first;
  1103. });
  1104. if (SectionAddress != SectionAddresses.begin()) {
  1105. --SectionAddress;
  1106. TargetSectionSymbols = &AllSymbols[SectionAddress->second];
  1107. } else {
  1108. TargetSectionSymbols = nullptr;
  1109. }
  1110. }
  1111. // Find the first symbol in the section whose offset is less than
  1112. // or equal to the target.
  1113. if (TargetSectionSymbols) {
  1114. auto TargetSym = std::upper_bound(
  1115. TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
  1116. Target, [](uint64_t LHS,
  1117. const std::pair<uint64_t, StringRef> &RHS) {
  1118. return LHS < RHS.first;
  1119. });
  1120. if (TargetSym != TargetSectionSymbols->begin()) {
  1121. --TargetSym;
  1122. uint64_t TargetAddress = std::get<0>(*TargetSym);
  1123. StringRef TargetName = std::get<1>(*TargetSym);
  1124. outs() << " <" << TargetName;
  1125. uint64_t Disp = Target - TargetAddress;
  1126. if (Disp)
  1127. outs() << "+0x" << utohexstr(Disp);
  1128. outs() << '>';
  1129. }
  1130. }
  1131. }
  1132. }
  1133. outs() << "\n";
  1134. // Print relocation for instruction.
  1135. while (rel_cur != rel_end) {
  1136. bool hidden = getHidden(*rel_cur);
  1137. uint64_t addr = rel_cur->getOffset();
  1138. SmallString<16> name;
  1139. SmallString<32> val;
  1140. // If this relocation is hidden, skip it.
  1141. if (hidden) goto skip_print_rel;
  1142. // Stop when rel_cur's address is past the current instruction.
  1143. if (addr >= Index + Size) break;
  1144. rel_cur->getTypeName(name);
  1145. error(getRelocationValueString(*rel_cur, val));
  1146. outs() << format(Fmt.data(), SectionAddr + addr) << name
  1147. << "\t" << val << "\n";
  1148. skip_print_rel:
  1149. ++rel_cur;
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. void llvm::PrintRelocations(const ObjectFile *Obj) {
  1156. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
  1157. "%08" PRIx64;
  1158. // Regular objdump doesn't print relocations in non-relocatable object
  1159. // files.
  1160. if (!Obj->isRelocatableObject())
  1161. return;
  1162. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1163. if (Section.relocation_begin() == Section.relocation_end())
  1164. continue;
  1165. StringRef secname;
  1166. error(Section.getName(secname));
  1167. outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
  1168. for (const RelocationRef &Reloc : Section.relocations()) {
  1169. bool hidden = getHidden(Reloc);
  1170. uint64_t address = Reloc.getOffset();
  1171. SmallString<32> relocname;
  1172. SmallString<32> valuestr;
  1173. if (hidden)
  1174. continue;
  1175. Reloc.getTypeName(relocname);
  1176. error(getRelocationValueString(Reloc, valuestr));
  1177. outs() << format(Fmt.data(), address) << " " << relocname << " "
  1178. << valuestr << "\n";
  1179. }
  1180. outs() << "\n";
  1181. }
  1182. }
  1183. void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
  1184. outs() << "Sections:\n"
  1185. "Idx Name Size Address Type\n";
  1186. unsigned i = 0;
  1187. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1188. StringRef Name;
  1189. error(Section.getName(Name));
  1190. uint64_t Address = Section.getAddress();
  1191. uint64_t Size = Section.getSize();
  1192. bool Text = Section.isText();
  1193. bool Data = Section.isData();
  1194. bool BSS = Section.isBSS();
  1195. std::string Type = (std::string(Text ? "TEXT " : "") +
  1196. (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
  1197. outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
  1198. Name.str().c_str(), Size, Address, Type.c_str());
  1199. ++i;
  1200. }
  1201. }
  1202. void llvm::PrintSectionContents(const ObjectFile *Obj) {
  1203. std::error_code EC;
  1204. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1205. StringRef Name;
  1206. StringRef Contents;
  1207. error(Section.getName(Name));
  1208. uint64_t BaseAddr = Section.getAddress();
  1209. uint64_t Size = Section.getSize();
  1210. if (!Size)
  1211. continue;
  1212. outs() << "Contents of section " << Name << ":\n";
  1213. if (Section.isBSS()) {
  1214. outs() << format("<skipping contents of bss section at [%04" PRIx64
  1215. ", %04" PRIx64 ")>\n",
  1216. BaseAddr, BaseAddr + Size);
  1217. continue;
  1218. }
  1219. error(Section.getContents(Contents));
  1220. // Dump out the content as hex and printable ascii characters.
  1221. for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
  1222. outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
  1223. // Dump line of hex.
  1224. for (std::size_t i = 0; i < 16; ++i) {
  1225. if (i != 0 && i % 4 == 0)
  1226. outs() << ' ';
  1227. if (addr + i < end)
  1228. outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
  1229. << hexdigit(Contents[addr + i] & 0xF, true);
  1230. else
  1231. outs() << " ";
  1232. }
  1233. // Print ascii.
  1234. outs() << " ";
  1235. for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
  1236. if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
  1237. outs() << Contents[addr + i];
  1238. else
  1239. outs() << ".";
  1240. }
  1241. outs() << "\n";
  1242. }
  1243. }
  1244. }
  1245. void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
  1246. StringRef ArchitectureName) {
  1247. outs() << "SYMBOL TABLE:\n";
  1248. if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
  1249. printCOFFSymbolTable(coff);
  1250. return;
  1251. }
  1252. for (const SymbolRef &Symbol : o->symbols()) {
  1253. Expected<uint64_t> AddressOrError = Symbol.getAddress();
  1254. if (!AddressOrError)
  1255. report_error(ArchiveName, o->getFileName(), AddressOrError.takeError());
  1256. uint64_t Address = *AddressOrError;
  1257. Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
  1258. if (!TypeOrError)
  1259. report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
  1260. SymbolRef::Type Type = *TypeOrError;
  1261. uint32_t Flags = Symbol.getFlags();
  1262. Expected<section_iterator> SectionOrErr = Symbol.getSection();
  1263. error(errorToErrorCode(SectionOrErr.takeError()));
  1264. section_iterator Section = *SectionOrErr;
  1265. StringRef Name;
  1266. if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
  1267. Section->getName(Name);
  1268. } else {
  1269. Expected<StringRef> NameOrErr = Symbol.getName();
  1270. if (!NameOrErr)
  1271. report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
  1272. ArchitectureName);
  1273. Name = *NameOrErr;
  1274. }
  1275. bool Global = Flags & SymbolRef::SF_Global;
  1276. bool Weak = Flags & SymbolRef::SF_Weak;
  1277. bool Absolute = Flags & SymbolRef::SF_Absolute;
  1278. bool Common = Flags & SymbolRef::SF_Common;
  1279. bool Hidden = Flags & SymbolRef::SF_Hidden;
  1280. char GlobLoc = ' ';
  1281. if (Type != SymbolRef::ST_Unknown)
  1282. GlobLoc = Global ? 'g' : 'l';
  1283. char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
  1284. ? 'd' : ' ';
  1285. char FileFunc = ' ';
  1286. if (Type == SymbolRef::ST_File)
  1287. FileFunc = 'f';
  1288. else if (Type == SymbolRef::ST_Function)
  1289. FileFunc = 'F';
  1290. const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
  1291. "%08" PRIx64;
  1292. outs() << format(Fmt, Address) << " "
  1293. << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
  1294. << (Weak ? 'w' : ' ') // Weak?
  1295. << ' ' // Constructor. Not supported yet.
  1296. << ' ' // Warning. Not supported yet.
  1297. << ' ' // Indirect reference to another symbol.
  1298. << Debug // Debugging (d) or dynamic (D) symbol.
  1299. << FileFunc // Name of function (F), file (f) or object (O).
  1300. << ' ';
  1301. if (Absolute) {
  1302. outs() << "*ABS*";
  1303. } else if (Common) {
  1304. outs() << "*COM*";
  1305. } else if (Section == o->section_end()) {
  1306. outs() << "*UND*";
  1307. } else {
  1308. if (const MachOObjectFile *MachO =
  1309. dyn_cast<const MachOObjectFile>(o)) {
  1310. DataRefImpl DR = Section->getRawDataRefImpl();
  1311. StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
  1312. outs() << SegmentName << ",";
  1313. }
  1314. StringRef SectionName;
  1315. error(Section->getName(SectionName));
  1316. outs() << SectionName;
  1317. }
  1318. outs() << '\t';
  1319. if (Common || isa<ELFObjectFileBase>(o)) {
  1320. uint64_t Val =
  1321. Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
  1322. outs() << format("\t %08" PRIx64 " ", Val);
  1323. }
  1324. if (Hidden) {
  1325. outs() << ".hidden ";
  1326. }
  1327. outs() << Name
  1328. << '\n';
  1329. }
  1330. }
  1331. static void PrintUnwindInfo(const ObjectFile *o) {
  1332. outs() << "Unwind info:\n\n";
  1333. if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
  1334. printCOFFUnwindInfo(coff);
  1335. } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1336. printMachOUnwindInfo(MachO);
  1337. else {
  1338. // TODO: Extract DWARF dump tool to objdump.
  1339. errs() << "This operation is only currently supported "
  1340. "for COFF and MachO object files.\n";
  1341. return;
  1342. }
  1343. }
  1344. void llvm::printExportsTrie(const ObjectFile *o) {
  1345. outs() << "Exports trie:\n";
  1346. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1347. printMachOExportsTrie(MachO);
  1348. else {
  1349. errs() << "This operation is only currently supported "
  1350. "for Mach-O executable files.\n";
  1351. return;
  1352. }
  1353. }
  1354. void llvm::printRebaseTable(const ObjectFile *o) {
  1355. outs() << "Rebase table:\n";
  1356. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1357. printMachORebaseTable(MachO);
  1358. else {
  1359. errs() << "This operation is only currently supported "
  1360. "for Mach-O executable files.\n";
  1361. return;
  1362. }
  1363. }
  1364. void llvm::printBindTable(const ObjectFile *o) {
  1365. outs() << "Bind table:\n";
  1366. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1367. printMachOBindTable(MachO);
  1368. else {
  1369. errs() << "This operation is only currently supported "
  1370. "for Mach-O executable files.\n";
  1371. return;
  1372. }
  1373. }
  1374. void llvm::printLazyBindTable(const ObjectFile *o) {
  1375. outs() << "Lazy bind table:\n";
  1376. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1377. printMachOLazyBindTable(MachO);
  1378. else {
  1379. errs() << "This operation is only currently supported "
  1380. "for Mach-O executable files.\n";
  1381. return;
  1382. }
  1383. }
  1384. void llvm::printWeakBindTable(const ObjectFile *o) {
  1385. outs() << "Weak bind table:\n";
  1386. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1387. printMachOWeakBindTable(MachO);
  1388. else {
  1389. errs() << "This operation is only currently supported "
  1390. "for Mach-O executable files.\n";
  1391. return;
  1392. }
  1393. }
  1394. /// Dump the raw contents of the __clangast section so the output can be piped
  1395. /// into llvm-bcanalyzer.
  1396. void llvm::printRawClangAST(const ObjectFile *Obj) {
  1397. if (outs().is_displayed()) {
  1398. errs() << "The -raw-clang-ast option will dump the raw binary contents of "
  1399. "the clang ast section.\n"
  1400. "Please redirect the output to a file or another program such as "
  1401. "llvm-bcanalyzer.\n";
  1402. return;
  1403. }
  1404. StringRef ClangASTSectionName("__clangast");
  1405. if (isa<COFFObjectFile>(Obj)) {
  1406. ClangASTSectionName = "clangast";
  1407. }
  1408. Optional<object::SectionRef> ClangASTSection;
  1409. for (auto Sec : ToolSectionFilter(*Obj)) {
  1410. StringRef Name;
  1411. Sec.getName(Name);
  1412. if (Name == ClangASTSectionName) {
  1413. ClangASTSection = Sec;
  1414. break;
  1415. }
  1416. }
  1417. if (!ClangASTSection)
  1418. return;
  1419. StringRef ClangASTContents;
  1420. error(ClangASTSection.getValue().getContents(ClangASTContents));
  1421. outs().write(ClangASTContents.data(), ClangASTContents.size());
  1422. }
  1423. static void printFaultMaps(const ObjectFile *Obj) {
  1424. const char *FaultMapSectionName = nullptr;
  1425. if (isa<ELFObjectFileBase>(Obj)) {
  1426. FaultMapSectionName = ".llvm_faultmaps";
  1427. } else if (isa<MachOObjectFile>(Obj)) {
  1428. FaultMapSectionName = "__llvm_faultmaps";
  1429. } else {
  1430. errs() << "This operation is only currently supported "
  1431. "for ELF and Mach-O executable files.\n";
  1432. return;
  1433. }
  1434. Optional<object::SectionRef> FaultMapSection;
  1435. for (auto Sec : ToolSectionFilter(*Obj)) {
  1436. StringRef Name;
  1437. Sec.getName(Name);
  1438. if (Name == FaultMapSectionName) {
  1439. FaultMapSection = Sec;
  1440. break;
  1441. }
  1442. }
  1443. outs() << "FaultMap table:\n";
  1444. if (!FaultMapSection.hasValue()) {
  1445. outs() << "<not found>\n";
  1446. return;
  1447. }
  1448. StringRef FaultMapContents;
  1449. error(FaultMapSection.getValue().getContents(FaultMapContents));
  1450. FaultMapParser FMP(FaultMapContents.bytes_begin(),
  1451. FaultMapContents.bytes_end());
  1452. outs() << FMP;
  1453. }
  1454. static void printPrivateFileHeaders(const ObjectFile *o) {
  1455. if (o->isELF())
  1456. printELFFileHeader(o);
  1457. else if (o->isCOFF())
  1458. printCOFFFileHeader(o);
  1459. else if (o->isMachO()) {
  1460. printMachOFileHeader(o);
  1461. printMachOLoadCommands(o);
  1462. } else
  1463. report_fatal_error("Invalid/Unsupported object file format");
  1464. }
  1465. static void printFirstPrivateFileHeader(const ObjectFile *o) {
  1466. if (o->isELF())
  1467. printELFFileHeader(o);
  1468. else if (o->isCOFF())
  1469. printCOFFFileHeader(o);
  1470. else if (o->isMachO())
  1471. printMachOFileHeader(o);
  1472. else
  1473. report_fatal_error("Invalid/Unsupported object file format");
  1474. }
  1475. static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
  1476. StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
  1477. // Avoid other output when using a raw option.
  1478. if (!RawClangAST) {
  1479. outs() << '\n';
  1480. if (a)
  1481. outs() << a->getFileName() << "(" << o->getFileName() << ")";
  1482. else
  1483. outs() << o->getFileName();
  1484. outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
  1485. }
  1486. if (Disassemble)
  1487. DisassembleObject(o, Relocations);
  1488. if (Relocations && !Disassemble)
  1489. PrintRelocations(o);
  1490. if (SectionHeaders)
  1491. PrintSectionHeaders(o);
  1492. if (SectionContents)
  1493. PrintSectionContents(o);
  1494. if (SymbolTable)
  1495. PrintSymbolTable(o, ArchiveName);
  1496. if (UnwindInfo)
  1497. PrintUnwindInfo(o);
  1498. if (PrivateHeaders)
  1499. printPrivateFileHeaders(o);
  1500. if (FirstPrivateHeader)
  1501. printFirstPrivateFileHeader(o);
  1502. if (ExportsTrie)
  1503. printExportsTrie(o);
  1504. if (Rebase)
  1505. printRebaseTable(o);
  1506. if (Bind)
  1507. printBindTable(o);
  1508. if (LazyBind)
  1509. printLazyBindTable(o);
  1510. if (WeakBind)
  1511. printWeakBindTable(o);
  1512. if (RawClangAST)
  1513. printRawClangAST(o);
  1514. if (PrintFaultMaps)
  1515. printFaultMaps(o);
  1516. if (DwarfDumpType != DIDT_Null) {
  1517. std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
  1518. // Dump the complete DWARF structure.
  1519. DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
  1520. }
  1521. }
  1522. /// @brief Dump each object file in \a a;
  1523. static void DumpArchive(const Archive *a) {
  1524. for (auto &ErrorOrChild : a->children()) {
  1525. if (std::error_code EC = ErrorOrChild.getError())
  1526. report_error(a->getFileName(), EC);
  1527. const Archive::Child &C = *ErrorOrChild;
  1528. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  1529. if (!ChildOrErr) {
  1530. if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  1531. report_error(a->getFileName(), C, std::move(E));
  1532. continue;
  1533. }
  1534. if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
  1535. DumpObject(o, a);
  1536. else
  1537. report_error(a->getFileName(), object_error::invalid_file_type);
  1538. }
  1539. }
  1540. /// @brief Open file and figure out how to dump it.
  1541. static void DumpInput(StringRef file) {
  1542. // If we are using the Mach-O specific object file parser, then let it parse
  1543. // the file and process the command line options. So the -arch flags can
  1544. // be used to select specific slices, etc.
  1545. if (MachOOpt) {
  1546. ParseInputMachO(file);
  1547. return;
  1548. }
  1549. // Attempt to open the binary.
  1550. Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
  1551. if (!BinaryOrErr)
  1552. report_error(file, BinaryOrErr.takeError());
  1553. Binary &Binary = *BinaryOrErr.get().getBinary();
  1554. if (Archive *a = dyn_cast<Archive>(&Binary))
  1555. DumpArchive(a);
  1556. else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
  1557. DumpObject(o);
  1558. else
  1559. report_error(file, object_error::invalid_file_type);
  1560. }
  1561. int main(int argc, char **argv) {
  1562. // Print a stack trace if we signal out.
  1563. sys::PrintStackTraceOnErrorSignal(argv[0]);
  1564. PrettyStackTraceProgram X(argc, argv);
  1565. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  1566. // Initialize targets and assembly printers/parsers.
  1567. llvm::InitializeAllTargetInfos();
  1568. llvm::InitializeAllTargetMCs();
  1569. llvm::InitializeAllDisassemblers();
  1570. // Register the target printer for --version.
  1571. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  1572. cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
  1573. TripleName = Triple::normalize(TripleName);
  1574. ToolName = argv[0];
  1575. // Defaults to a.out if no filenames specified.
  1576. if (InputFilenames.size() == 0)
  1577. InputFilenames.push_back("a.out");
  1578. if (DisassembleAll)
  1579. Disassemble = true;
  1580. if (!Disassemble
  1581. && !Relocations
  1582. && !SectionHeaders
  1583. && !SectionContents
  1584. && !SymbolTable
  1585. && !UnwindInfo
  1586. && !PrivateHeaders
  1587. && !FirstPrivateHeader
  1588. && !ExportsTrie
  1589. && !Rebase
  1590. && !Bind
  1591. && !LazyBind
  1592. && !WeakBind
  1593. && !RawClangAST
  1594. && !(UniversalHeaders && MachOOpt)
  1595. && !(ArchiveHeaders && MachOOpt)
  1596. && !(IndirectSymbols && MachOOpt)
  1597. && !(DataInCode && MachOOpt)
  1598. && !(LinkOptHints && MachOOpt)
  1599. && !(InfoPlist && MachOOpt)
  1600. && !(DylibsUsed && MachOOpt)
  1601. && !(DylibId && MachOOpt)
  1602. && !(ObjcMetaData && MachOOpt)
  1603. && !(FilterSections.size() != 0 && MachOOpt)
  1604. && !PrintFaultMaps
  1605. && DwarfDumpType == DIDT_Null) {
  1606. cl::PrintHelpMessage();
  1607. return 2;
  1608. }
  1609. std::for_each(InputFilenames.begin(), InputFilenames.end(),
  1610. DumpInput);
  1611. return EXIT_SUCCESS;
  1612. }