kobako 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.release-please-manifest.json +1 -0
- data/CHANGELOG.md +29 -0
- data/Cargo.lock +1 -1
- data/README.md +85 -6
- data/data/kobako.wasm +0 -0
- data/ext/kobako/Cargo.toml +1 -1
- data/ext/kobako/src/lib.rs +4 -2
- data/ext/kobako/src/{wasm → runtime}/cache.rs +22 -18
- data/ext/kobako/src/runtime/capture.rs +91 -0
- data/ext/kobako/src/runtime/config.rs +26 -0
- data/ext/kobako/src/runtime/dispatch.rs +211 -0
- data/ext/kobako/src/runtime/exports.rs +51 -0
- data/ext/kobako/src/runtime/guest_mem.rs +228 -0
- data/ext/kobako/src/{wasm/host_state.rs → runtime/invocation.rs} +195 -81
- data/ext/kobako/src/runtime/trap.rs +134 -0
- data/ext/kobako/src/runtime.rs +782 -0
- data/ext/kobako/src/snapshot.rs +110 -0
- data/lib/kobako/capture.rb +11 -16
- data/lib/kobako/catalog/handles.rb +107 -0
- data/lib/kobako/catalog/namespaces.rb +99 -0
- data/lib/kobako/{snippet/table.rb → catalog/snippets.rb} +37 -62
- data/lib/kobako/catalog.rb +18 -0
- data/lib/kobako/codec/decoder.rb +13 -7
- data/lib/kobako/codec/factory.rb +21 -18
- data/lib/kobako/codec/utils.rb +118 -29
- data/lib/kobako/codec.rb +6 -3
- data/lib/kobako/errors.rb +45 -28
- data/lib/kobako/fault.rb +40 -0
- data/lib/kobako/handle.rb +60 -0
- data/lib/kobako/namespace.rb +67 -0
- data/lib/kobako/outcome.rb +55 -29
- data/lib/kobako/runtime.rb +30 -0
- data/lib/kobako/sandbox.rb +131 -67
- data/lib/kobako/sandbox_options.rb +6 -9
- data/lib/kobako/snapshot.rb +40 -0
- data/lib/kobako/snippet/binary.rb +6 -7
- data/lib/kobako/snippet/source.rb +8 -8
- data/lib/kobako/snippet.rb +7 -9
- data/lib/kobako/transport/dispatcher.rb +195 -0
- data/lib/kobako/transport/error.rb +24 -0
- data/lib/kobako/transport/request.rb +78 -0
- data/lib/kobako/transport/response.rb +69 -0
- data/lib/kobako/transport/run.rb +141 -0
- data/lib/kobako/transport/yield.rb +91 -0
- data/lib/kobako/transport/yielder.rb +89 -0
- data/lib/kobako/transport.rb +24 -0
- data/lib/kobako/usage.rb +41 -0
- data/lib/kobako/version.rb +1 -1
- data/lib/kobako.rb +4 -3
- data/release-please-config.json +24 -0
- data/sig/kobako/capture.rbs +0 -2
- data/sig/kobako/{rpc/handle_table.rbs → catalog/handles.rbs} +3 -9
- data/sig/kobako/catalog/namespaces.rbs +17 -0
- data/sig/kobako/{snippet/table.rbs → catalog/snippets.rbs} +2 -11
- data/sig/kobako/{rpc.rbs → catalog.rbs} +1 -1
- data/sig/kobako/codec/decoder.rbs +2 -1
- data/sig/kobako/codec/factory.rbs +3 -3
- data/sig/kobako/codec/utils.rbs +11 -1
- data/sig/kobako/errors.rbs +7 -7
- data/sig/kobako/fault.rbs +19 -0
- data/sig/kobako/handle.rbs +18 -0
- data/sig/kobako/namespace.rbs +19 -0
- data/sig/kobako/outcome.rbs +2 -2
- data/sig/kobako/runtime.rbs +23 -0
- data/sig/kobako/sandbox.rbs +10 -7
- data/sig/kobako/snapshot.rbs +15 -0
- data/sig/kobako/transport/dispatcher.rbs +34 -0
- data/sig/kobako/transport/error.rbs +6 -0
- data/sig/kobako/transport/request.rbs +32 -0
- data/sig/kobako/transport/response.rbs +30 -0
- data/sig/kobako/transport/run.rbs +27 -0
- data/sig/kobako/transport/yield.rbs +34 -0
- data/sig/kobako/transport/yielder.rbs +21 -0
- data/sig/kobako/transport.rbs +4 -0
- data/sig/kobako/usage.rbs +11 -0
- metadata +52 -30
- data/ext/kobako/src/wasm/dispatch.rs +0 -161
- data/ext/kobako/src/wasm/instance.rs +0 -771
- data/ext/kobako/src/wasm.rs +0 -125
- data/lib/kobako/invocation.rb +0 -112
- data/lib/kobako/rpc/dispatcher.rb +0 -169
- data/lib/kobako/rpc/envelope.rb +0 -118
- data/lib/kobako/rpc/fault.rb +0 -41
- data/lib/kobako/rpc/handle.rb +0 -39
- data/lib/kobako/rpc/handle_table.rb +0 -107
- data/lib/kobako/rpc/namespace.rb +0 -74
- data/lib/kobako/rpc/server.rb +0 -158
- data/lib/kobako/rpc.rb +0 -11
- data/lib/kobako/wasm.rb +0 -25
- data/sig/kobako/invocation.rbs +0 -23
- data/sig/kobako/rpc/dispatcher.rbs +0 -33
- data/sig/kobako/rpc/envelope.rbs +0 -51
- data/sig/kobako/rpc/fault.rbs +0 -20
- data/sig/kobako/rpc/handle.rbs +0 -19
- data/sig/kobako/rpc/namespace.rbs +0 -24
- data/sig/kobako/rpc/server.rbs +0 -37
- data/sig/kobako/wasm.rbs +0 -39
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
//! Host-side dispatch for the `__kobako_dispatch` import.
|
|
2
|
+
//!
|
|
3
|
+
//! When the guest invokes the wasm import declared in
|
|
4
|
+
//! `wasm/kobako-wasm/src/abi.rs`, wasmtime calls back into the host
|
|
5
|
+
//! through the closure built in `super::Runtime::build`.
|
|
6
|
+
//! That closure delegates here. The dispatcher (docs/behavior.md B-12 / B-13):
|
|
7
|
+
//!
|
|
8
|
+
//! 1. Reads the Request bytes from guest linear memory.
|
|
9
|
+
//! 2. Invokes the Ruby-side dispatch Proc bound via
|
|
10
|
+
//! `Runtime#on_dispatch=` and recovers Response bytes.
|
|
11
|
+
//! 3. Allocates a guest buffer via `__kobako_alloc(len)` invoked
|
|
12
|
+
//! through `Caller::get_export`.
|
|
13
|
+
//! 4. Writes the Response bytes into the guest buffer.
|
|
14
|
+
//! 5. Returns packed `(ptr<<32)|len` for the guest to decode.
|
|
15
|
+
//!
|
|
16
|
+
//! Returns 0 on any step failure. `Kobako::Sandbox#initialize` always
|
|
17
|
+
//! installs the dispatch Proc before any invocation, so reaching the
|
|
18
|
+
//! dispatcher with no Proc bound is itself a wire-layer fault; the
|
|
19
|
+
//! guest maps a 0 return to a trap. Failures during normal dispatch
|
|
20
|
+
//! surface as Response.err envelopes from
|
|
21
|
+
//! `Kobako::Transport::Dispatcher.dispatch` itself — they never reach
|
|
22
|
+
//! this 0-return path.
|
|
23
|
+
//!
|
|
24
|
+
//! ## Why this module writes to `stderr`
|
|
25
|
+
//!
|
|
26
|
+
//! This file is the one place in `ext/` that deliberately prints
|
|
27
|
+
//! through `eprintln!`. The host normally surfaces faults by
|
|
28
|
+
//! raising a `MagnusError` back into Ruby; the dispatcher contract
|
|
29
|
+
//! is the exception — it must return a packed `i64` to the guest
|
|
30
|
+
//! and cannot raise, so a 0 return is the only signal the wasm side
|
|
31
|
+
//! receives. The guest collapses every 0 into the same trap, so the
|
|
32
|
+
//! Ruby host has no way to attribute the failure to a specific step
|
|
33
|
+
//! (missing `memory` export vs. no dispatch Proc bound vs. the Proc
|
|
34
|
+
//! raised vs. `__kobako_alloc` returned 0 vs. `memory.write`
|
|
35
|
+
//! rejected).
|
|
36
|
+
//!
|
|
37
|
+
//! `handle` writes a single `[kobako-dispatch] <reason>` line to
|
|
38
|
+
//! `stderr` on each failure path so operators have a breadcrumb to
|
|
39
|
+
//! correlate the trap with the actual cause. The line is emitted in
|
|
40
|
+
//! both debug and release builds on purpose: dispatcher failures are
|
|
41
|
+
//! wire-layer faults rather than expected error paths (`Kobako::Sandbox`
|
|
42
|
+
//! always installs the Proc, the Proc is contracted never to raise,
|
|
43
|
+
//! etc.), so the "release-build noise" cost is bounded — under normal
|
|
44
|
+
//! operation the line is never written. Operators that need to silence
|
|
45
|
+
//! the stream can redirect the host process's stderr, but the kobako
|
|
46
|
+
//! convention is "ext never logs" plus this single, named exception.
|
|
47
|
+
|
|
48
|
+
use core::cell::Cell;
|
|
49
|
+
use core::ptr::NonNull;
|
|
50
|
+
|
|
51
|
+
use magnus::value::{Opaque, ReprValue};
|
|
52
|
+
use magnus::{Error as MagnusError, RString, Ruby, Value};
|
|
53
|
+
use wasmtime::Caller;
|
|
54
|
+
|
|
55
|
+
use super::invocation::Invocation;
|
|
56
|
+
|
|
57
|
+
// ============================================================
|
|
58
|
+
// Active-caller pointer for the per-thread Invocation slot (B-24, B-28,
|
|
59
|
+
// SPEC.md Single-Invocation Slot).
|
|
60
|
+
// ============================================================
|
|
61
|
+
//
|
|
62
|
+
// `Runtime#yield_to_active_invocation` (whose body is the
|
|
63
|
+
// `__kobako_yield_to_block` guest export) runs synchronously inside a
|
|
64
|
+
// Ruby Service callback that itself was invoked from inside this
|
|
65
|
+
// dispatcher — at that moment we are several stack frames deep in
|
|
66
|
+
// `try_handle`, with the original `&mut Caller<'_, Invocation>` parked
|
|
67
|
+
// unused on the Rust stack while Ruby code is running. The yield path
|
|
68
|
+
// needs the same Caller to call the guest export, but the Rust borrow
|
|
69
|
+
// type is non-`'static` so it cannot be stored on the `Invocation`
|
|
70
|
+
// struct directly (the `&mut Caller` outlives no struct field — its
|
|
71
|
+
// lifetime ends when `handle` returns to wasmtime).
|
|
72
|
+
//
|
|
73
|
+
// The pointer is therefore erased to `NonNull<()>` and parked in a
|
|
74
|
+
// per-thread slot — the materialised form of the SPEC.md
|
|
75
|
+
// "Single-Invocation Slot" invariant. The single-threaded wasm
|
|
76
|
+
// execution per Sandbox (B-22) plus the LIFO re-entry shape of nested
|
|
77
|
+
// dispatch frames (B-28) ensures no aliasing across threads or across
|
|
78
|
+
// frames; the recovery invariant lives at `current_caller`. The
|
|
79
|
+
// pointer is set on entry to `handle` and restored to the outer
|
|
80
|
+
// frame's value on every exit through a drop guard.
|
|
81
|
+
|
|
82
|
+
thread_local! {
|
|
83
|
+
static ACTIVE_CALLER: Cell<Option<NonNull<()>>> = const { Cell::new(None) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// RAII guard that saves the previous `ACTIVE_CALLER` value on
|
|
87
|
+
/// installation and restores it on drop. Nested `__kobako_dispatch`
|
|
88
|
+
/// frames stack within one Invocation (B-28) — the inner frame's `set`
|
|
89
|
+
/// swaps in its own pointer while remembering the outer's; drop
|
|
90
|
+
/// restores the outer so its continuation (e.g. iterating over another
|
|
91
|
+
/// guest block) still finds a live caller.
|
|
92
|
+
pub(crate) struct CallerGuard {
|
|
93
|
+
previous: Option<NonNull<()>>,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
impl CallerGuard {
|
|
97
|
+
fn set(ptr: NonNull<()>) -> Self {
|
|
98
|
+
let previous = ACTIVE_CALLER.with(|c| c.replace(Some(ptr)));
|
|
99
|
+
Self { previous }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
impl Drop for CallerGuard {
|
|
104
|
+
fn drop(&mut self) {
|
|
105
|
+
ACTIVE_CALLER.with(|c| c.set(self.previous));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/// Recover the active `&mut Caller<'_, Invocation>` set by the
|
|
110
|
+
/// enclosing `handle` frame. Returns `None` when no dispatch frame is
|
|
111
|
+
/// active on this thread.
|
|
112
|
+
///
|
|
113
|
+
/// # Safety
|
|
114
|
+
///
|
|
115
|
+
/// The returned reference aliases the original `&mut Caller` borrow
|
|
116
|
+
/// held on the Rust stack inside `handle`'s enclosing frame. The
|
|
117
|
+
/// original borrow is logically inactive while Ruby code is running
|
|
118
|
+
/// (it is parked on the stack between `invoke_on_dispatch` and the
|
|
119
|
+
/// eventual `funcall` return), and the SPEC.md Single-Invocation Slot
|
|
120
|
+
/// invariant (one Invocation per OS thread for the duration of any
|
|
121
|
+
/// invocation) guarantees no other Rust frame can observe it. Callers
|
|
122
|
+
/// must not retain the returned `&mut` past the synchronous Ruby
|
|
123
|
+
/// callback that requested it — i.e. only use it inside one short
|
|
124
|
+
/// magnus method body and let the borrow end before the method returns.
|
|
125
|
+
pub(crate) fn current_caller<'a>() -> Option<&'a mut Caller<'a, Invocation>> {
|
|
126
|
+
let raw: NonNull<()> = ACTIVE_CALLER.with(|c| c.get())?;
|
|
127
|
+
// SAFETY: see item doc.
|
|
128
|
+
Some(unsafe { &mut *raw.as_ptr().cast::<Caller<'a, Invocation>>() })
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/// Drive a single `__kobako_dispatch` invocation end-to-end. Entry point
|
|
132
|
+
/// from the wasmtime closure built in `super::Runtime::build`.
|
|
133
|
+
///
|
|
134
|
+
/// Returns the packed `(ptr<<32)|len` u64 on success, 0 on any
|
|
135
|
+
/// wire-layer fault. Failure paths log a `[kobako-dispatch]` line to
|
|
136
|
+
/// `stderr` so operators have a breadcrumb when the guest sees a 0
|
|
137
|
+
/// return and traps. The bound dispatch Proc is contracted never to
|
|
138
|
+
/// raise (it folds Service exceptions into Response.err envelopes),
|
|
139
|
+
/// so reaching the failure path is always a wiring bug or wire-layer
|
|
140
|
+
/// fault rather than an expected path.
|
|
141
|
+
pub(crate) fn handle(caller: &mut Caller<'_, Invocation>, req_ptr: i32, req_len: i32) -> i64 {
|
|
142
|
+
// SAFETY: lifetime erased to `NonNull<()>` per the module's
|
|
143
|
+
// Invocation-slot doc. The pointer is restored by `_caller_guard`
|
|
144
|
+
// before this function returns, and only
|
|
145
|
+
// `Runtime#yield_to_active_invocation` (running inside a Ruby
|
|
146
|
+
// callback we are about to invoke) reads it through `current_caller`.
|
|
147
|
+
let ptr: NonNull<()> = NonNull::from(&mut *caller).cast();
|
|
148
|
+
let _caller_guard = CallerGuard::set(ptr);
|
|
149
|
+
|
|
150
|
+
match try_handle(caller, req_ptr, req_len) {
|
|
151
|
+
Ok(packed) => packed,
|
|
152
|
+
Err(reason) => {
|
|
153
|
+
eprintln!("[kobako-dispatch] {}", reason);
|
|
154
|
+
0
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/// Result-returning core of `handle`. Pulled out so each early
|
|
160
|
+
/// failure path carries a diagnostic string instead of an opaque 0.
|
|
161
|
+
fn try_handle(
|
|
162
|
+
caller: &mut Caller<'_, Invocation>,
|
|
163
|
+
req_ptr: i32,
|
|
164
|
+
req_len: i32,
|
|
165
|
+
) -> Result<i64, &'static str> {
|
|
166
|
+
let req_bytes = super::guest_mem::read(caller, req_ptr, req_len)?;
|
|
167
|
+
|
|
168
|
+
// `Kobako::Sandbox` always installs the dispatch Proc before
|
|
169
|
+
// invoking the runtime, so reaching this branch indicates a misuse
|
|
170
|
+
// rather than a normal control path.
|
|
171
|
+
let on_dispatch = caller
|
|
172
|
+
.data()
|
|
173
|
+
.on_dispatch()
|
|
174
|
+
.ok_or("a Sandbox callback fired outside an active Sandbox#run — please report this as a kobako bug")?;
|
|
175
|
+
|
|
176
|
+
let resp_bytes = invoke_on_dispatch(on_dispatch, &req_bytes).map_err(|_| {
|
|
177
|
+
"a Sandbox callback raised an exception instead of returning a fault — please report this as a kobako bug"
|
|
178
|
+
})?;
|
|
179
|
+
|
|
180
|
+
write_response(caller, &resp_bytes)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// Invoke the Ruby-side dispatch +Proc+ with the request bytes and return
|
|
184
|
+
/// the encoded Response bytes. The Proc is contracted to fold every
|
|
185
|
+
/// dispatch failure into a +Response.err+ envelope (see
|
|
186
|
+
/// `Kobako::Transport::Dispatcher.dispatch`), so reaching the error
|
|
187
|
+
/// branch is itself a wire-layer fault rather than a normal control path.
|
|
188
|
+
fn invoke_on_dispatch(
|
|
189
|
+
on_dispatch: Opaque<Value>,
|
|
190
|
+
req_bytes: &[u8],
|
|
191
|
+
) -> Result<Vec<u8>, MagnusError> {
|
|
192
|
+
// The wasmtime callback runs on the same Ruby thread that called the
|
|
193
|
+
// active Sandbox invocation (#eval or #run) — the invariant SPEC
|
|
194
|
+
// Implementation Standards Architecture pins for the host gem — so
|
|
195
|
+
// `Ruby::get()` is always available here. Panicking with `expect`
|
|
196
|
+
// localises the violation rather than letting a nonsense error
|
|
197
|
+
// propagate.
|
|
198
|
+
let ruby = Ruby::get().expect("Ruby handle unavailable in __kobako_dispatch");
|
|
199
|
+
let proc_value: Value = ruby.get_inner(on_dispatch);
|
|
200
|
+
let req_str = ruby.str_from_slice(req_bytes);
|
|
201
|
+
let resp: RString = proc_value.funcall("call", (req_str,))?;
|
|
202
|
+
Ok(super::rstring_to_vec(resp))
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// Allocate a guest-side buffer and copy the response bytes into it via
|
|
206
|
+
/// `super::guest_mem::alloc_and_write`, returning the packed
|
|
207
|
+
/// `(ptr<<32)|len` u64 the guest's `__kobako_dispatch` import expects.
|
|
208
|
+
fn write_response(caller: &mut Caller<'_, Invocation>, bytes: &[u8]) -> Result<i64, &'static str> {
|
|
209
|
+
let ptr = super::guest_mem::alloc_and_write(caller, bytes)?;
|
|
210
|
+
Ok(((ptr as i64) << 32) | (bytes.len() as i64))
|
|
211
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
//! Cached wasmtime export handles for the host-driven ABI surface.
|
|
2
|
+
//!
|
|
3
|
+
//! `Runtime::from_path` resolves the three docs/wire-codec.md ABI exports
|
|
4
|
+
//! the run path drives (`__kobako_eval` / `__kobako_run` /
|
|
5
|
+
//! `__kobako_take_outcome`) once at construction and stores their typed
|
|
6
|
+
//! handles here, so each `#eval` / `#run` calls a cached handle rather than
|
|
7
|
+
//! re-resolving the export by name. Distinct from `super::cache` (the
|
|
8
|
+
//! process-wide Engine / Module cache): this caches *which guest function
|
|
9
|
+
//! to call*, per `Runtime`.
|
|
10
|
+
//!
|
|
11
|
+
//! `__kobako_alloc` is deliberately absent — only `super::dispatch` calls
|
|
12
|
+
//! it, and it does so through `Caller::get_export` on the wasmtime side.
|
|
13
|
+
|
|
14
|
+
use wasmtime::{AsContextMut, Instance as WtInstance, TypedFunc};
|
|
15
|
+
|
|
16
|
+
use super::invocation::StoreCell;
|
|
17
|
+
|
|
18
|
+
/// The cached host-driven export handles. Each is `Option` because test
|
|
19
|
+
/// fixtures (a minimal "ping" module) need not provide them; real
|
|
20
|
+
/// `kobako.wasm` always does, and the run-path methods raise a Ruby
|
|
21
|
+
/// `Kobako::TrapError` (via `require_export`) when a handle is `None`.
|
|
22
|
+
pub(crate) struct Exports {
|
|
23
|
+
pub(crate) eval: Option<TypedFunc<(), ()>>,
|
|
24
|
+
pub(crate) run: Option<TypedFunc<(i32, i32), ()>>,
|
|
25
|
+
pub(crate) take_outcome: Option<TypedFunc<(), u64>>,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
impl Exports {
|
|
29
|
+
/// Best-effort lookup of the three host-driven exports against a
|
|
30
|
+
/// freshly instantiated module. Missing exports are not an error here
|
|
31
|
+
/// (the test fixture is a bare module); the host enforces presence at
|
|
32
|
+
/// invocation time. Only the SPEC ABI shapes are accepted —
|
|
33
|
+
/// `__kobako_eval` is `() -> ()`, `__kobako_run` is
|
|
34
|
+
/// `(env_ptr, env_len) -> ()`, `__kobako_take_outcome` is `() -> u64`
|
|
35
|
+
/// (docs/wire-codec.md § ABI Signatures).
|
|
36
|
+
pub(crate) fn resolve(instance: &WtInstance, store: &StoreCell) -> Self {
|
|
37
|
+
let mut store_ref = store.borrow_mut();
|
|
38
|
+
let mut ctx = store_ref.as_context_mut();
|
|
39
|
+
Self {
|
|
40
|
+
eval: instance
|
|
41
|
+
.get_typed_func::<(), ()>(&mut ctx, "__kobako_eval")
|
|
42
|
+
.ok(),
|
|
43
|
+
run: instance
|
|
44
|
+
.get_typed_func::<(i32, i32), ()>(&mut ctx, "__kobako_run")
|
|
45
|
+
.ok(),
|
|
46
|
+
take_outcome: instance
|
|
47
|
+
.get_typed_func::<(), u64>(&mut ctx, "__kobako_take_outcome")
|
|
48
|
+
.ok(),
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
//! Caller-based guest linear-memory I/O shared by the host-import paths.
|
|
2
|
+
//!
|
|
3
|
+
//! Both directions of a host↔guest buffer handoff that run *inside* a wasm
|
|
4
|
+
//! callback frame go through here: writing the transport Response back
|
|
5
|
+
//! (`super::dispatch`) and shipping block-yield args into the guest
|
|
6
|
+
//! (`drive_yield`, below) performed the same `__kobako_alloc` +
|
|
7
|
+
//! bounds-check + `memory.write` dance with only the diagnostic strings
|
|
8
|
+
//! differing. The Store-based write path (`Runtime::write_envelope`) is a
|
|
9
|
+
//! separate beast — it holds the cached `Store`, not a `Caller` — and stays
|
|
10
|
+
//! in `runtime.rs`.
|
|
11
|
+
|
|
12
|
+
use wasmtime::{Caller, Extern, Memory};
|
|
13
|
+
|
|
14
|
+
use super::invocation::Invocation;
|
|
15
|
+
|
|
16
|
+
/// User-facing reason when a required guest export (the allocation or
|
|
17
|
+
/// block-yield hook) is absent or has the wrong signature — the loaded
|
|
18
|
+
/// `data/kobako.wasm` does not match the installed gem. Phrased in caller
|
|
19
|
+
/// vocabulary: the underlying hook symbol names are not actionable, and
|
|
20
|
+
/// the actionable fix is to rebuild the runtime.
|
|
21
|
+
const RUNTIME_INCOMPATIBLE: &str =
|
|
22
|
+
"the Sandbox runtime is incompatible; rebuild data/kobako.wasm against the installed version";
|
|
23
|
+
|
|
24
|
+
/// Resolve the guest's exported linear `memory`. The lookup shape (and its
|
|
25
|
+
/// diagnostic) is shared by every Caller-based path here — the write side
|
|
26
|
+
/// (`alloc_and_write`), the read side (`read`), and the yield round-trip
|
|
27
|
+
/// (`drive_yield`) — so the "no linear memory" reason lives in one place.
|
|
28
|
+
/// `read` maps the `Err` to its own `None` outcome via `.ok()`.
|
|
29
|
+
fn memory_export(caller: &mut Caller<'_, Invocation>) -> Result<Memory, &'static str> {
|
|
30
|
+
match caller.get_export("memory") {
|
|
31
|
+
Some(Extern::Memory(m)) => Ok(m),
|
|
32
|
+
_ => Err("the loaded Wasm module is not a Kobako-compatible runtime"),
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// Allocate `bytes.len()` bytes in guest memory via `__kobako_alloc` and
|
|
37
|
+
/// copy `bytes` in. Returns the guest pointer. Every failure path carries a
|
|
38
|
+
/// `&'static str` reason so the caller can surface a diagnostic rather than
|
|
39
|
+
/// a silent fault.
|
|
40
|
+
pub(super) fn alloc_and_write(
|
|
41
|
+
caller: &mut Caller<'_, Invocation>,
|
|
42
|
+
bytes: &[u8],
|
|
43
|
+
) -> Result<u32, &'static str> {
|
|
44
|
+
let alloc = match caller.get_export("__kobako_alloc") {
|
|
45
|
+
Some(Extern::Func(f)) => f
|
|
46
|
+
.typed::<i32, i32>(&*caller)
|
|
47
|
+
.map_err(|_| RUNTIME_INCOMPATIBLE)?,
|
|
48
|
+
_ => return Err(RUNTIME_INCOMPATIBLE),
|
|
49
|
+
};
|
|
50
|
+
let len = checked_payload_len(bytes.len())?;
|
|
51
|
+
let ptr = alloc
|
|
52
|
+
.call(&mut *caller, len)
|
|
53
|
+
.map_err(|_| "the Sandbox trapped while allocating memory for the request")?;
|
|
54
|
+
if ptr == 0 {
|
|
55
|
+
return Err("the Sandbox ran out of memory while preparing the request");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let mem = memory_export(caller)?;
|
|
59
|
+
mem.write(&mut *caller, ptr as usize, bytes)
|
|
60
|
+
.map_err(|_| "could not write the request into the Sandbox's memory")?;
|
|
61
|
+
Ok(ptr as u32)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// Copy `[ptr, ptr + len)` out of the guest's linear memory as seen from
|
|
65
|
+
/// `caller`. Each failure carries a `&'static str` reason — matching the
|
|
66
|
+
/// other Caller-based ops here — so the caller surfaces a specific
|
|
67
|
+
/// diagnostic instead of a lumped one; a guest-claimed length past the
|
|
68
|
+
/// 16 MiB cap is a wire violation that names the cap (the caller walks
|
|
69
|
+
/// the trap path on any `Err`).
|
|
70
|
+
pub(super) fn read(
|
|
71
|
+
caller: &mut Caller<'_, Invocation>,
|
|
72
|
+
ptr: i32,
|
|
73
|
+
len: i32,
|
|
74
|
+
) -> Result<Vec<u8>, &'static str> {
|
|
75
|
+
let len = usize::try_from(len).map_err(|_| "the Sandbox produced a negative request length")?;
|
|
76
|
+
if len > MAX_DISPATCH_PAYLOAD {
|
|
77
|
+
return Err("request payload exceeds the 16 MiB limit");
|
|
78
|
+
}
|
|
79
|
+
let mem = memory_export(caller)?;
|
|
80
|
+
let data = mem.data(&caller);
|
|
81
|
+
let start =
|
|
82
|
+
usize::try_from(ptr).map_err(|_| "the Sandbox produced a negative request pointer")?;
|
|
83
|
+
let end = start
|
|
84
|
+
.checked_add(len)
|
|
85
|
+
.ok_or("the Sandbox produced an out-of-range request")?;
|
|
86
|
+
data.get(start..end)
|
|
87
|
+
.map(|s| s.to_vec())
|
|
88
|
+
.ok_or("the Sandbox produced an out-of-bounds request")
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/// Single-dispatch payload cap: 16 MiB in either direction
|
|
92
|
+
/// (SPEC.md § Wire Codec; docs/wire-codec.md § ABI). A host↔guest
|
|
93
|
+
/// transfer larger than this is a wire violation — the Host Gem walks
|
|
94
|
+
/// the trap path rather than allocate or copy the buffer. Held as a
|
|
95
|
+
/// constant for now; a future SPEC anchor may let the Host App raise it.
|
|
96
|
+
pub(super) const MAX_DISPATCH_PAYLOAD: usize = 16 * 1024 * 1024;
|
|
97
|
+
|
|
98
|
+
/// Validate a payload length against `MAX_DISPATCH_PAYLOAD` and narrow it
|
|
99
|
+
/// to `i32` — the signed wasm ABI width for the guest buffer parameters.
|
|
100
|
+
/// Every host *write* boundary (`alloc_and_write`, `drive_yield`,
|
|
101
|
+
/// `Runtime::write_envelope`) routes its length through here so the
|
|
102
|
+
/// wire-violation reason is uniform; the *read* boundaries compare
|
|
103
|
+
/// against `MAX_DISPATCH_PAYLOAD` directly.
|
|
104
|
+
pub(super) fn checked_payload_len(len: usize) -> Result<i32, &'static str> {
|
|
105
|
+
if len > MAX_DISPATCH_PAYLOAD {
|
|
106
|
+
return Err("payload exceeds the 16 MiB limit");
|
|
107
|
+
}
|
|
108
|
+
// The cap above sits below `i32::MAX`, so this conversion cannot wrap.
|
|
109
|
+
i32::try_from(len).map_err(|_| "payload exceeds the 16 MiB limit")
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Compute the half-open range `[ptr, ptr + len)` for a guest linear-memory
|
|
113
|
+
/// copy, validating that the arithmetic does not overflow and the range
|
|
114
|
+
/// fits inside `mem_size`. Shared by `Runtime::write_envelope` (write side)
|
|
115
|
+
/// and `Runtime::fetch_outcome_bytes` (read side).
|
|
116
|
+
pub(super) fn guest_buffer_range(
|
|
117
|
+
ptr: usize,
|
|
118
|
+
len: usize,
|
|
119
|
+
mem_size: usize,
|
|
120
|
+
) -> Result<core::ops::Range<usize>, &'static str> {
|
|
121
|
+
let end = ptr.checked_add(len).ok_or("ptr + len overflow")?;
|
|
122
|
+
if end > mem_size {
|
|
123
|
+
return Err("range exceeds Sandbox memory size");
|
|
124
|
+
}
|
|
125
|
+
Ok(ptr..end)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/// Unpack the `(ptr, len)` u64 returned by `__kobako_take_outcome`:
|
|
129
|
+
/// high 32 bits = ptr, low 32 bits = len. Mirrors the guest-side
|
|
130
|
+
/// `crate::abi::unpack_u64` in `wasm/kobako-wasm/src/abi.rs`.
|
|
131
|
+
pub(super) fn unpack_outcome_packed(packed: u64) -> (usize, usize) {
|
|
132
|
+
let ptr = (packed >> 32) as u32 as usize;
|
|
133
|
+
let len = packed as u32 as usize;
|
|
134
|
+
(ptr, len)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// Allocate `args.len()` bytes in guest memory, copy the args payload in,
|
|
138
|
+
/// call `__kobako_yield_to_block(ptr, len)`, then read the response slice
|
|
139
|
+
/// the guest produced and return it. Mirrors `dispatch::write_response`'s
|
|
140
|
+
/// allocator dance but in the opposite direction — the host is the
|
|
141
|
+
/// *initiator* of this round-trip, not the responder.
|
|
142
|
+
pub(super) fn drive_yield(
|
|
143
|
+
caller: &mut Caller<'_, Invocation>,
|
|
144
|
+
args: &[u8],
|
|
145
|
+
) -> Result<Vec<u8>, &'static str> {
|
|
146
|
+
let len_i32 = checked_payload_len(args.len())?;
|
|
147
|
+
let req_ptr = alloc_and_write(caller, args)? as i32;
|
|
148
|
+
|
|
149
|
+
let yield_fn = match caller.get_export("__kobako_yield_to_block") {
|
|
150
|
+
Some(Extern::Func(f)) => f
|
|
151
|
+
.typed::<(i32, i32), u64>(&*caller)
|
|
152
|
+
.map_err(|_| RUNTIME_INCOMPATIBLE)?,
|
|
153
|
+
_ => return Err(RUNTIME_INCOMPATIBLE),
|
|
154
|
+
};
|
|
155
|
+
let packed = yield_fn
|
|
156
|
+
.call(&mut *caller, (req_ptr, len_i32))
|
|
157
|
+
.map_err(|_| "the Sandbox trapped while invoking a block")?;
|
|
158
|
+
let (resp_ptr, resp_len) = unpack_outcome_packed(packed);
|
|
159
|
+
if resp_len == 0 {
|
|
160
|
+
return Err("the Sandbox returned an empty block result");
|
|
161
|
+
}
|
|
162
|
+
if resp_len > MAX_DISPATCH_PAYLOAD {
|
|
163
|
+
return Err("block result payload exceeds the 16 MiB limit");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
let mem = memory_export(caller)?;
|
|
167
|
+
let data = mem.data(&caller);
|
|
168
|
+
let range = guest_buffer_range(resp_ptr, resp_len, data.len())
|
|
169
|
+
.map_err(|_| "the Sandbox returned an out-of-bounds block result")?;
|
|
170
|
+
Ok(data[range].to_vec())
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
#[cfg(test)]
|
|
174
|
+
mod tests {
|
|
175
|
+
use super::{
|
|
176
|
+
checked_payload_len, guest_buffer_range, unpack_outcome_packed, MAX_DISPATCH_PAYLOAD,
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
#[test]
|
|
180
|
+
fn checked_payload_len_accepts_zero_and_the_cap() {
|
|
181
|
+
assert_eq!(checked_payload_len(0), Ok(0));
|
|
182
|
+
assert_eq!(
|
|
183
|
+
checked_payload_len(MAX_DISPATCH_PAYLOAD),
|
|
184
|
+
Ok(MAX_DISPATCH_PAYLOAD as i32)
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
#[test]
|
|
189
|
+
fn checked_payload_len_rejects_past_the_cap() {
|
|
190
|
+
assert!(checked_payload_len(MAX_DISPATCH_PAYLOAD + 1).is_err());
|
|
191
|
+
assert!(checked_payload_len(usize::MAX).is_err());
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
#[test]
|
|
195
|
+
fn guest_buffer_range_returns_half_open_range() {
|
|
196
|
+
assert_eq!(guest_buffer_range(10, 5, 100), Ok(10..15));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#[test]
|
|
200
|
+
fn guest_buffer_range_accepts_zero_length_at_any_in_bounds_ptr() {
|
|
201
|
+
assert_eq!(guest_buffer_range(0, 0, 0), Ok(0..0));
|
|
202
|
+
assert_eq!(guest_buffer_range(42, 0, 100), Ok(42..42));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
#[test]
|
|
206
|
+
fn guest_buffer_range_rejects_ptr_plus_len_overflow() {
|
|
207
|
+
assert!(guest_buffer_range(usize::MAX, 1, usize::MAX).is_err());
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
#[test]
|
|
211
|
+
fn guest_buffer_range_rejects_end_past_memory() {
|
|
212
|
+
assert!(guest_buffer_range(10, 100, 50).is_err());
|
|
213
|
+
assert_eq!(guest_buffer_range(0, 50, 50), Ok(0..50));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
#[test]
|
|
217
|
+
fn unpack_outcome_packed_extracts_high_ptr_low_len() {
|
|
218
|
+
assert_eq!(
|
|
219
|
+
unpack_outcome_packed(0xAABB_CCDD_1122_3344),
|
|
220
|
+
(0xAABB_CCDD, 0x1122_3344)
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
#[test]
|
|
225
|
+
fn unpack_outcome_packed_zero_decodes_to_zero_pair() {
|
|
226
|
+
assert_eq!(unpack_outcome_packed(0), (0, 0));
|
|
227
|
+
}
|
|
228
|
+
}
|