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) {
156 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
161 static const Target *getTarget(const ObjectFile *Obj = NULL) {
162 // Figure out the target triple.
163 llvm::Triple TheTriple("unknown-unknown-unknown");
164 if (TripleName.empty()) {
166 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
167 // TheTriple defaults to ELF, and COFF doesn't have an environment:
168 // the best we can do here is indicate that it is mach-o.
170 TheTriple.setEnvironment(Triple::MachO);
173 TheTriple.setTriple(Triple::normalize(TripleName));
175 // Get the target specific parser.
177 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
180 errs() << ToolName << ": " << Error;
184 // Update the triple name and return the found target.
185 TripleName = TheTriple.getTriple();
189 // Write a graphviz file for the CFG inside an MCFunction.
190 // FIXME: Use GraphWriter
191 static void emitDOTFile(const char *FileName, const MCFunction &f,
193 // Start a new dot file.
195 raw_fd_ostream Out(FileName, Error);
196 if (!Error.empty()) {
197 errs() << "llvm-objdump: warning: " << Error << '\n';
201 Out << "digraph \"" << f.getName() << "\" {\n";
202 Out << "graph [ rankdir = \"LR\" ];\n";
203 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
204 // Only print blocks that have predecessors.
205 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
207 if (!hasPreds && i != f.begin())
210 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
211 // Print instructions.
212 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
214 if (ii != 0) // Not the first line, start a new row.
216 if (ii + 1 == ie) // Last line, add an end id.
219 // Escape special chars and print the instruction in mnemonic form.
221 raw_string_ostream OS(Str);
222 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
223 Out << DOT::EscapeString(OS.str());
225 Out << "\" shape=\"record\" ];\n";
228 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
229 se = (*i)->succ_end(); si != se; ++si)
230 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
231 << (*si)->getInsts()->getBeginAddr() << ":a\n";
236 void llvm::DumpBytes(StringRef bytes) {
237 static const char hex_rep[] = "0123456789abcdef";
238 // FIXME: The real way to do this is to figure out the longest instruction
239 // and align to that size before printing. I'll fix this when I get
240 // around to outputting relocations.
241 // 15 is the longest x86 instruction
242 // 3 is for the hex rep of a byte + a space.
243 // 1 is for the null terminator.
244 enum { OutputSize = (15 * 3) + 1 };
245 char output[OutputSize];
247 assert(bytes.size() <= 15
248 && "DumpBytes only supports instructions of up to 15 bytes");
249 memset(output, ' ', sizeof(output));
251 for (StringRef::iterator i = bytes.begin(),
252 e = bytes.end(); i != e; ++i) {
253 output[index] = hex_rep[(*i & 0xF0) >> 4];
254 output[index + 1] = hex_rep[*i & 0xF];
258 output[sizeof(output) - 1] = 0;
262 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
263 uint64_t a_addr, b_addr;
264 if (error(a.getOffset(a_addr))) return false;
265 if (error(b.getOffset(b_addr))) return false;
266 return a_addr < b_addr;
269 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
270 const Target *TheTarget = getTarget(Obj);
271 // getTarget() will have already issued a diagnostic if necessary, so
272 // just bail here if it failed.
276 // Package up features to be passed to target/subtarget
277 std::string FeaturesStr;
279 SubtargetFeatures Features;
280 for (unsigned i = 0; i != MAttrs.size(); ++i)
281 Features.AddFeature(MAttrs[i]);
282 FeaturesStr = Features.getString();
285 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
287 errs() << "error: no register info for target " << TripleName << "\n";
291 // Set up disassembler.
292 OwningPtr<const MCAsmInfo> AsmInfo(
293 TheTarget->createMCAsmInfo(*MRI, TripleName));
295 errs() << "error: no assembly info for target " << TripleName << "\n";
299 OwningPtr<const MCSubtargetInfo> STI(
300 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
302 errs() << "error: no subtarget info for target " << TripleName << "\n";
306 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
308 errs() << "error: no instruction info for target " << TripleName << "\n";
312 OwningPtr<MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
314 errs() << "error: no disassembler for target " << TripleName << "\n";
318 OwningPtr<const MCObjectFileInfo> MOFI;
319 OwningPtr<MCContext> Ctx;
322 MOFI.reset(new MCObjectFileInfo);
323 Ctx.reset(new MCContext(AsmInfo.get(), MRI.get(), MOFI.get()));
324 OwningPtr<MCRelocationInfo> RelInfo(
325 TheTarget->createMCRelocationInfo(TripleName, *Ctx.get()));
327 OwningPtr<MCSymbolizer> Symzer(
328 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, Obj));
330 DisAsm->setSymbolizer(Symzer);
334 OwningPtr<const MCInstrAnalysis>
335 MIA(TheTarget->createMCInstrAnalysis(MII.get()));
337 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
338 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
339 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
341 errs() << "error: no instruction printer for target " << TripleName
346 if (CFG || !YAMLCFG.empty()) {
347 OwningPtr<MCObjectDisassembler> OD(
348 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
349 OwningPtr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
350 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
351 AE = Mod->atom_end();
353 outs() << "Atom " << (*AI)->getName() << ": \n";
354 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
355 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
358 IP->printInst(&II->Inst, outs(), "");
364 for (MCModule::const_func_iterator FI = Mod->func_begin(),
365 FE = Mod->func_end();
367 static int filenum = 0;
368 emitDOTFile((Twine((*FI)->getName()) + "_" +
369 utostr(filenum) + ".dot").str().c_str(),
374 if (!YAMLCFG.empty()) {
376 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error);
377 if (!Error.empty()) {
378 errs() << ToolName << ": warning: " << Error << '\n';
381 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
385 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
386 // in RelocSecs contain the relocations for section S.
388 std::map<SectionRef, SmallVector<SectionRef, 1> > SectionRelocMap;
389 for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
390 I != E; I.increment(EC)) {
393 section_iterator Sec2 = I->getRelocatedSection();
394 if (Sec2 != Obj->end_sections())
395 SectionRelocMap[*Sec2].push_back(*I);
398 for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
399 I != E; I.increment(EC)) {
403 if (error(I->isText(Text)))
408 uint64_t SectionAddr;
409 if (error(I->getAddress(SectionAddr)))
412 // Make a list of all the symbols in this section.
413 std::vector<std::pair<uint64_t, StringRef> > Symbols;
414 for (symbol_iterator SI = Obj->begin_symbols(), SE = Obj->end_symbols();
415 SI != SE; SI.increment(EC)) {
417 if (!error(I->containsSymbol(*SI, contains)) && contains) {
419 if (error(SI->getAddress(Address)))
421 if (Address == UnknownAddressOrSize)
423 Address -= SectionAddr;
426 if (error(SI->getName(Name)))
428 Symbols.push_back(std::make_pair(Address, Name));
432 // Sort the symbols by address, just in case they didn't come in that way.
433 array_pod_sort(Symbols.begin(), Symbols.end());
435 // Make a list of all the relocations for this section.
436 std::vector<RelocationRef> Rels;
438 SmallVectorImpl<SectionRef> *RelocSecs = &SectionRelocMap[*I];
439 for (SmallVectorImpl<SectionRef>::iterator RelocSec = RelocSecs->begin(),
440 E = RelocSecs->end();
441 RelocSec != E; ++RelocSec) {
442 for (relocation_iterator RI = RelocSec->begin_relocations(),
443 RE = RelocSec->end_relocations();
444 RI != RE; RI.increment(EC)) {
452 // Sort relocations by address.
453 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
455 StringRef SegmentName = "";
456 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
457 DataRefImpl DR = I->getRawDataRefImpl();
458 SegmentName = MachO->getSectionFinalSegmentName(DR);
461 if (error(I->getName(name)))
463 outs() << "Disassembly of section ";
464 if (!SegmentName.empty())
465 outs() << SegmentName << ",";
466 outs() << name << ':';
468 // If the section has no symbols just insert a dummy one and disassemble
469 // the whole section.
471 Symbols.push_back(std::make_pair(0, name));
474 SmallString<40> Comments;
475 raw_svector_ostream CommentStream(Comments);
478 if (error(I->getContents(Bytes)))
480 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
484 if (error(I->getSize(SectSize)))
487 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
488 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
489 // Disassemble symbol by symbol.
490 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
491 uint64_t Start = Symbols[si].first;
493 // The end is either the size of the section or the beginning of the next
497 // Make sure this symbol takes up space.
498 else if (Symbols[si + 1].first != Start)
499 End = Symbols[si + 1].first - 1;
501 // This symbol has the same address as the next symbol. Skip it.
504 outs() << '\n' << Symbols[si].second << ":\n";
507 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
509 raw_ostream &DebugOut = nulls();
512 for (Index = Start; Index < End; Index += Size) {
515 if (DisAsm->getInstruction(Inst, Size, memoryObject,
517 DebugOut, CommentStream)) {
518 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
519 if (!NoShowRawInsn) {
521 DumpBytes(StringRef(Bytes.data() + Index, Size));
523 IP->printInst(&Inst, outs(), "");
524 outs() << CommentStream.str();
528 errs() << ToolName << ": warning: invalid instruction encoding\n";
530 Size = 1; // skip illegible bytes
533 // Print relocation for instruction.
534 while (rel_cur != rel_end) {
537 SmallString<16> name;
540 // If this relocation is hidden, skip it.
541 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
542 if (hidden) goto skip_print_rel;
544 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
545 // Stop when rel_cur's address is past the current instruction.
546 if (addr >= Index + Size) break;
547 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
548 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
550 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
551 << "\t" << val << "\n";
561 static void PrintRelocations(const ObjectFile *o) {
563 for (section_iterator si = o->begin_sections(), se = o->end_sections();
564 si != se; si.increment(EC)) {
567 if (si->begin_relocations() == si->end_relocations())
570 if (error(si->getName(secname))) continue;
571 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
572 for (relocation_iterator ri = si->begin_relocations(),
573 re = si->end_relocations();
574 ri != re; ri.increment(EC)) {
580 SmallString<32> relocname;
581 SmallString<32> valuestr;
582 if (error(ri->getHidden(hidden))) continue;
583 if (hidden) continue;
584 if (error(ri->getTypeName(relocname))) continue;
585 if (error(ri->getOffset(address))) continue;
586 if (error(ri->getValueString(valuestr))) continue;
587 outs() << address << " " << relocname << " " << valuestr << "\n";
593 static void PrintSectionHeaders(const ObjectFile *o) {
594 outs() << "Sections:\n"
595 "Idx Name Size Address Type\n";
598 for (section_iterator si = o->begin_sections(), se = o->end_sections();
599 si != se; si.increment(EC)) {
603 if (error(si->getName(Name)))
606 if (error(si->getAddress(Address))) return;
608 if (error(si->getSize(Size))) return;
609 bool Text, Data, BSS;
610 if (error(si->isText(Text))) return;
611 if (error(si->isData(Data))) return;
612 if (error(si->isBSS(BSS))) return;
613 std::string Type = (std::string(Text ? "TEXT " : "") +
614 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
615 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
616 i, Name.str().c_str(), Size, Address, Type.c_str());
621 static void PrintSectionContents(const ObjectFile *o) {
623 for (section_iterator si = o->begin_sections(), se = o->end_sections();
624 si != se; si.increment(EC)) {
631 if (error(si->getName(Name))) continue;
632 if (error(si->getContents(Contents))) continue;
633 if (error(si->getAddress(BaseAddr))) continue;
634 if (error(si->isBSS(BSS))) continue;
636 outs() << "Contents of section " << Name << ":\n";
638 outs() << format("<skipping contents of bss section at [%04" PRIx64
639 ", %04" PRIx64 ")>\n", BaseAddr,
640 BaseAddr + Contents.size());
644 // Dump out the content as hex and printable ascii characters.
645 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
646 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
648 for (std::size_t i = 0; i < 16; ++i) {
649 if (i != 0 && i % 4 == 0)
652 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
653 << hexdigit(Contents[addr + i] & 0xF, true);
659 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
660 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
661 outs() << Contents[addr + i];
670 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
671 const coff_file_header *header;
672 if (error(coff->getHeader(header))) return;
674 const coff_symbol *symbol = 0;
675 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
677 // Figure out which type of aux this is.
678 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
679 && symbol->Value == 0) { // Section definition.
680 const coff_aux_section_definition *asd;
681 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
684 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
685 , unsigned(asd->Length)
686 , unsigned(asd->NumberOfRelocations)
687 , unsigned(asd->NumberOfLinenumbers)
688 , unsigned(asd->CheckSum))
689 << format("assoc %d comdat %d\n"
690 , unsigned(asd->Number)
691 , unsigned(asd->Selection));
693 outs() << "AUX Unknown\n";
696 if (error(coff->getSymbol(i, symbol))) return;
697 if (error(coff->getSymbolName(symbol, name))) return;
698 outs() << "[" << format("%2d", i) << "]"
699 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
700 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
701 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
702 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
703 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
704 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
706 aux_count = symbol->NumberOfAuxSymbols;
711 static void PrintSymbolTable(const ObjectFile *o) {
712 outs() << "SYMBOL TABLE:\n";
714 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
715 PrintCOFFSymbolTable(coff);
718 for (symbol_iterator si = o->begin_symbols(), se = o->end_symbols();
719 si != se; si.increment(EC)) {
724 SymbolRef::Type Type;
727 section_iterator Section = o->end_sections();
728 if (error(si->getName(Name))) continue;
729 if (error(si->getAddress(Address))) continue;
730 if (error(si->getFlags(Flags))) continue;
731 if (error(si->getType(Type))) continue;
732 if (error(si->getSize(Size))) continue;
733 if (error(si->getSection(Section))) continue;
735 bool Global = Flags & SymbolRef::SF_Global;
736 bool Weak = Flags & SymbolRef::SF_Weak;
737 bool Absolute = Flags & SymbolRef::SF_Absolute;
739 if (Address == UnknownAddressOrSize)
741 if (Size == UnknownAddressOrSize)
744 if (Type != SymbolRef::ST_Unknown)
745 GlobLoc = Global ? 'g' : 'l';
746 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
749 if (Type == SymbolRef::ST_File)
751 else if (Type == SymbolRef::ST_Function)
754 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
757 outs() << format(Fmt, Address) << " "
758 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
759 << (Weak ? 'w' : ' ') // Weak?
760 << ' ' // Constructor. Not supported yet.
761 << ' ' // Warning. Not supported yet.
762 << ' ' // Indirect reference to another symbol.
763 << Debug // Debugging (d) or dynamic (D) symbol.
764 << FileFunc // Name of function (F), file (f) or object (O).
768 else if (Section == o->end_sections())
771 if (const MachOObjectFile *MachO =
772 dyn_cast<const MachOObjectFile>(o)) {
773 DataRefImpl DR = Section->getRawDataRefImpl();
774 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
775 outs() << SegmentName << ",";
777 StringRef SectionName;
778 if (error(Section->getName(SectionName)))
780 outs() << SectionName;
783 << format("%08" PRIx64 " ", Size)
790 static void PrintUnwindInfo(const ObjectFile *o) {
791 outs() << "Unwind info:\n\n";
793 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
794 printCOFFUnwindInfo(coff);
796 // TODO: Extract DWARF dump tool to objdump.
797 errs() << "This operation is only currently supported "
798 "for COFF object files.\n";
803 static void printPrivateFileHeader(const ObjectFile *o) {
805 printELFFileHeader(o);
806 } else if (o->isCOFF()) {
807 printCOFFFileHeader(o);
811 static void DumpObject(const ObjectFile *o) {
813 outs() << o->getFileName()
814 << ":\tfile format " << o->getFileFormatName() << "\n\n";
817 DisassembleObject(o, Relocations);
818 if (Relocations && !Disassemble)
821 PrintSectionHeaders(o);
823 PrintSectionContents(o);
829 printPrivateFileHeader(o);
832 /// @brief Dump each object file in \a a;
833 static void DumpArchive(const Archive *a) {
834 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
836 OwningPtr<Binary> child;
837 if (error_code EC = i->getAsBinary(child)) {
838 // Ignore non-object files.
839 if (EC != object_error::invalid_file_type)
840 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
844 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
847 errs() << ToolName << ": '" << a->getFileName() << "': "
848 << "Unrecognized file type.\n";
852 /// @brief Open file and figure out how to dump it.
853 static void DumpInput(StringRef file) {
854 // If file isn't stdin, check that it exists.
855 if (file != "-" && !sys::fs::exists(file)) {
856 errs() << ToolName << ": '" << file << "': " << "No such file\n";
860 if (MachOOpt && Disassemble) {
861 DisassembleInputMachO(file);
865 // Attempt to open the binary.
866 ErrorOr<Binary *> BinaryOrErr = createBinary(file);
867 if (error_code EC = BinaryOrErr.getError()) {
868 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
871 OwningPtr<Binary> binary(BinaryOrErr.get());
873 if (Archive *a = dyn_cast<Archive>(binary.get()))
875 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
878 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
881 int main(int argc, char **argv) {
882 // Print a stack trace if we signal out.
883 sys::PrintStackTraceOnErrorSignal();
884 PrettyStackTraceProgram X(argc, argv);
885 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
887 // Initialize targets and assembly printers/parsers.
888 llvm::InitializeAllTargetInfos();
889 llvm::InitializeAllTargetMCs();
890 llvm::InitializeAllAsmParsers();
891 llvm::InitializeAllDisassemblers();
893 // Register the target printer for --version.
894 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
896 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
897 TripleName = Triple::normalize(TripleName);
901 // Defaults to a.out if no filenames specified.
902 if (InputFilenames.size() == 0)
903 InputFilenames.push_back("a.out");
911 && !PrivateHeaders) {
912 cl::PrintHelpMessage();
916 std::for_each(InputFilenames.begin(), InputFilenames.end(),