i3
log.c
Go to the documentation of this file.
1/*
2 * vim:ts=4:sw=4:expandtab
3 *
4 * i3 - an improved dynamic tiling window manager
5 * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6 *
7 * log.c: Logging functions.
8 *
9 */
10#include <config.h>
11
12#include <stdarg.h>
13#include <stdio.h>
14#include <string.h>
15#include <stdbool.h>
16#include <stdlib.h>
17#include <sys/time.h>
18#include <unistd.h>
19#include <fcntl.h>
20#include <sys/mman.h>
21#include <sys/stat.h>
22#include <errno.h>
23#if !defined(__OpenBSD__)
24#include <pthread.h>
25#endif
26
27#include "util.h"
28#include "log.h"
29#include "i3.h"
30#include "libi3.h"
31#include "shmlog.h"
32
33#if defined(__APPLE__)
34#include <sys/sysctl.h>
35#endif
36
37static bool debug_logging = false;
38static bool verbose = false;
39static FILE *errorfile;
41
42/* SHM logging variables */
43
44/* The name for the SHM (/i3-log-%pid). Will end up on /dev/shm on most
45 * systems. Global so that we can clean up at exit. */
46char *shmlogname = "";
47/* Size limit for the SHM log, by default 25 MiB. Can be overwritten using the
48 * flag --shmlog-size. */
50/* If enabled, logbuffer will point to a memory mapping of the i3 SHM log. */
51static char *logbuffer;
52/* A pointer (within logbuffer) where data will be written to next. */
53static char *logwalk;
54/* A pointer to the shmlog header */
56/* A pointer to the byte where we last wrapped. Necessary to not print the
57 * left-overs at the end of the ringbuffer. */
58static char *loglastwrap;
59/* Size (in bytes) of the i3 SHM log. */
60static int logbuffer_size;
61/* File descriptor for shm_open. */
62static int logbuffer_shm;
63/* Size (in bytes) of physical memory */
64static long long physical_mem_bytes;
65
66/*
67 * Writes the offsets for the next write and for the last wrap to the
68 * shmlog_header.
69 * Necessary to print the i3 SHM log in the correct order.
70 *
71 */
72static void store_log_markers(void) {
76}
77
78/*
79 * Initializes logging by creating an error logfile in /tmp (or
80 * XDG_RUNTIME_DIR, see get_process_filename()).
81 *
82 * Will be called twice if --shmlog-size is specified.
83 *
84 */
85void init_logging(void) {
86 if (!errorfilename) {
87 if (!(errorfilename = get_process_filename("errorlog")))
88 fprintf(stderr, "Could not initialize errorlog\n");
89 else {
90 errorfile = fopen(errorfilename, "w");
91 if (!errorfile) {
92 fprintf(stderr, "Could not initialize errorlog on %s: %s\n",
93 errorfilename, strerror(errno));
94 } else {
95 if (fcntl(fileno(errorfile), F_SETFD, FD_CLOEXEC)) {
96 fprintf(stderr, "Could not set close-on-exec flag\n");
97 }
98 }
99 }
100 }
101 if (physical_mem_bytes == 0) {
102#if defined(__APPLE__)
103 int mib[2] = {CTL_HW, HW_MEMSIZE};
104 size_t length = sizeof(long long);
105 sysctl(mib, 2, &physical_mem_bytes, &length, NULL, 0);
106#else
107 physical_mem_bytes = (long long)sysconf(_SC_PHYS_PAGES) *
108 sysconf(_SC_PAGESIZE);
109#endif
110 }
111 /* Start SHM logging if shmlog_size is > 0. shmlog_size is SHMLOG_SIZE by
112 * default on development versions, and 0 on release versions. If it is
113 * not > 0, the user has turned it off, so let's close the logbuffer. */
114 if (shmlog_size > 0 && logbuffer == NULL)
116 else if (shmlog_size <= 0 && logbuffer)
119}
120
121/*
122 * Opens the logbuffer.
123 *
124 */
125void open_logbuffer(void) {
126 /* Reserve 1% of the RAM for the logfile, but at max 25 MiB.
127 * For 512 MiB of RAM this will lead to a 5 MiB log buffer.
128 * At the moment (2011-12-10), no testcase leads to an i3 log
129 * of more than ~ 600 KiB. */
131#if defined(__FreeBSD__)
132 sasprintf(&shmlogname, "/tmp/i3-log-%d", getpid());
133#else
134 sasprintf(&shmlogname, "/i3-log-%d", getpid());
135#endif
136 logbuffer_shm = shm_open(shmlogname, O_RDWR | O_CREAT, S_IREAD | S_IWRITE);
137 if (logbuffer_shm == -1) {
138 fprintf(stderr, "Could not shm_open SHM segment for the i3 log: %s\n", strerror(errno));
139 return;
140 }
141
142#if defined(__OpenBSD__) || defined(__APPLE__)
143 if (ftruncate(logbuffer_shm, logbuffer_size) == -1) {
144 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(errno));
145#else
146 int ret;
147 if ((ret = posix_fallocate(logbuffer_shm, 0, logbuffer_size)) != 0) {
148 fprintf(stderr, "Could not ftruncate SHM segment for the i3 log: %s\n", strerror(ret));
149#endif
150 close(logbuffer_shm);
151 shm_unlink(shmlogname);
152 return;
153 }
154
155 logbuffer = mmap(NULL, logbuffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
156 if (logbuffer == MAP_FAILED) {
158 fprintf(stderr, "Could not mmap SHM segment for the i3 log: %s\n", strerror(errno));
159 return;
160 }
161
162 /* Initialize with 0-bytes, just to be sure… */
163 memset(logbuffer, '\0', logbuffer_size);
164
166
167#if !defined(__OpenBSD__)
168 pthread_condattr_t cond_attr;
169 pthread_condattr_init(&cond_attr);
170 if (pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED) != 0)
171 fprintf(stderr, "pthread_condattr_setpshared() failed, i3-dump-log -f will not work!\n");
172 pthread_cond_init(&(header->condvar), &cond_attr);
173#endif
174
178}
179
180/*
181 * Closes the logbuffer.
182 *
183 */
184void close_logbuffer(void) {
185 close(logbuffer_shm);
186 shm_unlink(shmlogname);
187 free(shmlogname);
188 logbuffer = NULL;
189 shmlogname = "";
190}
191
192/*
193 * Set verbosity of i3. If verbose is set to true, informative messages will
194 * be printed to stdout. If verbose is set to false, only errors will be
195 * printed.
196 *
197 */
198void set_verbosity(bool _verbose) {
199 verbose = _verbose;
200}
201
202/*
203 * Get debug logging.
204 *
205 */
207 return debug_logging;
208}
209
210/*
211 * Set debug logging.
212 *
213 */
214void set_debug_logging(const bool _debug_logging) {
215 debug_logging = _debug_logging;
216}
217
218/*
219 * Logs the given message to stdout (if print is true) while prefixing the
220 * current time to it. Additionally, the message will be saved in the i3 SHM
221 * log if enabled.
222 * This is to be called by *LOG() which includes filename/linenumber/function.
223 *
224 */
225static void vlog(const bool print, const char *fmt, va_list args) {
226 /* Precisely one page to not consume too much memory but to hold enough
227 * data to be useful. */
228 static char message[4096];
229 static struct tm result;
230 static time_t t;
231 static struct tm *tmp;
232 static size_t len;
233
234 /* Get current time */
235 t = time(NULL);
236 /* Convert time to local time (determined by the locale) */
237 tmp = localtime_r(&t, &result);
238 /* Generate time prefix */
239 len = strftime(message, sizeof(message), "%x %X - ", tmp);
240
241 /*
242 * logbuffer print
243 * ----------------
244 * true true format message, save, print
245 * true false format message, save
246 * false true print message only
247 * false false INVALID, never called
248 */
249 if (!logbuffer) {
250#ifdef DEBUG_TIMING
251 struct timeval tv;
252 gettimeofday(&tv, NULL);
253 printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
254#else
255 printf("%s", message);
256#endif
257 vprintf(fmt, args);
258 } else {
259 len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
260 if (len >= sizeof(message)) {
261 fprintf(stderr, "BUG: single log message > 4k\n");
262
263 /* vsnprintf returns the number of bytes that *would have been written*,
264 * not the actual amount written. Thus, limit len to sizeof(message) to avoid
265 * memory corruption and outputting garbage later. */
266 len = sizeof(message);
267
268 /* Punch in a newline so the next log message is not dangling at
269 * the end of the truncated message. */
270 message[len - 2] = '\n';
271 }
272
273 /* If there is no space for the current message in the ringbuffer, we
274 * need to wrap and write to the beginning again. */
275 if (len >= (size_t)(logbuffer_size - (logwalk - logbuffer))) {
280 }
281
282 /* Copy the buffer, move the write pointer to the byte after our
283 * current message. */
284 strncpy(logwalk, message, len);
285 logwalk += len;
286
288
289#if !defined(__OpenBSD__)
290 /* Wake up all (i3-dump-log) processes waiting for condvar. */
291 pthread_cond_broadcast(&(header->condvar));
292#endif
293
294 if (print)
295 fwrite(message, len, 1, stdout);
296 }
297}
298
299/*
300 * Logs the given message to stdout while prefixing the current time to it,
301 * but only if verbose mode is activated.
302 *
303 */
304void verboselog(char *fmt, ...) {
305 va_list args;
306
307 if (!logbuffer && !verbose)
308 return;
309
310 va_start(args, fmt);
311 vlog(verbose, fmt, args);
312 va_end(args);
313}
314
315/*
316 * Logs the given message to stdout while prefixing the current time to it.
317 *
318 */
319void errorlog(char *fmt, ...) {
320 va_list args;
321
322 va_start(args, fmt);
323 vlog(true, fmt, args);
324 va_end(args);
325
326 /* also log to the error logfile, if opened */
327 va_start(args, fmt);
328 vfprintf(errorfile, fmt, args);
329 fflush(errorfile);
330 va_end(args);
331}
332
333/*
334 * Logs the given message to stdout while prefixing the current time to it,
335 * but only if debug logging was activated.
336 * This is to be called by DLOG() which includes filename/linenumber
337 *
338 */
339void debuglog(char *fmt, ...) {
340 va_list args;
341
342 if (!logbuffer && !(debug_logging))
343 return;
344
345 va_start(args, fmt);
346 vlog(debug_logging, fmt, args);
347 va_end(args);
348}
349
350/*
351 * Deletes the unused log files. Useful if i3 exits immediately, eg.
352 * because --get-socketpath was called. We don't care for syscall
353 * failures. This function is invoked automatically when exiting.
354 */
356 struct stat st;
357 char *slash;
358
359 if (!errorfilename)
360 return;
361
362 /* don't delete the log file if it contains something */
363 if ((stat(errorfilename, &st)) == -1 || st.st_size > 0)
364 return;
365
366 if (unlink(errorfilename) == -1)
367 return;
368
369 if ((slash = strrchr(errorfilename, '/')) != NULL) {
370 *slash = '\0';
371 /* possibly fails with ENOTEMPTY if there are files (or
372 * sockets) left. */
373 rmdir(errorfilename);
374 }
375}
int min(int a, int b)
Definition: util.c:27
int shmlog_size
Definition: log.c:49
void errorlog(char *fmt,...)
Definition: log.c:319
void debuglog(char *fmt,...)
Definition: log.c:339
bool get_debug_logging(void)
Checks if debug logging is active.
Definition: log.c:206
static bool debug_logging
Definition: log.c:37
static int logbuffer_shm
Definition: log.c:62
void init_logging(void)
Initializes logging by creating an error logfile in /tmp (or XDG_RUNTIME_DIR, see get_process_filenam...
Definition: log.c:85
static int logbuffer_size
Definition: log.c:60
void set_debug_logging(const bool _debug_logging)
Set debug logging.
Definition: log.c:214
static char * logbuffer
Definition: log.c:51
static i3_shmlog_header * header
Definition: log.c:55
void open_logbuffer(void)
Opens the logbuffer.
Definition: log.c:125
void verboselog(char *fmt,...)
Definition: log.c:304
char * shmlogname
Definition: log.c:46
void set_verbosity(bool _verbose)
Set verbosity of i3.
Definition: log.c:198
void purge_zerobyte_logfile(void)
Deletes the unused log files.
Definition: log.c:355
static char * logwalk
Definition: log.c:53
char * errorfilename
Definition: log.c:40
static char * loglastwrap
Definition: log.c:58
static bool verbose
Definition: log.c:38
static void vlog(const bool print, const char *fmt, va_list args)
Definition: log.c:225
static long long physical_mem_bytes
Definition: log.c:64
static FILE * errorfile
Definition: log.c:39
static void store_log_markers(void)
Definition: log.c:72
void close_logbuffer(void)
Closes the logbuffer.
Definition: log.c:184
int sasprintf(char **strp, const char *fmt,...)
Safe-wrapper around asprintf which exits if it returns -1 (meaning that there is no more memory avail...
char * get_process_filename(const char *prefix)
Returns the name of a temporary file with the specified prefix.
Header of the shmlog file.
Definition: shmlog.h:27
uint32_t offset_last_wrap
Definition: shmlog.h:32
uint32_t offset_next_write
Definition: shmlog.h:29
uint32_t wrap_count
Definition: shmlog.h:42
pthread_cond_t condvar
Definition: shmlog.h:48
uint32_t size
Definition: shmlog.h:36