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
,
131 const std::string
&Triple
,
132 MemoryBuffer
&Buffer
,
134 // Set up disassembler.
135 OwningPtr
<const MCAsmInfo
> AsmInfo(T
.createAsmInfo(Triple
));
138 errs() << "error: no assembly info for target " << Triple
<< "\n";
142 OwningPtr
<const MCDisassembler
> DisAsm(T
.createMCDisassembler());
144 errs() << "error: no disassembler for target " << Triple
<< "\n";
148 int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
149 OwningPtr
<MCInstPrinter
> IP(T
.createMCInstPrinter(AsmPrinterVariant
,
152 errs() << "error: no instruction printer for target " << Triple
<< '\n';
156 bool ErrorOccurred
= false;
159 SM
.AddNewSourceBuffer(&Buffer
, SMLoc());
161 // Convert the input to a vector for disassembly.
162 ByteArrayTy ByteArray
;
163 StringRef Str
= Buffer
.getBuffer();
165 ErrorOccurred
|= ByteArrayFromString(ByteArray
, Str
, SM
);
167 if (!ByteArray
.empty())
168 ErrorOccurred
|= PrintInsts(*DisAsm
, *IP
, ByteArray
, SM
, Out
);
170 return ErrorOccurred
;
173 static int byteArrayReader(uint8_t *B
, uint64_t A
, void *Arg
) {
174 ByteArrayTy
&ByteArray
= *((ByteArrayTy
*)Arg
);
176 if (A
>= ByteArray
.size())
179 *B
= ByteArray
[A
].first
;
184 static int verboseEvaluator(uint64_t *V
, unsigned R
, void *Arg
) {
185 EDDisassembler
&disassembler
= *(EDDisassembler
*)((void **)Arg
)[0];
186 raw_ostream
&Out
= *(raw_ostream
*)((void **)Arg
)[1];
188 if (const char *regName
= disassembler
.nameWithRegisterID(R
))
189 Out
<< "[" << regName
<< "/" << R
<< "]";
191 if (disassembler
.registerIsStackPointer(R
))
193 if (disassembler
.registerIsProgramCounter(R
))
200 int Disassembler::disassembleEnhanced(const std::string
&TS
,
201 MemoryBuffer
&Buffer
,
203 ByteArrayTy ByteArray
;
204 StringRef Str
= Buffer
.getBuffer();
207 SM
.AddNewSourceBuffer(&Buffer
, SMLoc());
209 if (ByteArrayFromString(ByteArray
, Str
, SM
)) {
214 EDDisassembler::AssemblySyntax AS
;
216 switch (T
.getArch()) {
218 errs() << "error: no default assembly syntax for " << TS
.c_str() << "\n";
222 AS
= EDDisassembler::kEDAssemblySyntaxARMUAL
;
226 AS
= EDDisassembler::kEDAssemblySyntaxX86ATT
;
230 EDDisassembler::initialize();
231 OwningPtr
<EDDisassembler
>
232 disassembler(EDDisassembler::getDisassembler(TS
.c_str(), AS
));
234 if (disassembler
== 0) {
235 errs() << "error: couldn't get disassembler for " << TS
<< '\n';
239 while (ByteArray
.size()) {
241 inst(disassembler
->createInst(byteArrayReader
, 0, &ByteArray
));
244 errs() << "error: Didn't get an instruction\n";
248 ByteArray
.erase (ByteArray
.begin(), ByteArray
.begin() + inst
->byteSize());
250 unsigned numTokens
= inst
->numTokens();
251 if ((int)numTokens
< 0) {
252 errs() << "error: couldn't count the instruction's tokens\n";
256 for (unsigned tokenIndex
= 0; tokenIndex
!= numTokens
; ++tokenIndex
) {
259 if (inst
->getToken(token
, tokenIndex
)) {
260 errs() << "error: Couldn't get token\n";
265 if (token
->getString(buf
)) {
266 errs() << "error: Couldn't get string for token\n";
271 int operandIndex
= token
->operandID();
273 if (operandIndex
>= 0)
274 Out
<< operandIndex
<< "-";
276 switch (token
->type()) {
277 default: Out
<< "?"; break;
278 case EDToken::kTokenWhitespace
: Out
<< "w"; break;
279 case EDToken::kTokenPunctuation
: Out
<< "p"; break;
280 case EDToken::kTokenOpcode
: Out
<< "o"; break;
281 case EDToken::kTokenLiteral
: Out
<< "l"; break;
282 case EDToken::kTokenRegister
: Out
<< "r"; break;
287 if (token
->type() == EDToken::kTokenLiteral
) {
289 if (token
->literalSign())
291 uint64_t absoluteValue
;
292 if (token
->literalAbsoluteValue(absoluteValue
)) {
293 errs() << "error: Couldn't get the value of a literal token\n";
296 Out
<< absoluteValue
;
297 } else if (token
->type() == EDToken::kTokenRegister
) {
300 if (token
->registerID(regID
)) {
301 errs() << "error: Couldn't get the ID of a register token\n";
312 if (inst
->isBranch())
317 unsigned numOperands
= inst
->numOperands();
319 if ((int)numOperands
< 0) {
320 errs() << "error: Couldn't count operands\n";
324 for (unsigned operandIndex
= 0; operandIndex
!= numOperands
;
326 Out
<< operandIndex
<< ":";
329 if (inst
->getOperand(operand
, operandIndex
)) {
330 errs() << "error: couldn't get operand\n";
334 uint64_t evaluatedResult
;
335 void *Arg
[] = { disassembler
.get(), &Out
};
336 if (operand
->evaluate(evaluatedResult
, verboseEvaluator
, Arg
)) {
337 errs() << "error: Couldn't evaluate an operand\n";
340 Out
<< "=" << evaluatedResult
<< " ";