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