ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
common.c
Go to the documentation of this file.
4
11
12// Platform abstraction includes memory sizing functions
16#include <ascii-chat/common.h>
17#include <libplatform/system.h>
18#include <libplatform/socket.h>
20#include <libplatform/process.h>
21#include <libplatform/memory.h>
22#include <ascii-chat/log/log.h>
23#include <ascii-chat/log/asan.h>
24#include <ascii-chat/buffer.h>
26#include <ascii-chat/video/ascii/common.h> // For simd_caches_destroy_all()
27#include <options/colorscheme.h> // For colorscheme_destroy()
28#include <ascii-chat/util/time.h> // For timer_system_destroy()
31#include <options/options.h>
32#include <options/rcu.h> // For RCU-based options access
33#include <ascii-chat/discovery/strings.h> // For RCU-based options access
34#include <ascii-chat/debug/sync.h> // Synchronization diagnostics lifecycle
35#include <ascii-chat/debug/mutex.h> // For mutex_stack_cleanup
36#include <ascii-chat/debug/named.h> // For named_destroy()
37#include <ascii-chat/debug/atomic.h> // For debug_atomic_shutdown()
38#include <ascii-chat/debug/memory.h> // For debug memory reporting
39#include <libplatform/symbols.h> // For symbols cache init
40#include <libplatform/terminal.h> // For terminal_screen_cleanup
41#include <libplatform/keyboard.h> // For keyboard_destroy()
42#include <ascii-chat/tui/terminal_screen.h> // For terminal_screen_cleanup
43#include <string.h>
44#include <libplatform/atomic.h>
45#include <limits.h>
46#include <stdlib.h>
47
48#ifndef _WIN32
49#include <pthread.h> // For PTHREAD_MUTEX_INITIALIZER on POSIX
50#endif
51
52/* ============================================================================
53 * Global Variables for Early Argv Inspection
54 * ============================================================================
55 */
56
57// These globals are used by libplatform's terminal implementation to detect --color flag
58// during early execution phases (e.g., when --help is processed before
59// options are fully parsed and published to RCU)
60// ASCIICHAT_API is required for proper DLL export on Windows
62ASCIICHAT_API char **g_argv = NULL;
63
64// Global flags for --color detection (set during options_init before RCU is ready)
65ASCIICHAT_API bool g_color_flag_passed = false; // Was --color explicitly passed in argv?
66ASCIICHAT_API bool g_color_flag_value = false; // What was the value of --color?
67
68/* ============================================================================
69 * Shutdown Check System Implementation
70 * ============================================================================
71 */
72
73// Use atomic for thread-safe access to shutdown callback
74#include <libplatform/atomic.h>
75static atomic_ptr_t g_shutdown_callback = {0};
76static atomic_t g_shutdown_requested = {0};
77
79 atomic_ptr_store(&g_shutdown_callback, (void *)callback);
80}
81
82void shutdown_request(void) {
83 atomic_store_u64(&g_shutdown_requested, 1);
84}
85
87 if (atomic_load_u64(&g_shutdown_requested)) {
88 return true;
89 }
90 shutdown_check_fn callback = (shutdown_check_fn)atomic_ptr_load(&g_shutdown_callback);
91 if (callback == NULL) {
92 return false; // No callback registered, assume not shutting down
93 }
94 return callback();
95}
96
97/* ============================================================================
98 * Shared Initialization Implementation
99 * ============================================================================
100 */
101
102#if defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
103static void print_mimalloc_stats(void);
104#endif
105
106// Guard to prevent multiple initialization of shared subsystems
107// (can happen if asciichat_shared_init() is called multiple times during startup)
108// But allow subsystem reinitialization for tests and other use cases
109static bool g_shared_initialized = false;
110
111#ifndef _WIN32
118static void asciichat_common_atfork_child(void) {
119 // Reset the shared initialization flag so asciichat_shared_init() will reinitialize subsystems
120 g_shared_initialized = false;
121}
122
126__attribute__((constructor)) static void register_common_fork_handlers(void) {
127 pthread_atfork(NULL, NULL, asciichat_common_atfork_child);
128}
129#endif
130
131asciichat_error_t asciichat_shared_init(const char *log_file, bool is_client, bool quiet_startup) {
132 // Initialize shared subsystems BEFORE options_init()
133 // This allows options_init() to use properly configured logging with colors
134 //
135 // NOTE: This function is called BEFORE options_init(), so we can't use GET_OPTION()
136 // Palette config and quiet mode will be applied after options_init() is called
137
138 // Only register initialization tracking once
139 if (!g_shared_initialized) {
140 // 1. TIMER SYSTEM - Initialize first so timing is available for everything else
141 if (!timer_system_init()) {
142 FATAL(ERROR_PLATFORM_INIT, "Failed to initialize timer system");
143 }
144
145 // KEYBOARD SYSTEM must be initialized BEFORE logging since keyboard_init() calls log_info()
146 // But we need to initialize logging AFTER timer_system_init() and BEFORE keyboard_init()
147 // So we move keyboard_init() to AFTER log_init()
148
149#ifndef NDEBUG
150 if (named_init() != ASCIICHAT_OK) {
151 return SET_ERRNO(ERROR_PLATFORM_INIT, "Failed to initialize named.");
152 }
153 debug_memory_ensure_init();
154 static const char *const ascii_chat_libraries[] = {"libasciichat", NULL};
155 symbol_cache_set_project_modules("ascii-chat", ascii_chat_libraries);
156 symbol_cache_init();
157#endif
158
159 // 2. LOGGING - Initialize system state first, then user-level logging
160 // Initialize logging system internal state (terminal caps, colors)
162
163 // Initialize with provided log file
164 // Force stderr for client-like modes when stdout is piped to keep stdout clean
165 bool force_stderr = is_client && terminal_is_piped_output();
166
167 if (quiet_startup) {
169 }
170
171 // Use LOG_DEBUG by default; will be reconfigured after options_init()
173 log_init(log_file, LOG_DEBUG, force_stderr, false /* don't use_mmap */);
174
175 // 2. KEYBOARD SYSTEM - Initialize keyboard input AFTER logging (may fail if stdin/tty not available)
176 // Failure is not fatal - keyboard_read_nonblocking() safely handles uninitialized state
177 if (terminal_is_stdin_tty()) {
179 }
180
181 // 3. PLATFORM - Initialize platform-specific functionality (Winsock, etc)
182 if (platform_init() != ASCIICHAT_OK) {
183 FATAL(ERROR_PLATFORM_INIT, "Failed to initialize platform");
184 }
185 if (socket_init() != 0) {
186 FATAL(ERROR_PLATFORM_INIT, "Failed to initialize sockets");
187 }
188
189 // 4. buffer domain - Initialize global shared buffer domain
191
192 // Mark that we've initialized (prevents re-registration of subsystems)
193 g_shared_initialized = true;
194 }
195
196 // NOTE: This library function does NOT register atexit() handlers.
197 // Library code should not own the process lifecycle. The application
198 // is responsible for calling atexit(asciichat_shared_destroy) if it
199 // wants automatic cleanup on normal exit.
200
201 return ASCIICHAT_OK;
202}
203
220 // Guard against double cleanup (can be called explicitly + via atexit)
221 static bool shutdown_done = false;
222 if (shutdown_done) {
223 return;
224 }
225 shutdown_done = true;
226
227 // Ctrl-C has already stopped the application pipeline. Diagnostic workers
228 // may be inside logging/registry code and joining them from the atexit
229 // thread can deadlock. Restore the terminal output state and let the OS
230 // reclaim those process-owned workers after the remaining atexit handlers.
231 if (shutdown_is_requested()) {
233 return;
234 }
235
236 // Stop diagnostic readers before destroying symbols or synchronization state.
237 debug_sync_cleanup_thread();
240
246 // A signal-driven exit has already stopped all application workers. Do not
247 // enter the late atexit cleanup graph, whose debug-registry locks can be
248 // held by the console runtime; the OS reclaims process-owned resources.
250 return;
251
252 // Cleanup in reverse order of initialization (LIFO)
253 // This ensures dependencies are properly handled
254
255 // 0. Stop background threads first (before any cleanup that might use them)
256 // Terminal resize detection thread (Windows only, checks if active)
258
259#ifndef NDEBUG
260
261 // Clean up all remaining mutex stacks before memory report
263
264 // Clean up current thread's allocations
265 debug_sync_final_cleanup();
266
267 // Atomic debug cleanup
269#endif
270 debug_sync_destroy();
273
274 // 1. Terminal screen - cleanup frame buffer
276
277 // 2. SIMD caches - cleanup CPU-specific caches
279
280 // 3. Discovery service strings cache - cleanup session string cache
282
283 // 4. Logging - in correct order (end first, then begin)
286
287 // 5. Known hosts - cleanup authentication state
289
290 // 6. Options state - cleanup RCU-based options
292
293 // 7. buffer domain - cleanup global buffer domain
295
296 // 8. Platform cleanup - restores terminal, cleans up platform resources
297 // (includes symbol cache cleanup on Windows)
299
300 // 9. Keyboard - restore terminal settings (redundant with platform_destroy but safe)
302
303 // Workers have stopped; restore argv/environment before releasing title storage.
304 platform_process_title_destroy();
305
306 // 10. Timer system - cleanup timers (may still log!)
308
309 // 11. Error context cleanup
311
312 // 12. Logging cleanup - free log format buffers and system state
313 log_destroy();
316
317 // 13. Mutex stack cleanup - must be before memory report so stacks are freed
318#ifndef NDEBUG
320 // Final cleanup: free the main thread's debug allocations
321 debug_sync_final_cleanup();
322#endif
323
324 // 14. Memory stats (debug builds only) - runs with colors still available
325 // Note: debug_memory_report() is also called manually during shutdown in server_main()
326 // The function is safe to call multiple times with polling-based locking
327#if defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
328 print_mimalloc_stats();
329#endif
330
331#if defined(DEBUG_MEMORY) && !defined(NDEBUG)
332 debug_memory_report(GET_OPTION(color));
333#endif
334
335 // 15. Color cleanup - free compiled ANSI strings (AFTER memory report)
338
339 // 16. Clean up binary path cache explicitly
340 // Note: This is also called by platform_destroy() via atexit(), but it's idempotent
341 platform_cleanup_binary_path_cache();
342
343 // 17. Clean up RCU-based options state
345
346 // 18. Clean up errno context (allocated strings, backtrace symbols)
348
349#ifndef NDEBUG
350 // 19. Named registry - cleanup all registered thread names and debug entries
352#endif
353
354 // 21. timer resolution restore
355 platform_restore_timer_resolution(); // Restore timer resolution (no-op on POSIX)
356
357 // 22. Clean up SIMD caches
359
360 // 23. Clean up symbol cache
361 // This must be called BEFORE log_destroy() as symbol_cache_destroy() uses log_debug()
362 // Safe to call even if atexit() runs - it's idempotent (checks g_symbol_cache_initialized)
363 // Also called via platform_destroy() atexit handler, but explicit call ensures proper ordering
365
366 // 24. Clean up global buffer domain (explicitly, as atexit may not run on Ctrl-C)
367 // Note: This is also registered with atexit(), but calling it explicitly is safe (idempotent)
368 // Safe to call even if atexit() runs - it checks the default domain and sets it to NULL
370
371#ifndef NDEBUG
372 // 25. Symbol cache cleanup
374#endif
375 // No more shutdown diagnostics may scroll pending terminal errors away.
377}
378
379#if defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
380// Wrapper function for mi_stats_print to use with atexit()
381// mi_stats_print takes a parameter, but atexit requires void(void)
382static void print_mimalloc_stats(void) {
383 // Skip memory report if an action flag was passed (for clean action output)
384 // unless explicitly forced via ASCII_CHAT_MEMORY_DEBUG environment variable
385 if (has_action_flag() && !SAFE_GETENV("ASCII_CHAT_MEMORY_DEBUG")) {
386 return;
387 }
388 mi_stats_print(NULL); // NULL = print to stderr
389}
390#endif
void sanitizer_log_init(const char *filename)
Definition asan.c:48
void sanitizer_log_destroy(void)
Definition asan.c:51
void errno_shutdown(void)
void errno_destroy(void)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
void debug_atomic_shutdown(void)
uint64_t atomic_load_u64(atomic_t *a)
Atomically load a uint64_t value.
void buffer_system_cleanup(void)
Definition buffer.c:424
void buffer_system_init(void)
Definition buffer.c:396
void colorscheme_destroy(void)
Shutdown the color system.
Platform initialization and static synchronization helpers.
Named object registry for debugging — log identifiable resource names.
void acds_strings_destroy(void)
Cleanup function for session string cache Called by asciichat_shared_destroy() during library cleanup...
void debug_errno_destroy(void)
Definition errno.c:125
void debug_errno_cleanup_thread(void)
Definition errno.c:110
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
void ui_error_popup_flush(void)
bool g_color_flag_value
Value of –color flag (true if –color was in argv) Set by options_init() before RCU is initialized,...
Definition common.c:66
char ** g_argv
Global argv for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:62
int g_argc
Global argc for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:61
bool g_color_flag_passed
Was –color explicitly passed in command-line arguments? Set by options_init() before RCU is initializ...
Definition common.c:65
#define SAFE_GETENV(name)
asciichat_error_t asciichat_shared_init(const char *log_file, bool is_client, bool quiet_startup)
Initialize common subsystems shared by client and server.
Definition common.c:131
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
void asciichat_shared_destroy(void)
Clean up all shared library subsystems.
Definition common.c:219
void known_hosts_destroy(void)
Cleanup function to free cached known_hosts path.
void named_destroy(void)
Destroy the named object registry.
asciichat_error_t named_init(void)
Initialize the named object registry.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59
@ ASCIICHAT_OK
Definition error_codes.h:50
void log_system_init(void)
Initialize the logging system internal state (system-level init).
void log_shutdown_end(void)
End shutdown phase - restore previous logging settings.
void log_destroy(void)
Destroy the logging system and close log file.
void log_cleanup_colors(void)
Clean up compiled color scheme.
void log_shutdown_begin(void)
Begin shutdown phase - disable console logging but keep file logging.
void log_system_destroy(void)
Shutdown the logging system internal state (system-level cleanup).
void log_init(const char *filename, log_level_t level, bool force_stderr, bool use_mmap)
Initialize the logging system.
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:687
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
int32_t vec_t __attribute__((vector_size(4 *4)))
SESSION_CREATED (PACKET_TYPE_ACIP_SESSION_CREATED) - Session created response.
Definition vector.h:42
void timer_system_destroy(void)
Cleanup the timing system.
Definition time.c:171
bool timer_system_init(void)
Initialize the timing system.
Definition time.c:149
#define GET_OPTION(field)
Definition options.h:1333
bool has_action_flag(void)
Check if an action flag was detected.
Definition options.c:251
#define ASCIICHAT_API
Export symbols on Unix platforms (Linux, macOS).
Definition api.h:86
void shutdown_request(void)
Definition common.c:82
bool(* shutdown_check_fn)(void)
Shutdown check callback function type.
Definition shutdown.h:36
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:86
void shutdown_register_callback(shutdown_check_fn callback)
Register application's shutdown check function.
Definition common.c:78
void simd_caches_destroy_all(void)
Destroy all SIMD caches (palette and other caches).
⚙️ Common definitions, error codes, macros, and types shared throughout the application
Statistics worker for error totals and memory reports. Signal handlers may only request a report.
SIMD-optimized ASCII conversion interface.
int platform_init(void)
Definition init.c:9
void platform_destroy(void)
Definition init.c:14
Known hosts management for MITM attack prevention.
void debug_stats_cleanup_thread(void)
void debug_stats_destroy(void)
📝 Logging API with multiple log levels and terminal output control
void terminal_stop_resize_detection(void)
Definition misc.c:102
int platform_restore_timer_resolution(void)
Definition misc.c:107
int keyboard_init(void)
Definition misc.c:18
int socket_init(void)
Definition misc.c:22
void symbol_cache_destroy(void)
Definition misc.c:99
void mutex_stack_cleanup(void)
Cleanup mutex stack system.
Definition mutex.c:965
Per-thread mutex lock stack for deadlock detection.
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
ASCII Palette Management for Video-to-ASCII Conversion.
void options_state_destroy(void)
Shutdown RCU options system.
Definition rcu.c:465
void stats_runtime_stop(void)
Definition runtime.c:611
void keyboard_destroy(void)
bool terminal_is_stdin_tty(void)
bool terminal_is_piped_output(void)
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:110
Atomic value wrapper for integral/boolean types.
Definition atomic.h:76
void terminal_screen_cleanup(void)
Clean up terminal screen resources.
Reusable "fixed header + scrolling logs" terminal screen abstraction.
⏱️ High-precision timing utilities using sokol_time.h and uthash
void ui_controller_restore_terminal_output(void)
void ui_controller_shutdown(void)
void ui_input_shutdown(void)
Definition tui/input.c:549
#define LOG_DEBUG
Definition types.h:43