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