llvm-objdump.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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/COFF.h"
  35. #include "llvm/Object/MachO.h"
  36. #include "llvm/Object/ObjectFile.h"
  37. #include "llvm/Support/Casting.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/FileSystem.h"
  41. #include "llvm/Support/Format.h"
  42. #include "llvm/Support/GraphWriter.h"
  43. #include "llvm/Support/Host.h"
  44. #include "llvm/Support/ManagedStatic.h"
  45. #include "llvm/Support/MemoryBuffer.h"
  46. #include "llvm/Support/PrettyStackTrace.h"
  47. #include "llvm/Support/Signals.h"
  48. #include "llvm/Support/SourceMgr.h"
  49. #include "llvm/Support/TargetRegistry.h"
  50. #include "llvm/Support/TargetSelect.h"
  51. #include "llvm/Support/raw_ostream.h"
  52. #include <algorithm>
  53. #include <cctype>
  54. #include <cstring>
  55. #include <system_error>
  56. using namespace llvm;
  57. using namespace object;
  58. static cl::list<std::string>
  59. InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
  60. cl::opt<bool>
  61. llvm::Disassemble("disassemble",
  62. cl::desc("Display assembler mnemonics for the machine instructions"));
  63. static cl::alias
  64. Disassembled("d", cl::desc("Alias for --disassemble"),
  65. cl::aliasopt(Disassemble));
  66. cl::opt<bool>
  67. llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
  68. cl::opt<bool>
  69. llvm::SectionContents("s", cl::desc("Display the content of each section"));
  70. cl::opt<bool>
  71. llvm::SymbolTable("t", cl::desc("Display the symbol table"));
  72. cl::opt<bool>
  73. llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
  74. cl::opt<bool>
  75. llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
  76. cl::opt<bool>
  77. llvm::Bind("bind", cl::desc("Display mach-o binding info"));
  78. cl::opt<bool>
  79. llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
  80. cl::opt<bool>
  81. llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
  82. static cl::opt<bool>
  83. MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
  84. static cl::alias
  85. MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
  86. cl::opt<std::string>
  87. llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
  88. "see -version for available targets"));
  89. cl::opt<std::string>
  90. llvm::MCPU("mcpu",
  91. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  92. cl::value_desc("cpu-name"),
  93. cl::init(""));
  94. cl::opt<std::string>
  95. llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
  96. "see -version for available targets"));
  97. cl::opt<bool>
  98. llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
  99. "headers for each section."));
  100. static cl::alias
  101. SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
  102. cl::aliasopt(SectionHeaders));
  103. static cl::alias
  104. SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
  105. cl::aliasopt(SectionHeaders));
  106. cl::list<std::string>
  107. llvm::MAttrs("mattr",
  108. cl::CommaSeparated,
  109. cl::desc("Target specific attributes"),
  110. cl::value_desc("a1,+a2,-a3,..."));
  111. cl::opt<bool>
  112. llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
  113. "instructions, do not print "
  114. "the instruction bytes."));
  115. cl::opt<bool>
  116. llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
  117. static cl::alias
  118. UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
  119. cl::aliasopt(UnwindInfo));
  120. cl::opt<bool>
  121. llvm::PrivateHeaders("private-headers",
  122. cl::desc("Display format specific file headers"));
  123. static cl::alias
  124. PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
  125. cl::aliasopt(PrivateHeaders));
  126. static StringRef ToolName;
  127. static int ReturnValue = EXIT_SUCCESS;
  128. bool llvm::error(std::error_code EC) {
  129. if (!EC)
  130. return false;
  131. outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
  132. outs().flush();
  133. ReturnValue = EXIT_FAILURE;
  134. return true;
  135. }
  136. static const Target *getTarget(const ObjectFile *Obj = nullptr) {
  137. // Figure out the target triple.
  138. llvm::Triple TheTriple("unknown-unknown-unknown");
  139. if (TripleName.empty()) {
  140. if (Obj) {
  141. TheTriple.setArch(Triple::ArchType(Obj->getArch()));
  142. // TheTriple defaults to ELF, and COFF doesn't have an environment:
  143. // the best we can do here is indicate that it is mach-o.
  144. if (Obj->isMachO())
  145. TheTriple.setObjectFormat(Triple::MachO);
  146. if (Obj->isCOFF()) {
  147. const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
  148. if (COFFObj->getArch() == Triple::thumb)
  149. TheTriple.setTriple("thumbv7-windows");
  150. }
  151. }
  152. } else
  153. TheTriple.setTriple(Triple::normalize(TripleName));
  154. // Get the target specific parser.
  155. std::string Error;
  156. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  157. Error);
  158. if (!TheTarget) {
  159. errs() << ToolName << ": " << Error;
  160. return nullptr;
  161. }
  162. // Update the triple name and return the found target.
  163. TripleName = TheTriple.getTriple();
  164. return TheTarget;
  165. }
  166. bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
  167. uint64_t a_addr, b_addr;
  168. if (error(a.getOffset(a_addr))) return false;
  169. if (error(b.getOffset(b_addr))) return false;
  170. return a_addr < b_addr;
  171. }
  172. namespace {
  173. class PrettyPrinter {
  174. public:
  175. virtual ~PrettyPrinter(){}
  176. virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
  177. ArrayRef<uint8_t> Bytes, uint64_t Address,
  178. raw_ostream &OS, StringRef Annot,
  179. MCSubtargetInfo const &STI) {
  180. outs() << format("%8" PRIx64 ":", Address);
  181. if (!NoShowRawInsn) {
  182. outs() << "\t";
  183. dumpBytes(Bytes, outs());
  184. }
  185. IP.printInst(MI, outs(), "", STI);
  186. }
  187. };
  188. PrettyPrinter PrettyPrinterInst;
  189. class HexagonPrettyPrinter : public PrettyPrinter {
  190. public:
  191. void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
  192. raw_ostream &OS) {
  193. uint32_t opcode =
  194. (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
  195. OS << format("%8" PRIx64 ":", Address);
  196. if (!NoShowRawInsn) {
  197. OS << "\t";
  198. dumpBytes(Bytes.slice(0, 4), OS);
  199. OS << format("%08" PRIx32, opcode);
  200. }
  201. }
  202. void printInst(MCInstPrinter &IP, const MCInst *MI,
  203. ArrayRef<uint8_t> Bytes, uint64_t Address,
  204. raw_ostream &OS, StringRef Annot,
  205. MCSubtargetInfo const &STI) override {
  206. std::string Buffer;
  207. {
  208. raw_string_ostream TempStream(Buffer);
  209. IP.printInst(MI, TempStream, "", STI);
  210. }
  211. StringRef Contents(Buffer);
  212. // Split off bundle attributes
  213. auto PacketBundle = Contents.rsplit('\n');
  214. // Split off first instruction from the rest
  215. auto HeadTail = PacketBundle.first.split('\n');
  216. auto Preamble = " { ";
  217. auto Separator = "";
  218. while(!HeadTail.first.empty()) {
  219. OS << Separator;
  220. Separator = "\n";
  221. printLead(Bytes, Address, OS);
  222. OS << Preamble;
  223. Preamble = " ";
  224. StringRef Inst;
  225. auto Duplex = HeadTail.first.split('\v');
  226. if(!Duplex.second.empty()){
  227. OS << Duplex.first;
  228. OS << "; ";
  229. Inst = Duplex.second;
  230. }
  231. else
  232. Inst = HeadTail.first;
  233. OS << Inst;
  234. Bytes = Bytes.slice(4);
  235. Address += 4;
  236. HeadTail = HeadTail.second.split('\n');
  237. }
  238. OS << " } " << PacketBundle.second;
  239. }
  240. };
  241. HexagonPrettyPrinter HexagonPrettyPrinterInst;
  242. PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
  243. switch(Triple.getArch()) {
  244. default:
  245. return PrettyPrinterInst;
  246. case Triple::hexagon:
  247. return HexagonPrettyPrinterInst;
  248. }
  249. }
  250. }
  251. static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
  252. const Target *TheTarget = getTarget(Obj);
  253. // getTarget() will have already issued a diagnostic if necessary, so
  254. // just bail here if it failed.
  255. if (!TheTarget)
  256. return;
  257. // Package up features to be passed to target/subtarget
  258. std::string FeaturesStr;
  259. if (MAttrs.size()) {
  260. SubtargetFeatures Features;
  261. for (unsigned i = 0; i != MAttrs.size(); ++i)
  262. Features.AddFeature(MAttrs[i]);
  263. FeaturesStr = Features.getString();
  264. }
  265. std::unique_ptr<const MCRegisterInfo> MRI(
  266. TheTarget->createMCRegInfo(TripleName));
  267. if (!MRI) {
  268. errs() << "error: no register info for target " << TripleName << "\n";
  269. return;
  270. }
  271. // Set up disassembler.
  272. std::unique_ptr<const MCAsmInfo> AsmInfo(
  273. TheTarget->createMCAsmInfo(*MRI, TripleName));
  274. if (!AsmInfo) {
  275. errs() << "error: no assembly info for target " << TripleName << "\n";
  276. return;
  277. }
  278. std::unique_ptr<const MCSubtargetInfo> STI(
  279. TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
  280. if (!STI) {
  281. errs() << "error: no subtarget info for target " << TripleName << "\n";
  282. return;
  283. }
  284. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  285. if (!MII) {
  286. errs() << "error: no instruction info for target " << TripleName << "\n";
  287. return;
  288. }
  289. std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
  290. MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
  291. std::unique_ptr<MCDisassembler> DisAsm(
  292. TheTarget->createMCDisassembler(*STI, Ctx));
  293. if (!DisAsm) {
  294. errs() << "error: no disassembler for target " << TripleName << "\n";
  295. return;
  296. }
  297. std::unique_ptr<const MCInstrAnalysis> MIA(
  298. TheTarget->createMCInstrAnalysis(MII.get()));
  299. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  300. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  301. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
  302. if (!IP) {
  303. errs() << "error: no instruction printer for target " << TripleName
  304. << '\n';
  305. return;
  306. }
  307. PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
  308. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
  309. "\t\t\t%08" PRIx64 ": ";
  310. // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
  311. // in RelocSecs contain the relocations for section S.
  312. std::error_code EC;
  313. std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
  314. for (const SectionRef &Section : Obj->sections()) {
  315. section_iterator Sec2 = Section.getRelocatedSection();
  316. if (Sec2 != Obj->section_end())
  317. SectionRelocMap[*Sec2].push_back(Section);
  318. }
  319. for (const SectionRef &Section : Obj->sections()) {
  320. if (!Section.isText() || Section.isVirtual())
  321. continue;
  322. uint64_t SectionAddr = Section.getAddress();
  323. uint64_t SectSize = Section.getSize();
  324. if (!SectSize)
  325. continue;
  326. // Make a list of all the symbols in this section.
  327. std::vector<std::pair<uint64_t, StringRef>> Symbols;
  328. for (const SymbolRef &Symbol : Obj->symbols()) {
  329. if (Section.containsSymbol(Symbol)) {
  330. uint64_t Address;
  331. if (error(Symbol.getAddress(Address)))
  332. break;
  333. if (Address == UnknownAddressOrSize)
  334. continue;
  335. Address -= SectionAddr;
  336. if (Address >= SectSize)
  337. continue;
  338. StringRef Name;
  339. if (error(Symbol.getName(Name)))
  340. break;
  341. Symbols.push_back(std::make_pair(Address, Name));
  342. }
  343. }
  344. // Sort the symbols by address, just in case they didn't come in that way.
  345. array_pod_sort(Symbols.begin(), Symbols.end());
  346. // Make a list of all the relocations for this section.
  347. std::vector<RelocationRef> Rels;
  348. if (InlineRelocs) {
  349. for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
  350. for (const RelocationRef &Reloc : RelocSec.relocations()) {
  351. Rels.push_back(Reloc);
  352. }
  353. }
  354. }
  355. // Sort relocations by address.
  356. std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
  357. StringRef SegmentName = "";
  358. if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
  359. DataRefImpl DR = Section.getRawDataRefImpl();
  360. SegmentName = MachO->getSectionFinalSegmentName(DR);
  361. }
  362. StringRef name;
  363. if (error(Section.getName(name)))
  364. break;
  365. outs() << "Disassembly of section ";
  366. if (!SegmentName.empty())
  367. outs() << SegmentName << ",";
  368. outs() << name << ':';
  369. // If the section has no symbols just insert a dummy one and disassemble
  370. // the whole section.
  371. if (Symbols.empty())
  372. Symbols.push_back(std::make_pair(0, name));
  373. SmallString<40> Comments;
  374. raw_svector_ostream CommentStream(Comments);
  375. StringRef BytesStr;
  376. if (error(Section.getContents(BytesStr)))
  377. break;
  378. ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
  379. BytesStr.size());
  380. uint64_t Size;
  381. uint64_t Index;
  382. std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
  383. std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
  384. // Disassemble symbol by symbol.
  385. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
  386. uint64_t Start = Symbols[si].first;
  387. // The end is either the section end or the beginning of the next symbol.
  388. uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
  389. // If this symbol has the same address as the next symbol, then skip it.
  390. if (Start == End)
  391. continue;
  392. outs() << '\n' << Symbols[si].second << ":\n";
  393. #ifndef NDEBUG
  394. raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
  395. #else
  396. raw_ostream &DebugOut = nulls();
  397. #endif
  398. for (Index = Start; Index < End; Index += Size) {
  399. MCInst Inst;
  400. if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
  401. SectionAddr + Index, DebugOut,
  402. CommentStream)) {
  403. PIP.printInst(*IP, &Inst,
  404. Bytes.slice(Index, Size),
  405. SectionAddr + Index, outs(), "", *STI);
  406. outs() << CommentStream.str();
  407. Comments.clear();
  408. outs() << "\n";
  409. } else {
  410. errs() << ToolName << ": warning: invalid instruction encoding\n";
  411. if (Size == 0)
  412. Size = 1; // skip illegible bytes
  413. }
  414. // Print relocation for instruction.
  415. while (rel_cur != rel_end) {
  416. bool hidden = false;
  417. uint64_t addr;
  418. SmallString<16> name;
  419. SmallString<32> val;
  420. // If this relocation is hidden, skip it.
  421. if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
  422. if (hidden) goto skip_print_rel;
  423. if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
  424. // Stop when rel_cur's address is past the current instruction.
  425. if (addr >= Index + Size) break;
  426. if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
  427. if (error(rel_cur->getValueString(val))) goto skip_print_rel;
  428. outs() << format(Fmt.data(), SectionAddr + addr) << name
  429. << "\t" << val << "\n";
  430. skip_print_rel:
  431. ++rel_cur;
  432. }
  433. }
  434. }
  435. }
  436. }
  437. void llvm::PrintRelocations(const ObjectFile *Obj) {
  438. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
  439. "%08" PRIx64;
  440. // Regular objdump doesn't print relocations in non-relocatable object
  441. // files.
  442. if (!Obj->isRelocatableObject())
  443. return;
  444. for (const SectionRef &Section : Obj->sections()) {
  445. if (Section.relocation_begin() == Section.relocation_end())
  446. continue;
  447. StringRef secname;
  448. if (error(Section.getName(secname)))
  449. continue;
  450. outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
  451. for (const RelocationRef &Reloc : Section.relocations()) {
  452. bool hidden;
  453. uint64_t address;
  454. SmallString<32> relocname;
  455. SmallString<32> valuestr;
  456. if (error(Reloc.getHidden(hidden)))
  457. continue;
  458. if (hidden)
  459. continue;
  460. if (error(Reloc.getTypeName(relocname)))
  461. continue;
  462. if (error(Reloc.getOffset(address)))
  463. continue;
  464. if (error(Reloc.getValueString(valuestr)))
  465. continue;
  466. outs() << format(Fmt.data(), address) << " " << relocname << " "
  467. << valuestr << "\n";
  468. }
  469. outs() << "\n";
  470. }
  471. }
  472. void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
  473. outs() << "Sections:\n"
  474. "Idx Name Size Address Type\n";
  475. unsigned i = 0;
  476. for (const SectionRef &Section : Obj->sections()) {
  477. StringRef Name;
  478. if (error(Section.getName(Name)))
  479. return;
  480. uint64_t Address = Section.getAddress();
  481. uint64_t Size = Section.getSize();
  482. bool Text = Section.isText();
  483. bool Data = Section.isData();
  484. bool BSS = Section.isBSS();
  485. std::string Type = (std::string(Text ? "TEXT " : "") +
  486. (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
  487. outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
  488. Name.str().c_str(), Size, Address, Type.c_str());
  489. ++i;
  490. }
  491. }
  492. void llvm::PrintSectionContents(const ObjectFile *Obj) {
  493. std::error_code EC;
  494. for (const SectionRef &Section : Obj->sections()) {
  495. StringRef Name;
  496. StringRef Contents;
  497. if (error(Section.getName(Name)))
  498. continue;
  499. uint64_t BaseAddr = Section.getAddress();
  500. uint64_t Size = Section.getSize();
  501. if (!Size)
  502. continue;
  503. outs() << "Contents of section " << Name << ":\n";
  504. if (Section.isBSS()) {
  505. outs() << format("<skipping contents of bss section at [%04" PRIx64
  506. ", %04" PRIx64 ")>\n",
  507. BaseAddr, BaseAddr + Size);
  508. continue;
  509. }
  510. if (error(Section.getContents(Contents)))
  511. continue;
  512. // Dump out the content as hex and printable ascii characters.
  513. for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
  514. outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
  515. // Dump line of hex.
  516. for (std::size_t i = 0; i < 16; ++i) {
  517. if (i != 0 && i % 4 == 0)
  518. outs() << ' ';
  519. if (addr + i < end)
  520. outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
  521. << hexdigit(Contents[addr + i] & 0xF, true);
  522. else
  523. outs() << " ";
  524. }
  525. // Print ascii.
  526. outs() << " ";
  527. for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
  528. if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
  529. outs() << Contents[addr + i];
  530. else
  531. outs() << ".";
  532. }
  533. outs() << "\n";
  534. }
  535. }
  536. }
  537. static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
  538. for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
  539. ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
  540. StringRef Name;
  541. if (error(Symbol.getError()))
  542. return;
  543. if (error(coff->getSymbolName(*Symbol, Name)))
  544. return;
  545. outs() << "[" << format("%2d", SI) << "]"
  546. << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
  547. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  548. << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
  549. << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
  550. << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
  551. << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
  552. << Name << "\n";
  553. for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
  554. if (Symbol->isSectionDefinition()) {
  555. const coff_aux_section_definition *asd;
  556. if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
  557. return;
  558. int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
  559. outs() << "AUX "
  560. << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
  561. , unsigned(asd->Length)
  562. , unsigned(asd->NumberOfRelocations)
  563. , unsigned(asd->NumberOfLinenumbers)
  564. , unsigned(asd->CheckSum))
  565. << format("assoc %d comdat %d\n"
  566. , unsigned(AuxNumber)
  567. , unsigned(asd->Selection));
  568. } else if (Symbol->isFileRecord()) {
  569. const char *FileName;
  570. if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
  571. return;
  572. StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
  573. coff->getSymbolTableEntrySize());
  574. outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
  575. SI = SI + Symbol->getNumberOfAuxSymbols();
  576. break;
  577. } else {
  578. outs() << "AUX Unknown\n";
  579. }
  580. }
  581. }
  582. }
  583. void llvm::PrintSymbolTable(const ObjectFile *o) {
  584. outs() << "SYMBOL TABLE:\n";
  585. if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
  586. PrintCOFFSymbolTable(coff);
  587. return;
  588. }
  589. for (const SymbolRef &Symbol : o->symbols()) {
  590. StringRef Name;
  591. uint64_t Address;
  592. SymbolRef::Type Type;
  593. uint64_t Size;
  594. uint32_t Flags = Symbol.getFlags();
  595. section_iterator Section = o->section_end();
  596. if (error(Symbol.getName(Name)))
  597. continue;
  598. if (error(Symbol.getAddress(Address)))
  599. continue;
  600. if (error(Symbol.getType(Type)))
  601. continue;
  602. if (error(Symbol.getSize(Size)))
  603. continue;
  604. if (error(Symbol.getSection(Section)))
  605. continue;
  606. bool Global = Flags & SymbolRef::SF_Global;
  607. bool Weak = Flags & SymbolRef::SF_Weak;
  608. bool Absolute = Flags & SymbolRef::SF_Absolute;
  609. bool Common = Flags & SymbolRef::SF_Common;
  610. bool Hidden = Flags & SymbolRef::SF_Hidden;
  611. if (Common) {
  612. uint32_t Alignment = Symbol.getAlignment();
  613. Address = Size;
  614. Size = Alignment;
  615. }
  616. if (Address == UnknownAddressOrSize)
  617. Address = 0;
  618. if (Size == UnknownAddressOrSize)
  619. Size = 0;
  620. char GlobLoc = ' ';
  621. if (Type != SymbolRef::ST_Unknown)
  622. GlobLoc = Global ? 'g' : 'l';
  623. char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
  624. ? 'd' : ' ';
  625. char FileFunc = ' ';
  626. if (Type == SymbolRef::ST_File)
  627. FileFunc = 'f';
  628. else if (Type == SymbolRef::ST_Function)
  629. FileFunc = 'F';
  630. const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
  631. "%08" PRIx64;
  632. outs() << format(Fmt, Address) << " "
  633. << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
  634. << (Weak ? 'w' : ' ') // Weak?
  635. << ' ' // Constructor. Not supported yet.
  636. << ' ' // Warning. Not supported yet.
  637. << ' ' // Indirect reference to another symbol.
  638. << Debug // Debugging (d) or dynamic (D) symbol.
  639. << FileFunc // Name of function (F), file (f) or object (O).
  640. << ' ';
  641. if (Absolute) {
  642. outs() << "*ABS*";
  643. } else if (Common) {
  644. outs() << "*COM*";
  645. } else if (Section == o->section_end()) {
  646. outs() << "*UND*";
  647. } else {
  648. if (const MachOObjectFile *MachO =
  649. dyn_cast<const MachOObjectFile>(o)) {
  650. DataRefImpl DR = Section->getRawDataRefImpl();
  651. StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
  652. outs() << SegmentName << ",";
  653. }
  654. StringRef SectionName;
  655. if (error(Section->getName(SectionName)))
  656. SectionName = "";
  657. outs() << SectionName;
  658. }
  659. outs() << '\t'
  660. << format("%08" PRIx64 " ", Size);
  661. if (Hidden) {
  662. outs() << ".hidden ";
  663. }
  664. outs() << Name
  665. << '\n';
  666. }
  667. }
  668. static void PrintUnwindInfo(const ObjectFile *o) {
  669. outs() << "Unwind info:\n\n";
  670. if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
  671. printCOFFUnwindInfo(coff);
  672. } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  673. printMachOUnwindInfo(MachO);
  674. else {
  675. // TODO: Extract DWARF dump tool to objdump.
  676. errs() << "This operation is only currently supported "
  677. "for COFF and MachO object files.\n";
  678. return;
  679. }
  680. }
  681. void llvm::printExportsTrie(const ObjectFile *o) {
  682. outs() << "Exports trie:\n";
  683. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  684. printMachOExportsTrie(MachO);
  685. else {
  686. errs() << "This operation is only currently supported "
  687. "for Mach-O executable files.\n";
  688. return;
  689. }
  690. }
  691. void llvm::printRebaseTable(const ObjectFile *o) {
  692. outs() << "Rebase table:\n";
  693. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  694. printMachORebaseTable(MachO);
  695. else {
  696. errs() << "This operation is only currently supported "
  697. "for Mach-O executable files.\n";
  698. return;
  699. }
  700. }
  701. void llvm::printBindTable(const ObjectFile *o) {
  702. outs() << "Bind table:\n";
  703. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  704. printMachOBindTable(MachO);
  705. else {
  706. errs() << "This operation is only currently supported "
  707. "for Mach-O executable files.\n";
  708. return;
  709. }
  710. }
  711. void llvm::printLazyBindTable(const ObjectFile *o) {
  712. outs() << "Lazy bind table:\n";
  713. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  714. printMachOLazyBindTable(MachO);
  715. else {
  716. errs() << "This operation is only currently supported "
  717. "for Mach-O executable files.\n";
  718. return;
  719. }
  720. }
  721. void llvm::printWeakBindTable(const ObjectFile *o) {
  722. outs() << "Weak bind table:\n";
  723. if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
  724. printMachOWeakBindTable(MachO);
  725. else {
  726. errs() << "This operation is only currently supported "
  727. "for Mach-O executable files.\n";
  728. return;
  729. }
  730. }
  731. static void printPrivateFileHeader(const ObjectFile *o) {
  732. if (o->isELF()) {
  733. printELFFileHeader(o);
  734. } else if (o->isCOFF()) {
  735. printCOFFFileHeader(o);
  736. } else if (o->isMachO()) {
  737. printMachOFileHeader(o);
  738. }
  739. }
  740. static void DumpObject(const ObjectFile *o) {
  741. outs() << '\n';
  742. outs() << o->getFileName()
  743. << ":\tfile format " << o->getFileFormatName() << "\n\n";
  744. if (Disassemble)
  745. DisassembleObject(o, Relocations);
  746. if (Relocations && !Disassemble)
  747. PrintRelocations(o);
  748. if (SectionHeaders)
  749. PrintSectionHeaders(o);
  750. if (SectionContents)
  751. PrintSectionContents(o);
  752. if (SymbolTable)
  753. PrintSymbolTable(o);
  754. if (UnwindInfo)
  755. PrintUnwindInfo(o);
  756. if (PrivateHeaders)
  757. printPrivateFileHeader(o);
  758. if (ExportsTrie)
  759. printExportsTrie(o);
  760. if (Rebase)
  761. printRebaseTable(o);
  762. if (Bind)
  763. printBindTable(o);
  764. if (LazyBind)
  765. printLazyBindTable(o);
  766. if (WeakBind)
  767. printWeakBindTable(o);
  768. }
  769. /// @brief Dump each object file in \a a;
  770. static void DumpArchive(const Archive *a) {
  771. for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
  772. ++i) {
  773. ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
  774. if (std::error_code EC = ChildOrErr.getError()) {
  775. // Ignore non-object files.
  776. if (EC != object_error::invalid_file_type)
  777. errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
  778. << ".\n";
  779. continue;
  780. }
  781. if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
  782. DumpObject(o);
  783. else
  784. errs() << ToolName << ": '" << a->getFileName() << "': "
  785. << "Unrecognized file type.\n";
  786. }
  787. }
  788. /// @brief Open file and figure out how to dump it.
  789. static void DumpInput(StringRef file) {
  790. // If file isn't stdin, check that it exists.
  791. if (file != "-" && !sys::fs::exists(file)) {
  792. errs() << ToolName << ": '" << file << "': " << "No such file\n";
  793. return;
  794. }
  795. // If we are using the Mach-O specific object file parser, then let it parse
  796. // the file and process the command line options. So the -arch flags can
  797. // be used to select specific slices, etc.
  798. if (MachOOpt) {
  799. ParseInputMachO(file);
  800. return;
  801. }
  802. // Attempt to open the binary.
  803. ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
  804. if (std::error_code EC = BinaryOrErr.getError()) {
  805. errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
  806. return;
  807. }
  808. Binary &Binary = *BinaryOrErr.get().getBinary();
  809. if (Archive *a = dyn_cast<Archive>(&Binary))
  810. DumpArchive(a);
  811. else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
  812. DumpObject(o);
  813. else
  814. errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
  815. }
  816. int main(int argc, char **argv) {
  817. // Print a stack trace if we signal out.
  818. sys::PrintStackTraceOnErrorSignal();
  819. PrettyStackTraceProgram X(argc, argv);
  820. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  821. // Initialize targets and assembly printers/parsers.
  822. llvm::InitializeAllTargetInfos();
  823. llvm::InitializeAllTargetMCs();
  824. llvm::InitializeAllAsmParsers();
  825. llvm::InitializeAllDisassemblers();
  826. // Register the target printer for --version.
  827. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  828. cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
  829. TripleName = Triple::normalize(TripleName);
  830. ToolName = argv[0];
  831. // Defaults to a.out if no filenames specified.
  832. if (InputFilenames.size() == 0)
  833. InputFilenames.push_back("a.out");
  834. if (!Disassemble
  835. && !Relocations
  836. && !SectionHeaders
  837. && !SectionContents
  838. && !SymbolTable
  839. && !UnwindInfo
  840. && !PrivateHeaders
  841. && !ExportsTrie
  842. && !Rebase
  843. && !Bind
  844. && !LazyBind
  845. && !WeakBind
  846. && !(UniversalHeaders && MachOOpt)
  847. && !(ArchiveHeaders && MachOOpt)
  848. && !(IndirectSymbols && MachOOpt)
  849. && !(DataInCode && MachOOpt)
  850. && !(LinkOptHints && MachOOpt)
  851. && !(InfoPlist && MachOOpt)
  852. && !(DylibsUsed && MachOOpt)
  853. && !(DylibId && MachOOpt)
  854. && !(ObjcMetaData && MachOOpt)
  855. && !(DumpSections.size() != 0 && MachOOpt)) {
  856. cl::PrintHelpMessage();
  857. return 2;
  858. }
  859. std::for_each(InputFilenames.begin(), InputFilenames.end(),
  860. DumpInput);
  861. return ReturnValue;
  862. }