sysdep.c 91.2 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Interfaces to system-dependent kernel and library entries.
2 3
   Copyright (C) 1985-1988, 1993-1995, 1999-2013 Free Software
   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

#define SYSTIME_INLINE EXTERN_INLINE

24
#include <execinfo.h>
25
#include "sysstdio.h"
26 27 28 29 30
#ifdef HAVE_PWD_H
#include <pwd.h>
#include <grp.h>
#endif /* HAVE_PWD_H */
#include <limits.h>
31
#include <unistd.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
32

33
#include <c-ctype.h>
34
#include <utimens.h>
35

Jim Blandy's avatar
Jim Blandy committed
36
#include "lisp.h"
37
#include "sysselect.h"
38
#include "blockinput.h"
Jim Blandy's avatar
Jim Blandy committed
39

40 41
#if defined DARWIN_OS || defined __FreeBSD__
# include <sys/sysctl.h>
Paul Eggert's avatar
Paul Eggert committed
42 43 44
#endif

#ifdef __FreeBSD__
45 46 47 48 49 50 51 52
/* 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 <sys/resource.h>
# include <math.h>
53 54
#endif

55
#ifdef WINDOWSNT
56 57
#define read sys_read
#define write sys_write
58 59 60
#ifndef STDERR_FILENO
#define STDERR_FILENO fileno(GetStdHandle(STD_ERROR_HANDLE))
#endif
61 62 63
#include <windows.h>
#endif /* not WINDOWSNT */

Jim Blandy's avatar
Jim Blandy committed
64 65 66 67
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

68 69 70 71 72
/* Get SI_SRPC_DOMAIN, if it is available.  */
#ifdef HAVE_SYS_SYSTEMINFO_H
#include <sys/systeminfo.h>
#endif

73 74
#ifdef MSDOS	/* Demacs 1.1.2 91/10/20 Manabu Higashida, MW Aug 1993 */
#include "msdos.h"
75
#endif
76

77
#include <sys/param.h>
78 79
#include <sys/file.h>
#include <fcntl.h>
Jim Blandy's avatar
Jim Blandy committed
80

81
#include "systty.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
82
#include "syswait.h"
Jim Blandy's avatar
Jim Blandy committed
83

Dan Nicolaescu's avatar
Dan Nicolaescu committed
84
#ifdef HAVE_SYS_UTSNAME_H
Jim Blandy's avatar
Jim Blandy committed
85 86
#include <sys/utsname.h>
#include <memory.h>
Dan Nicolaescu's avatar
Dan Nicolaescu committed
87
#endif /* HAVE_SYS_UTSNAME_H */
Jim Blandy's avatar
Jim Blandy committed
88

89
#include "keyboard.h"
Jim Blandy's avatar
Jim Blandy committed
90
#include "frame.h"
Jim Blandy's avatar
Jim Blandy committed
91 92 93 94 95 96
#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
97
#include "cm.h"  /* for reset_sys_modes */
Jim Blandy's avatar
Jim Blandy committed
98

99 100 101 102
#ifdef WINDOWSNT
#include <direct.h>
/* In process.h which conflicts with the local copy.  */
#define _P_WAIT 0
103 104
int _cdecl _spawnlp (int, const char *, const char *, ...);
int _cdecl _getpid (void);
105 106
#endif

Jim Blandy's avatar
Jim Blandy committed
107 108
#include "syssignal.h"
#include "systime.h"
Jim Blandy's avatar
Jim Blandy committed
109

110 111
static void emacs_get_tty (int, struct emacs_tty *);
static int emacs_set_tty (int, struct emacs_tty *, bool);
112

113 114 115 116 117
/* 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
118 119 120
/* Declare here, including term.h is problematic on some systems.  */
extern void tputs (const char *, int, int (*)(int));

121
static const int baud_convert[] =
Jim Blandy's avatar
Jim Blandy committed
122 123 124 125 126
  {
    0, 50, 75, 110, 135, 150, 200, 300, 600, 1200,
    1800, 2400, 4800, 9600, 19200, 38400
  };

127

128
#if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
129

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

185

186
/* Discard pending input on all input descriptors.  */
Jim Blandy's avatar
Jim Blandy committed
187

188
void
189
discard_tty_input (void)
Jim Blandy's avatar
Jim Blandy committed
190
{
191
#ifndef WINDOWSNT
Jim Blandy's avatar
Jim Blandy committed
192
  struct emacs_tty buf;
Jim Blandy's avatar
Jim Blandy committed
193 194 195 196

  if (noninteractive)
    return;

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

216

Jim Blandy's avatar
Jim Blandy committed
217 218
#ifdef SIGTSTP

219
/* Arrange for character C to be read as the next input from
220 221 222
   the terminal.
   XXX What if we have multiple ttys?
*/
223

Andreas Schwab's avatar
Andreas Schwab committed
224
void
225
stuff_char (char c)
Jim Blandy's avatar
Jim Blandy committed
226
{
227
  if (! FRAME_TERMCAP_P (SELECTED_FRAME ()))
228 229
    return;

Jim Blandy's avatar
Jim Blandy committed
230 231
/* Should perhaps error if in batch mode */
#ifdef TIOCSTI
232
  ioctl (fileno (CURTTY()->input), TIOCSTI, &c);
Jim Blandy's avatar
Jim Blandy committed
233
#else /* no TIOCSTI */
234
  error ("Cannot stuff terminal input characters in this version of Unix");
Jim Blandy's avatar
Jim Blandy committed
235 236 237 238
#endif /* no TIOCSTI */
}

#endif /* SIGTSTP */
239

240
void
241
init_baud_rate (int fd)
Jim Blandy's avatar
Jim Blandy committed
242
{
Dan Nicolaescu's avatar
Dan Nicolaescu committed
243
  int emacs_ospeed;
244

Jim Blandy's avatar
Jim Blandy committed
245
  if (noninteractive)
Gerd Moellmann's avatar
Gerd Moellmann committed
246
    emacs_ospeed = 0;
Jim Blandy's avatar
Jim Blandy committed
247 248
  else
    {
249
#ifdef DOS_NT
Gerd Moellmann's avatar
Gerd Moellmann committed
250
    emacs_ospeed = 15;
251
#else  /* not DOS_NT */
252
      struct termios sg;
Jim Blandy's avatar
Jim Blandy committed
253

254
      sg.c_cflag = B9600;
255
      tcgetattr (fd, &sg);
Gerd Moellmann's avatar
Gerd Moellmann committed
256
      emacs_ospeed = cfgetospeed (&sg);
257
#endif /* not DOS_NT */
Jim Blandy's avatar
Jim Blandy committed
258
    }
259

Gerd Moellmann's avatar
Gerd Moellmann committed
260 261
  baud_rate = (emacs_ospeed < sizeof baud_convert / sizeof baud_convert[0]
	       ? baud_convert[emacs_ospeed] : 9600);
Jim Blandy's avatar
Jim Blandy committed
262 263 264 265
  if (baud_rate == 0)
    baud_rate = 1200;
}

266

Jim Blandy's avatar
Jim Blandy committed
267

268
#ifndef MSDOS
Jim Blandy's avatar
Jim Blandy committed
269

270 271 272 273 274 275 276 277 278 279 280
/* 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
281
{
282 283 284 285 286 287 288
  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.  */
289
  eassert (child > 0);
290 291

  while ((pid = waitpid (child, status, options)) < 0)
Jim Blandy's avatar
Jim Blandy committed
292
    {
293 294 295 296 297 298
      /* 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 ();
299

300 301
      /* Note: the MS-Windows emulation of waitpid calls QUIT
	 internally.  */
302 303
      if (interruptible)
	QUIT;
Jim Blandy's avatar
Jim Blandy committed
304 305
    }

306 307 308 309
  /* 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)
    *input_available_clear_time = make_emacs_time (0, 0);
310

311 312 313 314 315 316 317 318
  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.  */
319
void
320
wait_for_termination (pid_t child, int *status, bool interruptible)
321
{
322
  get_child_status (child, status, 0, interruptible);
323 324
}

325 326 327 328 329 330 331 332 333 334 335
/* 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)
336
{
337
  return get_child_status (child, status, WNOHANG | options, 0);
338 339
}

340

Jim Blandy's avatar
Jim Blandy committed
341 342 343 344 345
/*  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.  */

346
void
347
child_setup_tty (int out)
Jim Blandy's avatar
Jim Blandy committed
348
{
349
#ifndef WINDOWSNT
Jim Blandy's avatar
Jim Blandy committed
350 351
  struct emacs_tty s;

Dan Nicolaescu's avatar
Dan Nicolaescu committed
352
  emacs_get_tty (out, &s);
Jim Blandy's avatar
Jim Blandy committed
353 354
  s.main.c_oflag |= OPOST;	/* Enable output postprocessing */
  s.main.c_oflag &= ~ONLCR;	/* Disable map of NL to CR-NL on output */
355
#ifdef NLDLY
356 357 358
  /* 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
359 360
  s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY|FFDLY);
  				/* No output delays */
361 362 363 364
#else
  s.main.c_oflag &= ~(NLDLY|CRDLY|TABDLY|BSDLY|VTDLY);
  				/* No output delays */
#endif
365
#endif
Jim Blandy's avatar
Jim Blandy committed
366 367
  s.main.c_lflag &= ~ECHO;	/* Disable echo */
  s.main.c_lflag |= ISIG;	/* Enable signals */
368 369 370
#ifdef IUCLC
  s.main.c_iflag &= ~IUCLC;	/* Disable downcasing on input.  */
#endif
371 372 373
#ifdef ISTRIP
  s.main.c_iflag &= ~ISTRIP;	/* don't strip 8th bit on input */
#endif
374
#ifdef OLCUC
375 376
  s.main.c_oflag &= ~OLCUC;	/* Disable upcasing on output.  */
#endif
377
  s.main.c_oflag &= ~TAB3;	/* Disable tab expansion */
378
  s.main.c_cflag = (s.main.c_cflag & ~CSIZE) | CS8; /* Don't strip 8th bit */
379 380
  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
381

Jim Blandy's avatar
Jim Blandy committed
382
#ifdef HPUX
Jim Blandy's avatar
Jim Blandy committed
383
  s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
Jim Blandy's avatar
Jim Blandy committed
384
#endif /* HPUX */
Jim Blandy's avatar
Jim Blandy committed
385

386 387 388
#ifdef SIGNALS_VIA_CHARACTERS
  /* the QUIT and INTR character are used in process_send_signal
     so set them here to something useful.  */
389
  if (s.main.c_cc[VQUIT] == CDISABLE)
390
    s.main.c_cc[VQUIT] = '\\'&037;	/* Control-\ */
391
  if (s.main.c_cc[VINTR] == CDISABLE)
392 393 394
    s.main.c_cc[VINTR] = 'C'&037;	/* Control-C */
#endif /* not SIGNALS_VIA_CHARACTERS */

Jim Blandy's avatar
Jim Blandy committed
395 396 397
#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
398 399
  s.main.c_iflag &= ~IGNBRK;
  s.main.c_iflag &= ~BRKINT;
400 401 402
  /* 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
403
  s.main.c_cflag = (s.main.c_cflag & ~CBAUD) | B9600; /* baud rate sanity */
Jim Blandy's avatar
Jim Blandy committed
404 405
#endif /* AIX */

406
  /* We originally enabled ICANON (and set VEOF to 04), and then had
Paul Eggert's avatar
Paul Eggert committed
407
     process.c send additional EOF chars to flush the output when faced
408
     with long lines, but this leads to weird effects when the
409 410
     subprocess has disabled ICANON and ends up seeing those spurious
     extra EOFs.  So we don't send EOFs any more in
411 412 413 414 415 416 417 418 419 420 421
     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?  */
422 423 424

  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
425
#if 0	    /* These settings only apply to non-ICANON mode. */
426 427
  s.main.c_cc[VMIN] = 1;
  s.main.c_cc[VTIME] = 0;
428
#endif
429

Dan Nicolaescu's avatar
Dan Nicolaescu committed
430
  emacs_set_tty (out, &s, 0);
431
#endif /* not WINDOWSNT */
Jim Blandy's avatar
Jim Blandy committed
432
}
Dan Nicolaescu's avatar
Dan Nicolaescu committed
433
#endif	/* not MSDOS */
Jim Blandy's avatar
Jim Blandy committed
434

435

Paul Eggert's avatar
Paul Eggert committed
436
/* Record a signal code and the action for it.  */
Jim Blandy's avatar
Jim Blandy committed
437 438 439
struct save_signal
{
  int code;
Paul Eggert's avatar
Paul Eggert committed
440
  struct sigaction action;
Jim Blandy's avatar
Jim Blandy committed
441 442
};

443 444
static void save_signal_handlers (struct save_signal *);
static void restore_signal_handlers (struct save_signal *);
Andreas Schwab's avatar
Andreas Schwab committed
445

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

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

459
#endif
460 461 462 463
}

/* Fork a subshell.  */

464
void
465
sys_subshell (void)
466
{
467
#ifdef DOS_NT	/* Demacs 1.1.2 91/10/20 Manabu Higashida */
468 469 470
  int st;
  char oldwd[MAXPATHLEN+1]; /* Fixed length is safe on MSDOS.  */
#endif
471
  pid_t pid;
472
  int status;
Jim Blandy's avatar
Jim Blandy committed
473
  struct save_signal saved_handlers[5];
474 475 476 477 478 479 480 481 482 483 484 485 486 487
  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
488 489 490 491

  saved_handlers[0].code = SIGINT;
  saved_handlers[1].code = SIGQUIT;
  saved_handlers[2].code = SIGTERM;
Paul Eggert's avatar
Paul Eggert committed
492
#ifdef USABLE_SIGIO
Jim Blandy's avatar
Jim Blandy committed
493 494 495 496 497 498
  saved_handlers[3].code = SIGIO;
  saved_handlers[4].code = 0;
#else
  saved_handlers[3].code = 0;
#endif

499
#ifdef DOS_NT
500
  save_signal_handlers (saved_handlers);
501 502
#endif

Jim Blandy's avatar
Jim Blandy committed
503 504
  if (pid == 0)
    {
505
      const char *sh = 0;
Jim Blandy's avatar
Jim Blandy committed
506

507
#ifdef DOS_NT    /* MW, Aug 1993 */
508
      getcwd (oldwd, sizeof oldwd);
509
      if (sh == 0)
Paul Eggert's avatar
Paul Eggert committed
510
	sh = egetenv ("SUSPEND");	/* KFS, 1994-12-14 */
511
#endif
512
      if (sh == 0)
Paul Eggert's avatar
Paul Eggert committed
513
	sh = egetenv ("SHELL");
Jim Blandy's avatar
Jim Blandy committed
514 515
      if (sh == 0)
	sh = "sh";
516

Jim Blandy's avatar
Jim Blandy committed
517
      /* Use our buffer's default directory for the subshell.  */
518
      if (chdir (str) != 0)
Paul Eggert's avatar
Paul Eggert committed
519 520
	{
#ifndef DOS_NT
521
	  emacs_perror (str);
522
	  _exit (EXIT_CANCELED);
Paul Eggert's avatar
Paul Eggert committed
523 524
#endif
	}
525

526
#ifdef MSDOS    /* Demacs 1.1.2 91/10/20 Manabu Higashida */
527
      {
528 529
	char *epwd = getenv ("PWD");
	char old_pwd[MAXPATHLEN+1+4];
530 531

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

557
  /* Do this now if we did not do it before.  */
558
#ifndef MSDOS
Jim Blandy's avatar
Jim Blandy committed
559
  save_signal_handlers (saved_handlers);
560 561
#endif

562
#ifndef DOS_NT
563
  wait_for_termination (pid, &status, 0);
564
#endif
Jim Blandy's avatar
Jim Blandy committed
565 566 567
  restore_signal_handlers (saved_handlers);
}

Andreas Schwab's avatar
Andreas Schwab committed
568
static void
569
save_signal_handlers (struct save_signal *saved_handlers)
Jim Blandy's avatar
Jim Blandy committed
570 571 572
{
  while (saved_handlers->code)
    {
Paul Eggert's avatar
Paul Eggert committed
573 574 575
      struct sigaction action;
      emacs_sigaction_init (&action, SIG_IGN);
      sigaction (saved_handlers->code, &action, &saved_handlers->action);
Jim Blandy's avatar
Jim Blandy committed
576 577 578 579
      saved_handlers++;
    }
}

Andreas Schwab's avatar
Andreas Schwab committed
580
static void
581
restore_signal_handlers (struct save_signal *saved_handlers)
Jim Blandy's avatar
Jim Blandy committed
582 583 584
{
  while (saved_handlers->code)
    {
Paul Eggert's avatar
Paul Eggert committed
585
      sigaction (saved_handlers->code, &saved_handlers->action, 0);
Jim Blandy's avatar
Jim Blandy committed
586 587 588 589
      saved_handlers++;
    }
}

Paul Eggert's avatar
Paul Eggert committed
590
#ifdef USABLE_SIGIO
591
static int old_fcntl_flags[MAXDESC];
Paul Eggert's avatar
Paul Eggert committed
592
#endif
Jim Blandy's avatar
Jim Blandy committed
593

594
void
595
init_sigio (int fd)
Jim Blandy's avatar
Jim Blandy committed
596
{
Paul Eggert's avatar
Paul Eggert committed
597
#ifdef USABLE_SIGIO
598 599
  old_fcntl_flags[fd] = fcntl (fd, F_GETFL, 0) & ~FASYNC;
  fcntl (fd, F_SETFL, old_fcntl_flags[fd] | FASYNC);
600
  interrupts_deferred = 0;
Paul Eggert's avatar
Paul Eggert committed
601
#endif
Jim Blandy's avatar
Jim Blandy committed
602 603
}

604
static void
605
reset_sigio (int fd)
Jim Blandy's avatar
Jim Blandy committed
606
{
Paul Eggert's avatar
Paul Eggert committed
607
#ifdef USABLE_SIGIO
608
  fcntl (fd, F_SETFL, old_fcntl_flags[fd]);
609
#endif
Jim Blandy's avatar
Jim Blandy committed
610 611
}

612
void
613
request_sigio (void)
Jim Blandy's avatar
Jim Blandy committed
614
{
Paul Eggert's avatar
Paul Eggert committed
615
#ifdef USABLE_SIGIO
Paul Eggert's avatar
Paul Eggert committed
616 617
  sigset_t unblocked;

618
  if (noninteractive)
619 620
    return;

Paul Eggert's avatar
Paul Eggert committed
621
  sigemptyset (&unblocked);
Paul Eggert's avatar
Paul Eggert committed
622
# ifdef SIGWINCH
Paul Eggert's avatar
Paul Eggert committed
623
  sigaddset (&unblocked, SIGWINCH);
Paul Eggert's avatar
Paul Eggert committed
624
# endif
Paul Eggert's avatar
Paul Eggert committed
625 626
  sigaddset (&unblocked, SIGIO);
  pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
Jim Blandy's avatar
Jim Blandy committed
627 628

  interrupts_deferred = 0;
Paul Eggert's avatar
Paul Eggert committed
629
#endif
Jim Blandy's avatar
Jim Blandy committed
630 631
}

632
void
Karoly Lorentey's avatar
Karoly Lorentey committed
633
unrequest_sigio (void)
634
{
Paul Eggert's avatar
Paul Eggert committed
635
#ifdef USABLE_SIGIO
Paul Eggert's avatar
Paul Eggert committed
636 637
  sigset_t blocked;

638 639 640
  if (noninteractive)
    return;

Paul Eggert's avatar
Paul Eggert committed
641
  sigemptyset (&blocked);
Paul Eggert's avatar
Paul Eggert committed
642
# ifdef SIGWINCH
Paul Eggert's avatar
Paul Eggert committed
643
  sigaddset (&blocked, SIGWINCH);
Paul Eggert's avatar
Paul Eggert committed
644
# endif
Paul Eggert's avatar
Paul Eggert committed
645 646
  sigaddset (&blocked, SIGIO);
  pthread_sigmask (SIG_BLOCK, &blocked, 0);
Jim Blandy's avatar
Jim Blandy committed
647
  interrupts_deferred = 1;
Paul Eggert's avatar
Paul Eggert committed
648
#endif
Jim Blandy's avatar
Jim Blandy committed
649
}
650

651
void
Paul Eggert's avatar
Paul Eggert committed
652
ignore_sigio (void)
Jim Blandy's avatar
Jim Blandy committed
653
{
Paul Eggert's avatar
Paul Eggert committed
654 655 656
#ifdef USABLE_SIGIO
  signal (SIGIO, SIG_IGN);
#endif
Jim Blandy's avatar
Jim Blandy committed
657
}
658

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

/* 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)
{
686
  pid_t pgrp = getpgrp ();
687 688 689
  inherited_pgroup = getpid () == pgrp ? 0 : pgrp;
}

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
/* Block and unblock SIGTTOU.  */

void
block_tty_out_signal (void)
{
#ifdef SIGTTOU
  sigset_t blocked;
  sigemptyset (&blocked);
  sigaddset (&blocked, SIGTTOU);
  pthread_sigmask (SIG_BLOCK, &blocked, 0);
#endif
}

void
unblock_tty_out_signal (void)
{
#ifdef SIGTTOU
  pthread_sigmask (SIG_SETMASK, &empty_mask, 0);
#endif
}

711 712 713 714 715 716 717 718 719 720 721 722
/* 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
  block_input ();
723
  block_tty_out_signal ();
724
  tcsetpgrp (fd, pgid);
725
  unblock_tty_out_signal ();
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
  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);
}
748

749 750
/* Getting and setting emacs_tty structures.  */

751 752 753
/* Set *TC to the parameters associated with the terminal FD,
   or clear it if the parameters are not available.  */
static void
754
emacs_get_tty (int fd, struct emacs_tty *settings)
755 756
{
  /* Retrieve the primary parameters - baud rate, character size, etcetera.  */
Dan Nicolaescu's avatar
Dan Nicolaescu committed
757
#ifndef DOS_NT
758
  /* We have those nifty POSIX tcmumbleattr functions.  */
759
  memset (&settings->main, 0, sizeof (settings->main));
760
  tcgetattr (fd, &settings->main);
761 762 763 764 765
#endif
}


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

769 770
static int
emacs_set_tty (int fd, struct emacs_tty *settings, bool flushp)
771 772
{
  /* Set the primary parameters - baud rate, character size, etcetera.  */
Dan Nicolaescu's avatar
Dan Nicolaescu committed
773
#ifndef DOS_NT
774
  int i;
775 776
  /* We have those nifty POSIX tcmumbleattr functions.
     William J. Smith <wjs@wiis.wang.com> writes:
777
     "POSIX 1003.1 defines tcsetattr to return success if it was
778 779 780 781
     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."  */
782
  /* This make sure that we don't loop indefinitely in here.  */
783
  for (i = 0 ; i < 10 ; i++)
784
    if (tcsetattr (fd, flushp ? TCSAFLUSH : TCSADRAIN, &settings->main) < 0)
785 786 787 788 789 790 791 792 793 794
      {
	if (errno == EINTR)
	  continue;
	else
	  return -1;
      }
    else
      {
	struct termios new;

795
	memset (&new, 0, sizeof (new));
796 797
	/* Get the current settings, and see if they're what we asked for.  */
	tcgetattr (fd, &new);
798 799 800 801 802 803 804 805
	/* 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
806
	    && memcmp (new.c_cc, settings->main.c_cc, NCCS) == 0)
807
	  break;
808 809
	else
	  continue;
810 811
      }
#endif
812

813 814 815 816
  /* We have survived the tempest.  */
  return 0;
}

Jim Blandy's avatar
Jim Blandy committed
817 818 819


#ifdef F_SETOWN
820
static int old_fcntl_owner[MAXDESC];
Jim Blandy's avatar
Jim Blandy committed
821 822 823 824 825 826
#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.  */

827
#if defined (USG)
Jim Blandy's avatar
Jim Blandy committed
828 829 830 831
unsigned char _sobuf[BUFSIZ+8];
#else
char _sobuf[BUFSIZ];
#endif
832

833 834 835
/* Initialize the terminal mode on all tty devices that are currently
   open. */

836
void
837 838
init_all_sys_modes (void)
{
839
  struct tty_display_info *tty;
840
  for (tty = tty_list; tty; tty = tty->next)
841 842 843
    init_sys_modes (tty);
}

844 845
/* Initialize the terminal mode on the given tty device. */

846
void
847
init_sys_modes (struct tty_display_info *tty_out)
Jim Blandy's avatar
Jim Blandy committed
848
{
Jim Blandy's avatar
Jim Blandy committed
849
  struct emacs_tty tty;
850
  Lisp_Object terminal;
Jim Blandy's avatar
Jim Blandy committed
851

852 853
  Vtty_erase_char = Qnil;

Jim Blandy's avatar