break monster VM into small pieces :D

This commit is contained in:
2026-03-24 13:40:48 +00:00
parent ea12bd3fd5
commit 9a60754e5a
24 changed files with 2894 additions and 3514 deletions
@@ -0,0 +1,182 @@
use super::*;
fn patch_module_hostcalls(
module: &mut BytecodeModule,
capabilities: prometeu_hal::syscalls::CapFlags,
) -> Result<(), LoaderPatchError> {
let resolved =
prometeu_hal::syscalls::resolve_declared_program_syscalls(&module.syscalls, capabilities)
.map_err(LoaderPatchError::ResolveFailed)?;
let mut used = vec![false; module.syscalls.len()];
let mut pc = 0usize;
while pc < module.code.len() {
let instr = decode_next(pc, &module.code).map_err(LoaderPatchError::DecodeFailed)?;
let next_pc = instr.next_pc;
match instr.opcode {
OpCode::Hostcall => {
let sysc_index = instr.imm_u32().map_err(LoaderPatchError::DecodeFailed)?;
let Some(resolved_syscall) = resolved.get(sysc_index as usize) else {
return Err(LoaderPatchError::HostcallIndexOutOfBounds {
pc,
sysc_index,
syscalls_len: resolved.len(),
});
};
used[sysc_index as usize] = true;
module.code[pc..pc + 2].copy_from_slice(&(OpCode::Syscall as u16).to_le_bytes());
module.code[pc + 2..pc + 6].copy_from_slice(&resolved_syscall.id.to_le_bytes());
}
OpCode::Syscall => {
return Err(LoaderPatchError::RawSyscallInPreloadArtifact {
pc,
syscall_id: instr.imm_u32().map_err(LoaderPatchError::DecodeFailed)?,
});
}
_ => {}
}
pc = next_pc;
}
for (index, (was_used, decl)) in used.iter().zip(&module.syscalls).enumerate() {
if !was_used {
return Err(LoaderPatchError::UnusedSyscallDecl {
sysc_index: index as u32,
module: decl.module.clone(),
name: decl.name.clone(),
version: decl.version,
});
}
}
let mut pc = 0usize;
while pc < module.code.len() {
let instr = decode_next(pc, &module.code).map_err(LoaderPatchError::DecodeFailed)?;
if instr.opcode == OpCode::Hostcall {
return Err(LoaderPatchError::HostcallRemaining {
pc,
sysc_index: instr.imm_u32().map_err(LoaderPatchError::DecodeFailed)?,
});
}
pc = instr.next_pc;
}
Ok(())
}
impl VirtualMachine {
pub fn initialize(
&mut self,
program_bytes: Vec<u8>,
entrypoint: &str,
) -> Result<(), VmInitError> {
self.program = ProgramImage::default();
self.pc = 0;
self.operand_stack.clear();
self.call_stack.clear();
self.globals.clear();
self.heap = Heap::new();
self.cycles = 0;
self.halted = true;
self.last_gc_live_count = 0;
self.current_tick = 0;
self.sleep_requested_until = None;
self.scheduler = Scheduler::new();
self.current_coro = None;
let program = if program_bytes.starts_with(b"PBS\0") {
match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
Ok(mut module) => {
patch_module_hostcalls(&mut module, self.capabilities)
.map_err(VmInitError::LoaderPatchFailed)?;
let max_stacks = Verifier::verify(&module.code, &module.functions)
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
let mut program = ProgramImage::from(module);
let mut functions = program.functions.as_ref().to_vec();
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
func.max_stack_slots = max_stack;
}
program.functions = std::sync::Arc::from(functions);
program
}
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
return Err(VmInitError::UnsupportedFormat);
}
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
}
} else {
return Err(VmInitError::InvalidFormat);
};
let pc = if entrypoint.is_empty() {
program.functions.first().map(|f| f.code_offset as usize).unwrap_or(0)
} else if let Ok(func_idx) = entrypoint.parse::<usize>() {
program
.functions
.get(func_idx)
.map(|f| f.code_offset as usize)
.ok_or(VmInitError::EntrypointNotFound)?
} else if let Some(&func_idx) = program.exports.get(entrypoint) {
program
.functions
.get(func_idx as usize)
.map(|f| f.code_offset as usize)
.ok_or(VmInitError::EntrypointNotFound)?
} else {
return Err(VmInitError::EntrypointNotFound);
};
self.program = program;
self.pc = pc;
self.halted = false;
Ok(())
}
pub fn set_capabilities(&mut self, caps: prometeu_hal::syscalls::CapFlags) {
self.capabilities = caps;
}
pub fn prepare_call(&mut self, entrypoint: &str) {
let func_idx = if let Ok(idx) = entrypoint.parse::<usize>() {
idx
} else {
self.program.exports.get(entrypoint).map(|&idx| idx as usize).ok_or(()).unwrap_or(0)
};
let callee = self.program.functions.get(func_idx).cloned().unwrap_or_default();
self.pc = callee.code_offset as usize;
self.halted = false;
self.operand_stack.clear();
self.call_stack.clear();
if let Some(func) = self.program.functions.get(func_idx) {
let total_slots = func.param_slots as u32 + func.local_slots as u32;
for _ in 0..total_slots {
self.operand_stack.push(Value::Null);
}
}
self.call_stack.push(CallFrame {
return_pc: self.program.rom.len() as u32,
stack_base: 0,
func_idx,
});
let main_href = self.heap.allocate_coroutine(
self.pc,
CoroutineState::Running,
0,
Vec::new(),
Vec::new(),
);
self.current_coro = Some(main_href);
self.scheduler.set_current(self.current_coro);
}
}