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));
116 PrivateHeaders("private-headers",
117 cl::desc("Display format specific file headers"));
120 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
121 cl::aliasopt(PrivateHeaders));
123 static StringRef ToolName;
125 bool llvm::error(error_code ec) {
126 if (!ec) return false;
128 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
133 static const Target *getTarget(const ObjectFile *Obj = NULL) {
134 // Figure out the target triple.
135 llvm::Triple TheTriple("unknown-unknown-unknown");
136 if (TripleName.empty()) {
138 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
140 TheTriple.setTriple(Triple::normalize(TripleName));
142 // Get the target specific parser.
144 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
147 errs() << ToolName << ": " << Error;
151 // Update the triple name and return the found target.
152 TripleName = TheTriple.getTriple();
156 void llvm::StringRefMemoryObject::anchor() { }
158 void llvm::DumpBytes(StringRef bytes) {
159 static const char hex_rep[] = "0123456789abcdef";
160 // FIXME: The real way to do this is to figure out the longest instruction
161 // and align to that size before printing. I'll fix this when I get
162 // around to outputting relocations.
163 // 15 is the longest x86 instruction
164 // 3 is for the hex rep of a byte + a space.
165 // 1 is for the null terminator.
166 enum { OutputSize = (15 * 3) + 1 };
167 char output[OutputSize];
169 assert(bytes.size() <= 15
170 && "DumpBytes only supports instructions of up to 15 bytes");
171 memset(output, ' ', sizeof(output));
173 for (StringRef::iterator i = bytes.begin(),
174 e = bytes.end(); i != e; ++i) {
175 output[index] = hex_rep[(*i & 0xF0) >> 4];
176 output[index + 1] = hex_rep[*i & 0xF];
180 output[sizeof(output) - 1] = 0;
184 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
185 uint64_t a_addr, b_addr;
186 if (error(a.getAddress(a_addr))) return false;
187 if (error(b.getAddress(b_addr))) return false;
188 return a_addr < b_addr;
191 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
192 const Target *TheTarget = getTarget(Obj);
193 // getTarget() will have already issued a diagnostic if necessary, so
194 // just bail here if it failed.
198 // Package up features to be passed to target/subtarget
199 std::string FeaturesStr;
201 SubtargetFeatures Features;
202 for (unsigned i = 0; i != MAttrs.size(); ++i)
203 Features.AddFeature(MAttrs[i]);
204 FeaturesStr = Features.getString();
208 for (section_iterator i = Obj->begin_sections(),
209 e = Obj->end_sections();
210 i != e; i.increment(ec)) {
211 if (error(ec)) break;
213 if (error(i->isText(text))) break;
216 uint64_t SectionAddr;
217 if (error(i->getAddress(SectionAddr))) break;
219 // Make a list of all the symbols in this section.
220 std::vector<std::pair<uint64_t, StringRef> > Symbols;
221 for (symbol_iterator si = Obj->begin_symbols(),
222 se = Obj->end_symbols();
223 si != se; si.increment(ec)) {
225 if (!error(i->containsSymbol(*si, contains)) && contains) {
227 if (error(si->getAddress(Address))) break;
228 Address -= SectionAddr;
231 if (error(si->getName(Name))) break;
232 Symbols.push_back(std::make_pair(Address, Name));
236 // Sort the symbols by address, just in case they didn't come in that way.
237 array_pod_sort(Symbols.begin(), Symbols.end());
239 // Make a list of all the relocations for this section.
240 std::vector<RelocationRef> Rels;
242 for (relocation_iterator ri = i->begin_relocations(),
243 re = i->end_relocations();
244 ri != re; ri.increment(ec)) {
245 if (error(ec)) break;
250 // Sort relocations by address.
251 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
253 StringRef SegmentName = "";
254 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
255 DataRefImpl DR = i->getRawDataRefImpl();
256 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
260 if (error(i->getName(name))) break;
261 outs() << "Disassembly of section ";
262 if (!SegmentName.empty())
263 outs() << SegmentName << ",";
264 outs() << name << ':';
266 // If the section has no symbols just insert a dummy one and disassemble
267 // the whole section.
269 Symbols.push_back(std::make_pair(0, name));
271 // Set up disassembler.
272 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
275 errs() << "error: no assembly info for target " << TripleName << "\n";
279 OwningPtr<const MCSubtargetInfo> STI(
280 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
283 errs() << "error: no subtarget info for target " << TripleName << "\n";
287 OwningPtr<const MCDisassembler> DisAsm(
288 TheTarget->createMCDisassembler(*STI));
290 errs() << "error: no disassembler for target " << TripleName << "\n";
294 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
296 errs() << "error: no register info for target " << TripleName << "\n";
300 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
302 errs() << "error: no instruction info for target " << TripleName << "\n";
306 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
307 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
308 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
310 errs() << "error: no instruction printer for target " << TripleName
316 if (error(i->getContents(Bytes))) break;
317 StringRefMemoryObject memoryObject(Bytes);
321 if (error(i->getSize(SectSize))) break;
323 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
324 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
325 // Disassemble symbol by symbol.
326 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
327 uint64_t Start = Symbols[si].first;
329 // The end is either the size of the section or the beginning of the next
333 // Make sure this symbol takes up space.
334 else if (Symbols[si + 1].first != Start)
335 End = Symbols[si + 1].first - 1;
337 // This symbol has the same address as the next symbol. Skip it.
340 outs() << '\n' << Symbols[si].second << ":\n";
343 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
345 raw_ostream &DebugOut = nulls();
348 for (Index = Start; Index < End; Index += Size) {
351 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
352 DebugOut, nulls())) {
353 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
354 if (!NoShowRawInsn) {
356 DumpBytes(StringRef(Bytes.data() + Index, Size));
358 IP->printInst(&Inst, outs(), "");
361 errs() << ToolName << ": warning: invalid instruction encoding\n";
363 Size = 1; // skip illegible bytes
366 // Print relocation for instruction.
367 while (rel_cur != rel_end) {
370 SmallString<16> name;
373 // If this relocation is hidden, skip it.
374 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
375 if (hidden) goto skip_print_rel;
377 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
378 // Stop when rel_cur's address is past the current instruction.
379 if (addr >= Index + Size) break;
380 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
381 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
383 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
384 << "\t" << val << "\n";
394 static void PrintRelocations(const ObjectFile *o) {
396 for (section_iterator si = o->begin_sections(), se = o->end_sections();
397 si != se; si.increment(ec)){
398 if (error(ec)) return;
399 if (si->begin_relocations() == si->end_relocations())
402 if (error(si->getName(secname))) continue;
403 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
404 for (relocation_iterator ri = si->begin_relocations(),
405 re = si->end_relocations();
406 ri != re; ri.increment(ec)) {
407 if (error(ec)) return;
411 SmallString<32> relocname;
412 SmallString<32> valuestr;
413 if (error(ri->getHidden(hidden))) continue;
414 if (hidden) continue;
415 if (error(ri->getTypeName(relocname))) continue;
416 if (error(ri->getAddress(address))) continue;
417 if (error(ri->getValueString(valuestr))) continue;
418 outs() << address << " " << relocname << " " << valuestr << "\n";
424 static void PrintSectionHeaders(const ObjectFile *o) {
425 outs() << "Sections:\n"
426 "Idx Name Size Address Type\n";
429 for (section_iterator si = o->begin_sections(), se = o->end_sections();
430 si != se; si.increment(ec)) {
431 if (error(ec)) return;
433 if (error(si->getName(Name))) return;
435 if (error(si->getAddress(Address))) return;
437 if (error(si->getSize(Size))) return;
438 bool Text, Data, BSS;
439 if (error(si->isText(Text))) return;
440 if (error(si->isData(Data))) return;
441 if (error(si->isBSS(BSS))) return;
442 std::string Type = (std::string(Text ? "TEXT " : "") +
443 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
444 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
445 i, Name.str().c_str(), Size, Address, Type.c_str());
450 static void PrintSectionContents(const ObjectFile *o) {
452 for (section_iterator si = o->begin_sections(),
453 se = o->end_sections();
454 si != se; si.increment(ec)) {
455 if (error(ec)) return;
459 if (error(si->getName(Name))) continue;
460 if (error(si->getContents(Contents))) continue;
461 if (error(si->getAddress(BaseAddr))) continue;
463 outs() << "Contents of section " << Name << ":\n";
465 // Dump out the content as hex and printable ascii characters.
466 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
467 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
469 for (std::size_t i = 0; i < 16; ++i) {
470 if (i != 0 && i % 4 == 0)
473 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
474 << hexdigit(Contents[addr + i] & 0xF, true);
480 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
481 if (std::isprint(Contents[addr + i] & 0xFF))
482 outs() << Contents[addr + i];
491 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
492 const coff_file_header *header;
493 if (error(coff->getHeader(header))) return;
495 const coff_symbol *symbol = 0;
496 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
498 // Figure out which type of aux this is.
499 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
500 && symbol->Value == 0) { // Section definition.
501 const coff_aux_section_definition *asd;
502 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
505 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
506 , unsigned(asd->Length)
507 , unsigned(asd->NumberOfRelocations)
508 , unsigned(asd->NumberOfLinenumbers)
509 , unsigned(asd->CheckSum))
510 << format("assoc %d comdat %d\n"
511 , unsigned(asd->Number)
512 , unsigned(asd->Selection));
514 outs() << "AUX Unknown\n";
517 if (error(coff->getSymbol(i, symbol))) return;
518 if (error(coff->getSymbolName(symbol, name))) return;
519 outs() << "[" << format("%2d", i) << "]"
520 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
521 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
522 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
523 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
524 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
525 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
527 aux_count = symbol->NumberOfAuxSymbols;
532 static void PrintSymbolTable(const ObjectFile *o) {
533 outs() << "SYMBOL TABLE:\n";
535 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
536 PrintCOFFSymbolTable(coff);
539 for (symbol_iterator si = o->begin_symbols(),
540 se = o->end_symbols(); si != se; si.increment(ec)) {
541 if (error(ec)) return;
544 SymbolRef::Type Type;
547 section_iterator Section = o->end_sections();
548 if (error(si->getName(Name))) continue;
549 if (error(si->getAddress(Address))) continue;
550 if (error(si->getFlags(Flags))) continue;
551 if (error(si->getType(Type))) continue;
552 if (error(si->getSize(Size))) continue;
553 if (error(si->getSection(Section))) continue;
555 bool Global = Flags & SymbolRef::SF_Global;
556 bool Weak = Flags & SymbolRef::SF_Weak;
557 bool Absolute = Flags & SymbolRef::SF_Absolute;
559 if (Address == UnknownAddressOrSize)
561 if (Size == UnknownAddressOrSize)
564 if (Type != SymbolRef::ST_Unknown)
565 GlobLoc = Global ? 'g' : 'l';
566 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
569 if (Type == SymbolRef::ST_File)
571 else if (Type == SymbolRef::ST_Function)
574 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
577 outs() << format(Fmt, Address) << " "
578 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
579 << (Weak ? 'w' : ' ') // Weak?
580 << ' ' // Constructor. Not supported yet.
581 << ' ' // Warning. Not supported yet.
582 << ' ' // Indirect reference to another symbol.
583 << Debug // Debugging (d) or dynamic (D) symbol.
584 << FileFunc // Name of function (F), file (f) or object (O).
588 else if (Section == o->end_sections())
591 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
592 StringRef SegmentName;
593 DataRefImpl DR = Section->getRawDataRefImpl();
594 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
596 outs() << SegmentName << ",";
598 StringRef SectionName;
599 if (error(Section->getName(SectionName)))
601 outs() << SectionName;
604 << format("%08" PRIx64 " ", Size)
611 static void PrintUnwindInfo(const ObjectFile *o) {
612 outs() << "Unwind info:\n\n";
614 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
615 printCOFFUnwindInfo(coff);
617 // TODO: Extract DWARF dump tool to objdump.
618 errs() << "This operation is only currently supported "
619 "for COFF object files.\n";
624 static void DumpObject(const ObjectFile *o) {
626 outs() << o->getFileName()
627 << ":\tfile format " << o->getFileFormatName() << "\n\n";
630 DisassembleObject(o, Relocations);
631 if (Relocations && !Disassemble)
634 PrintSectionHeaders(o);
636 PrintSectionContents(o);
641 if (PrivateHeaders && o->isELF())
642 printELFFileHeader(o);
645 /// @brief Dump each object file in \a a;
646 static void DumpArchive(const Archive *a) {
647 for (Archive::child_iterator i = a->begin_children(),
648 e = a->end_children(); i != e; ++i) {
649 OwningPtr<Binary> child;
650 if (error_code ec = i->getAsBinary(child)) {
651 // Ignore non-object files.
652 if (ec != object_error::invalid_file_type)
653 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
657 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
660 errs() << ToolName << ": '" << a->getFileName() << "': "
661 << "Unrecognized file type.\n";
665 /// @brief Open file and figure out how to dump it.
666 static void DumpInput(StringRef file) {
667 // If file isn't stdin, check that it exists.
668 if (file != "-" && !sys::fs::exists(file)) {
669 errs() << ToolName << ": '" << file << "': " << "No such file\n";
673 if (MachOOpt && Disassemble) {
674 DisassembleInputMachO(file);
678 // Attempt to open the binary.
679 OwningPtr<Binary> binary;
680 if (error_code ec = createBinary(file, binary)) {
681 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
685 if (Archive *a = dyn_cast<Archive>(binary.get()))
687 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
690 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
693 int main(int argc, char **argv) {
694 // Print a stack trace if we signal out.
695 sys::PrintStackTraceOnErrorSignal();
696 PrettyStackTraceProgram X(argc, argv);
697 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
699 // Initialize targets and assembly printers/parsers.
700 llvm::InitializeAllTargetInfos();
701 llvm::InitializeAllTargetMCs();
702 llvm::InitializeAllAsmParsers();
703 llvm::InitializeAllDisassemblers();
705 // Register the target printer for --version.
706 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
708 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
709 TripleName = Triple::normalize(TripleName);
713 // Defaults to a.out if no filenames specified.
714 if (InputFilenames.size() == 0)
715 InputFilenames.push_back("a.out");
723 && !PrivateHeaders) {
724 cl::PrintHelpMessage();
728 std::for_each(InputFilenames.begin(), InputFilenames.end(),