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/// `Bool` is not an integer here. Negative ints are rejected — those fields
240/// 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 Value::Int(i) = v {
247        if *i >= 0 {
248            return Ok(*i as u64);
249        }
250    }
251    Err(Fault::NativeError(format!(
252        "{fn_name}: argument {index} is not a non-negative int/pid (got {})",
253        v.type_name()
254    )))
255}
256
257/// Per-flow native allowlist snapshot, checked before indexing the table.
258#[derive(Clone, Debug)]
259pub struct NativeGate {
260    has_native: bool,
261    mask: NativeMask,
262    authority_epoch: u64,
263    flow_cell: Arc<RevocationCell>,
264    native_epoch: u64,
265    native_cell: Arc<RevocationCell>,
266}
267
268impl NativeGate {
269    /// No native right — unit tests and chunks that never call out.
270    pub fn deny(native_count: usize) -> Self {
271        Self {
272            has_native: false,
273            mask: NativeMask::empty(native_count),
274            authority_epoch: 0,
275            flow_cell: Arc::new(RevocationCell::new()),
276            native_epoch: 0,
277            native_cell: Arc::new(RevocationCell::new()),
278        }
279    }
280
281    pub fn from_authority(
282        cap: &Cap,
283        flow_cell: Arc<RevocationCell>,
284        native_cell: Arc<RevocationCell>,
285        native_count: usize,
286    ) -> Self {
287        let mask = match cap.native_mask() {
288            Some(m) => m.clone(),
289            None => NativeMask::empty(native_count),
290        };
291        Self {
292            has_native: cap.rights().contains(CapRights::NATIVE),
293            mask,
294            authority_epoch: cap.epoch(),
295            flow_cell,
296            native_epoch: native_cell.epoch(),
297            native_cell,
298        }
299    }
300
301    pub fn is_live(&self) -> bool {
302        self.flow_cell.epoch() == self.authority_epoch
303            && self.native_cell.epoch() == self.native_epoch
304    }
305}
306
307/// Host-side check against a [`Cap`] (not the interpreter path).
308///
309/// The VM uses [`check_native_gate`] on the per-flow snapshot. This helper
310/// is for embedders that hold a live `Cap` and want the same verdict.
311pub fn check_native_call(
312    cap: &Cap,
313    table: &NativeTable,
314    idx: NativeIdx,
315) -> Result<(), NativeCallError> {
316    if (idx as usize) >= table.len() {
317        return Err(NativeCallError::IndexOutOfRange(idx));
318    }
319    if !cap.rights().contains(CapRights::NATIVE) {
320        return Err(NativeCallError::NoNativeRight);
321    }
322    match cap.native_mask() {
323        Some(mask) if mask.allows(idx) => Ok(()),
324        _ => Err(NativeCallError::IndexNotAllowlisted(idx)),
325    }
326}
327
328pub fn check_native_gate(
329    gate: &NativeGate,
330    table: &NativeTable,
331    idx: NativeIdx,
332) -> Result<(), NativeCallError> {
333    if (idx as usize) >= table.len() {
334        return Err(NativeCallError::IndexOutOfRange(idx));
335    }
336    if !gate.is_live() {
337        return Err(NativeCallError::Revoked);
338    }
339    if !gate.has_native {
340        return Err(NativeCallError::NoNativeRight);
341    }
342    if gate.mask.allows(idx) {
343        Ok(())
344    } else {
345        Err(NativeCallError::IndexNotAllowlisted(idx))
346    }
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn expect_u64_rejects_bool_and_keeps_non_negative_ints() {
355        let flag = [Value::Bool(true)];
356        assert!(expect_u64(&flag, 0, "make_msg").is_err());
357        let negative = [Value::Int(-1)];
358        assert!(expect_u64(&negative, 0, "make_msg").is_err());
359        let zero = [Value::Int(0)];
360        assert_eq!(expect_u64(&zero, 0, "make_msg").ok(), Some(0));
361        let pid = [Value::Pid(7)];
362        assert_eq!(expect_u64(&pid, 0, "make_msg").ok(), Some(7));
363    }
364
365    #[test]
366    fn register_at_leaves_holes_as_none() -> Result<(), Box<dyn std::error::Error>> {
367        let table = NativeTable::builder()
368            .register_at(10, "answer", |_| Ok(Value::Int(42)))?
369            .build();
370        assert_eq!(table.len(), 11);
371        assert_eq!(table.index_of("answer"), Some(10));
372        let f = table.get(10).ok_or("missing native")?;
373        assert!(matches!(f(&[])?, Value::Int(42)));
374        assert!(table.get(2).is_none());
375        Ok(())
376    }
377
378    #[test]
379    fn register_at_rejects_an_index_past_the_slot_ceiling() {
380        let result = NativeTable::builder().register_at(u32::MAX, "huge", |_| Ok(Value::Unit));
381        assert_eq!(
382            result.map(|builder| builder.build().len()),
383            Err(NativeTableError::IndexTooLarge {
384                index: u32::MAX,
385                limit: MAX_NATIVE_SLOTS as u32,
386            })
387        );
388    }
389
390    #[test]
391    fn register_at_errors_on_duplicate_slot() {
392        let result = NativeTable::builder()
393            .register_at(3, "a", |_| Ok(Value::Unit))
394            .and_then(|b| b.register_at(3, "b", |_| Ok(Value::Unit)));
395        assert!(matches!(
396            result,
397            Err(NativeTableError::SlotOccupied { index: 3, .. })
398        ));
399    }
400
401    #[test]
402    fn register_errors_on_duplicate_name() {
403        let result = NativeTable::builder()
404            .register("x", |_| Ok(Value::Unit))
405            .and_then(|b| b.register("x", |_| Ok(Value::Unit)));
406        assert!(matches!(result, Err(NativeTableError::DuplicateName(_))));
407    }
408
409    #[test]
410    fn denies_unlisted_index_even_with_native_right() {
411        use crate::bytecode::{CapTarget, RevocationCell};
412
413        let cell = RevocationCell::new();
414        let mask = NativeMask::from_indices(16, &[2, 4]);
415        let cap = Cap::root(CapTarget::Flow(1), CapRights::NATIVE, Some(mask), &cell);
416        let table = NativeTable {
417            entries: Vec::new(),
418        };
419        assert!(matches!(
420            check_native_call(&cap, &table, 4),
421            Err(NativeCallError::IndexOutOfRange(_))
422        ));
423    }
424}