2
0

llvm-objdump.cpp 50 KB

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