Skip to main content

rpc/natives/
env_io.rs

1//! Host output channel for the eval-mode module.
2//!
3//! PRINT / DISPLAY / NEWLINE / DEBUG lower to a call into the `env.log`
4//! import (`(i32 level, i32 ptr, i32 len) -> ()`), reading the message from
5//! the guest's exported linear memory. Script mode wires this in
6//! `scripting::host`; the rpc Session path needs the same import or those
7//! natives can't compile. Output is routed to `tracing` (the rpc channel has
8//! no separate stdout) — same sink and level mapping as the script-mode host.
9
10use scripting::runtime::logged_values;
11use wasmtime::{AnyRef, Caller, Extern, Linker, Rooted};
12
13use crate::session::SessionData;
14
15pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
16    linker.func_wrap(
17        "env",
18        "log",
19        |mut caller: Caller<'_, SessionData>, level: u32, ptr: u32, len: u32| {
20            let Some(Extern::Memory(memory)) = caller.get_export("memory") else {
21                return;
22            };
23            let data = memory.data(&caller);
24            // `ptr`/`len` are guest-controlled; compute the end with a checked
25            // add so a hostile/overflowing range is rejected (not wrapped in
26            // release / panicked in debug) before the slice.
27            let start = ptr as usize;
28            let Some(end) = start.checked_add(len as usize) else {
29                return;
30            };
31            let Some(bytes) = data.get(start..end) else {
32                return;
33            };
34            let Ok(msg) = std::str::from_utf8(bytes) else {
35                return;
36            };
37            // Capture into the per-request buffer (for the SLYNK mREPL's
38            // `:write-string`) AND tee to tracing (the sshd / text-REPL paths,
39            // which don't drain the buffer, still see it in logs).
40            caller.data().push_output(msg);
41            match level {
42                0 => tracing::debug!("[script] {msg}"),
43                1 => tracing::info!("[script] {msg}"),
44                2 => tracing::warn!("[script] {msg}"),
45                _ => tracing::error!("[script] {msg}"),
46            }
47        },
48    )?;
49    linker.func_wrap(
50        "env",
51        "log_value",
52        |mut caller: Caller<'_, SessionData>,
53         args: Option<Rooted<AnyRef>>|
54         -> wasmtime::Result<i32> {
55            let Some(msg) = logged_values(&mut caller, args)? else {
56                return Ok(1);
57            };
58            caller.data().push_output(&msg);
59            tracing::debug!("[script] {msg}");
60            Ok(0)
61        },
62    )?;
63    Ok(())
64}
65
66/// Links a NO-OP `env.log` for the render surface; `env.log_value` decodes
67/// its values, discards the text, and answers 1 for an unreadable one like
68/// the other linkers. Eval-mode modules always
69/// import `env.log` (PRINT/DISPLAY/DEBUG lower to it), so the import must
70/// resolve — but a template is untrusted source with no legitimate output
71/// channel, so render discards the message entirely: no per-request buffer
72/// append, no `tracing` tee. This closes the log-flood / unbounded-host-memory
73/// side channel a real `env.log` would hand an attacker-controlled template.
74pub fn register_silent(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
75    linker.func_wrap(
76        "env",
77        "log",
78        |_caller: Caller<'_, SessionData>, _level: u32, _ptr: u32, _len: u32| {},
79    )?;
80    linker.func_wrap(
81        "env",
82        "log_value",
83        |mut caller: Caller<'_, SessionData>,
84         args: Option<Rooted<AnyRef>>|
85         -> wasmtime::Result<i32> {
86            Ok(i32::from(logged_values(&mut caller, args)?.is_none()))
87        },
88    )?;
89    Ok(())
90}
91
92#[cfg(test)]
93#[path = "env_io_tests.rs"]
94mod tests;