ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
mmap.c
Go to the documentation of this file.
1
9
10/* Storage capacities in elements; text buffers include the terminating NUL. */
11#define LOG_MMAP_DIAGNOSTIC_BUFFER_SIZE 64
12
13#include <ascii-chat/log/mmap.h>
14#include <ascii-chat/log/log.h>
15#include <libplatform/mmap.h>
16#include <libplatform/system.h>
19
20#include <stdarg.h>
21#include <stdio.h>
22#include <string.h>
23#include <time.h>
24#include <signal.h>
25
26#ifdef _WIN32
27#include <windows.h>
28#else
29#include <unistd.h>
30#endif
31
32/* ============================================================================
33 * Global State
34 * ============================================================================ */
35
36static struct {
37 platform_mmap_t mmap; /* Memory-mapped file handle */
38 char *text_region; /* Pointer to text area (entire file is text) */
39 size_t text_capacity; /* Total file size */
40 atomic_t write_pos; /* Current write position (in memory only) */
41 bool initialized; /* Initialization flag */
42 char file_path[PLATFORM_MAX_PATH_LENGTH]; /* Path to log file for truncation */
43
44 /* Statistics */
47} g_mmap_log = {
48 .initialized = false,
49 .file_path = {0},
50};
51
52/* ============================================================================
53 * Time Utilities
54 * ============================================================================ */
55
56static void format_timestamp(char *buf, size_t buf_size) {
57 uint64_t current_time_ns = time_get_realtime_ns();
58 time_t seconds = (time_t)(current_time_ns / NS_PER_SEC_INT);
59 uint64_t microseconds = time_ns_to_us(current_time_ns % NS_PER_SEC_INT);
60
61 struct tm tm_info;
62 platform_localtime(&seconds, &tm_info);
63
64 size_t len = strftime(buf, buf_size, "%H:%M:%S", &tm_info);
65 if (len > 0 && len < buf_size - 10) {
66 safe_snprintf(buf + len, buf_size - len, ".%06llu", (unsigned long long)microseconds);
67 }
68}
69
70/* ============================================================================
71 * Signal Handlers for Crash Safety
72 * ============================================================================ */
73
74static volatile sig_atomic_t g_crash_in_progress = {0};
75
76#ifndef _WIN32
77static void crash_signal_handler(int sig) {
78 /* Prevent recursive crashes */
79 if (g_crash_in_progress) {
80 _exit(128 + sig);
81 }
82 g_crash_in_progress = 1;
83
84 /* Write crash marker directly to mmap'd log */
85 if (g_mmap_log.initialized && g_mmap_log.text_region) {
86 const char *crash_msg = "\n=== CRASH DETECTED (signal %d) ===\n";
88 int len = safe_snprintf(msg_buf, sizeof(msg_buf), crash_msg, sig);
89 if (len > 0) {
90 uint64_t pos = atomic_fetch_add_u64(&g_mmap_log.write_pos, (uint64_t)len);
91 if (pos + (uint64_t)len <= g_mmap_log.text_capacity) {
92 memcpy(g_mmap_log.text_region + pos, msg_buf, (size_t)len);
93 }
94 }
95 }
96
97 /* Sync mmap to disk */
98 if (g_mmap_log.initialized) {
99 platform_mmap_sync(&g_mmap_log.mmap, true); /* sync = true for immediate flush */
100 }
101
102 /* Re-raise with default handler for core dump */
103 signal(sig, SIG_DFL);
104 raise(sig);
105}
106#endif /* !_WIN32 */
107
108#ifdef _WIN32
114static LONG WINAPI windows_crash_handler(EXCEPTION_POINTERS *exception_info) {
115 (void)exception_info; /* Unused for now, could log exception code */
116
117 /* Prevent recursive crashes */
118 if (g_crash_in_progress) {
119 return EXCEPTION_CONTINUE_SEARCH;
120 }
121 g_crash_in_progress = 1;
122
123 /* Write crash marker directly to mmap'd log */
124 if (g_mmap_log.initialized && g_mmap_log.text_region) {
125 DWORD exception_code = exception_info ? exception_info->ExceptionRecord->ExceptionCode : 0;
126 const char *crash_msg = "\n=== CRASH DETECTED (exception 0x%08lX) ===\n";
128 int len = safe_snprintf(msg_buf, sizeof(msg_buf), crash_msg, (unsigned long)exception_code);
129 if (len > 0) {
130 uint64_t pos = atomic_fetch_add_u64(&g_mmap_log.write_pos, (uint64_t)len);
131 if (pos + (uint64_t)len <= g_mmap_log.text_capacity) {
132 memcpy(g_mmap_log.text_region + pos, msg_buf, (size_t)len);
133 }
134 }
135 }
136
137 /* Sync mmap to disk */
138 if (g_mmap_log.initialized) {
139 platform_mmap_sync(&g_mmap_log.mmap, true);
140 }
141
142 /* Let Windows continue with default crash handling (creates minidump if configured) */
143 return EXCEPTION_CONTINUE_SEARCH;
144}
145#endif /* _WIN32 */
146
148#ifndef _WIN32
149 struct sigaction sa = {0};
150 sa.sa_handler = crash_signal_handler;
151 sigemptyset(&sa.sa_mask);
152 sa.sa_flags = (int)SA_RESETHAND; /* One-shot */
153
154 sigaction(SIGSEGV, &sa, NULL);
155 sigaction(SIGABRT, &sa, NULL);
156 sigaction(SIGBUS, &sa, NULL);
157 sigaction(SIGFPE, &sa, NULL);
158 sigaction(SIGILL, &sa, NULL);
159#else
160 SetUnhandledExceptionFilter(windows_crash_handler);
161#endif
162}
163
164/* ============================================================================
165 * Public API
166 * ============================================================================ */
167
174static size_t find_content_end(const char *text, size_t capacity) {
175 /* Scan backwards to find last non-space/non-null byte */
176 size_t pos = capacity;
177 while (pos > 0 && (text[pos - 1] == ' ' || text[pos - 1] == '\0' || text[pos - 1] == '\n')) {
178 pos--;
179 }
180
181 /* Now find the newline after the last content */
182 while (pos < capacity && text[pos] != '\n' && text[pos] != ' ' && text[pos] != '\0') {
183 pos++;
184 }
185
186 /* Include the newline if present */
187 if (pos < capacity && text[pos] == '\n') {
188 pos++;
189 }
190
191 return pos;
192}
193
195 if (!config || !config->log_path) {
196 return SET_ERRNO(ERROR_INVALID_PARAM, "mmap log: config or log_path is NULL");
197 }
198
199 if (g_mmap_log.initialized) {
200 log_warn("mmap log: already initialized, destroying first");
202 }
203
204 /* Determine file size */
205 size_t file_size = config->max_size > 0 ? config->max_size : LOG_MMAP_DEFAULT_SIZE;
206 if (file_size < 1024) {
207 file_size = 1024; /* Minimum reasonable size */
208 }
209
210 /* Store file path for later truncation */
211 SAFE_STRNCPY(g_mmap_log.file_path, config->log_path, sizeof(g_mmap_log.file_path) - 1);
212
213 /* Open mmap file */
214 platform_mmap_init(&g_mmap_log.mmap);
215 asciichat_error_t result = platform_mmap_open("mmap_log_file", config->log_path, file_size, &g_mmap_log.mmap);
216 if (result != ASCIICHAT_OK) {
217 return result;
218 }
219
220 /* Entire file is text - no header */
221 g_mmap_log.text_region = (char *)g_mmap_log.mmap.addr;
222 g_mmap_log.text_capacity = file_size;
223
224 /* Find where existing content ends (scan for last newline before spaces/nulls) */
225 size_t existing_pos = find_content_end(g_mmap_log.text_region, file_size);
226 atomic_store_u64(&g_mmap_log.write_pos, existing_pos);
227
228 /* Clear unused portion with newlines (grep-friendly without needing -a flag)
229 * We truncate the file on clean shutdown to save space */
230 if (existing_pos < file_size) {
231 memset(g_mmap_log.text_region + existing_pos, '\n', file_size - existing_pos);
232 }
233
234 if (existing_pos > 0) {
235 log_info("mmap log: resumed existing log at position %zu", existing_pos);
236 } else {
237 log_info("mmap log: created new log file %s (%zu bytes)", config->log_path, file_size);
238 }
239
240 /* Reset statistics */
241 atomic_store_u64(&g_mmap_log.bytes_written, 0);
242 atomic_store_u64(&g_mmap_log.wrap_count, 0);
243
244 /* Install crash handlers */
246
247 g_mmap_log.initialized = true;
248
249 /* Write startup marker */
250 log_mmap_write(1 /* LOG_INFO */, NULL, 0, NULL, "=== Log started (mmap text mode, %zu bytes) ===", file_size);
251
252 return ASCIICHAT_OK;
253}
254
255asciichat_error_t log_mmap_init_simple(const char *log_path, size_t max_size) {
256 log_mmap_config_t config = {
257 .log_path = log_path,
258 .max_size = max_size,
259 };
260 return log_mmap_init(&config);
261}
262
264 if (!g_mmap_log.initialized) {
265 return;
266 }
267
268 /* Write shutdown marker */
269 log_mmap_write(1 /* LOG_INFO */, NULL, 0, NULL, "=== Log ended ===");
270
271 /* Sync to disk */
272 platform_mmap_sync(&g_mmap_log.mmap, true);
273
274 /* Truncate file to actual content size to save space
275 * This converts the large mmap file (4MB with newlines) to just the actual log content */
276 uint64_t final_pos = atomic_load_u64(&g_mmap_log.write_pos);
277 if (final_pos < g_mmap_log.text_capacity && strlen(g_mmap_log.file_path) > 0) {
278#ifdef _WIN32
279 /* Windows: Close mmap first, then truncate file, then reopen for truncation */
280 platform_mmap_close(&g_mmap_log.mmap);
281 HANDLE hFile = CreateFileA(g_mmap_log.file_path, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
282 if (hFile != INVALID_HANDLE_VALUE) {
283 LARGE_INTEGER size;
284 size.QuadPart = (LONGLONG)final_pos;
285 if (SetFilePointerEx(hFile, size, NULL, FILE_BEGIN)) {
286 SetEndOfFile(hFile);
287 }
288 CloseHandle(hFile);
289 log_debug("mmap log: truncated %s to %zu bytes (was %zu MB)", g_mmap_log.file_path, (size_t)final_pos, g_mmap_log.text_capacity / 1024 / 1024);
290 }
291#else
292 /* POSIX: Use ftruncate() on the file descriptor */
293 if (g_mmap_log.mmap.fd >= 0) {
294 if (ftruncate(g_mmap_log.mmap.fd, (off_t)final_pos) == 0) {
295 log_debug("mmap log: truncated %s to %zu bytes (was %zu MB)", g_mmap_log.file_path, (size_t)final_pos, g_mmap_log.text_capacity / 1024 / 1024);
296 }
297 }
298 platform_mmap_close(&g_mmap_log.mmap);
299#endif
300 } else {
301 /* No truncation needed or path not set */
302 platform_mmap_close(&g_mmap_log.mmap);
303 }
304
305 g_mmap_log.text_region = NULL;
306 g_mmap_log.file_path[0] = '\0';
307
308 g_mmap_log.initialized = false;
309 log_debug("mmap log: destroyed");
310}
311
312void log_mmap_write(int level, const char *file, int line, const char *func, const char *fmt, ...) {
313 if (!g_mmap_log.initialized || !g_mmap_log.text_region) {
314 return;
315 }
316
317 static const char *level_names[] = {"DEV", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"};
318 const char *level_name = (level >= 0 && level < 6) ? level_names[level] : "???";
319
320 /* Format the complete log line into a local buffer first */
321 char line_buf[LOG_MMAP_MSG_BUFFER_SIZE];
322 char time_buf[LOG_TIMESTAMP_BUFFER_SIZE];
323 format_timestamp(time_buf, sizeof(time_buf));
324
325 int prefix_len;
326 if (file && func) {
327 prefix_len = safe_snprintf(line_buf, sizeof(line_buf), "[%s] [%s] %s:%d in %s(): ", time_buf, level_name, file, line, func);
328 } else {
329 prefix_len = safe_snprintf(line_buf, sizeof(line_buf), "[%s] [%s] ", time_buf, level_name);
330 }
331
332 if (prefix_len < 0) {
333 return;
334 }
335
336 /* Format the message */
337 va_list args;
338 va_start(args, fmt);
339 int msg_len = safe_vsnprintf(line_buf + prefix_len, sizeof(line_buf) - (size_t)prefix_len - 1, fmt, args);
340 va_end(args);
341
342 if (msg_len < 0) {
343 return;
344 }
345
346 /* Add newline */
347 size_t total_len = (size_t)prefix_len + (size_t)msg_len;
348 if (total_len >= sizeof(line_buf) - 1) {
349 total_len = sizeof(line_buf) - 2; /* Truncate if too long */
350 }
351 line_buf[total_len] = '\n';
352 total_len++;
353 line_buf[total_len] = '\0';
354
355 /* Strip ANSI escape codes from the log message before writing to file */
356 char *stripped = ansi_strip_escapes(line_buf, total_len);
357 const char *write_buf = stripped ? stripped : line_buf;
358 size_t write_len = stripped ? strlen(stripped) : total_len;
359
360 /* Atomically claim space in the mmap'd region */
361 uint64_t pos = atomic_fetch_add_u64(&g_mmap_log.write_pos, write_len);
362
363 /* Check if we exceeded capacity - drop this message if so */
364 /* Rotation is handled by maybe_rotate_log() called from logging.c */
365 if (pos + write_len > g_mmap_log.text_capacity) {
366 /* Undo our claim - we can't fit */
367 atomic_fetch_sub_u64(&g_mmap_log.write_pos, write_len);
368 if (stripped) {
369 SAFE_FREE(stripped);
370 }
371 return;
372 }
373
374 /* Copy formatted text to mmap'd region */
375 memcpy(g_mmap_log.text_region + pos, write_buf, write_len);
376
377 atomic_fetch_add_u64(&g_mmap_log.bytes_written, write_len);
378
379 if (stripped) {
380 SAFE_FREE(stripped);
381 }
382
383 /* Sync for ERROR/FATAL to ensure visibility on crash */
384 if (level >= 4 /* LOG_ERROR */) {
385 platform_mmap_sync(&g_mmap_log.mmap, false);
386 }
387}
388
390 return g_mmap_log.initialized;
391}
392
393void log_mmap_sync(void) {
394 if (g_mmap_log.initialized) {
395 platform_mmap_sync(&g_mmap_log.mmap, true);
396 }
397}
398
400 if (bytes_written) {
401 *bytes_written = atomic_load_u64(&g_mmap_log.bytes_written);
402 }
403 if (wrap_count) {
404 *wrap_count = atomic_load_u64(&g_mmap_log.wrap_count);
405 }
406}
407
408bool log_mmap_get_usage(size_t *used, size_t *capacity) {
409 if (!g_mmap_log.initialized) {
410 return false;
411 }
412
413 if (used) {
414 *used = (size_t)atomic_load_u64(&g_mmap_log.write_pos);
415 }
416 if (capacity) {
417 *capacity = g_mmap_log.text_capacity;
418 }
419 return true;
420}
421
422void log_mmap_rotate(void) {
423 if (!g_mmap_log.initialized || !g_mmap_log.text_region) {
424 return;
425 }
426
427 /* NOTE: Caller must hold the rotation mutex from logging.c */
428
429 uint64_t current_pos = atomic_load_u64(&g_mmap_log.write_pos);
430 size_t capacity = g_mmap_log.text_capacity;
431
432 /* Keep last 2/3 of the log (same ratio as file rotation) */
433 size_t keep_size = capacity * 2 / 3;
434 if (current_pos <= keep_size) {
435 return;
436 }
437
438 /* Find where to start keeping (skip to beginning of current_pos - keep_size) */
439 size_t skip_bytes = (size_t)current_pos - keep_size;
440 char *keep_start = g_mmap_log.text_region + skip_bytes;
441
442 /* Skip to next line boundary to avoid partial lines */
443 size_t skipped = 0;
444 while (skipped < keep_size && *keep_start != '\n') {
445 keep_start++;
446 skipped++;
447 }
448 if (skipped < keep_size && *keep_start == '\n') {
449 keep_start++;
450 skipped++;
451 }
452
453 size_t actual_keep = keep_size - skipped;
454 if (actual_keep == 0) {
455 /* Nothing to keep - just reset */
456 atomic_store_u64(&g_mmap_log.write_pos, 0);
457 memset(g_mmap_log.text_region, '\n', capacity);
458 return;
459 }
460
461 /* Move the tail to the beginning using memmove (handles overlap) */
462 memmove(g_mmap_log.text_region, keep_start, actual_keep);
463
464 /* Clear the rest with newlines (grep-friendly without needing -a flag) */
465 memset(g_mmap_log.text_region + actual_keep, '\n', capacity - actual_keep);
466
467 /* Update write position */
468 atomic_store_u64(&g_mmap_log.write_pos, actual_keep);
469
470 /* Write rotation marker */
471 const char *rotate_msg = "\n=== LOG ROTATED ===\n";
472 size_t rotate_len = strlen(rotate_msg);
473 if (actual_keep + rotate_len < capacity) {
474 memcpy(g_mmap_log.text_region + actual_keep, rotate_msg, rotate_len);
475 atomic_store_u64(&g_mmap_log.write_pos, actual_keep + rotate_len);
476 }
477
478 atomic_fetch_add_u64(&g_mmap_log.wrap_count, 1);
479
480 /* Sync after rotation */
481 platform_mmap_sync(&g_mmap_log.mmap, true);
482}
ANSI escape sequence utilities and fast color code generation.
#define SET_ERRNO(code,...)
uint64_t atomic_fetch_add_u64(atomic_t *a, uint64_t delta)
Atomically add to a uint64_t and return the previous value.
uint64_t atomic_fetch_sub_u64(atomic_t *a, uint64_t delta)
Atomically subtract from a uint64_t and return the previous value.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
char * ansi_strip_escapes(const char *input, size_t input_len)
When code needs to work with rgb error, it keeps r, g, b here instead of scattering it across globals...
Definition ansi.c:27
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#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_INVALID_PARAM
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define LOG_TIMESTAMP_BUFFER_SIZE
Maximum size of a timestamp string.
Definition log/log.h:100
#define LOG_MMAP_MSG_BUFFER_SIZE
Maximum size of a log message in mmap mode.
Definition log/log.h:94
#define NS_PER_SEC_INT
Definition time.h:173
action_args_t args
📝 Logging API with multiple log levels and terminal output control
struct log_mmap_config log_mmap_config_t
Definition log/log.h:902
char file_path[PLATFORM_MAX_PATH_LENGTH]
Definition mmap.c:42
asciichat_error_t log_mmap_init(const log_mmap_config_t *config)
Initialize mmap-based text logging.
Definition mmap.c:194
atomic_t bytes_written
Definition mmap.c:45
void log_mmap_rotate(void)
Rotate the mmap log (tail-keeping rotation).
Definition mmap.c:422
void log_mmap_install_crash_handlers(void)
Install signal handlers for crash safety.
Definition mmap.c:147
void log_mmap_sync(void)
Force sync the mmap'd file to disk.
Definition mmap.c:393
bool log_mmap_is_active(void)
Check if mmap logging is active.
Definition mmap.c:389
char * text_region
Definition mmap.c:38
void log_mmap_write(int level, const char *file, int line, const char *func, const char *fmt,...)
Write a log entry directly to the mmap'd file (lock-free).
Definition mmap.c:312
bool log_mmap_get_usage(size_t *used, size_t *capacity)
Get current mmap log usage.
Definition mmap.c:408
atomic_t wrap_count
Definition mmap.c:46
platform_mmap_t mmap
Definition mmap.c:37
void log_mmap_destroy(void)
Shutdown mmap logging.
Definition mmap.c:263
#define LOG_MMAP_DIAGNOSTIC_BUFFER_SIZE
Definition mmap.c:11
void log_mmap_get_stats(uint64_t *bytes_written, uint64_t *wrap_count)
Get statistics about the mmap log.
Definition mmap.c:399
atomic_t write_pos
Definition mmap.c:40
size_t text_capacity
Definition mmap.c:39
bool initialized
Definition mmap.c:41
asciichat_error_t log_mmap_init_simple(const char *log_path, size_t max_size)
Initialize mmap logging with simple parameters.
Definition mmap.c:255
Lock-free memory-mapped text logging with crash safety.
#define LOG_MMAP_DEFAULT_SIZE
Default mmap log file size (4MB).
Definition mmap.h:46
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
size_t max_size
Definition mmap.h:58
const char * log_path
Definition mmap.h:57
⏱️ High-precision timing utilities using sokol_time.h and uthash
int platform_localtime(const time_t *timer, struct tm *result)
Definition util.c:57