robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
27e36dea19
master
1// eval/fs.c: Filesystem related builtin functions 2 3#include <assert.h> 4#include <limits.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdint.h> 8#include <stdio.h> 9#include <stdlib.h> 10#include <string.h> 11#include <sys/stat.h> 12 13#include "auto/config.h" 14#include "nvim/api/private/helpers.h" 15#include "nvim/ascii_defs.h" 16#include "nvim/buffer_defs.h" 17#include "nvim/cmdexpand.h" 18#include "nvim/cmdexpand_defs.h" 19#include "nvim/errors.h" 20#include "nvim/eval.h" 21#include "nvim/eval/fs.h" 22#include "nvim/eval/typval.h" 23#include "nvim/eval/userfunc.h" 24#include "nvim/eval/vars.h" 25#include "nvim/eval/window.h" 26#include "nvim/ex_cmds.h" 27#include "nvim/ex_docmd.h" 28#include "nvim/file_search.h" 29#include "nvim/fileio.h" 30#include "nvim/garray.h" 31#include "nvim/garray_defs.h" 32#include "nvim/gettext_defs.h" 33#include "nvim/globals.h" 34#include "nvim/macros_defs.h" 35#include "nvim/mbyte.h" 36#include "nvim/memory.h" 37#include "nvim/message.h" 38#include "nvim/option_vars.h" 39#include "nvim/os/fileio.h" 40#include "nvim/os/fileio_defs.h" 41#include "nvim/os/fs.h" 42#include "nvim/os/fs_defs.h" 43#include "nvim/os/os.h" 44#include "nvim/path.h" 45#include "nvim/pos_defs.h" 46#include "nvim/runtime.h" 47#include "nvim/strings.h" 48#include "nvim/types_defs.h" 49#include "nvim/vim_defs.h" 50#include "nvim/window.h" 51 52#include "eval/fs.c.generated.h" 53 54static const char e_error_while_writing_str []= N_ ("E80: Error while writing: %s" ); 55 56/// Adjust a filename, according to a string of modifiers. 57/// *fnamep must be NUL terminated when called. When returning, the length is 58/// determined by *fnamelen. 59/// Returns VALID_ flags or -1 for failure. 60/// When there is an error, *fnamep is set to NULL. 61/// 62/// @param src string with modifiers 63/// @param tilde_file "~" is a file name, not $HOME 64/// @param usedlen characters after src that are used 65/// @param fnamep file name so far 66/// @param bufp buffer for allocated file name or NULL 67/// @param fnamelen length of fnamep 68/// @param use_shellslash adjust separators in `*fnamep` according to 'shellslash' 69int modify_fname (char * src ,bool tilde_file ,size_t * usedlen ,char ** fnamep ,char ** bufp , 70size_t * fnamelen ,bool use_shellslash ) 71{ 72int valid = 0 ; 73char * s ,* p ,* pbuf ; 74char dirname [MAXPATHL ]; 75bool has_fullname = false; 76bool has_homerelative = false; 77bool didit = false; 78 79repeat : 80// ":p" - full path/file_name 81if (src [* usedlen ]== ':' && src [* usedlen + 1 ]== 'p' ) { 82has_fullname = true; 83 84valid |=VALID_PATH ; 85* usedlen += 2 ; 86 87// Expand "~/path" for all systems and "~user/path" for Unix 88if ((* fnamep )[0 ]== '~' 89#ifndef UNIX 90&& ((* fnamep )[1 ]== '/' 91# ifdef BACKSLASH_IN_FILENAME 92|| (* fnamep )[1 ]== '\\' 93# endif 94|| (* fnamep )[1 ]== NUL ) 95#endif 96&& !(tilde_file && (* fnamep )[1 ]== NUL )) { 97* fnamep = expand_env_save (* fnamep ); 98xfree (* bufp );// free any allocated file name 99* bufp = * fnamep ; 100if (* fnamep == NULL ) { 101return -1 ; 102 } 103 } 104 105// When "/." or "/.." is used: force expansion to get rid of it. 106for (p = * fnamep ;* p != NUL ;MB_PTR_ADV (p )) { 107if (vim_ispathsep (* p ) 108&& p [1 ]== '.' 109&& (p [2 ]== NUL 110|| vim_ispathsep (p [2 ]) 111|| (p [2 ]== '.' 112&& (p [3 ]== NUL || vim_ispathsep (p [3 ]))))) { 113break ; 114 } 115 } 116 117// FullName_save() is slow, don't use it when not needed. 118if (* p != NUL || !vim_isAbsName (* fnamep ) 119#ifdef MSWIN // enforce drive letter on Windows paths 120|| ** fnamep == '/' || ** fnamep == '\\' 121#endif 122 ) { 123* fnamep = FullName_save (* fnamep ,* p != NUL ); 124xfree (* bufp );// free any allocated file name 125* bufp = * fnamep ; 126if (* fnamep == NULL ) { 127return -1 ; 128 } 129 } 130 131// Append a path separator to a directory. 132if (os_isdir (* fnamep )) { 133// Make room for one or two extra characters. 134* fnamep = xstrnsave (* fnamep ,strlen (* fnamep )+ 2 ); 135xfree (* bufp );// free any allocated file name 136* bufp = * fnamep ; 137add_pathsep (* fnamep ); 138 } 139 } 140 141int c ; 142 143// ":." - path relative to the current directory 144// ":~" - path relative to the home directory 145// ":8" - shortname path - postponed till after 146while (src [* usedlen ]== ':' 147&& ((c = (uint8_t )src [* usedlen + 1 ])== '.' || c == '~' || c == '8' )) { 148* usedlen += 2 ; 149if (c == '8' ) { 150continue ; 151 } 152pbuf = NULL ; 153// Need full path first (use expand_env() to remove a "~/") 154if (!has_fullname && !has_homerelative ) { 155if (** fnamep == '~' ) { 156p = pbuf = expand_env_save (* fnamep ); 157 }else { 158p = pbuf = FullName_save (* fnamep , false); 159 } 160 }else { 161p = * fnamep ; 162 } 163 164has_fullname = false; 165 166if (p != NULL ) { 167size_t dirnamelen = 0 ; 168 169if (c == '.' ) { 170os_dirname (dirname ,MAXPATHL ); 171if (has_homerelative ) { 172s = xstrdup (dirname ); 173dirnamelen = home_replace (NULL ,s ,dirname ,MAXPATHL , true); 174xfree (s ); 175 } 176 177if (dirnamelen == 0 ) { 178dirnamelen = strlen (dirname ); 179 } 180 181// Do not call shorten_fname() here since it removes the prefix 182// even though the path does not have a prefix. 183if (path_cmp (p_fic ,p ,dirname ,dirnamelen )== 0 ) { 184p += dirnamelen ; 185if (vim_ispathsep (* p )) { 186while (* p && vim_ispathsep (* p )) { 187p ++ ; 188 } 189* fnamep = p ; 190if (pbuf != NULL ) { 191// free any allocated file name 192xfree (* bufp ); 193* bufp = pbuf ; 194pbuf = NULL ; 195 } 196 } 197 } 198 }else { 199dirnamelen = home_replace (NULL ,p ,dirname ,MAXPATHL , true); 200// Only replace it when it starts with '~' 201if (* dirname == '~' ) { 202s = xmemdupz (dirname ,dirnamelen ); 203assert (s != NULL );// suppress clang "Argument with 'nonnull' attribute passed null" 204* fnamep = s ; 205xfree (* bufp ); 206* bufp = s ; 207has_homerelative = true; 208 } 209 } 210xfree (pbuf ); 211 } 212 } 213 214FileInfo file_info ; 215os_fileinfo2 (* fnamep ,& file_info ); 216if (src [* usedlen ]== ':' && src [* usedlen + 1 ]== 'h' ) { 217s = * fnamep + file_info .rest_off ; 218* fnamep = * fnamep + file_info .prefix_off ; 219 } 220 221char * tail = path_tail (* fnamep ); 222* fnamelen = strlen (* fnamep ); 223 224// ":h" - head, remove "/file_name", can be repeated 225// Don't remove the logical root, see `FileInfo`. 226while (src [* usedlen ]== ':' && src [* usedlen + 1 ]== 'h' ) { 227valid |=VALID_HEAD ; 228* usedlen += 2 ; 229while (tail > s && after_pathsep (s ,tail )) { 230MB_PTR_BACK (* fnamep ,tail ); 231 } 232* fnamelen = tail <=s ? (size_t )(s - * fnamep ) : (size_t )(tail - * fnamep ); 233if (* fnamelen == 0 ) { 234// Result is empty. Turn it into "." to make ":cd %:h" work. 235xfree (* bufp ); 236* bufp = * fnamep = tail = xstrdup ("." ); 237s = * fnamep ;// s pointed into the freed buffer. 238* fnamelen = 1 ; 239 }else { 240while (tail > s && !after_pathsep (s ,tail )) { 241MB_PTR_BACK (* fnamep ,tail ); 242 } 243 } 244 } 245 246// ":8" - shortname 247if (src [* usedlen ]== ':' && src [* usedlen + 1 ]== '8' ) { 248* usedlen += 2 ; 249 } 250 251// ":t" - tail, just the basename 252if (src [* usedlen ]== ':' && src [* usedlen + 1 ]== 't' ) { 253* usedlen += 2 ; 254* fnamelen -= (size_t )(tail - * fnamep ); 255* fnamep = tail ; 256 } 257 258// ":e" - extension, can be repeated 259// ":r" - root, without extension, can be repeated 260while (src [* usedlen ]== ':' 261&& (src [* usedlen + 1 ]== 'e' || src [* usedlen + 1 ]== 'r' )) { 262// find a '.' in the tail: 263// - for second :e: before the current fname 264// - otherwise: The last '.' 265const bool is_second_e = * fnamep > tail ; 266if (src [* usedlen + 1 ]== 'e' && is_second_e ) { 267s = (* fnamep )- 2 ; 268 }else { 269s = (* fnamep )+ * fnamelen - 1 ; 270 } 271 272for (;s > tail ;s -- ) { 273if (s [0 ]== '.' ) { 274break ; 275 } 276 } 277if (src [* usedlen + 1 ]== 'e' ) { 278if (s > tail || (0 && is_second_e && s == tail )) { 279// we stopped at a '.' (so anchor to &'.' + 1) 280char * newstart = s + 1 ; 281size_t distance_stepped_back = (size_t )(* fnamep - newstart ); 282* fnamelen += distance_stepped_back ; 283* fnamep = newstart ; 284 }else if (* fnamep <=tail ) { 285* fnamelen = 0 ; 286 } 287 }else { 288// :r - Remove one extension 289// 290// Ensure that `s` doesn't go before `*fnamep`, 291// since then we're taking too many roots: 292// 293// "path/to/this.file.ext" :e:e:r:r 294// ^ ^-------- *fnamep 295// +------------- tail 296// 297// Also ensure `s` doesn't go before `tail`, 298// since then we're taking too many roots again: 299// 300// "path/to/this.file.ext" :r:r:r 301// ^ ^------------- tail 302// +--------------------- *fnamep 303if (s > MAX (tail ,* fnamep )) { 304* fnamelen = (size_t )(s - * fnamep ); 305 } 306 } 307* usedlen += 2 ; 308 } 309 310#ifdef BACKSLASH_IN_FILENAME 311if (!didit && use_shellslash && * fnamep != NULL ) { 312* fnamep = xstrdup (* fnamep ); 313slash_adjust (* fnamep ); 314xfree (* bufp ); 315* bufp = * fnamep ; 316 } 317#endif 318 319// ":s?pat?foo?" - substitute 320// ":gs?pat?foo?" - global substitute 321if (src [* usedlen ]== ':' 322&& (src [* usedlen + 1 ]== 's' 323|| (src [* usedlen + 1 ]== 'g' && src [* usedlen + 2 ]== 's' ))) { 324char * flags = "" ; 325s = src + * usedlen + 2 ; 326if (src [* usedlen + 1 ]== 'g' ) { 327flags = "g" ; 328s ++ ; 329 } 330 331int sep = (uint8_t )(* s ++ ); 332if (sep ) { 333// find end of pattern 334p = vim_strchr (s ,sep ); 335if (p != NULL ) { 336char * const pat = xmemdupz (s , (size_t )(p - s )); 337s = p + 1 ; 338// find end of substitution 339p = vim_strchr (s ,sep ); 340if (p != NULL ) { 341char * const sub = xmemdupz (s , (size_t )(p - s )); 342char * const str = xmemdupz (* fnamep ,* fnamelen ); 343* usedlen = (size_t )(p + 1 - src ); 344size_t slen ; 345s = do_string_sub (str ,* fnamelen ,pat ,sub ,NULL ,flags ,& slen ); 346* fnamep = s ; 347* fnamelen = slen ; 348xfree (* bufp ); 349* bufp = s ; 350didit = true; 351xfree (sub ); 352xfree (str ); 353 } 354xfree (pat ); 355 } 356// after using ":s", repeat all the modifiers 357if (didit ) { 358 gotorepeat ; 359 } 360 } 361 } 362 363if (src [* usedlen ]== ':' && src [* usedlen + 1 ]== 'S' ) { 364// vim_strsave_shellescape() needs a NUL terminated string. 365c = (uint8_t )(* fnamep )[* fnamelen ]; 366if (c != NUL ) { 367 (* fnamep )[* fnamelen ]= NUL ; 368 } 369p = vim_strsave_shellescape (* fnamep , false, false); 370if (c != NUL ) { 371 (* fnamep )[* fnamelen ]= (char )c ; 372 } 373xfree (* bufp ); 374* bufp = * fnamep = p ; 375* fnamelen = strlen (p ); 376* usedlen += 2 ; 377 } 378 379return valid ; 380} 381 382/// "chdir(dir)" function 383void f_chdir (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 384{ 385rettv -> v_type = VAR_STRING ; 386rettv -> vval .v_string = NULL ; 387 388if (check_secure ()) { 389return ; 390 } 391 392if (argvars [0 ].v_type != VAR_STRING ) { 393// Returning an empty string means it failed. 394// No error message, for historic reasons. 395return ; 396 } 397 398// Return the current directory 399char * cwd = xmalloc (MAXPATHL ); 400if (os_dirname (cwd ,MAXPATHL )!= FAIL ) { 401#ifdef BACKSLASH_IN_FILENAME 402slash_adjust (cwd ); 403#endif 404rettv -> vval .v_string = xstrdup (cwd ); 405 } 406xfree (cwd ); 407 408CdScope scope = kCdScopeGlobal ; 409if (argvars [1 ].v_type != VAR_UNKNOWN ) { 410const char * s = tv_get_string (& argvars [1 ]); 411if (strcmp (s ,"global" )== 0 ) { 412scope = kCdScopeGlobal ; 413 }else if (strcmp (s ,"tabpage" )== 0 ) { 414scope = kCdScopeTabpage ; 415 }else if (strcmp (s ,"window" )== 0 ) { 416scope = kCdScopeWindow ; 417 }else if (strcmp (s ,"buffer" )== 0 ) { 418scope = kCdScopeBuffer ; 419 }else { 420semsg (_ (e_invargNval ),"scope" ,s ); 421return ; 422 } 423 }else if (curbuf -> b_localdir != NULL ) { 424scope = kCdScopeBuffer ; 425 }else if (curwin -> w_localdir != NULL ) { 426scope = kCdScopeWindow ; 427 }else if (curtab -> tp_localdir != NULL ) { 428scope = kCdScopeTabpage ; 429 } 430 431if (!do_chdir (argvars [0 ].vval .v_string ,scope )) { 432// Directory change failed 433XFREE_CLEAR (rettv -> vval .v_string ); 434 } 435} 436 437/// "delete()" function 438void f_delete (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 439{ 440rettv -> vval .v_number = -1 ; 441if (check_secure ()) { 442return ; 443 } 444 445const char * const name = tv_get_string (& argvars [0 ]); 446if (* name == NUL ) { 447emsg (_ (e_invarg )); 448return ; 449 } 450 451char nbuf [NUMBUFLEN ]; 452const char * flags ; 453if (argvars [1 ].v_type != VAR_UNKNOWN ) { 454flags = tv_get_string_buf (& argvars [1 ],nbuf ); 455 }else { 456flags = "" ; 457 } 458 459if (* flags == NUL ) { 460// delete a file 461rettv -> vval .v_number = os_remove (name )== 0 ?0 :-1 ; 462 }else if (strcmp (flags ,"d" )== 0 ) { 463// delete an empty directory 464rettv -> vval .v_number = os_rmdir (name )== 0 ?0 :-1 ; 465 }else if (strcmp (flags ,"rf" )== 0 ) { 466// delete a directory recursively 467rettv -> vval .v_number = delete_recursive (name ); 468 }else { 469semsg (_ (e_invexpr2 ),flags ); 470 } 471} 472 473/// "executable()" function 474void f_executable (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 475{ 476if (tv_check_for_string_arg (argvars ,0 )== FAIL ) { 477return ; 478 } 479 480// Check in $PATH and also check directly if there is a directory name 481rettv -> vval .v_number = os_can_exe (tv_get_string (& argvars [0 ]),NULL , true); 482} 483 484/// "exepath()" function 485void f_exepath (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 486{ 487if (tv_check_for_nonempty_string_arg (argvars ,0 )== FAIL ) { 488return ; 489 } 490 491char * path = NULL ; 492 493os_can_exe (tv_get_string (& argvars [0 ]),& path , true); 494 495#ifdef BACKSLASH_IN_FILENAME 496if (path != NULL ) { 497slash_adjust (path ); 498 } 499#endif 500 501rettv -> v_type = VAR_STRING ; 502rettv -> vval .v_string = path ; 503} 504 505/// "filecopy()" function 506void f_filecopy (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 507{ 508rettv -> vval .v_number = false; 509 510if (check_secure () 511|| tv_check_for_string_arg (argvars ,0 )== FAIL 512|| tv_check_for_string_arg (argvars ,1 )== FAIL ) { 513return ; 514 } 515 516const char * from = tv_get_string (& argvars [0 ]); 517 518FileInfo from_info ; 519if (os_fileinfo_link (from ,& from_info ) 520&& (S_ISREG (from_info .stat .st_mode )|| S_ISLNK (from_info .stat .st_mode ))) { 521rettv -> vval .v_number 522= vim_copyfile (tv_get_string (& argvars [0 ]),tv_get_string (& argvars [1 ]))== OK ; 523 } 524} 525 526/// "filereadable()" function 527void f_filereadable (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 528{ 529const char * const p = tv_get_string (& argvars [0 ]); 530rettv -> vval .v_number = (* p && !os_isdir (p )&& os_file_is_readable (p )); 531} 532 533/// @return 0 for not writable 534/// 1 for writable file 535/// 2 for a dir which we have rights to write into. 536void f_filewritable (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 537{ 538const char * filename = tv_get_string (& argvars [0 ]); 539rettv -> vval .v_number = os_file_is_writable (filename ); 540} 541 542static void findfilendir (typval_T * argvars ,typval_T * rettv ,int find_what ) 543{ 544char * fresult = NULL ; 545char * path = * curbuf -> b_p_path == NUL ?p_path :curbuf -> b_p_path ; 546int count = 1 ; 547bool first = true; 548bool error = false; 549 550rettv -> vval .v_string = NULL ; 551rettv -> v_type = VAR_STRING ; 552 553const char * fname = tv_get_string (& argvars [0 ]); 554 555char pathbuf [NUMBUFLEN ]; 556if (argvars [1 ].v_type != VAR_UNKNOWN ) { 557const char * p = tv_get_string_buf_chk (& argvars [1 ],pathbuf ); 558if (p == NULL ) { 559error = true; 560 }else { 561if (* p != NUL ) { 562path = (char * )p ; 563 } 564 565if (argvars [2 ].v_type != VAR_UNKNOWN ) { 566count = (int )tv_get_number_chk (& argvars [2 ],& error ); 567 } 568 } 569 } 570 571if (count < 0 ) { 572tv_list_alloc_ret (rettv ,kListLenUnknown ); 573 } 574 575if (* fname != NUL && !error ) { 576char * file_to_find = NULL ; 577char * search_ctx = NULL ; 578 579do { 580if (rettv -> v_type == VAR_STRING || rettv -> v_type == VAR_LIST ) { 581xfree (fresult ); 582 } 583fresult = find_file_in_path_option (first ? (char * )fname :NULL , 584first ?strlen (fname ) :0 , 5850 ,first ,path , 586find_what ,curbuf -> b_ffname , 587 (find_what == FINDFILE_DIR 588 ?"" 589 :curbuf -> b_p_sua ), 590& file_to_find ,& search_ctx ); 591first = false; 592 593if (fresult != NULL && rettv -> v_type == VAR_LIST ) { 594tv_list_append_string (rettv -> vval .v_list ,fresult ,-1 ); 595 } 596 }while ((rettv -> v_type == VAR_LIST || -- count > 0 )&& fresult != NULL ); 597 598xfree (file_to_find ); 599vim_findfile_cleanup (search_ctx ); 600 } 601 602if (rettv -> v_type == VAR_STRING ) { 603rettv -> vval .v_string = fresult ; 604 } 605} 606 607/// "finddir({fname}[, {path}[, {count}]])" function 608void f_finddir (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 609{ 610findfilendir (argvars ,rettv ,FINDFILE_DIR ); 611} 612 613/// "findfile({fname}[, {path}[, {count}]])" function 614void f_findfile (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 615{ 616findfilendir (argvars ,rettv ,FINDFILE_FILE ); 617} 618 619/// "fnamemodify({fname}, {mods})" function 620void f_fnamemodify (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 621{ 622char * fbuf = NULL ; 623size_t len = 0 ; 624char buf [NUMBUFLEN ]; 625const char * fname = tv_get_string_chk (& argvars [0 ]); 626const char * const mods = tv_get_string_buf_chk (& argvars [1 ],buf ); 627if (mods == NULL || fname == NULL ) { 628fname = NULL ; 629 }else { 630fbuf = TO_SLASH_SAVE (fname ); 631fname = fbuf ; 632len = strlen (fname ); 633if (* mods != NUL ) { 634size_t usedlen = 0 ; 635modify_fname ((char * )mods , false,& usedlen , 636 (char ** )& fname ,& fbuf ,& len , false); 637 } 638 } 639 640rettv -> v_type = VAR_STRING ; 641if (fname == NULL ) { 642rettv -> vval .v_string = NULL ; 643 }else { 644rettv -> vval .v_string = xmemdupz (fname ,len ); 645 } 646xfree (fbuf ); 647} 648 649/// Resolves the `[{winnr}[, {tabnr}[, {bufnr}]]]` arguments of `getcwd()`/`haslocaldir()` to the 650/// requested scope and the scope objects to inspect. In an argument, `0` means the current object 651/// and `-1` skips the scope (requesting the next broader one). Note that the argument order 652/// differs from the `CdScope` order. 653/// 654/// @param default_scope Scope when no arguments were given. 655/// 656/// @return false if an error message was emitted. 657static bool getcwd_scope_args (typval_T * argvars ,CdScope default_scope ,CdScope * scope ,win_T ** win , 658tabpage_T ** tp ,buf_T ** buf ) 659{ 660enum {kWinArg ,kTabArg ,kBufArg , }; 661int argv []= {0 ,0 ,0 }; 662int argc = 0 ; 663 664* scope = default_scope ; 665* win = curwin ; 666* tp = curtab ; 667* buf = curbuf ; 668 669for (;argc < 3 ;argc ++ ) { 670// If there is no argument there are no more scopes after it, break out. 671if (argvars [argc ].v_type == VAR_UNKNOWN ) { 672break ; 673 } 674if (argvars [argc ].v_type != VAR_NUMBER ) { 675emsg (_ (e_invarg )); 676return false; 677 } 678argv [argc ]= (int )argvars [argc ].vval .v_number ; 679// It is an error for the scope number to be less than `-1`. 680if (argv [argc ]< -1 ) { 681emsg (_ (e_invarg )); 682return false; 683 } 684 } 685 686// An argument may only be -1 if all preceding arguments are -1: `(2, 3, -1)` is an error. 687bool explicit_scope = false; 688for (int i = 0 ;i < argc ;i ++ ) { 689explicit_scope = explicit_scope || argv [i ] >=0 ; 690if (explicit_scope && argv [i ]< 0 ) { 691emsg (_ ("E5001: Argument cannot be -1 if preceding argument is >= 0." )); 692return false; 693 } 694 } 695 696// Narrowest requested scope. Imagine X >= 0: 697switch (argc ) { 698case 0 : 699break ; 700case 1 : 701if (argv [kWinArg ] >=0 ) { 702* scope = kCdScopeWindow ;// (X) 703 }else { 704* scope = kCdScopeTabpage ;// (-1) 705 } 706break ; 707case 2 : 708if (argv [kWinArg ] >=0 ) { 709* scope = kCdScopeWindow ;// (X, ...) 710 }else if (argv [kTabArg ] >=0 ) { 711* scope = kCdScopeTabpage ;// (-1, X) 712 }else { 713* scope = kCdScopeGlobal ;// (-1, -1) 714 } 715break ; 716case 3 : 717if (argv [kBufArg ] >=0 ) { 718* scope = kCdScopeBuffer ;// (-1, -1, X) 719 }else { 720* scope = kCdScopeGlobal ;// (-1, -1, -1) 721 } 722break ; 723 } 724 725if (* scope == kCdScopeBuffer ) { 726if (argv [kWinArg ] >=0 || argv [kTabArg ] >=0 ) { 727emsg (_ ("E5006: Window and tab scope must be -1 when using buffer scope" )); 728return false; 729 } 730if (argv [kBufArg ]> 0 ) { 731Error err = ERROR_INIT ; 732* buf = find_buffer_by_handle (argv [kBufArg ],& err ); 733if (ERROR_SET (& err )) { 734emsg (_ ("E5007: Cannot find buffer number." )); 735xfree (err .msg ); 736return false; 737 } 738 } 739 } 740 741// Find the tabpage by number. 742if (argv [kTabArg ]> 0 ) { 743* tp = find_tabpage (argv [kTabArg ]); 744if (* tp == NULL ) { 745emsg (_ ("E5000: Cannot find tab number." )); 746return false; 747 } 748 } 749 750// Find the window in `tp` by number. 751if (argv [kWinArg ]> 0 ) { 752* win = find_win_by_nr (& argvars [0 ],* tp ); 753if (* win == NULL ) { 754emsg (_ ("E5002: Cannot find window number." )); 755return false; 756 } 757 } 758 759return true; 760} 761 762/// `getcwd([{win}[, {tab}[, {buf}]]])` function 763/// 764/// Every scope not specified implies the currently selected scope object. 765/// 766/// @pre The arguments must be of type number. 767/// @pre There may not be more than three arguments. 768/// @pre An argument may not be -1 if preceding arguments are not all -1. 769/// 770/// @post The return value will be a string. 771void f_getcwd (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 772{ 773CdScope scope ; 774win_T * win ; 775tabpage_T * tp ; 776buf_T * buf ; 777 778rettv -> v_type = VAR_STRING ; 779rettv -> vval .v_string = NULL ; 780 781// Without arguments (kCdScopeInvalid), the effective working directory is returned. 782if (!getcwd_scope_args (argvars ,kCdScopeInvalid ,& scope ,& win ,& tp ,& buf )) { 783return ; 784 } 785 786char * from = NULL ;// The local directory to copy. 787char * cwd = xmalloc (MAXPATHL ); 788 789switch (scope ) { 790case kCdScopeWindow : 791from = win -> w_localdir ; 792if (from ) { 793break ; 794 } 795FALLTHROUGH ; 796case kCdScopeTabpage : 797from = tp -> tp_localdir ; 798if (from ) { 799break ; 800 } 801FALLTHROUGH ; 802case kCdScopeBuffer : 803// Only a buffer target reaches this with `scope` unchanged: a buffer belongs to no particular 804// window or tabpage, so it skips those and falls back to global dir. 805from = scope == kCdScopeBuffer ?buf -> b_localdir :NULL ; 806if (from ) { 807break ; 808 } 809FALLTHROUGH ; 810case kCdScopeGlobal : 811if (globaldir ) {// `globaldir` is not always set. 812from = globaldir ; 813break ; 814 } 815FALLTHROUGH ;// In global directory, just need to get OS CWD. 816case kCdScopeInvalid :// If called without any arguments, get OS CWD. 817if (os_dirname (cwd ,MAXPATHL )== FAIL ) { 818from = "" ;// Return empty string on failure. 819 } 820 } 821 822if (from ) { 823xstrlcpy (cwd ,from ,MAXPATHL ); 824 } 825 826rettv -> vval .v_string = xstrdup (cwd ); 827#ifdef BACKSLASH_IN_FILENAME 828slash_adjust (rettv -> vval .v_string ); 829#endif 830 831xfree (cwd ); 832} 833 834/// "getfperm({fname})" function 835void f_getfperm (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 836{ 837char * perm = NULL ; 838char flags []= "rwx" ; 839 840const char * filename = tv_get_string (& argvars [0 ]); 841int32_t file_perm = os_getperm (filename ); 842if (file_perm >=0 ) { 843perm = xstrdup ("---------" ); 844for (int i = 0 ;i < 9 ;i ++ ) { 845if (file_perm & (1 << (8 - i ))) { 846perm [i ]= flags [i %3 ]; 847 } 848 } 849 } 850rettv -> v_type = VAR_STRING ; 851rettv -> vval .v_string = perm ; 852} 853 854/// "getfsize({fname})" function 855void f_getfsize (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 856{ 857const char * fname = tv_get_string (& argvars [0 ]); 858 859FileInfo file_info ; 860if (os_fileinfo (fname ,& file_info )) { 861uint64_t filesize = os_fileinfo_size (& file_info ); 862if (os_isdir (fname )) { 863rettv -> vval .v_number = 0 ; 864 }else { 865rettv -> vval .v_number = (varnumber_T )filesize ; 866 867// non-perfect check for overflow 868if ((uint64_t )rettv -> vval .v_number != filesize ) { 869rettv -> vval .v_number = -2 ; 870 } 871 } 872 }else { 873rettv -> vval .v_number = -1 ; 874 } 875} 876 877/// "getftime({fname})" function 878void f_getftime (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 879{ 880const char * fname = tv_get_string (& argvars [0 ]); 881 882FileInfo file_info ; 883if (os_fileinfo (fname ,& file_info )) { 884rettv -> vval .v_number = (varnumber_T )file_info .stat .st_mtim .tv_sec ; 885 }else { 886rettv -> vval .v_number = -1 ; 887 } 888} 889 890/// "getftype({fname})" function 891void f_getftype (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 892{ 893char * type = NULL ; 894char * t ; 895 896const char * fname = tv_get_string (& argvars [0 ]); 897 898rettv -> v_type = VAR_STRING ; 899FileInfo file_info ; 900if (os_fileinfo_link (fname ,& file_info )) { 901uint64_t mode = file_info .stat .st_mode ; 902if (S_ISREG (mode )) { 903t = "file" ; 904 }else if (S_ISDIR (mode )) { 905t = "dir" ; 906 }else if (S_ISLNK (mode )) { 907t = "link" ; 908 }else if (S_ISBLK (mode )) { 909t = "bdev" ; 910 }else if (S_ISCHR (mode )) { 911t = "cdev" ; 912 }else if (S_ISFIFO (mode )) { 913t = "fifo" ; 914 }else if (S_ISSOCK (mode )) { 915t = "socket" ; 916 }else { 917t = "other" ; 918 } 919type = xstrdup (t ); 920 } 921rettv -> vval .v_string = type ; 922} 923 924/// "glob()" function 925void f_glob (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 926{ 927int options = WILD_SILENT |WILD_USE_NL ; 928expand_T xpc ; 929bool error = false; 930 931// When the optional second argument is non-zero, don't remove matches 932// for 'wildignore' and don't put matches for 'suffixes' at the end. 933rettv -> v_type = VAR_STRING ; 934if (argvars [1 ].v_type != VAR_UNKNOWN ) { 935if (tv_get_bool_chk (& argvars [1 ],& error )) { 936options |=WILD_KEEP_ALL ; 937 } 938if (argvars [2 ].v_type != VAR_UNKNOWN ) { 939if (tv_get_bool_chk (& argvars [2 ],& error )) { 940tv_list_set_ret (rettv ,NULL ); 941 } 942if (argvars [3 ].v_type != VAR_UNKNOWN 943&& tv_get_bool_chk (& argvars [3 ],& error )) { 944options |=WILD_ALLLINKS ; 945 } 946 } 947 } 948if (!error ) { 949ExpandInit (& xpc ); 950xpc .xp_context = EXPAND_FILES ; 951if (p_wic ) { 952options += WILD_ICASE ; 953 } 954if (rettv -> v_type == VAR_STRING ) { 955rettv -> vval .v_string = ExpandOne (& xpc , (char * ) 956tv_get_string (& argvars [0 ]),NULL ,options , 957WILD_ALL ); 958 }else { 959ExpandOne (& xpc , (char * )tv_get_string (& argvars [0 ]),NULL ,options , 960WILD_ALL_KEEP ); 961tv_list_alloc_ret (rettv ,xpc .xp_numfiles ); 962for (int i = 0 ;i < xpc .xp_numfiles ;i ++ ) { 963tv_list_append_string (rettv -> vval .v_list ,xpc .xp_files [i ],-1 ); 964 } 965ExpandCleanup (& xpc ); 966 } 967 }else { 968rettv -> vval .v_string = NULL ; 969 } 970} 971 972/// "globpath()" function 973void f_globpath (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 974{ 975int flags = 0 ;// Flags for globpath. 976bool error = false; 977 978// Return a string, or a list if the optional third argument is non-zero. 979rettv -> v_type = VAR_STRING ; 980 981if (argvars [2 ].v_type != VAR_UNKNOWN ) { 982// When the optional second argument is non-zero, don't remove matches 983// for 'wildignore' and don't put matches for 'suffixes' at the end. 984if (tv_get_bool_chk (& argvars [2 ],& error )) { 985flags |=WILD_KEEP_ALL ; 986 } 987 988if (argvars [3 ].v_type != VAR_UNKNOWN ) { 989if (tv_get_bool_chk (& argvars [3 ],& error )) { 990tv_list_set_ret (rettv ,NULL ); 991 } 992if (argvars [4 ].v_type != VAR_UNKNOWN 993&& tv_get_bool_chk (& argvars [4 ],& error )) { 994flags |=WILD_ALLLINKS ; 995 } 996 } 997 } 998 999char buf1 [NUMBUFLEN ]; 1000const char * const file = tv_get_string_buf_chk (& argvars [1 ],buf1 ); 1001if (file != NULL && !error ) { 1002garray_T ga ; 1003ga_init (& ga , (int )sizeof (char * ),10 ); 1004globpath ((char * )tv_get_string (& argvars [0 ]), (char * )file ,& ga ,flags , false); 1005 1006if (rettv -> v_type == VAR_STRING ) { 1007rettv -> vval .v_string = ga_concat_strings (& ga ,"\n" ); 1008 }else { 1009tv_list_alloc_ret (rettv ,ga .ga_len ); 1010for (int i = 0 ;i < ga .ga_len ;i ++ ) { 1011tv_list_append_string (rettv -> vval .v_list , 1012 ((const char ** )(ga .ga_data ))[i ],-1 ); 1013 } 1014 } 1015 1016ga_clear_strings (& ga ); 1017 }else { 1018rettv -> vval .v_string = NULL ; 1019 } 1020} 1021 1022/// "glob2regpat()" function 1023void f_glob2regpat (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1024{ 1025const char * const pat = tv_get_string_chk (& argvars [0 ]);// NULL on type error 1026 1027rettv -> v_type = VAR_STRING ; 1028rettv -> vval .v_string = pat == NULL ?NULL :file_pat_to_reg_pat (pat ,NULL ,NULL , false); 1029} 1030 1031/// `haslocaldir([{win}[, {tab}[, {buf}]]])` function 1032/// 1033/// Returns `1` if the scope object has a local directory, `0` otherwise. If a 1034/// scope object is not specified the current one is implied. 1035/// 1036/// @pre The arguments must be of type number. 1037/// @pre There may not be more than three arguments. 1038/// @pre An argument may not be -1 if preceding arguments are not all -1. 1039/// 1040/// @post The return value will be either the number `1` or `0`. 1041void f_haslocaldir (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1042{ 1043CdScope scope ; 1044win_T * win ; 1045tabpage_T * tp ; 1046buf_T * buf ; 1047 1048rettv -> v_type = VAR_NUMBER ; 1049rettv -> vval .v_number = 0 ; 1050 1051// Without arguments, default to window scope. 1052if (!getcwd_scope_args (argvars ,kCdScopeWindow ,& scope ,& win ,& tp ,& buf )) { 1053return ; 1054 } 1055 1056switch (scope ) { 1057case kCdScopeWindow : 1058rettv -> vval .v_number = win -> w_localdir != NULL ; 1059break ; 1060case kCdScopeBuffer : 1061rettv -> vval .v_number = buf -> b_localdir != NULL ; 1062break ; 1063case kCdScopeTabpage : 1064rettv -> vval .v_number = tp -> tp_localdir != NULL ; 1065break ; 1066case kCdScopeGlobal : 1067// The global scope never has a local directory 1068break ; 1069case kCdScopeInvalid : 1070// We should never get here 1071abort (); 1072 } 1073} 1074 1075/// "isabsolutepath()" function 1076void f_isabsolutepath (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1077{ 1078rettv -> vval .v_number = path_is_absolute (tv_get_string (& argvars [0 ])); 1079} 1080 1081/// "isdirectory()" function 1082void f_isdirectory (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1083{ 1084rettv -> vval .v_number = os_isdir (tv_get_string (& argvars [0 ])); 1085} 1086 1087/// "mkdir()" function 1088void f_mkdir (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1089{ 1090int prot = 0755 ; 1091 1092rettv -> vval .v_number = FAIL ; 1093if (check_secure ()) { 1094return ; 1095 } 1096 1097char buf [NUMBUFLEN ]; 1098const char * const dir = tv_get_string_buf (& argvars [0 ],buf ); 1099if (* dir == NUL ) { 1100return ; 1101 } 1102 1103if (* path_tail (dir )== NUL ) { 1104// Remove trailing slashes. 1105* path_tail_with_sep ((char * )dir )= NUL ; 1106 } 1107 1108bool defer = false; 1109bool defer_recurse = false; 1110char * created = NULL ; 1111if (argvars [1 ].v_type != VAR_UNKNOWN ) { 1112if (argvars [2 ].v_type != VAR_UNKNOWN ) { 1113prot = (int )tv_get_number_chk (& argvars [2 ],NULL ); 1114if (prot == -1 ) { 1115return ; 1116 } 1117 } 1118const char * arg2 = tv_get_string (& argvars [1 ]); 1119defer = vim_strchr (arg2 ,'D' )!= NULL ; 1120defer_recurse = vim_strchr (arg2 ,'R' )!= NULL ; 1121if ((defer || defer_recurse )&& !can_add_defer ()) { 1122return ; 1123 } 1124 1125if (vim_strchr (arg2 ,'p' )!= NULL ) { 1126char * failed_dir ; 1127int ret = os_mkdir_recurse (dir ,prot ,& failed_dir , 1128defer || defer_recurse ?& created :NULL ); 1129if (ret != 0 ) { 1130semsg (_ (e_mkdir ),failed_dir ,os_strerror (ret )); 1131xfree (failed_dir ); 1132rettv -> vval .v_number = FAIL ; 1133return ; 1134 } 1135rettv -> vval .v_number = OK ; 1136 } 1137 } 1138if (rettv -> vval .v_number == FAIL ) { 1139rettv -> vval .v_number = vim_mkdir_emsg (dir ,prot ); 1140 } 1141 1142// Handle "D" and "R": deferred deletion of the created directory. 1143if (rettv -> vval .v_number == OK 1144&& created == NULL && (defer || defer_recurse )) { 1145created = FullName_save (dir , false); 1146 } 1147if (created != NULL ) { 1148typval_T tv [2 ]; 1149tv [0 ].v_type = VAR_STRING ; 1150tv [0 ].v_lock = VAR_UNLOCKED ; 1151tv [0 ].vval .v_string = created ; 1152tv [1 ].v_type = VAR_STRING ; 1153tv [1 ].v_lock = VAR_UNLOCKED ; 1154tv [1 ].vval .v_string = xstrdup (defer_recurse ?"rf" :"d" ); 1155add_defer ("delete" ,2 ,tv ); 1156 } 1157} 1158 1159/// "pathshorten()" function 1160void f_pathshorten (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1161{ 1162int trim_len = 1 ; 1163 1164if (argvars [1 ].v_type != VAR_UNKNOWN ) { 1165trim_len = (int )tv_get_number (& argvars [1 ]); 1166if (trim_len < 1 ) { 1167trim_len = 1 ; 1168 } 1169 } 1170 1171rettv -> v_type = VAR_STRING ; 1172const char * p = tv_get_string_chk (& argvars [0 ]); 1173if (p == NULL ) { 1174rettv -> vval .v_string = NULL ; 1175 }else { 1176rettv -> vval .v_string = xstrdup (p ); 1177shorten_dir_len (rettv -> vval .v_string ,trim_len ); 1178 } 1179} 1180 1181/// Evaluate "expr" (= "context") for readdir(). 1182static varnumber_T readdir_checkitem (void * context ,const char * name ) 1183FUNC_ATTR_NONNULL_ALL 1184{ 1185typval_T * expr = (typval_T * )context ; 1186typval_T argv [2 ]; 1187varnumber_T retval = 0 ; 1188bool error = false; 1189 1190if (expr -> v_type == VAR_UNKNOWN ) { 1191return 1 ; 1192 } 1193 1194typval_T save_val ; 1195prepare_vimvar (VV_VAL ,& save_val ); 1196set_vim_var_string (VV_VAL ,name ,-1 ); 1197argv [0 ].v_type = VAR_STRING ; 1198argv [0 ].vval .v_string = (char * )name ; 1199 1200typval_T rettv ; 1201if (eval_expr_typval (expr , false,argv ,1 ,& rettv )== FAIL ) { 1202 gototheend ; 1203 } 1204 1205retval = tv_get_number_chk (& rettv ,& error ); 1206if (error ) { 1207retval = -1 ; 1208 } 1209 1210tv_clear (& rettv ); 1211 1212theend : 1213set_vim_var_string (VV_VAL ,NULL ,0 ); 1214restore_vimvar (VV_VAL ,& save_val ); 1215return retval ; 1216} 1217 1218/// "readdir()" function 1219void f_readdir (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1220{ 1221tv_list_alloc_ret (rettv ,kListLenUnknown ); 1222if (check_secure ()) { 1223return ; 1224 } 1225 1226const char * path = tv_get_string (& argvars [0 ]); 1227typval_T * expr = & argvars [1 ]; 1228garray_T ga ; 1229int ret = readdir_core (& ga ,path , (void * )expr ,readdir_checkitem ); 1230if (ret == OK && ga .ga_len > 0 ) { 1231for (int i = 0 ;i < ga .ga_len ;i ++ ) { 1232const char * p = ((const char ** )ga .ga_data )[i ]; 1233tv_list_append_string (rettv -> vval .v_list ,p ,-1 ); 1234 } 1235 } 1236ga_clear_strings (& ga ); 1237} 1238 1239/// Read blob from file "fd". 1240/// Caller has allocated a blob in "rettv". 1241/// 1242/// @param[in] fd File to read from. 1243/// @param[in,out] rettv Blob to write to. 1244/// @param[in] offset Read the file from the specified offset. 1245/// @param[in] size Read the specified size, or -1 if no limit. 1246/// 1247/// @return OK on success, or FAIL on failure. 1248static int read_blob (FILE * const fd ,typval_T * rettv ,off_T offset ,off_T size_arg ) 1249FUNC_ATTR_NONNULL_ALL 1250{ 1251blob_T * const blob = rettv -> vval .v_blob ; 1252FileInfo file_info ; 1253if (!os_fileinfo_fd (fileno (fd ),& file_info )) { 1254return FAIL ;// can't read the file, error 1255 } 1256 1257int whence ; 1258off_T size = size_arg ; 1259const off_T file_size = (off_T )os_fileinfo_size (& file_info ); 1260if (offset >=0 ) { 1261// The size defaults to the whole file. If a size is given it is 1262// limited to not go past the end of the file. 1263if (size == -1 || (size > file_size - offset && !S_ISCHR (file_info .stat .st_mode ))) { 1264// size may become negative, checked below 1265size = (off_T )os_fileinfo_size (& file_info )- offset ; 1266 } 1267whence = SEEK_SET ; 1268 }else { 1269// limit the offset to not go before the start of the file 1270if (- offset > file_size && !S_ISCHR (file_info .stat .st_mode )) { 1271offset = - file_size ; 1272 } 1273// Size defaults to reading until the end of the file. 1274if (size == -1 || size > - offset ) { 1275size = - offset ; 1276 } 1277whence = SEEK_END ; 1278 } 1279if (size <=0 ) { 1280return OK ; 1281 } 1282if (offset != 0 && vim_fseek (fd ,offset ,whence )!= 0 ) { 1283return OK ; 1284 } 1285 1286ga_grow (& blob -> bv_ga , (int )size ); 1287blob -> bv_ga .ga_len = (int )size ; 1288if (fread (blob -> bv_ga .ga_data ,1 , (size_t )blob -> bv_ga .ga_len ,fd ) 1289< (size_t )blob -> bv_ga .ga_len ) { 1290// An empty blob is returned on error. 1291tv_blob_free (rettv -> vval .v_blob ); 1292rettv -> vval .v_blob = NULL ; 1293return FAIL ; 1294 } 1295return OK ; 1296} 1297 1298/// "readfile()" or "readblob()" function 1299static void read_file_or_blob (typval_T * argvars ,typval_T * rettv ,bool always_blob ) 1300{ 1301bool binary = false; 1302bool blob = always_blob ; 1303FILE * fd ; 1304char buf [(IOSIZE /256 )* 256 ];// rounded to avoid odd + 1 1305int io_size = sizeof (buf ); 1306char * prev = NULL ;// previously read bytes, if any 1307ptrdiff_t prevlen = 0 ;// length of data in prev 1308ptrdiff_t prevsize = 0 ;// size of prev buffer 1309int64_t maxline = MAXLNUM ; 1310off_T offset = 0 ; 1311off_T size = -1 ; 1312 1313if (argvars [1 ].v_type != VAR_UNKNOWN ) { 1314if (always_blob ) { 1315offset = (off_T )tv_get_number (& argvars [1 ]); 1316if (argvars [2 ].v_type != VAR_UNKNOWN ) { 1317size = (off_T )tv_get_number (& argvars [2 ]); 1318 } 1319 }else { 1320if (strcmp (tv_get_string (& argvars [1 ]),"b" )== 0 ) { 1321binary = true; 1322 }else if (strcmp (tv_get_string (& argvars [1 ]),"B" )== 0 ) { 1323blob = true; 1324 } 1325if (argvars [2 ].v_type != VAR_UNKNOWN ) { 1326maxline = tv_get_number (& argvars [2 ]); 1327 } 1328 } 1329 } 1330 1331if (blob ) { 1332tv_blob_alloc_ret (rettv ); 1333 }else { 1334tv_list_alloc_ret (rettv ,kListLenUnknown ); 1335 } 1336 1337// Always open the file in binary mode, library functions have a mind of 1338// their own about CR-LF conversion. 1339const char * const fname = tv_get_string (& argvars [0 ]); 1340 1341if (os_isdir (fname )) { 1342semsg (_ (e_isadir2 ),fname ); 1343return ; 1344 } 1345if (* fname == NUL || (fd = os_fopen (fname ,READBIN ))== NULL ) { 1346semsg (_ (e_notopen ),* fname == NUL ?_ ("<empty>" ) :fname ); 1347return ; 1348 } 1349 1350if (blob ) { 1351if (read_blob (fd ,rettv ,offset ,size )== FAIL ) { 1352semsg (_ (e_cant_read_file_str ),fname ); 1353 } 1354fclose (fd ); 1355return ; 1356 } 1357 1358list_T * const l = rettv -> vval .v_list ; 1359 1360while (maxline < 0 || tv_list_len (l )< maxline ) { 1361int readlen = (int )fread (buf ,1 , (size_t )io_size ,fd ); 1362 1363// This for loop processes what was read, but is also entered at end 1364// of file so that either: 1365// - an incomplete line gets written 1366// - a "binary" file gets an empty line at the end if it ends in a 1367// newline. 1368char * p ;// Position in buf. 1369char * start ;// Start of current line. 1370for (p = buf ,start = buf ; 1371p < buf + readlen || (readlen <=0 && (prevlen > 0 || binary )); 1372p ++ ) { 1373if (readlen <=0 || * p == '\n' ) { 1374char * s = NULL ; 1375size_t len = (size_t )(p - start ); 1376 1377// Finished a line. Remove CRs before NL. 1378if (readlen > 0 && !binary ) { 1379while (len > 0 && start [len - 1 ]== '\r' ) { 1380len -- ; 1381 } 1382// removal may cross back to the "prev" string 1383if (len == 0 ) { 1384while (prevlen > 0 && prev [prevlen - 1 ]== '\r' ) { 1385prevlen -- ; 1386 } 1387 } 1388 } 1389if (prevlen == 0 ) { 1390assert (len < INT_MAX ); 1391s = xmemdupz (start ,len ); 1392 }else { 1393// Change "prev" buffer to be the right size. This way 1394// the bytes are only copied once, and very long lines are 1395// allocated only once. 1396s = xrealloc (prev , (size_t )prevlen + len + 1 ); 1397memcpy (s + prevlen ,start ,len ); 1398s [(size_t )prevlen + len ]= NUL ; 1399prev = NULL ;// the list will own the string 1400prevlen = prevsize = 0 ; 1401 } 1402 1403tv_list_append_owned_tv (l , (typval_T ) { 1404 .v_type = VAR_STRING , 1405 .v_lock = VAR_UNLOCKED , 1406 .vval .v_string = s , 1407 }); 1408 1409start = p + 1 ;// Step over newline. 1410if (maxline < 0 ) { 1411if (tv_list_len (l )> - maxline ) { 1412assert (tv_list_len (l )== 1 + (- maxline )); 1413tv_list_item_remove (l ,tv_list_first (l )); 1414 } 1415 }else if (tv_list_len (l ) >=maxline ) { 1416assert (tv_list_len (l )== maxline ); 1417break ; 1418 } 1419if (readlen <=0 ) { 1420break ; 1421 } 1422 }else if (* p == NUL ) { 1423* p = '\n' ; 1424// Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this 1425// when finding the BF and check the previous two bytes. 1426 }else if ((uint8_t )(* p )== 0xbf && !binary ) { 1427// Find the two bytes before the 0xbf. If p is at buf, or buf + 1, 1428// these may be in the "prev" string. 1429char back1 = p >=buf + 1 ?p [-1 ] 1430 :prevlen >=1 ?prev [prevlen - 1 ] :NUL ; 1431char back2 = p >=buf + 2 ?p [-2 ] 1432 : (p == buf + 1 && prevlen >=1 1433 ?prev [prevlen - 1 ] 1434 :prevlen >=2 ?prev [prevlen - 2 ] :NUL ); 1435 1436if ((uint8_t )back2 == 0xef && (uint8_t )back1 == 0xbb ) { 1437char * dest = p - 2 ; 1438 1439// Usually a BOM is at the beginning of a file, and so at 1440// the beginning of a line; then we can just step over it. 1441if (start == dest ) { 1442start = p + 1 ; 1443 }else { 1444// have to shuffle buf to close gap 1445int adjust_prevlen = 0 ; 1446 1447if (dest < buf ) { 1448// adjust_prevlen must be 1 or 2. 1449adjust_prevlen = (int )(buf - dest ); 1450dest = buf ; 1451 } 1452if (readlen > p - buf + 1 ) { 1453memmove (dest ,p + 1 , (size_t )readlen - (size_t )(p - buf )- 1 ); 1454 } 1455readlen -= 3 - adjust_prevlen ; 1456prevlen -= adjust_prevlen ; 1457p = dest - 1 ; 1458 } 1459 } 1460 } 1461 }// for 1462 1463if ((maxline >=0 && tv_list_len (l ) >=maxline )|| readlen <=0 ) { 1464break ; 1465 } 1466if (start < p ) { 1467// There's part of a line in buf, store it in "prev". 1468if (p - start + prevlen >=prevsize ) { 1469// A common use case is ordinary text files and "prev" gets a 1470// fragment of a line, so the first allocation is made 1471// small, to avoid repeatedly 'allocing' large and 1472// 'reallocing' small. 1473if (prevsize == 0 ) { 1474prevsize = p - start ; 1475 }else { 1476ptrdiff_t grow50pc = (prevsize * 3 ) /2 ; 1477ptrdiff_t growmin = (p - start )* 2 + prevlen ; 1478prevsize = grow50pc > growmin ?grow50pc :growmin ; 1479 } 1480prev = xrealloc (prev , (size_t )prevsize ); 1481 } 1482// Add the line part to end of "prev". 1483memmove (prev + prevlen ,start , (size_t )(p - start )); 1484prevlen += p - start ; 1485 } 1486 }// while 1487 1488xfree (prev ); 1489fclose (fd ); 1490} 1491 1492/// "readblob()" function 1493void f_readblob (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1494{ 1495if (check_secure ()) { 1496return ; 1497 } 1498 1499read_file_or_blob (argvars ,rettv , true); 1500} 1501 1502/// "readfile()" function 1503void f_readfile (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1504{ 1505if (check_secure ()) { 1506return ; 1507 } 1508 1509read_file_or_blob (argvars ,rettv , false); 1510} 1511 1512/// "rename({from}, {to})" function 1513void f_rename (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1514{ 1515if (check_secure ()) { 1516rettv -> vval .v_number = -1 ; 1517 }else { 1518char buf [NUMBUFLEN ]; 1519rettv -> vval .v_number = vim_rename (tv_get_string (& argvars [0 ]), 1520tv_get_string_buf (& argvars [1 ],buf )); 1521 } 1522} 1523 1524/// "resolve()" function 1525void f_resolve (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1526{ 1527rettv -> v_type = VAR_STRING ; 1528const char * fname = tv_get_string (& argvars [0 ]); 1529#ifdef MSWIN 1530char * v = os_resolve_shortcut (fname ); 1531if (v == NULL ) { 1532if (os_is_reparse_point_include (fname )) { 1533v = os_realpath (fname ,NULL ,MAXPATHL + 1 ); 1534 } 1535 } 1536rettv -> vval .v_string = (v == NULL ?xstrdup (fname ) :v ); 1537#else 1538# ifdef HAVE_READLINK 1539 { 1540bool is_relative_to_current = false; 1541bool has_trailing_pathsep = false; 1542int limit = 100 ; 1543 1544char * p = xstrdup (fname ); 1545 1546if (p [0 ]== '.' && (vim_ispathsep (p [1 ]) 1547|| (p [1 ]== '.' && (vim_ispathsep (p [2 ]))))) { 1548is_relative_to_current = true; 1549 } 1550 1551ptrdiff_t len = (ptrdiff_t )strlen (p ); 1552if (len > 1 && after_pathsep (p ,p + len )) { 1553has_trailing_pathsep = true; 1554p [len - 1 ]= NUL ;// The trailing slash breaks readlink(). 1555 } 1556 1557char * q = (char * )path_next_component (p ); 1558char * remain = NULL ; 1559if (* q != NUL ) { 1560// Separate the first path component in "p", and keep the 1561// remainder (beginning with the path separator). 1562remain = xstrdup (q - 1 ); 1563q [-1 ]= NUL ; 1564 } 1565 1566char * const buf = xmallocz (MAXPATHL ); 1567 1568char * cpy ; 1569while (true) { 1570while (true) { 1571len = readlink (p ,buf ,MAXPATHL ); 1572if (len <=0 ) { 1573break ; 1574 } 1575buf [len ]= NUL ; 1576 1577if (limit -- == 0 ) { 1578xfree (p ); 1579xfree (remain ); 1580emsg (_ ("E655: Too many symbolic links (cycle?)" )); 1581rettv -> vval .v_string = NULL ; 1582xfree (buf ); 1583return ; 1584 } 1585 1586// Ensure that the result will have a trailing path separator 1587// if the argument has one. 1588if (remain == NULL && has_trailing_pathsep ) { 1589add_pathsep (buf ); 1590 } 1591 1592// Separate the first path component in the link value and 1593// concatenate the remainders. 1594q = (char * )path_next_component (vim_ispathsep (* buf ) ?buf + 1 :buf ); 1595if (* q != NUL ) { 1596cpy = remain ; 1597remain = remain != NULL ?concat_str (q - 1 ,remain ) :xstrdup (q - 1 ); 1598xfree (cpy ); 1599q [-1 ]= NUL ; 1600 } 1601 1602q = path_tail (p ); 1603if (q > p && * q == NUL ) { 1604// Ignore trailing path separator. 1605p [q - p - 1 ]= NUL ; 1606q = path_tail (p ); 1607 } 1608if (q > p && !path_is_absolute (buf )) { 1609// Symlink is relative to directory of argument. Replace the 1610// symlink with the resolved name in the same directory. 1611const size_t p_len = strlen (p ); 1612const size_t buf_len = strlen (buf ); 1613p = xrealloc (p ,p_len + buf_len + 1 ); 1614memcpy (path_tail (p ),buf ,buf_len + 1 ); 1615 }else { 1616xfree (p ); 1617p = xstrdup (buf ); 1618 } 1619 } 1620 1621if (remain == NULL ) { 1622break ; 1623 } 1624 1625// Append the first path component of "remain" to "p". 1626q = (char * )path_next_component (remain + 1 ); 1627len = q - remain - (* q != NUL ); 1628const size_t p_len = strlen (p ); 1629cpy = xmallocz (p_len + (size_t )len ); 1630memcpy (cpy ,p ,p_len + 1 ); 1631xstrlcat (cpy + p_len ,remain , (size_t )len + 1 ); 1632xfree (p ); 1633p = cpy ; 1634 1635// Shorten "remain". 1636if (* q != NUL ) { 1637STRMOVE (remain ,q - 1 ); 1638 }else { 1639XFREE_CLEAR (remain ); 1640 } 1641 } 1642 1643// If the result is a relative path name, make it explicitly relative to 1644// the current directory if and only if the argument had this form. 1645if (!vim_ispathsep (* p )) { 1646if (is_relative_to_current 1647&& * p != NUL 1648&& !(p [0 ]== '.' 1649&& (p [1 ]== NUL 1650|| vim_ispathsep (p [1 ]) 1651|| (p [1 ]== '.' 1652&& (p [2 ]== NUL 1653|| vim_ispathsep (p [2 ])))))) { 1654// Prepend "./". 1655cpy = concat_str ("./" ,p ); 1656xfree (p ); 1657p = cpy ; 1658 }else if (!is_relative_to_current ) { 1659// Strip leading "./". 1660q = p ; 1661while (q [0 ]== '.' && vim_ispathsep (q [1 ])) { 1662q += 2 ; 1663 } 1664if (q > p ) { 1665STRMOVE (p ,p + 2 ); 1666 } 1667 } 1668 } 1669 1670// Ensure that the result will have no trailing path separator 1671// if the argument had none. But keep "/" or "//". 1672if (!has_trailing_pathsep ) { 1673q = p + strlen (p ); 1674if (after_pathsep (p ,q )) { 1675* path_tail_with_sep (p )= NUL ; 1676 } 1677 } 1678 1679rettv -> vval .v_string = p ; 1680xfree (buf ); 1681 } 1682# else 1683char * v = os_realpath (fname ,NULL ,MAXPATHL + 1 ); 1684rettv -> vval .v_string = v == NULL ?xstrdup (fname ) :v ; 1685# endif 1686#endif 1687 1688simplify_filename (rettv -> vval .v_string ); 1689} 1690 1691/// "simplify()" function 1692void f_simplify (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1693{ 1694const char * const p = tv_get_string (& argvars [0 ]); 1695rettv -> vval .v_string = xstrdup (p ); 1696simplify_filename (rettv -> vval .v_string );// Simplify in place. 1697rettv -> v_type = VAR_STRING ; 1698} 1699 1700/// "tempname()" function 1701void f_tempname (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1702{ 1703rettv -> v_type = VAR_STRING ; 1704rettv -> vval .v_string = vim_tempname (); 1705} 1706 1707/// Write "list" of strings to file "fd". 1708/// 1709/// @param fp File to write to. 1710/// @param[in] list List to write. 1711/// @param[in] binary Whether to write in binary mode. 1712/// 1713/// @return true in case of success, false otherwise. 1714static bool write_list (FileDescriptor * const fp ,const list_T * const list ,const bool binary ) 1715FUNC_ATTR_NONNULL_ARG (1 ) 1716{ 1717int error = 0 ; 1718TV_LIST_ITER_CONST (list ,li , { 1719const char * const s = tv_get_string_chk (TV_LIST_ITEM_TV (li )); 1720if (s == NULL ) { 1721return false; 1722 } 1723const char * hunk_start = s ; 1724for (const char * p = hunk_start ;;p ++ ) { 1725if (* p == NUL || * p == NL ) { 1726if (p != hunk_start ) { 1727const ptrdiff_t written = file_write (fp ,hunk_start , 1728 (size_t )(p - hunk_start )); 1729if (written < 0 ) { 1730error = (int )written ; 1731 gotowrite_list_error ; 1732 } 1733 } 1734if (* p == NUL ) { 1735break ; 1736 }else { 1737hunk_start = p + 1 ; 1738const ptrdiff_t written = file_write (fp , (char []){NUL },1 ); 1739if (written < 0 ) { 1740error = (int )written ; 1741break ; 1742 } 1743 } 1744 } 1745 } 1746if (!binary || TV_LIST_ITEM_NEXT (list ,li )!= NULL ) { 1747const ptrdiff_t written = file_write (fp ,"\n" ,1 ); 1748if (written < 0 ) { 1749error = (int )written ; 1750 gotowrite_list_error ; 1751 } 1752 } 1753 }); 1754if ((error = file_flush (fp ))!= 0 ) { 1755 gotowrite_list_error ; 1756 } 1757return true; 1758write_list_error : 1759semsg (_ (e_error_while_writing_str ),os_strerror (error )); 1760return false; 1761} 1762 1763/// Write a blob to file with descriptor `fp`. 1764/// 1765/// @param[in] fp File to write to. 1766/// @param[in] blob Blob to write. 1767/// 1768/// @return true on success, or false on failure. 1769static bool write_data (FileDescriptor * const fp ,const char * const data ,const size_t len ) 1770FUNC_ATTR_NONNULL_ARG (1 ) 1771{ 1772int error = 0 ; 1773if (len > 0 ) { 1774const ptrdiff_t written = file_write (fp ,data ,len ); 1775if (written < (ptrdiff_t )len ) { 1776error = (int )written ; 1777 gotowrite_blob_error ; 1778 } 1779 } 1780error = file_flush (fp ); 1781if (error != 0 ) { 1782 gotowrite_blob_error ; 1783 } 1784return true; 1785write_blob_error : 1786semsg (_ (e_error_while_writing_str ),os_strerror (error )); 1787return false; 1788} 1789 1790static bool write_blob (FileDescriptor * const fp ,const blob_T * const blob ) 1791FUNC_ATTR_NONNULL_ALL 1792{ 1793return write_data (fp ,blob -> bv_ga .ga_data , (size_t )tv_blob_len (blob )); 1794} 1795 1796static bool write_string (FileDescriptor * const fp ,const char * const data ) 1797FUNC_ATTR_NONNULL_ALL 1798{ 1799return write_data (fp ,data ,strlen (data )); 1800} 1801 1802/// "writefile()" function 1803void f_writefile (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1804{ 1805rettv -> vval .v_number = -1 ; 1806 1807if (check_secure ()) { 1808return ; 1809 } 1810 1811// XXX: this logic is bit weird because of how `decode_string` works: #39328 1812// - if decode_string finds NUL in the Lua string, it assigns VAR_BLOB 1813// - else it assigns VAR_STRING 1814 1815if (argvars [0 ].v_type == VAR_LIST ) { 1816TV_LIST_ITER_CONST (argvars [0 ].vval .v_list ,li , { 1817if (!tv_check_str_or_nr (TV_LIST_ITEM_TV (li ))) { 1818return ; 1819 } 1820 }); 1821 }else if (argvars [0 ].v_type != VAR_BLOB 1822// Always treat Lua/RPC strings as "blob" data. 1823&& !(argvars [0 ].v_type == VAR_STRING 1824&& (script_is_lua (current_sctx .sc_sid ) 1825|| current_sctx .sc_sid == SID_API_CLIENT ))) { 1826semsg (_ (e_invarg2 ),_ ("writefile() first argument must be a List or a Blob" )); 1827return ; 1828 } 1829 1830bool binary = false; 1831bool append = false; 1832bool defer = false; 1833bool do_fsync = !!p_fs ; 1834bool mkdir_p = false; 1835if (argvars [2 ].v_type != VAR_UNKNOWN ) { 1836const char * const flags = tv_get_string_chk (& argvars [2 ]); 1837if (flags == NULL ) { 1838return ; 1839 } 1840for (const char * p = flags ;* p ;p ++ ) { 1841switch (* p ) { 1842case 'b' : 1843binary = true;break ; 1844case 'a' : 1845append = true;break ; 1846case 'D' : 1847defer = true;break ; 1848case 's' : 1849do_fsync = true;break ; 1850case 'S' : 1851do_fsync = false;break ; 1852case 'p' : 1853mkdir_p = true;break ; 1854default : 1855// Using %s, p and not %c, *p to preserve multibyte characters 1856semsg (_ ("E5060: Unknown flag: %s" ),p ); 1857return ; 1858 } 1859 } 1860 } 1861 1862char buf [NUMBUFLEN ]; 1863const char * const fname = tv_get_string_buf_chk (& argvars [1 ],buf ); 1864if (fname == NULL ) { 1865return ; 1866 } 1867 1868if (defer && !can_add_defer ()) { 1869return ; 1870 } 1871 1872FileDescriptor fp ; 1873int error ; 1874if (* fname == NUL ) { 1875emsg (_ ("E482: Can't open file with an empty name" )); 1876 }else if ((error = file_open (& fp ,fname , 1877 ((append ?kFileAppend :kFileTruncate ) 1878 | (mkdir_p ?kFileMkDir :kFileCreate ) 1879 |kFileCreate ),0666 ))!= 0 ) { 1880semsg (_ ("E482: Can't open file %s for writing: %s" ),fname ,os_strerror (error )); 1881 }else { 1882if (defer ) { 1883typval_T tv = { 1884 .v_type = VAR_STRING , 1885 .v_lock = VAR_UNLOCKED , 1886 .vval .v_string = FullName_save (fname , false), 1887 }; 1888add_defer ("delete" ,1 ,& tv ); 1889 } 1890 1891bool write_ok ; 1892if (argvars [0 ].v_type == VAR_BLOB ) { 1893write_ok = argvars [0 ].vval .v_blob == NULL || write_blob (& fp ,argvars [0 ].vval .v_blob ); 1894 }else if (argvars [0 ].v_type == VAR_STRING ) { 1895write_ok = write_string (& fp ,argvars [0 ].vval .v_string ); 1896 }else { 1897write_ok = write_list (& fp ,argvars [0 ].vval .v_list ,binary ); 1898 } 1899if (write_ok ) { 1900rettv -> vval .v_number = 0 ; 1901 } 1902if ((error = file_close (& fp ,do_fsync ))!= 0 ) { 1903semsg (_ ("E80: Error when closing file %s: %s" ), 1904fname ,os_strerror (error )); 1905 } 1906 } 1907} 1908 1909/// "browse(save, title, initdir, default)" function 1910void f_browse (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1911{ 1912rettv -> vval .v_string = NULL ; 1913rettv -> v_type = VAR_STRING ; 1914} 1915 1916/// "browsedir(title, initdir)" function 1917void f_browsedir (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1918{ 1919f_browse (argvars ,rettv ,fptr ); 1920}