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