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 #if defined(__APPLE__)
25 #include <sys/types.h>
26 #include <sys/sysctl.h>
27 #endif
28 
29 #include "util.h"
30 #include "log.h"
31 #include "i3.h"
32 #include "libi3.h"
33 #include "shmlog.h"
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  ELOG("Could not initialize errorlog\n");
85  else {
86  errorfile = fopen(errorfilename, "w");
87  if (fcntl(fileno(errorfile), F_SETFD, FD_CLOEXEC)) {
88  ELOG("Could not set close-on-exec flag\n");
89  }
90  }
91  }
92 
93  /* If this is a debug build (not a release version), we will enable SHM
94  * logging by default, unless the user turned it off explicitly. */
95  if (logbuffer == NULL && shmlog_size > 0) {
96  /* Reserve 1% of the RAM for the logfile, but at max 25 MiB.
97  * For 512 MiB of RAM this will lead to a 5 MiB log buffer.
98  * At the moment (2011-12-10), no testcase leads to an i3 log
99  * of more than ~ 600 KiB. */
100  long long physical_mem_bytes;
101 #if defined(__APPLE__)
102  int mib[2] = { CTL_HW, HW_MEMSIZE };
103  size_t length = sizeof(long long);
104  sysctl(mib, 2, &physical_mem_bytes, &length, NULL, 0);
105 #else
106  physical_mem_bytes = (long long)sysconf(_SC_PHYS_PAGES) *
107  sysconf(_SC_PAGESIZE);
108 #endif
109  logbuffer_size = min(physical_mem_bytes * 0.01, shmlog_size);
110  sasprintf(&shmlogname, "/i3-log-%d", getpid());
111  logbuffer_shm = shm_open(shmlogname, O_RDWR | O_CREAT, S_IREAD | S_IWRITE);
112  if (logbuffer_shm == -1) {
113  ELOG("Could not shm_open SHM segment for the i3 log: %s\n", strerror(errno));
114  return;
115  }
116 
117  if (ftruncate(logbuffer_shm, logbuffer_size) == -1) {
118  close(logbuffer_shm);
119  shm_unlink("/i3-log-");
120  ELOG("Could not ftruncate SHM segment for the i3 log: %s\n", strerror(errno));
121  return;
122  }
123 
124  logbuffer = mmap(NULL, logbuffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, logbuffer_shm, 0);
125  if (logbuffer == MAP_FAILED) {
126  close(logbuffer_shm);
127  shm_unlink("/i3-log-");
128  ELOG("Could not mmap SHM segment for the i3 log: %s\n", strerror(errno));
129  logbuffer = NULL;
130  return;
131  }
132 
133  /* Initialize with 0-bytes, just to be sure… */
134  memset(logbuffer, '\0', logbuffer_size);
135 
136  header = (i3_shmlog_header*)logbuffer;
137 
138  pthread_condattr_t cond_attr;
139  pthread_condattr_init(&cond_attr);
140  if (pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED) != 0)
141  ELOG("pthread_condattr_setpshared() failed, i3-dump-log -f will not work!\n");
142  pthread_cond_init(&(header->condvar), &cond_attr);
143 
144  logwalk = logbuffer + sizeof(i3_shmlog_header);
147  }
148  atexit(purge_zerobyte_logfile);
149 }
150 
151 /*
152  * Set verbosity of i3. If verbose is set to true, informative messages will
153  * be printed to stdout. If verbose is set to false, only errors will be
154  * printed.
155  *
156  */
157 void set_verbosity(bool _verbose) {
158  verbose = _verbose;
159 }
160 
161 /*
162  * Set debug logging.
163  *
164  */
165 void set_debug_logging(const bool _debug_logging) {
166  debug_logging = _debug_logging;
167 }
168 
169 /*
170  * Logs the given message to stdout (if print is true) while prefixing the
171  * current time to it. Additionally, the message will be saved in the i3 SHM
172  * log if enabled.
173  * This is to be called by *LOG() which includes filename/linenumber/function.
174  *
175  */
176 static void vlog(const bool print, const char *fmt, va_list args) {
177  /* Precisely one page to not consume too much memory but to hold enough
178  * data to be useful. */
179  static char message[4096];
180  static struct tm result;
181  static time_t t;
182  static struct tm *tmp;
183  static size_t len;
184 
185  /* Get current time */
186  t = time(NULL);
187  /* Convert time to local time (determined by the locale) */
188  tmp = localtime_r(&t, &result);
189  /* Generate time prefix */
190  len = strftime(message, sizeof(message), "%x %X - ", tmp);
191 
192  /*
193  * logbuffer print
194  * ----------------
195  * true true format message, save, print
196  * true false format message, save
197  * false true print message only
198  * false false INVALID, never called
199  */
200  if (!logbuffer) {
201 #ifdef DEBUG_TIMING
202  struct timeval tv;
203  gettimeofday(&tv, NULL);
204  printf("%s%d.%d - ", message, tv.tv_sec, tv.tv_usec);
205 #else
206  printf("%s", message);
207 #endif
208  vprintf(fmt, args);
209  } else {
210  len += vsnprintf(message + len, sizeof(message) - len, fmt, args);
211  if (len >= sizeof(message)) {
212  fprintf(stderr, "BUG: single log message > 4k\n");
213  }
214 
215  /* If there is no space for the current message in the ringbuffer, we
216  * need to wrap and write to the beginning again. */
217  if (len >= (logbuffer_size - (logwalk - logbuffer))) {
219  logwalk = logbuffer + sizeof(i3_shmlog_header);
221  header->wrap_count++;
222  }
223 
224  /* Copy the buffer, move the write pointer to the byte after our
225  * current message. */
226  strncpy(logwalk, message, len);
227  logwalk += len;
228 
230 
231  /* Wake up all (i3-dump-log) processes waiting for condvar. */
232  pthread_cond_broadcast(&(header->condvar));
233 
234  if (print)
235  fwrite(message, len, 1, stdout);
236  }
237 }
238 
239 /*
240  * Logs the given message to stdout while prefixing the current time to it,
241  * but only if verbose mode is activated.
242  *
243  */
244 void verboselog(char *fmt, ...) {
245  va_list args;
246 
247  if (!logbuffer && !verbose)
248  return;
249 
250  va_start(args, fmt);
251  vlog(verbose, fmt, args);
252  va_end(args);
253 }
254 
255 /*
256  * Logs the given message to stdout while prefixing the current time to it.
257  *
258  */
259 void errorlog(char *fmt, ...) {
260  va_list args;
261 
262  va_start(args, fmt);
263  vlog(true, fmt, args);
264  va_end(args);
265 
266  /* also log to the error logfile, if opened */
267  va_start(args, fmt);
268  vfprintf(errorfile, fmt, args);
269  fflush(errorfile);
270  va_end(args);
271 }
272 
273 /*
274  * Logs the given message to stdout while prefixing the current time to it,
275  * but only if debug logging was activated.
276  * This is to be called by DLOG() which includes filename/linenumber
277  *
278  */
279 void debuglog(char *fmt, ...) {
280  va_list args;
281 
282  if (!logbuffer && !(debug_logging))
283  return;
284 
285  va_start(args, fmt);
286  vlog(debug_logging, fmt, args);
287  va_end(args);
288 }
289 
290 /*
291  * Deletes the unused log files. Useful if i3 exits immediately, eg.
292  * because --get-socketpath was called. We don't care for syscall
293  * failures. This function is invoked automatically when exiting.
294  */
296  struct stat st;
297  char *slash;
298 
299  if (!errorfilename)
300  return;
301 
302  /* don't delete the log file if it contains something */
303  if ((stat(errorfilename, &st)) == -1 || st.st_size > 0)
304  return;
305 
306  if (unlink(errorfilename) == -1)
307  return;
308 
309  if ((slash = strrchr(errorfilename, '/')) != NULL) {
310  *slash = '\0';
311  /* possibly fails with ENOTEMPTY if there are files (or
312  * sockets) left. */
313  rmdir(errorfilename);
314  }
315 }