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