rusty-xed 0.1.2

High-level, safe, bindings for XED
Documentation
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::{ffi::CStr, fmt::Display, sync::Mutex};
use xed_sys::{
    xed_decoded_inst_get_iclass, xed_decoded_inst_get_second_immediate,
    xed_decoded_inst_get_signed_immediate, xed_decoded_inst_get_unsigned_immediate,
    xed_decoded_inst_inst, xed_format_context, xed_inst_iform_enum, XED_SYNTAX_ATT,
    XED_SYNTAX_INTEL, XED_SYNTAX_XED,
};

mod iclass;
mod iform;
mod operand_name;
mod reg;

pub use iclass::XedIClass;
pub use iform::XedIForm;
pub use operand_name::OperandName;
pub use reg::XedReg;

#[macro_export]
macro_rules! enum_impl {
    (#[range($from:expr, $to:expr)] enum $name:ident { $($original_name:ident => $new_name:ident),* $(,)* }) => {
        const _RANGE_TEST: () = {
            let from = $from;
            let to = $to;
            let mut seen = [false; $to as usize];

            $(seen[$original_name as usize] = true;)*

            let mut n = from;
            while n < to {
                const_panic::concat_assert!{
                    seen[n as usize],
                    "Item missing: ", n
                };

                n += 1;
            }
        };

        #[allow(non_camel_case_types)]
        #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
        pub enum $name {
            $($new_name,)*
        }

        impl $name {
            #[allow(non_upper_case_globals)]
            #[forbid(unused_variables)]
            pub fn from_u32(val: u32) -> Option<$name> {
                Some(match val {
                    $($original_name => $name::$new_name,)*
                    _ => return None,
                })
            }
        }
    };
}

static INITIALIZED: Mutex<bool> = Mutex::new(false);

#[derive(Clone)]
pub struct XedError(xed_sys::xed_error_enum_t);

impl std::fmt::Debug for XedError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("XedError")
            .field("code", &self.0)
            .field("message", &self.to_string())
            .finish()
    }
}

impl std::fmt::Display for XedError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let error_message = unsafe {
            std::ffi::CStr::from_ptr(xed_sys::xed_error_enum_t2str(self.0)).to_string_lossy()
        };

        write!(f, "{error_message}")
    }
}

impl std::error::Error for XedError {}

#[non_exhaustive]
pub enum MachineMode {
    Long64,
}

impl MachineMode {
    fn to_xed(&self) -> u32 {
        match self {
            MachineMode::Long64 => xed_sys::XED_MACHINE_MODE_LONG_64,
        }
    }
}

#[non_exhaustive]
pub enum AddressWidth {
    Width64b,
}

impl AddressWidth {
    fn to_xed(&self) -> u32 {
        match self {
            AddressWidth::Width64b => xed_sys::XED_ADDRESS_WIDTH_64b,
        }
    }
}

pub struct Xed {
    mode: MachineMode,
    address_width: AddressWidth,
}

impl Xed {
    pub fn new(mode: MachineMode, address_width: AddressWidth) -> Self {
        {
            let mut lock = INITIALIZED.lock().unwrap();
            if !*lock {
                *lock = true;
                unsafe { xed_sys::xed_tables_init() }
            }
        }

        Self {
            mode,
            address_width,
        }
    }

    pub fn decode(&self, instr: &[u8]) -> Result<DecodedInstr, XedError> {
        let mut decoded = ::std::mem::MaybeUninit::<xed_sys::xed_decoded_inst_t>::uninit();
        unsafe {
            xed_sys::xed_decoded_inst_zero(decoded.as_mut_ptr());
            xed_sys::xed_decoded_inst_set_mode(
                decoded.as_mut_ptr(),
                self.mode.to_xed(),
                self.address_width.to_xed(),
            );

            let xed_error: xed_sys::xed_error_enum_t = xed_sys::xed_decode(
                decoded.as_mut_ptr(),
                instr.as_ptr(),
                instr.len().try_into().unwrap(),
            );
            if xed_error == xed_sys::XED_ERROR_NONE {
                let decoded = decoded.assume_init();
                Ok(DecodedInstr(decoded))
            } else {
                Err(XedError(xed_error))
            }
        }
    }
}

pub struct DecodedInstr(xed_sys::xed_decoded_inst_s);

impl DecodedInstr {
    pub fn operands(&self) -> Operands<'_> {
        Operands(self)
    }

    pub fn memory_accesses(&self) -> MemoryAccesses<'_> {
        MemoryAccesses(self)
    }

    pub fn iclass(&self) -> XedIClass {
        let iclass = unsafe { xed_decoded_inst_get_iclass(self.as_ptr()) };

        XedIClass::from_u32(iclass).unwrap()
    }

    pub fn iform(&self) -> XedIForm {
        let iform = unsafe {
            let inst = xed_sys::xed_decoded_inst_inst(self.as_ptr());
            xed_inst_iform_enum(inst)
        };

        XedIForm::from_u32(iform).unwrap()
    }

    fn as_ptr(&self) -> *const xed_sys::xed_decoded_inst_s {
        &self.0
    }

    fn as_inst(&self) -> *const xed_sys::xed_inst_s {
        unsafe { xed_decoded_inst_inst(self.as_ptr()) }
    }

    pub fn display(
        &self,
        syntax: XedSyntax,
        runtime_instruction_address: u64,
    ) -> impl Display + use<'_> {
        DisplayDecodedInstr {
            syntax,
            instr: self,
            runtime_instruction_address,
        }
    }
}

impl Display for DecodedInstr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.display(XedSyntax::Intel, 0), f)
    }
}

pub enum XedSyntax {
    Intel,
    Att,
    Xed,
}

struct DisplayDecodedInstr<'a> {
    syntax: XedSyntax,
    instr: &'a DecodedInstr,
    runtime_instruction_address: u64,
}

impl Display for DisplayDecodedInstr<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut buf = [0u8; 256];
        unsafe {
            xed_format_context(
                match self.syntax {
                    XedSyntax::Intel => XED_SYNTAX_INTEL,
                    XedSyntax::Att => XED_SYNTAX_ATT,
                    XedSyntax::Xed => XED_SYNTAX_XED,
                },
                self.instr.as_ptr(),
                buf.as_mut_ptr() as *mut i8,
                buf.len() as i32 - 1,
                self.runtime_instruction_address,
                std::ptr::null_mut(),
                None,
            );
        }

        f.write_str(
            CStr::from_bytes_until_nul(&buf)
                .expect("xed should not overwrite last byte")
                .to_str()
                .expect("xed_decoded_inst_dump should return valid UTF-8"),
        )
    }
}

pub struct Operands<'a>(&'a DecodedInstr);

impl<'a> Operands<'a> {
    #[must_use]
    pub fn len(&self) -> usize {
        unsafe { xed_sys::xed_decoded_inst_noperands(self.0.as_ptr()) }
            .try_into()
            .unwrap()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn get(&self, index: usize) -> Option<Operand<'a>> {
        let index = index.try_into().unwrap();
        let operand = unsafe { xed_sys::xed_inst_operand(self.0.as_inst(), index) };

        Some(Operand {
            source: self.0,
            index,
            operand,
        })
    }
}

pub struct Operand<'a> {
    source: &'a DecodedInstr,
    index: u32,
    operand: *const xed_sys::xed_operand_t,
}

impl<'a> Operand<'a> {
    fn operand_name(&self) -> xed_sys::xed_operand_enum_t {
        unsafe { xed_sys::xed_operand_name(self.operand) }
    }

    pub fn name(&self) -> OperandName {
        OperandName::from_u32(self.operand_name()).unwrap()
    }

    pub fn operand_size_bits(&self) -> usize {
        unsafe {
            xed_sys::xed_decoded_inst_operand_length_bits(self.source.as_ptr(), self.index)
                .try_into()
                .unwrap()
        }
    }

    pub fn reg(&self) -> Option<XedReg> {
        if self.is_reg() {
            Some(unsafe {
                XedReg::from_u32(xed_sys::xed_decoded_inst_get_reg(
                    self.source.as_ptr(),
                    self.operand_name(),
                ))
                .unwrap()
            })
        } else {
            None
        }
    }

    pub fn is_reg(&self) -> bool {
        unsafe { xed_sys::xed_operand_is_register(self.operand_name()) != 0 }
    }

    pub fn is_imm(&self) -> bool {
        self.imm_value().is_some()
    }

    pub fn imm_value(&self) -> Option<u64> {
        Some(match self.name() {
            OperandName::Imm0 => unsafe {
                xed_decoded_inst_get_unsigned_immediate(self.source.as_ptr())
            },
            OperandName::Imm0Signed => unsafe {
                xed_decoded_inst_get_signed_immediate(self.source.as_ptr()) as u32 as u64
            },
            OperandName::Imm1 | OperandName::Imm1Bytes => unsafe {
                xed_decoded_inst_get_second_immediate(self.source.as_ptr()) as u64
            },
            _ => return None,
        })
    }

    pub fn is_memory_addressing_register(&self) -> bool {
        unsafe { xed_sys::xed_operand_is_memory_addressing_register(self.operand_name()) != 0 }
    }
}

pub struct MemoryAccesses<'a>(&'a DecodedInstr);

impl<'a> MemoryAccesses<'a> {
    #[must_use]
    pub fn len(&self) -> usize {
        unsafe { xed_sys::xed_decoded_inst_number_of_memory_operands(self.0.as_ptr()) }
            .try_into()
            .unwrap()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn get(&self, index: usize) -> Option<MemoryAccess<'a>> {
        if index >= self.len() {
            None
        } else {
            Some(MemoryAccess {
                source: self.0,
                index: index.try_into().unwrap(),
            })
        }
    }
}

pub struct MemoryAccess<'a> {
    source: &'a DecodedInstr,
    index: u32,
}

impl std::fmt::Debug for MemoryAccess<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MemoryAccess")
            .field("segment_reg", &self.segment_reg())
            .field("base_reg", &self.base_reg())
            .field("index_reg", &self.index_reg())
            .field("scale", &self.scale())
            .field("memory_displacement", &self.memory_displacement())
            .field(
                "memory_displacement_width",
                &self.memory_displacement_width(),
            )
            .field(
                "memory_displacement_width_bits",
                &self.memory_displacement_width_bits(),
            )
            .field("is_read", &self.is_read())
            .field("is_written", &self.is_written())
            .field("is_written_only", &self.is_written_only())
            .finish()
    }
}

impl MemoryAccess<'_> {
    fn return_reg(reg: u32) -> Option<XedReg> {
        if reg == xed_sys::XED_REG_INVALID {
            None
        } else {
            Some(XedReg::from_u32(reg).unwrap())
        }
    }

    pub fn segment_reg(&self) -> Option<XedReg> {
        unsafe {
            Self::return_reg(xed_sys::xed_decoded_inst_get_seg_reg(
                self.source.as_ptr(),
                self.index,
            ))
        }
    }

    pub fn base_reg(&self) -> Option<XedReg> {
        unsafe {
            Self::return_reg(xed_sys::xed_decoded_inst_get_base_reg(
                self.source.as_ptr(),
                self.index,
            ))
        }
    }

    pub fn scale(&self) -> u32 {
        unsafe { xed_sys::xed_decoded_inst_get_scale(self.source.as_ptr(), self.index) }
    }

    pub fn memory_displacement(&self) -> i64 {
        unsafe {
            xed_sys::xed_decoded_inst_get_memory_displacement(self.source.as_ptr(), self.index)
        }
    }

    pub fn memory_displacement_width(&self) -> u32 {
        unsafe {
            xed_sys::xed_decoded_inst_get_memory_displacement_width(
                self.source.as_ptr(),
                self.index,
            )
        }
    }

    pub fn memory_displacement_width_bits(&self) -> u32 {
        unsafe {
            xed_sys::xed_decoded_inst_get_memory_displacement_width_bits(
                self.source.as_ptr(),
                self.index,
            )
        }
    }

    pub fn is_read(&self) -> bool {
        unsafe { xed_sys::xed_decoded_inst_mem_read(self.source.as_ptr(), self.index) != 0 }
    }

    pub fn is_written(&self) -> bool {
        unsafe { xed_sys::xed_decoded_inst_mem_written(self.source.as_ptr(), self.index) != 0 }
    }

    pub fn is_written_only(&self) -> bool {
        unsafe { xed_sys::xed_decoded_inst_mem_written_only(self.source.as_ptr(), self.index) != 0 }
    }

    pub fn index_reg(&self) -> Option<XedReg> {
        unsafe {
            Self::return_reg(xed_sys::xed_decoded_inst_get_index_reg(
                self.source.as_ptr(),
                self.index,
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{AddressWidth, MachineMode, Xed};

    #[test]
    pub fn imm_operands() {
        let xed = Xed::new(MachineMode::Long64, AddressWidth::Width64b);
        let instr = xed.decode(&[0x48, 0xC1, 0xE0, 0x03]).unwrap();
        let _op = instr.operands().get(1).unwrap();
    }

    #[test]
    pub fn iclass_valid() {
        let xed = Xed::new(MachineMode::Long64, AddressWidth::Width64b);
        let instr = xed.decode(&[0x40, 0x0F, 0x18, 0x32]).unwrap();

        instr.iclass();
    }

    #[test]
    pub fn display() {
        let xed = Xed::new(MachineMode::Long64, AddressWidth::Width64b);
        let instr = xed.decode(&[0x00, 0xd3]).unwrap();

        assert_eq!(instr.to_string(), "add bl, dl");
    }
}