hexpatch_keystone_sys/
lib.rs

1//! Keystone Assembler Engine (www.keystone-engine.org) */
2//! By Nguyen Anh Quynh <aquynh@gmail.com>, 2016 */
3//! Rust bindings by Remco Verhoef <remco@dutchcoders.io>, 2016 */
4//!
5#![allow(bad_style)]
6
7#[macro_use]
8extern crate bitflags;
9extern crate libc;
10
11pub mod keystone_const;
12
13use keystone_const::{Arch, Error, Mode, OptionType, OptionValue};
14use ::std::{
15    ffi::CStr,
16    fmt,
17    ptr,
18};
19use ::libc::{
20    c_char,
21    c_uchar,
22    c_int,
23    c_uint,
24    size_t,
25};
26
27/// Opaque type representing the Keystone engine
28#[repr(C)]
29pub struct ks_engine {
30    _private: [u8; 0],
31}
32pub type ks_handle = ptr::NonNull<ks_engine>;
33
34extern "C" {
35    pub fn ks_version(major: *mut c_uint, minor: *mut c_uint) -> c_uint;
36    pub fn ks_arch_supported(arch: Arch) -> c_int;
37    pub fn ks_open(arch: Arch, mode: Mode, engine: *mut Option<ks_handle>) -> Error;
38    pub fn ks_asm(
39        engine: ks_handle,
40        string: *const c_char,
41        address: u64,
42        encoding: *mut *mut c_uchar,
43        encoding_size: *mut size_t,
44        stat_count: *mut size_t,
45    ) -> c_int;
46    pub fn ks_errno(engine: ks_handle) -> Error;
47    pub fn ks_strerror(error_code: Error) -> *const c_char;
48    pub fn ks_option(engine: ks_handle, opt_type: OptionType, value: OptionValue) -> Error;
49    pub fn ks_close(engine: ks_handle);
50    pub fn ks_free(encoding: *mut c_uchar);
51}
52
53impl Error {
54    pub fn msg(self) -> String {
55        error_msg(self)
56    }
57}
58
59/// Return a string describing given error code.
60pub fn error_msg(error: Error) -> String {
61    unsafe {
62        CStr::from_ptr(ks_strerror(error))
63            .to_string_lossy()
64            .into_owned()
65    }
66}
67
68impl fmt::Display for Error {
69    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70        write!(f, "{}", self.msg())
71    }
72}