Move Vlibrary_cache to emacs.c and reset before dumping.
[emacs.git] / src / emacs.c
blob5aae812b869e4273341348fb7f85e72ac52abd6e
1 /* Fully extensible Emacs, running on Unix, intended for GNU.
3 Copyright (C) 1985-1987, 1993-1995, 1997-1999, 2001-2012
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/>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
26 #include <sys/types.h>
27 #include <sys/file.h>
28 #include <unistd.h>
30 #include <ignore-value.h>
32 #include "lisp.h"
34 #ifdef HAVE_WINDOW_SYSTEM
35 #include TERM_HEADER
36 #endif /* HAVE_WINDOW_SYSTEM */
38 #ifdef WINDOWSNT
39 #include <fcntl.h>
40 #include <windows.h> /* just for w32.h */
41 #include "w32.h"
42 #include "w32heap.h" /* for prototype of sbrk */
43 #endif
45 #ifdef NS_IMPL_GNUSTEP
46 /* At least under Debian, GSConfig is in a subdirectory. --Stef */
47 #include <GNUstepBase/GSConfig.h>
48 #endif
50 #include "commands.h"
51 #include "intervals.h"
52 #include "character.h"
53 #include "buffer.h"
54 #include "window.h"
56 #include "systty.h"
57 #include "atimer.h"
58 #include "blockinput.h"
59 #include "syssignal.h"
60 #include "process.h"
61 #include "frame.h"
62 #include "termhooks.h"
63 #include "keyboard.h"
64 #include "keymap.h"
66 #ifdef HAVE_GNUTLS
67 #include "gnutls.h"
68 #endif
70 #if (defined PROFILING \
71 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__))
72 # include <sys/gmon.h>
73 extern void moncontrol (int mode);
74 #endif
76 #ifdef HAVE_SETLOCALE
77 #include <locale.h>
78 #endif
80 #ifdef HAVE_SETRLIMIT
81 #include <sys/time.h>
82 #include <sys/resource.h>
83 #endif
85 #ifdef HAVE_PERSONALITY_LINUX32
86 #include <sys/personality.h>
87 #endif
89 #ifndef O_RDWR
90 #define O_RDWR 2
91 #endif
93 static const char emacs_version[] = VERSION;
94 static const char emacs_copyright[] = COPYRIGHT;
96 /* Empty lisp strings. To avoid having to build any others. */
97 Lisp_Object empty_unibyte_string, empty_multibyte_string;
99 #ifdef WINDOWSNT
100 /* Cache for externally loaded libraries. */
101 Lisp_Object Vlibrary_cache;
102 #endif
104 /* Set after Emacs has started up the first time.
105 Prevents reinitialization of the Lisp world and keymaps
106 on subsequent starts. */
107 bool initialized;
109 #ifdef DARWIN_OS
110 extern void unexec_init_emacs_zone (void);
111 #endif
113 #ifdef DOUG_LEA_MALLOC
114 /* Preserves a pointer to the memory allocated that copies that
115 static data inside glibc's malloc. */
116 static void *malloc_state_ptr;
117 /* From glibc, a routine that returns a copy of the malloc internal state. */
118 extern void *malloc_get_state (void);
119 /* From glibc, a routine that overwrites the malloc internal state. */
120 extern int malloc_set_state (void*);
121 /* True if the MALLOC_CHECK_ environment variable was set while
122 dumping. Used to work around a bug in glibc's malloc. */
123 static bool malloc_using_checking;
124 #endif
126 Lisp_Object Qfile_name_handler_alist;
128 Lisp_Object Qrisky_local_variable;
130 Lisp_Object Qkill_emacs;
132 /* If true, Emacs should not attempt to use a window-specific code,
133 but instead should use the virtual terminal under which it was started. */
134 bool inhibit_window_system;
136 /* If true, a filter or a sentinel is running. Tested to save the match
137 data on the first attempt to change it inside asynchronous code. */
138 bool running_asynch_code;
140 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NS)
141 /* If true, -d was specified, meaning we're using some window system. */
142 bool display_arg;
143 #endif
145 /* An address near the bottom of the stack.
146 Tells GC how to save a copy of the stack. */
147 char *stack_bottom;
149 #if defined (DOUG_LEA_MALLOC) || defined (GNU_LINUX)
150 /* The address where the heap starts (from the first sbrk (0) call). */
151 static void *my_heap_start;
152 #endif
154 #ifdef GNU_LINUX
155 /* The gap between BSS end and heap start as far as we can tell. */
156 static uprintmax_t heap_bss_diff;
157 #endif
159 /* True means running Emacs without interactive terminal. */
160 bool noninteractive;
162 /* True means remove site-lisp directories from load-path. */
163 bool no_site_lisp;
165 /* Name for the server started by the daemon.*/
166 static char *daemon_name;
168 /* Pipe used to send exit notification to the daemon parent at
169 startup. */
170 int daemon_pipe[2];
172 /* Save argv and argc. */
173 char **initial_argv;
174 int initial_argc;
176 static void sort_args (int argc, char **argv);
177 static void syms_of_emacs (void);
179 /* MSVC needs each string be shorter than 2048 bytes, so the usage
180 strings below are split to not overflow this limit. */
181 #define USAGE1 "\
182 Usage: %s [OPTION-OR-FILENAME]...\n\
184 Run Emacs, the extensible, customizable, self-documenting real-time\n\
185 display editor. The recommended way to start Emacs for normal editing\n\
186 is with no options at all.\n\
188 Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n\
189 read the main documentation for these command-line arguments.\n\
191 Initialization options:\n\
193 --batch do not do interactive display; implies -q\n\
194 --chdir DIR change to directory DIR\n\
195 --daemon start a server in the background\n\
196 --debug-init enable Emacs Lisp debugger for init file\n\
197 --display, -d DISPLAY use X server DISPLAY\n\
198 --no-desktop do not load a saved desktop\n\
199 --no-init-file, -q load neither ~/.emacs nor default.el\n\
200 --no-shared-memory, -nl do not use shared memory\n\
201 --no-site-file do not load site-start.el\n\
202 --no-site-lisp, -nsl do not add site-lisp directories to load-path\n\
203 --no-splash do not display a splash screen on startup\n\
204 --no-window-system, -nw do not communicate with X, ignoring $DISPLAY\n\
205 --quick, -Q equivalent to:\n\
206 -q --no-site-file --no-site-lisp --no-splash\n\
207 --script FILE run FILE as an Emacs Lisp script\n\
208 --terminal, -t DEVICE use DEVICE for terminal I/O\n\
209 --user, -u USER load ~USER/.emacs instead of your own\n\
210 \n%s"
212 #define USAGE2 "\
213 Action options:\n\
215 FILE visit FILE using find-file\n\
216 +LINE go to line LINE in next FILE\n\
217 +LINE:COLUMN go to line LINE, column COLUMN, in next FILE\n\
218 --directory, -L DIR add DIR to variable load-path\n\
219 --eval EXPR evaluate Emacs Lisp expression EXPR\n\
220 --execute EXPR evaluate Emacs Lisp expression EXPR\n\
221 --file FILE visit FILE using find-file\n\
222 --find-file FILE visit FILE using find-file\n\
223 --funcall, -f FUNC call Emacs Lisp function FUNC with no arguments\n\
224 --insert FILE insert contents of FILE into current buffer\n\
225 --kill exit without asking for confirmation\n\
226 --load, -l FILE load Emacs Lisp FILE using the load function\n\
227 --visit FILE visit FILE using find-file\n\
230 #define USAGE3 "\
231 Display options:\n\
233 --background-color, -bg COLOR window background color\n\
234 --basic-display, -D disable many display features;\n\
235 used for debugging Emacs\n\
236 --border-color, -bd COLOR main border color\n\
237 --border-width, -bw WIDTH width of main border\n\
238 --color, --color=MODE override color mode for character terminals;\n\
239 MODE defaults to `auto', and\n\
240 can also be `never', `always',\n\
241 or a mode name like `ansi8'\n\
242 --cursor-color, -cr COLOR color of the Emacs cursor indicating point\n\
243 --font, -fn FONT default font; must be fixed-width\n\
244 --foreground-color, -fg COLOR window foreground color\n\
245 --fullheight, -fh make the first frame high as the screen\n\
246 --fullscreen, -fs make the first frame fullscreen\n\
247 --fullwidth, -fw make the first frame wide as the screen\n\
248 --maximized, -mm make the first frame maximized\n\
249 --geometry, -g GEOMETRY window geometry\n\
250 --no-bitmap-icon, -nbi do not use picture of gnu for Emacs icon\n\
251 --iconic start Emacs in iconified state\n\
252 --internal-border, -ib WIDTH width between text and main border\n\
253 --line-spacing, -lsp PIXELS additional space to put between lines\n\
254 --mouse-color, -ms COLOR mouse cursor color in Emacs window\n\
255 --name NAME title for initial Emacs frame\n\
256 --no-blinking-cursor, -nbc disable blinking cursor\n\
257 --reverse-video, -r, -rv switch foreground and background\n\
258 --title, -T TITLE title for initial Emacs frame\n\
259 --vertical-scroll-bars, -vb enable vertical scroll bars\n\
260 --xrm XRESOURCES set additional X resources\n\
261 --parent-id XID set parent window\n\
262 --help display this help and exit\n\
263 --version output version information and exit\n\
266 #define USAGE4 "\
267 You can generally also specify long option names with a single -; for\n\
268 example, -batch as well as --batch. You can use any unambiguous\n\
269 abbreviation for a --option.\n\
271 Various environment variables and window system resources also affect\n\
272 Emacs' operation. See the main documentation.\n\
274 Report bugs to bug-gnu-emacs@gnu.org. First, please see the Bugs\n\
275 section of the Emacs manual or the file BUGS.\n"
278 /* True if handling a fatal error already. */
279 bool fatal_error_in_progress;
281 #ifdef HAVE_NS
282 /* NS autrelease pool, for memory management. */
283 static void *ns_pool;
284 #endif
288 /* Report a fatal error due to signal SIG, output a backtrace of at
289 most BACKTRACE_LIMIT lines, and exit. */
290 _Noreturn void
291 terminate_due_to_signal (int sig, int backtrace_limit)
293 signal (sig, SIG_DFL);
294 totally_unblock_input ();
296 /* If fatal error occurs in code below, avoid infinite recursion. */
297 if (! fatal_error_in_progress)
299 fatal_error_in_progress = 1;
301 if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT)
302 Fkill_emacs (make_number (sig));
304 shut_down_emacs (sig, Qnil);
305 emacs_backtrace (backtrace_limit);
308 /* Signal the same code; this time it will really be fatal.
309 Since we're in a signal handler, the signal is blocked, so we
310 have to unblock it if we want to really receive it. */
311 #ifndef MSDOS
313 sigset_t unblocked;
314 sigemptyset (&unblocked);
315 sigaddset (&unblocked, sig);
316 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
318 #endif
320 emacs_raise (sig);
322 /* This shouldn't be executed, but it prevents a warning. */
323 exit (1);
326 #ifdef SIGDANGER
328 /* Handler for SIGDANGER. */
329 static void
330 handle_danger_signal (int sig)
332 malloc_warning ("Operating system warns that virtual memory is running low.\n");
334 /* It might be unsafe to call do_auto_save now. */
335 force_auto_save_soon ();
338 static void
339 deliver_danger_signal (int sig)
341 deliver_process_signal (sig, handle_danger_signal);
343 #endif
345 /* Code for dealing with Lisp access to the Unix command line. */
347 static void
348 init_cmdargs (int argc, char **argv, int skip_args)
350 register int i;
351 Lisp_Object name, dir, handler;
352 ptrdiff_t count = SPECPDL_INDEX ();
353 Lisp_Object raw_name;
355 initial_argv = argv;
356 initial_argc = argc;
358 raw_name = build_string (argv[0]);
360 /* Add /: to the front of the name
361 if it would otherwise be treated as magic. */
362 handler = Ffind_file_name_handler (raw_name, Qt);
363 if (! NILP (handler))
364 raw_name = concat2 (build_string ("/:"), raw_name);
366 Vinvocation_name = Ffile_name_nondirectory (raw_name);
367 Vinvocation_directory = Ffile_name_directory (raw_name);
369 /* If we got no directory in argv[0], search PATH to find where
370 Emacs actually came from. */
371 if (NILP (Vinvocation_directory))
373 Lisp_Object found;
374 int yes = openp (Vexec_path, Vinvocation_name,
375 Vexec_suffixes, &found, make_number (X_OK));
376 if (yes == 1)
378 /* Add /: to the front of the name
379 if it would otherwise be treated as magic. */
380 handler = Ffind_file_name_handler (found, Qt);
381 if (! NILP (handler))
382 found = concat2 (build_string ("/:"), found);
383 Vinvocation_directory = Ffile_name_directory (found);
387 if (!NILP (Vinvocation_directory)
388 && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
389 /* Emacs was started with relative path, like ./emacs.
390 Make it absolute. */
391 Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, Qnil);
393 Vinstallation_directory = Qnil;
395 if (!NILP (Vinvocation_directory))
397 dir = Vinvocation_directory;
398 #ifdef WINDOWSNT
399 /* If we are running from the build directory, set DIR to the
400 src subdirectory of the Emacs tree, like on Posix
401 platforms. */
402 if (SBYTES (dir) > sizeof ("/i386/") - 1
403 && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
404 "/i386/"))
405 dir = Fexpand_file_name (build_string ("../.."), dir);
406 #else /* !WINDOWSNT */
407 #endif
408 name = Fexpand_file_name (Vinvocation_name, dir);
409 while (1)
411 Lisp_Object tem, lib_src_exists;
412 Lisp_Object etc_exists, info_exists;
414 /* See if dir contains subdirs for use by Emacs.
415 Check for the ones that would exist in a build directory,
416 not including lisp and info. */
417 tem = Fexpand_file_name (build_string ("lib-src"), dir);
418 lib_src_exists = Ffile_exists_p (tem);
420 #ifdef MSDOS
421 /* MSDOS installations frequently remove lib-src, but we still
422 must set installation-directory, or else info won't find
423 its files (it uses the value of installation-directory). */
424 tem = Fexpand_file_name (build_string ("info"), dir);
425 info_exists = Ffile_exists_p (tem);
426 #else
427 info_exists = Qnil;
428 #endif
430 if (!NILP (lib_src_exists) || !NILP (info_exists))
432 tem = Fexpand_file_name (build_string ("etc"), dir);
433 etc_exists = Ffile_exists_p (tem);
434 if (!NILP (etc_exists))
436 Vinstallation_directory
437 = Ffile_name_as_directory (dir);
438 break;
442 /* See if dir's parent contains those subdirs. */
443 tem = Fexpand_file_name (build_string ("../lib-src"), dir);
444 lib_src_exists = Ffile_exists_p (tem);
447 #ifdef MSDOS
448 /* See the MSDOS commentary above. */
449 tem = Fexpand_file_name (build_string ("../info"), dir);
450 info_exists = Ffile_exists_p (tem);
451 #else
452 info_exists = Qnil;
453 #endif
455 if (!NILP (lib_src_exists) || !NILP (info_exists))
457 tem = Fexpand_file_name (build_string ("../etc"), dir);
458 etc_exists = Ffile_exists_p (tem);
459 if (!NILP (etc_exists))
461 tem = Fexpand_file_name (build_string (".."), dir);
462 Vinstallation_directory
463 = Ffile_name_as_directory (tem);
464 break;
468 /* If the Emacs executable is actually a link,
469 next try the dir that the link points into. */
470 tem = Ffile_symlink_p (name);
471 if (!NILP (tem))
473 name = Fexpand_file_name (tem, dir);
474 dir = Ffile_name_directory (name);
476 else
477 break;
481 Vcommand_line_args = Qnil;
483 for (i = argc - 1; i >= 0; i--)
485 if (i == 0 || i > skip_args)
486 /* For the moment, we keep arguments as is in unibyte strings.
487 They are decoded in the function command-line after we know
488 locale-coding-system. */
489 Vcommand_line_args
490 = Fcons (make_unibyte_string (argv[i], strlen (argv[i])),
491 Vcommand_line_args);
494 unbind_to (count, Qnil);
497 DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
498 doc: /* Return the program name that was used to run Emacs.
499 Any directory names are omitted. */)
500 (void)
502 return Fcopy_sequence (Vinvocation_name);
505 DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
506 0, 0, 0,
507 doc: /* Return the directory name in which the Emacs executable was located. */)
508 (void)
510 return Fcopy_sequence (Vinvocation_directory);
514 #ifdef HAVE_TZSET
515 /* A valid but unlikely value for the TZ environment value.
516 It is OK (though a bit slower) if the user actually chooses this value. */
517 static char dump_tz[] = "UtC0";
518 #endif
520 #ifndef ORDINARY_LINK
521 /* We don't include crtbegin.o and crtend.o in the link,
522 so these functions and variables might be missed.
523 Provide dummy definitions to avoid error.
524 (We don't have any real constructors or destructors.) */
525 #ifdef __GNUC__
527 /* Define a dummy function F. Declare F too, to pacify gcc
528 -Wmissing-prototypes. */
529 #define DEFINE_DUMMY_FUNCTION(f) \
530 void f (void) ATTRIBUTE_CONST EXTERNALLY_VISIBLE; void f (void) {}
532 #ifndef GCC_CTORS_IN_LIBC
533 DEFINE_DUMMY_FUNCTION (__do_global_ctors)
534 DEFINE_DUMMY_FUNCTION (__do_global_ctors_aux)
535 DEFINE_DUMMY_FUNCTION (__do_global_dtors)
536 /* GNU/Linux has a bug in its library; avoid an error. */
537 #ifndef GNU_LINUX
538 char * __CTOR_LIST__[2] EXTERNALLY_VISIBLE = { (char *) (-1), 0 };
539 #endif
540 char * __DTOR_LIST__[2] EXTERNALLY_VISIBLE = { (char *) (-1), 0 };
541 #endif /* GCC_CTORS_IN_LIBC */
542 DEFINE_DUMMY_FUNCTION (__main)
543 #endif /* __GNUC__ */
544 #endif /* ORDINARY_LINK */
546 /* Test whether the next argument in ARGV matches SSTR or a prefix of
547 LSTR (at least MINLEN characters). If so, then if VALPTR is non-null
548 (the argument is supposed to have a value) store in *VALPTR either
549 the next argument or the portion of this one after the equal sign.
550 ARGV is read starting at position *SKIPPTR; this index is advanced
551 by the number of arguments used.
553 Too bad we can't just use getopt for all of this, but we don't have
554 enough information to do it right. */
556 static bool
557 argmatch (char **argv, int argc, const char *sstr, const char *lstr,
558 int minlen, char **valptr, int *skipptr)
560 char *p = NULL;
561 ptrdiff_t arglen;
562 char *arg;
564 /* Don't access argv[argc]; give up in advance. */
565 if (argc <= *skipptr + 1)
566 return 0;
568 arg = argv[*skipptr+1];
569 if (arg == NULL)
570 return 0;
571 if (strcmp (arg, sstr) == 0)
573 if (valptr != NULL)
575 *valptr = argv[*skipptr+2];
576 *skipptr += 2;
578 else
579 *skipptr += 1;
580 return 1;
582 arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
583 ? p - arg : strlen (arg));
584 if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
585 return 0;
586 else if (valptr == NULL)
588 *skipptr += 1;
589 return 1;
591 else if (p != NULL)
593 *valptr = p+1;
594 *skipptr += 1;
595 return 1;
597 else if (argv[*skipptr+2] != NULL)
599 *valptr = argv[*skipptr+2];
600 *skipptr += 2;
601 return 1;
603 else
605 return 0;
609 #ifdef DOUG_LEA_MALLOC
611 /* malloc can be invoked even before main (e.g. by the dynamic
612 linker), so the dumped malloc state must be restored as early as
613 possible using this special hook. */
615 static void
616 malloc_initialize_hook (void)
618 if (initialized)
620 if (!malloc_using_checking)
621 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
622 ignored if the heap to be restored was constructed without
623 malloc checking. Can't use unsetenv, since that calls malloc. */
625 char **p;
627 for (p = environ; p && *p; p++)
628 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
631 *p = p[1];
632 while (*++p);
633 break;
637 malloc_set_state (malloc_state_ptr);
638 #ifndef XMALLOC_OVERRUN_CHECK
639 free (malloc_state_ptr);
640 #endif
642 else
644 if (my_heap_start == 0)
645 my_heap_start = sbrk (0);
646 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
650 void (*__malloc_initialize_hook) (void) EXTERNALLY_VISIBLE = malloc_initialize_hook;
652 #endif /* DOUG_LEA_MALLOC */
655 /* ARGSUSED */
657 main (int argc, char **argv)
659 #if GC_MARK_STACK
660 Lisp_Object dummy;
661 #endif
662 char stack_bottom_variable;
663 bool do_initial_setlocale;
664 bool dumping;
665 int skip_args = 0;
666 #ifdef HAVE_SETRLIMIT
667 struct rlimit rlim;
668 #endif
669 bool no_loadup = 0;
670 char *junk = 0;
671 char *dname_arg = 0;
672 #ifdef NS_IMPL_COCOA
673 char dname_arg2[80];
674 #endif
675 char *ch_to_dir;
677 #if GC_MARK_STACK
678 stack_base = &dummy;
679 #endif
681 #if defined (USE_GTK) && defined (G_SLICE_ALWAYS_MALLOC)
682 /* This is used by the Cygwin build. */
683 setenv ("G_SLICE", "always-malloc", 1);
684 #endif
686 #ifdef GNU_LINUX
687 if (!initialized)
689 extern char my_endbss[];
690 extern char *my_endbss_static;
692 if (my_heap_start == 0)
693 my_heap_start = sbrk (0);
695 heap_bss_diff = (char *)my_heap_start - max (my_endbss, my_endbss_static);
697 #endif
699 #ifdef RUN_TIME_REMAP
700 if (initialized)
701 run_time_remap (argv[0]);
702 #endif
704 /* If using unexmacosx.c (set by s/darwin.h), we must do this. */
705 #ifdef DARWIN_OS
706 if (!initialized)
707 unexec_init_emacs_zone ();
708 #endif
710 sort_args (argc, argv);
711 argc = 0;
712 while (argv[argc]) argc++;
714 if (argmatch (argv, argc, "-version", "--version", 3, NULL, &skip_args))
716 const char *version, *copyright;
717 if (initialized)
719 Lisp_Object tem, tem2;
720 tem = Fsymbol_value (intern_c_string ("emacs-version"));
721 tem2 = Fsymbol_value (intern_c_string ("emacs-copyright"));
722 if (!STRINGP (tem))
724 fprintf (stderr, "Invalid value of `emacs-version'\n");
725 exit (1);
727 if (!STRINGP (tem2))
729 fprintf (stderr, "Invalid value of `emacs-copyright'\n");
730 exit (1);
732 else
734 version = SSDATA (tem);
735 copyright = SSDATA (tem2);
738 else
740 version = emacs_version;
741 copyright = emacs_copyright;
743 printf ("GNU Emacs %s\n", version);
744 printf ("%s\n", copyright);
745 printf ("GNU Emacs comes with ABSOLUTELY NO WARRANTY.\n");
746 printf ("You may redistribute copies of Emacs\n");
747 printf ("under the terms of the GNU General Public License.\n");
748 printf ("For more information about these matters, ");
749 printf ("see the file named COPYING.\n");
750 exit (0);
753 if (argmatch (argv, argc, "-chdir", "--chdir", 4, &ch_to_dir, &skip_args))
754 if (chdir (ch_to_dir) == -1)
756 fprintf (stderr, "%s: Can't chdir to %s: %s\n",
757 argv[0], ch_to_dir, strerror (errno));
758 exit (1);
761 dumping = !initialized && (strcmp (argv[argc - 1], "dump") == 0
762 || strcmp (argv[argc - 1], "bootstrap") == 0);
764 #ifdef HAVE_PERSONALITY_LINUX32
765 if (dumping && ! getenv ("EMACS_HEAP_EXEC"))
767 static char heapexec[] = "EMACS_HEAP_EXEC=true";
768 /* Set this so we only do this once. */
769 putenv (heapexec);
771 /* A flag to turn off address randomization which is introduced
772 in linux kernel shipped with fedora core 4 */
773 #define ADD_NO_RANDOMIZE 0x0040000
774 personality (PER_LINUX32 | ADD_NO_RANDOMIZE);
775 #undef ADD_NO_RANDOMIZE
777 execvp (argv[0], argv);
779 /* If the exec fails, try to dump anyway. */
780 perror ("execvp");
782 #endif /* HAVE_PERSONALITY_LINUX32 */
784 #if defined (HAVE_SETRLIMIT) && defined (RLIMIT_STACK)
785 /* Extend the stack space available.
786 Don't do that if dumping, since some systems (e.g. DJGPP)
787 might define a smaller stack limit at that time. */
788 if (1
789 #ifndef CANNOT_DUMP
790 && (!noninteractive || initialized)
791 #endif
792 && !getrlimit (RLIMIT_STACK, &rlim))
794 long newlim;
795 extern size_t re_max_failures;
796 /* Approximate the amount regex.c needs per unit of re_max_failures. */
797 int ratio = 20 * sizeof (char *);
798 /* Then add 33% to cover the size of the smaller stacks that regex.c
799 successively allocates and discards, on its way to the maximum. */
800 ratio += ratio / 3;
801 /* Add in some extra to cover
802 what we're likely to use for other reasons. */
803 newlim = re_max_failures * ratio + 200000;
804 #ifdef __NetBSD__
805 /* NetBSD (at least NetBSD 1.2G and former) has a bug in its
806 stack allocation routine for new process that the allocation
807 fails if stack limit is not on page boundary. So, round up the
808 new limit to page boundary. */
809 newlim = (newlim + getpagesize () - 1) / getpagesize () * getpagesize ();
810 #endif
811 if (newlim > rlim.rlim_max)
813 newlim = rlim.rlim_max;
814 /* Don't let regex.c overflow the stack we have. */
815 re_max_failures = (newlim - 200000) / ratio;
817 if (rlim.rlim_cur < newlim)
818 rlim.rlim_cur = newlim;
820 setrlimit (RLIMIT_STACK, &rlim);
822 #endif /* HAVE_SETRLIMIT and RLIMIT_STACK */
824 /* Record (approximately) where the stack begins. */
825 stack_bottom = &stack_bottom_variable;
827 clearerr (stdin);
829 #ifndef SYSTEM_MALLOC
830 /* Arrange to get warning messages as memory fills up. */
831 memory_warnings (0, malloc_warning);
833 /* Call malloc at least once, to run malloc_initialize_hook.
834 Also call realloc and free for consistency. */
835 free (realloc (malloc (4), 4));
837 #endif /* not SYSTEM_MALLOC */
839 #if defined (MSDOS) || defined (WINDOWSNT)
840 /* We do all file input/output as binary files. When we need to translate
841 newlines, we do that manually. */
842 _fmode = O_BINARY;
843 #endif /* MSDOS || WINDOWSNT */
845 #ifdef MSDOS
846 if (!isatty (fileno (stdin)))
847 setmode (fileno (stdin), O_BINARY);
848 if (!isatty (fileno (stdout)))
850 fflush (stdout);
851 setmode (fileno (stdout), O_BINARY);
853 #endif /* MSDOS */
855 /* Skip initial setlocale if LC_ALL is "C", as it's not needed in that case.
856 The build procedure uses this while dumping, to ensure that the
857 dumped Emacs does not have its system locale tables initialized,
858 as that might cause screwups when the dumped Emacs starts up. */
860 char *lc_all = getenv ("LC_ALL");
861 do_initial_setlocale = ! lc_all || strcmp (lc_all, "C");
864 /* Set locale now, so that initial error messages are localized properly.
865 fixup_locale must wait until later, since it builds strings. */
866 if (do_initial_setlocale)
867 setlocale (LC_ALL, "");
869 inhibit_window_system = 0;
871 /* Handle the -t switch, which specifies filename to use as terminal. */
872 while (1)
874 char *term;
875 if (argmatch (argv, argc, "-t", "--terminal", 4, &term, &skip_args))
877 int result;
878 emacs_close (0);
879 emacs_close (1);
880 result = emacs_open (term, O_RDWR, 0);
881 if (result < 0 || dup (0) < 0)
883 char *errstring = strerror (errno);
884 fprintf (stderr, "%s: %s: %s\n", argv[0], term, errstring);
885 exit (1);
887 if (! isatty (0))
889 fprintf (stderr, "%s: %s: not a tty\n", argv[0], term);
890 exit (1);
892 fprintf (stderr, "Using %s\n", term);
893 #ifdef HAVE_WINDOW_SYSTEM
894 inhibit_window_system = 1; /* -t => -nw */
895 #endif
897 else
898 break;
901 /* Command line option --no-windows is deprecated and thus not mentioned
902 in the manual and usage information. */
903 if (argmatch (argv, argc, "-nw", "--no-window-system", 6, NULL, &skip_args)
904 || argmatch (argv, argc, "-nw", "--no-windows", 6, NULL, &skip_args))
905 inhibit_window_system = 1;
907 /* Handle the -batch switch, which means don't do interactive display. */
908 noninteractive = 0;
909 if (argmatch (argv, argc, "-batch", "--batch", 5, NULL, &skip_args))
911 noninteractive = 1;
912 Vundo_outer_limit = Qnil;
914 if (argmatch (argv, argc, "-script", "--script", 3, &junk, &skip_args))
916 noninteractive = 1; /* Set batch mode. */
917 /* Convert --script to -scriptload, un-skip it, and sort again
918 so that it will be handled in proper sequence. */
919 /* FIXME broken for --script=FILE - is that supposed to work? */
920 argv[skip_args - 1] = (char *) "-scriptload";
921 skip_args -= 2;
922 sort_args (argc, argv);
925 /* Handle the --help option, which gives a usage message. */
926 if (argmatch (argv, argc, "-help", "--help", 3, NULL, &skip_args))
928 printf (USAGE1, argv[0], USAGE2);
929 printf (USAGE3);
930 printf (USAGE4);
931 exit (0);
934 if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
935 || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
937 #ifndef DOS_NT
938 pid_t f;
940 /* Start as a daemon: fork a new child process which will run the
941 rest of the initialization code, then exit.
943 Detaching a daemon requires the following steps:
944 - fork
945 - setsid
946 - exit the parent
947 - close the tty file-descriptors
949 We only want to do the last 2 steps once the daemon is ready to
950 serve requests, i.e. after loading .emacs (initialization).
951 OTOH initialization may start subprocesses (e.g. ispell) and these
952 should be run from the proper process (the one that will end up
953 running as daemon) and with the proper "session id" in order for
954 them to keep working after detaching, so fork and setsid need to be
955 performed before initialization.
957 We want to avoid exiting before the server socket is ready, so
958 use a pipe for synchronization. The parent waits for the child
959 to close its end of the pipe (using `daemon-initialized')
960 before exiting. */
961 if (pipe (daemon_pipe) == -1)
963 fprintf (stderr, "Cannot pipe!\n");
964 exit (1);
967 #ifndef NS_IMPL_COCOA
968 #ifdef USE_GTK
969 fprintf (stderr, "\nWarning: due to a long standing Gtk+ bug\nhttp://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
970 Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.\n\
971 Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.\n");
972 #endif
973 f = fork ();
974 #else /* NS_IMPL_COCOA */
975 /* Under Cocoa we must do fork+exec as CoreFoundation lib fails in
976 forked process: http://developer.apple.com/ReleaseNotes/
977 CoreFoundation/CoreFoundation.html)
978 We mark being in the exec'd process by a daemon name argument of
979 form "--daemon=\nFD0,FD1\nNAME" where FD are the pipe file descriptors,
980 NAME is the original daemon name, if any. */
981 if (!dname_arg || !strchr (dname_arg, '\n'))
982 f = fork (); /* in orig */
983 else
984 f = 0; /* in exec'd */
985 #endif /* NS_IMPL_COCOA */
986 if (f > 0)
988 int retval;
989 char buf[1];
991 /* Close unused writing end of the pipe. */
992 close (daemon_pipe[1]);
994 /* Just wait for the child to close its end of the pipe. */
997 retval = read (daemon_pipe[0], &buf, 1);
999 while (retval == -1 && errno == EINTR);
1001 if (retval < 0)
1003 fprintf (stderr, "Error reading status from child\n");
1004 exit (1);
1006 else if (retval == 0)
1008 fprintf (stderr, "Error: server did not start correctly\n");
1009 exit (1);
1012 close (daemon_pipe[0]);
1013 exit (0);
1015 if (f < 0)
1017 fprintf (stderr, "Cannot fork!\n");
1018 exit (1);
1021 #ifdef NS_IMPL_COCOA
1023 /* In orig process, forked as child, OR in exec'd. */
1024 if (!dname_arg || !strchr (dname_arg, '\n'))
1025 { /* In orig, child: now exec w/special daemon name. */
1026 char fdStr[80];
1027 int fdStrlen =
1028 snprintf (fdStr, sizeof fdStr,
1029 "--daemon=\n%d,%d\n%s", daemon_pipe[0],
1030 daemon_pipe[1], dname_arg ? dname_arg : "");
1032 if (! (0 <= fdStrlen && fdStrlen < sizeof fdStr))
1034 fprintf (stderr, "daemon: child name too long\n");
1035 exit (1);
1038 argv[skip_args] = fdStr;
1040 execv (argv[0], argv);
1041 fprintf (stderr, "emacs daemon: exec failed: %d\n", errno);
1042 exit (1);
1045 /* In exec'd: parse special dname into pipe and name info. */
1046 if (!dname_arg || !strchr (dname_arg, '\n')
1047 || strlen (dname_arg) < 1 || strlen (dname_arg) > 70)
1049 fprintf (stderr, "emacs daemon: daemon name absent or too long\n");
1050 exit (1);
1052 dname_arg2[0] = '\0';
1053 sscanf (dname_arg, "\n%d,%d\n%s", &(daemon_pipe[0]), &(daemon_pipe[1]),
1054 dname_arg2);
1055 dname_arg = *dname_arg2 ? dname_arg2 : NULL;
1057 #endif /* NS_IMPL_COCOA */
1059 if (dname_arg)
1060 daemon_name = xstrdup (dname_arg);
1061 /* Close unused reading end of the pipe. */
1062 close (daemon_pipe[0]);
1063 /* Make sure that the used end of the pipe is closed on exec, so
1064 that it is not accessible to programs started from .emacs. */
1065 fcntl (daemon_pipe[1], F_SETFD, FD_CLOEXEC);
1067 #ifdef HAVE_SETSID
1068 setsid ();
1069 #endif
1070 #else /* DOS_NT */
1071 fprintf (stderr, "This platform does not support the -daemon flag.\n");
1072 exit (1);
1073 #endif /* DOS_NT */
1076 if (! noninteractive)
1078 #if defined (USG5) && defined (INTERRUPT_INPUT)
1079 setpgrp ();
1080 #endif
1081 #if defined (HAVE_PTHREAD) && !defined (SYSTEM_MALLOC) && !defined (DOUG_LEA_MALLOC)
1083 extern void malloc_enable_thread (void);
1085 malloc_enable_thread ();
1087 #endif
1090 init_signals (dumping);
1092 noninteractive1 = noninteractive;
1094 /* Perform basic initializations (not merely interning symbols). */
1096 if (!initialized)
1098 init_alloc_once ();
1099 init_obarray ();
1100 init_eval_once ();
1101 init_charset_once ();
1102 init_coding_once ();
1103 init_syntax_once (); /* Create standard syntax table. */
1104 init_category_once (); /* Create standard category table. */
1105 /* Must be done before init_buffer. */
1106 init_casetab_once ();
1107 init_buffer_once (); /* Create buffer table and some buffers. */
1108 init_minibuf_once (); /* Create list of minibuffers. */
1109 /* Must precede init_window_once. */
1111 /* Call syms_of_xfaces before init_window_once because that
1112 function creates Vterminal_frame. Termcap frames now use
1113 faces, and the face implementation uses some symbols as
1114 face names. */
1115 syms_of_xfaces ();
1116 /* XXX syms_of_keyboard uses some symbols in keymap.c. It would
1117 be better to arrange things not to have this dependency. */
1118 syms_of_keymap ();
1119 /* Call syms_of_keyboard before init_window_once because
1120 keyboard sets up symbols that include some face names that
1121 the X support will want to use. This can happen when
1122 CANNOT_DUMP is defined. */
1123 syms_of_keyboard ();
1125 /* Called before syms_of_fileio, because it sets up Qerror_condition. */
1126 syms_of_data ();
1127 syms_of_fileio ();
1128 /* Before syms_of_coding to initialize Vgc_cons_threshold. */
1129 syms_of_alloc ();
1130 /* Before syms_of_coding because it initializes Qcharsetp. */
1131 syms_of_charset ();
1132 /* Before init_window_once, because it sets up the
1133 Vcoding_system_hash_table. */
1134 syms_of_coding (); /* This should be after syms_of_fileio. */
1136 init_window_once (); /* Init the window system. */
1137 #ifdef HAVE_WINDOW_SYSTEM
1138 init_fringe_once (); /* Swap bitmaps if necessary. */
1139 #endif /* HAVE_WINDOW_SYSTEM */
1142 init_alloc ();
1144 if (do_initial_setlocale)
1146 fixup_locale ();
1147 Vsystem_messages_locale = Vprevious_system_messages_locale;
1148 Vsystem_time_locale = Vprevious_system_time_locale;
1151 init_eval ();
1152 init_atimer ();
1153 running_asynch_code = 0;
1154 init_random ();
1156 no_loadup
1157 = argmatch (argv, argc, "-nl", "--no-loadup", 6, NULL, &skip_args);
1159 no_site_lisp
1160 = argmatch (argv, argc, "-nsl", "--no-site-lisp", 11, NULL, &skip_args);
1162 #ifdef HAVE_NS
1163 ns_pool = ns_alloc_autorelease_pool ();
1164 if (!noninteractive)
1166 #ifdef NS_IMPL_COCOA
1167 if (skip_args < argc)
1169 /* FIXME: Do the right thing if getenv returns NULL, or if
1170 chdir fails. */
1171 if (!strncmp (argv[skip_args], "-psn", 4))
1173 skip_args += 1;
1174 chdir (getenv ("HOME"));
1176 else if (skip_args+1 < argc && !strncmp (argv[skip_args+1], "-psn", 4))
1178 skip_args += 2;
1179 chdir (getenv ("HOME"));
1182 #endif /* COCOA */
1184 #endif /* HAVE_NS */
1186 #ifdef HAVE_X_WINDOWS
1187 /* Stupid kludge to catch command-line display spec. We can't
1188 handle this argument entirely in window system dependent code
1189 because we don't even know which window system dependent code
1190 to run until we've recognized this argument. */
1192 char *displayname = 0;
1193 int count_before = skip_args;
1195 /* Skip any number of -d options, but only use the last one. */
1196 while (1)
1198 int count_before_this = skip_args;
1200 if (argmatch (argv, argc, "-d", "--display", 3, &displayname, &skip_args))
1201 display_arg = 1;
1202 else if (argmatch (argv, argc, "-display", 0, 3, &displayname, &skip_args))
1203 display_arg = 1;
1204 else
1205 break;
1207 count_before = count_before_this;
1210 /* If we have the form --display=NAME,
1211 convert it into -d name.
1212 This requires inserting a new element into argv. */
1213 if (displayname && count_before < skip_args)
1215 if (skip_args == count_before + 1)
1217 memmove (argv + count_before + 3, argv + count_before + 2,
1218 (argc - (count_before + 2)) * sizeof *argv);
1219 argv[count_before + 2] = displayname;
1220 argc++;
1222 argv[count_before + 1] = (char *) "-d";
1225 if (! no_site_lisp)
1227 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1228 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1229 no_site_lisp = 1;
1232 /* Don't actually discard this arg. */
1233 skip_args = count_before;
1235 #else /* !HAVE_X_WINDOWS */
1236 if (! no_site_lisp)
1238 int count_before = skip_args;
1240 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1241 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1242 no_site_lisp = 1;
1244 skip_args = count_before;
1246 #endif
1248 /* argmatch must not be used after here,
1249 except when building temacs
1250 because the -d argument has not been skipped in skip_args. */
1252 #ifdef MSDOS
1253 /* Call early 'cause init_environment needs it. */
1254 init_dosfns ();
1255 /* Set defaults for several environment variables. */
1256 if (initialized)
1257 init_environment (argc, argv, skip_args);
1258 else
1259 tzset ();
1260 #endif /* MSDOS */
1262 #ifdef WINDOWSNT
1263 globals_of_w32 ();
1264 /* Initialize environment from registry settings. */
1265 init_environment (argv);
1266 init_ntproc (dumping); /* must precede init_editfns. */
1267 #endif
1269 /* Initialize and GC-protect Vinitial_environment and
1270 Vprocess_environment before set_initial_environment fills them
1271 in. */
1272 if (!initialized)
1273 syms_of_callproc ();
1274 /* egetenv is a pretty low-level facility, which may get called in
1275 many circumstances; it seems flimsy to put off initializing it
1276 until calling init_callproc. Do not do it when dumping. */
1277 if (! dumping)
1278 set_initial_environment ();
1280 /* AIX crashes are reported in system versions 3.2.3 and 3.2.4
1281 if this is not done. Do it after set_global_environment so that we
1282 don't pollute Vglobal_environment. */
1283 /* Setting LANG here will defeat the startup locale processing... */
1284 #ifdef AIX
1285 putenv ("LANG=C");
1286 #endif
1288 init_buffer (); /* Init default directory of main buffer. */
1290 init_callproc_1 (); /* Must precede init_cmdargs and init_sys_modes. */
1291 init_cmdargs (argc, argv, skip_args); /* Must precede init_lread. */
1293 if (initialized)
1295 /* Erase any pre-dump messages in the message log, to avoid confusion. */
1296 Lisp_Object old_log_max;
1297 old_log_max = Vmessage_log_max;
1298 XSETFASTINT (Vmessage_log_max, 0);
1299 message_dolog ("", 0, 1, 0);
1300 Vmessage_log_max = old_log_max;
1303 init_callproc (); /* Must follow init_cmdargs but not init_sys_modes. */
1304 init_lread ();
1305 #ifdef WINDOWSNT
1306 /* Check to see if Emacs has been installed correctly. */
1307 check_windows_init_file ();
1308 #endif
1310 /* Intern the names of all standard functions and variables;
1311 define standard keys. */
1313 if (!initialized)
1315 /* The basic levels of Lisp must come first. Note that
1316 syms_of_data and some others have already been called. */
1317 syms_of_chartab ();
1318 syms_of_lread ();
1319 syms_of_print ();
1320 syms_of_eval ();
1321 syms_of_fns ();
1322 syms_of_floatfns ();
1324 syms_of_buffer ();
1325 syms_of_bytecode ();
1326 syms_of_callint ();
1327 syms_of_casefiddle ();
1328 syms_of_casetab ();
1329 syms_of_category ();
1330 syms_of_ccl ();
1331 syms_of_character ();
1332 syms_of_cmds ();
1333 syms_of_dired ();
1334 syms_of_display ();
1335 syms_of_doc ();
1336 syms_of_editfns ();
1337 syms_of_emacs ();
1338 syms_of_filelock ();
1339 syms_of_indent ();
1340 syms_of_insdel ();
1341 /* syms_of_keymap (); */
1342 syms_of_macros ();
1343 syms_of_marker ();
1344 syms_of_minibuf ();
1345 syms_of_process ();
1346 syms_of_search ();
1347 syms_of_frame ();
1348 syms_of_syntax ();
1349 syms_of_terminal ();
1350 syms_of_term ();
1351 syms_of_undo ();
1352 #ifdef HAVE_SOUND
1353 syms_of_sound ();
1354 #endif
1355 syms_of_textprop ();
1356 syms_of_composite ();
1357 #ifdef WINDOWSNT
1358 syms_of_ntproc ();
1359 #endif /* WINDOWSNT */
1360 syms_of_window ();
1361 syms_of_xdisp ();
1362 syms_of_font ();
1363 #ifdef HAVE_WINDOW_SYSTEM
1364 syms_of_fringe ();
1365 syms_of_image ();
1366 #endif /* HAVE_WINDOW_SYSTEM */
1367 #ifdef HAVE_X_WINDOWS
1368 syms_of_xterm ();
1369 syms_of_xfns ();
1370 syms_of_xmenu ();
1371 syms_of_fontset ();
1372 syms_of_xsettings ();
1373 #ifdef HAVE_X_SM
1374 syms_of_xsmfns ();
1375 #endif
1376 #ifdef HAVE_X11
1377 syms_of_xselect ();
1378 #endif
1379 #endif /* HAVE_X_WINDOWS */
1381 #ifdef HAVE_LIBXML2
1382 syms_of_xml ();
1383 #endif
1385 syms_of_menu ();
1387 #ifdef HAVE_NTGUI
1388 syms_of_w32term ();
1389 syms_of_w32fns ();
1390 syms_of_w32select ();
1391 syms_of_w32menu ();
1392 syms_of_fontset ();
1393 #endif /* HAVE_NTGUI */
1395 #ifdef MSDOS
1396 syms_of_xmenu ();
1397 syms_of_dosfns ();
1398 syms_of_msdos ();
1399 syms_of_win16select ();
1400 #endif /* MSDOS */
1402 #ifdef HAVE_NS
1403 syms_of_nsterm ();
1404 syms_of_nsfns ();
1405 syms_of_nsmenu ();
1406 syms_of_nsselect ();
1407 syms_of_fontset ();
1408 #endif /* HAVE_NS */
1410 #ifdef HAVE_GNUTLS
1411 syms_of_gnutls ();
1412 #endif
1414 #ifdef HAVE_DBUS
1415 syms_of_dbusbind ();
1416 #endif /* HAVE_DBUS */
1418 #ifdef WINDOWSNT
1419 syms_of_ntterm ();
1420 #endif /* WINDOWSNT */
1422 keys_of_casefiddle ();
1423 keys_of_cmds ();
1424 keys_of_buffer ();
1425 keys_of_keyboard ();
1426 keys_of_keymap ();
1427 keys_of_window ();
1429 else
1431 /* Initialization that must be done even if the global variable
1432 initialized is non zero. */
1433 #ifdef HAVE_NTGUI
1434 globals_of_w32font ();
1435 globals_of_w32fns ();
1436 globals_of_w32menu ();
1437 globals_of_w32select ();
1438 #endif /* HAVE_NTGUI */
1441 init_charset ();
1443 init_editfns (); /* init_process_emacs uses Voperating_system_release. */
1444 init_process_emacs (); /* init_display uses add_keyboard_wait_descriptor. */
1445 init_keyboard (); /* This too must precede init_sys_modes. */
1446 if (!noninteractive)
1447 init_display (); /* Determine terminal type. Calls init_sys_modes. */
1448 init_xdisp ();
1449 #ifdef HAVE_WINDOW_SYSTEM
1450 init_fringe ();
1451 #endif /* HAVE_WINDOW_SYSTEM */
1452 init_macros ();
1453 init_window ();
1454 init_font ();
1456 if (!initialized)
1458 char *file;
1459 /* Handle -l loadup, args passed by Makefile. */
1460 if (argmatch (argv, argc, "-l", "--load", 3, &file, &skip_args))
1461 Vtop_level = Fcons (intern_c_string ("load"),
1462 Fcons (build_string (file), Qnil));
1463 /* Unless next switch is -nl, load "loadup.el" first thing. */
1464 if (! no_loadup)
1465 Vtop_level = Fcons (intern_c_string ("load"),
1466 Fcons (build_string ("loadup.el"), Qnil));
1469 if (initialized)
1471 #ifdef HAVE_TZSET
1473 /* If the execution TZ happens to be the same as the dump TZ,
1474 change it to some other value and then change it back,
1475 to force the underlying implementation to reload the TZ info.
1476 This is needed on implementations that load TZ info from files,
1477 since the TZ file contents may differ between dump and execution. */
1478 char *tz = getenv ("TZ");
1479 if (tz && !strcmp (tz, dump_tz))
1481 ++*tz;
1482 tzset ();
1483 --*tz;
1486 #endif
1489 /* Set up for profiling. This is known to work on FreeBSD,
1490 GNU/Linux and MinGW. It might work on some other systems too.
1491 Give it a try and tell us if it works on your system. To compile
1492 for profiling, use the configure option --enable-profiling. */
1493 #if defined (__FreeBSD__) || defined (GNU_LINUX) || defined (__MINGW32__)
1494 #ifdef PROFILING
1495 if (initialized)
1497 #ifdef __MINGW32__
1498 extern unsigned char etext asm ("etext");
1499 #else
1500 extern char etext;
1501 #endif
1503 atexit (_mcleanup);
1504 monstartup ((uintptr_t) __executable_start, (uintptr_t) &etext);
1506 else
1507 moncontrol (0);
1508 #endif
1509 #endif
1511 initialized = 1;
1513 #ifdef LOCALTIME_CACHE
1514 /* Some versions of localtime have a bug. They cache the value of the time
1515 zone rather than looking it up every time. Since localtime() is
1516 called to bolt the undumping time into the undumped emacs, this
1517 results in localtime ignoring the TZ environment variable.
1518 This flushes the new TZ value into localtime. */
1519 tzset ();
1520 #endif /* defined (LOCALTIME_CACHE) */
1522 /* Enter editor command loop. This never returns. */
1523 Frecursive_edit ();
1524 /* NOTREACHED */
1525 return 0;
1528 /* Sort the args so we can find the most important ones
1529 at the beginning of argv. */
1531 /* First, here's a table of all the standard options. */
1533 struct standard_args
1535 const char *name;
1536 const char *longname;
1537 int priority;
1538 int nargs;
1541 static const struct standard_args standard_args[] =
1543 { "-version", "--version", 150, 0 },
1544 { "-chdir", "--chdir", 130, 1 },
1545 { "-t", "--terminal", 120, 1 },
1546 { "-nw", "--no-window-system", 110, 0 },
1547 { "-nw", "--no-windows", 110, 0 },
1548 { "-batch", "--batch", 100, 0 },
1549 { "-script", "--script", 100, 1 },
1550 { "-daemon", "--daemon", 99, 0 },
1551 { "-help", "--help", 90, 0 },
1552 { "-nl", "--no-loadup", 70, 0 },
1553 { "-nsl", "--no-site-lisp", 65, 0 },
1554 /* -d must come last before the options handled in startup.el. */
1555 { "-d", "--display", 60, 1 },
1556 { "-display", 0, 60, 1 },
1557 /* Now for the options handled in `command-line' (startup.el). */
1558 /* (Note that to imply -nsl, -Q is partially handled here.) */
1559 { "-Q", "--quick", 55, 0 },
1560 { "-quick", 0, 55, 0 },
1561 { "-q", "--no-init-file", 50, 0 },
1562 { "-no-init-file", 0, 50, 0 },
1563 { "-no-site-file", "--no-site-file", 40, 0 },
1564 { "-u", "--user", 30, 1 },
1565 { "-user", 0, 30, 1 },
1566 { "-debug-init", "--debug-init", 20, 0 },
1567 { "-iconic", "--iconic", 15, 0 },
1568 { "-D", "--basic-display", 12, 0},
1569 { "-basic-display", 0, 12, 0},
1570 { "-nbc", "--no-blinking-cursor", 12, 0 },
1571 /* Now for the options handled in `command-line-1' (startup.el). */
1572 { "-nbi", "--no-bitmap-icon", 10, 0 },
1573 { "-bg", "--background-color", 10, 1 },
1574 { "-background", 0, 10, 1 },
1575 { "-fg", "--foreground-color", 10, 1 },
1576 { "-foreground", 0, 10, 1 },
1577 { "-bd", "--border-color", 10, 1 },
1578 { "-bw", "--border-width", 10, 1 },
1579 { "-ib", "--internal-border", 10, 1 },
1580 { "-ms", "--mouse-color", 10, 1 },
1581 { "-cr", "--cursor-color", 10, 1 },
1582 { "-fn", "--font", 10, 1 },
1583 { "-font", 0, 10, 1 },
1584 { "-fs", "--fullscreen", 10, 0 },
1585 { "-fw", "--fullwidth", 10, 0 },
1586 { "-fh", "--fullheight", 10, 0 },
1587 { "-mm", "--maximized", 10, 0 },
1588 { "-g", "--geometry", 10, 1 },
1589 { "-geometry", 0, 10, 1 },
1590 { "-T", "--title", 10, 1 },
1591 { "-title", 0, 10, 1 },
1592 { "-name", "--name", 10, 1 },
1593 { "-xrm", "--xrm", 10, 1 },
1594 { "-parent-id", "--parent-id", 10, 1 },
1595 { "-r", "--reverse-video", 5, 0 },
1596 { "-rv", 0, 5, 0 },
1597 { "-reverse", 0, 5, 0 },
1598 { "-hb", "--horizontal-scroll-bars", 5, 0 },
1599 { "-vb", "--vertical-scroll-bars", 5, 0 },
1600 { "-color", "--color", 5, 0},
1601 { "-no-splash", "--no-splash", 3, 0 },
1602 { "-no-desktop", "--no-desktop", 3, 0 },
1603 #ifdef HAVE_NS
1604 { "-NSAutoLaunch", 0, 5, 1 },
1605 { "-NXAutoLaunch", 0, 5, 1 },
1606 { "-disable-font-backend", "--disable-font-backend", 65, 0 },
1607 { "-_NSMachLaunch", 0, 85, 1 },
1608 { "-MachLaunch", 0, 85, 1 },
1609 { "-macosx", 0, 85, 0 },
1610 { "-NSHost", 0, 85, 1 },
1611 #endif
1612 /* These have the same priority as ordinary file name args,
1613 so they are not reordered with respect to those. */
1614 { "-L", "--directory", 0, 1 },
1615 { "-directory", 0, 0, 1 },
1616 { "-l", "--load", 0, 1 },
1617 { "-load", 0, 0, 1 },
1618 /* This has no longname, because using --scriptload confuses sort_args,
1619 because then the --script long option seems to match twice; ie
1620 you can't have a long option which is a prefix of another long
1621 option. In any case, this is entirely an internal option. */
1622 { "-scriptload", NULL, 0, 1 },
1623 { "-f", "--funcall", 0, 1 },
1624 { "-funcall", 0, 0, 1 },
1625 { "-eval", "--eval", 0, 1 },
1626 { "-execute", "--execute", 0, 1 },
1627 { "-find-file", "--find-file", 0, 1 },
1628 { "-visit", "--visit", 0, 1 },
1629 { "-file", "--file", 0, 1 },
1630 { "-insert", "--insert", 0, 1 },
1631 #ifdef HAVE_NS
1632 { "-NXOpen", 0, 0, 1 },
1633 { "-NXOpenTemp", 0, 0, 1 },
1634 { "-NSOpen", 0, 0, 1 },
1635 { "-NSOpenTemp", 0, 0, 1 },
1636 { "-GSFilePath", 0, 0, 1 },
1637 #endif
1638 /* This should be processed after ordinary file name args and the like. */
1639 { "-kill", "--kill", -10, 0 },
1642 /* Reorder the elements of ARGV (assumed to have ARGC elements)
1643 so that the highest priority ones come first.
1644 Do not change the order of elements of equal priority.
1645 If an option takes an argument, keep it and its argument together.
1647 If an option that takes no argument appears more
1648 than once, eliminate all but one copy of it. */
1650 static void
1651 sort_args (int argc, char **argv)
1653 char **new = xmalloc (argc * sizeof *new);
1654 /* For each element of argv,
1655 the corresponding element of options is:
1656 0 for an option that takes no arguments,
1657 1 for an option that takes one argument, etc.
1658 -1 for an ordinary non-option argument. */
1659 int *options = xnmalloc (argc, sizeof *options);
1660 int *priority = xnmalloc (argc, sizeof *priority);
1661 int to = 1;
1662 int incoming_used = 1;
1663 int from;
1664 int i;
1666 /* Categorize all the options,
1667 and figure out which argv elts are option arguments. */
1668 for (from = 1; from < argc; from++)
1670 options[from] = -1;
1671 priority[from] = 0;
1672 if (argv[from][0] == '-')
1674 int match;
1676 /* If we have found "--", don't consider
1677 any more arguments as options. */
1678 if (argv[from][1] == '-' && argv[from][2] == 0)
1680 /* Leave the "--", and everything following it, at the end. */
1681 for (; from < argc; from++)
1683 priority[from] = -100;
1684 options[from] = -1;
1686 break;
1689 /* Look for a match with a known old-fashioned option. */
1690 for (i = 0; i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1691 if (!strcmp (argv[from], standard_args[i].name))
1693 options[from] = standard_args[i].nargs;
1694 priority[from] = standard_args[i].priority;
1695 if (from + standard_args[i].nargs >= argc)
1696 fatal ("Option `%s' requires an argument\n", argv[from]);
1697 from += standard_args[i].nargs;
1698 goto done;
1701 /* Look for a match with a known long option.
1702 MATCH is -1 if no match so far, -2 if two or more matches so far,
1703 >= 0 (the table index of the match) if just one match so far. */
1704 if (argv[from][1] == '-')
1706 char const *equals = strchr (argv[from], '=');
1707 ptrdiff_t thislen =
1708 equals ? equals - argv[from] : strlen (argv[from]);
1710 match = -1;
1712 for (i = 0;
1713 i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1714 if (standard_args[i].longname
1715 && !strncmp (argv[from], standard_args[i].longname,
1716 thislen))
1718 if (match == -1)
1719 match = i;
1720 else
1721 match = -2;
1724 /* If we found exactly one match, use that. */
1725 if (match >= 0)
1727 options[from] = standard_args[match].nargs;
1728 priority[from] = standard_args[match].priority;
1729 /* If --OPTION=VALUE syntax is used,
1730 this option uses just one argv element. */
1731 if (equals != 0)
1732 options[from] = 0;
1733 if (from + options[from] >= argc)
1734 fatal ("Option `%s' requires an argument\n", argv[from]);
1735 from += options[from];
1737 /* FIXME When match < 0, shouldn't there be some error,
1738 or at least indication to the user that there was a
1739 problem? */
1741 done: ;
1745 /* Copy the arguments, in order of decreasing priority, to NEW. */
1746 new[0] = argv[0];
1747 while (incoming_used < argc)
1749 int best = -1;
1750 int best_priority = -9999;
1752 /* Find the highest priority remaining option.
1753 If several have equal priority, take the first of them. */
1754 for (from = 1; from < argc; from++)
1756 if (argv[from] != 0 && priority[from] > best_priority)
1758 best_priority = priority[from];
1759 best = from;
1761 /* Skip option arguments--they are tied to the options. */
1762 if (options[from] > 0)
1763 from += options[from];
1766 if (best < 0)
1767 emacs_abort ();
1769 /* Copy the highest priority remaining option, with its args, to NEW.
1770 Unless it is a duplicate of the previous one. */
1771 if (! (options[best] == 0
1772 && ! strcmp (new[to - 1], argv[best])))
1774 new[to++] = argv[best];
1775 for (i = 0; i < options[best]; i++)
1776 new[to++] = argv[best + i + 1];
1779 incoming_used += 1 + (options[best] > 0 ? options[best] : 0);
1781 /* Clear out this option in ARGV. */
1782 argv[best] = 0;
1783 for (i = 0; i < options[best]; i++)
1784 argv[best + i + 1] = 0;
1787 /* If duplicate options were deleted, fill up extra space with null ptrs. */
1788 while (to < argc)
1789 new[to++] = 0;
1791 memcpy (argv, new, sizeof (char *) * argc);
1793 xfree (options);
1794 xfree (new);
1795 xfree (priority);
1798 DEFUN ("kill-emacs", Fkill_emacs, Skill_emacs, 0, 1, "P",
1799 doc: /* Exit the Emacs job and kill it.
1800 If ARG is an integer, return ARG as the exit program code.
1801 If ARG is a string, stuff it as keyboard input.
1803 This function is called upon receipt of the signals SIGTERM
1804 or SIGHUP, and upon SIGINT in batch mode.
1806 The value of `kill-emacs-hook', if not void,
1807 is a list of functions (of no args),
1808 all of which are called before Emacs is actually killed. */)
1809 (Lisp_Object arg)
1811 struct gcpro gcpro1;
1812 Lisp_Object hook;
1813 int exit_code;
1815 GCPRO1 (arg);
1817 if (feof (stdin))
1818 arg = Qt;
1820 hook = intern ("kill-emacs-hook");
1821 Frun_hooks (1, &hook);
1823 UNGCPRO;
1825 #ifdef HAVE_X_WINDOWS
1826 /* Transfer any clipboards we own to the clipboard manager. */
1827 x_clipboard_manager_save_all ();
1828 #endif
1830 shut_down_emacs (0, STRINGP (arg) ? arg : Qnil);
1832 #ifdef HAVE_NS
1833 ns_release_autorelease_pool (ns_pool);
1834 #endif
1836 /* If we have an auto-save list file,
1837 kill it because we are exiting Emacs deliberately (not crashing).
1838 Do it after shut_down_emacs, which does an auto-save. */
1839 if (STRINGP (Vauto_save_list_file_name))
1840 unlink (SSDATA (Vauto_save_list_file_name));
1842 if (INTEGERP (arg))
1843 exit_code = (XINT (arg) < 0
1844 ? XINT (arg) | INT_MIN
1845 : XINT (arg) & INT_MAX);
1846 else if (noninteractive && (fflush (stdout) || ferror (stdout)))
1847 exit_code = EXIT_FAILURE;
1848 else
1849 exit_code = EXIT_SUCCESS;
1850 exit (exit_code);
1854 /* Perform an orderly shutdown of Emacs. Autosave any modified
1855 buffers, kill any child processes, clean up the terminal modes (if
1856 we're in the foreground), and other stuff like that. Don't perform
1857 any redisplay; this may be called when Emacs is shutting down in
1858 the background, or after its X connection has died.
1860 If SIG is a signal number, print a message for it.
1862 This is called by fatal signal handlers, X protocol error handlers,
1863 and Fkill_emacs. */
1865 void
1866 shut_down_emacs (int sig, Lisp_Object stuff)
1868 /* Prevent running of hooks from now on. */
1869 Vrun_hooks = Qnil;
1871 /* Don't update display from now on. */
1872 Vinhibit_redisplay = Qt;
1874 /* If we are controlling the terminal, reset terminal modes. */
1875 #ifndef DOS_NT
1877 int pgrp = EMACS_GETPGRP (0);
1878 int tpgrp = tcgetpgrp (0);
1879 if ((tpgrp != -1) && tpgrp == pgrp)
1881 reset_all_sys_modes ();
1882 if (sig && sig != SIGTERM)
1884 static char const format[] = "Fatal error %d: ";
1885 char buf[sizeof format - 2 + INT_STRLEN_BOUND (int)];
1886 int buflen = sprintf (buf, format, sig);
1887 char const *sig_desc = strsignal (sig);
1888 ignore_value (write (STDERR_FILENO, buf, buflen));
1889 ignore_value (write (STDERR_FILENO, sig_desc, strlen (sig_desc)));
1893 #else
1894 fflush (stdout);
1895 reset_all_sys_modes ();
1896 #endif
1898 stuff_buffered_input (stuff);
1900 inhibit_sentinels = 1;
1901 kill_buffer_processes (Qnil);
1902 Fdo_auto_save (Qt, Qnil);
1904 #ifdef CLASH_DETECTION
1905 unlock_all_files ();
1906 #endif
1908 /* There is a tendency for a SIGIO signal to arrive within exit,
1909 and cause a SIGHUP because the input descriptor is already closed. */
1910 unrequest_sigio ();
1911 ignore_sigio ();
1913 #ifdef WINDOWSNT
1914 term_ntproc (0);
1915 #endif
1917 /* Do this only if terminating normally, we want glyph matrices
1918 etc. in a core dump. */
1919 if (sig == 0 || sig == SIGTERM)
1921 check_glyph_memory ();
1922 check_message_stack ();
1925 #ifdef MSDOS
1926 dos_cleanup ();
1927 #endif
1929 #ifdef HAVE_NS
1930 ns_term_shutdown (sig);
1931 #endif
1933 #ifdef HAVE_LIBXML2
1934 xml_cleanup_parser ();
1935 #endif
1940 #ifndef CANNOT_DUMP
1942 #include "unexec.h"
1944 DEFUN ("dump-emacs", Fdump_emacs, Sdump_emacs, 2, 2, 0,
1945 doc: /* Dump current state of Emacs into executable file FILENAME.
1946 Take symbols from SYMFILE (presumably the file you executed to run Emacs).
1947 This is used in the file `loadup.el' when building Emacs.
1949 You must run Emacs in batch mode in order to dump it. */)
1950 (Lisp_Object filename, Lisp_Object symfile)
1952 Lisp_Object tem;
1953 Lisp_Object symbol;
1954 ptrdiff_t count = SPECPDL_INDEX ();
1956 check_pure_size ();
1958 if (! noninteractive)
1959 error ("Dumping Emacs works only in batch mode");
1961 #ifdef GNU_LINUX
1963 /* Warn if the gap between BSS end and heap start is larger than this. */
1964 # define MAX_HEAP_BSS_DIFF (1024*1024)
1966 if (heap_bss_diff > MAX_HEAP_BSS_DIFF)
1968 fprintf (stderr, "**************************************************\n");
1969 fprintf (stderr, "Warning: Your system has a gap between BSS and the\n");
1970 fprintf (stderr, "heap (%"pMu" bytes). This usually means that exec-shield\n",
1971 heap_bss_diff);
1972 fprintf (stderr, "or something similar is in effect. The dump may\n");
1973 fprintf (stderr, "fail because of this. See the section about\n");
1974 fprintf (stderr, "exec-shield in etc/PROBLEMS for more information.\n");
1975 fprintf (stderr, "**************************************************\n");
1977 #endif /* GNU_LINUX */
1979 /* Bind `command-line-processed' to nil before dumping,
1980 so that the dumped Emacs will process its command line
1981 and set up to work with X windows if appropriate. */
1982 symbol = intern ("command-line-processed");
1983 specbind (symbol, Qnil);
1985 CHECK_STRING (filename);
1986 filename = Fexpand_file_name (filename, Qnil);
1987 if (!NILP (symfile))
1989 CHECK_STRING (symfile);
1990 if (SCHARS (symfile))
1991 symfile = Fexpand_file_name (symfile, Qnil);
1994 tem = Vpurify_flag;
1995 Vpurify_flag = Qnil;
1997 #ifdef HAVE_TZSET
1998 set_time_zone_rule (dump_tz);
1999 #ifndef LOCALTIME_CACHE
2000 /* Force a tz reload, since set_time_zone_rule doesn't. */
2001 tzset ();
2002 #endif
2003 #endif
2005 fflush (stdout);
2006 /* Tell malloc where start of impure now is. */
2007 /* Also arrange for warnings when nearly out of space. */
2008 #ifndef SYSTEM_MALLOC
2009 #ifndef WINDOWSNT
2010 /* On Windows, this was done before dumping, and that once suffices.
2011 Meanwhile, my_edata is not valid on Windows. */
2013 extern char my_edata[];
2014 memory_warnings (my_edata, malloc_warning);
2016 #endif /* not WINDOWSNT */
2017 #endif /* not SYSTEM_MALLOC */
2018 #ifdef DOUG_LEA_MALLOC
2019 malloc_state_ptr = malloc_get_state ();
2020 #endif
2022 #ifdef USE_MMAP_FOR_BUFFERS
2023 mmap_set_vars (0);
2024 #endif
2025 unexec (SSDATA (filename), !NILP (symfile) ? SSDATA (symfile) : 0);
2026 #ifdef USE_MMAP_FOR_BUFFERS
2027 mmap_set_vars (1);
2028 #endif
2029 #ifdef DOUG_LEA_MALLOC
2030 free (malloc_state_ptr);
2031 #endif
2033 #ifdef WINDOWSNT
2034 Vlibrary_cache = Qnil;
2035 #endif
2036 #ifdef HAVE_WINDOW_SYSTEM
2037 reset_image_types ();
2038 #endif
2040 Vpurify_flag = tem;
2042 return unbind_to (count, Qnil);
2045 #endif /* not CANNOT_DUMP */
2047 #if HAVE_SETLOCALE
2048 /* Recover from setlocale (LC_ALL, ""). */
2049 void
2050 fixup_locale (void)
2052 /* The Emacs Lisp reader needs LC_NUMERIC to be "C",
2053 so that numbers are read and printed properly for Emacs Lisp. */
2054 setlocale (LC_NUMERIC, "C");
2057 /* Set system locale CATEGORY, with previous locale *PLOCALE, to
2058 DESIRED_LOCALE. */
2059 static void
2060 synchronize_locale (int category, Lisp_Object *plocale, Lisp_Object desired_locale)
2062 if (! EQ (*plocale, desired_locale))
2064 *plocale = desired_locale;
2065 setlocale (category, (STRINGP (desired_locale)
2066 ? SSDATA (desired_locale)
2067 : ""));
2071 /* Set system time locale to match Vsystem_time_locale, if possible. */
2072 void
2073 synchronize_system_time_locale (void)
2075 synchronize_locale (LC_TIME, &Vprevious_system_time_locale,
2076 Vsystem_time_locale);
2079 /* Set system messages locale to match Vsystem_messages_locale, if
2080 possible. */
2081 void
2082 synchronize_system_messages_locale (void)
2084 #ifdef LC_MESSAGES
2085 synchronize_locale (LC_MESSAGES, &Vprevious_system_messages_locale,
2086 Vsystem_messages_locale);
2087 #endif
2089 #endif /* HAVE_SETLOCALE */
2092 Lisp_Object
2093 decode_env_path (const char *evarname, const char *defalt)
2095 const char *path, *p;
2096 Lisp_Object lpath, element, tem;
2097 #ifdef WINDOWSNT
2098 bool defaulted = 0;
2099 const char *emacs_dir = egetenv ("emacs_dir");
2100 static const char *emacs_dir_env = "%emacs_dir%/";
2101 const size_t emacs_dir_len = strlen (emacs_dir_env);
2102 #endif
2104 /* It's okay to use getenv here, because this function is only used
2105 to initialize variables when Emacs starts up, and isn't called
2106 after that. */
2107 if (evarname != 0)
2108 path = getenv (evarname);
2109 else
2110 path = 0;
2111 if (!path)
2113 path = defalt;
2114 #ifdef WINDOWSNT
2115 defaulted = 1;
2116 #endif
2118 #ifdef DOS_NT
2119 /* Ensure values from the environment use the proper directory separator. */
2120 if (path)
2122 char *path_copy = alloca (strlen (path) + 1);
2123 strcpy (path_copy, path);
2124 dostounix_filename (path_copy);
2125 path = path_copy;
2127 #endif
2128 lpath = Qnil;
2129 while (1)
2131 p = strchr (path, SEPCHAR);
2132 if (!p)
2133 p = path + strlen (path);
2134 element = (p - path ? make_string (path, p - path)
2135 : build_string ("."));
2136 #ifdef WINDOWSNT
2137 /* Relative file names in the default path are interpreted as
2138 being relative to $emacs_dir. */
2139 if (emacs_dir && defaulted
2140 && strncmp (path, emacs_dir_env, emacs_dir_len) == 0)
2141 element = Fexpand_file_name (Fsubstring (element,
2142 make_number (emacs_dir_len),
2143 Qnil),
2144 build_string (emacs_dir));
2145 #endif
2147 /* Add /: to the front of the name
2148 if it would otherwise be treated as magic. */
2149 tem = Ffind_file_name_handler (element, Qt);
2151 /* However, if the handler says "I'm safe",
2152 don't bother adding /:. */
2153 if (SYMBOLP (tem))
2155 Lisp_Object prop;
2156 prop = Fget (tem, intern ("safe-magic"));
2157 if (! NILP (prop))
2158 tem = Qnil;
2161 if (! NILP (tem))
2162 element = concat2 (build_string ("/:"), element);
2164 lpath = Fcons (element, lpath);
2165 if (*p)
2166 path = p + 1;
2167 else
2168 break;
2170 return Fnreverse (lpath);
2173 DEFUN ("daemonp", Fdaemonp, Sdaemonp, 0, 0, 0,
2174 doc: /* Return non-nil if the current emacs process is a daemon.
2175 If the daemon was given a name argument, return that name. */)
2176 (void)
2178 if (IS_DAEMON)
2179 if (daemon_name)
2180 return build_string (daemon_name);
2181 else
2182 return Qt;
2183 else
2184 return Qnil;
2187 DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
2188 doc: /* Mark the Emacs daemon as being initialized.
2189 This finishes the daemonization process by doing the other half of detaching
2190 from the parent process and its tty file descriptors. */)
2191 (void)
2193 int nfd;
2194 bool err = 0;
2196 if (!IS_DAEMON)
2197 error ("This function can only be called if emacs is run as a daemon");
2199 if (daemon_pipe[1] < 0)
2200 error ("The daemon has already been initialized");
2202 if (NILP (Vafter_init_time))
2203 error ("This function can only be called after loading the init files");
2205 /* Get rid of stdin, stdout and stderr. */
2206 nfd = open ("/dev/null", O_RDWR);
2207 err |= nfd < 0;
2208 err |= dup2 (nfd, 0) < 0;
2209 err |= dup2 (nfd, 1) < 0;
2210 err |= dup2 (nfd, 2) < 0;
2211 err |= close (nfd) != 0;
2213 /* Closing the pipe will notify the parent that it can exit.
2214 FIXME: In case some other process inherited the pipe, closing it here
2215 won't notify the parent because it's still open elsewhere, so we
2216 additionally send a byte, just to make sure the parent really exits.
2217 Instead, we should probably close the pipe in start-process and
2218 call-process to make sure the pipe is never inherited by
2219 subprocesses. */
2220 err |= write (daemon_pipe[1], "\n", 1) < 0;
2221 err |= close (daemon_pipe[1]) != 0;
2222 /* Set it to an invalid value so we know we've already run this function. */
2223 daemon_pipe[1] = -1;
2225 if (err)
2226 error ("I/O error during daemon initialization");
2227 return Qt;
2230 void
2231 syms_of_emacs (void)
2233 DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
2234 DEFSYM (Qrisky_local_variable, "risky-local-variable");
2235 DEFSYM (Qkill_emacs, "kill-emacs");
2237 #ifndef CANNOT_DUMP
2238 defsubr (&Sdump_emacs);
2239 #endif
2241 defsubr (&Skill_emacs);
2243 defsubr (&Sinvocation_name);
2244 defsubr (&Sinvocation_directory);
2245 defsubr (&Sdaemonp);
2246 defsubr (&Sdaemon_initialized);
2248 DEFVAR_LISP ("command-line-args", Vcommand_line_args,
2249 doc: /* Args passed by shell to Emacs, as a list of strings.
2250 Many arguments are deleted from the list as they are processed. */);
2252 DEFVAR_LISP ("system-type", Vsystem_type,
2253 doc: /* The value is a symbol indicating the type of operating system you are using.
2254 Special values:
2255 `gnu' compiled for a GNU Hurd system.
2256 `gnu/linux' compiled for a GNU/Linux system.
2257 `gnu/kfreebsd' compiled for a GNU system with a FreeBSD kernel.
2258 `darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
2259 `ms-dos' compiled as an MS-DOS application.
2260 `windows-nt' compiled as a native W32 application.
2261 `cygwin' compiled using the Cygwin library.
2262 Anything else (in Emacs 24.1, the possibilities are: aix, berkeley-unix,
2263 hpux, irix, usg-unix-v) indicates some sort of Unix system. */);
2264 Vsystem_type = intern_c_string (SYSTEM_TYPE);
2265 /* See configure.ac (and config.nt) for the possible SYSTEM_TYPEs. */
2267 DEFVAR_LISP ("system-configuration", Vsystem_configuration,
2268 doc: /* Value is string indicating configuration Emacs was built for.
2269 On MS-Windows, the value reflects the OS flavor and version on which
2270 Emacs is running. */);
2271 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2273 DEFVAR_LISP ("system-configuration-options", Vsystem_configuration_options,
2274 doc: /* String containing the configuration options Emacs was built with. */);
2275 Vsystem_configuration_options = build_string (EMACS_CONFIG_OPTIONS);
2277 DEFVAR_BOOL ("noninteractive", noninteractive1,
2278 doc: /* Non-nil means Emacs is running without interactive terminal. */);
2280 DEFVAR_LISP ("kill-emacs-hook", Vkill_emacs_hook,
2281 doc: /* Hook run when `kill-emacs' is called.
2282 Since `kill-emacs' may be invoked when the terminal is disconnected (or
2283 in other similar situations), functions placed on this hook should not
2284 expect to be able to interact with the user. To ask for confirmation,
2285 see `kill-emacs-query-functions' instead.
2287 Before Emacs 24.1, the hook was not run in batch mode, i.e., if
2288 `noninteractive' was non-nil. */);
2289 Vkill_emacs_hook = Qnil;
2291 DEFVAR_LISP ("path-separator", Vpath_separator,
2292 doc: /* String containing the character that separates directories in
2293 search paths, such as PATH and other similar environment variables. */);
2295 char c = SEPCHAR;
2296 Vpath_separator = make_string (&c, 1);
2299 DEFVAR_LISP ("invocation-name", Vinvocation_name,
2300 doc: /* The program name that was used to run Emacs.
2301 Any directory names are omitted. */);
2303 DEFVAR_LISP ("invocation-directory", Vinvocation_directory,
2304 doc: /* The directory in which the Emacs executable was found, to run it.
2305 The value is nil if that directory's name is not known. */);
2307 DEFVAR_LISP ("installation-directory", Vinstallation_directory,
2308 doc: /* A directory within which to look for the `lib-src' and `etc' directories.
2309 In an installed Emacs, this is normally nil. It is non-nil if
2310 both `lib-src' (on MS-DOS, `info') and `etc' directories are found
2311 within the variable `invocation-directory' or its parent. For example,
2312 this is the case when running an uninstalled Emacs executable from its
2313 build directory. */);
2314 Vinstallation_directory = Qnil;
2316 DEFVAR_LISP ("system-messages-locale", Vsystem_messages_locale,
2317 doc: /* System locale for messages. */);
2318 Vsystem_messages_locale = Qnil;
2320 DEFVAR_LISP ("previous-system-messages-locale",
2321 Vprevious_system_messages_locale,
2322 doc: /* Most recently used system locale for messages. */);
2323 Vprevious_system_messages_locale = Qnil;
2325 DEFVAR_LISP ("system-time-locale", Vsystem_time_locale,
2326 doc: /* System locale for time. */);
2327 Vsystem_time_locale = Qnil;
2329 DEFVAR_LISP ("previous-system-time-locale", Vprevious_system_time_locale,
2330 doc: /* Most recently used system locale for time. */);
2331 Vprevious_system_time_locale = Qnil;
2333 DEFVAR_LISP ("before-init-time", Vbefore_init_time,
2334 doc: /* Value of `current-time' before Emacs begins initialization. */);
2335 Vbefore_init_time = Qnil;
2337 DEFVAR_LISP ("after-init-time", Vafter_init_time,
2338 doc: /* Value of `current-time' after loading the init files.
2339 This is nil during initialization. */);
2340 Vafter_init_time = Qnil;
2342 DEFVAR_BOOL ("inhibit-x-resources", inhibit_x_resources,
2343 doc: /* If non-nil, X resources, Windows Registry settings, and NS defaults are not used. */);
2344 inhibit_x_resources = 0;
2346 DEFVAR_LISP ("emacs-copyright", Vemacs_copyright,
2347 doc: /* Short copyright string for this version of Emacs. */);
2348 Vemacs_copyright = build_string (emacs_copyright);
2350 DEFVAR_LISP ("emacs-version", Vemacs_version,
2351 doc: /* Version numbers of this version of Emacs. */);
2352 Vemacs_version = build_string (emacs_version);
2354 DEFVAR_LISP ("dynamic-library-alist", Vdynamic_library_alist,
2355 doc: /* Alist of dynamic libraries vs external files implementing them.
2356 Each element is a list (LIBRARY FILE...), where the car is a symbol
2357 representing a supported external library, and the rest are strings giving
2358 alternate filenames for that library.
2360 Emacs tries to load the library from the files in the order they appear on
2361 the list; if none is loaded, the running session of Emacs won't have access
2362 to that library.
2364 Note that image types `pbm' and `xbm' do not need entries in this variable
2365 because they do not depend on external libraries and are always available.
2367 Also note that this is not a generic facility for accessing external
2368 libraries; only those already known by Emacs will be loaded. */);
2369 Vdynamic_library_alist = Qnil;
2370 Fput (intern_c_string ("dynamic-library-alist"), Qrisky_local_variable, Qt);
2372 #ifdef WINDOWSNT
2373 Vlibrary_cache = Qnil;
2374 staticpro (&Vlibrary_cache);
2375 #endif
2377 /* Make sure IS_DAEMON starts up as false. */
2378 daemon_pipe[1] = 0;