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