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