1use super::arg_str;
36use crate::host::{with_host, IoTask, JsObj};
37use fusevm::Value;
38use indexmap::IndexMap;
39use std::process::{Child, Command, Stdio};
40use std::sync::atomic::{AtomicU64, Ordering};
41use std::sync::mpsc::Sender;
42use std::sync::{Arc, Mutex};
43
44pub const METHODS: &[&str] = &[
45 "execSync",
46 "spawnSync",
47 "execFileSync",
48 "exec",
49 "execFile",
50 "spawn",
51 "fork",
52];
53
54pub const CHILD_PROCESS_METHODS: &[&str] = &["kill", "send", "disconnect", "ref", "unref"];
57
58pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
59 Some(match method {
60 "execSync" => exec_sync(args),
61 "spawnSync" => spawn_sync(args),
62 "execFileSync" => exec_file_sync(args),
63 "exec" => exec(args),
64 "execFile" => exec_file(args),
65 "spawn" => spawn(args),
66 "@@childEvents" => {
67 let child = args.first().cloned().unwrap_or(Value::Undef);
68 child_events(&child).map(|_| Value::Undef)
69 }
70 "fork" => fork(args),
71 _ => return None,
72 })
73}
74
75static NEXT_CHILD_ID: AtomicU64 = AtomicU64::new(1);
79
80struct ChildRec {
83 emitter: Value,
84 handle: Arc<Mutex<Option<Child>>>,
85}
86
87thread_local! {
88 static CHILDREN: std::cell::RefCell<std::collections::HashMap<u64, ChildRec>> =
89 std::cell::RefCell::new(std::collections::HashMap::new());
90}
91
92fn child_object(extra: IndexMap<String, Value>) -> Value {
95 super::net::new_emitter_object("ChildProcess", extra)
96}
97
98#[derive(Clone)]
101struct Run {
102 status: Option<i32>,
103 signal: Option<i32>,
105 stdout: Vec<u8>,
106 stderr: Vec<u8>,
107 pid: u32,
108}
109
110#[derive(Default)]
112struct SpawnOpts {
113 input: Option<Vec<u8>>,
114 env: Option<Vec<(String, String)>>,
116 cwd: Option<String>,
117}
118
119fn spawn_opts(args: &[Value], idx: usize) -> SpawnOpts {
126 let Some(opts) = args.get(idx) else {
127 return SpawnOpts::default();
128 };
129 let read = |k: &str| crate::builtins::get_property(opts, k).ok();
130 let input = match read("input") {
131 Some(Value::Undef) | None => None,
132 Some(v) => Some(super::arg_str(&[v], 0).into_bytes()),
133 };
134 let cwd = match read("cwd") {
135 Some(Value::Undef) | None => None,
136 Some(v) => Some(with_host(|h| h.str_of(&v))),
137 };
138 let env = match read("env") {
139 Some(v) if with_host(|h| matches!(h.get(&v), Some(JsObj::Object(_)))) => {
140 let keys = with_host(|h| match h.get(&v) {
141 Some(JsObj::Object(m)) => m
142 .keys()
143 .filter(|k| !k.starts_with("@@"))
144 .cloned()
145 .collect::<Vec<_>>(),
146 _ => Vec::new(),
147 });
148 Some(
149 keys.into_iter()
150 .filter_map(|k| {
151 let val = crate::builtins::get_property(&v, &k).ok()?;
152 Some((k, with_host(|h| h.str_of(&val))))
153 })
154 .collect(),
155 )
156 }
157 _ => None,
158 };
159 SpawnOpts { input, env, cwd }
160}
161
162fn run(program: &str, args: &[String], opts: &SpawnOpts) -> std::io::Result<Run> {
165 let input = opts.input.as_deref();
166 let mut cmd = Command::new(program);
167 cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped());
168 if let Some(dir) = &opts.cwd {
169 cmd.current_dir(dir);
170 }
171 if let Some(vars) = &opts.env {
172 cmd.env_clear();
173 for (k, v) in vars {
174 cmd.env(k, v);
175 }
176 }
177 cmd.stdin(if input.is_some() {
178 Stdio::piped()
179 } else {
180 Stdio::inherit()
181 });
182 let mut child = cmd.spawn()?;
183 let pid = child.id();
184 if let Some(bytes) = input {
185 if let Some(mut stdin) = child.stdin.take() {
186 use std::io::Write as _;
187 let _ = stdin.write_all(bytes);
188 }
190 }
191 let out = child.wait_with_output()?;
192 #[cfg(unix)]
193 let signal = std::os::unix::process::ExitStatusExt::signal(&out.status);
194 #[cfg(not(unix))]
195 let signal = None;
196 Ok(Run {
197 status: out.status.code(),
198 signal,
199 stdout: out.stdout,
200 stderr: out.stderr,
201 pid,
202 })
203}
204
205fn echo_stderr(args: &[Value], opts_idx: usize, bytes: &[u8]) {
214 if bytes.is_empty() {
215 return;
216 }
217 let explicit_stdio = args
218 .get(opts_idx)
219 .and_then(|o| crate::builtins::get_property(o, "stdio").ok())
220 .is_some_and(|v| !matches!(v, Value::Undef));
221 if explicit_stdio {
222 return;
223 }
224 let text = String::from_utf8_lossy(bytes).into_owned();
225 with_host(|h| h.write_out(&text, true));
226}
227
228fn command_failed(cmd: &str, r: &Run, enc: Option<&str>) -> String {
235 let tail = String::from_utf8_lossy(&r.stderr).into_owned();
236 let msg = format!("Command failed: {cmd}\n{tail}");
237 let stdout = output_value(&r.stdout, enc);
240 let stderr = output_value(&r.stderr, enc);
241 let e = crate::builtins::make_error_pub("Error", &msg);
244 let null = with_host(|h| h.null());
245 let status = r
246 .status
247 .map(|c| Value::Float(c as f64))
248 .unwrap_or_else(|| null.clone());
249 for (k, v) in [
250 ("status", status),
251 ("signal", null),
252 ("pid", Value::Float(r.pid as f64)),
253 ("stdout", stdout),
254 ("stderr", stderr),
255 ] {
256 let _ = crate::builtins::set_property_pub(&e, k, v);
257 }
258 with_host(|h| h.exc = Some(e));
259 format!("Error: {msg}")
260}
261
262fn exec_error(cmd: &str, r: &Run) -> Value {
266 let tail = String::from_utf8_lossy(&r.stderr).into_owned();
267 let e = crate::builtins::make_error_pub("Error", &format!("Command failed: {cmd}\n{tail}"));
268 let null = with_host(|h| h.null());
269 let cmd_v = with_host(|h| h.new_str(cmd.to_string()));
270 for (k, v) in [
271 ("killed", Value::Bool(false)),
272 ("code", Value::Float(r.status.unwrap_or(-1) as f64)),
273 ("signal", null),
274 ("cmd", cmd_v),
275 ] {
276 let _ = crate::builtins::set_property_pub(&e, k, v);
277 }
278 e
279}
280
281fn spawn_error(file: &str, argv: &[String], e: &std::io::Error) -> Value {
286 let code = super::fs::libuv_code(e);
287 let err = crate::builtins::make_error_pub("Error", &format!("spawn {file} {code}"));
288 let errno = -f64::from(e.raw_os_error().unwrap_or(5));
289 let (code_v, syscall, path, spawnargs) = with_host(|h| {
290 let items = argv.iter().map(|a| h.new_str(a.clone())).collect();
291 (
292 h.new_str(code.to_string()),
293 h.new_str(format!("spawn {file}")),
294 h.new_str(file.to_string()),
295 h.new_array(items),
296 )
297 });
298 for (k, v) in [
299 ("errno", Value::Float(errno)),
300 ("code", code_v),
301 ("syscall", syscall),
302 ("path", path),
303 ("spawnargs", spawnargs),
304 ] {
305 let _ = crate::builtins::set_property_pub(&err, k, v);
306 }
307 err
308}
309
310fn exec_sync(args: &[Value]) -> Result<Value, String> {
313 let cmd = arg_str(args, 0);
314 let enc = opts_encoding(args, 1);
315 let r = run("sh", &["-c".to_string(), cmd.clone()], &spawn_opts(args, 1))
316 .map_err(|e| format!("Error: {e}"))?;
317 echo_stderr(args, 1, &r.stderr);
318 if r.status != Some(0) {
319 return Err(command_failed(&cmd, &r, enc.as_deref()));
320 }
321 Ok(output_value(&r.stdout, enc.as_deref()))
322}
323
324fn spawn_sync(args: &[Value]) -> Result<Value, String> {
327 let cmd = arg_str(args, 0);
328 let cmd_args = arg_array(args, 1);
329 let enc = opts_encoding(args, 2);
330 match run(&cmd, &cmd_args, &spawn_opts(args, 2)) {
331 Ok(r) => {
332 let stdout = output_value(&r.stdout, enc.as_deref());
336 let stderr = output_value(&r.stderr, enc.as_deref());
337 Ok(with_host(|h| {
338 let mut m = IndexMap::new();
339 m.insert("pid".into(), Value::Float(r.pid as f64));
340 m.insert(
341 "status".into(),
342 r.status
343 .map(|c| Value::Float(c as f64))
344 .unwrap_or_else(|| h.null()),
345 );
346 m.insert("signal".into(), h.null());
349 m.insert("stdout".into(), stdout);
350 m.insert("stderr".into(), stderr);
351 h.new_object(m)
352 }))
353 }
354 Err(e) => Ok(with_host(|h| {
357 let mut m = IndexMap::new();
358 m.insert("pid".into(), Value::Float(0.0));
359 m.insert("status".into(), h.null());
360 m.insert("signal".into(), h.null());
361 m.insert("stdout".into(), h.null());
362 m.insert("stderr".into(), h.null());
363 m.insert("error".into(), h.new_str(format!("Error: spawn {cmd} {e}")));
364 h.new_object(m)
365 })),
366 }
367}
368
369fn exec_file_sync(args: &[Value]) -> Result<Value, String> {
372 let file = arg_str(args, 0);
373 let cmd_args = arg_array(args, 1);
374 let enc = opts_encoding(args, 2);
375 let r = run(&file, &cmd_args, &spawn_opts(args, 2))
376 .map_err(|e| format!("Error: spawn {file} {e}"))?;
377 echo_stderr(args, 2, &r.stderr);
378 if r.status != Some(0) {
379 return Err(command_failed(&file, &r, enc.as_deref()));
383 }
384 Ok(output_value(&r.stdout, enc.as_deref()))
385}
386
387fn exec(args: &[Value]) -> Result<Value, String> {
391 let cmd = arg_str(args, 0);
392 let cb = args
394 .last()
395 .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
396 .cloned();
397 let sh_args = ["-c".to_string(), cmd.clone()];
402 let result = run("/bin/sh", &sh_args, &spawn_opts(args, 1));
403 let child = spawned_child(
404 "/bin/sh",
405 &sh_args,
406 [Disposition::Pipe; 3],
407 clone_run(&result),
408 );
409 let Some(cb) = cb else {
410 return Ok(child);
411 };
412 let (err, out, errout) = match result {
413 Ok(r) => {
414 let stdout = String::from_utf8_lossy(&r.stdout).into_owned();
415 let stderr = String::from_utf8_lossy(&r.stderr).into_owned();
416 let err = if r.status == Some(0) {
423 with_host(|h| h.null())
424 } else {
425 exec_error(&cmd, &r)
426 };
427 (err, stdout, stderr)
428 }
429 Err(e) => (
430 with_host(|h| crate::builtins::synth_error(h, &format!("Error: {e}"))),
431 String::new(),
432 String::new(),
433 ),
434 };
435 let (so, se) = with_host(|h| (h.new_str(out), h.new_str(errout)));
436 on_close_call(&child, cb, vec![err, so, se])?;
437 Ok(child)
438}
439
440fn clone_run(r: &std::io::Result<Run>) -> std::io::Result<Run> {
443 match r {
444 Ok(run) => Ok(run.clone()),
445 Err(e) => Err(match e.raw_os_error() {
446 Some(code) => std::io::Error::from_raw_os_error(code),
447 None => std::io::Error::new(e.kind(), e.to_string()),
448 }),
449 }
450}
451
452fn spawn(args: &[Value]) -> Result<Value, String> {
456 let cmd = arg_str(args, 0);
457 let cmd_args = arg_array(args, 1);
458 let disp = stdio_dispositions(args.get(2));
459 let result = run(&cmd, &cmd_args, &spawn_opts(args, 2));
460 Ok(spawned_child(&cmd, &cmd_args, disp, result))
461}
462
463fn spawned_child(
467 cmd: &str,
468 cmd_args: &[String],
469 disp: [Disposition; 3],
470 result: std::io::Result<Run>,
471) -> Value {
472 let null = with_host(|h| h.null());
473 let pipe = |d: Disposition| match d {
474 Disposition::Pipe => child_pipe(),
475 _ => null.clone(),
476 };
477 let (stdout, stderr) = (pipe(disp[1]), pipe(disp[2]));
478 let mut m = IndexMap::new();
479 let (status, signal, out, err, spawn_err) = match result {
480 Ok(r) => {
481 m.insert("pid".into(), Value::Float(r.pid as f64));
482 (r.status, r.signal, r.stdout, r.stderr, None)
483 }
484 Err(e) => {
487 m.insert("pid".into(), Value::Undef);
488 (
489 None,
490 None,
491 Vec::new(),
492 Vec::new(),
493 Some(spawn_error(cmd, cmd_args, &e)),
494 )
495 }
496 };
497 m.insert("exitCode".into(), null.clone());
500 m.insert("signalCode".into(), null.clone());
501 m.insert("killed".into(), Value::Bool(false));
502 m.insert("connected".into(), Value::Bool(false));
503 m.insert("stdout".into(), stdout);
504 m.insert("stderr".into(), stderr);
505 let child = child_object(m);
506 PENDING.with(|p| {
507 p.borrow_mut().push(Finished {
508 child: child.clone(),
509 status,
510 signal,
511 out,
512 err,
513 disp,
514 spawn_err,
515 })
516 });
517 with_host(|h| {
518 let cb = h.alloc(JsObj::Builtin("child_process.@@childEvents".into()));
519 h.add_timer(-1.0, cb, vec![child.clone()], None);
520 });
521 child
522}
523
524fn on_close_call(child: &Value, cb: Value, cb_args: Vec<Value>) -> Result<(), String> {
528 thread_local! {
529 static BIND: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
530 }
531 let bind = match BIND.with(|b| b.borrow().clone()) {
532 Some(f) => f,
533 None => {
534 let f = crate::eval_internal(
535 "(function (cb, args) { return function () { Reflect.apply(cb, undefined, args); }; })",
536 )?;
537 BIND.with(|b| *b.borrow_mut() = Some(f.clone()));
538 f
539 }
540 };
541 let args = with_host(|h| h.new_array(cb_args));
542 let listener = crate::host::invoke(&bind, vec![cb, args], None)?;
543 let close = with_host(|h| h.new_str("close"));
544 super::events::instance_call(child, "on", vec![close, listener])?;
545 Ok(())
546}
547
548#[derive(Clone, Copy, PartialEq)]
550enum Disposition {
551 Pipe,
553 Inherit,
555 Ignore,
556}
557
558fn stdio_dispositions(opts: Option<&Value>) -> [Disposition; 3] {
562 let Some(stdio) = opts.and_then(|o| crate::builtins::get_property(o, "stdio").ok()) else {
563 return [Disposition::Pipe; 3];
564 };
565 let one = |v: &Value| -> Disposition {
566 match v {
567 Value::Float(_) | Value::Int(_) => Disposition::Inherit,
568 Value::Undef => Disposition::Pipe,
569 _ => with_host(|h| {
570 if h.is_null(v) {
571 return Disposition::Pipe;
572 }
573 if matches!(h.get(v), Some(JsObj::Object(_))) {
574 return Disposition::Inherit;
575 }
576 match h.str_of(v).as_str() {
577 "inherit" => Disposition::Inherit,
578 "ignore" => Disposition::Ignore,
579 _ => Disposition::Pipe,
580 }
581 }),
582 }
583 };
584 let items = with_host(|h| match h.get(&stdio) {
585 Some(JsObj::Array(items)) => Some(items.clone()),
586 _ => None,
587 });
588 match items {
589 Some(items) => {
590 let at = |i: usize| one(items.get(i).unwrap_or(&Value::Undef));
591 [at(0), at(1), at(2)]
592 }
593 None => [one(&stdio); 3],
594 }
595}
596
597struct Finished {
599 child: Value,
600 status: Option<i32>,
601 signal: Option<i32>,
602 out: Vec<u8>,
603 err: Vec<u8>,
604 disp: [Disposition; 3],
605 spawn_err: Option<Value>,
606}
607
608thread_local! {
609 static PENDING: std::cell::RefCell<Vec<Finished>> = const { std::cell::RefCell::new(Vec::new()) };
610}
611
612fn child_pipe() -> Value {
615 super::net::new_emitter_object("ChildPipe", IndexMap::new())
616}
617
618pub const CHILD_PIPE_METHODS: &[&str] = &["setEncoding", "pipe", "resume", "pause", "destroy"];
620
621pub fn pipe_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
622 if !CHILD_PIPE_METHODS.contains(&method) && super::events::METHODS.contains(&method) {
623 return super::events::instance_call(recv, method, args);
624 }
625 match method {
626 "setEncoding" => {
627 let enc = match args.first() {
628 Some(v) if !matches!(v, Value::Undef) => arg_str(&args, 0),
629 _ => "utf8".to_string(),
630 };
631 set_prop(recv, "@@encoding", with_host(|h| h.new_str(enc)));
632 Ok(recv.clone())
633 }
634 "pipe" => {
635 let dest = args.first().cloned().unwrap_or(Value::Undef);
636 set_prop(recv, "@@pipeDest", dest.clone());
637 Ok(dest)
638 }
639 "resume" | "pause" | "destroy" => Ok(recv.clone()),
640 _ => Err(crate::host::type_error(&format!(
641 "{method} is not a function"
642 ))),
643 }
644}
645
646fn prop(v: &Value, key: &str) -> Option<Value> {
647 with_host(|h| match h.get(v) {
648 Some(JsObj::Object(p)) => p.get(key).cloned(),
649 _ => None,
650 })
651}
652
653fn emit(target: &Value, event: &str, mut args: Vec<Value>) -> Result<(), String> {
654 args.insert(0, with_host(|h| h.new_str(event)));
655 super::events::instance_call(target, "emit", args).map(|_| ())
656}
657
658fn pipe_output(pipe: &Value, bytes: &[u8]) -> Result<(), String> {
661 let dest = prop(pipe, "@@pipeDest");
662 if !bytes.is_empty() {
663 let enc = prop(pipe, "@@encoding").map(|v| with_host(|h| h.str_of(&v)));
664 let chunk = output_value(bytes, enc.as_deref());
665 if let Some(dest) = &dest {
666 crate::host::call_method(dest, "write", vec![chunk.clone()])?;
667 }
668 emit(pipe, "data", vec![chunk])?;
669 }
670 if let Some(dest) = &dest {
671 let is_std = super::native_tag(dest).as_deref() == Some("WriteStream");
672 if !is_std {
673 crate::host::call_method(dest, "end", Vec::new())?;
674 }
675 }
676 emit(pipe, "end", Vec::new())
677}
678
679fn child_events(child: &Value) -> Result<(), String> {
684 let found = PENDING.with(|p| {
685 let mut p = p.borrow_mut();
686 let i = p
687 .iter()
688 .position(|f| with_host(|h| h.strict_eq(&f.child, child)))?;
689 Some(p.remove(i))
690 });
691 let Some(f) = found else { return Ok(()) };
692 let null = with_host(|h| h.null());
693 if let Some(err) = f.spawn_err {
694 emit(child, "error", vec![err])?;
695 return emit(child, "close", vec![Value::Float(-2.0), null]);
696 }
697 emit(child, "spawn", Vec::new())?;
698 let pipes = [prop(child, "stdout"), prop(child, "stderr")];
699 for (i, bytes) in [(1, &f.out), (2, &f.err)] {
700 match f.disp[i] {
701 Disposition::Pipe => {
702 if let Some(p) = &pipes[i - 1] {
703 pipe_output(p, bytes)?;
704 }
705 }
706 Disposition::Inherit => with_host(|h| h.write_out_bytes(bytes, i == 2)),
707 Disposition::Ignore => {}
708 }
709 }
710 let code = f
711 .status
712 .map_or_else(|| null.clone(), |c| Value::Float(c as f64));
713 let signal = match f.signal.and_then(signal_name) {
714 Some(name) => with_host(|h| h.new_str(name)),
715 None => null.clone(),
716 };
717 set_prop(child, "exitCode", code.clone());
718 set_prop(child, "signalCode", signal.clone());
719 emit(child, "exit", vec![code.clone(), signal.clone()])?;
720 emit(child, "close", vec![code, signal])?;
721 for (i, p) in pipes.iter().enumerate() {
722 if let (Some(p), Disposition::Pipe) = (p, f.disp[i + 1]) {
723 emit(p, "close", Vec::new())?;
724 }
725 }
726 Ok(())
727}
728
729fn signal_name(n: i32) -> Option<&'static str> {
732 const NAMES: &[&str] = &[
733 "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", "SIGBUS", "SIGFPE",
734 "SIGKILL", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGCHLD",
735 "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGWINCH",
736 ];
737 NAMES
738 .iter()
739 .copied()
740 .find(|name| super::process::signal_number(name) == Some(n))
741}
742
743fn exec_file(args: &[Value]) -> Result<Value, String> {
748 let file = arg_str(args, 0);
749 let cmd_args = arg_array(args, 1);
750 let cb = args
752 .iter()
753 .rev()
754 .find(|v| with_host(|h| crate::host::is_callable(h, v)))
755 .cloned();
756
757 let full_cmd = std::iter::once(file.clone())
758 .chain(cmd_args.iter().cloned())
759 .collect::<Vec<_>>()
760 .join(" ");
761
762 match run(&file, &cmd_args, &spawn_opts(args, 2)) {
763 Ok(r) => {
764 let stdout_buf = super::buffer::from_bytes(&r.stdout);
765 let stderr_buf = super::buffer::from_bytes(&r.stderr);
766 let null = with_host(|h| h.null());
767 if let Some(cb) = cb {
768 let so = String::from_utf8_lossy(&r.stdout).into_owned();
769 let se = String::from_utf8_lossy(&r.stderr).into_owned();
770 let err = if r.status == Some(0) {
777 null.clone()
778 } else {
779 exec_error(&full_cmd, &r)
780 };
781 with_host(|h| {
782 let so = h.new_str(so);
783 let se = h.new_str(se);
784 h.queue_io_callback(cb, vec![err, so, se]);
785 });
786 }
787 let mut m = IndexMap::new();
788 m.insert("pid".into(), Value::Float(r.pid as f64));
789 m.insert(
790 "exitCode".into(),
791 r.status
792 .map(|c| Value::Float(c as f64))
793 .unwrap_or_else(|| null.clone()),
794 );
795 m.insert("signalCode".into(), null);
796 m.insert("killed".into(), Value::Bool(false));
797 m.insert("connected".into(), Value::Bool(false));
798 m.insert("stdout".into(), stdout_buf);
799 m.insert("stderr".into(), stderr_buf);
800 Ok(child_object(m))
801 }
802 Err(e) => {
806 let err = spawn_error(&file, &cmd_args, &e);
807 if let Some(cb) = cb {
808 let (empty1, empty2) = with_host(|h| (h.new_str(""), h.new_str("")));
809 with_host(|h| h.queue_io_callback(cb, vec![err, empty1, empty2]));
810 let null = with_host(|h| h.null());
811 let mut m = IndexMap::new();
812 m.insert("pid".into(), Value::Undef);
813 m.insert("exitCode".into(), null.clone());
814 m.insert("signalCode".into(), null.clone());
815 m.insert("killed".into(), Value::Bool(false));
816 m.insert("connected".into(), Value::Bool(false));
817 m.insert("stdout".into(), null.clone());
818 m.insert("stderr".into(), null);
819 return Ok(child_object(m));
820 }
821 Err(format!("Error: spawn {file} {e}"))
822 }
823 }
824}
825
826fn fork(args: &[Value]) -> Result<Value, String> {
837 let module = arg_str(args, 0);
838 let extra_args = arg_array(args, 1);
839 let exe = std::env::current_exe().map_err(|e| format!("Error: fork: {e}"))?;
840
841 let mut cmd = Command::new(exe);
842 cmd.arg(&module).args(&extra_args);
843 cmd.stdin(Stdio::inherit())
844 .stdout(Stdio::inherit())
845 .stderr(Stdio::inherit());
846 let child = cmd
847 .spawn()
848 .map_err(|e| format!("Error: fork {module} {e}"))?;
849 let pid = child.id();
850
851 let id = NEXT_CHILD_ID.fetch_add(1, Ordering::Relaxed);
852 let handle = Arc::new(Mutex::new(Some(child)));
853
854 let mut extra = IndexMap::new();
855 extra.insert("@@childid".into(), Value::Float(id as f64));
856 extra.insert("pid".into(), Value::Float(pid as f64));
857 extra.insert("connected".into(), Value::Bool(false));
858 extra.insert("killed".into(), Value::Bool(false));
859 extra.insert("exitCode".into(), with_host(|h| h.null()));
860 extra.insert("signalCode".into(), with_host(|h| h.null()));
861 let emitter = child_object(extra);
862 CHILDREN.with(|c| {
863 c.borrow_mut().insert(
864 id,
865 ChildRec {
866 emitter: emitter.clone(),
867 handle: handle.clone(),
868 },
869 );
870 });
871 with_host(|h| h.incr_handle());
872
873 let io_tx = with_host(|h| h.io_sender());
874 std::thread::spawn(move || wait_child(id, handle, io_tx));
875 Ok(emitter)
876}
877
878fn wait_child(id: u64, handle: Arc<Mutex<Option<Child>>>, io_tx: Sender<IoTask>) {
882 loop {
883 std::thread::sleep(std::time::Duration::from_millis(20));
884 let status = {
885 let mut g = match handle.lock() {
886 Ok(g) => g,
887 Err(_) => return,
888 };
889 match g.as_mut() {
890 Some(child) => match child.try_wait() {
891 Ok(Some(status)) => {
892 *g = None;
893 Some(status.code())
894 }
895 Ok(None) => None,
896 Err(_) => {
897 *g = None;
898 Some(None)
899 }
900 },
901 None => return,
903 }
904 };
905 if let Some(code) = status {
906 let _ = io_tx.send(Box::new(move || on_child_exit(id, code)));
907 return;
908 }
909 }
910}
911
912fn on_child_exit(id: u64, code: Option<i32>) -> Result<(), String> {
915 let emitter = CHILDREN.with(|c| c.borrow().get(&id).map(|r| r.emitter.clone()));
916 let Some(emitter) = emitter else {
917 return Ok(());
918 };
919 let (code_val, null1, null2) = with_host(|h| {
920 let cv = code
921 .map(|c| Value::Float(c as f64))
922 .unwrap_or_else(|| h.null());
923 (cv, h.null(), h.null())
924 });
925 set_prop(&emitter, "exitCode", code_val.clone());
926 set_prop(&emitter, "killed", Value::Bool(true));
927 let ev_exit = with_host(|h| h.new_str("exit"));
928 let ev_close = with_host(|h| h.new_str("close"));
929 super::events::instance_call(&emitter, "emit", vec![ev_exit, code_val.clone(), null1])?;
930 super::events::instance_call(&emitter, "emit", vec![ev_close, code_val, null2])?;
931 CHILDREN.with(|c| c.borrow_mut().remove(&id));
932 with_host(|h| h.decr_handle());
933 let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
934 Ok(())
935}
936
937fn set_prop(recv: &Value, key: &str, val: Value) {
938 with_host(|h| {
939 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
940 p.insert(key.to_string(), val);
941 }
942 });
943}
944
945pub fn instance_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
952 if super::events::METHODS.contains(&method) {
953 return super::events::instance_call(recv, method, args);
954 }
955 match method {
956 "kill" => Ok(Value::Bool(kill_child(recv))),
957 "send" => Ok(Value::Bool(false)),
959 "disconnect" => {
960 set_prop(recv, "connected", Value::Bool(false));
961 Ok(Value::Undef)
962 }
963 "ref" | "unref" => Ok(recv.clone()),
964 _ => Err(crate::host::type_error(&format!(
965 "child.{method} is not a function"
966 ))),
967 }
968}
969
970fn kill_child(recv: &Value) -> bool {
974 let id = with_host(|h| match h.get(recv) {
975 Some(JsObj::Object(p)) => p.get("@@childid").map(|v| h.to_number(v) as u64),
976 _ => None,
977 });
978 let Some(id) = id else { return false };
979 let handle = CHILDREN.with(|c| c.borrow().get(&id).map(|r| r.handle.clone()));
980 let Some(handle) = handle else { return false };
981 if let Ok(mut g) = handle.lock() {
982 if let Some(child) = g.as_mut() {
983 let _ = child.kill();
984 return true;
985 }
986 }
987 false
988}
989
990fn output_value(bytes: &[u8], encoding: Option<&str>) -> Value {
994 match encoding {
995 Some(enc) if !enc.eq_ignore_ascii_case("buffer") => {
996 with_host(|h| h.new_str(String::from_utf8_lossy(bytes).into_owned()))
997 }
998 _ => super::buffer::from_bytes(bytes),
999 }
1000}
1001
1002fn arg_array(args: &[Value], i: usize) -> Vec<String> {
1005 with_host(|h| match args.get(i).and_then(|v| h.get(v)) {
1006 Some(crate::host::JsObj::Array(items)) => items.iter().map(|v| h.str_of(v)).collect(),
1007 _ => Vec::new(),
1008 })
1009}
1010
1011fn opts_encoding(args: &[Value], i: usize) -> Option<String> {
1014 with_host(|h| match args.get(i).and_then(|v| h.get(v)) {
1015 Some(crate::host::JsObj::Object(p)) => p
1016 .get("encoding")
1017 .map(|v| h.str_of(v))
1018 .filter(|s| !s.is_empty() && s != "undefined" && s != "null"),
1019 _ => None,
1020 })
1021}