llvm-objdump.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. //===----------------------------------------------------------------------===//
  15. #include "llvm-objdump.h"
  16. #include "MCFunction.h"
  17. #include "llvm/ADT/OwningPtr.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/MC/MCAsmInfo.h"
  22. #include "llvm/MC/MCDisassembler.h"
  23. #include "llvm/MC/MCInst.h"
  24. #include "llvm/MC/MCInstPrinter.h"
  25. #include "llvm/MC/MCInstrInfo.h"
  26. #include "llvm/MC/MCRegisterInfo.h"
  27. #include "llvm/MC/MCSubtargetInfo.h"
  28. #include "llvm/Object/Archive.h"
  29. #include "llvm/Object/COFF.h"
  30. #include "llvm/Object/MachO.h"
  31. #include "llvm/Object/ObjectFile.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "llvm/Support/Format.h"
  37. #include "llvm/Support/GraphWriter.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/ManagedStatic.h"
  40. #include "llvm/Support/MemoryBuffer.h"
  41. #include "llvm/Support/MemoryObject.h"
  42. #include "llvm/Support/PrettyStackTrace.h"
  43. #include "llvm/Support/Signals.h"
  44. #include "llvm/Support/SourceMgr.h"
  45. #include "llvm/Support/TargetRegistry.h"
  46. #include "llvm/Support/TargetSelect.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Support/system_error.h"
  49. #include <algorithm>
  50. #include <cctype>
  51. #include <cstring>
  52. using namespace llvm;
  53. using namespace object;
  54. static cl::list<std::string>
  55. InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
  56. static cl::opt<bool>
  57. Disassemble("disassemble",
  58. cl::desc("Display assembler mnemonics for the machine instructions"));
  59. static cl::alias
  60. Disassembled("d", cl::desc("Alias for --disassemble"),
  61. cl::aliasopt(Disassemble));
  62. static cl::opt<bool>
  63. Relocations("r", cl::desc("Display the relocation entries in the file"));
  64. static cl::opt<bool>
  65. SectionContents("s", cl::desc("Display the content of each section"));
  66. static cl::opt<bool>
  67. SymbolTable("t", cl::desc("Display the symbol table"));
  68. static cl::opt<bool>
  69. MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
  70. static cl::alias
  71. MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
  72. cl::opt<std::string>
  73. llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
  74. "see -version for available targets"));
  75. cl::opt<std::string>
  76. llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
  77. "see -version for available targets"));
  78. static cl::opt<bool>
  79. SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
  80. "for each section."));
  81. static cl::alias
  82. SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
  83. cl::aliasopt(SectionHeaders));
  84. static cl::alias
  85. SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
  86. cl::aliasopt(SectionHeaders));
  87. static cl::list<std::string>
  88. MAttrs("mattr",
  89. cl::CommaSeparated,
  90. cl::desc("Target specific attributes"),
  91. cl::value_desc("a1,+a2,-a3,..."));
  92. static cl::opt<bool>
  93. NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
  94. "do not print the instruction bytes."));
  95. static cl::opt<bool>
  96. UnwindInfo("unwind-info", cl::desc("Display unwind information"));
  97. static cl::alias
  98. UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
  99. cl::aliasopt(UnwindInfo));
  100. static StringRef ToolName;
  101. bool llvm::error(error_code ec) {
  102. if (!ec) return false;
  103. outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
  104. outs().flush();
  105. return true;
  106. }
  107. static const Target *getTarget(const ObjectFile *Obj = NULL) {
  108. // Figure out the target triple.
  109. llvm::Triple TheTriple("unknown-unknown-unknown");
  110. if (TripleName.empty()) {
  111. if (Obj)
  112. TheTriple.setArch(Triple::ArchType(Obj->getArch()));
  113. } else
  114. TheTriple.setTriple(Triple::normalize(TripleName));
  115. // Get the target specific parser.
  116. std::string Error;
  117. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  118. Error);
  119. if (!TheTarget) {
  120. errs() << ToolName << ": " << Error;
  121. return 0;
  122. }
  123. // Update the triple name and return the found target.
  124. TripleName = TheTriple.getTriple();
  125. return TheTarget;
  126. }
  127. void llvm::StringRefMemoryObject::anchor() { }
  128. void llvm::DumpBytes(StringRef bytes) {
  129. static const char hex_rep[] = "0123456789abcdef";
  130. // FIXME: The real way to do this is to figure out the longest instruction
  131. // and align to that size before printing. I'll fix this when I get
  132. // around to outputting relocations.
  133. // 15 is the longest x86 instruction
  134. // 3 is for the hex rep of a byte + a space.
  135. // 1 is for the null terminator.
  136. enum { OutputSize = (15 * 3) + 1 };
  137. char output[OutputSize];
  138. assert(bytes.size() <= 15
  139. && "DumpBytes only supports instructions of up to 15 bytes");
  140. memset(output, ' ', sizeof(output));
  141. unsigned index = 0;
  142. for (StringRef::iterator i = bytes.begin(),
  143. e = bytes.end(); i != e; ++i) {
  144. output[index] = hex_rep[(*i & 0xF0) >> 4];
  145. output[index + 1] = hex_rep[*i & 0xF];
  146. index += 3;
  147. }
  148. output[sizeof(output) - 1] = 0;
  149. outs() << output;
  150. }
  151. bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
  152. uint64_t a_addr, b_addr;
  153. if (error(a.getAddress(a_addr))) return false;
  154. if (error(b.getAddress(b_addr))) return false;
  155. return a_addr < b_addr;
  156. }
  157. static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
  158. const Target *TheTarget = getTarget(Obj);
  159. // getTarget() will have already issued a diagnostic if necessary, so
  160. // just bail here if it failed.
  161. if (!TheTarget)
  162. return;
  163. // Package up features to be passed to target/subtarget
  164. std::string FeaturesStr;
  165. if (MAttrs.size()) {
  166. SubtargetFeatures Features;
  167. for (unsigned i = 0; i != MAttrs.size(); ++i)
  168. Features.AddFeature(MAttrs[i]);
  169. FeaturesStr = Features.getString();
  170. }
  171. error_code ec;
  172. for (section_iterator i = Obj->begin_sections(),
  173. e = Obj->end_sections();
  174. i != e; i.increment(ec)) {
  175. if (error(ec)) break;
  176. bool text;
  177. if (error(i->isText(text))) break;
  178. if (!text) continue;
  179. uint64_t SectionAddr;
  180. if (error(i->getAddress(SectionAddr))) break;
  181. // Make a list of all the symbols in this section.
  182. std::vector<std::pair<uint64_t, StringRef> > Symbols;
  183. for (symbol_iterator si = Obj->begin_symbols(),
  184. se = Obj->end_symbols();
  185. si != se; si.increment(ec)) {
  186. bool contains;
  187. if (!error(i->containsSymbol(*si, contains)) && contains) {
  188. uint64_t Address;
  189. if (error(si->getAddress(Address))) break;
  190. Address -= SectionAddr;
  191. StringRef Name;
  192. if (error(si->getName(Name))) break;
  193. Symbols.push_back(std::make_pair(Address, Name));
  194. }
  195. }
  196. // Sort the symbols by address, just in case they didn't come in that way.
  197. array_pod_sort(Symbols.begin(), Symbols.end());
  198. // Make a list of all the relocations for this section.
  199. std::vector<RelocationRef> Rels;
  200. if (InlineRelocs) {
  201. for (relocation_iterator ri = i->begin_relocations(),
  202. re = i->end_relocations();
  203. ri != re; ri.increment(ec)) {
  204. if (error(ec)) break;
  205. Rels.push_back(*ri);
  206. }
  207. }
  208. // Sort relocations by address.
  209. std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
  210. StringRef name;
  211. if (error(i->getName(name))) break;
  212. outs() << "Disassembly of section " << name << ':';
  213. // If the section has no symbols just insert a dummy one and disassemble
  214. // the whole section.
  215. if (Symbols.empty())
  216. Symbols.push_back(std::make_pair(0, name));
  217. // Set up disassembler.
  218. OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
  219. if (!AsmInfo) {
  220. errs() << "error: no assembly info for target " << TripleName << "\n";
  221. return;
  222. }
  223. OwningPtr<const MCSubtargetInfo> STI(
  224. TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
  225. if (!STI) {
  226. errs() << "error: no subtarget info for target " << TripleName << "\n";
  227. return;
  228. }
  229. OwningPtr<const MCDisassembler> DisAsm(
  230. TheTarget->createMCDisassembler(*STI));
  231. if (!DisAsm) {
  232. errs() << "error: no disassembler for target " << TripleName << "\n";
  233. return;
  234. }
  235. OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  236. if (!MRI) {
  237. errs() << "error: no register info for target " << TripleName << "\n";
  238. return;
  239. }
  240. OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  241. if (!MII) {
  242. errs() << "error: no instruction info for target " << TripleName << "\n";
  243. return;
  244. }
  245. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  246. OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  247. AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
  248. if (!IP) {
  249. errs() << "error: no instruction printer for target " << TripleName
  250. << '\n';
  251. return;
  252. }
  253. StringRef Bytes;
  254. if (error(i->getContents(Bytes))) break;
  255. StringRefMemoryObject memoryObject(Bytes);
  256. uint64_t Size;
  257. uint64_t Index;
  258. uint64_t SectSize;
  259. if (error(i->getSize(SectSize))) break;
  260. std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
  261. std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
  262. // Disassemble symbol by symbol.
  263. for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
  264. uint64_t Start = Symbols[si].first;
  265. uint64_t End;
  266. // The end is either the size of the section or the beginning of the next
  267. // symbol.
  268. if (si == se - 1)
  269. End = SectSize;
  270. // Make sure this symbol takes up space.
  271. else if (Symbols[si + 1].first != Start)
  272. End = Symbols[si + 1].first - 1;
  273. else
  274. // This symbol has the same address as the next symbol. Skip it.
  275. continue;
  276. outs() << '\n' << Symbols[si].second << ":\n";
  277. #ifndef NDEBUG
  278. raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
  279. #else
  280. raw_ostream &DebugOut = nulls();
  281. #endif
  282. for (Index = Start; Index < End; Index += Size) {
  283. MCInst Inst;
  284. if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
  285. DebugOut, nulls())) {
  286. outs() << format("%8" PRIx64 ":", SectionAddr + Index);
  287. if (!NoShowRawInsn) {
  288. outs() << "\t";
  289. DumpBytes(StringRef(Bytes.data() + Index, Size));
  290. }
  291. IP->printInst(&Inst, outs(), "");
  292. outs() << "\n";
  293. } else {
  294. errs() << ToolName << ": warning: invalid instruction encoding\n";
  295. if (Size == 0)
  296. Size = 1; // skip illegible bytes
  297. }
  298. // Print relocation for instruction.
  299. while (rel_cur != rel_end) {
  300. bool hidden = false;
  301. uint64_t addr;
  302. SmallString<16> name;
  303. SmallString<32> val;
  304. // If this relocation is hidden, skip it.
  305. if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
  306. if (hidden) goto skip_print_rel;
  307. if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
  308. // Stop when rel_cur's address is past the current instruction.
  309. if (addr >= Index + Size) break;
  310. if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
  311. if (error(rel_cur->getValueString(val))) goto skip_print_rel;
  312. outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
  313. << "\t" << val << "\n";
  314. skip_print_rel:
  315. ++rel_cur;
  316. }
  317. }
  318. }
  319. }
  320. }
  321. static void PrintRelocations(const ObjectFile *o) {
  322. error_code ec;
  323. for (section_iterator si = o->begin_sections(), se = o->end_sections();
  324. si != se; si.increment(ec)){
  325. if (error(ec)) return;
  326. if (si->begin_relocations() == si->end_relocations())
  327. continue;
  328. StringRef secname;
  329. if (error(si->getName(secname))) continue;
  330. outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
  331. for (relocation_iterator ri = si->begin_relocations(),
  332. re = si->end_relocations();
  333. ri != re; ri.increment(ec)) {
  334. if (error(ec)) return;
  335. bool hidden;
  336. uint64_t address;
  337. SmallString<32> relocname;
  338. SmallString<32> valuestr;
  339. if (error(ri->getHidden(hidden))) continue;
  340. if (hidden) continue;
  341. if (error(ri->getTypeName(relocname))) continue;
  342. if (error(ri->getAddress(address))) continue;
  343. if (error(ri->getValueString(valuestr))) continue;
  344. outs() << address << " " << relocname << " " << valuestr << "\n";
  345. }
  346. outs() << "\n";
  347. }
  348. }
  349. static void PrintSectionHeaders(const ObjectFile *o) {
  350. outs() << "Sections:\n"
  351. "Idx Name Size Address Type\n";
  352. error_code ec;
  353. unsigned i = 0;
  354. for (section_iterator si = o->begin_sections(), se = o->end_sections();
  355. si != se; si.increment(ec)) {
  356. if (error(ec)) return;
  357. StringRef Name;
  358. if (error(si->getName(Name))) return;
  359. uint64_t Address;
  360. if (error(si->getAddress(Address))) return;
  361. uint64_t Size;
  362. if (error(si->getSize(Size))) return;
  363. bool Text, Data, BSS;
  364. if (error(si->isText(Text))) return;
  365. if (error(si->isData(Data))) return;
  366. if (error(si->isBSS(BSS))) return;
  367. std::string Type = (std::string(Text ? "TEXT " : "") +
  368. (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
  369. outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
  370. i, Name.str().c_str(), Size, Address, Type.c_str());
  371. ++i;
  372. }
  373. }
  374. static void PrintSectionContents(const ObjectFile *o) {
  375. error_code ec;
  376. for (section_iterator si = o->begin_sections(),
  377. se = o->end_sections();
  378. si != se; si.increment(ec)) {
  379. if (error(ec)) return;
  380. StringRef Name;
  381. StringRef Contents;
  382. uint64_t BaseAddr;
  383. if (error(si->getName(Name))) continue;
  384. if (error(si->getContents(Contents))) continue;
  385. if (error(si->getAddress(BaseAddr))) continue;
  386. outs() << "Contents of section " << Name << ":\n";
  387. // Dump out the content as hex and printable ascii characters.
  388. for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
  389. outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
  390. // Dump line of hex.
  391. for (std::size_t i = 0; i < 16; ++i) {
  392. if (i != 0 && i % 4 == 0)
  393. outs() << ' ';
  394. if (addr + i < end)
  395. outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
  396. << hexdigit(Contents[addr + i] & 0xF, true);
  397. else
  398. outs() << " ";
  399. }
  400. // Print ascii.
  401. outs() << " ";
  402. for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
  403. if (std::isprint(Contents[addr + i] & 0xFF))
  404. outs() << Contents[addr + i];
  405. else
  406. outs() << ".";
  407. }
  408. outs() << "\n";
  409. }
  410. }
  411. }
  412. static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
  413. const coff_file_header *header;
  414. if (error(coff->getHeader(header))) return;
  415. int aux_count = 0;
  416. const coff_symbol *symbol = 0;
  417. for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
  418. if (aux_count--) {
  419. // Figure out which type of aux this is.
  420. if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
  421. && symbol->Value == 0) { // Section definition.
  422. const coff_aux_section_definition *asd;
  423. if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
  424. return;
  425. outs() << "AUX "
  426. << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
  427. , unsigned(asd->Length)
  428. , unsigned(asd->NumberOfRelocations)
  429. , unsigned(asd->NumberOfLinenumbers)
  430. , unsigned(asd->CheckSum))
  431. << format("assoc %d comdat %d\n"
  432. , unsigned(asd->Number)
  433. , unsigned(asd->Selection));
  434. } else
  435. outs() << "AUX Unknown\n";
  436. } else {
  437. StringRef name;
  438. if (error(coff->getSymbol(i, symbol))) return;
  439. if (error(coff->getSymbolName(symbol, name))) return;
  440. outs() << "[" << format("%2d", i) << "]"
  441. << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
  442. << "(fl 0x00)" // Flag bits, which COFF doesn't have.
  443. << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
  444. << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
  445. << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
  446. << "0x" << format("%08x", unsigned(symbol->Value)) << " "
  447. << name << "\n";
  448. aux_count = symbol->NumberOfAuxSymbols;
  449. }
  450. }
  451. }
  452. static void PrintSymbolTable(const ObjectFile *o) {
  453. outs() << "SYMBOL TABLE:\n";
  454. if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
  455. PrintCOFFSymbolTable(coff);
  456. else {
  457. error_code ec;
  458. for (symbol_iterator si = o->begin_symbols(),
  459. se = o->end_symbols(); si != se; si.increment(ec)) {
  460. if (error(ec)) return;
  461. StringRef Name;
  462. uint64_t Address;
  463. SymbolRef::Type Type;
  464. uint64_t Size;
  465. uint32_t Flags;
  466. section_iterator Section = o->end_sections();
  467. if (error(si->getName(Name))) continue;
  468. if (error(si->getAddress(Address))) continue;
  469. if (error(si->getFlags(Flags))) continue;
  470. if (error(si->getType(Type))) continue;
  471. if (error(si->getSize(Size))) continue;
  472. if (error(si->getSection(Section))) continue;
  473. bool Global = Flags & SymbolRef::SF_Global;
  474. bool Weak = Flags & SymbolRef::SF_Weak;
  475. bool Absolute = Flags & SymbolRef::SF_Absolute;
  476. if (Address == UnknownAddressOrSize)
  477. Address = 0;
  478. if (Size == UnknownAddressOrSize)
  479. Size = 0;
  480. char GlobLoc = ' ';
  481. if (Type != SymbolRef::ST_Unknown)
  482. GlobLoc = Global ? 'g' : 'l';
  483. char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
  484. ? 'd' : ' ';
  485. char FileFunc = ' ';
  486. if (Type == SymbolRef::ST_File)
  487. FileFunc = 'f';
  488. else if (Type == SymbolRef::ST_Function)
  489. FileFunc = 'F';
  490. outs() << format("%08" PRIx64, Address) << " "
  491. << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
  492. << (Weak ? 'w' : ' ') // Weak?
  493. << ' ' // Constructor. Not supported yet.
  494. << ' ' // Warning. Not supported yet.
  495. << ' ' // Indirect reference to another symbol.
  496. << Debug // Debugging (d) or dynamic (D) symbol.
  497. << FileFunc // Name of function (F), file (f) or object (O).
  498. << ' ';
  499. if (Absolute)
  500. outs() << "*ABS*";
  501. else if (Section == o->end_sections())
  502. outs() << "*UND*";
  503. else {
  504. if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
  505. StringRef SegmentName;
  506. DataRefImpl DR = Section->getRawDataRefImpl();
  507. if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
  508. SegmentName = "";
  509. outs() << SegmentName << ",";
  510. }
  511. StringRef SectionName;
  512. if (error(Section->getName(SectionName)))
  513. SectionName = "";
  514. outs() << SectionName;
  515. }
  516. outs() << '\t'
  517. << format("%08" PRIx64 " ", Size)
  518. << Name
  519. << '\n';
  520. }
  521. }
  522. }
  523. static void PrintUnwindInfo(const ObjectFile *o) {
  524. outs() << "Unwind info:\n\n";
  525. if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
  526. printCOFFUnwindInfo(coff);
  527. } else {
  528. // TODO: Extract DWARF dump tool to objdump.
  529. errs() << "This operation is only currently supported "
  530. "for COFF object files.\n";
  531. return;
  532. }
  533. }
  534. static void DumpObject(const ObjectFile *o) {
  535. outs() << '\n';
  536. outs() << o->getFileName()
  537. << ":\tfile format " << o->getFileFormatName() << "\n\n";
  538. if (Disassemble)
  539. DisassembleObject(o, Relocations);
  540. if (Relocations && !Disassemble)
  541. PrintRelocations(o);
  542. if (SectionHeaders)
  543. PrintSectionHeaders(o);
  544. if (SectionContents)
  545. PrintSectionContents(o);
  546. if (SymbolTable)
  547. PrintSymbolTable(o);
  548. if (UnwindInfo)
  549. PrintUnwindInfo(o);
  550. }
  551. /// @brief Dump each object file in \a a;
  552. static void DumpArchive(const Archive *a) {
  553. for (Archive::child_iterator i = a->begin_children(),
  554. e = a->end_children(); i != e; ++i) {
  555. OwningPtr<Binary> child;
  556. if (error_code ec = i->getAsBinary(child)) {
  557. // Ignore non-object files.
  558. if (ec != object_error::invalid_file_type)
  559. errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
  560. << ".\n";
  561. continue;
  562. }
  563. if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
  564. DumpObject(o);
  565. else
  566. errs() << ToolName << ": '" << a->getFileName() << "': "
  567. << "Unrecognized file type.\n";
  568. }
  569. }
  570. /// @brief Open file and figure out how to dump it.
  571. static void DumpInput(StringRef file) {
  572. // If file isn't stdin, check that it exists.
  573. if (file != "-" && !sys::fs::exists(file)) {
  574. errs() << ToolName << ": '" << file << "': " << "No such file\n";
  575. return;
  576. }
  577. if (MachOOpt && Disassemble) {
  578. DisassembleInputMachO(file);
  579. return;
  580. }
  581. // Attempt to open the binary.
  582. OwningPtr<Binary> binary;
  583. if (error_code ec = createBinary(file, binary)) {
  584. errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
  585. return;
  586. }
  587. if (Archive *a = dyn_cast<Archive>(binary.get()))
  588. DumpArchive(a);
  589. else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
  590. DumpObject(o);
  591. else
  592. errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
  593. }
  594. int main(int argc, char **argv) {
  595. // Print a stack trace if we signal out.
  596. sys::PrintStackTraceOnErrorSignal();
  597. PrettyStackTraceProgram X(argc, argv);
  598. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  599. // Initialize targets and assembly printers/parsers.
  600. llvm::InitializeAllTargetInfos();
  601. llvm::InitializeAllTargetMCs();
  602. llvm::InitializeAllAsmParsers();
  603. llvm::InitializeAllDisassemblers();
  604. // Register the target printer for --version.
  605. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  606. cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
  607. TripleName = Triple::normalize(TripleName);
  608. ToolName = argv[0];
  609. // Defaults to a.out if no filenames specified.
  610. if (InputFilenames.size() == 0)
  611. InputFilenames.push_back("a.out");
  612. if (!Disassemble
  613. && !Relocations
  614. && !SectionHeaders
  615. && !SectionContents
  616. && !SymbolTable
  617. && !UnwindInfo) {
  618. cl::PrintHelpMessage();
  619. return 2;
  620. }
  621. std::for_each(InputFilenames.begin(), InputFilenames.end(),
  622. DumpInput);
  623. return 0;
  624. }