robin/laufey

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

taorefactor(path): more slash normalization #39426040bdf0bc5

master
12.4 KiB470 linesraw
1#include <assert.h>
2#include <stdbool.h>
3#include <stdlib.h>
4
5#include "nvim/ascii_defs.h"
6#include "nvim/eval/typval.h"
7#include "nvim/event/loop.h"
8#include "nvim/log.h"
9#include "nvim/mbyte.h"
10#include "nvim/memory.h"
11#include "nvim/os/fs.h"
12#include "nvim/os/os.h"
13#include "nvim/os/pty_conpty_win.h"
14#include "nvim/os/pty_proc_win.h"
15#include "nvim/path.h"
16
17#include "os/pty_proc_win.c.generated.h"
18
19static void CALLBACK pty_proc_terminate_cb(void *context, BOOLEAN unused)
20  FUNC_ATTR_NONNULL_ALL
21{
22  Proc *proc = (Proc *)context;
23  // NB: pty_proc_terminate_cb() is called on a separate thread,
24  // but finishing up the process needs to be done on the main thread.
25  loop_schedule_fast(proc->loop, event_create(pty_proc_finish, context));
26}
27
28/// Create a separate thread to call ClosePseudoConsole,
29/// which allows us to flush the final frame on the main thread.
30/// See https://learn.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session#ending-the-pseudoconsole-session
31static void pty_proc_close_console(Stream *stream, void *data)
32{
33  PtyProc *ptyproc = stream->internal_data;
34  Proc *proc = (Proc *)ptyproc;
35  if (ptyproc->conpty == NULL) {
36    return;
37  }
38  // On Windows 11, closing a terminal immediately after opening it can leave orphan conhost
39  // and shell processes, e.g. `during TermClose event` case in autocmd_spec.lua
40  // Checking `num_bytes` is an attempt to detect that, until we find a better way.
41  if (proc->out.num_bytes == 0) {
42    TerminateProcess(ptyproc->proc_handle, 0);
43  }
44  uv_thread_t tid;
45  uv_thread_create(&tid, os_conpty_free, ptyproc->conpty);
46  while (!proc->out.did_eof && WaitForSingleObject(tid, 0) == WAIT_TIMEOUT) {
47    uv_run(&proc->loop->uv, UV_RUN_ONCE);
48  }
49  uv_thread_detach(&tid);
50  ptyproc->conpty = NULL;
51}
52
53/// @returns zero on success, or negative error code.
54int pty_proc_spawn(PtyProc *ptyproc)
55  FUNC_ATTR_NONNULL_ALL
56{
57  Proc *proc = (Proc *)ptyproc;
58  int status = 0;
59  conpty_t *conpty_object = NULL;
60  char *in_name = NULL;
61  char *out_name = NULL;
62  HANDLE proc_handle = NULL;
63  uv_connect_t *in_req = NULL;
64  uv_connect_t *out_req = NULL;
65  wchar_t *file = NULL;
66  wchar_t *cmd_line = NULL;
67  wchar_t *cwd = NULL;
68  wchar_t *env = NULL;
69  const char *emsg = NULL;
70
71  assert(proc->err.s.closed);
72
73  if (!os_has_conpty_working() || (conpty_object = os_conpty_init(&in_name,
74                                                                  &out_name, ptyproc->width,
75                                                                  ptyproc->height)) == NULL) {
76    status = UV_ENOSYS;
77    goto cleanup;
78  }
79
80  if (!proc->in.closed) {
81    in_req = xmalloc(sizeof(uv_connect_t));
82    uv_pipe_connect(in_req,
83                    &proc->in.uv.pipe,
84                    in_name,
85                    pty_proc_connect_cb);
86  }
87
88  if (!proc->out.s.closed) {
89    out_req = xmalloc(sizeof(uv_connect_t));
90    uv_pipe_connect(out_req,
91                    &proc->out.s.uv.pipe,
92                    out_name,
93                    pty_proc_connect_cb);
94  }
95
96  if (proc->cwd != NULL) {
97    status = utf8_to_utf16(proc->cwd, -1, &cwd);
98    if (status != 0) {
99      emsg = "utf8_to_utf16(proc->cwd) failed";
100      goto cleanup;
101    }
102  }
103
104  // cmd.exe can’t recognize forward slash in argv[0] during
105  // initialization, so we keep only cmd.exe in the cmd_line
106  // and pass fullpath via lpApplicationName to avoid hijacking.
107  // See https://www.microsoft.com/en-us/msrc/blog/2014/04/ms14-019-fixing-a-binary-hijacking-via-cmd-or-bat-file
108  bool is_cmdexe = os_shell_is_cmdexe(proc->argv[0]);
109  if (is_cmdexe) {
110    char *path = NULL;
111    // TODO(ntdiary): Could put the search logic in one place.
112    // See https://github.com/neovim/neovim/issues/36818#issuecomment-3977147445
113    if (!os_can_exe(proc->argv[0], &path, true)) {
114      status = UV_ENOENT;
115      emsg = "executable not found";
116      goto cleanup;
117    }
118    status = utf8_to_utf16(path, -1, &file);
119    if (status != 0) {
120      emsg = "utf8_to_utf16(proc->argv[0]) failed";
121      goto cleanup;
122    }
123    xfree(path);
124  }
125  status = build_cmd_line(proc->argv, &cmd_line, is_cmdexe);
126  if (status != 0) {
127    emsg = "build_cmd_line failed";
128    goto cleanup;
129  }
130
131  if (proc->env != NULL) {
132    status = build_env_block(proc->env, &env);
133  }
134
135  if (status != 0) {
136    emsg = "build_env_block failed";
137    goto cleanup;
138  }
139
140  if (!os_conpty_spawn(conpty_object,
141                       &proc_handle,
142                       file,
143                       cmd_line,
144                       cwd,
145                       env)) {
146    emsg = "os_conpty_spawn failed";
147    status = (int)GetLastError();
148    goto cleanup;
149  }
150  proc->pid = (int)GetProcessId(proc_handle);
151
152  if (!RegisterWaitForSingleObject(&ptyproc->finish_wait,
153                                   proc_handle,
154                                   pty_proc_terminate_cb,
155                                   ptyproc,
156                                   INFINITE,
157                                   WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE)) {
158    abort();
159  }
160
161  // Wait until pty_proc_connect_cb is called.
162  while ((in_req != NULL && in_req->handle != NULL)
163         || (out_req != NULL && out_req->handle != NULL)) {
164    uv_run(&proc->loop->uv, UV_RUN_ONCE);
165  }
166
167  proc->out.s.before_close_cb = pty_proc_close_console;
168  ptyproc->conpty = conpty_object;
169  ptyproc->proc_handle = proc_handle;
170  conpty_object = NULL;
171  proc_handle = NULL;
172
173cleanup:
174  if (status) {
175    // In the case of an error of MultiByteToWideChar or CreateProcessW.
176    ELOG("pty_proc_spawn(%s): %s: error code: %d",
177         proc->argv[0], emsg, status);
178    status = os_translate_sys_error(status);
179  }
180  os_conpty_free(conpty_object);
181  xfree(in_name);
182  xfree(out_name);
183  if (proc_handle != NULL) {
184    CloseHandle(proc_handle);
185  }
186  xfree(in_req);
187  xfree(out_req);
188  xfree(file);
189  xfree(cmd_line);
190  xfree(env);
191  xfree(cwd);
192  return status;
193}
194
195const char *pty_proc_tty_name(PtyProc *ptyproc)
196{
197  return "?";
198}
199
200void pty_proc_resize(PtyProc *ptyproc, uint16_t width, uint16_t height)
201  FUNC_ATTR_NONNULL_ALL
202{
203  os_conpty_set_size(ptyproc->conpty, width, height);
204}
205
206void pty_proc_resume(PtyProc *ptyproc)
207  FUNC_ATTR_NONNULL_ALL
208{
209}
210
211void pty_proc_flush_master(PtyProc *ptyproc)
212  FUNC_ATTR_NONNULL_ALL
213{
214}
215
216void pty_proc_close(PtyProc *ptyproc)
217  FUNC_ATTR_NONNULL_ALL
218{
219  Proc *proc = (Proc *)ptyproc;
220
221  pty_proc_close_master(ptyproc);
222
223  if (ptyproc->finish_wait != NULL) {
224    UnregisterWaitEx(ptyproc->finish_wait, NULL);
225    ptyproc->finish_wait = NULL;
226  }
227  if (ptyproc->proc_handle != NULL) {
228    CloseHandle(ptyproc->proc_handle);
229    ptyproc->proc_handle = NULL;
230  }
231
232  if (proc->internal_close_cb) {
233    proc->internal_close_cb(proc);
234  }
235}
236
237void pty_proc_close_master(PtyProc *ptyproc)
238  FUNC_ATTR_NONNULL_ALL
239{
240}
241
242void pty_proc_teardown(Loop *loop)
243  FUNC_ATTR_NONNULL_ALL
244{
245}
246
247static void pty_proc_connect_cb(uv_connect_t *req, int status)
248  FUNC_ATTR_NONNULL_ALL
249{
250  assert(status == 0);
251  req->handle = NULL;
252}
253
254static void pty_proc_finish(void **argv)
255  FUNC_ATTR_NONNULL_ALL
256{
257  PtyProc *ptyproc = (PtyProc *)argv[0];
258  Proc *proc = (Proc *)ptyproc;
259
260  DWORD exit_code = 0;
261  GetExitCodeProcess(ptyproc->proc_handle, &exit_code);
262  proc->status = proc->exit_signal ? 128 + proc->exit_signal : (int)exit_code;
263
264  proc->internal_exit_cb(proc);
265}
266
267/// Build the command line to pass to CreateProcessW.
268///
269/// @param[in]  argv  Array with string arguments.
270/// @param[out]  cmd_line  Location where saved built cmd line.
271///
272/// @returns zero on success, or error code of MultiByteToWideChar function.
273///
274static int build_cmd_line(char **argv, wchar_t **cmd_line, bool is_cmdexe)
275  FUNC_ATTR_NONNULL_ALL
276{
277  size_t utf8_cmd_line_len = 0;
278  size_t argc = 0;
279  QUEUE args_q;
280
281  QUEUE_INIT(&args_q);
282  while (*argv) {
283    size_t buf_len = is_cmdexe ? (strlen(*argv) + 1) : (strlen(*argv) * 2 + 3);
284    ArgNode *arg_node = xmalloc(sizeof(*arg_node));
285    arg_node->arg = xmalloc(buf_len);
286    if (is_cmdexe) {
287      xstrlcpy(arg_node->arg, argc == 0 ? "cmd.exe" : *argv, buf_len);
288    } else {
289      quote_cmd_arg(arg_node->arg, buf_len, *argv);
290    }
291    utf8_cmd_line_len += strlen(arg_node->arg);
292    QUEUE_INIT(&arg_node->node);
293    QUEUE_INSERT_TAIL(&args_q, &arg_node->node);
294    argc++;
295    argv++;
296  }
297
298  utf8_cmd_line_len += argc;
299  char *utf8_cmd_line = xmalloc(utf8_cmd_line_len);
300  *utf8_cmd_line = NUL;
301  QUEUE *q;
302  QUEUE_FOREACH(q, &args_q, {
303    ArgNode *arg_node = QUEUE_DATA(q, ArgNode, node);
304    xstrlcat(utf8_cmd_line, arg_node->arg, utf8_cmd_line_len);
305    QUEUE_REMOVE(q);
306    xfree(arg_node->arg);
307    xfree(arg_node);
308    if (!QUEUE_EMPTY(&args_q)) {
309      xstrlcat(utf8_cmd_line, " ", utf8_cmd_line_len);
310    }
311  })
312
313  int result = utf8_to_utf16(utf8_cmd_line, -1, cmd_line);
314  xfree(utf8_cmd_line);
315  return result;
316}
317
318/// Emulate quote_cmd_arg of libuv and quotes command line argument.
319/// Most of the code came from libuv.
320///
321/// @param[out]  dest  Location where saved quotes argument.
322/// @param  dest_remaining  Destination buffer size.
323/// @param[in]  src Pointer to argument.
324///
325static void quote_cmd_arg(char *dest, size_t dest_remaining, const char *src)
326  FUNC_ATTR_NONNULL_ALL
327{
328  size_t src_len = strlen(src);
329  bool quote_hit = true;
330  char *start = dest;
331
332  if (src_len == 0) {
333    // Need double quotation for empty argument.
334    snprintf(dest, dest_remaining, "\"\"");
335    return;
336  }
337
338  if (NULL == strpbrk(src, " \t\"")) {
339    // No quotation needed.
340    xstrlcpy(dest, src, dest_remaining);
341    return;
342  }
343
344  if (NULL == strpbrk(src, "\"\\")) {
345    // No embedded double quotes or backlashes, so I can just wrap quote marks.
346    // around the whole thing.
347    snprintf(dest, dest_remaining, "\"%s\"", src);
348    return;
349  }
350
351  // Expected input/output:
352  //   input : 'hello"world'
353  //   output: '"hello\"world"'
354  //   input : 'hello""world'
355  //   output: '"hello\"\"world"'
356  //   input : 'hello\world'
357  //   output: 'hello\world'
358  //   input : 'hello\\world'
359  //   output: 'hello\\world'
360  //   input : 'hello\"world'
361  //   output: '"hello\\\"world"'
362  //   input : 'hello\\"world'
363  //   output: '"hello\\\\\"world"'
364  //   input : 'hello world\'
365  //   output: '"hello world\\"'
366
367  assert(dest_remaining--);
368  *(dest++) = NUL;
369  assert(dest_remaining--);
370  *(dest++) = '"';
371  for (size_t i = src_len; i > 0; i--) {
372    assert(dest_remaining--);
373    *(dest++) = src[i - 1];
374    if (quote_hit && src[i - 1] == '\\') {
375      assert(dest_remaining--);
376      *(dest++) = '\\';
377    } else if (src[i - 1] == '"') {
378      quote_hit = true;
379      assert(dest_remaining--);
380      *(dest++) = '\\';
381    } else {
382      quote_hit = false;
383    }
384  }
385  assert(dest_remaining);
386  *dest = '"';
387
388  while (start < dest) {
389    char tmp = *start;
390    *start = *dest;
391    *dest = tmp;
392    start++;
393    dest--;
394  }
395}
396
397typedef struct EnvNode {
398  wchar_t *str;
399  size_t len;
400  QUEUE node;
401} EnvNode;
402
403/// Build the environment block to pass to CreateProcessW.
404///
405/// @param[in]  denv  Dict of environment name/value pairs
406/// @param[out]  env  Allocated environment block
407///
408/// @returns zero on success or error code of MultiByteToWideChar function.
409static int build_env_block(dict_T *denv, wchar_t **env_block)
410{
411  const size_t denv_size = (size_t)tv_dict_len(denv);
412  size_t env_block_len = 0;
413  int rc = 0;
414  char **env = tv_dict_to_env(denv);
415
416  QUEUE *q;
417  QUEUE env_q;
418  QUEUE_INIT(&env_q);
419  // Convert env vars to wchar_t and calculate how big the final env block
420  // needs to be
421  for (size_t i = 0; i < denv_size; i++) {
422    EnvNode *env_node = xmalloc(sizeof(*env_node));
423    rc = utf8_to_utf16(env[i], -1, &env_node->str);
424    if (rc != 0) {
425      goto cleanup;
426    }
427    env_node->len = wcslen(env_node->str) + 1;
428    env_block_len += env_node->len;
429    QUEUE_INSERT_TAIL(&env_q, &env_node->node);
430  }
431
432  // Additional NUL after the final entry
433  env_block_len++;
434
435  *env_block = xmalloc(sizeof(**env_block) * env_block_len);
436  wchar_t *pos = *env_block;
437
438  QUEUE_FOREACH(q, &env_q, {
439    EnvNode *env_node = QUEUE_DATA(q, EnvNode, node);
440    memcpy(pos, env_node->str, env_node->len * sizeof(*pos));
441    pos += env_node->len;
442  })
443
444  *pos = L'\0';
445
446cleanup:
447  q = QUEUE_HEAD(&env_q);
448  while (q != &env_q) {
449    QUEUE *next = q->next;
450    EnvNode *env_node = QUEUE_DATA(q, EnvNode, node);
451    XFREE_CLEAR(env_node->str);
452    QUEUE_REMOVE(q);
453    xfree(env_node);
454    q = next;
455  }
456
457  return rc;
458}
459
460PtyProc pty_proc_init(Loop *loop, void *data)
461{
462  PtyProc rv;
463  rv.proc = proc_init(loop, kProcTypePty, data);
464  rv.width = 80;
465  rv.height = 24;
466  rv.conpty = NULL;
467  rv.finish_wait = NULL;
468  rv.proc_handle = NULL;
469  return rv;
470}