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