Use the new tool_output_file in several tools. This fixes a variety
[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, raw_ostream &Out) {
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, Out);
70       Out << "\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                               raw_ostream &Out) {
132   // Set up disassembler.
133   OwningPtr<const MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));
134   
135   if (!AsmInfo) {
136     errs() << "error: no assembly info for target " << Triple << "\n";
137     return -1;
138   }
139   
140   OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler());
141   if (!DisAsm) {
142     errs() << "error: no disassembler for target " << Triple << "\n";
143     return -1;
144   }
145   
146   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
147   OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
148                                                     *AsmInfo));
149   if (!IP) {
150     errs() << "error: no instruction printer for target " << Triple << '\n';
151     return -1;
152   }
153   
154   bool ErrorOccurred = false;
155   
156   SourceMgr SM;
157   SM.AddNewSourceBuffer(&Buffer, SMLoc());
158   
159   // Convert the input to a vector for disassembly.
160   ByteArrayTy ByteArray;
161   StringRef Str = Buffer.getBuffer();
162   
163   ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
164   
165   if (!ByteArray.empty())
166     ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
167     
168   return ErrorOccurred;
169 }
170
171 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
172   ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
173   
174   if (A >= ByteArray.size())
175     return -1;
176   
177   *B = ByteArray[A].first;
178   
179   return 0;
180 }
181
182 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
183   EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
184   raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
185   
186   if (const char *regName = disassembler.nameWithRegisterID(R))
187     Out << "[" << regName << "/" << R << "]";
188   
189   if (disassembler.registerIsStackPointer(R))
190     Out << "(sp)";
191   if (disassembler.registerIsProgramCounter(R))
192     Out << "(pc)";
193   
194   *V = 0;
195   return 0;
196 }
197
198 int Disassembler::disassembleEnhanced(const std::string &TS, 
199                                       MemoryBuffer &Buffer,
200                                       raw_ostream &Out) {
201   ByteArrayTy ByteArray;
202   StringRef Str = Buffer.getBuffer();
203   SourceMgr SM;
204   
205   SM.AddNewSourceBuffer(&Buffer, SMLoc());
206   
207   if (ByteArrayFromString(ByteArray, Str, SM)) {
208     return -1;
209   }
210   
211   Triple T(TS);
212   EDDisassembler::AssemblySyntax AS;
213   
214   switch (T.getArch()) {
215   default:
216     errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
217     return -1;
218   case Triple::arm:
219   case Triple::thumb:
220     AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
221     break;
222   case Triple::x86:
223   case Triple::x86_64:
224     AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
225     break;
226   }
227   
228   EDDisassembler::initialize();
229   EDDisassembler *disassembler =
230     EDDisassembler::getDisassembler(TS.c_str(), AS);
231   
232   if (disassembler == 0) {
233     errs() << "error: couldn't get disassembler for " << TS << '\n';
234     return -1;
235   }
236   
237   EDInst *inst =
238     disassembler->createInst(byteArrayReader, 0, &ByteArray);
239                              
240   if (inst == 0) {
241     errs() << "error: Didn't get an instruction\n";
242     return -1;
243   }
244   
245   unsigned numTokens = inst->numTokens();
246   if ((int)numTokens < 0) {
247     errs() << "error: couldn't count the instruction's tokens\n";
248     return -1;
249   }
250   
251   for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
252     EDToken *token;
253     
254     if (inst->getToken(token, tokenIndex)) {
255       errs() << "error: Couldn't get token\n";
256       return -1;
257     }
258     
259     const char *buf;
260     if (token->getString(buf)) {
261       errs() << "error: Couldn't get string for token\n";
262       return -1;
263     }
264     
265     Out << '[';
266     int operandIndex = token->operandID();
267     
268     if (operandIndex >= 0)
269       Out << operandIndex << "-";
270     
271     switch (token->type()) {
272     default: Out << "?"; break;
273     case EDToken::kTokenWhitespace: Out << "w"; break;
274     case EDToken::kTokenPunctuation: Out << "p"; break;
275     case EDToken::kTokenOpcode: Out << "o"; break;
276     case EDToken::kTokenLiteral: Out << "l"; break;
277     case EDToken::kTokenRegister: Out << "r"; break;
278     }
279     
280     Out << ":" << buf;
281   
282     if (token->type() == EDToken::kTokenLiteral) {
283       Out << "=";
284       if (token->literalSign())
285         Out << "-";
286       uint64_t absoluteValue;
287       if (token->literalAbsoluteValue(absoluteValue)) {
288         errs() << "error: Couldn't get the value of a literal token\n";
289         return -1;
290       }
291       Out << absoluteValue;
292     } else if (token->type() == EDToken::kTokenRegister) {
293       Out << "=";
294       unsigned regID;
295       if (token->registerID(regID)) {
296         errs() << "error: Couldn't get the ID of a register token\n";
297         return -1;
298       }
299       Out << "r" << regID;
300     }
301     
302     Out << "]";
303   }
304   
305   Out << " ";
306     
307   if (inst->isBranch())
308     Out << "<br> ";
309   if (inst->isMove())
310     Out << "<mov> ";
311   
312   unsigned numOperands = inst->numOperands();
313   
314   if ((int)numOperands < 0) {
315     errs() << "error: Couldn't count operands\n";
316     return -1;
317   }
318   
319   for (unsigned operandIndex = 0; operandIndex != numOperands; ++operandIndex) {
320     Out << operandIndex << ":";
321     
322     EDOperand *operand;
323     if (inst->getOperand(operand, operandIndex)) {
324       errs() << "error: couldn't get operand\n";
325       return -1;
326     }
327     
328     uint64_t evaluatedResult;
329     void *Arg[] = { disassembler, &Out };
330     evaluatedResult = operand->evaluate(evaluatedResult, verboseEvaluator, Arg);
331     Out << "=" << evaluatedResult << " ";
332   }
333   
334   Out << '\n';
335   
336   return 0;
337 }
338