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