1use std::cell::Cell;
5use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
6
7thread_local! {
8 static EMBEDDED: Cell<bool> = const { Cell::new(false) };
11}
12
13struct EmbedExit(i32);
15
16pub(crate) fn exit_if_embedded(code: i32) {
21 if EMBEDDED.with(Cell::get) {
22 resume_unwind(Box::new(EmbedExit(code)));
23 }
24}
25
26pub 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}