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/ObjectFile.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 cl::list<std::string>
100 cl::desc("Target specific attributes"),
101 cl::value_desc("a1,+a2,-a3,..."));
104 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
105 "do not print the instruction bytes."));
107 static StringRef ToolName;
109 static bool error(error_code ec) {
110 if (!ec) return false;
112 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
117 static const Target *getTarget(const ObjectFile *Obj = NULL) {
118 // Figure out the target triple.
119 llvm::Triple TheTriple("unknown-unknown-unknown");
120 if (TripleName.empty()) {
122 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
124 TheTriple.setTriple(Triple::normalize(TripleName));
126 // Get the target specific parser.
128 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
131 errs() << ToolName << ": " << Error;
135 // Update the triple name and return the found target.
136 TripleName = TheTriple.getTriple();
140 void llvm::StringRefMemoryObject::anchor() { }
142 void llvm::DumpBytes(StringRef bytes) {
143 static const char hex_rep[] = "0123456789abcdef";
144 // FIXME: The real way to do this is to figure out the longest instruction
145 // and align to that size before printing. I'll fix this when I get
146 // around to outputting relocations.
147 // 15 is the longest x86 instruction
148 // 3 is for the hex rep of a byte + a space.
149 // 1 is for the null terminator.
150 enum { OutputSize = (15 * 3) + 1 };
151 char output[OutputSize];
153 assert(bytes.size() <= 15
154 && "DumpBytes only supports instructions of up to 15 bytes");
155 memset(output, ' ', sizeof(output));
157 for (StringRef::iterator i = bytes.begin(),
158 e = bytes.end(); i != e; ++i) {
159 output[index] = hex_rep[(*i & 0xF0) >> 4];
160 output[index + 1] = hex_rep[*i & 0xF];
164 output[sizeof(output) - 1] = 0;
168 static bool RelocAddressLess(RelocationRef a, RelocationRef b) {
169 uint64_t a_addr, b_addr;
170 if (error(a.getAddress(a_addr))) return false;
171 if (error(b.getAddress(b_addr))) return false;
172 return a_addr < b_addr;
175 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
176 const Target *TheTarget = getTarget(Obj);
177 // getTarget() will have already issued a diagnostic if necessary, so
178 // just bail here if it failed.
182 // Package up features to be passed to target/subtarget
183 std::string FeaturesStr;
185 SubtargetFeatures Features;
186 for (unsigned i = 0; i != MAttrs.size(); ++i)
187 Features.AddFeature(MAttrs[i]);
188 FeaturesStr = Features.getString();
192 for (section_iterator i = Obj->begin_sections(),
193 e = Obj->end_sections();
194 i != e; i.increment(ec)) {
195 if (error(ec)) break;
197 if (error(i->isText(text))) break;
200 uint64_t SectionAddr;
201 if (error(i->getAddress(SectionAddr))) break;
203 // Make a list of all the symbols in this section.
204 std::vector<std::pair<uint64_t, StringRef> > Symbols;
205 for (symbol_iterator si = Obj->begin_symbols(),
206 se = Obj->end_symbols();
207 si != se; si.increment(ec)) {
209 if (!error(i->containsSymbol(*si, contains)) && contains) {
211 if (error(si->getAddress(Address))) break;
212 Address -= SectionAddr;
215 if (error(si->getName(Name))) break;
216 Symbols.push_back(std::make_pair(Address, Name));
220 // Sort the symbols by address, just in case they didn't come in that way.
221 array_pod_sort(Symbols.begin(), Symbols.end());
223 // Make a list of all the relocations for this section.
224 std::vector<RelocationRef> Rels;
226 for (relocation_iterator ri = i->begin_relocations(),
227 re = i->end_relocations();
228 ri != re; ri.increment(ec)) {
229 if (error(ec)) break;
234 // Sort relocations by address.
235 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
238 if (error(i->getName(name))) break;
239 outs() << "Disassembly of section " << name << ':';
241 // If the section has no symbols just insert a dummy one and disassemble
242 // the whole section.
244 Symbols.push_back(std::make_pair(0, name));
246 // Set up disassembler.
247 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
250 errs() << "error: no assembly info for target " << TripleName << "\n";
254 OwningPtr<const MCSubtargetInfo> STI(
255 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
258 errs() << "error: no subtarget info for target " << TripleName << "\n";
262 OwningPtr<const MCDisassembler> DisAsm(
263 TheTarget->createMCDisassembler(*STI));
265 errs() << "error: no disassembler for target " << TripleName << "\n";
269 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
271 errs() << "error: no register info for target " << TripleName << "\n";
275 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
277 errs() << "error: no instruction info for target " << TripleName << "\n";
281 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
282 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
283 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
285 errs() << "error: no instruction printer for target " << TripleName
291 if (error(i->getContents(Bytes))) break;
292 StringRefMemoryObject memoryObject(Bytes);
296 if (error(i->getSize(SectSize))) break;
298 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
299 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
300 // Disassemble symbol by symbol.
301 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
302 uint64_t Start = Symbols[si].first;
304 // The end is either the size of the section or the beginning of the next
308 // Make sure this symbol takes up space.
309 else if (Symbols[si + 1].first != Start)
310 End = Symbols[si + 1].first - 1;
312 // This symbol has the same address as the next symbol. Skip it.
315 outs() << '\n' << Symbols[si].second << ":\n";
318 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
320 raw_ostream &DebugOut = nulls();
323 for (Index = Start; Index < End; Index += Size) {
326 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
327 DebugOut, nulls())) {
328 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
329 if (!NoShowRawInsn) {
331 DumpBytes(StringRef(Bytes.data() + Index, Size));
333 IP->printInst(&Inst, outs(), "");
336 errs() << ToolName << ": warning: invalid instruction encoding\n";
338 Size = 1; // skip illegible bytes
341 // Print relocation for instruction.
342 while (rel_cur != rel_end) {
345 SmallString<16> name;
348 // If this relocation is hidden, skip it.
349 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
350 if (hidden) goto skip_print_rel;
352 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
353 // Stop when rel_cur's address is past the current instruction.
354 if (addr >= Index + Size) break;
355 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
356 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
358 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
359 << "\t" << val << "\n";
369 static void PrintRelocations(const ObjectFile *o) {
371 for (section_iterator si = o->begin_sections(), se = o->end_sections();
372 si != se; si.increment(ec)){
373 if (error(ec)) return;
374 if (si->begin_relocations() == si->end_relocations())
377 if (error(si->getName(secname))) continue;
378 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
379 for (relocation_iterator ri = si->begin_relocations(),
380 re = si->end_relocations();
381 ri != re; ri.increment(ec)) {
382 if (error(ec)) return;
386 SmallString<32> relocname;
387 SmallString<32> valuestr;
388 if (error(ri->getHidden(hidden))) continue;
389 if (hidden) continue;
390 if (error(ri->getTypeName(relocname))) continue;
391 if (error(ri->getAddress(address))) continue;
392 if (error(ri->getValueString(valuestr))) continue;
393 outs() << address << " " << relocname << " " << valuestr << "\n";
399 static void PrintSectionHeaders(const ObjectFile *o) {
400 outs() << "Sections:\n"
401 "Idx Name Size Address Type\n";
404 for (section_iterator si = o->begin_sections(), se = o->end_sections();
405 si != se; si.increment(ec)) {
406 if (error(ec)) return;
408 if (error(si->getName(Name))) return;
410 if (error(si->getAddress(Address))) return;
412 if (error(si->getSize(Size))) return;
413 bool Text, Data, BSS;
414 if (error(si->isText(Text))) return;
415 if (error(si->isData(Data))) return;
416 if (error(si->isBSS(BSS))) return;
417 std::string Type = (std::string(Text ? "TEXT " : "") +
418 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
419 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
420 i, Name.str().c_str(), Size, Address, Type.c_str());
425 static void PrintSectionContents(const ObjectFile *o) {
427 for (section_iterator si = o->begin_sections(),
428 se = o->end_sections();
429 si != se; si.increment(ec)) {
430 if (error(ec)) return;
434 if (error(si->getName(Name))) continue;
435 if (error(si->getContents(Contents))) continue;
436 if (error(si->getAddress(BaseAddr))) continue;
438 outs() << "Contents of section " << Name << ":\n";
440 // Dump out the content as hex and printable ascii characters.
441 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
442 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
444 for (std::size_t i = 0; i < 16; ++i) {
445 if (i != 0 && i % 4 == 0)
448 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
449 << hexdigit(Contents[addr + i] & 0xF, true);
455 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
456 if (std::isprint(Contents[addr + i] & 0xFF))
457 outs() << Contents[addr + i];
466 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
467 const coff_file_header *header;
468 if (error(coff->getHeader(header))) return;
470 const coff_symbol *symbol = 0;
471 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
473 // Figure out which type of aux this is.
474 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
475 && symbol->Value == 0) { // Section definition.
476 const coff_aux_section_definition *asd;
477 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
480 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
481 , unsigned(asd->Length)
482 , unsigned(asd->NumberOfRelocations)
483 , unsigned(asd->NumberOfLinenumbers)
484 , unsigned(asd->CheckSum))
485 << format("assoc %d comdat %d\n"
486 , unsigned(asd->Number)
487 , unsigned(asd->Selection));
489 outs() << "AUX Unknown\n";
492 if (error(coff->getSymbol(i, symbol))) return;
493 if (error(coff->getSymbolName(symbol, name))) return;
494 outs() << "[" << format("%2d", i) << "]"
495 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
496 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
497 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
498 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
499 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
500 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
502 aux_count = symbol->NumberOfAuxSymbols;
507 static void PrintSymbolTable(const ObjectFile *o) {
508 outs() << "SYMBOL TABLE:\n";
510 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
511 PrintCOFFSymbolTable(coff);
514 for (symbol_iterator si = o->begin_symbols(),
515 se = o->end_symbols(); si != se; si.increment(ec)) {
516 if (error(ec)) return;
519 SymbolRef::Type Type;
522 section_iterator Section = o->end_sections();
523 if (error(si->getName(Name))) continue;
524 if (error(si->getAddress(Address))) continue;
525 if (error(si->getFlags(Flags))) continue;
526 if (error(si->getType(Type))) continue;
527 if (error(si->getSize(Size))) continue;
528 if (error(si->getSection(Section))) continue;
530 bool Global = Flags & SymbolRef::SF_Global;
531 bool Weak = Flags & SymbolRef::SF_Weak;
532 bool Absolute = Flags & SymbolRef::SF_Absolute;
534 if (Address == UnknownAddressOrSize)
536 if (Size == UnknownAddressOrSize)
539 if (Type != SymbolRef::ST_Unknown)
540 GlobLoc = Global ? 'g' : 'l';
541 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
544 if (Type == SymbolRef::ST_File)
546 else if (Type == SymbolRef::ST_Function)
549 outs() << format("%08" PRIx64, Address) << " "
550 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
551 << (Weak ? 'w' : ' ') // Weak?
552 << ' ' // Constructor. Not supported yet.
553 << ' ' // Warning. Not supported yet.
554 << ' ' // Indirect reference to another symbol.
555 << Debug // Debugging (d) or dynamic (D) symbol.
556 << FileFunc // Name of function (F), file (f) or object (O).
560 else if (Section == o->end_sections())
563 StringRef SectionName;
564 if (error(Section->getName(SectionName)))
566 outs() << SectionName;
569 << format("%08" PRIx64 " ", Size)
576 static void DumpObject(const ObjectFile *o) {
578 outs() << o->getFileName()
579 << ":\tfile format " << o->getFileFormatName() << "\n\n";
582 DisassembleObject(o, Relocations);
583 if (Relocations && !Disassemble)
586 PrintSectionHeaders(o);
588 PrintSectionContents(o);
593 /// @brief Dump each object file in \a a;
594 static void DumpArchive(const Archive *a) {
595 for (Archive::child_iterator i = a->begin_children(),
596 e = a->end_children(); i != e; ++i) {
597 OwningPtr<Binary> child;
598 if (error_code ec = i->getAsBinary(child)) {
599 // Ignore non-object files.
600 if (ec != object_error::invalid_file_type)
601 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
605 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
608 errs() << ToolName << ": '" << a->getFileName() << "': "
609 << "Unrecognized file type.\n";
613 /// @brief Open file and figure out how to dump it.
614 static void DumpInput(StringRef file) {
615 // If file isn't stdin, check that it exists.
616 if (file != "-" && !sys::fs::exists(file)) {
617 errs() << ToolName << ": '" << file << "': " << "No such file\n";
621 if (MachO && Disassemble) {
622 DisassembleInputMachO(file);
626 // Attempt to open the binary.
627 OwningPtr<Binary> binary;
628 if (error_code ec = createBinary(file, binary)) {
629 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
633 if (Archive *a = dyn_cast<Archive>(binary.get()))
635 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
638 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
641 int main(int argc, char **argv) {
642 // Print a stack trace if we signal out.
643 sys::PrintStackTraceOnErrorSignal();
644 PrettyStackTraceProgram X(argc, argv);
645 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
647 // Initialize targets and assembly printers/parsers.
648 llvm::InitializeAllTargetInfos();
649 llvm::InitializeAllTargetMCs();
650 llvm::InitializeAllAsmParsers();
651 llvm::InitializeAllDisassemblers();
653 // Register the target printer for --version.
654 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
656 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
657 TripleName = Triple::normalize(TripleName);
661 // Defaults to a.out if no filenames specified.
662 if (InputFilenames.size() == 0)
663 InputFilenames.push_back("a.out");
670 cl::PrintHelpMessage();
674 std::for_each(InputFilenames.begin(), InputFilenames.end(),