Home | History | Annotate | Download | only in llvm-mc
      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                       "invalid instruction encoding", "warning");
     76       if (Size == 0)
     77         Size = 1; // skip illegible bytes
     78       break;
     79 
     80     case MCDisassembler::SoftFail:
     81       SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
     82                       "potentially undefined instruction encoding", "warning");
     83       // Fall through
     84 
     85     case MCDisassembler::Success:
     86       Printer.printInst(&Inst, Out, "");
     87       Out << "\n";
     88       break;
     89     }
     90   }
     91 
     92   return false;
     93 }
     94 
     95 static bool ByteArrayFromString(ByteArrayTy &ByteArray,
     96                                 StringRef &Str,
     97                                 SourceMgr &SM) {
     98   while (!Str.empty()) {
     99     // Strip horizontal whitespace.
    100     if (size_t Pos = Str.find_first_not_of(" \t\r")) {
    101       Str = Str.substr(Pos);
    102       continue;
    103     }
    104 
    105     // If this is the end of a line or start of a comment, remove the rest of
    106     // the line.
    107     if (Str[0] == '\n' || Str[0] == '#') {
    108       // Strip to the end of line if we already processed any bytes on this
    109       // line.  This strips the comment and/or the \n.
    110       if (Str[0] == '\n') {
    111         Str = Str.substr(1);
    112       } else {
    113         Str = Str.substr(Str.find_first_of('\n'));
    114         if (!Str.empty())
    115           Str = Str.substr(1);
    116       }
    117       continue;
    118     }
    119 
    120     // Get the current token.
    121     size_t Next = Str.find_first_of(" \t\n\r#");
    122     StringRef Value = Str.substr(0, Next);
    123 
    124     // Convert to a byte and add to the byte vector.
    125     unsigned ByteVal;
    126     if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
    127       // If we have an error, print it and skip to the end of line.
    128       SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
    129                       "invalid input token", "error");
    130       Str = Str.substr(Str.find('\n'));
    131       ByteArray.clear();
    132       continue;
    133     }
    134 
    135     ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
    136     Str = Str.substr(Next);
    137   }
    138 
    139   return false;
    140 }
    141 
    142 int Disassembler::disassemble(const Target &T,
    143                               const std::string &Triple,
    144                               const std::string &Cpu,
    145                               const std::string &FeaturesStr,
    146                               MemoryBuffer &Buffer,
    147                               raw_ostream &Out) {
    148   // Set up disassembler.
    149   OwningPtr<const MCAsmInfo> AsmInfo(T.createMCAsmInfo(Triple));
    150 
    151   if (!AsmInfo) {
    152     errs() << "error: no assembly info for target " << Triple << "\n";
    153     return -1;
    154   }
    155 
    156   OwningPtr<const MCSubtargetInfo> STI(T.createMCSubtargetInfo(Triple, Cpu, FeaturesStr));
    157   if (!STI) {
    158     errs() << "error: no subtarget info for target " << Triple << "\n";
    159     return -1;
    160   }
    161 
    162   OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler(*STI));
    163   if (!DisAsm) {
    164     errs() << "error: no disassembler for target " << Triple << "\n";
    165     return -1;
    166   }
    167 
    168   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
    169   OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
    170                                                     *AsmInfo, *STI));
    171   if (!IP) {
    172     errs() << "error: no instruction printer for target " << Triple << '\n';
    173     return -1;
    174   }
    175 
    176   bool ErrorOccurred = false;
    177 
    178   SourceMgr SM;
    179   SM.AddNewSourceBuffer(&Buffer, SMLoc());
    180 
    181   // Convert the input to a vector for disassembly.
    182   ByteArrayTy ByteArray;
    183   StringRef Str = Buffer.getBuffer();
    184 
    185   ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
    186 
    187   if (!ByteArray.empty())
    188     ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM, Out);
    189 
    190   return ErrorOccurred;
    191 }
    192 
    193 static int byteArrayReader(uint8_t *B, uint64_t A, void *Arg) {
    194   ByteArrayTy &ByteArray = *((ByteArrayTy*)Arg);
    195 
    196   if (A >= ByteArray.size())
    197     return -1;
    198 
    199   *B = ByteArray[A].first;
    200 
    201   return 0;
    202 }
    203 
    204 static int verboseEvaluator(uint64_t *V, unsigned R, void *Arg) {
    205   EDDisassembler &disassembler = *(EDDisassembler *)((void **)Arg)[0];
    206   raw_ostream &Out = *(raw_ostream *)((void **)Arg)[1];
    207 
    208   if (const char *regName = disassembler.nameWithRegisterID(R))
    209     Out << "[" << regName << "/" << R << "]";
    210 
    211   if (disassembler.registerIsStackPointer(R))
    212     Out << "(sp)";
    213   if (disassembler.registerIsProgramCounter(R))
    214     Out << "(pc)";
    215 
    216   *V = 0;
    217   return 0;
    218 }
    219 
    220 int Disassembler::disassembleEnhanced(const std::string &TS,
    221                                       MemoryBuffer &Buffer,
    222                                       raw_ostream &Out) {
    223   ByteArrayTy ByteArray;
    224   StringRef Str = Buffer.getBuffer();
    225   SourceMgr SM;
    226 
    227   SM.AddNewSourceBuffer(&Buffer, SMLoc());
    228 
    229   if (ByteArrayFromString(ByteArray, Str, SM)) {
    230     return -1;
    231   }
    232 
    233   Triple T(TS);
    234   EDDisassembler::AssemblySyntax AS;
    235 
    236   switch (T.getArch()) {
    237   default:
    238     errs() << "error: no default assembly syntax for " << TS.c_str() << "\n";
    239     return -1;
    240   case Triple::arm:
    241   case Triple::thumb:
    242     AS = EDDisassembler::kEDAssemblySyntaxARMUAL;
    243     break;
    244   case Triple::x86:
    245   case Triple::x86_64:
    246     AS = EDDisassembler::kEDAssemblySyntaxX86ATT;
    247     break;
    248   }
    249 
    250   EDDisassembler::initialize();
    251   OwningPtr<EDDisassembler>
    252     disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
    253 
    254   if (disassembler == 0) {
    255     errs() << "error: couldn't get disassembler for " << TS << '\n';
    256     return -1;
    257   }
    258 
    259   while (ByteArray.size()) {
    260     OwningPtr<EDInst>
    261       inst(disassembler->createInst(byteArrayReader, 0, &ByteArray));
    262 
    263     if (inst == 0) {
    264       errs() << "error: Didn't get an instruction\n";
    265       return -1;
    266     }
    267 
    268     ByteArray.erase (ByteArray.begin(), ByteArray.begin() + inst->byteSize());
    269 
    270     unsigned numTokens = inst->numTokens();
    271     if ((int)numTokens < 0) {
    272       errs() << "error: couldn't count the instruction's tokens\n";
    273       return -1;
    274     }
    275 
    276     for (unsigned tokenIndex = 0; tokenIndex != numTokens; ++tokenIndex) {
    277       EDToken *token;
    278 
    279       if (inst->getToken(token, tokenIndex)) {
    280         errs() << "error: Couldn't get token\n";
    281         return -1;
    282       }
    283 
    284       const char *buf;
    285       if (token->getString(buf)) {
    286         errs() << "error: Couldn't get string for token\n";
    287         return -1;
    288       }
    289 
    290       Out << '[';
    291       int operandIndex = token->operandID();
    292 
    293       if (operandIndex >= 0)
    294         Out << operandIndex << "-";
    295 
    296       switch (token->type()) {
    297       default: Out << "?"; break;
    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 
    369