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