ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
mutex.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE 4096
4#define DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE 256
5#define DEBUG_MUTEX_MUTEX_NAME_BUFFER_SIZE 256
6#define DEBUG_MUTEX_HELD_BY_NAME_BUFFER_SIZE 256
7#define DEBUG_MUTEX_STUCK_BUFFER_SIZE 64
8#define DEBUG_MUTEX_COND_BUFFER_SIZE 1024
9#define DEBUG_MUTEX_NAME_BUFFER_SIZE 256
10
21
22#include <ascii-chat/api.h>
25#include <ascii-chat/log/log.h>
26#include <ascii-chat/otel.h>
27#include <ascii-chat/source_root.h>
31#include <libplatform/cond.h>
32#include <libplatform/mutex.h>
33#include <libplatform/thread.h>
34#include <string.h>
35
36// ============================================================================
37// Per-thread Lock Stack Storage
38// ============================================================================
39
40#define MUTEX_STACK_MAX_DEPTH 64
41
50
51static void stack_lock(thread_lock_stack_t *stack) {
52 int expected = 0;
53 while (!atomic_cas_int(&stack->guard, &expected, 1))
54 expected = 0;
55}
56
57static void stack_unlock(thread_lock_stack_t *stack) {
58 atomic_store_int(&stack->guard, 0);
59}
60
61// Global registry of all threads that have used mutexes
62#define MAX_THREADS 256
69typedef struct {
70 thread_id_t thread_id;
71 thread_lock_stack_t *stack; // Heap-allocated stack per thread
75
76static thread_registry_entry_t g_thread_registry[MAX_THREADS] = {0};
77static atomic_t g_thread_registry_count = {0};
78static atomic_t g_registry_guard = {0};
79
80static void registry_lock(void) {
81 int expected = 0;
82 while (!atomic_cas_int(&g_registry_guard, &expected, 1))
83 expected = 0;
84}
85
86static void registry_unlock(void) { atomic_store_int(&g_registry_guard, 0); }
87
88// Thread-local storage key for per-thread lock stack
89// Destructor automatically frees memory when thread exits
90static tls_key_t g_tls_mutex_stack = 0;
91static atomic_t g_tls_initialized = {0};
92
93// Flag set during shutdown to prevent new stack allocations
94// (threads still running at shutdown time won't leak new stacks)
95static atomic_t g_shutting_down = {0};
96
97// Track the mutexes involved in the last detected deadlock for throttling
98#define MAX_CYCLE_MUTEXES 16
99typedef struct {
101 int count;
109static deadlock_state_t g_last_deadlock = {0};
110
111// ============================================================================
112// Thread Registry Management
113// ============================================================================
114
116static void tls_mutex_stack_destructor(void *arg) {
117 if (!arg)
118 return;
119 registry_lock();
120 int count = atomic_load_int(&g_thread_registry_count);
121 for (int i = 0; i < count; ++i) {
122 // Windows FLS deletion can invoke this on the thread deleting the key.
123 // Identify the allocation, rather than assuming the current thread owns it.
124 if (g_thread_registry[i].stack == arg) {
125 g_thread_registry[i].stack = NULL;
126 break;
127 }
128 }
129 registry_unlock();
130 // Matches the untracked allocation used to avoid instrumenting this tracker.
131 free(arg);
132}
133
138static void ensure_tls_initialized(void) {
139 if (!atomic_load_bool(&g_tls_initialized)) {
140 registry_lock();
141 // Try to initialize TLS key with destructor
142 if (!atomic_load_bool(&g_tls_initialized) &&
143 platform_tls_key_create(&g_tls_mutex_stack,
144 tls_mutex_stack_destructor) == 0) {
145 atomic_store_bool(&g_tls_initialized, true);
146 }
147 registry_unlock();
148 }
149}
150
151// Forward declaration
152static void register_thread_if_needed(void);
153
160static thread_lock_stack_t *get_thread_local_stack(void) {
161 // Skip allocation during shutdown (prevents leaks from threads killed
162 // mid-shutdown)
163 if (atomic_load_bool(&g_shutting_down)) {
164 return NULL;
165 }
166
167 // Ensure TLS key is initialized
168 ensure_tls_initialized();
169
170 // Get current thread's stack from TLS
171 thread_lock_stack_t *stack =
172 (thread_lock_stack_t *)platform_tls_get(g_tls_mutex_stack);
173
174 if (stack == NULL) {
175 // Allocate stack on heap for this thread
176 // Use raw malloc() to avoid recursive mutex locking in debug subsystem
177 stack = (thread_lock_stack_t *)malloc(sizeof(thread_lock_stack_t));
178 if (stack) {
179 memset(stack, 0, sizeof(thread_lock_stack_t));
180 // Store in TLS (destructor will free it when thread exits)
181 platform_tls_set(g_tls_mutex_stack, stack);
182 register_thread_if_needed();
183 }
184 }
185 return stack;
186}
187
189static void register_thread_if_needed(void) {
190 static _Thread_local bool registered = false;
191 if (registered)
192 return;
193 thread_lock_stack_t *local_stack = get_thread_local_stack();
194 if (!local_stack)
195 return;
196 thread_id_t current_thread = thread_self();
197 registry_lock();
198 int count = atomic_load_int(&g_thread_registry_count);
199 int slot = -1;
200 for (int i = 0; i < count; ++i) {
201 if (thread_equal(g_thread_registry[i].thread_id, current_thread)) {
202 slot = i;
203 break;
204 }
205 if (!g_thread_registry[i].stack && slot < 0)
206 slot = i;
207 }
208 if (slot < 0 && count < MAX_THREADS)
209 slot = count++;
210 if (slot >= 0) {
211 g_thread_registry[slot].thread_id = current_thread;
212 g_thread_registry[slot].stack = local_stack;
213 atomic_store_int(&g_thread_registry_count, count);
214 }
215 registry_unlock();
216 registered = true;
217}
218
219// ============================================================================
220// Public Stack Operations (Debug builds only)
221// ============================================================================
222
223#ifndef NDEBUG
224
225static void mutex_stack_push(uintptr_t mutex_key, const char *mutex_name,
226 mutex_stack_state_t state) {
227 thread_lock_stack_t *stack = get_thread_local_stack();
228 if (!stack) {
229 return;
230 }
231
232 // Register this thread in the global registry on first mutex use
233 register_thread_if_needed();
234
235 mutex_wait_snapshot_t telemetry = {0};
236 asciichat_error_context_t error = {0};
239 sizeof(telemetry.span_name));
240#ifndef __EMSCRIPTEN__
241 gotel_context_t context = ascii_otel_context();
242 memcpy(telemetry.trace_id, context.trace_id, sizeof(context.trace_id));
243 memcpy(telemetry.span_id, context.span_id, sizeof(context.span_id));
244 telemetry.context_valid = context.valid;
245 telemetry.context_sampled = context.sampled;
246 gotel_span_snapshot_t snapshot = gotel_current_span_snapshot();
247 memcpy(telemetry.parent_span_id, snapshot.parent_span_id,
248 sizeof(telemetry.parent_span_id));
249 telemetry.span_start_unix_ns = snapshot.start_unix_ns;
250#endif
251 (void)HAS_ERRNO(&error);
252 }
253 stack_lock(stack);
254 if (state == MUTEX_STACK_STATE_PENDING) {
255 telemetry.error_code = error.code;
256 memcpy(telemetry.error_message, error.context_message,
257 sizeof(telemetry.error_message));
258 stack->telemetry = telemetry;
259 }
260 if (stack->depth >= MUTEX_STACK_MAX_DEPTH) {
261 stack_unlock(stack);
262 return;
263 }
264 stack->stack[stack->depth].mutex_key = mutex_key;
265 stack->stack[stack->depth].mutex_name = mutex_name;
266 stack->stack[stack->depth].state = state;
267 stack->stack[stack->depth].timestamp_ns = time_get_ns();
268 stack->depth++;
269 stack_unlock(stack);
270}
271
272void mutex_stack_push_pending(uintptr_t mutex_key, const char *mutex_name) {
273 mutex_stack_push(mutex_key, mutex_name, MUTEX_STACK_STATE_PENDING);
274}
275
276void mutex_stack_push_locked(uintptr_t mutex_key, const char *mutex_name) {
277 mutex_stack_push(mutex_key, mutex_name, MUTEX_STACK_STATE_LOCKED);
278}
279
280void mutex_stack_mark_locked(uintptr_t mutex_key) {
281 thread_lock_stack_t *stack = get_thread_local_stack();
282 if (!stack) {
283 return;
284 }
285
286 // Mark the top of the stack as locked
287 stack_lock(stack);
288 if (stack->depth == 0) {
289 stack_unlock(stack);
290 return;
291 }
292 int top = stack->depth - 1;
293 if (stack->stack[top].mutex_key == mutex_key) {
295 stack->stack[top].timestamp_ns = time_get_ns();
296 }
297 stack_unlock(stack);
298
299 // Thread-local only. Registry is populated on-demand by
300 // mutex_stack_get_all_threads()
301}
302
303void mutex_stack_pop(uintptr_t mutex_key) {
304 thread_lock_stack_t *stack = get_thread_local_stack();
305 if (!stack) {
306 return;
307 }
308
309 // Validate top matches
310 stack_lock(stack);
311 if (stack->depth == 0) {
312 stack_unlock(stack);
313 return;
314 }
315 // Locks may be released out of acquisition order. Remove the most recent
316 // matching acquisition, preserving any recursive acquisitions below it.
317 for (int i = stack->depth - 1; i >= 0; --i) {
318 if (stack->stack[i].mutex_key == mutex_key) {
319 memmove(&stack->stack[i], &stack->stack[i + 1],
320 (size_t)(stack->depth - i - 1) * sizeof(stack->stack[0]));
321 --stack->depth;
322 break;
323 }
324 }
325 stack_unlock(stack);
326
327 // Thread-local only. Registry is populated on-demand by
328 // mutex_stack_get_all_threads()
329}
330
331#endif
332
333int mutex_stack_get_current(mutex_stack_entry_t *out_entries, int max_entries) {
334 thread_lock_stack_t *stack = get_thread_local_stack();
335 if (!stack || !out_entries) {
336 return 0;
337 }
338
339 stack_lock(stack);
340 int depth = stack->depth;
341 int count = (depth < max_entries) ? depth : max_entries;
342 memcpy(out_entries, stack->stack, count * sizeof(mutex_stack_entry_t));
343 stack_unlock(stack);
344 return depth; // Return actual depth even if truncated
345}
346
347// ============================================================================
348// Global Thread Stack Access
349// ============================================================================
350
352 int **out_stack_counts, int *out_thread_count) {
353
354 if (!out_stacks || !out_stack_counts || !out_thread_count) {
355 return -1;
356 }
357
358 // Read the thread count with acquire semantics (lock-free, no mutex needed)
359 // Use memory_order_seq_cst to ensure we get a consistent snapshot
360 int thread_count = atomic_load_int(&g_thread_registry_count);
361
362 // Allocate arrays for threads in the registry
363 // Note: SAFE_MALLOC takes bytes as first parameter, not count
364 *out_stacks = SAFE_CALLOC(thread_count, sizeof(mutex_stack_entry_t *),
366 *out_stack_counts = SAFE_CALLOC(thread_count, sizeof(int), int *);
367
368 if (!*out_stacks || !*out_stack_counts) {
369 SAFE_FREE(*out_stacks);
370 SAFE_FREE(*out_stack_counts);
371 return -1;
372 }
373
374 // Copy each thread's stack from the registry
375 // Note: the thread count can change concurrently, so we re-read it in the
376 // loop to avoid accessing out-of-bounds memory if threads exit during
377 // iteration
378 for (int i = 0; i < thread_count; i++) {
379 // Re-check thread count in case registry shrank
380 int current_registry_count = atomic_load_int(&g_thread_registry_count);
381 if (i >= current_registry_count) {
382 break;
383 }
384
385 // Allocate before locking because tracked allocation updates the lock
386 // stack.
387 (*out_stacks)[i] =
390 (*out_stack_counts)[i] = 0;
391 registry_lock();
392 thread_lock_stack_t *src = g_thread_registry[i].stack;
393 if (src) {
394 stack_lock(src);
395 int depth = src->depth;
396 (*out_stack_counts)[i] = depth;
397 memcpy((*out_stacks)[i], src->stack, depth * sizeof(mutex_stack_entry_t));
398 stack_unlock(src);
399 }
400 registry_unlock();
401 }
402
403 *out_thread_count = thread_count;
404 return 0;
405}
406
408 int *stack_counts, int thread_count) {
409
410 if (!stacks || !stack_counts)
411 return;
412
413 for (int i = 0; i < thread_count; i++) {
414 SAFE_FREE(stacks[i]);
415 }
416
417 SAFE_FREE(stacks);
418 SAFE_FREE(stack_counts);
419}
420
421// ============================================================================
422// Deadlock Detection
423// ============================================================================
424
428static bool thread_holds_mutex(thread_lock_stack_t *stack,
429 uintptr_t mutex_key) {
430 if (!stack) {
431 return false;
432 }
433 for (int i = 0; i < stack->depth; i++) {
434 if (stack->stack[i].mutex_key == mutex_key &&
435 stack->stack[i].state == MUTEX_STACK_STATE_LOCKED) {
436 return true;
437 }
438 }
439 return false;
440}
441
445static uintptr_t thread_waiting_for_mutex(thread_lock_stack_t *stack) {
446 if (!stack) {
447 return 0;
448 }
449 if (stack->depth > 0) {
450 int top = stack->depth - 1;
451 if (stack->stack[top].state == MUTEX_STACK_STATE_PENDING) {
452 return stack->stack[top].mutex_key;
453 }
454 }
455 return 0;
456}
457
461static int find_thread_holding_mutex(thread_lock_stack_t *snapshots,
462 int thread_count, uintptr_t mutex_key) {
463 for (int i = 0; i < thread_count; i++) {
464 thread_lock_stack_t *stack = &snapshots[i];
465 if (thread_holds_mutex(stack, mutex_key)) {
466 return i;
467 }
468 }
469 return -1;
470}
471
477#define MAX_CYCLE_LEN 64
478static int detect_cycle_dfs(thread_lock_stack_t *snapshots, int thread_count,
479 int start_thread, int *cycle_path, int *cycle_len) {
480 int visited[MAX_THREADS];
481 int path[MAX_CYCLE_LEN];
482 int path_len = 0;
483
484 // Initialize visited array
485 for (int i = 0; i < MAX_THREADS; i++) {
486 visited[i] = -1; // -1 = not visited, >= 0 = index in path
487 }
488
489 // DFS starting from start_thread
490 int current = start_thread;
491 while (path_len <= MAX_CYCLE_LEN && path_len <= thread_count) {
492 if (current < 0 || current >= thread_count) {
493 break; // Invalid thread
494 }
495
496 // Check if current is already in path (cycle found!)
497 for (int i = 0; i < path_len; i++) {
498 if (path[i] == current) {
499 // Found a cycle! Extract the cycle portion
500 *cycle_len = path_len - i;
501 for (int j = 0; j < *cycle_len; j++) {
502 cycle_path[j] = path[i + j];
503 }
504 return i; // Return where the cycle starts
505 }
506 }
507
508 if (path_len == MAX_CYCLE_LEN || path_len == thread_count)
509 break;
510 // Add current to path
511 path[path_len++] = current;
512
513 // Find next thread in the waits-for graph
514 thread_lock_stack_t *stack = &snapshots[current];
515 uintptr_t waiting_for = thread_waiting_for_mutex(stack);
516
517 if (waiting_for == 0) {
518 break; // No waiting, path ends
519 }
520
521 // Find who holds the mutex we're waiting for
522 current = find_thread_holding_mutex(snapshots, thread_count, waiting_for);
523 }
524
525 *cycle_len = 0;
526 return -1; // No cycle found
527}
528
530 size_t *count, bool *limited) {
531 // A single collector owns this scratch space. Never dereference names from
532 // copied stacks: their registry entries may have been removed meanwhile.
533 static thread_lock_stack_t snapshots[MAX_THREADS];
534 static thread_id_t ids[MAX_THREADS];
535 static atomic_flag sampling = ATOMIC_FLAG_INIT;
536 if (atomic_flag_test_and_set(&sampling))
537 return false;
538 uint64_t expected = 0;
539 if (!atomic_compare_exchange_strong(&g_registry_guard.impl, &expected, 1)) {
540 atomic_flag_clear(&sampling);
541 return false;
542 }
543 int threads = atomic_load_int_impl(&g_thread_registry_count);
544 bool complete = true;
545 for (int i = 0; i < threads; ++i) {
546 thread_lock_stack_t *stack = g_thread_registry[i].stack;
547 ids[i] = g_thread_registry[i].thread_id;
548 snapshots[i].depth = 0;
549 if (!stack)
550 continue;
551 expected = 0;
552 if (!atomic_compare_exchange_strong(&stack->guard.impl, &expected, 1)) {
553 complete = false;
554 break;
555 }
556 snapshots[i].depth = stack->depth;
557 memcpy(snapshots[i].stack, stack->stack, sizeof(stack->stack));
558 snapshots[i].telemetry = stack->telemetry;
559 atomic_store(&stack->guard.impl, 0);
560 }
561 atomic_store(&g_registry_guard.impl, 0);
562 if (complete) {
563 *count = 0;
564 *limited = threads >= MAX_CYCLE_LEN;
565 for (int i = 0; i < threads; ++i) {
566 uintptr_t key = thread_waiting_for_mutex(&snapshots[i]);
567 *limited |= snapshots[i].depth == MUTEX_STACK_MAX_DEPTH;
568 if (!key)
569 continue;
570 if (*count == capacity) {
571 *limited = true;
572 continue;
573 }
574 int path[MAX_CYCLE_LEN], length = 0;
575 bool cycle = thread_holds_mutex(&snapshots[i], key);
576 if (detect_cycle_dfs(snapshots, threads, i, path, &length) >= 0)
577 for (int j = 0; j < length; ++j)
578 cycle |= path[j] == i;
579 mutex_wait_snapshot_t *wait = &waits[(*count)++];
580 *wait = snapshots[i].telemetry;
581 wait->mutex_key = key;
582 wait->thread_key = (uintptr_t)ids[i];
583 wait->since_ns = snapshots[i].stack[snapshots[i].depth - 1].timestamp_ns;
584 wait->cycle = cycle;
585 }
586 }
587 atomic_flag_clear(&sampling);
588 return complete;
589}
590
594static int compare_uintptr(const void *a, const void *b) {
595 uintptr_t ua = *(const uintptr_t *)a;
596 uintptr_t ub = *(const uintptr_t *)b;
597 if (ua < ub)
598 return -1;
599 if (ua > ub)
600 return 1;
601 return 0;
602}
603
608static bool deadlock_mutexes_changed(const uintptr_t *current_mutexes,
609 int count) {
610 if (count != g_last_deadlock.count)
611 return true;
612
613 // Sort both arrays for order-independent comparison
614 uintptr_t current_sorted[MAX_CYCLE_MUTEXES];
615 uintptr_t last_sorted[MAX_CYCLE_MUTEXES];
616
617 for (int i = 0; i < count; i++) {
618 current_sorted[i] = current_mutexes[i];
619 last_sorted[i] = g_last_deadlock.mutexes[i];
620 }
621
622 qsort(current_sorted, count, sizeof(uintptr_t), compare_uintptr);
623 qsort(last_sorted, count, sizeof(uintptr_t), compare_uintptr);
624
625 for (int i = 0; i < count; i++) {
626 if (current_sorted[i] != last_sorted[i])
627 return true;
628 }
629 return false;
630}
631
635static void update_deadlock_state(const uintptr_t *mutexes, int count) {
636 g_last_deadlock.count =
637 (count < MAX_CYCLE_MUTEXES) ? count : MAX_CYCLE_MUTEXES;
638 for (int i = 0; i < g_last_deadlock.count; i++) {
639 g_last_deadlock.mutexes[i] = mutexes[i];
640 }
641}
642
657 // Fixed scratch avoids allocating one list per thread on every 100 ms scan.
658 // Skip a busy snapshot rather than interfering with the threads being
659 // observed.
660 static thread_lock_stack_t snapshots[MAX_THREADS];
661 static thread_id_t ids[MAX_THREADS];
662 static atomic_flag sampling = ATOMIC_FLAG_INIT;
663 if (atomic_flag_test_and_set(&sampling))
664 return;
665 uint64_t expected = 0;
666 if (!atomic_compare_exchange_strong(&g_registry_guard.impl, &expected, 1)) {
667 atomic_flag_clear(&sampling);
668 return;
669 }
670 int thread_count = atomic_load_int_impl(&g_thread_registry_count);
671 bool complete = true;
672 for (int i = 0; i < thread_count; ++i) {
673 thread_lock_stack_t *src = g_thread_registry[i].stack;
674 ids[i] = g_thread_registry[i].thread_id;
675 snapshots[i].depth = 0;
676 if (!src)
677 continue;
678 expected = 0;
679 if (!atomic_compare_exchange_strong(&src->guard.impl, &expected, 1)) {
680 complete = false;
681 break;
682 }
683 snapshots[i].depth = src->depth;
684 memcpy(snapshots[i].stack, src->stack,
685 (size_t)src->depth * sizeof(mutex_stack_entry_t));
686 atomic_store(&src->guard.impl, 0);
687 }
688 atomic_store(&g_registry_guard.impl, 0);
689 if (!complete) {
690 atomic_flag_clear(&sampling);
691 return;
692 }
693
694 // Check each thread for deadlock conditions
695 for (int i = 0; i < thread_count; i++) {
696 thread_lock_stack_t *stack_a = &snapshots[i];
697 uintptr_t waiting_for = thread_waiting_for_mutex(stack_a);
698
699 if (waiting_for == 0)
700 continue; // Thread not waiting
701
702 // Same-thread deadlock: thread trying to acquire a mutex it already holds
703 if (thread_holds_mutex(stack_a, waiting_for)) {
704 log_error(
705 "%s",
708 "╔═══════════════════════════════════════════════════════════╗"));
709 log_error(
710 "%s",
713 "║ ⚠️ DEADLOCK DETECTED: Same-thread Recursive Lock ⚠️ ║"));
714 log_error(
715 "%s",
718 "╚═══════════════════════════════════════════════════════════╝"));
719 log_error(" Thread Address: 0x%lx", (unsigned long)ids[i]);
720 log_error(" Mutex: 0x%lx", waiting_for);
721 log_error(" Issue: Thread attempts recursive lock on "
722 "non-recursive mutex");
723 continue;
724 }
725
726 // Multi-thread circular wait: use DFS to detect cycles
727 int cycle_path[MAX_CYCLE_LEN];
728 int cycle_len = 0;
729 int cycle_start =
730 detect_cycle_dfs(snapshots, thread_count, i, cycle_path, &cycle_len);
731
732 if (cycle_start >= 0 && cycle_len > 1) {
733 // Collect mutexes involved in this deadlock
734 uintptr_t cycle_mutexes[MAX_CYCLE_MUTEXES];
735 int mutex_count = 0;
736 for (int k = 0; k < cycle_len && mutex_count < MAX_CYCLE_MUTEXES; k++) {
737 int thread_idx = cycle_path[k];
738 thread_lock_stack_t *stack = &snapshots[thread_idx];
739 uintptr_t waiting_for = thread_waiting_for_mutex(stack);
740 if (waiting_for != 0) {
741 cycle_mutexes[mutex_count++] = waiting_for;
742 }
743 }
744
745 // Check if mutexes are different from last deadlock
746 bool is_new_deadlock =
747 deadlock_mutexes_changed(cycle_mutexes, mutex_count);
748 if (is_new_deadlock) {
749 update_deadlock_state(cycle_mutexes, mutex_count);
750 }
751
752 // Cycle detected! Build complete message in one string
753 char cycle_msg[DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE];
754 int msg_len = 0;
755
756 // Leading newline and header box
757 msg_len +=
758 snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len, "\n%s\n",
760 "╔═════════════════════════════════╗"));
761 msg_len +=
762 snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len, "%s\n",
764 "║ DEADLOCK: Circular Wait Cycle ║"));
765 msg_len +=
766 snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len, "%s\n",
768 "╚═════════════════════════════════╝"));
769
770 // Print each thread in the cycle
771 for (int k = 0; k < cycle_len; k++) {
772 int thread_idx = cycle_path[k];
773 int next_thread_idx = cycle_path[(k + 1) % cycle_len];
774
775 thread_lock_stack_t *current_stack = &snapshots[thread_idx];
776 uintptr_t current_waiting = thread_waiting_for_mutex(current_stack);
777
778 char thread_name[DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE],
781 NAMED_GET_BY_PTR((uintptr_t)ids[thread_idx], thread_name,
782 sizeof(thread_name));
783 NAMED_GET_BY_PTR((uintptr_t)current_waiting, mutex_name,
784 sizeof(mutex_name));
785 NAMED_GET_BY_PTR((uintptr_t)ids[next_thread_idx], held_by_name,
786 sizeof(held_by_name));
787
788 msg_len += snprintf(cycle_msg + msg_len, sizeof(cycle_msg) - msg_len,
789 " T%d: %s waits for %s (held by %s)%s", k + 1,
790 thread_name, mutex_name, held_by_name,
791 k < cycle_len - 1 ? "\n" : "");
792 }
793
794 // Log repeated deadlock detections (skip first call, throttle subsequent
795 // ones)
796 if (!is_new_deadlock) {
797 log_error_every(1000000, "%s", cycle_msg); // 1000000 µs = 1 second
798 }
799 }
800 }
801
802 atomic_flag_clear(&sampling);
803}
804
805// ============================================================================
806// Condition Variable Deadlock Detection (Debug builds only)
807// ============================================================================
808
809#ifndef NDEBUG
810
811#define COND_DEADLOCK_THRESHOLD_NS (5ULL * 1000000000ULL) // 5 seconds
812static _Atomic uint64_t g_next_cond_check_ns;
813
832
833static void copy_cond_deadlock_state(uintptr_t key, void *data) {
834 const cond_t *cond = (const cond_t *)key;
835 cond_deadlock_snapshot_t *snapshot = data;
836 snapshot->waiting_count = atomic_load(&cond->waiting_count);
837 snapshot->last_wait_time_ns = cond->last_wait_time_ns;
838 snapshot->last_signal_time_ns = cond->last_signal_time_ns;
839 snapshot->last_waiting_key = cond->last_waiting_key;
840 snapshot->last_wait_file = cond->last_wait_file;
841 snapshot->last_wait_line = cond->last_wait_line;
842 snapshot->last_wait_func = cond->last_wait_func;
843 snapshot->last_wait_mutex = cond->last_wait_mutex;
844}
845
856static void cond_deadlock_check_snapshot(const cond_deadlock_snapshot_t *cond,
857 const char *name) {
858 if (cond->waiting_count == 0) {
859 return; // No threads waiting, nothing to check
860 }
861
862 // Skip deadlock checks for thread pool work queues - it's normal for worker
863 // threads to wait idly when there's no work to process. Older registrations
864 // used task_available; current pools register work_available.
865 if (name && (strstr(name, "task_available") != NULL ||
866 strstr(name, "work_available") != NULL)) {
867 return;
868 }
869
870 uint64_t now = time_get_ns();
871 uint64_t stuck_ns = now - cond->last_wait_time_ns;
872 bool no_signal_since_wait =
873 (cond->last_signal_time_ns == 0 ||
875
876 if (stuck_ns < COND_DEADLOCK_THRESHOLD_NS || !no_signal_since_wait) {
877 return; // Not stuck yet or was signaled recently
878 }
879
880 // Condition variable appears to be stuck - log detailed diagnostic info
881 char stuck_str[DEBUG_MUTEX_STUCK_BUFFER_SIZE];
882 time_pretty(stuck_ns, -1, stuck_str, sizeof(stuck_str));
883
884 char cond_buf[DEBUG_MUTEX_COND_BUFFER_SIZE] = {0};
885 int cond_written =
886 safe_snprintf(cond_buf, sizeof(cond_buf),
887 "Stuck cond '%s': %lu thread(s) waiting %s with no signal "
888 "(most recent waiter: 0x%lx)\n",
889 name, cond->waiting_count, stuck_str,
890 (unsigned long)cond->last_waiting_key);
891
892 cond_written +=
893 safe_snprintf(cond_buf + cond_written, sizeof(cond_buf) - cond_written,
894 " wait entered at %s:%d %s()\n",
896 ASCIICHAT_OWNED_SOURCE_DIRS),
897 cond->last_wait_line, cond->last_wait_func);
898
899 if (cond_written >= 0 && cond->last_wait_mutex) {
900 safe_snprintf(
901 cond_buf + cond_written, sizeof(cond_buf) - cond_written,
902 " associated mutex: %p (cannot safely inspect without lock ownership)",
903 (void *)cond->last_wait_mutex);
904 }
905
906 log_warn_every(500 * NS_PER_MS_INT, "%s", cond_buf);
907}
908
909// Forward declare function from sync.c to check cleanup status
911
918
931
932static void copy_cond_deadlock_entry(uintptr_t key, uint64_t generation,
933 const char *name, const char *type,
934 const char *file, int line, void *data) {
935 (void)generation;
936 (void)file;
937 (void)line;
938 if (!type || strcmp(type, "cond") != 0)
939 return;
940 cond_deadlock_batch_t *batch = data;
941 cond_deadlock_entry_t *entry = &batch->entries[batch->count++];
942 copy_cond_deadlock_state(key, &entry->state);
943 safe_snprintf(entry->name, sizeof(entry->name), "%s", name ? name : "?");
944}
945
965 return;
966 }
967 uint64_t now = time_get_ns();
968 if (now < atomic_load(&g_next_cond_check_ns))
969 return;
970 bool completed = false;
971 size_t required = 0;
972 cond_deadlock_batch_t batch = {0};
973 if (named_registry_try_snapshot(0, &required, &completed,
974 copy_cond_deadlock_entry,
975 &batch) != ASCIICHAT_OK ||
976 !required || required > SIZE_MAX / sizeof(*batch.entries))
977 return;
978 // Registry metadata must not re-enter allocation tracking. Object state and
979 // names are copied while pinned, and diagnostics run after releasing the
980 // lock.
981 batch.entries = UNTRACKED_MALLOC(required * sizeof(*batch.entries),
983 if (!batch.entries)
984 return;
985 size_t capacity = required;
986 if (named_registry_try_snapshot(capacity, &required, &completed,
987 copy_cond_deadlock_entry,
988 &batch) == ASCIICHAT_OK &&
989 completed) {
991 for (size_t i = 0; i < batch.count; ++i) {
992 const cond_deadlock_snapshot_t *state = &batch.entries[i].state;
993 const char *name = batch.entries[i].name;
994 cond_deadlock_check_snapshot(state, name);
995 if (state->waiting_count && !strstr(name, "task_available") &&
996 !strstr(name, "work_available")) {
998 // A recent signal already rules out this wait. Repeated warnings for
999 // an actually stuck condition retain their existing 500 ms cadence.
1000 if (state->last_signal_time_ns < state->last_wait_time_ns ||
1001 !state->last_signal_time_ns) {
1002 if (due <= now)
1003 due = now + 500 * NS_PER_MS_INT;
1004 if (due < next)
1005 next = due;
1006 }
1007 }
1008 }
1009 atomic_store(&g_next_cond_check_ns, next);
1010 }
1011 UNTRACKED_FREE(batch.entries);
1012}
1013
1014#endif // NDEBUG
1015
1016// ============================================================================
1017// Initialization
1018// ============================================================================
1019
1021#ifndef NDEBUG
1022 atomic_store(&g_next_cond_check_ns, 0);
1023#endif
1024 // No initialization needed - registry uses lock-free atomic operations
1025 return 0;
1026}
1027
1029 // Explicitly free the current thread's TLS stack
1030 // This is used to prevent leaks when TLS destructors might not run reliably
1031 // (e.g., debug threads exiting before mutex_stack_cleanup() deletes the TLS
1032 // key)
1033
1034 if (!atomic_load_bool(&g_tls_initialized)) {
1035 return; // TLS not initialized, nothing to clean up
1036 }
1037
1038 thread_lock_stack_t *stack =
1039 (thread_lock_stack_t *)platform_tls_get(g_tls_mutex_stack);
1040 if (!stack) {
1041 return; // No stack allocated for this thread
1042 }
1043
1044 // Clear from TLS
1045 platform_tls_set(g_tls_mutex_stack, NULL);
1046
1047 // Update registry if this thread is registered
1048 thread_id_t current_thread = thread_self();
1049 registry_lock();
1050 int count = atomic_load_int(&g_thread_registry_count);
1051 for (int i = 0; i < count; i++) {
1052 if (thread_equal(g_thread_registry[i].thread_id, current_thread) &&
1053 g_thread_registry[i].stack == stack) {
1054 g_thread_registry[i].stack = NULL; // Mark as freed in registry
1055 break;
1056 }
1057 }
1058
1059 // Free the stack (raw free to match raw malloc above)
1060 free(stack);
1061 registry_unlock();
1062}
1063
1065 // Signal shutdown to prevent new allocations from threads still running
1066 atomic_store_bool(&g_shutting_down, true);
1067
1068 // Call only after tracked workers stop. Windows FLS key deletion invokes
1069 // destructors; POSIX key deletion does not. Delete first so those callbacks
1070 // retire their entries before we free any remaining allocations.
1071 if (atomic_load_bool(&g_tls_initialized)) {
1072 platform_tls_key_delete(g_tls_mutex_stack);
1073 atomic_store_bool(&g_tls_initialized, false);
1074 }
1075 registry_lock();
1076 int count = atomic_load_int(&g_thread_registry_count);
1077 for (int i = 0; i < count; ++i) {
1078 free(g_thread_registry[i].stack);
1079 g_thread_registry[i].stack = NULL;
1080 }
1081 registry_unlock();
1082
1083 // Clear registry on cleanup using atomic operations
1084 atomic_store_int(&g_thread_registry_count, 0);
1085}
1086
1087// ============================================================================
1088// Release Build Stubs (NDEBUG)
1089// ============================================================================
1090// These no-op implementations replace the debug implementations in release
1091// builds (when debug/mutex.c is not compiled into the library)
1092
1093#ifdef NDEBUG
1094
1095void mutex_stack_push_locked(uintptr_t mutex_key, const char *mutex_name) {
1096 (void)mutex_key;
1097 (void)mutex_name;
1098}
1099
1100void mutex_stack_push_pending(uintptr_t mutex_key, const char *mutex_name) {
1101 (void)mutex_key;
1102 (void)mutex_name;
1103 // No-op in release builds
1104}
1105
1106void mutex_stack_mark_locked(uintptr_t mutex_key) {
1107 (void)mutex_key;
1108 // No-op in release builds
1109}
1110
1111void mutex_stack_pop(uintptr_t mutex_key) {
1112 (void)mutex_key;
1113 // No-op in release builds
1114}
1115
1116#endif
DLL export/import macros for cross-platform symbol visibility.
#define HAS_ERRNO(context)
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
int atomic_load_int_impl(const atomic_t *a)
void atomic_store_int(atomic_t *a, int value)
Atomically store an int value.
bool atomic_cas_int(atomic_t *a, int *expected, int new_value)
Atomically compare-and-swap an int.
int atomic_load_int(atomic_t *a)
Atomically load an int value.
@ LOG_COLOR_ERROR
Definition color.h:11
Named object registry for debugging — log identifiable resource names.
#define UNTRACKED_FREE(ptr)
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
#define UNTRACKED_MALLOC(size, cast)
void debug_sync_check_cond_deadlocks(void)
The useful part of cond deadlock batch is in entries, count: together they describe what is pending,...
Definition mutex.c:963
#define NAMED_GET_BY_PTR(key, buffer, size)
Get name of a pointer/key or format as address fallback.
asciichat_error_t named_registry_try_snapshot(size_t capacity, size_t *required, bool *completed, named_snapshot_fn copy, void *data)
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
int time_pretty(uint64_t nanoseconds, int decimals, char *buffer, size_t buffer_size)
Format nanoseconds as a compact duration with configurable sub-minute precision.
Definition time.c:406
#define NS_PER_MS_INT
Definition time.h:172
const char * colored_string(log_color_t color, const char *text)
Build a colored string for terminal output.
const char * extract_project_relative_path(const char *file, const char *const *owned_dirs)
Extract a path relative to the source root embedded by CMake.
Definition path.c:137
Statistics worker for error totals and memory reports. Signal handlers may only request a report.
📝 Logging API with multiple log levels and terminal output control
#define log_error_every(interval_us, fmt,...)
Rate-limited ERROR logging.
Definition log/log.h:728
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
#define DEBUG_MUTEX_COND_BUFFER_SIZE
Definition mutex.c:8
bool debug_sync_is_cleanup_in_progress(void)
#define MAX_CYCLE_MUTEXES
Definition mutex.c:98
void mutex_stack_cleanup_current_thread(void)
Cleanup TLS stack for current thread Explicitly frees the thread-local mutex stack....
Definition mutex.c:1028
#define DEBUG_MUTEX_NAME_BUFFER_SIZE
Definition mutex.c:9
#define DEBUG_MUTEX_THREAD_NAME_BUFFER_SIZE
Definition mutex.c:4
int mutex_stack_get_all_threads(mutex_stack_entry_t ***out_stacks, int **out_stack_counts, int *out_thread_count)
Get all threads' lock stacks for deadlock analysis.
Definition mutex.c:351
void mutex_stack_free_all_threads(mutex_stack_entry_t **stacks, int *stack_counts, int thread_count)
Free memory allocated by mutex_stack_get_all_threads().
Definition mutex.c:407
#define COND_DEADLOCK_THRESHOLD_NS
Definition mutex.c:811
#define MUTEX_STACK_MAX_DEPTH
Definition mutex.c:40
void mutex_stack_cleanup(void)
Cleanup mutex stack system.
Definition mutex.c:1064
int mutex_stack_get_current(mutex_stack_entry_t *out_entries, int max_entries)
Get the current thread's lock stack.
Definition mutex.c:333
void mutex_stack_pop(uintptr_t mutex_key)
Pop the top mutex from the current thread's lock stack (unlock).
Definition mutex.c:303
#define DEBUG_MUTEX_MUTEX_NAME_BUFFER_SIZE
Definition mutex.c:5
void mutex_stack_push_locked(uintptr_t mutex_key, const char *mutex_name)
Definition mutex.c:276
bool mutex_stack_try_snapshot(mutex_wait_snapshot_t *waits, size_t capacity, size_t *count, bool *limited)
Definition mutex.c:529
#define MAX_CYCLE_LEN
DFS-based cycle detection in the waits-for graph Returns cycle start index if found,...
Definition mutex.c:477
#define MAX_THREADS
Definition mutex.c:62
#define DEBUG_MUTEX_HELD_BY_NAME_BUFFER_SIZE
Definition mutex.c:6
#define DEBUG_MUTEX_CYCLE_MSG_BUFFER_SIZE
Definition mutex.c:3
void mutex_stack_push_pending(uintptr_t mutex_key, const char *mutex_name)
Push a mutex onto the current thread's lock stack (PENDING state).
Definition mutex.c:272
void mutex_stack_mark_locked(uintptr_t mutex_key)
Mark the top of the current thread's lock stack as LOCKED (transitions PENDING -> LOCKED).
Definition mutex.c:280
int mutex_stack_init(void)
Initialize mutex stack system.
Definition mutex.c:1020
void mutex_stack_detect_deadlocks(void)
Detect circular wait deadlocks using DFS-based cycle detection.
Definition mutex.c:656
#define DEBUG_MUTEX_STUCK_BUFFER_SIZE
Definition mutex.c:7
Per-thread mutex lock stack for deadlock detection.
mutex_stack_state_t
mutex stack entry is intentionally a small, concrete record. Fields such as mutex_key,...
Definition mutex.h:36
@ MUTEX_STACK_STATE_LOCKED
Definition mutex.h:38
@ MUTEX_STACK_STATE_PENDING
Definition mutex.h:37
bool ascii_otel_enabled(void)
Definition otel.c:171
gotel_context_t ascii_otel_context(void)
Definition otel.c:870
const char * ascii_otel_current_operation(void)
Definition otel.c:165
📂 Path Manipulation Utilities
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
When code needs to work with cond deadlock entry, it keeps state here instead of scattering it across...
Definition mutex.c:925
cond_deadlock_entry_t * entries
Definition mutex.c:926
Definition mutex.c:912
cond_deadlock_snapshot_t state
Definition mutex.c:913
char name[256]
Definition mutex.c:914
deadlock state is intentionally a small, concrete record. Fields such as count give callers the ident...
Definition mutex.c:820
uint64_t last_signal_time_ns
Definition mutex.c:823
const mutex_t * last_wait_mutex
Definition mutex.c:828
uint64_t last_wait_time_ns
Definition mutex.c:822
const char * last_wait_func
Definition mutex.c:827
const char * last_wait_file
Definition mutex.c:825
uintptr_t last_waiting_key
Definition mutex.c:824
uintptr_t mutexes[16]
Definition mutex.c:100
Definition mutex.h:44
const char * mutex_name
Definition mutex.h:46
mutex_stack_state_t state
Definition mutex.h:47
uint64_t timestamp_ns
Definition mutex.h:48
uintptr_t mutex_key
Definition mutex.h:45
For mutex wait snapshot, this is the live record that ties mutex_key, thread_key, since_ns,...
Definition mutex.h:122
uint64_t since_ns
Definition mutex.h:125
uint8_t trace_id[16]
Definition mutex.h:130
uintptr_t thread_key
Definition mutex.h:124
uint8_t span_id[8]
Definition mutex.h:131
uint64_t span_start_unix_ns
Definition mutex.h:133
char span_name[224]
Definition mutex.h:127
uintptr_t mutex_key
Definition mutex.h:123
uint8_t parent_span_id[8]
Definition mutex.h:132
char error_message[1024]
Definition mutex.h:129
mutex_stack_entry_t stack[64]
Definition mutex.c:43
mutex_wait_snapshot_t telemetry
Definition mutex.c:46
atomic_t guard
Definition mutex.c:45
thread lock stack keeps the values that move through the subsystem: depth, guard, telemetry....
Definition mutex.c:69
thread_lock_stack_t * stack
Definition mutex.c:71
thread_id_t thread_id
Definition mutex.c:70
⏱️ High-precision timing utilities using sokol_time.h and uthash