Fix WASI threading regression with minimal invasive change

Recent changes made WASI targets use the Unix threading implementation, but
WASI does not support threading. When the Unix code tries to call
pthread_create, it fails with EAGAIN, causing libraries like rayon to
panic when trying to initialize their global thread pool.

This fix adds an early return in Thread::new() that checks for WASI and
returns UNSUPPORTED_PLATFORM. This approach:
- Continues using most of the unix.rs code path (less invasive)
- Only requires a small cfg check at the start of Thread::new()
- Can be easily removed once wasi-sdk is updated with the proper fix

The real fix is being tracked in `WebAssembly/wasi-libc#716` which will
change the error code returned by pthread_create to properly indicate
unsupported operations. Once that propagates to wasi-sdk, this workaround
can be removed.

Fixes the regression where rayon-based code (e.g., lopdf in PDF handling)
panicked on WASI after nightly-2025-12-10.

Before fix:
  pthread_create returns EAGAIN (error code 6)
  ThreadPoolBuildError { kind: IOError(Os { code: 6,
  kind: WouldBlock, message: "Resource temporarily unavailable" }) }

After fix:
  Thread::new returns Err(io::Error::UNSUPPORTED_PLATFORM)
  Libraries can gracefully handle the lack of threading support
This commit is contained in:
Colin Murphy 2026-01-12 10:45:24 -05:00
parent b115ea2e6a
commit c1bcae0638

View file

@ -45,6 +45,15 @@ impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
pub unsafe fn new(stack: usize, init: Box<ThreadInit>) -> io::Result<Thread> {
// FIXME: remove this block once wasi-sdk is updated with the fix from
// https://github.com/WebAssembly/wasi-libc/pull/716
// WASI does not support threading via pthreads. While wasi-libc provides
// pthread stubs, pthread_create returns EAGAIN, which causes confusing
// errors. We return UNSUPPORTED_PLATFORM directly instead.
if cfg!(target_os = "wasi") {
return Err(io::Error::UNSUPPORTED_PLATFORM);
}
let data = init;
let mut attr: mem::MaybeUninit<libc::pthread_attr_t> = mem::MaybeUninit::uninit();
assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0);