Coverage Report

Created: 2026-02-01 10:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/c-toxcore/toxcore/logger.c
Line
Count
Source
1
/* SPDX-License-Identifier: GPL-3.0-or-later
2
 * Copyright © 2016-2025 The TokTok team.
3
 * Copyright © 2013-2015 Tox project.
4
 */
5
6
/**
7
 * Text logging abstraction.
8
 */
9
#include "logger.h"
10
11
#include <assert.h>
12
#include <stdarg.h>
13
#include <stdio.h>
14
#include <stdlib.h>
15
#include <string.h>
16
17
#include "ccompat.h"
18
#include "mem.h"
19
20
struct Logger {
21
    const Memory *_Nonnull mem;
22
23
    logger_cb *_Nullable callback;
24
    void *_Nullable context;
25
    void *_Nullable userdata;
26
};
27
28
/*
29
 * Public Functions
30
 */
31
32
Logger *logger_new(const Memory *mem)
33
2.08k
{
34
2.08k
    Logger *log = (Logger *)mem_alloc(mem, sizeof(Logger));
35
36
2.08k
    if (log == nullptr) {
37
4
        return nullptr;
38
4
    }
39
40
2.08k
    log->mem = mem;
41
42
2.08k
    return log;
43
2.08k
}
44
45
void logger_kill(Logger *log)
46
2.08k
{
47
2.08k
    if (log == nullptr) {
48
0
        return;
49
0
    }
50
51
2.08k
    mem_delete(log->mem, log);
52
2.08k
}
53
54
void logger_callback_log(Logger *log, logger_cb *function, void *context, void *userdata)
55
1.58k
{
56
1.58k
    assert(log != nullptr);
57
1.58k
    log->callback = function;
58
1.58k
    log->context  = context;
59
1.58k
    log->userdata = userdata;
60
1.58k
}
61
62
void logger_write(const Logger *log, Logger_Level level, const char *file, uint32_t line, const char *func,
63
                  const char *format, ...)
64
81.6k
{
65
81.6k
    if (log == nullptr) {
66
0
        return;
67
0
    }
68
69
81.6k
    if (log->callback == nullptr) {
70
1.97k
        return;
71
1.97k
    }
72
73
    // Only pass the file name, not the entire file path, for privacy reasons.
74
    // The full path may contain PII of the person compiling toxcore (their
75
    // username and directory layout).
76
79.7k
    const char *filename = strrchr(file, '/');
77
79.7k
    if (filename != nullptr) {
78
79.7k
        file = &filename[1];
79
79.7k
    }
80
#if defined(_WIN32) || defined(__CYGWIN__)
81
    // On Windows, the path separator *may* be a backslash, so we look for that
82
    // one too.
83
    const char *windows_filename = strrchr(file, '\\');
84
    file = windows_filename != nullptr ? windows_filename + 1 : file;
85
#endif /* WIN32 */
86
87
    // Format message
88
79.7k
    char msg[1024];
89
79.7k
    va_list args;
90
79.7k
    va_start(args, format);
91
79.7k
    vsnprintf(msg, sizeof(msg), format, args);
92
79.7k
    va_end(args);
93
94
79.7k
    log->callback(log->context, level, file, line, func, msg, log->userdata);
95
79.7k
}
96
97
void logger_abort(void)
98
0
{
99
0
    abort();
100
0
}