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/ADT/OwningPtr.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/MemoryObject.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
34 typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
37 class VectorMemoryObject : public MemoryObject {
39 const ByteArrayTy &Bytes;
41 VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
43 uint64_t getBase() const { return 0; }
44 uint64_t getExtent() const { return Bytes.size(); }
46 int readByte(uint64_t Addr, uint8_t *Byte) const {
47 if (Addr >= getExtent())
49 *Byte = Bytes[Addr].first;
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);
61 // Disassemble it to strings.
65 for (Index = 0; Index < Bytes.size(); Index += Size) {
68 MCDisassembler::DecodeStatus S;
69 S = DisAsm.getInstruction(Inst, Size, memoryObject, Index,
72 case MCDisassembler::Fail:
73 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
74 "invalid instruction encoding", "warning");
76 Size = 1; // skip illegible bytes
79 case MCDisassembler::SoftFail:
80 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
81 "potentially undefined instruction encoding", "warning");
84 case MCDisassembler::Success:
85 Printer.printInst(&Inst, Out);
94 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
97 while (!Str.empty()) {
98 // Strip horizontal whitespace.
99 if (size_t Pos = Str.find_first_not_of(" \t\r")) {
100 Str = Str.substr(Pos);
104 // If this is the end of a line or start of a comment, remove the rest of
106 if (Str[0] == '\n' || Str[0] == '#') {
107 // Strip to the end of line if we already processed any bytes on this
108 // line. This strips the comment and/or the \n.
109 if (Str[0] == '\n') {
112 Str = Str.substr(Str.find_first_of('\n'));
119 // Get the current token.
120 size_t Next = Str.find_first_of(" \t\n\r#");
121 StringRef Value = Str.substr(0, Next);
123 // Convert to a byte and add to the byte vector.
125 if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
126 // If we have an error, print it and skip to the end of line.
127 SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
128 "invalid input token", "error");
129 Str = Str.substr(Str.find('\n'));
134 ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
135 Str = Str.substr(Next);
141 int Disassembler::disassemble(const Target &T,
142 const std::string &Triple,
143 MemoryBuffer &Buffer,
145 // Set up disassembler.
146 OwningPtr<const MCAsmInfo> AsmInfo(T.createMCAsmInfo(Triple));
149 errs() << "error: no assembly info for target " << Triple << "\n";
153 OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler());
155 errs() << "error: no disassembler for target " << Triple << "\n";
159 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
160 OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
163 errs() << "error: no instruction printer for target " << Triple << '\n';
167 bool ErrorOccurred = false;
170 SM.AddNewSourceBuffer(&Buffer, SMLoc());
172 // Convert the input to a vector for disassembly.
173 ByteArrayTy ByteArray;
174 StringRef Str = Buffer.getBuffer();
176 ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
178 if (!ByteArray.empty())
179 ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
181 return ErrorOccurred;
184 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
185 ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
187 if (A >= ByteArray.size())
190 *B = ByteArray[A].first;
195 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
196 EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
197 raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
199 if (const char *regName = disassembler.nameWithRegisterID(R))
200 Out << "[" << regName << "/" << R << "]";
202 if (disassembler.registerIsStackPointer(R))
204 if (disassembler.registerIsProgramCounter(R))
211 int Disassembler::disassembleEnhanced(const std::string &TS,
212 MemoryBuffer &Buffer,
214 ByteArrayTy ByteArray;
215 StringRef Str = Buffer.getBuffer();
218 SM.AddNewSourceBuffer(&Buffer, SMLoc());
220 if (ByteArrayFromString(ByteArray, Str, SM)) {
225 EDDisassembler::AssemblySyntax AS;
227 switch (T.getArch()) {
229 errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
233 AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
237 AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
241 EDDisassembler::initialize();
242 OwningPtr<EDDisassembler>
243 disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
245 if (disassembler == 0) {
246 errs() << "error: couldn't get disassembler for " << TS << '\n';
250 while (ByteArray.size()) {
252 inst(disassembler->createInst(byteArrayReader, 0, &ByteArray));
255 errs() << "error: Didn't get an instruction\n";
259 ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
261 unsigned numTokens = inst->numTokens();
262 if ((int)numTokens < 0) {
263 errs() << "error: couldn't count the instruction's tokens\n";
267 for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
270 if (inst->getToken(token, tokenIndex)) {
271 errs() << "error: Couldn't get token\n";
276 if (token->getString(buf)) {
277 errs() << "error: Couldn't get string for token\n";
282 int operandIndex = token->operandID();
284 if (operandIndex >= 0)
285 Out << operandIndex << "-";
287 switch (token->type()) {
288 default: Out << "?"; break;
289 case EDToken::kTokenWhitespace: Out << "w"; break;
290 case EDToken::kTokenPunctuation: Out << "p"; break;
291 case EDToken::kTokenOpcode: Out << "o"; break;
292 case EDToken::kTokenLiteral: Out << "l"; break;
293 case EDToken::kTokenRegister: Out << "r"; break;
298 if (token->type() == EDToken::kTokenLiteral) {
300 if (token->literalSign())
302 uint64_t absoluteValue;
303 if (token->literalAbsoluteValue(absoluteValue)) {
304 errs() << "error: Couldn't get the value of a literal token\n";
307 Out << absoluteValue;
308 } else if (token->type() == EDToken::kTokenRegister) {
311 if (token->registerID(regID)) {
312 errs() << "error: Couldn't get the ID of a register token\n";
323 if (inst->isBranch())
328 unsigned numOperands = inst->numOperands();
330 if ((int)numOperands < 0) {
331 errs() << "error: Couldn't count operands\n";
335 for (unsigned operandIndex = 0; operandIndex != numOperands;
337 Out << operandIndex << ":";
340 if (inst->getOperand(operand, operandIndex)) {
341 errs() << "error: couldn't get operand\n";
345 uint64_t evaluatedResult;
346 void *Arg[] = { disassembler.get(), &Out };
347 if (operand->evaluate(evaluatedResult, verboseEvaluator, Arg)) {
348 errs() << "error: Couldn't evaluate an operand\n";
351 Out << "=" << evaluatedResult << " ";