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