i3
sighandler.c
Go to the documentation of this file.
1 #undef I3__FILE__
2 #define I3__FILE__ "sighandler.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  * © 2009-2010 Jan-Erik Rediger
9  *
10  * sighandler.c: Interactive crash dialog upon SIGSEGV/SIGABRT/SIGFPE (offers
11  * to restart inplace).
12  *
13  */
14 #include "all.h"
15 
16 #include <ev.h>
17 #include <iconv.h>
18 #include <signal.h>
19 #include <sys/wait.h>
20 
21 #include <xcb/xcb_event.h>
22 
23 #include <X11/keysym.h>
24 
25 static void open_popups(void);
26 
27 static xcb_gcontext_t pixmap_gc;
28 static xcb_pixmap_t pixmap;
29 static int raised_signal;
30 
31 static char *crash_text[] = {
32  "i3 just crashed.",
33  "To debug this problem, either attach gdb now",
34  "or press",
35  "- 'b' to save a backtrace (needs GDB),",
36  "- 'r' to restart i3 in-place or",
37  "- 'f' to forget the current layout and restart"
38 };
39 static int crash_text_longest = 5;
40 static int backtrace_string_index = 3;
41 static int backtrace_done = 0;
42 
43 /*
44  * Attach gdb to pid_parent and dump a backtrace to i3-backtrace.$pid in the
45  * tmpdir
46  */
47 static int backtrace(void) {
48  char *tmpdir = getenv("TMPDIR");
49  if (tmpdir == NULL)
50  tmpdir = "/tmp";
51 
52  pid_t pid_parent = getpid();
53 
54  char *filename = NULL;
55  int suffix = 0;
56  struct stat bt;
57  /* Find a unique filename for the backtrace (since the PID of i3 stays the
58  * same), so that we don’t overwrite earlier backtraces. */
59  do {
60  FREE(filename);
61  sasprintf(&filename, "%s/i3-backtrace.%d.%d.txt", tmpdir, pid_parent, suffix);
62  suffix++;
63  } while (stat(filename, &bt) == 0);
64 
65  pid_t pid_gdb = fork();
66  if (pid_gdb < 0) {
67  DLOG("Failed to fork for GDB\n");
68  return -1;
69  } else if (pid_gdb == 0) {
70  /* child */
71  int stdin_pipe[2],
72  stdout_pipe[2];
73 
74  pipe(stdin_pipe);
75  pipe(stdout_pipe);
76 
77  /* close standard streams in case i3 is started from a terminal; gdb
78  * needs to run without controlling terminal for it to work properly in
79  * this situation */
80  close(STDIN_FILENO);
81  close(STDOUT_FILENO);
82  close(STDERR_FILENO);
83 
84  /* We provide pipe file descriptors for stdin/stdout because gdb < 7.5
85  * crashes otherwise, see
86  * http://sourceware.org/bugzilla/show_bug.cgi?id=14114 */
87  dup2(stdin_pipe[0], STDIN_FILENO);
88  dup2(stdout_pipe[1], STDOUT_FILENO);
89 
90  char *pid_s, *gdb_log_cmd;
91  sasprintf(&pid_s, "%d", pid_parent);
92  sasprintf(&gdb_log_cmd, "set logging file %s", filename);
93 
94  char *args[] = {
95  "gdb",
96  start_argv[0],
97  "-p",
98  pid_s,
99  "-batch",
100  "-nx",
101  "-ex", gdb_log_cmd,
102  "-ex", "set logging on",
103  "-ex", "bt full",
104  "-ex", "quit",
105  NULL
106  };
107  execvp(args[0], args);
108  DLOG("Failed to exec GDB\n");
109  exit(1);
110  }
111  int status = 0;
112 
113  waitpid(pid_gdb, &status, 0);
114 
115  /* see if the backtrace was succesful or not */
116  if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
117  DLOG("GDB did not run properly\n");
118  return -1;
119  } else if (stat(filename, &bt) == -1) {
120  DLOG("GDB executed successfully, but no backtrace was generated\n");
121  return -1;
122  }
123  return 1;
124 }
125 
126 /*
127  * Draw the window containing the info text
128  *
129  */
130 static int sig_draw_window(xcb_window_t win, int width, int height, int font_height, i3String **crash_text_i3strings) {
131  /* re-draw the background */
132  xcb_rectangle_t border = { 0, 0, width, height},
133  inner = { 2, 2, width - 4, height - 4};
134  xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#FF0000") });
135  xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &border);
136  xcb_change_gc(conn, pixmap_gc, XCB_GC_FOREGROUND, (uint32_t[]){ get_colorpixel("#000000") });
137  xcb_poly_fill_rectangle(conn, pixmap, pixmap_gc, 1, &inner);
138 
139  /* restore font color */
140  set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
141 
142  char *bt_colour = "#FFFFFF";
143  if (backtrace_done < 0)
144  bt_colour = "#AA0000";
145  else if (backtrace_done > 0)
146  bt_colour = "#00AA00";
147 
148  for (int i = 0; crash_text_i3strings[i] != NULL; ++i) {
149  /* fix the colour for the backtrace line when it finished */
150  if (i == backtrace_string_index)
151  set_font_colors(pixmap_gc, get_colorpixel(bt_colour), get_colorpixel("#000000"));
152 
153  draw_text(crash_text_i3strings[i], pixmap, pixmap_gc,
154  8, 5 + i * font_height, width - 16);
155 
156  /* and reset the colour again for other lines */
157  if (i == backtrace_string_index)
158  set_font_colors(pixmap_gc, get_colorpixel("#FFFFFF"), get_colorpixel("#000000"));
159  }
160 
161  /* Copy the contents of the pixmap to the real window */
162  xcb_copy_area(conn, pixmap, win, pixmap_gc, 0, 0, 0, 0, width, height);
163  xcb_flush(conn);
164 
165  return 1;
166 }
167 
168 /*
169  * Handles keypresses of 'b', 'r' and 'f' to get a backtrace or restart i3
170  *
171  */
172 static int sig_handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event) {
173  uint16_t state = event->state;
174 
175  /* Apparantly, after activating numlock once, the numlock modifier
176  * stays turned on (use xev(1) to verify). So, to resolve useful
177  * keysyms, we remove the numlock flag from the event state */
178  state &= ~xcb_numlock_mask;
179 
180  xcb_keysym_t sym = xcb_key_press_lookup_keysym(keysyms, event, state);
181 
182  if (sym == 'b') {
183  DLOG("User issued core-dump command.\n");
184 
185  /* fork and exec/attach GDB to the parent to get a backtrace in the
186  * tmpdir */
188 
189  /* re-open the windows to indicate that it's finished */
190  open_popups();
191  }
192 
193  if (sym == 'r')
194  i3_restart(false);
195 
196  if (sym == 'f')
197  i3_restart(true);
198 
199  return 1;
200 }
201 
202 /*
203  * Opens the window we use for input/output and maps it
204  *
205  */
206 static xcb_window_t open_input_window(xcb_connection_t *conn, Rect screen_rect, uint32_t width, uint32_t height) {
207  xcb_window_t win = xcb_generate_id(conn);
208 
209  uint32_t mask = 0;
210  uint32_t values[2];
211 
212  mask |= XCB_CW_BACK_PIXEL;
213  values[0] = 0;
214 
215  mask |= XCB_CW_OVERRIDE_REDIRECT;
216  values[1] = 1;
217 
218  /* center each popup on the specified screen */
219  uint32_t x = screen_rect.x + ((screen_rect.width / 2) - (width / 2)),
220  y = screen_rect.y + ((screen_rect.height / 2) - (height / 2));
221 
222  xcb_create_window(conn,
223  XCB_COPY_FROM_PARENT,
224  win, /* the window id */
225  root, /* parent == root */
226  x, y, width, height, /* dimensions */
227  0, /* border = 0, we draw our own */
228  XCB_WINDOW_CLASS_INPUT_OUTPUT,
229  XCB_WINDOW_CLASS_COPY_FROM_PARENT, /* copy visual from parent */
230  mask,
231  values);
232 
233  /* Map the window (= make it visible) */
234  xcb_map_window(conn, win);
235 
236  return win;
237 }
238 
239 static void open_popups() {
240  /* width and height of the popup window, so that the text fits in */
241  int crash_text_num = sizeof(crash_text) / sizeof(char*);
242  int height = 13 + (crash_text_num * config.font.height);
243 
244  int crash_text_length = sizeof(crash_text) / sizeof(char*);
245  i3String **crash_text_i3strings = smalloc(sizeof(i3String *) * (crash_text_length + 1));
246  /* Pre-compute i3Strings for our text */
247  for (int i = 0; i < crash_text_length; ++i) {
248  crash_text_i3strings[i] = i3string_from_utf8(crash_text[i]);
249  }
250  crash_text_i3strings[crash_text_length] = NULL;
251  /* calculate width for longest text */
252  int font_width = predict_text_width(crash_text_i3strings[crash_text_longest]);
253  int width = font_width + 20;
254 
255  /* Open a popup window on each virtual screen */
256  Output *screen;
257  xcb_window_t win;
258  TAILQ_FOREACH(screen, &outputs, outputs) {
259  if (!screen->active)
260  continue;
261  win = open_input_window(conn, screen->rect, width, height);
262 
263  /* Create pixmap */
264  pixmap = xcb_generate_id(conn);
265  pixmap_gc = xcb_generate_id(conn);
266  xcb_create_pixmap(conn, root_depth, pixmap, win, width, height);
267  xcb_create_gc(conn, pixmap_gc, pixmap, 0, 0);
268 
269  /* Grab the keyboard to get all input */
270  xcb_grab_keyboard(conn, false, win, XCB_CURRENT_TIME, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
271 
272  /* Grab the cursor inside the popup */
273  xcb_grab_pointer(conn, false, win, XCB_NONE, XCB_GRAB_MODE_ASYNC,
274  XCB_GRAB_MODE_ASYNC, win, XCB_NONE, XCB_CURRENT_TIME);
275 
276  sig_draw_window(win, width, height, config.font.height, crash_text_i3strings);
277  xcb_flush(conn);
278  }
279 }
280 
281 /*
282  * Handle signals
283  * It creates a window asking the user to restart in-place
284  * or exit to generate a core dump
285  *
286  */
287 void handle_signal(int sig, siginfo_t *info, void *data) {
288  DLOG("i3 crashed. SIG: %d\n", sig);
289 
290  struct sigaction action;
291  action.sa_handler = SIG_DFL;
292  sigaction(sig, &action, NULL);
293  raised_signal = sig;
294 
295  open_popups();
296 
297  xcb_generic_event_t *event;
298  /* Yay, more own eventhandlers… */
299  while ((event = xcb_wait_for_event(conn))) {
300  /* Strip off the highest bit (set if the event is generated) */
301  int type = (event->response_type & 0x7F);
302  if (type == XCB_KEY_PRESS) {
303  sig_handle_key_press(NULL, conn, (xcb_key_press_event_t*)event);
304  }
305  free(event);
306  }
307 }
308 
309 /*
310  * Setup signal handlers to safely handle SIGSEGV and SIGFPE
311  *
312  */
314  struct sigaction action;
315 
316  action.sa_sigaction = handle_signal;
317  action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
318  sigemptyset(&action.sa_mask);
319 
320  /* Catch all signals with default action "Core", see signal(7) */
321  if (sigaction(SIGQUIT, &action, NULL) == -1 ||
322  sigaction(SIGILL, &action, NULL) == -1 ||
323  sigaction(SIGABRT, &action, NULL) == -1 ||
324  sigaction(SIGFPE, &action, NULL) == -1 ||
325  sigaction(SIGSEGV, &action, NULL) == -1)
326  ELOG("Could not setup signal handler");
327 }
#define DLOG(fmt,...)
Definition: log.h:28
static void open_popups(void)
Definition: sighandler.c:239
Config config
Definition: config.c:19
i3String * i3string_from_utf8(const char *from_utf8)
Build an i3String from an UTF-8 encoded string.
Stores a rectangle, for example the size of a window, the child window etc.
Definition: data.h:107
uint32_t y
Definition: data.h:109
static int sig_draw_window(xcb_window_t win, int width, int height, int font_height, i3String **crash_text_i3strings)
Definition: sighandler.c:130
struct _i3String i3String
Opaque data structure for storing strings.
Definition: libi3.h:29
uint32_t height
Definition: data.h:33
static int sig_handle_key_press(void *ignored, xcb_connection_t *conn, xcb_key_press_event_t *event)
Definition: sighandler.c:172
static int backtrace(void)
Definition: sighandler.c:47
#define FREE(pointer)
Definition: util.h:47
xcb_connection_t * conn
Definition: main.c:42
uint32_t get_colorpixel(const char *hex) __attribute__((const ))
Returns the colorpixel to use for the given hex color (think of HTML).
uint32_t width
Definition: data.h:32
static xcb_pixmap_t pixmap
Definition: sighandler.c:28
static xcb_gcontext_t pixmap_gc
Definition: sighandler.c:27
static int crash_text_longest
Definition: sighandler.c:39
xcb_window_t root
Definition: main.c:55
static cmdp_state state
struct outputs_head outputs
Definition: randr.c:28
Rect rect
x, y, width, height
Definition: data.h:303
uint8_t root_depth
Definition: main.c:60
static int backtrace_string_index
Definition: sighandler.c:40
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 handle_signal(int sig, siginfo_t *info, void *data)
Definition: sighandler.c:287
uint32_t x
Definition: data.h:30
void * smalloc(size_t size)
Safe-wrapper around malloc which exits if malloc returns NULL (meaning that there is no more memory a...
static char * crash_text[]
Definition: sighandler.c:31
i3Font font
Definition: config.h:93
bool active
Whether the output is currently active (has a CRTC attached with a valid mode)
Definition: data.h:288
An Output is a physical output on your graphics driver.
Definition: data.h:282
static int raised_signal
Definition: sighandler.c:29
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:335
uint32_t y
Definition: data.h:31
uint32_t x
Definition: data.h:108
void setup_signal_handler(void)
Setup signal handlers to safely handle SIGSEGV and SIGFPE.
Definition: sighandler.c:313
static int backtrace_done
Definition: sighandler.c:41
void draw_text(i3String *text, xcb_drawable_t drawable, xcb_gcontext_t gc, int x, int y, int max_width)
Draws text onto the specified X drawable (normally a pixmap) at the specified coordinates (from the t...
uint32_t height
Definition: data.h:111
static xcb_window_t open_input_window(xcb_connection_t *conn, Rect screen_rect, uint32_t width, uint32_t height)
Definition: sighandler.c:206
void i3_restart(bool forget_layout)
Restart i3 in-place appends -a to argument list to disable autostart.
Definition: util.c:266
xcb_key_symbols_t * keysyms
Definition: main.c:66
int height
The height of the font, built from font_ascent + font_descent.
Definition: libi3.h:48
#define ELOG(fmt,...)
Definition: libi3.h:80
unsigned int xcb_numlock_mask
Definition: xcb.c:14
int predict_text_width(i3String *text)
Predict the text width in pixels for the given text.
void set_font_colors(xcb_gcontext_t gc, uint32_t foreground, uint32_t background)
Defines the colors to be used for the forthcoming draw_text calls.
uint32_t width
Definition: data.h:110
char ** start_argv
Definition: main.c:40