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 //===----------------------------------------------------------------------===//
16 #include "llvm-objdump.h"
17 #include "MCFunction.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Object/Archive.h"
30 #include "llvm/Object/COFF.h"
31 #include "llvm/Object/MachO.h"
32 #include "llvm/Object/ObjectFile.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Format.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/MemoryObject.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Support/system_error.h"
54 using namespace object;
56 static cl::list<std::string>
57 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
60 Disassemble("disassemble",
61 cl::desc("Display assembler mnemonics for the machine instructions"));
63 Disassembled("d", cl::desc("Alias for --disassemble"),
64 cl::aliasopt(Disassemble));
67 Relocations("r", cl::desc("Display the relocation entries in the file"));
70 SectionContents("s", cl::desc("Display the content of each section"));
73 SymbolTable("t", cl::desc("Display the symbol table"));
76 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
78 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
81 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
82 "see -version for available targets"));
85 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
86 "see -version for available targets"));
89 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
90 "for each section."));
92 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
93 cl::aliasopt(SectionHeaders));
95 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
96 cl::aliasopt(SectionHeaders));
98 static cl::list<std::string>
101 cl::desc("Target specific attributes"),
102 cl::value_desc("a1,+a2,-a3,..."));
105 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
106 "do not print the instruction bytes."));
109 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
112 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
113 cl::aliasopt(UnwindInfo));
115 static StringRef ToolName;
117 bool llvm::error(error_code ec) {
118 if (!ec) return false;
120 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
125 static const Target *getTarget(const ObjectFile *Obj = NULL) {
126 // Figure out the target triple.
127 llvm::Triple TheTriple("unknown-unknown-unknown");
128 if (TripleName.empty()) {
130 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
132 TheTriple.setTriple(Triple::normalize(TripleName));
134 // Get the target specific parser.
136 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
139 errs() << ToolName << ": " << Error;
143 // Update the triple name and return the found target.
144 TripleName = TheTriple.getTriple();
148 void llvm::StringRefMemoryObject::anchor() { }
150 void llvm::DumpBytes(StringRef bytes) {
151 static const char hex_rep[] = "0123456789abcdef";
152 // FIXME: The real way to do this is to figure out the longest instruction
153 // and align to that size before printing. I'll fix this when I get
154 // around to outputting relocations.
155 // 15 is the longest x86 instruction
156 // 3 is for the hex rep of a byte + a space.
157 // 1 is for the null terminator.
158 enum { OutputSize = (15 * 3) + 1 };
159 char output[OutputSize];
161 assert(bytes.size() <= 15
162 && "DumpBytes only supports instructions of up to 15 bytes");
163 memset(output, ' ', sizeof(output));
165 for (StringRef::iterator i = bytes.begin(),
166 e = bytes.end(); i != e; ++i) {
167 output[index] = hex_rep[(*i & 0xF0) >> 4];
168 output[index + 1] = hex_rep[*i & 0xF];
172 output[sizeof(output) - 1] = 0;
176 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
177 uint64_t a_addr, b_addr;
178 if (error(a.getAddress(a_addr))) return false;
179 if (error(b.getAddress(b_addr))) return false;
180 return a_addr < b_addr;
183 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
184 const Target *TheTarget = getTarget(Obj);
185 // getTarget() will have already issued a diagnostic if necessary, so
186 // just bail here if it failed.
190 // Package up features to be passed to target/subtarget
191 std::string FeaturesStr;
193 SubtargetFeatures Features;
194 for (unsigned i = 0; i != MAttrs.size(); ++i)
195 Features.AddFeature(MAttrs[i]);
196 FeaturesStr = Features.getString();
200 for (section_iterator i = Obj->begin_sections(),
201 e = Obj->end_sections();
202 i != e; i.increment(ec)) {
203 if (error(ec)) break;
205 if (error(i->isText(text))) break;
208 uint64_t SectionAddr;
209 if (error(i->getAddress(SectionAddr))) break;
211 // Make a list of all the symbols in this section.
212 std::vector<std::pair<uint64_t, StringRef> > Symbols;
213 for (symbol_iterator si = Obj->begin_symbols(),
214 se = Obj->end_symbols();
215 si != se; si.increment(ec)) {
217 if (!error(i->containsSymbol(*si, contains)) && contains) {
219 if (error(si->getAddress(Address))) break;
220 Address -= SectionAddr;
223 if (error(si->getName(Name))) break;
224 Symbols.push_back(std::make_pair(Address, Name));
228 // Sort the symbols by address, just in case they didn't come in that way.
229 array_pod_sort(Symbols.begin(), Symbols.end());
231 // Make a list of all the relocations for this section.
232 std::vector<RelocationRef> Rels;
234 for (relocation_iterator ri = i->begin_relocations(),
235 re = i->end_relocations();
236 ri != re; ri.increment(ec)) {
237 if (error(ec)) break;
242 // Sort relocations by address.
243 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
245 StringRef SegmentName = "";
246 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
247 DataRefImpl DR = i->getRawDataRefImpl();
248 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
252 if (error(i->getName(name))) break;
253 outs() << "Disassembly of section ";
254 if (!SegmentName.empty())
255 outs() << SegmentName << ",";
256 outs() << name << ':';
258 // If the section has no symbols just insert a dummy one and disassemble
259 // the whole section.
261 Symbols.push_back(std::make_pair(0, name));
263 // Set up disassembler.
264 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
267 errs() << "error: no assembly info for target " << TripleName << "\n";
271 OwningPtr<const MCSubtargetInfo> STI(
272 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
275 errs() << "error: no subtarget info for target " << TripleName << "\n";
279 OwningPtr<const MCDisassembler> DisAsm(
280 TheTarget->createMCDisassembler(*STI));
282 errs() << "error: no disassembler for target " << TripleName << "\n";
286 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
288 errs() << "error: no register info for target " << TripleName << "\n";
292 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
294 errs() << "error: no instruction info for target " << TripleName << "\n";
298 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
299 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
300 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
302 errs() << "error: no instruction printer for target " << TripleName
308 if (error(i->getContents(Bytes))) break;
309 StringRefMemoryObject memoryObject(Bytes);
313 if (error(i->getSize(SectSize))) break;
315 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
316 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
317 // Disassemble symbol by symbol.
318 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
319 uint64_t Start = Symbols[si].first;
321 // The end is either the size of the section or the beginning of the next
325 // Make sure this symbol takes up space.
326 else if (Symbols[si + 1].first != Start)
327 End = Symbols[si + 1].first - 1;
329 // This symbol has the same address as the next symbol. Skip it.
332 outs() << '\n' << Symbols[si].second << ":\n";
335 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
337 raw_ostream &DebugOut = nulls();
340 for (Index = Start; Index < End; Index += Size) {
343 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
344 DebugOut, nulls())) {
345 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
346 if (!NoShowRawInsn) {
348 DumpBytes(StringRef(Bytes.data() + Index, Size));
350 IP->printInst(&Inst, outs(), "");
353 errs() << ToolName << ": warning: invalid instruction encoding\n";
355 Size = 1; // skip illegible bytes
358 // Print relocation for instruction.
359 while (rel_cur != rel_end) {
362 SmallString<16> name;
365 // If this relocation is hidden, skip it.
366 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
367 if (hidden) goto skip_print_rel;
369 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
370 // Stop when rel_cur's address is past the current instruction.
371 if (addr >= Index + Size) break;
372 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
373 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
375 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
376 << "\t" << val << "\n";
386 static void PrintRelocations(const ObjectFile *o) {
388 for (section_iterator si = o->begin_sections(), se = o->end_sections();
389 si != se; si.increment(ec)){
390 if (error(ec)) return;
391 if (si->begin_relocations() == si->end_relocations())
394 if (error(si->getName(secname))) continue;
395 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
396 for (relocation_iterator ri = si->begin_relocations(),
397 re = si->end_relocations();
398 ri != re; ri.increment(ec)) {
399 if (error(ec)) return;
403 SmallString<32> relocname;
404 SmallString<32> valuestr;
405 if (error(ri->getHidden(hidden))) continue;
406 if (hidden) continue;
407 if (error(ri->getTypeName(relocname))) continue;
408 if (error(ri->getAddress(address))) continue;
409 if (error(ri->getValueString(valuestr))) continue;
410 outs() << address << " " << relocname << " " << valuestr << "\n";
416 static void PrintSectionHeaders(const ObjectFile *o) {
417 outs() << "Sections:\n"
418 "Idx Name Size Address Type\n";
421 for (section_iterator si = o->begin_sections(), se = o->end_sections();
422 si != se; si.increment(ec)) {
423 if (error(ec)) return;
425 if (error(si->getName(Name))) return;
427 if (error(si->getAddress(Address))) return;
429 if (error(si->getSize(Size))) return;
430 bool Text, Data, BSS;
431 if (error(si->isText(Text))) return;
432 if (error(si->isData(Data))) return;
433 if (error(si->isBSS(BSS))) return;
434 std::string Type = (std::string(Text ? "TEXT " : "") +
435 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
436 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
437 i, Name.str().c_str(), Size, Address, Type.c_str());
442 static void PrintSectionContents(const ObjectFile *o) {
444 for (section_iterator si = o->begin_sections(),
445 se = o->end_sections();
446 si != se; si.increment(ec)) {
447 if (error(ec)) return;
451 if (error(si->getName(Name))) continue;
452 if (error(si->getContents(Contents))) continue;
453 if (error(si->getAddress(BaseAddr))) continue;
455 outs() << "Contents of section " << Name << ":\n";
457 // Dump out the content as hex and printable ascii characters.
458 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
459 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
461 for (std::size_t i = 0; i < 16; ++i) {
462 if (i != 0 && i % 4 == 0)
465 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
466 << hexdigit(Contents[addr + i] & 0xF, true);
472 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
473 if (std::isprint(Contents[addr + i] & 0xFF))
474 outs() << Contents[addr + i];
483 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
484 const coff_file_header *header;
485 if (error(coff->getHeader(header))) return;
487 const coff_symbol *symbol = 0;
488 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
490 // Figure out which type of aux this is.
491 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
492 && symbol->Value == 0) { // Section definition.
493 const coff_aux_section_definition *asd;
494 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
497 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
498 , unsigned(asd->Length)
499 , unsigned(asd->NumberOfRelocations)
500 , unsigned(asd->NumberOfLinenumbers)
501 , unsigned(asd->CheckSum))
502 << format("assoc %d comdat %d\n"
503 , unsigned(asd->Number)
504 , unsigned(asd->Selection));
506 outs() << "AUX Unknown\n";
509 if (error(coff->getSymbol(i, symbol))) return;
510 if (error(coff->getSymbolName(symbol, name))) return;
511 outs() << "[" << format("%2d", i) << "]"
512 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
513 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
514 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
515 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
516 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
517 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
519 aux_count = symbol->NumberOfAuxSymbols;
524 static void PrintSymbolTable(const ObjectFile *o) {
525 outs() << "SYMBOL TABLE:\n";
527 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
528 PrintCOFFSymbolTable(coff);
531 for (symbol_iterator si = o->begin_symbols(),
532 se = o->end_symbols(); si != se; si.increment(ec)) {
533 if (error(ec)) return;
536 SymbolRef::Type Type;
539 section_iterator Section = o->end_sections();
540 if (error(si->getName(Name))) continue;
541 if (error(si->getAddress(Address))) continue;
542 if (error(si->getFlags(Flags))) continue;
543 if (error(si->getType(Type))) continue;
544 if (error(si->getSize(Size))) continue;
545 if (error(si->getSection(Section))) continue;
547 bool Global = Flags & SymbolRef::SF_Global;
548 bool Weak = Flags & SymbolRef::SF_Weak;
549 bool Absolute = Flags & SymbolRef::SF_Absolute;
551 if (Address == UnknownAddressOrSize)
553 if (Size == UnknownAddressOrSize)
556 if (Type != SymbolRef::ST_Unknown)
557 GlobLoc = Global ? 'g' : 'l';
558 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
561 if (Type == SymbolRef::ST_File)
563 else if (Type == SymbolRef::ST_Function)
566 outs() << format("%08" PRIx64, Address) << " "
567 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
568 << (Weak ? 'w' : ' ') // Weak?
569 << ' ' // Constructor. Not supported yet.
570 << ' ' // Warning. Not supported yet.
571 << ' ' // Indirect reference to another symbol.
572 << Debug // Debugging (d) or dynamic (D) symbol.
573 << FileFunc // Name of function (F), file (f) or object (O).
577 else if (Section == o->end_sections())
580 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
581 StringRef SegmentName;
582 DataRefImpl DR = Section->getRawDataRefImpl();
583 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
585 outs() << SegmentName << ",";
587 StringRef SectionName;
588 if (error(Section->getName(SectionName)))
590 outs() << SectionName;
593 << format("%08" PRIx64 " ", Size)
600 static void PrintUnwindInfo(const ObjectFile *o) {
601 outs() << "Unwind info:\n\n";
603 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
604 printCOFFUnwindInfo(coff);
606 // TODO: Extract DWARF dump tool to objdump.
607 errs() << "This operation is only currently supported "
608 "for COFF object files.\n";
613 static void DumpObject(const ObjectFile *o) {
615 outs() << o->getFileName()
616 << ":\tfile format " << o->getFileFormatName() << "\n\n";
619 DisassembleObject(o, Relocations);
620 if (Relocations && !Disassemble)
623 PrintSectionHeaders(o);
625 PrintSectionContents(o);
632 /// @brief Dump each object file in \a a;
633 static void DumpArchive(const Archive *a) {
634 for (Archive::child_iterator i = a->begin_children(),
635 e = a->end_children(); i != e; ++i) {
636 OwningPtr<Binary> child;
637 if (error_code ec = i->getAsBinary(child)) {
638 // Ignore non-object files.
639 if (ec != object_error::invalid_file_type)
640 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
644 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
647 errs() << ToolName << ": '" << a->getFileName() << "': "
648 << "Unrecognized file type.\n";
652 /// @brief Open file and figure out how to dump it.
653 static void DumpInput(StringRef file) {
654 // If file isn't stdin, check that it exists.
655 if (file != "-" && !sys::fs::exists(file)) {
656 errs() << ToolName << ": '" << file << "': " << "No such file\n";
660 if (MachOOpt && Disassemble) {
661 DisassembleInputMachO(file);
665 // Attempt to open the binary.
666 OwningPtr<Binary> binary;
667 if (error_code ec = createBinary(file, binary)) {
668 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
672 if (Archive *a = dyn_cast<Archive>(binary.get()))
674 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
677 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
680 int main(int argc, char **argv) {
681 // Print a stack trace if we signal out.
682 sys::PrintStackTraceOnErrorSignal();
683 PrettyStackTraceProgram X(argc, argv);
684 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
686 // Initialize targets and assembly printers/parsers.
687 llvm::InitializeAllTargetInfos();
688 llvm::InitializeAllTargetMCs();
689 llvm::InitializeAllAsmParsers();
690 llvm::InitializeAllDisassemblers();
692 // Register the target printer for --version.
693 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
695 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
696 TripleName = Triple::normalize(TripleName);
700 // Defaults to a.out if no filenames specified.
701 if (InputFilenames.size() == 0)
702 InputFilenames.push_back("a.out");
710 cl::PrintHelpMessage();
714 std::for_each(InputFilenames.begin(), InputFilenames.end(),