Skip to main content

leanfran_runtime/
process.rs

1//! Child processes (`IO.Process.spawn` and `IO.Process.Child`), with `fork` and `execvp` as in
2//! the C runtime: a command that cannot be executed is reported by the child on its standard
3//! error, and the child exits with 255.
4
5#[cfg(unix)]
6use crate::array::{lean_array_get_core, lean_array_size};
7#[cfg(not(unix))]
8use crate::io::io_result_unsupported;
9use crate::io::lean_io_result_mk_ok;
10#[cfg(unix)]
11use crate::io::{io_result_of_error, wrap_file};
12use crate::model::scalar_offset;
13use crate::object::*;
14#[cfg(unix)]
15use crate::string::lean_string_bytes;
16#[cfg(unix)]
17use std::ffi::CString;
18#[cfg(unix)]
19use std::io::Write;
20#[cfg(unix)]
21use std::os::fd::FromRawFd;
22
23/// `IO.Process.Stdio`: `piped`, `inherit`, `null`.
24#[cfg(unix)]
25const PIPED: u8 = 0;
26#[cfg(unix)]
27const NUL: u8 = 2;
28
29/// Offset of the pid in a `Child` (after its three handle fields), and of the `setsid` flag.
30const PID_OFFSET: u32 = scalar_offset(3, 0);
31const SETSID_OFFSET: u32 = scalar_offset(3, 4);
32
33#[cfg(unix)]
34unsafe fn c_string(s: Obj) -> CString {
35    let b = lean_string_bytes(s);
36    let end = b.iter().position(|&c| c == 0).unwrap_or(b.len());
37    CString::new(&b[..end]).unwrap()
38}
39
40/// A pipe whose ends are closed on `exec`: `(read, write)`.
41#[cfg(unix)]
42fn pipe() -> std::io::Result<(i32, i32)> {
43    let mut fds = [0i32; 2];
44    #[cfg(target_os = "linux")]
45    let r = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
46    #[cfg(not(target_os = "linux"))]
47    let r = unsafe {
48        let r = libc::pipe(fds.as_mut_ptr());
49        if r == 0 {
50            libc::fcntl(fds[0], libc::F_SETFD, libc::FD_CLOEXEC);
51            libc::fcntl(fds[1], libc::F_SETFD, libc::FD_CLOEXEC);
52        }
53        r
54    };
55    if r == -1 {
56        Err(std::io::Error::last_os_error())
57    } else {
58        Ok((fds[0], fds[1]))
59    }
60}
61
62/// Writes `msg` on the standard error of the child, without allocating or locking.
63#[cfg(unix)]
64unsafe fn child_message(msg: &[u8]) {
65    libc::write(2, msg.as_ptr() as *const libc::c_void, msg.len());
66}
67
68/// Connects the standard stream `target` of the child to its pipe end or `/dev/null`.
69#[cfg(unix)]
70unsafe fn child_stdio(mode: u8, pipe: Option<(i32, i32)>, target: i32, null: &CString) {
71    if let Some((r, w)) = pipe {
72        if target == 0 {
73            libc::dup2(r, 0);
74            libc::close(w);
75        } else {
76            libc::dup2(w, target);
77            libc::close(r);
78        }
79    } else if mode == NUL {
80        let flags = if target == 0 {
81            libc::O_RDONLY
82        } else {
83            libc::O_WRONLY
84        };
85        let fd = libc::open(null.as_ptr(), flags);
86        libc::dup2(fd, target);
87    }
88}
89
90/// `IO.Process.spawn : SpawnArgs → IO (Child args.toStdioConfig)` (consumes `args`).
91#[cfg(unix)]
92pub unsafe fn lean_io_process_spawn(args: Obj) -> Obj {
93    let r = spawn(args);
94    lean_dec(args);
95    r
96}
97
98#[cfg(not(unix))]
99pub unsafe fn lean_io_process_spawn(args: Obj) -> Obj {
100    lean_dec(args);
101    io_result_unsupported("spawning a process")
102}
103
104#[cfg(unix)]
105unsafe fn spawn(args: Obj) -> Obj {
106    let cfg = lean_ctor_get(args, 0);
107    let modes = [
108        lean_ctor_get_uint8(cfg, 0),
109        lean_ctor_get_uint8(cfg, 1),
110        lean_ctor_get_uint8(cfg, 2),
111    ];
112    let cmd = c_string(lean_ctor_get(args, 1));
113    let argv_arr = lean_ctor_get(args, 2);
114    let cwd = lean_ctor_get(args, 3);
115    let env = lean_ctor_get(args, 4);
116    let inherit_env = lean_ctor_get_uint8(args, scalar_offset(5, 0)) != 0;
117    let do_setsid = lean_ctor_get_uint8(args, scalar_offset(5, 1)) != 0;
118    if modes[0] == 1 {
119        let _ = std::io::stdout().flush();
120    }
121
122    let mut pipes = [None, None, None];
123    for i in 0..3 {
124        if modes[i] == PIPED {
125            match pipe() {
126                Ok(p) => pipes[i] = Some(p),
127                Err(e) => return io_result_of_error(&e),
128            }
129        }
130    }
131
132    let mut argv_c = vec![cmd.clone()];
133    for i in 0..lean_array_size(argv_arr) {
134        argv_c.push(c_string(lean_array_get_core(argv_arr, i)));
135    }
136    let mut argv: Vec<*const libc::c_char> = argv_c.iter().map(|s| s.as_ptr()).collect();
137    argv.push(core::ptr::null());
138    let env_c: Vec<(CString, Option<CString>)> = (0..lean_array_size(env))
139        .map(|i| {
140            let pair = lean_array_get_core(env, i);
141            let v = lean_ctor_get(pair, 1);
142            let v = (!lean_is_scalar(v)).then(|| c_string(lean_ctor_get(v, 0)));
143            (c_string(lean_ctor_get(pair, 0)), v)
144        })
145        .collect();
146    let cwd_c = (!lean_is_scalar(cwd)).then(|| c_string(lean_ctor_get(cwd, 0)));
147    let null = CString::new("/dev/null").unwrap();
148    let mut cwd_msg = b"could not change directory to ".to_vec();
149    if let Some(c) = &cwd_c {
150        cwd_msg.extend_from_slice(c.as_bytes());
151    }
152    cwd_msg.push(b'\n');
153    let mut exec_msg = b"could not execute external process '".to_vec();
154    exec_msg.extend_from_slice(cmd.as_bytes());
155    exec_msg.extend_from_slice(b"'\n");
156
157    let pid = libc::fork();
158    if pid == 0 {
159        if !inherit_env {
160            #[cfg(target_os = "linux")]
161            libc::clearenv();
162            #[cfg(not(target_os = "linux"))]
163            {
164                extern "C" {
165                    static mut environ: *const *const libc::c_char;
166                }
167                environ = core::ptr::null();
168            }
169        }
170        for (k, v) in &env_c {
171            match v {
172                Some(v) => libc::setenv(k.as_ptr(), v.as_ptr(), 1),
173                None => libc::unsetenv(k.as_ptr()),
174            };
175        }
176        for (i, target) in [0, 1, 2].into_iter().enumerate() {
177            child_stdio(modes[i], pipes[i], target, &null);
178        }
179        if let Some(c) = &cwd_c {
180            if libc::chdir(c.as_ptr()) < 0 {
181                child_message(&cwd_msg);
182                libc::_exit(255);
183            }
184        }
185        if do_setsid {
186            libc::setsid();
187        }
188        libc::execvp(argv[0], argv.as_ptr());
189        child_message(&exec_msg);
190        libc::_exit(255);
191    } else if pid == -1 {
192        let e = std::io::Error::last_os_error();
193        for (r, w) in pipes.into_iter().flatten() {
194            libc::close(r);
195            libc::close(w);
196        }
197        return io_result_of_error(&e);
198    }
199
200    let child = lean_alloc_ctor(0, 3, 5);
201    for (i, p) in pipes.into_iter().enumerate() {
202        let h = match p {
203            Some((r, w)) => {
204                let (ours, theirs) = if i == 0 { (w, r) } else { (r, w) };
205                libc::close(theirs);
206                wrap_file(std::fs::File::from_raw_fd(ours))
207            }
208            None => lean_box(0),
209        };
210        lean_ctor_set(child, i as u32, h);
211    }
212    lean_ctor_set_uint32(child, PID_OFFSET, pid as u32);
213    lean_ctor_set_uint8(child, SETSID_OFFSET, do_setsid as u8);
214    lean_io_result_mk_ok(child)
215}
216
217/// The exit code of a `waitpid` status: the signal number plus 128 for a signal (bash's
218/// convention).
219#[cfg(unix)]
220fn exit_code(status: i32) -> u32 {
221    if libc::WIFEXITED(status) {
222        libc::WEXITSTATUS(status) as u32
223    } else {
224        128 + libc::WTERMSIG(status) as u32
225    }
226}
227
228unsafe fn pid_of(child: Obj) -> i32 {
229    lean_ctor_get_uint32(child, PID_OFFSET) as i32
230}
231
232/// `Child.wait : (@& Child cfg) → IO UInt32`.
233#[cfg(unix)]
234pub unsafe fn lean_io_process_child_wait(_cfg: Obj, child: Obj) -> Obj {
235    let mut status = 0;
236    if libc::waitpid(pid_of(child), &mut status, 0) == -1 {
237        return io_result_of_error(&std::io::Error::last_os_error());
238    }
239    lean_io_result_mk_ok(lean_box_uint32(exit_code(status)))
240}
241
242/// `Child.tryWait : (@& Child cfg) → IO (Option UInt32)`.
243#[cfg(unix)]
244pub unsafe fn lean_io_process_child_try_wait(_cfg: Obj, child: Obj) -> Obj {
245    let mut status = 0;
246    match libc::waitpid(pid_of(child), &mut status, libc::WNOHANG) {
247        -1 => io_result_of_error(&std::io::Error::last_os_error()),
248        0 => lean_io_result_mk_ok(lean_box(0)),
249        _ => {
250            let s = lean_alloc_ctor(1, 1, 0);
251            lean_ctor_set(s, 0, lean_box_uint32(exit_code(status)));
252            lean_io_result_mk_ok(s)
253        }
254    }
255}
256
257/// `Child.kill : (@& Child cfg) → IO Unit`: `SIGKILL` to the process, or to its process group
258/// when it was spawned with `setsid`.
259#[cfg(unix)]
260pub unsafe fn lean_io_process_child_kill(_cfg: Obj, child: Obj) -> Obj {
261    let pid = pid_of(child);
262    let r = if lean_ctor_get_uint8(child, SETSID_OFFSET) != 0 {
263        libc::killpg(pid, libc::SIGKILL)
264    } else {
265        libc::kill(pid, libc::SIGKILL)
266    };
267    if r == -1 {
268        return io_result_of_error(&std::io::Error::last_os_error());
269    }
270    lean_io_result_mk_ok(lean_box(0))
271}
272
273#[cfg(not(unix))]
274pub unsafe fn lean_io_process_child_wait(_cfg: Obj, _child: Obj) -> Obj {
275    io_result_unsupported("waiting for a process")
276}
277
278#[cfg(not(unix))]
279pub unsafe fn lean_io_process_child_try_wait(_cfg: Obj, _child: Obj) -> Obj {
280    io_result_unsupported("waiting for a process")
281}
282
283#[cfg(not(unix))]
284pub unsafe fn lean_io_process_child_kill(_cfg: Obj, _child: Obj) -> Obj {
285    io_result_unsupported("killing a process")
286}
287
288/// `Child.pid : Child cfg → UInt32` (consumes `child`).
289pub unsafe fn lean_io_process_child_pid(_cfg: Obj, child: Obj) -> u32 {
290    let pid = pid_of(child) as u32;
291    lean_dec(child);
292    pid
293}
294
295/// `Child.takeStdin : Child cfg → IO (cfg.stdin.toHandleType × Child ..)` (consumes `child`):
296/// the stdin handle, and the child without it.
297pub unsafe fn lean_io_process_child_take_stdin(_cfg: Obj, child: Obj) -> Obj {
298    let rest = lean_alloc_ctor(0, 3, 5);
299    lean_ctor_set(rest, 0, lean_box(0));
300    for i in 1..3 {
301        let h = lean_ctor_get(child, i);
302        lean_inc(h);
303        lean_ctor_set(rest, i, h);
304    }
305    lean_ctor_set_uint32(rest, PID_OFFSET, pid_of(child) as u32);
306    lean_ctor_set_uint8(
307        rest,
308        SETSID_OFFSET,
309        lean_ctor_get_uint8(child, SETSID_OFFSET),
310    );
311    let stdin = lean_ctor_get(child, 0);
312    lean_inc(stdin);
313    lean_dec(child);
314    let pair = lean_alloc_ctor(0, 2, 0);
315    lean_ctor_set(pair, 0, stdin);
316    lean_ctor_set(pair, 1, rest);
317    lean_io_result_mk_ok(pair)
318}