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/MC/MCAsmInfo.h" 26 #include "llvm/MC/MCContext.h" 27 #include "llvm/MC/MCDisassembler.h" 28 #include "llvm/MC/MCInst.h" 29 #include "llvm/MC/MCInstPrinter.h" 30 #include "llvm/MC/MCInstrAnalysis.h" 31 #include "llvm/MC/MCInstrInfo.h" 32 #include "llvm/MC/MCObjectFileInfo.h" 33 #include "llvm/MC/MCRegisterInfo.h" 34 #include "llvm/MC/MCRelocationInfo.h" 35 #include "llvm/MC/MCSubtargetInfo.h" 36 #include "llvm/Object/Archive.h" 37 #include "llvm/Object/ELFObjectFile.h" 38 #include "llvm/Object/COFF.h" 39 #include "llvm/Object/MachO.h" 40 #include "llvm/Object/ObjectFile.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/Errc.h" 45 #include "llvm/Support/FileSystem.h" 46 #include "llvm/Support/Format.h" 47 #include "llvm/Support/GraphWriter.h" 48 #include "llvm/Support/Host.h" 49 #include "llvm/Support/ManagedStatic.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/PrettyStackTrace.h" 52 #include "llvm/Support/Signals.h" 53 #include "llvm/Support/SourceMgr.h" 54 #include "llvm/Support/TargetRegistry.h" 55 #include "llvm/Support/TargetSelect.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <algorithm> 58 #include <cctype> 59 #include <cstring> 60 #include <system_error> 61 62 using namespace llvm; 63 using namespace object; 64 65 static cl::list<std::string> 66 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 67 68 cl::opt<bool> 69 llvm::Disassemble("disassemble", 70 cl::desc("Display assembler mnemonics for the machine instructions")); 71 static cl::alias 72 Disassembled("d", cl::desc("Alias for --disassemble"), 73 cl::aliasopt(Disassemble)); 74 75 cl::opt<bool> 76 llvm::Relocations("r", cl::desc("Display the relocation entries in the file")); 77 78 cl::opt<bool> 79 llvm::SectionContents("s", cl::desc("Display the content of each section")); 80 81 cl::opt<bool> 82 llvm::SymbolTable("t", cl::desc("Display the symbol table")); 83 84 cl::opt<bool> 85 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); 86 87 cl::opt<bool> 88 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info")); 89 90 cl::opt<bool> 91 llvm::Bind("bind", cl::desc("Display mach-o binding info")); 92 93 cl::opt<bool> 94 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); 95 96 cl::opt<bool> 97 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); 98 99 static cl::opt<bool> 100 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 101 static cl::alias 102 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt)); 103 104 cl::opt<std::string> 105 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 106 "see -version for available targets")); 107 108 cl::opt<std::string> 109 llvm::MCPU("mcpu", 110 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 111 cl::value_desc("cpu-name"), 112 cl::init("")); 113 114 cl::opt<std::string> 115 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, " 116 "see -version for available targets")); 117 118 cl::opt<bool> 119 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the " 120 "headers for each section.")); 121 static cl::alias 122 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), 123 cl::aliasopt(SectionHeaders)); 124 static cl::alias 125 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), 126 cl::aliasopt(SectionHeaders)); 127 128 cl::list<std::string> 129 llvm::MAttrs("mattr", 130 cl::CommaSeparated, 131 cl::desc("Target specific attributes"), 132 cl::value_desc("a1,+a2,-a3,...")); 133 134 cl::opt<bool> 135 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " 136 "instructions, do not print " 137 "the instruction bytes.")); 138 139 cl::opt<bool> 140 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information")); 141 142 static cl::alias 143 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 144 cl::aliasopt(UnwindInfo)); 145 146 cl::opt<bool> 147 llvm::PrivateHeaders("private-headers", 148 cl::desc("Display format specific file headers")); 149 150 static cl::alias 151 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"), 152 cl::aliasopt(PrivateHeaders)); 153 154 cl::opt<bool> 155 llvm::PrintImmHex("print-imm-hex", 156 cl::desc("Use hex format for immediate values")); 157 158 cl::opt<bool> PrintFaultMaps("fault-map-section", 159 cl::desc("Display contents of faultmap section")); 160 161 static StringRef ToolName; 162 static int ReturnValue = EXIT_SUCCESS; 163 164 bool llvm::error(std::error_code EC) { 165 if (!EC) 166 return false; 167 168 outs() << ToolName << ": error reading file: " << EC.message() << ".\n"; 169 outs().flush(); 170 ReturnValue = EXIT_FAILURE; 171 return true; 172 } 173 174 static void report_error(StringRef File, std::error_code EC) { 175 assert(EC); 176 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n"; 177 ReturnValue = EXIT_FAILURE; 178 } 179 180 static const Target *getTarget(const ObjectFile *Obj = nullptr) { 181 // Figure out the target triple. 182 llvm::Triple TheTriple("unknown-unknown-unknown"); 183 if (TripleName.empty()) { 184 if (Obj) { 185 TheTriple.setArch(Triple::ArchType(Obj->getArch())); 186 // TheTriple defaults to ELF, and COFF doesn't have an environment: 187 // the best we can do here is indicate that it is mach-o. 188 if (Obj->isMachO()) 189 TheTriple.setObjectFormat(Triple::MachO); 190 191 if (Obj->isCOFF()) { 192 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj); 193 if (COFFObj->getArch() == Triple::thumb) 194 TheTriple.setTriple("thumbv7-windows"); 195 } 196 } 197 } else 198 TheTriple.setTriple(Triple::normalize(TripleName)); 199 200 // Get the target specific parser. 201 std::string Error; 202 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 203 Error); 204 if (!TheTarget) { 205 errs() << ToolName << ": " << Error; 206 return nullptr; 207 } 208 209 // Update the triple name and return the found target. 210 TripleName = TheTriple.getTriple(); 211 return TheTarget; 212 } 213 214 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { 215 uint64_t a_addr, b_addr; 216 if (error(a.getOffset(a_addr))) return false; 217 if (error(b.getOffset(b_addr))) return false; 218 return a_addr < b_addr; 219 } 220 221 namespace { 222 class PrettyPrinter { 223 public: 224 virtual ~PrettyPrinter(){} 225 virtual void printInst(MCInstPrinter &IP, const MCInst *MI, 226 ArrayRef<uint8_t> Bytes, uint64_t Address, 227 raw_ostream &OS, StringRef Annot, 228 MCSubtargetInfo const &STI) { 229 outs() << format("%8" PRIx64 ":", Address); 230 if (!NoShowRawInsn) { 231 outs() << "\t"; 232 dumpBytes(Bytes, outs()); 233 } 234 IP.printInst(MI, outs(), "", STI); 235 } 236 }; 237 PrettyPrinter PrettyPrinterInst; 238 class HexagonPrettyPrinter : public PrettyPrinter { 239 public: 240 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, 241 raw_ostream &OS) { 242 uint32_t opcode = 243 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; 244 OS << format("%8" PRIx64 ":", Address); 245 if (!NoShowRawInsn) { 246 OS << "\t"; 247 dumpBytes(Bytes.slice(0, 4), OS); 248 OS << format("%08" PRIx32, opcode); 249 } 250 } 251 void printInst(MCInstPrinter &IP, const MCInst *MI, 252 ArrayRef<uint8_t> Bytes, uint64_t Address, 253 raw_ostream &OS, StringRef Annot, 254 MCSubtargetInfo const &STI) override { 255 std::string Buffer; 256 { 257 raw_string_ostream TempStream(Buffer); 258 IP.printInst(MI, TempStream, "", STI); 259 } 260 StringRef Contents(Buffer); 261 // Split off bundle attributes 262 auto PacketBundle = Contents.rsplit('\n'); 263 // Split off first instruction from the rest 264 auto HeadTail = PacketBundle.first.split('\n'); 265 auto Preamble = " { "; 266 auto Separator = ""; 267 while(!HeadTail.first.empty()) { 268 OS << Separator; 269 Separator = "\n"; 270 printLead(Bytes, Address, OS); 271 OS << Preamble; 272 Preamble = " "; 273 StringRef Inst; 274 auto Duplex = HeadTail.first.split('\v'); 275 if(!Duplex.second.empty()){ 276 OS << Duplex.first; 277 OS << "; "; 278 Inst = Duplex.second; 279 } 280 else 281 Inst = HeadTail.first; 282 OS << Inst; 283 Bytes = Bytes.slice(4); 284 Address += 4; 285 HeadTail = HeadTail.second.split('\n'); 286 } 287 OS << " } " << PacketBundle.second; 288 } 289 }; 290 HexagonPrettyPrinter HexagonPrettyPrinterInst; 291 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 292 switch(Triple.getArch()) { 293 default: 294 return PrettyPrinterInst; 295 case Triple::hexagon: 296 return HexagonPrettyPrinterInst; 297 } 298 } 299 } 300 301 template <class ELFT> 302 static const typename ELFObjectFile<ELFT>::Elf_Rel * 303 getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) { 304 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel; 305 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b); 306 } 307 308 template <class ELFT> 309 static const typename ELFObjectFile<ELFT>::Elf_Rela * 310 getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) { 311 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela; 312 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b); 313 } 314 315 template <class ELFT> 316 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj, 317 DataRefImpl Rel, 318 SmallVectorImpl<char> &Result) { 319 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym; 320 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr; 321 const ELFFile<ELFT> &EF = *Obj->getELFFile(); 322 323 const Elf_Shdr *sec = EF.getSection(Rel.d.a); 324 const Elf_Shdr *SymTab = EF.getSection(sec->sh_link); 325 assert(SymTab->sh_type == ELF::SHT_SYMTAB || 326 SymTab->sh_type == ELF::SHT_DYNSYM); 327 const Elf_Shdr *StrTab = EF.getSection(SymTab->sh_link); 328 uint8_t type; 329 StringRef res; 330 int64_t addend = 0; 331 uint16_t symbol_index = 0; 332 switch (sec->sh_type) { 333 default: 334 return object_error::parse_failed; 335 case ELF::SHT_REL: { 336 type = getRel(EF, Rel)->getType(EF.isMips64EL()); 337 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL()); 338 // TODO: Read implicit addend from section data. 339 break; 340 } 341 case ELF::SHT_RELA: { 342 type = getRela(EF, Rel)->getType(EF.isMips64EL()); 343 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL()); 344 addend = getRela(EF, Rel)->r_addend; 345 break; 346 } 347 } 348 const Elf_Sym *symb = 349 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index); 350 StringRef Target; 351 const Elf_Shdr *SymSec = EF.getSection(symb); 352 if (symb->getType() == ELF::STT_SECTION) { 353 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec); 354 if (std::error_code EC = SecName.getError()) 355 return EC; 356 Target = *SecName; 357 } else { 358 ErrorOr<StringRef> SymName = EF.getSymbolName(StrTab, symb); 359 if (!SymName) 360 return SymName.getError(); 361 Target = *SymName; 362 } 363 switch (EF.getHeader()->e_machine) { 364 case ELF::EM_X86_64: 365 switch (type) { 366 case ELF::R_X86_64_PC8: 367 case ELF::R_X86_64_PC16: 368 case ELF::R_X86_64_PC32: { 369 std::string fmtbuf; 370 raw_string_ostream fmt(fmtbuf); 371 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P"; 372 fmt.flush(); 373 Result.append(fmtbuf.begin(), fmtbuf.end()); 374 } break; 375 case ELF::R_X86_64_8: 376 case ELF::R_X86_64_16: 377 case ELF::R_X86_64_32: 378 case ELF::R_X86_64_32S: 379 case ELF::R_X86_64_64: { 380 std::string fmtbuf; 381 raw_string_ostream fmt(fmtbuf); 382 fmt << Target << (addend < 0 ? "" : "+") << addend; 383 fmt.flush(); 384 Result.append(fmtbuf.begin(), fmtbuf.end()); 385 } break; 386 default: 387 res = "Unknown"; 388 } 389 break; 390 case ELF::EM_AARCH64: { 391 std::string fmtbuf; 392 raw_string_ostream fmt(fmtbuf); 393 fmt << Target; 394 if (addend != 0) 395 fmt << (addend < 0 ? "" : "+") << addend; 396 fmt.flush(); 397 Result.append(fmtbuf.begin(), fmtbuf.end()); 398 break; 399 } 400 case ELF::EM_386: 401 case ELF::EM_ARM: 402 case ELF::EM_HEXAGON: 403 case ELF::EM_MIPS: 404 res = Target; 405 break; 406 default: 407 res = "Unknown"; 408 } 409 if (Result.empty()) 410 Result.append(res.begin(), res.end()); 411 return std::error_code(); 412 } 413 414 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj, 415 const RelocationRef &RelRef, 416 SmallVectorImpl<char> &Result) { 417 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 418 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj)) 419 return getRelocationValueString(ELF32LE, Rel, Result); 420 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj)) 421 return getRelocationValueString(ELF64LE, Rel, Result); 422 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj)) 423 return getRelocationValueString(ELF32BE, Rel, Result); 424 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj); 425 return getRelocationValueString(ELF64BE, Rel, Result); 426 } 427 428 static std::error_code getRelocationValueString(const COFFObjectFile *Obj, 429 const RelocationRef &Rel, 430 SmallVectorImpl<char> &Result) { 431 symbol_iterator SymI = Rel.getSymbol(); 432 StringRef SymName; 433 if (std::error_code EC = SymI->getName(SymName)) 434 return EC; 435 Result.append(SymName.begin(), SymName.end()); 436 return std::error_code(); 437 } 438 439 static void printRelocationTargetName(const MachOObjectFile *O, 440 const MachO::any_relocation_info &RE, 441 raw_string_ostream &fmt) { 442 bool IsScattered = O->isRelocationScattered(RE); 443 444 // Target of a scattered relocation is an address. In the interest of 445 // generating pretty output, scan through the symbol table looking for a 446 // symbol that aligns with that address. If we find one, print it. 447 // Otherwise, we just print the hex address of the target. 448 if (IsScattered) { 449 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 450 451 for (const SymbolRef &Symbol : O->symbols()) { 452 std::error_code ec; 453 uint64_t Addr; 454 StringRef Name; 455 456 if ((ec = Symbol.getAddress(Addr))) 457 report_fatal_error(ec.message()); 458 if (Addr != Val) 459 continue; 460 if ((ec = Symbol.getName(Name))) 461 report_fatal_error(ec.message()); 462 fmt << Name; 463 return; 464 } 465 466 // If we couldn't find a symbol that this relocation refers to, try 467 // to find a section beginning instead. 468 for (const SectionRef &Section : O->sections()) { 469 std::error_code ec; 470 471 StringRef Name; 472 uint64_t Addr = Section.getAddress(); 473 if (Addr != Val) 474 continue; 475 if ((ec = Section.getName(Name))) 476 report_fatal_error(ec.message()); 477 fmt << Name; 478 return; 479 } 480 481 fmt << format("0x%x", Val); 482 return; 483 } 484 485 StringRef S; 486 bool isExtern = O->getPlainRelocationExternal(RE); 487 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 488 489 if (isExtern) { 490 symbol_iterator SI = O->symbol_begin(); 491 advance(SI, Val); 492 SI->getName(S); 493 } else { 494 section_iterator SI = O->section_begin(); 495 // Adjust for the fact that sections are 1-indexed. 496 advance(SI, Val - 1); 497 SI->getName(S); 498 } 499 500 fmt << S; 501 } 502 503 static std::error_code getRelocationValueString(const MachOObjectFile *Obj, 504 const RelocationRef &RelRef, 505 SmallVectorImpl<char> &Result) { 506 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 507 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 508 509 unsigned Arch = Obj->getArch(); 510 511 std::string fmtbuf; 512 raw_string_ostream fmt(fmtbuf); 513 unsigned Type = Obj->getAnyRelocationType(RE); 514 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 515 516 // Determine any addends that should be displayed with the relocation. 517 // These require decoding the relocation type, which is triple-specific. 518 519 // X86_64 has entirely custom relocation types. 520 if (Arch == Triple::x86_64) { 521 bool isPCRel = Obj->getAnyRelocationPCRel(RE); 522 523 switch (Type) { 524 case MachO::X86_64_RELOC_GOT_LOAD: 525 case MachO::X86_64_RELOC_GOT: { 526 printRelocationTargetName(Obj, RE, fmt); 527 fmt << "@GOT"; 528 if (isPCRel) 529 fmt << "PCREL"; 530 break; 531 } 532 case MachO::X86_64_RELOC_SUBTRACTOR: { 533 DataRefImpl RelNext = Rel; 534 Obj->moveRelocationNext(RelNext); 535 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 536 537 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 538 // X86_64_RELOC_UNSIGNED. 539 // NOTE: Scattered relocations don't exist on x86_64. 540 unsigned RType = Obj->getAnyRelocationType(RENext); 541 if (RType != MachO::X86_64_RELOC_UNSIGNED) 542 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after " 543 "X86_64_RELOC_SUBTRACTOR."); 544 545 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 546 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 547 printRelocationTargetName(Obj, RENext, fmt); 548 fmt << "-"; 549 printRelocationTargetName(Obj, RE, fmt); 550 break; 551 } 552 case MachO::X86_64_RELOC_TLV: 553 printRelocationTargetName(Obj, RE, fmt); 554 fmt << "@TLV"; 555 if (isPCRel) 556 fmt << "P"; 557 break; 558 case MachO::X86_64_RELOC_SIGNED_1: 559 printRelocationTargetName(Obj, RE, fmt); 560 fmt << "-1"; 561 break; 562 case MachO::X86_64_RELOC_SIGNED_2: 563 printRelocationTargetName(Obj, RE, fmt); 564 fmt << "-2"; 565 break; 566 case MachO::X86_64_RELOC_SIGNED_4: 567 printRelocationTargetName(Obj, RE, fmt); 568 fmt << "-4"; 569 break; 570 default: 571 printRelocationTargetName(Obj, RE, fmt); 572 break; 573 } 574 // X86 and ARM share some relocation types in common. 575 } else if (Arch == Triple::x86 || Arch == Triple::arm || 576 Arch == Triple::ppc) { 577 // Generic relocation types... 578 switch (Type) { 579 case MachO::GENERIC_RELOC_PAIR: // prints no info 580 return std::error_code(); 581 case MachO::GENERIC_RELOC_SECTDIFF: { 582 DataRefImpl RelNext = Rel; 583 Obj->moveRelocationNext(RelNext); 584 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 585 586 // X86 sect diff's must be followed by a relocation of type 587 // GENERIC_RELOC_PAIR. 588 unsigned RType = Obj->getAnyRelocationType(RENext); 589 590 if (RType != MachO::GENERIC_RELOC_PAIR) 591 report_fatal_error("Expected GENERIC_RELOC_PAIR after " 592 "GENERIC_RELOC_SECTDIFF."); 593 594 printRelocationTargetName(Obj, RE, fmt); 595 fmt << "-"; 596 printRelocationTargetName(Obj, RENext, fmt); 597 break; 598 } 599 } 600 601 if (Arch == Triple::x86 || Arch == Triple::ppc) { 602 switch (Type) { 603 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 604 DataRefImpl RelNext = Rel; 605 Obj->moveRelocationNext(RelNext); 606 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 607 608 // X86 sect diff's must be followed by a relocation of type 609 // GENERIC_RELOC_PAIR. 610 unsigned RType = Obj->getAnyRelocationType(RENext); 611 if (RType != MachO::GENERIC_RELOC_PAIR) 612 report_fatal_error("Expected GENERIC_RELOC_PAIR after " 613 "GENERIC_RELOC_LOCAL_SECTDIFF."); 614 615 printRelocationTargetName(Obj, RE, fmt); 616 fmt << "-"; 617 printRelocationTargetName(Obj, RENext, fmt); 618 break; 619 } 620 case MachO::GENERIC_RELOC_TLV: { 621 printRelocationTargetName(Obj, RE, fmt); 622 fmt << "@TLV"; 623 if (IsPCRel) 624 fmt << "P"; 625 break; 626 } 627 default: 628 printRelocationTargetName(Obj, RE, fmt); 629 } 630 } else { // ARM-specific relocations 631 switch (Type) { 632 case MachO::ARM_RELOC_HALF: 633 case MachO::ARM_RELOC_HALF_SECTDIFF: { 634 // Half relocations steal a bit from the length field to encode 635 // whether this is an upper16 or a lower16 relocation. 636 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1; 637 638 if (isUpper) 639 fmt << ":upper16:("; 640 else 641 fmt << ":lower16:("; 642 printRelocationTargetName(Obj, RE, fmt); 643 644 DataRefImpl RelNext = Rel; 645 Obj->moveRelocationNext(RelNext); 646 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 647 648 // ARM half relocs must be followed by a relocation of type 649 // ARM_RELOC_PAIR. 650 unsigned RType = Obj->getAnyRelocationType(RENext); 651 if (RType != MachO::ARM_RELOC_PAIR) 652 report_fatal_error("Expected ARM_RELOC_PAIR after " 653 "ARM_RELOC_HALF"); 654 655 // NOTE: The half of the target virtual address is stashed in the 656 // address field of the secondary relocation, but we can't reverse 657 // engineer the constant offset from it without decoding the movw/movt 658 // instruction to find the other half in its immediate field. 659 660 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 661 // symbol/section pointer of the follow-on relocation. 662 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 663 fmt << "-"; 664 printRelocationTargetName(Obj, RENext, fmt); 665 } 666 667 fmt << ")"; 668 break; 669 } 670 default: { printRelocationTargetName(Obj, RE, fmt); } 671 } 672 } 673 } else 674 printRelocationTargetName(Obj, RE, fmt); 675 676 fmt.flush(); 677 Result.append(fmtbuf.begin(), fmtbuf.end()); 678 return std::error_code(); 679 } 680 681 static std::error_code getRelocationValueString(const RelocationRef &Rel, 682 SmallVectorImpl<char> &Result) { 683 const ObjectFile *Obj = Rel.getObject(); 684 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 685 return getRelocationValueString(ELF, Rel, Result); 686 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 687 return getRelocationValueString(COFF, Rel, Result); 688 auto *MachO = cast<MachOObjectFile>(Obj); 689 return getRelocationValueString(MachO, Rel, Result); 690 } 691 692 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 693 const Target *TheTarget = getTarget(Obj); 694 // getTarget() will have already issued a diagnostic if necessary, so 695 // just bail here if it failed. 696 if (!TheTarget) 697 return; 698 699 // Package up features to be passed to target/subtarget 700 std::string FeaturesStr; 701 if (MAttrs.size()) { 702 SubtargetFeatures Features; 703 for (unsigned i = 0; i != MAttrs.size(); ++i) 704 Features.AddFeature(MAttrs[i]); 705 FeaturesStr = Features.getString(); 706 } 707 708 std::unique_ptr<const MCRegisterInfo> MRI( 709 TheTarget->createMCRegInfo(TripleName)); 710 if (!MRI) { 711 errs() << "error: no register info for target " << TripleName << "\n"; 712 return; 713 } 714 715 // Set up disassembler. 716 std::unique_ptr<const MCAsmInfo> AsmInfo( 717 TheTarget->createMCAsmInfo(*MRI, TripleName)); 718 if (!AsmInfo) { 719 errs() << "error: no assembly info for target " << TripleName << "\n"; 720 return; 721 } 722 723 std::unique_ptr<const MCSubtargetInfo> STI( 724 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); 725 if (!STI) { 726 errs() << "error: no subtarget info for target " << TripleName << "\n"; 727 return; 728 } 729 730 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 731 if (!MII) { 732 errs() << "error: no instruction info for target " << TripleName << "\n"; 733 return; 734 } 735 736 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); 737 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); 738 739 std::unique_ptr<MCDisassembler> DisAsm( 740 TheTarget->createMCDisassembler(*STI, Ctx)); 741 742 if (!DisAsm) { 743 errs() << "error: no disassembler for target " << TripleName << "\n"; 744 return; 745 } 746 747 std::unique_ptr<const MCInstrAnalysis> MIA( 748 TheTarget->createMCInstrAnalysis(MII.get())); 749 750 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 751 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 752 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 753 if (!IP) { 754 errs() << "error: no instruction printer for target " << TripleName 755 << '\n'; 756 return; 757 } 758 IP->setPrintImmHex(PrintImmHex); 759 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 760 761 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " : 762 "\t\t\t%08" PRIx64 ": "; 763 764 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections 765 // in RelocSecs contain the relocations for section S. 766 std::error_code EC; 767 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; 768 for (const SectionRef &Section : Obj->sections()) { 769 section_iterator Sec2 = Section.getRelocatedSection(); 770 if (Sec2 != Obj->section_end()) 771 SectionRelocMap[*Sec2].push_back(Section); 772 } 773 774 for (const SectionRef &Section : Obj->sections()) { 775 if (!Section.isText() || Section.isVirtual()) 776 continue; 777 778 uint64_t SectionAddr = Section.getAddress(); 779 uint64_t SectSize = Section.getSize(); 780 if (!SectSize) 781 continue; 782 783 // Make a list of all the symbols in this section. 784 std::vector<std::pair<uint64_t, StringRef>> Symbols; 785 for (const SymbolRef &Symbol : Obj->symbols()) { 786 if (Section.containsSymbol(Symbol)) { 787 uint64_t Address; 788 if (error(Symbol.getAddress(Address))) 789 break; 790 if (Address == UnknownAddress) 791 continue; 792 Address -= SectionAddr; 793 if (Address >= SectSize) 794 continue; 795 796 StringRef Name; 797 if (error(Symbol.getName(Name))) 798 break; 799 Symbols.push_back(std::make_pair(Address, Name)); 800 } 801 } 802 803 // Sort the symbols by address, just in case they didn't come in that way. 804 array_pod_sort(Symbols.begin(), Symbols.end()); 805 806 // Make a list of all the relocations for this section. 807 std::vector<RelocationRef> Rels; 808 if (InlineRelocs) { 809 for (const SectionRef &RelocSec : SectionRelocMap[Section]) { 810 for (const RelocationRef &Reloc : RelocSec.relocations()) { 811 Rels.push_back(Reloc); 812 } 813 } 814 } 815 816 // Sort relocations by address. 817 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 818 819 StringRef SegmentName = ""; 820 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 821 DataRefImpl DR = Section.getRawDataRefImpl(); 822 SegmentName = MachO->getSectionFinalSegmentName(DR); 823 } 824 StringRef name; 825 if (error(Section.getName(name))) 826 break; 827 outs() << "Disassembly of section "; 828 if (!SegmentName.empty()) 829 outs() << SegmentName << ","; 830 outs() << name << ':'; 831 832 // If the section has no symbol at the start, just insert a dummy one. 833 if (Symbols.empty() || Symbols[0].first != 0) 834 Symbols.insert(Symbols.begin(), std::make_pair(0, name)); 835 836 SmallString<40> Comments; 837 raw_svector_ostream CommentStream(Comments); 838 839 StringRef BytesStr; 840 if (error(Section.getContents(BytesStr))) 841 break; 842 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 843 BytesStr.size()); 844 845 uint64_t Size; 846 uint64_t Index; 847 848 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 849 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 850 // Disassemble symbol by symbol. 851 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 852 853 uint64_t Start = Symbols[si].first; 854 // The end is either the section end or the beginning of the next symbol. 855 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first; 856 // If this symbol has the same address as the next symbol, then skip it. 857 if (Start == End) 858 continue; 859 860 outs() << '\n' << Symbols[si].second << ":\n"; 861 862 #ifndef NDEBUG 863 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 864 #else 865 raw_ostream &DebugOut = nulls(); 866 #endif 867 868 for (Index = Start; Index < End; Index += Size) { 869 MCInst Inst; 870 871 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 872 SectionAddr + Index, DebugOut, 873 CommentStream)) { 874 PIP.printInst(*IP, &Inst, 875 Bytes.slice(Index, Size), 876 SectionAddr + Index, outs(), "", *STI); 877 outs() << CommentStream.str(); 878 Comments.clear(); 879 outs() << "\n"; 880 } else { 881 errs() << ToolName << ": warning: invalid instruction encoding\n"; 882 if (Size == 0) 883 Size = 1; // skip illegible bytes 884 } 885 886 // Print relocation for instruction. 887 while (rel_cur != rel_end) { 888 bool hidden = false; 889 uint64_t addr; 890 SmallString<16> name; 891 SmallString<32> val; 892 893 // If this relocation is hidden, skip it. 894 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel; 895 if (hidden) goto skip_print_rel; 896 897 if (error(rel_cur->getOffset(addr))) goto skip_print_rel; 898 // Stop when rel_cur's address is past the current instruction. 899 if (addr >= Index + Size) break; 900 if (error(rel_cur->getTypeName(name))) goto skip_print_rel; 901 if (error(getRelocationValueString(*rel_cur, val))) 902 goto skip_print_rel; 903 outs() << format(Fmt.data(), SectionAddr + addr) << name 904 << "\t" << val << "\n"; 905 906 skip_print_rel: 907 ++rel_cur; 908 } 909 } 910 } 911 } 912 } 913 914 void llvm::PrintRelocations(const ObjectFile *Obj) { 915 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 916 "%08" PRIx64; 917 // Regular objdump doesn't print relocations in non-relocatable object 918 // files. 919 if (!Obj->isRelocatableObject()) 920 return; 921 922 for (const SectionRef &Section : Obj->sections()) { 923 if (Section.relocation_begin() == Section.relocation_end()) 924 continue; 925 StringRef secname; 926 if (error(Section.getName(secname))) 927 continue; 928 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 929 for (const RelocationRef &Reloc : Section.relocations()) { 930 bool hidden; 931 uint64_t address; 932 SmallString<32> relocname; 933 SmallString<32> valuestr; 934 if (error(Reloc.getHidden(hidden))) 935 continue; 936 if (hidden) 937 continue; 938 if (error(Reloc.getTypeName(relocname))) 939 continue; 940 if (error(Reloc.getOffset(address))) 941 continue; 942 if (error(getRelocationValueString(Reloc, valuestr))) 943 continue; 944 outs() << format(Fmt.data(), address) << " " << relocname << " " 945 << valuestr << "\n"; 946 } 947 outs() << "\n"; 948 } 949 } 950 951 void llvm::PrintSectionHeaders(const ObjectFile *Obj) { 952 outs() << "Sections:\n" 953 "Idx Name Size Address Type\n"; 954 unsigned i = 0; 955 for (const SectionRef &Section : Obj->sections()) { 956 StringRef Name; 957 if (error(Section.getName(Name))) 958 return; 959 uint64_t Address = Section.getAddress(); 960 uint64_t Size = Section.getSize(); 961 bool Text = Section.isText(); 962 bool Data = Section.isData(); 963 bool BSS = Section.isBSS(); 964 std::string Type = (std::string(Text ? "TEXT " : "") + 965 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 966 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, 967 Name.str().c_str(), Size, Address, Type.c_str()); 968 ++i; 969 } 970 } 971 972 void llvm::PrintSectionContents(const ObjectFile *Obj) { 973 std::error_code EC; 974 for (const SectionRef &Section : Obj->sections()) { 975 StringRef Name; 976 StringRef Contents; 977 if (error(Section.getName(Name))) 978 continue; 979 uint64_t BaseAddr = Section.getAddress(); 980 uint64_t Size = Section.getSize(); 981 if (!Size) 982 continue; 983 984 outs() << "Contents of section " << Name << ":\n"; 985 if (Section.isBSS()) { 986 outs() << format("<skipping contents of bss section at [%04" PRIx64 987 ", %04" PRIx64 ")>\n", 988 BaseAddr, BaseAddr + Size); 989 continue; 990 } 991 992 if (error(Section.getContents(Contents))) 993 continue; 994 995 // Dump out the content as hex and printable ascii characters. 996 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 997 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 998 // Dump line of hex. 999 for (std::size_t i = 0; i < 16; ++i) { 1000 if (i != 0 && i % 4 == 0) 1001 outs() << ' '; 1002 if (addr + i < end) 1003 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 1004 << hexdigit(Contents[addr + i] & 0xF, true); 1005 else 1006 outs() << " "; 1007 } 1008 // Print ascii. 1009 outs() << " "; 1010 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 1011 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 1012 outs() << Contents[addr + i]; 1013 else 1014 outs() << "."; 1015 } 1016 outs() << "\n"; 1017 } 1018 } 1019 } 1020 1021 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) { 1022 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) { 1023 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI); 1024 StringRef Name; 1025 if (error(Symbol.getError())) 1026 return; 1027 1028 if (error(coff->getSymbolName(*Symbol, Name))) 1029 return; 1030 1031 outs() << "[" << format("%2d", SI) << "]" 1032 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")" 1033 << "(fl 0x00)" // Flag bits, which COFF doesn't have. 1034 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")" 1035 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") " 1036 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") " 1037 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " " 1038 << Name << "\n"; 1039 1040 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) { 1041 if (Symbol->isSectionDefinition()) { 1042 const coff_aux_section_definition *asd; 1043 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))) 1044 return; 1045 1046 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj()); 1047 1048 outs() << "AUX " 1049 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x " 1050 , unsigned(asd->Length) 1051 , unsigned(asd->NumberOfRelocations) 1052 , unsigned(asd->NumberOfLinenumbers) 1053 , unsigned(asd->CheckSum)) 1054 << format("assoc %d comdat %d\n" 1055 , unsigned(AuxNumber) 1056 , unsigned(asd->Selection)); 1057 } else if (Symbol->isFileRecord()) { 1058 const char *FileName; 1059 if (error(coff->getAuxSymbol<char>(SI + 1, FileName))) 1060 return; 1061 1062 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() * 1063 coff->getSymbolTableEntrySize()); 1064 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n'; 1065 1066 SI = SI + Symbol->getNumberOfAuxSymbols(); 1067 break; 1068 } else { 1069 outs() << "AUX Unknown\n"; 1070 } 1071 } 1072 } 1073 } 1074 1075 void llvm::PrintSymbolTable(const ObjectFile *o) { 1076 outs() << "SYMBOL TABLE:\n"; 1077 1078 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 1079 PrintCOFFSymbolTable(coff); 1080 return; 1081 } 1082 for (const SymbolRef &Symbol : o->symbols()) { 1083 uint64_t Address; 1084 SymbolRef::Type Type = Symbol.getType(); 1085 uint32_t Flags = Symbol.getFlags(); 1086 section_iterator Section = o->section_end(); 1087 if (error(Symbol.getAddress(Address))) 1088 continue; 1089 if (error(Symbol.getSection(Section))) 1090 continue; 1091 StringRef Name; 1092 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) { 1093 Section->getName(Name); 1094 } else if (error(Symbol.getName(Name))) { 1095 continue; 1096 } 1097 1098 bool Global = Flags & SymbolRef::SF_Global; 1099 bool Weak = Flags & SymbolRef::SF_Weak; 1100 bool Absolute = Flags & SymbolRef::SF_Absolute; 1101 bool Common = Flags & SymbolRef::SF_Common; 1102 bool Hidden = Flags & SymbolRef::SF_Hidden; 1103 1104 if (Common) 1105 Address = Symbol.getCommonSize(); 1106 1107 if (Address == UnknownAddress) 1108 Address = 0; 1109 char GlobLoc = ' '; 1110 if (Type != SymbolRef::ST_Unknown) 1111 GlobLoc = Global ? 'g' : 'l'; 1112 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1113 ? 'd' : ' '; 1114 char FileFunc = ' '; 1115 if (Type == SymbolRef::ST_File) 1116 FileFunc = 'f'; 1117 else if (Type == SymbolRef::ST_Function) 1118 FileFunc = 'F'; 1119 1120 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 1121 "%08" PRIx64; 1122 1123 outs() << format(Fmt, Address) << " " 1124 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1125 << (Weak ? 'w' : ' ') // Weak? 1126 << ' ' // Constructor. Not supported yet. 1127 << ' ' // Warning. Not supported yet. 1128 << ' ' // Indirect reference to another symbol. 1129 << Debug // Debugging (d) or dynamic (D) symbol. 1130 << FileFunc // Name of function (F), file (f) or object (O). 1131 << ' '; 1132 if (Absolute) { 1133 outs() << "*ABS*"; 1134 } else if (Common) { 1135 outs() << "*COM*"; 1136 } else if (Section == o->section_end()) { 1137 outs() << "*UND*"; 1138 } else { 1139 if (const MachOObjectFile *MachO = 1140 dyn_cast<const MachOObjectFile>(o)) { 1141 DataRefImpl DR = Section->getRawDataRefImpl(); 1142 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1143 outs() << SegmentName << ","; 1144 } 1145 StringRef SectionName; 1146 if (error(Section->getName(SectionName))) 1147 SectionName = ""; 1148 outs() << SectionName; 1149 } 1150 1151 outs() << '\t'; 1152 if (Common || isa<ELFObjectFileBase>(o)) { 1153 uint64_t Val = 1154 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1155 outs() << format("\t %08" PRIx64 " ", Val); 1156 } 1157 1158 if (Hidden) { 1159 outs() << ".hidden "; 1160 } 1161 outs() << Name 1162 << '\n'; 1163 } 1164 } 1165 1166 static void PrintUnwindInfo(const ObjectFile *o) { 1167 outs() << "Unwind info:\n\n"; 1168 1169 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 1170 printCOFFUnwindInfo(coff); 1171 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1172 printMachOUnwindInfo(MachO); 1173 else { 1174 // TODO: Extract DWARF dump tool to objdump. 1175 errs() << "This operation is only currently supported " 1176 "for COFF and MachO object files.\n"; 1177 return; 1178 } 1179 } 1180 1181 void llvm::printExportsTrie(const ObjectFile *o) { 1182 outs() << "Exports trie:\n"; 1183 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1184 printMachOExportsTrie(MachO); 1185 else { 1186 errs() << "This operation is only currently supported " 1187 "for Mach-O executable files.\n"; 1188 return; 1189 } 1190 } 1191 1192 void llvm::printRebaseTable(const ObjectFile *o) { 1193 outs() << "Rebase table:\n"; 1194 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1195 printMachORebaseTable(MachO); 1196 else { 1197 errs() << "This operation is only currently supported " 1198 "for Mach-O executable files.\n"; 1199 return; 1200 } 1201 } 1202 1203 void llvm::printBindTable(const ObjectFile *o) { 1204 outs() << "Bind table:\n"; 1205 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1206 printMachOBindTable(MachO); 1207 else { 1208 errs() << "This operation is only currently supported " 1209 "for Mach-O executable files.\n"; 1210 return; 1211 } 1212 } 1213 1214 void llvm::printLazyBindTable(const ObjectFile *o) { 1215 outs() << "Lazy bind table:\n"; 1216 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1217 printMachOLazyBindTable(MachO); 1218 else { 1219 errs() << "This operation is only currently supported " 1220 "for Mach-O executable files.\n"; 1221 return; 1222 } 1223 } 1224 1225 void llvm::printWeakBindTable(const ObjectFile *o) { 1226 outs() << "Weak bind table:\n"; 1227 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1228 printMachOWeakBindTable(MachO); 1229 else { 1230 errs() << "This operation is only currently supported " 1231 "for Mach-O executable files.\n"; 1232 return; 1233 } 1234 } 1235 1236 static void printFaultMaps(const ObjectFile *Obj) { 1237 const char *FaultMapSectionName = nullptr; 1238 1239 if (isa<ELFObjectFileBase>(Obj)) { 1240 FaultMapSectionName = ".llvm_faultmaps"; 1241 } else if (isa<MachOObjectFile>(Obj)) { 1242 FaultMapSectionName = "__llvm_faultmaps"; 1243 } else { 1244 errs() << "This operation is only currently supported " 1245 "for ELF and Mach-O executable files.\n"; 1246 return; 1247 } 1248 1249 Optional<object::SectionRef> FaultMapSection; 1250 1251 for (auto Sec : Obj->sections()) { 1252 StringRef Name; 1253 Sec.getName(Name); 1254 if (Name == FaultMapSectionName) { 1255 FaultMapSection = Sec; 1256 break; 1257 } 1258 } 1259 1260 outs() << "FaultMap table:\n"; 1261 1262 if (!FaultMapSection.hasValue()) { 1263 outs() << "<not found>\n"; 1264 return; 1265 } 1266 1267 StringRef FaultMapContents; 1268 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) { 1269 errs() << "Could not read the " << FaultMapContents << " section!\n"; 1270 return; 1271 } 1272 1273 FaultMapParser FMP(FaultMapContents.bytes_begin(), 1274 FaultMapContents.bytes_end()); 1275 1276 outs() << FMP; 1277 } 1278 1279 static void printPrivateFileHeader(const ObjectFile *o) { 1280 if (o->isELF()) { 1281 printELFFileHeader(o); 1282 } else if (o->isCOFF()) { 1283 printCOFFFileHeader(o); 1284 } else if (o->isMachO()) { 1285 printMachOFileHeader(o); 1286 } 1287 } 1288 1289 static void DumpObject(const ObjectFile *o) { 1290 outs() << '\n'; 1291 outs() << o->getFileName() 1292 << ":\tfile format " << o->getFileFormatName() << "\n\n"; 1293 1294 if (Disassemble) 1295 DisassembleObject(o, Relocations); 1296 if (Relocations && !Disassemble) 1297 PrintRelocations(o); 1298 if (SectionHeaders) 1299 PrintSectionHeaders(o); 1300 if (SectionContents) 1301 PrintSectionContents(o); 1302 if (SymbolTable) 1303 PrintSymbolTable(o); 1304 if (UnwindInfo) 1305 PrintUnwindInfo(o); 1306 if (PrivateHeaders) 1307 printPrivateFileHeader(o); 1308 if (ExportsTrie) 1309 printExportsTrie(o); 1310 if (Rebase) 1311 printRebaseTable(o); 1312 if (Bind) 1313 printBindTable(o); 1314 if (LazyBind) 1315 printLazyBindTable(o); 1316 if (WeakBind) 1317 printWeakBindTable(o); 1318 if (PrintFaultMaps) 1319 printFaultMaps(o); 1320 } 1321 1322 /// @brief Dump each object file in \a a; 1323 static void DumpArchive(const Archive *a) { 1324 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; 1325 ++i) { 1326 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); 1327 if (std::error_code EC = ChildOrErr.getError()) { 1328 // Ignore non-object files. 1329 if (EC != object_error::invalid_file_type) 1330 report_error(a->getFileName(), EC); 1331 continue; 1332 } 1333 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 1334 DumpObject(o); 1335 else 1336 report_error(a->getFileName(), object_error::invalid_file_type); 1337 } 1338 } 1339 1340 /// @brief Open file and figure out how to dump it. 1341 static void DumpInput(StringRef file) { 1342 // If file isn't stdin, check that it exists. 1343 if (file != "-" && !sys::fs::exists(file)) { 1344 report_error(file, errc::no_such_file_or_directory); 1345 return; 1346 } 1347 1348 // If we are using the Mach-O specific object file parser, then let it parse 1349 // the file and process the command line options. So the -arch flags can 1350 // be used to select specific slices, etc. 1351 if (MachOOpt) { 1352 ParseInputMachO(file); 1353 return; 1354 } 1355 1356 // Attempt to open the binary. 1357 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 1358 if (std::error_code EC = BinaryOrErr.getError()) { 1359 report_error(file, EC); 1360 return; 1361 } 1362 Binary &Binary = *BinaryOrErr.get().getBinary(); 1363 1364 if (Archive *a = dyn_cast<Archive>(&Binary)) 1365 DumpArchive(a); 1366 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 1367 DumpObject(o); 1368 else 1369 report_error(file, object_error::invalid_file_type); 1370 } 1371 1372 int main(int argc, char **argv) { 1373 // Print a stack trace if we signal out. 1374 sys::PrintStackTraceOnErrorSignal(); 1375 PrettyStackTraceProgram X(argc, argv); 1376 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 1377 1378 // Initialize targets and assembly printers/parsers. 1379 llvm::InitializeAllTargetInfos(); 1380 llvm::InitializeAllTargetMCs(); 1381 llvm::InitializeAllAsmParsers(); 1382 llvm::InitializeAllDisassemblers(); 1383 1384 // Register the target printer for --version. 1385 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 1386 1387 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 1388 TripleName = Triple::normalize(TripleName); 1389 1390 ToolName = argv[0]; 1391 1392 // Defaults to a.out if no filenames specified. 1393 if (InputFilenames.size() == 0) 1394 InputFilenames.push_back("a.out"); 1395 1396 if (!Disassemble 1397 && !Relocations 1398 && !SectionHeaders 1399 && !SectionContents 1400 && !SymbolTable 1401 && !UnwindInfo 1402 && !PrivateHeaders 1403 && !ExportsTrie 1404 && !Rebase 1405 && !Bind 1406 && !LazyBind 1407 && !WeakBind 1408 && !(UniversalHeaders && MachOOpt) 1409 && !(ArchiveHeaders && MachOOpt) 1410 && !(IndirectSymbols && MachOOpt) 1411 && !(DataInCode && MachOOpt) 1412 && !(LinkOptHints && MachOOpt) 1413 && !(InfoPlist && MachOOpt) 1414 && !(DylibsUsed && MachOOpt) 1415 && !(DylibId && MachOOpt) 1416 && !(ObjcMetaData && MachOOpt) 1417 && !(DumpSections.size() != 0 && MachOOpt) 1418 && !PrintFaultMaps) { 1419 cl::PrintHelpMessage(); 1420 return 2; 1421 } 1422 1423 std::for_each(InputFilenames.begin(), InputFilenames.end(), 1424 DumpInput); 1425 1426 return ReturnValue; 1427 } 1428