llvm-objdump.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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/MCAtom.h"
  24. #include "llvm/MC/MCContext.h"
  25. #include "llvm/MC/MCDisassembler.h"
  26. #include "llvm/MC/MCFunction.h"
  27. #include "llvm/MC/MCInst.h"
  28. #include "llvm/MC/MCInstPrinter.h"
  29. #include "llvm/MC/MCInstrAnalysis.h"
  30. #include "llvm/MC/MCInstrInfo.h"
  31. #include "llvm/MC/MCModule.h"
  32. #include "llvm/MC/MCModuleYAML.h"
  33. #include "llvm/MC/MCObjectDisassembler.h"
  34. #include "llvm/MC/MCObjectFileInfo.h"
  35. #include "llvm/MC/MCObjectSymbolizer.h"
  36. #include "llvm/MC/MCRegisterInfo.h"
  37. #include "llvm/MC/MCRelocationInfo.h"
  38. #include "llvm/MC/MCSubtargetInfo.h"
  39. #include "llvm/Object/Archive.h"
  40. #include "llvm/Object/COFF.h"
  41. #include "llvm/Object/MachO.h"
  42. #include "llvm/Object/ObjectFile.h"
  43. #include "llvm/Support/Casting.h"
  44. #include "llvm/Support/CommandLine.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/FileSystem.h"
  47. #include "llvm/Support/Format.h"
  48. #include "llvm/Support/GraphWriter.h"
  49. #include "llvm/Support/Host.h"
  50. #include "llvm/Support/ManagedStatic.h"
  51. #include "llvm/Support/MemoryBuffer.h"
  52. #include "llvm/Support/MemoryObject.h"
  53. #include "llvm/Support/PrettyStackTrace.h"
  54. #include "llvm/Support/Signals.h"
  55. #include "llvm/Support/SourceMgr.h"
  56. #include "llvm/Support/TargetRegistry.h"
  57. #include "llvm/Support/TargetSelect.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include "llvm/Support/system_error.h"
  60. #include <algorithm>
  61. #include <cctype>
  62. #include <cstring>
  63. using namespace llvm;
  64. using namespace object;
  65. static cl::list<std::string>
  66. InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
  67. static cl::opt<bool>
  68. Disassemble("disassemble",
  69. cl::desc("Display assembler mnemonics for the machine instructions"));
  70. static cl::alias
  71. Disassembled("d", cl::desc("Alias for --disassemble"),
  72. cl::aliasopt(Disassemble));
  73. static cl::opt<bool>
  74. Relocations("r", cl::desc("Display the relocation entries in the file"));
  75. static cl::opt<bool>
  76. SectionContents("s", cl::desc("Display the content of each section"));
  77. static cl::opt<bool>
  78. SymbolTable("t", cl::desc("Display the symbol table"));
  79. static cl::opt<bool>
  80. MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
  81. static cl::alias
  82. MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
  83. cl::opt<std::string>
  84. llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
  85. "see -version for available targets"));
  86. cl::opt<std::string>
  87. llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
  88. "see -version for available targets"));
  89. static cl::opt<bool>
  90. SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
  91. "for each section."));
  92. static cl::alias
  93. SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
  94. cl::aliasopt(SectionHeaders));
  95. static cl::alias
  96. SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
  97. cl::aliasopt(SectionHeaders));
  98. static cl::list<std::string>
  99. MAttrs("mattr",
  100. cl::CommaSeparated,
  101. cl::desc("Target specific attributes"),
  102. cl::value_desc("a1,+a2,-a3,..."));
  103. static cl::opt<bool>
  104. NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
  105. "do not print the instruction bytes."));
  106. static cl::opt<bool>
  107. UnwindInfo("unwind-info", cl::desc("Display unwind information"));
  108. static cl::alias
  109. UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
  110. cl::aliasopt(UnwindInfo));
  111. static cl::opt<bool>
  112. PrivateHeaders("private-headers",
  113. cl::desc("Display format specific file headers"));
  114. static cl::alias
  115. PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
  116. cl::aliasopt(PrivateHeaders));
  117. static cl::opt<bool>
  118. Symbolize("symbolize", cl::desc("When disassembling instructions, "
  119. "try to symbolize operands."));
  120. static cl::opt<bool>
  121. CFG("cfg", cl::desc("Create a CFG for every function found in the object"
  122. " and write it to a graphviz file"));
  123. // FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
  124. static cl::opt<std::string>
  125. YAMLCFG("yaml-cfg",
  126. cl::desc("Create a CFG and write it as a YAML MCModule."),
  127. cl::value_desc("yaml output file"));
  128. static StringRef ToolName;
  129. bool llvm::error(error_code EC) {
  130. if (!EC)
  131. return false;
  132. outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
  133. outs().flush();
  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. // Write a graphviz file for the CFG inside an MCFunction.
  167. // FIXME: Use GraphWriter
  168. static void emitDOTFile(const char *FileName, const MCFunction &f,
  169. MCInstPrinter *IP) {
  170. // Start a new dot file.
  171. std::string Error;
  172. raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
  173. if (!Error.empty()) {
  174. errs() << "llvm-objdump: warning: " << Error << '\n';
  175. return;
  176. }
  177. Out << "digraph \"" << f.getName() << "\" {\n";
  178. Out << "graph [ rankdir = \"LR\" ];\n";
  179. for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
  180. // Only print blocks that have predecessors.
  181. bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
  182. if (!hasPreds && i != f.begin())
  183. continue;
  184. Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
  185. // Print instructions.
  186. for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
  187. ++ii) {
  188. if (ii != 0) // Not the first line, start a new row.
  189. Out << '|';
  190. if (ii + 1 == ie) // Last line, add an end id.
  191. Out << "<o>";
  192. // Escape special chars and print the instruction in mnemonic form.
  193. std::string Str;
  194. raw_string_ostream OS(Str);
  195. IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
  196. Out << DOT::EscapeString(OS.str());
  197. }
  198. Out << "\" shape=\"record\" ];\n";
  199. // Add edges.
  200. for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
  201. se = (*i)->succ_end(); si != se; ++si)
  202. Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
  203. << (*si)->getInsts()->getBeginAddr() << ":a\n";
  204. }
  205. Out << "}\n";
  206. }
  207. void llvm::DumpBytes(StringRef bytes) {
  208. static const char hex_rep[] = "0123456789abcdef";
  209. // FIXME: The real way to do this is to figure out the longest instruction
  210. // and align to that size before printing. I'll fix this when I get
  211. // around to outputting relocations.
  212. // 15 is the longest x86 instruction
  213. // 3 is for the hex rep of a byte + a space.
  214. // 1 is for the null terminator.
  215. enum { OutputSize = (15 * 3) + 1 };
  216. char output[OutputSize];
  217. assert(bytes.size() <= 15
  218. && "DumpBytes only supports instructions of up to 15 bytes");
  219. memset(output, ' ', sizeof(output));
  220. unsigned index = 0;
  221. for (StringRef::iterator i = bytes.begin(),
  222. e = bytes.end(); i != e; ++i) {
  223. output[index] = hex_rep[(*i & 0xF0) >> 4];
  224. output[index + 1] = hex_rep[*i & 0xF];
  225. index += 3;
  226. }
  227. output[sizeof(output) - 1] = 0;
  228. outs() << output;
  229. }
  230. bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
  231. uint64_t a_addr, b_addr;
  232. if (error(a.getOffset(a_addr))) return false;
  233. if (error(b.getOffset(b_addr))) return false;
  234. return a_addr < b_addr;
  235. }
  236. static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
  237. const Target *TheTarget = getTarget(Obj);
  238. // getTarget() will have already issued a diagnostic if necessary, so
  239. // just bail here if it failed.
  240. if (!TheTarget)
  241. return;
  242. // Package up features to be passed to target/subtarget
  243. std::string FeaturesStr;
  244. if (MAttrs.size()) {
  245. SubtargetFeatures Features;
  246. for (unsigned i = 0; i != MAttrs.size(); ++i)
  247. Features.AddFeature(MAttrs[i]);
  248. FeaturesStr = Features.getString();
  249. }
  250. std::unique_ptr<const MCRegisterInfo> MRI(
  251. TheTarget->createMCRegInfo(TripleName));
  252. if (!MRI) {
  253. errs() << "error: no register info for target " << TripleName << "\n";
  254. return;
  255. }
  256. // Set up disassembler.
  257. std::unique_ptr<const MCAsmInfo> AsmInfo(
  258. TheTarget->createMCAsmInfo(*MRI, TripleName));
  259. if (!AsmInfo) {
  260. errs() << "error: no assembly info for target " << TripleName << "\n";
  261. return;
  262. }
  263. std::unique_ptr<const MCSubtargetInfo> STI(
  264. TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
  265. if (!STI) {
  266. errs() << "error: no subtarget info for target " << TripleName << "\n";
  267. return;
  268. }
  269. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  270. if (!MII) {
  271. errs() << "error: no instruction info for target " << TripleName << "\n";
  272. return;
  273. }
  274. std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
  275. MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
  276. std::unique_ptr<MCDisassembler> DisAsm(
  277. TheTarget->createMCDisassembler(*STI, Ctx));
  278. if (!DisAsm) {
  279. errs() << "error: no disassembler for target " << TripleName << "\n";
  280. return;
  281. }
  282. if (Symbolize) {
  283. std::unique_ptr<MCRelocationInfo> RelInfo(
  284. TheTarget->createMCRelocationInfo(TripleName, Ctx));
  285. if (RelInfo) {
  286. std::unique_ptr<MCSymbolizer> Symzer(
  287. MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
  288. Obj));
  289. if (Symzer)
  290. DisAsm->setSymbolizer(std::move(Symzer));
  291. }
  292. }
  293. std::unique_ptr<const MCInstrAnalysis> MIA(
  294. TheTarget->createMCInstrAnalysis(MII.get()));
  295. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  296. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  297. AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
  298. if (!IP) {
  299. errs() << "error: no instruction printer for target " << TripleName
  300. << '\n';
  301. return;
  302. }
  303. if (CFG || !YAMLCFG.empty()) {
  304. std::unique_ptr<MCObjectDisassembler> OD(
  305. new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
  306. std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
  307. for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
  308. AE = Mod->atom_end();
  309. AI != AE; ++AI) {
  310. outs() << "Atom " << (*AI)->getName() << ": \n";
  311. if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
  312. for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
  313. II != IE;
  314. ++II) {
  315. IP->printInst(&II->Inst, outs(), "");
  316. outs() << "\n";
  317. }
  318. }
  319. }
  320. if (CFG) {
  321. for (MCModule::const_func_iterator FI = Mod->func_begin(),
  322. FE = Mod->func_end();
  323. FI != FE; ++FI) {
  324. static int filenum = 0;
  325. emitDOTFile((Twine((*FI)->getName()) + "_" +
  326. utostr(filenum) + ".dot").str().c_str(),
  327. **FI, IP.get());
  328. ++filenum;
  329. }
  330. }
  331. if (!YAMLCFG.empty()) {
  332. std::string Error;
  333. raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
  334. if (!Error.empty()) {
  335. errs() << ToolName << ": warning: " << Error << '\n';
  336. return;
  337. }
  338. mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
  339. }
  340. }
  341. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
  342. "\t\t\t%08" PRIx64 ": ";
  343. // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
  344. // in RelocSecs contain the relocations for section S.
  345. error_code EC;
  346. std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
  347. for (const SectionRef &Section : Obj->sections()) {
  348. section_iterator Sec2 = Section.getRelocatedSection();
  349. if (Sec2 != Obj->section_end())
  350. SectionRelocMap[*Sec2].push_back(Section);
  351. }
  352. for (const SectionRef &Section : Obj->sections()) {
  353. bool Text;
  354. if (error(Section.isText(Text)))
  355. break;
  356. if (!Text)
  357. continue;
  358. uint64_t SectionAddr;
  359. if (error(Section.getAddress(SectionAddr)))
  360. break;
  361. uint64_t SectSize;
  362. if (error(Section.getSize(SectSize)))
  363. break;
  364. // Make a list of all the symbols in this section.
  365. std::vector<std::pair<uint64_t, StringRef>> Symbols;
  366. for (const SymbolRef &Symbol : Obj->symbols()) {
  367. bool contains;
  368. if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
  369. uint64_t Address;
  370. if (error(Symbol.getAddress(Address)))
  371. break;
  372. if (Address == UnknownAddressOrSize)
  373. continue;
  374. Address -= SectionAddr;
  375. if (Address >= SectSize)
  376. continue;
  377. StringRef Name;
  378. if (error(Symbol.getName(Name)))
  379. break;
  380. Symbols.push_back(std::make_pair(Address, Name));
  381. }
  382. }
  383. // Sort the symbols by address, just in case they didn't come in that way.
  384. array_pod_sort(Symbols.begin(), Symbols.end());
  385. // Make a list of all the relocations for this section.
  386. std::vector<RelocationRef> Rels;
  387. if (InlineRelocs) {
  388. for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
  389. for (const RelocationRef &Reloc : RelocSec.relocations()) {
  390. Rels.push_back(Reloc);
  391. }
  392. }
  393. }
  394. // Sort relocations by address.
  395. std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
  396. StringRef SegmentName = "";
  397. if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
  398. DataRefImpl DR = Section.getRawDataRefImpl();
  399. SegmentName = MachO->getSectionFinalSegmentName(DR);
  400. }
  401. StringRef name;
  402. if (error(Section.getName(name)))
  403. break;
  404. outs() << "Disassembly of section ";
  405. if (!SegmentName.empty())
  406. outs() << SegmentName << ",";
  407. outs() << name << ':';
  408. // If the section has no symbols just insert a dummy one and disassemble
  409. // the whole section.
  410. if (Symbols.empty())
  411. Symbols.push_back(std::make_pair(0, name));
  412. SmallString<40> Comments;
  413. raw_svector_ostream CommentStream(Comments);
  414. StringRef Bytes;
  415. if (error(Section.getContents(Bytes)))
  416. break;
  417. StringRefMemoryObject memoryObject(Bytes, SectionAddr);
  418. uint64_t Size;
  419. uint64_t Index;
  420. std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
  421. std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
  422. // Disassemble symbol by symbol.
  423. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
  424. uint64_t Start = Symbols[si].first;
  425. uint64_t End;
  426. // The end is either the size of the section or the beginning of the next
  427. // symbol.
  428. if (si == se - 1)
  429. End = SectSize;
  430. // Make sure this symbol takes up space.
  431. else if (Symbols[si + 1].first != Start)
  432. End = Symbols[si + 1].first - 1;
  433. else
  434. // This symbol has the same address as the next symbol. Skip it.
  435. continue;
  436. outs() << '\n' << Symbols[si].second << ":\n";
  437. #ifndef NDEBUG
  438. raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
  439. #else
  440. raw_ostream &DebugOut = nulls();
  441. #endif
  442. for (Index = Start; Index < End; Index += Size) {
  443. MCInst Inst;
  444. if (DisAsm->getInstruction(Inst, Size, memoryObject,
  445. SectionAddr + Index,
  446. DebugOut, CommentStream)) {
  447. outs() << format("%8" PRIx64 ":", SectionAddr + Index);
  448. if (!NoShowRawInsn) {
  449. outs() << "\t";
  450. DumpBytes(StringRef(Bytes.data() + Index, Size));
  451. }
  452. IP->printInst(&Inst, outs(), "");
  453. outs() << CommentStream.str();
  454. Comments.clear();
  455. outs() << "\n";
  456. } else {
  457. errs() << ToolName << ": warning: invalid instruction encoding\n";
  458. if (Size == 0)
  459. Size = 1; // skip illegible bytes
  460. }
  461. // Print relocation for instruction.
  462. while (rel_cur != rel_end) {
  463. bool hidden = false;
  464. uint64_t addr;
  465. SmallString<16> name;
  466. SmallString<32> val;
  467. // If this relocation is hidden, skip it.
  468. if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
  469. if (hidden) goto skip_print_rel;
  470. if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
  471. // Stop when rel_cur's address is past the current instruction.
  472. if (addr >= Index + Size) break;
  473. if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
  474. if (error(rel_cur->getValueString(val))) goto skip_print_rel;
  475. outs() << format(Fmt.data(), SectionAddr + addr) << name
  476. << "\t" << val << "\n";
  477. skip_print_rel:
  478. ++rel_cur;
  479. }
  480. }
  481. }
  482. }
  483. }
  484. static void PrintRelocations(const ObjectFile *Obj) {
  485. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
  486. "%08" PRIx64;
  487. for (const SectionRef &Section : Obj->sections()) {
  488. if (Section.relocation_begin() == Section.relocation_end())
  489. continue;
  490. StringRef secname;
  491. if (error(Section.getName(secname)))
  492. continue;
  493. outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
  494. for (const RelocationRef &Reloc : Section.relocations()) {
  495. bool hidden;
  496. uint64_t address;
  497. SmallString<32> relocname;
  498. SmallString<32> valuestr;
  499. if (error(Reloc.getHidden(hidden)))
  500. continue;
  501. if (hidden)
  502. continue;
  503. if (error(Reloc.getTypeName(relocname)))
  504. continue;
  505. if (error(Reloc.getOffset(address)))
  506. continue;
  507. if (error(Reloc.getValueString(valuestr)))
  508. continue;
  509. outs() << format(Fmt.data(), address) << " " << relocname << " "
  510. << valuestr << "\n";
  511. }
  512. outs() << "\n";
  513. }
  514. }
  515. static void PrintSectionHeaders(const ObjectFile *Obj) {
  516. outs() << "Sections:\n"
  517. "Idx Name Size Address Type\n";
  518. unsigned i = 0;
  519. for (const SectionRef &Section : Obj->sections()) {
  520. StringRef Name;
  521. if (error(Section.getName(Name)))
  522. return;
  523. uint64_t Address;
  524. if (error(Section.getAddress(Address)))
  525. return;
  526. uint64_t Size;
  527. if (error(Section.getSize(Size)))
  528. return;
  529. bool Text, Data, BSS;
  530. if (error(Section.isText(Text)))
  531. return;
  532. if (error(Section.isData(Data)))
  533. return;
  534. if (error(Section.isBSS(BSS)))
  535. return;
  536. std::string Type = (std::string(Text ? "TEXT " : "") +
  537. (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
  538. outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
  539. Name.str().c_str(), Size, Address, Type.c_str());
  540. ++i;
  541. }
  542. }
  543. static void PrintSectionContents(const ObjectFile *Obj) {
  544. error_code EC;
  545. for (const SectionRef &Section : Obj->sections()) {
  546. StringRef Name;
  547. StringRef Contents;
  548. uint64_t BaseAddr;
  549. bool BSS;
  550. if (error(Section.getName(Name)))
  551. continue;
  552. if (error(Section.getContents(Contents)))
  553. continue;
  554. if (error(Section.getAddress(BaseAddr)))
  555. continue;
  556. if (error(Section.isBSS(BSS)))
  557. continue;
  558. outs() << "Contents of section " << Name << ":\n";
  559. if (BSS) {
  560. outs() << format("<skipping contents of bss section at [%04" PRIx64
  561. ", %04" PRIx64 ")>\n", BaseAddr,
  562. BaseAddr + Contents.size());
  563. continue;
  564. }
  565. // Dump out the content as hex and printable ascii characters.
  566. for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
  567. outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
  568. // Dump line of hex.
  569. for (std::size_t i = 0; i < 16; ++i) {
  570. if (i != 0 && i % 4 == 0)
  571. outs() << ' ';
  572. if (addr + i < end)
  573. outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
  574. << hexdigit(Contents[addr + i] & 0xF, true);
  575. else
  576. outs() << " ";
  577. }
  578. // Print ascii.
  579. outs() << " ";
  580. for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
  581. if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
  582. outs() << Contents[addr + i];
  583. else
  584. outs() << ".";
  585. }
  586. outs() << "\n";
  587. }
  588. }
  589. }
  590. static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
  591. const coff_file_header *header;
  592. if (error(coff->getHeader(header)))
  593. return;
  594. for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
  595. const coff_symbol *Symbol;
  596. StringRef Name;
  597. if (error(coff->getSymbol(SI, Symbol)))
  598. return;
  599. if (error(coff->getSymbolName(Symbol, Name)))
  600. return;
  601. outs() << "[" << format("%2d", SI) << "]"
  602. << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
  603. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  604. << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
  605. << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
  606. << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
  607. << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
  608. << Name << "\n";
  609. for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
  610. if (Symbol->isSectionDefinition()) {
  611. const coff_aux_section_definition *asd;
  612. if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
  613. return;
  614. outs() << "AUX "
  615. << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
  616. , unsigned(asd->Length)
  617. , unsigned(asd->NumberOfRelocations)
  618. , unsigned(asd->NumberOfLinenumbers)
  619. , unsigned(asd->CheckSum))
  620. << format("assoc %d comdat %d\n"
  621. , unsigned(asd->Number)
  622. , unsigned(asd->Selection));
  623. } else if (Symbol->isFileRecord()) {
  624. const coff_aux_file *AF;
  625. if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
  626. return;
  627. StringRef Name(AF->FileName,
  628. Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
  629. outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
  630. SI = SI + Symbol->NumberOfAuxSymbols;
  631. break;
  632. } else {
  633. outs() << "AUX Unknown\n";
  634. }
  635. }
  636. }
  637. }
  638. static void PrintSymbolTable(const ObjectFile *o) {
  639. outs() << "SYMBOL TABLE:\n";
  640. if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
  641. PrintCOFFSymbolTable(coff);
  642. return;
  643. }
  644. for (const SymbolRef &Symbol : o->symbols()) {
  645. StringRef Name;
  646. uint64_t Address;
  647. SymbolRef::Type Type;
  648. uint64_t Size;
  649. uint32_t Flags = Symbol.getFlags();
  650. section_iterator Section = o->section_end();
  651. if (error(Symbol.getName(Name)))
  652. continue;
  653. if (error(Symbol.getAddress(Address)))
  654. continue;
  655. if (error(Symbol.getType(Type)))
  656. continue;
  657. if (error(Symbol.getSize(Size)))
  658. continue;
  659. if (error(Symbol.getSection(Section)))
  660. continue;
  661. bool Global = Flags & SymbolRef::SF_Global;
  662. bool Weak = Flags & SymbolRef::SF_Weak;
  663. bool Absolute = Flags & SymbolRef::SF_Absolute;
  664. if (Address == UnknownAddressOrSize)
  665. Address = 0;
  666. if (Size == UnknownAddressOrSize)
  667. Size = 0;
  668. char GlobLoc = ' ';
  669. if (Type != SymbolRef::ST_Unknown)
  670. GlobLoc = Global ? 'g' : 'l';
  671. char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
  672. ? 'd' : ' ';
  673. char FileFunc = ' ';
  674. if (Type == SymbolRef::ST_File)
  675. FileFunc = 'f';
  676. else if (Type == SymbolRef::ST_Function)
  677. FileFunc = 'F';
  678. const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
  679. "%08" PRIx64;
  680. outs() << format(Fmt, Address) << " "
  681. << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
  682. << (Weak ? 'w' : ' ') // Weak?
  683. << ' ' // Constructor. Not supported yet.
  684. << ' ' // Warning. Not supported yet.
  685. << ' ' // Indirect reference to another symbol.
  686. << Debug // Debugging (d) or dynamic (D) symbol.
  687. << FileFunc // Name of function (F), file (f) or object (O).
  688. << ' ';
  689. if (Absolute) {
  690. outs() << "*ABS*";
  691. } else if (Section == o->section_end()) {
  692. outs() << "*UND*";
  693. } else {
  694. if (const MachOObjectFile *MachO =
  695. dyn_cast<const MachOObjectFile>(o)) {
  696. DataRefImpl DR = Section->getRawDataRefImpl();
  697. StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
  698. outs() << SegmentName << ",";
  699. }
  700. StringRef SectionName;
  701. if (error(Section->getName(SectionName)))
  702. SectionName = "";
  703. outs() << SectionName;
  704. }
  705. outs() << '\t'
  706. << format("%08" PRIx64 " ", Size)
  707. << Name
  708. << '\n';
  709. }
  710. }
  711. static void PrintUnwindInfo(const ObjectFile *o) {
  712. outs() << "Unwind info:\n\n";
  713. if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
  714. printCOFFUnwindInfo(coff);
  715. } else {
  716. // TODO: Extract DWARF dump tool to objdump.
  717. errs() << "This operation is only currently supported "
  718. "for COFF object files.\n";
  719. return;
  720. }
  721. }
  722. static void printPrivateFileHeader(const ObjectFile *o) {
  723. if (o->isELF()) {
  724. printELFFileHeader(o);
  725. } else if (o->isCOFF()) {
  726. printCOFFFileHeader(o);
  727. }
  728. }
  729. static void DumpObject(const ObjectFile *o) {
  730. outs() << '\n';
  731. outs() << o->getFileName()
  732. << ":\tfile format " << o->getFileFormatName() << "\n\n";
  733. if (Disassemble)
  734. DisassembleObject(o, Relocations);
  735. if (Relocations && !Disassemble)
  736. PrintRelocations(o);
  737. if (SectionHeaders)
  738. PrintSectionHeaders(o);
  739. if (SectionContents)
  740. PrintSectionContents(o);
  741. if (SymbolTable)
  742. PrintSymbolTable(o);
  743. if (UnwindInfo)
  744. PrintUnwindInfo(o);
  745. if (PrivateHeaders)
  746. printPrivateFileHeader(o);
  747. }
  748. /// @brief Dump each object file in \a a;
  749. static void DumpArchive(const Archive *a) {
  750. for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
  751. ++i) {
  752. std::unique_ptr<Binary> child;
  753. if (error_code EC = i->getAsBinary(child)) {
  754. // Ignore non-object files.
  755. if (EC != object_error::invalid_file_type)
  756. errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
  757. << ".\n";
  758. continue;
  759. }
  760. if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
  761. DumpObject(o);
  762. else
  763. errs() << ToolName << ": '" << a->getFileName() << "': "
  764. << "Unrecognized file type.\n";
  765. }
  766. }
  767. /// @brief Open file and figure out how to dump it.
  768. static void DumpInput(StringRef file) {
  769. // If file isn't stdin, check that it exists.
  770. if (file != "-" && !sys::fs::exists(file)) {
  771. errs() << ToolName << ": '" << file << "': " << "No such file\n";
  772. return;
  773. }
  774. if (MachOOpt && Disassemble) {
  775. DisassembleInputMachO(file);
  776. return;
  777. }
  778. // Attempt to open the binary.
  779. ErrorOr<Binary *> BinaryOrErr = createBinary(file);
  780. if (error_code EC = BinaryOrErr.getError()) {
  781. errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
  782. return;
  783. }
  784. std::unique_ptr<Binary> binary(BinaryOrErr.get());
  785. if (Archive *a = dyn_cast<Archive>(binary.get()))
  786. DumpArchive(a);
  787. else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
  788. DumpObject(o);
  789. else
  790. errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
  791. }
  792. int main(int argc, char **argv) {
  793. // Print a stack trace if we signal out.
  794. sys::PrintStackTraceOnErrorSignal();
  795. PrettyStackTraceProgram X(argc, argv);
  796. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  797. // Initialize targets and assembly printers/parsers.
  798. llvm::InitializeAllTargetInfos();
  799. llvm::InitializeAllTargetMCs();
  800. llvm::InitializeAllAsmParsers();
  801. llvm::InitializeAllDisassemblers();
  802. // Register the target printer for --version.
  803. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  804. cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
  805. TripleName = Triple::normalize(TripleName);
  806. ToolName = argv[0];
  807. // Defaults to a.out if no filenames specified.
  808. if (InputFilenames.size() == 0)
  809. InputFilenames.push_back("a.out");
  810. if (!Disassemble
  811. && !Relocations
  812. && !SectionHeaders
  813. && !SectionContents
  814. && !SymbolTable
  815. && !UnwindInfo
  816. && !PrivateHeaders) {
  817. cl::PrintHelpMessage();
  818. return 2;
  819. }
  820. std::for_each(InputFilenames.begin(), InputFilenames.end(),
  821. DumpInput);
  822. return 0;
  823. }