cosmopolitan/libc/thread/lock.h
Justine Tunney af7bd80430
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.
2024-12-16 22:25:12 -08:00

46 lines
2.4 KiB
C

#ifndef COSMOPOLITAN_LIBC_THREAD_LOCK_H_
#define COSMOPOLITAN_LIBC_THREAD_LOCK_H_
COSMOPOLITAN_C_START_
//
// ┌undead
// │
// │┌dead
// ││
// ││┌robust
// │││
// │││ ┌depth
// │││ │
// COSMOPOLITAN MUTEXES │││ │ ┌waited
// │││ │ │
// │││ │ │┌locked
// │││ │ ││
// │││ │ ││┌pshared
// owner │││ │ │││
// tid │││ │ │││┌type
// │ │││ │ ││││
// ┌──────────────┴───────────────┐ │││┌─┴──┐│││├┐
// 0b0000000000000000000000000000000000000000000000000000000000000000
//
#define MUTEX_DEPTH_MIN 0x00000020ull
#define MUTEX_DEPTH_MAX 0x000007e0ull
#define MUTEX_TYPE(word) ((word) & 3)
#define MUTEX_PSHARED(word) ((word) & 4)
#define MUTEX_LOCKED(word) ((word) & 8)
#define MUTEX_WAITED(word) ((word) & 16)
#define MUTEX_DEPTH(word) ((word) & MUTEX_DEPTH_MAX)
#define MUTEX_OWNER(word) ((word) >> 32)
#define MUTEX_LOCK(word) (((word) & 7) | 8)
#define MUTEX_UNLOCK(word) ((word) & 7)
#define MUTEX_SET_WAITED(word) ((word) | 16)
#define MUTEX_SET_TYPE(word, type) (((word) & ~3ull) | (type))
#define MUTEX_SET_PSHARED(word, pshared) (((word) & ~4ull) | (pshared))
#define MUTEX_INC_DEPTH(word) ((word) + MUTEX_DEPTH_MIN)
#define MUTEX_DEC_DEPTH(word) ((word) - MUTEX_DEPTH_MIN)
#define MUTEX_SET_OWNER(word, tid) ((uint64_t)(tid) << 32 | (uint32_t)(word))
COSMOPOLITAN_C_END_
#endif /* COSMOPOLITAN_LIBC_THREAD_LOCK_H_ */