//! The `std/process.proc` effect for compiled programs (ADR 0004). //! //! Every actor receives a **root capability** for `proc`, a capability //! block like any handler's (ADR 0010). Its clauses are runtime closures, //! one per operation in `std/process.lse`'s declaration order, then the //! marker. So generated code performs `proc` operations exactly like other //! `fn` operations. Codegen checks the order against the declaration. //! //! Each clause consumes its arguments, as all closures do. It gives the //! actor a fresh reduction budget, because each operation is a scheduling //! point in the interpreter. If the operation stopped the running actor //! (killing itself, or a linked actor dying), the clause starts unwinding. //! //! Data built here follows the constructor order of `std/process.lse` and //! the prelude: //! - `None`, `Some(x)`; //! - `Subject(owner, tag)`, `Remote(owner, tag, wire)`; //! - `Normal`, `Killed`, `Crashed(m)`; //! - `Down(pid, reason)`, `ExitSignal(pid, reason)`: one shape //! ([`signal_value`]). //! //! The `process` run test checks the same constructor order for the //! interpreter. //! //! An operation on a remote pid (negative: `dist`) goes to the transport //! through `dist`'s hooks; on a local one, it costs one sign test. use std::sync::OnceLock; use crate::abi::{Block, Ctx, UNIT, Value, YIELD_KILL, YIELD_NONE, int, int_get, is_ptr}; use crate::heap::drop_value; use crate::int::saturating; use crate::otp::{Answer, Received, Tags, Timeout, Wait}; use crate::sched::{Actor, Exit, REDUCTIONS, Shared, Tie, exit_actor, park, this}; use crate::send::NotSendable; use crate::values::{tl_borrowed0, tl_borrowed1, tl_borrowed2}; /// The operations of `std/process.proc`, in declaration order. The list is /// shared with codegen, which refuses a `std/process` that differs. pub use louise_rt_prims::{PROC_OPS, RootCap}; /// A clause: `(ctx, this_, args...)`, `this_` being the clause itself. pub(crate) type Code = unsafe extern "C" fn(*mut Ctx, Value, Value, Value, Value, Value, Value) -> Value; /// The clause of each operation, in the order of [`PROC_OPS`], with the /// borrowed entry of its arity (ADR 0068; an operation with three or more /// arguments needs a `tl_borrowed3` — values.rs). const CLAUSES: [(Code, Code); PROC_OPS.len()] = [ (op_spawn, tl_borrowed1), (op_self, tl_borrowed0), (op_subject, tl_borrowed0), (op_send, tl_borrowed2), (op_receive, tl_borrowed2), (op_link, tl_borrowed1), (op_monitor, tl_borrowed1), (op_kill, tl_borrowed1), (op_trap_exits, tl_borrowed1), (op_exits, tl_borrowed0), (op_sleep, tl_borrowed1), (op_receive_any, tl_borrowed2), (op_spawn_link, tl_borrowed1), (op_spawn_monitor, tl_borrowed1), (op_stop, tl_borrowed1), (op_demonitor, tl_borrowed2), (op_unlink, tl_borrowed1), ]; /// A root capability of `kind` (`TL_ROOT_*`, owned), for a program /// compiled for `ops` operations of its effect. A mismatch means the /// program and the runtime come from different versions of std: stop /// before calling the wrong clauses. /// /// # Safety /// `ctx` must be the running actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_root_cap(_ctx: *mut Ctx, kind: i64, ops: i64) -> Value { let Some(kind) = u8::try_from(kind).ok().and_then(RootCap::from_u8) else { eprintln!( "louise: this program asks for root capability {kind}, which the runtime doesn't know: rebuild the runtime (cargo build -p louise_rt) with the same Louise version" ); std::process::abort(); }; if ops != kind.ops().len() as i64 { eprintln!( "louise: this program expects {ops} operations of a root effect ({}), but the runtime has {}: rebuild the runtime (cargo build -p louise_rt) with the same Louise version", kind.c_name(), kind.ops().len() ); std::process::abort(); } root_cap(kind) } /// A root capability of `kind` (owned): the immortal one of each kind /// (`clock.rs`, ADR 0036). pub(crate) fn root_cap(kind: RootCap) -> Value { match kind { RootCap::Proc => proc_cap(), RootCap::Clock => crate::clock::clock_cap(), RootCap::Random => crate::clock::random_cap(), } } /// The immortal root capability for `proc`. Its clauses capture nothing: /// each reads the running actor from its `ctx`. So, like `clock`'s, one /// block serves every actor, and an actor's start and exit allocate and /// free none of its 17 closures (ADR 0036, Revision 1). fn proc_cap() -> Value { static CAP: OnceLock = OnceLock::new(); *CAP.get_or_init(|| crate::clock::immortal_cap(&CLAUSES)) } // ---- data ------------------------------------------------------------------ /// A constructor of `tag` with `fields` (owned): a small int if nullary. /// Made outside any actor's context (`tl_alloc` does not read it). fn data(tag: u16, fields: &[Value]) -> Value { if fields.is_empty() { return int(i64::from(tag)); } crate::values::cell(std::ptr::null_mut(), tag, fields) } fn some(v: Value) -> Value { data(1, &[v]) } fn none() -> Value { int(0) } impl Answer for Value { fn received(message: Value, tag: Option) -> Value { match tag { Some(tag) => some(data(0, &[int(tag), message])), None => some(message), } } fn timed_out() -> Value { none() } fn unit() -> Value { UNIT } } fn subject(owner: i64, tag: i64) -> Value { data(0, &[int(owner), int(tag)]) } fn reason_value(r: &Exit) -> Value { match r { Exit::Normal => int(0), Exit::Killed => int(1), Exit::Shutdown => int(3), Exit::Crashed(m) => { // SAFETY: `m` is valid for its length. let s = unsafe { crate::values::tl_string_from(std::ptr::null_mut(), m.as_ptr().cast(), m.len()) }; data(2, &[s]) } } } /// `(owner, tag)` of a subject (borrowed): the first two fields of both /// constructors. /// /// # Safety /// `s` must be a live subject. pub(crate) unsafe fn subject_parts(s: Value) -> (i64, i64) { // SAFETY: caller guarantees a subject block. unsafe { let f = Block::fields_ptr(s as *mut Block); (int_get(*f), int_get(*f.add(1))) } } /// The `wire` of a `Remote` subject (borrowed), or `None` for a local one. /// /// # Safety /// `s` must be a live subject. pub(crate) unsafe fn subject_wire(s: Value) -> Option { // SAFETY: caller guarantees a subject block; `Remote` has 3 fields. unsafe { let b = s as *mut Block; ((*b).header.tag == 1).then(|| int_get(*Block::fields_ptr(b).add(2))) } } // ---- delivery ---------------------------------------------------------------- /// Prepare `v` (owned) for another actor ([`crate::send`]). If it cannot be /// sent, drop it and panic: `Err` holds what the operation returns. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn handover(ctx: *mut Ctx, v: Value) -> Result { // SAFETY: forwarded caller guarantee. unsafe { crate::send::transfer(ctx, v).map_err(|(NotSendable(reason), v)| { drop_value(ctx, v); crate::effects::tl_panic_str(ctx, reason.as_ptr()) }) } } /// Put `message` (owned) in `owner`'s inbox under `tag`, waking `owner` /// if it waits for a message. Returns it if `owner` is gone. fn deliver(sched: &Shared, owner: i64, tag: i64, message: Value) -> Option { sched.deliver(owner, tag, message) } /// Deliver a message the runtime made (outside any actor's context): if /// the receiver is gone meanwhile, free it here. pub(crate) fn deliver_made(sched: &Shared, owner: i64, tag: i64, message: Value) { if let Some(undelivered) = deliver(sched, owner, tag, message) { // SAFETY: the message was made here and never delivered. unsafe { crate::heap::drop_detached(undelivered) }; } } /// `Down(pid, reason)`, or `ExitSignal(pid, reason)`: both are /// constructor 0 with these fields. Made outside any actor's context. pub(crate) fn signal_value(pid: i64, reason: &Exit) -> Value { data(0, &[int(pid), reason_value(reason)]) } pub(crate) fn deliver_down(sched: &Shared, watcher: i64, tag: i64, pid: i64, reason: &Exit) { if !sched.exists(watcher) { return; } deliver_made(sched, watcher, tag, signal_value(pid, reason)); } pub(crate) fn deliver_exit_signal(sched: &Shared, to: i64, pid: i64, reason: &Exit) { let Some(tag) = exits_tag(sched, to) else { return; }; deliver_made(sched, to, tag, signal_value(pid, reason)); } /// The tag of `pid`'s exit signals (made on first use), if it is alive. fn exits_tag(sched: &Shared, pid: i64) -> Option { sched.with_alive(pid, |a| { *a.ties().exits_tag.get_or_insert_with(|| sched.tag()) }) } // ---- clauses ------------------------------------------------------------------- /// Common end of every clause: a fresh budget; unwind if the operation /// stopped the running actor. /// /// # Safety /// `ctx` must be the running actor's context. unsafe fn done(ctx: *mut Ctx, result: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { (*ctx).reductions = REDUCTIONS; let (a, _) = this(ctx); if a.kill_requested() && (*ctx).yielding == YIELD_NONE { (*ctx).yielding = YIELD_KILL; drop_value(ctx, result); return UNIT; } result } } unsafe extern "C" fn op_spawn( ctx: *mut Ctx, this_: Value, body: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: called as a closure by generated code on the running actor. unsafe { drop_value(ctx, this_); let body = match handover(ctx, body) { Ok(body) => body, Err(panicked) => return panicked, }; let (pid, _) = crate::sched::spawn_program(ctx, body, Tie::None); done(ctx, int(pid)) } } unsafe extern "C" fn op_spawn_link( ctx: *mut Ctx, this_: Value, body: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let body = match handover(ctx, body) { Ok(body) => body, Err(panicked) => return panicked, }; let (pid, _) = crate::sched::spawn_program(ctx, body, Tie::Link); done(ctx, int(pid)) } } unsafe extern "C" fn op_spawn_monitor( ctx: *mut Ctx, this_: Value, body: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let body = match handover(ctx, body) { Ok(body) => body, Err(panicked) => return panicked, }; let (pid, tag) = crate::sched::spawn_program(ctx, body, Tie::Monitor); let (me, _) = this(ctx); let down = subject(me.pid, tag.expect("monitored")); done(ctx, data(0, &[int(pid), down])) } } unsafe extern "C" fn op_self( ctx: *mut Ctx, this_: Value, _: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, _) = this(ctx); done(ctx, int(a.pid)) } } unsafe extern "C" fn op_subject( ctx: *mut Ctx, this_: Value, _: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let tag = sched.tag(); done(ctx, subject(a.pid, tag)) } } unsafe extern "C" fn op_send( ctx: *mut Ctx, this_: Value, to: Value, message: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above; `to` is a subject. unsafe { drop_value(ctx, this_); let (_, sched) = this(ctx); let (owner, tag) = subject_parts(to); if crate::dist::is_remote(owner) { return send_remote(ctx, to, owner, tag, message); } drop_value(ctx, to); let message = match handover(ctx, message) { Ok(message) => message, Err(panicked) => return panicked, }; if let Some(undelivered) = deliver(sched, owner, tag, message) { drop_value(ctx, undelivered); } done(ctx, UNIT) } } /// `send` to a subject on another node: the transport encodes `message` /// (borrowed) for `to`'s message type, parking the actor while the peer's /// queue is full (`dist::send_parking`). Out of line: local sends never /// carry it. /// /// # Safety /// As `op_send`'s; `to` and `message` are owned. #[cold] #[inline(never)] unsafe fn send_remote(ctx: *mut Ctx, to: Value, owner: i64, tag: i64, message: Value) -> Value { // SAFETY: forwarded caller guarantee. unsafe { // A `Remote` subject always (`dist`); a `Subject` with a remote // owner has no message type to encode with, and the message is lost. let sent = match subject_wire(to) { Some(wire) => crate::dist::send(ctx, owner, tag, wire, message), None => Ok(()), }; drop_value(ctx, to); drop_value(ctx, message); match sent { Ok(()) => done(ctx, UNIT), // A message the program cannot send: as the send walk's // backstop, a panic in the sender. Err(why) => crate::effects::tl_panic_str(ctx, why.as_ptr()), } } } unsafe extern "C" fn op_receive( ctx: *mut Ctx, this_: Value, from: Value, timeout: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above; `from` is a subject. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let (owner, tag) = subject_parts(from); drop_value(ctx, from); // A `Remote` subject's owner is never local (`dist`). if owner != a.pid { return crate::effects::tl_panic_str( ctx, c"receive on a subject owned by another actor".as_ptr(), ); } match take_or_wait(sched, a, Tags::One(tag), false, saturating(timeout)) { Some(answer) => done(ctx, answer), None => { let answer = wait_for_message(ctx); done(ctx, answer) } } } } /// `receive_any(tags, timeout)`: the oldest message on any of the tags, as /// `(tag, message)` (the subjects' owners are checked by /// `std/process.select`). unsafe extern "C" fn op_receive_any( ctx: *mut Ctx, this_: Value, tags: Value, timeout: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above; `tags` is a `List`. unsafe { drop_value(ctx, this_); let mut wanted = Vec::new(); let mut cell = tags; while is_ptr(cell) { let f = Block::fields_ptr(cell as *mut Block); wanted.push(int_get(*f)); cell = *f.add(1); } drop_value(ctx, tags); let (a, sched) = this(ctx); match take_or_wait(sched, a, Tags::Many(wanted), true, saturating(timeout)) { Some(answer) => done(ctx, answer), None => { let answer = wait_for_message(ctx); done(ctx, answer) } } } } /// Under one lock: take the oldest message of `me` on one of `tags`, or /// answer `None` if `timeout` is 0, or else set `me` waiting for them /// (then the caller parks). `any`: the answer carries the tag. fn take_or_wait(sched: &Shared, me: &Actor, tags: Tags, any: bool, timeout: i64) -> Option { let timeout = match timeout { 0 => Timeout::Zero, t if t > 0 => Timeout::At(sched.clock().saturating_add(t as u64)), _ => Timeout::Never, }; match me.with_proc(|p| p.receive(me.inbox(), tags, any, timeout)) { Received::Now(answer) => Some(answer), Received::Parked(generation) => { if let Timeout::At(d) = timeout { sched.add_timer(d, me.pid, generation); } None } } } /// Park until the receive [`take_or_wait`] started ends: what it returns, /// or unit while unwinding (the actor exited). A message on a tag it does /// not wait for wakes it too; it then waits again. /// /// # Safety /// `ctx` must be the running actor's context, waiting in a receive. unsafe fn wait_for_message(ctx: *mut Ctx) -> Value { // SAFETY: forwarded caller guarantee. unsafe { loop { crate::sched::suspend_waiting(ctx); let (a, _) = this(ctx); if (*ctx).yielding != YIELD_NONE { // A message may have been handed over before the exit. let handed = a.with_proc(|p| p.take_wake()); drop_value(ctx, handed); return UNIT; } if let Some(answer) = a.with_proc(|p| p.receive_woken(a.inbox())) { return answer; } } } } /// `coerce` (std/process): the value as another type. Only /// `std/process.select` uses it, on a message whose type its subject /// guarantees. /// /// # Safety /// `v` must be live. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_coerce(_ctx: *mut Ctx, v: Value) -> Value { // SAFETY: caller guarantees a live value (borrowed; the result is a // new reference). unsafe { crate::heap::dup_value(v) } } unsafe extern "C" fn op_link( ctx: *mut Ctx, this_: Value, pid: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let other = int_get(pid); if crate::dist::is_remote(other) { crate::dist::link(sched, a, other); } else if other != a.pid { link_local(sched, a, other); } done(ctx, UNIT) } } /// The running actor `me` links the local `other`: its own half, then /// `other`'s, each under its actor's lock. An exit counts only through a /// half its receiver still has (`propagate_exit`), so `other`'s half is /// made only: /// - while `other` is alive: else there is no link, as with a dead pid, /// and `me`'s half goes again; /// - while `me` has not exited, which `other`'s lock decides: `me`'s exit /// sets its kill flag under its own lock, then signals `other` under /// `other`'s. With the flag not set, that signal comes after and finds /// the half; with it set, it may have come already, and the half would /// link `other` to an actor that is gone. fn link_local(sched: &Shared, me: &Actor, other: i64) { if !me.with_proc(|p| p.link(other)) { // Exited (killed while running): no link is due. return; } let made = sched.with_alive(other, |o| !me.kill_requested() && o.link(me.pid)); if made.is_none() { me.with_proc(|p| p.unlink(other)); } } unsafe extern "C" fn op_monitor( ctx: *mut Ctx, this_: Value, pid: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let (me, watched) = (a.pid, int_get(pid)); let tag = sched.tag(); let watching = if crate::dist::is_remote(watched) { crate::dist::monitor(sched, a, watched, tag) } else { sched .with_alive(watched, |w| w.ties().monitors.push((me, tag))) .is_some() }; if !watching { // Like Erlang's `noproc`: the actor is already gone. deliver_down(sched, me, tag, watched, &Exit::Crashed("noproc".into())); } done(ctx, subject(me, tag)) } } /// `demonitor(pid, down)`: from now on, no `Down` of the monitor of `pid` /// that `down` came from is delivered; one already delivered stays /// (`std/process.demonitor_flush` drops it). Anything else (another pid, /// a subject of no monitor) is ignored. `down` must be the caller's. unsafe extern "C" fn op_demonitor( ctx: *mut Ctx, this_: Value, pid: Value, down: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above; `down` is a subject. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let (owner, tag) = subject_parts(down); drop_value(ctx, down); let (me, watched) = (a.pid, int_get(pid)); if owner != me { return crate::effects::tl_panic_str( ctx, c"demonitor on a subject owned by another actor".as_ptr(), ); } if crate::dist::is_remote(watched) { crate::dist::demonitor(a, watched, tag); } else { // Under the watched actor's lock, which its exit puts its local // watchers' `Down`s in their inboxes under (`exit_actor`): the // monitor is removed first, or its `Down` is delivered already. sched.with_alive(watched, |w| w.demonitor(me, tag)); } done(ctx, UNIT) } } /// `unlink(pid)`: from now on the link with `pid` has no effect on this /// actor, until a new `link`; an `ExitSignal` already in its mailbox /// stays. Its own half goes first, so an exit on its way finds none /// (`propagate_exit`); then `pid`'s, which `pid`'s node removes for a /// remote `pid` once the unlink reaches it (`dist`). No link, or a pid /// that is gone: nothing. unsafe extern "C" fn op_unlink( ctx: *mut Ctx, this_: Value, pid: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let (me, other) = (a.pid, int_get(pid)); if crate::dist::is_remote(other) { crate::dist::unlink(a, other); } else if other != me { a.with_proc(|p| p.unlink(other)); sched.with_alive(other, |o| o.unlink(me)); } done(ctx, UNIT) } } unsafe extern "C" fn op_kill( ctx: *mut Ctx, this_: Value, pid: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let target = int_get(pid); if crate::dist::is_remote(target) { crate::dist::signal(a.pid, target, crate::dist::Signal::Kill); } else { exit_actor(sched, target, Exit::Killed); } done(ctx, UNIT) } } /// `stop(pid)`: an actor that traps exits gets `ExitSignal(self, /// Shutdown)`, to clean up and return; any other stops with `Shutdown` /// (ADR 0060). Unknown or exited pids are ignored. unsafe extern "C" fn op_stop( ctx: *mut Ctx, this_: Value, pid: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let target = int_get(pid); if crate::dist::is_remote(target) { crate::dist::signal(a.pid, target, crate::dist::Signal::Stop); } else { stop(sched, a.pid, target); } done(ctx, UNIT) } } /// `from` asks the local `target` to stop (`op_stop`). pub(crate) fn stop(sched: &Shared, from: i64, target: i64) { match sched.with_alive(target, |p| p.ties().trap) { Some(true) => deliver_exit_signal(sched, target, from, &Exit::Shutdown), Some(false) => exit_actor(sched, target, Exit::Shutdown), None => {} } } unsafe extern "C" fn op_trap_exits( ctx: *mut Ctx, this_: Value, on: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, _) = this(ctx); a.with_proc(|p| p.ties().trap = !is_ptr(on) && int_get(on) == 1); done(ctx, UNIT) } } unsafe extern "C" fn op_exits( ctx: *mut Ctx, this_: Value, _: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let me = a.pid; let tag = a.with_proc(|p| *p.ties().exits_tag.get_or_insert_with(|| sched.tag())); done(ctx, subject(me, tag)) } } unsafe extern "C" fn op_sleep( ctx: *mut Ctx, this_: Value, ms: Value, _: Value, _: Value, _: Value, _: Value, ) -> Value { // SAFETY: as above. unsafe { drop_value(ctx, this_); let (a, sched) = this(ctx); let ms = saturating(ms); if ms <= 0 { // Go to the back of the run queue. crate::sched::tl_preempt(ctx); return done(ctx, UNIT); } let deadline = sched.clock().saturating_add(ms as u64); let generation = a.with_proc(|p| p.park_as(Wait::Sleep { deadline })); sched.add_timer(deadline, a.pid, generation); let answer = park(ctx); done(ctx, answer) } } /// `pid_eq` from `std/process`. #[unsafe(no_mangle)] pub extern "C" fn tl_pid_eq(_ctx: *mut Ctx, a: Value, b: Value) -> Value { int(i64::from(a == b)) }