feat(vm): add deterministic gameplay math and domain coverage gates
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit

This commit is contained in:
2026-10-09 10:25:11 +01:00
parent 2e041266f1
commit 9318cf7cd3
47 changed files with 8825 additions and 281 deletions
@@ -32,6 +32,12 @@ pub const TRAP_INVALID_HANDLE: u32 = 0x0000_000F;
pub const TRAP_RESOURCE_LIMIT: u32 = 0x0000_0010;
/// Known input query unavailable on this platform.
pub const TRAP_UNAVAILABLE: u32 = 0x0000_0011;
/// Mathematical domain is invalid for the supplied finite arguments.
pub const TRAP_NUMERIC_DOMAIN: u32 = 0x0000_0012;
/// Finite input produces an unrepresentable result or integer destination.
pub const TRAP_NUMERIC_RANGE: u32 = 0x0000_0013;
/// A NaN or infinite input cannot enter guest numeric computation.
pub const TRAP_NON_FINITE: u32 = 0x0000_0014;
use serde::{Deserialize, Serialize};
+3 -2
View File
@@ -13,8 +13,9 @@ mod value;
pub use abi::{
SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT,
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_HANDLE, TRAP_INVALID_INTRINSIC,
TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_NULL_REFERENCE, TRAP_OOB, TRAP_RESOURCE_LIMIT,
TRAP_STACK_UNDERFLOW, TRAP_TYPE, TRAP_UNAVAILABLE,
TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_NON_FINITE, TRAP_NULL_REFERENCE,
TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE, TRAP_OOB, TRAP_RESOURCE_LIMIT, TRAP_STACK_UNDERFLOW,
TRAP_TYPE, TRAP_UNAVAILABLE,
};
pub use assembler::{assemble, AsmError};
pub use decoder::{decode_next, DecodeError, DecodedInstr};
@@ -74,6 +74,7 @@ pub enum LoadReason {
Limit,
Allocation,
ConstantTag,
NonFiniteValue,
DebugRange,
DuplicateSyscall,
UnknownOpcode,
@@ -229,9 +229,17 @@ impl<'a> Reader<'a, '_> {
(|| {
match self.byte()? {
0 => {}
1 | 2 => {
1 => {
self.take(8)?;
}
2 => {
let at = self.pos;
let bits = u64::from_le_bytes(self.take(8)?.try_into().unwrap());
if bits & 0x7ff0_0000_0000_0000 == 0x7ff0_0000_0000_0000 {
return Err(E::new(C::InvalidFormat, R::NonFiniteValue)
.at(self.section.kind, self.section.offset + at));
}
}
3 => {
if self.byte()? > 1 {
return Err(self.error(C::InvalidFormat, R::InvalidFlag));
@@ -8,6 +8,41 @@ fn budget() -> LoadBudget {
LoadBudget::new(LoadLimits::default())
}
#[test]
fn nonfinite_constant_payloads_are_rejected_with_index_and_exact_offset() {
use prometeu_bytecode::model::ConstantPoolEntry as K;
let registry = minimal_registry();
let constants = [K::Float64(1.0)];
let module = PbxModule {
registry: &registry,
constants: &constants,
code: &[1, 0],
debug: None,
exports: &[],
syscalls: &[],
};
let valid = module.serialize(&mut budget()).unwrap();
let envelope = PbxEnvelope::parse(&valid, &mut budget()).unwrap();
let offset = envelope.section(0).unwrap().offset + 5;
for bits in [0x7ff0000000000000u64, 0xfff0000000000000, 0x7ff8000000000042, 0x7ff0000000000001]
{
let mut bytes = valid.clone();
bytes[offset..offset + 8].copy_from_slice(&bits.to_le_bytes());
let error = OwnedPbx::parse(&bytes, &mut budget()).unwrap_err();
assert_eq!(
(error.code, error.reason, error.section, error.offset, error.record),
(LoadCode::InvalidFormat, LoadReason::NonFiniteValue, Some(0), Some(offset), Some(0))
);
}
for bits in [0u64, 1, 0x000fffffffffffff, 0x7fefffffffffffff, 0x8000000000000000] {
let mut bytes = valid.clone();
bytes[offset..offset + 8].copy_from_slice(&bits.to_le_bytes());
let owned = OwnedPbx::parse(&bytes, &mut budget()).unwrap();
let K::Float64(x) = owned.constants[0] else { panic!() };
assert_eq!(x.to_bits(), bits);
}
}
#[test]
fn fn_keys_ignore_names_but_preserve_logical_parameter_and_result_order() {
let signature = Signature { parameters: vec![named(0)], results: vec![TypeId(1)] };
@@ -222,7 +257,7 @@ fn owned_payloads_preserve_utf8_float_bits_names_and_binding_declarations() {
K::Null,
K::Int32(i32::MIN),
K::Int64(i64::MAX),
K::Float64(f64::from_bits(0x7ff8000000000042)),
K::Float64(f64::from_bits(0x0008000000000042)),
K::Boolean(true),
K::String("é猫".into()),
K::String(String::new()),
@@ -253,7 +288,7 @@ fn owned_payloads_preserve_utf8_float_bits_names_and_binding_declarations() {
let module = OwnedPbx::parse(&bytes, &mut b).unwrap();
assert_eq!(&module.constants[..3], &constants[..3]);
let K::Float64(value) = module.constants[3] else { panic!() };
assert_eq!(value.to_bits(), 0x7ff8000000000042);
assert_eq!(value.to_bits(), 0x0008000000000042);
assert_eq!(&module.constants[4..], &constants[4..]);
assert_eq!(module.debug.as_ref(), Some(&debug));
assert_eq!(module.exports, exports);
@@ -319,7 +354,7 @@ fn complete_module_writer_preserves_non_registry_encodings() {
let constants = [
K::Null,
K::Int64(-1),
K::Float64(f64::from_bits(0x7ff8000000001234)),
K::Float64(f64::from_bits(0x0008000000001234)),
K::Boolean(true),
K::String("é".into()),
K::Int32(-2),
@@ -351,7 +386,7 @@ fn complete_module_writer_preserves_non_registry_encodings() {
parsed.section(0).unwrap().bytes,
hex("07 00 00 00 00
01 ff ff ff ff ff ff ff ff
02 34 12 00 00 00 00 f8 7f
02 34 12 00 00 00 00 08 00
03 01 04 02 00 00 00 c3 a9 05 fe ff ff ff 04 00 00 00 00")
);
assert_eq!(
+1
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
prometeu-bytecode = { path = "../prometeu-bytecode" }
prometeu-hal = { path = "../prometeu-hal" }
fpmath = { version = "=0.1.1", features = ["soft-float"] }
[dev-dependencies]
prometeu-test-support = { path = "../../dev/prometeu-test-support" }
@@ -0,0 +1,7 @@
fn main() {
if std::env::args().nth(1).as_deref() == Some("constants") {
print!("{}", prometeu_vm::builtin_constant_catalog_csv());
} else {
print!("{}", prometeu_vm::intrinsic_catalog_csv());
}
}
@@ -0,0 +1,37 @@
//! Local host timing only; these measurements never define guest cycles.
use prometeu_bytecode::Value;
use prometeu_vm::{HostContext, lookup_intrinsic_by_id};
use std::hint::black_box;
use std::time::Instant;
fn main() {
let iterations: u32 =
std::env::args().nth(1).unwrap_or_else(|| "20000".into()).parse().unwrap();
for (id, args) in [
(0x3010, vec![Value::Float(2.)]),
(0x3011, vec![Value::Float(f64::from_bits(0x6974e718d7d7625a))]),
(0x3012, vec![Value::Float(f64::from_bits(0x7fefffffffffffff))]),
(0x3013, vec![Value::Float(1.), Value::Float(3.)]),
(0x1000, vec![Value::Float(1.), Value::Float(2.), Value::Float(3.), Value::Float(4.)]),
(0x1001, vec![Value::Float(1e200), Value::Float(1e200)]),
] {
let m = lookup_intrinsic_by_id(id).unwrap();
let mut ctx = HostContext::new(None);
for _ in 0..100 {
black_box((m.implementation)(black_box(&args), &mut ctx).unwrap());
}
let start = Instant::now();
for _ in 0..iterations {
black_box((m.implementation)(black_box(&args), &mut ctx).unwrap());
}
let elapsed = start.elapsed().as_nanos();
println!(
"{}.{} iterations={} total_ns={} ns_per_call={:.2} virtual_cycles={}",
m.owner,
m.name,
iterations,
elapsed,
elapsed as f64 / f64::from(iterations),
m.cost_cycles
);
}
}
@@ -0,0 +1,91 @@
//! Reproducible bit-level probe for independent tooling; not a cartridge dependency.
//! stdin: intrinsic hex ID followed by f:bits / i:decimal / l:decimal.
//! Arithmetic opcode names ADD/SUB/MUL/DIV execute a validated PBX program.
use prometeu_bytecode::{Value, assemble};
use prometeu_hal::vm_fault::VmFault;
use prometeu_vm::{
HostContext, HostReturn, LogicalFrameEndingReason, NativeInterface, VirtualMachine,
lookup_intrinsic_by_id,
};
use std::io::{self, BufRead};
struct NoNative;
impl NativeInterface for NoNative {
fn syscall(
&mut self,
_: u32,
_: &[Value],
_: &mut HostReturn,
_: &mut HostContext,
) -> Result<(), VmFault> {
panic!("no native call in numeric probe")
}
}
fn text(value: &Value) -> String {
match value {
Value::Float(x) => format!("f:{:016x}", x.to_bits()),
Value::Int32(x) => format!("i:{x}"),
Value::Int64(x) => format!("l:{x}"),
_ => panic!("numeric output"),
}
}
fn main() {
for line in io::stdin().lock().lines() {
let line = line.unwrap();
let mut words = line.split_whitespace();
let op = words.next().unwrap();
let args: Vec<_> = words
.map(|s| {
let (kind, v) = s.split_once(':').unwrap();
match kind {
"f" => Value::Float(f64::from_bits(u64::from_str_radix(v, 16).unwrap())),
"i" => Value::Int32(v.parse().unwrap()),
"l" => Value::Int64(v.parse().unwrap()),
_ => panic!("carrier"),
}
})
.collect();
if !matches!(op, "ADD" | "SUB" | "MUL" | "DIV") {
let id = u32::from_str_radix(op, 16).unwrap();
let m = lookup_intrinsic_by_id(id).unwrap();
match (m.implementation)(&args, &mut HostContext::new(None)) {
Ok(v) => println!("{} {}", text(&v[0]), m.cost_cycles),
Err(prometeu_vm::IntrinsicExecutionError::Numeric(e)) => {
println!("trap:{:x} {}", e.code, m.cost_cycles)
}
Err(e) => panic!("{e:?}"),
}
} else {
let mut source = String::new();
for v in args {
source.push_str(&match v {
Value::Float(x) => format!("PUSH_F64 f64:0x{:016x}\n", x.to_bits()),
Value::Int32(x) => format!("PUSH_I32 {x}\n"),
Value::Int64(x) => format!("PUSH_I64 {x}\n"),
_ => unreachable!(),
});
}
source.push_str(op);
source.push_str("\nHALT");
let bytes = prometeu_test_support::program::TestProgram::single(
assemble(&source).unwrap(),
Default::default(),
0,
8,
)
.serialize();
let mut vm = VirtualMachine::default();
vm.initialize(bytes).unwrap();
vm.prepare_call("0").unwrap();
let r = vm.run_budget(100, &mut NoNative, &mut HostContext::new(None)).unwrap();
match r.reason {
LogicalFrameEndingReason::Halted => {
println!("{} {}", text(&vm.operand_stack_top(1)[0]), r.cycles_used)
}
LogicalFrameEndingReason::Trap(e) => {
println!("trap:{:x} {}", e.code, r.cycles_used)
}
e => panic!("{e:?}"),
}
}
}
}
+85 -4
View File
@@ -206,6 +206,7 @@ pub enum IntrinsicExecutionError {
ArityMismatch { expected: usize, got: usize },
TypeMismatch { index: usize, expected: AbiType },
HardwareUnavailable,
Numeric(crate::numeric::NumericError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -226,6 +227,9 @@ pub struct IntrinsicMeta {
pub version: u16,
pub arg_layout: &'static [AbiType],
pub ret_layout: &'static [AbiType],
pub parameter_names: &'static [&'static str],
/// Total virtual call cost; math attempts are charged before checks.
pub cost_cycles: u64,
pub deterministic: bool,
pub may_allocate: bool,
pub implementation: IntrinsicImplementation,
@@ -424,7 +428,23 @@ const COLOR_MAGENTA_SLOTS: [BuiltinConstSlotValue; 1] =
const COLOR_TRANSPARENT_SLOTS: [BuiltinConstSlotValue; 1] =
[BuiltinConstSlotValue::Int64(Color::TRANSPARENT.raw() as i64)];
const BUILTIN_CONSTS: [BuiltinConstMeta; 13] = [
const BUILTIN_CONSTS: [BuiltinConstMeta; 15] = [
BuiltinConstMeta {
key: BuiltinConstKey::new("mathf", "pi", 1),
flat_slot_layout: &SINGLE_FLOAT_RET,
flat_slot_width: 1,
materializer: BuiltinConstMaterializer::Direct(&[BuiltinConstSlotValue::Float(
f64::from_bits(crate::numeric::PI_BITS),
)]),
},
BuiltinConstMeta {
key: BuiltinConstKey::new("mathf", "tau", 1),
flat_slot_layout: &SINGLE_FLOAT_RET,
flat_slot_width: 1,
materializer: BuiltinConstMaterializer::Direct(&[BuiltinConstSlotValue::Float(
f64::from_bits(crate::numeric::TAU_BITS),
)]),
},
BuiltinConstMeta {
key: BuiltinConstKey::new("vec2", "zero", 1),
flat_slot_layout: &VEC2_ZERO_LAYOUT,
@@ -491,6 +511,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &VEC2_DOT_ARGS,
ret_layout: &SINGLE_FLOAT_RET,
parameter_names: &["ax", "ay", "bx", "by"],
cost_cycles: 10,
deterministic: true,
may_allocate: false,
implementation: vec2_dot,
@@ -502,6 +524,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &VEC2_LENGTH_ARGS,
ret_layout: &SINGLE_FLOAT_RET,
parameter_names: &["x", "y"],
cost_cycles: 40,
deterministic: true,
may_allocate: false,
implementation: vec2_length,
@@ -513,6 +537,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &INT_RET,
ret_layout: &COLOR_RET,
parameter_names: &["raw"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_from_raw,
@@ -524,6 +550,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_RGB_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &["r", "g", "b"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_rgb,
@@ -535,6 +563,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_RGBA_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &["r", "g", "b", "a"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_rgba,
@@ -546,6 +576,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_HTML_RGBA_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &["value"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_html_rgba,
@@ -557,6 +589,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &INT_RET,
ret_layout: &COLOR_RET,
parameter_names: &["value"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_gray_scale,
@@ -568,6 +602,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_ARGS,
ret_layout: &INT_RET,
parameter_names: &["color"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_hex,
@@ -579,6 +615,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_ARGS,
ret_layout: &INT_RET,
parameter_names: &["color"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_alpha,
@@ -590,6 +628,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_black,
@@ -601,6 +641,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_white,
@@ -612,6 +654,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_red,
@@ -623,6 +667,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_green,
@@ -634,6 +680,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_blue,
@@ -645,6 +693,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_yellow,
@@ -656,6 +706,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_orange,
@@ -667,6 +719,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_indigo,
@@ -678,6 +732,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_gray,
@@ -689,6 +745,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_cyan,
@@ -700,6 +758,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_magenta,
@@ -711,6 +771,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_transparent,
@@ -743,6 +805,7 @@ pub fn lookup_intrinsic(owner: &str, name: &str, version: u16) -> Option<&'stati
INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.find(|meta| meta.owner == owner && meta.name == name && meta.version == version)
}
@@ -750,6 +813,7 @@ pub fn lookup_intrinsic_by_id(id: u32) -> Option<&'static IntrinsicMeta> {
INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.find(|meta| meta.id == id)
}
@@ -841,6 +905,7 @@ fn vec2_dot(
args: &[Value],
_ctx: &mut HostContext<'_>,
) -> Result<Vec<Value>, IntrinsicExecutionError> {
lookup_intrinsic_by_id(0x1000).unwrap().validate_argument_values(args)?;
if args.len() != 4 {
return Err(IntrinsicExecutionError::ArityMismatch { expected: 4, got: args.len() });
}
@@ -848,7 +913,7 @@ fn vec2_dot(
let ay = expect_float_arg(args, 1)?;
let bx = expect_float_arg(args, 2)?;
let by = expect_float_arg(args, 3)?;
Ok(vec![Value::Float((ax * bx) + (ay * by))])
Ok(vec![Value::Float(crate::numeric::dot([ax, ay, bx, by])?)])
}
fn vec2_length(
@@ -858,9 +923,10 @@ fn vec2_length(
if args.len() != 2 {
return Err(IntrinsicExecutionError::ArityMismatch { expected: 2, got: args.len() });
}
lookup_intrinsic_by_id(0x1001).unwrap().validate_argument_values(args)?;
let x = expect_float_arg(args, 0)?;
let y = expect_float_arg(args, 1)?;
Ok(vec![Value::Float((x * x + y * y).sqrt())])
Ok(vec![Value::Float(crate::numeric::length(x, y)?)])
}
fn color_value(color: Color) -> Vec<Value> {
@@ -1041,7 +1107,11 @@ pub(crate) fn metered_lookup_intrinsic(
id: u32,
budget: &mut prometeu_bytecode::load_limits::LoadBudget,
) -> Result<Option<&'static IntrinsicMeta>, prometeu_bytecode::load_limits::LoadFailure> {
for meta in INTRINSICS.iter().chain(crate::input_intrinsics::INPUT_INTRINSICS.iter()) {
for meta in INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
{
budget.work(1)?;
if meta.id == id {
return Ok(Some(meta));
@@ -1210,3 +1280,14 @@ mod tests {
assert_eq!(pixel.field("color").map(|field| field.start_slot), Some(2));
}
}
/// Runtime-owned catalogue, including input and scalar math.
pub fn intrinsic_catalog() -> impl Iterator<Item = &'static IntrinsicMeta> {
INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
}
pub fn builtin_constant_catalog() -> impl Iterator<Item = &'static BuiltinConstMeta> {
BUILTIN_CONSTS.iter()
}
+69
View File
@@ -0,0 +1,69 @@
//! Exported handoff artifacts are generated from runtime metadata.
use crate::{AbiType, BuiltinScalarType, builtin_constant_catalog, intrinsic_catalog};
use prometeu_bytecode::Value;
use std::fmt::Write;
fn atom(t: AbiType) -> String {
match t {
AbiType::Scalar(BuiltinScalarType::Int32) => "Int32".into(),
AbiType::Scalar(BuiltinScalarType::Int64) => "Int64".into(),
AbiType::Scalar(BuiltinScalarType::Float) => "Float".into(),
AbiType::Scalar(BuiltinScalarType::Bool) => "Bool".into(),
AbiType::Scalar(BuiltinScalarType::String) => "String".into(),
AbiType::Builtin(k) => format!("builtin:{}", k.name),
AbiType::DynamicTag => "DynamicTag".into(),
AbiType::DynamicPayload => "DynamicPayload".into(),
}
}
pub fn intrinsic_catalog_csv() -> String {
let mut out = String::from(
"final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles\n",
);
let mut entries: Vec<_> = intrinsic_catalog().collect();
entries.sort_by_key(|m| m.id);
for m in entries {
writeln!(
&mut out,
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{}",
m.id,
m.id,
m.owner,
m.name,
m.version,
m.owner,
m.name,
m.arg_slots(),
m.ret_slots(),
m.arg_layout.iter().copied().map(atom).collect::<Vec<_>>().join("|"),
m.ret_layout.iter().copied().map(atom).collect::<Vec<_>>().join("|"),
m.deterministic,
m.may_allocate,
m.parameter_names.join("|"),
m.cost_cycles
)
.unwrap();
}
out
}
pub fn builtin_constant_catalog_csv() -> String {
let mut out = String::from("target,name,version,slot,carrier,bits_or_value\n");
let mut entries: Vec<_> = builtin_constant_catalog().collect();
entries.sort_by_key(|m| m.key.key());
for m in entries {
for (slot, v) in m.materialize().expect("canonical constant").iter().enumerate() {
let (carrier, value) = match v {
Value::Float(v) => ("Float", format!("0x{:016X}", v.to_bits())),
Value::Int32(v) => ("Int32", v.to_string()),
Value::Int64(v) => ("Int64", v.to_string()),
Value::Boolean(v) => ("Bool", v.to_string()),
_ => unreachable!("canonical constant carrier"),
};
writeln!(
&mut out,
"{},{},{},{},{},{}",
m.key.target, m.key.name, m.key.version, slot, carrier, value
)
.unwrap();
}
}
out
}
@@ -21,6 +21,8 @@ const fn query(
version: 1,
arg_layout: &[],
ret_layout,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation,
+8 -2
View File
@@ -1,8 +1,13 @@
#[cfg(test)]
extern crate self as prometeu_vm;
mod builtins;
mod catalog;
pub use catalog::{builtin_constant_catalog_csv, intrinsic_catalog_csv};
mod call_frame;
mod input_intrinsics;
mod math_intrinsics;
mod numeric;
pub use numeric::NumericError;
mod local_addressing;
// Keep the verifier internal in production builds, but expose it for integration tests
// so the golden verifier suite can exercise it without widening the public API in releases.
@@ -34,8 +39,9 @@ pub use builtins::{
AbiType, BuiltinConstKey, BuiltinConstMaterializer, BuiltinConstMeta, BuiltinConstSlotValue,
BuiltinFieldMeta, BuiltinLayoutType, BuiltinScalarType, BuiltinTypeKey, BuiltinTypeMeta,
BuiltinTypeShape, BuiltinValueError, IntrinsicExecutionError, IntrinsicImplementation,
IntrinsicKey, IntrinsicMeta, lookup_builtin_constant, lookup_builtin_type, lookup_intrinsic,
lookup_intrinsic_by_id, materialize_builtin_constant,
IntrinsicKey, IntrinsicMeta, builtin_constant_catalog, intrinsic_catalog,
lookup_builtin_constant, lookup_builtin_type, lookup_intrinsic, lookup_intrinsic_by_id,
materialize_builtin_constant,
};
pub use prometeu_hal::{HostContext, HostReturn, NativeInterface, SyscallId};
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
@@ -0,0 +1,149 @@
//! Exact scalar identities. Public math overloads are a consumer projection.
use crate::builtins::{AbiType, BuiltinScalarType, IntrinsicExecutionError as E, IntrinsicMeta};
use crate::numeric::{self, NumericError};
use prometeu_bytecode::{TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE, Value};
use prometeu_hal::HostContext;
const I32: AbiType = AbiType::Scalar(BuiltinScalarType::Int32);
const I64: AbiType = AbiType::Scalar(BuiltinScalarType::Int64);
const FLOAT: AbiType = AbiType::Scalar(BuiltinScalarType::Float);
const fn entry<const ID: u32>(
owner: &'static str,
name: &'static str,
arg_layout: &'static [AbiType],
ret_layout: &'static [AbiType],
parameter_names: &'static [&'static str],
cost_cycles: u64,
) -> IntrinsicMeta {
IntrinsicMeta {
id: ID,
owner,
name,
version: 1,
arg_layout,
ret_layout,
parameter_names,
cost_cycles,
deterministic: true,
may_allocate: false,
implementation: execute::<ID>,
}
}
pub(crate) const MATH_INTRINSICS: [IntrinsicMeta; 26] = [
entry::<0x3000>("math.i32", "min", &[I32, I32], &[I32], &["a", "b"], 2),
entry::<0x3001>("math.i32", "max", &[I32, I32], &[I32], &["a", "b"], 2),
entry::<0x3002>("math.i32", "clamp", &[I32, I32, I32], &[I32], &["value", "min", "max"], 4),
entry::<0x3003>("math.i32", "abs", &[I32], &[I32], &["value"], 2),
entry::<0x3004>("math.i64", "min", &[I64, I64], &[I64], &["a", "b"], 2),
entry::<0x3005>("math.i64", "max", &[I64, I64], &[I64], &["a", "b"], 2),
entry::<0x3006>("math.i64", "clamp", &[I64, I64, I64], &[I64], &["value", "min", "max"], 4),
entry::<0x3007>("math.i64", "abs", &[I64], &[I64], &["value"], 2),
entry::<0x3008>("mathf", "min", &[FLOAT, FLOAT], &[FLOAT], &["a", "b"], 2),
entry::<0x3009>("mathf", "max", &[FLOAT, FLOAT], &[FLOAT], &["a", "b"], 2),
entry::<0x300a>(
"mathf",
"clamp",
&[FLOAT, FLOAT, FLOAT],
&[FLOAT],
&["value", "min", "max"],
4,
),
entry::<0x300b>("mathf", "abs", &[FLOAT], &[FLOAT], &["value"], 2),
entry::<0x300c>("mathf", "floor", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x300d>("mathf", "ceil", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x300e>("mathf", "trunc", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x300f>("mathf", "round", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x3010>("mathf", "sqrt", &[FLOAT], &[FLOAT], &["value"], 16),
entry::<0x3011>("mathf", "sin", &[FLOAT], &[FLOAT], &["angle"], 32),
entry::<0x3012>("mathf", "cos", &[FLOAT], &[FLOAT], &["angle"], 32),
entry::<0x3013>("mathf", "atan2", &[FLOAT, FLOAT], &[FLOAT], &["y", "x"], 48),
entry::<0x3014>("math.i32", "to_i64", &[I32], &[I64], &["value"], 2),
entry::<0x3015>("math.i64", "to_i32", &[I64], &[I32], &["value"], 2),
entry::<0x3016>("math.i32", "to_float", &[I32], &[FLOAT], &["value"], 2),
entry::<0x3017>("math.i64", "to_float", &[I64], &[FLOAT], &["value"], 2),
entry::<0x3018>("mathf", "to_i32", &[FLOAT], &[I32], &["value"], 2),
entry::<0x3019>("mathf", "to_i64", &[FLOAT], &[I64], &["value"], 2),
];
impl From<NumericError> for E {
fn from(error: NumericError) -> Self {
Self::Numeric(error)
}
}
fn integer(args: &[Value], offset: u32, narrow: bool) -> Result<Value, E> {
let mut a = [0i64; 3];
for (i, value) in args.iter().enumerate() {
a[i] = match value {
Value::Int32(v) => i64::from(*v),
Value::Int64(v) => *v,
_ => unreachable!("validated exact integer carrier"),
};
}
let result = match offset {
0 => a[0].min(a[1]),
1 => a[0].max(a[1]),
2 => {
if a[1] > a[2] {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN).into());
}
a[0].clamp(a[1], a[2])
}
3 => {
if (narrow && a[0] == i64::from(i32::MIN)) || a[0] == i64::MIN {
return Err(NumericError::new(TRAP_NUMERIC_RANGE).into());
}
a[0].abs()
}
_ => unreachable!("private integer operation"),
};
Ok(if narrow { Value::Int32(result as i32) } else { Value::Int64(result) })
}
fn execute<const ID: u32>(args: &[Value], _: &mut HostContext<'_>) -> Result<Vec<Value>, E> {
let meta = crate::lookup_intrinsic_by_id(ID).expect("static scalar identity");
meta.validate_argument_values(args)?;
if ID < 0x3008 {
return Ok(vec![integer(args, (ID - 0x3000) % 4, ID < 0x3004)?]);
}
let mut floats = [0.0; 3];
for (i, value) in args.iter().enumerate() {
if let Value::Float(v) = value {
floats[i] = *v;
}
}
if (0x3008..=0x3013).contains(&ID) || ID >= 0x3018 {
numeric::check_inputs(&floats[..args.len()])?;
}
let x = floats[0];
let value = match ID {
0x3008 => Value::Float(numeric::min(x, floats[1])),
0x3009 => Value::Float(numeric::max(x, floats[1])),
0x300a => Value::Float(numeric::clamp(x, floats[1], floats[2])?),
0x300b => Value::Float(numeric::abs(x)),
0x300c => Value::Float(numeric::floor(x)?),
0x300d => Value::Float(numeric::ceil(x)?),
0x300e => Value::Float(numeric::trunc(x)?),
0x300f => Value::Float(numeric::round(x)?),
0x3010 => Value::Float(numeric::sqrt(x)?),
0x3011 => Value::Float(numeric::sin(x)?),
0x3012 => Value::Float(numeric::cos(x)?),
0x3013 => Value::Float(numeric::atan2(x, floats[1])?),
0x3014 => {
let Value::Int32(v) = args[0] else { unreachable!() };
Value::Int64(i64::from(v))
}
0x3015 => {
let Value::Int64(v) = args[0] else { unreachable!() };
Value::Int32(i32::try_from(v).map_err(|_| NumericError::new(TRAP_NUMERIC_RANGE))?)
}
0x3016 => {
let Value::Int32(v) = args[0] else { unreachable!() };
Value::Float(numeric::from_i64(i64::from(v)))
}
0x3017 => {
let Value::Int64(v) = args[0] else { unreachable!() };
Value::Float(numeric::from_i64(v))
}
0x3018 => Value::Int32(numeric::to_i64(x, 32)? as i32),
0x3019 => Value::Int64(numeric::to_i64(x, 64)?),
_ => unreachable!("static scalar identity"),
};
Ok(vec![value])
}
+324
View File
@@ -0,0 +1,324 @@
//! Canonical binary64 adapter. Host f64 is a bit carrier only; arithmetic and
//! comparisons use SoftF64. Integer conversions and ties-even rounding use bits.
use fpmath::SoftF64 as F;
use prometeu_bytecode::{TRAP_DIV_ZERO, TRAP_NON_FINITE, TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE};
pub(crate) const PI_BITS: u64 = 0x4009_21fb_5444_2d18;
pub(crate) const TAU_BITS: u64 = 0x4019_21fb_5444_2d18;
const PI_2_BITS: u64 = 0x3ff9_21fb_5444_2d18;
const SIGN: u64 = 1 << 63;
const MAG: u64 = !SIGN;
const EXP: u64 = 0x7ff0_0000_0000_0000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NumericError {
pub code: u32,
pub argument: Option<usize>,
}
impl NumericError {
pub(crate) fn new(code: u32) -> Self {
Self { code, argument: None }
}
}
pub(crate) type Result<T> = std::result::Result<T, NumericError>;
pub(crate) fn finite(x: f64) -> bool {
x.to_bits() & EXP != EXP
}
pub(crate) fn check_inputs(values: &[f64]) -> Result<()> {
for (argument, &value) in values.iter().enumerate() {
if !finite(value) {
return Err(NumericError { code: TRAP_NON_FINITE, argument: Some(argument) });
}
}
Ok(())
}
fn soft(x: f64) -> F {
F::from_bits(x.to_bits())
}
fn output(x: F) -> Result<f64> {
let bits = x.to_bits();
if bits & EXP == EXP {
Err(NumericError::new(TRAP_NUMERIC_RANGE))
} else {
Ok(f64::from_bits(bits))
}
}
pub(crate) fn zero(x: f64) -> bool {
x.to_bits() & MAG == 0
}
pub(crate) fn cmp(a: f64, b: f64) -> std::cmp::Ordering {
// All callers check finitude first. Both zeros compare equal.
soft(a).partial_cmp(&soft(b)).expect("finite binary64 comparison")
}
pub(crate) fn abs(x: f64) -> f64 {
f64::from_bits(x.to_bits() & MAG)
}
pub(crate) fn neg(x: f64) -> Result<f64> {
check_inputs(&[x])?;
Ok(f64::from_bits(x.to_bits() ^ SIGN))
}
pub(crate) fn min(a: f64, b: f64) -> f64 {
if zero(a) && zero(b) {
f64::from_bits(a.to_bits() | b.to_bits())
} else if cmp(a, b).is_gt() {
b
} else {
a
}
}
pub(crate) fn max(a: f64, b: f64) -> f64 {
if zero(a) && zero(b) {
f64::from_bits(a.to_bits() & b.to_bits())
} else if cmp(a, b).is_lt() {
b
} else {
a
}
}
pub(crate) fn clamp(value: f64, lo: f64, hi: f64) -> Result<f64> {
check_inputs(&[value, lo, hi])?;
if cmp(lo, hi).is_gt() {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN));
}
Ok(min(max(value, lo), hi))
}
pub(crate) fn add(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
output(soft(a) + soft(b))
}
pub(crate) fn sub(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
output(soft(a) - soft(b))
}
pub(crate) fn mul(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
output(soft(a) * soft(b))
}
pub(crate) fn div(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
if zero(b) {
return Err(NumericError::new(TRAP_DIV_ZERO));
}
output(soft(a) / soft(b))
}
pub(crate) fn sqrt(x: f64) -> Result<f64> {
check_inputs(&[x])?;
if !zero(x) && x.to_bits() & SIGN != 0 {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN));
}
output(fpmath::sqrt(soft(x)))
}
pub(crate) fn sin(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::sin(soft(x)))
}
pub(crate) fn cos(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::cos(soft(x)))
}
pub(crate) fn atan2(y: f64, x: f64) -> Result<f64> {
check_inputs(&[y, x])?;
let sign_y = y.to_bits() & SIGN;
if zero(y) {
if zero(x) {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN));
}
return Ok(f64::from_bits(sign_y | if x.to_bits() & SIGN != 0 { PI_BITS } else { 0 }));
}
if zero(x) {
return Ok(f64::from_bits(sign_y | PI_2_BITS));
}
output(fpmath::atan2(soft(y), soft(x)))
}
pub(crate) fn floor(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::floor(soft(x)))
}
pub(crate) fn ceil(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::ceil(soft(x)))
}
pub(crate) fn trunc(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::trunc(soft(x)))
}
pub(crate) fn round(x: f64) -> Result<f64> {
check_inputs(&[x])?;
let bits = x.to_bits();
let sign = bits & SIGN;
let magnitude = bits & MAG;
let exponent = ((magnitude >> 52) as i32) - 1023;
let rounded = if exponent >= 52 {
magnitude
} else if exponent < -1 {
0
} else if exponent == -1 {
// Exactly +/-0.5 ties to signed zero, all larger magnitudes to +/-1.
if magnitude == 0x3fe0_0000_0000_0000 { 0 } else { 0x3ff0_0000_0000_0000 }
} else {
let shift = 52 - exponent;
let unit = 1u64 << shift;
let remainder = magnitude & (unit - 1);
let half = unit >> 1;
let integral = magnitude & !(unit - 1);
integral
+ if remainder > half || (remainder == half && integral & unit != 0) { unit } else { 0 }
};
Ok(f64::from_bits(sign | rounded))
}
pub(crate) fn from_i64(value: i64) -> f64 {
let magnitude = value.unsigned_abs();
if magnitude == 0 {
return f64::from_bits(0);
}
let sign = if value < 0 { SIGN } else { 0 };
let mut exponent = 63 - magnitude.leading_zeros();
let mut significand = if exponent <= 52 {
magnitude << (52 - exponent)
} else {
let shift = exponent - 52;
let unit = 1u64 << shift;
let mut sig = magnitude >> shift;
let rem = magnitude & (unit - 1);
if rem > unit / 2 || (rem == unit / 2 && sig & 1 != 0) {
sig += 1;
}
sig
};
if significand == 1u64 << 53 {
significand >>= 1;
exponent += 1;
}
f64::from_bits(sign | (u64::from(exponent + 1023) << 52) | (significand & ((1 << 52) - 1)))
}
pub(crate) fn to_i64(x: f64, width: u32) -> Result<i64> {
check_inputs(&[x])?;
let bits = x.to_bits();
let exponent = ((bits & EXP) >> 52) as i32 - 1023;
if exponent < 0 {
return Ok(0);
}
if exponent > 63 {
return Err(NumericError::new(TRAP_NUMERIC_RANGE));
}
let significand = (bits & ((1 << 52) - 1)) | (1 << 52);
let magnitude = if exponent >= 52 {
significand << (exponent - 52)
} else {
significand >> (52 - exponent)
};
let negative = bits & SIGN != 0;
let limit = 1u64 << (width - 1);
if magnitude > limit || (magnitude == limit && !negative) {
return Err(NumericError::new(TRAP_NUMERIC_RANGE));
}
// unsigned magnitude handles exactly -2^63 without an intermediate overflow.
Ok(if negative { magnitude.wrapping_neg() as i64 } else { magnitude as i64 })
}
pub(crate) fn dot(a: [f64; 4]) -> Result<f64> {
check_inputs(&a)?;
let p1 = mul(a[0], a[2])?;
let p2 = mul(a[1], a[3])?;
add(p1, p2)
}
pub(crate) fn length(x: f64, y: f64) -> Result<f64> {
check_inputs(&[x, y])?;
let ax = abs(x);
let ay = abs(y);
let m = max(ax, ay);
let n = min(ax, ay);
if zero(m) {
return Ok(f64::from_bits(0));
}
let r = div(n, m)?;
let q = mul(r, r)?;
let s = add(f64::from_bits(0x3ff0_0000_0000_0000), q)?;
let t = sqrt(s)?;
mul(m, t)
}
fn promoted(value: &prometeu_bytecode::Value) -> Option<f64> {
use prometeu_bytecode::Value;
match value {
Value::Int32(v) => Some(from_i64(i64::from(*v))),
Value::Int64(v) => Some(from_i64(*v)),
Value::Float(v) => Some(*v),
_ => None,
}
}
pub(crate) fn opcode_binary(
op: prometeu_bytecode::isa::core::CoreOpCode,
a: &prometeu_bytecode::Value,
b: &prometeu_bytecode::Value,
) -> Result<prometeu_bytecode::Value> {
use prometeu_bytecode::isa::core::CoreOpCode as Op;
use prometeu_bytecode::{TRAP_TYPE, Value};
if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) {
let (Some(a), Some(b)) = (promoted(a), promoted(b)) else {
return Err(NumericError::new(TRAP_TYPE));
};
return Ok(Value::Float(match op {
Op::Add => add(a, b)?,
Op::Sub => sub(a, b)?,
Op::Mul => mul(a, b)?,
Op::Div => div(a, b)?,
_ => unreachable!(),
}));
}
let (a, b, narrow) = match (a, b) {
(Value::Int32(a), Value::Int32(b)) => (i64::from(*a), i64::from(*b), true),
(Value::Int32(a), Value::Int64(b)) => (i64::from(*a), *b, false),
(Value::Int64(a), Value::Int32(b)) => (*a, i64::from(*b), false),
(Value::Int64(a), Value::Int64(b)) => (*a, *b, false),
_ => return Err(NumericError::new(TRAP_TYPE)),
};
if op == Op::Div && b == 0 {
return Err(NumericError::new(TRAP_DIV_ZERO));
}
if narrow {
let (a, b) = (a as i32, b as i32);
return Ok(Value::Int32(match op {
Op::Add => a.wrapping_add(b),
Op::Sub => a.wrapping_sub(b),
Op::Mul => a.wrapping_mul(b),
Op::Div => a.wrapping_div(b),
_ => unreachable!(),
}));
}
Ok(Value::Int64(match op {
Op::Add => a.wrapping_add(b),
Op::Sub => a.wrapping_sub(b),
Op::Mul => a.wrapping_mul(b),
Op::Div => a.wrapping_div(b),
_ => unreachable!(),
}))
}
pub(crate) fn compare_values(
a: &prometeu_bytecode::Value,
b: &prometeu_bytecode::Value,
) -> Result<Option<std::cmp::Ordering>> {
use prometeu_bytecode::Value;
if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) {
let (Some(a), Some(b)) = (promoted(a), promoted(b)) else {
return Ok(None);
};
check_inputs(&[a, b])?;
Ok(Some(cmp(a, b)))
} else {
Ok(a.partial_cmp(b))
}
}
pub(crate) fn equal_values(
a: &prometeu_bytecode::Value,
b: &prometeu_bytecode::Value,
) -> Result<bool> {
use prometeu_bytecode::Value;
if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) {
Ok(compare_values(a, b)? == Some(std::cmp::Ordering::Equal))
} else {
Ok(a == b)
}
}
@@ -70,7 +70,7 @@ fn publication_shares_owners_and_preserves_payload_bits_and_names() {
K::Null,
K::String("é猫".into()),
K::String(String::new()),
K::Float64(f64::from_bits(0x7ff8000000000042)),
K::Float64(f64::from_bits(0x0008000000000042)),
K::Float64(-0.0),
];
let bytes = fixture(&[1, 0], 0, &constants, Some(&debug), &[]);
@@ -85,7 +85,7 @@ fn publication_shares_owners_and_preserves_payload_bits_and_names() {
assert!(image.lease_constant(0).is_none());
let Value::Float(nan) = image.constants()[3] else { panic!() };
let Value::Float(zero) = image.constants()[4] else { panic!() };
assert_eq!(nan.to_bits(), 0x7ff8000000000042);
assert_eq!(nan.to_bits(), 0x0008000000000042);
assert_eq!(zero.to_bits(), (-0.0f64).to_bits());
let projection = image.execution.clone();
assert!(Arc::ptr_eq(&projection.rom, &image.execution.rom));
@@ -111,6 +111,13 @@ fn validate_inner(
Op::PushBool if instruction.imm_u8().unwrap() > 1 => {
return Err(fail(R::BooleanImmediate));
}
Op::PushF64 => {
if instruction.imm_f64().unwrap().to_bits() & 0x7ff0_0000_0000_0000
== 0x7ff0_0000_0000_0000
{
return Err(fail(R::NonFiniteValue).at(2, start + pc));
}
}
Op::PushConst => {
let id = instruction.imm_u32().unwrap();
if id as usize >= constants {
@@ -165,7 +172,7 @@ fn validate_inner(
Op::Intrinsic => {
let id = instruction.imm_u32().unwrap();
if crate::builtins::metered_lookup_intrinsic(id, budget)?.is_none() {
return Err(with_id(reference_error(fail(R::NativeId)), id));
return Err(with_id(fail(R::NativeId), id));
}
}
_ => {}
@@ -445,7 +445,11 @@ fn unreachable_function_constant_boolean_and_native_operands_are_checked() {
assert_eq!((e.reason, e.pc, e.referenced_id), (reason, Some(2), Some(id)));
assert_eq!(
e.code,
if operation == Op::Hostcall { C::InvalidCode } else { C::InvalidReference }
if matches!(operation, Op::Hostcall | Op::Intrinsic) {
C::InvalidCode
} else {
C::InvalidReference
}
);
}
let code = [
@@ -7,6 +7,7 @@ use prometeu_bytecode::{HeapRef, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ValueError {
Type,
NonFinite,
InvalidHandle,
NullReference,
Bounds,
+86 -120
View File
@@ -1,3 +1,4 @@
use crate::numeric;
use crate::resource_budget::BudgetVec;
mod callable;
mod collections;
@@ -65,6 +66,12 @@ pub(crate) enum OpError {
Trap(u32, String),
}
impl From<crate::numeric::NumericError> for OpError {
fn from(error: crate::numeric::NumericError) -> Self {
Self::Trap(error.code, format!("Numeric operation failed: {error:?}"))
}
}
impl From<TrapInfo> for LogicalFrameEndingReason {
fn from(info: TrapInfo) -> Self {
LogicalFrameEndingReason::Trap(info)
@@ -276,6 +283,15 @@ impl VirtualMachine {
self.cycles += opcode.cycles();
}
let charged_math = if opcode == OpCode::Intrinsic {
lookup_intrinsic_by_id(instr.imm_u32().unwrap())
.filter(|m| m.owner == "vec2" || m.owner == "mathf" || m.owner.starts_with("math."))
} else {
None
};
if let Some(meta) = charged_math {
self.cycles += meta.cost_cycles;
}
// Execute
match opcode {
OpCode::Nop => {}
@@ -436,117 +452,40 @@ impl VirtualMachine {
{
self.execute_string_add(opcode, start_pc as u32)?;
} else {
self.binary_op(opcode, start_pc as u32, |a, b| match (&a, &b) {
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_add(*b))),
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_add(*b))),
(Value::Int32(a), Value::Int64(b)) => {
Ok(Value::Int64((*a as i64).wrapping_add(*b)))
}
(Value::Int64(a), Value::Int32(b)) => {
Ok(Value::Int64(a.wrapping_add(*b as i64)))
}
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
(Value::Int32(a), Value::Float(b)) => Ok(Value::Float(*a as f64 + b)),
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a + *b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(*a as f64 + b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a + *b as f64)),
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for ADD".into())),
self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::opcode_binary(opcode, &a, &b).map_err(|e| {
if e.code == TRAP_TYPE {
OpError::Trap(
TRAP_TYPE,
format!(
"Invalid types for {}",
format!("{opcode:?}").to_uppercase()
),
)
} else {
OpError::from(e)
}
})
})?;
}
}
OpCode::Sub => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_sub(b))),
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_sub(b))),
(Value::Int32(a), Value::Int64(b)) => Ok(Value::Int64((a as i64).wrapping_sub(b))),
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a.wrapping_sub(b as i64))),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a - b)),
(Value::Int32(a), Value::Float(b)) => Ok(Value::Float(a as f64 - b)),
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a - b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(a as f64 - b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a - b as f64)),
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for SUB".into())),
})?,
OpCode::Mul => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_mul(b))),
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_mul(b))),
(Value::Int32(a), Value::Int64(b)) => Ok(Value::Int64((a as i64).wrapping_mul(b))),
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a.wrapping_mul(b as i64))),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a * b)),
(Value::Int32(a), Value::Float(b)) => Ok(Value::Float(a as f64 * b)),
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a * b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(a as f64 * b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a * b as f64)),
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for MUL".into())),
})?,
OpCode::Div => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int32(a.wrapping_div(b)))
}
(Value::Int64(a), Value::Int64(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int64(a.wrapping_div(b)))
}
(Value::Int32(a), Value::Int64(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int64((a as i64).wrapping_div(b)))
}
(Value::Int64(a), Value::Int32(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int64(a.wrapping_div(b as i64)))
}
(Value::Float(a), Value::Float(b)) => {
if b == 0.0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a / b))
}
(Value::Int32(a), Value::Float(b)) => {
if b == 0.0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a as f64 / b))
}
(Value::Float(a), Value::Int32(b)) => {
if b == 0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a / b as f64))
}
(Value::Int64(a), Value::Float(b)) => {
if b == 0.0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a as f64 / b))
}
(Value::Float(a), Value::Int64(b)) => {
if b == 0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a / b as f64))
}
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for DIV".into())),
})?,
OpCode::Sub | OpCode::Mul | OpCode::Div => {
self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::opcode_binary(opcode, &a, &b).map_err(|e| {
if e.code == TRAP_TYPE {
OpError::Trap(
TRAP_TYPE,
format!(
"Invalid types for {}",
format!("{opcode:?}").to_uppercase()
),
)
} else {
OpError::from(e)
}
})
})?
}
OpCode::Mod => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => {
if b == 0 {
@@ -562,29 +501,33 @@ impl VirtualMachine {
}
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for MOD".into())),
})?,
OpCode::Eq => {
self.binary_op(opcode, start_pc as u32, |a, b| Ok(Value::Boolean(a == b)))?
}
OpCode::Neq => {
self.binary_op(opcode, start_pc as u32, |a, b| Ok(Value::Boolean(a != b)))?
}
OpCode::Eq => self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::equal_values(&a, &b).map(Value::Boolean).map_err(OpError::from)
})?,
OpCode::Neq => self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::equal_values(&a, &b).map(|v| Value::Boolean(!v)).map_err(OpError::from)
})?,
OpCode::Lt => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o == std::cmp::Ordering::Less))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for LT".into()))
})?,
OpCode::Gt => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o == std::cmp::Ordering::Greater))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for GT".into()))
})?,
OpCode::Lte => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o != std::cmp::Ordering::Greater))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for LTE".into()))
})?,
OpCode::Gte => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o != std::cmp::Ordering::Less))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for GTE".into()))
})?,
@@ -657,7 +600,12 @@ impl VirtualMachine {
Value::Int64(a) => {
self.push_trap(Value::Int64(a.wrapping_neg()), opcode, start_pc as u32)?
}
Value::Float(a) => self.push_trap(Value::Float(-a), opcode, start_pc as u32)?,
Value::Float(a) => {
let result = numeric::neg(a).map_err(|e| {
self.trap(e.code, opcode as u16, format!("NEG: {e:?}"), start_pc as u32)
})?;
self.push_trap(Value::Float(result), opcode, start_pc as u32)?;
}
_ => {
return Err(self.trap(
TRAP_TYPE,
@@ -997,6 +945,15 @@ impl VirtualMachine {
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::Numeric(error) => self.trap(
error.code,
opcode as u16,
format!(
"Intrinsic {}.{}: {:?}",
intrinsic.owner, intrinsic.name, error
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::HardwareUnavailable => self.trap(
TRAP_UNAVAILABLE,
OpCode::Intrinsic as u16,
@@ -1027,6 +984,15 @@ impl VirtualMachine {
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::Numeric(error) => self.trap(
error.code,
opcode as u16,
format!(
"Intrinsic {}.{} result: {:?}",
intrinsic.owner, intrinsic.name, error
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::HardwareUnavailable => self.trap(
TRAP_UNAVAILABLE,
OpCode::Intrinsic as u16,
@@ -1073,7 +1039,7 @@ impl VirtualMachine {
}
// Control attempts were already charged before validation.
if !charged_control {
if !charged_control && charged_math.is_none() {
self.cycles += opcode.cycles();
}
Ok(())
@@ -34,11 +34,17 @@ impl VirtualMachine {
LogicalFrameEndingReason::Trap(self.program.create_trap(code, opcode, message, pc))
}
pub fn push(&mut self, val: Value) -> Result<(), ResourceFailure> {
let growth = self.operand_stack.prepare_growth(1)?;
let val = self.import_string_value(&val)?;
pub fn push(&mut self, val: Value) -> Result<(), VmFault> {
if matches!(&val,Value::Float(x) if !crate::numeric::finite(*x)) {
return Err(VmFault::Trap(
prometeu_bytecode::TRAP_NON_FINITE,
"Native stack import contains a non-finite Float".into(),
));
}
let growth = self.operand_stack.prepare_growth(1).map_err(VmFault::ResourceLimit)?;
let val = self.import_string_value(&val).map_err(VmFault::ResourceLimit)?;
self.operand_stack.commit_growth(growth);
self.operand_stack.push(val)
self.operand_stack.push(val).map_err(VmFault::ResourceLimit)
}
pub(super) fn push_trap(
@@ -20,6 +20,7 @@ impl VirtualMachine {
pub(super) fn value_error_code(error: ValueError) -> u32 {
match error {
ValueError::Type => TRAP_TYPE,
ValueError::NonFinite => prometeu_bytecode::TRAP_NON_FINITE,
ValueError::InvalidHandle => TRAP_INVALID_HANDLE,
ValueError::NullReference => TRAP_NULL_REFERENCE,
ValueError::Bounds => TRAP_OOB,
@@ -74,6 +75,12 @@ impl VirtualMachine {
if values.len() != slot {
return Err((slot, ValueError::Type));
}
// Validate the complete signature before classifying numeric content.
if let Some(slot) =
values.iter().position(|v| matches!(v,Value::Float(x) if !crate::numeric::finite(*x)))
{
return Err((slot, ValueError::NonFinite));
}
Ok(())
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,434 @@
use prometeu_bytecode::load_limits::{LoadBudget, LoadCode as C, LoadReason as R};
use prometeu_bytecode::{
TRAP_DIV_ZERO, TRAP_NON_FINITE as NON_FINITE, TRAP_NUMERIC_DOMAIN as DOMAIN,
TRAP_NUMERIC_RANGE as RANGE, TRAP_TYPE, Value, assemble,
};
use prometeu_hal::vm_fault::VmFault;
use prometeu_test_support::program::TestProgram;
use prometeu_vm::resource_budget::RuntimeLimits;
use prometeu_vm::{
HostContext, HostReturn, IntrinsicExecutionError as E, LogicalFrameEndingReason as End,
NativeInterface, ValidatedProgramImage, VirtualMachine, VmInitError, lookup_intrinsic_by_id,
materialize_builtin_constant,
};
struct NoNative;
impl NativeInterface for NoNative {
fn syscall(
&mut self,
_: u32,
_: &[Value],
_: &mut HostReturn,
_: &mut HostContext,
) -> Result<(), VmFault> {
panic!("unexpected native call")
}
}
fn call(id: u32, args: &[Value]) -> Result<Value, E> {
let m = lookup_intrinsic_by_id(id).unwrap();
(m.implementation)(args, &mut HostContext::new(None)).map(|mut v| v.remove(0))
}
fn floats(id: u32, xs: &[f64]) -> Result<u64, u32> {
match call(id, &xs.iter().copied().map(Value::Float).collect::<Vec<_>>()) {
Ok(Value::Float(x)) => Ok(x.to_bits()),
Err(E::Numeric(e)) => Err(e.code),
v => panic!("{v:?}"),
}
}
fn vm(source: &str, limits: RuntimeLimits) -> VirtualMachine {
let bytes =
TestProgram::single(assemble(source).unwrap(), Default::default(), 0, 8).serialize();
let image =
ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(Default::default()), 0).unwrap();
let mut vm = VirtualMachine::from_image(image, limits);
vm.prepare_call("0").unwrap();
vm
}
fn run(vm: &mut VirtualMachine, budget: u64) -> prometeu_vm::BudgetReport {
vm.run_budget(budget, &mut NoNative, &mut HostContext::new(None)).unwrap()
}
fn trap(r: &prometeu_vm::BudgetReport) -> &prometeu_bytecode::TrapInfo {
let End::Trap(t) = &r.reason else { panic!("{r:?}") };
t
}
#[test]
fn integer_limits_are_exact_and_abs_does_not_wrap() {
for (base, a, b) in [
(0x3000, Value::Int32(i32::MIN), Value::Int32(i32::MAX)),
(0x3004, Value::Int64(i64::MIN), Value::Int64(i64::MAX)),
] {
assert_eq!(call(base, &[b.clone(), a.clone()]).unwrap(), a);
assert_eq!(call(base + 1, &[a.clone(), b.clone()]).unwrap(), b);
assert!(matches!(call(base+3,&[a.clone()]),Err(E::Numeric(e)) if e.code==RANGE));
assert!(matches!(call(base+2,&[b.clone(),b,a]),Err(E::Numeric(e)) if e.code==DOMAIN));
}
assert_eq!(
call(0x3002, &[Value::Int32(-5), Value::Int32(0), Value::Int32(10)]).unwrap(),
Value::Int32(0)
);
assert!(
matches!(call(0x3002,&[Value::Int32(5),Value::Int32(10),Value::Int32(0)]),Err(E::Numeric(e)) if e.code==DOMAIN)
);
}
#[test]
fn signed_zero_limits_and_rounding_follow_bits() {
for a in [0.0f64, -0.0] {
for b in [0.0f64, -0.0] {
let same = a.to_bits() == b.to_bits();
assert_eq!(
floats(0x3008, &[a, b]),
Ok(if same { a.to_bits() } else { (-0.0f64).to_bits() })
);
assert_eq!(floats(0x3009, &[a, b]), Ok(if same { a.to_bits() } else { 0 }));
}
}
assert_eq!(floats(0x300a, &[-0.0, 0.0, 1.0]), Ok(0));
assert_eq!(floats(0x300b, &[-0.0]), Ok(0));
assert_eq!(floats(0x3010, &[-0.0]), Ok((-0.0f64).to_bits()));
for id in 0x300c..=0x300f {
assert_eq!(floats(id, &[-0.0]), Ok((-0.0f64).to_bits()));
}
for (x, y) in [
(0.5, 0.0f64),
(-0.5, -0.0),
(1.5, 2.0),
(2.5, 2.0),
(3.5, 4.0),
(-2.5, -2.0),
(-3.5, -4.0),
(f64::from_bits(0x3fe0000000000001), 1.0),
(f64::from_bits(0x3fdfffffffffffff), 0.0),
] {
assert_eq!(floats(0x300f, &[x]), Ok(y.to_bits()));
}
assert_eq!(floats(0x300c, &[-2.7]), Ok((-3.0f64).to_bits()));
assert_eq!(floats(0x300d, &[-2.7]), Ok((-2.0f64).to_bits()));
assert_eq!(floats(0x300e, &[-2.7]), Ok((-2.0f64).to_bits()));
}
#[test]
fn atan2_has_explicit_zero_vector_and_signed_axis_contract() {
for y in [0.0, -0.0] {
for x in [0.0, -0.0] {
assert_eq!(floats(0x3013, &[y, x]), Err(DOMAIN));
}
}
for (y, x, bits) in [
(0.0, 1.0, 0),
(-0.0, 1.0, 1 << 63),
(0.0, -1.0, 0x400921fb54442d18),
(-0.0, -1.0, 0xc00921fb54442d18),
(1.0, 0.0, 0x3ff921fb54442d18),
(1.0, -0.0, 0x3ff921fb54442d18),
(-1.0, 0.0, 0xbff921fb54442d18),
(-1.0, -0.0, 0xbff921fb54442d18),
] {
assert_eq!(floats(0x3013, &[y, x]), Ok(bits));
}
assert_eq!(floats(0x3011, &[-0.0]), Ok(1 << 63));
assert_eq!(floats(0x3012, &[-0.0]), Ok(1.0f64.to_bits()));
}
#[test]
fn conversions_check_the_truncated_integer_without_saturating() {
for (x, expected) in [(3.9, 3), (-3.9, -3), (-2147483648.9, i32::MIN)] {
assert_eq!(call(0x3018, &[Value::Float(x)]).unwrap(), Value::Int32(expected));
}
assert!(
matches!(call(0x3018,&[Value::Float(2147483648.0)]),Err(E::Numeric(e)) if e.code==RANGE)
);
let minimum = f64::from_bits(0xc3e0000000000000);
assert_eq!(call(0x3019, &[Value::Float(minimum)]).unwrap(), Value::Int64(i64::MIN));
let Value::Float(wide) = call(0x3017, &[Value::Int64(i64::MAX)]).unwrap() else { panic!() };
assert_eq!(wide.to_bits(), 0x43e0000000000000);
assert!(matches!(call(0x3019,&[Value::Float(wide)]),Err(E::Numeric(e)) if e.code==RANGE));
assert_eq!(
call(0x3019, &[Value::Float(f64::from_bits(0x43dfffffffffffff))]).unwrap(),
Value::Int64(9223372036854774784)
);
assert_eq!(call(0x3014, &[Value::Int32(i32::MIN)]).unwrap(), Value::Int64(i64::from(i32::MIN)));
assert!(matches!(call(0x3015,&[Value::Int64(i64::MAX)]),Err(E::Numeric(e)) if e.code==RANGE));
assert_eq!(call(0x3018, &[Value::Float(-0.0)]).unwrap(), Value::Int32(0));
for (integer, bits) in
[(9007199254740993, 0x4340000000000000), (9007199254740995, 0x4340000000000002)]
{
let Value::Float(v) = call(0x3017, &[Value::Int64(integer)]).unwrap() else { panic!() };
assert_eq!(v.to_bits(), bits);
}
}
#[test]
fn faults_validate_all_types_then_finitude_then_domain() {
assert!(matches!(
call(0x300a, &[Value::Float(f64::NAN), Value::Float(2.), Value::Int32(1)]),
Err(E::TypeMismatch { index: 2, .. })
));
assert_eq!(floats(0x300a, &[f64::NAN, 2., 1.]), Err(NON_FINITE));
assert_eq!(floats(0x300a, &[0., 2., 1.]), Err(DOMAIN));
assert_eq!(floats(0x3010, &[-1.]), Err(DOMAIN));
for x in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert_eq!(floats(0x3010, &[x]), Err(NON_FINITE));
}
assert!(matches!(
call(
0x1000,
&[Value::Float(f64::NAN), Value::Float(1.), Value::Float(2.), Value::Int32(3)]
),
Err(E::TypeMismatch { index: 3, .. })
));
}
#[test]
fn vector_sequences_keep_stage_rounding_and_scaled_extremes() {
assert_eq!(floats(0x1001, &[1e200, 0.]), Ok(1e200f64.to_bits()));
assert_eq!(floats(0x1001, &[f64::from_bits(1), 0.]), Ok(1));
assert_eq!(floats(0x1001, &[-0., -0.]), Ok(0));
assert_eq!(floats(0x1001, &[f64::MAX, f64::MAX]), Err(RANGE));
assert_eq!(floats(0x1000, &[f64::MAX, f64::MAX, 2., -2.]), Err(RANGE));
// (1+2^-27)*(1-2^-27) rounds to 1 before subtracting 1.
assert_eq!(
floats(
0x1000,
&[f64::from_bits(0x3ff0000002000000), 1., f64::from_bits(0x3feffffffc000000), -1.]
),
Ok(0)
);
}
#[test]
fn math_attempts_charge_before_failure_and_positive_budget_overshoots() {
for (bits, expected) in [(0x4010000000000000u64, None), (0xbff0000000000000, Some(DOMAIN))] {
let mut v =
vm(&format!("PUSH_F64 f64:0x{bits:016x}\nINTRINSIC 0x3010\nHALT"), Default::default());
assert_eq!(run(&mut v, 1).cycles_used, 2);
let before = v.operand_stack_top(1);
let zero = run(&mut v, 0);
assert_eq!((zero.cycles_used, zero.steps_executed), (0, 0));
assert_eq!(&*before, &*v.operand_stack_top(1));
let attempt = run(&mut v, 1);
assert_eq!(attempt.cycles_used, 16);
if let Some(code) = expected {
assert_eq!((trap(&attempt).code, trap(&attempt).pc), (code, 10));
} else {
assert_eq!(attempt.reason, End::BudgetExhausted);
let Value::Float(x) = v.operand_stack_top(1)[0] else { panic!() };
assert_eq!(x.to_bits(), 2.0f64.to_bits());
assert_eq!(run(&mut v, 1).cycles_used, 1);
}
}
let mut v =
vm("PUSH_I32 1\nSET_GLOBAL 0\nGET_GLOBAL 0\nINTRINSIC 0x3010\nHALT", Default::default());
run(&mut v, 8);
let attempt = run(&mut v, 1);
assert_eq!((attempt.cycles_used, trap(&attempt).code), (16, TRAP_TYPE));
let mut v = vm(
"PUSH_F64 f64:0x4010000000000000\nINTRINSIC 0x3010\nHALT",
RuntimeLimits::default()
.lowered(prometeu_bytecode::RuntimeResource::TemporaryBytes, 0)
.unwrap(),
);
run(&mut v, 1);
let attempt = run(&mut v, 1);
assert_eq!(
(attempt.cycles_used, trap(&attempt).code),
(16, prometeu_bytecode::TRAP_RESOURCE_LIMIT)
);
}
#[test]
fn float_opcodes_preserve_underflow_zero_division_and_numeric_faults() {
for (source, bits) in [
("PUSH_F64 f64:0x0000000000000001\nPUSH_F64 f64:0x3ff0000000000000\nMUL\nHALT", 1),
("PUSH_F64 f64:0x0000000000000001\nPUSH_F64 f64:0x4000000000000000\nDIV\nHALT", 0),
("PUSH_F64 f64:0x8000000000000000\nNEG\nHALT", 0),
(
"PUSH_I64 9007199254740993\nPUSH_F64 f64:0x0000000000000000\nADD\nHALT",
0x4340000000000000,
),
] {
let mut v = vm(source, Default::default());
assert_eq!(run(&mut v, 100).reason, End::Halted);
let Value::Float(x) = v.operand_stack_top(1)[0] else { panic!() };
assert_eq!(x.to_bits(), bits);
}
for (source, code) in [
("PUSH_F64 f64:0x7fefffffffffffff\nPUSH_F64 f64:0x4000000000000000\nMUL\nHALT", RANGE),
(
"PUSH_F64 f64:0x3ff0000000000000\nPUSH_F64 f64:0x8000000000000000\nDIV\nHALT",
TRAP_DIV_ZERO,
),
] {
let mut v = vm(source, Default::default());
assert_eq!(trap(&run(&mut v, 100)).code, code);
}
}
#[test]
fn load_rejects_nonfinite_immediates_and_unknown_intrinsics_even_when_dead() {
for (source, reason) in [
("HALT\nPUSH_F64 f64:0x7ff0000000000000", R::NonFiniteValue),
("HALT\nPUSH_F64 f64:0x7ff8000000000042", R::NonFiniteValue),
("HALT\nINTRINSIC 0xffffffff", R::NativeId),
] {
let bytes =
TestProgram::single(assemble(source).unwrap(), Default::default(), 0, 8).serialize();
let Err(VmInitError::RegistryLoadFailed(e)) =
ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(Default::default()), 0)
else {
panic!()
};
assert_eq!(
(e.code, e.reason, e.function, e.pc),
(C::InvalidCode, reason, Some(0), Some(2))
);
}
}
#[test]
fn native_signature_checks_all_types_before_rejecting_nonfinite() {
use prometeu_bytecode::registry::{NamedType, Signature, TypeId};
let mut program = TestProgram::single(assemble("HALT").unwrap(), Default::default(), 0, 8);
program.functions[0].signature = Signature {
parameters: vec![NamedType { type_id: TypeId(2), name: None }; 2],
results: vec![],
};
let image = ValidatedProgramImage::load(
&program.serialize(),
&mut LoadBudget::new(Default::default()),
0,
)
.unwrap();
let mut v = VirtualMachine::from_image(image, Default::default());
for (args, slot, code) in [
([Value::Float(f64::NAN), Value::Int32(1)], 1, TRAP_TYPE),
([Value::Float(f64::NAN), Value::Float(1.)], 0, NON_FINITE),
] {
assert_eq!(
v.prepare_call_with_args("0", &args),
Err(VmInitError::EntrypointArgumentsInvalid { function: 0, slot, trap_code: code })
);
assert!(v.operand_stack_top(10).is_empty());
}
assert!(matches!(v.push(Value::Float(f64::INFINITY)), Err(VmFault::Trap(NON_FINITE, _))));
assert!(v.operand_stack_top(10).is_empty());
}
#[test]
fn catalog_has_exact_ids_costs_names_and_canonical_constants() {
let costs = [2, 2, 4, 2, 2, 2, 4, 2, 2, 2, 4, 2, 4, 4, 4, 4, 16, 32, 32, 48, 2, 2, 2, 2, 2, 2];
for (offset, cost) in costs.into_iter().enumerate() {
let m = lookup_intrinsic_by_id(0x3000 + offset as u32).unwrap();
assert_eq!((m.version, m.cost_cycles), (1, cost));
assert_eq!(m.parameter_names.len(), m.arg_layout.len());
assert!(m.deterministic && !m.may_allocate);
}
for (id, cost) in [(0x1000, 10), (0x1001, 40), (0x1101, 1), (0x2100, 1)] {
assert_eq!(lookup_intrinsic_by_id(id).unwrap().cost_cycles, cost);
}
for (name, bits) in [("pi", 0x400921fb54442d18), ("tau", 0x401921fb54442d18)] {
let constants = materialize_builtin_constant("mathf", name, 1).unwrap().unwrap();
let Value::Float(x) = constants[0] else { panic!() };
assert_eq!(x.to_bits(), bits);
}
assert_eq!(lookup_intrinsic_by_id(0x3013).unwrap().parameter_names, &["y", "x"]);
}
#[test]
fn exported_artifacts_match_the_single_runtime_catalog() {
assert_eq!(
prometeu_vm::intrinsic_catalog_csv(),
include_str!("../../../../docs/vm-arch/INTRINSICS.csv")
);
assert_eq!(
prometeu_vm::builtin_constant_catalog_csv(),
include_str!("../../../../docs/vm-arch/BUILTIN_CONSTANTS.csv")
);
let mut ids = std::collections::HashSet::new();
let mut keys = std::collections::HashSet::new();
for m in prometeu_vm::intrinsic_catalog() {
assert!(ids.insert(m.id));
assert!(keys.insert(m.key()));
assert_eq!(m.parameter_names.len(), m.arg_slots());
}
}
fn fixture_value(token: &str) -> Value {
let (kind, v) = token.split_once(':').unwrap();
match kind {
"f" => Value::Float(f64::from_bits(u64::from_str_radix(v, 16).unwrap())),
"i" => Value::Int32(v.parse().unwrap()),
"l" => Value::Int64(v.parse().unwrap()),
_ => panic!("numeric fixture"),
}
}
fn value_token(v: &Value) -> String {
match v {
Value::Float(v) => format!("f:{:016x}", v.to_bits()),
Value::Int32(v) => format!("i:{v}"),
Value::Int64(v) => format!("l:{v}"),
_ => panic!("numeric fixture result"),
}
}
fn push_source(v: &Value) -> String {
match v {
Value::Float(v) => format!("PUSH_F64 f64:0x{:016x}\n", v.to_bits()),
Value::Int32(v) => format!("PUSH_I32 {v}\n"),
Value::Int64(v) => format!("PUSH_I64 {v}\n"),
_ => panic!("numeric fixture argument"),
}
}
#[test]
fn mpfr_fixed_corpus_replays_without_a_runtime_or_test_mpfr_dependency() {
for row in include_str!("fixtures/numeric-conformance.tsv").lines() {
let tokens: Vec<_> = row.split_whitespace().collect();
let op = tokens[0];
let expected = tokens[tokens.len() - 2];
let cycles: u64 = tokens[tokens.len() - 1].parse().unwrap();
let args: Vec<_> = tokens[1..tokens.len() - 2].iter().map(|t| fixture_value(t)).collect();
if matches!(op, "ADD" | "SUB" | "MUL" | "DIV") {
let source = args.iter().map(push_source).collect::<String>() + op + "\nHALT";
let mut v = vm(&source, Default::default());
let report = run(&mut v, 100);
assert_eq!(report.cycles_used, cycles, "{row}");
let actual = match report.reason {
End::Halted => value_token(&v.operand_stack_top(1)[0]),
End::Trap(t) => format!("trap:{:x}", t.code),
e => panic!("{row}: {e:?}"),
};
assert_eq!(actual, expected, "{row}");
} else {
let id = u32::from_str_radix(op, 16).unwrap();
let actual = match call(id, &args) {
Ok(v) => value_token(&v),
Err(E::Numeric(e)) => format!("trap:{:x}", e.code),
e => panic!("{e:?}"),
};
assert_eq!(actual, expected, "{row}");
assert_eq!(lookup_intrinsic_by_id(id).unwrap().cost_cycles, cycles);
}
}
}
#[test]
fn every_scalar_and_vector_call_has_the_published_total_execution_cost() {
for m in prometeu_vm::intrinsic_catalog()
.filter(|m| m.owner == "vec2" || m.owner == "mathf" || m.owner.starts_with("math."))
{
let args: Vec<_> = m
.arg_layout
.iter()
.enumerate()
.map(|(i, t)| {
let n = if m.name == "clamp" { [1, 0, 2][i] } else { 1 };
match t {
prometeu_vm::AbiType::Scalar(prometeu_vm::BuiltinScalarType::Int32) => {
Value::Int32(n)
}
prometeu_vm::AbiType::Scalar(prometeu_vm::BuiltinScalarType::Int64) => {
Value::Int64(i64::from(n))
}
_ => Value::Float(f64::from(n)),
}
})
.collect();
let source = args.iter().map(push_source).collect::<String>()
+ &format!("INTRINSIC 0x{:x}\nHALT", m.id);
let mut v = vm(&source, Default::default());
let prefix = run(&mut v, 2 * args.len() as u64);
assert_eq!(prefix.cycles_used, 2 * args.len() as u64);
let attempt = run(&mut v, 1);
assert_eq!(attempt.cycles_used, m.cost_cycles, "{}", m.id);
assert_eq!(attempt.reason, End::BudgetExhausted, "{}", m.id);
}
}