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/ELF.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Object/ObjectFile.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/GraphWriter.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/MemoryObject.h"
44 #include "llvm/Support/PrettyStackTrace.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Support/system_error.h"
55 using namespace object;
57 static cl::list<std::string>
58 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
61 Disassemble("disassemble",
62 cl::desc("Display assembler mnemonics for the machine instructions"));
64 Disassembled("d", cl::desc("Alias for --disassemble"),
65 cl::aliasopt(Disassemble));
68 Relocations("r", cl::desc("Display the relocation entries in the file"));
71 SectionContents("s", cl::desc("Display the content of each section"));
74 SymbolTable("t", cl::desc("Display the symbol table"));
77 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
79 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
82 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
83 "see -version for available targets"));
86 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
87 "see -version for available targets"));
90 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
91 "for each section."));
93 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
94 cl::aliasopt(SectionHeaders));
96 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
97 cl::aliasopt(SectionHeaders));
99 static cl::list<std::string>
102 cl::desc("Target specific attributes"),
103 cl::value_desc("a1,+a2,-a3,..."));
106 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
107 "do not print the instruction bytes."));
110 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
113 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
114 cl::aliasopt(UnwindInfo));
117 PrivateHeaders("private-headers",
118 cl::desc("Display format specific file headers"));
121 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
122 cl::aliasopt(PrivateHeaders));
124 static StringRef ToolName;
126 bool llvm::error(error_code ec) {
127 if (!ec) return false;
129 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
134 static const Target *getTarget(const ObjectFile *Obj = NULL) {
135 // Figure out the target triple.
136 llvm::Triple TheTriple("unknown-unknown-unknown");
137 if (TripleName.empty()) {
139 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
141 TheTriple.setTriple(Triple::normalize(TripleName));
143 // Get the target specific parser.
145 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
148 errs() << ToolName << ": " << Error;
152 // Update the triple name and return the found target.
153 TripleName = TheTriple.getTriple();
157 void llvm::StringRefMemoryObject::anchor() { }
159 void llvm::DumpBytes(StringRef bytes) {
160 static const char hex_rep[] = "0123456789abcdef";
161 // FIXME: The real way to do this is to figure out the longest instruction
162 // and align to that size before printing. I'll fix this when I get
163 // around to outputting relocations.
164 // 15 is the longest x86 instruction
165 // 3 is for the hex rep of a byte + a space.
166 // 1 is for the null terminator.
167 enum { OutputSize = (15 * 3) + 1 };
168 char output[OutputSize];
170 assert(bytes.size() <= 15
171 && "DumpBytes only supports instructions of up to 15 bytes");
172 memset(output, ' ', sizeof(output));
174 for (StringRef::iterator i = bytes.begin(),
175 e = bytes.end(); i != e; ++i) {
176 output[index] = hex_rep[(*i & 0xF0) >> 4];
177 output[index + 1] = hex_rep[*i & 0xF];
181 output[sizeof(output) - 1] = 0;
185 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
186 uint64_t a_addr, b_addr;
187 if (error(a.getAddress(a_addr))) return false;
188 if (error(b.getAddress(b_addr))) return false;
189 return a_addr < b_addr;
192 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
193 const Target *TheTarget = getTarget(Obj);
194 // getTarget() will have already issued a diagnostic if necessary, so
195 // just bail here if it failed.
199 // Package up features to be passed to target/subtarget
200 std::string FeaturesStr;
202 SubtargetFeatures Features;
203 for (unsigned i = 0; i != MAttrs.size(); ++i)
204 Features.AddFeature(MAttrs[i]);
205 FeaturesStr = Features.getString();
209 for (section_iterator i = Obj->begin_sections(),
210 e = Obj->end_sections();
211 i != e; i.increment(ec)) {
212 if (error(ec)) break;
214 if (error(i->isText(text))) break;
217 uint64_t SectionAddr;
218 if (error(i->getAddress(SectionAddr))) break;
220 // Make a list of all the symbols in this section.
221 std::vector<std::pair<uint64_t, StringRef> > Symbols;
222 for (symbol_iterator si = Obj->begin_symbols(),
223 se = Obj->end_symbols();
224 si != se; si.increment(ec)) {
226 if (!error(i->containsSymbol(*si, contains)) && contains) {
228 if (error(si->getAddress(Address))) break;
229 Address -= SectionAddr;
232 if (error(si->getName(Name))) break;
233 Symbols.push_back(std::make_pair(Address, Name));
237 // Sort the symbols by address, just in case they didn't come in that way.
238 array_pod_sort(Symbols.begin(), Symbols.end());
240 // Make a list of all the relocations for this section.
241 std::vector<RelocationRef> Rels;
243 for (relocation_iterator ri = i->begin_relocations(),
244 re = i->end_relocations();
245 ri != re; ri.increment(ec)) {
246 if (error(ec)) break;
251 // Sort relocations by address.
252 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
254 StringRef SegmentName = "";
255 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
256 DataRefImpl DR = i->getRawDataRefImpl();
257 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
261 if (error(i->getName(name))) break;
262 outs() << "Disassembly of section ";
263 if (!SegmentName.empty())
264 outs() << SegmentName << ",";
265 outs() << name << ':';
267 // If the section has no symbols just insert a dummy one and disassemble
268 // the whole section.
270 Symbols.push_back(std::make_pair(0, name));
272 // Set up disassembler.
273 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
276 errs() << "error: no assembly info for target " << TripleName << "\n";
280 OwningPtr<const MCSubtargetInfo> STI(
281 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
284 errs() << "error: no subtarget info for target " << TripleName << "\n";
288 OwningPtr<const MCDisassembler> DisAsm(
289 TheTarget->createMCDisassembler(*STI));
291 errs() << "error: no disassembler for target " << TripleName << "\n";
295 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
297 errs() << "error: no register info for target " << TripleName << "\n";
301 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
303 errs() << "error: no instruction info for target " << TripleName << "\n";
307 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
308 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
309 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
311 errs() << "error: no instruction printer for target " << TripleName
317 if (error(i->getContents(Bytes))) break;
318 StringRefMemoryObject memoryObject(Bytes);
322 if (error(i->getSize(SectSize))) break;
324 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
325 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
326 // Disassemble symbol by symbol.
327 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
328 uint64_t Start = Symbols[si].first;
330 // The end is either the size of the section or the beginning of the next
334 // Make sure this symbol takes up space.
335 else if (Symbols[si + 1].first != Start)
336 End = Symbols[si + 1].first - 1;
338 // This symbol has the same address as the next symbol. Skip it.
341 outs() << '\n' << Symbols[si].second << ":\n";
344 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
346 raw_ostream &DebugOut = nulls();
349 for (Index = Start; Index < End; Index += Size) {
352 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
353 DebugOut, nulls())) {
354 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
355 if (!NoShowRawInsn) {
357 DumpBytes(StringRef(Bytes.data() + Index, Size));
359 IP->printInst(&Inst, outs(), "");
362 errs() << ToolName << ": warning: invalid instruction encoding\n";
364 Size = 1; // skip illegible bytes
367 // Print relocation for instruction.
368 while (rel_cur != rel_end) {
371 SmallString<16> name;
374 // If this relocation is hidden, skip it.
375 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
376 if (hidden) goto skip_print_rel;
378 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
379 // Stop when rel_cur's address is past the current instruction.
380 if (addr >= Index + Size) break;
381 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
382 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
384 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
385 << "\t" << val << "\n";
395 static void PrintRelocations(const ObjectFile *o) {
397 for (section_iterator si = o->begin_sections(), se = o->end_sections();
398 si != se; si.increment(ec)){
399 if (error(ec)) return;
400 if (si->begin_relocations() == si->end_relocations())
403 if (error(si->getName(secname))) continue;
404 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
405 for (relocation_iterator ri = si->begin_relocations(),
406 re = si->end_relocations();
407 ri != re; ri.increment(ec)) {
408 if (error(ec)) return;
412 SmallString<32> relocname;
413 SmallString<32> valuestr;
414 if (error(ri->getHidden(hidden))) continue;
415 if (hidden) continue;
416 if (error(ri->getTypeName(relocname))) continue;
417 if (error(ri->getAddress(address))) continue;
418 if (error(ri->getValueString(valuestr))) continue;
419 outs() << address << " " << relocname << " " << valuestr << "\n";
425 static void PrintSectionHeaders(const ObjectFile *o) {
426 outs() << "Sections:\n"
427 "Idx Name Size Address Type\n";
430 for (section_iterator si = o->begin_sections(), se = o->end_sections();
431 si != se; si.increment(ec)) {
432 if (error(ec)) return;
434 if (error(si->getName(Name))) return;
436 if (error(si->getAddress(Address))) return;
438 if (error(si->getSize(Size))) return;
439 bool Text, Data, BSS;
440 if (error(si->isText(Text))) return;
441 if (error(si->isData(Data))) return;
442 if (error(si->isBSS(BSS))) return;
443 std::string Type = (std::string(Text ? "TEXT " : "") +
444 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
445 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
446 i, Name.str().c_str(), Size, Address, Type.c_str());
451 static void PrintSectionContents(const ObjectFile *o) {
453 for (section_iterator si = o->begin_sections(),
454 se = o->end_sections();
455 si != se; si.increment(ec)) {
456 if (error(ec)) return;
460 if (error(si->getName(Name))) continue;
461 if (error(si->getContents(Contents))) continue;
462 if (error(si->getAddress(BaseAddr))) continue;
464 outs() << "Contents of section " << Name << ":\n";
466 // Dump out the content as hex and printable ascii characters.
467 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
468 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
470 for (std::size_t i = 0; i < 16; ++i) {
471 if (i != 0 && i % 4 == 0)
474 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
475 << hexdigit(Contents[addr + i] & 0xF, true);
481 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
482 if (std::isprint(Contents[addr + i] & 0xFF))
483 outs() << Contents[addr + i];
492 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
493 const coff_file_header *header;
494 if (error(coff->getHeader(header))) return;
496 const coff_symbol *symbol = 0;
497 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
499 // Figure out which type of aux this is.
500 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
501 && symbol->Value == 0) { // Section definition.
502 const coff_aux_section_definition *asd;
503 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
506 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
507 , unsigned(asd->Length)
508 , unsigned(asd->NumberOfRelocations)
509 , unsigned(asd->NumberOfLinenumbers)
510 , unsigned(asd->CheckSum))
511 << format("assoc %d comdat %d\n"
512 , unsigned(asd->Number)
513 , unsigned(asd->Selection));
515 outs() << "AUX Unknown\n";
518 if (error(coff->getSymbol(i, symbol))) return;
519 if (error(coff->getSymbolName(symbol, name))) return;
520 outs() << "[" << format("%2d", i) << "]"
521 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
522 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
523 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
524 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
525 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
526 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
528 aux_count = symbol->NumberOfAuxSymbols;
533 static void PrintSymbolTable(const ObjectFile *o) {
534 outs() << "SYMBOL TABLE:\n";
536 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
537 PrintCOFFSymbolTable(coff);
540 for (symbol_iterator si = o->begin_symbols(),
541 se = o->end_symbols(); si != se; si.increment(ec)) {
542 if (error(ec)) return;
545 SymbolRef::Type Type;
548 section_iterator Section = o->end_sections();
549 if (error(si->getName(Name))) continue;
550 if (error(si->getAddress(Address))) continue;
551 if (error(si->getFlags(Flags))) continue;
552 if (error(si->getType(Type))) continue;
553 if (error(si->getSize(Size))) continue;
554 if (error(si->getSection(Section))) continue;
556 bool Global = Flags & SymbolRef::SF_Global;
557 bool Weak = Flags & SymbolRef::SF_Weak;
558 bool Absolute = Flags & SymbolRef::SF_Absolute;
560 if (Address == UnknownAddressOrSize)
562 if (Size == UnknownAddressOrSize)
565 if (Type != SymbolRef::ST_Unknown)
566 GlobLoc = Global ? 'g' : 'l';
567 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
570 if (Type == SymbolRef::ST_File)
572 else if (Type == SymbolRef::ST_Function)
575 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
578 outs() << format(Fmt, Address) << " "
579 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
580 << (Weak ? 'w' : ' ') // Weak?
581 << ' ' // Constructor. Not supported yet.
582 << ' ' // Warning. Not supported yet.
583 << ' ' // Indirect reference to another symbol.
584 << Debug // Debugging (d) or dynamic (D) symbol.
585 << FileFunc // Name of function (F), file (f) or object (O).
589 else if (Section == o->end_sections())
592 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
593 StringRef SegmentName;
594 DataRefImpl DR = Section->getRawDataRefImpl();
595 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
597 outs() << SegmentName << ",";
599 StringRef SectionName;
600 if (error(Section->getName(SectionName)))
602 outs() << SectionName;
605 << format("%08" PRIx64 " ", Size)
612 static void PrintUnwindInfo(const ObjectFile *o) {
613 outs() << "Unwind info:\n\n";
615 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
616 printCOFFUnwindInfo(coff);
618 // TODO: Extract DWARF dump tool to objdump.
619 errs() << "This operation is only currently supported "
620 "for COFF object files.\n";
625 static void DumpObject(const ObjectFile *o) {
627 outs() << o->getFileName()
628 << ":\tfile format " << o->getFileFormatName() << "\n\n";
631 DisassembleObject(o, Relocations);
632 if (Relocations && !Disassemble)
635 PrintSectionHeaders(o);
637 PrintSectionContents(o);
642 if (PrivateHeaders && o->isELF())
643 printELFFileHeader(o);
646 /// @brief Dump each object file in \a a;
647 static void DumpArchive(const Archive *a) {
648 for (Archive::child_iterator i = a->begin_children(),
649 e = a->end_children(); i != e; ++i) {
650 OwningPtr<Binary> child;
651 if (error_code ec = i->getAsBinary(child)) {
652 // Ignore non-object files.
653 if (ec != object_error::invalid_file_type)
654 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
658 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
661 errs() << ToolName << ": '" << a->getFileName() << "': "
662 << "Unrecognized file type.\n";
666 /// @brief Open file and figure out how to dump it.
667 static void DumpInput(StringRef file) {
668 // If file isn't stdin, check that it exists.
669 if (file != "-" && !sys::fs::exists(file)) {
670 errs() << ToolName << ": '" << file << "': " << "No such file\n";
674 if (MachOOpt && Disassemble) {
675 DisassembleInputMachO(file);
679 // Attempt to open the binary.
680 OwningPtr<Binary> binary;
681 if (error_code ec = createBinary(file, binary)) {
682 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
686 if (Archive *a = dyn_cast<Archive>(binary.get()))
688 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
691 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
694 int main(int argc, char **argv) {
695 // Print a stack trace if we signal out.
696 sys::PrintStackTraceOnErrorSignal();
697 PrettyStackTraceProgram X(argc, argv);
698 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
700 // Initialize targets and assembly printers/parsers.
701 llvm::InitializeAllTargetInfos();
702 llvm::InitializeAllTargetMCs();
703 llvm::InitializeAllAsmParsers();
704 llvm::InitializeAllDisassemblers();
706 // Register the target printer for --version.
707 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
709 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
710 TripleName = Triple::normalize(TripleName);
714 // Defaults to a.out if no filenames specified.
715 if (InputFilenames.size() == 0)
716 InputFilenames.push_back("a.out");
724 && !PrivateHeaders) {
725 cl::PrintHelpMessage();
729 std::for_each(InputFilenames.begin(), InputFilenames.end(),