Skip to main content

nodejs/
embed.rs

1//! Uniform embedding entry point: run a whole program against a string stdin
2//! and get its stdout back.
3
4use std::cell::Cell;
5use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
6
7thread_local! {
8    /// Set on the thread [`run_program`] spawns: `process.exit` unwinds to it
9    /// instead of ending the process.
10    static EMBEDDED: Cell<bool> = const { Cell::new(false) };
11}
12
13/// Unwind payload carrying a `process.exit` code back to [`run_program`].
14struct EmbedExit(i32);
15
16/// Called by `process.exit` / `process.abort` before they end the process:
17/// on a [`run_program`] thread, unwind to it with `code` instead. Returns
18/// (does nothing) everywhere else. `resume_unwind` skips the panic hook, so
19/// nothing is printed.
20pub(crate) fn exit_if_embedded(code: i32) {
21    if EMBEDDED.with(Cell::get) {
22        resume_unwind(Box::new(EmbedExit(code)));
23    }
24}
25
26/// Run `src` as a complete program with `input` as its stdin and return
27/// everything it wrote to stdout.
28///
29/// Each call runs on its own thread with [`crate::JS_STACK_SIZE`] of stack and
30/// a freshly reset host, so nothing leaks between calls and concurrent calls
31/// never share a buffer. Stdout writes (`console.log`, `process.stdout.write`)
32/// are captured through [`crate::host::JsHost::begin_stdout_capture`]; stderr
33/// still reaches the process. `process.stdin`, `fs.readFileSync(0)` and
34/// `readline` read `input`.
35///
36/// A compile error, an uncaught exception, a nonzero `process.exitCode` or
37/// `process.exit(n)` with n != 0, and a panic inside the runtime return `Err`.
38/// `process.exit(0)` returns `Ok` with the output written so far.
39pub fn run_program(src: &str, input: &str) -> Result<String, String> {
40    let (src, input) = (src.to_owned(), input.to_owned());
41    std::thread::Builder::new()
42        .name("node-js-embed".into())
43        .stack_size(crate::JS_STACK_SIZE)
44        .spawn(move || run_captured(&src, &input))
45        .map_err(|e| format!("node-js: cannot spawn interpreter thread: {e}"))?
46        .join()
47        .unwrap_or_else(|p| Err(panic_message(p.as_ref())))
48}
49
50fn run_captured(src: &str, input: &str) -> Result<String, String> {
51    EMBEDDED.with(|e| e.set(true));
52    let run = catch_unwind(AssertUnwindSafe(|| {
53        crate::run_on_fresh_host(src, |h| {
54            h.set_stdin(input.as_bytes());
55            h.begin_stdout_capture();
56        })
57    }));
58    let (result, output, code) = match run {
59        Ok((result, output)) => (result, output, crate::exit_code().unwrap_or(0)),
60        Err(payload) => match payload.downcast::<EmbedExit>() {
61            Ok(exit) => {
62                let output = crate::host::with_host(|h| h.end_capture());
63                (Ok(fusevm::Value::Undef), output, exit.0)
64            }
65            Err(p) => return Err(panic_message(p.as_ref())),
66        },
67    };
68    match (result, code) {
69        (Err(e), _) => Err(e),
70        (Ok(_), 0) => Ok(output),
71        (Ok(_), code) => Err(format!("exit status {code}")),
72    }
73}
74
75fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
76    let msg = payload
77        .downcast_ref::<&str>()
78        .map(|s| s.to_string())
79        .or_else(|| payload.downcast_ref::<String>().cloned())
80        .unwrap_or_else(|| "unknown panic".to_string());
81    format!("node-js: interpreter panicked: {msg}")
82}