Skip to content

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

feat(no_std): Add custom sync primitives support via C API (#11836)

Salman Saghafi0dd73cc74e37
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index e23ce342e8..17d136b832 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -1040,7 +1040,7 @@ jobs:
with:
submodules: true
- uses: ./.github/actions/install-rust
- - run: cargo install cbindgen --vers "^0.28" --locked
+ - run: cargo install cbindgen --vers "^0.29" --locked
- run: rustup target add x86_64-unknown-none
- run: rustup target add wasm32-wasip2
- run: ./build.sh x86_64-unknown-none
diff --git a/crates/wasmtime/Cargo.toml b/crates/wasmtime/Cargo.toml
index 3023261926..ac6c5b0042 100644
--- a/crates/wasmtime/Cargo.toml
+++ b/crates/wasmtime/Cargo.toml
@@ -389,6 +389,9 @@ custom-virtual-memory = []
# Same as `custom-virtual-memory` above, but for custom signal-handling APIs.
custom-native-signals = []
+# Same as `custom-virtual-memory` above, but for custom sync primitive APIs.
+custom-sync-primitives = []
+
# Off-by-default support to profile the Pulley interpreter. This has a
# performance hit, even when not profiling, so it's disabled by default at
# compile time.
diff --git a/crates/wasmtime/build.rs b/crates/wasmtime/build.rs
index c095fecad4..c80e4bf505 100644
--- a/crates/wasmtime/build.rs
+++ b/crates/wasmtime/build.rs
@@ -26,9 +26,11 @@ fn main() {
&& (supported_os || cfg!(feature = "custom-native-signals"))
&& has_host_compiler_backend;
let has_virtual_memory = supported_os || cfg!(feature = "custom-virtual-memory");
+ let has_custom_sync = !cfg!(feature = "std") && cfg!(feature = "custom-sync-primitives");
custom_cfg("has_native_signals", has_native_signals);
custom_cfg("has_virtual_memory", has_virtual_memory);
+ custom_cfg("has_custom_sync", has_custom_sync);
custom_cfg("has_host_compiler_backend", has_host_compiler_backend);
// If this OS isn't supported and no debug-builtins or if Cranelift doesn't support
diff --git a/crates/wasmtime/src/runtime/vm.rs b/crates/wasmtime/src/runtime/vm.rs
index 2dc3160fd4..7823b515b6 100644
--- a/crates/wasmtime/src/runtime/vm.rs
+++ b/crates/wasmtime/src/runtime/vm.rs
@@ -129,6 +129,8 @@ pub use crate::runtime::vm::vmcontext::{
VMGlobalDefinition, VMGlobalImport, VMGlobalKind, VMMemoryDefinition, VMMemoryImport,
VMOpaqueContext, VMStoreContext, VMTableImport, VMTagImport, VMWasmCallFunction, ValRaw,
};
+#[cfg(has_custom_sync)]
+pub(crate) use sys::capi;
pub use send_sync_ptr::SendSyncPtr;
pub use wasmtime_unwinder::Unwind;
diff --git a/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs b/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs
index 5c7a546646..1a6974d5a4 100644
--- a/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs
+++ b/crates/wasmtime/src/runtime/vm/sys/custom/capi.rs
@@ -182,4 +182,54 @@ unsafe extern "C" {
///
/// This value should be returned when later calling `wasmtime_tls_get`.
pub fn wasmtime_tls_set(ptr: *mut u8);
+
+ /// Frees a synchronization lock.
+ ///
+ /// May be called on a lock that was never used (still has a zero pattern).
+ /// The implementor must handle this case gracefully.
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_lock_free(lock: *mut usize);
+
+ /// Acquires an exclusive lock.
+ ///
+ /// If the lock is uninitialized (zero pattern), it will be initialized lazily.
+ /// This function blocks until the lock is acquired.
+ /// Must be paired with [`wasmtime_sync_lock_release`].
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_lock_acquire(lock: *mut usize);
+
+ /// Releases an exclusive lock previously acquired with [`wasmtime_sync_lock_acquire`].
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_lock_release(lock: *mut usize);
+
+ /// Acquires a read lock on an RwLock.
+ ///
+ /// If the lock is uninitialized (zero pattern), it will be initialized lazily.
+ /// Multiple readers can hold the lock simultaneously.
+ /// Must be paired with [`wasmtime_sync_rwlock_read_release`].
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_rwlock_read(lock: *mut usize);
+
+ /// Releases a read lock previously acquired with [`wasmtime_sync_rwlock_read`].
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_rwlock_read_release(lock: *mut usize);
+
+ /// Acquires a write lock on an RwLock.
+ ///
+ /// If the lock is uninitialized (zero pattern), it will be initialized lazily.
+ /// Only one writer can hold the lock, and no readers can be present.
+ /// Must be paired with [`wasmtime_sync_rwlock_write_release`].
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_rwlock_write(lock: *mut usize);
+
+ /// Releases a write lock previously acquired with [`wasmtime_sync_rwlock_write`].
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_rwlock_write_release(lock: *mut usize);
+
+ /// Frees an RwLock.
+ ///
+ /// May be called on a lock that was never used (still has a zero pattern).
+ /// The implementor must handle this case gracefully.
+ #[cfg(has_custom_sync)]
+ pub fn wasmtime_sync_rwlock_free(lock: *mut usize);
}
diff --git a/crates/wasmtime/src/sync_nostd.rs b/crates/wasmtime/src/sync_nostd.rs
index c0fb73de0d..39913bbbd3 100644
--- a/crates/wasmtime/src/sync_nostd.rs
+++ b/crates/wasmtime/src/sync_nostd.rs
@@ -1,16 +1,16 @@
//! Synchronization primitives for Wasmtime for `no_std`.
//!
-//! These primitives are intended for use in `no_std` contexts are not as
-//! full-featured as the `std` brethren. Namely these panic and/or return an
-//! error on contention. This serves to continue to be correct in the face of
-//! actual multiple threads, but if a system actually has multiple threads then
-//! something will need to change in the Wasmtime crate to enable the external
-//! system to perform necessary synchronization.
+//! These primitives are intended for use in `no_std` contexts and are not as
+//! full-featured as the `std` brethren. Namely these panic on contention
+//! unless the `custom-sync-primitives` feature is enabled. This serves to
+//! continue to be correct in the face of actual multiple threads, but if a
+//! system actually has multiple threads then the `custom-sync-primitives`
+//! feature must be enabled to allow the external system to perform necessary
+//! synchronization via host-provided locks.
//!
-//! In the future if these primitives are not suitable we can switch to putting
-//! relevant functions in the `capi.rs` module where we basically require
-//! embedders to implement them instead of doing it ourselves here. It's unclear
-//! if this will be necessary, so this is the chosen starting point.
+//! With `custom-sync-primitives` enabled, this module uses [`RawMutex`] and
+//! [`RawRwLock`] which wrap host-provided synchronization primitives that
+//! support true concurrent access with proper blocking behavior.
//!
//! See a brief overview of this module in `sync_std.rs` as well.
@@ -24,9 +24,18 @@ use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicU8, AtomicU32, Ordering};
+#[cfg(has_custom_sync)]
+use crate::runtime::vm::capi::{
+ wasmtime_sync_lock_acquire, wasmtime_sync_lock_free, wasmtime_sync_lock_release,
+ wasmtime_sync_rwlock_free, wasmtime_sync_rwlock_read, wasmtime_sync_rwlock_read_release,
+ wasmtime_sync_rwlock_write, wasmtime_sync_rwlock_write_release,
+};
+
pub struct OnceLock<T> {
val: UnsafeCell<MaybeUninit<T>>,
state: AtomicU8,
+ #[cfg(has_custom_sync)]
+ mutex: RawMutex,
}
unsafe impl<T: Send> Send for OnceLock<T> {}
@@ -41,6 +50,8 @@ impl<T> OnceLock<T> {
OnceLock {
state: AtomicU8::new(UNINITIALIZED),
val: UnsafeCell::new(MaybeUninit::uninit()),
+ #[cfg(has_custom_sync)]
+ mutex: RawMutex::new(),
}
}
@@ -60,6 +71,7 @@ impl<T> OnceLock<T> {
fn get(&self) -> Option<&T> {
if self.state.load(Ordering::Acquire) == INITIALIZED {
+ // SAFETY: State is INITIALIZED, so val has been written
Some(unsafe { (*self.val.get()).assume_init_ref() })
} else {
None
@@ -67,6 +79,7 @@ impl<T> OnceLock<T> {
}
#[cold]
+ #[cfg(not(has_custom_sync))]
fn try_init<E>(&self, f: impl FnOnce() -> Result<T, E>) -> Result<&T, E> {
match self.state.compare_exchange(
UNINITIALIZED,
@@ -86,11 +99,52 @@ impl<T> OnceLock<T> {
_ => unreachable!(),
},
},
- Err(INITIALIZING) => panic!("concurrent initialization only allowed with `std`"),
+ Err(INITIALIZING) => panic!(
+ "concurrent initialization only allowed with `std` or `custom-sync-primitives` features"
+ ),
Err(INITIALIZED) => Ok(self.get().unwrap()),
_ => unreachable!(),
}
}
+
+ #[cold]
+ #[cfg(has_custom_sync)]
+ fn try_init<E>(&self, f: impl FnOnce() -> Result<T, E>) -> Result<&T, E> {
+ let _guard = OnceLockGuard::acquire(self.mutex.storage.get());
+
+ // Check state again under lock
+ match self.state.load(Ordering::Acquire) {
+ UNINITIALIZED => {
+ self.state.store(INITIALIZING, Ordering::Release);
+ match f() {
+ Ok(val) => {
+ // SAFETY: We hold the lock and state is INITIALIZING
+ let ret = unsafe { &*(*self.val.get()).write(val) };
+ self.state.store(INITIALIZED, Ordering::Release);
+ Ok(ret)
+ }
+ Err(e) => {
+ self.state.store(UNINITIALIZED, Ordering::Release);
+ Err(e)
+ }
+ }
+ }
+ INITIALIZED => {
+ // SAFETY: State is INITIALIZED, so val has been written
+ Ok(unsafe { (*self.val.get()).assume_init_ref() })
+ }
+ _ => panic!("concurrent initialization"),
+ }
+ }
+}
+
+impl<T> Drop for OnceLock<T> {
+ fn drop(&mut self) {
+ if self.state.load(Ordering::Acquire) == INITIALIZED {
+ // SAFETY: State is INITIALIZED, so val has been written
+ unsafe { (*self.val.get()).assume_init_drop() };
+ }
+ }
}
impl<T> Default for OnceLock<T> {
@@ -99,10 +153,65 @@ impl<T> Default for OnceLock<T> {
}
}
-#[derive(Debug, Default)]
+#[cfg(has_custom_sync)]
+#[derive(Debug)]
+struct RawMutex {
+ storage: UnsafeCell<usize>,
+}
+
+#[cfg(has_custom_sync)]
+impl RawMutex {
+ const fn new() -> RawMutex {
+ RawMutex {
+ storage: UnsafeCell::new(0),
+ }
+ }
+}
+
+#[cfg(has_custom_sync)]
+impl Drop for RawMutex {
+ fn drop(&mut self) {
+ // SAFETY: We have exclusive access via &mut self
+ // The host implementation handles the case where the lock was never used (still zero)
+ unsafe {
+ wasmtime_sync_lock_free(self.storage.get());
+ }
+ }
+}
+
+#[cfg(has_custom_sync)]
+struct OnceLockGuard {
+ lock: *mut usize,
+}
+
+#[cfg(has_custom_sync)]
+impl OnceLockGuard {
+ fn acquire(lock: *mut usize) -> OnceLockGuard {
+ // SAFETY: The host implementation handles lazy initialization in acquire
+ unsafe {
+ wasmtime_sync_lock_acquire(lock);
+ }
+ OnceLockGuard { lock }
+ }
+}
+
+#[cfg(has_custom_sync)]
+impl Drop for OnceLockGuard {
+ fn drop(&mut self) {
+ // SAFETY: We acquired the lock in OnceLockGuard::acquire
+ unsafe {
+ wasmtime_sync_lock_release(self.lock);
+ }
+ }
+}
+
+#[derive(Debug)]
pub struct RwLock<T> {
val: UnsafeCell<T>,
+ #[cfg(not(has_custom_sync))]
state: AtomicU32,
+ #[cfg(has_custom_sync)]
+ lock: RawRwLock,
}
unsafe impl<T: Send> Send for RwLock<T> {}
@@ -112,10 +221,14 @@ impl<T> RwLock<T> {
pub const fn new(val: T) -> RwLock<T> {
RwLock {
val: UnsafeCell::new(val),
+ #[cfg(not(has_custom_sync))]
state: AtomicU32::new(0),
+ #[cfg(has_custom_sync)]
+ lock: RawRwLock::new(),
}
}
+ #[cfg(not(has_custom_sync))]
pub fn read(&self) -> impl Deref<Target = T> + '_ {
const READER_LIMIT: u32 = u32::MAX / 2;
match self
@@ -133,18 +246,71 @@ impl<T> RwLock<T> {
}) {
Ok(_) => RwLockReadGuard { lock: self },
Err(_) => panic!(
- "concurrent read request while locked for writing, must use `std` to avoid panic"
+ "concurrent read request while locked for writing, must use `std` or `custom-sync-primitives` features to avoid panic"
),
}
}
+ #[cfg(has_custom_sync)]
+ pub fn read(&self) -> impl Deref<Target = T> + '_ {
+ // SAFETY: The host implementation handles lazy initialization in read
+ unsafe {
+ wasmtime_sync_rwlock_read(self.lock.storage.get());
+ }
+ RwLockReadGuard { lock: self }
+ }
+
+ #[cfg(not(has_custom_sync))]
pub fn write(&self) -> impl DerefMut<Target = T> + '_ {
match self
.state
.compare_exchange(0, u32::MAX, Ordering::Acquire, Ordering::Relaxed)
{
Ok(0) => RwLockWriteGuard { lock: self },
- _ => panic!("concurrent write request, must use `std` to avoid panicking"),
+ _ => panic!(
+ "concurrent write request, must use `std` or `custom-sync-primitives` features to avoid panicking"
+ ),
+ }
+ }
+
+ #[cfg(has_custom_sync)]
+ pub fn write(&self) -> impl DerefMut<Target = T> + '_ {
+ // SAFETY: The host implementation handles lazy initialization in write
+ unsafe {
+ wasmtime_sync_rwlock_write(self.lock.storage.get());
+ }
+ RwLockWriteGuard { lock: self }
+ }
+}
+
+impl<T: Default> Default for RwLock<T> {
+ fn default() -> RwLock<T> {
+ RwLock::new(T::default())
+ }
+}
+
+#[cfg(has_custom_sync)]
+#[derive(Debug)]
+struct RawRwLock {
+ storage: UnsafeCell<usize>,
+}
+
+#[cfg(has_custom_sync)]
+impl RawRwLock {
+ const fn new() -> RawRwLock {
+ RawRwLock {
+ storage: UnsafeCell::new(0),
+ }
+ }
+}
+
+#[cfg(has_custom_sync)]
+impl Drop for RawRwLock {
+ fn drop(&mut self) {
+ // SAFETY: We have exclusive access via &mut self
+ // The host implementation handles the case where the lock was never used (still zero)
+ unsafe {
+ wasmtime_sync_rwlock_free(self.storage.get());
}
}
}
@@ -157,16 +323,28 @@ impl<T> Deref for RwLockReadGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
+ // SAFETY: We hold the read lock
unsafe { &*self.lock.val.get() }
}
}
+#[cfg(not(has_custom_sync))]
impl<T> Drop for RwLockReadGuard<'_, T> {
fn drop(&mut self) {
self.lock.state.fetch_sub(1, Ordering::Release);
}
}
+#[cfg(has_custom_sync)]
+impl<T> Drop for RwLockReadGuard<'_, T> {
+ fn drop(&mut self) {
+ // SAFETY: We acquired the read lock in RwLock::read()
+ unsafe {
+ wasmtime_sync_rwlock_read_release(self.lock.lock.storage.get());
+ }
+ }
+}
+
struct RwLockWriteGuard<'a, T> {
lock: &'a RwLock<T>,
}
@@ -175,16 +353,19 @@ impl<T> Deref for RwLockWriteGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
+ // SAFETY: We hold the write lock
unsafe { &*self.lock.val.get() }
}
}
impl<T> DerefMut for RwLockWriteGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
+ // SAFETY: We hold the write lock
unsafe { &mut *self.lock.val.get() }
}
}
+#[cfg(not(has_custom_sync))]
impl<T> Drop for RwLockWriteGuard<'_, T> {
fn drop(&mut self) {
match self.lock.state.swap(0, Ordering::Release) {
@@ -194,6 +375,16 @@ impl<T> Drop for RwLockWriteGuard<'_, T> {
}
}
+#[cfg(has_custom_sync)]
+impl<T> Drop for RwLockWriteGuard<'_, T> {
+ fn drop(&mut self) {
+ // SAFETY: We acquired the write lock in RwLock::write()
+ unsafe {
+ wasmtime_sync_rwlock_write_release(self.lock.lock.storage.get());
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/examples/min-platform/build.sh b/examples/min-platform/build.sh
index 728ffa9198..b78a36b2c4 100755
--- a/examples/min-platform/build.sh
+++ b/examples/min-platform/build.sh
@@ -26,6 +26,11 @@ if [ "$WASMTIME_SIGNALS_BASED_TRAPS" = "1" ]; then
features="$features,custom"
fi
+if [ "$WASMTIME_CUSTOM_SYNC" = "1" ]; then
+ cflags="$cflags -DWASMTIME_CUSTOM_SYNC"
+ features="$features,custom-sync-primitives"
+fi
+
if [ "$MIN_PLATFORM_EXAMPLE_DISABLE_WASI" != "1" ]; then
features="$features,wasi"
cargo build \
diff --git a/examples/min-platform/embedding/cbindgen.toml b/examples/min-platform/embedding/cbindgen.toml
index e0602eb1c8..dca40a0594 100644
--- a/examples/min-platform/embedding/cbindgen.toml
+++ b/examples/min-platform/embedding/cbindgen.toml
@@ -21,6 +21,7 @@ header = """
// then the symbols will not be required.
//
// * `WASMTIME_SIGNALS_BASED_TRAPS` - corresponds to `signals-based-traps`
+// * `WASMTIME_CUSTOM_SYNC` - corresponds to `custom-sync-primitives`
//
// Some more information about this header can additionally be found at
// <https://docs.wasmtime.dev/stability-platform-support.html>.
@@ -29,3 +30,4 @@ header = """
[defines]
has_virtual_memory = 'WASMTIME_VIRTUAL_MEMORY'
has_native_signals = 'WASMTIME_NATIVE_SIGNALS'
+has_custom_sync = 'WASMTIME_CUSTOM_SYNC'
diff --git a/examples/min-platform/embedding/wasmtime-platform.c b/examples/min-platform/embedding/wasmtime-platform.c
index 4d582a46a8..ee174dc12f 100644
--- a/examples/min-platform/embedding/wasmtime-platform.c
+++ b/examples/min-platform/embedding/wasmtime-platform.c
@@ -130,10 +130,130 @@ void wasmtime_memory_image_free(struct wasmtime_memory_image *image) {
#endif // WASMTIME_VIRTUAL_MEMORY
-// Pretend that this platform doesn't have threads where storing in a static is
-// ok.
+#ifdef WASMTIME_CUSTOM_SYNC
+
+// Multi-threaded TLS using pthread
+#include <pthread.h>
+
+static pthread_key_t wasmtime_tls_key;
+static pthread_once_t wasmtime_tls_key_once = PTHREAD_ONCE_INIT;
+
+static void make_tls_key(void) { pthread_key_create(&wasmtime_tls_key, NULL); }
+
+uint8_t *wasmtime_tls_get(void) {
+ pthread_once(&wasmtime_tls_key_once, make_tls_key);
+ return (uint8_t *)pthread_getspecific(wasmtime_tls_key);
+}
+
+void wasmtime_tls_set(uint8_t *val) {
+ pthread_once(&wasmtime_tls_key_once, make_tls_key);
+ pthread_setspecific(wasmtime_tls_key, val);
+}
+
+#else
+
+// Single-threaded TLS using a static variable
static uint8_t *WASMTIME_TLS = NULL;
-uint8_t *wasmtime_tls_get() { return WASMTIME_TLS; }
+uint8_t *wasmtime_tls_get(void) { return WASMTIME_TLS; }
void wasmtime_tls_set(uint8_t *val) { WASMTIME_TLS = val; }
+
+#endif
+
+#ifdef WASMTIME_CUSTOM_SYNC
+
+#include <stdlib.h>
+
+void wasmtime_sync_lock_free(uintptr_t *lock) {
+ if (*lock != 0) {
+ pthread_mutex_t *mutex = (pthread_mutex_t *)*lock;
+ pthread_mutex_destroy(mutex);
+ free(mutex);
+ *lock = 0;
+ }
+}
+
+void wasmtime_sync_lock_acquire(uintptr_t *lock) {
+ pthread_mutex_t *mutex = (pthread_mutex_t *)*lock;
+ if (mutex == NULL) {
+ pthread_mutex_t *new_mutex = malloc(sizeof(pthread_mutex_t));
+ if (new_mutex == NULL) {
+ abort();
+ }
+ pthread_mutex_init(new_mutex, NULL);
+
+ // Atomically set lock only if it's still NULL
+ if (!__sync_bool_compare_and_swap(lock, 0, (uintptr_t)new_mutex)) {
+ pthread_mutex_destroy(new_mutex);
+ free(new_mutex);
+ }
+ mutex = (pthread_mutex_t *)*lock;
+ }
+ pthread_mutex_lock(mutex);
+}
+
+void wasmtime_sync_lock_release(uintptr_t *lock) {
+ pthread_mutex_t *mutex = (pthread_mutex_t *)*lock;
+ pthread_mutex_unlock(mutex);
+}
+
+void wasmtime_sync_rwlock_free(uintptr_t *lock) {
+ if (*lock != 0) {
+ pthread_rwlock_t *rwlock = (pthread_rwlock_t *)*lock;
+ pthread_rwlock_destroy(rwlock);
+ free(rwlock);
+ *lock = 0;
+ }
+}
+
+void wasmtime_sync_rwlock_read(uintptr_t *lock) {
+ pthread_rwlock_t *rwlock = (pthread_rwlock_t *)*lock;
+ if (rwlock == NULL) {
+ pthread_rwlock_t *new_rwlock = malloc(sizeof(pthread_rwlock_t));
+ if (new_rwlock == NULL) {
+ abort();
+ }
+ pthread_rwlock_init(new_rwlock, NULL);
+
+ // Atomically set lock only if it's still NULL
+ if (!__sync_bool_compare_and_swap(lock, 0, (uintptr_t)new_rwlock)) {
+ pthread_rwlock_destroy(new_rwlock);
+ free(new_rwlock);
+ }
+ rwlock = (pthread_rwlock_t *)*lock;
+ }
+ pthread_rwlock_rdlock(rwlock);
+}
+
+void wasmtime_sync_rwlock_read_release(uintptr_t *lock) {
+ pthread_rwlock_t *rwlock = (pthread_rwlock_t *)*lock;
+ pthread_rwlock_unlock(rwlock);
+}
+
+void wasmtime_sync_rwlock_write(uintptr_t *lock) {
+ pthread_rwlock_t *rwlock = (pthread_rwlock_t *)*lock;
+ if (rwlock == NULL) {
+ pthread_rwlock_t *new_rwlock = malloc(sizeof(pthread_rwlock_t));
+ if (new_rwlock == NULL) {
+ abort();
+ }
+ pthread_rwlock_init(new_rwlock, NULL);
+
+ // Atomically set lock only if it's still NULL
+ if (!__sync_bool_compare_and_swap(lock, 0, (uintptr_t)new_rwlock)) {
+ // Another thread won the race, discard our allocation
+ pthread_rwlock_destroy(new_rwlock);
+ free(new_rwlock);
+ }
+ rwlock = (pthread_rwlock_t *)*lock;
+ }
+ pthread_rwlock_wrlock(rwlock);
+}
+
+void wasmtime_sync_rwlock_write_release(uintptr_t *lock) {
+ pthread_rwlock_t *rwlock = (pthread_rwlock_t *)*lock;
+ pthread_rwlock_unlock(rwlock);
+}
+
+#endif // WASMTIME_CUSTOM_SYNC
diff --git a/examples/min-platform/embedding/wasmtime-platform.h b/examples/min-platform/embedding/wasmtime-platform.h
index dda4f279aa..b04310cde5 100644
--- a/examples/min-platform/embedding/wasmtime-platform.h
+++ b/examples/min-platform/embedding/wasmtime-platform.h
@@ -15,6 +15,7 @@
// then the symbols will not be required.
//
// * `WASMTIME_SIGNALS_BASED_TRAPS` - corresponds to `signals-based-traps`
+// * `WASMTIME_CUSTOM_SYNC` - corresponds to `custom-sync-primitives`
//
// Some more information about this header can additionally be found at
// <https://docs.wasmtime.dev/stability-platform-support.html>.
@@ -23,7 +24,7 @@
#ifndef _WASMTIME_PLATFORM_H
#define _WASMTIME_PLATFORM_H
-/* Generated with cbindgen:0.28.0 */
+/* Generated with cbindgen:0.29.0 */
#include <stdarg.h>
#include <stdbool.h>
@@ -253,6 +254,80 @@ extern uint8_t *wasmtime_tls_get(void);
*/
extern void wasmtime_tls_set(uint8_t *ptr);
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Frees a synchronization lock.
+ *
+ * May be called on a lock that was never used (still has a zero pattern).
+ * The implementor must handle this case gracefully.
+ */
+extern void wasmtime_sync_lock_free(uintptr_t *lock);
+#endif
+
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Acquires an exclusive lock.
+ *
+ * If the lock is uninitialized (zero pattern), it will be initialized lazily.
+ * This function blocks until the lock is acquired.
+ * Must be paired with [`wasmtime_sync_lock_release`].
+ */
+extern void wasmtime_sync_lock_acquire(uintptr_t *lock);
+#endif
+
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Releases an exclusive lock previously acquired with [`wasmtime_sync_lock_acquire`].
+ */
+extern void wasmtime_sync_lock_release(uintptr_t *lock);
+#endif
+
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Acquires a read lock on an RwLock.
+ *
+ * If the lock is uninitialized (zero pattern), it will be initialized lazily.
+ * Multiple readers can hold the lock simultaneously.
+ * Must be paired with [`wasmtime_sync_rwlock_read_release`].
+ */
+extern void wasmtime_sync_rwlock_read(uintptr_t *lock);
+#endif
+
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Releases a read lock previously acquired with [`wasmtime_sync_rwlock_read`].
+ */
+extern void wasmtime_sync_rwlock_read_release(uintptr_t *lock);
+#endif
+
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Acquires a write lock on an RwLock.
+ *
+ * If the lock is uninitialized (zero pattern), it will be initialized lazily.
+ * Only one writer can hold the lock, and no readers can be present.
+ * Must be paired with [`wasmtime_sync_rwlock_write_release`].
+ */
+extern void wasmtime_sync_rwlock_write(uintptr_t *lock);
+#endif
+
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Releases a write lock previously acquired with [`wasmtime_sync_rwlock_write`].
+ */
+extern void wasmtime_sync_rwlock_write_release(uintptr_t *lock);
+#endif
+
+#if defined(WASMTIME_CUSTOM_SYNC)
+/**
+ * Frees an RwLock.
+ *
+ * May be called on a lock that was never used (still has a zero pattern).
+ * The implementor must handle this case gracefully.
+ */
+extern void wasmtime_sync_rwlock_free(uintptr_t *lock);
+#endif
+
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus