//! Running a program for compiled programs (`std/command`, ADR 0085). //! //! The driver is `louise_rt_prims::command`, shared with the interpreter. //! Here the calling actor parks on the child's descriptors (its pipes, //! its pidfd and a timerfd for the next deadline), all registered with the //! scheduler's reactor under one token, as a socket is (`net.rs`): the //! scheduler thread is never blocked on the child. A kill wakes the actor, //! which unwinds; dropping the child then kills its process group and //! reaps it. //! //! Arguments come as plain values (texts, lists, `Bytes`, `Int`s) and the //! result as tuples of `Int`s and `Bytes`: `std/command` builds its own //! types from them, so nothing here depends on their layout. use std::os::fd::RawFd; use std::path::PathBuf; use std::time::Duration; use louise_rt_prims::command::{ Child, Collected, Dir, Failure, Interest, Outcome, Spec, Step, spawn, }; use mio::Token; use mio::unix::SourceFd; use crate::abi::{Ctx, UNIT, Value, int}; use crate::int::saturating; use crate::net::{io_events, wait_for}; use crate::prims::boolean; use crate::sched::this; use crate::values::{bytes_from, bytes_of, cell, list, list_items, string, text}; /// A running child and its registrations, undone when it is dropped /// (done, or its actor was killed). struct Running { ctx: *mut Ctx, child: Child, } impl Running { /// Register the child's descriptors under `token`, edge-triggered. fn register(&self, token: Token) -> std::io::Result<()> { // SAFETY: `ctx` is the running actor's context. let (_, sched) = unsafe { this(self.ctx) }; sched.with_registry(|registry| { self.child.fds().into_iter().try_for_each(|(fd, interest)| { let interest = match interest { Interest::Read => mio::Interest::READABLE, Interest::Write => mio::Interest::WRITABLE, }; registry.register(&mut SourceFd(&fd), token, interest) }) }) } } impl Drop for Running { fn drop(&mut self) { // SAFETY: `ctx` is the actor's context, alive while it unwinds. let (_, sched) = unsafe { this(self.ctx) }; let fds: Vec = self.child.fds().into_iter().map(|(fd, _)| fd).collect(); sched.with_registry(|registry| { for fd in &fds { // Closed descriptors left epoll by themselves. let _ = registry.deregister(&mut SourceFd(fd)); } }); } } /// `run_raw`: run a program to its end (see `std/command`). Returns /// `Ok((exit kind, exit value, stdout, stderr, stdout cut, stderr cut, /// files))`, each file `(kind, size, data)` in the order of `out_names`, /// or `Error((code, message))`. /// /// # Safety /// `ctx` must be the running actor's context; the other arguments live /// values of the types `std/command` declares. #[unsafe(no_mangle)] #[allow(clippy::too_many_arguments, reason = "one extern, all plain values")] pub unsafe extern "C" fn tl_command_run( ctx: *mut Ctx, program: Value, args: Value, env_names: Value, env_values: Value, dir_kind: Value, dir: Value, in_names: Value, in_data: Value, out_names: Value, max_file: Value, stdin: Value, max_stdout: Value, max_stderr: Value, timeout_ms: Value, grace_ms: Value, ) -> Value { // SAFETY: caller guarantees live values of the declared types. let spec = unsafe { let texts = |l: Value| { list_items(l) .map(|v| text(v).to_owned()) .collect::>() }; let count = |v: Value| usize::try_from(saturating(v)).unwrap_or(0); let ms = |v: Value| Duration::from_millis(u64::try_from(saturating(v)).unwrap_or(0)); let dir = match saturating(dir_kind) { 0 => Dir::Inherit, 1 => Dir::In(PathBuf::from(text(dir))), _ => Dir::Scratch { inputs: texts(in_names) .into_iter() .zip(list_items(in_data).map(|v| bytes_of(v).to_vec())) .collect(), outputs: texts(out_names), max_file: count(max_file), }, }; Spec { program: text(program).to_owned(), args: texts(args), env: texts(env_names) .into_iter() .zip(texts(env_values)) .collect(), dir, stdin: bytes_of(stdin).to_vec(), max_stdout: count(max_stdout), max_stderr: count(max_stderr), timeout: ms(timeout_ms), grace: ms(grace_ms), } }; let running = match spawn(spec) { Ok(child) => Running { ctx, child }, Err(f) => return failure(ctx, &f), }; // SAFETY: `ctx` is the running actor's context. let token = unsafe { this(ctx).1.io_token() }; if let Err(e) = running.register(token) { return failure(ctx, &Failure::Failed(format!("reactor: {e}"))); } let mut running = running; loop { // SAFETY: `ctx` is the running actor's context. let seen = unsafe { io_events(ctx) }; if let Step::Done(outcome) = running.child.step() { drop(running); return finished(ctx, outcome); } // SAFETY: as above; a kill returns false, and dropping `running` // kills and reaps the child. if !unsafe { wait_for(ctx, token, seen) } { return UNIT; } } } fn finished(ctx: *mut Ctx, o: Outcome) -> Value { let files: Vec = o .files .iter() .map(|f| { let (size, data) = match f { Collected::Found(_, data) => (data.len() as i64, bytes_from(ctx, data)), Collected::TooLarge(_, size) => (*size as i64, bytes_from(ctx, &[])), Collected::Absent(_) => (0, bytes_from(ctx, &[])), }; cell(ctx, 0, &[int(f.kind()), int(size), data]) }) .collect(); let fields = [ int(o.exit.kind()), int(o.exit.value()), bytes_from(ctx, &o.stdout), bytes_from(ctx, &o.stderr), boolean(o.stdout_cut), boolean(o.stderr_cut), list(ctx, files.into_iter()), ]; let tuple = cell(ctx, 0, &fields); cell(ctx, 0, &[tuple]) } fn failure(ctx: *mut Ctx, f: &Failure) -> Value { let pair = cell(ctx, 0, &[int(f.code()), string(ctx, f.message())]); cell(ctx, 1, &[pair]) }