Skip to main content

exarmo_core/
capi.rs

1//! What both runtimes' C libraries share: the caller's buffers, the token and
2//! string types, and the guard that stops a panic crossing into C. Each
3//! library adds its own operand model and entry points.
4
5use core::fmt::{self, Write};
6use std::panic::{AssertUnwindSafe, catch_unwind};
7
8use crate::Decoded;
9use crate::tokens::{OperandIndex, TokenKind, TokenSink};
10
11/// The outcome of a decode, `<prefix>_status`.
12///
13/// One numbering for both faces. An AArch64 decode does not return the last
14/// two, since the A64 index marks no row UNPREDICTABLE or a reserved hint.
15#[repr(u32)]
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Status {
18    /// The instruction decoded.
19    Ok = 0,
20    /// The encoding is allocated to no instruction.
21    Unallocated = 1,
22    /// The instruction's decode says it is UNDEFINED.
23    Undefined = 2,
24    /// The instruction's decode says it executes as a NOP.
25    Nop = 3,
26    /// The library failed internally.
27    Failed = 4,
28    /// The encoding index marks the encoding UNPREDICTABLE.
29    Unpredictable = 5,
30    /// The encoding is a hint the architecture reserves, which behaves as
31    /// a NOP.
32    ReservedHint = 6,
33    /// The bytes ended before the instruction did.
34    Truncated = 7,
35}
36
37impl From<crate::DecodeError> for Status {
38    fn from(error: crate::DecodeError) -> Self {
39        match error {
40            crate::DecodeError::Unallocated => Status::Unallocated,
41            crate::DecodeError::UNDEF => Status::Undefined,
42            crate::DecodeError::NOP => Status::Nop,
43            crate::DecodeError::Unpredictable => Status::Unpredictable,
44            crate::DecodeError::ReservedHint => Status::ReservedHint,
45            crate::DecodeError::Truncated => Status::Truncated,
46        }
47    }
48}
49
50/// A string that is not NUL-terminated.
51#[repr(C)]
52#[derive(Clone, Copy, Debug)]
53pub struct Str {
54    /// The bytes.
55    pub data: *const u8,
56    /// How many.
57    pub length: usize,
58}
59
60// A static string's bytes are read-only and never move, so the pointer is
61// safe to share between threads.
62unsafe impl Send for Str {}
63unsafe impl Sync for Str {}
64
65impl Str {
66    /// A string that lives as long as the library.
67    pub const fn of(s: &'static str) -> Self {
68        Str {
69            data: s.as_ptr(),
70            length: s.len(),
71        }
72    }
73
74    /// The empty string.
75    pub const EMPTY: Str = Str::of("");
76}
77
78/// One token of an instruction's text, a span of the text buffer it was
79/// written into.
80#[repr(C)]
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub struct Token {
83    /// What the token is, a `TokenKind` by number.
84    pub kind: u32,
85    /// Where its text starts in the buffer.
86    pub offset: u32,
87    /// How long its text is.
88    pub length: u32,
89    /// Which operand of the instruction it is part of, or
90    /// [`Token::NO_OPERAND`] for the mnemonic, the tab after it and the
91    /// `, ` between operands.
92    ///
93    /// It sits in padding, so it adds nothing to the token's size.
94    pub operand: u8,
95    /// The number an immediate, integer or address token writes, and zero
96    /// for any other token.
97    pub value: u64,
98}
99
100impl Token {
101    /// What `operand` holds for a token that is part of none. Every
102    /// instruction has far fewer operands than this, so no index can
103    /// collide with it.
104    pub const NO_OPERAND: u8 = 0xFF;
105}
106
107/// How much text and how many tokens an instruction has.
108#[repr(C)]
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub struct TextSize {
111    /// How many tokens.
112    pub tokens: usize,
113    /// The length of the text without its NUL.
114    pub length: usize,
115}
116
117impl TextSize {
118    /// Nothing written.
119    pub const NONE: TextSize = TextSize {
120        tokens: 0,
121        length: 0,
122    };
123}
124
125/// What an instruction does with the condition flags, as C holds it.
126#[repr(C)]
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub struct FlagEffect {
129    /// The flags it writes, N Z C V from bit 3 down.
130    pub writes: u8,
131    /// The flags it reads.
132    pub reads: u8,
133    /// Whether the flags written are a floating-point comparison's.
134    pub float_compare: bool,
135}
136
137/// What an instruction does to the flow of control, as C holds it.
138///
139/// `target` is meaningful only where `has_target` is set.
140#[repr(C)]
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct Branch {
143    /// The kind of branch, a `crate::branch::BranchKind` by number.
144    pub kind: u8,
145    /// Whether the branch is taken only where a test succeeds.
146    pub conditional: bool,
147    /// Whether the instruction names the address it branches to.
148    pub has_target: bool,
149    /// The address it branches to, where `has_target`.
150    pub target: u64,
151}
152
153impl Branch {
154    /// Takes no branch, for a caller that asked with a null pointer or
155    /// whose call failed.
156    pub const NONE: Branch = Branch {
157        kind: crate::branch::BranchKind::None as u8,
158        conditional: false,
159        has_target: false,
160        target: 0,
161    };
162}
163
164impl From<crate::branch::Branch> for Branch {
165    fn from(branch: crate::branch::Branch) -> Self {
166        Branch {
167            kind: branch.kind as u8,
168            conditional: branch.conditional,
169            has_target: branch.target.is_some(),
170            target: branch.target.unwrap_or(0),
171        }
172    }
173}
174
175impl From<crate::flags::FlagEffect> for FlagEffect {
176    fn from(effect: crate::flags::FlagEffect) -> Self {
177        FlagEffect {
178            writes: effect.writes.0,
179            reads: effect.reads.0,
180            float_compare: effect.float_compare,
181        }
182    }
183}
184
185/// A value from a value table, `<prefix>_symbol`.
186#[repr(C)]
187#[derive(Clone, Copy, Debug)]
188pub struct Symbol {
189    /// The bits the encoding holds.
190    pub bits: u16,
191    /// The name the assembly writes, empty where the table has none.
192    pub name: Str,
193}
194
195impl From<crate::view::Symbol> for Symbol {
196    fn from(s: crate::view::Symbol) -> Self {
197        Symbol {
198            bits: s.bits,
199            name: Str::of(s.name),
200        }
201    }
202}
203
204/// A branch target or a literal's address, `<prefix>_label`.
205#[repr(C)]
206#[derive(Clone, Copy, Debug)]
207pub struct Label {
208    /// The offset from the PC the instruction reads, which may run
209    /// backwards.
210    pub offset: i64,
211    /// How many bytes ahead of the instruction the PC reads.
212    pub pc_ahead: u8,
213    /// The alignment in bytes the PC is rounded down to before the offset is
214    /// added, 1 where it is not aligned.
215    pub pc_align: u32,
216}
217
218impl Label {
219    /// The label an offset from the PC names, as the instruction reads the PC.
220    pub fn of(offset: i64, pc: crate::address::PcRead) -> Self {
221        Label {
222            offset,
223            pc_ahead: pc.ahead,
224            pc_align: pc.align,
225        }
226    }
227}
228
229/// A floating-point immediate as C holds it, `<prefix>_fp_imm`.
230#[repr(C)]
231#[derive(Clone, Copy, Debug)]
232pub struct CFpImm {
233    /// The value.
234    pub value: f64,
235    /// The pattern the encoding holds, where `width` says there is one.
236    pub bits: u64,
237    /// How wide that pattern is, or zero where there is none.
238    pub width: u8,
239}
240
241/// Whether a memory operand's base is written back, `<prefix>_writeback`.
242#[repr(u32)]
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub enum Writeback {
245    /// Not written back.
246    None = 0,
247    /// Before the access, with the offset applied.
248    Pre = 1,
249    /// After the access, by the offset.
250    Post = 2,
251}
252
253impl From<crate::view::Writeback> for Writeback {
254    fn from(writeback: crate::view::Writeback) -> Self {
255        match writeback {
256            crate::view::Writeback::None => Writeback::None,
257            crate::view::Writeback::Pre => Writeback::Pre,
258            crate::view::Writeback::Post => Writeback::Post,
259        }
260    }
261}
262
263/// Run `f`, and should it panic, report `fallback` instead.
264pub fn guarded<T>(fallback: T, f: impl FnOnce() -> T) -> T {
265    catch_unwind(AssertUnwindSafe(f)).unwrap_or(fallback)
266}
267
268/// The opaque storage a C face decodes an instruction into,
269/// `exarmo_aarch64_instruction` or `exarmo_aarch32_instruction`.
270///
271/// The header fixes the storage's size, so a caller can hold one without
272/// knowing what the runtime's `Instruction` is. The helpers here read and
273/// write a pointer to the storage as a pointer to the instruction.
274///
275/// # Safety
276///
277/// An implementor must be at least as large and as aligned as
278/// `Self::Instruction`, so that a pointer to one is a valid place to write
279/// an instruction and read it back. Each crate asserts both at compile time
280/// beside its implementation. The instruction is `Copy` so that it has
281/// nothing to drop, since a decode overwrites whatever the storage held.
282pub unsafe trait Storage {
283    /// The runtime's own instruction, which a decode writes into the storage.
284    type Instruction: crate::Decoded + Copy;
285}
286
287/// The instruction a C pointer holds, or none for a null pointer.
288///
289/// # Safety
290///
291/// A non-null `inst` must point to a value that the crate's decode wrote.
292pub unsafe fn held<'a, C: Storage>(inst: *const C) -> Option<&'a C::Instruction> {
293    if inst.is_null() {
294        None
295    } else {
296        Some(unsafe { &*inst.cast::<C::Instruction>() })
297    }
298}
299
300/// Ask something of the instruction a C pointer holds. Gives `none` for a
301/// null pointer, or where the answer panics.
302///
303/// # Safety
304///
305/// As for [`held`].
306pub unsafe fn with_held<C: Storage, T>(
307    inst: *const C,
308    none: T,
309    ask: impl FnOnce(&C::Instruction) -> T,
310) -> T {
311    match unsafe { held(inst) } {
312        Some(inst) => guarded(none, || ask(inst)),
313        None => none,
314    }
315}
316
317/// Write items into a caller's buffer of `capacity` at `out`, as many as fit,
318/// and return how many there are, so a caller whose buffer was too small
319/// learns the size it needed.
320///
321/// # Safety
322///
323/// A non-null `out` must point to `capacity` writable items.
324pub unsafe fn fill<T>(
325    out: *mut T,
326    capacity: usize,
327    items: impl ExactSizeIterator<Item = T>,
328) -> usize {
329    let count = items.len();
330    for (slot, item) in unsafe { buffer(out, capacity) }.iter_mut().zip(items) {
331        *slot = item;
332    }
333    count
334}
335
336/// Write an instruction's text and tokens into the caller's buffers, as it
337/// reads at `address`.
338///
339/// # Safety
340///
341/// As for [`held`]. A non-null `text` must point to `text_capacity` writable
342/// bytes and a non-null `tokens` to `token_capacity` writable tokens.
343pub unsafe fn write_tokens<C: Storage>(
344    inst: *const C,
345    address: u64,
346    text: *mut u8,
347    text_capacity: usize,
348    tokens: *mut Token,
349    token_capacity: usize,
350) -> TextSize {
351    let text = unsafe { buffer(text, text_capacity) };
352    let tokens = unsafe { buffer(tokens, token_capacity) };
353    let write = |inst: &C::Instruction| {
354        let mut spans = Spans::new(text, tokens);
355        match inst.write_tokens_at(address, &mut spans) {
356            Ok(()) => spans.finish(),
357            Err(_) => TextSize::NONE,
358        }
359    };
360    unsafe { with_held(inst, TextSize::NONE, write) }
361}
362
363/// Write a decode's outcome into `out`, which is written only on
364/// `Status::Ok`.
365///
366/// A panic in the decode is reported as `Status::Failed` rather than
367/// unwinding into C.
368///
369/// # Safety
370///
371/// `out` must point to writable storage for a `C`.
372pub unsafe fn deliver<C: Storage>(
373    decoded: impl FnOnce() -> Result<C::Instruction, crate::DecodeError>,
374    out: *mut C,
375) -> Status {
376    guarded(Status::Failed, || match decoded() {
377        Ok(inst) => {
378            // SAFETY: the storage has room for the instruction, as
379            // `Storage` requires, and the instruction is `Copy`, so nothing
380            // the storage held before needs dropping.
381            unsafe { out.cast::<C::Instruction>().write(inst) };
382            Status::Ok
383        }
384        Err(error) => Status::from(error),
385    })
386}
387
388/// A caller's buffer of `capacity` items at `ptr`, empty for a null
389/// pointer or no capacity.
390///
391/// # Safety
392///
393/// A non-null `ptr` must point to `capacity` writable items.
394pub unsafe fn buffer<'a, T>(ptr: *mut T, capacity: usize) -> &'a mut [T] {
395    if ptr.is_null() || capacity == 0 {
396        &mut []
397    } else {
398        unsafe { std::slice::from_raw_parts_mut(ptr, capacity) }
399    }
400}
401
402/// The caller's `len` bytes at `ptr`, or nothing for a null pointer with a
403/// length.
404///
405/// # Safety
406///
407/// A non-null `ptr` must point to `len` readable bytes.
408pub unsafe fn bytes<'a>(ptr: *const u8, len: usize) -> Option<&'a [u8]> {
409    match (ptr.is_null(), len) {
410        (_, 0) => Some(&[]),
411        (true, _) => None,
412        (false, _) => Some(unsafe { std::slice::from_raw_parts(ptr, len) }),
413    }
414}
415
416/// A token sink writing into a caller's text and token buffers. Text beyond
417/// the buffer is counted and dropped, so the caller learns the size it
418/// needed, and the last byte is kept for the NUL.
419pub struct Spans<'a> {
420    text: &'a mut [u8],
421    length: usize,
422    tokens: &'a mut [Token],
423    count: usize,
424}
425
426impl<'a> Spans<'a> {
427    /// A sink writing into the caller's text and token buffers, either of
428    /// which may be empty.
429    pub fn new(text: &'a mut [u8], tokens: &'a mut [Token]) -> Self {
430        Spans {
431            text,
432            length: 0,
433            tokens,
434            count: 0,
435        }
436    }
437
438    fn record(&mut self, kind: TokenKind, operand: OperandIndex, start: usize) {
439        if let Some(slot) = self.tokens.get_mut(self.count) {
440            let (kind, value) = match kind {
441                TokenKind::Mnemonic => (0, 0),
442                TokenKind::Text => (1, 0),
443                TokenKind::Separator => (2, 0),
444                TokenKind::Bracket => (3, 0),
445                TokenKind::Register => (4, 0),
446                TokenKind::Symbol => (5, 0),
447                TokenKind::Immediate(value) => (6, value as u64),
448                TokenKind::Integer(value) => (7, value),
449                TokenKind::Address(address) => (8, address),
450                TokenKind::Float => (9, 0),
451            };
452            *slot = Token {
453                kind,
454                operand: operand.unwrap_or(Token::NO_OPERAND),
455                offset: start as u32,
456                length: (self.length - start) as u32,
457                value,
458            };
459        }
460        self.count += 1;
461    }
462
463    /// Write the NUL where the text ends, or where the buffer does.
464    pub fn finish(self) -> TextSize {
465        if let Some(last) = self.text.len().checked_sub(1) {
466            self.text[self.length.min(last)] = 0;
467        }
468        TextSize {
469            tokens: self.count,
470            length: self.length,
471        }
472    }
473}
474
475impl Write for Spans<'_> {
476    fn write_str(&mut self, s: &str) -> fmt::Result {
477        let room = self.text.len().saturating_sub(1);
478        if self.length < room {
479            let n = s.len().min(room - self.length);
480            self.text[self.length..self.length + n].copy_from_slice(&s.as_bytes()[..n]);
481        }
482        self.length += s.len();
483        Ok(())
484    }
485}
486
487impl TokenSink for Spans<'_> {
488    fn text(&mut self, kind: TokenKind, operand: OperandIndex, text: &str) -> fmt::Result {
489        let start = self.length;
490        self.write_str(text)?;
491        self.record(kind, operand, start);
492        Ok(())
493    }
494
495    fn value(
496        &mut self,
497        kind: TokenKind,
498        operand: OperandIndex,
499        value: &dyn fmt::Display,
500    ) -> fmt::Result {
501        let start = self.length;
502        write!(self, "{value}")?;
503        self.record(kind, operand, start);
504        Ok(())
505    }
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    #[test]
513    fn a_panic_is_reported_not_propagated() {
514        assert_eq!(guarded(7, || panic!("inside")), 7);
515        assert_eq!(guarded(7, || 1), 1);
516    }
517
518    #[test]
519    fn a_text_buffer_is_cut_at_its_capacity_and_terminated() {
520        let mut text = [0xAAu8; 5];
521        let mut spans = Spans::new(&mut text, &mut []);
522        spans.text(TokenKind::Mnemonic, None, "ldr").unwrap();
523        spans.text(TokenKind::Text, None, "\t").unwrap();
524        spans.value(TokenKind::Register, Some(0), &"x0").unwrap();
525        let size = spans.finish();
526        assert_eq!((size.tokens, size.length), (3, 6));
527        assert_eq!(&text, b"ldr\t\0");
528    }
529}