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"
60 #include "llvm/Support/system_error.h"
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(error_code EC) {
155 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
160 static const Target *getTarget(const ObjectFile *Obj = NULL) {
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 TheTriple.setTriple(Triple::normalize(TripleName));
174 // Get the target specific parser.
176 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
179 errs() << ToolName << ": " << Error;
183 // Update the triple name and return the found target.
184 TripleName = TheTriple.getTriple();
188 // Write a graphviz file for the CFG inside an MCFunction.
189 // FIXME: Use GraphWriter
190 static void emitDOTFile(const char *FileName, const MCFunction &f,
192 // Start a new dot file.
194 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
195 if (!Error.empty()) {
196 errs() << "llvm-objdump: warning: " << Error << '\n';
200 Out << "digraph \"" << f.getName() << "\" {\n";
201 Out << "graph [ rankdir = \"LR\" ];\n";
202 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
203 // Only print blocks that have predecessors.
204 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
206 if (!hasPreds && i != f.begin())
209 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
210 // Print instructions.
211 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
213 if (ii != 0) // Not the first line, start a new row.
215 if (ii + 1 == ie) // Last line, add an end id.
218 // Escape special chars and print the instruction in mnemonic form.
220 raw_string_ostream OS(Str);
221 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
222 Out << DOT::EscapeString(OS.str());
224 Out << "\" shape=\"record\" ];\n";
227 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
228 se = (*i)->succ_end(); si != se; ++si)
229 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
230 << (*si)->getInsts()->getBeginAddr() << ":a\n";
235 void llvm::DumpBytes(StringRef bytes) {
236 static const char hex_rep[] = "0123456789abcdef";
237 // FIXME: The real way to do this is to figure out the longest instruction
238 // and align to that size before printing. I'll fix this when I get
239 // around to outputting relocations.
240 // 15 is the longest x86 instruction
241 // 3 is for the hex rep of a byte + a space.
242 // 1 is for the null terminator.
243 enum { OutputSize = (15 * 3) + 1 };
244 char output[OutputSize];
246 assert(bytes.size() <= 15
247 && "DumpBytes only supports instructions of up to 15 bytes");
248 memset(output, ' ', sizeof(output));
250 for (StringRef::iterator i = bytes.begin(),
251 e = bytes.end(); i != e; ++i) {
252 output[index] = hex_rep[(*i & 0xF0) >> 4];
253 output[index + 1] = hex_rep[*i & 0xF];
257 output[sizeof(output) - 1] = 0;
261 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
262 uint64_t a_addr, b_addr;
263 if (error(a.getOffset(a_addr))) return false;
264 if (error(b.getOffset(b_addr))) return false;
265 return a_addr < b_addr;
268 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
269 const Target *TheTarget = getTarget(Obj);
270 // getTarget() will have already issued a diagnostic if necessary, so
271 // just bail here if it failed.
275 // Package up features to be passed to target/subtarget
276 std::string FeaturesStr;
278 SubtargetFeatures Features;
279 for (unsigned i = 0; i != MAttrs.size(); ++i)
280 Features.AddFeature(MAttrs[i]);
281 FeaturesStr = Features.getString();
284 std::unique_ptr<const MCRegisterInfo> MRI(
285 TheTarget->createMCRegInfo(TripleName));
287 errs() << "error: no register info for target " << TripleName << "\n";
291 // Set up disassembler.
292 std::unique_ptr<const MCAsmInfo> AsmInfo(
293 TheTarget->createMCAsmInfo(*MRI, TripleName));
295 errs() << "error: no assembly info for target " << TripleName << "\n";
299 std::unique_ptr<const MCSubtargetInfo> STI(
300 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
302 errs() << "error: no subtarget info for target " << TripleName << "\n";
306 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
308 errs() << "error: no instruction info for target " << TripleName << "\n";
312 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
313 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
315 std::unique_ptr<MCDisassembler> DisAsm(
316 TheTarget->createMCDisassembler(*STI, Ctx));
319 errs() << "error: no disassembler for target " << TripleName << "\n";
325 std::unique_ptr<MCRelocationInfo> RelInfo(
326 TheTarget->createMCRelocationInfo(TripleName, Ctx));
328 std::unique_ptr<MCSymbolizer> Symzer(
329 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
332 DisAsm->setSymbolizer(std::move(Symzer));
336 std::unique_ptr<const MCInstrAnalysis> MIA(
337 TheTarget->createMCInstrAnalysis(MII.get()));
339 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
340 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
341 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
343 errs() << "error: no instruction printer for target " << TripleName
348 if (CFG || !YAMLCFG.empty()) {
349 std::unique_ptr<MCObjectDisassembler> OD(
350 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
351 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
352 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
353 AE = Mod->atom_end();
355 outs() << "Atom " << (*AI)->getName() << ": \n";
356 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
357 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
360 IP->printInst(&II->Inst, outs(), "");
366 for (MCModule::const_func_iterator FI = Mod->func_begin(),
367 FE = Mod->func_end();
369 static int filenum = 0;
370 emitDOTFile((Twine((*FI)->getName()) + "_" +
371 utostr(filenum) + ".dot").str().c_str(),
376 if (!YAMLCFG.empty()) {
378 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
379 if (!Error.empty()) {
380 errs() << ToolName << ": warning: " << Error << '\n';
383 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
387 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
388 "\t\t\t%08" PRIx64 ": ";
390 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
391 // in RelocSecs contain the relocations for section S.
393 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
394 for (const SectionRef &Section : Obj->sections()) {
395 section_iterator Sec2 = Section.getRelocatedSection();
396 if (Sec2 != Obj->section_end())
397 SectionRelocMap[*Sec2].push_back(Section);
400 for (const SectionRef &Section : Obj->sections()) {
402 if (error(Section.isText(Text)))
407 uint64_t SectionAddr;
408 if (error(Section.getAddress(SectionAddr)))
412 if (error(Section.getSize(SectSize)))
415 // Make a list of all the symbols in this section.
416 std::vector<std::pair<uint64_t, StringRef>> Symbols;
417 for (const SymbolRef &Symbol : Obj->symbols()) {
419 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
421 if (error(Symbol.getAddress(Address)))
423 if (Address == UnknownAddressOrSize)
425 Address -= SectionAddr;
426 if (Address >= SectSize)
430 if (error(Symbol.getName(Name)))
432 Symbols.push_back(std::make_pair(Address, Name));
436 // Sort the symbols by address, just in case they didn't come in that way.
437 array_pod_sort(Symbols.begin(), Symbols.end());
439 // Make a list of all the relocations for this section.
440 std::vector<RelocationRef> Rels;
442 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
443 for (const RelocationRef &Reloc : RelocSec.relocations()) {
444 Rels.push_back(Reloc);
449 // Sort relocations by address.
450 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
452 StringRef SegmentName = "";
453 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
454 DataRefImpl DR = Section.getRawDataRefImpl();
455 SegmentName = MachO->getSectionFinalSegmentName(DR);
458 if (error(Section.getName(name)))
460 outs() << "Disassembly of section ";
461 if (!SegmentName.empty())
462 outs() << SegmentName << ",";
463 outs() << name << ':';
465 // If the section has no symbols just insert a dummy one and disassemble
466 // the whole section.
468 Symbols.push_back(std::make_pair(0, name));
471 SmallString<40> Comments;
472 raw_svector_ostream CommentStream(Comments);
475 if (error(Section.getContents(Bytes)))
477 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
481 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
482 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
483 // Disassemble symbol by symbol.
484 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
485 uint64_t Start = Symbols[si].first;
487 // The end is either the size of the section or the beginning of the next
491 // Make sure this symbol takes up space.
492 else if (Symbols[si + 1].first != Start)
493 End = Symbols[si + 1].first - 1;
495 // This symbol has the same address as the next symbol. Skip it.
498 outs() << '\n' << Symbols[si].second << ":\n";
501 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
503 raw_ostream &DebugOut = nulls();
506 for (Index = Start; Index < End; Index += Size) {
509 if (DisAsm->getInstruction(Inst, Size, memoryObject,
511 DebugOut, CommentStream)) {
512 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
513 if (!NoShowRawInsn) {
515 DumpBytes(StringRef(Bytes.data() + Index, Size));
517 IP->printInst(&Inst, outs(), "");
518 outs() << CommentStream.str();
522 errs() << ToolName << ": warning: invalid instruction encoding\n";
524 Size = 1; // skip illegible bytes
527 // Print relocation for instruction.
528 while (rel_cur != rel_end) {
531 SmallString<16> name;
534 // If this relocation is hidden, skip it.
535 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
536 if (hidden) goto skip_print_rel;
538 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
539 // Stop when rel_cur's address is past the current instruction.
540 if (addr >= Index + Size) break;
541 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
542 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
544 outs() << format(Fmt.data(), SectionAddr + addr) << name
545 << "\t" << val << "\n";
555 static void PrintRelocations(const ObjectFile *Obj) {
556 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
558 for (const SectionRef &Section : Obj->sections()) {
559 if (Section.relocation_begin() == Section.relocation_end())
562 if (error(Section.getName(secname)))
564 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
565 for (const RelocationRef &Reloc : Section.relocations()) {
568 SmallString<32> relocname;
569 SmallString<32> valuestr;
570 if (error(Reloc.getHidden(hidden)))
574 if (error(Reloc.getTypeName(relocname)))
576 if (error(Reloc.getOffset(address)))
578 if (error(Reloc.getValueString(valuestr)))
580 outs() << format(Fmt.data(), address) << " " << relocname << " "
587 static void PrintSectionHeaders(const ObjectFile *Obj) {
588 outs() << "Sections:\n"
589 "Idx Name Size Address Type\n";
591 for (const SectionRef &Section : Obj->sections()) {
593 if (error(Section.getName(Name)))
596 if (error(Section.getAddress(Address)))
599 if (error(Section.getSize(Size)))
601 bool Text, Data, BSS;
602 if (error(Section.isText(Text)))
604 if (error(Section.isData(Data)))
606 if (error(Section.isBSS(BSS)))
608 std::string Type = (std::string(Text ? "TEXT " : "") +
609 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
610 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
611 Name.str().c_str(), Size, Address, Type.c_str());
616 static void PrintSectionContents(const ObjectFile *Obj) {
618 for (const SectionRef &Section : Obj->sections()) {
623 if (error(Section.getName(Name)))
625 if (error(Section.getContents(Contents)))
627 if (error(Section.getAddress(BaseAddr)))
629 if (error(Section.isBSS(BSS)))
632 outs() << "Contents of section " << Name << ":\n";
634 outs() << format("<skipping contents of bss section at [%04" PRIx64
635 ", %04" PRIx64 ")>\n", BaseAddr,
636 BaseAddr + Contents.size());
640 // Dump out the content as hex and printable ascii characters.
641 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
642 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
644 for (std::size_t i = 0; i < 16; ++i) {
645 if (i != 0 && i % 4 == 0)
648 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
649 << hexdigit(Contents[addr + i] & 0xF, true);
655 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
656 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
657 outs() << Contents[addr + i];
666 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
667 const coff_file_header *header;
668 if (error(coff->getHeader(header)))
671 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
672 const coff_symbol *Symbol;
674 if (error(coff->getSymbol(SI, Symbol)))
677 if (error(coff->getSymbolName(Symbol, Name)))
680 outs() << "[" << format("%2d", SI) << "]"
681 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
682 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
683 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
684 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
685 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
686 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
689 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
690 if (Symbol->isSectionDefinition()) {
691 const coff_aux_section_definition *asd;
692 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
696 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
697 , unsigned(asd->Length)
698 , unsigned(asd->NumberOfRelocations)
699 , unsigned(asd->NumberOfLinenumbers)
700 , unsigned(asd->CheckSum))
701 << format("assoc %d comdat %d\n"
702 , unsigned(asd->Number)
703 , unsigned(asd->Selection));
704 } else if (Symbol->isFileRecord()) {
705 const coff_aux_file *AF;
706 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
709 StringRef Name(AF->FileName,
710 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
711 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
713 SI = SI + Symbol->NumberOfAuxSymbols;
716 outs() << "AUX Unknown\n";
722 static void PrintSymbolTable(const ObjectFile *o) {
723 outs() << "SYMBOL TABLE:\n";
725 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
726 PrintCOFFSymbolTable(coff);
729 for (const SymbolRef &Symbol : o->symbols()) {
732 SymbolRef::Type Type;
734 uint32_t Flags = Symbol.getFlags();
735 section_iterator Section = o->section_end();
736 if (error(Symbol.getName(Name)))
738 if (error(Symbol.getAddress(Address)))
740 if (error(Symbol.getType(Type)))
742 if (error(Symbol.getSize(Size)))
744 if (error(Symbol.getSection(Section)))
747 bool Global = Flags & SymbolRef::SF_Global;
748 bool Weak = Flags & SymbolRef::SF_Weak;
749 bool Absolute = Flags & SymbolRef::SF_Absolute;
751 if (Address == UnknownAddressOrSize)
753 if (Size == UnknownAddressOrSize)
756 if (Type != SymbolRef::ST_Unknown)
757 GlobLoc = Global ? 'g' : 'l';
758 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
761 if (Type == SymbolRef::ST_File)
763 else if (Type == SymbolRef::ST_Function)
766 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
769 outs() << format(Fmt, Address) << " "
770 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
771 << (Weak ? 'w' : ' ') // Weak?
772 << ' ' // Constructor. Not supported yet.
773 << ' ' // Warning. Not supported yet.
774 << ' ' // Indirect reference to another symbol.
775 << Debug // Debugging (d) or dynamic (D) symbol.
776 << FileFunc // Name of function (F), file (f) or object (O).
780 } else if (Section == o->section_end()) {
783 if (const MachOObjectFile *MachO =
784 dyn_cast<const MachOObjectFile>(o)) {
785 DataRefImpl DR = Section->getRawDataRefImpl();
786 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
787 outs() << SegmentName << ",";
789 StringRef SectionName;
790 if (error(Section->getName(SectionName)))
792 outs() << SectionName;
795 << format("%08" PRIx64 " ", Size)
801 static void PrintUnwindInfo(const ObjectFile *o) {
802 outs() << "Unwind info:\n\n";
804 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
805 printCOFFUnwindInfo(coff);
807 // TODO: Extract DWARF dump tool to objdump.
808 errs() << "This operation is only currently supported "
809 "for COFF object files.\n";
814 static void printPrivateFileHeader(const ObjectFile *o) {
816 printELFFileHeader(o);
817 } else if (o->isCOFF()) {
818 printCOFFFileHeader(o);
822 static void DumpObject(const ObjectFile *o) {
824 outs() << o->getFileName()
825 << ":\tfile format " << o->getFileFormatName() << "\n\n";
828 DisassembleObject(o, Relocations);
829 if (Relocations && !Disassemble)
832 PrintSectionHeaders(o);
834 PrintSectionContents(o);
840 printPrivateFileHeader(o);
843 /// @brief Dump each object file in \a a;
844 static void DumpArchive(const Archive *a) {
845 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
847 std::unique_ptr<Binary> child;
848 if (error_code EC = i->getAsBinary(child)) {
849 // Ignore non-object files.
850 if (EC != object_error::invalid_file_type)
851 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
855 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
858 errs() << ToolName << ": '" << a->getFileName() << "': "
859 << "Unrecognized file type.\n";
863 /// @brief Open file and figure out how to dump it.
864 static void DumpInput(StringRef file) {
865 // If file isn't stdin, check that it exists.
866 if (file != "-" && !sys::fs::exists(file)) {
867 errs() << ToolName << ": '" << file << "': " << "No such file\n";
871 if (MachOOpt && Disassemble) {
872 DisassembleInputMachO(file);
876 // Attempt to open the binary.
877 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
878 if (error_code EC = BinaryOrErr.getError()) {
879 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
882 std::unique_ptr<Binary> binary(BinaryOrErr.get());
884 if (Archive *a = dyn_cast<Archive>(binary.get()))
886 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
889 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
892 int main(int argc, char **argv) {
893 // Print a stack trace if we signal out.
894 sys::PrintStackTraceOnErrorSignal();
895 PrettyStackTraceProgram X(argc, argv);
896 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
898 // Initialize targets and assembly printers/parsers.
899 llvm::InitializeAllTargetInfos();
900 llvm::InitializeAllTargetMCs();
901 llvm::InitializeAllAsmParsers();
902 llvm::InitializeAllDisassemblers();
904 // Register the target printer for --version.
905 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
907 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
908 TripleName = Triple::normalize(TripleName);
912 // Defaults to a.out if no filenames specified.
913 if (InputFilenames.size() == 0)
914 InputFilenames.push_back("a.out");
922 && !PrivateHeaders) {
923 cl::PrintHelpMessage();
927 std::for_each(InputFilenames.begin(), InputFilenames.end(),