robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
040bdf0bc5
master
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 ) 20FUNC_ATTR_NONNULL_ALL 21{ 22Proc * 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. 25loop_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{ 33PtyProc * ptyproc = stream -> internal_data ; 34Proc * proc = (Proc * )ptyproc ; 35if (ptyproc -> conpty == NULL ) { 36return ; 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. 41if (proc -> out .num_bytes == 0 ) { 42TerminateProcess (ptyproc -> proc_handle ,0 ); 43 } 44uv_thread_t tid ; 45uv_thread_create (& tid ,os_conpty_free ,ptyproc -> conpty ); 46while (!proc -> out .did_eof && WaitForSingleObject (tid ,0 )== WAIT_TIMEOUT ) { 47uv_run (& proc -> loop -> uv ,UV_RUN_ONCE ); 48 } 49uv_thread_detach (& tid ); 50ptyproc -> conpty = NULL ; 51} 52 53/// @returns zero on success, or negative error code. 54int pty_proc_spawn (PtyProc * ptyproc ) 55FUNC_ATTR_NONNULL_ALL 56{ 57Proc * proc = (Proc * )ptyproc ; 58int status = 0 ; 59conpty_t * conpty_object = NULL ; 60char * in_name = NULL ; 61char * out_name = NULL ; 62HANDLE proc_handle = NULL ; 63uv_connect_t * in_req = NULL ; 64uv_connect_t * out_req = NULL ; 65wchar_t * file = NULL ; 66wchar_t * cmd_line = NULL ; 67wchar_t * cwd = NULL ; 68wchar_t * env = NULL ; 69const char * emsg = NULL ; 70 71assert (proc -> err .s .closed ); 72 73if (!os_has_conpty_working ()|| (conpty_object = os_conpty_init (& in_name , 74& out_name ,ptyproc -> width , 75ptyproc -> height ))== NULL ) { 76status = UV_ENOSYS ; 77 gotocleanup ; 78 } 79 80if (!proc -> in .closed ) { 81in_req = xmalloc (sizeof (uv_connect_t )); 82uv_pipe_connect (in_req , 83& proc -> in .uv .pipe , 84in_name , 85pty_proc_connect_cb ); 86 } 87 88if (!proc -> out .s .closed ) { 89out_req = xmalloc (sizeof (uv_connect_t )); 90uv_pipe_connect (out_req , 91& proc -> out .s .uv .pipe , 92out_name , 93pty_proc_connect_cb ); 94 } 95 96if (proc -> cwd != NULL ) { 97status = utf8_to_utf16 (proc -> cwd ,-1 ,& cwd ); 98if (status != 0 ) { 99emsg = "utf8_to_utf16(proc->cwd) failed" ; 100 gotocleanup ; 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 108bool is_cmdexe = os_shell_is_cmdexe (proc -> argv [0 ]); 109if (is_cmdexe ) { 110char * path = NULL ; 111// TODO(ntdiary): Could put the search logic in one place. 112// See https://github.com/neovim/neovim/issues/36818#issuecomment-3977147445 113if (!os_can_exe (proc -> argv [0 ],& path , true)) { 114status = UV_ENOENT ; 115emsg = "executable not found" ; 116 gotocleanup ; 117 } 118status = utf8_to_utf16 (path ,-1 ,& file ); 119if (status != 0 ) { 120emsg = "utf8_to_utf16(proc->argv[0]) failed" ; 121 gotocleanup ; 122 } 123xfree (path ); 124 } 125status = build_cmd_line (proc -> argv ,& cmd_line ,is_cmdexe ); 126if (status != 0 ) { 127emsg = "build_cmd_line failed" ; 128 gotocleanup ; 129 } 130 131if (proc -> env != NULL ) { 132status = build_env_block (proc -> env ,& env ); 133 } 134 135if (status != 0 ) { 136emsg = "build_env_block failed" ; 137 gotocleanup ; 138 } 139 140if (!os_conpty_spawn (conpty_object , 141& proc_handle , 142file , 143cmd_line , 144cwd , 145env )) { 146emsg = "os_conpty_spawn failed" ; 147status = (int )GetLastError (); 148 gotocleanup ; 149 } 150proc -> pid = (int )GetProcessId (proc_handle ); 151 152if (!RegisterWaitForSingleObject (& ptyproc -> finish_wait , 153proc_handle , 154pty_proc_terminate_cb , 155ptyproc , 156INFINITE , 157WT_EXECUTEDEFAULT |WT_EXECUTEONLYONCE )) { 158abort (); 159 } 160 161// Wait until pty_proc_connect_cb is called. 162while ((in_req != NULL && in_req -> handle != NULL ) 163|| (out_req != NULL && out_req -> handle != NULL )) { 164uv_run (& proc -> loop -> uv ,UV_RUN_ONCE ); 165 } 166 167proc -> out .s .before_close_cb = pty_proc_close_console ; 168ptyproc -> conpty = conpty_object ; 169ptyproc -> proc_handle = proc_handle ; 170conpty_object = NULL ; 171proc_handle = NULL ; 172 173cleanup : 174if (status ) { 175// In the case of an error of MultiByteToWideChar or CreateProcessW. 176ELOG ("pty_proc_spawn(%s): %s: error code: %d" , 177proc -> argv [0 ],emsg ,status ); 178status = os_translate_sys_error (status ); 179 } 180os_conpty_free (conpty_object ); 181xfree (in_name ); 182xfree (out_name ); 183if (proc_handle != NULL ) { 184CloseHandle (proc_handle ); 185 } 186xfree (in_req ); 187xfree (out_req ); 188xfree (file ); 189xfree (cmd_line ); 190xfree (env ); 191xfree (cwd ); 192return status ; 193} 194 195const char * pty_proc_tty_name (PtyProc * ptyproc ) 196{ 197return "?" ; 198} 199 200void pty_proc_resize (PtyProc * ptyproc ,uint16_t width ,uint16_t height ) 201FUNC_ATTR_NONNULL_ALL 202{ 203os_conpty_set_size (ptyproc -> conpty ,width ,height ); 204} 205 206void pty_proc_resume (PtyProc * ptyproc ) 207FUNC_ATTR_NONNULL_ALL 208{ 209} 210 211void pty_proc_flush_master (PtyProc * ptyproc ) 212FUNC_ATTR_NONNULL_ALL 213{ 214} 215 216void pty_proc_close (PtyProc * ptyproc ) 217FUNC_ATTR_NONNULL_ALL 218{ 219Proc * proc = (Proc * )ptyproc ; 220 221pty_proc_close_master (ptyproc ); 222 223if (ptyproc -> finish_wait != NULL ) { 224UnregisterWaitEx (ptyproc -> finish_wait ,NULL ); 225ptyproc -> finish_wait = NULL ; 226 } 227if (ptyproc -> proc_handle != NULL ) { 228CloseHandle (ptyproc -> proc_handle ); 229ptyproc -> proc_handle = NULL ; 230 } 231 232if (proc -> internal_close_cb ) { 233proc -> internal_close_cb (proc ); 234 } 235} 236 237void pty_proc_close_master (PtyProc * ptyproc ) 238FUNC_ATTR_NONNULL_ALL 239{ 240} 241 242void pty_proc_teardown (Loop * loop ) 243FUNC_ATTR_NONNULL_ALL 244{ 245} 246 247static void pty_proc_connect_cb (uv_connect_t * req ,int status ) 248FUNC_ATTR_NONNULL_ALL 249{ 250assert (status == 0 ); 251req -> handle = NULL ; 252} 253 254static void pty_proc_finish (void ** argv ) 255FUNC_ATTR_NONNULL_ALL 256{ 257PtyProc * ptyproc = (PtyProc * )argv [0 ]; 258Proc * proc = (Proc * )ptyproc ; 259 260DWORD exit_code = 0 ; 261GetExitCodeProcess (ptyproc -> proc_handle ,& exit_code ); 262proc -> status = proc -> exit_signal ?128 + proc -> exit_signal : (int )exit_code ; 263 264proc -> 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 ) 275FUNC_ATTR_NONNULL_ALL 276{ 277size_t utf8_cmd_line_len = 0 ; 278size_t argc = 0 ; 279QUEUE args_q ; 280 281QUEUE_INIT (& args_q ); 282while (* argv ) { 283size_t buf_len = is_cmdexe ? (strlen (* argv )+ 1 ) : (strlen (* argv )* 2 + 3 ); 284ArgNode * arg_node = xmalloc (sizeof (* arg_node )); 285arg_node -> arg = xmalloc (buf_len ); 286if (is_cmdexe ) { 287xstrlcpy (arg_node -> arg ,argc == 0 ?"cmd.exe" :* argv ,buf_len ); 288 }else { 289quote_cmd_arg (arg_node -> arg ,buf_len ,* argv ); 290 } 291utf8_cmd_line_len += strlen (arg_node -> arg ); 292QUEUE_INIT (& arg_node -> node ); 293QUEUE_INSERT_TAIL (& args_q ,& arg_node -> node ); 294argc ++ ; 295argv ++ ; 296 } 297 298utf8_cmd_line_len += argc ; 299char * utf8_cmd_line = xmalloc (utf8_cmd_line_len ); 300* utf8_cmd_line = NUL ; 301QUEUE * q ; 302QUEUE_FOREACH (q ,& args_q , { 303ArgNode * arg_node = QUEUE_DATA (q ,ArgNode ,node ); 304xstrlcat (utf8_cmd_line ,arg_node -> arg ,utf8_cmd_line_len ); 305QUEUE_REMOVE (q ); 306xfree (arg_node -> arg ); 307xfree (arg_node ); 308if (!QUEUE_EMPTY (& args_q )) { 309xstrlcat (utf8_cmd_line ," " ,utf8_cmd_line_len ); 310 } 311 }) 312 313int result = utf8_to_utf16 (utf8_cmd_line ,-1 ,cmd_line ); 314xfree (utf8_cmd_line ); 315return 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 ) 326FUNC_ATTR_NONNULL_ALL 327{ 328size_t src_len = strlen (src ); 329bool quote_hit = true; 330char * start = dest ; 331 332if (src_len == 0 ) { 333// Need double quotation for empty argument. 334snprintf (dest ,dest_remaining ,"\"\"" ); 335return ; 336 } 337 338if (NULL == strpbrk (src ," \t\"" )) { 339// No quotation needed. 340xstrlcpy (dest ,src ,dest_remaining ); 341return ; 342 } 343 344if (NULL == strpbrk (src ,"\"\\" )) { 345// No embedded double quotes or backlashes, so I can just wrap quote marks. 346// around the whole thing. 347snprintf (dest ,dest_remaining ,"\"%s\"" ,src ); 348return ; 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 367assert (dest_remaining -- ); 368* (dest ++ )= NUL ; 369assert (dest_remaining -- ); 370* (dest ++ )= '"' ; 371for (size_t i = src_len ;i > 0 ;i -- ) { 372assert (dest_remaining -- ); 373* (dest ++ )= src [i - 1 ]; 374if (quote_hit && src [i - 1 ]== '\\' ) { 375assert (dest_remaining -- ); 376* (dest ++ )= '\\' ; 377 }else if (src [i - 1 ]== '"' ) { 378quote_hit = true; 379assert (dest_remaining -- ); 380* (dest ++ )= '\\' ; 381 }else { 382quote_hit = false; 383 } 384 } 385assert (dest_remaining ); 386* dest = '"' ; 387 388while (start < dest ) { 389char tmp = * start ; 390* start = * dest ; 391* dest = tmp ; 392start ++ ; 393dest -- ; 394 } 395} 396 397typedef struct EnvNode { 398wchar_t * str ; 399size_t len ; 400QUEUE 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{ 411const size_t denv_size = (size_t )tv_dict_len (denv ); 412size_t env_block_len = 0 ; 413int rc = 0 ; 414char ** env = tv_dict_to_env (denv ); 415 416QUEUE * q ; 417QUEUE env_q ; 418QUEUE_INIT (& env_q ); 419// Convert env vars to wchar_t and calculate how big the final env block 420// needs to be 421for (size_t i = 0 ;i < denv_size ;i ++ ) { 422EnvNode * env_node = xmalloc (sizeof (* env_node )); 423rc = utf8_to_utf16 (env [i ],-1 ,& env_node -> str ); 424if (rc != 0 ) { 425 gotocleanup ; 426 } 427env_node -> len = wcslen (env_node -> str )+ 1 ; 428env_block_len += env_node -> len ; 429QUEUE_INSERT_TAIL (& env_q ,& env_node -> node ); 430 } 431 432// Additional NUL after the final entry 433env_block_len ++ ; 434 435* env_block = xmalloc (sizeof (** env_block )* env_block_len ); 436wchar_t * pos = * env_block ; 437 438QUEUE_FOREACH (q ,& env_q , { 439EnvNode * env_node = QUEUE_DATA (q ,EnvNode ,node ); 440memcpy (pos ,env_node -> str ,env_node -> len * sizeof (* pos )); 441pos += env_node -> len ; 442 }) 443 444* pos = L'\0' ; 445 446cleanup : 447q = QUEUE_HEAD (& env_q ); 448while (q != & env_q ) { 449QUEUE * next = q -> next ; 450EnvNode * env_node = QUEUE_DATA (q ,EnvNode ,node ); 451XFREE_CLEAR (env_node -> str ); 452QUEUE_REMOVE (q ); 453xfree (env_node ); 454q = next ; 455 } 456 457return rc ; 458} 459 460PtyProc pty_proc_init (Loop * loop ,void * data ) 461{ 462PtyProc rv ; 463rv .proc = proc_init (loop ,kProcTypePty ,data ); 464rv .width = 80 ; 465rv .height = 24 ; 466rv .conpty = NULL ; 467rv .finish_wait = NULL ; 468rv .proc_handle = NULL ; 469return rv ; 470}