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