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