robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. KeyesMerge #39626 docsdf5d559878

master
11.0 KiB464 linesraw
1// Some of the code came from pangoterm and libuv
2
3#include <assert.h>
4#include <errno.h>
5#include <fcntl.h>
6#include <signal.h>
7#include <stdlib.h>
8#include <string.h>
9#include <sys/ioctl.h>
10#include <sys/wait.h>
11#include <uv.h>
12
13// forkpty is not in POSIX, so headers are platform-specific
14#if defined(__FreeBSD__) || defined(__DragonFly__)
15# include <libutil.h>
16// TODO(bfredl): this is available on darwin, but there is an issue with cross-compile headers
17#elif defined(__APPLE__) && !defined(HAVE_FORKPTY)
18int forkpty(int *, char *, const struct termios *, const struct winsize *);
19#elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
20# include <util.h>
21#elif defined(__sun)
22# include <fcntl.h>
23# include <signal.h>
24# include <sys/stream.h>
25# include <sys/syscall.h>
26# include <unistd.h>
27#else
28# include <pty.h>
29#endif
30
31#ifdef __APPLE__
32# include <crt_externs.h>
33#endif
34#ifdef __linux__
35# include <poll.h>
36#endif
37
38#include "auto/config.h"
39#include "klib/kvec.h"
40#include "nvim/eval/typval.h"
41#include "nvim/event/defs.h"
42#include "nvim/event/loop.h"
43#include "nvim/event/proc.h"
44#include "nvim/log.h"
45#include "nvim/os/fs.h"
46#include "nvim/os/os_defs.h"
47#include "nvim/os/pty_proc.h"
48#include "nvim/os/pty_proc_unix.h"
49#include "nvim/types_defs.h"
50
51#include "os/pty_proc_unix.c.generated.h"
52
53#if !defined(HAVE_FORKPTY) && !defined(__APPLE__)
54
55// this header defines STR, just as nvim.h, but it is defined as ('S'<<8),
56// to avoid #undef STR, #undef STR, #define STR ('S'<<8) just delay the
57// inclusion of the header even though it gets include out of order.
58
59# if !defined(__HAIKU__)
60#  include <sys/stropts.h>
61# else
62#  define I_PUSH 0  // XXX: find the actual value
63# endif
64
65static int vim_openpty(int *amaster, int *aslave, char *name, struct termios *termp,
66                       struct winsize *winp)
67{
68  int slave = -1;
69  int master = open("/dev/ptmx", O_RDWR);
70  if (master == -1) {
71    goto error;
72  }
73
74  // grantpt will invoke a setuid program to change permissions
75  // and might fail if SIGCHLD handler is set, temporarily reset
76  // while running
77  void (*sig_saved)(int) = signal(SIGCHLD, SIG_DFL);
78  int res = grantpt(master);
79  signal(SIGCHLD, sig_saved);
80
81  if (res == -1 || unlockpt(master) == -1) {
82    goto error;
83  }
84
85  char *slave_name = ptsname(master);
86  if (slave_name == NULL) {
87    goto error;
88  }
89
90  slave = open(slave_name, O_RDWR|O_NOCTTY);
91  if (slave == -1) {
92    goto error;
93  }
94
95  // ptem emulates a terminal when used on a pseudo terminal driver,
96  // must be pushed before ldterm
97  ioctl(slave, I_PUSH, "ptem");
98  // ldterm provides most of the termio terminal interface
99  ioctl(slave, I_PUSH, "ldterm");
100  // ttcompat compatibility with older terminal ioctls
101  ioctl(slave, I_PUSH, "ttcompat");
102
103  if (termp) {
104    tcsetattr(slave, TCSAFLUSH, termp);
105  }
106  if (winp) {
107    ioctl(slave, TIOCSWINSZ, winp);
108  }
109
110  *amaster = master;
111  *aslave = slave;
112  // ignoring name, not passed and size is unknown in the API
113
114  return 0;
115
116error:
117  if (slave != -1) {
118    close(slave);
119  }
120  if (master != -1) {
121    close(master);
122  }
123  return -1;
124}
125
126static int vim_login_tty(int fd)
127{
128  setsid();
129  if (ioctl(fd, TIOCSCTTY, NULL) == -1) {
130    return -1;
131  }
132
133  dup2(fd, STDIN_FILENO);
134  dup2(fd, STDOUT_FILENO);
135  dup2(fd, STDERR_FILENO);
136  if (fd > STDERR_FILENO) {
137    close(fd);
138  }
139
140  return 0;
141}
142
143pid_t vim_forkpty(int *amaster, char *name, struct termios *termp, struct winsize *winp)
144{
145  int master, slave;
146  if (vim_openpty(&master, &slave, name, termp, winp) == -1) {
147    return -1;
148  }
149
150  pid_t pid = fork();
151  switch (pid) {
152  case -1:
153    close(master);
154    close(slave);
155    return -1;
156  case 0:
157    close(master);
158    vim_login_tty(slave);
159    return 0;
160  default:
161    close(slave);
162    *amaster = master;
163    return pid;
164  }
165}
166# define forkpty vim_forkpty
167#endif
168
169/// @returns zero on success, or negative error code
170int pty_proc_spawn(PtyProc *ptyproc)
171  FUNC_ATTR_NONNULL_ALL
172{
173  // termios initialized at first use
174  static struct termios termios_default;
175  if (!termios_default.c_cflag) {
176    init_termios(&termios_default);
177  }
178
179  int status = 0;  // zero or negative error code (libuv convention)
180  Proc *proc = (Proc *)ptyproc;
181  assert(proc->err.s.closed);
182  uv_signal_start(&proc->loop->children_watcher, chld_handler, SIGCHLD);
183  ptyproc->winsize = (struct winsize){ ptyproc->height, ptyproc->width, 0, 0 };
184  uv_disable_stdio_inheritance();
185  int master;
186  int pid = forkpty(&master, NULL, &termios_default, &ptyproc->winsize);
187
188  if (pid < 0) {
189    status = -errno;
190    ELOG("forkpty failed: %s", strerror(errno));
191    return status;
192  } else if (pid == 0) {
193    init_child(ptyproc);  // never returns
194  }
195
196  // make sure the master file descriptor is non blocking
197  int master_status_flags = fcntl(master, F_GETFL);
198  if (master_status_flags == -1) {
199    status = -errno;
200    ELOG("Failed to get master descriptor status flags: %s", strerror(errno));
201    goto error;
202  }
203  if (fcntl(master, F_SETFL, master_status_flags | O_NONBLOCK) == -1) {
204    status = -errno;
205    ELOG("Failed to make master descriptor non-blocking: %s", strerror(errno));
206    goto error;
207  }
208
209  // Other jobs and providers should not get a copy of this file descriptor.
210  if (os_set_cloexec(master) == -1) {
211    status = -errno;
212    ELOG("Failed to set CLOEXEC on ptmx file descriptor");
213    goto error;
214  }
215
216  if (!proc->in.closed
217      && (status = set_duplicating_descriptor(master, &proc->in.uv.pipe))) {
218    goto error;
219  }
220  if (!proc->out.s.closed
221      && (status = set_duplicating_descriptor(master, &proc->out.s.uv.pipe))) {
222    goto error;
223  }
224
225  ptyproc->tty_fd = master;
226  proc->pid = pid;
227  return 0;
228
229error:
230  close(master);
231  kill(pid, SIGKILL);
232  waitpid(pid, NULL, 0);
233  return status;
234}
235
236const char *pty_proc_tty_name(PtyProc *ptyproc)
237{
238  return ptsname(ptyproc->tty_fd);
239}
240
241void pty_proc_resize(PtyProc *ptyproc, uint16_t width, uint16_t height)
242  FUNC_ATTR_NONNULL_ALL
243{
244  ptyproc->winsize = (struct winsize){ height, width, 0, 0 };
245  ioctl(ptyproc->tty_fd, TIOCSWINSZ, &ptyproc->winsize);
246}
247
248void pty_proc_resume(PtyProc *ptyproc)
249  FUNC_ATTR_NONNULL_ALL
250{
251  // Send SIGCONT to the entire process group, as some shells (e.g. fish) don't
252  // propagate SIGCONT to suspended child processes.
253  killpg(((Proc *)ptyproc)->pid, SIGCONT);
254}
255
256/// On Linux, libuv's polling (which uses epoll) doesn't flush PTY master's pending
257/// work on kernel workqueue, so use an explicit poll() before that. #37982
258/// Note that poll() only flushes pending work if no data is immediately available,
259/// so this function is needed before every libuv poll in flush_stream().
260void pty_proc_flush_master(PtyProc *ptyproc)
261  FUNC_ATTR_NONNULL_ALL
262{
263#ifdef __linux__
264  struct pollfd pollfd = { .fd = ptyproc->tty_fd, .events = POLLIN };
265  int n = 0;
266  do {
267    n = poll(&pollfd, 1, 0);
268  } while (n < 0 && errno == EINTR);
269#endif
270}
271
272void pty_proc_close(PtyProc *ptyproc)
273  FUNC_ATTR_NONNULL_ALL
274{
275  pty_proc_close_master(ptyproc);
276  Proc *proc = (Proc *)ptyproc;
277  if (proc->internal_close_cb) {
278    proc->internal_close_cb(proc);
279  }
280}
281
282void pty_proc_close_master(PtyProc *ptyproc)
283  FUNC_ATTR_NONNULL_ALL
284{
285  if (ptyproc->tty_fd >= 0) {
286    close(ptyproc->tty_fd);
287    ptyproc->tty_fd = -1;
288  }
289}
290
291void pty_proc_teardown(Loop *loop)
292{
293  uv_signal_stop(&loop->children_watcher);
294}
295
296static void init_child(PtyProc *ptyproc)
297  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NORETURN
298{
299#ifdef HAVE__NSGETENVIRON
300# define environ (*_NSGetEnviron())
301#else
302  extern char **environ;
303#endif
304  // New session/process-group. #6530
305  setsid();
306
307  signal(SIGCHLD, SIG_DFL);
308  signal(SIGHUP, SIG_DFL);
309  signal(SIGINT, SIG_DFL);
310  signal(SIGQUIT, SIG_DFL);
311  signal(SIGTERM, SIG_DFL);
312  signal(SIGALRM, SIG_DFL);
313
314  Proc *proc = (Proc *)ptyproc;
315  int err = 0;
316  // Don't use os_chdir() as that may buffer UI events unnecessarily.
317  if (proc->cwd && (err = uv_chdir(proc->cwd)) != 0) {
318    ELOG("chdir(%s) failed: %s", proc->cwd, uv_strerror(err));
319    _exit(122);
320  }
321
322  const char *prog = proc_get_exepath(proc);
323
324  assert(proc->env);
325  environ = tv_dict_to_env(proc->env);
326  execvp(prog, proc->argv);
327  ELOG("execvp(%s) failed: %s", prog, strerror(errno));
328
329  _exit(122);  // 122 is EXEC_FAILED in the Vim source.
330}
331
332static void init_termios(struct termios *termios) FUNC_ATTR_NONNULL_ALL
333{
334  // Taken from pangoterm
335  termios->c_iflag = ICRNL|IXON;
336  termios->c_oflag = OPOST|ONLCR;
337#ifdef TAB0
338  termios->c_oflag |= TAB0;
339#endif
340  termios->c_cflag = CS8|CREAD;
341  termios->c_lflag = ISIG|ICANON|IEXTEN|ECHO|ECHOE|ECHOK;
342
343  // not using cfsetspeed, not available on all platforms
344  cfsetispeed(termios, 38400);
345  cfsetospeed(termios, 38400);
346
347#ifdef IUTF8
348  termios->c_iflag |= IUTF8;
349#endif
350#ifdef NL0
351  termios->c_oflag |= NL0;
352#endif
353#ifdef CR0
354  termios->c_oflag |= CR0;
355#endif
356#ifdef BS0
357  termios->c_oflag |= BS0;
358#endif
359#ifdef VT0
360  termios->c_oflag |= VT0;
361#endif
362#ifdef FF0
363  termios->c_oflag |= FF0;
364#endif
365#ifdef ECHOCTL
366  termios->c_lflag |= ECHOCTL;
367#endif
368#ifdef ECHOKE
369  termios->c_lflag |= ECHOKE;
370#endif
371
372  termios->c_cc[VINTR] = 0x1f & 'C';
373  termios->c_cc[VQUIT] = 0x1f & '\\';
374  termios->c_cc[VERASE] = 0x7f;
375  termios->c_cc[VKILL] = 0x1f & 'U';
376  termios->c_cc[VEOF] = 0x1f & 'D';
377  termios->c_cc[VEOL] = _POSIX_VDISABLE;
378  termios->c_cc[VEOL2] = _POSIX_VDISABLE;
379  termios->c_cc[VSTART] = 0x1f & 'Q';
380  termios->c_cc[VSTOP] = 0x1f & 'S';
381  termios->c_cc[VSUSP] = 0x1f & 'Z';
382#if !defined(__HAIKU__)
383  termios->c_cc[VREPRINT] = 0x1f & 'R';
384  termios->c_cc[VWERASE] = 0x1f & 'W';
385  termios->c_cc[VLNEXT] = 0x1f & 'V';
386#endif
387  termios->c_cc[VMIN] = 1;
388  termios->c_cc[VTIME] = 0;
389}
390
391static int set_duplicating_descriptor(int fd, uv_pipe_t *pipe)
392  FUNC_ATTR_NONNULL_ALL
393{
394  int status = 0;  // zero or negative error code (libuv convention)
395  int fd_dup = dup(fd);
396  if (fd_dup < 0) {
397    status = -errno;
398    ELOG("Failed to dup descriptor %d: %s", fd, strerror(errno));
399    return status;
400  }
401
402  if (os_set_cloexec(fd_dup) == -1) {
403    status = -errno;
404    ELOG("Failed to set CLOEXEC on duplicate fd");
405    goto error;
406  }
407
408  status = uv_pipe_open(pipe, fd_dup);
409  if (status) {
410    ELOG("Failed to set pipe to descriptor %d: %s",
411         fd_dup, uv_strerror(status));
412    goto error;
413  }
414  return status;
415
416error:
417  close(fd_dup);
418  return status;
419}
420
421static void chld_handler(uv_signal_t *handle, int signum)
422{
423  int stat = 0;
424  int pid;
425
426  Loop *loop = handle->loop->data;
427
428  for (size_t i = 0; i < kv_size(loop->children); i++) {
429    Proc *proc = kv_A(loop->children, i);
430    do {
431      pid = waitpid(proc->pid, &stat, WNOHANG|WUNTRACED|WCONTINUED);
432    } while (pid < 0 && errno == EINTR);
433
434    if (pid <= 0) {
435      continue;
436    }
437
438    if (WIFSTOPPED(stat)) {
439      proc->state_cb(proc, true, proc->data);
440      continue;
441    }
442    if (WIFCONTINUED(stat)) {
443      proc->state_cb(proc, false, proc->data);
444      continue;
445    }
446
447    if (WIFEXITED(stat)) {
448      proc->status = WEXITSTATUS(stat);
449    } else if (WIFSIGNALED(stat)) {
450      proc->status = 128 + WTERMSIG(stat);
451    }
452    proc->internal_exit_cb(proc);
453  }
454}
455
456PtyProc pty_proc_init(Loop *loop, void *data)
457{
458  PtyProc rv = { 0 };
459  rv.proc = proc_init(loop, kProcTypePty, data);
460  rv.width = 80;
461  rv.height = 24;
462  rv.tty_fd = -1;
463  return rv;
464}