robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
9c15a382de
master
1#include <assert.h> 2#include <inttypes.h> 3#include <signal.h> 4#include <string.h> 5#include <uv.h> 6 7#include "klib/kvec.h" 8#include "nvim/event/libuv_proc.h" 9#include "nvim/event/loop.h" 10#include "nvim/event/multiqueue.h" 11#include "nvim/event/proc.h" 12#include "nvim/event/rstream.h" 13#include "nvim/event/stream.h" 14#include "nvim/event/wstream.h" 15#include "nvim/globals.h" 16#include "nvim/log.h" 17#include "nvim/main.h" 18#include "nvim/memory_defs.h" 19#include "nvim/os/proc.h" 20#include "nvim/os/pty_proc.h" 21#include "nvim/os/shell.h" 22#include "nvim/os/time.h" 23#include "nvim/ui_client.h" 24 25#include "event/proc.c.generated.h" 26 27// Time for a process to exit cleanly before we send KILL. 28// For PTY processes SIGTERM is sent first (in case SIGHUP was not enough). 29#define KILL_TIMEOUT_MS 2000 30 31/// Externally defined with gcov. 32#ifdef USE_GCOV 33void __gcov_flush (void ); 34#endif 35 36static bool proc_is_tearing_down = false; 37 38// Delay exit until handles are closed, to avoid deadlocks 39static int exit_need_delay = 0 ; 40 41/// @returns zero on success, or negative error code 42int proc_spawn (Proc * proc ,bool in ,bool out ,bool err ) 43FUNC_ATTR_NONNULL_ALL 44{ 45// forwarding stderr contradicts with processing it internally 46assert (!(err && proc -> fwd_err )); 47 48if (in ) { 49uv_pipe_init (& proc -> loop -> uv ,& proc -> in .uv .pipe ,0 ); 50 }else { 51proc -> in .closed = true; 52 } 53 54if (out ) { 55uv_pipe_init (& proc -> loop -> uv ,& proc -> out .s .uv .pipe ,0 ); 56 }else { 57proc -> out .s .closed = true; 58 } 59 60if (err ) { 61uv_pipe_init (& proc -> loop -> uv ,& proc -> err .s .uv .pipe ,0 ); 62 }else { 63proc -> err .s .closed = true; 64 } 65 66#ifdef USE_GCOV 67// Flush coverage data before forking, to avoid "Merge mismatch" errors. 68__gcov_flush (); 69#endif 70 71int status ; 72switch (proc -> type ) { 73case kProcTypeUv : 74status = libuv_proc_spawn ((LibuvProc * )proc ); 75break ; 76case kProcTypePty : 77status = pty_proc_spawn ((PtyProc * )proc ); 78break ; 79 } 80 81if (status ) { 82if (in ) { 83uv_close ((uv_handle_t * )& proc -> in .uv .pipe ,NULL ); 84 } 85if (out ) { 86uv_close ((uv_handle_t * )& proc -> out .s .uv .pipe ,NULL ); 87 } 88if (err ) { 89uv_close ((uv_handle_t * )& proc -> err .s .uv .pipe ,NULL ); 90 } 91 92if (proc -> type == kProcTypeUv ) { 93uv_close ((uv_handle_t * )& (((LibuvProc * )proc )-> uv ),NULL ); 94 }else { 95proc_close (proc ); 96 } 97proc_free (proc ); 98proc -> status = -1 ; 99return status ; 100 } 101 102if (in ) { 103stream_init (NULL ,& proc -> in ,-1 , (uv_stream_t * )& proc -> in .uv .pipe ); 104proc -> in .internal_data = proc ; 105proc -> in .internal_close_cb = on_proc_stream_close ; 106proc -> refcount ++ ; 107 } 108 109if (out ) { 110stream_init (NULL ,& proc -> out .s ,-1 , (uv_stream_t * )& proc -> out .s .uv .pipe ); 111proc -> out .s .internal_data = proc ; 112proc -> out .s .internal_close_cb = on_proc_stream_close ; 113proc -> refcount ++ ; 114 } 115 116if (err ) { 117stream_init (NULL ,& proc -> err .s ,-1 , (uv_stream_t * )& proc -> err .s .uv .pipe ); 118proc -> err .s .internal_data = proc ; 119proc -> err .s .internal_close_cb = on_proc_stream_close ; 120proc -> refcount ++ ; 121 } 122 123proc -> internal_exit_cb = on_proc_exit ; 124proc -> internal_close_cb = decref ; 125proc -> refcount ++ ; 126kv_push (proc -> loop -> children ,proc ); 127DLOG ("new: pid=%d exepath=[%s]" ,proc -> pid ,proc_get_exepath (proc )); 128return 0 ; 129} 130 131void proc_teardown (Loop * loop )FUNC_ATTR_NONNULL_ALL 132{ 133proc_is_tearing_down = true; 134for (size_t i = 0 ;i < kv_size (loop -> children );i ++ ) { 135Proc * proc = kv_A (loop -> children ,i ); 136if (proc -> detach || proc -> type == kProcTypePty ) { 137// Close handles to process without killing it. 138CREATE_EVENT (loop -> events ,proc_close_handles ,proc ); 139 }else { 140proc_stop (proc ); 141 } 142 } 143 144// Wait until all children exit and all close events are processed. 145LOOP_PROCESS_EVENTS_UNTIL (loop ,loop -> events ,-1 , 146kv_size (loop -> children )== 0 && multiqueue_empty (loop -> events )); 147pty_proc_teardown (loop ); 148} 149 150void proc_close_streams (Proc * proc )FUNC_ATTR_NONNULL_ALL 151{ 152stream_may_close (& proc -> in ); 153rstream_may_close (& proc -> out ); 154rstream_may_close (& proc -> err ); 155} 156 157/// Synchronously wait for a process to finish 158/// 159/// @param process Process instance 160/// @param ms Time in milliseconds to wait for the process. 161/// 0 for no wait. -1 to wait until the process quits. 162/// @return Exit code of the process. proc->status will have the same value. 163/// -1 if the timeout expired while the process is still running. 164/// -2 if the user interrupted the wait. 165int proc_wait (Proc * proc ,int ms ,MultiQueue * events ) 166FUNC_ATTR_NONNULL_ARG (1 ) 167{ 168if (!proc -> refcount ) { 169int status = proc -> status ; 170LOOP_PROCESS_EVENTS (proc -> loop ,proc -> events ,0 ); 171return status ; 172 } 173 174if (!events ) { 175events = proc -> events ; 176 } 177 178// Increase refcount to stop the exit callback from being called (and possibly 179// freed) before we have a chance to get the status. 180proc -> refcount ++ ; 181LOOP_PROCESS_EVENTS_UNTIL (proc -> loop ,events ,ms , 182// Until... 183got_int // interrupted by the user 184|| proc -> refcount == 1 );// job exited 185 186// Assume that a user hitting CTRL-C does not like the current job. Kill it. 187if (got_int ) { 188got_int = false; 189proc_stop (proc ); 190if (ms == -1 ) { 191// We can only return if all streams/handles are closed and the job 192// exited. 193LOOP_PROCESS_EVENTS_UNTIL (proc -> loop ,events ,-1 , 194proc -> refcount == 1 ); 195 }else { 196LOOP_PROCESS_EVENTS (proc -> loop ,events ,0 ); 197 } 198 199proc -> status = -2 ; 200 } 201 202if (proc -> refcount == 1 ) { 203// Job exited, free its resources. 204decref (proc ); 205if (proc -> events ) { 206// decref() created an exit event, process it now. 207multiqueue_process_events (proc -> events ); 208 } 209 }else { 210proc -> refcount -- ; 211 } 212 213return proc -> status ; 214} 215 216/// Ask a process to terminate and eventually kill if it doesn't respond 217void proc_stop (Proc * proc )FUNC_ATTR_NONNULL_ALL 218{ 219bool exited = (proc -> status >=0 ); 220if (exited || proc -> stopped_time ) { 221return ; 222 } 223proc -> stopped_time = os_hrtime (); 224 225switch (proc -> type ) { 226case kProcTypeUv : 227proc -> exit_signal = SIGTERM ; 228os_proc_tree_kill (proc -> pid ,SIGTERM ); 229break ; 230case kProcTypePty : 231// close all streams for pty processes to send SIGHUP to the process 232proc -> exit_signal = SIGHUP ; 233proc_close_streams (proc ); 234pty_proc_close_master ((PtyProc * )proc ); 235break ; 236 } 237 238// (Re)start timer to verify that stopped process(es) died. 239uv_timer_start (& proc -> loop -> children_kill_timer ,children_kill_cb , 240KILL_TIMEOUT_MS ,0 ); 241} 242 243/// Frees process-owned resources. 244void proc_free (Proc * proc )FUNC_ATTR_NONNULL_ALL 245{ 246if (proc -> argv != NULL ) { 247shell_free_argv (proc -> argv ); 248proc -> argv = NULL ; 249 } 250} 251 252/// Sends SIGKILL (or SIGTERM..SIGKILL for PTY jobs) to processes that did 253/// not terminate after proc_stop(). 254static void children_kill_cb (uv_timer_t * handle ) 255{ 256Loop * loop = handle -> loop -> data ; 257 258for (size_t i = 0 ;i < kv_size (loop -> children );i ++ ) { 259Proc * proc = kv_A (loop -> children ,i ); 260bool exited = (proc -> status >=0 ); 261if (exited || !proc -> stopped_time ) { 262continue ; 263 } 264uint64_t term_sent = UINT64_MAX == proc -> stopped_time ; 265if (kProcTypePty != proc -> type || term_sent ) { 266proc -> exit_signal = SIGKILL ; 267os_proc_tree_kill (proc -> pid ,SIGKILL ); 268 }else { 269proc -> exit_signal = SIGTERM ; 270os_proc_tree_kill (proc -> pid ,SIGTERM ); 271proc -> stopped_time = UINT64_MAX ;// Flag: SIGTERM was sent. 272// Restart timer. 273uv_timer_start (& proc -> loop -> children_kill_timer ,children_kill_cb , 274KILL_TIMEOUT_MS ,0 ); 275 } 276 } 277} 278 279static void proc_close_event (void ** argv ) 280{ 281Proc * proc = argv [0 ]; 282if (proc -> cb ) { 283// User (hint: channel_job_start) is responsible for calling 284// proc_free(). 285proc -> cb (proc ,proc -> status ,proc -> data ); 286 }else { 287proc_free (proc ); 288 } 289} 290 291static void decref (Proc * proc ) 292{ 293if (-- proc -> refcount != 0 ) { 294return ; 295 } 296 297Loop * loop = proc -> loop ; 298size_t i ; 299for (i = 0 ;i < kv_size (loop -> children );i ++ ) { 300Proc * current = kv_A (loop -> children ,i ); 301if (current == proc ) { 302break ; 303 } 304 } 305assert (i < kv_size (loop -> children ));// element found 306if (i < kv_size (loop -> children )- 1 ) { 307memmove (& kv_A (loop -> children ,i ),& kv_A (loop -> children ,i + 1 ), 308sizeof (& kv_A (loop -> children ,i ))* (kv_size (loop -> children )- (i + 1 ))); 309 } 310kv_size (loop -> children )-- ; 311CREATE_EVENT (proc -> events ,proc_close_event ,proc ); 312} 313 314static void proc_close (Proc * proc ) 315FUNC_ATTR_NONNULL_ARG (1 ) 316{ 317if (proc_is_tearing_down && proc -> closed && (proc -> detach || proc -> type == kProcTypePty )) { 318// If a detached/pty process dies while tearing down it might get closed twice. 319return ; 320 } 321assert (!proc -> closed ); 322proc -> closed = true; 323 324if (proc -> detach ) { 325if (proc -> type == kProcTypeUv ) { 326uv_unref ((uv_handle_t * )& (((LibuvProc * )proc )-> uv )); 327 } 328 } 329 330switch (proc -> type ) { 331case kProcTypeUv : 332libuv_proc_close ((LibuvProc * )proc ); 333break ; 334case kProcTypePty : 335pty_proc_close ((PtyProc * )proc ); 336break ; 337 } 338} 339 340/// Flush output stream. 341/// 342/// @param proc Process, for which an output stream should be flushed. 343/// @param stream Stream to flush. 344static void flush_stream (Proc * proc ,RStream * stream ) 345FUNC_ATTR_NONNULL_ARG (1 ) 346{ 347if (!stream || stream -> s .closed ) { 348return ; 349 } 350 351size_t max_bytes = SIZE_MAX ; 352#ifdef MSWIN 353if (true) { 354#else 355// Don't limit remaining data size of PTY master unless when tearing down, as it may 356// have more remaining data than system buffer size (at least on Linux). #3030 357if (proc -> type != kProcTypePty || proc_is_tearing_down ) { 358#endif 359// Maximal remaining data size of terminated process is system buffer size. 360// Also helps with a child process that keeps the output streams open. If it 361// keeps sending data, we only accept as much data as the system buffer size. 362// Otherwise this would block cleanup/teardown. 363int system_buffer_size = 0 ; 364// All members of the stream->s.uv union share the same address. 365int err = uv_recv_buffer_size ((uv_handle_t * )& stream -> s .uv ,& system_buffer_size ); 366if (err != 0 ) { 367system_buffer_size = ARENA_BLOCK_SIZE ; 368 } 369max_bytes = stream -> num_bytes + (size_t )system_buffer_size ; 370 } 371 372// Read remaining data. 373while (!stream -> s .closed && stream -> num_bytes < max_bytes ) { 374// Remember number of bytes before polling. 375size_t num_bytes = stream -> num_bytes ; 376 377if (proc -> type == kProcTypePty && !stream -> did_eof ) { 378pty_proc_flush_master ((PtyProc * )proc ); 379 } 380// Poll for data and process the generated events. 381loop_poll_events (proc -> loop ,0 ); 382if (stream -> s .events ) { 383multiqueue_process_events (stream -> s .events ); 384 } 385 386// Stream can be closed if it is empty. 387if (num_bytes == stream -> num_bytes ) { 388if (stream -> read_cb && !stream -> did_eof ) { 389// Stream callback could miss EOF handling if a child keeps the stream 390// open. But only send EOF if we haven't already. 391stream -> read_cb (stream ,stream -> buffer ,0 ,stream -> s .cb_data , true); 392 } 393break ; 394 } 395 } 396} 397 398static void proc_close_handles (void ** argv ) 399{ 400Proc * proc = argv [0 ]; 401 402exit_need_delay ++ ; 403flush_stream (proc ,& proc -> out ); 404flush_stream (proc ,& proc -> err ); 405 406proc_close_streams (proc ); 407proc_close (proc ); 408exit_need_delay -- ; 409} 410 411static void exit_delay_cb (uv_timer_t * handle ) 412{ 413uv_timer_stop (& main_loop .exit_delay_timer ); 414multiqueue_put (main_loop .fast_events ,exit_event ,main_loop .exit_delay_timer .data ); 415} 416 417static void exit_event (void ** argv ) 418{ 419int status = (int )(intptr_t )argv [0 ]; 420if (exit_need_delay ) { 421main_loop .exit_delay_timer .data = argv [0 ]; 422uv_timer_start (& main_loop .exit_delay_timer ,exit_delay_cb ,0 ,0 ); 423return ; 424 } 425 426if (!exiting ) { 427if (ui_client_channel_id ) { 428ui_client_exit_status = status ; 429os_exit (status ); 430 }else { 431assert (status == 0 );// Called from rpc_close(), which passes 0 as status. 432preserve_exit (NULL ); 433 } 434 } 435} 436 437/// Performs self-exit because the primary RPC channel was closed. 438void exit_on_closed_chan (int status ) 439{ 440DLOG ("self-exit triggered by closed RPC channel..." ); 441multiqueue_put (main_loop .fast_events ,exit_event , (void * )(intptr_t )status ); 442} 443 444static void on_proc_exit (Proc * proc ) 445{ 446Loop * loop = proc -> loop ; 447ILOG ("child exited: pid=%d status=%d" PRIu64 ,proc -> pid ,proc -> status ); 448 449// Process has terminated, but there could still be data to be read from the 450// OS. We are still in the libuv loop, so we cannot call code that polls for 451// more data directly. Instead delay the reading after the libuv loop by 452// queueing proc_close_handles() as an event. 453MultiQueue * queue = proc -> events ?proc -> events :loop -> events ; 454CREATE_EVENT (queue ,proc_close_handles ,proc ); 455} 456 457static void on_proc_stream_close (Stream * stream ,void * data ) 458{ 459Proc * proc = data ; 460decref (proc ); 461}