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/Target/TargetRegistry.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/raw_ostream.h"
31 #include "llvm/Support/SourceMgr.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 if (DisAsm
.getInstruction(Inst
, Size
, memoryObject
, Index
,
69 /*REMOVE*/ nulls())) {
70 Printer
.printInst(&Inst
, Out
);
73 SM
.PrintMessage(SMLoc::getFromPointer(Bytes
[Index
].second
),
74 "invalid instruction encoding", "warning");
76 Size
= 1; // skip illegible bytes
83 static bool ByteArrayFromString(ByteArrayTy
&ByteArray
,
86 while (!Str
.empty()) {
87 // Strip horizontal whitespace.
88 if (size_t Pos
= Str
.find_first_not_of(" \t\r")) {
89 Str
= Str
.substr(Pos
);
93 // If this is the end of a line or start of a comment, remove the rest of
95 if (Str
[0] == '\n' || Str
[0] == '#') {
96 // Strip to the end of line if we already processed any bytes on this
97 // line. This strips the comment and/or the \n.
101 Str
= Str
.substr(Str
.find_first_of('\n'));
108 // Get the current token.
109 size_t Next
= Str
.find_first_of(" \t\n\r#");
110 StringRef Value
= Str
.substr(0, Next
);
112 // Convert to a byte and add to the byte vector.
114 if (Value
.getAsInteger(0, ByteVal
) || ByteVal
> 255) {
115 // If we have an error, print it and skip to the end of line.
116 SM
.PrintMessage(SMLoc::getFromPointer(Value
.data()),
117 "invalid input token", "error");
118 Str
= Str
.substr(Str
.find('\n'));
123 ByteArray
.push_back(std::make_pair((unsigned char)ByteVal
, Value
.data()));
124 Str
= Str
.substr(Next
);
130 int Disassembler::disassemble(const Target
&T
, const std::string
&Triple
,
131 MemoryBuffer
&Buffer
,
133 // Set up disassembler.
134 OwningPtr
<const MCAsmInfo
> AsmInfo(T
.createAsmInfo(Triple
));
137 errs() << "error: no assembly info for target " << Triple
<< "\n";
141 OwningPtr
<const MCDisassembler
> DisAsm(T
.createMCDisassembler());
143 errs() << "error: no disassembler for target " << Triple
<< "\n";
147 int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
148 OwningPtr
<MCInstPrinter
> IP(T
.createMCInstPrinter(AsmPrinterVariant
,
151 errs() << "error: no instruction printer for target " << Triple
<< '\n';
155 bool ErrorOccurred
= false;
158 SM
.AddNewSourceBuffer(&Buffer
, SMLoc());
160 // Convert the input to a vector for disassembly.
161 ByteArrayTy ByteArray
;
162 StringRef Str
= Buffer
.getBuffer();
164 ErrorOccurred
|= ByteArrayFromString(ByteArray
, Str
, SM
);
166 if (!ByteArray
.empty())
167 ErrorOccurred
|= PrintInsts(*DisAsm
, *IP
, ByteArray
, SM
, Out
);
169 return ErrorOccurred
;
172 static int byteArrayReader(uint8_t *B
, uint64_t A
, void *Arg
) {
173 ByteArrayTy
&ByteArray
= *((ByteArrayTy
*)Arg
);
175 if (A
>= ByteArray
.size())
178 *B
= ByteArray
[A
].first
;
183 static int verboseEvaluator(uint64_t *V
, unsigned R
, void *Arg
) {
184 EDDisassembler
&disassembler
= *(EDDisassembler
*)((void **)Arg
)[0];
185 raw_ostream
&Out
= *(raw_ostream
*)((void **)Arg
)[1];
187 if (const char *regName
= disassembler
.nameWithRegisterID(R
))
188 Out
<< "[" << regName
<< "/" << R
<< "]";
190 if (disassembler
.registerIsStackPointer(R
))
192 if (disassembler
.registerIsProgramCounter(R
))
199 int Disassembler::disassembleEnhanced(const std::string
&TS
,
200 MemoryBuffer
&Buffer
,
202 ByteArrayTy ByteArray
;
203 StringRef Str
= Buffer
.getBuffer();
206 SM
.AddNewSourceBuffer(&Buffer
, SMLoc());
208 if (ByteArrayFromString(ByteArray
, Str
, SM
)) {
213 EDDisassembler::AssemblySyntax AS
;
215 switch (T
.getArch()) {
217 errs() << "error: no default assembly syntax for " << TS
.c_str() << "\n";
221 AS
= EDDisassembler::kEDAssemblySyntaxARMUAL
;
225 AS
= EDDisassembler::kEDAssemblySyntaxX86ATT
;
229 EDDisassembler::initialize();
230 EDDisassembler
*disassembler
=
231 EDDisassembler::getDisassembler(TS
.c_str(), AS
);
233 if (disassembler
== 0) {
234 errs() << "error: couldn't get disassembler for " << TS
<< '\n';
239 disassembler
->createInst(byteArrayReader
, 0, &ByteArray
);
242 errs() << "error: Didn't get an instruction\n";
246 unsigned numTokens
= inst
->numTokens();
247 if ((int)numTokens
< 0) {
248 errs() << "error: couldn't count the instruction's tokens\n";
252 for (unsigned tokenIndex
= 0; tokenIndex
!= numTokens
; ++tokenIndex
) {
255 if (inst
->getToken(token
, tokenIndex
)) {
256 errs() << "error: Couldn't get token\n";
261 if (token
->getString(buf
)) {
262 errs() << "error: Couldn't get string for token\n";
267 int operandIndex
= token
->operandID();
269 if (operandIndex
>= 0)
270 Out
<< operandIndex
<< "-";
272 switch (token
->type()) {
273 default: Out
<< "?"; break;
274 case EDToken::kTokenWhitespace
: Out
<< "w"; break;
275 case EDToken::kTokenPunctuation
: Out
<< "p"; break;
276 case EDToken::kTokenOpcode
: Out
<< "o"; break;
277 case EDToken::kTokenLiteral
: Out
<< "l"; break;
278 case EDToken::kTokenRegister
: Out
<< "r"; break;
283 if (token
->type() == EDToken::kTokenLiteral
) {
285 if (token
->literalSign())
287 uint64_t absoluteValue
;
288 if (token
->literalAbsoluteValue(absoluteValue
)) {
289 errs() << "error: Couldn't get the value of a literal token\n";
292 Out
<< absoluteValue
;
293 } else if (token
->type() == EDToken::kTokenRegister
) {
296 if (token
->registerID(regID
)) {
297 errs() << "error: Couldn't get the ID of a register token\n";
308 if (inst
->isBranch())
313 unsigned numOperands
= inst
->numOperands();
315 if ((int)numOperands
< 0) {
316 errs() << "error: Couldn't count operands\n";
320 for (unsigned operandIndex
= 0; operandIndex
!= numOperands
; ++operandIndex
) {
321 Out
<< operandIndex
<< ":";
324 if (inst
->getOperand(operand
, operandIndex
)) {
325 errs() << "error: couldn't get operand\n";
329 uint64_t evaluatedResult
;
330 void *Arg
[] = { disassembler
, &Out
};
331 evaluatedResult
= operand
->evaluate(evaluatedResult
, verboseEvaluator
, Arg
);
332 Out
<< "=" << evaluatedResult
<< " ";