From b7b695134f8f3a6a6e937545da86ae59defa98b3 Mon Sep 17 00:00:00 2001 From: Andrew Brown Date: Thu, 13 Oct 2022 15:34:52 -0700 Subject: [PATCH] wasi-threads: add an initial implementation (WIP) This change demonstrates a first step at how `wasi-threads` might be implemented in Wasmtime. It has hacks (described below), so it should only be consided a highly-experimental, use-at-your-own-risk work in progress. The included test file can be run with the following incantation (the `+nightly` is to allow the `Arc`-mutation hack): ``` cargo +nightly run -p wasmtime-cli --features wasi-threads -- \ tests/all/cli_tests/threads.wat \ --wasm-features threads --wasi-modules experimental-wasi-threads ``` Implementing this highlights two large issues still to be resolved: - _`Host` sharing_: the approach taken here is to clone the `Linker` so that `wasi-threads` has a separate version of it and to share the `Host` among threads using an `Arc`. This does nothing to protect the `Host` state from concurrent access--which it must be in a future iteration of this. This could be done with, e.g., a `Mutex` per WASI proposal, preventing any concurrent access for any method in that proposal, but unfortunately the signature of `get_cx` prevents me from using the `MutexGuard`. Some more refactoring and thinking is necessary here; suggestions welcome. - _Guest code traps_: this change has no way to recover from traps in the user function and return control to the thread entry point, which may be responsible for clean up (e.g., in C, `notify` any `pthread_join`ers that execution is complete). Note that the associated CLI test fails, but probably just due to my misunderstanding how to correctly tell the WAT library to enable the threads proposal: ``` cargo +nightly test --features wasi-threads -p wasmtime-cli -- cli_tests ``` --- Cargo.lock | 11 ++ Cargo.toml | 5 +- crates/cli-flags/src/lib.rs | 36 ++++-- crates/wasi-threads/Cargo.toml | 21 +++ crates/wasi-threads/LICENSE | 220 ++++++++++++++++++++++++++++++++ crates/wasi-threads/README.md | 3 + crates/wasi-threads/src/lib.rs | 126 ++++++++++++++++++ src/commands/run.rs | 95 ++++++++++---- src/lib.rs | 8 +- tests/all/cli_tests.rs | 21 +++ tests/all/cli_tests/threads.wat | 55 ++++++++ 11 files changed, 561 insertions(+), 40 deletions(-) create mode 100644 crates/wasi-threads/Cargo.toml create mode 100644 crates/wasi-threads/LICENSE create mode 100644 crates/wasi-threads/README.md create mode 100644 crates/wasi-threads/src/lib.rs create mode 100644 tests/all/cli_tests/threads.wat diff --git a/Cargo.lock b/Cargo.lock index c95dc916e04c..fa72d1990f2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3499,6 +3499,7 @@ dependencies = [ "wasmtime-wasi", "wasmtime-wasi-crypto", "wasmtime-wasi-nn", + "wasmtime-wasi-threads", "wasmtime-wast", "wast 50.0.0", "wat", @@ -3766,6 +3767,16 @@ dependencies = [ "wiggle", ] +[[package]] +name = "wasmtime-wasi-threads" +version = "5.0.0" +dependencies = [ + "anyhow", + "log", + "rand 0.8.5", + "wasmtime", +] + [[package]] name = "wasmtime-wast" version = "5.0.0" diff --git a/Cargo.toml b/Cargo.toml index b17382b57747..4f804f768c77 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ wasmtime-wast = { workspace = true } wasmtime-wasi = { workspace = true } wasmtime-wasi-crypto = { workspace = true, optional = true } wasmtime-wasi-nn = { workspace = true, optional = true } +wasmtime-wasi-threads = { workspace = true, optional = true } clap = { workspace = true, features = ["color", "suggestions", "derive"] } anyhow = { workspace = true } target-lexicon = { workspace = true } @@ -87,6 +88,7 @@ members = [ "crates/bench-api", "crates/c-api", "crates/cli-flags", + "crates/wasi-threads", "crates/environ/fuzz", "crates/jit-icache-coherence", "crates/winch", @@ -123,6 +125,7 @@ wasmtime-wast = { path = "crates/wast", version = "=5.0.0" } wasmtime-wasi = { path = "crates/wasi", version = "5.0.0" } wasmtime-wasi-crypto = { path = "crates/wasi-crypto", version = "5.0.0" } wasmtime-wasi-nn = { path = "crates/wasi-nn", version = "5.0.0" } +wasmtime-wasi-threads = { path = "crates/wasi-threads", version = "5.0.0" } wasmtime-component-util = { path = "crates/component-util", version = "=5.0.0" } wasmtime-component-macro = { path = "crates/component-macro", version = "=5.0.0" } wasmtime-asm-macros = { path = "crates/asm-macros", version = "=5.0.0" } @@ -191,13 +194,13 @@ default = [ "wasmtime/wat", "wasmtime/parallel-compilation", "vtune", - "wasi-nn", "pooling-allocator", ] jitdump = ["wasmtime/jitdump"] vtune = ["wasmtime/vtune"] wasi-crypto = ["dep:wasmtime-wasi-crypto"] wasi-nn = ["dep:wasmtime-wasi-nn"] +wasi-threads = ["dep:wasmtime-wasi-threads"] pooling-allocator = ["wasmtime/pooling-allocator", "wasmtime-cli-flags/pooling-allocator"] all-arch = ["wasmtime/all-arch"] posix-signals-on-macos = ["wasmtime/posix-signals-on-macos"] diff --git a/crates/cli-flags/src/lib.rs b/crates/cli-flags/src/lib.rs index 279712cbc9f7..e0cb7b7d0e57 100644 --- a/crates/cli-flags/src/lib.rs +++ b/crates/cli-flags/src/lib.rs @@ -50,13 +50,17 @@ pub const SUPPORTED_WASI_MODULES: &[(&str, &str)] = &[ "wasi-common", "enables support for the WASI common APIs, see https://github.com/WebAssembly/WASI", ), + ( + "experimental-wasi-crypto", + "enables support for the WASI cryptography APIs (experimental), see https://github.com/WebAssembly/wasi-crypto", + ), ( "experimental-wasi-nn", "enables support for the WASI neural network API (experimental), see https://github.com/WebAssembly/wasi-nn", ), ( - "experimental-wasi-crypto", - "enables support for the WASI cryptography APIs (experimental), see https://github.com/WebAssembly/wasi-crypto", + "experimental-wasi-threads", + "enables support for the WASI threading API (experimental), see https://github.com/WebAssembly/wasi-threads", ), ]; @@ -477,8 +481,9 @@ fn parse_wasi_modules(modules: &str) -> Result { let mut set = |module: &str, enable: bool| match module { "" => Ok(()), "wasi-common" => Ok(wasi_modules.wasi_common = enable), - "experimental-wasi-nn" => Ok(wasi_modules.wasi_nn = enable), "experimental-wasi-crypto" => Ok(wasi_modules.wasi_crypto = enable), + "experimental-wasi-nn" => Ok(wasi_modules.wasi_nn = enable), + "experimental-wasi-threads" => Ok(wasi_modules.wasi_threads = enable), "default" => bail!("'default' cannot be specified with other WASI modules"), _ => bail!("unsupported WASI module '{}'", module), }; @@ -505,19 +510,23 @@ pub struct WasiModules { /// parts once the implementation allows for it (e.g. wasi-fs, wasi-clocks, etc.). pub wasi_common: bool, - /// Enable the experimental wasi-nn implementation + /// Enable the experimental wasi-crypto implementation. + pub wasi_crypto: bool, + + /// Enable the experimental wasi-nn implementation. pub wasi_nn: bool, - /// Enable the experimental wasi-crypto implementation - pub wasi_crypto: bool, + /// Enable the experimental wasi-threads implementation. + pub wasi_threads: bool, } impl Default for WasiModules { fn default() -> Self { Self { wasi_common: true, - wasi_nn: false, wasi_crypto: false, + wasi_nn: false, + wasi_threads: false, } } } @@ -529,6 +538,7 @@ impl WasiModules { wasi_common: false, wasi_nn: false, wasi_crypto: false, + wasi_threads: false, } } } @@ -674,8 +684,9 @@ mod test { options.wasi_modules.unwrap(), WasiModules { wasi_common: true, + wasi_crypto: false, wasi_nn: false, - wasi_crypto: false + wasi_threads: false } ); } @@ -687,8 +698,9 @@ mod test { options.wasi_modules.unwrap(), WasiModules { wasi_common: true, + wasi_crypto: false, wasi_nn: false, - wasi_crypto: false + wasi_threads: false } ); } @@ -704,8 +716,9 @@ mod test { options.wasi_modules.unwrap(), WasiModules { wasi_common: false, + wasi_crypto: false, wasi_nn: true, - wasi_crypto: false + wasi_threads: false } ); } @@ -718,8 +731,9 @@ mod test { options.wasi_modules.unwrap(), WasiModules { wasi_common: false, + wasi_crypto: false, wasi_nn: false, - wasi_crypto: false + wasi_threads: false } ); } diff --git a/crates/wasi-threads/Cargo.toml b/crates/wasi-threads/Cargo.toml new file mode 100644 index 000000000000..d017a816579f --- /dev/null +++ b/crates/wasi-threads/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "wasmtime-wasi-threads" +version.workspace = true +authors.workspace = true +description = "Wasmtime implementation of the wasi-threads API" +documentation = "https://docs.rs/wasmtime-wasi-nn" +license = "Apache-2.0 WITH LLVM-exception" +categories = ["wasm", "parallelism", "threads"] +keywords = ["webassembly", "wasm", "neural-network"] +repository = "https://github.com/bytecodealliance/wasmtime" +readme = "README.md" +edition.workspace = true + +[dependencies] +anyhow = { workspace = true } +log = { workspace = true } +rand = "0.8" +wasmtime = { workspace = true } + +[badges] +maintenance = { status = "experimental" } diff --git a/crates/wasi-threads/LICENSE b/crates/wasi-threads/LICENSE new file mode 100644 index 000000000000..f9d81955f4bc --- /dev/null +++ b/crates/wasi-threads/LICENSE @@ -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/crates/wasi-threads/README.md b/crates/wasi-threads/README.md new file mode 100644 index 000000000000..f165ed6d4149 --- /dev/null +++ b/crates/wasi-threads/README.md @@ -0,0 +1,3 @@ +# wasmtime-wasi-threads + +TODO diff --git a/crates/wasi-threads/src/lib.rs b/crates/wasi-threads/src/lib.rs new file mode 100644 index 000000000000..7c455e580aba --- /dev/null +++ b/crates/wasi-threads/src/lib.rs @@ -0,0 +1,126 @@ +//! Implement [`wasi-threads`]. +//! +//! [`wasi-threads`]: https://github.com/WebAssembly/wasi-threads + +use anyhow::{anyhow, Result}; +use rand::Rng; +use std::thread; +use wasmtime::{Caller, Linker, Module, SharedMemory, Store}; + +// This name is a function export designated by the wasi-threads specification: +// https://github.com/WebAssembly/wasi-threads/#detailed-design-discussion +const WASI_ENTRY_POINT: &str = "wasi_thread_start"; + +pub struct WasiThreadsCtx { + module: Module, + linker: Linker, + host: T, +} + +impl WasiThreadsCtx { + pub fn new(module: Module, linker: Linker, host: T) -> Self { + Self { + module, + linker, + host, + } + } + + pub fn spawn(&mut self, thread_start_arg: i32) -> Result { + let module = self.module.clone(); + let host = self.host.clone(); + let linker = self.linker.clone(); + + // Start a Rust thread running a new instance of the current module. + let wasi_thread_id = random_thread_id(); + let builder = thread::Builder::new().name(format!("wasi-thread-{}", wasi_thread_id)); + builder.spawn(move || { + // Convenience function for printing failures, since the `Thread` + // has no way to report a failure to the outer context. + let fail = |msg: String| { + format!( + "wasi-thread-{} exited unsuccessfully: {}", + wasi_thread_id, msg + ) + }; + + // Each new instance is created in its own store. + let mut store = Store::new(&module.engine(), host); + let instance = linker + .instantiate(&mut store, &module) + .expect(&fail("failed to instantiate".into())); + let thread_entry_point = instance + .get_typed_func::<(i32, i32), ()>(&mut store, WASI_ENTRY_POINT) + .expect(&fail(format!( + "failed to find wasi-threads entry point function: {}", + WASI_ENTRY_POINT + ))); + + // Start the thread's entry point; any failures are simply printed + // before exiting the thread. It may be necessary to handle failures + // here somehow, e.g., so that `pthread_join` can be notified if the + // user function traps for some reason (TODO). + match thread_entry_point.call(&mut store, (wasi_thread_id, thread_start_arg)) { + Ok(_) => {} + Err(trap) => panic!("{}", fail(trap.to_string())), + } + })?; + + Ok(wasi_thread_id) + } +} + +/// Helper for generating valid WASI thread IDs (TID). +/// +/// Callers of `wasi_thread_spawn` expect a TID >=0 to indicate a successful +/// spawning of the thread whereas a negative return value indicates an +/// failure to spawn. +fn random_thread_id() -> i32 { + let tid: u32 = rand::thread_rng().gen(); + (tid >> 1) as i32 +} + +/// Manually add the WASI `thread_spawn` function to the linker. +/// +/// It is unclear what namespace the `wasi-threads` proposal should live under: +/// it is not clear if it should be included in any of the `preview*` releases +/// so for the time being its module namespace is simply `"wasi"` (TODO). +pub fn add_to_linker( + linker: &mut wasmtime::Linker, + module: &Module, + get_cx: impl Fn(&mut T) -> &mut WasiThreadsCtx + Send + Sync + Copy + 'static, +) -> anyhow::Result { + linker.func_wrap( + "wasi", + "thread_spawn", + move |mut caller: Caller<'_, T>, start_arg: i32| -> i32 { + let ctx = get_cx(caller.data_mut()); + match ctx.spawn(start_arg) { + Ok(thread_id) => { + assert!(thread_id >= 0, "thread_id = {}", thread_id); + thread_id + } + Err(e) => { + log::error!("failed to spawn thread: {}", e); + -1 + } + } + }, + )?; + + // Find the shared memory import and satisfy it with a newly-created shared + // memory import. This currently does not handle multiple memories (TODO). + for import in module.imports() { + if let Some(m) = import.ty().memory() { + if m.is_shared() { + let mem = SharedMemory::new(module.engine(), m.clone())?; + linker.define(import.module(), import.name(), mem.clone())?; + return Ok(mem); + } + } + } + Err(anyhow!( + "unable to link a shared memory import to the module; a `wasi-threads` \ + module should import a single shared memory as \"memory\"" + )) +} diff --git a/src/commands/run.rs b/src/commands/run.rs index 9b2ed8268a4e..fea35ab0fc82 100644 --- a/src/commands/run.rs +++ b/src/commands/run.rs @@ -3,6 +3,7 @@ use anyhow::{anyhow, bail, Context as _, Result}; use clap::Parser; use once_cell::sync::Lazy; +use std::sync::Arc; use std::thread; use std::time::Duration; use std::{ @@ -21,6 +22,9 @@ use wasmtime_wasi_nn::WasiNnCtx; #[cfg(feature = "wasi-crypto")] use wasmtime_wasi_crypto::WasiCryptoCtx; +#[cfg(feature = "wasi-threads")] +use wasmtime_wasi_threads::WasiThreadsCtx; + fn parse_module(s: &OsStr) -> anyhow::Result { // Do not accept wasmtime subcommand names as the module name match s.to_str() { @@ -164,7 +168,8 @@ impl RunCommand { config.epoch_interruption(true); } let engine = Engine::new(&config)?; - let mut store = Store::new(&engine, Host::default()); + let host = Arc::new(Host::default()); + let mut store = Store::new(&engine, host.clone()); // If fuel has been configured, we want to add the configured // fuel amount to this store. @@ -181,9 +186,14 @@ impl RunCommand { let mut linker = Linker::new(&engine); linker.allow_unknown_exports(self.allow_unknown_exports); + // Read the wasm module binary either as `*.wat` or a raw binary. + let module = self.load_module(linker.engine(), &self.module)?; + populate_with_wasi( + host, &mut store, &mut linker, + module.clone(), preopen_dirs, &argv, &self.vars, @@ -207,7 +217,7 @@ impl RunCommand { // Load the main wasm module. match self - .load_main_module(&mut store, &mut linker) + .load_main_module(&mut store, &mut linker, module) .with_context(|| format!("failed to run main module `{}`", self.module.display())) { Ok(()) => (), @@ -309,7 +319,12 @@ impl RunCommand { result } - fn load_main_module(&self, store: &mut Store, linker: &mut Linker) -> Result<()> { + fn load_main_module( + &self, + store: &mut Store>, + linker: &mut Linker>, + module: Module, + ) -> Result<()> { if let Some(timeout) = self.wasm_timeout { store.set_epoch_deadline(1); let engine = store.engine().clone(); @@ -319,8 +334,6 @@ impl RunCommand { }); } - // Read the wasm module binary either as `*.wat` or a raw binary. - let module = self.load_module(linker.engine(), &self.module)?; // The main module might be allowed to have unknown imports, which // should be defined as traps: if self.trap_unknown_imports { @@ -342,8 +355,8 @@ impl RunCommand { fn invoke_export( &self, - store: &mut Store, - linker: &Linker, + store: &mut Store>, + linker: &Linker>, name: &str, ) -> Result<()> { let func = match linker @@ -357,7 +370,12 @@ impl RunCommand { self.invoke_func(store, func, Some(name)) } - fn invoke_func(&self, store: &mut Store, func: Func, name: Option<&str>) -> Result<()> { + fn invoke_func( + &self, + store: &mut Store>, + func: Func, + name: Option<&str>, + ) -> Result<()> { let ty = func.ty(&store); if ty.params().len() > 0 { eprintln!( @@ -435,16 +453,20 @@ impl RunCommand { #[derive(Default)] struct Host { wasi: Option, - #[cfg(feature = "wasi-nn")] - wasi_nn: Option, #[cfg(feature = "wasi-crypto")] wasi_crypto: Option, + #[cfg(feature = "wasi-nn")] + wasi_nn: Option, + #[cfg(feature = "wasi-threads")] + wasi_threads: Option>>, } /// Populates the given `Linker` with WASI APIs. fn populate_with_wasi( - store: &mut Store, - linker: &mut Linker, + host: Arc, + store: &mut Store>, + linker: &mut Linker>, + module: Module, preopen_dirs: Vec<(String, Dir)>, argv: &[String], vars: &[(String, String)], @@ -453,7 +475,12 @@ fn populate_with_wasi( mut tcplisten: Vec, ) -> Result<()> { if wasi_modules.wasi_common { - wasmtime_wasi::add_to_linker(linker, |host| host.wasi.as_mut().unwrap())?; + wasmtime_wasi::add_to_linker(linker, |host| { + unsafe { Arc::::get_mut_unchecked(host) } + .wasi + .as_mut() + .unwrap() + })?; let mut builder = WasiCtxBuilder::new(); builder = builder.inherit_stdio().args(argv)?.envs(vars)?; @@ -475,7 +502,19 @@ fn populate_with_wasi( builder = builder.preopened_dir(dir, name)?; } - store.data_mut().wasi = Some(builder.build()); + unsafe { Arc::::get_mut_unchecked(store.data_mut()) }.wasi = Some(builder.build()); + } + + if wasi_modules.wasi_crypto { + #[cfg(not(feature = "wasi-crypto"))] + { + bail!("Cannot enable wasi-crypto when the binary is not compiled with this feature."); + } + #[cfg(feature = "wasi-crypto")] + { + wasmtime_wasi_crypto::add_to_linker(linker, |host| host.wasi_crypto.as_mut().unwrap())?; + store.data_mut().wasi_crypto = Some(WasiCryptoCtx::new()); + } } if wasi_modules.wasi_nn { @@ -485,20 +524,32 @@ fn populate_with_wasi( } #[cfg(feature = "wasi-nn")] { - wasmtime_wasi_nn::add_to_linker(linker, |host| host.wasi_nn.as_mut().unwrap())?; - store.data_mut().wasi_nn = Some(WasiNnCtx::new()?); + wasmtime_wasi_nn::add_to_linker(linker, |host| { + unsafe { Arc::::get_mut_unchecked(host) } + .wasi_nn + .as_mut() + .unwrap() + })?; + unsafe { Arc::::get_mut_unchecked(store.data_mut()) }.wasi_nn = + Some(WasiNnCtx::new()?); } } - if wasi_modules.wasi_crypto { - #[cfg(not(feature = "wasi-crypto"))] + if wasi_modules.wasi_threads { + #[cfg(not(feature = "wasi-threads"))] { - bail!("Cannot enable wasi-crypto when the binary is not compiled with this feature."); + bail!("Cannot enable wasi-threads when the binary is not compiled with this feature."); } - #[cfg(feature = "wasi-crypto")] + #[cfg(feature = "wasi-threads")] { - wasmtime_wasi_crypto::add_to_linker(linker, |host| host.wasi_crypto.as_mut().unwrap())?; - store.data_mut().wasi_crypto = Some(WasiCryptoCtx::new()); + wasmtime_wasi_threads::add_to_linker(linker, &module, |host| { + unsafe { Arc::::get_mut_unchecked(host) } + .wasi_threads + .as_mut() + .unwrap() + })?; + unsafe { Arc::::get_mut_unchecked(store.data_mut()) }.wasi_threads = + Some(WasiThreadsCtx::new(module, linker.clone(), host.clone())); } } diff --git a/src/lib.rs b/src/lib.rs index fbe2ceb746fc..bfcfb4c78c6f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,12 +2,7 @@ //! //! This crate implements the Wasmtime command line tools. -#![deny( - missing_docs, - trivial_numeric_casts, - unused_extern_crates, - unstable_features -)] +#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates)] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../clippy.toml")))] #![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))] @@ -22,6 +17,7 @@ clippy::use_self ) )] +#![feature(get_mut_unchecked)] use once_cell::sync::Lazy; use wasmtime_cli_flags::{SUPPORTED_WASI_MODULES, SUPPORTED_WASM_FEATURES}; diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs index b8dbfce83139..86010e869100 100644 --- a/tests/all/cli_tests.rs +++ b/tests/all/cli_tests.rs @@ -473,3 +473,24 @@ fn run_cwasm_from_stdin() -> Result<()> { } Ok(()) } + +#[cfg(feature = "wasi-threads")] +#[test] +fn run_threads() -> Result<()> { + let wasm = build_wasm("tests/all/cli_tests/threads.wat")?; + let stdout = run_wasmtime(&[ + "run", + "--", + wasm.path().to_str().unwrap(), + "--wasi-modules", + "experimental-wasi-threads", + "--wasm-features", + "threads", + "--disable-cache", + ])?; + + assert!(stdout.contains("Hello _start")); + assert!(stdout.contains("Hello wasi_thread_start")); + assert!(stdout.contains("Hello done")); + Ok(()) +} diff --git a/tests/all/cli_tests/threads.wat b/tests/all/cli_tests/threads.wat new file mode 100644 index 000000000000..ca5847a60da8 --- /dev/null +++ b/tests/all/cli_tests/threads.wat @@ -0,0 +1,55 @@ +(module + ;; As we have discussed, it makes sense to make the shared memory an import + ;; so that all + (import "" "memory" (memory $shmem 1 1 shared)) + (import "wasi_snapshot_preview1" "fd_write" + (func $__wasi_fd_write (param i32 i32 i32 i32) (result i32))) + (import "wasi" "thread_spawn" + (func $__wasi_thread_spawn (param i32) (result i32))) + + (func (export "_start") + (local $i i32) + + ;; Print "Hello _start". + (call $print (i32.const 32) (i32.const 13)) + + ;; Print "Hello wasi_thread_start" in several threads. + (drop (call $__wasi_thread_spawn (i32.const 0))) + (drop (call $__wasi_thread_spawn (i32.const 0))) + (drop (call $__wasi_thread_spawn (i32.const 0))) + + ;; Wasmtime has no `wait/notify` yet, so we just spin to allow the threads + ;; to do their work. + (local.set $i (i32.const 2000000)) + (loop $again + (local.set $i (i32.sub (local.get $i) (i32.const 1))) + (br_if $again (i32.gt_s (local.get $i) (i32.const 0))) + ) + + ;; Print "Hello done". + (call $print (i32.const 64) (i32.const 11)) + ) + + ;; A threads-enabled module must export this spec-designated entry point. + (func (export "wasi_thread_start") (param $tid i32) (param $start_arg i32) + (call $print (i32.const 96) (i32.const 24)) + ) + + ;; A helper function for printing ptr-len strings. + (func $print (param $ptr i32) (param $len i32) + (i32.store (i32.const 8) (local.get $len)) + (i32.store (i32.const 4) (local.get $ptr)) + (drop (call $__wasi_fd_write + (i32.const 1) + (i32.const 4) + (i32.const 1) + (i32.const 0))) + ) + + ;; We still need to export the shared memory for Wiggle's sake. + (export "memory" (memory $shmem)) + + (data (i32.const 32) "Hello _start\0a") + (data (i32.const 64) "Hello done\0a") + (data (i32.const 96) "Hello wasi_thread_start\0a") +)