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/MCRegisterInfo.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/GraphWriter.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/MemoryObject.h"
41 #include "llvm/Support/PrettyStackTrace.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Support/system_error.h"
51 using namespace object;
53 static cl::list<std::string>
54 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
57 Disassemble("disassemble",
58 cl::desc("Display assembler mnemonics for the machine instructions"));
60 Disassembled("d", cl::desc("Alias for --disassemble"),
61 cl::aliasopt(Disassemble));
64 Relocations("r", cl::desc("Display the relocation entries in the file"));
67 SectionContents("s", cl::desc("Display the content of each section"));
70 SymbolTable("t", cl::desc("Display the symbol table"));
73 MachO("macho", cl::desc("Use MachO specific object file parser"));
75 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
78 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
79 "see -version for available targets"));
82 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
83 "see -version for available targets"));
86 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
87 "for each section."));
89 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
90 cl::aliasopt(SectionHeaders));
92 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
93 cl::aliasopt(SectionHeaders));
95 static StringRef ToolName;
97 static bool error(error_code ec) {
98 if (!ec) return false;
100 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
105 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
106 // Figure out the target triple.
107 llvm::Triple TT("unknown-unknown-unknown");
108 if (TripleName.empty()) {
110 TT.setArch(Triple::ArchType(Obj->getArch()));
112 TT.setTriple(Triple::normalize(TripleName));
114 if (!ArchName.empty())
115 TT.setArchName(ArchName);
117 TripleName = TT.str();
119 // Get the target specific parser.
121 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
125 errs() << ToolName << ": error: unable to get target for '" << TripleName
126 << "', see --version and --triple.\n";
130 void llvm::StringRefMemoryObject::anchor() { }
132 void llvm::DumpBytes(StringRef bytes) {
133 static const char hex_rep[] = "0123456789abcdef";
134 // FIXME: The real way to do this is to figure out the longest instruction
135 // and align to that size before printing. I'll fix this when I get
136 // around to outputting relocations.
137 // 15 is the longest x86 instruction
138 // 3 is for the hex rep of a byte + a space.
139 // 1 is for the null terminator.
140 enum { OutputSize = (15 * 3) + 1 };
141 char output[OutputSize];
143 assert(bytes.size() <= 15
144 && "DumpBytes only supports instructions of up to 15 bytes");
145 memset(output, ' ', sizeof(output));
147 for (StringRef::iterator i = bytes.begin(),
148 e = bytes.end(); i != e; ++i) {
149 output[index] = hex_rep[(*i & 0xF0) >> 4];
150 output[index + 1] = hex_rep[*i & 0xF];
154 output[sizeof(output) - 1] = 0;
158 static bool RelocAddressLess(RelocationRef a, RelocationRef b) {
159 uint64_t a_addr, b_addr;
160 if (error(a.getAddress(a_addr))) return false;
161 if (error(b.getAddress(b_addr))) return false;
162 return a_addr < b_addr;
165 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
166 const Target *TheTarget = GetTarget(Obj);
168 // GetTarget prints out stuff.
173 for (section_iterator i = Obj->begin_sections(),
174 e = Obj->end_sections();
175 i != e; i.increment(ec)) {
176 if (error(ec)) break;
178 if (error(i->isText(text))) break;
181 uint64_t SectionAddr;
182 if (error(i->getAddress(SectionAddr))) break;
184 // Make a list of all the symbols in this section.
185 std::vector<std::pair<uint64_t, StringRef> > Symbols;
186 for (symbol_iterator si = Obj->begin_symbols(),
187 se = Obj->end_symbols();
188 si != se; si.increment(ec)) {
190 if (!error(i->containsSymbol(*si, contains)) && contains) {
192 if (error(si->getAddress(Address))) break;
193 Address -= SectionAddr;
196 if (error(si->getName(Name))) break;
197 Symbols.push_back(std::make_pair(Address, Name));
201 // Sort the symbols by address, just in case they didn't come in that way.
202 array_pod_sort(Symbols.begin(), Symbols.end());
204 // Make a list of all the relocations for this section.
205 std::vector<RelocationRef> Rels;
207 for (relocation_iterator ri = i->begin_relocations(),
208 re = i->end_relocations();
209 ri != re; ri.increment(ec)) {
210 if (error(ec)) break;
215 // Sort relocations by address.
216 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
219 if (error(i->getName(name))) break;
220 outs() << "Disassembly of section " << name << ':';
222 // If the section has no symbols just insert a dummy one and disassemble
223 // the whole section.
225 Symbols.push_back(std::make_pair(0, name));
227 // Set up disassembler.
228 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
231 errs() << "error: no assembly info for target " << TripleName << "\n";
235 OwningPtr<const MCSubtargetInfo> STI(
236 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
239 errs() << "error: no subtarget info for target " << TripleName << "\n";
243 OwningPtr<const MCDisassembler> DisAsm(
244 TheTarget->createMCDisassembler(*STI));
246 errs() << "error: no disassembler for target " << TripleName << "\n";
250 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
252 errs() << "error: no register info for target " << TripleName << "\n";
256 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
257 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
258 AsmPrinterVariant, *AsmInfo, *MRI, *STI));
260 errs() << "error: no instruction printer for target " << TripleName
266 if (error(i->getContents(Bytes))) break;
267 StringRefMemoryObject memoryObject(Bytes);
271 if (error(i->getSize(SectSize))) break;
273 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
274 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
275 // Disassemble symbol by symbol.
276 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
277 uint64_t Start = Symbols[si].first;
279 // The end is either the size of the section or the beginning of the next
283 // Make sure this symbol takes up space.
284 else if (Symbols[si + 1].first != Start)
285 End = Symbols[si + 1].first - 1;
287 // This symbol has the same address as the next symbol. Skip it.
290 outs() << '\n' << Symbols[si].second << ":\n";
293 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
295 raw_ostream &DebugOut = nulls();
298 for (Index = Start; Index < End; Index += Size) {
301 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
302 DebugOut, nulls())) {
303 outs() << format("%8" PRIx64 ":\t", SectionAddr + Index);
304 DumpBytes(StringRef(Bytes.data() + Index, Size));
305 IP->printInst(&Inst, outs(), "");
308 errs() << ToolName << ": warning: invalid instruction encoding\n";
310 Size = 1; // skip illegible bytes
313 // Print relocation for instruction.
314 while (rel_cur != rel_end) {
317 SmallString<16> name;
320 // If this relocation is hidden, skip it.
321 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
322 if (hidden) goto skip_print_rel;
324 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
325 // Stop when rel_cur's address is past the current instruction.
326 if (addr >= Index + Size) break;
327 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
328 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
330 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
331 << "\t" << val << "\n";
341 static void PrintRelocations(const ObjectFile *o) {
343 for (section_iterator si = o->begin_sections(), se = o->end_sections();
344 si != se; si.increment(ec)){
345 if (error(ec)) return;
346 if (si->begin_relocations() == si->end_relocations())
349 if (error(si->getName(secname))) continue;
350 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
351 for (relocation_iterator ri = si->begin_relocations(),
352 re = si->end_relocations();
353 ri != re; ri.increment(ec)) {
354 if (error(ec)) return;
358 SmallString<32> relocname;
359 SmallString<32> valuestr;
360 if (error(ri->getHidden(hidden))) continue;
361 if (hidden) continue;
362 if (error(ri->getTypeName(relocname))) continue;
363 if (error(ri->getAddress(address))) continue;
364 if (error(ri->getValueString(valuestr))) continue;
365 outs() << address << " " << relocname << " " << valuestr << "\n";
371 static void PrintSectionHeaders(const ObjectFile *o) {
372 outs() << "Sections:\n"
373 "Idx Name Size Address Type\n";
376 for (section_iterator si = o->begin_sections(), se = o->end_sections();
377 si != se; si.increment(ec)) {
378 if (error(ec)) return;
380 if (error(si->getName(Name))) return;
382 if (error(si->getAddress(Address))) return;
384 if (error(si->getSize(Size))) return;
385 bool Text, Data, BSS;
386 if (error(si->isText(Text))) return;
387 if (error(si->isData(Data))) return;
388 if (error(si->isBSS(BSS))) return;
389 std::string Type = (std::string(Text ? "TEXT " : "") +
390 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
391 outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
392 i, Name.str().c_str(), Size, Address, Type.c_str());
397 static void PrintSectionContents(const ObjectFile *o) {
399 for (section_iterator si = o->begin_sections(),
400 se = o->end_sections();
401 si != se; si.increment(ec)) {
402 if (error(ec)) return;
406 if (error(si->getName(Name))) continue;
407 if (error(si->getContents(Contents))) continue;
408 if (error(si->getAddress(BaseAddr))) continue;
410 outs() << "Contents of section " << Name << ":\n";
412 // Dump out the content as hex and printable ascii characters.
413 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
414 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
416 for (std::size_t i = 0; i < 16; ++i) {
417 if (i != 0 && i % 4 == 0)
420 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
421 << hexdigit(Contents[addr + i] & 0xF, true);
427 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
428 if (std::isprint(Contents[addr + i] & 0xFF))
429 outs() << Contents[addr + i];
438 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
439 const coff_file_header *header;
440 if (error(coff->getHeader(header))) return;
442 const coff_symbol *symbol = 0;
443 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
445 // Figure out which type of aux this is.
446 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
447 && symbol->Value == 0) { // Section definition.
448 const coff_aux_section_definition *asd;
449 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
452 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
453 , unsigned(asd->Length)
454 , unsigned(asd->NumberOfRelocations)
455 , unsigned(asd->NumberOfLinenumbers)
456 , unsigned(asd->CheckSum))
457 << format("assoc %d comdat %d\n"
458 , unsigned(asd->Number)
459 , unsigned(asd->Selection));
461 outs() << "AUX Unknown\n";
465 if (error(coff->getSymbol(i, symbol))) return;
466 if (error(coff->getSymbolName(symbol, name))) return;
467 outs() << "[" << format("%2d", i) << "]"
468 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
469 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
470 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
471 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
472 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
473 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
475 aux_count = symbol->NumberOfAuxSymbols;
480 static void PrintSymbolTable(const ObjectFile *o) {
481 outs() << "SYMBOL TABLE:\n";
483 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
484 PrintCOFFSymbolTable(coff);
487 for (symbol_iterator si = o->begin_symbols(),
488 se = o->end_symbols(); si != se; si.increment(ec)) {
489 if (error(ec)) return;
492 SymbolRef::Type Type;
495 section_iterator Section = o->end_sections();
496 if (error(si->getName(Name))) continue;
497 if (error(si->getAddress(Address))) continue;
498 if (error(si->getFlags(Flags))) continue;
499 if (error(si->getType(Type))) continue;
500 if (error(si->getSize(Size))) continue;
501 if (error(si->getSection(Section))) continue;
503 bool Global = Flags & SymbolRef::SF_Global;
504 bool Weak = Flags & SymbolRef::SF_Weak;
505 bool Absolute = Flags & SymbolRef::SF_Absolute;
507 if (Address == UnknownAddressOrSize)
509 if (Size == UnknownAddressOrSize)
512 if (Type != SymbolRef::ST_Unknown)
513 GlobLoc = Global ? 'g' : 'l';
514 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
517 if (Type == SymbolRef::ST_File)
519 else if (Type == SymbolRef::ST_Function)
522 outs() << format("%08" PRIx64, Address) << " "
523 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
524 << (Weak ? 'w' : ' ') // Weak?
525 << ' ' // Constructor. Not supported yet.
526 << ' ' // Warning. Not supported yet.
527 << ' ' // Indirect reference to another symbol.
528 << Debug // Debugging (d) or dynamic (D) symbol.
529 << FileFunc // Name of function (F), file (f) or object (O).
533 else if (Section == o->end_sections())
536 StringRef SectionName;
537 if (error(Section->getName(SectionName)))
539 outs() << SectionName;
542 << format("%08" PRIx64 " ", Size)
549 static void DumpObject(const ObjectFile *o) {
551 outs() << o->getFileName()
552 << ":\tfile format " << o->getFileFormatName() << "\n\n";
555 DisassembleObject(o, Relocations);
556 if (Relocations && !Disassemble)
559 PrintSectionHeaders(o);
561 PrintSectionContents(o);
566 /// @brief Dump each object file in \a a;
567 static void DumpArchive(const Archive *a) {
568 for (Archive::child_iterator i = a->begin_children(),
569 e = a->end_children(); i != e; ++i) {
570 OwningPtr<Binary> child;
571 if (error_code ec = i->getAsBinary(child)) {
572 // Ignore non-object files.
573 if (ec != object_error::invalid_file_type)
574 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
578 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
581 errs() << ToolName << ": '" << a->getFileName() << "': "
582 << "Unrecognized file type.\n";
586 /// @brief Open file and figure out how to dump it.
587 static void DumpInput(StringRef file) {
588 // If file isn't stdin, check that it exists.
589 if (file != "-" && !sys::fs::exists(file)) {
590 errs() << ToolName << ": '" << file << "': " << "No such file\n";
594 if (MachO && Disassemble) {
595 DisassembleInputMachO(file);
599 // Attempt to open the binary.
600 OwningPtr<Binary> binary;
601 if (error_code ec = createBinary(file, binary)) {
602 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
606 if (Archive *a = dyn_cast<Archive>(binary.get())) {
608 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
611 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
615 int main(int argc, char **argv) {
616 // Print a stack trace if we signal out.
617 sys::PrintStackTraceOnErrorSignal();
618 PrettyStackTraceProgram X(argc, argv);
619 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
621 // Initialize targets and assembly printers/parsers.
622 llvm::InitializeAllTargetInfos();
623 llvm::InitializeAllTargetMCs();
624 llvm::InitializeAllAsmParsers();
625 llvm::InitializeAllDisassemblers();
627 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
628 TripleName = Triple::normalize(TripleName);
632 // Defaults to a.out if no filenames specified.
633 if (InputFilenames.size() == 0)
634 InputFilenames.push_back("a.out");
641 cl::PrintHelpMessage();
645 std::for_each(InputFilenames.begin(), InputFilenames.end(),