llvm-objdump.cpp 53 KB

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