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

@ -21,9 +21,25 @@
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
//
// - tib_ptid: always guaranteed to be non-zero in thread itself. on
// some platforms (e.g. xnu) the parent thread and other
// threads may need to wait for this value to be set. this
// is generally the value you want to read to get the tid.
//
// - tib_ctid: starts off as -1. once thread starts, it's set to the
// thread's tid before calling the thread callback. when
// thread is done executing, this is set to zero, and then
// this address is futex woken, in case the parent thread or
// any other thread is waiting on its completion. when a
// thread wants to read its own tid, it shouldn't use this,
// because the thread might need to do things after clearing
// its own tib_ctid (see pthread_exit() for static thread).
//
int _pthread_tid(struct PosixThread *pt) {
int tid = 0;
while (pt && !(tid = atomic_load_explicit(&pt->ptid, memory_order_acquire)))
while (pt && !(tid = atomic_load_explicit(&pt->tib->tib_ptid,
memory_order_acquire)))
pthread_yield_np();
return tid;
}