From 0e1c80f65c5e2a19bcb67ddfc0c7330f39678104 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Wed, 25 Nov 2026 16:35:52 +0000 Subject: [PATCH 1/3] Restore catchable preinit filesystem errors --- README.md | 29 +- .../wasm-rquickjs/skeleton/src/builtin/fs.rs | 145 +++++++--- .../skeleton/src/internal/module_loading.rs | 26 +- .../skeleton/src/internal/preinit.rs | 14 + .../skeleton/module_loader_architecture.rs | 2 +- tests/optimize/preinit.rs | 264 +++++++++++++----- 6 files changed, 356 insertions(+), 124 deletions(-) diff --git a/README.md b/README.md index 26218df95..a69abdfa3 100644 --- a/README.md +++ b/README.md @@ -264,17 +264,23 @@ not a hard disk quota. Only native compilation is shared; each operation creates a fresh engine, store, instance and WASI context. Use `init_func = "wizer-initialize"` with source input; custom initializers remain available without source input. -**External I/O during pre-initialization is rejected.** Top-level filesystem -probes (including `existsSync` and module/package lookup), socket/DNS/HTTP/WebSocket -acquisition, SQLite opens (including `:memory:`), execution-job creation, and -`process.chdir()` fail the -build immediately. Catching a JavaScript exception cannot suppress this failure. +**The filesystem is unavailable during pre-initialization.** Path-based file +operations report catchable `ENOENT` errors; existence probes return `false`, and +filesystem-backed module/package lookup follows its normal not-found behavior. +These results are synthesized before touching the build host, WASI preopens, +libc filesystem state or runtime loader caches. Optional imports and file probes +may catch this absence; an uncaught exception still fails the build. Values +computed from caught absence remain frozen in the snapshot, so perform any +filesystem-dependent work again after restoration when needed. + +Socket/DNS/HTTP/WebSocket acquisition, SQLite opens (including `:memory:`), +execution-job creation, and `process.chdir()` still fail the build immediately. +Catching a JavaScript exception cannot suppress these policy failures. The diagnostic identifies the operation and recommends moving it into an exported -function or lazy initialization after restoration. This avoids saving unavailable -build-time capabilities or false filesystem results in the snapshot. The optimizer +function or lazy initialization after restoration. The optimizer also traps filesystem preopens, network acquisition and outgoing HTTP for older -templates and custom initializers. Rebuild templates to get native guards, -restore-safe pre-init stdio and guest diagnostics. +templates and custom initializers. Rebuild templates to get catchable filesystem +absence, native guards, restore-safe pre-init stdio and guest diagnostics. Importing these builtins, embedded/data modules and explicitly supplied module sources remains supported. Logging and pure computation remain available. @@ -288,9 +294,8 @@ must implement this standard WASI import; `none` retains `/`. A supplied cwd mus be an accessible directory, or runtime initialization fails. Owned jobs retain their separate cwd. -Supplied CommonJS reexports that require filesystem analysis are still rejected -during pre-initialization, even if a loader could supply the child at runtime. -Defer those chains to runtime until loader-aware reexport analysis is supported. +CommonJS named-reexport analysis that depends on filesystem-only children remains +unavailable during pre-initialization. Defer those imports to runtime. Defer SQLite connections with `new DatabaseSync(path, { open: false })`, then call `.open()` after restoration. Applications that require top-level external I/O should skip `optimize` and initialize at runtime instead. diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/fs.rs b/crates/wasm-rquickjs/skeleton/src/builtin/fs.rs index 4c66e319d..886e33250 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/fs.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/fs.rs @@ -414,7 +414,7 @@ pub(super) fn realpath_for_module_resolution( ) -> std::io::Result { // Wizer has no guest preopens. Touching wasi-libc's lazy preopen cache here // would snapshot the empty build-time filesystem into every runtime. - crate::internal::preinit::check("fs.realpath", path); + crate::internal::preinit::filesystem()?; let services = ctx .userdata::() @@ -657,6 +657,17 @@ fn make_fs_error<'js>( make_fs_error_with_dest(ctx, err, syscall, path, None) } +fn preinit_error<'js>( + ctx: &rquickjs::Ctx<'js>, + syscall: &str, + path: &str, + dest: Option<&str>, +) -> Option> { + crate::internal::preinit::filesystem() + .err() + .map(|error| make_fs_error_with_dest(ctx, &error, syscall, Some(path), dest)) +} + fn make_fs_error_with_dest<'js>( ctx: &rquickjs::Ctx<'js>, err: &std::io::Error, @@ -916,7 +927,9 @@ pub mod native_module { path: String, encoding: String, ) -> List<(Option, Option)> { - crate::internal::preinit::check("fs.readFile", &path); + if let Err(error) = crate::internal::preinit::filesystem() { + return List((None, Some(format!("Failed to read file {path:?}: {error}")))); + } let resolved_path = runtime_path(&ctx, &path); let List((value, error)) = super::read_file_with_encoding_impl(&resolved_path, &encoding); List(( @@ -930,7 +943,9 @@ pub mod native_module { path: String, ctx: Ctx<'_>, ) -> List<(Option>, Option)> { - crate::internal::preinit::check("fs.readFile", &path); + if let Err(error) = crate::internal::preinit::filesystem() { + return List((None, Some(format!("Failed to read file {path:?}: {error}")))); + } let resolved_path = runtime_path(&ctx, &path); match std::fs::read(&resolved_path) { Ok(bytes) => { @@ -955,7 +970,10 @@ pub mod native_module { use std::io::Read; let result = Object::new(ctx.clone()).unwrap(); - crate::internal::preinit::check("fs.read_file", &path); + if let Some(error) = super::preinit_error(&ctx, "open", &path, None) { + result.set("error", error).unwrap(); + return result; + } let resolved_path = runtime_path(&ctx, &path); let mut file = match std::fs::File::open(&resolved_path) { @@ -1025,7 +1043,9 @@ pub mod native_module { encoding: String, content: String, ) -> Option { - crate::internal::preinit::check("fs.writeFile", &path); + if let Err(error) = crate::internal::preinit::filesystem() { + return Some(format!("Failed to write file {path:?}: {error}")); + } if encoding != "utf8" { Some("Only 'utf8' encoding is supported".to_string()) } else { @@ -1049,7 +1069,9 @@ pub mod native_module { #[rquickjs::function] pub fn write_file(ctx: Ctx<'_>, path: String, content: TypedArray<'_, u8>) -> Option { - crate::internal::preinit::check("fs.writeFile", &path); + if let Err(error) = crate::internal::preinit::filesystem() { + return Some(format!("Failed to write file {path:?}: {error}")); + } // SAFETY: No JS executes while the rooted input is read by synchronous file I/O. if let Some(bytes) = unsafe { content.as_bytes() } { let resolved_path = runtime_path(&ctx, &path); @@ -1073,7 +1095,9 @@ pub mod native_module { #[rquickjs::function] pub fn unlink(ctx: Ctx<'_>, path: String) -> Option> { - crate::internal::preinit::check("fs.unlink", &path); + if let Some(error) = super::preinit_error(&ctx, "unlink", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); match std::fs::remove_file(Path::new(&fs_path)) { Ok(_) => { @@ -1087,7 +1111,9 @@ pub mod native_module { #[rquickjs::function] pub fn rename(ctx: Ctx<'_>, old_path: String, new_path: String) -> Option> { - crate::internal::preinit::check("fs.rename", format_args!("{old_path} -> {new_path}")); + if let Some(error) = super::preinit_error(&ctx, "rename", &old_path, Some(&new_path)) { + return Some(error); + } let old_fs_path = runtime_path(&ctx, &old_path); let new_fs_path = runtime_path(&ctx, &new_path); match std::fs::rename(Path::new(&old_fs_path), Path::new(&new_fs_path)) { @@ -1109,7 +1135,9 @@ pub mod native_module { #[rquickjs::function] pub fn mkdir(ctx: Ctx<'_>, path: String, recursive: bool) -> Option { - crate::internal::preinit::check("fs.mkdir", &path); + if let Err(error) = crate::internal::preinit::filesystem() { + return Some(format!("Failed to create directory {path:?}: {error}")); + } let resolved_path = runtime_path(&ctx, &path); let fs_path = Path::new(&resolved_path); let result = if recursive { @@ -1135,7 +1163,10 @@ pub mod native_module { let result = Object::new(ctx.clone()).unwrap(); - crate::internal::preinit::check("fs.open", &path); + if let Some(error) = super::preinit_error(&ctx, "open", &path, None) { + result.set("error", error).unwrap(); + return result; + } let fs_path = runtime_path(&ctx, &path); @@ -1464,7 +1495,10 @@ pub mod native_module { return result; } - crate::internal::preinit::check("fs.stat", &path); + if let Some(error) = super::preinit_error(&ctx, "stat", &path, None) { + result.set("error", error).unwrap(); + return result; + } let fs_path = runtime_path(&ctx, &path); @@ -1502,7 +1536,10 @@ pub mod native_module { return result; } - crate::internal::preinit::check("fs.lstat", &path); + if let Some(error) = super::preinit_error(&ctx, "lstat", &path, None) { + result.set("error", error).unwrap(); + return result; + } let absolute_path = runtime_path(&ctx, &path); @@ -1592,7 +1629,10 @@ pub mod native_module { return result; } - crate::internal::preinit::check("fs.readdir", &path); + if let Some(error) = super::preinit_error(&ctx, "scandir", &path, None) { + result.set("error", error).unwrap(); + return result; + } let fs_path = runtime_path(&ctx, &path); @@ -1648,7 +1688,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_access(ctx: Ctx<'_>, path: String, _mode: i32) -> Option> { - crate::internal::preinit::check("fs.access", &path); + if let Some(error) = super::preinit_error(&ctx, "access", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); @@ -1715,7 +1757,10 @@ pub mod native_module { return result; } - crate::internal::preinit::check("fs.realpath", &path); + if let Some(error) = super::preinit_error(&ctx, "realpath", &path, None) { + result.set("error", error).unwrap(); + return result; + } let absolute_path = runtime_path(&ctx, &path); match super::canonicalize_guest_path(&absolute_path) { @@ -1740,7 +1785,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_truncate(ctx: Ctx<'_>, path: String, len: f64) -> Option> { - crate::internal::preinit::check("fs.truncate", &path); + if let Some(error) = super::preinit_error(&ctx, "truncate", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); match std::fs::OpenOptions::new().write(true).open(&fs_path) { Ok(file) => { @@ -1756,7 +1803,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_copy_file(ctx: Ctx<'_>, src: String, dest: String) -> Option> { - crate::internal::preinit::check("fs.copy_file", format_args!("{src} -> {dest}")); + if let Some(error) = super::preinit_error(&ctx, "copyfile", &src, Some(&dest)) { + return Some(error); + } let fs_src = runtime_path(&ctx, &src); let fs_dest = runtime_path(&ctx, &dest); match std::fs::copy(&fs_src, &fs_dest) { @@ -1776,7 +1825,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_link(ctx: Ctx<'_>, existing_path: String, new_path: String) -> Option> { - crate::internal::preinit::check("fs.link", format_args!("{existing_path} -> {new_path}")); + if let Some(error) = super::preinit_error(&ctx, "link", &existing_path, Some(&new_path)) { + return Some(error); + } let fs_existing_path = runtime_path(&ctx, &existing_path); let fs_new_path = runtime_path(&ctx, &new_path); match std::fs::hard_link(&fs_existing_path, &fs_new_path) { @@ -1796,7 +1847,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_symlink(ctx: Ctx<'_>, target: String, path: String) -> Option> { - crate::internal::preinit::check("fs.symlink", &path); + if let Some(error) = super::preinit_error(&ctx, "symlink", &target, Some(&path)) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); match super::symlink_at_path(&target, &fs_path) { @@ -1819,7 +1872,10 @@ pub mod native_module { let result = Object::new(ctx.clone()).unwrap(); let fs_path = runtime_path(&ctx, &path); - crate::internal::preinit::check("fs.readlink", &path); + if let Some(error) = super::preinit_error(&ctx, "readlink", &path, None) { + result.set("error", error).unwrap(); + return result; + } match std::fs::read_link(&fs_path) { Ok(target) => { @@ -1841,7 +1897,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_chmod(ctx: Ctx<'_>, path: String, mode: u32) -> Option> { - crate::internal::preinit::check("fs.chmod", &path); + if let Some(error) = super::preinit_error(&ctx, "chmod", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); // chmod is not supported on WASI; verify path exists match std::fs::metadata(&fs_path) { @@ -1879,7 +1937,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_chown(ctx: Ctx<'_>, path: String, _uid: u32, _gid: u32) -> Option> { - crate::internal::preinit::check("fs.chown", &path); + if let Some(error) = super::preinit_error(&ctx, "chown", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); // chown is not supported on WASI; just verify path exists match std::fs::metadata(&fs_path) { @@ -1903,7 +1963,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_lchown(ctx: Ctx<'_>, path: String, _uid: u32, _gid: u32) -> Option> { - crate::internal::preinit::check("fs.lchown", &path); + if let Some(error) = super::preinit_error(&ctx, "lchown", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); match std::fs::symlink_metadata(&fs_path) { Ok(_) => None, @@ -1918,7 +1980,9 @@ pub mod native_module { atime_secs: f64, mtime_secs: f64, ) -> Option> { - crate::internal::preinit::check("fs.utimes", &path); + if let Some(error) = super::preinit_error(&ctx, "utime", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); match super::set_path_times(&fs_path, atime_secs, mtime_secs, true) { Ok(_) => None, @@ -1933,7 +1997,9 @@ pub mod native_module { atime_secs: f64, mtime_secs: f64, ) -> Option> { - crate::internal::preinit::check("fs.lutimes", &path); + if let Some(error) = super::preinit_error(&ctx, "lutime", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); match super::set_path_times(&fs_path, atime_secs, mtime_secs, false) { Ok(_) => None, @@ -1964,7 +2030,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_mkdir(ctx: Ctx<'_>, path: String, recursive: bool, mode: u32) -> Option> { - crate::internal::preinit::check("fs.mkdir", &path); + if let Some(error) = super::preinit_error(&ctx, "mkdir", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); let p = Path::new(&fs_path); let mode = mode & 0o7777; @@ -1991,7 +2059,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_rmdir(ctx: Ctx<'_>, path: String) -> Option> { - crate::internal::preinit::check("fs.rmdir", &path); + if let Some(error) = super::preinit_error(&ctx, "rmdir", &path, None) { + return Some(error); + } let fs_path = runtime_path(&ctx, &path); match std::fs::remove_dir(&fs_path) { Ok(_) => { @@ -2005,7 +2075,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_rm(ctx: Ctx<'_>, path: String, recursive: bool, force: bool) -> Option> { - crate::internal::preinit::check("fs.rm", &path); + if let Some(error) = super::preinit_error(&ctx, "lstat", &path, None) { + return if force { None } else { Some(error) }; + } let fs_path = runtime_path(&ctx, &path); let meta = std::fs::symlink_metadata(&fs_path); match meta { @@ -2055,10 +2127,13 @@ pub mod native_module { #[rquickjs::function] pub fn fs_mkdtemp(ctx: Ctx<'_>, prefix: String) -> Object<'_> { - crate::internal::preinit::check("fs.mkdtemp", &prefix); use rand::Rng; let result = Object::new(ctx.clone()).unwrap(); + if let Some(error) = super::preinit_error(&ctx, "mkdtemp", &prefix, None) { + result.set("error", error).unwrap(); + return result; + } let mut rng = rand::rng(); let chars: Vec = (0..6) .map(|_| { @@ -2097,7 +2172,9 @@ pub mod native_module { path: String, data: TypedArray<'js, u8>, ) -> Option> { - crate::internal::preinit::check("fs.append_file", &path); + if let Some(error) = super::preinit_error(&ctx, "open", &path, None) { + return Some(error); + } // SAFETY: The bytes are consumed by synchronous file I/O without JS re-entry. let Some(bytes) = (unsafe { data.as_bytes() }) else { return Some(super::make_fs_error( @@ -2129,7 +2206,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_append_file_string(ctx: Ctx<'_>, path: String, data: String) -> Option> { - crate::internal::preinit::check("fs.append_file_string", &path); + if let Some(error) = super::preinit_error(&ctx, "open", &path, None) { + return Some(error); + } let file = std::fs::OpenOptions::new() .append(true) .create(true) @@ -2151,7 +2230,9 @@ pub mod native_module { #[rquickjs::function] pub fn fs_exists(ctx: Ctx<'_>, path: String) -> bool { - crate::internal::preinit::check("fs.exists", &path); + if crate::internal::preinit::filesystem().is_err() { + return false; + } let fs_path = runtime_path(&ctx, &path); std::path::Path::new(&fs_path).exists() diff --git a/crates/wasm-rquickjs/skeleton/src/internal/module_loading.rs b/crates/wasm-rquickjs/skeleton/src/internal/module_loading.rs index fcec929b1..47b4446f9 100644 --- a/crates/wasm-rquickjs/skeleton/src/internal/module_loading.rs +++ b/crates/wasm-rquickjs/skeleton/src/internal/module_loading.rs @@ -2343,7 +2343,7 @@ fn cjs_named_import_error_message( return None; } let source_path = canonical_cjs_analysis_path(ctx, &resolved); - let source = std::fs::read_to_string(&source_path).ok()?; + let source = required_module_source(std::path::Path::new(&source_path)).ok()?; let analysis = analyze_cjs_exports_for_file(ctx, &resolved, &source, &mut HashSet::new(), cjs_conditions); if !analysis.is_cjs && analysis.exports.is_empty() && analysis.reexports.is_empty() { @@ -4517,8 +4517,7 @@ impl NodeFileResolver { Self::module_resolution_is_file(ctx, normalized) } FileCandidateSemantics::DirectFilesystem => { - super::preinit::check("module path probe", normalized); - std::path::Path::new(normalized).is_file() + super::preinit::filesystem().is_ok() && std::path::Path::new(normalized).is_file() } } } @@ -4855,7 +4854,9 @@ impl Resolver for RuntimeFileResolver { if unsupported_esm_url_scheme(&input).is_some() { return NodeModuleErrorResolver.resolve(ctx, base, name, attributes); } - super::preinit::check("module filesystem resolution", name); + if super::preinit::filesystem().is_err() { + return Err(Error::new_resolving(base, name)); + } self.0.resolve(ctx, base, name, attributes) } } @@ -5116,7 +5117,12 @@ impl CjsModuleProbeSession { } fn probe(&self, normalized: &str) -> ModulePathProbe { - super::preinit::check("module path probe", normalized); + if super::preinit::filesystem().is_err() { + return ModulePathProbe { + classification: None, + _session_hit: false, + }; + } let cached = { let state = self.0.borrow(); (state.depth > 0 && state.cache_enabled()) @@ -5268,7 +5274,9 @@ fn module_resolution_path_matches( } fn cjs_module_path_stat(ctx: Ctx<'_>, filename: String) -> i32 { - super::preinit::check("module path stat", &filename); + if super::preinit::filesystem().is_err() { + return -2; + } let services = ctx .userdata::() .expect("runtime services not initialized"); @@ -5782,7 +5790,9 @@ impl NodeModulesResolver { pkg_path: &std::path::Path, resolution: &NodePackageResolutionContext<'_, '_>, ) -> Result>, NodePackageResolveError> { - super::preinit::check("package.json read", pkg_path.display()); + if super::preinit::filesystem().is_err() { + return Ok(None); + } let cache_key = CjsEvalResolver::normalize_path(pkg_path); #[cfg(feature = "typescript-compiler-profiling")] if let Some(profile) = &resolution.profile { @@ -11378,7 +11388,7 @@ fn module_source_filesystem_literal_path(ctx: &Ctx<'_>, fs_path: &str) -> String } fn required_module_source(path: &std::path::Path) -> std::io::Result { - super::preinit::check("module source read", path.display()); + super::preinit::filesystem()?; std::fs::read_to_string(path) } diff --git a/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs b/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs index 0e5f07f0a..a5fa356c1 100644 --- a/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs +++ b/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs @@ -29,6 +29,20 @@ pub(crate) fn is_active() -> bool { ACTIVE.load(Ordering::Relaxed) } +/// Filesystem absence is catchable, but must be synthesized before libc/preopen +/// discovery or loader caches can observe the optimizer's empty filesystem. +#[inline] +pub(crate) fn filesystem() -> std::io::Result<()> { + if is_active() { + Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + "ENOENT during Wizer pre-initialization", + )) + } else { + Ok(()) + } +} + /// Check before touching libc caches, host resources or runtime filesystem /// caches. `target` must contain only native strings/numbers, never JS values. #[inline] diff --git a/crates/wasm-rquickjs/src/skeleton/module_loader_architecture.rs b/crates/wasm-rquickjs/src/skeleton/module_loader_architecture.rs index ee6efe2ed..26a1a1696 100644 --- a/crates/wasm-rquickjs/src/skeleton/module_loader_architecture.rs +++ b/crates/wasm-rquickjs/src/skeleton/module_loader_architecture.rs @@ -850,7 +850,7 @@ fn module_loader_realpath_checks_wizer_before_filesystem_access() { .expect("loader realpath helper must have a bounded function body"); let body = &body[..end]; let guard = body - .find("crate::internal::preinit::check(") + .find("crate::internal::preinit::filesystem()?") .expect("loader realpath helper must retain the Wizer filesystem guard"); let filesystem_access = body .find("canonicalize_guest_path_with_cache(") diff --git a/tests/optimize/preinit.rs b/tests/optimize/preinit.rs index 4f05e186c..9f110988a 100644 --- a/tests/optimize/preinit.rs +++ b/tests/optimize/preinit.rs @@ -199,54 +199,64 @@ fn optimize_guest_failure(input: &Utf8Path, output: &Utf8Path) -> anyhow::Result } #[test] -fn optimizer_rejects_guest_io_filesystem() -> anyhow::Result<()> { - check_guest_denials(&[ - ("import fs from 'node:fs'; fs.existsSync('/');", "fs.exists"), - ( - "import fs from 'node:fs'; try { fs.statSync('/'); } catch {} await new Promise(() => {});", - "fs.stat", - ), +fn optimizer_rejects_uncaught_filesystem_errors() -> anyhow::Result<()> { + let temp = Utf8TempDir::new()?; + let template = build_preinit_template( + temp.path(), + wasm_rquickjs::GenerationTarget::WasiP3, + "full-p3", + )?; + let input = temp.path().join("input.wasm"); + let output = temp.path().join("optimized.wasm"); + for (source, expected) in [ + ("import fs from 'node:fs'; fs.readFileSync('/x');", "ENOENT"), ( - "import fs from 'node:fs/promises'; await fs.readFile('/x').catch(() => {});", - "fs.open", + "import fs from 'node:fs/promises'; await fs.readFile('/x');", + "ENOENT", ), ( "import fs from 'node:fs'; fs.writeFileSync('/x', 'x');", - "fs.open", + "ENOENT", ), ( "import fs from 'node:fs'; fs.openSync('/x', 'r');", - "fs.open", - ), - ( - "import {runInNewContext} from 'node:vm'; import fs from 'node:fs'; runInNewContext('fs.existsSync(\"/\")', {fs});", - "fs.exists", - ), - ( - "import fs from 'node:fs'; fs.statSync('/missing', {throwIfNoEntry:false});", - "fs.stat", - ), - ( - "import fs from 'node:fs'; fs.exists('/', () => {});", - "fs.exists", + "ENOENT", ), ( "import fs from 'node:fs'; fs.mkdirSync('/new-dir');", - "fs.mkdir", + "ENOENT", ), ( "import fs from 'node:fs'; fs.appendFileSync('/new-file', 'x');", - "fs.open", + "ENOENT", ), ( "import fs from 'node:fs'; fs.unlinkSync('/old-file');", - "fs.unlink", + "ENOENT", ), + ("import fs from 'node:fs'; fs.readdirSync('/');", "ENOENT"), + ("import fs from 'node:fs'; fs.accessSync('/');", "ENOENT"), + ("import fs from 'node:fs'; fs.realpathSync('/');", "ENOENT"), ( - "import fs from 'node:fs'; setImmediate(() => fs.existsSync('/'));", - "fs.exists", + "import fs from 'node:fs'; fs.realpathSync.native('/');", + "ENOENT", ), - ]) + ("await import('/runtime-only.mjs');", "ERR_MODULE_NOT_FOUND"), + ( + "import {createRequire} from 'node:module'; createRequire('/app/main.cjs')('./optional.cjs');", + "Cannot find module './optional.cjs'", + ), + ] { + let source = format!( + "{source}\nexport function ready() {{ return ''; }} export function run() {{ return ''; }}" + ); + wasm_rquickjs::inject_js_into_component(&template, &input, &[&source])?; + let failure = optimize_guest_failure(&input, &output)?; + assert!(failure.contains(expected), "{source}: {failure}"); + assert!(!failure.contains("WRQJS_PREINITIALIZATION_IO"), "{failure}"); + assert!(!output.exists()); + } + Ok(()) } // Keep the filesystem and host-service denials independently schedulable. Each @@ -259,7 +269,6 @@ fn optimizer_rejects_guest_io_host_services() -> anyhow::Result<()> { "WebSocket connection", ), ("process.chdir('/');", "process.chdir"), - ("await import('/runtime-only.mjs');", "module path probe"), ( "import {DatabaseSync} from 'node:sqlite'; new DatabaseSync(':memory:');", "SQLite database open", @@ -304,35 +313,14 @@ fn optimizer_rejects_execution_jobs_during_preinit() -> anyhow::Result<()> { #[test] fn optimizer_retains_stderr_tail_after_overflow() -> anyhow::Result<()> { check_guest_denials(&[( - "import fs from 'node:fs'; process.stderr.write('x'.repeat(70 * 1024)); fs.existsSync('/overflow-tail');", - "fs.exists", + "process.stderr.write('x'.repeat(70 * 1024)); process.chdir('/overflow-tail');", + "process.chdir", )]) } #[test] fn optimizer_rejects_additional_guest_io() -> anyhow::Result<()> { check_guest_denials(&[ - ( - "import fs from 'node:fs'; fs.readdirSync('/');", - "fs.readdir", - ), - ("import fs from 'node:fs'; fs.accessSync('/');", "fs.access"), - ( - "import fs from 'node:fs'; fs.realpathSync('/');", - "fs.lstat", - ), - ( - "import fs from 'node:fs'; fs.realpathSync.native('/');", - "fs.realpath", - ), - ( - "import {createRequire} from 'node:module'; createRequire('/app/main.cjs')('./optional.cjs');", - "module path probe", - ), - ( - "import {findPackageJSON} from 'node:module'; findPackageJSON('./package.json', 'file:///app/main.mjs');", - "package.json", - ), ( "import net from 'node:net'; net.createServer().listen(0);", "TCP listener creation", @@ -341,22 +329,6 @@ fn optimizer_rejects_additional_guest_io() -> anyhow::Result<()> { "import http from 'node:http'; http.createServer().listen(0);", "TCP listener creation", ), - ( - r#"import {register} from 'node:module'; - register('data:text/javascript,' + encodeURIComponent(` - export function resolve(s,c,n) { - if (s === 'chain:root') return {shortCircuit:true,url:'file:///chain/root.cjs',format:'commonjs'}; - if (s === './child.cjs') return {shortCircuit:true,url:'file:///chain/child.cjs',format:'commonjs'}; - return n(s,c); - } - export function load(u,c,n) { - if (u === 'file:///chain/root.cjs') return {shortCircuit:true,format:'commonjs',source:'module.exports = require("./child.cjs");'}; - if (u === 'file:///chain/child.cjs') return {shortCircuit:true,format:'commonjs',source:'exports.answer=1;'}; - return n(u,c); - } - `)); await import('chain:root');"#, - "module path probe", - ), ]) } @@ -396,7 +368,7 @@ fn check_guest_denials(cases: &[(&str, &str)]) -> anyhow::Result<()> { &template, &input, &[ - "import fs from 'node:fs'; fs.existsSync('/diagnostic-path'); export function run() { return ''; } export function ready() { return ''; }", + "process.chdir('/diagnostic-path'); export function run() { return ''; } export function ready() { return ''; }", ], )?; let failure = runtime @@ -404,7 +376,7 @@ fn check_guest_denials(cases: &[(&str, &str)]) -> anyhow::Result<()> { .unwrap_err(); let failure = format!("{failure:#}"); assert!(failure.contains("WRQJS_PREINITIALIZATION_IO"), "{failure}"); - assert!(failure.contains("fs.exists"), "{failure}"); + assert!(failure.contains("process.chdir"), "{failure}"); assert!(failure.contains("/diagnostic-path"), "{failure}"); } Ok(()) @@ -476,6 +448,156 @@ fn optimizer_preserves_console_stdio_after_preinit() -> anyhow::Result<()> { Ok(()) } +#[test] +fn optimizer_preserves_caught_filesystem_absence() -> anyhow::Result<()> { + let temp = Utf8TempDir::new()?; + let root = temp.path(); + let host_file = root.join("host-only.txt"); + std::fs::write(&host_file, "build-host-secret")?; + let template = + build_preinit_template(root, wasm_rquickjs::GenerationTarget::WasiP3, "full-p3")?; + let input = root.join("input.wasm"); + let output = root.join("optimized.wasm"); + let source = r#" + import assert from 'node:assert/strict'; + import fs from 'node:fs'; + import fsp from 'node:fs/promises'; + import {createRequire, findPackageJSON, register} from 'node:module'; + import {runInNewContext} from 'node:vm'; + const require = createRequire('/app/probe.cjs'); + for (const call of [ + () => fs.readFileSync('/app/value.txt'), + () => fs.openSync('/app/value.txt', 'r'), + () => fs.statSync('/app/value.txt'), + () => fs.lstatSync('/app/value.txt'), + () => fs.readdirSync('/app'), + () => fs.accessSync('/app/value.txt'), + () => fs.realpathSync('/app/value.txt'), + () => fs.realpathSync.native('/app/value.txt'), + () => fs.mkdirSync('/app/new-dir'), + () => fs.appendFileSync('/app/value.txt', 'x'), + () => fs.unlinkSync('/app/value.txt'), + () => fs.renameSync('/app/value.txt', '/app/other.txt'), + () => fs.copyFileSync('/app/value.txt', '/app/other.txt'), + () => fs.linkSync('/app/value.txt', '/app/other.txt'), + () => fs.symlinkSync('value.txt', '/app/link'), + () => fs.readlinkSync('/app/link'), + () => fs.truncateSync('/app/value.txt'), + () => fs.chmodSync('/app/value.txt', 0o600), + () => fs.chownSync('/app/value.txt', 0, 0), + () => fs.lchownSync('/app/value.txt', 0, 0), + () => fs.utimesSync('/app/value.txt', 1, 2), + () => fs.lutimesSync('/app/value.txt', 1, 2), + () => fs.rmdirSync('/app'), + () => fs.rmSync('/app/value.txt'), + () => fs.mkdtempSync('/app/temp-'), + () => fs.readFileSync(HOST_FILE), + () => fs.writeFileSync(HOST_FILE, 'must-not-write'), + ]) assert.throws(call, {code:'ENOENT'}); + assert.equal(fs.existsSync(HOST_FILE), false); + assert.equal(fs.existsSync('/app/value.txt'), false); + assert.equal(fs.statSync('/app/value.txt', {throwIfNoEntry:false}), undefined); + fs.rmSync('/app/value.txt', {force:true}); + assert.equal(findPackageJSON('./package.json', 'file:///app/main.mjs'), undefined); + let deferredAbsent = false; + setImmediate(() => { + assert.equal(fs.existsSync('/app/value.txt'), false); deferredAbsent = true; + }); + await assert.rejects(fsp.readFile('/app/value.txt'), {code:'ENOENT'}); + await new Promise(resolve => fs.exists('/app/value.txt', exists => { + assert.equal(exists, false); resolve(); + })); + assert.equal(runInNewContext('fs.existsSync("/app/value.txt")', {fs}), false); + // Supplied sources must not acquire a filesystem dependency. + register('data:text/javascript,' + encodeURIComponent(` + export function resolve(s,c,n) { + if (s === 'supplied:optional') return {shortCircuit:true,url:'file:///provided/optional.mjs'}; + if (s === 'chain:root') return {shortCircuit:true,url:'file:///chain/root.cjs',format:'commonjs'}; + if (s === './child.cjs') return {shortCircuit:true,url:'file:///chain/child.cjs',format:'commonjs'}; + return n(s,c); + } + export function load(u,c,n) { + if (u === 'file:///provided/optional.mjs') return {shortCircuit:true,format:'module',source:'export default 73'}; + if (u === 'file:///chain/root.cjs') return {shortCircuit:true,format:'commonjs',source:'module.exports = require("./child.cjs");'}; + if (u === 'file:///chain/child.cjs') return {shortCircuit:true,format:'commonjs',source:'exports.answer=1;'}; + return n(u,c); + } + `)); + const supplied = await import('supplied:optional'); + assert.equal(supplied.default, 73); + assert.equal((await import('chain:root')).default.answer, 1); + // Keep the loader registration unchanged across absence and restore. + for (const name of ['./optional.cjs', 'optional-package']) { + assert.throws(() => require(name), {code:'MODULE_NOT_FOUND'}); + assert.throws(() => require.resolve(name), {code:'MODULE_NOT_FOUND'}); + } + await assert.rejects(import('/app/optional.mjs'), {code:'ERR_MODULE_NOT_FOUND'}); + await assert.rejects(import('optional-package'), {code:'ERR_MODULE_NOT_FOUND'}); + export function ready() { return 'ready'; } + export async function run() { + assert.equal(deferredAbsent, true); + const value = fs.readFileSync('/app/value.txt', 'utf8'); + assert.equal(fs.existsSync('/app/value.txt'), true); + assert.equal(await fsp.readFile('/app/value.txt', 'utf8'), value); + assert.equal(fs.realpathSync('/app/value.txt'), '/app/value.txt'); + assert.equal(fs.statSync('/app/value.txt').isFile(), true); + fs.writeFileSync('/app/after.txt', value + '-written'); + assert.equal(fs.readFileSync('/app/after.txt', 'utf8'), value + '-written'); + assert.equal(require('./optional.cjs').value, 'cjs-' + value); + assert.equal(require('optional-package').value, 'package-' + value); + assert.equal((await import('/app/optional.mjs')).value, 'esm-' + value); + // Bare imports resolve from their module, not the restored cwd. + assert.equal((await import('/app/package-probe.mjs')).default.value, 'package-' + value); + return value; + } + "# + .replace("HOST_FILE", &serde_json::to_string(host_file.as_str())?); + wasm_rquickjs::inject_js_into_component(&template, &input, &[&source])?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + runtime.block_on(optimize_component(&input, &output, "wizer-initialize"))?; + assert_eq!(std::fs::read_to_string(&host_file)?, "build-host-secret"); + for value in ["first-17", "second-29"] { + let filesystem = root.join(value); + let app = filesystem.join("app"); + let package = app.join("node_modules/optional-package"); + std::fs::create_dir_all(&package)?; + std::fs::write(app.join("value.txt"), value)?; + std::fs::write( + app.join("optional.cjs"), + format!("exports.value = 'cjs-{value}';"), + )?; + std::fs::write( + app.join("optional.mjs"), + format!("export const value = 'esm-{value}';"), + )?; + std::fs::write( + app.join("package-probe.mjs"), + "export { default } from 'optional-package';", + )?; + std::fs::write(package.join("package.json"), r#"{"main":"index.cjs"}"#)?; + std::fs::write( + package.join("index.cjs"), + format!("exports.value = 'package-{value}';"), + )?; + let result = runtime + .block_on(run_probe_inner( + &output, + false, + Some(&filesystem), + Some("/app"), + ))? + .unwrap(); + assert_eq!(result.json, value); + assert_eq!( + std::fs::read_to_string(app.join("after.txt"))?, + format!("{value}-written") + ); + } + Ok(()) +} + #[test] fn optimizer_preserves_pure_sources_and_runtime_filesystem() -> anyhow::Result<()> { use wasm_rquickjs::GenerationTarget; From ac5060d816d39ee6dc7eb9d47c6dfdc99b885a06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Wed, 25 Nov 2026 17:09:01 +0000 Subject: [PATCH 2/3] Test catchable filesystem initializer probes --- tests/optimize/source_input.rs | 69 ++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 19 deletions(-) diff --git a/tests/optimize/source_input.rs b/tests/optimize/source_input.rs index aeb53755b..873c01832 100644 --- a/tests/optimize/source_input.rs +++ b/tests/optimize/source_input.rs @@ -230,25 +230,56 @@ fn initializer_sources_reuse_compilation_without_reusing_guest_state() -> anyhow ); assert!(!output.exists()); } - for invalid in [ - "export const = ;", - "import fs from 'node:fs'; fs.existsSync('/app');", - ] { - let sources = vec![invalid.into(), a[1].clone(), a[2].clone()]; - assert!( - optimize_component_with_options( - &template, - &output, - "wizer-initialize", - &OptimizeOptions { - sources: Some(&sources), - ..Default::default() - } - ) - .await - .is_err() - ); - assert!(!output.exists()); + let malformed = vec!["export const = ;".into(), a[1].clone(), a[2].clone()]; + assert!( + optimize_component_with_options( + &template, + &output, + "wizer-initialize", + &OptimizeOptions { + sources: Some(&malformed), + ..Default::default() + } + ) + .await + .is_err() + ); + assert!(!output.exists()); + + // Filesystem absence is catchable even with supplied initializer sources. + // Reuse compiled code, then execute the snapshot in fresh guest instances. + let probe = vec![ + r#" + import fs from 'node:fs'; + const exists = fs.existsSync('/app'); + let calls = 0; + export function ready() { return 'ready'; } + export function run() { return JSON.stringify({exists, calls: ++calls}); } + "# + .into(), + a[1].clone(), + a[2].clone(), + ]; + let result = optimize_component_with_options( + &template, + &output, + "wizer-initialize", + &OptimizeOptions { + sources: Some(&probe), + engine_config: Some(&config), + cache_config: Some(&cache_config), + ..Default::default() + }, + ) + .await?; + assert_eq!( + result.compilation_cache, + Some(CompilationCacheStats { hits: 1, misses: 0 }) + ); + for _ in 0..2 { + let value: serde_json::Value = + serde_json::from_str(&run_probe(&output, false).await?.unwrap())?; + assert_eq!(value, serde_json::json!({"exists": false, "calls": 1})); } optimize_component_with_options( &template, From 9cab043e9fd6b47b25037eef633b6c07685886e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1vid=20Istv=C3=A1n=20B=C3=ADr=C3=B3?= Date: Thu, 26 Nov 2026 09:51:22 +0000 Subject: [PATCH 3/3] Repair preinit loader retries and async errors --- README.md | 10 +- .../src/builtin/custom_invocation_context.rs | 10 ++ .../wasm-rquickjs/skeleton/src/builtin/fs.js | 2 + .../src/builtin/internal/fs/shared.js | 16 +++ .../skeleton/src/builtin/module.js | 33 ++++- .../skeleton/src/builtin/process.js | 52 ++++---- .../skeleton/src/builtin/process.rs | 14 ++- .../skeleton/src/internal/preinit.rs | 14 +++ tests/optimize/preinit.rs | 118 +++++++++++++++++- 9 files changed, 235 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index a69abdfa3..034e80493 100644 --- a/README.md +++ b/README.md @@ -269,9 +269,13 @@ operations report catchable `ENOENT` errors; existence probes return `false`, an filesystem-backed module/package lookup follows its normal not-found behavior. These results are synthesized before touching the build host, WASI preopens, libc filesystem state or runtime loader caches. Optional imports and file probes -may catch this absence; an uncaught exception still fails the build. Values -computed from caught absence remain frozen in the snapshot, so perform any -filesystem-dependent work again after restoration when needed. +may catch this absence. Pre-initialization now also rejects uncaught deferred +exceptions and unhandled promise rejections, including non-filesystem errors; +it no longer snapshots initialization after silently dropping those failures. +Registered loaders retry synthetic filesystem failures after restoration without +discarding ordinary loader errors or successful modules. Values computed from +caught absence remain frozen in the snapshot, so perform any filesystem-dependent +work again after restoration when needed. Socket/DNS/HTTP/WebSocket acquisition, SQLite opens (including `:memory:`), execution-job creation, and `process.chdir()` still fail the build immediately. diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/custom_invocation_context.rs b/crates/wasm-rquickjs/skeleton/src/builtin/custom_invocation_context.rs index f88da8cfd..6c477207a 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/custom_invocation_context.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/custom_invocation_context.rs @@ -3,6 +3,7 @@ pub const CUSTOM_INVOCATION_CONTEXT_JS: &str = include_str!("custom_invocation_c /// `queueMicrotask` jobs get no promise hook events, so the callback carries its scope itself. pub const WIRE_JS: &str = r#" import { capture_for_callback as __wasm_rquickjs_captureScope, enter_callback as __wasm_rquickjs_enterScope, leave_callback as __wasm_rquickjs_leaveScope } from '__wasm_rquickjs_builtin/custom_invocation_context_native'; + import { is_preinitializing as __wasm_rquickjs_isPreinitializing, reject_preinit_uncaught_error as __wasm_rquickjs_rejectPreinitUncaughtError } from '__wasm_rquickjs_builtin/process_native'; const __wasm_rquickjs_queueMicrotask = globalThis.queueMicrotask; globalThis.queueMicrotask = function queueMicrotask(callback) { if (typeof callback !== 'function') { @@ -13,6 +14,15 @@ pub const WIRE_JS: &str = r#" const previous = __wasm_rquickjs_enterScope(scope); try { return callback(); + } catch (error) { + // QuickJS's pending-job path discards escaped errors. Make + // initialization fail without changing runtime job policy. + if (!__wasm_rquickjs_isPreinitializing()) throw error; + if (typeof globalThis.__wasm_rquickjs_handleUncaughtError === 'function') { + globalThis.__wasm_rquickjs_handleUncaughtError(error); + } else { + __wasm_rquickjs_rejectPreinitUncaughtError(error); + } } finally { __wasm_rquickjs_leaveScope(previous); } diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/fs.js b/crates/wasm-rquickjs/skeleton/src/builtin/fs.js index 7da0995e8..1c6e58e2e 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/fs.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/fs.js @@ -12,6 +12,7 @@ import { describeType, getSystemErrorDescription, createSystemError, + markPreinitFilesystemError, validateInteger, validateMode, parseMkdirOptions as _parseMkdirOptions, @@ -434,6 +435,7 @@ function createCopyFileError(code, errno, description, src, dest) { err.syscall = 'copyfile'; err.path = src; err.dest = dest; + if (code === 'ENOENT') markPreinitFilesystemError(err); return err; } diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/internal/fs/shared.js b/crates/wasm-rquickjs/skeleton/src/builtin/internal/fs/shared.js index 55f55fcc5..ad4d6023e 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/internal/fs/shared.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/internal/fs/shared.js @@ -1,5 +1,18 @@ // Shared helpers used by both fs.js and fs_promises.js. // This module must NOT import from 'node:fs' to avoid circular dependencies. +import { is_preinitializing } from '__wasm_rquickjs_builtin/process_native'; +import { createPrivateWeakSet } from '__wasm_rquickjs_builtin/internal/weak_collections'; + +const preinitFilesystemErrors = createPrivateWeakSet(); + +export function markPreinitFilesystemError(error) { + if (is_preinitializing()) preinitFilesystemErrors.add(error); + return error; +} + +export function isStalePreinitFilesystemError(error) { + return preinitFilesystemErrors.has(error) && !is_preinitializing(); +} export function getInternalFsBinding() { return globalThis.__wasm_rquickjs_internal_fs_binding || @@ -45,6 +58,9 @@ export function createSystemError(errObj) { err.syscall = errObj.syscall; if (errObj.path !== undefined) err.path = errObj.path; if (errObj.dest !== undefined) err.dest = errObj.dest; + // Native filesystem ENOENT during preinit is synthetic. Keep its provenance + // private: a loader's own ENOENT must not become a retryable snapshot error. + if (errObj.code === 'ENOENT') markPreinitFilesystemError(err); return err; } diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/module.js b/crates/wasm-rquickjs/skeleton/src/builtin/module.js index 49a27d0b8..715c6cb9d 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/module.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/module.js @@ -9,7 +9,7 @@ import * as diagnostics_channel from 'node:diagnostics_channel'; import * as internalHttp from '__wasm_rquickjs_builtin/internal/http'; import { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } from '__wasm_rquickjs_builtin/internal/errors'; import * as internalErrors from '__wasm_rquickjs_builtin/internal/errors'; -import { createSystemError as createFsSystemError } from '__wasm_rquickjs_builtin/internal/fs/shared'; +import { createSystemError as createFsSystemError, markPreinitFilesystemError, isStalePreinitFilesystemError } from '__wasm_rquickjs_builtin/internal/fs/shared'; import * as internalFsUtils from '__wasm_rquickjs_builtin/internal/fs/utils'; import * as internalUrl from '__wasm_rquickjs_builtin/internal/url'; import * as internalUtil from '__wasm_rquickjs_builtin/internal/util'; @@ -2880,7 +2880,7 @@ function resultForEsmFileUrl(url, parentURL) { const filename = nodeUrl.fileURLToPath(url); const stat = _stat(filename); if (stat === 1) throw makeEsmUnsupportedDirImportError(filename); - if (stat !== 0) throw makeEsmModuleNotFoundError(url.href); + if (stat !== 0) throw markPreinitFilesystemError(makeEsmModuleNotFoundError(url.href)); if (shouldPreserveSymlinks(false)) { return registeredLoaderUrlFormatResult(url.href, defaultLoaderFormatForFilename(url.pathname)); } @@ -2959,17 +2959,23 @@ function registeredLoaderBuiltinResolve(specifier, cjsMode) { } function resolvePackageDefaultForLoader(specifier, parentURL, context, defaultConditions, mode, mapNotFoundToCjs) { + // Loader-controlled getters may throw ordinary errors with these codes. + // Only classify absence after entering the native filesystem resolver. + const conditions = packageConditionArrayForLoaderResolve(context, defaultConditions); try { return resolvePackageWithRustBridge( parentURL, specifier, - packageConditionArrayForLoaderResolve(context, defaultConditions), + conditions, mode, 'Internal package resolver provider is not initialized', ); } catch (err) { if (mapNotFoundToCjs && err && err.code === 'ERR_MODULE_NOT_FOUND') { - throw makeModuleNotFoundError(specifier); + throw markPreinitFilesystemError(makeModuleNotFoundError(specifier)); + } + if (err && (err.code === 'ERR_MODULE_NOT_FOUND' || err.code === 'ERR_PACKAGE_IMPORT_NOT_DEFINED')) { + markPreinitFilesystemError(err); } throw err; } @@ -4904,7 +4910,7 @@ if (typeof globalThis.__wasm_rquickjs_run_registered_loaders !== 'function') { const packageResolved = resolveEsmPackageDefaultForLoader(preprocessedSpecifier, internalParentURL, context); if (packageResolved) return packageResolved; if (missingAsUndefined) return undefined; - throw makeEsmModuleNotFoundError(preprocessedSpecifier); + throw markPreinitFilesystemError(makeEsmModuleNotFoundError(preprocessedSpecifier)); } if (missingAsUndefined) return undefined; @@ -5011,6 +5017,10 @@ if (typeof globalThis.__wasm_rquickjs_run_registered_loaders !== 'function') { if (cacheRegisteredLoaderLoad) { const loadCacheKey = registeredLoaderLoadCacheKey(resolvedState); let cacheEntry = registeredLoaderLoadCache[loadCacheKey]; + if (cacheEntry && isStalePreinitFilesystemError(cacheEntry.error)) { + delete registeredLoaderLoadCache[loadCacheKey]; + cacheEntry = undefined; + } if (!cacheEntry) { cacheEntry = { materialized: Object.create(null), @@ -5031,7 +5041,12 @@ if (typeof globalThis.__wasm_rquickjs_run_registered_loaders !== 'function') { ); })(); } - result = await cacheEntry.promise; + try { + result = await cacheEntry.promise; + } catch (error) { + cacheEntry.error = error; + throw error; + } } else { const loaded = await runLoad( entries.length - 1, @@ -5464,6 +5479,9 @@ if (typeof globalThis.__wasm_rquickjs_run_registered_loaders !== 'function') { function staticRegisteredLoaderCacheEntry(parentUrl, specifier, attrs, edgeReturn, publicParentUrl) { const key = staticRegisteredLoaderCacheKey(parentUrl, specifier, attrs); const cache = wasmRquickjsModuleGlobalThis.__wasm_rquickjs_static_registered_loader_cache; + if (cache[key] && isStalePreinitFilesystemError(cache[key].error)) { + delete cache[key]; + } if (Object.prototype.hasOwnProperty.call(cache, key)) { return { cached: cache[key], created: false }; } @@ -5586,6 +5604,9 @@ if (typeof globalThis.__wasm_rquickjs_run_registered_loaders !== 'function') { const parts = staticRegisteredLoaderCacheParts(specifier); const attrs = parts.typeValue === '' ? undefined : { typeValue: parts.typeValue }; const key = staticRegisteredLoaderCacheKey(baseUrl, parts.specifier, attrs); + if (cache && cache[key] && isStalePreinitFilesystemError(cache[key].error)) { + delete cache[key]; + } if (cache && Object.prototype.hasOwnProperty.call(cache, key)) { const cached = cache[key]; if (cached.error) throw cached.error; diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/process.js b/crates/wasm-rquickjs/skeleton/src/builtin/process.js index 8be63e140..181e6dc48 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/process.js +++ b/crates/wasm-rquickjs/skeleton/src/builtin/process.js @@ -9,6 +9,8 @@ import { memory_usage as _native_memory_usage, has_typescript_runtime, typescript_runtime_mode, + is_preinitializing, + reject_preinit_uncaught_error, await_runtime_idle } from '__wasm_rquickjs_builtin/process_native'; import { capture_for_callback as __captureScope, enter_callback as __enterScope, leave_callback as __leaveScope } from '__wasm_rquickjs_builtin/custom_invocation_context_native'; @@ -603,31 +605,37 @@ const __nextTickWakeupOwners = new Set(); const __jobOwner = globalThis.__wasm_rquickjs_job_owner; function __wasm_rquickjs_handleUncaughtError(err, domain) { - if (domain && typeof domain.emit === 'function') { - if (err != null && (typeof err === 'object' || typeof err === 'function')) { - err.domain = domain; - err.domainThrown = true; + try { + if (domain && typeof domain.emit === 'function') { + if (err != null && (typeof err === 'object' || typeof err === 'function')) { + err.domain = domain; + err.domainThrown = true; + } + domain.emit('error', err); + return; } - domain.emit('error', err); - return; - } - if (_uncaughtExceptionCallback !== null) { - _uncaughtExceptionCallback(err); - return; - } + if (_uncaughtExceptionCallback !== null) { + _uncaughtExceptionCallback(err); + return; + } - if (process.listenerCount('uncaughtException') > 0) { - process.emit('uncaughtException', err, 'uncaughtException'); - return; - } + if (process.listenerCount('uncaughtException') > 0) { + process.emit('uncaughtException', err, 'uncaughtException'); + return; + } - if (typeof globalThis.__wasm_rquickjs_child_uncaught === 'function') { - globalThis.__wasm_rquickjs_child_uncaught(err); - return; - } - if (typeof console !== 'undefined') { - console.error(err); + if (typeof globalThis.__wasm_rquickjs_child_uncaught === 'function') { + globalThis.__wasm_rquickjs_child_uncaught(err); + return; + } + reject_preinit_uncaught_error(err); + if (typeof console !== 'undefined') { + console.error(err); + } + } catch (handlerError) { + reject_preinit_uncaught_error(handlerError); + throw handlerError; } } @@ -1167,7 +1175,7 @@ globalThis.__wasm_rquickjs_unhandled_rejection_checkpoint = function() { emitted += 1; try { if (process.listenerCount('unhandledRejection') === 0 && - typeof globalThis.__wasm_rquickjs_child_uncaught === 'function') { + (is_preinitializing() || typeof globalThis.__wasm_rquickjs_child_uncaught === 'function')) { __wasm_rquickjs_handleUncaughtError(entry.reason); } else { process.emit('unhandledRejection', entry.reason, promise); diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/process.rs b/crates/wasm-rquickjs/skeleton/src/builtin/process.rs index 62506f0ef..471c62aa0 100644 --- a/crates/wasm-rquickjs/skeleton/src/builtin/process.rs +++ b/crates/wasm-rquickjs/skeleton/src/builtin/process.rs @@ -1,10 +1,22 @@ // Native functions for the process implementation #[rquickjs::module(rename = "camelCase")] pub mod native_module { - use rquickjs::{BigInt, Ctx, Persistent, Promise}; + use rquickjs::{BigInt, Ctx, Persistent, Promise, Value}; use std::collections::HashMap; use std::path::Path; + #[rquickjs::function] + pub fn is_preinitializing() -> bool { + crate::internal::preinit::is_active() + } + + #[rquickjs::function] + pub fn reject_preinit_uncaught_error(error: Value<'_>) { + if crate::internal::preinit::is_active() { + crate::internal::preinit::uncaught_error(&crate::internal::format_js_exception(&error)); + } + } + #[rquickjs::function] pub fn memory_usage(ctx: Ctx<'_>) -> Vec { let rt = unsafe { rquickjs::qjs::JS_GetRuntime(ctx.as_raw().as_ptr()) }; diff --git a/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs b/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs index a5fa356c1..9e2c7e365 100644 --- a/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs +++ b/crates/wasm-rquickjs/skeleton/src/internal/preinit.rs @@ -29,6 +29,20 @@ pub(crate) fn is_active() -> bool { ACTIVE.load(Ordering::Relaxed) } +#[cold] +pub(crate) fn uncaught_error(error: &str) -> ! { + if !VIOLATED.swap(true, Ordering::Relaxed) { + let mut bounded = DiagnosticTarget::default(); + let _ = write!(&mut bounded, "{error}"); + *FIRST_VIOLATION.lock().unwrap() = Some(format!( + "WRQJS_PREINITIALIZATION_ERROR: uncaught JavaScript error during Wizer \ + pre-initialization: {}", + bounded.text + )); + } + trap() +} + /// Filesystem absence is catchable, but must be synthesized before libc/preopen /// discovery or loader caches can observe the optimizer's empty filesystem. #[inline] diff --git a/tests/optimize/preinit.rs b/tests/optimize/preinit.rs index 9f110988a..749dd13f8 100644 --- a/tests/optimize/preinit.rs +++ b/tests/optimize/preinit.rs @@ -209,6 +209,30 @@ fn optimizer_rejects_uncaught_filesystem_errors() -> anyhow::Result<()> { let input = temp.path().join("input.wasm"); let output = temp.path().join("optimized.wasm"); for (source, expected) in [ + ( + "import fs from 'node:fs'; process.setUncaughtExceptionCaptureCallback(error => { throw error; }); setImmediate(() => fs.readFileSync('/x'));", + "ENOENT", + ), + ( + "setImmediate(() => { throw new Error('uncaught deferred error'); });", + "uncaught deferred error", + ), + ( + "Promise.reject(new Error('unhandled initialization rejection'));", + "unhandled initialization rejection", + ), + ( + "import fs from 'node:fs'; fs.readFile('/x', error => { if (error) throw error; });", + "ENOENT", + ), + ( + "import fs from 'node:fs/promises'; fs.readFile('/x').then(() => {});", + "ENOENT", + ), + ( + "import fs from 'node:fs'; setImmediate(() => fs.readFileSync('/x'));", + "ENOENT", + ), ("import fs from 'node:fs'; fs.readFileSync('/x');", "ENOENT"), ( "import fs from 'node:fs/promises'; await fs.readFile('/x');", @@ -458,7 +482,7 @@ fn optimizer_preserves_caught_filesystem_absence() -> anyhow::Result<()> { build_preinit_template(root, wasm_rquickjs::GenerationTarget::WasiP3, "full-p3")?; let input = root.join("input.wasm"); let output = root.join("optimized.wasm"); - let source = r#" + let source = r##" import assert from 'node:assert/strict'; import fs from 'node:fs'; import fsp from 'node:fs/promises'; @@ -504,19 +528,52 @@ fn optimizer_preserves_caught_filesystem_absence() -> anyhow::Result<()> { assert.equal(fs.existsSync('/app/value.txt'), false); deferredAbsent = true; }); await assert.rejects(fsp.readFile('/app/value.txt'), {code:'ENOENT'}); + await new Promise(resolve => fs.readFile('/app/value.txt', error => { + assert.equal(error.code, 'ENOENT'); resolve(); + })); await new Promise(resolve => fs.exists('/app/value.txt', exists => { assert.equal(exists, false); resolve(); })); assert.equal(runInNewContext('fs.existsSync("/app/value.txt")', {fs}), false); // Supplied sources must not acquire a filesystem dependency. register('data:text/javascript,' + encodeURIComponent(` + import fs from 'node:fs'; export function resolve(s,c,n) { + if (s === 'optional:read') return {shortCircuit:true,url:'file:///app/loader-read.mjs'}; + if (s === 'optional:static') return {shortCircuit:true,url:'file:///app/loader-static.mjs'}; + if (s === 'supplied:parent') return {shortCircuit:true,url:'file:///provided/parent.mjs'}; + if (s === 'supplied:default-parent') return {shortCircuit:true,url:'file:///app/default-parent.mjs'}; + if (s === 'supplied:map-parent') return {shortCircuit:true,url:'file:///app/map-parent.mjs'}; + if (s === 'supplied:conditions-parent') return {shortCircuit:true,url:'file:///app/conditions-parent.mjs'}; + if (s === 'ordinary:conditions') { + const conditions = ['import']; + Object.defineProperty(conditions, 0, {get() { + throw Object.assign(new Error('ordinary resolve miss'), {code:'ERR_MODULE_NOT_FOUND'}); + }}); + return n('optional-package', {...c, conditions}); + } + if (s === 'optional:copy') return {shortCircuit:true,url:'file:///provided/copy.mjs'}; + if (s === 'optional:copy-excl') return {shortCircuit:true,url:'file:///provided/copy-excl.mjs'}; + if (s === 'ordinary:error') return {shortCircuit:true,url:'file:///provided/error.mjs'}; if (s === 'supplied:optional') return {shortCircuit:true,url:'file:///provided/optional.mjs'}; if (s === 'chain:root') return {shortCircuit:true,url:'file:///chain/root.cjs',format:'commonjs'}; if (s === './child.cjs') return {shortCircuit:true,url:'file:///chain/child.cjs',format:'commonjs'}; return n(s,c); } export function load(u,c,n) { + if (u === 'file:///app/loader-read.mjs') return {shortCircuit:true,format:'module',source:fs.readFileSync('/app/loader-read.mjs','utf8')}; + if (u === 'file:///app/loader-static.mjs') return {shortCircuit:true,format:'module',source:fs.readFileSync('/app/loader-static.mjs','utf8')}; + if (u === 'file:///provided/parent.mjs') return {shortCircuit:true,format:'module',source:'export { value } from "optional:static";'}; + if (u === 'file:///app/default-parent.mjs') return {shortCircuit:true,format:'module',source:'export { value } from "file:///app/default-child.mjs"; export {value as packageValue} from "optional-package";'}; + if (u === 'file:///app/map-parent.mjs') return {shortCircuit:true,format:'module',source:'export { value } from "#child";'}; + if (u === 'file:///app/conditions-parent.mjs') return {shortCircuit:true,format:'module',source:'export { value } from "ordinary:conditions";'}; + if (u === 'file:///provided/copy.mjs' || u === 'file:///provided/copy-excl.mjs') { + const exclusive = u.endsWith('copy-excl.mjs'); + const target = exclusive ? '/app/copy-excl.mjs' : '/app/copy.mjs'; + fs.copyFileSync('/app/copy-source.mjs', target, exclusive ? fs.constants.COPYFILE_EXCL : 0); + return {shortCircuit:true,format:'module',source:fs.readFileSync(target,'utf8')}; + } + if (u === 'file:///provided/error.mjs') throw Object.assign(new Error('ordinary loader error'), {code:'ENOENT'}); if (u === 'file:///provided/optional.mjs') return {shortCircuit:true,format:'module',source:'export default 73'}; if (u === 'file:///chain/root.cjs') return {shortCircuit:true,format:'commonjs',source:'module.exports = require("./child.cjs");'}; if (u === 'file:///chain/child.cjs') return {shortCircuit:true,format:'commonjs',source:'exports.answer=1;'}; @@ -533,9 +590,29 @@ fn optimizer_preserves_caught_filesystem_absence() -> anyhow::Result<()> { } await assert.rejects(import('/app/optional.mjs'), {code:'ERR_MODULE_NOT_FOUND'}); await assert.rejects(import('optional-package'), {code:'ERR_MODULE_NOT_FOUND'}); + await assert.rejects(import('optional:read'), {code:'ENOENT'}); + await assert.rejects(import('supplied:parent'), {code:'ENOENT'}); + await assert.rejects(import('supplied:default-parent'), {code:'ERR_MODULE_NOT_FOUND'}); + await assert.rejects(import('optional:copy'), {code:'ENOENT'}); + await assert.rejects(import('optional:copy-excl'), {code:'ENOENT'}); + await assert.rejects(import('supplied:map-parent'), {code:'ERR_PACKAGE_IMPORT_NOT_DEFINED'}); + const ordinaryResolveError = await import('supplied:conditions-parent').catch(error => error); + assert.equal(ordinaryResolveError.message, 'ordinary resolve miss'); + const ordinaryError = await import('ordinary:error').catch(error => error); + assert.equal(ordinaryError.message, 'ordinary loader error'); + let handledAsyncErrors = 0; + function handleAsyncError(error) { + assert.equal(error.code, 'ENOENT'); handledAsyncErrors++; + } + process.on('uncaughtException', handleAsyncError); + queueMicrotask(() => fs.readFileSync('/app/value.txt')); + setImmediate(() => fs.readFileSync('/app/value.txt')); + fsp.readFile('/app/value.txt').then(() => {}); export function ready() { return 'ready'; } export async function run() { assert.equal(deferredAbsent, true); + assert.equal(handledAsyncErrors, 3); + process.off('uncaughtException', handleAsyncError); const value = fs.readFileSync('/app/value.txt', 'utf8'); assert.equal(fs.existsSync('/app/value.txt'), true); assert.equal(await fsp.readFile('/app/value.txt', 'utf8'), value); @@ -546,11 +623,24 @@ fn optimizer_preserves_caught_filesystem_absence() -> anyhow::Result<()> { assert.equal(require('./optional.cjs').value, 'cjs-' + value); assert.equal(require('optional-package').value, 'package-' + value); assert.equal((await import('/app/optional.mjs')).value, 'esm-' + value); + assert.equal((await import('optional:read')).value, 'loader-' + value); + assert.equal((await import('supplied:parent')).value, 'static-' + value); + const retries = await Promise.all(['supplied:default-parent', 'optional:copy', 'optional:copy-excl'].map( + specifier => import(specifier).then(module => module.value, error => error.code) + )); + assert.deepEqual(retries, ['default-' + value, 'copy-' + value, 'copy-' + value]); + assert.equal((await import('supplied:default-parent')).packageValue, 'package-' + value); + const mapResult = await import('supplied:map-parent').then(module => module.value, error => error.code); + const ordinaryResolveRetry = await import('supplied:conditions-parent').catch(error => error); + assert.deepEqual({mapResult, ordinarySame: ordinaryResolveRetry === ordinaryResolveError}, + {mapResult: 'mapped-' + value, ordinarySame: true}); + assert.equal(await import('ordinary:error').catch(error => error), ordinaryError); + assert.equal(await import('supplied:optional'), supplied); // Bare imports resolve from their module, not the restored cwd. assert.equal((await import('/app/package-probe.mjs')).default.value, 'package-' + value); return value; } - "# + "## .replace("HOST_FILE", &serde_json::to_string(host_file.as_str())?); wasm_rquickjs::inject_js_into_component(&template, &input, &[&source])?; let runtime = tokio::runtime::Builder::new_current_thread() @@ -572,6 +662,30 @@ fn optimizer_preserves_caught_filesystem_absence() -> anyhow::Result<()> { app.join("optional.mjs"), format!("export const value = 'esm-{value}';"), )?; + std::fs::write( + app.join("loader-read.mjs"), + format!("export const value = 'loader-{value}';"), + )?; + std::fs::write( + app.join("loader-static.mjs"), + format!("export const value = 'static-{value}';"), + )?; + std::fs::write( + app.join("default-child.mjs"), + format!("export const value = 'default-{value}';"), + )?; + std::fs::write( + app.join("copy-source.mjs"), + format!("export const value = 'copy-{value}';"), + )?; + std::fs::write( + app.join("package.json"), + r##"{"imports":{"#child":"./mapped.mjs"}}"##, + )?; + std::fs::write( + app.join("mapped.mjs"), + format!("export const value = 'mapped-{value}';"), + )?; std::fs::write( app.join("package-probe.mjs"), "export { default } from 'optional-package';",