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