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