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/MCInstrInfo.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/MemoryObject.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
37 typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
40 class VectorMemoryObject : public MemoryObject {
42 const ByteArrayTy &Bytes;
44 VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
46 uint64_t getBase() const { return 0; }
47 uint64_t getExtent() const { return Bytes.size(); }
49 int readByte(uint64_t Addr, uint8_t *Byte) const {
50 if (Addr >= getExtent())
52 *Byte = Bytes[Addr].first;
58 static bool PrintInsts(const MCDisassembler &DisAsm,
59 MCInstPrinter &Printer, const ByteArrayTy &Bytes,
60 SourceMgr &SM, raw_ostream &Out) {
61 // Wrap the vector in a MemoryObject.
62 VectorMemoryObject memoryObject(Bytes);
64 // Disassemble it to strings.
68 for (Index = 0; Index < Bytes.size(); Index += Size) {
71 MCDisassembler::DecodeStatus S;
72 S = DisAsm.getInstruction(Inst, Size, memoryObject, Index,
73 /*REMOVE*/ nulls(), nulls());
75 case MCDisassembler::Fail:
76 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
77 SourceMgr::DK_Warning,
78 "invalid instruction encoding");
80 Size = 1; // skip illegible bytes
83 case MCDisassembler::SoftFail:
84 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
85 SourceMgr::DK_Warning,
86 "potentially undefined instruction encoding");
89 case MCDisassembler::Success:
90 Printer.printInst(&Inst, Out, "");
99 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
102 while (!Str.empty()) {
103 // Strip horizontal whitespace.
104 if (size_t Pos = Str.find_first_not_of(" \t\r")) {
105 Str = Str.substr(Pos);
109 // If this is the end of a line or start of a comment, remove the rest of
111 if (Str[0] == '\n' || Str[0] == '#') {
112 // Strip to the end of line if we already processed any bytes on this
113 // line. This strips the comment and/or the \n.
114 if (Str[0] == '\n') {
117 Str = Str.substr(Str.find_first_of('\n'));
124 // Get the current token.
125 size_t Next = Str.find_first_of(" \t\n\r#");
126 StringRef Value = Str.substr(0, Next);
128 // Convert to a byte and add to the byte vector.
130 if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
131 // If we have an error, print it and skip to the end of line.
132 SM.PrintMessage(SMLoc::getFromPointer(Value.data()), SourceMgr::DK_Error,
133 "invalid input token");
134 Str = Str.substr(Str.find('\n'));
139 ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
140 Str = Str.substr(Next);
146 int Disassembler::disassemble(const Target &T,
147 const std::string &Triple,
148 const std::string &Cpu,
149 const std::string &FeaturesStr,
150 MemoryBuffer &Buffer,
152 // Set up disassembler.
153 OwningPtr<const MCAsmInfo> AsmInfo(T.createMCAsmInfo(Triple));
156 errs() << "error: no assembly info for target " << Triple << "\n";
160 OwningPtr<const MCSubtargetInfo> STI(T.createMCSubtargetInfo(Triple, Cpu,
163 errs() << "error: no subtarget info for target " << Triple << "\n";
167 OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler(*STI));
169 errs() << "error: no disassembler for target " << Triple << "\n";
173 OwningPtr<const MCRegisterInfo> MRI(T.createMCRegInfo(Triple));
175 errs() << "error: no register info for target " << Triple << "\n";
179 OwningPtr<const MCInstrInfo> MII(T.createMCInstrInfo());
181 errs() << "error: no instruction info for target " << Triple << "\n";
185 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
186 OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant, *AsmInfo,
189 errs() << "error: no instruction printer for target " << Triple << '\n';
193 bool ErrorOccurred = false;
196 SM.AddNewSourceBuffer(&Buffer, SMLoc());
198 // Convert the input to a vector for disassembly.
199 ByteArrayTy ByteArray;
200 StringRef Str = Buffer.getBuffer();
202 ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
204 if (!ByteArray.empty())
205 ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
207 return ErrorOccurred;
210 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
211 ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
213 if (A >= ByteArray.size())
216 *B = ByteArray[A].first;
221 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
222 EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
223 raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
225 if (const char *regName = disassembler.nameWithRegisterID(R))
226 Out << "[" << regName << "/" << R << "]";
228 if (disassembler.registerIsStackPointer(R))
230 if (disassembler.registerIsProgramCounter(R))
237 int Disassembler::disassembleEnhanced(const std::string &TS,
238 MemoryBuffer &Buffer,
240 ByteArrayTy ByteArray;
241 StringRef Str = Buffer.getBuffer();
244 SM.AddNewSourceBuffer(&Buffer, SMLoc());
246 if (ByteArrayFromString(ByteArray, Str, SM)) {
251 EDDisassembler::AssemblySyntax AS;
253 switch (T.getArch()) {
255 errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
259 AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
263 AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
267 OwningPtr<EDDisassembler>
268 disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
270 if (disassembler == 0) {
271 errs() << "error: couldn't get disassembler for " << TS << '\n';
275 while (ByteArray.size()) {
277 inst(disassembler->createInst(byteArrayReader, 0, &ByteArray));
280 errs() << "error: Didn't get an instruction\n";
284 ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
286 unsigned numTokens = inst->numTokens();
287 if ((int)numTokens < 0) {
288 errs() << "error: couldn't count the instruction's tokens\n";
292 for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
295 if (inst->getToken(token, tokenIndex)) {
296 errs() << "error: Couldn't get token\n";
301 if (token->getString(buf)) {
302 errs() << "error: Couldn't get string for token\n";
307 int operandIndex = token->operandID();
309 if (operandIndex >= 0)
310 Out << operandIndex << "-";
312 switch (token->type()) {
313 case EDToken::kTokenWhitespace: Out << "w"; break;
314 case EDToken::kTokenPunctuation: Out << "p"; break;
315 case EDToken::kTokenOpcode: Out << "o"; break;
316 case EDToken::kTokenLiteral: Out << "l"; break;
317 case EDToken::kTokenRegister: Out << "r"; break;
322 if (token->type() == EDToken::kTokenLiteral) {
324 if (token->literalSign())
326 uint64_t absoluteValue;
327 if (token->literalAbsoluteValue(absoluteValue)) {
328 errs() << "error: Couldn't get the value of a literal token\n";
331 Out << absoluteValue;
332 } else if (token->type() == EDToken::kTokenRegister) {
335 if (token->registerID(regID)) {
336 errs() << "error: Couldn't get the ID of a register token\n";
347 if (inst->isBranch())
352 unsigned numOperands = inst->numOperands();
354 if ((int)numOperands < 0) {
355 errs() << "error: Couldn't count operands\n";
359 for (unsigned operandIndex = 0; operandIndex != numOperands;
361 Out << operandIndex << ":";
364 if (inst->getOperand(operand, operandIndex)) {
365 errs() << "error: couldn't get operand\n";
369 uint64_t evaluatedResult;
370 void *Arg[] = { disassembler.get(), &Out };
371 if (operand->evaluate(evaluatedResult, verboseEvaluator, Arg)) {
372 errs() << "error: Couldn't evaluate an operand\n";
375 Out << "=" << evaluatedResult << " ";