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:
@@ -37,6 +37,9 @@ impl LoadCode {
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LoadReason {
|
||||
LifecycleRole,
|
||||
LifecycleSignature,
|
||||
DuplicateLifecycleRole,
|
||||
Magic,
|
||||
Version,
|
||||
Endianness,
|
||||
|
||||
@@ -57,8 +57,30 @@ pub struct TypeDecl {
|
||||
pub name: Option<String>,
|
||||
pub kind: TypeKind,
|
||||
}
|
||||
/// Runtime-owned roles; frontend names and FunctionIds are independent.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum LifecycleRole {
|
||||
#[default]
|
||||
None = 0,
|
||||
BeforePause = 1,
|
||||
BeforeResume = 2,
|
||||
}
|
||||
impl TryFrom<u8> for LifecycleRole {
|
||||
type Error = E;
|
||||
fn try_from(value: u8) -> Result<Self, E> {
|
||||
match value {
|
||||
0 => Ok(Self::None),
|
||||
1 => Ok(Self::BeforePause),
|
||||
2 => Ok(Self::BeforeResume),
|
||||
_ => Err(E::new(C::InvalidRegistry, R::LifecycleRole)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct FunctionDecl {
|
||||
pub lifecycle_role: LifecycleRole,
|
||||
pub name: Option<String>,
|
||||
pub signature: Signature,
|
||||
pub code_offset: u32,
|
||||
@@ -232,6 +254,7 @@ pub struct FunctionLayout {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Registry {
|
||||
lifecycle_hooks: [Option<FunctionId>; 2],
|
||||
declarations: RegistryDeclarations,
|
||||
layouts: Vec<TypeLayout>,
|
||||
functions: Vec<FunctionLayout>,
|
||||
@@ -239,6 +262,13 @@ pub struct Registry {
|
||||
implementations: Vec<(TypeId, TypeId, ImplementationId)>,
|
||||
}
|
||||
impl Registry {
|
||||
pub fn lifecycle_hook(&self, role: LifecycleRole) -> Option<FunctionId> {
|
||||
match role {
|
||||
LifecycleRole::None => None,
|
||||
LifecycleRole::BeforePause => self.lifecycle_hooks[0],
|
||||
LifecycleRole::BeforeResume => self.lifecycle_hooks[1],
|
||||
}
|
||||
}
|
||||
pub fn declarations(&self) -> &RegistryDeclarations {
|
||||
&self.declarations
|
||||
}
|
||||
@@ -346,10 +376,31 @@ impl Registry {
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut lifecycle_hooks = [None; 2];
|
||||
let mut functions = b.vector(d.functions.len(), Q::RegistryBytes)?;
|
||||
let mut ranges = b.vector(d.functions.len(), Q::TemporaryBytes)?;
|
||||
for (i, f) in d.functions.iter().enumerate() {
|
||||
b.work(1)?;
|
||||
if f.lifecycle_role != LifecycleRole::None {
|
||||
let invalid = i == 0
|
||||
|| !f.signature.parameters.is_empty()
|
||||
|| !f.signature.results.is_empty()
|
||||
|| !f.captures.is_empty();
|
||||
if invalid {
|
||||
return Err(E::new(C::InvalidEntrypoint, R::LifecycleSignature)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, None));
|
||||
}
|
||||
let slot = &mut lifecycle_hooks[f.lifecycle_role as usize - 1];
|
||||
if slot.replace(FunctionId(i as u32)).is_some() {
|
||||
return Err(E::new(C::InvalidRegistry, R::DuplicateLifecycleRole)
|
||||
.in_section(1)
|
||||
.record(i as u32)
|
||||
.in_function(i as u32, None));
|
||||
}
|
||||
}
|
||||
|
||||
let params = width(f.signature.parameters.iter().map(|p| p.type_id), &layouts, b)?;
|
||||
let results = width(f.signature.results.iter().copied(), &layouts, b)?;
|
||||
let frame = u64::from(params) + u64::from(f.local_slots) + u64::from(f.max_stack_slots);
|
||||
@@ -459,7 +510,7 @@ impl Registry {
|
||||
.record(pair[1].2 .0));
|
||||
}
|
||||
}
|
||||
Ok(Self { declarations: d, layouts, functions, implementations })
|
||||
Ok(Self { lifecycle_hooks, declarations: d, layouts, functions, implementations })
|
||||
}
|
||||
}
|
||||
fn overflow() -> E {
|
||||
|
||||
@@ -249,11 +249,14 @@ impl<'a, 'b> Reader<'a, 'b> {
|
||||
Ok(out)
|
||||
}
|
||||
fn functions(mut self) -> Result<Vec<FunctionDecl>, E> {
|
||||
let (mut out, n) = self.list(Q::Functions, 25)?;
|
||||
let (mut out, n) = self.list(Q::Functions, 26)?;
|
||||
for i in 0..n {
|
||||
self.budget.work(1)?;
|
||||
let f = (|| {
|
||||
Ok(FunctionDecl {
|
||||
lifecycle_role: LifecycleRole::try_from(self.byte()?).map_err(|e| {
|
||||
e.at(1, self.section.offset + self.pos - 1).in_function(i as u32, None)
|
||||
})?,
|
||||
name: self.name()?,
|
||||
signature: self.signature()?,
|
||||
code_offset: self.u32()?,
|
||||
@@ -407,6 +410,7 @@ pub fn encode_registry(registry: &Registry, b: &mut LoadBudget) -> Result<Regist
|
||||
let functions = write_section(b, |w| {
|
||||
w.count(d.functions.len())?;
|
||||
for f in &d.functions {
|
||||
w.byte(f.lifecycle_role as u8)?;
|
||||
w.name(&f.name)?;
|
||||
w.signature(&f.signature)?;
|
||||
w.u32(f.code_offset)?;
|
||||
|
||||
@@ -129,6 +129,7 @@ fn captures_section_has_independent_bytes_and_strict_shape() {
|
||||
let r = resolve(RegistryDeclarations {
|
||||
types: vec![builtin(BuiltinId::INT32), builtin(BuiltinId::VEC2)],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: 2,
|
||||
captures: vec![TypeId(1), TypeId(0)],
|
||||
..Default::default()
|
||||
@@ -167,22 +168,22 @@ fn hex(s: &str) -> Vec<u8> {
|
||||
|
||||
// Independently specified PBX, not generated by any production serializer.
|
||||
// Header 32 bytes, eight directory entries (96 bytes), payload starts at 128.
|
||||
// constants=128/4, functions=132/29, code=161/2, exports=163/4,
|
||||
// syscalls=167/4, types=171/10, implementations=181/4. Total=193.
|
||||
// constants=128/4, functions=132/30, code=162/2, exports=164/4,
|
||||
// syscalls=168/4, types=172/10, implementations=182/4, captures=186/8. Total=194.
|
||||
fn minimal_bytes() -> Vec<u8> {
|
||||
hex("
|
||||
50 42 58 00 01 00 00 00 08 00 00 00
|
||||
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
00 00 00 00 80 00 00 00 04 00 00 00
|
||||
01 00 00 00 84 00 00 00 1d 00 00 00
|
||||
02 00 00 00 a1 00 00 00 02 00 00 00
|
||||
04 00 00 00 a3 00 00 00 04 00 00 00
|
||||
05 00 00 00 a7 00 00 00 04 00 00 00
|
||||
06 00 00 00 ab 00 00 00 0a 00 00 00
|
||||
07 00 00 00 b5 00 00 00 04 00 00 00
|
||||
08 00 00 00 b9 00 00 00 08 00 00 00
|
||||
01 00 00 00 84 00 00 00 1e 00 00 00
|
||||
02 00 00 00 a2 00 00 00 02 00 00 00
|
||||
04 00 00 00 a4 00 00 00 04 00 00 00
|
||||
05 00 00 00 a8 00 00 00 04 00 00 00
|
||||
06 00 00 00 ac 00 00 00 0a 00 00 00
|
||||
07 00 00 00 b6 00 00 00 04 00 00 00
|
||||
08 00 00 00 ba 00 00 00 08 00 00 00
|
||||
00 00 00 00
|
||||
01 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
01 00 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00
|
||||
01 00
|
||||
00 00 00 00
|
||||
@@ -194,7 +195,11 @@ fn minimal_bytes() -> Vec<u8> {
|
||||
fn minimal_registry() -> Registry {
|
||||
resolve(RegistryDeclarations {
|
||||
types: vec![builtin(BuiltinId::BOOL)],
|
||||
functions: vec![FunctionDecl { code_len: 2, ..Default::default() }],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: 2,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap()
|
||||
@@ -225,10 +230,10 @@ fn writer_matches_independent_minimal_envelope() {
|
||||
let sections = encode_registry(&minimal_registry(), &mut budget()).unwrap();
|
||||
let bytes = envelope(§ions.types, §ions.functions, §ions.implementations);
|
||||
assert_eq!(bytes, minimal_bytes());
|
||||
assert_eq!(bytes.len(), 193);
|
||||
assert_eq!(bytes.len(), 194);
|
||||
let mut b = budget();
|
||||
let env = PbxEnvelope::parse(&bytes, &mut b).unwrap();
|
||||
assert_eq!(env.section(2).unwrap().offset, 161);
|
||||
assert_eq!(env.section(2).unwrap().offset, 162);
|
||||
let registry = env.resolve_registry(&mut b).unwrap();
|
||||
assert_eq!(registry.declarations(), minimal_registry().declarations());
|
||||
assert_eq!(b.used(LoadResource::TemporaryBytes), 0);
|
||||
@@ -499,7 +504,7 @@ fn representative_records_match_fixed_bytes_and_preserve_names_without_debug() {
|
||||
01 00 00 00 00 00 00 00 01 01 00 00 00 70
|
||||
01 00 00 00 00 00 00 00");
|
||||
let functions = hex("
|
||||
01 00 00 00 01 01 00 00 00 66
|
||||
01 00 00 00 00 01 01 00 00 00 66
|
||||
02 00 00 00 01 00 00 00 00 00 00 00 00 01 01 00 00 00 70
|
||||
01 00 00 00 00 00 00 00
|
||||
00 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00");
|
||||
@@ -721,6 +726,7 @@ fn implemented() -> RegistryDeclarations {
|
||||
},
|
||||
],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
signature: Signature { parameters: vec![named(1), named(0)], results: vec![TypeId(0)] },
|
||||
code_len: 2,
|
||||
max_stack_slots: 2,
|
||||
@@ -1024,7 +1030,7 @@ fn reference_map_probe() {
|
||||
fn independent_multi_slot_signature_fixture_has_no_serialized_widths() {
|
||||
// vec2 import; fn(vec2)->vec2; GET_LOCAL 0; GET_LOCAL 1; RET.
|
||||
let types = hex("01 00 00 00 00 00 02 00 00 00");
|
||||
let functions=hex("01 00 00 00 00 01 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 0e 00 00 00 00 00 00 00 02 00 00 00");
|
||||
let functions=hex("01 00 00 00 00 00 01 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 0e 00 00 00 00 00 00 00 02 00 00 00");
|
||||
let code = hex("42 00 00 00 00 00 42 00 01 00 00 00 51 00");
|
||||
let empty = [0; 4];
|
||||
let bytes = encode_envelope(
|
||||
@@ -1055,3 +1061,70 @@ fn independent_multi_slot_signature_fixture_has_no_serialized_widths() {
|
||||
assert_eq!(sections.functions, functions);
|
||||
assert_eq!(sections.types, types);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_roles_resolve_and_roundtrip_with_strict_validation() {
|
||||
let functions = vec![
|
||||
FunctionDecl { code_len: 2, ..Default::default() },
|
||||
FunctionDecl {
|
||||
lifecycle_role: LifecycleRole::BeforePause,
|
||||
code_offset: 2,
|
||||
code_len: 2,
|
||||
..Default::default()
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: LifecycleRole::BeforeResume,
|
||||
code_offset: 4,
|
||||
code_len: 2,
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let declarations = RegistryDeclarations {
|
||||
types: vec![builtin(BuiltinId::BOOL)],
|
||||
functions,
|
||||
..Default::default()
|
||||
};
|
||||
let registry = resolve(declarations.clone()).unwrap();
|
||||
assert_eq!(registry.lifecycle_hook(LifecycleRole::None), None);
|
||||
assert_eq!(registry.lifecycle_hook(LifecycleRole::BeforePause), Some(FunctionId(1)));
|
||||
assert_eq!(registry.lifecycle_hook(LifecycleRole::BeforeResume), Some(FunctionId(2)));
|
||||
let bytes = PbxModule {
|
||||
registry: ®istry,
|
||||
code: &[1, 0, 1, 0, 1, 0],
|
||||
constants: &[],
|
||||
debug: None,
|
||||
exports: &[],
|
||||
syscalls: &[],
|
||||
}
|
||||
.serialize(&mut budget())
|
||||
.unwrap();
|
||||
let parsed = OwnedPbx::parse(&bytes, &mut budget()).unwrap();
|
||||
assert_eq!(parsed.registry.declarations(), &declarations);
|
||||
let env = PbxEnvelope::parse(&bytes, &mut budget()).unwrap();
|
||||
let role_offset = env.section(1).unwrap().offset + 4;
|
||||
let mut invalid = bytes.clone();
|
||||
invalid[role_offset] = 255;
|
||||
let error = OwnedPbx::parse(&invalid, &mut budget()).unwrap_err();
|
||||
assert_eq!(error.reason, LoadReason::LifecycleRole);
|
||||
assert_eq!(error.function, Some(0));
|
||||
assert_eq!(error.offset, Some(role_offset));
|
||||
for case in 0..5 {
|
||||
let mut d = declarations.clone();
|
||||
match case {
|
||||
0 => d.functions[0].lifecycle_role = LifecycleRole::BeforePause,
|
||||
1 => d.functions[2].lifecycle_role = LifecycleRole::BeforePause,
|
||||
2 => d.functions[1].signature.parameters.push(named(0)),
|
||||
3 => d.functions[1].signature.results.push(TypeId(0)),
|
||||
_ => d.functions[1].captures.push(TypeId(0)),
|
||||
}
|
||||
let error = resolve(d).unwrap_err();
|
||||
assert_eq!(
|
||||
error.reason,
|
||||
if case == 1 {
|
||||
LoadReason::DuplicateLifecycleRole
|
||||
} else {
|
||||
LoadReason::LifecycleSignature
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,40 @@ impl Firmware {
|
||||
self.state_initialized = true;
|
||||
}
|
||||
|
||||
// Hooks run after leaving gameplay and before completing OS suspension/resume.
|
||||
if let Some((task_id, result)) = self.os.vm().poll_pending_lifecycle(platform) {
|
||||
if let Err(report) = result {
|
||||
let _ = self.os.lifecycle().crash_task(task_id, Some(&report));
|
||||
self.change_state(
|
||||
FirmwareState::AppCrashes(crate::firmware::firmware_state::AppCrashesStep {
|
||||
report,
|
||||
}),
|
||||
effective_signals,
|
||||
platform,
|
||||
);
|
||||
} else if matches!(self.state, FirmwareState::GameRunning(_))
|
||||
&& matches!(
|
||||
self.os.lifecycle().task_state(task_id),
|
||||
Some(
|
||||
prometeu_system::task::TaskState::Suspended
|
||||
| prometeu_system::task::TaskState::Closed
|
||||
)
|
||||
)
|
||||
{
|
||||
self.os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||
let state = match self.os.lifecycle().foreground_owner() {
|
||||
prometeu_system::ForegroundOwner::Shell(task_id) => {
|
||||
FirmwareState::ShellRunning(
|
||||
crate::firmware::firmware_state::ShellRunningStep::new(task_id),
|
||||
)
|
||||
}
|
||||
_ => FirmwareState::HubHome(crate::firmware::firmware_state::HubHomeStep),
|
||||
};
|
||||
self.change_state(state, effective_signals, platform);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Update the current state and check for transitions.
|
||||
if let Some(next_state) = self.on_update(effective_signals, platform) {
|
||||
self.change_state(next_state, effective_signals, platform);
|
||||
@@ -352,6 +386,7 @@ mod tests {
|
||||
TestProgram {
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
|
||||
@@ -392,6 +427,7 @@ mod tests {
|
||||
let program = TestProgram {
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
|
||||
@@ -1714,4 +1750,226 @@ mod tests {
|
||||
assert!(matches!(firmware.state, FirmwareState::GameRunning(_)));
|
||||
assert_eq!(firmware.os.vm().current_cartridge_title(), "Valid Cart");
|
||||
}
|
||||
fn lifecycle_cartridge(pause: &str, resume: &str) -> Cartridge {
|
||||
use prometeu_bytecode::registry::LifecycleRole;
|
||||
let mut program = TestProgram::single(
|
||||
assemble("FRAME_SYNC\nJMP 0").unwrap(),
|
||||
int64_signature(0, 0),
|
||||
0,
|
||||
8,
|
||||
);
|
||||
for (role, source) in
|
||||
[(LifecycleRole::BeforePause, pause), (LifecycleRole::BeforeResume, resume)]
|
||||
{
|
||||
if source.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let code = assemble(source).unwrap();
|
||||
program.functions.push(FunctionDecl {
|
||||
lifecycle_role: role,
|
||||
code_offset: program.code.len() as u32,
|
||||
code_len: code.len() as u32,
|
||||
max_stack_slots: 8,
|
||||
..Default::default()
|
||||
});
|
||||
program.code.extend(code);
|
||||
}
|
||||
let mut cartridge = valid_cartridge(AppMode::Game);
|
||||
cartridge.program = program.serialize();
|
||||
cartridge
|
||||
}
|
||||
|
||||
fn load_lifecycle(pause: &str, resume: &str) -> (Firmware, TestPlatform, TaskId) {
|
||||
let mut firmware = Firmware::new(None);
|
||||
let mut platform = TestPlatform::new();
|
||||
firmware.load_cartridge(lifecycle_cartridge(pause, resume));
|
||||
firmware.tick(&InputSignals::default(), &mut platform);
|
||||
let task = firmware.os.lifecycle().resident_game_task().unwrap();
|
||||
(firmware, platform, task)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_home_resume_callbacks_are_outside_frames_and_preserve_pc() {
|
||||
let (mut fw, mut platform, task) = load_lifecycle("RET", "RET");
|
||||
let signals = InputSignals::default();
|
||||
assert!(!fw.os.lifecycle().advance_game_pause_budget(task).unwrap());
|
||||
assert!(fw.os.vm().poll_pending_lifecycle(&mut platform).is_none());
|
||||
fw.request_home_from_host();
|
||||
fw.tick(&signals, &mut platform); // existing handoff tick
|
||||
let pc = fw.os.vm().active_pc();
|
||||
let ticks = vm_session_tick_index(&mut fw, task);
|
||||
let frames = fw.os.vm().completed_logical_frames();
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Foreground));
|
||||
fw.tick(&signals, &mut platform); // BeforePause only
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended));
|
||||
assert_eq!(fw.os.vm().active_pc(), pc);
|
||||
assert_eq!(vm_session_tick_index(&mut fw, task), ticks);
|
||||
assert!(fw.resume_resident_game_from_home());
|
||||
fw.tick(&signals, &mut platform); // BeforeResume only
|
||||
assert_eq!(fw.os.vm().active_pc(), pc);
|
||||
assert_eq!(vm_session_tick_index(&mut fw, task), ticks);
|
||||
assert_eq!(fw.os.vm().completed_logical_frames(), frames);
|
||||
assert_eq!(fw.os.lifecycle().resident_game().unwrap().state, ResidentGameState::Foreground);
|
||||
fw.tick(&signals, &mut platform);
|
||||
assert_eq!(vm_session_tick_index(&mut fw, task), ticks + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_direct_suspend_and_shell_handoff_wait_for_callback() {
|
||||
let (mut fw, mut platform, task) = load_lifecycle("RET", "RET");
|
||||
fw.os.lifecycle().suspend_task(task).unwrap();
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Foreground));
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended));
|
||||
assert!(fw.resume_resident_game_from_home());
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
let shell = fw.os.sessions().try_create_native_shell_task(99, "Tools").unwrap();
|
||||
assert_eq!(fw.os.lifecycle().foreground_owner(), ForegroundOwner::Game(task));
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert_eq!(fw.os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_debugger_retains_budget_and_steps_without_game_frames() {
|
||||
let (mut fw, mut platform, task) = load_lifecycle("PUSH_I32 7\nSET_GLOBAL 0\nRET", "RET");
|
||||
fw.os.lifecycle().suspend_task(task).unwrap();
|
||||
let offset = assemble("FRAME_SYNC\nJMP 0").unwrap().len();
|
||||
fw.os.vm().insert_active_breakpoint(offset);
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert!(fw.os.vm().paused());
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Foreground));
|
||||
let remaining =
|
||||
fw.os.sessions().vm_session_for_task(task).unwrap().vm.lifecycle_remaining_cycles();
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert_eq!(
|
||||
fw.os.sessions().vm_session_for_task(task).unwrap().vm.lifecycle_remaining_cycles(),
|
||||
remaining
|
||||
);
|
||||
for _ in 0..3 {
|
||||
assert!(fw.os.vm().debug_step_active_session(&mut platform).is_none());
|
||||
}
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended));
|
||||
assert_eq!(vm_session_tick_index(&mut fw, task), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_faults_exhaustion_and_halt_never_resume_gameplay() {
|
||||
for body in ["FRAME_SYNC\nRET", "JMP 0", "HALT"] {
|
||||
let (mut fw, mut platform, task) = load_lifecycle(body, "RET");
|
||||
fw.os.lifecycle().suspend_task(task).unwrap();
|
||||
for _ in 0..8 {
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
if fw.os.lifecycle().task_state(task) != Some(TaskState::Foreground) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if body == "HALT" {
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Closed));
|
||||
assert!(matches!(fw.state, FirmwareState::HubHome(_)));
|
||||
} else {
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Crashed));
|
||||
let FirmwareState::AppCrashes(step) = &fw.state else { panic!("expected crash") };
|
||||
assert!(step.report.to_string().contains("BeforePause"));
|
||||
}
|
||||
assert_eq!(vm_session_tick_index(&mut fw, task), 0);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn lifecycle_debugger_hostcalls_use_real_session_handles() {
|
||||
use prometeu_bytecode::registry::LifecycleRole;
|
||||
let main = assemble("FRAME_SYNC\nJMP 0").unwrap();
|
||||
let mut program = TestProgram::single(main, int64_signature(0, 0), 0, 8);
|
||||
let hook =
|
||||
assemble("PUSH_CONST 0\nHOSTCALL 0\nPOP_N 1\nPUSH_I32 42\nHOSTCALL 1\nRET").unwrap();
|
||||
program
|
||||
.const_pool
|
||||
.push(prometeu_bytecode::model::ConstantPoolEntry::String("/missing".into()));
|
||||
program.syscalls.push(SyscallDecl {
|
||||
module: "fs".into(),
|
||||
name: "open".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 1,
|
||||
});
|
||||
program.functions.push(FunctionDecl {
|
||||
lifecycle_role: LifecycleRole::BeforePause,
|
||||
code_offset: program.code.len() as u32,
|
||||
code_len: hook.len() as u32,
|
||||
max_stack_slots: 8,
|
||||
..Default::default()
|
||||
});
|
||||
program.code.extend(hook);
|
||||
program.syscalls.push(SyscallDecl {
|
||||
module: "fs".into(),
|
||||
name: "close".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
});
|
||||
let mut cartridge = valid_cartridge(AppMode::Game);
|
||||
cartridge.capabilities = caps::FS;
|
||||
cartridge.program = program.serialize();
|
||||
let mut fw = Firmware::new(None);
|
||||
let mut platform = TestPlatform::new();
|
||||
fw.load_cartridge(cartridge);
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
let task = fw.os.lifecycle().resident_game_task().unwrap();
|
||||
fw.os
|
||||
.sessions()
|
||||
.vm_session_for_task_mut(task)
|
||||
.unwrap()
|
||||
.open_files
|
||||
.insert(42, "/save".into());
|
||||
fw.os.lifecycle().suspend_task(task).unwrap();
|
||||
fw.os.vm().set_paused(true);
|
||||
assert_eq!(
|
||||
fw.os.sessions().vm_session_for_task(task).unwrap().fs_state,
|
||||
prometeu_system::fs::FsState::Unmounted
|
||||
);
|
||||
// fs.open returns an ordinary error value on this unmounted session.
|
||||
for _ in 0..6 {
|
||||
assert!(fw.os.vm().debug_step_active_session(&mut platform).is_none());
|
||||
}
|
||||
assert!(fw.os.sessions().vm_session_for_task(task).unwrap().open_files.is_empty());
|
||||
let pc = fw.os.vm().active_pc();
|
||||
assert!(fw.os.vm().debug_step_active_session(&mut platform).is_none());
|
||||
assert_eq!(fw.os.vm().active_pc(), pc);
|
||||
assert!(fw.os.vm().tick_session(task, &InputSignals::default(), &mut platform).is_none());
|
||||
assert_eq!(fw.os.vm().active_pc(), pc);
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert!(matches!(fw.state, FirmwareState::HubHome(_)));
|
||||
assert_eq!(vm_session_tick_index(&mut fw, task), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_resume_failure_blocks_gameplay_and_conflicting_pause_request() {
|
||||
let (mut fw, mut platform, task) = load_lifecycle("RET", "FRAME_SYNC\nRET");
|
||||
fw.os.lifecycle().suspend_task(task).unwrap();
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert!(fw.resume_resident_game_from_home());
|
||||
assert!(fw.os.lifecycle().request_home_from_game(task).is_err());
|
||||
assert!(fw.os.lifecycle().suspend_task(task).is_err());
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
let FirmwareState::AppCrashes(step) = &fw.state else { panic!("expected failure") };
|
||||
assert!(step.report.to_string().contains("BeforeResume"));
|
||||
assert_eq!(vm_session_tick_index(&mut fw, task), 0);
|
||||
}
|
||||
#[test]
|
||||
fn lifecycle_roles_are_independently_optional() {
|
||||
for (pause, resume) in [("", "RET"), ("RET", "")] {
|
||||
let (mut fw, mut platform, task) = load_lifecycle(pause, resume);
|
||||
fw.request_home_from_host();
|
||||
for _ in 0..2 {
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
}
|
||||
assert_eq!(fw.os.lifecycle().task_state(task), Some(TaskState::Suspended));
|
||||
assert!(fw.resume_resident_game_from_home());
|
||||
fw.tick(&InputSignals::default(), &mut platform);
|
||||
assert_eq!(
|
||||
fw.os.lifecycle().resident_game().unwrap().state,
|
||||
ResidentGameState::Foreground
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,15 @@ impl GameRunningStep {
|
||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||
};
|
||||
|
||||
if matches!(task_state, TaskState::Suspended | TaskState::Closed) {
|
||||
ctx.os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||
return Some(match ctx.os.lifecycle().foreground_owner() {
|
||||
prometeu_system::ForegroundOwner::Shell(task_id) => FirmwareState::ShellRunning(
|
||||
crate::firmware::firmware_state::ShellRunningStep::new(task_id),
|
||||
),
|
||||
_ => FirmwareState::HubHome(HubHomeStep),
|
||||
});
|
||||
}
|
||||
if task_state != TaskState::Foreground {
|
||||
// TODO: is it panic?
|
||||
let report = CrashReport::VmPanic {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -25,6 +25,7 @@ fn fixture(
|
||||
kind: TypeKind::Builtin(BuiltinId::BOOL),
|
||||
}],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
name: Some("boot".into()),
|
||||
code_len: code.len() as u32,
|
||||
max_stack_slots: max,
|
||||
|
||||
@@ -38,7 +38,12 @@ fn registry(code: &[u8], functions: Vec<FunctionDecl>) -> Registry {
|
||||
.unwrap()
|
||||
}
|
||||
fn function(code: &[u8]) -> FunctionDecl {
|
||||
FunctionDecl { code_len: code.len() as u32, max_stack_slots: 4, ..Default::default() }
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: code.len() as u32,
|
||||
max_stack_slots: 4,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
fn check(code: &[u8], registry: &Registry) -> Result<(), E> {
|
||||
validate_registry_instructions(code, registry, 1, &mut LoadBudget::new(Default::default()))
|
||||
@@ -53,7 +58,14 @@ fn stack_analysis_honors_literal_zero_and_wide_pop_operands() {
|
||||
let mut code = vec![];
|
||||
arg(&mut code, Op::PushI32, 0);
|
||||
op(&mut code, Op::Halt);
|
||||
let r = registry(&code, vec![FunctionDecl { max_stack_slots: 0, ..function(&code) }]);
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
max_stack_slots: 0,
|
||||
..function(&code)
|
||||
}],
|
||||
);
|
||||
let e = stacks(&code, &r).unwrap_err();
|
||||
assert_eq!(
|
||||
(e.reason, e.requested, e.limit, e.pc),
|
||||
@@ -78,6 +90,7 @@ fn stack_analysis_cannot_consume_parameters_or_extra_locals_as_temporaries() {
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
local_slots: 100,
|
||||
signature: Signature {
|
||||
parameters: vec![NamedType { type_id: TypeId(1), name: None }],
|
||||
@@ -112,8 +125,14 @@ fn stack_analysis_resolves_multislot_calls_and_registry_operations() {
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![
|
||||
FunctionDecl { code_len: callee as u32, max_stack_slots: 2, ..function(&code) },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: callee as u32,
|
||||
max_stack_slots: 2,
|
||||
..function(&code)
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: callee as u32,
|
||||
code_len: (code.len() - callee) as u32,
|
||||
signature,
|
||||
@@ -136,6 +155,7 @@ fn stack_analysis_checks_returns_empty_bodies_and_implicit_end_branches() {
|
||||
op(&mut code, operation);
|
||||
}
|
||||
let f = FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
signature: Signature { parameters: vec![], results: vec![TypeId(0)] },
|
||||
..function(&code)
|
||||
};
|
||||
@@ -172,7 +192,14 @@ fn stack_analysis_rejects_different_join_heights_and_accepts_a_bounded_loop() {
|
||||
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::StackJoin);
|
||||
let mut code = vec![];
|
||||
arg(&mut code, Op::Jmp, 0);
|
||||
let r = registry(&code, vec![FunctionDecl { max_stack_slots: 0, ..function(&code) }]);
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
max_stack_slots: 0,
|
||||
..function(&code)
|
||||
}],
|
||||
);
|
||||
assert!(stacks(&code, &r).is_ok());
|
||||
}
|
||||
|
||||
@@ -181,7 +208,14 @@ fn stack_analysis_accounts_only_reachable_transfers_but_preflights_dead_operands
|
||||
let mut code = vec![];
|
||||
op(&mut code, Op::Halt);
|
||||
arg(&mut code, Op::PopN, u32::MAX);
|
||||
let r = registry(&code, vec![FunctionDecl { max_stack_slots: 0, ..function(&code) }]);
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
max_stack_slots: 0,
|
||||
..function(&code)
|
||||
}],
|
||||
);
|
||||
assert!(stacks(&code, &r).is_ok());
|
||||
let mut code = vec![];
|
||||
op(&mut code, Op::Halt);
|
||||
@@ -220,7 +254,12 @@ fn stack_analysis_straight_line_storage_is_bounded_by_blocks_not_instruction_fra
|
||||
op(&mut code, Op::Halt);
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![FunctionDecl { local_slots: 300, max_stack_slots: 0, ..function(&code) }],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
local_slots: 300,
|
||||
max_stack_slots: 0,
|
||||
..function(&code)
|
||||
}],
|
||||
);
|
||||
let limits = LoadLimits { temporary_bytes: 41_000, ..Default::default() };
|
||||
let mut b = LoadBudget::new(limits);
|
||||
@@ -232,6 +271,7 @@ fn stack_analysis_straight_line_storage_is_bounded_by_blocks_not_instruction_fra
|
||||
fn stack_analysis_accepts_unknown_fn_targets_and_rejects_removed_opcodes() {
|
||||
let code = prometeu_bytecode::assemble("GET_LOCAL 0\nCALL_CLOSURE 4\nHALT").unwrap();
|
||||
let f = FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
signature: Signature {
|
||||
parameters: vec![NamedType { type_id: TypeId(4), name: None }],
|
||||
results: vec![],
|
||||
@@ -263,12 +303,19 @@ fn expected_fn_signature_checks_argument_height_after_permutations() {
|
||||
&code,
|
||||
vec![
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: end as u32,
|
||||
local_slots: 1,
|
||||
max_stack_slots: 2,
|
||||
..function(&code)
|
||||
},
|
||||
FunctionDecl { signature, code_offset: end as u32, code_len: 2, ..Default::default() },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
signature,
|
||||
code_offset: end as u32,
|
||||
code_len: 2,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
);
|
||||
assert_eq!(stacks(&code, &r).unwrap_err().reason, R::StackUnderflow);
|
||||
@@ -309,12 +356,14 @@ fn stack_analysis_charges_work_for_loop_reprocessing_and_refunds_on_exhaustion()
|
||||
&code,
|
||||
vec![
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: end as u32,
|
||||
local_slots: 1,
|
||||
max_stack_slots: 1,
|
||||
..function(&code)
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: end as u32,
|
||||
code_len: (code.len() - end) as u32,
|
||||
max_stack_slots: 1,
|
||||
@@ -353,8 +402,13 @@ fn typed_opcodes_and_relative_jumps_are_resolved_in_declared_ranges() {
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![
|
||||
FunctionDecl { code_len: start as u32, ..function(&code) },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: start as u32,
|
||||
..function(&code)
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: start as u32,
|
||||
code_len: 6,
|
||||
max_stack_slots: 0,
|
||||
@@ -394,8 +448,13 @@ fn jumps_reject_cross_range_and_mid_instruction_even_when_unreachable() {
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![
|
||||
FunctionDecl { code_len: 6, ..function(&code) },
|
||||
FunctionDecl { code_offset: 6, code_len: 2, ..function(&code) },
|
||||
FunctionDecl { lifecycle_role: Default::default(), code_len: 6, ..function(&code) },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 6,
|
||||
code_len: 2,
|
||||
..function(&code)
|
||||
},
|
||||
],
|
||||
);
|
||||
let e = check(&code, &r).unwrap_err();
|
||||
@@ -479,7 +538,10 @@ fn spawn_arity_does_not_truncate_and_closure_function_ids_are_checked() {
|
||||
#[test]
|
||||
fn declared_range_is_not_extended_into_gaps_or_neighbor_functions() {
|
||||
let code = vec![Op::Halt as u8, 0, 0xff, 0xff];
|
||||
let r = registry(&code, vec![FunctionDecl { code_len: 2, ..function(&code) }]);
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![FunctionDecl { lifecycle_role: Default::default(), code_len: 2, ..function(&code) }],
|
||||
);
|
||||
assert!(check(&code, &r).is_ok()); // Unowned gap is outside this phase's ranges.
|
||||
let r = registry(&code, vec![function(&code)]);
|
||||
assert_eq!(check(&code, &r).unwrap_err().reason, R::UnknownOpcode);
|
||||
@@ -493,8 +555,13 @@ fn scratch_is_refunded_per_function_and_preserves_prior_load_ownership() {
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![
|
||||
FunctionDecl { code_len: 2, ..function(&code) },
|
||||
FunctionDecl { code_offset: 2, code_len: 2, ..function(&code) },
|
||||
FunctionDecl { lifecycle_role: Default::default(), code_len: 2, ..function(&code) },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 2,
|
||||
code_len: 2,
|
||||
..function(&code)
|
||||
},
|
||||
],
|
||||
);
|
||||
let limits = LoadLimits { temporary_bytes: 8, ..Default::default() };
|
||||
@@ -531,8 +598,13 @@ fn truncated_immediates_cannot_borrow_bytes_from_the_next_function() {
|
||||
let r = registry(
|
||||
&code,
|
||||
vec![
|
||||
FunctionDecl { code_len: 2, ..function(&code) },
|
||||
FunctionDecl { code_offset: 2, code_len: 2, ..function(&code) },
|
||||
FunctionDecl { lifecycle_role: Default::default(), code_len: 2, ..function(&code) },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 2,
|
||||
code_len: 2,
|
||||
..function(&code)
|
||||
},
|
||||
],
|
||||
);
|
||||
let e = check(&code, &r).unwrap_err();
|
||||
|
||||
@@ -32,6 +32,7 @@ fn function(
|
||||
max: u32,
|
||||
) -> FunctionDecl {
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
captures: vec![],
|
||||
code_offset: offset as u32,
|
||||
code_len: len as u32,
|
||||
|
||||
@@ -7,6 +7,7 @@ mod collections_tests;
|
||||
mod control;
|
||||
mod dynamic;
|
||||
mod gc;
|
||||
mod lifecycle;
|
||||
mod loader;
|
||||
mod random;
|
||||
mod reference;
|
||||
@@ -49,6 +50,8 @@ use prometeu_test_support::program::{TestProgram, int64_signature};
|
||||
pub enum LogicalFrameEndingReason {
|
||||
/// Execution reached a `FRAME_SYNC` instruction, marking the end of the logical frame.
|
||||
FrameSync,
|
||||
/// The outer lifecycle callback returned; gameplay has not resumed.
|
||||
LifecycleComplete,
|
||||
/// The cycle budget for the current host tick was exhausted before reaching `FRAME_SYNC`.
|
||||
BudgetExhausted,
|
||||
/// A `HALT` instruction was executed, terminating the program.
|
||||
@@ -109,6 +112,8 @@ pub struct VirtualMachine {
|
||||
cycles: u64,
|
||||
/// Stop flag: true if a `HALT` opcode was encountered.
|
||||
halted: bool,
|
||||
lifecycle: Option<lifecycle::LifecycleCall>,
|
||||
lifecycle_failure: Option<LogicalFrameEndingReason>,
|
||||
/// Set of ROM addresses used for software breakpoints in the debugger.
|
||||
breakpoints: std::collections::HashSet<usize>,
|
||||
/// GC: number of newly allocated live objects threshold to trigger a collection at safepoint.
|
||||
@@ -229,6 +234,8 @@ impl VirtualMachine {
|
||||
heap: Heap::with_budget(&budget),
|
||||
cycles: 0,
|
||||
halted: true,
|
||||
lifecycle: None,
|
||||
lifecycle_failure: None,
|
||||
breakpoints: std::collections::HashSet::new(),
|
||||
gc_alloc_threshold: 1024, // conservative default; tests may override
|
||||
last_gc_live_count: 0,
|
||||
@@ -257,7 +264,7 @@ impl VirtualMachine {
|
||||
/// 1. Fetch: Read the opcode from memory.
|
||||
/// 2. Decode: Identify what operation to perform.
|
||||
/// 3. Execute: Perform the operation, updating stacks, memory, or calling peripherals.
|
||||
pub fn step(
|
||||
fn step_inner(
|
||||
&mut self,
|
||||
native: &mut dyn NativeInterface,
|
||||
ctx: &mut HostContext,
|
||||
@@ -1039,6 +1046,14 @@ impl VirtualMachine {
|
||||
return self.execute_collection(opcode, ty, field, start_pc as u32);
|
||||
}
|
||||
OpCode::FrameSync => {
|
||||
if self.lifecycle.is_some() {
|
||||
return Err(self.trap(
|
||||
TRAP_TYPE,
|
||||
opcode as u16,
|
||||
"FRAME_SYNC is forbidden in lifecycle hooks".into(),
|
||||
start_pc as u32,
|
||||
));
|
||||
}
|
||||
// Marks the logical end of a frame: consume cycles and signal to the driver
|
||||
self.cycles += OpCode::FrameSync.cycles();
|
||||
self.handle_safepoint()
|
||||
@@ -1152,7 +1167,11 @@ mod tests {
|
||||
typed_test_vm(
|
||||
code,
|
||||
constant_pool,
|
||||
vec![FunctionDecl { max_stack_slots: 256, ..Default::default() }],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
max_stack_slots: 256,
|
||||
..Default::default()
|
||||
}],
|
||||
)
|
||||
}
|
||||
fn limited_session(code: Vec<u8>, limits: RuntimeLimits) -> VirtualMachine {
|
||||
@@ -1196,6 +1215,7 @@ mod tests {
|
||||
TestProgram {
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
|
||||
@@ -1511,8 +1531,13 @@ mod tests {
|
||||
rom,
|
||||
vec![],
|
||||
vec![
|
||||
FunctionDecl { max_stack_slots: 256, ..Default::default() },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
max_stack_slots: 256,
|
||||
..Default::default()
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: func_addr as u32,
|
||||
signature: int64_signature(1, 1),
|
||||
max_stack_slots: 256,
|
||||
@@ -1593,8 +1618,13 @@ mod tests {
|
||||
rom2,
|
||||
vec![],
|
||||
vec![
|
||||
FunctionDecl { max_stack_slots: 256, ..Default::default() },
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
max_stack_slots: 256,
|
||||
..Default::default()
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: func_addr2 as u32,
|
||||
signature: int64_signature(0, 1),
|
||||
max_stack_slots: 256,
|
||||
@@ -1834,6 +1864,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -2449,6 +2480,7 @@ mod tests {
|
||||
let header = TestProgram {
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
|
||||
@@ -2964,6 +2996,7 @@ mod tests {
|
||||
vec![],
|
||||
vec![
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f0_start as u32,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -2974,6 +3007,7 @@ mod tests {
|
||||
local_slots: 0,
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f1_start,
|
||||
|
||||
signature: scalar_signature(2, 1, 1),
|
||||
@@ -3025,6 +3059,7 @@ mod tests {
|
||||
vec![],
|
||||
vec![
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f0_start as u32,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -3035,6 +3070,7 @@ mod tests {
|
||||
local_slots: 0,
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f1_start,
|
||||
|
||||
signature: scalar_signature(0, 2, 1),
|
||||
@@ -3085,6 +3121,7 @@ mod tests {
|
||||
vec![],
|
||||
vec![
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f0_start as u32,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -3095,6 +3132,7 @@ mod tests {
|
||||
local_slots: 0,
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f1_start,
|
||||
|
||||
signature: scalar_signature(1, 0, 1),
|
||||
@@ -3210,6 +3248,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
local_slots: 1,
|
||||
|
||||
@@ -3269,6 +3308,7 @@ mod tests {
|
||||
vec![],
|
||||
vec![
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f0_start as u32,
|
||||
|
||||
signature: scalar_signature(0, 0, 4),
|
||||
@@ -3279,6 +3319,7 @@ mod tests {
|
||||
local_slots: 0,
|
||||
},
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: f1_start,
|
||||
local_slots: 1,
|
||||
|
||||
@@ -3391,6 +3432,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -3439,6 +3481,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -3506,6 +3549,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -3556,6 +3600,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -3606,6 +3651,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
@@ -3661,6 +3707,7 @@ mod tests {
|
||||
rom.clone(),
|
||||
vec![],
|
||||
vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_offset: 0,
|
||||
|
||||
signature: scalar_signature(0, 0, 1),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Bounded calls that retain the suspended guest continuation and its GC roots.
|
||||
use super::*;
|
||||
use prometeu_bytecode::registry::LifecycleRole;
|
||||
|
||||
pub(super) struct LifecycleCall {
|
||||
depth: usize,
|
||||
pc: usize,
|
||||
halted: bool,
|
||||
pub(super) remaining: u64,
|
||||
pub(super) breakpoint: Option<usize>,
|
||||
}
|
||||
|
||||
impl VirtualMachine {
|
||||
pub const LIFECYCLE_CYCLES: u64 = 1_500_000;
|
||||
pub const LIFECYCLE_SLICE: u64 = 250_000;
|
||||
|
||||
pub fn has_lifecycle_hook(&self, role: LifecycleRole) -> bool {
|
||||
self.validated_image.as_ref().is_some_and(|i| i.registry().lifecycle_hook(role).is_some())
|
||||
}
|
||||
|
||||
pub fn lifecycle_active(&self) -> bool {
|
||||
self.lifecycle.is_some()
|
||||
}
|
||||
|
||||
pub fn lifecycle_remaining_cycles(&self) -> Option<u64> {
|
||||
self.lifecycle.as_ref().map(|call| call.remaining)
|
||||
}
|
||||
|
||||
/// Returns false for an absent role. Entry is transactional with respect to quotas.
|
||||
pub fn begin_lifecycle(&mut self, role: LifecycleRole) -> Result<bool, VmInitError> {
|
||||
if self.lifecycle.is_some() || self.lifecycle_failure.is_some() {
|
||||
return Err(VmInitError::EntrypointNotFound);
|
||||
}
|
||||
let Some(id) =
|
||||
self.validated_image.as_ref().and_then(|i| i.registry().lifecycle_hook(role))
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let func_idx = id.0 as usize;
|
||||
let callee = &self.program.functions[func_idx];
|
||||
let locals = callee.local_slots as usize;
|
||||
let offset = callee.code_offset as usize;
|
||||
self.budget.check(RuntimeResource::CallDepth, (self.call_stack.len() + 1) as u64)?;
|
||||
let operands = self.operand_stack.prepare_growth(locals)?;
|
||||
let frames = self.call_stack.prepare_growth(1)?;
|
||||
self.operand_stack.commit_growth(operands);
|
||||
self.call_stack.commit_growth(frames);
|
||||
let base = self.operand_stack.len();
|
||||
let call = LifecycleCall {
|
||||
depth: self.call_stack.len(),
|
||||
pc: self.pc,
|
||||
halted: self.halted,
|
||||
remaining: Self::LIFECYCLE_CYCLES,
|
||||
breakpoint: None,
|
||||
};
|
||||
for _ in 0..locals {
|
||||
self.operand_stack.push(Value::Null)?;
|
||||
}
|
||||
self.call_stack.push(CallFrame {
|
||||
return_pc: self.pc as u32,
|
||||
stack_base: base,
|
||||
func_idx,
|
||||
closure: None,
|
||||
})?;
|
||||
self.lifecycle = Some(call);
|
||||
self.pc = offset;
|
||||
self.halted = false;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Both the debugger and normal slices pass through the same accounting boundary.
|
||||
pub fn step(
|
||||
&mut self,
|
||||
native: &mut dyn NativeInterface,
|
||||
ctx: &mut HostContext,
|
||||
) -> Result<(), LogicalFrameEndingReason> {
|
||||
if let Some(reason) = &self.lifecycle_failure {
|
||||
return Err(reason.clone());
|
||||
}
|
||||
if let Some(call) = &mut self.lifecycle {
|
||||
call.breakpoint = None;
|
||||
}
|
||||
let before = self.cycles;
|
||||
let result = self.step_inner(native, ctx);
|
||||
let Some(call) = self.lifecycle.as_mut() else {
|
||||
return result;
|
||||
};
|
||||
call.remaining = call.remaining.saturating_sub(self.cycles - before);
|
||||
if result.is_ok() && !self.halted && self.call_stack.len() == call.depth {
|
||||
let call = self.lifecycle.take().unwrap();
|
||||
self.pc = call.pc;
|
||||
self.halted = call.halted;
|
||||
return Err(LogicalFrameEndingReason::LifecycleComplete);
|
||||
}
|
||||
let failure = match result {
|
||||
Err(reason) => Some(reason),
|
||||
Ok(()) if self.halted => Some(LogicalFrameEndingReason::Halted),
|
||||
Ok(()) if call.remaining == 0 => Some(LogicalFrameEndingReason::Panic(
|
||||
"lifecycle total cycle budget exhausted".into(),
|
||||
)),
|
||||
Ok(()) => None,
|
||||
};
|
||||
if let Some(reason) = failure {
|
||||
self.lifecycle_failure = Some(reason.clone());
|
||||
return Err(reason);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,9 @@ impl VirtualMachine {
|
||||
func_idx: usize,
|
||||
arguments: &[Value],
|
||||
) -> Result<(), VmInitError> {
|
||||
if self.lifecycle.is_some() || self.lifecycle_failure.is_some() {
|
||||
return Err(VmInitError::EntrypointNotFound);
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
if self.validated_image.is_none() {
|
||||
return Err(VmInitError::EntrypointNotFound);
|
||||
|
||||
@@ -7,6 +7,11 @@ impl VirtualMachine {
|
||||
native: &mut dyn NativeInterface,
|
||||
ctx: &mut HostContext,
|
||||
) -> Result<BudgetReport, String> {
|
||||
if let Some(reason) = &self.lifecycle_failure {
|
||||
return Ok(BudgetReport { cycles_used: 0, steps_executed: 0, reason: reason.clone() });
|
||||
}
|
||||
let budget =
|
||||
if self.lifecycle.is_some() { budget.min(Self::LIFECYCLE_SLICE) } else { budget };
|
||||
let start_cycles = self.cycles;
|
||||
let mut steps_executed = 0;
|
||||
let mut ending_reason: Option<LogicalFrameEndingReason> = None;
|
||||
@@ -15,7 +20,13 @@ impl VirtualMachine {
|
||||
&& !self.halted
|
||||
&& self.pc < self.program.rom.len()
|
||||
{
|
||||
if steps_executed > 0 && self.breakpoints.contains(&self.pc) {
|
||||
if self.breakpoints.contains(&self.pc)
|
||||
&& (steps_executed > 0
|
||||
|| self.lifecycle.as_ref().is_some_and(|c| c.breakpoint != Some(self.pc)))
|
||||
{
|
||||
if let Some(call) = &mut self.lifecycle {
|
||||
call.breakpoint = Some(self.pc);
|
||||
}
|
||||
ending_reason = Some(LogicalFrameEndingReason::Breakpoint);
|
||||
break;
|
||||
}
|
||||
@@ -70,7 +81,8 @@ impl VirtualMachine {
|
||||
let rep = self.run_budget(budget_per_slice, native, ctx)?;
|
||||
let terminal = matches!(
|
||||
rep.reason,
|
||||
LogicalFrameEndingReason::Halted
|
||||
LogicalFrameEndingReason::LifecycleComplete
|
||||
| LogicalFrameEndingReason::Halted
|
||||
| LogicalFrameEndingReason::EndOfRom
|
||||
| LogicalFrameEndingReason::Panic(_)
|
||||
| LogicalFrameEndingReason::Trap(_)
|
||||
@@ -113,7 +125,8 @@ impl VirtualMachine {
|
||||
let rep = self.run_budget(budget_per_slice, native, ctx)?;
|
||||
let terminal = matches!(
|
||||
rep.reason,
|
||||
LogicalFrameEndingReason::Halted
|
||||
LogicalFrameEndingReason::LifecycleComplete
|
||||
| LogicalFrameEndingReason::Halted
|
||||
| LogicalFrameEndingReason::EndOfRom
|
||||
| LogicalFrameEndingReason::Panic(_)
|
||||
| LogicalFrameEndingReason::Trap(_)
|
||||
|
||||
@@ -36,6 +36,7 @@ fn function(
|
||||
max: u32,
|
||||
) -> FunctionDecl {
|
||||
FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
captures: vec![],
|
||||
name: Some(format!("f{offset}")),
|
||||
code_offset: offset as u32,
|
||||
@@ -777,3 +778,171 @@ fn call_growth_refusal_does_not_publish_frame_or_keep_provisional_capacity() {
|
||||
assert_eq!(vm.budget.used(RuntimeResource::AuxiliaryBytes), before);
|
||||
assert_eq!(vm.budget.used(RuntimeResource::TemporaryBytes), 0);
|
||||
}
|
||||
|
||||
mod lifecycle_tests {
|
||||
use super::*;
|
||||
use prometeu_bytecode::registry::LifecycleRole;
|
||||
|
||||
fn machine(hook: Vec<u8>) -> VirtualMachine {
|
||||
let mut code = vec![];
|
||||
arg(&mut code, OpCode::PushI32, 17);
|
||||
op(&mut code, OpCode::FrameSync);
|
||||
arg(&mut code, OpCode::SetGlobal, 0);
|
||||
op(&mut code, OpCode::Ret);
|
||||
let len = code.len();
|
||||
code.extend(&hook);
|
||||
let mut callback = function(len, hook.len(), &[], &[], 0, 8);
|
||||
callback.lifecycle_role = LifecycleRole::BeforePause;
|
||||
let image = image(&code, vec![function(0, len, &[], &[], 0, 8), callback]);
|
||||
let mut vm = VirtualMachine::from_image(image, RuntimeLimits::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
assert_eq!(run(&mut vm), LogicalFrameEndingReason::FrameSync);
|
||||
vm
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_preserves_continuation_and_does_not_run_gameplay_after_return() {
|
||||
let mut hook = vec![];
|
||||
arg(&mut hook, OpCode::PushI32, 42);
|
||||
arg(&mut hook, OpCode::SetGlobal, 1);
|
||||
op(&mut hook, OpCode::Ret);
|
||||
let mut vm = machine(hook);
|
||||
let pc = vm.pc;
|
||||
let depth = vm.call_stack.len();
|
||||
let stack = vm.operand_stack.to_vec();
|
||||
assert!(vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap());
|
||||
assert!(vm.begin_lifecycle(LifecycleRole::BeforePause).is_err());
|
||||
assert_eq!(run(&mut vm), LogicalFrameEndingReason::LifecycleComplete);
|
||||
assert_eq!(vm.pc, pc);
|
||||
assert_eq!(vm.call_stack.len(), depth);
|
||||
assert_eq!(&vm.operand_stack[..], stack.as_slice());
|
||||
assert_eq!(vm.globals[1], Value::Int32(42));
|
||||
assert_eq!(run(&mut vm), LogicalFrameEndingReason::EndOfRom);
|
||||
assert_eq!(vm.globals[0], Value::Int32(17));
|
||||
assert!(!vm.begin_lifecycle(LifecycleRole::BeforeResume).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_budget_survives_slices_breakpoints_and_single_steps() {
|
||||
let mut hook = vec![];
|
||||
arg(&mut hook, OpCode::Jmp, 0);
|
||||
let mut vm = machine(hook);
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
vm.insert_breakpoint(vm.pc);
|
||||
let rep = vm.run_budget(u64::MAX, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert_eq!(rep.reason, LogicalFrameEndingReason::Breakpoint);
|
||||
assert_eq!(rep.cycles_used, 0);
|
||||
let before = vm.lifecycle_remaining_cycles().unwrap();
|
||||
vm.step(&mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert!(vm.lifecycle_remaining_cycles().unwrap() < before);
|
||||
vm.breakpoints.clear();
|
||||
let mut total = VirtualMachine::LIFECYCLE_CYCLES - vm.lifecycle_remaining_cycles().unwrap();
|
||||
loop {
|
||||
let rep = vm.run_budget(u64::MAX, &mut Native, &mut HostContext::new(None)).unwrap();
|
||||
assert!(rep.cycles_used <= VirtualMachine::LIFECYCLE_SLICE + OpCode::Jmp.cycles());
|
||||
total += rep.cycles_used;
|
||||
if let LogicalFrameEndingReason::Panic(message) = rep.reason {
|
||||
assert!(message.contains("total cycle budget"));
|
||||
break;
|
||||
}
|
||||
assert_eq!(rep.reason, LogicalFrameEndingReason::BudgetExhausted);
|
||||
}
|
||||
assert!(total >= VirtualMachine::LIFECYCLE_CYCLES);
|
||||
let pc = vm.pc;
|
||||
assert!(vm.step(&mut Native, &mut HostContext::new(None)).is_err());
|
||||
assert_eq!(vm.pc, pc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_normal_return_wins_at_budget_boundary_and_halt_does_not_complete() {
|
||||
for remaining in [1, OpCode::Ret.cycles()] {
|
||||
let mut hook = vec![];
|
||||
op(&mut hook, OpCode::Ret);
|
||||
let mut vm = machine(hook);
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
vm.lifecycle.as_mut().unwrap().remaining = remaining;
|
||||
assert_eq!(run(&mut vm), LogicalFrameEndingReason::LifecycleComplete);
|
||||
}
|
||||
let mut hook = vec![];
|
||||
op(&mut hook, OpCode::Halt);
|
||||
let mut vm = machine(hook);
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
assert_eq!(run(&mut vm), LogicalFrameEndingReason::Halted);
|
||||
assert!(vm.lifecycle_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_forbids_frame_sync_and_preserves_failure() {
|
||||
let mut hook = vec![];
|
||||
op(&mut hook, OpCode::FrameSync);
|
||||
op(&mut hook, OpCode::Ret);
|
||||
let mut vm = machine(hook);
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
let reason = run(&mut vm);
|
||||
assert!(
|
||||
matches!(&reason, LogicalFrameEndingReason::Trap(t) if t.message.contains("FRAME_SYNC"))
|
||||
);
|
||||
assert_eq!(run(&mut vm), reason);
|
||||
}
|
||||
#[test]
|
||||
fn lifecycle_nested_calls_keep_saved_roots_and_branch_returns_stop_at_boundary() {
|
||||
let main = prometeu_bytecode::assembler::assemble("FRAME_SYNC\nRET").unwrap();
|
||||
let hook = prometeu_bytecode::assembler::assemble("CALL 2\nJMP 12").unwrap();
|
||||
for callee_source in ["PUSH_I32 9\nSET_GLOBAL 0\nRET", "FRAME_SYNC\nRET"] {
|
||||
let callee = prometeu_bytecode::assembler::assemble(callee_source).unwrap();
|
||||
let mut callback = function(main.len(), hook.len(), &[], &[], 0, 8);
|
||||
callback.lifecycle_role = LifecycleRole::BeforePause;
|
||||
let code = [main.as_slice(), hook.as_slice(), callee.as_slice()].concat();
|
||||
let image = image(
|
||||
&code,
|
||||
vec![
|
||||
function(0, main.len(), &[], &[], 0, 8),
|
||||
callback,
|
||||
function(main.len() + hook.len(), callee.len(), &[], &[], 0, 8),
|
||||
],
|
||||
);
|
||||
let mut vm = VirtualMachine::from_image(image, RuntimeLimits::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
assert_eq!(run(&mut vm), LogicalFrameEndingReason::FrameSync);
|
||||
let retained = vm.heap.alloc_closure(0, &[]).unwrap();
|
||||
vm.operand_stack.push(Value::HeapRef(retained)).unwrap();
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
vm.gc_alloc_threshold = 1;
|
||||
vm.handle_safepoint().unwrap();
|
||||
assert!(vm.heap.is_valid(retained));
|
||||
let result = run(&mut vm);
|
||||
if callee_source.starts_with("FRAME_SYNC") {
|
||||
assert!(matches!(result, LogicalFrameEndingReason::Trap(_)));
|
||||
} else {
|
||||
assert_eq!(result, LogicalFrameEndingReason::LifecycleComplete);
|
||||
assert_eq!(vm.call_stack.len(), 1);
|
||||
assert_eq!(vm.operand_stack.last(), Some(&Value::HeapRef(retained)));
|
||||
assert_eq!(vm.globals[0], Value::Int32(9));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_entry_quota_refusal_is_transactional_and_empty_context_is_supported() {
|
||||
let mut vm = machine(prometeu_bytecode::assembler::assemble("RET").unwrap());
|
||||
let image = vm.validated_image.clone().unwrap();
|
||||
let limits = RuntimeLimits::default().lowered(RuntimeResource::CallDepth, 1).unwrap();
|
||||
vm = VirtualMachine::from_image(image.clone(), limits);
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let pc = vm.pc;
|
||||
let stack = vm.operand_stack.to_vec();
|
||||
assert!(vm.begin_lifecycle(LifecycleRole::BeforePause).is_err());
|
||||
assert_eq!(vm.pc, pc);
|
||||
assert_eq!(&vm.operand_stack[..], stack.as_slice());
|
||||
assert_eq!(vm.call_stack.len(), 1);
|
||||
assert!(!vm.lifecycle_active());
|
||||
let mut vm = VirtualMachine::from_image(image, RuntimeLimits::default());
|
||||
let halted = vm.halted;
|
||||
let pc = vm.pc;
|
||||
vm.begin_lifecycle(LifecycleRole::BeforePause).unwrap();
|
||||
assert_eq!(run(&mut vm), LogicalFrameEndingReason::LifecycleComplete);
|
||||
assert_eq!(vm.pc, pc);
|
||||
assert_eq!(vm.halted, halted);
|
||||
assert!(vm.call_stack.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ fn named_arguments_preserve_source_effect_order_and_call_in_signature_order_with
|
||||
vec![]
|
||||
};
|
||||
functions.push(FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
captures: vec![],
|
||||
name: Some(["main", "effectX", "effectY", "combine"][index].into()),
|
||||
signature: Signature {
|
||||
|
||||
@@ -7,20 +7,20 @@ use prometeu_vm::{
|
||||
};
|
||||
|
||||
// Independent executable oracle: 32-byte header, eight directory entries,
|
||||
// payload at 128, one Bool import, one zero-slot HALT function; total 193.
|
||||
// payload at 128, one Bool import, one zero-slot HALT function; total 194.
|
||||
fn minimal() -> Vec<u8> {
|
||||
"50 42 58 00 01 00 00 00 08 00 00 00
|
||||
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
00 00 00 00 80 00 00 00 04 00 00 00
|
||||
01 00 00 00 84 00 00 00 1d 00 00 00
|
||||
02 00 00 00 a1 00 00 00 02 00 00 00
|
||||
04 00 00 00 a3 00 00 00 04 00 00 00
|
||||
05 00 00 00 a7 00 00 00 04 00 00 00
|
||||
06 00 00 00 ab 00 00 00 0a 00 00 00
|
||||
07 00 00 00 b5 00 00 00 04 00 00 00
|
||||
08 00 00 00 b9 00 00 00 08 00 00 00
|
||||
01 00 00 00 84 00 00 00 1e 00 00 00
|
||||
02 00 00 00 a2 00 00 00 02 00 00 00
|
||||
04 00 00 00 a4 00 00 00 04 00 00 00
|
||||
05 00 00 00 a8 00 00 00 04 00 00 00
|
||||
06 00 00 00 ac 00 00 00 0a 00 00 00
|
||||
07 00 00 00 b6 00 00 00 04 00 00 00
|
||||
08 00 00 00 ba 00 00 00 08 00 00 00
|
||||
00 00 00 00
|
||||
01 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
01 00 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00
|
||||
01 00
|
||||
00 00 00 00
|
||||
@@ -48,7 +48,7 @@ impl NativeInterface for Native {
|
||||
#[test]
|
||||
fn independent_v1_bytes_load_publish_and_execute_through_the_public_sealed_boundary() {
|
||||
let bytes = minimal();
|
||||
assert_eq!(bytes.len(), 193);
|
||||
assert_eq!(bytes.len(), 194);
|
||||
let mut load = LoadBudget::new(Default::default());
|
||||
let image = ValidatedProgramImage::load(&bytes, &mut load, caps::NONE).unwrap();
|
||||
assert_eq!(load.used(LoadResource::TemporaryBytes), 0);
|
||||
@@ -65,9 +65,9 @@ fn independent_v1_bytes_load_publish_and_execute_through_the_public_sealed_bound
|
||||
fn single_violation_oracles_reject_before_image_publication_with_typed_context() {
|
||||
for (offset, replacement, code, reason, pc) in [
|
||||
(4, 0, LoadCode::UnsupportedFormat, LoadReason::Version, None),
|
||||
(177, 0, LoadCode::UnsupportedFormat, LoadReason::Builtin, None),
|
||||
(161, 0xff, LoadCode::InvalidCode, LoadReason::UnknownOpcode, Some(0)),
|
||||
(161, 0x11, LoadCode::InvalidCode, LoadReason::StackUnderflow, Some(0)),
|
||||
(178, 0, LoadCode::UnsupportedFormat, LoadReason::Builtin, None),
|
||||
(162, 0xff, LoadCode::InvalidCode, LoadReason::UnknownOpcode, Some(0)),
|
||||
(162, 0x11, LoadCode::InvalidCode, LoadReason::StackUnderflow, Some(0)),
|
||||
] {
|
||||
let mut bytes = minimal();
|
||||
bytes[offset] = replacement;
|
||||
|
||||
@@ -89,6 +89,7 @@ pub fn bytes_with_syscalls(
|
||||
for (source, signature, captures) in bodies {
|
||||
let body = assemble(source).unwrap();
|
||||
functions.push(FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
signature: signature.clone(),
|
||||
captures: captures.clone(),
|
||||
code_offset: code.len() as u32,
|
||||
|
||||
@@ -60,6 +60,7 @@ pub fn declarations(code_len: usize) -> RegistryDeclarations {
|
||||
RegistryDeclarations {
|
||||
types,
|
||||
functions: vec![FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
code_len: code_len as u32,
|
||||
local_slots: 0,
|
||||
max_stack_slots: 32,
|
||||
|
||||
@@ -50,6 +50,7 @@ pub fn bytes(bodies: &[Body<'_>]) -> Vec<u8> {
|
||||
for (text, signature, captures, locals) in bodies {
|
||||
let body = assemble(text).unwrap();
|
||||
functions.push(FunctionDecl {
|
||||
lifecycle_role: Default::default(),
|
||||
signature: signature.clone(),
|
||||
captures: captures.clone(),
|
||||
local_slots: *locals,
|
||||
|
||||
Reference in New Issue
Block a user