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/OwningPtr.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCAtom.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler.h"
28 #include "llvm/MC/MCFunction.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCInstrAnalysis.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCModule.h"
34 #include "llvm/MC/MCModuleYAML.h"
35 #include "llvm/MC/MCObjectDisassembler.h"
36 #include "llvm/MC/MCObjectFileInfo.h"
37 #include "llvm/MC/MCObjectSymbolizer.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCRelocationInfo.h"
40 #include "llvm/MC/MCSubtargetInfo.h"
41 #include "llvm/Object/Archive.h"
42 #include "llvm/Object/COFF.h"
43 #include "llvm/Object/MachO.h"
44 #include "llvm/Object/ObjectFile.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/FileSystem.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/GraphWriter.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Support/ManagedStatic.h"
53 #include "llvm/Support/MemoryBuffer.h"
54 #include "llvm/Support/MemoryObject.h"
55 #include "llvm/Support/PrettyStackTrace.h"
56 #include "llvm/Support/Signals.h"
57 #include "llvm/Support/SourceMgr.h"
58 #include "llvm/Support/TargetRegistry.h"
59 #include "llvm/Support/TargetSelect.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Support/system_error.h"
67 using namespace object;
69 static cl::list<std::string>
70 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
73 Disassemble("disassemble",
74 cl::desc("Display assembler mnemonics for the machine instructions"));
76 Disassembled("d", cl::desc("Alias for --disassemble"),
77 cl::aliasopt(Disassemble));
80 Relocations("r", cl::desc("Display the relocation entries in the file"));
83 SectionContents("s", cl::desc("Display the content of each section"));
86 SymbolTable("t", cl::desc("Display the symbol table"));
89 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
91 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
94 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
95 "see -version for available targets"));
98 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
99 "see -version for available targets"));
102 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
103 "for each section."));
105 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
106 cl::aliasopt(SectionHeaders));
108 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
109 cl::aliasopt(SectionHeaders));
111 static cl::list<std::string>
114 cl::desc("Target specific attributes"),
115 cl::value_desc("a1,+a2,-a3,..."));
118 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
119 "do not print the instruction bytes."));
122 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
125 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
126 cl::aliasopt(UnwindInfo));
129 PrivateHeaders("private-headers",
130 cl::desc("Display format specific file headers"));
133 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
134 cl::aliasopt(PrivateHeaders));
137 Symbolize("symbolize", cl::desc("When disassembling instructions, "
138 "try to symbolize operands."));
141 CFG("cfg", cl::desc("Create a CFG for every function found in the object"
142 " and write it to a graphviz file"));
144 // FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
145 static cl::opt<std::string>
147 cl::desc("Create a CFG and write it as a YAML MCModule."),
148 cl::value_desc("yaml output file"));
150 static StringRef ToolName;
152 bool llvm::error(error_code ec) {
153 if (!ec) return false;
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.setEnvironment(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);
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 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
286 errs() << "error: no register info for target " << TripleName << "\n";
290 // Set up disassembler.
291 OwningPtr<const MCAsmInfo> AsmInfo(
292 TheTarget->createMCAsmInfo(*MRI, TripleName));
294 errs() << "error: no assembly info for target " << TripleName << "\n";
298 OwningPtr<const MCSubtargetInfo> STI(
299 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
301 errs() << "error: no subtarget info for target " << TripleName << "\n";
305 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
307 errs() << "error: no instruction info for target " << TripleName << "\n";
311 OwningPtr<MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
313 errs() << "error: no disassembler for target " << TripleName << "\n";
317 OwningPtr<const MCObjectFileInfo> MOFI;
318 OwningPtr<MCContext> Ctx;
321 MOFI.reset(new MCObjectFileInfo);
322 Ctx.reset(new MCContext(AsmInfo.get(), MRI.get(), MOFI.get()));
323 OwningPtr<MCRelocationInfo> RelInfo(
324 TheTarget->createMCRelocationInfo(TripleName, *Ctx.get()));
326 OwningPtr<MCSymbolizer> Symzer(
327 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, Obj));
329 DisAsm->setSymbolizer(Symzer);
333 OwningPtr<const MCInstrAnalysis>
334 MIA(TheTarget->createMCInstrAnalysis(MII.get()));
336 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
337 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
338 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
340 errs() << "error: no instruction printer for target " << TripleName
345 if (CFG || !YAMLCFG.empty()) {
346 OwningPtr<MCObjectDisassembler> OD(
347 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
348 OwningPtr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
349 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
350 AE = Mod->atom_end();
352 outs() << "Atom " << (*AI)->getName() << ": \n";
353 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
354 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
357 IP->printInst(&II->Inst, outs(), "");
363 for (MCModule::const_func_iterator FI = Mod->func_begin(),
364 FE = Mod->func_end();
366 static int filenum = 0;
367 emitDOTFile((Twine((*FI)->getName()) + "_" +
368 utostr(filenum) + ".dot").str().c_str(),
373 if (!YAMLCFG.empty()) {
375 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error);
376 if (!Error.empty()) {
377 errs() << ToolName << ": warning: " << Error << '\n';
380 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
386 for (section_iterator i = Obj->begin_sections(),
387 e = Obj->end_sections();
388 i != e; i.increment(ec)) {
389 if (error(ec)) break;
391 if (error(i->isText(text))) break;
394 uint64_t SectionAddr;
395 if (error(i->getAddress(SectionAddr))) break;
397 // Make a list of all the symbols in this section.
398 std::vector<std::pair<uint64_t, StringRef> > Symbols;
399 for (symbol_iterator si = Obj->begin_symbols(),
400 se = Obj->end_symbols();
401 si != se; si.increment(ec)) {
403 if (!error(i->containsSymbol(*si, contains)) && contains) {
405 if (error(si->getAddress(Address))) break;
406 if (Address == UnknownAddressOrSize) continue;
407 Address -= SectionAddr;
410 if (error(si->getName(Name))) break;
411 Symbols.push_back(std::make_pair(Address, Name));
415 // Sort the symbols by address, just in case they didn't come in that way.
416 array_pod_sort(Symbols.begin(), Symbols.end());
418 // Make a list of all the relocations for this section.
419 std::vector<RelocationRef> Rels;
421 for (relocation_iterator ri = i->begin_relocations(),
422 re = i->end_relocations();
423 ri != re; ri.increment(ec)) {
424 if (error(ec)) break;
429 // Sort relocations by address.
430 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
432 StringRef SegmentName = "";
433 if (const MachOObjectFile *MachO =
434 dyn_cast<const MachOObjectFile>(Obj)) {
435 DataRefImpl DR = i->getRawDataRefImpl();
436 SegmentName = MachO->getSectionFinalSegmentName(DR);
439 if (error(i->getName(name))) break;
440 outs() << "Disassembly of section ";
441 if (!SegmentName.empty())
442 outs() << SegmentName << ",";
443 outs() << name << ':';
445 // If the section has no symbols just insert a dummy one and disassemble
446 // the whole section.
448 Symbols.push_back(std::make_pair(0, name));
451 SmallString<40> Comments;
452 raw_svector_ostream CommentStream(Comments);
455 if (error(i->getContents(Bytes))) break;
456 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
460 if (error(i->getSize(SectSize))) break;
462 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
463 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
464 // Disassemble symbol by symbol.
465 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
466 uint64_t Start = Symbols[si].first;
468 // The end is either the size of the section or the beginning of the next
472 // Make sure this symbol takes up space.
473 else if (Symbols[si + 1].first != Start)
474 End = Symbols[si + 1].first - 1;
476 // This symbol has the same address as the next symbol. Skip it.
479 outs() << '\n' << Symbols[si].second << ":\n";
482 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
484 raw_ostream &DebugOut = nulls();
487 for (Index = Start; Index < End; Index += Size) {
490 if (DisAsm->getInstruction(Inst, Size, memoryObject,
492 DebugOut, CommentStream)) {
493 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
494 if (!NoShowRawInsn) {
496 DumpBytes(StringRef(Bytes.data() + Index, Size));
498 IP->printInst(&Inst, outs(), "");
499 outs() << CommentStream.str();
503 errs() << ToolName << ": warning: invalid instruction encoding\n";
505 Size = 1; // skip illegible bytes
508 // Print relocation for instruction.
509 while (rel_cur != rel_end) {
512 SmallString<16> name;
515 // If this relocation is hidden, skip it.
516 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
517 if (hidden) goto skip_print_rel;
519 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
520 // Stop when rel_cur's address is past the current instruction.
521 if (addr >= Index + Size) break;
522 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
523 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
525 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
526 << "\t" << val << "\n";
536 static void PrintRelocations(const ObjectFile *o) {
538 for (section_iterator si = o->begin_sections(), se = o->end_sections();
539 si != se; si.increment(ec)){
540 if (error(ec)) return;
541 if (si->begin_relocations() == si->end_relocations())
544 if (error(si->getName(secname))) continue;
545 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
546 for (relocation_iterator ri = si->begin_relocations(),
547 re = si->end_relocations();
548 ri != re; ri.increment(ec)) {
549 if (error(ec)) return;
553 SmallString<32> relocname;
554 SmallString<32> valuestr;
555 if (error(ri->getHidden(hidden))) continue;
556 if (hidden) continue;
557 if (error(ri->getTypeName(relocname))) continue;
558 if (error(ri->getOffset(address))) continue;
559 if (error(ri->getValueString(valuestr))) continue;
560 outs() << address << " " << relocname << " " << valuestr << "\n";
566 static void PrintSectionHeaders(const ObjectFile *o) {
567 outs() << "Sections:\n"
568 "Idx Name Size Address Type\n";
571 for (section_iterator si = o->begin_sections(), se = o->end_sections();
572 si != se; si.increment(ec)) {
573 if (error(ec)) return;
575 if (error(si->getName(Name))) return;
577 if (error(si->getAddress(Address))) return;
579 if (error(si->getSize(Size))) return;
580 bool Text, Data, BSS;
581 if (error(si->isText(Text))) return;
582 if (error(si->isData(Data))) return;
583 if (error(si->isBSS(BSS))) return;
584 std::string Type = (std::string(Text ? "TEXT " : "") +
585 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
586 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
587 i, Name.str().c_str(), Size, Address, Type.c_str());
592 static void PrintSectionContents(const ObjectFile *o) {
594 for (section_iterator si = o->begin_sections(),
595 se = o->end_sections();
596 si != se; si.increment(ec)) {
597 if (error(ec)) return;
602 if (error(si->getName(Name))) continue;
603 if (error(si->getContents(Contents))) continue;
604 if (error(si->getAddress(BaseAddr))) continue;
605 if (error(si->isBSS(BSS))) continue;
607 outs() << "Contents of section " << Name << ":\n";
609 outs() << format("<skipping contents of bss section at [%04" PRIx64
610 ", %04" PRIx64 ")>\n", BaseAddr,
611 BaseAddr + Contents.size());
615 // Dump out the content as hex and printable ascii characters.
616 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
617 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
619 for (std::size_t i = 0; i < 16; ++i) {
620 if (i != 0 && i % 4 == 0)
623 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
624 << hexdigit(Contents[addr + i] & 0xF, true);
630 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
631 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
632 outs() << Contents[addr + i];
641 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
642 const coff_file_header *header;
643 if (error(coff->getHeader(header))) return;
645 const coff_symbol *symbol = 0;
646 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
648 // Figure out which type of aux this is.
649 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
650 && symbol->Value == 0) { // Section definition.
651 const coff_aux_section_definition *asd;
652 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
655 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
656 , unsigned(asd->Length)
657 , unsigned(asd->NumberOfRelocations)
658 , unsigned(asd->NumberOfLinenumbers)
659 , unsigned(asd->CheckSum))
660 << format("assoc %d comdat %d\n"
661 , unsigned(asd->Number)
662 , unsigned(asd->Selection));
664 outs() << "AUX Unknown\n";
667 if (error(coff->getSymbol(i, symbol))) return;
668 if (error(coff->getSymbolName(symbol, name))) return;
669 outs() << "[" << format("%2d", i) << "]"
670 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
671 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
672 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
673 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
674 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
675 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
677 aux_count = symbol->NumberOfAuxSymbols;
682 static void PrintSymbolTable(const ObjectFile *o) {
683 outs() << "SYMBOL TABLE:\n";
685 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
686 PrintCOFFSymbolTable(coff);
689 for (symbol_iterator si = o->begin_symbols(),
690 se = o->end_symbols(); si != se; si.increment(ec)) {
691 if (error(ec)) return;
694 SymbolRef::Type Type;
697 section_iterator Section = o->end_sections();
698 if (error(si->getName(Name))) continue;
699 if (error(si->getAddress(Address))) continue;
700 if (error(si->getFlags(Flags))) continue;
701 if (error(si->getType(Type))) continue;
702 if (error(si->getSize(Size))) continue;
703 if (error(si->getSection(Section))) continue;
705 bool Global = Flags & SymbolRef::SF_Global;
706 bool Weak = Flags & SymbolRef::SF_Weak;
707 bool Absolute = Flags & SymbolRef::SF_Absolute;
709 if (Address == UnknownAddressOrSize)
711 if (Size == UnknownAddressOrSize)
714 if (Type != SymbolRef::ST_Unknown)
715 GlobLoc = Global ? 'g' : 'l';
716 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
719 if (Type == SymbolRef::ST_File)
721 else if (Type == SymbolRef::ST_Function)
724 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
727 outs() << format(Fmt, Address) << " "
728 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
729 << (Weak ? 'w' : ' ') // Weak?
730 << ' ' // Constructor. Not supported yet.
731 << ' ' // Warning. Not supported yet.
732 << ' ' // Indirect reference to another symbol.
733 << Debug // Debugging (d) or dynamic (D) symbol.
734 << FileFunc // Name of function (F), file (f) or object (O).
738 else if (Section == o->end_sections())
741 if (const MachOObjectFile *MachO =
742 dyn_cast<const MachOObjectFile>(o)) {
743 DataRefImpl DR = Section->getRawDataRefImpl();
744 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
745 outs() << SegmentName << ",";
747 StringRef SectionName;
748 if (error(Section->getName(SectionName)))
750 outs() << SectionName;
753 << format("%08" PRIx64 " ", Size)
760 static void PrintUnwindInfo(const ObjectFile *o) {
761 outs() << "Unwind info:\n\n";
763 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
764 printCOFFUnwindInfo(coff);
766 // TODO: Extract DWARF dump tool to objdump.
767 errs() << "This operation is only currently supported "
768 "for COFF object files.\n";
773 static void DumpObject(const ObjectFile *o) {
775 outs() << o->getFileName()
776 << ":\tfile format " << o->getFileFormatName() << "\n\n";
779 DisassembleObject(o, Relocations);
780 if (Relocations && !Disassemble)
783 PrintSectionHeaders(o);
785 PrintSectionContents(o);
790 if (PrivateHeaders && o->isELF())
791 printELFFileHeader(o);
794 /// @brief Dump each object file in \a a;
795 static void DumpArchive(const Archive *a) {
796 for (Archive::child_iterator i = a->begin_children(),
797 e = a->end_children(); i != e; ++i) {
798 OwningPtr<Binary> child;
799 if (error_code ec = i->getAsBinary(child)) {
800 // Ignore non-object files.
801 if (ec != object_error::invalid_file_type)
802 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
806 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
809 errs() << ToolName << ": '" << a->getFileName() << "': "
810 << "Unrecognized file type.\n";
814 /// @brief Open file and figure out how to dump it.
815 static void DumpInput(StringRef file) {
816 // If file isn't stdin, check that it exists.
817 if (file != "-" && !sys::fs::exists(file)) {
818 errs() << ToolName << ": '" << file << "': " << "No such file\n";
822 if (MachOOpt && Disassemble) {
823 DisassembleInputMachO(file);
827 // Attempt to open the binary.
828 OwningPtr<Binary> binary;
829 if (error_code ec = createBinary(file, binary)) {
830 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
834 if (Archive *a = dyn_cast<Archive>(binary.get()))
836 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
839 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
842 int main(int argc, char **argv) {
843 // Print a stack trace if we signal out.
844 sys::PrintStackTraceOnErrorSignal();
845 PrettyStackTraceProgram X(argc, argv);
846 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
848 // Initialize targets and assembly printers/parsers.
849 llvm::InitializeAllTargetInfos();
850 llvm::InitializeAllTargetMCs();
851 llvm::InitializeAllAsmParsers();
852 llvm::InitializeAllDisassemblers();
854 // Register the target printer for --version.
855 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
857 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
858 TripleName = Triple::normalize(TripleName);
862 // Defaults to a.out if no filenames specified.
863 if (InputFilenames.size() == 0)
864 InputFilenames.push_back("a.out");
872 && !PrivateHeaders) {
873 cl::PrintHelpMessage();
877 std::for_each(InputFilenames.begin(), InputFilenames.end(),