robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
4b8c4dfc68
master
1#include <assert.h> 2#include <fcntl.h> 3#include <inttypes.h> 4#include <lauxlib.h> 5#include <stddef.h> 6#include <stdio.h> 7#include <string.h> 8 9#include "klib/kvec.h" 10#include "nvim/api/private/converter.h" 11#include "nvim/api/private/defs.h" 12#include "nvim/api/private/helpers.h" 13#include "nvim/autocmd.h" 14#include "nvim/autocmd_defs.h" 15#include "nvim/buffer_defs.h" 16#include "nvim/channel.h" 17#include "nvim/errors.h" 18#include "nvim/eval.h" 19#include "nvim/eval/encode.h" 20#include "nvim/eval/typval.h" 21#include "nvim/event/loop.h" 22#include "nvim/event/multiqueue.h" 23#include "nvim/event/proc.h" 24#include "nvim/event/rstream.h" 25#include "nvim/event/socket.h" 26#include "nvim/event/stream.h" 27#include "nvim/event/wstream.h" 28#include "nvim/garray.h" 29#include "nvim/gettext_defs.h" 30#include "nvim/globals.h" 31#include "nvim/log.h" 32#include "nvim/lua/executor.h" 33#include "nvim/main.h" 34#include "nvim/mbyte.h" 35#include "nvim/memory.h" 36#include "nvim/memory_defs.h" 37#include "nvim/message.h" 38#include "nvim/msgpack_rpc/channel.h" 39#include "nvim/msgpack_rpc/server.h" 40#include "nvim/os/fs.h" 41#include "nvim/os/os.h" 42#include "nvim/os/os_defs.h" 43#include "nvim/os/shell.h" 44#include "nvim/terminal.h" 45#include "nvim/types_defs.h" 46#include "nvim/ui_client.h" 47 48#ifdef MSWIN 49# include "nvim/os/fs.h" 50# include "nvim/os/os_win_console.h" 51# include "nvim/os/pty_conpty_win.h" 52#endif 53 54static bool did_stdio = false; 55 56/// next free id for a job or rpc channel 57/// 1 is reserved for stdio channel 58/// 2 is reserved for stderr channel 59static uint64_t next_chan_id = CHAN_STDERR + 1 ; 60 61#include "channel.c.generated.h" 62 63/// Teardown the module 64void channel_teardown (void ) 65{ 66Channel * chan ; 67map_foreach_value (& channels ,chan , { 68channel_close (chan -> id ,kChannelPartAll ,NULL ); 69 }); 70} 71 72#ifdef EXITFREE 73void channel_free_all_mem (void ) 74{ 75Channel * chan ; 76map_foreach_value (& channels ,chan , { 77channel_destroy (chan ); 78 }); 79map_destroy (uint64_t ,& channels ); 80 81callback_free (& on_print ); 82} 83#endif 84 85/// Closes a channel 86/// 87/// @param id The channel id 88/// @return true if successful, false otherwise 89bool channel_close (uint64_t id ,ChannelPart part ,const char ** error ) 90{ 91Channel * chan ; 92Proc * proc ; 93 94const char * dummy ; 95if (!error ) { 96error = & dummy ; 97 } 98 99if (!(chan = find_channel (id ))) { 100if (id < next_chan_id ) { 101// allow double close, even though we can't say what parts was valid. 102return true; 103 } 104* error = e_invchan ; 105return false; 106 } 107 108bool close_main = false; 109if (part == kChannelPartRpc || part == kChannelPartAll ) { 110close_main = true; 111if (chan -> is_rpc ) { 112rpc_close (chan ); 113 }else if (part == kChannelPartRpc ) { 114* error = e_invstream ; 115return false; 116 } 117 }else if ((part == kChannelPartStdin || part == kChannelPartStdout ) 118&& chan -> is_rpc ) { 119* error = e_invstreamrpc ; 120return false; 121 } 122 123switch (chan -> streamtype ) { 124case kChannelStreamSocket : 125if (!close_main ) { 126* error = e_invstream ; 127return false; 128 } 129rstream_may_close (& chan -> stream .socket ); 130break ; 131 132case kChannelStreamProc : 133proc = & chan -> stream .proc ; 134if (part == kChannelPartStdin || close_main ) { 135stream_may_close (& proc -> in ); 136 } 137if (part == kChannelPartStdout || close_main ) { 138rstream_may_close (& proc -> out ); 139 } 140if (part == kChannelPartStderr || part == kChannelPartAll ) { 141rstream_may_close (& proc -> err ); 142 } 143if (proc -> type == kProcTypePty && part == kChannelPartAll ) { 144pty_proc_close_master (& chan -> stream .pty ); 145 } 146 147break ; 148 149case kChannelStreamStdio : 150if (part == kChannelPartStdin || close_main ) { 151rstream_may_close (& chan -> stream .stdio .in ); 152 } 153if (part == kChannelPartStdout || close_main ) { 154stream_may_close (& chan -> stream .stdio .out ); 155 } 156if (part == kChannelPartStderr ) { 157* error = e_invstream ; 158return false; 159 } 160break ; 161 162case kChannelStreamStderr : 163if (part != kChannelPartAll && part != kChannelPartStderr ) { 164* error = e_invstream ; 165return false; 166 } 167if (!chan -> stream .err .closed ) { 168chan -> stream .err .closed = true; 169// Don't close on exit, in case late error messages 170if (!exiting ) { 171// Don't close the file descriptor, as that may cause later writes to stderr 172// to go to an unrelated file. Redirect it to NUL or /dev/null instead. 173#ifdef MSWIN 174freopen ("NUL:" ,"w" ,stderr ); 175#else 176freopen ("/dev/null" ,"w" ,stderr ); 177#endif 178 } 179channel_decref (chan ); 180 } 181break ; 182 183case kChannelStreamInternal : 184if (!close_main ) { 185* error = e_invstream ; 186return false; 187 } 188if (chan -> term ) { 189api_free_luaref (chan -> stream .internal .cb ); 190chan -> stream .internal .cb = LUA_NOREF ; 191chan -> stream .internal .closed = true; 192terminal_close (& chan -> term ,0 ); 193chan -> exit_status = 0 ; 194 }else { 195channel_decref (chan ); 196 } 197break ; 198 } 199 200return true; 201} 202 203/// Initializes the module 204void channel_init (void ) 205{ 206channel_alloc (kChannelStreamStderr ); 207rpc_init (); 208} 209 210/// Allocates a channel. 211/// 212/// Channel is allocated with refcount 1, which should be decreased 213/// when the underlying stream closes. 214Channel * channel_alloc (ChannelStreamType type ) 215FUNC_ATTR_NONNULL_RET 216{ 217Channel * chan = xcalloc (1 ,sizeof (* chan )); 218if (type == kChannelStreamStdio ) { 219chan -> id = CHAN_STDIO ; 220 }else if (type == kChannelStreamStderr ) { 221chan -> id = CHAN_STDERR ; 222 }else { 223chan -> id = next_chan_id ++ ; 224 } 225chan -> events = multiqueue_new_child (main_loop .events ); 226chan -> refcount = 1 ; 227chan -> exit_status = -1 ; 228chan -> streamtype = type ; 229chan -> detach = false; 230assert (chan -> id <=VARNUMBER_MAX ); 231pmap_put (uint64_t )(& channels ,chan -> id ,chan ); 232return chan ; 233} 234 235void channel_create_event (Channel * chan ,const char * ext_source ) 236{ 237#ifdef NVIM_LOG_DEBUG 238const char * source ; 239 240if (ext_source ) { 241// TODO(bfredl): in a future improved traceback solution, 242// external events should be included. 243source = ext_source ; 244 }else { 245eval_fmt_source_name_line (IObuff ,sizeof (IObuff )); 246source = IObuff ; 247 } 248 249assert (chan -> id <=VARNUMBER_MAX ); 250Arena arena = ARENA_EMPTY ; 251Dict info = channel_info (chan -> id ,& arena ); 252typval_T tv = TV_INITIAL_VALUE ; 253// TODO(bfredl): do the conversion in one step. Also would be nice 254// to pretty print top level dict in defined order 255object_to_vim (DICT_OBJ (info ),& tv ,NULL ); 256assert (tv .v_type == VAR_DICT ); 257char * str = encode_tv2json (& tv ,NULL ); 258ILOG ("new channel %" PRIu64 " (%s) : %s" ,chan -> id ,source ,str ); 259xfree (str ); 260arena_mem_free (arena_finish (& arena )); 261 262#else 263 (void )ext_source ; 264#endif 265 266channel_event (chan ,EVENT_CHANOPEN ); 267} 268 269void channel_incref (Channel * chan ) 270{ 271chan -> refcount ++ ; 272} 273 274void channel_decref (Channel * chan ) 275{ 276if (chan -> refcount == 1 && !chan -> did_close_event ) { 277chan -> did_close_event = true; 278channel_event (chan ,EVENT_CHANCLOSE ); 279 } 280 281if (!(-- chan -> refcount )) { 282// delay free, so that libuv is done with the handles 283multiqueue_put (main_loop .events ,free_channel_event ,chan ); 284 } 285} 286 287void callback_reader_free (CallbackReader * reader ) 288{ 289callback_free (& reader -> cb ); 290ga_clear (& reader -> buffer ); 291} 292 293void callback_reader_start (CallbackReader * reader ,const char * type ) 294{ 295ga_init (& reader -> buffer ,sizeof (char * ),32 ); 296reader -> type = type ; 297} 298 299static void channel_destroy (Channel * chan ) 300{ 301if (chan -> is_rpc ) { 302rpc_free (chan ); 303 } 304 305if (chan -> streamtype == kChannelStreamProc ) { 306proc_free (& chan -> stream .proc ); 307 } 308 309callback_reader_free (& chan -> on_data ); 310callback_reader_free (& chan -> on_stderr ); 311callback_free (& chan -> on_exit ); 312 313multiqueue_free (chan -> events ); 314xfree (chan ); 315} 316 317static void free_channel_event (void ** argv ) 318{ 319Channel * chan = argv [0 ]; 320pmap_del (uint64_t )(& channels ,chan -> id ,NULL ); 321channel_destroy (chan ); 322} 323 324static void channel_destroy_early (Channel * chan ) 325{ 326if ((chan -> id != -- next_chan_id )) { 327abort (); 328 } 329pmap_del (uint64_t )(& channels ,chan -> id ,NULL ); 330chan -> id = 0 ; 331 332if ((-- chan -> refcount != 0 )) { 333abort (); 334 } 335 336// uv will keep a reference to handles until next loop tick, so delay free 337multiqueue_put (main_loop .events ,free_channel_event ,chan ); 338} 339 340static void close_cb (Stream * stream ,void * data ) 341{ 342channel_decref (data ); 343} 344 345/// Starts a job and returns the associated channel 346/// 347/// @param[in] argv Arguments vector specifying the command to run, 348/// NULL-terminated 349/// @param[in] exepath The path to the executable. If NULL, use `argv[0]`. 350/// @param[in] on_stdout Callback to read the job's stdout 351/// @param[in] on_stderr Callback to read the job's stderr 352/// @param[in] on_exit Callback to receive the job's exit status 353/// @param[in] pty True if the job should run attached to a pty 354/// @param[in] rpc True to communicate with the job using msgpack-rpc, 355/// `on_stdout` is ignored 356/// @param[in] detach True if the job should not be killed when nvim exits, 357/// ignored if `pty` is true 358/// @param[in] stdin_mode Stdin mode. Either kChannelStdinPipe to open a 359/// channel for stdin or kChannelStdinNull to leave 360/// stdin disconnected. 361/// @param[in] cwd Initial working directory for the job. Nvim's working 362/// directory if `cwd` is NULL 363/// @param[in] pty_width Width of the pty, ignored if `pty` is false 364/// @param[in] pty_height Height of the pty, ignored if `pty` is false 365/// @param[in] env Nvim's configured environment is used if this is NULL, 366/// otherwise defines all environment variables 367/// @param[out] status_out 0 for invalid arguments, > 0 for the channel id, 368/// < 0 if the job can't start 369/// 370/// @returns [allocated] channel 371Channel * channel_job_start (char ** argv ,const char * exepath ,CallbackReader on_stdout , 372CallbackReader on_stderr ,Callback on_exit ,bool pty ,bool rpc , 373bool overlapped ,bool detach ,ChannelStdinMode stdin_mode , 374const char * cwd ,uint16_t pty_width ,uint16_t pty_height ,dict_T * env , 375varnumber_T * status_out ) 376{ 377Channel * chan = channel_alloc (kChannelStreamProc ); 378chan -> on_data = on_stdout ; 379chan -> on_stderr = on_stderr ; 380chan -> on_exit = on_exit ; 381 382if (pty ) { 383if (detach ) { 384semsg (_ (e_invarg2 ),"terminal/pty job cannot be detached" ); 385shell_free_argv (argv ); 386if (env ) { 387tv_dict_free (env ); 388 } 389channel_destroy_early (chan ); 390* status_out = 0 ; 391return NULL ; 392 } 393chan -> stream .pty = pty_proc_init (& main_loop ,chan ); 394if (pty_width > 0 ) { 395chan -> stream .pty .width = pty_width ; 396 } 397if (pty_height > 0 ) { 398chan -> stream .pty .height = pty_height ; 399 } 400 }else { 401chan -> stream .uv = libuv_proc_init (& main_loop ,chan ); 402 } 403 404Proc * proc = & chan -> stream .proc ; 405proc -> argv = argv ; 406proc -> exepath = exepath ; 407proc -> cb = channel_proc_exit_cb ; 408proc -> state_cb = channel_proc_state_cb ; 409proc -> events = chan -> events ; 410proc -> detach = detach ; 411proc -> cwd = cwd ; 412proc -> env = env ; 413proc -> overlapped = overlapped ; 414#ifdef MSWIN 415// Windows: spawn channel jobs with noinherit (so writes don't leak to TUI #40074). 416proc -> stdio_noinherit = true; 417#endif 418 419char * cmd = xstrdup (proc_get_exepath (proc )); 420bool has_out ,has_err ; 421if (proc -> type == kProcTypePty ) { 422has_out = true; 423has_err = false; 424 }else { 425has_out = rpc || callback_reader_set (chan -> on_data ); 426has_err = callback_reader_set (chan -> on_stderr ); 427proc -> fwd_err = chan -> on_stderr .fwd_err ; 428#ifdef MSWIN 429// DETACHED_PROCESS can't inherit console handles (like ConPTY stderr). 430// Use a pipe relay: libuv creates a pipe, on_channel_output writes to stderr. 431if (!has_err && proc -> fwd_err && proc -> detach ) { 432has_err = true; 433proc -> fwd_err = false; 434 } 435#endif 436 } 437 438bool has_in = stdin_mode == kChannelStdinPipe ; 439 440int status = proc_spawn (proc ,has_in ,has_out ,has_err ); 441if (status ) { 442semsg (_ (e_jobspawn ),os_strerror (status ),cmd ); 443xfree (cmd ); 444if (proc -> env ) { 445tv_dict_free (proc -> env ); 446 } 447channel_destroy_early (chan ); 448* status_out = proc -> status ; 449return NULL ; 450 } 451xfree (cmd ); 452if (proc -> env ) { 453tv_dict_free (proc -> env ); 454 } 455 456if (has_in ) { 457wstream_init (& proc -> in ,0 ); 458 } 459if (has_out ) { 460rstream_init (& proc -> out ); 461 } 462 463if (rpc ) { 464// the rpc takes over the in and out streams 465rpc_start (chan ); 466 }else { 467if (has_out ) { 468callback_reader_start (& chan -> on_data ,"stdout" ); 469rstream_start (& proc -> out ,on_channel_data ,chan ); 470 } 471 } 472 473if (has_err ) { 474callback_reader_start (& chan -> on_stderr ,"stderr" ); 475rstream_init (& proc -> err ); 476rstream_start (& proc -> err ,on_job_stderr ,chan ); 477 } 478 479* status_out = (varnumber_T )chan -> id ; 480return chan ; 481} 482 483uint64_t channel_connect (bool tcp ,const char * address ,bool rpc ,CallbackReader on_output , 484int timeout ,const char ** error ) 485{ 486Channel * channel ; 487 488if (!tcp && rpc ) { 489if (server_owns_pipe_address (address )) { 490// Create a loopback channel. This avoids deadlock if nvim connects to 491// its own named pipe. 492channel = channel_alloc (kChannelStreamInternal ); 493channel -> stream .internal .cb = LUA_NOREF ; 494rpc_start (channel ); 495 gotoend ; 496 } 497 } 498 499channel = channel_alloc (kChannelStreamSocket ); 500if (!socket_connect (& main_loop ,& channel -> stream .socket , 501tcp ,address ,timeout ,error )) { 502// Don't use channel_destroy_early() as new channels may have been allocated 503// by channel_from_connection() while polling for uv events. 504channel_decref (channel ); 505return 0 ; 506 } 507 508channel -> stream .socket .s .internal_close_cb = close_cb ; 509channel -> stream .socket .s .internal_data = channel ; 510wstream_init (& channel -> stream .socket .s ,0 ); 511rstream_init (& channel -> stream .socket ); 512 513if (rpc ) { 514rpc_start (channel ); 515 }else { 516channel -> on_data = on_output ; 517callback_reader_start (& channel -> on_data ,"data" ); 518rstream_start (& channel -> stream .socket ,on_channel_data ,channel ); 519 } 520 521end : 522channel_create_event (channel ,address ); 523return channel -> id ; 524} 525 526/// Creates an RPC channel from a tcp/pipe socket connection 527/// 528/// @param watcher The SocketWatcher ready to accept the connection 529void channel_from_connection (SocketWatcher * watcher ) 530{ 531Channel * channel = channel_alloc (kChannelStreamSocket ); 532int result = socket_watcher_accept (watcher ,& channel -> stream .socket ); 533if (result != 0 ) { 534ELOG ("Failed to accept connection: %s" ,uv_strerror (result )); 535channel_destroy_early (channel ); 536return ; 537 } 538channel -> stream .socket .s .internal_close_cb = close_cb ; 539channel -> stream .socket .s .internal_data = channel ; 540wstream_init (& channel -> stream .socket .s ,0 ); 541rstream_init (& channel -> stream .socket ); 542rpc_start (channel ); 543channel_create_event (channel ,watcher -> addr ); 544} 545 546/// Creates an API channel from stdin/stdout. Used when embedding Nvim. 547uint64_t channel_from_stdio (bool rpc ,CallbackReader on_output ,const char ** error ) 548FUNC_ATTR_NONNULL_ALL 549{ 550if (!headless_mode && !embedded_mode ) { 551* error = _ ("can only be opened in headless mode" ); 552return 0 ; 553 } 554 555if (did_stdio ) { 556* error = _ ("channel was already open" ); 557return 0 ; 558 } 559did_stdio = true; 560 561Channel * channel = channel_alloc (kChannelStreamStdio ); 562 563int stdin_dup_fd = STDIN_FILENO ; 564int stdout_dup_fd = STDOUT_FILENO ; 565#ifdef MSWIN 566// Strangely, ConPTY doesn't work if stdin and stdout are pipes. So replace 567// stdin and stdout with CONIN$ and CONOUT$, respectively. 568if (embedded_mode && os_has_conpty_working ()) { 569stdin_dup_fd = os_dup_cloexec (STDIN_FILENO ); 570stdout_dup_fd = os_dup_cloexec (STDOUT_FILENO ); 571if (!GetConsoleWindow ()) { 572// Borrow the parent's console so CONOUT$ resolves to the real terminal, 573// preserving io.stdout rendering (e.g. SIXEL/Kitty images). A replacement 574// server started by :restart can reuse the current server's console. 575// Only fall back to a hidden console when the parent has no console. 576if (!AttachConsole (ATTACH_PARENT_PROCESS )) { 577ILOG ("parent console attach failed: %lu; allocating hidden console" ,GetLastError ()); 578AllocConsole (); 579ShowWindow (GetConsoleWindow (),SW_HIDE ); 580 } 581 } 582os_reattach_console_stdio (); 583 } 584#else 585if (embedded_mode ) { 586// Redirect stdout/stdin (the UI channel) to stderr. Use fnctl(F_DUPFD_CLOEXEC) instead of dup() 587// to prevent child processes from inheriting the file descriptors, which are used by UIs to 588// detect when Nvim exits. 589stdin_dup_fd = fcntl (STDIN_FILENO ,F_DUPFD_CLOEXEC ,STDERR_FILENO + 1 ); 590stdout_dup_fd = fcntl (STDOUT_FILENO ,F_DUPFD_CLOEXEC ,STDERR_FILENO + 1 ); 591dup2 (STDERR_FILENO ,STDOUT_FILENO ); 592dup2 (STDERR_FILENO ,STDIN_FILENO ); 593 } 594#endif 595rstream_init_fd (& main_loop ,& channel -> stream .stdio .in ,stdin_dup_fd ); 596wstream_init_fd (& main_loop ,& channel -> stream .stdio .out ,stdout_dup_fd ,0 ); 597 598if (rpc ) { 599rpc_start (channel ); 600 }else { 601channel -> on_data = on_output ; 602callback_reader_start (& channel -> on_data ,"stdin" ); 603rstream_start (& channel -> stream .stdio .in ,on_channel_data ,channel ); 604 } 605 606return channel -> id ; 607} 608 609/// @param data will be consumed 610size_t channel_send (uint64_t id ,char * data ,size_t len ,bool data_owned ,const char ** error ) 611FUNC_ATTR_NONNULL_ALL 612{ 613Channel * chan = find_channel (id ); 614size_t written = 0 ; 615if (!chan ) { 616* error = _ (e_invchan ); 617 gotoretfree ; 618 } 619 620if (chan -> streamtype == kChannelStreamStderr ) { 621if (chan -> stream .err .closed ) { 622* error = _ ("Can't send data to closed stream" ); 623 gotoretfree ; 624 } 625// unbuffered write 626ptrdiff_t wres = os_write (STDERR_FILENO ,data ,len , false); 627if (wres >=0 ) { 628written = (size_t )wres ; 629 } 630 gotoretfree ; 631 } 632 633if (chan -> streamtype == kChannelStreamInternal ) { 634if (chan -> is_rpc ) { 635* error = _ ("Can't send raw data to rpc channel" ); 636 gotoretfree ; 637 } 638if (!chan -> term || chan -> stream .internal .closed ) { 639* error = _ ("Can't send data to closed stream" ); 640 gotoretfree ; 641 } 642terminal_receive (chan -> term ,data ,len ); 643written = len ; 644 gotoretfree ; 645 } 646 647Stream * in = channel_instream (chan ); 648if (in -> closed ) { 649* error = _ ("Can't send data to closed stream" ); 650 gotoretfree ; 651 } 652 653if (chan -> is_rpc ) { 654* error = _ ("Can't send raw data to rpc channel" ); 655 gotoretfree ; 656 } 657 658// write can be delayed indefinitely, so always use an allocated buffer 659WBuffer * buf = wstream_new_buffer (data_owned ?data :xmemdup (data ,len ), 660len ,1 ,xfree ); 661return wstream_write (in ,buf )== 0 ?len :0 ; 662 663retfree : 664if (data_owned ) { 665xfree (data ); 666 } 667return written ; 668} 669 670/// Convert binary byte array to a readfile()-style list 671/// 672/// @param[in] buf Array to convert. 673/// @param[in] len Array length. 674/// 675/// @return [allocated] Converted list. 676static inline list_T * buffer_to_tv_list (const char * const buf ,const size_t len ) 677FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE 678{ 679list_T * const l = tv_list_alloc (kListLenMayKnow ); 680// Empty buffer should be represented by [''], encode_list_write() thinks 681// empty list is fine for the case. 682tv_list_append_string (l ,"" ,0 ); 683if (len > 0 ) { 684encode_list_write (l ,buf ,len ); 685 } 686return l ; 687} 688 689size_t on_channel_data (RStream * stream ,const char * buf ,size_t count ,void * data ,bool eof ) 690{ 691Channel * chan = data ; 692return on_channel_output (stream ,chan ,buf ,count ,eof ,& chan -> on_data ); 693} 694 695size_t on_job_stderr (RStream * stream ,const char * buf ,size_t count ,void * data ,bool eof ) 696{ 697Channel * chan = data ; 698return on_channel_output (stream ,chan ,buf ,count ,eof ,& chan -> on_stderr ); 699} 700 701static size_t on_channel_output (RStream * stream ,Channel * chan ,const char * buf ,size_t count , 702bool eof ,CallbackReader * reader ) 703{ 704if (chan -> term ) { 705terminal_receive (chan -> term ,buf ,count ); 706 } 707 708if (eof ) { 709reader -> eof = true; 710 } 711 712#ifdef MSWIN 713// Pipe relay for fwd_err on Windows: relay server stderr to stdout. 714// DETACHED_PROCESS prevents inheriting console handles, so channel_job_start 715// creates a pipe instead. Write to stdout because ConPTY only captures stdout. 716// On non-Windows, fwd_err uses UV_INHERIT_FD directly; this path is never reached. 717if (reader -> fwd_err && count > 0 ) { 718ptrdiff_t wres = os_write (STDOUT_FILENO ,buf ,count , false); 719return (size_t )MAX (wres ,0 ); 720 } 721#endif 722 723if (callback_reader_set (* reader )) { 724ga_concat_len (& reader -> buffer ,buf ,count ); 725schedule_channel_event (chan ); 726 } 727 728return count ; 729} 730 731/// schedule the necessary callbacks to be invoked as a deferred event 732static void schedule_channel_event (Channel * chan ) 733{ 734if (!chan -> callback_scheduled ) { 735if (!chan -> callback_busy ) { 736multiqueue_put (chan -> events ,on_channel_event ,chan ); 737channel_incref (chan ); 738 } 739chan -> callback_scheduled = true; 740 } 741} 742 743static void on_channel_event (void ** args ) 744{ 745Channel * chan = (Channel * )args [0 ]; 746 747chan -> callback_busy = true; 748chan -> callback_scheduled = false; 749 750int exit_status = chan -> exit_status ; 751channel_reader_callbacks (chan ,& chan -> on_data ); 752channel_reader_callbacks (chan ,& chan -> on_stderr ); 753if (exit_status > -1 ) { 754channel_callback_call (chan ,NULL ); 755chan -> exit_status = -1 ; 756 } 757 758chan -> callback_busy = false; 759if (chan -> callback_scheduled ) { 760// further callback was deferred to avoid recursion. 761multiqueue_put (chan -> events ,on_channel_event ,chan ); 762channel_incref (chan ); 763 } 764 765channel_decref (chan ); 766} 767 768void channel_reader_callbacks (Channel * chan ,CallbackReader * reader ) 769{ 770if (reader -> buffered ) { 771if (reader -> eof ) { 772if (reader -> self ) { 773if (tv_dict_find (reader -> self ,reader -> type ,-1 )== NULL ) { 774list_T * data = buffer_to_tv_list (reader -> buffer .ga_data , 775 (size_t )reader -> buffer .ga_len ); 776tv_dict_add_list (reader -> self ,reader -> type ,strlen (reader -> type ), 777data ); 778 }else { 779semsg (_ (e_streamkey ),reader -> type ,chan -> id ); 780 } 781 }else { 782channel_callback_call (chan ,reader ); 783 } 784reader -> eof = false; 785 } 786 }else { 787bool is_eof = reader -> eof ; 788if (reader -> buffer .ga_len > 0 ) { 789channel_callback_call (chan ,reader ); 790 } 791// if the stream reached eof, invoke extra callback with no data 792if (is_eof ) { 793channel_callback_call (chan ,reader ); 794reader -> eof = false; 795 } 796 } 797} 798 799static void channel_proc_exit_cb (Proc * proc ,int status ,void * data ) 800{ 801Channel * chan = data ; 802if (chan -> term ) { 803terminal_close (& chan -> term ,status ); 804 } 805 806// TODO(justinmk): figure out why rpc_close sometimes(??) isn't called. 807// Theories: 808// - EOF not received in receive_msgpack, then doesn't call chan_close_on_err(). 809// - proc_close_handles not tickled by ui_client.c's LOOP_PROCESS_EVENTS? 810if (!exiting && ui_client_channel_id == chan -> id ) { 811// rpc_close_event() could handle this in principle also for processes, but 812// sometimes it gets called later than this, and we do care about the exit status 813ui_client_attach_to_restarted_server (proc -> status != 0 ); 814if (ui_client_channel_id == chan -> id ) { 815// If the current embedded server has exited and no new server is started, 816// the client should exit with the same status. 817exit_on_closed_chan (status ); 818 } 819 } 820 821// If process did not exit, we only closed the handle of a detached process. 822bool exited = (status >=0 ); 823if (exited && chan -> on_exit .type != kCallbackNone ) { 824schedule_channel_event (chan ); 825 } 826chan -> exit_status = exited ?status :chan -> exit_status ; 827 828channel_decref (chan ); 829} 830 831static void channel_proc_state_cb (Proc * proc ,bool suspended ,void * data ) 832{ 833Channel * chan = data ; 834if (chan -> term ) { 835terminal_set_state (chan -> term ,suspended ); 836 } 837} 838 839static void channel_callback_call (Channel * chan ,CallbackReader * reader ) 840{ 841Callback * cb ; 842typval_T argv [4 ]; 843 844argv [0 ].v_type = VAR_NUMBER ; 845argv [0 ].v_lock = VAR_UNLOCKED ; 846argv [0 ].vval .v_number = (varnumber_T )chan -> id ; 847 848if (reader ) { 849argv [1 ].v_type = VAR_LIST ; 850argv [1 ].v_lock = VAR_UNLOCKED ; 851argv [1 ].vval .v_list = buffer_to_tv_list (reader -> buffer .ga_data , 852 (size_t )reader -> buffer .ga_len ); 853tv_list_ref (argv [1 ].vval .v_list ); 854ga_clear (& reader -> buffer ); 855cb = & reader -> cb ; 856argv [2 ].vval .v_string = (char * )reader -> type ; 857 }else { 858argv [1 ].v_type = VAR_NUMBER ; 859argv [1 ].v_lock = VAR_UNLOCKED ; 860argv [1 ].vval .v_number = chan -> exit_status ; 861cb = & chan -> on_exit ; 862argv [2 ].vval .v_string = "exit" ; 863 } 864 865argv [2 ].v_type = VAR_STRING ; 866argv [2 ].v_lock = VAR_UNLOCKED ; 867 868typval_T rettv = TV_INITIAL_VALUE ; 869callback_call (cb ,3 ,argv ,& rettv ); 870tv_clear (& rettv ); 871 872if (reader ) { 873tv_list_unref (argv [1 ].vval .v_list ); 874 } 875} 876 877/// Allocate terminal for channel 878/// 879/// Channel `chan` is assumed to be an open pty channel, 880/// and `buf` is assumed to be a new, unmodified buffer. 881void channel_terminal_alloc (buf_T * buf ,Channel * chan ) 882{ 883TerminalOptions topts = { 884 .data = chan , 885 .width = chan -> stream .pty .width , 886 .height = chan -> stream .pty .height , 887 .read_pause_cb = term_read_pause , 888 .write_cb = term_write , 889 .resize_cb = term_resize , 890 .resume_cb = term_resume , 891 .close_cb = term_close , 892 .force_crlf = false, 893 }; 894buf -> b_p_channel = (OptInt )chan -> id ;// 'channel' option 895channel_incref (chan ); 896chan -> term = terminal_alloc (buf ,topts ); 897} 898 899static void term_read_pause (bool pause ,void * data ) 900{ 901Channel * chan = data ; 902if (chan -> stream .proc .out .s .closed ) { 903return ; 904 } 905if (pause ) { 906rstream_stop_inner (& chan -> stream .proc .out ); 907 }else { 908rstream_start_inner (& chan -> stream .proc .out ); 909 } 910} 911 912static void term_write (const char * buf ,size_t size ,void * data ) 913{ 914Channel * chan = data ; 915if (chan -> stream .proc .in .closed ) { 916// If the backing stream was closed abruptly, there may be write events 917// ahead of the terminal close event. Just ignore the writes. 918ILOG ("write failed: stream is closed" ); 919return ; 920 } 921WBuffer * wbuf = wstream_new_buffer (xmemdup (buf ,size ),size ,1 ,xfree ); 922wstream_write (& chan -> stream .proc .in ,wbuf ); 923} 924 925static void term_resize (uint16_t width ,uint16_t height ,void * data ) 926{ 927Channel * chan = data ; 928pty_proc_resize (& chan -> stream .pty ,width ,height ); 929} 930 931static void term_resume (void * data ) 932{ 933Channel * chan = data ; 934pty_proc_resume (& chan -> stream .pty ); 935} 936 937static inline void term_delayed_free (void ** argv ) 938{ 939Channel * chan = argv [0 ]; 940if (chan -> stream .proc .in .pending_reqs || chan -> stream .proc .out .s .pending_reqs ) { 941multiqueue_put (chan -> events ,term_delayed_free ,chan ); 942return ; 943 } 944 945if (chan -> term ) { 946terminal_destroy (& chan -> term ); 947 } 948channel_decref (chan ); 949} 950 951static void term_close (void * data ) 952{ 953Channel * chan = data ; 954proc_stop (& chan -> stream .proc ); 955multiqueue_put (chan -> events ,term_delayed_free ,data ); 956} 957 958void channel_event (Channel * chan ,event_T event ) 959{ 960if (has_event (event )) { 961channel_incref (chan ); 962multiqueue_put (main_loop .events ,set_info_event ,chan , (void * )(intptr_t )event ); 963 } 964} 965 966static void set_info_event (void ** argv ) 967{ 968Channel * chan = argv [0 ]; 969event_T event = (event_T )(ptrdiff_t )argv [1 ]; 970 971save_v_event_T save_v_event ; 972dict_T * dict = get_v_event (& save_v_event ); 973Arena arena = ARENA_EMPTY ; 974Dict info = channel_info (chan -> id ,& arena ); 975typval_T retval ; 976object_to_vim (DICT_OBJ (info ),& retval ,NULL ); 977assert (retval .v_type == VAR_DICT ); 978tv_dict_add_dict (dict ,S_LEN ("info" ),retval .vval .v_dict ); 979tv_dict_set_keys_readonly (dict ); 980 981apply_autocmds (event ,NULL ,NULL , true,curbuf ); 982 983restore_v_event (dict ,& save_v_event ); 984arena_mem_free (arena_finish (& arena )); 985channel_decref (chan ); 986} 987 988/// Unlike terminal_running(), this returns false immediately after stopping a job. 989/// However, this always returns false for nvim_open_term() terminals. 990bool channel_job_running (uint64_t id ) 991{ 992Channel * chan = find_channel (id ); 993return (chan 994&& chan -> streamtype == kChannelStreamProc 995&& !proc_is_stopped (& chan -> stream .proc )); 996} 997 998Dict channel_info (uint64_t id ,Arena * arena ) 999{ 1000Channel * chan = find_channel (id ); 1001if (!chan ) { 1002return (Dict )ARRAY_DICT_INIT ; 1003 } 1004 1005Dict info = arena_dict (arena ,9 ); 1006PUT_C (info ,"id" ,INTEGER_OBJ ((Integer )chan -> id )); 1007 1008const char * stream_desc ,* mode_desc ; 1009switch (chan -> streamtype ) { 1010case kChannelStreamProc : { 1011stream_desc = "job" ; 1012if (chan -> stream .proc .type == kProcTypePty ) { 1013const char * name = pty_proc_tty_name (& chan -> stream .pty ); 1014PUT_C (info ,"pty" ,CSTR_TO_ARENA_OBJ (arena ,name )); 1015 } 1016 1017char ** args = chan -> stream .proc .argv ; 1018Array argv = ARRAY_DICT_INIT ; 1019if (args != NULL ) { 1020size_t n ; 1021for (n = 0 ;args [n ]!= NULL ;n ++ ) {} 1022argv = arena_array (arena ,n ); 1023for (size_t i = 0 ;i < n ;i ++ ) { 1024ADD_C (argv ,CSTR_AS_OBJ (args [i ])); 1025 } 1026 } 1027PUT_C (info ,"argv" ,ARRAY_OBJ (argv )); 1028break ; 1029 } 1030 1031case kChannelStreamStdio : 1032stream_desc = "stdio" ; 1033break ; 1034 1035case kChannelStreamStderr : 1036stream_desc = "stderr" ; 1037break ; 1038 1039case kChannelStreamInternal : 1040PUT_C (info ,"internal" ,BOOLEAN_OBJ (true)); 1041FALLTHROUGH ; 1042 1043case kChannelStreamSocket : 1044stream_desc = "socket" ; 1045break ; 1046 } 1047PUT_C (info ,"stream" ,CSTR_AS_OBJ (stream_desc )); 1048 1049if (chan -> is_rpc ) { 1050mode_desc = "rpc" ; 1051PUT_C (info ,"client" ,DICT_OBJ (chan -> rpc .info )); 1052 }else if (chan -> term ) { 1053mode_desc = "terminal" ; 1054PUT_C (info ,"buf" ,BUFFER_OBJ (terminal_buf (chan -> term ))); 1055PUT_C (info ,"buffer" ,BUFFER_OBJ (terminal_buf (chan -> term ))); 1056PUT_C (info ,"exitcode" ,INTEGER_OBJ (chan -> exit_status )); 1057 }else { 1058mode_desc = "bytes" ; 1059 } 1060PUT_C (info ,"mode" ,CSTR_AS_OBJ (mode_desc )); 1061 1062return info ; 1063} 1064 1065/// Simple int64_t comparison function for use with qsort() 1066static int int64_t_cmp (const void * pa ,const void * pb ) 1067{ 1068const int64_t a = * (const int64_t * )pa ; 1069const int64_t b = * (const int64_t * )pb ; 1070return a == b ?0 :a > b ?1 :-1 ; 1071} 1072 1073Array channel_all_info (Arena * arena ) 1074{ 1075// order the items in the array by channel number, for Determinismâ„¢ 1076kvec_t (int64_t )ids = KV_INITIAL_VALUE ; 1077kv_fixsize_arena (arena ,ids ,map_size (& channels )); 1078uint64_t id ; 1079map_foreach_key (& channels ,id , { 1080kv_push (ids , (int64_t )id ); 1081 }); 1082qsort (ids .items ,ids .size ,sizeof ids .items [0 ],int64_t_cmp ); 1083 1084Array ret = arena_array (arena ,ids .size ); 1085for (size_t i = 0 ;i < ids .size ;i ++ ) { 1086ADD_C (ret ,DICT_OBJ (channel_info ((uint64_t )ids .items [i ],arena ))); 1087 } 1088return ret ; 1089}