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