]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/debug.h
Use char const * instead of const char *.
[coloredstderr/coloredstderr.git] / src / debug.h
1 /*
2  * Debug functions.
3  *
4  * Copyright (C) 2013  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifndef DEBUG_H
21 #define DEBUG_H 1
22
23 static void debug_write(int fd, int first_call, char const *format, va_list ap) {
24     char buffer[1024];
25
26     int written = vsnprintf(buffer, sizeof(buffer), format, ap);
27     /* Overflow. */
28     if ((size_t)written >= sizeof(buffer)) {
29         written = sizeof(buffer) - 1;
30     }
31
32     /* Make sure these functions are loaded. */
33     DLSYM_FUNCTION(real_write, "write");
34     DLSYM_FUNCTION(real_close, "close");
35
36     if (first_call) {
37         char nl = '\n';
38         real_write(fd, &nl, 1);
39     }
40     real_write(fd, buffer, (size_t)written);
41     real_close(fd);
42 }
43
44 static void debug(char const *format, ...) {
45     va_list ap;
46
47     /* If the file doesn't exist, do nothing. Prevents writing log files in
48      * unexpected places. The user must create the file manually. */
49     int fd = open(DEBUG_FILE, O_WRONLY | O_APPEND);
50     if (fd == -1) {
51         return;
52     }
53
54     static int call_count = 0;
55     call_count++;
56
57     va_start(ap, format);
58     debug_write(fd, call_count == 1, format, ap);
59     va_end(ap);
60 }
61
62 static void warning(char const *format, ...) {
63     va_list ap;
64
65     char *home = getenv("HOME");
66     if (!home) {
67         return;
68     }
69
70     char path[strlen(home) + 1 + strlen(WARNING_FILE) + 1];
71     strcpy(path, home);
72     strcat(path, "/");
73     strcat(path, WARNING_FILE);
74
75     /* Create the warning file if it doesn't exist yet. */
76     int fd = open(path, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
77     if (fd == -1) {
78         return;
79     }
80
81     static int call_count = 0;
82     call_count++;
83
84     va_start(ap, format);
85     debug_write(fd, call_count == 1, format, ap);
86     va_end(ap);
87 }
88
89 #endif