llvm-objdump.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  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/STLExtras.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/Triple.h"
  22. #include "llvm/MC/MCAsmInfo.h"
  23. #include "llvm/MC/MCContext.h"
  24. #include "llvm/MC/MCDisassembler.h"
  25. #include "llvm/MC/MCInst.h"
  26. #include "llvm/MC/MCInstPrinter.h"
  27. #include "llvm/MC/MCInstrAnalysis.h"
  28. #include "llvm/MC/MCInstrInfo.h"
  29. #include "llvm/MC/MCObjectFileInfo.h"
  30. #include "llvm/MC/MCRegisterInfo.h"
  31. #include "llvm/MC/MCRelocationInfo.h"
  32. #include "llvm/MC/MCSubtargetInfo.h"
  33. #include "llvm/Object/Archive.h"
  34. #include "llvm/Object/ELFObjectFile.h"
  35. #include "llvm/Object/COFF.h"
  36. #include "llvm/Object/MachO.h"
  37. #include "llvm/Object/ObjectFile.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/Errc.h"
  42. #include "llvm/Support/FileSystem.h"
  43. #include "llvm/Support/Format.h"
  44. #include "llvm/Support/GraphWriter.h"
  45. #include "llvm/Support/Host.h"
  46. #include "llvm/Support/ManagedStatic.h"
  47. #include "llvm/Support/MemoryBuffer.h"
  48. #include "llvm/Support/PrettyStackTrace.h"
  49. #include "llvm/Support/Signals.h"
  50. #include "llvm/Support/SourceMgr.h"
  51. #include "llvm/Support/TargetRegistry.h"
  52. #include "llvm/Support/TargetSelect.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include <algorithm>
  55. #include <cctype>
  56. #include <cstring>
  57. #include <system_error>
  58. using namespace llvm;
  59. using namespace object;
  60. static cl::list<std::string>
  61. InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
  62. cl::opt<bool>
  63. llvm::Disassemble("disassemble",
  64. cl::desc("Display assembler mnemonics for the machine instructions"));
  65. static cl::alias
  66. Disassembled("d", cl::desc("Alias for --disassemble"),
  67. cl::aliasopt(Disassemble));
  68. cl::opt<bool>
  69. llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
  70. cl::opt<bool>
  71. llvm::SectionContents("s", cl::desc("Display the content of each section"));
  72. cl::opt<bool>
  73. llvm::SymbolTable("t", cl::desc("Display the symbol table"));
  74. cl::opt<bool>
  75. llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
  76. cl::opt<bool>
  77. llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
  78. cl::opt<bool>
  79. llvm::Bind("bind", cl::desc("Display mach-o binding info"));
  80. cl::opt<bool>
  81. llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
  82. cl::opt<bool>
  83. llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
  84. static cl::opt<bool>
  85. MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
  86. static cl::alias
  87. MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
  88. cl::opt<std::string>
  89. llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
  90. "see -version for available targets"));
  91. cl::opt<std::string>
  92. llvm::MCPU("mcpu",
  93. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  94. cl::value_desc("cpu-name"),
  95. cl::init(""));
  96. cl::opt<std::string>
  97. llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
  98. "see -version for available targets"));
  99. cl::opt<bool>
  100. llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
  101. "headers for each section."));
  102. static cl::alias
  103. SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
  104. cl::aliasopt(SectionHeaders));
  105. static cl::alias
  106. SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
  107. cl::aliasopt(SectionHeaders));
  108. cl::list<std::string>
  109. llvm::MAttrs("mattr",
  110. cl::CommaSeparated,
  111. cl::desc("Target specific attributes"),
  112. cl::value_desc("a1,+a2,-a3,..."));
  113. cl::opt<bool>
  114. llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
  115. "instructions, do not print "
  116. "the instruction bytes."));
  117. cl::opt<bool>
  118. llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
  119. static cl::alias
  120. UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
  121. cl::aliasopt(UnwindInfo));
  122. cl::opt<bool>
  123. llvm::PrivateHeaders("private-headers",
  124. cl::desc("Display format specific file headers"));
  125. static cl::alias
  126. PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
  127. cl::aliasopt(PrivateHeaders));
  128. cl::opt<bool>
  129. llvm::PrintImmHex("print-imm-hex",
  130. cl::desc("Use hex format for immediate values"));
  131. static StringRef ToolName;
  132. static int ReturnValue = EXIT_SUCCESS;
  133. bool llvm::error(std::error_code EC) {
  134. if (!EC)
  135. return false;
  136. outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
  137. outs().flush();
  138. ReturnValue = EXIT_FAILURE;
  139. return true;
  140. }
  141. static void report_error(StringRef File, std::error_code EC) {
  142. assert(EC);
  143. errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
  144. ReturnValue = EXIT_FAILURE;
  145. }
  146. static const Target *getTarget(const ObjectFile *Obj = nullptr) {
  147. // Figure out the target triple.
  148. llvm::Triple TheTriple("unknown-unknown-unknown");
  149. if (TripleName.empty()) {
  150. if (Obj) {
  151. TheTriple.setArch(Triple::ArchType(Obj->getArch()));
  152. // TheTriple defaults to ELF, and COFF doesn't have an environment:
  153. // the best we can do here is indicate that it is mach-o.
  154. if (Obj->isMachO())
  155. TheTriple.setObjectFormat(Triple::MachO);
  156. if (Obj->isCOFF()) {
  157. const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
  158. if (COFFObj->getArch() == Triple::thumb)
  159. TheTriple.setTriple("thumbv7-windows");
  160. }
  161. }
  162. } else
  163. TheTriple.setTriple(Triple::normalize(TripleName));
  164. // Get the target specific parser.
  165. std::string Error;
  166. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  167. Error);
  168. if (!TheTarget) {
  169. errs() << ToolName << ": " << Error;
  170. return nullptr;
  171. }
  172. // Update the triple name and return the found target.
  173. TripleName = TheTriple.getTriple();
  174. return TheTarget;
  175. }
  176. bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
  177. uint64_t a_addr, b_addr;
  178. if (error(a.getOffset(a_addr))) return false;
  179. if (error(b.getOffset(b_addr))) return false;
  180. return a_addr < b_addr;
  181. }
  182. namespace {
  183. class PrettyPrinter {
  184. public:
  185. virtual ~PrettyPrinter(){}
  186. virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
  187. ArrayRef<uint8_t> Bytes, uint64_t Address,
  188. raw_ostream &OS, StringRef Annot,
  189. MCSubtargetInfo const &STI) {
  190. outs() << format("%8" PRIx64 ":", Address);
  191. if (!NoShowRawInsn) {
  192. outs() << "\t";
  193. dumpBytes(Bytes, outs());
  194. }
  195. IP.printInst(MI, outs(), "", STI);
  196. }
  197. };
  198. PrettyPrinter PrettyPrinterInst;
  199. class HexagonPrettyPrinter : public PrettyPrinter {
  200. public:
  201. void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
  202. raw_ostream &OS) {
  203. uint32_t opcode =
  204. (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
  205. OS << format("%8" PRIx64 ":", Address);
  206. if (!NoShowRawInsn) {
  207. OS << "\t";
  208. dumpBytes(Bytes.slice(0, 4), OS);
  209. OS << format("%08" PRIx32, opcode);
  210. }
  211. }
  212. void printInst(MCInstPrinter &IP, const MCInst *MI,
  213. ArrayRef<uint8_t> Bytes, uint64_t Address,
  214. raw_ostream &OS, StringRef Annot,
  215. MCSubtargetInfo const &STI) override {
  216. std::string Buffer;
  217. {
  218. raw_string_ostream TempStream(Buffer);
  219. IP.printInst(MI, TempStream, "", STI);
  220. }
  221. StringRef Contents(Buffer);
  222. // Split off bundle attributes
  223. auto PacketBundle = Contents.rsplit('\n');
  224. // Split off first instruction from the rest
  225. auto HeadTail = PacketBundle.first.split('\n');
  226. auto Preamble = " { ";
  227. auto Separator = "";
  228. while(!HeadTail.first.empty()) {
  229. OS << Separator;
  230. Separator = "\n";
  231. printLead(Bytes, Address, OS);
  232. OS << Preamble;
  233. Preamble = " ";
  234. StringRef Inst;
  235. auto Duplex = HeadTail.first.split('\v');
  236. if(!Duplex.second.empty()){
  237. OS << Duplex.first;
  238. OS << "; ";
  239. Inst = Duplex.second;
  240. }
  241. else
  242. Inst = HeadTail.first;
  243. OS << Inst;
  244. Bytes = Bytes.slice(4);
  245. Address += 4;
  246. HeadTail = HeadTail.second.split('\n');
  247. }
  248. OS << " } " << PacketBundle.second;
  249. }
  250. };
  251. HexagonPrettyPrinter HexagonPrettyPrinterInst;
  252. PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
  253. switch(Triple.getArch()) {
  254. default:
  255. return PrettyPrinterInst;
  256. case Triple::hexagon:
  257. return HexagonPrettyPrinterInst;
  258. }
  259. }
  260. }
  261. template <class ELFT>
  262. static const typename ELFObjectFile<ELFT>::Elf_Rel *
  263. getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
  264. typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
  265. return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
  266. }
  267. template <class ELFT>
  268. static const typename ELFObjectFile<ELFT>::Elf_Rela *
  269. getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
  270. typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
  271. return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
  272. }
  273. template <class ELFT>
  274. static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
  275. DataRefImpl Rel,
  276. SmallVectorImpl<char> &Result) {
  277. typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
  278. typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
  279. const ELFFile<ELFT> &EF = *Obj->getELFFile();
  280. const Elf_Shdr *sec = EF.getSection(Rel.d.a);
  281. uint8_t type;
  282. StringRef res;
  283. int64_t addend = 0;
  284. uint16_t symbol_index = 0;
  285. switch (sec->sh_type) {
  286. default:
  287. return object_error::parse_failed;
  288. case ELF::SHT_REL: {
  289. type = getRel(EF, Rel)->getType(EF.isMips64EL());
  290. symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
  291. // TODO: Read implicit addend from section data.
  292. break;
  293. }
  294. case ELF::SHT_RELA: {
  295. type = getRela(EF, Rel)->getType(EF.isMips64EL());
  296. symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
  297. addend = getRela(EF, Rel)->r_addend;
  298. break;
  299. }
  300. }
  301. const Elf_Sym *symb =
  302. EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
  303. StringRef Target;
  304. const Elf_Shdr *SymSec = EF.getSection(symb);
  305. if (symb->getType() == ELF::STT_SECTION) {
  306. ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
  307. if (std::error_code EC = SecName.getError())
  308. return EC;
  309. Target = *SecName;
  310. } else {
  311. ErrorOr<StringRef> SymName =
  312. EF.getSymbolName(EF.getSection(sec->sh_link), symb);
  313. if (!SymName)
  314. return SymName.getError();
  315. Target = *SymName;
  316. }
  317. switch (EF.getHeader()->e_machine) {
  318. case ELF::EM_X86_64:
  319. switch (type) {
  320. case ELF::R_X86_64_PC8:
  321. case ELF::R_X86_64_PC16:
  322. case ELF::R_X86_64_PC32: {
  323. std::string fmtbuf;
  324. raw_string_ostream fmt(fmtbuf);
  325. fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
  326. fmt.flush();
  327. Result.append(fmtbuf.begin(), fmtbuf.end());
  328. } break;
  329. case ELF::R_X86_64_8:
  330. case ELF::R_X86_64_16:
  331. case ELF::R_X86_64_32:
  332. case ELF::R_X86_64_32S:
  333. case ELF::R_X86_64_64: {
  334. std::string fmtbuf;
  335. raw_string_ostream fmt(fmtbuf);
  336. fmt << Target << (addend < 0 ? "" : "+") << addend;
  337. fmt.flush();
  338. Result.append(fmtbuf.begin(), fmtbuf.end());
  339. } break;
  340. default:
  341. res = "Unknown";
  342. }
  343. break;
  344. case ELF::EM_AARCH64: {
  345. std::string fmtbuf;
  346. raw_string_ostream fmt(fmtbuf);
  347. fmt << Target;
  348. if (addend != 0)
  349. fmt << (addend < 0 ? "" : "+") << addend;
  350. fmt.flush();
  351. Result.append(fmtbuf.begin(), fmtbuf.end());
  352. break;
  353. }
  354. case ELF::EM_386:
  355. case ELF::EM_ARM:
  356. case ELF::EM_HEXAGON:
  357. case ELF::EM_MIPS:
  358. res = Target;
  359. break;
  360. default:
  361. res = "Unknown";
  362. }
  363. if (Result.empty())
  364. Result.append(res.begin(), res.end());
  365. return std::error_code();
  366. }
  367. static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
  368. const RelocationRef &RelRef,
  369. SmallVectorImpl<char> &Result) {
  370. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  371. if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
  372. return getRelocationValueString(ELF32LE, Rel, Result);
  373. if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
  374. return getRelocationValueString(ELF64LE, Rel, Result);
  375. if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
  376. return getRelocationValueString(ELF32BE, Rel, Result);
  377. auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
  378. return getRelocationValueString(ELF64BE, Rel, Result);
  379. }
  380. static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
  381. const RelocationRef &Rel,
  382. SmallVectorImpl<char> &Result) {
  383. symbol_iterator SymI = Rel.getSymbol();
  384. StringRef SymName;
  385. if (std::error_code EC = SymI->getName(SymName))
  386. return EC;
  387. Result.append(SymName.begin(), SymName.end());
  388. return std::error_code();
  389. }
  390. static void printRelocationTargetName(const MachOObjectFile *O,
  391. const MachO::any_relocation_info &RE,
  392. raw_string_ostream &fmt) {
  393. bool IsScattered = O->isRelocationScattered(RE);
  394. // Target of a scattered relocation is an address. In the interest of
  395. // generating pretty output, scan through the symbol table looking for a
  396. // symbol that aligns with that address. If we find one, print it.
  397. // Otherwise, we just print the hex address of the target.
  398. if (IsScattered) {
  399. uint32_t Val = O->getPlainRelocationSymbolNum(RE);
  400. for (const SymbolRef &Symbol : O->symbols()) {
  401. std::error_code ec;
  402. uint64_t Addr;
  403. StringRef Name;
  404. if ((ec = Symbol.getAddress(Addr)))
  405. report_fatal_error(ec.message());
  406. if (Addr != Val)
  407. continue;
  408. if ((ec = Symbol.getName(Name)))
  409. report_fatal_error(ec.message());
  410. fmt << Name;
  411. return;
  412. }
  413. // If we couldn't find a symbol that this relocation refers to, try
  414. // to find a section beginning instead.
  415. for (const SectionRef &Section : O->sections()) {
  416. std::error_code ec;
  417. StringRef Name;
  418. uint64_t Addr = Section.getAddress();
  419. if (Addr != Val)
  420. continue;
  421. if ((ec = Section.getName(Name)))
  422. report_fatal_error(ec.message());
  423. fmt << Name;
  424. return;
  425. }
  426. fmt << format("0x%x", Val);
  427. return;
  428. }
  429. StringRef S;
  430. bool isExtern = O->getPlainRelocationExternal(RE);
  431. uint64_t Val = O->getPlainRelocationSymbolNum(RE);
  432. if (isExtern) {
  433. symbol_iterator SI = O->symbol_begin();
  434. advance(SI, Val);
  435. SI->getName(S);
  436. } else {
  437. section_iterator SI = O->section_begin();
  438. // Adjust for the fact that sections are 1-indexed.
  439. advance(SI, Val - 1);
  440. SI->getName(S);
  441. }
  442. fmt << S;
  443. }
  444. static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
  445. const RelocationRef &RelRef,
  446. SmallVectorImpl<char> &Result) {
  447. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  448. MachO::any_relocation_info RE = Obj->getRelocation(Rel);
  449. unsigned Arch = Obj->getArch();
  450. std::string fmtbuf;
  451. raw_string_ostream fmt(fmtbuf);
  452. unsigned Type = Obj->getAnyRelocationType(RE);
  453. bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
  454. // Determine any addends that should be displayed with the relocation.
  455. // These require decoding the relocation type, which is triple-specific.
  456. // X86_64 has entirely custom relocation types.
  457. if (Arch == Triple::x86_64) {
  458. bool isPCRel = Obj->getAnyRelocationPCRel(RE);
  459. switch (Type) {
  460. case MachO::X86_64_RELOC_GOT_LOAD:
  461. case MachO::X86_64_RELOC_GOT: {
  462. printRelocationTargetName(Obj, RE, fmt);
  463. fmt << "@GOT";
  464. if (isPCRel)
  465. fmt << "PCREL";
  466. break;
  467. }
  468. case MachO::X86_64_RELOC_SUBTRACTOR: {
  469. DataRefImpl RelNext = Rel;
  470. Obj->moveRelocationNext(RelNext);
  471. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  472. // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
  473. // X86_64_RELOC_UNSIGNED.
  474. // NOTE: Scattered relocations don't exist on x86_64.
  475. unsigned RType = Obj->getAnyRelocationType(RENext);
  476. if (RType != MachO::X86_64_RELOC_UNSIGNED)
  477. report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
  478. "X86_64_RELOC_SUBTRACTOR.");
  479. // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
  480. // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
  481. printRelocationTargetName(Obj, RENext, fmt);
  482. fmt << "-";
  483. printRelocationTargetName(Obj, RE, fmt);
  484. break;
  485. }
  486. case MachO::X86_64_RELOC_TLV:
  487. printRelocationTargetName(Obj, RE, fmt);
  488. fmt << "@TLV";
  489. if (isPCRel)
  490. fmt << "P";
  491. break;
  492. case MachO::X86_64_RELOC_SIGNED_1:
  493. printRelocationTargetName(Obj, RE, fmt);
  494. fmt << "-1";
  495. break;
  496. case MachO::X86_64_RELOC_SIGNED_2:
  497. printRelocationTargetName(Obj, RE, fmt);
  498. fmt << "-2";
  499. break;
  500. case MachO::X86_64_RELOC_SIGNED_4:
  501. printRelocationTargetName(Obj, RE, fmt);
  502. fmt << "-4";
  503. break;
  504. default:
  505. printRelocationTargetName(Obj, RE, fmt);
  506. break;
  507. }
  508. // X86 and ARM share some relocation types in common.
  509. } else if (Arch == Triple::x86 || Arch == Triple::arm ||
  510. Arch == Triple::ppc) {
  511. // Generic relocation types...
  512. switch (Type) {
  513. case MachO::GENERIC_RELOC_PAIR: // prints no info
  514. return std::error_code();
  515. case MachO::GENERIC_RELOC_SECTDIFF: {
  516. DataRefImpl RelNext = Rel;
  517. Obj->moveRelocationNext(RelNext);
  518. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  519. // X86 sect diff's must be followed by a relocation of type
  520. // GENERIC_RELOC_PAIR.
  521. unsigned RType = Obj->getAnyRelocationType(RENext);
  522. if (RType != MachO::GENERIC_RELOC_PAIR)
  523. report_fatal_error("Expected GENERIC_RELOC_PAIR after "
  524. "GENERIC_RELOC_SECTDIFF.");
  525. printRelocationTargetName(Obj, RE, fmt);
  526. fmt << "-";
  527. printRelocationTargetName(Obj, RENext, fmt);
  528. break;
  529. }
  530. }
  531. if (Arch == Triple::x86 || Arch == Triple::ppc) {
  532. switch (Type) {
  533. case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
  534. DataRefImpl RelNext = Rel;
  535. Obj->moveRelocationNext(RelNext);
  536. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  537. // X86 sect diff's must be followed by a relocation of type
  538. // GENERIC_RELOC_PAIR.
  539. unsigned RType = Obj->getAnyRelocationType(RENext);
  540. if (RType != MachO::GENERIC_RELOC_PAIR)
  541. report_fatal_error("Expected GENERIC_RELOC_PAIR after "
  542. "GENERIC_RELOC_LOCAL_SECTDIFF.");
  543. printRelocationTargetName(Obj, RE, fmt);
  544. fmt << "-";
  545. printRelocationTargetName(Obj, RENext, fmt);
  546. break;
  547. }
  548. case MachO::GENERIC_RELOC_TLV: {
  549. printRelocationTargetName(Obj, RE, fmt);
  550. fmt << "@TLV";
  551. if (IsPCRel)
  552. fmt << "P";
  553. break;
  554. }
  555. default:
  556. printRelocationTargetName(Obj, RE, fmt);
  557. }
  558. } else { // ARM-specific relocations
  559. switch (Type) {
  560. case MachO::ARM_RELOC_HALF:
  561. case MachO::ARM_RELOC_HALF_SECTDIFF: {
  562. // Half relocations steal a bit from the length field to encode
  563. // whether this is an upper16 or a lower16 relocation.
  564. bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
  565. if (isUpper)
  566. fmt << ":upper16:(";
  567. else
  568. fmt << ":lower16:(";
  569. printRelocationTargetName(Obj, RE, fmt);
  570. DataRefImpl RelNext = Rel;
  571. Obj->moveRelocationNext(RelNext);
  572. MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
  573. // ARM half relocs must be followed by a relocation of type
  574. // ARM_RELOC_PAIR.
  575. unsigned RType = Obj->getAnyRelocationType(RENext);
  576. if (RType != MachO::ARM_RELOC_PAIR)
  577. report_fatal_error("Expected ARM_RELOC_PAIR after "
  578. "ARM_RELOC_HALF");
  579. // NOTE: The half of the target virtual address is stashed in the
  580. // address field of the secondary relocation, but we can't reverse
  581. // engineer the constant offset from it without decoding the movw/movt
  582. // instruction to find the other half in its immediate field.
  583. // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
  584. // symbol/section pointer of the follow-on relocation.
  585. if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
  586. fmt << "-";
  587. printRelocationTargetName(Obj, RENext, fmt);
  588. }
  589. fmt << ")";
  590. break;
  591. }
  592. default: { printRelocationTargetName(Obj, RE, fmt); }
  593. }
  594. }
  595. } else
  596. printRelocationTargetName(Obj, RE, fmt);
  597. fmt.flush();
  598. Result.append(fmtbuf.begin(), fmtbuf.end());
  599. return std::error_code();
  600. }
  601. static std::error_code getRelocationValueString(const RelocationRef &Rel,
  602. SmallVectorImpl<char> &Result) {
  603. const ObjectFile *Obj = Rel.getObjectFile();
  604. if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
  605. return getRelocationValueString(ELF, Rel, Result);
  606. if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
  607. return getRelocationValueString(COFF, Rel, Result);
  608. auto *MachO = cast<MachOObjectFile>(Obj);
  609. return getRelocationValueString(MachO, Rel, Result);
  610. }
  611. static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
  612. const Target *TheTarget = getTarget(Obj);
  613. // getTarget() will have already issued a diagnostic if necessary, so
  614. // just bail here if it failed.
  615. if (!TheTarget)
  616. return;
  617. // Package up features to be passed to target/subtarget
  618. std::string FeaturesStr;
  619. if (MAttrs.size()) {
  620. SubtargetFeatures Features;
  621. for (unsigned i = 0; i != MAttrs.size(); ++i)
  622. Features.AddFeature(MAttrs[i]);
  623. FeaturesStr = Features.getString();
  624. }
  625. std::unique_ptr<const MCRegisterInfo> MRI(
  626. TheTarget->createMCRegInfo(TripleName));
  627. if (!MRI) {
  628. errs() << "error: no register info for target " << TripleName << "\n";
  629. return;
  630. }
  631. // Set up disassembler.
  632. std::unique_ptr<const MCAsmInfo> AsmInfo(
  633. TheTarget->createMCAsmInfo(*MRI, TripleName));
  634. if (!AsmInfo) {
  635. errs() << "error: no assembly info for target " << TripleName << "\n";
  636. return;
  637. }
  638. std::unique_ptr<const MCSubtargetInfo> STI(
  639. TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
  640. if (!STI) {
  641. errs() << "error: no subtarget info for target " << TripleName << "\n";
  642. return;
  643. }
  644. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  645. if (!MII) {
  646. errs() << "error: no instruction info for target " << TripleName << "\n";
  647. return;
  648. }
  649. std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
  650. MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
  651. std::unique_ptr<MCDisassembler> DisAsm(
  652. TheTarget->createMCDisassembler(*STI, Ctx));
  653. if (!DisAsm) {
  654. errs() << "error: no disassembler for target " << TripleName << "\n";
  655. return;
  656. }
  657. std::unique_ptr<const MCInstrAnalysis> MIA(
  658. TheTarget->createMCInstrAnalysis(MII.get()));
  659. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  660. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  661. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
  662. if (!IP) {
  663. errs() << "error: no instruction printer for target " << TripleName
  664. << '\n';
  665. return;
  666. }
  667. IP->setPrintImmHex(PrintImmHex);
  668. PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
  669. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
  670. "\t\t\t%08" PRIx64 ": ";
  671. // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
  672. // in RelocSecs contain the relocations for section S.
  673. std::error_code EC;
  674. std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
  675. for (const SectionRef &Section : Obj->sections()) {
  676. section_iterator Sec2 = Section.getRelocatedSection();
  677. if (Sec2 != Obj->section_end())
  678. SectionRelocMap[*Sec2].push_back(Section);
  679. }
  680. for (const SectionRef &Section : Obj->sections()) {
  681. if (!Section.isText() || Section.isVirtual())
  682. continue;
  683. uint64_t SectionAddr = Section.getAddress();
  684. uint64_t SectSize = Section.getSize();
  685. if (!SectSize)
  686. continue;
  687. // Make a list of all the symbols in this section.
  688. std::vector<std::pair<uint64_t, StringRef>> Symbols;
  689. for (const SymbolRef &Symbol : Obj->symbols()) {
  690. if (Section.containsSymbol(Symbol)) {
  691. uint64_t Address;
  692. if (error(Symbol.getAddress(Address)))
  693. break;
  694. if (Address == UnknownAddressOrSize)
  695. continue;
  696. Address -= SectionAddr;
  697. if (Address >= SectSize)
  698. continue;
  699. StringRef Name;
  700. if (error(Symbol.getName(Name)))
  701. break;
  702. Symbols.push_back(std::make_pair(Address, Name));
  703. }
  704. }
  705. // Sort the symbols by address, just in case they didn't come in that way.
  706. array_pod_sort(Symbols.begin(), Symbols.end());
  707. // Make a list of all the relocations for this section.
  708. std::vector<RelocationRef> Rels;
  709. if (InlineRelocs) {
  710. for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
  711. for (const RelocationRef &Reloc : RelocSec.relocations()) {
  712. Rels.push_back(Reloc);
  713. }
  714. }
  715. }
  716. // Sort relocations by address.
  717. std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
  718. StringRef SegmentName = "";
  719. if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
  720. DataRefImpl DR = Section.getRawDataRefImpl();
  721. SegmentName = MachO->getSectionFinalSegmentName(DR);
  722. }
  723. StringRef name;
  724. if (error(Section.getName(name)))
  725. break;
  726. outs() << "Disassembly of section ";
  727. if (!SegmentName.empty())
  728. outs() << SegmentName << ",";
  729. outs() << name << ':';
  730. // If the section has no symbol at the start, just insert a dummy one.
  731. if (Symbols.empty() || Symbols[0].first != 0)
  732. Symbols.insert(Symbols.begin(), std::make_pair(0, name));
  733. SmallString<40> Comments;
  734. raw_svector_ostream CommentStream(Comments);
  735. StringRef BytesStr;
  736. if (error(Section.getContents(BytesStr)))
  737. break;
  738. ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
  739. BytesStr.size());
  740. uint64_t Size;
  741. uint64_t Index;
  742. std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
  743. std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
  744. // Disassemble symbol by symbol.
  745. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
  746. uint64_t Start = Symbols[si].first;
  747. // The end is either the section end or the beginning of the next symbol.
  748. uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
  749. // If this symbol has the same address as the next symbol, then skip it.
  750. if (Start == End)
  751. continue;
  752. outs() << '\n' << Symbols[si].second << ":\n";
  753. #ifndef NDEBUG
  754. raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
  755. #else
  756. raw_ostream &DebugOut = nulls();
  757. #endif
  758. for (Index = Start; Index < End; Index += Size) {
  759. MCInst Inst;
  760. if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  761. SectionAddr + Index, DebugOut,
  762. CommentStream)) {
  763. PIP.printInst(*IP, &Inst,
  764. Bytes.slice(Index, Size),
  765. SectionAddr + Index, outs(), "", *STI);
  766. outs() << CommentStream.str();
  767. Comments.clear();
  768. outs() << "\n";
  769. } else {
  770. errs() << ToolName << ": warning: invalid instruction encoding\n";
  771. if (Size == 0)
  772. Size = 1; // skip illegible bytes
  773. }
  774. // Print relocation for instruction.
  775. while (rel_cur != rel_end) {
  776. bool hidden = false;
  777. uint64_t addr;
  778. SmallString<16> name;
  779. SmallString<32> val;
  780. // If this relocation is hidden, skip it.
  781. if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
  782. if (hidden) goto skip_print_rel;
  783. if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
  784. // Stop when rel_cur's address is past the current instruction.
  785. if (addr >= Index + Size) break;
  786. if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
  787. if (error(getRelocationValueString(*rel_cur, val)))
  788. goto skip_print_rel;
  789. outs() << format(Fmt.data(), SectionAddr + addr) << name
  790. << "\t" << val << "\n";
  791. skip_print_rel:
  792. ++rel_cur;
  793. }
  794. }
  795. }
  796. }
  797. }
  798. void llvm::PrintRelocations(const ObjectFile *Obj) {
  799. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
  800. "%08" PRIx64;
  801. // Regular objdump doesn't print relocations in non-relocatable object
  802. // files.
  803. if (!Obj->isRelocatableObject())
  804. return;
  805. for (const SectionRef &Section : Obj->sections()) {
  806. if (Section.relocation_begin() == Section.relocation_end())
  807. continue;
  808. StringRef secname;
  809. if (error(Section.getName(secname)))
  810. continue;
  811. outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
  812. for (const RelocationRef &Reloc : Section.relocations()) {
  813. bool hidden;
  814. uint64_t address;
  815. SmallString<32> relocname;
  816. SmallString<32> valuestr;
  817. if (error(Reloc.getHidden(hidden)))
  818. continue;
  819. if (hidden)
  820. continue;
  821. if (error(Reloc.getTypeName(relocname)))
  822. continue;
  823. if (error(Reloc.getOffset(address)))
  824. continue;
  825. if (error(getRelocationValueString(Reloc, valuestr)))
  826. continue;
  827. outs() << format(Fmt.data(), address) << " " << relocname << " "
  828. << valuestr << "\n";
  829. }
  830. outs() << "\n";
  831. }
  832. }
  833. void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
  834. outs() << "Sections:\n"
  835. "Idx Name Size Address Type\n";
  836. unsigned i = 0;
  837. for (const SectionRef &Section : Obj->sections()) {
  838. StringRef Name;
  839. if (error(Section.getName(Name)))
  840. return;
  841. uint64_t Address = Section.getAddress();
  842. uint64_t Size = Section.getSize();
  843. bool Text = Section.isText();
  844. bool Data = Section.isData();
  845. bool BSS = Section.isBSS();
  846. std::string Type = (std::string(Text ? "TEXT " : "") +
  847. (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
  848. outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
  849. Name.str().c_str(), Size, Address, Type.c_str());
  850. ++i;
  851. }
  852. }
  853. void llvm::PrintSectionContents(const ObjectFile *Obj) {
  854. std::error_code EC;
  855. for (const SectionRef &Section : Obj->sections()) {
  856. StringRef Name;
  857. StringRef Contents;
  858. if (error(Section.getName(Name)))
  859. continue;
  860. uint64_t BaseAddr = Section.getAddress();
  861. uint64_t Size = Section.getSize();
  862. if (!Size)
  863. continue;
  864. outs() << "Contents of section " << Name << ":\n";
  865. if (Section.isBSS()) {
  866. outs() << format("<skipping contents of bss section at [%04" PRIx64
  867. ", %04" PRIx64 ")>\n",
  868. BaseAddr, BaseAddr + Size);
  869. continue;
  870. }
  871. if (error(Section.getContents(Contents)))
  872. continue;
  873. // Dump out the content as hex and printable ascii characters.
  874. for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
  875. outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
  876. // Dump line of hex.
  877. for (std::size_t i = 0; i < 16; ++i) {
  878. if (i != 0 && i % 4 == 0)
  879. outs() << ' ';
  880. if (addr + i < end)
  881. outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
  882. << hexdigit(Contents[addr + i] & 0xF, true);
  883. else
  884. outs() << " ";
  885. }
  886. // Print ascii.
  887. outs() << " ";
  888. for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
  889. if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
  890. outs() << Contents[addr + i];
  891. else
  892. outs() << ".";
  893. }
  894. outs() << "\n";
  895. }
  896. }
  897. }
  898. static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
  899. for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
  900. ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
  901. StringRef Name;
  902. if (error(Symbol.getError()))
  903. return;
  904. if (error(coff->getSymbolName(*Symbol, Name)))
  905. return;
  906. outs() << "[" << format("%2d", SI) << "]"
  907. << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
  908. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  909. << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
  910. << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
  911. << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
  912. << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
  913. << Name << "\n";
  914. for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
  915. if (Symbol->isSectionDefinition()) {
  916. const coff_aux_section_definition *asd;
  917. if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
  918. return;
  919. int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
  920. outs() << "AUX "
  921. << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
  922. , unsigned(asd->Length)
  923. , unsigned(asd->NumberOfRelocations)
  924. , unsigned(asd->NumberOfLinenumbers)
  925. , unsigned(asd->CheckSum))
  926. << format("assoc %d comdat %d\n"
  927. , unsigned(AuxNumber)
  928. , unsigned(asd->Selection));
  929. } else if (Symbol->isFileRecord()) {
  930. const char *FileName;
  931. if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
  932. return;
  933. StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
  934. coff->getSymbolTableEntrySize());
  935. outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
  936. SI = SI + Symbol->getNumberOfAuxSymbols();
  937. break;
  938. } else {
  939. outs() << "AUX Unknown\n";
  940. }
  941. }
  942. }
  943. }
  944. void llvm::PrintSymbolTable(const ObjectFile *o) {
  945. outs() << "SYMBOL TABLE:\n";
  946. if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
  947. PrintCOFFSymbolTable(coff);
  948. return;
  949. }
  950. for (const SymbolRef &Symbol : o->symbols()) {
  951. uint64_t Address;
  952. SymbolRef::Type Type;
  953. uint32_t Flags = Symbol.getFlags();
  954. section_iterator Section = o->section_end();
  955. if (error(Symbol.getAddress(Address)))
  956. continue;
  957. if (error(Symbol.getType(Type)))
  958. continue;
  959. uint64_t Size = Symbol.getSize();
  960. if (error(Symbol.getSection(Section)))
  961. continue;
  962. StringRef Name;
  963. if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
  964. Section->getName(Name);
  965. } else if (error(Symbol.getName(Name))) {
  966. continue;
  967. }
  968. bool Global = Flags & SymbolRef::SF_Global;
  969. bool Weak = Flags & SymbolRef::SF_Weak;
  970. bool Absolute = Flags & SymbolRef::SF_Absolute;
  971. bool Common = Flags & SymbolRef::SF_Common;
  972. bool Hidden = Flags & SymbolRef::SF_Hidden;
  973. if (Common) {
  974. uint32_t Alignment = Symbol.getAlignment();
  975. Address = Size;
  976. Size = Alignment;
  977. }
  978. if (Address == UnknownAddressOrSize)
  979. Address = 0;
  980. if (Size == UnknownAddressOrSize)
  981. Size = 0;
  982. char GlobLoc = ' ';
  983. if (Type != SymbolRef::ST_Unknown)
  984. GlobLoc = Global ? 'g' : 'l';
  985. char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
  986. ? 'd' : ' ';
  987. char FileFunc = ' ';
  988. if (Type == SymbolRef::ST_File)
  989. FileFunc = 'f';
  990. else if (Type == SymbolRef::ST_Function)
  991. FileFunc = 'F';
  992. const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
  993. "%08" PRIx64;
  994. outs() << format(Fmt, Address) << " "
  995. << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
  996. << (Weak ? 'w' : ' ') // Weak?
  997. << ' ' // Constructor. Not supported yet.
  998. << ' ' // Warning. Not supported yet.
  999. << ' ' // Indirect reference to another symbol.
  1000. << Debug // Debugging (d) or dynamic (D) symbol.
  1001. << FileFunc // Name of function (F), file (f) or object (O).
  1002. << ' ';
  1003. if (Absolute) {
  1004. outs() << "*ABS*";
  1005. } else if (Common) {
  1006. outs() << "*COM*";
  1007. } else if (Section == o->section_end()) {
  1008. outs() << "*UND*";
  1009. } else {
  1010. if (const MachOObjectFile *MachO =
  1011. dyn_cast<const MachOObjectFile>(o)) {
  1012. DataRefImpl DR = Section->getRawDataRefImpl();
  1013. StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
  1014. outs() << SegmentName << ",";
  1015. }
  1016. StringRef SectionName;
  1017. if (error(Section->getName(SectionName)))
  1018. SectionName = "";
  1019. outs() << SectionName;
  1020. }
  1021. outs() << '\t'
  1022. << format("%08" PRIx64 " ", Size);
  1023. if (Hidden) {
  1024. outs() << ".hidden ";
  1025. }
  1026. outs() << Name
  1027. << '\n';
  1028. }
  1029. }
  1030. static void PrintUnwindInfo(const ObjectFile *o) {
  1031. outs() << "Unwind info:\n\n";
  1032. if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
  1033. printCOFFUnwindInfo(coff);
  1034. } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1035. printMachOUnwindInfo(MachO);
  1036. else {
  1037. // TODO: Extract DWARF dump tool to objdump.
  1038. errs() << "This operation is only currently supported "
  1039. "for COFF and MachO object files.\n";
  1040. return;
  1041. }
  1042. }
  1043. void llvm::printExportsTrie(const ObjectFile *o) {
  1044. outs() << "Exports trie:\n";
  1045. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1046. printMachOExportsTrie(MachO);
  1047. else {
  1048. errs() << "This operation is only currently supported "
  1049. "for Mach-O executable files.\n";
  1050. return;
  1051. }
  1052. }
  1053. void llvm::printRebaseTable(const ObjectFile *o) {
  1054. outs() << "Rebase table:\n";
  1055. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1056. printMachORebaseTable(MachO);
  1057. else {
  1058. errs() << "This operation is only currently supported "
  1059. "for Mach-O executable files.\n";
  1060. return;
  1061. }
  1062. }
  1063. void llvm::printBindTable(const ObjectFile *o) {
  1064. outs() << "Bind table:\n";
  1065. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1066. printMachOBindTable(MachO);
  1067. else {
  1068. errs() << "This operation is only currently supported "
  1069. "for Mach-O executable files.\n";
  1070. return;
  1071. }
  1072. }
  1073. void llvm::printLazyBindTable(const ObjectFile *o) {
  1074. outs() << "Lazy bind table:\n";
  1075. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1076. printMachOLazyBindTable(MachO);
  1077. else {
  1078. errs() << "This operation is only currently supported "
  1079. "for Mach-O executable files.\n";
  1080. return;
  1081. }
  1082. }
  1083. void llvm::printWeakBindTable(const ObjectFile *o) {
  1084. outs() << "Weak bind table:\n";
  1085. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  1086. printMachOWeakBindTable(MachO);
  1087. else {
  1088. errs() << "This operation is only currently supported "
  1089. "for Mach-O executable files.\n";
  1090. return;
  1091. }
  1092. }
  1093. static void printPrivateFileHeader(const ObjectFile *o) {
  1094. if (o->isELF()) {
  1095. printELFFileHeader(o);
  1096. } else if (o->isCOFF()) {
  1097. printCOFFFileHeader(o);
  1098. } else if (o->isMachO()) {
  1099. printMachOFileHeader(o);
  1100. }
  1101. }
  1102. static void DumpObject(const ObjectFile *o) {
  1103. outs() << '\n';
  1104. outs() << o->getFileName()
  1105. << ":\tfile format " << o->getFileFormatName() << "\n\n";
  1106. if (Disassemble)
  1107. DisassembleObject(o, Relocations);
  1108. if (Relocations && !Disassemble)
  1109. PrintRelocations(o);
  1110. if (SectionHeaders)
  1111. PrintSectionHeaders(o);
  1112. if (SectionContents)
  1113. PrintSectionContents(o);
  1114. if (SymbolTable)
  1115. PrintSymbolTable(o);
  1116. if (UnwindInfo)
  1117. PrintUnwindInfo(o);
  1118. if (PrivateHeaders)
  1119. printPrivateFileHeader(o);
  1120. if (ExportsTrie)
  1121. printExportsTrie(o);
  1122. if (Rebase)
  1123. printRebaseTable(o);
  1124. if (Bind)
  1125. printBindTable(o);
  1126. if (LazyBind)
  1127. printLazyBindTable(o);
  1128. if (WeakBind)
  1129. printWeakBindTable(o);
  1130. }
  1131. /// @brief Dump each object file in \a a;
  1132. static void DumpArchive(const Archive *a) {
  1133. for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
  1134. ++i) {
  1135. ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
  1136. if (std::error_code EC = ChildOrErr.getError()) {
  1137. // Ignore non-object files.
  1138. if (EC != object_error::invalid_file_type)
  1139. report_error(a->getFileName(), EC);
  1140. continue;
  1141. }
  1142. if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
  1143. DumpObject(o);
  1144. else
  1145. report_error(a->getFileName(), object_error::invalid_file_type);
  1146. }
  1147. }
  1148. /// @brief Open file and figure out how to dump it.
  1149. static void DumpInput(StringRef file) {
  1150. // If file isn't stdin, check that it exists.
  1151. if (file != "-" && !sys::fs::exists(file)) {
  1152. report_error(file, errc::no_such_file_or_directory);
  1153. return;
  1154. }
  1155. // If we are using the Mach-O specific object file parser, then let it parse
  1156. // the file and process the command line options. So the -arch flags can
  1157. // be used to select specific slices, etc.
  1158. if (MachOOpt) {
  1159. ParseInputMachO(file);
  1160. return;
  1161. }
  1162. // Attempt to open the binary.
  1163. ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
  1164. if (std::error_code EC = BinaryOrErr.getError()) {
  1165. report_error(file, EC);
  1166. return;
  1167. }
  1168. Binary &Binary = *BinaryOrErr.get().getBinary();
  1169. if (Archive *a = dyn_cast<Archive>(&Binary))
  1170. DumpArchive(a);
  1171. else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
  1172. DumpObject(o);
  1173. else
  1174. report_error(file, object_error::invalid_file_type);
  1175. }
  1176. int main(int argc, char **argv) {
  1177. // Print a stack trace if we signal out.
  1178. sys::PrintStackTraceOnErrorSignal();
  1179. PrettyStackTraceProgram X(argc, argv);
  1180. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  1181. // Initialize targets and assembly printers/parsers.
  1182. llvm::InitializeAllTargetInfos();
  1183. llvm::InitializeAllTargetMCs();
  1184. llvm::InitializeAllAsmParsers();
  1185. llvm::InitializeAllDisassemblers();
  1186. // Register the target printer for --version.
  1187. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  1188. cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
  1189. TripleName = Triple::normalize(TripleName);
  1190. ToolName = argv[0];
  1191. // Defaults to a.out if no filenames specified.
  1192. if (InputFilenames.size() == 0)
  1193. InputFilenames.push_back("a.out");
  1194. if (!Disassemble
  1195. && !Relocations
  1196. && !SectionHeaders
  1197. && !SectionContents
  1198. && !SymbolTable
  1199. && !UnwindInfo
  1200. && !PrivateHeaders
  1201. && !ExportsTrie
  1202. && !Rebase
  1203. && !Bind
  1204. && !LazyBind
  1205. && !WeakBind
  1206. && !(UniversalHeaders && MachOOpt)
  1207. && !(ArchiveHeaders && MachOOpt)
  1208. && !(IndirectSymbols && MachOOpt)
  1209. && !(DataInCode && MachOOpt)
  1210. && !(LinkOptHints && MachOOpt)
  1211. && !(InfoPlist && MachOOpt)
  1212. && !(DylibsUsed && MachOOpt)
  1213. && !(DylibId && MachOOpt)
  1214. && !(ObjcMetaData && MachOOpt)
  1215. && !(DumpSections.size() != 0 && MachOOpt)) {
  1216. cl::PrintHelpMessage();
  1217. return 2;
  1218. }
  1219. std::for_each(InputFilenames.begin(), InputFilenames.end(),
  1220. DumpInput);
  1221. return ReturnValue;
  1222. }