Skip to content
Merged
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
39 changes: 27 additions & 12 deletions crates/wasi-threads/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
//! [`wasi-threads`]: https://github.com/WebAssembly/wasi-threads

use anyhow::{anyhow, Result};
use rand::Rng;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
use std::thread;
use wasmtime::{Caller, ExternType, InstancePre, Linker, Module, SharedMemory, Store, ValType};
Expand All @@ -16,12 +16,14 @@ const WASI_ENTRY_POINT: &str = "wasi_thread_start";

pub struct WasiThreadsCtx<T> {
instance_pre: Arc<InstancePre<T>>,
tid: AtomicI32,
}

impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {
pub fn new(module: Module, linker: Arc<Linker<T>>) -> Result<Self> {
let instance_pre = Arc::new(linker.instantiate_pre(&module)?);
Ok(Self { instance_pre })
let tid = AtomicI32::new(0);
Ok(Self { instance_pre, tid })
}

pub fn spawn(&self, host: T, thread_start_arg: i32) -> Result<i32> {
Expand All @@ -45,8 +47,14 @@ impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {
return Ok(-1);
}

let wasi_thread_id = self.next_thread_id();
if wasi_thread_id.is_none() {
log::error!("ran out of valid thread IDs");
return Ok(-1);
}
let wasi_thread_id = wasi_thread_id.unwrap();

// 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 || {
// Catch any panic failures in host code; e.g., if a WASI module
Expand Down Expand Up @@ -89,16 +97,23 @@ impl<T: Clone + Send + 'static> WasiThreadsCtx<T> {

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
/// Helper for generating valid WASI thread IDs (TID).
///
/// Callers of `wasi_thread_spawn` expect a TID in range of 0 < TID <= 0x1FFFFFFF
/// to indicate a successful spawning of the thread whereas a negative
/// return value indicates an failure to spawn.
fn next_thread_id(&self) -> Option<i32> {
match self
.tid
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| match v {
..=0x1ffffffe => Some(v + 1),
_ => None,
}) {
Ok(v) => Some(v + 1),
Err(_) => None,
}
}
}

/// Manually add the WASI `thread_spawn` function to the linker.
Expand Down