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