diff --git a/rust/README.md b/rust/README.md index 75fd8989..3381af1e 100644 --- a/rust/README.md +++ b/rust/README.md @@ -66,6 +66,7 @@ Only Rust has: - A heap cap and live heap size: [`Limits::max_heap_bytes`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs), measured in the size model of [`heap.rs`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/heap.rs); over it, `MemoryLimitExceeded`. [`Run::heap_bytes`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) returns the last measured reachable bytes of a live run without the `gc-stats` feature. It is measured under `max_heap_bytes`, or without a cap at the run's waits for the host with `Runtime::measure_heap(true)`; otherwise `None`. A run that drops much of its heap without allocating keeps reporting the old size until it allocates again. - CPU-time budgets: [`Limits::clock`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs) `Clock::ThreadCpu` for `timeout_ms` (also [`thread_clock`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/thread_clock.rs) for hosts). - The interpreter slice: [`Limits::slice_ms`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs), the longest stretch between awaits of the host; past it, `SliceExceeded`. +- A configurable source size limit: [`Limits::max_source_bytes`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs), defaulting to [`DEFAULT_MAX_SOURCE_BYTES`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/compiler.rs) (256 KiB). - Located host errors: [`HostError::located`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs) (`HostValue::Located`), caught as a standard error at the call, with the host error's own fields. - The program's own lines: [`Runtime::program_lines`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs); an error raised in the host's code around them (a prelude), or by a host function called from there, is located at the nearest frame of the program, as is [`Call::location`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs). - Always-on typed arrays: `ArrayBuffer` and every standard typed array besides Uint8Array, as [`HostValue::TypedArray`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs): lent without a copy to sync host functions, copied for async and durable ones. diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index 079ba9f5..ecd845e2 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1506,7 +1506,7 @@ mod tests { /// A VM as a run of `CODE` starts, which a snapshot of it restores into. fn program_vm() -> (Vm, String) { let mut atoms = Strings::fresh(); - let Ok(program) = crate::run::compile(CODE, &mut atoms) else { + let Ok(program) = crate::run::compile(CODE, &mut atoms, CODE.len()) else { panic!("compiles"); }; let mut vm = Vm::new(RunHost::bare(), Limits::default(), atoms); diff --git a/rust/crates/psychoscript/src/compiler.rs b/rust/crates/psychoscript/src/compiler.rs index 4723001e..bb3eb3c9 100644 --- a/rust/crates/psychoscript/src/compiler.rs +++ b/rust/crates/psychoscript/src/compiler.rs @@ -35,8 +35,9 @@ type R = Result; /// Deepest syntactic nesting a program may have; it bounds the recursion of analysis and compilation. const MAX_NESTING: u32 = 2_000; -/// Largest program accepted, which bounds the parser's own recursion. -const MAX_SOURCE_BYTES: usize = 256 * 1024; +/// The largest program accepted when [`Limits::max_source_bytes`](crate::Limits::max_source_bytes) is `None` +/// (256 KiB); `run::compile` refuses a larger one. +pub const DEFAULT_MAX_SOURCE_BYTES: usize = 256 * 1024; pub fn compile(source: &str, atoms: &mut Strings) -> R { compile_as(source, atoms, false) @@ -84,13 +85,6 @@ fn compile_in( atoms: &mut Strings, internal: bool, ) -> R { - if source.len() > MAX_SOURCE_BYTES { - return Err(CompileError { - kind: DiagnosticKind::ParseError, - message: format!("Program is larger than {MAX_SOURCE_BYTES} bytes."), - offset: None, - }); - } if source.trim().is_empty() { return Err(CompileError { kind: DiagnosticKind::ParseError, diff --git a/rust/crates/psychoscript/src/diagnostic.rs b/rust/crates/psychoscript/src/diagnostic.rs index 376ccf6c..c0f8a77c 100644 --- a/rust/crates/psychoscript/src/diagnostic.rs +++ b/rust/crates/psychoscript/src/diagnostic.rs @@ -15,6 +15,12 @@ pub struct Limits { /// [`MAX_VALUE_DEPTH_LIMIT`](crate::MAX_VALUE_DEPTH_LIMIT), as the copies recurse on the native stack once a /// level. A value nested deeper fails with a `TypeError` (a `RangeError` for the result and `JSON.stringify`). pub max_value_depth: Option, + /// The most bytes of source code [`Runtime::compile`](crate::Runtime::compile) and + /// [`Runtime::execute`](crate::Runtime::execute) accept; `None` (the default) is + /// [`DEFAULT_MAX_SOURCE_BYTES`](crate::DEFAULT_MAX_SOURCE_BYTES) (256 KiB). What compiling costs grows with it: + /// a source nested past `MAX_COMPILE_LEVELS` is refused before it is parsed, which for 1 MiB of `[` takes 16 ms + /// and 48 MiB in a release build. + pub max_source_bytes: Option, /// What `timeout_ms` and `slice_ms` count; [`Clock::Wall`] by default. pub clock: Clock, /// The longest a run may compute without awaiting the host: from its start or resume, or from when a host call it @@ -26,6 +32,13 @@ pub struct Limits { pub slice_ms: Option, } +impl Limits { + pub(crate) fn source_limit(&self) -> usize { + self.max_source_bytes + .unwrap_or(crate::DEFAULT_MAX_SOURCE_BYTES) + } +} + /// What a run's `timeout_ms` and `slice_ms` count. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Clock { diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index e8d4e0c3..58cd3d58 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -53,6 +53,7 @@ mod time; mod value; mod vm; +pub use compiler::DEFAULT_MAX_SOURCE_BYTES; pub use convert::MAX_VALUE_DEPTH_LIMIT; pub use data::Data; pub use diagnostic::{Clock, Diagnostic, DiagnosticKind, Interrupted, Limits}; diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index 466648b7..9bfbf288 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -88,9 +88,10 @@ impl<'a> From<&'a Compiled> for Code<'a> { } /// Parses and compiles a program, or the diagnostic a run of it would fail with before running anything. -pub fn compile_program(code: &str) -> Result { +pub fn compile_program(code: &str, max_source_bytes: usize) -> Result { let mut atoms = Strings::fresh(); - let program = compile(code, &mut atoms).map_err(|e| compile_diagnostic(code, e))?; + let program = + compile(code, &mut atoms, max_source_bytes).map_err(|e| compile_diagnostic(code, e))?; Ok(Compiled(Arc::new(CompiledProgram { code: Arc::from(code), program, @@ -119,7 +120,18 @@ pub fn execute(rt: &Runtime, code: Code<'_>, options: &ProgramOptions) -> Outcom /// more native stack for deep syntax, so only compiling moves. On `wasm32`, where spawning a helper thread is /// unsupported, programs exceeding `RUN_STACK_BUDGET` return an error instead of attempting to spawn or overflowing /// the wasm stack. -pub fn compile(code: &str, atoms: &mut Strings) -> Result { +pub fn compile( + code: &str, + atoms: &mut Strings, + max_source_bytes: usize, +) -> Result { + if code.len() > max_source_bytes { + return Err(CompileError { + kind: DiagnosticKind::ParseError, + message: format!("Program is larger than {max_source_bytes} bytes."), + offset: None, + }); + } // A program nests no deeper than it has bytes, so a short one needs no scan to know it fits. let fits = |levels: usize| levels.saturating_mul(COMPILE_STACK_PER_LEVEL) <= RUN_STACK_BUDGET; let need = match fits(code.len()) { @@ -199,7 +211,7 @@ pub fn start( Code::Compiled(c) => (c.0.code.clone(), c.0.program.clone(), c.0.atoms.clone()), Code::Source(code) => { let mut atoms = Strings::fresh(); - match compile(code, &mut atoms) { + match compile(code, &mut atoms, rt.setup().limits.source_limit()) { Ok(p) => (Arc::from(code), p, atoms), Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))), } @@ -245,7 +257,8 @@ pub fn start_for_resume( ) -> Result { let code = restored.code; let mut atoms = Strings::fresh(); - let mut program = compile(&code, &mut atoms).map_err(|_| { + // The run that saved the state accepted its source: it compiles again whatever its size. + let mut program = compile(&code, &mut atoms, code.len()).map_err(|_| { crate::snapshot::SnapshotError::new( "Source main does not compile in this build, so it can't resume.", ) diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 2fe93056..a680d01c 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -283,8 +283,9 @@ impl Runtime { /// /// # Panics /// - /// When `timeout_ms` or `max_heap_bytes` is `Some(0)`, or `max_value_depth` is `Some(0)` or more than - /// [`MAX_VALUE_DEPTH_LIMIT`](crate::MAX_VALUE_DEPTH_LIMIT), which the reference refuses with a `RangeError`. + /// When `timeout_ms`, `max_heap_bytes` or `max_source_bytes` is `Some(0)`, or `max_value_depth` is `Some(0)` or + /// more than [`MAX_VALUE_DEPTH_LIMIT`](crate::MAX_VALUE_DEPTH_LIMIT), which the reference refuses with a + /// `RangeError`. pub fn limits(mut self, limits: Limits) -> Self { assert!( limits.timeout_ms != Some(0), @@ -301,6 +302,10 @@ impl Runtime { "maxValueDepth must be an integer from 1 to {}.", crate::MAX_VALUE_DEPTH_LIMIT ); + assert!( + limits.max_source_bytes != Some(0), + "max_source_bytes must be at least 1." + ); self.setup.limits = limits; self } @@ -369,7 +374,7 @@ impl Runtime { /// without doing it again; or the diagnostic a run of it would fail with first (an empty program, a syntax /// error). Unsupported syntax still fails where it runs, as from source. A compiled program runs in any runtime. pub fn compile(&self, code: &str) -> Result { - crate::run::compile_program(code) + crate::run::compile_program(code, self.setup.limits.source_limit()) } /// A program continuing a suspended run, from its state. It keeps the limits it was saved with, and its globals diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index faa41a6b..e1d485ef 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -562,8 +562,10 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { }; let state = enc.state(c).map_err(|e| Refusal::Other(e.message))?; let base = vm.snapshot_base; - let program = crate::run::compile(c.code, &mut crate::strings::Strings::fresh()) - .map_err(|e| Refusal::Other(e.message))?; + // The run accepted its source when it started: it compiles again whatever its size. + let fresh = &mut crate::strings::Strings::fresh(); + let program = + crate::run::compile(c.code, fresh, c.code.len()).map_err(|e| Refusal::Other(e.message))?; let limits = *vm.limits; // Deep metadata is saved flat: as plain JSON, it would pass the nesting limit of the JSON reader in `from_bytes`. let (metadata, metadata_data) = vm.host.run.update_metadata(|m| { @@ -1130,8 +1132,8 @@ fn hex_bytes(s: &str) -> R> { /// Each object of a fresh run's base, encoded, to see which ones the run changed. fn baseline(vm: &Vm, code: &str) -> R> { let mut atoms = crate::strings::Strings::fresh(); - let program = - crate::run::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?; + let program = crate::run::compile(code, &mut atoms, code.len()) + .map_err(|e| SnapshotError::new(e.message))?; let h = &vm.host; let host = host::RunHost::new( h.globals.clone(), @@ -2536,6 +2538,8 @@ pub fn header(snapshot: &Snapshot) -> R { .ok_or_else(|| invalid("the value depth is out of range."))?, ), }, + // Not saved: it bounds the source a run starts from, and a state brings its own. + max_source_bytes: None, }, active_ms: field(budget, "activeMs")?.as_u64().unwrap_or(0), }) diff --git a/rust/crates/psychoscript/tests/source_limit.rs b/rust/crates/psychoscript/tests/source_limit.rs new file mode 100644 index 00000000..9164dd4f --- /dev/null +++ b/rust/crates/psychoscript/tests/source_limit.rs @@ -0,0 +1,92 @@ +//! `Limits::max_source_bytes`: defaults to `DEFAULT_MAX_SOURCE_BYTES` (256 KiB) and survives suspend/resume. + +use std::sync::mpsc; + +use psychoscript::{ + DEFAULT_MAX_SOURCE_BYTES, DiagnosticKind, HostFunction, HostValue, Limits, ProgramOptions, + RunOutcome, Runtime, from_bytes, to_bytes, +}; +use serde_json::json; + +fn padded(bytes: usize, tail: &str) -> String { + format!( + "// {}\n{tail}", + "a".repeat(bytes.saturating_sub(tail.len() + 4)) + ) +} + +#[test] +fn source_size_bound_defaults_to_256kib_and_is_configurable() { + let over_default = padded(DEFAULT_MAX_SOURCE_BYTES + 1, "return 42"); + let err = Runtime::make().compile(&over_default).unwrap_err(); + assert_eq!(err.kind, DiagnosticKind::ParseError); + assert!( + err.message_lossy() + .contains(&DEFAULT_MAX_SOURCE_BYTES.to_string()) + ); + + let one_mib = 1 << 20; + let rt = Runtime::make().limits(Limits { + max_source_bytes: Some(one_mib), + ..Limits::default() + }); + let at_1m = padded(one_mib, "return 99"); + assert_eq!(at_1m.len(), one_mib); + let compiled = rt.compile(&at_1m).expect("1 MiB fits under 1 MiB limit"); + assert_eq!(rt.execute(&compiled).json().unwrap(), json!(99)); + assert_eq!(rt.execute(at_1m.as_str()).json().unwrap(), json!(99)); + assert_eq!( + rt.compile(&padded(one_mib + 1, "return 99")) + .unwrap_err() + .kind, + DiagnosticKind::ParseError + ); +} + +#[test] +fn large_program_survives_suspend_and_resume() { + let (started, ready) = mpsc::channel(); + let rt1 = Runtime::make() + .limits(Limits { + max_source_bytes: Some(1 << 20), + ..Limits::default() + }) + .globals(move |_| { + let started = started.clone(); + [( + "wait", + HostFunction::new_async(move |_, _| { + let _ = started.send(()); + std::future::pending() + }) + .idempotent(), + )] + }); + let code = padded(300 * 1024, "await wait(); return 7"); + let program = rt1.program(code.as_str(), &ProgramOptions::new()); + let suspender = program.suspender(); + let state = std::thread::scope(|s| { + let h = s.spawn(move || { + ready.recv().unwrap(); + suspender.suspend(None).unwrap() + }); + let _ = program.run_resumable().unwrap(); + let RunOutcome::Suspended(suspended) = h.join().unwrap() else { + panic!("expected suspended") + }; + suspended.state + }); + let state = from_bytes(&to_bytes(&state)).unwrap(); + + // Resumes on a default-limit runtime: the limit bounds the source a run starts from, not a saved state's. + let rt2 = Runtime::make().globals(|_| { + [( + "wait", + HostFunction::new_async(|_, _| async { Ok(HostValue::Undefined) }).idempotent(), + )] + }); + let RunOutcome::Done(outcome) = rt2.resume(&state).unwrap().run_resumable().unwrap() else { + panic!("expected done") + }; + assert_eq!(outcome.json().unwrap(), json!(7)); +}