Skip to main content

nodejs/stdlib/
child_process.rs

1//! Node `child_process` module — real subprocess execution via
2//! `std::process::Command`.
3//!
4//! The synchronous entry points (`execSync`, `spawnSync`, `execFileSync`) are
5//! fully implemented: they spawn the child with piped stdio, wait for it, and
6//! return its captured output. `stdout`/`stderr` are returned as `Buffer`s by
7//! default (built through `buffer::from_bytes`, identical to the `fs` module's
8//! byte returns) or as strings when an `encoding` other than `"buffer"` is
9//! given in the options object.
10//!
11//! The asynchronous forms are backed synchronously here because node-js has no
12//! socket-driven child event loop:
13//!   * `exec(cmd, cb)` runs the command to completion, then delivers the result
14//!     through its callback `(error, stdout, stderr)` scheduled as a microtask
15//!     (`queue_micro`), matching Node's "callback fires after the current tick"
16//!     ordering. `stdout`/`stderr` are strings, as Node's `exec` default.
17//!   * `execFile(file, args, cb)` is `exec` without a shell — `file` is run
18//!     directly with the `args` array — and additionally returns a (non-live)
19//!     ChildProcess-shaped object carrying the collected result.
20//!   * `spawn(cmd, args)` runs the command to completion up front, then
21//!     delivers what happened on a later turn of the loop, as events on the
22//!     ChildProcess it returned: `'spawn'`, `'data'`/`'end'` on the
23//!     `child.stdout`/`child.stderr` streams (or the output written straight
24//!     through under `stdio: 'inherit'`), `'exit'`, `'close'`; a binary that
25//!     cannot start is an `'error'` event. LIMITATION: the child has finished
26//!     before `spawn` returns, so a long-running one blocks the caller and its
27//!     output arrives as one chunk per stream.
28//!
29//! `fork(modulePath)` is the exception: it spawns THIS `node` executable on
30//! `modulePath` as a genuinely live child and returns a live ChildProcess
31//! emitter that fires `exit`/`close` when the process terminates and supports
32//! `.kill()`. Its IPC channel (`.send()` / `process.on('message')`) is NOT
33//! implemented — see the `fork` fn doc for why.
34
35use 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
54/// Instance method names for the `ChildProcess` `@@native` tag, exposed to
55/// `stdlib::instance_has_method` (property reads that yield a bound method).
56pub 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
75// ── live ChildProcess registry (used by `fork`) ──────────────────────────────
76
77/// Process-global id source for live (`fork`ed) children.
78static NEXT_CHILD_ID: AtomicU64 = AtomicU64::new(1);
79
80/// Main-thread record for a live child: its emitter object and a shared handle
81/// the waiter thread polls (`try_wait`) and `kill` signals through.
82struct 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
92/// Build a `ChildProcess`-shaped emitter object (tagged `@@native = "ChildProcess"`)
93/// carrying the given extra properties, sharing the EventEmitter shape.
94fn child_object(extra: IndexMap<String, Value>) -> Value {
95    super::net::new_emitter_object("ChildProcess", extra)
96}
97
98/// Result of running a child to completion: exit code (`None` if terminated by a
99/// signal), captured stdout, captured stderr.
100#[derive(Clone)]
101struct Run {
102    status: Option<i32>,
103    /// The signal that terminated the child, when one did.
104    signal: Option<i32>,
105    stdout: Vec<u8>,
106    stderr: Vec<u8>,
107    pid: u32,
108}
109
110/// The options a *Sync call passes through to the child.
111#[derive(Default)]
112struct SpawnOpts {
113    input: Option<Vec<u8>>,
114    /// `env` REPLACES the environment rather than extending it, as in node.
115    env: Option<Vec<(String, String)>>,
116    cwd: Option<String>,
117}
118
119/// Read `input`, `env` and `cwd` out of the options argument.
120///
121/// `env` and `cwd` were being ignored entirely: the child inherited this
122/// process's environment and working directory, so `spawnSync(cmd, args,
123/// { cwd })` silently ran somewhere else and `{ env }` silently saw the wrong
124/// variables.
125fn 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
162/// Spawn `program` with `args`, capture both pipes, optionally feed `input` to
163/// stdin, and wait for exit.
164fn 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            // Drop stdin to send EOF so the child (e.g. `cat`/`wc`) can finish.
189        }
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
205/// `execSync`/`execFileSync` send the child's stderr on to the PARENT's stderr
206/// as well as capturing it — that is their documented DEFAULT stdio, and it is
207/// how a build script's diagnostics reach the terminal. `spawnSync` does not,
208/// and must not.
209///
210/// "Default" is the operative word: node echoes only when the caller left
211/// `stdio` unspecified. Echoing regardless meant a caller that had asked for
212/// the pipes explicitly still saw the child's stderr on its own.
213fn 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
228/// The error a failing `execSync` throws.
229///
230/// Node throws a real Error carrying `status`, `signal`, `pid`, `stdout` and
231/// `stderr`, and the standard shape of a caller is to read `e.status` or
232/// `e.stderr`. This used to throw a bare message string, so every one of those
233/// read back as undefined and the exit code was unrecoverable.
234fn 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    // Build the pipe values before the allocating `with_host` below; each takes
238    // its own borrow.
239    let stdout = output_value(&r.stdout, enc);
240    let stderr = output_value(&r.stderr, enc);
241    // Each of these takes its own host borrow, so none may be built inside
242    // another's `with_host` closure.
243    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
262/// The Error `exec`'s callback is handed for a non-zero exit: node's message is
263/// `Command failed: <cmd>\n<stderr>`, and the fields are `cmd`, `code` (the
264/// exit status), `killed` and `signal` — nothing else.
265fn 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
281/// The Error a failed SPAWN is reported with — node never throws here, it hands
282/// the error-first callback an `ENOENT` carrying `errno`, `syscall`, `path` and
283/// `spawnargs`, so `err.code === 'ENOENT'` distinguishes "no such binary" from
284/// "the binary ran and failed".
285fn 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
310/// `execSync(command[, options])` — run `sh -c <command>`, return stdout, and
311/// throw when the command exits non-zero (matching Node's `execSync`).
312fn 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
324/// `spawnSync(command, args[, options])` — return
325/// `{ status, signal, pid, stdout, stderr }` (never throws on non-zero exit).
326fn 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            // Build the stdout/stderr values FIRST (each allocates via its own
333            // `with_host`); inserting them inside the outer `with_host` below would
334            // re-enter the host borrow and panic.
335            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                // A signal name is not recovered here; report null (as when the
347                // child exited normally).
348                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        // Failure to launch (e.g. ENOENT): Node populates `error` and leaves
355        // status/stdout/stderr null.
356        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
369/// `execFileSync(file, args[, options])` — like `spawnSync` but returns stdout
370/// and throws on a non-zero exit.
371fn 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        // Same rich error `execSync` throws: a caller reads `e.status` and
380        // `e.stderr` here exactly as it does there, and this path was still
381        // handing back a bare message string.
382        return Err(command_failed(&file, &r, enc.as_deref()));
383    }
384    Ok(output_value(&r.stdout, enc.as_deref()))
385}
386
387/// `exec(command[, options], callback)` — run `sh -c <command>` synchronously,
388/// then fire `callback(error, stdout, stderr)` as a microtask. Node's `exec`
389/// defaults to string output, so stdout/stderr are passed as strings.
390fn exec(args: &[Value]) -> Result<Value, String> {
391    let cmd = arg_str(args, 0);
392    // Callback is the last function-shaped argument.
393    let cb = args
394        .last()
395        .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
396        .cloned();
397    // node's `exec` is `execFile('/bin/sh', ['-c', command])`: it RETURNS the
398    // ChildProcess (whose events fire), and the callback is that child's first
399    // `close` listener. It returned `undefined`, so `promisify(exec)(cmd).child`
400    // and `exec(cmd, cb).on('exit', …)` had no child to reach.
401    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            // An error-first callback receives an ERROR OBJECT carrying node's
417            // fields — `err.code` is the exit STATUS, and `cmd`, `killed` and
418            // `signal` ride along. This handed over a message string, so
419            // `err.code` was `undefined` and the exit status was unrecoverable;
420            // the message was this module's own wording too, where node appends
421            // the command's STDERR.
422            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
440/// A second copy of a run's outcome (the child's events and the callback each
441/// take one); an error keeps its kind and OS code.
442fn 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
452/// `spawn(command, args[, options])` — see the module doc comment: runs the
453/// child synchronously and returns a minimal, non-live ChildProcess-shaped
454/// object exposing the collected result. Event listeners do not fire.
455fn 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
463/// The ChildProcess for a child that has already run: `stdout`/`stderr`
464/// streams per `disp`, and its `spawn`/`data`/`exit`/`close` (or `error`)
465/// events queued for delivery. Shared by `spawn`, `exec` and `execFile`.
466fn 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        // A binary that cannot be started is an `'error'` EVENT, followed by
485        // `'close'` with code -2, not a throw: `spawn` is asynchronous in node.
486        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    // Not exited yet, as far as the caller can tell: `exitCode` is `null` until
498    // `'exit'` fires.
499    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
524/// Give `child` its first `close` listener: the exec-style callback, called
525/// as `cb(err, stdout, stderr)` — so it runs where node's does, after `exit`
526/// and ahead of any `close` listener the caller adds.
527fn 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/// Where a spawned child's stdout or stderr goes (`options.stdio`).
549#[derive(Clone, Copy, PartialEq)]
550enum Disposition {
551    /// A `child.stdout`/`child.stderr` stream carries it.
552    Pipe,
553    /// Straight to this process's own stream; the property is `null`.
554    Inherit,
555    Ignore,
556}
557
558/// Read `options.stdio`: one string for all three streams, or an array of
559/// per-stream entries, where a descriptor number or a stream object
560/// (`process.stdout`) means the parent's own.
561fn 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
597/// A finished child whose events have not been delivered yet.
598struct 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
612/// A `child.stdout`/`child.stderr` stream: an emitter with the readable
613/// surface programs use on it.
614fn child_pipe() -> Value {
615    super::net::new_emitter_object("ChildPipe", IndexMap::new())
616}
617
618/// The methods of a `ChildPipe`, besides the EventEmitter ones.
619pub 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
658/// Deliver a pipe's bytes: one `'data'` chunk (a Buffer, or a string after
659/// `setEncoding`), written on to a `pipe` destination too, then `'end'`.
660fn 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
679/// The events of a spawned child, delivered on a later turn of the loop as
680/// node delivers them: `'spawn'`, each pipe's output, `'exit'` (with
681/// `exitCode`/`signalCode` set), `'close'`, then the pipes' own `'close'`. A
682/// child that could not start emits `'error'` and `'close'` with code -2.
683fn 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
729/// The name of signal number `n` (`SIGTERM`), from the same table
730/// `process.kill` reads.
731fn 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
743/// `execFile(file[, args][, options][, callback])` — like `exec` but WITHOUT a
744/// shell: `file` is run directly with the `args` array. Runs to completion, fires
745/// `callback(error, stdout, stderr)` (strings) as a microtask, and returns a
746/// (non-live) ChildProcess-shaped object carrying the collected result.
747fn exec_file(args: &[Value]) -> Result<Value, String> {
748    let file = arg_str(args, 0);
749    let cmd_args = arg_array(args, 1);
750    // Callback is the last function-shaped argument, if any.
751    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                // As in `exec`, the callback takes an ERROR OBJECT. This built
771                // a STRING, so `err instanceof Error` was false and every field
772                // a caller reads — `code`, `cmd`, `killed`, `signal` — was
773                // `undefined`; the wording was this module's own too. Node's
774                // `cmd` here is the file and its arguments joined, since there
775                // is no shell command line to quote.
776                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        // A missing binary is reported THROUGH the callback — `execFile` is
803        // async, so it does not throw. Throwing here meant the caller's
804        // error-first handler never ran and the whole script died instead.
805        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
826/// `fork(modulePath[, args][, options])` — spawn THIS `node` executable on
827/// `modulePath` as a live child (inheriting stdio), returning a live
828/// ChildProcess emitter that fires `exit`/`close` when the child terminates.
829///
830/// LIMITATION: Node's `fork` also opens an IPC channel so parent and child can
831/// exchange messages via `child.send()` / `process.on('message')`. That requires
832/// the child `node` process to detect and bind an inherited IPC file descriptor,
833/// which this runtime does not implement — so `child.send()` is a no-op that
834/// returns `false`, `child.connected` is `false`, and no `'message'` event fires.
835/// The process itself is real and live (`exit`/`close`/`kill` all work).
836fn 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
878/// Background waiter for a `fork`ed child: polls `try_wait` (so `kill` can still
879/// acquire the shared handle between polls) and posts an `IoTask` emitting
880/// `exit`/`close` once the child terminates.
881fn 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                // Handle already taken (killed + reaped elsewhere): stop polling.
902                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
912/// Main-thread handler: emit `exit` then `close` on a terminated child, mark it,
913/// release its event-loop handle, and drop its registry record.
914fn 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
945// ── ChildProcess instance methods (tag `@@native = "ChildProcess"`) ──────────
946
947/// `stdlib::instance_call` entry for a `ChildProcess` receiver. EventEmitter
948/// methods delegate to `events`; process-control methods act on the live child
949/// (only `fork`ed children are live — a `spawn`/`execFile` result has already
950/// exited, so `kill` is a no-op there).
951pub 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        // IPC is not implemented (see `fork` doc): `send` cannot deliver a message.
958        "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
970/// Terminate a live (`fork`ed) child. The signal argument is accepted for API
971/// compatibility but ignored — `std::process::Child::kill` always sends `SIGKILL`.
972/// Returns `true` if a live child was signalled.
973fn 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
990/// Bytes → a `Buffer` value (default) or a decoded string when `encoding` is set
991/// to anything other than `"buffer"`. Buffers are built exactly like `fs`
992/// returns them, via `buffer::from_bytes`.
993fn 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
1002/// The array argument at `args[i]` as a list of stringified elements (empty when
1003/// the argument is absent or not an array).
1004fn 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
1011/// Read `.encoding` from the options object at `args[i]`, if present and a
1012/// non-empty string.
1013fn 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}