Skip to main content

byteflow/vm/
native.rs

1//! Native (FFI) table for `Opcode::CallNative`.
2//!
3//! # The one rule: never block
4//!
5//! `CallNative` runs **inline** on the worker thread. A native that blocks
6//! stalls every other Flow on that worker. Slow I/O belongs in a dedicated
7//! Flow (`Send`/`Receive`), not here.
8
9use std::sync::Arc;
10
11use crate::bytecode::{Cap, CapRights, NativeIdx, NativeMask, RevocationCell, Value};
12
13use super::fault::Fault;
14
15pub use super::fault::NativeCallError;
16
17/// Result type for a native function.
18pub type NativeResult = Result<Value, Fault>;
19
20/// A host-side function callable from bytecode via `Opcode::CallNative`.
21pub type NativeFn = Arc<dyn Fn(&[Value]) -> NativeResult + Send + Sync>;
22
23/// Immutable, indexable set of natives. Gaps left by [`NativeTableBuilder::register_at`]
24/// are `None` — calling them faults with [`Fault::BadNative`].
25pub struct NativeTable {
26    entries: Vec<Option<(String, NativeFn)>>,
27}
28
29impl NativeTable {
30    pub fn builder() -> NativeTableBuilder {
31        NativeTableBuilder {
32            entries: Vec::new(),
33        }
34    }
35
36    /// Empty table — valid for chunks that never emit `CallNative`.
37    pub fn empty() -> Arc<NativeTable> {
38        Arc::new(NativeTable {
39            entries: Vec::new(),
40        })
41    }
42
43    #[inline]
44    pub fn get(&self, index: u32) -> Option<&NativeFn> {
45        self.entries
46            .get(index as usize)
47            .and_then(|slot| slot.as_ref())
48            .map(|(_, f)| f)
49    }
50
51    pub fn index_of(&self, name: &str) -> Option<u32> {
52        self.entries
53            .iter()
54            .enumerate()
55            .find(|(_, slot)| slot.as_ref().is_some_and(|(n, _)| n == name))
56            .map(|(i, _)| i as u32)
57    }
58
59    /// Slot count including reserved-but-empty gaps (one past the highest
60    /// touched index), not the count of registered functions.
61    pub fn len(&self) -> usize {
62        self.entries.len()
63    }
64
65    pub fn is_empty(&self) -> bool {
66        self.entries.is_empty()
67    }
68
69    pub fn names(&self) -> impl Iterator<Item = &str> {
70        self.entries
71            .iter()
72            .filter_map(|slot| slot.as_ref().map(|(n, _)| n.as_str()))
73    }
74}
75
76/// Highest index [`NativeTableBuilder::register_at`] will allocate.
77/// A `u32` index would otherwise resize the slot `Vec` to `index + 1`.
78pub const MAX_NATIVE_SLOTS: usize = 4096;
79
80/// Host error while building a [`NativeTable`] (duplicate name, occupied slot,
81/// or an index past [`MAX_NATIVE_SLOTS`]).
82///
83/// Category A: the embedder misconfigured FFI. Never a panic — `std_native_table`
84/// and host tables must surface this as `Result`.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum NativeTableError {
87    DuplicateName(String),
88    SlotOccupied {
89        index: u32,
90        name: String,
91    },
92    /// `register_at` asked for an index at or past [`MAX_NATIVE_SLOTS`].
93    IndexTooLarge {
94        index: u32,
95        limit: u32,
96    },
97}
98
99impl std::fmt::Display for NativeTableError {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        match self {
102            NativeTableError::DuplicateName(name) => {
103                write!(f, "duplicate native function registered: '{name}'")
104            }
105            NativeTableError::SlotOccupied { index, name } => {
106                write!(
107                    f,
108                    "native slot {index} already occupied (registering '{name}')"
109                )
110            }
111            NativeTableError::IndexTooLarge { index, limit } => {
112                write!(f, "native slot {index} is past the limit of {limit}")
113            }
114        }
115    }
116}
117
118impl std::error::Error for NativeTableError {}
119
120/// Fluent builder for a [`NativeTable`].
121///
122/// - [`Self::register`] — next sequential slot (host builds table + chunk together).
123/// - [`Self::register_at`] — fixed ABI slot (MCU / separately flashed bytecode).
124pub struct NativeTableBuilder {
125    entries: Vec<Option<(String, NativeFn)>>,
126}
127
128impl NativeTableBuilder {
129    pub fn new() -> Self {
130        Self {
131            entries: Vec::new(),
132        }
133    }
134
135    /// Register `f` under `name` at the next sequential slot.
136    pub fn register<F>(self, name: impl Into<String>, f: F) -> Result<Self, NativeTableError>
137    where
138        F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
139    {
140        let index = self.entries.len() as u32;
141        self.register_at(index, name, f)
142    }
143
144    /// Register `f` under `name` at explicit `index`, padding lower gaps as
145    /// unregistered (`get` → `None` → [`Fault::BadNative`]).
146    pub fn register_at<F>(
147        mut self,
148        index: u32,
149        name: impl Into<String>,
150        f: F,
151    ) -> Result<Self, NativeTableError>
152    where
153        F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
154    {
155        let name = name.into();
156        for (n, _) in self.entries.iter().flatten() {
157            if n == &name {
158                return Err(NativeTableError::DuplicateName(name));
159            }
160        }
161        let index_usize = index as usize;
162        if index_usize >= MAX_NATIVE_SLOTS {
163            return Err(NativeTableError::IndexTooLarge {
164                index,
165                limit: MAX_NATIVE_SLOTS as u32,
166            });
167        }
168        if index_usize >= self.entries.len() {
169            self.entries.resize_with(index_usize + 1, || None);
170        }
171        if self.entries[index_usize].is_some() {
172            return Err(NativeTableError::SlotOccupied { index, name });
173        }
174        self.entries[index_usize] = Some((name, Arc::new(f)));
175        Ok(self)
176    }
177
178    pub fn build(self) -> Arc<NativeTable> {
179        Arc::new(NativeTable {
180            entries: self.entries,
181        })
182    }
183}
184
185impl Default for NativeTableBuilder {
186    fn default() -> Self {
187        Self::new()
188    }
189}
190
191/// Require `args[index]` to exist.
192pub fn expect_arg<'a>(args: &'a [Value], index: usize, fn_name: &str) -> Result<&'a Value, Fault> {
193    args.get(index).ok_or(Fault::NativeError(format!(
194        "{fn_name}: missing argument {index}"
195    )))
196}
197
198/// Require `args[index]` to coerce to an int (`Value::as_int`).
199pub fn expect_int(args: &[Value], index: usize, fn_name: &str) -> Result<i64, Fault> {
200    expect_arg(args, index, fn_name)?
201        .as_int()
202        .ok_or(Fault::NativeError(format!(
203            "{fn_name}: argument {index} is not an int"
204        )))
205}
206
207/// Require `args[index]` to be a bool (ints: nonzero = true).
208pub fn expect_bool(args: &[Value], index: usize, fn_name: &str) -> Result<bool, Fault> {
209    let v = expect_arg(args, index, fn_name)?;
210    match v {
211        Value::Bool(_) | Value::Int(_) => Ok(v.is_truthy()),
212        other => Err(Fault::NativeError(format!(
213            "{fn_name}: argument {index} is not a bool/int (got {})",
214            other.type_name()
215        ))),
216    }
217}
218
219/// Require `args[index]` to be a [`crate::Message`].
220///
221/// Used by the std `msg_*` natives. A wrong type becomes
222/// [`Fault::NativeError`] (category B — Flow fault), not a host panic.
223pub fn expect_message(
224    args: &[Value],
225    index: usize,
226    fn_name: &str,
227) -> Result<crate::Message, Fault> {
228    expect_arg(args, index, fn_name)?
229        .as_message()
230        .cloned()
231        .ok_or(Fault::NativeError(format!(
232            "{fn_name}: argument {index} is not a message"
233        )))
234}
235
236/// Coerce `args[index]` to `u64` from `Int` (≥ 0) or `Pid`.
237///
238/// Used by `make_msg` for unsigned envelope fields (`request_id`, `tag`);
239/// accepts a non-negative `Int` or a `Pid` without an extra conversion.
240/// Negative ints are rejected — those fields are unsigned on the wire.
241pub fn expect_u64(args: &[Value], index: usize, fn_name: &str) -> Result<u64, Fault> {
242    let v = expect_arg(args, index, fn_name)?;
243    if let Some(p) = v.as_pid() {
244        return Ok(p);
245    }
246    if let Some(i) = v.as_int().filter(|&n| n >= 0) {
247        return Ok(i as u64);
248    }
249    Err(Fault::NativeError(format!(
250        "{fn_name}: argument {index} is not a non-negative int/pid (got {})",
251        v.type_name()
252    )))
253}
254
255/// Per-flow native allowlist snapshot, checked before indexing the table.
256#[derive(Clone, Debug)]
257pub struct NativeGate {
258    has_native: bool,
259    mask: NativeMask,
260    authority_epoch: u64,
261    flow_cell: Arc<RevocationCell>,
262    native_epoch: u64,
263    native_cell: Arc<RevocationCell>,
264}
265
266impl NativeGate {
267    /// No native right — unit tests and chunks that never call out.
268    pub fn deny(native_count: usize) -> Self {
269        Self {
270            has_native: false,
271            mask: NativeMask::empty(native_count),
272            authority_epoch: 0,
273            flow_cell: Arc::new(RevocationCell::new()),
274            native_epoch: 0,
275            native_cell: Arc::new(RevocationCell::new()),
276        }
277    }
278
279    pub fn from_authority(
280        cap: &Cap,
281        flow_cell: Arc<RevocationCell>,
282        native_cell: Arc<RevocationCell>,
283        native_count: usize,
284    ) -> Self {
285        let mask = match &cap.native_mask {
286            Some(m) => m.clone(),
287            None => NativeMask::empty(native_count),
288        };
289        Self {
290            has_native: cap.rights.contains(CapRights::NATIVE),
291            mask,
292            authority_epoch: cap.epoch(),
293            flow_cell,
294            native_epoch: native_cell.epoch(),
295            native_cell,
296        }
297    }
298
299    pub fn is_live(&self) -> bool {
300        self.flow_cell.epoch() == self.authority_epoch
301            && self.native_cell.epoch() == self.native_epoch
302    }
303}
304
305/// Host-side check against a [`Cap`] (not the interpreter path).
306///
307/// The VM uses [`check_native_gate`] on the per-flow snapshot. This helper
308/// is for embedders that hold a live `Cap` and want the same verdict.
309pub fn check_native_call(
310    cap: &Cap,
311    table: &NativeTable,
312    idx: NativeIdx,
313) -> Result<(), NativeCallError> {
314    if (idx as usize) >= table.len() {
315        return Err(NativeCallError::IndexOutOfRange(idx));
316    }
317    if !cap.rights.contains(CapRights::NATIVE) {
318        return Err(NativeCallError::NoNativeRight);
319    }
320    match &cap.native_mask {
321        Some(mask) if mask.allows(idx) => Ok(()),
322        _ => Err(NativeCallError::IndexNotAllowlisted(idx)),
323    }
324}
325
326pub fn check_native_gate(
327    gate: &NativeGate,
328    table: &NativeTable,
329    idx: NativeIdx,
330) -> Result<(), NativeCallError> {
331    if (idx as usize) >= table.len() {
332        return Err(NativeCallError::IndexOutOfRange(idx));
333    }
334    if !gate.is_live() {
335        return Err(NativeCallError::Revoked);
336    }
337    if !gate.has_native {
338        return Err(NativeCallError::NoNativeRight);
339    }
340    if gate.mask.allows(idx) {
341        Ok(())
342    } else {
343        Err(NativeCallError::IndexNotAllowlisted(idx))
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn register_at_leaves_holes_as_none() -> Result<(), Box<dyn std::error::Error>> {
353        let table = NativeTable::builder()
354            .register_at(10, "answer", |_| Ok(Value::Int(42)))?
355            .build();
356        assert_eq!(table.len(), 11);
357        assert_eq!(table.index_of("answer"), Some(10));
358        let f = table.get(10).ok_or("missing native")?;
359        assert!(matches!(f(&[])?, Value::Int(42)));
360        assert!(table.get(2).is_none());
361        Ok(())
362    }
363
364    #[test]
365    fn register_at_rejects_an_index_past_the_slot_ceiling() {
366        let result = NativeTable::builder().register_at(u32::MAX, "huge", |_| Ok(Value::Unit));
367        assert_eq!(
368            result.map(|builder| builder.build().len()),
369            Err(NativeTableError::IndexTooLarge {
370                index: u32::MAX,
371                limit: MAX_NATIVE_SLOTS as u32,
372            })
373        );
374    }
375
376    #[test]
377    fn register_at_errors_on_duplicate_slot() {
378        let result = NativeTable::builder()
379            .register_at(3, "a", |_| Ok(Value::Unit))
380            .and_then(|b| b.register_at(3, "b", |_| Ok(Value::Unit)));
381        assert!(matches!(
382            result,
383            Err(NativeTableError::SlotOccupied { index: 3, .. })
384        ));
385    }
386
387    #[test]
388    fn register_errors_on_duplicate_name() {
389        let result = NativeTable::builder()
390            .register("x", |_| Ok(Value::Unit))
391            .and_then(|b| b.register("x", |_| Ok(Value::Unit)));
392        assert!(matches!(result, Err(NativeTableError::DuplicateName(_))));
393    }
394
395    #[test]
396    fn denies_unlisted_index_even_with_native_right() {
397        use crate::bytecode::{CapTarget, RevocationCell};
398
399        let cell = RevocationCell::new();
400        let mask = NativeMask::from_indices(16, &[2, 4]);
401        let cap = Cap::root(CapTarget::Flow(1), CapRights::NATIVE, Some(mask), &cell);
402        let table = NativeTable {
403            entries: Vec::new(),
404        };
405        assert!(matches!(
406            check_native_call(&cap, &table, 4),
407            Err(NativeCallError::IndexOutOfRange(_))
408        ));
409    }
410}