llvm-objdump.cpp 70 KB

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