1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#![feature(untagged_unions)]

#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]

include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

use std::ffi::CStr;
use std::marker::PhantomData;
use std::os::raw::c_char;
use std::ptr;

/// Represents a Result from the capstone engine.
pub type CsResult<T> = Result<T, cs_err>;

type CsOptionValue = Option<usize>;

/// A utlity for configuring the Capstone engine.
pub struct Builder {
    arch: cs_arch,
    mode: cs_mode,
    syntax: CsOptionValue,
    detail: CsOptionValue,
    skipdata: CsOptionValue,
    skipdata_config: Option<cs_opt_skipdata>,
}

impl Builder {
    /// Returns a new `Builder` for the given `arch` and `mode`.
    pub fn new(arch: cs_arch, mode: cs_mode) -> Builder {
        Builder {
            arch: arch,
            mode: mode,
            syntax: None,
            detail: None,
            skipdata: None,
            skipdata_config: None,
        }
    }

    /// Create the Capstone engine with the configured options.
    pub fn build(self) -> CsResult<Capstone> {
        let engine = Capstone::new(self.arch, self.mode)?;

        if let Some(opt) = self.syntax {
            engine.option(CS_OPT_SYNTAX, opt)?;
        }

        if let Some(opt) = self.detail {
            engine.option(CS_OPT_DETAIL, opt)?;
        }

        if let Some(opt) = self.skipdata {
            engine.option(CS_OPT_SKIPDATA, opt)?;
        }

        if let Some(opt) = self.skipdata_config {
            if self.skipdata.is_none() || self.skipdata.unwrap() != CS_OPT_ON as _ {
                engine.option(CS_OPT_SKIPDATA, CS_OPT_ON as _)?;
            }

            engine.option(CS_OPT_SKIPDATA_SETUP, &opt as *const _ as _)?;
        }

        Ok(engine)
    }

    /// Set the syntax for the engine.
    pub fn syntax(mut self, syntax: cs_opt_value) -> Builder {
        self.syntax = Some(syntax as _);
        self
    }

    /// Set whether detail mode should be on.
    pub fn detail(mut self, detail: cs_opt_value) -> Builder {
        self.detail = Some(detail as _);
        self
    }

    /// Whether data encountered in code should be skipped.
    pub fn skipdata(mut self, doit: cs_opt_value) -> Builder {
        self.skipdata = Some(doit as _);
        self
    }

    /// Setup configuration for skipdata.
    /// Userdata will always be a nullptr for now.
    pub fn skipdata_config(mut self,
                           mnemonic: Option<&'static str>,
                           callback: cs_skipdata_cb_t)
                           -> Builder {
        self.skipdata_config = Some(cs_opt_skipdata {
                                        mnemonic: mnemonic.unwrap_or(".byte").as_ptr() as _,
                                        callback: callback,
                                        user_data: ptr::null_mut(),
                                    });
        self
    }
}

/// An instance of `Capstone` represents an instance of the capstone engine.
pub struct Capstone {
    handle: csh,
}

impl Capstone {
    /// `new` returns a new instance of the capstone engine with the given
    /// `arch`itecture and `mode` used.
    pub fn new(arch: cs_arch, mode: cs_mode) -> CsResult<Capstone> {
        let mut handle = 0;
        let err = unsafe { cs_open(arch, mode, &mut handle) };
        if err != CS_ERR_OK {
            Err(err)
        } else {
            Ok(Capstone { handle: handle })
        }
    }

    /// `disasm` disassembles the given `code` at the given `address`.
    /// It disassembles `count` instructions. If `count` is 0, then as many
    /// instructions as possible are disassembled.
    pub fn disasm(&self, code: &[u8], address: u64, count: usize) -> CsResult<Instructions> {
        let mut instructions: *mut cs_insn = ptr::null_mut();
        let count = unsafe {
            cs_disasm(self.handle,
                      code.as_ptr(),
                      code.len(),
                      address,
                      count,
                      &mut instructions)
        };

        if count == 0 {
            let err = unsafe { cs_errno(self.handle) };
            debug_assert_ne!(err, CS_ERR_OK);
            Err(err)
        } else {
            Ok(Instructions::from_raw(instructions, count))
        }
    }

    /// `disasm_all` disassembles as many instructions as possible in the given `code`
    /// at the given `address`.
    pub fn disasm_all(&self, code: &[u8], address: u64) -> CsResult<Instructions> {
        self.disasm(code, address, 0)
    }

    /// `error` returns the current error as a String.
    /// This may return `None`, if there is no error, or the conversion to a String failed.
    pub fn error(&self) -> Option<String> {
        let err = unsafe { cs_errno(self.handle) };
        if err != CS_ERR_OK {
            to_string(unsafe { cs_strerror(err) })
        } else {
            None
        }
    }

    /// Returns the name of the given group.
    pub fn group_name(&self, group_id: u32) -> Option<String> {
        to_string(unsafe { cs_group_name(self.handle, group_id) })
    }

    /// Returns whether the given instruction belongs to the given group.
    pub fn insn_group(&self, insn: &cs_insn, group_id: u32) -> bool {
        unsafe { cs_insn_group(self.handle, insn, group_id) }
    }

    /// Returns the name of the given instruction.
    pub fn insn_name(&self, insn_id: u32) -> Option<String> {
        to_string(unsafe { cs_insn_name(self.handle, insn_id) })
    }

    /// `option` sets the given option `type_` to the given `value`.
    pub fn option(&self, type_: cs_opt_type, value: usize) -> CsResult<()> {
        let err = unsafe { cs_option(self.handle, type_, value) };
        if err != CS_ERR_OK { Err(err) } else { Ok(()) }
    }

    /// Returns the name of the given register.
    pub fn reg_name(&self, reg_id: u32) -> Option<String> {
        to_string(unsafe { cs_reg_name(self.handle, reg_id) })
    }

    /// Returns whether the given register is read by the given instruction.
    pub fn reg_read(&self, insn: &cs_insn, reg_id: u32) -> bool {
        unsafe { cs_reg_read(self.handle, insn, reg_id) }
    }

    /// Returns whether the given register is written by the given instruction.
    pub fn reg_write(&self, insn: &cs_insn, reg_id: u32) -> bool {
        unsafe { cs_reg_write(self.handle, insn, reg_id) }
    }
}

impl Drop for Capstone {
    fn drop(&mut self) {
        let err = unsafe { cs_close(&mut self.handle) };
        if err != CS_ERR_OK {
            panic!("Error while calling cs_close: {:?}", err)
        }
    }
}

/// `Instructions` represents a number of disassembled instructions.
pub struct Instructions {
    instructions: *mut cs_insn,
    count: usize,
}

impl Instructions {
    fn from_raw(p: *mut cs_insn, count: usize) -> Instructions {
        Instructions {
            instructions: p,
            count: count,
        }
    }

    /// Returns true if there are no instructions.
    /// This actually will never be true but clippy wants there to be a `is_empty` method
    /// when there is a `len` method.
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Returns an `PointerIter` to iterate over all the instructions.
    pub fn iter(&self) -> PointerIter<cs_insn> {
        PointerIter::new(self.instructions, self.count)
    }

    /// Returns the number of instructions owned by this struct.
    pub fn len(&self) -> usize {
        self.count
    }
}

impl Drop for Instructions {
    fn drop(&mut self) {
        unsafe { cs_free(self.instructions, self.count) }
    }
}

/// Returns whether the requested feature is supported.
/// `query` can be one of the `CS_ARCH_`* values or `CS_ARCH_ALL` + 1 to check the diet mode.
pub fn support(query: cs_arch) -> bool {
    unsafe { cs_support(query as _) }
}

/// Returns the major version, minor version and the combined version.
pub fn version() -> (i32, i32, u32) {
    let mut major = 0;
    let mut minor = 0;
    (major, minor, unsafe { cs_version(&mut major, &mut minor) })
}

/// `PointerIter` iterates over an array of things that are
/// pointed to by an pointer.
pub struct PointerIter<'a, T: 'a> {
    ptr: *const T,
    count: usize,
    current: usize,
    lifetime: PhantomData<&'a T>,
}

impl<'a, T: 'a> PointerIter<'a, T> {
    pub fn new(ptr: *const T, count: usize) -> Self {
        PointerIter {
            ptr: ptr,
            count: count,
            current: 0,
            lifetime: PhantomData,
        }
    }
}

impl<'a, T: 'a> Iterator for PointerIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<&'a T> {
        if self.current >= self.count {
            None
        } else {
            let object = unsafe { &*self.ptr.offset(self.current as _) };
            self.current += 1;
            Some(object)
        }
    }
}

impl cs_arm {
    pub fn operand_iter(&self) -> PointerIter<cs_arm_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_arm64 {
    pub fn operand_iter(&self) -> PointerIter<cs_arm64_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_mips {
    pub fn operand_iter(&self) -> PointerIter<cs_mips_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_ppc {
    pub fn operand_iter(&self) -> PointerIter<cs_ppc_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_sparc {
    pub fn operand_iter(&self) -> PointerIter<cs_sparc_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_sysz {
    pub fn operand_iter(&self) -> PointerIter<cs_sysz_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_x86 {
    pub fn operand_iter(&self) -> PointerIter<cs_x86_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_xcore {
    pub fn operand_iter(&self) -> PointerIter<cs_xcore_op> {
        PointerIter::new(self.operands.as_ptr(), self.op_count as _)
    }
}

impl cs_detail {
    /// Returns a reference to the `x86` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_x86(&self) -> &cs_x86 {
        unsafe { &self.__bindgen_anon_1.x86 }
    }

    /// Returns a reference to the `arm64` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_arm64(&self) -> &cs_arm64 {
        unsafe { &self.__bindgen_anon_1.arm64 }
    }

    /// Returns a reference to the `arm` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_arm(&self) -> &cs_arm {
        unsafe { &self.__bindgen_anon_1.arm }
    }

    /// Returns a reference to the `mips` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_mips(&self) -> &cs_mips {
        unsafe { &self.__bindgen_anon_1.mips }
    }

    /// Returns a reference to the `ppc` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_ppc(&self) -> &cs_ppc {
        unsafe { &self.__bindgen_anon_1.ppc }
    }

    /// Returns a reference to the `sparc` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_sparc(&self) -> &cs_sparc {
        unsafe { &self.__bindgen_anon_1.sparc }
    }

    /// Returns a reference to the `sysz` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_sysz(&self) -> &cs_sysz {
        unsafe { &self.__bindgen_anon_1.sysz }
    }

    /// Returns a reference to the `xcore` field of the union.
    /// It is the responsibility of the caller to ensure that the field may be used.
    pub fn get_xcore(&self) -> &cs_xcore {
        unsafe { &self.__bindgen_anon_1.xcore }
    }

    /// Returns an iterator over the registers read by this instruction.
    pub fn regs_read_iter(&self) -> PointerIter<u8> {
        PointerIter::new(self.regs_read.as_ptr(), self.regs_read_count as _)
    }

    /// Returns an iterator over the registers written to by this instruction.
    pub fn regs_write_iter(&self) -> PointerIter<u8> {
        PointerIter::new(self.regs_write.as_ptr(), self.regs_write_count as _)
    }

    /// Returns an iterator over the groups this instruction belongs to.
    pub fn groups_iter(&self) -> PointerIter<u8> {
        PointerIter::new(self.groups.as_ptr(), self.groups_count as _)
    }
}

impl cs_insn {
    pub fn get_mnemonic(&self) -> Option<String> {
        to_string(self.mnemonic.as_ptr())
    }

    pub fn get_op_str(&self) -> Option<String> {
        to_string(self.op_str.as_ptr())
    }
}

use std::fmt;
impl fmt::Debug for cs_insn {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("cs_insn")
            .field("id", &self.id)
            .field("address", &self.address)
            .field("size", &self.size)
            .field("bytes", &self.bytes)
            .field("mnemonic", &self.mnemonic)
            .field("detail", &self.detail)
            .finish()
    }
}

fn to_string(p: *const c_char) -> Option<String> {
    if p.is_null() {
        None
    } else {
        Some(unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned())
    }
}