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 OwningPtr<EDDisassembler> 253 disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS)); 254 255 if (disassembler == 0) { 256 errs() << "error: couldn't get disassembler for " << TS << '\n'; 257 return -1; 258 } 259 260 while (ByteArray.size()) { 261 OwningPtr<EDInst> 262 inst(disassembler->createInst(byteArrayReader, 0, &ByteArray)); 263 264 if (inst == 0) { 265 errs() << "error: Didn't get an instruction\n"; 266 return -1; 267 } 268 269 ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize()); 270 271 unsigned numTokens = inst->numTokens(); 272 if ((int)numTokens < 0) { 273 errs() << "error: couldn't count the instruction's tokens\n"; 274 return -1; 275 } 276 277 for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) { 278 EDToken *token; 279 280 if (inst->getToken(token, tokenIndex)) { 281 errs() << "error: Couldn't get token\n"; 282 return -1; 283 } 284 285 const char *buf; 286 if (token->getString(buf)) { 287 errs() << "error: Couldn't get string for token\n"; 288 return -1; 289 } 290 291 Out << '['; 292 int operandIndex = token->operandID(); 293 294 if (operandIndex >= 0) 295 Out << operandIndex << "-"; 296 297 switch (token->type()) { 298 case EDToken::kTokenWhitespace: Out << "w"; break; 299 case EDToken::kTokenPunctuation: Out << "p"; break; 300 case EDToken::kTokenOpcode: Out << "o"; break; 301 case EDToken::kTokenLiteral: Out << "l"; break; 302 case EDToken::kTokenRegister: Out << "r"; break; 303 } 304 305 Out << ":" << buf; 306 307 if (token->type() == EDToken::kTokenLiteral) { 308 Out << "="; 309 if (token->literalSign()) 310 Out << "-"; 311 uint64_t absoluteValue; 312 if (token->literalAbsoluteValue(absoluteValue)) { 313 errs() << "error: Couldn't get the value of a literal token\n"; 314 return -1; 315 } 316 Out << absoluteValue; 317 } else if (token->type() == EDToken::kTokenRegister) { 318 Out << "="; 319 unsigned regID; 320 if (token->registerID(regID)) { 321 errs() << "error: Couldn't get the ID of a register token\n"; 322 return -1; 323 } 324 Out << "r" << regID; 325 } 326 327 Out << "]"; 328 } 329 330 Out << " "; 331 332 if (inst->isBranch()) 333 Out << "<br> "; 334 if (inst->isMove()) 335 Out << "<mov> "; 336 337 unsigned numOperands = inst->numOperands(); 338 339 if ((int)numOperands < 0) { 340 errs() << "error: Couldn't count operands\n"; 341 return -1; 342 } 343 344 for (unsigned operandIndex = 0; operandIndex != numOperands; 345 ++operandIndex) { 346 Out << operandIndex << ":"; 347 348 EDOperand *operand; 349 if (inst->getOperand(operand, operandIndex)) { 350 errs() << "error: couldn't get operand\n"; 351 return -1; 352 } 353 354 uint64_t evaluatedResult; 355 void *Arg[] = { disassembler.get(), &Out }; 356 if (operand->evaluate(evaluatedResult, verboseEvaluator, Arg)) { 357 errs() << "error: Couldn't evaluate an operand\n"; 358 return -1; 359 } 360 Out << "=" << evaluatedResult << " "; 361 } 362 363 Out << '\n'; 364 } 365 366 return 0; 367 } 368