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/MCAsmInfo.h"
24 #include "llvm/MC/MCAtom.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCFunction.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrAnalysis.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCModule.h"
33 #include "llvm/MC/MCModuleYAML.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 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
227 Out << DOT::EscapeString(OS.str());
229 Out << "\" shape=\"record\" ];\n";
232 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
233 se = (*i)->succ_end(); si != se; ++si)
234 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
235 << (*si)->getInsts()->getBeginAddr() << ":a\n";
240 void llvm::DumpBytes(StringRef bytes) {
241 static const char hex_rep[] = "0123456789abcdef";
242 // FIXME: The real way to do this is to figure out the longest instruction
243 // and align to that size before printing. I'll fix this when I get
244 // around to outputting relocations.
245 // 15 is the longest x86 instruction
246 // 3 is for the hex rep of a byte + a space.
247 // 1 is for the null terminator.
248 enum { OutputSize = (15 * 3) + 1 };
249 char output[OutputSize];
251 assert(bytes.size() <= 15
252 && "DumpBytes only supports instructions of up to 15 bytes");
253 memset(output, ' ', sizeof(output));
255 for (StringRef::iterator i = bytes.begin(),
256 e = bytes.end(); i != e; ++i) {
257 output[index] = hex_rep[(*i & 0xF0) >> 4];
258 output[index + 1] = hex_rep[*i & 0xF];
262 output[sizeof(output) - 1] = 0;
266 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
267 uint64_t a_addr, b_addr;
268 if (error(a.getOffset(a_addr))) return false;
269 if (error(b.getOffset(b_addr))) return false;
270 return a_addr < b_addr;
273 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
274 const Target *TheTarget = getTarget(Obj);
275 // getTarget() will have already issued a diagnostic if necessary, so
276 // just bail here if it failed.
280 // Package up features to be passed to target/subtarget
281 std::string FeaturesStr;
283 SubtargetFeatures Features;
284 for (unsigned i = 0; i != MAttrs.size(); ++i)
285 Features.AddFeature(MAttrs[i]);
286 FeaturesStr = Features.getString();
289 std::unique_ptr<const MCRegisterInfo> MRI(
290 TheTarget->createMCRegInfo(TripleName));
292 errs() << "error: no register info for target " << TripleName << "\n";
296 // Set up disassembler.
297 std::unique_ptr<const MCAsmInfo> AsmInfo(
298 TheTarget->createMCAsmInfo(*MRI, TripleName));
300 errs() << "error: no assembly info for target " << TripleName << "\n";
304 std::unique_ptr<const MCSubtargetInfo> STI(
305 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
307 errs() << "error: no subtarget info for target " << TripleName << "\n";
311 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
313 errs() << "error: no instruction info for target " << TripleName << "\n";
317 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
318 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
320 std::unique_ptr<MCDisassembler> DisAsm(
321 TheTarget->createMCDisassembler(*STI, Ctx));
324 errs() << "error: no disassembler for target " << TripleName << "\n";
330 std::unique_ptr<MCRelocationInfo> RelInfo(
331 TheTarget->createMCRelocationInfo(TripleName, Ctx));
333 std::unique_ptr<MCSymbolizer> Symzer(
334 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
337 DisAsm->setSymbolizer(std::move(Symzer));
341 std::unique_ptr<const MCInstrAnalysis> MIA(
342 TheTarget->createMCInstrAnalysis(MII.get()));
344 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
345 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
346 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
348 errs() << "error: no instruction printer for target " << TripleName
353 if (CFG || !YAMLCFG.empty()) {
354 std::unique_ptr<MCObjectDisassembler> OD(
355 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
356 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
357 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
358 AE = Mod->atom_end();
360 outs() << "Atom " << (*AI)->getName() << ": \n";
361 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
362 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
365 IP->printInst(&II->Inst, outs(), "");
371 for (MCModule::const_func_iterator FI = Mod->func_begin(),
372 FE = Mod->func_end();
374 static int filenum = 0;
375 emitDOTFile((Twine((*FI)->getName()) + "_" +
376 utostr(filenum) + ".dot").str().c_str(),
381 if (!YAMLCFG.empty()) {
383 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
384 if (!Error.empty()) {
385 errs() << ToolName << ": warning: " << Error << '\n';
388 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
392 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
393 "\t\t\t%08" PRIx64 ": ";
395 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
396 // in RelocSecs contain the relocations for section S.
398 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
399 for (const SectionRef &Section : Obj->sections()) {
400 section_iterator Sec2 = Section.getRelocatedSection();
401 if (Sec2 != Obj->section_end())
402 SectionRelocMap[*Sec2].push_back(Section);
405 for (const SectionRef &Section : Obj->sections()) {
407 if (error(Section.isText(Text)))
412 uint64_t SectionAddr;
413 if (error(Section.getAddress(SectionAddr)))
417 if (error(Section.getSize(SectSize)))
420 // Make a list of all the symbols in this section.
421 std::vector<std::pair<uint64_t, StringRef>> Symbols;
422 for (const SymbolRef &Symbol : Obj->symbols()) {
424 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
426 if (error(Symbol.getAddress(Address)))
428 if (Address == UnknownAddressOrSize)
430 Address -= SectionAddr;
431 if (Address >= SectSize)
435 if (error(Symbol.getName(Name)))
437 Symbols.push_back(std::make_pair(Address, Name));
441 // Sort the symbols by address, just in case they didn't come in that way.
442 array_pod_sort(Symbols.begin(), Symbols.end());
444 // Make a list of all the relocations for this section.
445 std::vector<RelocationRef> Rels;
447 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
448 for (const RelocationRef &Reloc : RelocSec.relocations()) {
449 Rels.push_back(Reloc);
454 // Sort relocations by address.
455 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
457 StringRef SegmentName = "";
458 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
459 DataRefImpl DR = Section.getRawDataRefImpl();
460 SegmentName = MachO->getSectionFinalSegmentName(DR);
463 if (error(Section.getName(name)))
465 outs() << "Disassembly of section ";
466 if (!SegmentName.empty())
467 outs() << SegmentName << ",";
468 outs() << name << ':';
470 // If the section has no symbols just insert a dummy one and disassemble
471 // the whole section.
473 Symbols.push_back(std::make_pair(0, name));
475 small_string_ostream<40> Comments;
478 if (error(Section.getContents(Bytes)))
480 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
484 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
485 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
486 // Disassemble symbol by symbol.
487 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
488 uint64_t Start = Symbols[si].first;
490 // The end is either the size of the section or the beginning of the next
494 // Make sure this symbol takes up space.
495 else if (Symbols[si + 1].first != Start)
496 End = Symbols[si + 1].first - 1;
498 // This symbol has the same address as the next symbol. Skip it.
501 outs() << '\n' << Symbols[si].second << ":\n";
504 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
506 raw_ostream &DebugOut = nulls();
509 for (Index = Start; Index < End; Index += Size) {
512 if (DisAsm->getInstruction(Inst, Size, memoryObject,
513 SectionAddr + Index, DebugOut, Comments)) {
514 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
515 if (!NoShowRawInsn) {
517 DumpBytes(StringRef(Bytes.data() + Index, Size));
519 IP->printInst(&Inst, outs(), "");
520 outs() << Comments.str();
524 errs() << ToolName << ": warning: invalid instruction encoding\n";
526 Size = 1; // skip illegible bytes
529 // Print relocation for instruction.
530 while (rel_cur != rel_end) {
533 SmallString<16> name;
536 // If this relocation is hidden, skip it.
537 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
538 if (hidden) goto skip_print_rel;
540 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
541 // Stop when rel_cur's address is past the current instruction.
542 if (addr >= Index + Size) break;
543 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
544 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
546 outs() << format(Fmt.data(), SectionAddr + addr) << name
547 << "\t" << val << "\n";
557 static void PrintRelocations(const ObjectFile *Obj) {
558 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
560 for (const SectionRef &Section : Obj->sections()) {
561 if (Section.relocation_begin() == Section.relocation_end())
564 if (error(Section.getName(secname)))
566 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
567 for (const RelocationRef &Reloc : Section.relocations()) {
570 SmallString<32> relocname;
571 SmallString<32> valuestr;
572 if (error(Reloc.getHidden(hidden)))
576 if (error(Reloc.getTypeName(relocname)))
578 if (error(Reloc.getOffset(address)))
580 if (error(Reloc.getValueString(valuestr)))
582 outs() << format(Fmt.data(), address) << " " << relocname << " "
589 static void PrintSectionHeaders(const ObjectFile *Obj) {
590 outs() << "Sections:\n"
591 "Idx Name Size Address Type\n";
593 for (const SectionRef &Section : Obj->sections()) {
595 if (error(Section.getName(Name)))
598 if (error(Section.getAddress(Address)))
601 if (error(Section.getSize(Size)))
603 bool Text, Data, BSS;
604 if (error(Section.isText(Text)))
606 if (error(Section.isData(Data)))
608 if (error(Section.isBSS(BSS)))
610 std::string Type = (std::string(Text ? "TEXT " : "") +
611 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
612 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
613 Name.str().c_str(), Size, Address, Type.c_str());
618 static void PrintSectionContents(const ObjectFile *Obj) {
620 for (const SectionRef &Section : Obj->sections()) {
625 if (error(Section.getName(Name)))
627 if (error(Section.getContents(Contents)))
629 if (error(Section.getAddress(BaseAddr)))
631 if (error(Section.isBSS(BSS)))
634 outs() << "Contents of section " << Name << ":\n";
636 outs() << format("<skipping contents of bss section at [%04" PRIx64
637 ", %04" PRIx64 ")>\n", BaseAddr,
638 BaseAddr + Contents.size());
642 // Dump out the content as hex and printable ascii characters.
643 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
644 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
646 for (std::size_t i = 0; i < 16; ++i) {
647 if (i != 0 && i % 4 == 0)
650 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
651 << hexdigit(Contents[addr + i] & 0xF, true);
657 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
658 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
659 outs() << Contents[addr + i];
668 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
669 const coff_file_header *header;
670 if (error(coff->getHeader(header)))
673 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
674 const coff_symbol *Symbol;
676 if (error(coff->getSymbol(SI, Symbol)))
679 if (error(coff->getSymbolName(Symbol, Name)))
682 outs() << "[" << format("%2d", SI) << "]"
683 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
684 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
685 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
686 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
687 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
688 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
691 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
692 if (Symbol->isSectionDefinition()) {
693 const coff_aux_section_definition *asd;
694 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
698 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
699 , unsigned(asd->Length)
700 , unsigned(asd->NumberOfRelocations)
701 , unsigned(asd->NumberOfLinenumbers)
702 , unsigned(asd->CheckSum))
703 << format("assoc %d comdat %d\n"
704 , unsigned(asd->Number)
705 , unsigned(asd->Selection));
706 } else if (Symbol->isFileRecord()) {
707 const coff_aux_file *AF;
708 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
711 StringRef Name(AF->FileName,
712 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
713 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
715 SI = SI + Symbol->NumberOfAuxSymbols;
718 outs() << "AUX Unknown\n";
724 static void PrintSymbolTable(const ObjectFile *o) {
725 outs() << "SYMBOL TABLE:\n";
727 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
728 PrintCOFFSymbolTable(coff);
731 for (const SymbolRef &Symbol : o->symbols()) {
734 SymbolRef::Type Type;
736 uint32_t Flags = Symbol.getFlags();
737 section_iterator Section = o->section_end();
738 if (error(Symbol.getName(Name)))
740 if (error(Symbol.getAddress(Address)))
742 if (error(Symbol.getType(Type)))
744 if (error(Symbol.getSize(Size)))
746 if (error(Symbol.getSection(Section)))
749 bool Global = Flags & SymbolRef::SF_Global;
750 bool Weak = Flags & SymbolRef::SF_Weak;
751 bool Absolute = Flags & SymbolRef::SF_Absolute;
753 if (Address == UnknownAddressOrSize)
755 if (Size == UnknownAddressOrSize)
758 if (Type != SymbolRef::ST_Unknown)
759 GlobLoc = Global ? 'g' : 'l';
760 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
763 if (Type == SymbolRef::ST_File)
765 else if (Type == SymbolRef::ST_Function)
768 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
771 outs() << format(Fmt, Address) << " "
772 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
773 << (Weak ? 'w' : ' ') // Weak?
774 << ' ' // Constructor. Not supported yet.
775 << ' ' // Warning. Not supported yet.
776 << ' ' // Indirect reference to another symbol.
777 << Debug // Debugging (d) or dynamic (D) symbol.
778 << FileFunc // Name of function (F), file (f) or object (O).
782 } else if (Section == o->section_end()) {
785 if (const MachOObjectFile *MachO =
786 dyn_cast<const MachOObjectFile>(o)) {
787 DataRefImpl DR = Section->getRawDataRefImpl();
788 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
789 outs() << SegmentName << ",";
791 StringRef SectionName;
792 if (error(Section->getName(SectionName)))
794 outs() << SectionName;
797 << format("%08" PRIx64 " ", Size)
803 static void PrintUnwindInfo(const ObjectFile *o) {
804 outs() << "Unwind info:\n\n";
806 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
807 printCOFFUnwindInfo(coff);
809 // TODO: Extract DWARF dump tool to objdump.
810 errs() << "This operation is only currently supported "
811 "for COFF object files.\n";
816 static void printPrivateFileHeader(const ObjectFile *o) {
818 printELFFileHeader(o);
819 } else if (o->isCOFF()) {
820 printCOFFFileHeader(o);
824 static void DumpObject(const ObjectFile *o) {
826 outs() << o->getFileName()
827 << ":\tfile format " << o->getFileFormatName() << "\n\n";
830 DisassembleObject(o, Relocations);
831 if (Relocations && !Disassemble)
834 PrintSectionHeaders(o);
836 PrintSectionContents(o);
842 printPrivateFileHeader(o);
845 /// @brief Dump each object file in \a a;
846 static void DumpArchive(const Archive *a) {
847 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
849 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
850 if (std::error_code EC = ChildOrErr.getError()) {
851 // Ignore non-object files.
852 if (EC != object_error::invalid_file_type)
853 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
857 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
860 errs() << ToolName << ": '" << a->getFileName() << "': "
861 << "Unrecognized file type.\n";
865 /// @brief Open file and figure out how to dump it.
866 static void DumpInput(StringRef file) {
867 // If file isn't stdin, check that it exists.
868 if (file != "-" && !sys::fs::exists(file)) {
869 errs() << ToolName << ": '" << file << "': " << "No such file\n";
873 if (MachOOpt && Disassemble) {
874 DisassembleInputMachO(file);
878 // Attempt to open the binary.
879 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
880 if (std::error_code EC = BinaryOrErr.getError()) {
881 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
884 std::unique_ptr<Binary> binary(BinaryOrErr.get());
886 if (Archive *a = dyn_cast<Archive>(binary.get()))
888 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
891 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
894 int main(int argc, char **argv) {
895 // Print a stack trace if we signal out.
896 sys::PrintStackTraceOnErrorSignal();
897 PrettyStackTraceProgram X(argc, argv);
898 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
900 // Initialize targets and assembly printers/parsers.
901 llvm::InitializeAllTargetInfos();
902 llvm::InitializeAllTargetMCs();
903 llvm::InitializeAllAsmParsers();
904 llvm::InitializeAllDisassemblers();
906 // Register the target printer for --version.
907 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
909 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
910 TripleName = Triple::normalize(TripleName);
914 // Defaults to a.out if no filenames specified.
915 if (InputFilenames.size() == 0)
916 InputFilenames.push_back("a.out");
924 && !PrivateHeaders) {
925 cl::PrintHelpMessage();
929 std::for_each(InputFilenames.begin(), InputFilenames.end(),