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/MCAnalysis/MCAtom.h"
24 #include "llvm/MC/MCAnalysis/MCFunction.h"
25 #include "llvm/MC/MCAnalysis/MCModule.h"
26 #include "llvm/MC/MCAnalysis/MCModuleYAML.h"
27 #include "llvm/MC/MCAnalysis/MCObjectSymbolizer.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCDisassembler.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCInstrAnalysis.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectDisassembler.h"
36 #include "llvm/MC/MCObjectFileInfo.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MC/MCRelocationInfo.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/COFF.h"
42 #include "llvm/Object/MachO.h"
43 #include "llvm/Object/ObjectFile.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Format.h"
49 #include "llvm/Support/GraphWriter.h"
50 #include "llvm/Support/Host.h"
51 #include "llvm/Support/ManagedStatic.h"
52 #include "llvm/Support/MemoryBuffer.h"
53 #include "llvm/Support/MemoryObject.h"
54 #include "llvm/Support/PrettyStackTrace.h"
55 #include "llvm/Support/Signals.h"
56 #include "llvm/Support/SourceMgr.h"
57 #include "llvm/Support/TargetRegistry.h"
58 #include "llvm/Support/TargetSelect.h"
59 #include "llvm/Support/raw_ostream.h"
63 #include <system_error>
66 using namespace object;
68 static cl::list<std::string>
69 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
72 Disassemble("disassemble",
73 cl::desc("Display assembler mnemonics for the machine instructions"));
75 Disassembled("d", cl::desc("Alias for --disassemble"),
76 cl::aliasopt(Disassemble));
79 Relocations("r", cl::desc("Display the relocation entries in the file"));
82 SectionContents("s", cl::desc("Display the content of each section"));
85 SymbolTable("t", cl::desc("Display the symbol table"));
88 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
90 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
93 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
94 "see -version for available targets"));
98 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
99 cl::value_desc("cpu-name"),
103 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
104 "see -version for available targets"));
107 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
108 "for each section."));
110 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
111 cl::aliasopt(SectionHeaders));
113 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
114 cl::aliasopt(SectionHeaders));
116 cl::list<std::string>
117 llvm::MAttrs("mattr",
119 cl::desc("Target specific attributes"),
120 cl::value_desc("a1,+a2,-a3,..."));
123 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
124 "do not print the instruction bytes."));
127 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
130 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
131 cl::aliasopt(UnwindInfo));
134 PrivateHeaders("private-headers",
135 cl::desc("Display format specific file headers"));
138 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
139 cl::aliasopt(PrivateHeaders));
142 Symbolize("symbolize", cl::desc("When disassembling instructions, "
143 "try to symbolize operands."));
146 CFG("cfg", cl::desc("Create a CFG for every function found in the object"
147 " and write it to a graphviz file"));
149 // FIXME: Does it make sense to have a dedicated tool for yaml cfg output?
150 static cl::opt<std::string>
152 cl::desc("Create a CFG and write it as a YAML MCModule."),
153 cl::value_desc("yaml output file"));
155 static StringRef ToolName;
157 bool llvm::error(std::error_code EC) {
161 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
166 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
167 // Figure out the target triple.
168 llvm::Triple TheTriple("unknown-unknown-unknown");
169 if (TripleName.empty()) {
171 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
172 // TheTriple defaults to ELF, and COFF doesn't have an environment:
173 // the best we can do here is indicate that it is mach-o.
175 TheTriple.setObjectFormat(Triple::MachO);
178 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
179 if (COFFObj->getArch() == Triple::thumb)
180 TheTriple.setTriple("thumbv7-windows");
184 TheTriple.setTriple(Triple::normalize(TripleName));
186 // Get the target specific parser.
188 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
191 errs() << ToolName << ": " << Error;
195 // Update the triple name and return the found target.
196 TripleName = TheTriple.getTriple();
200 // Write a graphviz file for the CFG inside an MCFunction.
201 // FIXME: Use GraphWriter
202 static void emitDOTFile(const char *FileName, const MCFunction &f,
204 // Start a new dot file.
206 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text);
207 if (!Error.empty()) {
208 errs() << "llvm-objdump: warning: " << Error << '\n';
212 Out << "digraph \"" << f.getName() << "\" {\n";
213 Out << "graph [ rankdir = \"LR\" ];\n";
214 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) {
215 // Only print blocks that have predecessors.
216 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
218 if (!hasPreds && i != f.begin())
221 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
222 // Print instructions.
223 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
225 if (ii != 0) // Not the first line, start a new row.
227 if (ii + 1 == ie) // Last line, add an end id.
230 // Escape special chars and print the instruction in mnemonic form.
232 raw_string_ostream OS(Str);
233 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
234 Out << DOT::EscapeString(OS.str());
236 Out << "\" shape=\"record\" ];\n";
239 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
240 se = (*i)->succ_end(); si != se; ++si)
241 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
242 << (*si)->getInsts()->getBeginAddr() << ":a\n";
247 void llvm::DumpBytes(StringRef bytes) {
248 static const char hex_rep[] = "0123456789abcdef";
249 // FIXME: The real way to do this is to figure out the longest instruction
250 // and align to that size before printing. I'll fix this when I get
251 // around to outputting relocations.
252 // 15 is the longest x86 instruction
253 // 3 is for the hex rep of a byte + a space.
254 // 1 is for the null terminator.
255 enum { OutputSize = (15 * 3) + 1 };
256 char output[OutputSize];
258 assert(bytes.size() <= 15
259 && "DumpBytes only supports instructions of up to 15 bytes");
260 memset(output, ' ', sizeof(output));
262 for (StringRef::iterator i = bytes.begin(),
263 e = bytes.end(); i != e; ++i) {
264 output[index] = hex_rep[(*i & 0xF0) >> 4];
265 output[index + 1] = hex_rep[*i & 0xF];
269 output[sizeof(output) - 1] = 0;
273 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
274 uint64_t a_addr, b_addr;
275 if (error(a.getOffset(a_addr))) return false;
276 if (error(b.getOffset(b_addr))) return false;
277 return a_addr < b_addr;
280 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
281 const Target *TheTarget = getTarget(Obj);
282 // getTarget() will have already issued a diagnostic if necessary, so
283 // just bail here if it failed.
287 // Package up features to be passed to target/subtarget
288 std::string FeaturesStr;
290 SubtargetFeatures Features;
291 for (unsigned i = 0; i != MAttrs.size(); ++i)
292 Features.AddFeature(MAttrs[i]);
293 FeaturesStr = Features.getString();
296 std::unique_ptr<const MCRegisterInfo> MRI(
297 TheTarget->createMCRegInfo(TripleName));
299 errs() << "error: no register info for target " << TripleName << "\n";
303 // Set up disassembler.
304 std::unique_ptr<const MCAsmInfo> AsmInfo(
305 TheTarget->createMCAsmInfo(*MRI, TripleName));
307 errs() << "error: no assembly info for target " << TripleName << "\n";
311 std::unique_ptr<const MCSubtargetInfo> STI(
312 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
314 errs() << "error: no subtarget info for target " << TripleName << "\n";
318 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
320 errs() << "error: no instruction info for target " << TripleName << "\n";
324 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
325 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
327 std::unique_ptr<MCDisassembler> DisAsm(
328 TheTarget->createMCDisassembler(*STI, Ctx));
331 errs() << "error: no disassembler for target " << TripleName << "\n";
337 std::unique_ptr<MCRelocationInfo> RelInfo(
338 TheTarget->createMCRelocationInfo(TripleName, Ctx));
340 std::unique_ptr<MCSymbolizer> Symzer(
341 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo),
344 DisAsm->setSymbolizer(std::move(Symzer));
348 std::unique_ptr<const MCInstrAnalysis> MIA(
349 TheTarget->createMCInstrAnalysis(MII.get()));
351 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
352 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
353 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
355 errs() << "error: no instruction printer for target " << TripleName
360 if (CFG || !YAMLCFG.empty()) {
361 std::unique_ptr<MCObjectDisassembler> OD(
362 new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
363 std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
364 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
365 AE = Mod->atom_end();
367 outs() << "Atom " << (*AI)->getName() << ": \n";
368 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
369 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
372 IP->printInst(&II->Inst, outs(), "");
378 for (MCModule::const_func_iterator FI = Mod->func_begin(),
379 FE = Mod->func_end();
381 static int filenum = 0;
382 emitDOTFile((Twine((*FI)->getName()) + "_" +
383 utostr(filenum) + ".dot").str().c_str(),
388 if (!YAMLCFG.empty()) {
390 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
391 if (!Error.empty()) {
392 errs() << ToolName << ": warning: " << Error << '\n';
395 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
399 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
400 "\t\t\t%08" PRIx64 ": ";
402 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
403 // in RelocSecs contain the relocations for section S.
405 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
406 for (const SectionRef &Section : Obj->sections()) {
407 section_iterator Sec2 = Section.getRelocatedSection();
408 if (Sec2 != Obj->section_end())
409 SectionRelocMap[*Sec2].push_back(Section);
412 for (const SectionRef &Section : Obj->sections()) {
414 if (error(Section.isText(Text)))
419 uint64_t SectionAddr;
420 if (error(Section.getAddress(SectionAddr)))
424 if (error(Section.getSize(SectSize)))
427 // Make a list of all the symbols in this section.
428 std::vector<std::pair<uint64_t, StringRef>> Symbols;
429 for (const SymbolRef &Symbol : Obj->symbols()) {
431 if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
433 if (error(Symbol.getAddress(Address)))
435 if (Address == UnknownAddressOrSize)
437 Address -= SectionAddr;
438 if (Address >= SectSize)
442 if (error(Symbol.getName(Name)))
444 Symbols.push_back(std::make_pair(Address, Name));
448 // Sort the symbols by address, just in case they didn't come in that way.
449 array_pod_sort(Symbols.begin(), Symbols.end());
451 // Make a list of all the relocations for this section.
452 std::vector<RelocationRef> Rels;
454 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
455 for (const RelocationRef &Reloc : RelocSec.relocations()) {
456 Rels.push_back(Reloc);
461 // Sort relocations by address.
462 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
464 StringRef SegmentName = "";
465 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
466 DataRefImpl DR = Section.getRawDataRefImpl();
467 SegmentName = MachO->getSectionFinalSegmentName(DR);
470 if (error(Section.getName(name)))
472 outs() << "Disassembly of section ";
473 if (!SegmentName.empty())
474 outs() << SegmentName << ",";
475 outs() << name << ':';
477 // If the section has no symbols just insert a dummy one and disassemble
478 // the whole section.
480 Symbols.push_back(std::make_pair(0, name));
483 SmallString<40> Comments;
484 raw_svector_ostream CommentStream(Comments);
487 if (error(Section.getContents(Bytes)))
489 StringRefMemoryObject memoryObject(Bytes, SectionAddr);
493 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
494 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
495 // Disassemble symbol by symbol.
496 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
498 uint64_t Start = Symbols[si].first;
499 // The end is either the section end or the beginning of the next symbol.
500 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
501 // If this symbol has the same address as the next symbol, then skip it.
505 outs() << '\n' << Symbols[si].second << ":\n";
508 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
510 raw_ostream &DebugOut = nulls();
513 for (Index = Start; Index < End; Index += Size) {
516 if (DisAsm->getInstruction(Inst, Size, memoryObject,
518 DebugOut, CommentStream)) {
519 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
520 if (!NoShowRawInsn) {
522 DumpBytes(StringRef(Bytes.data() + Index, Size));
524 IP->printInst(&Inst, outs(), "");
525 outs() << CommentStream.str();
529 errs() << ToolName << ": warning: invalid instruction encoding\n";
531 Size = 1; // skip illegible bytes
534 // Print relocation for instruction.
535 while (rel_cur != rel_end) {
538 SmallString<16> name;
541 // If this relocation is hidden, skip it.
542 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
543 if (hidden) goto skip_print_rel;
545 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
546 // Stop when rel_cur's address is past the current instruction.
547 if (addr >= Index + Size) break;
548 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
549 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
551 outs() << format(Fmt.data(), SectionAddr + addr) << name
552 << "\t" << val << "\n";
562 static void PrintRelocations(const ObjectFile *Obj) {
563 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
565 // Regular objdump doesn't print relocations in non-relocatable object
567 if (!Obj->isRelocatableObject())
570 for (const SectionRef &Section : Obj->sections()) {
571 if (Section.relocation_begin() == Section.relocation_end())
574 if (error(Section.getName(secname)))
576 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
577 for (const RelocationRef &Reloc : Section.relocations()) {
580 SmallString<32> relocname;
581 SmallString<32> valuestr;
582 if (error(Reloc.getHidden(hidden)))
586 if (error(Reloc.getTypeName(relocname)))
588 if (error(Reloc.getOffset(address)))
590 if (error(Reloc.getValueString(valuestr)))
592 outs() << format(Fmt.data(), address) << " " << relocname << " "
599 static void PrintSectionHeaders(const ObjectFile *Obj) {
600 outs() << "Sections:\n"
601 "Idx Name Size Address Type\n";
603 for (const SectionRef &Section : Obj->sections()) {
605 if (error(Section.getName(Name)))
608 if (error(Section.getAddress(Address)))
611 if (error(Section.getSize(Size)))
613 bool Text, Data, BSS;
614 if (error(Section.isText(Text)))
616 if (error(Section.isData(Data)))
618 if (error(Section.isBSS(BSS)))
620 std::string Type = (std::string(Text ? "TEXT " : "") +
621 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
622 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
623 Name.str().c_str(), Size, Address, Type.c_str());
628 static void PrintSectionContents(const ObjectFile *Obj) {
630 for (const SectionRef &Section : Obj->sections()) {
635 if (error(Section.getName(Name)))
637 if (error(Section.getAddress(BaseAddr)))
639 if (error(Section.isBSS(BSS)))
642 outs() << "Contents of section " << Name << ":\n";
645 if (error(Section.getSize(Size)))
647 outs() << format("<skipping contents of bss section at [%04" PRIx64
648 ", %04" PRIx64 ")>\n",
649 BaseAddr, BaseAddr + Size);
653 if (error(Section.getContents(Contents)))
656 // Dump out the content as hex and printable ascii characters.
657 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
658 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
660 for (std::size_t i = 0; i < 16; ++i) {
661 if (i != 0 && i % 4 == 0)
664 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
665 << hexdigit(Contents[addr + i] & 0xF, true);
671 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
672 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
673 outs() << Contents[addr + i];
682 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
683 const coff_file_header *header;
684 if (error(coff->getHeader(header)))
687 for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
688 const coff_symbol *Symbol;
690 if (error(coff->getSymbol(SI, Symbol)))
693 if (error(coff->getSymbolName(Symbol, Name)))
696 outs() << "[" << format("%2d", SI) << "]"
697 << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
698 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
699 << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
700 << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
701 << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
702 << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
705 for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
706 if (Symbol->isSectionDefinition()) {
707 const coff_aux_section_definition *asd;
708 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
712 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
713 , unsigned(asd->Length)
714 , unsigned(asd->NumberOfRelocations)
715 , unsigned(asd->NumberOfLinenumbers)
716 , unsigned(asd->CheckSum))
717 << format("assoc %d comdat %d\n"
718 , unsigned(asd->Number)
719 , unsigned(asd->Selection));
720 } else if (Symbol->isFileRecord()) {
721 const coff_aux_file *AF;
722 if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
725 StringRef Name(AF->FileName,
726 Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
727 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
729 SI = SI + Symbol->NumberOfAuxSymbols;
732 outs() << "AUX Unknown\n";
738 static void PrintSymbolTable(const ObjectFile *o) {
739 outs() << "SYMBOL TABLE:\n";
741 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
742 PrintCOFFSymbolTable(coff);
745 for (const SymbolRef &Symbol : o->symbols()) {
748 SymbolRef::Type Type;
750 uint32_t Flags = Symbol.getFlags();
751 section_iterator Section = o->section_end();
752 if (error(Symbol.getName(Name)))
754 if (error(Symbol.getAddress(Address)))
756 if (error(Symbol.getType(Type)))
758 if (error(Symbol.getSize(Size)))
760 if (error(Symbol.getSection(Section)))
763 bool Global = Flags & SymbolRef::SF_Global;
764 bool Weak = Flags & SymbolRef::SF_Weak;
765 bool Absolute = Flags & SymbolRef::SF_Absolute;
767 if (Address == UnknownAddressOrSize)
769 if (Size == UnknownAddressOrSize)
772 if (Type != SymbolRef::ST_Unknown)
773 GlobLoc = Global ? 'g' : 'l';
774 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
777 if (Type == SymbolRef::ST_File)
779 else if (Type == SymbolRef::ST_Function)
782 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
785 outs() << format(Fmt, Address) << " "
786 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
787 << (Weak ? 'w' : ' ') // Weak?
788 << ' ' // Constructor. Not supported yet.
789 << ' ' // Warning. Not supported yet.
790 << ' ' // Indirect reference to another symbol.
791 << Debug // Debugging (d) or dynamic (D) symbol.
792 << FileFunc // Name of function (F), file (f) or object (O).
796 } else if (Section == o->section_end()) {
799 if (const MachOObjectFile *MachO =
800 dyn_cast<const MachOObjectFile>(o)) {
801 DataRefImpl DR = Section->getRawDataRefImpl();
802 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
803 outs() << SegmentName << ",";
805 StringRef SectionName;
806 if (error(Section->getName(SectionName)))
808 outs() << SectionName;
811 << format("%08" PRIx64 " ", Size)
817 static void PrintUnwindInfo(const ObjectFile *o) {
818 outs() << "Unwind info:\n\n";
820 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
821 printCOFFUnwindInfo(coff);
822 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
823 printMachOUnwindInfo(MachO);
825 // TODO: Extract DWARF dump tool to objdump.
826 errs() << "This operation is only currently supported "
827 "for COFF and MachO object files.\n";
832 static void printPrivateFileHeader(const ObjectFile *o) {
834 printELFFileHeader(o);
835 } else if (o->isCOFF()) {
836 printCOFFFileHeader(o);
837 } else if (o->isMachO()) {
838 printMachOFileHeader(o);
842 static void DumpObject(const ObjectFile *o) {
844 outs() << o->getFileName()
845 << ":\tfile format " << o->getFileFormatName() << "\n\n";
848 DisassembleObject(o, Relocations);
849 if (Relocations && !Disassemble)
852 PrintSectionHeaders(o);
854 PrintSectionContents(o);
860 printPrivateFileHeader(o);
863 /// @brief Dump each object file in \a a;
864 static void DumpArchive(const Archive *a) {
865 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
867 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
868 if (std::error_code EC = ChildOrErr.getError()) {
869 // Ignore non-object files.
870 if (EC != object_error::invalid_file_type)
871 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
875 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
878 errs() << ToolName << ": '" << a->getFileName() << "': "
879 << "Unrecognized file type.\n";
883 /// @brief Open file and figure out how to dump it.
884 static void DumpInput(StringRef file) {
885 // If file isn't stdin, check that it exists.
886 if (file != "-" && !sys::fs::exists(file)) {
887 errs() << ToolName << ": '" << file << "': " << "No such file\n";
891 if (MachOOpt && Disassemble) {
892 DisassembleInputMachO(file);
896 // Attempt to open the binary.
897 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
898 if (std::error_code EC = BinaryOrErr.getError()) {
899 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
902 Binary &Binary = *BinaryOrErr.get().getBinary();
904 if (Archive *a = dyn_cast<Archive>(&Binary))
906 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
909 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
912 int main(int argc, char **argv) {
913 // Print a stack trace if we signal out.
914 sys::PrintStackTraceOnErrorSignal();
915 PrettyStackTraceProgram X(argc, argv);
916 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
918 // Initialize targets and assembly printers/parsers.
919 llvm::InitializeAllTargetInfos();
920 llvm::InitializeAllTargetMCs();
921 llvm::InitializeAllAsmParsers();
922 llvm::InitializeAllDisassemblers();
924 // Register the target printer for --version.
925 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
927 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
928 TripleName = Triple::normalize(TripleName);
932 // Defaults to a.out if no filenames specified.
933 if (InputFilenames.size() == 0)
934 InputFilenames.push_back("a.out");
942 && !PrivateHeaders) {
943 cl::PrintHelpMessage();
947 std::for_each(InputFilenames.begin(), InputFilenames.end(),