OSDN Git Service

Rename createAsmInfo to createMCAsmInfo and move registration code to MCTargetDesc...
[android-x86/external-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/Object/ObjectFile.h"
17 #include "llvm/ADT/OwningPtr.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCDisassembler.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/MemoryObject.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/Signals.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/system_error.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSelect.h"
37 #include <algorithm>
38 #include <cstring>
39 using namespace llvm;
40 using namespace object;
41
42 namespace {
43   cl::list<std::string>
44   InputFilenames(cl::Positional, cl::desc("<input object files>"),
45                  cl::ZeroOrMore);
46
47   cl::opt<bool>
48   Disassemble("disassemble",
49     cl::desc("Display assembler mnemonics for the machine instructions"));
50   cl::alias
51   Disassembled("d", cl::desc("Alias for --disassemble"),
52                cl::aliasopt(Disassemble));
53
54   cl::opt<std::string>
55   TripleName("triple", cl::desc("Target triple to disassemble for, "
56                                 "see -version for available targets"));
57
58   cl::opt<std::string>
59   ArchName("arch", cl::desc("Target arch to disassemble for, "
60                             "see -version for available targets"));
61
62   StringRef ToolName;
63
64   bool error(error_code ec) {
65     if (!ec) return false;
66
67     outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
68     outs().flush();
69     return true;
70   }
71 }
72
73 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
74   // Figure out the target triple.
75   llvm::Triple TT("unknown-unknown-unknown");
76   if (TripleName.empty()) {
77     if (Obj)
78       TT.setArch(Triple::ArchType(Obj->getArch()));
79   } else
80     TT.setTriple(Triple::normalize(TripleName));
81
82   if (!ArchName.empty())
83     TT.setArchName(ArchName);
84
85   TripleName = TT.str();
86
87   // Get the target specific parser.
88   std::string Error;
89   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
90   if (TheTarget)
91     return TheTarget;
92
93   errs() << ToolName << ": error: unable to get target for '" << TripleName
94          << "', see --version and --triple.\n";
95   return 0;
96 }
97
98 namespace {
99 class StringRefMemoryObject : public MemoryObject {
100 private:
101   StringRef Bytes;
102 public:
103   StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
104
105   uint64_t getBase() const { return 0; }
106   uint64_t getExtent() const { return Bytes.size(); }
107
108   int readByte(uint64_t Addr, uint8_t *Byte) const {
109     if (Addr > getExtent())
110       return -1;
111     *Byte = Bytes[Addr];
112     return 0;
113   }
114 };
115 }
116
117 static void DumpBytes(StringRef bytes) {
118   static char hex_rep[] = "0123456789abcdef";
119   // FIXME: The real way to do this is to figure out the longest instruction
120   //        and align to that size before printing. I'll fix this when I get
121   //        around to outputting relocations.
122   // 15 is the longest x86 instruction
123   // 3 is for the hex rep of a byte + a space.
124   // 1 is for the null terminator.
125   enum { OutputSize = (15 * 3) + 1 };
126   char output[OutputSize];
127
128   assert(bytes.size() <= 15
129     && "DumpBytes only supports instructions of up to 15 bytes");
130   memset(output, ' ', sizeof(output));
131   unsigned index = 0;
132   for (StringRef::iterator i = bytes.begin(),
133                            e = bytes.end(); i != e; ++i) {
134     output[index] = hex_rep[(*i & 0xF0) >> 4];
135     output[index + 1] = hex_rep[*i & 0xF];
136     index += 3;
137   }
138
139   output[sizeof(output) - 1] = 0;
140   outs() << output;
141 }
142
143 static void DisassembleInput(const StringRef &Filename) {
144   OwningPtr<MemoryBuffer> Buff;
145
146   if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
147     errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
148     return;
149   }
150
151   OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
152
153   const Target *TheTarget = GetTarget(Obj.get());
154   if (!TheTarget) {
155     // GetTarget prints out stuff.
156     return;
157   }
158
159   outs() << '\n';
160   outs() << Filename
161          << ":\tfile format " << Obj->getFileFormatName() << "\n\n\n";
162
163   error_code ec;
164   for (ObjectFile::section_iterator i = Obj->begin_sections(),
165                                     e = Obj->end_sections();
166                                     i != e; i.increment(ec)) {
167     if (error(ec)) break;
168     bool text;
169     if (error(i->isText(text))) break;
170     if (!text) continue;
171
172     StringRef name;
173     if (error(i->getName(name))) break;
174     outs() << "Disassembly of section " << name << ":\n\n";
175
176     // Set up disassembler.
177     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
178
179     if (!AsmInfo) {
180       errs() << "error: no assembly info for target " << TripleName << "\n";
181       return;
182     }
183
184     OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
185     if (!DisAsm) {
186       errs() << "error: no disassembler for target " << TripleName << "\n";
187       return;
188     }
189
190     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
191     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
192                                   AsmPrinterVariant, *AsmInfo));
193     if (!IP) {
194       errs() << "error: no instruction printer for target " << TripleName << '\n';
195       return;
196     }
197
198     StringRef Bytes;
199     if (error(i->getContents(Bytes))) break;
200     StringRefMemoryObject memoryObject(Bytes);
201     uint64_t Size;
202     uint64_t Index;
203
204     for (Index = 0; Index < Bytes.size(); Index += Size) {
205       MCInst Inst;
206
207 #     ifndef NDEBUG
208       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
209 #     else
210       raw_ostream &DebugOut = nulls();
211 #     endif
212
213       if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, DebugOut)) {
214         uint64_t addr;
215         if (error(i->getAddress(addr))) break;
216         outs() << format("%8x:\t", addr + Index);
217         DumpBytes(StringRef(Bytes.data() + Index, Size));
218         IP->printInst(&Inst, outs());
219         outs() << "\n";
220       } else {
221         errs() << ToolName << ": warning: invalid instruction encoding\n";
222         if (Size == 0)
223           Size = 1; // skip illegible bytes
224       }
225     }
226   }
227 }
228
229 int main(int argc, char **argv) {
230   // Print a stack trace if we signal out.
231   sys::PrintStackTraceOnErrorSignal();
232   PrettyStackTraceProgram X(argc, argv);
233   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
234
235   // Initialize targets and assembly printers/parsers.
236   llvm::InitializeAllTargetInfos();
237   // FIXME: We shouldn't need to initialize the Target(Machine)s.
238   llvm::InitializeAllTargets();
239   llvm::InitializeAllMCAsmInfos();
240   llvm::InitializeAllAsmPrinters();
241   llvm::InitializeAllAsmParsers();
242   llvm::InitializeAllDisassemblers();
243
244   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
245   TripleName = Triple::normalize(TripleName);
246
247   ToolName = argv[0];
248
249   // Defaults to a.out if no filenames specified.
250   if (InputFilenames.size() == 0)
251     InputFilenames.push_back("a.out");
252
253   // -d is the only flag that is currently implemented, so just print help if
254   // it is not set.
255   if (!Disassemble) {
256     cl::PrintHelpMessage();
257     return 2;
258   }
259
260   std::for_each(InputFilenames.begin(), InputFilenames.end(),
261                 DisassembleInput);
262
263   return 0;
264 }