Combine all MC initialization routines into one. e.g. InitializeX86MCAsmInfo,
[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 "MCFunction.h"
17 #include "llvm/Object/ObjectFile.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCDisassembler.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstPrinter.h"
25 #include "llvm/MC/MCInstrDesc.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/MemoryObject.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetRegistry.h"
40 #include "llvm/Target/TargetSelect.h"
41 #include <algorithm>
42 #include <cstring>
43 using namespace llvm;
44 using namespace object;
45
46 namespace {
47   cl::list<std::string>
48   InputFilenames(cl::Positional, cl::desc("<input object files>"),
49                  cl::ZeroOrMore);
50
51   cl::opt<bool>
52   Disassemble("disassemble",
53     cl::desc("Display assembler mnemonics for the machine instructions"));
54   cl::alias
55   Disassembled("d", cl::desc("Alias for --disassemble"),
56                cl::aliasopt(Disassemble));
57
58   cl::opt<bool>
59   CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
60                       "write it to a graphviz file"));
61
62   cl::opt<std::string>
63   TripleName("triple", cl::desc("Target triple to disassemble for, "
64                                 "see -version for available targets"));
65
66   cl::opt<std::string>
67   ArchName("arch", cl::desc("Target arch to disassemble for, "
68                             "see -version for available targets"));
69
70   StringRef ToolName;
71
72   bool error(error_code ec) {
73     if (!ec) return false;
74
75     outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
76     outs().flush();
77     return true;
78   }
79 }
80
81 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
82   // Figure out the target triple.
83   llvm::Triple TT("unknown-unknown-unknown");
84   if (TripleName.empty()) {
85     if (Obj)
86       TT.setArch(Triple::ArchType(Obj->getArch()));
87   } else
88     TT.setTriple(Triple::normalize(TripleName));
89
90   if (!ArchName.empty())
91     TT.setArchName(ArchName);
92
93   TripleName = TT.str();
94
95   // Get the target specific parser.
96   std::string Error;
97   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
98   if (TheTarget)
99     return TheTarget;
100
101   errs() << ToolName << ": error: unable to get target for '" << TripleName
102          << "', see --version and --triple.\n";
103   return 0;
104 }
105
106 namespace {
107 class StringRefMemoryObject : public MemoryObject {
108 private:
109   StringRef Bytes;
110 public:
111   StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
112
113   uint64_t getBase() const { return 0; }
114   uint64_t getExtent() const { return Bytes.size(); }
115
116   int readByte(uint64_t Addr, uint8_t *Byte) const {
117     if (Addr >= getExtent())
118       return -1;
119     *Byte = Bytes[Addr];
120     return 0;
121   }
122 };
123 }
124
125 static void DumpBytes(StringRef bytes) {
126   static char hex_rep[] = "0123456789abcdef";
127   // FIXME: The real way to do this is to figure out the longest instruction
128   //        and align to that size before printing. I'll fix this when I get
129   //        around to outputting relocations.
130   // 15 is the longest x86 instruction
131   // 3 is for the hex rep of a byte + a space.
132   // 1 is for the null terminator.
133   enum { OutputSize = (15 * 3) + 1 };
134   char output[OutputSize];
135
136   assert(bytes.size() <= 15
137     && "DumpBytes only supports instructions of up to 15 bytes");
138   memset(output, ' ', sizeof(output));
139   unsigned index = 0;
140   for (StringRef::iterator i = bytes.begin(),
141                            e = bytes.end(); i != e; ++i) {
142     output[index] = hex_rep[(*i & 0xF0) >> 4];
143     output[index + 1] = hex_rep[*i & 0xF];
144     index += 3;
145   }
146
147   output[sizeof(output) - 1] = 0;
148   outs() << output;
149 }
150
151 static void DisassembleInput(const StringRef &Filename) {
152   OwningPtr<MemoryBuffer> Buff;
153
154   if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
155     errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
156     return;
157   }
158
159   OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
160
161   const Target *TheTarget = GetTarget(Obj.get());
162   if (!TheTarget) {
163     // GetTarget prints out stuff.
164     return;
165   }
166   const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
167
168   outs() << '\n';
169   outs() << Filename
170          << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
171
172   error_code ec;
173   for (ObjectFile::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     // Make a list of all the symbols in this section.
182     std::vector<std::pair<uint64_t, StringRef> > Symbols;
183     for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
184                                      se = Obj->end_symbols();
185                                      si != se; si.increment(ec)) {
186       bool contains;
187       if (!error(i->containsSymbol(*si, contains)) && contains) {
188         uint64_t Address;
189         if (error(si->getAddress(Address))) break;
190         StringRef Name;
191         if (error(si->getName(Name))) break;
192         Symbols.push_back(std::make_pair(Address, Name));
193       }
194     }
195
196     // Sort the symbols by address, just in case they didn't come in that way.
197     array_pod_sort(Symbols.begin(), Symbols.end());
198
199     StringRef name;
200     if (error(i->getName(name))) break;
201     outs() << "Disassembly of section " << name << ':';
202
203     // If the section has no symbols just insert a dummy one and disassemble
204     // the whole section.
205     if (Symbols.empty())
206       Symbols.push_back(std::make_pair(0, name));
207
208     // Set up disassembler.
209     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
210
211     if (!AsmInfo) {
212       errs() << "error: no assembly info for target " << TripleName << "\n";
213       return;
214     }
215
216     OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
217     if (!DisAsm) {
218       errs() << "error: no disassembler for target " << TripleName << "\n";
219       return;
220     }
221
222     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
223     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
224                                   AsmPrinterVariant, *AsmInfo));
225     if (!IP) {
226       errs() << "error: no instruction printer for target " << TripleName << '\n';
227       return;
228     }
229
230     StringRef Bytes;
231     if (error(i->getContents(Bytes))) break;
232     StringRefMemoryObject memoryObject(Bytes);
233     uint64_t Size;
234     uint64_t Index;
235     uint64_t SectSize;
236     if (error(i->getSize(SectSize))) break;
237
238     // Disassemble symbol by symbol.
239     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
240       uint64_t Start = Symbols[si].first;
241       uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
242       outs() << '\n' << Symbols[si].second << ":\n";
243
244 #ifndef NDEBUG
245         raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
246 #else
247         raw_ostream &DebugOut = nulls();
248 #endif
249
250       for (Index = Start; Index < End; Index += Size) {
251         MCInst Inst;
252         if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, DebugOut)) {
253           uint64_t addr;
254           if (error(i->getAddress(addr))) break;
255           outs() << format("%8x:\t", addr + Index);
256           DumpBytes(StringRef(Bytes.data() + Index, Size));
257           IP->printInst(&Inst, outs());
258           outs() << "\n";
259         } else {
260           errs() << ToolName << ": warning: invalid instruction encoding\n";
261           if (Size == 0)
262             Size = 1; // skip illegible bytes
263         }
264       }
265
266       if (CFG) {
267         MCFunction f =
268           MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
269                                            memoryObject, Start, End, InstrInfo,
270                                            DebugOut);
271
272         // Start a new dot file.
273         std::string Error;
274         raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
275         if (!Error.empty()) {
276           errs() << ToolName << ": warning: " << Error << '\n';
277           continue;
278         }
279
280         Out << "digraph " << f.getName() << " {\n";
281         Out << "graph [ rankdir = \"LR\" ];\n";
282         for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
283           Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
284           // Print instructions.
285           for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
286                ++ii) {
287             IP->printInst(&i->second.getInsts()[ii].Inst, Out);
288             Out << '|';
289           }
290           Out << "<o>\" shape=\"record\" ];\n";
291
292           // Add edges.
293           for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
294               se = i->second.succ_end(); si != se; ++si)
295             Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
296         }
297         Out << "}\n";
298       }
299     }
300   }
301 }
302
303 int main(int argc, char **argv) {
304   // Print a stack trace if we signal out.
305   sys::PrintStackTraceOnErrorSignal();
306   PrettyStackTraceProgram X(argc, argv);
307   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
308
309   // Initialize targets and assembly printers/parsers.
310   llvm::InitializeAllTargetInfos();
311   // FIXME: We shouldn't need to initialize the Target(Machine)s.
312   llvm::InitializeAllTargets();
313   llvm::InitializeAllTargetMCs();
314   llvm::InitializeAllAsmPrinters();
315   llvm::InitializeAllAsmParsers();
316   llvm::InitializeAllDisassemblers();
317
318   // Register the target printer for --version.
319   // FIXME: Remove when we stop initializing the Target(Machine)s above.
320   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
321
322   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
323   TripleName = Triple::normalize(TripleName);
324
325   ToolName = argv[0];
326
327   // Defaults to a.out if no filenames specified.
328   if (InputFilenames.size() == 0)
329     InputFilenames.push_back("a.out");
330
331   // -d is the only flag that is currently implemented, so just print help if
332   // it is not set.
333   if (!Disassemble) {
334     cl::PrintHelpMessage();
335     return 2;
336   }
337
338   std::for_each(InputFilenames.begin(), InputFilenames.end(),
339                 DisassembleInput);
340
341   return 0;
342 }