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