summaryrefslogtreecommitdiff
path: root/dev-libs/libaaruformat/files/replace-slog-logger.patch
blob: b27af551765653f701f727da7bab3f3f245d0048 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
From 79a244c9719b37b7b9d281a907db1e4fae5858e9 Mon Sep 17 00:00:00 2001
From: Natalia Portillo <claunia@claunia.com>
Date: Tue, 13 Oct 2026 15:25:05 +0100
Subject: [PATCH] Replace slog with an in-house TRACE/FATAL logger.

The slog upstream repository no longer exists. The library only used
slog_trace/slog_fatal and slog_init, so a small internal logger in
src/log.c replaces it: printf-style, line-atomic output to stderr or to
the file named by AARUFORMAT_LOG_FILE, runtime filtering through
AARUFORMAT_LOG_LEVEL (trace, fatal, none), and lazy one-time
initialization that also covers aaruf_create().

The CMake option is now AARU_ENABLE_LOGGING; USE_SLOG remains as a
deprecated alias. log.h now includes inttypes.h, which several sources
relied on slog.h to provide for PRIu64.
---
 CMakeLists.txt |  36 +++-----
 include/log.h  |  79 ++++++++++++-----
 src/log.c      | 236 +++++++++++++++++++++++++++++++++++++++++++++++++
 src/open.c     |   8 --
 4 files changed, 307 insertions(+), 52 deletions(-)
 create mode 100644 src/log.c

diff --git a/CMakeLists.txt b/CMakeLists.txt
index cb2e453e..c9c32b08 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -55,8 +55,14 @@ endif()
 
 project(libaaruformat C)
 
-# Option to enable slog logging (disabled by default)
-option(USE_SLOG "Enable slog logging" OFF)
+# Option to enable TRACE/FATAL debug logging (disabled by default)
+option(AARU_ENABLE_LOGGING "Enable TRACE/FATAL debug logging" OFF)
+
+# Deprecated alias kept for existing build scripts
+if(USE_SLOG)
+  message(WARNING "USE_SLOG is deprecated, use AARU_ENABLE_LOGGING instead")
+  set(AARU_ENABLE_LOGGING ON CACHE BOOL "Enable TRACE/FATAL debug logging" FORCE)
+endif()
 
 # Option to enable address sanitizer (disabled by default)
 option(USE_ASAN "Enable address sanitizer" OFF)
@@ -270,6 +276,7 @@ add_library(aaruformat
             src/options.c
             src/create.c
             src/time.c
+            src/log.c
             src/write.c
             include/log.h
             src/ddt/hash_map.c
@@ -365,27 +372,12 @@ else()
   set_property(TARGET aaruformat PROPERTY POSITION_INDEPENDENT_CODE FALSE)
 endif()
 
-# Add slog submodule
-if(POLICY CMP0000)
-  cmake_policy(VERSION 3.5)
-endif()
-
-# Conditionally enable slog logging
-if(USE_SLOG)
-  add_subdirectory(3rdparty/slog)
-
-  # Include slog headers
-  target_include_directories(aaruformat PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/slog/src)
-
-  # Enable TRACE and slog output
-  target_compile_definitions(aaruformat PRIVATE ENABLE_TRACE ENABLE_FATAL USE_SLOG)
-
-  # Link slog
-  target_link_libraries(aaruformat slog)
-
-  message(STATUS "slog logging enabled")
+# Conditionally enable debug logging
+if(AARU_ENABLE_LOGGING)
+  target_compile_definitions(aaruformat PRIVATE ENABLE_TRACE ENABLE_FATAL)
+  message(STATUS "Debug logging enabled")
 else()
-  message(STATUS "slog logging disabled (enable with -DUSE_SLOG=ON)")
+  message(STATUS "Debug logging disabled (enable with -DAARU_ENABLE_LOGGING=ON)")
 endif()
 
 # Check for math library
diff --git a/include/log.h b/include/log.h
index be02428e..3c854658 100644
--- a/include/log.h
+++ b/include/log.h
@@ -1,43 +1,78 @@
-//
-// Created by claunia on 13/8/25.
-//
+/*
+ * This file is part of the Aaru Data Preservation Suite.
+ * Copyright (c) 2019-2026 Natalia Portillo.
+ *
+ * This library is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
 
 #ifndef LIBAARUFORMAT_LOG_H
 #define LIBAARUFORMAT_LOG_H
 
+/*
+ * Internal debug logging.
+ *
+ * TRACE and FATAL compile to nothing unless ENABLE_TRACE / ENABLE_FATAL are defined
+ * (CMake: -DAARU_ENABLE_LOGGING=ON). When enabled, output goes to stderr unless the
+ * AARUFORMAT_LOG_FILE environment variable names a file to append to, and the
+ * AARUFORMAT_LOG_LEVEL environment variable (trace, fatal, none) filters it at runtime.
+ *
+ * Never log key material.
+ */
+
+#include <inttypes.h>  // PRIu64 and friends, used throughout log format strings
 #include <stdarg.h>
 #include <stdio.h>
 
-// Uncomment to enable tracing
-// #define ENABLE_TRACE
-// Uncomment to use slog instead of stderr
-// #define USE_SLOG
-
-#ifdef ENABLE_TRACE
-#ifdef USE_SLOG
-#include "slog.h"
+#define AARU_LOG_FATAL 0
+#define AARU_LOG_TRACE 1
 
-#define TRACE(fmt, ...) slog_trace(fmt, ##__VA_ARGS__)
+#if defined(__GNUC__) || defined(__clang__)
+#define AARU_LOG_PRINTF_ATTR    __attribute__((format(printf, 5, 6)))
+#if !defined(_WIN32) && !defined(__CYGWIN__)
+#define AARU_LOG_VISIBILITY_ATTR __attribute__((visibility("hidden")))
 #else
-#define TRACE(fmt, ...) fprintf(stderr, "[TRACE] %s:%d:%s(): " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
+#define AARU_LOG_VISIBILITY_ATTR
 #endif
 #else
-#define TRACE(fmt, ...)
+#define AARU_LOG_PRINTF_ATTR
+#define AARU_LOG_VISIBILITY_ATTR
 #endif
 
-#include <stdarg.h>
-#include <stdio.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
 
-#ifdef ENABLE_FATAL
-#ifdef USE_SLOG
-#include "slog.h"
+void aaru_log_write(int level, const char *file, int line, const char *func, const char *fmt,
+                    ...) AARU_LOG_PRINTF_ATTR AARU_LOG_VISIBILITY_ATTR;
 
-#define FATAL(fmt, ...) slog_fatal(fmt, ##__VA_ARGS__)
+/* Closes any log file and forgets the configuration so the environment is read again. Used by tests. */
+void aaru_log_reset(void) AARU_LOG_VISIBILITY_ATTR;
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef ENABLE_TRACE
+#define TRACE(fmt, ...) aaru_log_write(AARU_LOG_TRACE, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
 #else
-#define FATAL(fmt, ...) fprintf(stderr, "[FATAL] %s:%d:%s(): " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
+#define TRACE(fmt, ...) ((void)0)
 #endif
+
+#ifdef ENABLE_FATAL
+#define FATAL(fmt, ...) aaru_log_write(AARU_LOG_FATAL, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
 #else
-#define FATAL(fmt, ...)
+#define FATAL(fmt, ...) ((void)0)
 #endif
 
 #endif  // LIBAARUFORMAT_LOG_H
diff --git a/src/log.c b/src/log.c
new file mode 100644
index 00000000..c9f93bdd
--- /dev/null
+++ b/src/log.c
@@ -0,0 +1,236 @@
+/*
+ * This file is part of the Aaru Data Preservation Suite.
+ * Copyright (c) 2019-2026 Natalia Portillo.
+ *
+ * This library is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE)
+#define _POSIX_C_SOURCE 200112L  // localtime_r
+#endif
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <sys/time.h>
+#endif
+
+#include "log.h"
+
+#define LOG_STATE_UNINITIALIZED 0
+#define LOG_STATE_INITIALIZING  1
+#define LOG_STATE_READY         2
+
+#define LOG_LEVEL_NONE (-1)
+
+#define LOG_STACK_BUFFER_SIZE 1024
+
+static volatile long log_state  = LOG_STATE_UNINITIALIZED;
+static FILE         *log_stream = NULL;
+static int           log_level  = AARU_LOG_TRACE;
+
+/* Minimal portable atomics so the one-time initialization is race-free without pthreads. */
+#if defined(_MSC_VER)
+static int  log_state_claim(void) { return InterlockedCompareExchange(&log_state, LOG_STATE_INITIALIZING, LOG_STATE_UNINITIALIZED) == LOG_STATE_UNINITIALIZED; }
+static long log_state_load(void) { return InterlockedCompareExchange(&log_state, 0, 0); }
+static void log_state_store(long value) { InterlockedExchange(&log_state, value); }
+#elif defined(__GNUC__) || defined(__clang__)
+static int log_state_claim(void)
+{
+    long expected = LOG_STATE_UNINITIALIZED;
+    return __atomic_compare_exchange_n(&log_state, &expected, LOG_STATE_INITIALIZING, 0, __ATOMIC_ACQ_REL,
+                                       __ATOMIC_ACQUIRE);
+}
+static long log_state_load(void) { return __atomic_load_n(&log_state, __ATOMIC_ACQUIRE); }
+static void log_state_store(long value) { __atomic_store_n(&log_state, value, __ATOMIC_RELEASE); }
+#else
+static int log_state_claim(void)
+{
+    if(log_state != LOG_STATE_UNINITIALIZED) return 0;
+    log_state = LOG_STATE_INITIALIZING;
+    return 1;
+}
+static long log_state_load(void) { return log_state; }
+static void log_state_store(long value) { log_state = value; }
+#endif
+
+static int log_strcasecmp(const char *a, const char *b)
+{
+    while(*a && *b)
+    {
+        int ca = (unsigned char)*a++;
+        int cb = (unsigned char)*b++;
+        if(ca >= 'A' && ca <= 'Z') ca += 'a' - 'A';
+        if(cb >= 'A' && cb <= 'Z') cb += 'a' - 'A';
+        if(ca != cb) return ca - cb;
+    }
+    return (unsigned char)*a - (unsigned char)*b;
+}
+
+/**
+ * @brief Resolves the logging configuration from the environment, exactly once per process.
+ *
+ * AARUFORMAT_LOG_LEVEL selects "trace" (default), "fatal" or "none".
+ * AARUFORMAT_LOG_FILE names a file to append to; if unset or unopenable, stderr is used.
+ */
+static void log_init(void)
+{
+    const char *level_env;
+    const char *file_env;
+
+    if(log_state_load() == LOG_STATE_READY) return;
+
+    if(!log_state_claim())
+    {
+        // Another thread is initializing; the window is a getenv() and an fopen().
+        while(log_state_load() != LOG_STATE_READY);
+        return;
+    }
+
+    level_env = getenv("AARUFORMAT_LOG_LEVEL");
+    if(level_env != NULL)
+    {
+        if(log_strcasecmp(level_env, "none") == 0 || log_strcasecmp(level_env, "off") == 0)
+            log_level = LOG_LEVEL_NONE;
+        else if(log_strcasecmp(level_env, "fatal") == 0)
+            log_level = AARU_LOG_FATAL;
+        else
+            log_level = AARU_LOG_TRACE;
+    }
+
+    log_stream = stderr;
+    file_env   = getenv("AARUFORMAT_LOG_FILE");
+    if(file_env != NULL && *file_env != '\0' && log_level != LOG_LEVEL_NONE)
+    {
+        FILE *file = fopen(file_env, "a");
+        if(file != NULL) log_stream = file;
+    }
+
+    log_state_store(LOG_STATE_READY);
+}
+
+/** @brief Strips the build-machine directory from __FILE__, keeping the path below src/ if present. */
+static const char *log_short_path(const char *file)
+{
+    const char *p;
+    const char *base = file;
+
+    for(p = file; *p; p++)
+    {
+        if((*p == '/' || *p == '\\') && strncmp(p + 1, "src", 3) == 0 && (p[4] == '/' || p[4] == '\\'))
+            base = p + 5;
+    }
+
+    if(base != file) return base;
+
+    for(p = file; *p; p++)
+        if(*p == '/' || *p == '\\') base = p + 1;
+
+    return base;
+}
+
+static int log_timestamp(char *buf, size_t size)
+{
+#ifdef _WIN32
+    SYSTEMTIME st;
+    GetLocalTime(&st);
+    return snprintf(buf, size, "%02u:%02u:%02u.%03u", st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
+#else
+    struct timeval tv;
+    struct tm      tm;
+    time_t         secs;
+
+    gettimeofday(&tv, NULL);
+    secs = tv.tv_sec;
+    if(localtime_r(&secs, &tm) == NULL) return snprintf(buf, size, "??:??:??.???");
+    return snprintf(buf, size, "%02d:%02d:%02d.%03ld", tm.tm_hour, tm.tm_min, tm.tm_sec, (long)(tv.tv_usec / 1000));
+#endif
+}
+
+/**
+ * @brief Writes one log line. Called through the TRACE and FATAL macros in log.h.
+ *
+ * The whole line is formatted into a buffer and emitted with a single fwrite(), which stdio
+ * locks per call, so lines from concurrent threads do not interleave.
+ */
+void aaru_log_write(int level, const char *file, int line, const char *func, const char *fmt, ...)
+{
+    char        stack_buf[LOG_STACK_BUFFER_SIZE];
+    char       *buf = stack_buf;
+    char        timestamp[16];
+    const char *tag = level == AARU_LOG_FATAL ? "FATAL" : "TRACE";
+    int         prefix_len;
+    int         msg_len;
+    size_t      total;
+    va_list     args;
+    va_list     args_copy;
+
+    log_init();
+
+    if(level > log_level) return;
+
+    log_timestamp(timestamp, sizeof(timestamp));
+
+    prefix_len = snprintf(NULL, 0, "%s [%s] %s:%d %s(): ", timestamp, tag, log_short_path(file), line, func);
+
+    va_start(args, fmt);
+    va_copy(args_copy, args);
+    msg_len = vsnprintf(NULL, 0, fmt, args_copy);
+    va_end(args_copy);
+
+    if(prefix_len < 0 || msg_len < 0)
+    {
+        va_end(args);
+        return;
+    }
+
+    total = (size_t)prefix_len + (size_t)msg_len + 2;  // newline + terminator
+
+    if(total > sizeof(stack_buf))
+    {
+        buf = malloc(total);
+        if(buf == NULL)
+        {
+            va_end(args);
+            return;
+        }
+    }
+
+    snprintf(buf, total, "%s [%s] %s:%d %s(): ", timestamp, tag, log_short_path(file), line, func);
+    vsnprintf(buf + prefix_len, total - (size_t)prefix_len, fmt, args);
+    va_end(args);
+
+    buf[total - 2] = '\n';
+    buf[total - 1] = '\0';
+
+    fwrite(buf, 1, total - 1, log_stream);
+    fflush(log_stream);
+
+    if(buf != stack_buf) free(buf);
+}
+
+void aaru_log_reset(void)
+{
+    if(log_state_load() == LOG_STATE_READY && log_stream != NULL && log_stream != stderr) fclose(log_stream);
+
+    log_stream = NULL;
+    log_level  = AARU_LOG_TRACE;
+    log_state_store(LOG_STATE_UNINITIALIZED);
+}
diff --git a/src/open.c b/src/open.c
index 3bc4277c..837ed533 100644
--- a/src/open.c
+++ b/src/open.c
@@ -244,14 +244,6 @@ AARU_EXPORT void *AARU_CALL aaruf_open(const char *filepath, const bool resume_m
     uint32_t            signature     = 0;
     UT_array           *index_entries = NULL;
 
-#ifdef USE_SLOG
-#include "slog.h"
-
-    slog_init("aaruformat.log", SLOG_FLAGS_ALL, 0);
-#endif
-
-    TRACE("Logging initialized");
-
     TRACE("Entering aaruf_open(%s)", filepath);
     aaruf_set_open_error(0);