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() const { return Bytes.size(); }
47 int readByte(uint64_t Addr, uint8_t *Byte) const {
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,
73 case MCDisassembler::Fail:
74 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
75 "invalid instruction encoding", "warning");
77 Size = 1; // skip illegible bytes
80 case MCDisassembler::SoftFail:
81 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
82 "potentially undefined instruction encoding", "warning");
85 case MCDisassembler::Success:
86 Printer.printInst(&Inst, Out);
95 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
98 while (!Str.empty()) {
99 // Strip horizontal whitespace.
100 if (size_t Pos = Str.find_first_not_of(" \t\r")) {
101 Str = Str.substr(Pos);
105 // If this is the end of a line or start of a comment, remove the rest of
107 if (Str[0] == '\n' || Str[0] == '#') {
108 // Strip to the end of line if we already processed any bytes on this
109 // line. This strips the comment and/or the \n.
110 if (Str[0] == '\n') {
113 Str = Str.substr(Str.find_first_of('\n'));
120 // Get the current token.
121 size_t Next = Str.find_first_of(" \t\n\r#");
122 StringRef Value = Str.substr(0, Next);
124 // Convert to a byte and add to the byte vector.
126 if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
127 // If we have an error, print it and skip to the end of line.
128 SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
129 "invalid input token", "error");
130 Str = Str.substr(Str.find('\n'));
135 ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
136 Str = Str.substr(Next);
142 int Disassembler::disassemble(const Target &T,
143 const std::string &Triple,
144 const std::string &Cpu,
145 const std::string &FeaturesStr,
146 MemoryBuffer &Buffer,
148 // Set up disassembler.
149 OwningPtr<const MCAsmInfo> AsmInfo(T.createMCAsmInfo(Triple));
152 errs() << "error: no assembly info for target " << Triple << "\n";
156 OwningPtr<const MCSubtargetInfo> STI(T.createMCSubtargetInfo(Triple, Cpu, FeaturesStr));
158 errs() << "error: no subtarget info for target " << Triple << "\n";
162 OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler(*STI));
164 errs() << "error: no disassembler for target " << Triple << "\n";
168 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
169 OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
172 errs() << "error: no instruction printer for target " << Triple << '\n';
176 bool ErrorOccurred = false;
179 SM.AddNewSourceBuffer(&Buffer, SMLoc());
181 // Convert the input to a vector for disassembly.
182 ByteArrayTy ByteArray;
183 StringRef Str = Buffer.getBuffer();
185 ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
187 if (!ByteArray.empty())
188 ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
190 return ErrorOccurred;
193 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
194 ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
196 if (A >= ByteArray.size())
199 *B = ByteArray[A].first;
204 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
205 EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
206 raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
208 if (const char *regName = disassembler.nameWithRegisterID(R))
209 Out << "[" << regName << "/" << R << "]";
211 if (disassembler.registerIsStackPointer(R))
213 if (disassembler.registerIsProgramCounter(R))
220 int Disassembler::disassembleEnhanced(const std::string &TS,
221 MemoryBuffer &Buffer,
223 ByteArrayTy ByteArray;
224 StringRef Str = Buffer.getBuffer();
227 SM.AddNewSourceBuffer(&Buffer, SMLoc());
229 if (ByteArrayFromString(ByteArray, Str, SM)) {
234 EDDisassembler::AssemblySyntax AS;
236 switch (T.getArch()) {
238 errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
242 AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
246 AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
250 EDDisassembler::initialize();
251 OwningPtr<EDDisassembler>
252 disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
254 if (disassembler == 0) {
255 errs() << "error: couldn't get disassembler for " << TS << '\n';
259 while (ByteArray.size()) {
261 inst(disassembler->createInst(byteArrayReader, 0, &ByteArray));
264 errs() << "error: Didn't get an instruction\n";
268 ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
270 unsigned numTokens = inst->numTokens();
271 if ((int)numTokens < 0) {
272 errs() << "error: couldn't count the instruction's tokens\n";
276 for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
279 if (inst->getToken(token, tokenIndex)) {
280 errs() << "error: Couldn't get token\n";
285 if (token->getString(buf)) {
286 errs() << "error: Couldn't get string for token\n";
291 int operandIndex = token->operandID();
293 if (operandIndex >= 0)
294 Out << operandIndex << "-";
296 switch (token->type()) {
297 default: Out << "?"; break;
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 << " ";