1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 // The flags and output of this program should be near identical to those of
17 //===----------------------------------------------------------------------===//
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/MCAnalysis/MCAtom.h"
24 #include "llvm/MC/MCAnalysis/MCFunction.h"
25 #include "llvm/MC/MCAnalysis/MCModule.h"
26 #include "llvm/MC/MCAnalysis/MCModuleYAML.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDisassembler.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCInstPrinter.h"
32 #include "llvm/MC/MCInstrAnalysis.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectDisassembler.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCObjectSymbolizer.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MC/MCRelocationInfo.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/COFF.h"
42 #include "llvm/Object/MachO.h"
43 #include "llvm/Object/ObjectFile.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Format.h"
49 #include "llvm/Support/GraphWriter.h"
50 #include "llvm/Support/Host.h"
51 #include "llvm/Support/ManagedStatic.h"
52 #include "llvm/Support/MemoryBuffer.h"
53 #include "llvm/Support/MemoryObject.h"
54 #include "llvm/Support/PrettyStackTrace.h"
55 #include "llvm/Support/Signals.h"
56 #include "llvm/Support/SourceMgr.h"
57 #include "llvm/Support/TargetRegistry.h"
58 #include "llvm/Support/TargetSelect.h"
59 #include "llvm/Support/raw_ostream.h"
63 #include <system_error>
66 using namespace object;
68 static cl::list<std::string>
69 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
72 Disassemble("disassemble",
73 cl::desc("Display assembler mnemonics for the machine instructions"));
75 Disassembled("d", cl::desc("Alias for --disassemble"),
76 cl::aliasopt(Disassemble));
79 Relocations("r", cl::desc("Display the relocation entries in the file"));
82 SectionContents("s", cl::desc("Display the content of each section"));
85 SymbolTable("t", cl::desc("Display the symbol table"));
88 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
90 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
93 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
94 "see -version for available targets"));
97 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
98 "see -version for available targets"));
101 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
102 "for each section."));
104 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
105 cl::aliasopt(SectionHeaders));
107 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
108 cl::aliasopt(SectionHeaders));
110 static cl::list<std::string>
113 cl::desc("Target specific attributes"),
114 cl::value_desc("a1,+a2,-a3,..."));
117 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
118 "do not print the instruction bytes."));
121 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
124 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
125 cl::aliasopt(UnwindInfo));
128 PrivateHeaders("private-headers",
129 cl::desc("Display format specific file headers"));
132 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
133 cl::aliasopt(PrivateHeaders));
136 Symbolize("symbolize", cl::desc("When disassembling instructions, "
137 "try to symbolize operands."));
140 CFG("cfg", cl::desc("Create a CFG for every function found in the object"
141 " and write it to a graphviz file"));
143 // FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
144 static cl::opt<std::string>
146 cl::desc("Create a CFG and write it as a YAML MCModule."),
147 cl::value_desc("yaml output file"));
149 static StringRef ToolName;
151 bool llvm::error(std::error_code EC) {
155 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
160 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
161 // Figure out the target triple.
162 llvm::Triple TheTriple("unknown-unknown-unknown");
163 if (TripleName.empty()) {
165 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
166 // TheTriple defaults to ELF, and COFF doesn't have an environment:
167 // the best we can do here is indicate that it is mach-o.
169 TheTriple.setObjectFormat(Triple::MachO);
172 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
173 if (COFFObj->getArch() == Triple::thumb)
174 TheTriple.setTriple("thumbv7-windows");
178 TheTriple.setTriple(Triple::normalize(TripleName));
180 // Get the target specific parser.
182 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
185 errs() << ToolName << ": " << Error;
189 // Update the triple name and return the found target.
190 TripleName = TheTriple.getTriple();
194 // Write a graphviz file for the CFG inside an MCFunction.
195 // FIXME: Use GraphWriter
196 static void emitDOTFile(const char *FileName, const MCFunction &f,
198 // Start a new dot file.
200 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
201 if (!Error.empty()) {
202 errs() << "llvm-objdump: warning: " << Error << '\n';
206 Out << "digraph \"" << f.getName() << "\" {\n";
207 Out << "graph [ rankdir = \"LR\" ];\n";
208 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
209 // Only print blocks that have predecessors.
210 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
212 if (!hasPreds && i != f.begin())
215 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
216 // Print instructions.
217 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
219 if (ii != 0) // Not the first line, start a new row.
221 if (ii + 1 == ie) // Last line, add an end id.
224 // Escape special chars and print the instruction in mnemonic form.
226 raw_string_ostream OS(Str);
227 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
228 Out << DOT::EscapeString(OS.str());
230 Out << "\" shape=\"record\" ];\n";
233 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
234 se = (*i)->succ_end(); si != se; ++si)
235 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
236 << (*si)->getInsts()->getBeginAddr() << ":a\n";
241 void llvm::DumpBytes(StringRef bytes) {
242 static const char hex_rep[] = "0123456789abcdef";
243 // FIXME: The real way to do this is to figure out the longest instruction
244 // and align to that size before printing. I'll fix this when I get
245 // around to outputting relocations.
246 // 15 is the longest x86 instruction
247 // 3 is for the hex rep of a byte + a space.
248 // 1 is for the null terminator.
249 enum { OutputSize = (15 * 3) + 1 };
250 char output[OutputSize];
252 assert(bytes.size() <= 15
253 && "DumpBytes only supports instructions of up to 15 bytes");
254 memset(output, ' ', sizeof(output));
256 for (StringRef::iterator i = bytes.begin(),
257 e = bytes.end(); i != e; ++i) {
258 output[index] = hex_rep[(*i & 0xF0) >> 4];
259 output[index + 1] = hex_rep[*i & 0xF];
263 output[sizeof(output) - 1] = 0;
267 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
268 uint64_t a_addr, b_addr;
269 if (error(a.getOffset(a_addr))) return false;
270 if (error(b.getOffset(b_addr))) return false;
271 return a_addr < b_addr;
274 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
275 const Target *TheTarget = getTarget(Obj);
276 // getTarget() will have already issued a diagnostic if necessary, so
277 // just bail here if it failed.
281 // Package up features to be passed to target/subtarget
282 std::string FeaturesStr;
284 SubtargetFeatures Features;
285 for (unsigned i = 0; i != MAttrs.size(); ++i)
286 Features.AddFeature(MAttrs[i]);
287 FeaturesStr = Features.getString();
290 std::unique_ptr<const MCRegisterInfo> MRI(
291 TheTarget->createMCRegInfo(TripleName));
293 errs() << "error: no register info for target " << TripleName << "\n";
297 // Set up disassembler.
298 std::unique_ptr<const MCAsmInfo> AsmInfo(
299 TheTarget->createMCAsmInfo(*MRI, TripleName));
301 errs() << "error: no assembly info for target " << TripleName << "\n";
305 std::unique_ptr<const MCSubtargetInfo> STI(
306 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
308 errs() << "error: no subtarget info for target " << TripleName << "\n";
312 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
314 errs() << "error: no instruction info for target " << TripleName << "\n";
318 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
319 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
321 std::unique_ptr<MCDisassembler> DisAsm(
322 TheTarget->createMCDisassembler(*STI, Ctx));
325 errs() << "error: no disassembler for target " << TripleName << "\n";
331 std::unique_ptr<MCRelocationInfo> RelInfo(
332 TheTarget->createMCRelocationInfo(TripleName, Ctx));
334 std::unique_ptr<MCSymbolizer> Symzer(
335 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
338 DisAsm->setSymbolizer(std::move(Symzer));
342 std::unique_ptr<const MCInstrAnalysis> MIA(
343 TheTarget->createMCInstrAnalysis(MII.get()));
345 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
346 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
347 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
349 errs() << "error: no instruction printer for target " << TripleName
354 if (CFG || !YAMLCFG.empty()) {
355 std::unique_ptr<MCObjectDisassembler> OD(
356 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
357 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
358 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
359 AE = Mod->atom_end();
361 outs() << "Atom " << (*AI)->getName() << ": \n";
362 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
363 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
366 IP->printInst(&II->Inst, outs(), "");
372 for (MCModule::const_func_iterator FI = Mod->func_begin(),
373 FE = Mod->func_end();
375 static int filenum = 0;
376 emitDOTFile((Twine((*FI)->getName()) + "_" +
377 utostr(filenum) + ".dot").str().c_str(),
382 if (!YAMLCFG.empty()) {
384 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
385 if (!Error.empty()) {
386 errs() << ToolName << ": warning: " << Error << '\n';
389 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
393 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
394 "\t\t\t%08" PRIx64 ": ";
396 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
397 // in RelocSecs contain the relocations for section S.
399 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
400 for (const SectionRef &Section : Obj->sections()) {
401 section_iterator Sec2 = Section.getRelocatedSection();
402 if (Sec2 != Obj->section_end())
403 SectionRelocMap[*Sec2].push_back(Section);
406 for (const SectionRef &Section : Obj->sections()) {
408 if (error(Section.isText(Text)))
413 uint64_t SectionAddr;
414 if (error(Section.getAddress(SectionAddr)))
418 if (error(Section.getSize(SectSize)))
421 // Make a list of all the symbols in this section.
422 std::vector<std::pair<uint64_t, StringRef>> Symbols;
423 for (const SymbolRef &Symbol : Obj->symbols()) {
425 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
427 if (error(Symbol.getAddress(Address)))
429 if (Address == UnknownAddressOrSize)
431 Address -= SectionAddr;
432 if (Address >= SectSize)
436 if (error(Symbol.getName(Name)))
438 Symbols.push_back(std::make_pair(Address, Name));
442 // Sort the symbols by address, just in case they didn't come in that way.
443 array_pod_sort(Symbols.begin(), Symbols.end());
445 // Make a list of all the relocations for this section.
446 std::vector<RelocationRef> Rels;
448 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
449 for (const RelocationRef &Reloc : RelocSec.relocations()) {
450 Rels.push_back(Reloc);
455 // Sort relocations by address.
456 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
458 StringRef SegmentName = "";
459 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
460 DataRefImpl DR = Section.getRawDataRefImpl();
461 SegmentName = MachO->getSectionFinalSegmentName(DR);
464 if (error(Section.getName(name)))
466 outs() << "Disassembly of section ";
467 if (!SegmentName.empty())
468 outs() << SegmentName << ",";
469 outs() << name << ':';
471 // If the section has no symbols just insert a dummy one and disassemble
472 // the whole section.
474 Symbols.push_back(std::make_pair(0, name));
477 SmallString<40> Comments;
478 raw_svector_ostream CommentStream(Comments);
481 if (error(Section.getContents(Bytes)))
483 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
487 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
488 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
489 // Disassemble symbol by symbol.
490 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
491 uint64_t Start = Symbols[si].first;
493 // The end is either the size of the section or the beginning of the next
497 // Make sure this symbol takes up space.
498 else if (Symbols[si + 1].first != Start)
499 End = Symbols[si + 1].first - 1;
501 // This symbol has the same address as the next symbol. Skip it.
504 outs() << '\n' << Symbols[si].second << ":\n";
507 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
509 raw_ostream &DebugOut = nulls();
512 for (Index = Start; Index < End; Index += Size) {
515 if (DisAsm->getInstruction(Inst, Size, memoryObject,
517 DebugOut, CommentStream)) {
518 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
519 if (!NoShowRawInsn) {
521 DumpBytes(StringRef(Bytes.data() + Index, Size));
523 IP->printInst(&Inst, outs(), "");
524 outs() << CommentStream.str();
528 errs() << ToolName << ": warning: invalid instruction encoding\n";
530 Size = 1; // skip illegible bytes
533 // Print relocation for instruction.
534 while (rel_cur != rel_end) {
537 SmallString<16> name;
540 // If this relocation is hidden, skip it.
541 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
542 if (hidden) goto skip_print_rel;
544 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
545 // Stop when rel_cur's address is past the current instruction.
546 if (addr >= Index + Size) break;
547 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
548 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
550 outs() << format(Fmt.data(), SectionAddr + addr) << name
551 << "\t" << val << "\n";
561 static void PrintRelocations(const ObjectFile *Obj) {
562 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
564 for (const SectionRef &Section : Obj->sections()) {
565 if (Section.relocation_begin() == Section.relocation_end())
568 if (error(Section.getName(secname)))
570 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
571 for (const RelocationRef &Reloc : Section.relocations()) {
574 SmallString<32> relocname;
575 SmallString<32> valuestr;
576 if (error(Reloc.getHidden(hidden)))
580 if (error(Reloc.getTypeName(relocname)))
582 if (error(Reloc.getOffset(address)))
584 if (error(Reloc.getValueString(valuestr)))
586 outs() << format(Fmt.data(), address) << " " << relocname << " "
593 static void PrintSectionHeaders(const ObjectFile *Obj) {
594 outs() << "Sections:\n"
595 "Idx Name Size Address Type\n";
597 for (const SectionRef &Section : Obj->sections()) {
599 if (error(Section.getName(Name)))
602 if (error(Section.getAddress(Address)))
605 if (error(Section.getSize(Size)))
607 bool Text, Data, BSS;
608 if (error(Section.isText(Text)))
610 if (error(Section.isData(Data)))
612 if (error(Section.isBSS(BSS)))
614 std::string Type = (std::string(Text ? "TEXT " : "") +
615 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
616 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
617 Name.str().c_str(), Size, Address, Type.c_str());
622 static void PrintSectionContents(const ObjectFile *Obj) {
624 for (const SectionRef &Section : Obj->sections()) {
629 if (error(Section.getName(Name)))
631 if (error(Section.getAddress(BaseAddr)))
633 if (error(Section.isBSS(BSS)))
636 outs() << "Contents of section " << Name << ":\n";
639 if (error(Section.getSize(Size)))
641 outs() << format("<skipping contents of bss section at [%04" PRIx64
642 ", %04" PRIx64 ")>\n",
643 BaseAddr, BaseAddr + Size);
647 if (error(Section.getContents(Contents)))
650 // Dump out the content as hex and printable ascii characters.
651 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
652 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
654 for (std::size_t i = 0; i < 16; ++i) {
655 if (i != 0 && i % 4 == 0)
658 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
659 << hexdigit(Contents[addr + i] & 0xF, true);
665 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
666 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
667 outs() << Contents[addr + i];
676 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
677 const coff_file_header *header;
678 if (error(coff->getHeader(header)))
681 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
682 const coff_symbol *Symbol;
684 if (error(coff->getSymbol(SI, Symbol)))
687 if (error(coff->getSymbolName(Symbol, Name)))
690 outs() << "[" << format("%2d", SI) << "]"
691 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
692 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
693 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
694 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
695 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
696 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
699 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
700 if (Symbol->isSectionDefinition()) {
701 const coff_aux_section_definition *asd;
702 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
706 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
707 , unsigned(asd->Length)
708 , unsigned(asd->NumberOfRelocations)
709 , unsigned(asd->NumberOfLinenumbers)
710 , unsigned(asd->CheckSum))
711 << format("assoc %d comdat %d\n"
712 , unsigned(asd->Number)
713 , unsigned(asd->Selection));
714 } else if (Symbol->isFileRecord()) {
715 const coff_aux_file *AF;
716 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
719 StringRef Name(AF->FileName,
720 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
721 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
723 SI = SI + Symbol->NumberOfAuxSymbols;
726 outs() << "AUX Unknown\n";
732 static void PrintSymbolTable(const ObjectFile *o) {
733 outs() << "SYMBOL TABLE:\n";
735 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
736 PrintCOFFSymbolTable(coff);
739 for (const SymbolRef &Symbol : o->symbols()) {
742 SymbolRef::Type Type;
744 uint32_t Flags = Symbol.getFlags();
745 section_iterator Section = o->section_end();
746 if (error(Symbol.getName(Name)))
748 if (error(Symbol.getAddress(Address)))
750 if (error(Symbol.getType(Type)))
752 if (error(Symbol.getSize(Size)))
754 if (error(Symbol.getSection(Section)))
757 bool Global = Flags & SymbolRef::SF_Global;
758 bool Weak = Flags & SymbolRef::SF_Weak;
759 bool Absolute = Flags & SymbolRef::SF_Absolute;
761 if (Address == UnknownAddressOrSize)
763 if (Size == UnknownAddressOrSize)
766 if (Type != SymbolRef::ST_Unknown)
767 GlobLoc = Global ? 'g' : 'l';
768 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
771 if (Type == SymbolRef::ST_File)
773 else if (Type == SymbolRef::ST_Function)
776 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
779 outs() << format(Fmt, Address) << " "
780 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
781 << (Weak ? 'w' : ' ') // Weak?
782 << ' ' // Constructor. Not supported yet.
783 << ' ' // Warning. Not supported yet.
784 << ' ' // Indirect reference to another symbol.
785 << Debug // Debugging (d) or dynamic (D) symbol.
786 << FileFunc // Name of function (F), file (f) or object (O).
790 } else if (Section == o->section_end()) {
793 if (const MachOObjectFile *MachO =
794 dyn_cast<const MachOObjectFile>(o)) {
795 DataRefImpl DR = Section->getRawDataRefImpl();
796 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
797 outs() << SegmentName << ",";
799 StringRef SectionName;
800 if (error(Section->getName(SectionName)))
802 outs() << SectionName;
805 << format("%08" PRIx64 " ", Size)
811 static void PrintUnwindInfo(const ObjectFile *o) {
812 outs() << "Unwind info:\n\n";
814 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
815 printCOFFUnwindInfo(coff);
817 // TODO: Extract DWARF dump tool to objdump.
818 errs() << "This operation is only currently supported "
819 "for COFF object files.\n";
824 static void printPrivateFileHeader(const ObjectFile *o) {
826 printELFFileHeader(o);
827 } else if (o->isCOFF()) {
828 printCOFFFileHeader(o);
832 static void DumpObject(const ObjectFile *o) {
834 outs() << o->getFileName()
835 << ":\tfile format " << o->getFileFormatName() << "\n\n";
838 DisassembleObject(o, Relocations);
839 if (Relocations && !Disassemble)
842 PrintSectionHeaders(o);
844 PrintSectionContents(o);
850 printPrivateFileHeader(o);
853 /// @brief Dump each object file in \a a;
854 static void DumpArchive(const Archive *a) {
855 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
857 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
858 if (std::error_code EC = ChildOrErr.getError()) {
859 // Ignore non-object files.
860 if (EC != object_error::invalid_file_type)
861 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
865 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
868 errs() << ToolName << ": '" << a->getFileName() << "': "
869 << "Unrecognized file type.\n";
873 /// @brief Open file and figure out how to dump it.
874 static void DumpInput(StringRef file) {
875 // If file isn't stdin, check that it exists.
876 if (file != "-" && !sys::fs::exists(file)) {
877 errs() << ToolName << ": '" << file << "': " << "No such file\n";
881 if (MachOOpt && Disassemble) {
882 DisassembleInputMachO(file);
886 // Attempt to open the binary.
887 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
888 if (std::error_code EC = BinaryOrErr.getError()) {
889 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
892 std::unique_ptr<Binary> binary(BinaryOrErr.get());
894 if (Archive *a = dyn_cast<Archive>(binary.get()))
896 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
899 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
902 int main(int argc, char **argv) {
903 // Print a stack trace if we signal out.
904 sys::PrintStackTraceOnErrorSignal();
905 PrettyStackTraceProgram X(argc, argv);
906 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
908 // Initialize targets and assembly printers/parsers.
909 llvm::InitializeAllTargetInfos();
910 llvm::InitializeAllTargetMCs();
911 llvm::InitializeAllAsmParsers();
912 llvm::InitializeAllDisassemblers();
914 // Register the target printer for --version.
915 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
917 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
918 TripleName = Triple::normalize(TripleName);
922 // Defaults to a.out if no filenames specified.
923 if (InputFilenames.size() == 0)
924 InputFilenames.push_back("a.out");
932 && !PrivateHeaders) {
933 cl::PrintHelpMessage();
937 std::for_each(InputFilenames.begin(), InputFilenames.end(),