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  *
7  * main.c: Initialization, main loop
8  *
9  */
10 #include "all.h"
11 #include "shmlog.h"
12 
13 #include <ev.h>
14 #include <fcntl.h>
15 #include <getopt.h>
16 #include <libgen.h>
17 #include <locale.h>
18 #include <signal.h>
19 #include <sys/mman.h>
20 #include <sys/resource.h>
21 #include <sys/socket.h>
22 #include <sys/stat.h>
23 #include <sys/time.h>
24 #include <sys/types.h>
25 #include <sys/un.h>
26 #include <unistd.h>
27 #include <xcb/xcb_atom.h>
28 #include <xcb/xinerama.h>
29 #include <xcb/bigreq.h>
30 
31 #ifdef I3_ASAN_ENABLED
32 #include <sanitizer/lsan_interface.h>
33 #endif
34 
35 #include "sd-daemon.h"
36 
37 #include "i3-atoms_NET_SUPPORTED.xmacro.h"
38 #include "i3-atoms_rest.xmacro.h"
39 
40 /* The original value of RLIMIT_CORE when i3 was started. We need to restore
41  * this before starting any other process, since we set RLIMIT_CORE to
42  * RLIM_INFINITY for i3 debugging versions. */
43 struct rlimit original_rlimit_core;
44 
45 /* The number of file descriptors passed via socket activation. */
46 int listen_fds;
47 
48 /* We keep the xcb_prepare watcher around to be able to enable and disable it
49  * temporarily for drag_pointer(). */
50 static struct ev_prepare *xcb_prepare;
51 
52 char **start_argv;
53 
54 xcb_connection_t *conn;
55 /* The screen (0 when you are using DISPLAY=:0) of the connection 'conn' */
56 int conn_screen;
57 
58 /* Display handle for libstartup-notification */
59 SnDisplay *sndisplay;
60 
61 /* The last timestamp we got from X11 (timestamps are included in some events
62  * and are used for some things, like determining a unique ID in startup
63  * notification). */
64 xcb_timestamp_t last_timestamp = XCB_CURRENT_TIME;
65 
66 xcb_screen_t *root_screen;
67 xcb_window_t root;
68 
69 xcb_window_t wm_sn_selection_owner;
70 xcb_atom_t wm_sn;
71 
72 /* Color depth, visual id and colormap to use when creating windows and
73  * pixmaps. Will use 32 bit depth and an appropriate visual, if available,
74  * otherwise the root window’s default (usually 24 bit TrueColor). */
75 uint8_t root_depth;
76 xcb_visualtype_t *visual_type;
77 xcb_colormap_t colormap;
78 
79 struct ev_loop *main_loop;
80 
81 xcb_key_symbols_t *keysyms;
82 
83 /* Default shmlog size if not set by user. */
84 const int default_shmlog_size = 25 * 1024 * 1024;
85 
86 /* The list of key bindings */
87 struct bindings_head *bindings;
88 const char *current_binding_mode = NULL;
89 
90 /* The list of exec-lines */
91 struct autostarts_head autostarts = TAILQ_HEAD_INITIALIZER(autostarts);
92 
93 /* The list of exec_always lines */
94 struct autostarts_always_head autostarts_always = TAILQ_HEAD_INITIALIZER(autostarts_always);
95 
96 /* The list of assignments */
97 struct assignments_head assignments = TAILQ_HEAD_INITIALIZER(assignments);
98 
99 /* The list of workspace assignments (which workspace should end up on which
100  * output) */
101 struct ws_assignments_head ws_assignments = TAILQ_HEAD_INITIALIZER(ws_assignments);
102 
103 /* We hope that those are supported and set them to true */
104 bool xkb_supported = true;
105 bool shape_supported = true;
106 
107 bool force_xinerama = false;
108 
109 /* Define all atoms as global variables */
110 #define xmacro(atom) xcb_atom_t A_##atom;
111 I3_NET_SUPPORTED_ATOMS_XMACRO
112 I3_REST_ATOMS_XMACRO
113 #undef xmacro
114 
115 /*
116  * This callback is only a dummy, see xcb_prepare_cb.
117  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
118  *
119  */
xcb_got_event(EV_P_ struct ev_io * w,int revents)120 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
121     /* empty, because xcb_prepare_cb are used */
122 }
123 
124 /*
125  * Called just before the event loop sleeps. Ensures xcb’s incoming and outgoing
126  * queues are empty so that any activity will trigger another event loop
127  * iteration, and hence another xcb_prepare_cb invocation.
128  *
129  */
xcb_prepare_cb(EV_P_ ev_prepare * w,int revents)130 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
131     /* Process all queued (and possibly new) events before the event loop
132        sleeps. */
133     xcb_generic_event_t *event;
134 
135     while ((event = xcb_poll_for_event(conn)) != NULL) {
136         if (event->response_type == 0) {
137             if (event_is_ignored(event->sequence, 0))
138                 DLOG("Expected X11 Error received for sequence %x\n", event->sequence);
139             else {
140                 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
141                 DLOG("X11 Error received (probably harmless)! sequence 0x%x, error_code = %d\n",
142                      error->sequence, error->error_code);
143             }
144             free(event);
145             continue;
146         }
147 
148         /* Strip off the highest bit (set if the event is generated) */
149         int type = (event->response_type & 0x7F);
150 
151         handle_event(type, event);
152 
153         free(event);
154     }
155 
156     /* Flush all queued events to X11. */
157     xcb_flush(conn);
158 }
159 
160 /*
161  * Enable or disable the main X11 event handling function.
162  * This is used by drag_pointer() which has its own, modal event handler, which
163  * takes precedence over the normal event handler.
164  *
165  */
main_set_x11_cb(bool enable)166 void main_set_x11_cb(bool enable) {
167     DLOG("Setting main X11 callback to enabled=%d\n", enable);
168     if (enable) {
169         ev_prepare_start(main_loop, xcb_prepare);
170         /* Trigger the watcher explicitly to handle all remaining X11 events.
171          * drag_pointer()’s event handler exits in the middle of the loop. */
172         ev_feed_event(main_loop, xcb_prepare, 0);
173     } else {
174         ev_prepare_stop(main_loop, xcb_prepare);
175     }
176 }
177 
178 /*
179  * Exit handler which destroys the main_loop. Will trigger cleanup handlers.
180  *
181  */
i3_exit(void)182 static void i3_exit(void) {
183     if (*shmlogname != '\0') {
184         fprintf(stderr, "Closing SHM log \"%s\"\n", shmlogname);
185         fflush(stderr);
186         shm_unlink(shmlogname);
187     }
188     ipc_shutdown(SHUTDOWN_REASON_EXIT, -1);
189     unlink(config.ipc_socket_path);
190     if (current_log_stream_socket_path != NULL) {
191         unlink(current_log_stream_socket_path);
192     }
193     xcb_disconnect(conn);
194 
195     /* If a nagbar is active, kill it */
196     kill_nagbar(config_error_nagbar_pid, false);
197     kill_nagbar(command_error_nagbar_pid, false);
198 
199 /* We need ev >= 4 for the following code. Since it is not *that* important (it
200  * only makes sure that there are no i3-nagbar instances left behind) we still
201  * support old systems with libev 3. */
202 #if EV_VERSION_MAJOR >= 4
203     ev_loop_destroy(main_loop);
204 #endif
205 
206 #ifdef I3_ASAN_ENABLED
207     __lsan_do_leak_check();
208 #endif
209 }
210 
211 /*
212  * (One-shot) Handler for all signals with default action "Core", see signal(7)
213  *
214  * Unlinks the SHM log and re-raises the signal.
215  *
216  */
handle_core_signal(int sig,siginfo_t * info,void * data)217 static void handle_core_signal(int sig, siginfo_t *info, void *data) {
218     if (*shmlogname != '\0') {
219         shm_unlink(shmlogname);
220     }
221     raise(sig);
222 }
223 
224 /*
225  * (One-shot) Handler for all signals with default action "Term", see signal(7)
226  *
227  * Exits the program gracefully.
228  *
229  */
handle_term_signal(struct ev_loop * loop,ev_signal * signal,int revents)230 static void handle_term_signal(struct ev_loop *loop, ev_signal *signal, int revents) {
231     /* We exit gracefully here in the sense that cleanup handlers
232      * installed via atexit are invoked. */
233     exit(128 + signal->signum);
234 }
235 
236 /*
237  * Set up handlers for all signals with default action "Term", see signal(7)
238  *
239  */
setup_term_handlers(void)240 static void setup_term_handlers(void) {
241     static struct ev_signal signal_watchers[6];
242     size_t num_watchers = sizeof(signal_watchers) / sizeof(signal_watchers[0]);
243 
244     /* We have to rely on libev functionality here and should not use
245      * sigaction handlers because we need to invoke the exit handlers
246      * and cannot do so from an asynchronous signal handling context as
247      * not all code triggered during exit is signal safe (and exiting
248      * the main loop from said handler is not easily possible). libev's
249      * signal handlers does not impose such a constraint on us. */
250     ev_signal_init(&signal_watchers[0], handle_term_signal, SIGHUP);
251     ev_signal_init(&signal_watchers[1], handle_term_signal, SIGINT);
252     ev_signal_init(&signal_watchers[2], handle_term_signal, SIGALRM);
253     ev_signal_init(&signal_watchers[3], handle_term_signal, SIGTERM);
254     ev_signal_init(&signal_watchers[4], handle_term_signal, SIGUSR1);
255     ev_signal_init(&signal_watchers[5], handle_term_signal, SIGUSR1);
256     for (size_t i = 0; i < num_watchers; i++) {
257         ev_signal_start(main_loop, &signal_watchers[i]);
258         /* The signal handlers should not block ev_run from returning
259          * and so none of the signal handlers should hold a reference to
260          * the main loop. */
261         ev_unref(main_loop);
262     }
263 }
264 
parse_restart_fd(void)265 static int parse_restart_fd(void) {
266     const char *restart_fd = getenv("_I3_RESTART_FD");
267     if (restart_fd == NULL) {
268         return -1;
269     }
270 
271     long int fd = -1;
272     if (!parse_long(restart_fd, &fd, 10)) {
273         ELOG("Malformed _I3_RESTART_FD \"%s\"\n", restart_fd);
274         return -1;
275     }
276     return fd;
277 }
278 
main(int argc,char * argv[])279 int main(int argc, char *argv[]) {
280     /* Keep a symbol pointing to the I3_VERSION string constant so that we have
281      * it in gdb backtraces. */
282     static const char *_i3_version __attribute__((used)) = I3_VERSION;
283     char *override_configpath = NULL;
284     bool autostart = true;
285     char *layout_path = NULL;
286     bool delete_layout_path = false;
287     bool disable_randr15 = false;
288     char *fake_outputs = NULL;
289     bool disable_signalhandler = false;
290     bool only_check_config = false;
291     bool replace_wm = false;
292     static struct option long_options[] = {
293         {"no-autostart", no_argument, 0, 'a'},
294         {"config", required_argument, 0, 'c'},
295         {"version", no_argument, 0, 'v'},
296         {"moreversion", no_argument, 0, 'm'},
297         {"more-version", no_argument, 0, 'm'},
298         {"more_version", no_argument, 0, 'm'},
299         {"help", no_argument, 0, 'h'},
300         {"layout", required_argument, 0, 'L'},
301         {"restart", required_argument, 0, 0},
302         {"force-xinerama", no_argument, 0, 0},
303         {"force_xinerama", no_argument, 0, 0},
304         {"disable-randr15", no_argument, 0, 0},
305         {"disable_randr15", no_argument, 0, 0},
306         {"disable-signalhandler", no_argument, 0, 0},
307         {"shmlog-size", required_argument, 0, 0},
308         {"shmlog_size", required_argument, 0, 0},
309         {"get-socketpath", no_argument, 0, 0},
310         {"get_socketpath", no_argument, 0, 0},
311         {"fake_outputs", required_argument, 0, 0},
312         {"fake-outputs", required_argument, 0, 0},
313         {"force-old-config-parser-v4.4-only", no_argument, 0, 0},
314         {"replace", no_argument, 0, 'r'},
315         {0, 0, 0, 0}};
316     int option_index = 0, opt;
317 
318     setlocale(LC_ALL, "");
319 
320     /* Get the RLIMIT_CORE limit at startup time to restore this before
321      * starting processes. */
322     getrlimit(RLIMIT_CORE, &original_rlimit_core);
323 
324     /* Disable output buffering to make redirects in .xsession actually useful for debugging */
325     if (!isatty(fileno(stdout)))
326         setbuf(stdout, NULL);
327 
328     srand(time(NULL));
329 
330     /* Init logging *before* initializing debug_build to guarantee early
331      * (file) logging. */
332     init_logging();
333 
334     /* On release builds, disable SHM logging by default. */
335     shmlog_size = (is_debug_build() || strstr(argv[0], "i3-with-shmlog") != NULL ? default_shmlog_size : 0);
336 
337     start_argv = argv;
338 
339     while ((opt = getopt_long(argc, argv, "c:CvmaL:hld:Vr", long_options, &option_index)) != -1) {
340         switch (opt) {
341             case 'a':
342                 LOG("Autostart disabled using -a\n");
343                 autostart = false;
344                 break;
345             case 'L':
346                 FREE(layout_path);
347                 layout_path = sstrdup(optarg);
348                 delete_layout_path = false;
349                 break;
350             case 'c':
351                 FREE(override_configpath);
352                 override_configpath = sstrdup(optarg);
353                 break;
354             case 'C':
355                 LOG("Checking configuration file only (-C)\n");
356                 only_check_config = true;
357                 break;
358             case 'v':
359                 printf("i3 version %s © 2009 Michael Stapelberg and contributors\n", i3_version);
360                 exit(EXIT_SUCCESS);
361                 break;
362             case 'm':
363                 printf("Binary i3 version:  %s © 2009 Michael Stapelberg and contributors\n", i3_version);
364                 display_running_version();
365                 exit(EXIT_SUCCESS);
366                 break;
367             case 'V':
368                 set_verbosity(true);
369                 break;
370             case 'd':
371                 LOG("Enabling debug logging\n");
372                 set_debug_logging(true);
373                 break;
374             case 'l':
375                 /* DEPRECATED, ignored for the next 3 versions (3.e, 3.f, 3.g) */
376                 break;
377             case 'r':
378                 replace_wm = true;
379                 break;
380             case 0:
381                 if (strcmp(long_options[option_index].name, "force-xinerama") == 0 ||
382                     strcmp(long_options[option_index].name, "force_xinerama") == 0) {
383                     force_xinerama = true;
384                     ELOG("Using Xinerama instead of RandR. This option should be "
385                          "avoided at all cost because it does not refresh the list "
386                          "of screens, so you cannot configure displays at runtime. "
387                          "Please check if your driver really does not support RandR "
388                          "and disable this option as soon as you can.\n");
389                     break;
390                 } else if (strcmp(long_options[option_index].name, "disable-randr15") == 0 ||
391                            strcmp(long_options[option_index].name, "disable_randr15") == 0) {
392                     disable_randr15 = true;
393                     break;
394                 } else if (strcmp(long_options[option_index].name, "disable-signalhandler") == 0) {
395                     disable_signalhandler = true;
396                     break;
397                 } else if (strcmp(long_options[option_index].name, "get-socketpath") == 0 ||
398                            strcmp(long_options[option_index].name, "get_socketpath") == 0) {
399                     char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
400                     if (socket_path) {
401                         printf("%s\n", socket_path);
402                         /* With -O2 (i.e. the buildtype=debugoptimized meson
403                          * option, which we set by default), gcc 9.2.1 optimizes
404                          * away socket_path at this point, resulting in a Leak
405                          * Sanitizer report. An explicit free helps: */
406                         free(socket_path);
407                         exit(EXIT_SUCCESS);
408                     }
409 
410                     exit(EXIT_FAILURE);
411                 } else if (strcmp(long_options[option_index].name, "shmlog-size") == 0 ||
412                            strcmp(long_options[option_index].name, "shmlog_size") == 0) {
413                     shmlog_size = atoi(optarg);
414                     /* Re-initialize logging immediately to get as many
415                      * logmessages as possible into the SHM log. */
416                     init_logging();
417                     LOG("Limiting SHM log size to %d bytes\n", shmlog_size);
418                     break;
419                 } else if (strcmp(long_options[option_index].name, "restart") == 0) {
420                     FREE(layout_path);
421                     layout_path = sstrdup(optarg);
422                     delete_layout_path = true;
423                     break;
424                 } else if (strcmp(long_options[option_index].name, "fake-outputs") == 0 ||
425                            strcmp(long_options[option_index].name, "fake_outputs") == 0) {
426                     LOG("Initializing fake outputs: %s\n", optarg);
427                     fake_outputs = sstrdup(optarg);
428                     break;
429                 } else if (strcmp(long_options[option_index].name, "force-old-config-parser-v4.4-only") == 0) {
430                     ELOG("You are passing --force-old-config-parser-v4.4-only, but that flag was removed by now.\n");
431                     break;
432                 }
433             /* fall-through */
434             default:
435                 fprintf(stderr, "Usage: %s [-c configfile] [-d all] [-a] [-v] [-V] [-C]\n", argv[0]);
436                 fprintf(stderr, "\n");
437                 fprintf(stderr, "\t-a          disable autostart ('exec' lines in config)\n");
438                 fprintf(stderr, "\t-c <file>   use the provided configfile instead\n");
439                 fprintf(stderr, "\t-C          validate configuration file and exit\n");
440                 fprintf(stderr, "\t-d all      enable debug output\n");
441                 fprintf(stderr, "\t-L <file>   path to the serialized layout during restarts\n");
442                 fprintf(stderr, "\t-v          display version and exit\n");
443                 fprintf(stderr, "\t-V          enable verbose mode\n");
444                 fprintf(stderr, "\n");
445                 fprintf(stderr, "\t--force-xinerama\n"
446                                 "\tUse Xinerama instead of RandR.\n"
447                                 "\tThis option should only be used if you are stuck with the\n"
448                                 "\told nVidia closed source driver (older than 302.17), which does\n"
449                                 "\tnot support RandR.\n");
450                 fprintf(stderr, "\n");
451                 fprintf(stderr, "\t--get-socketpath\n"
452                                 "\tRetrieve the i3 IPC socket path from X11, print it, then exit.\n");
453                 fprintf(stderr, "\n");
454                 fprintf(stderr, "\t--shmlog-size <limit>\n"
455                                 "\tLimits the size of the i3 SHM log to <limit> bytes. Setting this\n"
456                                 "\tto 0 disables SHM logging entirely.\n"
457                                 "\tThe default is %d bytes.\n",
458                         shmlog_size);
459                 fprintf(stderr, "\n");
460                 fprintf(stderr, "\t--replace\n"
461                                 "\tReplace an existing window manager.\n");
462                 fprintf(stderr, "\n");
463                 fprintf(stderr, "If you pass plain text arguments, i3 will interpret them as a command\n"
464                                 "to send to a currently running i3 (like i3-msg). This allows you to\n"
465                                 "use nice and logical commands, such as:\n"
466                                 "\n"
467                                 "\ti3 border none\n"
468                                 "\ti3 floating toggle\n"
469                                 "\ti3 kill window\n"
470                                 "\n");
471                 exit(opt == 'h' ? EXIT_SUCCESS : EXIT_FAILURE);
472         }
473     }
474 
475     if (only_check_config) {
476         exit(load_configuration(override_configpath, C_VALIDATE) ? EXIT_SUCCESS : EXIT_FAILURE);
477     }
478 
479     /* If the user passes more arguments, we act like i3-msg would: Just send
480      * the arguments as an IPC message to i3. This allows for nice semantic
481      * commands such as 'i3 border none'. */
482     if (optind < argc) {
483         /* We enable verbose mode so that the user knows what’s going on.
484          * This should make it easier to find mistakes when the user passes
485          * arguments by mistake. */
486         set_verbosity(true);
487 
488         LOG("Additional arguments passed. Sending them as a command to i3.\n");
489         char *payload = NULL;
490         while (optind < argc) {
491             if (!payload) {
492                 payload = sstrdup(argv[optind]);
493             } else {
494                 char *both;
495                 sasprintf(&both, "%s %s", payload, argv[optind]);
496                 free(payload);
497                 payload = both;
498             }
499             optind++;
500         }
501         DLOG("Command is: %s (%zd bytes)\n", payload, strlen(payload));
502         char *socket_path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
503         if (!socket_path) {
504             ELOG("Could not get i3 IPC socket path\n");
505             return 1;
506         }
507 
508         int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
509         if (sockfd == -1)
510             err(EXIT_FAILURE, "Could not create socket");
511 
512         struct sockaddr_un addr;
513         memset(&addr, 0, sizeof(struct sockaddr_un));
514         addr.sun_family = AF_LOCAL;
515         strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);
516         FREE(socket_path);
517         if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
518             err(EXIT_FAILURE, "Could not connect to i3");
519 
520         if (ipc_send_message(sockfd, strlen(payload), I3_IPC_MESSAGE_TYPE_RUN_COMMAND,
521                              (uint8_t *)payload) == -1)
522             err(EXIT_FAILURE, "IPC: write()");
523         FREE(payload);
524 
525         uint32_t reply_length;
526         uint32_t reply_type;
527         uint8_t *reply;
528         int ret;
529         if ((ret = ipc_recv_message(sockfd, &reply_type, &reply_length, &reply)) != 0) {
530             if (ret == -1)
531                 err(EXIT_FAILURE, "IPC: read()");
532             return 1;
533         }
534         if (reply_type != I3_IPC_REPLY_TYPE_COMMAND)
535             errx(EXIT_FAILURE, "IPC: received reply of type %d but expected %d (COMMAND)", reply_type, I3_IPC_REPLY_TYPE_COMMAND);
536         printf("%.*s\n", reply_length, reply);
537         FREE(reply);
538         return 0;
539     }
540 
541     /* Enable logging to handle the case when the user did not specify --shmlog-size */
542     init_logging();
543 
544     /* Try to enable core dumps by default when running a debug build */
545     if (is_debug_build()) {
546         struct rlimit limit = {RLIM_INFINITY, RLIM_INFINITY};
547         setrlimit(RLIMIT_CORE, &limit);
548 
549         /* The following code is helpful, but not required. We thus don’t pay
550          * much attention to error handling, non-linux or other edge cases. */
551         LOG("CORE DUMPS: You are running a development version of i3, so coredumps were automatically enabled (ulimit -c unlimited).\n");
552         size_t cwd_size = 1024;
553         char *cwd = smalloc(cwd_size);
554         char *cwd_ret;
555         while ((cwd_ret = getcwd(cwd, cwd_size)) == NULL && errno == ERANGE) {
556             cwd_size = cwd_size * 2;
557             cwd = srealloc(cwd, cwd_size);
558         }
559         if (cwd_ret != NULL)
560             LOG("CORE DUMPS: Your current working directory is \"%s\".\n", cwd);
561         int patternfd;
562         if ((patternfd = open("/proc/sys/kernel/core_pattern", O_RDONLY)) >= 0) {
563             memset(cwd, '\0', cwd_size);
564             if (read(patternfd, cwd, cwd_size) > 0)
565                 /* a trailing newline is included in cwd */
566                 LOG("CORE DUMPS: Your core_pattern is: %s", cwd);
567             close(patternfd);
568         }
569         free(cwd);
570     }
571 
572     LOG("i3 %s starting\n", i3_version);
573 
574     conn = xcb_connect(NULL, &conn_screen);
575     if (xcb_connection_has_error(conn))
576         errx(EXIT_FAILURE, "Cannot open display");
577 
578     sndisplay = sn_xcb_display_new(conn, NULL, NULL);
579 
580     /* Initialize the libev event loop. This needs to be done before loading
581      * the config file because the parser will install an ev_child watcher
582      * for the nagbar when config errors are found. */
583     main_loop = EV_DEFAULT;
584     if (main_loop == NULL)
585         die("Could not initialize libev. Bad LIBEV_FLAGS?\n");
586 
587     root_screen = xcb_aux_get_screen(conn, conn_screen);
588     root = root_screen->root;
589 
590     /* Prefetch X11 extensions that we are interested in. */
591     xcb_prefetch_extension_data(conn, &xcb_xkb_id);
592     xcb_prefetch_extension_data(conn, &xcb_shape_id);
593     /* BIG-REQUESTS is used by libxcb internally. */
594     xcb_prefetch_extension_data(conn, &xcb_big_requests_id);
595     if (force_xinerama) {
596         xcb_prefetch_extension_data(conn, &xcb_xinerama_id);
597     } else {
598         xcb_prefetch_extension_data(conn, &xcb_randr_id);
599     }
600 
601     /* Prepare for us to get a current timestamp as recommended by ICCCM */
602     xcb_change_window_attributes(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){XCB_EVENT_MASK_PROPERTY_CHANGE});
603     xcb_change_property(conn, XCB_PROP_MODE_APPEND, root, XCB_ATOM_SUPERSCRIPT_X, XCB_ATOM_CARDINAL, 32, 0, "");
604 
605     /* Place requests for the atoms we need as soon as possible */
606 #define xmacro(atom) \
607     xcb_intern_atom_cookie_t atom##_cookie = xcb_intern_atom(conn, 0, strlen(#atom), #atom);
608     I3_NET_SUPPORTED_ATOMS_XMACRO
609     I3_REST_ATOMS_XMACRO
610 #undef xmacro
611 
612     root_depth = root_screen->root_depth;
613     colormap = root_screen->default_colormap;
614     visual_type = xcb_aux_find_visual_by_attrs(root_screen, -1, 32);
615     if (visual_type != NULL) {
616         root_depth = xcb_aux_get_depth_of_visual(root_screen, visual_type->visual_id);
617         colormap = xcb_generate_id(conn);
618 
619         xcb_void_cookie_t cm_cookie = xcb_create_colormap_checked(conn,
620                                                                   XCB_COLORMAP_ALLOC_NONE,
621                                                                   colormap,
622                                                                   root,
623                                                                   visual_type->visual_id);
624 
625         xcb_generic_error_t *error = xcb_request_check(conn, cm_cookie);
626         if (error != NULL) {
627             ELOG("Could not create colormap. Error code: %d\n", error->error_code);
628             exit(EXIT_FAILURE);
629         }
630     } else {
631         visual_type = get_visualtype(root_screen);
632     }
633 
634     xcb_prefetch_maximum_request_length(conn);
635 
636     init_dpi();
637 
638     DLOG("root_depth = %d, visual_id = 0x%08x.\n", root_depth, visual_type->visual_id);
639     DLOG("root_screen->height_in_pixels = %d, root_screen->height_in_millimeters = %d\n",
640          root_screen->height_in_pixels, root_screen->height_in_millimeters);
641     DLOG("One logical pixel corresponds to %d physical pixels on this display.\n", logical_px(1));
642 
643     xcb_get_geometry_cookie_t gcookie = xcb_get_geometry(conn, root);
644     xcb_query_pointer_cookie_t pointercookie = xcb_query_pointer(conn, root);
645 
646     /* Get the PropertyNotify event we caused above */
647     xcb_flush(conn);
648     {
649         xcb_generic_event_t *event;
650         DLOG("waiting for PropertyNotify event\n");
651         while ((event = xcb_wait_for_event(conn)) != NULL) {
652             if (event->response_type == XCB_PROPERTY_NOTIFY) {
653                 last_timestamp = ((xcb_property_notify_event_t *)event)->time;
654                 free(event);
655                 break;
656             }
657             free(event);
658         }
659         DLOG("got timestamp %d\n", last_timestamp);
660     }
661 
662     /* Setup NetWM atoms */
663 #define xmacro(name)                                                                       \
664     do {                                                                                   \
665         xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(conn, name##_cookie, NULL); \
666         if (!reply) {                                                                      \
667             ELOG("Could not get atom " #name "\n");                                        \
668             exit(-1);                                                                      \
669         }                                                                                  \
670         A_##name = reply->atom;                                                            \
671         free(reply);                                                                       \
672     } while (0);
673     I3_NET_SUPPORTED_ATOMS_XMACRO
674     I3_REST_ATOMS_XMACRO
675 #undef xmacro
676 
677     load_configuration(override_configpath, C_LOAD);
678 
679     if (config.ipc_socket_path == NULL) {
680         /* Fall back to a file name in /tmp/ based on the PID */
681         if ((config.ipc_socket_path = getenv("I3SOCK")) == NULL)
682             config.ipc_socket_path = get_process_filename("ipc-socket");
683         else
684             config.ipc_socket_path = sstrdup(config.ipc_socket_path);
685     }
686 
687     if (config.force_xinerama) {
688         force_xinerama = true;
689     }
690 
691     /* Acquire the WM_Sn selection. */
692     {
693         /* Get the WM_Sn atom */
694         char *atom_name = xcb_atom_name_by_screen("WM_S", conn_screen);
695         wm_sn_selection_owner = xcb_generate_id(conn);
696 
697         if (atom_name == NULL) {
698             ELOG("xcb_atom_name_by_screen(\"WM_S\", %d) failed, exiting\n", conn_screen);
699             return 1;
700         }
701 
702         xcb_intern_atom_reply_t *atom_reply;
703         atom_reply = xcb_intern_atom_reply(conn,
704                                            xcb_intern_atom_unchecked(conn,
705                                                                      0,
706                                                                      strlen(atom_name),
707                                                                      atom_name),
708                                            NULL);
709         free(atom_name);
710         if (atom_reply == NULL) {
711             ELOG("Failed to intern the WM_Sn atom, exiting\n");
712             return 1;
713         }
714         wm_sn = atom_reply->atom;
715         free(atom_reply);
716 
717         /* Check if the selection is already owned */
718         xcb_get_selection_owner_reply_t *selection_reply =
719             xcb_get_selection_owner_reply(conn,
720                                           xcb_get_selection_owner(conn, wm_sn),
721                                           NULL);
722         if (selection_reply && selection_reply->owner != XCB_NONE && !replace_wm) {
723             ELOG("Another window manager is already running (WM_Sn is owned)");
724             return 1;
725         }
726 
727         /* Become the selection owner */
728         xcb_create_window(conn,
729                           root_screen->root_depth,
730                           wm_sn_selection_owner, /* window id */
731                           root_screen->root,     /* parent */
732                           -1, -1, 1, 1,          /* geometry */
733                           0,                     /* border width */
734                           XCB_WINDOW_CLASS_INPUT_OUTPUT,
735                           root_screen->root_visual,
736                           0, NULL);
737         xcb_change_property(conn,
738                             XCB_PROP_MODE_REPLACE,
739                             wm_sn_selection_owner,
740                             XCB_ATOM_WM_CLASS,
741                             XCB_ATOM_STRING,
742                             8,
743                             (strlen("i3-WM_Sn") + 1) * 2,
744                             "i3-WM_Sn\0i3-WM_Sn\0");
745 
746         xcb_set_selection_owner(conn, wm_sn_selection_owner, wm_sn, last_timestamp);
747 
748         if (selection_reply && selection_reply->owner != XCB_NONE) {
749             unsigned int usleep_time = 100000; /* 0.1 seconds */
750             int check_rounds = 150;            /* Wait for a maximum of 15 seconds */
751             xcb_get_geometry_reply_t *geom_reply = NULL;
752 
753             DLOG("waiting for old WM_Sn selection owner to exit");
754             do {
755                 free(geom_reply);
756                 usleep(usleep_time);
757                 if (check_rounds-- == 0) {
758                     ELOG("The old window manager is not exiting");
759                     return 1;
760                 }
761                 geom_reply = xcb_get_geometry_reply(conn,
762                                                     xcb_get_geometry(conn, selection_reply->owner),
763                                                     NULL);
764             } while (geom_reply != NULL);
765         }
766         free(selection_reply);
767 
768         /* Announce that we are the new owner */
769         /* Every X11 event is 32 bytes long. Therefore, XCB will copy 32 bytes.
770          * In order to properly initialize these bytes, we allocate 32 bytes even
771          * though we only need less for an xcb_client_message_event_t */
772         union {
773             xcb_client_message_event_t message;
774             char storage[32];
775         } event;
776         memset(&event, 0, sizeof(event));
777         event.message.response_type = XCB_CLIENT_MESSAGE;
778         event.message.window = root_screen->root;
779         event.message.format = 32;
780         event.message.type = A_MANAGER;
781         event.message.data.data32[0] = last_timestamp;
782         event.message.data.data32[1] = wm_sn;
783         event.message.data.data32[2] = wm_sn_selection_owner;
784 
785         xcb_send_event(conn, 0, root_screen->root, XCB_EVENT_MASK_STRUCTURE_NOTIFY, event.storage);
786     }
787 
788     xcb_void_cookie_t cookie;
789     cookie = xcb_change_window_attributes_checked(conn, root, XCB_CW_EVENT_MASK, (uint32_t[]){ROOT_EVENT_MASK});
790     xcb_generic_error_t *error = xcb_request_check(conn, cookie);
791     if (error != NULL) {
792         ELOG("Another window manager seems to be running (X error %d)\n", error->error_code);
793 #ifdef I3_ASAN_ENABLED
794         __lsan_do_leak_check();
795 #endif
796         return 1;
797     }
798 
799     xcb_get_geometry_reply_t *greply = xcb_get_geometry_reply(conn, gcookie, NULL);
800     if (greply == NULL) {
801         ELOG("Could not get geometry of the root window, exiting\n");
802         return 1;
803     }
804     DLOG("root geometry reply: (%d, %d) %d x %d\n", greply->x, greply->y, greply->width, greply->height);
805 
806     xcursor_load_cursors();
807 
808     /* Set a cursor for the root window (otherwise the root window will show no
809        cursor until the first client is launched). */
810     xcursor_set_root_cursor(XCURSOR_CURSOR_POINTER);
811 
812     const xcb_query_extension_reply_t *extreply;
813     extreply = xcb_get_extension_data(conn, &xcb_xkb_id);
814     xkb_supported = extreply->present;
815     if (!extreply->present) {
816         DLOG("xkb is not present on this server\n");
817     } else {
818         DLOG("initializing xcb-xkb\n");
819         xcb_xkb_use_extension(conn, XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);
820         xcb_xkb_select_events(conn,
821                               XCB_XKB_ID_USE_CORE_KBD,
822                               XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
823                               0,
824                               XCB_XKB_EVENT_TYPE_STATE_NOTIFY | XCB_XKB_EVENT_TYPE_MAP_NOTIFY | XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
825                               0xff,
826                               0xff,
827                               NULL);
828 
829         /* Setting both, XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE and
830          * XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED, will lead to the
831          * X server sending us the full XKB state in KeyPress and KeyRelease:
832          * https://cgit.freedesktop.org/xorg/xserver/tree/xkb/xkbEvents.c?h=xorg-server-1.20.0#n927
833          *
834          * XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT enable detectable autorepeat:
835          * https://www.x.org/releases/current/doc/kbproto/xkbproto.html#Detectable_Autorepeat
836          * This affects bindings using the --release flag: instead of getting multiple KeyRelease
837          * events we get only one event when the key is physically released by the user.
838          */
839         const uint32_t mask = XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE |
840                               XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED |
841                               XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT;
842         xcb_xkb_per_client_flags_reply_t *pcf_reply;
843         /* The last three parameters are unset because they are only relevant
844          * when using a feature called “automatic reset of boolean controls”:
845          * https://www.x.org/releases/X11R7.7/doc/kbproto/xkbproto.html#Automatic_Reset_of_Boolean_Controls
846          * */
847         pcf_reply = xcb_xkb_per_client_flags_reply(
848             conn,
849             xcb_xkb_per_client_flags(
850                 conn,
851                 XCB_XKB_ID_USE_CORE_KBD,
852                 mask,
853                 mask,
854                 0 /* uint32_t ctrlsToChange */,
855                 0 /* uint32_t autoCtrls */,
856                 0 /* uint32_t autoCtrlsValues */),
857             NULL);
858 
859 #define PCF_REPLY_ERROR(_value)                                    \
860     do {                                                           \
861         if (pcf_reply == NULL || !(pcf_reply->value & (_value))) { \
862             ELOG("Could not set " #_value "\n");                   \
863         }                                                          \
864     } while (0)
865 
866         PCF_REPLY_ERROR(XCB_XKB_PER_CLIENT_FLAG_GRABS_USE_XKB_STATE);
867         PCF_REPLY_ERROR(XCB_XKB_PER_CLIENT_FLAG_LOOKUP_STATE_WHEN_GRABBED);
868         PCF_REPLY_ERROR(XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT);
869 
870         free(pcf_reply);
871         xkb_base = extreply->first_event;
872     }
873 
874     /* Check for Shape extension. We want to handle input shapes which is
875      * introduced in 1.1. */
876     extreply = xcb_get_extension_data(conn, &xcb_shape_id);
877     if (extreply->present) {
878         shape_base = extreply->first_event;
879         xcb_shape_query_version_cookie_t cookie = xcb_shape_query_version(conn);
880         xcb_shape_query_version_reply_t *version =
881             xcb_shape_query_version_reply(conn, cookie, NULL);
882         shape_supported = version && version->minor_version >= 1;
883         free(version);
884     } else {
885         shape_supported = false;
886     }
887     if (!shape_supported) {
888         DLOG("shape 1.1 is not present on this server\n");
889     }
890 
891     restore_connect();
892 
893     property_handlers_init();
894 
895     ewmh_setup_hints();
896 
897     keysyms = xcb_key_symbols_alloc(conn);
898 
899     xcb_numlock_mask = aio_get_mod_mask_for(XCB_NUM_LOCK, keysyms);
900 
901     if (!load_keymap())
902         die("Could not load keymap\n");
903 
904     translate_keysyms();
905     grab_all_keys(conn);
906 
907     bool needs_tree_init = true;
908     if (layout_path != NULL) {
909         LOG("Trying to restore the layout from \"%s\".\n", layout_path);
910         needs_tree_init = !tree_restore(layout_path, greply);
911         if (delete_layout_path) {
912             unlink(layout_path);
913             const char *dir = dirname(layout_path);
914             /* possibly fails with ENOTEMPTY if there are files (or
915              * sockets) left. */
916             rmdir(dir);
917         }
918     }
919     if (needs_tree_init)
920         tree_init(greply);
921 
922     free(greply);
923 
924     /* Setup fake outputs for testing */
925     if (fake_outputs == NULL && config.fake_outputs != NULL)
926         fake_outputs = config.fake_outputs;
927 
928     if (fake_outputs != NULL) {
929         fake_outputs_init(fake_outputs);
930         FREE(fake_outputs);
931         config.fake_outputs = NULL;
932     } else if (force_xinerama) {
933         /* Force Xinerama (for drivers which don't support RandR yet, esp. the
934          * nVidia binary graphics driver), when specified either in the config
935          * file or on command-line */
936         xinerama_init();
937     } else {
938         DLOG("Checking for XRandR...\n");
939         randr_init(&randr_base, disable_randr15 || config.disable_randr15);
940     }
941 
942     /* We need to force disabling outputs which have been loaded from the
943      * layout file but are no longer active. This can happen if the output has
944      * been disabled in the short time between writing the restart layout file
945      * and restarting i3. See #2326. */
946     if (layout_path != NULL && randr_base > -1) {
947         Con *con;
948         TAILQ_FOREACH (con, &(croot->nodes_head), nodes) {
949             Output *output;
950             TAILQ_FOREACH (output, &outputs, outputs) {
951                 if (output->active || strcmp(con->name, output_primary_name(output)) != 0)
952                     continue;
953 
954                 /* This will correctly correlate the output with its content
955                  * container. We need to make the connection to properly
956                  * disable the output. */
957                 if (output->con == NULL) {
958                     output_init_con(output);
959                     output->changed = false;
960                 }
961 
962                 output->to_be_disabled = true;
963                 randr_disable_output(output);
964             }
965         }
966     }
967     FREE(layout_path);
968 
969     scratchpad_fix_resolution();
970 
971     xcb_query_pointer_reply_t *pointerreply;
972     Output *output = NULL;
973     if (!(pointerreply = xcb_query_pointer_reply(conn, pointercookie, NULL))) {
974         ELOG("Could not query pointer position, using first screen\n");
975     } else {
976         DLOG("Pointer at %d, %d\n", pointerreply->root_x, pointerreply->root_y);
977         output = get_output_containing(pointerreply->root_x, pointerreply->root_y);
978         if (!output) {
979             ELOG("ERROR: No screen at (%d, %d), starting on the first screen\n",
980                  pointerreply->root_x, pointerreply->root_y);
981         }
982     }
983     if (!output) {
984         output = get_first_output();
985     }
986     con_activate(con_descend_focused(output_get_content(output->con)));
987     free(pointerreply);
988 
989     tree_render();
990 
991     /* Create the UNIX domain socket for IPC */
992     int ipc_socket = create_socket(config.ipc_socket_path, &current_socketpath);
993     if (ipc_socket == -1) {
994         ELOG("Could not create the IPC socket, IPC disabled\n");
995     } else {
996         struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
997         ev_io_init(ipc_io, ipc_new_client, ipc_socket, EV_READ);
998         ev_io_start(main_loop, ipc_io);
999     }
1000 
1001     /* Chose a file name in /tmp/ based on the PID */
1002     char *log_stream_socket_path = get_process_filename("log-stream-socket");
1003     int log_socket = create_socket(log_stream_socket_path, &current_log_stream_socket_path);
1004     free(log_stream_socket_path);
1005     if (log_socket == -1) {
1006         ELOG("Could not create the log socket, i3-dump-log -f will not work\n");
1007     } else {
1008         struct ev_io *log_io = scalloc(1, sizeof(struct ev_io));
1009         ev_io_init(log_io, log_new_client, log_socket, EV_READ);
1010         ev_io_start(main_loop, log_io);
1011     }
1012 
1013     /* Also handle the UNIX domain sockets passed via socket
1014      * activation. The parameter 0 means "do not remove the
1015      * environment variables", we need to be able to reexec. */
1016     listen_fds = sd_listen_fds(0);
1017     if (listen_fds < 0)
1018         ELOG("socket activation: Error in sd_listen_fds\n");
1019     else if (listen_fds == 0)
1020         DLOG("socket activation: no sockets passed\n");
1021     else {
1022         int flags;
1023         for (int fd = SD_LISTEN_FDS_START;
1024              fd < (SD_LISTEN_FDS_START + listen_fds);
1025              fd++) {
1026             DLOG("socket activation: also listening on fd %d\n", fd);
1027 
1028             /* sd_listen_fds() enables FD_CLOEXEC by default.
1029              * However, we need to keep the file descriptors open for in-place
1030              * restarting, therefore we explicitly disable FD_CLOEXEC. */
1031             if ((flags = fcntl(fd, F_GETFD)) < 0 ||
1032                 fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
1033                 ELOG("Could not disable FD_CLOEXEC on fd %d\n", fd);
1034             }
1035 
1036             struct ev_io *ipc_io = scalloc(1, sizeof(struct ev_io));
1037             ev_io_init(ipc_io, ipc_new_client, fd, EV_READ);
1038             ev_io_start(main_loop, ipc_io);
1039         }
1040     }
1041 
1042     {
1043         const int restart_fd = parse_restart_fd();
1044         if (restart_fd != -1) {
1045             DLOG("serving restart fd %d", restart_fd);
1046             ipc_client *client = ipc_new_client_on_fd(main_loop, restart_fd);
1047             ipc_confirm_restart(client);
1048             unsetenv("_I3_RESTART_FD");
1049         }
1050     }
1051 
1052     /* Set up i3 specific atoms like I3_SOCKET_PATH and I3_CONFIG_PATH */
1053     x_set_i3_atoms();
1054     ewmh_update_workarea();
1055 
1056     /* Set the ewmh desktop properties. */
1057     ewmh_update_desktop_properties();
1058 
1059     struct ev_io *xcb_watcher = scalloc(1, sizeof(struct ev_io));
1060     xcb_prepare = scalloc(1, sizeof(struct ev_prepare));
1061 
1062     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1063     ev_io_start(main_loop, xcb_watcher);
1064 
1065     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1066     ev_prepare_start(main_loop, xcb_prepare);
1067 
1068     xcb_flush(conn);
1069 
1070     /* What follows is a fugly consequence of X11 protocol race conditions like
1071      * the following: In an i3 in-place restart, i3 will reparent all windows
1072      * to the root window, then exec() itself. In the new process, it calls
1073      * manage_existing_windows. However, in case any application sent a
1074      * generated UnmapNotify message to the WM (as GIMP does), this message
1075      * will be handled by i3 *after* managing the window, thus i3 thinks the
1076      * window just closed itself. In reality, the message was sent in the time
1077      * period where i3 wasn’t running yet.
1078      *
1079      * To prevent this, we grab the server (disables processing of any other
1080      * connections), then discard all pending events (since we didn’t do
1081      * anything, there cannot be any meaningful responses), then ungrab the
1082      * server. */
1083     xcb_grab_server(conn);
1084     {
1085         xcb_aux_sync(conn);
1086         xcb_generic_event_t *event;
1087         while ((event = xcb_poll_for_event(conn)) != NULL) {
1088             if (event->response_type == 0) {
1089                 free(event);
1090                 continue;
1091             }
1092 
1093             /* Strip off the highest bit (set if the event is generated) */
1094             int type = (event->response_type & 0x7F);
1095 
1096             /* We still need to handle MapRequests which are sent in the
1097              * timespan starting from when we register as a window manager and
1098              * this piece of code which drops events. */
1099             if (type == XCB_MAP_REQUEST)
1100                 handle_event(type, event);
1101 
1102             free(event);
1103         }
1104         manage_existing_windows(root);
1105     }
1106     xcb_ungrab_server(conn);
1107 
1108     if (autostart) {
1109         /* When the root's window background is set to NONE, that might mean
1110          * that old content stays visible when a window is closed. That has
1111          * unpleasant effect of "my terminal (does not seem to) close!".
1112          *
1113          * There does not seem to be an easy way to query for this problem, so
1114          * we test for it: Open & close a window and check if the background is
1115          * redrawn or the window contents stay visible.
1116          */
1117         LOG("This is not an in-place restart, checking if a wallpaper is set.\n");
1118 
1119         xcb_screen_t *root = xcb_aux_get_screen(conn, conn_screen);
1120         if (is_background_set(conn, root)) {
1121             LOG("A wallpaper is set, so no screenshot is necessary.\n");
1122         } else {
1123             LOG("No wallpaper set, copying root window contents to a pixmap\n");
1124             set_screenshot_as_wallpaper(conn, root);
1125         }
1126     }
1127 
1128 #if defined(__OpenBSD__)
1129     if (pledge("stdio rpath wpath cpath proc exec unix", NULL) == -1)
1130         err(EXIT_FAILURE, "pledge");
1131 #endif
1132 
1133     if (!disable_signalhandler)
1134         setup_signal_handler();
1135     else {
1136         struct sigaction action;
1137 
1138         action.sa_sigaction = handle_core_signal;
1139         action.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO;
1140         sigemptyset(&action.sa_mask);
1141 
1142         /* Catch all signals with default action "Core", see signal(7) */
1143         if (sigaction(SIGQUIT, &action, NULL) == -1 ||
1144             sigaction(SIGILL, &action, NULL) == -1 ||
1145             sigaction(SIGABRT, &action, NULL) == -1 ||
1146             sigaction(SIGFPE, &action, NULL) == -1 ||
1147             sigaction(SIGSEGV, &action, NULL) == -1)
1148             ELOG("Could not setup signal handler.\n");
1149     }
1150 
1151     setup_term_handlers();
1152     /* Ignore SIGPIPE to survive errors when an IPC client disconnects
1153      * while we are sending them a message */
1154     signal(SIGPIPE, SIG_IGN);
1155 
1156     /* Autostarting exec-lines */
1157     if (autostart) {
1158         while (!TAILQ_EMPTY(&autostarts)) {
1159             struct Autostart *exec = TAILQ_FIRST(&autostarts);
1160 
1161             LOG("auto-starting %s\n", exec->command);
1162             start_application(exec->command, exec->no_startup_id);
1163 
1164             FREE(exec->command);
1165             TAILQ_REMOVE(&autostarts, exec, autostarts);
1166             FREE(exec);
1167         }
1168     }
1169 
1170     /* Autostarting exec_always-lines */
1171     while (!TAILQ_EMPTY(&autostarts_always)) {
1172         struct Autostart *exec_always = TAILQ_FIRST(&autostarts_always);
1173 
1174         LOG("auto-starting (always!) %s\n", exec_always->command);
1175         start_application(exec_always->command, exec_always->no_startup_id);
1176 
1177         FREE(exec_always->command);
1178         TAILQ_REMOVE(&autostarts_always, exec_always, autostarts_always);
1179         FREE(exec_always);
1180     }
1181 
1182     /* Start i3bar processes for all configured bars */
1183     Barconfig *barconfig;
1184     TAILQ_FOREACH (barconfig, &barconfigs, configs) {
1185         char *command = NULL;
1186         sasprintf(&command, "%s %s --bar_id=%s --socket=\"%s\"",
1187                   barconfig->i3bar_command ? barconfig->i3bar_command : "exec i3bar",
1188                   barconfig->verbose ? "-V" : "",
1189                   barconfig->id, current_socketpath);
1190         LOG("Starting bar process: %s\n", command);
1191         start_application(command, true);
1192         free(command);
1193     }
1194 
1195     /* Make sure to destroy the event loop to invoke the cleanup callbacks
1196      * when calling exit() */
1197     atexit(i3_exit);
1198 
1199     sd_notify(1, "READY=1");
1200     ev_loop(main_loop, 0);
1201 }
1202