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