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