robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
df5d559878
master
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 , 66struct winsize * winp ) 67{ 68int slave = -1 ; 69int master = open ("/dev/ptmx" ,O_RDWR ); 70if (master == -1 ) { 71 gotoerror ; 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 77void (* sig_saved )(int )= signal (SIGCHLD ,SIG_DFL ); 78int res = grantpt (master ); 79signal (SIGCHLD ,sig_saved ); 80 81if (res == -1 || unlockpt (master )== -1 ) { 82 gotoerror ; 83 } 84 85char * slave_name = ptsname (master ); 86if (slave_name == NULL ) { 87 gotoerror ; 88 } 89 90slave = open (slave_name ,O_RDWR |O_NOCTTY ); 91if (slave == -1 ) { 92 gotoerror ; 93 } 94 95// ptem emulates a terminal when used on a pseudo terminal driver, 96// must be pushed before ldterm 97ioctl (slave ,I_PUSH ,"ptem" ); 98// ldterm provides most of the termio terminal interface 99ioctl (slave ,I_PUSH ,"ldterm" ); 100// ttcompat compatibility with older terminal ioctls 101ioctl (slave ,I_PUSH ,"ttcompat" ); 102 103if (termp ) { 104tcsetattr (slave ,TCSAFLUSH ,termp ); 105 } 106if (winp ) { 107ioctl (slave ,TIOCSWINSZ ,winp ); 108 } 109 110* amaster = master ; 111* aslave = slave ; 112// ignoring name, not passed and size is unknown in the API 113 114return 0 ; 115 116error : 117if (slave != -1 ) { 118close (slave ); 119 } 120if (master != -1 ) { 121close (master ); 122 } 123return -1 ; 124} 125 126static int vim_login_tty (int fd ) 127{ 128setsid (); 129if (ioctl (fd ,TIOCSCTTY ,NULL )== -1 ) { 130return -1 ; 131 } 132 133dup2 (fd ,STDIN_FILENO ); 134dup2 (fd ,STDOUT_FILENO ); 135dup2 (fd ,STDERR_FILENO ); 136if (fd > STDERR_FILENO ) { 137close (fd ); 138 } 139 140return 0 ; 141} 142 143pid_t vim_forkpty (int * amaster ,char * name ,struct termios * termp ,struct winsize * winp ) 144{ 145int master ,slave ; 146if (vim_openpty (& master ,& slave ,name ,termp ,winp )== -1 ) { 147return -1 ; 148 } 149 150pid_t pid = fork (); 151switch (pid ) { 152case -1 : 153close (master ); 154close (slave ); 155return -1 ; 156case 0 : 157close (master ); 158vim_login_tty (slave ); 159return 0 ; 160default : 161close (slave ); 162* amaster = master ; 163return 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 ) 171FUNC_ATTR_NONNULL_ALL 172{ 173// termios initialized at first use 174static struct termios termios_default ; 175if (!termios_default .c_cflag ) { 176init_termios (& termios_default ); 177 } 178 179int status = 0 ;// zero or negative error code (libuv convention) 180Proc * proc = (Proc * )ptyproc ; 181assert (proc -> err .s .closed ); 182uv_signal_start (& proc -> loop -> children_watcher ,chld_handler ,SIGCHLD ); 183ptyproc -> winsize = (struct winsize ){ptyproc -> height ,ptyproc -> width ,0 ,0 }; 184uv_disable_stdio_inheritance (); 185int master ; 186int pid = forkpty (& master ,NULL ,& termios_default ,& ptyproc -> winsize ); 187 188if (pid < 0 ) { 189status = - errno ; 190ELOG ("forkpty failed: %s" ,strerror (errno )); 191return status ; 192 }else if (pid == 0 ) { 193init_child (ptyproc );// never returns 194 } 195 196// make sure the master file descriptor is non blocking 197int master_status_flags = fcntl (master ,F_GETFL ); 198if (master_status_flags == -1 ) { 199status = - errno ; 200ELOG ("Failed to get master descriptor status flags: %s" ,strerror (errno )); 201 gotoerror ; 202 } 203if (fcntl (master ,F_SETFL ,master_status_flags |O_NONBLOCK )== -1 ) { 204status = - errno ; 205ELOG ("Failed to make master descriptor non-blocking: %s" ,strerror (errno )); 206 gotoerror ; 207 } 208 209// Other jobs and providers should not get a copy of this file descriptor. 210if (os_set_cloexec (master )== -1 ) { 211status = - errno ; 212ELOG ("Failed to set CLOEXEC on ptmx file descriptor" ); 213 gotoerror ; 214 } 215 216if (!proc -> in .closed 217&& (status = set_duplicating_descriptor (master ,& proc -> in .uv .pipe ))) { 218 gotoerror ; 219 } 220if (!proc -> out .s .closed 221&& (status = set_duplicating_descriptor (master ,& proc -> out .s .uv .pipe ))) { 222 gotoerror ; 223 } 224 225ptyproc -> tty_fd = master ; 226proc -> pid = pid ; 227return 0 ; 228 229error : 230close (master ); 231kill (pid ,SIGKILL ); 232waitpid (pid ,NULL ,0 ); 233return status ; 234} 235 236const char * pty_proc_tty_name (PtyProc * ptyproc ) 237{ 238return ptsname (ptyproc -> tty_fd ); 239} 240 241void pty_proc_resize (PtyProc * ptyproc ,uint16_t width ,uint16_t height ) 242FUNC_ATTR_NONNULL_ALL 243{ 244ptyproc -> winsize = (struct winsize ){height ,width ,0 ,0 }; 245ioctl (ptyproc -> tty_fd ,TIOCSWINSZ ,& ptyproc -> winsize ); 246} 247 248void pty_proc_resume (PtyProc * ptyproc ) 249FUNC_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. 253killpg (((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 ) 261FUNC_ATTR_NONNULL_ALL 262{ 263#ifdef __linux__ 264struct pollfd pollfd = { .fd = ptyproc -> tty_fd , .events = POLLIN }; 265int n = 0 ; 266do { 267n = poll (& pollfd ,1 ,0 ); 268 }while (n < 0 && errno == EINTR ); 269#endif 270} 271 272void pty_proc_close (PtyProc * ptyproc ) 273FUNC_ATTR_NONNULL_ALL 274{ 275pty_proc_close_master (ptyproc ); 276Proc * proc = (Proc * )ptyproc ; 277if (proc -> internal_close_cb ) { 278proc -> internal_close_cb (proc ); 279 } 280} 281 282void pty_proc_close_master (PtyProc * ptyproc ) 283FUNC_ATTR_NONNULL_ALL 284{ 285if (ptyproc -> tty_fd >=0 ) { 286close (ptyproc -> tty_fd ); 287ptyproc -> tty_fd = -1 ; 288 } 289} 290 291void pty_proc_teardown (Loop * loop ) 292{ 293uv_signal_stop (& loop -> children_watcher ); 294} 295 296static void init_child (PtyProc * ptyproc ) 297FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NORETURN 298{ 299#ifdef HAVE__NSGETENVIRON 300# define environ (*_NSGetEnviron()) 301#else 302extern char ** environ ; 303#endif 304// New session/process-group. #6530 305setsid (); 306 307signal (SIGCHLD ,SIG_DFL ); 308signal (SIGHUP ,SIG_DFL ); 309signal (SIGINT ,SIG_DFL ); 310signal (SIGQUIT ,SIG_DFL ); 311signal (SIGTERM ,SIG_DFL ); 312signal (SIGALRM ,SIG_DFL ); 313 314Proc * proc = (Proc * )ptyproc ; 315int err = 0 ; 316// Don't use os_chdir() as that may buffer UI events unnecessarily. 317if (proc -> cwd && (err = uv_chdir (proc -> cwd ))!= 0 ) { 318ELOG ("chdir(%s) failed: %s" ,proc -> cwd ,uv_strerror (err )); 319_exit (122 ); 320 } 321 322const char * prog = proc_get_exepath (proc ); 323 324assert (proc -> env ); 325environ = tv_dict_to_env (proc -> env ); 326execvp (prog ,proc -> argv ); 327ELOG ("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 335termios -> c_iflag = ICRNL |IXON ; 336termios -> c_oflag = OPOST |ONLCR ; 337#ifdef TAB0 338termios -> c_oflag |=TAB0 ; 339#endif 340termios -> c_cflag = CS8 |CREAD ; 341termios -> c_lflag = ISIG |ICANON |IEXTEN |ECHO |ECHOE |ECHOK ; 342 343// not using cfsetspeed, not available on all platforms 344cfsetispeed (termios ,38400 ); 345cfsetospeed (termios ,38400 ); 346 347#ifdef IUTF8 348termios -> c_iflag |=IUTF8 ; 349#endif 350#ifdef NL0 351termios -> c_oflag |=NL0 ; 352#endif 353#ifdef CR0 354termios -> c_oflag |=CR0 ; 355#endif 356#ifdef BS0 357termios -> c_oflag |=BS0 ; 358#endif 359#ifdef VT0 360termios -> c_oflag |=VT0 ; 361#endif 362#ifdef FF0 363termios -> c_oflag |=FF0 ; 364#endif 365#ifdef ECHOCTL 366termios -> c_lflag |=ECHOCTL ; 367#endif 368#ifdef ECHOKE 369termios -> c_lflag |=ECHOKE ; 370#endif 371 372termios -> c_cc [VINTR ]= 0x1f & 'C' ; 373termios -> c_cc [VQUIT ]= 0x1f & '\\' ; 374termios -> c_cc [VERASE ]= 0x7f ; 375termios -> c_cc [VKILL ]= 0x1f & 'U' ; 376termios -> c_cc [VEOF ]= 0x1f & 'D' ; 377termios -> c_cc [VEOL ]= _POSIX_VDISABLE ; 378termios -> c_cc [VEOL2 ]= _POSIX_VDISABLE ; 379termios -> c_cc [VSTART ]= 0x1f & 'Q' ; 380termios -> c_cc [VSTOP ]= 0x1f & 'S' ; 381termios -> c_cc [VSUSP ]= 0x1f & 'Z' ; 382#if !defined(__HAIKU__ ) 383termios -> c_cc [VREPRINT ]= 0x1f & 'R' ; 384termios -> c_cc [VWERASE ]= 0x1f & 'W' ; 385termios -> c_cc [VLNEXT ]= 0x1f & 'V' ; 386#endif 387termios -> c_cc [VMIN ]= 1 ; 388termios -> c_cc [VTIME ]= 0 ; 389} 390 391static int set_duplicating_descriptor (int fd ,uv_pipe_t * pipe ) 392FUNC_ATTR_NONNULL_ALL 393{ 394int status = 0 ;// zero or negative error code (libuv convention) 395int fd_dup = dup (fd ); 396if (fd_dup < 0 ) { 397status = - errno ; 398ELOG ("Failed to dup descriptor %d: %s" ,fd ,strerror (errno )); 399return status ; 400 } 401 402if (os_set_cloexec (fd_dup )== -1 ) { 403status = - errno ; 404ELOG ("Failed to set CLOEXEC on duplicate fd" ); 405 gotoerror ; 406 } 407 408status = uv_pipe_open (pipe ,fd_dup ); 409if (status ) { 410ELOG ("Failed to set pipe to descriptor %d: %s" , 411fd_dup ,uv_strerror (status )); 412 gotoerror ; 413 } 414return status ; 415 416error : 417close (fd_dup ); 418return status ; 419} 420 421static void chld_handler (uv_signal_t * handle ,int signum ) 422{ 423int stat = 0 ; 424int pid ; 425 426Loop * loop = handle -> loop -> data ; 427 428for (size_t i = 0 ;i < kv_size (loop -> children );i ++ ) { 429Proc * proc = kv_A (loop -> children ,i ); 430do { 431pid = waitpid (proc -> pid ,& stat ,WNOHANG |WUNTRACED |WCONTINUED ); 432 }while (pid < 0 && errno == EINTR ); 433 434if (pid <=0 ) { 435continue ; 436 } 437 438if (WIFSTOPPED (stat )) { 439proc -> state_cb (proc , true,proc -> data ); 440continue ; 441 } 442if (WIFCONTINUED (stat )) { 443proc -> state_cb (proc , false,proc -> data ); 444continue ; 445 } 446 447if (WIFEXITED (stat )) { 448proc -> status = WEXITSTATUS (stat ); 449 }else if (WIFSIGNALED (stat )) { 450proc -> status = 128 + WTERMSIG (stat ); 451 } 452proc -> internal_exit_cb (proc ); 453 } 454} 455 456PtyProc pty_proc_init (Loop * loop ,void * data ) 457{ 458PtyProc rv = {0 }; 459rv .proc = proc_init (loop ,kProcTypePty ,data ); 460rv .width = 80 ; 461rv .height = 24 ; 462rv .tty_fd = -1 ; 463return rv ; 464}