Eliminate cyclic locks in runtime

This change introduces a new deadlock detector for Cosmo's POSIX threads
implementation. Error check mutexes will now track a DAG of nested locks
and report EDEADLK when a deadlock is theoretically possible. These will
occur rarely, but it's important for production hardening your code. You
don't even need to change your mutexes to use the POSIX error check mode
because `cosmocc -mdbg` will enable error checking on mutexes by default
globally. When cycles are found, an error message showing your demangled
symbols describing the strongly connected component are printed and then
the SIGTRAP is raised, which means you'll also get a backtrace if you're
using ShowCrashReports() too. This new error checker is so low-level and
so pure that it's able to verify the relationships of every libc runtime
lock, including those locks upon which the mutex implementation depends.
This commit is contained in:
Justine Tunney 2024-12-16 20:51:27 -08:00
parent 26c051c297
commit af7bd80430
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
141 changed files with 2094 additions and 1601 deletions

View file

@ -16,47 +16,26 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/intrin/weaken.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/internal.h"
#include "libc/stdio/stdio.h"
/**
* Closes standard i/o stream and its underlying thing.
*
* @param f is the file object
* @return 0 on success or -1 on error, which can be a trick for
* differentiating between EOF and real errors during previous
* i/o calls, without needing to call ferror()
* @return 0 on success, or EOF w/ errno
*/
int fclose(FILE *f) {
int rc;
if (!f)
return 0;
__fflush_unregister(f);
fflush(f);
if (_weaken(free)) {
_weaken(free)(f->getln);
if (!f->nofree && f->buf != f->mem) {
_weaken(free)(f->buf);
}
}
f->state = EOF;
if (f->noclose) {
int rc = 0;
if (f) {
flockfile(f);
rc |= fflush(f);
int fd = f->fd;
f->fd = -1;
} else if (f->fd != -1 && close(f->fd) == -1) {
f->state = errno;
f->state = EOF;
if (fd != -1)
rc |= close(fd);
funlockfile(f);
__stdio_unref(f);
}
if (f->state == EOF) {
rc = 0;
} else {
errno = f->state;
rc = EOF;
}
__stdio_free(f);
return rc;
}