ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Panic Instrumentation

🚨 Per-statement logging for crash debugging in C programs More...

Files

file  instrument_log.h
 🔍 Debug instrumentation logging runtime for ascii-chat line tracing

Macros

#define ASCII_INSTR_SOURCE_PRINT_SIGNAL_HANDLER
 Attribute to mark signal handler functions.

Typedefs

typedef struct asciichat_instr_runtime asciichat_instr_runtime_t
 Per-thread instrumentation runtime state.

Enumerations

enum  { ASCII_INSTR_SOURCE_PRINT_MACRO_NONE = 0u , ASCII_INSTR_SOURCE_PRINT_MACRO_EXPANSION = 1u , ASCII_INSTR_SOURCE_PRINT_MACRO_INVOCATION = 2u }
 Macro expansion indicator values for asciichat_instr_log_line(). More...

Functions

asciichat_instr_runtime_t * asciichat_instr_runtime_get (void)
 Get or create the thread-local runtime context.
void asciichat_instr_runtime_destroy (asciichat_instr_runtime_t *runtime)
 Destroy a runtime context and release resources.
void asciichat_instr_runtime_global_destroy (void)
 Global shutdown of the instrumentation system.
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.
bool asciichat_instr_coverage_enabled (void)
 Check if coverage logging is enabled.
void asciichat_instr_log_pc (uintptr_t program_counter)
 Log a program counter for coverage analysis.

Detailed Description

🚨 Per-statement logging for crash debugging in C programs

This module provides the runtime logging infrastructure for the source-print instrumentation system. When code is instrumented with ascii-instr-panic, calls to asciichat_instr_log_line() are inserted at each statement to trace execution flow.

Features

  • Per-Thread Logging: Each thread gets its own log file or runtime context
  • Configurable Filtering: Filter by file path, function name, thread ID, or using regex patterns
  • Rate Limiting: Sample every Nth log entry to reduce output volume
  • Coverage Mode: Log program counter addresses for coverage analysis
  • Environment Configuration: All settings controlled via environment variables

Environment Variables

  • ASCII_INSTR_SOURCE_PRINT_ENABLE: Enable/disable tracing (default: enabled)
  • ASCII_INSTR_SOURCE_PRINT_OUTPUT_DIR: Directory for log files
  • ASCII_INSTR_SOURCE_PRINT_INCLUDE: Substring filter for file paths (include)
  • ASCII_INSTR_SOURCE_PRINT_EXCLUDE: Substring filter for file paths (exclude)
  • ASCII_INSTR_SOURCE_PRINT_FUNCTION_INCLUDE: Substring filter for functions
  • ASCII_INSTR_SOURCE_PRINT_FUNCTION_EXCLUDE: Substring filter for functions
  • ASCII_INSTR_SOURCE_PRINT_THREAD: Filter by thread ID(s)
  • ASCII_INSTR_SOURCE_PRINT_RATE: Log every Nth entry (rate limiting)
  • ASCII_INSTR_SOURCE_PRINT_ONLY: Comma-separated selector filters
  • ASCII_INSTR_SOURCE_PRINT_ENABLE_COVERAGE: Enable PC logging for coverage

Regex variants (Unix only):

  • ASCII_INSTR_SOURCE_PRINT_INCLUDE_REGEX
  • ASCII_INSTR_SOURCE_PRINT_EXCLUDE_REGEX
  • ASCII_INSTR_SOURCE_PRINT_FUNCTION_INCLUDE_REGEX
  • ASCII_INSTR_SOURCE_PRINT_FUNCTION_EXCLUDE_REGEX
See also
docs/tooling/panic-instrumentation.md for full documentation

Panic Instrumentation

🚨 Overview

Panic instrumentation provides per-statement logging for debugging crashes in C programs. The core idea is simple: the last line printed before a crash is the crashing line (or the line immediately before it in most cases).

Implementation: src/tooling/panic/tool.cpp

Key Features:

  • Per-statement source code logging
  • Multi-threaded support with per-thread log files
  • Environment variable filtering (by file, function, thread, regex, glob patterns)
  • Signal-safe logging using atomic writes
  • Post-mortem analysis with ascii-panic-report tool
  • SanitizerCoverage integration for edge coverage

Background: The Core Idea

The Problem: C programs crash without error messages. When a segfault or other crash occurs, you get no information about which line of code caused it. Traditional debugging approaches have limitations:

  • Manual printf debugging: You have to guess where to add logs, and you might not even be in the right function yet. Hours can be wasted adding printf() calls to the wrong places.
  • Debuggers (gdb/lldb): Great for reproducible crashes, but timing-sensitive bugs (race conditions) may not reproduce under a debugger.
  • Sanitizers (ASan/UBSan): Excellent for memory bugs, but don't help with logic errors or silent hangs.

The Solution: What if we automatically insert a log before every line of code? When the program crashes, the last line printed tells you exactly where it crashed.

If your program crashes without logs:
??? → ??? → ??? → CRASH
With panic instrumentation:
log(line 10) → log(line 11) → log(line 12) → CRASH
↑
Last printed line = crash location!

Why This Works:

  1. We log BEFORE each statement executes
  2. The logging uses atomic writes (survives crashes)
  3. Whatever printed last was the last thing that ran
  4. Therefore, the crash is at or after that line

Why Hasn't This Been Done Before?

Tools like this exist in various forms (SanitizerCoverage, -finstrument-functions, dynamic binary instrumentation), but they typically:

  • Log addresses/PCs that need symbolization, not actual source text
  • Work at function granularity, not per-statement
  • Require post-processing to map back to source

This approach is deliberately simple: print the actual source code text, so the crash location is immediately readable. No symbolization, no post-processing.

Multi-Threaded Programs

With multiple threads, the "last printed line globally" might be from a different thread than the one that crashed. The solution:

  • Each thread writes to its own log file (ascii-instr-<pid>-<tid>.log)
  • Each log line includes the thread ID
  • Use ascii-panic-report to find the last line from each thread
  • Identify the crashing thread from the crash report, then check its log

When to Use

Use panic instrumentation when:

  • You have a crash that's difficult to reproduce
  • Traditional debuggers don't work (e.g., timing-sensitive bugs)
  • You need to know exactly which statement crashed
  • You're debugging multi-threaded code

How It Works

The panic instrumentation tool transforms your C source code to print each statement before executing it:

Original code: Instrumented code:
--------------- -------------------------------------------
int x = 5; log("lib/foo.c:10: int x = 5;");
int x = 5;
int y = x / 0; log("lib/foo.c:11: int y = x / 0;"); // Last printed!
int y = x / 0; // CRASH!
return y; log("lib/foo.c:12: return y;"); // Never reached
return y;

Single-Threaded Programs: The last log line is the crash location.

Multi-Threaded Programs: Each thread writes to its own log file (ascii-instr-<pid>-<tid>.log). Use ascii-panic-report to summarize the last statement executed by each thread.

Usage

Building with Panic Instrumentation

Panic instrumentation runs before the defer transformation. Both tools operate on generated copies; edit the original sources as usual.

# Build with panic instrumentation
cmake -B build -DASCIICHAT_BUILD_WITH_PANIC=ON
cmake --build build

Debugging Workflow

# 1. Build with panic instrumentation
cmake -B build -DASCIICHAT_BUILD_WITH_PANIC=ON
cmake --build build
# 2. Run the crashing program
export ASCII_PANIC_OUTPUT_DIR=/tmp/crash-logs
./build/bin/ascii-chat server
# ... program crashes ...
# 3. Find the crash location
# Single-threaded: just look at the last line
tail -n1 /tmp/crash-logs/ascii-instr-*.log
# Multi-threaded: use the report tool
./build/bin/ascii-panic-report --log-dir /tmp/crash-logs

The ascii-panic-report Tool

For multi-threaded programs, ascii-panic-report parses all log files and shows the last executed statement per thread:

# Build the report tool
cmake --build build --target ascii-panic-report
# Run it
./build/bin/ascii-panic-report --log-dir /tmp/crash-logs
# Output:
# Latest instrumentation record per thread (3 threads)
# ======================================================================
# tid=1234 seq=42891 pid=5678
# timestamp : 2025-11-07T18:32:01.123456789Z
# elapsed : 12.3ms
# location : lib/network.c:512
# function : socket_send
# macro : none (0)
# snippet : send_packet(queue, payload)
# ----------------------------------------------------------------------
# tid=1235 seq=8901 pid=5678
# location : lib/mixer.c:234
# function : mix_audio_frames
# snippet : buffer[i] = left + right

Report Tool Options

# Filter to specific thread
./build/bin/ascii-panic-report --thread 1234
# Filter by file path
./build/bin/ascii-panic-report --include network.c
# Exclude files
./build/bin/ascii-panic-report --exclude video
# Show raw log lines
./build/bin/ascii-panic-report --raw

Log Record Format

Each log line contains:

pid=12345 tid=678 seq=42 ts=2025-11-07T18:32:01.123456789Z elapsed=12.3ms file=lib/network.c line=512 func=socket_send macro=0 snippet=send_packet(queue, payload)
  • pid: Process ID
  • tid: Thread ID
  • seq: Sequence number for this thread
  • ts: Timestamp (ISO 8601 format)
  • elapsed: Time since runtime initialization
  • file: Source file path
  • line: Line number
  • func: Function name
  • macro: Macro flag (0=normal, 1=from macro expansion, 2=macro invocation)
  • snippet: The source code being executed

Environment Variable Filtering

Reduce log volume by filtering what gets logged. Filters are checked before formatting to minimize overhead.

Basic Filters

Variable Purpose
ASCII_INSTR_SOURCE_PRINT_INCLUDE Only log files matching substring
ASCII_INSTR_SOURCE_PRINT_EXCLUDE Skip files matching substring
ASCII_INSTR_SOURCE_PRINT_THREAD Comma-separated thread IDs to log
ASCII_INSTR_SOURCE_PRINT_FUNCTION_INCLUDE Only log functions matching substring
ASCII_INSTR_SOURCE_PRINT_FUNCTION_EXCLUDE Skip functions matching substring
ASCII_INSTR_SOURCE_PRINT_OUTPUT_DIR Directory for log files
ASCII_INSTR_SOURCE_PRINT_RATE Log every Nth statement (throttle)
ASCII_INSTR_SOURCE_PRINT_ENABLE Set to "0" to disable at runtime

Regex Filters (POSIX platforms only)

Variable Purpose
ASCII_INSTR_SOURCE_PRINT_INCLUDE_REGEX POSIX regex include filter on file path
ASCII_INSTR_SOURCE_PRINT_EXCLUDE_REGEX POSIX regex exclude filter on file path
ASCII_INSTR_SOURCE_PRINT_FUNCTION_INCLUDE_REGEX POSIX regex include filter on function name
ASCII_INSTR_SOURCE_PRINT_FUNCTION_EXCLUDE_REGEX POSIX regex exclude filter on function name

ONLY Selectors (Advanced)

The ASCII_INSTR_SOURCE_PRINT_ONLY variable supports sophisticated allow-list filtering using comma-separated selectors:

Syntax Description
file=<glob> Match files by glob pattern
func=<glob> Match functions by glob pattern
module=<name> Match files under /name/ directory
module=<name>:<glob> Match files under /name/ with basename matching glob
<name>:<glob> Shorthand for module=<name>:<glob>
<substring> Match files containing substring

Examples:

# Only log network-related files
export ASCII_INSTR_SOURCE_PRINT_INCLUDE=network.c
# Skip video processing (too noisy)
export ASCII_INSTR_SOURCE_PRINT_EXCLUDE=video
# Only log specific threads
export ASCII_INSTR_SOURCE_PRINT_THREAD=1234,5678
# Log every 100th statement (reduce volume)
export ASCII_INSTR_SOURCE_PRINT_RATE=100
# Custom output directory
export ASCII_INSTR_SOURCE_PRINT_OUTPUT_DIR=/tmp/crash-logs
# Advanced: Only log server render code
export ASCII_INSTR_SOURCE_PRINT_ONLY="server:render_*"
# Advanced: Multiple selectors
export ASCII_INSTR_SOURCE_PRINT_ONLY="file=lib/network/*,func=socket_*"
# Advanced: Module with glob pattern
export ASCII_INSTR_SOURCE_PRINT_ONLY="module=crypto:handshake*"
# Disable instrumentation at runtime (binary still instrumented)
export ASCII_INSTR_SOURCE_PRINT_ENABLE=0

Custom Log File

For debugging specific issues, you can direct all output to a single file:

# Write to a specific file (allows appending across runs)
export ASCII_CHAT_DEBUG_SELF_SOURCE_CODE_LOG_FILE=/tmp/trace.log
# Also echo to stderr for live viewing
export ASCII_CHAT_DEBUG_SELF_SOURCE_CODE_LOG_STDERR=1

Signal Handler Annotations

Mark functions that must remain async-signal-safe:

ASCII_PANIC_SIGNAL_HANDLER
void handle_sigint(int signum) {
// ... signal handler code ...
}

The panic instrumentation tool skips any function carrying that annotation, ensuring inserted logging calls never appear inside signal handlers.

Safety Guarantees

  • Original sources remain untouched: The tool writes only to new files under build/instrumented/
  • Atomic writes: Each log line is emitted with a single write() call, so concurrent threads cannot interleave records
  • Signal tolerance: Once initialized, the runtime avoids non-signal-safe functions inside the hot path
  • Thread isolation: Separate files per thread prevent interleaving

Limitations and Best Practices

  • Performance cost: Logging every statement carries significant overhead. Use filters to narrow the scope when possible.
  • Timing changes: Heavy I/O can mask race conditions (Heisenbugs). After localizing the failure, confirm with sanitizers or record/replay tools.
  • Binary size: Expect larger binaries because every statement introduces a logging call and associated string literal.
  • Thread IDs differ by platform: Always copy the numeric ID from log headers when using ASCII_PANIC_THREAD.

Build System Details

File Locations

CMake Options

Option Default Description
ASCIICHAT_BUILD_WITH_PANIC OFF Enable panic instrumentation
ASCIICHAT_PANIC_TOOL "" Path to pre-built tool (faster rebuilds)

SanitizerCoverage Mode

For lightweight edge coverage without full statement logging:

# Build with coverage instrumentation
cmake -B build -DCMAKE_C_FLAGS="-fsanitize-coverage=trace-pc-guard"
# Enable coverage logging at runtime
export ASCII_INSTR_SOURCE_PRINT_ENABLE_COVERAGE=1
./build/bin/ascii-chat server

Coverage mode logs compact pc=0x... entries that can be symbolized with llvm-symbolizer or addr2line to map back to source locations.

Tool Command-Line Options

The ascii-instr-panic tool supports:

Option Description
--output-dir <path> Where to write instrumented sources
--input-root <path> Root for computing relative paths
--log-macro-expansions Instrument statements from macro expansions
--log-macro-invocations Emit synthetic log for macro call sites
--filter-file <substring> Only instrument files matching substring
--filter-function <substring> Only instrument functions matching substring
--signal-handler-annotation <name> Annotation to skip (default: ASCII_INSTR_PANIC_SIGNAL_HANDLER)

Troubleshooting

No logs emitted:

  • Check the output directory exists and is writable
  • Verify filters aren't over-restrictive (unset ASCII_INSTR_SOURCE_PRINT_INCLUDE)
  • Check ASCII_INSTR_SOURCE_PRINT_ENABLE isn't set to "0"

"Refusing to overwrite" errors:

  • Remove existing build/instrumented/ directory
  • Or specify a fresh output directory

Partial log files:

  • Ensure disk isn't full
  • Check runtime didn't hit a fatal error before logging

Thread IDs don't match:

  • Thread IDs are platform-specific (pthread vs system TID)
  • Always copy the exact numeric ID from log headers

Related Tools and Alternatives

Tool Approach Pros Cons
Panic instrumentation Source rewriting Readable output, no symbolization High overhead
SanitizerCoverage Edge callbacks Lower overhead Needs symbolization
-finstrument-functions Function entry/exit Very low overhead Function granularity only
rr (record/replay) Deterministic replay Perfect reproduction Linux only, heavyweight
ASan/UBSan Memory/UB detection Catches specific bugs Not for all crash types
gdb/lldb Debugger Full control May perturb timing

Panic instrumentation is best when you need:

  • Immediate, readable crash location without post-processing
  • To debug timing-sensitive code that doesn't reproduce under debuggers
  • Per-statement granularity for complex control flow

References

Macro Definition Documentation

◆ ASCII_INSTR_SOURCE_PRINT_SIGNAL_HANDLER

#define ASCII_INSTR_SOURCE_PRINT_SIGNAL_HANDLER

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Attribute to mark signal handler functions.

Functions marked with this attribute are recognized by the instrumentation tool and may receive special handling to avoid signal-unsafe operations.

Definition at line 76 of file instrument_log.h.

Typedef Documentation

◆ asciichat_instr_runtime_t

#include <lib/tooling/panic/instrument_log.c>

Per-thread instrumentation runtime state.

Opaque runtime context for instrumentation logging.

Tracks state for source code instrumentation logging, including file descriptors, filter configuration, and rate limiting for the current thread.

Each thread has its own runtime context that tracks:

  • File descriptor for the log file
  • Sequence numbers and call counters
  • Filter configuration (compiled regexes, substring patterns)
  • Rate limiting state

Enumeration Type Documentation

◆ anonymous enum

anonymous enum

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Macro expansion indicator values for asciichat_instr_log_line().

These values indicate whether a logged line originates from a macro expansion, the macro invocation site, or regular code.

Enumerator
ASCII_INSTR_SOURCE_PRINT_MACRO_NONE 

Regular code, not from a macro

ASCII_INSTR_SOURCE_PRINT_MACRO_EXPANSION 

Inside macro expansion

ASCII_INSTR_SOURCE_PRINT_MACRO_INVOCATION 

At macro invocation site

Definition at line 61 of file instrument_log.h.

61 {
65};
@ ASCII_INSTR_SOURCE_PRINT_MACRO_INVOCATION
@ ASCII_INSTR_SOURCE_PRINT_MACRO_EXPANSION
@ ASCII_INSTR_SOURCE_PRINT_MACRO_NONE

Function Documentation

◆ asciichat_instr_coverage_enabled()

bool asciichat_instr_coverage_enabled ( void )

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Check if coverage logging is enabled.

Coverage mode logs program counter addresses instead of full source info, useful for generating coverage reports with lower overhead.

Returns
true if ASCII_INSTR_SOURCE_PRINT_ENABLE_COVERAGE is set

Definition at line 440 of file instrument_log.c.

440 {
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}

Referenced by asciichat_instr_log_pc().

◆ asciichat_instr_log_line()

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 )

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Log a source line execution event.

Called by instrumented code at each statement to record execution trace. The log entry includes timestamp, thread ID, sequence number, file location, function name, and source code snippet.

Parameters
file_pathSource file path (typically from FILE)
line_numberLine number in the source file
function_nameName of the containing function
snippetSource code snippet for this line
is_macro_expansionOne of ASCII_INSTR_SOURCE_PRINT_MACRO_* values
Note
Filters are applied before logging; entry may be skipped
Thread-safe: uses per-thread runtime context
Reentrant-safe: nested calls are detected and skipped

Definition at line 293 of file instrument_log.c.

293 {
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}
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_GETENV(name)
unsigned long long uint64_t
@ ASCIICHAT_OK
Definition error_codes.h:50
#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
struct asciichat_instr_runtime asciichat_instr_runtime_t
Per-thread instrumentation runtime state.
asciichat_instr_runtime_t * asciichat_instr_runtime_get(void)
Get or create the thread-local runtime context.
#define posix_write
#define TOOLING_PANIC_INSTRUMENT_LOG_TIMESTAMP_BUFFER_SIZE
#define ASCII_INSTR_SOURCE_PRINT_MAX_SNIPPET
#define ASCII_INSTR_SOURCE_PRINT_MAX_LINE
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:42
uint64_t call_counter
Total number of instrumentation calls.
bool rate_enabled
Whether rate limiting is enabled.
uint64_t sequence
Sequence number for log entries.
uint32_t rate
Rate limiting: log every Nth call.
int fd
Log file descriptor (-1 if not open).
uint64_t thread_id
Thread ID.
bool stderr_fallback
Use stderr if log file can't be opened.

References ASCII_INSTR_SOURCE_PRINT_MAX_LINE, ASCII_INSTR_SOURCE_PRINT_MAX_SNIPPET, asciichat_instr_runtime_get(), ASCIICHAT_OK, asciichat_instr_runtime::call_counter, asciichat_instr_runtime::fd, file_path, NS_PER_SEC_INT, asciichat_instr_runtime::pid, posix_write, asciichat_instr_runtime::rate, asciichat_instr_runtime::rate_enabled, SAFE_GETENV, SAFE_STRNCPY, asciichat_instr_runtime::sequence, asciichat_instr_runtime::stderr_fallback, asciichat_instr_runtime::thread_id, TIME_DURATION_BUFFER_SIZE, time_elapsed_ns(), time_pretty(), and TOOLING_PANIC_INSTRUMENT_LOG_TIMESTAMP_BUFFER_SIZE.

Referenced by asciichat_instr_log_pc().

◆ asciichat_instr_log_pc()

void asciichat_instr_log_pc ( uintptr_t program_counter)

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Log a program counter for coverage analysis.

Records just the PC address with minimal metadata, intended for post-processing into coverage reports.

Parameters
program_counterThe instruction address to log
Note
Only logs if coverage mode is enabled

Definition at line 456 of file instrument_log.c.

456 {
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}
bool asciichat_instr_coverage_enabled(void)
Check if coverage logging is enabled.
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.
#define TOOLING_PANIC_INSTRUMENT_LOG_SNIPPET_BUFFER_SIZE

References ASCII_INSTR_SOURCE_PRINT_MACRO_NONE, asciichat_instr_coverage_enabled(), asciichat_instr_log_line(), and TOOLING_PANIC_INSTRUMENT_LOG_SNIPPET_BUFFER_SIZE.

Referenced by __sanitizer_cov_trace_pc_guard().

◆ asciichat_instr_runtime_destroy()

void asciichat_instr_runtime_destroy ( asciichat_instr_runtime_t * runtime)

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Destroy a runtime context and release resources.

Closes the log file descriptor, frees compiled regexes, and deallocates the runtime structure. Called automatically by TLS destructor on thread exit.

Parameters
runtimeContext to destroy (safe to pass NULL)

Definition at line 235 of file instrument_log.c.

235 {
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}
int platform_close(int fd)
Definition filesystem.c:91
#define SAFE_FREE(ptr)
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.
regex_t function_exclude_regex
Compiled regex for function name exclusion.
regex_t exclude_regex
Compiled regex for file path exclusion.
bool function_include_regex_valid
Whether function_include_regex was successfully compiled.
regex_t include_regex
Compiled regex for file path inclusion.
regex_t function_include_regex
Compiled regex for function name inclusion.
bool exclude_regex_valid
Whether exclude_regex was successfully compiled.
bool include_regex_valid
Whether include_regex was successfully compiled.

References asciichat_instr_runtime::exclude_regex, asciichat_instr_runtime::exclude_regex_valid, asciichat_instr_runtime::fd, asciichat_instr_runtime::function_exclude_regex, asciichat_instr_runtime::function_exclude_regex_valid, asciichat_instr_runtime::function_include_regex, asciichat_instr_runtime::function_include_regex_valid, asciichat_instr_runtime::include_regex, asciichat_instr_runtime::include_regex_valid, asciichat_instr_runtime::only_selectors, platform_close(), and SAFE_FREE.

Referenced by asciichat_instr_runtime_global_destroy().

◆ asciichat_instr_runtime_get()

asciichat_instr_runtime_t * asciichat_instr_runtime_get ( void )

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Get or create the thread-local runtime context.

Returns the instrumentation runtime for the current thread, creating one if it doesn't exist. The runtime is stored in thread-local storage and cleaned up automatically when the thread exits.

Returns
Runtime context, or NULL if disabled or initialization fails
Note
Thread-safe: each thread gets its own context
Returns NULL if ASCII_INSTR_SOURCE_PRINT_ENABLE=0

Definition at line 188 of file instrument_log.c.

188 {
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}
#define SAFE_CALLOC(count, size, cast)
const char * filter_exclude
File path substring to exclude (from env var).
const char * filter_include
File path substring to include (from env var).
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).
const char * filter_thread
Thread ID filter (from env var).
bool filters_enabled
Whether any filters are active.
pid_t platform_get_pid(void)
Definition system.c:67

References asciichat_instr_runtime::call_counter, asciichat_instr_runtime::fd, asciichat_instr_runtime::filter_exclude, asciichat_instr_runtime::filter_function_exclude, asciichat_instr_runtime::filter_function_include, asciichat_instr_runtime::filter_include, asciichat_instr_runtime::filter_thread, asciichat_instr_runtime::filters_enabled, asciichat_instr_runtime::pid, platform_get_pid(), asciichat_instr_runtime::rate, asciichat_instr_runtime::rate_enabled, SAFE_CALLOC, SAFE_FREE, SAFE_GETENV, asciichat_instr_runtime::sequence, and asciichat_instr_runtime::thread_id.

Referenced by asciichat_instr_log_line().

◆ asciichat_instr_runtime_global_destroy()

void asciichat_instr_runtime_global_destroy ( void )

#include <include/ascii-chat/tooling/panic/instrument_log.h>

Global shutdown of the instrumentation system.

Disables all logging, cleans up the TLS key, and resets global state. Should be called at program exit to ensure clean shutdown.

Note
After calling this, logging can be re-enabled by resetting env vars
Thread-safe: acquires global mutex during shutdown

Definition at line 268 of file instrument_log.c.

268 {
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}
void asciichat_instr_runtime_destroy(asciichat_instr_runtime_t *runtime)
Destroy a runtime context and release resources.

References asciichat_instr_runtime_destroy().