robin/laufey

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

zeertzjqrevert: "refactor(process): don't read from PTY master using uv_pipe_t" (#37401)9c15a382de

master
12.7 KiB461 linesraw
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)
43  FUNC_ATTR_NONNULL_ALL
44{
45  // forwarding stderr contradicts with processing it internally
46  assert(!(err && proc->fwd_err));
47
48  if (in) {
49    uv_pipe_init(&proc->loop->uv, &proc->in.uv.pipe, 0);
50  } else {
51    proc->in.closed = true;
52  }
53
54  if (out) {
55    uv_pipe_init(&proc->loop->uv, &proc->out.s.uv.pipe, 0);
56  } else {
57    proc->out.s.closed = true;
58  }
59
60  if (err) {
61    uv_pipe_init(&proc->loop->uv, &proc->err.s.uv.pipe, 0);
62  } else {
63    proc->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
71  int status;
72  switch (proc->type) {
73  case kProcTypeUv:
74    status = libuv_proc_spawn((LibuvProc *)proc);
75    break;
76  case kProcTypePty:
77    status = pty_proc_spawn((PtyProc *)proc);
78    break;
79  }
80
81  if (status) {
82    if (in) {
83      uv_close((uv_handle_t *)&proc->in.uv.pipe, NULL);
84    }
85    if (out) {
86      uv_close((uv_handle_t *)&proc->out.s.uv.pipe, NULL);
87    }
88    if (err) {
89      uv_close((uv_handle_t *)&proc->err.s.uv.pipe, NULL);
90    }
91
92    if (proc->type == kProcTypeUv) {
93      uv_close((uv_handle_t *)&(((LibuvProc *)proc)->uv), NULL);
94    } else {
95      proc_close(proc);
96    }
97    proc_free(proc);
98    proc->status = -1;
99    return status;
100  }
101
102  if (in) {
103    stream_init(NULL, &proc->in, -1, (uv_stream_t *)&proc->in.uv.pipe);
104    proc->in.internal_data = proc;
105    proc->in.internal_close_cb = on_proc_stream_close;
106    proc->refcount++;
107  }
108
109  if (out) {
110    stream_init(NULL, &proc->out.s, -1, (uv_stream_t *)&proc->out.s.uv.pipe);
111    proc->out.s.internal_data = proc;
112    proc->out.s.internal_close_cb = on_proc_stream_close;
113    proc->refcount++;
114  }
115
116  if (err) {
117    stream_init(NULL, &proc->err.s, -1, (uv_stream_t *)&proc->err.s.uv.pipe);
118    proc->err.s.internal_data = proc;
119    proc->err.s.internal_close_cb = on_proc_stream_close;
120    proc->refcount++;
121  }
122
123  proc->internal_exit_cb = on_proc_exit;
124  proc->internal_close_cb = decref;
125  proc->refcount++;
126  kv_push(proc->loop->children, proc);
127  DLOG("new: pid=%d exepath=[%s]", proc->pid, proc_get_exepath(proc));
128  return 0;
129}
130
131void proc_teardown(Loop *loop) FUNC_ATTR_NONNULL_ALL
132{
133  proc_is_tearing_down = true;
134  for (size_t i = 0; i < kv_size(loop->children); i++) {
135    Proc *proc = kv_A(loop->children, i);
136    if (proc->detach || proc->type == kProcTypePty) {
137      // Close handles to process without killing it.
138      CREATE_EVENT(loop->events, proc_close_handles, proc);
139    } else {
140      proc_stop(proc);
141    }
142  }
143
144  // Wait until all children exit and all close events are processed.
145  LOOP_PROCESS_EVENTS_UNTIL(loop, loop->events, -1,
146                            kv_size(loop->children) == 0 && multiqueue_empty(loop->events));
147  pty_proc_teardown(loop);
148}
149
150void proc_close_streams(Proc *proc) FUNC_ATTR_NONNULL_ALL
151{
152  stream_may_close(&proc->in);
153  rstream_may_close(&proc->out);
154  rstream_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)
166  FUNC_ATTR_NONNULL_ARG(1)
167{
168  if (!proc->refcount) {
169    int status = proc->status;
170    LOOP_PROCESS_EVENTS(proc->loop, proc->events, 0);
171    return status;
172  }
173
174  if (!events) {
175    events = 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.
180  proc->refcount++;
181  LOOP_PROCESS_EVENTS_UNTIL(proc->loop, events, ms,
182                            // Until...
183                            got_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.
187  if (got_int) {
188    got_int = false;
189    proc_stop(proc);
190    if (ms == -1) {
191      // We can only return if all streams/handles are closed and the job
192      // exited.
193      LOOP_PROCESS_EVENTS_UNTIL(proc->loop, events, -1,
194                                proc->refcount == 1);
195    } else {
196      LOOP_PROCESS_EVENTS(proc->loop, events, 0);
197    }
198
199    proc->status = -2;
200  }
201
202  if (proc->refcount == 1) {
203    // Job exited, free its resources.
204    decref(proc);
205    if (proc->events) {
206      // decref() created an exit event, process it now.
207      multiqueue_process_events(proc->events);
208    }
209  } else {
210    proc->refcount--;
211  }
212
213  return 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{
219  bool exited = (proc->status >= 0);
220  if (exited || proc->stopped_time) {
221    return;
222  }
223  proc->stopped_time = os_hrtime();
224
225  switch (proc->type) {
226  case kProcTypeUv:
227    proc->exit_signal = SIGTERM;
228    os_proc_tree_kill(proc->pid, SIGTERM);
229    break;
230  case kProcTypePty:
231    // close all streams for pty processes to send SIGHUP to the process
232    proc->exit_signal = SIGHUP;
233    proc_close_streams(proc);
234    pty_proc_close_master((PtyProc *)proc);
235    break;
236  }
237
238  // (Re)start timer to verify that stopped process(es) died.
239  uv_timer_start(&proc->loop->children_kill_timer, children_kill_cb,
240                 KILL_TIMEOUT_MS, 0);
241}
242
243/// Frees process-owned resources.
244void proc_free(Proc *proc) FUNC_ATTR_NONNULL_ALL
245{
246  if (proc->argv != NULL) {
247    shell_free_argv(proc->argv);
248    proc->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{
256  Loop *loop = handle->loop->data;
257
258  for (size_t i = 0; i < kv_size(loop->children); i++) {
259    Proc *proc = kv_A(loop->children, i);
260    bool exited = (proc->status >= 0);
261    if (exited || !proc->stopped_time) {
262      continue;
263    }
264    uint64_t term_sent = UINT64_MAX == proc->stopped_time;
265    if (kProcTypePty != proc->type || term_sent) {
266      proc->exit_signal = SIGKILL;
267      os_proc_tree_kill(proc->pid, SIGKILL);
268    } else {
269      proc->exit_signal = SIGTERM;
270      os_proc_tree_kill(proc->pid, SIGTERM);
271      proc->stopped_time = UINT64_MAX;  // Flag: SIGTERM was sent.
272      // Restart timer.
273      uv_timer_start(&proc->loop->children_kill_timer, children_kill_cb,
274                     KILL_TIMEOUT_MS, 0);
275    }
276  }
277}
278
279static void proc_close_event(void **argv)
280{
281  Proc *proc = argv[0];
282  if (proc->cb) {
283    // User (hint: channel_job_start) is responsible for calling
284    // proc_free().
285    proc->cb(proc, proc->status, proc->data);
286  } else {
287    proc_free(proc);
288  }
289}
290
291static void decref(Proc *proc)
292{
293  if (--proc->refcount != 0) {
294    return;
295  }
296
297  Loop *loop = proc->loop;
298  size_t i;
299  for (i = 0; i < kv_size(loop->children); i++) {
300    Proc *current = kv_A(loop->children, i);
301    if (current == proc) {
302      break;
303    }
304  }
305  assert(i < kv_size(loop->children));  // element found
306  if (i < kv_size(loop->children) - 1) {
307    memmove(&kv_A(loop->children, i), &kv_A(loop->children, i + 1),
308            sizeof(&kv_A(loop->children, i)) * (kv_size(loop->children) - (i + 1)));
309  }
310  kv_size(loop->children)--;
311  CREATE_EVENT(proc->events, proc_close_event, proc);
312}
313
314static void proc_close(Proc *proc)
315  FUNC_ATTR_NONNULL_ARG(1)
316{
317  if (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.
319    return;
320  }
321  assert(!proc->closed);
322  proc->closed = true;
323
324  if (proc->detach) {
325    if (proc->type == kProcTypeUv) {
326      uv_unref((uv_handle_t *)&(((LibuvProc *)proc)->uv));
327    }
328  }
329
330  switch (proc->type) {
331  case kProcTypeUv:
332    libuv_proc_close((LibuvProc *)proc);
333    break;
334  case kProcTypePty:
335    pty_proc_close((PtyProc *)proc);
336    break;
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)
345  FUNC_ATTR_NONNULL_ARG(1)
346{
347  if (!stream || stream->s.closed) {
348    return;
349  }
350
351  size_t max_bytes = SIZE_MAX;
352#ifdef MSWIN
353  if (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
357  if (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.
363    int system_buffer_size = 0;
364    // All members of the stream->s.uv union share the same address.
365    int err = uv_recv_buffer_size((uv_handle_t *)&stream->s.uv, &system_buffer_size);
366    if (err != 0) {
367      system_buffer_size = ARENA_BLOCK_SIZE;
368    }
369    max_bytes = stream->num_bytes + (size_t)system_buffer_size;
370  }
371
372  // Read remaining data.
373  while (!stream->s.closed && stream->num_bytes < max_bytes) {
374    // Remember number of bytes before polling.
375    size_t num_bytes = stream->num_bytes;
376
377    if (proc->type == kProcTypePty && !stream->did_eof) {
378      pty_proc_flush_master((PtyProc *)proc);
379    }
380    // Poll for data and process the generated events.
381    loop_poll_events(proc->loop, 0);
382    if (stream->s.events) {
383      multiqueue_process_events(stream->s.events);
384    }
385
386    // Stream can be closed if it is empty.
387    if (num_bytes == stream->num_bytes) {
388      if (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.
391        stream->read_cb(stream, stream->buffer, 0, stream->s.cb_data, true);
392      }
393      break;
394    }
395  }
396}
397
398static void proc_close_handles(void **argv)
399{
400  Proc *proc = argv[0];
401
402  exit_need_delay++;
403  flush_stream(proc, &proc->out);
404  flush_stream(proc, &proc->err);
405
406  proc_close_streams(proc);
407  proc_close(proc);
408  exit_need_delay--;
409}
410
411static void exit_delay_cb(uv_timer_t *handle)
412{
413  uv_timer_stop(&main_loop.exit_delay_timer);
414  multiqueue_put(main_loop.fast_events, exit_event, main_loop.exit_delay_timer.data);
415}
416
417static void exit_event(void **argv)
418{
419  int status = (int)(intptr_t)argv[0];
420  if (exit_need_delay) {
421    main_loop.exit_delay_timer.data = argv[0];
422    uv_timer_start(&main_loop.exit_delay_timer, exit_delay_cb, 0, 0);
423    return;
424  }
425
426  if (!exiting) {
427    if (ui_client_channel_id) {
428      ui_client_exit_status = status;
429      os_exit(status);
430    } else {
431      assert(status == 0);  // Called from rpc_close(), which passes 0 as status.
432      preserve_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{
440  DLOG("self-exit triggered by closed RPC channel...");
441  multiqueue_put(main_loop.fast_events, exit_event, (void *)(intptr_t)status);
442}
443
444static void on_proc_exit(Proc *proc)
445{
446  Loop *loop = proc->loop;
447  ILOG("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.
453  MultiQueue *queue = proc->events ? proc->events : loop->events;
454  CREATE_EVENT(queue, proc_close_handles, proc);
455}
456
457static void on_proc_stream_close(Stream *stream, void *data)
458{
459  Proc *proc = data;
460  decref(proc);
461}