exarmo_aarch64_capi/lib.rs
1//! The C face of the exarmo-aarch64 disassembler, declared in
2//! `include/exarmo/aarch64.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/aarch64.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#![warn(missing_docs)]
12
13use std::fmt::Write;
14
15use exarmo_aarch64::{Encoding, Instruction, Mnemonic};
16pub use exarmo_core::capi::{Branch, FlagEffect, Status, Str, TextSize, Token};
17use exarmo_core::capi::{
18 Spans, Storage, buffer, bytes, deliver, fill, guarded, with_held, write_tokens,
19};
20
21pub mod model;
22pub mod tables;
23
24use model::{CIntrinsic, CIntrinsicDef, CIntrinsicTypeDef, COperand};
25
26/// Opaque storage for an `Instruction`, `exarmo_aarch64_instruction` in C.
27#[repr(C)]
28#[derive(Clone, Copy)]
29pub struct CInstruction {
30 opaque: [u64; 3],
31}
32
33// SAFETY: the assertions below hold the storage to an `Instruction`'s size
34// and alignment.
35unsafe impl Storage for CInstruction {
36 type Instruction = Instruction;
37}
38
39const _: () = assert!(std::mem::size_of::<Instruction>() <= std::mem::size_of::<CInstruction>());
40const _: () = assert!(std::mem::align_of::<Instruction>() <= std::mem::align_of::<CInstruction>());
41
42/// How many bytes of storage a decode writes, as the library was built.
43///
44/// The header fixes the size of the `exarmo_aarch64_instruction` a caller
45/// reserves. A caller linked against a library from another release checks
46/// this against it.
47#[unsafe(no_mangle)]
48pub extern "C" fn exarmo_aarch64_instruction_size() -> usize {
49 std::mem::size_of::<CInstruction>()
50}
51
52/// Decode `bits` into `out`, which is written only on `Status::Ok`.
53///
54/// # Safety
55///
56/// A non-null `out` must point to writable storage for a `CInstruction`.
57#[unsafe(no_mangle)]
58pub unsafe extern "C" fn exarmo_aarch64_decode_word(bits: u32, out: *mut CInstruction) -> Status {
59 if out.is_null() {
60 return Status::Failed;
61 }
62 unsafe { deliver(|| exarmo_aarch64::decode_word(bits), out) }
63}
64
65/// The former name of [`exarmo_aarch64_decode_word`], which the header marks
66/// deprecated.
67///
68/// # Safety
69///
70/// See [`exarmo_aarch64_decode_word`].
71#[unsafe(no_mangle)]
72pub unsafe extern "C" fn exarmo_aarch64_decode(bits: u32, out: *mut CInstruction) -> Status {
73 unsafe { exarmo_aarch64_decode_word(bits, out) }
74}
75
76/// Decode the instruction at the start of the `len` bytes at `bytes` into
77/// `out`, which is written only on `Status::Ok`.
78///
79/// # Safety
80///
81/// A non-null `bytes` must point to `len` readable bytes, and a non-null
82/// `out` to writable storage for a `CInstruction`.
83#[unsafe(no_mangle)]
84pub unsafe extern "C" fn exarmo_aarch64_decode_bytes(
85 bytes: *const u8,
86 len: usize,
87 out: *mut CInstruction,
88) -> Status {
89 match (unsafe { self::bytes(bytes, len) }, out.is_null()) {
90 (Some(code), false) => unsafe { deliver(|| exarmo_aarch64::decode_bytes(code), out) },
91 _ => Status::Failed,
92 }
93}
94
95/// Which encoding the instruction is. Returns `EXARMO_AARCH64_ENCODING_COUNT`
96/// for a null pointer.
97///
98/// # Safety
99///
100/// A non-null `inst` must point to an instruction written by a successful
101/// decode.
102#[unsafe(no_mangle)]
103pub unsafe extern "C" fn exarmo_aarch64_instruction_encoding(inst: *const CInstruction) -> u32 {
104 let none = Encoding::COUNT as u32;
105 unsafe { with_held(inst, none, |inst| inst.encoding() as u32) }
106}
107
108/// The mnemonic the instruction is written with. Returns
109/// `EXARMO_AARCH64_MNEMONIC_COUNT` for a null pointer.
110///
111/// # Safety
112///
113/// A non-null `inst` must point to an instruction written by a successful
114/// decode.
115#[unsafe(no_mangle)]
116pub unsafe extern "C" fn exarmo_aarch64_instruction_mnemonic(inst: *const CInstruction) -> u32 {
117 let none = Mnemonic::COUNT as u32;
118 unsafe { with_held(inst, none, |inst| inst.mnemonic() as u32) }
119}
120
121/// The mnemonic an encoding is written with. Returns
122/// `EXARMO_AARCH64_MNEMONIC_COUNT` for a value that is no encoding.
123#[unsafe(no_mangle)]
124pub extern "C" fn exarmo_aarch64_encoding_mnemonic(encoding: u32) -> u32 {
125 Encoding::from_index(encoding as usize).map_or(Mnemonic::COUNT as u32, |e| e.mnemonic() as u32)
126}
127
128/// An encoding's name, or empty for a value that is no encoding.
129#[unsafe(no_mangle)]
130pub extern "C" fn exarmo_aarch64_encoding_name(encoding: u32) -> Str {
131 Encoding::from_index(encoding as usize).map_or(Str::EMPTY, |e| Str::of(e.name()))
132}
133
134/// How many bytes an encoding is, or 0 for a value that is no encoding.
135///
136/// Every A64 encoding is four. The AArch32 face answers 2 or 4, and a
137/// caller stepping either instruction stream asks the same question.
138#[unsafe(no_mangle)]
139pub extern "C" fn exarmo_aarch64_encoding_length(encoding: u32) -> u8 {
140 Encoding::from_index(encoding as usize).map_or(0, |e| e.length())
141}
142
143/// How many bytes of the instruction stream the instruction is, or 0 for a
144/// null pointer.
145///
146/// # Safety
147///
148/// A non-null `inst` must point to an instruction written by a successful
149/// decode.
150#[unsafe(no_mangle)]
151pub unsafe extern "C" fn exarmo_aarch64_instruction_length(inst: *const CInstruction) -> u8 {
152 unsafe { with_held(inst, 0, |inst| inst.encoding().length()) }
153}
154
155/// Whether the word `inst` was decoded from is CONSTRAINED UNPREDICTABLE,
156/// through its decode's tests or a bit its diagram writes `(0)` or `(1)`.
157/// Returns false for a null pointer.
158///
159/// # Safety
160///
161/// A non-null `inst` must point to an instruction written by a successful
162/// decode.
163#[unsafe(no_mangle)]
164pub unsafe extern "C" fn exarmo_aarch64_instruction_unpredictable(
165 inst: *const CInstruction,
166) -> bool {
167 unsafe { with_held(inst, false, |inst| inst.unpredictable()) }
168}
169
170/// A mnemonic's text, or empty for a value that is no mnemonic.
171#[unsafe(no_mangle)]
172pub extern "C" fn exarmo_aarch64_mnemonic_name(mnemonic: u32) -> Str {
173 Mnemonic::from_index(mnemonic as usize).map_or(Str::EMPTY, |m| Str::of(m.name()))
174}
175
176/// What the instruction does with the condition flags. Nothing for a null
177/// pointer.
178///
179/// # Safety
180///
181/// A non-null `inst` must point to an instruction written by a successful
182/// decode.
183#[unsafe(no_mangle)]
184pub unsafe extern "C" fn exarmo_aarch64_instruction_flags(inst: *const CInstruction) -> FlagEffect {
185 let none = FlagEffect::from(exarmo_aarch64::FlagEffect::NONE);
186 unsafe { with_held(inst, none, |inst| inst.flags().into()) }
187}
188
189/// What the instruction does to the flow of control, as it reads at
190/// `address`. Nothing for a null pointer.
191///
192/// # Safety
193///
194/// A non-null `inst` must point to an instruction written by a successful
195/// decode.
196#[unsafe(no_mangle)]
197pub unsafe extern "C" fn exarmo_aarch64_instruction_branch(
198 inst: *const CInstruction,
199 address: u64,
200) -> Branch {
201 unsafe { with_held(inst, Branch::NONE, |inst| inst.at(address).branch().into()) }
202}
203
204/// Write the instruction's operands into `out`, up to `capacity`. Returns
205/// how many the instruction has.
206///
207/// # Safety
208///
209/// A non-null `inst` must point to an instruction written by a successful
210/// decode. A non-null `out` must point to `capacity` writable operands.
211#[unsafe(no_mangle)]
212pub unsafe extern "C" fn exarmo_aarch64_instruction_operands(
213 inst: *const CInstruction,
214 out: *mut COperand,
215 capacity: usize,
216) -> usize {
217 unsafe {
218 with_held(inst, 0, |inst| {
219 fill(
220 out,
221 capacity,
222 inst.operands().iter().map(|op| COperand::from(*op)),
223 )
224 })
225 }
226}
227
228/// Write the instruction's text and tokens into the caller's buffers.
229///
230/// # Safety
231///
232/// A non-null `inst` must point to an instruction written by a successful
233/// decode. A non-null `text` must point to `text_capacity` writable bytes and a
234/// non-null `tokens` to `token_capacity` writable tokens.
235#[unsafe(no_mangle)]
236pub unsafe extern "C" fn exarmo_aarch64_instruction_tokens(
237 inst: *const CInstruction,
238 address: u64,
239 text: *mut u8,
240 text_capacity: usize,
241 tokens: *mut Token,
242 token_capacity: usize,
243) -> TextSize {
244 unsafe { write_tokens(inst, address, text, text_capacity, tokens, token_capacity) }
245}
246
247/// Write the instruction's text into the caller's buffer. Returns the
248/// length of the whole text.
249///
250/// # Safety
251///
252/// See [`exarmo_aarch64_instruction_tokens`].
253#[unsafe(no_mangle)]
254pub unsafe extern "C" fn exarmo_aarch64_instruction_text(
255 inst: *const CInstruction,
256 address: u64,
257 text: *mut u8,
258 capacity: usize,
259) -> usize {
260 unsafe {
261 exarmo_aarch64_instruction_tokens(inst, address, text, capacity, std::ptr::null_mut(), 0)
262 }
263 .length
264}
265
266/// Write a system register's name into the caller's buffer. Returns the
267/// length of the whole name.
268///
269/// # Safety
270///
271/// A non-null `name` must point to `capacity` writable bytes.
272#[unsafe(no_mangle)]
273pub unsafe extern "C" fn exarmo_aarch64_sysreg_name(
274 encoding: u16,
275 write: bool,
276 name: *mut u8,
277 capacity: usize,
278) -> usize {
279 let name = unsafe { buffer(name, capacity) };
280 guarded(0, || {
281 let reg = if write {
282 exarmo_aarch64::SysReg::write(encoding)
283 } else {
284 exarmo_aarch64::SysReg::read(encoding)
285 };
286 let mut spans = Spans::new(name, &mut []);
287 match write!(spans, "{reg}") {
288 Ok(()) => spans.finish().length,
289 Err(_) => 0,
290 }
291 })
292}
293
294/// Write the ACLE intrinsics the instruction realises into `out`, up to
295/// `capacity` of them. Returns how many it has.
296///
297/// The instruction cannot always tell them apart, since signed and unsigned
298/// bytes are the same bytes. Where several are listed they are ordered by
299/// what a reader would write first, and `out[0]` is the one to show.
300///
301/// The list is every intrinsic the instruction's own operands allow, so a
302/// list of one is the only one it can be. Each carries its own arguments,
303/// and they differ. CMGT is vcgt with its operands one way round and vclt
304/// with them the other, so a caller showing an intrinsic other than
305/// `out[0]` reads that one's arguments.
306///
307/// Each argument says where the instruction holds it, as an index into
308/// `exarmo_aarch64_instruction_operands`. `exarmo_aarch64_intrinsic_at`
309/// gives the name, signature and types for an `id`.
310///
311/// # Safety
312///
313/// `inst` must be a pointer `exarmo_aarch64_decode_word` filled, and `out` must be
314/// writable for `capacity` elements, or null when `capacity` is zero.
315#[unsafe(no_mangle)]
316pub unsafe extern "C" fn exarmo_aarch64_instruction_intrinsics(
317 inst: *const CInstruction,
318 out: *mut CIntrinsic,
319 capacity: usize,
320) -> usize {
321 unsafe {
322 with_held(inst, 0, |inst| {
323 fill(
324 out,
325 capacity,
326 inst.intrinsics().iter().map(CIntrinsic::from),
327 )
328 })
329 }
330}
331
332/// Write the intrinsic `id` names into `out`. Returns false, leaving `out`
333/// untouched, if `id` names none.
334///
335/// Every string points into the library and lives as long as it does.
336///
337/// # Safety
338///
339/// `out` must be writable, and is written only when this returns true.
340#[unsafe(no_mangle)]
341pub unsafe extern "C" fn exarmo_aarch64_intrinsic_at(id: u32, out: *mut CIntrinsicDef) -> bool {
342 if out.is_null() {
343 return false;
344 }
345 guarded(false, || {
346 let Some(def) = exarmo_aarch64::intrinsics::DEFS.get(id as usize) else {
347 return false;
348 };
349 unsafe { out.write(CIntrinsicDef::from(def)) };
350 true
351 })
352}
353
354/// Write what the C type `ty` is into `out`. Returns false, leaving `out`
355/// untouched, if `ty` is not one.
356///
357/// A definition's `result` and `parameters` are these indexes. There are
358/// far fewer types than parameters, so a caller builds its own type for
359/// each of these once.
360///
361/// The name points into the library and lives as long as it does.
362///
363/// # Safety
364///
365/// `out` must be writable, and is written only when this returns true.
366#[unsafe(no_mangle)]
367pub unsafe extern "C" fn exarmo_aarch64_intrinsic_type_at(
368 ty: u32,
369 out: *mut CIntrinsicTypeDef,
370) -> bool {
371 if out.is_null() {
372 return false;
373 }
374 guarded(false, || {
375 let Some(def) = exarmo_aarch64::intrinsics::TYPES.get(ty as usize) else {
376 return false;
377 };
378 unsafe { out.write(CIntrinsicTypeDef::from(def)) };
379 true
380 })
381}