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