Object: make the following changes into SymbolRef
[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/MCInstrAnalysis.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/MemoryObject.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/system_error.h"
44 #include <algorithm>
45 #include <cstring>
46 using namespace llvm;
47 using namespace object;
48
49 namespace {
50   cl::list<std::string>
51   InputFilenames(cl::Positional, cl::desc("<input object files>"),
52                  cl::ZeroOrMore);
53
54   cl::opt<bool>
55   Disassemble("disassemble",
56     cl::desc("Display assembler mnemonics for the machine instructions"));
57   cl::alias
58   Disassembled("d", cl::desc("Alias for --disassemble"),
59                cl::aliasopt(Disassemble));
60
61   cl::opt<bool>
62   CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
63                       "write it to a graphviz file"));
64
65   cl::opt<std::string>
66   TripleName("triple", cl::desc("Target triple to disassemble for, "
67                                 "see -version for available targets"));
68
69   cl::opt<std::string>
70   ArchName("arch", cl::desc("Target arch to disassemble for, "
71                             "see -version for available targets"));
72
73   StringRef ToolName;
74
75   bool error(error_code ec) {
76     if (!ec) return false;
77
78     outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
79     outs().flush();
80     return true;
81   }
82 }
83
84 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
85   // Figure out the target triple.
86   llvm::Triple TT("unknown-unknown-unknown");
87   if (TripleName.empty()) {
88     if (Obj)
89       TT.setArch(Triple::ArchType(Obj->getArch()));
90   } else
91     TT.setTriple(Triple::normalize(TripleName));
92
93   if (!ArchName.empty())
94     TT.setArchName(ArchName);
95
96   TripleName = TT.str();
97
98   // Get the target specific parser.
99   std::string Error;
100   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
101   if (TheTarget)
102     return TheTarget;
103
104   errs() << ToolName << ": error: unable to get target for '" << TripleName
105          << "', see --version and --triple.\n";
106   return 0;
107 }
108
109 namespace {
110 class StringRefMemoryObject : public MemoryObject {
111 private:
112   StringRef Bytes;
113 public:
114   StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
115
116   uint64_t getBase() const { return 0; }
117   uint64_t getExtent() const { return Bytes.size(); }
118
119   int readByte(uint64_t Addr, uint8_t *Byte) const {
120     if (Addr >= getExtent())
121       return -1;
122     *Byte = Bytes[Addr];
123     return 0;
124   }
125 };
126 }
127
128 static void DumpBytes(StringRef bytes) {
129   static char hex_rep[] = "0123456789abcdef";
130   // FIXME: The real way to do this is to figure out the longest instruction
131   //        and align to that size before printing. I'll fix this when I get
132   //        around to outputting relocations.
133   // 15 is the longest x86 instruction
134   // 3 is for the hex rep of a byte + a space.
135   // 1 is for the null terminator.
136   enum { OutputSize = (15 * 3) + 1 };
137   char output[OutputSize];
138
139   assert(bytes.size() <= 15
140     && "DumpBytes only supports instructions of up to 15 bytes");
141   memset(output, ' ', sizeof(output));
142   unsigned index = 0;
143   for (StringRef::iterator i = bytes.begin(),
144                            e = bytes.end(); i != e; ++i) {
145     output[index] = hex_rep[(*i & 0xF0) >> 4];
146     output[index + 1] = hex_rep[*i & 0xF];
147     index += 3;
148   }
149
150   output[sizeof(output) - 1] = 0;
151   outs() << output;
152 }
153
154 static void DisassembleInput(const StringRef &Filename) {
155   OwningPtr<MemoryBuffer> Buff;
156
157   if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
158     errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
159     return;
160   }
161
162   OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
163
164   const Target *TheTarget = GetTarget(Obj.get());
165   if (!TheTarget) {
166     // GetTarget prints out stuff.
167     return;
168   }
169   const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
170   OwningPtr<MCInstrAnalysis>
171     InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
172
173   outs() << '\n';
174   outs() << Filename
175          << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
176
177   error_code ec;
178   for (ObjectFile::section_iterator i = Obj->begin_sections(),
179                                     e = Obj->end_sections();
180                                     i != e; i.increment(ec)) {
181     if (error(ec)) break;
182     bool text;
183     if (error(i->isText(text))) break;
184     if (!text) continue;
185
186     // Make a list of all the symbols in this section.
187     std::vector<std::pair<uint64_t, StringRef> > Symbols;
188     for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
189                                      se = Obj->end_symbols();
190                                      si != se; si.increment(ec)) {
191       bool contains;
192       if (!error(i->containsSymbol(*si, contains)) && contains) {
193         uint64_t Address;
194         if (error(si->getOffset(Address))) break;
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     StringRef name;
205     if (error(i->getName(name))) break;
206     outs() << "Disassembly of section " << name << ':';
207
208     // If the section has no symbols just insert a dummy one and disassemble
209     // the whole section.
210     if (Symbols.empty())
211       Symbols.push_back(std::make_pair(0, name));
212
213     // Set up disassembler.
214     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
215
216     if (!AsmInfo) {
217       errs() << "error: no assembly info for target " << TripleName << "\n";
218       return;
219     }
220
221     OwningPtr<const MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
222
223     if (!STI) {
224       errs() << "error: no subtarget info for target " << TripleName << "\n";
225       return;
226     }
227
228     OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
229     if (!DisAsm) {
230       errs() << "error: no disassembler for target " << TripleName << "\n";
231       return;
232     }
233
234     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
235     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
236                                 AsmPrinterVariant, *AsmInfo, *STI));
237     if (!IP) {
238       errs() << "error: no instruction printer for target " << TripleName << '\n';
239       return;
240     }
241
242     StringRef Bytes;
243     if (error(i->getContents(Bytes))) break;
244     StringRefMemoryObject memoryObject(Bytes);
245     uint64_t Size;
246     uint64_t Index;
247     uint64_t SectSize;
248     if (error(i->getSize(SectSize))) break;
249
250     // Disassemble symbol by symbol.
251     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
252       uint64_t Start = Symbols[si].first;
253       uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
254       outs() << '\n' << Symbols[si].second << ":\n";
255
256 #ifndef NDEBUG
257         raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
258 #else
259         raw_ostream &DebugOut = nulls();
260 #endif
261
262       if (!CFG) {
263         for (Index = Start; Index < End; Index += Size) {
264           MCInst Inst;
265           if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
266                                      DebugOut)) {
267             uint64_t addr;
268             if (error(i->getAddress(addr))) break;
269             outs() << format("%8x:\t", addr + Index);
270             DumpBytes(StringRef(Bytes.data() + Index, Size));
271             IP->printInst(&Inst, outs());
272             outs() << "\n";
273           } else {
274             errs() << ToolName << ": warning: invalid instruction encoding\n";
275             if (Size == 0)
276               Size = 1; // skip illegible bytes
277           }
278         }
279
280       } else {
281         // Create CFG and use it for disassembly.
282         MCFunction f =
283           MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
284                                            memoryObject, Start, End,
285                                            InstrAnalysis.get(), DebugOut);
286
287         for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
288           bool hasPreds = false;
289           // Only print blocks that have predecessors.
290           // FIXME: Slow.
291           for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
292               ++pi)
293             if (pi->second.contains(&fi->second)) {
294               hasPreds = true;
295               break;
296             }
297
298           // Data block.
299           if (!hasPreds && fi != f.begin()) {
300             uint64_t End = llvm::next(fi) == fe ? SectSize :
301                                                   llvm::next(fi)->first;
302             uint64_t addr;
303             if (error(i->getAddress(addr))) break;
304             outs() << "# " << End-fi->first << " bytes of data:\n";
305             for (unsigned pos = fi->first; pos != End; ++pos) {
306               outs() << format("%8x:\t", addr + pos);
307               DumpBytes(StringRef(Bytes.data() + pos, 1));
308               outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
309             }
310             continue;
311           }
312
313           if (fi->second.contains(&fi->second))
314             outs() << "# Loop begin:\n";
315
316           for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
317                ++ii) {
318             uint64_t addr;
319             if (error(i->getAddress(addr))) break;
320             const MCDecodedInst &Inst = fi->second.getInsts()[ii];
321             outs() << format("%8x:\t", addr + Inst.Address);
322             DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
323             // Simple loops.
324             if (fi->second.contains(&fi->second))
325               outs() << '\t';
326             IP->printInst(&Inst.Inst, outs());
327             outs() << '\n';
328           }
329         }
330
331         // Start a new dot file.
332         std::string Error;
333         raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
334         if (!Error.empty()) {
335           errs() << ToolName << ": warning: " << Error << '\n';
336           continue;
337         }
338
339         Out << "digraph " << f.getName() << " {\n";
340         Out << "graph [ rankdir = \"LR\" ];\n";
341         for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
342           bool hasPreds = false;
343           // Only print blocks that have predecessors.
344           // FIXME: Slow.
345           for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
346                ++pi)
347             if (pi->second.contains(&i->second)) {
348               hasPreds = true;
349               break;
350             }
351
352           if (!hasPreds && i != f.begin())
353             continue;
354
355           Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
356           // Print instructions.
357           for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
358                ++ii) {
359             // Escape special chars and print the instruction in mnemonic form.
360             std::string Str;
361             raw_string_ostream OS(Str);
362             IP->printInst(&i->second.getInsts()[ii].Inst, OS);
363             Out << DOT::EscapeString(OS.str()) << '|';
364           }
365           Out << "<o>\" shape=\"record\" ];\n";
366
367           // Add edges.
368           for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
369               se = i->second.succ_end(); si != se; ++si)
370             Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
371         }
372         Out << "}\n";
373       }
374     }
375   }
376 }
377
378 int main(int argc, char **argv) {
379   // Print a stack trace if we signal out.
380   sys::PrintStackTraceOnErrorSignal();
381   PrettyStackTraceProgram X(argc, argv);
382   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
383
384   // Initialize targets and assembly printers/parsers.
385   llvm::InitializeAllTargetInfos();
386   llvm::InitializeAllTargetMCs();
387   llvm::InitializeAllAsmParsers();
388   llvm::InitializeAllDisassemblers();
389
390   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
391   TripleName = Triple::normalize(TripleName);
392
393   ToolName = argv[0];
394
395   // Defaults to a.out if no filenames specified.
396   if (InputFilenames.size() == 0)
397     InputFilenames.push_back("a.out");
398
399   // -d is the only flag that is currently implemented, so just print help if
400   // it is not set.
401   if (!Disassemble) {
402     cl::PrintHelpMessage();
403     return 2;
404   }
405
406   std::for_each(InputFilenames.begin(), InputFilenames.end(),
407                 DisassembleInput);
408
409   return 0;
410 }