ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
report.c
Go to the documentation of this file.
1
10
11// SPDX-License-Identifier: MIT
12// Summarizer for ascii-chat instrumentation runtime logs
13
14/* Storage capacities in elements; text buffers include the terminating NUL. */
15#define TOOLING_PANIC_REPORT_BUFFER_BUFFER_SIZE 8192
16
17#include <ascii-chat/common.h>
18#include <libplatform/filesystem.h>
19#include <ascii-chat/log/log.h>
21
22#include <ascii-chat/uthash.h>
24
25#include <errno.h>
26#include <inttypes.h>
27#include <limits.h>
28#include <stdbool.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32
33#include <unistd.h>
34#ifdef _WIN32
35#include <libplatform/windows/getopt.h>
36#else
37#include <getopt.h>
38#endif
39
52
65
87
99
100static const char *macro_flag_label(uint32_t flag) {
101 switch (flag) {
103 return "expansion";
105 return "invocation";
107 default:
108 return "none";
109 }
110}
111
112static void thread_filter_list_destroy(thread_filter_list_t *list) {
113 if (list == NULL) {
114 return;
115 }
116 SAFE_FREE(list->values);
117 list->values = NULL;
118 list->count = 0;
119 list->capacity = 0;
120}
121
122static bool thread_filter_list_append(thread_filter_list_t *list, uint64_t value) {
123 if (list == NULL) {
124 return false;
125 }
126
127 if (list->count == list->capacity) {
128 size_t new_capacity = list->capacity == 0 ? 4 : list->capacity * 2;
129 uint64_t *new_values = SAFE_REALLOC(list->values, new_capacity * sizeof(uint64_t), uint64_t *);
130 if (new_values == NULL) {
131 return false;
132 }
133 list->values = new_values;
134 list->capacity = new_capacity;
135 }
136
137 list->values[list->count++] = value;
138 return true;
139}
140
141static bool thread_filter_list_contains(const thread_filter_list_t *list, uint64_t value) {
142 if (list == NULL || list->count == 0) {
143 return true;
144 }
145
146 for (size_t i = 0; i < list->count; ++i) {
147 if (list->values[i] == value) {
148 return true;
149 }
150 }
151 return false;
152}
153
154static const char *resolve_default_log_dir(void) {
155 const char *dir = SAFE_GETENV("ASCII_INSTR_SOURCE_PRINT_OUTPUT_DIR");
156 if (dir != NULL && dir[0] != '\0') {
157 return dir;
158 }
159 dir = SAFE_GETENV("TMPDIR");
160 if (dir != NULL && dir[0] != '\0') {
161 return dir;
162 }
163 dir = SAFE_GETENV("TEMP");
164 if (dir != NULL && dir[0] != '\0') {
165 return dir;
166 }
167 dir = SAFE_GETENV("TMP");
168 if (dir != NULL && dir[0] != '\0') {
169 return dir;
170 }
171 // Default to system temp directory
172 const char *tmp = SAFE_GETENV("TMPDIR");
173 if (!tmp)
174 tmp = SAFE_GETENV("TMP");
175 if (!tmp)
176 tmp = SAFE_GETENV("TEMP");
177#ifdef _WIN32
178 if (!tmp)
179 tmp = ".";
180#else
181 if (!tmp)
182 tmp = "/tmp";
183#endif
184 return tmp;
185}
186
187static void free_record(log_record_t *record) {
188 if (record == NULL) {
189 return;
190 }
191 SAFE_FREE(record->timestamp);
192 SAFE_FREE(record->elapsed);
193 SAFE_FREE(record->file);
194 SAFE_FREE(record->function);
195 SAFE_FREE(record->snippet);
196 SAFE_FREE(record->raw_line);
197 memset(record, 0, sizeof(*record));
198}
199
200static void destroy_entries(thread_entry_t **entries) {
201 thread_entry_t *current;
202 thread_entry_t *tmp;
203 HASH_ITER(hh, *entries, current, tmp) {
204 HASH_DEL(*entries, current);
205 free_record(&current->record);
206 SAFE_FREE(current);
207 }
208}
209
210static char *duplicate_segment(const char *begin, size_t length) {
211 char *copy = SAFE_MALLOC(length + 1, char *);
212 if (copy == NULL) {
213 return NULL;
214 }
215 memcpy(copy, begin, length);
216 copy[length] = '\0';
217 return copy;
218}
219
220static bool extract_token(const char *line, const char *key, char **out_value) {
221 const char *position = strstr(line, key);
222 if (position == NULL) {
223 return false;
224 }
225 position += strlen(key);
226 const char *end = strchr(position, ' ');
227 if (end == NULL) {
228 end = line + strlen(line);
229 }
230 size_t length = (size_t)(end - position);
231 *out_value = duplicate_segment(position, length);
232 return *out_value != NULL;
233}
234
235static bool extract_snippet(const char *line, char **out_value) {
236 const char *position = strstr(line, "snippet=");
237 if (position == NULL) {
238 return false;
239 }
240 position += strlen("snippet=");
241 size_t length = strlen(position);
242 while (length > 0 && (position[length - 1] == '\n' || position[length - 1] == '\r')) {
243 length--;
244 }
245 *out_value = duplicate_segment(position, length);
246 return *out_value != NULL;
247}
248
249static bool extract_uint64(const char *line, const char *key, uint64_t *out_value) {
250 char *token = NULL;
251 if (!extract_token(line, key, &token))
252 return false;
253 unsigned long long value = 0;
254 asciichat_error_t result = token[0] == '-' ? ERROR_INVALID_PARAM : parse_ulonglong(token, &value, 0, ULLONG_MAX);
255 SAFE_FREE(token);
256 if (result != ASCIICHAT_OK)
257 return false;
258 *out_value = (uint64_t)value;
259 return true;
260}
261
262static bool extract_uint32(const char *line, const char *key, uint32_t *out_value) {
263 uint64_t tmp_value = 0;
264 if (!extract_uint64(line, key, &tmp_value)) {
265 return false;
266 }
267 if (tmp_value > UINT32_MAX) {
268 return false;
269 }
270 *out_value = (uint32_t)tmp_value;
271 return true;
272}
273
274static bool parse_log_line(const char *line, log_record_t *record) {
275 if (!extract_uint64(line, "pid=", &record->pid)) {
276 return false;
277 }
278 if (!extract_uint64(line, "tid=", &record->tid)) {
279 return false;
280 }
281 if (!extract_uint64(line, "seq=", &record->seq)) {
282 return false;
283 }
284 if (!extract_token(line, "ts=", &record->timestamp)) {
285 return false;
286 }
287 if (!extract_token(line, "elapsed=", &record->elapsed)) {
288 return false;
289 }
290 if (!extract_token(line, "file=", &record->file)) {
291 return false;
292 }
293 if (!extract_uint32(line, "line=", &record->line)) {
294 return false;
295 }
296 if (!extract_token(line, "func=", &record->function)) {
297 return false;
298 }
299 if (!extract_uint32(line, "macro=", &record->macro_flag)) {
300 return false;
301 }
302 if (!extract_snippet(line, &record->snippet)) {
303 return false;
304 }
305
306 size_t len = strlen(line);
307 while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
308 len--;
309 }
310 record->raw_line = duplicate_segment(line, len);
311 return record->raw_line != NULL;
312}
313
314static bool record_matches_filters(const report_config_t *config, const log_record_t *record) {
315 if (config->include_filter != NULL && config->include_filter[0] != '\0') {
316 if (record->file == NULL || strstr(record->file, config->include_filter) == NULL) {
317 return false;
318 }
319 }
320
321 if (config->exclude_filter != NULL && config->exclude_filter[0] != '\0') {
322 if (record->file != NULL && strstr(record->file, config->exclude_filter) != NULL) {
323 return false;
324 }
325 }
326
327 if (!thread_filter_list_contains(&config->threads, record->tid)) {
328 return false;
329 }
330
331 return true;
332}
333
334static void update_entry(thread_entry_t **entries, const log_record_t *record) {
335 thread_entry_t *entry = NULL;
336 HASH_FIND(hh, *entries, &record->tid, sizeof(uint64_t), entry);
337 if (entry == NULL) {
338 entry = SAFE_CALLOC(1, sizeof(*entry), thread_entry_t *);
339 entry->thread_id = record->tid;
340 entry->record = *record;
341 HASH_ADD(hh, *entries, thread_id, sizeof(uint64_t), entry);
342 return;
343 }
344
345 if (record->seq >= entry->record.seq) {
346 free_record(&entry->record);
347 entry->record = *record;
348 } else {
349 free_record((log_record_t *)record);
350 }
351}
352
353static int compare_entries(const void *lhs, const void *rhs) {
354 const thread_entry_t *const *a = lhs;
355 const thread_entry_t *const *b = rhs;
356 if ((*a)->thread_id < (*b)->thread_id) {
357 return -1;
358 }
359 if ((*a)->thread_id > (*b)->thread_id) {
360 return 1;
361 }
362 return 0;
363}
364
365static void print_summary(const report_config_t *config, thread_entry_t **entries) {
366 size_t count = HASH_COUNT(*entries);
367 if (count == 0) {
368 printf("No instrumentation records matched the given filters.\n");
369 return;
370 }
371
372 thread_entry_t **sorted = SAFE_CALLOC(count, sizeof(*sorted), thread_entry_t **);
373 size_t index = 0;
374 thread_entry_t *entry = NULL;
375 thread_entry_t *tmp = NULL;
376 HASH_ITER(hh, *entries, entry, tmp) {
377 sorted[index++] = entry;
378 }
379
380 qsort(sorted, count, sizeof(*sorted), compare_entries);
381
382 printf("Latest instrumentation record per thread (%zu thread%s)\n", count, count == 1 ? "" : "s");
383 printf("======================================================================\n");
384 for (size_t i = 0; i < count; ++i) {
385 const log_record_t *record = &sorted[i]->record;
386 if (config->emit_raw_line) {
387 printf("%s\n", record->raw_line);
388 continue;
389 }
390
391 printf("tid=%" PRIu64 " seq=%" PRIu64 " pid=%" PRIu64 "\n", record->tid, record->seq, record->pid);
392 printf(" timestamp : %s\n", record->timestamp);
393 printf(" elapsed : %s\n", record->elapsed);
394 printf(" location : %s:%u\n", record->file != NULL ? record->file : "<unknown>", record->line);
395 printf(" function : %s\n", record->function != NULL ? record->function : "<unknown>");
396 printf(" macro : %s (%u)\n", macro_flag_label(record->macro_flag), record->macro_flag);
397 printf(" snippet : %s\n", record->snippet != NULL ? record->snippet : "<missing>");
398 printf("----------------------------------------------------------------------\n");
399 }
400
401 SAFE_FREE(sorted);
402}
403
404static void usage(FILE *stream, const char *program) {
405 fprintf(stream,
406 "Usage: %s [options]\n"
407 " --log-file <path> Single log file to analyze (e.g., trace.log)\n"
408 " --log-dir <path> Directory containing ascii-instr-*.log files (default: resolve from environment)\n"
409 " --thread <id> Limit to specific thread ID (repeatable)\n"
410 " --include <substr> Include records whose file path contains substring\n"
411 " --exclude <substr> Exclude records whose file path contains substring\n"
412 " --raw Emit raw log lines instead of formatted summary\n"
413 " --help Show this help and exit\n",
414 program);
415}
416
417// Simple pre-scan for --log-file to avoid corrupted optarg from instrumented getopt
418// This is a workaround for stack corruption caused by panic instrumentation
419static const char *prescan_log_file(int argc, char **argv) {
420 for (int i = 1; i < argc; i++) {
421 if (strcmp(argv[i], "--log-file") == 0 && i + 1 < argc) {
422 return argv[i + 1];
423 }
424 // Handle --log-file=path format
425 if (strncmp(argv[i], "--log-file=", 11) == 0) {
426 return argv[i] + 11;
427 }
428 }
429 return NULL;
430}
431
432// Check if only --log-file is specified (to skip getopt entirely)
433static bool is_simple_log_file_invocation(int argc, char **argv) {
434 // Expected patterns: program --log-file path (argc=3) or program --log-file=path (argc=2)
435 if (argc == 3 && strcmp(argv[1], "--log-file") == 0) {
436 return true;
437 }
438 if (argc == 2 && strncmp(argv[1], "--log-file=", 11) == 0) {
439 return true;
440 }
441 return false;
442}
443
444static bool parse_arguments(int argc, char **argv, report_config_t *config) {
445 // Pre-scan for --log-file before getopt (workaround for instrumentation bug)
446 const char *log_file_arg = prescan_log_file(argc, argv);
447 if (log_file_arg != NULL) {
448 config->log_file = log_file_arg;
449 }
450
451 // If just --log-file with no other args, skip getopt entirely
452 // (instrumented getopt corrupts memory)
453 if (config->log_file != NULL && is_simple_log_file_invocation(argc, argv)) {
454 return true;
455 }
456
457 static const struct option kLongOptions[] = {
458 {"log-file", required_argument, NULL, 'f'}, {"log-dir", required_argument, NULL, 'd'}, {"thread", required_argument, NULL, 't'}, {"include", required_argument, NULL, 'i'},
459 {"exclude", required_argument, NULL, 'x'}, {"raw", no_argument, NULL, 'r'}, {"help", no_argument, NULL, 'h'}, {0, 0, 0, 0},
460 };
461
462 int option = 0;
463 while ((option = getopt_long(argc, argv, "", kLongOptions, NULL)) != -1) {
464 switch (option) {
465 case 'f':
466 // Already handled by prescan - skip (optarg may be corrupted)
467 break;
468 case 'd':
469 config->log_dir = optarg;
470 break;
471 case 't': {
472 unsigned long long tid_value = 0;
473 asciichat_error_t result = parse_ulonglong(optarg, &tid_value, 0, ULLONG_MAX);
474 if (result != ASCIICHAT_OK) {
475 log_error("Invalid thread id: %s", optarg);
476 return false;
477 }
478 if (!thread_filter_list_append(&config->threads, (uint64_t)tid_value)) {
479 log_error("Failed to record thread filter");
480 return false;
481 }
482 break;
483 }
484 case 'i':
485 config->include_filter = optarg;
486 break;
487 case 'x':
488 config->exclude_filter = optarg;
489 break;
490 case 'r':
491 config->emit_raw_line = true;
492 break;
493 case 'h':
494 config->help_requested = true;
495 usage(stdout, argv[0]);
496 return false;
497 default:
498 usage(stderr, argv[0]);
499 return false;
500 }
501 }
502
503 if (optind < argc) {
504 log_error("Unexpected positional argument: %s", argv[optind]);
505 usage(stderr, argv[0]);
506 return false;
507 }
508
509 // Validate --log-file and --log-dir are mutually exclusive
510 if (config->log_file != NULL && config->log_dir != NULL) {
511 log_error("Cannot specify both --log-file and --log-dir");
512 return false;
513 }
514
515 // Fall back to default log directory only if no log file specified
516 if (config->log_file == NULL && config->log_dir == NULL) {
517 config->log_dir = resolve_default_log_dir();
518 }
519
520 return true;
521}
522
523static bool process_file(const report_config_t *config, const char *path, thread_entry_t **entries) {
524 FILE *handle = platform_fopen("file_stream", path, "r");
525 if (handle == NULL) {
526 log_warn("Cannot open log file '%s': %s", path, SAFE_STRERROR(errno));
527 return false;
528 }
529
531 while (fgets(buffer, sizeof(buffer), handle) != NULL) {
532 log_record_t record = {0};
533 if (!parse_log_line(buffer, &record)) {
534 free_record(&record);
535 continue;
536 }
537 if (!record_matches_filters(config, &record)) {
538 free_record(&record);
539 continue;
540 }
541 update_entry(entries, &record);
542 }
543
544 fclose(handle);
545 return true;
546}
547
558
559static bool collect_entry_cb(const platform_dir_entry_t *entry, void *user_data) {
560 collect_ctx_t *ctx = (collect_ctx_t *)user_data;
561 if (entry->is_dir)
562 return true;
563
564 // Filter: must start with "ascii-instr-" and end with ".log"
565 if (strncmp(entry->name, "ascii-instr-", strlen("ascii-instr-")) != 0)
566 return true;
567 size_t name_len = strlen(entry->name);
568 if (name_len < 5 || strcmp(entry->name + name_len - 4, ".log") != 0)
569 return true;
570
571 char path_buffer[PLATFORM_MAX_PATH_LENGTH];
572 int written = safe_snprintf(path_buffer, sizeof(path_buffer), "%s/%s", ctx->config->log_dir, entry->name);
573 if (written < 0 || written >= (int)sizeof(path_buffer)) {
574 log_warn("Skipping path that exceeds buffer: %s/%s", ctx->config->log_dir, entry->name);
575 return true;
576 }
577
578 if (!process_file(ctx->config, path_buffer, ctx->entries)) {
579 ctx->success = false;
580 }
581 return true;
582}
583
584static bool collect_entries(const report_config_t *config, thread_entry_t **entries) {
585 // If a single log file is specified, just process that file
586 if (config->log_file != NULL) {
587 return process_file(config, config->log_file, entries);
588 }
589
590 collect_ctx_t ctx = {.config = config, .entries = entries, .success = true};
591 asciichat_error_t err = platform_dir_foreach(config->log_dir, collect_entry_cb, &ctx);
592 if (err != ASCIICHAT_OK) {
593 log_error("Unable to open instrumentation log directory '%s'", config->log_dir);
594 return false;
595 }
596 return ctx.success;
597}
598
599int main(int argc, char **argv) {
600 report_config_t config = {
601 .log_dir = NULL,
602 .log_file = NULL,
603 .include_filter = NULL,
604 .exclude_filter = NULL,
605 .threads = {.values = NULL, .count = 0, .capacity = 0},
606 .emit_raw_line = false,
607 };
608
609 log_init(NULL, LOG_INFO, false, false);
610
611 int exit_code = EXIT_SUCCESS;
612 if (!parse_arguments(argc, argv, &config)) {
613 exit_code = config.help_requested ? EXIT_SUCCESS : ERROR_USAGE;
614 goto cleanup;
615 }
616
617 thread_entry_t *entries = NULL;
618 if (!collect_entries(&config, &entries)) {
619 exit_code = ERROR_GENERAL;
620 destroy_entries(&entries);
621 goto cleanup;
622 }
623
624 print_summary(&config, &entries);
625 destroy_entries(&entries);
626
627cleanup:
628 thread_filter_list_destroy(&config.threads);
629 log_destroy();
630 return exit_code;
631}
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define SAFE_REALLOC(ptr, size, cast)
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_GETENV(name)
#define SAFE_STRERROR(errnum)
#define SAFE_CALLOC(count, size, cast)
#define PLATFORM_MAX_PATH_LENGTH
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_GENERAL
Definition error_codes.h:51
@ ERROR_USAGE
Definition error_codes.h:52
@ ERROR_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
void log_destroy(void)
Destroy the logging system and close log file.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
void log_init(const char *filename, log_level_t level, bool force_stderr, bool use_mmap)
Initialize the logging system.
void usage(FILE *desc, asciichat_mode_t mode)
Print usage information for a specific mode.
@ ASCII_INSTR_SOURCE_PRINT_MACRO_INVOCATION
@ ASCII_INSTR_SOURCE_PRINT_MACRO_EXPANSION
@ ASCII_INSTR_SOURCE_PRINT_MACRO_NONE
⚙️ Common definitions, error codes, macros, and types shared throughout the application
🔍 Debug instrumentation logging runtime for ascii-chat line tracing
📝 Logging API with multiple log levels and terminal output control
static bool size_t index
Definition queries.h:8
struct report_config report_config_t
Configuration for panic report generation.
struct thread_entry thread_entry_t
Hash table entry for thread-local last log record.
struct thread_filter_list thread_filter_list_t
Owned fields extracted from one instrumentation log line.
int main(int argc, char **argv)
Definition report.c:599
struct log_record log_record_t
Owned fields extracted from one instrumentation log line.
#define TOOLING_PANIC_REPORT_BUFFER_BUFFER_SIZE
Definition report.c:15
🔤 String Manipulation and Shell Escaping Utilities
const report_config_t * config
Definition report.c:549
thread_entry_t ** entries
Definition report.c:550
bool success
Definition report.c:551
Owned fields extracted from one instrumentation log line.
Definition report.c:74
uint64_t pid
Process ID.
Definition report.c:75
char * function
Function name.
Definition report.c:82
char * file
Source file path.
Definition report.c:80
char * snippet
Code snippet.
Definition report.c:84
uint32_t macro_flag
Macro expansion flag.
Definition report.c:83
uint32_t line
Source line number.
Definition report.c:81
char * elapsed
Elapsed time since start.
Definition report.c:79
char * raw_line
Original raw log line.
Definition report.c:85
uint64_t tid
Thread ID.
Definition report.c:76
char * timestamp
Timestamp string.
Definition report.c:78
uint64_t seq
Sequence number.
Definition report.c:77
Configuration for panic report generation.
Definition report.c:56
const char * exclude_filter
File path substring filter for exclusion.
Definition report.c:60
const char * log_file
Single log file path (alternative to log_dir).
Definition report.c:58
bool emit_raw_line
Whether to emit raw log lines in output.
Definition report.c:63
bool help_requested
Help was requested without a usage error.
Definition report.c:62
thread_filter_list_t threads
Thread IDs to include in report.
Definition report.c:61
const char * log_dir
Directory containing instrumentation log files.
Definition report.c:57
const char * include_filter
File path substring filter for inclusion.
Definition report.c:59
Hash table entry for thread-local last log record.
Definition report.c:94
uint64_t thread_id
Thread ID (hash key).
Definition report.c:95
log_record_t record
Last log record from this thread.
Definition report.c:96
UT_hash_handle hh
uthash handle
Definition report.c:97
Owned fields extracted from one instrumentation log line.
Definition report.c:47
uint64_t * values
Array of thread IDs.
Definition report.c:48
size_t count
Number of thread IDs.
Definition report.c:49
size_t capacity
Allocated capacity.
Definition report.c:50
#define LOG_INFO
Definition types.h:44
asciichat_error_t parse_ulonglong(const char *str, unsigned long long *out_value, unsigned long long min_value, unsigned long long max_value)
Parse unsigned long long integer with range validation.
🔍 Safe Parsing Utilities