Fix fork waiter leak in nsync

This change fixes a bug where nsync waiter objects would leak. It'd mean
that long-running programs like runitd would run out of file descriptors
on NetBSD where waiter objects have ksem file descriptors. On other OSes
this bug is mostly harmless since the worst that can happen with a futex
is to leak a little bit of ram. The bug was caused because tib_nsync was
sneaking back in after the finalization code had cleared it. This change
refactors the thread exiting code to handle nsync teardown appropriately
and in making this change I found another issue, which is that user code
which is buggy, and tries to exit without joining joinable threads which
haven't been detached, would result in a deadlock. That doesn't sound so
bad, except the main thread is a joinable thread. So this deadlock would
be triggered in ways that put libc at fault. So we now auto-join threads
and libc will log a warning to --strace when that happens for any thread
This commit is contained in:
Justine Tunney 2024-12-31 00:55:15 -08:00
parent fd7da586b5
commit 98c5847727
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
35 changed files with 299 additions and 173 deletions

View file

@ -18,11 +18,13 @@
*/
#include "libc/assert.h"
#include "libc/atomic.h"
#include "libc/calls/calls.h"
#include "libc/cosmo.h"
#include "libc/cxxabi.h"
#include "libc/dce.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/cxaatexit.h"
#include "libc/intrin/describebacktrace.h"
#include "libc/intrin/strace.h"
#include "libc/intrin/weaken.h"
#include "libc/limits.h"
@ -97,13 +99,15 @@ wontreturn void pthread_exit(void *rc) {
// notice how we avoid acquiring the pthread gil
if (!(population = atomic_fetch_sub(&_pthread_count, 1) - 1)) {
// we know for certain we're an orphan. any other threads that
// exist, will terminate and clear their tid very soon. but...
// some goofball could spawn more threads from atexit handlers
// exist, will terminate and clear their tid very soon. but some
// goofball could spawn more threads from atexit() handlers. we'd
// also like to avoid looping forever here, by auto-joining threads
// that leaked, because the user forgot to join them or detach them
for (;;) {
_pthread_decimate();
if (_weaken(__cxa_finalize))
_weaken(__cxa_finalize)(NULL);
_pthread_decimate(kPosixThreadTerminated);
if (pthread_orphan_np()) {
if (_weaken(__cxa_finalize))
_weaken(__cxa_finalize)(NULL);
population = atomic_load(&_pthread_count);
break;
}
@ -147,8 +151,8 @@ wontreturn void pthread_exit(void *rc) {
// check if the main thread has died whilst children live
// note that the main thread is joinable by child threads
if (pt->pt_flags & PT_STATIC) {
atomic_store_explicit(&tib->tib_tid, 0, memory_order_release);
cosmo_futex_wake((atomic_int *)&tib->tib_tid, INT_MAX,
atomic_store_explicit(&tib->tib_ctid, 0, memory_order_release);
cosmo_futex_wake((atomic_int *)&tib->tib_ctid, INT_MAX,
!IsWindows() && !IsXnu());
_Exit1(0);
}