xref: /llvm-project/llvm/tools/llvm-mc/Disassembler.cpp (revision be81988c99d6867b05d0900ce4536284838e3131)
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   while (ByteArray.size()) {
239     EDInst *inst =
240       disassembler->createInst(byteArrayReader, 0, &ByteArray);
241 
242     ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
243 
244     if (inst == 0) {
245       errs() << "error: Didn't get an instruction\n";
246       return -1;
247     }
248 
249     unsigned numTokens = inst->numTokens();
250     if ((int)numTokens < 0) {
251       errs() << "error: couldn't count the instruction's tokens\n";
252       return -1;
253     }
254 
255     for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
256       EDToken *token;
257 
258       if (inst->getToken(token, tokenIndex)) {
259         errs() << "error: Couldn't get token\n";
260         return -1;
261       }
262 
263       const char *buf;
264       if (token->getString(buf)) {
265         errs() << "error: Couldn't get string for token\n";
266         return -1;
267       }
268 
269       Out << '[';
270       int operandIndex = token->operandID();
271 
272       if (operandIndex >= 0)
273         Out << operandIndex << "-";
274 
275       switch (token->type()) {
276       default: Out << "?"; break;
277       case EDToken::kTokenWhitespace: Out << "w"; break;
278       case EDToken::kTokenPunctuation: Out << "p"; break;
279       case EDToken::kTokenOpcode: Out << "o"; break;
280       case EDToken::kTokenLiteral: Out << "l"; break;
281       case EDToken::kTokenRegister: Out << "r"; break;
282       }
283 
284       Out << ":" << buf;
285 
286       if (token->type() == EDToken::kTokenLiteral) {
287         Out << "=";
288         if (token->literalSign())
289           Out << "-";
290         uint64_t absoluteValue;
291         if (token->literalAbsoluteValue(absoluteValue)) {
292           errs() << "error: Couldn't get the value of a literal token\n";
293           return -1;
294         }
295         Out << absoluteValue;
296       } else if (token->type() == EDToken::kTokenRegister) {
297         Out << "=";
298         unsigned regID;
299         if (token->registerID(regID)) {
300           errs() << "error: Couldn't get the ID of a register token\n";
301           return -1;
302         }
303         Out << "r" << regID;
304       }
305 
306       Out << "]";
307     }
308 
309     Out << " ";
310 
311     if (inst->isBranch())
312       Out << "<br> ";
313     if (inst->isMove())
314       Out << "<mov> ";
315 
316     unsigned numOperands = inst->numOperands();
317 
318     if ((int)numOperands < 0) {
319       errs() << "error: Couldn't count operands\n";
320       return -1;
321     }
322 
323     for (unsigned operandIndex = 0; operandIndex != numOperands; ++operandIndex) {
324       Out << operandIndex << ":";
325 
326       EDOperand *operand;
327       if (inst->getOperand(operand, operandIndex)) {
328         errs() << "error: couldn't get operand\n";
329         return -1;
330       }
331 
332       uint64_t evaluatedResult;
333       void *Arg[] = { disassembler, &Out };
334       if (operand->evaluate(evaluatedResult, verboseEvaluator, Arg)) {
335         errs() << "error: Couldn't evaluate an operand\n";
336         return -1;
337       }
338       Out << "=" << evaluatedResult << " ";
339     }
340 
341     Out << '\n';
342   }
343 
344   return 0;
345 }
346 
347