diff --git a/Cargo.lock b/Cargo.lock index ce785ca..8023ba4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -272,6 +272,15 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -569,6 +578,15 @@ dependencies = [ "windows 0.54.0", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -590,6 +608,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -602,6 +630,16 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -820,6 +858,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -2113,6 +2161,7 @@ dependencies = [ "prometeu-system", "ringbuf", "serde_json", + "sha2", "winit", ] @@ -2159,6 +2208,7 @@ dependencies = [ "prometeu-vm", "serde", "serde_json", + "sha2", ] [[package]] @@ -2504,6 +2554,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "1.3.0" @@ -2773,6 +2834,12 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "ultraviolet" version = "0.10.0" diff --git a/crates/console/prometeu-system/Cargo.toml b/crates/console/prometeu-system/Cargo.toml index d3d013b..f2e5e5c 100644 --- a/crates/console/prometeu-system/Cargo.toml +++ b/crates/console/prometeu-system/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [dependencies] serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.149" +sha2 = "0.10.9" prometeu-vm = { path = "../prometeu-vm" } prometeu-bytecode = { path = "../prometeu-bytecode" } prometeu-hal = { path = "../prometeu-hal" } diff --git a/crates/console/prometeu-system/src/crash_report.rs b/crates/console/prometeu-system/src/crash_report.rs index a686efd..d43bbec 100644 --- a/crates/console/prometeu-system/src/crash_report.rs +++ b/crates/console/prometeu-system/src/crash_report.rs @@ -11,6 +11,22 @@ pub enum CrashReport { } impl CrashReport { + /// Canonical machine facts; presentation and transport envelopes remain host-owned. + pub fn diagnostic(&self) -> serde_json::Value { + use serde_json::json; + let mut result = json!({"kind":self.kind(),"pc":self.pc(),"summary":self.summary()}); + match self { + Self::VmTrap { trap } => { + result["trap"] = json!({"code":trap.code,"opcode":trap.opcode, + "message":trap.message,"pc":trap.pc,"span":trap.span,"resource":trap.resource}) + } + Self::VmPanic { message, .. } => result["message"] = json!(message), + Self::VmInit { .. } => { + result["initError"] = self.init_diagnostic().expect("initialization report") + } + } + result + } /// The same machine fields serve headless and desktop transports. pub fn init_diagnostic(&self) -> Option { match self { diff --git a/crates/console/prometeu-system/src/os/facades/vm.rs b/crates/console/prometeu-system/src/os/facades/vm.rs index 9ceee00..f29a2ab 100644 --- a/crates/console/prometeu-system/src/os/facades/vm.rs +++ b/crates/console/prometeu-system/src/os/facades/vm.rs @@ -425,6 +425,12 @@ impl<'a> VmFacade<'a> { .unwrap_or(self.os.vm_runtime.current_app_id) } + pub fn loaded_program_sha256(&self) -> Option<[u8; 32]> { + self.active_session() + .and_then(|session| session.runtime.loaded_program_sha256) + .or(self.os.vm_runtime.loaded_program_sha256) + } + pub fn current_cartridge_title(&self) -> String { self.active_session() .map(|session| session.runtime.current_cartridge_title.clone()) diff --git a/crates/console/prometeu-system/src/services/vm_runtime/lifecycle.rs b/crates/console/prometeu-system/src/services/vm_runtime/lifecycle.rs index 607b234..eb41675 100644 --- a/crates/console/prometeu-system/src/services/vm_runtime/lifecycle.rs +++ b/crates/console/prometeu-system/src/services/vm_runtime/lifecycle.rs @@ -35,6 +35,7 @@ impl VirtualMachineRuntime { game_lifecycle_events_delivered: Vec::new(), atomic_telemetry, last_crash_report: None, + loaded_program_sha256: None, certifier: Certifier::new(cap_config.unwrap_or_default()), paused: false, debug_step_request: false, @@ -139,6 +140,7 @@ impl VirtualMachineRuntime { self.game_lifecycle_events_delivered.clear(); self.last_crash_report = None; + self.loaded_program_sha256 = None; self.paused = false; self.debug_step_request = false; @@ -226,6 +228,8 @@ impl VirtualMachineRuntime { ) -> Result<(), CrashReport> { self.clear_cartridge_state(); vm.set_capabilities(cartridge.capabilities); + use sha2::Digest; + self.loaded_program_sha256 = Some(sha2::Sha256::digest(&cartridge.program).into()); match vm.initialize(cartridge.program.clone()) { Ok(_) => { diff --git a/crates/console/prometeu-system/src/services/vm_runtime/mod.rs b/crates/console/prometeu-system/src/services/vm_runtime/mod.rs index e37f580..23064ed 100644 --- a/crates/console/prometeu-system/src/services/vm_runtime/mod.rs +++ b/crates/console/prometeu-system/src/services/vm_runtime/mod.rs @@ -53,6 +53,8 @@ pub struct VirtualMachineRuntime { pub game_lifecycle_events_delivered: Vec, pub atomic_telemetry: Arc, pub last_crash_report: Option, + /// Digest of the exact bounded PBX input supplied to initialization. + pub loaded_program_sha256: Option<[u8; 32]>, pub certifier: Certifier, pub paused: bool, pub debug_step_request: bool, diff --git a/crates/host/prometeu-host-desktop-winit/Cargo.toml b/crates/host/prometeu-host-desktop-winit/Cargo.toml index 032d6b9..2d84a3f 100644 --- a/crates/host/prometeu-host-desktop-winit/Cargo.toml +++ b/crates/host/prometeu-host-desktop-winit/Cargo.toml @@ -25,6 +25,9 @@ ringbuf = "0.4.7" serde_json = "1.0.149" clap = { version = "4.5", features = ["derive"] } +[dev-dependencies] +sha2 = "0.10.9" + [[bench]] name = "wall_clock" harness = false diff --git a/crates/host/prometeu-host-desktop-winit/src/runner.rs b/crates/host/prometeu-host-desktop-winit/src/runner.rs index 34e123a..ef2f271 100644 --- a/crates/host/prometeu-host-desktop-winit/src/runner.rs +++ b/crates/host/prometeu-host-desktop-winit/src/runner.rs @@ -153,6 +153,7 @@ pub struct HostRunner { /// Tracks whether a new logical frame or host-only surface invalidation requires presentation. presentation: PresentationState, studio_capture: bool, + studio_loaded_program_sha256: Option<[u8; 32]>, } impl HostRunner { @@ -242,6 +243,7 @@ impl HostRunner { render_frame_store, presentation: PresentationState::default(), studio_capture: false, + studio_loaded_program_sha256: None, } } @@ -274,6 +276,12 @@ impl HostRunner { } } + pub(crate) fn studio_start_background_io(&mut self) { + // Mount admission may precede audio setup. Its worker must already run + // while a platform audio driver initializes, without advancing the VM. + self.firmware.os.poll_background_io(&mut self.hardware); + } + pub(crate) fn studio_boot_step(&mut self, disposable: bool) -> Result { self.studio_capture = true; if matches!(self.firmware.state, FirmwareState::GameRunning(_)) { @@ -317,6 +325,22 @@ impl HostRunner { Ok(()) } + pub(crate) fn studio_crash_report(&self) -> Option { + match &self.firmware.state { + FirmwareState::AppCrashes(step) => Some(step.report.clone()), + _ => None, + } + } + + pub(crate) fn studio_program_sha256(&mut self) -> Option<[u8; 32]> { + // Firmware may remove the failed VM session when entering AppCrashes. + // Keep the identity observed before READY for the final diagnostic. + if let Some(digest) = self.firmware.os.vm().loaded_program_sha256() { + self.studio_loaded_program_sha256 = Some(digest); + } + self.studio_loaded_program_sha256 + } + pub(crate) fn studio_pause(&mut self, paused: bool) { self.input.clear_guest_signals(); self.firmware.os.vm().set_paused(paused); @@ -687,6 +711,38 @@ impl ApplicationHandler for HostRunner { mod tests { use super::*; + #[test] + fn studio_background_io_runs_admitted_mount_before_any_firmware_tick() { + for start_worker in [false, true] { + let mut host = HostRunner::new(None, None); + let (entered, receiver) = std::sync::mpsc::channel(); + host.firmware + .os + .memcard() + .mount_card_with(move || { + entered.send(()).unwrap(); + Err(prometeu_system::memcard::image::Error::InvalidState) + }) + .unwrap(); + if start_worker { + host.studio_start_background_io(); + receiver + .recv_timeout(Duration::from_secs(2)) + .expect("mount worker did not run before firmware"); + let deadline = Instant::now() + Duration::from_secs(2); + while host.firmware.os.memcard().preparation_active() { + assert!(Instant::now() < deadline); + host.firmware.os.memcard().poll(Instant::now()); + std::thread::yield_now(); + } + } + host.firmware.os.memcard().poll(Instant::now() + Duration::from_secs(2)); + assert_eq!(host.firmware.os.memcard().host_faulted(), !start_worker); + assert!(matches!(host.firmware.state, FirmwareState::Reset(_))); + host.studio_abort(); + } + } + #[test] fn studio_stress_demoscene_publishes_graphics_and_native_music() { let cart = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) diff --git a/crates/host/prometeu-host-desktop-winit/src/studio/diagnostic.rs b/crates/host/prometeu-host-desktop-winit/src/studio/diagnostic.rs new file mode 100644 index 0000000..d18b3de --- /dev/null +++ b/crates/host/prometeu-host-desktop-winit/src/studio/diagnostic.rs @@ -0,0 +1,95 @@ +use super::wire::{CONTROL_LIMIT, invalid}; +use prometeu_system::CrashReport; +use serde_json::{Value, json}; +use std::io; + +pub(super) fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn bound_strings(value: &mut Value, limit: usize) -> bool { + match value { + Value::String(text) if text.len() > limit => { + let mut end = limit; + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + true + } + Value::Array(items) => { + items.iter_mut().fold(false, |changed, item| bound_strings(item, limit) | changed) + } + Value::Object(items) => { + items.values_mut().fold(false, |changed, item| bound_strings(item, limit) | changed) + } + _ => false, + } +} + +pub(super) fn payload( + report: &CrashReport, + session: &[u8; 16], + program: Option<[u8; 32]>, + tick: u64, +) -> io::Result> { + let mut fault = report.diagnostic(); + let mut truncated = bound_strings(&mut fault, 8192); + let envelope = |fault: &Value, truncated| { + json!({"schemaVersion":1,"sessionId":hex(session), + "programSha256":program.map(|p|hex(&p)),"tick":tick,"truncated":truncated,"fault":fault}) + }; + let mut bytes = + serde_json::to_vec(&envelope(&fault, truncated)).map_err(|e| invalid(&e.to_string()))?; + if bytes.len() > CONTROL_LIMIT { + // Preserve machine identity and location even when rich init detail is too large. + fault = json!({"kind":fault["kind"],"pc":fault["pc"],"summary":fault["summary"], + "trap":fault["trap"],"message":fault["message"], + "initError":{"code":fault["initError"]["code"],"detailsOmitted":true}}); + // JSON escaping can expand a UTF-8 byte sixfold; reserve space for that too. + bound_strings(&mut fault, 2048); + truncated = true; + bytes = serde_json::to_vec(&envelope(&fault, truncated)) + .map_err(|e| invalid(&e.to_string()))?; + } + if bytes.len() > CONTROL_LIMIT { + return Err(invalid("Studio fault exceeds control limit")); + } + Ok(bytes) +} + +pub(super) fn host_payload(kind: &str, message: &str, session: &[u8; 16], tick: u64) -> Vec { + let mut fault = json!({"kind": kind, "summary": message, "pc": null}); + // A single string with worst-case JSON escaping still fits the control budget. + let truncated = bound_strings(&mut fault, 8192); + serde_json::to_vec(&json!({"schemaVersion":1,"sessionId":hex(session),"programSha256":null, + "tick":tick,"truncated":truncated,"fault":fault})) + .expect("serializable diagnostic") +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn unicode_is_bounded_and_machine_location_is_preserved() { + let report = CrashReport::VmPanic { message: "😀".repeat(20_000), pc: Some(42) }; + let bytes = payload(&report, &[1; 16], Some([2; 32]), 7).unwrap(); + assert!(bytes.len() <= CONTROL_LIMIT); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["fault"]["pc"], 42); + assert_eq!(value["truncated"], true); + assert_eq!(value["programSha256"], "02".repeat(32)); + assert_eq!(value["fault"]["message"].as_str().unwrap().len(), 8192); + } + + #[test] + fn escaped_text_also_fits_the_wire_budget() { + let report = CrashReport::VmPanic { message: "\u{1}".repeat(30_000), pc: None }; + let bytes = payload(&report, &[1; 16], None, u64::MAX).unwrap(); + assert!(bytes.len() <= CONTROL_LIMIT); + let value: Value = serde_json::from_slice(&bytes).unwrap(); + assert!(value["fault"]["pc"].is_null()); + assert!(value["programSha256"].is_null()); + assert_eq!(value["truncated"], true); + } +} diff --git a/crates/host/prometeu-host-desktop-winit/src/studio/mod.rs b/crates/host/prometeu-host-desktop-winit/src/studio/mod.rs index 20b548b..e8a7cb2 100644 --- a/crates/host/prometeu-host-desktop-winit/src/studio/mod.rs +++ b/crates/host/prometeu-host-desktop-winit/src/studio/mod.rs @@ -1,4 +1,5 @@ //! Interactive Play integration, separate from the automation host. +mod diagnostic; pub(crate) mod platform; mod transport; pub mod wire; @@ -70,6 +71,7 @@ fn input(p: &[u8], width: usize, height: usize) -> io::Result<(u64, InputSignals pub(crate) fn run(mut runner: HostRunner, boot: Bootstrap) -> io::Result<()> { let transport = Transport::connect(&boot)?; + runner.studio_start_background_io(); runner.studio_audio_init(); let (width, height) = runner.studio_dimensions(); frame_bytes(width as u32, height as u32, width as u32)?; @@ -85,12 +87,15 @@ pub(crate) fn run(mut runner: HostRunner, boot: Bootstrap) -> io::Result<()> { ); let mut last_request = 0; let mut last_frame = None; + let mut error_kind = "host"; let outcome = (|| -> io::Result<()> { loop { if let Some(error) = transport.failure() { + error_kind = "transport"; return Err(invalid(&error)); } if ready && transport.idle() > Duration::from_secs(5) { + error_kind = "watchdog"; return Err(invalid("Studio control heartbeat expired")); } for _ in 0..64 { @@ -221,10 +226,22 @@ pub(crate) fn run(mut runner: HostRunner, boot: Bootstrap) -> io::Result<()> { } if !ready { if Instant::now() > boot_deadline { + error_kind = "watchdog"; return Err(invalid("Studio cartridge boot timed out")); } - ready = runner.studio_boot_step(boot.disposable).map_err(|e| invalid(&e))?; + ready = runner.studio_boot_step(boot.disposable).map_err(|e| { + error_kind = "load"; + invalid(&e) + })?; if ready { + let digest = runner + .studio_program_sha256() + .ok_or_else(|| invalid("Studio loaded program identity unavailable"))?; + if digest != boot.program_sha256 { + return Err(invalid( + "Studio loaded program identity differs from prepared compilation", + )); + } runner.studio_pause(true); let mut p = Vec::new(); for n in [ @@ -235,6 +252,7 @@ pub(crate) fn run(mut runner: HostRunner, boot: Bootstrap) -> io::Result<()> { ] { p.extend_from_slice(&n.to_le_bytes()); } + p.extend_from_slice(&digest); p.extend_from_slice(env!("CARGO_PKG_VERSION").as_bytes()); transport.send(READY, 0, p)?; } @@ -255,7 +273,24 @@ pub(crate) fn run(mut runner: HostRunner, boot: Bootstrap) -> io::Result<()> { })(); if let Err(error) = &outcome { eprintln!("[Studio] {error}"); - let _ = transport.send(ERROR, 0, error.to_string().into_bytes()); + let digest = runner.studio_program_sha256(); + if let Some(report) = runner.studio_crash_report() + && digest.is_none_or(|value| value == boot.program_sha256) + { + if let Ok(payload) = + diagnostic::payload(&report, &boot.session, digest, runner.studio_tick_index()) + { + let _ = transport.send_flushed(FAULT, 0, payload); + } + } else { + let payload = diagnostic::host_payload( + error_kind, + &error.to_string(), + &boot.session, + runner.studio_tick_index(), + ); + let _ = transport.send_flushed(ERROR, 0, payload); + } runner.studio_abort(); } outcome diff --git a/crates/host/prometeu-host-desktop-winit/src/studio/transport.rs b/crates/host/prometeu-host-desktop-winit/src/studio/transport.rs index 54f93de..296f946 100644 --- a/crates/host/prometeu-host-desktop-winit/src/studio/transport.rs +++ b/crates/host/prometeu-host-desktop-winit/src/studio/transport.rs @@ -225,9 +225,13 @@ impl Transport { .map_err(|_| invalid("Studio output queue unavailable")) } pub fn finish(&self, request: u64) -> io::Result<()> { + self.send_flushed(STOPPED, request, Vec::new()) + } + /// Observe terminal diagnostic delivery before abort closes the channels. + pub fn send_flushed(&self, kind: u16, request: u64, payload: Vec) -> io::Result<()> { let (tx, rx) = mpsc::sync_channel(1); self.outgoing - .try_send(Outbound { kind: STOPPED, request, payload: Vec::new(), flushed: Some(tx) }) + .try_send(Outbound { kind, request, payload, flushed: Some(tx) }) .map_err(|_| invalid("Studio output queue unavailable"))?; rx.recv_timeout(Duration::from_secs(2)) .map_err(|_| invalid("Studio shutdown acknowledgement failed")) diff --git a/crates/host/prometeu-host-desktop-winit/src/studio/wire.rs b/crates/host/prometeu-host-desktop-winit/src/studio/wire.rs index 52b5acf..2ec27dc 100644 --- a/crates/host/prometeu-host-desktop-winit/src/studio/wire.rs +++ b/crates/host/prometeu-host-desktop-winit/src/studio/wire.rs @@ -19,6 +19,7 @@ pub const PONG: u16 = 12; pub const ERROR: u16 = 13; pub const STOPPED: u16 = 14; pub const BOOTSTRAP: u16 = 15; +pub const FAULT: u16 = 16; pub const RGBA8: u32 = 1; pub fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) @@ -33,7 +34,7 @@ pub struct Header { } impl Header { fn validate(self) -> io::Result<()> { - if !(HELLO..=BOOTSTRAP).contains(&self.kind) || self.sequence == 0 { + if !(HELLO..=FAULT).contains(&self.kind) || self.sequence == 0 { return Err(invalid("invalid Studio message type/sequence")); } if self.length > if self.kind == FRAME { FRAME_LIMIT } else { CONTROL_LIMIT } { @@ -45,7 +46,7 @@ impl Header { self.validate()?; let mut b = [0; HEADER_BYTES]; b[..4].copy_from_slice(b"PST1"); - b[4..6].copy_from_slice(&1u16.to_le_bytes()); + b[4..6].copy_from_slice(&2u16.to_le_bytes()); b[8..10].copy_from_slice(&self.kind.to_le_bytes()); b[12..16].copy_from_slice(&(self.length as u32).to_le_bytes()); b[16..24].copy_from_slice(&self.sequence.to_le_bytes()); @@ -53,8 +54,10 @@ impl Header { Ok(b) } pub fn decode(b: &[u8; HEADER_BYTES]) -> io::Result { - if &b[..4] != b"PST1" || b[4..8] != [1, 0, 0, 0] || b[10..12] != [0, 0] { - return Err(invalid("invalid Studio magic/version/flags")); + if &b[..4] != b"PST1" || b[4..8] != [2, 0, 0, 0] || b[10..12] != [0, 0] { + return Err(invalid( + "incompatible Studio Play protocol: required 2.0, or invalid magic/flags", + )); } let h = Self { kind: u16::from_le_bytes(b[8..10].try_into().unwrap()), @@ -126,12 +129,13 @@ pub struct Bootstrap { pub control_port: u16, pub video_port: u16, pub disposable: bool, + pub program_sha256: [u8; 32], } impl Bootstrap { pub fn read(input: impl Read) -> io::Result { let m = Reader::new(input).receive()?; let p = &m.payload; - if m.header.kind != BOOTSTRAP || m.header.request != 0 || p.len() != 53 || p[52] > 1 { + if m.header.kind != BOOTSTRAP || m.header.request != 0 || p.len() != 85 || p[52] > 1 { return Err(invalid("invalid Studio bootstrap")); } let b = Self { @@ -140,6 +144,7 @@ impl Bootstrap { control_port: u16::from_le_bytes(p[48..50].try_into().unwrap()), video_port: u16::from_le_bytes(p[50..52].try_into().unwrap()), disposable: p[52] != 0, + program_sha256: p[53..85].try_into().unwrap(), }; if b.control_port == 0 || b.video_port == 0 || b.control_port == b.video_port { return Err(invalid("invalid Studio ports")); diff --git a/crates/host/prometeu-host-desktop-winit/tests/studio_process.rs b/crates/host/prometeu-host-desktop-winit/tests/studio_process.rs index 15ab2a2..c1a702d 100644 --- a/crates/host/prometeu-host-desktop-winit/tests/studio_process.rs +++ b/crates/host/prometeu-host-desktop-winit/tests/studio_process.rs @@ -1,5 +1,6 @@ //! Real process qualification: no window, slow consumer, pause and broken IPC. use prometeu_host_desktop_winit::studio::wire::*; +use sha2::{Digest, Sha256}; use std::io::{self, BufRead, Write}; use std::net::{Shutdown, TcpListener, TcpStream}; use std::process::{Child, Command, ExitStatus, Stdio}; @@ -21,6 +22,8 @@ impl Session { let video = TcpListener::bind("127.0.0.1:0").unwrap(); let cart = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../../test-cartridges/dummy-boy"); + let program_sha256: [u8; 32] = + Sha256::digest(std::fs::read(cart.join("program.pbx")).unwrap()).into(); let child = Command::new(env!("CARGO_BIN_EXE_prometeu-host-desktop-winit")) .args(["--studio", "--run"]) .arg(cart) @@ -51,6 +54,7 @@ impl Session { p.extend_from_slice(&control.local_addr().unwrap().port().to_le_bytes()); p.extend_from_slice(&video.local_addr().unwrap().port().to_le_bytes()); p.push(1); + p.extend_from_slice(&program_sha256); Writer::new(session_child.stdin.take().unwrap()).send(BOOTSTRAP, 0, &p).unwrap(); fn accept(listener: TcpListener) -> TcpStream { listener.set_nonblocking(true).unwrap(); @@ -92,7 +96,9 @@ impl Session { }; let ready = session.control.receive().unwrap(); assert_eq!(ready.header.kind, READY, "{:?}", session.logs.lock().unwrap()); + assert!(ready.payload.len() >= 48); assert_eq!(u32::from_le_bytes(ready.payload[..4].try_into().unwrap()), 640); + assert_eq!(&ready.payload[16..48], &program_sha256); session } fn command(&mut self, kind: u16, request: u64) -> Message { diff --git a/crates/host/prometeu-host-desktop-winit/tests/studio_protocol.rs b/crates/host/prometeu-host-desktop-winit/tests/studio_protocol.rs index f5cc158..f53f0b0 100644 --- a/crates/host/prometeu-host-desktop-winit/tests/studio_protocol.rs +++ b/crates/host/prometeu-host-desktop-winit/tests/studio_protocol.rs @@ -22,17 +22,35 @@ fn rgba_fixture_pins_channel_order_and_metadata() { #[test] fn bootstrap_rejects_wrong_roles_lengths_and_ports() { - let mut p = vec![0; 53]; + let mut p = vec![0; 85]; p[48..50].copy_from_slice(&1234u16.to_le_bytes()); p[50..52].copy_from_slice(&1235u16.to_le_bytes()); p[52] = 1; + p[53..85].fill(0xab); let mut bytes = Vec::new(); Writer::new(&mut bytes).send(BOOTSTRAP, 0, &p).unwrap(); let boot = Bootstrap::read(bytes.as_slice()).unwrap(); assert!(boot.disposable); + assert_eq!(boot.program_sha256, [0xab; 32]); assert_eq!(boot.hello(1).len(), 49); p[50..52].copy_from_slice(&1234u16.to_le_bytes()); bytes.clear(); Writer::new(&mut bytes).send(BOOTSTRAP, 0, &p).unwrap(); assert!(Bootstrap::read(bytes.as_slice()).is_err()); } + +#[test] +fn v2_fault_fixture_preserves_unsigned_pc_span_and_unicode() { + let hex = include_str!("../../../../devtools/studio-protocol/fixtures/fault.hex"); + let bytes: Vec<_> = + hex.split_whitespace().map(|s| u8::from_str_radix(s, 16).unwrap()).collect(); + let m = Reader::new(bytes.as_slice()).receive_control().unwrap(); + assert_eq!(m.header.kind, FAULT); + let value: serde_json::Value = serde_json::from_slice(&m.payload).unwrap(); + assert_eq!(value["fault"]["pc"], u32::MAX); + assert_eq!(value["fault"]["trap"]["span"]["file_id"], 7); + assert!(value["fault"]["summary"].as_str().unwrap().contains("ação")); + let mut old: [u8; 32] = bytes[..32].try_into().unwrap(); + old[4] = 1; + assert!(Header::decode(&old).unwrap_err().to_string().contains("required 2.0")); +} diff --git a/crates/host/prometeu-host-headless/src/automation/wire.rs b/crates/host/prometeu-host-headless/src/automation/wire.rs index 5521a71..60dd761 100644 --- a/crates/host/prometeu-host-headless/src/automation/wire.rs +++ b/crates/host/prometeu-host-headless/src/automation/wire.rs @@ -422,20 +422,7 @@ fn log_event(event: &prometeu_hal::log::LogEvent) -> Value { } pub(super) fn fault(report: &CrashReport) -> Value { - let mut result = json!({"kind":report.kind(),"pc":report.pc(),"summary":report.summary()}); - match report { - CrashReport::VmTrap { trap } => { - result["trap"] = json!({"code":trap.code,"opcode":trap.opcode, - "message":trap.message,"pc":trap.pc,"span":trap.span,"resource":trap.resource}); - } - CrashReport::VmPanic { message, .. } => { - result["message"] = json!(message); - } - CrashReport::VmInit { .. } => { - result["initError"] = report.init_diagnostic().expect("initialization report"); - } - } - result + report.diagnostic() } pub(super) fn capture(c: CapturedFrame) -> Result { diff --git a/devtools/studio-protocol/fixtures/fault.hex b/devtools/studio-protocol/fixtures/fault.hex new file mode 100644 index 0000000..e759773 --- /dev/null +++ b/devtools/studio-protocol/fixtures/fault.hex @@ -0,0 +1,27 @@ +50 53 54 31 02 00 00 00 10 00 00 00 82 01 00 00 +01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +7b 22 73 63 68 65 6d 61 56 65 72 73 69 6f 6e 22 +3a 31 2c 22 73 65 73 73 69 6f 6e 49 64 22 3a 22 +30 33 30 33 30 33 30 33 30 33 30 33 30 33 30 33 +30 33 30 33 30 33 30 33 30 33 30 33 30 33 30 33 +22 2c 22 70 72 6f 67 72 61 6d 53 68 61 32 35 36 +22 3a 22 61 62 61 62 61 62 61 62 61 62 61 62 61 +62 61 62 61 62 61 62 61 62 61 62 61 62 61 62 61 +62 61 62 61 62 61 62 61 62 61 62 61 62 61 62 61 +62 61 62 61 62 61 62 61 62 61 62 61 62 61 62 61 +62 61 62 22 2c 22 74 69 63 6b 22 3a 37 2c 22 74 +72 75 6e 63 61 74 65 64 22 3a 66 61 6c 73 65 2c +22 66 61 75 6c 74 22 3a 7b 22 6b 69 6e 64 22 3a +22 76 6d 5f 74 72 61 70 22 2c 22 70 63 22 3a 34 +32 39 34 39 36 37 32 39 35 2c 22 73 75 6d 6d 61 +72 79 22 3a 22 64 69 76 69 73 69 6f 6e 20 62 79 +20 7a 65 72 6f 20 e2 80 94 20 61 c3 a7 c3 a3 6f +22 2c 22 74 72 61 70 22 3a 7b 22 70 63 22 3a 34 +32 39 34 39 36 37 32 39 35 2c 22 63 6f 64 65 22 +3a 32 2c 22 6f 70 63 6f 64 65 22 3a 31 34 2c 22 +73 70 61 6e 22 3a 7b 22 66 69 6c 65 5f 69 64 22 +3a 37 2c 22 73 74 61 72 74 22 3a 31 38 2c 22 65 +6e 64 22 3a 32 33 7d 2c 22 6d 65 73 73 61 67 65 +22 3a 22 64 69 76 69 73 69 6f 6e 20 62 79 20 7a +65 72 6f 20 e2 80 94 20 61 c3 a7 c3 a3 6f 22 7d +7d 7d diff --git a/devtools/studio-protocol/fixtures/pause.hex b/devtools/studio-protocol/fixtures/pause.hex index 7e2bf24..3bc6323 100644 --- a/devtools/studio-protocol/fixtures/pause.hex +++ b/devtools/studio-protocol/fixtures/pause.hex @@ -1,2 +1 @@ -50 53 54 31 01 00 00 00 04 00 00 00 00 00 00 00 -01 00 00 00 00 00 00 00 2a 00 00 00 00 00 00 00 +50 53 54 31 02 00 00 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 2a 00 00 00 00 00 00 00 diff --git a/devtools/studio-protocol/fixtures/rgba.hex b/devtools/studio-protocol/fixtures/rgba.hex index d20ae4e..1820213 100644 --- a/devtools/studio-protocol/fixtures/rgba.hex +++ b/devtools/studio-protocol/fixtures/rgba.hex @@ -1,6 +1 @@ -50 53 54 31 01 00 00 00 09 00 00 00 38 00 00 00 -01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 -00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f -01 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 -02 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 -ff 00 00 ff 00 00 ff 80 +50 53 54 31 02 00 00 00 09 00 00 00 38 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 01 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 02 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 ff 00 00 ff 00 00 ff 80 diff --git a/docs/specs/runtime/11b-studio-play-protocol.md b/docs/specs/runtime/11b-studio-play-protocol.md index 8aa35c6..d1cbab9 100644 --- a/docs/specs/runtime/11b-studio-play-protocol.md +++ b/docs/specs/runtime/11b-studio-play-protocol.md @@ -1,16 +1,17 @@ -# Studio Play Protocol v1 +# Studio Play Protocol v2 This protocol belongs to the interactive desktop host. It does not extend or replace the deterministic headless automation protocol. The mode and Java adapter are -implemented and exercised on macOS ARM64 with a relocated installation of current -debug binaries. Protocol fixtures do not qualify other platforms or release builds. +implemented and exercised on macOS ARM64 with the qualified release umbrella +installation. Protocol fixtures alone do not qualify a binary or other platforms. The Studio starts `prometeu-runtime --studio --run ` directly. No native window/event loop is created in this mode. The parent listens on two ephemeral IPv4 loopback ports: control/input and video. Both connect/authenticate before readiness. The parent sends a BOOTSTRAP message through private child stdin and closes stdin. Bootstrap payload: session ID (16 bytes), random token (32 bytes), control/video ports -(u16 each), disposable-save selection (u8: 0 persistent, 1 explicitly disposable). +(u16 each), disposable-save selection (u8: 0 persistent, 1 explicitly disposable), +and expected PBX SHA-256 (32 raw bytes). The payload is exactly 85 bytes. Token material must not appear in arguments or logs. No reconnect or automatic restart. All integer fields use little-endian encoding. Messages have this 32-byte header: @@ -18,7 +19,7 @@ All integer fields use little-endian encoding. Messages have this 32-byte header | Offset | Type | Meaning | | --- | --- | --- | | 0 | 4 bytes | ASCII PST1 | -| 4 / 6 | u16 / u16 | major 1 / minor 0 | +| 4 / 6 | u16 / u16 | major 2 / minor 0 | | 8 / 10 | u16 / u16 | type / flags (zero) | | 12 | u32 | payload bytes, validated before allocation | | 16 | u64 | strictly increasing nonzero sequence per direction/channel | @@ -26,23 +27,88 @@ All integer fields use little-endian encoding. Messages have this 32-byte header Types: HELLO=1, READY=2, START=3, PAUSE=4, RESUME=5, STOP=6, RESULT=7, INPUT=8, FRAME=9, FRAME_RECEIVED=10, PING=11, PONG=12, ERROR=13, -STOPPED=14, BOOTSTRAP=15. Unknown types/flags/versions, invalid sizes, replay, +STOPPED=14, BOOTSTRAP=15, FAULT=16. Unknown types/flags/versions, invalid sizes, replay, invalid UTF-8 and truncated messages fail the connection. Control payload limit is 64 KiB; FRAME limit is 16 MiB including metadata. Overflow is rejected. | Message | Payload | | --- | --- | | HELLO | session[16], token[32], role u8 (control=1, video=2) | -| READY | width/height/fps/format u32; UTF-8 runtime version in remaining bytes | +| READY | width/height/fps/format u32; actual PBX SHA-256[32]; UTF-8 runtime version in remaining bytes | | START / PAUSE / RESUME / STOP / PING | empty; nonzero request ID for commands | | RESULT | command u16, status u16 (0 success, 1 invalid state, 2 save blocked), input epoch u64, tick u64, UTF-8 diagnostic remainder | | INPUT | input epoch u64, buttons u16, reserved u16=0, touch x/y i32 | | FRAME | session[16], input epoch u64, frame ID u64, width/height/stride/format u32, pixels | | FRAME_RECEIVED | input epoch u64, frame ID u64 | | PONG | input epoch u64, tick u64, state u32 (0 ready, 1 running, 2 paused) | -| ERROR | UTF-8 diagnostic | +| ERROR | bounded UTF-8 JSON host-error envelope, unsolicited request=0 | +| FAULT | bounded UTF-8 JSON VM-fault envelope, unsolicited request=0 | | STOPPED | empty; correlated with successful STOP | +## Program identity and diagnostics + +The host MUST hash the exact PBX bytes supplied to VM initialization, rather than +reopening the path or echoing the expected digest. READY MUST carry that actual +identity. The host MUST reject a mismatch before READY and Studio MUST compare +READY against the prepared compilation before START. The host retains the observed +identity after firmware removes a crashed VM session, for its final diagnostic. +Play v1 peers are incompatible; no silent downgrade is permitted. PBX, guest ABI, +save policy and the headless wire contract are unchanged. Existing exact native +bundle qualification and artifact guards remain required. + +Both terminal envelopes have this shape: + +```json +{ + "schemaVersion": 1, + "sessionId": "03030303030303030303030303030303", + "programSha256": "abababababababababababababababababababababababababababababababab", + "tick": 7, + "truncated": false, + "fault": { + "kind": "vm_trap", "pc": 42, "summary": "...", + "trap": { + "pc": 42, "code": 10, "opcode": 35, "message": "...", + "span": {"file_id": 7, "start": 18, "end": 23}, "resource": null + } + } +} +``` + +`programSha256` is a JSON string or null, never the literal text "null". `tick` is +an unsigned 64-bit integer. FAULT's `fault` is the canonical CrashReport projection +also used by headless: `vm_trap` includes unsigned 32-bit PC/code, unsigned 16-bit +opcode, message, nullable span and resource; `vm_panic` includes message and +nullable PC; `vm_init` includes `initError` and null PC. A span uses compilation-local +file ID and half-open UTF-8 byte offsets, all unsigned 32-bit fields. It is optional. A trap MUST carry a known +program digest; an initialization failure may have no confirmed digest. The +consumer rejects inconsistent top-level/trap PCs and mismatched session/program. + +ERROR uses the same envelope with `kind=load|host|transport|watchdog`, summary, +null PC and null program digest. It MUST NOT claim an executed source location. +Categories are producer facts, not parsed log text. Failures before authenticated +channels exist are reported locally by Studio as preparation/connection failures. + +Each diagnostic string is limited to 8 KiB UTF-8 at a character boundary. The whole +envelope MUST fit the 64 KiB control limit, including JSON escaping. Rich detail may +be omitted and strings shortened further to fit, with `truncated=true`; category, +numeric code, PC and span are preserved. Studio validates types, integer ranges, +UTF-8, identity, nesting (maximum 32) and size before publishing neutral values. + +Terminal messages are flushed with a bounded 2-second observation before channels +close. Studio drains terminal control after process exit or video EOF with a +bounded wait, and preserves the first structured failure as the primary cause. +Consequent EOF/teardown MUST NOT replace it with a generic connection diagnostic. +An unreachable peer cannot be promised delivery. Cleanup and ownership still wait +for actual process exit. No token or source text enters these envelopes. + +## Execution and presentation + +The host MUST start its background IO worker before potentially blocking platform +audio initialization. A memory-card mount admitted during host setup must be able +to progress before the first firmware/VM tick, under its existing deadlines. This +does not authorize advancing the guest before START or weakening save watchdogs. + Pixel format 1 is compact RGBA8: R,G,B,A bytes, stride equal to width. Never memcpy native u32 `0xRRGGBBAA` as wire pixels. FRAME metadata occupies 48 bytes; dimensions must match readiness and payload length exactly. Zoom is entirely a Studio concern.