Disassembler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. //===- Disassembler.cpp - Disassembler for hex strings --------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This class implements the disassembler of strings of bytes written in
  11. // hexadecimal, from standard input or from a file.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "Disassembler.h"
  15. #include "../../lib/MC/MCDisassembler/EDDisassembler.h"
  16. #include "../../lib/MC/MCDisassembler/EDInst.h"
  17. #include "../../lib/MC/MCDisassembler/EDOperand.h"
  18. #include "../../lib/MC/MCDisassembler/EDToken.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/MC/MCSubtargetInfo.h"
  24. #include "llvm/ADT/OwningPtr.h"
  25. #include "llvm/ADT/Triple.h"
  26. #include "llvm/ADT/Twine.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/MemoryObject.h"
  29. #include "llvm/Support/SourceMgr.h"
  30. #include "llvm/Support/TargetRegistry.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. using namespace llvm;
  33. typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;
  34. namespace {
  35. class VectorMemoryObject : public MemoryObject {
  36. private:
  37. const ByteArrayTy &Bytes;
  38. public:
  39. VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}
  40. uint64_t getBase() const { return 0; }
  41. uint64_t getExtent() const { return Bytes.size(); }
  42. int readByte(uint64_t Addr, uint8_t *Byte) const {
  43. if (Addr >= getExtent())
  44. return -1;
  45. *Byte = Bytes[Addr].first;
  46. return 0;
  47. }
  48. };
  49. }
  50. static bool PrintInsts(const MCDisassembler &DisAsm,
  51. MCInstPrinter &Printer, const ByteArrayTy &Bytes,
  52. SourceMgr &SM, raw_ostream &Out) {
  53. // Wrap the vector in a MemoryObject.
  54. VectorMemoryObject memoryObject(Bytes);
  55. // Disassemble it to strings.
  56. uint64_t Size;
  57. uint64_t Index;
  58. for (Index = 0; Index < Bytes.size(); Index += Size) {
  59. MCInst Inst;
  60. MCDisassembler::DecodeStatus S;
  61. S = DisAsm.getInstruction(Inst, Size, memoryObject, Index,
  62. /*REMOVE*/ nulls(), nulls());
  63. switch (S) {
  64. case MCDisassembler::Fail:
  65. SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
  66. SourceMgr::DK_Warning,
  67. "invalid instruction encoding");
  68. if (Size == 0)
  69. Size = 1; // skip illegible bytes
  70. break;
  71. case MCDisassembler::SoftFail:
  72. SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
  73. SourceMgr::DK_Warning,
  74. "potentially undefined instruction encoding");
  75. // Fall through
  76. case MCDisassembler::Success:
  77. Printer.printInst(&Inst, Out, "");
  78. Out << "\n";
  79. break;
  80. }
  81. }
  82. return false;
  83. }
  84. static bool ByteArrayFromString(ByteArrayTy &ByteArray,
  85. StringRef &Str,
  86. SourceMgr &SM) {
  87. while (!Str.empty()) {
  88. // Strip horizontal whitespace.
  89. if (size_t Pos = Str.find_first_not_of(" \t\r")) {
  90. Str = Str.substr(Pos);
  91. continue;
  92. }
  93. // If this is the end of a line or start of a comment, remove the rest of
  94. // the line.
  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.
  98. if (Str[0] == '\n') {
  99. Str = Str.substr(1);
  100. } else {
  101. Str = Str.substr(Str.find_first_of('\n'));
  102. if (!Str.empty())
  103. Str = Str.substr(1);
  104. }
  105. continue;
  106. }
  107. // Get the current token.
  108. size_t Next = Str.find_first_of(" \t\n\r#");
  109. StringRef Value = Str.substr(0, Next);
  110. // Convert to a byte and add to the byte vector.
  111. unsigned ByteVal;
  112. if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
  113. // If we have an error, print it and skip to the end of line.
  114. SM.PrintMessage(SMLoc::getFromPointer(Value.data()), SourceMgr::DK_Error,
  115. "invalid input token");
  116. Str = Str.substr(Str.find('\n'));
  117. ByteArray.clear();
  118. continue;
  119. }
  120. ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
  121. Str = Str.substr(Next);
  122. }
  123. return false;
  124. }
  125. int Disassembler::disassemble(const Target &T,
  126. const std::string &Triple,
  127. const std::string &Cpu,
  128. const std::string &FeaturesStr,
  129. MemoryBuffer &Buffer,
  130. raw_ostream &Out) {
  131. // Set up disassembler.
  132. OwningPtr<const MCAsmInfo> AsmInfo(T.createMCAsmInfo(Triple));
  133. if (!AsmInfo) {
  134. errs() << "error: no assembly info for target " << Triple << "\n";
  135. return -1;
  136. }
  137. OwningPtr<const MCSubtargetInfo> STI(T.createMCSubtargetInfo(Triple, Cpu, FeaturesStr));
  138. if (!STI) {
  139. errs() << "error: no subtarget info for target " << Triple << "\n";
  140. return -1;
  141. }
  142. OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler(*STI));
  143. if (!DisAsm) {
  144. errs() << "error: no disassembler for target " << Triple << "\n";
  145. return -1;
  146. }
  147. int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
  148. OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
  149. *AsmInfo, *STI));
  150. if (!IP) {
  151. errs() << "error: no instruction printer for target " << Triple << '\n';
  152. return -1;
  153. }
  154. bool ErrorOccurred = false;
  155. SourceMgr SM;
  156. SM.AddNewSourceBuffer(&Buffer, SMLoc());
  157. // Convert the input to a vector for disassembly.
  158. ByteArrayTy ByteArray;
  159. StringRef Str = Buffer.getBuffer();
  160. ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
  161. if (!ByteArray.empty())
  162. ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
  163. return ErrorOccurred;
  164. }
  165. static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
  166. ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
  167. if (A >= ByteArray.size())
  168. return -1;
  169. *B = ByteArray[A].first;
  170. return 0;
  171. }
  172. static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
  173. EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
  174. raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
  175. if (const char *regName = disassembler.nameWithRegisterID(R))
  176. Out << "[" << regName << "/" << R << "]";
  177. if (disassembler.registerIsStackPointer(R))
  178. Out << "(sp)";
  179. if (disassembler.registerIsProgramCounter(R))
  180. Out << "(pc)";
  181. *V = 0;
  182. return 0;
  183. }
  184. int Disassembler::disassembleEnhanced(const std::string &TS,
  185. MemoryBuffer &Buffer,
  186. raw_ostream &Out) {
  187. ByteArrayTy ByteArray;
  188. StringRef Str = Buffer.getBuffer();
  189. SourceMgr SM;
  190. SM.AddNewSourceBuffer(&Buffer, SMLoc());
  191. if (ByteArrayFromString(ByteArray, Str, SM)) {
  192. return -1;
  193. }
  194. Triple T(TS);
  195. EDDisassembler::AssemblySyntax AS;
  196. switch (T.getArch()) {
  197. default:
  198. errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
  199. return -1;
  200. case Triple::arm:
  201. case Triple::thumb:
  202. AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
  203. break;
  204. case Triple::x86:
  205. case Triple::x86_64:
  206. AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
  207. break;
  208. }
  209. OwningPtr<EDDisassembler>
  210. disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
  211. if (disassembler == 0) {
  212. errs() << "error: couldn't get disassembler for " << TS << '\n';
  213. return -1;
  214. }
  215. while (ByteArray.size()) {
  216. OwningPtr<EDInst>
  217. inst(disassembler->createInst(byteArrayReader, 0, &ByteArray));
  218. if (inst == 0) {
  219. errs() << "error: Didn't get an instruction\n";
  220. return -1;
  221. }
  222. ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
  223. unsigned numTokens = inst->numTokens();
  224. if ((int)numTokens < 0) {
  225. errs() << "error: couldn't count the instruction's tokens\n";
  226. return -1;
  227. }
  228. for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
  229. EDToken *token;
  230. if (inst->getToken(token, tokenIndex)) {
  231. errs() << "error: Couldn't get token\n";
  232. return -1;
  233. }
  234. const char *buf;
  235. if (token->getString(buf)) {
  236. errs() << "error: Couldn't get string for token\n";
  237. return -1;
  238. }
  239. Out << '[';
  240. int operandIndex = token->operandID();
  241. if (operandIndex >= 0)
  242. Out << operandIndex << "-";
  243. switch (token->type()) {
  244. case EDToken::kTokenWhitespace: Out << "w"; break;
  245. case EDToken::kTokenPunctuation: Out << "p"; break;
  246. case EDToken::kTokenOpcode: Out << "o"; break;
  247. case EDToken::kTokenLiteral: Out << "l"; break;
  248. case EDToken::kTokenRegister: Out << "r"; break;
  249. }
  250. Out << ":" << buf;
  251. if (token->type() == EDToken::kTokenLiteral) {
  252. Out << "=";
  253. if (token->literalSign())
  254. Out << "-";
  255. uint64_t absoluteValue;
  256. if (token->literalAbsoluteValue(absoluteValue)) {
  257. errs() << "error: Couldn't get the value of a literal token\n";
  258. return -1;
  259. }
  260. Out << absoluteValue;
  261. } else if (token->type() == EDToken::kTokenRegister) {
  262. Out << "=";
  263. unsigned regID;
  264. if (token->registerID(regID)) {
  265. errs() << "error: Couldn't get the ID of a register token\n";
  266. return -1;
  267. }
  268. Out << "r" << regID;
  269. }
  270. Out << "]";
  271. }
  272. Out << " ";
  273. if (inst->isBranch())
  274. Out << "<br> ";
  275. if (inst->isMove())
  276. Out << "<mov> ";
  277. unsigned numOperands = inst->numOperands();
  278. if ((int)numOperands < 0) {
  279. errs() << "error: Couldn't count operands\n";
  280. return -1;
  281. }
  282. for (unsigned operandIndex = 0; operandIndex != numOperands;
  283. ++operandIndex) {
  284. Out << operandIndex << ":";
  285. EDOperand *operand;
  286. if (inst->getOperand(operand, operandIndex)) {
  287. errs() << "error: couldn't get operand\n";
  288. return -1;
  289. }
  290. uint64_t evaluatedResult;
  291. void *Arg[] = { disassembler.get(), &Out };
  292. if (operand->evaluate(evaluatedResult, verboseEvaluator, Arg)) {
  293. errs() << "error: Couldn't evaluate an operand\n";
  294. return -1;
  295. }
  296. Out << "=" << evaluatedResult << " ";
  297. }
  298. Out << '\n';
  299. }
  300. return 0;
  301. }