diff --git a/changelog.d/16005-wasm-global-exception-flag.md b/changelog.d/16005-wasm-global-exception-flag.md new file mode 100644 index 00000000000..f0f6238a02a --- /dev/null +++ b/changelog.d/16005-wasm-global-exception-flag.md @@ -0,0 +1 @@ +- wasm: export mutable `__perry_has_exc` and `__perry_arg_sp` globals, replacing per-call `rt.has_exception` checks with `global.get` and factoring unguarded exception unwind helpers. diff --git a/crates/perry-codegen-wasm/src/emit/compile.rs b/crates/perry-codegen-wasm/src/emit/compile.rs index b101ee9e5a9..8ca8abba06a 100644 --- a/crates/perry-codegen-wasm/src/emit/compile.rs +++ b/crates/perry-codegen-wasm/src/emit/compile.rs @@ -1084,6 +1084,10 @@ impl WasmModuleEmitter { // reads the counter. let start_idx = user_func_idx; let start_type = t_void; + let exc_prop_void_type = self.get_type_idx(vec![ValType::I32], vec![]); + let exc_prop_i64_type = self.get_type_idx(vec![ValType::I32], vec![ValType::I64]); + self.exc_propagate_void_fn = start_idx + 1; + self.exc_propagate_i64_fn = start_idx + 2; // Issue #1071: build cross-module imported-variable → WASM global map. // The HIR lowers `import { FOO } from './m'` value reads (where FOO is @@ -1255,6 +1259,10 @@ impl WasmModuleEmitter { // Add a NaN-safe temp global for mem_store_slot (Firefox canonicalizes locals) self.nan_temp_global = self.num_globals; self.num_globals += 1; + self.has_exc_global = self.num_globals; + self.num_globals += 1; + self.wasm_depth_global = self.num_globals; + self.num_globals += 1; // Build the WASM module let mut wasm_module = Module::new(); @@ -1382,6 +1390,8 @@ impl WasmModuleEmitter { } // _start func_section.function(start_type); + func_section.function(exc_prop_void_type); + func_section.function(exc_prop_i64_type); wasm_module.section(&func_section); // --- Table section (for indirect calls / closures) --- @@ -1480,15 +1490,22 @@ impl WasmModuleEmitter { if self.num_globals > 0 { let mut global_section = GlobalSection::new(); for g in 0..self.num_globals { - if g == self.nan_temp_global { - // Stack pointer for arg buffer (i32, initialized to 0x10000) + if g == self.nan_temp_global + || g == self.has_exc_global + || g == self.wasm_depth_global + { + let init = if g == self.nan_temp_global { + 0x10000 + } else { + 0 + }; global_section.global( GlobalType { val_type: ValType::I32, mutable: true, shared: false, }, - &wasm_encoder::ConstExpr::i32_const(0x10000), + &wasm_encoder::ConstExpr::i32_const(init), ); } else { // Regular i64 global for module-level variables (NaN-boxed) @@ -1521,6 +1538,13 @@ impl WasmModuleEmitter { export_section.export("_start", ExportKind::Func, start_idx); export_section.export("memory", ExportKind::Memory, 0); export_section.export("__indirect_function_table", ExportKind::Table, 0); + export_section.export("__perry_arg_sp", ExportKind::Global, self.nan_temp_global); + export_section.export("__perry_has_exc", ExportKind::Global, self.has_exc_global); + export_section.export( + "__perry_wasm_depth", + ExportKind::Global, + self.wasm_depth_global, + ); // Export all user functions so async JS code can call them by index. for idx in self.num_imports..start_idx { export_section.export(&format!("__wasm_func_{}", idx), ExportKind::Func, idx); @@ -1919,6 +1943,7 @@ impl WasmModuleEmitter { func.instruction(&Instruction::End); code_section.function(&func); } + self.emit_exc_propagate_helpers(&mut code_section); wasm_module.section(&code_section); diff --git a/crates/perry-codegen-wasm/src/emit/exception_flag_tests.rs b/crates/perry-codegen-wasm/src/emit/exception_flag_tests.rs new file mode 100644 index 00000000000..fc1abb1bf11 --- /dev/null +++ b/crates/perry-codegen-wasm/src/emit/exception_flag_tests.rs @@ -0,0 +1,990 @@ +//! Verification for exported `__perry_has_exc` / `__perry_arg_sp` Wasm globals, +//! replacement of `rt.has_exception` calls with `global.get`, arg-stack unwinding, +//! Wasm->JS->Wasm reentrancy, and async rejection semantics. + +use super::*; +use perry_base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; + +struct Cursor<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Cursor<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, pos: 0 } + } + + fn remaining(&self) -> usize { + self.bytes.len() - self.pos + } + + fn read_u8(&mut self) -> u8 { + let byte = self.bytes[self.pos]; + self.pos += 1; + byte + } + + fn read_bytes(&mut self, len: usize) -> &'a [u8] { + let slice = &self.bytes[self.pos..self.pos + len]; + self.pos += len; + slice + } + + fn read_u32_leb(&mut self) -> u32 { + let mut result = 0u32; + let mut shift = 0u32; + loop { + let byte = self.read_u8(); + result |= ((byte & 0x7f) as u32) << shift; + if (byte & 0x80) == 0 { + return result; + } + shift += 7; + } + } + + fn read_i64_leb(&mut self) -> i64 { + let mut result = 0i64; + let mut shift = 0u32; + loop { + let byte = self.read_u8(); + result |= ((byte & 0x7f) as i64) << shift; + shift += 7; + if (byte & 0x80) == 0 { + if shift < 64 && (byte & 0x40) != 0 { + result |= !0i64 << shift; + } + return result; + } + } + } + + fn read_str(&mut self) -> &'a str { + let len = self.read_u32_leb() as usize; + std::str::from_utf8(self.read_bytes(len)).unwrap() + } +} + +struct GlobalMeta { + val_type: u8, + mutable: bool, + init_i32: Option, +} + +struct WasmExceptionInspection { + has_exc_import_idx: Option, + has_exc_global: Option<(u32, GlobalMeta)>, + arg_sp_global: Option<(u32, GlobalMeta)>, + has_exc_calls: usize, + has_exc_global_gets: usize, +} + +fn inspect_wasm_exception_wiring(wasm: &[u8]) -> WasmExceptionInspection { + assert_eq!(&wasm[0..4], b"\0asm"); + assert_eq!(&wasm[4..8], &[1, 0, 0, 0]); + let mut cursor = Cursor::new(&wasm[8..]); + + let mut has_exc_import_idx = None; + let mut globals: Vec = Vec::new(); + let mut has_exc_export_idx = None; + let mut arg_sp_export_idx = None; + let mut code_section: Option<&[u8]> = None; + + while cursor.remaining() > 0 { + let section_id = cursor.read_u8(); + let section_len = cursor.read_u32_leb() as usize; + let payload = cursor.read_bytes(section_len); + let mut sec = Cursor::new(payload); + match section_id { + 2 => { + let count = sec.read_u32_leb(); + let mut func_import_idx = 0u32; + for _ in 0..count { + let module = sec.read_str(); + let name = sec.read_str(); + let kind = sec.read_u8(); + match kind { + 0x00 => { + let _type_idx = sec.read_u32_leb(); + if module == "rt" && name == "has_exception" { + has_exc_import_idx = Some(func_import_idx); + } + func_import_idx += 1; + } + 0x01 => { + let _elem = sec.read_u8(); + let flags = sec.read_u8(); + let _min = sec.read_u32_leb(); + if (flags & 1) != 0 { + let _max = sec.read_u32_leb(); + } + } + 0x02 => { + let flags = sec.read_u8(); + let _min = sec.read_u32_leb(); + if (flags & 1) != 0 { + let _max = sec.read_u32_leb(); + } + } + 0x03 => { + let _val_type = sec.read_u8(); + let _mutable = sec.read_u8(); + } + other => panic!("unexpected import kind 0x{other:02x}"), + } + } + } + 6 => { + let count = sec.read_u32_leb(); + for _ in 0..count { + let val_type = sec.read_u8(); + let mutable = sec.read_u8() == 1; + let init_op = sec.read_u8(); + let init_i32 = match init_op { + 0x41 => Some(sec.read_i64_leb() as i32), + 0x42 => { + let _ = sec.read_i64_leb(); + None + } + 0x43 => { + sec.read_bytes(4); + None + } + 0x44 => { + sec.read_bytes(8); + None + } + other => panic!("unexpected global init opcode 0x{other:02x}"), + }; + assert_eq!(sec.read_u8(), 0x0b, "global init expr must end with 0x0b"); + globals.push(GlobalMeta { + val_type, + mutable, + init_i32, + }); + } + } + 7 => { + let count = sec.read_u32_leb(); + for _ in 0..count { + let name = sec.read_str(); + let kind = sec.read_u8(); + let idx = sec.read_u32_leb(); + if name == "__perry_has_exc" { + assert_eq!(kind, 0x03, "__perry_has_exc must export a global"); + has_exc_export_idx = Some(idx); + } else if name == "__perry_arg_sp" { + assert_eq!(kind, 0x03, "__perry_arg_sp must export a global"); + arg_sp_export_idx = Some(idx); + } + } + } + 10 => { + code_section = Some(payload); + } + _ => {} + } + } + + let mut has_exc_calls = 0usize; + let mut has_exc_global_gets = 0usize; + + if let Some(code) = code_section { + let mut sec = Cursor::new(code); + let body_count = sec.read_u32_leb(); + for _ in 0..body_count { + let body_len = sec.read_u32_leb() as usize; + let body_bytes = sec.read_bytes(body_len); + let mut body = Cursor::new(body_bytes); + let local_decl_count = body.read_u32_leb(); + for _ in 0..local_decl_count { + let _n = body.read_u32_leb(); + let _ty = body.read_u8(); + } + while body.remaining() > 0 { + let opcode = body.read_u8(); + match opcode { + 0x00 | 0x01 | 0x05 | 0x0b | 0x0f | 0x1a | 0x1b | 0x45..=0xc4 => {} + 0x02..=0x04 => { + let _ = body.read_i64_leb(); + } + 0x0c | 0x0d => { + let _ = body.read_u32_leb(); + } + 0x0e => { + let targets = body.read_u32_leb(); + for _ in 0..=targets { + let _ = body.read_u32_leb(); + } + } + 0x10 => { + let callee = body.read_u32_leb(); + if has_exc_import_idx == Some(callee) { + has_exc_calls += 1; + } + } + 0x11 => { + let _ = body.read_u32_leb(); + let _ = body.read_u32_leb(); + } + 0x20..=0x22 | 0x24 => { + let _ = body.read_u32_leb(); + } + 0x23 => { + let global_idx = body.read_u32_leb(); + if has_exc_export_idx == Some(global_idx) { + has_exc_global_gets += 1; + } + } + 0x28..=0x3e => { + let _ = body.read_u32_leb(); + let _ = body.read_u32_leb(); + } + 0x3f | 0x40 => { + let _ = body.read_u8(); + } + 0x41 | 0x42 => { + let _ = body.read_i64_leb(); + } + 0x43 => { + let _ = body.read_bytes(4); + } + 0x44 => { + let _ = body.read_bytes(8); + } + 0xfc => { + let sub = body.read_u32_leb(); + match sub { + 0..=7 => {} + 8 => { + let _ = body.read_u32_leb(); + let _ = body.read_u32_leb(); + } + 9 => { + let _ = body.read_u32_leb(); + } + 10 => { + let _ = body.read_bytes(2); + } + 11 => { + let _ = body.read_u8(); + } + other => panic!("unexpected 0xfc sub-opcode {other}"), + } + } + other => panic!("unexpected wasm opcode 0x{other:02x}"), + } + } + } + } + + let has_exc_global = has_exc_export_idx.map(|idx| { + let meta = &globals[idx as usize]; + ( + idx, + GlobalMeta { + val_type: meta.val_type, + mutable: meta.mutable, + init_i32: meta.init_i32, + }, + ) + }); + let arg_sp_global = arg_sp_export_idx.map(|idx| { + let meta = &globals[idx as usize]; + ( + idx, + GlobalMeta { + val_type: meta.val_type, + mutable: meta.mutable, + init_i32: meta.init_i32, + }, + ) + }); + + WasmExceptionInspection { + has_exc_import_idx, + has_exc_global, + arg_sp_global, + has_exc_calls, + has_exc_global_gets, + } +} + +fn compile_source_output(source: &str) -> crate::emit::WasmCompileOutput { + let ast = perry_parser::parse_typescript(source, "exc_flag.ts").unwrap(); + let mut module = perry_hir::lower::lower_module(&ast, "exc_flag", "exc_flag.ts").unwrap(); + perry_transform::inline_finally_into_returns(&mut module); + perry_transform::transform_generators_without_private_frames(&mut module); + crate::emit::compile_to_wasm_with_async(&[("exc_flag.ts".to_string(), module)]) +} + +fn run_node_script(script: &str) -> String { + let mut child = Command::new("node") + .arg("-") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("Node is required for WASM semantics tests"); + child + .stdin + .take() + .unwrap() + .write_all(script.as_bytes()) + .unwrap(); + let result = child.wait_with_output().unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + String::from_utf8(result.stdout).unwrap().trim().to_string() +} + +fn build_runtime_harness( + source: &str, + before_boot: &str, + driver: &str, +) -> (crate::emit::WasmCompileOutput, String) { + let output = compile_source_output(source); + let b64 = BASE64.encode(&output.wasm_bytes); + let async_inject = if output.async_js.is_empty() { + String::new() + } else { + format!("const __asyncFuncImpls = {{\n{}\n}};\n", output.async_js) + }; + let runtime = crate::WASM_RUNTIME_JS; + let script = format!( + r#" +globalThis.window = globalThis; +{STUB_DOM} +{before_boot} +(async () => {{ +{runtime} +{async_inject} +const WASM_B64 = "{b64}"; +{driver} +}})().catch(e => {{ console.error(e); process.exitCode = 1; }}); +"# + ); + (output, script) +} + +#[test] +fn wasm_exports_mutable_exception_and_arg_sp_globals_without_has_exception_calls() { + let source = r#" +function fail(tag: string): number { + throw new Error(tag); +} +function run(): void { + try { + try { + fail("inner"); + } catch (e) { + console.log("caught:" + (e as Error).message); + throw new Error("outer"); + } finally { + console.log("inner-finally"); + } + } catch (e) { + console.log("outer:" + (e as Error).message); + } finally { + console.log("outer-finally"); + } +} +run(); +"#; + let (output, script) = build_runtime_harness( + source, + "", + r#" +const assert = require('node:assert/strict'); +const wasmBytes = Uint8Array.from(atob(WASM_B64), c => c.charCodeAt(0)); +const imports = wrapImportsForI64(buildImports()); +imports.rt.has_exception = () => { + throw new Error('Wasm must read __perry_has_exc instead of calling rt.has_exception'); +}; +const { instance } = await WebAssembly.instantiate(wasmBytes, imports); +wasmInstance = instance; +wasmMemory = instance.exports.memory; +assert.ok(instance.exports.__perry_has_exc instanceof WebAssembly.Global); +assert.ok(instance.exports.__perry_arg_sp instanceof WebAssembly.Global); +assert.equal(instance.exports.__perry_has_exc.value, 0); +assert.equal(instance.exports.__perry_arg_sp.value, 0x10000); +instance.exports.__perry_has_exc.value = 1; +assert.equal(instance.exports.__perry_has_exc.value, 1); +instance.exports.__perry_has_exc.value = 0; +instance.exports._start(); +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(instance.exports.__perry_has_exc.value, 0); +assert.equal(instance.exports.__perry_arg_sp.value, 0x10000); +// Swapping `wasmInstance` to a fresh direct instantiation must lazily rebind the flag global. +const { instance: instance2 } = await WebAssembly.instantiate(wasmBytes, imports); +wasmInstance = instance2; +wasmMemory = instance2.exports.memory; +__memDispatch.throw_value(new Error('swap-check')); +assert.equal(instance2.exports.__perry_has_exc.value, 1); +assert.equal(instance.exports.__perry_has_exc.value, 0); +__memDispatch.get_exception(); +assert.equal(instance2.exports.__perry_has_exc.value, 0); +"#, + ); + + let info = inspect_wasm_exception_wiring(&output.wasm_bytes); + assert!( + info.has_exc_import_idx.is_some(), + "rt.has_exception import declaration should remain present for ABI compatibility" + ); + let (_, has_exc) = info + .has_exc_global + .expect("__perry_has_exc global export must be present"); + assert_eq!(has_exc.val_type, 0x7f, "__perry_has_exc must be i32"); + assert!(has_exc.mutable, "__perry_has_exc must be mutable"); + assert_eq!(has_exc.init_i32, Some(0), "__perry_has_exc must init to 0"); + + let (_, arg_sp) = info + .arg_sp_global + .expect("__perry_arg_sp global export must be present"); + assert_eq!(arg_sp.val_type, 0x7f, "__perry_arg_sp must be i32"); + assert!(arg_sp.mutable, "__perry_arg_sp must be mutable"); + assert_eq!( + arg_sp.init_i32, + Some(0x10000), + "__perry_arg_sp must init to 0x10000" + ); + assert_eq!( + info.has_exc_calls, 0, + "Wasm function bodies must not call rt.has_exception" + ); + assert!( + info.has_exc_global_gets > 0, + "Wasm exception guards and handlers must read __perry_has_exc via global.get" + ); + + assert_eq!( + run_node_script(&script), + "caught:inner\ninner-finally\nouter:outer\nouter-finally" + ); +} + +#[test] +fn sync_try_catch_finally_and_nested_try_keep_flag_and_sp_clean() { + assert_eq!( + run_web_source_then( + r#" +function boom(msg: string): string { + throw new Error(msg); +} +function nestedArgUnwind(prefix: string): string { + // Forces an open outer argument frame in an unguarded helper when `boom` throws. + return [prefix, boom("from-arg")].join(":"); +} +function testAll(): void { + try { + console.log(nestedArgUnwind("p")); + } catch (e) { + console.log("unwind:" + (e as Error).message); + } + try { + try { + throw null; + } finally { + console.log("null-finally"); + } + } catch (e) { + console.log("null:" + String(e)); + } + try { + try { + boom("first"); + } finally { + boom("override"); + } + } catch (e) { + console.log("override:" + (e as Error).message); + } + try { + JSON.parse("{bad"); + console.log("json-unreachable"); + } catch (e) { + console.log("json-caught:" + (e instanceof SyntaxError)); + } +} +testAll(); +"#, + r#" +const assert = require('node:assert/strict'); +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); +"# + ), + "unwind:from-arg\nnull-finally\nnull:null\noverride:override\njson-caught:true" + ); +} + +#[test] +fn uncaught_exception_unwinds_arg_sp_and_clears_exc_flag() { + let source = r#" +function boom(): string { + throw new Error("uncaught-boom"); +} +function ok(): string { + return "still-alive"; +} +console.log("before", boom()); +console.log(ok()); +"#; + let (_, script) = build_runtime_harness( + source, + "", + r#" +const assert = require('node:assert/strict'); +let caught = null; +try { + await bootPerryWasm(WASM_B64); +} catch (e) { + caught = e; +} +assert.ok(caught instanceof Error); +assert.equal(caught.message, "uncaught-boom"); +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); +console.log("sp-clean-throw"); +"#, + ); + assert_eq!(run_node_script(&script), "sp-clean-throw"); + + let memcall_source = r#" +console.log("prefix", decodeURIComponent("%E0%A4%A")); +"#; + let (_, memcall_script) = build_runtime_harness( + memcall_source, + "", + r#" +const assert = require('node:assert/strict'); +let caught = null; +try { + await bootPerryWasm(WASM_B64); +} catch (e) { + caught = e; +} +assert.ok(caught instanceof URIError); +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); +// Direct WebAssembly.instantiate without bootPerryWasm also restores `__perry_arg_sp` on throw. +const wasmBytes = Uint8Array.from(atob(WASM_B64), c => c.charCodeAt(0)); +const { instance } = await WebAssembly.instantiate(wasmBytes, wrapImportsForI64(buildImports())); +wasmInstance = instance; +wasmMemory = instance.exports.memory; +assert.throws(() => instance.exports._start(), e => e instanceof URIError); +assert.equal(instance.exports.__perry_has_exc.value, 0); +assert.equal(instance.exports.__perry_arg_sp.value, 0x10000); +console.log("sp-clean-memcall"); +"#, + ); + assert_eq!(run_node_script(&memcall_script), "sp-clean-memcall"); +} + +#[test] +fn wasm_js_wasm_reentrant_exceptions_isolate_inner_and_deliver_outer() { + let source = r#" +function runReentrant(): void { + // 1. Inner Wasm try/catch inside JS array.map callback must not leak into outer try. + try { + const mapped = [1, 2, 3].map((x) => { + try { + if (x === 2) throw new Error("inner-handled"); + return x * 10; + } catch (e) { + return -1; + } + }); + console.log("inner-isolated:" + mapped.join(",")); + } catch (e) { + console.log("unexpected-outer-1:" + (e as Error).message); + } + + // 2. Uncaught throw from inner Wasm callback propagates through JS back to outer catch. + try { + [1, 2, 3].map((x) => { + if (x === 2) throw new Error("propagate-2"); + return x; + }); + console.log("unreachable-2"); + } catch (e) { + console.log("outer-caught-map:" + (e as Error).message); + } + + // 3. JS host catches inner Wasm throw and returns normally: outer Wasm try stays clean. + try { + const res = (globalThis as any).__hostSafeRun(() => { + throw new Error("caught-in-host"); + }); + console.log("host-caught:" + res); + } catch (e) { + console.log("unexpected-outer-3:" + (e as Error).message); + } + + // 4. JS host lets inner Wasm throw propagate while outer has an open arg frame. + try { + console.log( + "pair", + (globalThis as any).__hostPassThrough(() => { + throw new Error("host-passthrough"); + }) + ); + } catch (e) { + console.log("outer-caught-host:" + (e as Error).message); + } +} + +runReentrant(); +"#; + let (_, script) = build_runtime_harness( + source, + r#" +globalThis.__hostSafeRun = (fn) => { + try { + return fn(); + } catch (e) { + return "js:" + e.message; + } +}; +globalThis.__hostPassThrough = (fn) => fn(); +"#, + r#" +const assert = require('node:assert/strict'); +await bootPerryWasm(WASM_B64); +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); + +// External host re-entering Wasm while an outer exception is pending must preserve +// both `currentException` and `__perry_has_exc.value`. +const pending = new Error("outer-pending"); +__memDispatch.try_start(); +__memDispatch.throw_value(pending); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 1); +const preserved = __runWasmBoundary(() => { + assert.equal(__memDispatch.has_exception(), 0); + assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); + return "inner-ok"; +}); +assert.equal(preserved, "inner-ok"); +assert.equal(__memDispatch.has_exception(), 1); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 1); +assert.equal(__memDispatch.get_exception(), pending); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +__memDispatch.try_end(); +console.log("boundary-preserved"); +"#, + ); + assert_eq!( + run_node_script(&script), + "inner-isolated:10,-1,30\nouter-caught-map:propagate-2\nhost-caught:js:caught-in-host\nouter-caught-host:host-passthrough\nboundary-preserved" + ); +} + +#[test] +fn async_function_throw_and_calling_throwing_wasm_rejects_cleanly() { + let source = r#" +function syncBoom(tag: string): number { + throw new Error(tag); +} +async function directThrow(): Promise { + throw new Error("async-direct"); +} +async function callsThrowingWasm(): Promise { + return syncBoom("wasm-sync-boom"); +} +async function catchesWasmThrow(): Promise { + try { + syncBoom("handled-in-async"); + return "unreachable"; + } catch (e) { + return "async-caught:" + (e as Error).message; + } +} +async function drive(): Promise { + try { + await directThrow(); + console.log("direct-unreachable"); + } catch (e) { + console.log("direct-rejected:" + (e as Error).message); + } + // Start an async function whose synchronous prefix throws from Wasm while + // inside a sync try: the promise must reject without leaking into the sync catch. + let pending: Promise; + try { + pending = callsThrowingWasm(); + console.log("sync-try-clean"); + } catch (e) { + console.log("unexpected-sync-catch:" + (e as Error).message); + return; + } + try { + await pending; + console.log("wasm-unreachable"); + } catch (e) { + console.log("wasm-rejected:" + (e as Error).message); + } + console.log(await catchesWasmThrow()); + try { + await Promise.resolve(1).then(() => syncBoom("then-boom")); + console.log("then-unreachable"); + } catch (e) { + console.log("then-rejected:" + (e as Error).message); + } +} +(globalThis as any).__driveDone = drive(); +"#; + let (_, script) = build_runtime_harness( + source, + "", + r#" +const assert = require('node:assert/strict'); +await bootPerryWasm(WASM_B64); +await globalThis.__driveDone; +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); +"#, + ); + assert_eq!( + run_node_script(&script), + "direct-rejected:async-direct\nsync-try-clean\nwasm-rejected:wasm-sync-boom\nasync-caught:handled-in-async\nthen-rejected:then-boom" + ); +} + +#[test] +fn bare_export_cross_function_throw_restores_outer_frame_sp() { + let source = r#" +function inner(): string { + return decodeURIComponent("%E0%A4%A"); +} +function outer(): void { + console.log("prefix", inner()); +} +outer(); +"#; + let (_, script) = build_runtime_harness( + source, + "", + r#" +const assert = require('node:assert/strict'); +const wasmBytes = Uint8Array.from(atob(WASM_B64), c => c.charCodeAt(0)); +const { instance } = await WebAssembly.instantiate(wasmBytes, wrapImportsForI64(buildImports())); +wasmInstance = instance; +wasmMemory = instance.exports.memory; +assert.throws(() => instance.exports._start(), e => e instanceof URIError); +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(instance.exports.__perry_has_exc.value, 0); +assert.equal(instance.exports.__perry_arg_sp.value, 0x10000); +assert.throws(() => instance.exports._start(), e => e instanceof URIError); +assert.equal(instance.exports.__perry_arg_sp.value, 0x10000); +console.log("bare-cross-fn-clean"); +"#, + ); + assert_eq!(run_node_script(&script), "bare-cross-fn-clean"); +} + +#[test] +fn reentrant_host_catches_bare_export_cross_function_throw_and_returns_to_wasm() { + let source = r#" +function innerFail(): string { + return decodeURIComponent("%E0%A4%A"); +} +function outerFail(): string { + return ["lead", innerFail()].join(":"); +} +function callHostUnguarded(): string { + return (globalThis as any).hostCatchBare("tag", "val"); +} +function callHostGuarded(): string { + try { + return (globalThis as any).hostCatchBare("tag", "val"); + } catch (e) { + return "outer-caught:" + (e as Error).name; + } +} +function runAll(): void { + (globalThis as any).registerFail({ fn: () => outerFail() }); + if ((globalThis as any).shouldRun) { + console.log("unguarded:" + callHostUnguarded()); + console.log("guarded:" + callHostGuarded()); + } +} +runAll(); +"#; + let (_, script) = build_runtime_harness( + source, + "globalThis.shouldRun = false; globalThis.registerFail = (box) => { globalThis.__failClosure = box.fn; };", + r#" +const assert = require('node:assert/strict'); +await bootPerryWasm(WASM_B64); +assert.equal(typeof globalThis.__failClosure.funcIdx, 'number'); +const bareOuterFail = wasmInstance.exports.__indirect_function_table.get(globalThis.__failClosure.funcIdx | 0); +globalThis.hostCatchBare = (a, b) => { + const spBefore = wasmInstance.exports.__perry_arg_sp.value; + let saw = "none"; + try { + bareOuterFail(); + } catch (e) { + saw = e.name; + } + const spAfter = wasmInstance.exports.__perry_arg_sp.value; + return `${a}:${b}:${saw}:${spAfter === spBefore}`; +}; +globalThis.shouldRun = true; +wasmInstance.exports._start(); +assert.equal(tryDepth, 0); +assert.equal(__memDispatch.has_exception(), 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); +assert.equal(wasmInstance.exports.__perry_wasm_depth.value, 0); +"#, + ); + assert_eq!( + run_node_script(&script), + "unguarded:tag:val:URIError:true\nguarded:tag:val:URIError:true" + ); +} + +#[test] +fn ffi_and_async_reentry_and_throwing_ffi_keep_wasm_depth_clean() { + let source = r#" +declare function ffi_reenter(): string; +declare function ffi_reenter_raw(): number; +declare function ffi_throw(): void; + +function innerFail(): string { + return decodeURIComponent("%E0%A4%A"); +} +function outerFail(): string { + return ["lead", innerFail()].join(":"); +} +function midReenter(): string { + return ffi_reenter() + "|" + String(ffi_reenter_raw()); +} +function midThrow(): void { + ffi_throw(); +} +async function asyncSyncPrefixReenter(): Promise { + return (globalThis as any).invokeBareAndCatch(); +} +function midAsyncReenter(): Promise { + return asyncSyncPrefixReenter(); +} +function init(): void { + const g: any = globalThis; + g.__boxes = { + fail: () => outerFail(), + reenter: () => midReenter(), + throwFfi: () => midThrow(), + asyncReenter: () => midAsyncReenter(), + }; + if (g.__throwOnBoot) { + console.log("lead", midThrow()); + } +} +init(); +"#; + let (_, script) = build_runtime_harness( + source, + r#" +globalThis.__throwOnBoot = false; +"#, + r#" +const assert = require('node:assert/strict'); +let bareFail = null; +globalThis.invokeBareAndCatch = () => { + const spBefore = wasmInstance.exports.__perry_arg_sp.value; + const depthInside = wasmInstance.exports.__perry_wasm_depth.value; + let saw = "none"; + try { + bareFail(); + } catch (e) { + saw = e.name; + } + const spAfter = wasmInstance.exports.__perry_arg_sp.value; + return `${depthInside}:${saw}:${spAfter === spBefore}`; +}; +const rawReenter = () => { + const info = globalThis.invokeBareAndCatch(); + globalThis.__rawInfo = info; + return __jsValueToBits(7); +}; +rawReenter.__rawBigint = true; +const ffi = { + ffi_reenter: () => globalThis.invokeBareAndCatch(), + ffi_reenter_raw: rawReenter, + ffi_throw: () => { + if (globalThis.__throwOnBoot) { + globalThis.__bootThrowSp = wasmInstance.exports.__perry_arg_sp.value; + } + throw new RangeError("ffi-boom"); + }, +}; + +await bootPerryWasm(WASM_B64, ffi); +bareFail = wasmInstance.exports.__indirect_function_table.get(globalThis.__boxes.fail.funcIdx | 0); +const reenterFn = wasmInstance.exports.__indirect_function_table.get(globalThis.__boxes.reenter.funcIdx | 0); +const throwFn = wasmInstance.exports.__indirect_function_table.get(globalThis.__boxes.throwFfi.funcIdx | 0); +const asyncReenterFn = wasmInstance.exports.__indirect_function_table.get(globalThis.__boxes.asyncReenter.funcIdx | 0); + +// 1. Normal + __rawBigint FFI calls from nested Wasm reset depth to 0 so bare export throws into host catch. +const ffiOut = __bitsToJsValue(__invokeWasmCallback(reenterFn)); +assert.equal(ffiOut, "0:URIError:true|7"); +assert.equal(globalThis.__rawInfo, "0:URIError:true"); +assert.equal(wasmInstance.exports.__perry_wasm_depth.value, 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); + +// 2. Async import synchronous prefix from nested Wasm resets depth to 0 as well. +const asyncPromise = __bitsToJsValue(__invokeWasmCallback(asyncReenterFn)); +assert.equal(await asyncPromise, "0:URIError:true"); +assert.equal(wasmInstance.exports.__perry_wasm_depth.value, 0); + +// 3. Direct FFI throw when savedDepth === 0 restores depth back to 0 in __runWasmBoundary. +assert.throws(() => __invokeWasmCallback(throwFn), e => e instanceof RangeError && e.message === "ffi-boom"); +assert.equal(wasmInstance.exports.__perry_wasm_depth.value, 0); +assert.equal(wasmInstance.exports.__perry_has_exc.value, 0); +assert.throws(() => bareFail(), e => e instanceof URIError); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); + +// 4. Direct FFI throw through mem_call when savedDepth === 0 also restores depth to 0. +const closureCallId = stringTable.indexOf("closure_call_0"); +assert.ok(closureCallId >= 0); +const u64 = new BigUint64Array(wasmMemory.buffer, 0x10000, 1); +u64[0] = __jsValueToBits(globalThis.__boxes.throwFfi); +buildImports().rt.mem_call(closureCallId, 1, 0x10000); +assert.equal(wasmInstance.exports.__perry_wasm_depth.value, 0); +const captured = __memDispatch.get_exception(); +assert.ok(captured instanceof RangeError && captured.message === "ffi-boom"); +assert.throws(() => bareFail(), e => e instanceof URIError); + +// 5. Direct FFI throw during bootPerryWasm restores depth to 0 and SP to 0x10000. +globalThis.__throwOnBoot = true; +globalThis.__bootThrowSp = 0; +await assert.rejects(() => bootPerryWasm(WASM_B64, ffi), e => e instanceof RangeError && e.message === "ffi-boom"); +assert.ok(globalThis.__bootThrowSp > 0x10000); +assert.equal(wasmInstance.exports.__perry_wasm_depth.value, 0); +assert.equal(wasmInstance.exports.__perry_arg_sp.value, 0x10000); +const bareFail2 = wasmInstance.exports.__indirect_function_table.get(globalThis.__boxes.fail.funcIdx | 0); +assert.throws(() => bareFail2(), e => e instanceof URIError); +console.log("ffi-async-depth-clean"); +"#, + ); + assert_eq!(run_node_script(&script), "ffi-async-depth-clean"); +} diff --git a/crates/perry-codegen-wasm/src/emit/expr/calls.rs b/crates/perry-codegen-wasm/src/emit/expr/calls.rs index db7409b090c..e4ea3fc5ebc 100644 --- a/crates/perry-codegen-wasm/src/emit/expr/calls.rs +++ b/crates/perry-codegen-wasm/src/emit/expr/calls.rs @@ -60,8 +60,7 @@ impl<'a> FuncEmitCtx<'a> { func.instruction(&Instruction::Drop); } } - func.instruction(&Instruction::Call(idx)); - self.emit_exception_guard(func); + self.emit_wasm_call(func, idx); if self.emitter.void_funcs.contains(&idx) { func.instruction(&Instruction::I64Const(TAG_UNDEFINED as i64)); } @@ -264,8 +263,7 @@ impl<'a> FuncEmitCtx<'a> { func.instruction(&Instruction::Drop); } } - func.instruction(&Instruction::Call(idx)); - self.emit_exception_guard(func); + self.emit_wasm_call(func, idx); // Void functions don't push a return value; push undefined // so the caller always has a value on the stack. if self.emitter.void_funcs.contains(&idx) { @@ -303,8 +301,7 @@ impl<'a> FuncEmitCtx<'a> { func.instruction(&Instruction::Drop); } } - func.instruction(&Instruction::Call(idx)); - self.emit_exception_guard(func); + self.emit_wasm_call(func, idx); // Void functions don't push a return value, but call // expressions always need a value on the stack. Push undefined. if matches!(return_type, perry_hir::types::Type::Void) diff --git a/crates/perry-codegen-wasm/src/emit/expr/classes.rs b/crates/perry-codegen-wasm/src/emit/expr/classes.rs index 21bbd8c4b8a..1856eb40801 100644 --- a/crates/perry-codegen-wasm/src/emit/expr/classes.rs +++ b/crates/perry-codegen-wasm/src/emit/expr/classes.rs @@ -399,8 +399,7 @@ impl<'a> FuncEmitCtx<'a> { func.instruction(&Instruction::Drop); } } - func.instruction(&Instruction::Call(ctor_idx)); - self.emit_exception_guard(func); + self.emit_wasm_call(func, ctor_idx); } // If no compiled constructor, just leave the instance handle on stack } @@ -487,8 +486,7 @@ impl<'a> FuncEmitCtx<'a> { func.instruction(&Instruction::Drop); } } - func.instruction(&Instruction::Call(ctor_idx)); - self.emit_exception_guard(func); + self.emit_wasm_call(func, ctor_idx); func.instruction(&Instruction::Drop); // parent ctor returns this, discard called = true; } @@ -826,8 +824,7 @@ impl<'a> FuncEmitCtx<'a> { func.instruction(&Instruction::Drop); } } - func.instruction(&Instruction::Call(static_idx)); - self.emit_exception_guard(func); + self.emit_wasm_call(func, static_idx); return true; } } diff --git a/crates/perry-codegen-wasm/src/emit/memcall.rs b/crates/perry-codegen-wasm/src/emit/memcall.rs index e4280f22689..f9c2a893d0c 100644 --- a/crates/perry-codegen-wasm/src/emit/memcall.rs +++ b/crates/perry-codegen-wasm/src/emit/memcall.rs @@ -6,6 +6,42 @@ use super::*; +impl WasmModuleEmitter { + pub(super) fn emit_exc_propagate_helpers(&self, code_section: &mut CodeSection) { + let rt = self.rt.as_ref().unwrap(); + let prop_id = self + .string_map + .get("propagate_exception") + .copied() + .unwrap_or(0); + let mut prop_void = Function::new(vec![]); + prop_void.instruction(&Instruction::GlobalGet(self.nan_temp_global)); + prop_void.instruction(&Instruction::LocalGet(0)); + prop_void.instruction(&Instruction::I32Sub); + prop_void.instruction(&Instruction::GlobalSet(self.nan_temp_global)); + // Defer throwing across the JS boundary while an outer Wasm caller is still + // active so every caller unwinds its own open argument frames first. + prop_void.instruction(&Instruction::GlobalGet(self.wasm_depth_global)); + prop_void.instruction(&Instruction::I32Eqz); + prop_void.instruction(&Instruction::If(wasm_encoder::BlockType::Empty)); + prop_void.instruction(&f64_const(prop_id as f64)); + prop_void.instruction(&f64_const(0.0)); + prop_void.instruction(&Instruction::GlobalGet(self.nan_temp_global)); + prop_void.instruction(&Instruction::Call(rt.mem_call)); + prop_void.instruction(&Instruction::Drop); + prop_void.instruction(&Instruction::End); + prop_void.instruction(&Instruction::End); + code_section.function(&prop_void); + + let mut prop_i64 = Function::new(vec![]); + prop_i64.instruction(&Instruction::LocalGet(0)); + prop_i64.instruction(&Instruction::Call(self.exc_propagate_void_fn)); + prop_i64.instruction(&Instruction::I64Const(TAG_UNDEFINED as i64)); + prop_i64.instruction(&Instruction::End); + code_section.function(&prop_i64); + } +} + impl<'a> FuncEmitCtx<'a> { pub(super) fn rt(&self) -> &RuntimeImports { self.emitter.rt.as_ref().unwrap() @@ -28,30 +64,54 @@ impl<'a> FuncEmitCtx<'a> { .exception_handlers .last() .map(|(depth, bytes, _)| (*depth, *bytes)); - func.instruction(&Instruction::Call(self.rt().has_exception)); + func.instruction(&Instruction::GlobalGet(self.emitter.has_exc_global)); func.instruction(&Instruction::If(wasm_encoder::BlockType::Empty)); - // Abandon unfinished argument frames before transferring to the handler. let unwind_bytes = self.frame_bytes() - handler.map_or(0, |(_, bytes)| bytes); - if unwind_bytes > 0 { - let sp = self.emitter.nan_temp_global; - func.instruction(&Instruction::GlobalGet(sp)); - func.instruction(&Instruction::I32Const(unwind_bytes as i32)); - func.instruction(&Instruction::I32Sub); - func.instruction(&Instruction::GlobalSet(sp)); - } if let Some((depth, _)) = handler { + // Abandon unfinished argument frames before transferring to the handler. + if unwind_bytes > 0 { + let sp = self.emitter.nan_temp_global; + func.instruction(&Instruction::GlobalGet(sp)); + func.instruction(&Instruction::I32Const(unwind_bytes as i32)); + func.instruction(&Instruction::I32Sub); + func.instruction(&Instruction::GlobalSet(sp)); + } func.instruction(&Instruction::Br(self.block_depth - depth + 1)); } else { - self.emit_frame_begin(func, 0); - self.emit_memcall_void(func, "propagate_exception", 0); - if self.returns_value { - func.instruction(&Instruction::I64Const(TAG_UNDEFINED as i64)); - } + let helper = if self.returns_value { + self.emitter.exc_propagate_i64_fn + } else { + self.emitter.exc_propagate_void_fn + }; + func.instruction(&Instruction::I32Const(unwind_bytes as i32)); + func.instruction(&Instruction::Call(helper)); func.instruction(&Instruction::Return); } func.instruction(&Instruction::End); } + /// Emit a direct Wasm-to-Wasm call while tracking nested caller depth so an + /// inner throw unwinds outer argument frames before crossing back into JS. + pub(super) fn emit_wasm_call(&mut self, func: &mut Function, target_idx: u32) { + let is_wasm_callee = target_idx >= self.emitter.num_imports; + if is_wasm_callee { + let depth = self.emitter.wasm_depth_global; + func.instruction(&Instruction::GlobalGet(depth)); + func.instruction(&Instruction::I32Const(1)); + func.instruction(&Instruction::I32Add); + func.instruction(&Instruction::GlobalSet(depth)); + } + func.instruction(&Instruction::Call(target_idx)); + if is_wasm_callee { + let depth = self.emitter.wasm_depth_global; + func.instruction(&Instruction::GlobalGet(depth)); + func.instruction(&Instruction::I32Const(1)); + func.instruction(&Instruction::I32Sub); + func.instruction(&Instruction::GlobalSet(depth)); + } + self.emit_exception_guard(func); + } + /// The one value of the function declaration `func_idx` (`function_value`). pub(super) fn emit_function_value(&mut self, func: &mut Function, func_idx: u32) { let table_idx = self diff --git a/crates/perry-codegen-wasm/src/emit/module_emitter.rs b/crates/perry-codegen-wasm/src/emit/module_emitter.rs index 053159d5024..3a3970aa427 100644 --- a/crates/perry-codegen-wasm/src/emit/module_emitter.rs +++ b/crates/perry-codegen-wasm/src/emit/module_emitter.rs @@ -76,6 +76,14 @@ pub(super) struct WasmModuleEmitter { pub(super) enum_values: BTreeMap<(String, String), EnumResolvedValue>, /// Global index for NaN-safe temp storage (global.set/get may preserve NaN in Firefox) pub(super) nan_temp_global: u32, + /// Exported mutable i32 global (`__perry_has_exc`) mirrored by JS exception state. + pub(super) has_exc_global: u32, + /// Exported mutable i32 global (`__perry_wasm_depth`) tracking active nested Wasm callers. + pub(super) wasm_depth_global: u32, + /// Internal `(unwind_bytes: i32) -> ()` helper that unwinds `__perry_arg_sp` and propagates. + pub(super) exc_propagate_void_fn: u32, + /// Internal `(unwind_bytes: i32) -> i64` helper that unwinds, propagates, and yields undefined. + pub(super) exc_propagate_i64_fn: u32, /// Async function names (compiled to JS, not WASM) pub(super) async_func_imports: Vec<(String, u32, usize)>, // (name, import_idx, param_count) /// Generated JS code for async functions @@ -184,6 +192,10 @@ impl WasmModuleEmitter { ctor_cap_params: BTreeMap::new(), enum_values: BTreeMap::new(), nan_temp_global: 0, // set during compile() + has_exc_global: 0, + wasm_depth_global: 0, + exc_propagate_void_fn: 0, + exc_propagate_i64_fn: 0, async_func_imports: Vec::new(), module_func_maps: Vec::new(), fn_proto_kinds: BTreeMap::new(), diff --git a/crates/perry-codegen-wasm/src/emit/stmt.rs b/crates/perry-codegen-wasm/src/emit/stmt.rs index d3cf7894c58..1edf23c0305 100644 --- a/crates/perry-codegen-wasm/src/emit/stmt.rs +++ b/crates/perry-codegen-wasm/src/emit/stmt.rs @@ -101,12 +101,12 @@ impl<'a> FuncEmitCtx<'a> { fn emit_finally(&mut self, func: &mut Function, body: &[Stmt], returning: bool) { // Keep both presence and payload on the operand stack: nullish throws are valid. - func.instruction(&Instruction::Call(self.rt().has_exception)); + func.instruction(&Instruction::GlobalGet(self.emitter.has_exc_global)); self.emit_frame_begin(func, 0); self.emit_memcall(func, "get_exception", 0); self.emit_guarded_body(func, body, None, returning); func.instruction(&Instruction::LocalSet(self.temp_store_local)); - func.instruction(&Instruction::Call(self.rt().has_exception)); + func.instruction(&Instruction::GlobalGet(self.emitter.has_exc_global)); func.instruction(&Instruction::I32Eqz); func.instruction(&Instruction::I32And); func.instruction(&Instruction::If(wasm_encoder::BlockType::Empty)); @@ -471,7 +471,7 @@ impl<'a> FuncEmitCtx<'a> { }); self.emit_guarded_body(func, body, target, in_returning_func); if let Some(catch_clause) = catch { - func.instruction(&Instruction::Call(self.rt().has_exception)); + func.instruction(&Instruction::GlobalGet(self.emitter.has_exc_global)); func.instruction(&Instruction::If(wasm_encoder::BlockType::Empty)); self.block_depth += 1; self.emit_frame_begin(func, 0); diff --git a/crates/perry-codegen-wasm/src/emit/tests_more.rs b/crates/perry-codegen-wasm/src/emit/tests_more.rs index 1ccca47b2a5..4e101ae9cd0 100644 --- a/crates/perry-codegen-wasm/src/emit/tests_more.rs +++ b/crates/perry-codegen-wasm/src/emit/tests_more.rs @@ -1619,3 +1619,6 @@ mod array_iterator; #[path = "web_layout_tests.rs"] mod web_layout; + +#[path = "exception_flag_tests.rs"] +mod exception_flag; diff --git a/crates/perry-codegen-wasm/src/wasm_runtime.js b/crates/perry-codegen-wasm/src/wasm_runtime.js index c2a157e67b1..86c6a1b771f 100644 --- a/crates/perry-codegen-wasm/src/wasm_runtime.js +++ b/crates/perry-codegen-wasm/src/wasm_runtime.js @@ -163,6 +163,103 @@ function getString(val) { let wasmMemory = null; let wasmInstance = null; +// Single source of truth for exception state and mirrored Wasm globals +// (`__perry_has_exc`, `__perry_arg_sp`). Refreshes lazily when `wasmInstance` +// changes so direct `WebAssembly.instantiate` callers stay in sync with +// `bootPerryWasm`. +let tryDepth = 0; +const NO_EXCEPTION = Symbol('no exception'); +let currentException = NO_EXCEPTION; +let __cachedGlobalsInstance = null; +let __excFlagGlobal = null; +let __argSpGlobal = null; +let __wasmDepthGlobal = null; + +function __refreshWasmGlobals() { + if (__cachedGlobalsInstance !== wasmInstance) { + __cachedGlobalsInstance = wasmInstance; + const exports = wasmInstance && wasmInstance.exports; + __excFlagGlobal = exports && exports.__perry_has_exc ? exports.__perry_has_exc : null; + __argSpGlobal = exports && exports.__perry_arg_sp ? exports.__perry_arg_sp : null; + __wasmDepthGlobal = exports && exports.__perry_wasm_depth ? exports.__perry_wasm_depth : null; + } +} + +function __syncExcFlag() { + __refreshWasmGlobals(); + if (__excFlagGlobal) { + __excFlagGlobal.value = currentException !== NO_EXCEPTION ? 1 : 0; + } +} + +function __hasException() { + return currentException !== NO_EXCEPTION ? 1 : 0; +} + +function __setException(error) { + currentException = error; + __syncExcFlag(); +} + +function __clearException() { + currentException = NO_EXCEPTION; + __syncExcFlag(); +} + +function __takeException(fallback = undefined) { + const err = currentException; + currentException = NO_EXCEPTION; + __syncExcFlag(); + return err !== NO_EXCEPTION ? err : fallback; +} + +function __captureException(error) { + if (tryDepth === 0) throw error; + __setException(error); +} + +function __getArgSp() { + __refreshWasmGlobals(); + return __argSpGlobal ? __argSpGlobal.value : 0x10000; +} + +function __setArgSp(sp) { + __refreshWasmGlobals(); + if (__argSpGlobal) __argSpGlobal.value = sp; +} + +function __withZeroWasmDepth(invoke) { + __refreshWasmGlobals(); + const depthGlobal = __wasmDepthGlobal; + const savedDepth = depthGlobal ? depthGlobal.value : 0; + if (depthGlobal) depthGlobal.value = 0; + try { + return invoke(); + } finally { + if (depthGlobal) depthGlobal.value = savedDepth; + } +} + +function __runWasmBoundary(invoke) { + return __withZeroWasmDepth(() => { + const savedSp = __getArgSp(); + const savedExc = currentException; + if (savedExc !== NO_EXCEPTION) __clearException(); + try { + const result = invoke(); + __memDispatch.propagate_exception(true); + if (savedExc !== NO_EXCEPTION) __setException(savedExc); + return result; + } catch (error) { + __setArgSp(savedSp); + if (savedExc !== NO_EXCEPTION && currentException === NO_EXCEPTION && tryDepth > 0) { + __setException(savedExc); + } + throw error; + } + }); +} + // Expose NaN-box conversion for FFI bridge (bloom_glue.js etc.) // These allow external code to convert between Perry's NaN-boxed i64 values and JS values. globalThis.__perryToJsValue = function(nanboxedF64) { return toJsValue(nanboxedF64); }; @@ -841,7 +938,7 @@ function buildImports() { const s = getString(str); return fromJsValue(JSON.parse(s)); } catch (e) { - if (tryDepth > 0) { currentException = fromJsValue(e); } + if (tryDepth > 0) { __setException(fromJsValue(e)); } return u64ToF64(TAG_UNDEFINED); } }, @@ -970,7 +1067,7 @@ function buildImports() { const f = getString(flags); return nanboxPointer(allocHandle(new RegExp(p, f))); } catch (e) { - if (tryDepth > 0) { currentException = fromJsValue(e); } + if (tryDepth > 0) { __setException(fromJsValue(e)); } return u64ToF64(TAG_UNDEFINED); } }, @@ -1008,13 +1105,9 @@ function buildImports() { try_start: () => { tryDepth++; }, try_end: () => { if (tryDepth > 0) tryDepth--; }, - throw_value: (val) => { currentException = val; }, - has_exception: () => currentException !== NO_EXCEPTION ? 1 : 0, - get_exception: () => { - const e = currentException; - currentException = NO_EXCEPTION; - return e !== NO_EXCEPTION ? e : u64ToF64(TAG_UNDEFINED); - }, + throw_value: (val) => { __setException(val); }, + has_exception: () => __hasException(), + get_exception: () => __takeException(u64ToF64(TAG_UNDEFINED)), // ===== Phase 4: URL ===== @@ -1022,7 +1115,7 @@ function buildImports() { try { return nanboxPointer(allocHandle(new URL(getString(urlStr)))); } catch (e) { - if (tryDepth > 0) { currentException = fromJsValue(e); } + if (tryDepth > 0) { __setException(fromJsValue(e)); } return u64ToF64(TAG_UNDEFINED); } }, @@ -1424,21 +1517,23 @@ function buildImports() { for (let i = 0; i < argc; i++) args.push(__bitsToJsValue(u64View[i])); let result; const coreFn = __memDispatch[name]; - try { - if (coreFn) { - result = coreFn(...args); - } else { - const uiFn = __perryUiDispatch[name]; - if (uiFn) { - result = uiFn(...args); - } else if (argc > 0) { - result = __classDispatch(args[0], name, args.slice(1)); + __withZeroWasmDepth(() => { + try { + if (coreFn) { + result = coreFn(...args); + } else { + const uiFn = __perryUiDispatch[name]; + if (uiFn) { + result = uiFn(...args); + } else if (argc > 0) { + result = __classDispatch(args[0], name, args.slice(1)); + } } + } catch (error) { + if (stringTable[nameId | 0] === 'propagate_exception' || base < 0x10000) throw error; + __setException(error); } - } catch (error) { - if (tryDepth === 0) throw error; - currentException = error; - } + }); // Write result back to same base address const outU64 = new BigUint64Array(wasmMemory.buffer, base, 1); outU64[0] = __jsValueToBits(result); @@ -1453,13 +1548,15 @@ function buildImports() { for (let i = 0; i < argc; i++) args.push(__bitsToJsValue(u64View[i])); const fn = __memDispatch[name]; if (!fn) return 0; - try { - return fn(...args) | 0; - } catch (error) { - if (tryDepth === 0) throw error; - currentException = error; - return 0; - } + return __withZeroWasmDepth(() => { + try { + return fn(...args) | 0; + } catch (error) { + if (stringTable[nameId | 0] === 'propagate_exception' || base < 0x10000) throw error; + __setException(error); + return 0; + } + }); }, // Async function implementations (merged from generated code) @@ -1588,10 +1685,14 @@ function wrapForI64(fn, coerceNumberToBigInt = true) { // the f64 round-trip entirely and also gives wasm-bindgen a plain Number for // INT32-tagged values (avoiding `Cannot convert BigInt value to a number`). function wrapFfiForI64(fn) { - if (fn.__rawBigint === true) return fn; + if (fn.__rawBigint === true) { + return function(...args) { + return __withZeroWasmDepth(() => __reflectApply(fn, this, args)); + }; + } return function(...args) { const convertedArgs = args.map(a => (typeof a === 'bigint') ? __bitsToJsValue(a) : a); - const result = __reflectApply(fn, this, convertedArgs); + const result = __withZeroWasmDepth(() => __reflectApply(fn, this, convertedArgs)); if (typeof result === 'bigint') return result; if (typeof result === 'number') { // #1049 instance 1: the WASM import side declares these as `i64` @@ -1634,7 +1735,13 @@ function wrapRtNamespace(ns) { const v = target[prop]; if (typeof v === 'function') { const coerce = !__NON_I64_RETURN_IMPORTS.has(prop); - return wrapForI64(v, coerce); + const wrapped = wrapForI64(v, coerce); + if (typeof prop === 'string' && prop.startsWith('__async_')) { + return function(...args) { + return __withZeroWasmDepth(() => __reflectApply(wrapped, this, args)); + }; + } + return wrapped; } return v; }, @@ -1833,8 +1940,7 @@ function __hostAdder(obj, name) { const fn = obj[name]; if (__isPerryClosure(fn)) { return (...args) => { - __callClosureMethod(fn, obj, args); - __memDispatch.propagate_exception(true); + __runWasmBoundary(() => __callClosureMethod(fn, obj, args)); }; } if (typeof fn !== 'function') throw new TypeError(`'${String(fn)}' returned for property '${name}' of object '#<${obj.constructor.name}>' is not a function`); @@ -2729,9 +2835,7 @@ const __memDispatch = { throw new TypeError(`${what} is not a function`); } return Array.from(val, (v, i) => { - const mapped = __memDispatch.reflect_apply(fn, thisArg, [v, i]); - __memDispatch.propagate_exception(true); - return mapped; + return __runWasmBoundary(() => __memDispatch.reflect_apply(fn, thisArg, [v, i])); }); }, // `[...source]`: any iterable source (a Set, a Map, an iterator) spreads its values. @@ -3285,7 +3389,7 @@ const __memDispatch = { }, // JSON — args are plain JS values - json_parse: (str) => { try { return JSON.parse(String(str)); } catch (e) { if (tryDepth > 0) currentException = e; return undefined; } }, + json_parse: (str) => { try { return JSON.parse(String(str)); } catch (e) { if (tryDepth > 0) __setException(e); return undefined; } }, // A closure value is omitted as a function is, through a `toJSON` its prototype has // only meanwhile; a replacer function gets the closure itself. json_stringify: (val, replacer, space) => { @@ -3478,7 +3582,7 @@ const __memDispatch = { global_property: (name) => __hostGlobal[name], // RegExp — args are plain JS values - regexp_new: (pattern, flags) => { try { return new RegExp(String(pattern), String(flags)); } catch (e) { if (tryDepth > 0) currentException = e; return undefined; } }, + regexp_new: (pattern, flags) => { try { return new RegExp(String(pattern), String(flags)); } catch (e) { if (tryDepth > 0) __setException(e); return undefined; } }, regexp_test: (re, str) => { if (!(re instanceof RegExp)) return 0; return re.test(String(str)) ? 1 : 0; }, // Globals — args are plain JS values @@ -3498,19 +3602,17 @@ const __memDispatch = { // Try/Catch — args are plain JS values try_start: () => { tryDepth++; }, try_end: () => { if (tryDepth > 0) tryDepth--; }, - throw_value: (val) => { currentException = val; }, + throw_value: (val) => { __setException(val); }, propagate_exception: (callbackBoundary = false) => { - if ((callbackBoundary || tryDepth === 0) && currentException !== NO_EXCEPTION) { - const error = currentException; - currentException = NO_EXCEPTION; - throw error; + if (__hasException()) { + throw __takeException(); } }, - has_exception: () => currentException !== NO_EXCEPTION ? 1 : 0, - get_exception: () => { const e = currentException; currentException = NO_EXCEPTION; return e !== NO_EXCEPTION ? e : undefined; }, + has_exception: () => __hasException(), + get_exception: () => __takeException(), // URL — args are plain JS values (u is the URL object itself) - url_parse: (urlStr) => { try { return new URL(String(urlStr)); } catch (e) { if (tryDepth > 0) currentException = e; return undefined; } }, + url_parse: (urlStr) => { try { return new URL(String(urlStr)); } catch (e) { if (tryDepth > 0) __setException(e); return undefined; } }, url_get_href: (u) => (u instanceof URL) ? u.href : undefined, url_get_pathname: (u) => (u instanceof URL) ? u.pathname : undefined, url_get_hostname: (u) => (u instanceof URL) ? u.hostname : undefined, @@ -3592,12 +3694,12 @@ const __memDispatch = { set_timeout: (closure, delay) => { if (typeof closure === 'function') return setTimeout(closure, delay); if (!closure || typeof closure.funcIdx === 'undefined' || !wasmInstance) return 0; - return setTimeout(() => { const fn = wasmInstance.exports.__indirect_function_table?.get(closure.funcIdx | 0); if (fn) fn(...__padBigintArgs(fn, 0, [...closure.captures])); }, delay); + return setTimeout(() => { const fn = wasmInstance.exports.__indirect_function_table?.get(closure.funcIdx | 0); if (fn) __invokeWasmCallback(fn, ...closure.captures); }, delay); }, set_interval: (closure, delay) => { if (typeof closure === 'function') return setInterval(closure, delay); if (!closure || typeof closure.funcIdx === 'undefined' || !wasmInstance) return 0; - return setInterval(() => { const fn = wasmInstance.exports.__indirect_function_table?.get(closure.funcIdx | 0); if (fn) fn(...__padBigintArgs(fn, 0, [...closure.captures])); }, delay); + return setInterval(() => { const fn = wasmInstance.exports.__indirect_function_table?.get(closure.funcIdx | 0); if (fn) __invokeWasmCallback(fn, ...closure.captures); }, delay); }, clear_timeout: (id) => { clearTimeout(id); }, clear_interval: (id) => { clearInterval(id); }, @@ -3652,7 +3754,7 @@ const __memDispatch = { const newP = p.then(val => { if (closure && typeof closure.funcIdx !== 'undefined' && wasmInstance) { const fn = wasmInstance.exports.__indirect_function_table?.get(closure.funcIdx | 0); - if (fn) return __bitsToJsValue(fn(...__padBigintArgs(fn, 0, [...closure.captures, __jsValueToBits(val)]))); + if (fn) return __bitsToJsValue(__invokeWasmCallback(fn, ...closure.captures, __jsValueToBits(val))); } return val; }); @@ -4007,11 +4109,6 @@ self.onmessage = async function(e) { }; })(); -// Exception state for try/catch bridge -let tryDepth = 0; -const NO_EXCEPTION = Symbol('no exception'); -let currentException = NO_EXCEPTION; - // ===== Perry UI Runtime (DOM-based, for --target wasm) ===== // Ported from perry-codegen-js/web_runtime.js — maps perry/ui widgets to DOM elements. @@ -4034,9 +4131,7 @@ function __invokeWasmCallback(fn, ...bigintArgs) { // `__invokeWasmCallback` of a constructor whose last `caps` arguments are its class's // captures. function __invokeConstructor(fn, caps, ...bigintArgs) { - const result = fn(...__padBigintArgs(fn, 0, bigintArgs, caps)); - __memDispatch.propagate_exception(true); - return result; + return __runWasmBoundary(() => fn(...__padBigintArgs(fn, 0, bigintArgs, caps))); } // Accept a boxed handle or decoded closure; extra arguments are plain JS values. @@ -4060,7 +4155,7 @@ function callWasmClosure(closureVal, ...extraArgs) { const wasmArgs = extraArgs.map(v => __jsValueToBits(v)); if (fn) { const captures = closure.captures || []; - const result = fn(...captures, ...__padBigintArgs(fn, captures.length, wasmArgs)); + const result = __invokeWasmCallback(fn, ...captures, ...wasmArgs); return (typeof result === 'bigint') ? __bitsToJsValue(result) : undefined; } } @@ -6685,8 +6780,7 @@ function __callHostFunction(fn, args, receiver = undefined) { try { return __reflectApply(fn, receiver, __classMethodFns.has(fn) ? args : __hostArgs(fn, args, receiver)); } catch (error) { - if (tryDepth === 0) throw error; - currentException = error; + __captureException(error); return undefined; } } @@ -6702,8 +6796,7 @@ function __constructHostFunction(fn, args) { } return Reflect.construct(fn, __perryClassCtors.has(fn) ? args : args.map(__hostCallback)); } catch (error) { - if (tryDepth === 0) throw error; - currentException = error; + __captureException(error); return undefined; } } @@ -6743,9 +6836,7 @@ function __hostAccessor(v) { let fn = hostAccessors.get(v); if (!fn) { fn = function (...args) { - const result = __callClosureMethod(v, this, args); - __memDispatch.propagate_exception(true); - return result; + return __runWasmBoundary(() => __callClosureMethod(v, this, args)); }; hostAccessors.set(v, fn); hostAccessorClosures.set(fn, v); @@ -6806,9 +6897,7 @@ function __hostCallback(value) { // Strict, so a host call without a receiver has an undefined `this`. hostCallbacks.set(value, __withKindProto(function () { 'use strict'; - const result = __callClosureMethod(value, this, [...arguments]); - __memDispatch.propagate_exception(true); - return result; + return __runWasmBoundary(() => __callClosureMethod(value, this, [...arguments])); }, __PerryClosure.protoKindOf(value))); } return hostCallbacks.get(value); @@ -7013,14 +7102,10 @@ function __jsMethodInvoke(ref, args) { if (ref.user) { // As __invokeWasmCallback: a compiled method that threw under an enclosing WASM // `try` leaves the exception pending; rethrow it here so the async body rejects. - const result = __classDispatch(ref.r, ref.m, args); - __memDispatch.propagate_exception(true); - return result; + return __runWasmBoundary(() => __classDispatch(ref.r, ref.m, args)); } if (__isPerryClosure(ref.f)) { - const result = __callClosureMethod(ref.f, ref.r, args); - __memDispatch.propagate_exception(true); - return result; + return __runWasmBoundary(() => __callClosureMethod(ref.f, ref.r, args)); } if (typeof ref.f !== 'function') throw new TypeError(String(ref.m) + ' is not a function'); // A compiled class method takes Perry values, as `reflect_apply` passes them. @@ -7078,8 +7163,7 @@ function __classDispatch(objVal, mname, rawArgs) { if (typeof method === 'function') return __callHostFunction(method, rawArgs, objVal); if (__isPerryClosure(method)) return __callClosureMethod(method, objVal, rawArgs); } catch (error) { - if (tryDepth === 0) throw error; - currentException = error; + __captureException(error); return undefined; } } @@ -7151,10 +7235,19 @@ async function bootPerryWasm(wasmBase64, ffiImports) { const { instance } = await WebAssembly.instantiate(wasmBytes, imports); wasmInstance = instance; wasmMemory = instance.exports.memory; - // Call the entry point - if (instance.exports._start) { - instance.exports._start(); - } else if (instance.exports.main) { - instance.exports.main(); - } + __syncExcFlag(); + __withZeroWasmDepth(() => { + const savedSp = __getArgSp(); + try { + // Call the entry point + if (instance.exports._start) { + instance.exports._start(); + } else if (instance.exports.main) { + instance.exports.main(); + } + } catch (error) { + __setArgSp(savedSp); + throw error; + } + }); }