use prometeu_bytecode::load_limits::{ LoadBudget, LoadCode, LoadFailure, LoadLimits, LoadReason, LoadResource, }; use prometeu_bytecode::registry::*; use prometeu_bytecode::registry_codec::*; fn budget() -> LoadBudget { LoadBudget::new(LoadLimits::default()) } fn named(id: u32) -> NamedType { NamedType { type_id: TypeId(id), name: None } } fn builtin(id: BuiltinId) -> TypeDecl { TypeDecl { name: None, kind: TypeKind::Builtin(id) } } fn resolve(d: RegistryDeclarations) -> Result { Registry::resolve(d, 100, &mut budget()) } fn hex(s: &str) -> Vec { s.split_whitespace().map(|b| u8::from_str_radix(b, 16).unwrap()).collect() } // Independently specified PBX, not generated by any production serializer. // Header 32 bytes, seven directory entries (84 bytes), payload starts at 116. // constants=116/4, functions=120/29, code=149/2, exports=151/4, // syscalls=155/4, types=159/10, implementations=169/4. Total=173. fn minimal_bytes() -> Vec { hex(" 50 42 58 00 01 00 00 00 07 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 74 00 00 00 04 00 00 00 01 00 00 00 78 00 00 00 1d 00 00 00 02 00 00 00 95 00 00 00 02 00 00 00 04 00 00 00 97 00 00 00 04 00 00 00 05 00 00 00 9b 00 00 00 04 00 00 00 06 00 00 00 9f 00 00 00 0a 00 00 00 07 00 00 00 a9 00 00 00 04 00 00 00 00 00 00 00 01 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 00 00 00 00 01 00 00 00 00 00 13 00 00 00 00 00 00 00") } fn minimal_registry() -> Registry { resolve(RegistryDeclarations { types: vec![builtin(BuiltinId::BOOL)], functions: vec![FunctionDecl { code_len: 2, ..Default::default() }], ..Default::default() }) .unwrap() } fn envelope(types: &[u8], functions: &[u8], implementations: &[u8]) -> Vec { let empty = [0; 4]; let code = [1, 0]; encode_envelope( &[ SectionData { kind: 0, bytes: &empty }, SectionData { kind: 1, bytes: functions }, SectionData { kind: 2, bytes: &code }, SectionData { kind: 4, bytes: &empty }, SectionData { kind: 5, bytes: &empty }, SectionData { kind: 6, bytes: types }, SectionData { kind: 7, bytes: implementations }, ], &mut budget(), ) .unwrap() } #[test] 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(), 173); let mut b = budget(); let env = PbxEnvelope::parse(&bytes, &mut b).unwrap(); assert_eq!(env.section(2).unwrap().offset, 149); let registry = env.resolve_registry(&mut b).unwrap(); assert_eq!(registry.declarations(), minimal_registry().declarations()); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); assert_eq!(registry.declarations().functions[0].max_stack_slots, 0); } #[test] fn owned_v1_decoder_accepts_independent_bytes_without_publishing_an_image() { let mut b = budget(); let owned = OwnedPbx::parse(&minimal_bytes(), &mut b).unwrap(); assert_eq!(owned.registry.declarations(), minimal_registry().declarations()); assert_eq!(owned.code, [1, 0]); assert!(owned.constants.is_empty()); assert!(owned.exports.is_empty()); assert!(owned.syscalls.is_empty()); assert!(owned.debug.is_none()); assert_eq!(b.used(LoadResource::TemporaryBytes), owned.code.capacity() as u64); } #[test] fn owned_payloads_preserve_utf8_float_bits_names_and_binding_declarations() { use prometeu_bytecode::model::{ConstantPoolEntry as K, DebugInfo, Export, SyscallDecl}; use prometeu_bytecode::SourceSpan; let registry = minimal_registry(); let constants = [ K::Null, K::Int32(i32::MIN), K::Int64(i64::MAX), K::Float64(f64::from_bits(0x7ff8000000000042)), K::Boolean(true), K::String("é猫".into()), K::String(String::new()), ]; let debug = DebugInfo { pc_to_span: vec![(0, SourceSpan { file_id: 9, start: 2, end: 7 })], function_names: vec![(0, "débug".into())], }; let exports = [Export { func_idx: 0, symbol: "入口".into() }]; let syscalls = [SyscallDecl { module: "system".into(), name: "hasCart".into(), version: 1, arg_slots: 0, ret_slots: 1, }]; let bytes = PbxModule { registry: ®istry, constants: &constants, code: &[1, 0], debug: Some(&debug), exports: &exports, syscalls: &syscalls, } .serialize(&mut budget()) .unwrap(); let mut b = budget(); 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!(&module.constants[4..], &constants[4..]); assert_eq!(module.debug.as_ref(), Some(&debug)); assert_eq!(module.exports, exports); assert_eq!(module.syscalls, syscalls); assert_eq!(b.used(LoadResource::ConstantEntries), 7); assert_eq!(b.used(LoadResource::ConstantStringBytes), 5); drop(bytes); assert_eq!(module.constants[5], K::String("é猫".into())); } #[test] fn owned_payload_refusal_rolls_back_all_ownership_and_preserves_prior_budget() { let bytes = minimal_bytes(); let mut full = budget(); OwnedPbx::parse(&bytes, &mut full).unwrap(); let limits = LoadLimits { work: full.used(LoadResource::Work) - 1, ..Default::default() }; let mut b = LoadBudget::new(limits); b.charge(LoadResource::TemporaryBytes, 7).unwrap(); b.charge(LoadResource::RegistryBytes, 3).unwrap(); let failure = OwnedPbx::parse(&bytes, &mut b).unwrap_err(); assert_eq!(failure.resource, Some(LoadResource::Work)); assert_eq!(failure.section, Some(2)); assert_eq!(b.used(LoadResource::TemporaryBytes), 7); assert_eq!(b.used(LoadResource::RegistryBytes), 3); assert_eq!(b.used(LoadResource::Types), 0); assert_eq!(b.used(LoadResource::ConstantEntries), 0); let mut limits = LoadLimits::default(); limits.temporary_bytes = 1; let mut b = LoadBudget::new(limits); assert_eq!( OwnedPbx::parse(&bytes, &mut b).unwrap_err().resource, Some(LoadResource::TemporaryBytes) ); assert_eq!(b.used(LoadResource::RegistryBytes), 0); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); } #[test] fn complete_module_writer_matches_independent_minimal_bytes_and_refunds_scratch() { let registry = minimal_registry(); let module = PbxModule { registry: ®istry, constants: &[], code: &[1, 0], debug: None, exports: &[], syscalls: &[], }; let mut b = budget(); b.charge(LoadResource::TemporaryBytes, 7).unwrap(); let bytes = module.serialize(&mut b).unwrap(); assert_eq!(bytes, minimal_bytes()); assert_eq!(b.used(LoadResource::TemporaryBytes), 7 + bytes.capacity() as u64); assert_eq!(b.used(LoadResource::RegistryBytes), 0); assert_eq!(b.used(LoadResource::ConstantEntries), 0); ParsedPbx::parse(&bytes, &mut budget()).unwrap(); } #[test] fn complete_module_writer_preserves_non_registry_encodings() { use prometeu_bytecode::model::{ConstantPoolEntry as K, DebugInfo, Export, SyscallDecl}; use prometeu_bytecode::SourceSpan; let registry = minimal_registry(); let constants = [ K::Null, K::Int64(-1), K::Float64(f64::from_bits(0x7ff8000000001234)), K::Boolean(true), K::String("é".into()), K::Int32(-2), K::String(String::new()), ]; let debug = DebugInfo { pc_to_span: vec![(0, SourceSpan { file_id: 7, start: 2, end: 9 })], function_names: vec![(0, String::new())], }; let exports = [Export { symbol: "boot".into(), func_idx: 0 }]; let syscalls = [SyscallDecl { module: "m".into(), name: "n".into(), version: 3, arg_slots: 2, ret_slots: 1, }]; let module = PbxModule { registry: ®istry, constants: &constants, code: &[1, 0], debug: Some(&debug), exports: &exports, syscalls: &syscalls, }; let bytes = module.serialize(&mut budget()).unwrap(); let parsed = ParsedPbx::parse(&bytes, &mut budget()).unwrap(); assert_eq!( 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 03 01 04 02 00 00 00 c3 a9 05 fe ff ff ff 04 00 00 00 00") ); assert_eq!( parsed.section(3).unwrap().bytes, hex("01 00 00 00 00 00 00 00 07 00 00 00 02 00 00 00 09 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00") ); assert_eq!( parsed.section(4).unwrap().bytes, hex("01 00 00 00 00 00 00 00 04 00 00 00 62 6f 6f 74") ); assert_eq!( parsed.section(5).unwrap().bytes, hex("01 00 00 00 01 00 6d 01 00 6e 03 00 02 00 01 00") ); } #[test] fn complete_module_writer_rejects_invalid_payload_records_without_retaining_scratch() { use prometeu_bytecode::model::{DebugInfo, Export, SyscallDecl}; use prometeu_bytecode::SourceSpan; let registry = minimal_registry(); let bad_export = [Export { symbol: "bad".into(), func_idx: u32::MAX }]; let syscall = SyscallDecl { module: "m".into(), name: "n".into(), ..Default::default() }; let duplicates = [syscall.clone(), syscall]; let bad_debug = DebugInfo { pc_to_span: vec![(2, SourceSpan { file_id: 0, start: 0, end: 1 })], ..Default::default() }; for (exports, syscalls, debug, reason) in [ (&bad_export[..], &[][..], None, LoadReason::FunctionId), (&[][..], &duplicates[..], None, LoadReason::DuplicateSyscall), (&[][..], &[][..], Some(&bad_debug), LoadReason::DebugRange), ] { let mut b = budget(); b.charge(LoadResource::TemporaryBytes, 7).unwrap(); let e = PbxModule { registry: ®istry, constants: &[], code: &[1, 0], debug, exports, syscalls, } .serialize(&mut b) .unwrap_err(); assert_eq!(e.reason, reason); assert_eq!(b.used(LoadResource::TemporaryBytes), 7); assert!(b.used(LoadResource::Work) > 0); } } #[test] fn complete_module_writer_checks_constant_quotas_before_payload_allocation() { use prometeu_bytecode::model::ConstantPoolEntry as K; let registry = minimal_registry(); let constants = [K::String("abc".into()), K::String("abc".into())]; let module = PbxModule { registry: ®istry, constants: &constants, code: &[1, 0], debug: None, exports: &[], syscalls: &[], }; for (resource, limit) in [ (LoadResource::ConstantEntries, 1), (LoadResource::ConstantStringBytes, 5), (LoadResource::TemporaryBytes, 1), ] { let mut limits = LoadLimits::default(); match resource { LoadResource::ConstantEntries => limits.constant_entries = limit, LoadResource::ConstantStringBytes => limits.constant_string_bytes = limit, LoadResource::TemporaryBytes => limits.temporary_bytes = limit, _ => unreachable!(), } let mut b = LoadBudget::new(limits); let error = module.serialize(&mut b).unwrap_err(); assert_eq!(error.code, LoadCode::ResourceLimit); assert_eq!(error.resource, Some(resource)); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); } } #[test] fn complete_module_writer_rejects_code_range_mismatch() { let registry = minimal_registry(); let e = PbxModule { registry: ®istry, constants: &[], code: &[], debug: None, exports: &[], syscalls: &[], } .serialize(&mut budget()) .unwrap_err(); assert_eq!((e.code, e.reason), (LoadCode::InvalidCode, LoadReason::CodeRange)); assert_eq!((e.function, e.pc), (Some(0), Some(0))); } #[test] fn representative_records_match_fixed_bytes_and_preserve_names_without_debug() { let types = hex(" 04 00 00 00 00 00 13 00 00 00 01 01 00 00 00 00 01 00 00 00 00 00 00 00 00 02 00 01 00 00 00 03 00 01 00 00 00 01 01 00 00 00 6d 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 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"); let implementations = hex("01 00 00 00 01 00 00 00 03 00 00 00 01 00 00 00 00 00 00 00"); let bytes = envelope(&types, &functions, &implementations); let mut b = budget(); let env = PbxEnvelope::parse(&bytes, &mut b).unwrap(); assert!(env.section(3).is_none()); let r = env.resolve_registry(&mut b).unwrap(); assert_eq!(r.declarations().types[0].name, None); assert_eq!(r.declarations().types[1].name, Some(String::new())); assert_eq!(r.declarations().functions[0].signature.parameters[1].name.as_deref(), Some("p")); assert_eq!(r.implementation(TypeId(1), TypeId(3)), Some(ImplementationId(0))); assert_eq!(r.type_layout(TypeId(2)).unwrap().storage.size, 8); let encoded = encode_registry(&r, &mut budget()).unwrap(); assert_eq!(encoded.types, types); assert_eq!(encoded.functions, functions); assert_eq!(encoded.implementations, implementations); } #[test] fn every_truncated_envelope_is_rejected_without_panic() { let bytes = minimal_bytes(); for n in 0..bytes.len() { let mut b = budget(); assert!(PbxEnvelope::parse(&bytes[..n], &mut b).is_err(), "prefix {n}"); } } #[test] fn envelope_mutations_have_typed_reasons() { for (offset, value, code, reason) in [ (0, 0, LoadCode::InvalidFormat, LoadReason::Magic), (4, 0, LoadCode::UnsupportedFormat, LoadReason::Version), (6, 1, LoadCode::InvalidFormat, LoadReason::Endianness), (7, 1, LoadCode::InvalidFormat, LoadReason::Reserved), (31, 1, LoadCode::InvalidFormat, LoadReason::Reserved), (32, 8, LoadCode::UnsupportedFormat, LoadReason::SectionKind), (44, 0, LoadCode::InvalidFormat, LoadReason::DuplicateSection), (36, 0, LoadCode::InvalidFormat, LoadReason::Overlap), (48, 116, LoadCode::InvalidFormat, LoadReason::Overlap), ] { let mut bytes = minimal_bytes(); bytes[offset] = value; let err = PbxEnvelope::parse(&bytes, &mut budget()).unwrap_err(); assert_eq!((err.code, err.reason), (code, reason), "offset {offset}"); } } #[test] fn mandatory_empty_sections_are_required() { let mut bytes = minimal_bytes(); bytes[32] = 3; // replaces constants with optional debug let err = PbxEnvelope::parse(&bytes, &mut budget()).unwrap_err(); assert_eq!(err.reason, LoadReason::MissingSection); assert_eq!(err.section, Some(0)); } #[test] fn record_flags_utf8_trailing_bytes_and_unknown_categories_fail() { let valid = minimal_bytes(); let mut b = budget(); let env = PbxEnvelope::parse(&valid, &mut b).unwrap(); let functions = env.section(1).unwrap().bytes; let implementations = env.section(7).unwrap().bytes; for (types, reason) in [ (hex("01 00 00 00 00 02 13 00 00 00"), LoadReason::InvalidFlag), (hex("01 00 00 00 04 00 13 00 00 00"), LoadReason::Category), (hex("01 00 00 00 00 01 01 00 00 00 ff 13 00 00 00"), LoadReason::Utf8), (hex("01 00 00 00 00 00 13 00 00 00 ff"), LoadReason::TrailingBytes), (hex("01 00 00 00 00 00 00 01 00 00"), LoadReason::Builtin), ] { let bytes = envelope(&types, functions, implementations); let mut b = budget(); let env = PbxEnvelope::parse(&bytes, &mut b).unwrap(); let err = env.resolve_registry(&mut b).unwrap_err(); assert_eq!(err.reason, reason); assert_eq!(b.used(LoadResource::RegistryBytes), 0); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); } } #[test] fn oversized_counts_fail_before_dependent_allocation() { let bytes = envelope(&[255; 4], &[0; 4], &[0; 4]); let mut b = budget(); let env = PbxEnvelope::parse(&bytes, &mut b).unwrap(); let err = env.resolve_registry(&mut b).unwrap_err(); assert_eq!(err.resource, Some(LoadResource::Types)); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); } #[test] fn logical_scalar_layout_and_empty_nominal_identity() { let d = RegistryDeclarations { types: vec![ builtin(BuiltinId::BOOL), builtin(BuiltinId::INT32), TypeDecl { name: None, kind: TypeKind::Struct(vec![named(0), named(1), named(0)]) }, TypeDecl { name: None, kind: TypeKind::Struct(vec![]) }, TypeDecl { name: None, kind: TypeKind::Struct(vec![]) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(2)) }, ], ..Default::default() }; let r = resolve(d).unwrap(); let s = r.type_layout(TypeId(2)).unwrap(); assert_eq!(s.storage.size, 8); let p = s.instance.as_ref().unwrap(); assert_eq!((p.size, p.alignment), (12, 4)); assert_eq!(p.fields.iter().map(|f| f.offset).collect::>(), vec![0, 4, 8]); assert!(p.owned_fields.is_empty()); for id in [3, 4] { let l = r.type_layout(TypeId(id)).unwrap().instance.as_ref().unwrap(); assert_eq!((l.size, l.alignment), (0, 1)); } assert_eq!(r.type_layout(TypeId(5)).unwrap().storage.size, 8); assert_eq!(r.declarations().types.len(), 6); } #[test] fn nominal_recursion_and_forward_references_terminate() { let r = resolve(RegistryDeclarations { types: vec![ TypeDecl { name: None, kind: TypeKind::Struct(vec![named(0), named(1)]) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }, ], ..Default::default() }) .unwrap(); let layout = r.type_layout(TypeId(0)).unwrap().instance.as_ref().unwrap(); assert_eq!(layout.size, 16); assert_eq!(layout.owned_fields.len(), 2); } #[test] fn duplicate_imports_and_arrays_and_structural_cycles_fail() { let cases = [ (vec![builtin(BuiltinId::BOOL), builtin(BuiltinId::BOOL)], LoadReason::DuplicateBuiltin), ( vec![ builtin(BuiltinId::BOOL), TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }, ], LoadReason::DuplicateArray, ), (vec![TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }], LoadReason::ArrayCycle), ( vec![ TypeDecl { name: None, kind: TypeKind::Array(TypeId(1)) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }, ], LoadReason::ArrayCycle, ), ]; for (types, reason) in cases { assert_eq!( resolve(RegistryDeclarations { types, ..Default::default() }).unwrap_err().reason, reason ); } } #[test] fn long_array_chain_uses_bounded_iteration() { let mut types: Vec<_> = (0..10_000) .map(|i| TypeDecl { name: None, kind: TypeKind::Array(TypeId(i + 1)) }) .collect(); types.push(builtin(BuiltinId::INT32)); assert!(resolve(RegistryDeclarations { types, ..Default::default() }).is_ok()); } #[test] fn invalid_references_are_not_indexed() { let d = RegistryDeclarations { types: vec![TypeDecl { name: None, kind: TypeKind::Struct(vec![named(u32::MAX)]) }], ..Default::default() }; let e = resolve(d).unwrap_err(); assert_eq!(e.code, LoadCode::InvalidReference); assert_eq!(e.member, Some(0)); } #[test] fn all_builtin_widths_native_layout_and_unknown_imports() { for (id, size, alignment, slots) in [ (1, 4, 4, 1), (2, 16, 8, 2), (3, 24, 8, 3), (0x10, 4, 4, 1), (0x11, 8, 8, 1), (0x12, 8, 8, 1), (0x13, 1, 1, 1), ] { let l = BuiltinId(id).layout().unwrap(); assert_eq!((l.size, l.alignment, l.slots), (size, alignment, slots)); assert!(!l.nullable()); } let s = BuiltinId::STRING.layout().unwrap(); assert_eq!((s.size, s.alignment), (size_of::(), align_of::())); assert!(s.nullable()); let d = BuiltinId::DYNAMIC.layout().unwrap(); assert_eq!((d.size, d.alignment), (size_of::(), align_of::())); for id in [0, 4, 0x100, 0x101, 0x102, u32::MAX] { assert_eq!(BuiltinId(id).layout().unwrap_err().reason, LoadReason::Builtin); } } fn implemented() -> RegistryDeclarations { RegistryDeclarations { types: vec![ builtin(BuiltinId::VEC2), TypeDecl { name: None, kind: TypeKind::Struct(vec![]) }, TypeDecl { name: None, kind: TypeKind::Trait(vec![MethodDecl { name: None, signature: Signature { parameters: vec![named(0)], results: vec![TypeId(0)] }, }]), }, ], functions: vec![FunctionDecl { signature: Signature { parameters: vec![named(1), named(0)], results: vec![TypeId(0)] }, code_len: 2, max_stack_slots: 2, ..Default::default() }], implementations: vec![ImplementationDecl { owner: TypeId(1), trait_id: TypeId(2), methods: vec![FunctionId(0)], }], } } #[test] fn multi_slot_signatures_derive_counts_and_validate_exact_trait_pair() { let r = resolve(implemented()).unwrap(); assert_eq!( r.function_layout(FunctionId(0)), Some(&FunctionLayout { parameter_slots: 3, result_slots: 2 }) ); let mut d = implemented(); d.functions[0].signature.parameters.swap(0, 1); assert_eq!(resolve(d).unwrap_err().reason, LoadReason::Signature); let mut d = implemented(); d.functions[0].signature.results.clear(); assert_eq!(resolve(d).unwrap_err().reason, LoadReason::Signature); let mut d = implemented(); d.implementations.push(d.implementations[0].clone()); assert_eq!(resolve(d).unwrap_err().reason, LoadReason::DuplicateImplementation); let mut d = implemented(); d.implementations[0].methods.clear(); assert_eq!(resolve(d).unwrap_err().reason, LoadReason::MethodCount); let mut d = implemented(); d.implementations[0].owner = TypeId(0); assert_eq!(resolve(d).unwrap_err().reason, LoadReason::OwnerCategory); } #[test] fn literal_zero_max_stack_is_preserved_and_frame_limits_are_not_truncated() { let mut d = implemented(); d.functions[0].max_stack_slots = 0; assert!(resolve(d).is_ok()); let mut d = implemented(); d.functions[0].local_slots = 65_536; assert_eq!(resolve(d).unwrap_err().reason, LoadReason::FrameSlots); let mut d = implemented(); d.functions[0].code_offset = u32::MAX; assert_eq!(resolve(d).unwrap_err().reason, LoadReason::CodeRange); let mut d = implemented(); d.functions.push(d.functions[0].clone()); assert_eq!(resolve(d).unwrap_err().reason, LoadReason::CodeRange); } #[test] fn work_retained_and_temporary_limits_refuse_before_publication() { for limits in [ LoadLimits { work: 1, ..Default::default() }, LoadLimits { registry_bytes: 1, ..Default::default() }, LoadLimits { temporary_bytes: 1, ..Default::default() }, ] { let mut b = LoadBudget::new(limits); let e = Registry::resolve(implemented(), 100, &mut b).unwrap_err(); assert_eq!(e.code, LoadCode::ResourceLimit); assert_eq!(b.used(LoadResource::RegistryBytes), 0); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); } } #[test] fn budget_boundaries_are_transactional_and_product_ceiling_cannot_be_raised() { let mut b = LoadBudget::new(LoadLimits { temporary_bytes: 8, ..Default::default() }); b.charge(LoadResource::TemporaryBytes, 8).unwrap(); assert!(b.charge(LoadResource::TemporaryBytes, 1).is_err()); assert_eq!(b.used(LoadResource::TemporaryBytes), 8); b.refund(LoadResource::TemporaryBytes, 8); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); let b = LoadBudget::new(LoadLimits { pbx_bytes: u64::MAX, ..Default::default() }); assert_eq!(b.limit(LoadResource::PbxBytes), 64 * 1_048_576); } #[test] fn name_limits_include_aggregate_and_empty_is_not_absent() { let mut d = implemented(); d.types[0].name = Some("x".repeat(4097)); assert_eq!(resolve(d).unwrap_err().resource, Some(LoadResource::NameBytes)); let mut d = implemented(); d.types[0].name = Some("ab".into()); d.types[1].name = Some("cd".into()); let mut b = LoadBudget::new(LoadLimits { name_bytes: 3, ..Default::default() }); assert_eq!( Registry::resolve(d, 100, &mut b).unwrap_err().resource, Some(LoadResource::NameBytes) ); } fn with_section(kind: u32, payload: &[u8]) -> Vec { let bytes = minimal_bytes(); let mut b = budget(); let env = PbxEnvelope::parse(&bytes, &mut b).unwrap(); let mut sections = Vec::new(); for k in 0..8 { if k == kind { sections.push(SectionData { kind: k, bytes: payload }); } else if let Some(section) = env.section(k) { sections.push(SectionData { kind: k, bytes: section.bytes }); } } encode_envelope(§ions, &mut budget()).unwrap() } #[test] fn full_pbx_validation_accepts_independent_minimal_fixture() { let bytes = minimal_bytes(); let mut b = budget(); let parsed = ParsedPbx::parse(&bytes, &mut b).unwrap(); assert_eq!(parsed.encode(&mut budget()).unwrap(), bytes); assert_eq!(parsed.registry().declarations(), minimal_registry().declarations()); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); } #[test] fn constants_are_strict_and_validate_every_tag_without_lossy_utf8() { let constants=hex("06 00 00 00 00 01 ff ff ff ff ff ff ff ff 02 00 00 00 00 00 00 00 00 03 01 04 03 00 00 00 61 62 63 05 ff ff ff ff"); let bytes = with_section(0, &constants); let mut b = budget(); let parsed = ParsedPbx::parse(&bytes, &mut b).unwrap(); assert_eq!(parsed.section(0).unwrap().bytes, constants); assert_eq!(b.used(LoadResource::ConstantEntries), 6); assert_eq!(b.used(LoadResource::ConstantStringBytes), 3); for (cp, reason) in [ (hex("01 00 00 00 03 02"), LoadReason::InvalidFlag), (hex("01 00 00 00 04 01 00 00 00 ff"), LoadReason::Utf8), (hex("01 00 00 00 06"), LoadReason::ConstantTag), (hex("01 00 00 00 01 ff"), LoadReason::Truncated), (hex("00 00 00 00 ff"), LoadReason::TrailingBytes), ] { let bytes = with_section(0, &cp); let mut b = budget(); let e = ParsedPbx::parse(&bytes, &mut b).unwrap_err(); assert_eq!(e.reason, reason); assert_eq!(e.section, Some(0)); assert_eq!(b.used(LoadResource::RegistryBytes), 0); } } #[test] fn constant_string_limits_are_checked_before_materialization() { let bytes = with_section(0, &hex("01 00 00 00 04 03 00 00 00 61 62 63")); for limits in [ LoadLimits { individual_string_bytes: 2, ..Default::default() }, LoadLimits { constant_string_bytes: 2, ..Default::default() }, LoadLimits { constant_entries: 0, ..Default::default() }, ] { let mut b = LoadBudget::new(limits); let e = ParsedPbx::parse(&bytes, &mut b).unwrap_err(); assert_eq!(e.code, LoadCode::ResourceLimit); assert_eq!(b.used(LoadResource::ConstantStringBytes), 0); assert_eq!(b.used(LoadResource::RegistryBytes), 0); } } #[test] fn export_and_debug_references_are_checked_and_table_tails_rejected() { let export = hex("01 00 00 00 00 00 00 00 04 00 00 00 6d 61 69 6e"); assert!(ParsedPbx::parse(&with_section(4, &export), &mut budget()).is_ok()); let mut bad = export; bad[4] = 1; let e = ParsedPbx::parse(&with_section(4, &bad), &mut budget()).unwrap_err(); assert_eq!(e.code, LoadCode::InvalidReference); assert_eq!(e.referenced_id, Some(1)); // One pc/span record; one function name. These are independent of signature names. let debug=hex("01 00 00 00 00 00 00 00 07 00 00 00 0a 00 00 00 0c 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 66"); let bytes = with_section(3, &debug); assert!(ParsedPbx::parse(&bytes, &mut budget()).is_ok()); let mut bad = debug; bad[4] = 2; assert_eq!( ParsedPbx::parse(&with_section(3, &bad), &mut budget()).unwrap_err().reason, LoadReason::DebugRange ); for kind in [3, 4, 5] { let payload = if kind == 3 { hex("00 00 00 00 00 00 00 00 ff") } else { hex("00 00 00 00 ff") }; assert_eq!( ParsedPbx::parse(&with_section(kind, &payload), &mut budget()).unwrap_err().reason, LoadReason::TrailingBytes ); } } #[test] fn syscall_identity_validation_keeps_versions_distinct_and_rejects_duplicates() { // module m, name n, version 1, zero arguments/results. let entry = hex("01 00 6d 01 00 6e 01 00 00 00 00 00"); let mut payload = vec![2, 0, 0, 0]; payload.extend_from_slice(&entry); payload.extend_from_slice(&entry); let e = ParsedPbx::parse(&with_section(5, &payload), &mut budget()).unwrap_err(); assert_eq!((e.reason, e.section, e.record), (LoadReason::DuplicateSyscall, Some(5), Some(1))); payload[22] = 2; // version in second 12-byte entry let bytes = with_section(5, &payload); let mut b = budget(); assert!(ParsedPbx::parse(&bytes, &mut b).is_ok()); assert_eq!(b.used(LoadResource::TemporaryBytes), 0); } #[test] fn array_stride_uses_stored_element_layout_and_defaults_are_typed() { use prometeu_bytecode::Value; let registry = resolve(RegistryDeclarations { types: vec![ builtin(BuiltinId::INT32), builtin(BuiltinId::BOOL), builtin(BuiltinId::VEC2), TypeDecl { name: None, kind: TypeKind::Struct(vec![named(0), named(1)]) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(0)) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(1)) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(2)) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(3)) }, TypeDecl { name: None, kind: TypeKind::Array(TypeId(4)) }, ], ..Default::default() }) .unwrap(); for (id, stride, alignment) in [(4, 4, 4), (5, 1, 1), (6, 16, 8), (7, 8, 8), (8, 8, 8)] { let a = registry.type_layout(TypeId(id)).unwrap().array.unwrap(); assert_eq!((a.stride, a.element_alignment), (stride, alignment)); } assert!(matches!(BuiltinId::INT32.layout().unwrap().default_values(), [Value::Int32(0)])); assert!(matches!(BuiltinId::BOOL.layout().unwrap().default_values(), [Value::Boolean(false)])); assert!(matches!(BuiltinId::COLOR.layout().unwrap().default_values(), [Value::Int64(0)])); assert!(matches!(BuiltinId::STRING.layout().unwrap().default_values(), [Value::Null])); assert!(matches!( BuiltinId::DYNAMIC.layout().unwrap().default_values(), [Value::Null, Value::Null] )); for value in BuiltinId::VEC2.layout().unwrap().default_values() { let Value::Float(value) = value else { panic!("expected float default") }; assert_eq!(value.to_bits(), 0); } assert_eq!(registry.type_layout(TypeId(3)).unwrap().storage.default_values(), &[Value::Null]); } /// Run explicitly in release mode; records a map-only comparison, not VM/GC throughput. #[test] #[ignore = "explicit layout measurement; not a timing assertion"] fn reference_map_probe() { use std::hint::black_box; use std::time::Instant; for period in [1, 16, 256] { let d = RegistryDeclarations { types: vec![ builtin(BuiltinId::INT64), TypeDecl { name: None, kind: TypeKind::Struct(vec![]) }, TypeDecl { name: None, kind: TypeKind::Struct( (0..4096).map(|i| named(if i % period == 0 { 1 } else { 0 })).collect(), ), }, ], ..Default::default() }; let mut b = budget(); let load_start = Instant::now(); let r = Registry::resolve(d, 0, &mut b).unwrap(); let load_ns = load_start.elapsed().as_nanos(); let layout = r.type_layout(TypeId(2)).unwrap().instance.as_ref().unwrap(); let mut bitmap = vec![0u64; 64]; for field in &layout.owned_fields { let bit = field.offset / 8; bitmap[bit / 64] |= 1u64 << (bit % 64); } let runs = 10_000; let start = Instant::now(); let mut list_checksum = 0usize; for _ in 0..runs { for field in black_box(&layout.owned_fields) { list_checksum = list_checksum.wrapping_add(field.offset); } } black_box(list_checksum); let list_ns = start.elapsed().as_nanos(); let start = Instant::now(); let mut bitmap_checksum = 0usize; for _ in 0..runs { for (word_index, &word) in black_box(&bitmap).iter().enumerate() { let mut word = word; while word != 0 { bitmap_checksum = bitmap_checksum .wrapping_add((word_index * 64 + word.trailing_zeros() as usize) * 8); word &= word - 1; } } } black_box(bitmap_checksum); let bitmap_ns = start.elapsed().as_nanos(); assert_eq!(list_checksum, bitmap_checksum); println!("arch={} fields=4096 period={} roots={} payload={} registry={} load_ns={} list_bytes={} bitmap_bytes={} runs={} list_ns={} bitmap_ns={}", std::env::consts::ARCH,period,layout.owned_fields.len(),layout.size,b.used(LoadResource::RegistryBytes),load_ns, layout.owned_fields.capacity()*size_of::(),bitmap.capacity()*8,runs,list_ns,bitmap_ns); } } #[test] 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 code = hex("42 00 00 00 00 00 42 00 01 00 00 00 51 00"); let empty = [0; 4]; let bytes = encode_envelope( &[ SectionData { kind: 0, bytes: &empty }, SectionData { kind: 1, bytes: &functions }, SectionData { kind: 2, bytes: &code }, SectionData { kind: 4, bytes: &empty }, SectionData { kind: 5, bytes: &empty }, SectionData { kind: 6, bytes: &types }, SectionData { kind: 7, bytes: &empty }, ], &mut budget(), ) .unwrap(); let parsed = ParsedPbx::parse(&bytes, &mut budget()).unwrap(); assert_eq!( parsed.registry().function_layout(FunctionId(0)), Some(&FunctionLayout { parameter_slots: 2, result_slots: 2 }) ); let sections = encode_registry(parsed.registry(), &mut budget()).unwrap(); assert_eq!(sections.functions, functions); assert_eq!(sections.types, types); }