process.c 248 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* Asynchronous subprocess control for GNU Emacs.
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1985-1988, 1993-1996, 1998-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 21


22
#include <config.h>
Paul Eggert's avatar
Paul Eggert committed
23

Jim Blandy's avatar
Jim Blandy committed
24
#include <stdio.h>
Paul Eggert's avatar
Paul Eggert committed
25
#include <stdlib.h>
Jim Blandy's avatar
Jim Blandy committed
26
#include <errno.h>
27
#include <sys/types.h>		/* Some typedefs are used in sys/file.h.  */
Jim Blandy's avatar
Jim Blandy committed
28 29
#include <sys/file.h>
#include <sys/stat.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
30
#include <unistd.h>
31 32
#include <fcntl.h>

33 34
#include "lisp.h"

35 36 37
/* Only MS-DOS does not define `subprocesses'.  */
#ifdef subprocesses

Jim Blandy's avatar
Jim Blandy committed
38 39 40 41
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
42

Eli Zaretskii's avatar
Eli Zaretskii committed
43 44
#endif	/* subprocesses */

Paul Eggert's avatar
Paul Eggert committed
45 46
#ifdef HAVE_SETRLIMIT
# include <sys/resource.h>
47 48 49 50 51

/* If NOFILE_LIMIT.rlim_cur is greater than FD_SETSIZE, then
   NOFILE_LIMIT is the initial limit on the number of open files,
   which should be restored in child processes.  */
static struct rlimit nofile_limit;
Paul Eggert's avatar
Paul Eggert committed
52 53
#endif

Eli Zaretskii's avatar
Eli Zaretskii committed
54 55
#ifdef subprocesses

56
/* Are local (unix) sockets supported?  */
57
#if defined (HAVE_SYS_UN_H)
58 59 60 61 62 63 64 65
#if !defined (AF_LOCAL) && defined (AF_UNIX)
#define AF_LOCAL AF_UNIX
#endif
#ifdef AF_LOCAL
#define HAVE_LOCAL_SOCKETS
#include <sys/un.h>
#endif
#endif
Jim Blandy's avatar
Jim Blandy committed
66 67

#include <sys/ioctl.h>
Juanma Barranquero's avatar
Juanma Barranquero committed
68
#if defined (HAVE_NET_IF_H)
69 70
#include <net/if.h>
#endif /* HAVE_NET_IF_H */
Jim Blandy's avatar
Jim Blandy committed
71

Juanma Barranquero's avatar
Juanma Barranquero committed
72
#if defined (HAVE_IFADDRS_H)
73 74 75 76
/* Must be after net/if.h */
#include <ifaddrs.h>

/* We only use structs from this header when we use getifaddrs.  */
Juanma Barranquero's avatar
Juanma Barranquero committed
77
#if defined (HAVE_NET_IF_DL_H)
78 79 80 81 82
#include <net/if_dl.h>
#endif

#endif

Jim Blandy's avatar
Jim Blandy committed
83 84 85 86
#ifdef NEED_BSDTTY
#include <bsdtty.h>
#endif

Paul Eggert's avatar
Paul Eggert committed
87 88 89 90 91
#ifdef USG5_4
# include <sys/stream.h>
# include <sys/stropts.h>
#endif

92 93 94 95
#ifdef HAVE_UTIL_H
#include <util.h>
#endif

Dan Nicolaescu's avatar
Dan Nicolaescu committed
96 97 98 99
#ifdef HAVE_PTY_H
#include <pty.h>
#endif

100
#include <c-ctype.h>
101
#include <flexmember.h>
102
#include <sig2str.h>
103
#include <verify.h>
104

105 106
#endif	/* subprocesses */

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

#include "window.h"
111
#include "character.h"
112
#include "buffer.h"
Karl Heuer's avatar
Karl Heuer committed
113
#include "coding.h"
Jim Blandy's avatar
Jim Blandy committed
114
#include "process.h"
115
#include "frame.h"
Jim Blandy's avatar
Jim Blandy committed
116
#include "termopts.h"
117
#include "keyboard.h"
Richard M. Stallman's avatar
Richard M. Stallman committed
118
#include "blockinput.h"
Gerd Moellmann's avatar
Gerd Moellmann committed
119
#include "atimer.h"
120 121 122
#include "sysselect.h"
#include "syssignal.h"
#include "syswait.h"
Ted Zlatanov's avatar
Ted Zlatanov committed
123 124 125
#ifdef HAVE_GNUTLS
#include "gnutls.h"
#endif
Jim Blandy's avatar
Jim Blandy committed
126

127 128 129 130
#ifdef HAVE_WINDOW_SYSTEM
#include TERM_HEADER
#endif /* HAVE_WINDOW_SYSTEM */

131
#ifdef HAVE_GLIB
132
#include "xgselect.h"
133 134 135
#ifndef WINDOWSNT
#include <glib.h>
#endif
136
#endif
Dan Nicolaescu's avatar
Dan Nicolaescu committed
137

138 139 140 141 142
#if defined HAVE_GETADDRINFO_A || defined HAVE_GNUTLS
/* This is 0.1s in nanoseconds. */
#define ASYNC_RETRY_NSEC 100000000
#endif

143
#ifdef WINDOWSNT
144
extern int sys_select (int, fd_set *, fd_set *, fd_set *,
145
                       const struct timespec *, const sigset_t *);
146 147
#endif

148
/* Work around GCC 4.3.0 bug with strict overflow checking; see
149
   <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52904>.
150
   This bug appears to be fixed in GCC 5.1, so don't work around it there.  */
151
#if GNUC_PREREQ (4, 3, 0) && ! GNUC_PREREQ (5, 1, 0)
Eli Zaretskii's avatar
Eli Zaretskii committed
152 153 154 155 156 157 158 159 160 161 162
# pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif

/* True if keyboard input is on hold, zero otherwise.  */

static bool kbd_is_on_hold;

/* Nonzero means don't run process sentinels.  This is used
   when exiting.  */
bool inhibit_sentinels;

163 164 165 166 167 168 169 170 171 172 173 174
union u_sockaddr
{
  struct sockaddr sa;
  struct sockaddr_in in;
#ifdef AF_INET6
  struct sockaddr_in6 in6;
#endif
#ifdef HAVE_LOCAL_SOCKETS
  struct sockaddr_un un;
#endif
};

Eli Zaretskii's avatar
Eli Zaretskii committed
175 176
#ifdef subprocesses

177 178
#ifndef SOCK_CLOEXEC
# define SOCK_CLOEXEC 0
Paul Eggert's avatar
Paul Eggert committed
179
#endif
180
#ifndef SOCK_NONBLOCK
181
# define SOCK_NONBLOCK 0
182
#endif
Paul Eggert's avatar
Paul Eggert committed
183

184 185 186 187 188 189 190 191 192 193 194 195
/* True if ERRNUM represents an error where the system call would
   block if a blocking variant were used.  */
static bool
would_block (int errnum)
{
#ifdef EWOULDBLOCK
  if (EWOULDBLOCK != EAGAIN && errnum == EWOULDBLOCK)
    return true;
#endif
  return errnum == EAGAIN;
}

Paul Eggert's avatar
Paul Eggert committed
196
#ifndef HAVE_ACCEPT4
197 198 199 200 201 202 203 204 205 206 207

/* Emulate GNU/Linux accept4 and socket well enough for this module.  */

static int
close_on_exec (int fd)
{
  if (0 <= fd)
    fcntl (fd, F_SETFD, FD_CLOEXEC);
  return fd;
}

208 209 210
# undef accept4
# define accept4(sockfd, addr, addrlen, flags) \
    process_accept4 (sockfd, addr, addrlen, flags)
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
static int
accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
{
  return close_on_exec (accept (sockfd, addr, addrlen));
}

static int
process_socket (int domain, int type, int protocol)
{
  return close_on_exec (socket (domain, type, protocol));
}
# undef socket
# define socket(domain, type, protocol) process_socket (domain, type, protocol)
#endif

226 227 228 229
#define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
#define NETCONN1_P(p) (EQ (p->type, Qnetwork))
#define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
#define SERIALCONN1_P(p) (EQ (p->type, Qserial))
230 231
#define PIPECONN_P(p) (EQ (XPROCESS (p)->type, Qpipe))
#define PIPECONN1_P(p) (EQ (p->type, Qpipe))
Jim Blandy's avatar
Jim Blandy committed
232 233

/* Number of events of change of status of a process.  */
234
static EMACS_INT process_tick;
Jim Blandy's avatar
Jim Blandy committed
235
/* Number of events for which the user or sentinel has been notified.  */
236
static EMACS_INT update_tick;
Jim Blandy's avatar
Jim Blandy committed
237

238 239 240 241 242
/* Define DATAGRAM_SOCKETS if datagrams can be used safely on
   this system.  We need to read full packets, so we need a
   "non-destructive" select.  So we require either native select,
   or emulation of select using FIONREAD.  */

Paul Eggert's avatar
Paul Eggert committed
243 244 245 246 247 248 249
#ifndef BROKEN_DATAGRAM_SOCKETS
# if defined HAVE_SELECT || defined USABLE_FIONREAD
#  if defined HAVE_SENDTO && defined HAVE_RECVFROM && defined EMSGSIZE
#   define DATAGRAM_SOCKETS
#  endif
# endif
#endif
250

Stefan Monnier's avatar
Stefan Monnier committed
251 252 253 254
#if defined HAVE_LOCAL_SOCKETS && defined DATAGRAM_SOCKETS
# define HAVE_SEQPACKET
#endif

Paul Eggert's avatar
Paul Eggert committed
255
#define READ_OUTPUT_DELAY_INCREMENT (TIMESPEC_HZ / 100)
Kenichi Handa's avatar
Kenichi Handa committed
256 257 258
#define READ_OUTPUT_DELAY_MAX       (READ_OUTPUT_DELAY_INCREMENT * 5)
#define READ_OUTPUT_DELAY_MAX_MAX   (READ_OUTPUT_DELAY_INCREMENT * 7)

259 260
/* Number of processes which have a non-zero read_output_delay,
   and therefore might be delayed for adaptive read buffering.  */
Kenichi Handa's avatar
Kenichi Handa committed
261 262 263

static int process_output_delay_count;

264
/* True if any process has non-nil read_output_skip.  */
Kenichi Handa's avatar
Kenichi Handa committed
265

266
static bool process_output_skip;
Kenichi Handa's avatar
Kenichi Handa committed
267

268
static void start_process_unwind (Lisp_Object);
269
static void create_process (Lisp_Object, char **, Lisp_Object);
Paul Eggert's avatar
Paul Eggert committed
270
#ifdef USABLE_SIGIO
271
static bool keyboard_bit_set (fd_set *);
272
#endif
273
static void deactivate_process (Lisp_Object);
274
static int status_notify (struct Lisp_Process *, struct Lisp_Process *);
275 276
static int read_process_output (Lisp_Object, int);
static void create_pty (Lisp_Object);
277
static void exec_sentinel (Lisp_Object, Lisp_Object);
278

Robert Pluim's avatar
Robert Pluim committed
279 280 281 282
static Lisp_Object
network_lookup_address_info_1 (Lisp_Object host, const char *service,
                               struct addrinfo *hints, struct addrinfo **res);

283 284
/* Number of bits set in connect_wait_mask.  */
static int num_pending_connects;
285

Tom Tromey's avatar
Tom Tromey committed
286
/* The largest descriptor currently in use; -1 if none.  */
Tom Tromey's avatar
Tom Tromey committed
287
static int max_desc;
288

289 290 291 292
/* Set the external socket descriptor for Emacs to use when
   `make-network-process' is called with a non-nil
   `:use-external-socket' option.  The value should be either -1, or
   the file descriptor of a socket that is already bound.  */
293
static int external_sock_fd;
294

295
/* Indexed by descriptor, gives the process (if any) for that descriptor.  */
296
static Lisp_Object chan_process[FD_SETSIZE];
297
static void wait_for_socket_fds (Lisp_Object, char const *);
Jim Blandy's avatar
Jim Blandy committed
298

299
/* Alist of elements (NAME . PROCESS).  */
300
static Lisp_Object Vprocess_alist;
Jim Blandy's avatar
Jim Blandy committed
301 302 303 304 305 306 307

/* Buffered-ahead input char from process, indexed by channel.
   -1 means empty (no char is buffered).
   Used on sys V where the only way to tell if there is any
   output from the process is to read at least one char.
   Always -1 on systems that support FIONREAD.  */

308
static int proc_buffered_char[FD_SETSIZE];
309

Karl Heuer's avatar
Karl Heuer committed
310
/* Table of `struct coding-system' for each process.  */
311 312
static struct coding_system *proc_decode_coding_system[FD_SETSIZE];
static struct coding_system *proc_encode_coding_system[FD_SETSIZE];
Karl Heuer's avatar
Karl Heuer committed
313

314 315
#ifdef DATAGRAM_SOCKETS
/* Table of `partner address' for datagram sockets.  */
316
static struct sockaddr_and_len {
317
  struct sockaddr *sa;
318
  ptrdiff_t len;
319
} datagram_address[FD_SETSIZE];
320
#define DATAGRAM_CHAN_P(chan)	(datagram_address[chan].sa != 0)
321 322 323 324
#define DATAGRAM_CONN_P(proc)                                           \
  (PROCESSP (proc) &&                                                   \
   XPROCESS (proc)->infd >= 0 &&                                        \
   datagram_address[XPROCESS (proc)->infd].sa != 0)
325 326 327 328
#else
#define DATAGRAM_CONN_P(proc)	(0)
#endif

329 330 331 332 333 334
/* FOR_EACH_PROCESS (LIST_VAR, PROC_VAR) followed by a statement is
   a `for' loop which iterates over processes from Vprocess_alist.  */

#define FOR_EACH_PROCESS(list_var, proc_var)			\
  FOR_EACH_ALIST_VALUE (Vprocess_alist, list_var, proc_var)

Paul Eggert's avatar
Paul Eggert committed
335
/* These setters are used only in this file, so they can be private.  */
336
static void
Paul Eggert's avatar
Paul Eggert committed
337 338 339 340
pset_buffer (struct Lisp_Process *p, Lisp_Object val)
{
  p->buffer = val;
}
341
static void
Paul Eggert's avatar
Paul Eggert committed
342 343 344 345
pset_command (struct Lisp_Process *p, Lisp_Object val)
{
  p->command = val;
}
346
static void
Paul Eggert's avatar
Paul Eggert committed
347 348 349 350
pset_decode_coding_system (struct Lisp_Process *p, Lisp_Object val)
{
  p->decode_coding_system = val;
}
351
static void
Paul Eggert's avatar
Paul Eggert committed
352 353 354 355
pset_decoding_buf (struct Lisp_Process *p, Lisp_Object val)
{
  p->decoding_buf = val;
}
356
static void
Paul Eggert's avatar
Paul Eggert committed
357 358 359 360
pset_encode_coding_system (struct Lisp_Process *p, Lisp_Object val)
{
  p->encode_coding_system = val;
}
361
static void
Paul Eggert's avatar
Paul Eggert committed
362 363 364 365
pset_encoding_buf (struct Lisp_Process *p, Lisp_Object val)
{
  p->encoding_buf = val;
}
366
static void
Paul Eggert's avatar
Paul Eggert committed
367 368
pset_filter (struct Lisp_Process *p, Lisp_Object val)
{
369
  p->filter = NILP (val) ? Qinternal_default_process_filter : val;
Paul Eggert's avatar
Paul Eggert committed
370
}
371
static void
Paul Eggert's avatar
Paul Eggert committed
372 373 374 375
pset_log (struct Lisp_Process *p, Lisp_Object val)
{
  p->log = val;
}
376
static void
Paul Eggert's avatar
Paul Eggert committed
377 378 379 380
pset_mark (struct Lisp_Process *p, Lisp_Object val)
{
  p->mark = val;
}
381
static void
Tom Tromey's avatar
Tom Tromey committed
382 383 384 385
pset_thread (struct Lisp_Process *p, Lisp_Object val)
{
  p->thread = val;
}
Tom Tromey's avatar
Tom Tromey committed
386
static void
Paul Eggert's avatar
Paul Eggert committed
387 388 389 390
pset_name (struct Lisp_Process *p, Lisp_Object val)
{
  p->name = val;
}
391
static void
Paul Eggert's avatar
Paul Eggert committed
392 393 394 395
pset_plist (struct Lisp_Process *p, Lisp_Object val)
{
  p->plist = val;
}
396
static void
Paul Eggert's avatar
Paul Eggert committed
397 398
pset_sentinel (struct Lisp_Process *p, Lisp_Object val)
{
399
  p->sentinel = NILP (val) ? Qinternal_default_process_sentinel : val;
Paul Eggert's avatar
Paul Eggert committed
400
}
401
static void
Paul Eggert's avatar
Paul Eggert committed
402 403 404 405
pset_tty_name (struct Lisp_Process *p, Lisp_Object val)
{
  p->tty_name = val;
}
406
static void
Paul Eggert's avatar
Paul Eggert committed
407 408 409 410
pset_type (struct Lisp_Process *p, Lisp_Object val)
{
  p->type = val;
}
411
static void
Paul Eggert's avatar
Paul Eggert committed
412 413 414 415
pset_write_queue (struct Lisp_Process *p, Lisp_Object val)
{
  p->write_queue = val;
}
416 417 418 419 420
static void
pset_stderrproc (struct Lisp_Process *p, Lisp_Object val)
{
  p->stderrproc = val;
}
Paul Eggert's avatar
Paul Eggert committed
421

422

Dmitry Antipov's avatar
Dmitry Antipov committed
423 424 425 426 427
static Lisp_Object
make_lisp_proc (struct Lisp_Process *p)
{
  return make_lisp_ptr (p, Lisp_Vectorlike);
}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
enum fd_bits
{
  /* Read from file descriptor.  */
  FOR_READ = 1,
  /* Write to file descriptor.  */
  FOR_WRITE = 2,
  /* This descriptor refers to a keyboard.  Only valid if FOR_READ is
     set.  */
  KEYBOARD_FD = 4,
  /* This descriptor refers to a process.  */
  PROCESS_FD = 8,
  /* A non-blocking connect.  Only valid if FOR_WRITE is set.  */
  NON_BLOCKING_CONNECT_FD = 16
};

444
static struct fd_callback_data
445 446 447
{
  fd_callback func;
  void *data;
448 449
  /* Flags from enum fd_bits.  */
  int flags;
Tom Tromey's avatar
Tom Tromey committed
450 451 452 453 454 455 456
  /* If this fd is locked to a certain thread, this points to it.
     Otherwise, this is NULL.  If an fd is locked to a thread, then
     only that thread is permitted to wait on it.  */
  struct thread_state *thread;
  /* If this fd is currently being selected on by a thread, this
     points to the thread.  Otherwise it is NULL.  */
  struct thread_state *waiting_thread;
457
} fd_callback_info[FD_SETSIZE];
458 459 460 461 462 463 464 465 466 467 468 469


/* Add a file descriptor FD to be monitored for when read is possible.
   When read is possible, call FUNC with argument DATA.  */

void
add_read_fd (int fd, fd_callback func, void *data)
{
  add_keyboard_wait_descriptor (fd);

  fd_callback_info[fd].func = func;
  fd_callback_info[fd].data = data;
470 471
}

Tom Tromey's avatar
Tom Tromey committed
472
static void
473 474
add_non_keyboard_read_fd (int fd)
{
Ken Raeburn's avatar
Ken Raeburn committed
475
  eassert (fd >= 0 && fd < FD_SETSIZE);
476
  eassert (fd_callback_info[fd].func == NULL);
Eli Zaretskii's avatar
Eli Zaretskii committed
477 478

  fd_callback_info[fd].flags &= ~KEYBOARD_FD;
479
  fd_callback_info[fd].flags |= FOR_READ;
Tom Tromey's avatar
Tom Tromey committed
480 481
  if (fd > max_desc)
    max_desc = fd;
482 483
}

Tom Tromey's avatar
Tom Tromey committed
484
static void
485 486 487 488
add_process_read_fd (int fd)
{
  add_non_keyboard_read_fd (fd);
  fd_callback_info[fd].flags |= PROCESS_FD;
489 490 491 492 493 494 495 496 497
}

/* Stop monitoring file descriptor FD for when read is possible.  */

void
delete_read_fd (int fd)
{
  delete_keyboard_wait_descriptor (fd);

498
  if (fd_callback_info[fd].flags == 0)
499 500 501 502 503 504 505 506 507 508 509 510
    {
      fd_callback_info[fd].func = 0;
      fd_callback_info[fd].data = 0;
    }
}

/* Add a file descriptor FD to be monitored for when write is possible.
   When write is possible, call FUNC with argument DATA.  */

void
add_write_fd (int fd, fd_callback func, void *data)
{
Eli Zaretskii's avatar
Eli Zaretskii committed
511
  eassert (fd >= 0 && fd < FD_SETSIZE);
512 513 514

  fd_callback_info[fd].func = func;
  fd_callback_info[fd].data = data;
515
  fd_callback_info[fd].flags |= FOR_WRITE;
Eli Zaretskii's avatar
Eli Zaretskii committed
516 517
  if (fd > max_desc)
    max_desc = fd;
518 519
}

Tom Tromey's avatar
Tom Tromey committed
520
static void
521 522
add_non_blocking_write_fd (int fd)
{
Ken Raeburn's avatar
Ken Raeburn committed
523
  eassert (fd >= 0 && fd < FD_SETSIZE);
524 525 526
  eassert (fd_callback_info[fd].func == NULL);

  fd_callback_info[fd].flags |= FOR_WRITE | NON_BLOCKING_CONNECT_FD;
Tom Tromey's avatar
Tom Tromey committed
527 528
  if (fd > max_desc)
    max_desc = fd;
529
  ++num_pending_connects;
530
}
531 532

static void
Tom Tromey's avatar
Tom Tromey committed
533
recompute_max_desc (void)
534
{
Tom Tromey's avatar
Tom Tromey committed
535
  int fd;
536

Tom Tromey's avatar
Tom Tromey committed
537 538 539 540 541 542 543
  for (fd = max_desc; fd >= 0; --fd)
    {
      if (fd_callback_info[fd].flags != 0)
	{
	  max_desc = fd;
	  break;
	}
544 545 546
    }
}

547 548 549 550 551
/* Stop monitoring file descriptor FD for when write is possible.  */

void
delete_write_fd (int fd)
{
552 553 554
  if ((fd_callback_info[fd].flags & NON_BLOCKING_CONNECT_FD) != 0)
    {
      if (--num_pending_connects < 0)
Eli Zaretskii's avatar
Eli Zaretskii committed
555
	emacs_abort ();
556 557 558
    }
  fd_callback_info[fd].flags &= ~(FOR_WRITE | NON_BLOCKING_CONNECT_FD);
  if (fd_callback_info[fd].flags == 0)
559 560 561 562
    {
      fd_callback_info[fd].func = 0;
      fd_callback_info[fd].data = 0;

Tom Tromey's avatar
Tom Tromey committed
563 564
      if (fd == max_desc)
	recompute_max_desc ();
565 566 567 568
    }
}

static void
Ken Raeburn's avatar
Ken Raeburn committed
569
compute_input_wait_mask (fd_set *mask)
570 571
{
  int fd;
572

573
  FD_ZERO (mask);
Tom Tromey's avatar
Tom Tromey committed
574
  for (fd = 0; fd <= max_desc; ++fd)
575
    {
Tom Tromey's avatar
Tom Tromey committed
576 577 578 579 580 581
      if (fd_callback_info[fd].thread != NULL
	  && fd_callback_info[fd].thread != current_thread)
	continue;
      if (fd_callback_info[fd].waiting_thread != NULL
	  && fd_callback_info[fd].waiting_thread != current_thread)
	continue;
582
      if ((fd_callback_info[fd].flags & FOR_READ) != 0)
Tom Tromey's avatar
Tom Tromey committed
583 584 585 586
	{
	  FD_SET (fd, mask);
	  fd_callback_info[fd].waiting_thread = current_thread;
	}
587 588 589
    }
}

590
static void
Ken Raeburn's avatar
Ken Raeburn committed
591
compute_non_process_wait_mask (fd_set *mask)
592 593 594 595
{
  int fd;

  FD_ZERO (mask);
Tom Tromey's avatar
Tom Tromey committed
596
  for (fd = 0; fd <= max_desc; ++fd)
597
    {
Tom Tromey's avatar
Tom Tromey committed
598 599 600 601 602 603
      if (fd_callback_info[fd].thread != NULL
	  && fd_callback_info[fd].thread != current_thread)
	continue;
      if (fd_callback_info[fd].waiting_thread != NULL
	  && fd_callback_info[fd].waiting_thread != current_thread)
	continue;
604 605
      if ((fd_callback_info[fd].flags & FOR_READ) != 0
	  && (fd_callback_info[fd].flags & PROCESS_FD) == 0)
Tom Tromey's avatar
Tom Tromey committed
606 607 608 609
	{
	  FD_SET (fd, mask);
	  fd_callback_info[fd].waiting_thread = current_thread;
	}
610 611 612 613
    }
}

static void
Ken Raeburn's avatar
Ken Raeburn committed
614
compute_non_keyboard_wait_mask (fd_set *mask)
615 616 617 618
{
  int fd;

  FD_ZERO (mask);
Tom Tromey's avatar
Tom Tromey committed
619
  for (fd = 0; fd <= max_desc; ++fd)
620
    {
Tom Tromey's avatar
Tom Tromey committed
621 622 623 624 625 626
      if (fd_callback_info[fd].thread != NULL
	  && fd_callback_info[fd].thread != current_thread)
	continue;
      if (fd_callback_info[fd].waiting_thread != NULL
	  && fd_callback_info[fd].waiting_thread != current_thread)
	continue;
627 628
      if ((fd_callback_info[fd].flags & FOR_READ) != 0
	  && (fd_callback_info[fd].flags & KEYBOARD_FD) == 0)
Tom Tromey's avatar
Tom Tromey committed
629 630 631 632
	{
	  FD_SET (fd, mask);
	  fd_callback_info[fd].waiting_thread = current_thread;
	}
633 634 635 636
    }
}

static void
Ken Raeburn's avatar
Ken Raeburn committed
637
compute_write_mask (fd_set *mask)
638 639 640 641
{
  int fd;

  FD_ZERO (mask);
Tom Tromey's avatar
Tom Tromey committed
642
  for (fd = 0; fd <= max_desc; ++fd)
643
    {
Tom Tromey's avatar
Tom Tromey committed
644 645 646 647 648 649
      if (fd_callback_info[fd].thread != NULL
	  && fd_callback_info[fd].thread != current_thread)
	continue;
      if (fd_callback_info[fd].waiting_thread != NULL
	  && fd_callback_info[fd].waiting_thread != current_thread)
	continue;
650
      if ((fd_callback_info[fd].flags & FOR_WRITE) != 0)
Tom Tromey's avatar
Tom Tromey committed
651 652 653 654
	{
	  FD_SET (fd, mask);
	  fd_callback_info[fd].waiting_thread = current_thread;
	}
655 656 657
    }
}

Tom Tromey's avatar
Tom Tromey committed
658 659 660 661
static void
clear_waiting_thread_info (void)
{
  int fd;
662

Tom Tromey's avatar
Tom Tromey committed
663
  for (fd = 0; fd <= max_desc; ++fd)
Tom Tromey's avatar
Tom Tromey committed
664 665 666
    {
      if (fd_callback_info[fd].waiting_thread == current_thread)
	fd_callback_info[fd].waiting_thread = NULL;
667 668 669
    }
}

Jim Blandy's avatar
Jim Blandy committed
670 671 672 673

/* Compute the Lisp form of the process status, p->status, from
   the numeric status that was returned by `wait'.  */

674
static Lisp_Object status_convert (int);
675

676
static void
677
update_status (struct Lisp_Process *p)
Jim Blandy's avatar
Jim Blandy committed
678
{
679
  eassert (p->raw_status_new);
Paul Eggert's avatar
Paul Eggert committed
680
  pset_status (p, status_convert (p->raw_status));
681
  p->raw_status_new = 0;
Jim Blandy's avatar
Jim Blandy committed
682 683
}

684
/*  Convert a process status word in Unix format to
Jim Blandy's avatar
Jim Blandy committed
685 686
    the list that we use internally.  */

687
static Lisp_Object
688
status_convert (int w)
Jim Blandy's avatar
Jim Blandy committed
689 690
{
  if (WIFSTOPPED (w))
691
    return Fcons (Qstop, Fcons (make_fixnum (WSTOPSIG (w)), Qnil));
Jim Blandy's avatar
Jim Blandy committed
692
  else if (WIFEXITED (w))
693
    return Fcons (Qexit, Fcons (make_fixnum (WEXITSTATUS (w)),
Jim Blandy's avatar
Jim Blandy committed
694 695
				WCOREDUMP (w) ? Qt : Qnil));
  else if (WIFSIGNALED (w))
696
    return Fcons (Qsignal, Fcons (make_fixnum (WTERMSIG (w)),
Jim Blandy's avatar
Jim Blandy committed
697 698 699 700 701
				  WCOREDUMP (w) ? Qt : Qnil));
  else
    return Qrun;
}

702 703 704 705 706 707 708 709
/* True if STATUS is that of a process attempting connection.  */

static bool
connecting_status (Lisp_Object status)
{
  return CONSP (status) && EQ (XCAR (status), Qconnect);
}

Jim Blandy's avatar
Jim Blandy committed
710 711 712
/* Given a status-list, extract the three pieces of information
   and store them individually through the three pointers.  */

713
static void
714 715
decode_status (Lisp_Object l, Lisp_Object *symbol, Lisp_Object *code,
	       bool *coredump)
Jim Blandy's avatar
Jim Blandy committed
716 717 718
{
  Lisp_Object tem;

719 720 721
  if (connecting_status (l))
    l = XCAR (l);

722
  if (SYMBOLP (l))
Jim Blandy's avatar
Jim Blandy committed
723 724
    {
      *symbol = l;
725
      *code = make_fixnum (0);
Jim Blandy's avatar
Jim Blandy committed
726 727 728 729
      *coredump = 0;
    }
  else
    {
730 731
      *symbol = XCAR (l);
      tem = XCDR (l);
732
      *code = XCAR (tem);
733
      tem = XCDR (tem);
Jim Blandy's avatar
Jim Blandy committed
734 735 736 737 738 739
      *coredump = !NILP (tem);
    }
}

/* Return a string describing a process status list.  */

740
static Lisp_Object
741
status_message (struct Lisp_Process *p)
Jim Blandy's avatar
Jim Blandy committed
742
{
743
  Lisp_Object status = p->status;
744
  Lisp_Object symbol, code;
745
  bool coredump;
746
  Lisp_Object string;
Jim Blandy's avatar
Jim Blandy committed
747 748 749 750 751

  decode_status (status, &symbol, &code, &coredump);

  if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
    {
752
      char const *signame;
753
      synchronize_system_messages_locale ();
Tom Tromey's avatar
Tom Tromey committed
754
      signame = strsignal (XFIXNAT (code));
755
      if (signame == 0)
756 757 758 759 760
	string = build_string ("unknown");
      else
	{
	  int c1, c2;

761
	  string = build_unibyte_string (signame);
762 763 764
	  if (! NILP (Vlocale_coding_system))
	    string = (code_convert_string_norecord
		      (string, Vlocale_coding_system, 0));
765
	  c1 = STRING_CHAR (SDATA (string));
766
	  c2 = downcase (c1);
767
	  if (c1 != c2)
768
	    Faset (string, make_fixnum (0), make_fixnum (c2));
769
	}
770 771
      AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
      return concat2 (string, suffix);
Jim Blandy's avatar
Jim Blandy committed
772 773 774
    }
  else if (EQ (symbol, Qexit))
    {
775
      if (NETCONN1_P (p))
Tom Tromey's avatar
Tom Tromey committed
776
	return build_string (XFIXNAT (code) == 0
777 778
			     ? "deleted\n"
			     : "connection broken by remote peer\n");
Tom Tromey's avatar
Tom Tromey committed
779
      if (XFIXNAT (code) == 0)
Jim Blandy's avatar
Jim Blandy committed
780
	return build_string ("finished\n");
781
      AUTO_STRING (prefix, "exited abnormally with code ");
782
      string = Fnumber_to_string (code);
783 784
      AUTO_STRING (suffix, coredump ? " (core dumped)\n" : "\n");
      return concat3 (prefix, string, suffix);
Jim Blandy's avatar
Jim Blandy committed
785
    }
786 787
  else if (EQ (symbol, Qfailed))
    {
788 789
      AUTO_STRING (format, "failed with code %s\n");
      return CALLN (Fformat, format, code);
790
    }
Jim Blandy's avatar
Jim Blandy committed
791 792 793 794
  else
    return Fcopy_sequence (Fsymbol_name (symbol));
}

795
enum { PTY_NAME_SIZE = 24 };
Dan Nicolaescu's avatar
Dan Nicolaescu committed
796

797
/* Open an available pty, returning a file descriptor.
798 799
   Store into PTY_NAME the file name of the terminal corresponding to the pty.
   Return -1 on failure.  */
800

801
static int
802
allocate_pty (char pty_name[PTY_NAME_SIZE])
Jim Blandy's avatar
Jim Blandy committed
803
{
804
#ifdef HAVE_PTYS
Jim Blandy's avatar
Jim Blandy committed
805 806 807 808 809
  int fd;

#ifdef PTY_ITERATION
  PTY_ITERATION
#else
810
  register int c, i;
Jim Blandy's avatar
Jim Blandy committed
811 812 813 814 815 816 817 818 819 820
  for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
    for (i = 0; i < 16; i++)
#endif
      {
#ifdef PTY_NAME_SPRINTF
	PTY_NAME_SPRINTF
#else
	sprintf (pty_name, "/dev/pty%c%x", c, i);
#endif /* no PTY_NAME_SPRINTF */

821 822 823
#ifdef PTY_OPEN
	PTY_OPEN;
#else /* no PTY_OPEN */
824
	fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
825
#endif /* no PTY_OPEN */
Jim Blandy's avatar
Jim Blandy committed
826 827 828

	if (fd >= 0)
	  {
829 830 831 832 833 834
#ifdef PTY_TTY_NAME_SPRINTF
	    PTY_TTY_NAME_SPRINTF
#else
	    sprintf (pty_name, "/dev/tty%c%x", c, i);
#endif /* no PTY_TTY_NAME_SPRINTF */

835 836 837
	    /* Set FD's close-on-exec flag.  This is needed even if
	       PT_OPEN calls posix_openpt with O_CLOEXEC, since POSIX
	       doesn't require support for that combination.
838 839
	       Do this after PTY_TTY_NAME_SPRINTF, which on some platforms
	       doesn't work if the close-on-exec flag is set (Bug#20555).
840 841 842 843
	       Multithreaded platforms where posix_openpt ignores
	       O_CLOEXEC (or where PTY_OPEN doesn't call posix_openpt)
	       have a race condition between the PTY_OPEN and here.  */
	    fcntl (fd, F_SETFD, FD_CLOEXEC);
844 845 846

	    /* Check to make certain that both sides are available.
	       This avoids a nasty yet stupid bug in rlogins.  */
847
	    if (faccessat (AT_FDCWD, pty_name, R_OK | W_OK, AT_EACCESS) != 0)
Jim Blandy's avatar
Jim Blandy committed
848
	      {
849
		emacs_close (fd);
Jim Blandy's avatar
Jim Blandy committed
850 851 852 853 854 855
		continue;
	      }
	    setup_pty (fd);
	    return fd;
	  }
      }
856
#endif /* HAVE_PTYS */
Jim Blandy's avatar
Jim Blandy committed
857 858
  return -1;
}
859 860 861 862 863 864

/* Allocate basically initialized process.  */

static struct Lisp_Process *
allocate_process (void)
{
865 866
  return ALLOCATE_ZEROED_PSEUDOVECTOR (struct Lisp_Process, thread,
				       PVEC_PROCESS);
867 868
}

869
static Lisp_Object
870
make_process (Lisp_Object name)
Jim Blandy's avatar
Jim Blandy committed
871
{
872
  struct Lisp_Process *p = allocate_process ();
873 874
  /* Initialize Lisp data.  Note that allocate_process initializes all
     Lisp data to nil, so do it only for slots which should not be nil.  */
Paul Eggert's avatar
Paul Eggert committed
875 876
  pset_status (p, Qrun);
  pset_mark (p, Fmake_marker ());
Tom Tromey's avatar
Tom Tromey committed
877
  pset_thread (p, Fcurrent_thread ());
Jim Blandy's avatar
Jim Blandy committed
878

879 880 881 882
  /* Initialize non-Lisp data.  Note that allocate_process zeroes out all
     non-Lisp data, so do it only for slots which should not be zero.  */
  p->infd = -1;
  p->outfd = -1;
883
  for (int i = 0; i < PROCESS_OPEN_FDS; i++)
884
    p->open_fd[i] = -1;
Kenichi Handa's avatar
Kenichi Handa committed
885

Ted Zlatanov's avatar
Ted Zlatanov committed
886
#ifdef HAVE_GNUTLS
887 888 889
  verify (GNUTLS_STAGE_EMPTY == 0);
  eassert (p->gnutls_initstage == GNUTLS_STAGE_EMPTY);
  eassert (NILP (p->gnutls_boot_parameters));
Ted Zlatanov's avatar
Ted Zlatanov committed
890 891
#endif

Jim Blandy's avatar
Jim Blandy committed
892 893
  /* If name is already in use, modify it until it is unused.  */

894
  Lisp_Object name1 = name;
Paul Eggert's avatar
Paul Eggert committed
895
  for (intmax_t i = 1; ; i++)
Jim Blandy's avatar
Jim Blandy committed
896
    {
897 898 899
      Lisp_Object tem = Fget_process (name1);
      if (NILP (tem))
	break;
Paul Eggert's avatar
Paul Eggert committed
900 901
      char const suffix_fmt[] = "<%"PRIdMAX">";
      char suffix[sizeof suffix_fmt + INT_STRLEN_BOUND (i)];
902 903
      AUTO_STRING_WITH_LEN (lsuffix, suffix, sprintf (suffix, suffix_fmt, i));
      name1 = concat2 (name, lsuffix);
Jim Blandy's avatar
Jim Blandy committed
904 905
    }
  name = name1;
Paul Eggert's avatar
Paul Eggert committed
906
  pset_name (p, name);
907 908
  pset_sentinel (p, Qinternal_default_process_sentinel);
  pset_filter (p, Qinternal_default_process_filter);
909
  Lisp_Object val;
910
  XSETPROCESS (val, p);
Jim Blandy's avatar
Jim Blandy committed
911 912 913 914
  Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
  return val;
}

915
static void
916
remove_process (register Lisp_Object proc)
Jim Blandy's avatar
Jim Blandy committed
917 918 919 920 921 922 923 924
{
  register Lisp_Object pair;

  pair = Frassq (proc, Vprocess_alist);
  Vprocess_alist = Fdelq (pair, Vprocess_alist);

  deactivate_process (proc);
}
925

Tom Tromey's avatar
Tom Tromey committed
926 927 928 929 930 931 932 933 934 935 936 937
void
update_processes_for_thread_death (Lisp_Object dying_thread)
{
  Lisp_Object pair;

  for (pair = Vprocess_alist; !NILP (pair); pair = XCDR (pair))
    {
      Lisp_Object process = XCDR (XCAR (pair));
      if (EQ (XPROCESS (process)->thread, dying_thread))
	{
	  struct Lisp_Process *proc = XPROCESS (process);

Eli Zaretskii's avatar
Eli Zaretskii committed
938
	  pset_thread (proc, Qnil);
Tom Tromey's avatar
Tom Tromey committed
939 940 941 942 943 944 945 946
	  if (proc->infd >= 0)
	    fd_callback_info[proc->infd].thread = NULL;
	  if (proc->outfd >= 0)
	    fd_callback_info[proc->outfd].thread = NULL;
	}
    }
}

947 948 949 950 951 952
#ifdef HAVE_GETADDRINFO_A
static void
free_dns_request (Lisp_Object proc)
{
  struct Lisp_Process *p = XPROCESS (proc);

953 954 955 956
  if (p->dns_request->ar_result)
    freeaddrinfo (p->dns_request->ar_result);
  xfree (p->dns_request);
  p->dns_request = NULL;
957 958 959
}
#endif

Jim Blandy's avatar
Jim Blandy committed
960 961

DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
962
       doc: /* Return t if OBJECT is a process.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
963
  (Lisp_Object object)
Jim Blandy's avatar
Jim Blandy committed
964
{
965
  return PROCESSP (object) ? Qt : Qnil;
Jim Blandy's avatar
Jim Blandy committed
966 967 968
}

DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
969
       doc: /* Return the process named NAME, or nil if there is none.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
970
  (register Lisp_Object name)
Jim Blandy's avatar
Jim Blandy committed
971
{
972
  if (PROCESSP (name))
Jim Blandy's avatar
Jim Blandy committed
973
    return name;
974
  CHECK_STRING (name);
975
  return Fcdr (Fassoc (name, Vprocess_alist, Qnil));
Jim Blandy's avatar
Jim Blandy committed
976 977
}

Jim Blandy's avatar
Jim Blandy committed
978 979 980 981
/* This is how commands for the user decode process arguments.  It
   accepts a process, a process name, a buffer, a buffer name, or nil.
   Buffers denote the first process in the buffer, and nil denotes the
   current buffer.  */
Jim Blandy's avatar
Jim Blandy committed
982

983
static Lisp_Object
Juanma Barranquero's avatar