diff --git a/ci/check-deps.sh b/ci/check-deps.sh index 8e448ca617..7eab075634 100755 --- a/ci/check-deps.sh +++ b/ci/check-deps.sh @@ -1158,7 +1158,7 @@ fi fi # route # fnlen: app/run.rs::run <= 200 lines, run_application (app/mod.rs, the D4 skeleton) <= 10 and -# plex_run (port.rs: install, then hand over) <= 10 — counted by brace +# plex_main (port.rs: install, hand over, end the process) <= 10 — counted by brace # depth from the `fn` line to its matching close, not by grep pattern. fn_body_lines() { # fn_body_lines — prints the line count of the first matching fn's body @@ -1178,9 +1178,15 @@ else fail "fnlen: app/run.rs::run is ${run_len:-unknown} lines, budget 200 — a runapp_len=$(fn_body_lines "$SRC/app/mod.rs" 'run_application') if [ -n "$runapp_len" ] && [ "$runapp_len" -le 10 ]; then ok "fnlen: run_application (app/mod.rs) ($runapp_len lines)" else fail "fnlen: run_application (app/mod.rs) is ${runapp_len:-unknown} lines, budget 10"; fi +plexmain_len=$(fn_body_lines "$SRC/port.rs" 'plex_main') +if [ -n "$plexmain_len" ] && [ "$plexmain_len" -le 10 ]; then ok "fnlen: plex_main (port.rs) ($plexmain_len lines)" +else fail "fnlen: plex_main (port.rs) is ${plexmain_len:-unknown} lines, budget 10"; fi +# plex_run is the one-line C wrapper over plex_main (the `-> !` entry the const beside it proves): its +# signature, the call and the closing brace. `app::exit`'s lifecycle_no_production_exit test holds the +# body to exactly that call. plexrun_len=$(fn_body_lines "$SRC/port.rs" 'plex_run') -if [ -n "$plexrun_len" ] && [ "$plexrun_len" -le 10 ]; then ok "fnlen: plex_run (port.rs) ($plexrun_len lines)" -else fail "fnlen: plex_run (port.rs) is ${plexrun_len:-unknown} lines, budget 10"; fi +if [ -n "$plexrun_len" ] && [ "$plexrun_len" -le 3 ]; then ok "fnlen: plex_run (port.rs) ($plexrun_len lines)" +else fail "fnlen: plex_run (port.rs) is ${plexrun_len:-unknown} lines, budget 3 — it only calls plex_main"; fi fi # fnlen # testmod: `#[cfg(test)] mod` count in app/mod.rs = 0 (D4/D8) — every test module named in D8's diff --git a/docs/module-layers.md b/docs/module-layers.md index 135fddf71f..1973c5a9c3 100644 --- a/docs/module-layers.md +++ b/docs/module-layers.md @@ -368,8 +368,9 @@ published values rather than hooks: the webOS code writes them into `tv::device` `tv` may name only `base`, `machine` and `os`. `port.rs` holds `plex_run` and the `PORT` table that points each hook at the `webos`, `keymanager` and `system` function behind it. The C shim and -the simulator both enter through `port::plex_run`; `app::run_application` is the two-line body it -hands over to. `lib.rs` declares the port but re-exports nothing from it, because a re-export would +the simulator both enter through `port::plex_run`: it calls `app::run_application`, which returns +how the session ended as an `Exit` (a status and whether the teardown released everything), and then +ends the process with that status. `lib.rs` declares the port but re-exports nothing from it, because a re-export would be a reference from the crate root into the port, which the gate refuses. The video sink landed as a verb-level cut. `tv::sink::VideoSink` has one method per verb of the diff --git a/rust-modules/base/src/task/watchdog.rs b/rust-modules/base/src/task/watchdog.rs index 7e8724871d..07d81b0c87 100644 --- a/rust-modules/base/src/task/watchdog.rs +++ b/rust-modules/base/src/task/watchdog.rs @@ -12,7 +12,7 @@ use std::{ cell::Cell, marker::PhantomData, rc::Rc, - sync::{atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU8, AtomicUsize, Ordering}, OnceLock}, + sync::{atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU8, AtomicUsize, Ordering}, Mutex, OnceLock, PoisonError}, time::{Duration, Instant}, }; @@ -186,6 +186,49 @@ struct Signals { foreground: AtomicBool, progress: AtomicUsize, label: AtomicPtr, + /// The thread a freeze probe (and the developer build's fatal abort) signals. + loop_thread: LoopThread, +} + +/// **The loop owner's thread id, and whether anything may signal it.** Captured on the loop thread +/// itself ([`LoopThread::arm`]) because it is the target of `pthread_kill`; cleared +/// ([`LoopThread::disarm`]) whenever that id must not be used: a hosted loop thread that has +/// returned leaves a dead id the system may hand to an unrelated thread, and a paused host has no +/// loop to probe. The id sits behind a lock held for the length of a send, so once `disarm` +/// returns no signal is in flight and none will start. +struct LoopThread(Mutex>); + +impl LoopThread { + const fn new() -> Self { + Self(Mutex::new(None)) + } + + fn slot(&self) -> std::sync::MutexGuard<'_, Option> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Capture the CALLING thread as the loop owner. Called on the loop thread, never on the + /// observer. A second call replaces the first: this is the re-capture. + fn arm(&self) { + // SAFETY: `pthread_self` takes no argument and cannot fail. libc supplies the native + // `pthread_t` ABI (pointer on Darwin, unsigned long on ARM Linux), widened to the word + // the slot stores. + *self.slot() = Some(unsafe { libc::pthread_self() } as usize); + } + + fn disarm(&self) { + *self.slot() = None; + } + + fn armed(&self) -> bool { + self.slot().is_some() + } + + /// Run `send` against the armed loop thread while the slot is held; `None` (and `send` never + /// runs) when disarmed. + fn with(&self, send: impl FnOnce(usize) -> R) -> Option { + self.slot().map(send) + } } impl Signals { @@ -196,6 +239,7 @@ impl Signals { foreground: AtomicBool::new(true), progress: AtomicUsize::new(0), label: AtomicPtr::new(&UNLABELED as *const BlockingLabel as *mut BlockingLabel), + loop_thread: LoopThread::new(), } } @@ -223,6 +267,24 @@ pub fn set_foreground(foreground: bool) { SIGNALS.foreground.store(foreground, Ordering::Release); } +/// Stop the observer signalling the loop thread, for good or until [`arm`]. Returns once no signal +/// is in flight. A hosted entry calls it before it reports its stop (the loop thread is about to +/// end, and its id with it) and while the host is paused; `LoopWatch::start` arms again. +pub fn disarm() { + SIGNALS.loop_thread.disarm(); +} + +/// Make the CALLING thread the one the observer signals: call it on the loop thread after a +/// [`disarm`]. [`LoopWatch::start`] does the same at every loop start. +pub fn arm() { + SIGNALS.loop_thread.arm(); +} + +/// Whether the observer may signal a loop thread right now. +pub fn is_armed() -> bool { + SIGNALS.loop_thread.armed() +} + thread_local! { /// Other workers may enter blocking scopes, but cannot publish the frame thread's label. static WATCHED: Cell> = const { Cell::new(None) }; @@ -494,24 +556,27 @@ impl LoopWatch { // task::spawn uses std::thread::Builder::spawn and logs EAGAIN as an error return. // Exactly one observer lives for this process; a failed start stays disabled. // - // The loop owner's thread is captured HERE, on the loop owner, never inside the - // observer: it is the target of the freeze probe (and of the developer build's fatal - // abort). libc supplies the native pthread_t ABI (pointer on Darwin, unsigned long on - // ARM Linux); fwcompat inventories export `pthread_self` and `pthread_kill` at - // GLIBC_2.4 across all releases: libpthread on older firmware, libc after the glibc - // pthread merge. - let main_thread = unsafe { libc::pthread_self() } as usize; + // The observer never captures the loop owner's thread: that id lives in + // `SIGNALS.loop_thread`, written on the loop owner below, because it is the target of + // the freeze probe (and of the developer build's fatal abort) and a hosted loop can + // end and start again on another thread. fwcompat inventories export `pthread_self` + // and `pthread_kill` at GLIBC_2.4 across all releases: libpthread on older firmware, + // libc after the glibc pthread merge. #[cfg(feature = "threadcheck")] let log_only = crate::devtrig::guard_log_only(); #[cfg(feature = "threadcheck")] - let started = super::spawn("main-thread watchdog", move || observe_loop(main_thread, log_only)).is_some(); + let started = super::spawn("main-thread watchdog", move || observe_loop(log_only)).is_some(); #[cfg(not(feature = "threadcheck"))] - let started = super::spawn("main-thread watchdog", move || observe_loop(main_thread)).is_some(); + let started = super::spawn("main-thread watchdog", observe_loop).is_some(); if !started { crate::eventlog::log("main-thread watchdog: unavailable; hang detection disabled"); } started }); if !started { return Self::disabled(); } - Self::attach(&SIGNALS) + let watch = Self::attach(&SIGNALS); + // Only the loop that attached becomes the signal target: a refused second loop must not + // retarget the first. + if watch.signals.is_some() { arm(); } + watch } fn attach(signals: &'static Signals) -> Self { @@ -685,8 +750,9 @@ pub fn set_crash_phase(phase: CrashPhase) { /// at playback) is never signalled. Returns whether the signal was sent. fn probe_main_thread(main_thread: usize, seq: u32) -> bool { // SAFETY: `sigaction` with a null new action only reads the current disposition into `old`, - // a zeroed plain-data struct; `pthread_kill` on a thread id captured from the loop owner, - // which lives for the whole process, is the call the developer build's abort already makes. + // a zeroed plain-data struct; `pthread_kill` on a thread id captured from the loop owner + // ([`LoopThread`]; its caller holds the slot, so the id is the live loop's or this is not + // reached) is the call the developer build's abort already makes. unsafe { let mut old: libc::sigaction = std::mem::zeroed(); if libc::sigaction(libc::SIGUSR2, std::ptr::null(), &mut old) != 0 { @@ -707,6 +773,12 @@ fn probe_main_thread(main_thread: usize, seq: u32) -> bool { } } +/// [`probe_main_thread`] against the loop thread, if one is armed. The slot stays held for the send, +/// so a [`disarm`] that returns has no probe still on its way to a thread that is gone. +fn probe_loop(loop_thread: &LoopThread, seq: u32) -> bool { + loop_thread.with(|thread| probe_main_thread(thread, seq)).unwrap_or(false) +} + /// Whether `handler` lives in the same loaded object as this code, i.e. is the crash tracer's own /// `freeze_handler` and not a library's that took `SIGUSR2` after the tracer was installed /// (ACB is `dlopen`ed at playback). A stranger's handler fired at a random moment is not a probe. @@ -750,7 +822,7 @@ fn answer_probe( (sent, format!("main-thread freeze: {ms}ms without loop progress{at} (probe {seq}, recorded={sent})")) } -fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bool) { +fn observe_loop(#[cfg(feature = "threadcheck")] log_only: bool) { let origin = Instant::now(); let mut freezes = Freezes::default(); // The probe whose recovery this thread must write down: set only when the probe was really @@ -779,7 +851,7 @@ fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bo Some(FreezeEvent::Probe { seq, ms }) => { let crash_log = crate::paths::in_runtime_dir(crate::paths::runtime_file::CRASH); let (sent, line) = - answer_probe(&crash_log, seq, ms, current_leg(), |seq| probe_main_thread(main_thread, seq)); + answer_probe(&crash_log, seq, ms, current_leg(), |seq| probe_loop(&SIGNALS.loop_thread, seq)); if !sent { freezes.unsent(); } @@ -816,8 +888,9 @@ fn observe_loop(main_thread: usize, #[cfg(feature = "threadcheck")] log_only: bo // stale sample; the next poll will rebase and discard its warning as well. let sample_age = origin.elapsed().as_millis().saturating_sub(now as u128); if sample_age <= MAX_POLL_GAP_MS as u128 && SIGNALS.progress() == progress { - let rc = unsafe { libc::pthread_kill(main_thread as libc::pthread_t, libc::SIGABRT) }; - if rc != 0 { crate::eventlog::log(&format!("main-thread hang: pthread_kill failed: {rc}")); } + // A disarmed loop has nobody to abort: `with` runs nothing. + let rc = SIGNALS.loop_thread.with(|thread| unsafe { libc::pthread_kill(thread as libc::pthread_t, libc::SIGABRT) }); + if let Some(rc) = rc.filter(|rc| *rc != 0) { crate::eventlog::log(&format!("main-thread hang: pthread_kill failed: {rc}")); } } } } @@ -1533,4 +1606,60 @@ mod tests { assert_eq!(plx_freeze_seq.load(Ordering::Acquire), 0, "an unsent probe arms nothing"); } + fn this_thread() -> usize { + unsafe { libc::pthread_self() as usize } + } + + #[test] + fn a_disarmed_loop_thread_is_never_signalled() { + let loop_thread = LoopThread::new(); + assert!(!loop_thread.armed()); + let mut sent = false; + assert_eq!(loop_thread.with(|_| sent = true), None); + assert!(!sent, "nothing runs against a loop that was never armed"); + assert!(!probe_loop(&loop_thread, 1), "and a probe is reported unsent"); + loop_thread.arm(); + assert!(loop_thread.armed()); + loop_thread.disarm(); + assert!(!loop_thread.armed()); + assert_eq!(loop_thread.with(|_| sent = true), None); + assert!(!sent, "a disarmed loop is not signalled either"); + } + + #[test] + fn arming_captures_the_calling_thread_and_a_second_arm_recaptures() { + let loop_thread = std::sync::Arc::new(LoopThread::new()); + loop_thread.arm(); + assert_eq!(loop_thread.with(|thread| thread), Some(this_thread())); + let later = std::sync::Arc::clone(&loop_thread); + let theirs = std::thread::Builder::new().spawn(move || { + later.arm(); + this_thread() + }).unwrap().join().unwrap(); + assert_ne!(theirs, this_thread(), "the two threads are two ids"); + assert_eq!(loop_thread.with(|thread| thread), Some(theirs), + "an arm from a new loop thread replaces the id of the one that ended"); + } + + #[test] + fn disarm_cannot_return_while_a_signal_is_in_flight() { + let loop_thread = LoopThread::new(); + loop_thread.arm(); + let held = loop_thread.with(|_| loop_thread.0.try_lock().is_err()); + assert_eq!(held, Some(true), + "the slot is held for the whole send, so `disarm` waits for it and none follows it"); + assert!(loop_thread.0.try_lock().is_ok(), "and is free again once the send ends"); + } + + #[test] + fn the_process_watchdog_arms_disarms_and_rearms() { + let _serial = crate::testlock::serial(); + disarm(); + assert!(!is_armed()); + arm(); + assert!(is_armed()); + assert_eq!(SIGNALS.loop_thread.with(|thread| thread), Some(this_thread())); + disarm(); + assert!(!is_armed(), "disarmed before a hosted stop is reported"); + } } diff --git a/rust-modules/gfx/src/gfx.rs b/rust-modules/gfx/src/gfx.rs index 2d69342b4b..27ec6d8cd6 100644 --- a/rust-modules/gfx/src/gfx.rs +++ b/rust-modules/gfx/src/gfx.rs @@ -1192,7 +1192,7 @@ fn gl_is_es() -> bool { // and therefore the safe default — a wrong guess there changes nothing. // `starts_with`, not a substring scan: the ES spec mandates this exact prefix, while a // desktop vendor string containing "ES" anywhere would otherwise skip the preamble and - // hard-exit at the first shader compile. + // fail the boot at the first shader compile. v.is_null() || CStr::from_ptr(v).to_bytes().starts_with(b"OpenGL ES") }) } @@ -1228,12 +1228,53 @@ unsafe fn supersample_aa(src: *const c_char) -> Option { std::ffi::CString::new(text.replace(EDGE, &format!("smoothstep(-{w:.6}, {w:.6}, d)"))).ok() } -pub fn gfx_compile(ty: c_uint, src: *const c_char) -> c_uint { - try_compile(ty, src).unwrap_or_else(|| plx_base::process::exit_now(1)) +/// A required shader program the driver refused: the typed form of the two `exit_now(1)` calls +/// this module made (a compile rejection inside `gfx_compile`, the base program's link failure in +/// `init_gl`). [`init_gl`], [`init_text`](crate::text::init_text) and [`init_image`] return it and +/// the application's entry turns it into its exit, so a process that hosts the app is told instead +/// of being killed under its host. What each refusal costs is unchanged: a compile rejection of +/// any program linked through [`link_program`] is a fault; a link failure is one only for the base +/// program, and the others degrade ([`degrade_on_link_failure`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GfxFault { + /// The driver rejected a shader's source (the compile log is already in the event log). + Compile, + /// The driver compiled both shaders and refused to link them. + Link, } -/// Optional programs may degrade on a driver's compile rejection; required shaders keep the -/// existing exit policy through `gfx_compile` above. +impl std::fmt::Display for GfxFault { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + GfxFault::Compile => f.write_str("a required shader failed to compile"), + GfxFault::Link => f.write_str("a required shader program failed to link"), + } + } +} + +/// The two driver steps a program's bring-up takes, so what a refusal costs is decided in +/// [`link_required`] and graded without a GL context (`fault_tests`). +trait ProgramDriver { + /// Compile one shader; `None` is the driver's rejection. + fn compile(&self, ty: c_uint, src: *const c_char) -> Option; + /// Link a program from two compiled shaders; `None` is the driver's refusal. + fn link(&self, vs: c_uint, fs: c_uint) -> Option; +} + +/// The GLES driver. +struct Gles; + +impl ProgramDriver for Gles { + fn compile(&self, ty: c_uint, src: *const c_char) -> Option { + try_compile(ty, src) + } + fn link(&self, vs: c_uint, fs: c_uint) -> Option { + link_shaders(vs, fs) + } +} + +/// Optional programs may degrade on a driver's compile rejection; required shaders report it as a +/// [`GfxFault`] through [`link_required`]. fn try_compile(ty: c_uint, src: *const c_char) -> Option { unsafe { let s = glCreateShader(ty); @@ -1276,10 +1317,33 @@ fn try_compile(ty: c_uint, src: *const c_char) -> Option { } /// Shared program bring-up for every shader pair: create → attach VS/FS → bind `a_pos` -/// (attrib 0, the shared unit quad) → link. `None` = link failure; each caller keeps its -/// own failure policy (hard-exit, degrade to 0, or early-return). -pub fn link_program(vs: *const c_char, fs: *const c_char) -> Option { - link_shaders(gfx_compile(GL_VERTEX_SHADER, vs), gfx_compile(GL_FRAGMENT_SHADER, fs)) +/// (attrib 0, the shared unit quad) → link. A compile rejection is `Err(GfxFault::Compile)` for +/// every caller; a link failure is `Err(GfxFault::Link)` and each caller keeps its own policy +/// (return the fault, degrade to 0 through [`degrade_on_link_failure`], or early-return). +/// +/// **Boot only.** The frame loop must not link a required program: it would have to end the loop +/// with a fault where boot returns one. The program a frame links on demand takes +/// [`link_optional_program`] (`blur_lazy_init`) and degrades on either refusal. +pub fn link_program(vs: *const c_char, fs: *const c_char) -> Result { + link_required(&Gles, vs, fs) +} + +fn link_required(driver: &dyn ProgramDriver, vs: *const c_char, fs: *const c_char) -> Result { + let vs = driver.compile(GL_VERTEX_SHADER, vs).ok_or(GfxFault::Compile)?; + let fs = driver.compile(GL_FRAGMENT_SHADER, fs).ok_or(GfxFault::Compile)?; + driver.link(vs, fs).ok_or(GfxFault::Link) +} + +/// The policy of a required program that the frame can do without: a link failure is logged with +/// `note` and answered `0` ("no program"), a compile rejection stays a fault. +pub(crate) fn degrade_on_link_failure(program: Result, note: &str) -> Result { + program.or_else(|fault| match fault { + GfxFault::Link => { + log(note); + Ok(0) + } + GfxFault::Compile => Err(fault), + }) } fn link_optional_program(vs: *const c_char, fs: *const c_char) -> Option { @@ -1433,7 +1497,7 @@ fn bind_core_profile_vao() { } } -pub fn init_gl() { +pub fn init_gl() -> Result<(), GfxFault> { unsafe { WARM_TARGET = None; // Before any buffer or attribute state is touched — in a core profile the calls below are @@ -1441,15 +1505,17 @@ pub fn init_gl() { #[cfg(feature = "hostsim")] bind_core_profile_vao(); - PROG = link_program(VS_SRC.as_ptr(), FS_SRC.as_ptr()).unwrap_or_else(|| { - // Logged for the same reason as the compile failure in `gfx_compile`: stderr is not the - // event log and a clean exit is not a crash, so this line is the only trace the death - // leaves. The base program is the one every draw needs, hence the exit where the - // ambient/shadow/image programs below merely degrade. - log("base prog link FAILED — exiting"); - eprintln!("link failed"); - plx_base::process::exit_now(1); - }); + PROG = link_program(VS_SRC.as_ptr(), FS_SRC.as_ptr()).map_err(|fault| { + // A compile rejection logged itself in `try_compile`. A link failure is logged here, + // for the same reason: stderr is not the event log and a clean exit is not a crash, so + // this line is the only trace the death leaves. The base program is the one every draw + // needs, hence the fault where the ambient/shadow/image programs below merely degrade. + if fault == GfxFault::Link { + log("base prog link FAILED — exiting"); + eprintln!("link failed"); + } + fault + })?; use_prog(PROG); RECT_UNIFORMS = RectUniforms::of(PROG); glUniform2f(RECT_UNIFORMS.screen, SCR_W, SCR_H); @@ -1488,10 +1554,11 @@ pub fn init_gl() { glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, std::ptr::null()); - APROG = link_program(VS_AMBIENT_DITHERED.as_ptr(), FS_AMBIENT.as_ptr()).unwrap_or_else(|| { - log("ambient prog link failed"); - 0 // draw_ambient then binds program 0 and draws nothing — the corner wash is a nicety - }); + APROG = degrade_on_link_failure( + link_program(VS_AMBIENT_DITHERED.as_ptr(), FS_AMBIENT.as_ptr()), + // draw_ambient then binds program 0 and draws nothing — the corner wash is a nicety + "ambient prog link failed", + )?; if APROG != 0 { AL_RECT = glGetUniformLocation(APROG, c"u_rect".as_ptr()); AL_SCREEN = glGetUniformLocation(APROG, c"u_screen".as_ptr()); @@ -1505,10 +1572,10 @@ pub fn init_gl() { AL_SCRIM = ScrimLoc::of(APROG); } SCRIM_SENT = [scrim::GroundShade::NONE; 3]; - SCRIM_PROG = link_program(VS_SCRIM_LAYER.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()).unwrap_or_else(|| { - log("scrim layer prog link failed — a layered hero draws no scrim over its art"); - 0 - }); + SCRIM_PROG = degrade_on_link_failure( + link_program(VS_SCRIM_LAYER.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()), + "scrim layer prog link failed — a layered hero draws no scrim over its art", + )?; if SCRIM_PROG != 0 { SCL_RECT = glGetUniformLocation(SCRIM_PROG, c"u_rect".as_ptr()); SCL_INK = glGetUniformLocation(SCRIM_PROG, c"u_ink".as_ptr()); @@ -1518,10 +1585,10 @@ pub fn init_gl() { } bind_dither_tile(); - APROG_PLAIN = link_program(VS_AMBIENT.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()).unwrap_or_else(|| { - log("ambient (plain) prog link failed — the dithered program serves every frame"); - 0 - }); + APROG_PLAIN = degrade_on_link_failure( + link_program(VS_AMBIENT.as_ptr(), FS_AMBIENT_PLAIN.as_ptr()), + "ambient (plain) prog link failed — the dithered program serves every frame", + )?; if APROG_PLAIN != 0 { PL_RECT = glGetUniformLocation(APROG_PLAIN, c"u_rect".as_ptr()); PL_TL = glGetUniformLocation(APROG_PLAIN, c"u_atl".as_ptr()); @@ -1533,10 +1600,11 @@ pub fn init_gl() { } // Soft-shadow program (own program so the hot FS_SRC pays nothing; mirrors init_image). - SPROG = link_program(VS_SRC.as_ptr(), FS_SHADOW.as_ptr()).unwrap_or_else(|| { - log("shadow prog link failed"); - 0 // draw_shadow no-ops → cards simply lose the drop-shadow, nothing else breaks - }); + SPROG = degrade_on_link_failure( + link_program(VS_SRC.as_ptr(), FS_SHADOW.as_ptr()), + // draw_shadow no-ops → cards simply lose the drop-shadow, nothing else breaks + "shadow prog link failed", + )?; if SPROG != 0 { SL_RECT = glGetUniformLocation(SPROG, c"u_rect".as_ptr()); SL_SCREEN = glGetUniformLocation(SPROG, c"u_screen".as_ptr()); @@ -1549,10 +1617,10 @@ pub fn init_gl() { SL_COL = glGetUniformLocation(SPROG, c"u_col".as_ptr()); } - FPROG = link_program(VS_SRC.as_ptr(), FS_FLAT.as_ptr()).unwrap_or_else(|| { - log("flat prog link failed — uniform rects take the fill program's flat path"); - 0 - }); + FPROG = degrade_on_link_failure( + link_program(VS_SRC.as_ptr(), FS_FLAT.as_ptr()), + "flat prog link failed — uniform rects take the fill program's flat path", + )?; if FPROG != 0 { FL_RECT = glGetUniformLocation(FPROG, c"u_rect".as_ptr()); FL_COL = glGetUniformLocation(FPROG, c"u_col".as_ptr()); @@ -1560,8 +1628,8 @@ pub fn init_gl() { glUniform2f(glGetUniformLocation(FPROG, c"u_screen".as_ptr()), SCR_W, SCR_H); } - // Optional on purpose: `link_program` exits the process on a compile rejection - // (`gfx_compile`), which would make `draw_ramp`'s fallback unreachable for the failure a + // Optional on purpose: `link_program` makes a compile rejection a fault boot returns + // (`link_required`), which would make `draw_ramp`'s fallback unreachable for the failure a // driver is likeliest to give a new program. `try_compile` logs the compile error itself. RPROG = link_optional_program(VS_SRC.as_ptr(), FS_RAMP.as_ptr()).unwrap_or_else(|| { log("ramp prog compile/link failed — square gradients take the fill program's flat path"); @@ -1579,10 +1647,10 @@ pub fn init_gl() { // unit quad IS the texture coordinate and there is nothing for a `u_uvrect` to express. // DITHERED: `fs_field.frag` is built with `glsl_dithered!`, so its paired vertex source // must be the `PLX_DITHER_NC` variant that supplies `v_dither_nc` (cost rule 4). - UPROG = link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD.as_ptr()).unwrap_or_else(|| { - log("field prog link failed — an underlay field draws nothing"); - 0 - }); + UPROG = degrade_on_link_failure( + link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD.as_ptr()), + "field prog link failed — an underlay field draws nothing", + )?; if UPROG != 0 { UL_RECT = glGetUniformLocation(UPROG, c"u_rect".as_ptr()); UL_TINT = glGetUniformLocation(UPROG, c"u_tint".as_ptr()); @@ -1595,10 +1663,10 @@ pub fn init_gl() { // The same field as a popover's material — `draw_field_panel`. DITHERED, same contract as // `UPROG` above: `fs_field_panel.frag` is built with `glsl_dithered!`, so it must link // against the `PLX_DITHER_NC` vertex variant. - PPROG = link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD_PANEL.as_ptr()).unwrap_or_else(|| { - log("field-panel prog link failed — popover panels fall back to the flat sheet"); - 0 - }); + PPROG = degrade_on_link_failure( + link_program(VS_SRC_DITHERED.as_ptr(), FS_FIELD_PANEL.as_ptr()), + "field-panel prog link failed — popover panels fall back to the flat sheet", + )?; if PPROG != 0 { FP_RECT = glGetUniformLocation(PPROG, c"u_rect".as_ptr()); FP_TINT = glGetUniformLocation(PPROG, c"u_tint".as_ptr()); @@ -1681,6 +1749,7 @@ pub fn init_gl() { // Last: it reads GL's extension string and links against the context just built. straighten::init(); } + Ok(()) } /// The CAPSULE OUTLINE's solved geometry as the shader takes it — `[R, f, r, big centre y, end @@ -2725,14 +2794,15 @@ pub fn draw_number(mut n: i32, right_x: f32, y: f32, s: f32, col: *const f32) { } // ---- image program: RGBA textures (posters/logos/backdrop) with rounded corners ---- -pub fn init_image() { +pub fn init_image() -> Result<(), GfxFault> { unsafe { IPROG = match link_program(VS_IMG.as_ptr(), FS_IMG.as_ptr()) { - Some(p) => p, - None => { + Ok(p) => p, + Err(GfxFault::Link) => { log("image prog link failed"); - return; + return Ok(()); } + Err(fault) => return Err(fault), }; IL_RECT = glGetUniformLocation(IPROG, c"u_trect".as_ptr()); IL_SCREEN = glGetUniformLocation(IPROG, c"u_tscreen".as_ptr()); @@ -2836,6 +2906,7 @@ pub fn init_image() { use_prog(PROG); } + Ok(()) } /// Can the wash carry its artwork in one pass? `false` means the caller draws [`draw_ambient`] and @@ -6222,7 +6293,10 @@ fn blur_lazy_init() -> bool { if (*std::ptr::addr_of!(BLURST)).is_some() { return true; } - BPROG = match link_program(VS_IMG.as_ptr(), FS_BLUR.as_ptr()) { + // OPTIONAL, both programs: this runs from the frame (`draw_blur_backdrop`) as well as from + // boot, and a frame has no way to return a fault, so a compile rejection degrades exactly + // as a link failure does (`link_program` is boot-only). + BPROG = match link_optional_program(VS_IMG.as_ptr(), FS_BLUR.as_ptr()) { Some(p) => p, None => { log("blur: prog link failed — backdrop blur off"); @@ -6243,7 +6317,7 @@ fn blur_lazy_init() -> bool { glUniform4f(BL_RECT, 0.0, 0.0, SCR_W, SCR_H); glUniform4f(BL_UVRECT, 0.0, 0.0, 1.0, 1.0); - GPROG = match link_program(VS_IMG_DITHERED.as_ptr(), FS_GLASS.as_ptr()) { + GPROG = match link_optional_program(VS_IMG_DITHERED.as_ptr(), FS_GLASS.as_ptr()) { Some(p) => p, None => { log("blur: glass prog link failed — backdrop blur off"); @@ -10035,8 +10109,8 @@ mod tests { /// overdraw ledger BEFORE choosing a program, and fall back to the fill program rather than /// draw nothing when the ramp program did not compile or link. Each arm of the routing must call /// ITS program (a swap would still contain both calls), and the ramp program must be built from - /// `VS_SRC` + `FS_RAMP` through `link_optional_program`: `link_program` exits the process on a - /// compile rejection, so the fallback above would never be reached for it. + /// `VS_SRC` + `FS_RAMP` through `link_optional_program`: `link_program` makes a compile rejection a + /// boot fault, so the fallback above would never be reached for it. #[test] fn the_ramp_program_is_the_fill_programs_flat_path_in_a_smaller_shader() { let ramp = shader_code(FS_RAMP); @@ -13142,3 +13216,92 @@ mod frost_tests { assert_eq!(FROST_TAPS.iter().map(|d| d * d + 0.25).sum::(), 9.0, "sigma 3 texels = 24 px at 1/8"); } } + +/// What a driver's refusal costs a required program, graded without a GL context: the decision is +/// [`link_required`] / [`degrade_on_link_failure`], which take the driver as a parameter. +#[cfg(test)] +mod fault_tests { + use super::*; + use std::cell::RefCell; + + /// A driver that rejects what it is told to and records the steps it was asked for. + struct Refusing { + reject_compile_of: Option, + refuse_link: bool, + steps: RefCell>, + } + + impl Refusing { + fn new(reject_compile_of: Option, refuse_link: bool) -> Self { + Self { reject_compile_of, refuse_link, steps: RefCell::new(Vec::new()) } + } + } + + impl ProgramDriver for Refusing { + fn compile(&self, ty: c_uint, _src: *const c_char) -> Option { + self.steps.borrow_mut().push(if ty == GL_VERTEX_SHADER { "compile vs" } else { "compile fs" }); + (self.reject_compile_of != Some(ty)).then_some(ty) + } + fn link(&self, _vs: c_uint, _fs: c_uint) -> Option { + self.steps.borrow_mut().push("link"); + (!self.refuse_link).then_some(7) + } + } + + #[test] + fn an_injected_compile_rejection_is_a_fault_for_either_shader() { + let vertex = Refusing::new(Some(GL_VERTEX_SHADER), false); + assert_eq!(link_required(&vertex, std::ptr::null(), std::ptr::null()), Err(GfxFault::Compile)); + assert_eq!(*vertex.steps.borrow(), ["compile vs"], "the first rejection ends it, as the exit did"); + let fragment = Refusing::new(Some(GL_FRAGMENT_SHADER), false); + assert_eq!(link_required(&fragment, std::ptr::null(), std::ptr::null()), Err(GfxFault::Compile)); + assert_eq!(*fragment.steps.borrow(), ["compile vs", "compile fs"], "and nothing is linked after it"); + } + + #[test] + fn an_injected_link_refusal_is_a_link_fault() { + let driver = Refusing::new(None, true); + assert_eq!(link_required(&driver, std::ptr::null(), std::ptr::null()), Err(GfxFault::Link)); + assert_eq!(*driver.steps.borrow(), ["compile vs", "compile fs", "link"]); + } + + #[test] + fn a_program_the_driver_accepts_comes_back() { + let driver = Refusing::new(None, false); + assert_eq!(link_required(&driver, std::ptr::null(), std::ptr::null()), Ok(7)); + } + + /// The split the exits had: a link failure costs the base program the boot and every other + /// required program only itself; a compile rejection costs the boot whichever program it was. + #[test] + fn a_link_fault_degrades_a_program_and_a_compile_fault_never_does() { + assert_eq!(degrade_on_link_failure(Ok(5), "kept"), Ok(5)); + assert_eq!(degrade_on_link_failure(Err(GfxFault::Link), "a fault test's degraded program"), Ok(0), + "no program: the draw that needs it does nothing or falls back"); + assert_eq!(degrade_on_link_failure(Err(GfxFault::Compile), "unused"), Err(GfxFault::Compile)); + } + + #[test] + fn a_fault_names_what_failed() { + assert_eq!(GfxFault::Compile.to_string(), "a required shader failed to compile"); + assert_eq!(GfxFault::Link.to_string(), "a required shader program failed to link"); + } + + /// `blur_lazy_init` runs from the frame, which cannot return a fault: it links only optional + /// programs, so a driver's rejection degrades it exactly as its link failure did. Reads the + /// source for the reason the neighbouring tests do (no host test has a GL context). + #[test] + fn the_frames_lazy_link_is_optional_so_the_loop_never_owes_a_fault() { + let source = include_str!("gfx.rs"); + let body = source + .split_once(concat!("\nfn blur_lazy_", "init() -> bool {")) + .expect("blur_lazy_init") + .1 + .split_once("\n}\n") + .expect("the end of blur_lazy_init") + .0; + assert!(!body.contains(concat!("link_", "program(")), "a required program linked from the frame"); + assert_eq!(body.matches(concat!("link_optional_", "program(")).count(), 3, + "the blur, the glass and the frost programs are all optional"); + } +} diff --git a/rust-modules/gfx/src/text.rs b/rust-modules/gfx/src/text.rs index 282b151703..269e8ec623 100644 --- a/rust-modules/gfx/src/text.rs +++ b/rust-modules/gfx/src/text.rs @@ -89,6 +89,7 @@ use std::ptr::{addr_of, addr_of_mut}; use std::rc::Rc; use plx_base::surface::{LOGICAL_H as SCR_H, LOGICAL_W as SCR_W}; +use crate::gfx::{degrade_on_link_failure, GfxFault}; use crate::overdraw::{gate, Class}; /// Last resort only. Reaching this is a DEFECT, not a graceful degradation — see `font_at`. @@ -1646,20 +1647,21 @@ unsafe fn publish_text_ok() -> bool { true } -pub fn init_text() { +pub fn init_text() -> Result<(), GfxFault> { FITTED_LINES.with(|cache| cache.borrow_mut().entries.clear()); MEASURED_BOUNDS.with(|cache| cache.borrow_mut().entries.clear()); unsafe { if !ttf_init() { log("TTF_Init failed"); - return; + return Ok(()); } TPROG = match crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT.as_ptr()) { - Some(p) => p, - None => { + Ok(p) => p, + Err(GfxFault::Link) => { log("text prog link failed"); - return; + return Ok(()); } + Err(fault) => return Err(fault), }; TL_RECT = glGetUniformLocation(TPROG, c"u_trect".as_ptr()); TL_SCREEN = glGetUniformLocation(TPROG, c"u_tscreen".as_ptr()); @@ -1667,12 +1669,10 @@ pub fn init_text() { TL_TEX = glGetUniformLocation(TPROG, c"u_tex".as_ptr()); // the fade program shares VS_TEXT; a link failure leaves TPROGF=0 and draw_text_fade // falls back to the plain path (the fade is a nicety, not load-bearing) - TPROGF = crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_FADE.as_ptr()).unwrap_or_else( - || { - log("text fade prog link failed"); - 0 - }, - ); + TPROGF = degrade_on_link_failure( + crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_FADE.as_ptr()), + "text fade prog link failed", + )?; if TPROGF != 0 { TLF_RECT = glGetUniformLocation(TPROGF, c"u_trect".as_ptr()); TLF_SCREEN = glGetUniformLocation(TPROGF, c"u_tscreen".as_ptr()); @@ -1685,12 +1685,10 @@ pub fn init_text() { } // the ink program shares VS_TEXT too; without it a label crossed by a capsule's rounded end // is painted plain (a nicety again: the stretches' ink is still chosen, only the edge is square) - TPROGI = crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_INK.as_ptr()).unwrap_or_else( - || { - log("text ink prog link failed"); - 0 - }, - ); + TPROGI = degrade_on_link_failure( + crate::gfx::link_program(VS_TEXT.as_ptr(), FS_TEXT_INK.as_ptr()), + "text ink prog link failed", + )?; if TPROGI != 0 { TLI_RECT = glGetUniformLocation(TPROGI, c"u_trect".as_ptr()); TLI_SCREEN = glGetUniformLocation(TPROGI, c"u_tscreen".as_ptr()); @@ -1723,6 +1721,7 @@ pub fn init_text() { // which is a shared reference to a `static mut` (`static_mut_refs`, a future hard error) log(&format!("init_text ok={}", *addr_of!(TEXT_OK))); } + Ok(()) } /// **The fonts without the renderer.** [`init_text`] opens the fonts AND links the text shaders, so it diff --git a/rust-modules/src/app/boot.rs b/rust-modules/src/app/boot.rs index b002896f88..3a2cbea1cd 100644 --- a/rust-modules/src/app/boot.rs +++ b/rust-modules/src/app/boot.rs @@ -531,73 +531,6 @@ mod seam_order_tests { ); } - /// **No exit of the app process returns into libc's `exit`.** `exit` runs libcrypto's - /// `OPENSSL_cleanup`, which frees and NULLs its global locks while the detached curl workers - /// still run (#1115). The run-and-shutdown sequence and the entry point are typed `-> !` (a - /// path that returns does not compile): these consts are the compile-time proof, and the - /// source scan below finds any other `exit` call, which would sidestep - /// `plx_base::process::exit_now`. - const _: unsafe fn(&mut super::super::App) -> ! = super::super::run_and_shutdown; - const _: fn(*const std::os::raw::c_char, std::os::raw::c_int) -> ! = - super::super::run_application; - - #[test] - fn no_production_code_calls_libc_exit_outside_the_shared_helper() { - // The app process links every crate under rust-modules except `storage` (the separate - // `plxstorage` helper binary, no OpenSSL workers) and the os layer's `storage_service/` (that - // helper's body). `base/src/process.rs` is the helper itself. - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); - let mut files = Vec::new(); - collect_rs(&root.join("src"), &mut files); - for entry in std::fs::read_dir(root).expect("rust-modules") { - let dir = entry.expect("entry").path(); - let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string(); - if matches!(name.as_str(), "storage" | "target" | "tests") - || name.starts_with("target-") - || !dir.join("src").is_dir() - { - continue; - } - collect_rs(&dir.join("src"), &mut files); - } - assert!(files.len() > 100, "the scan must see the whole tree"); - let (a, b) = (concat!("process::", "exit("), concat!("libc::", "exit(")); - let mut hits = Vec::new(); - for f in files { - let path = f.to_string_lossy().replace('\\', "/"); - if path.ends_with("base/src/process.rs") - || path.contains("/storage_service/") - || path.contains("/tests/") - || path.ends_with("_tests.rs") - { - continue; - } - let text = std::fs::read_to_string(&f).expect("read"); - let prod = text.split("#[cfg(test)]").next().unwrap_or(""); - for (n, line) in prod.lines().enumerate() { - let code = line.split("//").next().unwrap_or(""); - if code.contains(a) || code.contains(b) { - hits.push(format!("{path}:{}", n + 1)); - } - } - } - assert!( - hits.is_empty(), - "exit through plx_base::process::exit_now, never libc exit (#1115): {hits:?}" - ); - } - - fn collect_rs(dir: &std::path::Path, out: &mut Vec) { - for entry in std::fs::read_dir(dir).expect("read_dir").flatten() { - let p = entry.path(); - if p.is_dir() { - collect_rs(&p, out); - } else if p.extension().is_some_and(|e| e == "rs") { - out.push(p); - } - } - } - /// `enter_application` installs the player's error-trace eraser before telemetry first loads a /// decision (`pre_boot_diagnostics` -> `telemetry::boot`, which already erases through it) and /// before anything can play. It was installed by `player::report::requested`, which a @@ -1439,7 +1372,8 @@ pub(super) fn install_pms_owned( /// Everything before the loop: SDL and the window, GL, text, the poster workers, the boot gate /// (login / token / session / picker), every dev trigger read once, and the `App` literal — /// `plex_run`'s former body up to `while app.running`, moved verbatim in phase 1b-ii. An early -/// exit ends the process through `plx_base::process::exit_now` (the caller maps `Err(code)` to it). +/// refusal returns its `Exit` (the entry ends the process with its code, `port::plex_run`; a hosted +/// entry reports it and stays alive). /// /// `mt`, THE main-thread token, is minted once by `plex_run` itself (`plx_base::task::MainThread:: /// assume()` — that function IS the SDL main thread) and MOVES into `App.adapters.player` here, @@ -1451,7 +1385,7 @@ pub(crate) unsafe fn boot( pms_port: c_int, mt: plx_base::task::MainThread, preflight: super::bootstrap::Preflight, -) -> Result { +) -> Result { // The Up Next still prefetch `route::pump_play` asks for is `ui`'s, which `route` may not name, // so it is handed over here, before any playback can land. Replay boots take it too. plx_media::route::install_up_next_still_warm(super::playback::warm_up_next_still); @@ -1466,7 +1400,7 @@ pub(crate) unsafe fn boot( let host = std::ffi::CStr::from_ptr(pms_host).to_string_lossy(); match super::bootstrap::Initial::capture_home(&host, pms_port) { Ok(initial) => Some(initial), - Err(reason) => { log(&format!("rec: REFUSED — {reason}")); return Err(1); } + Err(reason) => { log(&format!("rec: REFUSED — {reason}")); return Err(Exit::refused(1)); } } } super::bootstrap::Preflight::Replay { initial, .. } => Some((initial.clone(), None)), @@ -1522,12 +1456,12 @@ pub(crate) unsafe fn construct( pms_host: *const c_char, pms_port: c_int, mt: plx_base::task::MainThread, preflight: super::bootstrap::Preflight, initial: Option, deferred: Option, -) -> Result { +) -> Result { let controlled = preflight.controlled(); if let Some(initial) = &initial { plx_data::stores::tape::init(initial.person_credits(), preflight.replay()); - initial.home.restore(&mt).map_err(|_| 1)?; - plx_plex::plex::Client::restore_generation_seed(initial.primary_client).map_err(|_| 1)?; + initial.home.restore(&mt).map_err(|_| Exit::refused(1))?; + plx_plex::plex::Client::restore_generation_seed(initial.primary_client).map_err(|_| Exit::refused(1))?; } SDL_SetMainReady(); // DEAD END, measured 2026-07-31 — do not re-try this. The obvious answer to "a parked TV @@ -1546,7 +1480,7 @@ pub(crate) unsafe fn construct( webos3_cursor_sleep_hint(); if SDL_Init(SDL_INIT_VIDEO) != 0 { log("SDL_Init failed"); - return Err(1); + return Err(Exit::refused(1)); } tap_relaunch_payloads(); { @@ -1656,7 +1590,7 @@ pub(crate) unsafe fn construct( log(&format!("GL ctx failed at {ww_try}x{wh_try}")); SDL_DestroyWindow(win); } - let Some((w, h)) = fallback.take() else { return Err(1); }; + let Some((w, h)) = fallback.take() else { return Err(Exit::refused(1)); }; log(&format!("surface: retrying the window at the native {w}x{h}")); (ww_try, wh_try) = (w, h); }; @@ -1727,9 +1661,11 @@ pub(crate) unsafe fn construct( // wl_region once, so `opaque_route` below can declare the UI plane opaque on every screen // that has nothing behind it. See `system.rs`'s section on it. plx_os::tv::window::arm_opaque_region(); - plx_gfx::gfx::init_gl(); - plx_gfx::text::init_text(); - plx_gfx::gfx::init_image(); + // A required shader the driver refuses is a refusal like any other (`Exit::from(GfxFault)`): + // the same status the process always ended with, returned instead of `exit_now`'d from inside GL. + plx_gfx::gfx::init_gl()?; + plx_gfx::text::init_text()?; + plx_gfx::gfx::init_image()?; plx_gfx::gfx::init_blur(); // The transport takes the client's `User-Agent` as a value (it names no Plex layer): hand it // over before any request can be made, so the first one already carries it. @@ -2518,6 +2454,8 @@ pub(crate) unsafe fn construct( rec: super::recorder::Recplay::Off, boot_initial: initial, telemetry_guard: None, + #[cfg(test)] + drop_probe: Default::default(), glass, // **The application's page stack runs the route DIP** (§6.2). It ran `Immediate` until @@ -2639,16 +2577,16 @@ pub(crate) unsafe fn construct( plx_plex::plex::account::announce_discover(); if controlled { let initial = app.snapshot_init().expect("controlled constructor retains initial inputs"); - initial.validate().map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); 1 })?; + initial.validate().map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); Exit::refused(1) })?; let replay = preflight.replay(); app.rec = super::recorder::Recplay::controlled(preflight, &initial) - .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); 1 })?; + .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); Exit::refused(1) })?; let mut bridge = app.runtime.bridge(&mut app.bridge); app.rec.arm_landgate(bridge.landgate()); log("bootstrap: captured pre-effect initial state"); if let Some(deferred) = deferred { apply_deferred_capture(&mut app.rec, bridge.landgate(), deferred) - .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); 1 })?; + .map_err(|reason| { log(&format!("rec: REFUSED — {reason}")); Exit::refused(1) })?; log("bootstrap: captured session persistence applied"); } if !replay { @@ -2659,13 +2597,13 @@ pub(crate) unsafe fn construct( app.rec.prepare_resources(&mut bridge); if !matches!(activate_session(&mut bridge, &mut app.pages, &mut app.rec), BootTo::Home) { log("bootstrap: controlled Home activation refused"); - return Err(1); + return Err(Exit::refused(1)); } let tree = app.pages.state_hash(); app.rec.resource_requests(bridge.take_resource_requests()); if let Some(reason) = app.rec.failure().or_else(|| bridge.controlled_failure()) { log(&format!("bootstrap: REFUSED — {reason}")); - return Err(1); + return Err(Exit::refused(1)); } super::run::recorder_end_frame(&mut app.rec, &bridge, "home", "", "bootstrap", tree); @@ -2698,7 +2636,7 @@ pub(crate) unsafe fn construct( // Preflight refuses the still-unsupported first-run surface before resource boot. if plx_screens::consent::should_show(&initial.consent, initial.automated) { log("bootstrap: REFUSED — unsupported initial consent route"); - return Err(1); + return Err(Exit::refused(1)); } } else { maybe_ask_consent(&mut app.pages, &mut app.runtime.consent.machine.ask); diff --git a/rust-modules/src/app/exit.rs b/rust-modules/src/app/exit.rs new file mode 100644 index 0000000000..786354c0fd --- /dev/null +++ b/rust-modules/src/app/exit.rs @@ -0,0 +1,622 @@ +//! How the application ends, and what it hands back to whatever started it. +//! +//! [`run_application`](super::run_application) RETURNS an [`Exit`]; it never ends the process. +//! An early-boot refusal returns its code, and a played session returns after `run::shutdown` and +//! the telemetry guard drop. Ending the process is the EXECUTABLE entry's: `port::plex_main` (the C +//! shim and the simulator both enter through `plex_run`, which only calls it) calls +//! `plx_base::process::exit_now(exit.code)` right after, in the order the app always ended in, so a +//! television behaves as before. A process that HOSTS the application never calls `exit_now` or +//! `exit`: libc's `exit` runs OpenSSL's cleanup under the detached curl workers (#1115), and a host +//! would be killed under its own runtime. No exit a hosted process can reach remains in the tree: +//! the graphics boot returns a [`GfxFault`](plx_gfx::gfx::GfxFault) ([`Exit::from`]) where it used +//! to call `exit_now(1)`, and `lifecycle_tests` below scans the production source for any +//! `exit_now(` outside the entries. `plex_main` is typed `-> !`, a const beside it proves it, and +//! the scan holds that the const is still there. +//! +//! # What is leaked, and why +//! +//! [`entry`] wraps the mounted value in `ManuallyDrop`, so returning drops nothing: the detached +//! workers (notification feed, metadata, watchlist, auth probes) are still running, and +//! `SessionAdapter::drop`, GL object drops (`QrCode::drop` deletes a texture) and the feed +//! `Engine` must never run under them (#1115). It is the same on both entry kinds. `App`'s +//! `drop_probe` (test builds) is the sentinel that proves it: dropping the `App` drops the probe, +//! whatever its other fields are. +//! +//! # What the release says +//! +//! [`Release`] is the one decision the teardown makes about the display: `Complete` is the arm of +//! [`release_of`] that ends with `SDL_Quit()` (`NativeExit::Clean`), `Retained` is the arm that logs +//! "SDL_Quit skipped" because a native worker is still inside firmware +//! (`NativeExit::WorkerInFirmware`) and, for a refusal, "nothing was torn down". The executable +//! ignores it; a hosted entry maps `Retained` to `clean = 0`. Until the shell crate lands, `SDL_Quit` +//! IS the release of the window and the GL context, so `Complete` already means both. +//! +//! # The host doorway +//! +//! [`HostGate`], [`Completion`] and [`Stopped`] are the hosted entry's half of the contract (the +//! Tizen host's callbacks, `plx_host_stop` and its deadline watchdog). They are plain values, not +//! statics, and decide nothing by themselves that a runner has to wait for: [`HostGate::report`] +//! answers "not yet" while a gated callback is running and the runner asks again. The C ABI that +//! drives them is the hosted platform's; `lifecycle_tests` drives them through a fake host. +//! +//! ```text +//! host callback ──enter──▶ gate ──(stopping? refused)──▶ runs ──drop──▶ inflight - 1 +//! loop thread returns ──report──▶ clean = Complete AND inflight == 0 ──deliver──▶ on_stopped (once) +//! deadline thread ──expire──▶ clean = 0 ──deliver──▶ on_stopped (once; the loser is suppressed) +//! ``` + +use plx_gfx::gfx::GfxFault; +use plx_media::player::NativeExit; +use std::mem::ManuallyDrop; +use std::os::raw::c_int; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +/// Whether the application gave back every native resource it held before it returned. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Release { + /// The teardown ran to its end and released the window and the GL context. + Complete, + /// Something is still held: a native worker is inside firmware, or the boot refused before any + /// teardown ran. Nothing may be released under it, and a host treats process exit as the + /// teardown. + Retained, +} + +/// What `run_application` returns to its entry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Exit { + /// The process exit status: `1` after a failed recording or a refused boot, else `0`. + pub(crate) code: c_int, + pub(crate) release: Release, +} + +impl Exit { + /// An early-boot refusal. Nothing was torn down, so nothing is released. + pub(crate) const fn refused(code: c_int) -> Self { + Self { code, release: Release::Retained } + } + + /// A played session's end: `failed` is a recording that did not land or a controlled run that + /// refused, and `release` is what [`crate::app::run::shutdown`] returned. + pub(crate) fn played(failed: bool, release: Release) -> Self { + Self { code: c_int::from(failed), release } + } +} + +/// A required shader the driver refused ended the process with status 1 (`exit_now(1)`); it ends the +/// boot with the same status and no teardown, which is a refusal like any other. +impl From for Exit { + fn from(_: GfxFault) -> Self { + Self::refused(1) + } +} + +/// What [`crate::app::run::shutdown`] releases for a worker-exit verdict. The ONE `match` that +/// decides it, exhaustive with no `_` arm so a third [`NativeExit`] fails to compile here and in +/// [`crate::app::run::quits_sdl`], which is derived from it: the hosted report cannot say +/// `Complete` where the executable skipped `SDL_Quit`. +pub(crate) fn release_of(native_exit: NativeExit) -> Release { + match native_exit { + NativeExit::Clean => Release::Complete, + // A native worker is still inside firmware: the display must not be torn down under it. + NativeExit::WorkerInFirmware => Release::Retained, + } +} + +/// Construct, run, return, and leak: the whole of `run_application`'s body, with the two phases +/// passed in so a host test drives the same path with a refusal, a stand-in or a real `App`. +/// +/// A refusal returns its [`Exit`]. A mounted value is handed to `run` and then forgotten +/// (`ManuallyDrop`), never dropped: see the module note. `run` ends the session and says how. +pub(crate) fn entry( + enter: impl FnOnce() -> Result, + run: impl FnOnce(&mut T) -> Exit, +) -> Exit { + match enter() { + Ok(mounted) => run(&mut ManuallyDrop::new(mounted)), + Err(exit) => exit, + } +} + +/// The sentinel on `App` that shows the leak: a counter its `Drop` increments, shared with the test +/// that holds the other end. It is a FIELD, not a static, so dropping the `App` drops it whatever +/// the `App`'s other fields are (and no `statics` line is owed). +#[cfg(test)] +#[derive(Default)] +pub(crate) struct DropProbe(std::sync::Arc); + +#[cfg(test)] +impl DropProbe { + /// The counter, to be read after the `App` has gone wherever the test sent it. Only the + /// hostsim lifecycle tests build an `App` to read it from. + #[cfg_attr(not(all(feature = "hostsim", feature = "play-feed")), allow(dead_code))] + pub(crate) fn counter(&self) -> std::sync::Arc { + std::sync::Arc::clone(&self.0) + } +} + +#[cfg(test)] +impl Drop for DropProbe { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +/// One host-bound callback's admission. Every callback into the host (window, player request, log +/// sink) and every event from it (a player completion) enters through ONE of these, and is refused +/// once the stop was requested. +/// +/// `stopping` alone could only choose which sender reports; it cannot drain a callback that is +/// already running. `inflight` is that drain: [`HostGate::report`] answers `clean` only once it is +/// zero. +// The first caller is the hosted entry (the Tizen platform); `lifecycle_tests` grade it until then. +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct HostGate { + stopping: AtomicBool, + inflight: AtomicUsize, +} + +/// A callback that was admitted by [`HostGate::enter`] and has not returned. Dropping it is the +/// return. +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct InFlight<'a>(&'a HostGate); + +impl Drop for InFlight<'_> { + fn drop(&mut self) { + self.0.inflight.fetch_sub(1, Ordering::SeqCst); + } +} + +#[cfg_attr(not(test), allow(dead_code))] +impl HostGate { + pub(crate) const fn new() -> Self { + Self { stopping: AtomicBool::new(false), inflight: AtomicUsize::new(0) } + } + + /// Admit one callback, or refuse it (`None`) because the stop was requested: the caller drops a + /// late player completion and makes no further call into the host. + /// + /// The count goes up BEFORE `stopping` is read and comes back down on a refusal. The other + /// order lets a callback read "not stopping", lose the CPU while [`HostGate::stop`] and + /// [`HostGate::report`] run, and then start with the report already sent as clean. All four + /// operations are `SeqCst`, so either the callback sees the stop or `report` sees the callback. + pub(crate) fn enter(&self) -> Option> { + self.inflight.fetch_add(1, Ordering::SeqCst); + if self.stopping.load(Ordering::SeqCst) { + self.inflight.fetch_sub(1, Ordering::SeqCst); + return None; + } + Some(InFlight(self)) + } + + /// `plx_host_stop`: refuse every later callback. Answers whether THIS call is the one that + /// stopped (a second `stop` is harmless and answers `false`). + pub(crate) fn stop(&self) -> bool { + !self.stopping.swap(true, Ordering::SeqCst) + } + + pub(crate) fn stopping(&self) -> bool { + self.stopping.load(Ordering::SeqCst) + } + + /// Callbacks admitted and not yet returned. A refused [`HostGate::enter`] shows here for an + /// instant, which is why [`HostGate::report`] is asked again rather than trusted once. + pub(crate) fn in_flight(&self) -> usize { + self.inflight.load(Ordering::SeqCst) + } + + /// The loop thread's report once `run_application` returned `exit`: it stops the gate, and + /// answers `None` ("a callback is still running, ask again") until none is. `clean` is + /// `Complete` AND drained: a `Retained` loop is never clean, whatever the callbacks did. + pub(crate) fn report(&self, exit: &Exit) -> Option { + self.stop(); + (self.in_flight() == 0) + .then_some(Stopped { code: exit.code, clean: exit.release == Release::Complete }) + } + + /// The deadline thread's report, when the loop has not finished in time (a stalled swap): never + /// clean, because a loop that has not returned has released nothing. + pub(crate) fn expire(&self, code: c_int) -> Stopped { + self.stop(); + Stopped { code, clean: false } + } +} + +/// What `on_stopped(code, clean)` carries. With `clean` the host may release its callbacks and +/// surfaces; without it, it releases nothing and treats process exit as the teardown. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct Stopped { + pub(crate) code: c_int, + pub(crate) clean: bool, +} + +/// `on_stopped`'s exactly-once guard. The loop thread's report and the deadline thread's race for +/// it; the first delivers, and the loser's report is suppressed (`false`). +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) struct Completion { + delivered: AtomicBool, +} + +#[cfg_attr(not(test), allow(dead_code))] +impl Completion { + pub(crate) const fn new() -> Self { + Self { delivered: AtomicBool::new(false) } + } + + /// Deliver `stopped` through `on_stopped`, unless a report was delivered already. The watchdog + /// is disarmed first: the loop thread is about to end (its id with it), and after `on_stopped` + /// the host may tear the process down around it. + pub(crate) fn deliver(&self, stopped: Stopped, on_stopped: impl FnOnce(Stopped)) -> bool { + if self.delivered.swap(true, Ordering::SeqCst) { + return false; + } + plx_base::task::watchdog::disarm(); + on_stopped(stopped); + true + } +} + +/// The host-doorway contract, through a fake host: the second implementation of the table the +/// hosted platform will fill, with threads standing in for its. +#[cfg(test)] +mod lifecycle_tests { + use super::*; + use std::sync::{mpsc, Mutex}; + + /// A host: the gate and the once-guard its table shares, and what `on_stopped` received. It + /// holds the process-global test lock for its whole life: `Completion::deliver` disarms the + /// process watchdog, which a test that arms it and reads it back must not race. + struct FakeHost { + _serial: plx_base::testlock::Serial, + gate: HostGate, + completion: Completion, + /// Each delivery, with whether the watchdog was still armed when the callback ran. + received: Mutex>, + } + + impl FakeHost { + fn new() -> Self { + Self { + _serial: plx_base::testlock::serial(), + gate: HostGate::new(), + completion: Completion::new(), + received: Mutex::new(Vec::new()), + } + } + + fn on_stopped(&self, stopped: Stopped) { + self.received.lock().unwrap().push((stopped, plx_base::task::watchdog::is_armed())); + } + + /// The loop thread's tail once `run_application` returned: ask until the gate drains. + fn loop_returned(&self, exit: &Exit) -> bool { + loop { + if let Some(stopped) = self.gate.report(exit) { + return self.completion.deliver(stopped, |stopped| self.on_stopped(stopped)); + } + std::thread::yield_now(); + } + } + + /// The watchdog thread `plx_host_stop` starts, once its deadline passed. + fn deadline(&self, code: c_int) -> bool { + let stopped = self.gate.expire(code); + self.completion.deliver(stopped, |stopped| self.on_stopped(stopped)) + } + + fn received(&self) -> Vec { + self.received.lock().unwrap().iter().map(|(stopped, _)| *stopped).collect() + } + } + + fn quit() -> Exit { + Exit::played(false, Release::Complete) + } + + #[test] + fn a_boot_refusal_returns_its_code_and_the_host_is_told_once() { + let exit = entry::<()>(|| Err(Exit::refused(7)), |_| unreachable!("nothing was mounted")); + assert_eq!(exit, Exit { code: 7, release: Release::Retained }); + let host = FakeHost::new(); + assert!(host.loop_returned(&exit)); + assert_eq!(host.received(), [Stopped { code: 7, clean: false }], + "a refusal tore nothing down, so the host is told not to release anything"); + } + + #[test] + fn a_shader_the_driver_refused_reaches_the_host_as_status_one_and_the_host_stays_alive() { + for fault in [GfxFault::Compile, GfxFault::Link] { + let exit = entry::<()>(|| Err(Exit::from(fault)), |_| unreachable!("nothing was mounted")); + assert_eq!(exit, Exit { code: 1, release: Release::Retained }, "{fault}"); + let host = FakeHost::new(); + assert!(host.loop_returned(&exit)); + assert_eq!(host.received(), [Stopped { code: 1, clean: false }], "{fault}"); + } + } + + #[test] + fn a_quit_during_playback_returns_after_the_teardown_and_reports_clean() { + let ended = Mutex::new(false); + let exit = entry(|| Ok(()), |_| { + *ended.lock().unwrap() = true; + quit() + }); + assert!(*ended.lock().unwrap(), "the session ran before the entry returned"); + assert_eq!(exit, Exit { code: 0, release: Release::Complete }); + let host = FakeHost::new(); + assert!(host.loop_returned(&exit)); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + #[test] + fn a_failed_recording_is_status_one_and_still_a_complete_release() { + assert_eq!(Exit::played(true, Release::Complete), Exit { code: 1, release: Release::Complete }); + } + + #[test] + fn a_stop_with_a_player_request_outstanding_drops_its_late_completion() { + let host = FakeHost::new(); + // The loop asked the host to play; the host took the request and has not answered. + drop(host.gate.enter().expect("a request before the stop is admitted")); + assert!(host.gate.stop(), "plx_host_stop"); + assert!(host.loop_returned(&quit())); + // The completion arrives after the stop: dropped, and nothing is delivered for it. + assert!(host.gate.enter().is_none(), "a late player completion is refused"); + assert_eq!(host.gate.in_flight(), 0, "a refusal leaves nothing counted"); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + #[test] + fn a_returning_loop_with_a_retained_worker_is_never_clean() { + let host = FakeHost::new(); + assert!(host.loop_returned(&Exit::played(false, Release::Retained))); + assert_eq!(host.received(), [Stopped { code: 0, clean: false }], + "a worker is still in firmware: the host releases nothing"); + } + + #[test] + fn a_callback_in_flight_at_stop_holds_the_clean_report_until_it_returns() { + let gate = HostGate::new(); + let running = gate.enter().expect("admitted"); + assert_eq!(gate.in_flight(), 1); + assert_eq!(gate.report(&quit()), None, "a flag alone cannot drain a callback already running"); + assert!(gate.stopping(), "and the report itself refuses every later one"); + assert!(gate.enter().is_none()); + drop(running); + assert_eq!(gate.report(&quit()), Some(Stopped { code: 0, clean: true })); + } + + #[test] + fn the_loop_thread_waits_for_a_running_callback_and_reports_exactly_once() { + let host = FakeHost::new(); + let running = host.gate.enter().expect("admitted"); + let (done, finished) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| done.send(host.loop_returned(&quit())).unwrap()); + while !host.gate.stopping() { + std::thread::yield_now(); + } + assert!(host.received().is_empty(), "the callback has not returned: nothing is reported"); + drop(running); + assert!(finished.recv().unwrap(), "the loop thread delivered"); + }); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + /// Two senders, one flag: whichever reaches it first delivers, and the loser is suppressed. + #[test] + fn a_swap_that_stalls_and_wakes_after_the_deadline_reports_once_and_unclean() { + let host = FakeHost::new(); + assert!(host.deadline(1), "the deadline thread reports while the loop is still stuck"); + assert!(!host.loop_returned(&quit()), "the loop wakes, returns Complete, and is suppressed"); + assert_eq!(host.received(), [Stopped { code: 1, clean: false }]); + } + + #[test] + fn a_loop_that_returns_in_time_suppresses_the_deadline() { + let host = FakeHost::new(); + assert!(host.loop_returned(&quit())); + assert!(!host.deadline(1)); + assert_eq!(host.received(), [Stopped { code: 0, clean: true }]); + } + + #[test] + fn two_senders_racing_deliver_exactly_once() { + for _ in 0..200 { + let host = FakeHost::new(); + let delivered = std::thread::scope(|scope| { + let loop_thread = scope.spawn(|| host.loop_returned(&quit())); + let deadline = scope.spawn(|| host.deadline(1)); + [loop_thread.join().unwrap(), deadline.join().unwrap()] + }); + assert_eq!(delivered.iter().filter(|delivered| **delivered).count(), 1); + assert_eq!(host.received().len(), 1); + } + } + + #[test] + fn pause_then_stop_leaves_the_watchdog_disarmed_when_on_stopped_runs() { + let host = FakeHost::new(); + plx_base::task::watchdog::arm(); + // OnPause: nothing may signal the loop thread while the host is parked. + plx_base::task::watchdog::disarm(); + assert!(!plx_base::task::watchdog::is_armed()); + // OnResume re-captures the loop thread. + plx_base::task::watchdog::arm(); + assert!(plx_base::task::watchdog::is_armed()); + // Stop: the report disarms before the callback runs. + assert!(host.loop_returned(&quit())); + let received = host.received.lock().unwrap(); + assert_eq!(received.len(), 1); + assert!(!received[0].1, "the watchdog was disarmed before on_stopped"); + } + + #[test] + fn the_gate_refuses_after_stop_and_counts_what_it_admitted() { + let gate = HostGate::new(); + assert!(!gate.stopping()); + let (first, second) = (gate.enter().unwrap(), gate.enter().unwrap()); + assert_eq!(gate.in_flight(), 2); + drop(first); + assert_eq!(gate.in_flight(), 1); + assert!(gate.stop()); + assert!(!gate.stop(), "only the first stop is the one that stopped"); + assert!(gate.enter().is_none()); + drop(second); + assert_eq!(gate.in_flight(), 0); + } + + #[test] + fn release_follows_the_worker_exit_verdict_in_both_directions() { + assert_eq!(release_of(NativeExit::Clean), Release::Complete); + assert_eq!(release_of(NativeExit::WorkerInFirmware), Release::Retained); + } + + /// **No exit of the app process returns into libc's `exit`, and none a hosted process could + /// reach is left.** `exit` runs libcrypto's `OPENSSL_cleanup`, which frees and NULLs its global + /// locks while the detached curl workers still run (#1115), so every exit goes through + /// `plx_base::process::exit_now`; and that is the executable entries' to call, because a host + /// is killed under its own runtime by one. `run_application` and the graphics boot RETURN + /// (`Exit`, `GfxFault`), so the production `exit_now(` sites are the entries that own the + /// process end (`port::plex_main`, the simulator's `main`), the frame dump (`devtriggers`, off in + /// a release build) and the helper itself. A new exit anywhere else fails here. + #[test] + fn lifecycle_no_production_exit_is_reachable_from_a_hosted_process() { + // The app process links every crate under rust-modules except `storage` (the separate + // `plxstorage` helper binary, no OpenSSL workers) and os's `storage_service/` (that + // helper's body). `base/src/process.rs` is the helper itself. + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let mut files = Vec::new(); + collect_rs(&root.join("src"), &mut files); + for entry in std::fs::read_dir(root).expect("rust-modules") { + let dir = entry.expect("entry").path(); + let name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string(); + if matches!(name.as_str(), "storage" | "target" | "tests") + || name.starts_with("target-") + || !dir.join("src").is_dir() + { + continue; + } + collect_rs(&dir.join("src"), &mut files); + } + assert!(files.len() > 100, "the scan must see the whole tree"); + let owns_process_end = ["src/port.rs", "src/bin/sim.rs", "src/dev/framedump.rs"].map(|p| root.join(p)); + for entry in &owns_process_end { + assert!(entry.is_file(), "{}: an entry the scan allows is gone; update the list", entry.display()); + } + let (libc_exit, std_exit, exit_now) = + (concat!("process::", "exit("), concat!("libc::", "exit("), concat!("exit_", "now(")); + let mut hits = Vec::new(); + for f in files { + let path = f.to_string_lossy().replace('\\', "/"); + if path.ends_with("base/src/process.rs") + || path.contains("/storage_service/") + || path.contains("/tests/") + || path.ends_with("_tests.rs") + { + continue; + } + let text = std::fs::read_to_string(&f).expect("read"); + let prod = production_prefix(&text); + if path.ends_with("src/app/mod.rs") { + assert!(prod.contains("fn run_application"), "the scan must still reach run_application"); + } + if f == root.join("src/port.rs") { + // The process entry ends the process itself and is typed `-> !`: `plex_run` returns + // into `__libc_start_main`'s libc `exit` if it ever returns (#1115). The const is the + // compile-time proof for `plex_main` only; `plex_run`, the C entry, is `-> c_int`, so + // an early `return 2;` above its call to `plex_main` would compile (`!` coerces). This + // holds the const still there, `plex_main` still the one that exits, and `plex_run` + // exactly the one call. All of it is read off comment-stripped lines, so a commented-out + // const or call cannot satisfy it (and no block comment may exist to defeat that). + assert!(!prod.contains("/*"), "port.rs has a block comment; strip those as well"); + let code: String = + prod.lines().map(|l| l.split("//").next().unwrap_or("")).collect::>().join("\n"); + let main = code.split_once("fn plex_main(").expect("port.rs must keep plex_main").1; + let main = main.split_once("\n}\n").expect("the end of plex_main").0; + assert!(main.contains(exit_now), "plex_main must end the process through exit_now"); + assert!( + code.contains("const _: fn(*const c_char, c_int) -> ! = plex_main;"), + "the const proving plex_main never returns is gone" + ); + let run = code.split_once("fn plex_run(").expect("port.rs must keep plex_run").1; + let run = run.split_once('{').expect("the start of plex_run's body").1; + let run = run.split_once('}').expect("the end of plex_run's body").0; + assert_eq!( + run.split_whitespace().collect::>().join(" "), + "plex_main(pms_host, pms_port)", + "plex_run must be exactly the call to plex_main: no `return`, no other statement, \ + or it can return into libc `exit` (#1115)" + ); + } + for (n, line) in prod.lines().enumerate() { + let code = line.split("//").next().unwrap_or(""); + if code.contains(libc_exit) + || code.contains(std_exit) + || (code.contains(exit_now) && !owns_process_end.contains(&f)) + { + hits.push(format!("{path}:{}", n + 1)); + } + } + } + assert!( + hits.is_empty(), + "exit through plx_base::process::exit_now from an entry that owns the process end, \ + never libc exit (#1115) and never from library code a host runs: {hits:?}" + ); + } + + /// The text above the file's first `#[cfg(test)]` MODULE. A `#[cfg(test)]` import or field on the + /// way (`app/mod.rs` has both, above `run_application`) must not hide the production code under it. + fn production_prefix(text: &str) -> &str { + let lines: Vec<&str> = text.split_inclusive('\n').collect(); + let mut offset = 0; + for pair in lines.windows(2) { + let attr = pair[0].trim(); + let test_only = attr == "#[cfg(test)]" || attr.starts_with("#[cfg(all(test"); + if test_only && pair[1].contains("mod ") && pair[1].trim_end().ends_with('{') { + return &text[..offset]; + } + offset += pair[0].len(); + } + text + } + + fn collect_rs(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).expect("read_dir").flatten() { + let p = entry.path(); + if p.is_dir() { + collect_rs(&p, out); + } else if p.extension().is_some_and(|e| e == "rs") { + out.push(p); + } + } + } + + /// The `App` itself: the rig builds a real one, which only a hostsim build with the Feed has. + #[cfg(all(feature = "hostsim", feature = "play-feed"))] + mod app_leak { + use super::*; + use crate::app::run::lifecycle_regression_tests::app; + + #[test] + fn the_returning_exit_path_leaks_the_app_so_nothing_under_it_drops() { + let _serial = plx_base::testlock::serial(); + let app = app(); + let dropped = app.drop_probe.counter(); + let exit = entry(|| Ok(app), |_| quit()); + assert_eq!(exit, quit()); + assert_eq!(dropped.load(Ordering::SeqCst), 0, "the probe is a field: no field of the App dropped"); + } + + #[test] + fn control_an_app_dropped_the_ordinary_way_trips_the_probe() { + let _serial = plx_base::testlock::serial(); + let app = app(); + let dropped = app.drop_probe.counter(); + drop(app); + assert_eq!(dropped.load(Ordering::SeqCst), 1, "the probe detects a drop"); + } + } +} diff --git a/rust-modules/src/app/mod.rs b/rust-modules/src/app/mod.rs index 1996146a90..341e151c8d 100644 --- a/rust-modules/src/app/mod.rs +++ b/rust-modules/src/app/mod.rs @@ -2,7 +2,8 @@ //! event loop, input decode, the per-frame tick, draw orchestration, app lifecycle, //! the buffer-feed pump orchestration, and the dev triggers. The C boot shim //! (main.c) sets up the log and fallback crash tracer, calls the Rust image-marker and native-spool -//! entries when required, then calls `plex_run` (port.rs), which hands over to `run_application`. +//! entries when required, then calls `plex_run` (port.rs), which hands over to `run_application` +//! and, when it returns its `Exit` (`exit.rs`), ends the process. //! The only application subsystems left in C are the starfish.c C++ Feed seam and the video_plane.c //! ACB / exported-window display binding (the engine itself is Rust: plx_media::player). #![allow(non_upper_case_globals)] @@ -131,6 +132,8 @@ mod clock_notice; mod hint_taught; mod recorder; mod window_activity; +mod exit; +pub(crate) use exit::Exit; pub(crate) mod events; pub(crate) mod lifecycle; pub(crate) mod playback; @@ -368,6 +371,12 @@ pub(crate) struct App { pub(crate) rec: recorder::Recplay, pub(crate) boot_initial: Option, pub(crate) telemetry_guard: Option, + /// The sentinel that proves the returning exit leaks the `App` (`exit::entry`): a counter its + /// own drop increments, so dropping the `App` drops it whatever the other fields are. A field, + /// not a static. Read by the hostsim lifecycle tests, which build the `App` the rig needs. + #[cfg(test)] + #[cfg_attr(not(all(feature = "hostsim", feature = "play-feed")), allow(dead_code))] + drop_probe: exit::DropProbe, /// The frame plan's GLASS half (spec §8.3): the layer/region source registry, shared chrome /// material and dev load dial. The budget half lives on the `Dispatcher` (§2.2). @@ -434,7 +443,7 @@ impl App { /// Controlled construction receives decoded/captured inputs before bootstrap effects. pub(crate) unsafe fn from_init(initial: bootstrap::Initial, mode: bootstrap::Preflight, pms_host: *const c_char, pms_port: c_int, mt: plx_base::task::MainThread, - deferred: Option) -> Result { + deferred: Option) -> Result { boot::construct(pms_host, pms_port, mt, mode, Some(initial), deferred) } /// **Which page is on top** (spec §15.2) — the container's answer, and since D1 the ONLY one. @@ -558,7 +567,11 @@ fn pre_boot_diagnostics() -> plx_telemetry::telemetry::native::Guard { /// The run+teardown sequence `run_application` hands the mounted `App` to, split out for the same /// reason as [`pre_boot_diagnostics`] (D4): `run_application` stays a ten-line skeleton naming only /// the THREE real phases (pre-boot diagnostics, `boot`, this), never the steps inside any one of them. -unsafe fn run_and_shutdown(app: &mut App) -> ! { +/// +/// It RETURNS how the session ended; ending the process is the executable entry's (`port::plex_run`). +/// The `App` is leaked by the caller (`exit::entry`), so the last thing this does is the one `Drop` +/// that persists something. +unsafe fn run_and_shutdown(app: &mut App) -> Exit { run::run(app); // The crash record's phase (`src/crashtrace.c`): from here a fault is in the teardown. plx_base::task::watchdog::set_crash_phase(plx_base::task::watchdog::CrashPhase::Shutdown); @@ -568,12 +581,11 @@ unsafe fn run_and_shutdown(app: &mut App) -> ! { let failed = finish_recording(&mut app.rec, bridge.landgate()) || bridge.controlled_failure().is_some(); app.glass.sources.borrow_mut().clear(); - let code = i32::from(failed); - run::shutdown(&mut app.player.session, &mut app.adapters.player); + let release = run::shutdown(&mut app.player.session, &mut app.adapters.player); // The crash-channel guard is the one `Drop` that persists something (it closes the capture // backend and removes its database), so it runs here explicitly: nothing drops the `App`. drop(app.telemetry_guard.take()); - plx_base::process::exit_now(code) + Exit::played(failed, release) } fn finish_recording(rec: &mut recorder::Recplay, gate: &plx_machine::landgate::Gate) -> bool { @@ -597,7 +609,7 @@ pub fn synthetic_home_initial(seed: u32, port: u16, settings: Option) serde_json::to_string_pretty(&initial).map_err(|_| "cannot encode synthetic initial inputs") } -fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result { +fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result { // What `plx_plex` reports as `X-Plex-Version` is this build's `PLX_VERSION`, which a // `cargo:rustc-env` makes visible to this crate only; before anything can build a header. plx_plex::plex::identity::set_version(env!("PLX_VERSION")); @@ -617,7 +629,7 @@ fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result mode, - Err(reason) => { log(&format!("replay: REFUSED — {reason}")); return Err(1); } + Err(reason) => { log(&format!("replay: REFUSED — {reason}")); return Err(Exit::refused(1)); } }; // The player's `…` menu draws the Stats for nerds switch from the read-out's own flag, which // this layer owns and `appkit` cannot name, so it is handed the reader on EVERY boot (a @@ -639,11 +651,11 @@ fn enter_application(pms_host: *const c_char, pms_port: c_int) -> Result ! { - // An early-boot refusal ends the same way: the workers it has already started (diagnostics, - // capability probe, telemetry) are as live as after a played session. - let mut app = match enter_application(pms_host,pms_port) { Ok(app) => app, Err(code) => plx_base::process::exit_now(code) }; - unsafe { run_and_shutdown(&mut app) } +pub(crate) fn run_application(pms_host: *const c_char, pms_port: c_int) -> Exit { + // Returns how it ended and drops nothing: an early-boot refusal has live workers (diagnostics, + // capability probe, telemetry) just as a played session does, so `exit::entry` leaks the `App`. + // Ending the process is the entry's (`port::plex_run`); a hosted entry never does. + exit::entry(|| enter_application(pms_host,pms_port), |app| unsafe { run_and_shutdown(app) }) } diff --git a/rust-modules/src/app/run.rs b/rust-modules/src/app/run.rs index 831fbe7943..61912e3956 100644 --- a/rust-modules/src/app/run.rs +++ b/rust-modules/src/app/run.rs @@ -34,6 +34,7 @@ use super::*; use plx_ui::dispatch::Rig as _; use super::bridge::AppHost; +use super::exit::{release_of, Release}; /// One lazy product frame-tail hash path for recording and replay grading alike. pub(super) fn recorder_end_frame( @@ -3706,24 +3707,23 @@ pub(crate) unsafe fn heartbeat(app: &mut App, fr: &mut Frame) { } } -/// Whether [`shutdown`] quits SDL before the process ends. EVERY exit ends the process with `_exit` -/// (`plx_base::process::exit_now`), never by returning into libc's `exit` (#1115); this is the one decision -/// left in the teardown. +/// Whether [`shutdown`] quits SDL before the process ends. The executable entry ends the process with +/// `_exit` (`plx_base::process::exit_now`), never by returning into libc's `exit` (#1115); this is the one +/// decision left in the teardown, and it is [`release_of`]'s: `SDL_Quit` runs exactly when the +/// release is `Complete`, so the hosted entry's report cannot say `Complete` where the executable +/// skipped it. pub(crate) fn quits_sdl(native_exit: plx_media::player::NativeExit) -> bool { - match native_exit { - plx_media::player::NativeExit::Clean => true, - // A native worker is still inside firmware: the display must not be torn down under it. - plx_media::player::NativeExit::WorkerInFirmware => false, - } + release_of(native_exit) == Release::Complete } /// Teardown after the loop: abandon the pending report, stop the active backend, wait for the stop /// scrobble, close the capture stream and the poster workers, quit SDL (unless a worker is still -/// in firmware). The caller (`app::run_and_shutdown`) then ends the process with `_exit`. +/// in firmware). Answers what it released: the caller (`app::run_and_shutdown`) returns it in the +/// `Exit`, and the executable entry then ends the process with `_exit`. pub(crate) unsafe fn shutdown( ps: &mut plx_media::route::PlaybackSession, pa: &mut plx_media::player::adapter::PlayerAdapter, -) { +) -> Release { ps.finish_metric_request(plx_media::player::attempt_metrics::RequestOutcome::Cancelled); pa.sync_request_metrics(ps); plx_media::player::report::abandon_pending(ps); @@ -3734,7 +3734,7 @@ pub(crate) unsafe fn shutdown( // object it is releasing left undestroyed. The wait is bounded, and a worker still inside // firmware (an overdue `Unload`, or a timed-out Load's media thread) means the display must not // be torn down under it, and nothing may run the firmware libraries' destructors either: the - // caller (`app::run_and_shutdown`) ends the process with `_exit`. + // executable entry ends the process with `_exit`, and the `App` is leaked (`app::exit::entry`). let native_exit = plx_media::player::exit_native(ps, pa); // The stop scrobble is posted off-thread now, and this process is about to die with any // worker still running — so THIS is the one place its result has to be waited for, or the @@ -3751,6 +3751,7 @@ pub(crate) unsafe fn shutdown( } else { log("shutdown: a native worker is still inside firmware; SDL_Quit skipped, exiting without unwinding"); } + release_of(native_exit) } /// Re-inject one recorded input (`app::recorder`'s encodings) for the frame being replayed: SDL @@ -3912,14 +3913,21 @@ unsafe fn controlled_key_input(app: &mut App, event: plx_machine::machine::Input } #[cfg(all(test, feature = "hostsim", feature = "play-feed"))] -mod lifecycle_regression_tests { +pub(in crate::app) mod lifecycle_regression_tests { use super::*; + /// Both answers, pinned for both variants: `SDL_Quit` runs exactly when the release is + /// `Complete`, so the hosted report cannot say `Complete` where the executable skipped it. #[test] fn shutdown_quits_sdl_only_when_no_worker_is_in_firmware() { use plx_media::player::NativeExit; assert!(!quits_sdl(NativeExit::WorkerInFirmware)); assert!(quits_sdl(NativeExit::Clean)); + assert_eq!(release_of(NativeExit::WorkerInFirmware), Release::Retained); + assert_eq!(release_of(NativeExit::Clean), Release::Complete); + for exit in [NativeExit::Clean, NativeExit::WorkerInFirmware] { + assert_eq!(quits_sdl(exit), release_of(exit) == Release::Complete, "{exit:?}: one decision, two readings"); + } } use std::io::{BufRead, BufReader, Read, Write}; use std::sync::{ @@ -3967,7 +3975,7 @@ mod lifecycle_regression_tests { } // No boot, renderer or device: the real App/event/frame phases with Bridge's host rig. - fn app() -> App { + pub(in crate::app) fn app() -> App { plx_play_feed::ff_test_support::reset_session_for_test(&mut plx_media::player::reset_common_for_test); let (runtime, bridge) = super::super::bridge::BridgeRetained::for_test(|| 0); let mut app = App { @@ -4106,6 +4114,7 @@ mod lifecycle_regression_tests { rec: super::super::recorder::Recplay::Off, boot_initial: Default::default(), telemetry_guard: Default::default(), + drop_probe: Default::default(), glass: Default::default(), pages: plx_ui::dispatch::Dispatcher::new(), diff --git a/rust-modules/src/port.rs b/rust-modules/src/port.rs index 9c0ef1f871..89f91fbf8f 100644 --- a/rust-modules/src/port.rs +++ b/rust-modules/src/port.rs @@ -52,16 +52,35 @@ static PORT: plx_os::tv::Port = plx_os::tv::Port { uri_media: plx_os::webos::URI_MEDIA, }; -/// The C shim's entry (`src/main.c`) and the simulator's (`src/bin/sim.rs`): install the port, then -/// hand over to `app::run_application`. +/// The C shim's entry (`src/main.c`) and the simulator's (`src/bin/sim.rs`). The `-> c_int` is only +/// the C signature: `plex_main` never returns, so neither does this. #[no_mangle] pub extern "C" fn plex_run(pms_host: *const c_char, pms_port: c_int) -> c_int { + plex_main(pms_host, pms_port) +} + +/// The process entry: install the port, hand over to `app::run_application`, then end the process +/// with the status it returned. +/// +/// The executable owns the process end: `exit_now` (`_exit`, never libc's `exit`, #1115) right after +/// the app returns, in the order the app always ended in. A process that hosts the app never calls it. +/// +/// It is typed `-> !` rather than left to diverge through its last expression. `src/main.c` does +/// `return plex_run(..)`, so an entry that returned would fall into `__libc_start_main`, which calls +/// libc `exit` directly (the interposer in `src/exit.c` cannot catch that), and `OPENSSL_cleanup` +/// would then free libcrypto's locks under the live curl workers (#1115). The `const` below is the +/// compile-time proof that replaced the ones `app::boot`'s `seam_order_tests` held for +/// `run_application` and `run_and_shutdown` when those started to return an `Exit`: a later edit that +/// lets this return does not compile. +fn plex_main(pms_host: *const c_char, pms_port: c_int) -> ! { let _ = plx_os::tv::install(&PORT); #[cfg(target_os = "linux")] let _ = plx_os::storage::client::install_activator(plx_os::webos::activate_storage_helper); - crate::app::run_application(pms_host, pms_port) + plx_base::process::exit_now(crate::app::run_application(pms_host, pms_port).code) } +const _: fn(*const c_char, c_int) -> ! = plex_main; + /// `src/main.c` hands over SAM's launch payload (`argv[1]`) before `plex_run`. Kept raw in /// `tv::launch`; `app::deeplink` reads it once the app has a session to act in. ///