Make MCRegisterInfo available to the the MCInstPrinter.
[oota-llvm.git] / tools / llvm-objdump / llvm-objdump.cpp
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // flags.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
48 #include <algorithm>
49 #include <cstring>
50 using namespace llvm;
51 using namespace object;
52
53 static cl::list<std::string>
54 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
55
56 static cl::opt<bool>
57 Disassemble("disassemble",
58   cl::desc("Display assembler mnemonics for the machine instructions"));
59 static cl::alias
60 Disassembled("d", cl::desc("Alias for --disassemble"),
61              cl::aliasopt(Disassemble));
62
63 static cl::opt<bool>
64 Relocations("r", cl::desc("Display the relocation entries in the file"));
65
66 static cl::opt<bool>
67 SectionContents("s", cl::desc("Display the content of each section"));
68
69 static cl::opt<bool>
70 SymbolTable("t", cl::desc("Display the symbol table"));
71
72 static cl::opt<bool>
73 MachO("macho", cl::desc("Use MachO specific object file parser"));
74 static cl::alias
75 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
76
77 cl::opt<std::string>
78 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
79                                     "see -version for available targets"));
80
81 cl::opt<std::string>
82 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
83                                 "see -version for available targets"));
84
85 static cl::opt<bool>
86 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
87                                            "for each section."));
88 static cl::alias
89 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
90                     cl::aliasopt(SectionHeaders));
91 static cl::alias
92 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
93                       cl::aliasopt(SectionHeaders));
94
95 static StringRef ToolName;
96
97 static bool error(error_code ec) {
98   if (!ec) return false;
99
100   outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
101   outs().flush();
102   return true;
103 }
104
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()) {
109     if (Obj)
110       TT.setArch(Triple::ArchType(Obj->getArch()));
111   } else
112     TT.setTriple(Triple::normalize(TripleName));
113
114   if (!ArchName.empty())
115     TT.setArchName(ArchName);
116
117   TripleName = TT.str();
118
119   // Get the target specific parser.
120   std::string Error;
121   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
122   if (TheTarget)
123     return TheTarget;
124
125   errs() << ToolName << ": error: unable to get target for '" << TripleName
126          << "', see --version and --triple.\n";
127   return 0;
128 }
129
130 void llvm::StringRefMemoryObject::anchor() { }
131
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];
142
143   assert(bytes.size() <= 15
144     && "DumpBytes only supports instructions of up to 15 bytes");
145   memset(output, ' ', sizeof(output));
146   unsigned index = 0;
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];
151     index += 3;
152   }
153
154   output[sizeof(output) - 1] = 0;
155   outs() << output;
156 }
157
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;
163 }
164
165 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
166   const Target *TheTarget = GetTarget(Obj);
167   if (!TheTarget) {
168     // GetTarget prints out stuff.
169     return;
170   }
171
172   error_code ec;
173   for (section_iterator i = Obj->begin_sections(),
174                         e = Obj->end_sections();
175                         i != e; i.increment(ec)) {
176     if (error(ec)) break;
177     bool text;
178     if (error(i->isText(text))) break;
179     if (!text) continue;
180
181     uint64_t SectionAddr;
182     if (error(i->getAddress(SectionAddr))) break;
183
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)) {
189       bool contains;
190       if (!error(i->containsSymbol(*si, contains)) && contains) {
191         uint64_t Address;
192         if (error(si->getAddress(Address))) break;
193         Address -= SectionAddr;
194
195         StringRef Name;
196         if (error(si->getName(Name))) break;
197         Symbols.push_back(std::make_pair(Address, Name));
198       }
199     }
200
201     // Sort the symbols by address, just in case they didn't come in that way.
202     array_pod_sort(Symbols.begin(), Symbols.end());
203
204     // Make a list of all the relocations for this section.
205     std::vector<RelocationRef> Rels;
206     if (InlineRelocs) {
207       for (relocation_iterator ri = i->begin_relocations(),
208                                re = i->end_relocations();
209                               ri != re; ri.increment(ec)) {
210         if (error(ec)) break;
211         Rels.push_back(*ri);
212       }
213     }
214
215     // Sort relocations by address.
216     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
217
218     StringRef name;
219     if (error(i->getName(name))) break;
220     outs() << "Disassembly of section " << name << ':';
221
222     // If the section has no symbols just insert a dummy one and disassemble
223     // the whole section.
224     if (Symbols.empty())
225       Symbols.push_back(std::make_pair(0, name));
226
227     // Set up disassembler.
228     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
229
230     if (!AsmInfo) {
231       errs() << "error: no assembly info for target " << TripleName << "\n";
232       return;
233     }
234
235     OwningPtr<const MCSubtargetInfo> STI(
236       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
237
238     if (!STI) {
239       errs() << "error: no subtarget info for target " << TripleName << "\n";
240       return;
241     }
242
243     OwningPtr<const MCDisassembler> DisAsm(
244       TheTarget->createMCDisassembler(*STI));
245     if (!DisAsm) {
246       errs() << "error: no disassembler for target " << TripleName << "\n";
247       return;
248     }
249
250     OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
251     if (!MRI) {
252       errs() << "error: no register info for target " << TripleName << "\n";
253       return;
254     }
255
256     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
257     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
258                                 AsmPrinterVariant, *AsmInfo, *MRI, *STI));
259     if (!IP) {
260       errs() << "error: no instruction printer for target " << TripleName
261              << '\n';
262       return;
263     }
264
265     StringRef Bytes;
266     if (error(i->getContents(Bytes))) break;
267     StringRefMemoryObject memoryObject(Bytes);
268     uint64_t Size;
269     uint64_t Index;
270     uint64_t SectSize;
271     if (error(i->getSize(SectSize))) break;
272
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;
278       uint64_t End;
279       // The end is either the size of the section or the beginning of the next
280       // symbol.
281       if (si == se - 1)
282         End = SectSize;
283       // Make sure this symbol takes up space.
284       else if (Symbols[si + 1].first != Start)
285         End = Symbols[si + 1].first - 1;
286       else
287         // This symbol has the same address as the next symbol. Skip it.
288         continue;
289
290       outs() << '\n' << Symbols[si].second << ":\n";
291
292 #ifndef NDEBUG
293         raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
294 #else
295         raw_ostream &DebugOut = nulls();
296 #endif
297
298       for (Index = Start; Index < End; Index += Size) {
299         MCInst Inst;
300
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(), "");
306           outs() << "\n";
307         } else {
308           errs() << ToolName << ": warning: invalid instruction encoding\n";
309           if (Size == 0)
310             Size = 1; // skip illegible bytes
311         }
312
313         // Print relocation for instruction.
314         while (rel_cur != rel_end) {
315           bool hidden = false;
316           uint64_t addr;
317           SmallString<16> name;
318           SmallString<32> val;
319
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;
323
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;
329
330           outs() << format("\t\t\t%8"PRIx64": ", SectionAddr + addr) << name << "\t"
331                  << val << "\n";
332
333         skip_print_rel:
334           ++rel_cur;
335         }
336       }
337     }
338   }
339 }
340
341 static void PrintRelocations(const ObjectFile *o) {
342   error_code ec;
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())
347       continue;
348     StringRef secname;
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;
355
356       bool hidden;
357       uint64_t address;
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";
366     }
367     outs() << "\n";
368   }
369 }
370
371 static void PrintSectionHeaders(const ObjectFile *o) {
372   outs() << "Sections:\n"
373             "Idx Name          Size      Address          Type\n";
374   error_code ec;
375   unsigned i = 0;
376   for (section_iterator si = o->begin_sections(), se = o->end_sections();
377                                                   si != se; si.increment(ec)) {
378     if (error(ec)) return;
379     StringRef Name;
380     if (error(si->getName(Name))) return;
381     uint64_t Address;
382     if (error(si->getAddress(Address))) return;
383     uint64_t Size;
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", i, Name.str().c_str(), Size,
392                      Address, Type.c_str());
393     ++i;
394   }
395 }
396
397 static void PrintSectionContents(const ObjectFile *o) {
398   error_code ec;
399   for (section_iterator si = o->begin_sections(),
400                         se = o->end_sections();
401                         si != se; si.increment(ec)) {
402     if (error(ec)) return;
403     StringRef Name;
404     StringRef Contents;
405     uint64_t BaseAddr;
406     if (error(si->getName(Name))) continue;
407     if (error(si->getContents(Contents))) continue;
408     if (error(si->getAddress(BaseAddr))) continue;
409
410     outs() << "Contents of section " << Name << ":\n";
411
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);
415       // Dump line of hex.
416       for (std::size_t i = 0; i < 16; ++i) {
417         if (i != 0 && i % 4 == 0)
418           outs() << ' ';
419         if (addr + i < end)
420           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
421                  << hexdigit(Contents[addr + i] & 0xF, true);
422         else
423           outs() << "  ";
424       }
425       // Print ascii.
426       outs() << "  ";
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];
430         else
431           outs() << ".";
432       }
433       outs() << "\n";
434     }
435   }
436 }
437
438 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
439   const coff_file_header *header;
440   if (error(coff->getHeader(header))) return;
441   int aux_count = 0;
442   const coff_symbol *symbol = 0;
443   for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
444     if (aux_count--) {
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)))
450           return;
451         outs() << "AUX "
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));
460       } else {
461         outs() << "AUX Unknown\n";
462       }
463     } else {
464       StringRef name;
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)) << " "
474              << name << "\n";
475       aux_count = symbol->NumberOfAuxSymbols;
476     }
477   }
478 }
479
480 static void PrintSymbolTable(const ObjectFile *o) {
481   outs() << "SYMBOL TABLE:\n";
482
483   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
484     PrintCOFFSymbolTable(coff);
485   else {
486     error_code ec;
487     for (symbol_iterator si = o->begin_symbols(),
488                          se = o->end_symbols(); si != se; si.increment(ec)) {
489       if (error(ec)) return;
490       StringRef Name;
491       uint64_t Address;
492       SymbolRef::Type Type;
493       uint64_t Size;
494       uint32_t Flags;
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;
502
503       bool Global = Flags & SymbolRef::SF_Global;
504       bool Weak = Flags & SymbolRef::SF_Weak;
505       bool Absolute = Flags & SymbolRef::SF_Absolute;
506
507       if (Address == UnknownAddressOrSize)
508         Address = 0;
509       if (Size == UnknownAddressOrSize)
510         Size = 0;
511       char GlobLoc = ' ';
512       if (Type != SymbolRef::ST_Unknown)
513         GlobLoc = Global ? 'g' : 'l';
514       char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
515                    ? 'd' : ' ';
516       char FileFunc = ' ';
517       if (Type == SymbolRef::ST_File)
518         FileFunc = 'f';
519       else if (Type == SymbolRef::ST_Function)
520         FileFunc = 'F';
521
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).
530              << ' ';
531       if (Absolute)
532         outs() << "*ABS*";
533       else if (Section == o->end_sections())
534         outs() << "*UND*";
535       else {
536         StringRef SectionName;
537         if (error(Section->getName(SectionName)))
538           SectionName = "";
539         outs() << SectionName;
540       }
541       outs() << '\t'
542              << format("%08"PRIx64" ", Size)
543              << Name
544              << '\n';
545     }
546   }
547 }
548
549 static void DumpObject(const ObjectFile *o) {
550   outs() << '\n';
551   outs() << o->getFileName()
552          << ":\tfile format " << o->getFileFormatName() << "\n\n";
553
554   if (Disassemble)
555     DisassembleObject(o, Relocations);
556   if (Relocations && !Disassemble)
557     PrintRelocations(o);
558   if (SectionHeaders)
559     PrintSectionHeaders(o);
560   if (SectionContents)
561     PrintSectionContents(o);
562   if (SymbolTable)
563     PrintSymbolTable(o);
564 }
565
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()
575                << ".\n";
576       continue;
577     }
578     if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
579       DumpObject(o);
580     else
581       errs() << ToolName << ": '" << a->getFileName() << "': "
582               << "Unrecognized file type.\n";
583   }
584 }
585
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";
591     return;
592   }
593
594   if (MachO && Disassemble) {
595     DisassembleInputMachO(file);
596     return;
597   }
598
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";
603     return;
604   }
605
606   if (Archive *a = dyn_cast<Archive>(binary.get())) {
607     DumpArchive(a);
608   } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
609     DumpObject(o);
610   } else {
611     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
612   }
613 }
614
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.
620
621   // Initialize targets and assembly printers/parsers.
622   llvm::InitializeAllTargetInfos();
623   llvm::InitializeAllTargetMCs();
624   llvm::InitializeAllAsmParsers();
625   llvm::InitializeAllDisassemblers();
626
627   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
628   TripleName = Triple::normalize(TripleName);
629
630   ToolName = argv[0];
631
632   // Defaults to a.out if no filenames specified.
633   if (InputFilenames.size() == 0)
634     InputFilenames.push_back("a.out");
635
636   if (!Disassemble
637       && !Relocations
638       && !SectionHeaders
639       && !SectionContents
640       && !SymbolTable) {
641     cl::PrintHelpMessage();
642     return 2;
643   }
644
645   std::for_each(InputFilenames.begin(), InputFilenames.end(),
646                 DumpInput);
647
648   return 0;
649 }