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