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