diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 4be7148e..96da3d5a 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -28,7 +28,7 @@ jobs: - uses: actions/setup-python@v5 with: - python-version: "3.14.0" + python-version: "3.14.10" - name: Install latest Rust stable toolchain uses: dtolnay/rust-toolchain@stable @@ -120,7 +120,7 @@ jobs: - uses: actions/setup-python@v5 with: - python-version: "3.14.0" + python-version: "3.14.10" - name: Test shell: bash diff --git a/Cargo.lock b/Cargo.lock index 7504a1ed..c831327b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -558,6 +558,7 @@ dependencies = [ "clap", "component-init-transform", "componentize-py-test-generator", + "filetime", "flate2", "fs_extra", "futures", @@ -573,6 +574,7 @@ dependencies = [ "reqwest 0.12.28", "semver", "serde", + "sha2 0.10.9", "tar", "tempfile", "tokio", @@ -4820,8 +4822,7 @@ dependencies = [ [[package]] name = "wit-component" version = "0.258.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0fca88950af0c1f42bc77e17315e48798b8d68340171b6d204f62bc19a878a6" +source = "git+https://github.com/golemcloud/wasm-tools?rev=801650b5c9e5e4aa32451283f7a6d14100f92889#801650b5c9e5e4aa32451283f7a6d14100f92889" dependencies = [ "anyhow", "bitflags", diff --git a/Cargo.toml b/Cargo.toml index 8eb8120c..01bf1355 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,8 @@ serde = { version = "1.0.213", features = ["derive"] } toml = "0.8.19" semver = "1.0.23" wit-bindgen-core = "0.61.0" +sha2 = "0.10.9" +filetime = "0.2.29" [dev-dependencies] assert_cmd = "2.0.16" @@ -82,6 +84,8 @@ tar = "0.4.41" zstd = "0.13.2" componentize-py-test-generator = { path = "test-generator", version = "0.25.0" } flate2 = "1.1.1" +hex = "0.4.3" +sha2 = "0.10.9" wasmparser = "0.258.0" wasm-encoder = "0.258.0" @@ -91,3 +95,11 @@ package.edition = "2024" package.license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" package.repository = "https://github.com/bytecodealliance/componentize-py" members = ["runtime", "test-generator"] + +# wit-component 0.258.3 from the golem-2.0 branch of golemcloud/wasm-tools, +# which adds one fix in `src/linking.rs`: the dlopen symbol table counts only +# the symbols it writes, so a library exporting a Wasm tag (such as +# `__c_longjmp`) no longer corrupts the table. Its sibling crates (wasmparser, +# wasm-encoder, wit-parser, ...) still come from crates.io. +[patch.crates-io] +wit-component = { git = "https://github.com/golemcloud/wasm-tools", rev = "801650b5c9e5e4aa32451283f7a6d14100f92889" } diff --git a/build.rs b/build.rs index 5c2e65c6..e95716d0 100644 --- a/build.rs +++ b/build.rs @@ -2,6 +2,7 @@ use { anyhow::{Context, Result, anyhow, bail}, + sha2::{Digest as _, Sha256}, std::{ env, fmt::Write as _, @@ -22,9 +23,14 @@ const STRIP_RUNTIME: bool = !DEBUG_RUNTIME; const ZSTD_COMPRESSION_LEVEL: i32 = if DEBUG_RUNTIME { 0 } else { 19 }; const DEFAULT_SDK_VERSION: &str = "34"; -// SQLite version to build - 3.51.2 (latest as of Jan 2026) -const SQLITE_VERSION: &str = "3510200"; +const SQLITE_VERSION: &str = "3540100"; const SQLITE_YEAR: &str = "2026"; +const SQLITE_TARBALL_SHA256: &str = + "926ef8d3eab93fbf6e06011901273eec076b25594a4e1cdadd50c987f4f6d64e"; + +const ZLIB_VERSION: &str = "1.3.2"; +const ZLIB_TARBALL_SHA256: &str = + "bb329a0a2cd0274d05519d61c667c062e06990d72e125ee2dfa8de64f0119d16"; #[cfg(any(target_os = "macos", target_os = "windows"))] const PYTHON_EXECUTABLE: &str = "python.exe"; @@ -36,10 +42,18 @@ const CLANG_EXECUTABLE: &str = "clang.exe"; #[cfg(not(target_os = "windows"))] const CLANG_EXECUTABLE: &str = "clang"; -// TODO: switch to upstream release per -// https://github.com/bytecodealliance/componentize-py/issues/215 -const CPYTHON_TARBALL_URL: &str = "https://github.com/dicej/cpython/tarball/v3.14.0-wasi-sdk-30"; -const CPYTHON_TARBALL_BASE_DIR: &str = "dicej-cpython-0e13686"; +// The CPython release tarball from python.org, plus the WASI patches in +// `cpython-patches/` that are not part of this release. +const CPYTHON_VERSION: &str = "3.14.10"; +const CPYTHON_TARBALL_SHA256: &str = + "9e4996c19ae5a3df31f10c37723661f71d3455d73bd005f79df7098e5cc13192"; + +// The file in `cpython/` and in `cpython/builddir/wasi` that names the sources +// the tree and the built library were made from. A tree or library with +// another identity, or none, is rejected instead of being reused. +// The name is not hidden, because CI uploads `cpython/builddir/wasi` as an +// artifact without hidden files. +const CPYTHON_SOURCE_IDENTITY_FILE: &str = "componentize-py-source-identity"; fn main() -> Result<()> { println!("cargo:rerun-if-changed=build.rs"); @@ -76,6 +90,7 @@ fn stubs_for_clippy(out_dir: &Path) -> Result<()> { "libwasi-emulated-signal.so.zst", "libc++.so.zst", "libc++abi.so.zst", + "libsetjmp.so.zst", "wasi_snapshot_preview1.reactor.wasm.zst", ]; @@ -154,7 +169,8 @@ fn find_wasi_sdk(out_dir: &Path) -> Result { url, wasi_sdk.display() ); - fetch_extract(&url, out_dir)?; + // The SDK source and version are configurable, so no digest is pinned for it. + fetch_extract(&url, None, out_dir)?; Ok(wasi_sdk) } @@ -189,6 +205,7 @@ fn package_all_the_things(out_dir: &Path) -> Result<()> { let libraries = [ "libc.so", + "libsetjmp.so", "libwasi-emulated-mman.so", "libwasi-emulated-process-clocks.so", "libwasi-emulated-getpid.so", @@ -307,113 +324,206 @@ fn add(builder: &mut Builder, root: &Path, path: &Path) -> Result<() fn maybe_make_cpython(repo_dir: &Path, wasi_sdk: &Path) -> Result<()> { let cpython_dir = repo_dir.join("cpython"); - if !cpython_dir.exists() { - let url = &env::var("CPYTHON_TARBALL_URL").unwrap_or_else(|_| CPYTHON_TARBALL_URL.into()); - let base_dir = &env::var_os("CPYTHON_TARBALL_BASE_DIR") - .unwrap_or_else(|| CPYTHON_TARBALL_BASE_DIR.into()); - println!("cargo:warning=downloading CPython source code from {url}"); - fetch_extract(url, repo_dir)?; - fs::rename(repo_dir.join(base_dir), &cpython_dir)?; - } + let patch_dir = repo_dir.join("cpython-patches"); + println!("cargo:rerun-if-changed={}", patch_dir.display()); + let mut patches = fs::read_dir(&patch_dir)? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>()?; + patches.retain(|path| { + path.extension() + .is_some_and(|extension| extension == "patch") + }); + patches.sort(); + let identity = cpython_source_identity(&patches)?; let cpython_wasi_dir = cpython_dir.join("builddir/wasi"); - if !cpython_wasi_dir.join("libpython3.14.so").exists() { - fs::create_dir_all(&cpython_wasi_dir)?; - if !cpython_wasi_dir.join("libpython3.14.a").exists() { - let cpython_native_dir = repo_dir.join("cpython/builddir/build"); - if !cpython_native_dir.join(PYTHON_EXECUTABLE).exists() { - fs::create_dir_all(&cpython_native_dir)?; - - run(Command::new("../../configure") - .current_dir(&cpython_native_dir) - .arg(format!( - "--prefix={}/install", - cpython_native_dir.to_str().ok_or_else(|| anyhow!( - "non-UTF8 path: {}", - cpython_native_dir.display() - ))? - )))?; - - run(Command::new("make").current_dir(cpython_native_dir))?; - } + if cpython_wasi_dir.join("libpython3.14.so").exists() { + // A build restored without its sources, as in CI, carries the + // identity next to the library. + return check_cpython_identity(&cpython_wasi_dir, &identity, &cpython_dir, &patch_dir); + } - let lib_install_dir = cpython_wasi_dir.join("deps"); - build_zlib(wasi_sdk, &lib_install_dir)?; - - build_sqlite(wasi_sdk, &lib_install_dir)?; - - let config_guess = - run(Command::new("../../config.guess").current_dir(&cpython_wasi_dir))?; - - let dir = cpython_wasi_dir - .to_str() - .ok_or_else(|| anyhow!("non-UTF8 path: {}", cpython_wasi_dir.display()))?; - - // Configure CPython with SQLite support - // The CFLAGS and LDFLAGS now include paths to both zlib AND sqlite - run(Command::new("../../Tools/wasm/wasi-env") - .env( - "CONFIG_SITE", - "../../Tools/wasm/wasi/config.site-wasm32-wasi", - ) - .env( - "CFLAGS", - format!("--target=wasm32-wasip2 -fPIC -I{dir}/deps/include"), - ) - .env("WASI_SDK_PATH", wasi_sdk) - .env( - "LDFLAGS", - format!("--target=wasm32-wasip2 -L{dir}/deps/lib"), - ) - .current_dir(&cpython_wasi_dir) - .args([ - "../../configure", - "-C", - "--host=wasm32-unknown-wasip2", - &format!("--build={}", String::from_utf8(config_guess)?), - &format!("--with-build-python={dir}/../build/{PYTHON_EXECUTABLE}",), - &format!("--prefix={dir}/install"), - "--disable-test-modules", - "--enable-ipv6", - ]))?; - - // Write Modules/Setup.local to force-enable _sqlite3 - // This ensures the module is built even if configure doesn't auto-detect it - write_setup_local(&cpython_wasi_dir)?; - - run(Command::new("make") - .current_dir(&cpython_wasi_dir) - .args(["build_all", "install"]))?; + if cpython_dir.exists() { + check_cpython_identity(&cpython_dir, &identity, &cpython_dir, &patch_dir)?; + } else { + let url = format!( + "https://www.python.org/ftp/python/{CPYTHON_VERSION}/Python-{CPYTHON_VERSION}.tgz" + ); + println!("cargo:warning=downloading CPython source code from {url}"); + // An interrupted build can leave a partly patched tree behind, which + // the patches would not apply to again. + let source_dir = repo_dir.join(format!("Python-{CPYTHON_VERSION}")); + if source_dir.exists() { + fs::remove_dir_all(&source_dir)?; + } + fetch_extract(&url, Some(CPYTHON_TARBALL_SHA256), repo_dir)?; + + for patch in &patches { + run(Command::new("patch") + .current_dir(&source_dir) + .arg("--batch") + .arg("--forward") + .arg("-p1") + .arg("-i") + .arg(patch))?; } - // Link libpython3.14.so - now includes libsqlite3.a - run(Command::new(wasi_sdk.join("bin/clang")) - .arg("--target=wasm32-wasip2") - .arg("-shared") - .arg("-o") - .arg(cpython_wasi_dir.join("libpython3.14.so")) - .arg("-Wl,--whole-archive") - .arg(cpython_wasi_dir.join("libpython3.14.a")) - .arg("-Wl,--no-whole-archive") - .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_HMAC.a")) - .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_BLAKE2.a")) - .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_MD5.a")) - .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_SHA1.a")) - .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_SHA2.a")) - .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_SHA3.a")) - .arg(cpython_wasi_dir.join("Modules/_decimal/libmpdec/libmpdec.a")) - .arg(cpython_wasi_dir.join("Modules/expat/libexpat.a")) - .arg(cpython_wasi_dir.join("deps/lib/libz.a")) - .arg(cpython_wasi_dir.join("deps/lib/libsqlite3.a")) - .arg("-lwasi-emulated-signal") - .arg("-lwasi-emulated-getpid") - .arg("-lwasi-emulated-process-clocks") - .arg("-ldl"))?; + fs::write(source_dir.join(CPYTHON_SOURCE_IDENTITY_FILE), &identity)?; + fs::rename(source_dir, &cpython_dir)?; } + fs::create_dir_all(&cpython_wasi_dir)?; + if !cpython_wasi_dir.join("libpython3.14.a").exists() { + let cpython_native_dir = repo_dir.join("cpython/builddir/build"); + if !cpython_native_dir.join(PYTHON_EXECUTABLE).exists() { + fs::create_dir_all(&cpython_native_dir)?; + + run(Command::new("../../configure") + .current_dir(&cpython_native_dir) + .arg(format!( + "--prefix={}/install", + cpython_native_dir.to_str().ok_or_else(|| anyhow!( + "non-UTF8 path: {}", + cpython_native_dir.display() + ))? + )))?; + + run(Command::new("make").current_dir(cpython_native_dir))?; + } + + let lib_install_dir = cpython_wasi_dir.join("deps"); + build_zlib(wasi_sdk, &lib_install_dir)?; + + build_sqlite(wasi_sdk, &lib_install_dir)?; + + let config_guess = run(Command::new("../../config.guess").current_dir(&cpython_wasi_dir))?; + + let dir = cpython_wasi_dir + .to_str() + .ok_or_else(|| anyhow!("non-UTF8 path: {}", cpython_wasi_dir.display()))?; + + // Configure CPython with SQLite support + // The CFLAGS and LDFLAGS now include paths to both zlib AND sqlite + run(Command::new("../../Tools/wasm/wasi-env") + .env( + "CONFIG_SITE", + "../../Tools/wasm/wasi/config.site-wasm32-wasi", + ) + .env( + "CFLAGS", + format!("--target=wasm32-wasip2 -fPIC -I{dir}/deps/include"), + ) + .env("WASI_SDK_PATH", wasi_sdk) + .env( + "LDFLAGS", + format!("--target=wasm32-wasip2 -L{dir}/deps/lib"), + ) + .current_dir(&cpython_wasi_dir) + .args([ + "../../configure", + "-C", + "--host=wasm32-unknown-wasip2", + &format!("--build={}", String::from_utf8(config_guess)?), + &format!("--with-build-python={dir}/../build/{PYTHON_EXECUTABLE}",), + &format!("--prefix={dir}/install"), + "--disable-test-modules", + "--enable-ipv6", + ]))?; + + // Write Modules/Setup.local to force-enable _sqlite3 + // This ensures the module is built even if configure doesn't auto-detect it + write_setup_local(&cpython_wasi_dir)?; + + run(Command::new("make") + .current_dir(&cpython_wasi_dir) + .args(["build_all", "install"]))?; + } + + // Link libpython3.14.so - now includes libsqlite3.a + run(Command::new(wasi_sdk.join("bin/clang")) + .arg("--target=wasm32-wasip2") + .arg("-shared") + .arg("-o") + .arg(cpython_wasi_dir.join("libpython3.14.so")) + .arg("-Wl,--whole-archive") + .arg(cpython_wasi_dir.join("libpython3.14.a")) + .arg("-Wl,--no-whole-archive") + .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_HMAC.a")) + .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_BLAKE2.a")) + .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_MD5.a")) + .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_SHA1.a")) + .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_SHA2.a")) + .arg(cpython_wasi_dir.join("Modules/_hacl/libHacl_Hash_SHA3.a")) + .arg(cpython_wasi_dir.join("Modules/_decimal/libmpdec/libmpdec.a")) + .arg(cpython_wasi_dir.join("Modules/expat/libexpat.a")) + .arg(cpython_wasi_dir.join("deps/lib/libz.a")) + .arg(cpython_wasi_dir.join("deps/lib/libsqlite3.a")) + .arg("-lwasi-emulated-signal") + .arg("-lwasi-emulated-getpid") + .arg("-lwasi-emulated-process-clocks") + .arg("-ldl"))?; + + fs::write( + cpython_wasi_dir.join(CPYTHON_SOURCE_IDENTITY_FILE), + &identity, + )?; + Ok(()) +} + +/// Fails unless `dir` names the CPython sources that `identity` describes. +fn check_cpython_identity( + dir: &Path, + identity: &str, + cpython_dir: &Path, + patch_dir: &Path, +) -> Result<()> { + let found = fs::read_to_string(dir.join(CPYTHON_SOURCE_IDENTITY_FILE)).ok(); + let found = found.as_deref().map(str::trim); + if found != Some(identity) { + bail!( + "{} was not made from CPython {CPYTHON_VERSION} with the patches in {} \ + (source identity {}, expected {identity}); delete {} to download, patch and \ + build CPython again", + dir.display(), + patch_dir.display(), + found.unwrap_or("missing"), + cpython_dir.display() + ); + } Ok(()) } +/// Returns the SHA-256 of the sources that go into `cpython/`: the CPython +/// tarball, the name and content of each patch in order, and the zlib and +/// SQLite tarballs that are built into `libpython3.14.so`. +fn cpython_source_identity(patches: &[PathBuf]) -> Result { + let mut hasher = Sha256::new(); + for part in [ + CPYTHON_VERSION, + CPYTHON_TARBALL_SHA256, + ZLIB_VERSION, + ZLIB_TARBALL_SHA256, + SQLITE_VERSION, + SQLITE_TARBALL_SHA256, + ] { + hasher.update(part.as_bytes()); + hasher.update([0]); + } + for patch in patches { + let name = patch + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| anyhow!("non-UTF8 path: {}", patch.display()))?; + // Git may check the patches out with CRLF line endings on Windows. + let content = String::from_utf8(fs::read(patch)?)?.replace("\r\n", "\n"); + hasher.update(name.as_bytes()); + hasher.update([0]); + hasher.update((content.len() as u64).to_le_bytes()); + hasher.update(&content); + } + Ok(hex::encode(hasher.finalize())) +} + /// Write Modules/Setup.local to enable _sqlite3 module /// /// CPython's configure may not auto-detect sqlite3 for WASI cross-compilation, @@ -575,9 +685,15 @@ fn make_runtime( Ok(()) } -fn fetch_extract(url: &str, out_dir: &Path) -> Result<()> { - let response = reqwest::blocking::get(url)?; - let decoder = flate2::read::GzDecoder::new(response); +fn fetch_extract(url: &str, sha256: Option<&str>, out_dir: &Path) -> Result<()> { + let bytes = reqwest::blocking::get(url)?.error_for_status()?.bytes()?; + if let Some(expected) = sha256 { + let actual = hex::encode(Sha256::digest(&bytes)); + if actual != expected { + bail!("{url} has SHA-256 {actual}, expected {expected}"); + } + } + let decoder = flate2::read::GzDecoder::new(Cursor::new(bytes)); let mut archive = tar::Archive::new(decoder); archive.unpack(out_dir)?; Ok(()) @@ -603,10 +719,13 @@ fn add_compile_envs(wasi_sdk: &Path, command: &mut Command) { fn build_zlib(wasi_sdk: &Path, install_dir: &Path) -> Result<()> { let out_dir = PathBuf::from(env::var("OUT_DIR")?); fetch_extract( - "https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz", + &format!( + "https://github.com/madler/zlib/releases/download/v{ZLIB_VERSION}/zlib-{ZLIB_VERSION}.tar.gz" + ), + Some(ZLIB_TARBALL_SHA256), &out_dir, )?; - let src_dir = out_dir.join("zlib-1.3.1"); + let src_dir = out_dir.join(format!("zlib-{ZLIB_VERSION}")); let prefix = install_dir .to_str() @@ -663,7 +782,7 @@ fn build_sqlite(wasi_sdk: &Path, install_dir: &Path) -> Result<()> { // Download SQLite amalgamation let url = format!("https://sqlite.org/{SQLITE_YEAR}/sqlite-autoconf-{SQLITE_VERSION}.tar.gz"); - fetch_extract(&url, &out_dir)?; + fetch_extract(&url, Some(SQLITE_TARBALL_SHA256), &out_dir)?; let src_dir = out_dir.join(format!("sqlite-autoconf-{SQLITE_VERSION}")); diff --git a/cpython-patches/0001-GH-142234-Allow-enable-wasm-dynamic-linking-under-WA.patch b/cpython-patches/0001-GH-142234-Allow-enable-wasm-dynamic-linking-under-WA.patch new file mode 100644 index 00000000..d16439d8 --- /dev/null +++ b/cpython-patches/0001-GH-142234-Allow-enable-wasm-dynamic-linking-under-WA.patch @@ -0,0 +1,64 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Brett Cannon +Date: Fri, 5 Dec 2025 15:27:16 -0800 +Subject: [PATCH 1/2] GH-142234: Allow `--enable-wasm-dynamic-linking` under + WASI (GH-142235) + +While CPython doesn't support `--enable-wasm-dynamic-linking`, external tools like componentize-py do and they have to patch around it. Since the flag is off by default, allowing the flag so external users can add/inject dynamic linking support seems acceptable. +--- + .../Build/2025-12-03-10-44-42.gh-issue-142234.i1kaFb.rst | 3 +++ + configure | 5 +++-- + configure.ac | 4 ++-- + 3 files changed, 8 insertions(+), 4 deletions(-) + create mode 100644 Misc/NEWS.d/next/Build/2025-12-03-10-44-42.gh-issue-142234.i1kaFb.rst + +diff --git a/Misc/NEWS.d/next/Build/2025-12-03-10-44-42.gh-issue-142234.i1kaFb.rst b/Misc/NEWS.d/next/Build/2025-12-03-10-44-42.gh-issue-142234.i1kaFb.rst +new file mode 100644 +index 0000000000..a586512fc0 +--- /dev/null ++++ b/Misc/NEWS.d/next/Build/2025-12-03-10-44-42.gh-issue-142234.i1kaFb.rst +@@ -0,0 +1,3 @@ ++Allow ``--enable-wasm-dynamic-linking`` for WASI. While CPython doesn't ++directly support it so external/downstream users do not have to patch in ++support for the flag. +diff --git a/configure b/configure +index 2a4b6fc96c..5afe2e09b0 100755 +--- a/configure ++++ b/configure +@@ -1821,7 +1821,8 @@ Optional Features: + no) + --enable-wasm-dynamic-linking + Enable dynamic linking support for WebAssembly +- (default is no) ++ (default is no); WASI requires an external dynamic ++ loader to handle imports + --enable-wasm-pthreads Enable pthread emulation for WebAssembly (default is + no) + --enable-shared enable building a shared Python library (default is +@@ -7403,7 +7404,7 @@ then : + Emscripten) : + ;; #( + WASI) : +- as_fn_error $? "WASI dynamic linking is not implemented yet." "$LINENO" 5 ;; #( ++ ;; #( + *) : + as_fn_error $? "--enable-wasm-dynamic-linking only applies to Emscripten and WASI" "$LINENO" 5 + ;; +diff --git a/configure.ac b/configure.ac +index f51935d881..f869a9e941 100644 +--- a/configure.ac ++++ b/configure.ac +@@ -1324,11 +1324,11 @@ dnl See https://emscripten.org/docs/compiling/Dynamic-Linking.html + AC_MSG_CHECKING([for --enable-wasm-dynamic-linking]) + AC_ARG_ENABLE([wasm-dynamic-linking], + [AS_HELP_STRING([--enable-wasm-dynamic-linking], +- [Enable dynamic linking support for WebAssembly (default is no)])], ++ [Enable dynamic linking support for WebAssembly (default is no); WASI requires an external dynamic loader to handle imports])], + [ + AS_CASE([$ac_sys_system], + [Emscripten], [], +- [WASI], [AC_MSG_ERROR([WASI dynamic linking is not implemented yet.])], ++ [WASI], [], + [AC_MSG_ERROR([--enable-wasm-dynamic-linking only applies to Emscripten and WASI])] + ) + ], [ diff --git a/cpython-patches/0002-use-sys-ioctl.h-in-socketmodule.c-on-WASI.patch b/cpython-patches/0002-use-sys-ioctl.h-in-socketmodule.c-on-WASI.patch new file mode 100644 index 00000000..871e5a5a --- /dev/null +++ b/cpython-patches/0002-use-sys-ioctl.h-in-socketmodule.c-on-WASI.patch @@ -0,0 +1,25 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Joel Dice +Date: Thu, 12 Feb 2026 10:21:16 -0700 +Subject: [PATCH 2/2] use `sys/ioctl.h` in `socketmodule.c` on WASI + +As of this writing, `wasi-libc` does not yet support `O_NONBLOCK` in its `fcntl` +implementation, but _does_ support `FIONBIO` in its `ioctl` implementation, so +we need to use the latter. +--- + Modules/socketmodule.c | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c +index b9dadaf6a8..4997518ac2 100644 +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -203,7 +203,7 @@ shutdown(how) -- shut down traffic in one or both directions\n\ + # define USE_GETHOSTBYNAME_LOCK + #endif + +-#if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__) ++#if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__) || defined(__wasi__) + # include + #endif + diff --git a/cpython-patches/0003-Bound-deallocation-chains-by-depth-on-WASI.patch b/cpython-patches/0003-Bound-deallocation-chains-by-depth-on-WASI.patch new file mode 100644 index 00000000..9712f6e0 --- /dev/null +++ b/cpython-patches/0003-Bound-deallocation-chains-by-depth-on-WASI.patch @@ -0,0 +1,81 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: David Biro +Date: Mon, 16 Nov 2026 21:48:30 +0000 +Subject: [PATCH] Bound deallocation chains by depth on WASI + +The trashcan defers a deallocation when the measured C stack margin is small, +but on WebAssembly that margin measures only the linear-memory stack. A chain +of list deallocations exhausts the engine's call stack long before. Count the +nested deallocations instead. +--- + Objects/object.c | 34 ++++++++++++++++++++++++++++++++++ + 1 file changed, 34 insertions(+) + +diff --git a/Objects/object.c b/Objects/object.c +index b0bfaf0a5c..47aae62ab4 100644 +--- a/Objects/object.c ++++ b/Objects/object.c +@@ -3067,6 +3067,17 @@ Py_ReprLeave(PyObject *obj) + + /* Trashcan support. */ + ++#ifdef __wasi__ ++/* On WebAssembly, C functions keep most of their state in the engine's own ++ call stack, which is separate from the linear-memory stack that ++ _Py_RecursionLimit_GetMargin() measures. A chain of deallocations can ++ therefore exhaust the engine's stack while the measured margin still looks ++ large. Deallocations nest strictly, so count them instead, and defer ++ deallocation once the chain is _PyWasi_DEALLOC_DEPTH deep. */ ++#define _PyWasi_DEALLOC_DEPTH 50 ++static int _PyWasi_dealloc_depth = 0; ++#endif ++ + /* Add op to the gcstate->trash_delete_later list. Called when the current + * call-stack depth gets large. op must be a gc'ed object, with refcount 0. + * Py_DECREF must already have been called on it. +@@ -3125,7 +3136,15 @@ _PyTrash_thread_destroy_chain(PyThreadState *tstate) + _Py_ForgetReference(op); + #endif + _PyReftracerTrack(op, PyRefTracer_DESTROY); ++#ifdef __wasi__ ++ /* Count this call too, so that a deallocation it starts cannot ++ unwind the chain again at the same depth. */ ++ _PyWasi_dealloc_depth++; ++#endif + (*dealloc)(op); ++#ifdef __wasi__ ++ _PyWasi_dealloc_depth--; ++#endif + } + } + +@@ -3195,6 +3214,15 @@ _Py_Dealloc(PyObject *op) + destructor dealloc = type->tp_dealloc; + PyThreadState *tstate = _PyThreadState_GET(); + intptr_t margin = _Py_RecursionLimit_GetMargin(tstate); ++#ifdef __wasi__ ++ if (_PyWasi_dealloc_depth >= _PyWasi_DEALLOC_DEPTH) { ++ margin = 0; ++ } ++ else if (_PyWasi_dealloc_depth >= _PyWasi_DEALLOC_DEPTH / 2 && margin >= 4) { ++ /* Too deep to unwind the deferred chain here. */ ++ margin = 3; ++ } ++#endif + if (margin < 2 && gc_flag) { + _PyTrash_thread_deposit_object(tstate, (PyObject *)op); + return; +@@ -3217,7 +3245,13 @@ _Py_Dealloc(PyObject *op) + _Py_ForgetReference(op); + #endif + _PyReftracerTrack(op, PyRefTracer_DESTROY); ++#ifdef __wasi__ ++ _PyWasi_dealloc_depth++; ++#endif + (*dealloc)(op); ++#ifdef __wasi__ ++ _PyWasi_dealloc_depth--; ++#endif + + #ifdef Py_DEBUG + // gh-89373: The tp_dealloc function must leave the current exception diff --git a/runtime/src/check.rs b/runtime/src/check.rs new file mode 100644 index 00000000..5f86c347 --- /dev/null +++ b/runtime/src/check.rs @@ -0,0 +1,311 @@ +//! Checks that a Python value can be lowered as a WIT type. +//! +//! The `Call` implementation lowers values with infallible methods, so a value +//! that does not match its WIT type would otherwise panic in the middle of +//! lowering. Checking the complete value first lets an import call raise a +//! Python exception before anything reaches the host, and lets an export report +//! which value is wrong. + +use { + super::{ERR_CONSTRUCTOR, OK_CONSTRUCTOR, OPTIONS, RECORDS, RESULTS, TUPLES, VARIANTS}, + crate::bindings::exports::exports::OptionKind, + num_bigint::BigUint, + pyo3::{ + Bound, PyAny, PyErr, PyResult, Python, + exceptions::{PyOverflowError, PyTypeError, PyValueError}, + intern, + types::{ + PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods, PyString, + PyStringMethods, PyTuple, PyTupleMethods, PyTypeMethods, + }, + }, + wit_dylib_ffi::Type, +}; + +/// Checks `value` against `ty`, naming the value `path` in any error. +pub fn check( + py: Python<'_>, + ty: Type, + value: &Bound<'_, PyAny>, + path: &mut String, +) -> PyResult<()> { + match ty { + Type::U8 => int::(value, "u8", path), + Type::U16 => int::(value, "u16", path), + Type::U32 => int::(value, "u32", path), + Type::U64 => int::(value, "u64", path), + Type::S8 => int::(value, "s8", path), + Type::S16 => int::(value, "s16", path), + Type::S32 => int::(value, "s32", path), + Type::S64 => int::(value, "s64", path), + Type::Bool => Ok(()), + Type::F32 | Type::F64 => number::(value, "float", "a float", path), + Type::Char => { + let s = value + .cast::() + .map_err(|_| type_error("char (str of length 1)", value, path))?; + if s.to_cow()?.chars().count() == 1 { + Ok(()) + } else { + Err(PyValueError::new_err(format!( + "{path}: expected char, got a str of length {}", + s.len()? + ))) + } + } + Type::String => { + let s = value + .cast::() + .map_err(|_| type_error("str", value, path))?; + // Lone surrogates cannot be encoded as UTF-8. + s.to_str().map(drop).map_err(|error| { + let wrapped = PyValueError::new_err(format!("{path}: {}", error.value(py))); + wrapped.set_cause(py, Some(error)); + wrapped + }) + } + Type::ErrorContext => Ok(()), + Type::Record(ty) => { + let record = &RECORDS.get().unwrap()[ty.index()]; + for (name, (_, field_ty)) in record.fields.iter().zip(ty.fields()) { + let field = value + .getattr(name.as_str()) + .map_err(|_| type_error(&format!("record `{}`", ty.name()), value, path))?; + nested(path, &format!(".{name}"), |path| { + check(py, field_ty, &field, path) + })?; + } + Ok(()) + } + Type::Own(_) | Type::Borrow(_) | Type::Future(_) | Type::Stream(_) => { + // Exported resources accept any object; imported handles must still + // be live. + let is_import = match ty { + Type::Own(ty) | Type::Borrow(ty) => ty.new().is_none(), + _ => true, + }; + if is_import { + let handle = value + .getattr(intern!(py, "handle")) + .and_then(|handle| handle.extract::()) + .map_err(|_| type_error("a resource handle", value, path))?; + if handle == 0 { + return Err(PyValueError::new_err(format!( + "{path}: the handle was already moved or dropped" + ))); + } + } + Ok(()) + } + Type::Tuple(ty) => { + let count = TUPLES.get().unwrap()[ty.index()].count; + let tuple = value + .cast::() + .map_err(|_| type_error(&format!("tuple of {count}"), value, path))?; + if tuple.len() != count { + return Err(PyValueError::new_err(format!( + "{path}: expected a tuple of {count}, got {}", + tuple.len() + ))); + } + for (index, element_ty) in ty.types().enumerate() { + let element = tuple.get_item(index)?; + nested(path, &format!("[{index}]"), |path| { + check(py, element_ty, &element, path) + })?; + } + Ok(()) + } + Type::Variant(ty) => { + let variant = &VARIANTS.get().unwrap()[ty.index()]; + let discriminant = variant + .types_to_discriminants + .bind(py) + .get_item(value.get_type())? + .ok_or_else(|| { + type_error(&format!("a case of variant `{}`", ty.name()), value, path) + })? + .extract::()?; + let (case_name, case_ty) = ty.cases().nth(discriminant).unwrap(); + match case_ty { + Some(case_ty) if variant.cases[discriminant].has_payload => { + let payload = value.getattr(intern!(py, "value"))?; + nested(path, &format!("<{case_name}>"), |path| { + check(py, case_ty, &payload, path) + }) + } + _ => Ok(()), + } + } + Type::Flags(_) => value + .getattr(intern!(py, "value")) + .and_then(|bits| bits.extract::()) + .map(drop) + .map_err(|_| type_error("flags", value, path)), + Type::Enum(ty) => { + let index = value + .getattr(intern!(py, "value")) + .and_then(|index| index.extract::()) + .map_err(|_| type_error(&format!("enum `{}`", ty.name()), value, path))?; + if index < ty.names().len() { + Ok(()) + } else { + Err(PyValueError::new_err(format!( + "{path}: {index} is not a case of enum `{}`", + ty.name() + ))) + } + } + Type::Option(ty) => { + if value.is_none() { + return Ok(()); + } + let payload = match OPTIONS.get().unwrap()[ty.index()] { + OptionKind::NonNesting => value.clone(), + OptionKind::Nesting => value + .getattr(intern!(py, "value")) + .map_err(|_| type_error("None or Some", value, path))?, + }; + nested(path, "?", |path| check(py, ty.ty(), &payload, path)) + } + Type::Result(ty) => { + let record = &RESULTS.get().unwrap()[ty.index()]; + let (name, payload_ty, has_payload) = if OK_CONSTRUCTOR + .get() + .unwrap() + .bind(py) + .eq(value.get_type())? + { + ("Ok", ty.ok(), record.has_ok) + } else if ERR_CONSTRUCTOR + .get() + .unwrap() + .bind(py) + .eq(value.get_type())? + { + ("Err", ty.err(), record.has_err) + } else { + return Err(type_error("Ok or Err", value, path)); + }; + match payload_ty { + Some(payload_ty) if has_payload => { + let payload = value.getattr(intern!(py, "value"))?; + nested(path, &format!("<{name}>"), |path| { + check(py, payload_ty, &payload, path) + }) + } + _ => Ok(()), + } + } + Type::List(ty) => { + let element_ty = ty.ty(); + if let Type::U8 | Type::S8 = element_ty { + return value + .cast::() + .map(drop) + .map_err(|_| type_error("bytes", value, path)); + } + let list = value + .cast::() + .map_err(|_| type_error("list", value, path))?; + for (index, element) in list.iter().enumerate() { + nested(path, &format!("[{index}]"), |path| { + check(py, element_ty, &element, path) + })?; + } + Ok(()) + } + Type::FixedLengthList(ty) => { + let list = value + .cast::() + .map_err(|_| type_error(&format!("list of {}", ty.len()), value, path))?; + if list.len() != ty.len() { + return Err(PyValueError::new_err(format!( + "{path}: expected a list of {}, got {}", + ty.len(), + list.len() + ))); + } + for (index, element) in list.iter().enumerate() { + nested(path, &format!("[{index}]"), |path| { + check(py, ty.ty(), &element, path) + })?; + } + Ok(()) + } + Type::Map(ty) => { + let dict = value + .cast::() + .map_err(|_| type_error("dict", value, path))?; + for (key, item) in dict.iter() { + let label = key.repr()?.to_string(); + nested(path, &format!("[{label}] key"), |path| { + check(py, ty.key_type(), &key, path) + })?; + nested(path, &format!("[{label}]"), |path| { + check(py, ty.value_type(), &item, path) + })?; + } + Ok(()) + } + Type::Alias(ty) => check(py, ty.ty(), value, path), + } +} + +fn int<'py, T: for<'a> pyo3::FromPyObject<'a, 'py>>( + value: &Bound<'py, PyAny>, + name: &str, + path: &str, +) -> PyResult<()> { + number::(value, name, name, path) +} + +/// Accepts what the lowering accepts: the extraction goes through +/// `__index__` for integers and `__float__` for floats, so `numpy.int64` and +/// other number types are valid, and only the error is translated. +fn number<'py, T: for<'a> pyo3::FromPyObject<'a, 'py>>( + value: &Bound<'py, PyAny>, + name: &str, + range: &str, + path: &str, +) -> PyResult<()> { + value.extract::().map(drop).map_err(|error| { + let error: PyErr = error.into(); + if error.is_instance_of::(value.py()) { + PyOverflowError::new_err(format!( + "{path}: {} is out of range for {range}", + repr(value) + )) + } else { + type_error(name, value, path) + } + }) +} + +fn nested( + path: &mut String, + suffix: &str, + f: impl FnOnce(&mut String) -> PyResult<()>, +) -> PyResult<()> { + let len = path.len(); + path.push_str(suffix); + let result = f(path); + path.truncate(len); + result +} + +fn type_error(expected: &str, value: &Bound<'_, PyAny>, path: &str) -> PyErr { + let actual = value + .get_type() + .name() + .map(|name| name.to_string()) + .unwrap_or_else(|_| "?".into()); + PyTypeError::new_err(format!("{path}: expected {expected}, got {actual}")) +} + +fn repr(value: &Bound<'_, PyAny>) -> String { + value + .repr() + .map(|repr| repr.to_string()) + .unwrap_or_else(|_| "?".into()) +} diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 94a27996..39b2faca 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -41,6 +41,8 @@ use { }, }; +mod check; + mod bindings { wit_bindgen::generate!({ world: "init", @@ -182,15 +184,22 @@ fn call_import<'a>( module: Bound<'a, PyModule>, index: u32, params: Vec>, -) -> Bound<'a, PyAny> { +) -> PyResult> { let py = module.py(); let func = WIT .get() .unwrap() .import_func(usize::try_from(index).unwrap()); + // Reject a value that does not match its WIT type before anything is + // lowered, so the host sees no call. + for (position, (ty, value)) in func.params().zip(¶ms).enumerate() { + let mut path = format!("argument {position} of `{}`", func.name()); + check::check(py, ty, value, &mut path)?; + } + let mut call = MyCall::new(params.into_iter().rev().map(|v| v.unbind()).collect()); - if func.is_async() { + Ok(if func.is_async() { #[cfg(feature = "async")] { if let Some(pending) = unsafe { func.call_import_async(&mut call) } { @@ -231,7 +240,20 @@ fn call_import<'a>( assert!(call.stack.len() < 2); call.stack.pop().unwrap_or(py.None()) } - .into_bound(py) + .into_bound(py)) +} + +/// Traps with a diagnostic when an export's result does not match its WIT +/// type. The handler already ran, so there is no Python caller to raise to. +fn check_export_result(py: Python<'_>, func: ExportFunction, result: Option<&Py>) { + if let (Some(ty), Some(result)) = (func.result(), result) { + let mut path = format!("result of `{}`", func.name()); + if let Err(error) = check::check(py, ty, result.bind(py), &mut path) { + let message = error.to_string(); + error.print(py); + panic!("invalid export result: {message}") + } + } } #[pyo3::pyfunction] @@ -503,6 +525,8 @@ mod async_ { release_borrows(py, *unsafe { Box::from_raw(borrows as *mut Vec) }); } + check_export_result(py, func, results.first()); + let mut call = MyCall::new(results); func.call_task_return(&mut call); } @@ -1313,6 +1337,8 @@ impl MyInterpreter { } }; + check_export_result(py, func, result.as_ref()); + if let Some(result) = result { cx.stack.push(result); } @@ -1372,11 +1398,22 @@ impl Interpreter for MyInterpreter { } } - fn resource_dtor(ty: wit::Resource, handle: usize) { - // We don't currently include a `drop` function as part of the abstract - // base class we generate for an exported resource, so there's nothing - // to do here. If/when that changes, we'll want to call `drop` here. - _ = (ty, handle); + fn resource_dtor(_ty: wit::Resource, handle: usize) { + // `exported_resource_to_canon` gave the handle table a strong reference + // to the Python object as its rep. The last handle is gone, so release + // that reference; the object is finalized once nothing else uses it. + Python::attach(|py| { + let value = unsafe { Bound::::from_owned_ptr(py, handle as _) }; + let name = intern!(py, "__componentize_py_handle"); + if value.hasattr(name).unwrap() { + value.delattr(name).unwrap(); + } + value + .getattr(intern!(py, "finalizer")) + .unwrap() + .call_method0(intern!(py, "detach")) + .unwrap(); + }) } } @@ -1968,20 +2005,12 @@ impl Call for MyCall<'_> { fn push_own(&mut self, ty: wit::Resource, handle: u32) { Python::attach(|py| { self.stack.push(if let Some(rep) = ty.rep() { - // exported resource type + // exported resource type: take the object back and drop the + // handle, whose destructor releases the handle table's + // reference to it. let rep = unsafe { rep(handle) }; let value = unsafe { Bound::::from_borrowed_ptr(py, rep as _) }; - - value - .delattr(intern!(py, "__componentize_py_handle")) - .unwrap(); - - value - .getattr(intern!(py, "finalizer")) - .unwrap() - .call_method0(intern!(py, "detach")) - .unwrap(); - + unsafe { ty.drop()(handle) }; value.unbind() } else { // imported resource type diff --git a/src/command.rs b/src/command.rs index 0d9e03c7..9a789951 100644 --- a/src/command.rs +++ b/src/command.rs @@ -205,6 +205,16 @@ pub struct Componentize { /// randomness is required. #[arg(short = 's', long)] pub stub_wasi: bool, + + /// Size in bytes of the linear-memory stack used by C code. + /// + /// CPython raises `RecursionError` when this stack is nearly full. The + /// Wasm runtime's own call stack is separate and is not visible to + /// CPython, so a smaller value makes deep C recursion raise + /// `RecursionError` before that call stack is exhausted. Defaults to the + /// linker's 1 MiB. + #[arg(long)] + pub stack_size: Option, } #[derive(clap::Args, Debug)] @@ -322,6 +332,7 @@ fn componentize(common: Common, componentize: Componentize) -> Result<()> { output_path: &componentize.output, add_to_linker: None, stub_wasi: componentize.stub_wasi, + stack_size: componentize.stack_size, import_interface_names: &common .import_interface_name .iter() @@ -587,6 +598,7 @@ class Bindings(bindings.WorldExports): module_worlds: vec![], output: out_dir.path().join("app.wasm"), stub_wasi: false, + stack_size: None, intersect_world: None, }; componentize(common, componentize_opts) @@ -704,6 +716,7 @@ world lib-world { module_worlds: vec![], output: dir.path().join("app.wasm"), stub_wasi: false, + stack_size: None, intersect_world: None, }, ) diff --git a/src/lib.rs b/src/lib.rs index dd3fe44c..2cee563a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ use { futures::future::FutureExt, indexmap::{IndexMap, IndexSet}, serde::Deserialize, + sha2::{Digest as _, Sha256}, std::{ borrow::Cow, collections::{HashMap, HashSet}, @@ -26,7 +27,7 @@ use { component::{Component, Instance, Linker, ResourceTable, ResourceType}, }, wasmtime_wasi::{ - FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, + Deterministic, FsPerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, p2::pipe::{MemoryInputPipe, MemoryOutputPipe}, }, wit_component::metadata, @@ -75,6 +76,52 @@ impl WasiView for Ctx { } } +/// The clock seen during pre-initialization. It starts at the Unix epoch and +/// advances one microsecond each time it is read, so nothing the application +/// saves depends on when it was built, and code waiting for time to pass still +/// finishes. +#[derive(Default)] +struct BuildClock(std::sync::atomic::AtomicU64); + +impl BuildClock { + fn tick(&self) -> u64 { + self.0.fetch_add(1000, std::sync::atomic::Ordering::Relaxed) + } +} + +impl wasmtime_wasi::HostWallClock for BuildClock { + fn resolution(&self) -> std::time::Duration { + std::time::Duration::from_micros(1) + } + + fn now(&self) -> std::time::Duration { + std::time::Duration::from_nanos(self.tick()) + } +} + +impl wasmtime_wasi::HostMonotonicClock for BuildClock { + fn resolution(&self) -> u64 { + 1000 + } + + fn now(&self) -> u64 { + self.tick() + } +} + +/// Sets the access and modification times of `path` and everything under it +/// to the Unix epoch. +fn set_build_mtimes(path: &Path) -> Result<()> { + if path.is_dir() { + for entry in fs::read_dir(path)? { + set_build_mtimes(&entry?.path())?; + } + } + // `FileTime::zero` is the platform epoch, which Windows cannot set. + let epoch = filetime::FileTime::from_unix_time(0, 0); + filetime::set_file_times(path, epoch, epoch).with_context(|| path.display().to_string()) +} + pub struct Library { name: String, module: Vec, @@ -410,6 +457,9 @@ pub struct ComponentGenerator<'a> { pub output_path: &'a Path, pub add_to_linker: AddToLinker<'a>, pub stub_wasi: bool, + /// Size in bytes of the linear-memory stack shared by C code, which + /// CPython's recursion guard measures. `None` keeps the linker default. + pub stack_size: Option, pub import_interface_names: &'a HashMap<&'a str, &'a str>, pub export_interface_names: &'a HashMap<&'a str, &'a str>, pub intersect_world: Option<&'a str>, @@ -816,7 +866,7 @@ impl ComponentGenerator<'_> { dl_openable: false, }); - let component = link::link_libraries(&libraries)?; + let component = link::link_libraries(&libraries, self.stack_size)?; let stubbed_component = if self.stub_wasi { stubwasi::link_stub_modules(libraries)? @@ -833,7 +883,36 @@ impl ComponentGenerator<'_> { let stdout = MemoryOutputPipe::new(10000); let stderr = MemoryOutputPipe::new(10000); + // Pre-initialization saves everything the application computes into + // the component, so derive its hash seed and random bytes from the + // linked component and the application's sources instead of from host + // entropy. Identical inputs then produce identical components, and + // applications that share the same libraries still get different + // values. The runtime reseeds `random` from the host before the first + // export call. + let digest = build_digest(&component, self.app_name, python_path)?; + let random_bytes = (0u32..1024) + .flat_map(|counter| { + Sha256::new() + .chain_update(digest) + .chain_update(counter.to_le_bytes()) + .finalize() + }) + .collect::>(); + let mut wasi = WasiCtxBuilder::new(); + wasi.secure_random(Deterministic::new(random_bytes.clone())) + .insecure_random(Deterministic::new(random_bytes)) + .insecure_random_seed(u128::from_le_bytes(digest[..16].try_into().unwrap())) + .env( + "PYTHONHASHSEED", + u32::from_le_bytes(digest[..4].try_into().unwrap()).to_string(), + ) + .wall_clock(BuildClock::default()) + .monotonic_clock(BuildClock::default()) + // Writing bytecode would change the source directories during the + // build and record the time of the write. + .env("PYTHONDONTWRITEBYTECODE", "1"); wasi.stdin(MemoryInputPipe::new(Bytes::new())) .stdout(stdout.clone()) .stderr(stderr.clone()) @@ -934,6 +1013,18 @@ impl ComponentGenerator<'_> { } } + // The guest's import system records directory modification times, so + // give the directories created for this build a fixed time. + for dir in [ + embedded_python_standard_lib.path(), + embedded_helper_utils.path(), + ] + .into_iter() + .chain(world_dir_mounts.iter().map(|(_, dir)| dir.path())) + { + set_build_mtimes(dir)?; + } + if DEBUG_PYTHON_BINDINGS { // Prevent temporary directories from being deleted: std::mem::forget(world_dir_mounts); @@ -1322,3 +1413,50 @@ fn is_wasip2_cli(interface_name: &str) -> bool { || interface_name.starts_with("wasi:sockets/")) && interface_name.contains("@0.2.") } + +/// Returns the SHA-256 of the linked component, the application name and the +/// relative path and content of every file in each Python path entry, in +/// sorted order. A symbolic link counts as its target path, not as the content +/// it points to. +fn build_digest(component: &[u8], app_name: &str, python_path: &[&str]) -> Result<[u8; 32]> { + fn update_tree(hasher: &mut Sha256, root: &Path, path: &Path) -> Result<()> { + let relative = path + .strip_prefix(root)? + .to_string_lossy() + .replace('\\', "/"); + hasher.update(relative.as_bytes()); + hasher.update([0]); + let metadata = fs::symlink_metadata(path)?; + if metadata.is_symlink() { + hasher.update(b"l"); + hasher.update(fs::read_link(path)?.to_string_lossy().as_bytes()); + hasher.update([0]); + } else if metadata.is_dir() { + hasher.update(b"d"); + let mut entries = fs::read_dir(path)? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>()?; + entries.sort(); + for entry in entries { + update_tree(hasher, root, &entry)?; + } + } else { + let content = fs::read(path)?; + hasher.update(b"f"); + hasher.update((content.len() as u64).to_le_bytes()); + hasher.update(&content); + } + Ok(()) + } + + let mut hasher = Sha256::new(); + hasher.update(Sha256::digest(component)); + hasher.update(app_name.as_bytes()); + hasher.update([0]); + for (index, entry) in python_path.iter().enumerate() { + hasher.update((index as u64).to_le_bytes()); + let root = fs::canonicalize(entry)?; + update_tree(&mut hasher, &root, &root)?; + } + Ok(hasher.finalize().into()) +} diff --git a/src/link.rs b/src/link.rs index 86793864..da7ae43b 100644 --- a/src/link.rs +++ b/src/link.rs @@ -4,9 +4,12 @@ use anyhow::Result; use crate::Library; -pub fn link_libraries(libraries: &[Library]) -> Result> { +pub fn link_libraries(libraries: &[Library], stack_size: Option) -> Result> { let mut linker = wit_component::Linker::default(); linker.use_built_in_libdl(true).encoder().validate(true); + if let Some(stack_size) = stack_size { + linker.stack_size(stack_size); + } for Library { name, diff --git a/src/prelink.rs b/src/prelink.rs index 3aac57af..d02b815b 100644 --- a/src/prelink.rs +++ b/src/prelink.rs @@ -57,7 +57,97 @@ pub fn embedded_helper_utils() -> Result { Ok(bundled) } -pub fn bundle_libraries(library_path: Vec<(&str, Vec)>) -> Result> { +/// Support libraries from the WASI SDK that extensions may depend on. Each is +/// linked only when a linked library names it in its `dylink.0` needed list. +fn toolchain_support_libraries() -> Result)>> { + Ok(vec![( + "libsetjmp.so", + zstd::decode_all(Cursor::new(include_bytes!(concat!( + env!("OUT_DIR"), + "/libsetjmp.so.zst" + ))))?, + )]) +} + +/// Returns the names in a module's `dylink.0` needed list. +fn needed_libraries(module: &[u8]) -> Result> { + let mut needed = Vec::new(); + for payload in wasmparser::Parser::new(0).parse_all(module) { + if let wasmparser::Payload::CustomSection(section) = payload? + && let wasmparser::KnownCustom::Dylink0(reader) = section.as_known() + { + for subsection in reader { + if let wasmparser::Dylink0Subsection::Needed(names) = subsection? { + needed.extend(names.into_iter().map(String::from)); + } + } + } + } + Ok(needed) +} + +/// Adds every support library that a linked library needs, directly or +/// through another support library. +/// +/// A support library is a shared library that is not a Python extension, such +/// as `libjpeg.so` shipped next to the extension using it. It is linked under +/// its file name, which is the name its dependents use, and is not visible to +/// `dlopen`. Support libraries that nothing needs are not linked, so they do +/// not change the component. A needed name that remains unresolved is reported +/// by the linker as a missing library. +fn add_support_libraries(libraries: &mut Vec, support: &[PathBuf]) -> Result<()> { + let mut candidates: IndexMap)>> = IndexMap::new(); + for path in support { + let name = path + .file_name() + .and_then(|name| name.to_str()) + .context("non-UTF-8 path")? + .to_owned(); + let module = fs::read(path).with_context(|| path.display().to_string())?; + candidates + .entry(name) + .or_default() + .push((path.display().to_string(), module)); + } + let toolchain = toolchain_support_libraries()?; + + let mut index = 0; + while index < libraries.len() { + for needed in needed_libraries(&libraries[index].module)? { + if libraries.iter().any(|library| library.name == needed) { + continue; + } + let module = if let Some(found) = candidates.get(&needed) { + let (first_path, first) = &found[0]; + if let Some((other_path, _)) = found.iter().find(|(_, module)| module != first) { + bail!( + "support library `{needed}` needed by `{}` has different contents at \ + {first_path} and {other_path}", + libraries[index].name + ); + } + first.clone() + } else if let Some((_, module)) = toolchain.iter().find(|(name, _)| *name == needed) { + module.clone() + } else { + continue; + }; + libraries.push(Library { + name: needed, + module, + dl_openable: false, + }); + } + index += 1; + } + + Ok(()) +} + +pub fn bundle_libraries( + library_path: Vec<(&str, Vec)>, + support: &[PathBuf], +) -> Result> { let mut libraries = vec![ Library { name: "libcomponentize_py_runtime_sync.so".into(), @@ -159,6 +249,8 @@ pub fn bundle_libraries(library_path: Vec<(&str, Vec)>) -> Result( ) -> Result<(ConfigsMatchedWorlds<'a>, Vec)> { let mut raw_configs: Vec> = Vec::new(); let mut library_path: Vec<(&str, Vec)> = Vec::with_capacity(python_path.len()); + let mut support = Vec::new(); for path in python_path { let mut libraries = Vec::new(); search_directory( Path::new(path), Path::new(path), &mut libraries, + &mut support, &mut raw_configs, &mut HashSet::new(), )?; library_path.push((*path, libraries)); } - let libraries = bundle_libraries(library_path)?; + let libraries = bundle_libraries(library_path, &support)?; // Validate the paths parsed from any componentize-py.toml files discovered // above and match them up with `module_worlds` entries. Note that we use @@ -234,12 +328,20 @@ fn search_directory( root: &Path, path: &Path, libraries: &mut Vec, + support: &mut Vec, configs: &mut Vec>, modules_seen: &mut HashSet, ) -> Result<()> { if path.is_dir() { for entry in fs::read_dir(path).with_context(|| path.display().to_string())? { - search_directory(root, &entry?.path(), libraries, configs, modules_seen)?; + search_directory( + root, + &entry?.path(), + libraries, + support, + configs, + modules_seen, + )?; } } else if let Some(name) = path.file_name().and_then(|name| name.to_str()) { if NATIVE_EXTENSION_SUFFIXES @@ -248,6 +350,8 @@ fn search_directory( && is_wasm_file(path) { libraries.push(path.to_owned()); + } else if name.ends_with(".so") && is_wasm_file(path) { + support.push(path.to_owned()); } else if name == "componentize-py.toml" { let root = root .canonicalize() diff --git a/src/python.rs b/src/python.rs index 39d98f1c..a3283140 100644 --- a/src/python.rs +++ b/src/python.rs @@ -18,7 +18,7 @@ use { #[allow(clippy::too_many_arguments)] #[pyo3::pyfunction] #[pyo3(name = "componentize")] -#[pyo3(signature = (wit_path, worlds, features, all_features, bindings_module, python_path, module_worlds, app_name, output_path, stub_wasi, import_interface_names, export_interface_names, full_names = None, intersect_world = None, world_module = None, registry_config = None, no_default_registries = false))] +#[pyo3(signature = (wit_path, worlds, features, all_features, bindings_module, python_path, module_worlds, app_name, output_path, stub_wasi, import_interface_names, export_interface_names, full_names = None, intersect_world = None, world_module = None, registry_config = None, no_default_registries = false, stack_size = None))] fn python_componentize( wit_path: Vec, worlds: Vec, @@ -37,6 +37,7 @@ fn python_componentize( world_module: Option<&str>, registry_config: Option, no_default_registries: bool, + stack_size: Option, ) -> PyResult<()> { let bindings_module = crate::resolve_deprecated( bindings_module.map(str::to_owned), @@ -65,6 +66,7 @@ fn python_componentize( output_path: &output_path, add_to_linker: None, stub_wasi, + stack_size, import_interface_names: &import_interface_names .iter() .map(|(a, b)| (a.as_ref(), b.as_ref())) diff --git a/src/test.rs b/src/test.rs index d5e88df4..12af50d2 100644 --- a/src/test.rs +++ b/src/test.rs @@ -82,6 +82,7 @@ async fn make_component( output_path: &tempdir.path().join("app.wasm"), add_to_linker, stub_wasi: false, + stack_size: None, import_interface_names: &HashMap::new(), export_interface_names: &HashMap::new(), intersect_world, diff --git a/src/test/python_source/app.py b/src/test/python_source/app.py index 71618735..bd831e50 100644 --- a/src/test/python_source/app.py +++ b/src/test/python_source/app.py @@ -209,6 +209,16 @@ async def write_host_thing(thing: host_thing_interface.HostThing, wrote = await tx2.write(thing) assert wrote +def expect_moved(call): + # The handle was given away by the previous call, so lowering it again + # must fail in the guest before the host sees a second call. + try: + call() + except ValueError as error: + assert "already moved or dropped" in str(error), error + else: + unreachable() + def unreachable() -> str: raise AssertionError @@ -275,23 +285,36 @@ def test_refcounts(self): for _ in range(5 * 1024): chunk = tests.get_bytes(1024 * 1024) - def trap_on_empty_resource(self, thing: imports.resource_alias1.Thing): + def lower_numbers(self) -> int: + # Lowering takes any object with __index__, as numpy integers have, + # so the check before it accepts them too. + class Index: + def __index__(self) -> int: + return 40 + + for value, error in ((2**32, OverflowError), ("40", TypeError), (40.5, TypeError)): + try: + simple_import_and_export.foo(value) + except error: + pass + else: + unreachable() + return simple_import_and_export.foo(Index()) + + def reject_moved_resource(self, thing: imports.resource_alias1.Thing): tests.take_thing(thing) - tests.take_thing(thing) # should trap since we already gave away `thing` - unreachable() - - def trap_on_empty_future(self): + expect_moved(lambda: tests.take_thing(thing)) + + def reject_moved_future(self): tx, rx = tests.unit_future(lambda: None) tests.take_future(rx) - tests.take_future(rx) # should trap since we already gave away `rx` - unreachable() - - def trap_on_empty_stream(self): + expect_moved(lambda: tests.take_future(rx)) + + def reject_moved_stream(self): tx, rx = tests.unit_stream() tests.take_stream(rx) - tests.take_stream(rx) # should trap since we already gave away `rx` - unreachable() - + expect_moved(lambda: tests.take_stream(rx)) + @foo_iface.guest class FooInterface(foo_exports.FooInterface): def test(self, s: str) -> str: diff --git a/src/test/tests.rs b/src/test/tests.rs index 09aefd04..ace66be4 100644 --- a/src/test/tests.rs +++ b/src/test/tests.rs @@ -1085,6 +1085,7 @@ fn componentize_app( output_path: &tempdir.join("app.wasm"), add_to_linker: None, stub_wasi: false, + stack_size: None, import_interface_names: &std::collections::HashMap::new(), export_interface_names: &std::collections::HashMap::new(), intersect_world: None, @@ -1246,7 +1247,15 @@ fn filesystem() -> Result<()> { } #[test] -fn trap_on_empty_resource() -> Result<()> { +fn lower_numbers() -> Result<()> { + TESTER.test(|world, store, runtime| { + assert_eq!(40 + 2, runtime.block_on(world.call_lower_numbers(store))?); + Ok(()) + }) +} + +#[test] +fn reject_moved_resource() -> Result<()> { TESTER.test(|world, store, runtime| { runtime.block_on(async { let thing = store @@ -1255,16 +1264,7 @@ fn trap_on_empty_resource() -> Result<()> { .table .push(ThingString("Ni Hao".to_string()))?; - let error = world - .call_trap_on_empty_resource(store, thing) - .await - .unwrap_err(); - - let expected = "unknown handle index 0"; - assert!( - format!("{error:?}").contains(expected), - "expected error message to contain `{expected}`; got {error:?}" - ); + world.call_reject_moved_resource(store, thing).await?; Ok(()) }) @@ -1272,36 +1272,16 @@ fn trap_on_empty_resource() -> Result<()> { } #[test] -fn trap_on_empty_future() -> Result<()> { +fn reject_moved_future() -> Result<()> { TESTER.test(|world, store, runtime| { - runtime.block_on(async { - let error = world.call_trap_on_empty_future(store).await.unwrap_err(); - - let expected = "unknown handle index 0"; - assert!( - format!("{error:?}").contains(expected), - "expected error message to contain `{expected}`; got {error:?}" - ); - - Ok(()) - }) + Ok(runtime.block_on(async { world.call_reject_moved_future(store).await })?) }) } #[test] -fn trap_on_empty_stream() -> Result<()> { +fn reject_moved_stream() -> Result<()> { TESTER.test(|world, store, runtime| { - runtime.block_on(async { - let error = world.call_trap_on_empty_stream(store).await.unwrap_err(); - - let expected = "unknown handle index 0"; - assert!( - format!("{error:?}").contains(expected), - "expected error message to contain `{expected}`; got {error:?}" - ); - - Ok(()) - }) + Ok(runtime.block_on(async { world.call_reject_moved_stream(store).await })?) }) } diff --git a/src/test/wit/tests.wit b/src/test/wit/tests.wit index 0ef3070a..4797391e 100644 --- a/src/test/wit/tests.wit +++ b/src/test/wit/tests.wit @@ -241,15 +241,17 @@ world tests { export test-refcounts: func(); - export trap-on-empty-resource: func(thing: thing); + export lower-numbers: func() -> u32; + + export reject-moved-resource: func(thing: thing); import take-thing: func(thing: thing); - export trap-on-empty-future: func(); + export reject-moved-future: func(); import take-future: func(v: future); - export trap-on-empty-stream: func(); + export reject-moved-stream: func(); import take-stream: func(v: stream);