feat(runtime): add optional pause and resume lifecycle hooks
Intrepid/Prometeu/Runtime/pipeline/pr-master Build started...
Intrepid/Prometeu/Runtime/pipeline/pr-master Build started...
This commit is contained in:
@@ -9,6 +9,7 @@ use crate::services::foreground::{
|
||||
ForegroundOwner, ForegroundStackError, ResidentGame, ResidentGameState,
|
||||
};
|
||||
use crate::task::{TaskId, TaskKind, TaskState};
|
||||
use crate::vm_session::LifecycleTransition;
|
||||
|
||||
pub struct LifecycleFacade<'a> {
|
||||
pub(in crate::os) os: &'a mut SystemOS,
|
||||
@@ -45,6 +46,27 @@ impl<'a> LifecycleFacade<'a> {
|
||||
});
|
||||
}
|
||||
|
||||
if self
|
||||
.os
|
||||
.vm_sessions
|
||||
.for_task(task_id)
|
||||
.is_some_and(|session| session.lifecycle_transition.is_some())
|
||||
{
|
||||
return Err(LifecycleError::InvalidTransition {
|
||||
task_id,
|
||||
from: self.task_state(task_id).unwrap_or(TaskState::Closed),
|
||||
operation: LifecycleOperation::SetForeground,
|
||||
});
|
||||
}
|
||||
if self.task_state(task_id) == Some(TaskState::Suspended)
|
||||
&& self.os.vm_sessions.for_task(task_id).is_some_and(|session| {
|
||||
session
|
||||
.vm
|
||||
.has_lifecycle_hook(prometeu_bytecode::registry::LifecycleRole::BeforeResume)
|
||||
})
|
||||
{
|
||||
return self.resume_task(task_id);
|
||||
}
|
||||
self.os.foreground_stack.set_game_foreground(task_id).map_err(map_foreground_error)?;
|
||||
self.os.task_manager.set_foreground(task_id);
|
||||
self.os.process_manager.mark_running(process_id);
|
||||
@@ -67,6 +89,9 @@ impl<'a> LifecycleFacade<'a> {
|
||||
&& game_task_id != task_id
|
||||
&& self.task_state(game_task_id) != Some(TaskState::Suspended)
|
||||
{
|
||||
if self.defer_pause(game_task_id, LifecycleTransition::PauseToShell(task_id))? {
|
||||
return Ok(());
|
||||
}
|
||||
let game_process_id = process_id_for_task(self.os, game_task_id)?;
|
||||
self.os.task_manager.mark_suspended(game_task_id);
|
||||
self.os.process_manager.mark_suspended(game_process_id);
|
||||
@@ -93,6 +118,19 @@ impl<'a> LifecycleFacade<'a> {
|
||||
|
||||
pub fn request_home_from_game(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||
let _process_id = process_id_for_task(self.os, task_id)?;
|
||||
if let Some(pending) =
|
||||
self.os.vm_sessions.for_task(task_id).and_then(|s| s.lifecycle_transition)
|
||||
{
|
||||
return if pending == LifecycleTransition::PauseToHub {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(LifecycleError::InvalidTransition {
|
||||
task_id,
|
||||
from: self.task_state(task_id).unwrap_or(TaskState::Closed),
|
||||
operation: LifecycleOperation::Suspend,
|
||||
})
|
||||
};
|
||||
}
|
||||
let previous = self.os.foreground_stack.resident_game();
|
||||
|
||||
self.os
|
||||
@@ -113,6 +151,13 @@ impl<'a> LifecycleFacade<'a> {
|
||||
}
|
||||
|
||||
pub fn advance_game_pause_budget(&mut self, task_id: TaskId) -> Result<bool, LifecycleError> {
|
||||
if self.os.foreground_stack.resident_game().is_some_and(|game| {
|
||||
game.task_id == task_id
|
||||
&& game.state == ResidentGameState::PauseRequested { remaining_ticks: 1 }
|
||||
}) && self.defer_pause(task_id, LifecycleTransition::PauseToHub)?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let expired =
|
||||
self.os.foreground_stack.advance_pause_budget(task_id).map_err(map_foreground_error)?;
|
||||
|
||||
@@ -125,6 +170,34 @@ impl<'a> LifecycleFacade<'a> {
|
||||
Ok(expired)
|
||||
}
|
||||
|
||||
fn defer_pause(
|
||||
&mut self,
|
||||
task_id: TaskId,
|
||||
transition: LifecycleTransition,
|
||||
) -> Result<bool, LifecycleError> {
|
||||
let state = self.task_state(task_id).unwrap_or(TaskState::Closed);
|
||||
let Some(session) = self.os.vm_sessions.for_task_mut(task_id) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if let Some(pending) = session.lifecycle_transition {
|
||||
return if pending == transition {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(LifecycleError::InvalidTransition {
|
||||
task_id,
|
||||
from: state,
|
||||
operation: LifecycleOperation::Suspend,
|
||||
})
|
||||
};
|
||||
}
|
||||
if session.pause_hook_complete || !session.vm.has_lifecycle_hook(transition.role()) {
|
||||
return Ok(false);
|
||||
}
|
||||
session.lifecycle_transition = Some(transition);
|
||||
session.lifecycle_started = false;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn pending_game_lifecycle_events(&self) -> &[GameLifecycleEvent] {
|
||||
&self.os.game_lifecycle_events
|
||||
}
|
||||
@@ -141,6 +214,11 @@ impl<'a> LifecycleFacade<'a> {
|
||||
pub fn suspend_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||
let process_id = process_id_for_task(self.os, task_id)?;
|
||||
|
||||
if task_kind_for_task(self.os, task_id)? == TaskKind::Game
|
||||
&& self.defer_pause(task_id, LifecycleTransition::PauseToHub)?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
self.os.task_manager.mark_suspended(task_id);
|
||||
self.os.process_manager.mark_suspended(process_id);
|
||||
match self.os.foreground_stack.owner() {
|
||||
@@ -189,6 +267,16 @@ impl<'a> LifecycleFacade<'a> {
|
||||
task_id,
|
||||
kind: GameLifecycleEventKind::ResumeForeground,
|
||||
});
|
||||
if let Some(session) = self.os.vm_sessions.for_task_mut(task_id) {
|
||||
session.pause_hook_complete = false;
|
||||
if session.vm.has_lifecycle_hook(
|
||||
prometeu_bytecode::registry::LifecycleRole::BeforeResume,
|
||||
) {
|
||||
session.lifecycle_transition = Some(LifecycleTransition::Resume);
|
||||
session.lifecycle_started = false;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
self.os
|
||||
.foreground_stack
|
||||
.complete_resume_game(task_id)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::CrashReport;
|
||||
use crate::os::{GameLifecycleEvent, SystemOS};
|
||||
use crate::task::TaskId;
|
||||
use crate::vm_session::VmSession;
|
||||
use crate::vm_session::{LifecycleTransition, VmSession};
|
||||
use crate::{RenderWorkerConfig, RenderWorkerController};
|
||||
use prometeu_hal::app_mode::AppMode;
|
||||
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
|
||||
@@ -9,6 +9,7 @@ use prometeu_hal::{
|
||||
FrameId, InputSignals, RenderOwnership, RenderWorkerBackend, RenderWorkerError,
|
||||
RenderWorkerFrameSink, RuntimePlatform,
|
||||
};
|
||||
use prometeu_vm::LogicalFrameEndingReason;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
pub struct VmFacade<'a> {
|
||||
@@ -22,6 +23,12 @@ impl<'a> VmFacade<'a> {
|
||||
signals: &InputSignals,
|
||||
platform: &mut dyn RuntimePlatform,
|
||||
) -> Option<CrashReport> {
|
||||
if self.os.lifecycle().task_state(task_id) != Some(crate::task::TaskState::Foreground) {
|
||||
return None;
|
||||
}
|
||||
if self.os.vm_sessions.for_task(task_id).is_some_and(|s| s.lifecycle_transition.is_some()) {
|
||||
return self.drive_lifecycle(task_id, platform, false).err();
|
||||
}
|
||||
self.deliver_pending_game_lifecycle_events_to_session(task_id);
|
||||
|
||||
let Some(session) = self.os.vm_sessions.for_task_mut(task_id) else {
|
||||
@@ -44,6 +51,104 @@ impl<'a> VmFacade<'a> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Firmware polls this before dispatching ordinary Game/Shell updates.
|
||||
pub fn poll_pending_lifecycle(
|
||||
&mut self,
|
||||
platform: &mut dyn RuntimePlatform,
|
||||
) -> Option<(TaskId, Result<(), CrashReport>)> {
|
||||
let task_id = self.os.foreground_stack.resident_game_task()?;
|
||||
self.os.vm_sessions.for_task(task_id)?.lifecycle_transition?;
|
||||
Some((task_id, self.drive_lifecycle(task_id, platform, false)))
|
||||
}
|
||||
|
||||
fn drive_lifecycle(
|
||||
&mut self,
|
||||
task_id: TaskId,
|
||||
platform: &mut dyn RuntimePlatform,
|
||||
single_step: bool,
|
||||
) -> Result<(), CrashReport> {
|
||||
self.deliver_pending_game_lifecycle_events_to_session(task_id);
|
||||
let session = self.os.vm_sessions.for_task_mut(task_id).expect("pending lifecycle session");
|
||||
let transition = session.lifecycle_transition.expect("pending lifecycle transition");
|
||||
let role = transition.role();
|
||||
// A fatal hook remains failed even if a caller tries to tick the same session again.
|
||||
if let Some(report) = &session.runtime.last_crash_report {
|
||||
return Err(report.clone());
|
||||
}
|
||||
let reason = if !session.lifecycle_started {
|
||||
session.lifecycle_started = true;
|
||||
match session.vm.begin_lifecycle(role) {
|
||||
Ok(true) => None,
|
||||
Ok(false) => Some(LogicalFrameEndingReason::LifecycleComplete),
|
||||
Err(error) => Some(LogicalFrameEndingReason::Panic(format!("{error:?}"))),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let reason = reason.unwrap_or_else(|| {
|
||||
session.runtime.tick_lifecycle(
|
||||
&mut self.os.log_service,
|
||||
&mut self.os.fs,
|
||||
&mut session.fs_state,
|
||||
&mut self.os.memcard,
|
||||
&mut session.open_files,
|
||||
&mut session.next_handle,
|
||||
&mut session.vm,
|
||||
platform,
|
||||
single_step,
|
||||
)
|
||||
});
|
||||
match reason {
|
||||
LogicalFrameEndingReason::BudgetExhausted | LogicalFrameEndingReason::Breakpoint => {
|
||||
Ok(())
|
||||
}
|
||||
LogicalFrameEndingReason::LifecycleComplete => {
|
||||
session.lifecycle_transition = None;
|
||||
session.lifecycle_started = false;
|
||||
match transition {
|
||||
LifecycleTransition::PauseToHub => {
|
||||
session.pause_hook_complete = true;
|
||||
self.os.lifecycle().suspend_task(task_id).expect("validated suspension");
|
||||
}
|
||||
LifecycleTransition::PauseToShell(shell) => {
|
||||
session.pause_hook_complete = true;
|
||||
self.os
|
||||
.lifecycle()
|
||||
.set_shell_foreground_task(shell)
|
||||
.expect("validated Shell transition");
|
||||
}
|
||||
LifecycleTransition::Resume => {
|
||||
self.os
|
||||
.foreground_stack
|
||||
.complete_resume_game(task_id)
|
||||
.expect("validated resume");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
LogicalFrameEndingReason::Halted => {
|
||||
// HALT ends the session; it must never restore or resume gameplay.
|
||||
session.lifecycle_transition = None;
|
||||
self.os.lifecycle().close_task(task_id).expect("validated task");
|
||||
Ok(())
|
||||
}
|
||||
failure => {
|
||||
let report = match failure {
|
||||
LogicalFrameEndingReason::Trap(mut trap) => {
|
||||
trap.message = format!("{role:?}: {}", trap.message);
|
||||
CrashReport::VmTrap { trap }
|
||||
}
|
||||
other => CrashReport::VmPanic {
|
||||
message: format!("{role:?} lifecycle failed: {other:?}"),
|
||||
pc: Some(session.vm.pc() as u32),
|
||||
},
|
||||
};
|
||||
session.runtime.last_crash_report = Some(report.clone());
|
||||
Err(report)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn deliver_pending_game_lifecycle_events_to_session(&mut self, task_id: TaskId) {
|
||||
let Some(session) = self.os.vm_sessions.for_task(task_id) else {
|
||||
return;
|
||||
@@ -85,6 +190,12 @@ impl<'a> VmFacade<'a> {
|
||||
pc: None,
|
||||
});
|
||||
};
|
||||
if self.os.lifecycle().task_state(task_id) != Some(crate::task::TaskState::Foreground) {
|
||||
return None;
|
||||
}
|
||||
if self.os.vm_sessions.for_task(task_id).is_some_and(|s| s.lifecycle_transition.is_some()) {
|
||||
return self.drive_lifecycle(task_id, platform, true).err();
|
||||
}
|
||||
let Some(session) = self.os.vm_sessions.for_task_mut(task_id) else {
|
||||
return Some(CrashReport::VmPanic {
|
||||
message: format!("active debug task {:?} has no VM session", task_id),
|
||||
|
||||
@@ -101,6 +101,7 @@ fn serialized_single_function_module_with_consts(
|
||||
TestProgram {
|
||||
const_pool,
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
|
||||
|
||||
@@ -105,7 +105,8 @@ impl VirtualMachineRuntime {
|
||||
match step_result {
|
||||
Ok(())
|
||||
| Err(
|
||||
LogicalFrameEndingReason::FrameSync
|
||||
LogicalFrameEndingReason::LifecycleComplete
|
||||
| LogicalFrameEndingReason::FrameSync
|
||||
| LogicalFrameEndingReason::BudgetExhausted
|
||||
| LogicalFrameEndingReason::Halted
|
||||
| LogicalFrameEndingReason::EndOfRom
|
||||
@@ -138,6 +139,55 @@ impl VirtualMachineRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses the session's real services, outside logical-frame accounting.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn tick_lifecycle(
|
||||
&mut self,
|
||||
log_service: &mut LogService,
|
||||
fs: &mut VirtualFS,
|
||||
fs_state: &mut FsState,
|
||||
memcard: &mut MemcardService,
|
||||
open_files: &mut HashMap<u32, String>,
|
||||
next_handle: &mut u32,
|
||||
vm: &mut VirtualMachine,
|
||||
platform: &mut dyn RuntimePlatform,
|
||||
single_step: bool,
|
||||
) -> LogicalFrameEndingReason {
|
||||
if self.paused && !single_step && !self.debug_step_request {
|
||||
return LogicalFrameEndingReason::Breakpoint;
|
||||
}
|
||||
let result = catch_unwind(AssertUnwindSafe(|| {
|
||||
let mut ctx = HostContext::new_platform(Some(platform));
|
||||
let mut host = VmRuntimeHost {
|
||||
runtime: self,
|
||||
log_service,
|
||||
fs,
|
||||
fs_state,
|
||||
memcard,
|
||||
open_files,
|
||||
next_handle,
|
||||
};
|
||||
if single_step {
|
||||
vm.step(&mut host, &mut ctx)
|
||||
.err()
|
||||
.unwrap_or(LogicalFrameEndingReason::BudgetExhausted)
|
||||
} else {
|
||||
vm.run_budget(VirtualMachine::LIFECYCLE_SLICE, &mut host, &mut ctx)
|
||||
.map(|report| report.reason)
|
||||
.unwrap_or_else(LogicalFrameEndingReason::Panic)
|
||||
}
|
||||
}));
|
||||
let reason = result.unwrap_or_else(|payload| {
|
||||
LogicalFrameEndingReason::Panic(Self::host_panic_payload_to_string(payload))
|
||||
});
|
||||
if reason == LogicalFrameEndingReason::Breakpoint || single_step || self.debug_step_request
|
||||
{
|
||||
self.paused = true;
|
||||
self.debug_step_request = false;
|
||||
}
|
||||
reason
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn tick(
|
||||
&mut self,
|
||||
|
||||
@@ -20,7 +20,27 @@ pub enum VmSessionError {
|
||||
ProcessIsNotVmBacked(ProcessId),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum LifecycleTransition {
|
||||
PauseToHub,
|
||||
PauseToShell(TaskId),
|
||||
Resume,
|
||||
}
|
||||
|
||||
impl LifecycleTransition {
|
||||
pub(crate) fn role(self) -> prometeu_bytecode::registry::LifecycleRole {
|
||||
use prometeu_bytecode::registry::LifecycleRole;
|
||||
match self {
|
||||
Self::Resume => LifecycleRole::BeforeResume,
|
||||
_ => LifecycleRole::BeforePause,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct VmSession {
|
||||
pub(crate) lifecycle_transition: Option<LifecycleTransition>,
|
||||
pub(crate) lifecycle_started: bool,
|
||||
pub(crate) pause_hook_complete: bool,
|
||||
pub id: VmSessionId,
|
||||
pub task_id: TaskId,
|
||||
pub process_id: ProcessId,
|
||||
@@ -45,6 +65,9 @@ impl VmSession {
|
||||
logs_count: Arc<AtomicU32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
lifecycle_transition: None,
|
||||
lifecycle_started: false,
|
||||
pause_hook_complete: false,
|
||||
id: VmSessionId(task.id),
|
||||
task_id: task.id,
|
||||
process_id: process.id,
|
||||
|
||||
Reference in New Issue
Block a user