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/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"
65 using namespace object;
67 static cl::list<std::string>
68 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
71 Disassemble("disassemble",
72 cl::desc("Display assembler mnemonics for the machine instructions"));
74 Disassembled("d", cl::desc("Alias for --disassemble"),
75 cl::aliasopt(Disassemble));
78 Relocations("r", cl::desc("Display the relocation entries in the file"));
81 SectionContents("s", cl::desc("Display the content of each section"));
84 SymbolTable("t", cl::desc("Display the symbol table"));
87 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
89 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
92 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
93 "see -version for available targets"));
96 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
97 "see -version for available targets"));
100 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
101 "for each section."));
103 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
104 cl::aliasopt(SectionHeaders));
106 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
107 cl::aliasopt(SectionHeaders));
109 static cl::list<std::string>
112 cl::desc("Target specific attributes"),
113 cl::value_desc("a1,+a2,-a3,..."));
116 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
117 "do not print the instruction bytes."));
120 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
123 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
124 cl::aliasopt(UnwindInfo));
127 PrivateHeaders("private-headers",
128 cl::desc("Display format specific file headers"));
131 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
132 cl::aliasopt(PrivateHeaders));
135 Symbolize("symbolize", cl::desc("When disassembling instructions, "
136 "try to symbolize operands."));
139 CFG("cfg", cl::desc("Create a CFG for every function found in the object"
140 " and write it to a graphviz file"));
142 static StringRef ToolName;
144 bool llvm::error(error_code ec) {
145 if (!ec) return false;
147 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
152 static const Target *getTarget(const ObjectFile *Obj = NULL) {
153 // Figure out the target triple.
154 llvm::Triple TheTriple("unknown-unknown-unknown");
155 if (TripleName.empty()) {
157 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
158 // TheTriple defaults to ELF, and COFF doesn't have an environment:
159 // the best we can do here is indicate that it is mach-o.
161 TheTriple.setEnvironment(Triple::MachO);
164 TheTriple.setTriple(Triple::normalize(TripleName));
166 // Get the target specific parser.
168 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
171 errs() << ToolName << ": " << Error;
175 // Update the triple name and return the found target.
176 TripleName = TheTriple.getTriple();
180 // Write a graphviz file for the CFG inside an MCFunction.
181 static void emitDOTFile(const char *FileName, const MCFunction &f,
183 // Start a new dot file.
185 raw_fd_ostream Out(FileName, Error);
186 if (!Error.empty()) {
187 errs() << "llvm-objdump: warning: " << Error << '\n';
191 Out << "digraph \"" << f.getName() << "\" {\n";
192 Out << "graph [ rankdir = \"LR\" ];\n";
193 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
194 // Only print blocks that have predecessors.
195 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
197 if (!hasPreds && i != f.begin())
200 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
201 // Print instructions.
202 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
204 if (ii != 0) // Not the first line, start a new row.
206 if (ii + 1 == ie) // Last line, add an end id.
209 // Escape special chars and print the instruction in mnemonic form.
211 raw_string_ostream OS(Str);
212 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
213 Out << DOT::EscapeString(OS.str());
215 Out << "\" shape=\"record\" ];\n";
218 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
219 se = (*i)->succ_end(); si != se; ++si)
220 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
221 << (*si)->getInsts()->getBeginAddr() << ":a\n";
226 void llvm::DumpBytes(StringRef bytes) {
227 static const char hex_rep[] = "0123456789abcdef";
228 // FIXME: The real way to do this is to figure out the longest instruction
229 // and align to that size before printing. I'll fix this when I get
230 // around to outputting relocations.
231 // 15 is the longest x86 instruction
232 // 3 is for the hex rep of a byte + a space.
233 // 1 is for the null terminator.
234 enum { OutputSize = (15 * 3) + 1 };
235 char output[OutputSize];
237 assert(bytes.size() <= 15
238 && "DumpBytes only supports instructions of up to 15 bytes");
239 memset(output, ' ', sizeof(output));
241 for (StringRef::iterator i = bytes.begin(),
242 e = bytes.end(); i != e; ++i) {
243 output[index] = hex_rep[(*i & 0xF0) >> 4];
244 output[index + 1] = hex_rep[*i & 0xF];
248 output[sizeof(output) - 1] = 0;
252 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
253 uint64_t a_addr, b_addr;
254 if (error(a.getOffset(a_addr))) return false;
255 if (error(b.getOffset(b_addr))) return false;
256 return a_addr < b_addr;
259 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
260 const Target *TheTarget = getTarget(Obj);
261 // getTarget() will have already issued a diagnostic if necessary, so
262 // just bail here if it failed.
266 // Package up features to be passed to target/subtarget
267 std::string FeaturesStr;
269 SubtargetFeatures Features;
270 for (unsigned i = 0; i != MAttrs.size(); ++i)
271 Features.AddFeature(MAttrs[i]);
272 FeaturesStr = Features.getString();
275 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
277 errs() << "error: no register info for target " << TripleName << "\n";
281 // Set up disassembler.
282 OwningPtr<const MCAsmInfo> AsmInfo(
283 TheTarget->createMCAsmInfo(*MRI, TripleName));
285 errs() << "error: no assembly info for target " << TripleName << "\n";
289 OwningPtr<const MCSubtargetInfo> STI(
290 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
292 errs() << "error: no subtarget info for target " << TripleName << "\n";
296 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
298 errs() << "error: no instruction info for target " << TripleName << "\n";
302 OwningPtr<MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
304 errs() << "error: no disassembler for target " << TripleName << "\n";
308 OwningPtr<const MCObjectFileInfo> MOFI;
309 OwningPtr<MCContext> Ctx;
312 MOFI.reset(new MCObjectFileInfo);
313 Ctx.reset(new MCContext(*AsmInfo.get(), *MRI.get(), MOFI.get()));
314 OwningPtr<MCRelocationInfo> RelInfo(
315 TheTarget->createMCRelocationInfo(TripleName, *Ctx.get()));
317 OwningPtr<MCSymbolizer> Symzer(
318 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, Obj));
320 DisAsm->setSymbolizer(Symzer);
324 OwningPtr<const MCInstrAnalysis>
325 MIA(TheTarget->createMCInstrAnalysis(MII.get()));
327 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
328 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
329 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
331 errs() << "error: no instruction printer for target " << TripleName
337 OwningPtr<MCObjectDisassembler> OD(
338 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
339 OwningPtr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
340 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
341 AE = Mod->atom_end();
343 outs() << "Atom " << (*AI)->getName() << ": \n";
344 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
345 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
348 IP->printInst(&II->Inst, outs(), "");
353 for (MCModule::const_func_iterator FI = Mod->func_begin(),
354 FE = Mod->func_end();
356 static int filenum = 0;
357 emitDOTFile((Twine((*FI)->getName()) + "_" +
358 utostr(filenum++) + ".dot").str().c_str(),
365 for (section_iterator i = Obj->begin_sections(),
366 e = Obj->end_sections();
367 i != e; i.increment(ec)) {
368 if (error(ec)) break;
370 if (error(i->isText(text))) break;
373 uint64_t SectionAddr;
374 if (error(i->getAddress(SectionAddr))) break;
376 // Make a list of all the symbols in this section.
377 std::vector<std::pair<uint64_t, StringRef> > Symbols;
378 for (symbol_iterator si = Obj->begin_symbols(),
379 se = Obj->end_symbols();
380 si != se; si.increment(ec)) {
382 if (!error(i->containsSymbol(*si, contains)) && contains) {
384 if (error(si->getAddress(Address))) break;
385 if (Address == UnknownAddressOrSize) continue;
386 Address -= SectionAddr;
389 if (error(si->getName(Name))) break;
390 Symbols.push_back(std::make_pair(Address, Name));
394 // Sort the symbols by address, just in case they didn't come in that way.
395 array_pod_sort(Symbols.begin(), Symbols.end());
397 // Make a list of all the relocations for this section.
398 std::vector<RelocationRef> Rels;
400 for (relocation_iterator ri = i->begin_relocations(),
401 re = i->end_relocations();
402 ri != re; ri.increment(ec)) {
403 if (error(ec)) break;
408 // Sort relocations by address.
409 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
411 StringRef SegmentName = "";
412 if (const MachOObjectFile *MachO =
413 dyn_cast<const MachOObjectFile>(Obj)) {
414 DataRefImpl DR = i->getRawDataRefImpl();
415 SegmentName = MachO->getSectionFinalSegmentName(DR);
418 if (error(i->getName(name))) break;
419 outs() << "Disassembly of section ";
420 if (!SegmentName.empty())
421 outs() << SegmentName << ",";
422 outs() << name << ':';
424 // If the section has no symbols just insert a dummy one and disassemble
425 // the whole section.
427 Symbols.push_back(std::make_pair(0, name));
430 SmallString<40> Comments;
431 raw_svector_ostream CommentStream(Comments);
434 if (error(i->getContents(Bytes))) break;
435 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
439 if (error(i->getSize(SectSize))) break;
441 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
442 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
443 // Disassemble symbol by symbol.
444 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
445 uint64_t Start = Symbols[si].first;
447 // The end is either the size of the section or the beginning of the next
451 // Make sure this symbol takes up space.
452 else if (Symbols[si + 1].first != Start)
453 End = Symbols[si + 1].first - 1;
455 // This symbol has the same address as the next symbol. Skip it.
458 outs() << '\n' << Symbols[si].second << ":\n";
461 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
463 raw_ostream &DebugOut = nulls();
466 for (Index = Start; Index < End; Index += Size) {
469 if (DisAsm->getInstruction(Inst, Size, memoryObject,
471 DebugOut, CommentStream)) {
472 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
473 if (!NoShowRawInsn) {
475 DumpBytes(StringRef(Bytes.data() + Index, Size));
477 IP->printInst(&Inst, outs(), "");
478 outs() << CommentStream.str();
482 errs() << ToolName << ": warning: invalid instruction encoding\n";
484 Size = 1; // skip illegible bytes
487 // Print relocation for instruction.
488 while (rel_cur != rel_end) {
491 SmallString<16> name;
494 // If this relocation is hidden, skip it.
495 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
496 if (hidden) goto skip_print_rel;
498 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
499 // Stop when rel_cur's address is past the current instruction.
500 if (addr >= Index + Size) break;
501 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
502 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
504 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
505 << "\t" << val << "\n";
515 static void PrintRelocations(const ObjectFile *o) {
517 for (section_iterator si = o->begin_sections(), se = o->end_sections();
518 si != se; si.increment(ec)){
519 if (error(ec)) return;
520 if (si->begin_relocations() == si->end_relocations())
523 if (error(si->getName(secname))) continue;
524 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
525 for (relocation_iterator ri = si->begin_relocations(),
526 re = si->end_relocations();
527 ri != re; ri.increment(ec)) {
528 if (error(ec)) return;
532 SmallString<32> relocname;
533 SmallString<32> valuestr;
534 if (error(ri->getHidden(hidden))) continue;
535 if (hidden) continue;
536 if (error(ri->getTypeName(relocname))) continue;
537 if (error(ri->getOffset(address))) continue;
538 if (error(ri->getValueString(valuestr))) continue;
539 outs() << address << " " << relocname << " " << valuestr << "\n";
545 static void PrintSectionHeaders(const ObjectFile *o) {
546 outs() << "Sections:\n"
547 "Idx Name Size Address Type\n";
550 for (section_iterator si = o->begin_sections(), se = o->end_sections();
551 si != se; si.increment(ec)) {
552 if (error(ec)) return;
554 if (error(si->getName(Name))) return;
556 if (error(si->getAddress(Address))) return;
558 if (error(si->getSize(Size))) return;
559 bool Text, Data, BSS;
560 if (error(si->isText(Text))) return;
561 if (error(si->isData(Data))) return;
562 if (error(si->isBSS(BSS))) return;
563 std::string Type = (std::string(Text ? "TEXT " : "") +
564 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
565 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
566 i, Name.str().c_str(), Size, Address, Type.c_str());
571 static void PrintSectionContents(const ObjectFile *o) {
573 for (section_iterator si = o->begin_sections(),
574 se = o->end_sections();
575 si != se; si.increment(ec)) {
576 if (error(ec)) return;
581 if (error(si->getName(Name))) continue;
582 if (error(si->getContents(Contents))) continue;
583 if (error(si->getAddress(BaseAddr))) continue;
584 if (error(si->isBSS(BSS))) continue;
586 outs() << "Contents of section " << Name << ":\n";
588 outs() << format("<skipping contents of bss section at [%04" PRIx64
589 ", %04" PRIx64 ")>\n", BaseAddr,
590 BaseAddr + Contents.size());
594 // Dump out the content as hex and printable ascii characters.
595 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
596 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
598 for (std::size_t i = 0; i < 16; ++i) {
599 if (i != 0 && i % 4 == 0)
602 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
603 << hexdigit(Contents[addr + i] & 0xF, true);
609 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
610 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
611 outs() << Contents[addr + i];
620 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
621 const coff_file_header *header;
622 if (error(coff->getHeader(header))) return;
624 const coff_symbol *symbol = 0;
625 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
627 // Figure out which type of aux this is.
628 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
629 && symbol->Value == 0) { // Section definition.
630 const coff_aux_section_definition *asd;
631 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
634 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
635 , unsigned(asd->Length)
636 , unsigned(asd->NumberOfRelocations)
637 , unsigned(asd->NumberOfLinenumbers)
638 , unsigned(asd->CheckSum))
639 << format("assoc %d comdat %d\n"
640 , unsigned(asd->Number)
641 , unsigned(asd->Selection));
643 outs() << "AUX Unknown\n";
646 if (error(coff->getSymbol(i, symbol))) return;
647 if (error(coff->getSymbolName(symbol, name))) return;
648 outs() << "[" << format("%2d", i) << "]"
649 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
650 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
651 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
652 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
653 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
654 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
656 aux_count = symbol->NumberOfAuxSymbols;
661 static void PrintSymbolTable(const ObjectFile *o) {
662 outs() << "SYMBOL TABLE:\n";
664 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
665 PrintCOFFSymbolTable(coff);
668 for (symbol_iterator si = o->begin_symbols(),
669 se = o->end_symbols(); si != se; si.increment(ec)) {
670 if (error(ec)) return;
673 SymbolRef::Type Type;
676 section_iterator Section = o->end_sections();
677 if (error(si->getName(Name))) continue;
678 if (error(si->getAddress(Address))) continue;
679 if (error(si->getFlags(Flags))) continue;
680 if (error(si->getType(Type))) continue;
681 if (error(si->getSize(Size))) continue;
682 if (error(si->getSection(Section))) continue;
684 bool Global = Flags & SymbolRef::SF_Global;
685 bool Weak = Flags & SymbolRef::SF_Weak;
686 bool Absolute = Flags & SymbolRef::SF_Absolute;
688 if (Address == UnknownAddressOrSize)
690 if (Size == UnknownAddressOrSize)
693 if (Type != SymbolRef::ST_Unknown)
694 GlobLoc = Global ? 'g' : 'l';
695 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
698 if (Type == SymbolRef::ST_File)
700 else if (Type == SymbolRef::ST_Function)
703 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
706 outs() << format(Fmt, Address) << " "
707 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
708 << (Weak ? 'w' : ' ') // Weak?
709 << ' ' // Constructor. Not supported yet.
710 << ' ' // Warning. Not supported yet.
711 << ' ' // Indirect reference to another symbol.
712 << Debug // Debugging (d) or dynamic (D) symbol.
713 << FileFunc // Name of function (F), file (f) or object (O).
717 else if (Section == o->end_sections())
720 if (const MachOObjectFile *MachO =
721 dyn_cast<const MachOObjectFile>(o)) {
722 DataRefImpl DR = Section->getRawDataRefImpl();
723 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
724 outs() << SegmentName << ",";
726 StringRef SectionName;
727 if (error(Section->getName(SectionName)))
729 outs() << SectionName;
732 << format("%08" PRIx64 " ", Size)
739 static void PrintUnwindInfo(const ObjectFile *o) {
740 outs() << "Unwind info:\n\n";
742 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
743 printCOFFUnwindInfo(coff);
745 // TODO: Extract DWARF dump tool to objdump.
746 errs() << "This operation is only currently supported "
747 "for COFF object files.\n";
752 static void DumpObject(const ObjectFile *o) {
754 outs() << o->getFileName()
755 << ":\tfile format " << o->getFileFormatName() << "\n\n";
758 DisassembleObject(o, Relocations);
759 if (Relocations && !Disassemble)
762 PrintSectionHeaders(o);
764 PrintSectionContents(o);
769 if (PrivateHeaders && o->isELF())
770 printELFFileHeader(o);
773 /// @brief Dump each object file in \a a;
774 static void DumpArchive(const Archive *a) {
775 for (Archive::child_iterator i = a->begin_children(),
776 e = a->end_children(); i != e; ++i) {
777 OwningPtr<Binary> child;
778 if (error_code ec = i->getAsBinary(child)) {
779 // Ignore non-object files.
780 if (ec != object_error::invalid_file_type)
781 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
785 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
788 errs() << ToolName << ": '" << a->getFileName() << "': "
789 << "Unrecognized file type.\n";
793 /// @brief Open file and figure out how to dump it.
794 static void DumpInput(StringRef file) {
795 // If file isn't stdin, check that it exists.
796 if (file != "-" && !sys::fs::exists(file)) {
797 errs() << ToolName << ": '" << file << "': " << "No such file\n";
801 if (MachOOpt && Disassemble) {
802 DisassembleInputMachO(file);
806 // Attempt to open the binary.
807 OwningPtr<Binary> binary;
808 if (error_code ec = createBinary(file, binary)) {
809 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
813 if (Archive *a = dyn_cast<Archive>(binary.get()))
815 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
818 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
821 int main(int argc, char **argv) {
822 // Print a stack trace if we signal out.
823 sys::PrintStackTraceOnErrorSignal();
824 PrettyStackTraceProgram X(argc, argv);
825 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
827 // Initialize targets and assembly printers/parsers.
828 llvm::InitializeAllTargetInfos();
829 llvm::InitializeAllTargetMCs();
830 llvm::InitializeAllAsmParsers();
831 llvm::InitializeAllDisassemblers();
833 // Register the target printer for --version.
834 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
836 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
837 TripleName = Triple::normalize(TripleName);
841 // Defaults to a.out if no filenames specified.
842 if (InputFilenames.size() == 0)
843 InputFilenames.push_back("a.out");
851 && !PrivateHeaders) {
852 cl::PrintHelpMessage();
856 std::for_each(InputFilenames.begin(), InputFilenames.end(),