emacs.c 91.2 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Fully extensible Emacs, running on Unix, intended for GNU.
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1985-1987, 1993-1995, 1997-1999, 2001-2020 Free Software
Paul Eggert's avatar
Paul Eggert committed
4
Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
5 6 7

This file is part of GNU Emacs.

8
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
9
it under the terms of the GNU General Public License as published by
10 11
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
12 13 14 15 16 17 18

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
19
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
20

Paul Eggert's avatar
Paul Eggert committed
21
#define INLINE EXTERN_INLINE
22
#include <config.h>
Paul Eggert's avatar
Paul Eggert committed
23

Jim Blandy's avatar
Jim Blandy committed
24
#include <errno.h>
25
#include <fcntl.h>
Paul Eggert's avatar
Paul Eggert committed
26
#include <stdlib.h>
Jim Blandy's avatar
Jim Blandy committed
27 28

#include <sys/file.h>
29
#include <sys/stat.h>
30 31
#include <unistd.h>

32
#define MAIN_PROGRAM
33
#include "lisp.h"
34
#include "sysstdio.h"
35

36 37
#ifdef WINDOWSNT
#include <fcntl.h>
38
#include <sys/socket.h>
39
#include <mbstring.h>
40
#include "w32.h"
Daniel Colascione's avatar
Daniel Colascione committed
41 42 43
#include "w32heap.h"
#endif

44
#if defined WINDOWSNT || defined HAVE_NTGUI
Daniel Colascione's avatar
Daniel Colascione committed
45 46
#include "w32select.h"
#include "w32font.h"
47
#include "w32common.h"
Daniel Colascione's avatar
Daniel Colascione committed
48 49
#endif

50
#if defined CYGWIN
Daniel Colascione's avatar
Daniel Colascione committed
51
#include "cygw32.h"
52 53
#endif

54 55
#ifdef MSDOS
#include <binary-io.h>
Eli Zaretskii's avatar
Eli Zaretskii committed
56
#include "dosfns.h"
57 58
#endif

59
#ifdef HAVE_LIBSYSTEMD
60 61 62
# include <systemd/sd-daemon.h>
# include <sys/socket.h>
#endif
63

64 65 66 67
#ifdef HAVE_WINDOW_SYSTEM
#include TERM_HEADER
#endif /* HAVE_WINDOW_SYSTEM */

Paul Eggert's avatar
Paul Eggert committed
68
#include "bignum.h"
Joseph Arceneaux's avatar
Joseph Arceneaux committed
69
#include "intervals.h"
70
#include "character.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
71
#include "buffer.h"
Stefan Monnier's avatar
Stefan Monnier committed
72
#include "window.h"
Paul Eggert's avatar
Paul Eggert committed
73
#include "xwidget.h"
74
#include "atimer.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
75
#include "blockinput.h"
76
#include "syssignal.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
77
#include "process.h"
78
#include "frame.h"
79
#include "termhooks.h"
Andreas Schwab's avatar
Andreas Schwab committed
80
#include "keyboard.h"
Stefan Monnier's avatar
Stefan Monnier committed
81
#include "keymap.h"
Paul Eggert's avatar
Paul Eggert committed
82 83 84 85
#include "category.h"
#include "charset.h"
#include "composite.h"
#include "dispextern.h"
86
#include "ptr-bounds.h"
87
#include "regex-emacs.h"
88
#include "sheap.h"
Paul Eggert's avatar
Paul Eggert committed
89
#include "syntax.h"
90
#include "sysselect.h"
Paul Eggert's avatar
Paul Eggert committed
91
#include "systime.h"
92
#include "puresize.h"
Jim Blandy's avatar
Jim Blandy committed
93

Paul Eggert's avatar
Paul Eggert committed
94
#include "getpagesize.h"
Ted Zlatanov's avatar
Ted Zlatanov committed
95 96
#include "gnutls.h"

97
#ifdef PROFILING
98 99
# include <sys/gmon.h>
extern void moncontrol (int mode);
100 101 102 103 104
# ifdef __MINGW32__
extern unsigned char etext asm ("etext");
# else
extern char etext;
# endif
105 106
#endif

107 108 109 110
#ifdef HAVE_SETLOCALE
#include <locale.h>
#endif

111 112 113 114
#if HAVE_WCHAR_H
# include <wchar.h>
#endif

115 116 117 118 119
#ifdef HAVE_SETRLIMIT
#include <sys/time.h>
#include <sys/resource.h>
#endif

Daniel Colascione's avatar
Daniel Colascione committed
120 121 122
#include "pdumper.h"
#include "epaths.h"

Glenn Morris's avatar
Glenn Morris committed
123
static const char emacs_version[] = PACKAGE_VERSION;
124
static const char emacs_copyright[] = COPYRIGHT;
Glenn Morris's avatar
Glenn Morris committed
125
static const char emacs_bugreport[] = PACKAGE_BUGREPORT;
126

Paul Eggert's avatar
Paul Eggert committed
127 128 129 130 131
/* Put version info into the executable in the form that 'ident' uses.  */
char const EXTERNALLY_VISIBLE RCS_Id[]
  = "$Id" ": GNU Emacs " PACKAGE_VERSION
    " (" EMACS_CONFIGURATION " " EMACS_CONFIG_FEATURES ") $";

132 133
/* Empty lisp strings.  To avoid having to build any others.  */
Lisp_Object empty_unibyte_string, empty_multibyte_string;
Stefan Monnier's avatar
Stefan Monnier committed
134

135 136 137 138 139
#ifdef WINDOWSNT
/* Cache for externally loaded libraries.  */
Lisp_Object Vlibrary_cache;
#endif

Daniel Colascione's avatar
Daniel Colascione committed
140
struct gflags gflags;
141
bool initialized;
Jim Blandy's avatar
Jim Blandy committed
142

143
/* If true, Emacs should not attempt to use a window-specific code,
Pavel Janík's avatar
Pavel Janík committed
144
   but instead should use the virtual terminal under which it was started.  */
145
bool inhibit_window_system;
Jim Blandy's avatar
Jim Blandy committed
146

147
/* If true, a filter or a sentinel is running.  Tested to save the match
Pavel Janík's avatar
Pavel Janík committed
148
   data on the first attempt to change it inside asynchronous code.  */
149
bool running_asynch_code;
150

Juanma Barranquero's avatar
Juanma Barranquero committed
151
#if defined (HAVE_X_WINDOWS) || defined (HAVE_NS)
152 153
/* If true, -d was specified, meaning we're using some window system.  */
bool display_arg;
Jim Blandy's avatar
Jim Blandy committed
154 155
#endif

156
#if defined GNU_LINUX && defined HAVE_UNEXEC
157
/* The gap between BSS end and heap start as far as we can tell.  */
Paul Eggert's avatar
Paul Eggert committed
158
static uintmax_t heap_bss_diff;
159
#endif
160

161 162
/* To run as a background daemon under Cocoa or Windows,
   we must do a fork+exec, not a simple fork.
163

164 165 166
   On Cocoa, CoreFoundation lib fails in forked process, see Mac OS X
   Leopard Developer Release Notes for CoreFoundation Framework:

Paul Eggert's avatar
Paul Eggert committed
167
   https://web.archive.org/web/20090225231934/http://developer.apple.com/ReleaseNotes/CoreFoundation/CoreFoundation.html
168 169 170 171 172 173

   On Windows, a Cygwin fork child cannot access the USER subsystem.

   We mark being in the exec'd process by a daemon name argument of
   form "--daemon=\nFD0,FD1\nNAME" where FD are the pipe file descriptors,
   NAME is the original daemon name, if any. */
174
#if defined NS_IMPL_COCOA || (defined HAVE_NTGUI && defined CYGWIN)
175 176 177
# define DAEMON_MUST_EXEC
#endif

178 179
/* True means running Emacs without interactive terminal.  */
bool noninteractive;
Jim Blandy's avatar
Jim Blandy committed
180

181 182
/* True means remove site-lisp directories from load-path.  */
bool no_site_lisp;
183

Paul Eggert's avatar
Paul Eggert committed
184 185 186
/* True means put details like time stamps into builds.  */
bool build_details;

187 188
/* Name for the server started by the daemon.*/
static char *daemon_name;
189

190 191 192
/* 0 not a daemon, 1 new-style (foreground), 2 old-style (background).  */
int daemon_type;

193
#ifndef WINDOWSNT
194 195
/* Pipe used to send exit notification to the background daemon parent at
   startup.  On Windows, we use a kernel event instead.  */
196
static int daemon_pipe[2];
197 198 199
#else
HANDLE w32_daemon_event;
#endif
200

201 202 203
/* Save argv and argc.  */
char **initial_argv;
int initial_argc;
204

205 206 207
/* The name of the working directory, or NULL if this info is unavailable.  */
char const *emacs_wd;

208
static void sort_args (int argc, char **argv);
209
static void syms_of_emacs (void);
Gerd Moellmann's avatar
Gerd Moellmann committed
210

Paul Eggert's avatar
Paul Eggert committed
211
/* C99 needs each string to be at most 4095 characters, and the usage
Kenichi Handa's avatar
Kenichi Handa committed
212
   strings below are split to not overflow this limit.  */
Paul Eggert's avatar
Paul Eggert committed
213 214
static char const *const usage_message[] =
  { "\
Gerd Moellmann's avatar
Gerd Moellmann committed
215 216 217 218 219
\n\
Run Emacs, the extensible, customizable, self-documenting real-time\n\
display editor.  The recommended way to start Emacs for normal editing\n\
is with no options at all.\n\
\n\
220
Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n\
Gerd Moellmann's avatar
Gerd Moellmann committed
221 222 223 224
read the main documentation for these command-line arguments.\n\
\n\
Initialization options:\n\
\n\
Paul Eggert's avatar
Paul Eggert committed
225 226
",
    "\
Kenichi Handa's avatar
Kenichi Handa committed
227
--batch                     do not do interactive display; implies -q\n\
228
--chdir DIR                 change to directory DIR\n\
229 230
--daemon, --bg-daemon[=NAME] start a (named) server in the background\n\
--fg-daemon[=NAME]          start a (named) server in the foreground\n\
Kenichi Handa's avatar
Kenichi Handa committed
231 232
--debug-init                enable Emacs Lisp debugger for init file\n\
--display, -d DISPLAY       use X server DISPLAY\n\
233 234 235
",
#ifdef HAVE_MODULES
    "\
236
--module-assertions         assert behavior of dynamic modules\n\
Paul Eggert's avatar
Paul Eggert committed
237
",
238 239 240 241 242
#endif
#ifdef HAVE_PDUMPER
    "\
--dump-file FILE            read dumped state from FILE\n\
",
243
#endif
Paul Eggert's avatar
Paul Eggert committed
244
    "\
Paul Eggert's avatar
Paul Eggert committed
245
--no-build-details          do not add build details such as time stamps\n\
Kenichi Handa's avatar
Kenichi Handa committed
246 247
--no-desktop                do not load a saved desktop\n\
--no-init-file, -q          load neither ~/.emacs nor default.el\n\
248
--no-loadup, -nl            do not load loadup.el into bare Emacs\n\
Kenichi Handa's avatar
Kenichi Handa committed
249
--no-site-file              do not load site-start.el\n\
250
--no-x-resources            do not load X resources\n\
251
--no-site-lisp, -nsl        do not add site-lisp directories to load-path\n\
Kenichi Handa's avatar
Kenichi Handa committed
252
--no-splash                 do not display a splash screen on startup\n\
253
--no-window-system, -nw     do not communicate with X, ignoring $DISPLAY\n\
Paul Eggert's avatar
Paul Eggert committed
254 255
",
    "\
256 257
--quick, -Q                 equivalent to:\n\
                              -q --no-site-file --no-site-lisp --no-splash\n\
258
                              --no-x-resources\n\
Kenichi Handa's avatar
Kenichi Handa committed
259 260 261
--script FILE               run FILE as an Emacs Lisp script\n\
--terminal, -t DEVICE       use DEVICE for terminal I/O\n\
--user, -u USER             load ~USER/.emacs instead of your own\n\
Paul Eggert's avatar
Paul Eggert committed
262 263 264
\n\
",
    "\
Gerd Moellmann's avatar
Gerd Moellmann committed
265 266
Action options:\n\
\n\
267
FILE                    visit FILE\n\
268 269
+LINE                   go to line LINE in next FILE\n\
+LINE:COLUMN            go to line LINE, column COLUMN, in next FILE\n\
270
--directory, -L DIR     prepend DIR to load-path (with :DIR, append DIR)\n\
Kenichi Handa's avatar
Kenichi Handa committed
271 272
--eval EXPR             evaluate Emacs Lisp expression EXPR\n\
--execute EXPR          evaluate Emacs Lisp expression EXPR\n\
Paul Eggert's avatar
Paul Eggert committed
273 274
",
    "\
275 276
--file FILE             visit FILE\n\
--find-file FILE        visit FILE\n\
Kenichi Handa's avatar
Kenichi Handa committed
277 278 279 280
--funcall, -f FUNC      call Emacs Lisp function FUNC with no arguments\n\
--insert FILE           insert contents of FILE into current buffer\n\
--kill                  exit without asking for confirmation\n\
--load, -l FILE         load Emacs Lisp FILE using the load function\n\
281
--visit FILE            visit FILE\n\
Paul Eggert's avatar
Paul Eggert committed
282 283 284
\n\
",
    "\
285
Display options:\n\
Gerd Moellmann's avatar
Gerd Moellmann committed
286
\n\
Kenichi Handa's avatar
Kenichi Handa committed
287
--background-color, -bg COLOR   window background color\n\
288 289
--basic-display, -D             disable many display features;\n\
                                  used for debugging Emacs\n\
Kenichi Handa's avatar
Kenichi Handa committed
290 291
--border-color, -bd COLOR       main border color\n\
--border-width, -bw WIDTH       width of main border\n\
Paul Eggert's avatar
Paul Eggert committed
292 293
",
    "\
294
--color, --color=MODE           override color mode for character terminals;\n\
295 296
                                  MODE defaults to `auto', and\n\
                                  can also be `never', `always',\n\
Kenichi Handa's avatar
Kenichi Handa committed
297 298 299 300
                                  or a mode name like `ansi8'\n\
--cursor-color, -cr COLOR       color of the Emacs cursor indicating point\n\
--font, -fn FONT                default font; must be fixed-width\n\
--foreground-color, -fg COLOR   window foreground color\n\
Paul Eggert's avatar
Paul Eggert committed
301 302
",
    "\
Kenichi Handa's avatar
Kenichi Handa committed
303
--fullheight, -fh               make the first frame high as the screen\n\
304
--fullscreen, -fs               make the first frame fullscreen\n\
Kenichi Handa's avatar
Kenichi Handa committed
305
--fullwidth, -fw                make the first frame wide as the screen\n\
306
--maximized, -mm                make the first frame maximized\n\
Kenichi Handa's avatar
Kenichi Handa committed
307
--geometry, -g GEOMETRY         window geometry\n\
Paul Eggert's avatar
Paul Eggert committed
308 309
",
    "\
Jan Djärv's avatar
Jan Djärv committed
310
--no-bitmap-icon, -nbi          do not use picture of gnu for Emacs icon\n\
Kenichi Handa's avatar
Kenichi Handa committed
311 312 313 314 315
--iconic                        start Emacs in iconified state\n\
--internal-border, -ib WIDTH    width between text and main border\n\
--line-spacing, -lsp PIXELS     additional space to put between lines\n\
--mouse-color, -ms COLOR        mouse cursor color in Emacs window\n\
--name NAME                     title for initial Emacs frame\n\
Paul Eggert's avatar
Paul Eggert committed
316 317
",
    "\
318
--no-blinking-cursor, -nbc      disable blinking cursor\n\
Kenichi Handa's avatar
Kenichi Handa committed
319 320 321 322
--reverse-video, -r, -rv        switch foreground and background\n\
--title, -T TITLE               title for initial Emacs frame\n\
--vertical-scroll-bars, -vb     enable vertical scroll bars\n\
--xrm XRESOURCES                set additional X resources\n\
Jan Djärv's avatar
Jan Djärv committed
323
--parent-id XID                 set parent window\n\
Kenichi Handa's avatar
Kenichi Handa committed
324 325
--help                          display this help and exit\n\
--version                       output version information and exit\n\
Paul Eggert's avatar
Paul Eggert committed
326 327 328
\n\
",
    "\
Gerd Moellmann's avatar
Gerd Moellmann committed
329 330 331 332 333
You can generally also specify long option names with a single -; for\n\
example, -batch as well as --batch.  You can use any unambiguous\n\
abbreviation for a --option.\n\
\n\
Various environment variables and window system resources also affect\n\
334
the operation of Emacs.  See the main documentation.\n\
335
\n\
Glenn Morris's avatar
Glenn Morris committed
336
Report bugs to " PACKAGE_BUGREPORT ".  First, please see the Bugs\n\
Gerd Moellmann's avatar
Gerd Moellmann committed
337
section of the Emacs manual or the file BUGS.\n"
Paul Eggert's avatar
Paul Eggert committed
338
  };
Gerd Moellmann's avatar
Gerd Moellmann committed
339

Jim Blandy's avatar
Jim Blandy committed
340

341 342
/* True if handling a fatal error already.  */
bool fatal_error_in_progress;
343

344
#ifdef HAVE_NS
345
/* NS autorelease pool, for memory management.  */
346
static void *ns_pool;
347 348
#endif

349 350 351 352 353 354 355
#if !HAVE_SETLOCALE
static char *
setlocale (int cat, char const *locale)
{
  return 0;
}
#endif
356

357 358 359 360 361 362 363 364 365 366 367 368 369
/* True if the current system locale uses UTF-8 encoding.  */
static bool
using_utf8 (void)
{
#ifdef HAVE_WCHAR_H
  wchar_t wc;
  mbstate_t mbs = { 0 };
  return mbrtowc (&wc, "\xc4\x80", 2, &mbs) == 2 && wc == 0x100;
#else
  return false;
#endif
}

370

371 372
/* Report a fatal error due to signal SIG, output a backtrace of at
   most BACKTRACE_LIMIT lines, and exit.  */
373
AVOID
374
terminate_due_to_signal (int sig, int backtrace_limit)
Jim Blandy's avatar
Jim Blandy committed
375 376
{
  signal (sig, SIG_DFL);
377

378
  if (attempt_orderly_shutdown_on_fatal_signal)
379
    {
380 381 382 383 384 385 386
      /* If fatal error occurs in code below, avoid infinite recursion.  */
      if (! fatal_error_in_progress)
        {
          fatal_error_in_progress = 1;

          totally_unblock_input ();
          if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT)
387
            Fkill_emacs (make_fixnum (sig));
388 389 390 391

          shut_down_emacs (sig, Qnil);
          emacs_backtrace (backtrace_limit);
        }
392
    }
Jim Blandy's avatar
Jim Blandy committed
393

394
  /* Signal the same code; this time it will really be fatal.
395 396
     Since we're in a signal handler, the signal is blocked, so we
     have to unblock it if we want to really receive it.  */
397
#ifndef MSDOS
Paul Eggert's avatar
Paul Eggert committed
398 399 400
  {
    sigset_t unblocked;
    sigemptyset (&unblocked);
401
    sigaddset (&unblocked, sig);
Paul Eggert's avatar
Paul Eggert committed
402 403
    pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
  }
404
#endif
405

406
  emacs_raise (sig);
407 408 409

  /* This shouldn't be executed, but it prevents a warning.  */
  exit (1);
Jim Blandy's avatar
Jim Blandy committed
410 411
}

Pavel Janík's avatar
Pavel Janík committed
412
/* Code for dealing with Lisp access to the Unix command line.  */
Jim Blandy's avatar
Jim Blandy committed
413

Andreas Schwab's avatar
Andreas Schwab committed
414
static void
415
init_cmdargs (int argc, char **argv, int skip_args, char const *original_pwd)
Jim Blandy's avatar
Jim Blandy committed
416
{
417
  int i;
418
  Lisp_Object name, dir, handler;
419
  ptrdiff_t count = SPECPDL_INDEX ();
420
  Lisp_Object raw_name;
421
  AUTO_STRING (slash_colon, "/:");
Jim Blandy's avatar
Jim Blandy committed
422

423 424 425
  initial_argv = argv;
  initial_argc = argc;

426 427 428 429 430 431 432 433 434 435 436 437
#ifdef WINDOWSNT
  /* Must use argv[0] converted to UTF-8, as it begets many standard
     file and directory names.  */
  {
    char argv0[MAX_UTF8_PATH];

    if (filename_from_ansi (argv[0], argv0) == 0)
      raw_name = build_unibyte_string (argv0);
    else
      raw_name = build_unibyte_string (argv[0]);
  }
#else
438
  raw_name = build_unibyte_string (argv[0]);
439
#endif
440 441 442

  /* Add /: to the front of the name
     if it would otherwise be treated as magic.  */
443 444
  handler = Ffind_file_name_handler (raw_name, Qt);
  if (! NILP (handler))
445
    raw_name = concat2 (slash_colon, raw_name);
446 447 448 449

  Vinvocation_name = Ffile_name_nondirectory (raw_name);
  Vinvocation_directory = Ffile_name_directory (raw_name);

450 451 452 453 454 455
  /* If we got no directory in argv[0], search PATH to find where
     Emacs actually came from.  */
  if (NILP (Vinvocation_directory))
    {
      Lisp_Object found;
      int yes = openp (Vexec_path, Vinvocation_name,
456
		       Vexec_suffixes, &found, make_fixnum (X_OK), false);
457
      if (yes == 1)
458 459 460
	{
	  /* Add /: to the front of the name
	     if it would otherwise be treated as magic.  */
461 462
	  handler = Ffind_file_name_handler (found, Qt);
	  if (! NILP (handler))
463
	    found = concat2 (slash_colon, found);
464 465
	  Vinvocation_directory = Ffile_name_directory (found);
	}
466
    }
467

468 469
  if (!NILP (Vinvocation_directory)
      && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
470 471
    /* Emacs was started with relative path, like ./emacs.
       Make it absolute.  */
472
    {
473 474 475
      Lisp_Object odir =
	original_pwd ? build_unibyte_string (original_pwd) : Qnil;

476 477
      Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, odir);
    }
478

479 480 481 482 483
  Vinstallation_directory = Qnil;

  if (!NILP (Vinvocation_directory))
    {
      dir = Vinvocation_directory;
484 485 486 487 488 489 490
#ifdef WINDOWSNT
      /* If we are running from the build directory, set DIR to the
	 src subdirectory of the Emacs tree, like on Posix
	 platforms.  */
      if (SBYTES (dir) > sizeof ("/i386/") - 1
	  && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
			  "/i386/"))
491 492 493 494 495 496 497 498 499
	{
	  if (NILP (Vpurify_flag))
	    {
	      Lisp_Object file_truename = intern ("file-truename");
	      if (!NILP (Ffboundp (file_truename)))
		dir = call1 (file_truename, dir);
	    }
	  dir = Fexpand_file_name (build_string ("../.."), dir);
	}
500
#endif
501 502 503
      name = Fexpand_file_name (Vinvocation_name, dir);
      while (1)
	{
504
	  Lisp_Object tem, lib_src_exists;
505 506
	  Lisp_Object etc_exists, info_exists;

507 508 509 510 511
	  /* See if dir contains subdirs for use by Emacs.
	     Check for the ones that would exist in a build directory,
	     not including lisp and info.  */
	  tem = Fexpand_file_name (build_string ("lib-src"), dir);
	  lib_src_exists = Ffile_exists_p (tem);
512

513
#ifdef MSDOS
514 515 516 517 518
	  /* MSDOS installations frequently remove lib-src, but we still
	     must set installation-directory, or else info won't find
	     its files (it uses the value of installation-directory).  */
	  tem = Fexpand_file_name (build_string ("info"), dir);
	  info_exists = Ffile_exists_p (tem);
519 520 521
#else
	  info_exists = Qnil;
#endif
522 523

	  if (!NILP (lib_src_exists) || !NILP (info_exists))
524
	    {
525 526 527
	      tem = Fexpand_file_name (build_string ("etc"), dir);
	      etc_exists = Ffile_exists_p (tem);
	      if (!NILP (etc_exists))
528
		{
Daniel Colascione's avatar
Daniel Colascione committed
529
                  Vinstallation_directory = Ffile_name_as_directory (dir);
530
		  break;
531 532 533 534
		}
	    }

	  /* See if dir's parent contains those subdirs.  */
535 536
	  tem = Fexpand_file_name (build_string ("../lib-src"), dir);
	  lib_src_exists = Ffile_exists_p (tem);
537

538 539 540

#ifdef MSDOS
	  /* See the MSDOS commentary above.  */
541 542
	  tem = Fexpand_file_name (build_string ("../info"), dir);
	  info_exists = Ffile_exists_p (tem);
543 544 545
#else
	  info_exists = Qnil;
#endif
546 547

	  if (!NILP (lib_src_exists) || !NILP (info_exists))
548
	    {
549 550 551
	      tem = Fexpand_file_name (build_string ("../etc"), dir);
	      etc_exists = Ffile_exists_p (tem);
	      if (!NILP (etc_exists))
552
		{
553
		  tem = Fexpand_file_name (build_string (".."), dir);
Daniel Colascione's avatar
Daniel Colascione committed
554
                  Vinstallation_directory = Ffile_name_as_directory (tem);
555
		  break;
556 557 558 559 560 561 562 563
		}
	    }

	  /* If the Emacs executable is actually a link,
	     next try the dir that the link points into.  */
	  tem = Ffile_symlink_p (name);
	  if (!NILP (tem))
	    {
564
	      name = Fexpand_file_name (tem, dir);
565 566 567 568 569 570 571
	      dir = Ffile_name_directory (name);
	    }
	  else
	    break;
	}
    }

Jim Blandy's avatar
Jim Blandy committed
572 573 574 575 576
  Vcommand_line_args = Qnil;

  for (i = argc - 1; i >= 0; i--)
    {
      if (i == 0 || i > skip_args)
577 578 579
	/* For the moment, we keep arguments as is in unibyte strings.
	   They are decoded in the function command-line after we know
	   locale-coding-system.  */
Jim Blandy's avatar
Jim Blandy committed
580
	Vcommand_line_args
581
	  = Fcons (build_unibyte_string (argv[i]), Vcommand_line_args);
Jim Blandy's avatar
Jim Blandy committed
582
    }
583 584

  unbind_to (count, Qnil);
Jim Blandy's avatar
Jim Blandy committed
585
}
586 587

DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
Pavel Janík's avatar
Pavel Janík committed
588 589
       doc: /* Return the program name that was used to run Emacs.
Any directory names are omitted.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
590
  (void)
591 592 593 594
{
  return Fcopy_sequence (Vinvocation_name);
}

595
DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
Pavel Janík's avatar
Pavel Janík committed
596 597
       0, 0, 0,
       doc: /* Return the directory name in which the Emacs executable was located.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
598
  (void)
599 600 601 602
{
  return Fcopy_sequence (Vinvocation_directory);
}

Jim Blandy's avatar
Jim Blandy committed
603

Karl Heuer's avatar
Karl Heuer committed
604 605 606 607 608 609 610 611 612
/* Test whether the next argument in ARGV matches SSTR or a prefix of
   LSTR (at least MINLEN characters).  If so, then if VALPTR is non-null
   (the argument is supposed to have a value) store in *VALPTR either
   the next argument or the portion of this one after the equal sign.
   ARGV is read starting at position *SKIPPTR; this index is advanced
   by the number of arguments used.

   Too bad we can't just use getopt for all of this, but we don't have
   enough information to do it right.  */
613

614
static bool
615 616
argmatch (char **argv, int argc, const char *sstr, const char *lstr,
          int minlen, char **valptr, int *skipptr)
Karl Heuer's avatar
Karl Heuer committed
617
{
618
  char *p = NULL;
619
  ptrdiff_t arglen;
620 621 622 623 624 625 626
  char *arg;

  /* Don't access argv[argc]; give up in advance.  */
  if (argc <= *skipptr + 1)
    return 0;

  arg = argv[*skipptr+1];
Karl Heuer's avatar
Karl Heuer committed
627 628 629 630 631 632 633 634 635 636 637 638 639
  if (arg == NULL)
    return 0;
  if (strcmp (arg, sstr) == 0)
    {
      if (valptr != NULL)
	{
	  *valptr = argv[*skipptr+2];
	  *skipptr += 2;
	}
      else
	*skipptr += 1;
      return 1;
    }
640
  arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
Karl Heuer's avatar
Karl Heuer committed
641
	    ? p - arg : strlen (arg));
642
  if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
Karl Heuer's avatar
Karl Heuer committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    return 0;
  else if (valptr == NULL)
    {
      *skipptr += 1;
      return 1;
    }
  else if (p != NULL)
    {
      *valptr = p+1;
      *skipptr += 1;
      return 1;
    }
  else if (argv[*skipptr+2] != NULL)
    {
      *valptr = argv[*skipptr+2];
      *skipptr += 2;
      return 1;
    }
  else
    {
      return 0;
    }
}

Daniel Colascione's avatar
Daniel Colascione committed
667 668 669
#ifdef HAVE_PDUMPER

static const char *
670
dump_error_to_string (int result)
Daniel Colascione's avatar
Daniel Colascione committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
{
  switch (result)
    {
    case PDUMPER_LOAD_SUCCESS:
      return "success";
    case PDUMPER_LOAD_OOM:
      return "out of memory";
    case PDUMPER_NOT_LOADED:
      return "not loaded";
    case PDUMPER_LOAD_FILE_NOT_FOUND:
      return "could not open file";
    case PDUMPER_LOAD_BAD_FILE_TYPE:
      return "not a dump file";
    case PDUMPER_LOAD_FAILED_DUMP:
      return "dump file is result of failed dump attempt";
    case PDUMPER_LOAD_VERSION_MISMATCH:
      return "not built for this Emacs executable";
    default:
689 690 691
      return (result <= PDUMPER_LOAD_ERROR
	      ? "generic error"
	      : strerror (result - PDUMPER_LOAD_ERROR));
Daniel Colascione's avatar
Daniel Colascione committed
692 693 694
    }
}

695 696 697 698 699 700 701 702 703
/* Find a name (absolute or relative) of the Emacs executable whose
   name (as passed into this program) is ARGV0.  Called early in
   initialization by portable dumper loading code, so avoid Lisp and
   associated machinery.  Return a heap-allocated string giving a name
   of the Emacs executable, or an empty heap-allocated string or NULL
   if not found.  Store into *CANDIDATE_SIZE a lower bound on the size
   of any heap allocation.  */
static char *
load_pdump_find_executable (char const *argv0, ptrdiff_t *candidate_size)
704
{
705 706 707 708
  *candidate_size = 0;

  /* Use xstrdup etc. to allocate storage, so as to call our private
     implementation of malloc, since the caller calls our free.  */
709 710
#ifdef WINDOWSNT
  char *prog_fname = w32_my_exename ();
711
  return prog_fname ? xstrdup (prog_fname) : NULL;
712
#else  /* !WINDOWSNT */
713 714 715 716 717 718
  char *candidate = NULL;

  /* If the executable name contains a slash, we have some kind of
     path already, so just copy it.  */
  eassert (argv0);
  if (strchr (argv0, DIRECTORY_SEP))
719 720
    return xstrdup (argv0);
  ptrdiff_t argv0_length = strlen (argv0);
721 722 723 724 725 726

  const char *path = getenv ("PATH");
  if (!path)
    {
      /* Default PATH is implementation-defined, so we don't know how
         to conduct the search.  */
727
      return NULL;
728 729 730 731 732 733
    }

  /* Actually try each concatenation of a path element and the
     executable basename.  */
  do
    {
734 735
      static char const path_sep[] = { SEPCHAR, '\0' };
      ptrdiff_t path_part_length = strcspn (path, path_sep);
736 737 738 739 740 741 742
      const char *path_part = path;
      path += path_part_length;
      if (path_part_length == 0)
        {
          path_part = ".";
          path_part_length = 1;
        }
743 744 745 746 747 748 749
      ptrdiff_t needed = path_part_length + 1 + argv0_length + 1;
      if (*candidate_size <= needed)
	{
	  xfree (candidate);
	  candidate = xpalloc (NULL, candidate_size,
			       needed - *candidate_size + 1, -1, 1);
	}
750 751 752 753
      memcpy (candidate + 0, path_part, path_part_length);
      candidate[path_part_length] = DIRECTORY_SEP;
      memcpy (candidate + path_part_length + 1, argv0, argv0_length + 1);
      struct stat st;
754
      if (file_access_p (candidate, X_OK)
755 756 757 758 759
	  && stat (candidate, &st) == 0 && S_ISREG (st.st_mode))
	return candidate;
      *candidate = '\0';
    }
  while (*path++ != '\0');
760

761
  return candidate;
762
#endif	/* !WINDOWSNT */
763 764
}

765
static void
Daniel Colascione's avatar
Daniel Colascione committed
766 767 768
load_pdump (int argc, char **argv)
{
  const char *const suffix = ".pdmp";
769 770
  int result;
  const char *strip_suffix =
771
#if defined DOS_NT || defined CYGWIN
772 773 774 775 776
    ".exe"
#else
    NULL
#endif
    ;
Daniel Colascione's avatar
Daniel Colascione committed
777 778

  /* TODO: maybe more thoroughly scrub process environment in order to
779
     make this use case (loading a dump file in an unexeced emacs)
Daniel Colascione's avatar
Daniel Colascione committed
780 781 782 783
     possible?  Right now, we assume that things we don't touch are
     zero-initialized, and in an unexeced Emacs, this assumption
     doesn't hold.  */
  if (initialized)
784
    fatal ("cannot load dump file in unexeced Emacs");
Daniel Colascione's avatar
Daniel Colascione committed
785 786 787

  /* Look for an explicitly-specified dump file.  */
  const char *path_exec = PATH_EXEC;
788 789 790 791 792 793 794 795 796 797
  char *dump_file = NULL;
  int skip_args = 0;
  while (skip_args < argc - 1)
    {
      if (argmatch (argv, argc, "-dump-file", "--dump-file", 6,
		    &dump_file, &skip_args)
	  || argmatch (argv, argc, "--", NULL, 2, NULL, &skip_args))
	break;
      skip_args++;
    }
Daniel Colascione's avatar
Daniel Colascione committed
798 799

  if (dump_file)
800 801
    {
      result = pdumper_load (dump_file);
Daniel Colascione's avatar
Daniel Colascione committed
802

803 804 805
      if (result != PDUMPER_LOAD_SUCCESS)
        fatal ("could not load dump file \"%s\": %s",
               dump_file, dump_error_to_string (result));
806
      return;
807
    }
Daniel Colascione's avatar
Daniel Colascione committed
808 809

  /* Look for a dump file in the same directory as the executable; it
810 811 812 813 814
     should have the same basename.  Take care to search PATH to find
     the executable if needed.  We're too early in init to use Lisp,
     so we can't use decode_env_path.  We're working in whatever
     encoding the system natively uses for filesystem access, so
     there's no need for character set conversion.  */
815 816
  ptrdiff_t bufsize;
  dump_file = load_pdump_find_executable (argv[0], &bufsize);
Daniel Colascione's avatar
Daniel Colascione committed
817

818 819
  /* If we couldn't find our executable, go straight to looking for
     the dump in the hardcoded location.  */
820
  if (dump_file && *dump_file)
821
    {
822
#ifdef WINDOWSNT
823 824
      /* w32_my_exename resolves symlinks internally, so no need to
	 call realpath.  */
825
#else
826
      char *real_exename = realpath (dump_file, NULL);
827 828
      if (!real_exename)
        fatal ("could not resolve realpath of \"%s\": %s",
829 830 831 832 833 834 835
               dump_file, strerror (errno));
      xfree (dump_file);
      dump_file = real_exename;
#endif
      ptrdiff_t exenamelen = strlen (dump_file);
#ifndef WINDOWSNT
      bufsize = exenamelen + 1;
836
#endif
837 838
      if (strip_suffix)
        {
839 840 841 842 843 844
	  ptrdiff_t strip_suffix_length = strlen (strip_suffix);
	  ptrdiff_t prefix_length = exenamelen - strip_suffix_length;
	  if (0 <= prefix_length
	      && !memcmp (&dump_file[prefix_length], strip_suffix,
			  strip_suffix_length))
	    exenamelen = prefix_length;
845
        }
846 847 848 849
      ptrdiff_t needed = exenamelen + strlen (suffix) + 1;
      if (bufsize < needed)
	dump_file = xpalloc (dump_file, &bufsize, needed - bufsize, -1, 1);
      strcpy (dump_file + exenamelen, suffix);
850 851 852 853 854 855 856 857
      result = pdumper_load (dump_file);
      if (result == PDUMPER_LOAD_SUCCESS)
        goto out;

      if (result != PDUMPER_LOAD_FILE_NOT_FOUND)
        fatal ("could not load dump file \"%s\": %s",
               dump_file, dump_error_to_string (result));
    }
Daniel Colascione's avatar
Daniel Colascione committed
858 859 860 861 862 863

#ifdef WINDOWSNT
  /* On MS-Windows, PATH_EXEC normally starts with a literal
     "%emacs_dir%", so it will never work without some tweaking.  */
  path_exec = w32_relocate (path_exec);
#endif
864 865 866 867 868

  /* Look for "emacs.pdmp" in PATH_EXEC.  We hardcode "emacs" in
     "emacs.pdmp" so that the Emacs binary still works if the user
     copies and renames it.  */
  const char *argv0_base = "emacs";
869
  ptrdiff_t needed = (strlen (path_exec)
Daniel Colascione's avatar
Daniel Colascione committed
870 871 872 873
                      + 1
                      + strlen (argv0_base)
                      + strlen (suffix)
                      + 1);
874 875 876 877 878
  if (bufsize < needed)
    {
      xfree (dump_file);
      dump_file = xpalloc (NULL, &bufsize, needed - bufsize, -1, 1);
    }
Daniel Colascione's avatar
Daniel Colascione committed
879 880 881
  sprintf (dump_file, "%s%c%s%s",
           path_exec, DIRECTORY_SEP, argv0_base, suffix);
  result = pdumper_load (dump_file);
882

883
  if (result == PDUMPER_LOAD_FILE_NOT_FOUND)
884
    {
885
      /* Finally, look for basename(argv0)+".pdmp" in PATH_EXEC.
886 887 888 889
	 This way, they can rename both the executable and its pdump
	 file in PATH_EXEC, and have several Emacs configurations in
	 the same versioned libexec subdirectory.  */
      char *p, *last_sep = NULL;
890
      for (p = argv[0]; *p; p++)
891 892 893 894
	{
	  if (IS_DIRECTORY_SEP (*p))
	    last_sep = p;
	}
895
      argv0_base = last_sep ? last_sep + 1 : argv[0];
896
      ptrdiff_t needed = (strlen (path_exec)
897 898 899 900
			  + 1
			  + strlen (argv0_base)
			  + strlen (suffix)
			  + 1);
901 902 903 904 905
      if (bufsize < needed)
	{
	  xfree (dump_file);
	  dump_file = xmalloc (needed);
	}
906
#ifdef DOS_NT
907
      ptrdiff_t argv0_len = strlen (argv0_base);
908 909 910 911 912 913 914 915 916 917
      if (argv0_len >= 4
	  && c_strcasecmp (argv0_base + argv0_len - 4, ".exe") == 0)
	sprintf (dump_file, "%s%c%.*s%s", path_exec, DIRECTORY_SEP,
		 (int)(argv0_len - 4), argv0_base, suffix);
      else
#endif
      sprintf (dump_file, "%s%c%s%s",
	       path_exec, DIRECTORY_SEP, argv0_base, suffix);
      result = pdumper_load (dump_file);
    }
918

Daniel Colascione's avatar
Daniel Colascione committed
919
  if (result != PDUMPER_LOAD_SUCCESS)
Eli Zaretskii's avatar
Eli Zaretskii committed
920 921 922 923 924
    {
      if (result != PDUMPER_LOAD_FILE_NOT_FOUND)
	fatal ("could not load dump file \"%s\": %s",
	       dump_file, dump_error_to_string (result));
    }
Daniel Colascione's avatar
Daniel Colascione committed
925 926

 out:
927
  xfree (dump_file);
Daniel Colascione's avatar
Daniel Colascione committed
928 929 930
}
#endif /* HAVE_PDUMPER */

931
int
Dan Nicolaescu's avatar
Dan Nicolaescu committed
932
main (int argc, char **argv)
933
{
Paul Eggert's avatar
Paul Eggert committed
934 935 936 937
  /* Variable near the bottom of the stack, and aligned appropriately
     for pointers.  */
  void *stack_bottom_variable;

938
  bool do_initial_setlocale;
939
  bool no_loadup = false;
Richard M. Stallman's avatar
Richard M. Stallman committed
940
  char *junk = 0;
941
  char *dname_arg = 0;
942
#ifdef DAEMON_MUST_EXEC
943 944
  char dname_arg2[80];
#endif
945
  char *ch_to_dir = 0;
946

947
  /* If we use --chdir, this records the original directory.  */
948
  char const *original_pwd = 0;
949

950
  /* Record (approximately) where the stack begins.  */
Paul Eggert's avatar
Paul Eggert committed
951
  stack_bottom = (char *) &stack_bottom_variable;
952

Daniel Colascione's avatar
Daniel Colascione committed
953
  const char *dump_mode = NULL;
954 955 956 957 958 959 960 961 962
  int skip_args = 0;
  char *temacs = NULL;
  while (skip_args < argc - 1)
    {
      if (argmatch (argv, argc, "-temacs", "--temacs", 8, &temacs, &skip_args)
	  || argmatch (argv, argc, "--", NULL, 2, NULL, &skip_args))
	break;
      skip_args++;
    }
Daniel Colascione's avatar
Daniel Colascione committed