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/MCAnalysis/MCObjectSymbolizer.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCDisassembler.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCInstrAnalysis.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectDisassembler.h"
36 #include "llvm/MC/MCObjectFileInfo.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"));
98 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
99 cl::value_desc("cpu-name"),
103 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
104 "see -version for available targets"));
107 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
108 "for each section."));
110 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
111 cl::aliasopt(SectionHeaders));
113 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
114 cl::aliasopt(SectionHeaders));
116 cl::list<std::string>
117 llvm::MAttrs("mattr",
119 cl::desc("Target specific attributes"),
120 cl::value_desc("a1,+a2,-a3,..."));
123 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
124 "do not print the instruction bytes."));
127 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
130 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
131 cl::aliasopt(UnwindInfo));
134 PrivateHeaders("private-headers",
135 cl::desc("Display format specific file headers"));
138 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
139 cl::aliasopt(PrivateHeaders));
142 Symbolize("symbolize", cl::desc("When disassembling instructions, "
143 "try to symbolize operands."));
146 CFG("cfg", cl::desc("Create a CFG for every function found in the object"
147 " and write it to a graphviz file"));
149 // FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
150 static cl::opt<std::string>
152 cl::desc("Create a CFG and write it as a YAML MCModule."),
153 cl::value_desc("yaml output file"));
155 static StringRef ToolName;
157 bool llvm::error(std::error_code EC) {
161 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
166 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
167 // Figure out the target triple.
168 llvm::Triple TheTriple("unknown-unknown-unknown");
169 if (TripleName.empty()) {
171 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
172 // TheTriple defaults to ELF, and COFF doesn't have an environment:
173 // the best we can do here is indicate that it is mach-o.
175 TheTriple.setObjectFormat(Triple::MachO);
178 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
179 if (COFFObj->getArch() == Triple::thumb)
180 TheTriple.setTriple("thumbv7-windows");
184 TheTriple.setTriple(Triple::normalize(TripleName));
186 // Get the target specific parser.
188 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
191 errs() << ToolName << ": " << Error;
195 // Update the triple name and return the found target.
196 TripleName = TheTriple.getTriple();
200 // Write a graphviz file for the CFG inside an MCFunction.
201 // FIXME: Use GraphWriter
202 static void emitDOTFile(const char *FileName, const MCFunction &f,
204 // Start a new dot file.
206 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
207 if (!Error.empty()) {
208 errs() << "llvm-objdump: warning: " << Error << '\n';
212 Out << "digraph \"" << f.getName() << "\" {\n";
213 Out << "graph [ rankdir = \"LR\" ];\n";
214 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
215 // Only print blocks that have predecessors.
216 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
218 if (!hasPreds && i != f.begin())
221 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
222 // Print instructions.
223 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
225 if (ii != 0) // Not the first line, start a new row.
227 if (ii + 1 == ie) // Last line, add an end id.
230 // Escape special chars and print the instruction in mnemonic form.
232 raw_string_ostream OS(Str);
233 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
234 Out << DOT::EscapeString(OS.str());
236 Out << "\" shape=\"record\" ];\n";
239 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
240 se = (*i)->succ_end(); si != se; ++si)
241 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
242 << (*si)->getInsts()->getBeginAddr() << ":a\n";
247 void llvm::DumpBytes(StringRef bytes) {
248 static const char hex_rep[] = "0123456789abcdef";
249 // FIXME: The real way to do this is to figure out the longest instruction
250 // and align to that size before printing. I'll fix this when I get
251 // around to outputting relocations.
252 // 15 is the longest x86 instruction
253 // 3 is for the hex rep of a byte + a space.
254 // 1 is for the null terminator.
255 enum { OutputSize = (15 * 3) + 1 };
256 char output[OutputSize];
258 assert(bytes.size() <= 15
259 && "DumpBytes only supports instructions of up to 15 bytes");
260 memset(output, ' ', sizeof(output));
262 for (StringRef::iterator i = bytes.begin(),
263 e = bytes.end(); i != e; ++i) {
264 output[index] = hex_rep[(*i & 0xF0) >> 4];
265 output[index + 1] = hex_rep[*i & 0xF];
269 output[sizeof(output) - 1] = 0;
273 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
274 uint64_t a_addr, b_addr;
275 if (error(a.getOffset(a_addr))) return false;
276 if (error(b.getOffset(b_addr))) return false;
277 return a_addr < b_addr;
280 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
281 const Target *TheTarget = getTarget(Obj);
282 // getTarget() will have already issued a diagnostic if necessary, so
283 // just bail here if it failed.
287 // Package up features to be passed to target/subtarget
288 std::string FeaturesStr;
290 SubtargetFeatures Features;
291 for (unsigned i = 0; i != MAttrs.size(); ++i)
292 Features.AddFeature(MAttrs[i]);
293 FeaturesStr = Features.getString();
296 std::unique_ptr<const MCRegisterInfo> MRI(
297 TheTarget->createMCRegInfo(TripleName));
299 errs() << "error: no register info for target " << TripleName << "\n";
303 // Set up disassembler.
304 std::unique_ptr<const MCAsmInfo> AsmInfo(
305 TheTarget->createMCAsmInfo(*MRI, TripleName));
307 errs() << "error: no assembly info for target " << TripleName << "\n";
311 std::unique_ptr<const MCSubtargetInfo> STI(
312 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
314 errs() << "error: no subtarget info for target " << TripleName << "\n";
318 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
320 errs() << "error: no instruction info for target " << TripleName << "\n";
324 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
325 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
327 std::unique_ptr<MCDisassembler> DisAsm(
328 TheTarget->createMCDisassembler(*STI, Ctx));
331 errs() << "error: no disassembler for target " << TripleName << "\n";
337 std::unique_ptr<MCRelocationInfo> RelInfo(
338 TheTarget->createMCRelocationInfo(TripleName, Ctx));
340 std::unique_ptr<MCSymbolizer> Symzer(
341 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
344 DisAsm->setSymbolizer(std::move(Symzer));
348 std::unique_ptr<const MCInstrAnalysis> MIA(
349 TheTarget->createMCInstrAnalysis(MII.get()));
351 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
352 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
353 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
355 errs() << "error: no instruction printer for target " << TripleName
360 if (CFG || !YAMLCFG.empty()) {
361 std::unique_ptr<MCObjectDisassembler> OD(
362 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
363 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
364 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
365 AE = Mod->atom_end();
367 outs() << "Atom " << (*AI)->getName() << ": \n";
368 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
369 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
372 IP->printInst(&II->Inst, outs(), "");
378 for (MCModule::const_func_iterator FI = Mod->func_begin(),
379 FE = Mod->func_end();
381 static int filenum = 0;
382 emitDOTFile((Twine((*FI)->getName()) + "_" +
383 utostr(filenum) + ".dot").str().c_str(),
388 if (!YAMLCFG.empty()) {
390 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
391 if (!Error.empty()) {
392 errs() << ToolName << ": warning: " << Error << '\n';
395 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
399 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
400 "\t\t\t%08" PRIx64 ": ";
402 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
403 // in RelocSecs contain the relocations for section S.
405 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
406 for (const SectionRef &Section : Obj->sections()) {
407 section_iterator Sec2 = Section.getRelocatedSection();
408 if (Sec2 != Obj->section_end())
409 SectionRelocMap[*Sec2].push_back(Section);
412 for (const SectionRef &Section : Obj->sections()) {
414 if (error(Section.isText(Text)))
419 uint64_t SectionAddr;
420 if (error(Section.getAddress(SectionAddr)))
424 if (error(Section.getSize(SectSize)))
427 // Make a list of all the symbols in this section.
428 std::vector<std::pair<uint64_t, StringRef>> Symbols;
429 for (const SymbolRef &Symbol : Obj->symbols()) {
431 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
433 if (error(Symbol.getAddress(Address)))
435 if (Address == UnknownAddressOrSize)
437 Address -= SectionAddr;
438 if (Address >= SectSize)
442 if (error(Symbol.getName(Name)))
444 Symbols.push_back(std::make_pair(Address, Name));
448 // Sort the symbols by address, just in case they didn't come in that way.
449 array_pod_sort(Symbols.begin(), Symbols.end());
451 // Make a list of all the relocations for this section.
452 std::vector<RelocationRef> Rels;
454 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
455 for (const RelocationRef &Reloc : RelocSec.relocations()) {
456 Rels.push_back(Reloc);
461 // Sort relocations by address.
462 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
464 StringRef SegmentName = "";
465 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
466 DataRefImpl DR = Section.getRawDataRefImpl();
467 SegmentName = MachO->getSectionFinalSegmentName(DR);
470 if (error(Section.getName(name)))
472 outs() << "Disassembly of section ";
473 if (!SegmentName.empty())
474 outs() << SegmentName << ",";
475 outs() << name << ':';
477 // If the section has no symbols just insert a dummy one and disassemble
478 // the whole section.
480 Symbols.push_back(std::make_pair(0, name));
483 SmallString<40> Comments;
484 raw_svector_ostream CommentStream(Comments);
487 if (error(Section.getContents(Bytes)))
489 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
493 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
494 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
495 // Disassemble symbol by symbol.
496 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
498 uint64_t Start = Symbols[si].first;
499 // The end is either the section end or the beginning of the next symbol.
500 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
501 // If this symbol has the same address as the next symbol, then skip it.
505 outs() << '\n' << Symbols[si].second << ":\n";
508 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
510 raw_ostream &DebugOut = nulls();
513 for (Index = Start; Index < End; Index += Size) {
516 if (DisAsm->getInstruction(Inst, Size, memoryObject,
518 DebugOut, CommentStream)) {
519 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
520 if (!NoShowRawInsn) {
522 DumpBytes(StringRef(Bytes.data() + Index, Size));
524 IP->printInst(&Inst, outs(), "");
525 outs() << CommentStream.str();
529 errs() << ToolName << ": warning: invalid instruction encoding\n";
531 Size = 1; // skip illegible bytes
534 // Print relocation for instruction.
535 while (rel_cur != rel_end) {
538 SmallString<16> name;
541 // If this relocation is hidden, skip it.
542 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
543 if (hidden) goto skip_print_rel;
545 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
546 // Stop when rel_cur's address is past the current instruction.
547 if (addr >= Index + Size) break;
548 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
549 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
551 outs() << format(Fmt.data(), SectionAddr + addr) << name
552 << "\t" << val << "\n";
562 static void PrintRelocations(const ObjectFile *Obj) {
563 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
565 for (const SectionRef &Section : Obj->sections()) {
566 if (Section.relocation_begin() == Section.relocation_end())
569 if (error(Section.getName(secname)))
571 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
572 for (const RelocationRef &Reloc : Section.relocations()) {
575 SmallString<32> relocname;
576 SmallString<32> valuestr;
577 if (error(Reloc.getHidden(hidden)))
581 if (error(Reloc.getTypeName(relocname)))
583 if (error(Reloc.getOffset(address)))
585 if (error(Reloc.getValueString(valuestr)))
587 outs() << format(Fmt.data(), address) << " " << relocname << " "
594 static void PrintSectionHeaders(const ObjectFile *Obj) {
595 outs() << "Sections:\n"
596 "Idx Name Size Address Type\n";
598 for (const SectionRef &Section : Obj->sections()) {
600 if (error(Section.getName(Name)))
603 if (error(Section.getAddress(Address)))
606 if (error(Section.getSize(Size)))
608 bool Text, Data, BSS;
609 if (error(Section.isText(Text)))
611 if (error(Section.isData(Data)))
613 if (error(Section.isBSS(BSS)))
615 std::string Type = (std::string(Text ? "TEXT " : "") +
616 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
617 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
618 Name.str().c_str(), Size, Address, Type.c_str());
623 static void PrintSectionContents(const ObjectFile *Obj) {
625 for (const SectionRef &Section : Obj->sections()) {
630 if (error(Section.getName(Name)))
632 if (error(Section.getAddress(BaseAddr)))
634 if (error(Section.isBSS(BSS)))
637 outs() << "Contents of section " << Name << ":\n";
640 if (error(Section.getSize(Size)))
642 outs() << format("<skipping contents of bss section at [%04" PRIx64
643 ", %04" PRIx64 ")>\n",
644 BaseAddr, BaseAddr + Size);
648 if (error(Section.getContents(Contents)))
651 // Dump out the content as hex and printable ascii characters.
652 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
653 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
655 for (std::size_t i = 0; i < 16; ++i) {
656 if (i != 0 && i % 4 == 0)
659 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
660 << hexdigit(Contents[addr + i] & 0xF, true);
666 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
667 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
668 outs() << Contents[addr + i];
677 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
678 const coff_file_header *header;
679 if (error(coff->getHeader(header)))
682 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
683 const coff_symbol *Symbol;
685 if (error(coff->getSymbol(SI, Symbol)))
688 if (error(coff->getSymbolName(Symbol, Name)))
691 outs() << "[" << format("%2d", SI) << "]"
692 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
693 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
694 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
695 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
696 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
697 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
700 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
701 if (Symbol->isSectionDefinition()) {
702 const coff_aux_section_definition *asd;
703 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
707 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
708 , unsigned(asd->Length)
709 , unsigned(asd->NumberOfRelocations)
710 , unsigned(asd->NumberOfLinenumbers)
711 , unsigned(asd->CheckSum))
712 << format("assoc %d comdat %d\n"
713 , unsigned(asd->Number)
714 , unsigned(asd->Selection));
715 } else if (Symbol->isFileRecord()) {
716 const coff_aux_file *AF;
717 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
720 StringRef Name(AF->FileName,
721 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
722 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
724 SI = SI + Symbol->NumberOfAuxSymbols;
727 outs() << "AUX Unknown\n";
733 static void PrintSymbolTable(const ObjectFile *o) {
734 outs() << "SYMBOL TABLE:\n";
736 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
737 PrintCOFFSymbolTable(coff);
740 for (const SymbolRef &Symbol : o->symbols()) {
743 SymbolRef::Type Type;
745 uint32_t Flags = Symbol.getFlags();
746 section_iterator Section = o->section_end();
747 if (error(Symbol.getName(Name)))
749 if (error(Symbol.getAddress(Address)))
751 if (error(Symbol.getType(Type)))
753 if (error(Symbol.getSize(Size)))
755 if (error(Symbol.getSection(Section)))
758 bool Global = Flags & SymbolRef::SF_Global;
759 bool Weak = Flags & SymbolRef::SF_Weak;
760 bool Absolute = Flags & SymbolRef::SF_Absolute;
762 if (Address == UnknownAddressOrSize)
764 if (Size == UnknownAddressOrSize)
767 if (Type != SymbolRef::ST_Unknown)
768 GlobLoc = Global ? 'g' : 'l';
769 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
772 if (Type == SymbolRef::ST_File)
774 else if (Type == SymbolRef::ST_Function)
777 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
780 outs() << format(Fmt, Address) << " "
781 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
782 << (Weak ? 'w' : ' ') // Weak?
783 << ' ' // Constructor. Not supported yet.
784 << ' ' // Warning. Not supported yet.
785 << ' ' // Indirect reference to another symbol.
786 << Debug // Debugging (d) or dynamic (D) symbol.
787 << FileFunc // Name of function (F), file (f) or object (O).
791 } else if (Section == o->section_end()) {
794 if (const MachOObjectFile *MachO =
795 dyn_cast<const MachOObjectFile>(o)) {
796 DataRefImpl DR = Section->getRawDataRefImpl();
797 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
798 outs() << SegmentName << ",";
800 StringRef SectionName;
801 if (error(Section->getName(SectionName)))
803 outs() << SectionName;
806 << format("%08" PRIx64 " ", Size)
812 static void PrintUnwindInfo(const ObjectFile *o) {
813 outs() << "Unwind info:\n\n";
815 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
816 printCOFFUnwindInfo(coff);
817 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
818 printMachOUnwindInfo(MachO);
820 // TODO: Extract DWARF dump tool to objdump.
821 errs() << "This operation is only currently supported "
822 "for COFF and MachO object files.\n";
827 static void printPrivateFileHeader(const ObjectFile *o) {
829 printELFFileHeader(o);
830 } else if (o->isCOFF()) {
831 printCOFFFileHeader(o);
835 static void DumpObject(const ObjectFile *o) {
837 outs() << o->getFileName()
838 << ":\tfile format " << o->getFileFormatName() << "\n\n";
841 DisassembleObject(o, Relocations);
842 if (Relocations && !Disassemble)
845 PrintSectionHeaders(o);
847 PrintSectionContents(o);
853 printPrivateFileHeader(o);
856 /// @brief Dump each object file in \a a;
857 static void DumpArchive(const Archive *a) {
858 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
860 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
861 if (std::error_code EC = ChildOrErr.getError()) {
862 // Ignore non-object files.
863 if (EC != object_error::invalid_file_type)
864 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
868 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
871 errs() << ToolName << ": '" << a->getFileName() << "': "
872 << "Unrecognized file type.\n";
876 /// @brief Open file and figure out how to dump it.
877 static void DumpInput(StringRef file) {
878 // If file isn't stdin, check that it exists.
879 if (file != "-" && !sys::fs::exists(file)) {
880 errs() << ToolName << ": '" << file << "': " << "No such file\n";
884 if (MachOOpt && Disassemble) {
885 DisassembleInputMachO(file);
889 // Attempt to open the binary.
890 ErrorOr<std::unique_ptr<Binary>> BinaryOrErr = createBinary(file);
891 if (std::error_code EC = BinaryOrErr.getError()) {
892 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
895 Binary &Binary = *BinaryOrErr.get();
897 if (Archive *a = dyn_cast<Archive>(&Binary))
899 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
902 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
905 int main(int argc, char **argv) {
906 // Print a stack trace if we signal out.
907 sys::PrintStackTraceOnErrorSignal();
908 PrettyStackTraceProgram X(argc, argv);
909 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
911 // Initialize targets and assembly printers/parsers.
912 llvm::InitializeAllTargetInfos();
913 llvm::InitializeAllTargetMCs();
914 llvm::InitializeAllAsmParsers();
915 llvm::InitializeAllDisassemblers();
917 // Register the target printer for --version.
918 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
920 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
921 TripleName = Triple::normalize(TripleName);
925 // Defaults to a.out if no filenames specified.
926 if (InputFilenames.size() == 0)
927 InputFilenames.push_back("a.out");
935 && !PrivateHeaders) {
936 cl::PrintHelpMessage();
940 std::for_each(InputFilenames.begin(), InputFilenames.end(),