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