llvm-objdump.cpp 30 KB

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