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/Object/Archive.h"
19 #include "llvm/Object/COFF.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/GraphWriter.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/MemoryObject.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/SourceMgr.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Support/system_error.h"
53 using namespace object;
55 static cl::list<std::string>
56 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
59 Disassemble("disassemble",
60 cl::desc("Display assembler mnemonics for the machine instructions"));
62 Disassembled("d", cl::desc("Alias for --disassemble"),
63 cl::aliasopt(Disassemble));
66 Relocations("r", cl::desc("Display the relocation entries in the file"));
69 SectionContents("s", cl::desc("Display the content of each section"));
72 SymbolTable("t", cl::desc("Display the symbol table"));
75 MachO("macho", cl::desc("Use MachO specific object file parser"));
77 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
80 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
81 "see -version for available targets"));
84 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
85 "see -version for available targets"));
88 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
89 "for each section."));
91 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
92 cl::aliasopt(SectionHeaders));
94 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
95 cl::aliasopt(SectionHeaders));
97 static StringRef ToolName;
99 static bool error(error_code ec) {
100 if (!ec) return false;
102 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
107 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
108 // Figure out the target triple.
109 llvm::Triple TT("unknown-unknown-unknown");
110 if (TripleName.empty()) {
112 TT.setArch(Triple::ArchType(Obj->getArch()));
114 TT.setTriple(Triple::normalize(TripleName));
116 if (!ArchName.empty())
117 TT.setArchName(ArchName);
119 TripleName = TT.str();
121 // Get the target specific parser.
123 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
127 errs() << ToolName << ": error: unable to get target for '" << TripleName
128 << "', see --version and --triple.\n";
132 void llvm::StringRefMemoryObject::anchor() { }
134 void llvm::DumpBytes(StringRef bytes) {
135 static const char hex_rep[] = "0123456789abcdef";
136 // FIXME: The real way to do this is to figure out the longest instruction
137 // and align to that size before printing. I'll fix this when I get
138 // around to outputting relocations.
139 // 15 is the longest x86 instruction
140 // 3 is for the hex rep of a byte + a space.
141 // 1 is for the null terminator.
142 enum { OutputSize = (15 * 3) + 1 };
143 char output[OutputSize];
145 assert(bytes.size() <= 15
146 && "DumpBytes only supports instructions of up to 15 bytes");
147 memset(output, ' ', sizeof(output));
149 for (StringRef::iterator i = bytes.begin(),
150 e = bytes.end(); i != e; ++i) {
151 output[index] = hex_rep[(*i & 0xF0) >> 4];
152 output[index + 1] = hex_rep[*i & 0xF];
156 output[sizeof(output) - 1] = 0;
160 static bool RelocAddressLess(RelocationRef a, RelocationRef b) {
161 uint64_t a_addr, b_addr;
162 if (error(a.getAddress(a_addr))) return false;
163 if (error(b.getAddress(b_addr))) return false;
164 return a_addr < b_addr;
167 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
168 const Target *TheTarget = GetTarget(Obj);
170 // GetTarget prints out stuff.
175 for (section_iterator i = Obj->begin_sections(),
176 e = Obj->end_sections();
177 i != e; i.increment(ec)) {
178 if (error(ec)) break;
180 if (error(i->isText(text))) break;
183 uint64_t SectionAddr;
184 if (error(i->getAddress(SectionAddr))) break;
186 // Make a list of all the symbols in this section.
187 std::vector<std::pair<uint64_t, StringRef> > Symbols;
188 for (symbol_iterator si = Obj->begin_symbols(),
189 se = Obj->end_symbols();
190 si != se; si.increment(ec)) {
192 if (!error(i->containsSymbol(*si, contains)) && contains) {
194 if (error(si->getAddress(Address))) break;
195 Address -= SectionAddr;
198 if (error(si->getName(Name))) break;
199 Symbols.push_back(std::make_pair(Address, Name));
203 // Sort the symbols by address, just in case they didn't come in that way.
204 array_pod_sort(Symbols.begin(), Symbols.end());
206 // Make a list of all the relocations for this section.
207 std::vector<RelocationRef> Rels;
209 for (relocation_iterator ri = i->begin_relocations(),
210 re = i->end_relocations();
211 ri != re; ri.increment(ec)) {
212 if (error(ec)) break;
217 // Sort relocations by address.
218 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
221 if (error(i->getName(name))) break;
222 outs() << "Disassembly of section " << name << ':';
224 // If the section has no symbols just insert a dummy one and disassemble
225 // the whole section.
227 Symbols.push_back(std::make_pair(0, name));
229 // Set up disassembler.
230 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
233 errs() << "error: no assembly info for target " << TripleName << "\n";
237 OwningPtr<const MCSubtargetInfo> STI(
238 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
241 errs() << "error: no subtarget info for target " << TripleName << "\n";
245 OwningPtr<const MCDisassembler> DisAsm(
246 TheTarget->createMCDisassembler(*STI));
248 errs() << "error: no disassembler for target " << TripleName << "\n";
252 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
254 errs() << "error: no register info for target " << TripleName << "\n";
258 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
260 errs() << "error: no instruction info for target " << TripleName << "\n";
264 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
265 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
266 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
268 errs() << "error: no instruction printer for target " << TripleName
274 if (error(i->getContents(Bytes))) break;
275 StringRefMemoryObject memoryObject(Bytes);
279 if (error(i->getSize(SectSize))) break;
281 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
282 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
283 // Disassemble symbol by symbol.
284 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
285 uint64_t Start = Symbols[si].first;
287 // The end is either the size of the section or the beginning of the next
291 // Make sure this symbol takes up space.
292 else if (Symbols[si + 1].first != Start)
293 End = Symbols[si + 1].first - 1;
295 // This symbol has the same address as the next symbol. Skip it.
298 outs() << '\n' << Symbols[si].second << ":\n";
301 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
303 raw_ostream &DebugOut = nulls();
306 for (Index = Start; Index < End; Index += Size) {
309 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
310 DebugOut, nulls())) {
311 outs() << format("%8" PRIx64 ":\t", SectionAddr + Index);
312 DumpBytes(StringRef(Bytes.data() + Index, Size));
313 IP->printInst(&Inst, outs(), "");
316 errs() << ToolName << ": warning: invalid instruction encoding\n";
318 Size = 1; // skip illegible bytes
321 // Print relocation for instruction.
322 while (rel_cur != rel_end) {
325 SmallString<16> name;
328 // If this relocation is hidden, skip it.
329 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
330 if (hidden) goto skip_print_rel;
332 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
333 // Stop when rel_cur's address is past the current instruction.
334 if (addr >= Index + Size) break;
335 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
336 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
338 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
339 << "\t" << val << "\n";
349 static void PrintRelocations(const ObjectFile *o) {
351 for (section_iterator si = o->begin_sections(), se = o->end_sections();
352 si != se; si.increment(ec)){
353 if (error(ec)) return;
354 if (si->begin_relocations() == si->end_relocations())
357 if (error(si->getName(secname))) continue;
358 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
359 for (relocation_iterator ri = si->begin_relocations(),
360 re = si->end_relocations();
361 ri != re; ri.increment(ec)) {
362 if (error(ec)) return;
366 SmallString<32> relocname;
367 SmallString<32> valuestr;
368 if (error(ri->getHidden(hidden))) continue;
369 if (hidden) continue;
370 if (error(ri->getTypeName(relocname))) continue;
371 if (error(ri->getAddress(address))) continue;
372 if (error(ri->getValueString(valuestr))) continue;
373 outs() << address << " " << relocname << " " << valuestr << "\n";
379 static void PrintSectionHeaders(const ObjectFile *o) {
380 outs() << "Sections:\n"
381 "Idx Name Size Address Type\n";
384 for (section_iterator si = o->begin_sections(), se = o->end_sections();
385 si != se; si.increment(ec)) {
386 if (error(ec)) return;
388 if (error(si->getName(Name))) return;
390 if (error(si->getAddress(Address))) return;
392 if (error(si->getSize(Size))) return;
393 bool Text, Data, BSS;
394 if (error(si->isText(Text))) return;
395 if (error(si->isData(Data))) return;
396 if (error(si->isBSS(BSS))) return;
397 std::string Type = (std::string(Text ? "TEXT " : "") +
398 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
399 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
400 i, Name.str().c_str(), Size, Address, Type.c_str());
405 static void PrintSectionContents(const ObjectFile *o) {
407 for (section_iterator si = o->begin_sections(),
408 se = o->end_sections();
409 si != se; si.increment(ec)) {
410 if (error(ec)) return;
414 if (error(si->getName(Name))) continue;
415 if (error(si->getContents(Contents))) continue;
416 if (error(si->getAddress(BaseAddr))) continue;
418 outs() << "Contents of section " << Name << ":\n";
420 // Dump out the content as hex and printable ascii characters.
421 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
422 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
424 for (std::size_t i = 0; i < 16; ++i) {
425 if (i != 0 && i % 4 == 0)
428 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
429 << hexdigit(Contents[addr + i] & 0xF, true);
435 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
436 if (std::isprint(Contents[addr + i] & 0xFF))
437 outs() << Contents[addr + i];
446 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
447 const coff_file_header *header;
448 if (error(coff->getHeader(header))) return;
450 const coff_symbol *symbol = 0;
451 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
453 // Figure out which type of aux this is.
454 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
455 && symbol->Value == 0) { // Section definition.
456 const coff_aux_section_definition *asd;
457 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
460 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
461 , unsigned(asd->Length)
462 , unsigned(asd->NumberOfRelocations)
463 , unsigned(asd->NumberOfLinenumbers)
464 , unsigned(asd->CheckSum))
465 << format("assoc %d comdat %d\n"
466 , unsigned(asd->Number)
467 , unsigned(asd->Selection));
469 outs() << "AUX Unknown\n";
473 if (error(coff->getSymbol(i, symbol))) return;
474 if (error(coff->getSymbolName(symbol, name))) return;
475 outs() << "[" << format("%2d", i) << "]"
476 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
477 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
478 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
479 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
480 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
481 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
483 aux_count = symbol->NumberOfAuxSymbols;
488 static void PrintSymbolTable(const ObjectFile *o) {
489 outs() << "SYMBOL TABLE:\n";
491 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
492 PrintCOFFSymbolTable(coff);
495 for (symbol_iterator si = o->begin_symbols(),
496 se = o->end_symbols(); si != se; si.increment(ec)) {
497 if (error(ec)) return;
500 SymbolRef::Type Type;
503 section_iterator Section = o->end_sections();
504 if (error(si->getName(Name))) continue;
505 if (error(si->getAddress(Address))) continue;
506 if (error(si->getFlags(Flags))) continue;
507 if (error(si->getType(Type))) continue;
508 if (error(si->getSize(Size))) continue;
509 if (error(si->getSection(Section))) continue;
511 bool Global = Flags & SymbolRef::SF_Global;
512 bool Weak = Flags & SymbolRef::SF_Weak;
513 bool Absolute = Flags & SymbolRef::SF_Absolute;
515 if (Address == UnknownAddressOrSize)
517 if (Size == UnknownAddressOrSize)
520 if (Type != SymbolRef::ST_Unknown)
521 GlobLoc = Global ? 'g' : 'l';
522 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
525 if (Type == SymbolRef::ST_File)
527 else if (Type == SymbolRef::ST_Function)
530 outs() << format("%08" PRIx64, Address) << " "
531 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
532 << (Weak ? 'w' : ' ') // Weak?
533 << ' ' // Constructor. Not supported yet.
534 << ' ' // Warning. Not supported yet.
535 << ' ' // Indirect reference to another symbol.
536 << Debug // Debugging (d) or dynamic (D) symbol.
537 << FileFunc // Name of function (F), file (f) or object (O).
541 else if (Section == o->end_sections())
544 StringRef SectionName;
545 if (error(Section->getName(SectionName)))
547 outs() << SectionName;
550 << format("%08" PRIx64 " ", Size)
557 static void DumpObject(const ObjectFile *o) {
559 outs() << o->getFileName()
560 << ":\tfile format " << o->getFileFormatName() << "\n\n";
563 DisassembleObject(o, Relocations);
564 if (Relocations && !Disassemble)
567 PrintSectionHeaders(o);
569 PrintSectionContents(o);
574 /// @brief Dump each object file in \a a;
575 static void DumpArchive(const Archive *a) {
576 for (Archive::child_iterator i = a->begin_children(),
577 e = a->end_children(); i != e; ++i) {
578 OwningPtr<Binary> child;
579 if (error_code ec = i->getAsBinary(child)) {
580 // Ignore non-object files.
581 if (ec != object_error::invalid_file_type)
582 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
586 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
589 errs() << ToolName << ": '" << a->getFileName() << "': "
590 << "Unrecognized file type.\n";
594 /// @brief Open file and figure out how to dump it.
595 static void DumpInput(StringRef file) {
596 // If file isn't stdin, check that it exists.
597 if (file != "-" && !sys::fs::exists(file)) {
598 errs() << ToolName << ": '" << file << "': " << "No such file\n";
602 if (MachO && Disassemble) {
603 DisassembleInputMachO(file);
607 // Attempt to open the binary.
608 OwningPtr<Binary> binary;
609 if (error_code ec = createBinary(file, binary)) {
610 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
614 if (Archive *a = dyn_cast<Archive>(binary.get())) {
616 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
619 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
623 int main(int argc, char **argv) {
624 // Print a stack trace if we signal out.
625 sys::PrintStackTraceOnErrorSignal();
626 PrettyStackTraceProgram X(argc, argv);
627 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
629 // Initialize targets and assembly printers/parsers.
630 llvm::InitializeAllTargetInfos();
631 llvm::InitializeAllTargetMCs();
632 llvm::InitializeAllAsmParsers();
633 llvm::InitializeAllDisassemblers();
635 // Register the target printer for --version.
636 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
638 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
639 TripleName = Triple::normalize(TripleName);
643 // Defaults to a.out if no filenames specified.
644 if (InputFilenames.size() == 0)
645 InputFilenames.push_back("a.out");
652 cl::PrintHelpMessage();
656 std::for_each(InputFilenames.begin(), InputFilenames.end(),