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/// Host error while building a [`NativeTable`] (duplicate name or occupied slot).
77///
78/// Category A: the embedder misconfigured FFI. Never a panic — `std_native_table`
79/// and host tables must surface this as `Result`.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum NativeTableError {
82    DuplicateName(String),
83    SlotOccupied { index: u32, name: String },
84}
85
86impl std::fmt::Display for NativeTableError {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        match self {
89            NativeTableError::DuplicateName(name) => {
90                write!(f, "duplicate native function registered: '{name}'")
91            }
92            NativeTableError::SlotOccupied { index, name } => {
93                write!(f, "native slot {index} already occupied (registering '{name}')")
94            }
95        }
96    }
97}
98
99impl std::error::Error for NativeTableError {}
100
101/// Fluent builder for a [`NativeTable`].
102///
103/// - [`Self::register`] — next sequential slot (host builds table + chunk together).
104/// - [`Self::register_at`] — fixed ABI slot (MCU / separately flashed bytecode).
105pub struct NativeTableBuilder {
106    entries: Vec<Option<(String, NativeFn)>>,
107}
108
109impl NativeTableBuilder {
110    pub fn new() -> Self {
111        Self {
112            entries: Vec::new(),
113        }
114    }
115
116    /// Register `f` under `name` at the next sequential slot.
117    pub fn register<F>(self, name: impl Into<String>, f: F) -> Result<Self, NativeTableError>
118    where
119        F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
120    {
121        let index = self.entries.len() as u32;
122        self.register_at(index, name, f)
123    }
124
125    /// Register `f` under `name` at explicit `index`, padding lower gaps as
126    /// unregistered (`get` → `None` → [`Fault::BadNative`]).
127    pub fn register_at<F>(
128        mut self,
129        index: u32,
130        name: impl Into<String>,
131        f: F,
132    ) -> Result<Self, NativeTableError>
133    where
134        F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
135    {
136        let name = name.into();
137        for (n, _) in self.entries.iter().flatten() {
138            if n == &name {
139                return Err(NativeTableError::DuplicateName(name));
140            }
141        }
142        let index_usize = index as usize;
143        if index_usize >= self.entries.len() {
144            self.entries.resize_with(index_usize + 1, || None);
145        }
146        if self.entries[index_usize].is_some() {
147            return Err(NativeTableError::SlotOccupied { index, name });
148        }
149        self.entries[index_usize] = Some((name, Arc::new(f)));
150        Ok(self)
151    }
152
153    pub fn build(self) -> Arc<NativeTable> {
154        Arc::new(NativeTable {
155            entries: self.entries,
156        })
157    }
158}
159
160impl Default for NativeTableBuilder {
161    fn default() -> Self {
162        Self::new()
163    }
164}
165
166/// Require `args[index]` to exist.
167pub fn expect_arg<'a>(
168    args: &'a [Value],
169    index: usize,
170    fn_name: &str,
171) -> Result<&'a Value, Fault> {
172    args.get(index).ok_or(Fault::NativeError(format!(
173        "{fn_name}: missing argument {index}"
174    )))
175}
176
177/// Require `args[index]` to coerce to an int (`Value::as_int`).
178pub fn expect_int(args: &[Value], index: usize, fn_name: &str) -> Result<i64, Fault> {
179    expect_arg(args, index, fn_name)?
180        .as_int()
181        .ok_or(Fault::NativeError(format!(
182            "{fn_name}: argument {index} is not an int"
183        )))
184}
185
186/// Require `args[index]` to be a bool (ints: nonzero = true).
187pub fn expect_bool(args: &[Value], index: usize, fn_name: &str) -> Result<bool, Fault> {
188    match expect_arg(args, index, fn_name)? {
189        Value::Bool(b) => Ok(*b),
190        Value::Int(i) => Ok(*i != 0),
191        other => Err(Fault::NativeError(format!(
192            "{fn_name}: argument {index} is not a bool/int (got {})",
193            other.type_name()
194        ))),
195    }
196}
197
198/// Require `args[index]` to be a [`crate::Message`].
199///
200/// Used by the std `msg_*` natives. A wrong type becomes
201/// [`Fault::NativeError`] (category B — Flow fault), not a host panic.
202pub fn expect_message(
203    args: &[Value],
204    index: usize,
205    fn_name: &str,
206) -> Result<crate::Message, Fault> {
207    expect_arg(args, index, fn_name)?
208        .as_message()
209        .cloned()
210        .ok_or(Fault::NativeError(format!(
211            "{fn_name}: argument {index} is not a message"
212        )))
213}
214
215/// Coerce `args[index]` to `u64` from `Int` (≥ 0), `Pid`, `Cap`, or `Bool`.
216///
217/// `make_msg` accepts these so bytecode can pass a `SelfPid` / Spawn Cap
218/// result, a `Pid` identity, or a `LoadImm` without an extra conversion.
219/// Negative ints are rejected — envelope fields are unsigned on the wire.
220pub fn expect_u64(args: &[Value], index: usize, fn_name: &str) -> Result<u64, Fault> {
221    match expect_arg(args, index, fn_name)? {
222        Value::Pid(p) => Ok(*p),
223        Value::Int(i) if *i >= 0 => Ok(*i as u64),
224        Value::Bool(b) => Ok(u64::from(*b)),
225        other => Err(Fault::NativeError(format!(
226            "{fn_name}: argument {index} is not a non-negative int/pid (got {})",
227            other.type_name()
228        ))),
229    }
230}
231
232/// Per-flow native allowlist snapshot, checked before indexing the table.
233#[derive(Clone, Debug)]
234pub struct NativeGate {
235    has_native: bool,
236    mask: NativeMask,
237    authority_epoch: u64,
238    flow_cell: Arc<RevocationCell>,
239    native_epoch: u64,
240    native_cell: Arc<RevocationCell>,
241}
242
243impl NativeGate {
244    /// No native right — unit tests and chunks that never call out.
245    pub fn deny(native_count: usize) -> Self {
246        Self {
247            has_native: false,
248            mask: NativeMask::empty(native_count),
249            authority_epoch: 0,
250            flow_cell: Arc::new(RevocationCell::new()),
251            native_epoch: 0,
252            native_cell: Arc::new(RevocationCell::new()),
253        }
254    }
255
256    pub fn from_authority(
257        cap: &Cap,
258        flow_cell: Arc<RevocationCell>,
259        native_cell: Arc<RevocationCell>,
260        native_count: usize,
261    ) -> Self {
262        let mask = match &cap.native_mask {
263            Some(m) => m.clone(),
264            None => NativeMask::empty(native_count),
265        };
266        Self {
267            has_native: cap.rights.contains(CapRights::NATIVE),
268            mask,
269            authority_epoch: cap.epoch(),
270            flow_cell,
271            native_epoch: native_cell.epoch(),
272            native_cell,
273        }
274    }
275
276    pub fn is_live(&self) -> bool {
277        self.flow_cell.epoch() == self.authority_epoch
278            && self.native_cell.epoch() == self.native_epoch
279    }
280}
281
282/// Host-side check against a [`Cap`] (not the interpreter path).
283///
284/// The VM uses [`check_native_gate`] on the per-flow snapshot. This helper
285/// is for embedders that hold a live `Cap` and want the same verdict.
286pub fn check_native_call(
287    cap: &Cap,
288    table: &NativeTable,
289    idx: NativeIdx,
290) -> Result<(), NativeCallError> {
291    if (idx as usize) >= table.len() {
292        return Err(NativeCallError::IndexOutOfRange(idx));
293    }
294    if !cap.rights.contains(CapRights::NATIVE) {
295        return Err(NativeCallError::NoNativeRight);
296    }
297    match &cap.native_mask {
298        Some(mask) if mask.allows(idx) => Ok(()),
299        _ => Err(NativeCallError::IndexNotAllowlisted(idx)),
300    }
301}
302
303pub fn check_native_gate(
304    gate: &NativeGate,
305    table: &NativeTable,
306    idx: NativeIdx,
307) -> Result<(), NativeCallError> {
308    if (idx as usize) >= table.len() {
309        return Err(NativeCallError::IndexOutOfRange(idx));
310    }
311    if !gate.is_live() {
312        return Err(NativeCallError::Revoked);
313    }
314    if !gate.has_native {
315        return Err(NativeCallError::NoNativeRight);
316    }
317    if gate.mask.allows(idx) {
318        Ok(())
319    } else {
320        Err(NativeCallError::IndexNotAllowlisted(idx))
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn register_at_leaves_holes_as_none() -> Result<(), Box<dyn std::error::Error>> {
330        let table = NativeTable::builder()
331            .register_at(10, "answer", |_| Ok(Value::Int(42)))?
332            .build();
333        assert_eq!(table.len(), 11);
334        assert_eq!(table.index_of("answer"), Some(10));
335        let f = table.get(10).ok_or("missing native")?;
336        assert!(matches!(f(&[])?, Value::Int(42)));
337        assert!(table.get(2).is_none());
338        Ok(())
339    }
340
341    #[test]
342    fn register_at_errors_on_duplicate_slot() {
343        let result = NativeTable::builder()
344            .register_at(3, "a", |_| Ok(Value::Unit))
345            .and_then(|b| b.register_at(3, "b", |_| Ok(Value::Unit)));
346        assert!(matches!(
347            result,
348            Err(NativeTableError::SlotOccupied { index: 3, .. })
349        ));
350    }
351
352    #[test]
353    fn register_errors_on_duplicate_name() {
354        let result = NativeTable::builder()
355            .register("x", |_| Ok(Value::Unit))
356            .and_then(|b| b.register("x", |_| Ok(Value::Unit)));
357        assert!(matches!(result, Err(NativeTableError::DuplicateName(_))));
358    }
359
360    #[test]
361    fn denies_unlisted_index_even_with_native_right() {
362        use crate::bytecode::{CapTarget, RevocationCell};
363
364        let cell = RevocationCell::new();
365        let mask = NativeMask::from_indices(16, &[2, 4]);
366        let cap = Cap::root(CapTarget::Flow(1), CapRights::NATIVE, Some(mask), &cell);
367        let table = NativeTable {
368            entries: Vec::new(),
369        };
370        assert!(matches!(
371            check_native_call(&cap, &table, 4),
372            Err(NativeCallError::IndexOutOfRange(_))
373        ));
374    }
375}