ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
include/ascii-chat/common.h
Go to the documentation of this file.
1
26
27#pragma once
28
29/* Note: string.h must come before any platform includes
30 * that might use memcpy (used in unaligned access helpers below). */
31#include <string.h> // For memcpy in unaligned access helpers
32
33// DLL export/import macros (must be included first to avoid circular dependencies)
34#include <ascii-chat/api.h> // IWYU pragma: keep
35#include <libplatform/filesystem.h> // platform file and descriptor helpers
36#include <libplatform/mutex.h>
37#include <libplatform/cond.h>
38#include <util/string.h>
39
40/* Feature test macros for POSIX functions */
41#include <stdbool.h>
42#include <stddef.h>
43#include <stdint.h>
44#include <stdlib.h> // For malloc/free in ALLOC_* macros
45
47#define ASCII_CHAT_APP_NAME "ascii-chat"
48
49#if (defined(__clang__) || defined(__GNUC__)) && !defined(__builtin_c23_va_start)
50#define __builtin_c23_va_start(ap, param) __builtin_va_start(ap, param)
51#endif
52
53#if (defined(__clang__) || defined(__GNUC__)) && !defined(__builtin_c23_va_end)
54#define __builtin_c23_va_end(ap) __builtin_va_end(ap)
55#endif
56
57// This fixes clangd errors about missing types. I DID include stdint.h, but
58// it's not enough.
59#ifndef UINT8_MAX
60typedef unsigned char uint8_t;
61typedef unsigned short uint16_t;
62typedef unsigned int uint32_t;
63typedef unsigned long long uint64_t;
64#endif
65
66/* ============================================================================
67 * Platform Maximum Path Length
68 * ============================================================================
69 * Defined here (before logging.h) to avoid circular dependencies.
70 * Also defined in libplatform/system.h for documentation purposes.
71 */
72#ifdef _WIN32
73#include <limits.h>
74#ifndef PATH_MAX
75#define PATH_MAX 260
76#endif
77// Windows extended-length path maximum (not the legacy 260 MAX_PATH)
78#define PLATFORM_MAX_PATH_LENGTH 32767
79#elif defined(__linux__)
80#include <limits.h>
81#ifndef PATH_MAX
82#define PLATFORM_MAX_PATH_LENGTH 4096
83#else
84#define PLATFORM_MAX_PATH_LENGTH PATH_MAX
85#endif
86#elif defined(__APPLE__)
87#include <sys/syslimits.h>
88#ifndef PATH_MAX
89#define PLATFORM_MAX_PATH_LENGTH 1024
90#else
91#define PLATFORM_MAX_PATH_LENGTH PATH_MAX
92#endif
93#else
94// Fallback for unknown platforms
95#define PLATFORM_MAX_PATH_LENGTH 4096
96#endif
97
98// INFO: flightaware/dump1090 dev made this after my pr: https://github.com/flightaware/dump1090/pull/282
99#if ((defined(__clang__) && __clang_major__ >= 21) || (defined(__GNUC__) && __GNUC__ >= 10))
100#define NONSTRING __attribute__((nonstring))
101#else
102#define NONSTRING /* nothing */
103#endif
104
105/* ============================================================================
106 * Include organized sub-headers for specific domains
107 * ============================================================================ */
108
109#include "common/error_codes.h" // Error codes and error_string function
110#include "common/protocol_constants.h" // Protocol version, features, compression, frames
111#include "common/limits.h" // MAX_CLIENTS, FPS limits, display name length
112#include "common/buffer_sizes.h" // Standard buffer size constants
113#include "common/log_rates.h" // Logging rate limit constants
114#include "common/shutdown.h" // Shutdown detection system
115#include "common/string_constants.h" // String literal constants (STR_TRUE, STR_FALSE, etc.)
116
117#ifdef __cplusplus
118extern "C" {
119#endif
120
121/* Forward declaration for asciichat_fatal_with_context - now after asciichat_error_t is defined */
122void asciichat_fatal_with_context(asciichat_error_t code, const char *file, int line, const char *function, const char *format, ...);
123
124#ifdef __cplusplus
125}
126#endif
127
128/* ============================================================================
129 * Fatal Error Macros - Exit with Error Message and Stack Trace
130 * ============================================================================
131 * These macros provide a convenient way to exit the program with a detailed
132 * error message. In debug builds, they also print a stack trace.
133 *
134 * Usage in src/ code:
135 * FATAL(ERROR_WEBCAM, "Custom msg: %d", val); // Error code + custom message
136 */
137
155#ifdef NDEBUG
156#define FATAL(code, ...) asciichat_fatal_with_context(code, NULL, 0, NULL, ##__VA_ARGS__)
157#else
158#define FATAL(code, ...) asciichat_fatal_with_context(code, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
159#endif
160
161/* ============================================================================
162 * Utility Macros
163 * ============================================================================ */
164
165/* Common utility macros */
167#ifndef MIN
168#define MIN(a, b) ((a) < (b) ? (a) : (b))
169#endif
170
172#ifndef MAX
173#define MAX(a, b) ((a) > (b) ? (a) : (b))
174#endif
175
177#ifndef ARRAY_SIZE
178#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
179#endif
180
181/* ============================================================================
182 * Burst and Throttle Macro
183 * ============================================================================
184 *
185 * @brief Rate-limit code execution with a burst window followed by throttle
186 *
187 * Allows code to execute frequently for an initial burst period, then refuses
188 * to execute again until a throttle period has elapsed since first invocation.
189 * The timer resets when called after the throttle period expires.
190 *
191 * Uses time_get_ns() from util/time.h for high-resolution monotonic timing.
192 *
193 * Example (backtrace every 500ms, then silence for 10 seconds):
194 * RUN_BURST_AND_THROTTLE(500 * NS_PER_MS_INT, 10 * NS_PER_SEC_INT, {
195 * platform_print_backtrace(1);
196 * });
197 *
198 * Time values in nanoseconds (use NS_PER_MS_INT, NS_PER_SEC_INT from util/time.h):
199 * - 500 milliseconds = 500 * NS_PER_MS_INT
200 * - 10 seconds = 10 * NS_PER_SEC_INT
201 *
202 * @param burst_ns Allow execution for this many nanoseconds
203 * @param throttle_ns Refuse execution until this many nanoseconds pass
204 * @param code_block Code to execute when throttle conditions permit (use braces: { ... })
205 */
206#define RUN_BURST_AND_THROTTLE(burst_ns, throttle_ns, code_block) \
207 do { \
208 static uint64_t burst_start = 0; \
209 uint64_t now = time_get_ns(); \
210 \
211 /* First call or timer reset */ \
212 if (burst_start == 0) { \
213 burst_start = now; \
214 code_block; \
215 } else { \
216 uint64_t elapsed_ns = now - burst_start; \
217 \
218 if (elapsed_ns < (uint64_t)(burst_ns)) { \
219 /* Within burst window */ \
220 code_block; \
221 } else if (elapsed_ns >= (uint64_t)(throttle_ns)) { \
222 /* Throttle period complete, reset and execute */ \
223 burst_start = now; \
224 code_block; \
225 } \
226 /* else: in throttle period, do nothing */ \
227 } \
228 } while (0)
229
230/* ============================================================================
231 * Memory Allocation with mimalloc Support
232 * ============================================================================
233 * When USE_MIMALLOC is enabled:
234 * - MI_OVERRIDE=ON (glibc): malloc/free automatically redirected to mimalloc
235 * - MI_OVERRIDE=OFF (musl): must explicitly use mi_malloc/mi_free
236 */
237
238#ifdef USE_MIMALLOC
239#include <mimalloc.h>
240#define ALLOC_MALLOC(size) mi_malloc(size)
241#define ALLOC_CALLOC(count, size) mi_calloc((count), (size))
242#define ALLOC_REALLOC(ptr, size) mi_realloc((ptr), (size))
243#define ALLOC_FREE(ptr) mi_free(ptr)
244#elif defined(DEBUG_MEMORY) && !defined(NDEBUG)
245#include "debug/memory.h"
246#define ALLOC_MALLOC(size) debug_malloc(size, __FILE__, __LINE__)
247#define ALLOC_CALLOC(count, size) debug_calloc((count), (size), __FILE__, __LINE__)
248#define ALLOC_REALLOC(ptr, size) debug_realloc((ptr), (size), __FILE__, __LINE__)
249#define ALLOC_FREE(ptr) debug_free(ptr, __FILE__, __LINE__)
250#else
251#define ALLOC_MALLOC(size) malloc(size)
252#define ALLOC_CALLOC(count, size) calloc((count), (size))
253#define ALLOC_REALLOC(ptr, size) realloc((ptr), (size))
254#define ALLOC_FREE(ptr) free(ptr)
255#endif
261
262/* Safe memory allocation with error checking - returns allocated pointer */
263#define SAFE_MALLOC(size, cast) \
264 ({ \
265 cast _ptr = (cast)ALLOC_MALLOC(size); \
266 if (!_ptr) { \
267 FATAL(ERROR_MEMORY, "Memory allocation failed: %zu bytes", (size_t)(size)); \
268 } \
269 _ptr; \
270 })
271
272/* Safe zero-initialized memory allocation */
273#define SAFE_CALLOC(count, size, cast) \
274 ({ \
275 cast _ptr = (cast)ALLOC_CALLOC((count), (size)); \
276 if (!_ptr) { \
277 FATAL(ERROR_MEMORY, "Memory allocation failed: %zu elements x %zu bytes", (size_t)(count), (size_t)(size)); \
278 } \
279 _ptr; \
280 })
281
282/* Safe memory reallocation */
283#define SAFE_REALLOC(ptr, size, cast) \
284 ({ \
285 void *tmp_ptr = ALLOC_REALLOC((ptr), (size)); \
286 if (!tmp_ptr) { \
287 FATAL(ERROR_MEMORY, "Memory reallocation failed: %zu bytes", (size_t)(size)); \
288 } \
289 (cast)(tmp_ptr); \
290 })
291
292/* Helper macro to track aligned allocations when DEBUG_MEMORY is enabled */
293#if defined(DEBUG_MEMORY) && !defined(MI_MALLOC_OVERRIDE)
294#ifdef NDEBUG
295/* Production build: don't include file/line info */
296#define TRACK_ALIGNED_ALLOC(ptr, size, file, line) debug_track_aligned((void *)(ptr), (size_t)(size), NULL, 0)
297#else
298/* Debug build: include file/line info */
299#define TRACK_ALIGNED_ALLOC(ptr, size, file, line) debug_track_aligned((void *)(ptr), (size_t)(size), (file), (line))
300#endif
301#else
302#define TRACK_ALIGNED_ALLOC(ptr, size, file, line) ((void)0)
303#endif
304
305/* SIMD-aligned memory allocation macros for optimal NEON/AVX performance */
306#ifdef USE_MIMALLOC
307/* Use mimalloc's aligned allocation (works on all platforms) */
308#define SAFE_MALLOC_ALIGNED(size, alignment, cast) \
309 ({ \
310 cast _ptr = (cast)mi_malloc_aligned((size), (alignment)); \
311 if (!_ptr) { \
312 FATAL(ERROR_MEMORY, "Aligned memory allocation failed: %zu bytes, %zu alignment", (size_t)(size), (size_t)(alignment)); \
313 } \
314 TRACK_ALIGNED_ALLOC(_ptr, (size), __FILE__, __LINE__); \
315 _ptr; \
316 })
317#else
318/* Fall back to platform-specific aligned allocation when mimalloc is disabled */
319#ifdef _WIN32
320/* Windows uses _aligned_malloc() for aligned allocation */
321#include <malloc.h>
322#define SAFE_MALLOC_ALIGNED(size, alignment, cast) \
323 ({ \
324 cast _ptr = (cast)_aligned_malloc((size), (alignment)); \
325 if (!_ptr) { \
326 FATAL(ERROR_MEMORY, "Aligned memory allocation failed: %zu bytes, %zu alignment", (size_t)(size), (size_t)(alignment)); \
327 } \
328 TRACK_ALIGNED_ALLOC(_ptr, (size), __FILE__, __LINE__); \
329 _ptr; \
330 })
331#elif defined(__APPLE__)
332/* macOS uses posix_memalign() for aligned allocation */
333#define SAFE_MALLOC_ALIGNED(size, alignment, cast) \
334 ({ \
335 cast _ptr; \
336 int result = posix_memalign((void **)&_ptr, (alignment), (size)); \
337 if (result != 0 || !_ptr) { \
338 FATAL(ERROR_MEMORY, "Aligned memory allocation failed: %zu bytes, %zu alignment", (size_t)(size), (size_t)(alignment)); \
339 } \
340 TRACK_ALIGNED_ALLOC(_ptr, (size), __FILE__, __LINE__); \
341 _ptr; \
342 })
343#else
344/* Linux/other platforms use aligned_alloc() (C11) */
345#define SAFE_MALLOC_ALIGNED(size, alignment, cast) \
346 ({ \
347 size_t aligned_size = (((size) + (alignment) - 1) / (alignment)) * (alignment); \
348 cast _ptr = (cast)aligned_alloc((alignment), aligned_size); \
349 if (!_ptr) { \
350 FATAL(ERROR_MEMORY, "Aligned memory allocation failed: %zu bytes, %zu alignment", aligned_size, (size_t)(alignment)); \
351 } \
352 TRACK_ALIGNED_ALLOC(_ptr, aligned_size, __FILE__, __LINE__); \
353 _ptr; \
354 })
355#endif
356#endif
357
358/* 16-byte aligned allocation for SIMD operations */
359#define SAFE_MALLOC_SIMD(size, cast) SAFE_MALLOC_ALIGNED(size, 16, cast)
360
361/* 16-byte aligned zero-initialized allocation */
362#define SAFE_CALLOC_SIMD(count, size, cast) \
363 ({ \
364 size_t total_size = (count) * (size); \
365 cast _ptr = SAFE_MALLOC_SIMD(total_size, cast); \
366 memset(_ptr, 0, total_size); \
367 _ptr; \
368 })
369
370/* Safe free that nulls the pointer - available in all builds */
371#define SAFE_FREE(ptr) \
372 do { \
373 if ((ptr) != NULL) { \
374 ALLOC_FREE((void *)(ptr)); \
375 (ptr) = NULL; \
376 } \
377 } while (0)
378
379/* These block declarations require the defer header and source transformer. */
380#define SAFE_MALLOC_DEFER_FREE(name, size, cast) \
381 cast name = SAFE_MALLOC(size, cast); \
382 defer(SAFE_FREE(name))
383#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast) \
384 cast name = SAFE_CALLOC(count, size, cast); \
385 defer(SAFE_FREE(name))
386
387/* Safe fclose that nulls the pointer - for use with defer() */
388/* Usage: defer(SAFE_FCLOSE(fp)); */
389#define SAFE_FCLOSE(fp) \
390 do { \
391 if ((fp) != NULL) { \
392 fclose(fp); \
393 (fp) = NULL; \
394 } \
395 } while (0)
396
397/* Untracked malloc/free - bypass memory tracking for special cases like mode_argv */
398/* These use raw malloc/free to avoid appearing in leak reports */
399#define UNTRACKED_MALLOC(size, cast) \
400 ({ \
401 cast _ptr = (cast)malloc(size); \
402 if (!_ptr) { \
403 FATAL(ERROR_MEMORY, "Memory allocation failed: %zu bytes", (size_t)(size)); \
404 } \
405 _ptr; \
406 })
407
408#define UNTRACKED_FREE(ptr) \
409 do { \
410 if ((ptr) != NULL) { \
411 free((void *)(ptr)); \
412 (ptr) = NULL; \
413 } \
414 } while (0)
415
416/* Safe string copy */
417#define SAFE_STRNCPY(dst, src, size) \
418 do { \
419 size_t _safe_strncpy_size = (size); \
420 if (_safe_strncpy_size > 0) { \
421 (void)platform_strncpy((dst), _safe_strncpy_size, (src), _safe_strncpy_size - 1); \
422 } \
423 } while (0)
424
425#include "asciichat_errno.h"
426/* Safe string duplication with memory tracking */
427#define SAFE_STRDUP(dst, src) \
428 do { \
429 if (src) { \
430 size_t _len = strlen(src) + 1; \
431 (dst) = SAFE_MALLOC(_len, char *); \
432 if (dst) { \
433 SAFE_MEMCPY((dst), _len, (src), _len); \
434 } else { \
435 SET_ERRNO(ERROR_MEMORY, "String duplication failed for: %s", (src)); \
436 } \
437 } else { \
438 (dst) = NULL; \
439 } \
440 } while (0)
441
442/* Platform-safe environment variable access */
443#define SAFE_GETENV(name) platform_getenv(name)
444
445/* Platform-safe sscanf (only used with numeric format specifiers) */
446#ifdef _WIN32
447#define SAFE_SSCANF(str, format, ...) sscanf_s(str, format, __VA_ARGS__)
448#else
449#define SAFE_SSCANF(str, format, ...) sscanf(str, format, __VA_ARGS__)
450#endif
451
452/* POSIX case-insensitive string comparison (Windows uses _stricmp/_strnicmp) */
453#ifdef _WIN32
454#include <string.h>
455#define strcasecmp _stricmp
456#define strncasecmp _strnicmp
457/* POSIX access() mode flags */
458#ifndef R_OK
459#define R_OK 4
460#endif
461#ifndef W_OK
462#define W_OK 2
463#endif
464#ifndef X_OK
465#define X_OK 0
466#endif
467#ifndef F_OK
468#define F_OK 0
469#endif
470#endif
471
472/* Platform-safe strerror */
473#include <libplatform/system.h>
474#define SAFE_STRERROR(errnum) platform_strerror(errnum)
475
476/* Safe memory functions */
477#define SAFE_MEMCPY(dest, dest_size, src, count) platform_memcpy((dest), (dest_size), (src), (count))
478#define SAFE_MEMSET(dest, dest_size, ch, count) platform_memset((dest), (dest_size), (ch), (count))
479#define SAFE_MEMMOVE(dest, dest_size, src, count) platform_memmove((dest), (dest_size), (src), (count))
480#define SAFE_STRCPY(dest, dest_size, src) platform_strcpy((dest), (dest_size), (src))
481
482/* ============================================================================
483 * Unaligned Memory Access Helpers (Backward Compatibility)
484 * ============================================================================
485 * NOTE: These functions have been moved to util/bytes.h
486 * This header includes util/bytes.h and provides backward compatibility
487 * macros for existing code using the old names.
488 */
489
490#include "util/bytes.h"
491
492/* Backward compatibility aliases for existing code */
493#define read_u16_unaligned bytes_read_u16_unaligned
494#define read_u32_unaligned bytes_read_u32_unaligned
495#define write_u16_unaligned bytes_write_u16_unaligned
496#define write_u32_unaligned bytes_write_u32_unaligned
497#define safe_size_mul bytes_safe_size_mul
498
499/* Safe string formatting */
500// clang-format off
501#define SAFE_SNPRINTF(buffer, buffer_size, ...) (size_t)safe_snprintf((buffer), (buffer_size), __VA_ARGS__)
502// clang-format on
503
510#define SAFE_BUFFER_SIZE(buffer_size, offset) ((offset) < 0 || (size_t)(offset) >= (buffer_size) ? 0 : (buffer_size) - (size_t)(offset))
511
512/* ============================================================================
513 * Thread Creation and Synchronization Macros
514 * ============================================================================ */
515
530#define THREAD_CREATE_OR_RETURN(thread, func, arg) \
531 do { \
532 if (platform_thread_create(&(thread), (func), (arg)) != 0) { \
533 log_error("Failed to create thread: %s", #func); \
534 return -1; \
535 } \
536 } while (0)
537
550#define MUTEX_INIT_OR_RETURN(m) \
551 do { \
552 if (mutex_init(&(m)) != 0) { \
553 log_error("Failed to initialize mutex: %s", #m); \
554 return -1; \
555 } \
556 } while (0)
557
558/* Include logging.h to provide logging macros to all files that include common.h */
559#include "log/log.h" // IWYU pragma: keep
560
562
563/* ============================================================================
564 * Shared Initialization
565 * ============================================================================
566 * Common initialization code shared between client and server modes.
567 * This function handles platform setup, logging, owned buffers, cleanup
568 * registration, and other shared initialization tasks.
569 */
570
594#ifdef __cplusplus
595extern "C" {
596#endif
597asciichat_error_t asciichat_shared_init(const char *log_file, bool is_client, bool quiet_startup);
598#ifdef __cplusplus
599}
600#endif
601
616void asciichat_shared_destroy(void);
617
618/* ============================================================================
619 * Error Handling Macros
620 * ============================================================================
621 * Macros for common error handling patterns to reduce code duplication
622 */
623
643#define ASCIICHAT_CHECK_AND_LOG(expr, ok_value, msg, ...) \
644 do { \
645 if ((expr) != (ok_value)) { \
646 log_error(msg, ##__VA_ARGS__); \
647 return (expr); \
648 } \
649 } while (0)
650
651/* ============================================================================
652 * Global Variables for Early Argv Inspection and Color Flag Detection
653 * ============================================================================ */
654
659#ifdef __cplusplus
660extern "C" {
661#endif
662
663extern ASCIICHAT_API int g_argc;
664
669extern ASCIICHAT_API char **g_argv;
670
676
682
683#ifdef __cplusplus
684}
685#endif
686
DLL export/import macros for cross-platform symbol visibility.
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
Common buffer size definitions.
🔢 Byte-Level Access and Arithmetic Utilities
Application limits and constraints.
Error and exit codes - unified status values (0-255).
unsigned short uint16_t
void asciichat_fatal_with_context(asciichat_error_t code, const char *file, int line, const char *function, const char *format,...)
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
unsigned int uint32_t
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
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
unsigned long long uint64_t
unsigned char uint8_t
void asciichat_shared_destroy(void)
Clean up shared library subsystems.
Definition common.c:219
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:687
#define ASCIICHAT_API
Export symbols on Unix platforms (Linux, macOS).
Definition api.h:86
📝 Logging API with multiple log levels and terminal output control
Logging rate limit constants (in microseconds).
Protocol version, features, compression, and frame flag constants.
Shutdown check system for clean library/application separation.
🔤 String Manipulation and Shell Escaping Utilities
String literal constants.