1 //===- Disassembler.cpp - Disassembler for hex strings --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the disassembler of strings of bytes written in
11 // hexadecimal, from standard input or from a file.
13 //===----------------------------------------------------------------------===//
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/MCSubtargetInfo.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/SourceMgr.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Support/raw_ostream.h"
35 typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
38 class VectorMemoryObject : public MemoryObject {
40 const ByteArrayTy &Bytes;
42 VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
44 uint64_t getBase() const { return 0; }
45 uint64_t getExtent() { return Bytes.size(); }
47 int readByte(uint64_t Addr, uint8_t *Byte) {
48 if (Addr >= getExtent())
50 *Byte = Bytes[Addr].first;
56 static bool PrintInsts(const MCDisassembler &DisAsm,
57 MCInstPrinter &Printer, const ByteArrayTy &Bytes,
58 SourceMgr &SM, raw_ostream &Out) {
59 // Wrap the vector in a MemoryObject.
60 VectorMemoryObject memoryObject(Bytes);
62 // Disassemble it to strings.
66 for (Index = 0; Index < Bytes.size(); Index += Size) {
69 MCDisassembler::DecodeStatus S;
70 S = DisAsm.getInstruction(Inst, Size, memoryObject, Index,
71 /*REMOVE*/ nulls(), nulls());
73 case MCDisassembler::Fail:
74 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
75 SourceMgr::DK_Warning,
76 "invalid instruction encoding");
78 Size = 1; // skip illegible bytes
81 case MCDisassembler::SoftFail:
82 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
83 SourceMgr::DK_Warning,
84 "potentially undefined instruction encoding");
87 case MCDisassembler::Success:
88 Printer.printInst(&Inst, Out, "");
97 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
100 while (!Str.empty()) {
101 // Strip horizontal whitespace.
102 if (size_t Pos = Str.find_first_not_of(" \t\r")) {
103 Str = Str.substr(Pos);
107 // If this is the end of a line or start of a comment, remove the rest of
109 if (Str[0] == '\n' || Str[0] == '#') {
110 // Strip to the end of line if we already processed any bytes on this
111 // line. This strips the comment and/or the \n.
112 if (Str[0] == '\n') {
115 Str = Str.substr(Str.find_first_of('\n'));
122 // Get the current token.
123 size_t Next = Str.find_first_of(" \t\n\r#");
124 StringRef Value = Str.substr(0, Next);
126 // Convert to a byte and add to the byte vector.
128 if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
129 // If we have an error, print it and skip to the end of line.
130 SM.PrintMessage(SMLoc::getFromPointer(Value.data()), SourceMgr::DK_Error,
131 "invalid input token");
132 Str = Str.substr(Str.find('\n'));
137 ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
138 Str = Str.substr(Next);
144 int Disassembler::disassemble(const Target &T,
145 const std::string &Triple,
146 const std::string &Cpu,
147 const std::string &FeaturesStr,
148 MemoryBuffer &Buffer,
150 // Set up disassembler.
151 OwningPtr<const MCAsmInfo> AsmInfo(T.createMCAsmInfo(Triple));
154 errs() << "error: no assembly info for target " << Triple << "\n";
158 OwningPtr<const MCSubtargetInfo> STI(T.createMCSubtargetInfo(Triple, Cpu, FeaturesStr));
160 errs() << "error: no subtarget info for target " << Triple << "\n";
164 OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler(*STI));
166 errs() << "error: no disassembler for target " << Triple << "\n";
170 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
171 OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
174 errs() << "error: no instruction printer for target " << Triple << '\n';
178 bool ErrorOccurred = false;
181 SM.AddNewSourceBuffer(&Buffer, SMLoc());
183 // Convert the input to a vector for disassembly.
184 ByteArrayTy ByteArray;
185 StringRef Str = Buffer.getBuffer();
187 ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
189 if (!ByteArray.empty())
190 ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
192 return ErrorOccurred;
195 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
196 ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
198 if (A >= ByteArray.size())
201 *B = ByteArray[A].first;
206 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
207 EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
208 raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
210 if (const char *regName = disassembler.nameWithRegisterID(R))
211 Out << "[" << regName << "/" << R << "]";
213 if (disassembler.registerIsStackPointer(R))
215 if (disassembler.registerIsProgramCounter(R))
222 int Disassembler::disassembleEnhanced(const std::string &TS,
223 MemoryBuffer &Buffer,
225 ByteArrayTy ByteArray;
226 StringRef Str = Buffer.getBuffer();
229 SM.AddNewSourceBuffer(&Buffer, SMLoc());
231 if (ByteArrayFromString(ByteArray, Str, SM)) {
236 EDDisassembler::AssemblySyntax AS;
238 switch (T.getArch()) {
240 errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
244 AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
248 AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
252 OwningPtr<EDDisassembler>
253 disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
255 if (disassembler == 0) {
256 errs() << "error: couldn't get disassembler for " << TS << '\n';
260 while (ByteArray.size()) {
262 inst(disassembler->createInst(byteArrayReader, 0, &ByteArray));
265 errs() << "error: Didn't get an instruction\n";
269 ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
271 unsigned numTokens = inst->numTokens();
272 if ((int)numTokens < 0) {
273 errs() << "error: couldn't count the instruction's tokens\n";
277 for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
280 if (inst->getToken(token, tokenIndex)) {
281 errs() << "error: Couldn't get token\n";
286 if (token->getString(buf)) {
287 errs() << "error: Couldn't get string for token\n";
292 int operandIndex = token->operandID();
294 if (operandIndex >= 0)
295 Out << operandIndex << "-";
297 switch (token->type()) {
298 case EDToken::kTokenWhitespace: Out << "w"; break;
299 case EDToken::kTokenPunctuation: Out << "p"; break;
300 case EDToken::kTokenOpcode: Out << "o"; break;
301 case EDToken::kTokenLiteral: Out << "l"; break;
302 case EDToken::kTokenRegister: Out << "r"; break;
307 if (token->type() == EDToken::kTokenLiteral) {
309 if (token->literalSign())
311 uint64_t absoluteValue;
312 if (token->literalAbsoluteValue(absoluteValue)) {
313 errs() << "error: Couldn't get the value of a literal token\n";
316 Out << absoluteValue;
317 } else if (token->type() == EDToken::kTokenRegister) {
320 if (token->registerID(regID)) {
321 errs() << "error: Couldn't get the ID of a register token\n";
332 if (inst->isBranch())
337 unsigned numOperands = inst->numOperands();
339 if ((int)numOperands < 0) {
340 errs() << "error: Couldn't count operands\n";
344 for (unsigned operandIndex = 0; operandIndex != numOperands;
346 Out << operandIndex << ":";
349 if (inst->getOperand(operand, operandIndex)) {
350 errs() << "error: couldn't get operand\n";
354 uint64_t evaluatedResult;
355 void *Arg[] = { disassembler.get(), &Out };
356 if (operand->evaluate(evaluatedResult, verboseEvaluator, Arg)) {
357 errs() << "error: Couldn't evaluate an operand\n";
360 Out << "=" << evaluatedResult << " ";