wasi-libc icon indicating copy to clipboard operation
wasi-libc copied to clipboard

Calling `pthread_create` with a stack size of 2047 (or at the default) results in an "out of memory" error, but 2048 works

Open fatlotus opened this issue 1 month ago • 2 comments

Here's my example program:

#include <pthread.h>
#include <stdio.h>

void *thread_func(void *arg) {
  printf("The thread is running!\n");
  return NULL;
}

int main() {
  printf("Starting\n");
  pthread_t thread;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setstacksize(&attr, 2047); // <- 2048 (and above) works, 2047 (and below) does NOT work
  if (pthread_create(&thread, &attr, thread_func, NULL) != 0) {
    perror("pthread_create");
    return 1;
  }
  pthread_join(thread, NULL);
  printf("Done\n");
  return 0;
}

Here's main.c as a WAT file: main.wat.txt

I'm compiling and running with the following commands:

# With a stack size of 2048 or greater
$ /opt/homebrew/opt/llvm/bin/clang -Wl,--import-memory,--export-memory -g --target=wasm32-wasip1-threads --sysroot=~/Downloads/wasi-sdk-29.0-arm64-macos/share/wasi-sysroot main.c -o main.wasm
$ wasmtime run --wasi threads=y --wasm threads=y main.wasm
Starting
The thread is running!
Done

# With a stack size of 2047 or less
$ /opt/homebrew/opt/llvm/bin/clang -Wl,--import-memory,--export-memory -g --target=wasm32-wasip1-threads --sysroot=~/Downloads/wasi-sdk-29.0-arm64-macos/share/wasi-sysroot main.c -o main.wasm
$ wasmtime run --wasi threads=y --wasm threads=y main.wasm
Starting
pthread_create: Out of memory

It also fails if you leave the stack size as the default.

Platform: I'm using an macOS 14.6.1 on an M1, with Homebrew Clang, a pre-built WASI sysroot, and wasm32-wasip1-threads, though it also repros with wasm32-wasi-threads.

Looking through the code, I see a PTHREAD_STACK_MIN config variable set to 2048 which.. would seem to explain this behavior, though I can't find any place outside of pthread_attr_setstack where it ever gets read. It also seems strange that the default behavior of pthread would result in a stack that's too small.

fatlotus avatar Dec 25 '25 21:12 fatlotus