Adding disassembler interface and external hook to udis86 library.
[oota-llvm.git] / lib / Support / Disassembler.cpp
1 //===- lib/Support/Disassembler.cpp -----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Anton Korobeynikov and is distributed under the
6 // University of Illinois Open Source 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 std::string llvm::disassembleBuffer(uint8_t* start, size_t length,
30                               Disassembler::Type type, uint64_t pc) {
31   std::stringstream res;
32   
33   if (type == Disassembler::X86_32 || type == Disassembler::X86_64) {
34 #if USE_UDIS86
35     ud_t ud_obj;
36    
37     ud_init(&ud_obj);
38     ud_set_input_buffer(&ud_obj, start, length);
39     ud_set_mode(&ud_obj, (type == Disassembler::X86_32 ? 32 : 64));
40     ud_set_pc(&ud_obj, pc);
41     ud_set_syntax(&ud_obj, UD_SYN_ATT);
42
43     res << std::setbase(16)
44         << std::setw((type == Disassembler::X86_32 ? 8 : 16));
45
46     while (ud_disassemble(&ud_obj)) {
47       res << ud_insn_off(&ud_obj) << ":\t" << ud_insn_asm(&ud_obj) << "\n";
48     }
49 #endif
50   }
51
52   return res.str();
53 }