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/COFF.h" 36 #include "llvm/Object/MachO.h" 37 #include "llvm/Object/ObjectFile.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/FileSystem.h" 42 #include "llvm/Support/Format.h" 43 #include "llvm/Support/GraphWriter.h" 44 #include "llvm/Support/Host.h" 45 #include "llvm/Support/ManagedStatic.h" 46 #include "llvm/Support/MemoryBuffer.h" 47 #include "llvm/Support/PrettyStackTrace.h" 48 #include "llvm/Support/Signals.h" 49 #include "llvm/Support/SourceMgr.h" 50 #include "llvm/Support/TargetRegistry.h" 51 #include "llvm/Support/TargetSelect.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include <algorithm> 54 #include <cctype> 55 #include <cstring> 56 #include <system_error> 57 58 using namespace llvm; 59 using namespace object; 60 61 static cl::list<std::string> 62 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 63 64 cl::opt<bool> 65 llvm::Disassemble("disassemble", 66 cl::desc("Display assembler mnemonics for the machine instructions")); 67 static cl::alias 68 Disassembled("d", cl::desc("Alias for --disassemble"), 69 cl::aliasopt(Disassemble)); 70 71 cl::opt<bool> 72 llvm::Relocations("r", cl::desc("Display the relocation entries in the file")); 73 74 cl::opt<bool> 75 llvm::SectionContents("s", cl::desc("Display the content of each section")); 76 77 cl::opt<bool> 78 llvm::SymbolTable("t", cl::desc("Display the symbol table")); 79 80 cl::opt<bool> 81 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); 82 83 cl::opt<bool> 84 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info")); 85 86 cl::opt<bool> 87 llvm::Bind("bind", cl::desc("Display mach-o binding info")); 88 89 cl::opt<bool> 90 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); 91 92 cl::opt<bool> 93 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); 94 95 static cl::opt<bool> 96 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 97 static cl::alias 98 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt)); 99 100 cl::opt<std::string> 101 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 102 "see -version for available targets")); 103 104 cl::opt<std::string> 105 llvm::MCPU("mcpu", 106 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 107 cl::value_desc("cpu-name"), 108 cl::init("")); 109 110 cl::opt<std::string> 111 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, " 112 "see -version for available targets")); 113 114 cl::opt<bool> 115 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the " 116 "headers for each section.")); 117 static cl::alias 118 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), 119 cl::aliasopt(SectionHeaders)); 120 static cl::alias 121 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), 122 cl::aliasopt(SectionHeaders)); 123 124 cl::list<std::string> 125 llvm::MAttrs("mattr", 126 cl::CommaSeparated, 127 cl::desc("Target specific attributes"), 128 cl::value_desc("a1,+a2,-a3,...")); 129 130 cl::opt<bool> 131 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " 132 "instructions, do not print " 133 "the instruction bytes.")); 134 135 cl::opt<bool> 136 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information")); 137 138 static cl::alias 139 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 140 cl::aliasopt(UnwindInfo)); 141 142 cl::opt<bool> 143 llvm::PrivateHeaders("private-headers", 144 cl::desc("Display format specific file headers")); 145 146 static cl::alias 147 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"), 148 cl::aliasopt(PrivateHeaders)); 149 150 static StringRef ToolName; 151 static int ReturnValue = EXIT_SUCCESS; 152 153 bool llvm::error(std::error_code EC) { 154 if (!EC) 155 return false; 156 157 outs() << ToolName << ": error reading file: " << EC.message() << ".\n"; 158 outs().flush(); 159 ReturnValue = EXIT_FAILURE; 160 return true; 161 } 162 163 static const Target *getTarget(const ObjectFile *Obj = nullptr) { 164 // Figure out the target triple. 165 llvm::Triple TheTriple("unknown-unknown-unknown"); 166 if (TripleName.empty()) { 167 if (Obj) { 168 TheTriple.setArch(Triple::ArchType(Obj->getArch())); 169 // TheTriple defaults to ELF, and COFF doesn't have an environment: 170 // the best we can do here is indicate that it is mach-o. 171 if (Obj->isMachO()) 172 TheTriple.setObjectFormat(Triple::MachO); 173 174 if (Obj->isCOFF()) { 175 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj); 176 if (COFFObj->getArch() == Triple::thumb) 177 TheTriple.setTriple("thumbv7-windows"); 178 } 179 } 180 } else 181 TheTriple.setTriple(Triple::normalize(TripleName)); 182 183 // Get the target specific parser. 184 std::string Error; 185 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 186 Error); 187 if (!TheTarget) { 188 errs() << ToolName << ": " << Error; 189 return nullptr; 190 } 191 192 // Update the triple name and return the found target. 193 TripleName = TheTriple.getTriple(); 194 return TheTarget; 195 } 196 197 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { 198 uint64_t a_addr, b_addr; 199 if (error(a.getOffset(a_addr))) return false; 200 if (error(b.getOffset(b_addr))) return false; 201 return a_addr < b_addr; 202 } 203 204 namespace { 205 class PrettyPrinter { 206 public: 207 virtual void printInst(MCInstPrinter &IP, const MCInst *MI, bool ShowRawInsn, 208 ArrayRef<uint8_t> Bytes, uint64_t Address, 209 raw_ostream &OS, StringRef Annot, 210 MCSubtargetInfo const &STI) { 211 outs() << format("%8" PRIx64 ":", Address); 212 if (!NoShowRawInsn) { 213 outs() << "\t"; 214 dumpBytes(Bytes, outs()); 215 } 216 IP.printInst(MI, outs(), "", STI); 217 } 218 }; 219 PrettyPrinter PrettyPrinterInst; 220 PrettyPrinter &selectPrettyPrinter(Triple const &Triple, MCInstPrinter &IP) { 221 switch(Triple.getArch()) { 222 default: 223 return PrettyPrinterInst; 224 } 225 } 226 } 227 228 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 229 const Target *TheTarget = getTarget(Obj); 230 // getTarget() will have already issued a diagnostic if necessary, so 231 // just bail here if it failed. 232 if (!TheTarget) 233 return; 234 235 // Package up features to be passed to target/subtarget 236 std::string FeaturesStr; 237 if (MAttrs.size()) { 238 SubtargetFeatures Features; 239 for (unsigned i = 0; i != MAttrs.size(); ++i) 240 Features.AddFeature(MAttrs[i]); 241 FeaturesStr = Features.getString(); 242 } 243 244 std::unique_ptr<const MCRegisterInfo> MRI( 245 TheTarget->createMCRegInfo(TripleName)); 246 if (!MRI) { 247 errs() << "error: no register info for target " << TripleName << "\n"; 248 return; 249 } 250 251 // Set up disassembler. 252 std::unique_ptr<const MCAsmInfo> AsmInfo( 253 TheTarget->createMCAsmInfo(*MRI, TripleName)); 254 if (!AsmInfo) { 255 errs() << "error: no assembly info for target " << TripleName << "\n"; 256 return; 257 } 258 259 std::unique_ptr<const MCSubtargetInfo> STI( 260 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); 261 if (!STI) { 262 errs() << "error: no subtarget info for target " << TripleName << "\n"; 263 return; 264 } 265 266 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 267 if (!MII) { 268 errs() << "error: no instruction info for target " << TripleName << "\n"; 269 return; 270 } 271 272 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); 273 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); 274 275 std::unique_ptr<MCDisassembler> DisAsm( 276 TheTarget->createMCDisassembler(*STI, Ctx)); 277 278 if (!DisAsm) { 279 errs() << "error: no disassembler for target " << TripleName << "\n"; 280 return; 281 } 282 283 std::unique_ptr<const MCInstrAnalysis> MIA( 284 TheTarget->createMCInstrAnalysis(MII.get())); 285 286 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 287 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 288 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 289 if (!IP) { 290 errs() << "error: no instruction printer for target " << TripleName 291 << '\n'; 292 return; 293 } 294 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName), *IP); 295 296 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " : 297 "\t\t\t%08" PRIx64 ": "; 298 299 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections 300 // in RelocSecs contain the relocations for section S. 301 std::error_code EC; 302 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; 303 for (const SectionRef &Section : Obj->sections()) { 304 section_iterator Sec2 = Section.getRelocatedSection(); 305 if (Sec2 != Obj->section_end()) 306 SectionRelocMap[*Sec2].push_back(Section); 307 } 308 309 for (const SectionRef &Section : Obj->sections()) { 310 if (!Section.isText() || Section.isVirtual()) 311 continue; 312 313 uint64_t SectionAddr = Section.getAddress(); 314 uint64_t SectSize = Section.getSize(); 315 if (!SectSize) 316 continue; 317 318 // Make a list of all the symbols in this section. 319 std::vector<std::pair<uint64_t, StringRef>> Symbols; 320 for (const SymbolRef &Symbol : Obj->symbols()) { 321 if (Section.containsSymbol(Symbol)) { 322 uint64_t Address; 323 if (error(Symbol.getAddress(Address))) 324 break; 325 if (Address == UnknownAddressOrSize) 326 continue; 327 Address -= SectionAddr; 328 if (Address >= SectSize) 329 continue; 330 331 StringRef Name; 332 if (error(Symbol.getName(Name))) 333 break; 334 Symbols.push_back(std::make_pair(Address, Name)); 335 } 336 } 337 338 // Sort the symbols by address, just in case they didn't come in that way. 339 array_pod_sort(Symbols.begin(), Symbols.end()); 340 341 // Make a list of all the relocations for this section. 342 std::vector<RelocationRef> Rels; 343 if (InlineRelocs) { 344 for (const SectionRef &RelocSec : SectionRelocMap[Section]) { 345 for (const RelocationRef &Reloc : RelocSec.relocations()) { 346 Rels.push_back(Reloc); 347 } 348 } 349 } 350 351 // Sort relocations by address. 352 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 353 354 StringRef SegmentName = ""; 355 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 356 DataRefImpl DR = Section.getRawDataRefImpl(); 357 SegmentName = MachO->getSectionFinalSegmentName(DR); 358 } 359 StringRef name; 360 if (error(Section.getName(name))) 361 break; 362 outs() << "Disassembly of section "; 363 if (!SegmentName.empty()) 364 outs() << SegmentName << ","; 365 outs() << name << ':'; 366 367 // If the section has no symbols just insert a dummy one and disassemble 368 // the whole section. 369 if (Symbols.empty()) 370 Symbols.push_back(std::make_pair(0, name)); 371 372 373 SmallString<40> Comments; 374 raw_svector_ostream CommentStream(Comments); 375 376 StringRef BytesStr; 377 if (error(Section.getContents(BytesStr))) 378 break; 379 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 380 BytesStr.size()); 381 382 uint64_t Size; 383 uint64_t Index; 384 385 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 386 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 387 // Disassemble symbol by symbol. 388 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 389 390 uint64_t Start = Symbols[si].first; 391 // The end is either the section end or the beginning of the next symbol. 392 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first; 393 // If this symbol has the same address as the next symbol, then skip it. 394 if (Start == End) 395 continue; 396 397 outs() << '\n' << Symbols[si].second << ":\n"; 398 399 #ifndef NDEBUG 400 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 401 #else 402 raw_ostream &DebugOut = nulls(); 403 #endif 404 405 for (Index = Start; Index < End; Index += Size) { 406 MCInst Inst; 407 408 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 409 SectionAddr + Index, DebugOut, 410 CommentStream)) { 411 PIP.printInst(*IP, &Inst, !NoShowRawInsn, 412 Bytes.slice(Index, Size), 413 SectionAddr + Index, outs(), "", *STI); 414 outs() << CommentStream.str(); 415 Comments.clear(); 416 outs() << "\n"; 417 } else { 418 errs() << ToolName << ": warning: invalid instruction encoding\n"; 419 if (Size == 0) 420 Size = 1; // skip illegible bytes 421 } 422 423 // Print relocation for instruction. 424 while (rel_cur != rel_end) { 425 bool hidden = false; 426 uint64_t addr; 427 SmallString<16> name; 428 SmallString<32> val; 429 430 // If this relocation is hidden, skip it. 431 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel; 432 if (hidden) goto skip_print_rel; 433 434 if (error(rel_cur->getOffset(addr))) goto skip_print_rel; 435 // Stop when rel_cur's address is past the current instruction. 436 if (addr >= Index + Size) break; 437 if (error(rel_cur->getTypeName(name))) goto skip_print_rel; 438 if (error(rel_cur->getValueString(val))) goto skip_print_rel; 439 440 outs() << format(Fmt.data(), SectionAddr + addr) << name 441 << "\t" << val << "\n"; 442 443 skip_print_rel: 444 ++rel_cur; 445 } 446 } 447 } 448 } 449 } 450 451 void llvm::PrintRelocations(const ObjectFile *Obj) { 452 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 453 "%08" PRIx64; 454 // Regular objdump doesn't print relocations in non-relocatable object 455 // files. 456 if (!Obj->isRelocatableObject()) 457 return; 458 459 for (const SectionRef &Section : Obj->sections()) { 460 if (Section.relocation_begin() == Section.relocation_end()) 461 continue; 462 StringRef secname; 463 if (error(Section.getName(secname))) 464 continue; 465 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 466 for (const RelocationRef &Reloc : Section.relocations()) { 467 bool hidden; 468 uint64_t address; 469 SmallString<32> relocname; 470 SmallString<32> valuestr; 471 if (error(Reloc.getHidden(hidden))) 472 continue; 473 if (hidden) 474 continue; 475 if (error(Reloc.getTypeName(relocname))) 476 continue; 477 if (error(Reloc.getOffset(address))) 478 continue; 479 if (error(Reloc.getValueString(valuestr))) 480 continue; 481 outs() << format(Fmt.data(), address) << " " << relocname << " " 482 << valuestr << "\n"; 483 } 484 outs() << "\n"; 485 } 486 } 487 488 void llvm::PrintSectionHeaders(const ObjectFile *Obj) { 489 outs() << "Sections:\n" 490 "Idx Name Size Address Type\n"; 491 unsigned i = 0; 492 for (const SectionRef &Section : Obj->sections()) { 493 StringRef Name; 494 if (error(Section.getName(Name))) 495 return; 496 uint64_t Address = Section.getAddress(); 497 uint64_t Size = Section.getSize(); 498 bool Text = Section.isText(); 499 bool Data = Section.isData(); 500 bool BSS = Section.isBSS(); 501 std::string Type = (std::string(Text ? "TEXT " : "") + 502 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 503 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, 504 Name.str().c_str(), Size, Address, Type.c_str()); 505 ++i; 506 } 507 } 508 509 void llvm::PrintSectionContents(const ObjectFile *Obj) { 510 std::error_code EC; 511 for (const SectionRef &Section : Obj->sections()) { 512 StringRef Name; 513 StringRef Contents; 514 if (error(Section.getName(Name))) 515 continue; 516 uint64_t BaseAddr = Section.getAddress(); 517 uint64_t Size = Section.getSize(); 518 if (!Size) 519 continue; 520 521 outs() << "Contents of section " << Name << ":\n"; 522 if (Section.isBSS()) { 523 outs() << format("<skipping contents of bss section at [%04" PRIx64 524 ", %04" PRIx64 ")>\n", 525 BaseAddr, BaseAddr + Size); 526 continue; 527 } 528 529 if (error(Section.getContents(Contents))) 530 continue; 531 532 // Dump out the content as hex and printable ascii characters. 533 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 534 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 535 // Dump line of hex. 536 for (std::size_t i = 0; i < 16; ++i) { 537 if (i != 0 && i % 4 == 0) 538 outs() << ' '; 539 if (addr + i < end) 540 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 541 << hexdigit(Contents[addr + i] & 0xF, true); 542 else 543 outs() << " "; 544 } 545 // Print ascii. 546 outs() << " "; 547 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 548 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 549 outs() << Contents[addr + i]; 550 else 551 outs() << "."; 552 } 553 outs() << "\n"; 554 } 555 } 556 } 557 558 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) { 559 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) { 560 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI); 561 StringRef Name; 562 if (error(Symbol.getError())) 563 return; 564 565 if (error(coff->getSymbolName(*Symbol, Name))) 566 return; 567 568 outs() << "[" << format("%2d", SI) << "]" 569 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")" 570 << "(fl 0x00)" // Flag bits, which COFF doesn't have. 571 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")" 572 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") " 573 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") " 574 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " " 575 << Name << "\n"; 576 577 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) { 578 if (Symbol->isSectionDefinition()) { 579 const coff_aux_section_definition *asd; 580 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))) 581 return; 582 583 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj()); 584 585 outs() << "AUX " 586 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x " 587 , unsigned(asd->Length) 588 , unsigned(asd->NumberOfRelocations) 589 , unsigned(asd->NumberOfLinenumbers) 590 , unsigned(asd->CheckSum)) 591 << format("assoc %d comdat %d\n" 592 , unsigned(AuxNumber) 593 , unsigned(asd->Selection)); 594 } else if (Symbol->isFileRecord()) { 595 const char *FileName; 596 if (error(coff->getAuxSymbol<char>(SI + 1, FileName))) 597 return; 598 599 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() * 600 coff->getSymbolTableEntrySize()); 601 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n'; 602 603 SI = SI + Symbol->getNumberOfAuxSymbols(); 604 break; 605 } else { 606 outs() << "AUX Unknown\n"; 607 } 608 } 609 } 610 } 611 612 void llvm::PrintSymbolTable(const ObjectFile *o) { 613 outs() << "SYMBOL TABLE:\n"; 614 615 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 616 PrintCOFFSymbolTable(coff); 617 return; 618 } 619 for (const SymbolRef &Symbol : o->symbols()) { 620 StringRef Name; 621 uint64_t Address; 622 SymbolRef::Type Type; 623 uint64_t Size; 624 uint32_t Flags = Symbol.getFlags(); 625 section_iterator Section = o->section_end(); 626 if (error(Symbol.getName(Name))) 627 continue; 628 if (error(Symbol.getAddress(Address))) 629 continue; 630 if (error(Symbol.getType(Type))) 631 continue; 632 if (error(Symbol.getSize(Size))) 633 continue; 634 if (error(Symbol.getSection(Section))) 635 continue; 636 637 bool Global = Flags & SymbolRef::SF_Global; 638 bool Weak = Flags & SymbolRef::SF_Weak; 639 bool Absolute = Flags & SymbolRef::SF_Absolute; 640 bool Common = Flags & SymbolRef::SF_Common; 641 bool Hidden = Flags & SymbolRef::SF_Hidden; 642 643 if (Common) { 644 uint32_t Alignment; 645 if (error(Symbol.getAlignment(Alignment))) 646 Alignment = 0; 647 Address = Size; 648 Size = Alignment; 649 } 650 if (Address == UnknownAddressOrSize) 651 Address = 0; 652 if (Size == UnknownAddressOrSize) 653 Size = 0; 654 char GlobLoc = ' '; 655 if (Type != SymbolRef::ST_Unknown) 656 GlobLoc = Global ? 'g' : 'l'; 657 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 658 ? 'd' : ' '; 659 char FileFunc = ' '; 660 if (Type == SymbolRef::ST_File) 661 FileFunc = 'f'; 662 else if (Type == SymbolRef::ST_Function) 663 FileFunc = 'F'; 664 665 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 666 "%08" PRIx64; 667 668 outs() << format(Fmt, Address) << " " 669 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 670 << (Weak ? 'w' : ' ') // Weak? 671 << ' ' // Constructor. Not supported yet. 672 << ' ' // Warning. Not supported yet. 673 << ' ' // Indirect reference to another symbol. 674 << Debug // Debugging (d) or dynamic (D) symbol. 675 << FileFunc // Name of function (F), file (f) or object (O). 676 << ' '; 677 if (Absolute) { 678 outs() << "*ABS*"; 679 } else if (Common) { 680 outs() << "*COM*"; 681 } else if (Section == o->section_end()) { 682 outs() << "*UND*"; 683 } else { 684 if (const MachOObjectFile *MachO = 685 dyn_cast<const MachOObjectFile>(o)) { 686 DataRefImpl DR = Section->getRawDataRefImpl(); 687 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 688 outs() << SegmentName << ","; 689 } 690 StringRef SectionName; 691 if (error(Section->getName(SectionName))) 692 SectionName = ""; 693 outs() << SectionName; 694 } 695 outs() << '\t' 696 << format("%08" PRIx64 " ", Size); 697 if (Hidden) { 698 outs() << ".hidden "; 699 } 700 outs() << Name 701 << '\n'; 702 } 703 } 704 705 static void PrintUnwindInfo(const ObjectFile *o) { 706 outs() << "Unwind info:\n\n"; 707 708 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 709 printCOFFUnwindInfo(coff); 710 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 711 printMachOUnwindInfo(MachO); 712 else { 713 // TODO: Extract DWARF dump tool to objdump. 714 errs() << "This operation is only currently supported " 715 "for COFF and MachO object files.\n"; 716 return; 717 } 718 } 719 720 void llvm::printExportsTrie(const ObjectFile *o) { 721 outs() << "Exports trie:\n"; 722 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 723 printMachOExportsTrie(MachO); 724 else { 725 errs() << "This operation is only currently supported " 726 "for Mach-O executable files.\n"; 727 return; 728 } 729 } 730 731 void llvm::printRebaseTable(const ObjectFile *o) { 732 outs() << "Rebase table:\n"; 733 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 734 printMachORebaseTable(MachO); 735 else { 736 errs() << "This operation is only currently supported " 737 "for Mach-O executable files.\n"; 738 return; 739 } 740 } 741 742 void llvm::printBindTable(const ObjectFile *o) { 743 outs() << "Bind table:\n"; 744 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 745 printMachOBindTable(MachO); 746 else { 747 errs() << "This operation is only currently supported " 748 "for Mach-O executable files.\n"; 749 return; 750 } 751 } 752 753 void llvm::printLazyBindTable(const ObjectFile *o) { 754 outs() << "Lazy bind table:\n"; 755 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 756 printMachOLazyBindTable(MachO); 757 else { 758 errs() << "This operation is only currently supported " 759 "for Mach-O executable files.\n"; 760 return; 761 } 762 } 763 764 void llvm::printWeakBindTable(const ObjectFile *o) { 765 outs() << "Weak bind table:\n"; 766 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 767 printMachOWeakBindTable(MachO); 768 else { 769 errs() << "This operation is only currently supported " 770 "for Mach-O executable files.\n"; 771 return; 772 } 773 } 774 775 static void printPrivateFileHeader(const ObjectFile *o) { 776 if (o->isELF()) { 777 printELFFileHeader(o); 778 } else if (o->isCOFF()) { 779 printCOFFFileHeader(o); 780 } else if (o->isMachO()) { 781 printMachOFileHeader(o); 782 } 783 } 784 785 static void DumpObject(const ObjectFile *o) { 786 outs() << '\n'; 787 outs() << o->getFileName() 788 << ":\tfile format " << o->getFileFormatName() << "\n\n"; 789 790 if (Disassemble) 791 DisassembleObject(o, Relocations); 792 if (Relocations && !Disassemble) 793 PrintRelocations(o); 794 if (SectionHeaders) 795 PrintSectionHeaders(o); 796 if (SectionContents) 797 PrintSectionContents(o); 798 if (SymbolTable) 799 PrintSymbolTable(o); 800 if (UnwindInfo) 801 PrintUnwindInfo(o); 802 if (PrivateHeaders) 803 printPrivateFileHeader(o); 804 if (ExportsTrie) 805 printExportsTrie(o); 806 if (Rebase) 807 printRebaseTable(o); 808 if (Bind) 809 printBindTable(o); 810 if (LazyBind) 811 printLazyBindTable(o); 812 if (WeakBind) 813 printWeakBindTable(o); 814 } 815 816 /// @brief Dump each object file in \a a; 817 static void DumpArchive(const Archive *a) { 818 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; 819 ++i) { 820 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); 821 if (std::error_code EC = ChildOrErr.getError()) { 822 // Ignore non-object files. 823 if (EC != object_error::invalid_file_type) 824 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message() 825 << ".\n"; 826 continue; 827 } 828 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 829 DumpObject(o); 830 else 831 errs() << ToolName << ": '" << a->getFileName() << "': " 832 << "Unrecognized file type.\n"; 833 } 834 } 835 836 /// @brief Open file and figure out how to dump it. 837 static void DumpInput(StringRef file) { 838 // If file isn't stdin, check that it exists. 839 if (file != "-" && !sys::fs::exists(file)) { 840 errs() << ToolName << ": '" << file << "': " << "No such file\n"; 841 return; 842 } 843 844 // If we are using the Mach-O specific object file parser, then let it parse 845 // the file and process the command line options. So the -arch flags can 846 // be used to select specific slices, etc. 847 if (MachOOpt) { 848 ParseInputMachO(file); 849 return; 850 } 851 852 // Attempt to open the binary. 853 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 854 if (std::error_code EC = BinaryOrErr.getError()) { 855 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n"; 856 return; 857 } 858 Binary &Binary = *BinaryOrErr.get().getBinary(); 859 860 if (Archive *a = dyn_cast<Archive>(&Binary)) 861 DumpArchive(a); 862 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 863 DumpObject(o); 864 else 865 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; 866 } 867 868 int main(int argc, char **argv) { 869 // Print a stack trace if we signal out. 870 sys::PrintStackTraceOnErrorSignal(); 871 PrettyStackTraceProgram X(argc, argv); 872 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 873 874 // Initialize targets and assembly printers/parsers. 875 llvm::InitializeAllTargetInfos(); 876 llvm::InitializeAllTargetMCs(); 877 llvm::InitializeAllAsmParsers(); 878 llvm::InitializeAllDisassemblers(); 879 880 // Register the target printer for --version. 881 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 882 883 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 884 TripleName = Triple::normalize(TripleName); 885 886 ToolName = argv[0]; 887 888 // Defaults to a.out if no filenames specified. 889 if (InputFilenames.size() == 0) 890 InputFilenames.push_back("a.out"); 891 892 if (!Disassemble 893 && !Relocations 894 && !SectionHeaders 895 && !SectionContents 896 && !SymbolTable 897 && !UnwindInfo 898 && !PrivateHeaders 899 && !ExportsTrie 900 && !Rebase 901 && !Bind 902 && !LazyBind 903 && !WeakBind 904 && !(UniversalHeaders && MachOOpt) 905 && !(ArchiveHeaders && MachOOpt) 906 && !(IndirectSymbols && MachOOpt) 907 && !(DataInCode && MachOOpt) 908 && !(LinkOptHints && MachOOpt) 909 && !(InfoPlist && MachOOpt) 910 && !(DylibsUsed && MachOOpt) 911 && !(DylibId && MachOOpt) 912 && !(ObjcMetaData && MachOOpt) 913 && !(DumpSections.size() != 0 && MachOOpt)) { 914 cl::PrintHelpMessage(); 915 return 2; 916 } 917 918 std::for_each(InputFilenames.begin(), InputFilenames.end(), 919 DumpInput); 920 921 return ReturnValue; 922 } 923