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