ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
asciichat_errno.c
Go to the documentation of this file.
1
5
6/* Storage capacities in elements; text buffers include the terminating NUL. */
7#define ASCIICHAT_ERRNO_SUFFIX_BUFFER_SIZE 256
8
9/* Existing buffer budgets in bytes, including NUL for text storage. */
10#define ERROR_RENDER_SLOT_COUNT 8
11
12#include <ascii-chat/otel.h>
14#include <ascii-chat/log/io.h>
16#include <libplatform/atomic.h>
18#include <libplatform/backtrace.h>
19#include <libplatform/thread.h>
20#include <libplatform/errno.h>
23#include <ascii-chat/source_root.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <string.h>
27#include <inttypes.h>
28
29#define ERRNO_BUCKETS 257
30#define NO_FRAME (-1)
31#define RESERVED_FRAMES (2 * ASCIICHAT_ERRNO_MAX_THREADS)
32_Static_assert(ASCIICHAT_ERRNO_MAX_FRAMES > RESERVED_FRAMES, "Reserve root/latest slots for every thread");
33
44
58
59// The error path must work before allocators, logging, and instrumented locks.
60// A bounded pool avoids recursive allocation and is reclaimed/zeroed on pop.
61// The guard uses the platform atomic implementation without diagnostic hooks.
62// No allocation, logging, callback, or symbolization occurs while it is held.
63static atomic_t g_guard = {0};
64static error_thread_t *g_buckets[ERRNO_BUCKETS];
68static size_t g_history_count;
69static size_t g_history_next;
70static asciichat_error_stats_t g_stats;
71static uint64_t g_next_id;
72static uint64_t g_generation;
73static int g_free_head;
74static bool g_initialized;
75static bool g_shutdown;
76static asciichat_error_t g_exit_code;
77#ifndef EMSCRIPTEN_BUILD
78static tls_key_t g_tls_key;
79static bool g_tls_ready;
80#endif
81static PLATFORM_THREAD_LOCAL bool g_recording;
82static PLATFORM_THREAD_LOCAL bool g_suppress_logging;
83static void registry_lock(void);
84static void registry_unlock(void);
85static PLATFORM_THREAD_LOCAL bool g_suppress_notifications;
87static size_t g_notification_first, g_notification_count;
88static uint64_t g_notification_dropped;
89// Dismissed errors remain in their owning stacks but no longer affect the title.
90static uint64_t g_title_dismissed_through;
91static bool g_notifications_enabled;
92static bool g_notifications_paused;
93static atomic_t g_notifications_pending = {0};
94
96 registry_lock();
97 if (!enabled || (!g_notifications_enabled && !g_notifications_paused)) {
98 g_notification_first = g_notification_count = 0;
99 g_notification_dropped = 0;
100 atomic_store_bool_impl(&g_notifications_pending, false);
101 }
102 g_notifications_enabled = enabled;
103 g_notifications_paused = false;
104 registry_unlock();
105}
106
108 registry_lock();
109 if (g_notifications_enabled) {
110 g_notifications_enabled = false;
111 g_notifications_paused = true;
112 }
113 registry_unlock();
114}
115
117 return atomic_load_bool_impl(&g_notifications_pending);
118}
119
120bool errno_notifications_suppress(bool suppress) {
121 bool previous = g_suppress_notifications;
122 g_suppress_notifications = suppress;
123 return previous;
124}
125
127 registry_lock();
128 size_t count = MIN(capacity, g_notification_count);
129 for (size_t i = 0; out && i < count; ++i)
130 out[i] = g_notifications[(g_notification_first + i) % ASCIICHAT_ERRNO_HISTORY_SIZE];
131 if (dropped)
132 *dropped = g_notification_dropped;
133 registry_unlock();
134 return count;
135}
136
138 registry_lock();
139 if (through_id > g_title_dismissed_through)
140 g_title_dismissed_through = through_id;
141 while (g_notification_count && g_notifications[g_notification_first].error_id <= through_id) {
142 memset(&g_notifications[g_notification_first], 0, sizeof(g_notifications[0]));
143 g_notification_first = (g_notification_first + 1) % ASCIICHAT_ERRNO_HISTORY_SIZE;
144 --g_notification_count;
145 }
146 g_notification_dropped = 0;
147 atomic_store_bool_impl(&g_notifications_pending, g_notification_count != 0);
148 registry_unlock();
149}
150
151static void notify_locked(const asciichat_error_context_t *context) {
152 if (!g_notifications_enabled || g_suppress_notifications)
153 return;
154 if (g_notification_count == ASCIICHAT_ERRNO_HISTORY_SIZE) {
155 g_notification_first = (g_notification_first + 1) % ASCIICHAT_ERRNO_HISTORY_SIZE;
156 --g_notification_count;
157 ++g_notification_dropped;
158 }
159 g_notifications[(g_notification_first + g_notification_count++) % ASCIICHAT_ERRNO_HISTORY_SIZE] = *context;
160 atomic_store_bool_impl(&g_notifications_pending, true);
161}
162
163const char *asciichat_error_format(const char *message, asciichat_error_t code) {
165 static PLATFORM_THREAD_LOCAL unsigned next;
166 char *output = buffers[next++ % 8];
168 snprintf(suffix, sizeof(suffix), "%s (code=%d)", asciichat_error_string(code), code);
169 if (!message || !*message || !strcmp(message, asciichat_error_string(code))) {
170 snprintf(output, sizeof(buffers[0]), "%s", suffix);
171 } else {
172 size_t length = strlen(message);
173 size_t suffix_length = strlen(suffix);
174 if (length >= suffix_length && !strcmp(message + length - suffix_length, suffix))
175 snprintf(output, sizeof(buffers[0]), "%s", message);
176 else {
177 size_t limit = length < ASCIICHAT_ERRNO_MESSAGE_MAX ? length : ASCIICHAT_ERRNO_MESSAGE_MAX - 1;
178 // Do not cut a UTF-8 character in half when shortening the message.
179 while (limit && ((unsigned char)message[limit] & 0xc0) == 0x80)
180 --limit;
181 snprintf(output, sizeof(buffers[0]), "%.*s: %s", (int)limit, message, suffix);
182 }
183 }
184 return output;
185}
186
187static void registry_lock(void) {
188 int expected = 0;
189 while (!atomic_cas_int_impl(&g_guard, &expected, 1))
190 expected = 0;
191}
192static void registry_unlock(void) {
193 atomic_store_int_impl(&g_guard, 0);
194}
195
196static size_t bucket_for(uint64_t id) {
197 return (size_t)((id ^ (id >> 32)) % ERRNO_BUCKETS);
198}
199
200static error_thread_t *find_thread(uint64_t id) {
201 for (error_thread_t *thread = g_buckets[bucket_for(id)]; thread; thread = thread->next)
202 if (thread->id == id)
203 return thread;
204 return NULL;
205}
206
208 asciichat_error_context_t newest = {0};
209 registry_lock();
210 size_t count = 0;
211 for (size_t i = 0; i < ASCIICHAT_ERRNO_MAX_THREADS; ++i) {
212 error_thread_t *thread = &g_threads[i];
213 for (int frame = thread->depth ? thread->top : NO_FRAME; frame != NO_FRAME; frame = g_frames[frame].next) {
214 const asciichat_error_context_t *entry = &g_frames[frame].context;
215 if (entry->error_id <= g_title_dismissed_through)
216 continue;
217 ++count;
218 if (entry->error_id > newest.error_id)
219 newest = *entry;
220 }
221 }
222 for (size_t i = 0; i < g_notification_count; ++i) {
223 const asciichat_error_context_t *entry = &g_notifications[(g_notification_first + i) % ASCIICHAT_ERRNO_HISTORY_SIZE];
224 error_thread_t *thread = find_thread(entry->thread_id);
225 bool pending = false;
226 if (thread && thread->generation == entry->generation) {
227 for (int frame = thread->top; frame != NO_FRAME; frame = g_frames[frame].next) {
228 if (g_frames[frame].context.error_id == entry->error_id) {
229 pending = true;
230 break;
231 }
232 }
233 }
234 if (!pending)
235 ++count;
236 if (entry->error_id > newest.error_id)
237 newest = *entry;
238 }
239 if (latest)
240 *latest = newest;
241 registry_unlock();
242 return count;
243}
244
245static void initialize_locked(void) {
246 if (g_initialized)
247 return;
248 for (int i = RESERVED_FRAMES; i < ASCIICHAT_ERRNO_MAX_FRAMES; ++i)
249 g_frames[i].next = i + 1;
251 g_free_head = RESERVED_FRAMES;
252 g_initialized = true;
253}
254
255static void remember_locked(const asciichat_error_context_t *context, asciichat_errno_outcome_t outcome, uint64_t now) {
256 asciichat_errno_history_t *event = &g_history[g_history_next];
257 event->context = *context;
258 event->outcome = outcome;
259 event->resolved_ns = now;
260 g_history_next = (g_history_next + 1) % ASCIICHAT_ERRNO_HISTORY_SIZE;
261 if (g_history_count < ASCIICHAT_ERRNO_HISTORY_SIZE)
262 ++g_history_count;
263 else
264 ++g_stats.overwritten_history;
265}
266
267static void release_frame_locked(int index, asciichat_errno_outcome_t outcome, uint64_t now) {
268 remember_locked(&g_frames[index].context, outcome, now);
269 memset(&g_frames[index], 0, sizeof(g_frames[index]));
270 if (index >= RESERVED_FRAMES) {
271 g_frames[index].next = g_free_head;
272 g_free_head = index;
273 }
274 --g_stats.pending_errors;
275}
276
277static void pop_locked(error_thread_t *thread, asciichat_errno_outcome_t outcome, uint64_t now) {
278 int index = thread->top;
279 if (index == NO_FRAME)
280 return;
281 thread->top = g_frames[index].next;
282 --thread->depth;
283 release_frame_locked(index, outcome, now);
284}
285
286static void unregister_locked(error_thread_t *thread, uint64_t now) {
287 while (thread->depth)
288 pop_locked(thread, ASCIICHAT_ERRNO_THREAD_EXIT, now);
289 error_thread_t **link = &g_buckets[bucket_for(thread->id)];
290 while (*link && *link != thread)
291 link = &(*link)->next;
292 if (*link == thread)
293 *link = thread->next;
294 memset(thread, 0, sizeof(*thread));
295 --g_stats.registered_threads;
296}
297
298#ifndef EMSCRIPTEN_BUILD
299static void error_thread_destructor(void *value) {
300 registry_lock();
301 uint64_t now = time_get_ns();
302 error_thread_t *thread = value;
303 if (thread && thread->generation && !g_shutdown)
304 unregister_locked(thread, now);
305 registry_unlock();
306}
307#endif
308
309static error_thread_t *register_current_locked(uint64_t id) {
310 error_thread_t *thread = find_thread(id);
311 if (thread)
312 return thread;
313 if (g_shutdown)
314 return NULL;
315 initialize_locked();
316#ifndef EMSCRIPTEN_BUILD
317 // Platform TLS creation/setters do not log or allocate through SAFE_MALLOC.
318 if (!g_tls_ready) {
319 if (platform_tls_key_create(&g_tls_key, error_thread_destructor) != 0)
320 return NULL;
321 g_tls_ready = true;
322 }
323#endif
324 for (size_t i = 0; i < ASCIICHAT_ERRNO_MAX_THREADS; ++i) {
325 if (g_threads[i].generation)
326 continue;
327 thread = &g_threads[i];
328#ifndef EMSCRIPTEN_BUILD
329 if (platform_tls_set(g_tls_key, thread) != 0)
330 return NULL;
331#endif
332 thread->id = id;
333 thread->generation = ++g_generation;
334 thread->top = NO_FRAME;
335 size_t bucket = bucket_for(id);
336 thread->next = g_buckets[bucket];
337 g_buckets[bucket] = thread;
338 ++g_stats.registered_threads;
339 return thread;
340 }
341 return NULL;
342}
343
344static void record_stats_locked(asciichat_error_t code, uint64_t timestamp) {
345 if (code == ASCIICHAT_OK)
346 return;
347 if ((unsigned)code < ARRAY_SIZE(g_stats.error_counts))
348 ++g_stats.error_counts[code];
349 ++g_stats.total_errors;
350 g_stats.last_error_time = timestamp;
351 g_stats.last_error_code = code;
352}
353
354static void push_context(asciichat_error_context_t *context) {
355 registry_lock();
356 if (g_shutdown) {
357 registry_unlock();
358 return;
359 }
360 bool already_notified = false;
361 if (context->cause_id) {
362 for (size_t i = 0; i < g_notification_count; ++i) {
363 const asciichat_error_context_t *entry = &g_notifications[(g_notification_first + i) % ASCIICHAT_ERRNO_HISTORY_SIZE];
364 if (entry->error_id == context->cause_id || entry->cause_id == context->cause_id) {
365 already_notified = true;
366 break;
367 }
368 }
369 }
370 record_stats_locked(context->code, context->timestamp);
371 context->error_id = ++g_next_id;
372 error_thread_t *thread = register_current_locked(context->thread_id);
373 if (!thread) {
374 ++g_stats.dropped_errors;
375 remember_locked(context, ASCIICHAT_ERRNO_OVERFLOW, context->created_ns);
376 if (!already_notified)
377 notify_locked(context);
378 registry_unlock();
379 return;
380 }
381 context->generation = thread->generation;
382 if (!context->cause_id && thread->top != NO_FRAME && g_frames[thread->top].context.error_id > thread->cause_after_id)
383 context->cause_id = g_frames[thread->top].context.error_id;
384
385 int reserved = (int)(thread - g_threads) * 2;
386 bool has_reserved = !g_frames[reserved].used || !g_frames[reserved + 1].used;
387 // Preserve the oldest/root frame and newest context by evicting the second
388 // oldest frame when this thread reaches its depth limit or the pool fills.
389 if ((thread->depth == ASCIICHAT_ERRNO_MAX_DEPTH || (!has_reserved && g_free_head == NO_FRAME)) && thread->depth > 1) {
390 int previous = NO_FRAME;
391 int victim = thread->top;
392 while (g_frames[g_frames[victim].next].next != NO_FRAME) {
393 previous = victim;
394 victim = g_frames[victim].next;
395 }
396 if (previous == NO_FRAME)
397 thread->top = g_frames[victim].next;
398 else
399 g_frames[previous].next = g_frames[victim].next;
400 --thread->depth;
401 ++g_stats.dropped_errors;
402 release_frame_locked(victim, ASCIICHAT_ERRNO_OVERFLOW, context->created_ns);
403 }
404 int index;
405 if (!g_frames[reserved].used)
406 index = reserved;
407 else if (!g_frames[reserved + 1].used)
408 index = reserved + 1;
409 else {
410 index = g_free_head;
411 g_free_head = g_frames[index].next;
412 }
413 g_frames[index].used = true;
414 g_frames[index].context = *context;
415 g_frames[index].next = thread->top;
416 thread->top = index;
417 ++thread->depth;
418 ++g_stats.pending_errors;
419 if (!already_notified)
420 notify_locked(context);
421 registry_unlock();
422}
423
424static asciichat_error_t set_formatted(asciichat_error_t code, const char *file, int line, const char *function, int sys_errno, bool system, int wsa, bool windows_socket, const char *format,
425 va_list args) {
426 if (code == ASCIICHAT_OK || g_recording)
427 return code;
428 registry_lock();
429 bool shutdown = g_shutdown;
430 registry_unlock();
431 if (shutdown)
432 return code;
433 g_recording = true;
434 asciichat_error_context_t context = {0};
435 context.code = code;
436 context.file = file;
437 context.line = line;
438 context.function = function;
439 context.system_errno = sys_errno;
440 context.has_system_error = system;
441 context.wsa_error = wsa;
442 context.has_wsa_error = windows_socket;
443 context.thread_id = thread_current_id();
444 context.timestamp = time_ns_to_us(time_get_realtime_ns());
445 context.created_ns = time_get_ns();
446 int length = vsnprintf(context.context_message, sizeof(context.context_message), format ? format : "", args);
447 context.message_truncated = length < 0 || (size_t)length >= sizeof(context.context_message);
448#if !defined(NDEBUG) || defined(ENABLE_ERRNO_BACKTRACES)
450#endif
451 push_context(&context);
452#ifndef __EMSCRIPTEN__
454#endif
455 if (!g_suppress_logging) {
456 log_debug("%s%s", asciichat_error_format(context.context_message, code), context.message_truncated ? " [message truncated]" : "");
457 }
458 g_recording = false;
459 return code;
460}
461
462asciichat_error_t errno_set_with_message(asciichat_error_t code, const char *file, int line, const char *function, const char *format, ...) {
463 va_list args;
464 va_start(args, format);
465 asciichat_error_t result = set_formatted(code, file, line, function, 0, false, 0, false, format, args);
466 va_end(args);
467 return result;
468}
469
470asciichat_error_t errno_set(asciichat_error_t code, const char *file, int line, const char *function, const char *message) {
471 return errno_set_with_message(code, file, line, function, "%s", message ? message : "");
472}
473
474asciichat_error_t errno_set_with_system_error_and_message(asciichat_error_t code, const char *file, int line, const char *function, int sys_errno, const char *format, ...) {
475 va_list args;
476 va_start(args, format);
477 asciichat_error_t result = set_formatted(code, file, line, function, sys_errno, true, 0, false, format, args);
478 va_end(args);
479 return result;
480}
481
482asciichat_error_t errno_set_with_system_error(asciichat_error_t code, const char *file, int line, const char *function, int sys_errno) {
483 return errno_set_with_system_error_and_message(code, file, line, function, sys_errno, "System operation failed (%d)", sys_errno);
484}
485
486// WSA metadata must be published together with the frame, never patched later.
487static asciichat_error_t set_wsa(asciichat_error_t code, const char *file, int line, const char *function, int wsa, const char *format, ...) {
488 va_list args;
489 va_start(args, format);
490 asciichat_error_t result = set_formatted(code, file, line, function, 0, false, wsa, true, format, args);
491 va_end(args);
492 return result;
493}
494asciichat_error_t errno_set_with_wsa_error(asciichat_error_t code, const char *file, int line, const char *function, int wsa_error) {
495 return set_wsa(code, file, line, function, wsa_error, "Socket operation failed (%d)", wsa_error);
496}
497
499 registry_lock();
500 error_thread_t *thread = find_thread(id);
501 bool found = thread && thread->depth;
502 if (context) {
503 if (found)
504 *context = g_frames[thread->top].context;
505 else
506 memset(context, 0, sizeof(*context));
507 }
508 registry_unlock();
509 return found;
510}
512 return errno_has_thread_error(thread_current_id(), context);
513}
515 registry_lock();
516 error_thread_t *thread = find_thread(id);
517 asciichat_error_t code = thread && thread->depth ? g_frames[thread->top].context.code : ASCIICHAT_OK;
518 registry_unlock();
519 return code;
520}
522 return errno_get_thread_error(thread_current_id());
523}
526 return HAS_ERRNO(&context) && context.has_wsa_error;
527}
528
529static bool has_code_locked(error_thread_t *thread, uint64_t after_id, asciichat_error_t code) {
530 if (!thread || code == ASCIICHAT_OK)
531 return false;
532 for (int index = thread->top; index != NO_FRAME; index = g_frames[index].next) {
533 const asciichat_error_context_t *context = &g_frames[index].context;
534 if (context->error_id <= after_id)
535 break;
536 if (context->code == code)
537 return true;
538 }
539 return false;
540}
542 registry_lock();
543 bool found = has_code_locked(find_thread(id), 0, code);
544 registry_unlock();
545 return found;
546}
548 return errno_has_code_tid(thread_current_id(), code);
549}
551 registry_lock();
552 error_thread_t *thread = find_thread(scope.thread_id);
553 bool found = thread && thread->generation == scope.generation && has_code_locked(thread, scope.after_id, code);
554 registry_unlock();
555 return found;
556}
557
559 registry_lock();
560 error_thread_t *thread = find_thread(scope.thread_id);
561 bool found = thread && thread->generation == scope.generation && thread->top != NO_FRAME && g_frames[thread->top].context.error_id > scope.after_id;
562 if (found && out)
563 *out = g_frames[thread->top].context;
564 registry_unlock();
565 return found;
566}
568 if (!cause || cause->code == ASCIICHAT_OK)
569 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing failure snapshot");
570 if (g_recording)
571 return cause->code;
572 g_recording = true;
573 asciichat_error_context_t copy = *cause;
574 copy.cause_id = cause->error_id;
575 copy.thread_id = thread_current_id();
576 copy.timestamp = time_ns_to_us(time_get_realtime_ns());
577 copy.created_ns = time_get_ns();
578 copy.backtrace.symbols = NULL;
579 copy.backtrace.tried_symbolize = false;
580 push_context(&copy);
581 g_recording = false;
582 return copy.code;
583}
584
585static void clear_thread(uint64_t id, bool all) {
586 registry_lock();
587 uint64_t now = time_get_ns();
588 error_thread_t *thread = find_thread(id);
589 if (thread) {
590 do {
591 pop_locked(thread, ASCIICHAT_ERRNO_HANDLED, now);
592 } while (all && thread->depth);
593 }
594 registry_unlock();
595}
597 clear_thread(id, false);
598}
600 clear_thread(id, true);
601}
602void errno_clear(void) {
603 clear_thread(thread_current_id(), false);
605}
606void errno_clear_all(void) {
607 clear_thread(thread_current_id(), true);
609}
611 registry_lock();
612 uint64_t now = time_get_ns();
613 error_thread_t *thread = find_thread(id);
614 bool matches = thread && thread->generation == generation && thread->depth && g_frames[thread->top].context.error_id == error_id;
615 if (matches)
616 pop_locked(thread, ASCIICHAT_ERRNO_HANDLED, now);
617 registry_unlock();
618 return matches;
619}
621 registry_lock();
622 uint64_t now = time_get_ns();
623 error_thread_t *thread = find_thread(id);
624 int previous = NO_FRAME;
625 int index = thread ? thread->top : NO_FRAME;
626 while (index != NO_FRAME && g_frames[index].context.error_id != error_id) {
627 previous = index;
628 index = g_frames[index].next;
629 }
630 bool matches = thread && thread->generation == generation && index != NO_FRAME;
631 if (matches) {
632 if (previous == NO_FRAME)
633 thread->top = g_frames[index].next;
634 else
635 g_frames[previous].next = g_frames[index].next;
636 --thread->depth;
637 release_frame_locked(index, ASCIICHAT_ERRNO_HANDLED, now);
638 }
639 registry_unlock();
640 return matches;
641}
642static asciichat_errno_scope_t checkpoint(bool new_cause) {
643 asciichat_errno_scope_t scope = {.thread_id = thread_current_id()};
644 registry_lock();
645 error_thread_t *thread = register_current_locked(scope.thread_id);
646 scope.generation = thread ? thread->generation : 0;
647 scope.after_id = g_next_id;
648 if (thread) {
649 scope.previous_after_id = thread->cause_after_id;
650 if (new_cause)
651 thread->cause_after_id = scope.after_id;
652 }
653 registry_unlock();
654 return scope;
655}
657 return checkpoint(false);
658}
660 return checkpoint(true);
661}
663 uint64_t now = time_get_ns();
664 // Recovery runs on the offending thread. Cross-thread clearing has separate APIs.
665 if (scope.thread_id != thread_current_id())
666 return;
667 registry_lock();
668 error_thread_t *thread = find_thread(scope.thread_id);
669 if (thread && thread->generation == scope.generation) {
670 while (thread->depth && g_frames[thread->top].context.error_id > scope.after_id)
671 pop_locked(thread, outcome, now);
672 thread->cause_after_id = scope.previous_after_id;
673 }
674 registry_unlock();
675}
677 registry_lock();
678 error_thread_t *thread = find_thread(id);
679 size_t depth = thread ? thread->depth : 0;
680 asciichat_errno_snapshot_t snapshot = {.total = depth};
681 if (thread && out)
682 for (int index = thread->top; index != NO_FRAME && snapshot.copied < capacity; index = g_frames[index].next)
683 out[snapshot.copied++] = g_frames[index].context;
684 registry_unlock();
685 return snapshot;
686}
687size_t errno_threads_snapshot(uint64_t *out, size_t capacity) {
688 registry_lock();
689 size_t count = 0;
690 for (size_t i = 0; i < ASCIICHAT_ERRNO_MAX_THREADS; ++i) {
691 if (!g_threads[i].generation)
692 continue;
693 if (out && count < capacity)
694 out[count] = g_threads[i].id;
695 ++count;
696 }
697 registry_unlock();
698 return count;
699}
701 registry_lock();
702 size_t count = g_history_count;
703 if (out)
704 for (size_t i = 0; i < count && i < capacity; ++i)
705 out[i] = g_history[(g_history_next + ASCIICHAT_ERRNO_HISTORY_SIZE - 1 - i) % ASCIICHAT_ERRNO_HISTORY_SIZE];
706 registry_unlock();
707 return count;
708}
709
710void errno_suppress(bool suppress) {
711 g_suppress_logging = suppress;
712}
713void errno_destroy(void) {
714 uint64_t now = time_get_ns();
715 uint64_t id = thread_current_id();
716 registry_lock();
717#ifndef EMSCRIPTEN_BUILD
718 if (g_tls_ready)
719 platform_tls_set(g_tls_key, NULL);
720#endif
721 error_thread_t *thread = find_thread(id);
722 if (thread)
723 unregister_locked(thread, now);
724 registry_unlock();
725}
726void errno_shutdown(void) {
729 registry_lock();
730 g_shutdown = true;
731 memset(g_threads, 0, sizeof(g_threads));
732 memset(g_buckets, 0, sizeof(g_buckets));
733 memset(g_frames, 0, sizeof(g_frames));
734 memset(g_history, 0, sizeof(g_history));
735 g_history_count = g_history_next = 0;
736 g_stats.pending_errors = g_stats.registered_threads = 0;
737#ifndef EMSCRIPTEN_BUILD
738 bool delete_key = g_tls_ready;
739 tls_key_t key = g_tls_key;
740 g_tls_ready = false;
741#endif
742 registry_unlock();
743#ifndef EMSCRIPTEN_BUILD
744 if (delete_key)
745 platform_tls_key_delete(key);
746#endif
747}
748
750 registry_lock();
751 initialize_locked();
752 registry_unlock();
753}
755 uint64_t timestamp = time_ns_to_us(time_get_realtime_ns());
756 registry_lock();
757 record_stats_locked(code, timestamp);
758 registry_unlock();
759}
761 registry_lock();
762 asciichat_error_stats_t stats = g_stats;
763 registry_unlock();
764 return stats;
765}
767 registry_lock();
768 size_t pending = g_stats.pending_errors, threads = g_stats.registered_threads;
769 memset(&g_stats, 0, sizeof(g_stats));
770 g_stats.pending_errors = pending;
771 g_stats.registered_threads = threads;
772 registry_unlock();
773}
776 log_plain("Errors: total=%" PRIu64 " pending=%zu threads=%zu dropped=%" PRIu64 " history_overwritten=%" PRIu64, stats.total_errors, stats.pending_errors, stats.registered_threads,
778 for (size_t i = 1; i < ARRAY_SIZE(stats.error_counts); ++i)
779 if (stats.error_counts[i])
780 log_plain(" %s: %" PRIu64, asciichat_error_string((asciichat_error_t)i), stats.error_counts[i]);
781}
782
783static void print_error_context(const asciichat_error_context_t *context, bool include_backtrace) {
784 if (!context || context->code == ASCIICHAT_OK)
785 return;
786 bool previous = g_recording;
787 g_recording = true;
788 uint64_t now = time_get_ns();
789 log_plain(" Error #%" PRIu64 " thread=%" PRIu64 "/%" PRIu64 " code=%d cause=#%" PRIu64 " age=%.3fs", context->error_id, context->thread_id, context->generation, context->code, context->cause_id,
790 now >= context->created_ns ? (double)(now - context->created_ns) / 1e9 : 0.0);
791 log_plain(" %s%s", asciichat_error_format(context->context_message, context->code), context->message_truncated ? " [truncated]" : "");
792 if (context->file)
793 log_plain(" %s:%d in %s()", extract_project_relative_path(context->file, ASCIICHAT_OWNED_SOURCE_DIRS), context->line, context->function ? context->function : "?");
794 if (context->has_system_error)
795 log_plain(" System error: %d", context->system_errno);
796 if (context->has_wsa_error)
797 log_plain(" WSA error: %d", context->wsa_error);
798 if (context->backtrace.count > 0 && include_backtrace) {
799 backtrace_t trace = context->backtrace;
800 trace.symbols = NULL;
801 trace.tried_symbolize = false;
802 // Symbolizer subprocess diagnostics must not leak into a live frame.
803 LOG_IO("symbolizer", { backtrace_symbolize(&trace, ASCIICHAT_OWNED_SOURCE_DIRS); });
804 if (trace.symbols)
805 backtrace_print(LOG_ERROR, "Error backtrace", &trace, ERROR_BACKTRACE_INTERNAL_FRAMES, 0, backtrace_filter_error_internal);
806 backtrace_t_free(&trace);
807 }
808 g_recording = previous;
809}
810
812 print_error_context(context, true);
813}
814
816 // Copy one bounded thread stack at a time. A generation check prevents a
817 // reused thread slot from being attributed to the thread sampled earlier.
819 size_t count = 0;
820 registry_lock();
821 for (size_t i = 0; i < ASCIICHAT_ERRNO_MAX_THREADS; ++i)
822 if (g_threads[i].depth) {
823 ids[count] = g_threads[i].id;
824 generations[count++] = g_threads[i].generation;
825 }
826 registry_unlock();
827 log_plain("Pending error stacks (%zu threads):", count);
828 for (size_t i = 0; i < count; ++i) {
830 size_t depth = errno_snapshot(ids[i], contexts, ASCIICHAT_ERRNO_MAX_DEPTH).copied;
831 if (!depth || contexts[0].generation != generations[i])
832 continue;
833 for (size_t j = 0; j < depth; ++j)
834 asciichat_print_error_context(&contexts[j]);
835 }
837}
841 static const char *outcomes[] = {"handled", "dismissed", "thread-exit", "overflow"};
842 for (size_t i = 0; i < count; ++i) {
843 const asciichat_errno_history_t *event = &events[i];
844 log_plain("Error #%" PRIu64 " thread=%" PRIu64 " code=%d %s after %.3fms: %s", event->context.error_id, event->context.thread_id, event->context.code, outcomes[event->outcome],
845 (double)(event->resolved_ns - event->context.created_ns) / 1e6, event->context.context_message);
846 }
847}
849 size_t used = 0, max_chain = 0;
850 registry_lock();
851 for (size_t i = 0; i < ERRNO_BUCKETS; ++i) {
852 size_t chain = 0;
853 for (error_thread_t *thread = g_buckets[i]; thread; thread = thread->next)
854 ++chain;
855 used += chain != 0;
856 if (chain > max_chain)
857 max_chain = chain;
858 }
859 size_t entries = g_stats.registered_threads;
860 registry_unlock();
861 log_plain("Error registry: entries=%zu buckets=%d used=%zu max_chain=%zu reserved_bytes=%zu", entries, ERRNO_BUCKETS, used, max_chain,
862 sizeof(g_threads) + sizeof(g_buckets) + sizeof(g_frames) + sizeof(g_history));
863}
864
865void asciichat_fatal_with_context(asciichat_error_t code, const char *file, int line, const char *function, const char *format, ...) {
866 // This path must also work when an allocator or a diagnostic itself failed.
867 bool previous = g_recording;
868 g_recording = true;
869 char message[ASCIICHAT_ERRNO_MESSAGE_MAX];
870 va_list args;
871 va_start(args, format);
872 vsnprintf(message, sizeof(message), format ? format : "", args);
873 va_end(args);
874 NOTICE(FATAL, "FATAL ERROR", "%s", asciichat_error_format(message, code));
875 log_error("Fatal: %s (at %s:%d in %s)", asciichat_error_format(message, code), file ? file : "?", line, function ? function : "?");
877 g_recording = previous;
878#ifdef EMSCRIPTEN_BUILD
879 SET_ERRNO(code, "%s", message);
880#else
881 exit(code);
882#endif
883}
884
886 registry_lock();
887 error_thread_t *thread = find_thread(scope.thread_id);
888 bool clean = !thread || thread->generation != scope.generation || !thread->depth || g_frames[thread->top].context.error_id <= scope.after_id;
889 registry_unlock();
890 return clean;
891}
894 size_t count = errno_snapshot(id, frames, ASCIICHAT_ERRNO_MAX_DEPTH).copied;
895 log_plain("Failure chain (outer context -> root cause):");
896 for (size_t i = 0; i < count && error_id; ++i) {
897 if (frames[i].error_id == error_id) {
898 // Automatic error logs keep their full cause metadata at normal verbosity.
899 // Symbolization can launch external tools and is reserved for Debug logs;
900 // explicit stack reports above still include backtraces at every level.
901 print_error_context(&frames[i], log_get_level() <= LOG_DEBUG);
902 error_id = frames[i].cause_id;
903 }
904 }
905 if (error_id)
906 log_plain(" Cause #%" PRIu64 " was resolved or evicted; consult handled-error history", error_id);
907}
908
910 registry_lock();
911 if (g_exit_code == ASCIICHAT_OK)
912 g_exit_code = code;
913 registry_unlock();
914}
916 registry_lock();
917 asciichat_error_t code = g_exit_code;
918 registry_unlock();
919 return code;
920}
asciichat_error_t errno_set_with_message(asciichat_error_t code, const char *file, int line, const char *function, const char *format,...)
void errno_clear_all(void)
void errno_clear_thread_error(uint64_t id)
bool errno_has_code_since(asciichat_errno_scope_t scope, asciichat_error_t code)
void errno_request_exit(asciichat_error_t code)
void errno_notifications_dismiss(uint64_t through_id)
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_error_t errno_exit_code(void)
void errno_print_chain(uint64_t id, uint64_t error_id)
bool errno_notifications_pending(void)
void errno_notifications_pause(void)
asciichat_error_t errno_set_with_system_error(asciichat_error_t code, const char *file, int line, const char *function, int sys_errno)
bool errno_has_code_tid(uint64_t id, asciichat_error_t code)
void errno_shutdown(void)
size_t errno_notifications_snapshot(asciichat_error_context_t *out, size_t capacity, uint64_t *dropped)
#define ERROR_RENDER_SLOT_COUNT
bool errno_has(asciichat_error_context_t *context)
bool errno_clear_if_current(uint64_t id, uint64_t generation, uint64_t error_id)
void asciichat_error_stats_print(void)
size_t errno_threads_snapshot(uint64_t *out, size_t capacity)
void errno_clear_thread_errors(uint64_t id)
void errno_print_history(void)
asciichat_errno_snapshot_t errno_snapshot(uint64_t id, asciichat_error_context_t *out, size_t capacity)
#define ERRNO_BUCKETS
#define ASCIICHAT_ERRNO_SUFFIX_BUFFER_SIZE
#define RESERVED_FRAMES
bool errno_has_wsa_error(void)
asciichat_error_t errno_get(void)
bool errno_notifications_suppress(bool suppress)
asciichat_error_t errno_set(asciichat_error_t code, const char *file, int line, const char *function, const char *message)
asciichat_errno_scope_t errno_checkpoint(void)
#define NO_FRAME
asciichat_error_stats_t asciichat_error_stats_get(void)
bool errno_clear_if_top(uint64_t id, uint64_t generation, uint64_t error_id)
void asciichat_error_stats_init(void)
asciichat_error_t errno_set_with_wsa_error(asciichat_error_t code, const char *file, int line, const char *function, int wsa_error)
asciichat_errno_scope_t errno_scope_begin(void)
size_t errno_history_snapshot(asciichat_errno_history_t *out, size_t capacity)
asciichat_error_t errno_get_thread_error(uint64_t id)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
void errno_destroy(void)
void asciichat_error_stats_reset(void)
asciichat_error_t errno_import(const asciichat_error_context_t *cause)
asciichat_error_t errno_set_with_system_error_and_message(asciichat_error_t code, const char *file, int line, const char *function, int sys_errno, const char *format,...)
void errno_print_hash_stats(void)
void errno_print_stacks(void)
bool errno_scope_is_clean(asciichat_errno_scope_t scope)
struct error_thread error_thread_t
For error thread, this is the live record that ties id, generation, top, depth together....
bool errno_has_thread_error(uint64_t id, asciichat_error_context_t *context)
void errno_notifications_enable(bool enabled)
void errno_suppress(bool suppress)
void asciichat_print_error_context(const asciichat_error_context_t *context)
bool errno_has_code(asciichat_error_t code)
void asciichat_error_stats_record(asciichat_error_t code)
size_t errno_title_snapshot(asciichat_error_context_t *latest)
void errno_clear(void)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define ASCIICHAT_ERRNO_MESSAGE_MAX
#define ASCIICHAT_ERRNO_MAX_THREADS
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
#define ASCIICHAT_ERRNO_HISTORY_SIZE
asciichat_errno_outcome_t
@ ASCIICHAT_ERRNO_THREAD_EXIT
@ ASCIICHAT_ERRNO_HANDLED
@ ASCIICHAT_ERRNO_OVERFLOW
#define ASCIICHAT_ERRNO_MAX_FRAMES
#define ASCIICHAT_ERRNO_MAX_DEPTH
bool atomic_cas_int_impl(atomic_t *a, int *expected, int new_value)
bool atomic_load_bool_impl(const atomic_t *a)
void atomic_store_bool_impl(atomic_t *a, uint64_t value)
void atomic_store_int_impl(atomic_t *a, uint64_t value)
void backtrace_t_free(backtrace_t *bt)
Definition backtrace.c:35
void backtrace_symbolize(backtrace_t *bt, const char *const *owned_dirs)
Definition backtrace.c:42
void backtrace_print(int level, const char *label, const backtrace_t *bt, int skip_frames, int max_frames, backtrace_frame_filter_t filter)
Definition backtrace.c:50
void backtrace_capture(backtrace_t *bt)
Definition backtrace.c:14
bool backtrace_filter_error_internal(const char *frame)
Definition backtrace.c:9
bool enabled
Is filtering active?
Definition grep.c:62
void asciichat_fatal_with_context(asciichat_error_t code, const char *file, int line, const char *function, const char *format,...)
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
log_level_t log_get_level(void)
Get the current minimum log level.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:659
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:132
Capture stdout/stderr and redirect to logging system.
#define LOG_IO(prefix, block)
Definition io.h:104
action_args_t args
#define NOTICE(severity, title,...)
Definition notice.h:56
void ascii_otel_error_code(asciichat_error_t code, const char *message)
Definition otel.c:753
#define MIN(a, b)
Definition param.h:6
📂 Path Manipulation Utilities
static bool size_t index
Definition queries.h:8
static bool size_t gotel_query_t * out
Definition queries.h:8
🔤 String Manipulation and Shell Escaping Utilities
asciichat_error_context_t context
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
uint64_t created_ns
Monotonic time, for age.
uint64_t timestamp
Microseconds since epoch, for logs.
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
asciichat_error_context_t context
For error thread, this is the live record that ties id, generation, top, depth together....
uint64_t cause_after_id
struct error_thread * next
uint64_t generation
⏱️ High-precision timing utilities using sokol_time.h and uthash
#define LOG_DEBUG
Definition types.h:43
#define LOG_ERROR
Definition types.h:46
void platform_clear_error_state(void)
Definition util.c:76