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