]> code.delx.au - gnu-emacs/blob - src/emacs.c
Robustify stack-size calculation
[gnu-emacs] / src / emacs.c
1 /* Fully extensible Emacs, running on Unix, intended for GNU.
2
3 Copyright (C) 1985-1987, 1993-1995, 1997-1999, 2001-2016 Free Software
4 Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
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 (at
11 your option) any later version.
12
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.
17
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/>. */
20
21 #define INLINE EXTERN_INLINE
22 #include <config.h>
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdio.h>
27
28 #include <sys/types.h>
29 #include <sys/file.h>
30 #include <unistd.h>
31
32 #include <close-stream.h>
33
34 #define MAIN_PROGRAM
35 #include "lisp.h"
36
37 #ifdef WINDOWSNT
38 #include <fcntl.h>
39 #include <sys/socket.h>
40 #include <mbstring.h>
41 #include "w32.h"
42 #include "w32heap.h"
43 #endif
44
45 #if defined WINDOWSNT || defined HAVE_NTGUI
46 #include "w32select.h"
47 #include "w32font.h"
48 #include "w32common.h"
49 #endif
50
51 #if defined CYGWIN
52 #include "cygw32.h"
53 #endif
54
55 #ifdef MSDOS
56 #include <binary-io.h>
57 #include "dosfns.h"
58 #endif
59
60 #ifdef HAVE_LIBSYSTEMD
61 # include <systemd/sd-daemon.h>
62 # include <sys/socket.h>
63 #endif
64
65 #ifdef HAVE_WINDOW_SYSTEM
66 #include TERM_HEADER
67 #endif /* HAVE_WINDOW_SYSTEM */
68
69 #include "coding.h"
70 #include "intervals.h"
71 #include "character.h"
72 #include "buffer.h"
73 #include "window.h"
74 #include "xwidget.h"
75 #include "atimer.h"
76 #include "blockinput.h"
77 #include "syssignal.h"
78 #include "process.h"
79 #include "frame.h"
80 #include "termhooks.h"
81 #include "keyboard.h"
82 #include "keymap.h"
83 #include "category.h"
84 #include "charset.h"
85 #include "composite.h"
86 #include "dispextern.h"
87 #include "regex.h"
88 #include "sheap.h"
89 #include "syntax.h"
90 #include "sysselect.h"
91 #include "systime.h"
92 #include "puresize.h"
93
94 #include "getpagesize.h"
95 #include "gnutls.h"
96
97 #if (defined PROFILING \
98 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__))
99 # include <sys/gmon.h>
100 extern void moncontrol (int mode);
101 #endif
102
103 #ifdef HAVE_SETLOCALE
104 #include <locale.h>
105 #endif
106
107 #if HAVE_WCHAR_H
108 # include <wchar.h>
109 #endif
110
111 #ifdef HAVE_SETRLIMIT
112 #include <sys/time.h>
113 #include <sys/resource.h>
114 #endif
115
116 #ifdef HAVE_PERSONALITY_LINUX32
117 #include <sys/personality.h>
118 #endif
119
120 static const char emacs_version[] = PACKAGE_VERSION;
121 static const char emacs_copyright[] = COPYRIGHT;
122 static const char emacs_bugreport[] = PACKAGE_BUGREPORT;
123
124 /* Empty lisp strings. To avoid having to build any others. */
125 Lisp_Object empty_unibyte_string, empty_multibyte_string;
126
127 #ifdef WINDOWSNT
128 /* Cache for externally loaded libraries. */
129 Lisp_Object Vlibrary_cache;
130 #endif
131
132 /* Set after Emacs has started up the first time.
133 Prevents reinitialization of the Lisp world and keymaps
134 on subsequent starts. */
135 bool initialized;
136
137 /* Set to true if this instance of Emacs might dump. */
138 #ifndef DOUG_LEA_MALLOC
139 static
140 #endif
141 bool might_dump;
142
143 #ifdef DARWIN_OS
144 extern void unexec_init_emacs_zone (void);
145 #endif
146
147 /* If true, Emacs should not attempt to use a window-specific code,
148 but instead should use the virtual terminal under which it was started. */
149 bool inhibit_window_system;
150
151 /* If true, a filter or a sentinel is running. Tested to save the match
152 data on the first attempt to change it inside asynchronous code. */
153 bool running_asynch_code;
154
155 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NS)
156 /* If true, -d was specified, meaning we're using some window system. */
157 bool display_arg;
158 #endif
159
160 /* An address near the bottom of the stack.
161 Tells GC how to save a copy of the stack. */
162 char *stack_bottom;
163
164 #ifdef GNU_LINUX
165 /* The gap between BSS end and heap start as far as we can tell. */
166 static uprintmax_t heap_bss_diff;
167 #endif
168
169 /* To run as a daemon under Cocoa or Windows, we must do a fork+exec,
170 not a simple fork.
171
172 On Cocoa, CoreFoundation lib fails in forked process:
173 http://developer.apple.com/ReleaseNotes/
174 CoreFoundation/CoreFoundation.html)
175
176 On Windows, a Cygwin fork child cannot access the USER subsystem.
177
178 We mark being in the exec'd process by a daemon name argument of
179 form "--daemon=\nFD0,FD1\nNAME" where FD are the pipe file descriptors,
180 NAME is the original daemon name, if any. */
181 #if defined NS_IMPL_COCOA || (defined HAVE_NTGUI && defined CYGWIN)
182 # define DAEMON_MUST_EXEC
183 #endif
184
185 /* True means running Emacs without interactive terminal. */
186 bool noninteractive;
187
188 /* True means remove site-lisp directories from load-path. */
189 bool no_site_lisp;
190
191 /* True means put details like time stamps into builds. */
192 bool build_details;
193
194 /* Name for the server started by the daemon.*/
195 static char *daemon_name;
196
197 #ifndef WINDOWSNT
198 /* Pipe used to send exit notification to the daemon parent at
199 startup. */
200 int daemon_pipe[2];
201 #else
202 HANDLE w32_daemon_event;
203 #endif
204
205 /* Save argv and argc. */
206 char **initial_argv;
207 int initial_argc;
208
209 static void sort_args (int argc, char **argv);
210 static void syms_of_emacs (void);
211
212 /* C99 needs each string to be at most 4095 characters, and the usage
213 strings below are split to not overflow this limit. */
214 static char const *const usage_message[] =
215 { "\
216 \n\
217 Run Emacs, the extensible, customizable, self-documenting real-time\n\
218 display editor. The recommended way to start Emacs for normal editing\n\
219 is with no options at all.\n\
220 \n\
221 Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n\
222 read the main documentation for these command-line arguments.\n\
223 \n\
224 Initialization options:\n\
225 \n\
226 ",
227 "\
228 --batch do not do interactive display; implies -q\n\
229 --chdir DIR change to directory DIR\n\
230 --daemon start a server in the background\n\
231 --debug-init enable Emacs Lisp debugger for init file\n\
232 --display, -d DISPLAY use X server DISPLAY\n\
233 ",
234 "\
235 --no-build-details do not add build details such as time stamps\n\
236 --no-desktop do not load a saved desktop\n\
237 --no-init-file, -q load neither ~/.emacs nor default.el\n\
238 --no-loadup, -nl do not load loadup.el into bare Emacs\n\
239 --no-site-file do not load site-start.el\n\
240 --no-x-resources do not load X resources\n\
241 --no-site-lisp, -nsl do not add site-lisp directories to load-path\n\
242 --no-splash do not display a splash screen on startup\n\
243 --no-window-system, -nw do not communicate with X, ignoring $DISPLAY\n\
244 ",
245 "\
246 --quick, -Q equivalent to:\n\
247 -q --no-site-file --no-site-lisp --no-splash\n\
248 --no-x-resources\n\
249 --script FILE run FILE as an Emacs Lisp script\n\
250 --terminal, -t DEVICE use DEVICE for terminal I/O\n\
251 --user, -u USER load ~USER/.emacs instead of your own\n\
252 \n\
253 ",
254 "\
255 Action options:\n\
256 \n\
257 FILE visit FILE using find-file\n\
258 +LINE go to line LINE in next FILE\n\
259 +LINE:COLUMN go to line LINE, column COLUMN, in next FILE\n\
260 --directory, -L DIR prepend DIR to load-path (with :DIR, append DIR)\n\
261 --eval EXPR evaluate Emacs Lisp expression EXPR\n\
262 --execute EXPR evaluate Emacs Lisp expression EXPR\n\
263 ",
264 "\
265 --file FILE visit FILE using find-file\n\
266 --find-file FILE visit FILE using find-file\n\
267 --funcall, -f FUNC call Emacs Lisp function FUNC with no arguments\n\
268 --insert FILE insert contents of FILE into current buffer\n\
269 --kill exit without asking for confirmation\n\
270 --load, -l FILE load Emacs Lisp FILE using the load function\n\
271 --visit FILE visit FILE using find-file\n\
272 \n\
273 ",
274 "\
275 Display options:\n\
276 \n\
277 --background-color, -bg COLOR window background color\n\
278 --basic-display, -D disable many display features;\n\
279 used for debugging Emacs\n\
280 --border-color, -bd COLOR main border color\n\
281 --border-width, -bw WIDTH width of main border\n\
282 ",
283 "\
284 --color, --color=MODE override color mode for character terminals;\n\
285 MODE defaults to `auto', and\n\
286 can also be `never', `always',\n\
287 or a mode name like `ansi8'\n\
288 --cursor-color, -cr COLOR color of the Emacs cursor indicating point\n\
289 --font, -fn FONT default font; must be fixed-width\n\
290 --foreground-color, -fg COLOR window foreground color\n\
291 ",
292 "\
293 --fullheight, -fh make the first frame high as the screen\n\
294 --fullscreen, -fs make the first frame fullscreen\n\
295 --fullwidth, -fw make the first frame wide as the screen\n\
296 --maximized, -mm make the first frame maximized\n\
297 --geometry, -g GEOMETRY window geometry\n\
298 ",
299 "\
300 --no-bitmap-icon, -nbi do not use picture of gnu for Emacs icon\n\
301 --iconic start Emacs in iconified state\n\
302 --internal-border, -ib WIDTH width between text and main border\n\
303 --line-spacing, -lsp PIXELS additional space to put between lines\n\
304 --mouse-color, -ms COLOR mouse cursor color in Emacs window\n\
305 --name NAME title for initial Emacs frame\n\
306 ",
307 "\
308 --no-blinking-cursor, -nbc disable blinking cursor\n\
309 --reverse-video, -r, -rv switch foreground and background\n\
310 --title, -T TITLE title for initial Emacs frame\n\
311 --vertical-scroll-bars, -vb enable vertical scroll bars\n\
312 --xrm XRESOURCES set additional X resources\n\
313 --parent-id XID set parent window\n\
314 --help display this help and exit\n\
315 --version output version information and exit\n\
316 \n\
317 ",
318 "\
319 You can generally also specify long option names with a single -; for\n\
320 example, -batch as well as --batch. You can use any unambiguous\n\
321 abbreviation for a --option.\n\
322 \n\
323 Various environment variables and window system resources also affect\n\
324 the operation of Emacs. See the main documentation.\n\
325 \n\
326 Report bugs to " PACKAGE_BUGREPORT ". First, please see the Bugs\n\
327 section of the Emacs manual or the file BUGS.\n"
328 };
329
330 \f
331 /* True if handling a fatal error already. */
332 bool fatal_error_in_progress;
333
334 #ifdef HAVE_NS
335 /* NS autrelease pool, for memory management. */
336 static void *ns_pool;
337 #endif
338
339 #if !HAVE_SETLOCALE
340 static char *
341 setlocale (int cat, char const *locale)
342 {
343 return 0;
344 }
345 #endif
346
347 /* True if the current system locale uses UTF-8 encoding. */
348 static bool
349 using_utf8 (void)
350 {
351 #ifdef HAVE_WCHAR_H
352 wchar_t wc;
353 mbstate_t mbs = { 0 };
354 return mbrtowc (&wc, "\xc4\x80", 2, &mbs) == 2 && wc == 0x100;
355 #else
356 return false;
357 #endif
358 }
359
360
361 /* Report a fatal error due to signal SIG, output a backtrace of at
362 most BACKTRACE_LIMIT lines, and exit. */
363 _Noreturn void
364 terminate_due_to_signal (int sig, int backtrace_limit)
365 {
366 signal (sig, SIG_DFL);
367
368 if (attempt_orderly_shutdown_on_fatal_signal)
369 {
370 /* If fatal error occurs in code below, avoid infinite recursion. */
371 if (! fatal_error_in_progress)
372 {
373 fatal_error_in_progress = 1;
374
375 totally_unblock_input ();
376 if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT)
377 Fkill_emacs (make_number (sig));
378
379 shut_down_emacs (sig, Qnil);
380 emacs_backtrace (backtrace_limit);
381 }
382 }
383
384 /* Signal the same code; this time it will really be fatal.
385 Since we're in a signal handler, the signal is blocked, so we
386 have to unblock it if we want to really receive it. */
387 #ifndef MSDOS
388 {
389 sigset_t unblocked;
390 sigemptyset (&unblocked);
391 sigaddset (&unblocked, sig);
392 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
393 }
394 #endif
395
396 emacs_raise (sig);
397
398 /* This shouldn't be executed, but it prevents a warning. */
399 exit (1);
400 }
401 \f
402 /* Code for dealing with Lisp access to the Unix command line. */
403
404 static void
405 init_cmdargs (int argc, char **argv, int skip_args, char *original_pwd)
406 {
407 int i;
408 Lisp_Object name, dir, handler;
409 ptrdiff_t count = SPECPDL_INDEX ();
410 Lisp_Object raw_name;
411 AUTO_STRING (slash_colon, "/:");
412
413 initial_argv = argv;
414 initial_argc = argc;
415
416 #ifdef WINDOWSNT
417 /* Must use argv[0] converted to UTF-8, as it begets many standard
418 file and directory names. */
419 {
420 char argv0[MAX_UTF8_PATH];
421
422 if (filename_from_ansi (argv[0], argv0) == 0)
423 raw_name = build_unibyte_string (argv0);
424 else
425 raw_name = build_unibyte_string (argv[0]);
426 }
427 #else
428 raw_name = build_unibyte_string (argv[0]);
429 #endif
430
431 /* Add /: to the front of the name
432 if it would otherwise be treated as magic. */
433 handler = Ffind_file_name_handler (raw_name, Qt);
434 if (! NILP (handler))
435 raw_name = concat2 (slash_colon, raw_name);
436
437 Vinvocation_name = Ffile_name_nondirectory (raw_name);
438 Vinvocation_directory = Ffile_name_directory (raw_name);
439
440 /* If we got no directory in argv[0], search PATH to find where
441 Emacs actually came from. */
442 if (NILP (Vinvocation_directory))
443 {
444 Lisp_Object found;
445 int yes = openp (Vexec_path, Vinvocation_name,
446 Vexec_suffixes, &found, make_number (X_OK), false);
447 if (yes == 1)
448 {
449 /* Add /: to the front of the name
450 if it would otherwise be treated as magic. */
451 handler = Ffind_file_name_handler (found, Qt);
452 if (! NILP (handler))
453 found = concat2 (slash_colon, found);
454 Vinvocation_directory = Ffile_name_directory (found);
455 }
456 }
457
458 if (!NILP (Vinvocation_directory)
459 && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
460 /* Emacs was started with relative path, like ./emacs.
461 Make it absolute. */
462 {
463 Lisp_Object odir =
464 original_pwd ? build_unibyte_string (original_pwd) : Qnil;
465
466 Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, odir);
467 }
468
469 Vinstallation_directory = Qnil;
470
471 if (!NILP (Vinvocation_directory))
472 {
473 dir = Vinvocation_directory;
474 #ifdef WINDOWSNT
475 /* If we are running from the build directory, set DIR to the
476 src subdirectory of the Emacs tree, like on Posix
477 platforms. */
478 if (SBYTES (dir) > sizeof ("/i386/") - 1
479 && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
480 "/i386/"))
481 dir = Fexpand_file_name (build_string ("../.."), dir);
482 #else /* !WINDOWSNT */
483 #endif
484 name = Fexpand_file_name (Vinvocation_name, dir);
485 while (1)
486 {
487 Lisp_Object tem, lib_src_exists;
488 Lisp_Object etc_exists, info_exists;
489
490 /* See if dir contains subdirs for use by Emacs.
491 Check for the ones that would exist in a build directory,
492 not including lisp and info. */
493 tem = Fexpand_file_name (build_string ("lib-src"), dir);
494 lib_src_exists = Ffile_exists_p (tem);
495
496 #ifdef MSDOS
497 /* MSDOS installations frequently remove lib-src, but we still
498 must set installation-directory, or else info won't find
499 its files (it uses the value of installation-directory). */
500 tem = Fexpand_file_name (build_string ("info"), dir);
501 info_exists = Ffile_exists_p (tem);
502 #else
503 info_exists = Qnil;
504 #endif
505
506 if (!NILP (lib_src_exists) || !NILP (info_exists))
507 {
508 tem = Fexpand_file_name (build_string ("etc"), dir);
509 etc_exists = Ffile_exists_p (tem);
510 if (!NILP (etc_exists))
511 {
512 Vinstallation_directory
513 = Ffile_name_as_directory (dir);
514 break;
515 }
516 }
517
518 /* See if dir's parent contains those subdirs. */
519 tem = Fexpand_file_name (build_string ("../lib-src"), dir);
520 lib_src_exists = Ffile_exists_p (tem);
521
522
523 #ifdef MSDOS
524 /* See the MSDOS commentary above. */
525 tem = Fexpand_file_name (build_string ("../info"), dir);
526 info_exists = Ffile_exists_p (tem);
527 #else
528 info_exists = Qnil;
529 #endif
530
531 if (!NILP (lib_src_exists) || !NILP (info_exists))
532 {
533 tem = Fexpand_file_name (build_string ("../etc"), dir);
534 etc_exists = Ffile_exists_p (tem);
535 if (!NILP (etc_exists))
536 {
537 tem = Fexpand_file_name (build_string (".."), dir);
538 Vinstallation_directory
539 = Ffile_name_as_directory (tem);
540 break;
541 }
542 }
543
544 /* If the Emacs executable is actually a link,
545 next try the dir that the link points into. */
546 tem = Ffile_symlink_p (name);
547 if (!NILP (tem))
548 {
549 name = Fexpand_file_name (tem, dir);
550 dir = Ffile_name_directory (name);
551 }
552 else
553 break;
554 }
555 }
556
557 Vcommand_line_args = Qnil;
558
559 for (i = argc - 1; i >= 0; i--)
560 {
561 if (i == 0 || i > skip_args)
562 /* For the moment, we keep arguments as is in unibyte strings.
563 They are decoded in the function command-line after we know
564 locale-coding-system. */
565 Vcommand_line_args
566 = Fcons (build_unibyte_string (argv[i]), Vcommand_line_args);
567 }
568
569 unbind_to (count, Qnil);
570 }
571
572 DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
573 doc: /* Return the program name that was used to run Emacs.
574 Any directory names are omitted. */)
575 (void)
576 {
577 return Fcopy_sequence (Vinvocation_name);
578 }
579
580 DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
581 0, 0, 0,
582 doc: /* Return the directory name in which the Emacs executable was located. */)
583 (void)
584 {
585 return Fcopy_sequence (Vinvocation_directory);
586 }
587
588 \f
589 /* Test whether the next argument in ARGV matches SSTR or a prefix of
590 LSTR (at least MINLEN characters). If so, then if VALPTR is non-null
591 (the argument is supposed to have a value) store in *VALPTR either
592 the next argument or the portion of this one after the equal sign.
593 ARGV is read starting at position *SKIPPTR; this index is advanced
594 by the number of arguments used.
595
596 Too bad we can't just use getopt for all of this, but we don't have
597 enough information to do it right. */
598
599 static bool
600 argmatch (char **argv, int argc, const char *sstr, const char *lstr,
601 int minlen, char **valptr, int *skipptr)
602 {
603 char *p = NULL;
604 ptrdiff_t arglen;
605 char *arg;
606
607 /* Don't access argv[argc]; give up in advance. */
608 if (argc <= *skipptr + 1)
609 return 0;
610
611 arg = argv[*skipptr+1];
612 if (arg == NULL)
613 return 0;
614 if (strcmp (arg, sstr) == 0)
615 {
616 if (valptr != NULL)
617 {
618 *valptr = argv[*skipptr+2];
619 *skipptr += 2;
620 }
621 else
622 *skipptr += 1;
623 return 1;
624 }
625 arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
626 ? p - arg : strlen (arg));
627 if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
628 return 0;
629 else if (valptr == NULL)
630 {
631 *skipptr += 1;
632 return 1;
633 }
634 else if (p != NULL)
635 {
636 *valptr = p+1;
637 *skipptr += 1;
638 return 1;
639 }
640 else if (argv[*skipptr+2] != NULL)
641 {
642 *valptr = argv[*skipptr+2];
643 *skipptr += 2;
644 return 1;
645 }
646 else
647 {
648 return 0;
649 }
650 }
651
652 /* Close standard output and standard error, reporting any write
653 errors as best we can. This is intended for use with atexit. */
654 static void
655 close_output_streams (void)
656 {
657 if (close_stream (stdout) != 0)
658 {
659 emacs_perror ("Write error to standard output");
660 _exit (EXIT_FAILURE);
661 }
662
663 if (close_stream (stderr) != 0)
664 _exit (EXIT_FAILURE);
665 }
666
667 /* ARGSUSED */
668 int
669 main (int argc, char **argv)
670 {
671 Lisp_Object dummy;
672 char stack_bottom_variable;
673 bool do_initial_setlocale;
674 bool dumping;
675 int skip_args = 0;
676 bool no_loadup = 0;
677 char *junk = 0;
678 char *dname_arg = 0;
679 #ifdef DAEMON_MUST_EXEC
680 char dname_arg2[80];
681 #endif
682 char *ch_to_dir = 0;
683
684 /* If we use --chdir, this records the original directory. */
685 char *original_pwd = 0;
686
687 stack_base = &dummy;
688
689 #ifndef CANNOT_DUMP
690 might_dump = !initialized;
691 #endif
692
693 #ifdef GNU_LINUX
694 if (!initialized)
695 {
696 char *heap_start = my_heap_start ();
697 heap_bss_diff = heap_start - max (my_endbss, my_endbss_static);
698 }
699 #endif
700
701 #if defined WINDOWSNT || defined HAVE_NTGUI
702 /* Set global variables used to detect Windows version. Do this as
703 early as possible. (unexw32.c calls this function as well, but
704 the additional call here is harmless.) */
705 cache_system_info ();
706 #ifdef WINDOWSNT
707 /* On Windows 9X, we have to load UNICOWS.DLL as early as possible,
708 to have non-stub implementations of APIs we need to convert file
709 names between UTF-8 and the system's ANSI codepage. */
710 maybe_load_unicows_dll ();
711 #endif
712 /* This has to be done before module_init is called below, so that
713 the latter could use the thread ID of the main thread. */
714 w32_init_main_thread ();
715 #endif
716
717 #ifdef RUN_TIME_REMAP
718 if (initialized)
719 run_time_remap (argv[0]);
720 #endif
721
722 /* If using unexmacosx.c (set by s/darwin.h), we must do this. */
723 #ifdef DARWIN_OS
724 if (!initialized)
725 unexec_init_emacs_zone ();
726 #endif
727
728 init_standard_fds ();
729 atexit (close_output_streams);
730
731 #ifdef HAVE_MODULES
732 module_init ();
733 #endif
734
735 sort_args (argc, argv);
736 argc = 0;
737 while (argv[argc]) argc++;
738
739 if (argmatch (argv, argc, "-version", "--version", 3, NULL, &skip_args))
740 {
741 const char *version, *copyright;
742 if (initialized)
743 {
744 Lisp_Object tem, tem2;
745 tem = Fsymbol_value (intern_c_string ("emacs-version"));
746 tem2 = Fsymbol_value (intern_c_string ("emacs-copyright"));
747 if (!STRINGP (tem))
748 {
749 fprintf (stderr, "Invalid value of 'emacs-version'\n");
750 exit (1);
751 }
752 if (!STRINGP (tem2))
753 {
754 fprintf (stderr, "Invalid value of 'emacs-copyright'\n");
755 exit (1);
756 }
757 else
758 {
759 version = SSDATA (tem);
760 copyright = SSDATA (tem2);
761 }
762 }
763 else
764 {
765 version = emacs_version;
766 copyright = emacs_copyright;
767 }
768 printf ("%s %s\n", PACKAGE_NAME, version);
769 printf ("%s\n", copyright);
770 printf ("%s comes with ABSOLUTELY NO WARRANTY.\n", PACKAGE_NAME);
771 printf ("You may redistribute copies of %s\n", PACKAGE_NAME);
772 printf ("under the terms of the GNU General Public License.\n");
773 printf ("For more information about these matters, ");
774 printf ("see the file named COPYING.\n");
775 exit (0);
776 }
777
778 if (argmatch (argv, argc, "-chdir", "--chdir", 4, &ch_to_dir, &skip_args))
779 {
780 #ifdef WINDOWSNT
781 /* argv[] array is kept in its original ANSI codepage encoding,
782 we need to convert to UTF-8, for chdir to work. */
783 char newdir[MAX_UTF8_PATH];
784
785 filename_from_ansi (ch_to_dir, newdir);
786 ch_to_dir = newdir;
787 #endif
788 original_pwd = emacs_get_current_dir_name ();
789 if (chdir (ch_to_dir) != 0)
790 {
791 fprintf (stderr, "%s: Can't chdir to %s: %s\n",
792 argv[0], ch_to_dir, strerror (errno));
793 exit (1);
794 }
795 }
796
797 dumping = !initialized && (strcmp (argv[argc - 1], "dump") == 0
798 || strcmp (argv[argc - 1], "bootstrap") == 0);
799
800 #ifdef HAVE_PERSONALITY_LINUX32
801 if (dumping && ! getenv ("EMACS_HEAP_EXEC"))
802 {
803 /* Set this so we only do this once. */
804 xputenv ("EMACS_HEAP_EXEC=true");
805
806 /* A flag to turn off address randomization which is introduced
807 in linux kernel shipped with fedora core 4 */
808 #define ADD_NO_RANDOMIZE 0x0040000
809 personality (PER_LINUX32 | ADD_NO_RANDOMIZE);
810 #undef ADD_NO_RANDOMIZE
811
812 execvp (argv[0], argv);
813
814 /* If the exec fails, try to dump anyway. */
815 emacs_perror (argv[0]);
816 }
817 #endif /* HAVE_PERSONALITY_LINUX32 */
818
819 #if defined (HAVE_SETRLIMIT) && defined (RLIMIT_STACK) && !defined (CYGWIN)
820 /* Extend the stack space available. Don't do that if dumping,
821 since some systems (e.g. DJGPP) might define a smaller stack
822 limit at that time. And it's not needed on Cygwin, since emacs
823 is built with an 8MB stack. Moreover, the setrlimit call can
824 cause problems on Cygwin
825 (https://www.cygwin.com/ml/cygwin/2015-07/msg00096.html). */
826 struct rlimit rlim;
827 if (getrlimit (RLIMIT_STACK, &rlim) == 0
828 && 0 <= rlim.rlim_cur && rlim.rlim_cur <= LONG_MAX)
829 {
830 long lim = rlim.rlim_cur;
831
832 /* Approximate the amount regex.c needs per unit of
833 re_max_failures, then add 33% to cover the size of the
834 smaller stacks that regex.c successively allocates and
835 discards on its way to the maximum. */
836 int ratio = 20 * sizeof (char *);
837 ratio += ratio / 3;
838
839 /* Extra space to cover what we're likely to use for other reasons. */
840 int extra = 200000;
841
842 bool try_to_grow_stack = true;
843 #ifndef CANNOT_DUMP
844 try_to_grow_stack = !noninteractive || initialized;
845 #endif
846
847 if (try_to_grow_stack)
848 {
849 long newlim = re_max_failures * ratio + extra;
850
851 /* Round the new limit to a page boundary; this is needed
852 for Darwin kernel 15.4.0 (see Bug#23622) and perhaps
853 other systems. Do not shrink the stack and do not exceed
854 rlim_max. Don't worry about values like RLIM_INFINITY
855 since in practice they are so large that the code does
856 the right thing anyway. */
857 long pagesize = getpagesize ();
858 newlim = min (newlim + pagesize - 1, rlim.rlim_max);
859 newlim -= newlim % pagesize;
860
861 if (pagesize <= newlim - lim)
862 {
863 rlim.rlim_cur = newlim;
864 if (setrlimit (RLIMIT_STACK, &rlim) == 0)
865 lim = newlim;
866 }
867 }
868
869 /* Don't let regex.c overflow the stack. */
870 re_max_failures = lim < extra ? 0 : min (lim - extra, SIZE_MAX) / ratio;
871 }
872 #endif /* HAVE_SETRLIMIT and RLIMIT_STACK and not CYGWIN */
873
874 /* Record (approximately) where the stack begins. */
875 stack_bottom = &stack_bottom_variable;
876
877 clearerr (stdin);
878
879 emacs_backtrace (-1);
880
881 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
882 /* Arrange to get warning messages as memory fills up. */
883 memory_warnings (0, malloc_warning);
884
885 /* Call malloc at least once, to run malloc_initialize_hook.
886 Also call realloc and free for consistency. */
887 free (realloc (malloc (4), 4));
888
889 #endif /* not SYSTEM_MALLOC and not HYBRID_MALLOC */
890
891 #ifdef MSDOS
892 SET_BINARY (fileno (stdin));
893 fflush (stdout);
894 SET_BINARY (fileno (stdout));
895 #endif /* MSDOS */
896
897 /* Skip initial setlocale if LC_ALL is "C", as it's not needed in that case.
898 The build procedure uses this while dumping, to ensure that the
899 dumped Emacs does not have its system locale tables initialized,
900 as that might cause screwups when the dumped Emacs starts up. */
901 {
902 char *lc_all = getenv ("LC_ALL");
903 do_initial_setlocale = ! lc_all || strcmp (lc_all, "C");
904 }
905
906 /* Set locale now, so that initial error messages are localized properly.
907 fixup_locale must wait until later, since it builds strings. */
908 if (do_initial_setlocale)
909 setlocale (LC_ALL, "");
910 text_quoting_flag = using_utf8 ();
911
912 inhibit_window_system = 0;
913
914 /* Handle the -t switch, which specifies filename to use as terminal. */
915 while (1)
916 {
917 char *term;
918 if (argmatch (argv, argc, "-t", "--terminal", 4, &term, &skip_args))
919 {
920 emacs_close (STDIN_FILENO);
921 emacs_close (STDOUT_FILENO);
922 int result = emacs_open (term, O_RDWR, 0);
923 if (result != STDIN_FILENO
924 || (fcntl (STDIN_FILENO, F_DUPFD_CLOEXEC, STDOUT_FILENO)
925 != STDOUT_FILENO))
926 {
927 char *errstring = strerror (errno);
928 fprintf (stderr, "%s: %s: %s\n", argv[0], term, errstring);
929 exit (EXIT_FAILURE);
930 }
931 if (! isatty (STDIN_FILENO))
932 {
933 fprintf (stderr, "%s: %s: not a tty\n", argv[0], term);
934 exit (EXIT_FAILURE);
935 }
936 fprintf (stderr, "Using %s\n", term);
937 #ifdef HAVE_WINDOW_SYSTEM
938 inhibit_window_system = true; /* -t => -nw */
939 #endif
940 }
941 else
942 break;
943 }
944
945 /* Command line option --no-windows is deprecated and thus not mentioned
946 in the manual and usage information. */
947 if (argmatch (argv, argc, "-nw", "--no-window-system", 6, NULL, &skip_args)
948 || argmatch (argv, argc, "-nw", "--no-windows", 6, NULL, &skip_args))
949 inhibit_window_system = 1;
950
951 /* Handle the -batch switch, which means don't do interactive display. */
952 noninteractive = 0;
953 if (argmatch (argv, argc, "-batch", "--batch", 5, NULL, &skip_args))
954 {
955 noninteractive = 1;
956 Vundo_outer_limit = Qnil;
957 }
958 if (argmatch (argv, argc, "-script", "--script", 3, &junk, &skip_args))
959 {
960 noninteractive = 1; /* Set batch mode. */
961 /* Convert --script to -scriptload, un-skip it, and sort again
962 so that it will be handled in proper sequence. */
963 /* FIXME broken for --script=FILE - is that supposed to work? */
964 argv[skip_args - 1] = (char *) "-scriptload";
965 skip_args -= 2;
966 sort_args (argc, argv);
967 }
968
969 /* Handle the --help option, which gives a usage message. */
970 if (argmatch (argv, argc, "-help", "--help", 3, NULL, &skip_args))
971 {
972 int i;
973 printf ("Usage: %s [OPTION-OR-FILENAME]...\n", argv[0]);
974 for (i = 0; i < ARRAYELTS (usage_message); i++)
975 fputs (usage_message[i], stdout);
976 exit (0);
977 }
978
979 #ifndef WINDOWSNT
980 /* Make sure IS_DAEMON starts up as false. */
981 daemon_pipe[1] = 0;
982 #else
983 w32_daemon_event = NULL;
984 #endif
985
986
987 int sockfd = -1;
988
989 if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
990 || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
991 {
992 #ifndef DOS_NT
993 pid_t f;
994
995 /* Start as a daemon: fork a new child process which will run the
996 rest of the initialization code, then exit.
997
998 Detaching a daemon requires the following steps:
999 - fork
1000 - setsid
1001 - exit the parent
1002 - close the tty file-descriptors
1003
1004 We only want to do the last 2 steps once the daemon is ready to
1005 serve requests, i.e. after loading .emacs (initialization).
1006 OTOH initialization may start subprocesses (e.g. ispell) and these
1007 should be run from the proper process (the one that will end up
1008 running as daemon) and with the proper "session id" in order for
1009 them to keep working after detaching, so fork and setsid need to be
1010 performed before initialization.
1011
1012 We want to avoid exiting before the server socket is ready, so
1013 use a pipe for synchronization. The parent waits for the child
1014 to close its end of the pipe (using `daemon-initialized')
1015 before exiting. */
1016 if (emacs_pipe (daemon_pipe) != 0)
1017 {
1018 fprintf (stderr, "Cannot pipe!\n");
1019 exit (1);
1020 }
1021
1022 #ifdef HAVE_LIBSYSTEMD
1023 /* Read the number of sockets passed through by systemd. */
1024 int systemd_socket = sd_listen_fds (1);
1025
1026 if (systemd_socket > 1)
1027 fprintf (stderr,
1028 ("\n"
1029 "Warning: systemd passed more than one socket to Emacs.\n"
1030 "Try 'Accept=false' in the Emacs socket unit file.\n"));
1031 else if (systemd_socket == 1
1032 && (0 < sd_is_socket (SD_LISTEN_FDS_START,
1033 AF_UNSPEC, SOCK_STREAM, 1)))
1034 sockfd = SD_LISTEN_FDS_START;
1035 #endif /* HAVE_LIBSYSTEMD */
1036
1037 #ifndef DAEMON_MUST_EXEC
1038 #ifdef USE_GTK
1039 fprintf (stderr, "\nWarning: due to a long standing Gtk+ bug\nhttp://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
1040 Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.\n\
1041 Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.\n");
1042 #endif /* USE_GTK */
1043 f = fork ();
1044 #else /* DAEMON_MUST_EXEC */
1045 if (!dname_arg || !strchr (dname_arg, '\n'))
1046 f = fork (); /* in orig */
1047 else
1048 f = 0; /* in exec'd */
1049 #endif /* !DAEMON_MUST_EXEC */
1050 if (f > 0)
1051 {
1052 int retval;
1053 char buf[1];
1054
1055 /* Close unused writing end of the pipe. */
1056 emacs_close (daemon_pipe[1]);
1057
1058 /* Just wait for the child to close its end of the pipe. */
1059 do
1060 {
1061 retval = read (daemon_pipe[0], &buf, 1);
1062 }
1063 while (retval == -1 && errno == EINTR);
1064
1065 if (retval < 0)
1066 {
1067 fprintf (stderr, "Error reading status from child\n");
1068 exit (1);
1069 }
1070 else if (retval == 0)
1071 {
1072 fprintf (stderr, "Error: server did not start correctly\n");
1073 exit (1);
1074 }
1075
1076 emacs_close (daemon_pipe[0]);
1077 exit (0);
1078 }
1079 if (f < 0)
1080 {
1081 emacs_perror ("fork");
1082 exit (EXIT_CANCELED);
1083 }
1084
1085 #ifdef DAEMON_MUST_EXEC
1086 {
1087 /* In orig process, forked as child, OR in exec'd. */
1088 if (!dname_arg || !strchr (dname_arg, '\n'))
1089 { /* In orig, child: now exec w/special daemon name. */
1090 char fdStr[80];
1091 int fdStrlen =
1092 snprintf (fdStr, sizeof fdStr,
1093 "--daemon=\n%d,%d\n%s", daemon_pipe[0],
1094 daemon_pipe[1], dname_arg ? dname_arg : "");
1095
1096 if (! (0 <= fdStrlen && fdStrlen < sizeof fdStr))
1097 {
1098 fprintf (stderr, "daemon: child name too long\n");
1099 exit (EXIT_CANNOT_INVOKE);
1100 }
1101
1102 argv[skip_args] = fdStr;
1103
1104 fcntl (daemon_pipe[0], F_SETFD, 0);
1105 fcntl (daemon_pipe[1], F_SETFD, 0);
1106 execvp (argv[0], argv);
1107 emacs_perror (argv[0]);
1108 exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
1109 }
1110
1111 /* In exec'd: parse special dname into pipe and name info. */
1112 if (!dname_arg || !strchr (dname_arg, '\n')
1113 || strlen (dname_arg) < 1 || strlen (dname_arg) > 70)
1114 {
1115 fprintf (stderr, "emacs daemon: daemon name absent or too long\n");
1116 exit (EXIT_CANNOT_INVOKE);
1117 }
1118 dname_arg2[0] = '\0';
1119 sscanf (dname_arg, "\n%d,%d\n%s", &(daemon_pipe[0]), &(daemon_pipe[1]),
1120 dname_arg2);
1121 dname_arg = *dname_arg2 ? dname_arg2 : NULL;
1122 fcntl (daemon_pipe[1], F_SETFD, FD_CLOEXEC);
1123 }
1124 #endif /* DAEMON_MUST_EXEC */
1125
1126 /* Close unused reading end of the pipe. */
1127 emacs_close (daemon_pipe[0]);
1128
1129 setsid ();
1130 #elif defined(WINDOWSNT)
1131 /* Indicate that we want daemon mode. */
1132 w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
1133 if (w32_daemon_event == NULL)
1134 {
1135 fprintf (stderr, "Couldn't create MS-Windows event for daemon: %s\n",
1136 w32_strerror (0));
1137 exit (1);
1138 }
1139 #else /* MSDOS */
1140 fprintf (stderr, "This platform does not support the -daemon flag.\n");
1141 exit (1);
1142 #endif /* MSDOS */
1143 if (dname_arg)
1144 daemon_name = xstrdup (dname_arg);
1145 }
1146
1147 #if defined HAVE_PTHREAD && !defined SYSTEM_MALLOC \
1148 && !defined DOUG_LEA_MALLOC && !defined HYBRID_MALLOC
1149 # ifndef CANNOT_DUMP
1150 /* Do not make gmalloc thread-safe when creating bootstrap-emacs, as
1151 that causes an infinite recursive loop with FreeBSD. See
1152 Bug#14569. The part of this bug involving Cygwin is no longer
1153 relevant, now that Cygwin defines HYBRID_MALLOC. */
1154 if (!noninteractive || initialized)
1155 # endif
1156 malloc_enable_thread ();
1157 #endif
1158
1159 init_signals (dumping);
1160
1161 noninteractive1 = noninteractive;
1162
1163 /* Perform basic initializations (not merely interning symbols). */
1164
1165 if (!initialized)
1166 {
1167 init_alloc_once ();
1168 init_obarray ();
1169 init_eval_once ();
1170 init_charset_once ();
1171 init_coding_once ();
1172 init_syntax_once (); /* Create standard syntax table. */
1173 init_category_once (); /* Create standard category table. */
1174 init_casetab_once (); /* Must be done before init_buffer_once. */
1175 init_buffer_once (); /* Create buffer table and some buffers. */
1176 init_minibuf_once (); /* Create list of minibuffers. */
1177 /* Must precede init_window_once. */
1178
1179 /* Call syms_of_xfaces before init_window_once because that
1180 function creates Vterminal_frame. Termcap frames now use
1181 faces, and the face implementation uses some symbols as
1182 face names. */
1183 syms_of_xfaces ();
1184 /* XXX syms_of_keyboard uses some symbols in keymap.c. It would
1185 be better to arrange things not to have this dependency. */
1186 syms_of_keymap ();
1187 /* Call syms_of_keyboard before init_window_once because
1188 keyboard sets up symbols that include some face names that
1189 the X support will want to use. This can happen when
1190 CANNOT_DUMP is defined. */
1191 syms_of_keyboard ();
1192
1193 /* Called before syms_of_fileio, because it sets up Qerror_condition. */
1194 syms_of_data ();
1195 syms_of_fns (); /* Before syms_of_charset which uses hashtables. */
1196 syms_of_fileio ();
1197 /* Before syms_of_coding to initialize Vgc_cons_threshold. */
1198 syms_of_alloc ();
1199 /* May call Ffuncall and so GC, thus the latter should be initialized. */
1200 init_print_once ();
1201 /* Before syms_of_coding because it initializes Qcharsetp. */
1202 syms_of_charset ();
1203 /* Before init_window_once, because it sets up the
1204 Vcoding_system_hash_table. */
1205 syms_of_coding (); /* This should be after syms_of_fileio. */
1206
1207 init_window_once (); /* Init the window system. */
1208 #ifdef HAVE_WINDOW_SYSTEM
1209 init_fringe_once (); /* Swap bitmaps if necessary. */
1210 #endif /* HAVE_WINDOW_SYSTEM */
1211 }
1212
1213 init_alloc ();
1214
1215 if (do_initial_setlocale)
1216 {
1217 fixup_locale ();
1218 Vsystem_messages_locale = Vprevious_system_messages_locale;
1219 Vsystem_time_locale = Vprevious_system_time_locale;
1220 }
1221
1222 init_eval ();
1223 init_atimer ();
1224 running_asynch_code = 0;
1225 init_random ();
1226
1227 no_loadup
1228 = argmatch (argv, argc, "-nl", "--no-loadup", 6, NULL, &skip_args);
1229
1230 no_site_lisp
1231 = argmatch (argv, argc, "-nsl", "--no-site-lisp", 11, NULL, &skip_args);
1232
1233 build_details = ! argmatch (argv, argc, "-no-build-details",
1234 "--no-build-details", 7, NULL, &skip_args);
1235
1236 #ifdef HAVE_NS
1237 ns_pool = ns_alloc_autorelease_pool ();
1238 #ifdef NS_IMPL_GNUSTEP
1239 /* GNUstep stupidly resets our locale settings after we made them. */
1240 fixup_locale ();
1241 #endif
1242
1243 if (!noninteractive)
1244 {
1245 #ifdef NS_IMPL_COCOA
1246 /* Started from GUI? */
1247 /* FIXME: Do the right thing if getenv returns NULL, or if
1248 chdir fails. */
1249 if (! inhibit_window_system && ! isatty (STDIN_FILENO) && ! ch_to_dir)
1250 chdir (getenv ("HOME"));
1251 if (skip_args < argc)
1252 {
1253 if (!strncmp (argv[skip_args], "-psn", 4))
1254 {
1255 skip_args += 1;
1256 if (! ch_to_dir) chdir (getenv ("HOME"));
1257 }
1258 else if (skip_args+1 < argc && !strncmp (argv[skip_args+1], "-psn", 4))
1259 {
1260 skip_args += 2;
1261 if (! ch_to_dir) chdir (getenv ("HOME"));
1262 }
1263 }
1264 #endif /* COCOA */
1265 }
1266 #endif /* HAVE_NS */
1267
1268 #ifdef HAVE_X_WINDOWS
1269 /* Stupid kludge to catch command-line display spec. We can't
1270 handle this argument entirely in window system dependent code
1271 because we don't even know which window system dependent code
1272 to run until we've recognized this argument. */
1273 {
1274 char *displayname = 0;
1275 int count_before = skip_args;
1276
1277 /* Skip any number of -d options, but only use the last one. */
1278 while (1)
1279 {
1280 int count_before_this = skip_args;
1281
1282 if (argmatch (argv, argc, "-d", "--display", 3, &displayname, &skip_args))
1283 display_arg = 1;
1284 else if (argmatch (argv, argc, "-display", 0, 3, &displayname, &skip_args))
1285 display_arg = 1;
1286 else
1287 break;
1288
1289 count_before = count_before_this;
1290 }
1291
1292 /* If we have the form --display=NAME,
1293 convert it into -d name.
1294 This requires inserting a new element into argv. */
1295 if (displayname && count_before < skip_args)
1296 {
1297 if (skip_args == count_before + 1)
1298 {
1299 memmove (argv + count_before + 3, argv + count_before + 2,
1300 (argc - (count_before + 2)) * sizeof *argv);
1301 argv[count_before + 2] = displayname;
1302 argc++;
1303 }
1304 argv[count_before + 1] = (char *) "-d";
1305 }
1306
1307 if (! no_site_lisp)
1308 {
1309 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1310 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1311 no_site_lisp = 1;
1312 }
1313
1314 /* Don't actually discard this arg. */
1315 skip_args = count_before;
1316 }
1317 #else /* !HAVE_X_WINDOWS */
1318 if (! no_site_lisp)
1319 {
1320 int count_before = skip_args;
1321
1322 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1323 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1324 no_site_lisp = 1;
1325
1326 skip_args = count_before;
1327 }
1328 #endif
1329
1330 /* argmatch must not be used after here,
1331 except when building temacs
1332 because the -d argument has not been skipped in skip_args. */
1333
1334 #ifdef MSDOS
1335 /* Call early 'cause init_environment needs it. */
1336 init_dosfns ();
1337 /* Set defaults for several environment variables. */
1338 if (initialized)
1339 init_environment (argc, argv, skip_args);
1340 else
1341 tzset ();
1342 #endif /* MSDOS */
1343
1344 #ifdef HAVE_KQUEUE
1345 globals_of_kqueue ();
1346 #endif
1347
1348 #ifdef HAVE_GFILENOTIFY
1349 globals_of_gfilenotify ();
1350 #endif
1351
1352 #ifdef WINDOWSNT
1353 globals_of_w32 ();
1354 #ifdef HAVE_W32NOTIFY
1355 globals_of_w32notify ();
1356 #endif
1357 /* Initialize environment from registry settings. */
1358 init_environment (argv);
1359 init_ntproc (dumping); /* must precede init_editfns. */
1360 #endif
1361
1362 #ifdef HAVE_NS
1363 /* Initialize the locale from user defaults. */
1364 ns_init_locale ();
1365 #endif
1366
1367 /* Initialize and GC-protect Vinitial_environment and
1368 Vprocess_environment before set_initial_environment fills them
1369 in. */
1370 if (!initialized)
1371 syms_of_callproc ();
1372 /* egetenv is a pretty low-level facility, which may get called in
1373 many circumstances; it seems flimsy to put off initializing it
1374 until calling init_callproc. Do not do it when dumping. */
1375 if (! dumping)
1376 set_initial_environment ();
1377
1378 /* AIX crashes are reported in system versions 3.2.3 and 3.2.4
1379 if this is not done. Do it after set_global_environment so that we
1380 don't pollute Vglobal_environment. */
1381 /* Setting LANG here will defeat the startup locale processing... */
1382 #ifdef AIX
1383 xputenv ("LANG=C");
1384 #endif
1385
1386 /* Init buffer storage and default directory of main buffer. */
1387 init_buffer (initialized);
1388
1389 init_callproc_1 (); /* Must precede init_cmdargs and init_sys_modes. */
1390
1391 /* Must precede init_lread. */
1392 init_cmdargs (argc, argv, skip_args, original_pwd);
1393
1394 if (initialized)
1395 {
1396 /* Erase any pre-dump messages in the message log, to avoid confusion. */
1397 Lisp_Object old_log_max;
1398 old_log_max = Vmessage_log_max;
1399 XSETFASTINT (Vmessage_log_max, 0);
1400 message_dolog ("", 0, 1, 0);
1401 Vmessage_log_max = old_log_max;
1402 }
1403
1404 init_callproc (); /* Must follow init_cmdargs but not init_sys_modes. */
1405 init_fileio ();
1406 init_lread ();
1407 #ifdef WINDOWSNT
1408 /* Check to see if Emacs has been installed correctly. */
1409 check_windows_init_file ();
1410 #endif
1411
1412 /* Intern the names of all standard functions and variables;
1413 define standard keys. */
1414
1415 if (!initialized)
1416 {
1417 /* The basic levels of Lisp must come first. Note that
1418 syms_of_data and some others have already been called. */
1419 syms_of_chartab ();
1420 syms_of_lread ();
1421 syms_of_print ();
1422 syms_of_eval ();
1423 syms_of_floatfns ();
1424
1425 syms_of_buffer ();
1426 syms_of_bytecode ();
1427 syms_of_callint ();
1428 syms_of_casefiddle ();
1429 syms_of_casetab ();
1430 syms_of_category ();
1431 syms_of_ccl ();
1432 syms_of_character ();
1433 syms_of_cmds ();
1434 syms_of_dired ();
1435 syms_of_display ();
1436 syms_of_doc ();
1437 syms_of_editfns ();
1438 syms_of_emacs ();
1439 syms_of_filelock ();
1440 syms_of_indent ();
1441 syms_of_insdel ();
1442 /* syms_of_keymap (); */
1443 syms_of_macros ();
1444 syms_of_marker ();
1445 syms_of_minibuf ();
1446 syms_of_process ();
1447 syms_of_search ();
1448 syms_of_frame ();
1449 syms_of_syntax ();
1450 syms_of_terminal ();
1451 syms_of_term ();
1452 syms_of_undo ();
1453
1454 #ifdef HAVE_MODULES
1455 syms_of_module ();
1456 #endif
1457
1458 #ifdef HAVE_SOUND
1459 syms_of_sound ();
1460 #endif
1461 syms_of_textprop ();
1462 syms_of_composite ();
1463 #ifdef WINDOWSNT
1464 syms_of_ntproc ();
1465 #endif /* WINDOWSNT */
1466 #if defined CYGWIN
1467 syms_of_cygw32 ();
1468 #endif
1469 syms_of_window ();
1470 syms_of_xdisp ();
1471 syms_of_font ();
1472 #ifdef HAVE_WINDOW_SYSTEM
1473 syms_of_fringe ();
1474 syms_of_image ();
1475 #endif /* HAVE_WINDOW_SYSTEM */
1476 #ifdef HAVE_X_WINDOWS
1477 syms_of_xterm ();
1478 syms_of_xfns ();
1479 syms_of_xmenu ();
1480 syms_of_fontset ();
1481 syms_of_xwidget ();
1482 syms_of_xsettings ();
1483 #ifdef HAVE_X_SM
1484 syms_of_xsmfns ();
1485 #endif
1486 #ifdef HAVE_X11
1487 syms_of_xselect ();
1488 #endif
1489 #endif /* HAVE_X_WINDOWS */
1490
1491 #ifdef HAVE_LIBXML2
1492 syms_of_xml ();
1493 #endif
1494
1495 #ifdef HAVE_ZLIB
1496 syms_of_decompress ();
1497 #endif
1498
1499 syms_of_menu ();
1500
1501 #ifdef HAVE_NTGUI
1502 syms_of_w32term ();
1503 syms_of_w32fns ();
1504 syms_of_w32menu ();
1505 syms_of_fontset ();
1506 #endif /* HAVE_NTGUI */
1507
1508 #if defined WINDOWSNT || defined HAVE_NTGUI
1509 syms_of_w32select ();
1510 #endif
1511
1512 #ifdef MSDOS
1513 syms_of_xmenu ();
1514 syms_of_dosfns ();
1515 syms_of_msdos ();
1516 syms_of_win16select ();
1517 #endif /* MSDOS */
1518
1519 #ifdef HAVE_NS
1520 syms_of_nsterm ();
1521 syms_of_nsfns ();
1522 syms_of_nsmenu ();
1523 syms_of_nsselect ();
1524 syms_of_fontset ();
1525 #endif /* HAVE_NS */
1526
1527 syms_of_gnutls ();
1528
1529 #ifdef HAVE_INOTIFY
1530 syms_of_inotify ();
1531 #endif /* HAVE_INOTIFY */
1532
1533 #ifdef HAVE_KQUEUE
1534 syms_of_kqueue ();
1535 #endif /* HAVE_KQUEUE */
1536
1537 #ifdef HAVE_GFILENOTIFY
1538 syms_of_gfilenotify ();
1539 #endif /* HAVE_GFILENOTIFY */
1540
1541 #ifdef HAVE_DBUS
1542 syms_of_dbusbind ();
1543 #endif /* HAVE_DBUS */
1544
1545 #ifdef WINDOWSNT
1546 syms_of_ntterm ();
1547 #ifdef HAVE_W32NOTIFY
1548 syms_of_w32notify ();
1549 #endif /* HAVE_W32NOTIFY */
1550 #endif /* WINDOWSNT */
1551
1552 syms_of_profiler ();
1553
1554 keys_of_casefiddle ();
1555 keys_of_cmds ();
1556 keys_of_buffer ();
1557 keys_of_keyboard ();
1558 keys_of_keymap ();
1559 keys_of_window ();
1560 }
1561 else
1562 {
1563 /* Initialization that must be done even if the global variable
1564 initialized is non zero. */
1565 #ifdef HAVE_NTGUI
1566 globals_of_w32font ();
1567 globals_of_w32fns ();
1568 globals_of_w32menu ();
1569 #endif /* HAVE_NTGUI */
1570
1571 #if defined WINDOWSNT || defined HAVE_NTGUI
1572 globals_of_w32select ();
1573 #endif
1574 }
1575
1576 init_charset ();
1577
1578 /* This calls putenv and so must precede init_process_emacs. Also,
1579 it sets Voperating_system_release, which init_process_emacs uses. */
1580 init_editfns (dumping);
1581
1582 /* These two call putenv. */
1583 #ifdef HAVE_DBUS
1584 init_dbusbind ();
1585 #endif
1586 #ifdef USE_GTK
1587 init_xterm ();
1588 #endif
1589
1590 /* This can create a thread that may call getenv, so it must follow
1591 all calls to putenv and setenv. Also, this sets up
1592 add_keyboard_wait_descriptor, which init_display uses. */
1593 init_process_emacs (sockfd);
1594
1595 init_keyboard (); /* This too must precede init_sys_modes. */
1596 if (!noninteractive)
1597 init_display (); /* Determine terminal type. Calls init_sys_modes. */
1598 #if HAVE_W32NOTIFY
1599 else
1600 init_crit (); /* w32notify.c needs this in batch mode. */
1601 #endif /* HAVE_W32NOTIFY */
1602 init_xdisp ();
1603 #ifdef HAVE_WINDOW_SYSTEM
1604 init_fringe ();
1605 #endif /* HAVE_WINDOW_SYSTEM */
1606 init_macros ();
1607 init_window ();
1608 init_font ();
1609
1610 if (!initialized)
1611 {
1612 char *file;
1613 /* Handle -l loadup, args passed by Makefile. */
1614 if (argmatch (argv, argc, "-l", "--load", 3, &file, &skip_args))
1615 {
1616 #ifdef WINDOWSNT
1617 char file_utf8[MAX_UTF8_PATH];
1618
1619 if (filename_from_ansi (file, file_utf8) == 0)
1620 file = file_utf8;
1621 #endif
1622 Vtop_level = list2 (Qload, build_unibyte_string (file));
1623 }
1624 /* Unless next switch is -nl, load "loadup.el" first thing. */
1625 if (! no_loadup)
1626 Vtop_level = list2 (Qload, build_string ("loadup.el"));
1627 }
1628
1629 /* Set up for profiling. This is known to work on FreeBSD,
1630 GNU/Linux and MinGW. It might work on some other systems too.
1631 Give it a try and tell us if it works on your system. To compile
1632 for profiling, use the configure option --enable-profiling. */
1633 #if defined (__FreeBSD__) || defined (GNU_LINUX) || defined (__MINGW32__)
1634 #ifdef PROFILING
1635 if (initialized)
1636 {
1637 #ifdef __MINGW32__
1638 extern unsigned char etext asm ("etext");
1639 #else
1640 extern char etext;
1641 #endif
1642
1643 atexit (_mcleanup);
1644 monstartup ((uintptr_t) __executable_start, (uintptr_t) &etext);
1645 }
1646 else
1647 moncontrol (0);
1648 #endif
1649 #endif
1650
1651 initialized = 1;
1652
1653 /* Enter editor command loop. This never returns. */
1654 Frecursive_edit ();
1655 /* NOTREACHED */
1656 return 0;
1657 }
1658 \f
1659 /* Sort the args so we can find the most important ones
1660 at the beginning of argv. */
1661
1662 /* First, here's a table of all the standard options. */
1663
1664 struct standard_args
1665 {
1666 const char *name;
1667 const char *longname;
1668 int priority;
1669 int nargs;
1670 };
1671
1672 static const struct standard_args standard_args[] =
1673 {
1674 { "-version", "--version", 150, 0 },
1675 { "-chdir", "--chdir", 130, 1 },
1676 { "-t", "--terminal", 120, 1 },
1677 { "-nw", "--no-window-system", 110, 0 },
1678 { "-nw", "--no-windows", 110, 0 },
1679 { "-batch", "--batch", 100, 0 },
1680 { "-script", "--script", 100, 1 },
1681 { "-daemon", "--daemon", 99, 0 },
1682 { "-help", "--help", 90, 0 },
1683 { "-nl", "--no-loadup", 70, 0 },
1684 { "-nsl", "--no-site-lisp", 65, 0 },
1685 { "-no-build-details", "--no-build-details", 63, 0 },
1686 /* -d must come last before the options handled in startup.el. */
1687 { "-d", "--display", 60, 1 },
1688 { "-display", 0, 60, 1 },
1689 /* Now for the options handled in `command-line' (startup.el). */
1690 /* (Note that to imply -nsl, -Q is partially handled here.) */
1691 { "-Q", "--quick", 55, 0 },
1692 { "-quick", 0, 55, 0 },
1693 { "-q", "--no-init-file", 50, 0 },
1694 { "-no-init-file", 0, 50, 0 },
1695 { "-no-x-resources", "--no-x-resources", 40, 0 },
1696 { "-no-site-file", "--no-site-file", 40, 0 },
1697 { "-u", "--user", 30, 1 },
1698 { "-user", 0, 30, 1 },
1699 { "-debug-init", "--debug-init", 20, 0 },
1700 { "-iconic", "--iconic", 15, 0 },
1701 { "-D", "--basic-display", 12, 0},
1702 { "-basic-display", 0, 12, 0},
1703 { "-nbc", "--no-blinking-cursor", 12, 0 },
1704 /* Now for the options handled in `command-line-1' (startup.el). */
1705 { "-nbi", "--no-bitmap-icon", 10, 0 },
1706 { "-bg", "--background-color", 10, 1 },
1707 { "-background", 0, 10, 1 },
1708 { "-fg", "--foreground-color", 10, 1 },
1709 { "-foreground", 0, 10, 1 },
1710 { "-bd", "--border-color", 10, 1 },
1711 { "-bw", "--border-width", 10, 1 },
1712 { "-ib", "--internal-border", 10, 1 },
1713 { "-ms", "--mouse-color", 10, 1 },
1714 { "-cr", "--cursor-color", 10, 1 },
1715 { "-fn", "--font", 10, 1 },
1716 { "-font", 0, 10, 1 },
1717 { "-fs", "--fullscreen", 10, 0 },
1718 { "-fw", "--fullwidth", 10, 0 },
1719 { "-fh", "--fullheight", 10, 0 },
1720 { "-mm", "--maximized", 10, 0 },
1721 { "-g", "--geometry", 10, 1 },
1722 { "-geometry", 0, 10, 1 },
1723 { "-T", "--title", 10, 1 },
1724 { "-title", 0, 10, 1 },
1725 { "-name", "--name", 10, 1 },
1726 { "-xrm", "--xrm", 10, 1 },
1727 { "-parent-id", "--parent-id", 10, 1 },
1728 { "-r", "--reverse-video", 5, 0 },
1729 { "-rv", 0, 5, 0 },
1730 { "-reverse", 0, 5, 0 },
1731 { "-hb", "--horizontal-scroll-bars", 5, 0 },
1732 { "-vb", "--vertical-scroll-bars", 5, 0 },
1733 { "-color", "--color", 5, 0},
1734 { "-no-splash", "--no-splash", 3, 0 },
1735 { "-no-desktop", "--no-desktop", 3, 0 },
1736 #ifdef HAVE_NS
1737 { "-NSAutoLaunch", 0, 5, 1 },
1738 { "-NXAutoLaunch", 0, 5, 1 },
1739 { "-_NSMachLaunch", 0, 85, 1 },
1740 { "-MachLaunch", 0, 85, 1 },
1741 { "-macosx", 0, 85, 0 },
1742 { "-NSHost", 0, 85, 1 },
1743 #endif
1744 /* These have the same priority as ordinary file name args,
1745 so they are not reordered with respect to those. */
1746 { "-L", "--directory", 0, 1 },
1747 { "-directory", 0, 0, 1 },
1748 { "-l", "--load", 0, 1 },
1749 { "-load", 0, 0, 1 },
1750 /* This has no longname, because using --scriptload confuses sort_args,
1751 because then the --script long option seems to match twice; ie
1752 you can't have a long option which is a prefix of another long
1753 option. In any case, this is entirely an internal option. */
1754 { "-scriptload", NULL, 0, 1 },
1755 { "-f", "--funcall", 0, 1 },
1756 { "-funcall", 0, 0, 1 },
1757 { "-eval", "--eval", 0, 1 },
1758 { "-execute", "--execute", 0, 1 },
1759 { "-find-file", "--find-file", 0, 1 },
1760 { "-visit", "--visit", 0, 1 },
1761 { "-file", "--file", 0, 1 },
1762 { "-insert", "--insert", 0, 1 },
1763 #ifdef HAVE_NS
1764 { "-NXOpen", 0, 0, 1 },
1765 { "-NXOpenTemp", 0, 0, 1 },
1766 { "-NSOpen", 0, 0, 1 },
1767 { "-NSOpenTemp", 0, 0, 1 },
1768 { "-GSFilePath", 0, 0, 1 },
1769 #endif
1770 /* This should be processed after ordinary file name args and the like. */
1771 { "-kill", "--kill", -10, 0 },
1772 };
1773
1774 /* Reorder the elements of ARGV (assumed to have ARGC elements)
1775 so that the highest priority ones come first.
1776 Do not change the order of elements of equal priority.
1777 If an option takes an argument, keep it and its argument together.
1778
1779 If an option that takes no argument appears more
1780 than once, eliminate all but one copy of it. */
1781
1782 static void
1783 sort_args (int argc, char **argv)
1784 {
1785 char **new = xmalloc (argc * sizeof *new);
1786 /* For each element of argv,
1787 the corresponding element of options is:
1788 0 for an option that takes no arguments,
1789 1 for an option that takes one argument, etc.
1790 -1 for an ordinary non-option argument. */
1791 int *options = xnmalloc (argc, sizeof *options);
1792 int *priority = xnmalloc (argc, sizeof *priority);
1793 int to = 1;
1794 int incoming_used = 1;
1795 int from;
1796 int i;
1797
1798 /* Categorize all the options,
1799 and figure out which argv elts are option arguments. */
1800 for (from = 1; from < argc; from++)
1801 {
1802 options[from] = -1;
1803 priority[from] = 0;
1804 if (argv[from][0] == '-')
1805 {
1806 int match;
1807
1808 /* If we have found "--", don't consider
1809 any more arguments as options. */
1810 if (argv[from][1] == '-' && argv[from][2] == 0)
1811 {
1812 /* Leave the "--", and everything following it, at the end. */
1813 for (; from < argc; from++)
1814 {
1815 priority[from] = -100;
1816 options[from] = -1;
1817 }
1818 break;
1819 }
1820
1821 /* Look for a match with a known old-fashioned option. */
1822 for (i = 0; i < ARRAYELTS (standard_args); i++)
1823 if (!strcmp (argv[from], standard_args[i].name))
1824 {
1825 options[from] = standard_args[i].nargs;
1826 priority[from] = standard_args[i].priority;
1827 if (from + standard_args[i].nargs >= argc)
1828 fatal ("Option '%s' requires an argument\n", argv[from]);
1829 from += standard_args[i].nargs;
1830 goto done;
1831 }
1832
1833 /* Look for a match with a known long option.
1834 MATCH is -1 if no match so far, -2 if two or more matches so far,
1835 >= 0 (the table index of the match) if just one match so far. */
1836 if (argv[from][1] == '-')
1837 {
1838 char const *equals = strchr (argv[from], '=');
1839 ptrdiff_t thislen =
1840 equals ? equals - argv[from] : strlen (argv[from]);
1841
1842 match = -1;
1843
1844 for (i = 0; i < ARRAYELTS (standard_args); i++)
1845 if (standard_args[i].longname
1846 && !strncmp (argv[from], standard_args[i].longname,
1847 thislen))
1848 {
1849 if (match == -1)
1850 match = i;
1851 else
1852 match = -2;
1853 }
1854
1855 /* If we found exactly one match, use that. */
1856 if (match >= 0)
1857 {
1858 options[from] = standard_args[match].nargs;
1859 priority[from] = standard_args[match].priority;
1860 /* If --OPTION=VALUE syntax is used,
1861 this option uses just one argv element. */
1862 if (equals != 0)
1863 options[from] = 0;
1864 if (from + options[from] >= argc)
1865 fatal ("Option '%s' requires an argument\n", argv[from]);
1866 from += options[from];
1867 }
1868 /* FIXME When match < 0, shouldn't there be some error,
1869 or at least indication to the user that there was a
1870 problem? */
1871 }
1872 done: ;
1873 }
1874 }
1875
1876 /* Copy the arguments, in order of decreasing priority, to NEW. */
1877 new[0] = argv[0];
1878 while (incoming_used < argc)
1879 {
1880 int best = -1;
1881 int best_priority = -9999;
1882
1883 /* Find the highest priority remaining option.
1884 If several have equal priority, take the first of them. */
1885 for (from = 1; from < argc; from++)
1886 {
1887 if (argv[from] != 0 && priority[from] > best_priority)
1888 {
1889 best_priority = priority[from];
1890 best = from;
1891 }
1892 /* Skip option arguments--they are tied to the options. */
1893 if (options[from] > 0)
1894 from += options[from];
1895 }
1896
1897 if (best < 0)
1898 emacs_abort ();
1899
1900 /* Copy the highest priority remaining option, with its args, to NEW.
1901 Unless it is a duplicate of the previous one. */
1902 if (! (options[best] == 0
1903 && ! strcmp (new[to - 1], argv[best])))
1904 {
1905 new[to++] = argv[best];
1906 for (i = 0; i < options[best]; i++)
1907 new[to++] = argv[best + i + 1];
1908 }
1909
1910 incoming_used += 1 + (options[best] > 0 ? options[best] : 0);
1911
1912 /* Clear out this option in ARGV. */
1913 argv[best] = 0;
1914 for (i = 0; i < options[best]; i++)
1915 argv[best + i + 1] = 0;
1916 }
1917
1918 /* If duplicate options were deleted, fill up extra space with null ptrs. */
1919 while (to < argc)
1920 new[to++] = 0;
1921
1922 memcpy (argv, new, sizeof (char *) * argc);
1923
1924 xfree (options);
1925 xfree (new);
1926 xfree (priority);
1927 }
1928 \f
1929 DEFUN ("kill-emacs", Fkill_emacs, Skill_emacs, 0, 1, "P",
1930 doc: /* Exit the Emacs job and kill it.
1931 If ARG is an integer, return ARG as the exit program code.
1932 If ARG is a string, stuff it as keyboard input.
1933
1934 This function is called upon receipt of the signals SIGTERM
1935 or SIGHUP, and upon SIGINT in batch mode.
1936
1937 The value of `kill-emacs-hook', if not void,
1938 is a list of functions (of no args),
1939 all of which are called before Emacs is actually killed. */
1940 attributes: noreturn)
1941 (Lisp_Object arg)
1942 {
1943 int exit_code;
1944
1945 /* Fsignal calls emacs_abort () if it sees that waiting_for_input is
1946 set. */
1947 waiting_for_input = 0;
1948 run_hook (Qkill_emacs_hook);
1949
1950 #ifdef HAVE_X_WINDOWS
1951 /* Transfer any clipboards we own to the clipboard manager. */
1952 x_clipboard_manager_save_all ();
1953 #endif
1954
1955 shut_down_emacs (0, (STRINGP (arg) && !feof (stdin)) ? arg : Qnil);
1956
1957 #ifdef HAVE_NS
1958 ns_release_autorelease_pool (ns_pool);
1959 #endif
1960
1961 /* If we have an auto-save list file,
1962 kill it because we are exiting Emacs deliberately (not crashing).
1963 Do it after shut_down_emacs, which does an auto-save. */
1964 if (STRINGP (Vauto_save_list_file_name))
1965 {
1966 Lisp_Object listfile;
1967 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
1968 unlink (SSDATA (listfile));
1969 }
1970
1971 if (INTEGERP (arg))
1972 exit_code = (XINT (arg) < 0
1973 ? XINT (arg) | INT_MIN
1974 : XINT (arg) & INT_MAX);
1975 else
1976 exit_code = EXIT_SUCCESS;
1977 exit (exit_code);
1978 }
1979
1980
1981 /* Perform an orderly shutdown of Emacs. Autosave any modified
1982 buffers, kill any child processes, clean up the terminal modes (if
1983 we're in the foreground), and other stuff like that. Don't perform
1984 any redisplay; this may be called when Emacs is shutting down in
1985 the background, or after its X connection has died.
1986
1987 If SIG is a signal number, print a message for it.
1988
1989 This is called by fatal signal handlers, X protocol error handlers,
1990 and Fkill_emacs. */
1991
1992 void
1993 shut_down_emacs (int sig, Lisp_Object stuff)
1994 {
1995 /* Prevent running of hooks from now on. */
1996 Vrun_hooks = Qnil;
1997
1998 /* Don't update display from now on. */
1999 Vinhibit_redisplay = Qt;
2000
2001 /* If we are controlling the terminal, reset terminal modes. */
2002 #ifndef DOS_NT
2003 {
2004 pid_t pgrp = getpgrp ();
2005 pid_t tpgrp = tcgetpgrp (0);
2006 if ((tpgrp != -1) && tpgrp == pgrp)
2007 {
2008 reset_all_sys_modes ();
2009 if (sig && sig != SIGTERM)
2010 {
2011 static char const format[] = "Fatal error %d: ";
2012 char buf[sizeof format - 2 + INT_STRLEN_BOUND (int)];
2013 int buflen = sprintf (buf, format, sig);
2014 char const *sig_desc = safe_strsignal (sig);
2015 emacs_write (STDERR_FILENO, buf, buflen);
2016 emacs_write (STDERR_FILENO, sig_desc, strlen (sig_desc));
2017 }
2018 }
2019 }
2020 #else
2021 fflush (stdout);
2022 reset_all_sys_modes ();
2023 #endif
2024
2025 stuff_buffered_input (stuff);
2026
2027 inhibit_sentinels = 1;
2028 kill_buffer_processes (Qnil);
2029 Fdo_auto_save (Qt, Qnil);
2030
2031 unlock_all_files ();
2032
2033 /* There is a tendency for a SIGIO signal to arrive within exit,
2034 and cause a SIGHUP because the input descriptor is already closed. */
2035 unrequest_sigio ();
2036
2037 /* Do this only if terminating normally, we want glyph matrices
2038 etc. in a core dump. */
2039 if (sig == 0 || sig == SIGTERM)
2040 {
2041 check_glyph_memory ();
2042 check_message_stack ();
2043 }
2044
2045 #ifdef MSDOS
2046 dos_cleanup ();
2047 #endif
2048
2049 #ifdef HAVE_NS
2050 ns_term_shutdown (sig);
2051 #endif
2052
2053 #ifdef HAVE_LIBXML2
2054 xml_cleanup_parser ();
2055 #endif
2056
2057 #ifdef WINDOWSNT
2058 term_ntproc (0);
2059 #endif
2060 }
2061
2062
2063 \f
2064 #ifndef CANNOT_DUMP
2065
2066 #include "unexec.h"
2067
2068 DEFUN ("dump-emacs", Fdump_emacs, Sdump_emacs, 2, 2, 0,
2069 doc: /* Dump current state of Emacs into executable file FILENAME.
2070 Take symbols from SYMFILE (presumably the file you executed to run Emacs).
2071 This is used in the file `loadup.el' when building Emacs.
2072
2073 You must run Emacs in batch mode in order to dump it. */)
2074 (Lisp_Object filename, Lisp_Object symfile)
2075 {
2076 Lisp_Object tem;
2077 Lisp_Object symbol;
2078 ptrdiff_t count = SPECPDL_INDEX ();
2079
2080 check_pure_size ();
2081
2082 if (! noninteractive)
2083 error ("Dumping Emacs works only in batch mode");
2084
2085 if (!might_dump)
2086 error ("Emacs can be dumped only once");
2087
2088 #ifdef GNU_LINUX
2089
2090 /* Warn if the gap between BSS end and heap start is larger than this. */
2091 # define MAX_HEAP_BSS_DIFF (1024*1024)
2092
2093 if (heap_bss_diff > MAX_HEAP_BSS_DIFF)
2094 {
2095 fprintf (stderr, "**************************************************\n");
2096 fprintf (stderr, "Warning: Your system has a gap between BSS and the\n");
2097 fprintf (stderr, "heap (%"pMu" bytes). This usually means that exec-shield\n",
2098 heap_bss_diff);
2099 fprintf (stderr, "or something similar is in effect. The dump may\n");
2100 fprintf (stderr, "fail because of this. See the section about\n");
2101 fprintf (stderr, "exec-shield in etc/PROBLEMS for more information.\n");
2102 fprintf (stderr, "**************************************************\n");
2103 }
2104 #endif /* GNU_LINUX */
2105
2106 /* Bind `command-line-processed' to nil before dumping,
2107 so that the dumped Emacs will process its command line
2108 and set up to work with X windows if appropriate. */
2109 symbol = intern ("command-line-processed");
2110 specbind (symbol, Qnil);
2111
2112 CHECK_STRING (filename);
2113 filename = Fexpand_file_name (filename, Qnil);
2114 filename = ENCODE_FILE (filename);
2115 if (!NILP (symfile))
2116 {
2117 CHECK_STRING (symfile);
2118 if (SCHARS (symfile))
2119 {
2120 symfile = Fexpand_file_name (symfile, Qnil);
2121 symfile = ENCODE_FILE (symfile);
2122 }
2123 }
2124
2125 tem = Vpurify_flag;
2126 Vpurify_flag = Qnil;
2127
2128 #ifdef HYBRID_MALLOC
2129 {
2130 static char const fmt[] = "%d of %d static heap bytes used";
2131 char buf[sizeof fmt + 2 * (INT_STRLEN_BOUND (int) - 2)];
2132 int max_usage = max_bss_sbrk_ptr - bss_sbrk_buffer;
2133 sprintf (buf, fmt, max_usage, STATIC_HEAP_SIZE);
2134 /* Don't log messages, because at this point buffers cannot be created. */
2135 message1_nolog (buf);
2136 }
2137 #endif
2138
2139 fflush (stdout);
2140 /* Tell malloc where start of impure now is. */
2141 /* Also arrange for warnings when nearly out of space. */
2142 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
2143 #ifndef WINDOWSNT
2144 /* On Windows, this was done before dumping, and that once suffices.
2145 Meanwhile, my_edata is not valid on Windows. */
2146 memory_warnings (my_edata, malloc_warning);
2147 #endif /* not WINDOWSNT */
2148 #endif /* not SYSTEM_MALLOC and not HYBRID_MALLOC */
2149
2150 alloc_unexec_pre ();
2151
2152 unexec (SSDATA (filename), !NILP (symfile) ? SSDATA (symfile) : 0);
2153
2154 alloc_unexec_post ();
2155
2156 #ifdef WINDOWSNT
2157 Vlibrary_cache = Qnil;
2158 #endif
2159 #ifdef HAVE_WINDOW_SYSTEM
2160 reset_image_types ();
2161 #endif
2162
2163 Vpurify_flag = tem;
2164
2165 return unbind_to (count, Qnil);
2166 }
2167
2168 #endif /* not CANNOT_DUMP */
2169 \f
2170 #if HAVE_SETLOCALE
2171 /* Recover from setlocale (LC_ALL, ""). */
2172 void
2173 fixup_locale (void)
2174 {
2175 /* The Emacs Lisp reader needs LC_NUMERIC to be "C",
2176 so that numbers are read and printed properly for Emacs Lisp. */
2177 setlocale (LC_NUMERIC, "C");
2178 }
2179
2180 /* Set system locale CATEGORY, with previous locale *PLOCALE, to
2181 DESIRED_LOCALE. */
2182 static void
2183 synchronize_locale (int category, Lisp_Object *plocale, Lisp_Object desired_locale)
2184 {
2185 if (! EQ (*plocale, desired_locale))
2186 {
2187 *plocale = desired_locale;
2188 #ifdef WINDOWSNT
2189 /* Changing categories like LC_TIME usually requires specifying
2190 an encoding suitable for the new locale, but MS-Windows's
2191 'setlocale' will only switch the encoding when LC_ALL is
2192 specified. So we ignore CATEGORY, use LC_ALL instead, and
2193 then restore LC_NUMERIC to "C", so reading and printing
2194 numbers is unaffected. */
2195 setlocale (LC_ALL, (STRINGP (desired_locale)
2196 ? SSDATA (desired_locale)
2197 : ""));
2198 fixup_locale ();
2199 #else /* !WINDOWSNT */
2200 setlocale (category, (STRINGP (desired_locale)
2201 ? SSDATA (desired_locale)
2202 : ""));
2203 #endif /* !WINDOWSNT */
2204 }
2205 }
2206
2207 /* Set system time locale to match Vsystem_time_locale, if possible. */
2208 void
2209 synchronize_system_time_locale (void)
2210 {
2211 synchronize_locale (LC_TIME, &Vprevious_system_time_locale,
2212 Vsystem_time_locale);
2213 }
2214
2215 /* Set system messages locale to match Vsystem_messages_locale, if
2216 possible. */
2217 void
2218 synchronize_system_messages_locale (void)
2219 {
2220 #ifdef LC_MESSAGES
2221 synchronize_locale (LC_MESSAGES, &Vprevious_system_messages_locale,
2222 Vsystem_messages_locale);
2223 #endif
2224 }
2225 #endif /* HAVE_SETLOCALE */
2226 \f
2227
2228 Lisp_Object
2229 decode_env_path (const char *evarname, const char *defalt, bool empty)
2230 {
2231 const char *path, *p;
2232 Lisp_Object lpath, element, tem;
2233 /* Default is to use "." for empty path elements.
2234 But if argument EMPTY is true, use nil instead. */
2235 Lisp_Object empty_element = empty ? Qnil : build_string (".");
2236 #ifdef WINDOWSNT
2237 bool defaulted = 0;
2238 static const char *emacs_dir_env = "%emacs_dir%/";
2239 const size_t emacs_dir_len = strlen (emacs_dir_env);
2240 const char *edir = egetenv ("emacs_dir");
2241 char emacs_dir[MAX_UTF8_PATH];
2242
2243 /* egetenv looks in process-environment, which holds the variables
2244 in their original system-locale encoding. We need emacs_dir to
2245 be in UTF-8. */
2246 if (edir)
2247 filename_from_ansi (edir, emacs_dir);
2248 #endif
2249
2250 /* It's okay to use getenv here, because this function is only used
2251 to initialize variables when Emacs starts up, and isn't called
2252 after that. */
2253 if (evarname != 0)
2254 path = getenv (evarname);
2255 else
2256 path = 0;
2257 if (!path)
2258 {
2259 path = defalt;
2260 #ifdef WINDOWSNT
2261 defaulted = 1;
2262 #endif
2263 }
2264 #ifdef DOS_NT
2265 /* Ensure values from the environment use the proper directory separator. */
2266 if (path)
2267 {
2268 char *path_copy;
2269
2270 #ifdef WINDOWSNT
2271 char *path_utf8, *q, *d;
2272 int cnv_result;
2273
2274 /* Convert each element of PATH to UTF-8. */
2275 p = path_copy = alloca (strlen (path) + 1);
2276 strcpy (path_copy, path);
2277 d = path_utf8 = alloca (4 * strlen (path) + 1);
2278 *d = '\0';
2279 do {
2280 q = _mbschr (p, SEPCHAR);
2281 if (q)
2282 *q = '\0';
2283 cnv_result = filename_from_ansi (p, d);
2284 if (q)
2285 {
2286 *q++ = SEPCHAR;
2287 p = q;
2288 /* If conversion of this PATH elements fails, make sure
2289 destination pointer will stay put, thus effectively
2290 ignoring the offending element. */
2291 if (cnv_result == 0)
2292 {
2293 d += strlen (d);
2294 *d++ = SEPCHAR;
2295 }
2296 }
2297 else if (cnv_result != 0 && d > path_utf8)
2298 d[-1] = '\0'; /* remove last semi-colon and null-terminate PATH */
2299 } while (q);
2300 path_copy = path_utf8;
2301 #else /* MSDOS */
2302 path_copy = alloca (strlen (path) + 1);
2303 strcpy (path_copy, path);
2304 #endif
2305 dostounix_filename (path_copy);
2306 path = path_copy;
2307 }
2308 #endif
2309 lpath = Qnil;
2310 while (1)
2311 {
2312 p = strchr (path, SEPCHAR);
2313 if (!p)
2314 p = path + strlen (path);
2315 element = ((p - path) ? make_unibyte_string (path, p - path)
2316 : empty_element);
2317 if (! NILP (element))
2318 {
2319 #ifdef WINDOWSNT
2320 /* Relative file names in the default path are interpreted as
2321 being relative to $emacs_dir. */
2322 if (edir && defaulted
2323 && strncmp (path, emacs_dir_env, emacs_dir_len) == 0)
2324 element = Fexpand_file_name (Fsubstring
2325 (element,
2326 make_number (emacs_dir_len),
2327 Qnil),
2328 build_unibyte_string (emacs_dir));
2329 #endif
2330
2331 /* Add /: to the front of the name
2332 if it would otherwise be treated as magic. */
2333 tem = Ffind_file_name_handler (element, Qt);
2334
2335 /* However, if the handler says "I'm safe",
2336 don't bother adding /:. */
2337 if (SYMBOLP (tem))
2338 {
2339 Lisp_Object prop;
2340 prop = Fget (tem, intern ("safe-magic"));
2341 if (! NILP (prop))
2342 tem = Qnil;
2343 }
2344
2345 if (! NILP (tem))
2346 {
2347 AUTO_STRING (slash_colon, "/:");
2348 element = concat2 (slash_colon, element);
2349 }
2350 } /* !NILP (element) */
2351
2352 lpath = Fcons (element, lpath);
2353 if (*p)
2354 path = p + 1;
2355 else
2356 break;
2357 }
2358 return Fnreverse (lpath);
2359 }
2360
2361 DEFUN ("daemonp", Fdaemonp, Sdaemonp, 0, 0, 0,
2362 doc: /* Return non-nil if the current emacs process is a daemon.
2363 If the daemon was given a name argument, return that name. */)
2364 (void)
2365 {
2366 if (IS_DAEMON)
2367 if (daemon_name)
2368 return build_string (daemon_name);
2369 else
2370 return Qt;
2371 else
2372 return Qnil;
2373 }
2374
2375 DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
2376 doc: /* Mark the Emacs daemon as being initialized.
2377 This finishes the daemonization process by doing the other half of detaching
2378 from the parent process and its tty file descriptors. */)
2379 (void)
2380 {
2381 bool err = 0;
2382
2383 if (!IS_DAEMON)
2384 error ("This function can only be called if emacs is run as a daemon");
2385
2386 if (!DAEMON_RUNNING)
2387 error ("The daemon has already been initialized");
2388
2389 if (NILP (Vafter_init_time))
2390 error ("This function can only be called after loading the init files");
2391 #ifndef WINDOWSNT
2392 int nfd;
2393
2394 /* Get rid of stdin, stdout and stderr. */
2395 nfd = emacs_open ("/dev/null", O_RDWR, 0);
2396 err |= nfd < 0;
2397 err |= dup2 (nfd, STDIN_FILENO) < 0;
2398 err |= dup2 (nfd, STDOUT_FILENO) < 0;
2399 err |= dup2 (nfd, STDERR_FILENO) < 0;
2400 err |= emacs_close (nfd) != 0;
2401
2402 /* Closing the pipe will notify the parent that it can exit.
2403 FIXME: In case some other process inherited the pipe, closing it here
2404 won't notify the parent because it's still open elsewhere, so we
2405 additionally send a byte, just to make sure the parent really exits.
2406 Instead, we should probably close the pipe in start-process and
2407 call-process to make sure the pipe is never inherited by
2408 subprocesses. */
2409 err |= write (daemon_pipe[1], "\n", 1) < 0;
2410 err |= emacs_close (daemon_pipe[1]) != 0;
2411 /* Set it to an invalid value so we know we've already run this function. */
2412 daemon_pipe[1] = -1;
2413 #else /* WINDOWSNT */
2414 /* Signal the waiting emacsclient process. */
2415 err |= SetEvent (w32_daemon_event) == 0;
2416 err |= CloseHandle (w32_daemon_event) == 0;
2417 /* Set it to an invalid value so we know we've already run this function. */
2418 w32_daemon_event = INVALID_HANDLE_VALUE;
2419 #endif
2420
2421 if (err)
2422 error ("I/O error during daemon initialization");
2423 return Qt;
2424 }
2425
2426 void
2427 syms_of_emacs (void)
2428 {
2429 DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
2430 DEFSYM (Qrisky_local_variable, "risky-local-variable");
2431 DEFSYM (Qkill_emacs, "kill-emacs");
2432 DEFSYM (Qkill_emacs_hook, "kill-emacs-hook");
2433
2434 #ifndef CANNOT_DUMP
2435 defsubr (&Sdump_emacs);
2436 #endif
2437
2438 defsubr (&Skill_emacs);
2439
2440 defsubr (&Sinvocation_name);
2441 defsubr (&Sinvocation_directory);
2442 defsubr (&Sdaemonp);
2443 defsubr (&Sdaemon_initialized);
2444
2445 DEFVAR_LISP ("command-line-args", Vcommand_line_args,
2446 doc: /* Args passed by shell to Emacs, as a list of strings.
2447 Many arguments are deleted from the list as they are processed. */);
2448
2449 DEFVAR_LISP ("system-type", Vsystem_type,
2450 doc: /* The value is a symbol indicating the type of operating system you are using.
2451 Special values:
2452 `gnu' compiled for a GNU Hurd system.
2453 `gnu/linux' compiled for a GNU/Linux system.
2454 `gnu/kfreebsd' compiled for a GNU system with a FreeBSD kernel.
2455 `darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
2456 `ms-dos' compiled as an MS-DOS application.
2457 `windows-nt' compiled as a native W32 application.
2458 `cygwin' compiled using the Cygwin library.
2459 Anything else (in Emacs 26, the possibilities are: aix, berkeley-unix,
2460 hpux, usg-unix-v) indicates some sort of Unix system. */);
2461 Vsystem_type = intern_c_string (SYSTEM_TYPE);
2462 /* See configure.ac for the possible SYSTEM_TYPEs. */
2463
2464 DEFVAR_LISP ("system-configuration", Vsystem_configuration,
2465 doc: /* Value is string indicating configuration Emacs was built for. */);
2466 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2467
2468 DEFVAR_LISP ("system-configuration-options", Vsystem_configuration_options,
2469 doc: /* String containing the configuration options Emacs was built with. */);
2470 Vsystem_configuration_options = build_string (EMACS_CONFIG_OPTIONS);
2471
2472 DEFVAR_LISP ("system-configuration-features", Vsystem_configuration_features,
2473 doc: /* String listing some of the main features this Emacs was compiled with.
2474 An element of the form \"FOO\" generally means that HAVE_FOO was
2475 defined during the build.
2476
2477 This is mainly intended for diagnostic purposes in bug reports.
2478 Don't rely on it for testing whether a feature you want to use is available. */);
2479 Vsystem_configuration_features = build_string (EMACS_CONFIG_FEATURES);
2480
2481 DEFVAR_BOOL ("noninteractive", noninteractive1,
2482 doc: /* Non-nil means Emacs is running without interactive terminal. */);
2483
2484 DEFVAR_LISP ("kill-emacs-hook", Vkill_emacs_hook,
2485 doc: /* Hook run when `kill-emacs' is called.
2486 Since `kill-emacs' may be invoked when the terminal is disconnected (or
2487 in other similar situations), functions placed on this hook should not
2488 expect to be able to interact with the user. To ask for confirmation,
2489 see `kill-emacs-query-functions' instead.
2490
2491 Before Emacs 24.1, the hook was not run in batch mode, i.e., if
2492 `noninteractive' was non-nil. */);
2493 Vkill_emacs_hook = Qnil;
2494
2495 DEFVAR_LISP ("path-separator", Vpath_separator,
2496 doc: /* String containing the character that separates directories in
2497 search paths, such as PATH and other similar environment variables. */);
2498 {
2499 char c = SEPCHAR;
2500 Vpath_separator = make_string (&c, 1);
2501 }
2502
2503 DEFVAR_LISP ("invocation-name", Vinvocation_name,
2504 doc: /* The program name that was used to run Emacs.
2505 Any directory names are omitted. */);
2506
2507 DEFVAR_LISP ("invocation-directory", Vinvocation_directory,
2508 doc: /* The directory in which the Emacs executable was found, to run it.
2509 The value is nil if that directory's name is not known. */);
2510
2511 DEFVAR_LISP ("installation-directory", Vinstallation_directory,
2512 doc: /* A directory within which to look for the `lib-src' and `etc' directories.
2513 In an installed Emacs, this is normally nil. It is non-nil if
2514 both `lib-src' (on MS-DOS, `info') and `etc' directories are found
2515 within the variable `invocation-directory' or its parent. For example,
2516 this is the case when running an uninstalled Emacs executable from its
2517 build directory. */);
2518 Vinstallation_directory = Qnil;
2519
2520 DEFVAR_LISP ("system-messages-locale", Vsystem_messages_locale,
2521 doc: /* System locale for messages. */);
2522 Vsystem_messages_locale = Qnil;
2523
2524 DEFVAR_LISP ("previous-system-messages-locale",
2525 Vprevious_system_messages_locale,
2526 doc: /* Most recently used system locale for messages. */);
2527 Vprevious_system_messages_locale = Qnil;
2528
2529 DEFVAR_LISP ("system-time-locale", Vsystem_time_locale,
2530 doc: /* System locale for time. */);
2531 Vsystem_time_locale = Qnil;
2532
2533 DEFVAR_LISP ("previous-system-time-locale", Vprevious_system_time_locale,
2534 doc: /* Most recently used system locale for time. */);
2535 Vprevious_system_time_locale = Qnil;
2536
2537 DEFVAR_LISP ("before-init-time", Vbefore_init_time,
2538 doc: /* Value of `current-time' before Emacs begins initialization. */);
2539 Vbefore_init_time = Qnil;
2540
2541 DEFVAR_LISP ("after-init-time", Vafter_init_time,
2542 doc: /* Value of `current-time' after loading the init files.
2543 This is nil during initialization. */);
2544 Vafter_init_time = Qnil;
2545
2546 DEFVAR_BOOL ("inhibit-x-resources", inhibit_x_resources,
2547 doc: /* If non-nil, X resources, Windows Registry settings, and NS defaults are not used. */);
2548 inhibit_x_resources = 0;
2549
2550 DEFVAR_LISP ("emacs-copyright", Vemacs_copyright,
2551 doc: /* Short copyright string for this version of Emacs. */);
2552 Vemacs_copyright = build_string (emacs_copyright);
2553
2554 DEFVAR_LISP ("emacs-version", Vemacs_version,
2555 doc: /* Version numbers of this version of Emacs. */);
2556 Vemacs_version = build_string (emacs_version);
2557
2558 DEFVAR_LISP ("report-emacs-bug-address", Vreport_emacs_bug_address,
2559 doc: /* Address of mailing list for GNU Emacs bugs. */);
2560 Vreport_emacs_bug_address = build_string (emacs_bugreport);
2561
2562 DEFVAR_LISP ("dynamic-library-alist", Vdynamic_library_alist,
2563 doc: /* Alist of dynamic libraries vs external files implementing them.
2564 Each element is a list (LIBRARY FILE...), where the car is a symbol
2565 representing a supported external library, and the rest are strings giving
2566 alternate filenames for that library.
2567
2568 Emacs tries to load the library from the files in the order they appear on
2569 the list; if none is loaded, the running session of Emacs won't have access
2570 to that library.
2571
2572 Note that image types `pbm' and `xbm' do not need entries in this variable
2573 because they do not depend on external libraries and are always available.
2574
2575 Also note that this is not a generic facility for accessing external
2576 libraries; only those already known by Emacs will be loaded. */);
2577 Vdynamic_library_alist = Qnil;
2578 Fput (intern_c_string ("dynamic-library-alist"), Qrisky_local_variable, Qt);
2579
2580 #ifdef WINDOWSNT
2581 Vlibrary_cache = Qnil;
2582 staticpro (&Vlibrary_cache);
2583 #endif
2584 }