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