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