stdarch icon indicating copy to clipboard operation
stdarch copied to clipboard

Missing "# Safety" documentation for wasm32 atomic operations

Open yilin0518 opened this issue 6 days ago • 1 comments

I found that in library\stdarch\crates\core_arch\src\wasm32\atomic.rs, there are three atomic operations marked unsafe but don't have # Safety section. But these APIs may be wrongly used and cause error.

For these unsafe APIs, I think adding safety requirements are necessary, but there remains problems: What requirements should add in Rust side?

I think alignment, the validity of pointer, and no concurrent non-atomic access are necessary. But maybe they should add more requirements.

Given that these APIs internally use llvm intrinsic, these APIs can't be checked by Miri. So I asked AI to generate some test cases and find that there are cases will cause wasm runtime to trap and case Runtime error, and in some cases there are not runtime errors, but the bahaviour seems wrong in Rust side. So I paste these test codes.

Below is my cases and reproduction procudure.

  1. create a new lib crate, for example: cargo new wasm_atomic_test. Adding such a line below [lib] in cargo.toml: crate-type = ["cdylib"]
  2. Adding the follow code in lib.rs which contains test cases(Including alignment, out-of-bound/null pointer, uninitialized memory):
#![no_std]
#![feature(stdarch_wasm_atomic_wait)]

use core::arch::wasm32::{
    memory_atomic_notify, memory_atomic_wait32, memory_atomic_wait64, memory_size,
};
use core::cell::UnsafeCell;
use core::hint::black_box;
use core::mem::MaybeUninit;
use core::panic::PanicInfo;
use core::ptr;
use core::sync::atomic::{AtomicI32, Ordering};

#[panic_handler]
fn panic(_: &PanicInfo) -> ! {
    core::arch::wasm32::unreachable()
}

struct SyncCell(UnsafeCell<i32>);
unsafe impl Sync for SyncCell {}
static SLOT: SyncCell = SyncCell(UnsafeCell::new(0));

// 1. Misaligned pointers -> Wasm runtime trap
#[unsafe(no_mangle)]
pub unsafe extern "C" fn trap_unaligned_wait32() -> i32 {
    #[repr(align(4))]
    struct Buf([u8; 8]);
    let mut buf = Buf([0; 8]);
    let ptr = unsafe { buf.0.as_mut_ptr().add(1).cast::<i32>() };
    unsafe { memory_atomic_wait32(ptr, 0, 0) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn trap_unaligned_wait64() -> i32 {
    #[repr(align(8))]
    struct Buf([u8; 16]);
    let mut buf = Buf([0; 16]);
    let ptr = unsafe { buf.0.as_mut_ptr().add(4).cast::<i64>() };
    unsafe { memory_atomic_wait64(ptr, 0, 0) }
}

// 2. Out-of-bounds / null pointer
#[unsafe(no_mangle)]
pub unsafe extern "C" fn trap_oob_wait32() -> i32 {
    let oob = (memory_size::<0>() * 65536) as *mut i32;
    unsafe { memory_atomic_wait32(oob, 0, 0) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn ub_null_wait32() -> i32 {
    // Does not trap by default on wasm32: silently accesses linear address 0
    unsafe { memory_atomic_wait32(ptr::null_mut(), 0, 0) }
}

// 3. Uninitialized memory -> reads stale stack garbage and unexpectedly blocks/times out (returns 2)
#[inline(never)]
fn poison_stack() {
    let mut buf = [0x1234_5678i32; 16];
    black_box(&mut buf);
}

#[inline(never)]
fn wait_uninit() -> i32 {
    let mut uninit = MaybeUninit::<[i32; 16]>::uninit();
    unsafe { memory_atomic_wait32(uninit.as_mut_ptr().cast(), 0x1234_5678, 0) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn ub_uninit_wait32() -> i32 {
    poison_stack();
    wait_uninit()
}
  1. create a test_wasm.mjs in the same directory, containing the following content:
import fs from "node:fs";

const WASM = "./target/wasm32-unknown-unknown/release/wasm_atomic_test.wasm";

const memory = new WebAssembly.Memory({ initial: 20, maximum: 32, shared: true });
const { instance } = await WebAssembly.instantiate(fs.readFileSync(WASM), {
  env: { memory },
});
const exp = instance.exports;
exp.__wasm_init_memory?.();

for (const name of ["trap_unaligned_wait32", "trap_unaligned_wait64", "trap_oob_wait32"]) {
  try {
    exp[name]();
  } catch (e) {
    console.log(`${name}: ${e.name}: ${e.message}`);
  }
}

console.log("ub_null_wait32:", exp.ub_null_wait32());
console.log("ub_uninit_wait32:", exp.ub_uninit_wait32());
  1. use the following command to compile and run tests:

Install:

rustup +nightly target add wasm32-unknown-unknown

Compile:

RUSTFLAGS="-C target-feature=+atomics,+bulk-memory,+mutable-globals \
  -C link-arg=--shared-memory -C link-arg=--max-memory=2097152 \
  -C link-arg=--import-memory -C link-arg=--export-memory" \
  cargo +nightly build --release --target wasm32-unknown-unknown

Run:

node test_wasm.mjs

yilin0518 avatar Nov 30 '26 11:11 yilin0518

The device I use is Ubuntu 22.04.5 LTS. The rustc version is rustc 1.98.0-nightly (9e2abe0c6 2026-06-16).

After running these commands, you can get such output:

trap_unaligned_wait32: RuntimeError: operation does not support unaligned accesses
trap_unaligned_wait64: RuntimeError: operation does not support unaligned accesses
trap_oob_wait32: RuntimeError: memory access out of bounds
ub_null_wait32: 2
ub_uninit_wait32: 2

Some explanation about this issue:

  1. trap_unaligned_wait32 and trap_unaligned_wait64 test the alignment requirement, and I found that if not aligned the wasm runtime will report an error.
  2. trap_oob_wait32 tests the out-of-bound requirement. The inner oob is the address just past the end of linear memory.
  3. ub_null_wait32: This case passes the null pointer, and I found that this will not cause compile error and runtime error. This function returned 2, indicating that the null pointer is allowed in wasm runtime.
  4. ub_uninit_wait32: This case tests the uninitialized state of memory. The memory use by buf in poison_stack is already freed when wait_uninit is called in ub_uninit_wait32. But it can still use that value. The return 2 indicating wasm runtime use that memory, which has not been initialized by wait_uninit itself.

Also, I think these atomic APIs should follow the atomic rules: https://doc.rust-lang.org/core/sync/atomic/index.html#memory-model-for-atomic-accesses

yilin0518 avatar Nov 30 '26 12:11 yilin0518