Move TargetRegistry and TargetSelect from Target to Support where they belong.
[oota-llvm.git] / tools / llvm-mc / Disassembler.cpp
1 //===- Disassembler.cpp - Disassembler for hex strings --------------------===//
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 class implements the disassembler of strings of bytes written in
11 // hexadecimal, from standard input or from a file.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Disassembler.h"
16 #include "../../lib/MC/MCDisassembler/EDDisassembler.h"
17 #include "../../lib/MC/MCDisassembler/EDInst.h"
18 #include "../../lib/MC/MCDisassembler/EDOperand.h"
19 #include "../../lib/MC/MCDisassembler/EDToken.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCDisassembler.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/MemoryObject.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33
34 typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
35
36 namespace {
37 class VectorMemoryObject : public MemoryObject {
38 private:
39   const ByteArrayTy &Bytes;
40 public:
41   VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
42
43   uint64_t getBase() const { return 0; }
44   uint64_t getExtent() const { return Bytes.size(); }
45
46   int readByte(uint64_t Addr, uint8_t *Byte) const {
47     if (Addr >= getExtent())
48       return -1;
49     *Byte = Bytes[Addr].first;
50     return 0;
51   }
52 };
53 }
54
55 static bool PrintInsts(const MCDisassembler &DisAsm,
56                        MCInstPrinter &Printer, const ByteArrayTy &Bytes,
57                        SourceMgr &SM, raw_ostream &Out) {
58   // Wrap the vector in a MemoryObject.
59   VectorMemoryObject memoryObject(Bytes);
60
61   // Disassemble it to strings.
62   uint64_t Size;
63   uint64_t Index;
64
65   for (Index = 0; Index < Bytes.size(); Index += Size) {
66     MCInst Inst;
67
68     MCDisassembler::DecodeStatus S;
69     S = DisAsm.getInstruction(Inst, Size, memoryObject, Index,
70                               /*REMOVE*/ nulls());
71     switch (S) {
72     case MCDisassembler::Fail:
73       SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
74                       "invalid instruction encoding", "warning");
75       if (Size == 0)
76         Size = 1; // skip illegible bytes
77       break;
78
79     case MCDisassembler::SoftFail:
80       SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
81                       "potentially undefined instruction encoding", "warning");
82       // Fall through
83
84     case MCDisassembler::Success:
85       Printer.printInst(&Inst, Out);
86       Out << "\n";
87       break;
88     }
89   }
90
91   return false;
92 }
93
94 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
95                                 StringRef &Str,
96                                 SourceMgr &SM) {
97   while (!Str.empty()) {
98     // Strip horizontal whitespace.
99     if (size_t Pos = Str.find_first_not_of(" \t\r")) {
100       Str = Str.substr(Pos);
101       continue;
102     }
103
104     // If this is the end of a line or start of a comment, remove the rest of
105     // the line.
106     if (Str[0] == '\n' || Str[0] == '#') {
107       // Strip to the end of line if we already processed any bytes on this
108       // line.  This strips the comment and/or the \n.
109       if (Str[0] == '\n') {
110         Str = Str.substr(1);
111       } else {
112         Str = Str.substr(Str.find_first_of('\n'));
113         if (!Str.empty())
114           Str = Str.substr(1);
115       }
116       continue;
117     }
118
119     // Get the current token.
120     size_t Next = Str.find_first_of(" \t\n\r#");
121     StringRef Value = Str.substr(0, Next);
122
123     // Convert to a byte and add to the byte vector.
124     unsigned ByteVal;
125     if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
126       // If we have an error, print it and skip to the end of line.
127       SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
128                       "invalid input token", "error");
129       Str = Str.substr(Str.find('\n'));
130       ByteArray.clear();
131       continue;
132     }
133
134     ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
135     Str = Str.substr(Next);
136   }
137
138   return false;
139 }
140
141 int Disassembler::disassemble(const Target &T,
142                               const std::string &Triple,
143                               MemoryBuffer &Buffer,
144                               raw_ostream &Out) {
145   // Set up disassembler.
146   OwningPtr<const MCAsmInfo> AsmInfo(T.createMCAsmInfo(Triple));
147
148   if (!AsmInfo) {
149     errs() << "error: no assembly info for target " << Triple << "\n";
150     return -1;
151   }
152
153   OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler());
154   if (!DisAsm) {
155     errs() << "error: no disassembler for target " << Triple << "\n";
156     return -1;
157   }
158
159   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
160   OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
161                                                     *AsmInfo));
162   if (!IP) {
163     errs() << "error: no instruction printer for target " << Triple << '\n';
164     return -1;
165   }
166
167   bool ErrorOccurred = false;
168
169   SourceMgr SM;
170   SM.AddNewSourceBuffer(&Buffer, SMLoc());
171
172   // Convert the input to a vector for disassembly.
173   ByteArrayTy ByteArray;
174   StringRef Str = Buffer.getBuffer();
175
176   ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
177
178   if (!ByteArray.empty())
179     ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
180
181   return ErrorOccurred;
182 }
183
184 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
185   ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
186
187   if (A >= ByteArray.size())
188     return -1;
189
190   *B = ByteArray[A].first;
191
192   return 0;
193 }
194
195 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
196   EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
197   raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
198
199   if (const char *regName = disassembler.nameWithRegisterID(R))
200     Out << "[" << regName << "/" << R << "]";
201
202   if (disassembler.registerIsStackPointer(R))
203     Out << "(sp)";
204   if (disassembler.registerIsProgramCounter(R))
205     Out << "(pc)";
206
207   *V = 0;
208   return 0;
209 }
210
211 int Disassembler::disassembleEnhanced(const std::string &TS,
212                                       MemoryBuffer &Buffer,
213                                       raw_ostream &Out) {
214   ByteArrayTy ByteArray;
215   StringRef Str = Buffer.getBuffer();
216   SourceMgr SM;
217
218   SM.AddNewSourceBuffer(&Buffer, SMLoc());
219
220   if (ByteArrayFromString(ByteArray, Str, SM)) {
221     return -1;
222   }
223
224   Triple T(TS);
225   EDDisassembler::AssemblySyntax AS;
226
227   switch (T.getArch()) {
228   default:
229     errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
230     return -1;
231   case Triple::arm:
232   case Triple::thumb:
233     AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
234     break;
235   case Triple::x86:
236   case Triple::x86_64:
237     AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
238     break;
239   }
240
241   EDDisassembler::initialize();
242   OwningPtr<EDDisassembler>
243     disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
244
245   if (disassembler == 0) {
246     errs() << "error: couldn't get disassembler for " << TS << '\n';
247     return -1;
248   }
249
250   while (ByteArray.size()) {
251     OwningPtr<EDInst>
252       inst(disassembler->createInst(byteArrayReader, 0, &ByteArray));
253
254     if (inst == 0) {
255       errs() << "error: Didn't get an instruction\n";
256       return -1;
257     }
258
259     ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
260
261     unsigned numTokens = inst->numTokens();
262     if ((int)numTokens < 0) {
263       errs() << "error: couldn't count the instruction's tokens\n";
264       return -1;
265     }
266
267     for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
268       EDToken *token;
269
270       if (inst->getToken(token, tokenIndex)) {
271         errs() << "error: Couldn't get token\n";
272         return -1;
273       }
274
275       const char *buf;
276       if (token->getString(buf)) {
277         errs() << "error: Couldn't get string for token\n";
278         return -1;
279       }
280
281       Out << '[';
282       int operandIndex = token->operandID();
283
284       if (operandIndex >= 0)
285         Out << operandIndex << "-";
286
287       switch (token->type()) {
288       default: Out << "?"; break;
289       case EDToken::kTokenWhitespace: Out << "w"; break;
290       case EDToken::kTokenPunctuation: Out << "p"; break;
291       case EDToken::kTokenOpcode: Out << "o"; break;
292       case EDToken::kTokenLiteral: Out << "l"; break;
293       case EDToken::kTokenRegister: Out << "r"; break;
294       }
295
296       Out << ":" << buf;
297
298       if (token->type() == EDToken::kTokenLiteral) {
299         Out << "=";
300         if (token->literalSign())
301           Out << "-";
302         uint64_t absoluteValue;
303         if (token->literalAbsoluteValue(absoluteValue)) {
304           errs() << "error: Couldn't get the value of a literal token\n";
305           return -1;
306         }
307         Out << absoluteValue;
308       } else if (token->type() == EDToken::kTokenRegister) {
309         Out << "=";
310         unsigned regID;
311         if (token->registerID(regID)) {
312           errs() << "error: Couldn't get the ID of a register token\n";
313           return -1;
314         }
315         Out << "r" << regID;
316       }
317
318       Out << "]";
319     }
320
321     Out << " ";
322
323     if (inst->isBranch())
324       Out << "<br> ";
325     if (inst->isMove())
326       Out << "<mov> ";
327
328     unsigned numOperands = inst->numOperands();
329
330     if ((int)numOperands < 0) {
331       errs() << "error: Couldn't count operands\n";
332       return -1;
333     }
334
335     for (unsigned operandIndex = 0; operandIndex != numOperands;
336          ++operandIndex) {
337       Out << operandIndex << ":";
338
339       EDOperand *operand;
340       if (inst->getOperand(operand, operandIndex)) {
341         errs() << "error: couldn't get operand\n";
342         return -1;
343       }
344
345       uint64_t evaluatedResult;
346       void *Arg[] = { disassembler.get(), &Out };
347       if (operand->evaluate(evaluatedResult, verboseEvaluator, Arg)) {
348         errs() << "error: Couldn't evaluate an operand\n";
349         return -1;
350       }
351       Out << "=" << evaluatedResult << " ";
352     }
353
354     Out << '\n';
355   }
356
357   return 0;
358 }
359