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/MemoryObject.h" 48 #include "llvm/Support/PrettyStackTrace.h" 49 #include "llvm/Support/Signals.h" 50 #include "llvm/Support/SourceMgr.h" 51 #include "llvm/Support/TargetRegistry.h" 52 #include "llvm/Support/TargetSelect.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include <algorithm> 55 #include <cctype> 56 #include <cstring> 57 #include <system_error> 58 59 using namespace llvm; 60 using namespace object; 61 62 static cl::list<std::string> 63 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 64 65 static cl::opt<bool> 66 Disassemble("disassemble", 67 cl::desc("Display assembler mnemonics for the machine instructions")); 68 static cl::alias 69 Disassembled("d", cl::desc("Alias for --disassemble"), 70 cl::aliasopt(Disassemble)); 71 72 static cl::opt<bool> 73 Relocations("r", cl::desc("Display the relocation entries in the file")); 74 75 static cl::opt<bool> 76 SectionContents("s", cl::desc("Display the content of each section")); 77 78 static cl::opt<bool> 79 SymbolTable("t", cl::desc("Display the symbol table")); 80 81 static cl::opt<bool> 82 ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); 83 84 static cl::opt<bool> 85 Rebase("rebase", cl::desc("Display mach-o rebasing info")); 86 87 static cl::opt<bool> 88 Bind("bind", cl::desc("Display mach-o binding info")); 89 90 static cl::opt<bool> 91 LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); 92 93 static cl::opt<bool> 94 WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); 95 96 static cl::opt<bool> 97 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 98 static cl::alias 99 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt)); 100 101 cl::opt<std::string> 102 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 103 "see -version for available targets")); 104 105 cl::opt<std::string> 106 llvm::MCPU("mcpu", 107 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 108 cl::value_desc("cpu-name"), 109 cl::init("")); 110 111 cl::opt<std::string> 112 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, " 113 "see -version for available targets")); 114 115 static cl::opt<bool> 116 SectionHeaders("section-headers", cl::desc("Display summaries of the headers " 117 "for each section.")); 118 static cl::alias 119 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), 120 cl::aliasopt(SectionHeaders)); 121 static cl::alias 122 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), 123 cl::aliasopt(SectionHeaders)); 124 125 cl::list<std::string> 126 llvm::MAttrs("mattr", 127 cl::CommaSeparated, 128 cl::desc("Target specific attributes"), 129 cl::value_desc("a1,+a2,-a3,...")); 130 131 cl::opt<bool> 132 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " 133 "instructions, do not print " 134 "the instruction bytes.")); 135 136 static cl::opt<bool> 137 UnwindInfo("unwind-info", cl::desc("Display unwind information")); 138 139 static cl::alias 140 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 141 cl::aliasopt(UnwindInfo)); 142 143 static cl::opt<bool> 144 PrivateHeaders("private-headers", 145 cl::desc("Display format specific file headers")); 146 147 static cl::alias 148 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"), 149 cl::aliasopt(PrivateHeaders)); 150 151 static StringRef ToolName; 152 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 return true; 160 } 161 162 static const Target *getTarget(const ObjectFile *Obj = nullptr) { 163 // Figure out the target triple. 164 llvm::Triple TheTriple("unknown-unknown-unknown"); 165 if (TripleName.empty()) { 166 if (Obj) { 167 TheTriple.setArch(Triple::ArchType(Obj->getArch())); 168 // TheTriple defaults to ELF, and COFF doesn't have an environment: 169 // the best we can do here is indicate that it is mach-o. 170 if (Obj->isMachO()) 171 TheTriple.setObjectFormat(Triple::MachO); 172 173 if (Obj->isCOFF()) { 174 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj); 175 if (COFFObj->getArch() == Triple::thumb) 176 TheTriple.setTriple("thumbv7-windows"); 177 } 178 } 179 } else 180 TheTriple.setTriple(Triple::normalize(TripleName)); 181 182 // Get the target specific parser. 183 std::string Error; 184 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 185 Error); 186 if (!TheTarget) { 187 errs() << ToolName << ": " << Error; 188 return nullptr; 189 } 190 191 // Update the triple name and return the found target. 192 TripleName = TheTriple.getTriple(); 193 return TheTarget; 194 } 195 196 void llvm::DumpBytes(StringRef bytes) { 197 static const char hex_rep[] = "0123456789abcdef"; 198 // FIXME: The real way to do this is to figure out the longest instruction 199 // and align to that size before printing. I'll fix this when I get 200 // around to outputting relocations. 201 // 15 is the longest x86 instruction 202 // 3 is for the hex rep of a byte + a space. 203 // 1 is for the null terminator. 204 enum { OutputSize = (15 * 3) + 1 }; 205 char output[OutputSize]; 206 207 assert(bytes.size() <= 15 208 && "DumpBytes only supports instructions of up to 15 bytes"); 209 memset(output, ' ', sizeof(output)); 210 unsigned index = 0; 211 for (StringRef::iterator i = bytes.begin(), 212 e = bytes.end(); i != e; ++i) { 213 output[index] = hex_rep[(*i & 0xF0) >> 4]; 214 output[index + 1] = hex_rep[*i & 0xF]; 215 index += 3; 216 } 217 218 output[sizeof(output) - 1] = 0; 219 outs() << output; 220 } 221 222 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { 223 uint64_t a_addr, b_addr; 224 if (error(a.getOffset(a_addr))) return false; 225 if (error(b.getOffset(b_addr))) return false; 226 return a_addr < b_addr; 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 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI)); 290 if (!IP) { 291 errs() << "error: no instruction printer for target " << TripleName 292 << '\n'; 293 return; 294 } 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 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 412 if (!NoShowRawInsn) { 413 outs() << "\t"; 414 DumpBytes(StringRef( 415 reinterpret_cast<const char *>(Bytes.data()) + Index, Size)); 416 } 417 IP->printInst(&Inst, outs(), ""); 418 outs() << CommentStream.str(); 419 Comments.clear(); 420 outs() << "\n"; 421 } else { 422 errs() << ToolName << ": warning: invalid instruction encoding\n"; 423 if (Size == 0) 424 Size = 1; // skip illegible bytes 425 } 426 427 // Print relocation for instruction. 428 while (rel_cur != rel_end) { 429 bool hidden = false; 430 uint64_t addr; 431 SmallString<16> name; 432 SmallString<32> val; 433 434 // If this relocation is hidden, skip it. 435 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel; 436 if (hidden) goto skip_print_rel; 437 438 if (error(rel_cur->getOffset(addr))) goto skip_print_rel; 439 // Stop when rel_cur's address is past the current instruction. 440 if (addr >= Index + Size) break; 441 if (error(rel_cur->getTypeName(name))) goto skip_print_rel; 442 if (error(rel_cur->getValueString(val))) goto skip_print_rel; 443 444 outs() << format(Fmt.data(), SectionAddr + addr) << name 445 << "\t" << val << "\n"; 446 447 skip_print_rel: 448 ++rel_cur; 449 } 450 } 451 } 452 } 453 } 454 455 static void PrintRelocations(const ObjectFile *Obj) { 456 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 457 "%08" PRIx64; 458 // Regular objdump doesn't print relocations in non-relocatable object 459 // files. 460 if (!Obj->isRelocatableObject()) 461 return; 462 463 for (const SectionRef &Section : Obj->sections()) { 464 if (Section.relocation_begin() == Section.relocation_end()) 465 continue; 466 StringRef secname; 467 if (error(Section.getName(secname))) 468 continue; 469 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 470 for (const RelocationRef &Reloc : Section.relocations()) { 471 bool hidden; 472 uint64_t address; 473 SmallString<32> relocname; 474 SmallString<32> valuestr; 475 if (error(Reloc.getHidden(hidden))) 476 continue; 477 if (hidden) 478 continue; 479 if (error(Reloc.getTypeName(relocname))) 480 continue; 481 if (error(Reloc.getOffset(address))) 482 continue; 483 if (error(Reloc.getValueString(valuestr))) 484 continue; 485 outs() << format(Fmt.data(), address) << " " << relocname << " " 486 << valuestr << "\n"; 487 } 488 outs() << "\n"; 489 } 490 } 491 492 static void PrintSectionHeaders(const ObjectFile *Obj) { 493 outs() << "Sections:\n" 494 "Idx Name Size Address Type\n"; 495 unsigned i = 0; 496 for (const SectionRef &Section : Obj->sections()) { 497 StringRef Name; 498 if (error(Section.getName(Name))) 499 return; 500 uint64_t Address = Section.getAddress(); 501 uint64_t Size = Section.getSize(); 502 bool Text = Section.isText(); 503 bool Data = Section.isData(); 504 bool BSS = Section.isBSS(); 505 std::string Type = (std::string(Text ? "TEXT " : "") + 506 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 507 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, 508 Name.str().c_str(), Size, Address, Type.c_str()); 509 ++i; 510 } 511 } 512 513 static void PrintSectionContents(const ObjectFile *Obj) { 514 std::error_code EC; 515 for (const SectionRef &Section : Obj->sections()) { 516 StringRef Name; 517 StringRef Contents; 518 if (error(Section.getName(Name))) 519 continue; 520 uint64_t BaseAddr = Section.getAddress(); 521 uint64_t Size = Section.getSize(); 522 if (!Size) 523 continue; 524 525 outs() << "Contents of section " << Name << ":\n"; 526 if (Section.isBSS()) { 527 outs() << format("<skipping contents of bss section at [%04" PRIx64 528 ", %04" PRIx64 ")>\n", 529 BaseAddr, BaseAddr + Size); 530 continue; 531 } 532 533 if (error(Section.getContents(Contents))) 534 continue; 535 536 // Dump out the content as hex and printable ascii characters. 537 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 538 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 539 // Dump line of hex. 540 for (std::size_t i = 0; i < 16; ++i) { 541 if (i != 0 && i % 4 == 0) 542 outs() << ' '; 543 if (addr + i < end) 544 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 545 << hexdigit(Contents[addr + i] & 0xF, true); 546 else 547 outs() << " "; 548 } 549 // Print ascii. 550 outs() << " "; 551 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 552 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 553 outs() << Contents[addr + i]; 554 else 555 outs() << "."; 556 } 557 outs() << "\n"; 558 } 559 } 560 } 561 562 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) { 563 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) { 564 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI); 565 StringRef Name; 566 if (error(Symbol.getError())) 567 return; 568 569 if (error(coff->getSymbolName(*Symbol, Name))) 570 return; 571 572 outs() << "[" << format("%2d", SI) << "]" 573 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")" 574 << "(fl 0x00)" // Flag bits, which COFF doesn't have. 575 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")" 576 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") " 577 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") " 578 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " " 579 << Name << "\n"; 580 581 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) { 582 if (Symbol->isSectionDefinition()) { 583 const coff_aux_section_definition *asd; 584 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))) 585 return; 586 587 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj()); 588 589 outs() << "AUX " 590 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x " 591 , unsigned(asd->Length) 592 , unsigned(asd->NumberOfRelocations) 593 , unsigned(asd->NumberOfLinenumbers) 594 , unsigned(asd->CheckSum)) 595 << format("assoc %d comdat %d\n" 596 , unsigned(AuxNumber) 597 , unsigned(asd->Selection)); 598 } else if (Symbol->isFileRecord()) { 599 const char *FileName; 600 if (error(coff->getAuxSymbol<char>(SI + 1, FileName))) 601 return; 602 603 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() * 604 coff->getSymbolTableEntrySize()); 605 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n'; 606 607 SI = SI + Symbol->getNumberOfAuxSymbols(); 608 break; 609 } else { 610 outs() << "AUX Unknown\n"; 611 } 612 } 613 } 614 } 615 616 static void PrintSymbolTable(const ObjectFile *o) { 617 outs() << "SYMBOL TABLE:\n"; 618 619 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 620 PrintCOFFSymbolTable(coff); 621 return; 622 } 623 for (const SymbolRef &Symbol : o->symbols()) { 624 StringRef Name; 625 uint64_t Address; 626 SymbolRef::Type Type; 627 uint64_t Size; 628 uint32_t Flags = Symbol.getFlags(); 629 section_iterator Section = o->section_end(); 630 if (error(Symbol.getName(Name))) 631 continue; 632 if (error(Symbol.getAddress(Address))) 633 continue; 634 if (error(Symbol.getType(Type))) 635 continue; 636 if (error(Symbol.getSize(Size))) 637 continue; 638 if (error(Symbol.getSection(Section))) 639 continue; 640 641 bool Global = Flags & SymbolRef::SF_Global; 642 bool Weak = Flags & SymbolRef::SF_Weak; 643 bool Absolute = Flags & SymbolRef::SF_Absolute; 644 645 if (Address == UnknownAddressOrSize) 646 Address = 0; 647 if (Size == UnknownAddressOrSize) 648 Size = 0; 649 char GlobLoc = ' '; 650 if (Type != SymbolRef::ST_Unknown) 651 GlobLoc = Global ? 'g' : 'l'; 652 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 653 ? 'd' : ' '; 654 char FileFunc = ' '; 655 if (Type == SymbolRef::ST_File) 656 FileFunc = 'f'; 657 else if (Type == SymbolRef::ST_Function) 658 FileFunc = 'F'; 659 660 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 661 "%08" PRIx64; 662 663 outs() << format(Fmt, Address) << " " 664 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 665 << (Weak ? 'w' : ' ') // Weak? 666 << ' ' // Constructor. Not supported yet. 667 << ' ' // Warning. Not supported yet. 668 << ' ' // Indirect reference to another symbol. 669 << Debug // Debugging (d) or dynamic (D) symbol. 670 << FileFunc // Name of function (F), file (f) or object (O). 671 << ' '; 672 if (Absolute) { 673 outs() << "*ABS*"; 674 } else if (Section == o->section_end()) { 675 outs() << "*UND*"; 676 } else { 677 if (const MachOObjectFile *MachO = 678 dyn_cast<const MachOObjectFile>(o)) { 679 DataRefImpl DR = Section->getRawDataRefImpl(); 680 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 681 outs() << SegmentName << ","; 682 } 683 StringRef SectionName; 684 if (error(Section->getName(SectionName))) 685 SectionName = ""; 686 outs() << SectionName; 687 } 688 outs() << '\t' 689 << format("%08" PRIx64 " ", Size) 690 << Name 691 << '\n'; 692 } 693 } 694 695 static void PrintUnwindInfo(const ObjectFile *o) { 696 outs() << "Unwind info:\n\n"; 697 698 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 699 printCOFFUnwindInfo(coff); 700 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 701 printMachOUnwindInfo(MachO); 702 else { 703 // TODO: Extract DWARF dump tool to objdump. 704 errs() << "This operation is only currently supported " 705 "for COFF and MachO object files.\n"; 706 return; 707 } 708 } 709 710 static void printExportsTrie(const ObjectFile *o) { 711 outs() << "Exports trie:\n"; 712 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 713 printMachOExportsTrie(MachO); 714 else { 715 errs() << "This operation is only currently supported " 716 "for Mach-O executable files.\n"; 717 return; 718 } 719 } 720 721 static void printRebaseTable(const ObjectFile *o) { 722 outs() << "Rebase table:\n"; 723 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 724 printMachORebaseTable(MachO); 725 else { 726 errs() << "This operation is only currently supported " 727 "for Mach-O executable files.\n"; 728 return; 729 } 730 } 731 732 static void printBindTable(const ObjectFile *o) { 733 outs() << "Bind table:\n"; 734 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 735 printMachOBindTable(MachO); 736 else { 737 errs() << "This operation is only currently supported " 738 "for Mach-O executable files.\n"; 739 return; 740 } 741 } 742 743 static void printLazyBindTable(const ObjectFile *o) { 744 outs() << "Lazy bind table:\n"; 745 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 746 printMachOLazyBindTable(MachO); 747 else { 748 errs() << "This operation is only currently supported " 749 "for Mach-O executable files.\n"; 750 return; 751 } 752 } 753 754 static void printWeakBindTable(const ObjectFile *o) { 755 outs() << "Weak bind table:\n"; 756 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 757 printMachOWeakBindTable(MachO); 758 else { 759 errs() << "This operation is only currently supported " 760 "for Mach-O executable files.\n"; 761 return; 762 } 763 } 764 765 static void printPrivateFileHeader(const ObjectFile *o) { 766 if (o->isELF()) { 767 printELFFileHeader(o); 768 } else if (o->isCOFF()) { 769 printCOFFFileHeader(o); 770 } else if (o->isMachO()) { 771 printMachOFileHeader(o); 772 } 773 } 774 775 static void DumpObject(const ObjectFile *o) { 776 outs() << '\n'; 777 outs() << o->getFileName() 778 << ":\tfile format " << o->getFileFormatName() << "\n\n"; 779 780 if (Disassemble) 781 DisassembleObject(o, Relocations); 782 if (Relocations && !Disassemble) 783 PrintRelocations(o); 784 if (SectionHeaders) 785 PrintSectionHeaders(o); 786 if (SectionContents) 787 PrintSectionContents(o); 788 if (SymbolTable) 789 PrintSymbolTable(o); 790 if (UnwindInfo) 791 PrintUnwindInfo(o); 792 if (PrivateHeaders) 793 printPrivateFileHeader(o); 794 if (ExportsTrie) 795 printExportsTrie(o); 796 if (Rebase) 797 printRebaseTable(o); 798 if (Bind) 799 printBindTable(o); 800 if (LazyBind) 801 printLazyBindTable(o); 802 if (WeakBind) 803 printWeakBindTable(o); 804 } 805 806 /// @brief Dump each object file in \a a; 807 static void DumpArchive(const Archive *a) { 808 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; 809 ++i) { 810 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); 811 if (std::error_code EC = ChildOrErr.getError()) { 812 // Ignore non-object files. 813 if (EC != object_error::invalid_file_type) 814 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message() 815 << ".\n"; 816 continue; 817 } 818 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 819 DumpObject(o); 820 else 821 errs() << ToolName << ": '" << a->getFileName() << "': " 822 << "Unrecognized file type.\n"; 823 } 824 } 825 826 /// @brief Open file and figure out how to dump it. 827 static void DumpInput(StringRef file) { 828 // If file isn't stdin, check that it exists. 829 if (file != "-" && !sys::fs::exists(file)) { 830 errs() << ToolName << ": '" << file << "': " << "No such file\n"; 831 return; 832 } 833 834 if (MachOOpt && Disassemble) { 835 DisassembleInputMachO(file); 836 return; 837 } 838 839 // Attempt to open the binary. 840 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 841 if (std::error_code EC = BinaryOrErr.getError()) { 842 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n"; 843 return; 844 } 845 Binary &Binary = *BinaryOrErr.get().getBinary(); 846 847 if (Archive *a = dyn_cast<Archive>(&Binary)) 848 DumpArchive(a); 849 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 850 DumpObject(o); 851 else 852 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; 853 } 854 855 int main(int argc, char **argv) { 856 // Print a stack trace if we signal out. 857 sys::PrintStackTraceOnErrorSignal(); 858 PrettyStackTraceProgram X(argc, argv); 859 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 860 861 // Initialize targets and assembly printers/parsers. 862 llvm::InitializeAllTargetInfos(); 863 llvm::InitializeAllTargetMCs(); 864 llvm::InitializeAllAsmParsers(); 865 llvm::InitializeAllDisassemblers(); 866 867 // Register the target printer for --version. 868 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 869 870 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 871 TripleName = Triple::normalize(TripleName); 872 873 ToolName = argv[0]; 874 875 // Defaults to a.out if no filenames specified. 876 if (InputFilenames.size() == 0) 877 InputFilenames.push_back("a.out"); 878 879 if (!Disassemble 880 && !Relocations 881 && !SectionHeaders 882 && !SectionContents 883 && !SymbolTable 884 && !UnwindInfo 885 && !PrivateHeaders 886 && !ExportsTrie 887 && !Rebase 888 && !Bind 889 && !LazyBind 890 && !WeakBind) { 891 cl::PrintHelpMessage(); 892 return 2; 893 } 894 895 std::for_each(InputFilenames.begin(), InputFilenames.end(), 896 DumpInput); 897 898 return 0; 899 } 900