llvm-objdump.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  1. //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This program is a utility that works like binutils "objdump", that is, it
  10. // dumps out a plethora of information about an object file depending on the
  11. // flags.
  12. //
  13. // The flags and output of this program should be near identical to those of
  14. // binutils objdump.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm-objdump.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringSet.h"
  22. #include "llvm/ADT/Triple.h"
  23. #include "llvm/CodeGen/FaultMaps.h"
  24. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  25. #include "llvm/DebugInfo/Symbolize/Symbolize.h"
  26. #include "llvm/Demangle/Demangle.h"
  27. #include "llvm/MC/MCAsmInfo.h"
  28. #include "llvm/MC/MCContext.h"
  29. #include "llvm/MC/MCDisassembler/MCDisassembler.h"
  30. #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
  31. #include "llvm/MC/MCInst.h"
  32. #include "llvm/MC/MCInstPrinter.h"
  33. #include "llvm/MC/MCInstrAnalysis.h"
  34. #include "llvm/MC/MCInstrInfo.h"
  35. #include "llvm/MC/MCObjectFileInfo.h"
  36. #include "llvm/MC/MCRegisterInfo.h"
  37. #include "llvm/MC/MCSubtargetInfo.h"
  38. #include "llvm/Object/Archive.h"
  39. #include "llvm/Object/COFF.h"
  40. #include "llvm/Object/COFFImportFile.h"
  41. #include "llvm/Object/ELFObjectFile.h"
  42. #include "llvm/Object/MachO.h"
  43. #include "llvm/Object/MachOUniversal.h"
  44. #include "llvm/Object/ObjectFile.h"
  45. #include "llvm/Object/Wasm.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/CommandLine.h"
  48. #include "llvm/Support/Debug.h"
  49. #include "llvm/Support/Errc.h"
  50. #include "llvm/Support/FileSystem.h"
  51. #include "llvm/Support/Format.h"
  52. #include "llvm/Support/GraphWriter.h"
  53. #include "llvm/Support/Host.h"
  54. #include "llvm/Support/InitLLVM.h"
  55. #include "llvm/Support/MemoryBuffer.h"
  56. #include "llvm/Support/SourceMgr.h"
  57. #include "llvm/Support/StringSaver.h"
  58. #include "llvm/Support/TargetRegistry.h"
  59. #include "llvm/Support/TargetSelect.h"
  60. #include "llvm/Support/WithColor.h"
  61. #include "llvm/Support/raw_ostream.h"
  62. #include <algorithm>
  63. #include <cctype>
  64. #include <cstring>
  65. #include <system_error>
  66. #include <unordered_map>
  67. #include <utility>
  68. using namespace llvm::object;
  69. namespace llvm {
  70. // MachO specific
  71. extern cl::opt<bool> Bind;
  72. extern cl::opt<bool> DataInCode;
  73. extern cl::opt<bool> DylibsUsed;
  74. extern cl::opt<bool> DylibId;
  75. extern cl::opt<bool> ExportsTrie;
  76. extern cl::opt<bool> FirstPrivateHeader;
  77. extern cl::opt<bool> IndirectSymbols;
  78. extern cl::opt<bool> InfoPlist;
  79. extern cl::opt<bool> LazyBind;
  80. extern cl::opt<bool> LinkOptHints;
  81. extern cl::opt<bool> ObjcMetaData;
  82. extern cl::opt<bool> Rebase;
  83. extern cl::opt<bool> UniversalHeaders;
  84. extern cl::opt<bool> WeakBind;
  85. static cl::opt<uint64_t> AdjustVMA(
  86. "adjust-vma",
  87. cl::desc("Increase the displayed address by the specified offset"),
  88. cl::value_desc("offset"), cl::init(0));
  89. static cl::opt<bool>
  90. AllHeaders("all-headers",
  91. cl::desc("Display all available header information"));
  92. static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
  93. cl::NotHidden, cl::Grouping,
  94. cl::aliasopt(AllHeaders));
  95. static cl::opt<std::string>
  96. ArchName("arch-name", cl::desc("Target arch to disassemble for, "
  97. "see -version for available targets"));
  98. cl::opt<bool> ArchiveHeaders("archive-headers",
  99. cl::desc("Display archive header information"));
  100. static cl::alias ArchiveHeadersShort("a",
  101. cl::desc("Alias for --archive-headers"),
  102. cl::NotHidden, cl::Grouping,
  103. cl::aliasopt(ArchiveHeaders));
  104. cl::opt<bool> Demangle("demangle", cl::desc("Demangle symbols names"),
  105. cl::init(false));
  106. static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
  107. cl::NotHidden, cl::Grouping,
  108. cl::aliasopt(Demangle));
  109. cl::opt<bool> Disassemble(
  110. "disassemble",
  111. cl::desc("Display assembler mnemonics for the machine instructions"));
  112. static cl::alias DisassembleShort("d", cl::desc("Alias for --disassemble"),
  113. cl::NotHidden, cl::Grouping,
  114. cl::aliasopt(Disassemble));
  115. cl::opt<bool> DisassembleAll(
  116. "disassemble-all",
  117. cl::desc("Display assembler mnemonics for the machine instructions"));
  118. static cl::alias DisassembleAllShort("D",
  119. cl::desc("Alias for --disassemble-all"),
  120. cl::NotHidden, cl::Grouping,
  121. cl::aliasopt(DisassembleAll));
  122. static cl::list<std::string>
  123. DisassembleFunctions("disassemble-functions",
  124. cl::CommaSeparated,
  125. cl::desc("List of functions to disassemble"));
  126. static cl::opt<bool> DisassembleZeroes(
  127. "disassemble-zeroes",
  128. cl::desc("Do not skip blocks of zeroes when disassembling"));
  129. static cl::alias
  130. DisassembleZeroesShort("z", cl::desc("Alias for --disassemble-zeroes"),
  131. cl::NotHidden, cl::Grouping,
  132. cl::aliasopt(DisassembleZeroes));
  133. static cl::list<std::string>
  134. DisassemblerOptions("disassembler-options",
  135. cl::desc("Pass target specific disassembler options"),
  136. cl::value_desc("options"), cl::CommaSeparated);
  137. static cl::alias
  138. DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"),
  139. cl::NotHidden, cl::Grouping, cl::Prefix,
  140. cl::CommaSeparated,
  141. cl::aliasopt(DisassemblerOptions));
  142. cl::opt<DIDumpType> DwarfDumpType(
  143. "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
  144. cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
  145. static cl::opt<bool> DynamicRelocations(
  146. "dynamic-reloc",
  147. cl::desc("Display the dynamic relocation entries in the file"));
  148. static cl::alias DynamicRelocationShort("R",
  149. cl::desc("Alias for --dynamic-reloc"),
  150. cl::NotHidden, cl::Grouping,
  151. cl::aliasopt(DynamicRelocations));
  152. static cl::opt<bool>
  153. FaultMapSection("fault-map-section",
  154. cl::desc("Display contents of faultmap section"));
  155. static cl::opt<bool>
  156. FileHeaders("file-headers",
  157. cl::desc("Display the contents of the overall file header"));
  158. static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
  159. cl::NotHidden, cl::Grouping,
  160. cl::aliasopt(FileHeaders));
  161. cl::opt<bool> SectionContents("full-contents",
  162. cl::desc("Display the content of each section"));
  163. static cl::alias SectionContentsShort("s",
  164. cl::desc("Alias for --full-contents"),
  165. cl::NotHidden, cl::Grouping,
  166. cl::aliasopt(SectionContents));
  167. static cl::list<std::string>
  168. InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
  169. static cl::opt<bool>
  170. PrintLines("line-numbers",
  171. cl::desc("Display source line numbers with "
  172. "disassembly. Implies disassemble object"));
  173. static cl::alias PrintLinesShort("l", cl::desc("Alias for --line-numbers"),
  174. cl::NotHidden, cl::Grouping,
  175. cl::aliasopt(PrintLines));
  176. static cl::opt<bool>
  177. MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
  178. static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
  179. cl::Grouping, cl::aliasopt(MachOOpt));
  180. cl::opt<std::string>
  181. MCPU("mcpu",
  182. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  183. cl::value_desc("cpu-name"), cl::init(""));
  184. cl::list<std::string> MAttrs("mattr", cl::CommaSeparated,
  185. cl::desc("Target specific attributes"),
  186. cl::value_desc("a1,+a2,-a3,..."));
  187. cl::opt<bool> NoShowRawInsn("no-show-raw-insn",
  188. cl::desc("When disassembling "
  189. "instructions, do not print "
  190. "the instruction bytes."));
  191. cl::opt<bool> NoLeadingAddr("no-leading-addr",
  192. cl::desc("Print no leading address"));
  193. static cl::opt<bool> RawClangAST(
  194. "raw-clang-ast",
  195. cl::desc("Dump the raw binary contents of the clang AST section"));
  196. cl::opt<bool>
  197. Relocations("reloc",
  198. cl::desc("Display the relocation entries in the file"));
  199. static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
  200. cl::NotHidden, cl::Grouping,
  201. cl::aliasopt(Relocations));
  202. cl::opt<bool>
  203. PrintImmHex("print-imm-hex",
  204. cl::desc("Use hex format for immediate values"));
  205. cl::opt<bool>
  206. PrivateHeaders("private-headers",
  207. cl::desc("Display format specific file headers"));
  208. static cl::alias PrivateHeadersShort("p",
  209. cl::desc("Alias for --private-headers"),
  210. cl::NotHidden, cl::Grouping,
  211. cl::aliasopt(PrivateHeaders));
  212. cl::list<std::string>
  213. FilterSections("section",
  214. cl::desc("Operate on the specified sections only. "
  215. "With -macho dump segment,section"));
  216. static cl::alias FilterSectionsj("j", cl::desc("Alias for --section"),
  217. cl::NotHidden, cl::Grouping, cl::Prefix,
  218. cl::aliasopt(FilterSections));
  219. cl::opt<bool> SectionHeaders("section-headers",
  220. cl::desc("Display summaries of the "
  221. "headers for each section."));
  222. static cl::alias SectionHeadersShort("headers",
  223. cl::desc("Alias for --section-headers"),
  224. cl::NotHidden,
  225. cl::aliasopt(SectionHeaders));
  226. static cl::alias SectionHeadersShorter("h",
  227. cl::desc("Alias for --section-headers"),
  228. cl::NotHidden, cl::Grouping,
  229. cl::aliasopt(SectionHeaders));
  230. static cl::opt<bool>
  231. ShowLMA("show-lma",
  232. cl::desc("Display LMA column when dumping ELF section headers"));
  233. static cl::opt<bool> PrintSource(
  234. "source",
  235. cl::desc(
  236. "Display source inlined with disassembly. Implies disassemble object"));
  237. static cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
  238. cl::NotHidden, cl::Grouping,
  239. cl::aliasopt(PrintSource));
  240. static cl::opt<uint64_t>
  241. StartAddress("start-address", cl::desc("Disassemble beginning at address"),
  242. cl::value_desc("address"), cl::init(0));
  243. static cl::opt<uint64_t> StopAddress("stop-address",
  244. cl::desc("Stop disassembly at address"),
  245. cl::value_desc("address"),
  246. cl::init(UINT64_MAX));
  247. cl::opt<bool> SymbolTable("syms", cl::desc("Display the symbol table"));
  248. static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
  249. cl::NotHidden, cl::Grouping,
  250. cl::aliasopt(SymbolTable));
  251. cl::opt<std::string> TripleName("triple",
  252. cl::desc("Target triple to disassemble for, "
  253. "see -version for available targets"));
  254. cl::opt<bool> UnwindInfo("unwind-info",
  255. cl::desc("Display unwind information"));
  256. static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
  257. cl::NotHidden, cl::Grouping,
  258. cl::aliasopt(UnwindInfo));
  259. static cl::opt<bool>
  260. Wide("wide", cl::desc("Ignored for compatibility with GNU objdump"));
  261. static cl::alias WideShort("w", cl::Grouping, cl::aliasopt(Wide));
  262. static StringSet<> DisasmFuncsSet;
  263. static StringRef ToolName;
  264. typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
  265. SectionFilter ToolSectionFilter(object::ObjectFile const &O) {
  266. return SectionFilter(
  267. [](object::SectionRef const &S) {
  268. if (FilterSections.empty())
  269. return true;
  270. StringRef String;
  271. std::error_code error = S.getName(String);
  272. if (error)
  273. return false;
  274. return is_contained(FilterSections, String);
  275. },
  276. O);
  277. }
  278. void error(std::error_code EC) {
  279. if (!EC)
  280. return;
  281. WithColor::error(errs(), ToolName)
  282. << "reading file: " << EC.message() << ".\n";
  283. errs().flush();
  284. exit(1);
  285. }
  286. void error(Error E) {
  287. if (!E)
  288. return;
  289. WithColor::error(errs(), ToolName) << toString(std::move(E));
  290. exit(1);
  291. }
  292. LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
  293. WithColor::error(errs(), ToolName) << Message << ".\n";
  294. errs().flush();
  295. exit(1);
  296. }
  297. void warn(StringRef Message) {
  298. WithColor::warning(errs(), ToolName) << Message << ".\n";
  299. errs().flush();
  300. }
  301. LLVM_ATTRIBUTE_NORETURN void report_error(StringRef File, Twine Message) {
  302. WithColor::error(errs(), ToolName)
  303. << "'" << File << "': " << Message << ".\n";
  304. exit(1);
  305. }
  306. LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef File) {
  307. assert(E);
  308. std::string Buf;
  309. raw_string_ostream OS(Buf);
  310. logAllUnhandledErrors(std::move(E), OS);
  311. OS.flush();
  312. WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
  313. exit(1);
  314. }
  315. LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
  316. StringRef FileName,
  317. StringRef ArchitectureName) {
  318. assert(E);
  319. WithColor::error(errs(), ToolName);
  320. if (ArchiveName != "")
  321. errs() << ArchiveName << "(" << FileName << ")";
  322. else
  323. errs() << "'" << FileName << "'";
  324. if (!ArchitectureName.empty())
  325. errs() << " (for architecture " << ArchitectureName << ")";
  326. std::string Buf;
  327. raw_string_ostream OS(Buf);
  328. logAllUnhandledErrors(std::move(E), OS);
  329. OS.flush();
  330. errs() << ": " << Buf;
  331. exit(1);
  332. }
  333. LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
  334. const object::Archive::Child &C,
  335. StringRef ArchitectureName) {
  336. Expected<StringRef> NameOrErr = C.getName();
  337. // TODO: if we have a error getting the name then it would be nice to print
  338. // the index of which archive member this is and or its offset in the
  339. // archive instead of "???" as the name.
  340. if (!NameOrErr) {
  341. consumeError(NameOrErr.takeError());
  342. report_error(std::move(E), ArchiveName, "???", ArchitectureName);
  343. } else
  344. report_error(std::move(E), ArchiveName, NameOrErr.get(), ArchitectureName);
  345. }
  346. static const Target *getTarget(const ObjectFile *Obj = nullptr) {
  347. // Figure out the target triple.
  348. Triple TheTriple("unknown-unknown-unknown");
  349. if (TripleName.empty()) {
  350. if (Obj)
  351. TheTriple = Obj->makeTriple();
  352. } else {
  353. TheTriple.setTriple(Triple::normalize(TripleName));
  354. // Use the triple, but also try to combine with ARM build attributes.
  355. if (Obj) {
  356. auto Arch = Obj->getArch();
  357. if (Arch == Triple::arm || Arch == Triple::armeb)
  358. Obj->setARMSubArch(TheTriple);
  359. }
  360. }
  361. // Get the target specific parser.
  362. std::string Error;
  363. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  364. Error);
  365. if (!TheTarget) {
  366. if (Obj)
  367. report_error(Obj->getFileName(), "can't find target: " + Error);
  368. else
  369. error("can't find target: " + Error);
  370. }
  371. // Update the triple name and return the found target.
  372. TripleName = TheTriple.getTriple();
  373. return TheTarget;
  374. }
  375. bool isRelocAddressLess(RelocationRef A, RelocationRef B) {
  376. return A.getOffset() < B.getOffset();
  377. }
  378. static Error getRelocationValueString(const RelocationRef &Rel,
  379. SmallVectorImpl<char> &Result) {
  380. const ObjectFile *Obj = Rel.getObject();
  381. if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
  382. return getELFRelocationValueString(ELF, Rel, Result);
  383. if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
  384. return getCOFFRelocationValueString(COFF, Rel, Result);
  385. if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
  386. return getWasmRelocationValueString(Wasm, Rel, Result);
  387. if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
  388. return getMachORelocationValueString(MachO, Rel, Result);
  389. llvm_unreachable("unknown object file format");
  390. }
  391. /// Indicates whether this relocation should hidden when listing
  392. /// relocations, usually because it is the trailing part of a multipart
  393. /// relocation that will be printed as part of the leading relocation.
  394. static bool getHidden(RelocationRef RelRef) {
  395. auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
  396. if (!MachO)
  397. return false;
  398. unsigned Arch = MachO->getArch();
  399. DataRefImpl Rel = RelRef.getRawDataRefImpl();
  400. uint64_t Type = MachO->getRelocationType(Rel);
  401. // On arches that use the generic relocations, GENERIC_RELOC_PAIR
  402. // is always hidden.
  403. if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
  404. return Type == MachO::GENERIC_RELOC_PAIR;
  405. if (Arch == Triple::x86_64) {
  406. // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
  407. // an X86_64_RELOC_SUBTRACTOR.
  408. if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
  409. DataRefImpl RelPrev = Rel;
  410. RelPrev.d.a--;
  411. uint64_t PrevType = MachO->getRelocationType(RelPrev);
  412. if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
  413. return true;
  414. }
  415. }
  416. return false;
  417. }
  418. namespace {
  419. class SourcePrinter {
  420. protected:
  421. DILineInfo OldLineInfo;
  422. const ObjectFile *Obj = nullptr;
  423. std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
  424. // File name to file contents of source
  425. std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
  426. // Mark the line endings of the cached source
  427. std::unordered_map<std::string, std::vector<StringRef>> LineCache;
  428. private:
  429. bool cacheSource(const DILineInfo& LineInfoFile);
  430. public:
  431. SourcePrinter() = default;
  432. SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
  433. symbolize::LLVMSymbolizer::Options SymbolizerOpts(
  434. DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
  435. DefaultArch);
  436. Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
  437. }
  438. virtual ~SourcePrinter() = default;
  439. virtual void printSourceLine(raw_ostream &OS,
  440. object::SectionedAddress Address,
  441. StringRef Delimiter = "; ");
  442. };
  443. bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
  444. std::unique_ptr<MemoryBuffer> Buffer;
  445. if (LineInfo.Source) {
  446. Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
  447. } else {
  448. auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
  449. if (!BufferOrError)
  450. return false;
  451. Buffer = std::move(*BufferOrError);
  452. }
  453. // Chomp the file to get lines
  454. const char *BufferStart = Buffer->getBufferStart(),
  455. *BufferEnd = Buffer->getBufferEnd();
  456. std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
  457. const char *Start = BufferStart;
  458. for (const char *I = BufferStart; I != BufferEnd; ++I)
  459. if (*I == '\n') {
  460. Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r'));
  461. Start = I + 1;
  462. }
  463. if (Start < BufferEnd)
  464. Lines.emplace_back(Start, BufferEnd - Start);
  465. SourceCache[LineInfo.FileName] = std::move(Buffer);
  466. return true;
  467. }
  468. void SourcePrinter::printSourceLine(raw_ostream &OS,
  469. object::SectionedAddress Address,
  470. StringRef Delimiter) {
  471. if (!Symbolizer)
  472. return;
  473. DILineInfo LineInfo = DILineInfo();
  474. auto ExpectedLineInfo =
  475. Symbolizer->symbolizeCode(Obj->getFileName(), Address);
  476. if (!ExpectedLineInfo)
  477. consumeError(ExpectedLineInfo.takeError());
  478. else
  479. LineInfo = *ExpectedLineInfo;
  480. if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
  481. LineInfo.Line == 0)
  482. return;
  483. if (PrintLines)
  484. OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
  485. if (PrintSource) {
  486. if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
  487. if (!cacheSource(LineInfo))
  488. return;
  489. auto LineBuffer = LineCache.find(LineInfo.FileName);
  490. if (LineBuffer != LineCache.end()) {
  491. if (LineInfo.Line > LineBuffer->second.size())
  492. return;
  493. // Vector begins at 0, line numbers are non-zero
  494. OS << Delimiter << LineBuffer->second[LineInfo.Line - 1] << '\n';
  495. }
  496. }
  497. OldLineInfo = LineInfo;
  498. }
  499. static bool isArmElf(const ObjectFile *Obj) {
  500. return (Obj->isELF() &&
  501. (Obj->getArch() == Triple::aarch64 ||
  502. Obj->getArch() == Triple::aarch64_be ||
  503. Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
  504. Obj->getArch() == Triple::thumb ||
  505. Obj->getArch() == Triple::thumbeb));
  506. }
  507. static void printRelocation(const RelocationRef &Rel, uint64_t Address,
  508. uint8_t AddrSize) {
  509. StringRef Fmt =
  510. AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
  511. SmallString<16> Name;
  512. SmallString<32> Val;
  513. Rel.getTypeName(Name);
  514. error(getRelocationValueString(Rel, Val));
  515. outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
  516. }
  517. class PrettyPrinter {
  518. public:
  519. virtual ~PrettyPrinter() = default;
  520. virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
  521. ArrayRef<uint8_t> Bytes,
  522. object::SectionedAddress Address, raw_ostream &OS,
  523. StringRef Annot, MCSubtargetInfo const &STI,
  524. SourcePrinter *SP,
  525. std::vector<RelocationRef> *Rels = nullptr) {
  526. if (SP && (PrintSource || PrintLines))
  527. SP->printSourceLine(OS, Address);
  528. {
  529. formatted_raw_ostream FOS(OS);
  530. if (!NoLeadingAddr)
  531. FOS << format("%8" PRIx64 ":", Address.Address);
  532. if (!NoShowRawInsn) {
  533. FOS << ' ';
  534. dumpBytes(Bytes, FOS);
  535. }
  536. FOS.flush();
  537. // The output of printInst starts with a tab. Print some spaces so that
  538. // the tab has 1 column and advances to the target tab stop.
  539. unsigned TabStop = NoShowRawInsn ? 16 : 40;
  540. unsigned Column = FOS.getColumn();
  541. FOS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
  542. // The dtor calls flush() to ensure the indent comes before printInst().
  543. }
  544. if (MI)
  545. IP.printInst(MI, OS, "", STI);
  546. else
  547. OS << "\t<unknown>";
  548. }
  549. };
  550. PrettyPrinter PrettyPrinterInst;
  551. class HexagonPrettyPrinter : public PrettyPrinter {
  552. public:
  553. void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
  554. raw_ostream &OS) {
  555. uint32_t opcode =
  556. (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
  557. if (!NoLeadingAddr)
  558. OS << format("%8" PRIx64 ":", Address);
  559. if (!NoShowRawInsn) {
  560. OS << "\t";
  561. dumpBytes(Bytes.slice(0, 4), OS);
  562. OS << format("\t%08" PRIx32, opcode);
  563. }
  564. }
  565. void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
  566. object::SectionedAddress Address, raw_ostream &OS,
  567. StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
  568. std::vector<RelocationRef> *Rels) override {
  569. if (SP && (PrintSource || PrintLines))
  570. SP->printSourceLine(OS, Address, "");
  571. if (!MI) {
  572. printLead(Bytes, Address.Address, OS);
  573. OS << " <unknown>";
  574. return;
  575. }
  576. std::string Buffer;
  577. {
  578. raw_string_ostream TempStream(Buffer);
  579. IP.printInst(MI, TempStream, "", STI);
  580. }
  581. StringRef Contents(Buffer);
  582. // Split off bundle attributes
  583. auto PacketBundle = Contents.rsplit('\n');
  584. // Split off first instruction from the rest
  585. auto HeadTail = PacketBundle.first.split('\n');
  586. auto Preamble = " { ";
  587. auto Separator = "";
  588. // Hexagon's packets require relocations to be inline rather than
  589. // clustered at the end of the packet.
  590. std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
  591. std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
  592. auto PrintReloc = [&]() -> void {
  593. while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
  594. if (RelCur->getOffset() == Address.Address) {
  595. printRelocation(*RelCur, Address.Address, 4);
  596. return;
  597. }
  598. ++RelCur;
  599. }
  600. };
  601. while (!HeadTail.first.empty()) {
  602. OS << Separator;
  603. Separator = "\n";
  604. if (SP && (PrintSource || PrintLines))
  605. SP->printSourceLine(OS, Address, "");
  606. printLead(Bytes, Address.Address, OS);
  607. OS << Preamble;
  608. Preamble = " ";
  609. StringRef Inst;
  610. auto Duplex = HeadTail.first.split('\v');
  611. if (!Duplex.second.empty()) {
  612. OS << Duplex.first;
  613. OS << "; ";
  614. Inst = Duplex.second;
  615. }
  616. else
  617. Inst = HeadTail.first;
  618. OS << Inst;
  619. HeadTail = HeadTail.second.split('\n');
  620. if (HeadTail.first.empty())
  621. OS << " } " << PacketBundle.second;
  622. PrintReloc();
  623. Bytes = Bytes.slice(4);
  624. Address.Address += 4;
  625. }
  626. }
  627. };
  628. HexagonPrettyPrinter HexagonPrettyPrinterInst;
  629. class AMDGCNPrettyPrinter : public PrettyPrinter {
  630. public:
  631. void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
  632. object::SectionedAddress Address, raw_ostream &OS,
  633. StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
  634. std::vector<RelocationRef> *Rels) override {
  635. if (SP && (PrintSource || PrintLines))
  636. SP->printSourceLine(OS, Address);
  637. typedef support::ulittle32_t U32;
  638. if (MI) {
  639. SmallString<40> InstStr;
  640. raw_svector_ostream IS(InstStr);
  641. IP.printInst(MI, IS, "", STI);
  642. OS << left_justify(IS.str(), 60);
  643. } else {
  644. // an unrecognized encoding - this is probably data so represent it
  645. // using the .long directive, or .byte directive if fewer than 4 bytes
  646. // remaining
  647. if (Bytes.size() >= 4) {
  648. OS << format("\t.long 0x%08" PRIx32 " ",
  649. static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
  650. OS.indent(42);
  651. } else {
  652. OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
  653. for (unsigned int i = 1; i < Bytes.size(); i++)
  654. OS << format(", 0x%02" PRIx8, Bytes[i]);
  655. OS.indent(55 - (6 * Bytes.size()));
  656. }
  657. }
  658. OS << format("// %012" PRIX64 ": ", Address.Address);
  659. if (Bytes.size() >=4) {
  660. for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
  661. Bytes.size() / sizeof(U32)))
  662. // D should be explicitly casted to uint32_t here as it is passed
  663. // by format to snprintf as vararg.
  664. OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
  665. } else {
  666. for (unsigned int i = 0; i < Bytes.size(); i++)
  667. OS << format("%02" PRIX8 " ", Bytes[i]);
  668. }
  669. if (!Annot.empty())
  670. OS << "// " << Annot;
  671. }
  672. };
  673. AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
  674. class BPFPrettyPrinter : public PrettyPrinter {
  675. public:
  676. void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
  677. object::SectionedAddress Address, raw_ostream &OS,
  678. StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
  679. std::vector<RelocationRef> *Rels) override {
  680. if (SP && (PrintSource || PrintLines))
  681. SP->printSourceLine(OS, Address);
  682. if (!NoLeadingAddr)
  683. OS << format("%8" PRId64 ":", Address.Address / 8);
  684. if (!NoShowRawInsn) {
  685. OS << "\t";
  686. dumpBytes(Bytes, OS);
  687. }
  688. if (MI)
  689. IP.printInst(MI, OS, "", STI);
  690. else
  691. OS << "\t<unknown>";
  692. }
  693. };
  694. BPFPrettyPrinter BPFPrettyPrinterInst;
  695. PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
  696. switch(Triple.getArch()) {
  697. default:
  698. return PrettyPrinterInst;
  699. case Triple::hexagon:
  700. return HexagonPrettyPrinterInst;
  701. case Triple::amdgcn:
  702. return AMDGCNPrettyPrinterInst;
  703. case Triple::bpfel:
  704. case Triple::bpfeb:
  705. return BPFPrettyPrinterInst;
  706. }
  707. }
  708. }
  709. static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
  710. assert(Obj->isELF());
  711. if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
  712. return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
  713. if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
  714. return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
  715. if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
  716. return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
  717. if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
  718. return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
  719. llvm_unreachable("Unsupported binary format");
  720. }
  721. template <class ELFT> static void
  722. addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
  723. std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
  724. for (auto Symbol : Obj->getDynamicSymbolIterators()) {
  725. uint8_t SymbolType = Symbol.getELFType();
  726. if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
  727. continue;
  728. uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName());
  729. StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
  730. if (Name.empty())
  731. continue;
  732. section_iterator SecI =
  733. unwrapOrError(Symbol.getSection(), Obj->getFileName());
  734. if (SecI == Obj->section_end())
  735. continue;
  736. AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
  737. }
  738. }
  739. static void
  740. addDynamicElfSymbols(const ObjectFile *Obj,
  741. std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
  742. assert(Obj->isELF());
  743. if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
  744. addDynamicElfSymbols(Elf32LEObj, AllSymbols);
  745. else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
  746. addDynamicElfSymbols(Elf64LEObj, AllSymbols);
  747. else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
  748. addDynamicElfSymbols(Elf32BEObj, AllSymbols);
  749. else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
  750. addDynamicElfSymbols(Elf64BEObj, AllSymbols);
  751. else
  752. llvm_unreachable("Unsupported binary format");
  753. }
  754. static void addPltEntries(const ObjectFile *Obj,
  755. std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
  756. StringSaver &Saver) {
  757. Optional<SectionRef> Plt = None;
  758. for (const SectionRef &Section : Obj->sections()) {
  759. StringRef Name;
  760. if (Section.getName(Name))
  761. continue;
  762. if (Name == ".plt")
  763. Plt = Section;
  764. }
  765. if (!Plt)
  766. return;
  767. if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
  768. for (auto PltEntry : ElfObj->getPltAddresses()) {
  769. SymbolRef Symbol(PltEntry.first, ElfObj);
  770. uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
  771. StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
  772. if (!Name.empty())
  773. AllSymbols[*Plt].emplace_back(
  774. PltEntry.second, Saver.save((Name + "@plt").str()), SymbolType);
  775. }
  776. }
  777. }
  778. // Normally the disassembly output will skip blocks of zeroes. This function
  779. // returns the number of zero bytes that can be skipped when dumping the
  780. // disassembly of the instructions in Buf.
  781. static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
  782. // Find the number of leading zeroes.
  783. size_t N = 0;
  784. while (N < Buf.size() && !Buf[N])
  785. ++N;
  786. // We may want to skip blocks of zero bytes, but unless we see
  787. // at least 8 of them in a row.
  788. if (N < 8)
  789. return 0;
  790. // We skip zeroes in multiples of 4 because do not want to truncate an
  791. // instruction if it starts with a zero byte.
  792. return N & ~0x3;
  793. }
  794. // Returns a map from sections to their relocations.
  795. static std::map<SectionRef, std::vector<RelocationRef>>
  796. getRelocsMap(object::ObjectFile const &Obj) {
  797. std::map<SectionRef, std::vector<RelocationRef>> Ret;
  798. for (const SectionRef &Section : ToolSectionFilter(Obj)) {
  799. section_iterator RelSec = Section.getRelocatedSection();
  800. if (RelSec == Obj.section_end())
  801. continue;
  802. std::vector<RelocationRef> &V = Ret[*RelSec];
  803. for (const RelocationRef &R : Section.relocations())
  804. V.push_back(R);
  805. // Sort relocations by address.
  806. llvm::sort(V, isRelocAddressLess);
  807. }
  808. return Ret;
  809. }
  810. // Used for --adjust-vma to check if address should be adjusted by the
  811. // specified value for a given section.
  812. // For ELF we do not adjust non-allocatable sections like debug ones,
  813. // because they are not loadable.
  814. // TODO: implement for other file formats.
  815. static bool shouldAdjustVA(const SectionRef &Section) {
  816. const ObjectFile *Obj = Section.getObject();
  817. if (isa<object::ELFObjectFileBase>(Obj))
  818. return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
  819. return false;
  820. }
  821. static uint64_t
  822. dumpARMELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
  823. const ObjectFile *Obj, ArrayRef<uint8_t> Bytes,
  824. const std::vector<uint64_t> &TextMappingSymsAddr) {
  825. support::endianness Endian =
  826. Obj->isLittleEndian() ? support::little : support::big;
  827. while (Index < End) {
  828. outs() << format("%8" PRIx64 ":", SectionAddr + Index);
  829. outs() << "\t";
  830. if (Index + 4 <= End) {
  831. dumpBytes(Bytes.slice(Index, 4), outs());
  832. outs() << "\t.word\t"
  833. << format_hex(
  834. support::endian::read32(Bytes.data() + Index, Endian), 10);
  835. Index += 4;
  836. } else if (Index + 2 <= End) {
  837. dumpBytes(Bytes.slice(Index, 2), outs());
  838. outs() << "\t\t.short\t"
  839. << format_hex(
  840. support::endian::read16(Bytes.data() + Index, Endian), 6);
  841. Index += 2;
  842. } else {
  843. dumpBytes(Bytes.slice(Index, 1), outs());
  844. outs() << "\t\t.byte\t" << format_hex(Bytes[0], 4);
  845. ++Index;
  846. }
  847. outs() << "\n";
  848. if (std::binary_search(TextMappingSymsAddr.begin(),
  849. TextMappingSymsAddr.end(), Index))
  850. break;
  851. }
  852. return Index;
  853. }
  854. static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
  855. ArrayRef<uint8_t> Bytes) {
  856. // print out data up to 8 bytes at a time in hex and ascii
  857. uint8_t AsciiData[9] = {'\0'};
  858. uint8_t Byte;
  859. int NumBytes = 0;
  860. for (; Index < End; ++Index) {
  861. if (NumBytes == 0) {
  862. outs() << format("%8" PRIx64 ":", SectionAddr + Index);
  863. outs() << "\t";
  864. }
  865. Byte = Bytes.slice(Index)[0];
  866. outs() << format(" %02x", Byte);
  867. AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
  868. uint8_t IndentOffset = 0;
  869. NumBytes++;
  870. if (Index == End - 1 || NumBytes > 8) {
  871. // Indent the space for less than 8 bytes data.
  872. // 2 spaces for byte and one for space between bytes
  873. IndentOffset = 3 * (8 - NumBytes);
  874. for (int Excess = NumBytes; Excess < 8; Excess++)
  875. AsciiData[Excess] = '\0';
  876. NumBytes = 8;
  877. }
  878. if (NumBytes == 8) {
  879. AsciiData[8] = '\0';
  880. outs() << std::string(IndentOffset, ' ') << " ";
  881. outs() << reinterpret_cast<char *>(AsciiData);
  882. outs() << '\n';
  883. NumBytes = 0;
  884. }
  885. }
  886. }
  887. static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
  888. MCContext &Ctx, MCDisassembler *DisAsm,
  889. const MCInstrAnalysis *MIA, MCInstPrinter *IP,
  890. const MCSubtargetInfo *STI, PrettyPrinter &PIP,
  891. SourcePrinter &SP, bool InlineRelocs) {
  892. std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
  893. if (InlineRelocs)
  894. RelocMap = getRelocsMap(*Obj);
  895. // Create a mapping from virtual address to symbol name. This is used to
  896. // pretty print the symbols while disassembling.
  897. std::map<SectionRef, SectionSymbolsTy> AllSymbols;
  898. SectionSymbolsTy AbsoluteSymbols;
  899. const StringRef FileName = Obj->getFileName();
  900. for (const SymbolRef &Symbol : Obj->symbols()) {
  901. uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName);
  902. StringRef Name = unwrapOrError(Symbol.getName(), FileName);
  903. if (Name.empty())
  904. continue;
  905. uint8_t SymbolType = ELF::STT_NOTYPE;
  906. if (Obj->isELF()) {
  907. SymbolType = getElfSymbolType(Obj, Symbol);
  908. if (SymbolType == ELF::STT_SECTION)
  909. continue;
  910. }
  911. section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
  912. if (SecI != Obj->section_end())
  913. AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
  914. else
  915. AbsoluteSymbols.emplace_back(Address, Name, SymbolType);
  916. }
  917. if (AllSymbols.empty() && Obj->isELF())
  918. addDynamicElfSymbols(Obj, AllSymbols);
  919. BumpPtrAllocator A;
  920. StringSaver Saver(A);
  921. addPltEntries(Obj, AllSymbols, Saver);
  922. // Create a mapping from virtual address to section.
  923. std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
  924. for (SectionRef Sec : Obj->sections())
  925. SectionAddresses.emplace_back(Sec.getAddress(), Sec);
  926. array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
  927. // Linked executables (.exe and .dll files) typically don't include a real
  928. // symbol table but they might contain an export table.
  929. if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
  930. for (const auto &ExportEntry : COFFObj->export_directories()) {
  931. StringRef Name;
  932. error(ExportEntry.getSymbolName(Name));
  933. if (Name.empty())
  934. continue;
  935. uint32_t RVA;
  936. error(ExportEntry.getExportRVA(RVA));
  937. uint64_t VA = COFFObj->getImageBase() + RVA;
  938. auto Sec = llvm::bsearch(
  939. SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &RHS) {
  940. return VA < RHS.first;
  941. });
  942. if (Sec != SectionAddresses.begin()) {
  943. --Sec;
  944. AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
  945. } else
  946. AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
  947. }
  948. }
  949. // Sort all the symbols, this allows us to use a simple binary search to find
  950. // a symbol near an address.
  951. for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
  952. array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
  953. array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
  954. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  955. if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
  956. continue;
  957. uint64_t SectionAddr = Section.getAddress();
  958. uint64_t SectSize = Section.getSize();
  959. if (!SectSize)
  960. continue;
  961. // Get the list of all the symbols in this section.
  962. SectionSymbolsTy &Symbols = AllSymbols[Section];
  963. std::vector<uint64_t> DataMappingSymsAddr;
  964. std::vector<uint64_t> TextMappingSymsAddr;
  965. if (isArmElf(Obj)) {
  966. for (const auto &Symb : Symbols) {
  967. uint64_t Address = std::get<0>(Symb);
  968. StringRef Name = std::get<1>(Symb);
  969. if (Name.startswith("$d"))
  970. DataMappingSymsAddr.push_back(Address - SectionAddr);
  971. if (Name.startswith("$x"))
  972. TextMappingSymsAddr.push_back(Address - SectionAddr);
  973. if (Name.startswith("$a"))
  974. TextMappingSymsAddr.push_back(Address - SectionAddr);
  975. if (Name.startswith("$t"))
  976. TextMappingSymsAddr.push_back(Address - SectionAddr);
  977. }
  978. }
  979. llvm::sort(DataMappingSymsAddr);
  980. llvm::sort(TextMappingSymsAddr);
  981. if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
  982. // AMDGPU disassembler uses symbolizer for printing labels
  983. std::unique_ptr<MCRelocationInfo> RelInfo(
  984. TheTarget->createMCRelocationInfo(TripleName, Ctx));
  985. if (RelInfo) {
  986. std::unique_ptr<MCSymbolizer> Symbolizer(
  987. TheTarget->createMCSymbolizer(
  988. TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
  989. DisAsm->setSymbolizer(std::move(Symbolizer));
  990. }
  991. }
  992. StringRef SegmentName = "";
  993. if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
  994. DataRefImpl DR = Section.getRawDataRefImpl();
  995. SegmentName = MachO->getSectionFinalSegmentName(DR);
  996. }
  997. StringRef SectionName;
  998. error(Section.getName(SectionName));
  999. // If the section has no symbol at the start, just insert a dummy one.
  1000. if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
  1001. Symbols.insert(
  1002. Symbols.begin(),
  1003. std::make_tuple(SectionAddr, SectionName,
  1004. Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
  1005. }
  1006. SmallString<40> Comments;
  1007. raw_svector_ostream CommentStream(Comments);
  1008. ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
  1009. unwrapOrError(Section.getContents(), Obj->getFileName()));
  1010. uint64_t VMAAdjustment = 0;
  1011. if (shouldAdjustVA(Section))
  1012. VMAAdjustment = AdjustVMA;
  1013. uint64_t Size;
  1014. uint64_t Index;
  1015. bool PrintedSection = false;
  1016. std::vector<RelocationRef> Rels = RelocMap[Section];
  1017. std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
  1018. std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
  1019. // Disassemble symbol by symbol.
  1020. for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
  1021. // Skip if --disassemble-functions is not empty and the symbol is not in
  1022. // the list.
  1023. if (!DisasmFuncsSet.empty() &&
  1024. !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
  1025. continue;
  1026. uint64_t Start = std::get<0>(Symbols[SI]);
  1027. if (Start < SectionAddr || StopAddress <= Start)
  1028. continue;
  1029. // The end is the section end, the beginning of the next symbol, or
  1030. // --stop-address.
  1031. uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
  1032. if (SI + 1 < SE)
  1033. End = std::min(End, std::get<0>(Symbols[SI + 1]));
  1034. if (Start >= End || End <= StartAddress)
  1035. continue;
  1036. Start -= SectionAddr;
  1037. End -= SectionAddr;
  1038. if (!PrintedSection) {
  1039. PrintedSection = true;
  1040. outs() << "\nDisassembly of section ";
  1041. if (!SegmentName.empty())
  1042. outs() << SegmentName << ",";
  1043. outs() << SectionName << ":\n";
  1044. }
  1045. if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
  1046. if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
  1047. // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
  1048. Start += 256;
  1049. }
  1050. if (SI == SE - 1 ||
  1051. std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
  1052. // cut trailing zeroes at the end of kernel
  1053. // cut up to 256 bytes
  1054. const uint64_t EndAlign = 256;
  1055. const auto Limit = End - (std::min)(EndAlign, End - Start);
  1056. while (End > Limit &&
  1057. *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
  1058. End -= 4;
  1059. }
  1060. }
  1061. outs() << '\n';
  1062. if (!NoLeadingAddr)
  1063. outs() << format("%016" PRIx64 " ",
  1064. SectionAddr + Start + VMAAdjustment);
  1065. StringRef SymbolName = std::get<1>(Symbols[SI]);
  1066. if (Demangle)
  1067. outs() << demangle(SymbolName) << ":\n";
  1068. else
  1069. outs() << SymbolName << ":\n";
  1070. // Don't print raw contents of a virtual section. A virtual section
  1071. // doesn't have any contents in the file.
  1072. if (Section.isVirtual()) {
  1073. outs() << "...\n";
  1074. continue;
  1075. }
  1076. #ifndef NDEBUG
  1077. raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
  1078. #else
  1079. raw_ostream &DebugOut = nulls();
  1080. #endif
  1081. // Some targets (like WebAssembly) have a special prelude at the start
  1082. // of each symbol.
  1083. DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
  1084. SectionAddr + Start, DebugOut, CommentStream);
  1085. Start += Size;
  1086. Index = Start;
  1087. if (SectionAddr < StartAddress)
  1088. Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
  1089. // If there is a data symbol inside an ELF text section and we are
  1090. // only disassembling text (applicable all architectures), we are in a
  1091. // situation where we must print the data and not disassemble it.
  1092. if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
  1093. !DisassembleAll && Section.isText()) {
  1094. dumpELFData(SectionAddr, Index, End, Bytes);
  1095. Index = End;
  1096. }
  1097. bool CheckARMELFData = isArmElf(Obj) &&
  1098. std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
  1099. !DisassembleAll;
  1100. while (Index < End) {
  1101. // AArch64 ELF binaries can interleave data and text in the same
  1102. // section. We rely on the markers introduced to understand what we
  1103. // need to dump. If the data marker is within a function, it is
  1104. // denoted as a word/short etc.
  1105. if (CheckARMELFData &&
  1106. std::binary_search(DataMappingSymsAddr.begin(),
  1107. DataMappingSymsAddr.end(), Index)) {
  1108. Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
  1109. TextMappingSymsAddr);
  1110. continue;
  1111. }
  1112. // When -z or --disassemble-zeroes are given we always dissasemble
  1113. // them. Otherwise we might want to skip zero bytes we see.
  1114. if (!DisassembleZeroes) {
  1115. uint64_t MaxOffset = End - Index;
  1116. // For -reloc: print zero blocks patched by relocations, so that
  1117. // relocations can be shown in the dump.
  1118. if (RelCur != RelEnd)
  1119. MaxOffset = RelCur->getOffset() - Index;
  1120. if (size_t N =
  1121. countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
  1122. outs() << "\t\t..." << '\n';
  1123. Index += N;
  1124. continue;
  1125. }
  1126. }
  1127. // Disassemble a real instruction or a data when disassemble all is
  1128. // provided
  1129. MCInst Inst;
  1130. bool Disassembled = DisAsm->getInstruction(
  1131. Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut,
  1132. CommentStream);
  1133. if (Size == 0)
  1134. Size = 1;
  1135. PIP.printInst(
  1136. *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
  1137. {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, outs(),
  1138. "", *STI, &SP, &Rels);
  1139. outs() << CommentStream.str();
  1140. Comments.clear();
  1141. // Try to resolve the target of a call, tail call, etc. to a specific
  1142. // symbol.
  1143. if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
  1144. MIA->isConditionalBranch(Inst))) {
  1145. uint64_t Target;
  1146. if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
  1147. // In a relocatable object, the target's section must reside in
  1148. // the same section as the call instruction or it is accessed
  1149. // through a relocation.
  1150. //
  1151. // In a non-relocatable object, the target may be in any section.
  1152. //
  1153. // N.B. We don't walk the relocations in the relocatable case yet.
  1154. auto *TargetSectionSymbols = &Symbols;
  1155. if (!Obj->isRelocatableObject()) {
  1156. auto It = llvm::bsearch(
  1157. SectionAddresses,
  1158. [=](const std::pair<uint64_t, SectionRef> &RHS) {
  1159. return Target < RHS.first;
  1160. });
  1161. if (It != SectionAddresses.begin()) {
  1162. --It;
  1163. TargetSectionSymbols = &AllSymbols[It->second];
  1164. } else {
  1165. TargetSectionSymbols = &AbsoluteSymbols;
  1166. }
  1167. }
  1168. // Find the last symbol in the section whose offset is less than
  1169. // or equal to the target. If there isn't a section that contains
  1170. // the target, find the nearest preceding absolute symbol.
  1171. auto TargetSym = llvm::bsearch(
  1172. *TargetSectionSymbols,
  1173. [=](const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
  1174. return Target < std::get<0>(RHS);
  1175. });
  1176. if (TargetSym == TargetSectionSymbols->begin()) {
  1177. TargetSectionSymbols = &AbsoluteSymbols;
  1178. TargetSym = llvm::bsearch(
  1179. AbsoluteSymbols,
  1180. [=](const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
  1181. return Target < std::get<0>(RHS);
  1182. });
  1183. }
  1184. if (TargetSym != TargetSectionSymbols->begin()) {
  1185. --TargetSym;
  1186. uint64_t TargetAddress = std::get<0>(*TargetSym);
  1187. StringRef TargetName = std::get<1>(*TargetSym);
  1188. outs() << " <" << TargetName;
  1189. uint64_t Disp = Target - TargetAddress;
  1190. if (Disp)
  1191. outs() << "+0x" << Twine::utohexstr(Disp);
  1192. outs() << '>';
  1193. }
  1194. }
  1195. }
  1196. outs() << "\n";
  1197. // Hexagon does this in pretty printer
  1198. if (Obj->getArch() != Triple::hexagon) {
  1199. // Print relocation for instruction.
  1200. while (RelCur != RelEnd) {
  1201. uint64_t Offset = RelCur->getOffset();
  1202. // If this relocation is hidden, skip it.
  1203. if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
  1204. ++RelCur;
  1205. continue;
  1206. }
  1207. // Stop when RelCur's offset is past the current instruction.
  1208. if (Offset >= Index + Size)
  1209. break;
  1210. // When --adjust-vma is used, update the address printed.
  1211. if (RelCur->getSymbol() != Obj->symbol_end()) {
  1212. Expected<section_iterator> SymSI =
  1213. RelCur->getSymbol()->getSection();
  1214. if (SymSI && *SymSI != Obj->section_end() &&
  1215. shouldAdjustVA(**SymSI))
  1216. Offset += AdjustVMA;
  1217. }
  1218. printRelocation(*RelCur, SectionAddr + Offset,
  1219. Obj->getBytesInAddress());
  1220. ++RelCur;
  1221. }
  1222. }
  1223. Index += Size;
  1224. }
  1225. }
  1226. }
  1227. }
  1228. static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
  1229. if (StartAddress > StopAddress)
  1230. error("Start address should be less than stop address");
  1231. const Target *TheTarget = getTarget(Obj);
  1232. // Package up features to be passed to target/subtarget
  1233. SubtargetFeatures Features = Obj->getFeatures();
  1234. if (!MAttrs.empty())
  1235. for (unsigned I = 0; I != MAttrs.size(); ++I)
  1236. Features.AddFeature(MAttrs[I]);
  1237. std::unique_ptr<const MCRegisterInfo> MRI(
  1238. TheTarget->createMCRegInfo(TripleName));
  1239. if (!MRI)
  1240. report_error(Obj->getFileName(),
  1241. "no register info for target " + TripleName);
  1242. // Set up disassembler.
  1243. std::unique_ptr<const MCAsmInfo> AsmInfo(
  1244. TheTarget->createMCAsmInfo(*MRI, TripleName));
  1245. if (!AsmInfo)
  1246. report_error(Obj->getFileName(),
  1247. "no assembly info for target " + TripleName);
  1248. std::unique_ptr<const MCSubtargetInfo> STI(
  1249. TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
  1250. if (!STI)
  1251. report_error(Obj->getFileName(),
  1252. "no subtarget info for target " + TripleName);
  1253. std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  1254. if (!MII)
  1255. report_error(Obj->getFileName(),
  1256. "no instruction info for target " + TripleName);
  1257. MCObjectFileInfo MOFI;
  1258. MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
  1259. // FIXME: for now initialize MCObjectFileInfo with default values
  1260. MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
  1261. std::unique_ptr<MCDisassembler> DisAsm(
  1262. TheTarget->createMCDisassembler(*STI, Ctx));
  1263. if (!DisAsm)
  1264. report_error(Obj->getFileName(),
  1265. "no disassembler for target " + TripleName);
  1266. std::unique_ptr<const MCInstrAnalysis> MIA(
  1267. TheTarget->createMCInstrAnalysis(MII.get()));
  1268. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  1269. std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
  1270. Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
  1271. if (!IP)
  1272. report_error(Obj->getFileName(),
  1273. "no instruction printer for target " + TripleName);
  1274. IP->setPrintImmHex(PrintImmHex);
  1275. PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
  1276. SourcePrinter SP(Obj, TheTarget->getName());
  1277. for (StringRef Opt : DisassemblerOptions)
  1278. if (!IP->applyTargetSpecificCLOption(Opt))
  1279. error("Unrecognized disassembler option: " + Opt);
  1280. disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(),
  1281. STI.get(), PIP, SP, InlineRelocs);
  1282. }
  1283. void printRelocations(const ObjectFile *Obj) {
  1284. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
  1285. "%08" PRIx64;
  1286. // Regular objdump doesn't print relocations in non-relocatable object
  1287. // files.
  1288. if (!Obj->isRelocatableObject())
  1289. return;
  1290. // Build a mapping from relocation target to a vector of relocation
  1291. // sections. Usually, there is an only one relocation section for
  1292. // each relocated section.
  1293. MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
  1294. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1295. if (Section.relocation_begin() == Section.relocation_end())
  1296. continue;
  1297. const SectionRef TargetSec = *Section.getRelocatedSection();
  1298. SecToRelSec[TargetSec].push_back(Section);
  1299. }
  1300. for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
  1301. StringRef SecName;
  1302. error(P.first.getName(SecName));
  1303. outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
  1304. for (SectionRef Section : P.second) {
  1305. for (const RelocationRef &Reloc : Section.relocations()) {
  1306. uint64_t Address = Reloc.getOffset();
  1307. SmallString<32> RelocName;
  1308. SmallString<32> ValueStr;
  1309. if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
  1310. continue;
  1311. Reloc.getTypeName(RelocName);
  1312. error(getRelocationValueString(Reloc, ValueStr));
  1313. outs() << format(Fmt.data(), Address) << " " << RelocName << " "
  1314. << ValueStr << "\n";
  1315. }
  1316. }
  1317. outs() << "\n";
  1318. }
  1319. }
  1320. void printDynamicRelocations(const ObjectFile *Obj) {
  1321. // For the moment, this option is for ELF only
  1322. if (!Obj->isELF())
  1323. return;
  1324. const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
  1325. if (!Elf || Elf->getEType() != ELF::ET_DYN) {
  1326. error("not a dynamic object");
  1327. return;
  1328. }
  1329. std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
  1330. if (DynRelSec.empty())
  1331. return;
  1332. outs() << "DYNAMIC RELOCATION RECORDS\n";
  1333. StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
  1334. for (const SectionRef &Section : DynRelSec)
  1335. for (const RelocationRef &Reloc : Section.relocations()) {
  1336. uint64_t Address = Reloc.getOffset();
  1337. SmallString<32> RelocName;
  1338. SmallString<32> ValueStr;
  1339. Reloc.getTypeName(RelocName);
  1340. error(getRelocationValueString(Reloc, ValueStr));
  1341. outs() << format(Fmt.data(), Address) << " " << RelocName << " "
  1342. << ValueStr << "\n";
  1343. }
  1344. }
  1345. // Returns true if we need to show LMA column when dumping section headers. We
  1346. // show it only when the platform is ELF and either we have at least one section
  1347. // whose VMA and LMA are different and/or when --show-lma flag is used.
  1348. static bool shouldDisplayLMA(const ObjectFile *Obj) {
  1349. if (!Obj->isELF())
  1350. return false;
  1351. for (const SectionRef &S : ToolSectionFilter(*Obj))
  1352. if (S.getAddress() != getELFSectionLMA(S))
  1353. return true;
  1354. return ShowLMA;
  1355. }
  1356. void printSectionHeaders(const ObjectFile *Obj) {
  1357. bool HasLMAColumn = shouldDisplayLMA(Obj);
  1358. if (HasLMAColumn)
  1359. outs() << "Sections:\n"
  1360. "Idx Name Size VMA LMA "
  1361. "Type\n";
  1362. else
  1363. outs() << "Sections:\n"
  1364. "Idx Name Size VMA Type\n";
  1365. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1366. StringRef Name;
  1367. error(Section.getName(Name));
  1368. uint64_t VMA = Section.getAddress();
  1369. if (shouldAdjustVA(Section))
  1370. VMA += AdjustVMA;
  1371. uint64_t Size = Section.getSize();
  1372. bool Text = Section.isText();
  1373. bool Data = Section.isData();
  1374. bool BSS = Section.isBSS();
  1375. std::string Type = (std::string(Text ? "TEXT " : "") +
  1376. (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
  1377. if (HasLMAColumn)
  1378. outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
  1379. " %s\n",
  1380. (unsigned)Section.getIndex(), Name.str().c_str(), Size,
  1381. VMA, getELFSectionLMA(Section), Type.c_str());
  1382. else
  1383. outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
  1384. (unsigned)Section.getIndex(), Name.str().c_str(), Size,
  1385. VMA, Type.c_str());
  1386. }
  1387. outs() << "\n";
  1388. }
  1389. void printSectionContents(const ObjectFile *Obj) {
  1390. for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
  1391. StringRef Name;
  1392. error(Section.getName(Name));
  1393. uint64_t BaseAddr = Section.getAddress();
  1394. uint64_t Size = Section.getSize();
  1395. if (!Size)
  1396. continue;
  1397. outs() << "Contents of section " << Name << ":\n";
  1398. if (Section.isBSS()) {
  1399. outs() << format("<skipping contents of bss section at [%04" PRIx64
  1400. ", %04" PRIx64 ")>\n",
  1401. BaseAddr, BaseAddr + Size);
  1402. continue;
  1403. }
  1404. StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
  1405. // Dump out the content as hex and printable ascii characters.
  1406. for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
  1407. outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
  1408. // Dump line of hex.
  1409. for (std::size_t I = 0; I < 16; ++I) {
  1410. if (I != 0 && I % 4 == 0)
  1411. outs() << ' ';
  1412. if (Addr + I < End)
  1413. outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
  1414. << hexdigit(Contents[Addr + I] & 0xF, true);
  1415. else
  1416. outs() << " ";
  1417. }
  1418. // Print ascii.
  1419. outs() << " ";
  1420. for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
  1421. if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
  1422. outs() << Contents[Addr + I];
  1423. else
  1424. outs() << ".";
  1425. }
  1426. outs() << "\n";
  1427. }
  1428. }
  1429. }
  1430. void printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
  1431. StringRef ArchitectureName) {
  1432. outs() << "SYMBOL TABLE:\n";
  1433. if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
  1434. printCOFFSymbolTable(Coff);
  1435. return;
  1436. }
  1437. const StringRef FileName = O->getFileName();
  1438. for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
  1439. // Skip printing the special zero symbol when dumping an ELF file.
  1440. // This makes the output consistent with the GNU objdump.
  1441. if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
  1442. continue;
  1443. const SymbolRef &Symbol = *I;
  1444. uint64_t Address = unwrapOrError(Symbol.getAddress(), ArchiveName, FileName,
  1445. ArchitectureName);
  1446. if ((Address < StartAddress) || (Address > StopAddress))
  1447. continue;
  1448. SymbolRef::Type Type = unwrapOrError(Symbol.getType(), ArchiveName,
  1449. FileName, ArchitectureName);
  1450. uint32_t Flags = Symbol.getFlags();
  1451. section_iterator Section = unwrapOrError(Symbol.getSection(), ArchiveName,
  1452. FileName, ArchitectureName);
  1453. StringRef Name;
  1454. if (Type == SymbolRef::ST_Debug && Section != O->section_end())
  1455. Section->getName(Name);
  1456. else
  1457. Name = unwrapOrError(Symbol.getName(), ArchiveName, FileName,
  1458. ArchitectureName);
  1459. bool Global = Flags & SymbolRef::SF_Global;
  1460. bool Weak = Flags & SymbolRef::SF_Weak;
  1461. bool Absolute = Flags & SymbolRef::SF_Absolute;
  1462. bool Common = Flags & SymbolRef::SF_Common;
  1463. bool Hidden = Flags & SymbolRef::SF_Hidden;
  1464. char GlobLoc = ' ';
  1465. if (Type != SymbolRef::ST_Unknown)
  1466. GlobLoc = Global ? 'g' : 'l';
  1467. char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
  1468. ? 'd' : ' ';
  1469. char FileFunc = ' ';
  1470. if (Type == SymbolRef::ST_File)
  1471. FileFunc = 'f';
  1472. else if (Type == SymbolRef::ST_Function)
  1473. FileFunc = 'F';
  1474. else if (Type == SymbolRef::ST_Data)
  1475. FileFunc = 'O';
  1476. const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
  1477. "%08" PRIx64;
  1478. outs() << format(Fmt, Address) << " "
  1479. << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
  1480. << (Weak ? 'w' : ' ') // Weak?
  1481. << ' ' // Constructor. Not supported yet.
  1482. << ' ' // Warning. Not supported yet.
  1483. << ' ' // Indirect reference to another symbol.
  1484. << Debug // Debugging (d) or dynamic (D) symbol.
  1485. << FileFunc // Name of function (F), file (f) or object (O).
  1486. << ' ';
  1487. if (Absolute) {
  1488. outs() << "*ABS*";
  1489. } else if (Common) {
  1490. outs() << "*COM*";
  1491. } else if (Section == O->section_end()) {
  1492. outs() << "*UND*";
  1493. } else {
  1494. if (const MachOObjectFile *MachO =
  1495. dyn_cast<const MachOObjectFile>(O)) {
  1496. DataRefImpl DR = Section->getRawDataRefImpl();
  1497. StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
  1498. outs() << SegmentName << ",";
  1499. }
  1500. StringRef SectionName;
  1501. error(Section->getName(SectionName));
  1502. outs() << SectionName;
  1503. }
  1504. if (Common || isa<ELFObjectFileBase>(O)) {
  1505. uint64_t Val =
  1506. Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
  1507. outs() << format("\t%08" PRIx64, Val);
  1508. }
  1509. if (isa<ELFObjectFileBase>(O)) {
  1510. uint8_t Other = ELFSymbolRef(Symbol).getOther();
  1511. switch (Other) {
  1512. case ELF::STV_DEFAULT:
  1513. break;
  1514. case ELF::STV_INTERNAL:
  1515. outs() << " .internal";
  1516. break;
  1517. case ELF::STV_HIDDEN:
  1518. outs() << " .hidden";
  1519. break;
  1520. case ELF::STV_PROTECTED:
  1521. outs() << " .protected";
  1522. break;
  1523. default:
  1524. outs() << format(" 0x%02x", Other);
  1525. break;
  1526. }
  1527. } else if (Hidden) {
  1528. outs() << " .hidden";
  1529. }
  1530. if (Demangle)
  1531. outs() << ' ' << demangle(Name) << '\n';
  1532. else
  1533. outs() << ' ' << Name << '\n';
  1534. }
  1535. }
  1536. static void printUnwindInfo(const ObjectFile *O) {
  1537. outs() << "Unwind info:\n\n";
  1538. if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
  1539. printCOFFUnwindInfo(Coff);
  1540. else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
  1541. printMachOUnwindInfo(MachO);
  1542. else
  1543. // TODO: Extract DWARF dump tool to objdump.
  1544. WithColor::error(errs(), ToolName)
  1545. << "This operation is only currently supported "
  1546. "for COFF and MachO object files.\n";
  1547. }
  1548. /// Dump the raw contents of the __clangast section so the output can be piped
  1549. /// into llvm-bcanalyzer.
  1550. void printRawClangAST(const ObjectFile *Obj) {
  1551. if (outs().is_displayed()) {
  1552. WithColor::error(errs(), ToolName)
  1553. << "The -raw-clang-ast option will dump the raw binary contents of "
  1554. "the clang ast section.\n"
  1555. "Please redirect the output to a file or another program such as "
  1556. "llvm-bcanalyzer.\n";
  1557. return;
  1558. }
  1559. StringRef ClangASTSectionName("__clangast");
  1560. if (isa<COFFObjectFile>(Obj)) {
  1561. ClangASTSectionName = "clangast";
  1562. }
  1563. Optional<object::SectionRef> ClangASTSection;
  1564. for (auto Sec : ToolSectionFilter(*Obj)) {
  1565. StringRef Name;
  1566. Sec.getName(Name);
  1567. if (Name == ClangASTSectionName) {
  1568. ClangASTSection = Sec;
  1569. break;
  1570. }
  1571. }
  1572. if (!ClangASTSection)
  1573. return;
  1574. StringRef ClangASTContents = unwrapOrError(
  1575. ClangASTSection.getValue().getContents(), Obj->getFileName());
  1576. outs().write(ClangASTContents.data(), ClangASTContents.size());
  1577. }
  1578. static void printFaultMaps(const ObjectFile *Obj) {
  1579. StringRef FaultMapSectionName;
  1580. if (isa<ELFObjectFileBase>(Obj)) {
  1581. FaultMapSectionName = ".llvm_faultmaps";
  1582. } else if (isa<MachOObjectFile>(Obj)) {
  1583. FaultMapSectionName = "__llvm_faultmaps";
  1584. } else {
  1585. WithColor::error(errs(), ToolName)
  1586. << "This operation is only currently supported "
  1587. "for ELF and Mach-O executable files.\n";
  1588. return;
  1589. }
  1590. Optional<object::SectionRef> FaultMapSection;
  1591. for (auto Sec : ToolSectionFilter(*Obj)) {
  1592. StringRef Name;
  1593. Sec.getName(Name);
  1594. if (Name == FaultMapSectionName) {
  1595. FaultMapSection = Sec;
  1596. break;
  1597. }
  1598. }
  1599. outs() << "FaultMap table:\n";
  1600. if (!FaultMapSection.hasValue()) {
  1601. outs() << "<not found>\n";
  1602. return;
  1603. }
  1604. StringRef FaultMapContents =
  1605. unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
  1606. FaultMapParser FMP(FaultMapContents.bytes_begin(),
  1607. FaultMapContents.bytes_end());
  1608. outs() << FMP;
  1609. }
  1610. static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
  1611. if (O->isELF()) {
  1612. printELFFileHeader(O);
  1613. printELFDynamicSection(O);
  1614. printELFSymbolVersionInfo(O);
  1615. return;
  1616. }
  1617. if (O->isCOFF())
  1618. return printCOFFFileHeader(O);
  1619. if (O->isWasm())
  1620. return printWasmFileHeader(O);
  1621. if (O->isMachO()) {
  1622. printMachOFileHeader(O);
  1623. if (!OnlyFirst)
  1624. printMachOLoadCommands(O);
  1625. return;
  1626. }
  1627. report_error(O->getFileName(), "Invalid/Unsupported object file format");
  1628. }
  1629. static void printFileHeaders(const ObjectFile *O) {
  1630. if (!O->isELF() && !O->isCOFF())
  1631. report_error(O->getFileName(), "Invalid/Unsupported object file format");
  1632. Triple::ArchType AT = O->getArch();
  1633. outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
  1634. uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
  1635. StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
  1636. outs() << "start address: "
  1637. << "0x" << format(Fmt.data(), Address) << "\n\n";
  1638. }
  1639. static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
  1640. Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
  1641. if (!ModeOrErr) {
  1642. WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
  1643. consumeError(ModeOrErr.takeError());
  1644. return;
  1645. }
  1646. sys::fs::perms Mode = ModeOrErr.get();
  1647. outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
  1648. outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
  1649. outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
  1650. outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
  1651. outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
  1652. outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
  1653. outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
  1654. outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
  1655. outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
  1656. outs() << " ";
  1657. outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
  1658. unwrapOrError(C.getGID(), Filename),
  1659. unwrapOrError(C.getRawSize(), Filename));
  1660. StringRef RawLastModified = C.getRawLastModified();
  1661. unsigned Seconds;
  1662. if (RawLastModified.getAsInteger(10, Seconds))
  1663. outs() << "(date: \"" << RawLastModified
  1664. << "\" contains non-decimal chars) ";
  1665. else {
  1666. // Since ctime(3) returns a 26 character string of the form:
  1667. // "Sun Sep 16 01:03:52 1973\n\0"
  1668. // just print 24 characters.
  1669. time_t t = Seconds;
  1670. outs() << format("%.24s ", ctime(&t));
  1671. }
  1672. StringRef Name = "";
  1673. Expected<StringRef> NameOrErr = C.getName();
  1674. if (!NameOrErr) {
  1675. consumeError(NameOrErr.takeError());
  1676. Name = unwrapOrError(C.getRawName(), Filename);
  1677. } else {
  1678. Name = NameOrErr.get();
  1679. }
  1680. outs() << Name << "\n";
  1681. }
  1682. static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
  1683. const Archive::Child *C = nullptr) {
  1684. // Avoid other output when using a raw option.
  1685. if (!RawClangAST) {
  1686. outs() << '\n';
  1687. if (A)
  1688. outs() << A->getFileName() << "(" << O->getFileName() << ")";
  1689. else
  1690. outs() << O->getFileName();
  1691. outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
  1692. }
  1693. StringRef ArchiveName = A ? A->getFileName() : "";
  1694. if (FileHeaders)
  1695. printFileHeaders(O);
  1696. if (ArchiveHeaders && !MachOOpt && C)
  1697. printArchiveChild(ArchiveName, *C);
  1698. if (Disassemble)
  1699. disassembleObject(O, Relocations);
  1700. if (Relocations && !Disassemble)
  1701. printRelocations(O);
  1702. if (DynamicRelocations)
  1703. printDynamicRelocations(O);
  1704. if (SectionHeaders)
  1705. printSectionHeaders(O);
  1706. if (SectionContents)
  1707. printSectionContents(O);
  1708. if (SymbolTable)
  1709. printSymbolTable(O, ArchiveName);
  1710. if (UnwindInfo)
  1711. printUnwindInfo(O);
  1712. if (PrivateHeaders || FirstPrivateHeader)
  1713. printPrivateFileHeaders(O, FirstPrivateHeader);
  1714. if (ExportsTrie)
  1715. printExportsTrie(O);
  1716. if (Rebase)
  1717. printRebaseTable(O);
  1718. if (Bind)
  1719. printBindTable(O);
  1720. if (LazyBind)
  1721. printLazyBindTable(O);
  1722. if (WeakBind)
  1723. printWeakBindTable(O);
  1724. if (RawClangAST)
  1725. printRawClangAST(O);
  1726. if (FaultMapSection)
  1727. printFaultMaps(O);
  1728. if (DwarfDumpType != DIDT_Null) {
  1729. std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
  1730. // Dump the complete DWARF structure.
  1731. DIDumpOptions DumpOpts;
  1732. DumpOpts.DumpType = DwarfDumpType;
  1733. DICtx->dump(outs(), DumpOpts);
  1734. }
  1735. }
  1736. static void dumpObject(const COFFImportFile *I, const Archive *A,
  1737. const Archive::Child *C = nullptr) {
  1738. StringRef ArchiveName = A ? A->getFileName() : "";
  1739. // Avoid other output when using a raw option.
  1740. if (!RawClangAST)
  1741. outs() << '\n'
  1742. << ArchiveName << "(" << I->getFileName() << ")"
  1743. << ":\tfile format COFF-import-file"
  1744. << "\n\n";
  1745. if (ArchiveHeaders && !MachOOpt && C)
  1746. printArchiveChild(ArchiveName, *C);
  1747. if (SymbolTable)
  1748. printCOFFSymbolTable(I);
  1749. }
  1750. /// Dump each object file in \a a;
  1751. static void dumpArchive(const Archive *A) {
  1752. Error Err = Error::success();
  1753. for (auto &C : A->children(Err)) {
  1754. Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
  1755. if (!ChildOrErr) {
  1756. if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
  1757. report_error(std::move(E), A->getFileName(), C);
  1758. continue;
  1759. }
  1760. if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
  1761. dumpObject(O, A, &C);
  1762. else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
  1763. dumpObject(I, A, &C);
  1764. else
  1765. report_error(errorCodeToError(object_error::invalid_file_type),
  1766. A->getFileName());
  1767. }
  1768. if (Err)
  1769. report_error(std::move(Err), A->getFileName());
  1770. }
  1771. /// Open file and figure out how to dump it.
  1772. static void dumpInput(StringRef file) {
  1773. // If we are using the Mach-O specific object file parser, then let it parse
  1774. // the file and process the command line options. So the -arch flags can
  1775. // be used to select specific slices, etc.
  1776. if (MachOOpt) {
  1777. parseInputMachO(file);
  1778. return;
  1779. }
  1780. // Attempt to open the binary.
  1781. OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
  1782. Binary &Binary = *OBinary.getBinary();
  1783. if (Archive *A = dyn_cast<Archive>(&Binary))
  1784. dumpArchive(A);
  1785. else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
  1786. dumpObject(O);
  1787. else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
  1788. parseInputMachO(UB);
  1789. else
  1790. report_error(errorCodeToError(object_error::invalid_file_type), file);
  1791. }
  1792. } // namespace llvm
  1793. int main(int argc, char **argv) {
  1794. using namespace llvm;
  1795. InitLLVM X(argc, argv);
  1796. // Initialize targets and assembly printers/parsers.
  1797. InitializeAllTargetInfos();
  1798. InitializeAllTargetMCs();
  1799. InitializeAllDisassemblers();
  1800. // Register the target printer for --version.
  1801. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  1802. cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
  1803. ToolName = argv[0];
  1804. // Defaults to a.out if no filenames specified.
  1805. if (InputFilenames.empty())
  1806. InputFilenames.push_back("a.out");
  1807. if (AllHeaders)
  1808. ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
  1809. SectionHeaders = SymbolTable = true;
  1810. if (DisassembleAll || PrintSource || PrintLines)
  1811. Disassemble = true;
  1812. if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
  1813. !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
  1814. !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
  1815. !UnwindInfo && !FaultMapSection &&
  1816. !(MachOOpt &&
  1817. (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
  1818. FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind ||
  1819. LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders ||
  1820. WeakBind || !FilterSections.empty()))) {
  1821. cl::PrintHelpMessage();
  1822. return 2;
  1823. }
  1824. DisasmFuncsSet.insert(DisassembleFunctions.begin(),
  1825. DisassembleFunctions.end());
  1826. llvm::for_each(InputFilenames, dumpInput);
  1827. return EXIT_SUCCESS;
  1828. }