byteflow/natives.rs
1//! Standard native (FFI) table shipped with the facade.
2//!
3//! # Why Message make/unpack lives here (not as new opcodes)
4//!
5//! [`crate::Value::Message`] is already a first-class wire/register value
6//! (ABI v2). Building and tearing it apart in bytecode could be ISA ops
7//! (`MakeMessage`, `MsgSender`, …), but that would burn opcode space and
8//! force every embedder that never does request-reply to carry the
9//! dispatch cost. Natives keep the envelope **generic in the core** while
10//! the std table opts into the helpers — same pattern as `print` / `now_ms`
11//! (design notes §30-31): host Rust owns the operation, bytecode only
12//! picks a slot.
13//!
14//! # Stable indices are an embed contract
15//!
16//! Flash / separately-built `.bf` modules hard-code `CallNative` indices.
17//! Renumbering an existing slot is a **breaking** change. Keep
18//! [`std_native_map`] and [`std_native_table`] in lockstep; append only.
19//!
20//! | Index | Name | Role |
21//! |------:|------|------|
22//! | 0 | `print` | host stdout log line (flow-visible) |
23//! | 1 | `now_ms` | wall-clock millis as `Value::Int` |
24//! | 2 | `make_msg` | build [`crate::Message`] from four scalars (**untrusted** `sender`) |
25//! | 3 | `msg_sender` | extract `sender` → `Value::Pid` (authenticated **after** delivery) |
26//! | 4 | `msg_request_id` | extract `request_id` → `Value::Int` |
27//! | 5 | `msg_tag` | extract `tag` → `Value::Int` |
28//! | 6 | `msg_payload` | extract `payload` → `Value::Int` |
29//! | 7 | `msg_reply_cap` | extract `reply_cap` → `Value::Cap` (SEND grant) |
30//!
31//! # `CallNative` argument layout
32//!
33//! `CallNative ra, fb, nc` takes args from `r[a .. a+nc]` and writes the
34//! result back into `r[a]` — so a call **destroys** the first argument
35//! register. Samples that need to keep a `Message` while unpacking must
36//! `Move` it into the dest register first (see
37//! [`crate::samples::atomic_request_reply`]).
38
39use std::collections::HashMap;
40use std::sync::Arc;
41use std::time::{SystemTime, UNIX_EPOCH};
42
43use crate::bytecode::{Message, Value};
44use crate::vm::{expect_message, expect_u64, Fault, NativeTable};
45
46/// Name → `CallNative` index for documentation / host-side lookups.
47///
48/// Prefer this (or [`std_natives`]) over hard-coding integers in host code
49/// so renames stay discoverable; bytecode itself still embeds the numeric
50/// slot once assembled.
51pub fn std_native_map() -> HashMap<String, u32> {
52 HashMap::from([
53 ("print".to_owned(), 0),
54 ("now_ms".to_owned(), 1),
55 ("make_msg".to_owned(), 2),
56 ("msg_sender".to_owned(), 3),
57 ("msg_request_id".to_owned(), 4),
58 ("msg_tag".to_owned(), 5),
59 ("msg_payload".to_owned(), 6),
60 ("msg_reply_cap".to_owned(), 7),
61 ])
62}
63
64/// Default FFI table: print, clock, and Message make/unpack.
65///
66/// Pass this to [`crate::Runtime::with_natives`] (or
67/// `with_natives_and_config`) whenever the chunk emits the Message helpers
68/// or `print` / `now_ms`. Chunks that never `CallNative` can keep
69/// [`crate::NativeTable::empty`].
70pub fn std_native_table() -> Arc<NativeTable> {
71 let built = NativeTable::builder()
72 .register("print", |args| {
73 // Space-separated Display forms, trailing newline — mirrors a
74 // tiny "println!("{:?}", …)" for bytecode without allocating a
75 // format string in the VM.
76 let mut first = true;
77 for value in args {
78 if !first {
79 print!(" ");
80 }
81 print!("{value}");
82 first = false;
83 }
84 println!();
85 Ok(Value::Unit)
86 })
87 .and_then(|b| {
88 b.register("now_ms", |_| {
89 let duration = SystemTime::now()
90 .duration_since(UNIX_EPOCH)
91 .map_err(|e| Fault::NativeError(format!("system clock error: {e}")))?;
92 let millis = i64::try_from(duration.as_millis())
93 .map_err(|_| Fault::NativeError("system clock value exceeds i64".into()))?;
94 Ok(Value::Int(millis))
95 })
96 })
97 .and_then(|b| {
98 b.register("make_msg", |args| {
99 // Args: sender, request_id, tag, payload — each Int≥0, Pid, Cap, or Bool.
100 // Tag must fit `u16` (protocol discriminator width on the wire).
101 //
102 // # Security (crates.io contract)
103 //
104 // The first argument is retained so existing `.bf` modules and
105 // samples keep a stable CallNative layout (indices 0–6 frozen;
106 // 7 = msg_reply_cap appended). It is **not** an authentication
107 // primitive:
108 //
109 // - Before `Send` / `Ask`, `sender` is ordinary register data.
110 // - At delivery, the worker stamps `Message.sender` and mints
111 // `reply_cap` (`Message::authenticate`).
112 // - After a hop is received, `msg_sender` / `msg_reply_cap`
113 // reflect runtime identity and the SEND grant (S1 + FlowCap).
114 //
115 // Host code that only builds messages in memory (never sends)
116 // still sees the constructed field unchanged.
117 let sender = expect_u64(args, 0, "make_msg")?;
118 let request_id = expect_u64(args, 1, "make_msg")?;
119 let tag = expect_u64(args, 2, "make_msg")?;
120 let payload = expect_u64(args, 3, "make_msg")?;
121 let tag = u16::try_from(tag).map_err(|_| {
122 Fault::NativeError(format!("make_msg: tag {tag} does not fit in u16"))
123 })?;
124 Ok(Value::Message(Message::new(sender, request_id, tag, payload)))
125 })
126 })
127 .and_then(|b| {
128 b.register("msg_sender", |args| {
129 // After mailbox delivery this is the runtime-stamped origin.
130 // Identity only — not a Send/Ask address (use `msg_reply_cap`).
131 Ok(Value::Pid(expect_message(args, 0, "msg_sender")?.sender))
132 })
133 })
134 .and_then(|b| {
135 b.register("msg_request_id", |args| {
136 Ok(Value::Int(
137 expect_message(args, 0, "msg_request_id")?.request_id as i64,
138 ))
139 })
140 })
141 .and_then(|b| {
142 b.register("msg_tag", |args| {
143 Ok(Value::Int(i64::from(expect_message(args, 0, "msg_tag")?.tag)))
144 })
145 })
146 .and_then(|b| {
147 b.register("msg_payload", |args| {
148 Ok(Value::Int(
149 expect_message(args, 0, "msg_payload")?.payload as i64,
150 ))
151 })
152 })
153 .and_then(|b| {
154 b.register("msg_reply_cap", |args| {
155 Ok(Value::Cap(
156 expect_message(args, 0, "msg_reply_cap")?.reply_cap,
157 ))
158 })
159 });
160 // Unique sequential names cannot hit DuplicateName / SlotOccupied.
161 // Empty table on Err: fail-closed (CallNative → BadNative), never panic.
162 match built {
163 Ok(b) => b.build(),
164 Err(_) => NativeTable::empty(),
165 }
166}
167
168/// Build the default native table and its matching name map together.
169///
170/// Prefer this when the host both registers natives and resolves names to
171/// indices for `ChunkBuilder` — one source of truth, no drift between map
172/// and table.
173pub fn std_natives() -> (Arc<NativeTable>, HashMap<String, u32>) {
174 let table = std_native_table();
175 let map: HashMap<String, u32> = table
176 .names()
177 .filter_map(|n| table.index_of(n).map(|i| (n.to_string(), i)))
178 .collect();
179 (table, map)
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 #[test]
187 fn std_native_indices_are_stable() {
188 let map = std_native_map();
189 assert_eq!(map.get("print"), Some(&0));
190 assert_eq!(map.get("now_ms"), Some(&1));
191 assert_eq!(map.get("make_msg"), Some(&2));
192 assert_eq!(map.get("msg_sender"), Some(&3));
193 assert_eq!(map.get("msg_request_id"), Some(&4));
194 assert_eq!(map.get("msg_tag"), Some(&5));
195 assert_eq!(map.get("msg_payload"), Some(&6));
196 assert_eq!(map.get("msg_reply_cap"), Some(&7));
197 }
198
199 #[test]
200 fn std_native_table_matches_map() {
201 let (table, map) = std_natives();
202 assert_eq!(table.len(), 8);
203 for (name, idx) in &map {
204 assert_eq!(table.index_of(name), Some(*idx));
205 }
206 }
207
208 #[test]
209 fn now_ms_returns_non_negative_int() -> Result<(), Box<dyn std::error::Error>> {
210 let table = std_native_table();
211 let now_ms = table.get(1).ok_or("now_ms native")?;
212 let value = now_ms(&[])?;
213 assert!(matches!(value, Value::Int(ms) if ms >= 0));
214 Ok(())
215 }
216
217 #[test]
218 fn make_msg_and_unpack_round_trip() -> Result<(), Box<dyn std::error::Error>> {
219 let table = std_native_table();
220 let make = table.get(2).ok_or("make_msg")?;
221 let msg = make(&[
222 Value::Pid(9),
223 Value::Int(3),
224 Value::Int(7),
225 Value::Int(42),
226 ])?;
227 assert_eq!(msg.as_message(), Some(Message::new(9, 3, 7, 42)));
228 let sender = table.get(3).ok_or("msg_sender")?;
229 let req = table.get(4).ok_or("msg_request_id")?;
230 let tag = table.get(5).ok_or("msg_tag")?;
231 let payload = table.get(6).ok_or("msg_payload")?;
232 let cap = table.get(7).ok_or("msg_reply_cap")?;
233 assert_eq!(sender(std::slice::from_ref(&msg))?, Value::Pid(9));
234 assert_eq!(req(std::slice::from_ref(&msg))?, Value::Int(3));
235 assert_eq!(tag(std::slice::from_ref(&msg))?, Value::Int(7));
236 assert_eq!(payload(std::slice::from_ref(&msg))?, Value::Int(42));
237 assert_eq!(cap(std::slice::from_ref(&msg))?, Value::Cap(0));
238 Ok(())
239 }
240
241 #[test]
242 fn print_accepts_all_current_values() -> Result<(), Box<dyn std::error::Error>> {
243 let table = std_native_table();
244 let print = table.get(0).ok_or("print native")?;
245 let values = [
246 Value::Unit,
247 Value::Bool(true),
248 Value::Int(42),
249 Value::Float(1.5),
250 Value::Pid(7),
251 Value::Message(Message::new(1, 2, 3, 4)),
252 Value::Cap(9),
253 Value::str("hello"),
254 Value::bytes([1u8, 2, 3]),
255 ];
256 assert_eq!(print(&values)?, Value::Unit);
257 Ok(())
258 }
259
260 #[test]
261 fn print_with_no_args_still_returns_unit() -> Result<(), Box<dyn std::error::Error>> {
262 let table = std_native_table();
263 let print = table.get(0).ok_or("print native")?;
264 assert_eq!(print(&[])?, Value::Unit);
265 Ok(())
266 }
267}