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"
17 #include "llvm/ADT/OwningPtr.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCDisassembler.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCInstPrinter.h"
23 #include "llvm/Target/TargetRegistry.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/MemoryObject.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/SourceMgr.h"
29 #include "llvm-c/EnhancedDisassembly.h"
33 typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
36 class VectorMemoryObject : public MemoryObject {
38 const ByteArrayTy &Bytes;
40 VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
42 uint64_t getBase() const { return 0; }
43 uint64_t getExtent() const { return Bytes.size(); }
45 int readByte(uint64_t Addr, uint8_t *Byte) const {
46 if (Addr > getExtent())
48 *Byte = Bytes[Addr].first;
54 static bool PrintInsts(const MCDisassembler &DisAsm,
55 MCInstPrinter &Printer, const ByteArrayTy &Bytes,
57 // Wrap the vector in a MemoryObject.
58 VectorMemoryObject memoryObject(Bytes);
60 // Disassemble it to strings.
64 for (Index = 0; Index < Bytes.size(); Index += Size) {
67 if (DisAsm.getInstruction(Inst, Size, memoryObject, Index,
68 /*REMOVE*/ nulls())) {
69 Printer.printInst(&Inst, outs());
72 SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
73 "invalid instruction encoding", "warning");
75 Size = 1; // skip illegible bytes
82 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
85 while (!Str.empty()) {
86 // Strip horizontal whitespace.
87 if (size_t Pos = Str.find_first_not_of(" \t\r")) {
88 Str = Str.substr(Pos);
92 // If this is the end of a line or start of a comment, remove the rest of
94 if (Str[0] == '\n' || Str[0] == '#') {
95 // Strip to the end of line if we already processed any bytes on this
96 // line. This strips the comment and/or the \n.
100 Str = Str.substr(Str.find_first_of('\n'));
107 // Get the current token.
108 size_t Next = Str.find_first_of(" \t\n\r#");
109 StringRef Value = Str.substr(0, Next);
111 // Convert to a byte and add to the byte vector.
113 if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
114 // If we have an error, print it and skip to the end of line.
115 SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
116 "invalid input token", "error");
117 Str = Str.substr(Str.find('\n'));
122 ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
123 Str = Str.substr(Next);
129 int Disassembler::disassemble(const Target &T, const std::string &Triple,
130 MemoryBuffer &Buffer) {
131 // Set up disassembler.
132 OwningPtr<const MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));
135 errs() << "error: no assembly info for target " << Triple << "\n";
139 OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler());
141 errs() << "error: no disassembler for target " << Triple << "\n";
145 OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(0, *AsmInfo));
147 errs() << "error: no instruction printer for target " << Triple << '\n';
151 bool ErrorOccurred = false;
154 SM.AddNewSourceBuffer(&Buffer, SMLoc());
156 // Convert the input to a vector for disassembly.
157 ByteArrayTy ByteArray;
158 StringRef Str = Buffer.getBuffer();
160 ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
162 if (!ByteArray.empty())
163 ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM);
165 return ErrorOccurred;
168 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
169 ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
171 if (A >= ByteArray.size())
174 *B = ByteArray[A].first;
179 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
180 EDDisassemblerRef &disassembler = *((EDDisassemblerRef*)Arg);
184 if (!EDGetRegisterName(®Name,
187 outs() << "[" << regName << "/" << R << "]";
188 if (EDRegisterIsStackPointer(disassembler, R))
190 if (EDRegisterIsProgramCounter(disassembler, R))
198 int Disassembler::disassembleEnhanced(const std::string &TS,
199 MemoryBuffer &Buffer) {
200 ByteArrayTy ByteArray;
201 StringRef Str = Buffer.getBuffer();
204 SM.AddNewSourceBuffer(&Buffer, SMLoc());
206 if (ByteArrayFromString(ByteArray, Str, SM)) {
210 EDDisassemblerRef disassembler;
213 EDAssemblySyntax_t AS;
215 switch (T.getArch()) {
217 errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
221 AS = kEDAssemblySyntaxARMUAL;
225 AS = kEDAssemblySyntaxX86ATT;
229 if (EDGetDisassembler(&disassembler,
232 errs() << "error: couldn't get disassembler for " << TS.c_str() << "\n";
238 if (EDCreateInsts(&inst, 1, disassembler, byteArrayReader, 0,&ByteArray)
240 errs() << "error: Didn't get an instruction\n";
244 int numTokens = EDNumTokens(inst);
247 errs() << "error: Couldn't count the instruction's tokens\n";
253 for (tokenIndex = 0; tokenIndex < numTokens; ++tokenIndex) {
256 if (EDGetToken(&token, inst, tokenIndex)) {
257 errs() << "error: Couldn't get token\n";
263 if (EDGetTokenString(&buf, token)) {
264 errs() << "error: Couldn't get string for token\n";
270 int operandIndex = EDOperandIndexForToken(token);
272 if (operandIndex >= 0)
273 outs() << operandIndex << "-";
275 if (EDTokenIsWhitespace(token)) {
277 } else if (EDTokenIsPunctuation(token)) {
279 } else if (EDTokenIsOpcode(token)) {
281 } else if (EDTokenIsLiteral(token)) {
283 } else if (EDTokenIsRegister(token)) {
289 outs() << ":" << buf;
291 if (EDTokenIsLiteral(token)) {
293 if (EDTokenIsNegativeLiteral(token))
295 uint64_t absoluteValue;
296 if (EDLiteralTokenAbsoluteValue(&absoluteValue, token)) {
297 errs() << "error: Couldn't get the value of a literal token\n";
300 outs() << absoluteValue;
301 } else if (EDTokenIsRegister(token)) {
304 if (EDRegisterTokenValue(®ID, token)) {
305 errs() << "error: Couldn't get the ID of a register token\n";
308 outs() << "r" << regID;
316 int numOperands = EDNumOperands(inst);
318 if (numOperands < 0) {
319 errs() << "error: Couldn't count operands\n";
325 for (operandIndex = 0; operandIndex < numOperands; ++operandIndex) {
326 outs() << operandIndex << ":";
328 EDOperandRef operand;
330 if (EDGetOperand(&operand,
333 errs() << "error: Couldn't get operand\n";
337 uint64_t evaluatedResult;
339 EDEvaluateOperand(&evaluatedResult,