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