llvm-objdump.cpp 77 KB

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