sysdep.c 98 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Interfaces to system-dependent kernel and library entries.
2
   Copyright (C) 1985-1988, 1993-1995, 1999-2014 Free Software
3
   Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
4 5 6

This file is part of GNU Emacs.

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

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
18
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
19

Pavel Janík's avatar
Pavel Janík committed
20
#include <config.h>
21

22 23 24 25 26 27 28 29
/* If HYBRID_GET_CURRENT_DIR_NAME is defined in conf_post.h, then we
   need the following before including unistd.h, in order to pick up
   the right prototype for gget_current_dir_name.  */
#ifdef HYBRID_GET_CURRENT_DIR_NAME
#undef get_current_dir_name
#define get_current_dir_name gget_current_dir_name
#endif

30
#include <execinfo.h>
31
#include "sysstdio.h"
32 33 34 35 36
#ifdef HAVE_PWD_H
#include <pwd.h>
#include <grp.h>
#endif /* HAVE_PWD_H */
#include <limits.h>
37
#include <unistd.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
38

39
#include <c-ctype.h>
40
#include <utimens.h>
41

Jim Blandy's avatar
Jim Blandy committed
42
#include "lisp.h"
43
#include "sysselect.h"
44
#include "blockinput.h"
Jim Blandy's avatar
Jim Blandy committed
45

46 47
#if defined DARWIN_OS || defined __FreeBSD__
# include <sys/sysctl.h>
Paul Eggert's avatar
Paul Eggert committed
48 49 50
#endif

#ifdef __FreeBSD__
51 52 53 54 55 56 57
/* Sparc/ARM machine/frame.h has 'struct frame' which conflicts with Emacs's
   'struct frame', so rename it.  */
# define frame freebsd_frame
# include <sys/user.h>
# undef frame

# include <math.h>
58 59
#endif

60
#ifdef WINDOWSNT
61 62
#define read sys_read
#define write sys_write
63 64 65
#ifndef STDERR_FILENO
#define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
#endif
66 67 68
#include <windows.h>
#endif /* not WINDOWSNT */

Jim Blandy's avatar
Jim Blandy committed
69 70 71 72
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

73 74 75 76 77
/* Get SI_SRPC_DOMAIN, if it is available.  */
#ifdef HAVE_SYS_SYSTEMINFO_H
#include <sys/systeminfo.h>
#endif

78 79
#ifdef MSDOS	/* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
#include "msdos.h"
80
#endif
81

82 83 84
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
85
#include <sys/param.h>
86 87
#include <sys/file.h>
#include <fcntl.h>
Jim Blandy's avatar
Jim Blandy committed
88

89
#include "systty.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
90
#include "syswait.h"
Jim Blandy's avatar
Jim Blandy committed
91

Dan Nicolaescu's avatar
Dan Nicolaescu committed
92
#ifdef HAVE_SYS_UTSNAME_H
Jim Blandy's avatar
Jim Blandy committed
93 94
#include <sys/utsname.h>
#include <memory.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
95
#endif /* HAVE_SYS_UTSNAME_H */
Jim Blandy's avatar
Jim Blandy committed
96

97
#include "keyboard.h"
Jim Blandy's avatar
Jim Blandy committed
98
#include "frame.h"
Jim Blandy's avatar
Jim Blandy committed
99 100 101 102 103 104
#include "window.h"
#include "termhooks.h"
#include "termchar.h"
#include "termopts.h"
#include "dispextern.h"
#include "process.h"
Karoly Lorentey's avatar
Karoly Lorentey committed
105
#include "cm.h"  /* for reset_sys_modes */
Jim Blandy's avatar
Jim Blandy committed
106

107 108 109 110
#ifdef WINDOWSNT
#include <direct.h>
/* In process.h which conflicts with the local copy.  */
#define _P_WAIT 0
111 112
int _cdecl _spawnlp (int, const char *, const char *, ...);
int _cdecl _getpid (void);
113 114
#endif

Jim Blandy's avatar
Jim Blandy committed
115 116
#include "syssignal.h"
#include "systime.h"
Jim Blandy's avatar
Jim Blandy committed
117

118 119 120 121 122
/* ULLONG_MAX is missing on Red Hat Linux 7.3; see Bug#11781.  */
#ifndef ULLONG_MAX
#define ULLONG_MAX TYPE_MAXIMUM (unsigned long long int)
#endif

Dan Nicolaescu's avatar
Dan Nicolaescu committed
123 124 125
/* Declare here, including term.h is problematic on some systems.  */
extern void tputs (const char *, int, int (*)(int));

126
static const int baud_convert[] =
Jim Blandy's avatar
Jim Blandy committed
127 128 129 130 131
  {
    0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
    1800, 2400, 4800, 9600, 19200, 38400
  };

132 133
#if !defined HAVE_GET_CURRENT_DIR_NAME || defined BROKEN_GET_CURRENT_DIR_NAME \
  || (defined HYBRID_GET_CURRENT_DIR_NAME)
134
/* Return the current working directory.  Returns NULL on errors.
135 136
   Any other returned value must be freed with free. This is used
   only when get_current_dir_name is not defined on the system.  */
137
char *
138
get_current_dir_name (void)
139 140
{
  char *buf;
141
  char *pwd = getenv ("PWD");
142
  struct stat dotstat, pwdstat;
143
  /* If PWD is accurate, use it instead of calling getcwd.  PWD is
144 145
     sometimes a nicer name, and using it may avoid a fatal error if a
     parent directory is searchable but not readable.  */
146
  if (pwd
147 148 149 150 151 152 153 154 155 156
      && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
      && stat (pwd, &pwdstat) == 0
      && stat (".", &dotstat) == 0
      && dotstat.st_ino == pwdstat.st_ino
      && dotstat.st_dev == pwdstat.st_dev
#ifdef MAXPATHLEN
      && strlen (pwd) < MAXPATHLEN
#endif
      )
    {
157
      buf = malloc (strlen (pwd) + 1);
158 159 160 161 162 163 164
      if (!buf)
        return NULL;
      strcpy (buf, pwd);
    }
  else
    {
      size_t buf_size = 1024;
165
      buf = malloc (buf_size);
166 167 168 169 170 171 172 173 174 175 176 177 178 179
      if (!buf)
        return NULL;
      for (;;)
        {
          if (getcwd (buf, buf_size) == buf)
            break;
          if (errno != ERANGE)
            {
              int tmp_errno = errno;
              free (buf);
              errno = tmp_errno;
              return NULL;
            }
          buf_size *= 2;
180
          buf = realloc (buf, buf_size);
181 182 183 184 185 186 187 188
          if (!buf)
            return NULL;
        }
    }
  return buf;
}
#endif

189

190
/* Discard pending input on all input descriptors.  */
Jim Blandy's avatar
Jim Blandy committed
191

192
void
193
discard_tty_input (void)
Jim Blandy's avatar
Jim Blandy committed
194
{
195
#ifndef WINDOWSNT
Jim Blandy's avatar
Jim Blandy committed
196
  struct emacs_tty buf;
Jim Blandy's avatar
Jim Blandy committed
197 198 199 200

  if (noninteractive)
    return;

201
#ifdef MSDOS    /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
202
  while (dos_keyread () != -1)
203
    ;
204
#else /* not MSDOS */
205
  {
206
    struct tty_display_info *tty;
207 208
    for (tty = tty_list; tty; tty = tty->next)
      {
209 210
        if (tty->input)         /* Is the device suspended? */
          {
Dan Nicolaescu's avatar
Dan Nicolaescu committed
211 212
            emacs_get_tty (fileno (tty->input), &buf);
            emacs_set_tty (fileno (tty->input), &buf, 0);
213
          }
214 215
      }
  }
216
#endif /* not MSDOS */
217
#endif /* not WINDOWSNT */
Jim Blandy's avatar
Jim Blandy committed
218 219
}

220

Jim Blandy's avatar
Jim Blandy committed
221 222
#ifdef SIGTSTP

223
/* Arrange for character C to be read as the next input from
224 225 226
   the terminal.
   XXX What if we have multiple ttys?
*/
227

Andreas Schwab's avatar
Andreas Schwab committed
228
void
229
stuff_char (char c)
Jim Blandy's avatar
Jim Blandy committed
230
{
231 232 233
  if (! (FRAMEP (selected_frame)
	 && FRAME_LIVE_P (XFRAME (selected_frame))
	 && FRAME_TERMCAP_P (XFRAME (selected_frame))))
234 235
    return;

Jim Blandy's avatar
Jim Blandy committed
236 237
/* Should perhaps error if in batch mode */
#ifdef TIOCSTI
238
  ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
Jim Blandy's avatar
Jim Blandy committed
239
#else /* no TIOCSTI */
240
  error ("Cannot stuff terminal input characters in this version of Unix");
Jim Blandy's avatar
Jim Blandy committed
241 242 243 244
#endif /* no TIOCSTI */
}

#endif /* SIGTSTP */
245

246
void
247
init_baud_rate (int fd)
Jim Blandy's avatar
Jim Blandy committed
248
{
Dan Nicolaescu's avatar
Dan Nicolaescu committed
249
  int emacs_ospeed;
250

Jim Blandy's avatar
Jim Blandy committed
251
  if (noninteractive)
Gerd Moellmann's avatar
Gerd Moellmann committed
252
    emacs_ospeed = 0;
Jim Blandy's avatar
Jim Blandy committed
253 254
  else
    {
255
#ifdef DOS_NT
Gerd Moellmann's avatar
Gerd Moellmann committed
256
    emacs_ospeed = 15;
257
#else  /* not DOS_NT */
258
      struct termios sg;
Jim Blandy's avatar
Jim Blandy committed
259

260
      sg.c_cflag = B9600;
261
      tcgetattr (fd, &sg);
Gerd Moellmann's avatar
Gerd Moellmann committed
262
      emacs_ospeed = cfgetospeed (&sg);
263
#endif /* not DOS_NT */
Jim Blandy's avatar
Jim Blandy committed
264
    }
265

266
  baud_rate = (emacs_ospeed < ARRAYELTS (baud_convert)
Gerd Moellmann's avatar
Gerd Moellmann committed
267
	       ? baud_convert[emacs_ospeed] : 9600);
Jim Blandy's avatar
Jim Blandy committed
268 269 270 271
  if (baud_rate == 0)
    baud_rate = 1200;
}

272

Jim Blandy's avatar
Jim Blandy committed
273

274
#ifndef MSDOS
Jim Blandy's avatar
Jim Blandy committed
275

276 277 278 279 280 281 282 283 284 285 286
/* Wait for the subprocess with process id CHILD to terminate or change status.
   CHILD must be a child process that has not been reaped.
   If STATUS is non-null, store the waitpid-style exit status into *STATUS
   and tell wait_reading_process_output that it needs to look around.
   Use waitpid-style OPTIONS when waiting.
   If INTERRUPTIBLE, this function is interruptible by a signal.

   Return CHILD if successful, 0 if no status is available;
   the latter is possible only when options & NOHANG.  */
static pid_t
get_child_status (pid_t child, int *status, int options, bool interruptible)
Jim Blandy's avatar
Jim Blandy committed
287
{
288 289 290 291 292 293 294
  pid_t pid;

  /* Invoke waitpid only with a known process ID; do not invoke
     waitpid with a nonpositive argument.  Otherwise, Emacs might
     reap an unwanted process by mistake.  For example, invoking
     waitpid (-1, ...) can mess up glib by reaping glib's subprocesses,
     so that another thread running glib won't find them.  */
295
  eassert (child > 0);
296 297

  while ((pid = waitpid (child, status, options)) < 0)
Jim Blandy's avatar
Jim Blandy committed
298
    {
299 300 301 302 303 304
      /* Check that CHILD is a child process that has not been reaped,
	 and that STATUS and OPTIONS are valid.  Otherwise abort,
	 as continuing after this internal error could cause Emacs to
	 become confused and kill innocent-victim processes.  */
      if (errno != EINTR)
	emacs_abort ();
305

306 307
      /* Note: the MS-Windows emulation of waitpid calls QUIT
	 internally.  */
308 309
      if (interruptible)
	QUIT;
Jim Blandy's avatar
Jim Blandy committed
310 311
    }

312 313 314
  /* If successful and status is requested, tell wait_reading_process_output
     that it needs to wake up and look around.  */
  if (pid && status && input_available_clear_time)
315
    *input_available_clear_time = make_timespec (0, 0);
316

317 318 319 320 321 322 323 324
  return pid;
}

/* Wait for the subprocess with process id CHILD to terminate.
   CHILD must be a child process that has not been reaped.
   If STATUS is non-null, store the waitpid-style exit status into *STATUS
   and tell wait_reading_process_output that it needs to look around.
   If INTERRUPTIBLE, this function is interruptible by a signal.  */
325
void
326
wait_for_termination (pid_t child, int *status, bool interruptible)
327
{
328
  get_child_status (child, status, 0, interruptible);
329 330
}

331 332 333 334 335 336 337 338 339 340 341
/* Report whether the subprocess with process id CHILD has changed status.
   Termination counts as a change of status.
   CHILD must be a child process that has not been reaped.
   If STATUS is non-null, store the waitpid-style exit status into *STATUS
   and tell wait_reading_process_output that it needs to look around.
   Use waitpid-style OPTIONS to check status, but do not wait.

   Return CHILD if successful, 0 if no status is available because
   the process's state has not changed.  */
pid_t
child_status_changed (pid_t child, int *status, int options)
342
{
343
  return get_child_status (child, status, WNOHANG | options, 0);
344 345
}

346

Jim Blandy's avatar
Jim Blandy committed
347 348 349 350 351
/*  Set up the terminal at the other end of a pseudo-terminal that
    we will be controlling an inferior through.
    It should not echo or do line-editing, since that is done
    in Emacs.  No padding needed for insertion into an Emacs buffer.  */

352
void
353
child_setup_tty (int out)
Jim Blandy's avatar
Jim Blandy committed
354
{
355
#ifndef WINDOWSNT
Jim Blandy's avatar
Jim Blandy committed
356 357
  struct emacs_tty s;

Dan Nicolaescu's avatar
Dan Nicolaescu committed
358
  emacs_get_tty (out, &s);
Jim Blandy's avatar
Jim Blandy committed
359 360
  s.main.c_oflag |= OPOST;	/* Enable output postprocessing */
  s.main.c_oflag &= ~ONLCR;	/* Disable map of NL to CR-NL on output */
361
#ifdef NLDLY
362 363 364
  /* http://lists.gnu.org/archive/html/emacs-devel/2008-05/msg00406.html
     Some versions of GNU Hurd do not have FFDLY?  */
#ifdef FFDLY
Jim Blandy's avatar
Jim Blandy committed
365 366
  s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
  				/* No output delays */
367 368 369 370
#else
  s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
  				/* No output delays */
#endif
371
#endif
Jim Blandy's avatar
Jim Blandy committed
372 373
  s.main.c_lflag &= ~ECHO;	/* Disable echo */
  s.main.c_lflag |= ISIG;	/* Enable signals */
374 375 376
#ifdef IUCLC
  s.main.c_iflag &= ~IUCLC;	/* Disable downcasing on input.  */
#endif
377 378 379
#ifdef ISTRIP
  s.main.c_iflag &= ~ISTRIP;	/* don't strip 8th bit on input */
#endif
380
#ifdef OLCUC
381 382
  s.main.c_oflag &= ~OLCUC;	/* Disable upcasing on output.  */
#endif
383
  s.main.c_oflag &= ~TAB3;	/* Disable tab expansion */
384
  s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
385 386
  s.main.c_cc[VERASE] = CDISABLE;	/* disable erase processing */
  s.main.c_cc[VKILL] = CDISABLE;	/* disable kill processing */
Jim Blandy's avatar
Jim Blandy committed
387

Jim Blandy's avatar
Jim Blandy committed
388
#ifdef HPUX
Jim Blandy's avatar
Jim Blandy committed
389
  s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
Jim Blandy's avatar
Jim Blandy committed
390
#endif /* HPUX */
Jim Blandy's avatar
Jim Blandy committed
391

392 393 394
#ifdef SIGNALS_VIA_CHARACTERS
  /* the QUIT and INTR character are used in process_send_signal
     so set them here to something useful.  */
395
  if (s.main.c_cc[VQUIT] == CDISABLE)
396
    s.main.c_cc[VQUIT] = '\\'&037;	/* Control-\ */
397
  if (s.main.c_cc[VINTR] == CDISABLE)
398 399 400
    s.main.c_cc[VINTR] = 'C'&037;	/* Control-C */
#endif /* not SIGNALS_VIA_CHARACTERS */

Jim Blandy's avatar
Jim Blandy committed
401 402 403
#ifdef AIX
  /* Also, PTY overloads NUL and BREAK.
     don't ignore break, but don't signal either, so it looks like NUL.  */
Jim Blandy's avatar
Jim Blandy committed
404 405
  s.main.c_iflag &= ~IGNBRK;
  s.main.c_iflag &= ~BRKINT;
406 407 408
  /* rms: Formerly it set s.main.c_cc[VINTR] to 0377 here
     unconditionally.  Then a SIGNALS_VIA_CHARACTERS conditional
     would force it to 0377.  That looks like duplicated code.  */
Jim Blandy's avatar
Jim Blandy committed
409
  s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
Jim Blandy's avatar
Jim Blandy committed
410 411
#endif /* AIX */

412
  /* We originally enabled ICANON (and set VEOF to 04), and then had
Paul Eggert's avatar
Paul Eggert committed
413
     process.c send additional EOF chars to flush the output when faced
414
     with long lines, but this leads to weird effects when the
415 416
     subprocess has disabled ICANON and ends up seeing those spurious
     extra EOFs.  So we don't send EOFs any more in
417 418 419 420 421 422 423 424 425 426 427
     process.c:send_process.  First we tried to disable ICANON by
     default, so if a subsprocess sets up ICANON, it's his problem (or
     the Elisp package that talks to it) to deal with lines that are
     too long.  But this disables some features, such as the ability
     to send EOF signals.  So we re-enabled ICANON but there is no
     more "send eof to flush" going on (which is wrong and unportable
     in itself).  The correct way to handle too much output is to
     buffer what could not be written and then write it again when
     select returns ok for writing.  This has it own set of
     problems.  Write is now asynchronous, is that a problem?  How much
     do we buffer, and what do we do when that limit is reached?  */
428 429 430

  s.main.c_lflag |= ICANON;	/* Enable line editing and eof processing */
  s.main.c_cc[VEOF] = 'D'&037;	/* Control-D */
Nick Roberts's avatar
Nick Roberts committed
431
#if 0	    /* These settings only apply to non-ICANON mode. */
432 433
  s.main.c_cc[VMIN] = 1;
  s.main.c_cc[VTIME] = 0;
434
#endif
435

Dan Nicolaescu's avatar
Dan Nicolaescu committed
436
  emacs_set_tty (out, &s, 0);
437
#endif /* not WINDOWSNT */
Jim Blandy's avatar
Jim Blandy committed
438
}
Dan Nicolaescu's avatar
Dan Nicolaescu committed
439
#endif	/* not MSDOS */
Jim Blandy's avatar
Jim Blandy committed
440

441

Paul Eggert's avatar
Paul Eggert committed
442
/* Record a signal code and the action for it.  */
Jim Blandy's avatar
Jim Blandy committed
443 444 445
struct save_signal
{
  int code;
Paul Eggert's avatar
Paul Eggert committed
446
  struct sigaction action;
Jim Blandy's avatar
Jim Blandy committed
447 448
};

449 450
static void save_signal_handlers (struct save_signal *);
static void restore_signal_handlers (struct save_signal *);
Andreas Schwab's avatar
Andreas Schwab committed
451

Jim Blandy's avatar
Jim Blandy committed
452 453
/* Suspend the Emacs process; give terminal to its superior.  */

454
void
455
sys_suspend (void)
Jim Blandy's avatar
Jim Blandy committed
456
{
457 458 459
#ifndef DOS_NT
  kill (0, SIGTSTP);
#else
Jim Blandy's avatar
Jim Blandy committed
460 461 462
/* On a system where suspending is not implemented,
   instead fork a subshell and let it talk directly to the terminal
   while we wait.  */
463 464
  sys_subshell ();

465
#endif
466 467 468 469
}

/* Fork a subshell.  */

470
void
471
sys_subshell (void)
472
{
473
#ifdef DOS_NT	/* Demacs 1.1.2 91/10/20 Manabu Higashida */
474
  int st;
475
#ifdef MSDOS
476
  char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS.  */
477 478 479
#else
  char oldwd[MAX_UTF8_PATH];
#endif
480
#endif
481
  pid_t pid;
482
  int status;
Jim Blandy's avatar
Jim Blandy committed
483
  struct save_signal saved_handlers[5];
484 485 486 487 488 489 490 491 492 493 494 495 496 497
  char *str = SSDATA (encode_current_directory ());

#ifdef DOS_NT
  pid = 0;
#else
  {
    char *volatile str_volatile = str;
    pid = vfork ();
    str = str_volatile;
  }
#endif

  if (pid < 0)
    error ("Can't spawn subshell");
Jim Blandy's avatar
Jim Blandy committed
498 499 500 501

  saved_handlers[0].code = SIGINT;
  saved_handlers[1].code = SIGQUIT;
  saved_handlers[2].code = SIGTERM;
Paul Eggert's avatar
Paul Eggert committed
502
#ifdef USABLE_SIGIO
Jim Blandy's avatar
Jim Blandy committed
503 504 505 506 507 508
  saved_handlers[3].code = SIGIO;
  saved_handlers[4].code = 0;
#else
  saved_handlers[3].code = 0;
#endif

509
#ifdef DOS_NT
510
  save_signal_handlers (saved_handlers);
511 512
#endif

Jim Blandy's avatar
Jim Blandy committed
513 514
  if (pid == 0)
    {
515
      const char *sh = 0;
Jim Blandy's avatar
Jim Blandy committed
516

517
#ifdef DOS_NT    /* MW, Aug 1993 */
518
      getcwd (oldwd, sizeof oldwd);
519
      if (sh == 0)
Paul Eggert's avatar
Paul Eggert committed
520
	sh = egetenv ("SUSPEND");	/* KFS, 1994-12-14 */
521
#endif
522
      if (sh == 0)
Paul Eggert's avatar
Paul Eggert committed
523
	sh = egetenv ("SHELL");
Jim Blandy's avatar
Jim Blandy committed
524 525
      if (sh == 0)
	sh = "sh";
526

Jim Blandy's avatar
Jim Blandy committed
527
      /* Use our buffer's default directory for the subshell.  */
528
      if (chdir (str) != 0)
Paul Eggert's avatar
Paul Eggert committed
529 530
	{
#ifndef DOS_NT
531
	  emacs_perror (str);
532
	  _exit (EXIT_CANCELED);
Paul Eggert's avatar
Paul Eggert committed
533 534
#endif
	}
535

536
#ifdef MSDOS    /* Demacs 1.1.2 91/10/20 Manabu Higashida */
537
      {
538 539
	char *epwd = getenv ("PWD");
	char old_pwd[MAXPATHLEN+1+4];
540 541

	/* If PWD is set, pass it with corrected value.  */
542
	if (epwd)
543
	  {
544
	    strcpy (old_pwd, epwd);
545 546 547
	    setenv ("PWD", str, 1);
	  }
	st = system (sh);
Paul Eggert's avatar
Paul Eggert committed
548
	chdir (oldwd);	/* FIXME: Do the right thing on chdir failure.  */
549
	if (epwd)
550 551
	  putenv (old_pwd);	/* restore previous value */
      }
552
#else /* not MSDOS */
553 554 555
#ifdef  WINDOWSNT
      /* Waits for process completion */
      pid = _spawnlp (_P_WAIT, sh, sh, NULL);
Paul Eggert's avatar
Paul Eggert committed
556
      chdir (oldwd);	/* FIXME: Do the right thing on chdir failure.  */
557 558 559
      if (pid == -1)
	write (1, "Can't execute subshell", 22);
#else   /* not WINDOWSNT */
560
      execlp (sh, sh, (char *) 0);
561 562
      emacs_perror (sh);
      _exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
563
#endif  /* not WINDOWSNT */
564
#endif /* not MSDOS */
Jim Blandy's avatar
Jim Blandy committed
565 566
    }

567
  /* Do this now if we did not do it before.  */
568
#ifndef MSDOS
Jim Blandy's avatar
Jim Blandy committed
569
  save_signal_handlers (saved_handlers);
570 571
#endif

572
#ifndef DOS_NT
573
  wait_for_termination (pid, &status, 0);
574
#endif
Jim Blandy's avatar
Jim Blandy committed
575 576 577
  restore_signal_handlers (saved_handlers);
}

Andreas Schwab's avatar
Andreas Schwab committed
578
static void
579
save_signal_handlers (struct save_signal *saved_handlers)
Jim Blandy's avatar
Jim Blandy committed
580 581 582
{
  while (saved_handlers->code)
    {
Paul Eggert's avatar
Paul Eggert committed
583 584 585
      struct sigaction action;
      emacs_sigaction_init (&action, SIG_IGN);
      sigaction (saved_handlers->code, &action, &saved_handlers->action);
Jim Blandy's avatar
Jim Blandy committed
586 587 588 589
      saved_handlers++;
    }
}

Andreas Schwab's avatar
Andreas Schwab committed
590
static void
591
restore_signal_handlers (struct save_signal *saved_handlers)
Jim Blandy's avatar
Jim Blandy committed
592 593 594
{
  while (saved_handlers->code)
    {
Paul Eggert's avatar
Paul Eggert committed
595
      sigaction (saved_handlers->code, &saved_handlers->action, 0);
Jim Blandy's avatar
Jim Blandy committed
596 597 598 599
      saved_handlers++;
    }
}

Paul Eggert's avatar
Paul Eggert committed
600
#ifdef USABLE_SIGIO
601
static int old_fcntl_flags[FD_SETSIZE];
Paul Eggert's avatar
Paul Eggert committed
602
#endif
Jim Blandy's avatar
Jim Blandy committed
603

604
void
605
init_sigio (int fd)
Jim Blandy's avatar
Jim Blandy committed
606
{
Paul Eggert's avatar
Paul Eggert committed
607
#ifdef USABLE_SIGIO
608 609
  old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
  fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
610
  interrupts_deferred = 0;
Paul Eggert's avatar
Paul Eggert committed
611
#endif
Jim Blandy's avatar
Jim Blandy committed
612 613
}

614
#ifndef DOS_NT
615
static void
616
reset_sigio (int fd)
Jim Blandy's avatar
Jim Blandy committed
617
{
Paul Eggert's avatar
Paul Eggert committed
618
#ifdef USABLE_SIGIO
619
  fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
620
#endif
Jim Blandy's avatar
Jim Blandy committed
621
}
622
#endif
Jim Blandy's avatar
Jim Blandy committed
623

624
void
625
request_sigio (void)
Jim Blandy's avatar
Jim Blandy committed
626
{
Paul Eggert's avatar
Paul Eggert committed
627
#ifdef USABLE_SIGIO
Paul Eggert's avatar
Paul Eggert committed
628 629
  sigset_t unblocked;

630
  if (noninteractive)
631 632
    return;

Paul Eggert's avatar
Paul Eggert committed
633
  sigemptyset (&unblocked);
Paul Eggert's avatar
Paul Eggert committed
634
# ifdef SIGWINCH
Paul Eggert's avatar
Paul Eggert committed
635
  sigaddset (&unblocked, SIGWINCH);
Paul Eggert's avatar
Paul Eggert committed
636
# endif
Paul Eggert's avatar
Paul Eggert committed
637 638
  sigaddset (&unblocked, SIGIO);
  pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
Jim Blandy's avatar
Jim Blandy committed
639 640

  interrupts_deferred = 0;
Paul Eggert's avatar
Paul Eggert committed
641
#endif
Jim Blandy's avatar
Jim Blandy committed
642 643
}

644
void
Karoly Lorentey's avatar
Karoly Lorentey committed
645
unrequest_sigio (void)
646
{
Paul Eggert's avatar
Paul Eggert committed
647
#ifdef USABLE_SIGIO
Paul Eggert's avatar
Paul Eggert committed
648 649
  sigset_t blocked;

650 651 652
  if (noninteractive)
    return;

Paul Eggert's avatar
Paul Eggert committed
653
  sigemptyset (&blocked);
Paul Eggert's avatar
Paul Eggert committed
654
# ifdef SIGWINCH
Paul Eggert's avatar
Paul Eggert committed
655
  sigaddset (&blocked, SIGWINCH);
Paul Eggert's avatar
Paul Eggert committed
656
# endif
Paul Eggert's avatar
Paul Eggert committed
657 658
  sigaddset (&blocked, SIGIO);
  pthread_sigmask (SIG_BLOCK, &blocked, 0);
Jim Blandy's avatar
Jim Blandy committed
659
  interrupts_deferred = 1;
Paul Eggert's avatar
Paul Eggert committed
660
#endif
Jim Blandy's avatar
Jim Blandy committed
661
}
662

663
void
Paul Eggert's avatar
Paul Eggert committed
664
ignore_sigio (void)
Jim Blandy's avatar
Jim Blandy committed
665
{
Paul Eggert's avatar
Paul Eggert committed
666 667 668
#ifdef USABLE_SIGIO
  signal (SIGIO, SIG_IGN);
#endif
Jim Blandy's avatar
Jim Blandy committed
669
}
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690

#ifndef MSDOS
/* Block SIGCHLD.  */

void
block_child_signal (sigset_t *oldset)
{
  sigset_t blocked;
  sigemptyset (&blocked);
  sigaddset (&blocked, SIGCHLD);
  sigaddset (&blocked, SIGINT);
  pthread_sigmask (SIG_BLOCK, &blocked, oldset);
}

/* Unblock SIGCHLD.  */

void
unblock_child_signal (sigset_t const *oldset)
{
  pthread_sigmask (SIG_SETMASK, oldset, 0);
}
691

692
#endif	/* !MSDOS */
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719

/* Saving and restoring the process group of Emacs's terminal.  */

/* The process group of which Emacs was a member when it initially
   started.

   If Emacs was in its own process group (i.e. inherited_pgroup ==
   getpid ()), then we know we're running under a shell with job
   control (Emacs would never be run as part of a pipeline).
   Everything is fine.

   If Emacs was not in its own process group, then we know we're
   running under a shell (or a caller) that doesn't know how to
   separate itself from Emacs (like sh).  Emacs must be in its own
   process group in order to receive SIGIO correctly.  In this
   situation, we put ourselves in our own pgroup, forcibly set the
   tty's pgroup to our pgroup, and make sure to restore and reinstate
   the tty's pgroup just like any other terminal setting.  If
   inherited_group was not the tty's pgroup, then we'll get a
   SIGTTmumble when we try to change the tty's pgroup, and a CONT if
   it goes foreground in the future, which is what should happen.  */

static pid_t inherited_pgroup;

void
init_foreground_group (void)
{
720
  pid_t pgrp = getpgrp ();
721 722 723
  inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
}

724 725 726
/* Block and unblock SIGTTOU.  */

void
727
block_tty_out_signal (sigset_t *oldset)
728 729 730 731 732
{
#ifdef SIGTTOU
  sigset_t blocked;
  sigemptyset (&blocked);
  sigaddset (&blocked, SIGTTOU);
733
  pthread_sigmask (SIG_BLOCK, &blocked, oldset);
734 735 736 737
#endif
}

void
738
unblock_tty_out_signal (sigset_t const *oldset)
739 740
{
#ifdef SIGTTOU
741
  pthread_sigmask (SIG_SETMASK, oldset, 0);
742 743 744
#endif
}

745 746 747 748 749 750 751 752 753 754 755
/* Safely set a controlling terminal FD's process group to PGID.
   If we are not in the foreground already, POSIX requires tcsetpgrp
   to deliver a SIGTTOU signal, which would stop us.  This is an
   annoyance, so temporarily ignore the signal.

   In practice, platforms lacking SIGTTOU also lack tcsetpgrp, so
   skip all this unless SIGTTOU is defined.  */
static void
tcsetpgrp_without_stopping (int fd, pid_t pgid)
{
#ifdef SIGTTOU
756
  sigset_t oldset;
757
  block_input ();
758
  block_tty_out_signal (&oldset);
759
  tcsetpgrp (fd, pgid);
760
  unblock_tty_out_signal (&oldset);
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
  unblock_input ();
#endif
}

/* Split off the foreground process group to Emacs alone.  When we are
   in the foreground, but not started in our own process group,
   redirect the tty device handle FD to point to our own process
   group.  FD must be the file descriptor of the controlling tty.  */
static void
narrow_foreground_group (int fd)
{
  if (inherited_pgroup && setpgid (0, 0) == 0)
    tcsetpgrp_without_stopping (fd, getpid ());
}

/* Set the tty to our original foreground group.  */
static void
widen_foreground_group (int fd)
{
  if (inherited_pgroup && setpgid (0, inherited_pgroup) == 0)
    tcsetpgrp_without_stopping (fd, inherited_pgroup);
}
783

784 785
/* Getting and setting emacs_tty structures.  */

786
/* Set *TC to the parameters associated with the terminal FD,
787 788 789
   or clear it if the parameters are not available.
   Return 0 on success, -1 on failure.  */
int
790
emacs_get_tty (int fd, struct emacs_tty *settings)
791 792
{
  /* Retrieve the primary parameters - baud rate, character size, etcetera.  */
793
  memset (&settings->main, 0, sizeof (settings->main));
794 795 796 797 798
#ifdef DOS_NT
#ifdef WINDOWSNT
  HANDLE h = (HANDLE)_get_osfhandle (fd);
  DWORD console_mode;

799
  if (h && h != INVALID_HANDLE_VALUE && GetConsoleMode (h, &console_mode))
800
    {
801 802
      settings->main = console_mode;
      return 0;
803 804
    }
#endif	/* WINDOWSNT */
805
  return -1;
806 807
#else	/* !DOS_NT */
  /* We have those nifty POSIX tcmumbleattr functions.  */
808
  return tcgetattr (fd, &settings->main);
809 810 811 812 813
#endif
}


/* Set the parameters of the tty on FD according to the contents of
814 815
   *SETTINGS.  If FLUSHP, discard input.
   Return 0 if all went well, and -1 (setting errno) if anything failed.  */
816

Michael Albinus's avatar
Michael Albinus committed
817
int
818
emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
819 820
{
  /* Set the primary parameters - baud rate, character size, etcetera.  */
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
#ifdef DOS_NT
#ifdef WINDOWSNT
  HANDLE h = (HANDLE)_get_osfhandle (fd);

  if (h && h != INVALID_HANDLE_VALUE)
    {
      DWORD new_mode;

      /* Assume the handle is open for input.  */
      if (flushp)
	FlushConsoleInputBuffer (h);
      new_mode = settings->main;
      SetConsoleMode (h, new_mode);
    }
#endif	/* WINDOWSNT */
#else  /* !DOS_NT */
837
  int i;
838 839
  /* We have those nifty POSIX tcmumbleattr functions.
     William J. Smith <wjs@wiis.wang.com> writes:
840
     "POSIX 1003.1 defines tcsetattr to return success if it was
841 842 843 844
     able to perform any of the requested actions, even if some
     of the requested actions could not be performed.
     We must read settings back to ensure tty setup properly.
     AIX requires this to keep tty from hanging occasionally."  */
845
  /* This make sure that we don't loop indefinitely in here.  */
846
  for (i = 0 ; i < 10 ; i++)
847
    if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
848 849 850 851 852 853 854 855 856 857
      {
	if (errno == EINTR)
	  continue;
	else
	  return -1;
      }
    else
      {
	struct termios new;

858
	memset (&new, 0, sizeof (new));
859 860
	/* Get the current settings, and see if they're what we asked for.  */
	tcgetattr (fd, &new);
861 862 863 864 865 866 867 868
	/* We cannot use memcmp on the whole structure here because under
	 * aix386 the termios structure has some reserved field that may
	 * not be filled in.
	 */
	if (   new.c_iflag == settings->main.c_iflag
	    && new.c_oflag == settings->main.c_oflag
	    && new.c_cflag == settings->main.c_cflag
	    && new.c_lflag == settings->main.c_lflag
869
	    && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
870
	  break;
871 872
	else
	  continue;
873 874
      }
#endif
875

876 877 878 879
  /* We have survived the tempest.  */
  return 0;
}

Jim Blandy's avatar
Jim Blandy committed
880 881 882


#ifdef F_SETOWN
883
static int old_fcntl_owner[FD_SETSIZE];
Jim Blandy's avatar
Jim Blandy committed
884 885 886 887 888 889
#endif /* F_SETOWN */

/* This may also be defined in stdio,
   but if so, this does no harm,
   and using the same name avoids wasting the other one's space.  */

890
#if defined (USG)
Jim Blandy's avatar
Jim Blandy committed
891 892 893 894
unsigned char _sobuf[BUFSIZ+8];
#else
char _sobuf[BUFSIZ];
#endif
895

896 897 898
/* Initialize the terminal mode on all tty devices that are currently
   open. */

899
void
900 901
init_all_sys_modes (void)
{
902
  struct tty_display_info *tty;
903
  for (tty = tty_list; tty; tty = tty->next)
904 905 906
    init_sys_modes (tty);
}

907 908
/* Initialize the terminal mode on the given tty device. */

909
void
910
init_sys_modes (struct tty_display_info *tty_out)
Jim Blandy's avatar
Jim Blandy committed
911
{
Jim Blandy's avatar
Jim Blandy committed
912
  struct emacs_tty tty;
913
  Lisp_Object terminal;
Jim Blandy's avatar
Jim Blandy committed
914

915 916
  Vtty_erase_char = Qnil;

Jim Blandy's avatar
Jim Blandy committed
917 918 919
  if (noninteractive)
    return;

920 921
  if (!tty_out->output)
    return;                     /* The tty is suspended. */
922

923 924
  narrow_foreground_group (fileno (tty_out->input));

925
  if (! tty_out->old_tty)
926
    tty_out->old_tty = xmalloc (sizeof *tty_out->old_tty);
927

Dan Nicolaescu's avatar
Dan Nicolaescu committed
928
  emacs_get_tty (fileno (tty_out->input), tty_out->old_tty);
929

930
  tty = *tty_out->old_tty;
Jim Blandy's avatar
Jim Blandy committed
931

Dan Nicolaescu's avatar
Dan Nicolaescu committed
932
#if !defined (DOS_NT)
933
  XSETINT (Vtty_erase_char, tty.main.c_cc[VERASE]);
934

935 936
  tty.main.c_iflag |= (IGNBRK);	/* Ignore break condition */
  tty.main.c_iflag &= ~ICRNL;	/* Disable map of CR to NL on input */
937 938
#ifdef INLCR  /* I'm just being cautious,
		 since I can't check how widespread INLCR is--rms.  */
939
  tty.main.c_iflag &= ~INLCR;	/* Disable map of NL to CR on input */
940
#endif
Jim Blandy's avatar
Jim Blandy committed
941
#ifdef ISTRIP
942
  tty.main.c_iflag &= ~ISTRIP;	/* don't strip 8th bit on input */
Jim Blandy's avatar
Jim Blandy committed
943
#endif
944 945
  tty.main.c_lflag &= ~ECHO;	/* Disable echo */
  tty.main.c_lflag &= ~ICANON;	/* Disable erase/kill processing */
946
#ifdef IEXTEN
947
  tty.main.c_lflag &= ~IEXTEN;	/* Disable other editing characters.  */
948
#endif
949 950 951 952
  tty.main.c_lflag |= ISIG;	/* Enable signals */
  if (tty_out->flow_control)
    {
      tty.main.c_iflag |= IXON;	/* Enable start/stop output control */
Jim Blandy's avatar
Jim Blandy committed
953
#ifdef IXANY
954
      tty.main.c_iflag &= ~IXANY;
Jim Blandy's avatar
Jim Blandy committed
955
#endif /* IXANY */
956 957 958 959 960 961
    }
  else
    tty.main.c_iflag &= ~IXON;	/* Disable start/stop output control */
  tty.main.c_oflag &= ~ONLCR;	/* Disable map of NL to CR-NL
                                   on output */
  tty.main.c_oflag &= ~TAB3;	/* Disable tab expansion */
Jim Blandy's avatar
Jim Blandy committed
962
#ifdef CS8
963 964 965 966 967
  if (tty_out->meta_key)
    {
      tty.main.c_cflag |= CS8;	/* allow 8th bit on input */
      tty.main.c_cflag &= ~PARENB;/* Don't check parity */
    }
Jim Blandy's avatar
Jim Blandy committed
968
#endif
969 970 971

  XSETTERMINAL(terminal, tty_out->terminal);
  if (!NILP (Fcontrolling_tty_p (terminal)))
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
    {
      tty.main.c_cc[VINTR] = quit_char;	/* C-g (usually) gives SIGINT */
      /* Set up C-g for both SIGQUIT and SIGINT.
         We don't know which we will get, but we handle both alike
         so which one it really gives us does not matter.  */
      tty.main.c_cc[VQUIT] = quit_char;
    }
  else
    {
      /* We normally don't get interrupt or quit signals from tty
         devices other than our controlling terminal; therefore,
         we must handle C-g as normal input.  Unfortunately, this
         means that the interrupt and quit feature must be
         disabled on secondary ttys, or we would not even see the
         keypress.
987

988 989 990 991 992 993 994 995 996 997 998 999 1000
         Note that even though emacsclient could have special code
         to pass SIGINT to Emacs, we should _not_ enable
         interrupt/quit keys for emacsclient frames.  This means
         that we can't break out of loops in C code from a
         secondary tty frame, but we can always decide what
         display the C-g came from, which is more important from a
         usability point of view.  (Consider the case when two
         people work together using the same Emacs instance.)  */
      tty.main.c_cc[VINTR] = CDISABLE;
      tty.main.c_cc[VQUIT] = CDISABLE;
    }
  tty.main.c_cc[VMIN] = 1;	/* Input should wait for at least 1 char */
  tty.main.c_cc[VTIME] = 0;	/* no matter how long that takes.  */
Jim Blandy's avatar
Jim Blandy committed
1001
#ifdef VSWTCH
1002
  tty.main.c_cc[VSWTCH] = CDISABLE;	/* Turn off shell layering use
Jim Blandy's avatar
Jim Blandy committed
1003
					   of C-z */
Jim Blandy's avatar
Jim Blandy committed
1004
#endif /* VSWTCH */
1005

Jim Blandy's avatar
Jim Blandy committed
1006
#ifdef VSUSP
Dan Nicolaescu's avatar
Dan Nicolaescu committed
1007
  tty.main.c_cc[VSUSP] = CDISABLE;	/* Turn off handling of C-z.  */
Jim Blandy's avatar
Jim Blandy committed
1008 1009
#endif /* VSUSP */
#ifdef V_DSUSP
Dan Nicolaescu's avatar
Dan Nicolaescu committed
1010
  tty.main.c_cc[V_DSUSP] = CDISABLE; /* Turn off handling of C-y.  */
Jim Blandy's avatar
Jim Blandy committed
1011
#endif /* V_DSUSP */
1012
#ifdef VDSUSP /* Some systems have VDSUSP, some have V_DSUSP.  */
1013
  tty.main.c_cc[VDSUSP] = CDISABLE;
1014
#endif /* VDSUSP */
1015
#ifdef VLNEXT
1016
  tty.main.c_cc[VLNEXT] = CDISABLE;
1017 1018
#endif /* VLNEXT */
#ifdef VREPRINT
1019
  tty.main.c_cc[VREPRINT] = CDISABLE;
Richard M. Stallman's avatar