robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
64a301184e
master
1#include <assert.h> 2#include <stdbool.h> 3#include <stdint.h> 4#include <stdio.h> 5#include <string.h> 6#include <uv.h> 7 8#include "auto/config.h" 9#include "klib/kvec.h" 10#include "nvim/api/private/helpers.h" 11#include "nvim/ascii_defs.h" 12#include "nvim/buffer.h" 13#include "nvim/charset.h" 14#include "nvim/errors.h" 15#include "nvim/eval/typval_defs.h" 16#include "nvim/eval/vars.h" 17#include "nvim/event/defs.h" 18#include "nvim/event/libuv_proc.h" 19#include "nvim/event/loop.h" 20#include "nvim/event/multiqueue.h" 21#include "nvim/event/proc.h" 22#include "nvim/event/rstream.h" 23#include "nvim/event/stream.h" 24#include "nvim/event/wstream.h" 25#include "nvim/ex_cmds.h" 26#include "nvim/fileio.h" 27#include "nvim/gettext_defs.h" 28#include "nvim/globals.h" 29#include "nvim/macros_defs.h" 30#include "nvim/main.h" 31#include "nvim/mbyte.h" 32#include "nvim/memline.h" 33#include "nvim/memory.h" 34#include "nvim/message.h" 35#include "nvim/option_vars.h" 36#include "nvim/os/fs.h" 37#include "nvim/os/os.h" 38#include "nvim/os/os_defs.h" 39#include "nvim/os/shell.h" 40#include "nvim/os/signal.h" 41#include "nvim/os/time.h" 42#include "nvim/path.h" 43#include "nvim/pos_defs.h" 44#include "nvim/profile.h" 45#include "nvim/state_defs.h" 46#include "nvim/strings.h" 47#include "nvim/tag.h" 48#include "nvim/types_defs.h" 49#include "nvim/ui.h" 50#include "nvim/vim_defs.h" 51 52#define OUT_DATA_THRESHOLD 1024 * 10U // 10KB, "a few screenfuls" of data. 53 54#define SHELL_SPECIAL "\t \"&'$;<>()\\|\n" 55 56#include "os/shell.c.generated.h" 57 58static void save_patterns (int num_pat ,char ** pat ,int * num_file ,char *** file ) 59{ 60* file = xmalloc ((size_t )num_pat * sizeof (char * )); 61for (int i = 0 ;i < num_pat ;i ++ ) { 62char * s = xstrdup (pat [i ]); 63// Be compatible with expand_filename(): halve the number of 64// backslashes. 65backslash_halve (s ); 66 (* file )[i ]= s ; 67 } 68* num_file = num_pat ; 69} 70 71static bool have_wildcard (int num ,char ** file ) 72{ 73for (int i = 0 ;i < num ;i ++ ) { 74if (path_has_wildcard (file [i ], true)) { 75return true; 76 } 77 } 78return false; 79} 80 81static bool have_dollars (int num ,char ** file ) 82{ 83for (int i = 0 ;i < num ;i ++ ) { 84if (vim_strchr (file [i ],'$' )!= NULL ) { 85return true; 86 } 87 } 88return false; 89} 90 91/// Performs wildcard pattern matching using the shell. 92/// 93/// @param num_pat is the number of input patterns. 94/// @param pat is an array of pointers to input patterns. 95/// @param[out] num_file is pointer to number of matched file names. 96/// Set to the number of pointers in *file. 97/// @param[out] file is pointer to array of pointers to matched file names. 98/// Memory pointed to by the initial value of *file will 99/// not be freed. 100/// Set to NULL if FAIL is returned. Otherwise points to 101/// allocated memory. 102/// @param flags is a combination of EW_* flags used in 103/// expand_wildcards(). 104/// If matching fails but EW_NOTFOUND is set in flags or 105/// there are no wildcards, the patterns from pat are 106/// copied into *file. 107/// 108/// @returns OK for success or FAIL for error. 109int os_expand_wildcards (int num_pat ,char ** pat ,int * num_file ,char *** file ,int flags ) 110FUNC_ATTR_NONNULL_ARG (3 ) 111FUNC_ATTR_NONNULL_ARG (4 ) 112{ 113int i ; 114size_t len ; 115char * p ; 116char * extra_shell_arg = NULL ; 117int shellopts = kShellOptExpand |kShellOptSilent ; 118int j ; 119char * tempname ; 120#define STYLE_ECHO 0 // use "echo", the default 121#define STYLE_GLOB 1 // use "glob", for csh 122#define STYLE_VIMGLOB 2 // use "vimglob", for Posix sh 123#define STYLE_PRINT 3 // use "print -N", for zsh 124#define STYLE_BT 4 // `cmd` expansion, execute the pattern directly 125#define STYLE_GLOBSTAR 5 // use extended shell glob for bash (this uses extended 126// globbing functionality with globstar, needs bash > 4) 127int shell_style = STYLE_ECHO ; 128int check_spaces ; 129static bool did_find_nul = false; 130bool ampersand = false; 131// vimglob() function to define for Posix shell 132static char * sh_vimglob_func = 133"vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >" ; 134// vimglob() function with globstar setting enabled, only for bash >= 4.X 135static char * sh_globstar_opt = 136"[[ ${BASH_VERSINFO[0]} -ge 4 ]] && shopt -s globstar; " ; 137 138bool is_fish_shell = 139#ifdef UNIX 140strncmp (invocation_path_tail (p_sh ,NULL ),"fish" ,4 )== 0 ; 141#else 142 false; 143#endif 144 145* num_file = 0 ;// default: no files found 146* file = NULL ; 147 148// If there are no wildcards, just copy the names to allocated memory. 149// Saves a lot of time, because we don't have to start a new shell. 150if (!have_wildcard (num_pat ,pat )) { 151save_patterns (num_pat ,pat ,num_file ,file ); 152return OK ; 153 } 154 155// Don't allow any shell command in the sandbox. 156if (sandbox != 0 && check_secure ()) { 157return FAIL ; 158 } 159 160// Don't allow the use of backticks in secure. 161if (secure ) { 162for (i = 0 ;i < num_pat ;i ++ ) { 163if (vim_strchr (pat [i ],'`' )!= NULL 164&& (check_secure ())) { 165return FAIL ; 166 } 167 } 168 } 169 170// get a name for the temp file 171if ((tempname = vim_tempname ())== NULL ) { 172emsg (_ (e_notmp )); 173return FAIL ; 174 } 175 176// Let the shell expand the patterns and write the result into the temp 177// file. 178// STYLE_BT: NL separated 179// If expanding `cmd` execute it directly. 180// STYLE_GLOB: NUL separated 181// If we use *csh, "glob" will work better than "echo". 182// STYLE_PRINT: NL or NUL separated 183// If we use *zsh, "print -N" will work better than "glob". 184// STYLE_VIMGLOB: NL separated 185// If we use *sh*, we define "vimglob()". 186// STYLE_GLOBSTAR: NL separated 187// If we use *bash*, we define "vimglob() and enable globstar option". 188// STYLE_ECHO: space separated. 189// A shell we don't know, stay safe and use "echo". 190if (num_pat == 1 && * pat [0 ]== '`' 191&& (len = strlen (pat [0 ]))> 2 192&& * (pat [0 ]+ len - 1 )== '`' ) { 193shell_style = STYLE_BT ; 194 }else if ((len = strlen (p_sh )) >=3 ) { 195if (strcmp (p_sh + len - 3 ,"csh" )== 0 ) { 196shell_style = STYLE_GLOB ; 197 }else if (strcmp (p_sh + len - 3 ,"zsh" )== 0 ) { 198shell_style = STYLE_PRINT ; 199 } 200 } 201if (shell_style == STYLE_ECHO ) { 202if (strstr (path_tail (p_sh ),"bash" )!= NULL ) { 203shell_style = STYLE_GLOBSTAR ; 204 }else if (strstr (path_tail (p_sh ),"sh" )!= NULL ) { 205shell_style = STYLE_VIMGLOB ; 206 } 207 } 208 209// Compute the length of the command. We need 2 extra bytes: for the 210// optional '&' and for the NUL. 211// Worst case: "unset nonomatch; print -N >" plus two is 29 212len = strlen (tempname )+ 29 ; 213if (shell_style == STYLE_VIMGLOB ) { 214len += strlen (sh_vimglob_func ); 215 }else if (shell_style == STYLE_GLOBSTAR ) { 216len += strlen (sh_vimglob_func )+ strlen (sh_globstar_opt ); 217 } 218 219for (i = 0 ;i < num_pat ;i ++ ) { 220// Count the length of the patterns in the same way as they are put in 221// "command" below. 222len ++ ;// add space 223for (j = 0 ;pat [i ][j ]!= NUL ;j ++ ) { 224if (vim_strchr (SHELL_SPECIAL , (uint8_t )pat [i ][j ])!= NULL ) { 225len ++ ;// may add a backslash 226 } 227len ++ ; 228 } 229 } 230 231if (is_fish_shell ) { 232len += sizeof ("egin;" " end" )- 1 ; 233 } 234 235char * command = xmalloc (len ); 236 237// Build the shell command: 238// - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell 239// recognizes this). 240// - Add the shell command to print the expanded names. 241// - Add the temp file name. 242// - Add the file name patterns. 243if (shell_style == STYLE_BT ) { 244// change `command; command& ` to (command; command ) 245if (is_fish_shell ) { 246STRCPY (command ,"begin; " ); 247 }else { 248STRCPY (command ,"(" ); 249 } 250strcat (command ,pat [0 ]+ 1 );// exclude first backtick 251p = command + strlen (command )- 1 ; 252if (is_fish_shell ) { 253* p -- = ';' ; 254strcat (command ," end" ); 255 }else { 256* p -- = ')' ;// remove last backtick 257 } 258while (p > command && ascii_iswhite (* p )) { 259p -- ; 260 } 261if (* p == '&' ) {// remove trailing '&' 262ampersand = true; 263* p = ' ' ; 264 } 265strcat (command ,">" ); 266 }else { 267STRCPY (command ,"" ); 268if (shell_style == STYLE_GLOB ) { 269// Assume the nonomatch option is valid only for csh like shells, 270// otherwise, this may set the positional parameters for the shell, 271// e.g. "$*". 272if (flags & EW_NOTFOUND ) { 273strcat (command ,"set nonomatch; " ); 274 }else { 275strcat (command ,"unset nonomatch; " ); 276 } 277 } 278if (shell_style == STYLE_GLOB ) { 279strcat (command ,"glob >" ); 280 }else if (shell_style == STYLE_PRINT ) { 281strcat (command ,"print -N >" ); 282 }else if (shell_style == STYLE_VIMGLOB ) { 283strcat (command ,sh_vimglob_func ); 284 }else if (shell_style == STYLE_GLOBSTAR ) { 285strcat (command ,sh_globstar_opt ); 286strcat (command ,sh_vimglob_func ); 287 }else { 288strcat (command ,"echo >" ); 289 } 290 } 291 292strcat (command ,tempname ); 293 294if (shell_style != STYLE_BT ) { 295for (i = 0 ;i < num_pat ;i ++ ) { 296// Put a backslash before special 297// characters, except inside ``. 298bool intick = false; 299 300p = command + strlen (command ); 301* p ++ = ' ' ; 302for (j = 0 ;pat [i ][j ]!= NUL ;j ++ ) { 303if (pat [i ][j ]== '`' ) { 304intick = !intick ; 305 }else if (pat [i ][j ]== '\\' && pat [i ][j + 1 ]!= NUL ) { 306// Remove a backslash, take char literally. But keep 307// backslash inside backticks, before a special character 308// and before a backtick. 309if (intick 310|| vim_strchr (SHELL_SPECIAL , (uint8_t )pat [i ][j + 1 ])!= NULL 311|| pat [i ][j + 1 ]== '`' ) { 312* p ++ = '\\' ; 313 } 314j ++ ; 315 }else if (!intick 316&& ((flags & EW_KEEPDOLLAR )== 0 || pat [i ][j ]!= '$' ) 317&& vim_strchr (SHELL_SPECIAL , (uint8_t )pat [i ][j ])!= NULL ) { 318// Put a backslash before a special character, but not 319// when inside ``. And not for $var when EW_KEEPDOLLAR is 320// set. 321* p ++ = '\\' ; 322 } 323 324// Copy one character. 325* p ++ = pat [i ][j ]; 326 } 327* p = NUL ; 328 } 329 } 330 331if (flags & EW_SILENT ) { 332shellopts |=kShellOptHideMess ; 333 } 334 335if (ampersand ) { 336strcat (command ,"&" );// put the '&' after the redirection 337 } 338 339// Using zsh -G: If a pattern has no matches, it is just deleted from 340// the argument list, otherwise zsh gives an error message and doesn't 341// expand any other pattern. 342if (shell_style == STYLE_PRINT ) { 343extra_shell_arg = "-G" ;// Use zsh NULL_GLOB option 344 345// If we use -f then shell variables set in .cshrc won't get expanded. 346// vi can do it, so we will too, but it is only necessary if there is a "$" 347// in one of the patterns, otherwise we can still use the fast option. 348 }else if (shell_style == STYLE_GLOB && !have_dollars (num_pat ,pat )) { 349extra_shell_arg = "-f" ;// Use csh fast option 350 } 351 352// execute the shell command 353i = call_shell (command ,shellopts ,extra_shell_arg ); 354 355// When running in the background, give it some time to create the temp 356// file, but don't wait for it to finish. 357if (ampersand ) { 358os_delay (10 , true); 359 } 360 361xfree (command ); 362 363if (i ) {// os_call_shell() failed 364os_remove (tempname ); 365xfree (tempname ); 366// With interactive completion, the error message is not printed. 367if (!(flags & EW_SILENT )) { 368msg_putchar ('\n' );// clear bottom line quickly 369cmdline_row = Rows - 1 ;// continue on last line 370msg (_ (e_wildexpand ),0 ); 371msg_start ();// don't overwrite this message 372 } 373 374// If a `cmd` expansion failed, don't list `cmd` as a match, even when 375// EW_NOTFOUND is given 376if (shell_style == STYLE_BT ) { 377return FAIL ; 378 } 379 gotonotfound ; 380 } 381 382// read the names from the file into memory 383FILE * fd = fopen (tempname ,READBIN ); 384if (fd == NULL ) { 385// Something went wrong, perhaps a file name with a special char. 386if (!(flags & EW_SILENT )) { 387msg (_ (e_wildexpand ),0 ); 388msg_start ();// don't overwrite this message 389 } 390xfree (tempname ); 391 gotonotfound ; 392 } 393int fseek_res = fseek (fd ,0 ,SEEK_END ); 394if (fseek_res < 0 ) { 395xfree (tempname ); 396fclose (fd ); 397return FAIL ; 398 } 399int64_t templen = ftell (fd );// get size of temp file 400if (templen < 0 ) { 401xfree (tempname ); 402fclose (fd ); 403return FAIL ; 404 } 405#if 8 > SIZEOF_SIZE_T 406assert (templen <=SIZE_MAX );// NOLINT(runtime/int) 407#endif 408len = (size_t )templen ; 409fseek (fd ,0 ,SEEK_SET ); 410char * buffer = xmalloc (len + 1 ); 411// fread() doesn't terminate buffer with NUL; 412// appropriate termination (not always NUL) is done below. 413size_t readlen = fread (buffer ,1 ,len ,fd ); 414fclose (fd ); 415os_remove (tempname ); 416if (readlen != len ) { 417// unexpected read error 418semsg (_ (e_cant_read_file_str ),tempname ); 419xfree (tempname ); 420xfree (buffer ); 421return FAIL ; 422 } 423xfree (tempname ); 424 425// file names are separated with Space 426if (shell_style == STYLE_ECHO ) { 427buffer [len ]= '\n' ;// make sure the buffer ends in NL 428p = buffer ; 429for (i = 0 ;* p != '\n' ;i ++ ) {// count number of entries 430while (* p != ' ' && * p != '\n' ) { 431p ++ ; 432 } 433p = skipwhite (p );// skip to next entry 434 } 435// file names are separated with NL 436 }else if (shell_style == STYLE_BT 437|| shell_style == STYLE_VIMGLOB 438|| shell_style == STYLE_GLOBSTAR ) { 439buffer [len ]= NUL ;// make sure the buffer ends in NUL 440p = buffer ; 441for (i = 0 ;* p != NUL ;i ++ ) {// count number of entries 442while (* p != '\n' && * p != NUL ) { 443p ++ ; 444 } 445if (* p != NUL ) { 446p ++ ; 447 } 448p = skipwhite (p );// skip leading white space 449 } 450// file names are separated with NUL 451 }else { 452// Some versions of zsh use spaces instead of NULs to separate 453// results. Only do this when there is no NUL before the end of the 454// buffer, otherwise we would never be able to use file names with 455// embedded spaces when zsh does use NULs. 456// When we found a NUL once, we know zsh is OK, set did_find_nul and 457// don't check for spaces again. 458check_spaces = false; 459if (shell_style == STYLE_PRINT && !did_find_nul ) { 460// If there is a NUL, set did_find_nul, else set check_spaces 461buffer [len ]= NUL ; 462if (len && (int )strlen (buffer )< (int )len ) { 463did_find_nul = true; 464 }else { 465check_spaces = true; 466 } 467 } 468 469// Make sure the buffer ends with a NUL. For STYLE_PRINT there 470// already is one, for STYLE_GLOB it needs to be added. 471if (len && buffer [len - 1 ]== NUL ) { 472len -- ; 473 }else { 474buffer [len ]= NUL ; 475 } 476for (p = buffer ;p < buffer + len ;p ++ ) { 477if (* p == NUL || (* p == ' ' && check_spaces )) {// count entry 478i ++ ; 479* p = NUL ; 480 } 481 } 482if (len ) { 483i ++ ;// count last entry 484 } 485 } 486assert (buffer [len ]== NUL || buffer [len ]== '\n' ); 487 488if (i == 0 ) { 489// Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I". 490// /bin/sh will happily expand it to nothing rather than returning an 491// error; and hey, it's good to check anyway -- webb. 492xfree (buffer ); 493 gotonotfound ; 494 } 495* num_file = i ; 496* file = xmalloc (sizeof (char * )* (size_t )i ); 497 498// Isolate the individual file names. 499p = buffer ; 500for (i = 0 ;i < * num_file ;i ++ ) { 501 (* file )[i ]= p ; 502// Space or NL separates 503if (shell_style == STYLE_ECHO || shell_style == STYLE_BT 504|| shell_style == STYLE_VIMGLOB || shell_style == STYLE_GLOBSTAR ) { 505while (!(shell_style == STYLE_ECHO && * p == ' ' ) 506&& * p != '\n' && * p != NUL ) { 507p ++ ; 508 } 509if (p == buffer + len ) {// last entry 510* p = NUL ; 511 }else { 512* p ++ = NUL ; 513p = skipwhite (p );// skip to next entry 514 } 515 }else {// NUL separates 516while (* p && p < buffer + len ) {// skip entry 517p ++ ; 518 } 519p ++ ;// skip NUL 520 } 521 } 522 523// Move the file names to allocated memory. 524for (j = 0 ,i = 0 ;i < * num_file ;i ++ ) { 525// Require the files to exist. Helps when using /bin/sh 526if (!(flags & EW_NOTFOUND )&& !os_path_exists ((* file )[i ])) { 527continue ; 528 } 529 530// check if this entry should be included 531bool dir = (os_isdir ((* file )[i ])); 532if ((dir && !(flags & EW_DIR ))|| (!dir && !(flags & EW_FILE ))) { 533continue ; 534 } 535 536// Skip files that are not executable if we check for that. 537if (!dir && (flags & EW_EXEC ) 538&& !os_can_exe ((* file )[i ],NULL , !(flags & EW_SHELLCMD ))) { 539continue ; 540 } 541 542p = xmalloc (strlen ((* file )[i ])+ 1 + dir ); 543STRCPY (p , (* file )[i ]); 544if (dir ) { 545add_pathsep (p );// add '/' to a directory name 546 } 547 (* file )[j ++ ]= p ; 548 } 549xfree (buffer ); 550* num_file = j ; 551 552if (* num_file == 0 ) {// rejected all entries 553XFREE_CLEAR (* file ); 554 gotonotfound ; 555 } 556 557return OK ; 558 559notfound : 560if (flags & EW_NOTFOUND ) { 561save_patterns (num_pat ,pat ,num_file ,file ); 562return OK ; 563 } 564return FAIL ; 565} 566 567/// Builds the argument vector for running the user-configured 'shell' (p_sh) 568/// with an optional command prefixed by 'shellcmdflag' (p_shcf). E.g.: 569/// 570/// ["shell", "-extra_args", "-shellcmdflag", "command with spaces"] 571/// 572/// @param cmd Command string, or NULL to run an interactive shell. 573/// @param extra_args Extra arguments to the shell, or NULL. 574/// @return Newly allocated argument vector. Must be freed with shell_free_argv. 575char ** shell_build_argv (const char * cmd ,const char * extra_args ) 576FUNC_ATTR_NONNULL_RET 577{ 578size_t argc = tokenize (p_sh ,NULL )+ (cmd ?tokenize (p_shcf ,NULL ) :0 ); 579char ** rv = xmalloc ((argc + 4 )* sizeof (* rv )); 580 581// Split 'shell' 582size_t i = tokenize (p_sh ,rv ); 583 584if (extra_args ) { 585rv [i ++ ]= xstrdup (extra_args );// Push a copy of `extra_args` 586 } 587 588if (cmd ) { 589i += tokenize (p_shcf ,rv + i );// Split 'shellcmdflag' 590rv [i ++ ]= shell_xescape_xquote (cmd );// Copy (and escape) `cmd`. 591 } 592 593rv [i ]= NULL ; 594 595assert (rv [0 ]); 596 597return rv ; 598} 599 600/// Releases the memory allocated by `shell_build_argv`. 601/// 602/// @param argv The argument vector. 603void shell_free_argv (char ** argv ) 604{ 605char ** p = argv ; 606if (p == NULL ) { 607// Nothing was allocated, return 608return ; 609 } 610while (* p != NULL ) { 611// Free each argument 612xfree (* p ); 613p ++ ; 614 } 615xfree (argv ); 616} 617 618/// Joins shell arguments from `argv` into a new string. 619/// If the result is too long it is truncated with ellipsis ("..."). 620/// 621/// @returns[allocated] `argv` joined to a string. 622char * shell_argv_to_str (char ** const argv ) 623FUNC_ATTR_NONNULL_ALL 624{ 625size_t n = 0 ; 626char ** p = argv ; 627char * rv = xcalloc (256 ,sizeof (* rv )); 628const size_t maxsize = (256 * sizeof (* rv )); 629if (* p == NULL ) { 630return rv ; 631 } 632while (* p != NULL ) { 633xstrlcat (rv ,"'" ,maxsize ); 634xstrlcat (rv ,* p ,maxsize ); 635n = xstrlcat (rv ,"' " ,maxsize ); 636if (n >=maxsize ) { 637break ; 638 } 639p ++ ; 640 } 641if (n < maxsize ) { 642rv [n - 1 ]= NUL ; 643 }else { 644// Command too long, show ellipsis: "/bin/bash 'foo' 'bar'..." 645rv [maxsize - 4 ]= '.' ; 646rv [maxsize - 3 ]= '.' ; 647rv [maxsize - 2 ]= '.' ; 648rv [maxsize - 1 ]= NUL ; 649 } 650return rv ; 651} 652 653/// Calls the user-configured 'shell' (p_sh) for running a command or wildcard 654/// expansion. 655/// 656/// @param cmd The command to execute, or NULL to run an interactive shell. 657/// @param opts Options that control how the shell will work. 658/// @param extra_args Extra arguments to the shell, or NULL. 659/// 660/// @return shell command exit code 661int os_call_shell (char * cmd ,int opts ,char * extra_args ) 662{ 663StringBuilder input = KV_INITIAL_VALUE ; 664char * output = NULL ; 665char ** output_ptr = NULL ; 666int current_state = State ; 667bool forward_output = true; 668 669// While the child is running, ignore terminating signals 670signal_reject_deadly (); 671 672if (opts & (kShellOptHideMess |kShellOptExpand )) { 673forward_output = false; 674 }else { 675State = MODE_EXTERNCMD ; 676 677if (opts & kShellOptWrite ) { 678read_input (& input ); 679 } 680 681if (opts & kShellOptRead ) { 682output_ptr = & output ; 683forward_output = false; 684 }else if (opts & kShellOptDoOut ) { 685// Caller has already redirected output 686forward_output = false; 687 } 688 } 689 690size_t nread ; 691int exitcode = do_os_system (shell_build_argv (cmd ,extra_args ), 692input .items ,input .size ,output_ptr ,& nread , 693emsg_silent ,forward_output ); 694kv_destroy (input ); 695 696if (output ) { 697write_output (output ,nread , true); 698xfree (output ); 699 } 700 701if (!emsg_silent && exitcode != 0 && !(opts & kShellOptSilent )) { 702msg_ext_set_kind ("shell_ret" ); 703msg_ext_no_fast (); 704if (!ui_has (kUIMessages )) { 705msg_putchar ('\n' ); 706 } 707msg_puts (_ ("shell returned " )); 708msg_outnum (exitcode ); 709 } 710 711State = current_state ; 712signal_accept_deadly (); 713 714return exitcode ; 715} 716 717/// os_call_shell() wrapper. Handles 'verbose', :profile, and v:shell_error. 718/// Invalidates cached tags. 719/// 720/// @param opts a combination of ShellOpts flags 721/// 722/// @return shell command exit code 723int call_shell (char * cmd ,int opts ,char * extra_shell_arg ) 724{ 725int retval ; 726proftime_T wait_time ; 727 728if (p_verbose > 3 ) { 729verbose_enter (); 730smsg (0 ,_ ("Executing command: \"%s\"" ),cmd == NULL ?p_sh :cmd ); 731if (!ui_has (kUIMessages )) { 732msg_putchar ('\n' ); 733 } 734verbose_leave (); 735 } 736 737if (do_profiling == PROF_YES ) { 738prof_child_enter (& wait_time ); 739 } 740 741if (* p_sh == NUL ) { 742emsg (_ (e_shellempty )); 743retval = -1 ; 744 }else { 745// The external command may update a tags file, clear cached tags. 746tag_freematch (); 747 748retval = os_call_shell (cmd ,opts ,extra_shell_arg ); 749 } 750 751set_vim_var_nr (VV_SHELL_ERROR , (varnumber_T )retval ); 752if (do_profiling == PROF_YES ) { 753prof_child_exit (& wait_time ); 754 } 755 756return retval ; 757} 758 759/// Get the stdout of an external command. 760/// If "ret_len" is NULL replace NUL characters with NL. When "ret_len" is not 761/// NULL store the length there. 762/// 763/// @param cmd command to execute 764/// @param infile optional input file name 765/// @param flags can be kShellOptSilent or 0 766/// @param ret_len length of the stdout 767/// 768/// @return an allocated string, or NULL for error. 769char * get_cmd_output (char * cmd ,char * infile ,int flags ,size_t * ret_len ) 770{ 771char * buffer = NULL ; 772 773if (check_secure ()) { 774return NULL ; 775 } 776 777// get a name for the temp file 778char * tempname = vim_tempname (); 779if (tempname == NULL ) { 780emsg (_ (e_notmp )); 781return NULL ; 782 } 783 784// Add the redirection stuff 785char * command = make_filter_cmd (cmd ,infile ,tempname , false); 786 787// Call the shell to execute the command (errors are ignored). 788// Don't check timestamps here. 789no_check_timestamps ++ ; 790call_shell (command ,kShellOptDoOut |kShellOptExpand |flags ,NULL ); 791no_check_timestamps -- ; 792 793xfree (command ); 794 795// read the names from the file into memory 796FILE * fd = os_fopen (tempname ,READBIN ); 797 798// Not being able to seek means we can't read the file. 799long len_l ; 800if (fd == NULL 801|| fseek (fd ,0L ,SEEK_END )== -1 802|| (len_l = ftell (fd ))== -1 // get size of temp file 803|| fseek (fd ,0L ,SEEK_SET )== -1 ) {// back to the start 804semsg (_ (e_cannot_read_from_str_2 ),tempname ); 805if (fd != NULL ) { 806fclose (fd ); 807 } 808 gotodone ; 809 } 810 811size_t len = (size_t )len_l ; 812buffer = xmalloc (len + 1 ); 813size_t i = fread (buffer ,1 ,len ,fd ); 814fclose (fd ); 815if (i != len ) { 816semsg (_ (e_cant_read_file_str ),tempname ); 817XFREE_CLEAR (buffer ); 818 }else if (ret_len == NULL ) { 819// Change NUL into SOH, otherwise the string is truncated. 820for (i = 0 ;i < len ;i ++ ) { 821if (buffer [i ]== NUL ) { 822buffer [i ]= 1 ; 823 } 824 } 825 826buffer [len ]= NUL ;// make sure the buffer is terminated 827 }else { 828* ret_len = len ; 829 } 830 831done : 832os_remove (tempname ); 833xfree (tempname ); 834return buffer ; 835} 836/// os_system - synchronously execute a command in the shell 837/// 838/// example: 839/// char *output = NULL; 840/// size_t nread = 0; 841/// char *argv[] = {"ls", "-la", NULL}; 842/// int exitcode = os_system(argv, NULL, 0, &output, &nread); 843/// 844/// @param argv The commandline arguments to be passed to the shell. `argv` 845/// will be consumed. 846/// @param input The input to the shell (NULL for no input), passed to the 847/// stdin of the resulting process. 848/// @param len The length of the input buffer (not used if `input` == NULL) 849/// @param[out] output Pointer to a location where the output will be 850/// allocated and stored. Will point to NULL if the shell 851/// command did not output anything. If NULL is passed, 852/// the shell output will be ignored. 853/// @param[out] nread the number of bytes in the returned buffer (if the 854/// returned buffer is not NULL) 855/// @return the return code of the process, -1 if the process couldn't be 856/// started properly 857int os_system (char ** argv ,const char * input ,size_t len ,char ** output , 858size_t * nread )FUNC_ATTR_NONNULL_ARG (1 ) 859{ 860return do_os_system (argv ,input ,len ,output ,nread , true, false); 861} 862 863static int do_os_system (char ** argv ,const char * input ,size_t len ,char ** output ,size_t * nread , 864bool silent ,bool forward_output ) 865{ 866int exitcode = -1 ; 867 868#ifdef MSWIN 869// do not execute anything from the current directory by setting the 870// environment variable $NoDefaultCurrentDirectoryInExePath 871char * oldval = os_getenv ("NoDefaultCurrentDirectoryInExePath" ); 872os_setenv ("NoDefaultCurrentDirectoryInExePath" ,"1" , true); 873 874UINT old_output_cp = GetConsoleOutputCP (); 875UINT old_input_cp = GetConsoleCP (); 876// Force console codepage to UTF-8 before spawning child process. #33480 877SetConsoleOutputCP (CP_UTF8 ); 878SetConsoleCP (CP_UTF8 ); 879#endif 880 881out_data_decide_throttle (0 );// Initialize throttle decider. 882out_data_ring (NULL ,0 );// Initialize output ring-buffer. 883bool has_input = (input != NULL && len > 0 ); 884 885// the output buffer 886StringBuilder buf = KV_INITIAL_VALUE ; 887stream_read_cb data_cb = system_data_cb ; 888if (nread ) { 889* nread = 0 ; 890 } 891 892if (forward_output ) { 893data_cb = out_data_cb ; 894 }else if (!output ) { 895data_cb = NULL ; 896 } 897 898// Copy the program name in case we need to report an error. 899char prog [MAXPATHL ]; 900xstrlcpy (prog ,argv [0 ],MAXPATHL ); 901 902LibuvProc uvproc = libuv_proc_init (& main_loop ,& buf ); 903Proc * proc = & uvproc .proc ; 904MultiQueue * events = multiqueue_new_child (main_loop .events ); 905proc -> events = events ; 906proc -> argv = argv ; 907int status = proc_spawn (proc ,has_input , true, true); 908if (status ) { 909loop_poll_events (& main_loop ,0 ); 910// Failed, probably 'shell' is not executable. 911if (!silent ) { 912msg_puts (_ ("\nshell failed to start: " )); 913msg_outtrans (os_strerror (status ),0 , false); 914msg_puts (": " ); 915msg_outtrans (prog ,0 , false); 916msg_putchar ('\n' ); 917 } 918 gotoend ; 919 } 920 921// Note: unlike process events, stream events are not queued, as we want to 922// deal with stream events as fast a possible. It prevents closing the 923// streams while there's still data in the OS buffer (due to the process 924// exiting before all data is read). 925if (has_input ) { 926wstream_init (& proc -> in ,0 ); 927 } 928rstream_init (& proc -> out ); 929rstream_start (& proc -> out ,data_cb ,& buf ); 930rstream_init (& proc -> err ); 931rstream_start (& proc -> err ,data_cb ,& buf ); 932 933// write the input, if any 934if (has_input ) { 935WBuffer * input_buffer = wstream_new_buffer ((char * )input ,len ,1 ,NULL ); 936 937if (wstream_write (& proc -> in ,input_buffer )!= 0 ) { 938// couldn't write, stop the process and tell the user about it 939proc_stop (proc ); 940 gotoend ; 941 } 942// close the input stream after everything is written 943wstream_set_write_cb (& proc -> in ,shell_write_cb ,NULL ); 944 } 945 946// Invoke busy_start here so LOOP_PROCESS_EVENTS_UNTIL will not change the 947// busy state. 948ui_busy_start (); 949ui_flush (); 950if (forward_output ) { 951msg_sb_eol (); 952msg_start (); 953msg_no_more = true; 954lines_left = -1 ; 955 } 956exitcode = proc_wait (proc ,-1 ,NULL ); 957if (!got_int && out_data_decide_throttle (0 )) { 958// Last chunk of output was skipped; display it now. 959out_data_ring (NULL ,SIZE_MAX ); 960 } 961if (forward_output ) { 962// caller should decide if wait_return() is invoked 963no_wait_return ++ ; 964msg_end (); 965no_wait_return -- ; 966msg_no_more = false; 967 } 968 969ui_busy_stop (); 970 971// prepare the out parameters if requested 972if (output ) { 973assert (nread ); 974if (buf .size == 0 ) { 975// no data received from the process, return NULL 976* output = NULL ; 977* nread = 0 ; 978kv_destroy (buf ); 979 }else { 980* nread = buf .size ; 981// NUL-terminate to make the output directly usable as a C string 982kv_push (buf ,NUL ); 983* output = buf .items ; 984 } 985 } 986 987assert (multiqueue_empty (events )); 988end : 989multiqueue_free (events ); 990 991#ifdef MSWIN 992// Restore original value of NoDefaultCurrentDirectoryInExePath 993restore_env_var ("NoDefaultCurrentDirectoryInExePath" ,oldval , true); 994SetConsoleOutputCP (old_output_cp ); 995SetConsoleCP (old_input_cp ); 996#endif 997 998return exitcode ; 999} 1000 1001static size_t system_data_cb (RStream * stream ,const char * buf ,size_t count ,void * data ,bool eof ) 1002{ 1003StringBuilder * dbuf = data ; 1004kv_concat_len (* dbuf ,buf ,count ); 1005return count ; 1006} 1007 1008/// Tracks output received for the current executing shell command, and displays 1009/// a pulsing "..." when output should be skipped. Tracking depends on the 1010/// synchronous/blocking nature of ":!". 1011/// 1012/// Purpose: 1013/// 1. CTRL-C is more responsive. #1234 #5396 1014/// 2. Improves performance of :! (UI, esp. TUI, is the bottleneck). 1015/// 3. Avoids OOM during long-running, spammy :!. 1016/// 1017/// Vim does not need this hack because: 1018/// 1. :! in terminal-Vim runs in cooked mode, so CTRL-C is caught by the 1019/// terminal and raises SIGINT out-of-band. 1020/// 2. :! in terminal-Vim uses a tty (Nvim uses pipes), so commands 1021/// (e.g. `git grep`) may page themselves. 1022/// 1023/// @param size Length of data, used with internal state to decide whether 1024/// output should be skipped. size=0 resets the internal state and 1025/// returns the previous decision. 1026/// 1027/// @returns true if output should be skipped and pulse was displayed. 1028/// Returns the previous decision if size=0. 1029static bool out_data_decide_throttle (size_t size ) 1030{ 1031static uint64_t started = 0 ;// Start time of the current throttle. 1032static size_t received = 0 ;// Bytes observed since last throttle. 1033static size_t visit = 0 ;// "Pulse" count of the current throttle. 1034static char pulse_msg []= {' ' ,' ' ,' ' ,NUL }; 1035 1036if (!size ) { 1037bool previous_decision = (visit > 0 ); 1038started = received = visit = 0 ; 1039return previous_decision ; 1040 } 1041 1042received += size ; 1043if (received < OUT_DATA_THRESHOLD 1044// Display at least the first chunk of output even if it is big. 1045|| (!started && received < size + 1000 )) { 1046return false; 1047 }else if (!visit ) { 1048started = os_hrtime (); 1049 }else { 1050uint64_t since = os_hrtime ()- started ; 1051if (since < (visit * (NS_PER_SEC /10 ))) { 1052return true; 1053 } 1054if (since > (3 * NS_PER_SEC )) { 1055received = visit = 0 ; 1056return false; 1057 } 1058 } 1059 1060visit ++ ; 1061// Pulse "..." at the bottom of the screen. 1062size_t tick = visit %4 ; 1063pulse_msg [0 ]= (tick > 0 ) ?'.' :' ' ; 1064pulse_msg [1 ]= (tick > 1 ) ?'.' :' ' ; 1065pulse_msg [2 ]= (tick > 2 ) ?'.' :' ' ; 1066if (visit == 1 ) { 1067msg_puts ("...\n" ); 1068 } 1069msg_putchar ('\r' );// put cursor at start of line 1070msg_puts (pulse_msg ); 1071msg_putchar ('\r' ); 1072ui_flush (); 1073return true; 1074} 1075 1076/// Saves output in a quasi-ringbuffer. Used to ensure the last ~page of 1077/// output for a shell-command is always displayed. 1078/// 1079/// Init mode: Resets the internal state. 1080/// output = NULL 1081/// size = 0 1082/// Print mode: Displays the current saved data. 1083/// output = NULL 1084/// size = SIZE_MAX 1085/// 1086/// @param output Data to save, or NULL to invoke a special mode. 1087/// @param size Length of `output`. 1088static void out_data_ring (const char * output ,size_t size ) 1089{ 1090#define MAX_CHUNK_SIZE (OUT_DATA_THRESHOLD / 2) 1091static char last_skipped [MAX_CHUNK_SIZE ];// Saved output. 1092static size_t last_skipped_len = 0 ; 1093 1094assert (output != NULL || (size == 0 || size == SIZE_MAX )); 1095 1096if (output == NULL && size == 0 ) {// Init mode 1097last_skipped_len = 0 ; 1098return ; 1099 } 1100 1101if (output == NULL && size == SIZE_MAX ) {// Print mode 1102out_data_append_to_screen (last_skipped ,& last_skipped_len ,STDOUT_FILENO , true); 1103return ; 1104 } 1105 1106// This is basically a ring-buffer... 1107if (size >=MAX_CHUNK_SIZE ) {// Save mode 1108size_t start = size - MAX_CHUNK_SIZE ; 1109memcpy (last_skipped ,output + start ,MAX_CHUNK_SIZE ); 1110last_skipped_len = MAX_CHUNK_SIZE ; 1111 }else if (size > 0 ) { 1112// Length of the old data that can be kept. 1113size_t keep_len = MIN (last_skipped_len ,MAX_CHUNK_SIZE - size ); 1114size_t keep_start = last_skipped_len - keep_len ; 1115// Shift the kept part of the old data to the start. 1116if (keep_start ) { 1117memmove (last_skipped ,last_skipped + keep_start ,keep_len ); 1118 } 1119// Copy the entire new data to the remaining space. 1120memcpy (last_skipped + keep_len ,output ,size ); 1121last_skipped_len = keep_len + size ; 1122 } 1123} 1124 1125static void out_data_event (void ** argv ) 1126{ 1127bool need_clear = true; 1128int hl = (int )(intptr_t )argv [2 ]== STDERR_FILENO ?HLF_SE :HLF_SO ; 1129msg_ext_set_kind ((int )(intptr_t )argv [2 ]== STDERR_FILENO ?"shell_err" :"shell_out" ); 1130msg_ext_set_append (true); 1131msg_ext_no_fast (); 1132msg_multiline (cbuf_as_string ((char * )argv [0 ], (size_t )argv [1 ]),hl , false, false,& need_clear ); 1133xfree (argv [0 ]); 1134ui_flush (); 1135} 1136 1137/// Continue to append data to last screen line. 1138/// 1139/// @param output Data to append to screen lines. 1140/// @param count Size of data. 1141/// @param eof If true, there will be no more data output. 1142static void out_data_append_to_screen (const char * output ,size_t * count ,int fd ,bool eof ) 1143FUNC_ATTR_NONNULL_ALL 1144{ 1145const char * p = output ; 1146const char * end = output + * count ; 1147// Note: this is not 100% precise: 1148// 1. we don't check if received continuation bytes are already invalid 1149// and we thus do some buffering that could be avoided 1150// 2. we don't compose chars over buffer boundaries, even if we see an 1151// incomplete UTF-8 sequence that could be composing with the last 1152// complete sequence. 1153// This will be corrected when we switch to vterm based implementation 1154while (p < end ) { 1155int i = * p ?utfc_ptr2len_len (p , (int )* count - (int )(p - output )) :1 ; 1156if (!eof && i == 1 && utf8len_tab_zero [* (uint8_t * )p ]> (end - p )) { 1157* count = (size_t )(p - output ); 1158break ; 1159 } 1160p += i ; 1161 } 1162// Process after uv_run() to avoid recursion in vim.ui_attach() msg_show callback #38664. 1163char * str = xmemdupz (output ,* count ); 1164if (ui_has (kUIMessages )) { 1165multiqueue_put (main_loop .fast_events ,out_data_event , 1166 (void * )str , (void * )* count , (void * )(intptr_t )fd ); 1167 }else { 1168out_data_event ((void * []){ (void * )str , (void * )* count , (void * )(intptr_t )fd }); 1169 } 1170} 1171 1172static size_t out_data_cb (RStream * stream ,const char * ptr ,size_t count ,void * data ,bool eof ) 1173{ 1174if (count > 0 && out_data_decide_throttle (count )) {// Skip output above a threshold. 1175// Save the skipped output. If it is the final chunk, we display it later. 1176out_data_ring (ptr ,count ); 1177 }else if (count > 0 ) { 1178out_data_append_to_screen (ptr ,& count ,stream -> s .fd ,eof ); 1179 } 1180 1181return count ; 1182} 1183 1184/// Parses a command string into a sequence of words, taking quotes into 1185/// consideration. 1186/// 1187/// @param str The command string to be parsed 1188/// @param argv The vector that will be filled with copies of the parsed 1189/// words. It can be NULL if the caller only needs to count words. 1190/// @return The number of words parsed. 1191static size_t tokenize (const char * const str ,char ** const argv ) 1192FUNC_ATTR_NONNULL_ARG (1 ) 1193{ 1194size_t argc = 0 ; 1195const char * p = str ; 1196 1197while (* p != NUL ) { 1198const size_t len = word_length (p ); 1199 1200if (argv != NULL ) { 1201// Fill the slot 1202argv [argc ]= vim_strnsave_unquoted (p ,len ); 1203 } 1204 1205argc ++ ; 1206p = skipwhite ((p + len )); 1207 } 1208 1209return argc ; 1210} 1211 1212/// Calculates the length of a shell word. 1213/// 1214/// @param str A pointer to the first character of the word 1215/// @return The offset from `str` at which the word ends. 1216static size_t word_length (const char * str ) 1217{ 1218const char * p = str ; 1219bool inquote = false; 1220size_t length = 0 ; 1221 1222// Move `p` to the end of shell word by advancing the pointer while it's 1223// inside a quote or it's a non-whitespace character 1224while (* p && (inquote || (* p != ' ' && * p != TAB ))) { 1225if (* p == '"' ) { 1226// Found a quote character, switch the `inquote` flag 1227inquote = !inquote ; 1228 }else if (* p == '\\' && inquote ) { 1229p ++ ; 1230length ++ ; 1231 } 1232 1233p ++ ; 1234length ++ ; 1235 } 1236 1237return length ; 1238} 1239 1240/// To remain compatible with the old implementation (which forked a process 1241/// for writing) the entire text is copied to a temporary buffer before the 1242/// event loop starts. If we don't (by writing in chunks returned by `ml_get`) 1243/// the buffer being modified might get modified by reading from the process 1244/// before we finish writing. 1245static void read_input (StringBuilder * buf ) 1246{ 1247read_buffer_into (curbuf ,curbuf -> b_op_start .lnum ,curbuf -> b_op_end .lnum ,buf ); 1248} 1249 1250static size_t write_output (char * output ,size_t remaining ,bool eof ) 1251{ 1252if (!output ) { 1253return 0 ; 1254 } 1255 1256char * start = output ; 1257size_t off = 0 ; 1258while (off < remaining ) { 1259// CRLF 1260// special case: for binary mode, don't remove CR. 1261if (output [off ]== CAR && output [off + 1 ]== NL && !curbuf -> b_p_bin ) { 1262output [off ]= NUL ; 1263ml_append (curwin -> w_cursor .lnum ++ ,output , (int )off + 1 , false); 1264size_t skip = off + 2 ; 1265output += skip ; 1266remaining -= skip ; 1267off = 0 ; 1268continue ; 1269 }else if ((output [off ]== CAR && !curbuf -> b_p_bin )|| output [off ]== NL ) { 1270// Insert the line 1271output [off ]= NUL ; 1272ml_append (curwin -> w_cursor .lnum ++ ,output , (int )off + 1 , false); 1273size_t skip = off + 1 ; 1274output += skip ; 1275remaining -= skip ; 1276off = 0 ; 1277continue ; 1278 } 1279 1280if (output [off ]== NUL ) { 1281// Translate NUL to NL 1282output [off ]= NL ; 1283 } 1284off ++ ; 1285 } 1286 1287if (eof ) { 1288if (remaining ) { 1289// append unfinished line 1290ml_append (curwin -> w_cursor .lnum ++ ,output ,0 , false); 1291// remember that the line ending was missing 1292curbuf -> b_no_eol_lnum = curwin -> w_cursor .lnum ; 1293output += remaining ; 1294 }else { 1295curbuf -> b_no_eol_lnum = 0 ; 1296 } 1297 } 1298 1299ui_flush (); 1300 1301return (size_t )(output - start ); 1302} 1303 1304static void shell_write_cb (Stream * stream ,void * data ,int status ) 1305{ 1306if (status ) { 1307// Can happen if system() tries to send input to a shell command that was 1308// backgrounded (:call system("cat - &", "foo")). #3529 #5241 1309msg_schedule_semsg (_ ("E5677: Error writing input to shell-command: %s" ), 1310uv_err_name (status )); 1311 } 1312stream_may_close (stream ); 1313} 1314 1315/// Applies 'shellxescape' (p_sxe) and 'shellxquote' (p_sxq) to a command. 1316/// 1317/// @param cmd Command string 1318/// @return Escaped/quoted command string (allocated). 1319static char * shell_xescape_xquote (const char * cmd ) 1320FUNC_ATTR_NONNULL_ALL FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT 1321{ 1322if (* p_sxq == NUL ) { 1323return xstrdup (cmd ); 1324 } 1325 1326const char * ecmd = cmd ; 1327if (* p_sxe != NUL && strcmp (p_sxq ,"(" )== 0 ) { 1328ecmd = vim_strsave_escaped_ext (cmd ,p_sxe ,'^' , false); 1329 } 1330size_t ncmd_size = strlen (ecmd )+ strlen (p_sxq )* 2 + 1 ; 1331char * ncmd = xmalloc (ncmd_size ); 1332 1333// When 'shellxquote' is ( append ). 1334// When 'shellxquote' is "( append )". 1335if (strcmp (p_sxq ,"(" )== 0 ) { 1336vim_snprintf (ncmd ,ncmd_size ,"(%s)" ,ecmd ); 1337 }else if (strcmp (p_sxq ,"\"(" )== 0 ) { 1338vim_snprintf (ncmd ,ncmd_size ,"\"(%s)\"" ,ecmd ); 1339 }else { 1340vim_snprintf (ncmd ,ncmd_size ,"%s%s%s" ,p_sxq ,ecmd ,p_sxq ); 1341 } 1342 1343if (ecmd != cmd ) { 1344xfree ((void * )ecmd ); 1345 } 1346 1347return ncmd ; 1348}