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 bool Text = Section.isText(); 311 if (!Text) 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((uint8_t *)BytesStr.data(), 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((char *)Bytes.data() + Index, Size)); 415 } 416 IP->printInst(&Inst, outs(), ""); 417 outs() << CommentStream.str(); 418 Comments.clear(); 419 outs() << "\n"; 420 } else { 421 errs() << ToolName << ": warning: invalid instruction encoding\n"; 422 if (Size == 0) 423 Size = 1; // skip illegible bytes 424 } 425 426 // Print relocation for instruction. 427 while (rel_cur != rel_end) { 428 bool hidden = false; 429 uint64_t addr; 430 SmallString<16> name; 431 SmallString<32> val; 432 433 // If this relocation is hidden, skip it. 434 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel; 435 if (hidden) goto skip_print_rel; 436 437 if (error(rel_cur->getOffset(addr))) goto skip_print_rel; 438 // Stop when rel_cur's address is past the current instruction. 439 if (addr >= Index + Size) break; 440 if (error(rel_cur->getTypeName(name))) goto skip_print_rel; 441 if (error(rel_cur->getValueString(val))) goto skip_print_rel; 442 443 outs() << format(Fmt.data(), SectionAddr + addr) << name 444 << "\t" << val << "\n"; 445 446 skip_print_rel: 447 ++rel_cur; 448 } 449 } 450 } 451 } 452 } 453 454 static void PrintRelocations(const ObjectFile *Obj) { 455 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 456 "%08" PRIx64; 457 // Regular objdump doesn't print relocations in non-relocatable object 458 // files. 459 if (!Obj->isRelocatableObject()) 460 return; 461 462 for (const SectionRef &Section : Obj->sections()) { 463 if (Section.relocation_begin() == Section.relocation_end()) 464 continue; 465 StringRef secname; 466 if (error(Section.getName(secname))) 467 continue; 468 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 469 for (const RelocationRef &Reloc : Section.relocations()) { 470 bool hidden; 471 uint64_t address; 472 SmallString<32> relocname; 473 SmallString<32> valuestr; 474 if (error(Reloc.getHidden(hidden))) 475 continue; 476 if (hidden) 477 continue; 478 if (error(Reloc.getTypeName(relocname))) 479 continue; 480 if (error(Reloc.getOffset(address))) 481 continue; 482 if (error(Reloc.getValueString(valuestr))) 483 continue; 484 outs() << format(Fmt.data(), address) << " " << relocname << " " 485 << valuestr << "\n"; 486 } 487 outs() << "\n"; 488 } 489 } 490 491 static void PrintSectionHeaders(const ObjectFile *Obj) { 492 outs() << "Sections:\n" 493 "Idx Name Size Address Type\n"; 494 unsigned i = 0; 495 for (const SectionRef &Section : Obj->sections()) { 496 StringRef Name; 497 if (error(Section.getName(Name))) 498 return; 499 uint64_t Address = Section.getAddress(); 500 uint64_t Size = Section.getSize(); 501 bool Text = Section.isText(); 502 bool Data = Section.isData(); 503 bool BSS = Section.isBSS(); 504 std::string Type = (std::string(Text ? "TEXT " : "") + 505 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 506 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, 507 Name.str().c_str(), Size, Address, Type.c_str()); 508 ++i; 509 } 510 } 511 512 static void PrintSectionContents(const ObjectFile *Obj) { 513 std::error_code EC; 514 for (const SectionRef &Section : Obj->sections()) { 515 StringRef Name; 516 StringRef Contents; 517 if (error(Section.getName(Name))) 518 continue; 519 uint64_t BaseAddr = Section.getAddress(); 520 uint64_t Size = Section.getSize(); 521 if (!Size) 522 continue; 523 524 outs() << "Contents of section " << Name << ":\n"; 525 if (Section.isBSS()) { 526 outs() << format("<skipping contents of bss section at [%04" PRIx64 527 ", %04" PRIx64 ")>\n", 528 BaseAddr, BaseAddr + Size); 529 continue; 530 } 531 532 if (error(Section.getContents(Contents))) 533 continue; 534 535 // Dump out the content as hex and printable ascii characters. 536 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 537 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 538 // Dump line of hex. 539 for (std::size_t i = 0; i < 16; ++i) { 540 if (i != 0 && i % 4 == 0) 541 outs() << ' '; 542 if (addr + i < end) 543 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 544 << hexdigit(Contents[addr + i] & 0xF, true); 545 else 546 outs() << " "; 547 } 548 // Print ascii. 549 outs() << " "; 550 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 551 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 552 outs() << Contents[addr + i]; 553 else 554 outs() << "."; 555 } 556 outs() << "\n"; 557 } 558 } 559 } 560 561 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) { 562 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) { 563 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI); 564 StringRef Name; 565 if (error(Symbol.getError())) 566 return; 567 568 if (error(coff->getSymbolName(*Symbol, Name))) 569 return; 570 571 outs() << "[" << format("%2d", SI) << "]" 572 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")" 573 << "(fl 0x00)" // Flag bits, which COFF doesn't have. 574 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")" 575 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") " 576 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") " 577 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " " 578 << Name << "\n"; 579 580 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) { 581 if (Symbol->isSectionDefinition()) { 582 const coff_aux_section_definition *asd; 583 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd))) 584 return; 585 586 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj()); 587 588 outs() << "AUX " 589 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x " 590 , unsigned(asd->Length) 591 , unsigned(asd->NumberOfRelocations) 592 , unsigned(asd->NumberOfLinenumbers) 593 , unsigned(asd->CheckSum)) 594 << format("assoc %d comdat %d\n" 595 , unsigned(AuxNumber) 596 , unsigned(asd->Selection)); 597 } else if (Symbol->isFileRecord()) { 598 const char *FileName; 599 if (error(coff->getAuxSymbol<char>(SI + 1, FileName))) 600 return; 601 602 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() * 603 coff->getSymbolTableEntrySize()); 604 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n'; 605 606 SI = SI + Symbol->getNumberOfAuxSymbols(); 607 break; 608 } else { 609 outs() << "AUX Unknown\n"; 610 } 611 } 612 } 613 } 614 615 static void PrintSymbolTable(const ObjectFile *o) { 616 outs() << "SYMBOL TABLE:\n"; 617 618 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 619 PrintCOFFSymbolTable(coff); 620 return; 621 } 622 for (const SymbolRef &Symbol : o->symbols()) { 623 StringRef Name; 624 uint64_t Address; 625 SymbolRef::Type Type; 626 uint64_t Size; 627 uint32_t Flags = Symbol.getFlags(); 628 section_iterator Section = o->section_end(); 629 if (error(Symbol.getName(Name))) 630 continue; 631 if (error(Symbol.getAddress(Address))) 632 continue; 633 if (error(Symbol.getType(Type))) 634 continue; 635 if (error(Symbol.getSize(Size))) 636 continue; 637 if (error(Symbol.getSection(Section))) 638 continue; 639 640 bool Global = Flags & SymbolRef::SF_Global; 641 bool Weak = Flags & SymbolRef::SF_Weak; 642 bool Absolute = Flags & SymbolRef::SF_Absolute; 643 644 if (Address == UnknownAddressOrSize) 645 Address = 0; 646 if (Size == UnknownAddressOrSize) 647 Size = 0; 648 char GlobLoc = ' '; 649 if (Type != SymbolRef::ST_Unknown) 650 GlobLoc = Global ? 'g' : 'l'; 651 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 652 ? 'd' : ' '; 653 char FileFunc = ' '; 654 if (Type == SymbolRef::ST_File) 655 FileFunc = 'f'; 656 else if (Type == SymbolRef::ST_Function) 657 FileFunc = 'F'; 658 659 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 660 "%08" PRIx64; 661 662 outs() << format(Fmt, Address) << " " 663 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 664 << (Weak ? 'w' : ' ') // Weak? 665 << ' ' // Constructor. Not supported yet. 666 << ' ' // Warning. Not supported yet. 667 << ' ' // Indirect reference to another symbol. 668 << Debug // Debugging (d) or dynamic (D) symbol. 669 << FileFunc // Name of function (F), file (f) or object (O). 670 << ' '; 671 if (Absolute) { 672 outs() << "*ABS*"; 673 } else if (Section == o->section_end()) { 674 outs() << "*UND*"; 675 } else { 676 if (const MachOObjectFile *MachO = 677 dyn_cast<const MachOObjectFile>(o)) { 678 DataRefImpl DR = Section->getRawDataRefImpl(); 679 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 680 outs() << SegmentName << ","; 681 } 682 StringRef SectionName; 683 if (error(Section->getName(SectionName))) 684 SectionName = ""; 685 outs() << SectionName; 686 } 687 outs() << '\t' 688 << format("%08" PRIx64 " ", Size) 689 << Name 690 << '\n'; 691 } 692 } 693 694 static void PrintUnwindInfo(const ObjectFile *o) { 695 outs() << "Unwind info:\n\n"; 696 697 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 698 printCOFFUnwindInfo(coff); 699 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 700 printMachOUnwindInfo(MachO); 701 else { 702 // TODO: Extract DWARF dump tool to objdump. 703 errs() << "This operation is only currently supported " 704 "for COFF and MachO object files.\n"; 705 return; 706 } 707 } 708 709 static void printExportsTrie(const ObjectFile *o) { 710 outs() << "Exports trie:\n"; 711 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 712 printMachOExportsTrie(MachO); 713 else { 714 errs() << "This operation is only currently supported " 715 "for Mach-O executable files.\n"; 716 return; 717 } 718 } 719 720 static void printRebaseTable(const ObjectFile *o) { 721 outs() << "Rebase table:\n"; 722 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 723 printMachORebaseTable(MachO); 724 else { 725 errs() << "This operation is only currently supported " 726 "for Mach-O executable files.\n"; 727 return; 728 } 729 } 730 731 static void printBindTable(const ObjectFile *o) { 732 outs() << "Bind table:\n"; 733 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 734 printMachOBindTable(MachO); 735 else { 736 errs() << "This operation is only currently supported " 737 "for Mach-O executable files.\n"; 738 return; 739 } 740 } 741 742 static void printLazyBindTable(const ObjectFile *o) { 743 outs() << "Lazy bind table:\n"; 744 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 745 printMachOLazyBindTable(MachO); 746 else { 747 errs() << "This operation is only currently supported " 748 "for Mach-O executable files.\n"; 749 return; 750 } 751 } 752 753 static void printWeakBindTable(const ObjectFile *o) { 754 outs() << "Weak bind table:\n"; 755 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 756 printMachOWeakBindTable(MachO); 757 else { 758 errs() << "This operation is only currently supported " 759 "for Mach-O executable files.\n"; 760 return; 761 } 762 } 763 764 static void printPrivateFileHeader(const ObjectFile *o) { 765 if (o->isELF()) { 766 printELFFileHeader(o); 767 } else if (o->isCOFF()) { 768 printCOFFFileHeader(o); 769 } else if (o->isMachO()) { 770 printMachOFileHeader(o); 771 } 772 } 773 774 static void DumpObject(const ObjectFile *o) { 775 outs() << '\n'; 776 outs() << o->getFileName() 777 << ":\tfile format " << o->getFileFormatName() << "\n\n"; 778 779 if (Disassemble) 780 DisassembleObject(o, Relocations); 781 if (Relocations && !Disassemble) 782 PrintRelocations(o); 783 if (SectionHeaders) 784 PrintSectionHeaders(o); 785 if (SectionContents) 786 PrintSectionContents(o); 787 if (SymbolTable) 788 PrintSymbolTable(o); 789 if (UnwindInfo) 790 PrintUnwindInfo(o); 791 if (PrivateHeaders) 792 printPrivateFileHeader(o); 793 if (ExportsTrie) 794 printExportsTrie(o); 795 if (Rebase) 796 printRebaseTable(o); 797 if (Bind) 798 printBindTable(o); 799 if (LazyBind) 800 printLazyBindTable(o); 801 if (WeakBind) 802 printWeakBindTable(o); 803 } 804 805 /// @brief Dump each object file in \a a; 806 static void DumpArchive(const Archive *a) { 807 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; 808 ++i) { 809 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); 810 if (std::error_code EC = ChildOrErr.getError()) { 811 // Ignore non-object files. 812 if (EC != object_error::invalid_file_type) 813 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message() 814 << ".\n"; 815 continue; 816 } 817 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 818 DumpObject(o); 819 else 820 errs() << ToolName << ": '" << a->getFileName() << "': " 821 << "Unrecognized file type.\n"; 822 } 823 } 824 825 /// @brief Open file and figure out how to dump it. 826 static void DumpInput(StringRef file) { 827 // If file isn't stdin, check that it exists. 828 if (file != "-" && !sys::fs::exists(file)) { 829 errs() << ToolName << ": '" << file << "': " << "No such file\n"; 830 return; 831 } 832 833 if (MachOOpt && Disassemble) { 834 DisassembleInputMachO(file); 835 return; 836 } 837 838 // Attempt to open the binary. 839 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 840 if (std::error_code EC = BinaryOrErr.getError()) { 841 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n"; 842 return; 843 } 844 Binary &Binary = *BinaryOrErr.get().getBinary(); 845 846 if (Archive *a = dyn_cast<Archive>(&Binary)) 847 DumpArchive(a); 848 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 849 DumpObject(o); 850 else 851 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; 852 } 853 854 int main(int argc, char **argv) { 855 // Print a stack trace if we signal out. 856 sys::PrintStackTraceOnErrorSignal(); 857 PrettyStackTraceProgram X(argc, argv); 858 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 859 860 // Initialize targets and assembly printers/parsers. 861 llvm::InitializeAllTargetInfos(); 862 llvm::InitializeAllTargetMCs(); 863 llvm::InitializeAllAsmParsers(); 864 llvm::InitializeAllDisassemblers(); 865 866 // Register the target printer for --version. 867 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 868 869 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 870 TripleName = Triple::normalize(TripleName); 871 872 ToolName = argv[0]; 873 874 // Defaults to a.out if no filenames specified. 875 if (InputFilenames.size() == 0) 876 InputFilenames.push_back("a.out"); 877 878 if (!Disassemble 879 && !Relocations 880 && !SectionHeaders 881 && !SectionContents 882 && !SymbolTable 883 && !UnwindInfo 884 && !PrivateHeaders 885 && !ExportsTrie 886 && !Rebase 887 && !Bind 888 && !LazyBind 889 && !WeakBind) { 890 cl::PrintHelpMessage(); 891 return 2; 892 } 893 894 std::for_each(InputFilenames.begin(), InputFilenames.end(), 895 DumpInput); 896 897 return 0; 898 } 899