Avoid some core dumps in X session management
[emacs.git] / src / xsmfns.c
blob375b51c446623cf5b6d001feff7e74111c9c7ce2
1 /* Session management module for systems which understand the X Session
2 management protocol.
4 Copyright (C) 2002-2015 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #ifdef HAVE_X_SM
25 #include <X11/SM/SMlib.h>
26 #include <X11/Xlib.h>
27 #include <X11/Xutil.h>
29 #include <unistd.h>
30 #include <sys/param.h>
31 #include <stdio.h>
33 #include "lisp.h"
34 #include "systime.h"
35 #include "sysselect.h"
36 #include "frame.h"
37 #include "termhooks.h"
38 #include "xterm.h"
39 #include "process.h"
40 #include "keyboard.h"
42 #if defined USE_GTK && !defined HAVE_GTK3
43 #define gdk_x11_set_sm_client_id(w) gdk_set_sm_client_id (w)
44 #endif
46 /* This is the event used when SAVE_SESSION_EVENT occurs. */
48 static struct input_event emacs_event;
50 /* The descriptor that we use to check for data from the session manager. */
52 static int ice_fd = -1;
54 /* A flag that says if we are in shutdown interactions or not. */
56 static bool doing_interact;
58 /* The session manager object for the session manager connection. */
60 static SmcConn smc_conn;
62 /* The client session id for this session. */
64 static char *client_id;
66 /* The full path name to the Emacs program. */
68 static char *emacs_program;
70 /* The option we tell the session manager to start Emacs with when
71 restarting Emacs. The client_id is appended. */
73 #define SMID_OPT "--smid="
76 /* The option to start Emacs without the splash screen when
77 restarting Emacs. */
79 static char NOSPLASH_OPT[] = "--no-splash";
81 /* The option to make Emacs start in the given directory. */
83 #define CHDIR_OPT "--chdir="
85 static void
86 ice_connection_closed (void)
88 if (ice_fd >= 0)
89 delete_read_fd (ice_fd);
90 ice_fd = -1;
94 /* Handle any messages from the session manager. If no connection is
95 open to a session manager, just return. */
97 static void
98 x_session_check_input (int fd, void *data)
100 int ret;
102 if (ice_fd == -1) return;
104 /* Reset this so wo can check kind after callbacks have been called by
105 IceProcessMessages. The smc_interact_CB sets the kind to
106 SAVE_SESSION_EVENT, but we don't know beforehand if that callback
107 will be called. */
108 emacs_event.kind = NO_EVENT;
110 ret = IceProcessMessages (SmcGetIceConnection (smc_conn), 0, 0);
111 if (ret != IceProcessMessagesSuccess)
113 /* Either IO error or Connection closed. */
114 if (ret == IceProcessMessagesIOError)
115 IceCloseConnection (SmcGetIceConnection (smc_conn));
117 ice_connection_closed ();
120 /* Check if smc_interact_CB was called and we shall generate a
121 SAVE_SESSION_EVENT. */
122 if (emacs_event.kind != NO_EVENT)
123 kbd_buffer_store_event (&emacs_event);
126 /* Return true if we have a connection to a session manager. */
128 bool
129 x_session_have_connection (void)
131 return ice_fd != -1;
134 /* This is called when the session manager says it is OK to interact with the
135 user. Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
136 Then lisp code can interact with the user. */
138 static void
139 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
141 doing_interact = true;
142 emacs_event.kind = SAVE_SESSION_EVENT;
143 emacs_event.arg = Qnil;
146 /* This is called when the session manager tells us to save ourselves.
147 We set the required properties so the session manager can restart us,
148 plus the current working directory property (not mandatory) so we
149 are started in the correct directory.
151 If this is a shutdown and we can request to interact with the user,
152 we do so, because we don't know what the lisp code might do. */
154 static void
155 smc_save_yourself_CB (SmcConn smcConn,
156 SmPointer clientData,
157 int saveType,
158 Bool shutdown,
159 int interactStyle,
160 Bool fast)
162 #define NR_PROPS 5
164 SmProp *props[NR_PROPS];
165 SmProp prop_ptr[NR_PROPS];
167 SmPropValue values[20], *vp;
168 int val_idx = 0, vp_idx = 0;
169 int props_idx = 0;
170 int i;
171 char *smid_opt, *chdir_opt = NULL;
173 /* How to start a new instance of Emacs. */
174 props[props_idx] = &prop_ptr[props_idx];
175 props[props_idx]->name = xstrdup (SmCloneCommand);
176 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
177 props[props_idx]->num_vals = 1;
178 props[props_idx]->vals = &values[val_idx++];
179 props[props_idx]->vals[0].length = strlen (emacs_program);
180 props[props_idx]->vals[0].value = emacs_program;
181 ++props_idx;
183 if (STRINGP (Vinvocation_name))
185 /* The name of the program. */
186 props[props_idx] = &prop_ptr[props_idx];
187 props[props_idx]->name = xstrdup (SmProgram);
188 props[props_idx]->type = xstrdup (SmARRAY8);
189 props[props_idx]->num_vals = 1;
190 props[props_idx]->vals = &values[val_idx++];
191 props[props_idx]->vals[0].length = SBYTES (Vinvocation_name);
192 props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
193 ++props_idx;
196 /* User id. */
197 Lisp_Object user_login_name = Fuser_login_name (Qnil);
198 if (STRINGP (user_login_name))
200 props[props_idx] = &prop_ptr[props_idx];
201 props[props_idx]->name = xstrdup (SmUserID);
202 props[props_idx]->type = xstrdup (SmARRAY8);
203 props[props_idx]->num_vals = 1;
204 props[props_idx]->vals = &values[val_idx++];
205 props[props_idx]->vals[0].length = SBYTES (user_login_name);
206 props[props_idx]->vals[0].value = SDATA (user_login_name);
207 ++props_idx;
210 char *cwd = get_current_dir_name ();
211 if (cwd)
213 props[props_idx] = &prop_ptr[props_idx];
214 props[props_idx]->name = xstrdup (SmCurrentDirectory);
215 props[props_idx]->type = xstrdup (SmARRAY8);
216 props[props_idx]->num_vals = 1;
217 props[props_idx]->vals = &values[val_idx++];
218 props[props_idx]->vals[0].length = strlen (cwd);
219 props[props_idx]->vals[0].value = cwd;
220 ++props_idx;
224 /* How to restart Emacs. */
225 props[props_idx] = &prop_ptr[props_idx];
226 props[props_idx]->name = xstrdup (SmRestartCommand);
227 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
228 /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir ... */
229 if (INT_MAX - 3 < initial_argc)
230 memory_full (SIZE_MAX);
231 i = 3 + initial_argc;
232 props[props_idx]->num_vals = i;
233 vp = xnmalloc (i, sizeof *vp);
234 props[props_idx]->vals = vp;
235 props[props_idx]->vals[vp_idx].length = strlen (emacs_program);
236 props[props_idx]->vals[vp_idx++].value = emacs_program;
238 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
239 strcpy (stpcpy (smid_opt, SMID_OPT), client_id);
241 props[props_idx]->vals[vp_idx].length = strlen (smid_opt);
242 props[props_idx]->vals[vp_idx++].value = smid_opt;
244 props[props_idx]->vals[vp_idx].length = strlen (NOSPLASH_OPT);
245 props[props_idx]->vals[vp_idx++].value = NOSPLASH_OPT;
247 if (cwd)
249 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
250 strcpy (stpcpy (chdir_opt, CHDIR_OPT), cwd);
252 props[props_idx]->vals[vp_idx].length = strlen (chdir_opt);
253 props[props_idx]->vals[vp_idx++].value = chdir_opt;
256 for (i = 1; i < initial_argc; ++i)
258 props[props_idx]->vals[vp_idx].length = strlen (initial_argv[i]);
259 props[props_idx]->vals[vp_idx++].value = initial_argv[i];
262 ++props_idx;
264 SmcSetProperties (smcConn, props_idx, props);
266 xfree (smid_opt);
267 xfree (chdir_opt);
268 xfree (cwd);
269 xfree (vp);
271 for (i = 0; i < props_idx; ++i)
273 xfree (props[i]->type);
274 xfree (props[i]->name);
277 /* See if we maybe shall interact with the user. */
278 if (interactStyle != SmInteractStyleAny
279 || ! shutdown
280 || saveType == SmSaveLocal
281 || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
283 /* No interaction, we are done saving ourself. */
284 SmcSaveYourselfDone (smcConn, True);
288 /* According to the SM specification, this shall close the connection. */
290 static void
291 smc_die_CB (SmcConn smcConn, SmPointer clientData)
293 emacs_event.kind = SAVE_SESSION_EVENT;
294 emacs_event.arg = Qt;
297 /* We don't use the next two but they are mandatory, leave them empty.
298 According to the SM specification, we should not interact with the
299 user between smc_save_yourself_CB is called and until smc_save_complete_CB
300 is called. It seems like a lot of job to implement this and it doesn't
301 even seem necessary. */
303 static void
304 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
306 /* Empty */
309 static void
310 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
312 /* Empty */
315 /* Error handlers for SM and ICE. We don't want to exit Emacs just
316 because there is some error in the session management. */
318 static void
319 smc_error_handler (SmcConn smcConn,
320 Bool swap,
321 int offendingMinorOpcode,
322 unsigned long offendingSequence,
323 int errorClass,
324 int severity,
325 SmPointer values)
327 /* Empty */
330 static void
331 ice_error_handler (IceConn iceConn,
332 Bool swap,
333 int offendingMinorOpcode,
334 unsigned long offendingSequence,
335 int errorClass,
336 int severity,
337 IcePointer values)
339 /* Empty */
343 static void
344 ice_io_error_handler (IceConn iceConn)
346 /* Connection probably gone. */
347 ice_connection_closed ();
350 /* This is called when the ICE connection is created or closed. The SM library
351 uses ICE as it transport protocol. */
353 static void
354 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData,
355 int opening, IcePointer *watchData)
357 if (! opening)
359 ice_connection_closed ();
360 return;
363 ice_fd = IceConnectionNumber (iceConn);
364 add_read_fd (ice_fd, x_session_check_input, NULL);
367 /* Create the client leader window. */
369 #ifndef USE_GTK
370 static void
371 create_client_leader_window (struct x_display_info *dpyinfo, char *client_ID)
373 Window w;
374 XClassHint class_hints;
376 w = XCreateSimpleWindow (dpyinfo->display,
377 dpyinfo->root_window,
378 -1, -1, 1, 1,
379 CopyFromParent, CopyFromParent, CopyFromParent);
381 validate_x_resource_name ();
382 class_hints.res_name = SSDATA (Vx_resource_name);
383 class_hints.res_class = SSDATA (Vx_resource_class);
384 XSetClassHint (dpyinfo->display, w, &class_hints);
385 XStoreName (dpyinfo->display, w, class_hints.res_name);
387 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
388 XA_STRING, 8, PropModeReplace,
389 (unsigned char *) client_ID, strlen (client_ID));
391 dpyinfo->client_leader_window = w;
393 #endif /* ! USE_GTK */
396 /* Try to open a connection to the session manager. */
398 void
399 x_session_initialize (struct x_display_info *dpyinfo)
401 #define SM_ERRORSTRING_LEN 512
402 char errorstring[SM_ERRORSTRING_LEN];
403 char *previous_id = NULL;
404 SmcCallbacks callbacks;
405 ptrdiff_t name_len = 0;
407 ice_fd = -1;
408 doing_interact = false;
410 /* Check if we where started by the session manager. If so, we will
411 have a previous id. */
412 if (STRINGP (Vx_session_previous_id))
413 previous_id = SSDATA (Vx_session_previous_id);
415 /* Construct the path to the Emacs program. */
416 if (STRINGP (Vinvocation_directory))
417 name_len += SBYTES (Vinvocation_directory);
418 if (STRINGP (Vinvocation_name))
419 name_len += SBYTES (Vinvocation_name);
421 /* This malloc will not be freed, but it is only done once, and hopefully
422 not very large */
423 emacs_program = xmalloc (name_len + 1);
424 char *z = emacs_program;
426 if (STRINGP (Vinvocation_directory))
427 z = lispstpcpy (z, Vinvocation_directory);
428 if (STRINGP (Vinvocation_name))
429 lispstpcpy (z, Vinvocation_name);
431 /* The SM protocol says all callbacks are mandatory, so set up all
432 here and in the mask passed to SmcOpenConnection. */
433 callbacks.save_yourself.callback = smc_save_yourself_CB;
434 callbacks.save_yourself.client_data = 0;
435 callbacks.die.callback = smc_die_CB;
436 callbacks.die.client_data = 0;
437 callbacks.save_complete.callback = smc_save_complete_CB;
438 callbacks.save_complete.client_data = 0;
439 callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
440 callbacks.shutdown_cancelled.client_data = 0;
442 /* Set error handlers. */
443 SmcSetErrorHandler (smc_error_handler);
444 IceSetErrorHandler (ice_error_handler);
445 IceSetIOErrorHandler (ice_io_error_handler);
447 /* Install callback for when connection status changes. */
448 IceAddConnectionWatch (ice_conn_watch_CB, 0);
450 /* Open the connection to the session manager. A failure is not
451 critical, it usually means that no session manager is running.
452 The errorstring is here for debugging. */
453 smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
454 (SmcSaveYourselfProcMask|
455 SmcDieProcMask|
456 SmcSaveCompleteProcMask|
457 SmcShutdownCancelledProcMask),
458 &callbacks,
459 previous_id,
460 &client_id,
461 SM_ERRORSTRING_LEN,
462 errorstring);
464 if (smc_conn != 0)
466 Vx_session_id = build_string (client_id);
468 #ifdef USE_GTK
469 /* GTK creates a leader window by itself, but we need to tell
470 it about our client_id. */
471 gdk_x11_set_sm_client_id (client_id);
472 #else
473 create_client_leader_window (dpyinfo, client_id);
474 #endif
478 /* Ensure that the session manager is not contacted again. */
480 void
481 x_session_close (void)
483 ice_connection_closed ();
487 DEFUN ("handle-save-session", Fhandle_save_session,
488 Shandle_save_session, 1, 1, "e",
489 doc: /* Handle the save_yourself event from a session manager.
490 A session manager can tell Emacs that the window system is shutting down
491 by sending Emacs a save_yourself message. Emacs executes this function when
492 such an event occurs. This function then executes `emacs-session-save'.
493 After that, this function informs the session manager that it can continue
494 or abort shutting down the window system depending on the return value
495 from `emacs-session-save' If the return value is non-nil the session manager
496 is told to abort the window system shutdown.
498 Do not call this function yourself. */)
499 (Lisp_Object event)
501 bool kill_emacs = (CONSP (event) && CONSP (XCDR (event))
502 && EQ (Qt, XCAR (XCDR (event))));
504 /* Check doing_interact so that we don't do anything if someone called
505 this at the wrong time. */
506 if (doing_interact && ! kill_emacs)
508 bool cancel_shutdown = ! NILP (call0 (intern ("emacs-session-save")));
510 SmcInteractDone (smc_conn, cancel_shutdown);
511 SmcSaveYourselfDone (smc_conn, True);
513 doing_interact = false;
515 else if (kill_emacs)
517 /* We should not do user interaction here, but it is not easy to
518 prevent. Fix this in next version. */
519 Fkill_emacs (Qnil);
521 #if false
522 /* This will not be reached, but we want kill-emacs-hook to be run. */
523 SmcCloseConnection (smc_conn, 0, 0);
524 ice_connection_closed ();
525 #endif
528 return Qnil;
533 /***********************************************************************
534 Initialization
535 ***********************************************************************/
536 void
537 syms_of_xsmfns (void)
539 DEFVAR_LISP ("x-session-id", Vx_session_id,
540 doc: /* The session id Emacs got from the session manager for this session.
541 Changing the value does not change the session id used by Emacs.
542 The value is nil if no session manager is running.
543 See also `x-session-previous-id', `emacs-save-session-functions',
544 `emacs-session-save' and `emacs-session-restore'." */);
545 Vx_session_id = Qnil;
547 DEFVAR_LISP ("x-session-previous-id", Vx_session_previous_id,
548 doc: /* The previous session id Emacs got from session manager.
549 If Emacs is running on a window system that has a session manager, the
550 session manager gives Emacs a session id. It is feasible for Emacs Lisp
551 code to use the session id to save configuration in, for example, a file
552 with a file name based on the session id. If Emacs is running when the
553 window system is shut down, the session manager remembers that Emacs was
554 running and saves the session id Emacs had.
556 When the window system is started again, the session manager restarts
557 Emacs and hands Emacs the session id it had the last time it was
558 running. This is now the previous session id and the value of this
559 variable. If configuration was saved in a file as stated above, the
560 previous session id shall be used to reconstruct the file name.
562 The session id Emacs has while it is running is in the variable
563 `x-session-id'. The value of this variable and `x-session-id' may be the
564 same, depending on how the session manager works.
566 See also `emacs-save-session-functions', `emacs-session-save' and
567 `emacs-session-restore'." */);
568 Vx_session_previous_id = Qnil;
570 defsubr (&Shandle_save_session);
573 #endif /* HAVE_X_SM */