ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
debug/named.c
Go to the documentation of this file.
1
10
11/* Storage capacities in elements; text buffers include the terminating NUL. */
12#define DEBUG_NAMED_FINAL_BASE_NAME_BUFFER_SIZE 256
13
15#include "ascii-chat/log/log.h"
17#include "libplatform/rwlock.h"
18#include "libplatform/thread.h"
20#include <ascii-chat/source_root.h>
21#include <ascii-chat/uthash.h>
23#include <libplatform/lifecycle.h>
24
25#include <inttypes.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29
30// Hash table growth runs under entries_lock. Memory tracking looks up names
31// under the same lock, so registry metadata must use untracked allocations.
32#undef uthash_malloc
33#undef uthash_free
34#define uthash_malloc(sz) malloc(sz)
35#define uthash_free(ptr, sz) free(ptr)
36
37#define MAX_NAME_LEN 256
38#define DESCRIBE_BUFFER_SIZE 768
39
48static char *entry_strdup(const char *s) {
49 if (!s)
50 return NULL;
51 size_t len = strlen(s) + 1;
52 char *dup = malloc(len);
53 if (dup) {
54 asciichat_error_t strcpy_result = SAFE_STRCPY(dup, len, s);
55 if (strcpy_result != ASCIICHAT_OK) {
56 log_error("Failed to duplicate string: %s",
57 asciichat_error_format(NULL, strcpy_result));
58 free(dup);
59 return NULL;
60 }
61 }
62 return dup;
63}
64
68typedef struct named_entry {
69 uintptr_t key;
71 char *name;
72 char *type;
74 char *file;
75 int line;
76 char *func;
77 UT_hash_handle hh; // uthash handle
79
87typedef struct {
88 named_entry_t *entries; // uthash hash table
89 rwlock_t entries_lock; // Protects hash table
90 lifecycle_t lifecycle;
92
93static named_registry_t g_named_registry = {
94 .entries = NULL,
95 .entries_lock = {0},
96 .lifecycle = LIFECYCLE_INIT,
97};
98
99// Writers publish a revision while holding entries_lock. Readers only load it;
100// their snapshots own all display strings and never retain object pointers.
101static _Atomic uint64_t g_metadata_revision = 1;
102static tls_key_t g_metadata_tls;
103static bool g_metadata_tls_ready;
104
112
125static _Thread_local named_metadata_cache_t *g_thread_metadata;
126
127static void metadata_cache_destroy(void *data) {
128 named_metadata_cache_t *cache = data;
129 if (cache) {
130 if (g_thread_metadata == cache)
131 g_thread_metadata = NULL;
132 UNTRACKED_FREE(cache->entries);
133 UNTRACKED_FREE(cache);
134 }
135}
136
137static int metadata_compare(const void *left, const void *right) {
138 uintptr_t a = ((const named_metadata_entry_t *)left)->key;
139 uintptr_t b = ((const named_metadata_entry_t *)right)->key;
140 return (a > b) - (a < b);
141}
142
143static bool metadata_copy_entry(const named_entry_t *entry,
144 named_metadata_t *output) {
145 const char *name = entry->name ? entry->name : "?";
146 const char *type = entry->type ? entry->type : "object";
147 const char *format = entry->format_spec ? entry->format_spec : "0x%tx";
148 if (strlen(name) >= sizeof(output->name) ||
149 strlen(type) >= sizeof(output->type) ||
150 strlen(format) >= sizeof(output->format))
151 return false;
152 memcpy(output->name, name, strlen(name) + 1);
153 memcpy(output->type, type, strlen(type) + 1);
154 memcpy(output->format, format, strlen(format) + 1);
155 return true;
156}
157
158static named_metadata_cache_t *metadata_snapshot(void) {
159 if (!g_metadata_tls_ready ||
160 !lifecycle_is_initialized(&g_named_registry.lifecycle))
161 return NULL;
162 named_metadata_cache_t *cache = g_thread_metadata;
163 if (cache && cache->revision == atomic_load(&g_metadata_revision))
164 return cache;
165 if (!cache) {
166 cache = UNTRACKED_MALLOC(sizeof(*cache), named_metadata_cache_t *);
167 if (!cache)
168 return NULL;
169 memset(cache, 0, sizeof(*cache));
170 if (platform_tls_set(g_metadata_tls, cache) != 0) {
171 metadata_cache_destroy(cache);
172 return NULL;
173 }
174 g_thread_metadata = cache;
175 }
176 bool acquired = false;
177 if (rwlock_tryrdlock(&g_named_registry.entries_lock, &acquired) !=
178 ASCIICHAT_OK ||
179 !acquired)
180 return NULL;
181 size_t required = HASH_COUNT(g_named_registry.entries);
182 rwlock_rdunlock(&g_named_registry.entries_lock);
183 if (required > cache->capacity) {
184 if (required > SIZE_MAX / sizeof(*cache->entries))
185 return NULL;
186 named_metadata_entry_t *entries =
187 UNTRACKED_MALLOC(required * sizeof(*entries), named_metadata_entry_t *);
188 if (!entries)
189 return NULL;
190 UNTRACKED_FREE(cache->entries);
191 cache->entries = entries;
192 cache->capacity = required;
193 }
194 if (rwlock_tryrdlock(&g_named_registry.entries_lock, &acquired) !=
195 ASCIICHAT_OK ||
196 !acquired)
197 return NULL;
198 if (HASH_COUNT(g_named_registry.entries) > cache->capacity) {
199 rwlock_rdunlock(&g_named_registry.entries_lock);
200 return NULL;
201 }
202 cache->count = 0;
203 for (named_entry_t *entry = g_named_registry.entries; entry;
204 entry = entry->hh.next) {
205 // An initializer and owner can register the same address. Keep the latest
206 // hash entry, matching HASH_FIND, rather than returning an older alias.
207 named_entry_t *latest = NULL;
208 HASH_FIND(hh, g_named_registry.entries, &entry->key, sizeof(entry->key),
209 latest);
210 if (latest != entry)
211 continue;
212 named_metadata_entry_t *copy = &cache->entries[cache->count++];
213 copy->key = entry->key;
214 copy->valid = metadata_copy_entry(entry, &copy->metadata);
215 }
216 cache->revision = atomic_load(&g_metadata_revision);
217 rwlock_rdunlock(&g_named_registry.entries_lock);
218 if (cache->count > 1)
219 qsort(cache->entries, cache->count, sizeof(*cache->entries),
220 metadata_compare);
221 return cache;
222}
223
224bool named_metadata_copy(uintptr_t key, named_metadata_t *output) {
225 if (!output)
226 return false;
227 named_metadata_cache_t *cache = metadata_snapshot();
228 if (!cache) {
229 // Keep names available if TLS/allocation is unavailable. No borrowed
230 // strings escape this fallback either.
231 if (!lifecycle_is_initialized(&g_named_registry.lifecycle))
232 return false;
233 bool acquired = false;
234 if (rwlock_tryrdlock(&g_named_registry.entries_lock, &acquired) !=
235 ASCIICHAT_OK ||
236 !acquired)
237 return false;
238 named_entry_t *entry = NULL;
239 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(key), entry);
240 bool copied = entry && metadata_copy_entry(entry, output);
241 rwlock_rdunlock(&g_named_registry.entries_lock);
242 return copied;
243 }
244 named_metadata_entry_t lookup = {.key = key};
245 const named_metadata_entry_t *entry =
246 cache->count ? bsearch(&lookup, cache->entries, cache->count,
247 sizeof(*cache->entries), metadata_compare)
248 : NULL;
249 if (!entry || !entry->valid)
250 return false;
251 *output = entry->metadata;
252 return true;
253}
254
256 // Idempotent: if already initialized, return success
257 if (lifecycle_is_initialized(&g_named_registry.lifecycle)) {
258 return ASCIICHAT_OK;
259 }
260
261 if (!lifecycle_init(&g_named_registry.lifecycle, "named_registry")) {
262 return ASCIICHAT_OK;
263 }
264
265 if (rwlock_init(&g_named_registry.entries_lock, "named_registry_lock") != 0) {
266 lifecycle_shutdown(&g_named_registry.lifecycle);
267 return ASCIICHAT_OK; // Continue even if rwlock init fails
268 }
269
270 g_metadata_tls_ready =
271 platform_tls_key_create(&g_metadata_tls, metadata_cache_destroy) == 0;
272 atomic_fetch_add(&g_metadata_revision, 1);
273 lifecycle_init_commit(&g_named_registry.lifecycle);
274 return ASCIICHAT_OK;
275}
276
277void named_destroy(void) {
278 if (!lifecycle_shutdown(&g_named_registry.lifecycle))
279 return;
280 rwlock_wrlock(&g_named_registry.entries_lock);
281 named_entry_t *entry, *next;
282 HASH_ITER(hh, g_named_registry.entries, entry, next) {
283 // Remove each hash node so uthash releases its bucket storage as well.
284 // Unregistration is disabled after lifecycle shutdown, including for the
285 // registry lock itself; all entries must be freed here.
286 HASH_DEL(g_named_registry.entries, entry);
287 free(entry->name);
288 free(entry->type);
289 free(entry->format_spec);
290 free(entry->file);
291 free(entry->func);
292 free(entry);
293 }
294 g_named_registry.entries_lock.name = NULL;
295 atomic_fetch_add(&g_metadata_revision, 1);
296 rwlock_wrunlock(&g_named_registry.entries_lock);
297 rwlock_destroy(&g_named_registry.entries_lock);
298 if (g_metadata_tls_ready) {
299 void *cache = g_thread_metadata;
300 platform_tls_set(g_metadata_tls, NULL);
301 metadata_cache_destroy(cache);
302 platform_tls_key_delete(g_metadata_tls);
303 g_metadata_tls_ready = false;
304 }
305}
306
314static uint64_t mutex_counter = 0;
315static uint64_t rwlock_counter = 0;
316static uint64_t cond_counter = 0;
317static uint64_t atomic_counter = 0;
318static _Atomic uint64_t named_generation = 0;
319
325static void named_entry_init(named_entry_t *entry, const char *type,
326 const char *format_spec, const char *file,
327 int line, const char *func) {
328 entry->generation = ++named_generation;
329 entry->type = entry_strdup(type);
330 entry->format_spec = entry_strdup(format_spec);
331 entry->file = file ? entry_strdup(extract_project_relative_path(
332 file, ASCIICHAT_OWNED_SOURCE_DIRS))
333 : NULL;
334 entry->line = line;
335 entry->func = func ? entry_strdup(func) : NULL;
336}
337
345static const char *named_lookup_name_unlocked(uintptr_t parent_key) {
346 if (parent_key == 0)
347 return NULL;
348 named_entry_t *entry = NULL;
349 HASH_FIND(hh, g_named_registry.entries, &parent_key, sizeof(uintptr_t),
350 entry);
351 return entry ? entry->name : NULL;
352}
353
354const char *named_register(uintptr_t key, const char *base_name,
355 const char *type, const char *format_spec,
356 const char *file, int line, const char *func,
357 uintptr_t parent_key) {
358#ifdef NDEBUG
359 // In release builds, skip debug registry and return the base name
360 return base_name ? base_name : "?";
361#endif
362
363 if (!base_name || !type || !format_spec) {
364 return "?";
365 }
366
367 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
368 return base_name;
369 }
370
371 // If parent_key provided, look up parent name and create hierarchical name
372 char final_base_name[DEBUG_NAMED_FINAL_BASE_NAME_BUFFER_SIZE];
373 if (parent_key != 0) {
374 rwlock_rdlock(&g_named_registry.entries_lock);
375 const char *parent_name = named_lookup_name_unlocked(parent_key);
376 rwlock_rdunlock(&g_named_registry.entries_lock);
377
378 if (parent_name) {
379 snprintf(final_base_name, sizeof(final_base_name), "%s#%s", parent_name,
380 base_name);
381 } else {
382 // Parent not found, fall back to base name
383 snprintf(final_base_name, sizeof(final_base_name), "%s", base_name);
384 }
385 } else {
386 snprintf(final_base_name, sizeof(final_base_name), "%s", base_name);
387 }
388
389 // Generate unique name using atomic counters (only for non-hierarchical
390 // names)
391 char name_buffer[DEBUG_NAMED_NAME_BUFFER_SIZE];
392 if (parent_key == 0) {
393 uint64_t counter = 0;
394 if (strcmp(type, "mutex") == 0) {
395 counter = __sync_fetch_and_add(&mutex_counter, 1);
396 } else if (strcmp(type, "rwlock") == 0) {
397 counter = __sync_fetch_and_add(&rwlock_counter, 1);
398 } else if (strcmp(type, "cond") == 0) {
399 counter = __sync_fetch_and_add(&cond_counter, 1);
400 } else if (strcmp(type, "atomic") == 0) {
401 counter = __sync_fetch_and_add(&atomic_counter, 1);
402 }
403 snprintf(name_buffer, sizeof(name_buffer), "%s.%" PRIu64, final_base_name,
404 counter);
405 } else {
406 // Hierarchical names don't get counters - parent already has one
407 snprintf(name_buffer, sizeof(name_buffer), "%s", final_base_name);
408 }
409
410 // Allocate entry BEFORE acquiring lock (avoid long critical section)
411 named_entry_t *entry = malloc(sizeof(named_entry_t));
412 if (!entry)
413 return base_name;
414
415 entry->key = key;
416 entry->name = entry_strdup(name_buffer);
417 named_entry_init(entry, type, format_spec, file, line, func);
418
419 // Only hold lock for the hash table operation
420 log_dev("[NAMED_REGISTER_LOCK_1] About to acquire entries_lock for key=%p "
421 "type=%s",
422 (void *)key, type);
423 rwlock_wrlock(&g_named_registry.entries_lock);
424 HASH_ADD(hh, g_named_registry.entries, key, sizeof(uintptr_t), entry);
425 atomic_fetch_add(&g_metadata_revision, 1);
426 rwlock_wrunlock(&g_named_registry.entries_lock);
427 log_dev("[NAMED_REGISTER_LOCK_4] ✅ Released entries_lock");
428
429 return entry->name;
430}
431
432const char *named_register_fmt(uintptr_t key, const char *type,
433 const char *format_spec, const char *file,
434 int line, const char *func, const char *fmt,
435 ...) {
436 if (!type || !format_spec || !fmt) {
437 return "?";
438 }
439
440 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
441 return fmt;
442 }
443
444 // Format the name BEFORE acquiring lock
445 va_list args;
446 va_start(args, fmt);
447 char *full_name = NULL;
448 int ret = platform_vasprintf(&full_name, fmt, args);
449 va_end(args);
450
451 if (ret < 0) {
452 return "?";
453 }
454
455 // Allocate entry BEFORE acquiring lock
456 named_entry_t *entry = malloc(sizeof(named_entry_t));
457 if (!entry) {
458 free(full_name);
459 return "?";
460 }
461
462 // Initialize entry (name is pre-allocated as full_name)
463 entry->key = key;
464 entry->name = full_name;
465 named_entry_init(entry, type, format_spec, file, line, func);
466
467 // Only hold lock for the hash table operation
468 rwlock_wrlock(&g_named_registry.entries_lock);
469 HASH_ADD(hh, g_named_registry.entries, key, sizeof(uintptr_t), entry);
470 atomic_fetch_add(&g_metadata_revision, 1);
471 rwlock_wrunlock(&g_named_registry.entries_lock);
472
473 return entry->name;
474}
475
476void named_unregister(uintptr_t key) {
477 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
478 return;
479 }
480
481 rwlock_wrlock(&g_named_registry.entries_lock);
482 named_entry_t *entry = NULL;
483 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
484 bool changed = entry != NULL;
485 // A primitive may be registered again with a parent-qualified name. Retire
486 // every entry before its owner releases the object.
487 while (entry) {
488 HASH_DEL(g_named_registry.entries, entry);
489 free(entry->name);
490 if (entry->type)
491 free(entry->type);
492 if (entry->format_spec)
493 free(entry->format_spec);
494 if (entry->file)
495 free(entry->file);
496 if (entry->func)
497 free(entry->func);
498 free(entry);
499 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
500 }
501 if (changed)
502 atomic_fetch_add(&g_metadata_revision, 1);
503 rwlock_wrunlock(&g_named_registry.entries_lock);
504}
505
506const char *named_update_name(uintptr_t key, const char *new_base_name) {
507#ifndef NDEBUG
508 if (!new_base_name || !lifecycle_is_initialized(&g_named_registry.lifecycle))
509 return NULL;
510 char name[MAX_NAME_LEN];
511 snprintf(name, sizeof(name), "%s.%" PRIu64, new_base_name,
512 ++named_generation);
513 char *replacement = entry_strdup(name);
514 if (!replacement)
515 return NULL;
516 rwlock_wrlock(&g_named_registry.entries_lock);
517 named_entry_t *entry = NULL;
518 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(key), entry);
519 const char *result = NULL;
520 if (entry) {
521 UNTRACKED_FREE(entry->name);
522 entry->name = replacement;
523 result = replacement;
524 atomic_fetch_add(&g_metadata_revision, 1);
525 } else {
526 UNTRACKED_FREE(replacement);
527 }
528 rwlock_wrunlock(&g_named_registry.entries_lock);
529 return result;
530#else
531 (void)key;
532 (void)new_base_name;
533 return NULL;
534#endif
535}
536
537const char *named_get(uintptr_t key) {
538 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
539 return NULL;
540 }
541
542 rwlock_rdlock(&g_named_registry.entries_lock);
543 named_entry_t *entry = NULL;
544 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
545 const char *result = entry ? entry->name : NULL;
546 rwlock_rdunlock(&g_named_registry.entries_lock);
547 return result;
548}
549
550bool named_registry_has_type(const char *type, size_t length) {
551 if (!type || !length)
552 return false;
553 named_metadata_cache_t *cache = metadata_snapshot();
554 if (!cache)
555 return false;
556 for (size_t i = 0; i < cache->count; ++i) {
557 const named_metadata_entry_t *entry = &cache->entries[i];
558 if (entry->valid && strlen(entry->metadata.type) == length &&
559 memcmp(entry->metadata.type, type, length) == 0)
560 return true;
561 }
562 return false;
563}
564
565const char *named_get_type(uintptr_t key) {
566 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
567 return NULL;
568 }
569
570 rwlock_rdlock(&g_named_registry.entries_lock);
571 named_entry_t *entry = NULL;
572 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
573 const char *result = entry ? entry->type : NULL;
574 rwlock_rdunlock(&g_named_registry.entries_lock);
575 return result;
576}
577
578const char *named_get_format_spec(uintptr_t key) {
579 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
580 return NULL;
581 }
582
583 rwlock_rdlock(&g_named_registry.entries_lock);
584 named_entry_t *entry = NULL;
585 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
586 const char *result = entry ? entry->format_spec : NULL;
587 rwlock_rdunlock(&g_named_registry.entries_lock);
588 return result;
589}
590
591const char *named_describe(uintptr_t key, const char *type_hint) {
592 if (!type_hint)
593 type_hint = "object";
594
595 static _Thread_local char buffer[DESCRIBE_BUFFER_SIZE];
596
597 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
598 snprintf(buffer, sizeof(buffer), "%s (0x%tx)", type_hint, (ptrdiff_t)key);
599 return buffer;
600 }
601
602 rwlock_rdlock(&g_named_registry.entries_lock);
603 named_entry_t *entry = NULL;
604 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
605 rwlock_rdunlock(&g_named_registry.entries_lock);
606
607 if (entry) {
608 const char *type = entry->type ? entry->type : type_hint;
609 const char *name = entry->name ? entry->name : "unknown";
610 if (entry->file && entry->func && entry->line > 0) {
611 snprintf(buffer, sizeof(buffer), "%s/%s (0x%tx) @ %s:%d:%s()", type, name,
612 (ptrdiff_t)key, entry->file, entry->line, entry->func);
613 } else {
614 snprintf(buffer, sizeof(buffer), "%s/%s (0x%tx)", type, name,
615 (ptrdiff_t)key);
616 }
617 } else {
618 snprintf(buffer, sizeof(buffer), "%s (0x%tx)",
619 type_hint ? type_hint : "unknown", (ptrdiff_t)key);
620 }
621
622 return buffer;
623}
624
625const char *named_describe_thread(void *thread) {
626 uintptr_t key = thread_to_key((platform_thread_t)thread);
627 return named_describe(key, "thread");
628}
629
630typedef struct {
631 uintptr_t key;
640
642 void *user_data, bool *completed) {
643 if (!callback || !completed)
645 "Registry iteration requires a callback");
646 *completed = false;
647 // Logging also enumerates names during startup and teardown.
648 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
649 *completed = true;
650 return ASCIICHAT_OK;
651 }
652 bool acquired = false;
654 rwlock_tryrdlock(&g_named_registry.entries_lock, &acquired);
655 if (err != ASCIICHAT_OK || !acquired)
656 return err;
657 size_t capacity = HASH_COUNT(g_named_registry.entries);
658 rwlock_rdunlock(&g_named_registry.entries_lock);
659 if (!capacity) {
660 *completed = true;
661 return ASCIICHAT_OK;
662 }
663 if (capacity > SIZE_MAX / sizeof(named_iter_entry_t))
664 return SET_ERRNO(ERROR_MEMORY, "Named registry snapshot size overflow");
665 // Snapshot metadata must not re-enter the registry through memory tracking.
666 named_iter_entry_t *entries =
667 UNTRACKED_MALLOC(capacity * sizeof(*entries), named_iter_entry_t *);
668 if (!entries)
669 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate named registry snapshot");
670 err = rwlock_tryrdlock(&g_named_registry.entries_lock, &acquired);
671 if (err != ASCIICHAT_OK || !acquired) {
672 UNTRACKED_FREE(entries);
673 return err;
674 }
675 if (HASH_COUNT(g_named_registry.entries) > capacity) {
676 rwlock_rdunlock(&g_named_registry.entries_lock);
677 UNTRACKED_FREE(entries);
678 return ASCIICHAT_OK;
679 }
680 size_t count = 0;
681 for (named_entry_t *e = g_named_registry.entries; e != NULL; e = e->hh.next) {
682 entries[count].key = e->key;
683 const char *src = e->name ? e->name : "?";
684 size_t src_len = strlen(src);
685 if (src_len >= MAX_NAME_LEN)
686 src_len = MAX_NAME_LEN - 1;
687 memcpy(entries[count].name, src, src_len);
688 entries[count].name[src_len] = '\0';
689 count++;
690 }
691 rwlock_rdunlock(&g_named_registry.entries_lock);
692
693 // Call callback outside the lock
694 for (size_t i = 0; i < count; i++) {
695 callback(entries[i].key, entries[i].name, user_data);
696 }
697 UNTRACKED_FREE(entries);
698 *completed = true;
699 return ASCIICHAT_OK;
700}
701
702asciichat_error_t named_registry_try_snapshot(size_t capacity, size_t *required,
703 bool *completed,
705 void *data) {
706 if (!required || !completed || !copy)
708 "Invalid protected registry snapshot");
709 *completed = false;
710 *required = 0;
711 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
712 *completed = true;
713 return ASCIICHAT_OK;
714 }
715 bool acquired = false;
716 asciichat_error_t result =
717 rwlock_tryrdlock(&g_named_registry.entries_lock, &acquired);
718 if (result != ASCIICHAT_OK || !acquired)
719 return result;
720 *required = HASH_COUNT(g_named_registry.entries);
721 if (*required <= capacity) {
722 for (named_entry_t *e = g_named_registry.entries; e; e = e->hh.next)
723 copy(e->key, e->generation, e->name, e->type, e->file, e->line, data);
724 *completed = true;
725 }
726 rwlock_rdunlock(&g_named_registry.entries_lock);
727 return ASCIICHAT_OK;
728}
729
730bool named_registry_read(uintptr_t key, const char *type,
731 void (*read_object)(uintptr_t, void *),
732 void *user_data) {
733 if (!type || !read_object ||
734 !lifecycle_is_initialized(&g_named_registry.lifecycle))
735 return false;
736 bool acquired = false;
737 if (rwlock_tryrdlock(&g_named_registry.entries_lock, &acquired) !=
738 ASCIICHAT_OK ||
739 !acquired)
740 return false;
741 named_entry_t *entry = NULL;
742 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(key), entry);
743 bool found = entry && entry->type && strcmp(entry->type, type) == 0;
744 if (found)
745 read_object(key, user_data);
746 rwlock_rdunlock(&g_named_registry.entries_lock);
747 return found;
748}
749
750const char *named_search_by_type_id(const char *type, void *id) {
751 (void)type;
752 (void)id;
753 return NULL;
754}
755
759static inline uintptr_t encode_fd_key(int fd) {
760 return ((uintptr_t)-1 - (unsigned int)fd);
761}
762
766static inline uintptr_t encode_pkt_type_key(int pkt_type) {
767 return ((uintptr_t)-1 - 100000U - (unsigned int)pkt_type);
768}
769
771 return fd >= 0 && named_metadata_copy(encode_fd_key(fd), output);
772}
773
774bool named_packet_metadata_copy(int packet_type, named_metadata_t *output) {
775 return packet_type >= 0 &&
776 named_metadata_copy(encode_pkt_type_key(packet_type), output);
777}
778
779const char *named_register_fd(int fd, const char *name, const char *file,
780 int line, const char *func) {
781 if (fd < 0) {
782 return "?";
783 }
784
785 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
786 return "?";
787 }
788
789 char name_buffer[DEBUG_NAMED_NAME_BUFFER_SIZE];
790 if (name) {
791 snprintf(name_buffer, sizeof(name_buffer), "%s", name);
792 } else {
793 snprintf(name_buffer, sizeof(name_buffer), "fd=%d", fd);
794 }
795
796 // Allocate entry BEFORE acquiring lock
797 named_entry_t *entry = malloc(sizeof(named_entry_t));
798 if (!entry)
799 return "?";
800
801 uintptr_t key = encode_fd_key(fd);
802 entry->key = key;
803 entry->name = entry_strdup(name_buffer);
804 named_entry_init(entry, "fd", "%d", file, line, func);
805
806 // Only hold lock for the hash table operation
807 rwlock_wrlock(&g_named_registry.entries_lock);
808 HASH_ADD(hh, g_named_registry.entries, key, sizeof(uintptr_t), entry);
809 atomic_fetch_add(&g_metadata_revision, 1);
810 rwlock_wrunlock(&g_named_registry.entries_lock);
811
812 return entry->name;
813}
814
815const char *named_get_fd(int fd) {
816 if (fd < 0)
817 return NULL;
818
819 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
820 return NULL;
821 }
822
823 uintptr_t key = encode_fd_key(fd);
824 rwlock_rdlock(&g_named_registry.entries_lock);
825 named_entry_t *entry = NULL;
826 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
827 const char *result = entry ? entry->name : NULL;
828 rwlock_rdunlock(&g_named_registry.entries_lock);
829 return result;
830}
831
832const char *named_get_fd_format_spec(int fd) {
833 if (fd < 0)
834 return NULL;
835
836 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
837 return NULL;
838 }
839
840 uintptr_t key = encode_fd_key(fd);
841 rwlock_rdlock(&g_named_registry.entries_lock);
842 named_entry_t *entry = NULL;
843 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
844 const char *result = entry ? entry->format_spec : NULL;
845 rwlock_rdunlock(&g_named_registry.entries_lock);
846 return result;
847}
848
849const char *named_register_packet_type(int pkt_type, const char *file, int line,
850 const char *func) {
851 if (pkt_type < 0) {
852 return "?";
853 }
854
855 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
856 return "?";
857 }
858
859 char name_buffer[DEBUG_NAMED_NAME_BUFFER_SIZE];
860 snprintf(name_buffer, sizeof(name_buffer), "PACKET_TYPE=%d", pkt_type);
861
862 // Allocate entry BEFORE acquiring lock
863 named_entry_t *entry = malloc(sizeof(named_entry_t));
864 if (!entry)
865 return "?";
866
867 uintptr_t key = encode_pkt_type_key(pkt_type);
868 entry->key = key;
869 entry->name = entry_strdup(name_buffer);
870 named_entry_init(entry, "packet_type", "%d", file, line, func);
871
872 // Only hold lock for the hash table operation
873 rwlock_wrlock(&g_named_registry.entries_lock);
874 HASH_ADD(hh, g_named_registry.entries, key, sizeof(uintptr_t), entry);
875 atomic_fetch_add(&g_metadata_revision, 1);
876 rwlock_wrunlock(&g_named_registry.entries_lock);
877
878 return entry->name;
879}
880
881const char *named_get_packet_type(int pkt_type) {
882 if (pkt_type < 0)
883 return NULL;
884
885 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
886 return NULL;
887 }
888
889 uintptr_t key = encode_pkt_type_key(pkt_type);
890 rwlock_rdlock(&g_named_registry.entries_lock);
891 named_entry_t *entry = NULL;
892 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
893 const char *result = entry ? entry->name : NULL;
894 rwlock_rdunlock(&g_named_registry.entries_lock);
895 return result;
896}
897
898const char *named_get_packet_type_format_spec(int pkt_type) {
899 if (pkt_type < 0)
900 return NULL;
901
902 if (!lifecycle_is_initialized(&g_named_registry.lifecycle)) {
903 return NULL;
904 }
905
906 uintptr_t key = encode_pkt_type_key(pkt_type);
907 rwlock_rdlock(&g_named_registry.entries_lock);
908 named_entry_t *entry = NULL;
909 HASH_FIND(hh, g_named_registry.entries, &key, sizeof(uintptr_t), entry);
910 const char *result = entry ? entry->format_spec : NULL;
911 rwlock_rdunlock(&g_named_registry.entries_lock);
912 return result;
913}
914
916 // No-op
917}
918
920 if (!lifecycle_is_initialized(&g_named_registry.lifecycle))
921 return;
922 rwlock_rdlock(&g_named_registry.entries_lock);
923 size_t entries = HASH_COUNT(g_named_registry.entries);
924 size_t buckets = g_named_registry.entries
925 ? g_named_registry.entries->hh.tbl->num_buckets
926 : 0;
927 rwlock_rdunlock(&g_named_registry.entries_lock);
928 log_plain("Named registry: entries=%zu buckets=%zu", entries, buckets);
929}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
#define DESCRIBE_BUFFER_SIZE
Definition debug/named.c:38
struct named_entry named_entry_t
Registry entry for uthash.
#define DEBUG_NAMED_FINAL_BASE_NAME_BUFFER_SIZE
Definition debug/named.c:12
const char * named_search_by_type_id(const char *type, void *id)
#define MAX_NAME_LEN
Definition debug/named.c:37
Named object registry for debugging — log identifiable resource names.
#define UNTRACKED_FREE(ptr)
#define SAFE_STRCPY(dest, dest_size, src)
unsigned long long uint64_t
#define UNTRACKED_MALLOC(size, cast)
void named_print_hash_stats(void)
const char * named_get_fd(int fd)
Look up a registered file descriptor.
bool named_registry_has_type(const char *type, size_t length)
const char * named_get_packet_type_format_spec(int pkt_type)
Get the format specifier for a registered packet type.
uintptr_t thread_to_key(platform_thread_t thread)
Convert a thread handle to a registry key.
bool named_packet_metadata_copy(int packet_type, named_metadata_t *output)
bool named_registry_read(uintptr_t key, const char *type, void(*read_object)(uintptr_t, void *), void *user_data)
void named_destroy(void)
Destroy the named object registry.
const char * named_describe(uintptr_t key, const char *type_hint)
Format a description string for logging.
void(* named_snapshot_fn)(uintptr_t key, uint64_t generation, const char *name, const char *type, const char *file, int line, void *data)
bool named_metadata_copy(uintptr_t key, named_metadata_t *output)
const char * named_get_packet_type(int pkt_type)
Look up a registered packet type.
const char * named_register_packet_type(int pkt_type, const char *file, int line, const char *func)
Register a packet type with namespace encoding.
const char * named_register_fd(int fd, const char *name, const char *file, int line, const char *func)
Register a file descriptor with namespace encoding.
const char * named_get_type(uintptr_t key)
Look up the registered type for a resource.
void named_unregister(uintptr_t key)
Unregister a resource by key.
void(* named_iter_callback_t)(uintptr_t key, const char *name, void *user_data)
Callback function for iterating registered entries.
const char * named_get_format_spec(uintptr_t key)
Get the format specifier for a registered named object.
asciichat_error_t named_registry_try_snapshot(size_t capacity, size_t *required, bool *completed, named_snapshot_fn copy, void *data)
void named_registry_register_packet_types(void)
Register all packet types from packet_type_t enum.
const char * named_get(uintptr_t key)
Look up the registered name for a resource.
const char * named_get_fd_format_spec(int fd)
Get the format specifier for a registered file descriptor.
bool named_fd_metadata_copy(int fd, named_metadata_t *output)
asciichat_error_t named_registry_for_each(named_iter_callback_t callback, void *user_data, bool *completed)
Iterate through all registered entries.
#define DEBUG_NAMED_NAME_BUFFER_SIZE
Definition debug/named.h:47
asciichat_error_t named_init(void)
Initialize the named object registry.
const char * named_register(uintptr_t key, const char *base_name, const char *type, const char *format_spec, const char *file, int line, const char *func, uintptr_t parent_key)
Register a resource with an auto-suffixed name, type, and location info.
const char * named_describe_thread(void *thread)
Describe a thread for logging (function wrapper).
const char * named_register_fmt(uintptr_t key, const char *type, const char *format_spec, const char *file, int line, const char *func, const char *fmt,...)
Register a resource with a formatted name, type, and location info (no auto-suffix).
const char * named_update_name(uintptr_t key, const char *new_base_name)
Update the registered name for a resource with a new base name.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:551
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:635
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
📝 Logging API with multiple log levels and terminal output control
action_args_t args
📂 Path Manipulation Utilities
🔤 String Manipulation and Shell Escaping Utilities
Registry entry for uthash.
Definition debug/named.c:68
char * format_spec
Definition debug/named.c:73
uint64_t generation
Definition debug/named.c:70
char * func
Definition debug/named.c:76
uintptr_t key
Definition debug/named.c:69
char * file
Definition debug/named.c:74
int line
Definition debug/named.c:75
UT_hash_handle hh
Definition debug/named.c:77
char * name
Definition debug/named.c:71
char * type
Definition debug/named.c:72
uintptr_t key
char name[256]
named_metadata_entry_t * entries
bool valid
uintptr_t key
named_metadata_t metadata
The useful part of named metadata is in its fields: together they describe what is pending,...
Global registry with uthash and rwlock.
Definition debug/named.c:87
rwlock_t entries_lock
Definition debug/named.c:89
lifecycle_t lifecycle
Definition debug/named.c:90
named_entry_t * entries
Definition debug/named.c:88