Skip to main content

exarmo_aarch32_capi/
lib.rs

1//! The C face of the exarmo-aarch32 disassembler, declared in
2//! `include/exarmo/aarch32.h`.
3//!
4//! An instruction is decoded once into an opaque value the caller holds,
5//! and then read through functions: what it is, what it does to the flags,
6//! its operands as `include/exarmo/aarch32.h` lays them out, and its text as spans
7//! of a buffer the caller owns. Nothing allocates on the caller's behalf,
8//! and no panic crosses the boundary. Each entry point catches one and
9//! reports a failure.
10//!
11//! A32 and T32 are two decode entry points into one instruction. A T32
12//! decode is told the IT state, since a 16-bit encoding takes its
13//! condition from a preceding IT instruction, and a caller that tracks the
14//! blocks advances the state through `exarmo_aarch32_it_state_after`.
15
16#![warn(missing_docs)]
17
18use exarmo_aarch32::{Cond, Encoding, Instruction, ItState, Mnemonic};
19pub use exarmo_core::capi::{Branch, FlagEffect, Status, Str, TextSize, Token};
20use exarmo_core::capi::{Storage, bytes, deliver, fill, guarded, with_held, write_tokens};
21
22pub mod model;
23pub mod tables;
24
25use model::{COperand, SysReg};
26
27/// Opaque storage for an `Instruction`, `exarmo_aarch32_instruction` in C.
28#[repr(C)]
29#[derive(Clone, Copy)]
30pub struct CInstruction {
31    opaque: [u64; 5],
32}
33
34// SAFETY: the assertions below hold the storage to an `Instruction`'s size
35// and alignment.
36unsafe impl Storage for CInstruction {
37    type Instruction = Instruction;
38}
39
40const _: () = assert!(std::mem::size_of::<Instruction>() <= std::mem::size_of::<CInstruction>());
41const _: () = assert!(std::mem::align_of::<Instruction>() <= std::mem::align_of::<CInstruction>());
42
43/// How many bytes of storage a decode writes, as the library was built.
44///
45/// The header fixes the size of the `exarmo_aarch32_instruction` a caller
46/// reserves. A caller linked against a library from another release checks
47/// this against it.
48#[unsafe(no_mangle)]
49pub extern "C" fn exarmo_aarch32_instruction_size() -> usize {
50    std::mem::size_of::<CInstruction>()
51}
52
53/// Whether a T32 instruction is inside an IT block, `exarmo_aarch32_it_kind`.
54#[repr(u8)]
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum ItKind {
57    /// The caller has not tracked the blocks. Read as outside one.
58    Unknown = 0,
59    /// Outside any block.
60    Outside = 1,
61    /// Inside a block, under `cond`, with `mask` of it left.
62    Inside = 2,
63}
64
65/// The IT state a T32 decode is told, `exarmo_aarch32_it_state`.
66#[repr(C)]
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct CItState {
69    /// Which of the three, an `ItKind`.
70    pub kind: u8,
71    /// Inside a block, the condition this instruction runs under, an
72    /// `exarmo_aarch32_cond`.
73    pub cond: u8,
74    /// Inside a block, the low four bits of ITSTATE, which say what is left
75    /// of it.
76    pub mask: u8,
77}
78
79impl From<CItState> for ItState {
80    fn from(state: CItState) -> Self {
81        match state.kind {
82            1 => ItState::Outside,
83            2 => ItState::Inside {
84                cond: Cond::from_bits(state.cond).unwrap_or(Cond::Al),
85                mask: state.mask & 0xf,
86            },
87            _ => ItState::Unknown,
88        }
89    }
90}
91
92impl From<ItState> for CItState {
93    fn from(state: ItState) -> Self {
94        match state {
95            ItState::Unknown => CItState {
96                kind: ItKind::Unknown as u8,
97                cond: 0,
98                mask: 0,
99            },
100            ItState::Outside => CItState {
101                kind: ItKind::Outside as u8,
102                cond: 0,
103                mask: 0,
104            },
105            ItState::Inside { cond, mask } => CItState {
106                kind: ItKind::Inside as u8,
107                cond: cond as u8,
108                mask,
109            },
110        }
111    }
112}
113
114/// Decode the A32 word `bits` into `out`, which is written only on
115/// `Status::Ok`.
116///
117/// # Safety
118///
119/// A non-null `out` must point to writable storage for a `CInstruction`.
120#[unsafe(no_mangle)]
121pub unsafe extern "C" fn exarmo_aarch32_decode_a32_word(
122    bits: u32,
123    out: *mut CInstruction,
124) -> Status {
125    if out.is_null() {
126        return Status::Failed;
127    }
128    unsafe { deliver(|| exarmo_aarch32::a32::decode_word(bits), out) }
129}
130
131/// The former name of [`exarmo_aarch32_decode_a32_word`], which the header
132/// marks deprecated.
133///
134/// # Safety
135///
136/// See [`exarmo_aarch32_decode_a32_word`].
137#[unsafe(no_mangle)]
138pub unsafe extern "C" fn exarmo_aarch32_decode_a32(bits: u32, out: *mut CInstruction) -> Status {
139    unsafe { exarmo_aarch32_decode_a32_word(bits, out) }
140}
141
142/// Decode the A32 instruction at the start of the `len` bytes at `bytes` into
143/// `out`, which is written only on `Status::Ok`.
144///
145/// # Safety
146///
147/// A non-null `bytes` must point to `len` readable bytes, and a non-null
148/// `out` to writable storage for a `CInstruction`.
149#[unsafe(no_mangle)]
150pub unsafe extern "C" fn exarmo_aarch32_decode_a32_bytes(
151    bytes: *const u8,
152    len: usize,
153    out: *mut CInstruction,
154) -> Status {
155    match (unsafe { self::bytes(bytes, len) }, out.is_null()) {
156        (Some(code), false) => unsafe { deliver(|| exarmo_aarch32::a32::decode_bytes(code), out) },
157        _ => Status::Failed,
158    }
159}
160
161/// Decode the T32 word `bits`, its first halfword in the high half, under
162/// the IT state `state`, into `out`, which is written only on `Status::Ok`.
163///
164/// # Safety
165///
166/// A non-null `out` must point to writable storage for a `CInstruction`.
167#[unsafe(no_mangle)]
168pub unsafe extern "C" fn exarmo_aarch32_decode_t32_word(
169    bits: u32,
170    state: CItState,
171    out: *mut CInstruction,
172) -> Status {
173    if out.is_null() {
174        return Status::Failed;
175    }
176    unsafe { deliver(|| exarmo_aarch32::t32::decode_word(bits, state.into()), out) }
177}
178
179/// The former name of [`exarmo_aarch32_decode_t32_word`], which the header
180/// marks deprecated.
181///
182/// # Safety
183///
184/// See [`exarmo_aarch32_decode_t32_word`].
185#[unsafe(no_mangle)]
186pub unsafe extern "C" fn exarmo_aarch32_decode_t32(
187    bits: u32,
188    state: CItState,
189    out: *mut CInstruction,
190) -> Status {
191    unsafe { exarmo_aarch32_decode_t32_word(bits, state, out) }
192}
193
194/// Decode the T32 instruction at the start of the `len` bytes at `bytes`,
195/// under the IT state `state`, into `out`, which is written only on
196/// `Status::Ok`.
197///
198/// # Safety
199///
200/// A non-null `bytes` must point to `len` readable bytes, and a non-null
201/// `out` to writable storage for a `CInstruction`.
202#[unsafe(no_mangle)]
203pub unsafe extern "C" fn exarmo_aarch32_decode_t32_bytes(
204    bytes: *const u8,
205    len: usize,
206    state: CItState,
207    out: *mut CInstruction,
208) -> Status {
209    match (unsafe { self::bytes(bytes, len) }, out.is_null()) {
210        (Some(code), false) => unsafe {
211            deliver(
212                || exarmo_aarch32::t32::decode_bytes(code, state.into()),
213                out,
214            )
215        },
216        _ => Status::Failed,
217    }
218}
219
220/// How many bytes the T32 instruction beginning with the halfword `hw1`
221/// takes, 2 or 4.
222#[unsafe(no_mangle)]
223pub extern "C" fn exarmo_aarch32_t32_length(hw1: u16) -> u8 {
224    guarded(0, || exarmo_aarch32::t32::length(hw1))
225}
226
227/// The IT state the instruction after `inst` is in, on the straight line,
228/// given that `inst` was decoded under `state`. Returns `state` itself for a
229/// null pointer.
230///
231/// # Safety
232///
233/// A non-null `inst` must point to an instruction written by a successful
234/// decode.
235#[unsafe(no_mangle)]
236pub unsafe extern "C" fn exarmo_aarch32_it_state_after(
237    state: CItState,
238    inst: *const CInstruction,
239) -> CItState {
240    unsafe { with_held(inst, state, |inst| ItState::from(state).after(inst).into()) }
241}
242
243/// How many bytes of the instruction stream the instruction is, 4 for an
244/// A32 instruction and 2 or 4 for a T32 one. Returns 0 for a null pointer.
245///
246/// # Safety
247///
248/// A non-null `inst` must point to an instruction written by a successful
249/// decode.
250#[unsafe(no_mangle)]
251pub unsafe extern "C" fn exarmo_aarch32_instruction_length(inst: *const CInstruction) -> u8 {
252    unsafe { with_held(inst, 0, |inst| inst.encoding().length()) }
253}
254
255/// Whether the word `inst` was decoded from is CONSTRAINED UNPREDICTABLE,
256/// through its decode's tests or a bit its diagram writes `(0)` or `(1)`.
257/// Returns false for a null pointer.
258///
259/// # Safety
260///
261/// A non-null `inst` must point to an instruction written by a successful
262/// decode.
263#[unsafe(no_mangle)]
264pub unsafe extern "C" fn exarmo_aarch32_instruction_unpredictable(
265    inst: *const CInstruction,
266) -> bool {
267    unsafe { with_held(inst, false, |inst| inst.unpredictable()) }
268}
269
270/// Which encoding the instruction is. Returns `EXARMO_AARCH32_ENCODING_COUNT`
271/// for a null pointer.
272///
273/// # Safety
274///
275/// A non-null `inst` must point to an instruction written by a successful
276/// decode.
277#[unsafe(no_mangle)]
278pub unsafe extern "C" fn exarmo_aarch32_instruction_encoding(inst: *const CInstruction) -> u32 {
279    let none = Encoding::COUNT as u32;
280    unsafe { with_held(inst, none, |inst| inst.encoding() as u32) }
281}
282
283/// The mnemonic the instruction is written with. Returns
284/// `EXARMO_AARCH32_MNEMONIC_COUNT` for a null pointer.
285///
286/// # Safety
287///
288/// A non-null `inst` must point to an instruction written by a successful
289/// decode.
290#[unsafe(no_mangle)]
291pub unsafe extern "C" fn exarmo_aarch32_instruction_mnemonic(inst: *const CInstruction) -> u32 {
292    let none = Mnemonic::COUNT as u32;
293    unsafe { with_held(inst, none, |inst| inst.mnemonic() as u32) }
294}
295
296/// The mnemonic an encoding is written with. Returns
297/// `EXARMO_AARCH32_MNEMONIC_COUNT` for a value that is no encoding.
298#[unsafe(no_mangle)]
299pub extern "C" fn exarmo_aarch32_encoding_mnemonic(encoding: u32) -> u32 {
300    Encoding::from_index(encoding as usize).map_or(Mnemonic::COUNT as u32, |e| e.mnemonic() as u32)
301}
302
303/// An encoding's name, or empty for a value that is no encoding.
304#[unsafe(no_mangle)]
305pub extern "C" fn exarmo_aarch32_encoding_name(encoding: u32) -> Str {
306    Encoding::from_index(encoding as usize).map_or(Str::EMPTY, |e| Str::of(e.name()))
307}
308
309/// How many bytes an encoding is, or 0 for a value that is no encoding.
310#[unsafe(no_mangle)]
311pub extern "C" fn exarmo_aarch32_encoding_length(encoding: u32) -> u8 {
312    Encoding::from_index(encoding as usize).map_or(0, |e| e.length())
313}
314
315/// A mnemonic's text, or empty for a value that is no mnemonic.
316#[unsafe(no_mangle)]
317pub extern "C" fn exarmo_aarch32_mnemonic_name(mnemonic: u32) -> Str {
318    Mnemonic::from_index(mnemonic as usize).map_or(Str::EMPTY, |m| Str::of(m.name()))
319}
320
321/// What the instruction does with the condition flags. Nothing for a null
322/// pointer.
323///
324/// # Safety
325///
326/// A non-null `inst` must point to an instruction written by a successful
327/// decode.
328#[unsafe(no_mangle)]
329pub unsafe extern "C" fn exarmo_aarch32_instruction_flags(inst: *const CInstruction) -> FlagEffect {
330    let none = FlagEffect::from(exarmo_aarch32::FlagEffect::NONE);
331    unsafe { with_held(inst, none, |inst| inst.flags().into()) }
332}
333
334/// What the instruction does to the flow of control, as it reads at
335/// `address`. Nothing for a null pointer.
336///
337/// # Safety
338///
339/// A non-null `inst` must point to an instruction written by a successful
340/// decode.
341#[unsafe(no_mangle)]
342pub unsafe extern "C" fn exarmo_aarch32_instruction_branch(
343    inst: *const CInstruction,
344    address: u64,
345) -> Branch {
346    unsafe { with_held(inst, Branch::NONE, |inst| inst.at(address).branch().into()) }
347}
348
349/// Write the system register the instruction accesses into `out`, and
350/// return true. Returns false, leaving `out` untouched, for an instruction
351/// that reaches none or a null pointer.
352///
353/// # Safety
354///
355/// A non-null `inst` must point to an instruction written by a successful
356/// decode. A non-null `out` must point to a writable `exarmo_aarch32_sysreg`.
357#[unsafe(no_mangle)]
358pub unsafe extern "C" fn exarmo_aarch32_instruction_sysreg(
359    inst: *const CInstruction,
360    out: *mut SysReg,
361) -> bool {
362    match unsafe { with_held(inst, None, |inst| inst.system_register()) } {
363        Some(reg) if !out.is_null() => {
364            unsafe { out.write(reg.into()) };
365            true
366        }
367        _ => false,
368    }
369}
370
371/// The name of the register with this key in this space, accessed in this
372/// direction, or empty where the architecture names none.
373#[unsafe(no_mangle)]
374pub extern "C" fn exarmo_aarch32_sysreg_name(space: u8, encoding: u32, write: bool) -> Str {
375    exarmo_aarch32::SysRegSpace::from_bits(space)
376        .and_then(|space| exarmo_aarch32::SysReg::new(space, encoding, write).name())
377        .map_or(Str::EMPTY, Str::of)
378}
379
380/// Write the instruction's operands into `out`, up to `capacity`. Returns
381/// how many the instruction has.
382///
383/// # Safety
384///
385/// A non-null `inst` must point to an instruction written by a successful
386/// decode. A non-null `out` must point to `capacity` writable operands.
387#[unsafe(no_mangle)]
388pub unsafe extern "C" fn exarmo_aarch32_instruction_operands(
389    inst: *const CInstruction,
390    out: *mut COperand,
391    capacity: usize,
392) -> usize {
393    unsafe {
394        with_held(inst, 0, |inst| {
395            fill(
396                out,
397                capacity,
398                inst.operands().iter().map(|op| COperand::from(*op)),
399            )
400        })
401    }
402}
403
404/// Write the instruction's text and tokens into the caller's buffers.
405///
406/// # Safety
407///
408/// A non-null `inst` must point to an instruction written by a successful
409/// decode. A non-null `text` must point to `text_capacity` writable bytes and a
410/// non-null `tokens` to `token_capacity` writable tokens.
411#[unsafe(no_mangle)]
412pub unsafe extern "C" fn exarmo_aarch32_instruction_tokens(
413    inst: *const CInstruction,
414    address: u64,
415    text: *mut u8,
416    text_capacity: usize,
417    tokens: *mut Token,
418    token_capacity: usize,
419) -> TextSize {
420    unsafe { write_tokens(inst, address, text, text_capacity, tokens, token_capacity) }
421}
422
423/// Write the instruction's text into the caller's buffer. Returns the
424/// length of the whole text.
425///
426/// # Safety
427///
428/// See [`exarmo_aarch32_instruction_tokens`].
429#[unsafe(no_mangle)]
430pub unsafe extern "C" fn exarmo_aarch32_instruction_text(
431    inst: *const CInstruction,
432    address: u64,
433    text: *mut u8,
434    capacity: usize,
435) -> usize {
436    unsafe {
437        exarmo_aarch32_instruction_tokens(inst, address, text, capacity, std::ptr::null_mut(), 0)
438    }
439    .length
440}