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, MCInstPrinter &IP) { 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), *IP); 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 uint64_t Size; 680 uint32_t Flags = Symbol.getFlags(); 681 section_iterator Section = o->section_end(); 682 if (error(Symbol.getName(Name))) 683 continue; 684 if (error(Symbol.getAddress(Address))) 685 continue; 686 if (error(Symbol.getType(Type))) 687 continue; 688 if (error(Symbol.getSize(Size))) 689 continue; 690 if (error(Symbol.getSection(Section))) 691 continue; 692 693 bool Global = Flags & SymbolRef::SF_Global; 694 bool Weak = Flags & SymbolRef::SF_Weak; 695 bool Absolute = Flags & SymbolRef::SF_Absolute; 696 bool Common = Flags & SymbolRef::SF_Common; 697 bool Hidden = Flags & SymbolRef::SF_Hidden; 698 699 if (Common) { 700 uint32_t Alignment; 701 if (error(Symbol.getAlignment(Alignment))) 702 Alignment = 0; 703 Address = Size; 704 Size = Alignment; 705 } 706 if (Address == UnknownAddressOrSize) 707 Address = 0; 708 if (Size == UnknownAddressOrSize) 709 Size = 0; 710 char GlobLoc = ' '; 711 if (Type != SymbolRef::ST_Unknown) 712 GlobLoc = Global ? 'g' : 'l'; 713 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 714 ? 'd' : ' '; 715 char FileFunc = ' '; 716 if (Type == SymbolRef::ST_File) 717 FileFunc = 'f'; 718 else if (Type == SymbolRef::ST_Function) 719 FileFunc = 'F'; 720 721 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 722 "%08" PRIx64; 723 724 outs() << format(Fmt, Address) << " " 725 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 726 << (Weak ? 'w' : ' ') // Weak? 727 << ' ' // Constructor. Not supported yet. 728 << ' ' // Warning. Not supported yet. 729 << ' ' // Indirect reference to another symbol. 730 << Debug // Debugging (d) or dynamic (D) symbol. 731 << FileFunc // Name of function (F), file (f) or object (O). 732 << ' '; 733 if (Absolute) { 734 outs() << "*ABS*"; 735 } else if (Common) { 736 outs() << "*COM*"; 737 } else if (Section == o->section_end()) { 738 outs() << "*UND*"; 739 } else { 740 if (const MachOObjectFile *MachO = 741 dyn_cast<const MachOObjectFile>(o)) { 742 DataRefImpl DR = Section->getRawDataRefImpl(); 743 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 744 outs() << SegmentName << ","; 745 } 746 StringRef SectionName; 747 if (error(Section->getName(SectionName))) 748 SectionName = ""; 749 outs() << SectionName; 750 } 751 outs() << '\t' 752 << format("%08" PRIx64 " ", Size); 753 if (Hidden) { 754 outs() << ".hidden "; 755 } 756 outs() << Name 757 << '\n'; 758 } 759 } 760 761 static void PrintUnwindInfo(const ObjectFile *o) { 762 outs() << "Unwind info:\n\n"; 763 764 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 765 printCOFFUnwindInfo(coff); 766 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 767 printMachOUnwindInfo(MachO); 768 else { 769 // TODO: Extract DWARF dump tool to objdump. 770 errs() << "This operation is only currently supported " 771 "for COFF and MachO object files.\n"; 772 return; 773 } 774 } 775 776 void llvm::printExportsTrie(const ObjectFile *o) { 777 outs() << "Exports trie:\n"; 778 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 779 printMachOExportsTrie(MachO); 780 else { 781 errs() << "This operation is only currently supported " 782 "for Mach-O executable files.\n"; 783 return; 784 } 785 } 786 787 void llvm::printRebaseTable(const ObjectFile *o) { 788 outs() << "Rebase table:\n"; 789 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 790 printMachORebaseTable(MachO); 791 else { 792 errs() << "This operation is only currently supported " 793 "for Mach-O executable files.\n"; 794 return; 795 } 796 } 797 798 void llvm::printBindTable(const ObjectFile *o) { 799 outs() << "Bind table:\n"; 800 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 801 printMachOBindTable(MachO); 802 else { 803 errs() << "This operation is only currently supported " 804 "for Mach-O executable files.\n"; 805 return; 806 } 807 } 808 809 void llvm::printLazyBindTable(const ObjectFile *o) { 810 outs() << "Lazy bind table:\n"; 811 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 812 printMachOLazyBindTable(MachO); 813 else { 814 errs() << "This operation is only currently supported " 815 "for Mach-O executable files.\n"; 816 return; 817 } 818 } 819 820 void llvm::printWeakBindTable(const ObjectFile *o) { 821 outs() << "Weak bind table:\n"; 822 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 823 printMachOWeakBindTable(MachO); 824 else { 825 errs() << "This operation is only currently supported " 826 "for Mach-O executable files.\n"; 827 return; 828 } 829 } 830 831 static void printPrivateFileHeader(const ObjectFile *o) { 832 if (o->isELF()) { 833 printELFFileHeader(o); 834 } else if (o->isCOFF()) { 835 printCOFFFileHeader(o); 836 } else if (o->isMachO()) { 837 printMachOFileHeader(o); 838 } 839 } 840 841 static void DumpObject(const ObjectFile *o) { 842 outs() << '\n'; 843 outs() << o->getFileName() 844 << ":\tfile format " << o->getFileFormatName() << "\n\n"; 845 846 if (Disassemble) 847 DisassembleObject(o, Relocations); 848 if (Relocations && !Disassemble) 849 PrintRelocations(o); 850 if (SectionHeaders) 851 PrintSectionHeaders(o); 852 if (SectionContents) 853 PrintSectionContents(o); 854 if (SymbolTable) 855 PrintSymbolTable(o); 856 if (UnwindInfo) 857 PrintUnwindInfo(o); 858 if (PrivateHeaders) 859 printPrivateFileHeader(o); 860 if (ExportsTrie) 861 printExportsTrie(o); 862 if (Rebase) 863 printRebaseTable(o); 864 if (Bind) 865 printBindTable(o); 866 if (LazyBind) 867 printLazyBindTable(o); 868 if (WeakBind) 869 printWeakBindTable(o); 870 } 871 872 /// @brief Dump each object file in \a a; 873 static void DumpArchive(const Archive *a) { 874 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; 875 ++i) { 876 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary(); 877 if (std::error_code EC = ChildOrErr.getError()) { 878 // Ignore non-object files. 879 if (EC != object_error::invalid_file_type) 880 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message() 881 << ".\n"; 882 continue; 883 } 884 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 885 DumpObject(o); 886 else 887 errs() << ToolName << ": '" << a->getFileName() << "': " 888 << "Unrecognized file type.\n"; 889 } 890 } 891 892 /// @brief Open file and figure out how to dump it. 893 static void DumpInput(StringRef file) { 894 // If file isn't stdin, check that it exists. 895 if (file != "-" && !sys::fs::exists(file)) { 896 errs() << ToolName << ": '" << file << "': " << "No such file\n"; 897 return; 898 } 899 900 // If we are using the Mach-O specific object file parser, then let it parse 901 // the file and process the command line options. So the -arch flags can 902 // be used to select specific slices, etc. 903 if (MachOOpt) { 904 ParseInputMachO(file); 905 return; 906 } 907 908 // Attempt to open the binary. 909 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 910 if (std::error_code EC = BinaryOrErr.getError()) { 911 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n"; 912 return; 913 } 914 Binary &Binary = *BinaryOrErr.get().getBinary(); 915 916 if (Archive *a = dyn_cast<Archive>(&Binary)) 917 DumpArchive(a); 918 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 919 DumpObject(o); 920 else 921 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; 922 } 923 924 int main(int argc, char **argv) { 925 // Print a stack trace if we signal out. 926 sys::PrintStackTraceOnErrorSignal(); 927 PrettyStackTraceProgram X(argc, argv); 928 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 929 930 // Initialize targets and assembly printers/parsers. 931 llvm::InitializeAllTargetInfos(); 932 llvm::InitializeAllTargetMCs(); 933 llvm::InitializeAllAsmParsers(); 934 llvm::InitializeAllDisassemblers(); 935 936 // Register the target printer for --version. 937 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 938 939 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 940 TripleName = Triple::normalize(TripleName); 941 942 ToolName = argv[0]; 943 944 // Defaults to a.out if no filenames specified. 945 if (InputFilenames.size() == 0) 946 InputFilenames.push_back("a.out"); 947 948 if (!Disassemble 949 && !Relocations 950 && !SectionHeaders 951 && !SectionContents 952 && !SymbolTable 953 && !UnwindInfo 954 && !PrivateHeaders 955 && !ExportsTrie 956 && !Rebase 957 && !Bind 958 && !LazyBind 959 && !WeakBind 960 && !(UniversalHeaders && MachOOpt) 961 && !(ArchiveHeaders && MachOOpt) 962 && !(IndirectSymbols && MachOOpt) 963 && !(DataInCode && MachOOpt) 964 && !(LinkOptHints && MachOOpt) 965 && !(InfoPlist && MachOOpt) 966 && !(DylibsUsed && MachOOpt) 967 && !(DylibId && MachOOpt) 968 && !(ObjcMetaData && MachOOpt) 969 && !(DumpSections.size() != 0 && MachOOpt)) { 970 cl::PrintHelpMessage(); 971 return 2; 972 } 973 974 std::for_each(InputFilenames.begin(), InputFilenames.end(), 975 DumpInput); 976 977 return ReturnValue; 978 } 979