From e9990a22509e10e7bc7726d3d39f5c7ff7f98e36 Mon Sep 17 00:00:00 2001 From: Andrew Brown Date: Mon, 16 Oct 2023 10:26:22 -0700 Subject: [PATCH] WIP: add support for `pthread_atfork` This change is an experiment to enable `pthread_atfork` support under the mistaken assumption that it may have been called during thread creation. I no longer believe it is, so this is not a good idea. Here's how the registered handlers are executed, though: + prepare handlers are called in the parent before the fork with `__fork_handler(-1)` + parent handlers are called after the fork with `__fork_handler(0)`; fork returns the PID to the parent, which is negated (`!ret`) + child handlers are called after the fork with `__fork_handler(1)`; fork returns 0 to the child, which is negated (`!ret`) --- Makefile | 1 + expected/wasm32-wasi-threads/defined-symbols.txt | 2 ++ libc-top-half/musl/src/thread/pthread_create.c | 3 +++ 3 files changed, 6 insertions(+) diff --git a/Makefile b/Makefile index 7f79c7139..cec15eefe 100644 --- a/Makefile +++ b/Makefile @@ -206,6 +206,7 @@ LIBC_TOP_HALF_MUSL_SOURCES += \ thread/__wait.c \ thread/__timedwait.c \ thread/default_attr.c \ + thread/pthread_atfork.c \ thread/pthread_attr_destroy.c \ thread/pthread_attr_get.c \ thread/pthread_attr_init.c \ diff --git a/expected/wasm32-wasi-threads/defined-symbols.txt b/expected/wasm32-wasi-threads/defined-symbols.txt index c913f1620..2f533ad11 100644 --- a/expected/wasm32-wasi-threads/defined-symbols.txt +++ b/expected/wasm32-wasi-threads/defined-symbols.txt @@ -63,6 +63,7 @@ __flbf __floatscan __fmodeflags __fopen_rb_ca +__fork_handler __fpending __fpurge __fputwc_unlocked @@ -977,6 +978,7 @@ program_invocation_name program_invocation_short_name pselect psignal +pthread_atfork pthread_attr_destroy pthread_attr_getdetachstate pthread_attr_getguardsize diff --git a/libc-top-half/musl/src/thread/pthread_create.c b/libc-top-half/musl/src/thread/pthread_create.c index 450fe15ad..3102bfe0c 100644 --- a/libc-top-half/musl/src/thread/pthread_create.c +++ b/libc-top-half/musl/src/thread/pthread_create.c @@ -315,6 +315,7 @@ hidden void __wasi_thread_start_C(int tid, void *p) // without waiting. atomic_store((atomic_int *) &(self->tid), tid); // Execute the user's start function. + __fork_handler(1); __pthread_exit(args->start_func(args->start_arg)); } #endif @@ -540,7 +541,9 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att * of the current module and start executing the entry function. The * wasi-threads specification requires the module to export a * `wasi_thread_start` function, which is invoked with `args`. */ + __fork_handler(-1); ret = __wasi_thread_spawn((void *) args); + __fork_handler(0); #endif #ifdef __wasilibc_unmodified_upstream