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