Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Make component-model-async feature no_std-compatible (#13533)

Alex Crichton0402a1c834d6
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 027e5fcc9d..3102d9e25a 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -604,7 +604,7 @@ jobs:
os: ubuntu-latest
test: >
cargo check -p wasmtime --no-default-features --features runtime,component-model &&
- cargo check -p wasmtime --no-default-features --features runtime,gc,component-model,pulley,async,debug,debug-builtins,demangle,anyhow &&
+ cargo check -p wasmtime --no-default-features --features runtime,gc,component-model-async,pulley,debug,debug-builtins,demangle,anyhow &&
cargo check -p cranelift-control --no-default-features &&
cargo check -p cranelift-assembler-x64 --lib &&
cargo check -p cranelift-codegen --no-default-features --features x86,arm64,riscv64 &&
diff --git a/crates/wasmtime/Cargo.toml b/crates/wasmtime/Cargo.toml
index 8d8ed8a2a7..f8768fd53f 100644
--- a/crates/wasmtime/Cargo.toml
+++ b/crates/wasmtime/Cargo.toml
@@ -361,6 +361,7 @@ std = [
"dep:rustix",
"wasmtime-jit-icache-coherence",
"wasmtime-jit-debug?/std",
+ "futures?/std",
]
# Enables support for the `Store::call_hook` API which enables injecting custom
@@ -429,10 +430,8 @@ profile-pulley = [
component-model-async = [
"async",
"component-model",
- "std",
"wasmtime-component-macro?/component-model-async",
"dep:futures",
- "futures/std",
]
# Enables support for `stream` interop with the `bytes` crate.
diff --git a/crates/wasmtime/src/runtime.rs b/crates/wasmtime/src/runtime.rs
index 97e43a30bc..78eba4ad63 100644
--- a/crates/wasmtime/src/runtime.rs
+++ b/crates/wasmtime/src/runtime.rs
@@ -57,6 +57,8 @@ pub(crate) mod resources;
pub(crate) mod store;
pub(crate) mod trampoline;
pub(crate) mod trap;
+#[cfg(feature = "component-model-async")]
+pub(crate) mod try_mutex;
pub(crate) mod type_registry;
pub(crate) mod types;
pub(crate) mod v128;
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rs
index 8061b24263..46512a412b 100644
--- a/crates/wasmtime/src/runtime/component/concurrent.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent.rs
@@ -50,12 +50,14 @@
//! store. This is equivalent to `StoreContextMut::spawn` but more convenient to use
//! in host functions.
+use self::error_contexts::GlobalErrorContextRefCount;
use crate::bail_bug;
use crate::component::func::{self, Func, call_post_return};
use crate::component::{
HasData, HasSelf, Instance, Resource, ResourceTable, ResourceTableError, RuntimeInstance,
};
use crate::fiber::{self, StoreFiber, StoreFiberYield};
+use crate::hash_set::HashSet;
use crate::prelude::*;
use crate::store::{Store, StoreId, StoreInner, StoreOpaque, StoreToken};
use crate::vm::component::{CallContext, ComponentInstance, InstanceState};
@@ -63,25 +65,22 @@ use crate::vm::{AlwaysMut, SendSyncPtr, VMFuncRef, VMMemoryDefinition, VMStore};
use crate::{
AsContext, AsContextMut, FuncType, Result, StoreContext, StoreContextMut, ValRaw, ValType, bail,
};
-use error_contexts::GlobalErrorContextRefCount;
+use alloc::borrow::ToOwned;
+use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
+use core::any::Any;
+use core::cell::UnsafeCell;
+use core::fmt;
+use core::future::Future;
+use core::marker::PhantomData;
+use core::mem::{self, ManuallyDrop, MaybeUninit};
+use core::ops::DerefMut;
+use core::pin::{Pin, pin};
+use core::ptr::{self, NonNull};
+use core::task::{Context, Poll, Waker};
use futures::channel::oneshot;
use futures::future::{self, FutureExt};
use futures::stream::{FuturesUnordered, StreamExt};
use futures_and_streams::{FlatAbi, ReturnCode, TransmitHandle, TransmitIndex};
-use std::any::Any;
-use std::borrow::ToOwned;
-use std::boxed::Box;
-use std::cell::UnsafeCell;
-use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
-use std::fmt;
-use std::future::Future;
-use std::marker::PhantomData;
-use std::mem::{self, ManuallyDrop, MaybeUninit};
-use std::ops::DerefMut;
-use std::pin::{Pin, pin};
-use std::ptr::{self, NonNull};
-use std::task::{Context, Poll, Waker};
-use std::vec::Vec;
use table::{TableDebug, TableId};
use wasmtime_environ::component::{
CanonicalAbiInfo, CanonicalOptions, CanonicalOptionsDataModel, MAX_FLAT_PARAMS,
@@ -293,7 +292,7 @@ where
/// time so the store is effectively being passed between futures.
///
/// Rust's `Future` trait, however, has no means of passing a `Store`
-/// temporarily between futures. The [`Context`](std::task::Context) type does
+/// temporarily between futures. The [`Context`](core::task::Context) type does
/// not have the ability to attach arbitrary information to it at this time.
/// This type, [`Accessor`], is used to bridge this expressivity gap.
///
@@ -576,7 +575,7 @@ where
/// Represents a task which may be provided to `Accessor::spawn`,
/// `Accessor::forward`, or `StorecContextMut::spawn`.
-// TODO: Replace this with `std::ops::AsyncFnOnce` when that becomes a viable
+// TODO: Replace this with `core::ops::AsyncFnOnce` when that becomes a viable
// option.
//
// As of this writing, it's not possible to specify e.g. `Send` and `Sync`
@@ -4079,7 +4078,7 @@ impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
// SAFETY: The `wasmtime_cranelift`-generated code that calls
// this method will have ensured that `storage` is a valid
// pointer containing at least `storage_len` items.
- let params = unsafe { std::slice::from_raw_parts(storage, storage_len) }.to_vec();
+ let params = unsafe { core::slice::from_raw_parts(storage, storage_len) }.to_vec();
unsafe {
instance.prepare_call(
@@ -4132,7 +4131,7 @@ impl<T: 'static> VMComponentAsyncStore for StoreInner<T> {
// SAFETY: The `wasmtime_cranelift`-generated code that calls
// this method will have ensured that `storage` is a valid
// pointer containing at least `storage_len` items.
- Some(std::slice::from_raw_parts_mut(storage, storage_len)),
+ Some(core::slice::from_raw_parts_mut(storage, storage_len)),
)
.map(drop)
}
@@ -5605,7 +5604,7 @@ pub(crate) fn queue_call<T: 'static, R: Send + 'static>(
Ok(r) => Ok(*r),
Err(_) => bail_bug!("wrong type of value produced"),
},
- Err(e) => Err(e.into()),
+ Err(oneshot::Canceled) => bail_bug!("channel erroneously dropped"),
}),
))
}
diff --git a/crates/wasmtime/src/runtime/component/concurrent/abort.rs b/crates/wasmtime/src/runtime/component/concurrent/abort.rs
index 67a4779917..f32d3d2333 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/abort.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/abort.rs
@@ -1,7 +1,8 @@
-use std::mem::{self, ManuallyDrop};
-use std::pin::Pin;
-use std::sync::{Arc, Mutex};
-use std::task::{Context, Poll, Waker};
+use crate::try_mutex::TryMutex;
+use alloc::sync::Arc;
+use core::mem::{self, ManuallyDrop};
+use core::pin::Pin;
+use core::task::{Context, Poll, Waker};
/// Handle to a task which may be used to join on the result of executing it.
///
@@ -13,7 +14,12 @@ use std::task::{Context, Poll, Waker};
/// connected to. A manual invocation of [`JoinHandle::abort`] is required to
/// affect the task.
pub struct JoinHandle {
- state: Arc<Mutex<JoinState>>,
+ // Note that at this time the usage of this type within Wasmtime's async
+ // implementation is not expected to ever expose the ability to expose
+ // a situation where this lock can be contended. Everything's bound to the
+ // store and this is largely just used to satisfy compiler bounds. Hence,
+ // lock operations in this module all unwrap.
+ state: Arc<TryMutex<JoinState>>,
}
enum JoinState {
@@ -51,7 +57,7 @@ impl JoinHandle {
/// await the result and destruction of the task that this is associated
/// with.
pub fn abort(&self) {
- let mut state = self.state.lock().unwrap();
+ let mut state = self.state.try_lock().expect("should not be contended");
match &mut *state {
// If this task is still running, then fall through to below to
@@ -85,7 +91,7 @@ impl JoinHandle {
F: Future,
{
let handle = JoinHandle {
- state: Arc::new(Mutex::new(JoinState::Running {
+ state: Arc::new(TryMutex::new(JoinState::Running {
waiting_for_abort_signal: None,
waiting_for_abort_to_complete: None,
})),
@@ -102,7 +108,10 @@ impl Future for JoinHandle {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
- let mut state = self.state.lock().unwrap();
+ let mut state = self
+ .state
+ .try_lock()
+ .expect("this lock should not be contended");
match &mut *state {
// If this task is running or still only has requested an abort,
// wait further for the task to get dropped.
@@ -125,7 +134,7 @@ impl Future for JoinHandle {
struct JoinHandleFuture<F> {
future: ManuallyDrop<F>,
- state: Arc<Mutex<JoinState>>,
+ state: Arc<TryMutex<JoinState>>,
}
impl<F> Future for JoinHandleFuture<F>
@@ -146,7 +155,7 @@ where
// First, before polling the future, check to see if we've been
// aborted. If not register our task as awaiting such an abort.
{
- let mut state = state.lock().unwrap();
+ let mut state = state.try_lock().expect("this lock should not be contended");
match &mut *state {
JoinState::Running {
waiting_for_abort_signal,
@@ -178,7 +187,10 @@ impl<F> Drop for JoinHandleFuture<F> {
// After the future dropped see if there was a task awaiting its
// destruction. Simultaneously flag this state as complete.
- let prev = mem::replace(&mut *self.state.lock().unwrap(), JoinState::Complete);
+ let prev = mem::replace(
+ &mut *self.state.try_lock().expect("should not be contended"),
+ JoinState::Complete,
+ );
let task = match prev {
JoinState::Running {
waiting_for_abort_to_complete,
diff --git a/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs b/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs
index 0bdab44086..5d65b59e89 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs
@@ -10,8 +10,8 @@ use crate::component::{
};
use crate::store::StoreOpaque;
use crate::{AsContextMut, Result, bail, error::Context};
-use std::any::TypeId;
-use std::mem::MaybeUninit;
+use core::any::TypeId;
+use core::mem::MaybeUninit;
use wasmtime_environ::component::{
CanonicalAbiInfo, InterfaceType, TypeFutureTableIndex, TypeStreamTableIndex,
};
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
index 42fbf5452b..eec6cf54c3 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
@@ -9,7 +9,9 @@ use crate::component::{
AsAccessor, ComponentInstanceId, ComponentType, FutureAny, Instance, Lift, Lower, StreamAny,
Val, WasmList,
};
+use crate::prelude::*;
use crate::store::{StoreOpaque, StoreToken};
+use crate::try_mutex::{TryMutex, TryMutexGuard};
use crate::vm::component::{ComponentInstance, HandleTable, TransmitLocalState};
use crate::vm::{AlwaysMut, VMStore};
use crate::{AsContext, AsContextMut, StoreContextMut, ValRaw};
@@ -17,7 +19,9 @@ use crate::{
Error, Result, Trap, bail, bail_bug, ensure,
error::{Context as _, format_err},
};
+use alloc::sync::Arc;
use buffers::{Extender, SliceBuffer, UntypedWriteBuffer};
+use core::any::{Any, TypeId};
use core::fmt;
use core::future;
use core::iter;
@@ -28,11 +32,6 @@ use core::pin::Pin;
use core::task::{Context, Poll, Waker, ready};
use futures::channel::oneshot;
use futures::{FutureExt as _, stream};
-use std::any::{Any, TypeId};
-use std::boxed::Box;
-use std::string::String;
-use std::sync::{Arc, Mutex, MutexGuard};
-use std::vec::Vec;
use wasmtime_environ::component::{
CanonicalAbiInfo, ComponentTypes, InterfaceType, OptionsIndex, RuntimeComponentInstanceIndex,
TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
@@ -185,7 +184,7 @@ impl PartialEq<u32> for ItemCount {
}
impl PartialOrd<u32> for ItemCount {
- fn partial_cmp(&self, other: &u32) -> Option<std::cmp::Ordering> {
+ fn partial_cmp(&self, other: &u32) -> Option<core::cmp::Ordering> {
self.raw.partial_cmp(other)
}
}
@@ -469,6 +468,7 @@ pub struct DirectDestination<'a, D: 'static> {
store: StoreContextMut<'a, D>,
}
+#[cfg(feature = "std")]
impl<D: 'static> std::io::Write for DirectDestination<'_, D> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let rem = self.remaining();
@@ -982,6 +982,7 @@ pub struct DirectSource<'a, D: 'static> {
store: StoreContextMut<'a, D>,
}
+#[cfg(feature = "std")]
impl<D: 'static> std::io::Read for DirectSource<'_, D> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let rem = self.remaining();
@@ -3084,14 +3085,17 @@ async fn write<D: 'static, P: Send + 'static, T: func::Lower + 'static, B: Write
},
))))
});
- rx.await?
+ match rx.await {
+ Ok(r) => r,
+ Err(oneshot::Canceled) => bail_bug!("work cancelled"),
+ }
} else {
// Optimize flat payloads (i.e. those which do not
// require calling the guest's realloc function) by
// lowering directly instead of using a oneshot::channel
// and background task.
tls::get(|store| accept(token.as_context_mut(store)))?
- };
+ }
}
tls::get(|store| {
@@ -4899,14 +4903,14 @@ fn allow_intra_component_read_write(ty: Option<&InterfaceType>) -> bool {
/// contains an
/// `Option<T>`
struct LockedState<T> {
- inner: Mutex<Option<T>>,
+ inner: TryMutex<Option<T>>,
}
impl<T> LockedState<T> {
/// Creates a new initial state with `value` stored.
fn new(value: T) -> Self {
Self {
- inner: Mutex::new(Some(value)),
+ inner: TryMutex::new(Some(value)),
}
}
@@ -4918,10 +4922,10 @@ impl<T> LockedState<T> {
/// As-used in this file there should never actually be contention on this
/// lock nor recursive access so failing to acquire the lock is a fatal
/// error that gets propagated upwards.
- fn try_lock(&self) -> Result<MutexGuard<'_, Option<T>>> {
+ fn try_lock(&self) -> Result<TryMutexGuard<'_, Option<T>>> {
match self.inner.try_lock() {
- Ok(lock) => Ok(lock),
- Err(_) => bail_bug!("should not have contention on state lock"),
+ Some(lock) => Ok(lock),
+ None => bail_bug!("should not have contention on state lock"),
}
}
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs
index aea9a3e768..534942ab39 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams/buffers.rs
@@ -1,8 +1,8 @@
+use crate::prelude::*;
#[cfg(feature = "component-model-async-bytes")]
use bytes::{Bytes, BytesMut};
-use std::mem::{self, MaybeUninit};
-use std::slice;
-use std::vec::Vec;
+use core::mem::{self, MaybeUninit};
+use core::slice;
// Inner module here to restrict possible readers of the fields of
// `UntypedWriteBuffer`.
@@ -10,10 +10,10 @@ pub use untyped::*;
mod untyped {
use super::WriteBuffer;
use crate::vm::SendSyncPtr;
- use std::any::TypeId;
- use std::marker;
- use std::mem;
- use std::ptr::NonNull;
+ use core::any::TypeId;
+ use core::marker;
+ use core::mem;
+ use core::ptr::NonNull;
/// Helper structure to type-erase the `T` in `WriteBuffer<T>`.
///
@@ -440,7 +440,6 @@ fn unsafe_byte_slice(slice: &[u8]) -> &[MaybeUninit<u8>] {
#[cfg(test)]
mod tests {
use super::*;
- use crate::prelude::*;
#[test]
fn test_vec_buffer_take() {
diff --git a/crates/wasmtime/src/runtime/component/concurrent/table.rs b/crates/wasmtime/src/runtime/component/concurrent/table.rs
index 6f14c405a3..af8b07748b 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/table.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/table.rs
@@ -1,8 +1,8 @@
use crate::component::Resource;
-use std::cmp::Ordering;
-use std::fmt;
-use std::hash::{Hash, Hasher};
-use std::marker::PhantomData;
+use core::cmp::Ordering;
+use core::fmt;
+use core::hash::{Hash, Hasher};
+use core::marker::PhantomData;
/// Represents a `ResourceTable` entry for a `waitable` or `waitable-set`.
///
diff --git a/crates/wasmtime/src/runtime/component/concurrent/tls.rs b/crates/wasmtime/src/runtime/component/concurrent/tls.rs
index ec4dc9aca6..afe1ccde74 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/tls.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/tls.rs
@@ -17,17 +17,19 @@
//! must be audited for the `unsafe` blocks contained within.
use crate::runtime::vm::VMStore;
-use core::cell::Cell;
+use crate::vm::{component_async_tls_get, component_async_tls_set};
use core::mem;
use core::ptr::NonNull;
-std::thread_local! {
- // Note that care is currently taken to minimize the size of this TLS
- // variable as it's expected we'll refactor this in the future and have to
- // plumb it to the platform abstraction layer of Wasmtime eventually where
- // we want as minimal an impact as possible. Thus this TLS variable is
- // a single pointer.
- static STORAGE: Cell<Option<NonNull<SetStorage>>> = const { Cell::new(None) };
+fn tls_get() -> Option<NonNull<SetStorage>> {
+ NonNull::new(component_async_tls_get().cast())
+}
+
+fn tls_set(val: Option<NonNull<SetStorage>>) {
+ component_async_tls_set(match val {
+ Some(v) => v.as_ptr().cast(),
+ None => core::ptr::null_mut(),
+ })
}
enum SetStorage {
@@ -44,14 +46,15 @@ enum SetStorage {
/// `f` is not allowed to access `store` via Rust's borrow checker.
pub fn set<R>(store: &mut dyn VMStore, f: impl FnOnce() -> R) -> R {
let mut storage = SetStorage::Present(NonNull::from(store));
- let _reset = ResetTls(STORAGE.with(|s| s.replace(Some(NonNull::from(&mut storage)))));
+ let _reset = ResetTls(component_async_tls_get());
+ tls_set(Some(NonNull::from(&mut storage)));
return f();
- struct ResetTls(Option<NonNull<SetStorage>>);
+ struct ResetTls(*mut u8);
impl Drop for ResetTls {
fn drop(&mut self) {
- STORAGE.with(|s| s.set(self.0));
+ component_async_tls_set(self.0);
}
}
}
@@ -121,21 +124,21 @@ pub fn try_get<R>(f: impl FnOnce(TryGet<'_>) -> R) -> R {
// outside that closure. That means that once `f` is returned this
// function has exclusive access to the store again.
//
- // * If `STORAGE` is not set then that means `set` has not been configured,
+ // * If TLS is not set then that means `set` has not been configured,
// thus `TryGet::None` is yielded.
//
- // * If `STORAGE` is set then we're guaranteed it's set for the entire
+ // * If TLS is set then we're guaranteed it's set for the entire
// lifetime of this function call, and we're also guaranteed that the
// pointer stored in there is the same pointer we'll be modifying for
// this whole function call.
//
- // * The `STORAGE` pointer is read/written only in a scoped manner here and
+ // * The TLS pointer is read/written only in a scoped manner here and
// borrows of this value are not persisted for very long.
//
// With all of that put together it should make it such that this is a safe
// reborrow of the store provided to `set` to pass to the closure `f` here.
unsafe {
- let storage = STORAGE.with(|s| s.get());
+ let storage = tls_get();
let _reset;
let val = match storage {
Some(mut storage) => match mem::replace(storage.as_mut(), SetStorage::Taken) {
diff --git a/crates/wasmtime/src/runtime/component/linker.rs b/crates/wasmtime/src/runtime/component/linker.rs
index eef6040989..23050b21a7 100644
--- a/crates/wasmtime/src/runtime/component/linker.rs
+++ b/crates/wasmtime/src/runtime/component/linker.rs
@@ -861,8 +861,8 @@ impl<T: 'static> LinkerInstance<'_, T> {
let mut store = cx.as_context_mut();
let accessor =
&Accessor::new(crate::store::StoreToken::new(store.as_context_mut()));
- let mut future = std::pin::pin!(dtor(accessor, param));
- std::future::poll_fn(|cx| {
+ let mut future = core::pin::pin!(dtor(accessor, param));
+ core::future::poll_fn(|cx| {
crate::component::concurrent::tls::set(store.0, || future.as_mut().poll(cx))
})
.await
diff --git a/crates/wasmtime/src/runtime/try_mutex.rs b/crates/wasmtime/src/runtime/try_mutex.rs
new file mode 100644
index 0000000000..5bafd4f60b
--- /dev/null
+++ b/crates/wasmtime/src/runtime/try_mutex.rs
@@ -0,0 +1,99 @@
+use core::cell::UnsafeCell;
+use core::ops::{Deref, DerefMut};
+use core::sync::atomic::{AtomicU8, Ordering};
+
+const UNLOCKED: u8 = 0;
+const LOCKED: u8 = 1;
+
+/// A simple mutex which only supports the `try_lock` operation.
+///
+/// Suitable for use in Wasmtime when contention is never expected and is a bug
+/// for example. This is effectively a `RefCell` that's `Sync` in that case. It
+/// incurs runtime overhead that in theory is pure overhead at runtime at the
+/// cost of "obviously safe" code during review.
+pub struct TryMutex<T> {
+ state: AtomicU8,
+ data: UnsafeCell<T>,
+}
+
+// SAFETY: this type inherits `Send`-ness of the inner type `T`
+unsafe impl<T: Send> Send for TryMutex<T> {}
+// SAFETY: this is the standard `Sync` bound for any mutex-like structure.
+unsafe impl<T: Send> Sync for TryMutex<T> {}
+
+impl<T> TryMutex<T> {
+ /// Creates a new `TryMutex` containing the given data.
+ pub const fn new(data: T) -> Self {
+ Self {
+ state: AtomicU8::new(UNLOCKED),
+ data: UnsafeCell::new(data),
+ }
+ }
+
+ /// Attempts to acquire the lock, returning `Some(_)` if
+ /// successful and `None` if the lock is already held.
+ ///
+ /// This method does not block the current thread.
+ ///
+ /// The returned `TryMutexGuard` is an RAII guard to unlock this lock when
+ /// dropped.
+ pub fn try_lock(&self) -> Option<TryMutexGuard<'_, T>> {
+ if self
+ .state
+ .compare_exchange(UNLOCKED, LOCKED, Ordering::Acquire, Ordering::Relaxed)
+ .is_ok()
+ {
+ Some(TryMutexGuard { mutex: self })
+ } else {
+ None
+ }
+ }
+}
+
+/// RAII guard returned by [`TryMutex::try_lock`] which can be used to access
+/// the internal data in the lock.
+pub struct TryMutexGuard<'a, T> {
+ mutex: &'a TryMutex<T>,
+}
+
+impl<T> Deref for TryMutexGuard<'_, T> {
+ type Target = T;
+
+ fn deref(&self) -> &T {
+ // SAFETY: this object has exclusive access to the mutex so it is safe
+ // to access the inner data.
+ unsafe { &*self.mutex.data.get() }
+ }
+}
+
+impl<T> DerefMut for TryMutexGuard<'_, T> {
+ fn deref_mut(&mut self) -> &mut T {
+ // SAFETY: this object has exclusive access to the mutex so it is safe
+ // to access the inner data.
+ unsafe { &mut *self.mutex.data.get() }
+ }
+}
+
+impl<T> Drop for TryMutexGuard<'_, T> {
+ fn drop(&mut self) {
+ self.mutex.state.store(UNLOCKED, Ordering::Release);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_try_mutex() {
+ let mutex = TryMutex::new(42);
+
+ let mut guard = mutex.try_lock().expect("should acquire lock");
+ assert_eq!(*guard, 42);
+ assert!(mutex.try_lock().is_none());
+ *guard = 43;
+ drop(guard);
+ let guard2 = mutex.try_lock().expect("should acquire lock again");
+ assert_eq!(*guard2, 43);
+ }
+}
diff --git a/crates/wasmtime/src/runtime/vm.rs b/crates/wasmtime/src/runtime/vm.rs
index a42ec6666b..7b9bac6be4 100644
--- a/crates/wasmtime/src/runtime/vm.rs
+++ b/crates/wasmtime/src/runtime/vm.rs
@@ -90,6 +90,9 @@ pub(crate) mod interpreter_disabled;
#[cfg(not(feature = "pulley"))]
pub(crate) use interpreter_disabled as interpreter;
+#[cfg(feature = "component-model-async")]
+pub(crate) use sys::{component_async_tls_get, component_async_tls_set};
+
#[cfg(feature = "debug-builtins")]
pub use wasmtime_jit_debug::gdb_jit_int::GdbJitImageRegistration;
diff --git a/crates/wasmtime/src/runtime/vm/component/libcalls.rs b/crates/wasmtime/src/runtime/vm/component/libcalls.rs
index b9882b89d0..094b5562c2 100644
--- a/crates/wasmtime/src/runtime/vm/component/libcalls.rs
+++ b/crates/wasmtime/src/runtime/vm/component/libcalls.rs
@@ -901,7 +901,7 @@ unsafe fn sync_start(
callback.cast::<crate::vm::VMFuncRef>(),
NonNull::new(callee).unwrap().cast::<crate::vm::VMFuncRef>(),
param_count,
- storage.cast::<std::mem::MaybeUninit<crate::ValRaw>>(),
+ storage.cast::<core::mem::MaybeUninit<crate::ValRaw>>(),
storage_len,
)
}
diff --git a/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs b/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs
index 1a6974d5a4..2011cae0d5 100644
--- a/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs
+++ b/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs
@@ -172,16 +172,20 @@ unsafe extern "C" {
#[cfg(has_virtual_memory)]
pub fn wasmtime_memory_image_free(image: *mut wasmtime_memory_image);
- /// Wasmtime requires a single pointer's space of TLS to be used at runtime,
- /// and this function returns the current value of the TLS variable.
+ /// Wasmtime requires a small amount of TLS to be used at runtime,
+ /// and this function returns the current value of the TLS state.
///
- /// This value should default to `NULL`.
- pub fn wasmtime_tls_get() -> *mut u8;
-
- /// Sets the current TLS value for Wasmtime to the provided value.
+ /// Wasmtime needs at least one pointer's worth of TLS space, and with the
+ /// `component-model-async` feature a second pointer's worth of TLS space is
+ /// required. The `slot` variable is 0 for the default runtime TLS pointer,
+ /// and it is 1 for the component-model-async state. No other value of
+ /// `slot` is passed in.
///
- /// This value should be returned when later calling `wasmtime_tls_get`.
- pub fn wasmtime_tls_set(ptr: *mut u8);
+ /// The values should default to `NULL`.
+ pub fn wasmtime_tls_get(slot: usize) -> *mut u8;
+
+ /// Setter for the TLS space described in `wasmtime_tls_get`.
+ pub fn wasmtime_tls_set(slot: usize, ptr: *mut u8);
/// Frees a synchronization lock.
///
diff --git a/crates/wasmtime/src/runtime/vm/sys/custom/mod.rs b/crates/wasmtime/src/runtime/vm/sys/custom/mod.rs
index 78809db3b3..3e0b190d5b 100644
--- a/crates/wasmtime/src/runtime/vm/sys/custom/mod.rs
+++ b/crates/wasmtime/src/runtime/vm/sys/custom/mod.rs
@@ -32,10 +32,22 @@ fn cvt(rc: i32) -> Result<()> {
#[inline]
pub fn tls_get() -> *mut u8 {
- unsafe { capi::wasmtime_tls_get() }
+ unsafe { capi::wasmtime_tls_get(0) }
}
#[inline]
pub fn tls_set(ptr: *mut u8) {
- unsafe { capi::wasmtime_tls_set(ptr) }
+ unsafe { capi::wasmtime_tls_set(0, ptr) }
+}
+
+#[inline]
+#[cfg(feature = "component-model-async")]
+pub fn component_async_tls_get() -> *mut u8 {
+ unsafe { capi::wasmtime_tls_get(1) }
+}
+
+#[inline]
+#[cfg(feature = "component-model-async")]
+pub fn component_async_tls_set(ptr: *mut u8) {
+ unsafe { capi::wasmtime_tls_set(1, ptr) }
}
diff --git a/crates/wasmtime/src/runtime/vm/sys/miri/mod.rs b/crates/wasmtime/src/runtime/vm/sys/miri/mod.rs
index cf953c365a..821ed80088 100644
--- a/crates/wasmtime/src/runtime/vm/sys/miri/mod.rs
+++ b/crates/wasmtime/src/runtime/vm/sys/miri/mod.rs
@@ -4,21 +4,11 @@
//! notably WebAssembly tests are not executed at this time (MIRI can't execute
//! Cranelift-generated code).
-use std::cell::Cell;
-
pub mod mmap;
pub mod traphandlers;
pub mod unwind;
pub mod vm;
-std::thread_local!(static TLS: Cell<*mut u8> = const { Cell::new(std::ptr::null_mut()) });
-
-#[inline]
-pub fn tls_get() -> *mut u8 {
- TLS.with(|p| p.get())
-}
-
-#[inline]
-pub fn tls_set(ptr: *mut u8) {
- TLS.with(|p| p.set(ptr));
-}
+#[path = "../std_tls.rs"]
+mod std_tls;
+pub use std_tls::*;
diff --git a/crates/wasmtime/src/runtime/vm/sys/std_tls.rs b/crates/wasmtime/src/runtime/vm/sys/std_tls.rs
new file mode 100644
index 0000000000..3dfa20519f
--- /dev/null
+++ b/crates/wasmtime/src/runtime/vm/sys/std_tls.rs
@@ -0,0 +1,28 @@
+use std::cell::Cell;
+
+std::thread_local!(static TLS: Cell<*mut u8> = const { Cell::new(std::ptr::null_mut()) });
+
+#[inline]
+pub fn tls_get() -> *mut u8 {
+ TLS.with(|p| p.get())
+}
+
+#[inline]
+pub fn tls_set(ptr: *mut u8) {
+ TLS.with(|p| p.set(ptr));
+}
+
+#[cfg(feature = "component-model-async")]
+std::thread_local!(static COMPONENT_ASYNC_TLS: Cell<*mut u8> = const { Cell::new(std::ptr::null_mut()) });
+
+#[inline]
+#[cfg(feature = "component-model-async")]
+pub fn component_async_tls_get() -> *mut u8 {
+ COMPONENT_ASYNC_TLS.with(|p| p.get())
+}
+
+#[inline]
+#[cfg(feature = "component-model-async")]
+pub fn component_async_tls_set(ptr: *mut u8) {
+ COMPONENT_ASYNC_TLS.with(|p| p.set(ptr));
+}
diff --git a/crates/wasmtime/src/runtime/vm/sys/unix/mod.rs b/crates/wasmtime/src/runtime/vm/sys/unix/mod.rs
index 24137b7f5c..6e3fccd7b6 100644
--- a/crates/wasmtime/src/runtime/vm/sys/unix/mod.rs
+++ b/crates/wasmtime/src/runtime/vm/sys/unix/mod.rs
@@ -3,8 +3,6 @@
//!
//! This module handles Linux and macOS for example.
-use core::cell::Cell;
-
#[cfg(has_virtual_memory)]
pub mod mmap;
pub mod traphandlers;
@@ -23,14 +21,6 @@ mod pagemap;
#[cfg(not(all(target_os = "linux", target_pointer_width = "64", feature = "std")))]
use crate::vm::pagemap_disabled as pagemap;
-std::thread_local!(static TLS: Cell<*mut u8> = const { Cell::new(std::ptr::null_mut()) });
-
-#[inline]
-pub fn tls_get() -> *mut u8 {
- TLS.with(|p| p.get())
-}
-
-#[inline]
-pub fn tls_set(ptr: *mut u8) {
- TLS.with(|p| p.set(ptr));
-}
+#[path = "../std_tls.rs"]
+mod std_tls;
+pub use std_tls::*;
diff --git a/crates/wasmtime/src/runtime/vm/sys/windows/mod.rs b/crates/wasmtime/src/runtime/vm/sys/windows/mod.rs
index 6b6c2bd03c..f12da9451b 100644
--- a/crates/wasmtime/src/runtime/vm/sys/windows/mod.rs
+++ b/crates/wasmtime/src/runtime/vm/sys/windows/mod.rs
@@ -1,7 +1,5 @@
//! Implementation of Wasmtime's system primitives for Windows.
-use std::cell::Cell;
-
#[cfg(has_virtual_memory)]
pub mod mmap;
pub mod traphandlers;
@@ -17,14 +15,6 @@ pub use unwind64 as unwind;
#[cfg(all(not(target_pointer_width = "64"), has_host_compiler_backend))]
compile_error!("don't know how to unwind non-64 bit platforms");
-std::thread_local!(static TLS: Cell<*mut u8> = const { Cell::new(std::ptr::null_mut()) });
-
-#[inline]
-pub fn tls_get() -> *mut u8 {
- TLS.with(|p| p.get())
-}
-
-#[inline]
-pub fn tls_set(ptr: *mut u8) {
- TLS.with(|p| p.set(ptr));
-}
+#[path = "../std_tls.rs"]
+mod std_tls;
+pub use std_tls::*;
diff --git a/examples/min-platform/embedding/wasmtime-platform.c b/examples/min-platform/embedding/wasmtime-platform.c
index 007abe902d..1a18a8c7d0 100644
--- a/examples/min-platform/embedding/wasmtime-platform.c
+++ b/examples/min-platform/embedding/wasmtime-platform.c
@@ -135,29 +135,32 @@ void wasmtime_memory_image_free(struct wasmtime_memory_image *image) {
// Multi-threaded TLS using pthread
#include <pthread.h>
-static pthread_key_t wasmtime_tls_key;
+static pthread_key_t wasmtime_tls_keys[2];
static pthread_once_t wasmtime_tls_key_once = PTHREAD_ONCE_INIT;
-static void make_tls_key(void) { pthread_key_create(&wasmtime_tls_key, NULL); }
+static void make_tls_key(void) {
+ pthread_key_create(&wasmtime_tls_keys[0], NULL);
+ pthread_key_create(&wasmtime_tls_keys[1], NULL);
+}
-uint8_t *wasmtime_tls_get(void) {
+uint8_t *wasmtime_tls_get(size_t slot) {
pthread_once(&wasmtime_tls_key_once, make_tls_key);
- return (uint8_t *)pthread_getspecific(wasmtime_tls_key);
+ return (uint8_t *)pthread_getspecific(wasmtime_tls_keys[slot]);
}
-void wasmtime_tls_set(uint8_t *val) {
+void wasmtime_tls_set(size_t slot, uint8_t *val) {
pthread_once(&wasmtime_tls_key_once, make_tls_key);
- pthread_setspecific(wasmtime_tls_key, val);
+ pthread_setspecific(wasmtime_tls_keys[slot], val);
}
#else
// Single-threaded TLS using a static variable
-static uint8_t *WASMTIME_TLS = NULL;
+static uint8_t *WASMTIME_TLS[2] = {NULL, NULL};
-uint8_t *wasmtime_tls_get(void) { return WASMTIME_TLS; }
+uint8_t *wasmtime_tls_get(size_t slot) { return WASMTIME_TLS[slot]; }
-void wasmtime_tls_set(uint8_t *val) { WASMTIME_TLS = val; }
+void wasmtime_tls_set(size_t slot, uint8_t *val) { WASMTIME_TLS[slot] = val; }
#endif
diff --git a/examples/min-platform/embedding/wasmtime-platform.h b/examples/min-platform/embedding/wasmtime-platform.h
index b04310cde5..6f560df507 100644
--- a/examples/min-platform/embedding/wasmtime-platform.h
+++ b/examples/min-platform/embedding/wasmtime-platform.h
@@ -240,19 +240,23 @@ extern void wasmtime_memory_image_free(struct wasmtime_memory_image *image);
#endif
/**
- * Wasmtime requires a single pointer's space of TLS to be used at runtime,
- * and this function returns the current value of the TLS variable.
+ * Wasmtime requires a small amount of TLS to be used at runtime,
+ * and this function returns the current value of the TLS state.
*
- * This value should default to `NULL`.
+ * Wasmtime needs at least one pointer's worth of TLS space, and with the
+ * `component-model-async` feature a second pointer's worth of TLS space is
+ * required. The `slot` variable is 0 for the default runtime TLS pointer,
+ * and it is 1 for the component-model-async state. No other value of
+ * `slot` is passed in.
+ *
+ * The values should default to `NULL`.
*/
-extern uint8_t *wasmtime_tls_get(void);
+extern uint8_t *wasmtime_tls_get(uintptr_t slot);
/**
- * Sets the current TLS value for Wasmtime to the provided value.
- *
- * This value should be returned when later calling `wasmtime_tls_get`.
+ * Setter for the TLS space described in `wasmtime_tls_get`.
*/
-extern void wasmtime_tls_set(uint8_t *ptr);
+extern void wasmtime_tls_set(uintptr_t slot, uint8_t *ptr);
#if defined(WASMTIME_CUSTOM_SYNC)
/**