Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 31 additions & 7 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -1212,7 +1237,6 @@ impl Guest for MyExports {
}

unsafe {
reset_adapter_state();
wasilibc_reset_preopens();
}

Expand Down
22 changes: 19 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
};
Expand Down
20 changes: 11 additions & 9 deletions src/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>> {
pub fn link_libraries(libraries: &[Library], target: Target) -> Result<Vec<u8>> {
let mut linker = wit_component::Linker::default();
linker.use_built_in_libdl(true).encoder().validate(true);

Expand All @@ -17,13 +17,15 @@ pub fn link_libraries(libraries: &[Library]) -> Result<Vec<u8>> {
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))
}
16 changes: 11 additions & 5 deletions src/stubwasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>, Box<dyn Fn(u32) -> u32>)>;

pub fn link_stub_modules(libraries: Vec<Library>) -> Result<LinkedStubModules, Error> {
pub fn link_stub_modules(
libraries: Vec<Library>,
target: Target,
) -> Result<LinkedStubModules, Error> {
let mut wasi_imports = BTreeMap::new();
let mut linker = wit_component::Linker::default();
linker.use_built_in_libdl(true).encoder().validate(true);
Expand Down Expand Up @@ -46,7 +49,10 @@ pub fn link_stub_modules(libraries: Vec<Library>) -> Result<LinkedStubModules, E
// `wit_component::Linker`'s implementation changes. Can we make it more
// robust?

let old_adapter_count = 1;
let old_adapter_count = match target {
Target::Wasip2 => 1,
Target::Wasip3(_) => 0,
};
let new_adapter_count = u32::try_from(wasi_imports.len())?;
assert!(new_adapter_count >= old_adapter_count);

Expand All @@ -57,8 +63,8 @@ pub fn link_stub_modules(libraries: Vec<Library>) -> Result<LinkedStubModules, E
// `main` module
0
} else if index <= new_adapter_count {
// adapter module
old_adapter_count
// stub adapter module (no stage-1 memory or globals)
u32::MAX
} else {
// one of the other kinds of module
index + old_adapter_count - new_adapter_count
Expand Down
142 changes: 138 additions & 4 deletions src/test/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ impl super::Host for Host {
type World = Tests;

fn add_to_linker(linker: &mut Linker<Ctx>) -> 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)?;
Expand All @@ -149,8 +148,10 @@ struct FooHost;
impl super::Host for FooHost {
type World = foo_sdk::FooWorldUnion;

fn add_to_linker(_linker: &mut Linker<Ctx>) -> Result<()> {
unreachable!()
fn add_to_linker(linker: &mut Linker<Ctx>) -> 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<Ctx>, pre: InstancePre<Ctx>) -> Result<Self::World> {
Expand Down Expand Up @@ -929,7 +930,7 @@ fn multiworld_intersect() -> Result<()> {
}
}

let tester = Tester::<Host>::new(
let tester = Tester::<FooHost>::new(
"package dummy:dummy;",
&[],
None,
Expand Down Expand Up @@ -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::<Ctx>::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::<Ctx>::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(())
}
12 changes: 10 additions & 2 deletions wit/init.wit
Original file line number Diff line number Diff line change
@@ -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 `<scope>#<resource>` for a resource.
Expand Down Expand Up @@ -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;
}
Loading