diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 5d5a07b..65210fe 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -11,11 +11,11 @@ use { anyhow::{Error, Result}, bindings::{ + environment, exports::exports::{ self as exp, Constructor, FunctionExportKind, Guest, OptionKind, ResultRecord, ReturnStyle, Static, Symbols, }, - wasi::cli0_2_0::environment, }, num_bigint::BigUint, once_cell::sync::OnceCell, @@ -42,13 +42,31 @@ use { }, }; +#[cfg(not(feature = "async"))] mod bindings { wit_bindgen::generate!({ - world: "init", + world: "init-p2", path: "../wit", generate_all, }); + pub use wasi::cli0_2_0::environment; + + use super::MyExports; + + export!(MyExports); +} + +#[cfg(feature = "async")] +mod bindings { + wit_bindgen::generate!({ + world: "init-p3", + path: "../wit", + generate_all, + }); + + pub use wasi::cli0_3_0::environment; + use super::MyExports; export!(MyExports); @@ -1197,10 +1215,17 @@ impl Guest for MyExports { // In particular, we want it to forget about any open handles and // re-request the stdio handles at runtime since we'll be running under // a brand new host. - #[link(wasm_import_module = "wasi_snapshot_preview1")] - unsafe extern "C" { - #[link_name = "reset_adapter_state"] - fn reset_adapter_state(); + #[cfg(not(feature = "async"))] + { + #[link(wasm_import_module = "wasi_snapshot_preview1")] + unsafe extern "C" { + #[link_name = "reset_adapter_state"] + fn reset_adapter_state(); + } + + unsafe { + reset_adapter_state(); + } } // This tells wasi-libc to reset its preopen state, forcing @@ -1212,7 +1237,6 @@ impl Guest for MyExports { } unsafe { - reset_adapter_state(); wasilibc_reset_preopens(); } diff --git a/src/lib.rs b/src/lib.rs index 46ba4cc..d1b7b53 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -786,7 +786,23 @@ impl ComponentGenerator<'_> { )? .need_async(); - if need_async { + let has_wasip3_world = resolve.worlds[world] + .imports + .keys() + .chain(resolve.worlds[world].exports.keys()) + .any(|key| match key { + WorldKey::Interface(id) => resolve.interfaces[*id].package.is_some_and(|pkg| { + let name = &resolve.packages[pkg].name; + name.namespace == "wasi" + && name + .version + .as_ref() + .is_some_and(|v| v.major == 0 && v.minor == 3) + }), + WorldKey::Name(_) => false, + }); + + if need_async || has_wasip3_world { Target::Wasip3(Multithreading::Disabled) } else { Target::Wasip2 @@ -886,10 +902,10 @@ impl ComponentGenerator<'_> { &stream_and_future_indexes, )?; - let component = link::link_libraries(&libraries)?; + let component = link::link_libraries(&libraries, target)?; let stubbed_component = if self.stub_wasi { - stubwasi::link_stub_modules(libraries)? + stubwasi::link_stub_modules(libraries, target)? } else { None }; diff --git a/src/link.rs b/src/link.rs index 8679386..272fa6f 100644 --- a/src/link.rs +++ b/src/link.rs @@ -2,9 +2,9 @@ use std::io::Cursor; use anyhow::Result; -use crate::Library; +use crate::{Library, Target}; -pub fn link_libraries(libraries: &[Library]) -> Result> { +pub fn link_libraries(libraries: &[Library], target: Target) -> Result> { let mut linker = wit_component::Linker::default(); linker.use_built_in_libdl(true).encoder().validate(true); @@ -17,13 +17,15 @@ pub fn link_libraries(libraries: &[Library]) -> Result> { linker.library(name, module, *dl_openable)?; } - linker.encoder().adapter( - "wasi_snapshot_preview1", - &zstd::decode_all(Cursor::new(include_bytes!(concat!( - env!("OUT_DIR"), - "/wasi_snapshot_preview1.reactor.wasm.zst" - ))))?, - )?; + if matches!(target, Target::Wasip2) { + linker.encoder().adapter( + "wasi_snapshot_preview1", + &zstd::decode_all(Cursor::new(include_bytes!(concat!( + env!("OUT_DIR"), + "/wasi_snapshot_preview1.reactor.wasm.zst" + ))))?, + )?; + } linker.encode().map_err(|e| anyhow::anyhow!(e)) } diff --git a/src/stubwasi.rs b/src/stubwasi.rs index d34c7e6..db58484 100644 --- a/src/stubwasi.rs +++ b/src/stubwasi.rs @@ -7,11 +7,14 @@ use wasm_encoder::{ }; use wasmparser::{FuncType, Imports, Parser, Payload, TypeRef}; -use crate::Library; +use crate::{Library, Target}; type LinkedStubModules = Option<(Vec, Box u32>)>; -pub fn link_stub_modules(libraries: Vec) -> Result { +pub fn link_stub_modules( + libraries: Vec, + target: Target, +) -> Result { let mut wasi_imports = BTreeMap::new(); let mut linker = wit_component::Linker::default(); linker.use_built_in_libdl(true).encoder().validate(true); @@ -46,7 +49,10 @@ pub fn link_stub_modules(libraries: Vec) -> Result 1, + Target::Wasip3(_) => 0, + }; let new_adapter_count = u32::try_from(wasi_imports.len())?; assert!(new_adapter_count >= old_adapter_count); @@ -57,8 +63,8 @@ pub fn link_stub_modules(libraries: Vec) -> Result) -> Result<()> { - wasmtime_wasi::p2::add_to_linker_async(linker)?; wasmtime_wasi::p3::add_to_linker(linker)?; Tests::add_to_linker::<_, HasSelf<_>>(linker, |ctx| ctx)?; foo_sdk::FooWorldUnion::add_to_linker::<_, HasSelf<_>>(linker, |ctx| ctx)?; @@ -149,8 +148,10 @@ struct FooHost; impl super::Host for FooHost { type World = foo_sdk::FooWorldUnion; - fn add_to_linker(_linker: &mut Linker) -> Result<()> { - unreachable!() + fn add_to_linker(linker: &mut Linker) -> Result<()> { + wasmtime_wasi::p2::add_to_linker_async(linker)?; + foo_sdk::FooWorldUnion::add_to_linker::<_, HasSelf<_>>(linker, |ctx| ctx)?; + Ok(()) } async fn instantiate_pre(store: &mut Store, pre: InstancePre) -> Result { @@ -929,7 +930,7 @@ fn multiworld_intersect() -> Result<()> { } } - let tester = Tester::::new( + let tester = Tester::::new( "package dummy:dummy;", &[], None, @@ -2120,3 +2121,136 @@ class ResourceAggregates(_AggregatesBase, exports.ResourceAggregates): Ok(()) } + +#[test] +fn pure_wasip3_sync_world_and_stub_wasi() -> Result<()> { + use std::{fs, path::Path}; + + let tempdir = tempfile::tempdir()?; + fs::write( + tempdir.path().join("app.py"), + r#"import wit +from wit.imports.wasi.random_v0_3 import random as wasi_random + +@wit.guest +class App(wit.WorldExports): + def run(self) -> int: + return len(wasi_random.get_random_bytes(4)) +"#, + )?; + fs::write( + tempdir.path().join("stub_app.py"), + r#"import wit + +@wit.guest +class App(wit.WorldExports): + def run(self) -> int: + return 42 +"#, + )?; + + let wit_dir = Path::new("wit"); + fs::write( + tempdir.path().join("test.wit"), + r#"package test:pure-p3; + +world sync-p3 { + import wasi:random/random@0.3.0; + export run: func() -> u32; +} + +world stub-p3 { + export run: func() -> u32; +} +"#, + )?; + fs::create_dir_all(tempdir.path().join("deps"))?; + fs_extra::dir::copy( + wit_dir.join("deps/random-0.3.0"), + tempdir.path().join("deps"), + &fs_extra::dir::CopyOptions::new(), + )?; + + let runtime = tokio::runtime::Runtime::new()?; + let py_dir = tempdir.path().to_str().unwrap(); + + // 1. Sync world importing a WASI 0.3 interface auto-selects `wasip3` and + // instantiates against a pure WASIp3 linker (no WASIp2 bindings registered). + let sync_wasm = tempdir.path().join("sync.wasm"); + runtime.block_on( + crate::ComponentGenerator { + wit_paths: &[tempdir.path()], + worlds: &["sync-p3"], + features: &[], + all_features: false, + bindings_module: None, + python_path: &[py_dir], + module_worlds: &[], + app_name: "app", + output_path: &sync_wasm, + add_to_linker: None, + stub_wasi: false, + import_interface_names: &std::collections::HashMap::new(), + export_interface_names: &std::collections::HashMap::new(), + intersect_world: None, + registry_config: None, + default_registries: false, + target: None, + } + .generate(), + )?; + + let mut p3_linker = Linker::::new(&super::ENGINE); + wasmtime_wasi::p3::add_to_linker(&mut p3_linker)?; + let component = wasmtime::component::Component::new(&super::ENGINE, fs::read(&sync_wasm)?)?; + let mut store = Store::new( + &super::ENGINE, + Ctx { + wasi: WasiCtxBuilder::new().build(), + table: wasmtime::component::ResourceTable::new(), + }, + ); + let instance = runtime.block_on(p3_linker.instantiate_async(&mut store, &component))?; + let func = instance.get_typed_func::<(), (u32,)>(&mut store, "run")?; + let (len,) = runtime + .block_on(store.run_concurrent(async |store| func.call_concurrent(store, ()).await))??; + assert_eq!(len, 4); + + // 2. `--stub-wasi` with `--target=wasm32-wasip3` builds and instantiates on an empty linker. + let stub_wasm = tempdir.path().join("stub.wasm"); + runtime.block_on( + crate::ComponentGenerator { + wit_paths: &[tempdir.path()], + worlds: &["stub-p3"], + features: &[], + all_features: false, + bindings_module: None, + python_path: &[py_dir], + module_worlds: &[], + app_name: "stub_app", + output_path: &stub_wasm, + add_to_linker: None, + stub_wasi: true, + import_interface_names: &std::collections::HashMap::new(), + export_interface_names: &std::collections::HashMap::new(), + intersect_world: None, + registry_config: None, + default_registries: false, + target: Some(crate::Target::Wasip3(crate::Multithreading::Disabled)), + } + .generate(), + )?; + + let empty_linker = Linker::::new(&super::ENGINE); + let stub_component = + wasmtime::component::Component::new(&super::ENGINE, fs::read(&stub_wasm)?)?; + let stub_instance = + runtime.block_on(empty_linker.instantiate_async(&mut store, &stub_component))?; + let stub_func = stub_instance.get_typed_func::<(), (u32,)>(&mut store, "run")?; + let (ans,) = runtime.block_on( + store.run_concurrent(async |store| stub_func.call_concurrent(store, ()).await), + )??; + assert_eq!(ans, 42); + + Ok(()) +} diff --git a/wit/init.wit b/wit/init.wit index 8f0a97f..dd3848e 100644 --- a/wit/init.wit +++ b/wit/init.wit @@ -1,8 +1,6 @@ package componentize-py:init; world init { - import wasi:cli/environment@0.2.0; - export exports: interface { // `scope`: registry key -- interface name, bindings module for // world-level exports, or `#` for a resource. @@ -101,3 +99,13 @@ world init { init: async func(app-name: string, symbols: symbols, stub-wasi: bool) -> result<_, string>; } } + +world init-p2 { + include init; + import wasi:cli/environment@0.2.0; +} + +world init-p3 { + include init; + import wasi:cli/environment@0.3.0; +}