Home | History | Annotate | Download | only in Support
      1 //===- lib/Support/Disassembler.cpp -----------------------------*- C++ -*-===//
      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 file implements the necessary glue to call external disassembler
     11 // libraries.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "llvm/Config/config.h"
     16 #include "llvm/Support/Disassembler.h"
     17 
     18 #include <cassert>
     19 #include <iomanip>
     20 #include <string>
     21 #include <sstream>
     22 
     23 #if USE_UDIS86
     24 #include <udis86.h>
     25 #endif
     26 
     27 using namespace llvm;
     28 
     29 bool llvm::sys::hasDisassembler()
     30 {
     31 #if defined (__i386__) || defined (__amd64__) || defined (__x86_64__)
     32   // We have option to enable udis86 library.
     33 # if USE_UDIS86
     34   return true;
     35 #else
     36   return false;
     37 #endif
     38 #else
     39   return false;
     40 #endif
     41 }
     42 
     43 std::string llvm::sys::disassembleBuffer(uint8_t* start, size_t length,
     44                                          uint64_t pc) {
     45   std::stringstream res;
     46 
     47 #if (defined (__i386__) || defined (__amd64__) || defined (__x86_64__)) \
     48   && USE_UDIS86
     49   unsigned bits;
     50 # if defined(__i386__)
     51   bits = 32;
     52 # else
     53   bits = 64;
     54 # endif
     55 
     56   ud_t ud_obj;
     57 
     58   ud_init(&ud_obj);
     59   ud_set_input_buffer(&ud_obj, start, length);
     60   ud_set_mode(&ud_obj, bits);
     61   ud_set_pc(&ud_obj, pc);
     62   ud_set_syntax(&ud_obj, UD_SYN_ATT);
     63 
     64   res << std::setbase(16)
     65       << std::setw(bits/4);
     66 
     67   while (ud_disassemble(&ud_obj)) {
     68     res << ud_insn_off(&ud_obj) << ":\t" << ud_insn_asm(&ud_obj) << "\n";
     69   }
     70 #else
     71   res << "No disassembler available. See configure help for options.\n";
     72 #endif
     73 
     74   return res.str();
     75 }
     76