Skip to main content

rusty_xed/
lib.rs

1use std::{ffi::CStr, fmt::Display, sync::Mutex};
2use xed_sys::{
3    xed_decoded_inst_get_iclass, xed_decoded_inst_get_second_immediate,
4    xed_decoded_inst_get_signed_immediate, xed_decoded_inst_get_unsigned_immediate,
5    xed_decoded_inst_inst, xed_format_context, xed_inst_iform_enum, XED_SYNTAX_ATT,
6    XED_SYNTAX_INTEL, XED_SYNTAX_XED,
7};
8
9mod iclass;
10mod iform;
11mod operand_name;
12mod reg;
13
14pub use iclass::XedIClass;
15pub use iform::XedIForm;
16pub use operand_name::OperandName;
17pub use reg::XedReg;
18
19#[macro_export]
20macro_rules! enum_impl {
21    (#[range($from:expr, $to:expr)] enum $name:ident { $($original_name:ident => $new_name:ident),* $(,)* }) => {
22        const _RANGE_TEST: () = {
23            let from = $from;
24            let to = $to;
25            let mut seen = [false; $to as usize];
26
27            $(seen[$original_name as usize] = true;)*
28
29            let mut n = from;
30            while n < to {
31                const_panic::concat_assert!{
32                    seen[n as usize],
33                    "Item missing: ", n
34                };
35
36                n += 1;
37            }
38        };
39
40        #[allow(non_camel_case_types)]
41        #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
42        pub enum $name {
43            $($new_name,)*
44        }
45
46        impl $name {
47            #[allow(non_upper_case_globals)]
48            #[forbid(unused_variables)]
49            pub fn from_u32(val: u32) -> Option<$name> {
50                Some(match val {
51                    $($original_name => $name::$new_name,)*
52                    _ => return None,
53                })
54            }
55        }
56    };
57}
58
59static INITIALIZED: Mutex<bool> = Mutex::new(false);
60
61#[derive(Clone)]
62pub struct XedError(xed_sys::xed_error_enum_t);
63
64impl std::fmt::Debug for XedError {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("XedError")
67            .field("code", &self.0)
68            .field("message", &self.to_string())
69            .finish()
70    }
71}
72
73impl std::fmt::Display for XedError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        let error_message = unsafe {
76            std::ffi::CStr::from_ptr(xed_sys::xed_error_enum_t2str(self.0)).to_string_lossy()
77        };
78
79        write!(f, "{error_message}")
80    }
81}
82
83impl std::error::Error for XedError {}
84
85#[non_exhaustive]
86pub enum MachineMode {
87    Long64,
88}
89
90impl MachineMode {
91    fn to_xed(&self) -> u32 {
92        match self {
93            MachineMode::Long64 => xed_sys::XED_MACHINE_MODE_LONG_64,
94        }
95    }
96}
97
98#[non_exhaustive]
99pub enum AddressWidth {
100    Width64b,
101}
102
103impl AddressWidth {
104    fn to_xed(&self) -> u32 {
105        match self {
106            AddressWidth::Width64b => xed_sys::XED_ADDRESS_WIDTH_64b,
107        }
108    }
109}
110
111pub struct Xed {
112    mode: MachineMode,
113    address_width: AddressWidth,
114}
115
116impl Xed {
117    pub fn new(mode: MachineMode, address_width: AddressWidth) -> Self {
118        {
119            let mut lock = INITIALIZED.lock().unwrap();
120            if !*lock {
121                *lock = true;
122                unsafe { xed_sys::xed_tables_init() }
123            }
124        }
125
126        Self {
127            mode,
128            address_width,
129        }
130    }
131
132    pub fn decode(&self, instr: &[u8]) -> Result<DecodedInstr, XedError> {
133        let mut decoded = ::std::mem::MaybeUninit::<xed_sys::xed_decoded_inst_t>::uninit();
134        unsafe {
135            xed_sys::xed_decoded_inst_zero(decoded.as_mut_ptr());
136            xed_sys::xed_decoded_inst_set_mode(
137                decoded.as_mut_ptr(),
138                self.mode.to_xed(),
139                self.address_width.to_xed(),
140            );
141
142            let xed_error: xed_sys::xed_error_enum_t = xed_sys::xed_decode(
143                decoded.as_mut_ptr(),
144                instr.as_ptr(),
145                instr.len().try_into().unwrap(),
146            );
147            if xed_error == xed_sys::XED_ERROR_NONE {
148                let decoded = decoded.assume_init();
149                Ok(DecodedInstr(decoded))
150            } else {
151                Err(XedError(xed_error))
152            }
153        }
154    }
155}
156
157pub struct DecodedInstr(xed_sys::xed_decoded_inst_s);
158
159impl DecodedInstr {
160    pub fn operands(&self) -> Operands<'_> {
161        Operands(self)
162    }
163
164    pub fn memory_accesses(&self) -> MemoryAccesses<'_> {
165        MemoryAccesses(self)
166    }
167
168    pub fn iclass(&self) -> XedIClass {
169        let iclass = unsafe { xed_decoded_inst_get_iclass(self.as_ptr()) };
170
171        XedIClass::from_u32(iclass).unwrap()
172    }
173
174    pub fn iform(&self) -> XedIForm {
175        let iform = unsafe {
176            let inst = xed_sys::xed_decoded_inst_inst(self.as_ptr());
177            xed_inst_iform_enum(inst)
178        };
179
180        XedIForm::from_u32(iform).unwrap()
181    }
182
183    fn as_ptr(&self) -> *const xed_sys::xed_decoded_inst_s {
184        &self.0
185    }
186
187    fn as_inst(&self) -> *const xed_sys::xed_inst_s {
188        unsafe { xed_decoded_inst_inst(self.as_ptr()) }
189    }
190
191    pub fn display(
192        &self,
193        syntax: XedSyntax,
194        runtime_instruction_address: u64,
195    ) -> impl Display + use<'_> {
196        DisplayDecodedInstr {
197            syntax,
198            instr: self,
199            runtime_instruction_address,
200        }
201    }
202}
203
204impl Display for DecodedInstr {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        Display::fmt(&self.display(XedSyntax::Intel, 0), f)
207    }
208}
209
210pub enum XedSyntax {
211    Intel,
212    Att,
213    Xed,
214}
215
216struct DisplayDecodedInstr<'a> {
217    syntax: XedSyntax,
218    instr: &'a DecodedInstr,
219    runtime_instruction_address: u64,
220}
221
222impl Display for DisplayDecodedInstr<'_> {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        let mut buf = [0u8; 256];
225        unsafe {
226            xed_format_context(
227                match self.syntax {
228                    XedSyntax::Intel => XED_SYNTAX_INTEL,
229                    XedSyntax::Att => XED_SYNTAX_ATT,
230                    XedSyntax::Xed => XED_SYNTAX_XED,
231                },
232                self.instr.as_ptr(),
233                buf.as_mut_ptr() as *mut i8,
234                buf.len() as i32 - 1,
235                self.runtime_instruction_address,
236                std::ptr::null_mut(),
237                None,
238            );
239        }
240
241        f.write_str(
242            CStr::from_bytes_until_nul(&buf)
243                .expect("xed should not overwrite last byte")
244                .to_str()
245                .expect("xed_decoded_inst_dump should return valid UTF-8"),
246        )
247    }
248}
249
250pub struct Operands<'a>(&'a DecodedInstr);
251
252impl<'a> Operands<'a> {
253    #[must_use]
254    pub fn len(&self) -> usize {
255        unsafe { xed_sys::xed_decoded_inst_noperands(self.0.as_ptr()) }
256            .try_into()
257            .unwrap()
258    }
259
260    #[must_use]
261    pub fn is_empty(&self) -> bool {
262        self.len() == 0
263    }
264
265    pub fn get(&self, index: usize) -> Option<Operand<'a>> {
266        let index = index.try_into().unwrap();
267        let operand = unsafe { xed_sys::xed_inst_operand(self.0.as_inst(), index) };
268
269        Some(Operand {
270            source: self.0,
271            index,
272            operand,
273        })
274    }
275}
276
277pub struct Operand<'a> {
278    source: &'a DecodedInstr,
279    index: u32,
280    operand: *const xed_sys::xed_operand_t,
281}
282
283impl<'a> Operand<'a> {
284    fn operand_name(&self) -> xed_sys::xed_operand_enum_t {
285        unsafe { xed_sys::xed_operand_name(self.operand) }
286    }
287
288    pub fn name(&self) -> OperandName {
289        OperandName::from_u32(self.operand_name()).unwrap()
290    }
291
292    pub fn operand_size_bits(&self) -> usize {
293        unsafe {
294            xed_sys::xed_decoded_inst_operand_length_bits(self.source.as_ptr(), self.index)
295                .try_into()
296                .unwrap()
297        }
298    }
299
300    pub fn reg(&self) -> Option<XedReg> {
301        if self.is_reg() {
302            Some(unsafe {
303                XedReg::from_u32(xed_sys::xed_decoded_inst_get_reg(
304                    self.source.as_ptr(),
305                    self.operand_name(),
306                ))
307                .unwrap()
308            })
309        } else {
310            None
311        }
312    }
313
314    pub fn is_reg(&self) -> bool {
315        unsafe { xed_sys::xed_operand_is_register(self.operand_name()) != 0 }
316    }
317
318    pub fn is_imm(&self) -> bool {
319        self.imm_value().is_some()
320    }
321
322    pub fn imm_value(&self) -> Option<u64> {
323        Some(match self.name() {
324            OperandName::Imm0 => unsafe {
325                xed_decoded_inst_get_unsigned_immediate(self.source.as_ptr())
326            },
327            OperandName::Imm0Signed => unsafe {
328                xed_decoded_inst_get_signed_immediate(self.source.as_ptr()) as u32 as u64
329            },
330            OperandName::Imm1 | OperandName::Imm1Bytes => unsafe {
331                xed_decoded_inst_get_second_immediate(self.source.as_ptr()) as u64
332            },
333            _ => return None,
334        })
335    }
336
337    pub fn is_memory_addressing_register(&self) -> bool {
338        unsafe { xed_sys::xed_operand_is_memory_addressing_register(self.operand_name()) != 0 }
339    }
340}
341
342pub struct MemoryAccesses<'a>(&'a DecodedInstr);
343
344impl<'a> MemoryAccesses<'a> {
345    #[must_use]
346    pub fn len(&self) -> usize {
347        unsafe { xed_sys::xed_decoded_inst_number_of_memory_operands(self.0.as_ptr()) }
348            .try_into()
349            .unwrap()
350    }
351
352    #[must_use]
353    pub fn is_empty(&self) -> bool {
354        self.len() == 0
355    }
356
357    pub fn get(&self, index: usize) -> Option<MemoryAccess<'a>> {
358        if index >= self.len() {
359            None
360        } else {
361            Some(MemoryAccess {
362                source: self.0,
363                index: index.try_into().unwrap(),
364            })
365        }
366    }
367}
368
369pub struct MemoryAccess<'a> {
370    source: &'a DecodedInstr,
371    index: u32,
372}
373
374impl std::fmt::Debug for MemoryAccess<'_> {
375    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376        f.debug_struct("MemoryAccess")
377            .field("segment_reg", &self.segment_reg())
378            .field("base_reg", &self.base_reg())
379            .field("index_reg", &self.index_reg())
380            .field("scale", &self.scale())
381            .field("memory_displacement", &self.memory_displacement())
382            .field(
383                "memory_displacement_width",
384                &self.memory_displacement_width(),
385            )
386            .field(
387                "memory_displacement_width_bits",
388                &self.memory_displacement_width_bits(),
389            )
390            .field("is_read", &self.is_read())
391            .field("is_written", &self.is_written())
392            .field("is_written_only", &self.is_written_only())
393            .finish()
394    }
395}
396
397impl MemoryAccess<'_> {
398    fn return_reg(reg: u32) -> Option<XedReg> {
399        if reg == xed_sys::XED_REG_INVALID {
400            None
401        } else {
402            Some(XedReg::from_u32(reg).unwrap())
403        }
404    }
405
406    pub fn segment_reg(&self) -> Option<XedReg> {
407        unsafe {
408            Self::return_reg(xed_sys::xed_decoded_inst_get_seg_reg(
409                self.source.as_ptr(),
410                self.index,
411            ))
412        }
413    }
414
415    pub fn base_reg(&self) -> Option<XedReg> {
416        unsafe {
417            Self::return_reg(xed_sys::xed_decoded_inst_get_base_reg(
418                self.source.as_ptr(),
419                self.index,
420            ))
421        }
422    }
423
424    pub fn scale(&self) -> u32 {
425        unsafe { xed_sys::xed_decoded_inst_get_scale(self.source.as_ptr(), self.index) }
426    }
427
428    pub fn memory_displacement(&self) -> i64 {
429        unsafe {
430            xed_sys::xed_decoded_inst_get_memory_displacement(self.source.as_ptr(), self.index)
431        }
432    }
433
434    pub fn memory_displacement_width(&self) -> u32 {
435        unsafe {
436            xed_sys::xed_decoded_inst_get_memory_displacement_width(
437                self.source.as_ptr(),
438                self.index,
439            )
440        }
441    }
442
443    pub fn memory_displacement_width_bits(&self) -> u32 {
444        unsafe {
445            xed_sys::xed_decoded_inst_get_memory_displacement_width_bits(
446                self.source.as_ptr(),
447                self.index,
448            )
449        }
450    }
451
452    pub fn is_read(&self) -> bool {
453        unsafe { xed_sys::xed_decoded_inst_mem_read(self.source.as_ptr(), self.index) != 0 }
454    }
455
456    pub fn is_written(&self) -> bool {
457        unsafe { xed_sys::xed_decoded_inst_mem_written(self.source.as_ptr(), self.index) != 0 }
458    }
459
460    pub fn is_written_only(&self) -> bool {
461        unsafe { xed_sys::xed_decoded_inst_mem_written_only(self.source.as_ptr(), self.index) != 0 }
462    }
463
464    pub fn index_reg(&self) -> Option<XedReg> {
465        unsafe {
466            Self::return_reg(xed_sys::xed_decoded_inst_get_index_reg(
467                self.source.as_ptr(),
468                self.index,
469            ))
470        }
471    }
472}
473
474#[cfg(test)]
475mod tests {
476    use crate::{AddressWidth, MachineMode, Xed};
477
478    #[test]
479    pub fn imm_operands() {
480        let xed = Xed::new(MachineMode::Long64, AddressWidth::Width64b);
481        let instr = xed.decode(&[0x48, 0xC1, 0xE0, 0x03]).unwrap();
482        let _op = instr.operands().get(1).unwrap();
483    }
484
485    #[test]
486    pub fn iclass_valid() {
487        let xed = Xed::new(MachineMode::Long64, AddressWidth::Width64b);
488        let instr = xed.decode(&[0x40, 0x0F, 0x18, 0x32]).unwrap();
489
490        instr.iclass();
491    }
492
493    #[test]
494    pub fn display() {
495        let xed = Xed::new(MachineMode::Long64, AddressWidth::Width64b);
496        let instr = xed.decode(&[0x00, 0xd3]).unwrap();
497
498        assert_eq!(instr.to_string(), "add bl, dl");
499    }
500}