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