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