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