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