ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
instrument_log.c
Go to the documentation of this file.
1
10
11// SPDX-License-Identifier: MIT
12// Debug instrumentation logging runtime for ascii-chat line tracing
13
14/* Storage capacities in elements; text buffers include the terminating NUL. */
15#define TOOLING_PANIC_INSTRUMENT_LOG_TIMESTAMP_BUFFER_SIZE 32
16#define TOOLING_PANIC_INSTRUMENT_LOG_SNIPPET_BUFFER_SIZE 64
17#define TOOLING_PANIC_INSTRUMENT_LOG_TID_BUFFER_SIZE 32
18
19/* Existing buffer budgets in bytes, including NUL for text storage. */
20#define INSTRUMENT_LOG_KEY_BUFFER_SIZE 8
21
23#include <ascii-chat/common.h>
24#include <libplatform/mutex.h>
26#include <libplatform/filesystem.h>
27#include <libplatform/system.h>
28#include <util/string.h>
29#include <libplatform/thread.h>
31#include <libplatform/lifecycle.h>
33
34#include <ctype.h>
35#include <errno.h>
36#include <fcntl.h>
37#include <limits.h>
38#include <stdarg.h>
39#include <stdbool.h>
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <sys/stat.h>
44#include <sys/types.h>
45#include <time.h>
46
47#ifdef _WIN32
48#include <io.h>
49#else
50#include <unistd.h>
51#endif
52
53#if !defined(_WIN32)
54#define ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX 1
55#include <regex.h>
56#else
57#define ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX 0
58// Windows doesn't have mode_t
59typedef int mode_t;
60#endif
61
62#ifdef _WIN32
63#include <direct.h>
64#ifndef mkdir
65#define mkdir(path, mode) _mkdir(path)
66#endif
67// Windows uses _write instead of write
68#define posix_write _write
69#ifndef STDERR_FILENO
70#define STDERR_FILENO 2
71#endif
72#else
73#define posix_write write
74#endif
75
76#ifndef ASCII_INSTR_SOURCE_PRINT_DEFAULT_BASENAME
77#define ASCII_INSTR_SOURCE_PRINT_DEFAULT_BASENAME "ascii-instr"
78#endif
79
80#ifndef ASCII_INSTR_SOURCE_PRINT_MAX_LINE
81#define ASCII_INSTR_SOURCE_PRINT_MAX_LINE 4096
82#endif
83
84#ifndef ASCII_INSTR_SOURCE_PRINT_MAX_SNIPPET
85#define ASCII_INSTR_SOURCE_PRINT_MAX_SNIPPET 2048
86#endif
87
94
108
117
152
153static tls_key_t g_runtime_key;
154static lifecycle_t g_runtime_lc = LIFECYCLE_INIT;
155static char g_output_dir[PATH_MAX];
156static bool g_output_dir_set = false;
157static bool g_disable_write = false;
158static uint64_t g_start_ns = 0;
159static bool g_ticks_initialized = false;
160static bool g_coverage_enabled = false;
161static bool g_echo_to_stderr = false;
162static bool g_echo_to_stderr_initialized = false;
163
164static void asciichat_instr_runtime_init_once(void);
165static void asciichat_instr_runtime_tls_destructor(void *ptr);
166static int asciichat_instr_open_log_file(asciichat_instr_runtime_t *runtime);
167static void asciichat_instr_runtime_configure(asciichat_instr_runtime_t *runtime);
168static bool asciichat_instr_should_log(const asciichat_instr_runtime_t *runtime, const char *file_path, uint32_t line_number, const char *function_name);
169static int asciichat_instr_write_full(int fd, const char *buffer, size_t len);
170static bool asciichat_instr_env_is_enabled(const char *value);
171static bool asciichat_instr_parse_positive_uint32(const char *value, uint32_t *out_value);
172#if ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX
173static bool asciichat_instr_compile_regex(regex_t *regex, const char *pattern);
174#endif
175static void asciichat_instr_only_list_destroy(asciichat_instr_only_list_t *list);
176static bool asciichat_instr_only_list_append(asciichat_instr_only_list_t *list, asciichat_instr_selector_type_t type, const char *module, const char *pattern);
177static void asciichat_instr_trim(char *value);
178static bool asciichat_instr_parse_only_filters(asciichat_instr_runtime_t *runtime, const char *value);
179static bool asciichat_instr_only_selectors_match(const asciichat_instr_runtime_t *runtime, const char *file_path, const char *function_name);
180static bool asciichat_instr_match_glob(const char *pattern, const char *value);
181static const char *asciichat_instr_basename(const char *path);
182static bool asciichat_instr_path_contains_module(const char *file_path, const char *module_name);
183
184static _Thread_local bool g_logging_reentry_guard = false;
185static bool g_instrumentation_enabled = false;
186static bool g_instrumentation_enabled_checked = false;
187
189 if (g_disable_write) {
190 return NULL;
191 }
192
193 // Initialize runtime once using lock-free lifecycle API
194 if (!lifecycle_is_initialized(&g_runtime_lc)) {
195 if (lifecycle_init_once(&g_runtime_lc)) {
196 asciichat_instr_runtime_init_once();
197 lifecycle_init_commit(&g_runtime_lc);
198 }
199 }
200
201 asciichat_instr_runtime_t *runtime = platform_tls_get(g_runtime_key);
202 if (runtime != NULL) {
203 return runtime;
204 }
205
206 runtime = SAFE_CALLOC(1, sizeof(*runtime), asciichat_instr_runtime_t *);
207 if (runtime == NULL) {
208 return NULL;
209 }
210
211 runtime->pid = platform_get_pid();
212 runtime->thread_id = thread_current_id();
213 runtime->sequence = 0;
214 runtime->call_counter = 0;
215 runtime->fd = -1;
216 runtime->filter_include = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_INCLUDE");
217 runtime->filter_exclude = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_EXCLUDE");
218 runtime->filter_thread = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_THREAD");
219 runtime->filter_function_include = NULL;
220 runtime->filter_function_exclude = NULL;
221 runtime->filters_enabled = false;
222 runtime->rate = 1;
223 runtime->rate_enabled = false;
224
225 asciichat_instr_runtime_configure(runtime);
226
227 if (platform_tls_set(g_runtime_key, runtime) != 0) {
228 SAFE_FREE(runtime);
229 return NULL;
230 }
231
232 return runtime;
233}
234
236 if (runtime == NULL) {
237 return;
238 }
239
240 if (runtime->fd >= 0) {
241 platform_close(runtime->fd);
242 runtime->fd = -1;
243 }
244
245#if ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX
246 if (runtime->include_regex_valid) {
247 regfree(&runtime->include_regex);
248 runtime->include_regex_valid = false;
249 }
250 if (runtime->exclude_regex_valid) {
251 regfree(&runtime->exclude_regex);
252 runtime->exclude_regex_valid = false;
253 }
254 if (runtime->function_include_regex_valid) {
255 regfree(&runtime->function_include_regex);
256 runtime->function_include_regex_valid = false;
257 }
258 if (runtime->function_exclude_regex_valid) {
259 regfree(&runtime->function_exclude_regex);
260 runtime->function_exclude_regex_valid = false;
261 }
262#endif
263
264 asciichat_instr_only_list_destroy(&runtime->only_selectors);
265 SAFE_FREE(runtime);
266}
267
269 if (lifecycle_shutdown(&g_runtime_lc)) {
270 g_disable_write = true;
271 asciichat_instr_runtime_t *runtime = platform_tls_get(g_runtime_key);
272 if (runtime != NULL) {
273 platform_tls_set(g_runtime_key, NULL);
275 }
276 platform_tls_key_delete(g_runtime_key);
277 g_ticks_initialized = false;
278 g_start_ns = 0;
279 g_coverage_enabled = false;
280 g_output_dir_set = false;
281 g_output_dir[0] = '\0';
282 g_echo_to_stderr_initialized = false;
283 g_echo_to_stderr = false;
284 }
285
286 g_instrumentation_enabled_checked = false;
287 g_instrumentation_enabled = false;
288
289 // Reset g_disable_write so instrumentation can be re-enabled in subsequent tests
290 g_disable_write = false;
291}
292
293void asciichat_instr_log_line(const char *file_path, uint32_t line_number, const char *function_name, const char *snippet, uint8_t is_macro_expansion) {
294 // Initialization calls project helpers that may themselves be instrumented.
295 if (g_logging_reentry_guard) {
296 return;
297 }
298 g_logging_reentry_guard = true;
299
300 // Instrumentation is enabled by default when the binary is built with Source Print.
301 // Set ASCII_INSTR_SOURCE_PRINT_ENABLE=0 to disable tracing at runtime.
302 if (!g_instrumentation_enabled_checked) {
303 const char *enable_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_ENABLE");
304 // Default to enabled (true) - only disable if explicitly set to "0", "false", "off", or "no"
305 if (enable_env != NULL && enable_env[0] != '\0') {
306 g_instrumentation_enabled = asciichat_instr_env_is_enabled(enable_env);
307 } else {
308 g_instrumentation_enabled = true; // Default to enabled when instrumented
309 }
310 g_instrumentation_enabled_checked = true;
311 }
312
313 if (!g_instrumentation_enabled) {
314 goto cleanup;
315 }
316
317 if (g_disable_write) {
318 goto cleanup;
319 }
320
322 if (runtime == NULL) {
323 goto cleanup;
324 }
325
326 if (!asciichat_instr_should_log(runtime, file_path, line_number, function_name)) {
327 goto cleanup;
328 }
329
330 runtime->call_counter++;
331 if (runtime->rate_enabled) {
332 const uint64_t counter = runtime->call_counter;
333 if (((counter - 1U) % runtime->rate) != 0U) {
334 goto cleanup;
335 }
336 }
337
338 if (runtime->fd < 0) {
339 if (asciichat_instr_open_log_file(runtime) != 0) {
340 runtime->stderr_fallback = true;
341 }
342 }
343
344 const int fd = runtime->stderr_fallback ? STDERR_FILENO : runtime->fd;
346 size_t pos = 0;
347
348 uint64_t realtime_ns = time_get_realtime_ns();
349 time_t sec = (time_t)(realtime_ns / NS_PER_SEC_INT);
350 long nsec = (long)(realtime_ns % NS_PER_SEC_INT);
351 struct tm tm_now;
352 memset(&tm_now, 0, sizeof(tm_now));
353 if (platform_gtime(&sec, &tm_now) != ASCIICHAT_OK) {
354 memset(&tm_now, 0, sizeof(tm_now));
355 }
356
358 size_t ts_len = strftime(timestamp, sizeof(timestamp), "%Y-%m-%dT%H:%M:%S", &tm_now);
359 if (ts_len == 0) {
360 SAFE_STRNCPY(timestamp, "1970-01-01T00:00:00", sizeof(timestamp));
361 ts_len = strlen(timestamp);
362 }
363
364 char elapsed_buf[TIME_DURATION_BUFFER_SIZE];
365 elapsed_buf[0] = '\0';
366 if (g_ticks_initialized) {
367 uint64_t now_ns = time_get_ns();
368 uint64_t elapsed_ns = time_elapsed_ns(g_start_ns, now_ns);
369 if (time_pretty((uint64_t)elapsed_ns, -1, elapsed_buf, sizeof(elapsed_buf)) < 0) {
370 elapsed_buf[0] = '\0';
371 }
372 }
373
374 runtime->sequence++;
375
376 const char *elapsed_field = (elapsed_buf[0] != '\0') ? elapsed_buf : "-";
377
378 const char *safe_file_path = (file_path != NULL) ? file_path : "<unknown>";
379 pos += safe_snprintf(buffer + pos, sizeof(buffer) - pos, "pid=%d tid=%llu seq=%llu ts=%.*s.%09ldZ elapsed=%s file=%s line=%u func=%s macro=%u snippet=", runtime->pid,
380 (unsigned long long)runtime->thread_id, (unsigned long long)runtime->sequence, (int)ts_len, timestamp, nsec, elapsed_field, safe_file_path, line_number,
381 function_name ? function_name : "<unknown>", (unsigned)is_macro_expansion);
382
383 if (snippet != NULL) {
384 size_t snippet_len = strnlen(snippet, ASCII_INSTR_SOURCE_PRINT_MAX_SNIPPET);
385 for (size_t i = 0; i < snippet_len && pos < sizeof(buffer) - 2; ++i) {
386 const char ch = snippet[i];
387 switch (ch) {
388 case '\n':
389 buffer[pos++] = '\\';
390 buffer[pos++] = 'n';
391 break;
392 case '\r':
393 buffer[pos++] = '\\';
394 buffer[pos++] = 'r';
395 break;
396 case '\t':
397 buffer[pos++] = '\\';
398 buffer[pos++] = 't';
399 break;
400 default:
401 buffer[pos++] = ch;
402 break;
403 }
404 }
405 }
406
407 if (pos >= sizeof(buffer) - 1) {
408 pos = sizeof(buffer) - 2;
409 }
410
411 buffer[pos++] = '\n';
412 buffer[pos] = '\0';
413
414 asciichat_instr_write_full(fd, buffer, pos);
415
416 // Also echo to stderr if requested via environment variable
417 if (!g_echo_to_stderr_initialized) {
418 const char *echo_env = SAFE_GETENV("ASCII_CHAT_DEBUG_SELF_SOURCE_CODE_LOG_STDERR");
419 g_echo_to_stderr = asciichat_instr_env_is_enabled(echo_env);
420 g_echo_to_stderr_initialized = true;
421 }
422
423 if (g_echo_to_stderr && !runtime->stderr_fallback) {
424 // Write to stderr in addition to the log file
425 // Suppress Windows deprecation warning for POSIX write function
426#ifdef _WIN32
427#pragma clang diagnostic push
428#pragma clang diagnostic ignored "-Wdeprecated-declarations"
429#endif
430 (void)posix_write(STDERR_FILENO, buffer, pos);
431#ifdef _WIN32
432#pragma clang diagnostic pop
433#endif
434 }
435
436cleanup:
437 g_logging_reentry_guard = false;
438}
439
441 if (g_disable_write) {
442 return false;
443 }
444
445 // Initialize runtime once using lock-free lifecycle API
446 if (!lifecycle_is_initialized(&g_runtime_lc)) {
447 if (lifecycle_init_once(&g_runtime_lc)) {
448 asciichat_instr_runtime_init_once();
449 lifecycle_init_commit(&g_runtime_lc);
450 }
451 }
452
453 return g_coverage_enabled;
454}
455
456void asciichat_instr_log_pc(uintptr_t program_counter) {
458 return;
459 }
460
462 safe_snprintf(snippet, sizeof(snippet), "pc=0x%zx", (size_t)program_counter);
463 asciichat_instr_log_line("__coverage__", 0, "<coverage>", snippet, ASCII_INSTR_SOURCE_PRINT_MACRO_NONE);
464}
465
466static void asciichat_instr_runtime_init_once(void) {
467 // Called by lifecycle_init_once winner
468 (void)platform_tls_key_create(&g_runtime_key, asciichat_instr_runtime_tls_destructor);
469 const char *output_dir_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_OUTPUT_DIR");
470 if (output_dir_env != NULL && output_dir_env[0] != '\0') {
471 if (platform_is_directory(output_dir_env) && strlen(output_dir_env) < sizeof(g_output_dir)) {
472 SAFE_STRNCPY(g_output_dir, output_dir_env, sizeof(g_output_dir));
473 g_output_dir_set = true;
474 } else {
475 log_warn("Ignoring invalid ASCII_INSTR_SOURCE_PRINT_OUTPUT_DIR path: %s", output_dir_env);
476 }
477 }
478 const char *coverage_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_ENABLE_COVERAGE");
479 g_coverage_enabled = asciichat_instr_env_is_enabled(coverage_env);
480 g_start_ns = time_get_ns();
481 g_ticks_initialized = true;
482}
483
484static void asciichat_instr_runtime_tls_destructor(void *ptr) {
486}
487
488static bool asciichat_instr_build_log_path(asciichat_instr_runtime_t *runtime) {
489 // Check for custom log file path first
490 const char *custom_log_file = SAFE_GETENV("ASCII_CHAT_DEBUG_SELF_SOURCE_CODE_LOG_FILE");
491 bool is_custom_path = (custom_log_file != NULL && custom_log_file[0] != '\0');
492
493 if (is_custom_path) {
494 const char *debug_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_ECHO_STDERR");
495 if (debug_env && debug_env[0] == '1') {
496 fprintf(stderr, "ASCII_INSTR: Using custom log path: %s\n", custom_log_file);
497 }
498
499 // For instrumentation log files, bypass strict path validation since this is a debug feature
500 // Just normalize the path to an absolute path without security checks
501 char *expanded = expand_path(custom_log_file);
502 if (!expanded) {
503 log_warn("Failed to expand ASCII_CHAT_DEBUG_SELF_SOURCE_CODE_LOG_FILE path: %s", custom_log_file);
504 return false;
505 }
506
507 // Convert to absolute path if relative
508 char absolute_buf[PATH_MAX];
509 if (!path_is_absolute(expanded)) {
510 char cwd_buf[PATH_MAX];
511 if (!platform_get_cwd(cwd_buf, sizeof(cwd_buf))) {
512 SAFE_FREE(expanded);
513 return false;
514 }
515 // Check if expanded already starts with a separator to avoid double separators
516 if (strlen(expanded) > 0 && expanded[0] == PATH_DELIM) {
517 safe_snprintf(absolute_buf, sizeof(absolute_buf), "%s%s", cwd_buf, expanded);
518 } else {
519 safe_snprintf(absolute_buf, sizeof(absolute_buf), "%s%c%s", cwd_buf, PATH_DELIM, expanded);
520 }
521 SAFE_FREE(expanded);
522 expanded = platform_strdup(absolute_buf);
523 if (!expanded) {
524 return false;
525 }
526 }
527
528 SAFE_STRNCPY(runtime->log_path, expanded, sizeof(runtime->log_path));
529 runtime->log_path[sizeof(runtime->log_path) - 1] = '\0';
530 SAFE_FREE(expanded);
531
532 if (debug_env && debug_env[0] == '1') {
533 fprintf(stderr, "ASCII_INSTR: Resolved custom log path: %s\n", runtime->log_path);
534 }
535
536 // Don't check if file exists - allow appending to existing file
537 // Path already normalized, skip validation below
538 } else {
539 // Determine output directory
540 char output_dir_buf[PATH_MAX];
541 if (g_output_dir_set) {
542 // Use the output directory from ASCII_INSTR_SOURCE_PRINT_OUTPUT_DIR
543 SAFE_STRNCPY(output_dir_buf, g_output_dir, sizeof(output_dir_buf));
544 } else if (!platform_get_cwd(output_dir_buf, sizeof(output_dir_buf))) {
545 // Fallback to temp directory if cwd fails
546 const char *fallback = SAFE_GETENV("TMPDIR");
547 if (fallback == NULL) {
548 fallback = SAFE_GETENV("TEMP");
549 }
550 if (fallback == NULL) {
551 fallback = SAFE_GETENV("TMP");
552 }
553 if (fallback == NULL) {
554 fallback = "/tmp";
555 }
556 SAFE_STRNCPY(output_dir_buf, fallback, sizeof(output_dir_buf));
557 }
558
559 // Build log file name
560 if (g_output_dir_set) {
561 // When output directory is explicitly set, use unique naming with pid and tid
562 if (safe_snprintf(runtime->log_path, sizeof(runtime->log_path), "%s%c%s-%d-%llu.log", output_dir_buf, PATH_DELIM, ASCII_INSTR_SOURCE_PRINT_DEFAULT_BASENAME, runtime->pid,
563 (unsigned long long)runtime->thread_id) >= (int)sizeof(runtime->log_path)) {
564 return false;
565 }
566 } else {
567 // Use simple "trace.log" name in current directory
568 if (safe_snprintf(runtime->log_path, sizeof(runtime->log_path), "%s%ctrace.log", output_dir_buf, PATH_DELIM) >= (int)sizeof(runtime->log_path)) {
569 return false;
570 }
571 }
572 }
573
574 // Explicit output directories are validated during initialization and receive a generated filename.
575 if (!is_custom_path && !g_output_dir_set) {
576 char *validated_log_path = NULL;
577 asciichat_error_t validate_result = path_validate_user_path(runtime->log_path, PATH_ROLE_LOG_FILE, &validated_log_path);
578 if (validate_result != ASCIICHAT_OK || validated_log_path == NULL) {
579 SAFE_FREE(validated_log_path);
580 log_warn("Failed to validate instrumentation log path: %s", runtime->log_path);
581 return false;
582 }
583 SAFE_STRNCPY(runtime->log_path, validated_log_path, sizeof(runtime->log_path));
584 runtime->log_path[sizeof(runtime->log_path) - 1] = '\0';
585 SAFE_FREE(validated_log_path);
586 }
587
588 // Find last path separator
589 const char *last_sep = strrchr(runtime->log_path, PATH_DELIM);
590 if (last_sep != NULL && last_sep != runtime->log_path) {
591 const size_t dir_path_len = (size_t)(last_sep - runtime->log_path);
592 char dir_path[PATH_MAX];
593 memcpy(dir_path, runtime->log_path, dir_path_len);
594 dir_path[dir_path_len] = '\0';
595 if (mkdir(dir_path, DIR_PERM_PRIVATE) != 0) {
596 if (errno != EEXIST) {
597 return false;
598 }
599 }
600 }
601
602 return true;
603}
604
605static int asciichat_instr_open_log_file(asciichat_instr_runtime_t *runtime) {
606 if (!asciichat_instr_build_log_path(runtime)) {
607 const char *debug_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_ECHO_STDERR");
608 if (debug_env && debug_env[0] == '1') {
609 fprintf(stderr, "ASCII_INSTR: Failed to build log path\n");
610 }
611 return -1;
612 }
613
614 // Check if this is a custom log file (env var was set)
615 const char *custom_log_file = SAFE_GETENV("ASCII_CHAT_DEBUG_SELF_SOURCE_CODE_LOG_FILE");
616 const bool is_custom_file = (custom_log_file != NULL && custom_log_file[0] != '\0');
617
618 // For custom files, allow appending to existing file (no O_EXCL)
619 // For auto-generated files, use O_EXCL to avoid conflicts
620 int flags;
621 if (is_custom_file) {
622 flags = PLATFORM_O_WRONLY | PLATFORM_O_CREAT | PLATFORM_O_APPEND | PLATFORM_O_BINARY;
623 } else {
624 flags = PLATFORM_O_WRONLY | PLATFORM_O_CREAT | PLATFORM_O_EXCL | PLATFORM_O_APPEND | PLATFORM_O_BINARY;
625 }
626
627 const char *debug_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_ECHO_STDERR");
628 if (debug_env && debug_env[0] == '1') {
629 fprintf(stderr, "ASCII_INSTR: Opening log file: %s (custom=%d)\n", runtime->log_path, is_custom_file);
630 }
631
632 const mode_t mode = S_IRUSR | S_IWUSR;
633 int fd = platform_open("instrumentation_log", runtime->log_path, flags, mode);
634 if (fd < 0) {
635 if (debug_env && debug_env[0] == '1') {
636 fprintf(stderr, "ASCII_INSTR: Failed to open log file: %s (errno=%d)\n", runtime->log_path, errno);
637 }
638 return -1;
639 }
640
641 if (debug_env && debug_env[0] == '1') {
642 fprintf(stderr, "ASCII_INSTR: Successfully opened log file: %s (fd=%d)\n", runtime->log_path, fd);
643 }
644
645 runtime->fd = fd;
646 return 0;
647}
648
649static void asciichat_instr_runtime_configure(asciichat_instr_runtime_t *runtime) {
650 runtime->filter_function_include = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_FUNCTION_INCLUDE");
651 runtime->filter_function_exclude = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_FUNCTION_EXCLUDE");
652
653 const char *only_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_ONLY");
654 asciichat_instr_parse_only_filters(runtime, only_env);
655
656#if ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX
657 const char *include_regex = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_INCLUDE_REGEX");
658 if (include_regex != NULL && include_regex[0] != '\0') {
659 runtime->include_regex_valid = asciichat_instr_compile_regex(&runtime->include_regex, include_regex);
660 }
661
662 const char *exclude_regex = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_EXCLUDE_REGEX");
663 if (exclude_regex != NULL && exclude_regex[0] != '\0') {
664 runtime->exclude_regex_valid = asciichat_instr_compile_regex(&runtime->exclude_regex, exclude_regex);
665 }
666
667 const char *function_include_regex = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_FUNCTION_INCLUDE_REGEX");
668 if (function_include_regex != NULL && function_include_regex[0] != '\0') {
669 runtime->function_include_regex_valid = asciichat_instr_compile_regex(&runtime->function_include_regex, function_include_regex);
670 }
671
672 const char *function_exclude_regex = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_FUNCTION_EXCLUDE_REGEX");
673 if (function_exclude_regex != NULL && function_exclude_regex[0] != '\0') {
674 runtime->function_exclude_regex_valid = asciichat_instr_compile_regex(&runtime->function_exclude_regex, function_exclude_regex);
675 }
676#endif
677
678 const char *rate_env = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_RATE");
679 uint32_t rate_value = 0;
680 if (asciichat_instr_parse_positive_uint32(rate_env, &rate_value) && rate_value > 1U) {
681 runtime->rate = rate_value;
682 runtime->rate_enabled = true;
683 }
684
685 runtime->filters_enabled = (runtime->filter_include != NULL) || (runtime->filter_exclude != NULL) || (runtime->filter_thread != NULL) || (runtime->filter_function_include != NULL) ||
686 (runtime->filter_function_exclude != NULL)
689#endif
690 || runtime->only_selectors.count > 0;
691}
692
693static bool asciichat_instr_env_is_enabled(const char *value) {
694 if (value == NULL) {
695 return false;
696 }
697
698 while (*value != '\0' && isspace((unsigned char)*value) != 0) {
699 value++;
700 }
701
702 if (*value == '\0') {
703 return false;
704 }
705
706 if (strcmp(value, STR_ZERO) == 0) {
707 return false;
708 }
709
710 char lowered[INSTRUMENT_LOG_KEY_BUFFER_SIZE];
711 size_t len = 0;
712 while (value[len] != '\0' && len < sizeof(lowered) - 1) {
713 lowered[len] = (char)tolower((unsigned char)value[len]);
714 len++;
715 }
716 lowered[len] = '\0';
717
718 return !(strcmp(lowered, STR_FALSE) == 0 || strcmp(lowered, STR_OFF) == 0 || strcmp(lowered, STR_NO) == 0);
719}
720
721static bool asciichat_instr_parse_positive_uint32(const char *value, uint32_t *out_value) {
722 if (value == NULL || out_value == NULL) {
723 return false;
724 }
725
726 while (*value != '\0' && isspace((unsigned char)*value) != 0) {
727 value++;
728 }
729
730 if (*value == '\0') {
731 return false;
732 }
733
734 errno = 0;
735 char *endptr = NULL;
736 unsigned long long parsed = strtoull(value, &endptr, 10);
737 if (errno != 0 || endptr == value || parsed == 0ULL || parsed > UINT32_MAX) {
738 return false;
739 }
740
741 *out_value = (uint32_t)parsed;
742 return true;
743}
744
745#if ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX
746static bool asciichat_instr_compile_regex(regex_t *regex, const char *pattern) {
747 if (regex == NULL || pattern == NULL) {
748 return false;
749 }
750 int ret = regcomp(regex, pattern, REG_EXTENDED | REG_NOSUB);
751 return ret == 0;
752}
753#endif
754
755static void asciichat_instr_only_list_destroy(asciichat_instr_only_list_t *list) {
756 if (list == NULL) {
757 return;
758 }
759 if (list->items != NULL) {
760 for (size_t i = 0; i < list->count; ++i) {
761 asciichat_instr_only_selector_t *selector = &list->items[i];
762 SAFE_FREE(selector->pattern);
763 SAFE_FREE(selector->module);
764 }
765 SAFE_FREE(list->items);
766 }
767 list->count = 0;
768 list->capacity = 0;
769}
770
771static bool asciichat_instr_only_list_append(asciichat_instr_only_list_t *list, asciichat_instr_selector_type_t type, const char *module, const char *pattern) {
772 if (list == NULL) {
773 return false;
774 }
775
777 if (pattern == NULL || pattern[0] == '\0') {
778 return false;
779 }
780 }
781
783 if (module == NULL || module[0] == '\0') {
784 return false;
785 }
786 }
787
788 if (list->count == list->capacity) {
789 size_t new_capacity = (list->capacity == 0) ? 4U : list->capacity * 2U;
790 asciichat_instr_only_selector_t *new_items = SAFE_REALLOC(list->items, new_capacity * sizeof(*new_items), asciichat_instr_only_selector_t *);
791 if (new_items == NULL) {
792 return false; // SAFE_REALLOC already called FATAL, but satisfy analyzer
793 }
794 list->items = new_items;
795 list->capacity = new_capacity;
796 }
797
798 asciichat_instr_only_selector_t *selector = &list->items[list->count];
799 memset(selector, 0, sizeof(*selector));
800 selector->type = type;
801
802 if (module != NULL && module[0] != '\0') {
803 SAFE_STRDUP(selector->module, module);
804 }
805 if (pattern != NULL && pattern[0] != '\0') {
806 SAFE_STRDUP(selector->pattern, pattern);
807 }
808
809 list->count++;
810 return true;
811}
812
813static void asciichat_instr_trim(char *value) {
814 if (value == NULL) {
815 return;
816 }
817
818 char *start = value;
819 while (*start != '\0' && isspace((unsigned char)*start) != 0) {
820 start++;
821 }
822
823 char *end = start + strlen(start);
824 while (end > start && isspace((unsigned char)end[-1]) != 0) {
825 end--;
826 }
827
828 const size_t length = (size_t)(end - start);
829 if (start != value && length > 0U) {
830 memmove(value, start, length);
831 }
832 value[length] = '\0';
833}
834
835static bool asciichat_instr_parse_only_filters(asciichat_instr_runtime_t *runtime, const char *value) {
836 if (runtime == NULL) {
837 return false;
838 }
839
840 asciichat_instr_only_list_destroy(&runtime->only_selectors);
841
842 if (value == NULL || value[0] == '\0') {
843 return true;
844 }
845
846 char *mutable_value = NULL;
847 SAFE_STRDUP(mutable_value, value);
848 if (mutable_value == NULL) {
849 return false;
850 }
851
852 char *cursor = mutable_value;
853 while (cursor != NULL && *cursor != '\0') {
854 char *token_start = cursor;
855 while (*cursor != '\0' && *cursor != ',') {
856 cursor++;
857 }
858 if (*cursor == ',') {
859 *cursor = '\0';
860 cursor++;
861 } else {
862 cursor = NULL;
863 }
864
865 asciichat_instr_trim(token_start);
866 if (*token_start == '\0') {
867 continue;
868 }
869
870 char *equal_sign = strchr(token_start, '=');
871 if (equal_sign != NULL) {
872 *equal_sign = '\0';
873 char *kind = token_start;
874 char *spec = equal_sign + 1;
875 asciichat_instr_trim(kind);
876 asciichat_instr_trim(spec);
877 if (*spec == '\0') {
878 continue;
879 }
880
881 if (strcmp(kind, "func") == 0 || strcmp(kind, "function") == 0) {
882 (void)asciichat_instr_only_list_append(&runtime->only_selectors, ASCII_INSTR_SOURCE_PRINT_SELECTOR_FUNCTION_GLOB, NULL, spec);
883 } else if (strcmp(kind, "module") == 0) {
884 char *module_value = spec;
885 char *module_pattern = strchr(module_value, ':');
886 if (module_pattern != NULL) {
887 *module_pattern = '\0';
888 module_pattern++;
889 asciichat_instr_trim(module_pattern);
890 }
891 asciichat_instr_trim(module_value);
892 if (*module_value == '\0') {
893 continue;
894 }
895 const char *pattern_part = (module_pattern != NULL && *module_pattern != '\0') ? module_pattern : NULL;
896 (void)asciichat_instr_only_list_append(&runtime->only_selectors, ASCII_INSTR_SOURCE_PRINT_SELECTOR_MODULE, module_value, pattern_part);
897 } else {
898 // "file" kind or unknown kinds default to FILE_GLOB
899 (void)asciichat_instr_only_list_append(&runtime->only_selectors, ASCII_INSTR_SOURCE_PRINT_SELECTOR_FILE_GLOB, NULL, spec);
900 }
901 continue;
902 }
903
904 char *colon = strchr(token_start, ':');
905 if (colon != NULL) {
906 *colon = '\0';
907 char *module_name = token_start;
908 char *pattern_part = colon + 1;
909 asciichat_instr_trim(module_name);
910 asciichat_instr_trim(pattern_part);
911 if (*module_name == '\0') {
912 continue;
913 }
914 const char *pattern_spec = (*pattern_part != '\0') ? pattern_part : NULL;
915 (void)asciichat_instr_only_list_append(&runtime->only_selectors, ASCII_INSTR_SOURCE_PRINT_SELECTOR_MODULE, module_name, pattern_spec);
916 continue;
917 }
918
919 (void)asciichat_instr_only_list_append(&runtime->only_selectors, ASCII_INSTR_SOURCE_PRINT_SELECTOR_FILE_SUBSTRING, NULL, token_start);
920 }
921
922 SAFE_FREE(mutable_value);
923 return true;
924}
925
926static bool asciichat_instr_match_glob(const char *pattern, const char *value) {
927 if (pattern == NULL || value == NULL) {
928 return false;
929 }
930
931 const char *p = pattern;
932 const char *v = value;
933 const char *star = NULL;
934 const char *match = NULL;
935
936 while (*v != '\0') {
937 if (*p == '*') {
938 star = p++;
939 match = v;
940 } else if (*p == '?' || *p == *v) {
941 p++;
942 v++;
943 } else if (star != NULL) {
944 p = star + 1;
945 match++;
946 v = match;
947 } else {
948 return false;
949 }
950 }
951
952 while (*p == '*') {
953 p++;
954 }
955
956 return *p == '\0';
957}
958
959static const char *asciichat_instr_basename(const char *path) {
960 if (path == NULL) {
961 return NULL;
962 }
963
964 // Find last path separator
965 const char *last_sep = strrchr(path, PATH_DELIM);
966 if (last_sep != NULL && last_sep[1] != '\0') {
967 return last_sep + 1;
968 }
969 return path;
970}
971
972static bool asciichat_instr_path_contains_module(const char *file_path, const char *module_name) {
973 if (file_path == NULL || module_name == NULL || module_name[0] == '\0') {
974 return false;
975 }
976
977 const size_t module_len = strlen(module_name);
978 const char *cursor = file_path;
979 while ((cursor = strstr(cursor, module_name)) != NULL) {
980 bool left_ok = (cursor == file_path);
981 if (!left_ok) {
982 const char prev = cursor[-1];
983 left_ok = (prev == PATH_DELIM);
984 }
985
986 const char tail = cursor[module_len];
987 bool right_ok = (tail == '\0' || tail == PATH_DELIM);
988
989 if (left_ok && right_ok) {
990 return true;
991 }
992
993 cursor = cursor + 1;
994 }
995
996 return false;
997}
998
999static bool asciichat_instr_only_selectors_match(const asciichat_instr_runtime_t *runtime, const char *file_path, const char *function_name) {
1000 const asciichat_instr_only_list_t *list = &runtime->only_selectors;
1001 if (list->count == 0) {
1002 return true;
1003 }
1004
1005 const char *base_name = asciichat_instr_basename(file_path);
1006 for (size_t i = 0; i < list->count; ++i) {
1007 const asciichat_instr_only_selector_t *selector = &list->items[i];
1008 switch (selector->type) {
1010 if (file_path != NULL && selector->pattern != NULL && strstr(file_path, selector->pattern) != NULL) {
1011 return true;
1012 }
1013 break;
1015 if (file_path != NULL && selector->pattern != NULL && asciichat_instr_match_glob(selector->pattern, file_path)) {
1016 return true;
1017 }
1018 break;
1020 if (function_name != NULL && selector->pattern != NULL && asciichat_instr_match_glob(selector->pattern, function_name)) {
1021 return true;
1022 }
1023 break;
1025 if (file_path != NULL && selector->module != NULL && asciichat_instr_path_contains_module(file_path, selector->module)) {
1026 if (selector->pattern == NULL || (base_name != NULL && asciichat_instr_match_glob(selector->pattern, base_name))) {
1027 return true;
1028 }
1029 }
1030 break;
1031 default:
1032 break;
1033 }
1034 }
1035
1036 return false;
1037}
1038
1039static bool asciichat_instr_should_log(const asciichat_instr_runtime_t *runtime, const char *file_path, uint32_t line_number, const char *function_name) {
1040 if (!runtime->filters_enabled) {
1041 return true;
1042 }
1043
1044 if (runtime->filter_thread != NULL) {
1046 safe_snprintf(tid_buf, sizeof(tid_buf), "%llu", (unsigned long long)runtime->thread_id);
1047 if (strstr(runtime->filter_thread, tid_buf) == NULL) {
1048 return false;
1049 }
1050 }
1051
1052 if (runtime->filter_include != NULL) {
1053 if (file_path == NULL || strstr(file_path, runtime->filter_include) == NULL) {
1054 return false;
1055 }
1056 }
1057
1058 if (runtime->filter_exclude != NULL && file_path != NULL) {
1059 if (strstr(file_path, runtime->filter_exclude) != NULL) {
1060 return false;
1061 }
1062 }
1063
1064#if ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX
1065 if (runtime->include_regex_valid) {
1066 if (file_path == NULL || regexec(&runtime->include_regex, file_path, 0, NULL, 0) != 0) {
1067 return false;
1068 }
1069 }
1070
1071 if (runtime->exclude_regex_valid && file_path != NULL) {
1072 if (regexec(&runtime->exclude_regex, file_path, 0, NULL, 0) == 0) {
1073 return false;
1074 }
1075 }
1076#endif
1077
1078 if (runtime->filter_function_include != NULL) {
1079 if (function_name == NULL || strstr(function_name, runtime->filter_function_include) == NULL) {
1080 return false;
1081 }
1082 }
1083
1084 if (runtime->filter_function_exclude != NULL && function_name != NULL) {
1085 if (strstr(function_name, runtime->filter_function_exclude) != NULL) {
1086 return false;
1087 }
1088 }
1089
1090#if ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX
1091 if (runtime->function_include_regex_valid) {
1092 if (function_name == NULL || regexec(&runtime->function_include_regex, function_name, 0, NULL, 0) != 0) {
1093 return false;
1094 }
1095 }
1096
1097 if (runtime->function_exclude_regex_valid && function_name != NULL) {
1098 if (regexec(&runtime->function_exclude_regex, function_name, 0, NULL, 0) == 0) {
1099 return false;
1100 }
1101 }
1102#endif
1103
1104 if (runtime->only_selectors.count > 0) {
1105 if (!asciichat_instr_only_selectors_match(runtime, file_path, function_name)) {
1106 return false;
1107 }
1108 }
1109
1110 (void)line_number;
1111 return true;
1112}
1113
1114static int asciichat_instr_write_full(int fd, const char *buffer, size_t len) {
1115 size_t total = 0;
1116 while (total < len) {
1117 ssize_t written = platform_write(fd, buffer + total, len - total);
1118 if (written < 0) {
1119 if (errno == EINTR) {
1120 continue;
1121 }
1122 return -1;
1123 }
1124 total += (size_t)written;
1125 }
1126 return 0;
1127}
Platform initialization and static synchronization helpers.
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
int platform_close(int fd)
Definition filesystem.c:91
#define SAFE_REALLOC(ptr, size, cast)
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_GETENV(name)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define SAFE_STRDUP(dst, src)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define NS_PER_SEC_INT
Definition time.h:173
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:368
#define TIME_DURATION_BUFFER_SIZE
Definition time.h:40
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117
void asciichat_instr_runtime_global_destroy(void)
Global shutdown of the instrumentation system.
bool asciichat_instr_coverage_enabled(void)
Check if coverage logging is enabled.
void asciichat_instr_runtime_destroy(asciichat_instr_runtime_t *runtime)
Destroy a runtime context and release resources.
struct asciichat_instr_runtime asciichat_instr_runtime_t
Per-thread instrumentation runtime state.
void asciichat_instr_log_line(const char *file_path, uint32_t line_number, const char *function_name, const char *snippet, uint8_t is_macro_expansion)
Log a source line execution event.
void asciichat_instr_log_pc(uintptr_t program_counter)
Log a program counter for coverage analysis.
asciichat_instr_runtime_t * asciichat_instr_runtime_get(void)
Get or create the thread-local runtime context.
@ ASCII_INSTR_SOURCE_PRINT_MACRO_NONE
#define STR_ZERO
String literal: "0" (zero).
#define STR_FALSE
String literal: "false".
#define STR_NO
String literal: "no".
#define STR_OFF
String literal: "off".
bool path_is_absolute(const char *path)
Determine whether a path is absolute on the current platform.
Definition path.c:422
asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out)
Validate and canonicalize a user-supplied filesystem path.
Definition path.c:705
char * expand_path(const char *path)
Expand path with tilde (~) support.
Definition path.c:257
@ PATH_ROLE_LOG_FILE
Definition path.h:324
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define TOOLING_PANIC_INSTRUMENT_LOG_TID_BUFFER_SIZE
asciichat_instr_selector_type
@ ASCII_INSTR_SOURCE_PRINT_SELECTOR_FUNCTION_GLOB
@ ASCII_INSTR_SOURCE_PRINT_SELECTOR_FILE_GLOB
@ ASCII_INSTR_SOURCE_PRINT_SELECTOR_FILE_SUBSTRING
@ ASCII_INSTR_SOURCE_PRINT_SELECTOR_MODULE
#define posix_write
#define INSTRUMENT_LOG_KEY_BUFFER_SIZE
#define TOOLING_PANIC_INSTRUMENT_LOG_TIMESTAMP_BUFFER_SIZE
#define ASCII_INSTR_SOURCE_PRINT_MAX_SNIPPET
struct asciichat_instr_only_selector asciichat_instr_only_selector_t
Selector for filtering instrumentation output by file, function, or module.
#define ASCII_INSTR_SOURCE_PRINT_MAX_LINE
#define ASCII_INSTR_SOURCE_PRINT_DEFAULT_BASENAME
enum asciichat_instr_selector_type asciichat_instr_selector_type_t
struct asciichat_instr_only_list asciichat_instr_only_list_t
Dynamic array of instrumentation selectors for filtering output.
#define ASCII_INSTR_SOURCE_PRINT_HAVE_REGEX
#define TOOLING_PANIC_INSTRUMENT_LOG_SNIPPET_BUFFER_SIZE
🔍 Debug instrumentation logging runtime for ascii-chat line tracing
Capture stdout/stderr and redirect to logging system.
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:42
📂 Path Manipulation Utilities
PCRE2-based regex patterns for cryptographic parsing.
char * platform_strdup(const char *s)
🔤 String Manipulation and Shell Escaping Utilities
Dynamic array of instrumentation selectors for filtering output.
asciichat_instr_only_selector_t * items
Array of selectors.
size_t capacity
Allocated capacity.
size_t count
Number of active selectors.
Selector for filtering instrumentation output by file, function, or module.
asciichat_instr_selector_type_t type
Type of selector (file substring, glob, function glob, or module).
char * module
Module name for module-based filtering.
char * pattern
Pattern to match (file/function glob pattern).
Per-thread instrumentation runtime state.
const char * filter_exclude
File path substring to exclude (from env var).
bool function_exclude_regex_valid
Whether function_exclude_regex was successfully compiled.
asciichat_instr_only_list_t only_selectors
List of "only" selectors for filtering.
const char * filter_include
File path substring to include (from env var).
uint64_t call_counter
Total number of instrumentation calls.
char log_path[PATH_MAX]
Path to log file.
bool rate_enabled
Whether rate limiting is enabled.
regex_t function_exclude_regex
Compiled regex for function name exclusion.
uint64_t sequence
Sequence number for log entries.
regex_t exclude_regex
Compiled regex for file path exclusion.
bool function_include_regex_valid
Whether function_include_regex was successfully compiled.
uint32_t rate
Rate limiting: log every Nth call.
const char * filter_function_exclude
Function name substring to exclude (from env var).
const char * filter_function_include
Function name substring to include (from env var).
regex_t include_regex
Compiled regex for file path inclusion.
int fd
Log file descriptor (-1 if not open).
uint64_t thread_id
Thread ID.
regex_t function_include_regex
Compiled regex for function name inclusion.
const char * filter_thread
Thread ID filter (from env var).
bool stderr_fallback
Use stderr if log file can't be opened.
bool exclude_regex_valid
Whether exclude_regex was successfully compiled.
bool filters_enabled
Whether any filters are active.
bool include_regex_valid
Whether include_regex was successfully compiled.
pid_t platform_get_pid(void)
Definition system.c:67
ssize_t platform_write(int fd, const void *buf, size_t count)
Definition system.c:78
⏱️ High-precision timing utilities using sokol_time.h and uthash
bool platform_get_cwd(char *cwd, size_t path_size)
Definition util.c:122