llvm-objdump.cpp 46 KB

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