* bytecode.c (exec_byte_code): Use some more volatile variables
[emacs.git] / src / emacs.c
blob79f759cd5b59527858a6735d48505d8aa6b93027
1 /* Fully extensible Emacs, running on Unix, intended for GNU.
3 Copyright (C) 1985-1987, 1993-1995, 1997-1999, 2001-2013
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #define INLINE EXTERN_INLINE
22 #include <config.h>
24 #include <errno.h>
25 #include <stdio.h>
27 #include <sys/types.h>
28 #include <sys/file.h>
29 #include <unistd.h>
31 #include <close-stream.h>
33 #include "lisp.h"
35 #ifdef WINDOWSNT
36 #include <fcntl.h>
37 #include <sys/socket.h>
38 #include "w32.h"
39 #include "w32heap.h"
40 #endif
42 #if defined WINDOWSNT || defined HAVE_NTGUI
43 #include "w32select.h"
44 #include "w32font.h"
45 #include "w32common.h"
46 #endif
48 #if defined CYGWIN
49 #include "cygw32.h"
50 #endif
52 #ifdef HAVE_WINDOW_SYSTEM
53 #include TERM_HEADER
54 #endif /* HAVE_WINDOW_SYSTEM */
56 #ifdef NS_IMPL_GNUSTEP
57 /* At least under Debian, GSConfig is in a subdirectory. --Stef */
58 #include <GNUstepBase/GSConfig.h>
59 #endif
61 #include "commands.h"
62 #include "intervals.h"
63 #include "character.h"
64 #include "buffer.h"
65 #include "window.h"
67 #include "systty.h"
68 #include "atimer.h"
69 #include "blockinput.h"
70 #include "syssignal.h"
71 #include "process.h"
72 #include "frame.h"
73 #include "termhooks.h"
74 #include "keyboard.h"
75 #include "keymap.h"
76 #include "category.h"
77 #include "charset.h"
78 #include "composite.h"
79 #include "dispextern.h"
80 #include "syntax.h"
81 #include "systime.h"
83 #ifdef HAVE_GNUTLS
84 #include "gnutls.h"
85 #endif
87 #if (defined PROFILING \
88 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__))
89 # include <sys/gmon.h>
90 extern void moncontrol (int mode);
91 #endif
93 #ifdef HAVE_SETLOCALE
94 #include <locale.h>
95 #endif
97 #ifdef HAVE_SETRLIMIT
98 #include <sys/time.h>
99 #include <sys/resource.h>
100 #endif
102 #ifdef HAVE_PERSONALITY_LINUX32
103 #include <sys/personality.h>
104 #endif
106 static const char emacs_version[] = VERSION;
107 static const char emacs_copyright[] = COPYRIGHT;
109 /* Empty lisp strings. To avoid having to build any others. */
110 Lisp_Object empty_unibyte_string, empty_multibyte_string;
112 #ifdef WINDOWSNT
113 /* Cache for externally loaded libraries. */
114 Lisp_Object Vlibrary_cache;
115 #endif
117 /* Set after Emacs has started up the first time.
118 Prevents reinitialization of the Lisp world and keymaps
119 on subsequent starts. */
120 bool initialized;
122 #ifdef DARWIN_OS
123 extern void unexec_init_emacs_zone (void);
124 #endif
126 #ifdef DOUG_LEA_MALLOC
127 /* Preserves a pointer to the memory allocated that copies that
128 static data inside glibc's malloc. */
129 static void *malloc_state_ptr;
130 /* From glibc, a routine that returns a copy of the malloc internal state. */
131 extern void *malloc_get_state (void);
132 /* From glibc, a routine that overwrites the malloc internal state. */
133 extern int malloc_set_state (void*);
134 /* True if the MALLOC_CHECK_ environment variable was set while
135 dumping. Used to work around a bug in glibc's malloc. */
136 static bool malloc_using_checking;
137 #elif defined HAVE_PTHREAD && !defined SYSTEM_MALLOC
138 extern void malloc_enable_thread (void);
139 #endif
141 Lisp_Object Qfile_name_handler_alist;
143 Lisp_Object Qrisky_local_variable;
145 Lisp_Object Qkill_emacs;
146 static Lisp_Object Qkill_emacs_hook;
148 /* If true, Emacs should not attempt to use a window-specific code,
149 but instead should use the virtual terminal under which it was started. */
150 bool inhibit_window_system;
152 /* If true, a filter or a sentinel is running. Tested to save the match
153 data on the first attempt to change it inside asynchronous code. */
154 bool running_asynch_code;
156 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NS)
157 /* If true, -d was specified, meaning we're using some window system. */
158 bool display_arg;
159 #endif
161 /* An address near the bottom of the stack.
162 Tells GC how to save a copy of the stack. */
163 char *stack_bottom;
165 #if defined (DOUG_LEA_MALLOC) || defined (GNU_LINUX)
166 /* The address where the heap starts (from the first sbrk (0) call). */
167 static void *my_heap_start;
168 #endif
170 #ifdef GNU_LINUX
171 /* The gap between BSS end and heap start as far as we can tell. */
172 static uprintmax_t heap_bss_diff;
173 #endif
175 /* To run as a daemon under Cocoa or Windows, we must do a fork+exec,
176 not a simple fork.
178 On Cocoa, CoreFoundation lib fails in forked process:
179 http://developer.apple.com/ReleaseNotes/
180 CoreFoundation/CoreFoundation.html)
182 On Windows, a Cygwin fork child cannot access the USER subsystem.
184 We mark being in the exec'd process by a daemon name argument of
185 form "--daemon=\nFD0,FD1\nNAME" where FD are the pipe file descriptors,
186 NAME is the original daemon name, if any. */
187 #if defined NS_IMPL_COCOA || (defined HAVE_NTGUI && defined CYGWIN)
188 # define DAEMON_MUST_EXEC
189 #endif
191 /* True means running Emacs without interactive terminal. */
192 bool noninteractive;
194 /* True means remove site-lisp directories from load-path. */
195 bool no_site_lisp;
197 /* Name for the server started by the daemon.*/
198 static char *daemon_name;
200 /* Pipe used to send exit notification to the daemon parent at
201 startup. */
202 int daemon_pipe[2];
204 /* Save argv and argc. */
205 char **initial_argv;
206 int initial_argc;
208 static void sort_args (int argc, char **argv);
209 static void syms_of_emacs (void);
211 /* C89 needs each string be at most 509 characters, so the usage
212 strings below are split to not overflow this limit. */
213 static char const *const usage_message[] =
214 { "\
216 Run Emacs, the extensible, customizable, self-documenting real-time\n\
217 display editor. The recommended way to start Emacs for normal editing\n\
218 is with no options at all.\n\
220 Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n\
221 read the main documentation for these command-line arguments.\n\
223 Initialization options:\n\
227 --batch do not do interactive display; implies -q\n\
228 --chdir DIR change to directory DIR\n\
229 --daemon start a server in the background\n\
230 --debug-init enable Emacs Lisp debugger for init file\n\
231 --display, -d DISPLAY use X server DISPLAY\n\
234 --no-desktop do not load a saved desktop\n\
235 --no-init-file, -q load neither ~/.emacs nor default.el\n\
236 --no-shared-memory, -nl do not use shared memory\n\
237 --no-site-file do not load site-start.el\n\
238 --no-site-lisp, -nsl do not add site-lisp directories to load-path\n\
239 --no-splash do not display a splash screen on startup\n\
240 --no-window-system, -nw do not communicate with X, ignoring $DISPLAY\n\
243 --quick, -Q equivalent to:\n\
244 -q --no-site-file --no-site-lisp --no-splash\n\
245 --script FILE run FILE as an Emacs Lisp script\n\
246 --terminal, -t DEVICE use DEVICE for terminal I/O\n\
247 --user, -u USER load ~USER/.emacs instead of your own\n\
251 Action options:\n\
253 FILE visit FILE using find-file\n\
254 +LINE go to line LINE in next FILE\n\
255 +LINE:COLUMN go to line LINE, column COLUMN, in next FILE\n\
256 --directory, -L DIR add DIR to variable load-path\n\
257 --eval EXPR evaluate Emacs Lisp expression EXPR\n\
258 --execute EXPR evaluate Emacs Lisp expression EXPR\n\
261 --file FILE visit FILE using find-file\n\
262 --find-file FILE visit FILE using find-file\n\
263 --funcall, -f FUNC call Emacs Lisp function FUNC with no arguments\n\
264 --insert FILE insert contents of FILE into current buffer\n\
265 --kill exit without asking for confirmation\n\
266 --load, -l FILE load Emacs Lisp FILE using the load function\n\
267 --visit FILE visit FILE using find-file\n\
271 Display options:\n\
273 --background-color, -bg COLOR window background color\n\
274 --basic-display, -D disable many display features;\n\
275 used for debugging Emacs\n\
276 --border-color, -bd COLOR main border color\n\
277 --border-width, -bw WIDTH width of main border\n\
280 --color, --color=MODE override color mode for character terminals;\n\
281 MODE defaults to `auto', and\n\
282 can also be `never', `always',\n\
283 or a mode name like `ansi8'\n\
284 --cursor-color, -cr COLOR color of the Emacs cursor indicating point\n\
285 --font, -fn FONT default font; must be fixed-width\n\
286 --foreground-color, -fg COLOR window foreground color\n\
289 --fullheight, -fh make the first frame high as the screen\n\
290 --fullscreen, -fs make the first frame fullscreen\n\
291 --fullwidth, -fw make the first frame wide as the screen\n\
292 --maximized, -mm make the first frame maximized\n\
293 --geometry, -g GEOMETRY window geometry\n\
296 --no-bitmap-icon, -nbi do not use picture of gnu for Emacs icon\n\
297 --iconic start Emacs in iconified state\n\
298 --internal-border, -ib WIDTH width between text and main border\n\
299 --line-spacing, -lsp PIXELS additional space to put between lines\n\
300 --mouse-color, -ms COLOR mouse cursor color in Emacs window\n\
301 --name NAME title for initial Emacs frame\n\
304 --no-blinking-cursor, -nbc disable blinking cursor\n\
305 --reverse-video, -r, -rv switch foreground and background\n\
306 --title, -T TITLE title for initial Emacs frame\n\
307 --vertical-scroll-bars, -vb enable vertical scroll bars\n\
308 --xrm XRESOURCES set additional X resources\n\
309 --parent-id XID set parent window\n\
310 --help display this help and exit\n\
311 --version output version information and exit\n\
315 You can generally also specify long option names with a single -; for\n\
316 example, -batch as well as --batch. You can use any unambiguous\n\
317 abbreviation for a --option.\n\
319 Various environment variables and window system resources also affect\n\
320 the operation of Emacs. See the main documentation.\n\
322 Report bugs to bug-gnu-emacs@gnu.org. First, please see the Bugs\n\
323 section of the Emacs manual or the file BUGS.\n"
327 /* True if handling a fatal error already. */
328 bool fatal_error_in_progress;
330 #ifdef HAVE_NS
331 /* NS autrelease pool, for memory management. */
332 static void *ns_pool;
333 #endif
335 #if !HAVE_SETLOCALE
336 static char *
337 setlocale (int cat, char const *locale)
339 return 0;
341 #endif
344 /* Report a fatal error due to signal SIG, output a backtrace of at
345 most BACKTRACE_LIMIT lines, and exit. */
346 _Noreturn void
347 terminate_due_to_signal (int sig, int backtrace_limit)
349 signal (sig, SIG_DFL);
350 totally_unblock_input ();
352 /* If fatal error occurs in code below, avoid infinite recursion. */
353 if (! fatal_error_in_progress)
355 fatal_error_in_progress = 1;
357 if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT)
358 Fkill_emacs (make_number (sig));
360 shut_down_emacs (sig, Qnil);
361 emacs_backtrace (backtrace_limit);
364 /* Signal the same code; this time it will really be fatal.
365 Since we're in a signal handler, the signal is blocked, so we
366 have to unblock it if we want to really receive it. */
367 #ifndef MSDOS
369 sigset_t unblocked;
370 sigemptyset (&unblocked);
371 sigaddset (&unblocked, sig);
372 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
374 #endif
376 emacs_raise (sig);
378 /* This shouldn't be executed, but it prevents a warning. */
379 exit (1);
382 /* Code for dealing with Lisp access to the Unix command line. */
384 static void
385 init_cmdargs (int argc, char **argv, int skip_args)
387 register int i;
388 Lisp_Object name, dir, handler;
389 ptrdiff_t count = SPECPDL_INDEX ();
390 Lisp_Object raw_name;
392 initial_argv = argv;
393 initial_argc = argc;
395 raw_name = build_string (argv[0]);
397 /* Add /: to the front of the name
398 if it would otherwise be treated as magic. */
399 handler = Ffind_file_name_handler (raw_name, Qt);
400 if (! NILP (handler))
401 raw_name = concat2 (build_string ("/:"), raw_name);
403 Vinvocation_name = Ffile_name_nondirectory (raw_name);
404 Vinvocation_directory = Ffile_name_directory (raw_name);
406 /* If we got no directory in argv[0], search PATH to find where
407 Emacs actually came from. */
408 if (NILP (Vinvocation_directory))
410 Lisp_Object found;
411 int yes = openp (Vexec_path, Vinvocation_name,
412 Vexec_suffixes, &found, make_number (X_OK));
413 if (yes == 1)
415 /* Add /: to the front of the name
416 if it would otherwise be treated as magic. */
417 handler = Ffind_file_name_handler (found, Qt);
418 if (! NILP (handler))
419 found = concat2 (build_string ("/:"), found);
420 Vinvocation_directory = Ffile_name_directory (found);
424 if (!NILP (Vinvocation_directory)
425 && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
426 /* Emacs was started with relative path, like ./emacs.
427 Make it absolute. */
428 Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, Qnil);
430 Vinstallation_directory = Qnil;
432 if (!NILP (Vinvocation_directory))
434 dir = Vinvocation_directory;
435 #ifdef WINDOWSNT
436 /* If we are running from the build directory, set DIR to the
437 src subdirectory of the Emacs tree, like on Posix
438 platforms. */
439 if (SBYTES (dir) > sizeof ("/i386/") - 1
440 && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
441 "/i386/"))
442 dir = Fexpand_file_name (build_string ("../.."), dir);
443 #else /* !WINDOWSNT */
444 #endif
445 name = Fexpand_file_name (Vinvocation_name, dir);
446 while (1)
448 Lisp_Object tem, lib_src_exists;
449 Lisp_Object etc_exists, info_exists;
451 /* See if dir contains subdirs for use by Emacs.
452 Check for the ones that would exist in a build directory,
453 not including lisp and info. */
454 tem = Fexpand_file_name (build_string ("lib-src"), dir);
455 lib_src_exists = Ffile_exists_p (tem);
457 #ifdef MSDOS
458 /* MSDOS installations frequently remove lib-src, but we still
459 must set installation-directory, or else info won't find
460 its files (it uses the value of installation-directory). */
461 tem = Fexpand_file_name (build_string ("info"), dir);
462 info_exists = Ffile_exists_p (tem);
463 #else
464 info_exists = Qnil;
465 #endif
467 if (!NILP (lib_src_exists) || !NILP (info_exists))
469 tem = Fexpand_file_name (build_string ("etc"), dir);
470 etc_exists = Ffile_exists_p (tem);
471 if (!NILP (etc_exists))
473 Vinstallation_directory
474 = Ffile_name_as_directory (dir);
475 break;
479 /* See if dir's parent contains those subdirs. */
480 tem = Fexpand_file_name (build_string ("../lib-src"), dir);
481 lib_src_exists = Ffile_exists_p (tem);
484 #ifdef MSDOS
485 /* See the MSDOS commentary above. */
486 tem = Fexpand_file_name (build_string ("../info"), dir);
487 info_exists = Ffile_exists_p (tem);
488 #else
489 info_exists = Qnil;
490 #endif
492 if (!NILP (lib_src_exists) || !NILP (info_exists))
494 tem = Fexpand_file_name (build_string ("../etc"), dir);
495 etc_exists = Ffile_exists_p (tem);
496 if (!NILP (etc_exists))
498 tem = Fexpand_file_name (build_string (".."), dir);
499 Vinstallation_directory
500 = Ffile_name_as_directory (tem);
501 break;
505 /* If the Emacs executable is actually a link,
506 next try the dir that the link points into. */
507 tem = Ffile_symlink_p (name);
508 if (!NILP (tem))
510 name = Fexpand_file_name (tem, dir);
511 dir = Ffile_name_directory (name);
513 else
514 break;
518 Vcommand_line_args = Qnil;
520 for (i = argc - 1; i >= 0; i--)
522 if (i == 0 || i > skip_args)
523 /* For the moment, we keep arguments as is in unibyte strings.
524 They are decoded in the function command-line after we know
525 locale-coding-system. */
526 Vcommand_line_args
527 = Fcons (build_unibyte_string (argv[i]), Vcommand_line_args);
530 unbind_to (count, Qnil);
533 DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
534 doc: /* Return the program name that was used to run Emacs.
535 Any directory names are omitted. */)
536 (void)
538 return Fcopy_sequence (Vinvocation_name);
541 DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
542 0, 0, 0,
543 doc: /* Return the directory name in which the Emacs executable was located. */)
544 (void)
546 return Fcopy_sequence (Vinvocation_directory);
550 #ifdef HAVE_TZSET
551 /* A valid but unlikely value for the TZ environment value.
552 It is OK (though a bit slower) if the user actually chooses this value. */
553 static char const dump_tz[] = "UtC0";
554 #endif
556 /* Test whether the next argument in ARGV matches SSTR or a prefix of
557 LSTR (at least MINLEN characters). If so, then if VALPTR is non-null
558 (the argument is supposed to have a value) store in *VALPTR either
559 the next argument or the portion of this one after the equal sign.
560 ARGV is read starting at position *SKIPPTR; this index is advanced
561 by the number of arguments used.
563 Too bad we can't just use getopt for all of this, but we don't have
564 enough information to do it right. */
566 static bool
567 argmatch (char **argv, int argc, const char *sstr, const char *lstr,
568 int minlen, char **valptr, int *skipptr)
570 char *p = NULL;
571 ptrdiff_t arglen;
572 char *arg;
574 /* Don't access argv[argc]; give up in advance. */
575 if (argc <= *skipptr + 1)
576 return 0;
578 arg = argv[*skipptr+1];
579 if (arg == NULL)
580 return 0;
581 if (strcmp (arg, sstr) == 0)
583 if (valptr != NULL)
585 *valptr = argv[*skipptr+2];
586 *skipptr += 2;
588 else
589 *skipptr += 1;
590 return 1;
592 arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
593 ? p - arg : strlen (arg));
594 if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
595 return 0;
596 else if (valptr == NULL)
598 *skipptr += 1;
599 return 1;
601 else if (p != NULL)
603 *valptr = p+1;
604 *skipptr += 1;
605 return 1;
607 else if (argv[*skipptr+2] != NULL)
609 *valptr = argv[*skipptr+2];
610 *skipptr += 2;
611 return 1;
613 else
615 return 0;
619 #ifdef DOUG_LEA_MALLOC
621 /* malloc can be invoked even before main (e.g. by the dynamic
622 linker), so the dumped malloc state must be restored as early as
623 possible using this special hook. */
625 static void
626 malloc_initialize_hook (void)
628 if (initialized)
630 if (!malloc_using_checking)
631 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
632 ignored if the heap to be restored was constructed without
633 malloc checking. Can't use unsetenv, since that calls malloc. */
635 char **p;
637 for (p = environ; p && *p; p++)
638 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
641 *p = p[1];
642 while (*++p);
643 break;
647 malloc_set_state (malloc_state_ptr);
648 #ifndef XMALLOC_OVERRUN_CHECK
649 free (malloc_state_ptr);
650 #endif
652 else
654 if (my_heap_start == 0)
655 my_heap_start = sbrk (0);
656 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
660 void (*__malloc_initialize_hook) (void) EXTERNALLY_VISIBLE = malloc_initialize_hook;
662 #endif /* DOUG_LEA_MALLOC */
664 /* Close standard output and standard error, reporting any write
665 errors as best we can. This is intended for use with atexit. */
666 static void
667 close_output_streams (void)
669 if (close_stream (stdout) != 0)
671 emacs_perror ("Write error to standard output");
672 _exit (EXIT_FAILURE);
675 if (close_stream (stderr) != 0)
676 _exit (EXIT_FAILURE);
679 /* ARGSUSED */
681 main (int argc, char **argv)
683 #if GC_MARK_STACK
684 Lisp_Object dummy;
685 #endif
686 char stack_bottom_variable;
687 bool do_initial_setlocale;
688 bool dumping;
689 int skip_args = 0;
690 #ifdef HAVE_SETRLIMIT
691 struct rlimit rlim;
692 #endif
693 bool no_loadup = 0;
694 char *junk = 0;
695 char *dname_arg = 0;
696 #ifdef DAEMON_MUST_EXEC
697 char dname_arg2[80];
698 #endif
699 char *ch_to_dir;
701 #if GC_MARK_STACK
702 stack_base = &dummy;
703 #endif
705 #ifdef G_SLICE_ALWAYS_MALLOC
706 /* This is used by the Cygwin build. It's not needed starting with
707 cygwin-1.7.24, but it doesn't do any harm. */
708 xputenv ("G_SLICE=always-malloc");
709 #endif
711 #ifdef GNU_LINUX
712 if (!initialized)
714 extern char my_endbss[];
715 extern char *my_endbss_static;
717 if (my_heap_start == 0)
718 my_heap_start = sbrk (0);
720 heap_bss_diff = (char *)my_heap_start - max (my_endbss, my_endbss_static);
722 #endif
724 #if defined WINDOWSNT || defined HAVE_NTGUI
725 /* Set global variables used to detect Windows version. Do this as
726 early as possible. (unexw32.c calls this function as well, but
727 the additional call here is harmless.) */
728 cache_system_info ();
729 #endif
731 #ifdef RUN_TIME_REMAP
732 if (initialized)
733 run_time_remap (argv[0]);
734 #endif
736 /* If using unexmacosx.c (set by s/darwin.h), we must do this. */
737 #ifdef DARWIN_OS
738 if (!initialized)
739 unexec_init_emacs_zone ();
740 #endif
742 atexit (close_output_streams);
744 sort_args (argc, argv);
745 argc = 0;
746 while (argv[argc]) argc++;
748 if (argmatch (argv, argc, "-version", "--version", 3, NULL, &skip_args))
750 const char *version, *copyright;
751 if (initialized)
753 Lisp_Object tem, tem2;
754 tem = Fsymbol_value (intern_c_string ("emacs-version"));
755 tem2 = Fsymbol_value (intern_c_string ("emacs-copyright"));
756 if (!STRINGP (tem))
758 fprintf (stderr, "Invalid value of `emacs-version'\n");
759 exit (1);
761 if (!STRINGP (tem2))
763 fprintf (stderr, "Invalid value of `emacs-copyright'\n");
764 exit (1);
766 else
768 version = SSDATA (tem);
769 copyright = SSDATA (tem2);
772 else
774 version = emacs_version;
775 copyright = emacs_copyright;
777 printf ("GNU Emacs %s\n", version);
778 printf ("%s\n", copyright);
779 printf ("GNU Emacs comes with ABSOLUTELY NO WARRANTY.\n");
780 printf ("You may redistribute copies of Emacs\n");
781 printf ("under the terms of the GNU General Public License.\n");
782 printf ("For more information about these matters, ");
783 printf ("see the file named COPYING.\n");
784 exit (0);
787 if (argmatch (argv, argc, "-chdir", "--chdir", 4, &ch_to_dir, &skip_args))
788 if (chdir (ch_to_dir) == -1)
790 fprintf (stderr, "%s: Can't chdir to %s: %s\n",
791 argv[0], ch_to_dir, strerror (errno));
792 exit (1);
795 dumping = !initialized && (strcmp (argv[argc - 1], "dump") == 0
796 || strcmp (argv[argc - 1], "bootstrap") == 0);
798 #ifdef HAVE_PERSONALITY_LINUX32
799 if (dumping && ! getenv ("EMACS_HEAP_EXEC"))
801 /* Set this so we only do this once. */
802 xputenv ("EMACS_HEAP_EXEC=true");
804 /* A flag to turn off address randomization which is introduced
805 in linux kernel shipped with fedora core 4 */
806 #define ADD_NO_RANDOMIZE 0x0040000
807 personality (PER_LINUX32 | ADD_NO_RANDOMIZE);
808 #undef ADD_NO_RANDOMIZE
810 execvp (argv[0], argv);
812 /* If the exec fails, try to dump anyway. */
813 emacs_perror (argv[0]);
815 #endif /* HAVE_PERSONALITY_LINUX32 */
817 #if defined (HAVE_SETRLIMIT) && defined (RLIMIT_STACK)
818 /* Extend the stack space available.
819 Don't do that if dumping, since some systems (e.g. DJGPP)
820 might define a smaller stack limit at that time. */
821 if (1
822 #ifndef CANNOT_DUMP
823 && (!noninteractive || initialized)
824 #endif
825 && !getrlimit (RLIMIT_STACK, &rlim))
827 long newlim;
828 extern size_t re_max_failures;
829 /* Approximate the amount regex.c needs per unit of re_max_failures. */
830 int ratio = 20 * sizeof (char *);
831 /* Then add 33% to cover the size of the smaller stacks that regex.c
832 successively allocates and discards, on its way to the maximum. */
833 ratio += ratio / 3;
834 /* Add in some extra to cover
835 what we're likely to use for other reasons. */
836 newlim = re_max_failures * ratio + 200000;
837 #ifdef __NetBSD__
838 /* NetBSD (at least NetBSD 1.2G and former) has a bug in its
839 stack allocation routine for new process that the allocation
840 fails if stack limit is not on page boundary. So, round up the
841 new limit to page boundary. */
842 newlim = (newlim + getpagesize () - 1) / getpagesize () * getpagesize ();
843 #endif
844 if (newlim > rlim.rlim_max)
846 newlim = rlim.rlim_max;
847 /* Don't let regex.c overflow the stack we have. */
848 re_max_failures = (newlim - 200000) / ratio;
850 if (rlim.rlim_cur < newlim)
851 rlim.rlim_cur = newlim;
853 setrlimit (RLIMIT_STACK, &rlim);
855 #endif /* HAVE_SETRLIMIT and RLIMIT_STACK */
857 /* Record (approximately) where the stack begins. */
858 stack_bottom = &stack_bottom_variable;
860 clearerr (stdin);
862 #ifndef SYSTEM_MALLOC
863 /* Arrange to get warning messages as memory fills up. */
864 memory_warnings (0, malloc_warning);
866 /* Call malloc at least once, to run malloc_initialize_hook.
867 Also call realloc and free for consistency. */
868 free (realloc (malloc (4), 4));
870 #endif /* not SYSTEM_MALLOC */
872 #if defined (MSDOS) || defined (WINDOWSNT)
873 /* We do all file input/output as binary files. When we need to translate
874 newlines, we do that manually. */
875 _fmode = O_BINARY;
876 #endif /* MSDOS || WINDOWSNT */
878 #ifdef MSDOS
879 if (!isatty (fileno (stdin)))
880 setmode (fileno (stdin), O_BINARY);
881 if (!isatty (fileno (stdout)))
883 fflush (stdout);
884 setmode (fileno (stdout), O_BINARY);
886 #endif /* MSDOS */
888 /* Skip initial setlocale if LC_ALL is "C", as it's not needed in that case.
889 The build procedure uses this while dumping, to ensure that the
890 dumped Emacs does not have its system locale tables initialized,
891 as that might cause screwups when the dumped Emacs starts up. */
893 char *lc_all = getenv ("LC_ALL");
894 do_initial_setlocale = ! lc_all || strcmp (lc_all, "C");
897 /* Set locale now, so that initial error messages are localized properly.
898 fixup_locale must wait until later, since it builds strings. */
899 if (do_initial_setlocale)
900 setlocale (LC_ALL, "");
902 inhibit_window_system = 0;
904 /* Handle the -t switch, which specifies filename to use as terminal. */
905 while (1)
907 char *term;
908 if (argmatch (argv, argc, "-t", "--terminal", 4, &term, &skip_args))
910 int result;
911 emacs_close (0);
912 emacs_close (1);
913 result = emacs_open (term, O_RDWR, 0);
914 if (result < 0 || fcntl (0, F_DUPFD_CLOEXEC, 1) < 0)
916 char *errstring = strerror (errno);
917 fprintf (stderr, "%s: %s: %s\n", argv[0], term, errstring);
918 exit (1);
920 if (! isatty (0))
922 fprintf (stderr, "%s: %s: not a tty\n", argv[0], term);
923 exit (1);
925 fprintf (stderr, "Using %s\n", term);
926 #ifdef HAVE_WINDOW_SYSTEM
927 inhibit_window_system = 1; /* -t => -nw */
928 #endif
930 else
931 break;
934 /* Command line option --no-windows is deprecated and thus not mentioned
935 in the manual and usage information. */
936 if (argmatch (argv, argc, "-nw", "--no-window-system", 6, NULL, &skip_args)
937 || argmatch (argv, argc, "-nw", "--no-windows", 6, NULL, &skip_args))
938 inhibit_window_system = 1;
940 /* Handle the -batch switch, which means don't do interactive display. */
941 noninteractive = 0;
942 if (argmatch (argv, argc, "-batch", "--batch", 5, NULL, &skip_args))
944 noninteractive = 1;
945 Vundo_outer_limit = Qnil;
947 if (argmatch (argv, argc, "-script", "--script", 3, &junk, &skip_args))
949 noninteractive = 1; /* Set batch mode. */
950 /* Convert --script to -scriptload, un-skip it, and sort again
951 so that it will be handled in proper sequence. */
952 /* FIXME broken for --script=FILE - is that supposed to work? */
953 argv[skip_args - 1] = (char *) "-scriptload";
954 skip_args -= 2;
955 sort_args (argc, argv);
958 /* Handle the --help option, which gives a usage message. */
959 if (argmatch (argv, argc, "-help", "--help", 3, NULL, &skip_args))
961 int i;
962 printf ("Usage: %s [OPTION-OR-FILENAME]...\n", argv[0]);
963 for (i = 0; i < sizeof usage_message / sizeof *usage_message; i++)
964 fputs (usage_message[i], stdout);
965 exit (0);
968 if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
969 || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
971 #ifndef DOS_NT
972 pid_t f;
974 /* Start as a daemon: fork a new child process which will run the
975 rest of the initialization code, then exit.
977 Detaching a daemon requires the following steps:
978 - fork
979 - setsid
980 - exit the parent
981 - close the tty file-descriptors
983 We only want to do the last 2 steps once the daemon is ready to
984 serve requests, i.e. after loading .emacs (initialization).
985 OTOH initialization may start subprocesses (e.g. ispell) and these
986 should be run from the proper process (the one that will end up
987 running as daemon) and with the proper "session id" in order for
988 them to keep working after detaching, so fork and setsid need to be
989 performed before initialization.
991 We want to avoid exiting before the server socket is ready, so
992 use a pipe for synchronization. The parent waits for the child
993 to close its end of the pipe (using `daemon-initialized')
994 before exiting. */
995 if (emacs_pipe (daemon_pipe) != 0)
997 fprintf (stderr, "Cannot pipe!\n");
998 exit (1);
1001 #ifndef DAEMON_MUST_EXEC
1002 #ifdef USE_GTK
1003 fprintf (stderr, "\nWarning: due to a long standing Gtk+ bug\nhttp://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
1004 Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.\n\
1005 Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.\n");
1006 #endif /* USE_GTK */
1007 f = fork ();
1008 #else /* DAEMON_MUST_EXEC */
1009 if (!dname_arg || !strchr (dname_arg, '\n'))
1010 f = fork (); /* in orig */
1011 else
1012 f = 0; /* in exec'd */
1013 #endif /* !DAEMON_MUST_EXEC */
1014 if (f > 0)
1016 int retval;
1017 char buf[1];
1019 /* Close unused writing end of the pipe. */
1020 emacs_close (daemon_pipe[1]);
1022 /* Just wait for the child to close its end of the pipe. */
1025 retval = read (daemon_pipe[0], &buf, 1);
1027 while (retval == -1 && errno == EINTR);
1029 if (retval < 0)
1031 fprintf (stderr, "Error reading status from child\n");
1032 exit (1);
1034 else if (retval == 0)
1036 fprintf (stderr, "Error: server did not start correctly\n");
1037 exit (1);
1040 emacs_close (daemon_pipe[0]);
1041 exit (0);
1043 if (f < 0)
1045 emacs_perror ("fork");
1046 exit (EXIT_CANCELED);
1049 #ifdef DAEMON_MUST_EXEC
1051 /* In orig process, forked as child, OR in exec'd. */
1052 if (!dname_arg || !strchr (dname_arg, '\n'))
1053 { /* In orig, child: now exec w/special daemon name. */
1054 char fdStr[80];
1055 int fdStrlen =
1056 snprintf (fdStr, sizeof fdStr,
1057 "--daemon=\n%d,%d\n%s", daemon_pipe[0],
1058 daemon_pipe[1], dname_arg ? dname_arg : "");
1060 if (! (0 <= fdStrlen && fdStrlen < sizeof fdStr))
1062 fprintf (stderr, "daemon: child name too long\n");
1063 exit (EXIT_CANNOT_INVOKE);
1066 argv[skip_args] = fdStr;
1068 execvp (argv[0], argv);
1069 emacs_perror (argv[0]);
1070 exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
1073 /* In exec'd: parse special dname into pipe and name info. */
1074 if (!dname_arg || !strchr (dname_arg, '\n')
1075 || strlen (dname_arg) < 1 || strlen (dname_arg) > 70)
1077 fprintf (stderr, "emacs daemon: daemon name absent or too long\n");
1078 exit (EXIT_CANNOT_INVOKE);
1080 dname_arg2[0] = '\0';
1081 sscanf (dname_arg, "\n%d,%d\n%s", &(daemon_pipe[0]), &(daemon_pipe[1]),
1082 dname_arg2);
1083 dname_arg = *dname_arg2 ? dname_arg2 : NULL;
1085 #endif /* DAEMON_MUST_EXEC */
1087 if (dname_arg)
1088 daemon_name = xstrdup (dname_arg);
1089 /* Close unused reading end of the pipe. */
1090 emacs_close (daemon_pipe[0]);
1092 setsid ();
1093 #else /* DOS_NT */
1094 fprintf (stderr, "This platform does not support the -daemon flag.\n");
1095 exit (1);
1096 #endif /* DOS_NT */
1099 #if defined HAVE_PTHREAD && !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC
1100 # ifndef CANNOT_DUMP
1101 /* Do not make gmalloc thread-safe when creating bootstrap-emacs, as
1102 that causes an infinite recursive loop with FreeBSD. But do make
1103 it thread-safe when creating emacs, otherwise bootstrap-emacs
1104 fails on Cygwin. See Bug#14569. */
1105 if (!noninteractive || initialized)
1106 # endif
1107 malloc_enable_thread ();
1108 #endif
1110 init_signals (dumping);
1112 noninteractive1 = noninteractive;
1114 /* Perform basic initializations (not merely interning symbols). */
1116 if (!initialized)
1118 init_alloc_once ();
1119 init_obarray ();
1120 init_eval_once ();
1121 init_charset_once ();
1122 init_coding_once ();
1123 init_syntax_once (); /* Create standard syntax table. */
1124 init_category_once (); /* Create standard category table. */
1125 init_casetab_once (); /* Must be done before init_buffer_once. */
1126 init_buffer_once (); /* Create buffer table and some buffers. */
1127 init_minibuf_once (); /* Create list of minibuffers. */
1128 /* Must precede init_window_once. */
1130 /* Call syms_of_xfaces before init_window_once because that
1131 function creates Vterminal_frame. Termcap frames now use
1132 faces, and the face implementation uses some symbols as
1133 face names. */
1134 syms_of_xfaces ();
1135 /* XXX syms_of_keyboard uses some symbols in keymap.c. It would
1136 be better to arrange things not to have this dependency. */
1137 syms_of_keymap ();
1138 /* Call syms_of_keyboard before init_window_once because
1139 keyboard sets up symbols that include some face names that
1140 the X support will want to use. This can happen when
1141 CANNOT_DUMP is defined. */
1142 syms_of_keyboard ();
1144 /* Called before syms_of_fileio, because it sets up Qerror_condition. */
1145 syms_of_data ();
1146 syms_of_fns (); /* Before syms_of_charset which uses hashtables. */
1147 syms_of_fileio ();
1148 /* Before syms_of_coding to initialize Vgc_cons_threshold. */
1149 syms_of_alloc ();
1150 /* May call Ffuncall and so GC, thus the latter should be initialized. */
1151 init_print_once ();
1152 /* Before syms_of_coding because it initializes Qcharsetp. */
1153 syms_of_charset ();
1154 /* Before init_window_once, because it sets up the
1155 Vcoding_system_hash_table. */
1156 syms_of_coding (); /* This should be after syms_of_fileio. */
1158 init_window_once (); /* Init the window system. */
1159 #ifdef HAVE_WINDOW_SYSTEM
1160 init_fringe_once (); /* Swap bitmaps if necessary. */
1161 #endif /* HAVE_WINDOW_SYSTEM */
1164 init_alloc ();
1166 if (do_initial_setlocale)
1168 fixup_locale ();
1169 Vsystem_messages_locale = Vprevious_system_messages_locale;
1170 Vsystem_time_locale = Vprevious_system_time_locale;
1173 init_eval ();
1174 init_atimer ();
1175 running_asynch_code = 0;
1176 init_random ();
1178 no_loadup
1179 = argmatch (argv, argc, "-nl", "--no-loadup", 6, NULL, &skip_args);
1181 no_site_lisp
1182 = argmatch (argv, argc, "-nsl", "--no-site-lisp", 11, NULL, &skip_args);
1184 #ifdef HAVE_NS
1185 ns_pool = ns_alloc_autorelease_pool ();
1186 if (!noninteractive)
1188 #ifdef NS_IMPL_COCOA
1189 if (skip_args < argc)
1191 /* FIXME: Do the right thing if getenv returns NULL, or if
1192 chdir fails. */
1193 if (!strncmp (argv[skip_args], "-psn", 4))
1195 skip_args += 1;
1196 chdir (getenv ("HOME"));
1198 else if (skip_args+1 < argc && !strncmp (argv[skip_args+1], "-psn", 4))
1200 skip_args += 2;
1201 chdir (getenv ("HOME"));
1204 #endif /* COCOA */
1206 #endif /* HAVE_NS */
1208 #ifdef HAVE_X_WINDOWS
1209 /* Stupid kludge to catch command-line display spec. We can't
1210 handle this argument entirely in window system dependent code
1211 because we don't even know which window system dependent code
1212 to run until we've recognized this argument. */
1214 char *displayname = 0;
1215 int count_before = skip_args;
1217 /* Skip any number of -d options, but only use the last one. */
1218 while (1)
1220 int count_before_this = skip_args;
1222 if (argmatch (argv, argc, "-d", "--display", 3, &displayname, &skip_args))
1223 display_arg = 1;
1224 else if (argmatch (argv, argc, "-display", 0, 3, &displayname, &skip_args))
1225 display_arg = 1;
1226 else
1227 break;
1229 count_before = count_before_this;
1232 /* If we have the form --display=NAME,
1233 convert it into -d name.
1234 This requires inserting a new element into argv. */
1235 if (displayname && count_before < skip_args)
1237 if (skip_args == count_before + 1)
1239 memmove (argv + count_before + 3, argv + count_before + 2,
1240 (argc - (count_before + 2)) * sizeof *argv);
1241 argv[count_before + 2] = displayname;
1242 argc++;
1244 argv[count_before + 1] = (char *) "-d";
1247 if (! no_site_lisp)
1249 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1250 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1251 no_site_lisp = 1;
1254 /* Don't actually discard this arg. */
1255 skip_args = count_before;
1257 #else /* !HAVE_X_WINDOWS */
1258 if (! no_site_lisp)
1260 int count_before = skip_args;
1262 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1263 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1264 no_site_lisp = 1;
1266 skip_args = count_before;
1268 #endif
1270 /* argmatch must not be used after here,
1271 except when building temacs
1272 because the -d argument has not been skipped in skip_args. */
1274 #ifdef MSDOS
1275 /* Call early 'cause init_environment needs it. */
1276 init_dosfns ();
1277 /* Set defaults for several environment variables. */
1278 if (initialized)
1279 init_environment (argc, argv, skip_args);
1280 else
1281 tzset ();
1282 #endif /* MSDOS */
1284 #ifdef HAVE_GFILENOTIFY
1285 globals_of_gfilenotify ();
1286 #endif
1288 #ifdef WINDOWSNT
1289 globals_of_w32 ();
1290 #ifdef HAVE_W32NOTIFY
1291 globals_of_w32notify ();
1292 #endif
1293 /* Initialize environment from registry settings. */
1294 init_environment (argv);
1295 init_ntproc (dumping); /* must precede init_editfns. */
1296 #endif
1298 /* Initialize and GC-protect Vinitial_environment and
1299 Vprocess_environment before set_initial_environment fills them
1300 in. */
1301 if (!initialized)
1302 syms_of_callproc ();
1303 /* egetenv is a pretty low-level facility, which may get called in
1304 many circumstances; it seems flimsy to put off initializing it
1305 until calling init_callproc. Do not do it when dumping. */
1306 if (! dumping)
1307 set_initial_environment ();
1309 /* AIX crashes are reported in system versions 3.2.3 and 3.2.4
1310 if this is not done. Do it after set_global_environment so that we
1311 don't pollute Vglobal_environment. */
1312 /* Setting LANG here will defeat the startup locale processing... */
1313 #ifdef AIX
1314 xputenv ("LANG=C");
1315 #endif
1317 init_buffer (); /* Init default directory of main buffer. */
1319 init_callproc_1 (); /* Must precede init_cmdargs and init_sys_modes. */
1320 init_cmdargs (argc, argv, skip_args); /* Must precede init_lread. */
1322 if (initialized)
1324 /* Erase any pre-dump messages in the message log, to avoid confusion. */
1325 Lisp_Object old_log_max;
1326 old_log_max = Vmessage_log_max;
1327 XSETFASTINT (Vmessage_log_max, 0);
1328 message_dolog ("", 0, 1, 0);
1329 Vmessage_log_max = old_log_max;
1332 init_callproc (); /* Must follow init_cmdargs but not init_sys_modes. */
1333 init_fileio ();
1334 init_lread ();
1335 #ifdef WINDOWSNT
1336 /* Check to see if Emacs has been installed correctly. */
1337 check_windows_init_file ();
1338 #endif
1340 /* Intern the names of all standard functions and variables;
1341 define standard keys. */
1343 if (!initialized)
1345 /* The basic levels of Lisp must come first. Note that
1346 syms_of_data and some others have already been called. */
1347 syms_of_chartab ();
1348 syms_of_lread ();
1349 syms_of_print ();
1350 syms_of_eval ();
1351 syms_of_floatfns ();
1353 syms_of_buffer ();
1354 syms_of_bytecode ();
1355 syms_of_callint ();
1356 syms_of_casefiddle ();
1357 syms_of_casetab ();
1358 syms_of_category ();
1359 syms_of_ccl ();
1360 syms_of_character ();
1361 syms_of_cmds ();
1362 syms_of_dired ();
1363 syms_of_display ();
1364 syms_of_doc ();
1365 syms_of_editfns ();
1366 syms_of_emacs ();
1367 syms_of_filelock ();
1368 syms_of_indent ();
1369 syms_of_insdel ();
1370 /* syms_of_keymap (); */
1371 syms_of_macros ();
1372 syms_of_marker ();
1373 syms_of_minibuf ();
1374 syms_of_process ();
1375 syms_of_search ();
1376 syms_of_frame ();
1377 syms_of_syntax ();
1378 syms_of_terminal ();
1379 syms_of_term ();
1380 syms_of_undo ();
1381 #ifdef HAVE_SOUND
1382 syms_of_sound ();
1383 #endif
1384 syms_of_textprop ();
1385 syms_of_composite ();
1386 #ifdef WINDOWSNT
1387 syms_of_ntproc ();
1388 #endif /* WINDOWSNT */
1389 #if defined CYGWIN
1390 syms_of_cygw32 ();
1391 #endif
1392 syms_of_window ();
1393 syms_of_xdisp ();
1394 syms_of_font ();
1395 #ifdef HAVE_WINDOW_SYSTEM
1396 syms_of_fringe ();
1397 syms_of_image ();
1398 #endif /* HAVE_WINDOW_SYSTEM */
1399 #ifdef HAVE_X_WINDOWS
1400 syms_of_xterm ();
1401 syms_of_xfns ();
1402 syms_of_xmenu ();
1403 syms_of_fontset ();
1404 syms_of_xsettings ();
1405 #ifdef HAVE_X_SM
1406 syms_of_xsmfns ();
1407 #endif
1408 #ifdef HAVE_X11
1409 syms_of_xselect ();
1410 #endif
1411 #endif /* HAVE_X_WINDOWS */
1413 #ifdef HAVE_LIBXML2
1414 syms_of_xml ();
1415 #endif
1417 #ifdef HAVE_ZLIB
1418 syms_of_decompress ();
1419 #endif
1421 syms_of_menu ();
1423 #ifdef HAVE_NTGUI
1424 syms_of_w32term ();
1425 syms_of_w32fns ();
1426 syms_of_w32menu ();
1427 syms_of_fontset ();
1428 #endif /* HAVE_NTGUI */
1430 #if defined WINDOWSNT || defined HAVE_NTGUI
1431 syms_of_w32select ();
1432 #endif
1434 #ifdef MSDOS
1435 syms_of_xmenu ();
1436 syms_of_dosfns ();
1437 syms_of_msdos ();
1438 syms_of_win16select ();
1439 #endif /* MSDOS */
1441 #ifdef HAVE_NS
1442 syms_of_nsterm ();
1443 syms_of_nsfns ();
1444 syms_of_nsmenu ();
1445 syms_of_nsselect ();
1446 syms_of_fontset ();
1447 #endif /* HAVE_NS */
1449 #ifdef HAVE_GNUTLS
1450 syms_of_gnutls ();
1451 #endif
1453 #ifdef HAVE_GFILENOTIFY
1454 syms_of_gfilenotify ();
1455 #endif /* HAVE_GFILENOTIFY */
1457 #ifdef HAVE_INOTIFY
1458 syms_of_inotify ();
1459 #endif /* HAVE_INOTIFY */
1461 #ifdef HAVE_DBUS
1462 syms_of_dbusbind ();
1463 #endif /* HAVE_DBUS */
1465 #ifdef WINDOWSNT
1466 syms_of_ntterm ();
1467 #ifdef HAVE_W32NOTIFY
1468 syms_of_w32notify ();
1469 #endif /* HAVE_W32NOTIFY */
1470 #endif /* WINDOWSNT */
1472 syms_of_profiler ();
1474 keys_of_casefiddle ();
1475 keys_of_cmds ();
1476 keys_of_buffer ();
1477 keys_of_keyboard ();
1478 keys_of_keymap ();
1479 keys_of_window ();
1481 else
1483 /* Initialization that must be done even if the global variable
1484 initialized is non zero. */
1485 #ifdef HAVE_NTGUI
1486 globals_of_w32font ();
1487 globals_of_w32fns ();
1488 globals_of_w32menu ();
1489 #endif /* HAVE_NTGUI */
1491 #if defined WINDOWSNT || defined HAVE_NTGUI
1492 globals_of_w32select ();
1493 #endif
1496 init_charset ();
1498 init_editfns (); /* init_process_emacs uses Voperating_system_release. */
1499 init_process_emacs (); /* init_display uses add_keyboard_wait_descriptor. */
1500 init_keyboard (); /* This too must precede init_sys_modes. */
1501 if (!noninteractive)
1502 init_display (); /* Determine terminal type. Calls init_sys_modes. */
1503 init_xdisp ();
1504 #ifdef HAVE_WINDOW_SYSTEM
1505 init_fringe ();
1506 #endif /* HAVE_WINDOW_SYSTEM */
1507 init_macros ();
1508 init_window ();
1509 init_font ();
1511 if (!initialized)
1513 char *file;
1514 /* Handle -l loadup, args passed by Makefile. */
1515 if (argmatch (argv, argc, "-l", "--load", 3, &file, &skip_args))
1516 Vtop_level = list2 (intern_c_string ("load"), build_string (file));
1517 /* Unless next switch is -nl, load "loadup.el" first thing. */
1518 if (! no_loadup)
1519 Vtop_level = list2 (intern_c_string ("load"),
1520 build_string ("loadup.el"));
1523 if (initialized)
1525 #ifdef HAVE_TZSET
1527 /* If the execution TZ happens to be the same as the dump TZ,
1528 change it to some other value and then change it back,
1529 to force the underlying implementation to reload the TZ info.
1530 This is needed on implementations that load TZ info from files,
1531 since the TZ file contents may differ between dump and execution. */
1532 char *tz = getenv ("TZ");
1533 if (tz && !strcmp (tz, dump_tz))
1535 ++*tz;
1536 tzset ();
1537 --*tz;
1540 #endif
1543 /* Set up for profiling. This is known to work on FreeBSD,
1544 GNU/Linux and MinGW. It might work on some other systems too.
1545 Give it a try and tell us if it works on your system. To compile
1546 for profiling, use the configure option --enable-profiling. */
1547 #if defined (__FreeBSD__) || defined (GNU_LINUX) || defined (__MINGW32__)
1548 #ifdef PROFILING
1549 if (initialized)
1551 #ifdef __MINGW32__
1552 extern unsigned char etext asm ("etext");
1553 #else
1554 extern char etext;
1555 #endif
1557 atexit (_mcleanup);
1558 monstartup ((uintptr_t) __executable_start, (uintptr_t) &etext);
1560 else
1561 moncontrol (0);
1562 #endif
1563 #endif
1565 initialized = 1;
1567 #ifdef LOCALTIME_CACHE
1568 /* Some versions of localtime have a bug. They cache the value of the time
1569 zone rather than looking it up every time. Since localtime() is
1570 called to bolt the undumping time into the undumped emacs, this
1571 results in localtime ignoring the TZ environment variable.
1572 This flushes the new TZ value into localtime. */
1573 tzset ();
1574 #endif /* defined (LOCALTIME_CACHE) */
1576 /* Enter editor command loop. This never returns. */
1577 Frecursive_edit ();
1578 /* NOTREACHED */
1579 return 0;
1582 /* Sort the args so we can find the most important ones
1583 at the beginning of argv. */
1585 /* First, here's a table of all the standard options. */
1587 struct standard_args
1589 const char *name;
1590 const char *longname;
1591 int priority;
1592 int nargs;
1595 static const struct standard_args standard_args[] =
1597 { "-version", "--version", 150, 0 },
1598 { "-chdir", "--chdir", 130, 1 },
1599 { "-t", "--terminal", 120, 1 },
1600 { "-nw", "--no-window-system", 110, 0 },
1601 { "-nw", "--no-windows", 110, 0 },
1602 { "-batch", "--batch", 100, 0 },
1603 { "-script", "--script", 100, 1 },
1604 { "-daemon", "--daemon", 99, 0 },
1605 { "-help", "--help", 90, 0 },
1606 { "-nl", "--no-loadup", 70, 0 },
1607 { "-nsl", "--no-site-lisp", 65, 0 },
1608 /* -d must come last before the options handled in startup.el. */
1609 { "-d", "--display", 60, 1 },
1610 { "-display", 0, 60, 1 },
1611 /* Now for the options handled in `command-line' (startup.el). */
1612 /* (Note that to imply -nsl, -Q is partially handled here.) */
1613 { "-Q", "--quick", 55, 0 },
1614 { "-quick", 0, 55, 0 },
1615 { "-q", "--no-init-file", 50, 0 },
1616 { "-no-init-file", 0, 50, 0 },
1617 { "-no-site-file", "--no-site-file", 40, 0 },
1618 { "-u", "--user", 30, 1 },
1619 { "-user", 0, 30, 1 },
1620 { "-debug-init", "--debug-init", 20, 0 },
1621 { "-iconic", "--iconic", 15, 0 },
1622 { "-D", "--basic-display", 12, 0},
1623 { "-basic-display", 0, 12, 0},
1624 { "-nbc", "--no-blinking-cursor", 12, 0 },
1625 /* Now for the options handled in `command-line-1' (startup.el). */
1626 { "-nbi", "--no-bitmap-icon", 10, 0 },
1627 { "-bg", "--background-color", 10, 1 },
1628 { "-background", 0, 10, 1 },
1629 { "-fg", "--foreground-color", 10, 1 },
1630 { "-foreground", 0, 10, 1 },
1631 { "-bd", "--border-color", 10, 1 },
1632 { "-bw", "--border-width", 10, 1 },
1633 { "-ib", "--internal-border", 10, 1 },
1634 { "-ms", "--mouse-color", 10, 1 },
1635 { "-cr", "--cursor-color", 10, 1 },
1636 { "-fn", "--font", 10, 1 },
1637 { "-font", 0, 10, 1 },
1638 { "-fs", "--fullscreen", 10, 0 },
1639 { "-fw", "--fullwidth", 10, 0 },
1640 { "-fh", "--fullheight", 10, 0 },
1641 { "-mm", "--maximized", 10, 0 },
1642 { "-g", "--geometry", 10, 1 },
1643 { "-geometry", 0, 10, 1 },
1644 { "-T", "--title", 10, 1 },
1645 { "-title", 0, 10, 1 },
1646 { "-name", "--name", 10, 1 },
1647 { "-xrm", "--xrm", 10, 1 },
1648 { "-parent-id", "--parent-id", 10, 1 },
1649 { "-r", "--reverse-video", 5, 0 },
1650 { "-rv", 0, 5, 0 },
1651 { "-reverse", 0, 5, 0 },
1652 { "-hb", "--horizontal-scroll-bars", 5, 0 },
1653 { "-vb", "--vertical-scroll-bars", 5, 0 },
1654 { "-color", "--color", 5, 0},
1655 { "-no-splash", "--no-splash", 3, 0 },
1656 { "-no-desktop", "--no-desktop", 3, 0 },
1657 #ifdef HAVE_NS
1658 { "-NSAutoLaunch", 0, 5, 1 },
1659 { "-NXAutoLaunch", 0, 5, 1 },
1660 { "-disable-font-backend", "--disable-font-backend", 65, 0 },
1661 { "-_NSMachLaunch", 0, 85, 1 },
1662 { "-MachLaunch", 0, 85, 1 },
1663 { "-macosx", 0, 85, 0 },
1664 { "-NSHost", 0, 85, 1 },
1665 #endif
1666 /* These have the same priority as ordinary file name args,
1667 so they are not reordered with respect to those. */
1668 { "-L", "--directory", 0, 1 },
1669 { "-directory", 0, 0, 1 },
1670 { "-l", "--load", 0, 1 },
1671 { "-load", 0, 0, 1 },
1672 /* This has no longname, because using --scriptload confuses sort_args,
1673 because then the --script long option seems to match twice; ie
1674 you can't have a long option which is a prefix of another long
1675 option. In any case, this is entirely an internal option. */
1676 { "-scriptload", NULL, 0, 1 },
1677 { "-f", "--funcall", 0, 1 },
1678 { "-funcall", 0, 0, 1 },
1679 { "-eval", "--eval", 0, 1 },
1680 { "-execute", "--execute", 0, 1 },
1681 { "-find-file", "--find-file", 0, 1 },
1682 { "-visit", "--visit", 0, 1 },
1683 { "-file", "--file", 0, 1 },
1684 { "-insert", "--insert", 0, 1 },
1685 #ifdef HAVE_NS
1686 { "-NXOpen", 0, 0, 1 },
1687 { "-NXOpenTemp", 0, 0, 1 },
1688 { "-NSOpen", 0, 0, 1 },
1689 { "-NSOpenTemp", 0, 0, 1 },
1690 { "-GSFilePath", 0, 0, 1 },
1691 #endif
1692 /* This should be processed after ordinary file name args and the like. */
1693 { "-kill", "--kill", -10, 0 },
1696 /* Reorder the elements of ARGV (assumed to have ARGC elements)
1697 so that the highest priority ones come first.
1698 Do not change the order of elements of equal priority.
1699 If an option takes an argument, keep it and its argument together.
1701 If an option that takes no argument appears more
1702 than once, eliminate all but one copy of it. */
1704 static void
1705 sort_args (int argc, char **argv)
1707 char **new = xmalloc (argc * sizeof *new);
1708 /* For each element of argv,
1709 the corresponding element of options is:
1710 0 for an option that takes no arguments,
1711 1 for an option that takes one argument, etc.
1712 -1 for an ordinary non-option argument. */
1713 int *options = xnmalloc (argc, sizeof *options);
1714 int *priority = xnmalloc (argc, sizeof *priority);
1715 int to = 1;
1716 int incoming_used = 1;
1717 int from;
1718 int i;
1720 /* Categorize all the options,
1721 and figure out which argv elts are option arguments. */
1722 for (from = 1; from < argc; from++)
1724 options[from] = -1;
1725 priority[from] = 0;
1726 if (argv[from][0] == '-')
1728 int match;
1730 /* If we have found "--", don't consider
1731 any more arguments as options. */
1732 if (argv[from][1] == '-' && argv[from][2] == 0)
1734 /* Leave the "--", and everything following it, at the end. */
1735 for (; from < argc; from++)
1737 priority[from] = -100;
1738 options[from] = -1;
1740 break;
1743 /* Look for a match with a known old-fashioned option. */
1744 for (i = 0; i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1745 if (!strcmp (argv[from], standard_args[i].name))
1747 options[from] = standard_args[i].nargs;
1748 priority[from] = standard_args[i].priority;
1749 if (from + standard_args[i].nargs >= argc)
1750 fatal ("Option `%s' requires an argument\n", argv[from]);
1751 from += standard_args[i].nargs;
1752 goto done;
1755 /* Look for a match with a known long option.
1756 MATCH is -1 if no match so far, -2 if two or more matches so far,
1757 >= 0 (the table index of the match) if just one match so far. */
1758 if (argv[from][1] == '-')
1760 char const *equals = strchr (argv[from], '=');
1761 ptrdiff_t thislen =
1762 equals ? equals - argv[from] : strlen (argv[from]);
1764 match = -1;
1766 for (i = 0;
1767 i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1768 if (standard_args[i].longname
1769 && !strncmp (argv[from], standard_args[i].longname,
1770 thislen))
1772 if (match == -1)
1773 match = i;
1774 else
1775 match = -2;
1778 /* If we found exactly one match, use that. */
1779 if (match >= 0)
1781 options[from] = standard_args[match].nargs;
1782 priority[from] = standard_args[match].priority;
1783 /* If --OPTION=VALUE syntax is used,
1784 this option uses just one argv element. */
1785 if (equals != 0)
1786 options[from] = 0;
1787 if (from + options[from] >= argc)
1788 fatal ("Option `%s' requires an argument\n", argv[from]);
1789 from += options[from];
1791 /* FIXME When match < 0, shouldn't there be some error,
1792 or at least indication to the user that there was a
1793 problem? */
1795 done: ;
1799 /* Copy the arguments, in order of decreasing priority, to NEW. */
1800 new[0] = argv[0];
1801 while (incoming_used < argc)
1803 int best = -1;
1804 int best_priority = -9999;
1806 /* Find the highest priority remaining option.
1807 If several have equal priority, take the first of them. */
1808 for (from = 1; from < argc; from++)
1810 if (argv[from] != 0 && priority[from] > best_priority)
1812 best_priority = priority[from];
1813 best = from;
1815 /* Skip option arguments--they are tied to the options. */
1816 if (options[from] > 0)
1817 from += options[from];
1820 if (best < 0)
1821 emacs_abort ();
1823 /* Copy the highest priority remaining option, with its args, to NEW.
1824 Unless it is a duplicate of the previous one. */
1825 if (! (options[best] == 0
1826 && ! strcmp (new[to - 1], argv[best])))
1828 new[to++] = argv[best];
1829 for (i = 0; i < options[best]; i++)
1830 new[to++] = argv[best + i + 1];
1833 incoming_used += 1 + (options[best] > 0 ? options[best] : 0);
1835 /* Clear out this option in ARGV. */
1836 argv[best] = 0;
1837 for (i = 0; i < options[best]; i++)
1838 argv[best + i + 1] = 0;
1841 /* If duplicate options were deleted, fill up extra space with null ptrs. */
1842 while (to < argc)
1843 new[to++] = 0;
1845 memcpy (argv, new, sizeof (char *) * argc);
1847 xfree (options);
1848 xfree (new);
1849 xfree (priority);
1852 DEFUN ("kill-emacs", Fkill_emacs, Skill_emacs, 0, 1, "P",
1853 doc: /* Exit the Emacs job and kill it.
1854 If ARG is an integer, return ARG as the exit program code.
1855 If ARG is a string, stuff it as keyboard input.
1857 This function is called upon receipt of the signals SIGTERM
1858 or SIGHUP, and upon SIGINT in batch mode.
1860 The value of `kill-emacs-hook', if not void,
1861 is a list of functions (of no args),
1862 all of which are called before Emacs is actually killed. */)
1863 (Lisp_Object arg)
1865 struct gcpro gcpro1;
1866 int exit_code;
1868 GCPRO1 (arg);
1870 if (feof (stdin))
1871 arg = Qt;
1873 /* Fsignal calls emacs_abort () if it sees that waiting_for_input is
1874 set. */
1875 waiting_for_input = 0;
1876 Frun_hooks (1, &Qkill_emacs_hook);
1877 UNGCPRO;
1879 #ifdef HAVE_X_WINDOWS
1880 /* Transfer any clipboards we own to the clipboard manager. */
1881 x_clipboard_manager_save_all ();
1882 #endif
1884 shut_down_emacs (0, STRINGP (arg) ? arg : Qnil);
1886 #ifdef HAVE_NS
1887 ns_release_autorelease_pool (ns_pool);
1888 #endif
1890 /* If we have an auto-save list file,
1891 kill it because we are exiting Emacs deliberately (not crashing).
1892 Do it after shut_down_emacs, which does an auto-save. */
1893 if (STRINGP (Vauto_save_list_file_name))
1895 Lisp_Object listfile;
1896 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
1897 unlink (SSDATA (listfile));
1900 if (INTEGERP (arg))
1901 exit_code = (XINT (arg) < 0
1902 ? XINT (arg) | INT_MIN
1903 : XINT (arg) & INT_MAX);
1904 else
1905 exit_code = EXIT_SUCCESS;
1906 exit (exit_code);
1910 /* Perform an orderly shutdown of Emacs. Autosave any modified
1911 buffers, kill any child processes, clean up the terminal modes (if
1912 we're in the foreground), and other stuff like that. Don't perform
1913 any redisplay; this may be called when Emacs is shutting down in
1914 the background, or after its X connection has died.
1916 If SIG is a signal number, print a message for it.
1918 This is called by fatal signal handlers, X protocol error handlers,
1919 and Fkill_emacs. */
1921 void
1922 shut_down_emacs (int sig, Lisp_Object stuff)
1924 /* Prevent running of hooks from now on. */
1925 Vrun_hooks = Qnil;
1927 /* Don't update display from now on. */
1928 Vinhibit_redisplay = Qt;
1930 /* If we are controlling the terminal, reset terminal modes. */
1931 #ifndef DOS_NT
1933 pid_t pgrp = getpgrp ();
1934 pid_t tpgrp = tcgetpgrp (0);
1935 if ((tpgrp != -1) && tpgrp == pgrp)
1937 reset_all_sys_modes ();
1938 if (sig && sig != SIGTERM)
1940 static char const format[] = "Fatal error %d: ";
1941 char buf[sizeof format - 2 + INT_STRLEN_BOUND (int)];
1942 int buflen = sprintf (buf, format, sig);
1943 char const *sig_desc = safe_strsignal (sig);
1944 emacs_write (STDERR_FILENO, buf, buflen);
1945 emacs_write (STDERR_FILENO, sig_desc, strlen (sig_desc));
1949 #else
1950 fflush (stdout);
1951 reset_all_sys_modes ();
1952 #endif
1954 stuff_buffered_input (stuff);
1956 inhibit_sentinels = 1;
1957 kill_buffer_processes (Qnil);
1958 Fdo_auto_save (Qt, Qnil);
1960 #ifdef CLASH_DETECTION
1961 unlock_all_files ();
1962 #endif
1964 /* There is a tendency for a SIGIO signal to arrive within exit,
1965 and cause a SIGHUP because the input descriptor is already closed. */
1966 unrequest_sigio ();
1967 ignore_sigio ();
1969 /* Do this only if terminating normally, we want glyph matrices
1970 etc. in a core dump. */
1971 if (sig == 0 || sig == SIGTERM)
1973 check_glyph_memory ();
1974 check_message_stack ();
1977 #ifdef MSDOS
1978 dos_cleanup ();
1979 #endif
1981 #ifdef HAVE_NS
1982 ns_term_shutdown (sig);
1983 #endif
1985 #ifdef HAVE_LIBXML2
1986 xml_cleanup_parser ();
1987 #endif
1989 #ifdef WINDOWSNT
1990 term_ntproc (0);
1991 #endif
1996 #ifndef CANNOT_DUMP
1998 #include "unexec.h"
2000 DEFUN ("dump-emacs", Fdump_emacs, Sdump_emacs, 2, 2, 0,
2001 doc: /* Dump current state of Emacs into executable file FILENAME.
2002 Take symbols from SYMFILE (presumably the file you executed to run Emacs).
2003 This is used in the file `loadup.el' when building Emacs.
2005 You must run Emacs in batch mode in order to dump it. */)
2006 (Lisp_Object filename, Lisp_Object symfile)
2008 Lisp_Object tem;
2009 Lisp_Object symbol;
2010 ptrdiff_t count = SPECPDL_INDEX ();
2012 check_pure_size ();
2014 if (! noninteractive)
2015 error ("Dumping Emacs works only in batch mode");
2017 #ifdef GNU_LINUX
2019 /* Warn if the gap between BSS end and heap start is larger than this. */
2020 # define MAX_HEAP_BSS_DIFF (1024*1024)
2022 if (heap_bss_diff > MAX_HEAP_BSS_DIFF)
2024 fprintf (stderr, "**************************************************\n");
2025 fprintf (stderr, "Warning: Your system has a gap between BSS and the\n");
2026 fprintf (stderr, "heap (%"pMu" bytes). This usually means that exec-shield\n",
2027 heap_bss_diff);
2028 fprintf (stderr, "or something similar is in effect. The dump may\n");
2029 fprintf (stderr, "fail because of this. See the section about\n");
2030 fprintf (stderr, "exec-shield in etc/PROBLEMS for more information.\n");
2031 fprintf (stderr, "**************************************************\n");
2033 #endif /* GNU_LINUX */
2035 /* Bind `command-line-processed' to nil before dumping,
2036 so that the dumped Emacs will process its command line
2037 and set up to work with X windows if appropriate. */
2038 symbol = intern ("command-line-processed");
2039 specbind (symbol, Qnil);
2041 CHECK_STRING (filename);
2042 filename = Fexpand_file_name (filename, Qnil);
2043 if (!NILP (symfile))
2045 CHECK_STRING (symfile);
2046 if (SCHARS (symfile))
2047 symfile = Fexpand_file_name (symfile, Qnil);
2050 tem = Vpurify_flag;
2051 Vpurify_flag = Qnil;
2053 #ifdef HAVE_TZSET
2054 set_time_zone_rule (dump_tz);
2055 #ifndef LOCALTIME_CACHE
2056 /* Force a tz reload, since set_time_zone_rule doesn't. */
2057 tzset ();
2058 #endif
2059 #endif
2061 fflush (stdout);
2062 /* Tell malloc where start of impure now is. */
2063 /* Also arrange for warnings when nearly out of space. */
2064 #ifndef SYSTEM_MALLOC
2065 #ifndef WINDOWSNT
2066 /* On Windows, this was done before dumping, and that once suffices.
2067 Meanwhile, my_edata is not valid on Windows. */
2069 extern char my_edata[];
2070 memory_warnings (my_edata, malloc_warning);
2072 #endif /* not WINDOWSNT */
2073 #endif /* not SYSTEM_MALLOC */
2074 #ifdef DOUG_LEA_MALLOC
2075 malloc_state_ptr = malloc_get_state ();
2076 #endif
2078 #ifdef USE_MMAP_FOR_BUFFERS
2079 mmap_set_vars (0);
2080 #endif
2081 unexec (SSDATA (filename), !NILP (symfile) ? SSDATA (symfile) : 0);
2082 #ifdef USE_MMAP_FOR_BUFFERS
2083 mmap_set_vars (1);
2084 #endif
2085 #ifdef DOUG_LEA_MALLOC
2086 free (malloc_state_ptr);
2087 #endif
2089 #ifdef WINDOWSNT
2090 Vlibrary_cache = Qnil;
2091 #endif
2092 #ifdef HAVE_WINDOW_SYSTEM
2093 reset_image_types ();
2094 #endif
2096 Vpurify_flag = tem;
2098 return unbind_to (count, Qnil);
2101 #endif /* not CANNOT_DUMP */
2103 #if HAVE_SETLOCALE
2104 /* Recover from setlocale (LC_ALL, ""). */
2105 void
2106 fixup_locale (void)
2108 /* The Emacs Lisp reader needs LC_NUMERIC to be "C",
2109 so that numbers are read and printed properly for Emacs Lisp. */
2110 setlocale (LC_NUMERIC, "C");
2113 /* Set system locale CATEGORY, with previous locale *PLOCALE, to
2114 DESIRED_LOCALE. */
2115 static void
2116 synchronize_locale (int category, Lisp_Object *plocale, Lisp_Object desired_locale)
2118 if (! EQ (*plocale, desired_locale))
2120 *plocale = desired_locale;
2121 setlocale (category, (STRINGP (desired_locale)
2122 ? SSDATA (desired_locale)
2123 : ""));
2127 /* Set system time locale to match Vsystem_time_locale, if possible. */
2128 void
2129 synchronize_system_time_locale (void)
2131 synchronize_locale (LC_TIME, &Vprevious_system_time_locale,
2132 Vsystem_time_locale);
2135 /* Set system messages locale to match Vsystem_messages_locale, if
2136 possible. */
2137 void
2138 synchronize_system_messages_locale (void)
2140 #ifdef LC_MESSAGES
2141 synchronize_locale (LC_MESSAGES, &Vprevious_system_messages_locale,
2142 Vsystem_messages_locale);
2143 #endif
2145 #endif /* HAVE_SETLOCALE */
2148 Lisp_Object
2149 decode_env_path (const char *evarname, const char *defalt)
2151 const char *path, *p;
2152 Lisp_Object lpath, element, tem;
2153 #ifdef WINDOWSNT
2154 bool defaulted = 0;
2155 const char *emacs_dir = egetenv ("emacs_dir");
2156 static const char *emacs_dir_env = "%emacs_dir%/";
2157 const size_t emacs_dir_len = strlen (emacs_dir_env);
2158 #endif
2160 /* It's okay to use getenv here, because this function is only used
2161 to initialize variables when Emacs starts up, and isn't called
2162 after that. */
2163 if (evarname != 0)
2164 path = getenv (evarname);
2165 else
2166 path = 0;
2167 if (!path)
2169 path = defalt;
2170 #ifdef WINDOWSNT
2171 defaulted = 1;
2172 #endif
2174 #ifdef DOS_NT
2175 /* Ensure values from the environment use the proper directory separator. */
2176 if (path)
2178 char *path_copy = alloca (strlen (path) + 1);
2179 strcpy (path_copy, path);
2180 dostounix_filename (path_copy, 0);
2181 path = path_copy;
2183 #endif
2184 lpath = Qnil;
2185 while (1)
2187 p = strchr (path, SEPCHAR);
2188 if (!p)
2189 p = path + strlen (path);
2190 element = (p - path ? make_string (path, p - path)
2191 : build_string ("."));
2192 #ifdef WINDOWSNT
2193 /* Relative file names in the default path are interpreted as
2194 being relative to $emacs_dir. */
2195 if (emacs_dir && defaulted
2196 && strncmp (path, emacs_dir_env, emacs_dir_len) == 0)
2197 element = Fexpand_file_name (Fsubstring (element,
2198 make_number (emacs_dir_len),
2199 Qnil),
2200 build_string (emacs_dir));
2201 #endif
2203 /* Add /: to the front of the name
2204 if it would otherwise be treated as magic. */
2205 tem = Ffind_file_name_handler (element, Qt);
2207 /* However, if the handler says "I'm safe",
2208 don't bother adding /:. */
2209 if (SYMBOLP (tem))
2211 Lisp_Object prop;
2212 prop = Fget (tem, intern ("safe-magic"));
2213 if (! NILP (prop))
2214 tem = Qnil;
2217 if (! NILP (tem))
2218 element = concat2 (build_string ("/:"), element);
2220 lpath = Fcons (element, lpath);
2221 if (*p)
2222 path = p + 1;
2223 else
2224 break;
2226 return Fnreverse (lpath);
2229 DEFUN ("daemonp", Fdaemonp, Sdaemonp, 0, 0, 0,
2230 doc: /* Return non-nil if the current emacs process is a daemon.
2231 If the daemon was given a name argument, return that name. */)
2232 (void)
2234 if (IS_DAEMON)
2235 if (daemon_name)
2236 return build_string (daemon_name);
2237 else
2238 return Qt;
2239 else
2240 return Qnil;
2243 DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
2244 doc: /* Mark the Emacs daemon as being initialized.
2245 This finishes the daemonization process by doing the other half of detaching
2246 from the parent process and its tty file descriptors. */)
2247 (void)
2249 int nfd;
2250 bool err = 0;
2252 if (!IS_DAEMON)
2253 error ("This function can only be called if emacs is run as a daemon");
2255 if (daemon_pipe[1] < 0)
2256 error ("The daemon has already been initialized");
2258 if (NILP (Vafter_init_time))
2259 error ("This function can only be called after loading the init files");
2261 /* Get rid of stdin, stdout and stderr. */
2262 nfd = emacs_open ("/dev/null", O_RDWR, 0);
2263 err |= nfd < 0;
2264 err |= dup2 (nfd, 0) < 0;
2265 err |= dup2 (nfd, 1) < 0;
2266 err |= dup2 (nfd, 2) < 0;
2267 err |= emacs_close (nfd) != 0;
2269 /* Closing the pipe will notify the parent that it can exit.
2270 FIXME: In case some other process inherited the pipe, closing it here
2271 won't notify the parent because it's still open elsewhere, so we
2272 additionally send a byte, just to make sure the parent really exits.
2273 Instead, we should probably close the pipe in start-process and
2274 call-process to make sure the pipe is never inherited by
2275 subprocesses. */
2276 err |= write (daemon_pipe[1], "\n", 1) < 0;
2277 err |= emacs_close (daemon_pipe[1]) != 0;
2278 /* Set it to an invalid value so we know we've already run this function. */
2279 daemon_pipe[1] = -1;
2281 if (err)
2282 error ("I/O error during daemon initialization");
2283 return Qt;
2286 void
2287 syms_of_emacs (void)
2289 DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
2290 DEFSYM (Qrisky_local_variable, "risky-local-variable");
2291 DEFSYM (Qkill_emacs, "kill-emacs");
2292 DEFSYM (Qkill_emacs_hook, "kill-emacs-hook");
2294 #ifndef CANNOT_DUMP
2295 defsubr (&Sdump_emacs);
2296 #endif
2298 defsubr (&Skill_emacs);
2300 defsubr (&Sinvocation_name);
2301 defsubr (&Sinvocation_directory);
2302 defsubr (&Sdaemonp);
2303 defsubr (&Sdaemon_initialized);
2305 DEFVAR_LISP ("command-line-args", Vcommand_line_args,
2306 doc: /* Args passed by shell to Emacs, as a list of strings.
2307 Many arguments are deleted from the list as they are processed. */);
2309 DEFVAR_LISP ("system-type", Vsystem_type,
2310 doc: /* The value is a symbol indicating the type of operating system you are using.
2311 Special values:
2312 `gnu' compiled for a GNU Hurd system.
2313 `gnu/linux' compiled for a GNU/Linux system.
2314 `gnu/kfreebsd' compiled for a GNU system with a FreeBSD kernel.
2315 `darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
2316 `ms-dos' compiled as an MS-DOS application.
2317 `windows-nt' compiled as a native W32 application.
2318 `cygwin' compiled using the Cygwin library.
2319 Anything else (in Emacs 24.1, the possibilities are: aix, berkeley-unix,
2320 hpux, irix, usg-unix-v) indicates some sort of Unix system. */);
2321 Vsystem_type = intern_c_string (SYSTEM_TYPE);
2322 /* See configure.ac (and config.nt) for the possible SYSTEM_TYPEs. */
2324 DEFVAR_LISP ("system-configuration", Vsystem_configuration,
2325 doc: /* Value is string indicating configuration Emacs was built for.
2326 On MS-Windows, the value reflects the OS flavor and version on which
2327 Emacs is running. */);
2328 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2330 DEFVAR_LISP ("system-configuration-options", Vsystem_configuration_options,
2331 doc: /* String containing the configuration options Emacs was built with. */);
2332 Vsystem_configuration_options = build_string (EMACS_CONFIG_OPTIONS);
2334 DEFVAR_BOOL ("noninteractive", noninteractive1,
2335 doc: /* Non-nil means Emacs is running without interactive terminal. */);
2337 DEFVAR_LISP ("kill-emacs-hook", Vkill_emacs_hook,
2338 doc: /* Hook run when `kill-emacs' is called.
2339 Since `kill-emacs' may be invoked when the terminal is disconnected (or
2340 in other similar situations), functions placed on this hook should not
2341 expect to be able to interact with the user. To ask for confirmation,
2342 see `kill-emacs-query-functions' instead.
2344 Before Emacs 24.1, the hook was not run in batch mode, i.e., if
2345 `noninteractive' was non-nil. */);
2346 Vkill_emacs_hook = Qnil;
2348 DEFVAR_LISP ("path-separator", Vpath_separator,
2349 doc: /* String containing the character that separates directories in
2350 search paths, such as PATH and other similar environment variables. */);
2352 char c = SEPCHAR;
2353 Vpath_separator = make_string (&c, 1);
2356 DEFVAR_LISP ("invocation-name", Vinvocation_name,
2357 doc: /* The program name that was used to run Emacs.
2358 Any directory names are omitted. */);
2360 DEFVAR_LISP ("invocation-directory", Vinvocation_directory,
2361 doc: /* The directory in which the Emacs executable was found, to run it.
2362 The value is nil if that directory's name is not known. */);
2364 DEFVAR_LISP ("installation-directory", Vinstallation_directory,
2365 doc: /* A directory within which to look for the `lib-src' and `etc' directories.
2366 In an installed Emacs, this is normally nil. It is non-nil if
2367 both `lib-src' (on MS-DOS, `info') and `etc' directories are found
2368 within the variable `invocation-directory' or its parent. For example,
2369 this is the case when running an uninstalled Emacs executable from its
2370 build directory. */);
2371 Vinstallation_directory = Qnil;
2373 DEFVAR_LISP ("system-messages-locale", Vsystem_messages_locale,
2374 doc: /* System locale for messages. */);
2375 Vsystem_messages_locale = Qnil;
2377 DEFVAR_LISP ("previous-system-messages-locale",
2378 Vprevious_system_messages_locale,
2379 doc: /* Most recently used system locale for messages. */);
2380 Vprevious_system_messages_locale = Qnil;
2382 DEFVAR_LISP ("system-time-locale", Vsystem_time_locale,
2383 doc: /* System locale for time. */);
2384 Vsystem_time_locale = Qnil;
2386 DEFVAR_LISP ("previous-system-time-locale", Vprevious_system_time_locale,
2387 doc: /* Most recently used system locale for time. */);
2388 Vprevious_system_time_locale = Qnil;
2390 DEFVAR_LISP ("before-init-time", Vbefore_init_time,
2391 doc: /* Value of `current-time' before Emacs begins initialization. */);
2392 Vbefore_init_time = Qnil;
2394 DEFVAR_LISP ("after-init-time", Vafter_init_time,
2395 doc: /* Value of `current-time' after loading the init files.
2396 This is nil during initialization. */);
2397 Vafter_init_time = Qnil;
2399 DEFVAR_BOOL ("inhibit-x-resources", inhibit_x_resources,
2400 doc: /* If non-nil, X resources, Windows Registry settings, and NS defaults are not used. */);
2401 inhibit_x_resources = 0;
2403 DEFVAR_LISP ("emacs-copyright", Vemacs_copyright,
2404 doc: /* Short copyright string for this version of Emacs. */);
2405 Vemacs_copyright = build_string (emacs_copyright);
2407 DEFVAR_LISP ("emacs-version", Vemacs_version,
2408 doc: /* Version numbers of this version of Emacs. */);
2409 Vemacs_version = build_string (emacs_version);
2411 DEFVAR_LISP ("dynamic-library-alist", Vdynamic_library_alist,
2412 doc: /* Alist of dynamic libraries vs external files implementing them.
2413 Each element is a list (LIBRARY FILE...), where the car is a symbol
2414 representing a supported external library, and the rest are strings giving
2415 alternate filenames for that library.
2417 Emacs tries to load the library from the files in the order they appear on
2418 the list; if none is loaded, the running session of Emacs won't have access
2419 to that library.
2421 Note that image types `pbm' and `xbm' do not need entries in this variable
2422 because they do not depend on external libraries and are always available.
2424 Also note that this is not a generic facility for accessing external
2425 libraries; only those already known by Emacs will be loaded. */);
2426 Vdynamic_library_alist = Qnil;
2427 Fput (intern_c_string ("dynamic-library-alist"), Qrisky_local_variable, Qt);
2429 #ifdef WINDOWSNT
2430 Vlibrary_cache = Qnil;
2431 staticpro (&Vlibrary_cache);
2432 #endif
2434 /* Make sure IS_DAEMON starts up as false. */
2435 daemon_pipe[1] = 0;