Coverage Report

Created: 2025-04-02 10:29

/src/c-toxcore/toxcore/logger.c
Line
Count
Source (jump to first uncovered line)
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 *mem;
22
23
    logger_cb *callback;
24
    void *context;
25
    void *userdata;
26
};
27
28
/*
29
 * Public Functions
30
 */
31
32
Logger *logger_new(const Memory *mem)
33
2.32k
{
34
2.32k
    Logger *log = (Logger *)mem_alloc(mem, sizeof(Logger));
35
36
2.32k
    if (log == nullptr) {
37
4
        return nullptr;
38
4
    }
39
40
2.32k
    log->mem = mem;
41
42
2.32k
    return log;
43
2.32k
}
44
45
void logger_kill(Logger *log)
46
2.32k
{
47
2.32k
    if (log == nullptr) {
48
0
        return;
49
0
    }
50
51
2.32k
    mem_delete(log->mem, log);
52
2.32k
}
53
54
void logger_callback_log(Logger *log, logger_cb *function, void *context, void *userdata)
55
1.78k
{
56
1.78k
    assert(log != nullptr);
57
1.78k
    log->callback = function;
58
1.78k
    log->context  = context;
59
1.78k
    log->userdata = userdata;
60
1.78k
}
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
85.9k
{
65
85.9k
    if (log == nullptr) {
66
0
        return;
67
0
    }
68
69
85.9k
    if (log->callback == nullptr) {
70
5.65k
        return;
71
5.65k
    }
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
80.3k
    const char *filename = strrchr(file, '/');
77
80.3k
    file = filename != nullptr ? filename + 1 : file;
78
#if defined(_WIN32) || defined(__CYGWIN__)
79
    // On Windows, the path separator *may* be a backslash, so we look for that
80
    // one too.
81
    const char *windows_filename = strrchr(file, '\\');
82
    file = windows_filename != nullptr ? windows_filename + 1 : file;
83
#endif /* WIN32 */
84
85
    // Format message
86
80.3k
    char msg[1024];
87
80.3k
    va_list args;
88
80.3k
    va_start(args, format);
89
80.3k
    vsnprintf(msg, sizeof(msg), format, args);
90
80.3k
    va_end(args);
91
92
80.3k
    log->callback(log->context, level, file, line, func, msg, log->userdata);
93
80.3k
}
94
95
void logger_abort(void)
96
0
{
97
0
    abort();
98
0
}