From 6a7125266f2214d1ee06dacad5af50b5e533176e Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:09:53 +0000 Subject: [PATCH 01/14] Build CPython 3.14.10 from the python.org release Verify the CPython, zlib and SQLite source tarballs by SHA-256 and carry the WASI patches that 3.14.10 does not include in cpython-patches/. Update zlib to 1.3.2 and SQLite to 3.54.1. --- Cargo.lock | 1 + Cargo.toml | 2 + build.rs | 71 ++++++++++++++----- ...enable-wasm-dynamic-linking-under-WA.patch | 64 +++++++++++++++++ ...ys-ioctl.h-in-socketmodule.c-on-WASI.patch | 25 +++++++ 5 files changed, 145 insertions(+), 18 deletions(-) create mode 100644 cpython-patches/0001-GH-142234-Allow-enable-wasm-dynamic-linking-under-WA.patch create mode 100644 cpython-patches/0002-use-sys-ioctl.h-in-socketmodule.c-on-WASI.patch diff --git a/Cargo.lock b/Cargo.lock index 7504a1ed..2311b437 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -573,6 +573,7 @@ dependencies = [ "reqwest 0.12.28", "semver", "serde", + "sha2 0.10.9", "tar", "tempfile", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 8eb8120c..2c3f0dc4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,6 +82,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" diff --git a/build.rs b/build.rs index 5c2e65c6..1da10d2d 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,11 @@ 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"; fn main() -> Result<()> { println!("cargo:rerun-if-changed=build.rs"); @@ -154,7 +161,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) } @@ -307,13 +315,31 @@ 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"); + let patch_dir = repo_dir.join("cpython-patches"); + println!("cargo:rerun-if-changed={}", patch_dir.display()); 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()); + let url = format!( + "https://www.python.org/ftp/python/{CPYTHON_VERSION}/Python-{CPYTHON_VERSION}.tgz" + ); println!("cargo:warning=downloading CPython source code from {url}"); - fetch_extract(url, repo_dir)?; - fs::rename(repo_dir.join(base_dir), &cpython_dir)?; + fetch_extract(&url, Some(CPYTHON_TARBALL_SHA256), repo_dir)?; + let source_dir = repo_dir.join(format!("Python-{CPYTHON_VERSION}")); + + let mut patches = fs::read_dir(&patch_dir)? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>()?; + patches.sort(); + for patch in patches { + run(Command::new("patch") + .current_dir(&source_dir) + .arg("--batch") + .arg("--forward") + .arg("-p1") + .arg("-i") + .arg(&patch))?; + } + + fs::rename(source_dir, &cpython_dir)?; } let cpython_wasi_dir = cpython_dir.join("builddir/wasi"); @@ -575,9 +601,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 +635,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 +698,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 + From 311d5ae16f922cbcc260caeb39abd3eb00c94816 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:09:53 +0000 Subject: [PATCH 02/14] Count only written symbols in the dlopen table wit-component 0.258.3 counts a library's exports, including Wasm tags it does not write into the dlopen symbol table. A library exporting a tag, such as __c_longjmp from setjmp/longjmp support, then makes the loader read past its symbols. Carry wit-component with the one-line fix until it is released. --- Cargo.lock | 2 - Cargo.toml | 7 + vendor/wit-component/Cargo.toml | 225 + vendor/wit-component/LICENSE-APACHE | 201 + .../LICENSE-Apache-2.0_WITH_LLVM-exception | 220 + vendor/wit-component/LICENSE-MIT | 23 + vendor/wit-component/README.md | 251 ++ vendor/wit-component/libdl.so | Bin 0 -> 1358 bytes vendor/wit-component/src/dummy.rs | 457 ++ vendor/wit-component/src/encoding.rs | 3697 +++++++++++++++++ vendor/wit-component/src/encoding/dedupe.rs | 164 + vendor/wit-component/src/encoding/fixup.rs | 906 ++++ vendor/wit-component/src/encoding/types.rs | 538 +++ vendor/wit-component/src/encoding/wit.rs | 408 ++ vendor/wit-component/src/encoding/world.rs | 606 +++ vendor/wit-component/src/gc.rs | 1134 +++++ vendor/wit-component/src/lib.rs | 178 + vendor/wit-component/src/linking.rs | 1975 +++++++++ vendor/wit-component/src/linking/metadata.rs | 654 +++ vendor/wit-component/src/metadata.rs | 448 ++ vendor/wit-component/src/printing.rs | 1533 +++++++ vendor/wit-component/src/semver_check.rs | 113 + vendor/wit-component/src/targets.rs | 44 + vendor/wit-component/src/validation.rs | 2868 +++++++++++++ 24 files changed, 16650 insertions(+), 2 deletions(-) create mode 100644 vendor/wit-component/Cargo.toml create mode 100644 vendor/wit-component/LICENSE-APACHE create mode 100644 vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception create mode 100644 vendor/wit-component/LICENSE-MIT create mode 100644 vendor/wit-component/README.md create mode 100755 vendor/wit-component/libdl.so create mode 100644 vendor/wit-component/src/dummy.rs create mode 100644 vendor/wit-component/src/encoding.rs create mode 100644 vendor/wit-component/src/encoding/dedupe.rs create mode 100644 vendor/wit-component/src/encoding/fixup.rs create mode 100644 vendor/wit-component/src/encoding/types.rs create mode 100644 vendor/wit-component/src/encoding/wit.rs create mode 100644 vendor/wit-component/src/encoding/world.rs create mode 100644 vendor/wit-component/src/gc.rs create mode 100644 vendor/wit-component/src/lib.rs create mode 100644 vendor/wit-component/src/linking.rs create mode 100644 vendor/wit-component/src/linking/metadata.rs create mode 100644 vendor/wit-component/src/metadata.rs create mode 100644 vendor/wit-component/src/printing.rs create mode 100644 vendor/wit-component/src/semver_check.rs create mode 100644 vendor/wit-component/src/targets.rs create mode 100644 vendor/wit-component/src/validation.rs diff --git a/Cargo.lock b/Cargo.lock index 2311b437..b6676cad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4821,8 +4821,6 @@ dependencies = [ [[package]] name = "wit-component" version = "0.258.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0fca88950af0c1f42bc77e17315e48798b8d68340171b6d204f62bc19a878a6" dependencies = [ "anyhow", "bitflags", diff --git a/Cargo.toml b/Cargo.toml index 2c3f0dc4..f436c3d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -93,3 +93,10 @@ 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"] +exclude = ["vendor/wit-component"] + +# wit-component 0.258.3 from crates.io with 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. +[patch.crates-io] +wit-component = { path = "vendor/wit-component" } diff --git a/vendor/wit-component/Cargo.toml b/vendor/wit-component/Cargo.toml new file mode 100644 index 00000000..75a6ab0b --- /dev/null +++ b/vendor/wit-component/Cargo.toml @@ -0,0 +1,225 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.85.0" +name = "wit-component" +version = "0.258.3" +authors = ["Peter Huene "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = """ +Tooling for working with `*.wit` and component files together. +""" +homepage = "https://github.com/bytecodealliance/wasm-tools/tree/main/crates/wit-component" +documentation = "https://docs.rs/wit-component" +readme = "README.md" +license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" +repository = "https://github.com/bytecodealliance/wasm-tools/tree/main/crates/wit-component" + +[package.metadata.docs.rs] +all-features = true + +[features] +dummy-module = ["dep:wat"] +semver-check = ["dummy-module"] +wat = [ + "dep:wast", + "dep:wat", +] + +[lib] +name = "wit_component" +path = "src/lib.rs" + +[[test]] +name = "components" +path = "tests/components.rs" +harness = false + +[[test]] +name = "interfaces" +path = "tests/interfaces.rs" +harness = false + +[[test]] +name = "linking" +path = "tests/linking.rs" + +[[test]] +name = "merge" +path = "tests/merge.rs" + +[[test]] +name = "targets" +path = "tests/targets.rs" + +[[test]] +name = "wit" +path = "tests/wit.rs" + +[dependencies.anyhow] +version = "1.0.58" +default-features = false + +[dependencies.bitflags] +version = "2.3.3" + +[dependencies.indexmap] +version = "2.14.0" +features = ["std"] +default-features = false + +[dependencies.log] +version = "0.4.17" + +[dependencies.serde] +version = "1.0.166" +features = ["alloc"] +default-features = false + +[dependencies.serde_derive] +version = "1.0.166" + +[dependencies.serde_json] +version = "1" + +[dependencies.wasm-encoder] +version = "0.258.3" +features = [ + "std", + "wasmparser", +] +default-features = false + +[dependencies.wasm-metadata] +version = "0.258.3" +default-features = false + +[dependencies.wasmparser] +version = "0.258.3" +features = [ + "simd", + "std", + "component-model", + "simd", +] +default-features = false + +[dependencies.wast] +version = "258.0.3" +optional = true +default-features = false + +[dependencies.wat] +version = "1.258.3" +optional = true +default-features = false + +[dependencies.wit-parser] +version = "0.258.3" +features = [ + "decoding", + "serde", +] + +[dev-dependencies.env_logger] +version = "0.11" + +[dev-dependencies.glob] +version = "0.3.0" + +[dev-dependencies.libtest-mimic] +version = "0.8.1" + +[dev-dependencies.pretty_assertions] +version = "1.3.0" + +[dev-dependencies.toml] +version = "0.9.8" + +[dev-dependencies.wasm-metadata] +version = "0.258.3" +features = ["oci"] +default-features = false + +[dev-dependencies.wasmparser] +version = "0.258.3" +features = [ + "simd", + "std", + "component-model", + "features", +] +default-features = false + +[dev-dependencies.wasmprinter] +version = "0.258.3" +features = ["component-model"] +default-features = false + +[dev-dependencies.wat] +version = "1.258.3" +features = ["component-model"] +default-features = false + +[target.'cfg(not(target_family = "wasm"))'.dev-dependencies.wasmtime] +version = "36.0.7" +features = [ + "cranelift", + "component-model", + "runtime", + "gc-drc", +] +default-features = false + +[lints.clippy] +clone_on_copy = "warn" +manual_strip = "warn" +map_clone = "warn" +uninlined_format_args = "warn" +unnecessary_cast = "warn" +unnecessary_fallible_conversions = "warn" +unnecessary_mut_passed = "warn" +unnecessary_to_owned = "warn" + +[lints.clippy.all] +level = "allow" +priority = -1 + +[lints.rust] +deprecated_safe_2024 = "warn" +keyword_idents_2024 = "warn" +missing_unsafe_on_extern = "warn" +rust_2024_guarded_string_incompatible_syntax = "warn" +rust_2024_incompatible_pat = "warn" +rust_2024_prelude_collisions = "warn" +unsafe_attr_outside_unsafe = "warn" +unsafe_code = "deny" +unsafe_op_in_unsafe_fn = "warn" +unstable_features = "warn" +unused_extern_crates = "warn" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" + +[lints.rust.unexpected_cfgs] +level = "warn" +priority = 0 +check-cfg = [ + "cfg(fuzzing)", + "cfg(debug_check_try_op)", +] diff --git a/vendor/wit-component/LICENSE-APACHE b/vendor/wit-component/LICENSE-APACHE new file mode 100644 index 00000000..16fe87b0 --- /dev/null +++ b/vendor/wit-component/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception b/vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception new file mode 100644 index 00000000..f9d81955 --- /dev/null +++ b/vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception @@ -0,0 +1,220 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + diff --git a/vendor/wit-component/LICENSE-MIT b/vendor/wit-component/LICENSE-MIT new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/vendor/wit-component/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/vendor/wit-component/README.md b/vendor/wit-component/README.md new file mode 100644 index 00000000..2ba16c27 --- /dev/null +++ b/vendor/wit-component/README.md @@ -0,0 +1,251 @@ +# `wit-component` + +`wit-component` is a crate for creating and interacting with WebAssembly +components based on the [component model proposal][model]. + +## CLI usage + +The `wit-component` crate is available through the `wasm-tools` CLI suite under +two subcommands: + +``` +# Create a component from the input core wasm module +$ wasm-tools component new core.wasm -o component.wasm + +# Extract a `*.wit` interface from a component +$ wasm-tools component wit component.wasm +``` + +## Features + +* Creates WebAssembly [component binaries][model] from input core WebAssembly + modules. Input modules communicate with the [canonical ABI] to imported and + exported interfaces described with [`*.wit` files][wit]. The wit interface is + required to be embedded directly in the core wasm binary. + +* Supports "adapters" which can be used to bridge legacy core WebAssembly + imported functions into [component model][model] functions. Adapters are + themselves core wasm binaries which will be embedded into the final component. + An adapter's exports can be imported by the main core wasm binary and the + adapter can then call component model imports. + +* A [`*.wit`][wit] interface can be extracted from an existing component to + see the interface that it exports and intends to import. + +[model]: https://github.com/webassembly/component-model +[canonical ABI]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md +[wit]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md + +## Usage + +Note that this crate is intended to be a low-level detail of tooling for +components. Developers will not necessarily interact with this tooling +day-to-day, instead using wrappers such as +[`cargo-component`](https://github.com/bytecodealliance/cargo-component) which +will automatically execute `wit-component` to produce component binaries. + +First `wit-component` supports the wasm-based encoding of a WIT package: + +```sh +$ cat demo.wit +package my:demo; + +interface host { + hello: func(); +} + +world demo { + import host; +} + +$ wasm-tools component wit demo.wit -o demo.wasm --wasm + +# The output `demo.wasm` is a valid component binary +$ wasm-tools validate --features component-model demo.wasm +$ wasm-tools print demo.wasm + +# The `*.wit` file can be recovered from the `demo.wasm` as well +$ wasm-tools component wit demo.wasm +``` + +Toolchain authors can use `wit-component` to embed this component types section +into a core wasm binary. For a small demo here a raw `*.wat` wasm text file will +be used where the `demo.wit` argument is specified manually, however. + +```sh +$ cat demo.core.wat +(module + (import "my:demo/host" "hello" (func)) +) + +$ wasm-tools component embed demo.wit --world demo demo.core.wat -o demo.wasm + +# See that there's a new `component-type` custom section +$ wasm-tools objdump demo.wasm + +# Convert the core wasm into a component now +$ wasm-tools component new demo.wasm -o demo.component.wasm + +# Like before the output `demo.wasm` is a valid component binary +$ wasm-tools validate --features component-model demo.component.wasm +$ wasm-tools print demo.component.wasm + +# Additionally like before the `*.wit` interface can still be extracted +$ wasm-tools component wit demo.component.wasm +``` + +Here the `demo.component.wasm` can now be shipped to a component runtime or +embedded into hosts. + +## Custom Section Format + +Toolchains producing components typically have a workflow that looks something +like this: + +1. A bindings generator, often based on [`wit-bindgen`], is used to generate + source code. +2. A user writes source code against these bindings. +3. The language's compiler runs and produces a core WebAssembly module. +4. The core WebAssembly module is passed to this crate, producing a component. + +Steps (1) and (4) both take WIT as input and the goal is to make it such that +you don't have to specify the same WIT on both ends. Instead the WIT from (1) +should be seamlessly passed through to (4) without developers having to +explicitly opt-in to it otherwise. To do this, the `wit-component` crate and +componentization process uses a custom section. + +Part of the generated bindings from (1) above is source code (or similar) to +instruct the language to embed a custom section in the final binary. The custom +section's name must start with `component-type` but can have any number of +characters following it (e.g. it must match the regex `^component-type`). A +module is allowed to have any number of custom sections, including zero. + +Each custom section describes a WIT `world`. The unit of bindings generation is +a `world`, and each `world` used during step (1), which may possibly be in +multiple separate libraries, will be encoded into custom sections. Custom +sections typically have a name that includes the bindings generator, +the bindings generator's version, the world, and an optional use-provided +string. The contents of the custom section is a wasm-encoded WIT world. + +An example of this is that for this document: + +```wit +package a:b; + +world foo { + import host: func(); + export guest: func(); +} +``` + +this WIT world is encoded to wasm as: + +```wasm +(component + (type (;0;) + (component + (type (;0;) + (component + (type (;0;) (func)) + (import "host" (func (;0;) (type 0))) + (export (;1;) "guest" (func (type 0))) + ) + ) + (export (;0;) "a:b/foo" (component (type 0))) + ) + ) + (export (;1;) "foo" (type 0)) + (@custom "package-docs" "\00{}") + (@producers + (processed-by "wit-component" "0.218.0") + ) +) +``` + +More details about the wasm encoding of WIT can [be found +upstream](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md). + +Note here that the WIT world is just the single `component`-type export needed +to decode a single world, no other items are encoded into this wasm. + +When determining the `world` for a wasm component the componentization process +will read the input module, remove all sections that match `^component-type`, +extract the `world` that the type represents, and then "merge" all of the worlds +together. This merging process can fail if there are conflicts, but otherwise +duplicate imports are unified together. + +The final componentization process then understands the WIT `world` that's being +used and assumes that the component follows the naming scheme in +[`BuildTargets.md`](https://github.com/WebAssembly/component-model/pull/378) +upstream. (note that legacy names are also accepted at this time) + +## Merging Worlds + +Part of what `wit-component` does when creating a component is that it will +merge WIT `world`s from a number of sources. For example each custom section +above may have a world. For tools like `wasm-component-ld` worlds may also be +supplied on the command line. The final component, however, can only have one +set of imports and exports so a single `world` needs to be created from all +these input worlds. + +There are two workhorse methods for performing this merging process and both +live within the `wit-parser` crate: + +* [`wit_parser::Resolve::merge_worlds`] +* [`wit_parser::Resolve::merge_world_imports_based_on_semver`] + +The first is unconditionally used to merge all worlds together. Each custom +section, input argument, etc, are all merged with the +[`wit_parser::Resolve::merge_worlds`] method. This method may fail in certain +situations, primarily if there are duplicate exports specified in different +worlds (even if they're the same name they can't unify to one export as it's not +clear which export to pick). There are some other niche situations as well in +which the merging process can fail. + +Once all worlds are merged together with [`wit_parser::Resolve::merge_worlds`] +there is then an optional, but enabled by default, step to "trim" the world +down based on semver versions. This method is +[`wit_parser::Resolve::merge_world_imports_based_on_semver`] and is used to +change a world such as this: + +```wit +world { + import wasi:cli/environment@0.2.0; + import wasi:cli/environment@0.2.1; +} +``` + +into this + +```wit +world { + import wasi:cli/environment@0.2.1; +} +``` + +Notably imports are deduplicated based on their semver versions of interfaces. +The maximum version of the interface is always selected in the end. Only +interfaces which are semver compatible are deduplicated, for example this world +cannot be deduplicated further: + +```wit +world { + import wasi:cli/environment@0.2.0; + import wasi:cli/environment@0.3.0; +} +``` + +The main purpose for this deduplication is to enable internally within a +component various libraries and runtimes to evolve at a different pace with +respect to interface versions. By definition in WIT it should always be possible +to use a larger versions, so older imports are automatically "upgraded" to +newer imports in these situations. This ensures that, for example, only one +`wasi:io/poll/pollable` resource will be imported into the final component. If +two were imported there would be no way to actually functionally use the +resulting component. + +Note that this semver-deduplication process is enabled by default but can be +disabled through various options and flags in tooling. + +[`wit_parser::Resolve::merge_worlds`]: https://docs.rs/wit-parser/latest/wit_parser/struct.Resolve.html#method.merge_worlds +[`wit_parser::Resolve::merge_world_imports_based_on_semver`]: https://docs.rs/wit-parser/latest/wit_parser/struct.Resolve.html#method.merge_world_imports_based_on_semver diff --git a/vendor/wit-component/libdl.so b/vendor/wit-component/libdl.so new file mode 100755 index 0000000000000000000000000000000000000000..8e91fbfaeaa826df5de1f9cf90d0f92fe9c84439 GIT binary patch literal 1358 zcmZuxO>fjl5UsBE*We7y2?@=CwsYYWfrL1xC9)_i0%?_%5Eo}McEFCu9&9J8K>`D( z)r!L+R=dAp|H9t(XY6lT4!m~HBteQt?(QmAzgJbSduY}!1mT$m>8i}DlbyT5{X;Mj zkAz?5NAsPw7Pq}a(To02_Pv>i4ha(v21epPg)g(}%v)rOx>+#^W8F%Uyh`&Xn|I0a zX*KWix=Om)QJIM)k%<^5iQSPL&Du=%gL5mfL6?1A+cjlY*GPs@2(w;8!uWld8zUvve&^KU0n_B8 z2@78c?ze|!ED)?k5wXI`(aRzdyeoGV>%NG2Z!DD1lOh(19*rr~bYqPgv;KV`L*&3+ z0ABYYw)bmZ`#mNwMA)wh5lV#rvIy285%aG3f#d7j*T@-Q|CkJmNN$PHrij#NGEe}8 z4Vbeg_-h?%yiVk5vUtk5&MYWYP9%*F)krPQVoz}q`HGdVT;*%0E8;*qrdx_sfGG}? zPd@f3MT<(?hIm$Wlc-f4t3h>Xl`!LX>Pw@(wCXFd)&Yv#;jPFq`Iu!8yVqGV6ayFfcIDZ? z(NS(R)Bpz18%3m1M4~GW6xk{-6oC*{5k}K^)678;K34?fMiF3HMH~oiKp^fQD}*p0 zI93R}011p`Rk$kUzb`k8ad?#b3~~V~Knbum0!fGzei4GUDf}ez>J0ZeRrcDi)T>#A z+e{m?sylUDpH?a1Iv>@gx^UR5u8zyu%XV Vec { + let world = &resolve.worlds[world]; + let mut wat = String::new(); + wat.push_str("(module\n"); + for (name, import) in world.imports.iter() { + match import { + WorldItem::Function(func) => { + push_imported_func(&mut wat, resolve, None, func, mangling); + } + WorldItem::Interface { id: import, .. } => { + for (_, func) in resolve.interfaces[*import].functions.iter() { + push_imported_func(&mut wat, resolve, Some(name), func, mangling); + } + for (_, ty) in resolve.interfaces[*import].types.iter() { + push_imported_type_intrinsics(&mut wat, resolve, Some(name), *ty, mangling); + } + } + WorldItem::Type { id, .. } => { + push_imported_type_intrinsics(&mut wat, resolve, None, *id, mangling); + } + } + } + + if mangling.is_async() { + push_root_async_intrinsics(&mut wat); + } + + // Append any intrinsics which are imported but used in exported items + // (e.g. resources) + for (name, export) in world.exports.iter() { + match export { + WorldItem::Function(func) => { + push_exported_func_intrinsics(&mut wat, resolve, None, func, mangling); + } + WorldItem::Interface { id: export, .. } => { + for (_, func) in resolve.interfaces[*export].functions.iter() { + push_exported_func_intrinsics(&mut wat, resolve, Some(name), func, mangling); + } + for (_, ty) in resolve.interfaces[*export].types.iter() { + push_exported_type_intrinsics(&mut wat, resolve, Some(name), *ty, mangling); + } + } + WorldItem::Type { .. } => {} + } + } + + for (name, export) in world.exports.iter() { + match export { + WorldItem::Function(func) => { + push_func_export(&mut wat, resolve, None, func, mangling); + } + WorldItem::Interface { id: export, .. } => { + for (_, func) in resolve.interfaces[*export].functions.iter() { + push_func_export(&mut wat, resolve, Some(name), func, mangling); + } + for (_, ty) in resolve.interfaces[*export].types.iter() { + push_exported_resource_functions(&mut wat, resolve, name, *ty, mangling); + } + } + WorldItem::Type { .. } => {} + } + } + + let memory = resolve.wasm_export_name(mangling, WasmExport::Memory); + wat.push_str(&format!("(memory (export {memory:?}) 0)\n")); + let realloc = resolve.wasm_export_name(mangling, WasmExport::Realloc); + wat.push_str(&format!( + "(func (export {realloc:?}) (param i32 i32 i32 i32) (result i32) unreachable)\n" + )); + + let initialize = resolve.wasm_export_name(mangling, WasmExport::Initialize); + wat.push_str(&format!("(func (export {initialize:?}))")); + wat.push_str(")\n"); + + return wat::parse_str(&wat).unwrap(); +} + +fn push_imported_func( + wat: &mut String, + resolve: &Resolve, + interface: Option<&WorldKey>, + func: &Function, + mangling: ManglingAndAbi, +) { + let mangling = mangling.for_func(func); + let sig = resolve.wasm_signature(mangling.import_variant(), func); + + let (module, name) = resolve.wasm_import_name(mangling, WasmImport::Func { interface, func }); + wat.push_str(&format!("(import {module:?} {name:?} (func")); + push_tys(wat, "param", &sig.params); + push_tys(wat, "result", &sig.results); + wat.push_str("))\n"); + + if mangling.is_async() { + push_imported_future_and_stream_intrinsics(wat, resolve, mangling, false, interface, func); + } +} + +fn push_imported_type_intrinsics( + wat: &mut String, + resolve: &Resolve, + interface: Option<&WorldKey>, + resource: TypeId, + mangling: ManglingAndAbi, +) { + let ty = &resolve.types[resource]; + match ty.kind { + TypeDefKind::Resource => { + let (module, name) = resolve.wasm_import_name( + // Force using a sync ABI here at this time as support for async + // resource drop isn't implemented yet. + mangling.sync(), + WasmImport::ResourceIntrinsic { + interface, + resource, + intrinsic: ResourceIntrinsic::ImportedDrop, + }, + ); + wat.push_str(&format!("(import {module:?} {name:?} (func (param i32)))")); + + if mangling.is_async() { + // TODO: when wit-component supports async resource drop, + // implement it here too. + // let name = format!("[async-lower]{name}"); + // wat.push_str(&format!("(import {module:?} {name:?} (func (param i32)))")); + } + } + + // No other types with intrinsics at this time (futures/streams are + // relative to where they show up in function types. + _ => {} + } +} + +fn push_exported_func_intrinsics( + wat: &mut String, + resolve: &Resolve, + interface: Option<&WorldKey>, + func: &Function, + mangling: ManglingAndAbi, +) { + if !mangling.is_async() { + return; + } + + // For exported async functions, generate a `task.return` intrinsic. + let (module, name, sig) = func.task_return_import(resolve, interface, mangling.mangling()); + wat.push_str(&format!("(import {module:?} {name:?} (func")); + push_tys(wat, "param", &sig.params); + push_tys(wat, "result", &sig.results); + wat.push_str("))\n"); + + push_imported_future_and_stream_intrinsics(wat, resolve, mangling, true, interface, func); +} + +fn push_imported_future_and_stream_intrinsics( + wat: &mut String, + resolve: &Resolve, + mangling: ManglingAndAbi, + exported: bool, + interface: Option<&WorldKey>, + func: &Function, +) { + for id in func.find_futures_and_streams(resolve).into_iter() { + match &resolve.types[id].kind { + TypeDefKind::Future(_) => { + let mut module = None; + let mut intrinsic_name = |intrinsic, async_| { + let (m, name) = resolve.wasm_import_name( + mangling, + WasmImport::FutureIntrinsic { + interface, + func, + ty: Some(id), + intrinsic, + exported, + async_, + }, + ); + if let Some(prev) = &module { + debug_assert_eq!(prev, &m); + } else { + module = Some(m); + } + name + }; + + let new = intrinsic_name(FutureIntrinsic::New, false); + let read = intrinsic_name(FutureIntrinsic::Read, false); + let write = intrinsic_name(FutureIntrinsic::Write, false); + let cancel_read = intrinsic_name(FutureIntrinsic::CancelRead, false); + let cancel_write = intrinsic_name(FutureIntrinsic::CancelWrite, false); + let drop_readable = intrinsic_name(FutureIntrinsic::DropReadable, false); + let drop_writable = intrinsic_name(FutureIntrinsic::DropWritable, false); + let async_read = intrinsic_name(FutureIntrinsic::Read, true); + let async_write = intrinsic_name(FutureIntrinsic::Write, true); + let async_cancel_read = intrinsic_name(FutureIntrinsic::CancelRead, true); + let async_cancel_write = intrinsic_name(FutureIntrinsic::CancelWrite, true); + let module = module.unwrap(); + + wat.push_str(&format!( + r#" +(import {module:?} {new:?} (func (result i64))) +(import {module:?} {cancel_read:?} (func (param i32) (result i32))) +(import {module:?} {cancel_write:?} (func (param i32) (result i32))) +(import {module:?} {drop_readable:?} (func (param i32))) +(import {module:?} {drop_writable:?} (func (param i32))) +(import {module:?} {async_read:?} (func (param i32 i32) (result i32))) +(import {module:?} {async_write:?} (func (param i32 i32) (result i32))) + +;; deferred behind 🚝 +;;(import {module:?} {read:?} (func (param i32 i32) (result i32))) +;;(import {module:?} {write:?} (func (param i32 i32) (result i32))) +;;(import {module:?} {async_cancel_read:?} (func (param i32) (result i32))) +;;(import {module:?} {async_cancel_write:?} (func (param i32) (result i32))) +"# + )); + } + TypeDefKind::Stream(_) => { + let mut module = None; + let mut intrinsic_name = |intrinsic, async_| { + let (m, name) = resolve.wasm_import_name( + mangling, + WasmImport::StreamIntrinsic { + interface, + func, + ty: Some(id), + intrinsic, + exported, + async_, + }, + ); + if let Some(prev) = &module { + debug_assert_eq!(prev, &m); + } else { + module = Some(m); + } + name + }; + + let new = intrinsic_name(StreamIntrinsic::New, false); + let read = intrinsic_name(StreamIntrinsic::Read, false); + let write = intrinsic_name(StreamIntrinsic::Write, false); + let cancel_read = intrinsic_name(StreamIntrinsic::CancelRead, false); + let cancel_write = intrinsic_name(StreamIntrinsic::CancelWrite, false); + let drop_readable = intrinsic_name(StreamIntrinsic::DropReadable, false); + let drop_writable = intrinsic_name(StreamIntrinsic::DropWritable, false); + let async_read = intrinsic_name(StreamIntrinsic::Read, true); + let async_write = intrinsic_name(StreamIntrinsic::Write, true); + let async_cancel_read = intrinsic_name(StreamIntrinsic::CancelRead, true); + let async_cancel_write = intrinsic_name(StreamIntrinsic::CancelWrite, true); + let module = module.unwrap(); + + wat.push_str(&format!( + r#" +(import {module:?} {new:?} (func (result i64))) +(import {module:?} {cancel_read:?} (func (param i32) (result i32))) +(import {module:?} {cancel_write:?} (func (param i32) (result i32))) +(import {module:?} {drop_readable:?} (func (param i32))) +(import {module:?} {drop_writable:?} (func (param i32))) +(import {module:?} {async_read:?} (func (param i32 i32 i32) (result i32))) +(import {module:?} {async_write:?} (func (param i32 i32 i32) (result i32))) + +;; deferred behind 🚝 +;;(import {module:?} {read:?} (func (param i32 i32 i32) (result i32))) +;;(import {module:?} {write:?} (func (param i32 i32 i32) (result i32))) +;;(import {module:?} {async_cancel_read:?} (func (param i32) (result i32))) +;;(import {module:?} {async_cancel_write:?} (func (param i32) (result i32))) +"# + )); + } + _ => unreachable!(), + } + } +} + +fn push_exported_type_intrinsics( + wat: &mut String, + resolve: &Resolve, + interface: Option<&WorldKey>, + resource: TypeId, + mangling: ManglingAndAbi, +) { + let ty = &resolve.types[resource]; + match ty.kind { + TypeDefKind::Resource => { + let intrinsics = [ + (ResourceIntrinsic::ExportedDrop, "(func (param i32))"), + ( + ResourceIntrinsic::ExportedNew, + "(func (param i32) (result i32))", + ), + ( + ResourceIntrinsic::ExportedRep, + "(func (param i32) (result i32))", + ), + ]; + for (intrinsic, sig) in intrinsics { + let (module, name) = resolve.wasm_import_name( + mangling.sync(), + WasmImport::ResourceIntrinsic { + interface, + resource, + intrinsic, + }, + ); + wat.push_str(&format!("(import {module:?} {name:?} {sig})\n")); + } + } + + // No other types with intrinsics at this time (futures/streams + // relative to where they are in a function). + _ => {} + } +} + +fn push_exported_resource_functions( + wat: &mut String, + resolve: &Resolve, + interface: &WorldKey, + resource: TypeId, + mangling: ManglingAndAbi, +) { + let ty = &resolve.types[resource]; + match ty.kind { + TypeDefKind::Resource => {} + _ => return, + } + // Feign destructors for any resource that this interface + // exports + let name = resolve.wasm_export_name( + mangling, + WasmExport::ResourceDtor { + interface, + resource, + }, + ); + wat.push_str(&format!("(func (export {name:?}) (param i32))")); +} + +fn push_func_export( + wat: &mut String, + resolve: &Resolve, + interface: Option<&WorldKey>, + func: &Function, + mangling: ManglingAndAbi, +) { + let mangling = mangling.for_func(func); + let sig = resolve.wasm_signature(mangling.export_variant(), func); + let name = resolve.wasm_export_name( + mangling, + WasmExport::Func { + interface, + func, + kind: WasmExportKind::Normal, + }, + ); + wat.push_str(&format!("(func (export \"{name}\")")); + push_tys(wat, "param", &sig.params); + push_tys(wat, "result", &sig.results); + wat.push_str(" unreachable)\n"); + + match mangling { + ManglingAndAbi::Standard32 | ManglingAndAbi::Legacy(LiftLowerAbi::Sync) => { + let name = resolve.wasm_export_name( + mangling, + WasmExport::Func { + interface, + func, + kind: WasmExportKind::PostReturn, + }, + ); + wat.push_str(&format!("(func (export \"{name}\")")); + push_tys(wat, "param", &sig.results); + wat.push_str(")\n"); + } + ManglingAndAbi::Legacy(LiftLowerAbi::AsyncCallback) => { + let name = resolve.wasm_export_name( + mangling, + WasmExport::Func { + interface, + func, + kind: WasmExportKind::Callback, + }, + ); + wat.push_str(&format!( + "(func (export \"{name}\") (param i32 i32 i32) (result i32) unreachable)\n" + )); + } + ManglingAndAbi::Legacy(LiftLowerAbi::AsyncStackful) => {} + } +} + +fn push_tys(dst: &mut String, desc: &str, params: &[WasmType]) { + if params.is_empty() { + return; + } + dst.push_str(" ("); + dst.push_str(desc); + for ty in params { + dst.push(' '); + match ty { + WasmType::I32 => dst.push_str("i32"), + WasmType::I64 => dst.push_str("i64"), + WasmType::F32 => dst.push_str("f32"), + WasmType::F64 => dst.push_str("f64"), + WasmType::Pointer => dst.push_str("i32"), + WasmType::PointerOrI64 => dst.push_str("i64"), + WasmType::Length => dst.push_str("i32"), + } + } + dst.push(')'); +} + +fn push_root_async_intrinsics(dst: &mut String) { + dst.push_str( + r#" +(import "[export]$root" "[task-cancel]" (func)) +(import "$root" "[backpressure-inc]" (func)) +(import "$root" "[backpressure-dec]" (func)) +(import "$root" "[waitable-set-new]" (func (result i32))) +(import "$root" "[waitable-set-wait]" (func (param i32 i32) (result i32))) +(import "$root" "[waitable-set-poll]" (func (param i32 i32) (result i32))) +(import "$root" "[waitable-set-drop]" (func (param i32))) +(import "$root" "[waitable-join]" (func (param i32 i32))) +(import "$root" "[thread-yield]" (func (result i32))) +(import "$root" "[subtask-drop]" (func (param i32))) +(import "$root" "[subtask-cancel]" (func (param i32) (result i32))) +(import "$root" "[context-get-0]" (func (result i32))) +(import "$root" "[context-set-0]" (func (param i32))) + +;; deferred behind 🧵 upstream +;;(import "$root" "[cancellable][waitable-set-wait]" (func (param i32 i32) (result i32))) +;;(import "$root" "[cancellable][waitable-set-poll]" (func (param i32 i32) (result i32))) +;;(import "$root" "[cancellable][thread-yield]" (func (result i32))) +;;(import "$root" "[context-get-1]" (func (result i32))) +;;(import "$root" "[context-set-1]" (func (param i32))) + +;; deferred behind 📝 upstream +;;(import "$root" "[error-context-new-utf8]" (func (param i32 i32) (result i32))) +;;(import "$root" "[error-context-new-utf16]" (func (param i32 i32) (result i32))) +;;(import "$root" "[error-context-new-latin1+utf16]" (func (param i32 i32) (result i32))) +;;(import "$root" "[error-context-debug-message-utf8]" (func (param i32 i32))) +;;(import "$root" "[error-context-debug-message-utf16]" (func (param i32 i32))) +;;(import "$root" "[error-context-debug-message-latin1+utf16]" (func (param i32 i32))) +;;(import "$root" "[error-context-drop]" (func (param i32))) +"#, + ); +} diff --git a/vendor/wit-component/src/encoding.rs b/vendor/wit-component/src/encoding.rs new file mode 100644 index 00000000..b5c08a04 --- /dev/null +++ b/vendor/wit-component/src/encoding.rs @@ -0,0 +1,3697 @@ +//! Support for encoding a core wasm module into a component. +//! +//! This module, at a high level, is tasked with transforming a core wasm +//! module into a component. This will process the imports/exports of the core +//! wasm module and translate between the `wit-parser` AST and the component +//! model binary format, producing a final component which will import +//! `*.wit` defined interfaces and export `*.wit` defined interfaces as well +//! with everything wired up internally according to the canonical ABI and such. +//! +//! This doc block here is not currently 100% complete and doesn't cover the +//! full functionality of this module. +//! +//! # Adapter Modules +//! +//! One feature of this encoding process which is non-obvious is the support for +//! "adapter modules". The general idea here is that historical host API +//! definitions have been around for quite some time, such as +//! `wasi_snapshot_preview1`, but these host API definitions are not compatible +//! with the canonical ABI or component model exactly. These APIs, however, can +//! in most situations be roughly adapted to component-model equivalents. This +//! is where adapter modules come into play, they're converting from some +//! arbitrary API/ABI into a component-model using API. +//! +//! An adapter module is a separately compiled `*.wasm` blob which will export +//! functions matching the desired ABI (e.g. exporting functions matching the +//! `wasi_snapshot_preview1` ABI). The `*.wasm` blob will then import functions +//! in the canonical ABI and internally adapt the exported functions to the +//! imported functions. The encoding support in this module is what wires +//! everything up and makes sure that everything is imported and exported to the +//! right place. Adapter modules currently always use "indirect lowerings" +//! meaning that a shim module is created and provided as the imports to the +//! main core wasm module, and the shim module is "filled in" at a later time +//! during the instantiation process. +//! +//! Adapter modules are not intended to be general purpose and are currently +//! very restrictive, namely: +//! +//! * They must import a linear memory and not define their own linear memory +//! otherwise. In other words they import memory and cannot use multi-memory. +//! * They cannot define any `elem` or `data` segments since otherwise there's +//! no knowledge ahead-of-time of where their data or element segments could +//! go. This means things like no panics, no indirect calls, etc. +//! * If the adapter uses a shadow stack, the global that points to it must be a +//! mutable `i32` named `__stack_pointer`. This stack is automatically +//! allocated with an injected `allocate_stack` function that will either use +//! the main module's `cabi_realloc` export (if present) or `memory.grow`. It +//! allocates only 64KB of stack space, and there is no protection if that +//! overflows. +//! * If the adapter has a global, mutable `i32` named `allocation_state`, it +//! will be used to keep track of stack allocation status and avoid infinite +//! recursion if the main module's `cabi_realloc` function calls back into the +//! adapter. `allocate_stack` will check this global on entry; if it is zero, +//! it will set it to one, then allocate the stack, and finally set it to two. +//! If it is non-zero, `allocate_stack` will do nothing and return immediately +//! (because either the stack has already been allocated or is in the process +//! of being allocated). If the adapter does not have an `allocation_state`, +//! `allocate_stack` will use `memory.grow` to allocate the stack; it will +//! _not_ use the main module's `cabi_realloc` even if it's available. +//! * If the adapter imports a `cabi_realloc` function, and the main module +//! exports one, they'll be linked together via an alias. If the adapter +//! imports such a function but the main module does _not_ export one, we'll +//! synthesize one based on `memory.grow` (which will trap for any size other +//! than 64KB). Note that the main module's `cabi_realloc` function may call +//! back into the adapter before the shadow stack has been allocated. In this +//! case (when `allocation_state` is zero or one), the adapter should return +//! whatever dummy value(s) it can immediately without touching the stack. +//! +//! This means that adapter modules are not meant to be written by everyone. +//! It's assumed that these will be relatively few and far between yet still a +//! crucial part of the transition process from to the component model since +//! otherwise there's no way to run a `wasi_snapshot_preview1` module within the +//! component model. + +use crate::StringEncoding; +use crate::metadata::{self, Bindgen, ModuleMetadata}; +use crate::validation::{ + Export, ExportMap, Import, ImportInstance, ImportMap, PayloadInfo, PayloadType, +}; +use anyhow::{Context, Result, anyhow, bail}; +use indexmap::{IndexMap, IndexSet}; +use std::borrow::Cow; +use std::collections::HashMap; +use std::hash::Hash; +use std::mem; +use wasm_encoder::reencode::{Reencode, RoundtripReencoder}; +use wasm_encoder::*; +use wasmparser::{Validator, WasmFeatures}; +use wit_parser::{ + Function, FunctionKind, InterfaceId, LiveTypes, Param, Resolve, Stability, Type, TypeDefKind, + TypeId, TypeOwner, WorldItem, WorldKey, + abi::{AbiVariant, WasmSignature, WasmType}, +}; + +const INDIRECT_TABLE_NAME: &str = "$imports"; +const SHIM_MEMORY_NAME: &str = "$memory"; +const TLS_BASE_GET: &str = "$get-tls-base"; +const TLS_BASE_SET: &str = "$set-tls-base"; + +pub(crate) mod fixup; + +mod wit; +pub use wit::{encode, encode_world}; + +mod types; +use types::{InstanceTypeEncoder, RootTypeEncoder, TypeEncodingMaps, ValtypeEncoder}; +mod world; +use world::{ComponentWorld, ImportedInterface, Lowering}; + +mod dedupe; +pub(crate) use dedupe::ModuleImportMap; +use wasm_metadata::AddMetadataField; + +fn to_val_type(ty: &WasmType) -> ValType { + match ty { + WasmType::I32 => ValType::I32, + WasmType::I64 => ValType::I64, + WasmType::F32 => ValType::F32, + WasmType::F64 => ValType::F64, + WasmType::Pointer => ValType::I32, + WasmType::PointerOrI64 => ValType::I64, + WasmType::Length => ValType::I32, + } +} + +fn import_func_name(f: &Function) -> String { + match f.kind { + FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => { + format!("import-func-{}", f.item_name()) + } + + // transform `[method]foo.bar` into `import-method-foo-bar` to + // have it be a valid kebab-name which can't conflict with + // anything else. + // + // There's probably a better and more "formal" way to do this + // but quick-and-dirty string manipulation should work well + // enough for now hopefully. + FunctionKind::Method(_) + | FunctionKind::AsyncMethod(_) + | FunctionKind::Static(_) + | FunctionKind::AsyncStatic(_) + | FunctionKind::Constructor(_) => { + format!( + "import-{}", + f.name.replace('[', "").replace([']', '.', ' '], "-") + ) + } + } +} + +bitflags::bitflags! { + /// Options in the `canon lower` or `canon lift` required for a particular + /// function. + #[derive(Copy, Clone, Debug)] + pub struct RequiredOptions: u8 { + /// A memory must be specified, typically the "main module"'s memory + /// export. + const MEMORY = 1 << 0; + /// A `realloc` function must be specified, typically named + /// `cabi_realloc`. + const REALLOC = 1 << 1; + /// A string encoding must be specified, which is always utf-8 for now + /// today. + const STRING_ENCODING = 1 << 2; + const ASYNC = 1 << 3; + } +} + +impl RequiredOptions { + fn for_import(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions { + let sig = resolve.wasm_signature(abi, func); + let mut ret = RequiredOptions::empty(); + // Lift the params and lower the results for imports + ret.add_lift(TypeContents::for_types( + resolve, + func.params.iter().map(|p| &p.ty), + )); + ret.add_lower(TypeContents::for_types(resolve, &func.result)); + + // If anything is indirect then `memory` will be required to read the + // indirect values. + if sig.retptr || sig.indirect_params { + ret |= RequiredOptions::MEMORY; + } + if abi == AbiVariant::GuestImportAsync { + ret |= RequiredOptions::ASYNC; + } + ret + } + + fn for_export(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions { + let sig = resolve.wasm_signature(abi, func); + let mut ret = RequiredOptions::empty(); + // Lower the params and lift the results for exports + ret.add_lower(TypeContents::for_types( + resolve, + func.params.iter().map(|p| &p.ty), + )); + ret.add_lift(TypeContents::for_types(resolve, &func.result)); + + // If anything is indirect then `memory` will be required to read the + // indirect values, but if the arguments are indirect then `realloc` is + // additionally required to allocate space for the parameters. + if sig.retptr || sig.indirect_params { + ret |= RequiredOptions::MEMORY; + if sig.indirect_params { + ret |= RequiredOptions::REALLOC; + } + } + if let AbiVariant::GuestExportAsync | AbiVariant::GuestExportAsyncStackful = abi { + ret |= RequiredOptions::ASYNC; + ret |= task_return_options_and_type(resolve, func).0; + } + ret + } + + fn for_payload( + resolve: &Resolve, + info: &PayloadInfo, + kind: &PayloadFuncKind, + async_: bool, + ) -> RequiredOptions { + let payload = info.payload(resolve); + let (wit_param, wit_result) = match kind { + PayloadFuncKind::StreamRead | PayloadFuncKind::FutureRead => (None, payload), + PayloadFuncKind::StreamWrite | PayloadFuncKind::FutureWrite => (payload, None), + }; + RequiredOptions::MEMORY + | RequiredOptions::for_import( + resolve, + &Function { + name: String::new(), + kind: FunctionKind::Freestanding, + params: match wit_param { + Some(ty) => vec![Param { + name: "a".to_string(), + ty, + span: Default::default(), + }], + None => Vec::new(), + }, + result: wit_result, + docs: Default::default(), + stability: Stability::Unknown, + span: Default::default(), + external_id: None, + }, + if async_ { + AbiVariant::GuestImportAsync + } else { + AbiVariant::GuestImport + }, + ) + } + + fn add_lower(&mut self, types: TypeContents) { + // If lists/strings are lowered into wasm then memory is required as + // usual but `realloc` is also required to allow the external caller to + // allocate space in the destination for the list/string. + if types.contains(TypeContents::NEEDS_MEMORY) { + *self |= RequiredOptions::MEMORY | RequiredOptions::REALLOC; + } + if types.contains(TypeContents::STRING) { + *self |= RequiredOptions::MEMORY + | RequiredOptions::STRING_ENCODING + | RequiredOptions::REALLOC; + } + } + + fn add_lift(&mut self, types: TypeContents) { + // Unlike for `lower` when lifting a string/list all that's needed is + // memory, since the string/list already resides in memory `realloc` + // isn't needed. + if types.contains(TypeContents::NEEDS_MEMORY) { + *self |= RequiredOptions::MEMORY; + } + if types.contains(TypeContents::STRING) { + *self |= RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING; + } + } + + fn into_iter( + self, + encoding: StringEncoding, + memory_index: Option, + realloc_index: Option, + ) -> Result> { + #[derive(Default)] + struct Iter { + options: [Option; 5], + current: usize, + count: usize, + } + + impl Iter { + fn push(&mut self, option: CanonicalOption) { + assert!(self.count < self.options.len()); + self.options[self.count] = Some(option); + self.count += 1; + } + } + + impl Iterator for Iter { + type Item = CanonicalOption; + + fn next(&mut self) -> Option { + if self.current == self.count { + return None; + } + let option = self.options[self.current]; + self.current += 1; + option + } + + fn size_hint(&self) -> (usize, Option) { + (self.count - self.current, Some(self.count - self.current)) + } + } + + impl ExactSizeIterator for Iter {} + + let mut iter = Iter::default(); + + if self.contains(RequiredOptions::MEMORY) { + iter.push(CanonicalOption::Memory(memory_index.ok_or_else(|| { + anyhow!("module does not export a memory named `memory`") + })?)); + } + + if self.contains(RequiredOptions::REALLOC) { + iter.push(CanonicalOption::Realloc(realloc_index.ok_or_else( + || anyhow!("module does not export a function named `cabi_realloc`"), + )?)); + } + + if self.contains(RequiredOptions::STRING_ENCODING) { + iter.push(encoding.into()); + } + + if self.contains(RequiredOptions::ASYNC) { + iter.push(CanonicalOption::Async); + } + + Ok(iter) + } +} + +bitflags::bitflags! { + /// Flags about what kinds of types are present within the recursive + /// structure of a type. + struct TypeContents: u8 { + const STRING = 1 << 0; + const NEEDS_MEMORY = 1 << 1; + } +} + +impl TypeContents { + fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator) -> Self { + let mut cur = TypeContents::empty(); + for ty in types { + cur |= Self::for_type(resolve, ty); + } + cur + } + + fn for_optional_types<'a>( + resolve: &Resolve, + types: impl Iterator>, + ) -> Self { + Self::for_types(resolve, types.flatten()) + } + + fn for_optional_type(resolve: &Resolve, ty: Option<&Type>) -> Self { + match ty { + Some(ty) => Self::for_type(resolve, ty), + None => Self::empty(), + } + } + + fn for_type(resolve: &Resolve, ty: &Type) -> Self { + match ty { + Type::Id(id) => match &resolve.types[*id].kind { + TypeDefKind::Handle(h) => match h { + wit_parser::Handle::Own(_) => Self::empty(), + wit_parser::Handle::Borrow(_) => Self::empty(), + }, + TypeDefKind::Resource => Self::empty(), + TypeDefKind::Record(r) => Self::for_types(resolve, r.fields.iter().map(|f| &f.ty)), + TypeDefKind::Tuple(t) => Self::for_types(resolve, t.types.iter()), + TypeDefKind::Flags(_) => Self::empty(), + TypeDefKind::Option(t) => Self::for_type(resolve, t), + TypeDefKind::Result(r) => { + Self::for_optional_type(resolve, r.ok.as_ref()) + | Self::for_optional_type(resolve, r.err.as_ref()) + } + TypeDefKind::Variant(v) => { + Self::for_optional_types(resolve, v.cases.iter().map(|c| c.ty.as_ref())) + } + TypeDefKind::Enum(_) => Self::empty(), + TypeDefKind::List(t) => Self::for_type(resolve, t) | Self::NEEDS_MEMORY, + TypeDefKind::Map(k, v) => { + Self::for_type(resolve, k) | Self::for_type(resolve, v) | Self::NEEDS_MEMORY + } + TypeDefKind::FixedLengthList(t, _elements) => Self::for_type(resolve, t), + TypeDefKind::Type(t) => Self::for_type(resolve, t), + TypeDefKind::Future(_) => Self::empty(), + TypeDefKind::Stream(_) => Self::empty(), + TypeDefKind::Unknown => unreachable!(), + }, + Type::String => Self::STRING, + _ => Self::empty(), + } + } +} + +/// State relating to encoding a component. +pub struct EncodingState<'a> { + /// The component being encoded. + component: ComponentBuilder, + /// The index into the core module index space for the inner core module. + /// + /// If `None`, the core module has not been encoded. + module_index: Option, + /// The index into the core instance index space for the inner core module. + /// + /// If `None`, the core module has not been instantiated. + instance_index: Option, + /// The index in the core memory index space for the exported memory. + /// + /// If `None`, then the memory has not yet been aliased. + memory_index: Option, + /// The index of the shim instance used for lowering imports into the core instance. + /// + /// If `None`, then the shim instance how not yet been encoded. + shim_instance_index: Option, + + /// A map of named adapter modules and the index that the module was defined + /// at. + adapter_modules: IndexMap<&'a str, u32>, + /// A map of adapter module instances and the index of their instance. + adapter_instances: IndexMap<&'a str, u32>, + + /// Imported/exported instances and what index they were imported as. + instances: IndexMap, + imported_funcs: IndexMap, + + /// Maps used when translating types to the component model binary format. + /// Note that imports and exports are stored in separate maps since they + /// need fresh hierarchies of types in case the same interface is both + /// imported and exported. + type_encoding_maps: TypeEncodingMaps<'a>, + + /// Cache of items that have been aliased from core instances. + /// + /// This is a helper to reduce the number of aliases created by ensuring + /// that repeated requests for the same item return the same index of an + /// original `core alias` item. + aliased_core_items: HashMap<(u32, String), u32>, + + /// Metadata about the world inferred from the input to `ComponentEncoder`. + info: &'a ComponentWorld<'a>, + + /// Maps from the instance an export came from, plus its original core + /// name, to the index of the wrapper function which the fixup module + /// defines for it. + /// + /// Used to invoke the task hook around lifted exports, post-return + /// functions, callbacks, and `realloc` functions. + export_task_initialization_wrappers: HashMap<(fixup::ImportedInstance, String), u32>, +} + +impl<'a> EncodingState<'a> { + fn encode_core_modules(&mut self) { + assert!(self.module_index.is_none()); + let idx = self + .component + .core_module_raw(Some("main"), &self.info.encoder.module); + self.module_index = Some(idx); + + for (name, adapter) in self.info.adapters.iter() { + let debug_name = if adapter.library_info.is_some() { + name.to_string() + } else { + format!("wit-component:adapter:{name}") + }; + let idx = if self.info.encoder.debug_names { + let mut add_meta = wasm_metadata::AddMetadata::default(); + add_meta.name = AddMetadataField::Set(debug_name.clone()); + let wasm = add_meta + .to_wasm(&adapter.wasm) + .expect("core wasm can get name added"); + self.component.core_module_raw(Some(&debug_name), &wasm) + } else { + self.component + .core_module_raw(Some(&debug_name), &adapter.wasm) + }; + let prev = self.adapter_modules.insert(name, idx); + assert!(prev.is_none()); + } + } + + fn root_import_type_encoder( + &mut self, + interface: Option, + ) -> RootTypeEncoder<'_, 'a> { + RootTypeEncoder { + state: self, + interface, + import_types: true, + } + } + + fn root_export_type_encoder( + &mut self, + interface: Option, + ) -> RootTypeEncoder<'_, 'a> { + RootTypeEncoder { + state: self, + interface, + import_types: false, + } + } + + fn instance_type_encoder(&mut self, interface: InterfaceId) -> InstanceTypeEncoder<'_, 'a> { + InstanceTypeEncoder { + state: self, + interface, + type_encoding_maps: Default::default(), + ty: Default::default(), + } + } + + fn encode_imports(&mut self, name_map: &HashMap) -> Result<()> { + let mut has_funcs = false; + for (name, info) in self.info.import_map.iter() { + match name { + Some(name) => { + self.encode_interface_import(name_map.get(name).unwrap_or(name), info)? + } + None => has_funcs = true, + } + } + + let resolve = &self.info.encoder.metadata.resolve; + let world = &resolve.worlds[self.info.encoder.metadata.world]; + + // FIXME: ideally this would use the liveness analysis from + // world-building to only encode live types, not all type in a world. + for (_name, item) in world.imports.iter() { + if let WorldItem::Type { id, .. } = item { + self.root_import_type_encoder(None) + .encode_valtype(resolve, &Type::Id(*id))?; + } + } + + if has_funcs { + let info = &self.info.import_map[&None]; + self.encode_root_import_funcs(info)?; + } + Ok(()) + } + + fn encode_interface_import(&mut self, name: &str, info: &ImportedInterface) -> Result<()> { + let resolve = &self.info.encoder.metadata.resolve; + let interface_id = info.interface.as_ref().unwrap(); + let interface_id = *interface_id; + let interface = &resolve.interfaces[interface_id]; + log::trace!("encoding imports for `{name}` as {interface_id:?}"); + let mut encoder = self.instance_type_encoder(interface_id); + + // First encode all type information + if let Some(live) = encoder.state.info.live_type_imports.get(&interface_id) { + for ty in live { + log::trace!( + "encoding extra type {ty:?} name={:?}", + resolve.types[*ty].name + ); + encoder.encode_valtype(resolve, &Type::Id(*ty))?; + } + } + + // Next encode all required functions from this imported interface + // into the instance type. + for (_, func) in interface.functions.iter() { + if !(info + .lowerings + .contains_key(&(func.name.clone(), AbiVariant::GuestImport)) + || info + .lowerings + .contains_key(&(func.name.clone(), AbiVariant::GuestImportAsync))) + { + continue; + } + log::trace!("encoding function type for `{}`", func.name); + let idx = encoder.encode_func_type(resolve, func)?; + + encoder.ty.export( + crate::encoding::types::extern_name(&func.name, func.external_id.as_deref()), + ComponentTypeRef::Func(idx), + ); + } + + let ty = encoder.ty; + // Don't encode empty instance types since they're not + // meaningful to the runtime of the component anyway. + if ty.is_empty() { + return Ok(()); + } + let instance_type_idx = self + .component + .type_instance(Some(&format!("ty-{name}")), &ty); + let instance_idx = self.component.import( + wasm_encoder::ComponentExternName { + name: name.into(), + implements: info.implements.as_deref().map(|s| s.into()), + external_id: info.external_id.as_deref().map(|s| s.into()), + version_suffix: None, + }, + ComponentTypeRef::Instance(instance_type_idx), + ); + let prev = self.instances.insert(interface_id, instance_idx); + assert!(prev.is_none()); + Ok(()) + } + + fn encode_root_import_funcs(&mut self, info: &ImportedInterface) -> Result<()> { + let resolve = &self.info.encoder.metadata.resolve; + let world = self.info.encoder.metadata.world; + for (name, item) in resolve.worlds[world].imports.iter() { + let func = match item { + WorldItem::Function(f) => f, + WorldItem::Interface { .. } | WorldItem::Type { .. } => continue, + }; + let name = resolve.name_world_key(name); + if !(info + .lowerings + .contains_key(&(name.clone(), AbiVariant::GuestImport)) + || info + .lowerings + .contains_key(&(name.clone(), AbiVariant::GuestImportAsync))) + { + continue; + } + log::trace!("encoding function type for `{}`", func.name); + let idx = self + .root_import_type_encoder(None) + .encode_func_type(resolve, func)?; + let func_idx = self.component.import( + crate::encoding::types::extern_name(name.as_str(), func.external_id.as_deref()), + ComponentTypeRef::Func(idx), + ); + let prev = self.imported_funcs.insert(name, func_idx); + assert!(prev.is_none()); + } + Ok(()) + } + + fn alias_instance_type_export(&mut self, interface: InterfaceId, id: TypeId) -> u32 { + let ty = &self.info.encoder.metadata.resolve.types[id]; + let name = ty.name.as_ref().expect("type must have a name"); + let instance = self.instances[&interface]; + self.component + .alias_export(instance, name, ComponentExportKind::Type) + } + + fn encode_core_instantiation( + &mut self, + fixup_hook: Option<&mut dyn FnMut(&mut fixup::FixupModule) -> Result<()>>, + ) -> Result<()> { + // Encode a shim instantiation if needed + let (shims, mut fixups) = self.encode_shim_instantiation()?; + + // Next declare any types needed for imported intrinsics. This + // populates `export_type_map` and will additionally be used for + // imports to modules instantiated below. + self.declare_types_for_imported_intrinsics(&shims)?; + + // Next instantiate the main module. This provides the linear memory to + // use for all future adapters and enables creating indirect lowerings + // at the end. + self.instantiate_main_module(&shims)?; + + for (name, _adapter) in self.info.adapters.iter() { + self.instantiate_adapter_module(&shims, name)?; + } + + if let Some(initialize) = self.info.info.exports.initialize() { + fixups.add_initialize(initialize)?; + } + + if let Some(hook) = fixup_hook { + hook(&mut fixups)?; + } + + // With all the relevant core wasm instances in play now the original shim + // module, if present, can be filled in with lowerings/adapters/etc. + fixups.instantiate(&shims, self)?; + + Ok(()) + } + + fn lookup_resource_index(&mut self, id: TypeId) -> u32 { + let resolve = &self.info.encoder.metadata.resolve; + let ty = &resolve.types[id]; + match ty.owner { + // If this resource is owned by a world then it's a top-level + // resource which means it must have already been translated so + // it's available for lookup in `import_type_map`. + TypeOwner::World(_) => self.type_encoding_maps.id_to_index[&id], + TypeOwner::Interface(i) => { + let instance = self.instances[&i]; + let name = ty.name.as_ref().expect("resources must be named"); + self.component + .alias_export(instance, name, ComponentExportKind::Type) + } + TypeOwner::None => panic!("resources must have an owner"), + } + } + + fn encode_exports(&mut self, module: CustomModule) -> Result<()> { + let resolve = &self.info.encoder.metadata.resolve; + let exports = match module { + CustomModule::Main => &self.info.encoder.main_module_exports, + CustomModule::Adapter(name) => &self.info.encoder.adapters[name].required_exports, + }; + + if exports.is_empty() { + return Ok(()); + } + + let mut interface_func_core_names = IndexMap::new(); + let mut world_func_core_names = IndexMap::new(); + for (core_name, export) in self.info.exports_for(module).iter() { + match export { + Export::WorldFunc(_, name, _) => { + let prev = world_func_core_names.insert(name, core_name); + assert!(prev.is_none()); + } + Export::InterfaceFunc(key, _, name, _) => { + let prev = interface_func_core_names + .entry(key) + .or_insert(IndexMap::new()) + .insert(name.as_str(), core_name); + assert!(prev.is_none()); + } + Export::WorldFuncCallback(..) + | Export::InterfaceFuncCallback(..) + | Export::WorldFuncPostReturn(..) + | Export::InterfaceFuncPostReturn(..) + | Export::ResourceDtor(..) + | Export::Memory + | Export::GeneralPurposeRealloc + | Export::GeneralPurposeExportRealloc + | Export::GeneralPurposeImportRealloc + | Export::Initialize + | Export::ReallocForAdapter + | Export::IndirectFunctionTable + | Export::WasmTaskHook => continue, + } + } + + let world = &resolve.worlds[self.info.encoder.metadata.world]; + + for export_name in exports { + let export_string = resolve.name_world_key(export_name); + match &world.exports[export_name] { + WorldItem::Function(func) => { + let ty = self + .root_import_type_encoder(None) + .encode_func_type(resolve, func)?; + let core_name = world_func_core_names[&func.name]; + let idx = self.encode_lift(module, &core_name, export_name, func, ty)?; + self.component.export( + crate::encoding::types::extern_name( + &export_string, + func.external_id.as_deref(), + ), + ComponentExportKind::Func, + idx, + None, + ); + } + item @ WorldItem::Interface { id, .. } => { + let core_names = interface_func_core_names.get(export_name); + self.encode_interface_export( + &export_string, + module, + export_name, + item, + *id, + core_names, + )?; + } + WorldItem::Type { .. } => unreachable!(), + } + } + + Ok(()) + } + + fn encode_interface_export( + &mut self, + export_name: &str, + module: CustomModule<'_>, + key: &WorldKey, + item: &WorldItem, + export: InterfaceId, + interface_func_core_names: Option<&IndexMap<&str, &str>>, + ) -> Result<()> { + log::trace!("encode interface export `{export_name}`"); + let resolve = &self.info.encoder.metadata.resolve; + + // First execute a `canon lift` for all the functions in this interface + // from the core wasm export. This requires type information but notably + // not exported type information since we don't want to export this + // interface's types from the root of the component. Each lifted + // function is saved off into an `imports` array to get imported into + // the nested component synthesized below. + let mut imports = Vec::new(); + let mut root = self.root_export_type_encoder(Some(export)); + for (_, func) in &resolve.interfaces[export].functions { + let core_name = interface_func_core_names.unwrap()[func.name.as_str()]; + let ty = root.encode_func_type(resolve, func)?; + let func_index = root.state.encode_lift(module, &core_name, key, func, ty)?; + imports.push(( + import_func_name(func), + ComponentExportKind::Func, + func_index, + )); + } + + // Next a nested component is created which will import the functions + // above and then reexport them. The purpose of them is to "re-type" the + // functions through type ascription on each `func` item. + let mut nested = NestedComponentTypeEncoder { + component: ComponentBuilder::default(), + type_encoding_maps: Default::default(), + export_types: false, + interface: export, + state: self, + imports: IndexMap::new(), + }; + + // Import all transitively-referenced types from other interfaces into + // this component. This temporarily switches the `interface` listed to + // the interface of the referred-to-type to generate the import. After + // this loop `interface` is rewritten to `export`. + // + // Each component is a standalone "island" so the necessary type + // information needs to be rebuilt within this component. This ensures + // that we're able to build a valid component and additionally connect + // all the type information to the outer context. + let mut types_to_import = LiveTypes::default(); + types_to_import.add_interface(resolve, export); + let exports_used = &nested.state.info.exports_used[&export]; + for ty in types_to_import.iter() { + if let TypeOwner::Interface(owner) = resolve.types[ty].owner { + if owner == export { + // Here this deals with the current exported interface which + // is handled below. + continue; + } + + // Ensure that `self` has encoded this type before. If so this + // is a noop but otherwise it generates the type here. + let mut encoder = if exports_used.contains(&owner) { + nested.state.root_export_type_encoder(Some(export)) + } else { + nested.state.root_import_type_encoder(Some(export)) + }; + encoder.encode_valtype(resolve, &Type::Id(ty))?; + + // Next generate the same type but this time within the + // component itself. The type generated above (or prior) will be + // used to satisfy this type import. + nested.interface = owner; + nested.encode_valtype(resolve, &Type::Id(ty))?; + } + } + nested.interface = export; + + // Record the map of types imported to their index at where they were + // imported. This is used after imports are encoded as exported types + // will refer to these. + let imported_type_maps = nested.type_encoding_maps.clone(); + + // Handle resource types for this instance specially, namely importing + // them into the nested component. This models how the resource is + // imported from its definition in the outer component to get reexported + // internally. This chiefly avoids creating a second resource which is + // not desired in this situation. + let mut resources = HashMap::new(); + for (_name, ty) in resolve.interfaces[export].types.iter() { + if !matches!(resolve.types[*ty].kind, TypeDefKind::Resource) { + continue; + } + let idx = match nested.encode_valtype(resolve, &Type::Id(*ty))? { + ComponentValType::Type(idx) => idx, + _ => unreachable!(), + }; + resources.insert(*ty, idx); + } + + // Next import each function of this interface. This will end up + // defining local types as necessary or using the types as imported + // above. + for (_, func) in resolve.interfaces[export].functions.iter() { + let ty = nested.encode_func_type(resolve, func)?; + nested + .component + .import(&import_func_name(func), ComponentTypeRef::Func(ty)); + } + + // Swap the `nested.type_map` which was previously from `TypeId` to + // `u32` to instead being from `u32` to `TypeId`. This reverse map is + // then used in conjunction with `self.type_map` to satisfy all type + // imports of the nested component generated. The type import's index in + // the inner component is translated to a `TypeId` via `reverse_map` + // which is then translated back to our own index space via `type_map`. + let reverse_map = nested + .type_encoding_maps + .id_to_index + .drain() + .map(|p| (p.1, p.0)) + .collect::>(); + nested.type_encoding_maps.def_to_index.clear(); + for (name, idx) in nested.imports.drain(..) { + let id = reverse_map[&idx]; + let idx = nested.state.type_encoding_maps.id_to_index[&id]; + imports.push((name, ComponentExportKind::Type, idx)) + } + + // Before encoding exports reset the type map to what all was imported + // from foreign interfaces. This will enable any encoded types below to + // refer to imports which, after type substitution, will point to the + // correct type in the outer component context. + nested.type_encoding_maps = imported_type_maps; + + // Next the component reexports all of its imports, but notably uses the + // type ascription feature to change the type of the function. Note that + // no structural change is happening to the types here but instead types + // are getting proper names and such now that this nested component is a + // new type index space. Hence the `export_types = true` flag here which + // flows through the type encoding and when types are emitted. + nested.export_types = true; + nested.type_encoding_maps.func_type_map.clear(); + + // To start off all type information is encoded. This will be used by + // functions below but notably this also has special handling for + // resources. Resources reexport their imported resource type under + // the final name which achieves the desired goal of threading through + // the original resource without creating a new one. + for (_, id) in resolve.interfaces[export].types.iter() { + let ty = &resolve.types[*id]; + match ty.kind { + TypeDefKind::Resource => { + let idx = nested.component.export( + crate::encoding::types::extern_name( + ty.name.as_ref().expect("resources must be named"), + ty.external_id.as_deref(), + ), + ComponentExportKind::Type, + resources[id], + None, + ); + nested.type_encoding_maps.id_to_index.insert(*id, idx); + } + _ => { + nested.encode_valtype(resolve, &Type::Id(*id))?; + } + } + } + + for (i, (_, func)) in resolve.interfaces[export].functions.iter().enumerate() { + let ty = nested.encode_func_type(resolve, func)?; + nested.component.export( + crate::encoding::types::extern_name(&func.name, func.external_id.as_deref()), + ComponentExportKind::Func, + i as u32, + Some(ComponentTypeRef::Func(ty)), + ); + } + + // Embed the component within our component and then instantiate it with + // the lifted functions. That final instance is then exported under the + // appropriate name as the final typed export of this component. + let component = nested.component; + let component_index = self + .component + .component(Some(&format!("{export_name}-shim-component")), component); + let instance_index = self.component.instantiate( + Some(&format!("{export_name}-shim-instance")), + component_index, + imports, + ); + let idx = self.component.export( + wasm_encoder::ComponentExternName { + name: export_name.into(), + implements: resolve.implements_value(key, item).map(|s| s.into()), + external_id: resolve.external_id_value(key, item).map(|s| s.into()), + version_suffix: None, + }, + ComponentExportKind::Instance, + instance_index, + None, + ); + let prev = self.instances.insert(export, idx); + assert!(prev.is_none()); + + // After everything is all said and done remove all the type information + // about type exports of this interface. Any entries in the map + // currently were used to create the instance above but aren't the + // actual copy of the exported type since that comes from the exported + // instance itself. Entries will be re-inserted into this map as + // necessary via aliases from the exported instance which is the new + // source of truth for all these types. + for (_name, id) in resolve.interfaces[export].types.iter() { + self.type_encoding_maps.id_to_index.remove(id); + self.type_encoding_maps + .def_to_index + .remove(&resolve.types[*id].kind); + } + + return Ok(()); + + struct NestedComponentTypeEncoder<'state, 'a> { + component: ComponentBuilder, + type_encoding_maps: TypeEncodingMaps<'a>, + export_types: bool, + interface: InterfaceId, + state: &'state mut EncodingState<'a>, + imports: IndexMap, + } + + impl<'a> ValtypeEncoder<'a> for NestedComponentTypeEncoder<'_, 'a> { + fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { + self.component.type_defined(None) + } + fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { + self.component.type_function(None) + } + fn export_type( + &mut self, + idx: u32, + name: wasm_encoder::ComponentExternName<'a>, + ) -> Option { + if self.export_types { + Some( + self.component + .export(name, ComponentExportKind::Type, idx, None), + ) + } else { + let name = self.unique_import_name(&name.name); + let ret = self + .component + .import(&name, ComponentTypeRef::Type(TypeBounds::Eq(idx))); + self.imports.insert(name, ret); + Some(ret) + } + } + fn export_resource(&mut self, name: wasm_encoder::ComponentExternName<'a>) -> u32 { + if self.export_types { + panic!("resources should already be exported") + } else { + let name = self.unique_import_name(&name.name); + let ret = self + .component + .import(&name, ComponentTypeRef::Type(TypeBounds::SubResource)); + self.imports.insert(name, ret); + ret + } + } + fn import_type(&mut self, _: InterfaceId, _id: TypeId) -> u32 { + unreachable!() + } + fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { + &mut self.type_encoding_maps + } + fn interface(&self) -> Option { + Some(self.interface) + } + } + + impl NestedComponentTypeEncoder<'_, '_> { + fn unique_import_name(&mut self, name: &str) -> String { + let mut name = format!("import-type-{name}"); + let mut n = 0; + while self.imports.contains_key(&name) { + name = format!("{name}{n}"); + n += 1; + } + name + } + } + } + + fn encode_lift( + &mut self, + module: CustomModule<'_>, + core_name: &str, + key: &WorldKey, + func: &Function, + ty: u32, + ) -> Result { + let resolve = &self.info.encoder.metadata.resolve; + let metadata = self.info.module_metadata_for(module); + + let core_alias_export = + |me: &mut Self, core_name: &str| me.hooked_core_alias_export(module, core_name); + + let core_func_index = core_alias_export(self, core_name); + let exports = self.info.exports_for(module); + + let options = RequiredOptions::for_export( + resolve, + func, + exports + .abi(key, func) + .ok_or_else(|| anyhow!("no ABI found for {}", func.name))?, + ); + + let encoding = metadata + .export_encodings + .get(resolve, key, &func.name) + .unwrap(); + let exports = self.info.exports_for(module); + let realloc_index = if options.contains(RequiredOptions::REALLOC) { + let realloc = exports.export_realloc_for(key, &func.name); + resolve_realloc(self.info, module, realloc) + .map(|(module, name)| self.hooked_core_alias_export(module, name)) + } else { + None + }; + let mut options = options + .into_iter(encoding, self.memory_index, realloc_index)? + .collect::>(); + + if let Some(post_return) = exports.post_return(key, func) { + let post_return = core_alias_export(self, post_return); + options.push(CanonicalOption::PostReturn(post_return)); + } + if let Some(callback) = exports.callback(key, func) { + let callback = core_alias_export(self, callback); + options.push(CanonicalOption::Callback(callback)); + } + let func_index = self + .component + .lift_func(Some(&func.name), core_func_index, ty, options); + Ok(func_index) + } + + fn encode_shim_instantiation(&mut self) -> Result<(Shims<'a>, fixup::FixupModule)> { + let mut ret = Shims::default(); + let mut fixups = fixup::FixupModule::default(); + + ret.append_indirect(self.info, CustomModule::Main) + .context("failed to register indirect shims for main module")?; + + // For all required adapter modules a shim is created for each required + // function and additionally a set of shims are created for the + // interface imported into the shim module itself. + for (adapter_name, _adapter) in self.info.adapters.iter() { + ret.append_indirect(self.info, CustomModule::Adapter(adapter_name)) + .with_context(|| { + format!("failed to register indirect shims for adapter {adapter_name}") + })?; + } + + // Determine if a TLS global needs to be synthesized here by seeing if + // it was imported into any module. + let tls_base_global_type = if self.info.can_use_context_slot_1() { + None + } else { + let infos = [&self.info.info] + .into_iter() + .chain(self.info.adapters.values().map(|a| &a.info)); + let mut ret = None; + for info in infos { + for (_, _, import) in info.imports.imports() { + let ty = match import { + Import::TlsBaseGet { ty } | Import::TlsBaseSet { ty } => *ty, + _ => continue, + }; + let prev = *ret.get_or_insert(ty); + if prev != ty { + bail!("conflicting TLS base pointer types `{prev}` and `{ty}`"); + } + } + } + match ret { + Some(ret) => Some(ret.try_into()?), + None => None, + } + }; + + if ret.shims.is_empty() + && self.info.info.imports.imported_memory().is_none() + && tls_base_global_type.is_none() + { + return Ok((ret, fixups)); + } + + assert!(self.shim_instance_index.is_none()); + + // This function encodes a single module, the shim module, which defines + // functions to indirectly call through tables or globals. This shim + // additionally may contain the memory for the main module if it needs + // it as well as the TLS base pointer for the program. This shim is + // instantiated before the main module. + + let mut types = TypeSection::new(); + let mut shim_globals = GlobalSection::new(); + let mut shim_tables = TableSection::new(); + let mut shim_memories = MemorySection::new(); + let mut shim_functions = FunctionSection::new(); + let mut shim_exports = ExportSection::new(); + let mut shim_code = CodeSection::new(); + let mut sigs = IndexMap::new(); + let mut trapping_stubs = IndexMap::new(); + let mut func_indexes = Vec::new(); + let mut func_names = NameMap::new(); + + let mut intern_type = + |types: &mut TypeSection, params: Vec, results: Vec| { + *sigs + .entry((params, results)) + .or_insert_with_key(|(params, results)| { + let index = types.len(); + types + .ty() + .function(params.iter().copied(), results.iter().copied()); + index + }) + }; + + for shim in ret.shims.values() { + let type_index = intern_type( + &mut types, + shim.sig.params.iter().map(to_val_type).collect(), + shim.sig.results.iter().map(to_val_type).collect(), + ); + + let trapping_stub = if self.info.encoder.shim_return_call_ref { + // Generate a stub which is `unreachable` for the initializer of + // this global. This can be deduplicated by type signature. + Some(*trapping_stubs.entry(type_index).or_insert_with(|| { + let mut stub = wasm_encoder::Function::new(std::iter::empty()); + stub.instructions().unreachable().end(); + let index = shim_code.len(); + shim_functions.function(type_index); + shim_code.function(&stub); + func_names.append(index, "trap stub before initialization"); + index + })) + } else { + None + }; + + let func_index = shim_functions.len(); + shim_functions.function(type_index); + let mut func = wasm_encoder::Function::new(std::iter::empty()); + for i in 0..shim.sig.params.len() { + func.instructions().local_get(i as u32); + } + fixups.add_shim(&self.info.encoder, shim)?; + if self.info.encoder.shim_return_call_ref { + // Generate a global-per-function which gets exported from the + // module and then filled in later. + let global = shim_globals.len(); + let ty = GlobalType { + val_type: RefType { + nullable: false, + heap_type: HeapType::Concrete(type_index), + } + .into(), + mutable: true, + shared: false, + }; + let global_name = format!("g{}", shim.name); + shim_globals.global(ty, &ConstExpr::ref_func(trapping_stub.unwrap())); + shim_exports.export(&global_name, ExportKind::Global, global); + + func.instructions().global_get(global); + func.instructions().return_call_ref(type_index); + } else { + func.instructions().i32_const(func_index as i32); + func.instructions().call_indirect(0, type_index); + } + func.instructions().end(); + shim_code.function(&func); + shim_exports.export(&shim.name, ExportKind::Func, func_index); + + func_indexes.push(func_index); + func_names.append(func_index, &shim.debug_name); + } + + if !ret.shims.is_empty() && !self.info.encoder.shim_return_call_ref { + let table_type = TableType { + element_type: RefType::FUNCREF, + minimum: ret.shims.len() as u64, + maximum: Some(ret.shims.len() as u64), + table64: false, + shared: false, + }; + + shim_tables.table(table_type); + shim_exports.export(INDIRECT_TABLE_NAME, ExportKind::Table, 0); + } + + // If the main module imports its memory then define it here and export + // it for everyone else to use. + if let Some(ty) = self.info.info.imports.imported_memory() { + shim_memories.memory(RoundtripReencoder.memory_type(ty)?); + shim_exports.export(SHIM_MEMORY_NAME, ExportKind::Memory, 0); + } + + // If the TLS base pointer is stored in a `global`, as opposed to a + // `context` slot, then define that global here along with accessors + // for it which everyone else uses. + if let Some(ty) = tls_base_global_type { + let get_ty = intern_type(&mut types, Vec::new(), vec![ty]); + let set_ty = intern_type(&mut types, vec![ty], Vec::new()); + + let global = shim_globals.len(); + shim_globals.global( + GlobalType { + val_type: ty, + mutable: true, + shared: false, + }, + &match ty { + ValType::I64 => ConstExpr::i64_const(0), + ValType::I32 => ConstExpr::i32_const(0), + _ => unreachable!(), + }, + ); + + let get = shim_functions.len(); + shim_functions.function(get_ty); + let mut func = wasm_encoder::Function::new(std::iter::empty()); + func.instructions().global_get(global).end(); + shim_code.function(&func); + shim_exports.export(TLS_BASE_GET, ExportKind::Func, get); + func_names.append(get, TLS_BASE_GET); + + let set = shim_functions.len(); + shim_functions.function(set_ty); + let mut func = wasm_encoder::Function::new(std::iter::empty()); + func.instructions().local_get(0).global_set(global).end(); + shim_code.function(&func); + shim_exports.export(TLS_BASE_SET, ExportKind::Func, set); + func_names.append(set, TLS_BASE_SET); + } + + let mut shim_names = NameSection::new(); + shim_names.module("wit-component:shim"); + shim_names.functions(&func_names); + + let mut shim = Module::new(); + shim.section(&types); + if !shim_functions.is_empty() { + shim.section(&shim_functions); + } + if !shim_tables.is_empty() { + shim.section(&shim_tables); + } + if !shim_memories.is_empty() { + shim.section(&shim_memories); + } + if !shim_globals.is_empty() { + shim.section(&shim_globals); + } + if !shim_exports.is_empty() { + shim.section(&shim_exports); + } + if !shim_code.is_empty() { + shim.section(&shim_code); + } + shim.section(&RawCustomSection( + &crate::base_producers().raw_custom_section(), + )); + if self.info.encoder.debug_names { + shim.section(&shim_names); + } + + let shim_module_index = self + .component + .core_module(Some("wit-component-shim-module"), &shim); + + let shim_instance = self.component.core_instantiate( + Some("wit-component-shim-instance"), + shim_module_index, + [], + ); + self.shim_instance_index = Some(shim_instance); + + // With the shim instantiated the memory it defines, if any, is now + // available for use as a canonical option. + if self.info.info.imports.imported_memory().is_some() { + assert!(self.memory_index.is_none()); + self.memory_index = Some(self.core_alias_export( + Some("memory"), + shim_instance, + SHIM_MEMORY_NAME, + ExportKind::Memory, + )); + } + + Ok((ret, fixups)) + } + + fn encode_shim(&mut self, shims: &Shims<'_>, shim: &Shim<'_>) -> Result { + let resolve = &self.info.encoder.metadata.resolve; + Ok(match &shim.kind { + // Indirect lowerings are a `canon lower`'d function with + // options specified from a previously instantiated instance. + // This previous instance could either be the main module or an + // adapter module, which affects the `realloc` option here. + // Currently only one linear memory is supported so the linear + // memory always comes from the main module. + ShimKind::IndirectLowering { + interface, + index, + realloc, + encoding, + } => { + let interface = &self.info.import_map[interface]; + let ((name, _), _) = interface.lowerings.get_index(*index).unwrap(); + let func_index = match &interface.interface { + Some(interface_id) => { + let instance_index = self.instances[interface_id]; + self.component + .alias_export(instance_index, name, ComponentExportKind::Func) + } + None => self.imported_funcs[name], + }; + + let realloc_export = self + .info + .exports_for(*realloc) + .import_realloc_for(interface.interface, name); + let realloc = self.realloc_index( + shims, + *realloc, + ReallocSite::AfterInstantiation, + shim.options, + realloc_export, + ); + + self.component.lower_func( + Some(&shim.debug_name), + func_index, + shim.options + .into_iter(*encoding, self.memory_index, realloc)?, + ) + } + + // Adapter shims are defined by an export from an adapter + // instance, so use the specified name here and the previously + // created instances to get the core item that represents the + // shim. + ShimKind::Adapter { adapter, func } => self.core_alias_export( + Some(func), + self.adapter_instances[adapter], + func, + ExportKind::Func, + ), + + // Resources are required for a module to be instantiated + // meaning that any destructor for the resource must be called + // indirectly due to the otherwise circular dependency between + // the module and the resource itself. + ShimKind::ResourceDtor { module, export } => self.core_alias_export( + Some(export), + self.instance_for(*module), + export, + ExportKind::Func, + ), + + ShimKind::PayloadFunc { + for_module, + info, + kind, + } => self.encode_payload_func( + shims, + for_module, + info, + kind, + shim.options, + ReallocSite::AfterInstantiation, + )?, + + ShimKind::WaitableSetWait { cancellable } => self + .component + .waitable_set_wait(*cancellable, self.memory_index.unwrap()), + ShimKind::WaitableSetPoll { cancellable } => self + .component + .waitable_set_poll(*cancellable, self.memory_index.unwrap()), + ShimKind::ErrorContextNew { encoding } => self + .component + .error_context_new(shim.options.into_iter(*encoding, self.memory_index, None)?), + ShimKind::ErrorContextDebugMessage { + for_module, + encoding, + } => { + let realloc = self.info.exports_for(*for_module).import_realloc_fallback(); + let realloc_index = self.realloc_index( + shims, + *for_module, + ReallocSite::AfterInstantiation, + shim.options, + realloc, + ); + + self.component + .error_context_debug_message(shim.options.into_iter( + *encoding, + self.memory_index, + realloc_index, + )?) + } + ShimKind::TaskReturn { + interface, + func, + result, + encoding, + for_module, + } => { + // See `Import::ExportedTaskReturn` handling for why this + // encoder is treated specially. + let mut encoder = if interface.is_none() { + self.root_import_type_encoder(*interface) + } else { + self.root_export_type_encoder(*interface) + }; + let result = match result { + Some(ty) => Some(encoder.encode_valtype(resolve, ty)?), + None => None, + }; + + let exports = self.info.exports_for(*for_module); + let realloc = exports.import_realloc_for(*interface, func); + + let instance_index = self.instance_for(*for_module); + let realloc_index = realloc.map(|r| { + self.core_alias_export(Some("realloc"), instance_index, r, ExportKind::Func) + }); + let options = + shim.options + .into_iter(*encoding, self.memory_index, realloc_index)?; + self.component.task_return(result, options) + } + ShimKind::ThreadNewIndirect { func_ty } => { + // Encode the function type for the thread start function so we can reference it in the `canon` call. + let (func_ty_idx, f) = self.component.core_type(Some("thread-start")); + f.core().func_type(func_ty); + + // In order for the funcref table referenced by `thread.new-indirect` to be used, + // it must have been exported by the main module. + let exports = self.info.exports_for(CustomModule::Main); + let instance_index = self.instance_for(CustomModule::Main); + let table_idx = exports.indirect_function_table().map(|table| { + self.core_alias_export( + Some("indirect-function-table"), + instance_index, + table, + ExportKind::Table, + ) + }).ok_or_else(|| { + anyhow!( + "table __indirect_function_table must be an exported funcref table for thread.new-indirect" + ) + })?; + + self.component.thread_new_indirect(func_ty_idx, table_idx) + } + + ShimKind::Realloc { module, export } => { + let instance = self.instance_for(*module); + self.core_alias_export(Some(export), instance, export, ExportKind::Func) + } + }) + } + + fn encode_payload_func( + &mut self, + shims: &Shims<'_>, + for_module: &CustomModule, + info: &PayloadInfo, + kind: &PayloadFuncKind, + options: RequiredOptions, + site: ReallocSite, + ) -> Result { + let resolve = &self.info.encoder.metadata.resolve; + let metadata = self.info.module_metadata_for(*for_module); + let encoding = match &info.ty { + PayloadType::Type { function, .. } => { + if info.imported { + metadata.import_encodings.get(resolve, &info.key, function) + } else { + metadata.export_encodings.get(resolve, &info.key, function) + } + } + PayloadType::UnitFuture | PayloadType::UnitStream => None, + }; + let realloc = payload_realloc_name(self.info, *for_module, info); + let encoding = encoding.unwrap_or(StringEncoding::UTF8); + let realloc_index = self.realloc_index(shims, *for_module, site, options, realloc); + let type_index = self.payload_type_index(info)?; + let options = options.into_iter(encoding, self.memory_index, realloc_index)?; + + Ok(match kind { + PayloadFuncKind::FutureWrite => self.component.future_write(type_index, options), + PayloadFuncKind::FutureRead => self.component.future_read(type_index, options), + PayloadFuncKind::StreamWrite => self.component.stream_write(type_index, options), + PayloadFuncKind::StreamRead => self.component.stream_read(type_index, options), + }) + } + + /// Encode the specified `stream` or `future` type in the component using + /// either the `root_import_type_encoder` or the `root_export_type_encoder` + /// depending on the value of `imported`. + /// + /// Note that the payload type `T` of `stream` or `future` may be an + /// imported or exported type, and that determines the appropriate type + /// encoder to use. + fn payload_type_index(&mut self, info: &PayloadInfo) -> Result { + let resolve = &self.info.encoder.metadata.resolve; + // What exactly is selected here as the encoder is a bit unusual here. + // If the interface is imported, an import encoder is used. An import + // encoder is also used though if `info` is exported and + // `info.interface` is `None`, meaning that this is for a function that + // is in the top-level of a world. At the top level of a world all + // types are imported. + // + // Additionally for the import encoder the interface passed in is + // `None`, not `info.interface`. Notably this means that references to + // named types will be aliased from their imported versions, which is + // what we want here. + // + // Finally though exports do use `info.interface`. Honestly I'm not + // really entirely sure why. Fuzzing is happy though, and truly + // everything must be ok if the fuzzers are happy, right? + let mut encoder = if info.imported || info.interface.is_none() { + self.root_import_type_encoder(None) + } else { + self.root_export_type_encoder(info.interface) + }; + match info.ty { + PayloadType::Type { id, .. } => match encoder.encode_valtype(resolve, &Type::Id(id))? { + ComponentValType::Type(index) => Ok(index), + ComponentValType::Primitive(_) => unreachable!(), + }, + PayloadType::UnitFuture => Ok(encoder.encode_unit_future()), + PayloadType::UnitStream => Ok(encoder.encode_unit_stream()), + } + } + + /// This is a helper function that will declare any types necessary for + /// declaring intrinsics that are imported into the module or adapter. + /// + /// For example resources must be declared to generate + /// destructors/constructors/etc. Additionally types must also be declared + /// for `task.return` with the component model async feature. + fn declare_types_for_imported_intrinsics(&mut self, shims: &Shims<'_>) -> Result<()> { + let resolve = &self.info.encoder.metadata.resolve; + let world = &resolve.worlds[self.info.encoder.metadata.world]; + + // Iterate over the main module's exports and the exports of all + // adapters. Look for exported interfaces. + let main_module_keys = self.info.encoder.main_module_exports.iter(); + let main_module_keys = main_module_keys.map(|key| (CustomModule::Main, key)); + let adapter_keys = self.info.encoder.adapters.iter().flat_map(|(name, info)| { + info.required_exports + .iter() + .map(move |key| (CustomModule::Adapter(name), key)) + }); + for (for_module, key) in main_module_keys.chain(adapter_keys) { + let id = match &world.exports[key] { + WorldItem::Interface { id, .. } => *id, + WorldItem::Type { .. } => unreachable!(), + WorldItem::Function(_) => continue, + }; + + for ty in resolve.interfaces[id].types.values() { + let def = &resolve.types[*ty]; + match &def.kind { + // Declare exported resources specially as they generally + // need special treatment for later handling exports and + // such. + TypeDefKind::Resource => { + // Load the destructor, previously detected in module + // validation, if one is present. + let exports = self.info.exports_for(for_module); + let dtor = exports.resource_dtor(*ty).map(|name| { + let shim = &shims.shims[&ShimKind::ResourceDtor { + module: for_module, + export: name, + }]; + let index = self.shim_instance_index.unwrap(); + self.core_alias_export( + Some(&shim.debug_name), + index, + &shim.name, + ExportKind::Func, + ) + }); + + // Declare the resource with this destructor and register it in + // our internal map. This should be the first and only time this + // type is inserted into this map. + let resource_idx = self.component.type_resource( + Some(def.name.as_ref().unwrap()), + ValType::I32, + dtor, + ); + let prev = self + .type_encoding_maps + .id_to_index + .insert(*ty, resource_idx); + assert!(prev.is_none()); + } + _other => { + self.root_export_type_encoder(Some(id)) + .encode_valtype(resolve, &Type::Id(*ty))?; + } + } + } + } + Ok(()) + } + + /// Helper to instantiate the main module and record various results of its + /// instantiation within `self`. + fn instantiate_main_module(&mut self, shims: &Shims<'_>) -> Result<()> { + assert!(self.instance_index.is_none()); + + let instance_index = self.instantiate_core_module(shims, CustomModule::Main)?; + + // If memory hasn't been defined yet then it's provided by the main + // module here. + if self.memory_index.is_none() { + if let Some(memory) = self.info.info.exports.memory() { + self.memory_index = Some(self.core_alias_export( + Some("memory"), + instance_index, + memory, + ExportKind::Memory, + )); + } + } + + self.instance_index = Some(instance_index); + Ok(()) + } + + /// This function will instantiate the specified adapter module, which may + /// depend on previously-instantiated modules. + fn instantiate_adapter_module(&mut self, shims: &Shims<'_>, name: &'a str) -> Result<()> { + let instance = self.instantiate_core_module(shims, CustomModule::Adapter(name))?; + self.adapter_instances.insert(name, instance); + Ok(()) + } + + /// Generic helper to instantiate a module. + /// + /// The `for_module` provided will have all of its imports satisfied from + /// either previous instantiations or the `shims` module present. This + /// iterates over the metadata produced during validation to determine what + /// hooks up to what import. + fn instantiate_core_module( + &mut self, + shims: &Shims, + for_module: CustomModule<'_>, + ) -> Result { + let module = self.module_for(for_module); + + let mut args = Vec::new(); + for (core_wasm_name, instance) in self.info.imports_for(for_module).modules() { + match instance { + // For import modules that are a "bag of names" iterate over + // each name and materialize it into this component with the + // `materialize_import` helper. This is then all bottled up into + // a bag-of-exports instance which is then used for + // instantiation. + ImportInstance::Names(names) => { + let mut exports = Vec::new(); + for (name, import) in names { + log::trace!( + "attempting to materialize import of `{core_wasm_name}::{name}` for {for_module:?}" + ); + let (kind, index) = self + .materialize_import(&shims, for_module, import) + .with_context(|| { + format!("failed to satisfy import `{core_wasm_name}::{name}`") + })?; + exports.push((name.as_str(), kind, index)); + } + let index = self + .component + .core_instantiate_exports(Some(core_wasm_name), exports); + args.push((core_wasm_name.as_str(), ModuleArg::Instance(index))); + } + + // Some imports are entire instances, so use the instance for + // the module identifier as the import. + ImportInstance::Whole(which) => { + let instance = self.instance_for(which.to_custom_module()); + args.push((core_wasm_name.as_str(), ModuleArg::Instance(instance))); + } + } + } + + // And with all arguments prepared now, instantiate the module. + Ok(self + .component + .core_instantiate(Some(for_module.debug_name()), module, args)) + } + + /// Helper function to materialize an import into a core module within the + /// component being built. + /// + /// This function is called for individual imports and uses the results of + /// validation, notably the `Import` type, to determine what WIT-level or + /// component-level construct is being hooked up. + fn materialize_import( + &mut self, + shims: &Shims<'_>, + for_module: CustomModule<'_>, + import: &'a Import, + ) -> Result<(ExportKind, u32)> { + let resolve = &self.info.encoder.metadata.resolve; + match import { + // Main module dependencies on an adapter in use are done with an + // indirection here, so load the shim function and use that. + Import::AdapterExport { + adapter, + func, + ty: _, + } => { + assert!(self.info.encoder.adapters.contains_key(adapter)); + Ok(self.materialize_shim_import(shims, &ShimKind::Adapter { adapter, func })) + } + + // Adapters might use the main module's memory, in which case it + // should have been previously instantiated. + Import::MainModuleMemory(_) => { + let index = self + .memory_index + .ok_or_else(|| anyhow!("main module cannot import memory"))?; + Ok((ExportKind::Memory, index)) + } + + // Grab-bag of "this adapter wants this thing from the main module". + Import::MainModuleExport { name, kind } => { + let instance = self.instance_index.unwrap(); + let index = self.core_alias_export(Some(name), instance, name, *kind); + Ok((*kind, index)) + } + + // A similar grab-bag to above but with a slightly different + // structure. Should probably refactor to make these two the same in + // the future. + Import::Item(item) => { + let instance = self.instance_for(item.which.to_custom_module()); + let index = + self.core_alias_export(Some(&item.name), instance, &item.name, item.kind); + Ok((item.kind, index)) + } + + // Resource intrinsics related to exported resources. Despite being + // an exported resource the component still provides necessary + // intrinsics for manipulating resource state. These are all + // handled here using the resource types created during + // `declare_types_for_imported_intrinsics` above. + Import::ExportedResourceDrop(_key, id) => { + let index = self + .component + .resource_drop(self.type_encoding_maps.id_to_index[id]); + Ok((ExportKind::Func, index)) + } + Import::ExportedResourceRep(_key, id) => { + let index = self + .component + .resource_rep(self.type_encoding_maps.id_to_index[id]); + Ok((ExportKind::Func, index)) + } + Import::ExportedResourceNew(_key, id) => { + let index = self + .component + .resource_new(self.type_encoding_maps.id_to_index[id]); + Ok((ExportKind::Func, index)) + } + + // And finally here at the end these cases are going to all fall + // through to the code below. This is where these are connected to a + // WIT `ImportedInterface` one way or another with the name that was + // detected during validation. + Import::ImportedResourceDrop(key, iface, id) => { + let ty = &resolve.types[*id]; + let name = ty.name.as_ref().unwrap(); + self.materialize_wit_import( + shims, + for_module, + iface.map(|_| resolve.name_world_key(key)), + &format!("{name}_drop"), + key, + AbiVariant::GuestImport, + ) + } + Import::ExportedTaskReturn(key, interface, func) => { + let (options, _sig) = task_return_options_and_type(resolve, func); + let result_ty = func.result; + if options.is_empty() || self.memory_index.is_some() { + // Note that an "import type encoder" is used here despite + // this being for an exported function if the `interface` + // is none, meaning that this is for a top-level world + // function. In that situation all types that can be + // referred to are imported, not exported. + let mut encoder = if interface.is_none() { + self.root_import_type_encoder(*interface) + } else { + self.root_export_type_encoder(*interface) + }; + + let result = match result_ty.as_ref() { + Some(ty) => Some(encoder.encode_valtype(resolve, ty)?), + None => None, + }; + let metadata = &self.info.module_metadata_for(for_module); + let encoding = metadata + .export_encodings + .get(resolve, key, &func.name) + .ok_or_else(|| { + anyhow!("missing component metadata for export of `{}`", func.name) + })?; + let options = options + .into_iter(encoding, self.memory_index, None)? + .collect::>(); + let index = self.component.task_return(result, options); + Ok((ExportKind::Func, index)) + } else { + let metadata = &self.info.module_metadata_for(for_module); + let encoding = metadata + .export_encodings + .get(resolve, key, &func.name) + .unwrap(); + Ok(self.materialize_shim_import( + shims, + &ShimKind::TaskReturn { + for_module, + interface: *interface, + func: &func.name, + result: result_ty, + encoding, + }, + )) + } + } + Import::BackpressureInc => { + let index = self.component.backpressure_inc(); + Ok((ExportKind::Func, index)) + } + Import::BackpressureDec => { + let index = self.component.backpressure_dec(); + Ok((ExportKind::Func, index)) + } + Import::WaitableSetWait { cancellable } => { + if let Some(memory) = self.memory_index { + let index = self.component.waitable_set_wait(*cancellable, memory); + return Ok((ExportKind::Func, index)); + } + Ok(self.materialize_shim_import( + shims, + &ShimKind::WaitableSetWait { + cancellable: *cancellable, + }, + )) + } + Import::WaitableSetPoll { cancellable } => { + if let Some(memory) = self.memory_index { + let index = self.component.waitable_set_poll(*cancellable, memory); + return Ok((ExportKind::Func, index)); + } + Ok(self.materialize_shim_import( + shims, + &ShimKind::WaitableSetPoll { + cancellable: *cancellable, + }, + )) + } + Import::SubtaskDrop => { + let index = self.component.subtask_drop(); + Ok((ExportKind::Func, index)) + } + Import::SubtaskCancel { async_ } => { + let index = self.component.subtask_cancel(*async_); + Ok((ExportKind::Func, index)) + } + Import::StreamNew(info) => { + let ty = self.payload_type_index(info)?; + let index = self.component.stream_new(ty); + Ok((ExportKind::Func, index)) + } + Import::StreamRead { info, async_ } => self.materialize_payload_import( + shims, + for_module, + info, + PayloadFuncKind::StreamRead, + *async_, + ), + Import::StreamWrite { info, async_ } => self.materialize_payload_import( + shims, + for_module, + info, + PayloadFuncKind::StreamWrite, + *async_, + ), + Import::StreamCancelRead { info, async_ } => { + let ty = self.payload_type_index(info)?; + let index = self.component.stream_cancel_read(ty, *async_); + Ok((ExportKind::Func, index)) + } + Import::StreamCancelWrite { info, async_ } => { + let ty = self.payload_type_index(info)?; + let index = self.component.stream_cancel_write(ty, *async_); + Ok((ExportKind::Func, index)) + } + Import::StreamDropReadable(info) => { + let type_index = self.payload_type_index(info)?; + let index = self.component.stream_drop_readable(type_index); + Ok((ExportKind::Func, index)) + } + Import::StreamDropWritable(info) => { + let type_index = self.payload_type_index(info)?; + let index = self.component.stream_drop_writable(type_index); + Ok((ExportKind::Func, index)) + } + Import::FutureNew(info) => { + let ty = self.payload_type_index(info)?; + let index = self.component.future_new(ty); + Ok((ExportKind::Func, index)) + } + Import::FutureRead { info, async_ } => self.materialize_payload_import( + shims, + for_module, + info, + PayloadFuncKind::FutureRead, + *async_, + ), + Import::FutureWrite { info, async_ } => self.materialize_payload_import( + shims, + for_module, + info, + PayloadFuncKind::FutureWrite, + *async_, + ), + Import::FutureCancelRead { info, async_ } => { + let ty = self.payload_type_index(info)?; + let index = self.component.future_cancel_read(ty, *async_); + Ok((ExportKind::Func, index)) + } + Import::FutureCancelWrite { info, async_ } => { + let ty = self.payload_type_index(info)?; + let index = self.component.future_cancel_write(ty, *async_); + Ok((ExportKind::Func, index)) + } + Import::FutureDropReadable(info) => { + let type_index = self.payload_type_index(info)?; + let index = self.component.future_drop_readable(type_index); + Ok((ExportKind::Func, index)) + } + Import::FutureDropWritable(info) => { + let type_index = self.payload_type_index(info)?; + let index = self.component.future_drop_writable(type_index); + Ok((ExportKind::Func, index)) + } + Import::ErrorContextNew { encoding } => { + if self.memory_index.is_some() { + let options = (RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING) + .into_iter(*encoding, self.memory_index, None)?; + let index = self.component.error_context_new(options); + return Ok((ExportKind::Func, index)); + } + Ok(self.materialize_shim_import( + shims, + &ShimKind::ErrorContextNew { + encoding: *encoding, + }, + )) + } + Import::ErrorContextDebugMessage { encoding } => Ok(self.materialize_shim_import( + shims, + &ShimKind::ErrorContextDebugMessage { + for_module, + encoding: *encoding, + }, + )), + Import::ErrorContextDrop => { + let index = self.component.error_context_drop(); + Ok((ExportKind::Func, index)) + } + Import::WorldFunc(key, name, abi) => { + self.materialize_wit_import(shims, for_module, None, name, key, *abi) + } + Import::InterfaceFunc(key, _, name, abi) => self.materialize_wit_import( + shims, + for_module, + Some(resolve.name_world_key(key)), + name, + key, + *abi, + ), + + Import::WaitableSetNew => { + let index = self.component.waitable_set_new(); + Ok((ExportKind::Func, index)) + } + Import::WaitableSetDrop => { + let index = self.component.waitable_set_drop(); + Ok((ExportKind::Func, index)) + } + Import::WaitableJoin => { + let index = self.component.waitable_join(); + Ok((ExportKind::Func, index)) + } + Import::ContextGet { ty, slot } => { + let index = self.component.context_get((*ty).try_into()?, *slot); + Ok((ExportKind::Func, index)) + } + Import::ContextSet { ty, slot } => { + let index = self.component.context_set((*ty).try_into()?, *slot); + Ok((ExportKind::Func, index)) + } + Import::TlsBaseGet { ty } => Ok(( + ExportKind::Func, + self.materialize_tls_base_import(false, (*ty).try_into()?), + )), + Import::TlsBaseSet { ty } => Ok(( + ExportKind::Func, + self.materialize_tls_base_import(true, (*ty).try_into()?), + )), + Import::ExportedTaskCancel => { + let index = self.component.task_cancel(); + Ok((ExportKind::Func, index)) + } + Import::ThreadIndex => { + let index = self.component.thread_index(); + Ok((ExportKind::Func, index)) + } + Import::ThreadNewIndirect => Ok(self.materialize_shim_import( + shims, + &ShimKind::ThreadNewIndirect { + // This is fixed for now + func_ty: FuncType::new([ValType::I32], []), + }, + )), + Import::ThreadResumeLater => { + let index = self.component.thread_resume_later(); + Ok((ExportKind::Func, index)) + } + Import::ThreadSuspend { cancellable } => { + let index = self.component.thread_suspend(*cancellable); + Ok((ExportKind::Func, index)) + } + Import::ThreadYield { cancellable } => { + let index = self.component.thread_yield(*cancellable); + Ok((ExportKind::Func, index)) + } + Import::ThreadSuspendThenResume { cancellable } => { + let index = self.component.thread_suspend_then_resume(*cancellable); + Ok((ExportKind::Func, index)) + } + Import::ThreadYieldThenResume { cancellable } => { + let index = self.component.thread_yield_then_resume(*cancellable); + Ok((ExportKind::Func, index)) + } + Import::ThreadSuspendThenPromote { cancellable } => { + let index = self.component.thread_suspend_then_promote(*cancellable); + Ok((ExportKind::Func, index)) + } + Import::ThreadYieldThenPromote { cancellable } => { + let index = self.component.thread_yield_then_promote(*cancellable); + Ok((ExportKind::Func, index)) + } + } + } + + /// Helper to satisfy `__wasm_{get,set}_tls_base` imports. + /// + /// For more information on this see WebAssembly/wasi-libc#857 + fn materialize_tls_base_import(&mut self, set: bool, ty: ValType) -> u32 { + if self.info.can_use_context_slot_1() { + if set { + self.component.context_set(ty, 1) + } else { + self.component.context_get(ty, 1) + } + } else { + let name = if set { TLS_BASE_SET } else { TLS_BASE_GET }; + self.core_alias_export( + Some(name), + self.shim_instance_index.unwrap(), + name, + ExportKind::Func, + ) + } + } + + /// Helper for `materialize_import` above for materializing functions that + /// are part of the "shim module" generated. + fn materialize_shim_import(&mut self, shims: &Shims<'_>, kind: &ShimKind) -> (ExportKind, u32) { + let index = self.core_alias_export( + Some(&shims.shims[kind].debug_name), + self.shim_instance_index + .expect("shim should be instantiated"), + &shims.shims[kind].name, + ExportKind::Func, + ); + (ExportKind::Func, index) + } + + /// Helper for `materialize_import` above for generating imports for + /// future/stream read/write intrinsics. + fn materialize_payload_import( + &mut self, + shims: &Shims<'_>, + for_module: CustomModule<'_>, + info: &PayloadInfo, + kind: PayloadFuncKind, + async_: bool, + ) -> Result<(ExportKind, u32)> { + let shim_kind = ShimKind::PayloadFunc { + for_module, + info, + kind, + }; + if shims.shims.get(&shim_kind).is_some() { + return Ok(self.materialize_shim_import(shims, &shim_kind)); + } + let resolve = &self.info.encoder.metadata.resolve; + let options = RequiredOptions::for_payload(resolve, info, &kind, async_); + let func = self.encode_payload_func( + shims, + &for_module, + info, + &kind, + options, + ReallocSite::BeforeInstantiation, + )?; + Ok((ExportKind::Func, func)) + } + + /// Helper for `materialize_import` above which specifically operates on + /// WIT-level functions identified by `interface_key`, `name`, and `abi`. + fn materialize_wit_import( + &mut self, + shims: &Shims<'_>, + for_module: CustomModule<'_>, + interface_key: Option, + name: &String, + key: &WorldKey, + abi: AbiVariant, + ) -> Result<(ExportKind, u32)> { + let resolve = &self.info.encoder.metadata.resolve; + let import = &self.info.import_map[&interface_key]; + let (index, _, lowering) = import.lowerings.get_full(&(name.clone(), abi)).unwrap(); + let metadata = self.info.module_metadata_for(for_module); + + let index = match lowering { + // All direct lowerings can be `canon lower`'d here immediately + // and passed as arguments. + Lowering::Direct { options } => { + let func_index = match &import.interface { + Some(interface) => { + let instance_index = self.instances[interface]; + self.component + .alias_export(instance_index, name, ComponentExportKind::Func) + } + None => self.imported_funcs[name], + }; + let encoding = metadata + .import_encodings + .get(resolve, key, name) + .ok_or_else(|| anyhow!("missing component metadata for import of `{name}`"))?; + let realloc = self + .info + .exports_for(for_module) + .import_realloc_for(import.interface, name); + let realloc = self.realloc_index( + shims, + for_module, + ReallocSite::BeforeInstantiation, + *options, + realloc, + ); + let options = options + .into_iter(encoding, self.memory_index, realloc)? + .collect::>(); + self.component.lower_func(Some(name), func_index, options) + } + + // Indirect lowerings come from the shim that was previously + // created, so the specific export is loaded here and used as an + // import. + Lowering::Indirect { .. } => { + let encoding = metadata.import_encodings.get(resolve, key, name).unwrap(); + return Ok(self.materialize_shim_import( + shims, + &ShimKind::IndirectLowering { + interface: interface_key, + index, + realloc: for_module, + encoding, + }, + )); + } + + // A "resource drop" intrinsic only needs to find the index of the + // resource type itself and then the intrinsic is declared. + Lowering::ResourceDrop(id) => { + let resource_idx = self.lookup_resource_index(*id); + self.component.resource_drop(resource_idx) + } + }; + Ok((ExportKind::Func, index)) + } + + /// Returns the core function index to use for the `realloc` canonical + /// option where the function is named `export` within `module`. + fn realloc_index( + &mut self, + shims: &Shims<'_>, + module: CustomModule<'_>, + site: ReallocSite, + options: RequiredOptions, + export: Option<&str>, + ) -> Option { + if !options.contains(RequiredOptions::REALLOC) { + return None; + } + let (module, export) = resolve_realloc(self.info, module, export)?; + + if !realloc_needs_shim(self.info, site) { + let instance = self.instance_for(module); + return Some(self.core_alias_export(Some(export), instance, export, ExportKind::Func)); + } + + let kind = ShimKind::Realloc { module, export }; + let shim = shims.shims.get(&kind).unwrap_or_else(|| { + panic!( + "no shim was registered for the `realloc` \ + function `{export}` in `{}`", + module.debug_name() + ) + }); + let instance = self + .shim_instance_index + .expect("shim should be instantiated"); + Some(self.core_alias_export( + Some(&shim.debug_name), + instance, + &shim.name, + ExportKind::Func, + )) + } + + fn hooked_core_alias_export(&mut self, module: CustomModule<'_>, core_name: &str) -> u32 { + let key = (module.to_imported_instance(), core_name.to_string()); + if let Some(&wrapper_idx) = self.export_task_initialization_wrappers.get(&key) { + wrapper_idx + } else { + let instance = self.instance_for(module); + self.core_alias_export(Some(core_name), instance, core_name, ExportKind::Func) + } + } + + /// Convenience function to go from `CustomModule` to the instance index + /// corresponding to what that points to. + fn instance_for(&self, module: CustomModule) -> u32 { + match module { + CustomModule::Main => self.instance_index.expect("instantiated by now"), + CustomModule::Adapter(name) => self.adapter_instances[name], + } + } + + /// Convenience function to go from `CustomModule` to the module index + /// corresponding to what that points to. + fn module_for(&self, module: CustomModule) -> u32 { + match module { + CustomModule::Main => self.module_index.unwrap(), + CustomModule::Adapter(name) => self.adapter_modules[name], + } + } + + /// Convenience function which caches aliases created so repeated calls to + /// this function will all return the same index. + fn core_alias_export( + &mut self, + debug_name: Option<&str>, + instance: u32, + name: &str, + kind: ExportKind, + ) -> u32 { + *self + .aliased_core_items + .entry((instance, name.to_string())) + .or_insert_with(|| { + self.component + .core_alias_export(debug_name, instance, name, kind) + }) + } +} + +/// A list of "shims" which start out during the component instantiation process +/// as functions which immediately trap due to a `call_indirect`-to-`null` but +/// will get filled in by the time the component instantiation process +/// completes. +/// +/// Shims currently include: +/// +/// * "Indirect functions" lowered from imported instances where the lowering +/// requires an item exported from the main module. These are indirect due to +/// the circular dependency between the module needing an import and the +/// import needing the module. +/// +/// * Adapter modules which convert from a historical ABI to the component +/// model's ABI (e.g. wasi preview1 to preview2) get a shim since the adapters +/// are currently indicated as always requiring the memory of the main module. +/// +/// This structure is created by `encode_shim_instantiation`. +#[derive(Default)] +struct Shims<'a> { + /// The list of all shims that a module will require. + shims: IndexMap, Shim<'a>>, +} + +struct Shim<'a> { + /// Canonical ABI options required by this shim, used during `canon lower` + /// operations. + options: RequiredOptions, + + /// The name, in the shim instance, of this shim. + /// + /// Currently this is `"0"`, `"1"`, ... + name: String, + + /// A human-readable debugging name for this shim, used in a core wasm + /// `name` section. + debug_name: String, + + /// Precise information about what this shim is a lowering of. + kind: ShimKind<'a>, + + /// Wasm type of this shim. + sig: WasmSignature, +} + +/// Which variation of `{stream|future}.{read|write}` we're emitting for a +/// `ShimKind::PayloadFunc`. +#[derive(Debug, Clone, Hash, Eq, PartialEq, Copy)] +enum PayloadFuncKind { + FutureWrite, + FutureRead, + StreamWrite, + StreamRead, +} + +#[derive(Debug, Clone, Hash, Eq, PartialEq)] +enum ShimKind<'a> { + /// This shim is a late indirect lowering of an imported function in a + /// component which is only possible after prior core wasm modules are + /// instantiated so their memories and functions are available. + IndirectLowering { + /// The name of the interface that's being lowered. + interface: Option, + /// The index within the `lowerings` array of the function being lowered. + index: usize, + /// Which instance to pull the `realloc` function from, if necessary. + realloc: CustomModule<'a>, + /// The string encoding that this lowering is going to use. + encoding: StringEncoding, + }, + /// This shim is a core wasm function defined in an adapter module but isn't + /// available until the adapter module is itself instantiated. + Adapter { + /// The name of the adapter module this shim comes from. + adapter: &'a str, + /// The name of the export in the adapter module this shim points to. + func: &'a str, + }, + /// A shim used as the destructor for a resource which allows defining the + /// resource before the core module being instantiated. + ResourceDtor { + /// Which instance to pull the destructor function from. + module: CustomModule<'a>, + /// The exported function name of this destructor in the core module. + export: &'a str, + }, + /// A shim used for a `{stream|future}.{read|write}` built-in function, + /// which must refer to the core module instance's memory from/to which + /// payload values must be lifted/lowered. + PayloadFunc { + /// Which instance to pull the `realloc` function and string encoding + /// from, if necessary. + for_module: CustomModule<'a>, + /// Additional information regarding the function where this `stream` or + /// `future` type appeared, which we use in combination with + /// `for_module` to determine which `realloc` and string encoding to + /// use, as well as which type to specify when emitting the built-in. + info: &'a PayloadInfo, + /// Which variation of `{stream|future}.{read|write}` we're emitting. + kind: PayloadFuncKind, + }, + /// A shim used for the `waitable-set.wait` built-in function, which must + /// refer to the core module instance's memory to which results will be + /// written. + WaitableSetWait { cancellable: bool }, + /// A shim used for the `waitable-set.poll` built-in function, which must + /// refer to the core module instance's memory to which results will be + /// written. + WaitableSetPoll { cancellable: bool }, + /// Shim for `task.return` to handle a reference to a `memory` which may + TaskReturn { + /// The interface (optional) that owns `func` below. If `None` then it's + /// a world export. + interface: Option, + /// The function that this `task.return` is returning for, owned + /// within `interface` above. + func: &'a str, + /// The WIT type that `func` returns. + result: Option, + /// Which instance to pull the `realloc` function from, if necessary. + for_module: CustomModule<'a>, + /// String encoding to use in the ABI options. + encoding: StringEncoding, + }, + /// A shim used for the `error-context.new` built-in function, which must + /// refer to the core module instance's memory from which the debug message + /// will be read. + ErrorContextNew { + /// String encoding to use when lifting the debug message. + encoding: StringEncoding, + }, + /// A shim used for the `error-context.debug-message` built-in function, + /// which must refer to the core module instance's memory to which results + /// will be written. + ErrorContextDebugMessage { + /// Which instance to pull the `realloc` function from, if necessary. + for_module: CustomModule<'a>, + /// The string encoding to use when lowering the debug message. + encoding: StringEncoding, + }, + /// A shim used for the `thread.new-indirect` built-in function, which + /// must refer to the core module instance's indirect function table. + ThreadNewIndirect { + /// The function type to use when creating the thread. + func_ty: FuncType, + }, + /// A shim for a `realloc` function used as a canonical option. + Realloc { + /// Which instance the `realloc` function is exported from. + module: CustomModule<'a>, + /// The name of the `realloc` export within `module`. + export: &'a str, + }, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +enum ReallocSite { + /// This `realloc` is needed before the main module is instantiated. + BeforeInstantiation, + /// This `realloc` is needed after the main module is instantiated, but + /// before the fixup module is instantiated. + AfterInstantiation, +} + +fn realloc_needs_shim(world: &ComponentWorld<'_>, site: ReallocSite) -> bool { + match site { + // The function isn't available at all yet, so an indirection is + // required no matter what. + ReallocSite::BeforeInstantiation => true, + + // The function itself is available, but if task hooks are enabled then + // the hooked version of it is defined by the fixup module which hasn't + // been instantiated yet. + ReallocSite::AfterInstantiation => world.info.exports.wasm_task_hook().is_some(), + } +} + +/// Indicator for which module is being used for a lowering or where options +/// like `realloc` are drawn from. +/// +/// This is necessary for situations such as an imported function being lowered +/// into the main module and additionally into an adapter module. For example an +/// adapter might adapt from preview1 to preview2 for the standard library of a +/// programming language but the main module's custom application code may also +/// explicitly import from preview2. These two different lowerings of a preview2 +/// function are parameterized by this enumeration. +#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] +enum CustomModule<'a> { + /// This points to the "main module" which is generally the "output of LLVM" + /// or what a user wrote. + Main, + /// This is selecting an adapter module, identified by name here, where + /// something is being lowered into. + Adapter(&'a str), +} + +impl<'a> CustomModule<'a> { + fn debug_name(&self) -> &'a str { + match self { + CustomModule::Main => "main", + CustomModule::Adapter(s) => s, + } + } + + /// Returns the instance, as imported into the fixup module, that this + /// module corresponds to. + fn to_imported_instance(&self) -> fixup::ImportedInstance { + match self { + CustomModule::Main => fixup::ImportedInstance::Main, + CustomModule::Adapter(s) => fixup::ImportedInstance::Adapter(s.to_string()), + } + } +} + +impl<'a> Shims<'a> { + /// Adds all shims necessary for the instantiation of `for_module`. + /// + /// This function will iterate over all the imports required by this module + /// and for those that require a shim they're registered here. + fn append_indirect( + &mut self, + world: &'a ComponentWorld<'a>, + for_module: CustomModule<'a>, + ) -> Result<()> { + let module_imports = world.imports_for(for_module); + let module_exports = world.exports_for(for_module); + let resolve = &world.encoder.metadata.resolve; + let memory_available = world.info.imports.imported_memory().is_some(); + + for (module, field, import) in module_imports.imports() { + match import { + // These imports don't require shims, they can be satisfied + // as-needed when required. + Import::ImportedResourceDrop(..) + | Import::MainModuleMemory(_) + | Import::MainModuleExport { .. } + | Import::Item(_) + | Import::ExportedResourceDrop(..) + | Import::ExportedResourceRep(..) + | Import::ExportedResourceNew(..) + | Import::ExportedTaskCancel + | Import::ErrorContextDrop + | Import::BackpressureInc + | Import::BackpressureDec + | Import::SubtaskDrop + | Import::SubtaskCancel { .. } + | Import::FutureNew(..) + | Import::StreamNew(..) + | Import::FutureCancelRead { .. } + | Import::FutureCancelWrite { .. } + | Import::FutureDropWritable { .. } + | Import::FutureDropReadable { .. } + | Import::StreamCancelRead { .. } + | Import::StreamCancelWrite { .. } + | Import::StreamDropWritable { .. } + | Import::StreamDropReadable { .. } + | Import::WaitableSetNew + | Import::WaitableSetDrop + | Import::WaitableJoin + | Import::ContextGet { .. } + | Import::ContextSet { .. } + | Import::TlsBaseGet { .. } + | Import::TlsBaseSet { .. } + | Import::ThreadIndex + | Import::ThreadResumeLater + | Import::ThreadSuspend { .. } + | Import::ThreadYield { .. } + | Import::ThreadSuspendThenResume { .. } + | Import::ThreadYieldThenResume { .. } + | Import::ThreadSuspendThenPromote { .. } + | Import::ThreadYieldThenPromote { .. } => {} + + // If `task.return` needs to be indirect then generate a shim + // for it, otherwise skip the shim and let it get materialized + // naturally later. + Import::ExportedTaskReturn(key, interface, func) => { + let (options, sig) = task_return_options_and_type(resolve, func); + if options.is_empty() || memory_available { + continue; + } + let name = self.shims.len().to_string(); + let encoding = world + .module_metadata_for(for_module) + .export_encodings + .get(resolve, key, &func.name) + .ok_or_else(|| { + anyhow::anyhow!( + "missing component metadata for export of \ + `{module}::{field}`" + ) + })?; + self.push(Shim { + name, + debug_name: format!("task-return-{}", func.name), + options, + kind: ShimKind::TaskReturn { + interface: *interface, + func: &func.name, + result: func.result, + for_module, + encoding, + }, + sig, + }); + } + + Import::FutureWrite { async_, info } => { + self.append_indirect_payload_push( + world, + for_module, + module, + *async_, + info, + PayloadFuncKind::FutureWrite, + vec![WasmType::I32; 2], + vec![WasmType::I32], + ); + } + Import::FutureRead { async_, info } => { + self.append_indirect_payload_push( + world, + for_module, + module, + *async_, + info, + PayloadFuncKind::FutureRead, + vec![WasmType::I32; 2], + vec![WasmType::I32], + ); + } + Import::StreamWrite { async_, info } => { + self.append_indirect_payload_push( + world, + for_module, + module, + *async_, + info, + PayloadFuncKind::StreamWrite, + vec![WasmType::I32; 3], + vec![WasmType::I32], + ); + } + Import::StreamRead { async_, info } => { + self.append_indirect_payload_push( + world, + for_module, + module, + *async_, + info, + PayloadFuncKind::StreamRead, + vec![WasmType::I32; 3], + vec![WasmType::I32], + ); + } + + Import::WaitableSetWait { cancellable } => { + if memory_available { + continue; + } + let name = self.shims.len().to_string(); + self.push(Shim { + name, + debug_name: "waitable-set.wait".to_string(), + options: RequiredOptions::empty(), + kind: ShimKind::WaitableSetWait { + cancellable: *cancellable, + }, + sig: WasmSignature { + params: vec![WasmType::I32; 2], + results: vec![WasmType::I32], + indirect_params: false, + retptr: false, + }, + }); + } + + Import::WaitableSetPoll { cancellable } => { + if memory_available { + continue; + } + let name = self.shims.len().to_string(); + self.push(Shim { + name, + debug_name: "waitable-set.poll".to_string(), + options: RequiredOptions::empty(), + kind: ShimKind::WaitableSetPoll { + cancellable: *cancellable, + }, + sig: WasmSignature { + params: vec![WasmType::I32; 2], + results: vec![WasmType::I32], + indirect_params: false, + retptr: false, + }, + }); + } + + Import::ErrorContextNew { encoding } => { + if memory_available { + continue; + } + let name = self.shims.len().to_string(); + self.push(Shim { + name, + debug_name: "error-new".to_string(), + options: RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING, + kind: ShimKind::ErrorContextNew { + encoding: *encoding, + }, + sig: WasmSignature { + params: vec![WasmType::I32; 2], + results: vec![WasmType::I32], + indirect_params: false, + retptr: false, + }, + }); + } + + Import::ErrorContextDebugMessage { encoding } => { + let name = self.shims.len().to_string(); + let options = RequiredOptions::MEMORY + | RequiredOptions::STRING_ENCODING + | RequiredOptions::REALLOC; + self.push(Shim { + name, + debug_name: "error-debug-message".to_string(), + options, + kind: ShimKind::ErrorContextDebugMessage { + for_module, + encoding: *encoding, + }, + sig: WasmSignature { + params: vec![WasmType::I32; 2], + results: vec![], + indirect_params: false, + retptr: false, + }, + }); + let realloc = module_exports.import_realloc_fallback(); + self.push_realloc( + world, + for_module, + ReallocSite::AfterInstantiation, + options, + realloc, + ); + } + + Import::ThreadNewIndirect => { + let name = self.shims.len().to_string(); + self.push(Shim { + name, + debug_name: "thread.new-indirect".to_string(), + options: RequiredOptions::empty(), + kind: ShimKind::ThreadNewIndirect { + // This is fixed for now + func_ty: FuncType::new([ValType::I32], vec![]), + }, + sig: WasmSignature { + params: vec![WasmType::I32; 2], + results: vec![WasmType::I32], + indirect_params: false, + retptr: false, + }, + }); + } + + // Adapter imports into the main module must got through an + // indirection, so that's registered here. + Import::AdapterExport { adapter, func, ty } => { + let name = self.shims.len().to_string(); + log::debug!("shim {name} is adapter `{module}::{field}`"); + self.push(Shim { + name, + debug_name: format!("adapt-{module}-{field}"), + // Pessimistically assume that all adapters require + // memory in one form or another. While this isn't + // technically true it's true enough for WASI. + options: RequiredOptions::MEMORY, + kind: ShimKind::Adapter { adapter, func }, + sig: WasmSignature { + params: ty.params().iter().map(to_wasm_type).collect(), + results: ty.results().iter().map(to_wasm_type).collect(), + indirect_params: false, + retptr: false, + }, + }); + + fn to_wasm_type(ty: &wasmparser::ValType) -> WasmType { + match ty { + wasmparser::ValType::I32 => WasmType::I32, + wasmparser::ValType::I64 => WasmType::I64, + wasmparser::ValType::F32 => WasmType::F32, + wasmparser::ValType::F64 => WasmType::F64, + _ => unreachable!(), + } + } + } + + // WIT-level functions may require an indirection, so yield some + // metadata out of this `match` to the loop below to figure that + // out. + Import::InterfaceFunc(key, _, name, abi) => { + self.append_indirect_wit_func( + world, + for_module, + module, + field, + key, + name, + Some(resolve.name_world_key(key)), + *abi, + )?; + } + Import::WorldFunc(key, name, abi) => { + self.append_indirect_wit_func( + world, for_module, module, field, key, name, None, *abi, + )?; + } + } + } + + // In addition to all the shims added for imports above this module also + // requires shims for resource destructors that it exports. Resource + // types are declared before the module is instantiated so the actual + // destructor is registered as a shim (defined here) and it's then + // filled in with the module's exports later. + for (export_name, export) in module_exports.iter() { + let id = match export { + Export::ResourceDtor(id) => id, + _ => continue, + }; + let resource = resolve.types[*id].name.as_ref().unwrap(); + let name = self.shims.len().to_string(); + self.push(Shim { + name, + debug_name: format!("dtor-{resource}"), + options: RequiredOptions::empty(), + kind: ShimKind::ResourceDtor { + module: for_module, + export: export_name, + }, + sig: WasmSignature { + params: vec![WasmType::I32], + results: Vec::new(), + indirect_params: false, + retptr: false, + }, + }); + } + + Ok(()) + } + + /// Helper of `append_indirect` above which pushes information for + /// futures/streams read/write intrinsics. + fn append_indirect_payload_push( + &mut self, + world: &'a ComponentWorld<'a>, + for_module: CustomModule<'a>, + module: &str, + async_: bool, + info: &'a PayloadInfo, + kind: PayloadFuncKind, + params: Vec, + results: Vec, + ) { + let resolve = &world.encoder.metadata.resolve; + let debug_name = format!("{module}-{}", info.name); + let name = self.shims.len().to_string(); + + let options = RequiredOptions::for_payload(resolve, info, &kind, async_); + if !options.contains(RequiredOptions::REALLOC) + && world.info.imports.imported_memory().is_some() + { + return; + } + self.push(Shim { + name, + debug_name, + options, + kind: ShimKind::PayloadFunc { + for_module, + info, + kind, + }, + sig: WasmSignature { + params, + results, + indirect_params: false, + retptr: false, + }, + }); + let realloc = payload_realloc_name(world, for_module, info); + self.push_realloc( + world, + for_module, + ReallocSite::AfterInstantiation, + options, + realloc, + ); + } + + /// Helper for `append_indirect` above which will conditionally push a shim + /// for the WIT function specified by `interface_key`, `name`, and `abi`. + fn append_indirect_wit_func( + &mut self, + world: &'a ComponentWorld<'a>, + for_module: CustomModule<'a>, + module: &str, + field: &str, + key: &WorldKey, + name: &String, + interface_key: Option, + abi: AbiVariant, + ) -> Result<()> { + let resolve = &world.encoder.metadata.resolve; + let metadata = world.module_metadata_for(for_module); + let interface = &world.import_map[&interface_key]; + let (index, _, lowering) = interface.lowerings.get_full(&(name.clone(), abi)).unwrap(); + let shim_name = self.shims.len().to_string(); + match lowering { + Lowering::ResourceDrop(_) => {} + + Lowering::Direct { options } => { + let realloc = world + .exports_for(for_module) + .import_realloc_for(interface.interface, name); + self.push_realloc( + world, + for_module, + ReallocSite::BeforeInstantiation, + *options, + realloc, + ); + } + + Lowering::Indirect { sig, options } => { + log::debug!( + "shim {shim_name} is import `{module}::{field}` lowering {index} `{name}`", + ); + let encoding = metadata + .import_encodings + .get(resolve, key, name) + .ok_or_else(|| { + anyhow::anyhow!( + "missing component metadata for import of \ + `{module}::{field}`" + ) + })?; + self.push(Shim { + name: shim_name, + debug_name: format!("indirect-{module}-{field}"), + options: *options, + kind: ShimKind::IndirectLowering { + interface: interface_key, + index, + realloc: for_module, + encoding, + }, + sig: sig.clone(), + }); + + let realloc = world + .exports_for(for_module) + .import_realloc_for(interface.interface, name); + self.push_realloc( + world, + for_module, + ReallocSite::AfterInstantiation, + *options, + realloc, + ); + } + } + + Ok(()) + } + + /// Registers a shim, if one is necessary, for the `realloc` function named + /// `export` within `for_module` which is going to be used at `site` by + /// something requiring `options`. + fn push_realloc( + &mut self, + world: &'a ComponentWorld<'a>, + for_module: CustomModule<'a>, + site: ReallocSite, + options: RequiredOptions, + export: Option<&'a str>, + ) { + if !options.contains(RequiredOptions::REALLOC) { + return; + } + let Some((for_module, export)) = resolve_realloc(world, for_module, export) else { + return; + }; + if !realloc_needs_shim(world, site) { + return; + } + let name = self.shims.len().to_string(); + self.push(Shim { + name, + debug_name: format!("realloc-{}-{export}", for_module.debug_name()), + options: RequiredOptions::empty(), + kind: ShimKind::Realloc { + module: for_module, + export, + }, + sig: WasmSignature { + params: vec![WasmType::I32; 4], + results: vec![WasmType::I32], + indirect_params: false, + retptr: false, + }, + }); + } + + fn push(&mut self, shim: Shim<'a>) { + // Only one shim per `ShimKind` is retained, so if it's already present + // don't overwrite it. If it's not present though go ahead and insert + // it. + if !self.shims.contains_key(&shim.kind) { + self.shims.insert(shim.kind.clone(), shim); + } + } +} + +/// Resolves which module, and which export of it, provides the `realloc` +/// canonical option for `module`, where `export` is `module`'s own realloc +/// export if it has one. +/// +/// Libraries in a shared-everything link which don't export a realloc of their +/// own fall back to the one shared by the rest of the link +fn resolve_realloc<'a>( + world: &'a ComponentWorld<'a>, + module: CustomModule<'a>, + export: Option<&'a str>, +) -> Option<(CustomModule<'a>, &'a str)> { + if let Some(export) = export { + return Some((module, export)); + } + match module { + // If the main module doesn't have a realloc, then there's nothing to + // use. + CustomModule::Main => None, + + // For libraries fallback to the realloc in the main module, if present. + CustomModule::Adapter(name) => { + let _info = world.adapters[name].library_info.as_ref()?; + let main_realloc = world.info.exports.general_purpose_realloc()?; + Some((CustomModule::Main, main_realloc)) + } + } +} + +fn payload_realloc_name<'a>( + world: &'a ComponentWorld<'_>, + for_module: CustomModule<'_>, + info: &PayloadInfo, +) -> Option<&'a str> { + let exports = world.exports_for(for_module); + match &info.ty { + PayloadType::Type { function, .. } => { + if info.imported { + exports.import_realloc_for(info.interface, function) + } else { + exports.export_realloc_for(&info.key, function) + } + } + PayloadType::UnitFuture | PayloadType::UnitStream => None, + } +} + +fn task_return_options_and_type( + resolve: &Resolve, + func: &Function, +) -> (RequiredOptions, WasmSignature) { + let func_tmp = Function { + name: String::new(), + kind: FunctionKind::Freestanding, + params: match &func.result { + Some(ty) => vec![Param { + name: "a".to_string(), + ty: *ty, + span: Default::default(), + }], + None => Vec::new(), + }, + result: None, + docs: Default::default(), + stability: Stability::Unknown, + span: Default::default(), + external_id: None, + }; + let abi = AbiVariant::GuestImport; + let mut options = RequiredOptions::for_import(resolve, func, abi); + // `task.return` does not support a `realloc` canonical option. + options.remove(RequiredOptions::REALLOC); + let sig = resolve.wasm_signature(abi, &func_tmp); + (options, sig) +} + +/// Alias argument to an instantiation +#[derive(Clone, Debug)] +pub struct Item { + pub alias: String, + pub kind: ExportKind, + pub which: MainOrAdapter, + pub name: String, +} + +/// Module argument to an instantiation +#[derive(Debug, PartialEq, Clone)] +pub enum MainOrAdapter { + Main, + Adapter(String), +} + +impl MainOrAdapter { + fn to_custom_module(&self) -> CustomModule<'_> { + match self { + MainOrAdapter::Main => CustomModule::Main, + MainOrAdapter::Adapter(s) => CustomModule::Adapter(s), + } + } +} + +/// Module instantiation argument +#[derive(Clone)] +pub enum Instance { + /// Module argument + MainOrAdapter(MainOrAdapter), + + /// Alias argument + Items(Vec), +} + +/// Provides fine-grained control of how a library module is instantiated +/// relative to other module instances +#[derive(Clone)] +pub struct LibraryInfo { + /// Instantiation arguments + pub arguments: Vec<(String, Instance)>, +} + +/// Represents an adapter or library to be instantiated as part of the component +pub(super) struct Adapter { + /// The wasm of the module itself, with `component-type` sections stripped + wasm: Vec, + + /// The metadata for the adapter + metadata: ModuleMetadata, + + /// The set of exports from the final world which are defined by this + /// adapter or library + required_exports: IndexSet, + + /// If present, treat this module as a library rather than a "minimal" adapter + /// + /// TODO: We should refactor how various flavors of module are represented + /// and differentiated to avoid mistaking one for another. + library_info: Option, +} + +/// An encoder of components based on `wit` interface definitions. +#[derive(Default)] +pub struct ComponentEncoder { + module: Vec, + module_import_map: Option, + pub(super) metadata: Bindgen, + validate: bool, + pub(super) main_module_exports: IndexSet, + pub(super) adapters: IndexMap, + import_name_map: HashMap, + realloc_via_memory_grow: bool, + merge_imports_based_on_semver: Option, + pub(super) reject_legacy_names: bool, + debug_names: bool, + shim_return_call_ref: bool, +} + +impl ComponentEncoder { + /// Set the core module to encode as a component. + /// This method will also parse any component type information stored in custom sections + /// inside the module and add them as the interface, imports, and exports. + /// It will also add any producers information inside the component type information to the + /// core module. + pub fn module(&mut self, module: &[u8]) -> Result<&mut Self> { + let (wasm, metadata) = self.decode(module.as_ref())?; + let (wasm, module_import_map) = ModuleImportMap::new(wasm)?; + self.module = if let Some(producers) = &metadata.producers { + producers.add_to_wasm(&wasm)? + } else { + wasm.to_vec() + }; + let exports = self + .merge_metadata(metadata) + .context("failed merge WIT metadata for module with previous metadata")?; + self.main_module_exports.extend(exports); + self.module_import_map = module_import_map; + Ok(self) + } + + fn decode<'a>(&self, wasm: &'a [u8]) -> Result<(Cow<'a, [u8]>, Bindgen)> { + let (bytes, metadata) = metadata::decode(wasm)?; + match bytes { + Some(wasm) => Ok((Cow::Owned(wasm), metadata)), + None => Ok((Cow::Borrowed(wasm), metadata)), + } + } + + fn merge_metadata(&mut self, metadata: Bindgen) -> Result> { + self.metadata.merge(metadata) + } + + /// Sets whether or not the encoder will validate its output. + pub fn validate(&mut self, validate: bool) -> &mut Self { + self.validate = validate; + self + } + + /// Sets whether or not to generate debug names in the output component. + pub fn debug_names(&mut self, debug_names: bool) -> &mut Self { + self.debug_names = debug_names; + self + } + + /// Configures whether the shim module, if needed, will use + /// `return_call_ref` as opposed to the default `call_indirect`. + pub fn shim_return_call_ref(&mut self, enable: bool) -> &mut Self { + self.shim_return_call_ref = enable; + self + } + + /// Sets whether to merge imports based on semver to the specified value. + /// + /// This affects how when to WIT worlds are merged together, for example + /// from two different libraries, whether their imports are unified when the + /// semver version ranges for interface allow it. + /// + /// This is enabled by default. + pub fn merge_imports_based_on_semver(&mut self, merge: bool) -> &mut Self { + self.merge_imports_based_on_semver = Some(merge); + self + } + + /// Sets whether to reject the historical mangling/name scheme for core wasm + /// imports/exports as they map to the component model. + /// + /// The `wit-component` crate supported a different set of names prior to + /// WebAssembly/component-model#378 and this can be used to disable this + /// support. + /// + /// This is disabled by default. + pub fn reject_legacy_names(&mut self, reject: bool) -> &mut Self { + self.reject_legacy_names = reject; + self + } + + /// Specifies a new adapter which is used to translate from a historical + /// wasm ABI to the canonical ABI and the `interface` provided. + /// + /// This is primarily used to polyfill, for example, + /// `wasi_snapshot_preview1` with a component-model using interface. The + /// `name` provided is the module name of the adapter that is being + /// polyfilled, for example `"wasi_snapshot_preview1"`. + /// + /// The `bytes` provided is a core wasm module which implements the `name` + /// interface in terms of the `interface` interface. This core wasm module + /// is severely restricted in its shape, for example it cannot have any data + /// segments or element segments. + /// + /// The `interface` provided is the component-model-using-interface that the + /// wasm module specified by `bytes` imports. The `bytes` will then import + /// `interface` and export functions to get imported from the module `name` + /// in the core wasm that's being wrapped. + pub fn adapter(&mut self, name: &str, bytes: &[u8]) -> Result<&mut Self> { + self.library_or_adapter(name, bytes, None) + } + + /// Specifies a shared-everything library to link into the component. + /// + /// Unlike adapters, libraries _may_ have data and/or element segments, but + /// they must operate on an imported memory and table, respectively. In + /// this case, the correct amount of space is presumed to have been + /// statically allocated in the main module's memory and table at the + /// offsets which the segments target, e.g. as arranged by + /// [super::linking::Linker]. + /// + /// Libraries are treated similarly to adapters, except that they are not + /// "minified" the way adapters are, and instantiation is controlled + /// declaratively via the `library_info` parameter. + pub fn library( + &mut self, + name: &str, + bytes: &[u8], + library_info: LibraryInfo, + ) -> Result<&mut Self> { + self.library_or_adapter(name, bytes, Some(library_info)) + } + + fn library_or_adapter( + &mut self, + name: &str, + bytes: &[u8], + library_info: Option, + ) -> Result<&mut Self> { + let (wasm, mut metadata) = self.decode(bytes)?; + // Merge the adapter's document into our own document to have one large + // document, and then afterwards merge worlds as well. + // + // Note that the `metadata` tracking import/export encodings is removed + // since this adapter can get different lowerings and is allowed to + // differ from the main module. This is then tracked within the + // `Adapter` structure produced below. + let adapter_metadata = mem::take(&mut metadata.metadata); + let exports = self.merge_metadata(metadata).with_context(|| { + format!("failed to merge WIT packages of adapter `{name}` into main packages") + })?; + if let Some(library_info) = &library_info { + // Validate that all referenced modules can be resolved. + for (_, instance) in &library_info.arguments { + let resolve = |which: &_| match which { + MainOrAdapter::Main => Ok(()), + MainOrAdapter::Adapter(name) => { + if self.adapters.contains_key(name.as_str()) { + Ok(()) + } else { + Err(anyhow!("instance refers to unknown adapter `{name}`")) + } + } + }; + + match instance { + Instance::MainOrAdapter(which) => resolve(which)?, + Instance::Items(items) => { + for item in items { + resolve(&item.which)?; + } + } + } + } + } + self.adapters.insert( + name.to_string(), + Adapter { + wasm: wasm.to_vec(), + metadata: adapter_metadata, + required_exports: exports, + library_info, + }, + ); + Ok(self) + } + + /// Whether adapters use `memory.grow` for realloc and stack allocation. + /// + /// By default an adapter imports `cabi_realloc` from the main module. + /// Setting this to `true` makes it allocate with `memory.grow` instead, + /// which can be useful if `cabi_realloc` cannot be called before the host + /// runtime is initialized. + /// + /// This only affects modules added with [`ComponentEncoder::adapter`]. It + /// has no effect on the main module and does not synthesize a + /// `cabi_realloc` for a module that doesn't export one. + pub fn realloc_via_memory_grow(&mut self, value: bool) -> &mut Self { + self.realloc_via_memory_grow = value; + self + } + + /// The instance import name map to use. + /// + /// This is used to rename instance imports in the final component. + /// + /// For example, if there is an instance import `foo:bar/baz` and it is + /// desired that the import actually be an `unlocked-dep` name, then + /// `foo:bar/baz` can be mapped to `unlocked-dep==x.y.z}>`. + /// + /// Note: the replacement names are not validated during encoding unless + /// the `validate` option is set to true. + pub fn import_name_map(&mut self, map: HashMap) -> &mut Self { + self.import_name_map = map; + self + } + + /// Encode the component and return the bytes. + pub fn encode(&mut self) -> Result> { + self.encode_with_fixups(None) + } + + pub(crate) fn encode_with_fixups( + &mut self, + fixup_hook: Option<&mut dyn FnMut(&mut fixup::FixupModule) -> Result<()>>, + ) -> Result> { + if self.module.is_empty() { + bail!("a module is required when encoding a component"); + } + + if self.merge_imports_based_on_semver.unwrap_or(true) { + self.metadata + .resolve + .merge_world_imports_based_on_semver(self.metadata.world)?; + } + + self.finalize_resolve_with_nominal_ids(); + + let world = ComponentWorld::new(self).context("failed to decode world from module")?; + let mut state = EncodingState { + component: ComponentBuilder::default(), + module_index: None, + instance_index: None, + memory_index: None, + shim_instance_index: None, + adapter_modules: IndexMap::new(), + adapter_instances: IndexMap::new(), + type_encoding_maps: Default::default(), + instances: Default::default(), + imported_funcs: Default::default(), + aliased_core_items: Default::default(), + info: &world, + export_task_initialization_wrappers: HashMap::new(), + }; + state.encode_imports(&self.import_name_map)?; + state.encode_core_modules(); + state.encode_core_instantiation(fixup_hook)?; + state.encode_exports(CustomModule::Main)?; + for name in self.adapters.keys() { + state.encode_exports(CustomModule::Adapter(name))?; + } + state.component.append_names(); + state + .component + .raw_custom_section(&crate::base_producers().raw_custom_section()); + let bytes = state.component.finish(); + + if self.validate { + Validator::new_with_features(WasmFeatures::all()) + .validate_all(&bytes) + .context("failed to validate component output")?; + } + + Ok(bytes) + } + + /// Call the `generate_nominal_type_ids` method on the `Resolve` that we're + /// using, adjusting any preexisting keys/pointers as necessary. + /// + /// This is the final step after merging all known `Resolve`s together + /// before a component is actually created. By creating a unique + /// `InterfaceId` for all interfaces it makes the generation process easier + /// since there's no need to fret about whether an `InterfaceId` is an + /// import or an export for example. + fn finalize_resolve_with_nominal_ids(&mut self) { + // Before calling `generate_nominal_type_ids` we need to handle the fact + // that the exports of the world are going to be rewritten. The only + // pointers we have into those are the exports of the main module and + // adapters. To handle this, before we generate nominal ids, indices of + // exports are saved here on the stack to get restored later on. + // Effectively we're clearing out the exports and rebuilding them later. + let world = &self.metadata.resolve.worlds[self.metadata.world]; + let main_module_exports = self + .main_module_exports + .iter() + .map(|i| world.exports.get_index_of(i).unwrap()) + .collect::>(); + let adapter_exports = self + .adapters + .values() + .map(|adapter| { + adapter + .required_exports + .iter() + .map(|i| world.exports.get_index_of(i).unwrap()) + .collect::>() + }) + .collect::>(); + + // With everything saved this will modify `Resolve` to ensure there's a + // nominal identifier for all interfaces (e.g. not both simultaneously + // imported and exported). + self.metadata + .resolve + .generate_nominal_type_ids(self.metadata.world); + + // Rebuild the sets of exports now that the world's exports have been + // clobbered. + self.main_module_exports.clear(); + let world = &self.metadata.resolve.worlds[self.metadata.world]; + for index in main_module_exports { + let (key, _) = world.exports.get_index(index).unwrap(); + self.main_module_exports.insert(key.clone()); + } + for (exports, adapter) in adapter_exports.into_iter().zip(self.adapters.values_mut()) { + adapter.required_exports.clear(); + for index in exports { + let (key, _) = world.exports.get_index(index).unwrap(); + adapter.required_exports.insert(key.clone()); + } + } + } +} + +impl ComponentWorld<'_> { + /// Convenience function to lookup a module's import map. + fn imports_for(&self, module: CustomModule) -> &ImportMap { + match module { + CustomModule::Main => &self.info.imports, + CustomModule::Adapter(name) => &self.adapters[name].info.imports, + } + } + + /// Convenience function to lookup a module's export map. + fn exports_for(&self, module: CustomModule) -> &ExportMap { + match module { + CustomModule::Main => &self.info.exports, + CustomModule::Adapter(name) => &self.adapters[name].info.exports, + } + } + + /// Convenience function to lookup a module's metadata. + fn module_metadata_for(&self, module: CustomModule) -> &ModuleMetadata { + match module { + CustomModule::Main => &self.encoder.metadata.metadata, + CustomModule::Adapter(name) => &self.encoder.adapters[name].metadata, + } + } +} + +#[cfg(all(test, feature = "dummy-module"))] +mod test { + use super::*; + use crate::{dummy_module, embed_component_metadata}; + use wit_parser::ManglingAndAbi; + + #[test] + fn it_renames_imports() { + let mut resolve = Resolve::new(); + let pkg = resolve + .push_str( + "test.wit", + r#" +package test:wit; + +interface i { + f: func(); +} + +world test { + import i; + import foo: interface { + f: func(); + } +} +"#, + ) + .unwrap(); + let world = resolve.select_world(&[pkg], None).unwrap(); + + let mut module = dummy_module(&resolve, world, ManglingAndAbi::Standard32); + + embed_component_metadata(&mut module, &resolve, world, StringEncoding::UTF8).unwrap(); + + let encoded = ComponentEncoder::default() + .import_name_map(HashMap::from([ + ( + "foo".to_string(), + "unlocked-dep==1.0.0 <1.1.0}>".to_string(), + ), + ( + "test:wit/i".to_string(), + "locked-dep=".to_string(), + ), + ])) + .module(&module) + .unwrap() + .validate(true) + .encode() + .unwrap(); + + let wat = wasmprinter::print_bytes(encoded).unwrap(); + assert!(wat.contains("unlocked-dep==1.0.0 <1.1.0}>")); + assert!(wat.contains("locked-dep=")); + } +} diff --git a/vendor/wit-component/src/encoding/dedupe.rs b/vendor/wit-component/src/encoding/dedupe.rs new file mode 100644 index 00000000..6f0b1fc8 --- /dev/null +++ b/vendor/wit-component/src/encoding/dedupe.rs @@ -0,0 +1,164 @@ +//! Support for deduplicating module imports when turning them into a component. +//! +//! Core wasm allows for duplicate imports of the same name/field in a core wasm +//! module. This is not allowed in the component model, however, meaning that +//! such a core wasm module cannot be inserted into a component as-is. This +//! module is tasked with tackling this problem. +//! +//! The general idea of this module is to rewrite imports in-place to a +//! different and unique name. The original name is then recorded in +//! [`ModuleImportMap`] which is then plumbed through to the location that +//! classifies all imports. The classification then uses the original names for +//! what an import should be resolved to but records it under the unique names +//! generated here. + +use anyhow::Result; +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt::Write; +use wasm_encoder::reencode::{Reencode, RoundtripReencoder}; +use wasm_encoder::{ImportSection, RawSection}; +use wasmparser::{Parser, Payload::*}; + +/// A map of current names (possibly new) to original names, if any. +#[derive(Default)] +pub struct ModuleImportMap { + /// A two-level map for what names map to what. + /// + /// * The first level of the map is the "module" field, or the first string, + /// in a wasm import. + /// * The second level of the map is the "name" field, or the second string, + /// in a wasm import. + /// * The value of the second level is what this name was originally found + /// under in the original module. `None` means "same as the hash map key" + /// while `Some` means "it's this new name". + /// + /// This map is built during `ModuleImportMap::new` and serves double-duty + /// to actually track duplicate imports. + renamed_to_original: HashMap>>, +} + +impl ModuleImportMap { + /// Creates a new [`ModuleImportMap`] tracking duplicate imports, if any, + /// from the `wasm` provided. + /// + /// Upon success a new wasm binary (possibly the same as the original) is + /// returned which is the new source of truth for this module. If duplicate + /// imports were found then a [`ModuleImportMap`] is returned, otherwise + /// `None` is returned. + /// + /// # Errors + /// + /// Returns an error if `wasm` could not be parsed as a wasm module. + pub fn new<'a>(wasm: Cow<'a, [u8]>) -> Result<(Cow<'a, [u8]>, Option)> { + let mut module = wasm_encoder::Module::new(); + let mut ret = ModuleImportMap::default(); + let mut found_duplicate_imports = false; + + for payload in Parser::new(0).parse_all(&wasm) { + let payload = payload?; + match payload { + Version { encoding, .. } if encoding == wasmparser::Encoding::Component => { + // if this is a component let someone else deal with the + // error, we'll punt that up the stack. + assert!(!found_duplicate_imports); + break; + } + + // This is the section we're interested in. Go over each import + // and delegate to `ModuleImportMap::push_import` for figuring + // out what to do with this import. At the end put the new + // import section in the `module` we're building. + ImportSection(i) => { + let mut new_import_section = ImportSection::new(); + for import in i.clone().into_imports() { + found_duplicate_imports = ret + .push_import(&mut new_import_section, import?)? + || found_duplicate_imports; + } + module.section(&new_import_section); + } + + // All other sections get plumbed through as-is. This ensures we + // don't tamper with binary offsets anywhere in the module + // except the import section, for example. + _ => { + if let Some((id, range)) = payload.as_section() { + module.section(&RawSection { + id, + data: &wasm[range.start as usize..range.end as usize], + }); + } + } + } + } + + if found_duplicate_imports { + Ok((module.finish().into(), Some(ret))) + } else { + Ok((wasm, None)) + } + } + + /// Returns `Ok(true)` if this is a duplicate import, or `Ok(false)` if it's + /// a unique import for the first time. + fn push_import( + &mut self, + new_import_section: &mut ImportSection, + import: wasmparser::Import<'_>, + ) -> Result { + let module_map = self + .renamed_to_original + .entry(import.module.to_string()) + .or_insert(HashMap::new()); + + // If this import hasn't yet been seen, then great! Record that it is + // using its original name and encode it with its original name. + if !module_map.contains_key(import.name) { + let prev = module_map.insert(import.name.to_string(), None); + assert!(prev.is_none()); + RoundtripReencoder.parse_import(new_import_section, import)?; + return Ok(false); + } + + // FIXME: this is technically O(n^2), but it's also only applicable when + // a module has lots of imports, and surely that won't happen often... + // right? ... right? + // + // If this isn't fixed by the time someone reads this and is angry about + // O(n^2), sorry. + // + // Otherwise the purpose of this loop is to determine a unique name for + // the new import, something that hasn't previously been seen before. + let mut new_name = import.name.to_string(); + for i in 2.. { + new_name.truncate(import.name.len()); + write!(new_name, " [v{i}]").unwrap(); + if !module_map.contains_key(&new_name) { + break; + } + } + + // Now that `new_name` is unique, record the import in the new import + // section. + let mut new_import = import; + new_import.name = &new_name; + RoundtripReencoder.parse_import(new_import_section, new_import)?; + + // Also record that `new_name` was originally known as `import.name` + // for later lookup in `original_names` below. + let prev = module_map.insert(new_name, Some(import.name.to_string())); + assert!(prev.is_none()); + Ok(true) + } + + /// Returns the original `name` that `import` should use, if any. + /// + /// If `None` is returned then `import.name` should be used. + pub fn original_name(&self, import: &wasmparser::Import<'_>) -> Option<&str> { + self.renamed_to_original + .get(import.module)? + .get(import.name)? + .as_deref() + } +} diff --git a/vendor/wit-component/src/encoding/fixup.rs b/vendor/wit-component/src/encoding/fixup.rs new file mode 100644 index 00000000..f39df917 --- /dev/null +++ b/vendor/wit-component/src/encoding/fixup.rs @@ -0,0 +1,906 @@ +use crate::ComponentEncoder; +use crate::encoding::{CustomModule, EncodingState, Shim, ShimKind, Shims}; +use crate::validation::Export; +use anyhow::{Result, bail}; +use indexmap::IndexMap; +use std::collections::HashMap; +use std::mem; +use wasm_encoder::*; +use wit_parser::WorldItem; +use wit_parser::abi::{AbiVariant, WasmSignature}; + +#[derive(Default)] +pub struct FixupModule { + // Incrementally-built-up sections of the module-to-be. + types: TypeSection, + imports: ImportSection, + function_names: NameMap, + global_names: NameMap, + elements: ElementSection, + data: DataSection, + + /// Interning map for type signatures. + type_map: HashMap<(Vec, Vec), u32>, + + /// The start function, if needed. This is split between "ABI details" and + /// "user funcs" where ABI details must happen first and user funcs need to + /// be wrapped in task intrinsics if provided. + start_abi_details: Vec, + start_user_funcs: Vec, + + /// Entries used to initialize the imported shim's table, if necessary. + shims_in_table: Vec, + + /// Entries to go into a declared element segment. + declared_funcs: Vec, + + /// The instance names that are imported into this module, and what those + /// instances correspond to. + imported_instances: IndexMap, + + /// Interning map for imports. + imported_items: HashMap<(String, String), (u32, EntityType)>, + + /// Functions that will be defined in this module itself. + /// + /// This is deferred to get emitted until the very end so all imports have + /// been settled and then these import indices can be known. + defined_functions: Vec<(u32, DefinedFunction)>, + + // Current counters for index spaces. + funcs: u32, + globals: u32, + tables: u32, + memories: u32, +} + +/// Different instances that can be imported into the fixup module. +#[derive(Clone, PartialEq, Eq, Hash, Debug)] +pub enum ImportedInstance { + /// The original "shim" module with stubs that need to be filled in. + Shim, + /// The "main" module. + Main, + /// A synthetic instance created by collecting actual implementations of + /// shims from various locations. + Actual, + /// A named adapter module. + Adapter(String), +} + +pub enum StartAction { + /// Sets `$global` to `ref.func $shim` + InitGlobal { + /// The index in `declared_funcs` of the function to fill in. + shim: usize, + /// The global being set. + global: u32, + }, + /// Calls the specified function index. + Call(u32), + /// Used during the `link`-part of `wit-component` this adds the + /// `memory_base` and `export` globals together and stores the result in + /// `dest`. + InitializeAddress { + memory_base: u32, + export: u32, + dest: AddressDest, + }, + /// Invoke the `func` hook with the `hook` argument. + CallHook { func: u32, hook: TaskHook }, +} + +pub enum AddressDest { + /// A linear memory address that's statically known. + LinearMemory { address: u32, memory: u32 }, + /// A global indexed by the argument here. + Global(u32), +} + +/// What can be used to fill in a shim that was originally defined in the shim +/// module. +/// +/// Functions specified here either go into an element segment to fill in the +/// original shim module's table or they're inserted into globals. +enum ShimFill { + /// An imported function. + Import(u32), + /// An imported function which is also known to be a resource destructor. + /// Used to know when to insert task hooks. + ImportedResourceDtor(u32), + /// A `realloc` function which is exported from `instance` under the name + /// `export` and imported here as `func`. + Realloc { + instance: ImportedInstance, + export: String, + func: u32, + }, + /// A function defined in this fixup module. + DefinedFunction(usize), +} + +/// Different functions that can be defined in the fixup module, apart from the +/// `start` function. +enum DefinedFunction { + /// A function which wraps a core export to ensure that task state is set up + /// before the core export is called. + HookedCoreExport { + /// The task hook function. + task_hook: u32, + /// The core function to call and delegate to. + to_wrap: u32, + /// The number of parameters to forward to `export`. + params: usize, + /// The debug-related core name of this function it's hooking. + core_name: String, + /// If `Some` this is the instance that is is exported for which will + /// get inserted into `EncodingState`'s export wrapper map. + export: Option, + /// The kind of hook to use at the start of this function. + start: Option, + /// The kind of hook to use at the end of this function. + end: EndTaskHook, + }, +} + +#[derive(Copy, Clone)] +pub enum TaskHook { + /// A synchronous task has started. + SyncStart = 0, + /// A synchronous task has finished. + SyncFinish = 1, + /// An async task has started. + AsyncStart = 2, + /// An async has resumed in its `callback` option. + AsyncResume = 3, + /// An async blocked, but not yet completed, and it's returning from either + /// the main entrypoint or the `callback` option. + AsyncBlock = 4, + /// An async task has finished, returning from either the main entrypoint or + /// the `callback` option. + AsyncFinish = 5, + /// The `_initialize` function and other ctors are being called. + InitializeStart = 6, + /// The `_initialize` function and other ctors are finished. + InitializeFinish = 7, + /// A resource destructor is starting. + ResourceDtorStart = 8, + /// A resource destructor is finished. + ResourceDtorFinish = 9, + // + // 10/11 intentionally missing + // + /// A `realloc` function used as a canonical ABI option is being invoked. + ReallocStart = 12, + /// A `realloc` function used as a canonical ABI option has finished. + ReallocFinish = 13, +} + +enum EndTaskHook { + None, + AsyncCode, + Normal(TaskHook), +} + +impl FixupModule { + /// Returns the 0-parameter 0-result function type. + pub fn type_thunk(&mut self) -> u32 { + self.type_intern(Vec::new(), Vec::new()) + } + + /// Interns `params`/`results` as a function type. + pub fn type_intern(&mut self, params: Vec, results: Vec) -> u32 { + *self + .type_map + .entry((params.clone(), results.clone())) + .or_insert_with(|| { + let index = self.types.len(); + self.types + .ty() + .function(params.iter().copied(), results.iter().copied()); + index + }) + } + + fn type_index(&mut self, sig: &WasmSignature) -> u32 { + self.type_intern( + sig.params.iter().map(super::to_val_type).collect(), + sig.results.iter().map(super::to_val_type).collect(), + ) + } + + fn import_instance(&mut self, kind: &ImportedInstance) -> Result { + let name = match kind { + ImportedInstance::Shim => "shim", + ImportedInstance::Main => "main", + ImportedInstance::Actual => "actual", + ImportedInstance::Adapter(name) => name.as_str(), + }; + let name = name.to_string(); + if let Some(prev) = self.imported_instances.insert(name.clone(), kind.clone()) { + if prev != *kind { + bail!("instance `{name}` was already imported as a different kind: {prev:?}"); + } + } + Ok(name) + } + + /// Imports a new item into this fixup module to get used by later + /// functions/etc. + /// + /// Returns the index that the item is imported as. + pub fn import( + &mut self, + instance: &ImportedInstance, + name: &str, + ty: EntityType, + ) -> Result { + let module = self.import_instance(instance)?; + let key = (module, name.to_string()); + if let Some((index, prev)) = self.imported_items.get(&key) { + if *prev != ty { + bail!( + "`{}::{name}` was already imported with a different type", + key.0 + ); + } + return Ok(*index); + } + // Note that debug names are recorded here, rather than in the helpers + // below, so that a name is only recorded for a freshly created import. + let ret = match ty { + EntityType::Function(_) => { + let index = inc(&mut self.funcs); + self.function_names.append(index, name); + index + } + EntityType::Global(_) => { + let index = inc(&mut self.globals); + self.global_names.append(index, name); + index + } + EntityType::Table(_) => inc(&mut self.tables), + EntityType::Memory(_) => inc(&mut self.memories), + EntityType::Tag(_) | EntityType::FunctionExact(_) => unimplemented!(), + }; + self.imports.import(&key.0, name, ty); + self.imported_items.insert(key, (ret, ty)); + Ok(ret) + } + + /// Helper over `self.import(...)` + pub fn import_global( + &mut self, + instance: &ImportedInstance, + name: &str, + ty: GlobalType, + ) -> Result { + self.import(instance, name, ty.into()) + } + + /// Helper over `self.import(...)` + pub fn import_func(&mut self, instance: &ImportedInstance, name: &str, ty: u32) -> Result { + self.import(instance, name, EntityType::Function(ty)) + } + + /// Appends to the `start` function that'll get generated. + pub fn add_start_abi_detail(&mut self, action: StartAction) { + self.start_abi_details.push(action); + } + + /// Appends to the `start` function that'll get generated. + pub fn add_start_user_func(&mut self, action: StartAction) { + self.start_user_funcs.push(action); + } + + /// Returns the underlying element section. + pub fn elements(&mut self) -> &mut ElementSection { + &mut self.elements + } + + /// Returns the underlying data section. + pub fn data(&mut self) -> &mut DataSection { + &mut self.data + } + + /// Adds `shim` to this fixup module to get filled in. + pub(super) fn add_shim(&mut self, opts: &ComponentEncoder, shim: &Shim) -> Result<()> { + let type_index = self.type_index(&shim.sig); + let func = self.import_func(&ImportedInstance::Actual, &shim.name, type_index)?; + + let shim_fill = match &shim.kind { + ShimKind::Realloc { module, export } => ShimFill::Realloc { + instance: module.to_imported_instance(), + export: export.to_string(), + func, + }, + ShimKind::ResourceDtor { .. } => ShimFill::ImportedResourceDtor(func), + _ => ShimFill::Import(func), + }; + + if opts.shim_return_call_ref { + let global = self.import_global( + &ImportedInstance::Shim, + &format!("g{}", &shim.name), + GlobalType { + val_type: RefType { + heap_type: HeapType::Concrete(type_index), + nullable: false, + } + .into(), + mutable: true, + shared: false, + }, + )?; + + self.start_abi_details.push(StartAction::InitGlobal { + shim: self.declared_funcs.len(), + global, + }); + self.declared_funcs.push(shim_fill); + } else { + self.shims_in_table.push(shim_fill); + } + Ok(()) + } + + /// Ensures there's a `start` function which invokes `initialize`. + pub fn add_initialize(&mut self, initialize: &str) -> Result<()> { + let ty = self.type_thunk(); + let func = self.import_func(&ImportedInstance::Main, initialize, ty)?; + self.start_user_funcs.push(StartAction::Call(func)); + Ok(()) + } + + pub(super) fn instantiate( + &mut self, + shims: &Shims<'_>, + state: &mut EncodingState<'_>, + ) -> Result<()> { + // First inject task hooks as necessary throughout the module which is + // the final step before actually encoding the module. + self.prepare_task_hooks(state)?; + + // Generate the module, and this'll return `None` if the module isn't + // necessary in which case we bail out. + let Some(module) = self.encode(state)? else { + return Ok(()); + }; + + // Embed this fixup module in the component. + let module_index = state + .component + .core_module(Some("wit-component-fixup"), &module); + + // Prepare the arguments used to instantiate this component based on the + // `imported_instances` map that's been generated. + let mut instance_args = Vec::new(); + for (name, instance) in self.imported_instances.iter() { + let index = match instance { + ImportedInstance::Main => state + .instance_index + .expect("must have an instantiated module"), + ImportedInstance::Adapter(name) => state.adapter_instances[name.as_str()], + ImportedInstance::Shim => state + .shim_instance_index + .expect("must have an instantiated shim"), + ImportedInstance::Actual => { + let mut actual = Vec::new(); + for shim in shims.shims.values() { + let core_func_index = state.encode_shim(shims, shim)?; + actual.push((shim.name.as_str(), ExportKind::Func, core_func_index)); + } + state + .component + .core_instantiate_exports(Some("actual"), actual) + } + }; + instance_args.push((name.as_str(), ModuleArg::Instance(index))); + } + + // The side-effectful instantiation of the fixup instance. + let instance = state + .component + .core_instantiate(Some("fixup"), module_index, instance_args); + + // If there are hooked core exports in this module then register within + // `state` that they should be preferred over their raw brethren. + for (i, (_ty, func)) in self.defined_functions.iter().enumerate() { + match func { + DefinedFunction::HookedCoreExport { + core_name, + export: Some(from), + .. + } => { + let name = format!("hook{i}"); + let wrapper = + state.core_alias_export(Some(&name), instance, &name, ExportKind::Func); + state + .export_task_initialization_wrappers + .insert((from.clone(), core_name.clone()), wrapper); + } + DefinedFunction::HookedCoreExport { export: None, .. } => {} + } + } + Ok(()) + } + + fn encode(&mut self, state: &EncodingState<'_>) -> Result> { + let opts = &state.info.encoder; + if self.start_abi_details.is_empty() + && self.start_user_funcs.is_empty() + && self.shims_in_table.is_empty() + && self.declared_funcs.is_empty() + && self.elements.is_empty() + && self.data.is_empty() + && self.defined_functions.is_empty() + { + return Ok(None); + } + + let mut functions = FunctionSection::new(); + let mut code = CodeSection::new(); + let mut exports = ExportSection::new(); + + // First define functions within this module now that the import space + // for functions has settled. + let mut defined_func_indices = Vec::new(); + for (i, (ty, func)) in self.defined_functions.iter().enumerate() { + functions.function(*ty); + let index = inc(&mut self.funcs); + defined_func_indices.push(index); + let mut func = match func { + DefinedFunction::HookedCoreExport { + task_hook, + to_wrap, + params, + core_name, + export, + start, + end, + } => { + let mut locals = Vec::new(); + if let EndTaskHook::AsyncCode = end { + locals.push((1, ValType::I32)); + } + let mut f = Function::new(locals); + if let Some(start) = *start { + f.instructions().i32_const(start as i32).call(*task_hook); + } + for i in 0..*params { + f.instructions().local_get(i as u32); + } + f.instructions().call(*to_wrap); + match end { + EndTaskHook::AsyncCode => { + f.instructions() + .local_set(*params as u32) + // 0 == EXIT, 1/2 == yield/wait, so delegate to + // appropriate code. + // + // First thing pushed on the stack is "if true", + // which in this case nonzero means blocking. + // Second thing is "if false" meaning if 0 + // meaning EXIT meaning "done". Final thing is + // what to test, the return code. + .i32_const(TaskHook::AsyncBlock as i32) + .i32_const(TaskHook::AsyncFinish as i32) + .local_get(*params as u32) + .select() + .call(*task_hook) + // put the return code back on the stack to + // actually return + .local_get(*params as u32); + } + EndTaskHook::Normal(hook) => { + f.instructions().i32_const(*hook as i32).call(*task_hook); + } + EndTaskHook::None => {} + } + if export.is_some() { + exports.export(&format!("hook{i}"), ExportKind::Func, index); + } + self.function_names + .append(index, &format!("hook-{core_name}")); + f + } + }; + func.instructions().end(); + code.function(&func); + } + + // Using our defined functions above it's possible to implement + // resolution of `ShimFill` items. + let resolve_shim = |shim: &ShimFill| match shim { + ShimFill::Import(func) => *func, + ShimFill::ImportedResourceDtor(func) => *func, + ShimFill::DefinedFunction(i) => defined_func_indices[*i], + ShimFill::Realloc { func, .. } => *func, + }; + + // If this fixup is filling in a table, then import the table and use an + // element segment for its initialization. + if !self.shims_in_table.is_empty() { + let table_type = TableType { + element_type: RefType::FUNCREF, + minimum: self.shims_in_table.len() as u64, + maximum: Some(self.shims_in_table.len() as u64), + table64: false, + shared: false, + }; + let table = self.import( + &ImportedInstance::Shim, + super::INDIRECT_TABLE_NAME, + table_type.into(), + )?; + self.elements.active( + if table == 0 { None } else { Some(table) }, + &ConstExpr::i32_const(0), + Elements::Functions( + self.shims_in_table + .iter() + .map(resolve_shim) + .collect::>() + .into(), + ), + ); + } + + // Codegen the start function here. Special case an empty start function + // or just a single function call as the start function, otherwise each + // item needs to be handled individually. + let start = match (&self.start_abi_details[..], &self.start_user_funcs[..]) { + ([], []) => None, + ([], [StartAction::Call(func)]) => Some(*func), + (first, second) => { + let mut start = Function::new(Vec::new()); + for action in first.iter().chain(second.iter()) { + match action { + StartAction::InitGlobal { shim, global } => { + let func = resolve_shim(&self.declared_funcs[*shim]); + start.instructions().ref_func(func).global_set(*global); + } + StartAction::Call(func) => { + start.instructions().call(*func); + } + StartAction::CallHook { func, hook } => { + start.instructions().i32_const(*hook as i32).call(*func); + } + StartAction::InitializeAddress { + memory_base, + export, + dest, + } => match dest { + AddressDest::LinearMemory { address, memory } => { + start + .instructions() + .i32_const(*address as i32) + .global_get(*memory_base) + .global_get(*export) + .i32_add() + .i32_store(MemArg { + offset: 0, + align: 2, + memory_index: *memory, + }); + } + AddressDest::Global(global) => { + start + .instructions() + .global_get(*memory_base) + .global_get(*export) + .i32_add() + .global_set(*global); + } + }, + } + } + start.instructions().end(); + let index = inc(&mut self.funcs); + let ty = self.type_thunk(); + functions.function(ty); + code.function(&start); + self.function_names.append(index, "start"); + Some(index) + } + }; + + // Fill in the declared element segment, if necessary, used for + // `ref.func` in the start function above. + if !self.declared_funcs.is_empty() { + self.elements.declared(Elements::Functions( + self.declared_funcs + .iter() + .map(resolve_shim) + .collect::>() + .into(), + )); + } + + // Now that we've got all the pieces weave everything into a `Module`. + let mut module = Module::default(); + if !self.types.is_empty() { + module.section(&self.types); + } + if !self.imports.is_empty() { + module.section(&self.imports); + } + if !functions.is_empty() { + module.section(&functions); + } + if !exports.is_empty() { + module.section(&exports); + } + if let Some(start) = start { + module.section(&StartSection { + function_index: start, + }); + } + if !self.elements.is_empty() { + module.section(&self.elements); + } + if !code.is_empty() { + module.section(&code); + } + if !self.data.is_empty() { + module.section(&self.data); + } + module.section(&RawCustomSection( + &crate::base_producers().raw_custom_section(), + )); + + if opts.debug_names { + let mut names = NameSection::new(); + names.module("wit-component:fixups"); + if !self.function_names.is_empty() { + names.functions(&self.function_names); + } + if !self.global_names.is_empty() { + names.globals(&self.global_names); + } + module.section(&names); + } + + Ok(Some(module)) + } + + /// Prepares task hooks, like `__wasm_init_task`, to be configured in + /// various locations throughout this fixup module. + /// + /// This handles: + /// + /// * The `_initialize` function (needs task setup first) + /// * Hooks for all exports which are lifted. + fn prepare_task_hooks(&mut self, state: &mut EncodingState<'_>) -> Result<()> { + let info_main = state.info.exports_for(CustomModule::Main); + let Some(task_hook) = info_main.wasm_task_hook() else { + return Ok(()); + }; + let ty = self.type_intern(vec![ValType::I32], Vec::new()); + let task_hook = self.import_func(&ImportedInstance::Main, task_hook, ty)?; + + // Handle the start function first where if there's something registered + // in the "user function" area we need to configure that to work. + if !self.start_user_funcs.is_empty() { + self.start_user_funcs.insert( + 0, + StartAction::CallHook { + func: task_hook, + hook: TaskHook::InitializeStart, + }, + ); + self.start_user_funcs.push(StartAction::CallHook { + func: task_hook, + hook: TaskHook::InitializeFinish, + }); + } + + // Afterwards handle all exports for the main/adapter modules. + self.prepare_export_task_hooks_for(state, CustomModule::Main, task_hook)?; + for adapter in state.info.adapters.keys() { + self.prepare_export_task_hooks_for(state, CustomModule::Adapter(adapter), task_hook)?; + } + + // Next up generate wrappers for all `realloc` functions which might be + // used as a canonical option. + let mut reallocs = HashMap::new(); + self.prepare_realloc_task_hooks_for(state, CustomModule::Main, task_hook, &mut reallocs)?; + for adapter in state.info.adapters.keys() { + self.prepare_realloc_task_hooks_for( + state, + CustomModule::Adapter(adapter), + task_hook, + &mut reallocs, + )?; + } + + // And finally redirect/fixup shims that need hooks to defined versions + // locally in this module. + let mut shims_in_table = mem::take(&mut self.shims_in_table); + let mut declared_funcs = mem::take(&mut self.declared_funcs); + for shim in shims_in_table.iter_mut().chain(declared_funcs.iter_mut()) { + match shim { + // Resource destructors are handled here directly inline. + ShimFill::ImportedResourceDtor(func) => { + let func = *func; + let ty = self.type_intern(vec![ValType::I32], Vec::new()); + *shim = ShimFill::DefinedFunction(self.defined_functions.len()); + self.defined_functions.push(( + ty, + DefinedFunction::HookedCoreExport { + task_hook, + to_wrap: func, + params: 1, + start: Some(TaskHook::ResourceDtorStart), + end: EndTaskHook::Normal(TaskHook::ResourceDtorFinish), + export: None, + core_name: format!("resource-dtor"), + }, + )); + } + + // All realloc functions were hooked above in + // `prepare_realloc_task_hooks_for` so this just looks up in the + // map built there to figure out which function to redirect to. + ShimFill::Realloc { + instance, export, .. + } => { + let func = reallocs + .get(&(instance.clone(), export.clone())) + .copied() + .expect("realloc wrapper should have been generated"); + *shim = ShimFill::DefinedFunction(func); + } + + ShimFill::Import(_) | ShimFill::DefinedFunction(_) => {} + }; + } + + self.shims_in_table = shims_in_table; + self.declared_funcs = declared_funcs; + + Ok(()) + } + + /// Generates a task hook wrapper for each `realloc` function exported by + /// `for_module` which may be used as a canonical option. + /// + /// These wrappers are themselves imported from the fixup module for use in + /// lifts-of-exports, and then additionally these are used to fill in + /// `ShimFill::Realloc` later on. + fn prepare_realloc_task_hooks_for( + &mut self, + state: &mut EncodingState<'_>, + for_module: CustomModule<'_>, + task_hook: u32, + reallocs: &mut HashMap<(ImportedInstance, String), usize>, + ) -> Result<()> { + let instance = for_module.to_imported_instance(); + for name in state.info.exports_for(for_module).reallocs() { + let ty = self.type_intern(vec![ValType::I32; 4], vec![ValType::I32]); + let func = self.import_func(&instance, name, ty)?; + let index = self.defined_functions.len(); + self.defined_functions.push(( + ty, + DefinedFunction::HookedCoreExport { + task_hook, + to_wrap: func, + params: 4, + start: Some(TaskHook::ReallocStart), + end: EndTaskHook::Normal(TaskHook::ReallocFinish), + export: Some(instance.clone()), + core_name: name.to_string(), + }, + )); + reallocs.insert((instance.clone(), name.to_string()), index); + } + Ok(()) + } + + /// Looks over the exports of `for_module` and adds any functions as + /// necessary to `self.defined_functions` which hook the original export to + /// ensure it's got task state set up when called first. + fn prepare_export_task_hooks_for( + &mut self, + state: &mut EncodingState<'_>, + for_module: CustomModule<'_>, + task_hook: u32, + ) -> Result<()> { + let resolve = &state.info.encoder.metadata.resolve; + let world = &resolve.worlds[state.info.encoder.metadata.world]; + let info = state.info.exports_for(for_module); + let imported_instance = for_module.to_imported_instance(); + + for (core_name, export) in info.iter() { + let (key, f, abi) = match export { + Export::WorldFunc(key, _, abi) => match &world.exports[key] { + WorldItem::Function(f) => (key, f, abi), + _ => continue, + }, + Export::InterfaceFunc(key, id, func_name, abi) => { + let func = &resolve.interfaces[*id].functions[func_name.as_str()]; + (key, func, abi) + } + _ => continue, + }; + + let sig = resolve.wasm_signature(*abi, f); + let ty = self.type_index(&sig); + let func = self.import_func(&imported_instance, core_name, ty)?; + let post_return = info.post_return(key, f); + self.defined_functions.push(( + ty, + DefinedFunction::HookedCoreExport { + task_hook, + to_wrap: func, + export: Some(imported_instance.clone()), + params: sig.params.len(), + core_name: core_name.to_string(), + start: Some(if abi.is_async() { + TaskHook::AsyncStart + } else { + TaskHook::SyncStart + }), + end: if abi.is_async() { + assert!(post_return.is_none()); + if *abi == AbiVariant::GuestExportAsyncStackful { + EndTaskHook::Normal(TaskHook::AsyncFinish) + } else { + EndTaskHook::AsyncCode + } + } else { + if post_return.is_some() { + EndTaskHook::None + } else { + EndTaskHook::Normal(TaskHook::SyncFinish) + } + }, + }, + )); + + if let Some(post_return) = info.post_return(key, f) { + let mut post_return_sig = sig.clone(); + post_return_sig.params = mem::take(&mut post_return_sig.results); + let ty = self.type_index(&post_return_sig); + let func = self.import_func(&imported_instance, post_return, ty)?; + self.defined_functions.push(( + ty, + DefinedFunction::HookedCoreExport { + task_hook, + to_wrap: func, + export: Some(imported_instance.clone()), + params: post_return_sig.params.len(), + core_name: post_return.to_string(), + start: None, + end: EndTaskHook::Normal(TaskHook::SyncFinish), + }, + )); + } + + if let Some(callback) = info.callback(key, f) { + let ty = self.type_intern(vec![ValType::I32; 3], vec![ValType::I32]); + let func = self.import_func(&imported_instance, callback, ty)?; + self.defined_functions.push(( + ty, + DefinedFunction::HookedCoreExport { + task_hook, + to_wrap: func, + export: Some(imported_instance.clone()), + params: 3, + core_name: callback.to_string(), + start: Some(TaskHook::AsyncResume), + end: EndTaskHook::AsyncCode, + }, + )); + } + } + + Ok(()) + } +} + +fn inc(i: &mut u32) -> u32 { + let ret = *i; + *i += 1; + ret +} diff --git a/vendor/wit-component/src/encoding/types.rs b/vendor/wit-component/src/encoding/types.rs new file mode 100644 index 00000000..6b43e5a8 --- /dev/null +++ b/vendor/wit-component/src/encoding/types.rs @@ -0,0 +1,538 @@ +use super::EncodingState; +use anyhow::Result; +use std::collections::HashMap; +use wasm_encoder::*; +use wit_parser::{ + Enum, Flags, Function, Handle, InterfaceId, Param, Record, Resolve, Result_, Tuple, Type, + TypeDefKind, TypeId, TypeOwner, Variant, +}; + +/// A view of `&[Param]` that compares and hashes by name and type only, +/// ignoring source spans. +#[derive(Clone)] +struct ParamSignatures<'a>(&'a [Param]); + +impl PartialEq for ParamSignatures<'_> { + fn eq(&self, other: &Self) -> bool { + self.0.len() == other.0.len() + && self + .0 + .iter() + .zip(other.0) + .all(|(a, b)| a.name == b.name && a.ty == b.ty) + } +} + +impl Eq for ParamSignatures<'_> {} + +impl std::hash::Hash for ParamSignatures<'_> { + fn hash(&self, state: &mut H) { + for p in self.0 { + p.name.hash(state); + p.ty.hash(state); + } + } +} + +/// Represents a key type for interface function definitions. +#[derive(Hash, PartialEq, Eq, Clone)] +pub struct FunctionKey<'a> { + async_: bool, + params: ParamSignatures<'a>, + result: &'a Option, +} + +#[derive(Default, Clone)] +pub struct TypeEncodingMaps<'a> { + pub id_to_index: HashMap, + pub def_to_index: HashMap<&'a TypeDefKind, u32>, + pub func_type_map: HashMap, u32>, + pub unit_future: Option, + pub unit_stream: Option, +} + +impl<'a> TypeEncodingMaps<'a> { + /// Returns the index used to encode `id`, if it has been previously + /// encoded. + fn lookup(&self, resolve: &'a Resolve, id: TypeId) -> Option { + // If this exact id has been encoded before, use that. + if let Some(index) = self.id_to_index.get(&id) { + return Some(*index); + } + + // If this is an anonymous type, or one where the name of the type is + // `none`, then consult the `def_to_index` map as well. + let ty = &resolve.types[id]; + if ty.name.is_none() { + if let Some(index) = self.def_to_index.get(&ty.kind) { + return Some(*index); + } + } + + // Failing all that this hasn't previously been encoded. + None + } + + /// Inserts that `id` was encoded as `index`. + fn insert(&mut self, resolve: &'a Resolve, id: TypeId, index: u32) { + // Always record the id=>index mapping. + self.id_to_index.insert(id, index); + + // Conditionally record the kind=>index mapping if the type is anonymous + // and thus a candidate to use. + let ty = &resolve.types[id]; + if ty.name.is_none() { + self.def_to_index.insert(&ty.kind, index); + } + } +} + +/// Support for encoding a wit-parser type into a component. +/// +/// This is a `trait` to enable different implementations which define types +/// slightly differently in different contexts. For example types might be +/// defined within an instance type's index space or might be defined in the +/// component's root index space in a type section. The default trait methods +/// here are intended to assist in multiplexing over this difference. +pub trait ValtypeEncoder<'a> { + /// Returns a new type encoder used to define a new type in this type + /// section. + /// + /// The `u32` returned is the index of the type being defined in this type + /// index space and the encoder returned must be used to define a type. + fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>); + + /// Returns the index of a new function type and the encoder of where to + /// place its results. + fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>); + + /// Creates an export item for the specified type index. + fn export_type(&mut self, index: u32, name: ComponentExternName<'a>) -> Option; + + /// Creates a new `(type (sub resource))` export with the given name, + /// returning the type index that refers to the fresh type created. + fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32; + + /// Returns the encoding maps used to encoding types such as id-to-index + /// maps. + fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a>; + + /// Imports `id` from a different interface, returning the index of the + /// imported type into this index space. + fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32; + + /// Returns the identifier of the interface that generation is for. + fn interface(&self) -> Option; + + /// Encodes a new function type which is defined within the provided + /// document. + fn encode_func_type(&mut self, resolve: &'a Resolve, func: &'a Function) -> Result { + let key = FunctionKey { + async_: func.kind.is_async(), + params: ParamSignatures(&func.params), + result: &func.result, + }; + if let Some(index) = self.type_encoding_maps().func_type_map.get(&key) { + return Ok(*index); + } + + // Encode all referenced parameter types from this function. + let params: Vec<_> = self.encode_params(resolve, &func.params)?; + + let result = func + .result + .map(|ty| self.encode_valtype(resolve, &ty)) + .transpose()?; + + // Encode the function type + let (index, mut f) = self.define_function_type(); + f.async_(func.kind.is_async()).params(params).result(result); + let prev = self.type_encoding_maps().func_type_map.insert(key, index); + assert!(prev.is_none()); + Ok(index) + } + + fn encode_params( + &mut self, + resolve: &'a Resolve, + params: &'a [Param], + ) -> Result> { + params + .iter() + .map(|p| Ok((p.name.as_str(), self.encode_valtype(resolve, &p.ty)?))) + .collect::>() + } + + /// Encodes the `ty`, defined within `resolve`, into this encoder and returns + /// the corresponding `ComponentValType` that it represents. + /// + /// This will recursively define the entire structure of `ty` within `self` + /// if necessary. + fn encode_valtype(&mut self, resolve: &'a Resolve, ty: &Type) -> Result { + Ok(match *ty { + Type::Bool => ComponentValType::Primitive(PrimitiveValType::Bool), + Type::U8 => ComponentValType::Primitive(PrimitiveValType::U8), + Type::U16 => ComponentValType::Primitive(PrimitiveValType::U16), + Type::U32 => ComponentValType::Primitive(PrimitiveValType::U32), + Type::U64 => ComponentValType::Primitive(PrimitiveValType::U64), + Type::S8 => ComponentValType::Primitive(PrimitiveValType::S8), + Type::S16 => ComponentValType::Primitive(PrimitiveValType::S16), + Type::S32 => ComponentValType::Primitive(PrimitiveValType::S32), + Type::S64 => ComponentValType::Primitive(PrimitiveValType::S64), + Type::F32 => ComponentValType::Primitive(PrimitiveValType::F32), + Type::F64 => ComponentValType::Primitive(PrimitiveValType::F64), + Type::Char => ComponentValType::Primitive(PrimitiveValType::Char), + Type::String => ComponentValType::Primitive(PrimitiveValType::String), + Type::ErrorContext => ComponentValType::Primitive(PrimitiveValType::ErrorContext), + Type::Id(id) => { + // If this id has already been prior defined into this section + // refer to that definition. + if let Some(index) = self.type_encoding_maps().lookup(resolve, id) { + return Ok(ComponentValType::Type(index)); + } + + let ty = &resolve.types[id]; + + // If this type is imported from another interface then return + // it as it was bound here with an alias. + log::trace!("encode type name={:?} {:?}", ty.name, &ty.kind); + if let Some(index) = self.maybe_import_type(resolve, id) { + self.type_encoding_maps().insert(resolve, id, index); + return Ok(ComponentValType::Type(index)); + } + + // ... and failing all that insert the type export. + let mut encoded = match &ty.kind { + TypeDefKind::Record(r) => self.encode_record(resolve, r)?, + TypeDefKind::Tuple(t) => self.encode_tuple(resolve, t)?, + TypeDefKind::Flags(r) => self.encode_flags(r)?, + TypeDefKind::Variant(v) => self.encode_variant(resolve, v)?, + TypeDefKind::Option(t) => self.encode_option(resolve, t)?, + TypeDefKind::Result(r) => self.encode_result(resolve, r)?, + TypeDefKind::Enum(e) => self.encode_enum(e)?, + TypeDefKind::List(ty) => { + let ty = self.encode_valtype(resolve, ty)?; + let (index, encoder) = self.defined_type(); + encoder.list(ty); + ComponentValType::Type(index) + } + TypeDefKind::Map(key_ty, value_ty) => { + let key = self.encode_valtype(resolve, key_ty)?; + let value = self.encode_valtype(resolve, value_ty)?; + let (index, encoder) = self.defined_type(); + encoder.map(key, value); + ComponentValType::Type(index) + } + TypeDefKind::FixedLengthList(ty, elements) => { + let ty = self.encode_valtype(resolve, ty)?; + let (index, encoder) = self.defined_type(); + encoder.fixed_length_list(ty, *elements); + ComponentValType::Type(index) + } + TypeDefKind::Type(ty) => self.encode_valtype(resolve, ty)?, + TypeDefKind::Future(ty) => self.encode_future(resolve, ty)?, + TypeDefKind::Stream(ty) => self.encode_stream(resolve, ty)?, + TypeDefKind::Unknown => unreachable!(), + TypeDefKind::Resource => { + let name = ty.name.as_ref().expect("resources must be named"); + let index = + self.export_resource(extern_name(name, ty.external_id.as_deref())); + self.type_encoding_maps().id_to_index.insert(id, index); + return Ok(ComponentValType::Type(index)); + } + TypeDefKind::Handle(Handle::Own(id)) => { + let ty = match self.encode_valtype(resolve, &Type::Id(*id))? { + ComponentValType::Type(index) => index, + _ => panic!("must be an indexed type"), + }; + let (index, encoder) = self.defined_type(); + encoder.own(ty); + ComponentValType::Type(index) + } + TypeDefKind::Handle(Handle::Borrow(id)) => { + let ty = match self.encode_valtype(resolve, &Type::Id(*id))? { + ComponentValType::Type(index) => index, + _ => panic!("must be an indexed type"), + }; + let (index, encoder) = self.defined_type(); + encoder.borrow(ty); + ComponentValType::Type(index) + } + }; + + if let Some(name) = &ty.name { + let index = match encoded { + ComponentValType::Type(index) => index, + ComponentValType::Primitive(ty) => { + // Named primitive types need entries in the type + // section, so convert this to a type reference + let (index, encoder) = self.defined_type(); + encoder.primitive(ty); + index + } + }; + let index = self + .export_type(index, extern_name(name, ty.external_id.as_deref())) + .unwrap_or(index); + + encoded = ComponentValType::Type(index); + } + + if let ComponentValType::Type(index) = encoded { + self.type_encoding_maps().insert(resolve, id, index); + } + + encoded + } + }) + } + + /// Optionally imports `id` from a different interface, returning the index + /// of the imported type into this index space. + /// + /// Returns `None` if `id` can't be imported. + fn maybe_import_type(&mut self, resolve: &Resolve, id: TypeId) -> Option { + let ty = &resolve.types[id]; + let owner = match ty.owner { + TypeOwner::Interface(i) => i, + _ => return None, + }; + if Some(owner) == self.interface() { + return None; + } + Some(self.import_type(owner, id)) + } + + fn encode_optional_valtype( + &mut self, + resolve: &'a Resolve, + ty: Option<&Type>, + ) -> Result> { + match ty { + Some(ty) => self.encode_valtype(resolve, ty).map(Some), + None => Ok(None), + } + } + + fn encode_record(&mut self, resolve: &'a Resolve, record: &Record) -> Result { + let fields = record + .fields + .iter() + .map(|f| Ok((f.name.as_str(), self.encode_valtype(resolve, &f.ty)?))) + .collect::>>()?; + + let (index, encoder) = self.defined_type(); + encoder.record(fields); + Ok(ComponentValType::Type(index)) + } + + fn encode_tuple(&mut self, resolve: &'a Resolve, tuple: &Tuple) -> Result { + let tys = tuple + .types + .iter() + .map(|ty| self.encode_valtype(resolve, ty)) + .collect::>>()?; + let (index, encoder) = self.defined_type(); + encoder.tuple(tys); + Ok(ComponentValType::Type(index)) + } + + fn encode_flags(&mut self, flags: &Flags) -> Result { + let (index, encoder) = self.defined_type(); + encoder.flags(flags.flags.iter().map(|f| f.name.as_str())); + Ok(ComponentValType::Type(index)) + } + + fn encode_variant( + &mut self, + resolve: &'a Resolve, + variant: &Variant, + ) -> Result { + let cases = variant + .cases + .iter() + .map(|c| { + Ok(( + c.name.as_str(), + self.encode_optional_valtype(resolve, c.ty.as_ref())?, + )) + }) + .collect::>>()?; + + let (index, encoder) = self.defined_type(); + encoder.variant(cases); + Ok(ComponentValType::Type(index)) + } + + fn encode_option(&mut self, resolve: &'a Resolve, payload: &Type) -> Result { + let ty = self.encode_valtype(resolve, payload)?; + let (index, encoder) = self.defined_type(); + encoder.option(ty); + Ok(ComponentValType::Type(index)) + } + + fn encode_result( + &mut self, + resolve: &'a Resolve, + result: &Result_, + ) -> Result { + let ok = self.encode_optional_valtype(resolve, result.ok.as_ref())?; + let error = self.encode_optional_valtype(resolve, result.err.as_ref())?; + let (index, encoder) = self.defined_type(); + encoder.result(ok, error); + Ok(ComponentValType::Type(index)) + } + + fn encode_enum(&mut self, enum_: &Enum) -> Result { + let (index, encoder) = self.defined_type(); + encoder.enum_type(enum_.cases.iter().map(|c| c.name.as_str())); + Ok(ComponentValType::Type(index)) + } + + fn encode_future( + &mut self, + resolve: &'a Resolve, + payload: &Option, + ) -> Result { + let ty = self.encode_optional_valtype(resolve, payload.as_ref())?; + let (index, encoder) = self.defined_type(); + encoder.future(ty); + Ok(ComponentValType::Type(index)) + } + + fn encode_stream( + &mut self, + resolve: &'a Resolve, + payload: &Option, + ) -> Result { + let ty = self.encode_optional_valtype(resolve, payload.as_ref())?; + let (index, encoder) = self.defined_type(); + encoder.stream(ty); + Ok(ComponentValType::Type(index)) + } + + fn encode_unit_future(&mut self) -> u32 { + if let Some(index) = self.type_encoding_maps().unit_future { + return index; + } + let (index, encoder) = self.defined_type(); + encoder.future(None); + self.type_encoding_maps().unit_future = Some(index); + index + } + + fn encode_unit_stream(&mut self) -> u32 { + if let Some(index) = self.type_encoding_maps().unit_stream { + return index; + } + let (index, encoder) = self.defined_type(); + encoder.stream(None); + self.type_encoding_maps().unit_stream = Some(index); + index + } +} + +/// Helper to create a `ComponentExternName` from its component parts found +/// within a WIT AST node. +pub fn extern_name<'a>(name: &'a str, external_id: Option<&'a str>) -> ComponentExternName<'a> { + ComponentExternName { + name: name.into(), + implements: None, + external_id: external_id.map(|s| s.into()), + version_suffix: None, + } +} + +pub struct RootTypeEncoder<'state, 'a> { + pub state: &'state mut EncodingState<'a>, + pub interface: Option, + pub import_types: bool, +} + +impl<'a> ValtypeEncoder<'a> for RootTypeEncoder<'_, 'a> { + fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { + self.state.component.type_defined(None) + } + fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { + self.state.component.type_function(None) + } + fn interface(&self) -> Option { + self.interface + } + fn export_type(&mut self, idx: u32, name: ComponentExternName<'a>) -> Option { + // When encoding types for the root the root component will export + // this type, but when encoding types for a targeted interface then we + // can't export types just yet. Interfaces will be created as an + // instance with a bag-of-exports construction which can't refer to its + // own types. + if self.interface.is_none() { + Some(if self.import_types { + self.state + .component + .import(name, ComponentTypeRef::Type(TypeBounds::Eq(idx))) + } else { + self.state + .component + .export(name, ComponentExportKind::Type, idx, None) + }) + } else { + assert!(!self.import_types); + None + } + } + fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32 { + assert!(self.interface.is_none()); + assert!(self.import_types); + self.state + .component + .import(name, ComponentTypeRef::Type(TypeBounds::SubResource)) + } + fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 { + self.state.alias_instance_type_export(interface, id) + } + fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { + &mut self.state.type_encoding_maps + } +} + +pub struct InstanceTypeEncoder<'state, 'a> { + pub state: &'state mut EncodingState<'a>, + pub interface: InterfaceId, + pub type_encoding_maps: TypeEncodingMaps<'a>, + pub ty: InstanceType, +} + +impl<'a> ValtypeEncoder<'a> for InstanceTypeEncoder<'_, 'a> { + fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { + (self.ty.type_count(), self.ty.ty().defined_type()) + } + fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { + (self.ty.type_count(), self.ty.ty().function()) + } + fn export_type(&mut self, idx: u32, name: ComponentExternName<'a>) -> Option { + let ret = self.ty.type_count(); + self.ty + .export(name, ComponentTypeRef::Type(TypeBounds::Eq(idx))); + Some(ret) + } + fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32 { + let ret = self.ty.type_count(); + self.ty + .export(name, ComponentTypeRef::Type(TypeBounds::SubResource)); + ret + } + fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { + &mut self.type_encoding_maps + } + fn interface(&self) -> Option { + Some(self.interface) + } + fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 { + self.ty.alias(Alias::Outer { + count: 1, + index: self.state.alias_instance_type_export(interface, id), + kind: ComponentOuterAliasKind::Type, + }); + self.ty.type_count() - 1 + } +} diff --git a/vendor/wit-component/src/encoding/wit.rs b/vendor/wit-component/src/encoding/wit.rs new file mode 100644 index 00000000..a70f90cc --- /dev/null +++ b/vendor/wit-component/src/encoding/wit.rs @@ -0,0 +1,408 @@ +use crate::encoding::types::{TypeEncodingMaps, ValtypeEncoder, extern_name}; +use anyhow::Result; +use indexmap::IndexSet; +use std::collections::HashMap; +use std::mem; +use wasm_encoder::*; +use wit_parser::*; + +/// Encodes the given `package` within `resolve` to a binary WebAssembly +/// representation. +/// +/// This function is the root of the implementation of serializing a WIT package +/// into a WebAssembly representation. The wasm representation serves two +/// purposes: +/// +/// * One is to be a binary encoding of a WIT document which is ideally more +/// stable than the WIT textual format itself. +/// * Another is to provide a clear mapping of all WIT features into the +/// component model through use of its binary representation. +/// +/// The `resolve` provided is a set of packages and types and such and the +/// `package` argument is an ID within the world provided. The documents within +/// `package` will all be encoded into the binary returned. +/// +/// The binary returned can be [`decode`d](crate::decode) to recover the WIT +/// package provided. +pub fn encode(resolve: &Resolve, package: PackageId) -> Result> { + let mut component = encode_component(resolve, package)?; + component.raw_custom_section(&crate::base_producers().raw_custom_section()); + Ok(component.finish()) +} + +/// Encodes the given `package` within `resolve` to a binary WebAssembly +/// representation. +/// +/// This function is the root of the implementation of serializing a WIT package +/// into a WebAssembly representation. The wasm representation serves two +/// purposes: +/// +/// * One is to be a binary encoding of a WIT document which is ideally more +/// stable than the WIT textual format itself. +/// * Another is to provide a clear mapping of all WIT features into the +/// component model through use of its binary representation. +/// +/// The `resolve` provided is a set of packages and types and such and the +/// `package` argument is an ID within the world provided. The documents within +/// `package` will all be encoded into the binary returned. +/// +/// The binary returned can be [`decode`d](crate::decode) to recover the WIT +/// package provided. +pub fn encode_component(resolve: &Resolve, package: PackageId) -> Result { + let mut encoder = Encoder { + component: ComponentBuilder::default(), + resolve, + package, + }; + encoder.run()?; + + let package_metadata = PackageMetadata::extract(resolve, package); + encoder.component.custom_section(&CustomSection { + name: PackageMetadata::SECTION_NAME.into(), + data: package_metadata.encode()?.into(), + }); + + Ok(encoder.component) +} + +/// Encodes a `world` as a component type. +pub fn encode_world(resolve: &Resolve, world_id: WorldId) -> Result { + let mut component = InterfaceEncoder::new(resolve); + let world = &resolve.worlds[world_id]; + log::trace!("encoding world {}", world.name); + + // Encode the imports + for (key, import) in world.imports.iter() { + log::trace!("encoding import {}", resolve.name_world_key(key)); + let ty = match import { + WorldItem::Interface { id, .. } => { + component.interface = Some(*id); + let idx = component.encode_instance(*id)?; + ComponentTypeRef::Instance(idx) + } + WorldItem::Function(f) => { + component.interface = None; + let idx = component.encode_func_type(resolve, f)?; + ComponentTypeRef::Func(idx) + } + WorldItem::Type { id, .. } => { + component.interface = None; + component.import_types = true; + component.encode_valtype(resolve, &Type::Id(*id))?; + component.import_types = false; + continue; + } + }; + component + .outer + .import(component_extern_name(resolve, key, import), ty); + } + // Encode the exports + for (key, export) in world.exports.iter() { + log::trace!("encoding export {}", resolve.name_world_key(key)); + let ty = match export { + WorldItem::Interface { id, .. } => { + component.interface = Some(*id); + let idx = component.encode_instance(*id)?; + ComponentTypeRef::Instance(idx) + } + WorldItem::Function(f) => { + component.interface = None; + let idx = component.encode_func_type(resolve, f)?; + ComponentTypeRef::Func(idx) + } + WorldItem::Type { .. } => unreachable!(), + }; + component + .outer + .export(component_extern_name(resolve, key, export), ty); + } + + Ok(component.outer) +} + +fn component_extern_name( + resolve: &Resolve, + key: &WorldKey, + item: &WorldItem, +) -> wasm_encoder::ComponentExternName<'static> { + ComponentExternName { + name: resolve.name_world_key(key).into(), + implements: resolve.implements_value(key, item).map(|s| s.into()), + external_id: resolve.external_id_value(key, item).map(|s| s.into()), + version_suffix: None, + } +} + +struct Encoder<'a> { + component: ComponentBuilder, + resolve: &'a Resolve, + package: PackageId, +} + +impl Encoder<'_> { + fn run(&mut self) -> Result<()> { + // Encode all interfaces as component types and then export them. + for (name, &id) in self.resolve.packages[self.package].interfaces.iter() { + let component_ty = self.encode_interface(id)?; + let ty = self.component.type_component(Some(name), &component_ty); + self.component + .export(name, ComponentExportKind::Type, ty, None); + } + + // For each `world` encode it directly as a component and then create a + // wrapper component that exports that component. + for (name, &world) in self.resolve.packages[self.package].worlds.iter() { + let component_ty = encode_world(self.resolve, world)?; + + let world = &self.resolve.worlds[world]; + let mut wrapper = ComponentType::new(); + wrapper.ty().component(&component_ty); + let pkg = &self.resolve.packages[world.package.unwrap()]; + wrapper.export(pkg.name.interface_id(name), ComponentTypeRef::Component(0)); + + let ty = self.component.type_component(Some(name), &wrapper); + self.component + .export(name, ComponentExportKind::Type, ty, None); + } + + Ok(()) + } + + fn encode_interface(&mut self, id: InterfaceId) -> Result { + // Build a set of interfaces reachable from this document, including the + // interfaces in the document itself. This is used to import instances + // into the component type we're encoding. Note that entire interfaces + // are imported with all their types as opposed to just the needed types + // in an interface for this document. That's done to assist with the + // decoding process where everyone's view of a foreign document agrees + // notably on the order that types are defined in to assist with + // roundtripping. + let mut interfaces = IndexSet::new(); + self.add_live_interfaces(&mut interfaces, id); + + // Seed the set of used names with all exported interfaces to ensure + // that imported interfaces choose different names as the import names + // aren't used during decoding. + let mut used_names = IndexSet::new(); + for id in interfaces.iter() { + let iface = &self.resolve.interfaces[*id]; + if iface.package == Some(self.package) { + let first = used_names.insert(iface.name.as_ref().unwrap().clone()); + assert!(first); + } + } + + let mut encoder = InterfaceEncoder::new(self.resolve); + for interface in interfaces { + encoder.interface = Some(interface); + let iface = &self.resolve.interfaces[interface]; + let name = self.resolve.id_of(interface).unwrap(); + if interface == id { + let idx = encoder.encode_instance(interface)?; + log::trace!("exporting self as {idx}"); + encoder.outer.export(name, ComponentTypeRef::Instance(idx)); + } else { + encoder.push_instance(); + for (_, id) in iface.types.iter() { + encoder.encode_valtype(self.resolve, &Type::Id(*id))?; + } + let instance = encoder.pop_instance(); + let idx = encoder.outer.type_count(); + encoder.outer.ty().instance(&instance); + encoder.import_map.insert(interface, encoder.instances); + encoder.instances += 1; + encoder.outer.import(name, ComponentTypeRef::Instance(idx)); + } + } + + encoder.interface = None; + + Ok(encoder.outer) + } + + /// Recursively add all live interfaces reachable from `id` into the + /// `interfaces` set, and then add `id` to the set. + fn add_live_interfaces(&self, interfaces: &mut IndexSet, id: InterfaceId) { + if interfaces.contains(&id) { + return; + } + for id in self.resolve.interface_direct_deps(id) { + self.add_live_interfaces(interfaces, id); + } + assert!(interfaces.insert(id)); + } +} + +struct InterfaceEncoder<'a> { + resolve: &'a Resolve, + outer: ComponentType, + ty: Option, + type_encoding_maps: TypeEncodingMaps<'a>, + saved_maps: Option>, + import_map: HashMap, + outer_type_map: HashMap, + instances: u32, + import_types: bool, + interface: Option, +} + +impl InterfaceEncoder<'_> { + fn new(resolve: &Resolve) -> InterfaceEncoder<'_> { + InterfaceEncoder { + resolve, + outer: ComponentType::new(), + ty: None, + type_encoding_maps: Default::default(), + import_map: Default::default(), + outer_type_map: Default::default(), + instances: 0, + saved_maps: None, + import_types: false, + interface: None, + } + } + + fn encode_instance(&mut self, interface: InterfaceId) -> Result { + self.push_instance(); + let iface = &self.resolve.interfaces[interface]; + let mut type_order = IndexSet::new(); + for (_, id) in iface.types.iter() { + self.encode_valtype(self.resolve, &Type::Id(*id))?; + type_order.insert(*id); + } + + // Sort functions based on whether or not they're associated with + // resources. + // + // This is done here to ensure that when a WIT package is printed as WIT + // then decoded, or if it's printed as Wasm then decoded, the final + // result is the same. When printing via WIT resource methods are + // attached to the resource types themselves meaning that they'll appear + // intermingled with the rest of the types, namely first before all + // other functions. The purpose of this sort is to perform a stable sort + // over all functions by shuffling the resource-related functions first, + // in order of when their associated resource was encoded, and putting + // freestanding functions last. + // + // Note that this is not actually required for correctness, it's + // basically here to make fuzzing happy. + let mut funcs = iface.functions.iter().collect::>(); + funcs.sort_by_key(|(_name, func)| match func.kind.resource() { + Some(id) => type_order.get_index_of(&id).unwrap(), + None => type_order.len(), + }); + + for (name, func) in funcs { + let ty = self.encode_func_type(self.resolve, func)?; + self.ty.as_mut().unwrap().export( + extern_name(name, func.external_id.as_deref()), + ComponentTypeRef::Func(ty), + ); + } + let instance = self.pop_instance(); + let idx = self.outer.type_count(); + self.outer.ty().instance(&instance); + self.import_map.insert(interface, self.instances); + self.instances += 1; + Ok(idx) + } + + fn push_instance(&mut self) { + assert!(self.ty.is_none()); + assert!(self.saved_maps.is_none()); + self.saved_maps = Some(mem::take(&mut self.type_encoding_maps)); + self.ty = Some(InstanceType::default()); + } + + fn pop_instance(&mut self) -> InstanceType { + let maps = self.saved_maps.take().unwrap(); + self.type_encoding_maps = maps; + mem::take(&mut self.ty).unwrap() + } +} + +impl<'a> ValtypeEncoder<'a> for InterfaceEncoder<'a> { + fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { + match &mut self.ty { + Some(ty) => (ty.type_count(), ty.ty().defined_type()), + None => (self.outer.type_count(), self.outer.ty().defined_type()), + } + } + fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { + match &mut self.ty { + Some(ty) => (ty.type_count(), ty.ty().function()), + None => (self.outer.type_count(), self.outer.ty().function()), + } + } + fn export_type(&mut self, index: u32, name: ComponentExternName<'a>) -> Option { + match &mut self.ty { + Some(ty) => { + assert!(!self.import_types); + let ret = ty.type_count(); + ty.export(name, ComponentTypeRef::Type(TypeBounds::Eq(index))); + Some(ret) + } + None => { + let ret = self.outer.type_count(); + if self.import_types { + self.outer + .import(name, ComponentTypeRef::Type(TypeBounds::Eq(index))); + } else { + self.outer + .export(name, ComponentTypeRef::Type(TypeBounds::Eq(index))); + } + Some(ret) + } + } + } + fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32 { + let type_ref = ComponentTypeRef::Type(TypeBounds::SubResource); + match &mut self.ty { + Some(ty) => { + assert!(!self.import_types); + ty.export(name, type_ref); + ty.type_count() - 1 + } + None => { + if self.import_types { + self.outer.import(name, type_ref); + } else { + self.outer.export(name, type_ref); + } + self.outer.type_count() - 1 + } + } + } + fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { + &mut self.type_encoding_maps + } + fn interface(&self) -> Option { + self.interface + } + fn import_type(&mut self, owner: InterfaceId, id: TypeId) -> u32 { + let ty = &self.resolve.types[id]; + let instance = self.import_map[&owner]; + let outer_idx = *self.outer_type_map.entry(id).or_insert_with(|| { + let ret = self.outer.type_count(); + self.outer.alias(Alias::InstanceExport { + instance, + name: ty.name.as_ref().unwrap(), + kind: ComponentExportKind::Type, + }); + ret + }); + match &mut self.ty { + Some(ty) => { + let ret = ty.type_count(); + ty.alias(Alias::Outer { + count: 1, + index: outer_idx, + kind: ComponentOuterAliasKind::Type, + }); + ret + } + None => outer_idx, + } + } +} diff --git a/vendor/wit-component/src/encoding/world.rs b/vendor/wit-component/src/encoding/world.rs new file mode 100644 index 00000000..c95cde01 --- /dev/null +++ b/vendor/wit-component/src/encoding/world.rs @@ -0,0 +1,606 @@ +use super::{Adapter, ComponentEncoder, LibraryInfo, RequiredOptions}; +use crate::validation::{ + Import, ImportMap, PayloadType, ValidatedModule, validate_adapter_module, validate_module, +}; +use anyhow::{Context, Result}; +use indexmap::{IndexMap, IndexSet}; +use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; +use wit_parser::{ + Function, InterfaceId, LiveTypes, Resolve, TypeDefKind, TypeId, TypeOwner, WorldId, WorldItem, + WorldKey, + abi::{AbiVariant, WasmSignature}, +}; + +pub struct WorldAdapter<'a> { + pub wasm: Cow<'a, [u8]>, + pub info: ValidatedModule, + pub library_info: Option<&'a LibraryInfo>, +} + +/// Metadata discovered from the state configured in a `ComponentEncoder`. +/// +/// This is stored separately from `EncodingState` to be stored as a borrow in +/// `EncodingState` as this information doesn't change throughout the encoding +/// process. +pub struct ComponentWorld<'a> { + /// Encoder configuration with modules, the document ,etc. + pub encoder: &'a ComponentEncoder, + /// Validation information of the input module, or `None` in `--types-only` + /// mode. + pub info: ValidatedModule, + /// Validation information about adapters populated only for required + /// adapters. Additionally stores the gc'd wasm for each adapter. + pub adapters: IndexMap<&'a str, WorldAdapter<'a>>, + /// Map of all imports and descriptions of what they're importing. + pub import_map: IndexMap, ImportedInterface>, + /// Set of all live types which must be exported either because they're + /// directly used or because they're transitively used. + pub live_type_imports: IndexMap>, + /// For each exported interface in the desired world this map lists + /// the set of interfaces that it depends on which are also exported. + /// + /// This set is used to determine when types are imported/used whether they + /// come from imports or exports. + pub exports_used: HashMap>, +} + +#[derive(Debug)] +pub struct ImportedInterface { + pub lowerings: IndexMap<(String, AbiVariant), Lowering>, + pub interface: Option, + pub implements: Option, + pub external_id: Option, +} + +#[derive(Debug)] +pub enum Lowering { + /// This import can be `canon lower`'d at the same time that the core module + /// importing it is instantiated. + Direct { + options: RequiredOptions, + }, + /// This import requires an indirection through the shim module's table as + /// the `options` required here can only be satisfied after the core module + /// in question has been instantiated (e.g. `realloc`). + Indirect { + sig: WasmSignature, + options: RequiredOptions, + }, + ResourceDrop(TypeId), +} + +impl<'a> ComponentWorld<'a> { + pub fn new(encoder: &'a ComponentEncoder) -> Result { + let info = validate_module(encoder, &encoder.module, encoder.module_import_map.as_ref()) + .context("module was not valid")?; + + let mut ret = ComponentWorld { + encoder, + info, + adapters: IndexMap::new(), + import_map: IndexMap::new(), + live_type_imports: Default::default(), + exports_used: HashMap::new(), + }; + + ret.process_adapters()?; + ret.process_imports()?; + ret.process_exports_used(); + ret.process_live_type_imports(); + + Ok(ret) + } + + /// Returns whether the component encoding process should use context slot 1 + /// in tasks, generally reserved for TLS. + /// + /// This is a heuristic which should go away once component-model-threading + /// has been stable for awhile and the return value of this function should + /// be const-propagated as `true`. + pub fn can_use_context_slot_1(&self) -> bool { + let uses = |info: &ValidatedModule| { + info.imports.imports().any(|(_, _, import)| match import { + Import::ThreadNewIndirect + | Import::ContextGet { slot: 1, .. } + | Import::ContextSet { slot: 1, .. } => true, + _ => false, + }) + }; + uses(&self.info) || self.adapters.values().any(|a| uses(&a.info)) + } + + /// Process adapters which are required here. Iterate over all + /// adapters and figure out what functions are required from the + /// adapter itself, either because the functions are imported by the + /// main module or they're part of the adapter's exports. + fn process_adapters(&mut self) -> Result<()> { + let resolve = &self.encoder.metadata.resolve; + let world = self.encoder.metadata.world; + for ( + name, + Adapter { + wasm, + metadata: _, + required_exports, + library_info, + }, + ) in self.encoder.adapters.iter() + { + let required_by_import = self.info.imports.required_from_adapter(name.as_str()); + let no_required_by_import = || required_by_import.is_empty(); + let no_required_exports = || { + required_exports + .iter() + .all(|name| match &resolve.worlds[world].exports[name] { + WorldItem::Function(_) => false, + WorldItem::Interface { id, .. } => { + resolve.interfaces[*id].functions.is_empty() + } + WorldItem::Type { .. } => true, + }) + }; + if no_required_by_import() && no_required_exports() && library_info.is_none() { + continue; + } + let wasm = if library_info.is_some() { + Cow::Borrowed(wasm as &[u8]) + } else { + // Without `library_info` this means that this is an adapter. + // The goal of the adapter is to provide a suite of symbols that + // can be imported, but not all symbols may be imported. Here + // the module is trimmed down to only what's needed by the + // original main module. + // + // The main module requires `required_by_import` above, but + // adapters may themselves also export WIT items. To handle this + // the sequence of operations here are: + // + // 1. First the adapter is validated as-is. This ensures that + // everything looks good before GC. + // 2. The metadata from step (1) is used to determine the set of + // WIT-level exports that are needed. This includes things + // like realloc functions and such. + // 3. The set of WIT-level functions from (2) is unioned with + // `required_by_import` to create the set of required exports + // of the adapter. + // 4. This set of exports is used to delete some exports of the + // adapter and then perform a GC pass. + // + // Finally at the end of all of this the + // `validate_adapter_module` method is called for a second time + // on the minimized adapter. This is done because deleting + // imports may have deleted some imports which means that the + // final component may not need to import as many interfaces. + let info = validate_adapter_module( + self.encoder, + &wasm, + &required_by_import, + required_exports, + library_info.as_ref(), + ) + .with_context(|| { + format!("failed to validate the imports of the adapter module `{name}`") + })?; + let mut required = IndexSet::new(); + for (name, _ty) in required_by_import.iter() { + required.insert(name.to_string()); + } + for (name, _export) in info.exports.iter() { + required.insert(name.to_string()); + } + + Cow::Owned( + crate::gc::run( + wasm, + &required, + if self.encoder.realloc_via_memory_grow { + None + } else { + self.info.exports.realloc_to_import_into_adapter() + }, + ) + .context("failed to reduce input adapter module to its minimal size")?, + ) + }; + let info = validate_adapter_module( + self.encoder, + &wasm, + &required_by_import, + required_exports, + library_info.as_ref(), + ) + .with_context(|| { + format!("failed to validate the imports of the minimized adapter module `{name}`") + })?; + self.adapters.insert( + name, + WorldAdapter { + info, + wasm, + library_info: library_info.as_ref(), + }, + ); + } + Ok(()) + } + + /// Fills out the `import_map` field of `self` by determining the live + /// functions from all imports. This additionally classifies imported + /// functions into direct or indirect lowerings for managing shims. + fn process_imports(&mut self) -> Result<()> { + let resolve = &self.encoder.metadata.resolve; + let world = self.encoder.metadata.world; + + // Inspect all imports of the main module and adapters to find all + // WIT-looking things and register those as required. This is used to + // prune out unneeded things in the `add_item` function below. + let mut required = Required::default(); + for (_, _, import) in self + .adapters + .values() + .flat_map(|a| a.info.imports.imports()) + .chain(self.info.imports.imports()) + { + match import { + Import::WorldFunc(_, name, abi) => { + required + .interface_funcs + .entry(None) + .or_default() + .insert((name, *abi)); + } + Import::InterfaceFunc(_, id, name, abi) => { + required + .interface_funcs + .entry(Some(*id)) + .or_default() + .insert((name, *abi)); + } + Import::ImportedResourceDrop(_, _, id) => { + required.resource_drops.insert(*id); + } + _ => {} + } + } + for (name, item) in resolve.worlds[world].imports.iter() { + add_item( + &mut self.import_map, + resolve, + name, + item, + &required, + &self.info, + )?; + } + return Ok(()); + + fn add_item( + import_map: &mut IndexMap, ImportedInterface>, + resolve: &Resolve, + key: &WorldKey, + item: &WorldItem, + required: &Required<'_>, + info: &ValidatedModule, + ) -> Result<()> { + let name = resolve.name_world_key(key); + log::trace!("register import `{name}`"); + let import_map_key = match item { + WorldItem::Function(_) | WorldItem::Type { .. } => None, + WorldItem::Interface { .. } => Some(name), + }; + let interface_id = match item { + WorldItem::Function(_) | WorldItem::Type { .. } => None, + WorldItem::Interface { id, .. } => Some(*id), + }; + let implements = resolve.implements_value(key, item); + // Note that `external_id` is only tracked for interface imports + // here. World-level functions and types all share the `None` entry + // in `import_map` but each item can have its own `external-id` + // which is emitted on a per-item basis instead. + let external_id = match item { + WorldItem::Function(_) | WorldItem::Type { .. } => None, + WorldItem::Interface { .. } => resolve.external_id_value(key, item), + }; + let interface = import_map + .entry(import_map_key) + .or_insert_with(|| ImportedInterface { + interface: interface_id, + lowerings: Default::default(), + implements: implements.clone(), + external_id: external_id.clone(), + }); + assert_eq!(interface.interface, interface_id); + assert_eq!(interface.implements, implements); + assert_eq!(interface.external_id, external_id); + match item { + WorldItem::Function(func) => { + interface.add_func(required, resolve, func, info); + } + WorldItem::Type { id, .. } => { + interface.add_type(required, resolve, *id); + } + WorldItem::Interface { id, .. } => { + for (_name, ty) in resolve.interfaces[*id].types.iter() { + interface.add_type(required, resolve, *ty); + } + for (_name, func) in resolve.interfaces[*id].functions.iter() { + interface.add_func(required, resolve, func, info); + } + } + } + Ok(()) + } + } + + /// Determines the set of live imported types which are required to satisfy + /// the imports and exports of the lifted core module. + fn process_live_type_imports(&mut self) { + let mut live = LiveTypes::default(); + let resolve = &self.encoder.metadata.resolve; + let world = self.encoder.metadata.world; + + // First use the previously calculated metadata about live imports to + // determine the set of live types in those imports. + self.add_live_imports(world, &self.info.imports, &mut live); + for (adapter_name, adapter) in self.adapters.iter() { + log::trace!("processing adapter `{adapter_name}`"); + self.add_live_imports(world, &adapter.info.imports, &mut live); + } + + // Next any imported types used by an export must also be considered + // live. This is a little tricky though because interfaces can be both + // imported and exported, so it's not as simple as registering the + // entire export's set of types and their transitive references + // (otherwise if you only export an interface it would consider those + // types imports live too). + // + // Here if the export is an interface the set of live types for that + // interface is calculated separately. The `exports_used` field + // previously calculated is then consulted to add any types owned by + // interfaces not in the `exports_used` set to the live imported types + // set. This means that only types not defined by referenced exports + // will get added here. + for (name, item) in resolve.worlds[world].exports.iter() { + log::trace!("add live world export `{}`", resolve.name_world_key(name)); + let id = match item { + WorldItem::Interface { id, .. } => id, + WorldItem::Function(_) | WorldItem::Type { .. } => { + live.add_world_item(resolve, item); + continue; + } + }; + + let exports_used = &self.exports_used[id]; + let mut live_from_export = LiveTypes::default(); + live_from_export.add_world_item(resolve, item); + for ty in live_from_export.iter() { + let owner = match resolve.types[ty].owner { + TypeOwner::Interface(id) => id, + _ => continue, + }; + if owner != *id && !exports_used.contains(&owner) { + live.add_type_id(resolve, ty); + } + } + } + + for live in live.iter() { + let owner = match resolve.types[live].owner { + TypeOwner::Interface(id) => id, + _ => continue, + }; + self.live_type_imports + .entry(owner) + .or_insert(Default::default()) + .insert(live); + } + } + + fn add_live_imports(&self, world: WorldId, imports: &ImportMap, live: &mut LiveTypes) { + let resolve = &self.encoder.metadata.resolve; + let world = &resolve.worlds[world]; + + // FIXME: ideally liveness information here would be plumbed through to + // encoding but that's not done at this time. Only liveness for each + // interface is plumbed so top-level world types are unconditionally + // encoded and therefore unconditionally live here. Once encoding is + // based on conditionally-live things then this should be removed. + for (_, item) in world.imports.iter() { + if let WorldItem::Type { id, .. } = item { + live.add_type_id(resolve, *id); + } + } + + for (_, _, import) in imports.imports() { + match import { + // WIT-level function imports need the associated WIT definition. + Import::WorldFunc(key, _, _) => { + live.add_world_item(resolve, &world.imports[key]); + } + Import::InterfaceFunc(_, id, name, _) => { + live.add_func(resolve, &resolve.interfaces[*id].functions[name]); + } + + // Resource-related intrinsics will need the resource. + Import::ImportedResourceDrop(.., ty) + | Import::ExportedResourceDrop(_, ty) + | Import::ExportedResourceNew(_, ty) + | Import::ExportedResourceRep(_, ty) => live.add_type_id(resolve, *ty), + + // Future/Stream related intrinsics need to refer to the type + // that the intrinsic is operating on. + Import::StreamNew(info) + | Import::StreamRead { info, async_: _ } + | Import::StreamWrite { info, async_: _ } + | Import::StreamCancelRead { info, async_: _ } + | Import::StreamCancelWrite { info, async_: _ } + | Import::StreamDropReadable(info) + | Import::StreamDropWritable(info) + | Import::FutureNew(info) + | Import::FutureRead { info, async_: _ } + | Import::FutureWrite { info, async_: _ } + | Import::FutureCancelRead { info, async_: _ } + | Import::FutureCancelWrite { info, async_: _ } + | Import::FutureDropReadable(info) + | Import::FutureDropWritable(info) => { + if let PayloadType::Type { id, .. } = info.ty { + live.add_type_id(resolve, id); + } + } + + // The `task.return` intrinsic needs to be able to refer to the + // type that is being returned. + Import::ExportedTaskReturn(.., func) => { + if let Some(ty) = func.result { + live.add_type(resolve, &ty); + } + } + + // Intrinsics that don't need to refer to WIT types can be + // skipped here. + Import::AdapterExport { .. } + | Import::MainModuleMemory(_) + | Import::MainModuleExport { .. } + | Import::Item(_) + | Import::ContextGet { .. } + | Import::ContextSet { .. } + | Import::TlsBaseGet { .. } + | Import::TlsBaseSet { .. } + | Import::BackpressureInc + | Import::BackpressureDec + | Import::WaitableSetNew + | Import::WaitableSetWait { .. } + | Import::WaitableSetPoll { .. } + | Import::WaitableSetDrop + | Import::WaitableJoin + | Import::SubtaskDrop + | Import::SubtaskCancel { .. } + | Import::ErrorContextNew { .. } + | Import::ErrorContextDebugMessage { .. } + | Import::ErrorContextDrop + | Import::ExportedTaskCancel + | Import::ThreadIndex + | Import::ThreadNewIndirect { .. } + | Import::ThreadResumeLater + | Import::ThreadSuspend { .. } + | Import::ThreadYield { .. } + | Import::ThreadSuspendThenResume { .. } + | Import::ThreadYieldThenResume { .. } + | Import::ThreadSuspendThenPromote { .. } + | Import::ThreadYieldThenPromote { .. } => {} + } + } + } + + fn process_exports_used(&mut self) { + let resolve = &self.encoder.metadata.resolve; + let world = self.encoder.metadata.world; + + let exports = &resolve.worlds[world].exports; + for (_key, item) in exports.iter() { + let id = match item { + WorldItem::Function(_) => continue, + WorldItem::Interface { id, .. } => *id, + WorldItem::Type { .. } => unreachable!(), + }; + let mut set = HashSet::new(); + + for other in resolve.interface_direct_deps(id) { + let key = WorldKey::Interface(other); + // If this dependency is not exported, then it'll show up + // through an import, so we're not interested in it. + if !exports.contains_key(&key) { + continue; + } + + // Otherwise this is a new exported dependency of ours, and + // additionally this interface inherits all the transitive + // dependencies too. + if set.insert(other) { + set.extend(self.exports_used[&other].iter().copied()); + } + } + let prev = self.exports_used.insert(id, set); + assert!(prev.is_none()); + } + } +} + +#[derive(Default)] +struct Required<'a> { + interface_funcs: IndexMap, IndexSet<(&'a str, AbiVariant)>>, + resource_drops: IndexSet, +} + +/// Returns whether `options` can all be satisfied without needing anything from +/// a core module that hasn't been instantiated yet. +fn options_are_available_before_instantiation( + options: RequiredOptions, + info: &ValidatedModule, +) -> bool { + // If neither memory nor realloc are needed, this can always be lowered + // eagerly. + if !options.contains(RequiredOptions::MEMORY) && !options.contains(RequiredOptions::REALLOC) { + return true; + } + + // Otherwise this depends on linear memory. If the main module imports + // linear memory then it's available before instantiating it, and in that + // situation we'll also generate shim functions for `realloc` so that's also + // available before instantiation. + // + // If linear memory isn't imported, but instead it's only exported, then we + // can't have it before we instantiate the main module. + info.imports.imported_memory().is_some() +} + +impl ImportedInterface { + fn add_func( + &mut self, + required: &Required<'_>, + resolve: &Resolve, + func: &Function, + info: &ValidatedModule, + ) { + let mut abis = Vec::with_capacity(2); + if let Some(set) = required.interface_funcs.get(&self.interface) { + if set.contains(&(func.name.as_str(), AbiVariant::GuestImport)) { + abis.push(AbiVariant::GuestImport); + } + if set.contains(&(func.name.as_str(), AbiVariant::GuestImportAsync)) { + abis.push(AbiVariant::GuestImportAsync); + } + } + for abi in abis { + log::trace!("add func {} {abi:?}", func.name); + let options = RequiredOptions::for_import(resolve, func, abi); + let lowering = if options_are_available_before_instantiation(options, info) { + Lowering::Direct { options } + } else { + let sig = resolve.wasm_signature(abi, func); + Lowering::Indirect { sig, options } + }; + + let prev = self.lowerings.insert((func.name.clone(), abi), lowering); + assert!(prev.is_none()); + } + } + + fn add_type(&mut self, required: &Required<'_>, resolve: &Resolve, id: TypeId) { + let ty = &resolve.types[id]; + match &ty.kind { + TypeDefKind::Resource => {} + _ => return, + } + let name = ty.name.as_deref().expect("resources must be named"); + + if required.resource_drops.contains(&id) { + let name = format!("{name}_drop"); + let prev = self + .lowerings + .insert((name, AbiVariant::GuestImport), Lowering::ResourceDrop(id)); + assert!(prev.is_none()); + } + } +} diff --git a/vendor/wit-component/src/gc.rs b/vendor/wit-component/src/gc.rs new file mode 100644 index 00000000..83306041 --- /dev/null +++ b/vendor/wit-component/src/gc.rs @@ -0,0 +1,1134 @@ +use self::bitvec::BitVec; +use anyhow::{Result, bail}; +use indexmap::{IndexMap, IndexSet}; +use std::{ + borrow::Cow, + collections::{HashMap, HashSet}, + convert::Infallible, + mem, + ops::Deref, +}; +use wasm_encoder::{Encode, EntityType, RawCustomSection, reencode::Reencode}; +use wasmparser::*; + +const PAGE_SIZE: i32 = 64 * 1024; + +/// This function will reduce the input core `wasm` module to only the set of +/// exports `required`. +/// +/// This internally performs a "gc" pass after removing exports to ensure that +/// the resulting module imports the minimal set of functions necessary. +pub fn run( + wasm: &[u8], + required: &IndexSet, + main_module_realloc: Option<&str>, +) -> Result> { + assert!(!required.is_empty()); + + let mut module = Module::default(); + module.parse(wasm)?; + + // Make sure that all required names are present in the module, and then + // remove all names that are not required. + for name in required { + if !module.exports.contains_key(name.as_str()) { + bail!("adapter module does not have export `{name}`") + } + } + let mut not_required = IndexSet::new(); + for name in module.exports.keys().copied() { + if !required.contains(name) { + not_required.insert(name); + } + } + for name in not_required { + module.exports.swap_remove(name); + } + assert!(!module.exports.is_empty()); + module.liveness()?; + module.encode(main_module_realloc) +} + +/// This function generates a Wasm function body which implements `cabi_realloc` in terms of `memory.grow`. It +/// only accepts new, page-sized allocations. +fn realloc_via_memory_grow() -> wasm_encoder::Function { + let mut func = wasm_encoder::Function::new([(1, wasm_encoder::ValType::I32)]); + + // Assert `old_ptr` is null. + func.instructions().i32_const(0); + func.instructions().local_get(0); + func.instructions().i32_ne(); + func.instructions().if_(wasm_encoder::BlockType::Empty); + func.instructions().unreachable(); + func.instructions().end(); + + // Assert `old_len` is zero. + func.instructions().i32_const(0); + func.instructions().local_get(1); + func.instructions().i32_ne(); + func.instructions().if_(wasm_encoder::BlockType::Empty); + func.instructions().unreachable(); + func.instructions().end(); + + // Assert `new_len` is equal to the page size (which is the only value we currently support) + // Note: we could easily support arbitrary multiples of PAGE_SIZE here if the need arises. + func.instructions().i32_const(PAGE_SIZE); + func.instructions().local_get(3); + func.instructions().i32_ne(); + func.instructions().if_(wasm_encoder::BlockType::Empty); + func.instructions().unreachable(); + func.instructions().end(); + + // Grow the memory by 1 page. + func.instructions().i32_const(1); + func.instructions().memory_grow(0); + func.instructions().local_tee(4); + + // Test if the return value of the growth was -1 and, if so, trap due to a failed allocation. + func.instructions().i32_const(-1); + func.instructions().i32_eq(); + func.instructions().if_(wasm_encoder::BlockType::Empty); + func.instructions().unreachable(); + func.instructions().end(); + + func.instructions().local_get(4); + func.instructions().i32_const(16); + func.instructions().i32_shl(); + func.instructions().end(); + + func +} + +#[repr(i32)] +#[non_exhaustive] +enum StackAllocationState { + Unallocated, + Allocating, + Allocated, +} + +fn allocate_stack_via_realloc( + realloc_index: u32, + sp: u32, + allocation_state: Option, +) -> wasm_encoder::Function { + let mut func = wasm_encoder::Function::new([]); + + if let Some(allocation_state) = allocation_state { + // This means we're lazily allocating the stack, keeping track of state via `$allocation_state` + func.instructions().global_get(allocation_state); + func.instructions() + .i32_const(StackAllocationState::Unallocated as _); + func.instructions().i32_eq(); + func.instructions().if_(wasm_encoder::BlockType::Empty); + func.instructions() + .i32_const(StackAllocationState::Allocating as _); + func.instructions().global_set(allocation_state); + // We could also set `sp` to zero here to ensure the yet-to-be-allocated stack is empty. However, we + // assume it defaults to zero anyway, in which case setting it would be redundant. + } + + func.instructions().i32_const(0); + func.instructions().i32_const(0); + func.instructions().i32_const(8); + func.instructions().i32_const(PAGE_SIZE); + func.instructions().call(realloc_index); + func.instructions().i32_const(PAGE_SIZE); + func.instructions().i32_add(); + func.instructions().global_set(sp); + + if let Some(allocation_state) = allocation_state { + func.instructions() + .i32_const(StackAllocationState::Allocated as _); + func.instructions().global_set(allocation_state); + func.instructions().end(); + } + + func.instructions().end(); + + func +} + +// Represents a function called while processing a module work list. +type WorklistFunc<'a> = fn(&mut Module<'a>, u32) -> Result<()>; + +// Representation of a wasm module which is used to GC a module to its minimal +// set of required items necessary to implement the `exports` +// +// Note that this is not a complete representation of a wasm module since it +// doesn't represent everything such as data and element segments. This is only +// used for adapter modules which otherwise have these restrictions and makes +// this gc pass a bit easier to write. +#[derive(Default)] +struct Module<'a> { + // Definitions found when parsing a module + types: Vec, + tables: Vec>, + globals: Vec>, + memories: Vec>, + funcs: Vec>, + exports: IndexMap<&'a str, Export<'a>>, + func_names: HashMap, + global_names: HashMap, + producers: Option, + + // Known-live sets of indices after the `liveness` pass has run. + live_types: BitVec, + live_tables: BitVec, + live_globals: BitVec, + live_memories: BitVec, + live_funcs: BitVec, + + // Helper data structure used during the `liveness` path to avoid recursion. + // When calculating the liveness of an item this `worklist` is pushed to and + // then processed until it's empty. An item pushed onto this list represents + // a new index that has been discovered to be live and the function is what + // walks the item's definition to find other items that it references. + worklist: Vec<(u32, WorklistFunc<'a>)>, +} + +struct Table<'a> { + def: Definition<'a, ()>, + ty: TableType, +} + +struct Memory<'a> { + def: Definition<'a, ()>, + ty: MemoryType, +} + +struct Global<'a> { + def: Definition<'a, ConstExpr<'a>>, + ty: GlobalType, +} + +#[derive(Clone)] +struct Func<'a> { + def: Definition<'a, FunctionBody<'a>>, + ty: u32, +} + +#[derive(Clone)] +enum Definition<'a, T> { + Import(&'a str, &'a str), + Local(T), +} + +impl<'a> Module<'a> { + fn parse(&mut self, wasm: &'a [u8]) -> Result<()> { + let mut next_code_index = 0; + let mut validator = Validator::new(); + for payload in Parser::new(0).parse_all(wasm) { + let payload = payload?; + validator.payload(&payload)?; + match payload { + Payload::Version { encoding, .. } => { + if encoding != Encoding::Module { + bail!("adapter must be a core wasm module, not a component"); + } + } + Payload::End(_) => {} + Payload::TypeSection(s) => { + for ty in s.into_iter_err_on_gc_types() { + self.types.push(ty?); + } + } + Payload::ImportSection(s) => { + for i in s.into_imports() { + let i = i?; + match i.ty { + TypeRef::Func(ty) => self.funcs.push(Func { + def: Definition::Import(i.module, i.name), + ty, + }), + TypeRef::Table(ty) => self.tables.push(Table { + def: Definition::Import(i.module, i.name), + ty, + }), + TypeRef::Global(ty) => self.globals.push(Global { + def: Definition::Import(i.module, i.name), + ty, + }), + TypeRef::Memory(ty) => self.memories.push(Memory { + def: Definition::Import(i.module, i.name), + ty, + }), + TypeRef::Tag(_) => bail!("unsupported `tag` type"), + TypeRef::FuncExact(_) => { + bail!("unsupported `func_exact` type") + } + } + } + } + Payload::TableSection(s) => { + for table in s { + let table = table?; + self.tables.push(Table { + def: Definition::Local(()), + ty: table.ty, + }); + } + } + Payload::MemorySection(s) => { + for ty in s { + let ty = ty?; + self.memories.push(Memory { + def: Definition::Local(()), + ty, + }); + } + } + Payload::GlobalSection(s) => { + for g in s { + let g = g?; + self.globals.push(Global { + def: Definition::Local(g.init_expr), + ty: g.ty, + }); + } + } + + Payload::ExportSection(s) => { + for e in s { + let e = e?; + self.exports.insert(e.name, e); + } + } + + Payload::FunctionSection(s) => { + next_code_index = self.funcs.len(); + for ty in s { + let ty = ty?; + self.funcs.push(Func { + // Specify a dummy definition to get filled in later + // when parsing the code section. + def: Definition::Local(FunctionBody::new(BinaryReader::new(&[], 0))), + ty, + }); + } + } + + Payload::CodeSectionStart { .. } => {} + Payload::CodeSectionEntry(body) => { + self.funcs[next_code_index].def = Definition::Local(body); + next_code_index += 1; + } + + // Ignore all custom sections except for the `name` and + // `producers` sections which we parse, but ignore errors within. + Payload::CustomSection(s) => match s.as_known() { + KnownCustom::Name(s) => drop(self.parse_name_section(s)), + KnownCustom::Producers(_) => drop(self.parse_producers_section(&s)), + _ => {} + }, + + // sections that shouldn't appear in the specially-crafted core + // wasm adapter self we're processing + other => match other.as_section() { + Some((id, _)) => bail!("unsupported section `{id}` in adapter"), + None => bail!("unsupported payload in adapter"), + }, + } + } + + Ok(()) + } + + fn parse_name_section(&mut self, section: NameSectionReader<'a>) -> Result<()> { + for s in section { + match s? { + Name::Function(map) => { + for naming in map { + let naming = naming?; + self.func_names.insert(naming.index, naming.name); + } + } + Name::Global(map) => { + for naming in map { + let naming = naming?; + self.global_names.insert(naming.index, naming.name); + } + } + _ => {} + } + } + Ok(()) + } + + fn parse_producers_section(&mut self, section: &CustomSectionReader<'a>) -> Result<()> { + let producers = + wasm_metadata::Producers::from_bytes(section.data(), section.data_offset())?; + self.producers = Some(producers); + Ok(()) + } + + /// Iteratively calculates the set of live items within this module + /// considering all exports as the root of live functions. + fn liveness(&mut self) -> Result<()> { + let exports = mem::take(&mut self.exports); + for (_, e) in exports.iter() { + match e.kind { + ExternalKind::Func | ExternalKind::FuncExact => self.func(e.index), + ExternalKind::Global => self.global(e.index), + ExternalKind::Table => self.table(e.index), + ExternalKind::Memory => self.memory(e.index), + ExternalKind::Tag => bail!("unsupported exported tag"), + } + } + self.exports = exports; + + while let Some((idx, func)) = self.worklist.pop() { + func(self, idx)?; + } + Ok(()) + } + + fn func(&mut self, func: u32) { + if !self.live_funcs.insert(func) { + return; + } + self.worklist.push((func, |me, func| { + let func = me.funcs[func as usize].clone(); + me.ty(func.ty); + let mut body = match &func.def { + Definition::Import(..) => return Ok(()), + Definition::Local(e) => e.get_binary_reader(), + }; + let local_count = body.read_var_u32()?; + for _ in 0..local_count { + body.read_var_u32()?; + body.read::()?; + } + me.operators(body) + })); + } + + fn global(&mut self, global: u32) { + if !self.live_globals.insert(global) { + return; + } + self.worklist.push((global, |me, global| { + let init = match &me.globals[global as usize].def { + Definition::Import(..) => return Ok(()), + Definition::Local(e) => e, + }; + me.operators(init.get_binary_reader()) + })); + } + + fn table(&mut self, table: u32) { + if !self.live_tables.insert(table) { + return; + } + self.worklist.push((table, |me, table| { + let ty = me.tables[table as usize].ty.element_type; + me.valty(ty.into()); + Ok(()) + })); + } + + fn memory(&mut self, memory: u32) { + self.live_memories.insert(memory); + } + + fn blockty(&mut self, ty: BlockType) { + if let BlockType::FuncType(ty) = ty { + self.ty(ty); + } + } + + fn valty(&mut self, ty: ValType) { + match ty { + ValType::Ref(r) => self.refty(r), + ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 | ValType::V128 => {} + } + } + + fn valtys(&mut self, tys: &[ValType]) { + for i in tys { + self.valty(*i); + } + } + + fn refty(&mut self, ty: RefType) { + self.heapty(ty.heap_type()) + } + + fn heapty(&mut self, ty: HeapType) { + match ty { + HeapType::Abstract { .. } => {} + HeapType::Concrete(i) | HeapType::Exact(i) => self.ty(i.as_module_index().unwrap()), + } + } + + fn ty(&mut self, ty: u32) { + if !self.live_types.insert(ty) { + return; + } + self.worklist.push((ty, |me, ty| { + let ty = me.types[ty as usize].clone(); + for param in ty.params().iter().chain(ty.results()) { + me.valty(*param); + } + Ok(()) + })); + } + + fn operators(&mut self, reader: BinaryReader<'a>) -> Result<()> { + let mut ops = OperatorsReader::new(reader); + while !ops.eof() { + ops.visit_operator(self)?; + } + ops.finish()?; + Ok(()) + } + + fn live_types(&self) -> impl Iterator + '_ { + live_iter(&self.live_types, self.types.iter()) + } + + fn live_funcs(&self) -> impl Iterator)> + '_ { + live_iter(&self.live_funcs, self.funcs.iter()) + } + + fn live_memories(&self) -> impl Iterator)> + '_ { + live_iter(&self.live_memories, self.memories.iter()) + } + + fn live_globals(&self) -> impl Iterator)> + '_ { + live_iter(&self.live_globals, self.globals.iter()) + } + + fn live_tables(&self) -> impl Iterator)> + '_ { + live_iter(&self.live_tables, self.tables.iter()) + } + + /// Encodes this `Module` to a new wasm module which is gc'd and only + /// contains the items that are live as calculated by the `liveness` pass. + fn encode(&mut self, main_module_realloc: Option<&str>) -> Result> { + // Data structure used to track the mapping of old index to new index + // for all live items. + let mut map = Encoder::default(); + + // Sections that will be assembled into the final module at the end of + // this function. + let mut types = wasm_encoder::TypeSection::new(); + let mut imports = wasm_encoder::ImportSection::new(); + let mut funcs = wasm_encoder::FunctionSection::new(); + let mut tables = wasm_encoder::TableSection::new(); + let mut memories = wasm_encoder::MemorySection::new(); + let mut globals = wasm_encoder::GlobalSection::new(); + let mut code = wasm_encoder::CodeSection::new(); + + let mut empty_type = None; + for (i, ty) in self.live_types() { + map.types.push(i); + + let ty = map.func_type(ty.clone())?; + types.ty().func_type(&ty); + + // Keep track of the "empty type" to see if we can reuse an + // existing one or one needs to be injected if a `start` + // function is calculated at the end. + if ty.params().is_empty() && ty.results().is_empty() { + empty_type = Some(map.types.remap(i)); + } + } + + let mut num_memories = 0; + for (i, mem) in self.live_memories() { + map.memories.push(i); + let ty = map.memory_type(mem.ty); + match &mem.def { + Definition::Import(m, n) => { + imports.import(m, n, ty?); + } + Definition::Local(()) => { + memories.memory(ty?); + } + } + num_memories += 1; + } + + for (i, table) in self.live_tables() { + map.tables.push(i); + let ty = map.table_type(table.ty)?; + match &table.def { + Definition::Import(m, n) => { + imports.import(m, n, ty); + } + Definition::Local(()) => { + tables.table(ty); + } + } + } + + for (i, global) in self.live_globals() { + map.globals.push(i); + let ty = map.global_type(global.ty)?; + match &global.def { + Definition::Import(m, n) => { + imports.import(m, n, ty); + } + Definition::Local(init) => { + let init = &map.const_expr(init.clone())?; + globals.global(ty, &init); + } + } + } + + let mut realloc_index = None; + let mut num_func_imports = 0; + + // For functions first assign a new index to all functions and then + // afterwards actually map the body of all functions so the `map` of all + // index mappings is fully populated before instructions are mapped. + + let is_realloc = + |m, n| m == "__main_module__" && matches!(n, "canonical_abi_realloc" | "cabi_realloc"); + + let (imported, local) = + self.live_funcs() + .partition::, _>(|(_, func)| match &func.def { + Definition::Import(m, n) => { + !is_realloc(*m, *n) || main_module_realloc.is_some() + } + Definition::Local(_) => false, + }); + + for (i, func) in imported { + map.funcs.push(i); + let ty = map.types.remap(func.ty); + match &func.def { + Definition::Import(m, n) => { + let name = if is_realloc(*m, *n) { + // The adapter is importing `cabi_realloc` from the main module, and the main module + // exports that function, but possibly using a different name + // (e.g. `canonical_abi_realloc`). Update the name to match if necessary. + realloc_index = Some(num_func_imports); + main_module_realloc.unwrap_or(n) + } else { + n + }; + imports.import(m, name, EntityType::Function(ty)); + num_func_imports += 1; + } + Definition::Local(_) => unreachable!(), + } + } + + let add_realloc_type = |types: &mut wasm_encoder::TypeSection| { + let type_index = types.len(); + types.ty().function( + [ + wasm_encoder::ValType::I32, + wasm_encoder::ValType::I32, + wasm_encoder::ValType::I32, + wasm_encoder::ValType::I32, + ], + [wasm_encoder::ValType::I32], + ); + type_index + }; + + let add_empty_type = |types: &mut wasm_encoder::TypeSection| { + let type_index = types.len(); + types.ty().function([], []); + type_index + }; + + let sp = self.find_mut_i32_global("__stack_pointer")?; + let allocation_state = self.find_mut_i32_global("allocation_state")?; + + let mut func_names = Vec::new(); + + if let (Some(realloc), Some(_), None) = (main_module_realloc, sp, realloc_index) { + // The main module exports a realloc function, and although the adapter doesn't import it, we're going + // to add a function which calls it to allocate some stack space, so let's add an import now. + + // Tell the function remapper we're reserving a slot for our extra import: + map.funcs.next += 1; + + realloc_index = Some(num_func_imports); + imports.import( + "__main_module__", + realloc, + EntityType::Function(add_realloc_type(&mut types)), + ); + func_names.push((num_func_imports, realloc)); + num_func_imports += 1; + } + + for (i, func) in local { + map.funcs.push(i); + let ty = map.types.remap(func.ty); + match &func.def { + Definition::Import(_, _) => { + // The adapter is importing `cabi_realloc` from the main module, but the main module isn't + // exporting it. In this case, we need to define a local function it can call instead. + realloc_index = Some(num_func_imports + funcs.len()); + funcs.function(ty); + code.function(&realloc_via_memory_grow()); + } + Definition::Local(_) => { + funcs.function(ty); + } + } + } + + let lazy_stack_init_index = + if sp.is_some() && allocation_state.is_some() && main_module_realloc.is_some() { + // We have a stack pointer, a `cabi_realloc` function from the main module, and a global variable for + // keeping track of (and short-circuiting) reentrance. That means we can (and should) do lazy stack + // allocation. + let index = num_func_imports + funcs.len(); + + // Tell the function remapper we're reserving a slot for our extra function: + map.funcs.next += 1; + + funcs.function(add_empty_type(&mut types)); + + Some(index) + } else { + None + }; + + let exported_funcs = self + .exports + .values() + .filter_map(|export| match export.kind { + ExternalKind::Func => Some(export.index), + _ => None, + }) + .collect::>(); + + for (i, func) in self.live_funcs() { + let body = match &func.def { + Definition::Import(..) => continue, + Definition::Local(body) => body, + }; + + match (lazy_stack_init_index, exported_funcs.contains(&i)) { + // Prepend an `allocate_stack` call to all exports if we're + // lazily allocating the stack. + (Some(lazy_stack_init_index), true) => { + let mut func = map.new_function_with_parsed_locals(&body)?; + func.instructions().call(lazy_stack_init_index); + let mut reader = body.get_operators_reader()?; + while !reader.eof() { + func.instruction(&map.parse_instruction(&mut reader)?); + } + code.function(&func); + } + _ => { + map.parse_function_body(&mut code, body.clone())?; + } + } + } + + if lazy_stack_init_index.is_some() { + code.function(&allocate_stack_via_realloc( + realloc_index.unwrap(), + sp.unwrap(), + allocation_state, + )); + } + + if sp.is_some() && (realloc_index.is_none() || allocation_state.is_none()) { + // Either the main module does _not_ export a realloc function, or it is not safe to use for stack + // allocation because we have no way to short-circuit reentrance, so we'll use `memory.grow` instead. + realloc_index = Some(num_func_imports + funcs.len()); + funcs.function(add_realloc_type(&mut types)); + code.function(&realloc_via_memory_grow()); + } + + // Inject a start function to initialize the stack pointer which will be local to this module. This only + // happens if a memory is preserved, a stack pointer global is found, and we're not doing lazy stack + // allocation. + let mut start = None; + if let (Some(sp), None) = (sp, lazy_stack_init_index) { + if num_memories > 0 { + // If there are any memories or any mutable globals there must be + // precisely one of each as otherwise we don't know how to filter + // down to the right one. + if num_memories != 1 { + bail!("adapter modules don't support multi-memory"); + } + + let sp = map.globals.remap(sp); + + let function_index = num_func_imports + funcs.len(); + + // Generate a function type for this start function, adding a new + // function type to the module if necessary. + let empty_type = empty_type.unwrap_or_else(|| { + types.ty().function([], []); + types.len() - 1 + }); + funcs.function(empty_type); + func_names.push((function_index, "allocate_stack")); + code.function(&allocate_stack_via_realloc( + realloc_index.unwrap(), + sp, + allocation_state, + )); + + start = Some(wasm_encoder::StartSection { function_index }); + } + } + + // Sanity-check the shape of the module since some parts won't work if + // this fails. Note that during parsing we've already validated there + // are no data segments or element segments. + + // Shouldn't have any tables if there are no element segments since + // otherwise there's no meaning to a defined or imported table. + if self.live_tables().count() != 0 { + bail!("tables should not be present in the final adapter module"); + } + + // multi-memory should not be enabled and if any memory it should be + // imported. + if self.live_memories().count() > 1 { + bail!("the adapter module should not use multi-memory"); + } + if !memories.is_empty() { + bail!("locally-defined memories are not allowed define a local memory"); + } + + let mut ret = wasm_encoder::Module::default(); + if !types.is_empty() { + ret.section(&types); + } + if !imports.is_empty() { + ret.section(&imports); + } + if !funcs.is_empty() { + ret.section(&funcs); + } + if !tables.is_empty() { + ret.section(&tables); + } + if !memories.is_empty() { + ret.section(&memories); + } + if !globals.is_empty() { + ret.section(&globals); + } + + if !self.exports.is_empty() { + let mut exports = wasm_encoder::ExportSection::new(); + for (_, export) in self.exports.iter() { + let (kind, index) = match export.kind { + ExternalKind::Func => ( + wasm_encoder::ExportKind::Func, + map.funcs.remap(export.index), + ), + ExternalKind::Table => ( + wasm_encoder::ExportKind::Table, + map.tables.remap(export.index), + ), + ExternalKind::Memory => ( + wasm_encoder::ExportKind::Memory, + map.memories.remap(export.index), + ), + ExternalKind::Global => ( + wasm_encoder::ExportKind::Global, + map.globals.remap(export.index), + ), + kind => bail!("unsupported export kind {kind:?}"), + }; + exports.export(export.name, kind, index); + } + ret.section(&exports); + } + + if let Some(start) = &start { + ret.section(start); + } + + if !code.is_empty() { + ret.section(&code); + } + + // Append a custom `name` section using the names of the functions that + // were found prior to the GC pass in the original module. + let mut global_names = Vec::new(); + for (i, _func) in self.live_funcs() { + let name = match self.func_names.get(&i) { + Some(name) => name, + None => continue, + }; + func_names.push((map.funcs.remap(i), *name)); + } + for (i, _global) in self.live_globals() { + let name = match self.global_names.get(&i) { + Some(name) => name, + None => continue, + }; + global_names.push((map.globals.remap(i), *name)); + } + let mut section = Vec::new(); + let mut encode_subsection = |code: u8, names: &[(u32, &str)]| { + if names.is_empty() { + return; + } + let mut subsection = Vec::new(); + names.len().encode(&mut subsection); + for (i, name) in names { + i.encode(&mut subsection); + name.encode(&mut subsection); + } + section.push(code); + subsection.encode(&mut section); + }; + if let (Some(realloc_index), true) = ( + realloc_index, + main_module_realloc.is_none() || allocation_state.is_none(), + ) { + func_names.push((realloc_index, "realloc_via_memory_grow")); + } + if let Some(lazy_stack_init_index) = lazy_stack_init_index { + func_names.push((lazy_stack_init_index, "allocate_stack")); + } + encode_subsection(0x01, &func_names); + encode_subsection(0x07, &global_names); + if !section.is_empty() { + ret.section(&wasm_encoder::CustomSection { + name: "name".into(), + data: Cow::Borrowed(§ion), + }); + } + if let Some(producers) = &self.producers { + ret.section(&RawCustomSection(&producers.raw_custom_section())); + } + + Ok(ret.finish()) + } + + fn find_mut_i32_global(&self, name: &str) -> Result> { + let matches = &self + .live_globals() + .filter_map(|(i, g)| { + if g.ty.mutable + && g.ty.content_type == ValType::I32 + && *self.global_names.get(&i)? == name + { + Some(i) + } else { + None + } + }) + .collect::>(); + + match matches.deref() { + [] => Ok(None), + [i] => Ok(Some(*i)), + _ => bail!( + "found {} mutable i32 globals with name {name}", + matches.len() + ), + } + } +} + +// This helper macro is used to define a visitor of all instructions with +// special handling for all payloads of instructions to mark any referenced +// items live. +// +// Currently item identification happens through the field name of the payload. +// While not exactly the most robust solution this should work well enough for +// now. +macro_rules! define_visit { + ($(@$p:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => { + $( + #[allow(unused_variables)] + fn $visit(&mut self $(, $($arg: $argty),*)?) { + $( + $( + define_visit!(mark_live self $arg $arg); + )* + )? + } + )* + }; + + (mark_live $self:ident $arg:ident type_index) => {$self.ty($arg);}; + (mark_live $self:ident $arg:ident array_type_index) => {$self.ty($arg);}; + (mark_live $self:ident $arg:ident array_type_index_dst) => {$self.ty($arg);}; + (mark_live $self:ident $arg:ident array_type_index_src) => {$self.ty($arg);}; + (mark_live $self:ident $arg:ident struct_type_index) => {$self.ty($arg);}; + (mark_live $self:ident $arg:ident src_table) => {$self.table($arg);}; + (mark_live $self:ident $arg:ident dst_table) => {$self.table($arg);}; + (mark_live $self:ident $arg:ident table_index) => {$self.table($arg);}; + (mark_live $self:ident $arg:ident table) => {$self.table($arg);}; + (mark_live $self:ident $arg:ident global_index) => {$self.global($arg);}; + (mark_live $self:ident $arg:ident function_index) => {$self.func($arg);}; + (mark_live $self:ident $arg:ident mem) => {$self.memory($arg);}; + (mark_live $self:ident $arg:ident src_mem) => {$self.memory($arg);}; + (mark_live $self:ident $arg:ident dst_mem) => {$self.memory($arg);}; + (mark_live $self:ident $arg:ident memarg) => {$self.memory($arg.memory);}; + (mark_live $self:ident $arg:ident blockty) => {$self.blockty($arg);}; + (mark_live $self:ident $arg:ident ty) => {$self.valty($arg)}; + (mark_live $self:ident $arg:ident tys) => {$self.valtys(&$arg)}; + (mark_live $self:ident $arg:ident hty) => {$self.heapty($arg)}; + (mark_live $self:ident $arg:ident from_ref_type) => {$self.refty($arg);}; + (mark_live $self:ident $arg:ident to_ref_type) => {$self.refty($arg);}; + (mark_live $self:ident $arg:ident lane) => {}; + (mark_live $self:ident $arg:ident lanes) => {}; + (mark_live $self:ident $arg:ident value) => {}; + (mark_live $self:ident $arg:ident local_index) => {}; + (mark_live $self:ident $arg:ident relative_depth) => {}; + (mark_live $self:ident $arg:ident tag_index) => {}; + (mark_live $self:ident $arg:ident targets) => {}; + (mark_live $self:ident $arg:ident data_index) => {}; + (mark_live $self:ident $arg:ident array_data_index) => {}; + (mark_live $self:ident $arg:ident elem_index) => {}; + (mark_live $self:ident $arg:ident array_elem_index) => {}; + (mark_live $self:ident $arg:ident array_size) => {}; + (mark_live $self:ident $arg:ident field_index) => {}; + (mark_live $self:ident $arg:ident ordering) => {}; + (mark_live $self:ident $arg:ident try_table) => {unimplemented!();}; + (mark_live $self:ident $arg:ident argument_index) => {}; + (mark_live $self:ident $arg:ident result_index) => {}; + (mark_live $self:ident $arg:ident cont_type_index) => {}; + (mark_live $self:ident $arg:ident resume_table) => {unimplemented!();}; +} + +impl<'a> VisitOperator<'a> for Module<'a> { + type Output = (); + + fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { + Some(self) + } + + wasmparser::for_each_visit_operator!(define_visit); +} + +impl<'a> VisitSimdOperator<'a> for Module<'a> { + wasmparser::for_each_visit_simd_operator!(define_visit); +} + +/// Helper function to filter `iter` based on the `live` set, yielding an +/// iterator over the index of the item that's live as well as the item itself. +fn live_iter<'a, T>( + live: &'a BitVec, + iter: impl Iterator + 'a, +) -> impl Iterator + 'a { + iter.enumerate().filter_map(|(i, t)| { + let i = i as u32; + if live.contains(i) { Some((i, t)) } else { None } + }) +} + +#[derive(Default)] +struct Encoder { + types: Remap, + funcs: Remap, + memories: Remap, + globals: Remap, + tables: Remap, +} + +type ReencodeResult = Result>; + +impl Reencode for Encoder { + type Error = Infallible; + + fn type_index(&mut self, i: u32) -> ReencodeResult { + Ok(self.types.remap(i)) + } + fn function_index(&mut self, i: u32) -> ReencodeResult { + Ok(self.funcs.remap(i)) + } + fn memory_index(&mut self, i: u32) -> ReencodeResult { + Ok(self.memories.remap(i)) + } + fn global_index(&mut self, i: u32) -> ReencodeResult { + Ok(self.globals.remap(i)) + } + fn table_index(&mut self, i: u32) -> ReencodeResult { + Ok(self.tables.remap(i)) + } +} + +// Minimal definition of a bit vector necessary for the liveness calculations +// above. +mod bitvec { + use std::mem; + + type T = u64; + + #[derive(Default)] + pub struct BitVec { + bits: Vec, + } + + impl BitVec { + /// Inserts `idx` into this bit vector, returning whether it was not + /// previously present. + pub fn insert(&mut self, idx: u32) -> bool { + let (idx, bit) = idx_bit(idx); + match self.bits.get_mut(idx) { + Some(bits) => { + if *bits & bit != 0 { + return false; + } + *bits |= bit; + } + None => { + self.bits.resize(idx + 1, 0); + self.bits[idx] = bit; + } + } + true + } + + /// Returns whether this bit vector contains the specified `idx`th bit. + pub fn contains(&self, idx: u32) -> bool { + let (idx, bit) = idx_bit(idx); + match self.bits.get(idx) { + Some(bits) => (*bits & bit) != 0, + None => false, + } + } + } + + fn idx_bit(idx: u32) -> (usize, T) { + let idx = idx as usize; + let size = mem::size_of::() * 8; + let index = idx / size; + let bit = 1 << (idx % size); + (index, bit) + } +} + +/// Small data structure used to track index mappings from an old index space to +/// a new. +#[derive(Default)] +struct Remap { + /// Map, indexed by the old index set, to the new index set. + map: HashMap, + /// The next available index in the new index space. + next: u32, +} + +impl Remap { + /// Appends a new live "old index" into this remapping structure. + /// + /// This will assign a new index for the old index provided. + fn push(&mut self, old: u32) { + self.map.insert(old, self.next); + self.next += 1; + } + + /// Returns the new index corresponding to an old index. + /// + /// Panics if the `old` index was not added via `push` above. + fn remap(&self, old: u32) -> u32 { + *self + .map + .get(&old) + .unwrap_or_else(|| panic!("can't map {old} to a new index")) + } +} diff --git a/vendor/wit-component/src/lib.rs b/vendor/wit-component/src/lib.rs new file mode 100644 index 00000000..11f57201 --- /dev/null +++ b/vendor/wit-component/src/lib.rs @@ -0,0 +1,178 @@ +//! The WebAssembly component tooling. + +#![deny(missing_docs)] +#![cfg_attr(docsrs, feature(doc_cfg))] + +use std::str::FromStr; +use std::{borrow::Cow, fmt::Display}; + +use anyhow::{Result, bail}; +use wasm_encoder::{CanonicalOption, Encode, Section}; +use wit_parser::{Resolve, WorldId}; + +mod encoding; +mod gc; +mod linking; +mod printing; +mod targets; +mod validation; + +pub use encoding::{ComponentEncoder, LibraryInfo, encode}; +pub use linking::Linker; +pub use printing::*; +pub use targets::*; +pub use validation::AdapterModuleDidNotExport; +pub use wit_parser::decoding::{DecodedWasm, decode, decode_reader}; + +pub mod metadata; + +#[cfg(feature = "dummy-module")] +pub use dummy::dummy_module; +#[cfg(feature = "dummy-module")] +mod dummy; + +#[cfg(feature = "semver-check")] +mod semver_check; +#[cfg(feature = "semver-check")] +pub use semver_check::*; + +/// Supported string encoding formats. +#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum StringEncoding { + /// Strings are encoded with UTF-8. + #[default] + UTF8, + /// Strings are encoded with UTF-16. + UTF16, + /// Strings are encoded with compact UTF-16 (i.e. Latin1+UTF-16). + CompactUTF16, +} + +impl Display for StringEncoding { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + StringEncoding::UTF8 => write!(f, "utf8"), + StringEncoding::UTF16 => write!(f, "utf16"), + StringEncoding::CompactUTF16 => write!(f, "compact-utf16"), + } + } +} + +impl FromStr for StringEncoding { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s { + "utf8" => Ok(StringEncoding::UTF8), + "utf16" => Ok(StringEncoding::UTF16), + "compact-utf16" => Ok(StringEncoding::CompactUTF16), + _ => bail!("unknown string encoding `{s}`"), + } + } +} + +impl From for wasm_encoder::CanonicalOption { + fn from(e: StringEncoding) -> wasm_encoder::CanonicalOption { + match e { + StringEncoding::UTF8 => CanonicalOption::UTF8, + StringEncoding::UTF16 => CanonicalOption::UTF16, + StringEncoding::CompactUTF16 => CanonicalOption::CompactUTF16, + } + } +} + +/// A producer section to be added to all modules and components synthesized by +/// this crate +pub(crate) fn base_producers() -> wasm_metadata::Producers { + let mut producer = wasm_metadata::Producers::empty(); + producer.add("processed-by", "wit-component", env!("CARGO_PKG_VERSION")); + producer +} + +/// Embed component metadata in a buffer of bytes that contains a Wasm module +pub fn embed_component_metadata( + bytes: &mut Vec, + wit_resolver: &Resolve, + world: WorldId, + encoding: StringEncoding, +) -> Result<()> { + let encoded = metadata::encode(&wit_resolver, world, encoding, None)?; + + let section = wasm_encoder::CustomSection { + name: "component-type".into(), + data: Cow::Borrowed(&encoded), + }; + bytes.push(section.id()); + section.encode(bytes); + + Ok(()) +} + +#[cfg(test)] +mod tests { + use anyhow::Result; + use wasmparser::Payload; + use wit_parser::Resolve; + + use super::{StringEncoding, embed_component_metadata}; + + const MODULE_WAT: &str = r#" +(module + (type (;0;) (func)) + (func (;0;) (type 0) + nop + ) +) +"#; + + const COMPONENT_WIT: &str = r#" +package test:foo; +world test-world {} +"#; + + #[test] + fn component_metadata_embedding_works() -> Result<()> { + let mut bytes = wat::parse_str(MODULE_WAT)?; + + // Get original len & custom section count + let original_len = bytes.len(); + let payloads = wasmparser::Parser::new(0).parse_all(&bytes); + let original_custom_section_count = payloads.fold(0, |acc, payload| { + if let Ok(Payload::CustomSection { .. }) = payload { + acc + 1 + } else { + acc + } + }); + + // Parse pre-canned WIT to build resolver + let mut resolver = Resolve::default(); + let pkg = resolver.push_str("in-code.wit", COMPONENT_WIT)?; + let world = resolver.select_world(&[pkg], Some("test-world"))?; + + // Embed component metadata + embed_component_metadata(&mut bytes, &resolver, world, StringEncoding::UTF8)?; + + // Re-retrieve custom section count, and search for the component-type custom section along the way + let mut found_component_section = false; + let new_custom_section_count = + wasmparser::Parser::new(0) + .parse_all(&bytes) + .fold(0, |acc, payload| { + if let Ok(Payload::CustomSection(reader)) = payload { + if reader.name() == "component-type" { + found_component_section = true; + } + acc + 1 + } else { + acc + } + }); + + assert!(original_len < bytes.len()); + assert_eq!(original_custom_section_count + 1, new_custom_section_count); + assert!(found_component_section); + + Ok(()) + } +} diff --git a/vendor/wit-component/src/linking.rs b/vendor/wit-component/src/linking.rs new file mode 100644 index 00000000..301205a9 --- /dev/null +++ b/vendor/wit-component/src/linking.rs @@ -0,0 +1,1975 @@ +//! Support for "pseudo-dynamic", shared-everything linking of Wasm modules into a component. +//! +//! This implements [shared-everything +//! linking](https://github.com/WebAssembly/component-model/blob/main/design/mvp/examples/SharedEverythingDynamicLinking.md), +//! taking as input one or more [dynamic +//! library](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md) modules and producing a +//! component whose type is the union of any `component-type*` custom sections found in the input modules. +//! +//! The entry point into this process is `Linker::encode`, which analyzes and topologically sorts the input +//! modules, then synthesizes two additional modules: +//! +//! - `main` AKA `env`: hosts the component's single memory and function table and exports any functions needed to +//! break dependency cycles discovered in the input modules. Those functions use `call.indirect` to invoke the real +//! functions, references to which are placed in the table by the `init` module. +//! +//! - `init`: populates the function table as described above, initializes global variables per the dynamic linking +//! tool convention, and calls any static constructors and/or link-time fixup functions +//! +//! `Linker` also supports synthesizing `dlopen`/`dlsym` lookup tables which allow symbols to be resolved at +//! runtime. Note that this is not true dynamic linking, since all the code is baked into the component ahead of +//! time -- we simply allow runtime resolution of already-resident definitions. This is sufficient to support +//! dynamic language FFI features such as Python native extensions, provided the required libraries are linked +//! ahead-of-time. + +use { + crate::encoding::fixup::{AddressDest, FixupModule, ImportedInstance, StartAction}, + crate::encoding::{ComponentEncoder, Instance, Item, LibraryInfo, MainOrAdapter}, + anyhow::{Context, Result, anyhow, bail}, + indexmap::{IndexMap, IndexSet, map::Entry}, + metadata::{Export, ExportKey, FunctionType, GlobalType, Metadata, Type, ValueType}, + std::{ + borrow::Cow, + collections::{BTreeMap, HashMap, HashSet}, + fmt::Debug, + hash::Hash, + }, + wasm_encoder::{ + CodeSection, ConstExpr, Elements, EntityType, ExportKind, ExportSection, Function, + FunctionSection, GlobalSection, ImportSection, MemArg, MemorySection, MemoryType, Module, + RawCustomSection, RefType, TableSection, TableType, TypeSection, ValType, + }, + wasmparser::SymbolFlags, +}; + +pub(crate) mod metadata; + +const PAGE_SIZE_BYTES: u32 = 65536; +// This matches the default stack size LLVM produces: +pub const DEFAULT_STACK_SIZE_BYTES: u32 = 16 * PAGE_SIZE_BYTES; +const HEAP_ALIGNMENT_BYTES: u32 = 16; +const STUB_LIBRARY_NAME: &str = "wit-component:stubs"; +const CABI_REALLOC: &str = "cabi_realloc"; + +/// Symbols to re-export from the `env` module regardless of whether any +/// libraries import them, since +/// `EncodingState::create_export_task_initialization_wrappers` needs to be able +/// to call them. +static ENV_REEXPORTS: &[(&str, &[ValueType], &[ValueType])] = + &[(metadata::TASK_HOOK, &[ValueType::I32], &[])]; + +enum Address<'a> { + Function(u32), + Global(&'a str), +} + +/// Represents a `dlopen`/`dlsym` lookup table enabling runtime symbol resolution +/// +/// The top level of this table is a sorted list of library names and offsets, each pointing to a sorted list of +/// symbol names and offsets. See ../dl/src/lib.rs for how this is used at runtime. +struct DlOpenables<'a> { + /// Offset into the main module's table where function references will be stored + table_base: u32, + + /// Offset into the main module's memory where the lookup table will be stored + memory_base: u32, + + /// The lookup table itself + buffer: Vec, + + /// Linear memory addresses where global variable addresses will live + /// + /// The init module will fill in the correct values at instantiation time. + global_addresses: Vec<(&'a str, &'a str, u32)>, + + /// Number of function references to be stored in the main module's table + function_count: u32, + + /// Linear memory address where the root of the lookup table will reside + /// + /// This can be different from `memory_base` depending on how the tree of libraries and symbols is laid out in + /// memory. + libraries_address: u32, +} + +impl<'a> DlOpenables<'a> { + /// Construct a lookup table containing all "dlopen-able" libraries and their symbols using the specified table + /// and memory offsets. + fn new(table_base: u32, memory_base: u32, metadata: &'a [Metadata<'a>]) -> Self { + let mut function_count = 0; + let mut buffer = Vec::new(); + let mut global_addresses = Vec::new(); + let mut libraries = metadata + .iter() + .filter(|metadata| metadata.dl_openable) + .map(|metadata| { + let name_address = memory_base + u32::try_from(buffer.len()).unwrap(); + write_bytes_padded(&mut buffer, metadata.name.as_bytes()); + + let mut symbols = metadata + .exports + .iter() + .filter_map(|export| { + let name_address = memory_base + u32::try_from(buffer.len()).unwrap(); + write_bytes_padded(&mut buffer, export.key.name.as_bytes()); + + let address = match &export.key.ty { + Type::Function(_) => Address::Function( + table_base + get_and_increment(&mut function_count), + ), + Type::Global(_) => Address::Global(export.key.name), + Type::Tag(_) => return None, + }; + + Some((export.key.name, name_address, address)) + }) + .collect::>(); + + symbols.sort_by_key(|(name, ..)| *name); + let symbols_len = symbols.len(); + + let start = buffer.len(); + for (name, name_address, address) in symbols { + write_u32(&mut buffer, u32::try_from(name.len()).unwrap()); + write_u32(&mut buffer, name_address); + match address { + Address::Function(address) => write_u32(&mut buffer, address), + Address::Global(name) => { + global_addresses.push(( + metadata.name, + name, + memory_base + u32::try_from(buffer.len()).unwrap(), + )); + + write_u32(&mut buffer, 0); + } + } + } + + ( + metadata.name, + name_address, + symbols_len, + memory_base + u32::try_from(start).unwrap(), + ) + }) + .collect::>(); + + libraries.sort_by_key(|(name, ..)| *name); + + let start = buffer.len(); + for (name, name_address, count, symbols) in &libraries { + write_u32(&mut buffer, u32::try_from(name.len()).unwrap()); + write_u32(&mut buffer, *name_address); + write_u32(&mut buffer, u32::try_from(*count).unwrap()); + write_u32(&mut buffer, *symbols); + } + + let libraries_address = memory_base + u32::try_from(buffer.len()).unwrap(); + write_u32(&mut buffer, u32::try_from(libraries.len()).unwrap()); + write_u32(&mut buffer, memory_base + u32::try_from(start).unwrap()); + + Self { + table_base, + memory_base, + buffer, + global_addresses, + function_count, + libraries_address, + } + } +} + +/// The layout of the whole program's thread-local storage bookkeeping. +/// +/// This generates a C structure that matches this layout: +/// +/// ```c +/// struct { +/// size_t num_libraries; +/// void **library_info; +/// void **main_thread_tls_base; +/// } __wasm_program_tls_info; +/// ``` +/// +/// where the `main_thread_tls_base` array is placed first, then the +/// `library_info` array, then this structure itself. +#[derive(Default)] +struct TlsLayout { + /// Address of the `main_thread_tls_base` array. + /// + /// This is left zero-initialized; no data segment covers it. + main_thread_tls_base: u32, + + /// Address of the `library_info` array. + library_info: u32, + + /// Address of the `__wasm_program_tls_info` struct itself. + program_info: u32, + + /// For each library, the slot it uses in the array of TLS base pointers, or + /// `None` if it has no thread-local storage of its own. + slots: Vec>, + + /// Static contents of the `__wasm_program_tls_info`. + buffer: Vec, +} + +impl TlsLayout { + /// Reserve linear memory and table space for the layout described above, + /// advancing `memory_offset` and `table_offset` past what's used. + /// + /// Nothing is reserved for a program which doesn't use thread-local storage + /// at all, and the `__wasm_program_tls_info` half is skipped unless some + /// library actually asks for it, which is only the case when the program + /// might spawn a thread. + fn new(metadata: &[Metadata], memory_offset: &mut u32) -> Self { + let needs_tls_base = metadata + .iter() + .any(|m| m.needs_get_tls_base || m.needs_set_tls_base); + let needs_program_info = metadata.iter().any(|m| m.needs_program_tls_info); + if !needs_tls_base && !needs_program_info { + return Self::default(); + } + + // Filter out libraries that don't have TLS. + let libraries = metadata + .iter() + .enumerate() + .filter(|(_, metadata)| metadata.has_library_tls_info) + .map(|(index, _)| index) + .collect::>(); + + let mut slots = vec![None; metadata.len()]; + for (slot, index) in libraries.iter().enumerate() { + slots[*index] = Some(u32::try_from(slot).unwrap()); + } + let count = u32::try_from(libraries.len()).unwrap(); + + // Allocate space for `main_thread_tls_base` + *memory_offset = align(*memory_offset, 4); + let main_thread_tls_base = *memory_offset; + *memory_offset += count * 4; + + let mut library_info = 0; + let mut program_info = 0; + let mut buffer = Vec::new(); + if needs_program_info { + library_info = *memory_offset; + *memory_offset += count * 4; + program_info = *memory_offset; + *memory_offset += 12; + + write_u32(&mut buffer, count); + write_u32(&mut buffer, library_info); + write_u32(&mut buffer, main_thread_tls_base); + } + + Self { + main_thread_tls_base, + library_info, + program_info, + slots, + buffer, + } + } + + /// The slot library `index` uses in the array of TLS base pointers. + fn slot(&self, index: usize) -> Option { + self.slots.get(index).copied().flatten() + } +} + +fn write_u32(buffer: &mut Vec, value: u32) { + buffer.extend(value.to_le_bytes()); +} + +fn write_bytes_padded(buffer: &mut Vec, bytes: &[u8]) { + buffer.extend(bytes); + + let len = u32::try_from(bytes.len()).unwrap(); + for _ in len..align(len, 4) { + buffer.push(0); + } +} + +fn align(a: u32, b: u32) -> u32 { + assert!(b.is_power_of_two()); + (a + (b - 1)) & !(b - 1) +} + +fn get_and_increment(n: &mut u32) -> u32 { + let v = *n; + *n += 1; + v +} + +fn const_u32(a: u32) -> ConstExpr { + ConstExpr::i32_const(a as i32) +} + +/// Helper trait for determining the size of a set or map +trait Length { + fn len(&self) -> usize; +} + +impl Length for HashSet { + fn len(&self) -> usize { + HashSet::len(self) + } +} + +impl Length for HashMap { + fn len(&self) -> usize { + HashMap::len(self) + } +} + +impl Length for IndexSet { + fn len(&self) -> usize { + IndexSet::len(self) + } +} + +impl Length for IndexMap { + fn len(&self) -> usize { + IndexMap::len(self) + } +} + +/// Extension trait for collecting into a set or map and asserting that there were no duplicate entries in the +/// source iterator. +trait CollectUnique: Iterator + Sized { + fn collect_unique + Length>(self) -> T { + let tmp = self.collect::>(); + let len = tmp.len(); + let result = tmp.into_iter().collect::(); + assert!( + result.len() == len, + "one or more duplicate items detected when collecting into set or map" + ); + result + } +} + +impl CollectUnique for T {} + +/// Extension trait for inserting into a map and asserting that an entry did not already exist for the key +trait InsertUnique { + type Key; + type Value; + + fn insert_unique(&mut self, k: Self::Key, v: Self::Value); +} + +impl InsertUnique for HashMap { + type Key = K; + type Value = V; + + fn insert_unique(&mut self, k: Self::Key, v: Self::Value) { + if let Some(old_v) = self.get(&k) { + panic!( + "duplicate item inserted into map for key {k:?} (old value: {old_v:?}; new value: {v:?})" + ); + } + self.insert(k, v); + } +} + +/// Synthesize the "main" module for the component, responsible for exporting functions which break cyclic +/// dependencies, as well as hosting the memory and function table. +fn make_env_module<'a>( + metadata: &'a [Metadata<'a>], + env_exports: &[EnvExport<'_>], + cabi_realloc_exporter: Option<&str>, + stack_size_bytes: u32, +) -> (Vec, DlOpenables<'a>, TlsLayout, u32) { + // TODO: deduplicate types + let mut types = TypeSection::new(); + let mut imports = ImportSection::new(); + let mut import_map = IndexMap::new(); + let mut function_count = 0; + let mut global_offset = 0; + let mut wasi_start = None; + + for metadata in metadata { + for import in &metadata.imports { + if let Entry::Vacant(entry) = import_map.entry(import) { + imports.import( + import.module, + import.name, + match &import.ty { + Type::Function(ty) => { + let index = get_and_increment(&mut function_count); + entry.insert(index); + types.ty().function( + ty.parameters.iter().copied().map(ValType::from), + ty.results.iter().copied().map(ValType::from), + ); + EntityType::Function(index) + } + Type::Global(ty) => { + entry.insert(get_and_increment(&mut global_offset)); + EntityType::Global(wasm_encoder::GlobalType { + val_type: ty.ty.into(), + mutable: ty.mutable, + shared: ty.shared, + }) + } + Type::Tag(_) => continue, + }, + ); + } + } + + if metadata.has_wasi_start { + if wasi_start.is_some() { + panic!("multiple libraries export {}", metadata::START); + } + let index = get_and_increment(&mut function_count); + + types.ty().function(vec![], vec![]); + imports.import(metadata.name, metadata::START, EntityType::Function(index)); + + wasi_start = Some(index); + } + } + + let mut memory_offset = stack_size_bytes; + + // Table offset 0 is reserved for the null function pointer. + // This convention follows wasm-ld's table layout: + // https://github.com/llvm/llvm-project/blob/913622d012f72edb5ac3a501cef8639d0ebe471b/lld/wasm/Driver.cpp#L581-L584 + let mut table_offset = 1; + let mut globals = GlobalSection::new(); + let mut exports = ExportSection::new(); + + if let Some(exporter) = cabi_realloc_exporter { + let index = get_and_increment(&mut function_count); + types.ty().function([ValType::I32; 4], [ValType::I32]); + imports.import(exporter, CABI_REALLOC, EntityType::Function(index)); + exports.export(CABI_REALLOC, ExportKind::Func, index); + } + + // If tls base shims are being generated, and something might spawn a + // thread, then the shims generated will need access to `context.get 1`. + let indirect_tls_base = metadata + .iter() + .any(|m| m.needs_get_tls_base || m.needs_set_tls_base) + && metadata.iter().any(|m| m.uses_thread_new_indirect); + let tls_context_get = if indirect_tls_base { + let index = get_and_increment(&mut function_count); + types.ty().function([], [ValType::I32]); + imports.import( + metadata::ROOT, + metadata::CONTEXT_GET_1, + EntityType::Function(index), + ); + Some(index) + } else { + None + }; + + let mut add_global_export = |name: &str, value, mutable| { + let index = globals.len(); + globals.global( + wasm_encoder::GlobalType { + val_type: ValType::I32, + mutable, + shared: false, + }, + &const_u32(value), + ); + exports.export(name, ExportKind::Global, index); + }; + + let dl_openables = DlOpenables::new(table_offset, memory_offset, metadata); + + if metadata.iter().any(|m| m.needs_libdl_libraries) { + add_global_export( + metadata::LIBDL_LIBRARIES, + dl_openables.libraries_address, + true, + ); + } + + table_offset += dl_openables.function_count; + memory_offset += u32::try_from(dl_openables.buffer.len()).unwrap(); + + let tls = TlsLayout::new(metadata, &mut memory_offset); + + if metadata.iter().any(|m| m.needs_program_tls_info) { + add_global_export(metadata::PROGRAM_TLS_INFO, tls.program_info, true); + } + + let memory_size = { + if metadata.iter().any(|m| m.needs_stack_pointer) { + add_global_export(metadata::STACK_POINTER, stack_size_bytes, true); + } + if metadata.iter().any(|m| m.needs_init_stack_pointer) { + add_global_export(metadata::INIT_STACK_POINTER, stack_size_bytes, false); + } + + // Binaryen's Asyncify transform for shared everything linking requires these globals + // to be provided from env module + let has_asyncified_module = metadata.iter().any(|m| m.is_asyncified); + if has_asyncified_module { + add_global_export(metadata::ASYNCIFY_STATE, 0, true); + add_global_export(metadata::ASYNCIFY_DATA, 0, true); + } + + // The libc.so in WASI-SDK 28+ requires these: + if metadata.iter().any(|m| m.needs_stack_high) { + add_global_export(metadata::STACK_HIGH, stack_size_bytes, true); + } + if metadata.iter().any(|m| m.needs_stack_low) { + add_global_export(metadata::STACK_LOW, 0, true); + } + + for metadata in metadata { + memory_offset = align(memory_offset, 1 << metadata.mem_info.memory_alignment); + table_offset = align(table_offset, 1 << metadata.mem_info.table_alignment); + + add_global_export( + &format!("{}:memory_base", metadata.name), + memory_offset, + false, + ); + add_global_export( + &format!("{}:table_base", metadata.name), + table_offset, + false, + ); + + memory_offset += metadata.mem_info.memory_size; + table_offset += metadata.mem_info.table_size; + + for import in &metadata.memory_address_imports { + // Note that we initialize this to zero and let the init module compute the real value at + // instantiation time. + add_global_export(&format!("{}:{import}", metadata.name), 0, true); + } + } + + { + let offsets = env_exports + .iter() + .enumerate() + .map(|(offset, EnvExport { name, exporter, .. })| { + ( + *name, + ( + table_offset + u32::try_from(offset).unwrap(), + metadata[*exporter].name == STUB_LIBRARY_NAME, + ), + ) + }) + .collect_unique::>(); + + for metadata in metadata { + for import in &metadata.table_address_imports { + let &(offset, is_stub) = offsets.get(import).unwrap(); + if is_stub + && metadata + .env_imports + .iter() + .any(|e| e.0 == *import && e.1.1.contains(SymbolFlags::BINDING_WEAK)) + { + add_global_export(&format!("{}:{import}", metadata.name), 0, true); + } else { + add_global_export(&format!("{}:{import}", metadata.name), offset, true); + } + } + } + } + + memory_offset = align(memory_offset, HEAP_ALIGNMENT_BYTES); + if metadata.iter().any(|m| m.needs_heap_base) { + add_global_export(metadata::HEAP_BASE, memory_offset, true); + } + + let heap_end = align(memory_offset, PAGE_SIZE_BYTES); + if metadata.iter().any(|m| m.needs_heap_end) { + add_global_export(metadata::HEAP_END, heap_end, true); + } + heap_end / PAGE_SIZE_BYTES + }; + + let indirection_table_base = table_offset; + + let mut functions = FunctionSection::new(); + let mut code = CodeSection::new(); + for export in env_exports { + let index = get_and_increment(&mut function_count); + types.ty().function( + export.ty.parameters.iter().copied().map(ValType::from), + export.ty.results.iter().copied().map(ValType::from), + ); + functions.function(u32::try_from(index).unwrap()); + let mut function = Function::new([]); + for local in 0..export.ty.parameters.len() { + function + .instructions() + .local_get(u32::try_from(local).unwrap()); + } + function + .instructions() + .i32_const(i32::try_from(table_offset).unwrap()) + .call_indirect(0, u32::try_from(index).unwrap()) + .end(); + code.function(&function); + exports.export(export.name, ExportKind::Func, index); + + table_offset += 1; + } + + // Define a distinct `__wasm_{get,set}_tls_base` pair for each library that + // needs one. Each pair reads and writes that library's slot of the array of + // pointers described by `TlsLayout`. + for (index, metadata) in metadata.iter().enumerate() { + // A library with no thread-local storage of its own has no slot in the + // array. If it still imports these then synthesize functions that trap + // since they shouldn't ever be called. + let Some(slot) = tls.slot(index) else { + for (needed, name, params, results) in [ + ( + metadata.needs_get_tls_base, + metadata::GET_TLS_BASE, + &[][..], + &[ValType::I32][..], + ), + ( + metadata.needs_set_tls_base, + metadata::SET_TLS_BASE, + &[ValType::I32][..], + &[][..], + ), + ] { + if !needed { + continue; + } + let func = get_and_increment(&mut function_count); + types + .ty() + .function(params.iter().copied(), results.iter().copied()); + functions.function(func); + let mut function = Function::new([]); + function.instructions().unreachable().end(); + code.function(&function); + exports.export(&format!("{}:{name}", metadata.name), ExportKind::Func, func); + } + continue; + }; + + let mem_arg = MemArg { + offset: u64::from(slot * 4), + align: 2, + memory_index: 0, + }; + + if metadata.needs_get_tls_base { + let func = get_and_increment(&mut function_count); + types.ty().function([], [ValType::I32]); + functions.function(func); + let mut function = Function::new([]); + // With coop threads the base pointer is in `context.get 1`. Without + // coop threads the base pointer is `main_thread_tls_base` itself. + match tls_context_get { + Some(get) => { + function.instructions().call(get); + } + None => { + function + .instructions() + .i32_const(i32::try_from(tls.main_thread_tls_base).unwrap()); + } + } + function.instructions().i32_load(mem_arg).end(); + code.function(&function); + exports.export( + &format!("{}:{}", metadata.name, metadata::GET_TLS_BASE), + ExportKind::Func, + func, + ); + } + + if metadata.needs_set_tls_base { + let func = get_and_increment(&mut function_count); + types.ty().function([ValType::I32], []); + functions.function(func); + let mut function = Function::new_with_locals_types(if tls_context_get.is_some() { + vec![ValType::I32] + } else { + vec![] + }); + // With coop threads this intrinsic conditionally initializes + // `main_thread_tls_base` based on `context.get 1`. Otherwise it + // writes through to it if it's set. + // + // Without coop threads this is updating `main_thread_tls_base`. + match tls_context_get { + Some(get) => { + function + .instructions() + .call(get) + .local_tee(1) + .i32_eqz() + .if_(wasm_encoder::BlockType::Empty) + .i32_const(i32::try_from(tls.main_thread_tls_base).unwrap()) + .local_get(0) + .i32_store(mem_arg) + .else_() + .local_get(1) + .local_get(0) + .i32_store(mem_arg) + .end() + .end(); + } + None => { + function + .instructions() + .i32_const(i32::try_from(tls.main_thread_tls_base).unwrap()) + .local_get(0) + .i32_store(mem_arg) + .end(); + } + } + code.function(&function); + exports.export( + &format!("{}:{}", metadata.name, metadata::SET_TLS_BASE), + ExportKind::Func, + func, + ); + } + } + + for (import, offset) in import_map { + exports.export( + &format!("{}:{}", import.module, import.name), + ExportKind::from(&import.ty), + offset, + ); + } + if let Some(index) = wasi_start { + exports.export(metadata::START, ExportKind::Func, index); + } + + let mut module = Module::new(); + + module.section(&types); + module.section(&imports); + module.section(&functions); + + { + let mut tables = TableSection::new(); + tables.table(TableType { + element_type: RefType::FUNCREF, + minimum: table_offset.into(), + maximum: None, + table64: false, + shared: false, + }); + exports.export(metadata::INDIRECT_FUNCTION_TABLE, ExportKind::Table, 0); + module.section(&tables); + } + + { + let mut memories = MemorySection::new(); + memories.memory(MemoryType { + minimum: u64::from(memory_size), + maximum: None, + memory64: false, + shared: false, + page_size_log2: None, + }); + exports.export(metadata::MEMORY, ExportKind::Memory, 0); + module.section(&memories); + } + + module.section(&globals); + module.section(&exports); + module.section(&code); + module.section(&RawCustomSection( + &crate::base_producers().raw_custom_section(), + )); + + let module = module.finish(); + wasmparser::validate(&module).unwrap(); + + (module, dl_openables, tls, indirection_table_base) +} + +/// Synthesize the "init" module, responsible for initializing global variables per the dynamic linking tool +/// convention and calling any static constructors and/or link-time fixup functions. +/// +/// This module also contains the data segment for the `dlopen`/`dlsym` lookup table. +fn make_init_module( + fixups: &mut FixupModule, + metadata: &[Metadata], + exporters: &IndexMap<&ExportKey, (&str, &Export)>, + env_exports: &[EnvExport<'_>], + dl_openables: &DlOpenables, + tls: &TlsLayout, + indirection_table_base: u32, +) -> Result<()> { + let thunk_ty = fixups.type_thunk(); + let memory = fixups.import( + &ImportedInstance::Main, + metadata::MEMORY, + MemoryType { + minimum: 0, + maximum: None, + memory64: false, + shared: false, + page_size_log2: None, + } + .into(), + )?; + let table = fixups.import( + &ImportedInstance::Main, + metadata::INDIRECT_FUNCTION_TABLE, + TableType { + element_type: RefType::FUNCREF, + minimum: 0, + maximum: None, + table64: false, + shared: false, + } + .into(), + )?; + + let module_name_to_instance = |module: &str| match module { + metadata::ENV => ImportedInstance::Main, + other => ImportedInstance::Adapter(other.to_string()), + }; + + let mut global_map = HashMap::new(); + let mut add_global_import = |fixups: &mut FixupModule, module: &str, name: &str, mutable| { + *global_map + .entry((module.to_owned(), name.to_owned())) + .or_insert_with(|| { + fixups + .import_global( + &module_name_to_instance(module), + name, + wasm_encoder::GlobalType { + val_type: ValType::I32, + mutable, + shared: false, + }, + ) + .unwrap() + }) + }; + + let mut function_map = HashMap::new(); + let mut add_function_import = |fixups: &mut FixupModule, module: &str, name: &str, ty| { + *function_map + .entry((module.to_owned(), name.to_owned())) + .or_insert_with(|| { + fixups + .import_func(&module_name_to_instance(module), name, ty) + .unwrap() + }) + }; + + let mut names = HashMap::new(); + for (index, metadata) in metadata.iter().enumerate() { + names.insert_unique(index, metadata.name); + } + + for (exporter, export, address) in dl_openables.global_addresses.iter() { + let memory_base = add_global_import( + fixups, + metadata::ENV, + &format!("{exporter}:memory_base"), + false, + ); + let export = add_global_import(fixups, exporter, export, false); + + fixups.add_start_abi_detail(StartAction::InitializeAddress { + memory_base, + export, + dest: AddressDest::LinearMemory { + address: *address, + memory, + }, + }); + } + + for metadata in metadata { + for import in &metadata.memory_address_imports { + let (exporter, _) = find_offset_exporter(import, exporters)?; + + let memory_base = add_global_import( + fixups, + metadata::ENV, + &format!("{exporter}:memory_base"), + false, + ); + let offset = add_global_import(fixups, exporter, import, false); + let address = add_global_import( + fixups, + metadata::ENV, + &format!("{}:{import}", metadata.name), + true, + ); + fixups.add_start_abi_detail(StartAction::InitializeAddress { + memory_base, + export: offset, + dest: AddressDest::Global(address), + }); + } + } + + for metadata in metadata { + if metadata.has_data_relocs { + let func = + add_function_import(fixups, metadata.name, metadata::APPLY_DATA_RELOCS, thunk_ty); + fixups.add_start_abi_detail(StartAction::Call(func)); + } + } + + for metadata in metadata { + if metadata.has_ctors && metadata.has_initialize { + bail!( + "library {} exports both `{}` and `{}`; \ + expected at most one of the two", + metadata.name, + metadata::CALL_CTORS, + metadata::INITIALIZE + ); + } + + if metadata.has_ctors { + let func = add_function_import(fixups, metadata.name, metadata::CALL_CTORS, thunk_ty); + fixups.add_start_user_func(StartAction::Call(func)); + } + + if metadata.has_initialize { + let func = add_function_import(fixups, metadata.name, metadata::INITIALIZE, thunk_ty); + fixups.add_start_user_func(StartAction::Call(func)); + } + } + + let intern_type = |fixups: &mut FixupModule, ty: &FunctionType| { + fixups.type_intern( + ty.parameters.iter().copied().map(|t| t.into()).collect(), + ty.results.iter().copied().map(|t| t.into()).collect(), + ) + }; + + let mut dl_openable_functions = Vec::new(); + for metadata in metadata { + if metadata.dl_openable { + for export in &metadata.exports { + if let Type::Function(fty) = &export.key.ty { + let ty = intern_type(fixups, fty); + dl_openable_functions.push(add_function_import( + fixups, + metadata.name, + export.key.name, + ty, + )); + } + } + } + } + + let indirections = env_exports + .iter() + .map(|EnvExport { name, exporter, ty }| { + let ty = intern_type(fixups, ty); + add_function_import(fixups, names[exporter], name, ty) + }) + .collect::>(); + + // For all libraries that export TLS information the initialization function + // here will setup the in-memory `__wasm_program_tls_info` structure by + // storing the pointers to each `__wasm_library_tls_info` structure in a + // sequence. + if tls.library_info != 0 { + for (lib_index, tls_index) in tls + .slots + .iter() + .enumerate() + .filter_map(|(i, slot)| slot.map(|j| (i, j))) + { + let metadata = &metadata[lib_index]; + let memory_base = add_global_import( + fixups, + metadata::ENV, + &format!("{}:memory_base", metadata.name), + false, + ); + let i = add_global_import(fixups, metadata.name, metadata::LIBRARY_TLS_INFO, false); + + fixups.add_start_abi_detail(StartAction::InitializeAddress { + memory_base, + export: i, + dest: AddressDest::LinearMemory { + address: tls.library_info + tls_index * 4, + memory, + }, + }); + } + } + + fixups.elements().active( + if table == 0 { None } else { Some(table) }, + &const_u32(dl_openables.table_base), + Elements::Functions(dl_openable_functions.into()), + ); + fixups.elements().active( + if table == 0 { None } else { Some(table) }, + &const_u32(indirection_table_base), + Elements::Functions(indirections.into()), + ); + + let data = fixups.data(); + data.active( + memory, + &const_u32(dl_openables.memory_base), + dl_openables.buffer.clone(), + ); + if !tls.buffer.is_empty() { + data.active(memory, &const_u32(tls.program_info), tls.buffer.clone()); + } + + Ok(()) +} + +/// Find the library which exports the specified function or global address. +fn find_offset_exporter<'a>( + name: &str, + exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>, +) -> Result<(&'a str, &'a Export<'a>)> { + let export = ExportKey { + name, + ty: Type::Global(GlobalType { + ty: ValueType::I32, + mutable: false, + shared: false, + }), + }; + + exporters + .get(&export) + .copied() + .ok_or_else(|| anyhow!("unable to find {export:?} in any library")) +} + +/// Find the library which exports the specified function. +fn find_function_exporter<'a>( + name: &str, + ty: &FunctionType, + exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>, +) -> Result<(&'a str, &'a Export<'a>)> { + let export = ExportKey { + name, + ty: Type::Function(ty.clone()), + }; + + exporters + .get(&export) + .copied() + .ok_or_else(|| anyhow!("unable to find {export:?} in any library")) +} + +/// Find the library which exports the specified tag. +fn find_tag_exporter<'a>( + name: &str, + ty: &FunctionType, + exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>, +) -> Result<(&'a str, &'a Export<'a>)> { + let export = ExportKey { + name, + ty: Type::Tag(ty.clone()), + }; + + exporters + .get(&export) + .copied() + .ok_or_else(|| anyhow!("unable to find {export:?} in any library")) +} + +/// Analyze the specified library metadata, producing a symbol-to-library-name map of exports. +fn resolve_exporters<'a>( + metadata: &'a [Metadata<'a>], +) -> Result, Vec<(&'a str, &'a Export<'a>)>>> { + let mut exporters = IndexMap::<_, Vec<_>>::new(); + for metadata in metadata { + for export in &metadata.exports { + exporters + .entry(&export.key) + .or_default() + .push((metadata.name, export)); + } + } + Ok(exporters) +} + +/// Match up all imported symbols to their corresponding exports, reporting any missing or duplicate symbols. +fn resolve_symbols<'a>( + metadata: &'a [Metadata<'a>], + exporters: &'a IndexMap<&'a ExportKey<'a>, Vec<(&'a str, &'a Export<'a>)>>, +) -> ( + IndexMap<&'a ExportKey<'a>, (&'a str, &'a Export<'a>)>, + Vec<(&'a str, Export<'a>)>, + Vec<(&'a str, &'a ExportKey<'a>, &'a [(&'a str, &'a Export<'a>)])>, +) { + let function_exporters = exporters + .iter() + .filter_map(|(export, exporters)| match &export.ty { + Type::Function(_) => Some((export.name, (export, exporters))), + Type::Global(_) | Type::Tag(_) => None, + }) + .collect_unique::>(); + + let mut resolved = IndexMap::new(); + let mut missing = Vec::new(); + let mut duplicates = Vec::new(); + + let mut triage = |metadata: &'a Metadata, export: Export<'a>| { + if let Some((key, value)) = exporters.get_key_value(&export.key) { + // Note that we do not use `insert_unique` here since multiple libraries may import the same + // symbol, in which case we may redundantly insert the same value. + match value.as_slice() { + [] => unreachable!(), + [exporter] => { + resolved.insert(*key, *exporter); + } + [exporter, ..] => { + resolved.insert(*key, *exporter); + duplicates.push((metadata.name, *key, value.as_slice())); + } + } + } else { + missing.push((metadata.name, export)); + } + }; + + for metadata in metadata { + for (name, (ty, flags)) in &metadata.env_imports { + triage( + metadata, + Export { + key: ExportKey { + name, + ty: Type::Function(ty.clone()), + }, + flags: *flags, + }, + ); + } + + for name in &metadata.memory_address_imports { + triage( + metadata, + Export { + key: ExportKey { + name, + ty: Type::Global(GlobalType { + ty: ValueType::I32, + mutable: false, + shared: false, + }), + }, + flags: SymbolFlags::empty(), + }, + ); + } + + for (name, ty) in &metadata.tag_imports { + triage( + metadata, + Export { + key: ExportKey { + name, + ty: Type::Tag(ty.clone()), + }, + flags: SymbolFlags::empty(), + }, + ); + } + } + + for metadata in metadata { + for name in &metadata.table_address_imports { + if let Some((key, value)) = function_exporters.get(name) { + // Note that we do not use `insert_unique` here since multiple libraries may import the same + // symbol, in which case we may redundantly insert the same value. + match value.as_slice() { + [] => unreachable!(), + [exporter] => { + resolved.insert(key, *exporter); + } + [exporter, ..] => { + resolved.insert(key, *exporter); + duplicates.push((metadata.name, *key, value.as_slice())); + } + } + } else if metadata.env_imports.iter().any(|(n, _)| n == name) { + // GOT entry for a function which is imported from the env module, but not exported by any library, + // already handled above. + } else { + missing.push(( + metadata.name, + Export { + key: ExportKey { + name, + ty: Type::Function(FunctionType { + parameters: Vec::new(), + results: Vec::new(), + }), + }, + flags: SymbolFlags::empty(), + }, + )); + } + } + } + + // Even if no library imports these symbols, we re-export them from the + // `env` module so that + // `EncodingState::create_export_task_initialization_wrappers` can find + // and use them: + for (name, params, results) in ENV_REEXPORTS { + let export = Export { + key: ExportKey { + name, + ty: Type::Function(FunctionType { + parameters: params.to_vec(), + results: results.to_vec(), + }), + }, + flags: SymbolFlags::empty(), + }; + + if let Some((key, value)) = exporters.get_key_value(&export.key) { + // Note that we do not use `insert_unique` here since multiple + // libraries may import the same symbol, in which case we may + // redundantly insert the same value. + match value.as_slice() { + [] => unreachable!(), + [exporter] | [exporter, ..] => { + resolved.insert(*key, *exporter); + } + } + } + } + + (resolved, missing, duplicates) +} + +/// Recursively add a library (represented by its offset) and its dependency to the specified set, maintaining +/// topological order (modulo cycles). +fn topo_add( + sorted: &mut IndexSet, + dependencies: &IndexMap>, + element: usize, +) { + let empty = &IndexSet::new(); + let deps = dependencies.get(&element).unwrap_or(empty); + + // First, add any dependencies which do not depend on `element` + for &dep in deps { + if !(sorted.contains(&dep) || dependencies.get(&dep).unwrap_or(empty).contains(&element)) { + topo_add(sorted, dependencies, dep); + } + } + + // Next, add the element + sorted.insert(element); + + // Finally, add any dependencies which depend on `element` + for &dep in deps { + if !sorted.contains(&dep) && dependencies.get(&dep).unwrap_or(empty).contains(&element) { + topo_add(sorted, dependencies, dep); + } + } +} + +/// Topologically sort a set of libraries (represented by their offsets) according to their dependencies, modulo +/// cycles. +fn topo_sort(count: usize, dependencies: &IndexMap>) -> Result> { + let mut sorted = IndexSet::new(); + for index in 0..count { + topo_add(&mut sorted, &dependencies, index); + } + + Ok(sorted.into_iter().collect()) +} + +/// Analyze the specified library metadata, producing a map of transitive dependencies, where each library is +/// represented by its offset in the original metadata slice. +fn find_dependencies( + metadata: &[Metadata], + exporters: &IndexMap<&ExportKey, (&str, &Export)>, +) -> Result>> { + // First, generate a map of direct dependencies (i.e. depender to dependees) + let mut dependencies = IndexMap::<_, IndexSet<_>>::new(); + let mut indexes = HashMap::new(); + for (index, metadata) in metadata.iter().enumerate() { + indexes.insert_unique(metadata.name, index); + for &needed in &metadata.needed_libs { + dependencies + .entry(metadata.name) + .or_default() + .insert(needed); + } + for (import_name, (ty, _)) in &metadata.env_imports { + dependencies + .entry(metadata.name) + .or_default() + .insert(find_function_exporter(import_name, ty, exporters)?.0); + } + } + + // Next, convert the map from names to offsets + let mut dependencies = dependencies + .into_iter() + .map(|(k, v)| { + ( + indexes[k], + v.into_iter() + .map(|v| indexes[v]) + .collect_unique::>(), + ) + }) + .collect_unique::>(); + + // Finally, add all transitive dependencies to the map in a fixpoint loop, exiting when no new dependencies are + // discovered. + let empty = &IndexSet::new(); + + loop { + let mut new = IndexMap::<_, IndexSet<_>>::new(); + for (index, exporters) in &dependencies { + for exporter in exporters { + for exporter in dependencies.get(exporter).unwrap_or(empty) { + if !exporters.contains(exporter) { + new.entry(*index).or_default().insert(*exporter); + } + } + } + } + + if new.is_empty() { + break Ok(dependencies); + } else { + for (index, exporters) in new { + dependencies.entry(index).or_default().extend(exporters); + } + } + } +} + +struct EnvExports<'a> { + exports: Vec>, + reexport_cabi_realloc: bool, +} + +struct EnvExport<'a> { + name: &'a str, + ty: Cow<'a, FunctionType>, + exporter: usize, +} + +/// Analyze the specified metadata and generate what needs to be exported from +/// the main (aka "env") module. +/// +/// This includes a list of functions which should be re-exported as a +/// `call.indirect`-based function including the offset of the library +/// containing the original export. +/// +/// Additionally this includes any tags necessary that are shared amongst +/// modules. +fn env_exports<'a>( + metadata: &'a [Metadata<'a>], + exporters: &'a IndexMap<&'a ExportKey, (&'a str, &Export)>, + topo_sorted: &[usize], +) -> Result> { + let function_exporters = exporters + .iter() + .filter_map(|(export, exporter)| { + if let Type::Function(ty) = &export.ty { + Some((export.name, (ty, *exporter))) + } else { + None + } + }) + .collect_unique::>(); + + let indexes = metadata + .iter() + .enumerate() + .map(|(index, metadata)| (metadata.name, index)) + .collect_unique::>(); + + let mut result = Vec::new(); + let mut exported = HashSet::new(); + let mut seen = HashSet::new(); + + for &index in topo_sorted { + let metadata = &metadata[index]; + + for name in &metadata.table_address_imports { + if !exported.contains(name) { + let (ty, (exporter, _)) = function_exporters + .get(name) + .ok_or_else(|| anyhow!("unable to find {name:?} in any library"))?; + + result.push(EnvExport { + name: *name, + ty: Cow::Borrowed(*ty), + exporter: indexes[exporter], + }); + exported.insert(*name); + } + } + + for (import_name, (ty, _)) in &metadata.env_imports { + if !exported.contains(import_name) { + let exporter = indexes[find_function_exporter(import_name, ty, exporters) + .unwrap() + .0]; + if !seen.contains(&exporter) { + result.push(EnvExport { + name: *import_name, + ty: Cow::Borrowed(ty), + exporter, + }); + exported.insert(*import_name); + } + } + } + + seen.insert(index); + } + + // Even if no library imports these symbols, we re-export them from the + // `env` module so that + // `EncodingState::create_export_task_initialization_wrappers` can find + // and use them: + for (name, params, results) in ENV_REEXPORTS { + if !exported.contains(name) { + let ty = FunctionType { + parameters: params.to_vec(), + results: results.to_vec(), + }; + if let Some(exporter) = exporters.get(&ExportKey { + name, + ty: Type::Function(ty.clone()), + }) { + result.push(EnvExport { + name, + ty: Cow::Owned(ty), + exporter: indexes[exporter.0], + }); + exported.insert(name); + } + } + } + + let reexport_cabi_realloc = exported.contains(CABI_REALLOC); + + Ok(EnvExports { + exports: result, + reexport_cabi_realloc, + }) +} + +/// Synthesize a module which contains trapping stub exports for the specified functions. +fn make_stubs_module(missing: &[(&str, Export)]) -> Vec { + let mut types = TypeSection::new(); + let mut exports = ExportSection::new(); + let mut functions = FunctionSection::new(); + let mut code = CodeSection::new(); + for (offset, (_, export)) in missing.iter().enumerate() { + let offset = u32::try_from(offset).unwrap(); + + let Export { + key: + ExportKey { + name, + ty: Type::Function(ty), + }, + .. + } = export + else { + unreachable!(); + }; + + types.ty().function( + ty.parameters.iter().copied().map(ValType::from), + ty.results.iter().copied().map(ValType::from), + ); + functions.function(offset); + let mut function = Function::new([]); + function.instructions().unreachable().end(); + code.function(&function); + exports.export(name, ExportKind::Func, offset); + } + + let mut module = Module::new(); + + module.section(&types); + module.section(&functions); + module.section(&exports); + module.section(&code); + module.section(&RawCustomSection( + &crate::base_producers().raw_custom_section(), + )); + + let module = module.finish(); + wasmparser::validate(&module).unwrap(); + + module +} + +/// Determine which of the specified libraries are transitively reachable at runtime, i.e. reachable from a +/// component export or via `dlopen`. +fn find_reachable<'a>( + metadata: &'a [Metadata<'a>], + dependencies: &IndexMap>, +) -> IndexSet<&'a str> { + let reachable = metadata + .iter() + .enumerate() + .filter_map(|(index, metadata)| { + if metadata.has_component_exports || metadata.dl_openable || metadata.has_wasi_start { + Some(index) + } else { + None + } + }) + .collect_unique::>(); + + let empty = &IndexSet::new(); + + reachable + .iter() + .chain( + reachable + .iter() + .flat_map(|index| dependencies.get(index).unwrap_or(empty)), + ) + .map(|&index| metadata[index].name) + .collect() +} + +/// Builder type for composing dynamic library modules into a component +#[derive(Default)] +pub struct Linker { + /// The `(name, module, dl_openable)` triple representing the libraries to be composed + /// + /// The order of this list determines priority in cases where more than one library exports the same symbol. + libraries: Vec<(String, Vec, bool)>, + + /// Whether to generate trapping stubs for any unresolved imports + stub_missing_functions: bool, + + /// Whether to use a built-in implementation of `dlopen`/`dlsym`. + use_built_in_libdl: bool, + + /// Size of stack (in bytes) to allocate in the synthesized main module + /// + /// If `None`, use `DEFAULT_STACK_SIZE_BYTES`. + stack_size: Option, + + encoder: ComponentEncoder, +} + +impl Linker { + /// Add a dynamic library module to this linker. + /// + /// If `dl_openable` is true, all of the library's exports will be added to the `dlopen`/`dlsym` lookup table + /// for runtime resolution. + pub fn library(&mut self, name: &str, module: &[u8], dl_openable: bool) -> Result<&mut Self> { + self.libraries + .push((name.to_owned(), module.to_vec(), dl_openable)); + + Ok(self) + } + + /// Specify size of stack to allocate in the synthesized main module + pub fn stack_size(&mut self, stack_size: u32) -> &mut Self { + self.stack_size = Some(stack_size); + self + } + + /// Specify whether to generate trapping stubs for any unresolved imports + pub fn stub_missing_functions(&mut self, stub_missing_functions: bool) -> &mut Self { + self.stub_missing_functions = stub_missing_functions; + self + } + + /// Specify whether to use a built-in implementation of `dlopen`/`dlsym`. + pub fn use_built_in_libdl(&mut self, use_built_in_libdl: bool) -> &mut Self { + self.use_built_in_libdl = use_built_in_libdl; + self + } + + /// Returns a reference to the internal [`ComponentEncoder`] that can be + /// configured. + pub fn encoder(&mut self) -> &mut ComponentEncoder { + &mut self.encoder + } + + /// Encode the component and return the bytes + pub fn encode(mut self) -> Result> { + if self.use_built_in_libdl { + self.use_built_in_libdl = false; + self.library("libdl.so", include_bytes!("../libdl.so"), false)?; + } + + let adapter_names = self + .encoder + .adapters + .keys() + .map(|name| name.as_str()) + .collect::>(); + + let metadata = self + .libraries + .iter() + .map(|(name, module, dl_openable)| { + Metadata::try_new(name, *dl_openable, module, &adapter_names) + .with_context(|| format!("failed to extract linking metadata from {name}")) + }) + .collect::>>()?; + + { + let names = self + .libraries + .iter() + .map(|(name, ..)| name.as_str()) + .collect_unique::>(); + + let missing = metadata + .iter() + .filter_map(|metadata| { + let missing = metadata + .needed_libs + .iter() + .copied() + .filter(|name| !names.contains(*name)) + .collect::>(); + + if missing.is_empty() { + None + } else { + Some((metadata.name, missing)) + } + }) + .collect::>(); + + if !missing.is_empty() { + bail!( + "missing libraries:\n{}", + missing + .iter() + .map(|(needed_by, missing)| format!( + "\t{needed_by} needs {}", + missing.join(", ") + )) + .collect::>() + .join("\n") + ); + } + } + + let exporters = resolve_exporters(&metadata)?; + + let cabi_realloc_exporter = exporters + .get(&ExportKey { + name: "cabi_realloc", + ty: Type::Function(FunctionType { + parameters: vec![ValueType::I32; 4], + results: vec![ValueType::I32], + }), + }) + .map(|exporters| exporters.first().unwrap().0); + + let (exporters, missing, _) = resolve_symbols(&metadata, &exporters); + + if !missing.is_empty() { + if missing + .iter() + .all(|(_, export)| matches!(&export.key.ty, Type::Function(_))) + && (self.stub_missing_functions + || missing + .iter() + .all(|(_, export)| export.flags.contains(SymbolFlags::BINDING_WEAK))) + { + self.stub_missing_functions = false; + self.libraries + .push((STUB_LIBRARY_NAME.into(), make_stubs_module(&missing), false)); + return self.encode(); + } else { + bail!( + "unresolved symbol(s):\n{}", + missing + .iter() + .filter(|(_, export)| !export.flags.contains(SymbolFlags::BINDING_WEAK)) + .map(|(importer, export)| { format!("\t{importer} needs {}", export.key) }) + .collect::>() + .join("\n") + ); + } + } + + let dependencies = find_dependencies(&metadata, &exporters)?; + + { + let reachable = find_reachable(&metadata, &dependencies); + let unreachable = self + .libraries + .iter() + .filter_map(|(name, ..)| (!reachable.contains(name.as_str())).then(|| name.clone())) + .collect_unique::>(); + + if !unreachable.is_empty() { + self.libraries + .retain(|(name, ..)| !unreachable.contains(name)); + return self.encode(); + } + } + + let topo_sorted = topo_sort(metadata.len(), &dependencies)?; + + let EnvExports { + exports: env_exports, + reexport_cabi_realloc, + } = env_exports(&metadata, &exporters, &topo_sorted)?; + + let (env_module, dl_openables, tls, table_base) = make_env_module( + &metadata, + &env_exports, + if reexport_cabi_realloc { + // If "env" module already reexports "cabi_realloc", we don't need to + // reexport it again. + None + } else { + cabi_realloc_exporter + }, + self.stack_size.unwrap_or(DEFAULT_STACK_SIZE_BYTES), + ); + + self.encoder.module(&env_module)?; + + let default_env_items = [ + Item { + alias: metadata::MEMORY.into(), + kind: ExportKind::Memory, + which: MainOrAdapter::Main, + name: metadata::MEMORY.into(), + }, + Item { + alias: metadata::INDIRECT_FUNCTION_TABLE.into(), + kind: ExportKind::Table, + which: MainOrAdapter::Main, + name: metadata::INDIRECT_FUNCTION_TABLE.into(), + }, + Item { + alias: metadata::STACK_POINTER.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: metadata::STACK_POINTER.into(), + }, + Item { + alias: metadata::INIT_STACK_POINTER.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: metadata::INIT_STACK_POINTER.into(), + }, + ]; + + let mut seen = HashSet::new(); + for index in topo_sorted { + let (name, module, _) = &self.libraries[index]; + let metadata = &metadata[index]; + + let env_items = default_env_items + .iter() + .cloned() + .chain([ + Item { + alias: metadata::MEMORY_BASE.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: format!("{name}:memory_base"), + }, + Item { + alias: metadata::TABLE_BASE.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: format!("{name}:table_base"), + }, + ]) + .chain( + [ + (metadata.needs_get_tls_base, metadata::GET_TLS_BASE), + (metadata.needs_set_tls_base, metadata::SET_TLS_BASE), + ] + .into_iter() + .filter(|(needed, _)| *needed) + .map(|(_, intrinsic)| Item { + alias: intrinsic.into(), + kind: ExportKind::Func, + which: MainOrAdapter::Main, + name: format!("{name}:{intrinsic}"), + }), + ) + .chain(metadata.env_imports.iter().map(|(name, (ty, _))| { + let (exporter, _) = find_function_exporter(name, ty, &exporters).unwrap(); + + Item { + alias: (*name).into(), + kind: ExportKind::Func, + which: if seen.contains(exporter) { + MainOrAdapter::Adapter(exporter.to_owned()) + } else { + MainOrAdapter::Main + }, + name: (*name).into(), + } + })) + .chain( + metadata + .tag_imports + .iter() + .map(|(name, ty)| { + let (exporter, _) = find_tag_exporter(name, ty, &exporters).unwrap(); + + Ok(Item { + alias: (*name).into(), + kind: ExportKind::Tag, + which: if seen.contains(exporter) { + MainOrAdapter::Adapter(exporter.to_owned()) + } else { + // As of this writing, LLVM-produced shared + // libraries which use C++ exceptions import + // a `cpp_exception` tag which is defined in + // `libunwind.so`. Presumably + // `libunwind.so` will not import anything + // circularly from such shared libraries, so + // this case shouldn't be hit in practice + // unless we're dealing with some other, + // non-LLVM toolchain that does weird + // circular things with imports and + // exception tags. + bail!( + "circular dependency prevents direct tag import from `{}`", + exporter.to_owned() + ) + }, + name: (*name).into(), + }) + }) + .collect::>>()?, + ) + .chain(if metadata.is_asyncified { + vec![ + Item { + alias: metadata::ASYNCIFY_STATE.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: metadata::ASYNCIFY_STATE.into(), + }, + Item { + alias: metadata::ASYNCIFY_DATA.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: metadata::ASYNCIFY_DATA.into(), + }, + ] + } else { + vec![] + }) + .collect(); + + let global_item = |address_name: &str| Item { + alias: address_name.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: format!("{name}:{address_name}"), + }; + + let mem_items = metadata + .memory_address_imports + .iter() + .copied() + .map(global_item) + .chain( + [ + metadata::HEAP_BASE, + metadata::HEAP_END, + metadata::STACK_HIGH, + metadata::STACK_LOW, + metadata::LIBDL_LIBRARIES, + metadata::PROGRAM_TLS_INFO, + ] + .into_iter() + .map(|name| Item { + alias: name.into(), + kind: ExportKind::Global, + which: MainOrAdapter::Main, + name: name.into(), + }), + ) + .collect(); + + let func_items = metadata + .table_address_imports + .iter() + .copied() + .map(global_item) + .collect(); + + let mut import_items = BTreeMap::<_, Vec<_>>::new(); + for import in &metadata.imports { + import_items.entry(import.module).or_default().push(Item { + alias: import.name.into(), + kind: ExportKind::from(&import.ty), + which: MainOrAdapter::Main, + name: format!("{}:{}", import.module, import.name), + }); + } + + self.encoder.library( + name, + module, + LibraryInfo { + arguments: [ + (metadata::GOT_MEM.into(), Instance::Items(mem_items)), + (metadata::GOT_FUNC.into(), Instance::Items(func_items)), + (metadata::ENV.into(), Instance::Items(env_items)), + ] + .into_iter() + .chain( + import_items + .into_iter() + .map(|(k, v)| (k.into(), Instance::Items(v))), + ) + .collect(), + }, + )?; + + seen.insert(name.as_str()); + } + + self.encoder.encode_with_fixups(Some(&mut |fixups| { + make_init_module( + fixups, + &metadata, + &exporters, + &env_exports, + &dl_openables, + &tls, + table_base, + ) + })) + } +} diff --git a/vendor/wit-component/src/linking/metadata.rs b/vendor/wit-component/src/linking/metadata.rs new file mode 100644 index 00000000..7e26f86c --- /dev/null +++ b/vendor/wit-component/src/linking/metadata.rs @@ -0,0 +1,654 @@ +//! Support for parsing and analyzing [dynamic +//! library](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md) modules. + +use { + anyhow::{Context, Error, Result, bail}, + std::{ + collections::{BTreeSet, HashMap, HashSet}, + fmt, + }, + wasmparser::{ + Dylink0Subsection, ExternalKind, FuncType, KnownCustom, MemInfo, Parser, Payload, RefType, + SymbolFlags, TableType, TagKind, TagType, TypeRef, ValType, + }, +}; + +pub const ENV: &str = "env"; +pub const GOT_MEM: &str = "GOT.mem"; +pub const GOT_FUNC: &str = "GOT.func"; +pub const MEMORY: &str = "memory"; +pub const MEMORY_BASE: &str = "__memory_base"; +pub const TABLE_BASE: &str = "__table_base"; +pub const STACK_POINTER: &str = "__stack_pointer"; +pub const INIT_STACK_POINTER: &str = "__init_stack_pointer"; +pub const ASYNCIFY_DATA: &str = "__asyncify_data"; +pub const ASYNCIFY_STATE: &str = "__asyncify_state"; +pub const INDIRECT_FUNCTION_TABLE: &str = "__indirect_function_table"; +pub const HEAP_BASE: &str = "__heap_base"; +pub const HEAP_END: &str = "__heap_end"; +pub const STACK_HIGH: &str = "__stack_high"; +pub const STACK_LOW: &str = "__stack_low"; +pub const APPLY_DATA_RELOCS: &str = "__wasm_apply_data_relocs"; +pub const CALL_CTORS: &str = "__wasm_call_ctors"; +pub const INITIALIZE: &str = "_initialize"; +pub const START: &str = "_start"; +pub const LIBDL_LIBRARIES: &str = "__wasm_libdl_libraries"; +pub const TASK_HOOK: &str = "__wasm_task_hook"; +pub const ROOT: &str = "$root"; +pub const THREAD_NEW_INDIRECT: &str = "[thread-new-indirect-v0]"; +pub const CONTEXT_GET_1: &str = "[context-get-1]"; +pub const GET_STACK_POINTER: &str = "__wasm_get_stack_pointer"; +pub const SET_STACK_POINTER: &str = "__wasm_set_stack_pointer"; +pub const GET_TLS_BASE: &str = "__wasm_get_tls_base"; +pub const SET_TLS_BASE: &str = "__wasm_set_tls_base"; +pub const PROGRAM_TLS_INFO: &str = "__wasm_program_tls_info"; +pub const LIBRARY_TLS_INFO: &str = "__wasm_library_tls_info"; + +/// Represents a core Wasm value type (not including V128 or reference types, which are not yet supported) +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ValueType { + I32, + I64, + F32, + F64, +} + +impl TryFrom for ValueType { + type Error = Error; + + fn try_from(value: ValType) -> Result { + Ok(match value { + ValType::I32 => Self::I32, + ValType::I64 => Self::I64, + ValType::F32 => Self::F32, + ValType::F64 => Self::F64, + _ => bail!("{value:?} not yet supported"), + }) + } +} + +impl From for wasm_encoder::ValType { + fn from(value: ValueType) -> Self { + match value { + ValueType::I32 => Self::I32, + ValueType::I64 => Self::I64, + ValueType::F32 => Self::F32, + ValueType::F64 => Self::F64, + } + } +} + +/// Represents a core Wasm function type +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct FunctionType { + pub parameters: Vec, + pub results: Vec, +} + +impl fmt::Display for FunctionType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?} -> {:?}", self.parameters, self.results) + } +} + +impl TryFrom<&FuncType> for FunctionType { + type Error = Error; + + fn try_from(value: &FuncType) -> Result { + Ok(Self { + parameters: value + .params() + .iter() + .map(|&v| ValueType::try_from(v)) + .collect::>()?, + results: value + .results() + .iter() + .map(|&v| ValueType::try_from(v)) + .collect::>()?, + }) + } +} + +/// Represents a core Wasm global variable type +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct GlobalType { + pub ty: ValueType, + pub mutable: bool, + pub shared: bool, +} + +impl fmt::Display for GlobalType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.mutable { + write!(f, "mut ")?; + } + write!(f, "{:?}", self.ty) + } +} + +/// Represents a core Wasm export or import type +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Type { + Function(FunctionType), + Global(GlobalType), + Tag(FunctionType), +} + +impl fmt::Display for Type { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Function(ty) => write!(f, "function {ty}"), + Self::Global(ty) => write!(f, "global {ty}"), + Self::Tag(ty) => write!(f, "tag {ty}"), + } + } +} + +impl From<&Type> for wasm_encoder::ExportKind { + fn from(value: &Type) -> Self { + match value { + Type::Function(_) => wasm_encoder::ExportKind::Func, + Type::Global(_) => wasm_encoder::ExportKind::Global, + Type::Tag(_) => wasm_encoder::ExportKind::Tag, + } + } +} + +/// Represents a core Wasm import +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Import<'a> { + pub module: &'a str, + pub name: &'a str, + pub ty: Type, + pub flags: SymbolFlags, +} + +/// Represents a core Wasm export +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ExportKey<'a> { + pub name: &'a str, + pub ty: Type, +} + +impl<'a> fmt::Display for ExportKey<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} ({})", self.name, self.ty) + } +} + +/// Represents a core Wasm export, including dylink.0 flags +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Export<'a> { + pub key: ExportKey<'a>, + pub flags: SymbolFlags, +} + +/// Metadata extracted from a dynamic library module +#[derive(Debug)] +pub struct Metadata<'a> { + /// The name of the module + /// + /// This is currently not part of the file itself and must be provided separately, but the plan is to add + /// something like a `WASM_DYLINK_SO_NAME` field to the dynamic linking tool convention so we can parse it + /// along with everything else. + pub name: &'a str, + + /// Whether this module should be resolvable via `dlopen` + pub dl_openable: bool, + + /// The `WASM_DYLINK_MEM_INFO` value (or all zeros if not found) + pub mem_info: MemInfo, + + /// The `WASM_DYLINK_NEEDED` values, if any + pub needed_libs: Vec<&'a str>, + + /// The `WASM_DYLINK_RUNTIME_PATH` values, if any + pub runtime_path: Vec<&'a str>, + + /// Whether this module exports `__wasm_apply_data_relocs` + pub has_data_relocs: bool, + + /// Whether this module exports `__wasm_call_ctors` + pub has_ctors: bool, + + /// Whether this module exports `_initialize` + pub has_initialize: bool, + + /// Whether this module exports `_start` + pub has_wasi_start: bool, + + /// Whether this module imports `__wasm_libdl_libraries` + pub needs_libdl_libraries: bool, + + /// Whether this module includes any `component-type*` custom sections which include exports + pub has_component_exports: bool, + + /// Whether this module imports `__asyncify_state` or `__asyncify_data`, indicating that it is + /// asyncified with `--pass-arg=asyncify-relocatable` option. + pub is_asyncified: bool, + + /// Whether this module imports `__stack_pointer` + pub needs_stack_pointer: bool, + + /// Whether this module imports `__init_stack_pointer` + pub needs_init_stack_pointer: bool, + + /// Whether this module imports `__heap_base` + pub needs_heap_base: bool, + + /// Whether this module imports `__heap_end` + pub needs_heap_end: bool, + + /// Whether this module imports `__stack_high` + pub needs_stack_high: bool, + + /// Whether this module imports `__stack_low` + pub needs_stack_low: bool, + + /// Whether this module imports `env::__wasm_get_tls_base` + pub needs_get_tls_base: bool, + + /// Whether this module imports `env::__wasm_set_tls_base` + pub needs_set_tls_base: bool, + + /// Whether this module imports the address of `__wasm_program_tls_info` + pub needs_program_tls_info: bool, + + /// Whether this module imports `$root::[thread-new-indirect-v0]`, meaning + /// the program may spawn threads and is thus using cooperative threading. + pub uses_thread_new_indirect: bool, + + /// Whether this module exports a `__wasm_library_tls_info` symbol. + pub has_library_tls_info: bool, + + /// The functions imported from the `env` module, if any + pub env_imports: BTreeSet<(&'a str, (FunctionType, SymbolFlags))>, + + /// The memory addresses imported from `GOT.mem`, if any + pub memory_address_imports: BTreeSet<&'a str>, + + /// The table addresses imported from `GOT.func`, if any + pub table_address_imports: BTreeSet<&'a str>, + + /// Imported exception tags + pub tag_imports: BTreeSet<(&'a str, FunctionType)>, + + /// The symbols exported by this module, if any + pub exports: BTreeSet>, + + /// The symbols imported by this module (and not accounted for in the above fields), if any + pub imports: BTreeSet>, +} + +impl<'a> Metadata<'a> { + /// Parse the specified module and extract its metadata. + pub fn try_new( + name: &'a str, + dl_openable: bool, + module: &'a [u8], + adapter_names: &HashSet<&str>, + ) -> Result { + let bindgen = crate::metadata::decode(module)?.1; + let has_component_exports = !bindgen.resolve.worlds[bindgen.world].exports.is_empty(); + + let mut result = Self { + name, + dl_openable, + mem_info: MemInfo { + memory_size: 0, + memory_alignment: 1, + table_size: 0, + table_alignment: 1, + }, + needed_libs: Vec::new(), + runtime_path: Vec::new(), + has_data_relocs: false, + has_ctors: false, + has_initialize: false, + has_wasi_start: false, + needs_libdl_libraries: false, + has_component_exports, + is_asyncified: false, + needs_stack_pointer: false, + needs_init_stack_pointer: false, + needs_heap_base: false, + needs_heap_end: false, + needs_stack_high: false, + needs_stack_low: false, + needs_get_tls_base: false, + needs_set_tls_base: false, + needs_program_tls_info: false, + uses_thread_new_indirect: false, + has_library_tls_info: false, + env_imports: BTreeSet::new(), + memory_address_imports: BTreeSet::new(), + table_address_imports: BTreeSet::new(), + exports: BTreeSet::new(), + imports: BTreeSet::new(), + tag_imports: BTreeSet::new(), + }; + let mut types = Vec::new(); + let mut function_types = Vec::new(); + let mut global_types = Vec::new(); + let mut tag_types = Vec::new(); + let mut import_info = HashMap::new(); + let mut export_info = HashMap::new(); + + for payload in Parser::new(0).parse_all(module) { + match payload? { + Payload::CustomSection(section) => { + if let KnownCustom::Dylink0(reader) = section.as_known() { + for subsection in reader { + match subsection.context("failed to parse `dylink.0` subsection")? { + Dylink0Subsection::MemInfo(info) => result.mem_info = info, + Dylink0Subsection::Needed(needed) => { + result.needed_libs = needed.clone() + } + Dylink0Subsection::ExportInfo(info) => { + export_info + .extend(info.iter().map(|info| (info.name, info.flags))); + } + Dylink0Subsection::ImportInfo(info) => { + import_info.extend( + info.iter() + .map(|info| ((info.module, info.field), info.flags)), + ); + } + Dylink0Subsection::RuntimePath(runtime_path) => { + result.runtime_path.extend(runtime_path.iter()); + } + Dylink0Subsection::Unknown { ty, .. } => { + bail!("unrecognized `dylink.0` subsection: {ty}") + } + } + } + } + } + + Payload::TypeSection(reader) => { + types = reader + .into_iter_err_on_gc_types() + .collect::, _>>()?; + } + + Payload::ImportSection(reader) => { + for import in reader.into_imports() { + let import = import?; + + match import.ty { + TypeRef::Func(ty) => function_types.push(usize::try_from(ty).unwrap()), + TypeRef::Global(ty) => { + global_types.push(ty); + } + TypeRef::Tag(ty) => tag_types.push(ty), + _ => (), + } + + let type_error = || { + bail!( + "unexpected type for {}:{}: {:?}", + import.module, + import.name, + import.ty + ) + }; + + match (import.module, import.name) { + (self::ENV, self::MEMORY) => { + if !matches!(import.ty, TypeRef::Memory(_)) { + return type_error(); + } + } + (self::ENV, self::ASYNCIFY_DATA | self::ASYNCIFY_STATE) => { + result.is_asyncified = true; + if !matches!( + import.ty, + TypeRef::Global(wasmparser::GlobalType { + content_type: ValType::I32, + .. + }) + ) { + return type_error(); + } + } + ( + self::ENV, + self::MEMORY_BASE + | self::TABLE_BASE + | self::STACK_POINTER + | self::INIT_STACK_POINTER, + ) => { + if matches!( + import.ty, + TypeRef::Global(wasmparser::GlobalType { + content_type: ValType::I32, + .. + }) + ) { + match import.name { + self::STACK_POINTER => result.needs_stack_pointer = true, + self::INIT_STACK_POINTER => { + result.needs_init_stack_pointer = true + } + _ => {} + } + } else { + return type_error(); + } + } + (self::ENV, self::INDIRECT_FUNCTION_TABLE) => { + if let TypeRef::Table(TableType { + element_type, + maximum: None, + .. + }) = import.ty + { + if element_type != RefType::FUNCREF { + return type_error(); + } + } else { + return type_error(); + } + } + ( + self::ENV, + name @ (self::GET_STACK_POINTER + | self::SET_STACK_POINTER + | self::GET_TLS_BASE + | self::SET_TLS_BASE), + ) => { + if !matches!(import.ty, TypeRef::Func(_)) { + return type_error(); + } + match name { + self::GET_TLS_BASE => result.needs_get_tls_base = true, + self::SET_TLS_BASE => result.needs_set_tls_base = true, + _ => {} + } + } + (self::ENV, name) => match import.ty { + TypeRef::Func(ty) => { + result.env_imports.insert(( + name, + ( + FunctionType::try_from( + &types[usize::try_from(ty).unwrap()], + )?, + import_info + .get(&(self::ENV, name)) + .copied() + .unwrap_or_default(), + ), + )); + } + TypeRef::Tag(TagType { + kind: TagKind::Exception, + func_type_idx, + }) => { + result.tag_imports.insert(( + name, + FunctionType::try_from( + &types[usize::try_from(func_type_idx).unwrap()], + )?, + )); + } + _ => return type_error(), + }, + (self::GOT_MEM, name) => { + if let TypeRef::Global(wasmparser::GlobalType { + content_type: ValType::I32, + .. + }) = import.ty + { + match name { + self::HEAP_BASE => result.needs_heap_base = true, + self::HEAP_END => result.needs_heap_end = true, + self::STACK_HIGH => result.needs_stack_high = true, + self::STACK_LOW => result.needs_stack_low = true, + self::LIBDL_LIBRARIES => { + result.needs_libdl_libraries = true; + } + self::PROGRAM_TLS_INFO => { + result.needs_program_tls_info = true; + } + + _ => { + result.memory_address_imports.insert(name); + } + } + } else { + return type_error(); + } + } + (self::GOT_FUNC, name) => { + if let TypeRef::Global(wasmparser::GlobalType { + content_type: ValType::I32, + .. + }) = import.ty + { + result.table_address_imports.insert(name); + } else { + return type_error(); + } + } + (self::ROOT, self::THREAD_NEW_INDIRECT) => { + result.uses_thread_new_indirect = true; + } + (module, name) if adapter_names.contains(module) => { + let ty = match import.ty { + TypeRef::Global(wasmparser::GlobalType { + content_type, + mutable, + shared, + }) => Type::Global(GlobalType { + ty: content_type.try_into()?, + mutable, + shared, + }), + TypeRef::Func(ty) => Type::Function(FunctionType::try_from( + &types[usize::try_from(ty).unwrap()], + )?), + ty => { + bail!("unsupported import kind for {module}.{name}: {ty:?}",) + } + }; + let flags = import_info + .get(&(module, name)) + .copied() + .unwrap_or_default(); + result.imports.insert(Import { + module, + name, + ty, + flags, + }); + } + _ => { + if !matches!(import.ty, TypeRef::Func(_) | TypeRef::Global(_)) { + return type_error(); + } + } + } + } + } + + Payload::FunctionSection(reader) => { + for function in reader { + function_types.push(usize::try_from(function?).unwrap()); + } + } + + Payload::GlobalSection(reader) => { + for global in reader { + let global = global?; + global_types.push(global.ty); + } + } + + Payload::TagSection(reader) => { + for tag in reader { + tag_types.push(tag?); + } + } + + Payload::ExportSection(reader) => { + for export in reader { + let export = export?; + + match export.name { + self::APPLY_DATA_RELOCS => result.has_data_relocs = true, + self::CALL_CTORS => result.has_ctors = true, + self::INITIALIZE => result.has_initialize = true, + self::START => result.has_wasi_start = true, + self::LIBRARY_TLS_INFO => result.has_library_tls_info = true, + _ => { + let ty = match export.kind { + ExternalKind::Func => Type::Function(FunctionType::try_from( + &types[function_types + [usize::try_from(export.index).unwrap()]], + )?), + ExternalKind::Global => { + let ty = + global_types[usize::try_from(export.index).unwrap()]; + Type::Global(GlobalType { + ty: ValueType::try_from(ty.content_type)?, + mutable: ty.mutable, + shared: ty.shared, + }) + } + ExternalKind::Tag => Type::Tag(FunctionType::try_from( + &types[usize::try_from( + tag_types[usize::try_from(export.index).unwrap()] + .func_type_idx, + ) + .unwrap()], + )?), + kind => { + bail!( + "unsupported export kind for {}: {kind:?}", + export.name + ) + } + }; + let flags = + export_info.get(&export.name).copied().unwrap_or_default(); + result.exports.insert(Export { + key: ExportKey { + name: export.name, + ty, + }, + flags, + }); + } + } + } + } + + _ => {} + } + } + + Ok(result) + } +} diff --git a/vendor/wit-component/src/metadata.rs b/vendor/wit-component/src/metadata.rs new file mode 100644 index 00000000..361facbc --- /dev/null +++ b/vendor/wit-component/src/metadata.rs @@ -0,0 +1,448 @@ +//! Definition for encoding of custom sections within core wasm modules of +//! component-model related data. +//! +//! When creating a component from a source language the high-level process for +//! doing this is that code will be generated into the source language by +//! `wit-bindgen` or a similar tool which will be compiled down to core wasm. +//! The core wasm file is then fed into `wit-component` and a component is +//! created. This means that the componentization process is decoupled from the +//! binding generation process and intentionally affords for linking together +//! libraries into the main core wasm module that import different interfaces. +//! +//! The purpose of this module is to define an intermediate format to reside in +//! a custom section in the core wasm output. This intermediate format is +//! carried through the wasm linker through a custom section whose name starts +//! with `component-type`. This custom section is created +//! per-language-binding-generation and consumed by slurping up all the +//! sections during the component creation process. +//! +//! Currently the encoding of this custom section is itself a component. The +//! component has a single export which is a component type which represents the +//! `world` that was bound during bindings generation. This single export is +//! used to decode back into a `Resolve` with a WIT representation. +//! +//! Currently the component additionally has a custom section named +//! `wit-component-encoding` (see `CUSTOM_SECTION_NAME`). This section is +//! currently defined as 2 bytes: +//! +//! * The first byte is `CURRENT_VERSION` to help protect against future and +//! past changes. +//! * The second byte indicates the string encoding used for imports/exports as +//! part of the bindings process. The mapping is defined by +//! `encode_string_encoding`. +//! +//! This means that the top-level `encode` function takes a `Resolve`, a +//! `WorldId`, and a `StringEncoding`. Note that the top-level `decode` function +//! is slightly different because it's taking all custom sections in a core +//! wasm binary, possibly from multiple invocations of bindgen, and unioning +//! them all together. This means that the output is a `Bindgen` which +//! represents the union of all previous bindings. +//! +//! The dual of `encode` is the `decode_custom_section` function which decodes +//! the three arguments originally passed to `encode`. + +use crate::{DecodedWasm, StringEncoding}; +use anyhow::{Context, Result, bail}; +use indexmap::{IndexMap, IndexSet}; +use std::borrow::Cow; +use wasm_encoder::{ + ComponentBuilder, ComponentExportKind, ComponentType, ComponentTypeRef, CustomSection, +}; +use wasm_metadata::Producers; +use wasmparser::{BinaryReader, Encoding, Parser, Payload}; +use wit_parser::{CloneMaps, Package, PackageName, Resolve, World, WorldId, WorldItem, WorldKey}; + +const CURRENT_VERSION: u8 = 0x04; +const CUSTOM_SECTION_NAME: &str = "wit-component-encoding"; + +/// The result of decoding binding information from a WebAssembly binary. +/// +/// This structure is returned by [`decode`] and represents the interface of a +/// WebAssembly binary. +pub struct Bindgen { + /// Interface and type information for this binary. + pub resolve: Resolve, + /// The world that was bound. + pub world: WorldId, + /// Metadata about this specific module that was bound. + pub metadata: ModuleMetadata, + /// Producer information about tools used to produce this specific module. + pub producers: Option, +} + +impl Default for Bindgen { + fn default() -> Bindgen { + let mut resolve = Resolve::default(); + let package = resolve.packages.alloc(Package { + name: PackageName { + namespace: "root".to_string(), + name: "root".to_string(), + version: None, + }, + docs: Default::default(), + interfaces: Default::default(), + worlds: Default::default(), + }); + let world = resolve.worlds.alloc(World { + name: "root".to_string(), + docs: Default::default(), + imports: Default::default(), + exports: Default::default(), + includes: Default::default(), + package: Some(package), + stability: Default::default(), + span: Default::default(), + }); + resolve.packages[package] + .worlds + .insert("root".to_string(), world); + Bindgen { + resolve, + world, + metadata: ModuleMetadata::default(), + producers: None, + } + } +} + +/// Module-level metadata that's specific to one core WebAssembly module. This +/// is extracted with a [`Bindgen`]. +#[derive(Default)] +pub struct ModuleMetadata { + /// Per-function options imported into the core wasm module, currently only + /// related to string encoding. + pub import_encodings: EncodingMap, + + /// Per-function options exported from the core wasm module, currently only + /// related to string encoding. + pub export_encodings: EncodingMap, +} + +/// Internal map that keeps track of encodings for various world imports and +/// exports. +/// +/// Stored in [`ModuleMetadata`]. +#[derive(Default)] +pub struct EncodingMap { + /// A map of an "identifying string" for world items to what string + /// encoding the import or export is using. + /// + /// The keys of this map are created by `EncodingMap::key` and are + /// specifically chosen to be able to be looked up during both insertion and + /// fetching. Note that in particular this map does not use `*Id` types such + /// as `InterfaceId` from `wit_parser`. This is due to the fact that during + /// world merging new interfaces are created for named imports (e.g. `import + /// x: interface { ... }`) as inline interfaces are copied from one world to + /// another. Additionally during world merging different interfaces at the + /// same version may be deduplicated. + /// + /// For these reasons a string-based key is chosen to avoid juggling IDs + /// through the world merging process. Additionally versions are chopped off + /// for now to help with a problem such as: + /// + /// * The main module imports a:b/c@0.1.0 + /// * An adapter imports a:b/c@0.1.1 + /// * The final world uses a:b/c@0.1.1, but the main module has no + /// encoding listed for that exact item. + /// + /// By chopping off versions this is able to get everything registered + /// correctly even in the fact of merging interfaces and worlds. + encodings: IndexMap, +} + +impl EncodingMap { + fn insert_all( + &mut self, + resolve: &Resolve, + set: &IndexMap, + encoding: StringEncoding, + ) { + for (name, item) in set { + match item { + WorldItem::Function(func) => { + let key = self.key(resolve, name, &func.name); + self.encodings.insert(key, encoding); + } + WorldItem::Interface { id, .. } => { + for (func, _) in resolve.interfaces[*id].functions.iter() { + let key = self.key(resolve, name, func); + self.encodings.insert(key, encoding); + } + } + WorldItem::Type { .. } => {} + } + } + } + + /// Looks up the encoding of the function `func` which is scoped under `key` + /// in the world in question. + pub fn get(&self, resolve: &Resolve, key: &WorldKey, func: &str) -> Option { + let key = self.key(resolve, key, func); + self.encodings.get(&key).copied() + } + + fn key(&self, resolve: &Resolve, key: &WorldKey, func: &str) -> String { + format!( + "{}/{func}", + match key { + WorldKey::Name(name) => name.to_string(), + WorldKey::Interface(id) => { + let iface = &resolve.interfaces[*id]; + let pkg = &resolve.packages[iface.package.unwrap()]; + format!( + "{}:{}/{}", + pkg.name.namespace, + pkg.name.name, + iface.name.as_ref().unwrap() + ) + } + } + ) + } + + fn merge(&mut self, other: EncodingMap) -> Result<()> { + for (key, encoding) in other.encodings { + if let Some(prev) = self.encodings.insert(key.clone(), encoding) { + if prev != encoding { + bail!("conflicting string encodings specified for `{key}`"); + } + } + } + Ok(()) + } +} + +/// This function will parse the core `wasm` binary given as input and return a +/// [`Bindgen`] which extracts the custom sections describing component-level +/// types from within the binary itself. +/// +/// This is used to parse the output of `wit-bindgen`-generated modules and is +/// one of the earliest phases in transitioning such a module to a component. +/// The extraction here provides the metadata necessary to continue the process +/// later on. +/// +/// This will return an error if `wasm` is not a valid WebAssembly module. +/// +/// If a `component-type` custom section was found then a new binary is +/// optionally returned with the custom sections stripped out. If no +/// `component-type` custom sections are found then `None` is returned. +pub fn decode(wasm: &[u8]) -> Result<(Option>, Bindgen)> { + let mut ret = Bindgen::default(); + let mut new_module = wasm_encoder::Module::new(); + + let mut found_custom = false; + for payload in wasmparser::Parser::new(0).parse_all(&wasm) { + let payload = payload.context("decoding item in module")?; + match payload { + wasmparser::Payload::CustomSection(cs) if cs.name().starts_with("component-type") => { + let data = Bindgen::decode_custom_section(cs.data()) + .with_context(|| format!("decoding custom section {}", cs.name()))?; + ret.merge(data) + .with_context(|| format!("updating metadata for section {}", cs.name()))?; + found_custom = true; + } + wasmparser::Payload::Version { encoding, .. } if encoding != Encoding::Module => { + bail!("decoding a component is not supported") + } + _ => { + if let Some((id, range)) = payload.as_section() { + new_module.section(&wasm_encoder::RawSection { + id, + data: &wasm[range.start as usize..range.end as usize], + }); + } + } + } + } + + if found_custom { + Ok((Some(new_module.finish()), ret)) + } else { + Ok((None, ret)) + } +} + +/// Creates a `component-type*` custom section to be decoded by `decode` above. +/// +/// This is primarily created by wit-bindgen-based guest generators to embed +/// into the final core wasm binary. The core wasm binary is later fed +/// through `wit-component` to produce the actual component where this returned +/// section will be decoded. +pub fn encode( + resolve: &Resolve, + world: WorldId, + string_encoding: StringEncoding, + extra_producers: Option<&Producers>, +) -> Result> { + let ty = crate::encoding::encode_world(resolve, world)?; + + let world = &resolve.worlds[world]; + let mut outer_ty = ComponentType::new(); + outer_ty.ty().component(&ty); + outer_ty.export( + resolve.id_of_name(world.package.unwrap(), &world.name), + ComponentTypeRef::Component(0), + ); + + let mut builder = ComponentBuilder::default(); + + let string_encoding = encode_string_encoding(string_encoding); + builder.custom_section(&CustomSection { + name: CUSTOM_SECTION_NAME.into(), + data: Cow::Borrowed(&[CURRENT_VERSION, string_encoding]), + }); + + let ty = builder.type_component(None, &outer_ty); + builder.export(&world.name, ComponentExportKind::Type, ty, None); + + let mut producers = crate::base_producers(); + if let Some(p) = extra_producers { + producers.merge(&p); + } + builder.raw_custom_section(&producers.raw_custom_section()); + Ok(builder.finish()) +} + +fn decode_custom_section(wasm: &[u8]) -> Result<(Resolve, WorldId, StringEncoding)> { + let (resolve, world) = wit_parser::decoding::decode_world(wasm)?; + let mut custom_section = None; + + for payload in Parser::new(0).parse_all(wasm) { + match payload? { + Payload::CustomSection(s) if s.name() == CUSTOM_SECTION_NAME => { + custom_section = Some(s.data()); + } + _ => {} + } + } + let string_encoding = match custom_section { + None => bail!("missing custom section of name `{CUSTOM_SECTION_NAME}`"), + Some([CURRENT_VERSION, byte]) => decode_string_encoding(*byte)?, + Some([]) => bail!("custom section `{CUSTOM_SECTION_NAME}` in unknown format"), + Some([version, ..]) => bail!( + "custom section `{CUSTOM_SECTION_NAME}` uses format {version} but only {CURRENT_VERSION} is supported" + ), + }; + Ok((resolve, world, string_encoding)) +} + +fn encode_string_encoding(e: StringEncoding) -> u8 { + match e { + StringEncoding::UTF8 => 0x00, + StringEncoding::UTF16 => 0x01, + StringEncoding::CompactUTF16 => 0x02, + } +} + +fn decode_string_encoding(byte: u8) -> Result { + match byte { + 0x00 => Ok(StringEncoding::UTF8), + 0x01 => Ok(StringEncoding::UTF16), + 0x02 => Ok(StringEncoding::CompactUTF16), + byte => bail!("invalid string encoding {byte:#x}"), + } +} + +impl Bindgen { + fn decode_custom_section(data: &[u8]) -> Result { + let wasm; + let world; + let resolve; + let encoding; + + let mut reader = BinaryReader::new(&data, 0); + match reader.read_u8()? { + // Historical 0x03 format where the support here will be deleted in + // the future + 0x03 => { + encoding = decode_string_encoding(reader.read_u8()?)?; + let world_name = reader.read_string()?; + let data_offset = reader.original_position() as usize; + wasm = &data[data_offset..]; + + let (r, pkg) = match crate::decode(wasm)? { + DecodedWasm::WitPackage(resolve, pkgs) => (resolve, pkgs), + DecodedWasm::Component(..) => bail!("expected encoded wit package(s)"), + }; + resolve = r; + world = resolve.select_world(&[pkg], Some(world_name.into()))?; + } + + // Current format where `data` is a wasm component itself. + _ => { + wasm = data; + (resolve, world, encoding) = decode_custom_section(wasm)?; + } + } + + Ok(Bindgen { + metadata: ModuleMetadata::new(&resolve, world, encoding), + producers: wasm_metadata::Producers::from_wasm(wasm)?, + resolve, + world, + }) + } + + /// Merges another `BindgenMetadata` into this one. + /// + /// This operation is intended to be akin to "merging worlds" when the + /// abstraction level for that is what we're working at here. For now the + /// merge operation only succeeds if the two metadata descriptions are + /// entirely disjoint. + /// + /// Note that at this time there's no support for changing string encodings + /// between metadata. + /// + /// This function returns the set of exports that the main world of + /// `other` added to the world in `self`. + pub fn merge(&mut self, other: Bindgen) -> Result> { + let Bindgen { + resolve, + world, + metadata: + ModuleMetadata { + import_encodings, + export_encodings, + }, + producers, + } = other; + + let remap = self + .resolve + .merge(resolve) + .context("failed to merge WIT package sets together")?; + let world = remap.map_world(world, Default::default())?; + let exports = self.resolve.worlds[world].exports.keys().cloned().collect(); + self.resolve + .merge_worlds(world, self.world, &mut CloneMaps::default()) + .context("failed to merge worlds from two documents")?; + + self.metadata.import_encodings.merge(import_encodings)?; + self.metadata.export_encodings.merge(export_encodings)?; + if let Some(producers) = producers { + if let Some(mine) = &mut self.producers { + mine.merge(&producers); + } else { + self.producers = Some(producers); + } + } + + Ok(exports) + } +} + +impl ModuleMetadata { + /// Creates a new `ModuleMetadata` instance holding the given set of + /// interfaces which are expected to all use the `encoding` specified. + pub fn new(resolve: &Resolve, world: WorldId, encoding: StringEncoding) -> ModuleMetadata { + let mut ret = ModuleMetadata::default(); + + let world = &resolve.worlds[world]; + ret.export_encodings + .insert_all(resolve, &world.exports, encoding); + ret.import_encodings + .insert_all(resolve, &world.imports, encoding); + + ret + } +} diff --git a/vendor/wit-component/src/printing.rs b/vendor/wit-component/src/printing.rs new file mode 100644 index 00000000..a9381465 --- /dev/null +++ b/vendor/wit-component/src/printing.rs @@ -0,0 +1,1533 @@ +use anyhow::{Result, anyhow, bail}; +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt::Display; +use std::mem; +use std::ops::Deref; +use wit_parser::*; + +/// A utility for printing WebAssembly interface definitions to a string. +pub struct WitPrinter { + /// Visitor that holds the WIT document being printed. + pub output: O, + + // Count of how many items in this current block have been printed to print + // a blank line between each item, but not the first item. + any_items: bool, + + // Whether to print doc comments. + emit_docs: bool, +} + +impl Default for WitPrinter { + fn default() -> Self { + Self::new(OutputToString::default()) + } +} + +impl WitPrinter { + /// Create new instance. + pub fn new(output: O) -> Self { + Self { + output, + any_items: false, + emit_docs: true, + } + } + + /// Prints the specified `pkg` which is located in `resolve` to `O`. + /// + /// The `nested` list of packages are other packages to include at the end + /// of the output in `package ... { ... }` syntax. + pub fn print(&mut self, resolve: &Resolve, pkg: PackageId, nested: &[PackageId]) -> Result<()> { + self.print_package(resolve, pkg, true)?; + for (i, pkg_id) in nested.iter().enumerate() { + if i > 0 { + self.output.newline(); + self.output.newline(); + } + self.print_package(resolve, *pkg_id, false)?; + } + Ok(()) + } + + /// Configure whether doc comments will be printed. + /// + /// Defaults to true. + pub fn emit_docs(&mut self, enabled: bool) -> &mut Self { + self.emit_docs = enabled; + self + } + + /// Prints the specified `pkg`. + /// + /// If `is_main` is not set, nested package notation is used. + pub fn print_package( + &mut self, + resolve: &Resolve, + pkg: PackageId, + is_main: bool, + ) -> Result<()> { + let pkg = &resolve.packages[pkg]; + self.print_package_outer(pkg)?; + + if is_main { + self.output.semicolon(); + self.output.newline(); + } else { + self.output.indent_start(); + } + + for (name, id) in pkg.interfaces.iter() { + self.print_interface_outer(resolve, *id, name)?; + self.output.indent_start(); + self.print_interface(resolve, *id)?; + self.output.indent_end(); + if is_main { + self.output.newline(); + } + } + + for (name, id) in pkg.worlds.iter() { + self.print_docs(&resolve.worlds[*id].docs); + self.print_stability(&resolve.worlds[*id].stability); + self.output.keyword("world"); + self.output.str(" "); + self.print_name_type(name, TypeKind::WorldDeclaration); + self.output.indent_start(); + self.print_world(resolve, *id)?; + self.output.indent_end(); + } + if !is_main { + self.output.indent_end(); + } + Ok(()) + } + + /// Print the specified package without its content. + /// Does not print the semicolon nor starts the indentation. + pub fn print_package_outer(&mut self, pkg: &Package) -> Result<()> { + self.print_docs(&pkg.docs); + self.output.keyword("package"); + self.output.str(" "); + self.print_name_type(&pkg.name.namespace, TypeKind::NamespaceDeclaration); + self.output.str(":"); + self.print_name_type(&pkg.name.name, TypeKind::PackageNameDeclaration); + if let Some(version) = &pkg.name.version { + self.print_name_type(&format!("@{version}"), TypeKind::VersionDeclaration); + } + Ok(()) + } + + fn new_item(&mut self) { + if self.any_items { + self.output.newline(); + } + self.any_items = true; + } + + /// Print the given WebAssembly interface without its content. + /// Does not print the semicolon nor starts the indentation. + pub fn print_interface_outer( + &mut self, + resolve: &Resolve, + id: InterfaceId, + name: &str, + ) -> Result<()> { + self.print_docs(&resolve.interfaces[id].docs); + self.print_stability(&resolve.interfaces[id].stability); + self.output.keyword("interface"); + self.output.str(" "); + self.print_name_type(name, TypeKind::InterfaceDeclaration); + Ok(()) + } + + /// Print the inner content of a given WebAssembly interface. + pub fn print_interface(&mut self, resolve: &Resolve, id: InterfaceId) -> Result<()> { + let prev_items = mem::replace(&mut self.any_items, false); + let interface = &resolve.interfaces[id]; + + let mut resource_funcs = HashMap::new(); + let mut freestanding = Vec::new(); + for (_, func) in interface.functions.iter() { + if let Some(id) = func.kind.resource() { + resource_funcs.entry(id).or_insert(Vec::new()).push(func); + } else { + freestanding.push(func); + } + } + + self.print_types( + resolve, + TypeOwner::Interface(id), + interface + .types + .iter() + .map(|(name, id)| (name.as_str(), *id)), + &resource_funcs, + )?; + + for func in freestanding { + self.new_item(); + self.print_docs(&func.docs); + self.print_stability(&func.stability); + self.print_external_id(func.external_id.as_deref()); + self.print_name_type(func.item_name(), TypeKind::FunctionFreestanding); + self.output.str(": "); + self.print_function(resolve, func)?; + self.output.semicolon(); + } + + self.any_items = prev_items; + + Ok(()) + } + + /// Print types of an interface. + pub fn print_types<'a>( + &mut self, + resolve: &Resolve, + owner: TypeOwner, + types: impl Iterator, + resource_funcs: &HashMap>, + ) -> Result<()> { + // Partition types defined in this interface into either those imported + // from foreign interfaces or those defined locally. + let mut types_to_declare = Vec::new(); + let mut types_to_import: Vec<(_, &TypeDef, Vec<_>)> = Vec::new(); + for (name, ty_id) in types { + let ty = &resolve.types[ty_id]; + + // If `ty` points to another type, `other`, then this might actually + // be a `use`. + if let TypeDefKind::Type(Type::Id(other)) = ty.kind { + let other = &resolve.types[other]; + match other.owner { + TypeOwner::None => {} + + // `use` is only applicable when the owner of the current + // set of types is different than the owner of `other`. Once + // this is detected `types_to_import` is going to get + // modified. + other_owner if owner != other_owner => { + let other_name = other + .name + .as_ref() + .ok_or_else(|| anyhow!("cannot import unnamed type"))?; + + // As a convenience push onto the last set of types to + // import if it's to the same interface and with + // matching attributes. + if let Some((prev_owner, prev_ty, list)) = types_to_import.last_mut() { + if *prev_owner == other_owner + && ty.stability == prev_ty.stability + && ty.external_id == prev_ty.external_id + { + list.push((name, other_name)); + continue; + } + } + types_to_import.push((other_owner, ty, vec![(name, other_name)])); + continue; + } + _ => {} + } + } + + types_to_declare.push(ty_id); + } + + // Generate a `use` statement for all imported types. + let my_pkg = match owner { + TypeOwner::Interface(id) => resolve.interfaces[id].package.unwrap(), + TypeOwner::World(id) => resolve.worlds[id].package.unwrap(), + TypeOwner::None => unreachable!(), + }; + for (owner, ty, tys) in types_to_import { + self.any_items = true; + self.print_stability(&ty.stability); + self.print_external_id(ty.external_id.as_deref()); + self.output.keyword("use"); + self.output.str(" "); + let id = match owner { + TypeOwner::Interface(id) => id, + // it's only possible to import types from interfaces at + // this time. + _ => unreachable!(), + }; + self.print_path_to_interface(resolve, id, my_pkg)?; + self.output.str(".{"); // Note: not changing the indentation. + for (i, (my_name, other_name)) in tys.into_iter().enumerate() { + if i > 0 { + self.output.str(", "); + } + if my_name == other_name { + self.print_name_type(my_name, TypeKind::TypeImport); + } else { + self.print_name_type(other_name, TypeKind::TypeImport); + self.output.str(" "); + self.output.keyword("as"); + self.output.str(" "); + self.print_name_type(my_name, TypeKind::TypeAlias); + } + } + self.output.str("}"); // Note: not changing the indentation. + self.output.semicolon(); + } + + for id in types_to_declare { + self.new_item(); + self.print_docs(&resolve.types[id].docs); + self.print_stability(&resolve.types[id].stability); + self.print_external_id(resolve.types[id].external_id.as_deref()); + match resolve.types[id].kind { + TypeDefKind::Resource => self.print_resource( + resolve, + id, + resource_funcs.get(&id).unwrap_or(&Vec::new()), + )?, + _ => self.declare_type(resolve, &Type::Id(id))?, + } + } + + Ok(()) + } + + fn print_resource(&mut self, resolve: &Resolve, id: TypeId, funcs: &[&Function]) -> Result<()> { + let ty = &resolve.types[id]; + self.output.ty("resource", TypeKind::BuiltIn); + self.output.str(" "); + self.print_name_type( + ty.name.as_ref().expect("resources must be named"), + TypeKind::Resource, + ); + if funcs.is_empty() { + self.output.semicolon(); + return Ok(()); + } + self.output.indent_start(); + for func in funcs { + self.print_docs(&func.docs); + self.print_stability(&func.stability); + self.print_external_id(func.external_id.as_deref()); + + match &func.kind { + FunctionKind::Constructor(_) => {} + FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => { + self.print_name_type(func.item_name(), TypeKind::FunctionMethod); + self.output.str(": "); + } + FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => { + self.print_name_type(func.item_name(), TypeKind::FunctionStatic); + self.output.str(": "); + self.output.keyword("static"); + self.output.str(" "); + } + FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => unreachable!(), + } + self.print_function(resolve, func)?; + self.output.semicolon(); + } + self.output.indent_end(); + + Ok(()) + } + + fn print_function(&mut self, resolve: &Resolve, func: &Function) -> Result<()> { + // Handle the `async` prefix if necessary + match &func.kind { + FunctionKind::AsyncFreestanding + | FunctionKind::AsyncMethod(_) + | FunctionKind::AsyncStatic(_) => { + self.output.keyword("async"); + self.output.str(" "); + } + _ => {} + } + + // Constructors are named slightly differently. + match &func.kind { + FunctionKind::Constructor(_) => { + self.output.keyword("constructor"); + self.output.str("("); + } + FunctionKind::Freestanding + | FunctionKind::AsyncFreestanding + | FunctionKind::Method(_) + | FunctionKind::AsyncMethod(_) + | FunctionKind::Static(_) + | FunctionKind::AsyncStatic(_) => { + self.output.keyword("func"); + self.output.str("("); + } + } + + // Methods don't print their `self` argument + let params_to_skip = match &func.kind { + FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => 1, + _ => 0, + }; + for (i, param) in func.params.iter().skip(params_to_skip).enumerate() { + if i > 0 { + self.output.str(", "); + } + self.print_name_param(¶m.name); + self.output.str(": "); + self.print_type_name(resolve, ¶m.ty)?; + } + self.output.str(")"); + + // shorthand constructors don't have their results printed + if func.is_constructor_shorthand(resolve) { + return Ok(()); + } + + if let Some(ty) = &func.result { + self.output.str(" -> "); + self.print_type_name(resolve, ty)?; + } + Ok(()) + } + + /// Prints the world `id` within `resolve`. + /// + /// This is a little tricky to preserve round-tripping that WIT wants. This + /// function inherently can't preserve ordering of imports because resource + /// functions aren't guaranteed to be all adjacent to the resource itself + /// they're attached to. That means that at the very least, when printing + /// resource functions, items may be printed out-of-order. + /// + /// To help solve this the printing here is kept in sync with WIT encoding + /// of worlds which is to print items in the order of: + /// + /// * Any imported interface. Ordering between interfaces is preserved. + /// * Any types, including resource functions on those types. Ordering + /// between types is preserved. + /// * Any functions, which may refer to those types. Ordering between + /// functions is preserved. + /// + /// This keeps things printed in a roughly topological fashion and makes + /// round-tripping a bit more reliable. + fn print_world(&mut self, resolve: &Resolve, id: WorldId) -> Result<()> { + let prev_items = mem::replace(&mut self.any_items, false); + let world = &resolve.worlds[id]; + let pkgid = world.package.unwrap(); + let mut types = Vec::new(); + let mut resource_funcs = HashMap::new(); + let mut function_imports_to_print = Vec::new(); + for (name, import) in world.imports.iter() { + match import { + WorldItem::Type { id, .. } => match name { + WorldKey::Name(s) => types.push((s.as_str(), *id)), + WorldKey::Interface(_) => unreachable!(), + }, + _ => { + if let WorldItem::Function(f) = import { + if let Some(id) = f.kind.resource() { + resource_funcs.entry(id).or_insert(Vec::new()).push(f); + continue; + } + function_imports_to_print.push((name, import)); + continue; + } + self.print_world_item(resolve, name, import, pkgid, "import")?; + // Don't put a blank line between imports, but count + // imports as having printed something so if anything comes + // after them then a blank line is printed after imports. + self.any_items = true; + } + } + } + self.print_types( + resolve, + TypeOwner::World(id), + types.into_iter(), + &resource_funcs, + )?; + + for (name, import) in function_imports_to_print { + self.print_world_item(resolve, name, import, pkgid, "import")?; + self.any_items = true; + } + if !world.exports.is_empty() { + self.new_item(); + } + for (name, export) in world.exports.iter() { + self.print_world_item(resolve, name, export, pkgid, "export")?; + } + self.any_items = prev_items; + Ok(()) + } + + fn print_world_item( + &mut self, + resolve: &Resolve, + name: &WorldKey, + item: &WorldItem, + cur_pkg: PackageId, + import_or_export_keyword: &str, + ) -> Result<()> { + // Print docs for this import/export statement. For interfaces, prefer + // the docs attached to the statement itself (`WorldItem::Interface`'s + // `docs`); for an inline `import x: interface { .. }` with no statement + // docs fall back to the interface definition's docs. + let docs = match item { + WorldItem::Interface { id, docs, .. } => { + if docs.contents.is_some() { + Some(docs) + } else if matches!(name, WorldKey::Name(_)) { + Some(&resolve.interfaces[*id].docs) + } else { + None + } + } + WorldItem::Function(f) => Some(&f.docs), + // Types are handled separately + WorldItem::Type { .. } => unreachable!(), + }; + if let Some(docs) = docs { + self.print_docs(docs); + } + + self.print_stability(item.stability(resolve)); + self.print_external_id(resolve.external_id_value(name, item).as_deref()); + self.output.keyword(import_or_export_keyword); + self.output.str(" "); + match name { + WorldKey::Name(name) => { + match item { + WorldItem::Interface { id, .. } => { + self.print_name_type(name, TypeKind::Other); + self.output.str(": "); + if resolve.interfaces[*id].name.is_none() { + // `import label: interface { .. }` syntax + self.output.keyword("interface"); + self.output.indent_start(); + self.print_interface(resolve, *id)?; + self.output.indent_end(); + } else { + // `import label: use-path;` syntax + self.print_path_to_interface(resolve, *id, cur_pkg)?; + self.output.semicolon(); + } + } + WorldItem::Function(f) => { + self.print_name_type(&f.name, TypeKind::Other); + self.output.str(": "); + self.print_function(resolve, f)?; + self.output.semicolon(); + } + // Types are handled separately + WorldItem::Type { .. } => unreachable!(), + } + } + WorldKey::Interface(id) => { + match item { + WorldItem::Interface { id: id2, .. } => assert_eq!(id, id2), + _ => unreachable!(), + } + self.print_path_to_interface(resolve, *id, cur_pkg)?; + self.output.semicolon(); + } + } + Ok(()) + } + + fn print_path_to_interface( + &mut self, + resolve: &Resolve, + interface: InterfaceId, + cur_pkg: PackageId, + ) -> Result<()> { + let iface = &resolve.interfaces[interface]; + if iface.package == Some(cur_pkg) { + self.print_name_type(iface.name.as_ref().unwrap(), TypeKind::InterfacePath); + } else { + let pkg = &resolve.packages[iface.package.unwrap()].name; + self.print_name_type(&pkg.namespace, TypeKind::NamespacePath); + self.output.str(":"); + self.print_name_type(&pkg.name, TypeKind::PackageNamePath); + self.output.str("/"); + self.print_name_type(iface.name.as_ref().unwrap(), TypeKind::InterfacePath); + if let Some(version) = &pkg.version { + self.print_name_type(&format!("@{version}"), TypeKind::VersionPath); + } + } + Ok(()) + } + + /// Print the name of type `ty`. + pub fn print_type_name(&mut self, resolve: &Resolve, ty: &Type) -> Result<()> { + match ty { + Type::Bool => self.output.ty("bool", TypeKind::BuiltIn), + Type::U8 => self.output.ty("u8", TypeKind::BuiltIn), + Type::U16 => self.output.ty("u16", TypeKind::BuiltIn), + Type::U32 => self.output.ty("u32", TypeKind::BuiltIn), + Type::U64 => self.output.ty("u64", TypeKind::BuiltIn), + Type::S8 => self.output.ty("s8", TypeKind::BuiltIn), + Type::S16 => self.output.ty("s16", TypeKind::BuiltIn), + Type::S32 => self.output.ty("s32", TypeKind::BuiltIn), + Type::S64 => self.output.ty("s64", TypeKind::BuiltIn), + Type::F32 => self.output.ty("f32", TypeKind::BuiltIn), + Type::F64 => self.output.ty("f64", TypeKind::BuiltIn), + Type::Char => self.output.ty("char", TypeKind::BuiltIn), + Type::String => self.output.ty("string", TypeKind::BuiltIn), + Type::ErrorContext => self.output.ty("error-context", TypeKind::BuiltIn), + + Type::Id(id) => { + let ty = &resolve.types[*id]; + if let Some(name) = &ty.name { + self.print_name_type(name, TypeKind::Other); + return Ok(()); + } + + match &ty.kind { + TypeDefKind::Handle(h) => { + self.print_handle_type(resolve, h, false)?; + } + TypeDefKind::Resource => { + bail!("resolve has an unnamed resource type"); + } + TypeDefKind::Tuple(t) => { + self.print_tuple_type(resolve, t)?; + } + TypeDefKind::Option(t) => { + self.print_option_type(resolve, t)?; + } + TypeDefKind::Result(t) => { + self.print_result_type(resolve, t)?; + } + TypeDefKind::Record(_) => { + bail!("resolve has an unnamed record type"); + } + TypeDefKind::Flags(_) => { + bail!("resolve has unnamed flags type") + } + TypeDefKind::Enum(_) => { + bail!("resolve has unnamed enum type") + } + TypeDefKind::Variant(_) => { + bail!("resolve has unnamed variant type") + } + TypeDefKind::List(ty) => { + self.output.ty("list", TypeKind::BuiltIn); + self.output.generic_args_start(); + self.print_type_name(resolve, ty)?; + self.output.generic_args_end(); + } + TypeDefKind::Map(key_ty, value_ty) => { + self.output.ty("map", TypeKind::BuiltIn); + self.output.generic_args_start(); + self.print_type_name(resolve, key_ty)?; + self.output.str(", "); + self.print_type_name(resolve, value_ty)?; + self.output.generic_args_end(); + } + TypeDefKind::FixedLengthList(ty, size) => { + self.output.ty("list", TypeKind::BuiltIn); + self.output.generic_args_start(); + self.print_type_name(resolve, ty)?; + self.output.push_str(&format!(", {}", *size)); + self.output.generic_args_end(); + } + TypeDefKind::Type(ty) => self.print_type_name(resolve, ty)?, + TypeDefKind::Future(ty) => { + if let Some(ty) = ty { + self.output.push_str("future<"); + self.print_type_name(resolve, ty)?; + self.output.push_str(">"); + } else { + self.output.push_str("future"); + } + } + TypeDefKind::Stream(ty) => { + if let Some(ty) = ty { + self.output.push_str("stream<"); + self.print_type_name(resolve, ty)?; + self.output.push_str(">"); + } else { + self.output.push_str("stream"); + } + } + TypeDefKind::Unknown => unreachable!(), + } + } + } + + Ok(()) + } + + fn print_handle_type( + &mut self, + resolve: &Resolve, + handle: &Handle, + force_handle_type_printed: bool, + ) -> Result<()> { + match handle { + Handle::Own(ty) => { + let ty = &resolve.types[*ty]; + if force_handle_type_printed { + self.output.ty("own", TypeKind::BuiltIn); + self.output.generic_args_start(); + } + self.print_name_type( + ty.name + .as_ref() + .ok_or_else(|| anyhow!("unnamed resource type"))?, + TypeKind::Resource, + ); + if force_handle_type_printed { + self.output.generic_args_end(); + } + } + + Handle::Borrow(ty) => { + self.output.ty("borrow", TypeKind::BuiltIn); + self.output.generic_args_start(); + let ty = &resolve.types[*ty]; + self.print_name_type( + ty.name + .as_ref() + .ok_or_else(|| anyhow!("unnamed resource type"))?, + TypeKind::Resource, + ); + self.output.generic_args_end(); + } + } + + Ok(()) + } + + fn print_tuple_type(&mut self, resolve: &Resolve, tuple: &Tuple) -> Result<()> { + self.output.ty("tuple", TypeKind::BuiltIn); + self.output.generic_args_start(); + for (i, ty) in tuple.types.iter().enumerate() { + if i > 0 { + self.output.str(", "); + } + self.print_type_name(resolve, ty)?; + } + self.output.generic_args_end(); + + Ok(()) + } + + fn print_option_type(&mut self, resolve: &Resolve, payload: &Type) -> Result<()> { + self.output.ty("option", TypeKind::BuiltIn); + self.output.generic_args_start(); + self.print_type_name(resolve, payload)?; + self.output.generic_args_end(); + Ok(()) + } + + fn print_result_type(&mut self, resolve: &Resolve, result: &Result_) -> Result<()> { + match result { + Result_ { + ok: Some(ok), + err: Some(err), + } => { + self.output.ty("result", TypeKind::BuiltIn); + self.output.generic_args_start(); + self.print_type_name(resolve, ok)?; + self.output.str(", "); + self.print_type_name(resolve, err)?; + self.output.generic_args_end(); + } + Result_ { + ok: None, + err: Some(err), + } => { + self.output.ty("result", TypeKind::BuiltIn); + self.output.generic_args_start(); + self.output.str("_, "); + self.print_type_name(resolve, err)?; + self.output.generic_args_end(); + } + Result_ { + ok: Some(ok), + err: None, + } => { + self.output.ty("result", TypeKind::BuiltIn); + self.output.generic_args_start(); + self.print_type_name(resolve, ok)?; + self.output.generic_args_end(); + } + Result_ { + ok: None, + err: None, + } => { + self.output.ty("result", TypeKind::BuiltIn); + } + } + Ok(()) + } + + fn declare_type(&mut self, resolve: &Resolve, ty: &Type) -> Result<()> { + match ty { + Type::Bool + | Type::U8 + | Type::U16 + | Type::U32 + | Type::U64 + | Type::S8 + | Type::S16 + | Type::S32 + | Type::S64 + | Type::F32 + | Type::F64 + | Type::Char + | Type::String + | Type::ErrorContext => return Ok(()), + + Type::Id(id) => { + let ty = &resolve.types[*id]; + match &ty.kind { + TypeDefKind::Handle(h) => { + self.declare_handle(resolve, ty.name.as_deref(), h)? + } + TypeDefKind::Resource => panic!("resources should be processed separately"), + TypeDefKind::Record(r) => { + self.declare_record(resolve, ty.name.as_deref(), r)? + } + TypeDefKind::Tuple(t) => self.declare_tuple(resolve, ty.name.as_deref(), t)?, + TypeDefKind::Flags(f) => self.declare_flags(ty.name.as_deref(), f)?, + TypeDefKind::Variant(v) => { + self.declare_variant(resolve, ty.name.as_deref(), v)? + } + TypeDefKind::Option(t) => { + self.declare_option(resolve, ty.name.as_deref(), t)? + } + TypeDefKind::Result(r) => { + self.declare_result(resolve, ty.name.as_deref(), r)? + } + TypeDefKind::Enum(e) => self.declare_enum(ty.name.as_deref(), e)?, + TypeDefKind::List(inner) => { + self.declare_list(resolve, ty.name.as_deref(), inner)? + } + TypeDefKind::Map(key, value) => { + self.declare_map(resolve, ty.name.as_deref(), key, value)? + } + TypeDefKind::FixedLengthList(inner, size) => { + self.declare_fixed_length_list(resolve, ty.name.as_deref(), inner, *size)? + } + TypeDefKind::Type(inner) => match ty.name.as_deref() { + Some(name) => { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::TypeName); + self.output.str(" = "); + self.print_type_name(resolve, inner)?; + self.output.semicolon(); + } + None => bail!("unnamed type in document"), + }, + TypeDefKind::Future(inner) => { + self.declare_future(resolve, ty.name.as_deref(), inner.as_ref())? + } + TypeDefKind::Stream(inner) => { + self.declare_stream(resolve, ty.name.as_deref(), inner.as_ref())? + } + TypeDefKind::Unknown => unreachable!(), + } + } + } + Ok(()) + } + + fn declare_handle( + &mut self, + resolve: &Resolve, + name: Option<&str>, + handle: &Handle, + ) -> Result<()> { + match name { + Some(name) => { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Resource); + self.output.str(" = "); + // Note that the `true` here forces owned handles to be printed + // as `own`. The purpose of this is because `type a = b`, if + // `b` is a resource, is encoded differently as `type a = + // own`. By forcing a handle to be printed here it's staying + // true to what's in the WIT document. + self.print_handle_type(resolve, handle, true)?; + self.output.semicolon(); + + Ok(()) + } + None => bail!("document has unnamed handle type"), + } + } + + fn declare_record( + &mut self, + resolve: &Resolve, + name: Option<&str>, + record: &Record, + ) -> Result<()> { + match name { + Some(name) => { + self.output.keyword("record"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Record); + self.output.indent_start(); + for field in &record.fields { + self.print_docs(&field.docs); + self.print_name_param(&field.name); + self.output.str(": "); + self.print_type_name(resolve, &field.ty)?; + self.output.str(","); + self.output.newline(); + } + self.output.indent_end(); + Ok(()) + } + None => bail!("document has unnamed record type"), + } + } + + fn declare_tuple( + &mut self, + resolve: &Resolve, + name: Option<&str>, + tuple: &Tuple, + ) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Tuple); + self.output.str(" = "); + self.print_tuple_type(resolve, tuple)?; + self.output.semicolon(); + } + Ok(()) + } + + fn declare_flags(&mut self, name: Option<&str>, flags: &Flags) -> Result<()> { + match name { + Some(name) => { + self.output.keyword("flags"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Flags); + self.output.indent_start(); + for flag in &flags.flags { + self.print_docs(&flag.docs); + self.print_name_case(&flag.name); + self.output.str(","); + self.output.newline(); + } + self.output.indent_end(); + } + None => bail!("document has unnamed flags type"), + } + Ok(()) + } + + fn declare_variant( + &mut self, + resolve: &Resolve, + name: Option<&str>, + variant: &Variant, + ) -> Result<()> { + let name = match name { + Some(name) => name, + None => bail!("document has unnamed variant type"), + }; + self.output.keyword("variant"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Variant); + self.output.indent_start(); + for case in &variant.cases { + self.print_docs(&case.docs); + self.print_name_case(&case.name); + if let Some(ty) = case.ty { + self.output.str("("); + self.print_type_name(resolve, &ty)?; + self.output.str(")"); + } + self.output.str(","); + self.output.newline(); + } + self.output.indent_end(); + Ok(()) + } + + fn declare_option( + &mut self, + resolve: &Resolve, + name: Option<&str>, + payload: &Type, + ) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Option); + self.output.str(" = "); + self.print_option_type(resolve, payload)?; + self.output.semicolon(); + } + Ok(()) + } + + fn declare_result( + &mut self, + resolve: &Resolve, + name: Option<&str>, + result: &Result_, + ) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Result); + self.output.str(" = "); + self.print_result_type(resolve, result)?; + self.output.semicolon(); + } + Ok(()) + } + + fn declare_enum(&mut self, name: Option<&str>, enum_: &Enum) -> Result<()> { + let name = match name { + Some(name) => name, + None => bail!("document has unnamed enum type"), + }; + self.output.keyword("enum"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Enum); + self.output.indent_start(); + for case in &enum_.cases { + self.print_docs(&case.docs); + self.print_name_case(&case.name); + self.output.str(","); + self.output.newline(); + } + self.output.indent_end(); + Ok(()) + } + + fn declare_list(&mut self, resolve: &Resolve, name: Option<&str>, ty: &Type) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::List); + self.output.str(" = "); + self.output.ty("list", TypeKind::BuiltIn); + self.output.str("<"); + self.print_type_name(resolve, ty)?; + self.output.str(">"); + self.output.semicolon(); + return Ok(()); + } + + Ok(()) + } + + fn declare_map( + &mut self, + resolve: &Resolve, + name: Option<&str>, + key_ty: &Type, + value_ty: &Type, + ) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Map); + self.output.str(" = "); + self.output.ty("map", TypeKind::BuiltIn); + self.output.str("<"); + self.print_type_name(resolve, key_ty)?; + self.output.str(", "); + self.print_type_name(resolve, value_ty)?; + self.output.str(">"); + self.output.semicolon(); + return Ok(()); + } + + Ok(()) + } + + fn declare_fixed_length_list( + &mut self, + resolve: &Resolve, + name: Option<&str>, + ty: &Type, + elements: u32, + ) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::List); + self.output.str(" = "); + self.output.ty("list", TypeKind::BuiltIn); + self.output.str("<"); + self.print_type_name(resolve, ty)?; + self.output.str(&format!(", {elements}")); + self.output.str(">"); + self.output.semicolon(); + return Ok(()); + } + + Ok(()) + } + + fn declare_stream( + &mut self, + resolve: &Resolve, + name: Option<&str>, + ty: Option<&Type>, + ) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Stream); + self.output.str(" = "); + self.output.ty("stream", TypeKind::BuiltIn); + if let Some(ty) = ty { + self.output.str("<"); + self.print_type_name(resolve, ty)?; + self.output.str(">"); + } + self.output.semicolon(); + } + + Ok(()) + } + + fn declare_future( + &mut self, + resolve: &Resolve, + name: Option<&str>, + ty: Option<&Type>, + ) -> Result<()> { + if let Some(name) = name { + self.output.keyword("type"); + self.output.str(" "); + self.print_name_type(name, TypeKind::Future); + self.output.str(" = "); + self.output.ty("future", TypeKind::BuiltIn); + if let Some(ty) = ty { + self.output.str("<"); + self.print_type_name(resolve, ty)?; + self.output.str(">"); + } + self.output.semicolon(); + } + + Ok(()) + } + + fn escape_name(name: &str) -> Cow<'_, str> { + if is_keyword(name) { + Cow::Owned(format!("%{name}")) + } else { + Cow::Borrowed(name) + } + } + + fn print_name_type(&mut self, name: &str, kind: TypeKind) { + self.output.ty(Self::escape_name(name).deref(), kind); + } + + fn print_name_param(&mut self, name: &str) { + self.output.param(Self::escape_name(name).deref()); + } + + fn print_name_case(&mut self, name: &str) { + self.output.case(Self::escape_name(name).deref()); + } + + fn print_docs(&mut self, docs: &Docs) { + if self.emit_docs { + if let Some(contents) = &docs.contents { + for line in contents.lines() { + self.output.doc(line); + } + } + } + } + + fn print_stability(&mut self, stability: &Stability) { + match stability { + Stability::Unknown => {} + Stability::Stable { since, deprecated } => { + self.output.keyword("@since"); + self.output.str("("); + self.output.keyword("version"); + self.output.str(" = "); + self.print_name_type(&since.to_string(), TypeKind::VersionAnnotation); + self.output.str(")"); + self.output.newline(); + if let Some(version) = deprecated { + self.output.keyword("@deprecated"); + self.output.str("("); + self.output.keyword("version"); + self.output.str(" = "); + self.print_name_type(&version.to_string(), TypeKind::VersionAnnotation); + self.output.str(")"); + self.output.newline(); + } + } + Stability::Unstable { + feature, + deprecated, + } => { + self.output.keyword("@unstable"); + self.output.str("("); + self.output.keyword("feature"); + self.output.str(" = "); + self.output.str(feature); + self.output.str(")"); + self.output.newline(); + if let Some(version) = deprecated { + self.output.keyword("@deprecated"); + self.output.str("("); + self.output.keyword("version"); + self.output.str(" = "); + self.print_name_type(&version.to_string(), TypeKind::VersionAnnotation); + self.output.str(")"); + self.output.newline(); + } + } + } + } + + fn print_external_id(&mut self, id: Option<&str>) { + let Some(id) = id else { + return; + }; + self.output.keyword("@external-id"); + self.output.str("(\""); + let mut buf = [0; 4]; + for c in id.chars() { + if c.is_ascii_alphanumeric() + || c == '-' + || c == '_' + || c == '.' + || c == '/' + || c == ':' + || c == ' ' + { + self.output.push_str(c.encode_utf8(&mut buf)); + continue; + } + match c { + '\\' => self.output.push_str("\\\\"), + '"' => self.output.push_str("\\\""), + '\n' => self.output.push_str("\\n"), + '\r' => self.output.push_str("\\r"), + '\t' => self.output.push_str("\\t"), + _ => { + self.output.push_str(&format!("\\u{{{:x}}}", c as u32)); + } + } + } + self.output.str("\")"); + self.output.newline(); + } +} + +fn is_keyword(name: &str) -> bool { + matches!( + name, + "use" + | "type" + | "func" + | "u8" + | "u16" + | "u32" + | "u64" + | "s8" + | "s16" + | "s32" + | "s64" + | "f32" + | "f64" + | "float32" + | "float64" + | "char" + | "resource" + | "record" + | "flags" + | "variant" + | "enum" + | "bool" + | "string" + | "option" + | "result" + | "future" + | "stream" + | "list" + | "own" + | "borrow" + | "_" + | "as" + | "from" + | "static" + | "interface" + | "tuple" + | "world" + | "import" + | "export" + | "package" + | "with" + | "include" + | "constructor" + | "error-context" + | "async" + | "map" + ) +} + +/// Trait defining visitor methods driven by [`WitPrinter`](WitPrinter). +/// +/// Some methods in this trait have default implementations. These default +/// implementations may rely on helper functions that are not +/// invoked directly by `WitPrinter`. +pub trait Output { + /// Push a string slice into a buffer or an output. + /// + /// Parameter `src` can contain punctuation characters, and must be escaped + /// when outputting to languages like HTML. + /// Helper function used exclusively by the default implementations of trait methods. + /// This function is not called directly by `WitPrinter`. + /// When overriding all the trait methods, users do not need to handle this function. + fn push_str(&mut self, src: &str); + + /// Set the appropriate indentation. + /// + /// Helper function used exclusively by the default implementations of trait methods. + /// This function is not called directly by `WitPrinter`. + /// When overriding all the trait methods, users do not need to handle this function. + fn indent_if_needed(&mut self) -> bool; + + /// Start of indentation. In WIT this represents ` {\n`. + fn indent_start(&mut self); + + /// End of indentation. In WIT this represents `}\n`. + fn indent_end(&mut self); + + /// This method is designed to be used only by the default methods of this trait. + /// Called only from the default implementation functions of this trait. + fn indent_and_print(&mut self, src: &str) { + assert!(!src.contains('\n')); + let indented = self.indent_if_needed(); + if indented && src.starts_with(' ') { + panic!("cannot add a space at the beginning of a line"); + } + self.push_str(src); + } + + /// A newline is added. + fn newline(&mut self); + + /// A keyword is added. Keywords are hardcoded strings from `[a-z]`, but can start with `@` + /// when printing a [Feature Gate](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#feature-gates) + fn keyword(&mut self, src: &str) { + self.indent_and_print(src); + } + + /// A type is added. + fn ty(&mut self, src: &str, _kind: TypeKind) { + self.indent_and_print(src); + } + + /// A parameter name of a function, record or a named return is added. + fn param(&mut self, src: &str) { + self.indent_and_print(src); + } + + /// A case belonging to a variant, enum or flags is added. + fn case(&mut self, src: &str) { + self.indent_and_print(src); + } + + /// Generic argument section starts. In WIT this represents the `<` character. + fn generic_args_start(&mut self) { + assert!( + !self.indent_if_needed(), + "`generic_args_start` is never called after newline" + ); + self.push_str("<"); + } + + /// Generic argument section ends. In WIT this represents the '>' character. + fn generic_args_end(&mut self) { + assert!( + !self.indent_if_needed(), + "`generic_args_end` is never called after newline" + ); + self.push_str(">"); + } + + /// Called when a single documentation line is added. + /// The `doc` parameter starts with `///` omitted, and can be an empty string. + fn doc(&mut self, doc: &str) { + assert!(!doc.contains('\n')); + self.indent_if_needed(); + self.push_str("///"); + if !doc.is_empty() { + self.push_str(" "); + self.push_str(doc); + } + self.newline(); + } + + /// A semicolon is added. + fn semicolon(&mut self) { + assert!( + !self.indent_if_needed(), + "`semicolon` is never called after newline" + ); + self.push_str(";"); + self.newline(); + } + + /// Any string that does not have a specialized function is added. + /// Parameter `src` can contain punctuation characters, and must be escaped + /// when outputting to languages like HTML. + fn str(&mut self, src: &str) { + self.indent_and_print(src); + } +} + +/// Represents the different kinds of types that can be encountered while +/// visiting a WIT file. +/// +/// Each variant refers to the name of the respective element (e.g., function, type, or namespace), +/// not the entire declaration. +#[non_exhaustive] +#[derive(Clone, Copy, Debug)] +pub enum TypeKind { + /// A built-in type, such as "list" or "option". + BuiltIn, + /// An enumeration type name. + Enum, + /// An error-context type name. + ErrorContext, + /// A flags type name. + Flags, + /// A freestanding function name, not associated with any specific type or namespace. + /// For example, "myfunc" in `myfunc: func() -> string;`. + FunctionFreestanding, + /// A method, associated with a resource. + FunctionMethod, + /// A static function, associated with a resource. + FunctionStatic, + /// A future type name. + Future, + /// An interface declaration name. + InterfaceDeclaration, + /// An interface name when printing a path, for example in `use`. + InterfacePath, + /// A list type name. + List, + /// A map type name. + Map, + /// A namespace declaration. + NamespaceDeclaration, + /// A namespace when printing a path, for example in `use`. + NamespacePath, + /// An option type name. + Option, + /// A package name declaration. + PackageNameDeclaration, + /// A package name when printing a path, for example in `use`. + PackageNamePath, + /// A record type name. + Record, + /// A resource type name. + Resource, + /// A result type name. + Result, + /// A stream type name. + Stream, + /// A tuple type name. + Tuple, + /// A type alias. + TypeAlias, + /// An imported type name. + TypeImport, + /// A user-defined type name. + TypeName, + /// A variant type name. + Variant, + /// A version declaration. + VersionDeclaration, + /// A version when printing a path, for example in `use`. + VersionPath, + /// A version when printing stability annotations, for example in `@since` + VersionAnnotation, + /// A world declaration name. + WorldDeclaration, + /// A fallback for types that do not fit into any other category. + Other, +} + +/// Helper structure to help maintain an indentation level when printing source, +/// modeled after the support in `wit-bindgen-core`. Indentation is set to two spaces. +#[derive(Default)] +pub struct OutputToString { + indent: usize, + output: String, + // set to true after newline, then to false after first item is indented. + needs_indent: bool, +} + +impl Output for OutputToString { + fn push_str(&mut self, src: &str) { + self.output.push_str(src); + } + + fn indent_if_needed(&mut self) -> bool { + if self.needs_indent { + for _ in 0..self.indent { + // Indenting by two spaces. + self.output.push_str(" "); + } + self.needs_indent = false; + true + } else { + false + } + } + + fn indent_start(&mut self) { + assert!( + !self.needs_indent, + "`indent_start` is never called after newline" + ); + self.output.push_str(" {"); + self.indent += 1; + self.newline(); + } + + fn indent_end(&mut self) { + // Note that a `saturating_sub` is used here to prevent a panic + // here in the case of invalid code being generated in debug + // mode. It's typically easier to debug those issues through + // looking at the source code rather than getting a panic. + self.indent = self.indent.saturating_sub(1); + self.indent_if_needed(); + self.output.push('}'); + self.newline(); + } + + fn newline(&mut self) { + self.output.push('\n'); + self.needs_indent = true; + } +} + +impl From for String { + fn from(output: OutputToString) -> String { + output.output + } +} + +impl Display for OutputToString { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.output.fmt(f) + } +} diff --git a/vendor/wit-component/src/semver_check.rs b/vendor/wit-component/src/semver_check.rs new file mode 100644 index 00000000..8fb4cb1c --- /dev/null +++ b/vendor/wit-component/src/semver_check.rs @@ -0,0 +1,113 @@ +use crate::{ + ComponentEncoder, StringEncoding, dummy_module, embed_component_metadata, + encoding::encode_world, +}; +use anyhow::{Context, Result, bail}; +use wasm_encoder::{ComponentBuilder, ComponentExportKind, ComponentTypeRef}; +use wasmparser::Validator; +use wit_parser::{ManglingAndAbi, Resolve, WorldId}; + +/// Tests whether `new` is a semver-compatible upgrade from the world `prev`. +/// +/// This function is will test whether a WIT-level semver-compatible predicate +/// holds. Internally this will ignore all versions associated with packages and +/// will instead test for structural equality between types and such. For +/// example `new` is allowed to have more imports and fewer exports, but types +/// and such must have the exact same structure otherwise (e.g. function params, +/// record fields, etc). +// +// NB: the general implementation strategy here is similar to the `targets` +// function where components are synthesized and we effectively rely on +// wasmparser to figure out everything for us. Specifically what happens is: +// +// 1. A dummy component representing `prev` is created. +// 2. A component importing a component of shape `new` is created. +// 3. The component from (2) is instantiated with the component from (1). +// +// If that all type-checks and is valid then the semver compatible predicate +// holds. Otherwise something has gone wrong. +// +// Note that this does not produce great error messages, so this implementation +// likely wants to be improved in the future. +pub fn semver_check(mut resolve: Resolve, prev: WorldId, new: WorldId) -> Result<()> { + // First up clear out all version information. This is required to ensure + // that the strings line up for wasmparser's validation which does exact + // string matching. + // + // This can leave `resolve` in a weird state which is why this function + // takes ownership of `resolve`. Specifically the internal maps for package + // names won't be updated and additionally this could leave two packages + // with the same name (e.g. no version) which would be a bit odd. + // + // NB: this will probably cause confusing errors below if a world imports + // two versions of a package's interfaces. I think that'll result in weird + // wasmparser validation errors as there would be two imports of the same + // name for example. + for (_id, pkg) in resolve.packages.iter_mut() { + pkg.name.version = None; + } + + let old_pkg_id = resolve.worlds[prev] + .package + .context("old world not in named package")?; + let old_pkg_name = &resolve.packages[old_pkg_id].name; + let new_pkg_id = resolve.worlds[new] + .package + .context("new world not in named package")?; + let new_pkg_name = &resolve.packages[new_pkg_id].name; + if old_pkg_name != new_pkg_name { + bail!( + "the old world is in package {old_pkg_name}, which is not the same as the new world, which is in package {new_pkg_name}", + ) + } + + // Component that will be validated at the end. + let mut root_component = ComponentBuilder::default(); + + // (1) above - create a dummy component which has the shape of `prev`. + let mut prev_as_module = dummy_module(&resolve, prev, ManglingAndAbi::Standard32); + embed_component_metadata(&mut prev_as_module, &resolve, prev, StringEncoding::UTF8) + .context("failed to embed component metadata")?; + let prev_as_component = ComponentEncoder::default() + .module(&prev_as_module) + .context("failed to register previous world encoded as a module")? + .encode() + .context("failed to encode previous world as a component")?; + let component_to_test_idx = root_component.component_raw(None, &prev_as_component); + + // (2) above - create a component which imports a component of the shape of + // `new`. + let test_component_idx = { + let component_ty = + encode_world(&resolve, new).context("failed to encode the new world as a type")?; + let mut component = ComponentBuilder::default(); + let component_ty_idx = component.type_component(None, &component_ty); + component.import( + &resolve.worlds[new].name, + ComponentTypeRef::Component(component_ty_idx), + ); + root_component.component(None, component) + }; + + // (3) Instantiate the component from (2) with the component to test from (1). + root_component.instantiate( + None, + test_component_idx, + [( + resolve.worlds[new].name.clone(), + ComponentExportKind::Component, + component_to_test_idx, + )], + ); + let bytes = root_component.finish(); + + // The final step is validating that this component is indeed valid. If any + // error message is produced here an attempt is made to make it more + // understandable but there's only but so good these errors can be with this + // strategy. + Validator::new() + .validate_all(&bytes) + .context("new world is not semver-compatible with the previous world")?; + + Ok(()) +} diff --git a/vendor/wit-component/src/targets.rs b/vendor/wit-component/src/targets.rs new file mode 100644 index 00000000..4212b018 --- /dev/null +++ b/vendor/wit-component/src/targets.rs @@ -0,0 +1,44 @@ +use crate::encoding::encode_world; +use anyhow::{Context, Result}; +use wasm_encoder::{ComponentBuilder, ComponentExportKind, ComponentTypeRef}; +use wasmparser::{Validator, WasmFeatures}; +use wit_parser::{Resolve, WorldId}; + +/// This function checks whether `component_to_test` correctly conforms to the world specified. +/// It does so by instantiating a generated component that imports a component instance with +/// the component type as described by the "target" world. +pub fn targets(resolve: &Resolve, world: WorldId, component_to_test: &[u8]) -> Result<()> { + let mut root_component = ComponentBuilder::default(); + + // (1) Embed the component to test. + let component_to_test_idx = root_component.component_raw(None, component_to_test); + + // (2) Encode the world to a component type and embed a new component which + // imports the encoded component type. + let test_component_idx = { + let component_ty = encode_world(resolve, world)?; + let mut component = ComponentBuilder::default(); + let component_ty_idx = component.type_component(None, &component_ty); + component.import( + &resolve.worlds[world].name, + ComponentTypeRef::Component(component_ty_idx), + ); + root_component.component(None, component) + }; + + // (3) Instantiate the component from (2) with the component to test from (1). + let args: Vec<(String, ComponentExportKind, u32)> = vec![( + resolve.worlds[world].name.clone(), + ComponentExportKind::Component, + component_to_test_idx, + )]; + root_component.instantiate(None, test_component_idx, args); + + let bytes = root_component.finish(); + + Validator::new_with_features(WasmFeatures::all()) + .validate_all(&bytes) + .context("failed to validate encoded bytes")?; + + Ok(()) +} diff --git a/vendor/wit-component/src/validation.rs b/vendor/wit-component/src/validation.rs new file mode 100644 index 00000000..0b611b87 --- /dev/null +++ b/vendor/wit-component/src/validation.rs @@ -0,0 +1,2868 @@ +use crate::encoding::{Instance, Item, LibraryInfo, MainOrAdapter, ModuleImportMap}; +use crate::{ComponentEncoder, StringEncoding}; +use anyhow::{Context, Result, anyhow, bail}; +use indexmap::{IndexMap, IndexSet, map::Entry}; +use std::fmt; +use std::hash::Hash; +use std::mem; +use wasm_encoder::ExportKind; +use wasmparser::names::{ComponentName, ComponentNameKind}; +use wasmparser::{ + Encoding, ExternalKind, FuncType, MemoryType, Parser, Payload, TypeRef, ValType, ValidPayload, + Validator, WasmFeatures, types::TypesRef, +}; +use wit_parser::{ + Function, InterfaceId, PackageName, Resolve, Type, TypeDefKind, TypeId, World, WorldId, + WorldItem, WorldKey, + abi::{AbiVariant, WasmSignature, WasmType}, +}; + +fn wasm_sig_to_func_type(signature: WasmSignature) -> FuncType { + fn from_wasm_type(ty: &WasmType) -> ValType { + match ty { + WasmType::I32 => ValType::I32, + WasmType::I64 => ValType::I64, + WasmType::F32 => ValType::F32, + WasmType::F64 => ValType::F64, + WasmType::Pointer => ValType::I32, + WasmType::PointerOrI64 => ValType::I64, + WasmType::Length => ValType::I32, + } + } + + FuncType::new( + signature.params.iter().map(from_wasm_type), + signature.results.iter().map(from_wasm_type), + ) +} + +/// Metadata about a validated module and what was found internally. +/// +/// This structure houses information about `imports` and `exports` to the +/// module. Each of these specialized types contains "connection" information +/// between a module's imports/exports and the WIT or component-level constructs +/// they correspond to. + +#[derive(Default)] +pub struct ValidatedModule { + /// Information about a module's imports. + pub imports: ImportMap, + + /// Information about a module's exports. + pub exports: ExportMap, +} + +impl ValidatedModule { + fn new( + encoder: &ComponentEncoder, + bytes: &[u8], + exports: &IndexSet, + import_map: Option<&ModuleImportMap>, + info: Option<&LibraryInfo>, + ) -> Result { + let mut validator = Validator::new_with_features(WasmFeatures::all()); + let mut ret = ValidatedModule::default(); + + for payload in Parser::new(0).parse_all(bytes) { + let payload = payload?; + if let ValidPayload::End(_) = validator.payload(&payload)? { + break; + } + + let types = validator.types(0).unwrap(); + + match payload { + Payload::Version { encoding, .. } if encoding != Encoding::Module => { + bail!("data is not a WebAssembly module"); + } + Payload::ImportSection(s) => { + for import in s.into_imports() { + let import = import?; + ret.imports.add(import, encoder, import_map, info, types)?; + } + } + Payload::ExportSection(s) => { + for export in s { + let export = export?; + ret.exports.add(export, encoder, &exports, types)?; + } + } + _ => continue, + } + } + + ret.exports.validate(encoder, exports)?; + + Ok(ret) + } +} + +/// Metadata information about a module's imports. +/// +/// This structure maintains the connection between component model "things" and +/// core wasm "things" by ensuring that all imports to the core wasm module are +/// classified by the `Import` enumeration. +#[derive(Default)] +pub struct ImportMap { + /// The first level of the map here is the module namespace of the import + /// and the second level of the map is the field namespace. The item is then + /// how the import is satisfied. + names: IndexMap, + + /// Cache for the last-inserted `MainModuleMemory` into `names` + imported_memory: Option, +} + +pub enum ImportInstance { + /// This import is satisfied by an entire instance of another + /// adapter/module. + Whole(MainOrAdapter), + + /// This import is satisfied by filling out each name possibly differently. + Names(IndexMap), +} + +/// Represents metadata about a `stream` or `future` type for a specific +/// payload type `T`. +/// +/// Currently, the name mangling scheme we use to represent `stream` and +/// `future` intrinsics as core module function imports refers to a specific +/// `stream` or `future` type by naming an imported or exported component +/// function which has that type as a parameter or return type (where the +/// specific type is referred to using an ordinal numbering scheme). Not only +/// does this approach unambiguously indicate the type of interest, but it +/// allows us to reuse the `realloc`, string encoding, memory, etc. used by that +/// function when emitting intrinsic declarations. +/// +/// TODO: Rather than reusing the same canon opts as the function in which the +/// type appears, consider encoding them in the name mangling stream on an +/// individual basis, similar to how we encode `error-context.*` built-in +/// imports. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub struct PayloadInfo { + /// The original, mangled import name used to import this built-in + /// (currently used only for hashing and debugging). + pub name: String, + /// The resolved type id for the `stream` or `future` type of interest. + /// + /// If `Unit{Future,Stream}` this means that it's a "unit" payload or has no associated + /// type being sent. + pub ty: PayloadType, + /// The world key representing the import or export context of `function`. + pub key: WorldKey, + /// The interface that `function` was imported from or exported in, if any. + pub interface: Option, + /// Whether `function` is being imported or exported. + /// + /// This may affect how we emit the declaration of the built-in, e.g. if the + /// payload type is an exported resource. + pub imported: bool, +} + +/// The type of future/stream referenced by a `PayloadInfo` +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub enum PayloadType { + /// This is a future or stream located in a `Resolve` where `id` points to + /// either of `TypeDefKind::{Future, Stream}`. + Type { + id: TypeId, + /// The component-level function import or export where the type + /// appeared as a parameter or result type. + function: String, + }, + /// This is a `future` (no type) + UnitFuture, + /// This is a `stream` (no type) + UnitStream, +} + +impl PayloadInfo { + /// Returns the payload type that this future/stream type is using. + pub fn payload(&self, resolve: &Resolve) -> Option { + let id = match self.ty { + PayloadType::Type { id, .. } => id, + PayloadType::UnitFuture | PayloadType::UnitStream => return None, + }; + match resolve.types[id].kind { + TypeDefKind::Future(payload) | TypeDefKind::Stream(payload) => payload, + _ => unreachable!(), + } + } +} + +/// The different kinds of items that a module or an adapter can import. +/// +/// This is intended to be an exhaustive definition of what can be imported into +/// core modules within a component that wit-component supports. This doesn't +/// get down to the level of storing any idx numbers; at its most specific, it +/// gives a name. +#[derive(Debug, Clone)] +pub enum Import { + /// A top-level world function, with the name provided here, is imported + /// into the module. + WorldFunc(WorldKey, String, AbiVariant), + + /// An interface's function is imported into the module. + /// + /// The `WorldKey` here is the name of the interface in the world in + /// question. The `InterfaceId` is the interface that was imported from and + /// `String` is the WIT name of the function. + InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant), + + /// An imported resource's destructor is imported. + /// + /// The key provided indicates whether it's for the top-level types of the + /// world (`None`) or an interface (`Some` with the name of the interface). + /// The `TypeId` is what resource is being dropped. + ImportedResourceDrop(WorldKey, Option, TypeId), + + /// A `canon resource.drop` intrinsic for an exported item is being + /// imported. + /// + /// This lists the key of the interface that's exporting the resource plus + /// the id within that interface. + ExportedResourceDrop(WorldKey, TypeId), + + /// A `canon resource.new` intrinsic for an exported item is being + /// imported. + /// + /// This lists the key of the interface that's exporting the resource plus + /// the id within that interface. + ExportedResourceNew(WorldKey, TypeId), + + /// A `canon resource.rep` intrinsic for an exported item is being + /// imported. + /// + /// This lists the key of the interface that's exporting the resource plus + /// the id within that interface. + ExportedResourceRep(WorldKey, TypeId), + + /// An export of an adapter is being imported with the specified type. + /// + /// This is used for when the main module imports an adapter function. The + /// adapter name and function name match the module's own import, and the + /// type must match that listed here. + AdapterExport { + adapter: String, + func: String, + ty: FuncType, + }, + + /// An adapter is importing the memory of the main module. + /// + /// (should be combined with `MainModuleExport` below one day) + MainModuleMemory(MemoryType), + + /// An adapter is importing an arbitrary item from the main module. + MainModuleExport { name: String, kind: ExportKind }, + + /// An arbitrary item from either the main module or an adapter is being + /// imported. + /// + /// (should probably subsume `MainModule*` and maybe `AdapterExport` above + /// one day. + Item(Item), + + /// A `canon task.return` intrinsic for an exported function. + /// + /// This allows an exported function to return a value and then continue + /// running. + /// + /// As of this writing, only async-lifted exports use `task.return`, but the + /// plan is to also support it for sync-lifted exports in the future as + /// well. + ExportedTaskReturn(WorldKey, Option, Function), + + /// A `canon task.cancel` intrinsic for an exported function. + /// + /// This allows an exported function to acknowledge a `CANCELLED` event. + ExportedTaskCancel, + + /// The `context.get` intrinsic for the nth slot of storage. + ContextGet { + /// The type of the slot (`i32` or `i64`). + ty: ValType, + /// The index of the storage slot. + slot: u32, + }, + /// The `context.set` intrinsic for the nth slot of storage. + ContextSet { + /// The type of the slot (`i32` or `i64`). + ty: ValType, + /// The index of the storage slot. + slot: u32, + }, + + /// The `__wasm_get_tls_base` function that LLVM emits to read the base + /// pointer of this module's thread-local storage. + /// + /// Unlike [`Import::ContextGet`] this is not tied to a particular storage + /// mechanism: how it's satisfied depends on whether the program uses + /// cooperative threading. See + /// `EncodingState::materialize_tls_base_import` for the details. + TlsBaseGet { + /// The type of the base pointer (`i32` or `i64`). + ty: ValType, + }, + + /// The `__wasm_set_tls_base` counterpart to [`Import::TlsBaseGet`]. + TlsBaseSet { + /// The type of the base pointer (`i32` or `i64`). + ty: ValType, + }, + + /// A `canon backpressure.inc` intrinsic. + BackpressureInc, + + /// A `canon backpressure.dec` intrinsic. + BackpressureDec, + + /// A `waitable-set.new` intrinsic. + WaitableSetNew, + + /// A `canon waitable-set.wait` intrinsic. + /// + /// This allows the guest to wait for any pending calls to async-lowered + /// imports and/or `stream` and `future` operations to complete without + /// unwinding the current Wasm stack. + WaitableSetWait { cancellable: bool }, + + /// A `canon waitable.poll` intrinsic. + /// + /// This allows the guest to check whether any pending calls to + /// async-lowered imports and/or `stream` and `future` operations have + /// completed without unwinding the current Wasm stack and without blocking. + WaitableSetPoll { cancellable: bool }, + + /// A `waitable-set.drop` intrinsic. + WaitableSetDrop, + + /// A `waitable.join` intrinsic. + WaitableJoin, + + /// A `canon subtask.drop` intrinsic. + /// + /// This allows the guest to release its handle to a completed subtask. + SubtaskDrop, + + /// A `canon subtask.cancel` intrinsic. + /// + /// This allows the guest to cancel an in-progress subtask. + SubtaskCancel { async_: bool }, + + /// A `canon stream.new` intrinsic. + /// + /// This allows the guest to create a new `stream` of the specified type. + StreamNew(PayloadInfo), + + /// A `canon stream.read` intrinsic. + /// + /// This allows the guest to read the next values (if any) from the specified + /// stream. + StreamRead { async_: bool, info: PayloadInfo }, + + /// A `canon stream.write` intrinsic. + /// + /// This allows the guest to write one or more values to the specified + /// stream. + StreamWrite { async_: bool, info: PayloadInfo }, + + /// A `canon stream.cancel-read` intrinsic. + /// + /// This allows the guest to cancel a pending read it initiated earlier (but + /// which may have already partially or entirely completed). + StreamCancelRead { info: PayloadInfo, async_: bool }, + + /// A `canon stream.cancel-write` intrinsic. + /// + /// This allows the guest to cancel a pending write it initiated earlier + /// (but which may have already partially or entirely completed). + StreamCancelWrite { info: PayloadInfo, async_: bool }, + + /// A `canon stream.drop-readable` intrinsic. + /// + /// This allows the guest to drop the readable end of a `stream`. + StreamDropReadable(PayloadInfo), + + /// A `canon stream.drop-writable` intrinsic. + /// + /// This allows the guest to drop the writable end of a `stream`. + StreamDropWritable(PayloadInfo), + + /// A `canon future.new` intrinsic. + /// + /// This allows the guest to create a new `future` of the specified type. + FutureNew(PayloadInfo), + + /// A `canon future.read` intrinsic. + /// + /// This allows the guest to read the value (if any) from the specified + /// future. + FutureRead { async_: bool, info: PayloadInfo }, + + /// A `canon future.write` intrinsic. + /// + /// This allows the guest to write a value to the specified future. + FutureWrite { async_: bool, info: PayloadInfo }, + + /// A `canon future.cancel-read` intrinsic. + /// + /// This allows the guest to cancel a pending read it initiated earlier (but + /// which may have already completed). + FutureCancelRead { info: PayloadInfo, async_: bool }, + + /// A `canon future.cancel-write` intrinsic. + /// + /// This allows the guest to cancel a pending write it initiated earlier + /// (but which may have already completed). + FutureCancelWrite { info: PayloadInfo, async_: bool }, + + /// A `canon future.drop-readable` intrinsic. + /// + /// This allows the guest to drop the readable end of a `future`. + FutureDropReadable(PayloadInfo), + + /// A `canon future.drop-writable` intrinsic. + /// + /// This allows the guest to drop the writable end of a `future`. + FutureDropWritable(PayloadInfo), + + /// A `canon error-context.new` intrinsic. + /// + /// This allows the guest to create a new `error-context` instance with a + /// specified debug message. + ErrorContextNew { encoding: StringEncoding }, + + /// A `canon error-context.debug-message` intrinsic. + /// + /// This allows the guest to retrieve the debug message from a + /// `error-context` instance. Note that the content of this message might + /// not be identical to what was passed in to `error-context.new`. + ErrorContextDebugMessage { encoding: StringEncoding }, + + /// A `canon error-context.drop` intrinsic. + /// + /// This allows the guest to release its handle to the specified + /// `error-context` instance. + ErrorContextDrop, + + /// A `canon thread.index` intrinsic. + /// + /// This allows the guest to get the index of the current thread. + ThreadIndex, + + /// A `canon thread.new-indirect` intrinsic. + /// + /// This allows the guest to create a new thread running a specified function. + ThreadNewIndirect, + + /// A `canon thread.resume-later` intrinsic. + ThreadResumeLater, + + /// A `canon thread.suspend` intrinsic. + ThreadSuspend { cancellable: bool }, + + /// A `canon thread.yield` intrinsic. + ThreadYield { cancellable: bool }, + + /// A `canon thread.suspend-then-resume` intrinsic. + ThreadSuspendThenResume { cancellable: bool }, + + /// A `canon thread.yield-then-resume` intrinsic. + ThreadYieldThenResume { cancellable: bool }, + + /// A `canon thread.suspend-then-promote` intrinsic. + ThreadSuspendThenPromote { cancellable: bool }, + + /// A `canon thread.yield-then-promote` intrinsic. + ThreadYieldThenPromote { cancellable: bool }, +} + +impl ImportMap { + /// Returns the list of items that the adapter named `name` must export. + pub fn required_from_adapter(&self, name: &str) -> IndexMap { + let names = match self.names.get(name) { + Some(ImportInstance::Names(names)) => names, + _ => return IndexMap::new(), + }; + names + .iter() + .map(|(_, import)| match import { + Import::AdapterExport { ty, func, adapter } => { + assert_eq!(adapter, name); + (func.clone(), ty.clone()) + } + _ => unreachable!(), + }) + .collect() + } + + /// Returns an iterator over all individual imports registered in this map. + /// + /// Note that this doesn't iterate over the "whole instance" imports. + pub fn imports(&self) -> impl Iterator + '_ { + self.names + .iter() + .filter_map(|(module, m)| match m { + ImportInstance::Names(names) => Some((module, names)), + ImportInstance::Whole(_) => None, + }) + .flat_map(|(module, m)| { + m.iter() + .map(move |(field, import)| (module.as_str(), field.as_str(), import)) + }) + } + + /// Returns the map for how all imports must be satisfied. + pub fn modules(&self) -> &IndexMap { + &self.names + } + + /// Returns the type of the `env::memory` import of this module, if present. + pub fn imported_memory(&self) -> Option { + self.imported_memory + } + + /// Classify an import and call `insert_import()` on it. Used during + /// validation to build up this `ImportMap`. + fn add( + &mut self, + import: wasmparser::Import<'_>, + encoder: &ComponentEncoder, + import_map: Option<&ModuleImportMap>, + library_info: Option<&LibraryInfo>, + types: TypesRef<'_>, + ) -> Result<()> { + if self.classify_import_with_library(import, library_info)? { + return Ok(()); + } + let mut import_to_classify = import; + if let Some(map) = import_map { + if let Some(original_name) = map.original_name(&import) { + import_to_classify.name = original_name; + } + } + let item = self + .classify(import_to_classify, encoder, types) + .with_context(|| { + format!( + "failed to resolve import `{}::{}`", + import.module, import.name, + ) + })?; + self.insert_import(import, item) + } + + /// Determines what kind of thing is being imported: maps it from the + /// module/name/type triple in the raw wasm module to an enum. + /// + /// Handles a few special cases, then delegates to + /// `classify_component_model_import()`. + fn classify( + &self, + import: wasmparser::Import<'_>, + encoder: &ComponentEncoder, + types: TypesRef<'_>, + ) -> Result { + // Special-case the main module's memory imported into adapters which + // currently with `wasm-ld` is not easily configurable. + if import.module == "env" && import.name == "memory" { + if let TypeRef::Memory(ty) = import.ty { + return Ok(Import::MainModuleMemory(ty)); + } + } + + // Special-case imports from the main module into adapters. + if import.module == "__main_module__" { + return Ok(Import::MainModuleExport { + name: import.name.to_string(), + kind: match import.ty { + TypeRef::Func(_) => ExportKind::Func, + TypeRef::Table(_) => ExportKind::Table, + TypeRef::Memory(_) => ExportKind::Memory, + TypeRef::Global(_) => ExportKind::Global, + TypeRef::Tag(_) => ExportKind::Tag, + TypeRef::FuncExact(_) => bail!("Unexpected func_exact export"), + }, + }); + } + + let ty_index = match import.ty { + TypeRef::Func(ty) => ty, + _ => bail!("module is only allowed to import functions"), + }; + let ty = types[types.core_type_at_in_module(ty_index)].unwrap_func(); + + // Handle main module imports that match known adapters and set it up as + // an import of an adapter export. + if encoder.adapters.contains_key(import.module) { + return Ok(Import::AdapterExport { + adapter: import.module.to_string(), + func: import.name.to_string(), + ty: ty.clone(), + }); + } + + let (module, names) = match import.module.strip_prefix("cm32p2") { + Some(suffix) => (suffix, STANDARD), + None if encoder.reject_legacy_names => (import.module, STANDARD), + None => (import.module, LEGACY), + }; + self.classify_component_model_import(module, import.name, encoder, ty, names) + } + + /// Attempts to classify the import `{module}::{name}` with the rules + /// specified in WebAssembly/component-model#378 + fn classify_component_model_import( + &self, + module: &str, + name: &str, + encoder: &ComponentEncoder, + ty: &FuncType, + names: &dyn NameMangling, + ) -> Result { + let resolve = &encoder.metadata.resolve; + let world_id = encoder.metadata.world; + let world = &resolve.worlds[world_id]; + + if module == names.import_root() { + if names.error_context_drop(name) { + let expected = FuncType::new([ValType::I32], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ErrorContextDrop); + } + + if names.backpressure_inc(name) { + let expected = FuncType::new([], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::BackpressureInc); + } + + if names.backpressure_dec(name) { + let expected = FuncType::new([], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::BackpressureDec); + } + + if names.waitable_set_new(name) { + let expected = FuncType::new([], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::WaitableSetNew); + } + + if let Some((info, result_ty)) = names.waitable_set_wait(name) { + let expected = FuncType::new([ValType::I32, result_ty], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::WaitableSetWait { + cancellable: info.cancellable, + }); + } + + if let Some((info, result_ty)) = names.waitable_set_poll(name) { + let expected = FuncType::new([ValType::I32, result_ty], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::WaitableSetPoll { + cancellable: info.cancellable, + }); + } + + if names.waitable_set_drop(name) { + let expected = FuncType::new([ValType::I32], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::WaitableSetDrop); + } + + if names.waitable_join(name) { + let expected = FuncType::new([ValType::I32; 2], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::WaitableJoin); + } + + if names.subtask_drop(name) { + let expected = FuncType::new([ValType::I32], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::SubtaskDrop); + } + + if let Some(info) = names.subtask_cancel(name) { + let expected = FuncType::new([ValType::I32], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::SubtaskCancel { + async_: info.async_lowered, + }); + } + + if let Some(encoding) = names.error_context_new(name) { + let expected = FuncType::new([ValType::I32; 2], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ErrorContextNew { encoding }); + } + + if let Some(encoding) = names.error_context_debug_message(name) { + let expected = FuncType::new([ValType::I32; 2], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ErrorContextDebugMessage { encoding }); + } + + if let Some((slot_ty, slot)) = names.context_get(name) { + let expected = FuncType::new([], [slot_ty]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ContextGet { ty: slot_ty, slot }); + } + if let Some((slot_ty, slot)) = names.context_set(name) { + let expected = FuncType::new([slot_ty], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ContextSet { ty: slot_ty, slot }); + } + if names.thread_index(name) { + let expected = FuncType::new([], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadIndex); + } + if names.thread_new_indirect(name) { + let expected = FuncType::new([ValType::I32; 2], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadNewIndirect); + } + if names.thread_resume_later(name) { + let expected = FuncType::new([ValType::I32], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadResumeLater); + } + if let Some(info) = names.thread_suspend(name) { + let expected = FuncType::new([], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadSuspend { + cancellable: info.cancellable, + }); + } + if let Some(info) = names.thread_yield(name) { + let expected = FuncType::new([], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadYield { + cancellable: info.cancellable, + }); + } + if let Some(info) = names.thread_suspend_then_resume(name) { + let expected = FuncType::new([ValType::I32], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadSuspendThenResume { + cancellable: info.cancellable, + }); + } + if let Some(info) = names.thread_yield_then_resume(name) { + let expected = FuncType::new([ValType::I32], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadYieldThenResume { + cancellable: info.cancellable, + }); + } + if let Some(info) = names.thread_suspend_then_promote(name) { + let expected = FuncType::new([ValType::I32], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadSuspendThenPromote { + cancellable: info.cancellable, + }); + } + if let Some(info) = names.thread_yield_then_promote(name) { + let expected = FuncType::new([ValType::I32], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Import::ThreadYieldThenPromote { + cancellable: info.cancellable, + }); + } + + let (key_name, abi) = names.world_key_name_and_abi(name); + let key = WorldKey::Name(key_name.to_string()); + if let Some(WorldItem::Function(func)) = world.imports.get(&key) { + validate_func(resolve, ty, func, abi)?; + return Ok(Import::WorldFunc(key, func.name.clone(), abi)); + } + + if let Some(import) = + self.maybe_classify_wit_intrinsic(name, None, encoder, ty, true, names)? + { + return Ok(import); + } + + match world.imports.get(&key) { + Some(_) => bail!("expected world top-level import `{name}` to be a function"), + None => bail!("no top-level imported function `{name}` specified"), + } + } + + if module == "env" { + if let Some(import) = names.env_import(name, ty) { + return Ok(import); + } + } + + // Check for `[export]$root::[task-return]foo` or similar + if matches!( + module.strip_prefix(names.import_exported_intrinsic_prefix()), + Some(module) if module == names.import_root() + ) { + if let Some(import) = + self.maybe_classify_wit_intrinsic(name, None, encoder, ty, false, names)? + { + return Ok(import); + } + } + + let interface = match module.strip_prefix(names.import_non_root_prefix()) { + Some(name) => name, + None => bail!("unknown or invalid component model import syntax"), + }; + + if let Some(interface) = interface.strip_prefix(names.import_exported_intrinsic_prefix()) { + let (key, id) = names.module_to_interface(interface, resolve, &world.exports)?; + + if let Some(import) = + self.maybe_classify_wit_intrinsic(name, Some((key, id)), encoder, ty, false, names)? + { + return Ok(import); + } + bail!("unknown function `{name}`") + } + + let (key, id) = names.module_to_interface(interface, resolve, &world.imports)?; + let interface = &resolve.interfaces[id]; + let (function_name, abi) = names.interface_function_name_and_abi(name); + if let Some(f) = interface.functions.get(function_name) { + validate_func(resolve, ty, f, abi).with_context(|| { + let name = resolve.name_world_key(&key); + format!("failed to validate import interface `{name}`") + })?; + return Ok(Import::InterfaceFunc(key, id, f.name.clone(), abi)); + } + + if let Some(import) = + self.maybe_classify_wit_intrinsic(name, Some((key, id)), encoder, ty, true, names)? + { + return Ok(import); + } + bail!( + "import interface `{module}` is missing function \ + `{name}` that is required by the module", + ) + } + + /// Attempts to detect and classify `name` as a WIT intrinsic. + /// + /// This function is a bit of a sprawling sequence of matches used to + /// detect whether `name` corresponds to a WIT intrinsic, so specifically + /// not a WIT function itself. This is only used for functions imported + /// into a module but the import could be for an imported item in a world + /// or an exported item. + /// + /// ## Parameters + /// + /// * `name` - the core module name which is being pattern-matched. This + /// should be the "field" of the import. This may include the "[async-lower]" + /// or "[cancellable]" prefixes. + /// * `key_and_id` - this is the inferred "container" for the function + /// being described which is inferred from the module portion of the core + /// wasm import field. This is `None` for root-level function/type + /// imports, such as when referring to `import x: func();`. This is `Some` + /// when an interface is used (either `import x: interface { .. }` or a + /// standalone `interface`) where the world key is specified for the + /// interface in addition to the interface that was identified. + /// * `encoder` - this is the encoder state that contains + /// `Resolve`/metadata information. + /// * `ty` - the core wasm type of this import. + /// * `import` - whether or not this core wasm import is operating on a WIT + /// level import or export. An example of this being an export is when a + /// core module imports a destructor for an exported resource. + /// * `names` - the name mangling scheme that's configured to be used. + fn maybe_classify_wit_intrinsic( + &self, + name: &str, + key_and_id: Option<(WorldKey, InterfaceId)>, + encoder: &ComponentEncoder, + ty: &FuncType, + import: bool, + names: &dyn NameMangling, + ) -> Result> { + let resolve = &encoder.metadata.resolve; + let world_id = encoder.metadata.world; + let world = &resolve.worlds[world_id]; + + // Separate out `Option` and `Option`. If an + // interface is NOT specified then the `WorldKey` which is attached to + // imports is going to be calculated based on the name of the item + // extracted, such as the resource or function referenced. + let (key, id) = match key_and_id { + Some((key, id)) => (Some(key), Some(id)), + None => (None, None), + }; + + // Tests whether `name` is a resource within `id` (or `world_id`). + let resource_test = |name: &str| match id { + Some(id) => resource_test_for_interface(resolve, id)(name), + None => resource_test_for_world(resolve, world_id)(name), + }; + + // Test whether this is a `resource.drop` intrinsic. + if let Some(resource) = names.resource_drop_name(name) { + if let Some(resource_id) = resource_test(resource) { + let key = key.unwrap_or_else(|| WorldKey::Name(resource.to_string())); + let expected = FuncType::new([ValType::I32], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Some(if import { + Import::ImportedResourceDrop(key, id, resource_id) + } else { + Import::ExportedResourceDrop(key, resource_id) + })); + } + } + + // There are some intrinsics which are only applicable to exported + // functions/resources, so check those use cases here. + if !import { + if let Some(name) = names.resource_new_name(name) { + if let Some(id) = resource_test(name) { + let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string())); + let expected = FuncType::new([ValType::I32], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Some(Import::ExportedResourceNew(key, id))); + } + } + if let Some(name) = names.resource_rep_name(name) { + if let Some(id) = resource_test(name) { + let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string())); + let expected = FuncType::new([ValType::I32], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Some(Import::ExportedResourceRep(key, id))); + } + } + if let Some(name) = names.task_return_name(name) { + let func = get_function(resolve, world, name, id, import)?; + let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string())); + // TODO: should call `validate_func_sig` but would require + // calculating the expected signature based of `func.result`. + return Ok(Some(Import::ExportedTaskReturn(key, id, func.clone()))); + } + if names.task_cancel(name) { + let expected = FuncType::new([], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Some(Import::ExportedTaskCancel)); + } + } + + let lookup_context = PayloadLookupContext { + resolve, + world, + key, + id, + import, + }; + + // Test for a number of async-related intrinsics. All intrinsics are + // prefixed with `[...-N]` where `...` is the name of the intrinsic and + // the `N` is the indexed future/stream that is being referred to. + let import = if let Some(info) = names.future_new(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([], [ValType::I64]), ty)?; + Import::FutureNew(info) + } else if let Some(info) = names.future_write(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32; 2], [ValType::I32]), ty)?; + Import::FutureWrite { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.future_read(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32; 2], [ValType::I32]), ty)?; + Import::FutureRead { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.future_cancel_write(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; + Import::FutureCancelWrite { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.future_cancel_read(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; + Import::FutureCancelRead { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.future_drop_writable(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; + Import::FutureDropWritable(info) + } else if let Some(info) = names.future_drop_readable(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; + Import::FutureDropReadable(info) + } else if let Some(info) = names.stream_new(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([], [ValType::I64]), ty)?; + Import::StreamNew(info) + } else if let Some(info) = names.stream_write(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32; 3], [ValType::I32]), ty)?; + Import::StreamWrite { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.stream_read(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32; 3], [ValType::I32]), ty)?; + Import::StreamRead { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.stream_cancel_write(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; + Import::StreamCancelWrite { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.stream_cancel_read(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; + Import::StreamCancelRead { + async_: info.async_lowered, + info: info.inner, + } + } else if let Some(info) = names.stream_drop_writable(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; + Import::StreamDropWritable(info) + } else if let Some(info) = names.stream_drop_readable(&lookup_context, name) { + validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; + Import::StreamDropReadable(info) + } else { + return Ok(None); + }; + Ok(Some(import)) + } + + fn classify_import_with_library( + &mut self, + import: wasmparser::Import<'_>, + library_info: Option<&LibraryInfo>, + ) -> Result { + let info = match library_info { + Some(info) => info, + None => return Ok(false), + }; + let Some((_, instance)) = info + .arguments + .iter() + .find(|(name, _items)| *name == import.module) + else { + return Ok(false); + }; + match instance { + Instance::MainOrAdapter(module) => match self.names.get(import.module) { + Some(ImportInstance::Whole(which)) => { + if which != module { + bail!("different whole modules imported under the same name"); + } + } + Some(ImportInstance::Names(_)) => { + bail!("cannot mix individual imports and whole module imports") + } + None => { + let instance = ImportInstance::Whole(module.clone()); + self.names.insert(import.module.to_string(), instance); + } + }, + Instance::Items(items) => { + let Some(item) = items.iter().find(|i| i.alias == import.name) else { + return Ok(false); + }; + self.insert_import(import, Import::Item(item.clone()))?; + } + } + Ok(true) + } + + /// Map an imported item, by module and field name in `self.names`, to the + /// kind of `Import` it is: for example, a certain-typed function from an + /// adapter. + fn insert_import(&mut self, import: wasmparser::Import<'_>, item: Import) -> Result<()> { + if let Import::MainModuleMemory(ty) = item { + if self.imported_memory.is_some() { + bail!("module has multiple imports for memory"); + } + self.imported_memory = Some(ty); + } + let entry = self + .names + .entry(import.module.to_string()) + .or_insert(ImportInstance::Names(IndexMap::default())); + let names = match entry { + ImportInstance::Names(names) => names, + _ => bail!("cannot mix individual imports with module imports"), + }; + let entry = match names.entry(import.name.to_string()) { + Entry::Occupied(_) => { + bail!( + "module has duplicate import for `{}::{}`", + import.module, + import.name + ); + } + Entry::Vacant(v) => v, + }; + log::trace!( + "classifying import `{}::{} as {item:?}", + import.module, + import.name + ); + entry.insert(item); + Ok(()) + } +} + +/// Dual of `ImportMap` except describes the exports of a module instead of the +/// imports. +#[derive(Default)] +pub struct ExportMap { + names: IndexMap, + raw_exports: IndexMap, +} + +/// All possible (known) exports from a core wasm module that are recognized and +/// handled during the componentization process. +#[derive(Debug)] +pub enum Export { + /// An export of a top-level function of a world, where the world function + /// is named here. + WorldFunc(WorldKey, String, AbiVariant), + + /// A post-return for a top-level function of a world. + WorldFuncPostReturn(WorldKey), + + /// An export of a function in an interface. + InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant), + + /// A post-return for the above function. + InterfaceFuncPostReturn(WorldKey, String), + + /// A destructor for an exported resource. + ResourceDtor(TypeId), + + /// Memory, typically for an adapter. + Memory, + + /// `cabi_realloc` + GeneralPurposeRealloc, + + /// `cabi_export_realloc` + GeneralPurposeExportRealloc, + + /// `cabi_import_realloc` + GeneralPurposeImportRealloc, + + /// `_initialize` + Initialize, + + /// `cabi_realloc_adapter` + ReallocForAdapter, + + WorldFuncCallback(WorldKey), + + InterfaceFuncCallback(WorldKey, String), + + /// __indirect_function_table, used for `thread.new-indirect` + IndirectFunctionTable, + + /// Used to hook lifecycle events for tasks. + WasmTaskHook, +} + +impl ExportMap { + fn add( + &mut self, + export: wasmparser::Export<'_>, + encoder: &ComponentEncoder, + exports: &IndexSet, + types: TypesRef<'_>, + ) -> Result<()> { + if let Some(item) = self.classify(export, encoder, exports, types)? { + log::debug!("classifying export `{}` as {item:?}", export.name); + let prev = self.names.insert(export.name.to_string(), item); + assert!(prev.is_none()); + } + Ok(()) + } + + fn classify( + &mut self, + export: wasmparser::Export<'_>, + encoder: &ComponentEncoder, + exports: &IndexSet, + types: TypesRef<'_>, + ) -> Result> { + match export.kind { + ExternalKind::Func => { + let ty = types[types.core_function_at(export.index)].unwrap_func(); + self.raw_exports.insert(export.name.to_string(), ty.clone()); + } + _ => {} + } + + // Handle a few special-cased names first. + if export.name == "canonical_abi_realloc" { + return Ok(Some(Export::GeneralPurposeRealloc)); + } else if export.name == "cabi_import_realloc" { + return Ok(Some(Export::GeneralPurposeImportRealloc)); + } else if export.name == "cabi_export_realloc" { + return Ok(Some(Export::GeneralPurposeExportRealloc)); + } else if export.name == "cabi_realloc_adapter" { + return Ok(Some(Export::ReallocForAdapter)); + } + + let (name, names) = match export.name.strip_prefix("cm32p2") { + Some(name) => (name, STANDARD), + None if encoder.reject_legacy_names => return Ok(None), + None => (export.name, LEGACY), + }; + + if let Some(export) = self + .classify_component_export(names, name, &export, encoder, exports, types) + .with_context(|| format!("failed to classify export `{}`", export.name))? + { + return Ok(Some(export)); + } + log::debug!("unknown export `{}`", export.name); + Ok(None) + } + + fn classify_component_export( + &mut self, + names: &dyn NameMangling, + name: &str, + export: &wasmparser::Export<'_>, + encoder: &ComponentEncoder, + exports: &IndexSet, + types: TypesRef<'_>, + ) -> Result> { + let resolve = &encoder.metadata.resolve; + let world = encoder.metadata.world; + match export.kind { + ExternalKind::Func => {} + ExternalKind::Memory => { + if name == names.export_memory() { + return Ok(Some(Export::Memory)); + } + return Ok(None); + } + ExternalKind::Table => { + if Some(name) == names.export_indirect_function_table() { + return Ok(Some(Export::IndirectFunctionTable)); + } + return Ok(None); + } + _ => return Ok(None), + } + let ty = types[types.core_function_at(export.index)].unwrap_func(); + + // Handle a few special-cased names first. + if name == names.export_realloc() { + let expected = FuncType::new([ValType::I32; 4], [ValType::I32]); + validate_func_sig(name, &expected, ty)?; + return Ok(Some(Export::GeneralPurposeRealloc)); + } else if name == names.export_initialize() { + let expected = FuncType::new([], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Some(Export::Initialize)); + } else if Some(name) == names.export_wasm_task_hook() { + let expected = FuncType::new([ValType::I32], []); + validate_func_sig(name, &expected, ty)?; + return Ok(Some(Export::WasmTaskHook)); + } + + let full_name = name; + let (abi, name) = if let Some(name) = names.async_lift_name(name) { + (AbiVariant::GuestExportAsync, name) + } else if let Some(name) = names.async_lift_stackful_name(name) { + (AbiVariant::GuestExportAsyncStackful, name) + } else { + (AbiVariant::GuestExport, name) + }; + + // Try to match this to a known WIT export that `exports` allows. + if let Some((key, id, f)) = names.match_wit_export(name, resolve, world, exports) { + validate_func(resolve, ty, f, abi).with_context(|| { + let key = resolve.name_world_key(key); + format!("failed to validate export for `{key}`") + })?; + match id { + Some(id) => { + return Ok(Some(Export::InterfaceFunc( + key.clone(), + id, + f.name.clone(), + abi, + ))); + } + None => { + return Ok(Some(Export::WorldFunc(key.clone(), f.name.clone(), abi))); + } + } + } + + // See if this is a post-return for any known WIT export. + if let Some(remaining) = names.strip_post_return(name) { + if let Some((key, id, f)) = names.match_wit_export(remaining, resolve, world, exports) { + validate_post_return(resolve, ty, f).with_context(|| { + let key = resolve.name_world_key(key); + format!("failed to validate export for `{key}`") + })?; + match id { + Some(_id) => { + return Ok(Some(Export::InterfaceFuncPostReturn( + key.clone(), + f.name.clone(), + ))); + } + None => { + return Ok(Some(Export::WorldFuncPostReturn(key.clone()))); + } + } + } + } + + if let Some(suffix) = names.async_lift_callback_name(full_name) { + if let Some((key, id, f)) = names.match_wit_export(suffix, resolve, world, exports) { + validate_func_sig( + full_name, + &FuncType::new([ValType::I32; 3], [ValType::I32]), + ty, + )?; + return Ok(Some(if id.is_some() { + Export::InterfaceFuncCallback(key.clone(), f.name.clone()) + } else { + Export::WorldFuncCallback(key.clone()) + })); + } + } + + // And, finally, see if it matches a known destructor. + if let Some(dtor) = names.match_wit_resource_dtor(name, resolve, world, exports) { + let expected = FuncType::new([ValType::I32], []); + validate_func_sig(full_name, &expected, ty)?; + return Ok(Some(Export::ResourceDtor(dtor))); + } + + Ok(None) + } + + /// Returns the name of the post-return export, if any, for the `key` and + /// `func` combo. + pub fn post_return(&self, key: &WorldKey, func: &Function) -> Option<&str> { + self.find(|m| match m { + Export::WorldFuncPostReturn(k) => k == key, + Export::InterfaceFuncPostReturn(k, f) => k == key && func.name == *f, + _ => false, + }) + } + + /// Returns the name of the async callback export, if any, for the `key` and + /// `func` combo. + pub fn callback(&self, key: &WorldKey, func: &Function) -> Option<&str> { + self.find(|m| match m { + Export::WorldFuncCallback(k) => k == key, + Export::InterfaceFuncCallback(k, f) => k == key && func.name == *f, + _ => false, + }) + } + + pub fn abi(&self, key: &WorldKey, func: &Function) -> Option { + self.names.values().find_map(|m| match m { + Export::WorldFunc(k, f, abi) if k == key && func.name == *f => Some(*abi), + Export::InterfaceFunc(k, _, f, abi) if k == key && func.name == *f => Some(*abi), + _ => None, + }) + } + + /// Returns the realloc that the exported function `interface` and `func` + /// are using. + pub fn export_realloc_for(&self, key: &WorldKey, func: &str) -> Option<&str> { + // TODO: This realloc detection should probably be improved with + // some sort of scheme to have per-function reallocs like + // `cabi_realloc_{name}` or something like that. + let _ = (key, func); + + if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeExportRealloc)) { + return Some(name); + } + self.general_purpose_realloc() + } + + /// Returns the realloc that the imported function `interface` and `func` + /// are using. + pub fn import_realloc_for(&self, interface: Option, func: &str) -> Option<&str> { + // TODO: This realloc detection should probably be improved with + // some sort of scheme to have per-function reallocs like + // `cabi_realloc_{name}` or something like that. + let _ = (interface, func); + + self.import_realloc_fallback() + } + + /// Returns the general-purpose realloc function to use for imports. + /// + /// Note that `import_realloc_for` should be used instead where possible. + pub fn import_realloc_fallback(&self) -> Option<&str> { + if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeImportRealloc)) { + return Some(name); + } + self.general_purpose_realloc() + } + + /// Returns the realloc that the main module is exporting into the adapter. + pub fn realloc_to_import_into_adapter(&self) -> Option<&str> { + if let Some(name) = self.find(|m| matches!(m, Export::ReallocForAdapter)) { + return Some(name); + } + self.general_purpose_realloc() + } + + pub fn general_purpose_realloc(&self) -> Option<&str> { + self.find(|m| matches!(m, Export::GeneralPurposeRealloc)) + } + + /// Returns an iterator over all `realloc` functions exported by this module + /// which may be used as a `realloc` canonical option. + /// + /// Note that `cabi_realloc_adapter` is intentionally not included here as + /// that's only ever imported directly into an adapter module and is never + /// used as a canonical option. + pub fn reallocs(&self) -> impl Iterator + '_ { + self.names.iter().filter_map(|(name, export)| match export { + Export::GeneralPurposeRealloc + | Export::GeneralPurposeExportRealloc + | Export::GeneralPurposeImportRealloc => Some(name.as_str()), + _ => None, + }) + } + + /// Returns the memory, if exported, for this module. + pub fn memory(&self) -> Option<&str> { + self.find(|m| matches!(m, Export::Memory)) + } + + /// Returns the indirect function table, if exported, for this module. + pub fn indirect_function_table(&self) -> Option<&str> { + self.find(|t| matches!(t, Export::IndirectFunctionTable)) + } + + /// Returns the hook for tasks, if exported. + pub fn wasm_task_hook(&self) -> Option<&str> { + self.find(|t| matches!(t, Export::WasmTaskHook)) + } + + /// Returns the `_initialize` intrinsic, if exported, for this module. + pub fn initialize(&self) -> Option<&str> { + self.find(|m| matches!(m, Export::Initialize)) + } + + /// Returns destructor for the exported resource `ty`, if it was listed. + pub fn resource_dtor(&self, ty: TypeId) -> Option<&str> { + self.find(|m| match m { + Export::ResourceDtor(t) => *t == ty, + _ => false, + }) + } + + /// NB: this is a linear search and if that's ever a problem this should + /// build up an inverse map during construction to accelerate it. + fn find(&self, f: impl Fn(&Export) -> bool) -> Option<&str> { + let (name, _) = self.names.iter().filter(|(_, m)| f(m)).next()?; + Some(name) + } + + /// Iterates over all exports of this module. + pub fn iter(&self) -> impl Iterator + '_ { + self.names.iter().map(|(n, e)| (n.as_str(), e)) + } + + fn validate(&self, encoder: &ComponentEncoder, exports: &IndexSet) -> Result<()> { + let resolve = &encoder.metadata.resolve; + let world = encoder.metadata.world; + // Multi-memory isn't supported because otherwise we don't know what + // memory to put things in. + if self + .names + .values() + .filter(|m| matches!(m, Export::Memory)) + .count() + > 1 + { + bail!("cannot componentize module that exports multiple memories") + } + + // Every async-with-callback-lifted export must have a callback. + for (name, export) in &self.names { + match export { + Export::WorldFunc(_, _, AbiVariant::GuestExportAsync) => { + if !matches!( + self.names.get(&format!("[callback]{name}")), + Some(Export::WorldFuncCallback(_)) + ) { + bail!("missing callback for `{name}`"); + } + } + Export::InterfaceFunc(_, _, _, AbiVariant::GuestExportAsync) => { + if !matches!( + self.names.get(&format!("[callback]{name}")), + Some(Export::InterfaceFuncCallback(_, _)) + ) { + bail!("missing callback for `{name}`"); + } + } + _ => {} + } + } + + // All of `exports` must be exported and found within this module. + for export in exports { + let require_interface_func = |interface: InterfaceId, name: &str| -> Result<()> { + let result = self.find(|e| match e { + Export::InterfaceFunc(_, id, s, _) => interface == *id && name == s, + _ => false, + }); + if result.is_some() { + Ok(()) + } else { + let export = resolve.name_world_key(export); + bail!("failed to find export of interface `{export}` function `{name}`") + } + }; + let require_world_func = |name: &str| -> Result<()> { + let result = self.find(|e| match e { + Export::WorldFunc(_, s, _) => name == s, + _ => false, + }); + if result.is_some() { + Ok(()) + } else { + bail!("failed to find export of function `{name}`") + } + }; + match &resolve.worlds[world].exports[export] { + WorldItem::Interface { id, .. } => { + for (name, _) in resolve.interfaces[*id].functions.iter() { + require_interface_func(*id, name)?; + } + } + WorldItem::Function(f) => { + require_world_func(&f.name)?; + } + WorldItem::Type { .. } => unreachable!(), + } + } + + Ok(()) + } +} + +/// A builtin that may be declared as cancellable. +struct MaybeCancellable { + #[allow(unused)] + inner: T, + cancellable: bool, +} + +/// A builtin that may be declared as async-lowered. +struct MaybeAsyncLowered { + inner: T, + async_lowered: bool, +} + +/// Context passed to `NameMangling` implementations of stream and future functions +/// to help with looking up payload information. +struct PayloadLookupContext<'a> { + resolve: &'a Resolve, + world: &'a World, + id: Option, + import: bool, + key: Option, +} + +/// Trait dispatch and definition for parsing and interpreting "mangled names" +/// which show up in imports and exports of the component model. +/// +/// This trait is used to implement classification of imports and exports in the +/// component model. The methods on `ImportMap` and `ExportMap` will use this to +/// determine what an import is and how it's lifted/lowered in the world being +/// bound. +/// +/// This trait has a bit of history behind it as well. Before +/// WebAssembly/component-model#378 there was no standard naming scheme for core +/// wasm imports or exports when componenitizing. This meant that +/// `wit-component` implemented a particular scheme which mostly worked but was +/// mostly along the lines of "this at least works" rather than "someone sat +/// down and designed this". Since then, however, an standard naming scheme has +/// now been specified which was indeed designed. +/// +/// This trait serves as the bridge between these two. The historical naming +/// scheme is still supported for now through the `Legacy` implementation below +/// and will be for some time. The transition plan at this time is to support +/// the new scheme, eventually get it supported in bindings generators, and once +/// that's all propagated remove support for the legacy scheme. +trait NameMangling { + fn import_root(&self) -> &str; + fn import_non_root_prefix(&self) -> &str; + fn import_exported_intrinsic_prefix(&self) -> &str; + fn export_memory(&self) -> &str; + fn export_initialize(&self) -> &str; + fn export_realloc(&self) -> &str; + fn export_indirect_function_table(&self) -> Option<&str>; + fn export_wasm_task_hook(&self) -> Option<&str>; + fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str>; + fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str>; + fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str>; + fn task_return_name<'a>(&self, name: &'a str) -> Option<&'a str>; + fn task_cancel(&self, name: &str) -> bool; + fn backpressure_inc(&self, name: &str) -> bool; + fn backpressure_dec(&self, name: &str) -> bool; + fn waitable_set_new(&self, name: &str) -> bool; + fn waitable_set_wait(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)>; + fn waitable_set_poll(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)>; + fn waitable_set_drop(&self, name: &str) -> bool; + fn waitable_join(&self, name: &str) -> bool; + fn subtask_drop(&self, name: &str) -> bool; + fn subtask_cancel(&self, name: &str) -> Option>; + fn async_lift_callback_name<'a>(&self, name: &'a str) -> Option<&'a str>; + fn async_lift_name<'a>(&self, name: &'a str) -> Option<&'a str>; + fn async_lift_stackful_name<'a>(&self, name: &'a str) -> Option<&'a str>; + fn error_context_new(&self, name: &str) -> Option; + fn error_context_debug_message(&self, name: &str) -> Option; + fn error_context_drop(&self, name: &str) -> bool; + fn context_get(&self, name: &str) -> Option<(ValType, u32)>; + fn context_set(&self, name: &str) -> Option<(ValType, u32)>; + fn future_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option; + fn future_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn future_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn future_cancel_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn future_cancel_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn future_drop_writable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option; + fn future_drop_readable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option; + fn stream_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option; + fn stream_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn stream_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn stream_cancel_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn stream_cancel_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option>; + fn stream_drop_writable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option; + fn stream_drop_readable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option; + fn thread_index(&self, name: &str) -> bool; + fn thread_new_indirect(&self, name: &str) -> bool; + fn thread_resume_later(&self, name: &str) -> bool; + fn thread_suspend(&self, name: &str) -> Option>; + fn thread_yield(&self, name: &str) -> Option>; + fn thread_suspend_then_resume(&self, name: &str) -> Option>; + fn thread_yield_then_resume(&self, name: &str) -> Option>; + fn thread_suspend_then_promote(&self, name: &str) -> Option>; + fn thread_yield_then_promote(&self, name: &str) -> Option>; + fn module_to_interface( + &self, + module: &str, + resolve: &Resolve, + items: &IndexMap, + ) -> Result<(WorldKey, InterfaceId)>; + fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str>; + fn match_wit_export<'a>( + &self, + export_name: &str, + resolve: &'a Resolve, + world: WorldId, + exports: &'a IndexSet, + ) -> Option<(&'a WorldKey, Option, &'a Function)>; + fn match_wit_resource_dtor<'a>( + &self, + export_name: &str, + resolve: &'a Resolve, + world: WorldId, + exports: &'a IndexSet, + ) -> Option; + fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant); + fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant); + fn env_import(&self, name: &str, ty: &FuncType) -> Option; +} + +/// Definition of the "standard" naming scheme which currently starts with +/// "cm32p2". Note that wasm64 is not supported at this time. +struct Standard; + +const STANDARD: &'static dyn NameMangling = &Standard; + +impl NameMangling for Standard { + fn import_root(&self) -> &str { + "" + } + fn import_non_root_prefix(&self) -> &str { + "|" + } + fn import_exported_intrinsic_prefix(&self) -> &str { + "_ex_" + } + fn export_memory(&self) -> &str { + "_memory" + } + fn export_initialize(&self) -> &str { + "_initialize" + } + fn export_realloc(&self) -> &str { + "_realloc" + } + fn export_indirect_function_table(&self) -> Option<&str> { + None + } + fn export_wasm_task_hook(&self) -> Option<&str> { + None + } + fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_suffix("_drop") + } + fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_suffix("_new") + } + fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_suffix("_rep") + } + fn task_return_name<'a>(&self, _name: &'a str) -> Option<&'a str> { + None + } + fn task_cancel(&self, _name: &str) -> bool { + false + } + fn backpressure_inc(&self, _name: &str) -> bool { + false + } + fn backpressure_dec(&self, _name: &str) -> bool { + false + } + fn waitable_set_new(&self, _name: &str) -> bool { + false + } + fn waitable_set_wait(&self, _name: &str) -> Option<(MaybeCancellable<()>, ValType)> { + None + } + fn waitable_set_poll(&self, _name: &str) -> Option<(MaybeCancellable<()>, ValType)> { + None + } + fn waitable_set_drop(&self, _name: &str) -> bool { + false + } + fn waitable_join(&self, _name: &str) -> bool { + false + } + fn subtask_drop(&self, _name: &str) -> bool { + false + } + fn subtask_cancel(&self, _name: &str) -> Option> { + None + } + fn async_lift_callback_name<'a>(&self, _name: &'a str) -> Option<&'a str> { + None + } + fn async_lift_name<'a>(&self, _name: &'a str) -> Option<&'a str> { + None + } + fn async_lift_stackful_name<'a>(&self, _name: &'a str) -> Option<&'a str> { + None + } + fn error_context_new(&self, _name: &str) -> Option { + None + } + fn error_context_debug_message(&self, _name: &str) -> Option { + None + } + fn error_context_drop(&self, _name: &str) -> bool { + false + } + fn context_get(&self, _name: &str) -> Option<(ValType, u32)> { + None + } + fn context_set(&self, _name: &str) -> Option<(ValType, u32)> { + None + } + fn thread_index(&self, _name: &str) -> bool { + false + } + fn thread_new_indirect(&self, _name: &str) -> bool { + false + } + fn thread_resume_later(&self, _name: &str) -> bool { + false + } + fn thread_suspend(&self, _name: &str) -> Option> { + None + } + fn thread_yield(&self, _name: &str) -> Option> { + None + } + fn thread_suspend_then_resume(&self, _name: &str) -> Option> { + None + } + fn thread_yield_then_resume(&self, _name: &str) -> Option> { + None + } + fn thread_suspend_then_promote(&self, _name: &str) -> Option> { + None + } + fn thread_yield_then_promote(&self, _name: &str) -> Option> { + None + } + fn future_new( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option { + None + } + fn future_write( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn future_read( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn future_cancel_write( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn future_cancel_read( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn future_drop_writable( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option { + None + } + fn future_drop_readable( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option { + None + } + fn stream_new( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option { + None + } + fn stream_write( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn stream_read( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn stream_cancel_write( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn stream_cancel_read( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option> { + None + } + fn stream_drop_writable( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option { + None + } + fn stream_drop_readable( + &self, + _lookup_context: &PayloadLookupContext, + _name: &str, + ) -> Option { + None + } + fn module_to_interface( + &self, + interface: &str, + resolve: &Resolve, + items: &IndexMap, + ) -> Result<(WorldKey, InterfaceId)> { + for (key, item) in items.iter() { + let id = match key { + // Bare keys are matched exactly against `interface` + WorldKey::Name(name) => match item { + WorldItem::Interface { id, .. } if name == interface => *id, + _ => continue, + }, + // ID-identified keys are matched with their "canonical name" + WorldKey::Interface(id) => { + if resolve.canonicalized_id_of(*id).as_deref() != Some(interface) { + continue; + } + *id + } + }; + return Ok((key.clone(), id)); + } + bail!("failed to find world item corresponding to interface `{interface}`") + } + fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_suffix("_post") + } + fn match_wit_export<'a>( + &self, + export_name: &str, + resolve: &'a Resolve, + world: WorldId, + exports: &'a IndexSet, + ) -> Option<(&'a WorldKey, Option, &'a Function)> { + if let Some(world_export_name) = export_name.strip_prefix("||") { + let key = exports.get(&WorldKey::Name(world_export_name.to_string()))?; + match &resolve.worlds[world].exports[key] { + WorldItem::Function(f) => return Some((key, None, f)), + _ => return None, + } + } + + let (key, id, func_name) = + self.match_wit_interface(export_name, resolve, world, exports)?; + let func = resolve.interfaces[id].functions.get(func_name)?; + Some((key, Some(id), func)) + } + + fn match_wit_resource_dtor<'a>( + &self, + export_name: &str, + resolve: &'a Resolve, + world: WorldId, + exports: &'a IndexSet, + ) -> Option { + let (_key, id, name) = + self.match_wit_interface(export_name.strip_suffix("_dtor")?, resolve, world, exports)?; + let ty = *resolve.interfaces[id].types.get(name)?; + match resolve.types[ty].kind { + TypeDefKind::Resource => Some(ty), + _ => None, + } + } + + fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { + (name, AbiVariant::GuestImport) + } + fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { + (name, AbiVariant::GuestImport) + } + fn env_import(&self, _name: &str, _ty: &FuncType) -> Option { + None + } +} + +impl Standard { + fn match_wit_interface<'a, 'b>( + &self, + export_name: &'b str, + resolve: &'a Resolve, + world: WorldId, + exports: &'a IndexSet, + ) -> Option<(&'a WorldKey, InterfaceId, &'b str)> { + let world = &resolve.worlds[world]; + let export_name = export_name.strip_prefix("|")?; + + for export in exports { + let id = match &world.exports[export] { + WorldItem::Interface { id, .. } => *id, + WorldItem::Function(_) => continue, + WorldItem::Type { .. } => unreachable!(), + }; + let remaining = match export { + WorldKey::Name(name) => export_name.strip_prefix(name), + WorldKey::Interface(_) => { + let prefix = resolve.canonicalized_id_of(id).unwrap(); + export_name.strip_prefix(&prefix) + } + }; + let item_name = match remaining.and_then(|s| s.strip_prefix("|")) { + Some(name) => name, + None => continue, + }; + return Some((export, id, item_name)); + } + + None + } +} + +/// Definition of wit-component's "legacy" naming scheme which predates +/// WebAssembly/component-model#378. +struct Legacy; + +const LEGACY: &'static dyn NameMangling = &Legacy; + +impl Legacy { + // Looks for `[$prefix-N]foo` within `name`. If found then `foo` is + // used to find a function within `id` and `world` above. Once found + // then `N` is used to index within that function to extract a + // future/stream type. If that's all found then a `PayloadInfo` is + // returned to get attached to an intrinsic. + fn prefixed_payload( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + prefix: &str, + ) -> Option { + // parse the `prefix` into `func_name` and `type_index`, bailing out + // with `None` if anything doesn't match. + let (index_or_unit, func_name) = prefixed_intrinsic(name, prefix)?; + let ty = match index_or_unit { + "unit" => { + if name.starts_with("[future") { + PayloadType::UnitFuture + } else if name.starts_with("[stream") { + PayloadType::UnitStream + } else { + unreachable!() + } + } + other => { + // Note that this is parsed as a `u32` to ensure that the + // integer parsing is the same across platforms regardless of + // the the width of `usize`. + let type_index = other.parse::().ok()? as usize; + + // Double-check that `func_name` is indeed a function name within + // this interface/world. Then additionally double-check that + // `type_index` is indeed a valid index for this function's type + // signature. + let function = get_function( + lookup_context.resolve, + lookup_context.world, + func_name, + lookup_context.id, + lookup_context.import, + ) + .ok()?; + PayloadType::Type { + id: *function + .find_futures_and_streams(lookup_context.resolve) + .get(type_index)?, + function: function.name.clone(), + } + } + }; + + // And if all that passes wrap up everything in a `PayloadInfo`. + Some(PayloadInfo { + name: name.to_string(), + ty, + key: lookup_context + .key + .clone() + .unwrap_or_else(|| WorldKey::Name(name.to_string())), + interface: lookup_context.id, + imported: lookup_context.import, + }) + } + + fn maybe_async_lowered_payload( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + prefix: &str, + ) -> Option> { + let (async_lowered, clean_name) = self.strip_async_lowered_prefix(name); + let payload = self.prefixed_payload(lookup_context, clean_name, prefix)?; + Some(MaybeAsyncLowered { + inner: payload, + async_lowered, + }) + } + + fn strip_async_lowered_prefix<'a>(&self, name: &'a str) -> (bool, &'a str) { + name.strip_prefix("[async-lower]") + .map_or((false, name), |s| (true, s)) + } + fn match_with_async_lowered_prefix( + &self, + name: &str, + expected: &str, + ) -> Option> { + let (async_lowered, clean_name) = self.strip_async_lowered_prefix(name); + if clean_name == expected { + Some(MaybeAsyncLowered { + inner: (), + async_lowered, + }) + } else { + None + } + } + fn strip_cancellable_prefix<'a>(&self, name: &'a str) -> (bool, &'a str) { + name.strip_prefix("[cancellable]") + .map_or((false, name), |s| (true, s)) + } + fn match_with_cancellable_prefix( + &self, + name: &str, + expected: &str, + ) -> Option> { + let (cancellable, clean_name) = self.strip_cancellable_prefix(name); + if clean_name == expected { + Some(MaybeCancellable { + inner: (), + cancellable, + }) + } else { + None + } + } + + /// Matches a name with the given prefix and either no suffix (for backwards compat) or + /// "-i32" or "-i64". + /// Returns a `ValType` based on the suffix and defaults to `I32`. + fn match_with_optional_type_suffix(name: &str, match_prefix: &str) -> Option { + let tail = name.strip_prefix(match_prefix)?.strip_suffix(']')?; + if tail.is_empty() { + Some(ValType::I32) + } else { + match tail.strip_prefix('-')? { + "i32" => Some(ValType::I32), + "i64" => Some(ValType::I64), + // Other suffixes + _ => None, + } + } + } +} + +impl NameMangling for Legacy { + fn import_root(&self) -> &str { + "$root" + } + fn import_non_root_prefix(&self) -> &str { + "" + } + fn import_exported_intrinsic_prefix(&self) -> &str { + "[export]" + } + fn export_memory(&self) -> &str { + "memory" + } + fn export_initialize(&self) -> &str { + "_initialize" + } + fn export_realloc(&self) -> &str { + "cabi_realloc" + } + fn export_indirect_function_table(&self) -> Option<&str> { + Some("__indirect_function_table") + } + fn export_wasm_task_hook(&self) -> Option<&str> { + Some(crate::linking::metadata::TASK_HOOK) + } + fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("[resource-drop]") + } + fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("[resource-new]") + } + fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("[resource-rep]") + } + fn task_return_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("[task-return]") + } + fn task_cancel(&self, name: &str) -> bool { + name == "[task-cancel]" + } + fn backpressure_inc(&self, name: &str) -> bool { + name == "[backpressure-inc]" + } + fn backpressure_dec(&self, name: &str) -> bool { + name == "[backpressure-dec]" + } + fn waitable_set_new(&self, name: &str) -> bool { + name == "[waitable-set-new]" + } + fn waitable_set_wait(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)> { + let (cancellable, clean_name) = self.strip_cancellable_prefix(name); + let mb_cancellable = MaybeCancellable { + inner: (), + cancellable, + }; + let result_ty = Legacy::match_with_optional_type_suffix(clean_name, "[waitable-set-wait")?; + Some((mb_cancellable, result_ty)) + } + fn waitable_set_poll(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)> { + let (cancellable, clean_name) = self.strip_cancellable_prefix(name); + let mb_cancellable = MaybeCancellable { + inner: (), + cancellable, + }; + let result_ty = Legacy::match_with_optional_type_suffix(clean_name, "[waitable-set-poll")?; + Some((mb_cancellable, result_ty)) + } + fn waitable_set_drop(&self, name: &str) -> bool { + name == "[waitable-set-drop]" + } + fn waitable_join(&self, name: &str) -> bool { + name == "[waitable-join]" + } + fn subtask_drop(&self, name: &str) -> bool { + name == "[subtask-drop]" + } + fn subtask_cancel(&self, name: &str) -> Option> { + self.match_with_async_lowered_prefix(name, "[subtask-cancel]") + } + fn async_lift_callback_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("[callback][async-lift]") + } + fn async_lift_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("[async-lift]") + } + fn async_lift_stackful_name<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("[async-lift-stackful]") + } + fn error_context_new(&self, name: &str) -> Option { + match name { + "[error-context-new-utf8]" => Some(StringEncoding::UTF8), + "[error-context-new-utf16]" => Some(StringEncoding::UTF16), + "[error-context-new-latin1+utf16]" => Some(StringEncoding::CompactUTF16), + _ => None, + } + } + fn error_context_debug_message(&self, name: &str) -> Option { + match name { + "[error-context-debug-message-utf8]" => Some(StringEncoding::UTF8), + "[error-context-debug-message-utf16]" => Some(StringEncoding::UTF16), + "[error-context-debug-message-latin1+utf16]" => Some(StringEncoding::CompactUTF16), + _ => None, + } + } + fn error_context_drop(&self, name: &str) -> bool { + name == "[error-context-drop]" + } + fn context_get(&self, name: &str) -> Option<(ValType, u32)> { + parse_context_name(name, "[context-get-") + } + fn context_set(&self, name: &str) -> Option<(ValType, u32)> { + parse_context_name(name, "[context-set-") + } + fn thread_index(&self, name: &str) -> bool { + name == "[thread-index]" + } + fn thread_new_indirect(&self, name: &str) -> bool { + // For now, we'll fix the type of the start function and the table to extract it from + name == "[thread-new-indirect-v0]" + } + fn thread_resume_later(&self, name: &str) -> bool { + name == "[thread-resume-later]" + } + fn thread_suspend(&self, name: &str) -> Option> { + self.match_with_cancellable_prefix(name, "[thread-suspend]") + } + fn thread_yield(&self, name: &str) -> Option> { + self.match_with_cancellable_prefix(name, "[thread-yield]") + } + fn thread_suspend_then_resume(&self, name: &str) -> Option> { + self.match_with_cancellable_prefix(name, "[thread-suspend-then-resume]") + } + fn thread_yield_then_resume(&self, name: &str) -> Option> { + self.match_with_cancellable_prefix(name, "[thread-yield-then-resume]") + } + fn thread_suspend_then_promote(&self, name: &str) -> Option> { + self.match_with_cancellable_prefix(name, "[thread-suspend-then-promote]") + } + fn thread_yield_then_promote(&self, name: &str) -> Option> { + self.match_with_cancellable_prefix(name, "[thread-yield-then-promote]") + } + fn future_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option { + self.prefixed_payload(lookup_context, name, "[future-new-") + } + fn future_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[future-write-") + } + fn future_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[future-read-") + } + fn future_cancel_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[future-cancel-write-") + } + fn future_cancel_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[future-cancel-read-") + } + fn future_drop_writable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option { + self.prefixed_payload(lookup_context, name, "[future-drop-writable-") + } + fn future_drop_readable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option { + self.prefixed_payload(lookup_context, name, "[future-drop-readable-") + } + fn stream_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option { + self.prefixed_payload(lookup_context, name, "[stream-new-") + } + fn stream_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[stream-write-") + } + fn stream_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[stream-read-") + } + fn stream_cancel_write( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[stream-cancel-write-") + } + fn stream_cancel_read( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option> { + self.maybe_async_lowered_payload(lookup_context, name, "[stream-cancel-read-") + } + fn stream_drop_writable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option { + self.prefixed_payload(lookup_context, name, "[stream-drop-writable-") + } + fn stream_drop_readable( + &self, + lookup_context: &PayloadLookupContext, + name: &str, + ) -> Option { + self.prefixed_payload(lookup_context, name, "[stream-drop-readable-") + } + fn module_to_interface( + &self, + module: &str, + resolve: &Resolve, + items: &IndexMap, + ) -> Result<(WorldKey, InterfaceId)> { + // First see if this is a bare name + let bare_name = WorldKey::Name(module.to_string()); + if let Some(WorldItem::Interface { id, .. }) = items.get(&bare_name) { + return Ok((bare_name, *id)); + } + + // ... and if this isn't a bare name then it's time to do some parsing + // related to interfaces, versions, and such. First up the `module` name + // is parsed as a normal component name from `wasmparser` to see if it's + // of the "interface kind". If it's not then that means the above match + // should have been a hit but it wasn't, so an error is returned. + let kebab_name = ComponentName::new(module, 0); + let name = match kebab_name.as_ref().map(|k| k.kind()) { + Ok(ComponentNameKind::Interface(name)) => name, + _ => bail!("module requires an import interface named `{module}`"), + }; + + // FIXME: this prevents core wasm from importing from `@1` or + // `@0.1`, for example. More refactoring will be necessary to enable + // that. + let version = name.version(None)?; + + // Prioritize an exact match based on versions, so try that first. + let pkgname = PackageName { + namespace: name.namespace().to_string(), + name: name.package().to_string(), + version: version.clone(), + }; + if let Some(pkg) = resolve.package_names.get(&pkgname) { + if let Some(id) = resolve.packages[*pkg] + .interfaces + .get(name.interface().as_str()) + { + // If the interface from the package is directly in `items` then + // return that. + let key = WorldKey::Interface(*id); + if items.contains_key(&key) { + return Ok((key, *id)); + } + + // .. otherwise see if any interface in `items` is a clone of + // the package's interface. This means it's created by + // `generate_nominal_type_ids` and is used to match up exports + // to their nominal clone since the original is no longer + // exported. + for k in items.keys() { + let i = match *k { + WorldKey::Interface(id) => id, + WorldKey::Name(_) => continue, + }; + if resolve.interfaces[i].clone_of == Some(*id) { + return Ok((WorldKey::Interface(i), i)); + } + } + } + } + + // If an exact match wasn't found then instead search for the first + // match based on versions. This means that a core wasm import for + // "1.2.3" might end up matching an interface at "1.2.4", for example. + // (or "1.2.2", depending on what's available). + for (key, _) in items { + let id = match key { + WorldKey::Interface(id) => *id, + WorldKey::Name(_) => continue, + }; + // Make sure the interface names match + let interface = &resolve.interfaces[id]; + if interface.name.as_ref().unwrap() != name.interface().as_str() { + continue; + } + + // Make sure the package name (without version) matches + let pkg = &resolve.packages[interface.package.unwrap()]; + if pkg.name.namespace != pkgname.namespace || pkg.name.name != pkgname.name { + continue; + } + + let module_version = match &version { + Some(version) => version, + None => continue, + }; + let pkg_version = match &pkg.name.version { + Some(version) => version, + None => continue, + }; + + // Test if the two semver versions are compatible + let module_compat = PackageName::version_compat_track(&module_version); + let pkg_compat = PackageName::version_compat_track(pkg_version); + if module_compat == pkg_compat { + return Ok((key.clone(), id)); + } + } + + bail!("module requires an import interface named `{module}`") + } + fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str> { + name.strip_prefix("cabi_post_") + } + fn match_wit_export<'a>( + &self, + export_name: &str, + resolve: &'a Resolve, + world: WorldId, + exports: &'a IndexSet, + ) -> Option<(&'a WorldKey, Option, &'a Function)> { + let world = &resolve.worlds[world]; + for name in exports { + match &world.exports[name] { + WorldItem::Function(f) => { + if f.legacy_core_export_name(None) == export_name { + return Some((name, None, f)); + } + } + WorldItem::Interface { id, .. } => { + let string = resolve.name_world_key(name); + for (_, func) in resolve.interfaces[*id].functions.iter() { + if func.legacy_core_export_name(Some(&string)) == export_name { + return Some((name, Some(*id), func)); + } + } + } + + WorldItem::Type { .. } => unreachable!(), + } + } + + None + } + + fn match_wit_resource_dtor<'a>( + &self, + export_name: &str, + resolve: &'a Resolve, + world: WorldId, + exports: &'a IndexSet, + ) -> Option { + let world = &resolve.worlds[world]; + for name in exports { + let id = match &world.exports[name] { + WorldItem::Interface { id, .. } => *id, + WorldItem::Function(_) => continue, + WorldItem::Type { .. } => unreachable!(), + }; + let name = resolve.name_world_key(name); + let resource = match export_name + .strip_prefix(&name) + .and_then(|s| s.strip_prefix("#[dtor]")) + .and_then(|r| resolve.interfaces[id].types.get(r)) + { + Some(id) => *id, + None => continue, + }; + + match resolve.types[resource].kind { + TypeDefKind::Resource => {} + _ => continue, + } + + return Some(resource); + } + + None + } + + fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { + let (async_abi, name) = self.strip_async_lowered_prefix(name); + ( + name, + if async_abi { + AbiVariant::GuestImportAsync + } else { + AbiVariant::GuestImport + }, + ) + } + fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { + let (async_abi, name) = self.strip_async_lowered_prefix(name); + ( + name, + if async_abi { + AbiVariant::GuestImportAsync + } else { + AbiVariant::GuestImport + }, + ) + } + fn env_import(&self, name: &str, ty: &FuncType) -> Option { + match name { + "__wasm_get_stack_pointer" => { + let ty = *ty.results().get(0)?; + Some(Import::ContextGet { ty, slot: 0 }) + } + "__wasm_set_stack_pointer" => { + let ty = *ty.params().get(0)?; + Some(Import::ContextSet { ty, slot: 0 }) + } + // TLS handling is slightly different than above to handle + // coop-threading-vs-not, so the exact resolution of this import is + // deferred to later. + "__wasm_get_tls_base" => { + let ty = *ty.results().get(0)?; + Some(Import::TlsBaseGet { ty }) + } + "__wasm_set_tls_base" => { + let ty = *ty.params().get(0)?; + Some(Import::TlsBaseSet { ty }) + } + _ => None, + } + } +} + +/// This function validates the following: +/// +/// * The `bytes` represent a valid core WebAssembly module. +/// * The module's imports are all satisfied by the given `imports` interfaces +/// or the `adapters` set. +/// * The given default and exported interfaces are satisfied by the module's +/// exports. +/// +/// The `ValidatedModule` return value contains the metadata which describes the +/// input module on success. This is then further used to generate a component +/// for this module. +pub fn validate_module( + encoder: &ComponentEncoder, + bytes: &[u8], + import_map: Option<&ModuleImportMap>, +) -> Result { + ValidatedModule::new( + encoder, + bytes, + &encoder.main_module_exports, + import_map, + None, + ) +} + +/// This function will validate the `bytes` provided as a wasm adapter module. +/// Notably this will validate the wasm module itself in addition to ensuring +/// that it has the "shape" of an adapter module. Current constraints are: +/// +/// * The adapter module can import only one memory +/// * The adapter module can only import from the name of `interface` specified, +/// and all function imports must match the `required` types which correspond +/// to the lowered types of the functions in `interface`. +/// +/// The wasm module passed into this function is the output of the GC pass of an +/// adapter module's original source. This means that the adapter module is +/// already minimized and this is a double-check that the minimization pass +/// didn't accidentally break the wasm module. +/// +/// If `is_library` is true, we waive some of the constraints described above, +/// allowing the module to import tables and globals, as well as import +/// functions at the world level, not just at the interface level. +pub fn validate_adapter_module( + encoder: &ComponentEncoder, + bytes: &[u8], + required_by_import: &IndexMap, + exports: &IndexSet, + library_info: Option<&LibraryInfo>, +) -> Result { + let ret = ValidatedModule::new(encoder, bytes, exports, None, library_info)?; + + for (name, required_ty) in required_by_import { + let actual = match ret.exports.raw_exports.get(name) { + Some(ty) => ty, + None => return Err(AdapterModuleDidNotExport(name.clone()).into()), + }; + validate_func_sig(name, required_ty, &actual)?; + } + + Ok(ret) +} + +/// An error that can be returned from adapting a core Wasm module into a +/// component using an adapter module. +/// +/// If the core Wasm module contained an import that it requires to be +/// satisfied by the adapter, and the adapter does not contain an export +/// with the same name, an instance of this error is returned. +#[derive(Debug, Clone)] +pub struct AdapterModuleDidNotExport(String); + +impl fmt::Display for AdapterModuleDidNotExport { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "adapter module did not export `{}`", self.0) + } +} + +impl std::error::Error for AdapterModuleDidNotExport {} + +fn resource_test_for_interface<'a>( + resolve: &'a Resolve, + id: InterfaceId, +) -> impl Fn(&str) -> Option + 'a { + let interface = &resolve.interfaces[id]; + move |name: &str| { + let ty = match interface.types.get(name) { + Some(ty) => *ty, + None => return None, + }; + if matches!(resolve.types[ty].kind, TypeDefKind::Resource) { + Some(ty) + } else { + None + } + } +} + +fn resource_test_for_world<'a>( + resolve: &'a Resolve, + id: WorldId, +) -> impl Fn(&str) -> Option + 'a { + let world = &resolve.worlds[id]; + move |name: &str| match world.imports.get(&WorldKey::Name(name.to_string()))? { + WorldItem::Type { id, .. } => { + if matches!(resolve.types[*id].kind, TypeDefKind::Resource) { + Some(*id) + } else { + None + } + } + _ => None, + } +} + +fn validate_func( + resolve: &Resolve, + ty: &wasmparser::FuncType, + func: &Function, + abi: AbiVariant, +) -> Result<()> { + validate_func_sig( + &func.name, + &wasm_sig_to_func_type(resolve.wasm_signature(abi, func)), + ty, + ) +} + +fn validate_post_return( + resolve: &Resolve, + ty: &wasmparser::FuncType, + func: &Function, +) -> Result<()> { + // The expected signature of a post-return function is to take all the + // parameters that are returned by the guest function and then return no + // results. Model this by calculating the signature of `func` and then + // moving its results into the parameters list while emptying out the + // results. + let mut sig = resolve.wasm_signature(AbiVariant::GuestExport, func); + sig.params = mem::take(&mut sig.results); + validate_func_sig( + &format!("{} post-return", func.name), + &wasm_sig_to_func_type(sig), + ty, + ) +} + +fn validate_func_sig(name: &str, expected: &FuncType, ty: &wasmparser::FuncType) -> Result<()> { + if ty != expected { + bail!( + "type mismatch for function `{}`: expected `{:?} -> {:?}` but found `{:?} -> {:?}`", + name, + expected.params(), + expected.results(), + ty.params(), + ty.results() + ); + } + + Ok(()) +} + +/// Matches `name` as `[${prefix}S]...`, and if found returns `("S", "...")` +fn prefixed_intrinsic<'a>(name: &'a str, prefix: &str) -> Option<(&'a str, &'a str)> { + assert!(prefix.starts_with("[")); + assert!(prefix.ends_with("-")); + let suffix = name.strip_prefix(prefix)?; + let index = suffix.find(']')?; + let rest = &suffix[index + 1..]; + Some((&suffix[..index], rest)) +} + +/// Parses a `[context-get-]` / `[context-set-]` style name, optionally +/// carrying a type width infix: `[context-get-i64-]`. +/// +/// Returns the value type together with the numeric slot. Additional type +/// widths can be added here by extending the match below. +fn parse_context_name(name: &str, prefix: &str) -> Option<(ValType, u32)> { + let (suffix, rest) = prefixed_intrinsic(name, prefix)?; + if !rest.is_empty() { + return None; + } + let (ty, slot) = match suffix.split_once('-') { + Some(("i64", slot)) => (ValType::I64, slot), + Some(("i32", slot)) => (ValType::I32, slot), + _ => (ValType::I32, suffix), + }; + let slot = slot.parse().ok()?; + Some((ty, slot)) +} + +fn get_function<'a>( + resolve: &'a Resolve, + world: &'a World, + name: &str, + interface: Option, + imported: bool, +) -> Result<&'a Function> { + let function = if let Some(id) = interface { + return resolve.interfaces[id] + .functions + .get(name) + .ok_or_else(|| anyhow!("no export `{name}` found")); + } else if imported { + world.imports.get(&WorldKey::Name(name.to_string())) + } else { + world.exports.get(&WorldKey::Name(name.to_string())) + }; + let Some(WorldItem::Function(function)) = function else { + bail!("no export `{name}` found"); + }; + Ok(function) +} From 073330c780f9cffb49bd5ceab0bac313b0f30aa4 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:21:25 +0000 Subject: [PATCH 03/14] Check values against their WIT types before lowering Lowering a Python value that does not match its WIT type used to panic part way through, for example with an out-of-range int. Check the whole value first: an import call raises TypeError, OverflowError or ValueError naming the argument before the host sees a call, and an export whose result does not match traps with a message naming the value. --- runtime/src/check.rs | 308 ++++++++++++++++++++++++++++++++++ runtime/src/lib.rs | 32 +++- src/test/python_source/app.py | 31 ++-- src/test/tests.rs | 41 +---- src/test/wit/tests.wit | 6 +- 5 files changed, 365 insertions(+), 53 deletions(-) create mode 100644 runtime/src/check.rs diff --git a/runtime/src/check.rs b/runtime/src/check.rs new file mode 100644 index 00000000..33a18724 --- /dev/null +++ b/runtime/src/check.rs @@ -0,0 +1,308 @@ +//! 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, PyFloat, PyInt, 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 => { + if value.is_instance_of::() || value.is_instance_of::() { + value.extract::().map(drop).map_err(|_| { + PyOverflowError::new_err(format!( + "{path}: {} is out of range for a float", + repr(value) + )) + }) + } else { + Err(type_error("float", value, 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<()> { + if !value.is_instance_of::() { + return Err(type_error(name, value, path)); + } + value.extract::().map(drop).map_err(|_| { + PyOverflowError::new_err(format!( + "{path}: {} is out of range for {name}", + repr(value) + )) + }) +} + +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..57ae5b2e 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); } diff --git a/src/test/python_source/app.py b/src/test/python_source/app.py index 71618735..089951ab 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,20 @@ 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 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..0828f757 100644 --- a/src/test/tests.rs +++ b/src/test/tests.rs @@ -1246,7 +1246,7 @@ fn filesystem() -> Result<()> { } #[test] -fn trap_on_empty_resource() -> Result<()> { +fn reject_moved_resource() -> Result<()> { TESTER.test(|world, store, runtime| { runtime.block_on(async { let thing = store @@ -1255,16 +1255,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 +1263,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..f6e0846d 100644 --- a/src/test/wit/tests.wit +++ b/src/test/wit/tests.wit @@ -241,15 +241,15 @@ world tests { export test-refcounts: func(); - export trap-on-empty-resource: func(thing: thing); + 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); From 5760cac4d2e875fc15942576222ea34e9a2d12ca Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:21:35 +0000 Subject: [PATCH 04/14] Release exported resources when their last handle is dropped The handle table holds a strong reference to an exported resource's Python object, but the destructor did nothing, so objects whose handles the host dropped were never finalized. Release the reference in the destructor, and drop the handle when an owned handle returns to the guest instead of leaking it. --- runtime/src/lib.rs | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 57ae5b2e..39b2faca 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1398,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(); + }) } } @@ -1994,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 From 875d39f04d6f8fcaf9535c20886d9773254d0915 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:21:35 +0000 Subject: [PATCH 05/14] Link the support libraries that extensions need An extension may depend on a shared library that is not itself an extension, such as libsetjmp.so or a libjpeg.so shipped next to it. Link each library that a linked library names in its dylink.0 needed list, from the Python path or the WASI SDK's libsetjmp.so, under the name its dependents use. Libraries that nothing needs are not linked. --- build.rs | 2 + src/prelink.rs | 110 +++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 109 insertions(+), 3 deletions(-) diff --git a/build.rs b/build.rs index 1da10d2d..2b09d791 100644 --- a/build.rs +++ b/build.rs @@ -83,6 +83,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", ]; @@ -197,6 +198,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", 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() From ef5ac7ceaed2138eb4910a9e2b19b4502e028957 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:32:40 +0000 Subject: [PATCH 06/14] Derive pre-initialization inputs from the linked component Pre-initialization saves the application's state into the component, so host entropy, time and file writes during it made each build different. Derive the hash seed and random bytes from the linked component, give the guest a clock that starts at the Unix epoch, stop it from writing bytecode into the source directories, and give the directories created for the build fixed times. --- Cargo.lock | 1 + Cargo.toml | 2 ++ src/lib.rs | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 90 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index b6676cad..08cb5e5d 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", diff --git a/Cargo.toml b/Cargo.toml index f436c3d8..f7b6cf31 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" diff --git a/src/lib.rs b/src/lib.rs index dd3fe44c..e69a50f1 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, @@ -833,7 +880,34 @@ 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 instead of from host entropy. Identical inputs then + // produce identical components. The runtime reseeds `random` from the + // host before the first export call. + let digest = Sha256::digest(&component); + 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 +1008,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); From 94e3d7d89362ea1c90412a25fdd71579469cd08f Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:52:22 +0000 Subject: [PATCH 07/14] Bound deallocation chains by depth on WASI CPython defers a deallocation when its measured C stack margin is small, but on WebAssembly that margin covers only the linear-memory stack. Freeing a deeply nested list exhausted the engine's call stack first. Count nested deallocations instead and defer at depth 50. --- ...deallocation-chains-by-depth-on-WASI.patch | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 cpython-patches/0003-Bound-deallocation-chains-by-depth-on-WASI.patch 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 From 5dec3afbbf1c5376945934c8dbfc285a693dc6ec Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 21:52:22 +0000 Subject: [PATCH 08/14] Add an option for the size of the C stack CPython raises RecursionError when the linear-memory C stack is nearly full, but the engine's own call stack is separate and grows several times faster for the same C recursion. The --stack-size option, and stack_size in the library API, let the caller size the C stack so that RecursionError comes first for its engine's call stack. --- src/command.rs | 13 +++++++++++++ src/lib.rs | 5 ++++- src/link.rs | 5 ++++- src/python.rs | 4 +++- src/test.rs | 1 + src/test/tests.rs | 1 + 6 files changed, 26 insertions(+), 3 deletions(-) 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 e69a50f1..d9117a09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -457,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>, @@ -863,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)? 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/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/tests.rs b/src/test/tests.rs index 0828f757..55c29fa2 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, From 1ed12966632c72e8fa922f8b17b5994960fb4031 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 23:05:12 +0000 Subject: [PATCH 09/14] Use host Python 3.14.10 in the Test workflow setup-python has no 3.14.0 build for the current ubuntu-latest image, so the Test jobs failed before building. 3.14.10 is published for every runner in the matrix and matches the CPython release that the build uses. --- .github/workflows/test.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 From 3cf6e7921caa186c1e7e589d52bbb3b0d490c9e9 Mon Sep 17 00:00:00 2001 From: David Biro Date: Mon, 16 Nov 2026 23:51:23 +0000 Subject: [PATCH 10/14] Run CI From d5e074df24b158b4fe0a488819293a9c6ac8f5cd Mon Sep 17 00:00:00 2001 From: David Biro Date: Wed, 25 Nov 2026 23:27:08 +0000 Subject: [PATCH 11/14] Reject CPython caches made from other sources build.rs reused an existing cpython/ without the release tarball, its checksum or the patches, and an existing libpython3.14.so without a build. A checkout that had built other sources packaged that older runtime. It now records the SHA-256 of the CPython, zlib and SQLite tarballs and of each patch in cpython/ and cpython/builddir/wasi, and fails on a tree or library with another identity or none. --- build.rs | 269 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 171 insertions(+), 98 deletions(-) diff --git a/build.rs b/build.rs index 2b09d791..bffd3494 100644 --- a/build.rs +++ b/build.rs @@ -48,6 +48,13 @@ 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"); @@ -319,7 +326,22 @@ fn maybe_make_cpython(repo_dir: &Path, wasi_sdk: &Path) -> Result<()> { let cpython_dir = repo_dir.join("cpython"); let patch_dir = repo_dir.join("cpython-patches"); println!("cargo:rerun-if-changed={}", patch_dir.display()); - if !cpython_dir.exists() { + let mut patches = fs::read_dir(&patch_dir)? + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>()?; + 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() { + // 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); + } + + 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" ); @@ -327,121 +349,172 @@ fn maybe_make_cpython(repo_dir: &Path, wasi_sdk: &Path) -> Result<()> { fetch_extract(&url, Some(CPYTHON_TARBALL_SHA256), repo_dir)?; let source_dir = repo_dir.join(format!("Python-{CPYTHON_VERSION}")); - let mut patches = fs::read_dir(&patch_dir)? - .map(|entry| entry.map(|entry| entry.path())) - .collect::>>()?; - patches.sort(); - for patch in patches { + for patch in &patches { run(Command::new("patch") .current_dir(&source_dir) .arg("--batch") .arg("--forward") .arg("-p1") .arg("-i") - .arg(&patch))?; + .arg(patch))?; } + fs::write(source_dir.join(CPYTHON_SOURCE_IDENTITY_FILE), &identity)?; fs::rename(source_dir, &cpython_dir)?; } - 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))?; - } - - 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"]))?; + 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))?; } - // 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"))?; + 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, From c4b6bd1f61a6800c39556e70c1cc0676a01a2bb4 Mon Sep 17 00:00:00 2001 From: David Biro Date: Wed, 25 Nov 2026 23:40:02 +0000 Subject: [PATCH 12/14] Accept number types in checks and vary build entropy by app The checks before lowering accepted only int and float instances, but the lowering takes any object with __index__ or __float__, such as numpy.int64. They now extract the value as the lowering does and keep the TypeError and OverflowError messages. Pre-initialization entropy came from the linked component alone, so every app without native extensions got the same hash seed and random bytes. It now also covers the app name and the files of each Python path entry. build.rs removes a partly patched CPython tree before extracting, and applies only *.patch files. --- build.rs | 11 ++++++- runtime/src/check.rs | 46 ++++++++++++++-------------- src/lib.rs | 57 ++++++++++++++++++++++++++++++++--- src/test/python_source/app.py | 16 ++++++++++ src/test/tests.rs | 8 +++++ src/test/wit/tests.wit | 2 ++ 6 files changed, 113 insertions(+), 27 deletions(-) diff --git a/build.rs b/build.rs index bffd3494..e95716d0 100644 --- a/build.rs +++ b/build.rs @@ -329,6 +329,10 @@ fn maybe_make_cpython(repo_dir: &Path, wasi_sdk: &Path) -> Result<()> { 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)?; @@ -346,8 +350,13 @@ fn maybe_make_cpython(repo_dir: &Path, wasi_sdk: &Path) -> Result<()> { "https://www.python.org/ftp/python/{CPYTHON_VERSION}/Python-{CPYTHON_VERSION}.tgz" ); println!("cargo:warning=downloading CPython source code from {url}"); - fetch_extract(&url, Some(CPYTHON_TARBALL_SHA256), repo_dir)?; + // 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") diff --git a/runtime/src/check.rs b/runtime/src/check.rs index 33a18724..f8b82031 100644 --- a/runtime/src/check.rs +++ b/runtime/src/check.rs @@ -15,8 +15,8 @@ use { exceptions::{PyOverflowError, PyTypeError, PyValueError}, intern, types::{ - PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyFloat, PyInt, PyList, PyListMethods, - PyString, PyStringMethods, PyTuple, PyTupleMethods, PyTypeMethods, + PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods, PyString, + PyStringMethods, PyTuple, PyTupleMethods, PyTypeMethods, }, }, wit_dylib_ffi::Type, @@ -39,18 +39,7 @@ pub fn check( Type::S32 => int::(value, "s32", path), Type::S64 => int::(value, "s64", path), Type::Bool => Ok(()), - Type::F32 | Type::F64 => { - if value.is_instance_of::() || value.is_instance_of::() { - value.extract::().map(drop).map_err(|_| { - PyOverflowError::new_err(format!( - "{path}: {} is out of range for a float", - repr(value) - )) - }) - } else { - Err(type_error("float", value, path)) - } - } + Type::F32 | Type::F64 => number::(value, "float", "a float", path), Type::Char => { let s = value .cast::() @@ -268,14 +257,27 @@ fn int<'py, T: for<'a> pyo3::FromPyObject<'a, 'py>>( name: &str, path: &str, ) -> PyResult<()> { - if !value.is_instance_of::() { - return Err(type_error(name, value, path)); - } - value.extract::().map(drop).map_err(|_| { - PyOverflowError::new_err(format!( - "{path}: {} is out of range for {name}", - repr(value) - )) + 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| { + 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) + } }) } diff --git a/src/lib.rs b/src/lib.rs index d9117a09..2cee563a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -885,10 +885,12 @@ impl ComponentGenerator<'_> { // Pre-initialization saves everything the application computes into // the component, so derive its hash seed and random bytes from the - // linked component instead of from host entropy. Identical inputs then - // produce identical components. The runtime reseeds `random` from the - // host before the first export call. - let digest = Sha256::digest(&component); + // 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() @@ -1411,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/test/python_source/app.py b/src/test/python_source/app.py index 089951ab..bd831e50 100644 --- a/src/test/python_source/app.py +++ b/src/test/python_source/app.py @@ -285,6 +285,22 @@ def test_refcounts(self): for _ in range(5 * 1024): chunk = tests.get_bytes(1024 * 1024) + 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) expect_moved(lambda: tests.take_thing(thing)) diff --git a/src/test/tests.rs b/src/test/tests.rs index 55c29fa2..ace66be4 100644 --- a/src/test/tests.rs +++ b/src/test/tests.rs @@ -1246,6 +1246,14 @@ fn filesystem() -> Result<()> { }) } +#[test] +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| { diff --git a/src/test/wit/tests.wit b/src/test/wit/tests.wit index f6e0846d..4797391e 100644 --- a/src/test/wit/tests.wit +++ b/src/test/wit/tests.wit @@ -241,6 +241,8 @@ world tests { export test-refcounts: func(); + export lower-numbers: func() -> u32; + export reject-moved-resource: func(thing: thing); import take-thing: func(thing: thing); From 0aee3ff6e47ca3fa85b2084b2b37509147ce21eb Mon Sep 17 00:00:00 2001 From: David Biro Date: Wed, 25 Nov 2026 23:48:08 +0000 Subject: [PATCH 13/14] Convert the extraction error before checking its type --- runtime/src/check.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/runtime/src/check.rs b/runtime/src/check.rs index f8b82031..5f86c347 100644 --- a/runtime/src/check.rs +++ b/runtime/src/check.rs @@ -270,6 +270,7 @@ fn number<'py, T: for<'a> pyo3::FromPyObject<'a, 'py>>( 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}", From 7389c59bda4b73b8f91bda525d73e8f2b8f0e8d2 Mon Sep 17 00:00:00 2001 From: David Biro Date: Thu, 26 Nov 2026 13:42:43 +0000 Subject: [PATCH 14/14] Take wit-component from the golem-2.0 branch of wasm-tools The dlopen symbol-count fix is merged into the golem-2.0 branch of golemcloud/wasm-tools. The patch now pins that commit instead of the vendored copy, which is removed. Its source is the same as the vendored copy, and its sibling crates still come from crates.io. --- Cargo.lock | 1 + Cargo.toml | 11 +- vendor/wit-component/Cargo.toml | 225 - vendor/wit-component/LICENSE-APACHE | 201 - .../LICENSE-Apache-2.0_WITH_LLVM-exception | 220 - vendor/wit-component/LICENSE-MIT | 23 - vendor/wit-component/README.md | 251 -- vendor/wit-component/libdl.so | Bin 1358 -> 0 bytes vendor/wit-component/src/dummy.rs | 457 -- vendor/wit-component/src/encoding.rs | 3697 ----------------- vendor/wit-component/src/encoding/dedupe.rs | 164 - vendor/wit-component/src/encoding/fixup.rs | 906 ---- vendor/wit-component/src/encoding/types.rs | 538 --- vendor/wit-component/src/encoding/wit.rs | 408 -- vendor/wit-component/src/encoding/world.rs | 606 --- vendor/wit-component/src/gc.rs | 1134 ----- vendor/wit-component/src/lib.rs | 178 - vendor/wit-component/src/linking.rs | 1975 --------- vendor/wit-component/src/linking/metadata.rs | 654 --- vendor/wit-component/src/metadata.rs | 448 -- vendor/wit-component/src/printing.rs | 1533 ------- vendor/wit-component/src/semver_check.rs | 113 - vendor/wit-component/src/targets.rs | 44 - vendor/wit-component/src/validation.rs | 2868 ------------- 24 files changed, 7 insertions(+), 16648 deletions(-) delete mode 100644 vendor/wit-component/Cargo.toml delete mode 100644 vendor/wit-component/LICENSE-APACHE delete mode 100644 vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception delete mode 100644 vendor/wit-component/LICENSE-MIT delete mode 100644 vendor/wit-component/README.md delete mode 100755 vendor/wit-component/libdl.so delete mode 100644 vendor/wit-component/src/dummy.rs delete mode 100644 vendor/wit-component/src/encoding.rs delete mode 100644 vendor/wit-component/src/encoding/dedupe.rs delete mode 100644 vendor/wit-component/src/encoding/fixup.rs delete mode 100644 vendor/wit-component/src/encoding/types.rs delete mode 100644 vendor/wit-component/src/encoding/wit.rs delete mode 100644 vendor/wit-component/src/encoding/world.rs delete mode 100644 vendor/wit-component/src/gc.rs delete mode 100644 vendor/wit-component/src/lib.rs delete mode 100644 vendor/wit-component/src/linking.rs delete mode 100644 vendor/wit-component/src/linking/metadata.rs delete mode 100644 vendor/wit-component/src/metadata.rs delete mode 100644 vendor/wit-component/src/printing.rs delete mode 100644 vendor/wit-component/src/semver_check.rs delete mode 100644 vendor/wit-component/src/targets.rs delete mode 100644 vendor/wit-component/src/validation.rs diff --git a/Cargo.lock b/Cargo.lock index 08cb5e5d..c831327b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4822,6 +4822,7 @@ dependencies = [ [[package]] name = "wit-component" version = "0.258.3" +source = "git+https://github.com/golemcloud/wasm-tools?rev=801650b5c9e5e4aa32451283f7a6d14100f92889#801650b5c9e5e4aa32451283f7a6d14100f92889" dependencies = [ "anyhow", "bitflags", diff --git a/Cargo.toml b/Cargo.toml index f7b6cf31..01bf1355 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,10 +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"] -exclude = ["vendor/wit-component"] -# wit-component 0.258.3 from crates.io with 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. +# 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 = { path = "vendor/wit-component" } +wit-component = { git = "https://github.com/golemcloud/wasm-tools", rev = "801650b5c9e5e4aa32451283f7a6d14100f92889" } diff --git a/vendor/wit-component/Cargo.toml b/vendor/wit-component/Cargo.toml deleted file mode 100644 index 75a6ab0b..00000000 --- a/vendor/wit-component/Cargo.toml +++ /dev/null @@ -1,225 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2024" -rust-version = "1.85.0" -name = "wit-component" -version = "0.258.3" -authors = ["Peter Huene "] -build = false -autolib = false -autobins = false -autoexamples = false -autotests = false -autobenches = false -description = """ -Tooling for working with `*.wit` and component files together. -""" -homepage = "https://github.com/bytecodealliance/wasm-tools/tree/main/crates/wit-component" -documentation = "https://docs.rs/wit-component" -readme = "README.md" -license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" -repository = "https://github.com/bytecodealliance/wasm-tools/tree/main/crates/wit-component" - -[package.metadata.docs.rs] -all-features = true - -[features] -dummy-module = ["dep:wat"] -semver-check = ["dummy-module"] -wat = [ - "dep:wast", - "dep:wat", -] - -[lib] -name = "wit_component" -path = "src/lib.rs" - -[[test]] -name = "components" -path = "tests/components.rs" -harness = false - -[[test]] -name = "interfaces" -path = "tests/interfaces.rs" -harness = false - -[[test]] -name = "linking" -path = "tests/linking.rs" - -[[test]] -name = "merge" -path = "tests/merge.rs" - -[[test]] -name = "targets" -path = "tests/targets.rs" - -[[test]] -name = "wit" -path = "tests/wit.rs" - -[dependencies.anyhow] -version = "1.0.58" -default-features = false - -[dependencies.bitflags] -version = "2.3.3" - -[dependencies.indexmap] -version = "2.14.0" -features = ["std"] -default-features = false - -[dependencies.log] -version = "0.4.17" - -[dependencies.serde] -version = "1.0.166" -features = ["alloc"] -default-features = false - -[dependencies.serde_derive] -version = "1.0.166" - -[dependencies.serde_json] -version = "1" - -[dependencies.wasm-encoder] -version = "0.258.3" -features = [ - "std", - "wasmparser", -] -default-features = false - -[dependencies.wasm-metadata] -version = "0.258.3" -default-features = false - -[dependencies.wasmparser] -version = "0.258.3" -features = [ - "simd", - "std", - "component-model", - "simd", -] -default-features = false - -[dependencies.wast] -version = "258.0.3" -optional = true -default-features = false - -[dependencies.wat] -version = "1.258.3" -optional = true -default-features = false - -[dependencies.wit-parser] -version = "0.258.3" -features = [ - "decoding", - "serde", -] - -[dev-dependencies.env_logger] -version = "0.11" - -[dev-dependencies.glob] -version = "0.3.0" - -[dev-dependencies.libtest-mimic] -version = "0.8.1" - -[dev-dependencies.pretty_assertions] -version = "1.3.0" - -[dev-dependencies.toml] -version = "0.9.8" - -[dev-dependencies.wasm-metadata] -version = "0.258.3" -features = ["oci"] -default-features = false - -[dev-dependencies.wasmparser] -version = "0.258.3" -features = [ - "simd", - "std", - "component-model", - "features", -] -default-features = false - -[dev-dependencies.wasmprinter] -version = "0.258.3" -features = ["component-model"] -default-features = false - -[dev-dependencies.wat] -version = "1.258.3" -features = ["component-model"] -default-features = false - -[target.'cfg(not(target_family = "wasm"))'.dev-dependencies.wasmtime] -version = "36.0.7" -features = [ - "cranelift", - "component-model", - "runtime", - "gc-drc", -] -default-features = false - -[lints.clippy] -clone_on_copy = "warn" -manual_strip = "warn" -map_clone = "warn" -uninlined_format_args = "warn" -unnecessary_cast = "warn" -unnecessary_fallible_conversions = "warn" -unnecessary_mut_passed = "warn" -unnecessary_to_owned = "warn" - -[lints.clippy.all] -level = "allow" -priority = -1 - -[lints.rust] -deprecated_safe_2024 = "warn" -keyword_idents_2024 = "warn" -missing_unsafe_on_extern = "warn" -rust_2024_guarded_string_incompatible_syntax = "warn" -rust_2024_incompatible_pat = "warn" -rust_2024_prelude_collisions = "warn" -unsafe_attr_outside_unsafe = "warn" -unsafe_code = "deny" -unsafe_op_in_unsafe_fn = "warn" -unstable_features = "warn" -unused_extern_crates = "warn" -unused_import_braces = "warn" -unused_lifetimes = "warn" -unused_macro_rules = "warn" - -[lints.rust.unexpected_cfgs] -level = "warn" -priority = 0 -check-cfg = [ - "cfg(fuzzing)", - "cfg(debug_check_try_op)", -] diff --git a/vendor/wit-component/LICENSE-APACHE b/vendor/wit-component/LICENSE-APACHE deleted file mode 100644 index 16fe87b0..00000000 --- a/vendor/wit-component/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception b/vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception deleted file mode 100644 index f9d81955..00000000 --- a/vendor/wit-component/LICENSE-Apache-2.0_WITH_LLVM-exception +++ /dev/null @@ -1,220 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ---- LLVM Exceptions to the Apache 2.0 License ---- - -As an exception, if, as a result of your compiling your source code, portions -of this Software are embedded into an Object form of such source code, you -may redistribute such embedded portions in such Object form without complying -with the conditions of Sections 4(a), 4(b) and 4(d) of the License. - -In addition, if you combine or link compiled forms of this Software with -software that is licensed under the GPLv2 ("Combined Software") and if a -court of competent jurisdiction determines that the patent provision (Section -3), the indemnity provision (Section 9) or other Section of the License -conflicts with the conditions of the GPLv2, you may retroactively and -prospectively choose to deem waived or otherwise exclude such Section(s) of -the License, but only in their entirety and only with respect to the Combined -Software. - diff --git a/vendor/wit-component/LICENSE-MIT b/vendor/wit-component/LICENSE-MIT deleted file mode 100644 index 31aa7938..00000000 --- a/vendor/wit-component/LICENSE-MIT +++ /dev/null @@ -1,23 +0,0 @@ -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/vendor/wit-component/README.md b/vendor/wit-component/README.md deleted file mode 100644 index 2ba16c27..00000000 --- a/vendor/wit-component/README.md +++ /dev/null @@ -1,251 +0,0 @@ -# `wit-component` - -`wit-component` is a crate for creating and interacting with WebAssembly -components based on the [component model proposal][model]. - -## CLI usage - -The `wit-component` crate is available through the `wasm-tools` CLI suite under -two subcommands: - -``` -# Create a component from the input core wasm module -$ wasm-tools component new core.wasm -o component.wasm - -# Extract a `*.wit` interface from a component -$ wasm-tools component wit component.wasm -``` - -## Features - -* Creates WebAssembly [component binaries][model] from input core WebAssembly - modules. Input modules communicate with the [canonical ABI] to imported and - exported interfaces described with [`*.wit` files][wit]. The wit interface is - required to be embedded directly in the core wasm binary. - -* Supports "adapters" which can be used to bridge legacy core WebAssembly - imported functions into [component model][model] functions. Adapters are - themselves core wasm binaries which will be embedded into the final component. - An adapter's exports can be imported by the main core wasm binary and the - adapter can then call component model imports. - -* A [`*.wit`][wit] interface can be extracted from an existing component to - see the interface that it exports and intends to import. - -[model]: https://github.com/webassembly/component-model -[canonical ABI]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md -[wit]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md - -## Usage - -Note that this crate is intended to be a low-level detail of tooling for -components. Developers will not necessarily interact with this tooling -day-to-day, instead using wrappers such as -[`cargo-component`](https://github.com/bytecodealliance/cargo-component) which -will automatically execute `wit-component` to produce component binaries. - -First `wit-component` supports the wasm-based encoding of a WIT package: - -```sh -$ cat demo.wit -package my:demo; - -interface host { - hello: func(); -} - -world demo { - import host; -} - -$ wasm-tools component wit demo.wit -o demo.wasm --wasm - -# The output `demo.wasm` is a valid component binary -$ wasm-tools validate --features component-model demo.wasm -$ wasm-tools print demo.wasm - -# The `*.wit` file can be recovered from the `demo.wasm` as well -$ wasm-tools component wit demo.wasm -``` - -Toolchain authors can use `wit-component` to embed this component types section -into a core wasm binary. For a small demo here a raw `*.wat` wasm text file will -be used where the `demo.wit` argument is specified manually, however. - -```sh -$ cat demo.core.wat -(module - (import "my:demo/host" "hello" (func)) -) - -$ wasm-tools component embed demo.wit --world demo demo.core.wat -o demo.wasm - -# See that there's a new `component-type` custom section -$ wasm-tools objdump demo.wasm - -# Convert the core wasm into a component now -$ wasm-tools component new demo.wasm -o demo.component.wasm - -# Like before the output `demo.wasm` is a valid component binary -$ wasm-tools validate --features component-model demo.component.wasm -$ wasm-tools print demo.component.wasm - -# Additionally like before the `*.wit` interface can still be extracted -$ wasm-tools component wit demo.component.wasm -``` - -Here the `demo.component.wasm` can now be shipped to a component runtime or -embedded into hosts. - -## Custom Section Format - -Toolchains producing components typically have a workflow that looks something -like this: - -1. A bindings generator, often based on [`wit-bindgen`], is used to generate - source code. -2. A user writes source code against these bindings. -3. The language's compiler runs and produces a core WebAssembly module. -4. The core WebAssembly module is passed to this crate, producing a component. - -Steps (1) and (4) both take WIT as input and the goal is to make it such that -you don't have to specify the same WIT on both ends. Instead the WIT from (1) -should be seamlessly passed through to (4) without developers having to -explicitly opt-in to it otherwise. To do this, the `wit-component` crate and -componentization process uses a custom section. - -Part of the generated bindings from (1) above is source code (or similar) to -instruct the language to embed a custom section in the final binary. The custom -section's name must start with `component-type` but can have any number of -characters following it (e.g. it must match the regex `^component-type`). A -module is allowed to have any number of custom sections, including zero. - -Each custom section describes a WIT `world`. The unit of bindings generation is -a `world`, and each `world` used during step (1), which may possibly be in -multiple separate libraries, will be encoded into custom sections. Custom -sections typically have a name that includes the bindings generator, -the bindings generator's version, the world, and an optional use-provided -string. The contents of the custom section is a wasm-encoded WIT world. - -An example of this is that for this document: - -```wit -package a:b; - -world foo { - import host: func(); - export guest: func(); -} -``` - -this WIT world is encoded to wasm as: - -```wasm -(component - (type (;0;) - (component - (type (;0;) - (component - (type (;0;) (func)) - (import "host" (func (;0;) (type 0))) - (export (;1;) "guest" (func (type 0))) - ) - ) - (export (;0;) "a:b/foo" (component (type 0))) - ) - ) - (export (;1;) "foo" (type 0)) - (@custom "package-docs" "\00{}") - (@producers - (processed-by "wit-component" "0.218.0") - ) -) -``` - -More details about the wasm encoding of WIT can [be found -upstream](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md). - -Note here that the WIT world is just the single `component`-type export needed -to decode a single world, no other items are encoded into this wasm. - -When determining the `world` for a wasm component the componentization process -will read the input module, remove all sections that match `^component-type`, -extract the `world` that the type represents, and then "merge" all of the worlds -together. This merging process can fail if there are conflicts, but otherwise -duplicate imports are unified together. - -The final componentization process then understands the WIT `world` that's being -used and assumes that the component follows the naming scheme in -[`BuildTargets.md`](https://github.com/WebAssembly/component-model/pull/378) -upstream. (note that legacy names are also accepted at this time) - -## Merging Worlds - -Part of what `wit-component` does when creating a component is that it will -merge WIT `world`s from a number of sources. For example each custom section -above may have a world. For tools like `wasm-component-ld` worlds may also be -supplied on the command line. The final component, however, can only have one -set of imports and exports so a single `world` needs to be created from all -these input worlds. - -There are two workhorse methods for performing this merging process and both -live within the `wit-parser` crate: - -* [`wit_parser::Resolve::merge_worlds`] -* [`wit_parser::Resolve::merge_world_imports_based_on_semver`] - -The first is unconditionally used to merge all worlds together. Each custom -section, input argument, etc, are all merged with the -[`wit_parser::Resolve::merge_worlds`] method. This method may fail in certain -situations, primarily if there are duplicate exports specified in different -worlds (even if they're the same name they can't unify to one export as it's not -clear which export to pick). There are some other niche situations as well in -which the merging process can fail. - -Once all worlds are merged together with [`wit_parser::Resolve::merge_worlds`] -there is then an optional, but enabled by default, step to "trim" the world -down based on semver versions. This method is -[`wit_parser::Resolve::merge_world_imports_based_on_semver`] and is used to -change a world such as this: - -```wit -world { - import wasi:cli/environment@0.2.0; - import wasi:cli/environment@0.2.1; -} -``` - -into this - -```wit -world { - import wasi:cli/environment@0.2.1; -} -``` - -Notably imports are deduplicated based on their semver versions of interfaces. -The maximum version of the interface is always selected in the end. Only -interfaces which are semver compatible are deduplicated, for example this world -cannot be deduplicated further: - -```wit -world { - import wasi:cli/environment@0.2.0; - import wasi:cli/environment@0.3.0; -} -``` - -The main purpose for this deduplication is to enable internally within a -component various libraries and runtimes to evolve at a different pace with -respect to interface versions. By definition in WIT it should always be possible -to use a larger versions, so older imports are automatically "upgraded" to -newer imports in these situations. This ensures that, for example, only one -`wasi:io/poll/pollable` resource will be imported into the final component. If -two were imported there would be no way to actually functionally use the -resulting component. - -Note that this semver-deduplication process is enabled by default but can be -disabled through various options and flags in tooling. - -[`wit_parser::Resolve::merge_worlds`]: https://docs.rs/wit-parser/latest/wit_parser/struct.Resolve.html#method.merge_worlds -[`wit_parser::Resolve::merge_world_imports_based_on_semver`]: https://docs.rs/wit-parser/latest/wit_parser/struct.Resolve.html#method.merge_world_imports_based_on_semver diff --git a/vendor/wit-component/libdl.so b/vendor/wit-component/libdl.so deleted file mode 100755 index 8e91fbfaeaa826df5de1f9cf90d0f92fe9c84439..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1358 zcmZuxO>fjl5UsBE*We7y2?@=CwsYYWfrL1xC9)_i0%?_%5Eo}McEFCu9&9J8K>`D( z)r!L+R=dAp|H9t(XY6lT4!m~HBteQt?(QmAzgJbSduY}!1mT$m>8i}DlbyT5{X;Mj zkAz?5NAsPw7Pq}a(To02_Pv>i4ha(v21epPg)g(}%v)rOx>+#^W8F%Uyh`&Xn|I0a zX*KWix=Om)QJIM)k%<^5iQSPL&Du=%gL5mfL6?1A+cjlY*GPs@2(w;8!uWld8zUvve&^KU0n_B8 z2@78c?ze|!ED)?k5wXI`(aRzdyeoGV>%NG2Z!DD1lOh(19*rr~bYqPgv;KV`L*&3+ z0ABYYw)bmZ`#mNwMA)wh5lV#rvIy285%aG3f#d7j*T@-Q|CkJmNN$PHrij#NGEe}8 z4Vbeg_-h?%yiVk5vUtk5&MYWYP9%*F)krPQVoz}q`HGdVT;*%0E8;*qrdx_sfGG}? zPd@f3MT<(?hIm$Wlc-f4t3h>Xl`!LX>Pw@(wCXFd)&Yv#;jPFq`Iu!8yVqGV6ayFfcIDZ? z(NS(R)Bpz18%3m1M4~GW6xk{-6oC*{5k}K^)678;K34?fMiF3HMH~oiKp^fQD}*p0 zI93R}011p`Rk$kUzb`k8ad?#b3~~V~Knbum0!fGzei4GUDf}ez>J0ZeRrcDi)T>#A z+e{m?sylUDpH?a1Iv>@gx^UR5u8zyu%XV Vec { - let world = &resolve.worlds[world]; - let mut wat = String::new(); - wat.push_str("(module\n"); - for (name, import) in world.imports.iter() { - match import { - WorldItem::Function(func) => { - push_imported_func(&mut wat, resolve, None, func, mangling); - } - WorldItem::Interface { id: import, .. } => { - for (_, func) in resolve.interfaces[*import].functions.iter() { - push_imported_func(&mut wat, resolve, Some(name), func, mangling); - } - for (_, ty) in resolve.interfaces[*import].types.iter() { - push_imported_type_intrinsics(&mut wat, resolve, Some(name), *ty, mangling); - } - } - WorldItem::Type { id, .. } => { - push_imported_type_intrinsics(&mut wat, resolve, None, *id, mangling); - } - } - } - - if mangling.is_async() { - push_root_async_intrinsics(&mut wat); - } - - // Append any intrinsics which are imported but used in exported items - // (e.g. resources) - for (name, export) in world.exports.iter() { - match export { - WorldItem::Function(func) => { - push_exported_func_intrinsics(&mut wat, resolve, None, func, mangling); - } - WorldItem::Interface { id: export, .. } => { - for (_, func) in resolve.interfaces[*export].functions.iter() { - push_exported_func_intrinsics(&mut wat, resolve, Some(name), func, mangling); - } - for (_, ty) in resolve.interfaces[*export].types.iter() { - push_exported_type_intrinsics(&mut wat, resolve, Some(name), *ty, mangling); - } - } - WorldItem::Type { .. } => {} - } - } - - for (name, export) in world.exports.iter() { - match export { - WorldItem::Function(func) => { - push_func_export(&mut wat, resolve, None, func, mangling); - } - WorldItem::Interface { id: export, .. } => { - for (_, func) in resolve.interfaces[*export].functions.iter() { - push_func_export(&mut wat, resolve, Some(name), func, mangling); - } - for (_, ty) in resolve.interfaces[*export].types.iter() { - push_exported_resource_functions(&mut wat, resolve, name, *ty, mangling); - } - } - WorldItem::Type { .. } => {} - } - } - - let memory = resolve.wasm_export_name(mangling, WasmExport::Memory); - wat.push_str(&format!("(memory (export {memory:?}) 0)\n")); - let realloc = resolve.wasm_export_name(mangling, WasmExport::Realloc); - wat.push_str(&format!( - "(func (export {realloc:?}) (param i32 i32 i32 i32) (result i32) unreachable)\n" - )); - - let initialize = resolve.wasm_export_name(mangling, WasmExport::Initialize); - wat.push_str(&format!("(func (export {initialize:?}))")); - wat.push_str(")\n"); - - return wat::parse_str(&wat).unwrap(); -} - -fn push_imported_func( - wat: &mut String, - resolve: &Resolve, - interface: Option<&WorldKey>, - func: &Function, - mangling: ManglingAndAbi, -) { - let mangling = mangling.for_func(func); - let sig = resolve.wasm_signature(mangling.import_variant(), func); - - let (module, name) = resolve.wasm_import_name(mangling, WasmImport::Func { interface, func }); - wat.push_str(&format!("(import {module:?} {name:?} (func")); - push_tys(wat, "param", &sig.params); - push_tys(wat, "result", &sig.results); - wat.push_str("))\n"); - - if mangling.is_async() { - push_imported_future_and_stream_intrinsics(wat, resolve, mangling, false, interface, func); - } -} - -fn push_imported_type_intrinsics( - wat: &mut String, - resolve: &Resolve, - interface: Option<&WorldKey>, - resource: TypeId, - mangling: ManglingAndAbi, -) { - let ty = &resolve.types[resource]; - match ty.kind { - TypeDefKind::Resource => { - let (module, name) = resolve.wasm_import_name( - // Force using a sync ABI here at this time as support for async - // resource drop isn't implemented yet. - mangling.sync(), - WasmImport::ResourceIntrinsic { - interface, - resource, - intrinsic: ResourceIntrinsic::ImportedDrop, - }, - ); - wat.push_str(&format!("(import {module:?} {name:?} (func (param i32)))")); - - if mangling.is_async() { - // TODO: when wit-component supports async resource drop, - // implement it here too. - // let name = format!("[async-lower]{name}"); - // wat.push_str(&format!("(import {module:?} {name:?} (func (param i32)))")); - } - } - - // No other types with intrinsics at this time (futures/streams are - // relative to where they show up in function types. - _ => {} - } -} - -fn push_exported_func_intrinsics( - wat: &mut String, - resolve: &Resolve, - interface: Option<&WorldKey>, - func: &Function, - mangling: ManglingAndAbi, -) { - if !mangling.is_async() { - return; - } - - // For exported async functions, generate a `task.return` intrinsic. - let (module, name, sig) = func.task_return_import(resolve, interface, mangling.mangling()); - wat.push_str(&format!("(import {module:?} {name:?} (func")); - push_tys(wat, "param", &sig.params); - push_tys(wat, "result", &sig.results); - wat.push_str("))\n"); - - push_imported_future_and_stream_intrinsics(wat, resolve, mangling, true, interface, func); -} - -fn push_imported_future_and_stream_intrinsics( - wat: &mut String, - resolve: &Resolve, - mangling: ManglingAndAbi, - exported: bool, - interface: Option<&WorldKey>, - func: &Function, -) { - for id in func.find_futures_and_streams(resolve).into_iter() { - match &resolve.types[id].kind { - TypeDefKind::Future(_) => { - let mut module = None; - let mut intrinsic_name = |intrinsic, async_| { - let (m, name) = resolve.wasm_import_name( - mangling, - WasmImport::FutureIntrinsic { - interface, - func, - ty: Some(id), - intrinsic, - exported, - async_, - }, - ); - if let Some(prev) = &module { - debug_assert_eq!(prev, &m); - } else { - module = Some(m); - } - name - }; - - let new = intrinsic_name(FutureIntrinsic::New, false); - let read = intrinsic_name(FutureIntrinsic::Read, false); - let write = intrinsic_name(FutureIntrinsic::Write, false); - let cancel_read = intrinsic_name(FutureIntrinsic::CancelRead, false); - let cancel_write = intrinsic_name(FutureIntrinsic::CancelWrite, false); - let drop_readable = intrinsic_name(FutureIntrinsic::DropReadable, false); - let drop_writable = intrinsic_name(FutureIntrinsic::DropWritable, false); - let async_read = intrinsic_name(FutureIntrinsic::Read, true); - let async_write = intrinsic_name(FutureIntrinsic::Write, true); - let async_cancel_read = intrinsic_name(FutureIntrinsic::CancelRead, true); - let async_cancel_write = intrinsic_name(FutureIntrinsic::CancelWrite, true); - let module = module.unwrap(); - - wat.push_str(&format!( - r#" -(import {module:?} {new:?} (func (result i64))) -(import {module:?} {cancel_read:?} (func (param i32) (result i32))) -(import {module:?} {cancel_write:?} (func (param i32) (result i32))) -(import {module:?} {drop_readable:?} (func (param i32))) -(import {module:?} {drop_writable:?} (func (param i32))) -(import {module:?} {async_read:?} (func (param i32 i32) (result i32))) -(import {module:?} {async_write:?} (func (param i32 i32) (result i32))) - -;; deferred behind 🚝 -;;(import {module:?} {read:?} (func (param i32 i32) (result i32))) -;;(import {module:?} {write:?} (func (param i32 i32) (result i32))) -;;(import {module:?} {async_cancel_read:?} (func (param i32) (result i32))) -;;(import {module:?} {async_cancel_write:?} (func (param i32) (result i32))) -"# - )); - } - TypeDefKind::Stream(_) => { - let mut module = None; - let mut intrinsic_name = |intrinsic, async_| { - let (m, name) = resolve.wasm_import_name( - mangling, - WasmImport::StreamIntrinsic { - interface, - func, - ty: Some(id), - intrinsic, - exported, - async_, - }, - ); - if let Some(prev) = &module { - debug_assert_eq!(prev, &m); - } else { - module = Some(m); - } - name - }; - - let new = intrinsic_name(StreamIntrinsic::New, false); - let read = intrinsic_name(StreamIntrinsic::Read, false); - let write = intrinsic_name(StreamIntrinsic::Write, false); - let cancel_read = intrinsic_name(StreamIntrinsic::CancelRead, false); - let cancel_write = intrinsic_name(StreamIntrinsic::CancelWrite, false); - let drop_readable = intrinsic_name(StreamIntrinsic::DropReadable, false); - let drop_writable = intrinsic_name(StreamIntrinsic::DropWritable, false); - let async_read = intrinsic_name(StreamIntrinsic::Read, true); - let async_write = intrinsic_name(StreamIntrinsic::Write, true); - let async_cancel_read = intrinsic_name(StreamIntrinsic::CancelRead, true); - let async_cancel_write = intrinsic_name(StreamIntrinsic::CancelWrite, true); - let module = module.unwrap(); - - wat.push_str(&format!( - r#" -(import {module:?} {new:?} (func (result i64))) -(import {module:?} {cancel_read:?} (func (param i32) (result i32))) -(import {module:?} {cancel_write:?} (func (param i32) (result i32))) -(import {module:?} {drop_readable:?} (func (param i32))) -(import {module:?} {drop_writable:?} (func (param i32))) -(import {module:?} {async_read:?} (func (param i32 i32 i32) (result i32))) -(import {module:?} {async_write:?} (func (param i32 i32 i32) (result i32))) - -;; deferred behind 🚝 -;;(import {module:?} {read:?} (func (param i32 i32 i32) (result i32))) -;;(import {module:?} {write:?} (func (param i32 i32 i32) (result i32))) -;;(import {module:?} {async_cancel_read:?} (func (param i32) (result i32))) -;;(import {module:?} {async_cancel_write:?} (func (param i32) (result i32))) -"# - )); - } - _ => unreachable!(), - } - } -} - -fn push_exported_type_intrinsics( - wat: &mut String, - resolve: &Resolve, - interface: Option<&WorldKey>, - resource: TypeId, - mangling: ManglingAndAbi, -) { - let ty = &resolve.types[resource]; - match ty.kind { - TypeDefKind::Resource => { - let intrinsics = [ - (ResourceIntrinsic::ExportedDrop, "(func (param i32))"), - ( - ResourceIntrinsic::ExportedNew, - "(func (param i32) (result i32))", - ), - ( - ResourceIntrinsic::ExportedRep, - "(func (param i32) (result i32))", - ), - ]; - for (intrinsic, sig) in intrinsics { - let (module, name) = resolve.wasm_import_name( - mangling.sync(), - WasmImport::ResourceIntrinsic { - interface, - resource, - intrinsic, - }, - ); - wat.push_str(&format!("(import {module:?} {name:?} {sig})\n")); - } - } - - // No other types with intrinsics at this time (futures/streams - // relative to where they are in a function). - _ => {} - } -} - -fn push_exported_resource_functions( - wat: &mut String, - resolve: &Resolve, - interface: &WorldKey, - resource: TypeId, - mangling: ManglingAndAbi, -) { - let ty = &resolve.types[resource]; - match ty.kind { - TypeDefKind::Resource => {} - _ => return, - } - // Feign destructors for any resource that this interface - // exports - let name = resolve.wasm_export_name( - mangling, - WasmExport::ResourceDtor { - interface, - resource, - }, - ); - wat.push_str(&format!("(func (export {name:?}) (param i32))")); -} - -fn push_func_export( - wat: &mut String, - resolve: &Resolve, - interface: Option<&WorldKey>, - func: &Function, - mangling: ManglingAndAbi, -) { - let mangling = mangling.for_func(func); - let sig = resolve.wasm_signature(mangling.export_variant(), func); - let name = resolve.wasm_export_name( - mangling, - WasmExport::Func { - interface, - func, - kind: WasmExportKind::Normal, - }, - ); - wat.push_str(&format!("(func (export \"{name}\")")); - push_tys(wat, "param", &sig.params); - push_tys(wat, "result", &sig.results); - wat.push_str(" unreachable)\n"); - - match mangling { - ManglingAndAbi::Standard32 | ManglingAndAbi::Legacy(LiftLowerAbi::Sync) => { - let name = resolve.wasm_export_name( - mangling, - WasmExport::Func { - interface, - func, - kind: WasmExportKind::PostReturn, - }, - ); - wat.push_str(&format!("(func (export \"{name}\")")); - push_tys(wat, "param", &sig.results); - wat.push_str(")\n"); - } - ManglingAndAbi::Legacy(LiftLowerAbi::AsyncCallback) => { - let name = resolve.wasm_export_name( - mangling, - WasmExport::Func { - interface, - func, - kind: WasmExportKind::Callback, - }, - ); - wat.push_str(&format!( - "(func (export \"{name}\") (param i32 i32 i32) (result i32) unreachable)\n" - )); - } - ManglingAndAbi::Legacy(LiftLowerAbi::AsyncStackful) => {} - } -} - -fn push_tys(dst: &mut String, desc: &str, params: &[WasmType]) { - if params.is_empty() { - return; - } - dst.push_str(" ("); - dst.push_str(desc); - for ty in params { - dst.push(' '); - match ty { - WasmType::I32 => dst.push_str("i32"), - WasmType::I64 => dst.push_str("i64"), - WasmType::F32 => dst.push_str("f32"), - WasmType::F64 => dst.push_str("f64"), - WasmType::Pointer => dst.push_str("i32"), - WasmType::PointerOrI64 => dst.push_str("i64"), - WasmType::Length => dst.push_str("i32"), - } - } - dst.push(')'); -} - -fn push_root_async_intrinsics(dst: &mut String) { - dst.push_str( - r#" -(import "[export]$root" "[task-cancel]" (func)) -(import "$root" "[backpressure-inc]" (func)) -(import "$root" "[backpressure-dec]" (func)) -(import "$root" "[waitable-set-new]" (func (result i32))) -(import "$root" "[waitable-set-wait]" (func (param i32 i32) (result i32))) -(import "$root" "[waitable-set-poll]" (func (param i32 i32) (result i32))) -(import "$root" "[waitable-set-drop]" (func (param i32))) -(import "$root" "[waitable-join]" (func (param i32 i32))) -(import "$root" "[thread-yield]" (func (result i32))) -(import "$root" "[subtask-drop]" (func (param i32))) -(import "$root" "[subtask-cancel]" (func (param i32) (result i32))) -(import "$root" "[context-get-0]" (func (result i32))) -(import "$root" "[context-set-0]" (func (param i32))) - -;; deferred behind 🧵 upstream -;;(import "$root" "[cancellable][waitable-set-wait]" (func (param i32 i32) (result i32))) -;;(import "$root" "[cancellable][waitable-set-poll]" (func (param i32 i32) (result i32))) -;;(import "$root" "[cancellable][thread-yield]" (func (result i32))) -;;(import "$root" "[context-get-1]" (func (result i32))) -;;(import "$root" "[context-set-1]" (func (param i32))) - -;; deferred behind 📝 upstream -;;(import "$root" "[error-context-new-utf8]" (func (param i32 i32) (result i32))) -;;(import "$root" "[error-context-new-utf16]" (func (param i32 i32) (result i32))) -;;(import "$root" "[error-context-new-latin1+utf16]" (func (param i32 i32) (result i32))) -;;(import "$root" "[error-context-debug-message-utf8]" (func (param i32 i32))) -;;(import "$root" "[error-context-debug-message-utf16]" (func (param i32 i32))) -;;(import "$root" "[error-context-debug-message-latin1+utf16]" (func (param i32 i32))) -;;(import "$root" "[error-context-drop]" (func (param i32))) -"#, - ); -} diff --git a/vendor/wit-component/src/encoding.rs b/vendor/wit-component/src/encoding.rs deleted file mode 100644 index b5c08a04..00000000 --- a/vendor/wit-component/src/encoding.rs +++ /dev/null @@ -1,3697 +0,0 @@ -//! Support for encoding a core wasm module into a component. -//! -//! This module, at a high level, is tasked with transforming a core wasm -//! module into a component. This will process the imports/exports of the core -//! wasm module and translate between the `wit-parser` AST and the component -//! model binary format, producing a final component which will import -//! `*.wit` defined interfaces and export `*.wit` defined interfaces as well -//! with everything wired up internally according to the canonical ABI and such. -//! -//! This doc block here is not currently 100% complete and doesn't cover the -//! full functionality of this module. -//! -//! # Adapter Modules -//! -//! One feature of this encoding process which is non-obvious is the support for -//! "adapter modules". The general idea here is that historical host API -//! definitions have been around for quite some time, such as -//! `wasi_snapshot_preview1`, but these host API definitions are not compatible -//! with the canonical ABI or component model exactly. These APIs, however, can -//! in most situations be roughly adapted to component-model equivalents. This -//! is where adapter modules come into play, they're converting from some -//! arbitrary API/ABI into a component-model using API. -//! -//! An adapter module is a separately compiled `*.wasm` blob which will export -//! functions matching the desired ABI (e.g. exporting functions matching the -//! `wasi_snapshot_preview1` ABI). The `*.wasm` blob will then import functions -//! in the canonical ABI and internally adapt the exported functions to the -//! imported functions. The encoding support in this module is what wires -//! everything up and makes sure that everything is imported and exported to the -//! right place. Adapter modules currently always use "indirect lowerings" -//! meaning that a shim module is created and provided as the imports to the -//! main core wasm module, and the shim module is "filled in" at a later time -//! during the instantiation process. -//! -//! Adapter modules are not intended to be general purpose and are currently -//! very restrictive, namely: -//! -//! * They must import a linear memory and not define their own linear memory -//! otherwise. In other words they import memory and cannot use multi-memory. -//! * They cannot define any `elem` or `data` segments since otherwise there's -//! no knowledge ahead-of-time of where their data or element segments could -//! go. This means things like no panics, no indirect calls, etc. -//! * If the adapter uses a shadow stack, the global that points to it must be a -//! mutable `i32` named `__stack_pointer`. This stack is automatically -//! allocated with an injected `allocate_stack` function that will either use -//! the main module's `cabi_realloc` export (if present) or `memory.grow`. It -//! allocates only 64KB of stack space, and there is no protection if that -//! overflows. -//! * If the adapter has a global, mutable `i32` named `allocation_state`, it -//! will be used to keep track of stack allocation status and avoid infinite -//! recursion if the main module's `cabi_realloc` function calls back into the -//! adapter. `allocate_stack` will check this global on entry; if it is zero, -//! it will set it to one, then allocate the stack, and finally set it to two. -//! If it is non-zero, `allocate_stack` will do nothing and return immediately -//! (because either the stack has already been allocated or is in the process -//! of being allocated). If the adapter does not have an `allocation_state`, -//! `allocate_stack` will use `memory.grow` to allocate the stack; it will -//! _not_ use the main module's `cabi_realloc` even if it's available. -//! * If the adapter imports a `cabi_realloc` function, and the main module -//! exports one, they'll be linked together via an alias. If the adapter -//! imports such a function but the main module does _not_ export one, we'll -//! synthesize one based on `memory.grow` (which will trap for any size other -//! than 64KB). Note that the main module's `cabi_realloc` function may call -//! back into the adapter before the shadow stack has been allocated. In this -//! case (when `allocation_state` is zero or one), the adapter should return -//! whatever dummy value(s) it can immediately without touching the stack. -//! -//! This means that adapter modules are not meant to be written by everyone. -//! It's assumed that these will be relatively few and far between yet still a -//! crucial part of the transition process from to the component model since -//! otherwise there's no way to run a `wasi_snapshot_preview1` module within the -//! component model. - -use crate::StringEncoding; -use crate::metadata::{self, Bindgen, ModuleMetadata}; -use crate::validation::{ - Export, ExportMap, Import, ImportInstance, ImportMap, PayloadInfo, PayloadType, -}; -use anyhow::{Context, Result, anyhow, bail}; -use indexmap::{IndexMap, IndexSet}; -use std::borrow::Cow; -use std::collections::HashMap; -use std::hash::Hash; -use std::mem; -use wasm_encoder::reencode::{Reencode, RoundtripReencoder}; -use wasm_encoder::*; -use wasmparser::{Validator, WasmFeatures}; -use wit_parser::{ - Function, FunctionKind, InterfaceId, LiveTypes, Param, Resolve, Stability, Type, TypeDefKind, - TypeId, TypeOwner, WorldItem, WorldKey, - abi::{AbiVariant, WasmSignature, WasmType}, -}; - -const INDIRECT_TABLE_NAME: &str = "$imports"; -const SHIM_MEMORY_NAME: &str = "$memory"; -const TLS_BASE_GET: &str = "$get-tls-base"; -const TLS_BASE_SET: &str = "$set-tls-base"; - -pub(crate) mod fixup; - -mod wit; -pub use wit::{encode, encode_world}; - -mod types; -use types::{InstanceTypeEncoder, RootTypeEncoder, TypeEncodingMaps, ValtypeEncoder}; -mod world; -use world::{ComponentWorld, ImportedInterface, Lowering}; - -mod dedupe; -pub(crate) use dedupe::ModuleImportMap; -use wasm_metadata::AddMetadataField; - -fn to_val_type(ty: &WasmType) -> ValType { - match ty { - WasmType::I32 => ValType::I32, - WasmType::I64 => ValType::I64, - WasmType::F32 => ValType::F32, - WasmType::F64 => ValType::F64, - WasmType::Pointer => ValType::I32, - WasmType::PointerOrI64 => ValType::I64, - WasmType::Length => ValType::I32, - } -} - -fn import_func_name(f: &Function) -> String { - match f.kind { - FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => { - format!("import-func-{}", f.item_name()) - } - - // transform `[method]foo.bar` into `import-method-foo-bar` to - // have it be a valid kebab-name which can't conflict with - // anything else. - // - // There's probably a better and more "formal" way to do this - // but quick-and-dirty string manipulation should work well - // enough for now hopefully. - FunctionKind::Method(_) - | FunctionKind::AsyncMethod(_) - | FunctionKind::Static(_) - | FunctionKind::AsyncStatic(_) - | FunctionKind::Constructor(_) => { - format!( - "import-{}", - f.name.replace('[', "").replace([']', '.', ' '], "-") - ) - } - } -} - -bitflags::bitflags! { - /// Options in the `canon lower` or `canon lift` required for a particular - /// function. - #[derive(Copy, Clone, Debug)] - pub struct RequiredOptions: u8 { - /// A memory must be specified, typically the "main module"'s memory - /// export. - const MEMORY = 1 << 0; - /// A `realloc` function must be specified, typically named - /// `cabi_realloc`. - const REALLOC = 1 << 1; - /// A string encoding must be specified, which is always utf-8 for now - /// today. - const STRING_ENCODING = 1 << 2; - const ASYNC = 1 << 3; - } -} - -impl RequiredOptions { - fn for_import(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions { - let sig = resolve.wasm_signature(abi, func); - let mut ret = RequiredOptions::empty(); - // Lift the params and lower the results for imports - ret.add_lift(TypeContents::for_types( - resolve, - func.params.iter().map(|p| &p.ty), - )); - ret.add_lower(TypeContents::for_types(resolve, &func.result)); - - // If anything is indirect then `memory` will be required to read the - // indirect values. - if sig.retptr || sig.indirect_params { - ret |= RequiredOptions::MEMORY; - } - if abi == AbiVariant::GuestImportAsync { - ret |= RequiredOptions::ASYNC; - } - ret - } - - fn for_export(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions { - let sig = resolve.wasm_signature(abi, func); - let mut ret = RequiredOptions::empty(); - // Lower the params and lift the results for exports - ret.add_lower(TypeContents::for_types( - resolve, - func.params.iter().map(|p| &p.ty), - )); - ret.add_lift(TypeContents::for_types(resolve, &func.result)); - - // If anything is indirect then `memory` will be required to read the - // indirect values, but if the arguments are indirect then `realloc` is - // additionally required to allocate space for the parameters. - if sig.retptr || sig.indirect_params { - ret |= RequiredOptions::MEMORY; - if sig.indirect_params { - ret |= RequiredOptions::REALLOC; - } - } - if let AbiVariant::GuestExportAsync | AbiVariant::GuestExportAsyncStackful = abi { - ret |= RequiredOptions::ASYNC; - ret |= task_return_options_and_type(resolve, func).0; - } - ret - } - - fn for_payload( - resolve: &Resolve, - info: &PayloadInfo, - kind: &PayloadFuncKind, - async_: bool, - ) -> RequiredOptions { - let payload = info.payload(resolve); - let (wit_param, wit_result) = match kind { - PayloadFuncKind::StreamRead | PayloadFuncKind::FutureRead => (None, payload), - PayloadFuncKind::StreamWrite | PayloadFuncKind::FutureWrite => (payload, None), - }; - RequiredOptions::MEMORY - | RequiredOptions::for_import( - resolve, - &Function { - name: String::new(), - kind: FunctionKind::Freestanding, - params: match wit_param { - Some(ty) => vec![Param { - name: "a".to_string(), - ty, - span: Default::default(), - }], - None => Vec::new(), - }, - result: wit_result, - docs: Default::default(), - stability: Stability::Unknown, - span: Default::default(), - external_id: None, - }, - if async_ { - AbiVariant::GuestImportAsync - } else { - AbiVariant::GuestImport - }, - ) - } - - fn add_lower(&mut self, types: TypeContents) { - // If lists/strings are lowered into wasm then memory is required as - // usual but `realloc` is also required to allow the external caller to - // allocate space in the destination for the list/string. - if types.contains(TypeContents::NEEDS_MEMORY) { - *self |= RequiredOptions::MEMORY | RequiredOptions::REALLOC; - } - if types.contains(TypeContents::STRING) { - *self |= RequiredOptions::MEMORY - | RequiredOptions::STRING_ENCODING - | RequiredOptions::REALLOC; - } - } - - fn add_lift(&mut self, types: TypeContents) { - // Unlike for `lower` when lifting a string/list all that's needed is - // memory, since the string/list already resides in memory `realloc` - // isn't needed. - if types.contains(TypeContents::NEEDS_MEMORY) { - *self |= RequiredOptions::MEMORY; - } - if types.contains(TypeContents::STRING) { - *self |= RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING; - } - } - - fn into_iter( - self, - encoding: StringEncoding, - memory_index: Option, - realloc_index: Option, - ) -> Result> { - #[derive(Default)] - struct Iter { - options: [Option; 5], - current: usize, - count: usize, - } - - impl Iter { - fn push(&mut self, option: CanonicalOption) { - assert!(self.count < self.options.len()); - self.options[self.count] = Some(option); - self.count += 1; - } - } - - impl Iterator for Iter { - type Item = CanonicalOption; - - fn next(&mut self) -> Option { - if self.current == self.count { - return None; - } - let option = self.options[self.current]; - self.current += 1; - option - } - - fn size_hint(&self) -> (usize, Option) { - (self.count - self.current, Some(self.count - self.current)) - } - } - - impl ExactSizeIterator for Iter {} - - let mut iter = Iter::default(); - - if self.contains(RequiredOptions::MEMORY) { - iter.push(CanonicalOption::Memory(memory_index.ok_or_else(|| { - anyhow!("module does not export a memory named `memory`") - })?)); - } - - if self.contains(RequiredOptions::REALLOC) { - iter.push(CanonicalOption::Realloc(realloc_index.ok_or_else( - || anyhow!("module does not export a function named `cabi_realloc`"), - )?)); - } - - if self.contains(RequiredOptions::STRING_ENCODING) { - iter.push(encoding.into()); - } - - if self.contains(RequiredOptions::ASYNC) { - iter.push(CanonicalOption::Async); - } - - Ok(iter) - } -} - -bitflags::bitflags! { - /// Flags about what kinds of types are present within the recursive - /// structure of a type. - struct TypeContents: u8 { - const STRING = 1 << 0; - const NEEDS_MEMORY = 1 << 1; - } -} - -impl TypeContents { - fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator) -> Self { - let mut cur = TypeContents::empty(); - for ty in types { - cur |= Self::for_type(resolve, ty); - } - cur - } - - fn for_optional_types<'a>( - resolve: &Resolve, - types: impl Iterator>, - ) -> Self { - Self::for_types(resolve, types.flatten()) - } - - fn for_optional_type(resolve: &Resolve, ty: Option<&Type>) -> Self { - match ty { - Some(ty) => Self::for_type(resolve, ty), - None => Self::empty(), - } - } - - fn for_type(resolve: &Resolve, ty: &Type) -> Self { - match ty { - Type::Id(id) => match &resolve.types[*id].kind { - TypeDefKind::Handle(h) => match h { - wit_parser::Handle::Own(_) => Self::empty(), - wit_parser::Handle::Borrow(_) => Self::empty(), - }, - TypeDefKind::Resource => Self::empty(), - TypeDefKind::Record(r) => Self::for_types(resolve, r.fields.iter().map(|f| &f.ty)), - TypeDefKind::Tuple(t) => Self::for_types(resolve, t.types.iter()), - TypeDefKind::Flags(_) => Self::empty(), - TypeDefKind::Option(t) => Self::for_type(resolve, t), - TypeDefKind::Result(r) => { - Self::for_optional_type(resolve, r.ok.as_ref()) - | Self::for_optional_type(resolve, r.err.as_ref()) - } - TypeDefKind::Variant(v) => { - Self::for_optional_types(resolve, v.cases.iter().map(|c| c.ty.as_ref())) - } - TypeDefKind::Enum(_) => Self::empty(), - TypeDefKind::List(t) => Self::for_type(resolve, t) | Self::NEEDS_MEMORY, - TypeDefKind::Map(k, v) => { - Self::for_type(resolve, k) | Self::for_type(resolve, v) | Self::NEEDS_MEMORY - } - TypeDefKind::FixedLengthList(t, _elements) => Self::for_type(resolve, t), - TypeDefKind::Type(t) => Self::for_type(resolve, t), - TypeDefKind::Future(_) => Self::empty(), - TypeDefKind::Stream(_) => Self::empty(), - TypeDefKind::Unknown => unreachable!(), - }, - Type::String => Self::STRING, - _ => Self::empty(), - } - } -} - -/// State relating to encoding a component. -pub struct EncodingState<'a> { - /// The component being encoded. - component: ComponentBuilder, - /// The index into the core module index space for the inner core module. - /// - /// If `None`, the core module has not been encoded. - module_index: Option, - /// The index into the core instance index space for the inner core module. - /// - /// If `None`, the core module has not been instantiated. - instance_index: Option, - /// The index in the core memory index space for the exported memory. - /// - /// If `None`, then the memory has not yet been aliased. - memory_index: Option, - /// The index of the shim instance used for lowering imports into the core instance. - /// - /// If `None`, then the shim instance how not yet been encoded. - shim_instance_index: Option, - - /// A map of named adapter modules and the index that the module was defined - /// at. - adapter_modules: IndexMap<&'a str, u32>, - /// A map of adapter module instances and the index of their instance. - adapter_instances: IndexMap<&'a str, u32>, - - /// Imported/exported instances and what index they were imported as. - instances: IndexMap, - imported_funcs: IndexMap, - - /// Maps used when translating types to the component model binary format. - /// Note that imports and exports are stored in separate maps since they - /// need fresh hierarchies of types in case the same interface is both - /// imported and exported. - type_encoding_maps: TypeEncodingMaps<'a>, - - /// Cache of items that have been aliased from core instances. - /// - /// This is a helper to reduce the number of aliases created by ensuring - /// that repeated requests for the same item return the same index of an - /// original `core alias` item. - aliased_core_items: HashMap<(u32, String), u32>, - - /// Metadata about the world inferred from the input to `ComponentEncoder`. - info: &'a ComponentWorld<'a>, - - /// Maps from the instance an export came from, plus its original core - /// name, to the index of the wrapper function which the fixup module - /// defines for it. - /// - /// Used to invoke the task hook around lifted exports, post-return - /// functions, callbacks, and `realloc` functions. - export_task_initialization_wrappers: HashMap<(fixup::ImportedInstance, String), u32>, -} - -impl<'a> EncodingState<'a> { - fn encode_core_modules(&mut self) { - assert!(self.module_index.is_none()); - let idx = self - .component - .core_module_raw(Some("main"), &self.info.encoder.module); - self.module_index = Some(idx); - - for (name, adapter) in self.info.adapters.iter() { - let debug_name = if adapter.library_info.is_some() { - name.to_string() - } else { - format!("wit-component:adapter:{name}") - }; - let idx = if self.info.encoder.debug_names { - let mut add_meta = wasm_metadata::AddMetadata::default(); - add_meta.name = AddMetadataField::Set(debug_name.clone()); - let wasm = add_meta - .to_wasm(&adapter.wasm) - .expect("core wasm can get name added"); - self.component.core_module_raw(Some(&debug_name), &wasm) - } else { - self.component - .core_module_raw(Some(&debug_name), &adapter.wasm) - }; - let prev = self.adapter_modules.insert(name, idx); - assert!(prev.is_none()); - } - } - - fn root_import_type_encoder( - &mut self, - interface: Option, - ) -> RootTypeEncoder<'_, 'a> { - RootTypeEncoder { - state: self, - interface, - import_types: true, - } - } - - fn root_export_type_encoder( - &mut self, - interface: Option, - ) -> RootTypeEncoder<'_, 'a> { - RootTypeEncoder { - state: self, - interface, - import_types: false, - } - } - - fn instance_type_encoder(&mut self, interface: InterfaceId) -> InstanceTypeEncoder<'_, 'a> { - InstanceTypeEncoder { - state: self, - interface, - type_encoding_maps: Default::default(), - ty: Default::default(), - } - } - - fn encode_imports(&mut self, name_map: &HashMap) -> Result<()> { - let mut has_funcs = false; - for (name, info) in self.info.import_map.iter() { - match name { - Some(name) => { - self.encode_interface_import(name_map.get(name).unwrap_or(name), info)? - } - None => has_funcs = true, - } - } - - let resolve = &self.info.encoder.metadata.resolve; - let world = &resolve.worlds[self.info.encoder.metadata.world]; - - // FIXME: ideally this would use the liveness analysis from - // world-building to only encode live types, not all type in a world. - for (_name, item) in world.imports.iter() { - if let WorldItem::Type { id, .. } = item { - self.root_import_type_encoder(None) - .encode_valtype(resolve, &Type::Id(*id))?; - } - } - - if has_funcs { - let info = &self.info.import_map[&None]; - self.encode_root_import_funcs(info)?; - } - Ok(()) - } - - fn encode_interface_import(&mut self, name: &str, info: &ImportedInterface) -> Result<()> { - let resolve = &self.info.encoder.metadata.resolve; - let interface_id = info.interface.as_ref().unwrap(); - let interface_id = *interface_id; - let interface = &resolve.interfaces[interface_id]; - log::trace!("encoding imports for `{name}` as {interface_id:?}"); - let mut encoder = self.instance_type_encoder(interface_id); - - // First encode all type information - if let Some(live) = encoder.state.info.live_type_imports.get(&interface_id) { - for ty in live { - log::trace!( - "encoding extra type {ty:?} name={:?}", - resolve.types[*ty].name - ); - encoder.encode_valtype(resolve, &Type::Id(*ty))?; - } - } - - // Next encode all required functions from this imported interface - // into the instance type. - for (_, func) in interface.functions.iter() { - if !(info - .lowerings - .contains_key(&(func.name.clone(), AbiVariant::GuestImport)) - || info - .lowerings - .contains_key(&(func.name.clone(), AbiVariant::GuestImportAsync))) - { - continue; - } - log::trace!("encoding function type for `{}`", func.name); - let idx = encoder.encode_func_type(resolve, func)?; - - encoder.ty.export( - crate::encoding::types::extern_name(&func.name, func.external_id.as_deref()), - ComponentTypeRef::Func(idx), - ); - } - - let ty = encoder.ty; - // Don't encode empty instance types since they're not - // meaningful to the runtime of the component anyway. - if ty.is_empty() { - return Ok(()); - } - let instance_type_idx = self - .component - .type_instance(Some(&format!("ty-{name}")), &ty); - let instance_idx = self.component.import( - wasm_encoder::ComponentExternName { - name: name.into(), - implements: info.implements.as_deref().map(|s| s.into()), - external_id: info.external_id.as_deref().map(|s| s.into()), - version_suffix: None, - }, - ComponentTypeRef::Instance(instance_type_idx), - ); - let prev = self.instances.insert(interface_id, instance_idx); - assert!(prev.is_none()); - Ok(()) - } - - fn encode_root_import_funcs(&mut self, info: &ImportedInterface) -> Result<()> { - let resolve = &self.info.encoder.metadata.resolve; - let world = self.info.encoder.metadata.world; - for (name, item) in resolve.worlds[world].imports.iter() { - let func = match item { - WorldItem::Function(f) => f, - WorldItem::Interface { .. } | WorldItem::Type { .. } => continue, - }; - let name = resolve.name_world_key(name); - if !(info - .lowerings - .contains_key(&(name.clone(), AbiVariant::GuestImport)) - || info - .lowerings - .contains_key(&(name.clone(), AbiVariant::GuestImportAsync))) - { - continue; - } - log::trace!("encoding function type for `{}`", func.name); - let idx = self - .root_import_type_encoder(None) - .encode_func_type(resolve, func)?; - let func_idx = self.component.import( - crate::encoding::types::extern_name(name.as_str(), func.external_id.as_deref()), - ComponentTypeRef::Func(idx), - ); - let prev = self.imported_funcs.insert(name, func_idx); - assert!(prev.is_none()); - } - Ok(()) - } - - fn alias_instance_type_export(&mut self, interface: InterfaceId, id: TypeId) -> u32 { - let ty = &self.info.encoder.metadata.resolve.types[id]; - let name = ty.name.as_ref().expect("type must have a name"); - let instance = self.instances[&interface]; - self.component - .alias_export(instance, name, ComponentExportKind::Type) - } - - fn encode_core_instantiation( - &mut self, - fixup_hook: Option<&mut dyn FnMut(&mut fixup::FixupModule) -> Result<()>>, - ) -> Result<()> { - // Encode a shim instantiation if needed - let (shims, mut fixups) = self.encode_shim_instantiation()?; - - // Next declare any types needed for imported intrinsics. This - // populates `export_type_map` and will additionally be used for - // imports to modules instantiated below. - self.declare_types_for_imported_intrinsics(&shims)?; - - // Next instantiate the main module. This provides the linear memory to - // use for all future adapters and enables creating indirect lowerings - // at the end. - self.instantiate_main_module(&shims)?; - - for (name, _adapter) in self.info.adapters.iter() { - self.instantiate_adapter_module(&shims, name)?; - } - - if let Some(initialize) = self.info.info.exports.initialize() { - fixups.add_initialize(initialize)?; - } - - if let Some(hook) = fixup_hook { - hook(&mut fixups)?; - } - - // With all the relevant core wasm instances in play now the original shim - // module, if present, can be filled in with lowerings/adapters/etc. - fixups.instantiate(&shims, self)?; - - Ok(()) - } - - fn lookup_resource_index(&mut self, id: TypeId) -> u32 { - let resolve = &self.info.encoder.metadata.resolve; - let ty = &resolve.types[id]; - match ty.owner { - // If this resource is owned by a world then it's a top-level - // resource which means it must have already been translated so - // it's available for lookup in `import_type_map`. - TypeOwner::World(_) => self.type_encoding_maps.id_to_index[&id], - TypeOwner::Interface(i) => { - let instance = self.instances[&i]; - let name = ty.name.as_ref().expect("resources must be named"); - self.component - .alias_export(instance, name, ComponentExportKind::Type) - } - TypeOwner::None => panic!("resources must have an owner"), - } - } - - fn encode_exports(&mut self, module: CustomModule) -> Result<()> { - let resolve = &self.info.encoder.metadata.resolve; - let exports = match module { - CustomModule::Main => &self.info.encoder.main_module_exports, - CustomModule::Adapter(name) => &self.info.encoder.adapters[name].required_exports, - }; - - if exports.is_empty() { - return Ok(()); - } - - let mut interface_func_core_names = IndexMap::new(); - let mut world_func_core_names = IndexMap::new(); - for (core_name, export) in self.info.exports_for(module).iter() { - match export { - Export::WorldFunc(_, name, _) => { - let prev = world_func_core_names.insert(name, core_name); - assert!(prev.is_none()); - } - Export::InterfaceFunc(key, _, name, _) => { - let prev = interface_func_core_names - .entry(key) - .or_insert(IndexMap::new()) - .insert(name.as_str(), core_name); - assert!(prev.is_none()); - } - Export::WorldFuncCallback(..) - | Export::InterfaceFuncCallback(..) - | Export::WorldFuncPostReturn(..) - | Export::InterfaceFuncPostReturn(..) - | Export::ResourceDtor(..) - | Export::Memory - | Export::GeneralPurposeRealloc - | Export::GeneralPurposeExportRealloc - | Export::GeneralPurposeImportRealloc - | Export::Initialize - | Export::ReallocForAdapter - | Export::IndirectFunctionTable - | Export::WasmTaskHook => continue, - } - } - - let world = &resolve.worlds[self.info.encoder.metadata.world]; - - for export_name in exports { - let export_string = resolve.name_world_key(export_name); - match &world.exports[export_name] { - WorldItem::Function(func) => { - let ty = self - .root_import_type_encoder(None) - .encode_func_type(resolve, func)?; - let core_name = world_func_core_names[&func.name]; - let idx = self.encode_lift(module, &core_name, export_name, func, ty)?; - self.component.export( - crate::encoding::types::extern_name( - &export_string, - func.external_id.as_deref(), - ), - ComponentExportKind::Func, - idx, - None, - ); - } - item @ WorldItem::Interface { id, .. } => { - let core_names = interface_func_core_names.get(export_name); - self.encode_interface_export( - &export_string, - module, - export_name, - item, - *id, - core_names, - )?; - } - WorldItem::Type { .. } => unreachable!(), - } - } - - Ok(()) - } - - fn encode_interface_export( - &mut self, - export_name: &str, - module: CustomModule<'_>, - key: &WorldKey, - item: &WorldItem, - export: InterfaceId, - interface_func_core_names: Option<&IndexMap<&str, &str>>, - ) -> Result<()> { - log::trace!("encode interface export `{export_name}`"); - let resolve = &self.info.encoder.metadata.resolve; - - // First execute a `canon lift` for all the functions in this interface - // from the core wasm export. This requires type information but notably - // not exported type information since we don't want to export this - // interface's types from the root of the component. Each lifted - // function is saved off into an `imports` array to get imported into - // the nested component synthesized below. - let mut imports = Vec::new(); - let mut root = self.root_export_type_encoder(Some(export)); - for (_, func) in &resolve.interfaces[export].functions { - let core_name = interface_func_core_names.unwrap()[func.name.as_str()]; - let ty = root.encode_func_type(resolve, func)?; - let func_index = root.state.encode_lift(module, &core_name, key, func, ty)?; - imports.push(( - import_func_name(func), - ComponentExportKind::Func, - func_index, - )); - } - - // Next a nested component is created which will import the functions - // above and then reexport them. The purpose of them is to "re-type" the - // functions through type ascription on each `func` item. - let mut nested = NestedComponentTypeEncoder { - component: ComponentBuilder::default(), - type_encoding_maps: Default::default(), - export_types: false, - interface: export, - state: self, - imports: IndexMap::new(), - }; - - // Import all transitively-referenced types from other interfaces into - // this component. This temporarily switches the `interface` listed to - // the interface of the referred-to-type to generate the import. After - // this loop `interface` is rewritten to `export`. - // - // Each component is a standalone "island" so the necessary type - // information needs to be rebuilt within this component. This ensures - // that we're able to build a valid component and additionally connect - // all the type information to the outer context. - let mut types_to_import = LiveTypes::default(); - types_to_import.add_interface(resolve, export); - let exports_used = &nested.state.info.exports_used[&export]; - for ty in types_to_import.iter() { - if let TypeOwner::Interface(owner) = resolve.types[ty].owner { - if owner == export { - // Here this deals with the current exported interface which - // is handled below. - continue; - } - - // Ensure that `self` has encoded this type before. If so this - // is a noop but otherwise it generates the type here. - let mut encoder = if exports_used.contains(&owner) { - nested.state.root_export_type_encoder(Some(export)) - } else { - nested.state.root_import_type_encoder(Some(export)) - }; - encoder.encode_valtype(resolve, &Type::Id(ty))?; - - // Next generate the same type but this time within the - // component itself. The type generated above (or prior) will be - // used to satisfy this type import. - nested.interface = owner; - nested.encode_valtype(resolve, &Type::Id(ty))?; - } - } - nested.interface = export; - - // Record the map of types imported to their index at where they were - // imported. This is used after imports are encoded as exported types - // will refer to these. - let imported_type_maps = nested.type_encoding_maps.clone(); - - // Handle resource types for this instance specially, namely importing - // them into the nested component. This models how the resource is - // imported from its definition in the outer component to get reexported - // internally. This chiefly avoids creating a second resource which is - // not desired in this situation. - let mut resources = HashMap::new(); - for (_name, ty) in resolve.interfaces[export].types.iter() { - if !matches!(resolve.types[*ty].kind, TypeDefKind::Resource) { - continue; - } - let idx = match nested.encode_valtype(resolve, &Type::Id(*ty))? { - ComponentValType::Type(idx) => idx, - _ => unreachable!(), - }; - resources.insert(*ty, idx); - } - - // Next import each function of this interface. This will end up - // defining local types as necessary or using the types as imported - // above. - for (_, func) in resolve.interfaces[export].functions.iter() { - let ty = nested.encode_func_type(resolve, func)?; - nested - .component - .import(&import_func_name(func), ComponentTypeRef::Func(ty)); - } - - // Swap the `nested.type_map` which was previously from `TypeId` to - // `u32` to instead being from `u32` to `TypeId`. This reverse map is - // then used in conjunction with `self.type_map` to satisfy all type - // imports of the nested component generated. The type import's index in - // the inner component is translated to a `TypeId` via `reverse_map` - // which is then translated back to our own index space via `type_map`. - let reverse_map = nested - .type_encoding_maps - .id_to_index - .drain() - .map(|p| (p.1, p.0)) - .collect::>(); - nested.type_encoding_maps.def_to_index.clear(); - for (name, idx) in nested.imports.drain(..) { - let id = reverse_map[&idx]; - let idx = nested.state.type_encoding_maps.id_to_index[&id]; - imports.push((name, ComponentExportKind::Type, idx)) - } - - // Before encoding exports reset the type map to what all was imported - // from foreign interfaces. This will enable any encoded types below to - // refer to imports which, after type substitution, will point to the - // correct type in the outer component context. - nested.type_encoding_maps = imported_type_maps; - - // Next the component reexports all of its imports, but notably uses the - // type ascription feature to change the type of the function. Note that - // no structural change is happening to the types here but instead types - // are getting proper names and such now that this nested component is a - // new type index space. Hence the `export_types = true` flag here which - // flows through the type encoding and when types are emitted. - nested.export_types = true; - nested.type_encoding_maps.func_type_map.clear(); - - // To start off all type information is encoded. This will be used by - // functions below but notably this also has special handling for - // resources. Resources reexport their imported resource type under - // the final name which achieves the desired goal of threading through - // the original resource without creating a new one. - for (_, id) in resolve.interfaces[export].types.iter() { - let ty = &resolve.types[*id]; - match ty.kind { - TypeDefKind::Resource => { - let idx = nested.component.export( - crate::encoding::types::extern_name( - ty.name.as_ref().expect("resources must be named"), - ty.external_id.as_deref(), - ), - ComponentExportKind::Type, - resources[id], - None, - ); - nested.type_encoding_maps.id_to_index.insert(*id, idx); - } - _ => { - nested.encode_valtype(resolve, &Type::Id(*id))?; - } - } - } - - for (i, (_, func)) in resolve.interfaces[export].functions.iter().enumerate() { - let ty = nested.encode_func_type(resolve, func)?; - nested.component.export( - crate::encoding::types::extern_name(&func.name, func.external_id.as_deref()), - ComponentExportKind::Func, - i as u32, - Some(ComponentTypeRef::Func(ty)), - ); - } - - // Embed the component within our component and then instantiate it with - // the lifted functions. That final instance is then exported under the - // appropriate name as the final typed export of this component. - let component = nested.component; - let component_index = self - .component - .component(Some(&format!("{export_name}-shim-component")), component); - let instance_index = self.component.instantiate( - Some(&format!("{export_name}-shim-instance")), - component_index, - imports, - ); - let idx = self.component.export( - wasm_encoder::ComponentExternName { - name: export_name.into(), - implements: resolve.implements_value(key, item).map(|s| s.into()), - external_id: resolve.external_id_value(key, item).map(|s| s.into()), - version_suffix: None, - }, - ComponentExportKind::Instance, - instance_index, - None, - ); - let prev = self.instances.insert(export, idx); - assert!(prev.is_none()); - - // After everything is all said and done remove all the type information - // about type exports of this interface. Any entries in the map - // currently were used to create the instance above but aren't the - // actual copy of the exported type since that comes from the exported - // instance itself. Entries will be re-inserted into this map as - // necessary via aliases from the exported instance which is the new - // source of truth for all these types. - for (_name, id) in resolve.interfaces[export].types.iter() { - self.type_encoding_maps.id_to_index.remove(id); - self.type_encoding_maps - .def_to_index - .remove(&resolve.types[*id].kind); - } - - return Ok(()); - - struct NestedComponentTypeEncoder<'state, 'a> { - component: ComponentBuilder, - type_encoding_maps: TypeEncodingMaps<'a>, - export_types: bool, - interface: InterfaceId, - state: &'state mut EncodingState<'a>, - imports: IndexMap, - } - - impl<'a> ValtypeEncoder<'a> for NestedComponentTypeEncoder<'_, 'a> { - fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { - self.component.type_defined(None) - } - fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { - self.component.type_function(None) - } - fn export_type( - &mut self, - idx: u32, - name: wasm_encoder::ComponentExternName<'a>, - ) -> Option { - if self.export_types { - Some( - self.component - .export(name, ComponentExportKind::Type, idx, None), - ) - } else { - let name = self.unique_import_name(&name.name); - let ret = self - .component - .import(&name, ComponentTypeRef::Type(TypeBounds::Eq(idx))); - self.imports.insert(name, ret); - Some(ret) - } - } - fn export_resource(&mut self, name: wasm_encoder::ComponentExternName<'a>) -> u32 { - if self.export_types { - panic!("resources should already be exported") - } else { - let name = self.unique_import_name(&name.name); - let ret = self - .component - .import(&name, ComponentTypeRef::Type(TypeBounds::SubResource)); - self.imports.insert(name, ret); - ret - } - } - fn import_type(&mut self, _: InterfaceId, _id: TypeId) -> u32 { - unreachable!() - } - fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { - &mut self.type_encoding_maps - } - fn interface(&self) -> Option { - Some(self.interface) - } - } - - impl NestedComponentTypeEncoder<'_, '_> { - fn unique_import_name(&mut self, name: &str) -> String { - let mut name = format!("import-type-{name}"); - let mut n = 0; - while self.imports.contains_key(&name) { - name = format!("{name}{n}"); - n += 1; - } - name - } - } - } - - fn encode_lift( - &mut self, - module: CustomModule<'_>, - core_name: &str, - key: &WorldKey, - func: &Function, - ty: u32, - ) -> Result { - let resolve = &self.info.encoder.metadata.resolve; - let metadata = self.info.module_metadata_for(module); - - let core_alias_export = - |me: &mut Self, core_name: &str| me.hooked_core_alias_export(module, core_name); - - let core_func_index = core_alias_export(self, core_name); - let exports = self.info.exports_for(module); - - let options = RequiredOptions::for_export( - resolve, - func, - exports - .abi(key, func) - .ok_or_else(|| anyhow!("no ABI found for {}", func.name))?, - ); - - let encoding = metadata - .export_encodings - .get(resolve, key, &func.name) - .unwrap(); - let exports = self.info.exports_for(module); - let realloc_index = if options.contains(RequiredOptions::REALLOC) { - let realloc = exports.export_realloc_for(key, &func.name); - resolve_realloc(self.info, module, realloc) - .map(|(module, name)| self.hooked_core_alias_export(module, name)) - } else { - None - }; - let mut options = options - .into_iter(encoding, self.memory_index, realloc_index)? - .collect::>(); - - if let Some(post_return) = exports.post_return(key, func) { - let post_return = core_alias_export(self, post_return); - options.push(CanonicalOption::PostReturn(post_return)); - } - if let Some(callback) = exports.callback(key, func) { - let callback = core_alias_export(self, callback); - options.push(CanonicalOption::Callback(callback)); - } - let func_index = self - .component - .lift_func(Some(&func.name), core_func_index, ty, options); - Ok(func_index) - } - - fn encode_shim_instantiation(&mut self) -> Result<(Shims<'a>, fixup::FixupModule)> { - let mut ret = Shims::default(); - let mut fixups = fixup::FixupModule::default(); - - ret.append_indirect(self.info, CustomModule::Main) - .context("failed to register indirect shims for main module")?; - - // For all required adapter modules a shim is created for each required - // function and additionally a set of shims are created for the - // interface imported into the shim module itself. - for (adapter_name, _adapter) in self.info.adapters.iter() { - ret.append_indirect(self.info, CustomModule::Adapter(adapter_name)) - .with_context(|| { - format!("failed to register indirect shims for adapter {adapter_name}") - })?; - } - - // Determine if a TLS global needs to be synthesized here by seeing if - // it was imported into any module. - let tls_base_global_type = if self.info.can_use_context_slot_1() { - None - } else { - let infos = [&self.info.info] - .into_iter() - .chain(self.info.adapters.values().map(|a| &a.info)); - let mut ret = None; - for info in infos { - for (_, _, import) in info.imports.imports() { - let ty = match import { - Import::TlsBaseGet { ty } | Import::TlsBaseSet { ty } => *ty, - _ => continue, - }; - let prev = *ret.get_or_insert(ty); - if prev != ty { - bail!("conflicting TLS base pointer types `{prev}` and `{ty}`"); - } - } - } - match ret { - Some(ret) => Some(ret.try_into()?), - None => None, - } - }; - - if ret.shims.is_empty() - && self.info.info.imports.imported_memory().is_none() - && tls_base_global_type.is_none() - { - return Ok((ret, fixups)); - } - - assert!(self.shim_instance_index.is_none()); - - // This function encodes a single module, the shim module, which defines - // functions to indirectly call through tables or globals. This shim - // additionally may contain the memory for the main module if it needs - // it as well as the TLS base pointer for the program. This shim is - // instantiated before the main module. - - let mut types = TypeSection::new(); - let mut shim_globals = GlobalSection::new(); - let mut shim_tables = TableSection::new(); - let mut shim_memories = MemorySection::new(); - let mut shim_functions = FunctionSection::new(); - let mut shim_exports = ExportSection::new(); - let mut shim_code = CodeSection::new(); - let mut sigs = IndexMap::new(); - let mut trapping_stubs = IndexMap::new(); - let mut func_indexes = Vec::new(); - let mut func_names = NameMap::new(); - - let mut intern_type = - |types: &mut TypeSection, params: Vec, results: Vec| { - *sigs - .entry((params, results)) - .or_insert_with_key(|(params, results)| { - let index = types.len(); - types - .ty() - .function(params.iter().copied(), results.iter().copied()); - index - }) - }; - - for shim in ret.shims.values() { - let type_index = intern_type( - &mut types, - shim.sig.params.iter().map(to_val_type).collect(), - shim.sig.results.iter().map(to_val_type).collect(), - ); - - let trapping_stub = if self.info.encoder.shim_return_call_ref { - // Generate a stub which is `unreachable` for the initializer of - // this global. This can be deduplicated by type signature. - Some(*trapping_stubs.entry(type_index).or_insert_with(|| { - let mut stub = wasm_encoder::Function::new(std::iter::empty()); - stub.instructions().unreachable().end(); - let index = shim_code.len(); - shim_functions.function(type_index); - shim_code.function(&stub); - func_names.append(index, "trap stub before initialization"); - index - })) - } else { - None - }; - - let func_index = shim_functions.len(); - shim_functions.function(type_index); - let mut func = wasm_encoder::Function::new(std::iter::empty()); - for i in 0..shim.sig.params.len() { - func.instructions().local_get(i as u32); - } - fixups.add_shim(&self.info.encoder, shim)?; - if self.info.encoder.shim_return_call_ref { - // Generate a global-per-function which gets exported from the - // module and then filled in later. - let global = shim_globals.len(); - let ty = GlobalType { - val_type: RefType { - nullable: false, - heap_type: HeapType::Concrete(type_index), - } - .into(), - mutable: true, - shared: false, - }; - let global_name = format!("g{}", shim.name); - shim_globals.global(ty, &ConstExpr::ref_func(trapping_stub.unwrap())); - shim_exports.export(&global_name, ExportKind::Global, global); - - func.instructions().global_get(global); - func.instructions().return_call_ref(type_index); - } else { - func.instructions().i32_const(func_index as i32); - func.instructions().call_indirect(0, type_index); - } - func.instructions().end(); - shim_code.function(&func); - shim_exports.export(&shim.name, ExportKind::Func, func_index); - - func_indexes.push(func_index); - func_names.append(func_index, &shim.debug_name); - } - - if !ret.shims.is_empty() && !self.info.encoder.shim_return_call_ref { - let table_type = TableType { - element_type: RefType::FUNCREF, - minimum: ret.shims.len() as u64, - maximum: Some(ret.shims.len() as u64), - table64: false, - shared: false, - }; - - shim_tables.table(table_type); - shim_exports.export(INDIRECT_TABLE_NAME, ExportKind::Table, 0); - } - - // If the main module imports its memory then define it here and export - // it for everyone else to use. - if let Some(ty) = self.info.info.imports.imported_memory() { - shim_memories.memory(RoundtripReencoder.memory_type(ty)?); - shim_exports.export(SHIM_MEMORY_NAME, ExportKind::Memory, 0); - } - - // If the TLS base pointer is stored in a `global`, as opposed to a - // `context` slot, then define that global here along with accessors - // for it which everyone else uses. - if let Some(ty) = tls_base_global_type { - let get_ty = intern_type(&mut types, Vec::new(), vec![ty]); - let set_ty = intern_type(&mut types, vec![ty], Vec::new()); - - let global = shim_globals.len(); - shim_globals.global( - GlobalType { - val_type: ty, - mutable: true, - shared: false, - }, - &match ty { - ValType::I64 => ConstExpr::i64_const(0), - ValType::I32 => ConstExpr::i32_const(0), - _ => unreachable!(), - }, - ); - - let get = shim_functions.len(); - shim_functions.function(get_ty); - let mut func = wasm_encoder::Function::new(std::iter::empty()); - func.instructions().global_get(global).end(); - shim_code.function(&func); - shim_exports.export(TLS_BASE_GET, ExportKind::Func, get); - func_names.append(get, TLS_BASE_GET); - - let set = shim_functions.len(); - shim_functions.function(set_ty); - let mut func = wasm_encoder::Function::new(std::iter::empty()); - func.instructions().local_get(0).global_set(global).end(); - shim_code.function(&func); - shim_exports.export(TLS_BASE_SET, ExportKind::Func, set); - func_names.append(set, TLS_BASE_SET); - } - - let mut shim_names = NameSection::new(); - shim_names.module("wit-component:shim"); - shim_names.functions(&func_names); - - let mut shim = Module::new(); - shim.section(&types); - if !shim_functions.is_empty() { - shim.section(&shim_functions); - } - if !shim_tables.is_empty() { - shim.section(&shim_tables); - } - if !shim_memories.is_empty() { - shim.section(&shim_memories); - } - if !shim_globals.is_empty() { - shim.section(&shim_globals); - } - if !shim_exports.is_empty() { - shim.section(&shim_exports); - } - if !shim_code.is_empty() { - shim.section(&shim_code); - } - shim.section(&RawCustomSection( - &crate::base_producers().raw_custom_section(), - )); - if self.info.encoder.debug_names { - shim.section(&shim_names); - } - - let shim_module_index = self - .component - .core_module(Some("wit-component-shim-module"), &shim); - - let shim_instance = self.component.core_instantiate( - Some("wit-component-shim-instance"), - shim_module_index, - [], - ); - self.shim_instance_index = Some(shim_instance); - - // With the shim instantiated the memory it defines, if any, is now - // available for use as a canonical option. - if self.info.info.imports.imported_memory().is_some() { - assert!(self.memory_index.is_none()); - self.memory_index = Some(self.core_alias_export( - Some("memory"), - shim_instance, - SHIM_MEMORY_NAME, - ExportKind::Memory, - )); - } - - Ok((ret, fixups)) - } - - fn encode_shim(&mut self, shims: &Shims<'_>, shim: &Shim<'_>) -> Result { - let resolve = &self.info.encoder.metadata.resolve; - Ok(match &shim.kind { - // Indirect lowerings are a `canon lower`'d function with - // options specified from a previously instantiated instance. - // This previous instance could either be the main module or an - // adapter module, which affects the `realloc` option here. - // Currently only one linear memory is supported so the linear - // memory always comes from the main module. - ShimKind::IndirectLowering { - interface, - index, - realloc, - encoding, - } => { - let interface = &self.info.import_map[interface]; - let ((name, _), _) = interface.lowerings.get_index(*index).unwrap(); - let func_index = match &interface.interface { - Some(interface_id) => { - let instance_index = self.instances[interface_id]; - self.component - .alias_export(instance_index, name, ComponentExportKind::Func) - } - None => self.imported_funcs[name], - }; - - let realloc_export = self - .info - .exports_for(*realloc) - .import_realloc_for(interface.interface, name); - let realloc = self.realloc_index( - shims, - *realloc, - ReallocSite::AfterInstantiation, - shim.options, - realloc_export, - ); - - self.component.lower_func( - Some(&shim.debug_name), - func_index, - shim.options - .into_iter(*encoding, self.memory_index, realloc)?, - ) - } - - // Adapter shims are defined by an export from an adapter - // instance, so use the specified name here and the previously - // created instances to get the core item that represents the - // shim. - ShimKind::Adapter { adapter, func } => self.core_alias_export( - Some(func), - self.adapter_instances[adapter], - func, - ExportKind::Func, - ), - - // Resources are required for a module to be instantiated - // meaning that any destructor for the resource must be called - // indirectly due to the otherwise circular dependency between - // the module and the resource itself. - ShimKind::ResourceDtor { module, export } => self.core_alias_export( - Some(export), - self.instance_for(*module), - export, - ExportKind::Func, - ), - - ShimKind::PayloadFunc { - for_module, - info, - kind, - } => self.encode_payload_func( - shims, - for_module, - info, - kind, - shim.options, - ReallocSite::AfterInstantiation, - )?, - - ShimKind::WaitableSetWait { cancellable } => self - .component - .waitable_set_wait(*cancellable, self.memory_index.unwrap()), - ShimKind::WaitableSetPoll { cancellable } => self - .component - .waitable_set_poll(*cancellable, self.memory_index.unwrap()), - ShimKind::ErrorContextNew { encoding } => self - .component - .error_context_new(shim.options.into_iter(*encoding, self.memory_index, None)?), - ShimKind::ErrorContextDebugMessage { - for_module, - encoding, - } => { - let realloc = self.info.exports_for(*for_module).import_realloc_fallback(); - let realloc_index = self.realloc_index( - shims, - *for_module, - ReallocSite::AfterInstantiation, - shim.options, - realloc, - ); - - self.component - .error_context_debug_message(shim.options.into_iter( - *encoding, - self.memory_index, - realloc_index, - )?) - } - ShimKind::TaskReturn { - interface, - func, - result, - encoding, - for_module, - } => { - // See `Import::ExportedTaskReturn` handling for why this - // encoder is treated specially. - let mut encoder = if interface.is_none() { - self.root_import_type_encoder(*interface) - } else { - self.root_export_type_encoder(*interface) - }; - let result = match result { - Some(ty) => Some(encoder.encode_valtype(resolve, ty)?), - None => None, - }; - - let exports = self.info.exports_for(*for_module); - let realloc = exports.import_realloc_for(*interface, func); - - let instance_index = self.instance_for(*for_module); - let realloc_index = realloc.map(|r| { - self.core_alias_export(Some("realloc"), instance_index, r, ExportKind::Func) - }); - let options = - shim.options - .into_iter(*encoding, self.memory_index, realloc_index)?; - self.component.task_return(result, options) - } - ShimKind::ThreadNewIndirect { func_ty } => { - // Encode the function type for the thread start function so we can reference it in the `canon` call. - let (func_ty_idx, f) = self.component.core_type(Some("thread-start")); - f.core().func_type(func_ty); - - // In order for the funcref table referenced by `thread.new-indirect` to be used, - // it must have been exported by the main module. - let exports = self.info.exports_for(CustomModule::Main); - let instance_index = self.instance_for(CustomModule::Main); - let table_idx = exports.indirect_function_table().map(|table| { - self.core_alias_export( - Some("indirect-function-table"), - instance_index, - table, - ExportKind::Table, - ) - }).ok_or_else(|| { - anyhow!( - "table __indirect_function_table must be an exported funcref table for thread.new-indirect" - ) - })?; - - self.component.thread_new_indirect(func_ty_idx, table_idx) - } - - ShimKind::Realloc { module, export } => { - let instance = self.instance_for(*module); - self.core_alias_export(Some(export), instance, export, ExportKind::Func) - } - }) - } - - fn encode_payload_func( - &mut self, - shims: &Shims<'_>, - for_module: &CustomModule, - info: &PayloadInfo, - kind: &PayloadFuncKind, - options: RequiredOptions, - site: ReallocSite, - ) -> Result { - let resolve = &self.info.encoder.metadata.resolve; - let metadata = self.info.module_metadata_for(*for_module); - let encoding = match &info.ty { - PayloadType::Type { function, .. } => { - if info.imported { - metadata.import_encodings.get(resolve, &info.key, function) - } else { - metadata.export_encodings.get(resolve, &info.key, function) - } - } - PayloadType::UnitFuture | PayloadType::UnitStream => None, - }; - let realloc = payload_realloc_name(self.info, *for_module, info); - let encoding = encoding.unwrap_or(StringEncoding::UTF8); - let realloc_index = self.realloc_index(shims, *for_module, site, options, realloc); - let type_index = self.payload_type_index(info)?; - let options = options.into_iter(encoding, self.memory_index, realloc_index)?; - - Ok(match kind { - PayloadFuncKind::FutureWrite => self.component.future_write(type_index, options), - PayloadFuncKind::FutureRead => self.component.future_read(type_index, options), - PayloadFuncKind::StreamWrite => self.component.stream_write(type_index, options), - PayloadFuncKind::StreamRead => self.component.stream_read(type_index, options), - }) - } - - /// Encode the specified `stream` or `future` type in the component using - /// either the `root_import_type_encoder` or the `root_export_type_encoder` - /// depending on the value of `imported`. - /// - /// Note that the payload type `T` of `stream` or `future` may be an - /// imported or exported type, and that determines the appropriate type - /// encoder to use. - fn payload_type_index(&mut self, info: &PayloadInfo) -> Result { - let resolve = &self.info.encoder.metadata.resolve; - // What exactly is selected here as the encoder is a bit unusual here. - // If the interface is imported, an import encoder is used. An import - // encoder is also used though if `info` is exported and - // `info.interface` is `None`, meaning that this is for a function that - // is in the top-level of a world. At the top level of a world all - // types are imported. - // - // Additionally for the import encoder the interface passed in is - // `None`, not `info.interface`. Notably this means that references to - // named types will be aliased from their imported versions, which is - // what we want here. - // - // Finally though exports do use `info.interface`. Honestly I'm not - // really entirely sure why. Fuzzing is happy though, and truly - // everything must be ok if the fuzzers are happy, right? - let mut encoder = if info.imported || info.interface.is_none() { - self.root_import_type_encoder(None) - } else { - self.root_export_type_encoder(info.interface) - }; - match info.ty { - PayloadType::Type { id, .. } => match encoder.encode_valtype(resolve, &Type::Id(id))? { - ComponentValType::Type(index) => Ok(index), - ComponentValType::Primitive(_) => unreachable!(), - }, - PayloadType::UnitFuture => Ok(encoder.encode_unit_future()), - PayloadType::UnitStream => Ok(encoder.encode_unit_stream()), - } - } - - /// This is a helper function that will declare any types necessary for - /// declaring intrinsics that are imported into the module or adapter. - /// - /// For example resources must be declared to generate - /// destructors/constructors/etc. Additionally types must also be declared - /// for `task.return` with the component model async feature. - fn declare_types_for_imported_intrinsics(&mut self, shims: &Shims<'_>) -> Result<()> { - let resolve = &self.info.encoder.metadata.resolve; - let world = &resolve.worlds[self.info.encoder.metadata.world]; - - // Iterate over the main module's exports and the exports of all - // adapters. Look for exported interfaces. - let main_module_keys = self.info.encoder.main_module_exports.iter(); - let main_module_keys = main_module_keys.map(|key| (CustomModule::Main, key)); - let adapter_keys = self.info.encoder.adapters.iter().flat_map(|(name, info)| { - info.required_exports - .iter() - .map(move |key| (CustomModule::Adapter(name), key)) - }); - for (for_module, key) in main_module_keys.chain(adapter_keys) { - let id = match &world.exports[key] { - WorldItem::Interface { id, .. } => *id, - WorldItem::Type { .. } => unreachable!(), - WorldItem::Function(_) => continue, - }; - - for ty in resolve.interfaces[id].types.values() { - let def = &resolve.types[*ty]; - match &def.kind { - // Declare exported resources specially as they generally - // need special treatment for later handling exports and - // such. - TypeDefKind::Resource => { - // Load the destructor, previously detected in module - // validation, if one is present. - let exports = self.info.exports_for(for_module); - let dtor = exports.resource_dtor(*ty).map(|name| { - let shim = &shims.shims[&ShimKind::ResourceDtor { - module: for_module, - export: name, - }]; - let index = self.shim_instance_index.unwrap(); - self.core_alias_export( - Some(&shim.debug_name), - index, - &shim.name, - ExportKind::Func, - ) - }); - - // Declare the resource with this destructor and register it in - // our internal map. This should be the first and only time this - // type is inserted into this map. - let resource_idx = self.component.type_resource( - Some(def.name.as_ref().unwrap()), - ValType::I32, - dtor, - ); - let prev = self - .type_encoding_maps - .id_to_index - .insert(*ty, resource_idx); - assert!(prev.is_none()); - } - _other => { - self.root_export_type_encoder(Some(id)) - .encode_valtype(resolve, &Type::Id(*ty))?; - } - } - } - } - Ok(()) - } - - /// Helper to instantiate the main module and record various results of its - /// instantiation within `self`. - fn instantiate_main_module(&mut self, shims: &Shims<'_>) -> Result<()> { - assert!(self.instance_index.is_none()); - - let instance_index = self.instantiate_core_module(shims, CustomModule::Main)?; - - // If memory hasn't been defined yet then it's provided by the main - // module here. - if self.memory_index.is_none() { - if let Some(memory) = self.info.info.exports.memory() { - self.memory_index = Some(self.core_alias_export( - Some("memory"), - instance_index, - memory, - ExportKind::Memory, - )); - } - } - - self.instance_index = Some(instance_index); - Ok(()) - } - - /// This function will instantiate the specified adapter module, which may - /// depend on previously-instantiated modules. - fn instantiate_adapter_module(&mut self, shims: &Shims<'_>, name: &'a str) -> Result<()> { - let instance = self.instantiate_core_module(shims, CustomModule::Adapter(name))?; - self.adapter_instances.insert(name, instance); - Ok(()) - } - - /// Generic helper to instantiate a module. - /// - /// The `for_module` provided will have all of its imports satisfied from - /// either previous instantiations or the `shims` module present. This - /// iterates over the metadata produced during validation to determine what - /// hooks up to what import. - fn instantiate_core_module( - &mut self, - shims: &Shims, - for_module: CustomModule<'_>, - ) -> Result { - let module = self.module_for(for_module); - - let mut args = Vec::new(); - for (core_wasm_name, instance) in self.info.imports_for(for_module).modules() { - match instance { - // For import modules that are a "bag of names" iterate over - // each name and materialize it into this component with the - // `materialize_import` helper. This is then all bottled up into - // a bag-of-exports instance which is then used for - // instantiation. - ImportInstance::Names(names) => { - let mut exports = Vec::new(); - for (name, import) in names { - log::trace!( - "attempting to materialize import of `{core_wasm_name}::{name}` for {for_module:?}" - ); - let (kind, index) = self - .materialize_import(&shims, for_module, import) - .with_context(|| { - format!("failed to satisfy import `{core_wasm_name}::{name}`") - })?; - exports.push((name.as_str(), kind, index)); - } - let index = self - .component - .core_instantiate_exports(Some(core_wasm_name), exports); - args.push((core_wasm_name.as_str(), ModuleArg::Instance(index))); - } - - // Some imports are entire instances, so use the instance for - // the module identifier as the import. - ImportInstance::Whole(which) => { - let instance = self.instance_for(which.to_custom_module()); - args.push((core_wasm_name.as_str(), ModuleArg::Instance(instance))); - } - } - } - - // And with all arguments prepared now, instantiate the module. - Ok(self - .component - .core_instantiate(Some(for_module.debug_name()), module, args)) - } - - /// Helper function to materialize an import into a core module within the - /// component being built. - /// - /// This function is called for individual imports and uses the results of - /// validation, notably the `Import` type, to determine what WIT-level or - /// component-level construct is being hooked up. - fn materialize_import( - &mut self, - shims: &Shims<'_>, - for_module: CustomModule<'_>, - import: &'a Import, - ) -> Result<(ExportKind, u32)> { - let resolve = &self.info.encoder.metadata.resolve; - match import { - // Main module dependencies on an adapter in use are done with an - // indirection here, so load the shim function and use that. - Import::AdapterExport { - adapter, - func, - ty: _, - } => { - assert!(self.info.encoder.adapters.contains_key(adapter)); - Ok(self.materialize_shim_import(shims, &ShimKind::Adapter { adapter, func })) - } - - // Adapters might use the main module's memory, in which case it - // should have been previously instantiated. - Import::MainModuleMemory(_) => { - let index = self - .memory_index - .ok_or_else(|| anyhow!("main module cannot import memory"))?; - Ok((ExportKind::Memory, index)) - } - - // Grab-bag of "this adapter wants this thing from the main module". - Import::MainModuleExport { name, kind } => { - let instance = self.instance_index.unwrap(); - let index = self.core_alias_export(Some(name), instance, name, *kind); - Ok((*kind, index)) - } - - // A similar grab-bag to above but with a slightly different - // structure. Should probably refactor to make these two the same in - // the future. - Import::Item(item) => { - let instance = self.instance_for(item.which.to_custom_module()); - let index = - self.core_alias_export(Some(&item.name), instance, &item.name, item.kind); - Ok((item.kind, index)) - } - - // Resource intrinsics related to exported resources. Despite being - // an exported resource the component still provides necessary - // intrinsics for manipulating resource state. These are all - // handled here using the resource types created during - // `declare_types_for_imported_intrinsics` above. - Import::ExportedResourceDrop(_key, id) => { - let index = self - .component - .resource_drop(self.type_encoding_maps.id_to_index[id]); - Ok((ExportKind::Func, index)) - } - Import::ExportedResourceRep(_key, id) => { - let index = self - .component - .resource_rep(self.type_encoding_maps.id_to_index[id]); - Ok((ExportKind::Func, index)) - } - Import::ExportedResourceNew(_key, id) => { - let index = self - .component - .resource_new(self.type_encoding_maps.id_to_index[id]); - Ok((ExportKind::Func, index)) - } - - // And finally here at the end these cases are going to all fall - // through to the code below. This is where these are connected to a - // WIT `ImportedInterface` one way or another with the name that was - // detected during validation. - Import::ImportedResourceDrop(key, iface, id) => { - let ty = &resolve.types[*id]; - let name = ty.name.as_ref().unwrap(); - self.materialize_wit_import( - shims, - for_module, - iface.map(|_| resolve.name_world_key(key)), - &format!("{name}_drop"), - key, - AbiVariant::GuestImport, - ) - } - Import::ExportedTaskReturn(key, interface, func) => { - let (options, _sig) = task_return_options_and_type(resolve, func); - let result_ty = func.result; - if options.is_empty() || self.memory_index.is_some() { - // Note that an "import type encoder" is used here despite - // this being for an exported function if the `interface` - // is none, meaning that this is for a top-level world - // function. In that situation all types that can be - // referred to are imported, not exported. - let mut encoder = if interface.is_none() { - self.root_import_type_encoder(*interface) - } else { - self.root_export_type_encoder(*interface) - }; - - let result = match result_ty.as_ref() { - Some(ty) => Some(encoder.encode_valtype(resolve, ty)?), - None => None, - }; - let metadata = &self.info.module_metadata_for(for_module); - let encoding = metadata - .export_encodings - .get(resolve, key, &func.name) - .ok_or_else(|| { - anyhow!("missing component metadata for export of `{}`", func.name) - })?; - let options = options - .into_iter(encoding, self.memory_index, None)? - .collect::>(); - let index = self.component.task_return(result, options); - Ok((ExportKind::Func, index)) - } else { - let metadata = &self.info.module_metadata_for(for_module); - let encoding = metadata - .export_encodings - .get(resolve, key, &func.name) - .unwrap(); - Ok(self.materialize_shim_import( - shims, - &ShimKind::TaskReturn { - for_module, - interface: *interface, - func: &func.name, - result: result_ty, - encoding, - }, - )) - } - } - Import::BackpressureInc => { - let index = self.component.backpressure_inc(); - Ok((ExportKind::Func, index)) - } - Import::BackpressureDec => { - let index = self.component.backpressure_dec(); - Ok((ExportKind::Func, index)) - } - Import::WaitableSetWait { cancellable } => { - if let Some(memory) = self.memory_index { - let index = self.component.waitable_set_wait(*cancellable, memory); - return Ok((ExportKind::Func, index)); - } - Ok(self.materialize_shim_import( - shims, - &ShimKind::WaitableSetWait { - cancellable: *cancellable, - }, - )) - } - Import::WaitableSetPoll { cancellable } => { - if let Some(memory) = self.memory_index { - let index = self.component.waitable_set_poll(*cancellable, memory); - return Ok((ExportKind::Func, index)); - } - Ok(self.materialize_shim_import( - shims, - &ShimKind::WaitableSetPoll { - cancellable: *cancellable, - }, - )) - } - Import::SubtaskDrop => { - let index = self.component.subtask_drop(); - Ok((ExportKind::Func, index)) - } - Import::SubtaskCancel { async_ } => { - let index = self.component.subtask_cancel(*async_); - Ok((ExportKind::Func, index)) - } - Import::StreamNew(info) => { - let ty = self.payload_type_index(info)?; - let index = self.component.stream_new(ty); - Ok((ExportKind::Func, index)) - } - Import::StreamRead { info, async_ } => self.materialize_payload_import( - shims, - for_module, - info, - PayloadFuncKind::StreamRead, - *async_, - ), - Import::StreamWrite { info, async_ } => self.materialize_payload_import( - shims, - for_module, - info, - PayloadFuncKind::StreamWrite, - *async_, - ), - Import::StreamCancelRead { info, async_ } => { - let ty = self.payload_type_index(info)?; - let index = self.component.stream_cancel_read(ty, *async_); - Ok((ExportKind::Func, index)) - } - Import::StreamCancelWrite { info, async_ } => { - let ty = self.payload_type_index(info)?; - let index = self.component.stream_cancel_write(ty, *async_); - Ok((ExportKind::Func, index)) - } - Import::StreamDropReadable(info) => { - let type_index = self.payload_type_index(info)?; - let index = self.component.stream_drop_readable(type_index); - Ok((ExportKind::Func, index)) - } - Import::StreamDropWritable(info) => { - let type_index = self.payload_type_index(info)?; - let index = self.component.stream_drop_writable(type_index); - Ok((ExportKind::Func, index)) - } - Import::FutureNew(info) => { - let ty = self.payload_type_index(info)?; - let index = self.component.future_new(ty); - Ok((ExportKind::Func, index)) - } - Import::FutureRead { info, async_ } => self.materialize_payload_import( - shims, - for_module, - info, - PayloadFuncKind::FutureRead, - *async_, - ), - Import::FutureWrite { info, async_ } => self.materialize_payload_import( - shims, - for_module, - info, - PayloadFuncKind::FutureWrite, - *async_, - ), - Import::FutureCancelRead { info, async_ } => { - let ty = self.payload_type_index(info)?; - let index = self.component.future_cancel_read(ty, *async_); - Ok((ExportKind::Func, index)) - } - Import::FutureCancelWrite { info, async_ } => { - let ty = self.payload_type_index(info)?; - let index = self.component.future_cancel_write(ty, *async_); - Ok((ExportKind::Func, index)) - } - Import::FutureDropReadable(info) => { - let type_index = self.payload_type_index(info)?; - let index = self.component.future_drop_readable(type_index); - Ok((ExportKind::Func, index)) - } - Import::FutureDropWritable(info) => { - let type_index = self.payload_type_index(info)?; - let index = self.component.future_drop_writable(type_index); - Ok((ExportKind::Func, index)) - } - Import::ErrorContextNew { encoding } => { - if self.memory_index.is_some() { - let options = (RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING) - .into_iter(*encoding, self.memory_index, None)?; - let index = self.component.error_context_new(options); - return Ok((ExportKind::Func, index)); - } - Ok(self.materialize_shim_import( - shims, - &ShimKind::ErrorContextNew { - encoding: *encoding, - }, - )) - } - Import::ErrorContextDebugMessage { encoding } => Ok(self.materialize_shim_import( - shims, - &ShimKind::ErrorContextDebugMessage { - for_module, - encoding: *encoding, - }, - )), - Import::ErrorContextDrop => { - let index = self.component.error_context_drop(); - Ok((ExportKind::Func, index)) - } - Import::WorldFunc(key, name, abi) => { - self.materialize_wit_import(shims, for_module, None, name, key, *abi) - } - Import::InterfaceFunc(key, _, name, abi) => self.materialize_wit_import( - shims, - for_module, - Some(resolve.name_world_key(key)), - name, - key, - *abi, - ), - - Import::WaitableSetNew => { - let index = self.component.waitable_set_new(); - Ok((ExportKind::Func, index)) - } - Import::WaitableSetDrop => { - let index = self.component.waitable_set_drop(); - Ok((ExportKind::Func, index)) - } - Import::WaitableJoin => { - let index = self.component.waitable_join(); - Ok((ExportKind::Func, index)) - } - Import::ContextGet { ty, slot } => { - let index = self.component.context_get((*ty).try_into()?, *slot); - Ok((ExportKind::Func, index)) - } - Import::ContextSet { ty, slot } => { - let index = self.component.context_set((*ty).try_into()?, *slot); - Ok((ExportKind::Func, index)) - } - Import::TlsBaseGet { ty } => Ok(( - ExportKind::Func, - self.materialize_tls_base_import(false, (*ty).try_into()?), - )), - Import::TlsBaseSet { ty } => Ok(( - ExportKind::Func, - self.materialize_tls_base_import(true, (*ty).try_into()?), - )), - Import::ExportedTaskCancel => { - let index = self.component.task_cancel(); - Ok((ExportKind::Func, index)) - } - Import::ThreadIndex => { - let index = self.component.thread_index(); - Ok((ExportKind::Func, index)) - } - Import::ThreadNewIndirect => Ok(self.materialize_shim_import( - shims, - &ShimKind::ThreadNewIndirect { - // This is fixed for now - func_ty: FuncType::new([ValType::I32], []), - }, - )), - Import::ThreadResumeLater => { - let index = self.component.thread_resume_later(); - Ok((ExportKind::Func, index)) - } - Import::ThreadSuspend { cancellable } => { - let index = self.component.thread_suspend(*cancellable); - Ok((ExportKind::Func, index)) - } - Import::ThreadYield { cancellable } => { - let index = self.component.thread_yield(*cancellable); - Ok((ExportKind::Func, index)) - } - Import::ThreadSuspendThenResume { cancellable } => { - let index = self.component.thread_suspend_then_resume(*cancellable); - Ok((ExportKind::Func, index)) - } - Import::ThreadYieldThenResume { cancellable } => { - let index = self.component.thread_yield_then_resume(*cancellable); - Ok((ExportKind::Func, index)) - } - Import::ThreadSuspendThenPromote { cancellable } => { - let index = self.component.thread_suspend_then_promote(*cancellable); - Ok((ExportKind::Func, index)) - } - Import::ThreadYieldThenPromote { cancellable } => { - let index = self.component.thread_yield_then_promote(*cancellable); - Ok((ExportKind::Func, index)) - } - } - } - - /// Helper to satisfy `__wasm_{get,set}_tls_base` imports. - /// - /// For more information on this see WebAssembly/wasi-libc#857 - fn materialize_tls_base_import(&mut self, set: bool, ty: ValType) -> u32 { - if self.info.can_use_context_slot_1() { - if set { - self.component.context_set(ty, 1) - } else { - self.component.context_get(ty, 1) - } - } else { - let name = if set { TLS_BASE_SET } else { TLS_BASE_GET }; - self.core_alias_export( - Some(name), - self.shim_instance_index.unwrap(), - name, - ExportKind::Func, - ) - } - } - - /// Helper for `materialize_import` above for materializing functions that - /// are part of the "shim module" generated. - fn materialize_shim_import(&mut self, shims: &Shims<'_>, kind: &ShimKind) -> (ExportKind, u32) { - let index = self.core_alias_export( - Some(&shims.shims[kind].debug_name), - self.shim_instance_index - .expect("shim should be instantiated"), - &shims.shims[kind].name, - ExportKind::Func, - ); - (ExportKind::Func, index) - } - - /// Helper for `materialize_import` above for generating imports for - /// future/stream read/write intrinsics. - fn materialize_payload_import( - &mut self, - shims: &Shims<'_>, - for_module: CustomModule<'_>, - info: &PayloadInfo, - kind: PayloadFuncKind, - async_: bool, - ) -> Result<(ExportKind, u32)> { - let shim_kind = ShimKind::PayloadFunc { - for_module, - info, - kind, - }; - if shims.shims.get(&shim_kind).is_some() { - return Ok(self.materialize_shim_import(shims, &shim_kind)); - } - let resolve = &self.info.encoder.metadata.resolve; - let options = RequiredOptions::for_payload(resolve, info, &kind, async_); - let func = self.encode_payload_func( - shims, - &for_module, - info, - &kind, - options, - ReallocSite::BeforeInstantiation, - )?; - Ok((ExportKind::Func, func)) - } - - /// Helper for `materialize_import` above which specifically operates on - /// WIT-level functions identified by `interface_key`, `name`, and `abi`. - fn materialize_wit_import( - &mut self, - shims: &Shims<'_>, - for_module: CustomModule<'_>, - interface_key: Option, - name: &String, - key: &WorldKey, - abi: AbiVariant, - ) -> Result<(ExportKind, u32)> { - let resolve = &self.info.encoder.metadata.resolve; - let import = &self.info.import_map[&interface_key]; - let (index, _, lowering) = import.lowerings.get_full(&(name.clone(), abi)).unwrap(); - let metadata = self.info.module_metadata_for(for_module); - - let index = match lowering { - // All direct lowerings can be `canon lower`'d here immediately - // and passed as arguments. - Lowering::Direct { options } => { - let func_index = match &import.interface { - Some(interface) => { - let instance_index = self.instances[interface]; - self.component - .alias_export(instance_index, name, ComponentExportKind::Func) - } - None => self.imported_funcs[name], - }; - let encoding = metadata - .import_encodings - .get(resolve, key, name) - .ok_or_else(|| anyhow!("missing component metadata for import of `{name}`"))?; - let realloc = self - .info - .exports_for(for_module) - .import_realloc_for(import.interface, name); - let realloc = self.realloc_index( - shims, - for_module, - ReallocSite::BeforeInstantiation, - *options, - realloc, - ); - let options = options - .into_iter(encoding, self.memory_index, realloc)? - .collect::>(); - self.component.lower_func(Some(name), func_index, options) - } - - // Indirect lowerings come from the shim that was previously - // created, so the specific export is loaded here and used as an - // import. - Lowering::Indirect { .. } => { - let encoding = metadata.import_encodings.get(resolve, key, name).unwrap(); - return Ok(self.materialize_shim_import( - shims, - &ShimKind::IndirectLowering { - interface: interface_key, - index, - realloc: for_module, - encoding, - }, - )); - } - - // A "resource drop" intrinsic only needs to find the index of the - // resource type itself and then the intrinsic is declared. - Lowering::ResourceDrop(id) => { - let resource_idx = self.lookup_resource_index(*id); - self.component.resource_drop(resource_idx) - } - }; - Ok((ExportKind::Func, index)) - } - - /// Returns the core function index to use for the `realloc` canonical - /// option where the function is named `export` within `module`. - fn realloc_index( - &mut self, - shims: &Shims<'_>, - module: CustomModule<'_>, - site: ReallocSite, - options: RequiredOptions, - export: Option<&str>, - ) -> Option { - if !options.contains(RequiredOptions::REALLOC) { - return None; - } - let (module, export) = resolve_realloc(self.info, module, export)?; - - if !realloc_needs_shim(self.info, site) { - let instance = self.instance_for(module); - return Some(self.core_alias_export(Some(export), instance, export, ExportKind::Func)); - } - - let kind = ShimKind::Realloc { module, export }; - let shim = shims.shims.get(&kind).unwrap_or_else(|| { - panic!( - "no shim was registered for the `realloc` \ - function `{export}` in `{}`", - module.debug_name() - ) - }); - let instance = self - .shim_instance_index - .expect("shim should be instantiated"); - Some(self.core_alias_export( - Some(&shim.debug_name), - instance, - &shim.name, - ExportKind::Func, - )) - } - - fn hooked_core_alias_export(&mut self, module: CustomModule<'_>, core_name: &str) -> u32 { - let key = (module.to_imported_instance(), core_name.to_string()); - if let Some(&wrapper_idx) = self.export_task_initialization_wrappers.get(&key) { - wrapper_idx - } else { - let instance = self.instance_for(module); - self.core_alias_export(Some(core_name), instance, core_name, ExportKind::Func) - } - } - - /// Convenience function to go from `CustomModule` to the instance index - /// corresponding to what that points to. - fn instance_for(&self, module: CustomModule) -> u32 { - match module { - CustomModule::Main => self.instance_index.expect("instantiated by now"), - CustomModule::Adapter(name) => self.adapter_instances[name], - } - } - - /// Convenience function to go from `CustomModule` to the module index - /// corresponding to what that points to. - fn module_for(&self, module: CustomModule) -> u32 { - match module { - CustomModule::Main => self.module_index.unwrap(), - CustomModule::Adapter(name) => self.adapter_modules[name], - } - } - - /// Convenience function which caches aliases created so repeated calls to - /// this function will all return the same index. - fn core_alias_export( - &mut self, - debug_name: Option<&str>, - instance: u32, - name: &str, - kind: ExportKind, - ) -> u32 { - *self - .aliased_core_items - .entry((instance, name.to_string())) - .or_insert_with(|| { - self.component - .core_alias_export(debug_name, instance, name, kind) - }) - } -} - -/// A list of "shims" which start out during the component instantiation process -/// as functions which immediately trap due to a `call_indirect`-to-`null` but -/// will get filled in by the time the component instantiation process -/// completes. -/// -/// Shims currently include: -/// -/// * "Indirect functions" lowered from imported instances where the lowering -/// requires an item exported from the main module. These are indirect due to -/// the circular dependency between the module needing an import and the -/// import needing the module. -/// -/// * Adapter modules which convert from a historical ABI to the component -/// model's ABI (e.g. wasi preview1 to preview2) get a shim since the adapters -/// are currently indicated as always requiring the memory of the main module. -/// -/// This structure is created by `encode_shim_instantiation`. -#[derive(Default)] -struct Shims<'a> { - /// The list of all shims that a module will require. - shims: IndexMap, Shim<'a>>, -} - -struct Shim<'a> { - /// Canonical ABI options required by this shim, used during `canon lower` - /// operations. - options: RequiredOptions, - - /// The name, in the shim instance, of this shim. - /// - /// Currently this is `"0"`, `"1"`, ... - name: String, - - /// A human-readable debugging name for this shim, used in a core wasm - /// `name` section. - debug_name: String, - - /// Precise information about what this shim is a lowering of. - kind: ShimKind<'a>, - - /// Wasm type of this shim. - sig: WasmSignature, -} - -/// Which variation of `{stream|future}.{read|write}` we're emitting for a -/// `ShimKind::PayloadFunc`. -#[derive(Debug, Clone, Hash, Eq, PartialEq, Copy)] -enum PayloadFuncKind { - FutureWrite, - FutureRead, - StreamWrite, - StreamRead, -} - -#[derive(Debug, Clone, Hash, Eq, PartialEq)] -enum ShimKind<'a> { - /// This shim is a late indirect lowering of an imported function in a - /// component which is only possible after prior core wasm modules are - /// instantiated so their memories and functions are available. - IndirectLowering { - /// The name of the interface that's being lowered. - interface: Option, - /// The index within the `lowerings` array of the function being lowered. - index: usize, - /// Which instance to pull the `realloc` function from, if necessary. - realloc: CustomModule<'a>, - /// The string encoding that this lowering is going to use. - encoding: StringEncoding, - }, - /// This shim is a core wasm function defined in an adapter module but isn't - /// available until the adapter module is itself instantiated. - Adapter { - /// The name of the adapter module this shim comes from. - adapter: &'a str, - /// The name of the export in the adapter module this shim points to. - func: &'a str, - }, - /// A shim used as the destructor for a resource which allows defining the - /// resource before the core module being instantiated. - ResourceDtor { - /// Which instance to pull the destructor function from. - module: CustomModule<'a>, - /// The exported function name of this destructor in the core module. - export: &'a str, - }, - /// A shim used for a `{stream|future}.{read|write}` built-in function, - /// which must refer to the core module instance's memory from/to which - /// payload values must be lifted/lowered. - PayloadFunc { - /// Which instance to pull the `realloc` function and string encoding - /// from, if necessary. - for_module: CustomModule<'a>, - /// Additional information regarding the function where this `stream` or - /// `future` type appeared, which we use in combination with - /// `for_module` to determine which `realloc` and string encoding to - /// use, as well as which type to specify when emitting the built-in. - info: &'a PayloadInfo, - /// Which variation of `{stream|future}.{read|write}` we're emitting. - kind: PayloadFuncKind, - }, - /// A shim used for the `waitable-set.wait` built-in function, which must - /// refer to the core module instance's memory to which results will be - /// written. - WaitableSetWait { cancellable: bool }, - /// A shim used for the `waitable-set.poll` built-in function, which must - /// refer to the core module instance's memory to which results will be - /// written. - WaitableSetPoll { cancellable: bool }, - /// Shim for `task.return` to handle a reference to a `memory` which may - TaskReturn { - /// The interface (optional) that owns `func` below. If `None` then it's - /// a world export. - interface: Option, - /// The function that this `task.return` is returning for, owned - /// within `interface` above. - func: &'a str, - /// The WIT type that `func` returns. - result: Option, - /// Which instance to pull the `realloc` function from, if necessary. - for_module: CustomModule<'a>, - /// String encoding to use in the ABI options. - encoding: StringEncoding, - }, - /// A shim used for the `error-context.new` built-in function, which must - /// refer to the core module instance's memory from which the debug message - /// will be read. - ErrorContextNew { - /// String encoding to use when lifting the debug message. - encoding: StringEncoding, - }, - /// A shim used for the `error-context.debug-message` built-in function, - /// which must refer to the core module instance's memory to which results - /// will be written. - ErrorContextDebugMessage { - /// Which instance to pull the `realloc` function from, if necessary. - for_module: CustomModule<'a>, - /// The string encoding to use when lowering the debug message. - encoding: StringEncoding, - }, - /// A shim used for the `thread.new-indirect` built-in function, which - /// must refer to the core module instance's indirect function table. - ThreadNewIndirect { - /// The function type to use when creating the thread. - func_ty: FuncType, - }, - /// A shim for a `realloc` function used as a canonical option. - Realloc { - /// Which instance the `realloc` function is exported from. - module: CustomModule<'a>, - /// The name of the `realloc` export within `module`. - export: &'a str, - }, -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -enum ReallocSite { - /// This `realloc` is needed before the main module is instantiated. - BeforeInstantiation, - /// This `realloc` is needed after the main module is instantiated, but - /// before the fixup module is instantiated. - AfterInstantiation, -} - -fn realloc_needs_shim(world: &ComponentWorld<'_>, site: ReallocSite) -> bool { - match site { - // The function isn't available at all yet, so an indirection is - // required no matter what. - ReallocSite::BeforeInstantiation => true, - - // The function itself is available, but if task hooks are enabled then - // the hooked version of it is defined by the fixup module which hasn't - // been instantiated yet. - ReallocSite::AfterInstantiation => world.info.exports.wasm_task_hook().is_some(), - } -} - -/// Indicator for which module is being used for a lowering or where options -/// like `realloc` are drawn from. -/// -/// This is necessary for situations such as an imported function being lowered -/// into the main module and additionally into an adapter module. For example an -/// adapter might adapt from preview1 to preview2 for the standard library of a -/// programming language but the main module's custom application code may also -/// explicitly import from preview2. These two different lowerings of a preview2 -/// function are parameterized by this enumeration. -#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] -enum CustomModule<'a> { - /// This points to the "main module" which is generally the "output of LLVM" - /// or what a user wrote. - Main, - /// This is selecting an adapter module, identified by name here, where - /// something is being lowered into. - Adapter(&'a str), -} - -impl<'a> CustomModule<'a> { - fn debug_name(&self) -> &'a str { - match self { - CustomModule::Main => "main", - CustomModule::Adapter(s) => s, - } - } - - /// Returns the instance, as imported into the fixup module, that this - /// module corresponds to. - fn to_imported_instance(&self) -> fixup::ImportedInstance { - match self { - CustomModule::Main => fixup::ImportedInstance::Main, - CustomModule::Adapter(s) => fixup::ImportedInstance::Adapter(s.to_string()), - } - } -} - -impl<'a> Shims<'a> { - /// Adds all shims necessary for the instantiation of `for_module`. - /// - /// This function will iterate over all the imports required by this module - /// and for those that require a shim they're registered here. - fn append_indirect( - &mut self, - world: &'a ComponentWorld<'a>, - for_module: CustomModule<'a>, - ) -> Result<()> { - let module_imports = world.imports_for(for_module); - let module_exports = world.exports_for(for_module); - let resolve = &world.encoder.metadata.resolve; - let memory_available = world.info.imports.imported_memory().is_some(); - - for (module, field, import) in module_imports.imports() { - match import { - // These imports don't require shims, they can be satisfied - // as-needed when required. - Import::ImportedResourceDrop(..) - | Import::MainModuleMemory(_) - | Import::MainModuleExport { .. } - | Import::Item(_) - | Import::ExportedResourceDrop(..) - | Import::ExportedResourceRep(..) - | Import::ExportedResourceNew(..) - | Import::ExportedTaskCancel - | Import::ErrorContextDrop - | Import::BackpressureInc - | Import::BackpressureDec - | Import::SubtaskDrop - | Import::SubtaskCancel { .. } - | Import::FutureNew(..) - | Import::StreamNew(..) - | Import::FutureCancelRead { .. } - | Import::FutureCancelWrite { .. } - | Import::FutureDropWritable { .. } - | Import::FutureDropReadable { .. } - | Import::StreamCancelRead { .. } - | Import::StreamCancelWrite { .. } - | Import::StreamDropWritable { .. } - | Import::StreamDropReadable { .. } - | Import::WaitableSetNew - | Import::WaitableSetDrop - | Import::WaitableJoin - | Import::ContextGet { .. } - | Import::ContextSet { .. } - | Import::TlsBaseGet { .. } - | Import::TlsBaseSet { .. } - | Import::ThreadIndex - | Import::ThreadResumeLater - | Import::ThreadSuspend { .. } - | Import::ThreadYield { .. } - | Import::ThreadSuspendThenResume { .. } - | Import::ThreadYieldThenResume { .. } - | Import::ThreadSuspendThenPromote { .. } - | Import::ThreadYieldThenPromote { .. } => {} - - // If `task.return` needs to be indirect then generate a shim - // for it, otherwise skip the shim and let it get materialized - // naturally later. - Import::ExportedTaskReturn(key, interface, func) => { - let (options, sig) = task_return_options_and_type(resolve, func); - if options.is_empty() || memory_available { - continue; - } - let name = self.shims.len().to_string(); - let encoding = world - .module_metadata_for(for_module) - .export_encodings - .get(resolve, key, &func.name) - .ok_or_else(|| { - anyhow::anyhow!( - "missing component metadata for export of \ - `{module}::{field}`" - ) - })?; - self.push(Shim { - name, - debug_name: format!("task-return-{}", func.name), - options, - kind: ShimKind::TaskReturn { - interface: *interface, - func: &func.name, - result: func.result, - for_module, - encoding, - }, - sig, - }); - } - - Import::FutureWrite { async_, info } => { - self.append_indirect_payload_push( - world, - for_module, - module, - *async_, - info, - PayloadFuncKind::FutureWrite, - vec![WasmType::I32; 2], - vec![WasmType::I32], - ); - } - Import::FutureRead { async_, info } => { - self.append_indirect_payload_push( - world, - for_module, - module, - *async_, - info, - PayloadFuncKind::FutureRead, - vec![WasmType::I32; 2], - vec![WasmType::I32], - ); - } - Import::StreamWrite { async_, info } => { - self.append_indirect_payload_push( - world, - for_module, - module, - *async_, - info, - PayloadFuncKind::StreamWrite, - vec![WasmType::I32; 3], - vec![WasmType::I32], - ); - } - Import::StreamRead { async_, info } => { - self.append_indirect_payload_push( - world, - for_module, - module, - *async_, - info, - PayloadFuncKind::StreamRead, - vec![WasmType::I32; 3], - vec![WasmType::I32], - ); - } - - Import::WaitableSetWait { cancellable } => { - if memory_available { - continue; - } - let name = self.shims.len().to_string(); - self.push(Shim { - name, - debug_name: "waitable-set.wait".to_string(), - options: RequiredOptions::empty(), - kind: ShimKind::WaitableSetWait { - cancellable: *cancellable, - }, - sig: WasmSignature { - params: vec![WasmType::I32; 2], - results: vec![WasmType::I32], - indirect_params: false, - retptr: false, - }, - }); - } - - Import::WaitableSetPoll { cancellable } => { - if memory_available { - continue; - } - let name = self.shims.len().to_string(); - self.push(Shim { - name, - debug_name: "waitable-set.poll".to_string(), - options: RequiredOptions::empty(), - kind: ShimKind::WaitableSetPoll { - cancellable: *cancellable, - }, - sig: WasmSignature { - params: vec![WasmType::I32; 2], - results: vec![WasmType::I32], - indirect_params: false, - retptr: false, - }, - }); - } - - Import::ErrorContextNew { encoding } => { - if memory_available { - continue; - } - let name = self.shims.len().to_string(); - self.push(Shim { - name, - debug_name: "error-new".to_string(), - options: RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING, - kind: ShimKind::ErrorContextNew { - encoding: *encoding, - }, - sig: WasmSignature { - params: vec![WasmType::I32; 2], - results: vec![WasmType::I32], - indirect_params: false, - retptr: false, - }, - }); - } - - Import::ErrorContextDebugMessage { encoding } => { - let name = self.shims.len().to_string(); - let options = RequiredOptions::MEMORY - | RequiredOptions::STRING_ENCODING - | RequiredOptions::REALLOC; - self.push(Shim { - name, - debug_name: "error-debug-message".to_string(), - options, - kind: ShimKind::ErrorContextDebugMessage { - for_module, - encoding: *encoding, - }, - sig: WasmSignature { - params: vec![WasmType::I32; 2], - results: vec![], - indirect_params: false, - retptr: false, - }, - }); - let realloc = module_exports.import_realloc_fallback(); - self.push_realloc( - world, - for_module, - ReallocSite::AfterInstantiation, - options, - realloc, - ); - } - - Import::ThreadNewIndirect => { - let name = self.shims.len().to_string(); - self.push(Shim { - name, - debug_name: "thread.new-indirect".to_string(), - options: RequiredOptions::empty(), - kind: ShimKind::ThreadNewIndirect { - // This is fixed for now - func_ty: FuncType::new([ValType::I32], vec![]), - }, - sig: WasmSignature { - params: vec![WasmType::I32; 2], - results: vec![WasmType::I32], - indirect_params: false, - retptr: false, - }, - }); - } - - // Adapter imports into the main module must got through an - // indirection, so that's registered here. - Import::AdapterExport { adapter, func, ty } => { - let name = self.shims.len().to_string(); - log::debug!("shim {name} is adapter `{module}::{field}`"); - self.push(Shim { - name, - debug_name: format!("adapt-{module}-{field}"), - // Pessimistically assume that all adapters require - // memory in one form or another. While this isn't - // technically true it's true enough for WASI. - options: RequiredOptions::MEMORY, - kind: ShimKind::Adapter { adapter, func }, - sig: WasmSignature { - params: ty.params().iter().map(to_wasm_type).collect(), - results: ty.results().iter().map(to_wasm_type).collect(), - indirect_params: false, - retptr: false, - }, - }); - - fn to_wasm_type(ty: &wasmparser::ValType) -> WasmType { - match ty { - wasmparser::ValType::I32 => WasmType::I32, - wasmparser::ValType::I64 => WasmType::I64, - wasmparser::ValType::F32 => WasmType::F32, - wasmparser::ValType::F64 => WasmType::F64, - _ => unreachable!(), - } - } - } - - // WIT-level functions may require an indirection, so yield some - // metadata out of this `match` to the loop below to figure that - // out. - Import::InterfaceFunc(key, _, name, abi) => { - self.append_indirect_wit_func( - world, - for_module, - module, - field, - key, - name, - Some(resolve.name_world_key(key)), - *abi, - )?; - } - Import::WorldFunc(key, name, abi) => { - self.append_indirect_wit_func( - world, for_module, module, field, key, name, None, *abi, - )?; - } - } - } - - // In addition to all the shims added for imports above this module also - // requires shims for resource destructors that it exports. Resource - // types are declared before the module is instantiated so the actual - // destructor is registered as a shim (defined here) and it's then - // filled in with the module's exports later. - for (export_name, export) in module_exports.iter() { - let id = match export { - Export::ResourceDtor(id) => id, - _ => continue, - }; - let resource = resolve.types[*id].name.as_ref().unwrap(); - let name = self.shims.len().to_string(); - self.push(Shim { - name, - debug_name: format!("dtor-{resource}"), - options: RequiredOptions::empty(), - kind: ShimKind::ResourceDtor { - module: for_module, - export: export_name, - }, - sig: WasmSignature { - params: vec![WasmType::I32], - results: Vec::new(), - indirect_params: false, - retptr: false, - }, - }); - } - - Ok(()) - } - - /// Helper of `append_indirect` above which pushes information for - /// futures/streams read/write intrinsics. - fn append_indirect_payload_push( - &mut self, - world: &'a ComponentWorld<'a>, - for_module: CustomModule<'a>, - module: &str, - async_: bool, - info: &'a PayloadInfo, - kind: PayloadFuncKind, - params: Vec, - results: Vec, - ) { - let resolve = &world.encoder.metadata.resolve; - let debug_name = format!("{module}-{}", info.name); - let name = self.shims.len().to_string(); - - let options = RequiredOptions::for_payload(resolve, info, &kind, async_); - if !options.contains(RequiredOptions::REALLOC) - && world.info.imports.imported_memory().is_some() - { - return; - } - self.push(Shim { - name, - debug_name, - options, - kind: ShimKind::PayloadFunc { - for_module, - info, - kind, - }, - sig: WasmSignature { - params, - results, - indirect_params: false, - retptr: false, - }, - }); - let realloc = payload_realloc_name(world, for_module, info); - self.push_realloc( - world, - for_module, - ReallocSite::AfterInstantiation, - options, - realloc, - ); - } - - /// Helper for `append_indirect` above which will conditionally push a shim - /// for the WIT function specified by `interface_key`, `name`, and `abi`. - fn append_indirect_wit_func( - &mut self, - world: &'a ComponentWorld<'a>, - for_module: CustomModule<'a>, - module: &str, - field: &str, - key: &WorldKey, - name: &String, - interface_key: Option, - abi: AbiVariant, - ) -> Result<()> { - let resolve = &world.encoder.metadata.resolve; - let metadata = world.module_metadata_for(for_module); - let interface = &world.import_map[&interface_key]; - let (index, _, lowering) = interface.lowerings.get_full(&(name.clone(), abi)).unwrap(); - let shim_name = self.shims.len().to_string(); - match lowering { - Lowering::ResourceDrop(_) => {} - - Lowering::Direct { options } => { - let realloc = world - .exports_for(for_module) - .import_realloc_for(interface.interface, name); - self.push_realloc( - world, - for_module, - ReallocSite::BeforeInstantiation, - *options, - realloc, - ); - } - - Lowering::Indirect { sig, options } => { - log::debug!( - "shim {shim_name} is import `{module}::{field}` lowering {index} `{name}`", - ); - let encoding = metadata - .import_encodings - .get(resolve, key, name) - .ok_or_else(|| { - anyhow::anyhow!( - "missing component metadata for import of \ - `{module}::{field}`" - ) - })?; - self.push(Shim { - name: shim_name, - debug_name: format!("indirect-{module}-{field}"), - options: *options, - kind: ShimKind::IndirectLowering { - interface: interface_key, - index, - realloc: for_module, - encoding, - }, - sig: sig.clone(), - }); - - let realloc = world - .exports_for(for_module) - .import_realloc_for(interface.interface, name); - self.push_realloc( - world, - for_module, - ReallocSite::AfterInstantiation, - *options, - realloc, - ); - } - } - - Ok(()) - } - - /// Registers a shim, if one is necessary, for the `realloc` function named - /// `export` within `for_module` which is going to be used at `site` by - /// something requiring `options`. - fn push_realloc( - &mut self, - world: &'a ComponentWorld<'a>, - for_module: CustomModule<'a>, - site: ReallocSite, - options: RequiredOptions, - export: Option<&'a str>, - ) { - if !options.contains(RequiredOptions::REALLOC) { - return; - } - let Some((for_module, export)) = resolve_realloc(world, for_module, export) else { - return; - }; - if !realloc_needs_shim(world, site) { - return; - } - let name = self.shims.len().to_string(); - self.push(Shim { - name, - debug_name: format!("realloc-{}-{export}", for_module.debug_name()), - options: RequiredOptions::empty(), - kind: ShimKind::Realloc { - module: for_module, - export, - }, - sig: WasmSignature { - params: vec![WasmType::I32; 4], - results: vec![WasmType::I32], - indirect_params: false, - retptr: false, - }, - }); - } - - fn push(&mut self, shim: Shim<'a>) { - // Only one shim per `ShimKind` is retained, so if it's already present - // don't overwrite it. If it's not present though go ahead and insert - // it. - if !self.shims.contains_key(&shim.kind) { - self.shims.insert(shim.kind.clone(), shim); - } - } -} - -/// Resolves which module, and which export of it, provides the `realloc` -/// canonical option for `module`, where `export` is `module`'s own realloc -/// export if it has one. -/// -/// Libraries in a shared-everything link which don't export a realloc of their -/// own fall back to the one shared by the rest of the link -fn resolve_realloc<'a>( - world: &'a ComponentWorld<'a>, - module: CustomModule<'a>, - export: Option<&'a str>, -) -> Option<(CustomModule<'a>, &'a str)> { - if let Some(export) = export { - return Some((module, export)); - } - match module { - // If the main module doesn't have a realloc, then there's nothing to - // use. - CustomModule::Main => None, - - // For libraries fallback to the realloc in the main module, if present. - CustomModule::Adapter(name) => { - let _info = world.adapters[name].library_info.as_ref()?; - let main_realloc = world.info.exports.general_purpose_realloc()?; - Some((CustomModule::Main, main_realloc)) - } - } -} - -fn payload_realloc_name<'a>( - world: &'a ComponentWorld<'_>, - for_module: CustomModule<'_>, - info: &PayloadInfo, -) -> Option<&'a str> { - let exports = world.exports_for(for_module); - match &info.ty { - PayloadType::Type { function, .. } => { - if info.imported { - exports.import_realloc_for(info.interface, function) - } else { - exports.export_realloc_for(&info.key, function) - } - } - PayloadType::UnitFuture | PayloadType::UnitStream => None, - } -} - -fn task_return_options_and_type( - resolve: &Resolve, - func: &Function, -) -> (RequiredOptions, WasmSignature) { - let func_tmp = Function { - name: String::new(), - kind: FunctionKind::Freestanding, - params: match &func.result { - Some(ty) => vec![Param { - name: "a".to_string(), - ty: *ty, - span: Default::default(), - }], - None => Vec::new(), - }, - result: None, - docs: Default::default(), - stability: Stability::Unknown, - span: Default::default(), - external_id: None, - }; - let abi = AbiVariant::GuestImport; - let mut options = RequiredOptions::for_import(resolve, func, abi); - // `task.return` does not support a `realloc` canonical option. - options.remove(RequiredOptions::REALLOC); - let sig = resolve.wasm_signature(abi, &func_tmp); - (options, sig) -} - -/// Alias argument to an instantiation -#[derive(Clone, Debug)] -pub struct Item { - pub alias: String, - pub kind: ExportKind, - pub which: MainOrAdapter, - pub name: String, -} - -/// Module argument to an instantiation -#[derive(Debug, PartialEq, Clone)] -pub enum MainOrAdapter { - Main, - Adapter(String), -} - -impl MainOrAdapter { - fn to_custom_module(&self) -> CustomModule<'_> { - match self { - MainOrAdapter::Main => CustomModule::Main, - MainOrAdapter::Adapter(s) => CustomModule::Adapter(s), - } - } -} - -/// Module instantiation argument -#[derive(Clone)] -pub enum Instance { - /// Module argument - MainOrAdapter(MainOrAdapter), - - /// Alias argument - Items(Vec), -} - -/// Provides fine-grained control of how a library module is instantiated -/// relative to other module instances -#[derive(Clone)] -pub struct LibraryInfo { - /// Instantiation arguments - pub arguments: Vec<(String, Instance)>, -} - -/// Represents an adapter or library to be instantiated as part of the component -pub(super) struct Adapter { - /// The wasm of the module itself, with `component-type` sections stripped - wasm: Vec, - - /// The metadata for the adapter - metadata: ModuleMetadata, - - /// The set of exports from the final world which are defined by this - /// adapter or library - required_exports: IndexSet, - - /// If present, treat this module as a library rather than a "minimal" adapter - /// - /// TODO: We should refactor how various flavors of module are represented - /// and differentiated to avoid mistaking one for another. - library_info: Option, -} - -/// An encoder of components based on `wit` interface definitions. -#[derive(Default)] -pub struct ComponentEncoder { - module: Vec, - module_import_map: Option, - pub(super) metadata: Bindgen, - validate: bool, - pub(super) main_module_exports: IndexSet, - pub(super) adapters: IndexMap, - import_name_map: HashMap, - realloc_via_memory_grow: bool, - merge_imports_based_on_semver: Option, - pub(super) reject_legacy_names: bool, - debug_names: bool, - shim_return_call_ref: bool, -} - -impl ComponentEncoder { - /// Set the core module to encode as a component. - /// This method will also parse any component type information stored in custom sections - /// inside the module and add them as the interface, imports, and exports. - /// It will also add any producers information inside the component type information to the - /// core module. - pub fn module(&mut self, module: &[u8]) -> Result<&mut Self> { - let (wasm, metadata) = self.decode(module.as_ref())?; - let (wasm, module_import_map) = ModuleImportMap::new(wasm)?; - self.module = if let Some(producers) = &metadata.producers { - producers.add_to_wasm(&wasm)? - } else { - wasm.to_vec() - }; - let exports = self - .merge_metadata(metadata) - .context("failed merge WIT metadata for module with previous metadata")?; - self.main_module_exports.extend(exports); - self.module_import_map = module_import_map; - Ok(self) - } - - fn decode<'a>(&self, wasm: &'a [u8]) -> Result<(Cow<'a, [u8]>, Bindgen)> { - let (bytes, metadata) = metadata::decode(wasm)?; - match bytes { - Some(wasm) => Ok((Cow::Owned(wasm), metadata)), - None => Ok((Cow::Borrowed(wasm), metadata)), - } - } - - fn merge_metadata(&mut self, metadata: Bindgen) -> Result> { - self.metadata.merge(metadata) - } - - /// Sets whether or not the encoder will validate its output. - pub fn validate(&mut self, validate: bool) -> &mut Self { - self.validate = validate; - self - } - - /// Sets whether or not to generate debug names in the output component. - pub fn debug_names(&mut self, debug_names: bool) -> &mut Self { - self.debug_names = debug_names; - self - } - - /// Configures whether the shim module, if needed, will use - /// `return_call_ref` as opposed to the default `call_indirect`. - pub fn shim_return_call_ref(&mut self, enable: bool) -> &mut Self { - self.shim_return_call_ref = enable; - self - } - - /// Sets whether to merge imports based on semver to the specified value. - /// - /// This affects how when to WIT worlds are merged together, for example - /// from two different libraries, whether their imports are unified when the - /// semver version ranges for interface allow it. - /// - /// This is enabled by default. - pub fn merge_imports_based_on_semver(&mut self, merge: bool) -> &mut Self { - self.merge_imports_based_on_semver = Some(merge); - self - } - - /// Sets whether to reject the historical mangling/name scheme for core wasm - /// imports/exports as they map to the component model. - /// - /// The `wit-component` crate supported a different set of names prior to - /// WebAssembly/component-model#378 and this can be used to disable this - /// support. - /// - /// This is disabled by default. - pub fn reject_legacy_names(&mut self, reject: bool) -> &mut Self { - self.reject_legacy_names = reject; - self - } - - /// Specifies a new adapter which is used to translate from a historical - /// wasm ABI to the canonical ABI and the `interface` provided. - /// - /// This is primarily used to polyfill, for example, - /// `wasi_snapshot_preview1` with a component-model using interface. The - /// `name` provided is the module name of the adapter that is being - /// polyfilled, for example `"wasi_snapshot_preview1"`. - /// - /// The `bytes` provided is a core wasm module which implements the `name` - /// interface in terms of the `interface` interface. This core wasm module - /// is severely restricted in its shape, for example it cannot have any data - /// segments or element segments. - /// - /// The `interface` provided is the component-model-using-interface that the - /// wasm module specified by `bytes` imports. The `bytes` will then import - /// `interface` and export functions to get imported from the module `name` - /// in the core wasm that's being wrapped. - pub fn adapter(&mut self, name: &str, bytes: &[u8]) -> Result<&mut Self> { - self.library_or_adapter(name, bytes, None) - } - - /// Specifies a shared-everything library to link into the component. - /// - /// Unlike adapters, libraries _may_ have data and/or element segments, but - /// they must operate on an imported memory and table, respectively. In - /// this case, the correct amount of space is presumed to have been - /// statically allocated in the main module's memory and table at the - /// offsets which the segments target, e.g. as arranged by - /// [super::linking::Linker]. - /// - /// Libraries are treated similarly to adapters, except that they are not - /// "minified" the way adapters are, and instantiation is controlled - /// declaratively via the `library_info` parameter. - pub fn library( - &mut self, - name: &str, - bytes: &[u8], - library_info: LibraryInfo, - ) -> Result<&mut Self> { - self.library_or_adapter(name, bytes, Some(library_info)) - } - - fn library_or_adapter( - &mut self, - name: &str, - bytes: &[u8], - library_info: Option, - ) -> Result<&mut Self> { - let (wasm, mut metadata) = self.decode(bytes)?; - // Merge the adapter's document into our own document to have one large - // document, and then afterwards merge worlds as well. - // - // Note that the `metadata` tracking import/export encodings is removed - // since this adapter can get different lowerings and is allowed to - // differ from the main module. This is then tracked within the - // `Adapter` structure produced below. - let adapter_metadata = mem::take(&mut metadata.metadata); - let exports = self.merge_metadata(metadata).with_context(|| { - format!("failed to merge WIT packages of adapter `{name}` into main packages") - })?; - if let Some(library_info) = &library_info { - // Validate that all referenced modules can be resolved. - for (_, instance) in &library_info.arguments { - let resolve = |which: &_| match which { - MainOrAdapter::Main => Ok(()), - MainOrAdapter::Adapter(name) => { - if self.adapters.contains_key(name.as_str()) { - Ok(()) - } else { - Err(anyhow!("instance refers to unknown adapter `{name}`")) - } - } - }; - - match instance { - Instance::MainOrAdapter(which) => resolve(which)?, - Instance::Items(items) => { - for item in items { - resolve(&item.which)?; - } - } - } - } - } - self.adapters.insert( - name.to_string(), - Adapter { - wasm: wasm.to_vec(), - metadata: adapter_metadata, - required_exports: exports, - library_info, - }, - ); - Ok(self) - } - - /// Whether adapters use `memory.grow` for realloc and stack allocation. - /// - /// By default an adapter imports `cabi_realloc` from the main module. - /// Setting this to `true` makes it allocate with `memory.grow` instead, - /// which can be useful if `cabi_realloc` cannot be called before the host - /// runtime is initialized. - /// - /// This only affects modules added with [`ComponentEncoder::adapter`]. It - /// has no effect on the main module and does not synthesize a - /// `cabi_realloc` for a module that doesn't export one. - pub fn realloc_via_memory_grow(&mut self, value: bool) -> &mut Self { - self.realloc_via_memory_grow = value; - self - } - - /// The instance import name map to use. - /// - /// This is used to rename instance imports in the final component. - /// - /// For example, if there is an instance import `foo:bar/baz` and it is - /// desired that the import actually be an `unlocked-dep` name, then - /// `foo:bar/baz` can be mapped to `unlocked-dep==x.y.z}>`. - /// - /// Note: the replacement names are not validated during encoding unless - /// the `validate` option is set to true. - pub fn import_name_map(&mut self, map: HashMap) -> &mut Self { - self.import_name_map = map; - self - } - - /// Encode the component and return the bytes. - pub fn encode(&mut self) -> Result> { - self.encode_with_fixups(None) - } - - pub(crate) fn encode_with_fixups( - &mut self, - fixup_hook: Option<&mut dyn FnMut(&mut fixup::FixupModule) -> Result<()>>, - ) -> Result> { - if self.module.is_empty() { - bail!("a module is required when encoding a component"); - } - - if self.merge_imports_based_on_semver.unwrap_or(true) { - self.metadata - .resolve - .merge_world_imports_based_on_semver(self.metadata.world)?; - } - - self.finalize_resolve_with_nominal_ids(); - - let world = ComponentWorld::new(self).context("failed to decode world from module")?; - let mut state = EncodingState { - component: ComponentBuilder::default(), - module_index: None, - instance_index: None, - memory_index: None, - shim_instance_index: None, - adapter_modules: IndexMap::new(), - adapter_instances: IndexMap::new(), - type_encoding_maps: Default::default(), - instances: Default::default(), - imported_funcs: Default::default(), - aliased_core_items: Default::default(), - info: &world, - export_task_initialization_wrappers: HashMap::new(), - }; - state.encode_imports(&self.import_name_map)?; - state.encode_core_modules(); - state.encode_core_instantiation(fixup_hook)?; - state.encode_exports(CustomModule::Main)?; - for name in self.adapters.keys() { - state.encode_exports(CustomModule::Adapter(name))?; - } - state.component.append_names(); - state - .component - .raw_custom_section(&crate::base_producers().raw_custom_section()); - let bytes = state.component.finish(); - - if self.validate { - Validator::new_with_features(WasmFeatures::all()) - .validate_all(&bytes) - .context("failed to validate component output")?; - } - - Ok(bytes) - } - - /// Call the `generate_nominal_type_ids` method on the `Resolve` that we're - /// using, adjusting any preexisting keys/pointers as necessary. - /// - /// This is the final step after merging all known `Resolve`s together - /// before a component is actually created. By creating a unique - /// `InterfaceId` for all interfaces it makes the generation process easier - /// since there's no need to fret about whether an `InterfaceId` is an - /// import or an export for example. - fn finalize_resolve_with_nominal_ids(&mut self) { - // Before calling `generate_nominal_type_ids` we need to handle the fact - // that the exports of the world are going to be rewritten. The only - // pointers we have into those are the exports of the main module and - // adapters. To handle this, before we generate nominal ids, indices of - // exports are saved here on the stack to get restored later on. - // Effectively we're clearing out the exports and rebuilding them later. - let world = &self.metadata.resolve.worlds[self.metadata.world]; - let main_module_exports = self - .main_module_exports - .iter() - .map(|i| world.exports.get_index_of(i).unwrap()) - .collect::>(); - let adapter_exports = self - .adapters - .values() - .map(|adapter| { - adapter - .required_exports - .iter() - .map(|i| world.exports.get_index_of(i).unwrap()) - .collect::>() - }) - .collect::>(); - - // With everything saved this will modify `Resolve` to ensure there's a - // nominal identifier for all interfaces (e.g. not both simultaneously - // imported and exported). - self.metadata - .resolve - .generate_nominal_type_ids(self.metadata.world); - - // Rebuild the sets of exports now that the world's exports have been - // clobbered. - self.main_module_exports.clear(); - let world = &self.metadata.resolve.worlds[self.metadata.world]; - for index in main_module_exports { - let (key, _) = world.exports.get_index(index).unwrap(); - self.main_module_exports.insert(key.clone()); - } - for (exports, adapter) in adapter_exports.into_iter().zip(self.adapters.values_mut()) { - adapter.required_exports.clear(); - for index in exports { - let (key, _) = world.exports.get_index(index).unwrap(); - adapter.required_exports.insert(key.clone()); - } - } - } -} - -impl ComponentWorld<'_> { - /// Convenience function to lookup a module's import map. - fn imports_for(&self, module: CustomModule) -> &ImportMap { - match module { - CustomModule::Main => &self.info.imports, - CustomModule::Adapter(name) => &self.adapters[name].info.imports, - } - } - - /// Convenience function to lookup a module's export map. - fn exports_for(&self, module: CustomModule) -> &ExportMap { - match module { - CustomModule::Main => &self.info.exports, - CustomModule::Adapter(name) => &self.adapters[name].info.exports, - } - } - - /// Convenience function to lookup a module's metadata. - fn module_metadata_for(&self, module: CustomModule) -> &ModuleMetadata { - match module { - CustomModule::Main => &self.encoder.metadata.metadata, - CustomModule::Adapter(name) => &self.encoder.adapters[name].metadata, - } - } -} - -#[cfg(all(test, feature = "dummy-module"))] -mod test { - use super::*; - use crate::{dummy_module, embed_component_metadata}; - use wit_parser::ManglingAndAbi; - - #[test] - fn it_renames_imports() { - let mut resolve = Resolve::new(); - let pkg = resolve - .push_str( - "test.wit", - r#" -package test:wit; - -interface i { - f: func(); -} - -world test { - import i; - import foo: interface { - f: func(); - } -} -"#, - ) - .unwrap(); - let world = resolve.select_world(&[pkg], None).unwrap(); - - let mut module = dummy_module(&resolve, world, ManglingAndAbi::Standard32); - - embed_component_metadata(&mut module, &resolve, world, StringEncoding::UTF8).unwrap(); - - let encoded = ComponentEncoder::default() - .import_name_map(HashMap::from([ - ( - "foo".to_string(), - "unlocked-dep==1.0.0 <1.1.0}>".to_string(), - ), - ( - "test:wit/i".to_string(), - "locked-dep=".to_string(), - ), - ])) - .module(&module) - .unwrap() - .validate(true) - .encode() - .unwrap(); - - let wat = wasmprinter::print_bytes(encoded).unwrap(); - assert!(wat.contains("unlocked-dep==1.0.0 <1.1.0}>")); - assert!(wat.contains("locked-dep=")); - } -} diff --git a/vendor/wit-component/src/encoding/dedupe.rs b/vendor/wit-component/src/encoding/dedupe.rs deleted file mode 100644 index 6f0b1fc8..00000000 --- a/vendor/wit-component/src/encoding/dedupe.rs +++ /dev/null @@ -1,164 +0,0 @@ -//! Support for deduplicating module imports when turning them into a component. -//! -//! Core wasm allows for duplicate imports of the same name/field in a core wasm -//! module. This is not allowed in the component model, however, meaning that -//! such a core wasm module cannot be inserted into a component as-is. This -//! module is tasked with tackling this problem. -//! -//! The general idea of this module is to rewrite imports in-place to a -//! different and unique name. The original name is then recorded in -//! [`ModuleImportMap`] which is then plumbed through to the location that -//! classifies all imports. The classification then uses the original names for -//! what an import should be resolved to but records it under the unique names -//! generated here. - -use anyhow::Result; -use std::borrow::Cow; -use std::collections::HashMap; -use std::fmt::Write; -use wasm_encoder::reencode::{Reencode, RoundtripReencoder}; -use wasm_encoder::{ImportSection, RawSection}; -use wasmparser::{Parser, Payload::*}; - -/// A map of current names (possibly new) to original names, if any. -#[derive(Default)] -pub struct ModuleImportMap { - /// A two-level map for what names map to what. - /// - /// * The first level of the map is the "module" field, or the first string, - /// in a wasm import. - /// * The second level of the map is the "name" field, or the second string, - /// in a wasm import. - /// * The value of the second level is what this name was originally found - /// under in the original module. `None` means "same as the hash map key" - /// while `Some` means "it's this new name". - /// - /// This map is built during `ModuleImportMap::new` and serves double-duty - /// to actually track duplicate imports. - renamed_to_original: HashMap>>, -} - -impl ModuleImportMap { - /// Creates a new [`ModuleImportMap`] tracking duplicate imports, if any, - /// from the `wasm` provided. - /// - /// Upon success a new wasm binary (possibly the same as the original) is - /// returned which is the new source of truth for this module. If duplicate - /// imports were found then a [`ModuleImportMap`] is returned, otherwise - /// `None` is returned. - /// - /// # Errors - /// - /// Returns an error if `wasm` could not be parsed as a wasm module. - pub fn new<'a>(wasm: Cow<'a, [u8]>) -> Result<(Cow<'a, [u8]>, Option)> { - let mut module = wasm_encoder::Module::new(); - let mut ret = ModuleImportMap::default(); - let mut found_duplicate_imports = false; - - for payload in Parser::new(0).parse_all(&wasm) { - let payload = payload?; - match payload { - Version { encoding, .. } if encoding == wasmparser::Encoding::Component => { - // if this is a component let someone else deal with the - // error, we'll punt that up the stack. - assert!(!found_duplicate_imports); - break; - } - - // This is the section we're interested in. Go over each import - // and delegate to `ModuleImportMap::push_import` for figuring - // out what to do with this import. At the end put the new - // import section in the `module` we're building. - ImportSection(i) => { - let mut new_import_section = ImportSection::new(); - for import in i.clone().into_imports() { - found_duplicate_imports = ret - .push_import(&mut new_import_section, import?)? - || found_duplicate_imports; - } - module.section(&new_import_section); - } - - // All other sections get plumbed through as-is. This ensures we - // don't tamper with binary offsets anywhere in the module - // except the import section, for example. - _ => { - if let Some((id, range)) = payload.as_section() { - module.section(&RawSection { - id, - data: &wasm[range.start as usize..range.end as usize], - }); - } - } - } - } - - if found_duplicate_imports { - Ok((module.finish().into(), Some(ret))) - } else { - Ok((wasm, None)) - } - } - - /// Returns `Ok(true)` if this is a duplicate import, or `Ok(false)` if it's - /// a unique import for the first time. - fn push_import( - &mut self, - new_import_section: &mut ImportSection, - import: wasmparser::Import<'_>, - ) -> Result { - let module_map = self - .renamed_to_original - .entry(import.module.to_string()) - .or_insert(HashMap::new()); - - // If this import hasn't yet been seen, then great! Record that it is - // using its original name and encode it with its original name. - if !module_map.contains_key(import.name) { - let prev = module_map.insert(import.name.to_string(), None); - assert!(prev.is_none()); - RoundtripReencoder.parse_import(new_import_section, import)?; - return Ok(false); - } - - // FIXME: this is technically O(n^2), but it's also only applicable when - // a module has lots of imports, and surely that won't happen often... - // right? ... right? - // - // If this isn't fixed by the time someone reads this and is angry about - // O(n^2), sorry. - // - // Otherwise the purpose of this loop is to determine a unique name for - // the new import, something that hasn't previously been seen before. - let mut new_name = import.name.to_string(); - for i in 2.. { - new_name.truncate(import.name.len()); - write!(new_name, " [v{i}]").unwrap(); - if !module_map.contains_key(&new_name) { - break; - } - } - - // Now that `new_name` is unique, record the import in the new import - // section. - let mut new_import = import; - new_import.name = &new_name; - RoundtripReencoder.parse_import(new_import_section, new_import)?; - - // Also record that `new_name` was originally known as `import.name` - // for later lookup in `original_names` below. - let prev = module_map.insert(new_name, Some(import.name.to_string())); - assert!(prev.is_none()); - Ok(true) - } - - /// Returns the original `name` that `import` should use, if any. - /// - /// If `None` is returned then `import.name` should be used. - pub fn original_name(&self, import: &wasmparser::Import<'_>) -> Option<&str> { - self.renamed_to_original - .get(import.module)? - .get(import.name)? - .as_deref() - } -} diff --git a/vendor/wit-component/src/encoding/fixup.rs b/vendor/wit-component/src/encoding/fixup.rs deleted file mode 100644 index f39df917..00000000 --- a/vendor/wit-component/src/encoding/fixup.rs +++ /dev/null @@ -1,906 +0,0 @@ -use crate::ComponentEncoder; -use crate::encoding::{CustomModule, EncodingState, Shim, ShimKind, Shims}; -use crate::validation::Export; -use anyhow::{Result, bail}; -use indexmap::IndexMap; -use std::collections::HashMap; -use std::mem; -use wasm_encoder::*; -use wit_parser::WorldItem; -use wit_parser::abi::{AbiVariant, WasmSignature}; - -#[derive(Default)] -pub struct FixupModule { - // Incrementally-built-up sections of the module-to-be. - types: TypeSection, - imports: ImportSection, - function_names: NameMap, - global_names: NameMap, - elements: ElementSection, - data: DataSection, - - /// Interning map for type signatures. - type_map: HashMap<(Vec, Vec), u32>, - - /// The start function, if needed. This is split between "ABI details" and - /// "user funcs" where ABI details must happen first and user funcs need to - /// be wrapped in task intrinsics if provided. - start_abi_details: Vec, - start_user_funcs: Vec, - - /// Entries used to initialize the imported shim's table, if necessary. - shims_in_table: Vec, - - /// Entries to go into a declared element segment. - declared_funcs: Vec, - - /// The instance names that are imported into this module, and what those - /// instances correspond to. - imported_instances: IndexMap, - - /// Interning map for imports. - imported_items: HashMap<(String, String), (u32, EntityType)>, - - /// Functions that will be defined in this module itself. - /// - /// This is deferred to get emitted until the very end so all imports have - /// been settled and then these import indices can be known. - defined_functions: Vec<(u32, DefinedFunction)>, - - // Current counters for index spaces. - funcs: u32, - globals: u32, - tables: u32, - memories: u32, -} - -/// Different instances that can be imported into the fixup module. -#[derive(Clone, PartialEq, Eq, Hash, Debug)] -pub enum ImportedInstance { - /// The original "shim" module with stubs that need to be filled in. - Shim, - /// The "main" module. - Main, - /// A synthetic instance created by collecting actual implementations of - /// shims from various locations. - Actual, - /// A named adapter module. - Adapter(String), -} - -pub enum StartAction { - /// Sets `$global` to `ref.func $shim` - InitGlobal { - /// The index in `declared_funcs` of the function to fill in. - shim: usize, - /// The global being set. - global: u32, - }, - /// Calls the specified function index. - Call(u32), - /// Used during the `link`-part of `wit-component` this adds the - /// `memory_base` and `export` globals together and stores the result in - /// `dest`. - InitializeAddress { - memory_base: u32, - export: u32, - dest: AddressDest, - }, - /// Invoke the `func` hook with the `hook` argument. - CallHook { func: u32, hook: TaskHook }, -} - -pub enum AddressDest { - /// A linear memory address that's statically known. - LinearMemory { address: u32, memory: u32 }, - /// A global indexed by the argument here. - Global(u32), -} - -/// What can be used to fill in a shim that was originally defined in the shim -/// module. -/// -/// Functions specified here either go into an element segment to fill in the -/// original shim module's table or they're inserted into globals. -enum ShimFill { - /// An imported function. - Import(u32), - /// An imported function which is also known to be a resource destructor. - /// Used to know when to insert task hooks. - ImportedResourceDtor(u32), - /// A `realloc` function which is exported from `instance` under the name - /// `export` and imported here as `func`. - Realloc { - instance: ImportedInstance, - export: String, - func: u32, - }, - /// A function defined in this fixup module. - DefinedFunction(usize), -} - -/// Different functions that can be defined in the fixup module, apart from the -/// `start` function. -enum DefinedFunction { - /// A function which wraps a core export to ensure that task state is set up - /// before the core export is called. - HookedCoreExport { - /// The task hook function. - task_hook: u32, - /// The core function to call and delegate to. - to_wrap: u32, - /// The number of parameters to forward to `export`. - params: usize, - /// The debug-related core name of this function it's hooking. - core_name: String, - /// If `Some` this is the instance that is is exported for which will - /// get inserted into `EncodingState`'s export wrapper map. - export: Option, - /// The kind of hook to use at the start of this function. - start: Option, - /// The kind of hook to use at the end of this function. - end: EndTaskHook, - }, -} - -#[derive(Copy, Clone)] -pub enum TaskHook { - /// A synchronous task has started. - SyncStart = 0, - /// A synchronous task has finished. - SyncFinish = 1, - /// An async task has started. - AsyncStart = 2, - /// An async has resumed in its `callback` option. - AsyncResume = 3, - /// An async blocked, but not yet completed, and it's returning from either - /// the main entrypoint or the `callback` option. - AsyncBlock = 4, - /// An async task has finished, returning from either the main entrypoint or - /// the `callback` option. - AsyncFinish = 5, - /// The `_initialize` function and other ctors are being called. - InitializeStart = 6, - /// The `_initialize` function and other ctors are finished. - InitializeFinish = 7, - /// A resource destructor is starting. - ResourceDtorStart = 8, - /// A resource destructor is finished. - ResourceDtorFinish = 9, - // - // 10/11 intentionally missing - // - /// A `realloc` function used as a canonical ABI option is being invoked. - ReallocStart = 12, - /// A `realloc` function used as a canonical ABI option has finished. - ReallocFinish = 13, -} - -enum EndTaskHook { - None, - AsyncCode, - Normal(TaskHook), -} - -impl FixupModule { - /// Returns the 0-parameter 0-result function type. - pub fn type_thunk(&mut self) -> u32 { - self.type_intern(Vec::new(), Vec::new()) - } - - /// Interns `params`/`results` as a function type. - pub fn type_intern(&mut self, params: Vec, results: Vec) -> u32 { - *self - .type_map - .entry((params.clone(), results.clone())) - .or_insert_with(|| { - let index = self.types.len(); - self.types - .ty() - .function(params.iter().copied(), results.iter().copied()); - index - }) - } - - fn type_index(&mut self, sig: &WasmSignature) -> u32 { - self.type_intern( - sig.params.iter().map(super::to_val_type).collect(), - sig.results.iter().map(super::to_val_type).collect(), - ) - } - - fn import_instance(&mut self, kind: &ImportedInstance) -> Result { - let name = match kind { - ImportedInstance::Shim => "shim", - ImportedInstance::Main => "main", - ImportedInstance::Actual => "actual", - ImportedInstance::Adapter(name) => name.as_str(), - }; - let name = name.to_string(); - if let Some(prev) = self.imported_instances.insert(name.clone(), kind.clone()) { - if prev != *kind { - bail!("instance `{name}` was already imported as a different kind: {prev:?}"); - } - } - Ok(name) - } - - /// Imports a new item into this fixup module to get used by later - /// functions/etc. - /// - /// Returns the index that the item is imported as. - pub fn import( - &mut self, - instance: &ImportedInstance, - name: &str, - ty: EntityType, - ) -> Result { - let module = self.import_instance(instance)?; - let key = (module, name.to_string()); - if let Some((index, prev)) = self.imported_items.get(&key) { - if *prev != ty { - bail!( - "`{}::{name}` was already imported with a different type", - key.0 - ); - } - return Ok(*index); - } - // Note that debug names are recorded here, rather than in the helpers - // below, so that a name is only recorded for a freshly created import. - let ret = match ty { - EntityType::Function(_) => { - let index = inc(&mut self.funcs); - self.function_names.append(index, name); - index - } - EntityType::Global(_) => { - let index = inc(&mut self.globals); - self.global_names.append(index, name); - index - } - EntityType::Table(_) => inc(&mut self.tables), - EntityType::Memory(_) => inc(&mut self.memories), - EntityType::Tag(_) | EntityType::FunctionExact(_) => unimplemented!(), - }; - self.imports.import(&key.0, name, ty); - self.imported_items.insert(key, (ret, ty)); - Ok(ret) - } - - /// Helper over `self.import(...)` - pub fn import_global( - &mut self, - instance: &ImportedInstance, - name: &str, - ty: GlobalType, - ) -> Result { - self.import(instance, name, ty.into()) - } - - /// Helper over `self.import(...)` - pub fn import_func(&mut self, instance: &ImportedInstance, name: &str, ty: u32) -> Result { - self.import(instance, name, EntityType::Function(ty)) - } - - /// Appends to the `start` function that'll get generated. - pub fn add_start_abi_detail(&mut self, action: StartAction) { - self.start_abi_details.push(action); - } - - /// Appends to the `start` function that'll get generated. - pub fn add_start_user_func(&mut self, action: StartAction) { - self.start_user_funcs.push(action); - } - - /// Returns the underlying element section. - pub fn elements(&mut self) -> &mut ElementSection { - &mut self.elements - } - - /// Returns the underlying data section. - pub fn data(&mut self) -> &mut DataSection { - &mut self.data - } - - /// Adds `shim` to this fixup module to get filled in. - pub(super) fn add_shim(&mut self, opts: &ComponentEncoder, shim: &Shim) -> Result<()> { - let type_index = self.type_index(&shim.sig); - let func = self.import_func(&ImportedInstance::Actual, &shim.name, type_index)?; - - let shim_fill = match &shim.kind { - ShimKind::Realloc { module, export } => ShimFill::Realloc { - instance: module.to_imported_instance(), - export: export.to_string(), - func, - }, - ShimKind::ResourceDtor { .. } => ShimFill::ImportedResourceDtor(func), - _ => ShimFill::Import(func), - }; - - if opts.shim_return_call_ref { - let global = self.import_global( - &ImportedInstance::Shim, - &format!("g{}", &shim.name), - GlobalType { - val_type: RefType { - heap_type: HeapType::Concrete(type_index), - nullable: false, - } - .into(), - mutable: true, - shared: false, - }, - )?; - - self.start_abi_details.push(StartAction::InitGlobal { - shim: self.declared_funcs.len(), - global, - }); - self.declared_funcs.push(shim_fill); - } else { - self.shims_in_table.push(shim_fill); - } - Ok(()) - } - - /// Ensures there's a `start` function which invokes `initialize`. - pub fn add_initialize(&mut self, initialize: &str) -> Result<()> { - let ty = self.type_thunk(); - let func = self.import_func(&ImportedInstance::Main, initialize, ty)?; - self.start_user_funcs.push(StartAction::Call(func)); - Ok(()) - } - - pub(super) fn instantiate( - &mut self, - shims: &Shims<'_>, - state: &mut EncodingState<'_>, - ) -> Result<()> { - // First inject task hooks as necessary throughout the module which is - // the final step before actually encoding the module. - self.prepare_task_hooks(state)?; - - // Generate the module, and this'll return `None` if the module isn't - // necessary in which case we bail out. - let Some(module) = self.encode(state)? else { - return Ok(()); - }; - - // Embed this fixup module in the component. - let module_index = state - .component - .core_module(Some("wit-component-fixup"), &module); - - // Prepare the arguments used to instantiate this component based on the - // `imported_instances` map that's been generated. - let mut instance_args = Vec::new(); - for (name, instance) in self.imported_instances.iter() { - let index = match instance { - ImportedInstance::Main => state - .instance_index - .expect("must have an instantiated module"), - ImportedInstance::Adapter(name) => state.adapter_instances[name.as_str()], - ImportedInstance::Shim => state - .shim_instance_index - .expect("must have an instantiated shim"), - ImportedInstance::Actual => { - let mut actual = Vec::new(); - for shim in shims.shims.values() { - let core_func_index = state.encode_shim(shims, shim)?; - actual.push((shim.name.as_str(), ExportKind::Func, core_func_index)); - } - state - .component - .core_instantiate_exports(Some("actual"), actual) - } - }; - instance_args.push((name.as_str(), ModuleArg::Instance(index))); - } - - // The side-effectful instantiation of the fixup instance. - let instance = state - .component - .core_instantiate(Some("fixup"), module_index, instance_args); - - // If there are hooked core exports in this module then register within - // `state` that they should be preferred over their raw brethren. - for (i, (_ty, func)) in self.defined_functions.iter().enumerate() { - match func { - DefinedFunction::HookedCoreExport { - core_name, - export: Some(from), - .. - } => { - let name = format!("hook{i}"); - let wrapper = - state.core_alias_export(Some(&name), instance, &name, ExportKind::Func); - state - .export_task_initialization_wrappers - .insert((from.clone(), core_name.clone()), wrapper); - } - DefinedFunction::HookedCoreExport { export: None, .. } => {} - } - } - Ok(()) - } - - fn encode(&mut self, state: &EncodingState<'_>) -> Result> { - let opts = &state.info.encoder; - if self.start_abi_details.is_empty() - && self.start_user_funcs.is_empty() - && self.shims_in_table.is_empty() - && self.declared_funcs.is_empty() - && self.elements.is_empty() - && self.data.is_empty() - && self.defined_functions.is_empty() - { - return Ok(None); - } - - let mut functions = FunctionSection::new(); - let mut code = CodeSection::new(); - let mut exports = ExportSection::new(); - - // First define functions within this module now that the import space - // for functions has settled. - let mut defined_func_indices = Vec::new(); - for (i, (ty, func)) in self.defined_functions.iter().enumerate() { - functions.function(*ty); - let index = inc(&mut self.funcs); - defined_func_indices.push(index); - let mut func = match func { - DefinedFunction::HookedCoreExport { - task_hook, - to_wrap, - params, - core_name, - export, - start, - end, - } => { - let mut locals = Vec::new(); - if let EndTaskHook::AsyncCode = end { - locals.push((1, ValType::I32)); - } - let mut f = Function::new(locals); - if let Some(start) = *start { - f.instructions().i32_const(start as i32).call(*task_hook); - } - for i in 0..*params { - f.instructions().local_get(i as u32); - } - f.instructions().call(*to_wrap); - match end { - EndTaskHook::AsyncCode => { - f.instructions() - .local_set(*params as u32) - // 0 == EXIT, 1/2 == yield/wait, so delegate to - // appropriate code. - // - // First thing pushed on the stack is "if true", - // which in this case nonzero means blocking. - // Second thing is "if false" meaning if 0 - // meaning EXIT meaning "done". Final thing is - // what to test, the return code. - .i32_const(TaskHook::AsyncBlock as i32) - .i32_const(TaskHook::AsyncFinish as i32) - .local_get(*params as u32) - .select() - .call(*task_hook) - // put the return code back on the stack to - // actually return - .local_get(*params as u32); - } - EndTaskHook::Normal(hook) => { - f.instructions().i32_const(*hook as i32).call(*task_hook); - } - EndTaskHook::None => {} - } - if export.is_some() { - exports.export(&format!("hook{i}"), ExportKind::Func, index); - } - self.function_names - .append(index, &format!("hook-{core_name}")); - f - } - }; - func.instructions().end(); - code.function(&func); - } - - // Using our defined functions above it's possible to implement - // resolution of `ShimFill` items. - let resolve_shim = |shim: &ShimFill| match shim { - ShimFill::Import(func) => *func, - ShimFill::ImportedResourceDtor(func) => *func, - ShimFill::DefinedFunction(i) => defined_func_indices[*i], - ShimFill::Realloc { func, .. } => *func, - }; - - // If this fixup is filling in a table, then import the table and use an - // element segment for its initialization. - if !self.shims_in_table.is_empty() { - let table_type = TableType { - element_type: RefType::FUNCREF, - minimum: self.shims_in_table.len() as u64, - maximum: Some(self.shims_in_table.len() as u64), - table64: false, - shared: false, - }; - let table = self.import( - &ImportedInstance::Shim, - super::INDIRECT_TABLE_NAME, - table_type.into(), - )?; - self.elements.active( - if table == 0 { None } else { Some(table) }, - &ConstExpr::i32_const(0), - Elements::Functions( - self.shims_in_table - .iter() - .map(resolve_shim) - .collect::>() - .into(), - ), - ); - } - - // Codegen the start function here. Special case an empty start function - // or just a single function call as the start function, otherwise each - // item needs to be handled individually. - let start = match (&self.start_abi_details[..], &self.start_user_funcs[..]) { - ([], []) => None, - ([], [StartAction::Call(func)]) => Some(*func), - (first, second) => { - let mut start = Function::new(Vec::new()); - for action in first.iter().chain(second.iter()) { - match action { - StartAction::InitGlobal { shim, global } => { - let func = resolve_shim(&self.declared_funcs[*shim]); - start.instructions().ref_func(func).global_set(*global); - } - StartAction::Call(func) => { - start.instructions().call(*func); - } - StartAction::CallHook { func, hook } => { - start.instructions().i32_const(*hook as i32).call(*func); - } - StartAction::InitializeAddress { - memory_base, - export, - dest, - } => match dest { - AddressDest::LinearMemory { address, memory } => { - start - .instructions() - .i32_const(*address as i32) - .global_get(*memory_base) - .global_get(*export) - .i32_add() - .i32_store(MemArg { - offset: 0, - align: 2, - memory_index: *memory, - }); - } - AddressDest::Global(global) => { - start - .instructions() - .global_get(*memory_base) - .global_get(*export) - .i32_add() - .global_set(*global); - } - }, - } - } - start.instructions().end(); - let index = inc(&mut self.funcs); - let ty = self.type_thunk(); - functions.function(ty); - code.function(&start); - self.function_names.append(index, "start"); - Some(index) - } - }; - - // Fill in the declared element segment, if necessary, used for - // `ref.func` in the start function above. - if !self.declared_funcs.is_empty() { - self.elements.declared(Elements::Functions( - self.declared_funcs - .iter() - .map(resolve_shim) - .collect::>() - .into(), - )); - } - - // Now that we've got all the pieces weave everything into a `Module`. - let mut module = Module::default(); - if !self.types.is_empty() { - module.section(&self.types); - } - if !self.imports.is_empty() { - module.section(&self.imports); - } - if !functions.is_empty() { - module.section(&functions); - } - if !exports.is_empty() { - module.section(&exports); - } - if let Some(start) = start { - module.section(&StartSection { - function_index: start, - }); - } - if !self.elements.is_empty() { - module.section(&self.elements); - } - if !code.is_empty() { - module.section(&code); - } - if !self.data.is_empty() { - module.section(&self.data); - } - module.section(&RawCustomSection( - &crate::base_producers().raw_custom_section(), - )); - - if opts.debug_names { - let mut names = NameSection::new(); - names.module("wit-component:fixups"); - if !self.function_names.is_empty() { - names.functions(&self.function_names); - } - if !self.global_names.is_empty() { - names.globals(&self.global_names); - } - module.section(&names); - } - - Ok(Some(module)) - } - - /// Prepares task hooks, like `__wasm_init_task`, to be configured in - /// various locations throughout this fixup module. - /// - /// This handles: - /// - /// * The `_initialize` function (needs task setup first) - /// * Hooks for all exports which are lifted. - fn prepare_task_hooks(&mut self, state: &mut EncodingState<'_>) -> Result<()> { - let info_main = state.info.exports_for(CustomModule::Main); - let Some(task_hook) = info_main.wasm_task_hook() else { - return Ok(()); - }; - let ty = self.type_intern(vec![ValType::I32], Vec::new()); - let task_hook = self.import_func(&ImportedInstance::Main, task_hook, ty)?; - - // Handle the start function first where if there's something registered - // in the "user function" area we need to configure that to work. - if !self.start_user_funcs.is_empty() { - self.start_user_funcs.insert( - 0, - StartAction::CallHook { - func: task_hook, - hook: TaskHook::InitializeStart, - }, - ); - self.start_user_funcs.push(StartAction::CallHook { - func: task_hook, - hook: TaskHook::InitializeFinish, - }); - } - - // Afterwards handle all exports for the main/adapter modules. - self.prepare_export_task_hooks_for(state, CustomModule::Main, task_hook)?; - for adapter in state.info.adapters.keys() { - self.prepare_export_task_hooks_for(state, CustomModule::Adapter(adapter), task_hook)?; - } - - // Next up generate wrappers for all `realloc` functions which might be - // used as a canonical option. - let mut reallocs = HashMap::new(); - self.prepare_realloc_task_hooks_for(state, CustomModule::Main, task_hook, &mut reallocs)?; - for adapter in state.info.adapters.keys() { - self.prepare_realloc_task_hooks_for( - state, - CustomModule::Adapter(adapter), - task_hook, - &mut reallocs, - )?; - } - - // And finally redirect/fixup shims that need hooks to defined versions - // locally in this module. - let mut shims_in_table = mem::take(&mut self.shims_in_table); - let mut declared_funcs = mem::take(&mut self.declared_funcs); - for shim in shims_in_table.iter_mut().chain(declared_funcs.iter_mut()) { - match shim { - // Resource destructors are handled here directly inline. - ShimFill::ImportedResourceDtor(func) => { - let func = *func; - let ty = self.type_intern(vec![ValType::I32], Vec::new()); - *shim = ShimFill::DefinedFunction(self.defined_functions.len()); - self.defined_functions.push(( - ty, - DefinedFunction::HookedCoreExport { - task_hook, - to_wrap: func, - params: 1, - start: Some(TaskHook::ResourceDtorStart), - end: EndTaskHook::Normal(TaskHook::ResourceDtorFinish), - export: None, - core_name: format!("resource-dtor"), - }, - )); - } - - // All realloc functions were hooked above in - // `prepare_realloc_task_hooks_for` so this just looks up in the - // map built there to figure out which function to redirect to. - ShimFill::Realloc { - instance, export, .. - } => { - let func = reallocs - .get(&(instance.clone(), export.clone())) - .copied() - .expect("realloc wrapper should have been generated"); - *shim = ShimFill::DefinedFunction(func); - } - - ShimFill::Import(_) | ShimFill::DefinedFunction(_) => {} - }; - } - - self.shims_in_table = shims_in_table; - self.declared_funcs = declared_funcs; - - Ok(()) - } - - /// Generates a task hook wrapper for each `realloc` function exported by - /// `for_module` which may be used as a canonical option. - /// - /// These wrappers are themselves imported from the fixup module for use in - /// lifts-of-exports, and then additionally these are used to fill in - /// `ShimFill::Realloc` later on. - fn prepare_realloc_task_hooks_for( - &mut self, - state: &mut EncodingState<'_>, - for_module: CustomModule<'_>, - task_hook: u32, - reallocs: &mut HashMap<(ImportedInstance, String), usize>, - ) -> Result<()> { - let instance = for_module.to_imported_instance(); - for name in state.info.exports_for(for_module).reallocs() { - let ty = self.type_intern(vec![ValType::I32; 4], vec![ValType::I32]); - let func = self.import_func(&instance, name, ty)?; - let index = self.defined_functions.len(); - self.defined_functions.push(( - ty, - DefinedFunction::HookedCoreExport { - task_hook, - to_wrap: func, - params: 4, - start: Some(TaskHook::ReallocStart), - end: EndTaskHook::Normal(TaskHook::ReallocFinish), - export: Some(instance.clone()), - core_name: name.to_string(), - }, - )); - reallocs.insert((instance.clone(), name.to_string()), index); - } - Ok(()) - } - - /// Looks over the exports of `for_module` and adds any functions as - /// necessary to `self.defined_functions` which hook the original export to - /// ensure it's got task state set up when called first. - fn prepare_export_task_hooks_for( - &mut self, - state: &mut EncodingState<'_>, - for_module: CustomModule<'_>, - task_hook: u32, - ) -> Result<()> { - let resolve = &state.info.encoder.metadata.resolve; - let world = &resolve.worlds[state.info.encoder.metadata.world]; - let info = state.info.exports_for(for_module); - let imported_instance = for_module.to_imported_instance(); - - for (core_name, export) in info.iter() { - let (key, f, abi) = match export { - Export::WorldFunc(key, _, abi) => match &world.exports[key] { - WorldItem::Function(f) => (key, f, abi), - _ => continue, - }, - Export::InterfaceFunc(key, id, func_name, abi) => { - let func = &resolve.interfaces[*id].functions[func_name.as_str()]; - (key, func, abi) - } - _ => continue, - }; - - let sig = resolve.wasm_signature(*abi, f); - let ty = self.type_index(&sig); - let func = self.import_func(&imported_instance, core_name, ty)?; - let post_return = info.post_return(key, f); - self.defined_functions.push(( - ty, - DefinedFunction::HookedCoreExport { - task_hook, - to_wrap: func, - export: Some(imported_instance.clone()), - params: sig.params.len(), - core_name: core_name.to_string(), - start: Some(if abi.is_async() { - TaskHook::AsyncStart - } else { - TaskHook::SyncStart - }), - end: if abi.is_async() { - assert!(post_return.is_none()); - if *abi == AbiVariant::GuestExportAsyncStackful { - EndTaskHook::Normal(TaskHook::AsyncFinish) - } else { - EndTaskHook::AsyncCode - } - } else { - if post_return.is_some() { - EndTaskHook::None - } else { - EndTaskHook::Normal(TaskHook::SyncFinish) - } - }, - }, - )); - - if let Some(post_return) = info.post_return(key, f) { - let mut post_return_sig = sig.clone(); - post_return_sig.params = mem::take(&mut post_return_sig.results); - let ty = self.type_index(&post_return_sig); - let func = self.import_func(&imported_instance, post_return, ty)?; - self.defined_functions.push(( - ty, - DefinedFunction::HookedCoreExport { - task_hook, - to_wrap: func, - export: Some(imported_instance.clone()), - params: post_return_sig.params.len(), - core_name: post_return.to_string(), - start: None, - end: EndTaskHook::Normal(TaskHook::SyncFinish), - }, - )); - } - - if let Some(callback) = info.callback(key, f) { - let ty = self.type_intern(vec![ValType::I32; 3], vec![ValType::I32]); - let func = self.import_func(&imported_instance, callback, ty)?; - self.defined_functions.push(( - ty, - DefinedFunction::HookedCoreExport { - task_hook, - to_wrap: func, - export: Some(imported_instance.clone()), - params: 3, - core_name: callback.to_string(), - start: Some(TaskHook::AsyncResume), - end: EndTaskHook::AsyncCode, - }, - )); - } - } - - Ok(()) - } -} - -fn inc(i: &mut u32) -> u32 { - let ret = *i; - *i += 1; - ret -} diff --git a/vendor/wit-component/src/encoding/types.rs b/vendor/wit-component/src/encoding/types.rs deleted file mode 100644 index 6b43e5a8..00000000 --- a/vendor/wit-component/src/encoding/types.rs +++ /dev/null @@ -1,538 +0,0 @@ -use super::EncodingState; -use anyhow::Result; -use std::collections::HashMap; -use wasm_encoder::*; -use wit_parser::{ - Enum, Flags, Function, Handle, InterfaceId, Param, Record, Resolve, Result_, Tuple, Type, - TypeDefKind, TypeId, TypeOwner, Variant, -}; - -/// A view of `&[Param]` that compares and hashes by name and type only, -/// ignoring source spans. -#[derive(Clone)] -struct ParamSignatures<'a>(&'a [Param]); - -impl PartialEq for ParamSignatures<'_> { - fn eq(&self, other: &Self) -> bool { - self.0.len() == other.0.len() - && self - .0 - .iter() - .zip(other.0) - .all(|(a, b)| a.name == b.name && a.ty == b.ty) - } -} - -impl Eq for ParamSignatures<'_> {} - -impl std::hash::Hash for ParamSignatures<'_> { - fn hash(&self, state: &mut H) { - for p in self.0 { - p.name.hash(state); - p.ty.hash(state); - } - } -} - -/// Represents a key type for interface function definitions. -#[derive(Hash, PartialEq, Eq, Clone)] -pub struct FunctionKey<'a> { - async_: bool, - params: ParamSignatures<'a>, - result: &'a Option, -} - -#[derive(Default, Clone)] -pub struct TypeEncodingMaps<'a> { - pub id_to_index: HashMap, - pub def_to_index: HashMap<&'a TypeDefKind, u32>, - pub func_type_map: HashMap, u32>, - pub unit_future: Option, - pub unit_stream: Option, -} - -impl<'a> TypeEncodingMaps<'a> { - /// Returns the index used to encode `id`, if it has been previously - /// encoded. - fn lookup(&self, resolve: &'a Resolve, id: TypeId) -> Option { - // If this exact id has been encoded before, use that. - if let Some(index) = self.id_to_index.get(&id) { - return Some(*index); - } - - // If this is an anonymous type, or one where the name of the type is - // `none`, then consult the `def_to_index` map as well. - let ty = &resolve.types[id]; - if ty.name.is_none() { - if let Some(index) = self.def_to_index.get(&ty.kind) { - return Some(*index); - } - } - - // Failing all that this hasn't previously been encoded. - None - } - - /// Inserts that `id` was encoded as `index`. - fn insert(&mut self, resolve: &'a Resolve, id: TypeId, index: u32) { - // Always record the id=>index mapping. - self.id_to_index.insert(id, index); - - // Conditionally record the kind=>index mapping if the type is anonymous - // and thus a candidate to use. - let ty = &resolve.types[id]; - if ty.name.is_none() { - self.def_to_index.insert(&ty.kind, index); - } - } -} - -/// Support for encoding a wit-parser type into a component. -/// -/// This is a `trait` to enable different implementations which define types -/// slightly differently in different contexts. For example types might be -/// defined within an instance type's index space or might be defined in the -/// component's root index space in a type section. The default trait methods -/// here are intended to assist in multiplexing over this difference. -pub trait ValtypeEncoder<'a> { - /// Returns a new type encoder used to define a new type in this type - /// section. - /// - /// The `u32` returned is the index of the type being defined in this type - /// index space and the encoder returned must be used to define a type. - fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>); - - /// Returns the index of a new function type and the encoder of where to - /// place its results. - fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>); - - /// Creates an export item for the specified type index. - fn export_type(&mut self, index: u32, name: ComponentExternName<'a>) -> Option; - - /// Creates a new `(type (sub resource))` export with the given name, - /// returning the type index that refers to the fresh type created. - fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32; - - /// Returns the encoding maps used to encoding types such as id-to-index - /// maps. - fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a>; - - /// Imports `id` from a different interface, returning the index of the - /// imported type into this index space. - fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32; - - /// Returns the identifier of the interface that generation is for. - fn interface(&self) -> Option; - - /// Encodes a new function type which is defined within the provided - /// document. - fn encode_func_type(&mut self, resolve: &'a Resolve, func: &'a Function) -> Result { - let key = FunctionKey { - async_: func.kind.is_async(), - params: ParamSignatures(&func.params), - result: &func.result, - }; - if let Some(index) = self.type_encoding_maps().func_type_map.get(&key) { - return Ok(*index); - } - - // Encode all referenced parameter types from this function. - let params: Vec<_> = self.encode_params(resolve, &func.params)?; - - let result = func - .result - .map(|ty| self.encode_valtype(resolve, &ty)) - .transpose()?; - - // Encode the function type - let (index, mut f) = self.define_function_type(); - f.async_(func.kind.is_async()).params(params).result(result); - let prev = self.type_encoding_maps().func_type_map.insert(key, index); - assert!(prev.is_none()); - Ok(index) - } - - fn encode_params( - &mut self, - resolve: &'a Resolve, - params: &'a [Param], - ) -> Result> { - params - .iter() - .map(|p| Ok((p.name.as_str(), self.encode_valtype(resolve, &p.ty)?))) - .collect::>() - } - - /// Encodes the `ty`, defined within `resolve`, into this encoder and returns - /// the corresponding `ComponentValType` that it represents. - /// - /// This will recursively define the entire structure of `ty` within `self` - /// if necessary. - fn encode_valtype(&mut self, resolve: &'a Resolve, ty: &Type) -> Result { - Ok(match *ty { - Type::Bool => ComponentValType::Primitive(PrimitiveValType::Bool), - Type::U8 => ComponentValType::Primitive(PrimitiveValType::U8), - Type::U16 => ComponentValType::Primitive(PrimitiveValType::U16), - Type::U32 => ComponentValType::Primitive(PrimitiveValType::U32), - Type::U64 => ComponentValType::Primitive(PrimitiveValType::U64), - Type::S8 => ComponentValType::Primitive(PrimitiveValType::S8), - Type::S16 => ComponentValType::Primitive(PrimitiveValType::S16), - Type::S32 => ComponentValType::Primitive(PrimitiveValType::S32), - Type::S64 => ComponentValType::Primitive(PrimitiveValType::S64), - Type::F32 => ComponentValType::Primitive(PrimitiveValType::F32), - Type::F64 => ComponentValType::Primitive(PrimitiveValType::F64), - Type::Char => ComponentValType::Primitive(PrimitiveValType::Char), - Type::String => ComponentValType::Primitive(PrimitiveValType::String), - Type::ErrorContext => ComponentValType::Primitive(PrimitiveValType::ErrorContext), - Type::Id(id) => { - // If this id has already been prior defined into this section - // refer to that definition. - if let Some(index) = self.type_encoding_maps().lookup(resolve, id) { - return Ok(ComponentValType::Type(index)); - } - - let ty = &resolve.types[id]; - - // If this type is imported from another interface then return - // it as it was bound here with an alias. - log::trace!("encode type name={:?} {:?}", ty.name, &ty.kind); - if let Some(index) = self.maybe_import_type(resolve, id) { - self.type_encoding_maps().insert(resolve, id, index); - return Ok(ComponentValType::Type(index)); - } - - // ... and failing all that insert the type export. - let mut encoded = match &ty.kind { - TypeDefKind::Record(r) => self.encode_record(resolve, r)?, - TypeDefKind::Tuple(t) => self.encode_tuple(resolve, t)?, - TypeDefKind::Flags(r) => self.encode_flags(r)?, - TypeDefKind::Variant(v) => self.encode_variant(resolve, v)?, - TypeDefKind::Option(t) => self.encode_option(resolve, t)?, - TypeDefKind::Result(r) => self.encode_result(resolve, r)?, - TypeDefKind::Enum(e) => self.encode_enum(e)?, - TypeDefKind::List(ty) => { - let ty = self.encode_valtype(resolve, ty)?; - let (index, encoder) = self.defined_type(); - encoder.list(ty); - ComponentValType::Type(index) - } - TypeDefKind::Map(key_ty, value_ty) => { - let key = self.encode_valtype(resolve, key_ty)?; - let value = self.encode_valtype(resolve, value_ty)?; - let (index, encoder) = self.defined_type(); - encoder.map(key, value); - ComponentValType::Type(index) - } - TypeDefKind::FixedLengthList(ty, elements) => { - let ty = self.encode_valtype(resolve, ty)?; - let (index, encoder) = self.defined_type(); - encoder.fixed_length_list(ty, *elements); - ComponentValType::Type(index) - } - TypeDefKind::Type(ty) => self.encode_valtype(resolve, ty)?, - TypeDefKind::Future(ty) => self.encode_future(resolve, ty)?, - TypeDefKind::Stream(ty) => self.encode_stream(resolve, ty)?, - TypeDefKind::Unknown => unreachable!(), - TypeDefKind::Resource => { - let name = ty.name.as_ref().expect("resources must be named"); - let index = - self.export_resource(extern_name(name, ty.external_id.as_deref())); - self.type_encoding_maps().id_to_index.insert(id, index); - return Ok(ComponentValType::Type(index)); - } - TypeDefKind::Handle(Handle::Own(id)) => { - let ty = match self.encode_valtype(resolve, &Type::Id(*id))? { - ComponentValType::Type(index) => index, - _ => panic!("must be an indexed type"), - }; - let (index, encoder) = self.defined_type(); - encoder.own(ty); - ComponentValType::Type(index) - } - TypeDefKind::Handle(Handle::Borrow(id)) => { - let ty = match self.encode_valtype(resolve, &Type::Id(*id))? { - ComponentValType::Type(index) => index, - _ => panic!("must be an indexed type"), - }; - let (index, encoder) = self.defined_type(); - encoder.borrow(ty); - ComponentValType::Type(index) - } - }; - - if let Some(name) = &ty.name { - let index = match encoded { - ComponentValType::Type(index) => index, - ComponentValType::Primitive(ty) => { - // Named primitive types need entries in the type - // section, so convert this to a type reference - let (index, encoder) = self.defined_type(); - encoder.primitive(ty); - index - } - }; - let index = self - .export_type(index, extern_name(name, ty.external_id.as_deref())) - .unwrap_or(index); - - encoded = ComponentValType::Type(index); - } - - if let ComponentValType::Type(index) = encoded { - self.type_encoding_maps().insert(resolve, id, index); - } - - encoded - } - }) - } - - /// Optionally imports `id` from a different interface, returning the index - /// of the imported type into this index space. - /// - /// Returns `None` if `id` can't be imported. - fn maybe_import_type(&mut self, resolve: &Resolve, id: TypeId) -> Option { - let ty = &resolve.types[id]; - let owner = match ty.owner { - TypeOwner::Interface(i) => i, - _ => return None, - }; - if Some(owner) == self.interface() { - return None; - } - Some(self.import_type(owner, id)) - } - - fn encode_optional_valtype( - &mut self, - resolve: &'a Resolve, - ty: Option<&Type>, - ) -> Result> { - match ty { - Some(ty) => self.encode_valtype(resolve, ty).map(Some), - None => Ok(None), - } - } - - fn encode_record(&mut self, resolve: &'a Resolve, record: &Record) -> Result { - let fields = record - .fields - .iter() - .map(|f| Ok((f.name.as_str(), self.encode_valtype(resolve, &f.ty)?))) - .collect::>>()?; - - let (index, encoder) = self.defined_type(); - encoder.record(fields); - Ok(ComponentValType::Type(index)) - } - - fn encode_tuple(&mut self, resolve: &'a Resolve, tuple: &Tuple) -> Result { - let tys = tuple - .types - .iter() - .map(|ty| self.encode_valtype(resolve, ty)) - .collect::>>()?; - let (index, encoder) = self.defined_type(); - encoder.tuple(tys); - Ok(ComponentValType::Type(index)) - } - - fn encode_flags(&mut self, flags: &Flags) -> Result { - let (index, encoder) = self.defined_type(); - encoder.flags(flags.flags.iter().map(|f| f.name.as_str())); - Ok(ComponentValType::Type(index)) - } - - fn encode_variant( - &mut self, - resolve: &'a Resolve, - variant: &Variant, - ) -> Result { - let cases = variant - .cases - .iter() - .map(|c| { - Ok(( - c.name.as_str(), - self.encode_optional_valtype(resolve, c.ty.as_ref())?, - )) - }) - .collect::>>()?; - - let (index, encoder) = self.defined_type(); - encoder.variant(cases); - Ok(ComponentValType::Type(index)) - } - - fn encode_option(&mut self, resolve: &'a Resolve, payload: &Type) -> Result { - let ty = self.encode_valtype(resolve, payload)?; - let (index, encoder) = self.defined_type(); - encoder.option(ty); - Ok(ComponentValType::Type(index)) - } - - fn encode_result( - &mut self, - resolve: &'a Resolve, - result: &Result_, - ) -> Result { - let ok = self.encode_optional_valtype(resolve, result.ok.as_ref())?; - let error = self.encode_optional_valtype(resolve, result.err.as_ref())?; - let (index, encoder) = self.defined_type(); - encoder.result(ok, error); - Ok(ComponentValType::Type(index)) - } - - fn encode_enum(&mut self, enum_: &Enum) -> Result { - let (index, encoder) = self.defined_type(); - encoder.enum_type(enum_.cases.iter().map(|c| c.name.as_str())); - Ok(ComponentValType::Type(index)) - } - - fn encode_future( - &mut self, - resolve: &'a Resolve, - payload: &Option, - ) -> Result { - let ty = self.encode_optional_valtype(resolve, payload.as_ref())?; - let (index, encoder) = self.defined_type(); - encoder.future(ty); - Ok(ComponentValType::Type(index)) - } - - fn encode_stream( - &mut self, - resolve: &'a Resolve, - payload: &Option, - ) -> Result { - let ty = self.encode_optional_valtype(resolve, payload.as_ref())?; - let (index, encoder) = self.defined_type(); - encoder.stream(ty); - Ok(ComponentValType::Type(index)) - } - - fn encode_unit_future(&mut self) -> u32 { - if let Some(index) = self.type_encoding_maps().unit_future { - return index; - } - let (index, encoder) = self.defined_type(); - encoder.future(None); - self.type_encoding_maps().unit_future = Some(index); - index - } - - fn encode_unit_stream(&mut self) -> u32 { - if let Some(index) = self.type_encoding_maps().unit_stream { - return index; - } - let (index, encoder) = self.defined_type(); - encoder.stream(None); - self.type_encoding_maps().unit_stream = Some(index); - index - } -} - -/// Helper to create a `ComponentExternName` from its component parts found -/// within a WIT AST node. -pub fn extern_name<'a>(name: &'a str, external_id: Option<&'a str>) -> ComponentExternName<'a> { - ComponentExternName { - name: name.into(), - implements: None, - external_id: external_id.map(|s| s.into()), - version_suffix: None, - } -} - -pub struct RootTypeEncoder<'state, 'a> { - pub state: &'state mut EncodingState<'a>, - pub interface: Option, - pub import_types: bool, -} - -impl<'a> ValtypeEncoder<'a> for RootTypeEncoder<'_, 'a> { - fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { - self.state.component.type_defined(None) - } - fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { - self.state.component.type_function(None) - } - fn interface(&self) -> Option { - self.interface - } - fn export_type(&mut self, idx: u32, name: ComponentExternName<'a>) -> Option { - // When encoding types for the root the root component will export - // this type, but when encoding types for a targeted interface then we - // can't export types just yet. Interfaces will be created as an - // instance with a bag-of-exports construction which can't refer to its - // own types. - if self.interface.is_none() { - Some(if self.import_types { - self.state - .component - .import(name, ComponentTypeRef::Type(TypeBounds::Eq(idx))) - } else { - self.state - .component - .export(name, ComponentExportKind::Type, idx, None) - }) - } else { - assert!(!self.import_types); - None - } - } - fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32 { - assert!(self.interface.is_none()); - assert!(self.import_types); - self.state - .component - .import(name, ComponentTypeRef::Type(TypeBounds::SubResource)) - } - fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 { - self.state.alias_instance_type_export(interface, id) - } - fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { - &mut self.state.type_encoding_maps - } -} - -pub struct InstanceTypeEncoder<'state, 'a> { - pub state: &'state mut EncodingState<'a>, - pub interface: InterfaceId, - pub type_encoding_maps: TypeEncodingMaps<'a>, - pub ty: InstanceType, -} - -impl<'a> ValtypeEncoder<'a> for InstanceTypeEncoder<'_, 'a> { - fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { - (self.ty.type_count(), self.ty.ty().defined_type()) - } - fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { - (self.ty.type_count(), self.ty.ty().function()) - } - fn export_type(&mut self, idx: u32, name: ComponentExternName<'a>) -> Option { - let ret = self.ty.type_count(); - self.ty - .export(name, ComponentTypeRef::Type(TypeBounds::Eq(idx))); - Some(ret) - } - fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32 { - let ret = self.ty.type_count(); - self.ty - .export(name, ComponentTypeRef::Type(TypeBounds::SubResource)); - ret - } - fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { - &mut self.type_encoding_maps - } - fn interface(&self) -> Option { - Some(self.interface) - } - fn import_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 { - self.ty.alias(Alias::Outer { - count: 1, - index: self.state.alias_instance_type_export(interface, id), - kind: ComponentOuterAliasKind::Type, - }); - self.ty.type_count() - 1 - } -} diff --git a/vendor/wit-component/src/encoding/wit.rs b/vendor/wit-component/src/encoding/wit.rs deleted file mode 100644 index a70f90cc..00000000 --- a/vendor/wit-component/src/encoding/wit.rs +++ /dev/null @@ -1,408 +0,0 @@ -use crate::encoding::types::{TypeEncodingMaps, ValtypeEncoder, extern_name}; -use anyhow::Result; -use indexmap::IndexSet; -use std::collections::HashMap; -use std::mem; -use wasm_encoder::*; -use wit_parser::*; - -/// Encodes the given `package` within `resolve` to a binary WebAssembly -/// representation. -/// -/// This function is the root of the implementation of serializing a WIT package -/// into a WebAssembly representation. The wasm representation serves two -/// purposes: -/// -/// * One is to be a binary encoding of a WIT document which is ideally more -/// stable than the WIT textual format itself. -/// * Another is to provide a clear mapping of all WIT features into the -/// component model through use of its binary representation. -/// -/// The `resolve` provided is a set of packages and types and such and the -/// `package` argument is an ID within the world provided. The documents within -/// `package` will all be encoded into the binary returned. -/// -/// The binary returned can be [`decode`d](crate::decode) to recover the WIT -/// package provided. -pub fn encode(resolve: &Resolve, package: PackageId) -> Result> { - let mut component = encode_component(resolve, package)?; - component.raw_custom_section(&crate::base_producers().raw_custom_section()); - Ok(component.finish()) -} - -/// Encodes the given `package` within `resolve` to a binary WebAssembly -/// representation. -/// -/// This function is the root of the implementation of serializing a WIT package -/// into a WebAssembly representation. The wasm representation serves two -/// purposes: -/// -/// * One is to be a binary encoding of a WIT document which is ideally more -/// stable than the WIT textual format itself. -/// * Another is to provide a clear mapping of all WIT features into the -/// component model through use of its binary representation. -/// -/// The `resolve` provided is a set of packages and types and such and the -/// `package` argument is an ID within the world provided. The documents within -/// `package` will all be encoded into the binary returned. -/// -/// The binary returned can be [`decode`d](crate::decode) to recover the WIT -/// package provided. -pub fn encode_component(resolve: &Resolve, package: PackageId) -> Result { - let mut encoder = Encoder { - component: ComponentBuilder::default(), - resolve, - package, - }; - encoder.run()?; - - let package_metadata = PackageMetadata::extract(resolve, package); - encoder.component.custom_section(&CustomSection { - name: PackageMetadata::SECTION_NAME.into(), - data: package_metadata.encode()?.into(), - }); - - Ok(encoder.component) -} - -/// Encodes a `world` as a component type. -pub fn encode_world(resolve: &Resolve, world_id: WorldId) -> Result { - let mut component = InterfaceEncoder::new(resolve); - let world = &resolve.worlds[world_id]; - log::trace!("encoding world {}", world.name); - - // Encode the imports - for (key, import) in world.imports.iter() { - log::trace!("encoding import {}", resolve.name_world_key(key)); - let ty = match import { - WorldItem::Interface { id, .. } => { - component.interface = Some(*id); - let idx = component.encode_instance(*id)?; - ComponentTypeRef::Instance(idx) - } - WorldItem::Function(f) => { - component.interface = None; - let idx = component.encode_func_type(resolve, f)?; - ComponentTypeRef::Func(idx) - } - WorldItem::Type { id, .. } => { - component.interface = None; - component.import_types = true; - component.encode_valtype(resolve, &Type::Id(*id))?; - component.import_types = false; - continue; - } - }; - component - .outer - .import(component_extern_name(resolve, key, import), ty); - } - // Encode the exports - for (key, export) in world.exports.iter() { - log::trace!("encoding export {}", resolve.name_world_key(key)); - let ty = match export { - WorldItem::Interface { id, .. } => { - component.interface = Some(*id); - let idx = component.encode_instance(*id)?; - ComponentTypeRef::Instance(idx) - } - WorldItem::Function(f) => { - component.interface = None; - let idx = component.encode_func_type(resolve, f)?; - ComponentTypeRef::Func(idx) - } - WorldItem::Type { .. } => unreachable!(), - }; - component - .outer - .export(component_extern_name(resolve, key, export), ty); - } - - Ok(component.outer) -} - -fn component_extern_name( - resolve: &Resolve, - key: &WorldKey, - item: &WorldItem, -) -> wasm_encoder::ComponentExternName<'static> { - ComponentExternName { - name: resolve.name_world_key(key).into(), - implements: resolve.implements_value(key, item).map(|s| s.into()), - external_id: resolve.external_id_value(key, item).map(|s| s.into()), - version_suffix: None, - } -} - -struct Encoder<'a> { - component: ComponentBuilder, - resolve: &'a Resolve, - package: PackageId, -} - -impl Encoder<'_> { - fn run(&mut self) -> Result<()> { - // Encode all interfaces as component types and then export them. - for (name, &id) in self.resolve.packages[self.package].interfaces.iter() { - let component_ty = self.encode_interface(id)?; - let ty = self.component.type_component(Some(name), &component_ty); - self.component - .export(name, ComponentExportKind::Type, ty, None); - } - - // For each `world` encode it directly as a component and then create a - // wrapper component that exports that component. - for (name, &world) in self.resolve.packages[self.package].worlds.iter() { - let component_ty = encode_world(self.resolve, world)?; - - let world = &self.resolve.worlds[world]; - let mut wrapper = ComponentType::new(); - wrapper.ty().component(&component_ty); - let pkg = &self.resolve.packages[world.package.unwrap()]; - wrapper.export(pkg.name.interface_id(name), ComponentTypeRef::Component(0)); - - let ty = self.component.type_component(Some(name), &wrapper); - self.component - .export(name, ComponentExportKind::Type, ty, None); - } - - Ok(()) - } - - fn encode_interface(&mut self, id: InterfaceId) -> Result { - // Build a set of interfaces reachable from this document, including the - // interfaces in the document itself. This is used to import instances - // into the component type we're encoding. Note that entire interfaces - // are imported with all their types as opposed to just the needed types - // in an interface for this document. That's done to assist with the - // decoding process where everyone's view of a foreign document agrees - // notably on the order that types are defined in to assist with - // roundtripping. - let mut interfaces = IndexSet::new(); - self.add_live_interfaces(&mut interfaces, id); - - // Seed the set of used names with all exported interfaces to ensure - // that imported interfaces choose different names as the import names - // aren't used during decoding. - let mut used_names = IndexSet::new(); - for id in interfaces.iter() { - let iface = &self.resolve.interfaces[*id]; - if iface.package == Some(self.package) { - let first = used_names.insert(iface.name.as_ref().unwrap().clone()); - assert!(first); - } - } - - let mut encoder = InterfaceEncoder::new(self.resolve); - for interface in interfaces { - encoder.interface = Some(interface); - let iface = &self.resolve.interfaces[interface]; - let name = self.resolve.id_of(interface).unwrap(); - if interface == id { - let idx = encoder.encode_instance(interface)?; - log::trace!("exporting self as {idx}"); - encoder.outer.export(name, ComponentTypeRef::Instance(idx)); - } else { - encoder.push_instance(); - for (_, id) in iface.types.iter() { - encoder.encode_valtype(self.resolve, &Type::Id(*id))?; - } - let instance = encoder.pop_instance(); - let idx = encoder.outer.type_count(); - encoder.outer.ty().instance(&instance); - encoder.import_map.insert(interface, encoder.instances); - encoder.instances += 1; - encoder.outer.import(name, ComponentTypeRef::Instance(idx)); - } - } - - encoder.interface = None; - - Ok(encoder.outer) - } - - /// Recursively add all live interfaces reachable from `id` into the - /// `interfaces` set, and then add `id` to the set. - fn add_live_interfaces(&self, interfaces: &mut IndexSet, id: InterfaceId) { - if interfaces.contains(&id) { - return; - } - for id in self.resolve.interface_direct_deps(id) { - self.add_live_interfaces(interfaces, id); - } - assert!(interfaces.insert(id)); - } -} - -struct InterfaceEncoder<'a> { - resolve: &'a Resolve, - outer: ComponentType, - ty: Option, - type_encoding_maps: TypeEncodingMaps<'a>, - saved_maps: Option>, - import_map: HashMap, - outer_type_map: HashMap, - instances: u32, - import_types: bool, - interface: Option, -} - -impl InterfaceEncoder<'_> { - fn new(resolve: &Resolve) -> InterfaceEncoder<'_> { - InterfaceEncoder { - resolve, - outer: ComponentType::new(), - ty: None, - type_encoding_maps: Default::default(), - import_map: Default::default(), - outer_type_map: Default::default(), - instances: 0, - saved_maps: None, - import_types: false, - interface: None, - } - } - - fn encode_instance(&mut self, interface: InterfaceId) -> Result { - self.push_instance(); - let iface = &self.resolve.interfaces[interface]; - let mut type_order = IndexSet::new(); - for (_, id) in iface.types.iter() { - self.encode_valtype(self.resolve, &Type::Id(*id))?; - type_order.insert(*id); - } - - // Sort functions based on whether or not they're associated with - // resources. - // - // This is done here to ensure that when a WIT package is printed as WIT - // then decoded, or if it's printed as Wasm then decoded, the final - // result is the same. When printing via WIT resource methods are - // attached to the resource types themselves meaning that they'll appear - // intermingled with the rest of the types, namely first before all - // other functions. The purpose of this sort is to perform a stable sort - // over all functions by shuffling the resource-related functions first, - // in order of when their associated resource was encoded, and putting - // freestanding functions last. - // - // Note that this is not actually required for correctness, it's - // basically here to make fuzzing happy. - let mut funcs = iface.functions.iter().collect::>(); - funcs.sort_by_key(|(_name, func)| match func.kind.resource() { - Some(id) => type_order.get_index_of(&id).unwrap(), - None => type_order.len(), - }); - - for (name, func) in funcs { - let ty = self.encode_func_type(self.resolve, func)?; - self.ty.as_mut().unwrap().export( - extern_name(name, func.external_id.as_deref()), - ComponentTypeRef::Func(ty), - ); - } - let instance = self.pop_instance(); - let idx = self.outer.type_count(); - self.outer.ty().instance(&instance); - self.import_map.insert(interface, self.instances); - self.instances += 1; - Ok(idx) - } - - fn push_instance(&mut self) { - assert!(self.ty.is_none()); - assert!(self.saved_maps.is_none()); - self.saved_maps = Some(mem::take(&mut self.type_encoding_maps)); - self.ty = Some(InstanceType::default()); - } - - fn pop_instance(&mut self) -> InstanceType { - let maps = self.saved_maps.take().unwrap(); - self.type_encoding_maps = maps; - mem::take(&mut self.ty).unwrap() - } -} - -impl<'a> ValtypeEncoder<'a> for InterfaceEncoder<'a> { - fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) { - match &mut self.ty { - Some(ty) => (ty.type_count(), ty.ty().defined_type()), - None => (self.outer.type_count(), self.outer.ty().defined_type()), - } - } - fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) { - match &mut self.ty { - Some(ty) => (ty.type_count(), ty.ty().function()), - None => (self.outer.type_count(), self.outer.ty().function()), - } - } - fn export_type(&mut self, index: u32, name: ComponentExternName<'a>) -> Option { - match &mut self.ty { - Some(ty) => { - assert!(!self.import_types); - let ret = ty.type_count(); - ty.export(name, ComponentTypeRef::Type(TypeBounds::Eq(index))); - Some(ret) - } - None => { - let ret = self.outer.type_count(); - if self.import_types { - self.outer - .import(name, ComponentTypeRef::Type(TypeBounds::Eq(index))); - } else { - self.outer - .export(name, ComponentTypeRef::Type(TypeBounds::Eq(index))); - } - Some(ret) - } - } - } - fn export_resource(&mut self, name: ComponentExternName<'a>) -> u32 { - let type_ref = ComponentTypeRef::Type(TypeBounds::SubResource); - match &mut self.ty { - Some(ty) => { - assert!(!self.import_types); - ty.export(name, type_ref); - ty.type_count() - 1 - } - None => { - if self.import_types { - self.outer.import(name, type_ref); - } else { - self.outer.export(name, type_ref); - } - self.outer.type_count() - 1 - } - } - } - fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> { - &mut self.type_encoding_maps - } - fn interface(&self) -> Option { - self.interface - } - fn import_type(&mut self, owner: InterfaceId, id: TypeId) -> u32 { - let ty = &self.resolve.types[id]; - let instance = self.import_map[&owner]; - let outer_idx = *self.outer_type_map.entry(id).or_insert_with(|| { - let ret = self.outer.type_count(); - self.outer.alias(Alias::InstanceExport { - instance, - name: ty.name.as_ref().unwrap(), - kind: ComponentExportKind::Type, - }); - ret - }); - match &mut self.ty { - Some(ty) => { - let ret = ty.type_count(); - ty.alias(Alias::Outer { - count: 1, - index: outer_idx, - kind: ComponentOuterAliasKind::Type, - }); - ret - } - None => outer_idx, - } - } -} diff --git a/vendor/wit-component/src/encoding/world.rs b/vendor/wit-component/src/encoding/world.rs deleted file mode 100644 index c95cde01..00000000 --- a/vendor/wit-component/src/encoding/world.rs +++ /dev/null @@ -1,606 +0,0 @@ -use super::{Adapter, ComponentEncoder, LibraryInfo, RequiredOptions}; -use crate::validation::{ - Import, ImportMap, PayloadType, ValidatedModule, validate_adapter_module, validate_module, -}; -use anyhow::{Context, Result}; -use indexmap::{IndexMap, IndexSet}; -use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use wit_parser::{ - Function, InterfaceId, LiveTypes, Resolve, TypeDefKind, TypeId, TypeOwner, WorldId, WorldItem, - WorldKey, - abi::{AbiVariant, WasmSignature}, -}; - -pub struct WorldAdapter<'a> { - pub wasm: Cow<'a, [u8]>, - pub info: ValidatedModule, - pub library_info: Option<&'a LibraryInfo>, -} - -/// Metadata discovered from the state configured in a `ComponentEncoder`. -/// -/// This is stored separately from `EncodingState` to be stored as a borrow in -/// `EncodingState` as this information doesn't change throughout the encoding -/// process. -pub struct ComponentWorld<'a> { - /// Encoder configuration with modules, the document ,etc. - pub encoder: &'a ComponentEncoder, - /// Validation information of the input module, or `None` in `--types-only` - /// mode. - pub info: ValidatedModule, - /// Validation information about adapters populated only for required - /// adapters. Additionally stores the gc'd wasm for each adapter. - pub adapters: IndexMap<&'a str, WorldAdapter<'a>>, - /// Map of all imports and descriptions of what they're importing. - pub import_map: IndexMap, ImportedInterface>, - /// Set of all live types which must be exported either because they're - /// directly used or because they're transitively used. - pub live_type_imports: IndexMap>, - /// For each exported interface in the desired world this map lists - /// the set of interfaces that it depends on which are also exported. - /// - /// This set is used to determine when types are imported/used whether they - /// come from imports or exports. - pub exports_used: HashMap>, -} - -#[derive(Debug)] -pub struct ImportedInterface { - pub lowerings: IndexMap<(String, AbiVariant), Lowering>, - pub interface: Option, - pub implements: Option, - pub external_id: Option, -} - -#[derive(Debug)] -pub enum Lowering { - /// This import can be `canon lower`'d at the same time that the core module - /// importing it is instantiated. - Direct { - options: RequiredOptions, - }, - /// This import requires an indirection through the shim module's table as - /// the `options` required here can only be satisfied after the core module - /// in question has been instantiated (e.g. `realloc`). - Indirect { - sig: WasmSignature, - options: RequiredOptions, - }, - ResourceDrop(TypeId), -} - -impl<'a> ComponentWorld<'a> { - pub fn new(encoder: &'a ComponentEncoder) -> Result { - let info = validate_module(encoder, &encoder.module, encoder.module_import_map.as_ref()) - .context("module was not valid")?; - - let mut ret = ComponentWorld { - encoder, - info, - adapters: IndexMap::new(), - import_map: IndexMap::new(), - live_type_imports: Default::default(), - exports_used: HashMap::new(), - }; - - ret.process_adapters()?; - ret.process_imports()?; - ret.process_exports_used(); - ret.process_live_type_imports(); - - Ok(ret) - } - - /// Returns whether the component encoding process should use context slot 1 - /// in tasks, generally reserved for TLS. - /// - /// This is a heuristic which should go away once component-model-threading - /// has been stable for awhile and the return value of this function should - /// be const-propagated as `true`. - pub fn can_use_context_slot_1(&self) -> bool { - let uses = |info: &ValidatedModule| { - info.imports.imports().any(|(_, _, import)| match import { - Import::ThreadNewIndirect - | Import::ContextGet { slot: 1, .. } - | Import::ContextSet { slot: 1, .. } => true, - _ => false, - }) - }; - uses(&self.info) || self.adapters.values().any(|a| uses(&a.info)) - } - - /// Process adapters which are required here. Iterate over all - /// adapters and figure out what functions are required from the - /// adapter itself, either because the functions are imported by the - /// main module or they're part of the adapter's exports. - fn process_adapters(&mut self) -> Result<()> { - let resolve = &self.encoder.metadata.resolve; - let world = self.encoder.metadata.world; - for ( - name, - Adapter { - wasm, - metadata: _, - required_exports, - library_info, - }, - ) in self.encoder.adapters.iter() - { - let required_by_import = self.info.imports.required_from_adapter(name.as_str()); - let no_required_by_import = || required_by_import.is_empty(); - let no_required_exports = || { - required_exports - .iter() - .all(|name| match &resolve.worlds[world].exports[name] { - WorldItem::Function(_) => false, - WorldItem::Interface { id, .. } => { - resolve.interfaces[*id].functions.is_empty() - } - WorldItem::Type { .. } => true, - }) - }; - if no_required_by_import() && no_required_exports() && library_info.is_none() { - continue; - } - let wasm = if library_info.is_some() { - Cow::Borrowed(wasm as &[u8]) - } else { - // Without `library_info` this means that this is an adapter. - // The goal of the adapter is to provide a suite of symbols that - // can be imported, but not all symbols may be imported. Here - // the module is trimmed down to only what's needed by the - // original main module. - // - // The main module requires `required_by_import` above, but - // adapters may themselves also export WIT items. To handle this - // the sequence of operations here are: - // - // 1. First the adapter is validated as-is. This ensures that - // everything looks good before GC. - // 2. The metadata from step (1) is used to determine the set of - // WIT-level exports that are needed. This includes things - // like realloc functions and such. - // 3. The set of WIT-level functions from (2) is unioned with - // `required_by_import` to create the set of required exports - // of the adapter. - // 4. This set of exports is used to delete some exports of the - // adapter and then perform a GC pass. - // - // Finally at the end of all of this the - // `validate_adapter_module` method is called for a second time - // on the minimized adapter. This is done because deleting - // imports may have deleted some imports which means that the - // final component may not need to import as many interfaces. - let info = validate_adapter_module( - self.encoder, - &wasm, - &required_by_import, - required_exports, - library_info.as_ref(), - ) - .with_context(|| { - format!("failed to validate the imports of the adapter module `{name}`") - })?; - let mut required = IndexSet::new(); - for (name, _ty) in required_by_import.iter() { - required.insert(name.to_string()); - } - for (name, _export) in info.exports.iter() { - required.insert(name.to_string()); - } - - Cow::Owned( - crate::gc::run( - wasm, - &required, - if self.encoder.realloc_via_memory_grow { - None - } else { - self.info.exports.realloc_to_import_into_adapter() - }, - ) - .context("failed to reduce input adapter module to its minimal size")?, - ) - }; - let info = validate_adapter_module( - self.encoder, - &wasm, - &required_by_import, - required_exports, - library_info.as_ref(), - ) - .with_context(|| { - format!("failed to validate the imports of the minimized adapter module `{name}`") - })?; - self.adapters.insert( - name, - WorldAdapter { - info, - wasm, - library_info: library_info.as_ref(), - }, - ); - } - Ok(()) - } - - /// Fills out the `import_map` field of `self` by determining the live - /// functions from all imports. This additionally classifies imported - /// functions into direct or indirect lowerings for managing shims. - fn process_imports(&mut self) -> Result<()> { - let resolve = &self.encoder.metadata.resolve; - let world = self.encoder.metadata.world; - - // Inspect all imports of the main module and adapters to find all - // WIT-looking things and register those as required. This is used to - // prune out unneeded things in the `add_item` function below. - let mut required = Required::default(); - for (_, _, import) in self - .adapters - .values() - .flat_map(|a| a.info.imports.imports()) - .chain(self.info.imports.imports()) - { - match import { - Import::WorldFunc(_, name, abi) => { - required - .interface_funcs - .entry(None) - .or_default() - .insert((name, *abi)); - } - Import::InterfaceFunc(_, id, name, abi) => { - required - .interface_funcs - .entry(Some(*id)) - .or_default() - .insert((name, *abi)); - } - Import::ImportedResourceDrop(_, _, id) => { - required.resource_drops.insert(*id); - } - _ => {} - } - } - for (name, item) in resolve.worlds[world].imports.iter() { - add_item( - &mut self.import_map, - resolve, - name, - item, - &required, - &self.info, - )?; - } - return Ok(()); - - fn add_item( - import_map: &mut IndexMap, ImportedInterface>, - resolve: &Resolve, - key: &WorldKey, - item: &WorldItem, - required: &Required<'_>, - info: &ValidatedModule, - ) -> Result<()> { - let name = resolve.name_world_key(key); - log::trace!("register import `{name}`"); - let import_map_key = match item { - WorldItem::Function(_) | WorldItem::Type { .. } => None, - WorldItem::Interface { .. } => Some(name), - }; - let interface_id = match item { - WorldItem::Function(_) | WorldItem::Type { .. } => None, - WorldItem::Interface { id, .. } => Some(*id), - }; - let implements = resolve.implements_value(key, item); - // Note that `external_id` is only tracked for interface imports - // here. World-level functions and types all share the `None` entry - // in `import_map` but each item can have its own `external-id` - // which is emitted on a per-item basis instead. - let external_id = match item { - WorldItem::Function(_) | WorldItem::Type { .. } => None, - WorldItem::Interface { .. } => resolve.external_id_value(key, item), - }; - let interface = import_map - .entry(import_map_key) - .or_insert_with(|| ImportedInterface { - interface: interface_id, - lowerings: Default::default(), - implements: implements.clone(), - external_id: external_id.clone(), - }); - assert_eq!(interface.interface, interface_id); - assert_eq!(interface.implements, implements); - assert_eq!(interface.external_id, external_id); - match item { - WorldItem::Function(func) => { - interface.add_func(required, resolve, func, info); - } - WorldItem::Type { id, .. } => { - interface.add_type(required, resolve, *id); - } - WorldItem::Interface { id, .. } => { - for (_name, ty) in resolve.interfaces[*id].types.iter() { - interface.add_type(required, resolve, *ty); - } - for (_name, func) in resolve.interfaces[*id].functions.iter() { - interface.add_func(required, resolve, func, info); - } - } - } - Ok(()) - } - } - - /// Determines the set of live imported types which are required to satisfy - /// the imports and exports of the lifted core module. - fn process_live_type_imports(&mut self) { - let mut live = LiveTypes::default(); - let resolve = &self.encoder.metadata.resolve; - let world = self.encoder.metadata.world; - - // First use the previously calculated metadata about live imports to - // determine the set of live types in those imports. - self.add_live_imports(world, &self.info.imports, &mut live); - for (adapter_name, adapter) in self.adapters.iter() { - log::trace!("processing adapter `{adapter_name}`"); - self.add_live_imports(world, &adapter.info.imports, &mut live); - } - - // Next any imported types used by an export must also be considered - // live. This is a little tricky though because interfaces can be both - // imported and exported, so it's not as simple as registering the - // entire export's set of types and their transitive references - // (otherwise if you only export an interface it would consider those - // types imports live too). - // - // Here if the export is an interface the set of live types for that - // interface is calculated separately. The `exports_used` field - // previously calculated is then consulted to add any types owned by - // interfaces not in the `exports_used` set to the live imported types - // set. This means that only types not defined by referenced exports - // will get added here. - for (name, item) in resolve.worlds[world].exports.iter() { - log::trace!("add live world export `{}`", resolve.name_world_key(name)); - let id = match item { - WorldItem::Interface { id, .. } => id, - WorldItem::Function(_) | WorldItem::Type { .. } => { - live.add_world_item(resolve, item); - continue; - } - }; - - let exports_used = &self.exports_used[id]; - let mut live_from_export = LiveTypes::default(); - live_from_export.add_world_item(resolve, item); - for ty in live_from_export.iter() { - let owner = match resolve.types[ty].owner { - TypeOwner::Interface(id) => id, - _ => continue, - }; - if owner != *id && !exports_used.contains(&owner) { - live.add_type_id(resolve, ty); - } - } - } - - for live in live.iter() { - let owner = match resolve.types[live].owner { - TypeOwner::Interface(id) => id, - _ => continue, - }; - self.live_type_imports - .entry(owner) - .or_insert(Default::default()) - .insert(live); - } - } - - fn add_live_imports(&self, world: WorldId, imports: &ImportMap, live: &mut LiveTypes) { - let resolve = &self.encoder.metadata.resolve; - let world = &resolve.worlds[world]; - - // FIXME: ideally liveness information here would be plumbed through to - // encoding but that's not done at this time. Only liveness for each - // interface is plumbed so top-level world types are unconditionally - // encoded and therefore unconditionally live here. Once encoding is - // based on conditionally-live things then this should be removed. - for (_, item) in world.imports.iter() { - if let WorldItem::Type { id, .. } = item { - live.add_type_id(resolve, *id); - } - } - - for (_, _, import) in imports.imports() { - match import { - // WIT-level function imports need the associated WIT definition. - Import::WorldFunc(key, _, _) => { - live.add_world_item(resolve, &world.imports[key]); - } - Import::InterfaceFunc(_, id, name, _) => { - live.add_func(resolve, &resolve.interfaces[*id].functions[name]); - } - - // Resource-related intrinsics will need the resource. - Import::ImportedResourceDrop(.., ty) - | Import::ExportedResourceDrop(_, ty) - | Import::ExportedResourceNew(_, ty) - | Import::ExportedResourceRep(_, ty) => live.add_type_id(resolve, *ty), - - // Future/Stream related intrinsics need to refer to the type - // that the intrinsic is operating on. - Import::StreamNew(info) - | Import::StreamRead { info, async_: _ } - | Import::StreamWrite { info, async_: _ } - | Import::StreamCancelRead { info, async_: _ } - | Import::StreamCancelWrite { info, async_: _ } - | Import::StreamDropReadable(info) - | Import::StreamDropWritable(info) - | Import::FutureNew(info) - | Import::FutureRead { info, async_: _ } - | Import::FutureWrite { info, async_: _ } - | Import::FutureCancelRead { info, async_: _ } - | Import::FutureCancelWrite { info, async_: _ } - | Import::FutureDropReadable(info) - | Import::FutureDropWritable(info) => { - if let PayloadType::Type { id, .. } = info.ty { - live.add_type_id(resolve, id); - } - } - - // The `task.return` intrinsic needs to be able to refer to the - // type that is being returned. - Import::ExportedTaskReturn(.., func) => { - if let Some(ty) = func.result { - live.add_type(resolve, &ty); - } - } - - // Intrinsics that don't need to refer to WIT types can be - // skipped here. - Import::AdapterExport { .. } - | Import::MainModuleMemory(_) - | Import::MainModuleExport { .. } - | Import::Item(_) - | Import::ContextGet { .. } - | Import::ContextSet { .. } - | Import::TlsBaseGet { .. } - | Import::TlsBaseSet { .. } - | Import::BackpressureInc - | Import::BackpressureDec - | Import::WaitableSetNew - | Import::WaitableSetWait { .. } - | Import::WaitableSetPoll { .. } - | Import::WaitableSetDrop - | Import::WaitableJoin - | Import::SubtaskDrop - | Import::SubtaskCancel { .. } - | Import::ErrorContextNew { .. } - | Import::ErrorContextDebugMessage { .. } - | Import::ErrorContextDrop - | Import::ExportedTaskCancel - | Import::ThreadIndex - | Import::ThreadNewIndirect { .. } - | Import::ThreadResumeLater - | Import::ThreadSuspend { .. } - | Import::ThreadYield { .. } - | Import::ThreadSuspendThenResume { .. } - | Import::ThreadYieldThenResume { .. } - | Import::ThreadSuspendThenPromote { .. } - | Import::ThreadYieldThenPromote { .. } => {} - } - } - } - - fn process_exports_used(&mut self) { - let resolve = &self.encoder.metadata.resolve; - let world = self.encoder.metadata.world; - - let exports = &resolve.worlds[world].exports; - for (_key, item) in exports.iter() { - let id = match item { - WorldItem::Function(_) => continue, - WorldItem::Interface { id, .. } => *id, - WorldItem::Type { .. } => unreachable!(), - }; - let mut set = HashSet::new(); - - for other in resolve.interface_direct_deps(id) { - let key = WorldKey::Interface(other); - // If this dependency is not exported, then it'll show up - // through an import, so we're not interested in it. - if !exports.contains_key(&key) { - continue; - } - - // Otherwise this is a new exported dependency of ours, and - // additionally this interface inherits all the transitive - // dependencies too. - if set.insert(other) { - set.extend(self.exports_used[&other].iter().copied()); - } - } - let prev = self.exports_used.insert(id, set); - assert!(prev.is_none()); - } - } -} - -#[derive(Default)] -struct Required<'a> { - interface_funcs: IndexMap, IndexSet<(&'a str, AbiVariant)>>, - resource_drops: IndexSet, -} - -/// Returns whether `options` can all be satisfied without needing anything from -/// a core module that hasn't been instantiated yet. -fn options_are_available_before_instantiation( - options: RequiredOptions, - info: &ValidatedModule, -) -> bool { - // If neither memory nor realloc are needed, this can always be lowered - // eagerly. - if !options.contains(RequiredOptions::MEMORY) && !options.contains(RequiredOptions::REALLOC) { - return true; - } - - // Otherwise this depends on linear memory. If the main module imports - // linear memory then it's available before instantiating it, and in that - // situation we'll also generate shim functions for `realloc` so that's also - // available before instantiation. - // - // If linear memory isn't imported, but instead it's only exported, then we - // can't have it before we instantiate the main module. - info.imports.imported_memory().is_some() -} - -impl ImportedInterface { - fn add_func( - &mut self, - required: &Required<'_>, - resolve: &Resolve, - func: &Function, - info: &ValidatedModule, - ) { - let mut abis = Vec::with_capacity(2); - if let Some(set) = required.interface_funcs.get(&self.interface) { - if set.contains(&(func.name.as_str(), AbiVariant::GuestImport)) { - abis.push(AbiVariant::GuestImport); - } - if set.contains(&(func.name.as_str(), AbiVariant::GuestImportAsync)) { - abis.push(AbiVariant::GuestImportAsync); - } - } - for abi in abis { - log::trace!("add func {} {abi:?}", func.name); - let options = RequiredOptions::for_import(resolve, func, abi); - let lowering = if options_are_available_before_instantiation(options, info) { - Lowering::Direct { options } - } else { - let sig = resolve.wasm_signature(abi, func); - Lowering::Indirect { sig, options } - }; - - let prev = self.lowerings.insert((func.name.clone(), abi), lowering); - assert!(prev.is_none()); - } - } - - fn add_type(&mut self, required: &Required<'_>, resolve: &Resolve, id: TypeId) { - let ty = &resolve.types[id]; - match &ty.kind { - TypeDefKind::Resource => {} - _ => return, - } - let name = ty.name.as_deref().expect("resources must be named"); - - if required.resource_drops.contains(&id) { - let name = format!("{name}_drop"); - let prev = self - .lowerings - .insert((name, AbiVariant::GuestImport), Lowering::ResourceDrop(id)); - assert!(prev.is_none()); - } - } -} diff --git a/vendor/wit-component/src/gc.rs b/vendor/wit-component/src/gc.rs deleted file mode 100644 index 83306041..00000000 --- a/vendor/wit-component/src/gc.rs +++ /dev/null @@ -1,1134 +0,0 @@ -use self::bitvec::BitVec; -use anyhow::{Result, bail}; -use indexmap::{IndexMap, IndexSet}; -use std::{ - borrow::Cow, - collections::{HashMap, HashSet}, - convert::Infallible, - mem, - ops::Deref, -}; -use wasm_encoder::{Encode, EntityType, RawCustomSection, reencode::Reencode}; -use wasmparser::*; - -const PAGE_SIZE: i32 = 64 * 1024; - -/// This function will reduce the input core `wasm` module to only the set of -/// exports `required`. -/// -/// This internally performs a "gc" pass after removing exports to ensure that -/// the resulting module imports the minimal set of functions necessary. -pub fn run( - wasm: &[u8], - required: &IndexSet, - main_module_realloc: Option<&str>, -) -> Result> { - assert!(!required.is_empty()); - - let mut module = Module::default(); - module.parse(wasm)?; - - // Make sure that all required names are present in the module, and then - // remove all names that are not required. - for name in required { - if !module.exports.contains_key(name.as_str()) { - bail!("adapter module does not have export `{name}`") - } - } - let mut not_required = IndexSet::new(); - for name in module.exports.keys().copied() { - if !required.contains(name) { - not_required.insert(name); - } - } - for name in not_required { - module.exports.swap_remove(name); - } - assert!(!module.exports.is_empty()); - module.liveness()?; - module.encode(main_module_realloc) -} - -/// This function generates a Wasm function body which implements `cabi_realloc` in terms of `memory.grow`. It -/// only accepts new, page-sized allocations. -fn realloc_via_memory_grow() -> wasm_encoder::Function { - let mut func = wasm_encoder::Function::new([(1, wasm_encoder::ValType::I32)]); - - // Assert `old_ptr` is null. - func.instructions().i32_const(0); - func.instructions().local_get(0); - func.instructions().i32_ne(); - func.instructions().if_(wasm_encoder::BlockType::Empty); - func.instructions().unreachable(); - func.instructions().end(); - - // Assert `old_len` is zero. - func.instructions().i32_const(0); - func.instructions().local_get(1); - func.instructions().i32_ne(); - func.instructions().if_(wasm_encoder::BlockType::Empty); - func.instructions().unreachable(); - func.instructions().end(); - - // Assert `new_len` is equal to the page size (which is the only value we currently support) - // Note: we could easily support arbitrary multiples of PAGE_SIZE here if the need arises. - func.instructions().i32_const(PAGE_SIZE); - func.instructions().local_get(3); - func.instructions().i32_ne(); - func.instructions().if_(wasm_encoder::BlockType::Empty); - func.instructions().unreachable(); - func.instructions().end(); - - // Grow the memory by 1 page. - func.instructions().i32_const(1); - func.instructions().memory_grow(0); - func.instructions().local_tee(4); - - // Test if the return value of the growth was -1 and, if so, trap due to a failed allocation. - func.instructions().i32_const(-1); - func.instructions().i32_eq(); - func.instructions().if_(wasm_encoder::BlockType::Empty); - func.instructions().unreachable(); - func.instructions().end(); - - func.instructions().local_get(4); - func.instructions().i32_const(16); - func.instructions().i32_shl(); - func.instructions().end(); - - func -} - -#[repr(i32)] -#[non_exhaustive] -enum StackAllocationState { - Unallocated, - Allocating, - Allocated, -} - -fn allocate_stack_via_realloc( - realloc_index: u32, - sp: u32, - allocation_state: Option, -) -> wasm_encoder::Function { - let mut func = wasm_encoder::Function::new([]); - - if let Some(allocation_state) = allocation_state { - // This means we're lazily allocating the stack, keeping track of state via `$allocation_state` - func.instructions().global_get(allocation_state); - func.instructions() - .i32_const(StackAllocationState::Unallocated as _); - func.instructions().i32_eq(); - func.instructions().if_(wasm_encoder::BlockType::Empty); - func.instructions() - .i32_const(StackAllocationState::Allocating as _); - func.instructions().global_set(allocation_state); - // We could also set `sp` to zero here to ensure the yet-to-be-allocated stack is empty. However, we - // assume it defaults to zero anyway, in which case setting it would be redundant. - } - - func.instructions().i32_const(0); - func.instructions().i32_const(0); - func.instructions().i32_const(8); - func.instructions().i32_const(PAGE_SIZE); - func.instructions().call(realloc_index); - func.instructions().i32_const(PAGE_SIZE); - func.instructions().i32_add(); - func.instructions().global_set(sp); - - if let Some(allocation_state) = allocation_state { - func.instructions() - .i32_const(StackAllocationState::Allocated as _); - func.instructions().global_set(allocation_state); - func.instructions().end(); - } - - func.instructions().end(); - - func -} - -// Represents a function called while processing a module work list. -type WorklistFunc<'a> = fn(&mut Module<'a>, u32) -> Result<()>; - -// Representation of a wasm module which is used to GC a module to its minimal -// set of required items necessary to implement the `exports` -// -// Note that this is not a complete representation of a wasm module since it -// doesn't represent everything such as data and element segments. This is only -// used for adapter modules which otherwise have these restrictions and makes -// this gc pass a bit easier to write. -#[derive(Default)] -struct Module<'a> { - // Definitions found when parsing a module - types: Vec, - tables: Vec>, - globals: Vec>, - memories: Vec>, - funcs: Vec>, - exports: IndexMap<&'a str, Export<'a>>, - func_names: HashMap, - global_names: HashMap, - producers: Option, - - // Known-live sets of indices after the `liveness` pass has run. - live_types: BitVec, - live_tables: BitVec, - live_globals: BitVec, - live_memories: BitVec, - live_funcs: BitVec, - - // Helper data structure used during the `liveness` path to avoid recursion. - // When calculating the liveness of an item this `worklist` is pushed to and - // then processed until it's empty. An item pushed onto this list represents - // a new index that has been discovered to be live and the function is what - // walks the item's definition to find other items that it references. - worklist: Vec<(u32, WorklistFunc<'a>)>, -} - -struct Table<'a> { - def: Definition<'a, ()>, - ty: TableType, -} - -struct Memory<'a> { - def: Definition<'a, ()>, - ty: MemoryType, -} - -struct Global<'a> { - def: Definition<'a, ConstExpr<'a>>, - ty: GlobalType, -} - -#[derive(Clone)] -struct Func<'a> { - def: Definition<'a, FunctionBody<'a>>, - ty: u32, -} - -#[derive(Clone)] -enum Definition<'a, T> { - Import(&'a str, &'a str), - Local(T), -} - -impl<'a> Module<'a> { - fn parse(&mut self, wasm: &'a [u8]) -> Result<()> { - let mut next_code_index = 0; - let mut validator = Validator::new(); - for payload in Parser::new(0).parse_all(wasm) { - let payload = payload?; - validator.payload(&payload)?; - match payload { - Payload::Version { encoding, .. } => { - if encoding != Encoding::Module { - bail!("adapter must be a core wasm module, not a component"); - } - } - Payload::End(_) => {} - Payload::TypeSection(s) => { - for ty in s.into_iter_err_on_gc_types() { - self.types.push(ty?); - } - } - Payload::ImportSection(s) => { - for i in s.into_imports() { - let i = i?; - match i.ty { - TypeRef::Func(ty) => self.funcs.push(Func { - def: Definition::Import(i.module, i.name), - ty, - }), - TypeRef::Table(ty) => self.tables.push(Table { - def: Definition::Import(i.module, i.name), - ty, - }), - TypeRef::Global(ty) => self.globals.push(Global { - def: Definition::Import(i.module, i.name), - ty, - }), - TypeRef::Memory(ty) => self.memories.push(Memory { - def: Definition::Import(i.module, i.name), - ty, - }), - TypeRef::Tag(_) => bail!("unsupported `tag` type"), - TypeRef::FuncExact(_) => { - bail!("unsupported `func_exact` type") - } - } - } - } - Payload::TableSection(s) => { - for table in s { - let table = table?; - self.tables.push(Table { - def: Definition::Local(()), - ty: table.ty, - }); - } - } - Payload::MemorySection(s) => { - for ty in s { - let ty = ty?; - self.memories.push(Memory { - def: Definition::Local(()), - ty, - }); - } - } - Payload::GlobalSection(s) => { - for g in s { - let g = g?; - self.globals.push(Global { - def: Definition::Local(g.init_expr), - ty: g.ty, - }); - } - } - - Payload::ExportSection(s) => { - for e in s { - let e = e?; - self.exports.insert(e.name, e); - } - } - - Payload::FunctionSection(s) => { - next_code_index = self.funcs.len(); - for ty in s { - let ty = ty?; - self.funcs.push(Func { - // Specify a dummy definition to get filled in later - // when parsing the code section. - def: Definition::Local(FunctionBody::new(BinaryReader::new(&[], 0))), - ty, - }); - } - } - - Payload::CodeSectionStart { .. } => {} - Payload::CodeSectionEntry(body) => { - self.funcs[next_code_index].def = Definition::Local(body); - next_code_index += 1; - } - - // Ignore all custom sections except for the `name` and - // `producers` sections which we parse, but ignore errors within. - Payload::CustomSection(s) => match s.as_known() { - KnownCustom::Name(s) => drop(self.parse_name_section(s)), - KnownCustom::Producers(_) => drop(self.parse_producers_section(&s)), - _ => {} - }, - - // sections that shouldn't appear in the specially-crafted core - // wasm adapter self we're processing - other => match other.as_section() { - Some((id, _)) => bail!("unsupported section `{id}` in adapter"), - None => bail!("unsupported payload in adapter"), - }, - } - } - - Ok(()) - } - - fn parse_name_section(&mut self, section: NameSectionReader<'a>) -> Result<()> { - for s in section { - match s? { - Name::Function(map) => { - for naming in map { - let naming = naming?; - self.func_names.insert(naming.index, naming.name); - } - } - Name::Global(map) => { - for naming in map { - let naming = naming?; - self.global_names.insert(naming.index, naming.name); - } - } - _ => {} - } - } - Ok(()) - } - - fn parse_producers_section(&mut self, section: &CustomSectionReader<'a>) -> Result<()> { - let producers = - wasm_metadata::Producers::from_bytes(section.data(), section.data_offset())?; - self.producers = Some(producers); - Ok(()) - } - - /// Iteratively calculates the set of live items within this module - /// considering all exports as the root of live functions. - fn liveness(&mut self) -> Result<()> { - let exports = mem::take(&mut self.exports); - for (_, e) in exports.iter() { - match e.kind { - ExternalKind::Func | ExternalKind::FuncExact => self.func(e.index), - ExternalKind::Global => self.global(e.index), - ExternalKind::Table => self.table(e.index), - ExternalKind::Memory => self.memory(e.index), - ExternalKind::Tag => bail!("unsupported exported tag"), - } - } - self.exports = exports; - - while let Some((idx, func)) = self.worklist.pop() { - func(self, idx)?; - } - Ok(()) - } - - fn func(&mut self, func: u32) { - if !self.live_funcs.insert(func) { - return; - } - self.worklist.push((func, |me, func| { - let func = me.funcs[func as usize].clone(); - me.ty(func.ty); - let mut body = match &func.def { - Definition::Import(..) => return Ok(()), - Definition::Local(e) => e.get_binary_reader(), - }; - let local_count = body.read_var_u32()?; - for _ in 0..local_count { - body.read_var_u32()?; - body.read::()?; - } - me.operators(body) - })); - } - - fn global(&mut self, global: u32) { - if !self.live_globals.insert(global) { - return; - } - self.worklist.push((global, |me, global| { - let init = match &me.globals[global as usize].def { - Definition::Import(..) => return Ok(()), - Definition::Local(e) => e, - }; - me.operators(init.get_binary_reader()) - })); - } - - fn table(&mut self, table: u32) { - if !self.live_tables.insert(table) { - return; - } - self.worklist.push((table, |me, table| { - let ty = me.tables[table as usize].ty.element_type; - me.valty(ty.into()); - Ok(()) - })); - } - - fn memory(&mut self, memory: u32) { - self.live_memories.insert(memory); - } - - fn blockty(&mut self, ty: BlockType) { - if let BlockType::FuncType(ty) = ty { - self.ty(ty); - } - } - - fn valty(&mut self, ty: ValType) { - match ty { - ValType::Ref(r) => self.refty(r), - ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 | ValType::V128 => {} - } - } - - fn valtys(&mut self, tys: &[ValType]) { - for i in tys { - self.valty(*i); - } - } - - fn refty(&mut self, ty: RefType) { - self.heapty(ty.heap_type()) - } - - fn heapty(&mut self, ty: HeapType) { - match ty { - HeapType::Abstract { .. } => {} - HeapType::Concrete(i) | HeapType::Exact(i) => self.ty(i.as_module_index().unwrap()), - } - } - - fn ty(&mut self, ty: u32) { - if !self.live_types.insert(ty) { - return; - } - self.worklist.push((ty, |me, ty| { - let ty = me.types[ty as usize].clone(); - for param in ty.params().iter().chain(ty.results()) { - me.valty(*param); - } - Ok(()) - })); - } - - fn operators(&mut self, reader: BinaryReader<'a>) -> Result<()> { - let mut ops = OperatorsReader::new(reader); - while !ops.eof() { - ops.visit_operator(self)?; - } - ops.finish()?; - Ok(()) - } - - fn live_types(&self) -> impl Iterator + '_ { - live_iter(&self.live_types, self.types.iter()) - } - - fn live_funcs(&self) -> impl Iterator)> + '_ { - live_iter(&self.live_funcs, self.funcs.iter()) - } - - fn live_memories(&self) -> impl Iterator)> + '_ { - live_iter(&self.live_memories, self.memories.iter()) - } - - fn live_globals(&self) -> impl Iterator)> + '_ { - live_iter(&self.live_globals, self.globals.iter()) - } - - fn live_tables(&self) -> impl Iterator)> + '_ { - live_iter(&self.live_tables, self.tables.iter()) - } - - /// Encodes this `Module` to a new wasm module which is gc'd and only - /// contains the items that are live as calculated by the `liveness` pass. - fn encode(&mut self, main_module_realloc: Option<&str>) -> Result> { - // Data structure used to track the mapping of old index to new index - // for all live items. - let mut map = Encoder::default(); - - // Sections that will be assembled into the final module at the end of - // this function. - let mut types = wasm_encoder::TypeSection::new(); - let mut imports = wasm_encoder::ImportSection::new(); - let mut funcs = wasm_encoder::FunctionSection::new(); - let mut tables = wasm_encoder::TableSection::new(); - let mut memories = wasm_encoder::MemorySection::new(); - let mut globals = wasm_encoder::GlobalSection::new(); - let mut code = wasm_encoder::CodeSection::new(); - - let mut empty_type = None; - for (i, ty) in self.live_types() { - map.types.push(i); - - let ty = map.func_type(ty.clone())?; - types.ty().func_type(&ty); - - // Keep track of the "empty type" to see if we can reuse an - // existing one or one needs to be injected if a `start` - // function is calculated at the end. - if ty.params().is_empty() && ty.results().is_empty() { - empty_type = Some(map.types.remap(i)); - } - } - - let mut num_memories = 0; - for (i, mem) in self.live_memories() { - map.memories.push(i); - let ty = map.memory_type(mem.ty); - match &mem.def { - Definition::Import(m, n) => { - imports.import(m, n, ty?); - } - Definition::Local(()) => { - memories.memory(ty?); - } - } - num_memories += 1; - } - - for (i, table) in self.live_tables() { - map.tables.push(i); - let ty = map.table_type(table.ty)?; - match &table.def { - Definition::Import(m, n) => { - imports.import(m, n, ty); - } - Definition::Local(()) => { - tables.table(ty); - } - } - } - - for (i, global) in self.live_globals() { - map.globals.push(i); - let ty = map.global_type(global.ty)?; - match &global.def { - Definition::Import(m, n) => { - imports.import(m, n, ty); - } - Definition::Local(init) => { - let init = &map.const_expr(init.clone())?; - globals.global(ty, &init); - } - } - } - - let mut realloc_index = None; - let mut num_func_imports = 0; - - // For functions first assign a new index to all functions and then - // afterwards actually map the body of all functions so the `map` of all - // index mappings is fully populated before instructions are mapped. - - let is_realloc = - |m, n| m == "__main_module__" && matches!(n, "canonical_abi_realloc" | "cabi_realloc"); - - let (imported, local) = - self.live_funcs() - .partition::, _>(|(_, func)| match &func.def { - Definition::Import(m, n) => { - !is_realloc(*m, *n) || main_module_realloc.is_some() - } - Definition::Local(_) => false, - }); - - for (i, func) in imported { - map.funcs.push(i); - let ty = map.types.remap(func.ty); - match &func.def { - Definition::Import(m, n) => { - let name = if is_realloc(*m, *n) { - // The adapter is importing `cabi_realloc` from the main module, and the main module - // exports that function, but possibly using a different name - // (e.g. `canonical_abi_realloc`). Update the name to match if necessary. - realloc_index = Some(num_func_imports); - main_module_realloc.unwrap_or(n) - } else { - n - }; - imports.import(m, name, EntityType::Function(ty)); - num_func_imports += 1; - } - Definition::Local(_) => unreachable!(), - } - } - - let add_realloc_type = |types: &mut wasm_encoder::TypeSection| { - let type_index = types.len(); - types.ty().function( - [ - wasm_encoder::ValType::I32, - wasm_encoder::ValType::I32, - wasm_encoder::ValType::I32, - wasm_encoder::ValType::I32, - ], - [wasm_encoder::ValType::I32], - ); - type_index - }; - - let add_empty_type = |types: &mut wasm_encoder::TypeSection| { - let type_index = types.len(); - types.ty().function([], []); - type_index - }; - - let sp = self.find_mut_i32_global("__stack_pointer")?; - let allocation_state = self.find_mut_i32_global("allocation_state")?; - - let mut func_names = Vec::new(); - - if let (Some(realloc), Some(_), None) = (main_module_realloc, sp, realloc_index) { - // The main module exports a realloc function, and although the adapter doesn't import it, we're going - // to add a function which calls it to allocate some stack space, so let's add an import now. - - // Tell the function remapper we're reserving a slot for our extra import: - map.funcs.next += 1; - - realloc_index = Some(num_func_imports); - imports.import( - "__main_module__", - realloc, - EntityType::Function(add_realloc_type(&mut types)), - ); - func_names.push((num_func_imports, realloc)); - num_func_imports += 1; - } - - for (i, func) in local { - map.funcs.push(i); - let ty = map.types.remap(func.ty); - match &func.def { - Definition::Import(_, _) => { - // The adapter is importing `cabi_realloc` from the main module, but the main module isn't - // exporting it. In this case, we need to define a local function it can call instead. - realloc_index = Some(num_func_imports + funcs.len()); - funcs.function(ty); - code.function(&realloc_via_memory_grow()); - } - Definition::Local(_) => { - funcs.function(ty); - } - } - } - - let lazy_stack_init_index = - if sp.is_some() && allocation_state.is_some() && main_module_realloc.is_some() { - // We have a stack pointer, a `cabi_realloc` function from the main module, and a global variable for - // keeping track of (and short-circuiting) reentrance. That means we can (and should) do lazy stack - // allocation. - let index = num_func_imports + funcs.len(); - - // Tell the function remapper we're reserving a slot for our extra function: - map.funcs.next += 1; - - funcs.function(add_empty_type(&mut types)); - - Some(index) - } else { - None - }; - - let exported_funcs = self - .exports - .values() - .filter_map(|export| match export.kind { - ExternalKind::Func => Some(export.index), - _ => None, - }) - .collect::>(); - - for (i, func) in self.live_funcs() { - let body = match &func.def { - Definition::Import(..) => continue, - Definition::Local(body) => body, - }; - - match (lazy_stack_init_index, exported_funcs.contains(&i)) { - // Prepend an `allocate_stack` call to all exports if we're - // lazily allocating the stack. - (Some(lazy_stack_init_index), true) => { - let mut func = map.new_function_with_parsed_locals(&body)?; - func.instructions().call(lazy_stack_init_index); - let mut reader = body.get_operators_reader()?; - while !reader.eof() { - func.instruction(&map.parse_instruction(&mut reader)?); - } - code.function(&func); - } - _ => { - map.parse_function_body(&mut code, body.clone())?; - } - } - } - - if lazy_stack_init_index.is_some() { - code.function(&allocate_stack_via_realloc( - realloc_index.unwrap(), - sp.unwrap(), - allocation_state, - )); - } - - if sp.is_some() && (realloc_index.is_none() || allocation_state.is_none()) { - // Either the main module does _not_ export a realloc function, or it is not safe to use for stack - // allocation because we have no way to short-circuit reentrance, so we'll use `memory.grow` instead. - realloc_index = Some(num_func_imports + funcs.len()); - funcs.function(add_realloc_type(&mut types)); - code.function(&realloc_via_memory_grow()); - } - - // Inject a start function to initialize the stack pointer which will be local to this module. This only - // happens if a memory is preserved, a stack pointer global is found, and we're not doing lazy stack - // allocation. - let mut start = None; - if let (Some(sp), None) = (sp, lazy_stack_init_index) { - if num_memories > 0 { - // If there are any memories or any mutable globals there must be - // precisely one of each as otherwise we don't know how to filter - // down to the right one. - if num_memories != 1 { - bail!("adapter modules don't support multi-memory"); - } - - let sp = map.globals.remap(sp); - - let function_index = num_func_imports + funcs.len(); - - // Generate a function type for this start function, adding a new - // function type to the module if necessary. - let empty_type = empty_type.unwrap_or_else(|| { - types.ty().function([], []); - types.len() - 1 - }); - funcs.function(empty_type); - func_names.push((function_index, "allocate_stack")); - code.function(&allocate_stack_via_realloc( - realloc_index.unwrap(), - sp, - allocation_state, - )); - - start = Some(wasm_encoder::StartSection { function_index }); - } - } - - // Sanity-check the shape of the module since some parts won't work if - // this fails. Note that during parsing we've already validated there - // are no data segments or element segments. - - // Shouldn't have any tables if there are no element segments since - // otherwise there's no meaning to a defined or imported table. - if self.live_tables().count() != 0 { - bail!("tables should not be present in the final adapter module"); - } - - // multi-memory should not be enabled and if any memory it should be - // imported. - if self.live_memories().count() > 1 { - bail!("the adapter module should not use multi-memory"); - } - if !memories.is_empty() { - bail!("locally-defined memories are not allowed define a local memory"); - } - - let mut ret = wasm_encoder::Module::default(); - if !types.is_empty() { - ret.section(&types); - } - if !imports.is_empty() { - ret.section(&imports); - } - if !funcs.is_empty() { - ret.section(&funcs); - } - if !tables.is_empty() { - ret.section(&tables); - } - if !memories.is_empty() { - ret.section(&memories); - } - if !globals.is_empty() { - ret.section(&globals); - } - - if !self.exports.is_empty() { - let mut exports = wasm_encoder::ExportSection::new(); - for (_, export) in self.exports.iter() { - let (kind, index) = match export.kind { - ExternalKind::Func => ( - wasm_encoder::ExportKind::Func, - map.funcs.remap(export.index), - ), - ExternalKind::Table => ( - wasm_encoder::ExportKind::Table, - map.tables.remap(export.index), - ), - ExternalKind::Memory => ( - wasm_encoder::ExportKind::Memory, - map.memories.remap(export.index), - ), - ExternalKind::Global => ( - wasm_encoder::ExportKind::Global, - map.globals.remap(export.index), - ), - kind => bail!("unsupported export kind {kind:?}"), - }; - exports.export(export.name, kind, index); - } - ret.section(&exports); - } - - if let Some(start) = &start { - ret.section(start); - } - - if !code.is_empty() { - ret.section(&code); - } - - // Append a custom `name` section using the names of the functions that - // were found prior to the GC pass in the original module. - let mut global_names = Vec::new(); - for (i, _func) in self.live_funcs() { - let name = match self.func_names.get(&i) { - Some(name) => name, - None => continue, - }; - func_names.push((map.funcs.remap(i), *name)); - } - for (i, _global) in self.live_globals() { - let name = match self.global_names.get(&i) { - Some(name) => name, - None => continue, - }; - global_names.push((map.globals.remap(i), *name)); - } - let mut section = Vec::new(); - let mut encode_subsection = |code: u8, names: &[(u32, &str)]| { - if names.is_empty() { - return; - } - let mut subsection = Vec::new(); - names.len().encode(&mut subsection); - for (i, name) in names { - i.encode(&mut subsection); - name.encode(&mut subsection); - } - section.push(code); - subsection.encode(&mut section); - }; - if let (Some(realloc_index), true) = ( - realloc_index, - main_module_realloc.is_none() || allocation_state.is_none(), - ) { - func_names.push((realloc_index, "realloc_via_memory_grow")); - } - if let Some(lazy_stack_init_index) = lazy_stack_init_index { - func_names.push((lazy_stack_init_index, "allocate_stack")); - } - encode_subsection(0x01, &func_names); - encode_subsection(0x07, &global_names); - if !section.is_empty() { - ret.section(&wasm_encoder::CustomSection { - name: "name".into(), - data: Cow::Borrowed(§ion), - }); - } - if let Some(producers) = &self.producers { - ret.section(&RawCustomSection(&producers.raw_custom_section())); - } - - Ok(ret.finish()) - } - - fn find_mut_i32_global(&self, name: &str) -> Result> { - let matches = &self - .live_globals() - .filter_map(|(i, g)| { - if g.ty.mutable - && g.ty.content_type == ValType::I32 - && *self.global_names.get(&i)? == name - { - Some(i) - } else { - None - } - }) - .collect::>(); - - match matches.deref() { - [] => Ok(None), - [i] => Ok(Some(*i)), - _ => bail!( - "found {} mutable i32 globals with name {name}", - matches.len() - ), - } - } -} - -// This helper macro is used to define a visitor of all instructions with -// special handling for all payloads of instructions to mark any referenced -// items live. -// -// Currently item identification happens through the field name of the payload. -// While not exactly the most robust solution this should work well enough for -// now. -macro_rules! define_visit { - ($(@$p:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => { - $( - #[allow(unused_variables)] - fn $visit(&mut self $(, $($arg: $argty),*)?) { - $( - $( - define_visit!(mark_live self $arg $arg); - )* - )? - } - )* - }; - - (mark_live $self:ident $arg:ident type_index) => {$self.ty($arg);}; - (mark_live $self:ident $arg:ident array_type_index) => {$self.ty($arg);}; - (mark_live $self:ident $arg:ident array_type_index_dst) => {$self.ty($arg);}; - (mark_live $self:ident $arg:ident array_type_index_src) => {$self.ty($arg);}; - (mark_live $self:ident $arg:ident struct_type_index) => {$self.ty($arg);}; - (mark_live $self:ident $arg:ident src_table) => {$self.table($arg);}; - (mark_live $self:ident $arg:ident dst_table) => {$self.table($arg);}; - (mark_live $self:ident $arg:ident table_index) => {$self.table($arg);}; - (mark_live $self:ident $arg:ident table) => {$self.table($arg);}; - (mark_live $self:ident $arg:ident global_index) => {$self.global($arg);}; - (mark_live $self:ident $arg:ident function_index) => {$self.func($arg);}; - (mark_live $self:ident $arg:ident mem) => {$self.memory($arg);}; - (mark_live $self:ident $arg:ident src_mem) => {$self.memory($arg);}; - (mark_live $self:ident $arg:ident dst_mem) => {$self.memory($arg);}; - (mark_live $self:ident $arg:ident memarg) => {$self.memory($arg.memory);}; - (mark_live $self:ident $arg:ident blockty) => {$self.blockty($arg);}; - (mark_live $self:ident $arg:ident ty) => {$self.valty($arg)}; - (mark_live $self:ident $arg:ident tys) => {$self.valtys(&$arg)}; - (mark_live $self:ident $arg:ident hty) => {$self.heapty($arg)}; - (mark_live $self:ident $arg:ident from_ref_type) => {$self.refty($arg);}; - (mark_live $self:ident $arg:ident to_ref_type) => {$self.refty($arg);}; - (mark_live $self:ident $arg:ident lane) => {}; - (mark_live $self:ident $arg:ident lanes) => {}; - (mark_live $self:ident $arg:ident value) => {}; - (mark_live $self:ident $arg:ident local_index) => {}; - (mark_live $self:ident $arg:ident relative_depth) => {}; - (mark_live $self:ident $arg:ident tag_index) => {}; - (mark_live $self:ident $arg:ident targets) => {}; - (mark_live $self:ident $arg:ident data_index) => {}; - (mark_live $self:ident $arg:ident array_data_index) => {}; - (mark_live $self:ident $arg:ident elem_index) => {}; - (mark_live $self:ident $arg:ident array_elem_index) => {}; - (mark_live $self:ident $arg:ident array_size) => {}; - (mark_live $self:ident $arg:ident field_index) => {}; - (mark_live $self:ident $arg:ident ordering) => {}; - (mark_live $self:ident $arg:ident try_table) => {unimplemented!();}; - (mark_live $self:ident $arg:ident argument_index) => {}; - (mark_live $self:ident $arg:ident result_index) => {}; - (mark_live $self:ident $arg:ident cont_type_index) => {}; - (mark_live $self:ident $arg:ident resume_table) => {unimplemented!();}; -} - -impl<'a> VisitOperator<'a> for Module<'a> { - type Output = (); - - fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { - Some(self) - } - - wasmparser::for_each_visit_operator!(define_visit); -} - -impl<'a> VisitSimdOperator<'a> for Module<'a> { - wasmparser::for_each_visit_simd_operator!(define_visit); -} - -/// Helper function to filter `iter` based on the `live` set, yielding an -/// iterator over the index of the item that's live as well as the item itself. -fn live_iter<'a, T>( - live: &'a BitVec, - iter: impl Iterator + 'a, -) -> impl Iterator + 'a { - iter.enumerate().filter_map(|(i, t)| { - let i = i as u32; - if live.contains(i) { Some((i, t)) } else { None } - }) -} - -#[derive(Default)] -struct Encoder { - types: Remap, - funcs: Remap, - memories: Remap, - globals: Remap, - tables: Remap, -} - -type ReencodeResult = Result>; - -impl Reencode for Encoder { - type Error = Infallible; - - fn type_index(&mut self, i: u32) -> ReencodeResult { - Ok(self.types.remap(i)) - } - fn function_index(&mut self, i: u32) -> ReencodeResult { - Ok(self.funcs.remap(i)) - } - fn memory_index(&mut self, i: u32) -> ReencodeResult { - Ok(self.memories.remap(i)) - } - fn global_index(&mut self, i: u32) -> ReencodeResult { - Ok(self.globals.remap(i)) - } - fn table_index(&mut self, i: u32) -> ReencodeResult { - Ok(self.tables.remap(i)) - } -} - -// Minimal definition of a bit vector necessary for the liveness calculations -// above. -mod bitvec { - use std::mem; - - type T = u64; - - #[derive(Default)] - pub struct BitVec { - bits: Vec, - } - - impl BitVec { - /// Inserts `idx` into this bit vector, returning whether it was not - /// previously present. - pub fn insert(&mut self, idx: u32) -> bool { - let (idx, bit) = idx_bit(idx); - match self.bits.get_mut(idx) { - Some(bits) => { - if *bits & bit != 0 { - return false; - } - *bits |= bit; - } - None => { - self.bits.resize(idx + 1, 0); - self.bits[idx] = bit; - } - } - true - } - - /// Returns whether this bit vector contains the specified `idx`th bit. - pub fn contains(&self, idx: u32) -> bool { - let (idx, bit) = idx_bit(idx); - match self.bits.get(idx) { - Some(bits) => (*bits & bit) != 0, - None => false, - } - } - } - - fn idx_bit(idx: u32) -> (usize, T) { - let idx = idx as usize; - let size = mem::size_of::() * 8; - let index = idx / size; - let bit = 1 << (idx % size); - (index, bit) - } -} - -/// Small data structure used to track index mappings from an old index space to -/// a new. -#[derive(Default)] -struct Remap { - /// Map, indexed by the old index set, to the new index set. - map: HashMap, - /// The next available index in the new index space. - next: u32, -} - -impl Remap { - /// Appends a new live "old index" into this remapping structure. - /// - /// This will assign a new index for the old index provided. - fn push(&mut self, old: u32) { - self.map.insert(old, self.next); - self.next += 1; - } - - /// Returns the new index corresponding to an old index. - /// - /// Panics if the `old` index was not added via `push` above. - fn remap(&self, old: u32) -> u32 { - *self - .map - .get(&old) - .unwrap_or_else(|| panic!("can't map {old} to a new index")) - } -} diff --git a/vendor/wit-component/src/lib.rs b/vendor/wit-component/src/lib.rs deleted file mode 100644 index 11f57201..00000000 --- a/vendor/wit-component/src/lib.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! The WebAssembly component tooling. - -#![deny(missing_docs)] -#![cfg_attr(docsrs, feature(doc_cfg))] - -use std::str::FromStr; -use std::{borrow::Cow, fmt::Display}; - -use anyhow::{Result, bail}; -use wasm_encoder::{CanonicalOption, Encode, Section}; -use wit_parser::{Resolve, WorldId}; - -mod encoding; -mod gc; -mod linking; -mod printing; -mod targets; -mod validation; - -pub use encoding::{ComponentEncoder, LibraryInfo, encode}; -pub use linking::Linker; -pub use printing::*; -pub use targets::*; -pub use validation::AdapterModuleDidNotExport; -pub use wit_parser::decoding::{DecodedWasm, decode, decode_reader}; - -pub mod metadata; - -#[cfg(feature = "dummy-module")] -pub use dummy::dummy_module; -#[cfg(feature = "dummy-module")] -mod dummy; - -#[cfg(feature = "semver-check")] -mod semver_check; -#[cfg(feature = "semver-check")] -pub use semver_check::*; - -/// Supported string encoding formats. -#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub enum StringEncoding { - /// Strings are encoded with UTF-8. - #[default] - UTF8, - /// Strings are encoded with UTF-16. - UTF16, - /// Strings are encoded with compact UTF-16 (i.e. Latin1+UTF-16). - CompactUTF16, -} - -impl Display for StringEncoding { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - StringEncoding::UTF8 => write!(f, "utf8"), - StringEncoding::UTF16 => write!(f, "utf16"), - StringEncoding::CompactUTF16 => write!(f, "compact-utf16"), - } - } -} - -impl FromStr for StringEncoding { - type Err = anyhow::Error; - - fn from_str(s: &str) -> Result { - match s { - "utf8" => Ok(StringEncoding::UTF8), - "utf16" => Ok(StringEncoding::UTF16), - "compact-utf16" => Ok(StringEncoding::CompactUTF16), - _ => bail!("unknown string encoding `{s}`"), - } - } -} - -impl From for wasm_encoder::CanonicalOption { - fn from(e: StringEncoding) -> wasm_encoder::CanonicalOption { - match e { - StringEncoding::UTF8 => CanonicalOption::UTF8, - StringEncoding::UTF16 => CanonicalOption::UTF16, - StringEncoding::CompactUTF16 => CanonicalOption::CompactUTF16, - } - } -} - -/// A producer section to be added to all modules and components synthesized by -/// this crate -pub(crate) fn base_producers() -> wasm_metadata::Producers { - let mut producer = wasm_metadata::Producers::empty(); - producer.add("processed-by", "wit-component", env!("CARGO_PKG_VERSION")); - producer -} - -/// Embed component metadata in a buffer of bytes that contains a Wasm module -pub fn embed_component_metadata( - bytes: &mut Vec, - wit_resolver: &Resolve, - world: WorldId, - encoding: StringEncoding, -) -> Result<()> { - let encoded = metadata::encode(&wit_resolver, world, encoding, None)?; - - let section = wasm_encoder::CustomSection { - name: "component-type".into(), - data: Cow::Borrowed(&encoded), - }; - bytes.push(section.id()); - section.encode(bytes); - - Ok(()) -} - -#[cfg(test)] -mod tests { - use anyhow::Result; - use wasmparser::Payload; - use wit_parser::Resolve; - - use super::{StringEncoding, embed_component_metadata}; - - const MODULE_WAT: &str = r#" -(module - (type (;0;) (func)) - (func (;0;) (type 0) - nop - ) -) -"#; - - const COMPONENT_WIT: &str = r#" -package test:foo; -world test-world {} -"#; - - #[test] - fn component_metadata_embedding_works() -> Result<()> { - let mut bytes = wat::parse_str(MODULE_WAT)?; - - // Get original len & custom section count - let original_len = bytes.len(); - let payloads = wasmparser::Parser::new(0).parse_all(&bytes); - let original_custom_section_count = payloads.fold(0, |acc, payload| { - if let Ok(Payload::CustomSection { .. }) = payload { - acc + 1 - } else { - acc - } - }); - - // Parse pre-canned WIT to build resolver - let mut resolver = Resolve::default(); - let pkg = resolver.push_str("in-code.wit", COMPONENT_WIT)?; - let world = resolver.select_world(&[pkg], Some("test-world"))?; - - // Embed component metadata - embed_component_metadata(&mut bytes, &resolver, world, StringEncoding::UTF8)?; - - // Re-retrieve custom section count, and search for the component-type custom section along the way - let mut found_component_section = false; - let new_custom_section_count = - wasmparser::Parser::new(0) - .parse_all(&bytes) - .fold(0, |acc, payload| { - if let Ok(Payload::CustomSection(reader)) = payload { - if reader.name() == "component-type" { - found_component_section = true; - } - acc + 1 - } else { - acc - } - }); - - assert!(original_len < bytes.len()); - assert_eq!(original_custom_section_count + 1, new_custom_section_count); - assert!(found_component_section); - - Ok(()) - } -} diff --git a/vendor/wit-component/src/linking.rs b/vendor/wit-component/src/linking.rs deleted file mode 100644 index 301205a9..00000000 --- a/vendor/wit-component/src/linking.rs +++ /dev/null @@ -1,1975 +0,0 @@ -//! Support for "pseudo-dynamic", shared-everything linking of Wasm modules into a component. -//! -//! This implements [shared-everything -//! linking](https://github.com/WebAssembly/component-model/blob/main/design/mvp/examples/SharedEverythingDynamicLinking.md), -//! taking as input one or more [dynamic -//! library](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md) modules and producing a -//! component whose type is the union of any `component-type*` custom sections found in the input modules. -//! -//! The entry point into this process is `Linker::encode`, which analyzes and topologically sorts the input -//! modules, then synthesizes two additional modules: -//! -//! - `main` AKA `env`: hosts the component's single memory and function table and exports any functions needed to -//! break dependency cycles discovered in the input modules. Those functions use `call.indirect` to invoke the real -//! functions, references to which are placed in the table by the `init` module. -//! -//! - `init`: populates the function table as described above, initializes global variables per the dynamic linking -//! tool convention, and calls any static constructors and/or link-time fixup functions -//! -//! `Linker` also supports synthesizing `dlopen`/`dlsym` lookup tables which allow symbols to be resolved at -//! runtime. Note that this is not true dynamic linking, since all the code is baked into the component ahead of -//! time -- we simply allow runtime resolution of already-resident definitions. This is sufficient to support -//! dynamic language FFI features such as Python native extensions, provided the required libraries are linked -//! ahead-of-time. - -use { - crate::encoding::fixup::{AddressDest, FixupModule, ImportedInstance, StartAction}, - crate::encoding::{ComponentEncoder, Instance, Item, LibraryInfo, MainOrAdapter}, - anyhow::{Context, Result, anyhow, bail}, - indexmap::{IndexMap, IndexSet, map::Entry}, - metadata::{Export, ExportKey, FunctionType, GlobalType, Metadata, Type, ValueType}, - std::{ - borrow::Cow, - collections::{BTreeMap, HashMap, HashSet}, - fmt::Debug, - hash::Hash, - }, - wasm_encoder::{ - CodeSection, ConstExpr, Elements, EntityType, ExportKind, ExportSection, Function, - FunctionSection, GlobalSection, ImportSection, MemArg, MemorySection, MemoryType, Module, - RawCustomSection, RefType, TableSection, TableType, TypeSection, ValType, - }, - wasmparser::SymbolFlags, -}; - -pub(crate) mod metadata; - -const PAGE_SIZE_BYTES: u32 = 65536; -// This matches the default stack size LLVM produces: -pub const DEFAULT_STACK_SIZE_BYTES: u32 = 16 * PAGE_SIZE_BYTES; -const HEAP_ALIGNMENT_BYTES: u32 = 16; -const STUB_LIBRARY_NAME: &str = "wit-component:stubs"; -const CABI_REALLOC: &str = "cabi_realloc"; - -/// Symbols to re-export from the `env` module regardless of whether any -/// libraries import them, since -/// `EncodingState::create_export_task_initialization_wrappers` needs to be able -/// to call them. -static ENV_REEXPORTS: &[(&str, &[ValueType], &[ValueType])] = - &[(metadata::TASK_HOOK, &[ValueType::I32], &[])]; - -enum Address<'a> { - Function(u32), - Global(&'a str), -} - -/// Represents a `dlopen`/`dlsym` lookup table enabling runtime symbol resolution -/// -/// The top level of this table is a sorted list of library names and offsets, each pointing to a sorted list of -/// symbol names and offsets. See ../dl/src/lib.rs for how this is used at runtime. -struct DlOpenables<'a> { - /// Offset into the main module's table where function references will be stored - table_base: u32, - - /// Offset into the main module's memory where the lookup table will be stored - memory_base: u32, - - /// The lookup table itself - buffer: Vec, - - /// Linear memory addresses where global variable addresses will live - /// - /// The init module will fill in the correct values at instantiation time. - global_addresses: Vec<(&'a str, &'a str, u32)>, - - /// Number of function references to be stored in the main module's table - function_count: u32, - - /// Linear memory address where the root of the lookup table will reside - /// - /// This can be different from `memory_base` depending on how the tree of libraries and symbols is laid out in - /// memory. - libraries_address: u32, -} - -impl<'a> DlOpenables<'a> { - /// Construct a lookup table containing all "dlopen-able" libraries and their symbols using the specified table - /// and memory offsets. - fn new(table_base: u32, memory_base: u32, metadata: &'a [Metadata<'a>]) -> Self { - let mut function_count = 0; - let mut buffer = Vec::new(); - let mut global_addresses = Vec::new(); - let mut libraries = metadata - .iter() - .filter(|metadata| metadata.dl_openable) - .map(|metadata| { - let name_address = memory_base + u32::try_from(buffer.len()).unwrap(); - write_bytes_padded(&mut buffer, metadata.name.as_bytes()); - - let mut symbols = metadata - .exports - .iter() - .filter_map(|export| { - let name_address = memory_base + u32::try_from(buffer.len()).unwrap(); - write_bytes_padded(&mut buffer, export.key.name.as_bytes()); - - let address = match &export.key.ty { - Type::Function(_) => Address::Function( - table_base + get_and_increment(&mut function_count), - ), - Type::Global(_) => Address::Global(export.key.name), - Type::Tag(_) => return None, - }; - - Some((export.key.name, name_address, address)) - }) - .collect::>(); - - symbols.sort_by_key(|(name, ..)| *name); - let symbols_len = symbols.len(); - - let start = buffer.len(); - for (name, name_address, address) in symbols { - write_u32(&mut buffer, u32::try_from(name.len()).unwrap()); - write_u32(&mut buffer, name_address); - match address { - Address::Function(address) => write_u32(&mut buffer, address), - Address::Global(name) => { - global_addresses.push(( - metadata.name, - name, - memory_base + u32::try_from(buffer.len()).unwrap(), - )); - - write_u32(&mut buffer, 0); - } - } - } - - ( - metadata.name, - name_address, - symbols_len, - memory_base + u32::try_from(start).unwrap(), - ) - }) - .collect::>(); - - libraries.sort_by_key(|(name, ..)| *name); - - let start = buffer.len(); - for (name, name_address, count, symbols) in &libraries { - write_u32(&mut buffer, u32::try_from(name.len()).unwrap()); - write_u32(&mut buffer, *name_address); - write_u32(&mut buffer, u32::try_from(*count).unwrap()); - write_u32(&mut buffer, *symbols); - } - - let libraries_address = memory_base + u32::try_from(buffer.len()).unwrap(); - write_u32(&mut buffer, u32::try_from(libraries.len()).unwrap()); - write_u32(&mut buffer, memory_base + u32::try_from(start).unwrap()); - - Self { - table_base, - memory_base, - buffer, - global_addresses, - function_count, - libraries_address, - } - } -} - -/// The layout of the whole program's thread-local storage bookkeeping. -/// -/// This generates a C structure that matches this layout: -/// -/// ```c -/// struct { -/// size_t num_libraries; -/// void **library_info; -/// void **main_thread_tls_base; -/// } __wasm_program_tls_info; -/// ``` -/// -/// where the `main_thread_tls_base` array is placed first, then the -/// `library_info` array, then this structure itself. -#[derive(Default)] -struct TlsLayout { - /// Address of the `main_thread_tls_base` array. - /// - /// This is left zero-initialized; no data segment covers it. - main_thread_tls_base: u32, - - /// Address of the `library_info` array. - library_info: u32, - - /// Address of the `__wasm_program_tls_info` struct itself. - program_info: u32, - - /// For each library, the slot it uses in the array of TLS base pointers, or - /// `None` if it has no thread-local storage of its own. - slots: Vec>, - - /// Static contents of the `__wasm_program_tls_info`. - buffer: Vec, -} - -impl TlsLayout { - /// Reserve linear memory and table space for the layout described above, - /// advancing `memory_offset` and `table_offset` past what's used. - /// - /// Nothing is reserved for a program which doesn't use thread-local storage - /// at all, and the `__wasm_program_tls_info` half is skipped unless some - /// library actually asks for it, which is only the case when the program - /// might spawn a thread. - fn new(metadata: &[Metadata], memory_offset: &mut u32) -> Self { - let needs_tls_base = metadata - .iter() - .any(|m| m.needs_get_tls_base || m.needs_set_tls_base); - let needs_program_info = metadata.iter().any(|m| m.needs_program_tls_info); - if !needs_tls_base && !needs_program_info { - return Self::default(); - } - - // Filter out libraries that don't have TLS. - let libraries = metadata - .iter() - .enumerate() - .filter(|(_, metadata)| metadata.has_library_tls_info) - .map(|(index, _)| index) - .collect::>(); - - let mut slots = vec![None; metadata.len()]; - for (slot, index) in libraries.iter().enumerate() { - slots[*index] = Some(u32::try_from(slot).unwrap()); - } - let count = u32::try_from(libraries.len()).unwrap(); - - // Allocate space for `main_thread_tls_base` - *memory_offset = align(*memory_offset, 4); - let main_thread_tls_base = *memory_offset; - *memory_offset += count * 4; - - let mut library_info = 0; - let mut program_info = 0; - let mut buffer = Vec::new(); - if needs_program_info { - library_info = *memory_offset; - *memory_offset += count * 4; - program_info = *memory_offset; - *memory_offset += 12; - - write_u32(&mut buffer, count); - write_u32(&mut buffer, library_info); - write_u32(&mut buffer, main_thread_tls_base); - } - - Self { - main_thread_tls_base, - library_info, - program_info, - slots, - buffer, - } - } - - /// The slot library `index` uses in the array of TLS base pointers. - fn slot(&self, index: usize) -> Option { - self.slots.get(index).copied().flatten() - } -} - -fn write_u32(buffer: &mut Vec, value: u32) { - buffer.extend(value.to_le_bytes()); -} - -fn write_bytes_padded(buffer: &mut Vec, bytes: &[u8]) { - buffer.extend(bytes); - - let len = u32::try_from(bytes.len()).unwrap(); - for _ in len..align(len, 4) { - buffer.push(0); - } -} - -fn align(a: u32, b: u32) -> u32 { - assert!(b.is_power_of_two()); - (a + (b - 1)) & !(b - 1) -} - -fn get_and_increment(n: &mut u32) -> u32 { - let v = *n; - *n += 1; - v -} - -fn const_u32(a: u32) -> ConstExpr { - ConstExpr::i32_const(a as i32) -} - -/// Helper trait for determining the size of a set or map -trait Length { - fn len(&self) -> usize; -} - -impl Length for HashSet { - fn len(&self) -> usize { - HashSet::len(self) - } -} - -impl Length for HashMap { - fn len(&self) -> usize { - HashMap::len(self) - } -} - -impl Length for IndexSet { - fn len(&self) -> usize { - IndexSet::len(self) - } -} - -impl Length for IndexMap { - fn len(&self) -> usize { - IndexMap::len(self) - } -} - -/// Extension trait for collecting into a set or map and asserting that there were no duplicate entries in the -/// source iterator. -trait CollectUnique: Iterator + Sized { - fn collect_unique + Length>(self) -> T { - let tmp = self.collect::>(); - let len = tmp.len(); - let result = tmp.into_iter().collect::(); - assert!( - result.len() == len, - "one or more duplicate items detected when collecting into set or map" - ); - result - } -} - -impl CollectUnique for T {} - -/// Extension trait for inserting into a map and asserting that an entry did not already exist for the key -trait InsertUnique { - type Key; - type Value; - - fn insert_unique(&mut self, k: Self::Key, v: Self::Value); -} - -impl InsertUnique for HashMap { - type Key = K; - type Value = V; - - fn insert_unique(&mut self, k: Self::Key, v: Self::Value) { - if let Some(old_v) = self.get(&k) { - panic!( - "duplicate item inserted into map for key {k:?} (old value: {old_v:?}; new value: {v:?})" - ); - } - self.insert(k, v); - } -} - -/// Synthesize the "main" module for the component, responsible for exporting functions which break cyclic -/// dependencies, as well as hosting the memory and function table. -fn make_env_module<'a>( - metadata: &'a [Metadata<'a>], - env_exports: &[EnvExport<'_>], - cabi_realloc_exporter: Option<&str>, - stack_size_bytes: u32, -) -> (Vec, DlOpenables<'a>, TlsLayout, u32) { - // TODO: deduplicate types - let mut types = TypeSection::new(); - let mut imports = ImportSection::new(); - let mut import_map = IndexMap::new(); - let mut function_count = 0; - let mut global_offset = 0; - let mut wasi_start = None; - - for metadata in metadata { - for import in &metadata.imports { - if let Entry::Vacant(entry) = import_map.entry(import) { - imports.import( - import.module, - import.name, - match &import.ty { - Type::Function(ty) => { - let index = get_and_increment(&mut function_count); - entry.insert(index); - types.ty().function( - ty.parameters.iter().copied().map(ValType::from), - ty.results.iter().copied().map(ValType::from), - ); - EntityType::Function(index) - } - Type::Global(ty) => { - entry.insert(get_and_increment(&mut global_offset)); - EntityType::Global(wasm_encoder::GlobalType { - val_type: ty.ty.into(), - mutable: ty.mutable, - shared: ty.shared, - }) - } - Type::Tag(_) => continue, - }, - ); - } - } - - if metadata.has_wasi_start { - if wasi_start.is_some() { - panic!("multiple libraries export {}", metadata::START); - } - let index = get_and_increment(&mut function_count); - - types.ty().function(vec![], vec![]); - imports.import(metadata.name, metadata::START, EntityType::Function(index)); - - wasi_start = Some(index); - } - } - - let mut memory_offset = stack_size_bytes; - - // Table offset 0 is reserved for the null function pointer. - // This convention follows wasm-ld's table layout: - // https://github.com/llvm/llvm-project/blob/913622d012f72edb5ac3a501cef8639d0ebe471b/lld/wasm/Driver.cpp#L581-L584 - let mut table_offset = 1; - let mut globals = GlobalSection::new(); - let mut exports = ExportSection::new(); - - if let Some(exporter) = cabi_realloc_exporter { - let index = get_and_increment(&mut function_count); - types.ty().function([ValType::I32; 4], [ValType::I32]); - imports.import(exporter, CABI_REALLOC, EntityType::Function(index)); - exports.export(CABI_REALLOC, ExportKind::Func, index); - } - - // If tls base shims are being generated, and something might spawn a - // thread, then the shims generated will need access to `context.get 1`. - let indirect_tls_base = metadata - .iter() - .any(|m| m.needs_get_tls_base || m.needs_set_tls_base) - && metadata.iter().any(|m| m.uses_thread_new_indirect); - let tls_context_get = if indirect_tls_base { - let index = get_and_increment(&mut function_count); - types.ty().function([], [ValType::I32]); - imports.import( - metadata::ROOT, - metadata::CONTEXT_GET_1, - EntityType::Function(index), - ); - Some(index) - } else { - None - }; - - let mut add_global_export = |name: &str, value, mutable| { - let index = globals.len(); - globals.global( - wasm_encoder::GlobalType { - val_type: ValType::I32, - mutable, - shared: false, - }, - &const_u32(value), - ); - exports.export(name, ExportKind::Global, index); - }; - - let dl_openables = DlOpenables::new(table_offset, memory_offset, metadata); - - if metadata.iter().any(|m| m.needs_libdl_libraries) { - add_global_export( - metadata::LIBDL_LIBRARIES, - dl_openables.libraries_address, - true, - ); - } - - table_offset += dl_openables.function_count; - memory_offset += u32::try_from(dl_openables.buffer.len()).unwrap(); - - let tls = TlsLayout::new(metadata, &mut memory_offset); - - if metadata.iter().any(|m| m.needs_program_tls_info) { - add_global_export(metadata::PROGRAM_TLS_INFO, tls.program_info, true); - } - - let memory_size = { - if metadata.iter().any(|m| m.needs_stack_pointer) { - add_global_export(metadata::STACK_POINTER, stack_size_bytes, true); - } - if metadata.iter().any(|m| m.needs_init_stack_pointer) { - add_global_export(metadata::INIT_STACK_POINTER, stack_size_bytes, false); - } - - // Binaryen's Asyncify transform for shared everything linking requires these globals - // to be provided from env module - let has_asyncified_module = metadata.iter().any(|m| m.is_asyncified); - if has_asyncified_module { - add_global_export(metadata::ASYNCIFY_STATE, 0, true); - add_global_export(metadata::ASYNCIFY_DATA, 0, true); - } - - // The libc.so in WASI-SDK 28+ requires these: - if metadata.iter().any(|m| m.needs_stack_high) { - add_global_export(metadata::STACK_HIGH, stack_size_bytes, true); - } - if metadata.iter().any(|m| m.needs_stack_low) { - add_global_export(metadata::STACK_LOW, 0, true); - } - - for metadata in metadata { - memory_offset = align(memory_offset, 1 << metadata.mem_info.memory_alignment); - table_offset = align(table_offset, 1 << metadata.mem_info.table_alignment); - - add_global_export( - &format!("{}:memory_base", metadata.name), - memory_offset, - false, - ); - add_global_export( - &format!("{}:table_base", metadata.name), - table_offset, - false, - ); - - memory_offset += metadata.mem_info.memory_size; - table_offset += metadata.mem_info.table_size; - - for import in &metadata.memory_address_imports { - // Note that we initialize this to zero and let the init module compute the real value at - // instantiation time. - add_global_export(&format!("{}:{import}", metadata.name), 0, true); - } - } - - { - let offsets = env_exports - .iter() - .enumerate() - .map(|(offset, EnvExport { name, exporter, .. })| { - ( - *name, - ( - table_offset + u32::try_from(offset).unwrap(), - metadata[*exporter].name == STUB_LIBRARY_NAME, - ), - ) - }) - .collect_unique::>(); - - for metadata in metadata { - for import in &metadata.table_address_imports { - let &(offset, is_stub) = offsets.get(import).unwrap(); - if is_stub - && metadata - .env_imports - .iter() - .any(|e| e.0 == *import && e.1.1.contains(SymbolFlags::BINDING_WEAK)) - { - add_global_export(&format!("{}:{import}", metadata.name), 0, true); - } else { - add_global_export(&format!("{}:{import}", metadata.name), offset, true); - } - } - } - } - - memory_offset = align(memory_offset, HEAP_ALIGNMENT_BYTES); - if metadata.iter().any(|m| m.needs_heap_base) { - add_global_export(metadata::HEAP_BASE, memory_offset, true); - } - - let heap_end = align(memory_offset, PAGE_SIZE_BYTES); - if metadata.iter().any(|m| m.needs_heap_end) { - add_global_export(metadata::HEAP_END, heap_end, true); - } - heap_end / PAGE_SIZE_BYTES - }; - - let indirection_table_base = table_offset; - - let mut functions = FunctionSection::new(); - let mut code = CodeSection::new(); - for export in env_exports { - let index = get_and_increment(&mut function_count); - types.ty().function( - export.ty.parameters.iter().copied().map(ValType::from), - export.ty.results.iter().copied().map(ValType::from), - ); - functions.function(u32::try_from(index).unwrap()); - let mut function = Function::new([]); - for local in 0..export.ty.parameters.len() { - function - .instructions() - .local_get(u32::try_from(local).unwrap()); - } - function - .instructions() - .i32_const(i32::try_from(table_offset).unwrap()) - .call_indirect(0, u32::try_from(index).unwrap()) - .end(); - code.function(&function); - exports.export(export.name, ExportKind::Func, index); - - table_offset += 1; - } - - // Define a distinct `__wasm_{get,set}_tls_base` pair for each library that - // needs one. Each pair reads and writes that library's slot of the array of - // pointers described by `TlsLayout`. - for (index, metadata) in metadata.iter().enumerate() { - // A library with no thread-local storage of its own has no slot in the - // array. If it still imports these then synthesize functions that trap - // since they shouldn't ever be called. - let Some(slot) = tls.slot(index) else { - for (needed, name, params, results) in [ - ( - metadata.needs_get_tls_base, - metadata::GET_TLS_BASE, - &[][..], - &[ValType::I32][..], - ), - ( - metadata.needs_set_tls_base, - metadata::SET_TLS_BASE, - &[ValType::I32][..], - &[][..], - ), - ] { - if !needed { - continue; - } - let func = get_and_increment(&mut function_count); - types - .ty() - .function(params.iter().copied(), results.iter().copied()); - functions.function(func); - let mut function = Function::new([]); - function.instructions().unreachable().end(); - code.function(&function); - exports.export(&format!("{}:{name}", metadata.name), ExportKind::Func, func); - } - continue; - }; - - let mem_arg = MemArg { - offset: u64::from(slot * 4), - align: 2, - memory_index: 0, - }; - - if metadata.needs_get_tls_base { - let func = get_and_increment(&mut function_count); - types.ty().function([], [ValType::I32]); - functions.function(func); - let mut function = Function::new([]); - // With coop threads the base pointer is in `context.get 1`. Without - // coop threads the base pointer is `main_thread_tls_base` itself. - match tls_context_get { - Some(get) => { - function.instructions().call(get); - } - None => { - function - .instructions() - .i32_const(i32::try_from(tls.main_thread_tls_base).unwrap()); - } - } - function.instructions().i32_load(mem_arg).end(); - code.function(&function); - exports.export( - &format!("{}:{}", metadata.name, metadata::GET_TLS_BASE), - ExportKind::Func, - func, - ); - } - - if metadata.needs_set_tls_base { - let func = get_and_increment(&mut function_count); - types.ty().function([ValType::I32], []); - functions.function(func); - let mut function = Function::new_with_locals_types(if tls_context_get.is_some() { - vec![ValType::I32] - } else { - vec![] - }); - // With coop threads this intrinsic conditionally initializes - // `main_thread_tls_base` based on `context.get 1`. Otherwise it - // writes through to it if it's set. - // - // Without coop threads this is updating `main_thread_tls_base`. - match tls_context_get { - Some(get) => { - function - .instructions() - .call(get) - .local_tee(1) - .i32_eqz() - .if_(wasm_encoder::BlockType::Empty) - .i32_const(i32::try_from(tls.main_thread_tls_base).unwrap()) - .local_get(0) - .i32_store(mem_arg) - .else_() - .local_get(1) - .local_get(0) - .i32_store(mem_arg) - .end() - .end(); - } - None => { - function - .instructions() - .i32_const(i32::try_from(tls.main_thread_tls_base).unwrap()) - .local_get(0) - .i32_store(mem_arg) - .end(); - } - } - code.function(&function); - exports.export( - &format!("{}:{}", metadata.name, metadata::SET_TLS_BASE), - ExportKind::Func, - func, - ); - } - } - - for (import, offset) in import_map { - exports.export( - &format!("{}:{}", import.module, import.name), - ExportKind::from(&import.ty), - offset, - ); - } - if let Some(index) = wasi_start { - exports.export(metadata::START, ExportKind::Func, index); - } - - let mut module = Module::new(); - - module.section(&types); - module.section(&imports); - module.section(&functions); - - { - let mut tables = TableSection::new(); - tables.table(TableType { - element_type: RefType::FUNCREF, - minimum: table_offset.into(), - maximum: None, - table64: false, - shared: false, - }); - exports.export(metadata::INDIRECT_FUNCTION_TABLE, ExportKind::Table, 0); - module.section(&tables); - } - - { - let mut memories = MemorySection::new(); - memories.memory(MemoryType { - minimum: u64::from(memory_size), - maximum: None, - memory64: false, - shared: false, - page_size_log2: None, - }); - exports.export(metadata::MEMORY, ExportKind::Memory, 0); - module.section(&memories); - } - - module.section(&globals); - module.section(&exports); - module.section(&code); - module.section(&RawCustomSection( - &crate::base_producers().raw_custom_section(), - )); - - let module = module.finish(); - wasmparser::validate(&module).unwrap(); - - (module, dl_openables, tls, indirection_table_base) -} - -/// Synthesize the "init" module, responsible for initializing global variables per the dynamic linking tool -/// convention and calling any static constructors and/or link-time fixup functions. -/// -/// This module also contains the data segment for the `dlopen`/`dlsym` lookup table. -fn make_init_module( - fixups: &mut FixupModule, - metadata: &[Metadata], - exporters: &IndexMap<&ExportKey, (&str, &Export)>, - env_exports: &[EnvExport<'_>], - dl_openables: &DlOpenables, - tls: &TlsLayout, - indirection_table_base: u32, -) -> Result<()> { - let thunk_ty = fixups.type_thunk(); - let memory = fixups.import( - &ImportedInstance::Main, - metadata::MEMORY, - MemoryType { - minimum: 0, - maximum: None, - memory64: false, - shared: false, - page_size_log2: None, - } - .into(), - )?; - let table = fixups.import( - &ImportedInstance::Main, - metadata::INDIRECT_FUNCTION_TABLE, - TableType { - element_type: RefType::FUNCREF, - minimum: 0, - maximum: None, - table64: false, - shared: false, - } - .into(), - )?; - - let module_name_to_instance = |module: &str| match module { - metadata::ENV => ImportedInstance::Main, - other => ImportedInstance::Adapter(other.to_string()), - }; - - let mut global_map = HashMap::new(); - let mut add_global_import = |fixups: &mut FixupModule, module: &str, name: &str, mutable| { - *global_map - .entry((module.to_owned(), name.to_owned())) - .or_insert_with(|| { - fixups - .import_global( - &module_name_to_instance(module), - name, - wasm_encoder::GlobalType { - val_type: ValType::I32, - mutable, - shared: false, - }, - ) - .unwrap() - }) - }; - - let mut function_map = HashMap::new(); - let mut add_function_import = |fixups: &mut FixupModule, module: &str, name: &str, ty| { - *function_map - .entry((module.to_owned(), name.to_owned())) - .or_insert_with(|| { - fixups - .import_func(&module_name_to_instance(module), name, ty) - .unwrap() - }) - }; - - let mut names = HashMap::new(); - for (index, metadata) in metadata.iter().enumerate() { - names.insert_unique(index, metadata.name); - } - - for (exporter, export, address) in dl_openables.global_addresses.iter() { - let memory_base = add_global_import( - fixups, - metadata::ENV, - &format!("{exporter}:memory_base"), - false, - ); - let export = add_global_import(fixups, exporter, export, false); - - fixups.add_start_abi_detail(StartAction::InitializeAddress { - memory_base, - export, - dest: AddressDest::LinearMemory { - address: *address, - memory, - }, - }); - } - - for metadata in metadata { - for import in &metadata.memory_address_imports { - let (exporter, _) = find_offset_exporter(import, exporters)?; - - let memory_base = add_global_import( - fixups, - metadata::ENV, - &format!("{exporter}:memory_base"), - false, - ); - let offset = add_global_import(fixups, exporter, import, false); - let address = add_global_import( - fixups, - metadata::ENV, - &format!("{}:{import}", metadata.name), - true, - ); - fixups.add_start_abi_detail(StartAction::InitializeAddress { - memory_base, - export: offset, - dest: AddressDest::Global(address), - }); - } - } - - for metadata in metadata { - if metadata.has_data_relocs { - let func = - add_function_import(fixups, metadata.name, metadata::APPLY_DATA_RELOCS, thunk_ty); - fixups.add_start_abi_detail(StartAction::Call(func)); - } - } - - for metadata in metadata { - if metadata.has_ctors && metadata.has_initialize { - bail!( - "library {} exports both `{}` and `{}`; \ - expected at most one of the two", - metadata.name, - metadata::CALL_CTORS, - metadata::INITIALIZE - ); - } - - if metadata.has_ctors { - let func = add_function_import(fixups, metadata.name, metadata::CALL_CTORS, thunk_ty); - fixups.add_start_user_func(StartAction::Call(func)); - } - - if metadata.has_initialize { - let func = add_function_import(fixups, metadata.name, metadata::INITIALIZE, thunk_ty); - fixups.add_start_user_func(StartAction::Call(func)); - } - } - - let intern_type = |fixups: &mut FixupModule, ty: &FunctionType| { - fixups.type_intern( - ty.parameters.iter().copied().map(|t| t.into()).collect(), - ty.results.iter().copied().map(|t| t.into()).collect(), - ) - }; - - let mut dl_openable_functions = Vec::new(); - for metadata in metadata { - if metadata.dl_openable { - for export in &metadata.exports { - if let Type::Function(fty) = &export.key.ty { - let ty = intern_type(fixups, fty); - dl_openable_functions.push(add_function_import( - fixups, - metadata.name, - export.key.name, - ty, - )); - } - } - } - } - - let indirections = env_exports - .iter() - .map(|EnvExport { name, exporter, ty }| { - let ty = intern_type(fixups, ty); - add_function_import(fixups, names[exporter], name, ty) - }) - .collect::>(); - - // For all libraries that export TLS information the initialization function - // here will setup the in-memory `__wasm_program_tls_info` structure by - // storing the pointers to each `__wasm_library_tls_info` structure in a - // sequence. - if tls.library_info != 0 { - for (lib_index, tls_index) in tls - .slots - .iter() - .enumerate() - .filter_map(|(i, slot)| slot.map(|j| (i, j))) - { - let metadata = &metadata[lib_index]; - let memory_base = add_global_import( - fixups, - metadata::ENV, - &format!("{}:memory_base", metadata.name), - false, - ); - let i = add_global_import(fixups, metadata.name, metadata::LIBRARY_TLS_INFO, false); - - fixups.add_start_abi_detail(StartAction::InitializeAddress { - memory_base, - export: i, - dest: AddressDest::LinearMemory { - address: tls.library_info + tls_index * 4, - memory, - }, - }); - } - } - - fixups.elements().active( - if table == 0 { None } else { Some(table) }, - &const_u32(dl_openables.table_base), - Elements::Functions(dl_openable_functions.into()), - ); - fixups.elements().active( - if table == 0 { None } else { Some(table) }, - &const_u32(indirection_table_base), - Elements::Functions(indirections.into()), - ); - - let data = fixups.data(); - data.active( - memory, - &const_u32(dl_openables.memory_base), - dl_openables.buffer.clone(), - ); - if !tls.buffer.is_empty() { - data.active(memory, &const_u32(tls.program_info), tls.buffer.clone()); - } - - Ok(()) -} - -/// Find the library which exports the specified function or global address. -fn find_offset_exporter<'a>( - name: &str, - exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>, -) -> Result<(&'a str, &'a Export<'a>)> { - let export = ExportKey { - name, - ty: Type::Global(GlobalType { - ty: ValueType::I32, - mutable: false, - shared: false, - }), - }; - - exporters - .get(&export) - .copied() - .ok_or_else(|| anyhow!("unable to find {export:?} in any library")) -} - -/// Find the library which exports the specified function. -fn find_function_exporter<'a>( - name: &str, - ty: &FunctionType, - exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>, -) -> Result<(&'a str, &'a Export<'a>)> { - let export = ExportKey { - name, - ty: Type::Function(ty.clone()), - }; - - exporters - .get(&export) - .copied() - .ok_or_else(|| anyhow!("unable to find {export:?} in any library")) -} - -/// Find the library which exports the specified tag. -fn find_tag_exporter<'a>( - name: &str, - ty: &FunctionType, - exporters: &IndexMap<&ExportKey, (&'a str, &'a Export<'a>)>, -) -> Result<(&'a str, &'a Export<'a>)> { - let export = ExportKey { - name, - ty: Type::Tag(ty.clone()), - }; - - exporters - .get(&export) - .copied() - .ok_or_else(|| anyhow!("unable to find {export:?} in any library")) -} - -/// Analyze the specified library metadata, producing a symbol-to-library-name map of exports. -fn resolve_exporters<'a>( - metadata: &'a [Metadata<'a>], -) -> Result, Vec<(&'a str, &'a Export<'a>)>>> { - let mut exporters = IndexMap::<_, Vec<_>>::new(); - for metadata in metadata { - for export in &metadata.exports { - exporters - .entry(&export.key) - .or_default() - .push((metadata.name, export)); - } - } - Ok(exporters) -} - -/// Match up all imported symbols to their corresponding exports, reporting any missing or duplicate symbols. -fn resolve_symbols<'a>( - metadata: &'a [Metadata<'a>], - exporters: &'a IndexMap<&'a ExportKey<'a>, Vec<(&'a str, &'a Export<'a>)>>, -) -> ( - IndexMap<&'a ExportKey<'a>, (&'a str, &'a Export<'a>)>, - Vec<(&'a str, Export<'a>)>, - Vec<(&'a str, &'a ExportKey<'a>, &'a [(&'a str, &'a Export<'a>)])>, -) { - let function_exporters = exporters - .iter() - .filter_map(|(export, exporters)| match &export.ty { - Type::Function(_) => Some((export.name, (export, exporters))), - Type::Global(_) | Type::Tag(_) => None, - }) - .collect_unique::>(); - - let mut resolved = IndexMap::new(); - let mut missing = Vec::new(); - let mut duplicates = Vec::new(); - - let mut triage = |metadata: &'a Metadata, export: Export<'a>| { - if let Some((key, value)) = exporters.get_key_value(&export.key) { - // Note that we do not use `insert_unique` here since multiple libraries may import the same - // symbol, in which case we may redundantly insert the same value. - match value.as_slice() { - [] => unreachable!(), - [exporter] => { - resolved.insert(*key, *exporter); - } - [exporter, ..] => { - resolved.insert(*key, *exporter); - duplicates.push((metadata.name, *key, value.as_slice())); - } - } - } else { - missing.push((metadata.name, export)); - } - }; - - for metadata in metadata { - for (name, (ty, flags)) in &metadata.env_imports { - triage( - metadata, - Export { - key: ExportKey { - name, - ty: Type::Function(ty.clone()), - }, - flags: *flags, - }, - ); - } - - for name in &metadata.memory_address_imports { - triage( - metadata, - Export { - key: ExportKey { - name, - ty: Type::Global(GlobalType { - ty: ValueType::I32, - mutable: false, - shared: false, - }), - }, - flags: SymbolFlags::empty(), - }, - ); - } - - for (name, ty) in &metadata.tag_imports { - triage( - metadata, - Export { - key: ExportKey { - name, - ty: Type::Tag(ty.clone()), - }, - flags: SymbolFlags::empty(), - }, - ); - } - } - - for metadata in metadata { - for name in &metadata.table_address_imports { - if let Some((key, value)) = function_exporters.get(name) { - // Note that we do not use `insert_unique` here since multiple libraries may import the same - // symbol, in which case we may redundantly insert the same value. - match value.as_slice() { - [] => unreachable!(), - [exporter] => { - resolved.insert(key, *exporter); - } - [exporter, ..] => { - resolved.insert(key, *exporter); - duplicates.push((metadata.name, *key, value.as_slice())); - } - } - } else if metadata.env_imports.iter().any(|(n, _)| n == name) { - // GOT entry for a function which is imported from the env module, but not exported by any library, - // already handled above. - } else { - missing.push(( - metadata.name, - Export { - key: ExportKey { - name, - ty: Type::Function(FunctionType { - parameters: Vec::new(), - results: Vec::new(), - }), - }, - flags: SymbolFlags::empty(), - }, - )); - } - } - } - - // Even if no library imports these symbols, we re-export them from the - // `env` module so that - // `EncodingState::create_export_task_initialization_wrappers` can find - // and use them: - for (name, params, results) in ENV_REEXPORTS { - let export = Export { - key: ExportKey { - name, - ty: Type::Function(FunctionType { - parameters: params.to_vec(), - results: results.to_vec(), - }), - }, - flags: SymbolFlags::empty(), - }; - - if let Some((key, value)) = exporters.get_key_value(&export.key) { - // Note that we do not use `insert_unique` here since multiple - // libraries may import the same symbol, in which case we may - // redundantly insert the same value. - match value.as_slice() { - [] => unreachable!(), - [exporter] | [exporter, ..] => { - resolved.insert(*key, *exporter); - } - } - } - } - - (resolved, missing, duplicates) -} - -/// Recursively add a library (represented by its offset) and its dependency to the specified set, maintaining -/// topological order (modulo cycles). -fn topo_add( - sorted: &mut IndexSet, - dependencies: &IndexMap>, - element: usize, -) { - let empty = &IndexSet::new(); - let deps = dependencies.get(&element).unwrap_or(empty); - - // First, add any dependencies which do not depend on `element` - for &dep in deps { - if !(sorted.contains(&dep) || dependencies.get(&dep).unwrap_or(empty).contains(&element)) { - topo_add(sorted, dependencies, dep); - } - } - - // Next, add the element - sorted.insert(element); - - // Finally, add any dependencies which depend on `element` - for &dep in deps { - if !sorted.contains(&dep) && dependencies.get(&dep).unwrap_or(empty).contains(&element) { - topo_add(sorted, dependencies, dep); - } - } -} - -/// Topologically sort a set of libraries (represented by their offsets) according to their dependencies, modulo -/// cycles. -fn topo_sort(count: usize, dependencies: &IndexMap>) -> Result> { - let mut sorted = IndexSet::new(); - for index in 0..count { - topo_add(&mut sorted, &dependencies, index); - } - - Ok(sorted.into_iter().collect()) -} - -/// Analyze the specified library metadata, producing a map of transitive dependencies, where each library is -/// represented by its offset in the original metadata slice. -fn find_dependencies( - metadata: &[Metadata], - exporters: &IndexMap<&ExportKey, (&str, &Export)>, -) -> Result>> { - // First, generate a map of direct dependencies (i.e. depender to dependees) - let mut dependencies = IndexMap::<_, IndexSet<_>>::new(); - let mut indexes = HashMap::new(); - for (index, metadata) in metadata.iter().enumerate() { - indexes.insert_unique(metadata.name, index); - for &needed in &metadata.needed_libs { - dependencies - .entry(metadata.name) - .or_default() - .insert(needed); - } - for (import_name, (ty, _)) in &metadata.env_imports { - dependencies - .entry(metadata.name) - .or_default() - .insert(find_function_exporter(import_name, ty, exporters)?.0); - } - } - - // Next, convert the map from names to offsets - let mut dependencies = dependencies - .into_iter() - .map(|(k, v)| { - ( - indexes[k], - v.into_iter() - .map(|v| indexes[v]) - .collect_unique::>(), - ) - }) - .collect_unique::>(); - - // Finally, add all transitive dependencies to the map in a fixpoint loop, exiting when no new dependencies are - // discovered. - let empty = &IndexSet::new(); - - loop { - let mut new = IndexMap::<_, IndexSet<_>>::new(); - for (index, exporters) in &dependencies { - for exporter in exporters { - for exporter in dependencies.get(exporter).unwrap_or(empty) { - if !exporters.contains(exporter) { - new.entry(*index).or_default().insert(*exporter); - } - } - } - } - - if new.is_empty() { - break Ok(dependencies); - } else { - for (index, exporters) in new { - dependencies.entry(index).or_default().extend(exporters); - } - } - } -} - -struct EnvExports<'a> { - exports: Vec>, - reexport_cabi_realloc: bool, -} - -struct EnvExport<'a> { - name: &'a str, - ty: Cow<'a, FunctionType>, - exporter: usize, -} - -/// Analyze the specified metadata and generate what needs to be exported from -/// the main (aka "env") module. -/// -/// This includes a list of functions which should be re-exported as a -/// `call.indirect`-based function including the offset of the library -/// containing the original export. -/// -/// Additionally this includes any tags necessary that are shared amongst -/// modules. -fn env_exports<'a>( - metadata: &'a [Metadata<'a>], - exporters: &'a IndexMap<&'a ExportKey, (&'a str, &Export)>, - topo_sorted: &[usize], -) -> Result> { - let function_exporters = exporters - .iter() - .filter_map(|(export, exporter)| { - if let Type::Function(ty) = &export.ty { - Some((export.name, (ty, *exporter))) - } else { - None - } - }) - .collect_unique::>(); - - let indexes = metadata - .iter() - .enumerate() - .map(|(index, metadata)| (metadata.name, index)) - .collect_unique::>(); - - let mut result = Vec::new(); - let mut exported = HashSet::new(); - let mut seen = HashSet::new(); - - for &index in topo_sorted { - let metadata = &metadata[index]; - - for name in &metadata.table_address_imports { - if !exported.contains(name) { - let (ty, (exporter, _)) = function_exporters - .get(name) - .ok_or_else(|| anyhow!("unable to find {name:?} in any library"))?; - - result.push(EnvExport { - name: *name, - ty: Cow::Borrowed(*ty), - exporter: indexes[exporter], - }); - exported.insert(*name); - } - } - - for (import_name, (ty, _)) in &metadata.env_imports { - if !exported.contains(import_name) { - let exporter = indexes[find_function_exporter(import_name, ty, exporters) - .unwrap() - .0]; - if !seen.contains(&exporter) { - result.push(EnvExport { - name: *import_name, - ty: Cow::Borrowed(ty), - exporter, - }); - exported.insert(*import_name); - } - } - } - - seen.insert(index); - } - - // Even if no library imports these symbols, we re-export them from the - // `env` module so that - // `EncodingState::create_export_task_initialization_wrappers` can find - // and use them: - for (name, params, results) in ENV_REEXPORTS { - if !exported.contains(name) { - let ty = FunctionType { - parameters: params.to_vec(), - results: results.to_vec(), - }; - if let Some(exporter) = exporters.get(&ExportKey { - name, - ty: Type::Function(ty.clone()), - }) { - result.push(EnvExport { - name, - ty: Cow::Owned(ty), - exporter: indexes[exporter.0], - }); - exported.insert(name); - } - } - } - - let reexport_cabi_realloc = exported.contains(CABI_REALLOC); - - Ok(EnvExports { - exports: result, - reexport_cabi_realloc, - }) -} - -/// Synthesize a module which contains trapping stub exports for the specified functions. -fn make_stubs_module(missing: &[(&str, Export)]) -> Vec { - let mut types = TypeSection::new(); - let mut exports = ExportSection::new(); - let mut functions = FunctionSection::new(); - let mut code = CodeSection::new(); - for (offset, (_, export)) in missing.iter().enumerate() { - let offset = u32::try_from(offset).unwrap(); - - let Export { - key: - ExportKey { - name, - ty: Type::Function(ty), - }, - .. - } = export - else { - unreachable!(); - }; - - types.ty().function( - ty.parameters.iter().copied().map(ValType::from), - ty.results.iter().copied().map(ValType::from), - ); - functions.function(offset); - let mut function = Function::new([]); - function.instructions().unreachable().end(); - code.function(&function); - exports.export(name, ExportKind::Func, offset); - } - - let mut module = Module::new(); - - module.section(&types); - module.section(&functions); - module.section(&exports); - module.section(&code); - module.section(&RawCustomSection( - &crate::base_producers().raw_custom_section(), - )); - - let module = module.finish(); - wasmparser::validate(&module).unwrap(); - - module -} - -/// Determine which of the specified libraries are transitively reachable at runtime, i.e. reachable from a -/// component export or via `dlopen`. -fn find_reachable<'a>( - metadata: &'a [Metadata<'a>], - dependencies: &IndexMap>, -) -> IndexSet<&'a str> { - let reachable = metadata - .iter() - .enumerate() - .filter_map(|(index, metadata)| { - if metadata.has_component_exports || metadata.dl_openable || metadata.has_wasi_start { - Some(index) - } else { - None - } - }) - .collect_unique::>(); - - let empty = &IndexSet::new(); - - reachable - .iter() - .chain( - reachable - .iter() - .flat_map(|index| dependencies.get(index).unwrap_or(empty)), - ) - .map(|&index| metadata[index].name) - .collect() -} - -/// Builder type for composing dynamic library modules into a component -#[derive(Default)] -pub struct Linker { - /// The `(name, module, dl_openable)` triple representing the libraries to be composed - /// - /// The order of this list determines priority in cases where more than one library exports the same symbol. - libraries: Vec<(String, Vec, bool)>, - - /// Whether to generate trapping stubs for any unresolved imports - stub_missing_functions: bool, - - /// Whether to use a built-in implementation of `dlopen`/`dlsym`. - use_built_in_libdl: bool, - - /// Size of stack (in bytes) to allocate in the synthesized main module - /// - /// If `None`, use `DEFAULT_STACK_SIZE_BYTES`. - stack_size: Option, - - encoder: ComponentEncoder, -} - -impl Linker { - /// Add a dynamic library module to this linker. - /// - /// If `dl_openable` is true, all of the library's exports will be added to the `dlopen`/`dlsym` lookup table - /// for runtime resolution. - pub fn library(&mut self, name: &str, module: &[u8], dl_openable: bool) -> Result<&mut Self> { - self.libraries - .push((name.to_owned(), module.to_vec(), dl_openable)); - - Ok(self) - } - - /// Specify size of stack to allocate in the synthesized main module - pub fn stack_size(&mut self, stack_size: u32) -> &mut Self { - self.stack_size = Some(stack_size); - self - } - - /// Specify whether to generate trapping stubs for any unresolved imports - pub fn stub_missing_functions(&mut self, stub_missing_functions: bool) -> &mut Self { - self.stub_missing_functions = stub_missing_functions; - self - } - - /// Specify whether to use a built-in implementation of `dlopen`/`dlsym`. - pub fn use_built_in_libdl(&mut self, use_built_in_libdl: bool) -> &mut Self { - self.use_built_in_libdl = use_built_in_libdl; - self - } - - /// Returns a reference to the internal [`ComponentEncoder`] that can be - /// configured. - pub fn encoder(&mut self) -> &mut ComponentEncoder { - &mut self.encoder - } - - /// Encode the component and return the bytes - pub fn encode(mut self) -> Result> { - if self.use_built_in_libdl { - self.use_built_in_libdl = false; - self.library("libdl.so", include_bytes!("../libdl.so"), false)?; - } - - let adapter_names = self - .encoder - .adapters - .keys() - .map(|name| name.as_str()) - .collect::>(); - - let metadata = self - .libraries - .iter() - .map(|(name, module, dl_openable)| { - Metadata::try_new(name, *dl_openable, module, &adapter_names) - .with_context(|| format!("failed to extract linking metadata from {name}")) - }) - .collect::>>()?; - - { - let names = self - .libraries - .iter() - .map(|(name, ..)| name.as_str()) - .collect_unique::>(); - - let missing = metadata - .iter() - .filter_map(|metadata| { - let missing = metadata - .needed_libs - .iter() - .copied() - .filter(|name| !names.contains(*name)) - .collect::>(); - - if missing.is_empty() { - None - } else { - Some((metadata.name, missing)) - } - }) - .collect::>(); - - if !missing.is_empty() { - bail!( - "missing libraries:\n{}", - missing - .iter() - .map(|(needed_by, missing)| format!( - "\t{needed_by} needs {}", - missing.join(", ") - )) - .collect::>() - .join("\n") - ); - } - } - - let exporters = resolve_exporters(&metadata)?; - - let cabi_realloc_exporter = exporters - .get(&ExportKey { - name: "cabi_realloc", - ty: Type::Function(FunctionType { - parameters: vec![ValueType::I32; 4], - results: vec![ValueType::I32], - }), - }) - .map(|exporters| exporters.first().unwrap().0); - - let (exporters, missing, _) = resolve_symbols(&metadata, &exporters); - - if !missing.is_empty() { - if missing - .iter() - .all(|(_, export)| matches!(&export.key.ty, Type::Function(_))) - && (self.stub_missing_functions - || missing - .iter() - .all(|(_, export)| export.flags.contains(SymbolFlags::BINDING_WEAK))) - { - self.stub_missing_functions = false; - self.libraries - .push((STUB_LIBRARY_NAME.into(), make_stubs_module(&missing), false)); - return self.encode(); - } else { - bail!( - "unresolved symbol(s):\n{}", - missing - .iter() - .filter(|(_, export)| !export.flags.contains(SymbolFlags::BINDING_WEAK)) - .map(|(importer, export)| { format!("\t{importer} needs {}", export.key) }) - .collect::>() - .join("\n") - ); - } - } - - let dependencies = find_dependencies(&metadata, &exporters)?; - - { - let reachable = find_reachable(&metadata, &dependencies); - let unreachable = self - .libraries - .iter() - .filter_map(|(name, ..)| (!reachable.contains(name.as_str())).then(|| name.clone())) - .collect_unique::>(); - - if !unreachable.is_empty() { - self.libraries - .retain(|(name, ..)| !unreachable.contains(name)); - return self.encode(); - } - } - - let topo_sorted = topo_sort(metadata.len(), &dependencies)?; - - let EnvExports { - exports: env_exports, - reexport_cabi_realloc, - } = env_exports(&metadata, &exporters, &topo_sorted)?; - - let (env_module, dl_openables, tls, table_base) = make_env_module( - &metadata, - &env_exports, - if reexport_cabi_realloc { - // If "env" module already reexports "cabi_realloc", we don't need to - // reexport it again. - None - } else { - cabi_realloc_exporter - }, - self.stack_size.unwrap_or(DEFAULT_STACK_SIZE_BYTES), - ); - - self.encoder.module(&env_module)?; - - let default_env_items = [ - Item { - alias: metadata::MEMORY.into(), - kind: ExportKind::Memory, - which: MainOrAdapter::Main, - name: metadata::MEMORY.into(), - }, - Item { - alias: metadata::INDIRECT_FUNCTION_TABLE.into(), - kind: ExportKind::Table, - which: MainOrAdapter::Main, - name: metadata::INDIRECT_FUNCTION_TABLE.into(), - }, - Item { - alias: metadata::STACK_POINTER.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: metadata::STACK_POINTER.into(), - }, - Item { - alias: metadata::INIT_STACK_POINTER.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: metadata::INIT_STACK_POINTER.into(), - }, - ]; - - let mut seen = HashSet::new(); - for index in topo_sorted { - let (name, module, _) = &self.libraries[index]; - let metadata = &metadata[index]; - - let env_items = default_env_items - .iter() - .cloned() - .chain([ - Item { - alias: metadata::MEMORY_BASE.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: format!("{name}:memory_base"), - }, - Item { - alias: metadata::TABLE_BASE.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: format!("{name}:table_base"), - }, - ]) - .chain( - [ - (metadata.needs_get_tls_base, metadata::GET_TLS_BASE), - (metadata.needs_set_tls_base, metadata::SET_TLS_BASE), - ] - .into_iter() - .filter(|(needed, _)| *needed) - .map(|(_, intrinsic)| Item { - alias: intrinsic.into(), - kind: ExportKind::Func, - which: MainOrAdapter::Main, - name: format!("{name}:{intrinsic}"), - }), - ) - .chain(metadata.env_imports.iter().map(|(name, (ty, _))| { - let (exporter, _) = find_function_exporter(name, ty, &exporters).unwrap(); - - Item { - alias: (*name).into(), - kind: ExportKind::Func, - which: if seen.contains(exporter) { - MainOrAdapter::Adapter(exporter.to_owned()) - } else { - MainOrAdapter::Main - }, - name: (*name).into(), - } - })) - .chain( - metadata - .tag_imports - .iter() - .map(|(name, ty)| { - let (exporter, _) = find_tag_exporter(name, ty, &exporters).unwrap(); - - Ok(Item { - alias: (*name).into(), - kind: ExportKind::Tag, - which: if seen.contains(exporter) { - MainOrAdapter::Adapter(exporter.to_owned()) - } else { - // As of this writing, LLVM-produced shared - // libraries which use C++ exceptions import - // a `cpp_exception` tag which is defined in - // `libunwind.so`. Presumably - // `libunwind.so` will not import anything - // circularly from such shared libraries, so - // this case shouldn't be hit in practice - // unless we're dealing with some other, - // non-LLVM toolchain that does weird - // circular things with imports and - // exception tags. - bail!( - "circular dependency prevents direct tag import from `{}`", - exporter.to_owned() - ) - }, - name: (*name).into(), - }) - }) - .collect::>>()?, - ) - .chain(if metadata.is_asyncified { - vec![ - Item { - alias: metadata::ASYNCIFY_STATE.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: metadata::ASYNCIFY_STATE.into(), - }, - Item { - alias: metadata::ASYNCIFY_DATA.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: metadata::ASYNCIFY_DATA.into(), - }, - ] - } else { - vec![] - }) - .collect(); - - let global_item = |address_name: &str| Item { - alias: address_name.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: format!("{name}:{address_name}"), - }; - - let mem_items = metadata - .memory_address_imports - .iter() - .copied() - .map(global_item) - .chain( - [ - metadata::HEAP_BASE, - metadata::HEAP_END, - metadata::STACK_HIGH, - metadata::STACK_LOW, - metadata::LIBDL_LIBRARIES, - metadata::PROGRAM_TLS_INFO, - ] - .into_iter() - .map(|name| Item { - alias: name.into(), - kind: ExportKind::Global, - which: MainOrAdapter::Main, - name: name.into(), - }), - ) - .collect(); - - let func_items = metadata - .table_address_imports - .iter() - .copied() - .map(global_item) - .collect(); - - let mut import_items = BTreeMap::<_, Vec<_>>::new(); - for import in &metadata.imports { - import_items.entry(import.module).or_default().push(Item { - alias: import.name.into(), - kind: ExportKind::from(&import.ty), - which: MainOrAdapter::Main, - name: format!("{}:{}", import.module, import.name), - }); - } - - self.encoder.library( - name, - module, - LibraryInfo { - arguments: [ - (metadata::GOT_MEM.into(), Instance::Items(mem_items)), - (metadata::GOT_FUNC.into(), Instance::Items(func_items)), - (metadata::ENV.into(), Instance::Items(env_items)), - ] - .into_iter() - .chain( - import_items - .into_iter() - .map(|(k, v)| (k.into(), Instance::Items(v))), - ) - .collect(), - }, - )?; - - seen.insert(name.as_str()); - } - - self.encoder.encode_with_fixups(Some(&mut |fixups| { - make_init_module( - fixups, - &metadata, - &exporters, - &env_exports, - &dl_openables, - &tls, - table_base, - ) - })) - } -} diff --git a/vendor/wit-component/src/linking/metadata.rs b/vendor/wit-component/src/linking/metadata.rs deleted file mode 100644 index 7e26f86c..00000000 --- a/vendor/wit-component/src/linking/metadata.rs +++ /dev/null @@ -1,654 +0,0 @@ -//! Support for parsing and analyzing [dynamic -//! library](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md) modules. - -use { - anyhow::{Context, Error, Result, bail}, - std::{ - collections::{BTreeSet, HashMap, HashSet}, - fmt, - }, - wasmparser::{ - Dylink0Subsection, ExternalKind, FuncType, KnownCustom, MemInfo, Parser, Payload, RefType, - SymbolFlags, TableType, TagKind, TagType, TypeRef, ValType, - }, -}; - -pub const ENV: &str = "env"; -pub const GOT_MEM: &str = "GOT.mem"; -pub const GOT_FUNC: &str = "GOT.func"; -pub const MEMORY: &str = "memory"; -pub const MEMORY_BASE: &str = "__memory_base"; -pub const TABLE_BASE: &str = "__table_base"; -pub const STACK_POINTER: &str = "__stack_pointer"; -pub const INIT_STACK_POINTER: &str = "__init_stack_pointer"; -pub const ASYNCIFY_DATA: &str = "__asyncify_data"; -pub const ASYNCIFY_STATE: &str = "__asyncify_state"; -pub const INDIRECT_FUNCTION_TABLE: &str = "__indirect_function_table"; -pub const HEAP_BASE: &str = "__heap_base"; -pub const HEAP_END: &str = "__heap_end"; -pub const STACK_HIGH: &str = "__stack_high"; -pub const STACK_LOW: &str = "__stack_low"; -pub const APPLY_DATA_RELOCS: &str = "__wasm_apply_data_relocs"; -pub const CALL_CTORS: &str = "__wasm_call_ctors"; -pub const INITIALIZE: &str = "_initialize"; -pub const START: &str = "_start"; -pub const LIBDL_LIBRARIES: &str = "__wasm_libdl_libraries"; -pub const TASK_HOOK: &str = "__wasm_task_hook"; -pub const ROOT: &str = "$root"; -pub const THREAD_NEW_INDIRECT: &str = "[thread-new-indirect-v0]"; -pub const CONTEXT_GET_1: &str = "[context-get-1]"; -pub const GET_STACK_POINTER: &str = "__wasm_get_stack_pointer"; -pub const SET_STACK_POINTER: &str = "__wasm_set_stack_pointer"; -pub const GET_TLS_BASE: &str = "__wasm_get_tls_base"; -pub const SET_TLS_BASE: &str = "__wasm_set_tls_base"; -pub const PROGRAM_TLS_INFO: &str = "__wasm_program_tls_info"; -pub const LIBRARY_TLS_INFO: &str = "__wasm_library_tls_info"; - -/// Represents a core Wasm value type (not including V128 or reference types, which are not yet supported) -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub enum ValueType { - I32, - I64, - F32, - F64, -} - -impl TryFrom for ValueType { - type Error = Error; - - fn try_from(value: ValType) -> Result { - Ok(match value { - ValType::I32 => Self::I32, - ValType::I64 => Self::I64, - ValType::F32 => Self::F32, - ValType::F64 => Self::F64, - _ => bail!("{value:?} not yet supported"), - }) - } -} - -impl From for wasm_encoder::ValType { - fn from(value: ValueType) -> Self { - match value { - ValueType::I32 => Self::I32, - ValueType::I64 => Self::I64, - ValueType::F32 => Self::F32, - ValueType::F64 => Self::F64, - } - } -} - -/// Represents a core Wasm function type -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct FunctionType { - pub parameters: Vec, - pub results: Vec, -} - -impl fmt::Display for FunctionType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?} -> {:?}", self.parameters, self.results) - } -} - -impl TryFrom<&FuncType> for FunctionType { - type Error = Error; - - fn try_from(value: &FuncType) -> Result { - Ok(Self { - parameters: value - .params() - .iter() - .map(|&v| ValueType::try_from(v)) - .collect::>()?, - results: value - .results() - .iter() - .map(|&v| ValueType::try_from(v)) - .collect::>()?, - }) - } -} - -/// Represents a core Wasm global variable type -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct GlobalType { - pub ty: ValueType, - pub mutable: bool, - pub shared: bool, -} - -impl fmt::Display for GlobalType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.mutable { - write!(f, "mut ")?; - } - write!(f, "{:?}", self.ty) - } -} - -/// Represents a core Wasm export or import type -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub enum Type { - Function(FunctionType), - Global(GlobalType), - Tag(FunctionType), -} - -impl fmt::Display for Type { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Self::Function(ty) => write!(f, "function {ty}"), - Self::Global(ty) => write!(f, "global {ty}"), - Self::Tag(ty) => write!(f, "tag {ty}"), - } - } -} - -impl From<&Type> for wasm_encoder::ExportKind { - fn from(value: &Type) -> Self { - match value { - Type::Function(_) => wasm_encoder::ExportKind::Func, - Type::Global(_) => wasm_encoder::ExportKind::Global, - Type::Tag(_) => wasm_encoder::ExportKind::Tag, - } - } -} - -/// Represents a core Wasm import -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Import<'a> { - pub module: &'a str, - pub name: &'a str, - pub ty: Type, - pub flags: SymbolFlags, -} - -/// Represents a core Wasm export -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct ExportKey<'a> { - pub name: &'a str, - pub ty: Type, -} - -impl<'a> fmt::Display for ExportKey<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{} ({})", self.name, self.ty) - } -} - -/// Represents a core Wasm export, including dylink.0 flags -#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct Export<'a> { - pub key: ExportKey<'a>, - pub flags: SymbolFlags, -} - -/// Metadata extracted from a dynamic library module -#[derive(Debug)] -pub struct Metadata<'a> { - /// The name of the module - /// - /// This is currently not part of the file itself and must be provided separately, but the plan is to add - /// something like a `WASM_DYLINK_SO_NAME` field to the dynamic linking tool convention so we can parse it - /// along with everything else. - pub name: &'a str, - - /// Whether this module should be resolvable via `dlopen` - pub dl_openable: bool, - - /// The `WASM_DYLINK_MEM_INFO` value (or all zeros if not found) - pub mem_info: MemInfo, - - /// The `WASM_DYLINK_NEEDED` values, if any - pub needed_libs: Vec<&'a str>, - - /// The `WASM_DYLINK_RUNTIME_PATH` values, if any - pub runtime_path: Vec<&'a str>, - - /// Whether this module exports `__wasm_apply_data_relocs` - pub has_data_relocs: bool, - - /// Whether this module exports `__wasm_call_ctors` - pub has_ctors: bool, - - /// Whether this module exports `_initialize` - pub has_initialize: bool, - - /// Whether this module exports `_start` - pub has_wasi_start: bool, - - /// Whether this module imports `__wasm_libdl_libraries` - pub needs_libdl_libraries: bool, - - /// Whether this module includes any `component-type*` custom sections which include exports - pub has_component_exports: bool, - - /// Whether this module imports `__asyncify_state` or `__asyncify_data`, indicating that it is - /// asyncified with `--pass-arg=asyncify-relocatable` option. - pub is_asyncified: bool, - - /// Whether this module imports `__stack_pointer` - pub needs_stack_pointer: bool, - - /// Whether this module imports `__init_stack_pointer` - pub needs_init_stack_pointer: bool, - - /// Whether this module imports `__heap_base` - pub needs_heap_base: bool, - - /// Whether this module imports `__heap_end` - pub needs_heap_end: bool, - - /// Whether this module imports `__stack_high` - pub needs_stack_high: bool, - - /// Whether this module imports `__stack_low` - pub needs_stack_low: bool, - - /// Whether this module imports `env::__wasm_get_tls_base` - pub needs_get_tls_base: bool, - - /// Whether this module imports `env::__wasm_set_tls_base` - pub needs_set_tls_base: bool, - - /// Whether this module imports the address of `__wasm_program_tls_info` - pub needs_program_tls_info: bool, - - /// Whether this module imports `$root::[thread-new-indirect-v0]`, meaning - /// the program may spawn threads and is thus using cooperative threading. - pub uses_thread_new_indirect: bool, - - /// Whether this module exports a `__wasm_library_tls_info` symbol. - pub has_library_tls_info: bool, - - /// The functions imported from the `env` module, if any - pub env_imports: BTreeSet<(&'a str, (FunctionType, SymbolFlags))>, - - /// The memory addresses imported from `GOT.mem`, if any - pub memory_address_imports: BTreeSet<&'a str>, - - /// The table addresses imported from `GOT.func`, if any - pub table_address_imports: BTreeSet<&'a str>, - - /// Imported exception tags - pub tag_imports: BTreeSet<(&'a str, FunctionType)>, - - /// The symbols exported by this module, if any - pub exports: BTreeSet>, - - /// The symbols imported by this module (and not accounted for in the above fields), if any - pub imports: BTreeSet>, -} - -impl<'a> Metadata<'a> { - /// Parse the specified module and extract its metadata. - pub fn try_new( - name: &'a str, - dl_openable: bool, - module: &'a [u8], - adapter_names: &HashSet<&str>, - ) -> Result { - let bindgen = crate::metadata::decode(module)?.1; - let has_component_exports = !bindgen.resolve.worlds[bindgen.world].exports.is_empty(); - - let mut result = Self { - name, - dl_openable, - mem_info: MemInfo { - memory_size: 0, - memory_alignment: 1, - table_size: 0, - table_alignment: 1, - }, - needed_libs: Vec::new(), - runtime_path: Vec::new(), - has_data_relocs: false, - has_ctors: false, - has_initialize: false, - has_wasi_start: false, - needs_libdl_libraries: false, - has_component_exports, - is_asyncified: false, - needs_stack_pointer: false, - needs_init_stack_pointer: false, - needs_heap_base: false, - needs_heap_end: false, - needs_stack_high: false, - needs_stack_low: false, - needs_get_tls_base: false, - needs_set_tls_base: false, - needs_program_tls_info: false, - uses_thread_new_indirect: false, - has_library_tls_info: false, - env_imports: BTreeSet::new(), - memory_address_imports: BTreeSet::new(), - table_address_imports: BTreeSet::new(), - exports: BTreeSet::new(), - imports: BTreeSet::new(), - tag_imports: BTreeSet::new(), - }; - let mut types = Vec::new(); - let mut function_types = Vec::new(); - let mut global_types = Vec::new(); - let mut tag_types = Vec::new(); - let mut import_info = HashMap::new(); - let mut export_info = HashMap::new(); - - for payload in Parser::new(0).parse_all(module) { - match payload? { - Payload::CustomSection(section) => { - if let KnownCustom::Dylink0(reader) = section.as_known() { - for subsection in reader { - match subsection.context("failed to parse `dylink.0` subsection")? { - Dylink0Subsection::MemInfo(info) => result.mem_info = info, - Dylink0Subsection::Needed(needed) => { - result.needed_libs = needed.clone() - } - Dylink0Subsection::ExportInfo(info) => { - export_info - .extend(info.iter().map(|info| (info.name, info.flags))); - } - Dylink0Subsection::ImportInfo(info) => { - import_info.extend( - info.iter() - .map(|info| ((info.module, info.field), info.flags)), - ); - } - Dylink0Subsection::RuntimePath(runtime_path) => { - result.runtime_path.extend(runtime_path.iter()); - } - Dylink0Subsection::Unknown { ty, .. } => { - bail!("unrecognized `dylink.0` subsection: {ty}") - } - } - } - } - } - - Payload::TypeSection(reader) => { - types = reader - .into_iter_err_on_gc_types() - .collect::, _>>()?; - } - - Payload::ImportSection(reader) => { - for import in reader.into_imports() { - let import = import?; - - match import.ty { - TypeRef::Func(ty) => function_types.push(usize::try_from(ty).unwrap()), - TypeRef::Global(ty) => { - global_types.push(ty); - } - TypeRef::Tag(ty) => tag_types.push(ty), - _ => (), - } - - let type_error = || { - bail!( - "unexpected type for {}:{}: {:?}", - import.module, - import.name, - import.ty - ) - }; - - match (import.module, import.name) { - (self::ENV, self::MEMORY) => { - if !matches!(import.ty, TypeRef::Memory(_)) { - return type_error(); - } - } - (self::ENV, self::ASYNCIFY_DATA | self::ASYNCIFY_STATE) => { - result.is_asyncified = true; - if !matches!( - import.ty, - TypeRef::Global(wasmparser::GlobalType { - content_type: ValType::I32, - .. - }) - ) { - return type_error(); - } - } - ( - self::ENV, - self::MEMORY_BASE - | self::TABLE_BASE - | self::STACK_POINTER - | self::INIT_STACK_POINTER, - ) => { - if matches!( - import.ty, - TypeRef::Global(wasmparser::GlobalType { - content_type: ValType::I32, - .. - }) - ) { - match import.name { - self::STACK_POINTER => result.needs_stack_pointer = true, - self::INIT_STACK_POINTER => { - result.needs_init_stack_pointer = true - } - _ => {} - } - } else { - return type_error(); - } - } - (self::ENV, self::INDIRECT_FUNCTION_TABLE) => { - if let TypeRef::Table(TableType { - element_type, - maximum: None, - .. - }) = import.ty - { - if element_type != RefType::FUNCREF { - return type_error(); - } - } else { - return type_error(); - } - } - ( - self::ENV, - name @ (self::GET_STACK_POINTER - | self::SET_STACK_POINTER - | self::GET_TLS_BASE - | self::SET_TLS_BASE), - ) => { - if !matches!(import.ty, TypeRef::Func(_)) { - return type_error(); - } - match name { - self::GET_TLS_BASE => result.needs_get_tls_base = true, - self::SET_TLS_BASE => result.needs_set_tls_base = true, - _ => {} - } - } - (self::ENV, name) => match import.ty { - TypeRef::Func(ty) => { - result.env_imports.insert(( - name, - ( - FunctionType::try_from( - &types[usize::try_from(ty).unwrap()], - )?, - import_info - .get(&(self::ENV, name)) - .copied() - .unwrap_or_default(), - ), - )); - } - TypeRef::Tag(TagType { - kind: TagKind::Exception, - func_type_idx, - }) => { - result.tag_imports.insert(( - name, - FunctionType::try_from( - &types[usize::try_from(func_type_idx).unwrap()], - )?, - )); - } - _ => return type_error(), - }, - (self::GOT_MEM, name) => { - if let TypeRef::Global(wasmparser::GlobalType { - content_type: ValType::I32, - .. - }) = import.ty - { - match name { - self::HEAP_BASE => result.needs_heap_base = true, - self::HEAP_END => result.needs_heap_end = true, - self::STACK_HIGH => result.needs_stack_high = true, - self::STACK_LOW => result.needs_stack_low = true, - self::LIBDL_LIBRARIES => { - result.needs_libdl_libraries = true; - } - self::PROGRAM_TLS_INFO => { - result.needs_program_tls_info = true; - } - - _ => { - result.memory_address_imports.insert(name); - } - } - } else { - return type_error(); - } - } - (self::GOT_FUNC, name) => { - if let TypeRef::Global(wasmparser::GlobalType { - content_type: ValType::I32, - .. - }) = import.ty - { - result.table_address_imports.insert(name); - } else { - return type_error(); - } - } - (self::ROOT, self::THREAD_NEW_INDIRECT) => { - result.uses_thread_new_indirect = true; - } - (module, name) if adapter_names.contains(module) => { - let ty = match import.ty { - TypeRef::Global(wasmparser::GlobalType { - content_type, - mutable, - shared, - }) => Type::Global(GlobalType { - ty: content_type.try_into()?, - mutable, - shared, - }), - TypeRef::Func(ty) => Type::Function(FunctionType::try_from( - &types[usize::try_from(ty).unwrap()], - )?), - ty => { - bail!("unsupported import kind for {module}.{name}: {ty:?}",) - } - }; - let flags = import_info - .get(&(module, name)) - .copied() - .unwrap_or_default(); - result.imports.insert(Import { - module, - name, - ty, - flags, - }); - } - _ => { - if !matches!(import.ty, TypeRef::Func(_) | TypeRef::Global(_)) { - return type_error(); - } - } - } - } - } - - Payload::FunctionSection(reader) => { - for function in reader { - function_types.push(usize::try_from(function?).unwrap()); - } - } - - Payload::GlobalSection(reader) => { - for global in reader { - let global = global?; - global_types.push(global.ty); - } - } - - Payload::TagSection(reader) => { - for tag in reader { - tag_types.push(tag?); - } - } - - Payload::ExportSection(reader) => { - for export in reader { - let export = export?; - - match export.name { - self::APPLY_DATA_RELOCS => result.has_data_relocs = true, - self::CALL_CTORS => result.has_ctors = true, - self::INITIALIZE => result.has_initialize = true, - self::START => result.has_wasi_start = true, - self::LIBRARY_TLS_INFO => result.has_library_tls_info = true, - _ => { - let ty = match export.kind { - ExternalKind::Func => Type::Function(FunctionType::try_from( - &types[function_types - [usize::try_from(export.index).unwrap()]], - )?), - ExternalKind::Global => { - let ty = - global_types[usize::try_from(export.index).unwrap()]; - Type::Global(GlobalType { - ty: ValueType::try_from(ty.content_type)?, - mutable: ty.mutable, - shared: ty.shared, - }) - } - ExternalKind::Tag => Type::Tag(FunctionType::try_from( - &types[usize::try_from( - tag_types[usize::try_from(export.index).unwrap()] - .func_type_idx, - ) - .unwrap()], - )?), - kind => { - bail!( - "unsupported export kind for {}: {kind:?}", - export.name - ) - } - }; - let flags = - export_info.get(&export.name).copied().unwrap_or_default(); - result.exports.insert(Export { - key: ExportKey { - name: export.name, - ty, - }, - flags, - }); - } - } - } - } - - _ => {} - } - } - - Ok(result) - } -} diff --git a/vendor/wit-component/src/metadata.rs b/vendor/wit-component/src/metadata.rs deleted file mode 100644 index 361facbc..00000000 --- a/vendor/wit-component/src/metadata.rs +++ /dev/null @@ -1,448 +0,0 @@ -//! Definition for encoding of custom sections within core wasm modules of -//! component-model related data. -//! -//! When creating a component from a source language the high-level process for -//! doing this is that code will be generated into the source language by -//! `wit-bindgen` or a similar tool which will be compiled down to core wasm. -//! The core wasm file is then fed into `wit-component` and a component is -//! created. This means that the componentization process is decoupled from the -//! binding generation process and intentionally affords for linking together -//! libraries into the main core wasm module that import different interfaces. -//! -//! The purpose of this module is to define an intermediate format to reside in -//! a custom section in the core wasm output. This intermediate format is -//! carried through the wasm linker through a custom section whose name starts -//! with `component-type`. This custom section is created -//! per-language-binding-generation and consumed by slurping up all the -//! sections during the component creation process. -//! -//! Currently the encoding of this custom section is itself a component. The -//! component has a single export which is a component type which represents the -//! `world` that was bound during bindings generation. This single export is -//! used to decode back into a `Resolve` with a WIT representation. -//! -//! Currently the component additionally has a custom section named -//! `wit-component-encoding` (see `CUSTOM_SECTION_NAME`). This section is -//! currently defined as 2 bytes: -//! -//! * The first byte is `CURRENT_VERSION` to help protect against future and -//! past changes. -//! * The second byte indicates the string encoding used for imports/exports as -//! part of the bindings process. The mapping is defined by -//! `encode_string_encoding`. -//! -//! This means that the top-level `encode` function takes a `Resolve`, a -//! `WorldId`, and a `StringEncoding`. Note that the top-level `decode` function -//! is slightly different because it's taking all custom sections in a core -//! wasm binary, possibly from multiple invocations of bindgen, and unioning -//! them all together. This means that the output is a `Bindgen` which -//! represents the union of all previous bindings. -//! -//! The dual of `encode` is the `decode_custom_section` function which decodes -//! the three arguments originally passed to `encode`. - -use crate::{DecodedWasm, StringEncoding}; -use anyhow::{Context, Result, bail}; -use indexmap::{IndexMap, IndexSet}; -use std::borrow::Cow; -use wasm_encoder::{ - ComponentBuilder, ComponentExportKind, ComponentType, ComponentTypeRef, CustomSection, -}; -use wasm_metadata::Producers; -use wasmparser::{BinaryReader, Encoding, Parser, Payload}; -use wit_parser::{CloneMaps, Package, PackageName, Resolve, World, WorldId, WorldItem, WorldKey}; - -const CURRENT_VERSION: u8 = 0x04; -const CUSTOM_SECTION_NAME: &str = "wit-component-encoding"; - -/// The result of decoding binding information from a WebAssembly binary. -/// -/// This structure is returned by [`decode`] and represents the interface of a -/// WebAssembly binary. -pub struct Bindgen { - /// Interface and type information for this binary. - pub resolve: Resolve, - /// The world that was bound. - pub world: WorldId, - /// Metadata about this specific module that was bound. - pub metadata: ModuleMetadata, - /// Producer information about tools used to produce this specific module. - pub producers: Option, -} - -impl Default for Bindgen { - fn default() -> Bindgen { - let mut resolve = Resolve::default(); - let package = resolve.packages.alloc(Package { - name: PackageName { - namespace: "root".to_string(), - name: "root".to_string(), - version: None, - }, - docs: Default::default(), - interfaces: Default::default(), - worlds: Default::default(), - }); - let world = resolve.worlds.alloc(World { - name: "root".to_string(), - docs: Default::default(), - imports: Default::default(), - exports: Default::default(), - includes: Default::default(), - package: Some(package), - stability: Default::default(), - span: Default::default(), - }); - resolve.packages[package] - .worlds - .insert("root".to_string(), world); - Bindgen { - resolve, - world, - metadata: ModuleMetadata::default(), - producers: None, - } - } -} - -/// Module-level metadata that's specific to one core WebAssembly module. This -/// is extracted with a [`Bindgen`]. -#[derive(Default)] -pub struct ModuleMetadata { - /// Per-function options imported into the core wasm module, currently only - /// related to string encoding. - pub import_encodings: EncodingMap, - - /// Per-function options exported from the core wasm module, currently only - /// related to string encoding. - pub export_encodings: EncodingMap, -} - -/// Internal map that keeps track of encodings for various world imports and -/// exports. -/// -/// Stored in [`ModuleMetadata`]. -#[derive(Default)] -pub struct EncodingMap { - /// A map of an "identifying string" for world items to what string - /// encoding the import or export is using. - /// - /// The keys of this map are created by `EncodingMap::key` and are - /// specifically chosen to be able to be looked up during both insertion and - /// fetching. Note that in particular this map does not use `*Id` types such - /// as `InterfaceId` from `wit_parser`. This is due to the fact that during - /// world merging new interfaces are created for named imports (e.g. `import - /// x: interface { ... }`) as inline interfaces are copied from one world to - /// another. Additionally during world merging different interfaces at the - /// same version may be deduplicated. - /// - /// For these reasons a string-based key is chosen to avoid juggling IDs - /// through the world merging process. Additionally versions are chopped off - /// for now to help with a problem such as: - /// - /// * The main module imports a:b/c@0.1.0 - /// * An adapter imports a:b/c@0.1.1 - /// * The final world uses a:b/c@0.1.1, but the main module has no - /// encoding listed for that exact item. - /// - /// By chopping off versions this is able to get everything registered - /// correctly even in the fact of merging interfaces and worlds. - encodings: IndexMap, -} - -impl EncodingMap { - fn insert_all( - &mut self, - resolve: &Resolve, - set: &IndexMap, - encoding: StringEncoding, - ) { - for (name, item) in set { - match item { - WorldItem::Function(func) => { - let key = self.key(resolve, name, &func.name); - self.encodings.insert(key, encoding); - } - WorldItem::Interface { id, .. } => { - for (func, _) in resolve.interfaces[*id].functions.iter() { - let key = self.key(resolve, name, func); - self.encodings.insert(key, encoding); - } - } - WorldItem::Type { .. } => {} - } - } - } - - /// Looks up the encoding of the function `func` which is scoped under `key` - /// in the world in question. - pub fn get(&self, resolve: &Resolve, key: &WorldKey, func: &str) -> Option { - let key = self.key(resolve, key, func); - self.encodings.get(&key).copied() - } - - fn key(&self, resolve: &Resolve, key: &WorldKey, func: &str) -> String { - format!( - "{}/{func}", - match key { - WorldKey::Name(name) => name.to_string(), - WorldKey::Interface(id) => { - let iface = &resolve.interfaces[*id]; - let pkg = &resolve.packages[iface.package.unwrap()]; - format!( - "{}:{}/{}", - pkg.name.namespace, - pkg.name.name, - iface.name.as_ref().unwrap() - ) - } - } - ) - } - - fn merge(&mut self, other: EncodingMap) -> Result<()> { - for (key, encoding) in other.encodings { - if let Some(prev) = self.encodings.insert(key.clone(), encoding) { - if prev != encoding { - bail!("conflicting string encodings specified for `{key}`"); - } - } - } - Ok(()) - } -} - -/// This function will parse the core `wasm` binary given as input and return a -/// [`Bindgen`] which extracts the custom sections describing component-level -/// types from within the binary itself. -/// -/// This is used to parse the output of `wit-bindgen`-generated modules and is -/// one of the earliest phases in transitioning such a module to a component. -/// The extraction here provides the metadata necessary to continue the process -/// later on. -/// -/// This will return an error if `wasm` is not a valid WebAssembly module. -/// -/// If a `component-type` custom section was found then a new binary is -/// optionally returned with the custom sections stripped out. If no -/// `component-type` custom sections are found then `None` is returned. -pub fn decode(wasm: &[u8]) -> Result<(Option>, Bindgen)> { - let mut ret = Bindgen::default(); - let mut new_module = wasm_encoder::Module::new(); - - let mut found_custom = false; - for payload in wasmparser::Parser::new(0).parse_all(&wasm) { - let payload = payload.context("decoding item in module")?; - match payload { - wasmparser::Payload::CustomSection(cs) if cs.name().starts_with("component-type") => { - let data = Bindgen::decode_custom_section(cs.data()) - .with_context(|| format!("decoding custom section {}", cs.name()))?; - ret.merge(data) - .with_context(|| format!("updating metadata for section {}", cs.name()))?; - found_custom = true; - } - wasmparser::Payload::Version { encoding, .. } if encoding != Encoding::Module => { - bail!("decoding a component is not supported") - } - _ => { - if let Some((id, range)) = payload.as_section() { - new_module.section(&wasm_encoder::RawSection { - id, - data: &wasm[range.start as usize..range.end as usize], - }); - } - } - } - } - - if found_custom { - Ok((Some(new_module.finish()), ret)) - } else { - Ok((None, ret)) - } -} - -/// Creates a `component-type*` custom section to be decoded by `decode` above. -/// -/// This is primarily created by wit-bindgen-based guest generators to embed -/// into the final core wasm binary. The core wasm binary is later fed -/// through `wit-component` to produce the actual component where this returned -/// section will be decoded. -pub fn encode( - resolve: &Resolve, - world: WorldId, - string_encoding: StringEncoding, - extra_producers: Option<&Producers>, -) -> Result> { - let ty = crate::encoding::encode_world(resolve, world)?; - - let world = &resolve.worlds[world]; - let mut outer_ty = ComponentType::new(); - outer_ty.ty().component(&ty); - outer_ty.export( - resolve.id_of_name(world.package.unwrap(), &world.name), - ComponentTypeRef::Component(0), - ); - - let mut builder = ComponentBuilder::default(); - - let string_encoding = encode_string_encoding(string_encoding); - builder.custom_section(&CustomSection { - name: CUSTOM_SECTION_NAME.into(), - data: Cow::Borrowed(&[CURRENT_VERSION, string_encoding]), - }); - - let ty = builder.type_component(None, &outer_ty); - builder.export(&world.name, ComponentExportKind::Type, ty, None); - - let mut producers = crate::base_producers(); - if let Some(p) = extra_producers { - producers.merge(&p); - } - builder.raw_custom_section(&producers.raw_custom_section()); - Ok(builder.finish()) -} - -fn decode_custom_section(wasm: &[u8]) -> Result<(Resolve, WorldId, StringEncoding)> { - let (resolve, world) = wit_parser::decoding::decode_world(wasm)?; - let mut custom_section = None; - - for payload in Parser::new(0).parse_all(wasm) { - match payload? { - Payload::CustomSection(s) if s.name() == CUSTOM_SECTION_NAME => { - custom_section = Some(s.data()); - } - _ => {} - } - } - let string_encoding = match custom_section { - None => bail!("missing custom section of name `{CUSTOM_SECTION_NAME}`"), - Some([CURRENT_VERSION, byte]) => decode_string_encoding(*byte)?, - Some([]) => bail!("custom section `{CUSTOM_SECTION_NAME}` in unknown format"), - Some([version, ..]) => bail!( - "custom section `{CUSTOM_SECTION_NAME}` uses format {version} but only {CURRENT_VERSION} is supported" - ), - }; - Ok((resolve, world, string_encoding)) -} - -fn encode_string_encoding(e: StringEncoding) -> u8 { - match e { - StringEncoding::UTF8 => 0x00, - StringEncoding::UTF16 => 0x01, - StringEncoding::CompactUTF16 => 0x02, - } -} - -fn decode_string_encoding(byte: u8) -> Result { - match byte { - 0x00 => Ok(StringEncoding::UTF8), - 0x01 => Ok(StringEncoding::UTF16), - 0x02 => Ok(StringEncoding::CompactUTF16), - byte => bail!("invalid string encoding {byte:#x}"), - } -} - -impl Bindgen { - fn decode_custom_section(data: &[u8]) -> Result { - let wasm; - let world; - let resolve; - let encoding; - - let mut reader = BinaryReader::new(&data, 0); - match reader.read_u8()? { - // Historical 0x03 format where the support here will be deleted in - // the future - 0x03 => { - encoding = decode_string_encoding(reader.read_u8()?)?; - let world_name = reader.read_string()?; - let data_offset = reader.original_position() as usize; - wasm = &data[data_offset..]; - - let (r, pkg) = match crate::decode(wasm)? { - DecodedWasm::WitPackage(resolve, pkgs) => (resolve, pkgs), - DecodedWasm::Component(..) => bail!("expected encoded wit package(s)"), - }; - resolve = r; - world = resolve.select_world(&[pkg], Some(world_name.into()))?; - } - - // Current format where `data` is a wasm component itself. - _ => { - wasm = data; - (resolve, world, encoding) = decode_custom_section(wasm)?; - } - } - - Ok(Bindgen { - metadata: ModuleMetadata::new(&resolve, world, encoding), - producers: wasm_metadata::Producers::from_wasm(wasm)?, - resolve, - world, - }) - } - - /// Merges another `BindgenMetadata` into this one. - /// - /// This operation is intended to be akin to "merging worlds" when the - /// abstraction level for that is what we're working at here. For now the - /// merge operation only succeeds if the two metadata descriptions are - /// entirely disjoint. - /// - /// Note that at this time there's no support for changing string encodings - /// between metadata. - /// - /// This function returns the set of exports that the main world of - /// `other` added to the world in `self`. - pub fn merge(&mut self, other: Bindgen) -> Result> { - let Bindgen { - resolve, - world, - metadata: - ModuleMetadata { - import_encodings, - export_encodings, - }, - producers, - } = other; - - let remap = self - .resolve - .merge(resolve) - .context("failed to merge WIT package sets together")?; - let world = remap.map_world(world, Default::default())?; - let exports = self.resolve.worlds[world].exports.keys().cloned().collect(); - self.resolve - .merge_worlds(world, self.world, &mut CloneMaps::default()) - .context("failed to merge worlds from two documents")?; - - self.metadata.import_encodings.merge(import_encodings)?; - self.metadata.export_encodings.merge(export_encodings)?; - if let Some(producers) = producers { - if let Some(mine) = &mut self.producers { - mine.merge(&producers); - } else { - self.producers = Some(producers); - } - } - - Ok(exports) - } -} - -impl ModuleMetadata { - /// Creates a new `ModuleMetadata` instance holding the given set of - /// interfaces which are expected to all use the `encoding` specified. - pub fn new(resolve: &Resolve, world: WorldId, encoding: StringEncoding) -> ModuleMetadata { - let mut ret = ModuleMetadata::default(); - - let world = &resolve.worlds[world]; - ret.export_encodings - .insert_all(resolve, &world.exports, encoding); - ret.import_encodings - .insert_all(resolve, &world.imports, encoding); - - ret - } -} diff --git a/vendor/wit-component/src/printing.rs b/vendor/wit-component/src/printing.rs deleted file mode 100644 index a9381465..00000000 --- a/vendor/wit-component/src/printing.rs +++ /dev/null @@ -1,1533 +0,0 @@ -use anyhow::{Result, anyhow, bail}; -use std::borrow::Cow; -use std::collections::HashMap; -use std::fmt::Display; -use std::mem; -use std::ops::Deref; -use wit_parser::*; - -/// A utility for printing WebAssembly interface definitions to a string. -pub struct WitPrinter { - /// Visitor that holds the WIT document being printed. - pub output: O, - - // Count of how many items in this current block have been printed to print - // a blank line between each item, but not the first item. - any_items: bool, - - // Whether to print doc comments. - emit_docs: bool, -} - -impl Default for WitPrinter { - fn default() -> Self { - Self::new(OutputToString::default()) - } -} - -impl WitPrinter { - /// Create new instance. - pub fn new(output: O) -> Self { - Self { - output, - any_items: false, - emit_docs: true, - } - } - - /// Prints the specified `pkg` which is located in `resolve` to `O`. - /// - /// The `nested` list of packages are other packages to include at the end - /// of the output in `package ... { ... }` syntax. - pub fn print(&mut self, resolve: &Resolve, pkg: PackageId, nested: &[PackageId]) -> Result<()> { - self.print_package(resolve, pkg, true)?; - for (i, pkg_id) in nested.iter().enumerate() { - if i > 0 { - self.output.newline(); - self.output.newline(); - } - self.print_package(resolve, *pkg_id, false)?; - } - Ok(()) - } - - /// Configure whether doc comments will be printed. - /// - /// Defaults to true. - pub fn emit_docs(&mut self, enabled: bool) -> &mut Self { - self.emit_docs = enabled; - self - } - - /// Prints the specified `pkg`. - /// - /// If `is_main` is not set, nested package notation is used. - pub fn print_package( - &mut self, - resolve: &Resolve, - pkg: PackageId, - is_main: bool, - ) -> Result<()> { - let pkg = &resolve.packages[pkg]; - self.print_package_outer(pkg)?; - - if is_main { - self.output.semicolon(); - self.output.newline(); - } else { - self.output.indent_start(); - } - - for (name, id) in pkg.interfaces.iter() { - self.print_interface_outer(resolve, *id, name)?; - self.output.indent_start(); - self.print_interface(resolve, *id)?; - self.output.indent_end(); - if is_main { - self.output.newline(); - } - } - - for (name, id) in pkg.worlds.iter() { - self.print_docs(&resolve.worlds[*id].docs); - self.print_stability(&resolve.worlds[*id].stability); - self.output.keyword("world"); - self.output.str(" "); - self.print_name_type(name, TypeKind::WorldDeclaration); - self.output.indent_start(); - self.print_world(resolve, *id)?; - self.output.indent_end(); - } - if !is_main { - self.output.indent_end(); - } - Ok(()) - } - - /// Print the specified package without its content. - /// Does not print the semicolon nor starts the indentation. - pub fn print_package_outer(&mut self, pkg: &Package) -> Result<()> { - self.print_docs(&pkg.docs); - self.output.keyword("package"); - self.output.str(" "); - self.print_name_type(&pkg.name.namespace, TypeKind::NamespaceDeclaration); - self.output.str(":"); - self.print_name_type(&pkg.name.name, TypeKind::PackageNameDeclaration); - if let Some(version) = &pkg.name.version { - self.print_name_type(&format!("@{version}"), TypeKind::VersionDeclaration); - } - Ok(()) - } - - fn new_item(&mut self) { - if self.any_items { - self.output.newline(); - } - self.any_items = true; - } - - /// Print the given WebAssembly interface without its content. - /// Does not print the semicolon nor starts the indentation. - pub fn print_interface_outer( - &mut self, - resolve: &Resolve, - id: InterfaceId, - name: &str, - ) -> Result<()> { - self.print_docs(&resolve.interfaces[id].docs); - self.print_stability(&resolve.interfaces[id].stability); - self.output.keyword("interface"); - self.output.str(" "); - self.print_name_type(name, TypeKind::InterfaceDeclaration); - Ok(()) - } - - /// Print the inner content of a given WebAssembly interface. - pub fn print_interface(&mut self, resolve: &Resolve, id: InterfaceId) -> Result<()> { - let prev_items = mem::replace(&mut self.any_items, false); - let interface = &resolve.interfaces[id]; - - let mut resource_funcs = HashMap::new(); - let mut freestanding = Vec::new(); - for (_, func) in interface.functions.iter() { - if let Some(id) = func.kind.resource() { - resource_funcs.entry(id).or_insert(Vec::new()).push(func); - } else { - freestanding.push(func); - } - } - - self.print_types( - resolve, - TypeOwner::Interface(id), - interface - .types - .iter() - .map(|(name, id)| (name.as_str(), *id)), - &resource_funcs, - )?; - - for func in freestanding { - self.new_item(); - self.print_docs(&func.docs); - self.print_stability(&func.stability); - self.print_external_id(func.external_id.as_deref()); - self.print_name_type(func.item_name(), TypeKind::FunctionFreestanding); - self.output.str(": "); - self.print_function(resolve, func)?; - self.output.semicolon(); - } - - self.any_items = prev_items; - - Ok(()) - } - - /// Print types of an interface. - pub fn print_types<'a>( - &mut self, - resolve: &Resolve, - owner: TypeOwner, - types: impl Iterator, - resource_funcs: &HashMap>, - ) -> Result<()> { - // Partition types defined in this interface into either those imported - // from foreign interfaces or those defined locally. - let mut types_to_declare = Vec::new(); - let mut types_to_import: Vec<(_, &TypeDef, Vec<_>)> = Vec::new(); - for (name, ty_id) in types { - let ty = &resolve.types[ty_id]; - - // If `ty` points to another type, `other`, then this might actually - // be a `use`. - if let TypeDefKind::Type(Type::Id(other)) = ty.kind { - let other = &resolve.types[other]; - match other.owner { - TypeOwner::None => {} - - // `use` is only applicable when the owner of the current - // set of types is different than the owner of `other`. Once - // this is detected `types_to_import` is going to get - // modified. - other_owner if owner != other_owner => { - let other_name = other - .name - .as_ref() - .ok_or_else(|| anyhow!("cannot import unnamed type"))?; - - // As a convenience push onto the last set of types to - // import if it's to the same interface and with - // matching attributes. - if let Some((prev_owner, prev_ty, list)) = types_to_import.last_mut() { - if *prev_owner == other_owner - && ty.stability == prev_ty.stability - && ty.external_id == prev_ty.external_id - { - list.push((name, other_name)); - continue; - } - } - types_to_import.push((other_owner, ty, vec![(name, other_name)])); - continue; - } - _ => {} - } - } - - types_to_declare.push(ty_id); - } - - // Generate a `use` statement for all imported types. - let my_pkg = match owner { - TypeOwner::Interface(id) => resolve.interfaces[id].package.unwrap(), - TypeOwner::World(id) => resolve.worlds[id].package.unwrap(), - TypeOwner::None => unreachable!(), - }; - for (owner, ty, tys) in types_to_import { - self.any_items = true; - self.print_stability(&ty.stability); - self.print_external_id(ty.external_id.as_deref()); - self.output.keyword("use"); - self.output.str(" "); - let id = match owner { - TypeOwner::Interface(id) => id, - // it's only possible to import types from interfaces at - // this time. - _ => unreachable!(), - }; - self.print_path_to_interface(resolve, id, my_pkg)?; - self.output.str(".{"); // Note: not changing the indentation. - for (i, (my_name, other_name)) in tys.into_iter().enumerate() { - if i > 0 { - self.output.str(", "); - } - if my_name == other_name { - self.print_name_type(my_name, TypeKind::TypeImport); - } else { - self.print_name_type(other_name, TypeKind::TypeImport); - self.output.str(" "); - self.output.keyword("as"); - self.output.str(" "); - self.print_name_type(my_name, TypeKind::TypeAlias); - } - } - self.output.str("}"); // Note: not changing the indentation. - self.output.semicolon(); - } - - for id in types_to_declare { - self.new_item(); - self.print_docs(&resolve.types[id].docs); - self.print_stability(&resolve.types[id].stability); - self.print_external_id(resolve.types[id].external_id.as_deref()); - match resolve.types[id].kind { - TypeDefKind::Resource => self.print_resource( - resolve, - id, - resource_funcs.get(&id).unwrap_or(&Vec::new()), - )?, - _ => self.declare_type(resolve, &Type::Id(id))?, - } - } - - Ok(()) - } - - fn print_resource(&mut self, resolve: &Resolve, id: TypeId, funcs: &[&Function]) -> Result<()> { - let ty = &resolve.types[id]; - self.output.ty("resource", TypeKind::BuiltIn); - self.output.str(" "); - self.print_name_type( - ty.name.as_ref().expect("resources must be named"), - TypeKind::Resource, - ); - if funcs.is_empty() { - self.output.semicolon(); - return Ok(()); - } - self.output.indent_start(); - for func in funcs { - self.print_docs(&func.docs); - self.print_stability(&func.stability); - self.print_external_id(func.external_id.as_deref()); - - match &func.kind { - FunctionKind::Constructor(_) => {} - FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => { - self.print_name_type(func.item_name(), TypeKind::FunctionMethod); - self.output.str(": "); - } - FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => { - self.print_name_type(func.item_name(), TypeKind::FunctionStatic); - self.output.str(": "); - self.output.keyword("static"); - self.output.str(" "); - } - FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => unreachable!(), - } - self.print_function(resolve, func)?; - self.output.semicolon(); - } - self.output.indent_end(); - - Ok(()) - } - - fn print_function(&mut self, resolve: &Resolve, func: &Function) -> Result<()> { - // Handle the `async` prefix if necessary - match &func.kind { - FunctionKind::AsyncFreestanding - | FunctionKind::AsyncMethod(_) - | FunctionKind::AsyncStatic(_) => { - self.output.keyword("async"); - self.output.str(" "); - } - _ => {} - } - - // Constructors are named slightly differently. - match &func.kind { - FunctionKind::Constructor(_) => { - self.output.keyword("constructor"); - self.output.str("("); - } - FunctionKind::Freestanding - | FunctionKind::AsyncFreestanding - | FunctionKind::Method(_) - | FunctionKind::AsyncMethod(_) - | FunctionKind::Static(_) - | FunctionKind::AsyncStatic(_) => { - self.output.keyword("func"); - self.output.str("("); - } - } - - // Methods don't print their `self` argument - let params_to_skip = match &func.kind { - FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => 1, - _ => 0, - }; - for (i, param) in func.params.iter().skip(params_to_skip).enumerate() { - if i > 0 { - self.output.str(", "); - } - self.print_name_param(¶m.name); - self.output.str(": "); - self.print_type_name(resolve, ¶m.ty)?; - } - self.output.str(")"); - - // shorthand constructors don't have their results printed - if func.is_constructor_shorthand(resolve) { - return Ok(()); - } - - if let Some(ty) = &func.result { - self.output.str(" -> "); - self.print_type_name(resolve, ty)?; - } - Ok(()) - } - - /// Prints the world `id` within `resolve`. - /// - /// This is a little tricky to preserve round-tripping that WIT wants. This - /// function inherently can't preserve ordering of imports because resource - /// functions aren't guaranteed to be all adjacent to the resource itself - /// they're attached to. That means that at the very least, when printing - /// resource functions, items may be printed out-of-order. - /// - /// To help solve this the printing here is kept in sync with WIT encoding - /// of worlds which is to print items in the order of: - /// - /// * Any imported interface. Ordering between interfaces is preserved. - /// * Any types, including resource functions on those types. Ordering - /// between types is preserved. - /// * Any functions, which may refer to those types. Ordering between - /// functions is preserved. - /// - /// This keeps things printed in a roughly topological fashion and makes - /// round-tripping a bit more reliable. - fn print_world(&mut self, resolve: &Resolve, id: WorldId) -> Result<()> { - let prev_items = mem::replace(&mut self.any_items, false); - let world = &resolve.worlds[id]; - let pkgid = world.package.unwrap(); - let mut types = Vec::new(); - let mut resource_funcs = HashMap::new(); - let mut function_imports_to_print = Vec::new(); - for (name, import) in world.imports.iter() { - match import { - WorldItem::Type { id, .. } => match name { - WorldKey::Name(s) => types.push((s.as_str(), *id)), - WorldKey::Interface(_) => unreachable!(), - }, - _ => { - if let WorldItem::Function(f) = import { - if let Some(id) = f.kind.resource() { - resource_funcs.entry(id).or_insert(Vec::new()).push(f); - continue; - } - function_imports_to_print.push((name, import)); - continue; - } - self.print_world_item(resolve, name, import, pkgid, "import")?; - // Don't put a blank line between imports, but count - // imports as having printed something so if anything comes - // after them then a blank line is printed after imports. - self.any_items = true; - } - } - } - self.print_types( - resolve, - TypeOwner::World(id), - types.into_iter(), - &resource_funcs, - )?; - - for (name, import) in function_imports_to_print { - self.print_world_item(resolve, name, import, pkgid, "import")?; - self.any_items = true; - } - if !world.exports.is_empty() { - self.new_item(); - } - for (name, export) in world.exports.iter() { - self.print_world_item(resolve, name, export, pkgid, "export")?; - } - self.any_items = prev_items; - Ok(()) - } - - fn print_world_item( - &mut self, - resolve: &Resolve, - name: &WorldKey, - item: &WorldItem, - cur_pkg: PackageId, - import_or_export_keyword: &str, - ) -> Result<()> { - // Print docs for this import/export statement. For interfaces, prefer - // the docs attached to the statement itself (`WorldItem::Interface`'s - // `docs`); for an inline `import x: interface { .. }` with no statement - // docs fall back to the interface definition's docs. - let docs = match item { - WorldItem::Interface { id, docs, .. } => { - if docs.contents.is_some() { - Some(docs) - } else if matches!(name, WorldKey::Name(_)) { - Some(&resolve.interfaces[*id].docs) - } else { - None - } - } - WorldItem::Function(f) => Some(&f.docs), - // Types are handled separately - WorldItem::Type { .. } => unreachable!(), - }; - if let Some(docs) = docs { - self.print_docs(docs); - } - - self.print_stability(item.stability(resolve)); - self.print_external_id(resolve.external_id_value(name, item).as_deref()); - self.output.keyword(import_or_export_keyword); - self.output.str(" "); - match name { - WorldKey::Name(name) => { - match item { - WorldItem::Interface { id, .. } => { - self.print_name_type(name, TypeKind::Other); - self.output.str(": "); - if resolve.interfaces[*id].name.is_none() { - // `import label: interface { .. }` syntax - self.output.keyword("interface"); - self.output.indent_start(); - self.print_interface(resolve, *id)?; - self.output.indent_end(); - } else { - // `import label: use-path;` syntax - self.print_path_to_interface(resolve, *id, cur_pkg)?; - self.output.semicolon(); - } - } - WorldItem::Function(f) => { - self.print_name_type(&f.name, TypeKind::Other); - self.output.str(": "); - self.print_function(resolve, f)?; - self.output.semicolon(); - } - // Types are handled separately - WorldItem::Type { .. } => unreachable!(), - } - } - WorldKey::Interface(id) => { - match item { - WorldItem::Interface { id: id2, .. } => assert_eq!(id, id2), - _ => unreachable!(), - } - self.print_path_to_interface(resolve, *id, cur_pkg)?; - self.output.semicolon(); - } - } - Ok(()) - } - - fn print_path_to_interface( - &mut self, - resolve: &Resolve, - interface: InterfaceId, - cur_pkg: PackageId, - ) -> Result<()> { - let iface = &resolve.interfaces[interface]; - if iface.package == Some(cur_pkg) { - self.print_name_type(iface.name.as_ref().unwrap(), TypeKind::InterfacePath); - } else { - let pkg = &resolve.packages[iface.package.unwrap()].name; - self.print_name_type(&pkg.namespace, TypeKind::NamespacePath); - self.output.str(":"); - self.print_name_type(&pkg.name, TypeKind::PackageNamePath); - self.output.str("/"); - self.print_name_type(iface.name.as_ref().unwrap(), TypeKind::InterfacePath); - if let Some(version) = &pkg.version { - self.print_name_type(&format!("@{version}"), TypeKind::VersionPath); - } - } - Ok(()) - } - - /// Print the name of type `ty`. - pub fn print_type_name(&mut self, resolve: &Resolve, ty: &Type) -> Result<()> { - match ty { - Type::Bool => self.output.ty("bool", TypeKind::BuiltIn), - Type::U8 => self.output.ty("u8", TypeKind::BuiltIn), - Type::U16 => self.output.ty("u16", TypeKind::BuiltIn), - Type::U32 => self.output.ty("u32", TypeKind::BuiltIn), - Type::U64 => self.output.ty("u64", TypeKind::BuiltIn), - Type::S8 => self.output.ty("s8", TypeKind::BuiltIn), - Type::S16 => self.output.ty("s16", TypeKind::BuiltIn), - Type::S32 => self.output.ty("s32", TypeKind::BuiltIn), - Type::S64 => self.output.ty("s64", TypeKind::BuiltIn), - Type::F32 => self.output.ty("f32", TypeKind::BuiltIn), - Type::F64 => self.output.ty("f64", TypeKind::BuiltIn), - Type::Char => self.output.ty("char", TypeKind::BuiltIn), - Type::String => self.output.ty("string", TypeKind::BuiltIn), - Type::ErrorContext => self.output.ty("error-context", TypeKind::BuiltIn), - - Type::Id(id) => { - let ty = &resolve.types[*id]; - if let Some(name) = &ty.name { - self.print_name_type(name, TypeKind::Other); - return Ok(()); - } - - match &ty.kind { - TypeDefKind::Handle(h) => { - self.print_handle_type(resolve, h, false)?; - } - TypeDefKind::Resource => { - bail!("resolve has an unnamed resource type"); - } - TypeDefKind::Tuple(t) => { - self.print_tuple_type(resolve, t)?; - } - TypeDefKind::Option(t) => { - self.print_option_type(resolve, t)?; - } - TypeDefKind::Result(t) => { - self.print_result_type(resolve, t)?; - } - TypeDefKind::Record(_) => { - bail!("resolve has an unnamed record type"); - } - TypeDefKind::Flags(_) => { - bail!("resolve has unnamed flags type") - } - TypeDefKind::Enum(_) => { - bail!("resolve has unnamed enum type") - } - TypeDefKind::Variant(_) => { - bail!("resolve has unnamed variant type") - } - TypeDefKind::List(ty) => { - self.output.ty("list", TypeKind::BuiltIn); - self.output.generic_args_start(); - self.print_type_name(resolve, ty)?; - self.output.generic_args_end(); - } - TypeDefKind::Map(key_ty, value_ty) => { - self.output.ty("map", TypeKind::BuiltIn); - self.output.generic_args_start(); - self.print_type_name(resolve, key_ty)?; - self.output.str(", "); - self.print_type_name(resolve, value_ty)?; - self.output.generic_args_end(); - } - TypeDefKind::FixedLengthList(ty, size) => { - self.output.ty("list", TypeKind::BuiltIn); - self.output.generic_args_start(); - self.print_type_name(resolve, ty)?; - self.output.push_str(&format!(", {}", *size)); - self.output.generic_args_end(); - } - TypeDefKind::Type(ty) => self.print_type_name(resolve, ty)?, - TypeDefKind::Future(ty) => { - if let Some(ty) = ty { - self.output.push_str("future<"); - self.print_type_name(resolve, ty)?; - self.output.push_str(">"); - } else { - self.output.push_str("future"); - } - } - TypeDefKind::Stream(ty) => { - if let Some(ty) = ty { - self.output.push_str("stream<"); - self.print_type_name(resolve, ty)?; - self.output.push_str(">"); - } else { - self.output.push_str("stream"); - } - } - TypeDefKind::Unknown => unreachable!(), - } - } - } - - Ok(()) - } - - fn print_handle_type( - &mut self, - resolve: &Resolve, - handle: &Handle, - force_handle_type_printed: bool, - ) -> Result<()> { - match handle { - Handle::Own(ty) => { - let ty = &resolve.types[*ty]; - if force_handle_type_printed { - self.output.ty("own", TypeKind::BuiltIn); - self.output.generic_args_start(); - } - self.print_name_type( - ty.name - .as_ref() - .ok_or_else(|| anyhow!("unnamed resource type"))?, - TypeKind::Resource, - ); - if force_handle_type_printed { - self.output.generic_args_end(); - } - } - - Handle::Borrow(ty) => { - self.output.ty("borrow", TypeKind::BuiltIn); - self.output.generic_args_start(); - let ty = &resolve.types[*ty]; - self.print_name_type( - ty.name - .as_ref() - .ok_or_else(|| anyhow!("unnamed resource type"))?, - TypeKind::Resource, - ); - self.output.generic_args_end(); - } - } - - Ok(()) - } - - fn print_tuple_type(&mut self, resolve: &Resolve, tuple: &Tuple) -> Result<()> { - self.output.ty("tuple", TypeKind::BuiltIn); - self.output.generic_args_start(); - for (i, ty) in tuple.types.iter().enumerate() { - if i > 0 { - self.output.str(", "); - } - self.print_type_name(resolve, ty)?; - } - self.output.generic_args_end(); - - Ok(()) - } - - fn print_option_type(&mut self, resolve: &Resolve, payload: &Type) -> Result<()> { - self.output.ty("option", TypeKind::BuiltIn); - self.output.generic_args_start(); - self.print_type_name(resolve, payload)?; - self.output.generic_args_end(); - Ok(()) - } - - fn print_result_type(&mut self, resolve: &Resolve, result: &Result_) -> Result<()> { - match result { - Result_ { - ok: Some(ok), - err: Some(err), - } => { - self.output.ty("result", TypeKind::BuiltIn); - self.output.generic_args_start(); - self.print_type_name(resolve, ok)?; - self.output.str(", "); - self.print_type_name(resolve, err)?; - self.output.generic_args_end(); - } - Result_ { - ok: None, - err: Some(err), - } => { - self.output.ty("result", TypeKind::BuiltIn); - self.output.generic_args_start(); - self.output.str("_, "); - self.print_type_name(resolve, err)?; - self.output.generic_args_end(); - } - Result_ { - ok: Some(ok), - err: None, - } => { - self.output.ty("result", TypeKind::BuiltIn); - self.output.generic_args_start(); - self.print_type_name(resolve, ok)?; - self.output.generic_args_end(); - } - Result_ { - ok: None, - err: None, - } => { - self.output.ty("result", TypeKind::BuiltIn); - } - } - Ok(()) - } - - fn declare_type(&mut self, resolve: &Resolve, ty: &Type) -> Result<()> { - match ty { - Type::Bool - | Type::U8 - | Type::U16 - | Type::U32 - | Type::U64 - | Type::S8 - | Type::S16 - | Type::S32 - | Type::S64 - | Type::F32 - | Type::F64 - | Type::Char - | Type::String - | Type::ErrorContext => return Ok(()), - - Type::Id(id) => { - let ty = &resolve.types[*id]; - match &ty.kind { - TypeDefKind::Handle(h) => { - self.declare_handle(resolve, ty.name.as_deref(), h)? - } - TypeDefKind::Resource => panic!("resources should be processed separately"), - TypeDefKind::Record(r) => { - self.declare_record(resolve, ty.name.as_deref(), r)? - } - TypeDefKind::Tuple(t) => self.declare_tuple(resolve, ty.name.as_deref(), t)?, - TypeDefKind::Flags(f) => self.declare_flags(ty.name.as_deref(), f)?, - TypeDefKind::Variant(v) => { - self.declare_variant(resolve, ty.name.as_deref(), v)? - } - TypeDefKind::Option(t) => { - self.declare_option(resolve, ty.name.as_deref(), t)? - } - TypeDefKind::Result(r) => { - self.declare_result(resolve, ty.name.as_deref(), r)? - } - TypeDefKind::Enum(e) => self.declare_enum(ty.name.as_deref(), e)?, - TypeDefKind::List(inner) => { - self.declare_list(resolve, ty.name.as_deref(), inner)? - } - TypeDefKind::Map(key, value) => { - self.declare_map(resolve, ty.name.as_deref(), key, value)? - } - TypeDefKind::FixedLengthList(inner, size) => { - self.declare_fixed_length_list(resolve, ty.name.as_deref(), inner, *size)? - } - TypeDefKind::Type(inner) => match ty.name.as_deref() { - Some(name) => { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::TypeName); - self.output.str(" = "); - self.print_type_name(resolve, inner)?; - self.output.semicolon(); - } - None => bail!("unnamed type in document"), - }, - TypeDefKind::Future(inner) => { - self.declare_future(resolve, ty.name.as_deref(), inner.as_ref())? - } - TypeDefKind::Stream(inner) => { - self.declare_stream(resolve, ty.name.as_deref(), inner.as_ref())? - } - TypeDefKind::Unknown => unreachable!(), - } - } - } - Ok(()) - } - - fn declare_handle( - &mut self, - resolve: &Resolve, - name: Option<&str>, - handle: &Handle, - ) -> Result<()> { - match name { - Some(name) => { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Resource); - self.output.str(" = "); - // Note that the `true` here forces owned handles to be printed - // as `own`. The purpose of this is because `type a = b`, if - // `b` is a resource, is encoded differently as `type a = - // own`. By forcing a handle to be printed here it's staying - // true to what's in the WIT document. - self.print_handle_type(resolve, handle, true)?; - self.output.semicolon(); - - Ok(()) - } - None => bail!("document has unnamed handle type"), - } - } - - fn declare_record( - &mut self, - resolve: &Resolve, - name: Option<&str>, - record: &Record, - ) -> Result<()> { - match name { - Some(name) => { - self.output.keyword("record"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Record); - self.output.indent_start(); - for field in &record.fields { - self.print_docs(&field.docs); - self.print_name_param(&field.name); - self.output.str(": "); - self.print_type_name(resolve, &field.ty)?; - self.output.str(","); - self.output.newline(); - } - self.output.indent_end(); - Ok(()) - } - None => bail!("document has unnamed record type"), - } - } - - fn declare_tuple( - &mut self, - resolve: &Resolve, - name: Option<&str>, - tuple: &Tuple, - ) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Tuple); - self.output.str(" = "); - self.print_tuple_type(resolve, tuple)?; - self.output.semicolon(); - } - Ok(()) - } - - fn declare_flags(&mut self, name: Option<&str>, flags: &Flags) -> Result<()> { - match name { - Some(name) => { - self.output.keyword("flags"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Flags); - self.output.indent_start(); - for flag in &flags.flags { - self.print_docs(&flag.docs); - self.print_name_case(&flag.name); - self.output.str(","); - self.output.newline(); - } - self.output.indent_end(); - } - None => bail!("document has unnamed flags type"), - } - Ok(()) - } - - fn declare_variant( - &mut self, - resolve: &Resolve, - name: Option<&str>, - variant: &Variant, - ) -> Result<()> { - let name = match name { - Some(name) => name, - None => bail!("document has unnamed variant type"), - }; - self.output.keyword("variant"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Variant); - self.output.indent_start(); - for case in &variant.cases { - self.print_docs(&case.docs); - self.print_name_case(&case.name); - if let Some(ty) = case.ty { - self.output.str("("); - self.print_type_name(resolve, &ty)?; - self.output.str(")"); - } - self.output.str(","); - self.output.newline(); - } - self.output.indent_end(); - Ok(()) - } - - fn declare_option( - &mut self, - resolve: &Resolve, - name: Option<&str>, - payload: &Type, - ) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Option); - self.output.str(" = "); - self.print_option_type(resolve, payload)?; - self.output.semicolon(); - } - Ok(()) - } - - fn declare_result( - &mut self, - resolve: &Resolve, - name: Option<&str>, - result: &Result_, - ) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Result); - self.output.str(" = "); - self.print_result_type(resolve, result)?; - self.output.semicolon(); - } - Ok(()) - } - - fn declare_enum(&mut self, name: Option<&str>, enum_: &Enum) -> Result<()> { - let name = match name { - Some(name) => name, - None => bail!("document has unnamed enum type"), - }; - self.output.keyword("enum"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Enum); - self.output.indent_start(); - for case in &enum_.cases { - self.print_docs(&case.docs); - self.print_name_case(&case.name); - self.output.str(","); - self.output.newline(); - } - self.output.indent_end(); - Ok(()) - } - - fn declare_list(&mut self, resolve: &Resolve, name: Option<&str>, ty: &Type) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::List); - self.output.str(" = "); - self.output.ty("list", TypeKind::BuiltIn); - self.output.str("<"); - self.print_type_name(resolve, ty)?; - self.output.str(">"); - self.output.semicolon(); - return Ok(()); - } - - Ok(()) - } - - fn declare_map( - &mut self, - resolve: &Resolve, - name: Option<&str>, - key_ty: &Type, - value_ty: &Type, - ) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Map); - self.output.str(" = "); - self.output.ty("map", TypeKind::BuiltIn); - self.output.str("<"); - self.print_type_name(resolve, key_ty)?; - self.output.str(", "); - self.print_type_name(resolve, value_ty)?; - self.output.str(">"); - self.output.semicolon(); - return Ok(()); - } - - Ok(()) - } - - fn declare_fixed_length_list( - &mut self, - resolve: &Resolve, - name: Option<&str>, - ty: &Type, - elements: u32, - ) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::List); - self.output.str(" = "); - self.output.ty("list", TypeKind::BuiltIn); - self.output.str("<"); - self.print_type_name(resolve, ty)?; - self.output.str(&format!(", {elements}")); - self.output.str(">"); - self.output.semicolon(); - return Ok(()); - } - - Ok(()) - } - - fn declare_stream( - &mut self, - resolve: &Resolve, - name: Option<&str>, - ty: Option<&Type>, - ) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Stream); - self.output.str(" = "); - self.output.ty("stream", TypeKind::BuiltIn); - if let Some(ty) = ty { - self.output.str("<"); - self.print_type_name(resolve, ty)?; - self.output.str(">"); - } - self.output.semicolon(); - } - - Ok(()) - } - - fn declare_future( - &mut self, - resolve: &Resolve, - name: Option<&str>, - ty: Option<&Type>, - ) -> Result<()> { - if let Some(name) = name { - self.output.keyword("type"); - self.output.str(" "); - self.print_name_type(name, TypeKind::Future); - self.output.str(" = "); - self.output.ty("future", TypeKind::BuiltIn); - if let Some(ty) = ty { - self.output.str("<"); - self.print_type_name(resolve, ty)?; - self.output.str(">"); - } - self.output.semicolon(); - } - - Ok(()) - } - - fn escape_name(name: &str) -> Cow<'_, str> { - if is_keyword(name) { - Cow::Owned(format!("%{name}")) - } else { - Cow::Borrowed(name) - } - } - - fn print_name_type(&mut self, name: &str, kind: TypeKind) { - self.output.ty(Self::escape_name(name).deref(), kind); - } - - fn print_name_param(&mut self, name: &str) { - self.output.param(Self::escape_name(name).deref()); - } - - fn print_name_case(&mut self, name: &str) { - self.output.case(Self::escape_name(name).deref()); - } - - fn print_docs(&mut self, docs: &Docs) { - if self.emit_docs { - if let Some(contents) = &docs.contents { - for line in contents.lines() { - self.output.doc(line); - } - } - } - } - - fn print_stability(&mut self, stability: &Stability) { - match stability { - Stability::Unknown => {} - Stability::Stable { since, deprecated } => { - self.output.keyword("@since"); - self.output.str("("); - self.output.keyword("version"); - self.output.str(" = "); - self.print_name_type(&since.to_string(), TypeKind::VersionAnnotation); - self.output.str(")"); - self.output.newline(); - if let Some(version) = deprecated { - self.output.keyword("@deprecated"); - self.output.str("("); - self.output.keyword("version"); - self.output.str(" = "); - self.print_name_type(&version.to_string(), TypeKind::VersionAnnotation); - self.output.str(")"); - self.output.newline(); - } - } - Stability::Unstable { - feature, - deprecated, - } => { - self.output.keyword("@unstable"); - self.output.str("("); - self.output.keyword("feature"); - self.output.str(" = "); - self.output.str(feature); - self.output.str(")"); - self.output.newline(); - if let Some(version) = deprecated { - self.output.keyword("@deprecated"); - self.output.str("("); - self.output.keyword("version"); - self.output.str(" = "); - self.print_name_type(&version.to_string(), TypeKind::VersionAnnotation); - self.output.str(")"); - self.output.newline(); - } - } - } - } - - fn print_external_id(&mut self, id: Option<&str>) { - let Some(id) = id else { - return; - }; - self.output.keyword("@external-id"); - self.output.str("(\""); - let mut buf = [0; 4]; - for c in id.chars() { - if c.is_ascii_alphanumeric() - || c == '-' - || c == '_' - || c == '.' - || c == '/' - || c == ':' - || c == ' ' - { - self.output.push_str(c.encode_utf8(&mut buf)); - continue; - } - match c { - '\\' => self.output.push_str("\\\\"), - '"' => self.output.push_str("\\\""), - '\n' => self.output.push_str("\\n"), - '\r' => self.output.push_str("\\r"), - '\t' => self.output.push_str("\\t"), - _ => { - self.output.push_str(&format!("\\u{{{:x}}}", c as u32)); - } - } - } - self.output.str("\")"); - self.output.newline(); - } -} - -fn is_keyword(name: &str) -> bool { - matches!( - name, - "use" - | "type" - | "func" - | "u8" - | "u16" - | "u32" - | "u64" - | "s8" - | "s16" - | "s32" - | "s64" - | "f32" - | "f64" - | "float32" - | "float64" - | "char" - | "resource" - | "record" - | "flags" - | "variant" - | "enum" - | "bool" - | "string" - | "option" - | "result" - | "future" - | "stream" - | "list" - | "own" - | "borrow" - | "_" - | "as" - | "from" - | "static" - | "interface" - | "tuple" - | "world" - | "import" - | "export" - | "package" - | "with" - | "include" - | "constructor" - | "error-context" - | "async" - | "map" - ) -} - -/// Trait defining visitor methods driven by [`WitPrinter`](WitPrinter). -/// -/// Some methods in this trait have default implementations. These default -/// implementations may rely on helper functions that are not -/// invoked directly by `WitPrinter`. -pub trait Output { - /// Push a string slice into a buffer or an output. - /// - /// Parameter `src` can contain punctuation characters, and must be escaped - /// when outputting to languages like HTML. - /// Helper function used exclusively by the default implementations of trait methods. - /// This function is not called directly by `WitPrinter`. - /// When overriding all the trait methods, users do not need to handle this function. - fn push_str(&mut self, src: &str); - - /// Set the appropriate indentation. - /// - /// Helper function used exclusively by the default implementations of trait methods. - /// This function is not called directly by `WitPrinter`. - /// When overriding all the trait methods, users do not need to handle this function. - fn indent_if_needed(&mut self) -> bool; - - /// Start of indentation. In WIT this represents ` {\n`. - fn indent_start(&mut self); - - /// End of indentation. In WIT this represents `}\n`. - fn indent_end(&mut self); - - /// This method is designed to be used only by the default methods of this trait. - /// Called only from the default implementation functions of this trait. - fn indent_and_print(&mut self, src: &str) { - assert!(!src.contains('\n')); - let indented = self.indent_if_needed(); - if indented && src.starts_with(' ') { - panic!("cannot add a space at the beginning of a line"); - } - self.push_str(src); - } - - /// A newline is added. - fn newline(&mut self); - - /// A keyword is added. Keywords are hardcoded strings from `[a-z]`, but can start with `@` - /// when printing a [Feature Gate](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#feature-gates) - fn keyword(&mut self, src: &str) { - self.indent_and_print(src); - } - - /// A type is added. - fn ty(&mut self, src: &str, _kind: TypeKind) { - self.indent_and_print(src); - } - - /// A parameter name of a function, record or a named return is added. - fn param(&mut self, src: &str) { - self.indent_and_print(src); - } - - /// A case belonging to a variant, enum or flags is added. - fn case(&mut self, src: &str) { - self.indent_and_print(src); - } - - /// Generic argument section starts. In WIT this represents the `<` character. - fn generic_args_start(&mut self) { - assert!( - !self.indent_if_needed(), - "`generic_args_start` is never called after newline" - ); - self.push_str("<"); - } - - /// Generic argument section ends. In WIT this represents the '>' character. - fn generic_args_end(&mut self) { - assert!( - !self.indent_if_needed(), - "`generic_args_end` is never called after newline" - ); - self.push_str(">"); - } - - /// Called when a single documentation line is added. - /// The `doc` parameter starts with `///` omitted, and can be an empty string. - fn doc(&mut self, doc: &str) { - assert!(!doc.contains('\n')); - self.indent_if_needed(); - self.push_str("///"); - if !doc.is_empty() { - self.push_str(" "); - self.push_str(doc); - } - self.newline(); - } - - /// A semicolon is added. - fn semicolon(&mut self) { - assert!( - !self.indent_if_needed(), - "`semicolon` is never called after newline" - ); - self.push_str(";"); - self.newline(); - } - - /// Any string that does not have a specialized function is added. - /// Parameter `src` can contain punctuation characters, and must be escaped - /// when outputting to languages like HTML. - fn str(&mut self, src: &str) { - self.indent_and_print(src); - } -} - -/// Represents the different kinds of types that can be encountered while -/// visiting a WIT file. -/// -/// Each variant refers to the name of the respective element (e.g., function, type, or namespace), -/// not the entire declaration. -#[non_exhaustive] -#[derive(Clone, Copy, Debug)] -pub enum TypeKind { - /// A built-in type, such as "list" or "option". - BuiltIn, - /// An enumeration type name. - Enum, - /// An error-context type name. - ErrorContext, - /// A flags type name. - Flags, - /// A freestanding function name, not associated with any specific type or namespace. - /// For example, "myfunc" in `myfunc: func() -> string;`. - FunctionFreestanding, - /// A method, associated with a resource. - FunctionMethod, - /// A static function, associated with a resource. - FunctionStatic, - /// A future type name. - Future, - /// An interface declaration name. - InterfaceDeclaration, - /// An interface name when printing a path, for example in `use`. - InterfacePath, - /// A list type name. - List, - /// A map type name. - Map, - /// A namespace declaration. - NamespaceDeclaration, - /// A namespace when printing a path, for example in `use`. - NamespacePath, - /// An option type name. - Option, - /// A package name declaration. - PackageNameDeclaration, - /// A package name when printing a path, for example in `use`. - PackageNamePath, - /// A record type name. - Record, - /// A resource type name. - Resource, - /// A result type name. - Result, - /// A stream type name. - Stream, - /// A tuple type name. - Tuple, - /// A type alias. - TypeAlias, - /// An imported type name. - TypeImport, - /// A user-defined type name. - TypeName, - /// A variant type name. - Variant, - /// A version declaration. - VersionDeclaration, - /// A version when printing a path, for example in `use`. - VersionPath, - /// A version when printing stability annotations, for example in `@since` - VersionAnnotation, - /// A world declaration name. - WorldDeclaration, - /// A fallback for types that do not fit into any other category. - Other, -} - -/// Helper structure to help maintain an indentation level when printing source, -/// modeled after the support in `wit-bindgen-core`. Indentation is set to two spaces. -#[derive(Default)] -pub struct OutputToString { - indent: usize, - output: String, - // set to true after newline, then to false after first item is indented. - needs_indent: bool, -} - -impl Output for OutputToString { - fn push_str(&mut self, src: &str) { - self.output.push_str(src); - } - - fn indent_if_needed(&mut self) -> bool { - if self.needs_indent { - for _ in 0..self.indent { - // Indenting by two spaces. - self.output.push_str(" "); - } - self.needs_indent = false; - true - } else { - false - } - } - - fn indent_start(&mut self) { - assert!( - !self.needs_indent, - "`indent_start` is never called after newline" - ); - self.output.push_str(" {"); - self.indent += 1; - self.newline(); - } - - fn indent_end(&mut self) { - // Note that a `saturating_sub` is used here to prevent a panic - // here in the case of invalid code being generated in debug - // mode. It's typically easier to debug those issues through - // looking at the source code rather than getting a panic. - self.indent = self.indent.saturating_sub(1); - self.indent_if_needed(); - self.output.push('}'); - self.newline(); - } - - fn newline(&mut self) { - self.output.push('\n'); - self.needs_indent = true; - } -} - -impl From for String { - fn from(output: OutputToString) -> String { - output.output - } -} - -impl Display for OutputToString { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.output.fmt(f) - } -} diff --git a/vendor/wit-component/src/semver_check.rs b/vendor/wit-component/src/semver_check.rs deleted file mode 100644 index 8fb4cb1c..00000000 --- a/vendor/wit-component/src/semver_check.rs +++ /dev/null @@ -1,113 +0,0 @@ -use crate::{ - ComponentEncoder, StringEncoding, dummy_module, embed_component_metadata, - encoding::encode_world, -}; -use anyhow::{Context, Result, bail}; -use wasm_encoder::{ComponentBuilder, ComponentExportKind, ComponentTypeRef}; -use wasmparser::Validator; -use wit_parser::{ManglingAndAbi, Resolve, WorldId}; - -/// Tests whether `new` is a semver-compatible upgrade from the world `prev`. -/// -/// This function is will test whether a WIT-level semver-compatible predicate -/// holds. Internally this will ignore all versions associated with packages and -/// will instead test for structural equality between types and such. For -/// example `new` is allowed to have more imports and fewer exports, but types -/// and such must have the exact same structure otherwise (e.g. function params, -/// record fields, etc). -// -// NB: the general implementation strategy here is similar to the `targets` -// function where components are synthesized and we effectively rely on -// wasmparser to figure out everything for us. Specifically what happens is: -// -// 1. A dummy component representing `prev` is created. -// 2. A component importing a component of shape `new` is created. -// 3. The component from (2) is instantiated with the component from (1). -// -// If that all type-checks and is valid then the semver compatible predicate -// holds. Otherwise something has gone wrong. -// -// Note that this does not produce great error messages, so this implementation -// likely wants to be improved in the future. -pub fn semver_check(mut resolve: Resolve, prev: WorldId, new: WorldId) -> Result<()> { - // First up clear out all version information. This is required to ensure - // that the strings line up for wasmparser's validation which does exact - // string matching. - // - // This can leave `resolve` in a weird state which is why this function - // takes ownership of `resolve`. Specifically the internal maps for package - // names won't be updated and additionally this could leave two packages - // with the same name (e.g. no version) which would be a bit odd. - // - // NB: this will probably cause confusing errors below if a world imports - // two versions of a package's interfaces. I think that'll result in weird - // wasmparser validation errors as there would be two imports of the same - // name for example. - for (_id, pkg) in resolve.packages.iter_mut() { - pkg.name.version = None; - } - - let old_pkg_id = resolve.worlds[prev] - .package - .context("old world not in named package")?; - let old_pkg_name = &resolve.packages[old_pkg_id].name; - let new_pkg_id = resolve.worlds[new] - .package - .context("new world not in named package")?; - let new_pkg_name = &resolve.packages[new_pkg_id].name; - if old_pkg_name != new_pkg_name { - bail!( - "the old world is in package {old_pkg_name}, which is not the same as the new world, which is in package {new_pkg_name}", - ) - } - - // Component that will be validated at the end. - let mut root_component = ComponentBuilder::default(); - - // (1) above - create a dummy component which has the shape of `prev`. - let mut prev_as_module = dummy_module(&resolve, prev, ManglingAndAbi::Standard32); - embed_component_metadata(&mut prev_as_module, &resolve, prev, StringEncoding::UTF8) - .context("failed to embed component metadata")?; - let prev_as_component = ComponentEncoder::default() - .module(&prev_as_module) - .context("failed to register previous world encoded as a module")? - .encode() - .context("failed to encode previous world as a component")?; - let component_to_test_idx = root_component.component_raw(None, &prev_as_component); - - // (2) above - create a component which imports a component of the shape of - // `new`. - let test_component_idx = { - let component_ty = - encode_world(&resolve, new).context("failed to encode the new world as a type")?; - let mut component = ComponentBuilder::default(); - let component_ty_idx = component.type_component(None, &component_ty); - component.import( - &resolve.worlds[new].name, - ComponentTypeRef::Component(component_ty_idx), - ); - root_component.component(None, component) - }; - - // (3) Instantiate the component from (2) with the component to test from (1). - root_component.instantiate( - None, - test_component_idx, - [( - resolve.worlds[new].name.clone(), - ComponentExportKind::Component, - component_to_test_idx, - )], - ); - let bytes = root_component.finish(); - - // The final step is validating that this component is indeed valid. If any - // error message is produced here an attempt is made to make it more - // understandable but there's only but so good these errors can be with this - // strategy. - Validator::new() - .validate_all(&bytes) - .context("new world is not semver-compatible with the previous world")?; - - Ok(()) -} diff --git a/vendor/wit-component/src/targets.rs b/vendor/wit-component/src/targets.rs deleted file mode 100644 index 4212b018..00000000 --- a/vendor/wit-component/src/targets.rs +++ /dev/null @@ -1,44 +0,0 @@ -use crate::encoding::encode_world; -use anyhow::{Context, Result}; -use wasm_encoder::{ComponentBuilder, ComponentExportKind, ComponentTypeRef}; -use wasmparser::{Validator, WasmFeatures}; -use wit_parser::{Resolve, WorldId}; - -/// This function checks whether `component_to_test` correctly conforms to the world specified. -/// It does so by instantiating a generated component that imports a component instance with -/// the component type as described by the "target" world. -pub fn targets(resolve: &Resolve, world: WorldId, component_to_test: &[u8]) -> Result<()> { - let mut root_component = ComponentBuilder::default(); - - // (1) Embed the component to test. - let component_to_test_idx = root_component.component_raw(None, component_to_test); - - // (2) Encode the world to a component type and embed a new component which - // imports the encoded component type. - let test_component_idx = { - let component_ty = encode_world(resolve, world)?; - let mut component = ComponentBuilder::default(); - let component_ty_idx = component.type_component(None, &component_ty); - component.import( - &resolve.worlds[world].name, - ComponentTypeRef::Component(component_ty_idx), - ); - root_component.component(None, component) - }; - - // (3) Instantiate the component from (2) with the component to test from (1). - let args: Vec<(String, ComponentExportKind, u32)> = vec![( - resolve.worlds[world].name.clone(), - ComponentExportKind::Component, - component_to_test_idx, - )]; - root_component.instantiate(None, test_component_idx, args); - - let bytes = root_component.finish(); - - Validator::new_with_features(WasmFeatures::all()) - .validate_all(&bytes) - .context("failed to validate encoded bytes")?; - - Ok(()) -} diff --git a/vendor/wit-component/src/validation.rs b/vendor/wit-component/src/validation.rs deleted file mode 100644 index 0b611b87..00000000 --- a/vendor/wit-component/src/validation.rs +++ /dev/null @@ -1,2868 +0,0 @@ -use crate::encoding::{Instance, Item, LibraryInfo, MainOrAdapter, ModuleImportMap}; -use crate::{ComponentEncoder, StringEncoding}; -use anyhow::{Context, Result, anyhow, bail}; -use indexmap::{IndexMap, IndexSet, map::Entry}; -use std::fmt; -use std::hash::Hash; -use std::mem; -use wasm_encoder::ExportKind; -use wasmparser::names::{ComponentName, ComponentNameKind}; -use wasmparser::{ - Encoding, ExternalKind, FuncType, MemoryType, Parser, Payload, TypeRef, ValType, ValidPayload, - Validator, WasmFeatures, types::TypesRef, -}; -use wit_parser::{ - Function, InterfaceId, PackageName, Resolve, Type, TypeDefKind, TypeId, World, WorldId, - WorldItem, WorldKey, - abi::{AbiVariant, WasmSignature, WasmType}, -}; - -fn wasm_sig_to_func_type(signature: WasmSignature) -> FuncType { - fn from_wasm_type(ty: &WasmType) -> ValType { - match ty { - WasmType::I32 => ValType::I32, - WasmType::I64 => ValType::I64, - WasmType::F32 => ValType::F32, - WasmType::F64 => ValType::F64, - WasmType::Pointer => ValType::I32, - WasmType::PointerOrI64 => ValType::I64, - WasmType::Length => ValType::I32, - } - } - - FuncType::new( - signature.params.iter().map(from_wasm_type), - signature.results.iter().map(from_wasm_type), - ) -} - -/// Metadata about a validated module and what was found internally. -/// -/// This structure houses information about `imports` and `exports` to the -/// module. Each of these specialized types contains "connection" information -/// between a module's imports/exports and the WIT or component-level constructs -/// they correspond to. - -#[derive(Default)] -pub struct ValidatedModule { - /// Information about a module's imports. - pub imports: ImportMap, - - /// Information about a module's exports. - pub exports: ExportMap, -} - -impl ValidatedModule { - fn new( - encoder: &ComponentEncoder, - bytes: &[u8], - exports: &IndexSet, - import_map: Option<&ModuleImportMap>, - info: Option<&LibraryInfo>, - ) -> Result { - let mut validator = Validator::new_with_features(WasmFeatures::all()); - let mut ret = ValidatedModule::default(); - - for payload in Parser::new(0).parse_all(bytes) { - let payload = payload?; - if let ValidPayload::End(_) = validator.payload(&payload)? { - break; - } - - let types = validator.types(0).unwrap(); - - match payload { - Payload::Version { encoding, .. } if encoding != Encoding::Module => { - bail!("data is not a WebAssembly module"); - } - Payload::ImportSection(s) => { - for import in s.into_imports() { - let import = import?; - ret.imports.add(import, encoder, import_map, info, types)?; - } - } - Payload::ExportSection(s) => { - for export in s { - let export = export?; - ret.exports.add(export, encoder, &exports, types)?; - } - } - _ => continue, - } - } - - ret.exports.validate(encoder, exports)?; - - Ok(ret) - } -} - -/// Metadata information about a module's imports. -/// -/// This structure maintains the connection between component model "things" and -/// core wasm "things" by ensuring that all imports to the core wasm module are -/// classified by the `Import` enumeration. -#[derive(Default)] -pub struct ImportMap { - /// The first level of the map here is the module namespace of the import - /// and the second level of the map is the field namespace. The item is then - /// how the import is satisfied. - names: IndexMap, - - /// Cache for the last-inserted `MainModuleMemory` into `names` - imported_memory: Option, -} - -pub enum ImportInstance { - /// This import is satisfied by an entire instance of another - /// adapter/module. - Whole(MainOrAdapter), - - /// This import is satisfied by filling out each name possibly differently. - Names(IndexMap), -} - -/// Represents metadata about a `stream` or `future` type for a specific -/// payload type `T`. -/// -/// Currently, the name mangling scheme we use to represent `stream` and -/// `future` intrinsics as core module function imports refers to a specific -/// `stream` or `future` type by naming an imported or exported component -/// function which has that type as a parameter or return type (where the -/// specific type is referred to using an ordinal numbering scheme). Not only -/// does this approach unambiguously indicate the type of interest, but it -/// allows us to reuse the `realloc`, string encoding, memory, etc. used by that -/// function when emitting intrinsic declarations. -/// -/// TODO: Rather than reusing the same canon opts as the function in which the -/// type appears, consider encoding them in the name mangling stream on an -/// individual basis, similar to how we encode `error-context.*` built-in -/// imports. -#[derive(Debug, Eq, PartialEq, Clone, Hash)] -pub struct PayloadInfo { - /// The original, mangled import name used to import this built-in - /// (currently used only for hashing and debugging). - pub name: String, - /// The resolved type id for the `stream` or `future` type of interest. - /// - /// If `Unit{Future,Stream}` this means that it's a "unit" payload or has no associated - /// type being sent. - pub ty: PayloadType, - /// The world key representing the import or export context of `function`. - pub key: WorldKey, - /// The interface that `function` was imported from or exported in, if any. - pub interface: Option, - /// Whether `function` is being imported or exported. - /// - /// This may affect how we emit the declaration of the built-in, e.g. if the - /// payload type is an exported resource. - pub imported: bool, -} - -/// The type of future/stream referenced by a `PayloadInfo` -#[derive(Debug, Eq, PartialEq, Clone, Hash)] -pub enum PayloadType { - /// This is a future or stream located in a `Resolve` where `id` points to - /// either of `TypeDefKind::{Future, Stream}`. - Type { - id: TypeId, - /// The component-level function import or export where the type - /// appeared as a parameter or result type. - function: String, - }, - /// This is a `future` (no type) - UnitFuture, - /// This is a `stream` (no type) - UnitStream, -} - -impl PayloadInfo { - /// Returns the payload type that this future/stream type is using. - pub fn payload(&self, resolve: &Resolve) -> Option { - let id = match self.ty { - PayloadType::Type { id, .. } => id, - PayloadType::UnitFuture | PayloadType::UnitStream => return None, - }; - match resolve.types[id].kind { - TypeDefKind::Future(payload) | TypeDefKind::Stream(payload) => payload, - _ => unreachable!(), - } - } -} - -/// The different kinds of items that a module or an adapter can import. -/// -/// This is intended to be an exhaustive definition of what can be imported into -/// core modules within a component that wit-component supports. This doesn't -/// get down to the level of storing any idx numbers; at its most specific, it -/// gives a name. -#[derive(Debug, Clone)] -pub enum Import { - /// A top-level world function, with the name provided here, is imported - /// into the module. - WorldFunc(WorldKey, String, AbiVariant), - - /// An interface's function is imported into the module. - /// - /// The `WorldKey` here is the name of the interface in the world in - /// question. The `InterfaceId` is the interface that was imported from and - /// `String` is the WIT name of the function. - InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant), - - /// An imported resource's destructor is imported. - /// - /// The key provided indicates whether it's for the top-level types of the - /// world (`None`) or an interface (`Some` with the name of the interface). - /// The `TypeId` is what resource is being dropped. - ImportedResourceDrop(WorldKey, Option, TypeId), - - /// A `canon resource.drop` intrinsic for an exported item is being - /// imported. - /// - /// This lists the key of the interface that's exporting the resource plus - /// the id within that interface. - ExportedResourceDrop(WorldKey, TypeId), - - /// A `canon resource.new` intrinsic for an exported item is being - /// imported. - /// - /// This lists the key of the interface that's exporting the resource plus - /// the id within that interface. - ExportedResourceNew(WorldKey, TypeId), - - /// A `canon resource.rep` intrinsic for an exported item is being - /// imported. - /// - /// This lists the key of the interface that's exporting the resource plus - /// the id within that interface. - ExportedResourceRep(WorldKey, TypeId), - - /// An export of an adapter is being imported with the specified type. - /// - /// This is used for when the main module imports an adapter function. The - /// adapter name and function name match the module's own import, and the - /// type must match that listed here. - AdapterExport { - adapter: String, - func: String, - ty: FuncType, - }, - - /// An adapter is importing the memory of the main module. - /// - /// (should be combined with `MainModuleExport` below one day) - MainModuleMemory(MemoryType), - - /// An adapter is importing an arbitrary item from the main module. - MainModuleExport { name: String, kind: ExportKind }, - - /// An arbitrary item from either the main module or an adapter is being - /// imported. - /// - /// (should probably subsume `MainModule*` and maybe `AdapterExport` above - /// one day. - Item(Item), - - /// A `canon task.return` intrinsic for an exported function. - /// - /// This allows an exported function to return a value and then continue - /// running. - /// - /// As of this writing, only async-lifted exports use `task.return`, but the - /// plan is to also support it for sync-lifted exports in the future as - /// well. - ExportedTaskReturn(WorldKey, Option, Function), - - /// A `canon task.cancel` intrinsic for an exported function. - /// - /// This allows an exported function to acknowledge a `CANCELLED` event. - ExportedTaskCancel, - - /// The `context.get` intrinsic for the nth slot of storage. - ContextGet { - /// The type of the slot (`i32` or `i64`). - ty: ValType, - /// The index of the storage slot. - slot: u32, - }, - /// The `context.set` intrinsic for the nth slot of storage. - ContextSet { - /// The type of the slot (`i32` or `i64`). - ty: ValType, - /// The index of the storage slot. - slot: u32, - }, - - /// The `__wasm_get_tls_base` function that LLVM emits to read the base - /// pointer of this module's thread-local storage. - /// - /// Unlike [`Import::ContextGet`] this is not tied to a particular storage - /// mechanism: how it's satisfied depends on whether the program uses - /// cooperative threading. See - /// `EncodingState::materialize_tls_base_import` for the details. - TlsBaseGet { - /// The type of the base pointer (`i32` or `i64`). - ty: ValType, - }, - - /// The `__wasm_set_tls_base` counterpart to [`Import::TlsBaseGet`]. - TlsBaseSet { - /// The type of the base pointer (`i32` or `i64`). - ty: ValType, - }, - - /// A `canon backpressure.inc` intrinsic. - BackpressureInc, - - /// A `canon backpressure.dec` intrinsic. - BackpressureDec, - - /// A `waitable-set.new` intrinsic. - WaitableSetNew, - - /// A `canon waitable-set.wait` intrinsic. - /// - /// This allows the guest to wait for any pending calls to async-lowered - /// imports and/or `stream` and `future` operations to complete without - /// unwinding the current Wasm stack. - WaitableSetWait { cancellable: bool }, - - /// A `canon waitable.poll` intrinsic. - /// - /// This allows the guest to check whether any pending calls to - /// async-lowered imports and/or `stream` and `future` operations have - /// completed without unwinding the current Wasm stack and without blocking. - WaitableSetPoll { cancellable: bool }, - - /// A `waitable-set.drop` intrinsic. - WaitableSetDrop, - - /// A `waitable.join` intrinsic. - WaitableJoin, - - /// A `canon subtask.drop` intrinsic. - /// - /// This allows the guest to release its handle to a completed subtask. - SubtaskDrop, - - /// A `canon subtask.cancel` intrinsic. - /// - /// This allows the guest to cancel an in-progress subtask. - SubtaskCancel { async_: bool }, - - /// A `canon stream.new` intrinsic. - /// - /// This allows the guest to create a new `stream` of the specified type. - StreamNew(PayloadInfo), - - /// A `canon stream.read` intrinsic. - /// - /// This allows the guest to read the next values (if any) from the specified - /// stream. - StreamRead { async_: bool, info: PayloadInfo }, - - /// A `canon stream.write` intrinsic. - /// - /// This allows the guest to write one or more values to the specified - /// stream. - StreamWrite { async_: bool, info: PayloadInfo }, - - /// A `canon stream.cancel-read` intrinsic. - /// - /// This allows the guest to cancel a pending read it initiated earlier (but - /// which may have already partially or entirely completed). - StreamCancelRead { info: PayloadInfo, async_: bool }, - - /// A `canon stream.cancel-write` intrinsic. - /// - /// This allows the guest to cancel a pending write it initiated earlier - /// (but which may have already partially or entirely completed). - StreamCancelWrite { info: PayloadInfo, async_: bool }, - - /// A `canon stream.drop-readable` intrinsic. - /// - /// This allows the guest to drop the readable end of a `stream`. - StreamDropReadable(PayloadInfo), - - /// A `canon stream.drop-writable` intrinsic. - /// - /// This allows the guest to drop the writable end of a `stream`. - StreamDropWritable(PayloadInfo), - - /// A `canon future.new` intrinsic. - /// - /// This allows the guest to create a new `future` of the specified type. - FutureNew(PayloadInfo), - - /// A `canon future.read` intrinsic. - /// - /// This allows the guest to read the value (if any) from the specified - /// future. - FutureRead { async_: bool, info: PayloadInfo }, - - /// A `canon future.write` intrinsic. - /// - /// This allows the guest to write a value to the specified future. - FutureWrite { async_: bool, info: PayloadInfo }, - - /// A `canon future.cancel-read` intrinsic. - /// - /// This allows the guest to cancel a pending read it initiated earlier (but - /// which may have already completed). - FutureCancelRead { info: PayloadInfo, async_: bool }, - - /// A `canon future.cancel-write` intrinsic. - /// - /// This allows the guest to cancel a pending write it initiated earlier - /// (but which may have already completed). - FutureCancelWrite { info: PayloadInfo, async_: bool }, - - /// A `canon future.drop-readable` intrinsic. - /// - /// This allows the guest to drop the readable end of a `future`. - FutureDropReadable(PayloadInfo), - - /// A `canon future.drop-writable` intrinsic. - /// - /// This allows the guest to drop the writable end of a `future`. - FutureDropWritable(PayloadInfo), - - /// A `canon error-context.new` intrinsic. - /// - /// This allows the guest to create a new `error-context` instance with a - /// specified debug message. - ErrorContextNew { encoding: StringEncoding }, - - /// A `canon error-context.debug-message` intrinsic. - /// - /// This allows the guest to retrieve the debug message from a - /// `error-context` instance. Note that the content of this message might - /// not be identical to what was passed in to `error-context.new`. - ErrorContextDebugMessage { encoding: StringEncoding }, - - /// A `canon error-context.drop` intrinsic. - /// - /// This allows the guest to release its handle to the specified - /// `error-context` instance. - ErrorContextDrop, - - /// A `canon thread.index` intrinsic. - /// - /// This allows the guest to get the index of the current thread. - ThreadIndex, - - /// A `canon thread.new-indirect` intrinsic. - /// - /// This allows the guest to create a new thread running a specified function. - ThreadNewIndirect, - - /// A `canon thread.resume-later` intrinsic. - ThreadResumeLater, - - /// A `canon thread.suspend` intrinsic. - ThreadSuspend { cancellable: bool }, - - /// A `canon thread.yield` intrinsic. - ThreadYield { cancellable: bool }, - - /// A `canon thread.suspend-then-resume` intrinsic. - ThreadSuspendThenResume { cancellable: bool }, - - /// A `canon thread.yield-then-resume` intrinsic. - ThreadYieldThenResume { cancellable: bool }, - - /// A `canon thread.suspend-then-promote` intrinsic. - ThreadSuspendThenPromote { cancellable: bool }, - - /// A `canon thread.yield-then-promote` intrinsic. - ThreadYieldThenPromote { cancellable: bool }, -} - -impl ImportMap { - /// Returns the list of items that the adapter named `name` must export. - pub fn required_from_adapter(&self, name: &str) -> IndexMap { - let names = match self.names.get(name) { - Some(ImportInstance::Names(names)) => names, - _ => return IndexMap::new(), - }; - names - .iter() - .map(|(_, import)| match import { - Import::AdapterExport { ty, func, adapter } => { - assert_eq!(adapter, name); - (func.clone(), ty.clone()) - } - _ => unreachable!(), - }) - .collect() - } - - /// Returns an iterator over all individual imports registered in this map. - /// - /// Note that this doesn't iterate over the "whole instance" imports. - pub fn imports(&self) -> impl Iterator + '_ { - self.names - .iter() - .filter_map(|(module, m)| match m { - ImportInstance::Names(names) => Some((module, names)), - ImportInstance::Whole(_) => None, - }) - .flat_map(|(module, m)| { - m.iter() - .map(move |(field, import)| (module.as_str(), field.as_str(), import)) - }) - } - - /// Returns the map for how all imports must be satisfied. - pub fn modules(&self) -> &IndexMap { - &self.names - } - - /// Returns the type of the `env::memory` import of this module, if present. - pub fn imported_memory(&self) -> Option { - self.imported_memory - } - - /// Classify an import and call `insert_import()` on it. Used during - /// validation to build up this `ImportMap`. - fn add( - &mut self, - import: wasmparser::Import<'_>, - encoder: &ComponentEncoder, - import_map: Option<&ModuleImportMap>, - library_info: Option<&LibraryInfo>, - types: TypesRef<'_>, - ) -> Result<()> { - if self.classify_import_with_library(import, library_info)? { - return Ok(()); - } - let mut import_to_classify = import; - if let Some(map) = import_map { - if let Some(original_name) = map.original_name(&import) { - import_to_classify.name = original_name; - } - } - let item = self - .classify(import_to_classify, encoder, types) - .with_context(|| { - format!( - "failed to resolve import `{}::{}`", - import.module, import.name, - ) - })?; - self.insert_import(import, item) - } - - /// Determines what kind of thing is being imported: maps it from the - /// module/name/type triple in the raw wasm module to an enum. - /// - /// Handles a few special cases, then delegates to - /// `classify_component_model_import()`. - fn classify( - &self, - import: wasmparser::Import<'_>, - encoder: &ComponentEncoder, - types: TypesRef<'_>, - ) -> Result { - // Special-case the main module's memory imported into adapters which - // currently with `wasm-ld` is not easily configurable. - if import.module == "env" && import.name == "memory" { - if let TypeRef::Memory(ty) = import.ty { - return Ok(Import::MainModuleMemory(ty)); - } - } - - // Special-case imports from the main module into adapters. - if import.module == "__main_module__" { - return Ok(Import::MainModuleExport { - name: import.name.to_string(), - kind: match import.ty { - TypeRef::Func(_) => ExportKind::Func, - TypeRef::Table(_) => ExportKind::Table, - TypeRef::Memory(_) => ExportKind::Memory, - TypeRef::Global(_) => ExportKind::Global, - TypeRef::Tag(_) => ExportKind::Tag, - TypeRef::FuncExact(_) => bail!("Unexpected func_exact export"), - }, - }); - } - - let ty_index = match import.ty { - TypeRef::Func(ty) => ty, - _ => bail!("module is only allowed to import functions"), - }; - let ty = types[types.core_type_at_in_module(ty_index)].unwrap_func(); - - // Handle main module imports that match known adapters and set it up as - // an import of an adapter export. - if encoder.adapters.contains_key(import.module) { - return Ok(Import::AdapterExport { - adapter: import.module.to_string(), - func: import.name.to_string(), - ty: ty.clone(), - }); - } - - let (module, names) = match import.module.strip_prefix("cm32p2") { - Some(suffix) => (suffix, STANDARD), - None if encoder.reject_legacy_names => (import.module, STANDARD), - None => (import.module, LEGACY), - }; - self.classify_component_model_import(module, import.name, encoder, ty, names) - } - - /// Attempts to classify the import `{module}::{name}` with the rules - /// specified in WebAssembly/component-model#378 - fn classify_component_model_import( - &self, - module: &str, - name: &str, - encoder: &ComponentEncoder, - ty: &FuncType, - names: &dyn NameMangling, - ) -> Result { - let resolve = &encoder.metadata.resolve; - let world_id = encoder.metadata.world; - let world = &resolve.worlds[world_id]; - - if module == names.import_root() { - if names.error_context_drop(name) { - let expected = FuncType::new([ValType::I32], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ErrorContextDrop); - } - - if names.backpressure_inc(name) { - let expected = FuncType::new([], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::BackpressureInc); - } - - if names.backpressure_dec(name) { - let expected = FuncType::new([], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::BackpressureDec); - } - - if names.waitable_set_new(name) { - let expected = FuncType::new([], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::WaitableSetNew); - } - - if let Some((info, result_ty)) = names.waitable_set_wait(name) { - let expected = FuncType::new([ValType::I32, result_ty], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::WaitableSetWait { - cancellable: info.cancellable, - }); - } - - if let Some((info, result_ty)) = names.waitable_set_poll(name) { - let expected = FuncType::new([ValType::I32, result_ty], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::WaitableSetPoll { - cancellable: info.cancellable, - }); - } - - if names.waitable_set_drop(name) { - let expected = FuncType::new([ValType::I32], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::WaitableSetDrop); - } - - if names.waitable_join(name) { - let expected = FuncType::new([ValType::I32; 2], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::WaitableJoin); - } - - if names.subtask_drop(name) { - let expected = FuncType::new([ValType::I32], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::SubtaskDrop); - } - - if let Some(info) = names.subtask_cancel(name) { - let expected = FuncType::new([ValType::I32], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::SubtaskCancel { - async_: info.async_lowered, - }); - } - - if let Some(encoding) = names.error_context_new(name) { - let expected = FuncType::new([ValType::I32; 2], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ErrorContextNew { encoding }); - } - - if let Some(encoding) = names.error_context_debug_message(name) { - let expected = FuncType::new([ValType::I32; 2], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ErrorContextDebugMessage { encoding }); - } - - if let Some((slot_ty, slot)) = names.context_get(name) { - let expected = FuncType::new([], [slot_ty]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ContextGet { ty: slot_ty, slot }); - } - if let Some((slot_ty, slot)) = names.context_set(name) { - let expected = FuncType::new([slot_ty], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ContextSet { ty: slot_ty, slot }); - } - if names.thread_index(name) { - let expected = FuncType::new([], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadIndex); - } - if names.thread_new_indirect(name) { - let expected = FuncType::new([ValType::I32; 2], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadNewIndirect); - } - if names.thread_resume_later(name) { - let expected = FuncType::new([ValType::I32], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadResumeLater); - } - if let Some(info) = names.thread_suspend(name) { - let expected = FuncType::new([], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadSuspend { - cancellable: info.cancellable, - }); - } - if let Some(info) = names.thread_yield(name) { - let expected = FuncType::new([], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadYield { - cancellable: info.cancellable, - }); - } - if let Some(info) = names.thread_suspend_then_resume(name) { - let expected = FuncType::new([ValType::I32], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadSuspendThenResume { - cancellable: info.cancellable, - }); - } - if let Some(info) = names.thread_yield_then_resume(name) { - let expected = FuncType::new([ValType::I32], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadYieldThenResume { - cancellable: info.cancellable, - }); - } - if let Some(info) = names.thread_suspend_then_promote(name) { - let expected = FuncType::new([ValType::I32], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadSuspendThenPromote { - cancellable: info.cancellable, - }); - } - if let Some(info) = names.thread_yield_then_promote(name) { - let expected = FuncType::new([ValType::I32], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Import::ThreadYieldThenPromote { - cancellable: info.cancellable, - }); - } - - let (key_name, abi) = names.world_key_name_and_abi(name); - let key = WorldKey::Name(key_name.to_string()); - if let Some(WorldItem::Function(func)) = world.imports.get(&key) { - validate_func(resolve, ty, func, abi)?; - return Ok(Import::WorldFunc(key, func.name.clone(), abi)); - } - - if let Some(import) = - self.maybe_classify_wit_intrinsic(name, None, encoder, ty, true, names)? - { - return Ok(import); - } - - match world.imports.get(&key) { - Some(_) => bail!("expected world top-level import `{name}` to be a function"), - None => bail!("no top-level imported function `{name}` specified"), - } - } - - if module == "env" { - if let Some(import) = names.env_import(name, ty) { - return Ok(import); - } - } - - // Check for `[export]$root::[task-return]foo` or similar - if matches!( - module.strip_prefix(names.import_exported_intrinsic_prefix()), - Some(module) if module == names.import_root() - ) { - if let Some(import) = - self.maybe_classify_wit_intrinsic(name, None, encoder, ty, false, names)? - { - return Ok(import); - } - } - - let interface = match module.strip_prefix(names.import_non_root_prefix()) { - Some(name) => name, - None => bail!("unknown or invalid component model import syntax"), - }; - - if let Some(interface) = interface.strip_prefix(names.import_exported_intrinsic_prefix()) { - let (key, id) = names.module_to_interface(interface, resolve, &world.exports)?; - - if let Some(import) = - self.maybe_classify_wit_intrinsic(name, Some((key, id)), encoder, ty, false, names)? - { - return Ok(import); - } - bail!("unknown function `{name}`") - } - - let (key, id) = names.module_to_interface(interface, resolve, &world.imports)?; - let interface = &resolve.interfaces[id]; - let (function_name, abi) = names.interface_function_name_and_abi(name); - if let Some(f) = interface.functions.get(function_name) { - validate_func(resolve, ty, f, abi).with_context(|| { - let name = resolve.name_world_key(&key); - format!("failed to validate import interface `{name}`") - })?; - return Ok(Import::InterfaceFunc(key, id, f.name.clone(), abi)); - } - - if let Some(import) = - self.maybe_classify_wit_intrinsic(name, Some((key, id)), encoder, ty, true, names)? - { - return Ok(import); - } - bail!( - "import interface `{module}` is missing function \ - `{name}` that is required by the module", - ) - } - - /// Attempts to detect and classify `name` as a WIT intrinsic. - /// - /// This function is a bit of a sprawling sequence of matches used to - /// detect whether `name` corresponds to a WIT intrinsic, so specifically - /// not a WIT function itself. This is only used for functions imported - /// into a module but the import could be for an imported item in a world - /// or an exported item. - /// - /// ## Parameters - /// - /// * `name` - the core module name which is being pattern-matched. This - /// should be the "field" of the import. This may include the "[async-lower]" - /// or "[cancellable]" prefixes. - /// * `key_and_id` - this is the inferred "container" for the function - /// being described which is inferred from the module portion of the core - /// wasm import field. This is `None` for root-level function/type - /// imports, such as when referring to `import x: func();`. This is `Some` - /// when an interface is used (either `import x: interface { .. }` or a - /// standalone `interface`) where the world key is specified for the - /// interface in addition to the interface that was identified. - /// * `encoder` - this is the encoder state that contains - /// `Resolve`/metadata information. - /// * `ty` - the core wasm type of this import. - /// * `import` - whether or not this core wasm import is operating on a WIT - /// level import or export. An example of this being an export is when a - /// core module imports a destructor for an exported resource. - /// * `names` - the name mangling scheme that's configured to be used. - fn maybe_classify_wit_intrinsic( - &self, - name: &str, - key_and_id: Option<(WorldKey, InterfaceId)>, - encoder: &ComponentEncoder, - ty: &FuncType, - import: bool, - names: &dyn NameMangling, - ) -> Result> { - let resolve = &encoder.metadata.resolve; - let world_id = encoder.metadata.world; - let world = &resolve.worlds[world_id]; - - // Separate out `Option` and `Option`. If an - // interface is NOT specified then the `WorldKey` which is attached to - // imports is going to be calculated based on the name of the item - // extracted, such as the resource or function referenced. - let (key, id) = match key_and_id { - Some((key, id)) => (Some(key), Some(id)), - None => (None, None), - }; - - // Tests whether `name` is a resource within `id` (or `world_id`). - let resource_test = |name: &str| match id { - Some(id) => resource_test_for_interface(resolve, id)(name), - None => resource_test_for_world(resolve, world_id)(name), - }; - - // Test whether this is a `resource.drop` intrinsic. - if let Some(resource) = names.resource_drop_name(name) { - if let Some(resource_id) = resource_test(resource) { - let key = key.unwrap_or_else(|| WorldKey::Name(resource.to_string())); - let expected = FuncType::new([ValType::I32], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Some(if import { - Import::ImportedResourceDrop(key, id, resource_id) - } else { - Import::ExportedResourceDrop(key, resource_id) - })); - } - } - - // There are some intrinsics which are only applicable to exported - // functions/resources, so check those use cases here. - if !import { - if let Some(name) = names.resource_new_name(name) { - if let Some(id) = resource_test(name) { - let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string())); - let expected = FuncType::new([ValType::I32], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Some(Import::ExportedResourceNew(key, id))); - } - } - if let Some(name) = names.resource_rep_name(name) { - if let Some(id) = resource_test(name) { - let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string())); - let expected = FuncType::new([ValType::I32], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Some(Import::ExportedResourceRep(key, id))); - } - } - if let Some(name) = names.task_return_name(name) { - let func = get_function(resolve, world, name, id, import)?; - let key = key.unwrap_or_else(|| WorldKey::Name(name.to_string())); - // TODO: should call `validate_func_sig` but would require - // calculating the expected signature based of `func.result`. - return Ok(Some(Import::ExportedTaskReturn(key, id, func.clone()))); - } - if names.task_cancel(name) { - let expected = FuncType::new([], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Some(Import::ExportedTaskCancel)); - } - } - - let lookup_context = PayloadLookupContext { - resolve, - world, - key, - id, - import, - }; - - // Test for a number of async-related intrinsics. All intrinsics are - // prefixed with `[...-N]` where `...` is the name of the intrinsic and - // the `N` is the indexed future/stream that is being referred to. - let import = if let Some(info) = names.future_new(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([], [ValType::I64]), ty)?; - Import::FutureNew(info) - } else if let Some(info) = names.future_write(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32; 2], [ValType::I32]), ty)?; - Import::FutureWrite { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.future_read(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32; 2], [ValType::I32]), ty)?; - Import::FutureRead { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.future_cancel_write(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; - Import::FutureCancelWrite { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.future_cancel_read(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; - Import::FutureCancelRead { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.future_drop_writable(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; - Import::FutureDropWritable(info) - } else if let Some(info) = names.future_drop_readable(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; - Import::FutureDropReadable(info) - } else if let Some(info) = names.stream_new(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([], [ValType::I64]), ty)?; - Import::StreamNew(info) - } else if let Some(info) = names.stream_write(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32; 3], [ValType::I32]), ty)?; - Import::StreamWrite { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.stream_read(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32; 3], [ValType::I32]), ty)?; - Import::StreamRead { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.stream_cancel_write(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; - Import::StreamCancelWrite { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.stream_cancel_read(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], [ValType::I32]), ty)?; - Import::StreamCancelRead { - async_: info.async_lowered, - info: info.inner, - } - } else if let Some(info) = names.stream_drop_writable(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; - Import::StreamDropWritable(info) - } else if let Some(info) = names.stream_drop_readable(&lookup_context, name) { - validate_func_sig(name, &FuncType::new([ValType::I32], []), ty)?; - Import::StreamDropReadable(info) - } else { - return Ok(None); - }; - Ok(Some(import)) - } - - fn classify_import_with_library( - &mut self, - import: wasmparser::Import<'_>, - library_info: Option<&LibraryInfo>, - ) -> Result { - let info = match library_info { - Some(info) => info, - None => return Ok(false), - }; - let Some((_, instance)) = info - .arguments - .iter() - .find(|(name, _items)| *name == import.module) - else { - return Ok(false); - }; - match instance { - Instance::MainOrAdapter(module) => match self.names.get(import.module) { - Some(ImportInstance::Whole(which)) => { - if which != module { - bail!("different whole modules imported under the same name"); - } - } - Some(ImportInstance::Names(_)) => { - bail!("cannot mix individual imports and whole module imports") - } - None => { - let instance = ImportInstance::Whole(module.clone()); - self.names.insert(import.module.to_string(), instance); - } - }, - Instance::Items(items) => { - let Some(item) = items.iter().find(|i| i.alias == import.name) else { - return Ok(false); - }; - self.insert_import(import, Import::Item(item.clone()))?; - } - } - Ok(true) - } - - /// Map an imported item, by module and field name in `self.names`, to the - /// kind of `Import` it is: for example, a certain-typed function from an - /// adapter. - fn insert_import(&mut self, import: wasmparser::Import<'_>, item: Import) -> Result<()> { - if let Import::MainModuleMemory(ty) = item { - if self.imported_memory.is_some() { - bail!("module has multiple imports for memory"); - } - self.imported_memory = Some(ty); - } - let entry = self - .names - .entry(import.module.to_string()) - .or_insert(ImportInstance::Names(IndexMap::default())); - let names = match entry { - ImportInstance::Names(names) => names, - _ => bail!("cannot mix individual imports with module imports"), - }; - let entry = match names.entry(import.name.to_string()) { - Entry::Occupied(_) => { - bail!( - "module has duplicate import for `{}::{}`", - import.module, - import.name - ); - } - Entry::Vacant(v) => v, - }; - log::trace!( - "classifying import `{}::{} as {item:?}", - import.module, - import.name - ); - entry.insert(item); - Ok(()) - } -} - -/// Dual of `ImportMap` except describes the exports of a module instead of the -/// imports. -#[derive(Default)] -pub struct ExportMap { - names: IndexMap, - raw_exports: IndexMap, -} - -/// All possible (known) exports from a core wasm module that are recognized and -/// handled during the componentization process. -#[derive(Debug)] -pub enum Export { - /// An export of a top-level function of a world, where the world function - /// is named here. - WorldFunc(WorldKey, String, AbiVariant), - - /// A post-return for a top-level function of a world. - WorldFuncPostReturn(WorldKey), - - /// An export of a function in an interface. - InterfaceFunc(WorldKey, InterfaceId, String, AbiVariant), - - /// A post-return for the above function. - InterfaceFuncPostReturn(WorldKey, String), - - /// A destructor for an exported resource. - ResourceDtor(TypeId), - - /// Memory, typically for an adapter. - Memory, - - /// `cabi_realloc` - GeneralPurposeRealloc, - - /// `cabi_export_realloc` - GeneralPurposeExportRealloc, - - /// `cabi_import_realloc` - GeneralPurposeImportRealloc, - - /// `_initialize` - Initialize, - - /// `cabi_realloc_adapter` - ReallocForAdapter, - - WorldFuncCallback(WorldKey), - - InterfaceFuncCallback(WorldKey, String), - - /// __indirect_function_table, used for `thread.new-indirect` - IndirectFunctionTable, - - /// Used to hook lifecycle events for tasks. - WasmTaskHook, -} - -impl ExportMap { - fn add( - &mut self, - export: wasmparser::Export<'_>, - encoder: &ComponentEncoder, - exports: &IndexSet, - types: TypesRef<'_>, - ) -> Result<()> { - if let Some(item) = self.classify(export, encoder, exports, types)? { - log::debug!("classifying export `{}` as {item:?}", export.name); - let prev = self.names.insert(export.name.to_string(), item); - assert!(prev.is_none()); - } - Ok(()) - } - - fn classify( - &mut self, - export: wasmparser::Export<'_>, - encoder: &ComponentEncoder, - exports: &IndexSet, - types: TypesRef<'_>, - ) -> Result> { - match export.kind { - ExternalKind::Func => { - let ty = types[types.core_function_at(export.index)].unwrap_func(); - self.raw_exports.insert(export.name.to_string(), ty.clone()); - } - _ => {} - } - - // Handle a few special-cased names first. - if export.name == "canonical_abi_realloc" { - return Ok(Some(Export::GeneralPurposeRealloc)); - } else if export.name == "cabi_import_realloc" { - return Ok(Some(Export::GeneralPurposeImportRealloc)); - } else if export.name == "cabi_export_realloc" { - return Ok(Some(Export::GeneralPurposeExportRealloc)); - } else if export.name == "cabi_realloc_adapter" { - return Ok(Some(Export::ReallocForAdapter)); - } - - let (name, names) = match export.name.strip_prefix("cm32p2") { - Some(name) => (name, STANDARD), - None if encoder.reject_legacy_names => return Ok(None), - None => (export.name, LEGACY), - }; - - if let Some(export) = self - .classify_component_export(names, name, &export, encoder, exports, types) - .with_context(|| format!("failed to classify export `{}`", export.name))? - { - return Ok(Some(export)); - } - log::debug!("unknown export `{}`", export.name); - Ok(None) - } - - fn classify_component_export( - &mut self, - names: &dyn NameMangling, - name: &str, - export: &wasmparser::Export<'_>, - encoder: &ComponentEncoder, - exports: &IndexSet, - types: TypesRef<'_>, - ) -> Result> { - let resolve = &encoder.metadata.resolve; - let world = encoder.metadata.world; - match export.kind { - ExternalKind::Func => {} - ExternalKind::Memory => { - if name == names.export_memory() { - return Ok(Some(Export::Memory)); - } - return Ok(None); - } - ExternalKind::Table => { - if Some(name) == names.export_indirect_function_table() { - return Ok(Some(Export::IndirectFunctionTable)); - } - return Ok(None); - } - _ => return Ok(None), - } - let ty = types[types.core_function_at(export.index)].unwrap_func(); - - // Handle a few special-cased names first. - if name == names.export_realloc() { - let expected = FuncType::new([ValType::I32; 4], [ValType::I32]); - validate_func_sig(name, &expected, ty)?; - return Ok(Some(Export::GeneralPurposeRealloc)); - } else if name == names.export_initialize() { - let expected = FuncType::new([], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Some(Export::Initialize)); - } else if Some(name) == names.export_wasm_task_hook() { - let expected = FuncType::new([ValType::I32], []); - validate_func_sig(name, &expected, ty)?; - return Ok(Some(Export::WasmTaskHook)); - } - - let full_name = name; - let (abi, name) = if let Some(name) = names.async_lift_name(name) { - (AbiVariant::GuestExportAsync, name) - } else if let Some(name) = names.async_lift_stackful_name(name) { - (AbiVariant::GuestExportAsyncStackful, name) - } else { - (AbiVariant::GuestExport, name) - }; - - // Try to match this to a known WIT export that `exports` allows. - if let Some((key, id, f)) = names.match_wit_export(name, resolve, world, exports) { - validate_func(resolve, ty, f, abi).with_context(|| { - let key = resolve.name_world_key(key); - format!("failed to validate export for `{key}`") - })?; - match id { - Some(id) => { - return Ok(Some(Export::InterfaceFunc( - key.clone(), - id, - f.name.clone(), - abi, - ))); - } - None => { - return Ok(Some(Export::WorldFunc(key.clone(), f.name.clone(), abi))); - } - } - } - - // See if this is a post-return for any known WIT export. - if let Some(remaining) = names.strip_post_return(name) { - if let Some((key, id, f)) = names.match_wit_export(remaining, resolve, world, exports) { - validate_post_return(resolve, ty, f).with_context(|| { - let key = resolve.name_world_key(key); - format!("failed to validate export for `{key}`") - })?; - match id { - Some(_id) => { - return Ok(Some(Export::InterfaceFuncPostReturn( - key.clone(), - f.name.clone(), - ))); - } - None => { - return Ok(Some(Export::WorldFuncPostReturn(key.clone()))); - } - } - } - } - - if let Some(suffix) = names.async_lift_callback_name(full_name) { - if let Some((key, id, f)) = names.match_wit_export(suffix, resolve, world, exports) { - validate_func_sig( - full_name, - &FuncType::new([ValType::I32; 3], [ValType::I32]), - ty, - )?; - return Ok(Some(if id.is_some() { - Export::InterfaceFuncCallback(key.clone(), f.name.clone()) - } else { - Export::WorldFuncCallback(key.clone()) - })); - } - } - - // And, finally, see if it matches a known destructor. - if let Some(dtor) = names.match_wit_resource_dtor(name, resolve, world, exports) { - let expected = FuncType::new([ValType::I32], []); - validate_func_sig(full_name, &expected, ty)?; - return Ok(Some(Export::ResourceDtor(dtor))); - } - - Ok(None) - } - - /// Returns the name of the post-return export, if any, for the `key` and - /// `func` combo. - pub fn post_return(&self, key: &WorldKey, func: &Function) -> Option<&str> { - self.find(|m| match m { - Export::WorldFuncPostReturn(k) => k == key, - Export::InterfaceFuncPostReturn(k, f) => k == key && func.name == *f, - _ => false, - }) - } - - /// Returns the name of the async callback export, if any, for the `key` and - /// `func` combo. - pub fn callback(&self, key: &WorldKey, func: &Function) -> Option<&str> { - self.find(|m| match m { - Export::WorldFuncCallback(k) => k == key, - Export::InterfaceFuncCallback(k, f) => k == key && func.name == *f, - _ => false, - }) - } - - pub fn abi(&self, key: &WorldKey, func: &Function) -> Option { - self.names.values().find_map(|m| match m { - Export::WorldFunc(k, f, abi) if k == key && func.name == *f => Some(*abi), - Export::InterfaceFunc(k, _, f, abi) if k == key && func.name == *f => Some(*abi), - _ => None, - }) - } - - /// Returns the realloc that the exported function `interface` and `func` - /// are using. - pub fn export_realloc_for(&self, key: &WorldKey, func: &str) -> Option<&str> { - // TODO: This realloc detection should probably be improved with - // some sort of scheme to have per-function reallocs like - // `cabi_realloc_{name}` or something like that. - let _ = (key, func); - - if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeExportRealloc)) { - return Some(name); - } - self.general_purpose_realloc() - } - - /// Returns the realloc that the imported function `interface` and `func` - /// are using. - pub fn import_realloc_for(&self, interface: Option, func: &str) -> Option<&str> { - // TODO: This realloc detection should probably be improved with - // some sort of scheme to have per-function reallocs like - // `cabi_realloc_{name}` or something like that. - let _ = (interface, func); - - self.import_realloc_fallback() - } - - /// Returns the general-purpose realloc function to use for imports. - /// - /// Note that `import_realloc_for` should be used instead where possible. - pub fn import_realloc_fallback(&self) -> Option<&str> { - if let Some(name) = self.find(|m| matches!(m, Export::GeneralPurposeImportRealloc)) { - return Some(name); - } - self.general_purpose_realloc() - } - - /// Returns the realloc that the main module is exporting into the adapter. - pub fn realloc_to_import_into_adapter(&self) -> Option<&str> { - if let Some(name) = self.find(|m| matches!(m, Export::ReallocForAdapter)) { - return Some(name); - } - self.general_purpose_realloc() - } - - pub fn general_purpose_realloc(&self) -> Option<&str> { - self.find(|m| matches!(m, Export::GeneralPurposeRealloc)) - } - - /// Returns an iterator over all `realloc` functions exported by this module - /// which may be used as a `realloc` canonical option. - /// - /// Note that `cabi_realloc_adapter` is intentionally not included here as - /// that's only ever imported directly into an adapter module and is never - /// used as a canonical option. - pub fn reallocs(&self) -> impl Iterator + '_ { - self.names.iter().filter_map(|(name, export)| match export { - Export::GeneralPurposeRealloc - | Export::GeneralPurposeExportRealloc - | Export::GeneralPurposeImportRealloc => Some(name.as_str()), - _ => None, - }) - } - - /// Returns the memory, if exported, for this module. - pub fn memory(&self) -> Option<&str> { - self.find(|m| matches!(m, Export::Memory)) - } - - /// Returns the indirect function table, if exported, for this module. - pub fn indirect_function_table(&self) -> Option<&str> { - self.find(|t| matches!(t, Export::IndirectFunctionTable)) - } - - /// Returns the hook for tasks, if exported. - pub fn wasm_task_hook(&self) -> Option<&str> { - self.find(|t| matches!(t, Export::WasmTaskHook)) - } - - /// Returns the `_initialize` intrinsic, if exported, for this module. - pub fn initialize(&self) -> Option<&str> { - self.find(|m| matches!(m, Export::Initialize)) - } - - /// Returns destructor for the exported resource `ty`, if it was listed. - pub fn resource_dtor(&self, ty: TypeId) -> Option<&str> { - self.find(|m| match m { - Export::ResourceDtor(t) => *t == ty, - _ => false, - }) - } - - /// NB: this is a linear search and if that's ever a problem this should - /// build up an inverse map during construction to accelerate it. - fn find(&self, f: impl Fn(&Export) -> bool) -> Option<&str> { - let (name, _) = self.names.iter().filter(|(_, m)| f(m)).next()?; - Some(name) - } - - /// Iterates over all exports of this module. - pub fn iter(&self) -> impl Iterator + '_ { - self.names.iter().map(|(n, e)| (n.as_str(), e)) - } - - fn validate(&self, encoder: &ComponentEncoder, exports: &IndexSet) -> Result<()> { - let resolve = &encoder.metadata.resolve; - let world = encoder.metadata.world; - // Multi-memory isn't supported because otherwise we don't know what - // memory to put things in. - if self - .names - .values() - .filter(|m| matches!(m, Export::Memory)) - .count() - > 1 - { - bail!("cannot componentize module that exports multiple memories") - } - - // Every async-with-callback-lifted export must have a callback. - for (name, export) in &self.names { - match export { - Export::WorldFunc(_, _, AbiVariant::GuestExportAsync) => { - if !matches!( - self.names.get(&format!("[callback]{name}")), - Some(Export::WorldFuncCallback(_)) - ) { - bail!("missing callback for `{name}`"); - } - } - Export::InterfaceFunc(_, _, _, AbiVariant::GuestExportAsync) => { - if !matches!( - self.names.get(&format!("[callback]{name}")), - Some(Export::InterfaceFuncCallback(_, _)) - ) { - bail!("missing callback for `{name}`"); - } - } - _ => {} - } - } - - // All of `exports` must be exported and found within this module. - for export in exports { - let require_interface_func = |interface: InterfaceId, name: &str| -> Result<()> { - let result = self.find(|e| match e { - Export::InterfaceFunc(_, id, s, _) => interface == *id && name == s, - _ => false, - }); - if result.is_some() { - Ok(()) - } else { - let export = resolve.name_world_key(export); - bail!("failed to find export of interface `{export}` function `{name}`") - } - }; - let require_world_func = |name: &str| -> Result<()> { - let result = self.find(|e| match e { - Export::WorldFunc(_, s, _) => name == s, - _ => false, - }); - if result.is_some() { - Ok(()) - } else { - bail!("failed to find export of function `{name}`") - } - }; - match &resolve.worlds[world].exports[export] { - WorldItem::Interface { id, .. } => { - for (name, _) in resolve.interfaces[*id].functions.iter() { - require_interface_func(*id, name)?; - } - } - WorldItem::Function(f) => { - require_world_func(&f.name)?; - } - WorldItem::Type { .. } => unreachable!(), - } - } - - Ok(()) - } -} - -/// A builtin that may be declared as cancellable. -struct MaybeCancellable { - #[allow(unused)] - inner: T, - cancellable: bool, -} - -/// A builtin that may be declared as async-lowered. -struct MaybeAsyncLowered { - inner: T, - async_lowered: bool, -} - -/// Context passed to `NameMangling` implementations of stream and future functions -/// to help with looking up payload information. -struct PayloadLookupContext<'a> { - resolve: &'a Resolve, - world: &'a World, - id: Option, - import: bool, - key: Option, -} - -/// Trait dispatch and definition for parsing and interpreting "mangled names" -/// which show up in imports and exports of the component model. -/// -/// This trait is used to implement classification of imports and exports in the -/// component model. The methods on `ImportMap` and `ExportMap` will use this to -/// determine what an import is and how it's lifted/lowered in the world being -/// bound. -/// -/// This trait has a bit of history behind it as well. Before -/// WebAssembly/component-model#378 there was no standard naming scheme for core -/// wasm imports or exports when componenitizing. This meant that -/// `wit-component` implemented a particular scheme which mostly worked but was -/// mostly along the lines of "this at least works" rather than "someone sat -/// down and designed this". Since then, however, an standard naming scheme has -/// now been specified which was indeed designed. -/// -/// This trait serves as the bridge between these two. The historical naming -/// scheme is still supported for now through the `Legacy` implementation below -/// and will be for some time. The transition plan at this time is to support -/// the new scheme, eventually get it supported in bindings generators, and once -/// that's all propagated remove support for the legacy scheme. -trait NameMangling { - fn import_root(&self) -> &str; - fn import_non_root_prefix(&self) -> &str; - fn import_exported_intrinsic_prefix(&self) -> &str; - fn export_memory(&self) -> &str; - fn export_initialize(&self) -> &str; - fn export_realloc(&self) -> &str; - fn export_indirect_function_table(&self) -> Option<&str>; - fn export_wasm_task_hook(&self) -> Option<&str>; - fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str>; - fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str>; - fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str>; - fn task_return_name<'a>(&self, name: &'a str) -> Option<&'a str>; - fn task_cancel(&self, name: &str) -> bool; - fn backpressure_inc(&self, name: &str) -> bool; - fn backpressure_dec(&self, name: &str) -> bool; - fn waitable_set_new(&self, name: &str) -> bool; - fn waitable_set_wait(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)>; - fn waitable_set_poll(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)>; - fn waitable_set_drop(&self, name: &str) -> bool; - fn waitable_join(&self, name: &str) -> bool; - fn subtask_drop(&self, name: &str) -> bool; - fn subtask_cancel(&self, name: &str) -> Option>; - fn async_lift_callback_name<'a>(&self, name: &'a str) -> Option<&'a str>; - fn async_lift_name<'a>(&self, name: &'a str) -> Option<&'a str>; - fn async_lift_stackful_name<'a>(&self, name: &'a str) -> Option<&'a str>; - fn error_context_new(&self, name: &str) -> Option; - fn error_context_debug_message(&self, name: &str) -> Option; - fn error_context_drop(&self, name: &str) -> bool; - fn context_get(&self, name: &str) -> Option<(ValType, u32)>; - fn context_set(&self, name: &str) -> Option<(ValType, u32)>; - fn future_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option; - fn future_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn future_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn future_cancel_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn future_cancel_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn future_drop_writable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option; - fn future_drop_readable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option; - fn stream_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option; - fn stream_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn stream_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn stream_cancel_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn stream_cancel_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option>; - fn stream_drop_writable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option; - fn stream_drop_readable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option; - fn thread_index(&self, name: &str) -> bool; - fn thread_new_indirect(&self, name: &str) -> bool; - fn thread_resume_later(&self, name: &str) -> bool; - fn thread_suspend(&self, name: &str) -> Option>; - fn thread_yield(&self, name: &str) -> Option>; - fn thread_suspend_then_resume(&self, name: &str) -> Option>; - fn thread_yield_then_resume(&self, name: &str) -> Option>; - fn thread_suspend_then_promote(&self, name: &str) -> Option>; - fn thread_yield_then_promote(&self, name: &str) -> Option>; - fn module_to_interface( - &self, - module: &str, - resolve: &Resolve, - items: &IndexMap, - ) -> Result<(WorldKey, InterfaceId)>; - fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str>; - fn match_wit_export<'a>( - &self, - export_name: &str, - resolve: &'a Resolve, - world: WorldId, - exports: &'a IndexSet, - ) -> Option<(&'a WorldKey, Option, &'a Function)>; - fn match_wit_resource_dtor<'a>( - &self, - export_name: &str, - resolve: &'a Resolve, - world: WorldId, - exports: &'a IndexSet, - ) -> Option; - fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant); - fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant); - fn env_import(&self, name: &str, ty: &FuncType) -> Option; -} - -/// Definition of the "standard" naming scheme which currently starts with -/// "cm32p2". Note that wasm64 is not supported at this time. -struct Standard; - -const STANDARD: &'static dyn NameMangling = &Standard; - -impl NameMangling for Standard { - fn import_root(&self) -> &str { - "" - } - fn import_non_root_prefix(&self) -> &str { - "|" - } - fn import_exported_intrinsic_prefix(&self) -> &str { - "_ex_" - } - fn export_memory(&self) -> &str { - "_memory" - } - fn export_initialize(&self) -> &str { - "_initialize" - } - fn export_realloc(&self) -> &str { - "_realloc" - } - fn export_indirect_function_table(&self) -> Option<&str> { - None - } - fn export_wasm_task_hook(&self) -> Option<&str> { - None - } - fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_suffix("_drop") - } - fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_suffix("_new") - } - fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_suffix("_rep") - } - fn task_return_name<'a>(&self, _name: &'a str) -> Option<&'a str> { - None - } - fn task_cancel(&self, _name: &str) -> bool { - false - } - fn backpressure_inc(&self, _name: &str) -> bool { - false - } - fn backpressure_dec(&self, _name: &str) -> bool { - false - } - fn waitable_set_new(&self, _name: &str) -> bool { - false - } - fn waitable_set_wait(&self, _name: &str) -> Option<(MaybeCancellable<()>, ValType)> { - None - } - fn waitable_set_poll(&self, _name: &str) -> Option<(MaybeCancellable<()>, ValType)> { - None - } - fn waitable_set_drop(&self, _name: &str) -> bool { - false - } - fn waitable_join(&self, _name: &str) -> bool { - false - } - fn subtask_drop(&self, _name: &str) -> bool { - false - } - fn subtask_cancel(&self, _name: &str) -> Option> { - None - } - fn async_lift_callback_name<'a>(&self, _name: &'a str) -> Option<&'a str> { - None - } - fn async_lift_name<'a>(&self, _name: &'a str) -> Option<&'a str> { - None - } - fn async_lift_stackful_name<'a>(&self, _name: &'a str) -> Option<&'a str> { - None - } - fn error_context_new(&self, _name: &str) -> Option { - None - } - fn error_context_debug_message(&self, _name: &str) -> Option { - None - } - fn error_context_drop(&self, _name: &str) -> bool { - false - } - fn context_get(&self, _name: &str) -> Option<(ValType, u32)> { - None - } - fn context_set(&self, _name: &str) -> Option<(ValType, u32)> { - None - } - fn thread_index(&self, _name: &str) -> bool { - false - } - fn thread_new_indirect(&self, _name: &str) -> bool { - false - } - fn thread_resume_later(&self, _name: &str) -> bool { - false - } - fn thread_suspend(&self, _name: &str) -> Option> { - None - } - fn thread_yield(&self, _name: &str) -> Option> { - None - } - fn thread_suspend_then_resume(&self, _name: &str) -> Option> { - None - } - fn thread_yield_then_resume(&self, _name: &str) -> Option> { - None - } - fn thread_suspend_then_promote(&self, _name: &str) -> Option> { - None - } - fn thread_yield_then_promote(&self, _name: &str) -> Option> { - None - } - fn future_new( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option { - None - } - fn future_write( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn future_read( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn future_cancel_write( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn future_cancel_read( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn future_drop_writable( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option { - None - } - fn future_drop_readable( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option { - None - } - fn stream_new( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option { - None - } - fn stream_write( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn stream_read( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn stream_cancel_write( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn stream_cancel_read( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option> { - None - } - fn stream_drop_writable( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option { - None - } - fn stream_drop_readable( - &self, - _lookup_context: &PayloadLookupContext, - _name: &str, - ) -> Option { - None - } - fn module_to_interface( - &self, - interface: &str, - resolve: &Resolve, - items: &IndexMap, - ) -> Result<(WorldKey, InterfaceId)> { - for (key, item) in items.iter() { - let id = match key { - // Bare keys are matched exactly against `interface` - WorldKey::Name(name) => match item { - WorldItem::Interface { id, .. } if name == interface => *id, - _ => continue, - }, - // ID-identified keys are matched with their "canonical name" - WorldKey::Interface(id) => { - if resolve.canonicalized_id_of(*id).as_deref() != Some(interface) { - continue; - } - *id - } - }; - return Ok((key.clone(), id)); - } - bail!("failed to find world item corresponding to interface `{interface}`") - } - fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_suffix("_post") - } - fn match_wit_export<'a>( - &self, - export_name: &str, - resolve: &'a Resolve, - world: WorldId, - exports: &'a IndexSet, - ) -> Option<(&'a WorldKey, Option, &'a Function)> { - if let Some(world_export_name) = export_name.strip_prefix("||") { - let key = exports.get(&WorldKey::Name(world_export_name.to_string()))?; - match &resolve.worlds[world].exports[key] { - WorldItem::Function(f) => return Some((key, None, f)), - _ => return None, - } - } - - let (key, id, func_name) = - self.match_wit_interface(export_name, resolve, world, exports)?; - let func = resolve.interfaces[id].functions.get(func_name)?; - Some((key, Some(id), func)) - } - - fn match_wit_resource_dtor<'a>( - &self, - export_name: &str, - resolve: &'a Resolve, - world: WorldId, - exports: &'a IndexSet, - ) -> Option { - let (_key, id, name) = - self.match_wit_interface(export_name.strip_suffix("_dtor")?, resolve, world, exports)?; - let ty = *resolve.interfaces[id].types.get(name)?; - match resolve.types[ty].kind { - TypeDefKind::Resource => Some(ty), - _ => None, - } - } - - fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { - (name, AbiVariant::GuestImport) - } - fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { - (name, AbiVariant::GuestImport) - } - fn env_import(&self, _name: &str, _ty: &FuncType) -> Option { - None - } -} - -impl Standard { - fn match_wit_interface<'a, 'b>( - &self, - export_name: &'b str, - resolve: &'a Resolve, - world: WorldId, - exports: &'a IndexSet, - ) -> Option<(&'a WorldKey, InterfaceId, &'b str)> { - let world = &resolve.worlds[world]; - let export_name = export_name.strip_prefix("|")?; - - for export in exports { - let id = match &world.exports[export] { - WorldItem::Interface { id, .. } => *id, - WorldItem::Function(_) => continue, - WorldItem::Type { .. } => unreachable!(), - }; - let remaining = match export { - WorldKey::Name(name) => export_name.strip_prefix(name), - WorldKey::Interface(_) => { - let prefix = resolve.canonicalized_id_of(id).unwrap(); - export_name.strip_prefix(&prefix) - } - }; - let item_name = match remaining.and_then(|s| s.strip_prefix("|")) { - Some(name) => name, - None => continue, - }; - return Some((export, id, item_name)); - } - - None - } -} - -/// Definition of wit-component's "legacy" naming scheme which predates -/// WebAssembly/component-model#378. -struct Legacy; - -const LEGACY: &'static dyn NameMangling = &Legacy; - -impl Legacy { - // Looks for `[$prefix-N]foo` within `name`. If found then `foo` is - // used to find a function within `id` and `world` above. Once found - // then `N` is used to index within that function to extract a - // future/stream type. If that's all found then a `PayloadInfo` is - // returned to get attached to an intrinsic. - fn prefixed_payload( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - prefix: &str, - ) -> Option { - // parse the `prefix` into `func_name` and `type_index`, bailing out - // with `None` if anything doesn't match. - let (index_or_unit, func_name) = prefixed_intrinsic(name, prefix)?; - let ty = match index_or_unit { - "unit" => { - if name.starts_with("[future") { - PayloadType::UnitFuture - } else if name.starts_with("[stream") { - PayloadType::UnitStream - } else { - unreachable!() - } - } - other => { - // Note that this is parsed as a `u32` to ensure that the - // integer parsing is the same across platforms regardless of - // the the width of `usize`. - let type_index = other.parse::().ok()? as usize; - - // Double-check that `func_name` is indeed a function name within - // this interface/world. Then additionally double-check that - // `type_index` is indeed a valid index for this function's type - // signature. - let function = get_function( - lookup_context.resolve, - lookup_context.world, - func_name, - lookup_context.id, - lookup_context.import, - ) - .ok()?; - PayloadType::Type { - id: *function - .find_futures_and_streams(lookup_context.resolve) - .get(type_index)?, - function: function.name.clone(), - } - } - }; - - // And if all that passes wrap up everything in a `PayloadInfo`. - Some(PayloadInfo { - name: name.to_string(), - ty, - key: lookup_context - .key - .clone() - .unwrap_or_else(|| WorldKey::Name(name.to_string())), - interface: lookup_context.id, - imported: lookup_context.import, - }) - } - - fn maybe_async_lowered_payload( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - prefix: &str, - ) -> Option> { - let (async_lowered, clean_name) = self.strip_async_lowered_prefix(name); - let payload = self.prefixed_payload(lookup_context, clean_name, prefix)?; - Some(MaybeAsyncLowered { - inner: payload, - async_lowered, - }) - } - - fn strip_async_lowered_prefix<'a>(&self, name: &'a str) -> (bool, &'a str) { - name.strip_prefix("[async-lower]") - .map_or((false, name), |s| (true, s)) - } - fn match_with_async_lowered_prefix( - &self, - name: &str, - expected: &str, - ) -> Option> { - let (async_lowered, clean_name) = self.strip_async_lowered_prefix(name); - if clean_name == expected { - Some(MaybeAsyncLowered { - inner: (), - async_lowered, - }) - } else { - None - } - } - fn strip_cancellable_prefix<'a>(&self, name: &'a str) -> (bool, &'a str) { - name.strip_prefix("[cancellable]") - .map_or((false, name), |s| (true, s)) - } - fn match_with_cancellable_prefix( - &self, - name: &str, - expected: &str, - ) -> Option> { - let (cancellable, clean_name) = self.strip_cancellable_prefix(name); - if clean_name == expected { - Some(MaybeCancellable { - inner: (), - cancellable, - }) - } else { - None - } - } - - /// Matches a name with the given prefix and either no suffix (for backwards compat) or - /// "-i32" or "-i64". - /// Returns a `ValType` based on the suffix and defaults to `I32`. - fn match_with_optional_type_suffix(name: &str, match_prefix: &str) -> Option { - let tail = name.strip_prefix(match_prefix)?.strip_suffix(']')?; - if tail.is_empty() { - Some(ValType::I32) - } else { - match tail.strip_prefix('-')? { - "i32" => Some(ValType::I32), - "i64" => Some(ValType::I64), - // Other suffixes - _ => None, - } - } - } -} - -impl NameMangling for Legacy { - fn import_root(&self) -> &str { - "$root" - } - fn import_non_root_prefix(&self) -> &str { - "" - } - fn import_exported_intrinsic_prefix(&self) -> &str { - "[export]" - } - fn export_memory(&self) -> &str { - "memory" - } - fn export_initialize(&self) -> &str { - "_initialize" - } - fn export_realloc(&self) -> &str { - "cabi_realloc" - } - fn export_indirect_function_table(&self) -> Option<&str> { - Some("__indirect_function_table") - } - fn export_wasm_task_hook(&self) -> Option<&str> { - Some(crate::linking::metadata::TASK_HOOK) - } - fn resource_drop_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("[resource-drop]") - } - fn resource_new_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("[resource-new]") - } - fn resource_rep_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("[resource-rep]") - } - fn task_return_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("[task-return]") - } - fn task_cancel(&self, name: &str) -> bool { - name == "[task-cancel]" - } - fn backpressure_inc(&self, name: &str) -> bool { - name == "[backpressure-inc]" - } - fn backpressure_dec(&self, name: &str) -> bool { - name == "[backpressure-dec]" - } - fn waitable_set_new(&self, name: &str) -> bool { - name == "[waitable-set-new]" - } - fn waitable_set_wait(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)> { - let (cancellable, clean_name) = self.strip_cancellable_prefix(name); - let mb_cancellable = MaybeCancellable { - inner: (), - cancellable, - }; - let result_ty = Legacy::match_with_optional_type_suffix(clean_name, "[waitable-set-wait")?; - Some((mb_cancellable, result_ty)) - } - fn waitable_set_poll(&self, name: &str) -> Option<(MaybeCancellable<()>, ValType)> { - let (cancellable, clean_name) = self.strip_cancellable_prefix(name); - let mb_cancellable = MaybeCancellable { - inner: (), - cancellable, - }; - let result_ty = Legacy::match_with_optional_type_suffix(clean_name, "[waitable-set-poll")?; - Some((mb_cancellable, result_ty)) - } - fn waitable_set_drop(&self, name: &str) -> bool { - name == "[waitable-set-drop]" - } - fn waitable_join(&self, name: &str) -> bool { - name == "[waitable-join]" - } - fn subtask_drop(&self, name: &str) -> bool { - name == "[subtask-drop]" - } - fn subtask_cancel(&self, name: &str) -> Option> { - self.match_with_async_lowered_prefix(name, "[subtask-cancel]") - } - fn async_lift_callback_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("[callback][async-lift]") - } - fn async_lift_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("[async-lift]") - } - fn async_lift_stackful_name<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("[async-lift-stackful]") - } - fn error_context_new(&self, name: &str) -> Option { - match name { - "[error-context-new-utf8]" => Some(StringEncoding::UTF8), - "[error-context-new-utf16]" => Some(StringEncoding::UTF16), - "[error-context-new-latin1+utf16]" => Some(StringEncoding::CompactUTF16), - _ => None, - } - } - fn error_context_debug_message(&self, name: &str) -> Option { - match name { - "[error-context-debug-message-utf8]" => Some(StringEncoding::UTF8), - "[error-context-debug-message-utf16]" => Some(StringEncoding::UTF16), - "[error-context-debug-message-latin1+utf16]" => Some(StringEncoding::CompactUTF16), - _ => None, - } - } - fn error_context_drop(&self, name: &str) -> bool { - name == "[error-context-drop]" - } - fn context_get(&self, name: &str) -> Option<(ValType, u32)> { - parse_context_name(name, "[context-get-") - } - fn context_set(&self, name: &str) -> Option<(ValType, u32)> { - parse_context_name(name, "[context-set-") - } - fn thread_index(&self, name: &str) -> bool { - name == "[thread-index]" - } - fn thread_new_indirect(&self, name: &str) -> bool { - // For now, we'll fix the type of the start function and the table to extract it from - name == "[thread-new-indirect-v0]" - } - fn thread_resume_later(&self, name: &str) -> bool { - name == "[thread-resume-later]" - } - fn thread_suspend(&self, name: &str) -> Option> { - self.match_with_cancellable_prefix(name, "[thread-suspend]") - } - fn thread_yield(&self, name: &str) -> Option> { - self.match_with_cancellable_prefix(name, "[thread-yield]") - } - fn thread_suspend_then_resume(&self, name: &str) -> Option> { - self.match_with_cancellable_prefix(name, "[thread-suspend-then-resume]") - } - fn thread_yield_then_resume(&self, name: &str) -> Option> { - self.match_with_cancellable_prefix(name, "[thread-yield-then-resume]") - } - fn thread_suspend_then_promote(&self, name: &str) -> Option> { - self.match_with_cancellable_prefix(name, "[thread-suspend-then-promote]") - } - fn thread_yield_then_promote(&self, name: &str) -> Option> { - self.match_with_cancellable_prefix(name, "[thread-yield-then-promote]") - } - fn future_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option { - self.prefixed_payload(lookup_context, name, "[future-new-") - } - fn future_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[future-write-") - } - fn future_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[future-read-") - } - fn future_cancel_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[future-cancel-write-") - } - fn future_cancel_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[future-cancel-read-") - } - fn future_drop_writable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option { - self.prefixed_payload(lookup_context, name, "[future-drop-writable-") - } - fn future_drop_readable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option { - self.prefixed_payload(lookup_context, name, "[future-drop-readable-") - } - fn stream_new(&self, lookup_context: &PayloadLookupContext, name: &str) -> Option { - self.prefixed_payload(lookup_context, name, "[stream-new-") - } - fn stream_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[stream-write-") - } - fn stream_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[stream-read-") - } - fn stream_cancel_write( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[stream-cancel-write-") - } - fn stream_cancel_read( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option> { - self.maybe_async_lowered_payload(lookup_context, name, "[stream-cancel-read-") - } - fn stream_drop_writable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option { - self.prefixed_payload(lookup_context, name, "[stream-drop-writable-") - } - fn stream_drop_readable( - &self, - lookup_context: &PayloadLookupContext, - name: &str, - ) -> Option { - self.prefixed_payload(lookup_context, name, "[stream-drop-readable-") - } - fn module_to_interface( - &self, - module: &str, - resolve: &Resolve, - items: &IndexMap, - ) -> Result<(WorldKey, InterfaceId)> { - // First see if this is a bare name - let bare_name = WorldKey::Name(module.to_string()); - if let Some(WorldItem::Interface { id, .. }) = items.get(&bare_name) { - return Ok((bare_name, *id)); - } - - // ... and if this isn't a bare name then it's time to do some parsing - // related to interfaces, versions, and such. First up the `module` name - // is parsed as a normal component name from `wasmparser` to see if it's - // of the "interface kind". If it's not then that means the above match - // should have been a hit but it wasn't, so an error is returned. - let kebab_name = ComponentName::new(module, 0); - let name = match kebab_name.as_ref().map(|k| k.kind()) { - Ok(ComponentNameKind::Interface(name)) => name, - _ => bail!("module requires an import interface named `{module}`"), - }; - - // FIXME: this prevents core wasm from importing from `@1` or - // `@0.1`, for example. More refactoring will be necessary to enable - // that. - let version = name.version(None)?; - - // Prioritize an exact match based on versions, so try that first. - let pkgname = PackageName { - namespace: name.namespace().to_string(), - name: name.package().to_string(), - version: version.clone(), - }; - if let Some(pkg) = resolve.package_names.get(&pkgname) { - if let Some(id) = resolve.packages[*pkg] - .interfaces - .get(name.interface().as_str()) - { - // If the interface from the package is directly in `items` then - // return that. - let key = WorldKey::Interface(*id); - if items.contains_key(&key) { - return Ok((key, *id)); - } - - // .. otherwise see if any interface in `items` is a clone of - // the package's interface. This means it's created by - // `generate_nominal_type_ids` and is used to match up exports - // to their nominal clone since the original is no longer - // exported. - for k in items.keys() { - let i = match *k { - WorldKey::Interface(id) => id, - WorldKey::Name(_) => continue, - }; - if resolve.interfaces[i].clone_of == Some(*id) { - return Ok((WorldKey::Interface(i), i)); - } - } - } - } - - // If an exact match wasn't found then instead search for the first - // match based on versions. This means that a core wasm import for - // "1.2.3" might end up matching an interface at "1.2.4", for example. - // (or "1.2.2", depending on what's available). - for (key, _) in items { - let id = match key { - WorldKey::Interface(id) => *id, - WorldKey::Name(_) => continue, - }; - // Make sure the interface names match - let interface = &resolve.interfaces[id]; - if interface.name.as_ref().unwrap() != name.interface().as_str() { - continue; - } - - // Make sure the package name (without version) matches - let pkg = &resolve.packages[interface.package.unwrap()]; - if pkg.name.namespace != pkgname.namespace || pkg.name.name != pkgname.name { - continue; - } - - let module_version = match &version { - Some(version) => version, - None => continue, - }; - let pkg_version = match &pkg.name.version { - Some(version) => version, - None => continue, - }; - - // Test if the two semver versions are compatible - let module_compat = PackageName::version_compat_track(&module_version); - let pkg_compat = PackageName::version_compat_track(pkg_version); - if module_compat == pkg_compat { - return Ok((key.clone(), id)); - } - } - - bail!("module requires an import interface named `{module}`") - } - fn strip_post_return<'a>(&self, name: &'a str) -> Option<&'a str> { - name.strip_prefix("cabi_post_") - } - fn match_wit_export<'a>( - &self, - export_name: &str, - resolve: &'a Resolve, - world: WorldId, - exports: &'a IndexSet, - ) -> Option<(&'a WorldKey, Option, &'a Function)> { - let world = &resolve.worlds[world]; - for name in exports { - match &world.exports[name] { - WorldItem::Function(f) => { - if f.legacy_core_export_name(None) == export_name { - return Some((name, None, f)); - } - } - WorldItem::Interface { id, .. } => { - let string = resolve.name_world_key(name); - for (_, func) in resolve.interfaces[*id].functions.iter() { - if func.legacy_core_export_name(Some(&string)) == export_name { - return Some((name, Some(*id), func)); - } - } - } - - WorldItem::Type { .. } => unreachable!(), - } - } - - None - } - - fn match_wit_resource_dtor<'a>( - &self, - export_name: &str, - resolve: &'a Resolve, - world: WorldId, - exports: &'a IndexSet, - ) -> Option { - let world = &resolve.worlds[world]; - for name in exports { - let id = match &world.exports[name] { - WorldItem::Interface { id, .. } => *id, - WorldItem::Function(_) => continue, - WorldItem::Type { .. } => unreachable!(), - }; - let name = resolve.name_world_key(name); - let resource = match export_name - .strip_prefix(&name) - .and_then(|s| s.strip_prefix("#[dtor]")) - .and_then(|r| resolve.interfaces[id].types.get(r)) - { - Some(id) => *id, - None => continue, - }; - - match resolve.types[resource].kind { - TypeDefKind::Resource => {} - _ => continue, - } - - return Some(resource); - } - - None - } - - fn world_key_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { - let (async_abi, name) = self.strip_async_lowered_prefix(name); - ( - name, - if async_abi { - AbiVariant::GuestImportAsync - } else { - AbiVariant::GuestImport - }, - ) - } - fn interface_function_name_and_abi<'a>(&self, name: &'a str) -> (&'a str, AbiVariant) { - let (async_abi, name) = self.strip_async_lowered_prefix(name); - ( - name, - if async_abi { - AbiVariant::GuestImportAsync - } else { - AbiVariant::GuestImport - }, - ) - } - fn env_import(&self, name: &str, ty: &FuncType) -> Option { - match name { - "__wasm_get_stack_pointer" => { - let ty = *ty.results().get(0)?; - Some(Import::ContextGet { ty, slot: 0 }) - } - "__wasm_set_stack_pointer" => { - let ty = *ty.params().get(0)?; - Some(Import::ContextSet { ty, slot: 0 }) - } - // TLS handling is slightly different than above to handle - // coop-threading-vs-not, so the exact resolution of this import is - // deferred to later. - "__wasm_get_tls_base" => { - let ty = *ty.results().get(0)?; - Some(Import::TlsBaseGet { ty }) - } - "__wasm_set_tls_base" => { - let ty = *ty.params().get(0)?; - Some(Import::TlsBaseSet { ty }) - } - _ => None, - } - } -} - -/// This function validates the following: -/// -/// * The `bytes` represent a valid core WebAssembly module. -/// * The module's imports are all satisfied by the given `imports` interfaces -/// or the `adapters` set. -/// * The given default and exported interfaces are satisfied by the module's -/// exports. -/// -/// The `ValidatedModule` return value contains the metadata which describes the -/// input module on success. This is then further used to generate a component -/// for this module. -pub fn validate_module( - encoder: &ComponentEncoder, - bytes: &[u8], - import_map: Option<&ModuleImportMap>, -) -> Result { - ValidatedModule::new( - encoder, - bytes, - &encoder.main_module_exports, - import_map, - None, - ) -} - -/// This function will validate the `bytes` provided as a wasm adapter module. -/// Notably this will validate the wasm module itself in addition to ensuring -/// that it has the "shape" of an adapter module. Current constraints are: -/// -/// * The adapter module can import only one memory -/// * The adapter module can only import from the name of `interface` specified, -/// and all function imports must match the `required` types which correspond -/// to the lowered types of the functions in `interface`. -/// -/// The wasm module passed into this function is the output of the GC pass of an -/// adapter module's original source. This means that the adapter module is -/// already minimized and this is a double-check that the minimization pass -/// didn't accidentally break the wasm module. -/// -/// If `is_library` is true, we waive some of the constraints described above, -/// allowing the module to import tables and globals, as well as import -/// functions at the world level, not just at the interface level. -pub fn validate_adapter_module( - encoder: &ComponentEncoder, - bytes: &[u8], - required_by_import: &IndexMap, - exports: &IndexSet, - library_info: Option<&LibraryInfo>, -) -> Result { - let ret = ValidatedModule::new(encoder, bytes, exports, None, library_info)?; - - for (name, required_ty) in required_by_import { - let actual = match ret.exports.raw_exports.get(name) { - Some(ty) => ty, - None => return Err(AdapterModuleDidNotExport(name.clone()).into()), - }; - validate_func_sig(name, required_ty, &actual)?; - } - - Ok(ret) -} - -/// An error that can be returned from adapting a core Wasm module into a -/// component using an adapter module. -/// -/// If the core Wasm module contained an import that it requires to be -/// satisfied by the adapter, and the adapter does not contain an export -/// with the same name, an instance of this error is returned. -#[derive(Debug, Clone)] -pub struct AdapterModuleDidNotExport(String); - -impl fmt::Display for AdapterModuleDidNotExport { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "adapter module did not export `{}`", self.0) - } -} - -impl std::error::Error for AdapterModuleDidNotExport {} - -fn resource_test_for_interface<'a>( - resolve: &'a Resolve, - id: InterfaceId, -) -> impl Fn(&str) -> Option + 'a { - let interface = &resolve.interfaces[id]; - move |name: &str| { - let ty = match interface.types.get(name) { - Some(ty) => *ty, - None => return None, - }; - if matches!(resolve.types[ty].kind, TypeDefKind::Resource) { - Some(ty) - } else { - None - } - } -} - -fn resource_test_for_world<'a>( - resolve: &'a Resolve, - id: WorldId, -) -> impl Fn(&str) -> Option + 'a { - let world = &resolve.worlds[id]; - move |name: &str| match world.imports.get(&WorldKey::Name(name.to_string()))? { - WorldItem::Type { id, .. } => { - if matches!(resolve.types[*id].kind, TypeDefKind::Resource) { - Some(*id) - } else { - None - } - } - _ => None, - } -} - -fn validate_func( - resolve: &Resolve, - ty: &wasmparser::FuncType, - func: &Function, - abi: AbiVariant, -) -> Result<()> { - validate_func_sig( - &func.name, - &wasm_sig_to_func_type(resolve.wasm_signature(abi, func)), - ty, - ) -} - -fn validate_post_return( - resolve: &Resolve, - ty: &wasmparser::FuncType, - func: &Function, -) -> Result<()> { - // The expected signature of a post-return function is to take all the - // parameters that are returned by the guest function and then return no - // results. Model this by calculating the signature of `func` and then - // moving its results into the parameters list while emptying out the - // results. - let mut sig = resolve.wasm_signature(AbiVariant::GuestExport, func); - sig.params = mem::take(&mut sig.results); - validate_func_sig( - &format!("{} post-return", func.name), - &wasm_sig_to_func_type(sig), - ty, - ) -} - -fn validate_func_sig(name: &str, expected: &FuncType, ty: &wasmparser::FuncType) -> Result<()> { - if ty != expected { - bail!( - "type mismatch for function `{}`: expected `{:?} -> {:?}` but found `{:?} -> {:?}`", - name, - expected.params(), - expected.results(), - ty.params(), - ty.results() - ); - } - - Ok(()) -} - -/// Matches `name` as `[${prefix}S]...`, and if found returns `("S", "...")` -fn prefixed_intrinsic<'a>(name: &'a str, prefix: &str) -> Option<(&'a str, &'a str)> { - assert!(prefix.starts_with("[")); - assert!(prefix.ends_with("-")); - let suffix = name.strip_prefix(prefix)?; - let index = suffix.find(']')?; - let rest = &suffix[index + 1..]; - Some((&suffix[..index], rest)) -} - -/// Parses a `[context-get-]` / `[context-set-]` style name, optionally -/// carrying a type width infix: `[context-get-i64-]`. -/// -/// Returns the value type together with the numeric slot. Additional type -/// widths can be added here by extending the match below. -fn parse_context_name(name: &str, prefix: &str) -> Option<(ValType, u32)> { - let (suffix, rest) = prefixed_intrinsic(name, prefix)?; - if !rest.is_empty() { - return None; - } - let (ty, slot) = match suffix.split_once('-') { - Some(("i64", slot)) => (ValType::I64, slot), - Some(("i32", slot)) => (ValType::I32, slot), - _ => (ValType::I32, suffix), - }; - let slot = slot.parse().ok()?; - Some((ty, slot)) -} - -fn get_function<'a>( - resolve: &'a Resolve, - world: &'a World, - name: &str, - interface: Option, - imported: bool, -) -> Result<&'a Function> { - let function = if let Some(id) = interface { - return resolve.interfaces[id] - .functions - .get(name) - .ok_or_else(|| anyhow!("no export `{name}` found")); - } else if imported { - world.imports.get(&WorldKey::Name(name.to_string())) - } else { - world.exports.get(&WorldKey::Name(name.to_string())) - }; - let Some(WorldItem::Function(function)) = function else { - bail!("no export `{name}` found"); - }; - Ok(function) -}