robin/laufey

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

zeertzjqMerge pull request #41235 from janlazo/vim-8.2.157227e36dea19

master
53.0 KiB1920 linesraw
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,
70                 size_t *fnamelen, bool use_shellslash)
71{
72  int valid = 0;
73  char *s, *p, *pbuf;
74  char dirname[MAXPATHL];
75  bool has_fullname = false;
76  bool has_homerelative = false;
77  bool didit = false;
78
79repeat:
80  // ":p" - full path/file_name
81  if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p') {
82    has_fullname = true;
83
84    valid |= VALID_PATH;
85    *usedlen += 2;
86
87    // Expand "~/path" for all systems and "~user/path" for Unix
88    if ((*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);
98      xfree(*bufp);          // free any allocated file name
99      *bufp = *fnamep;
100      if (*fnamep == NULL) {
101        return -1;
102      }
103    }
104
105    // When "/." or "/.." is used: force expansion to get rid of it.
106    for (p = *fnamep; *p != NUL; MB_PTR_ADV(p)) {
107      if (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]))))) {
113        break;
114      }
115    }
116
117    // FullName_save() is slow, don't use it when not needed.
118    if (*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);
124      xfree(*bufp);          // free any allocated file name
125      *bufp = *fnamep;
126      if (*fnamep == NULL) {
127        return -1;
128      }
129    }
130
131    // Append a path separator to a directory.
132    if (os_isdir(*fnamep)) {
133      // Make room for one or two extra characters.
134      *fnamep = xstrnsave(*fnamep, strlen(*fnamep) + 2);
135      xfree(*bufp);          // free any allocated file name
136      *bufp = *fnamep;
137      add_pathsep(*fnamep);
138    }
139  }
140
141  int c;
142
143  // ":." - path relative to the current directory
144  // ":~" - path relative to the home directory
145  // ":8" - shortname path - postponed till after
146  while (src[*usedlen] == ':'
147         && ((c = (uint8_t)src[*usedlen + 1]) == '.' || c == '~' || c == '8')) {
148    *usedlen += 2;
149    if (c == '8') {
150      continue;
151    }
152    pbuf = NULL;
153    // Need full path first (use expand_env() to remove a "~/")
154    if (!has_fullname && !has_homerelative) {
155      if (**fnamep == '~') {
156        p = pbuf = expand_env_save(*fnamep);
157      } else {
158        p = pbuf = FullName_save(*fnamep, false);
159      }
160    } else {
161      p = *fnamep;
162    }
163
164    has_fullname = false;
165
166    if (p != NULL) {
167      size_t dirnamelen = 0;
168
169      if (c == '.') {
170        os_dirname(dirname, MAXPATHL);
171        if (has_homerelative) {
172          s = xstrdup(dirname);
173          dirnamelen = home_replace(NULL, s, dirname, MAXPATHL, true);
174          xfree(s);
175        }
176
177        if (dirnamelen == 0) {
178          dirnamelen = 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.
183        if (path_cmp(p_fic, p, dirname, dirnamelen) == 0) {
184          p += dirnamelen;
185          if (vim_ispathsep(*p)) {
186            while (*p && vim_ispathsep(*p)) {
187              p++;
188            }
189            *fnamep = p;
190            if (pbuf != NULL) {
191              // free any allocated file name
192              xfree(*bufp);
193              *bufp = pbuf;
194              pbuf = NULL;
195            }
196          }
197        }
198      } else {
199        dirnamelen = home_replace(NULL, p, dirname, MAXPATHL, true);
200        // Only replace it when it starts with '~'
201        if (*dirname == '~') {
202          s = xmemdupz(dirname, dirnamelen);
203          assert(s != NULL);  // suppress clang "Argument with 'nonnull' attribute passed null"
204          *fnamep = s;
205          xfree(*bufp);
206          *bufp = s;
207          has_homerelative = true;
208        }
209      }
210      xfree(pbuf);
211    }
212  }
213
214  FileInfo file_info;
215  os_fileinfo2(*fnamep, &file_info);
216  if (src[*usedlen] == ':' && src[*usedlen + 1] == 'h') {
217    s = *fnamep + file_info.rest_off;
218    *fnamep = *fnamep + file_info.prefix_off;
219  }
220
221  char *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`.
226  while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h') {
227    valid |= VALID_HEAD;
228    *usedlen += 2;
229    while (tail > s && after_pathsep(s, tail)) {
230      MB_PTR_BACK(*fnamep, tail);
231    }
232    *fnamelen = tail <= s ? (size_t)(s - *fnamep) : (size_t)(tail - *fnamep);
233    if (*fnamelen == 0) {
234      // Result is empty.  Turn it into "." to make ":cd %:h" work.
235      xfree(*bufp);
236      *bufp = *fnamep = tail = xstrdup(".");
237      s = *fnamep;  // s pointed into the freed buffer.
238      *fnamelen = 1;
239    } else {
240      while (tail > s && !after_pathsep(s, tail)) {
241        MB_PTR_BACK(*fnamep, tail);
242      }
243    }
244  }
245
246  // ":8" - shortname
247  if (src[*usedlen] == ':' && src[*usedlen + 1] == '8') {
248    *usedlen += 2;
249  }
250
251  // ":t" - tail, just the basename
252  if (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
260  while (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 '.'
265    const bool is_second_e = *fnamep > tail;
266    if (src[*usedlen + 1] == 'e' && is_second_e) {
267      s = (*fnamep) - 2;
268    } else {
269      s = (*fnamep) + *fnamelen - 1;
270    }
271
272    for (; s > tail; s--) {
273      if (s[0] == '.') {
274        break;
275      }
276    }
277    if (src[*usedlen + 1] == 'e') {
278      if (s > tail || (0 && is_second_e && s == tail)) {
279        // we stopped at a '.' (so anchor to &'.' + 1)
280        char *newstart = s + 1;
281        size_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
303      if (s > MAX(tail, *fnamep)) {
304        *fnamelen = (size_t)(s - *fnamep);
305      }
306    }
307    *usedlen += 2;
308  }
309
310#ifdef BACKSLASH_IN_FILENAME
311  if (!didit && use_shellslash && *fnamep != NULL) {
312    *fnamep = xstrdup(*fnamep);
313    slash_adjust(*fnamep);
314    xfree(*bufp);
315    *bufp = *fnamep;
316  }
317#endif
318
319  // ":s?pat?foo?" - substitute
320  // ":gs?pat?foo?" - global substitute
321  if (src[*usedlen] == ':'
322      && (src[*usedlen + 1] == 's'
323          || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's'))) {
324    char *flags = "";
325    s = src + *usedlen + 2;
326    if (src[*usedlen + 1] == 'g') {
327      flags = "g";
328      s++;
329    }
330
331    int sep = (uint8_t)(*s++);
332    if (sep) {
333      // find end of pattern
334      p = vim_strchr(s, sep);
335      if (p != NULL) {
336        char *const pat = xmemdupz(s, (size_t)(p - s));
337        s = p + 1;
338        // find end of substitution
339        p = vim_strchr(s, sep);
340        if (p != NULL) {
341          char *const sub = xmemdupz(s, (size_t)(p - s));
342          char *const str = xmemdupz(*fnamep, *fnamelen);
343          *usedlen = (size_t)(p + 1 - src);
344          size_t slen;
345          s = do_string_sub(str, *fnamelen, pat, sub, NULL, flags, &slen);
346          *fnamep = s;
347          *fnamelen = slen;
348          xfree(*bufp);
349          *bufp = s;
350          didit = true;
351          xfree(sub);
352          xfree(str);
353        }
354        xfree(pat);
355      }
356      // after using ":s", repeat all the modifiers
357      if (didit) {
358        goto repeat;
359      }
360    }
361  }
362
363  if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S') {
364    // vim_strsave_shellescape() needs a NUL terminated string.
365    c = (uint8_t)(*fnamep)[*fnamelen];
366    if (c != NUL) {
367      (*fnamep)[*fnamelen] = NUL;
368    }
369    p = vim_strsave_shellescape(*fnamep, false, false);
370    if (c != NUL) {
371      (*fnamep)[*fnamelen] = (char)c;
372    }
373    xfree(*bufp);
374    *bufp = *fnamep = p;
375    *fnamelen = strlen(p);
376    *usedlen += 2;
377  }
378
379  return valid;
380}
381
382/// "chdir(dir)" function
383void f_chdir(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
384{
385  rettv->v_type = VAR_STRING;
386  rettv->vval.v_string = NULL;
387
388  if (check_secure()) {
389    return;
390  }
391
392  if (argvars[0].v_type != VAR_STRING) {
393    // Returning an empty string means it failed.
394    // No error message, for historic reasons.
395    return;
396  }
397
398  // Return the current directory
399  char *cwd = xmalloc(MAXPATHL);
400  if (os_dirname(cwd, MAXPATHL) != FAIL) {
401#ifdef BACKSLASH_IN_FILENAME
402    slash_adjust(cwd);
403#endif
404    rettv->vval.v_string = xstrdup(cwd);
405  }
406  xfree(cwd);
407
408  CdScope scope = kCdScopeGlobal;
409  if (argvars[1].v_type != VAR_UNKNOWN) {
410    const char *s = tv_get_string(&argvars[1]);
411    if (strcmp(s, "global") == 0) {
412      scope = kCdScopeGlobal;
413    } else if (strcmp(s, "tabpage") == 0) {
414      scope = kCdScopeTabpage;
415    } else if (strcmp(s, "window") == 0) {
416      scope = kCdScopeWindow;
417    } else if (strcmp(s, "buffer") == 0) {
418      scope = kCdScopeBuffer;
419    } else {
420      semsg(_(e_invargNval), "scope", s);
421      return;
422    }
423  } else if (curbuf->b_localdir != NULL) {
424    scope = kCdScopeBuffer;
425  } else if (curwin->w_localdir != NULL) {
426    scope = kCdScopeWindow;
427  } else if (curtab->tp_localdir != NULL) {
428    scope = kCdScopeTabpage;
429  }
430
431  if (!do_chdir(argvars[0].vval.v_string, scope)) {
432    // Directory change failed
433    XFREE_CLEAR(rettv->vval.v_string);
434  }
435}
436
437/// "delete()" function
438void f_delete(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
439{
440  rettv->vval.v_number = -1;
441  if (check_secure()) {
442    return;
443  }
444
445  const char *const name = tv_get_string(&argvars[0]);
446  if (*name == NUL) {
447    emsg(_(e_invarg));
448    return;
449  }
450
451  char nbuf[NUMBUFLEN];
452  const char *flags;
453  if (argvars[1].v_type != VAR_UNKNOWN) {
454    flags = tv_get_string_buf(&argvars[1], nbuf);
455  } else {
456    flags = "";
457  }
458
459  if (*flags == NUL) {
460    // delete a file
461    rettv->vval.v_number = os_remove(name) == 0 ? 0 : -1;
462  } else if (strcmp(flags, "d") == 0) {
463    // delete an empty directory
464    rettv->vval.v_number = os_rmdir(name) == 0 ? 0 : -1;
465  } else if (strcmp(flags, "rf") == 0) {
466    // delete a directory recursively
467    rettv->vval.v_number = delete_recursive(name);
468  } else {
469    semsg(_(e_invexpr2), flags);
470  }
471}
472
473/// "executable()" function
474void f_executable(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
475{
476  if (tv_check_for_string_arg(argvars, 0) == FAIL) {
477    return;
478  }
479
480  // Check in $PATH and also check directly if there is a directory name
481  rettv->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{
487  if (tv_check_for_nonempty_string_arg(argvars, 0) == FAIL) {
488    return;
489  }
490
491  char *path = NULL;
492
493  os_can_exe(tv_get_string(&argvars[0]), &path, true);
494
495#ifdef BACKSLASH_IN_FILENAME
496  if (path != NULL) {
497    slash_adjust(path);
498  }
499#endif
500
501  rettv->v_type = VAR_STRING;
502  rettv->vval.v_string = path;
503}
504
505/// "filecopy()" function
506void f_filecopy(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
507{
508  rettv->vval.v_number = false;
509
510  if (check_secure()
511      || tv_check_for_string_arg(argvars, 0) == FAIL
512      || tv_check_for_string_arg(argvars, 1) == FAIL) {
513    return;
514  }
515
516  const char *from = tv_get_string(&argvars[0]);
517
518  FileInfo from_info;
519  if (os_fileinfo_link(from, &from_info)
520      && (S_ISREG(from_info.stat.st_mode) || S_ISLNK(from_info.stat.st_mode))) {
521    rettv->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{
529  const char *const p = tv_get_string(&argvars[0]);
530  rettv->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{
538  const char *filename = tv_get_string(&argvars[0]);
539  rettv->vval.v_number = os_file_is_writable(filename);
540}
541
542static void findfilendir(typval_T *argvars, typval_T *rettv, int find_what)
543{
544  char *fresult = NULL;
545  char *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
546  int count = 1;
547  bool first = true;
548  bool error = false;
549
550  rettv->vval.v_string = NULL;
551  rettv->v_type = VAR_STRING;
552
553  const char *fname = tv_get_string(&argvars[0]);
554
555  char pathbuf[NUMBUFLEN];
556  if (argvars[1].v_type != VAR_UNKNOWN) {
557    const char *p = tv_get_string_buf_chk(&argvars[1], pathbuf);
558    if (p == NULL) {
559      error = true;
560    } else {
561      if (*p != NUL) {
562        path = (char *)p;
563      }
564
565      if (argvars[2].v_type != VAR_UNKNOWN) {
566        count = (int)tv_get_number_chk(&argvars[2], &error);
567      }
568    }
569  }
570
571  if (count < 0) {
572    tv_list_alloc_ret(rettv, kListLenUnknown);
573  }
574
575  if (*fname != NUL && !error) {
576    char *file_to_find = NULL;
577    char *search_ctx = NULL;
578
579    do {
580      if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST) {
581        xfree(fresult);
582      }
583      fresult = find_file_in_path_option(first ? (char *)fname : NULL,
584                                         first ? strlen(fname) : 0,
585                                         0, first, path,
586                                         find_what, curbuf->b_ffname,
587                                         (find_what == FINDFILE_DIR
588                                          ? ""
589                                          : curbuf->b_p_sua),
590                                         &file_to_find, &search_ctx);
591      first = false;
592
593      if (fresult != NULL && rettv->v_type == VAR_LIST) {
594        tv_list_append_string(rettv->vval.v_list, fresult, -1);
595      }
596    } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
597
598    xfree(file_to_find);
599    vim_findfile_cleanup(search_ctx);
600  }
601
602  if (rettv->v_type == VAR_STRING) {
603    rettv->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{
610  findfilendir(argvars, rettv, FINDFILE_DIR);
611}
612
613/// "findfile({fname}[, {path}[, {count}]])" function
614void f_findfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
615{
616  findfilendir(argvars, rettv, FINDFILE_FILE);
617}
618
619/// "fnamemodify({fname}, {mods})" function
620void f_fnamemodify(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
621{
622  char *fbuf = NULL;
623  size_t len = 0;
624  char buf[NUMBUFLEN];
625  const char *fname = tv_get_string_chk(&argvars[0]);
626  const char *const mods = tv_get_string_buf_chk(&argvars[1], buf);
627  if (mods == NULL || fname == NULL) {
628    fname = NULL;
629  } else {
630    fbuf = TO_SLASH_SAVE(fname);
631    fname = fbuf;
632    len = strlen(fname);
633    if (*mods != NUL) {
634      size_t usedlen = 0;
635      modify_fname((char *)mods, false, &usedlen,
636                   (char **)&fname, &fbuf, &len, false);
637    }
638  }
639
640  rettv->v_type = VAR_STRING;
641  if (fname == NULL) {
642    rettv->vval.v_string = NULL;
643  } else {
644    rettv->vval.v_string = xmemdupz(fname, len);
645  }
646  xfree(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,
658                              tabpage_T **tp, buf_T **buf)
659{
660  enum { kWinArg, kTabArg, kBufArg, };
661  int argv[] = { 0, 0, 0 };
662  int argc = 0;
663
664  *scope = default_scope;
665  *win = curwin;
666  *tp = curtab;
667  *buf = curbuf;
668
669  for (; argc < 3; argc++) {
670    // If there is no argument there are no more scopes after it, break out.
671    if (argvars[argc].v_type == VAR_UNKNOWN) {
672      break;
673    }
674    if (argvars[argc].v_type != VAR_NUMBER) {
675      emsg(_(e_invarg));
676      return false;
677    }
678    argv[argc] = (int)argvars[argc].vval.v_number;
679    // It is an error for the scope number to be less than `-1`.
680    if (argv[argc] < -1) {
681      emsg(_(e_invarg));
682      return false;
683    }
684  }
685
686  // An argument may only be -1 if all preceding arguments are -1: `(2, 3, -1)` is an error.
687  bool explicit_scope = false;
688  for (int i = 0; i < argc; i++) {
689    explicit_scope = explicit_scope || argv[i] >= 0;
690    if (explicit_scope && argv[i] < 0) {
691      emsg(_("E5001: Argument cannot be -1 if preceding argument is >= 0."));
692      return false;
693    }
694  }
695
696  // Narrowest requested scope. Imagine X >= 0:
697  switch (argc) {
698  case 0:
699    break;
700  case 1:
701    if (argv[kWinArg] >= 0) {
702      *scope = kCdScopeWindow;  // (X)
703    } else {
704      *scope = kCdScopeTabpage;  // (-1)
705    }
706    break;
707  case 2:
708    if (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    }
715    break;
716  case 3:
717    if (argv[kBufArg] >= 0) {
718      *scope = kCdScopeBuffer;  // (-1, -1, X)
719    } else {
720      *scope = kCdScopeGlobal;  // (-1, -1, -1)
721    }
722    break;
723  }
724
725  if (*scope == kCdScopeBuffer) {
726    if (argv[kWinArg] >= 0 || argv[kTabArg] >= 0) {
727      emsg(_("E5006: Window and tab scope must be -1 when using buffer scope"));
728      return false;
729    }
730    if (argv[kBufArg] > 0) {
731      Error err = ERROR_INIT;
732      *buf = find_buffer_by_handle(argv[kBufArg], &err);
733      if (ERROR_SET(&err)) {
734        emsg(_("E5007: Cannot find buffer number."));
735        xfree(err.msg);
736        return false;
737      }
738    }
739  }
740
741  // Find the tabpage by number.
742  if (argv[kTabArg] > 0) {
743    *tp = find_tabpage(argv[kTabArg]);
744    if (*tp == NULL) {
745      emsg(_("E5000: Cannot find tab number."));
746      return false;
747    }
748  }
749
750  // Find the window in `tp` by number.
751  if (argv[kWinArg] > 0) {
752    *win = find_win_by_nr(&argvars[0], *tp);
753    if (*win == NULL) {
754      emsg(_("E5002: Cannot find window number."));
755      return false;
756    }
757  }
758
759  return 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{
773  CdScope scope;
774  win_T *win;
775  tabpage_T *tp;
776  buf_T *buf;
777
778  rettv->v_type = VAR_STRING;
779  rettv->vval.v_string = NULL;
780
781  // Without arguments (kCdScopeInvalid), the effective working directory is returned.
782  if (!getcwd_scope_args(argvars, kCdScopeInvalid, &scope, &win, &tp, &buf)) {
783    return;
784  }
785
786  char *from = NULL;  // The local directory to copy.
787  char *cwd = xmalloc(MAXPATHL);
788
789  switch (scope) {
790  case kCdScopeWindow:
791    from = win->w_localdir;
792    if (from) {
793      break;
794    }
795    FALLTHROUGH;
796  case kCdScopeTabpage:
797    from = tp->tp_localdir;
798    if (from) {
799      break;
800    }
801    FALLTHROUGH;
802  case 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.
805    from = scope == kCdScopeBuffer ? buf->b_localdir : NULL;
806    if (from) {
807      break;
808    }
809    FALLTHROUGH;
810  case kCdScopeGlobal:
811    if (globaldir) {        // `globaldir` is not always set.
812      from = globaldir;
813      break;
814    }
815    FALLTHROUGH;            // In global directory, just need to get OS CWD.
816  case kCdScopeInvalid:     // If called without any arguments, get OS CWD.
817    if (os_dirname(cwd, MAXPATHL) == FAIL) {
818      from = "";  // Return empty string on failure.
819    }
820  }
821
822  if (from) {
823    xstrlcpy(cwd, from, MAXPATHL);
824  }
825
826  rettv->vval.v_string = xstrdup(cwd);
827#ifdef BACKSLASH_IN_FILENAME
828  slash_adjust(rettv->vval.v_string);
829#endif
830
831  xfree(cwd);
832}
833
834/// "getfperm({fname})" function
835void f_getfperm(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
836{
837  char *perm = NULL;
838  char flags[] = "rwx";
839
840  const char *filename = tv_get_string(&argvars[0]);
841  int32_t file_perm = os_getperm(filename);
842  if (file_perm >= 0) {
843    perm = xstrdup("---------");
844    for (int i = 0; i < 9; i++) {
845      if (file_perm & (1 << (8 - i))) {
846        perm[i] = flags[i % 3];
847      }
848    }
849  }
850  rettv->v_type = VAR_STRING;
851  rettv->vval.v_string = perm;
852}
853
854/// "getfsize({fname})" function
855void f_getfsize(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
856{
857  const char *fname = tv_get_string(&argvars[0]);
858
859  FileInfo file_info;
860  if (os_fileinfo(fname, &file_info)) {
861    uint64_t filesize = os_fileinfo_size(&file_info);
862    if (os_isdir(fname)) {
863      rettv->vval.v_number = 0;
864    } else {
865      rettv->vval.v_number = (varnumber_T)filesize;
866
867      // non-perfect check for overflow
868      if ((uint64_t)rettv->vval.v_number != filesize) {
869        rettv->vval.v_number = -2;
870      }
871    }
872  } else {
873    rettv->vval.v_number = -1;
874  }
875}
876
877/// "getftime({fname})" function
878void f_getftime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
879{
880  const char *fname = tv_get_string(&argvars[0]);
881
882  FileInfo file_info;
883  if (os_fileinfo(fname, &file_info)) {
884    rettv->vval.v_number = (varnumber_T)file_info.stat.st_mtim.tv_sec;
885  } else {
886    rettv->vval.v_number = -1;
887  }
888}
889
890/// "getftype({fname})" function
891void f_getftype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
892{
893  char *type = NULL;
894  char *t;
895
896  const char *fname = tv_get_string(&argvars[0]);
897
898  rettv->v_type = VAR_STRING;
899  FileInfo file_info;
900  if (os_fileinfo_link(fname, &file_info)) {
901    uint64_t mode = file_info.stat.st_mode;
902    if (S_ISREG(mode)) {
903      t = "file";
904    } else if (S_ISDIR(mode)) {
905      t = "dir";
906    } else if (S_ISLNK(mode)) {
907      t = "link";
908    } else if (S_ISBLK(mode)) {
909      t = "bdev";
910    } else if (S_ISCHR(mode)) {
911      t = "cdev";
912    } else if (S_ISFIFO(mode)) {
913      t = "fifo";
914    } else if (S_ISSOCK(mode)) {
915      t = "socket";
916    } else {
917      t = "other";
918    }
919    type = xstrdup(t);
920  }
921  rettv->vval.v_string = type;
922}
923
924/// "glob()" function
925void f_glob(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
926{
927  int options = WILD_SILENT|WILD_USE_NL;
928  expand_T xpc;
929  bool 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.
933  rettv->v_type = VAR_STRING;
934  if (argvars[1].v_type != VAR_UNKNOWN) {
935    if (tv_get_bool_chk(&argvars[1], &error)) {
936      options |= WILD_KEEP_ALL;
937    }
938    if (argvars[2].v_type != VAR_UNKNOWN) {
939      if (tv_get_bool_chk(&argvars[2], &error)) {
940        tv_list_set_ret(rettv, NULL);
941      }
942      if (argvars[3].v_type != VAR_UNKNOWN
943          && tv_get_bool_chk(&argvars[3], &error)) {
944        options |= WILD_ALLLINKS;
945      }
946    }
947  }
948  if (!error) {
949    ExpandInit(&xpc);
950    xpc.xp_context = EXPAND_FILES;
951    if (p_wic) {
952      options += WILD_ICASE;
953    }
954    if (rettv->v_type == VAR_STRING) {
955      rettv->vval.v_string = ExpandOne(&xpc, (char *)
956                                       tv_get_string(&argvars[0]), NULL, options,
957                                       WILD_ALL);
958    } else {
959      ExpandOne(&xpc, (char *)tv_get_string(&argvars[0]), NULL, options,
960                WILD_ALL_KEEP);
961      tv_list_alloc_ret(rettv, xpc.xp_numfiles);
962      for (int i = 0; i < xpc.xp_numfiles; i++) {
963        tv_list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
964      }
965      ExpandCleanup(&xpc);
966    }
967  } else {
968    rettv->vval.v_string = NULL;
969  }
970}
971
972/// "globpath()" function
973void f_globpath(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
974{
975  int flags = 0;  // Flags for globpath.
976  bool error = false;
977
978  // Return a string, or a list if the optional third argument is non-zero.
979  rettv->v_type = VAR_STRING;
980
981  if (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.
984    if (tv_get_bool_chk(&argvars[2], &error)) {
985      flags |= WILD_KEEP_ALL;
986    }
987
988    if (argvars[3].v_type != VAR_UNKNOWN) {
989      if (tv_get_bool_chk(&argvars[3], &error)) {
990        tv_list_set_ret(rettv, NULL);
991      }
992      if (argvars[4].v_type != VAR_UNKNOWN
993          && tv_get_bool_chk(&argvars[4], &error)) {
994        flags |= WILD_ALLLINKS;
995      }
996    }
997  }
998
999  char buf1[NUMBUFLEN];
1000  const char *const file = tv_get_string_buf_chk(&argvars[1], buf1);
1001  if (file != NULL && !error) {
1002    garray_T ga;
1003    ga_init(&ga, (int)sizeof(char *), 10);
1004    globpath((char *)tv_get_string(&argvars[0]), (char *)file, &ga, flags, false);
1005
1006    if (rettv->v_type == VAR_STRING) {
1007      rettv->vval.v_string = ga_concat_strings(&ga, "\n");
1008    } else {
1009      tv_list_alloc_ret(rettv, ga.ga_len);
1010      for (int i = 0; i < ga.ga_len; i++) {
1011        tv_list_append_string(rettv->vval.v_list,
1012                              ((const char **)(ga.ga_data))[i], -1);
1013      }
1014    }
1015
1016    ga_clear_strings(&ga);
1017  } else {
1018    rettv->vval.v_string = NULL;
1019  }
1020}
1021
1022/// "glob2regpat()" function
1023void f_glob2regpat(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1024{
1025  const char *const pat = tv_get_string_chk(&argvars[0]);  // NULL on type error
1026
1027  rettv->v_type = VAR_STRING;
1028  rettv->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{
1043  CdScope scope;
1044  win_T *win;
1045  tabpage_T *tp;
1046  buf_T *buf;
1047
1048  rettv->v_type = VAR_NUMBER;
1049  rettv->vval.v_number = 0;
1050
1051  // Without arguments, default to window scope.
1052  if (!getcwd_scope_args(argvars, kCdScopeWindow, &scope, &win, &tp, &buf)) {
1053    return;
1054  }
1055
1056  switch (scope) {
1057  case kCdScopeWindow:
1058    rettv->vval.v_number = win->w_localdir != NULL;
1059    break;
1060  case kCdScopeBuffer:
1061    rettv->vval.v_number = buf->b_localdir != NULL;
1062    break;
1063  case kCdScopeTabpage:
1064    rettv->vval.v_number = tp->tp_localdir != NULL;
1065    break;
1066  case kCdScopeGlobal:
1067    // The global scope never has a local directory
1068    break;
1069  case kCdScopeInvalid:
1070    // We should never get here
1071    abort();
1072  }
1073}
1074
1075/// "isabsolutepath()" function
1076void f_isabsolutepath(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1077{
1078  rettv->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{
1084  rettv->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{
1090  int prot = 0755;
1091
1092  rettv->vval.v_number = FAIL;
1093  if (check_secure()) {
1094    return;
1095  }
1096
1097  char buf[NUMBUFLEN];
1098  const char *const dir = tv_get_string_buf(&argvars[0], buf);
1099  if (*dir == NUL) {
1100    return;
1101  }
1102
1103  if (*path_tail(dir) == NUL) {
1104    // Remove trailing slashes.
1105    *path_tail_with_sep((char *)dir) = NUL;
1106  }
1107
1108  bool defer = false;
1109  bool defer_recurse = false;
1110  char *created = NULL;
1111  if (argvars[1].v_type != VAR_UNKNOWN) {
1112    if (argvars[2].v_type != VAR_UNKNOWN) {
1113      prot = (int)tv_get_number_chk(&argvars[2], NULL);
1114      if (prot == -1) {
1115        return;
1116      }
1117    }
1118    const char *arg2 = tv_get_string(&argvars[1]);
1119    defer = vim_strchr(arg2, 'D') != NULL;
1120    defer_recurse = vim_strchr(arg2, 'R') != NULL;
1121    if ((defer || defer_recurse) && !can_add_defer()) {
1122      return;
1123    }
1124
1125    if (vim_strchr(arg2, 'p') != NULL) {
1126      char *failed_dir;
1127      int ret = os_mkdir_recurse(dir, prot, &failed_dir,
1128                                 defer || defer_recurse ? &created : NULL);
1129      if (ret != 0) {
1130        semsg(_(e_mkdir), failed_dir, os_strerror(ret));
1131        xfree(failed_dir);
1132        rettv->vval.v_number = FAIL;
1133        return;
1134      }
1135      rettv->vval.v_number = OK;
1136    }
1137  }
1138  if (rettv->vval.v_number == FAIL) {
1139    rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
1140  }
1141
1142  // Handle "D" and "R": deferred deletion of the created directory.
1143  if (rettv->vval.v_number == OK
1144      && created == NULL && (defer || defer_recurse)) {
1145    created = FullName_save(dir, false);
1146  }
1147  if (created != NULL) {
1148    typval_T tv[2];
1149    tv[0].v_type = VAR_STRING;
1150    tv[0].v_lock = VAR_UNLOCKED;
1151    tv[0].vval.v_string = created;
1152    tv[1].v_type = VAR_STRING;
1153    tv[1].v_lock = VAR_UNLOCKED;
1154    tv[1].vval.v_string = xstrdup(defer_recurse ? "rf" : "d");
1155    add_defer("delete", 2, tv);
1156  }
1157}
1158
1159/// "pathshorten()" function
1160void f_pathshorten(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1161{
1162  int trim_len = 1;
1163
1164  if (argvars[1].v_type != VAR_UNKNOWN) {
1165    trim_len = (int)tv_get_number(&argvars[1]);
1166    if (trim_len < 1) {
1167      trim_len = 1;
1168    }
1169  }
1170
1171  rettv->v_type = VAR_STRING;
1172  const char *p = tv_get_string_chk(&argvars[0]);
1173  if (p == NULL) {
1174    rettv->vval.v_string = NULL;
1175  } else {
1176    rettv->vval.v_string = xstrdup(p);
1177    shorten_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)
1183  FUNC_ATTR_NONNULL_ALL
1184{
1185  typval_T *expr = (typval_T *)context;
1186  typval_T argv[2];
1187  varnumber_T retval = 0;
1188  bool error = false;
1189
1190  if (expr->v_type == VAR_UNKNOWN) {
1191    return 1;
1192  }
1193
1194  typval_T save_val;
1195  prepare_vimvar(VV_VAL, &save_val);
1196  set_vim_var_string(VV_VAL, name, -1);
1197  argv[0].v_type = VAR_STRING;
1198  argv[0].vval.v_string = (char *)name;
1199
1200  typval_T rettv;
1201  if (eval_expr_typval(expr, false, argv, 1, &rettv) == FAIL) {
1202    goto theend;
1203  }
1204
1205  retval = tv_get_number_chk(&rettv, &error);
1206  if (error) {
1207    retval = -1;
1208  }
1209
1210  tv_clear(&rettv);
1211
1212theend:
1213  set_vim_var_string(VV_VAL, NULL, 0);
1214  restore_vimvar(VV_VAL, &save_val);
1215  return retval;
1216}
1217
1218/// "readdir()" function
1219void f_readdir(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1220{
1221  tv_list_alloc_ret(rettv, kListLenUnknown);
1222  if (check_secure()) {
1223    return;
1224  }
1225
1226  const char *path = tv_get_string(&argvars[0]);
1227  typval_T *expr = &argvars[1];
1228  garray_T ga;
1229  int ret = readdir_core(&ga, path, (void *)expr, readdir_checkitem);
1230  if (ret == OK && ga.ga_len > 0) {
1231    for (int i = 0; i < ga.ga_len; i++) {
1232      const char *p = ((const char **)ga.ga_data)[i];
1233      tv_list_append_string(rettv->vval.v_list, p, -1);
1234    }
1235  }
1236  ga_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)
1249  FUNC_ATTR_NONNULL_ALL
1250{
1251  blob_T *const blob = rettv->vval.v_blob;
1252  FileInfo file_info;
1253  if (!os_fileinfo_fd(fileno(fd), &file_info)) {
1254    return FAIL;  // can't read the file, error
1255  }
1256
1257  int whence;
1258  off_T size = size_arg;
1259  const off_T file_size = (off_T)os_fileinfo_size(&file_info);
1260  if (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.
1263    if (size == -1 || (size > file_size - offset && !S_ISCHR(file_info.stat.st_mode))) {
1264      // size may become negative, checked below
1265      size = (off_T)os_fileinfo_size(&file_info) - offset;
1266    }
1267    whence = SEEK_SET;
1268  } else {
1269    // limit the offset to not go before the start of the file
1270    if (-offset > file_size && !S_ISCHR(file_info.stat.st_mode)) {
1271      offset = -file_size;
1272    }
1273    // Size defaults to reading until the end of the file.
1274    if (size == -1 || size > -offset) {
1275      size = -offset;
1276    }
1277    whence = SEEK_END;
1278  }
1279  if (size <= 0) {
1280    return OK;
1281  }
1282  if (offset != 0 && vim_fseek(fd, offset, whence) != 0) {
1283    return OK;
1284  }
1285
1286  ga_grow(&blob->bv_ga, (int)size);
1287  blob->bv_ga.ga_len = (int)size;
1288  if (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.
1291    tv_blob_free(rettv->vval.v_blob);
1292    rettv->vval.v_blob = NULL;
1293    return FAIL;
1294  }
1295  return OK;
1296}
1297
1298/// "readfile()" or "readblob()" function
1299static void read_file_or_blob(typval_T *argvars, typval_T *rettv, bool always_blob)
1300{
1301  bool binary = false;
1302  bool blob = always_blob;
1303  FILE *fd;
1304  char buf[(IOSIZE/256) * 256];    // rounded to avoid odd + 1
1305  int io_size = sizeof(buf);
1306  char *prev = NULL;               // previously read bytes, if any
1307  ptrdiff_t prevlen = 0;               // length of data in prev
1308  ptrdiff_t prevsize = 0;               // size of prev buffer
1309  int64_t maxline = MAXLNUM;
1310  off_T offset = 0;
1311  off_T size = -1;
1312
1313  if (argvars[1].v_type != VAR_UNKNOWN) {
1314    if (always_blob) {
1315      offset = (off_T)tv_get_number(&argvars[1]);
1316      if (argvars[2].v_type != VAR_UNKNOWN) {
1317        size = (off_T)tv_get_number(&argvars[2]);
1318      }
1319    } else {
1320      if (strcmp(tv_get_string(&argvars[1]), "b") == 0) {
1321        binary = true;
1322      } else if (strcmp(tv_get_string(&argvars[1]), "B") == 0) {
1323        blob = true;
1324      }
1325      if (argvars[2].v_type != VAR_UNKNOWN) {
1326        maxline = tv_get_number(&argvars[2]);
1327      }
1328    }
1329  }
1330
1331  if (blob) {
1332    tv_blob_alloc_ret(rettv);
1333  } else {
1334    tv_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.
1339  const char *const fname = tv_get_string(&argvars[0]);
1340
1341  if (os_isdir(fname)) {
1342    semsg(_(e_isadir2), fname);
1343    return;
1344  }
1345  if (*fname == NUL || (fd = os_fopen(fname, READBIN)) == NULL) {
1346    semsg(_(e_notopen), *fname == NUL ? _("<empty>") : fname);
1347    return;
1348  }
1349
1350  if (blob) {
1351    if (read_blob(fd, rettv, offset, size) == FAIL) {
1352      semsg(_(e_cant_read_file_str), fname);
1353    }
1354    fclose(fd);
1355    return;
1356  }
1357
1358  list_T *const l = rettv->vval.v_list;
1359
1360  while (maxline < 0 || tv_list_len(l) < maxline) {
1361    int 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.
1368    char *p;  // Position in buf.
1369    char *start;  // Start of current line.
1370    for (p = buf, start = buf;
1371         p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1372         p++) {
1373      if (readlen <= 0 || *p == '\n') {
1374        char *s = NULL;
1375        size_t len = (size_t)(p - start);
1376
1377        // Finished a line.  Remove CRs before NL.
1378        if (readlen > 0 && !binary) {
1379          while (len > 0 && start[len - 1] == '\r') {
1380            len--;
1381          }
1382          // removal may cross back to the "prev" string
1383          if (len == 0) {
1384            while (prevlen > 0 && prev[prevlen - 1] == '\r') {
1385              prevlen--;
1386            }
1387          }
1388        }
1389        if (prevlen == 0) {
1390          assert(len < INT_MAX);
1391          s = 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.
1396          s = xrealloc(prev, (size_t)prevlen + len + 1);
1397          memcpy(s + prevlen, start, len);
1398          s[(size_t)prevlen + len] = NUL;
1399          prev = NULL;             // the list will own the string
1400          prevlen = prevsize = 0;
1401        }
1402
1403        tv_list_append_owned_tv(l, (typval_T) {
1404          .v_type = VAR_STRING,
1405          .v_lock = VAR_UNLOCKED,
1406          .vval.v_string = s,
1407        });
1408
1409        start = p + 1;  // Step over newline.
1410        if (maxline < 0) {
1411          if (tv_list_len(l) > -maxline) {
1412            assert(tv_list_len(l) == 1 + (-maxline));
1413            tv_list_item_remove(l, tv_list_first(l));
1414          }
1415        } else if (tv_list_len(l) >= maxline) {
1416          assert(tv_list_len(l) == maxline);
1417          break;
1418        }
1419        if (readlen <= 0) {
1420          break;
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.
1429        char back1 = p >= buf + 1 ? p[-1]
1430                                  : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1431        char back2 = p >= buf + 2 ? p[-2]
1432                                  : (p == buf + 1 && prevlen >= 1
1433                                     ? prev[prevlen - 1]
1434                                     : prevlen >= 2 ? prev[prevlen - 2] : NUL);
1435
1436        if ((uint8_t)back2 == 0xef && (uint8_t)back1 == 0xbb) {
1437          char *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.
1441          if (start == dest) {
1442            start = p + 1;
1443          } else {
1444            // have to shuffle buf to close gap
1445            int adjust_prevlen = 0;
1446
1447            if (dest < buf) {
1448              // adjust_prevlen must be 1 or 2.
1449              adjust_prevlen = (int)(buf - dest);
1450              dest = buf;
1451            }
1452            if (readlen > p - buf + 1) {
1453              memmove(dest, p + 1, (size_t)readlen - (size_t)(p - buf) - 1);
1454            }
1455            readlen -= 3 - adjust_prevlen;
1456            prevlen -= adjust_prevlen;
1457            p = dest - 1;
1458          }
1459        }
1460      }
1461    }     // for
1462
1463    if ((maxline >= 0 && tv_list_len(l) >= maxline) || readlen <= 0) {
1464      break;
1465    }
1466    if (start < p) {
1467      // There's part of a line in buf, store it in "prev".
1468      if (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.
1473        if (prevsize == 0) {
1474          prevsize = p - start;
1475        } else {
1476          ptrdiff_t grow50pc = (prevsize * 3) / 2;
1477          ptrdiff_t growmin = (p - start) * 2 + prevlen;
1478          prevsize = grow50pc > growmin ? grow50pc : growmin;
1479        }
1480        prev = xrealloc(prev, (size_t)prevsize);
1481      }
1482      // Add the line part to end of "prev".
1483      memmove(prev + prevlen, start, (size_t)(p - start));
1484      prevlen += p - start;
1485    }
1486  }   // while
1487
1488  xfree(prev);
1489  fclose(fd);
1490}
1491
1492/// "readblob()" function
1493void f_readblob(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1494{
1495  if (check_secure()) {
1496    return;
1497  }
1498
1499  read_file_or_blob(argvars, rettv, true);
1500}
1501
1502/// "readfile()" function
1503void f_readfile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1504{
1505  if (check_secure()) {
1506    return;
1507  }
1508
1509  read_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{
1515  if (check_secure()) {
1516    rettv->vval.v_number = -1;
1517  } else {
1518    char buf[NUMBUFLEN];
1519    rettv->vval.v_number = vim_rename(tv_get_string(&argvars[0]),
1520                                      tv_get_string_buf(&argvars[1], buf));
1521  }
1522}
1523
1524/// "resolve()" function
1525void f_resolve(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1526{
1527  rettv->v_type = VAR_STRING;
1528  const char *fname = tv_get_string(&argvars[0]);
1529#ifdef MSWIN
1530  char *v = os_resolve_shortcut(fname);
1531  if (v == NULL) {
1532    if (os_is_reparse_point_include(fname)) {
1533      v = os_realpath(fname, NULL, MAXPATHL + 1);
1534    }
1535  }
1536  rettv->vval.v_string = (v == NULL ? xstrdup(fname) : v);
1537#else
1538# ifdef HAVE_READLINK
1539  {
1540    bool is_relative_to_current = false;
1541    bool has_trailing_pathsep = false;
1542    int limit = 100;
1543
1544    char *p = xstrdup(fname);
1545
1546    if (p[0] == '.' && (vim_ispathsep(p[1])
1547                        || (p[1] == '.' && (vim_ispathsep(p[2]))))) {
1548      is_relative_to_current = true;
1549    }
1550
1551    ptrdiff_t len = (ptrdiff_t)strlen(p);
1552    if (len > 1 && after_pathsep(p, p + len)) {
1553      has_trailing_pathsep = true;
1554      p[len - 1] = NUL;  // The trailing slash breaks readlink().
1555    }
1556
1557    char *q = (char *)path_next_component(p);
1558    char *remain = NULL;
1559    if (*q != NUL) {
1560      // Separate the first path component in "p", and keep the
1561      // remainder (beginning with the path separator).
1562      remain = xstrdup(q - 1);
1563      q[-1] = NUL;
1564    }
1565
1566    char *const buf = xmallocz(MAXPATHL);
1567
1568    char *cpy;
1569    while (true) {
1570      while (true) {
1571        len = readlink(p, buf, MAXPATHL);
1572        if (len <= 0) {
1573          break;
1574        }
1575        buf[len] = NUL;
1576
1577        if (limit-- == 0) {
1578          xfree(p);
1579          xfree(remain);
1580          emsg(_("E655: Too many symbolic links (cycle?)"));
1581          rettv->vval.v_string = NULL;
1582          xfree(buf);
1583          return;
1584        }
1585
1586        // Ensure that the result will have a trailing path separator
1587        // if the argument has one.
1588        if (remain == NULL && has_trailing_pathsep) {
1589          add_pathsep(buf);
1590        }
1591
1592        // Separate the first path component in the link value and
1593        // concatenate the remainders.
1594        q = (char *)path_next_component(vim_ispathsep(*buf) ? buf + 1 : buf);
1595        if (*q != NUL) {
1596          cpy = remain;
1597          remain = remain != NULL ? concat_str(q - 1, remain) : xstrdup(q - 1);
1598          xfree(cpy);
1599          q[-1] = NUL;
1600        }
1601
1602        q = path_tail(p);
1603        if (q > p && *q == NUL) {
1604          // Ignore trailing path separator.
1605          p[q - p - 1] = NUL;
1606          q = path_tail(p);
1607        }
1608        if (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.
1611          const size_t p_len = strlen(p);
1612          const size_t buf_len = strlen(buf);
1613          p = xrealloc(p, p_len + buf_len + 1);
1614          memcpy(path_tail(p), buf, buf_len + 1);
1615        } else {
1616          xfree(p);
1617          p = xstrdup(buf);
1618        }
1619      }
1620
1621      if (remain == NULL) {
1622        break;
1623      }
1624
1625      // Append the first path component of "remain" to "p".
1626      q = (char *)path_next_component(remain + 1);
1627      len = q - remain - (*q != NUL);
1628      const size_t p_len = strlen(p);
1629      cpy = xmallocz(p_len + (size_t)len);
1630      memcpy(cpy, p, p_len + 1);
1631      xstrlcat(cpy + p_len, remain, (size_t)len + 1);
1632      xfree(p);
1633      p = cpy;
1634
1635      // Shorten "remain".
1636      if (*q != NUL) {
1637        STRMOVE(remain, q - 1);
1638      } else {
1639        XFREE_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.
1645    if (!vim_ispathsep(*p)) {
1646      if (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 "./".
1655        cpy = concat_str("./", p);
1656        xfree(p);
1657        p = cpy;
1658      } else if (!is_relative_to_current) {
1659        // Strip leading "./".
1660        q = p;
1661        while (q[0] == '.' && vim_ispathsep(q[1])) {
1662          q += 2;
1663        }
1664        if (q > p) {
1665          STRMOVE(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 "//".
1672    if (!has_trailing_pathsep) {
1673      q = p + strlen(p);
1674      if (after_pathsep(p, q)) {
1675        *path_tail_with_sep(p) = NUL;
1676      }
1677    }
1678
1679    rettv->vval.v_string = p;
1680    xfree(buf);
1681  }
1682# else
1683  char *v = os_realpath(fname, NULL, MAXPATHL + 1);
1684  rettv->vval.v_string = v == NULL ? xstrdup(fname) : v;
1685# endif
1686#endif
1687
1688  simplify_filename(rettv->vval.v_string);
1689}
1690
1691/// "simplify()" function
1692void f_simplify(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1693{
1694  const char *const p = tv_get_string(&argvars[0]);
1695  rettv->vval.v_string = xstrdup(p);
1696  simplify_filename(rettv->vval.v_string);  // Simplify in place.
1697  rettv->v_type = VAR_STRING;
1698}
1699
1700/// "tempname()" function
1701void f_tempname(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1702{
1703  rettv->v_type = VAR_STRING;
1704  rettv->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)
1715  FUNC_ATTR_NONNULL_ARG(1)
1716{
1717  int error = 0;
1718  TV_LIST_ITER_CONST(list, li, {
1719    const char *const s = tv_get_string_chk(TV_LIST_ITEM_TV(li));
1720    if (s == NULL) {
1721      return false;
1722    }
1723    const char *hunk_start = s;
1724    for (const char *p = hunk_start;; p++) {
1725      if (*p == NUL || *p == NL) {
1726        if (p != hunk_start) {
1727          const ptrdiff_t written = file_write(fp, hunk_start,
1728                                               (size_t)(p - hunk_start));
1729          if (written < 0) {
1730            error = (int)written;
1731            goto write_list_error;
1732          }
1733        }
1734        if (*p == NUL) {
1735          break;
1736        } else {
1737          hunk_start = p + 1;
1738          const ptrdiff_t written = file_write(fp, (char[]){ NUL }, 1);
1739          if (written < 0) {
1740            error = (int)written;
1741            break;
1742          }
1743        }
1744      }
1745    }
1746    if (!binary || TV_LIST_ITEM_NEXT(list, li) != NULL) {
1747      const ptrdiff_t written = file_write(fp, "\n", 1);
1748      if (written < 0) {
1749        error = (int)written;
1750        goto write_list_error;
1751      }
1752    }
1753  });
1754  if ((error = file_flush(fp)) != 0) {
1755    goto write_list_error;
1756  }
1757  return true;
1758write_list_error:
1759  semsg(_(e_error_while_writing_str), os_strerror(error));
1760  return 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)
1770  FUNC_ATTR_NONNULL_ARG(1)
1771{
1772  int error = 0;
1773  if (len > 0) {
1774    const ptrdiff_t written = file_write(fp, data, len);
1775    if (written < (ptrdiff_t)len) {
1776      error = (int)written;
1777      goto write_blob_error;
1778    }
1779  }
1780  error = file_flush(fp);
1781  if (error != 0) {
1782    goto write_blob_error;
1783  }
1784  return true;
1785write_blob_error:
1786  semsg(_(e_error_while_writing_str), os_strerror(error));
1787  return false;
1788}
1789
1790static bool write_blob(FileDescriptor *const fp, const blob_T *const blob)
1791  FUNC_ATTR_NONNULL_ALL
1792{
1793  return 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)
1797  FUNC_ATTR_NONNULL_ALL
1798{
1799  return write_data(fp, data, strlen(data));
1800}
1801
1802/// "writefile()" function
1803void f_writefile(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1804{
1805  rettv->vval.v_number = -1;
1806
1807  if (check_secure()) {
1808    return;
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
1815  if (argvars[0].v_type == VAR_LIST) {
1816    TV_LIST_ITER_CONST(argvars[0].vval.v_list, li, {
1817      if (!tv_check_str_or_nr(TV_LIST_ITEM_TV(li))) {
1818        return;
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))) {
1826    semsg(_(e_invarg2), _("writefile() first argument must be a List or a Blob"));
1827    return;
1828  }
1829
1830  bool binary = false;
1831  bool append = false;
1832  bool defer = false;
1833  bool do_fsync = !!p_fs;
1834  bool mkdir_p = false;
1835  if (argvars[2].v_type != VAR_UNKNOWN) {
1836    const char *const flags = tv_get_string_chk(&argvars[2]);
1837    if (flags == NULL) {
1838      return;
1839    }
1840    for (const char *p = flags; *p; p++) {
1841      switch (*p) {
1842      case 'b':
1843        binary = true; break;
1844      case 'a':
1845        append = true; break;
1846      case 'D':
1847        defer = true; break;
1848      case 's':
1849        do_fsync = true; break;
1850      case 'S':
1851        do_fsync = false; break;
1852      case 'p':
1853        mkdir_p = true; break;
1854      default:
1855        // Using %s, p and not %c, *p to preserve multibyte characters
1856        semsg(_("E5060: Unknown flag: %s"), p);
1857        return;
1858      }
1859    }
1860  }
1861
1862  char buf[NUMBUFLEN];
1863  const char *const fname = tv_get_string_buf_chk(&argvars[1], buf);
1864  if (fname == NULL) {
1865    return;
1866  }
1867
1868  if (defer && !can_add_defer()) {
1869    return;
1870  }
1871
1872  FileDescriptor fp;
1873  int error;
1874  if (*fname == NUL) {
1875    emsg(_("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) {
1880    semsg(_("E482: Can't open file %s for writing: %s"), fname, os_strerror(error));
1881  } else {
1882    if (defer) {
1883      typval_T tv = {
1884        .v_type = VAR_STRING,
1885        .v_lock = VAR_UNLOCKED,
1886        .vval.v_string = FullName_save(fname, false),
1887      };
1888      add_defer("delete", 1, &tv);
1889    }
1890
1891    bool write_ok;
1892    if (argvars[0].v_type == VAR_BLOB) {
1893      write_ok = argvars[0].vval.v_blob == NULL || write_blob(&fp, argvars[0].vval.v_blob);
1894    } else if (argvars[0].v_type == VAR_STRING) {
1895      write_ok = write_string(&fp, argvars[0].vval.v_string);
1896    } else {
1897      write_ok = write_list(&fp, argvars[0].vval.v_list, binary);
1898    }
1899    if (write_ok) {
1900      rettv->vval.v_number = 0;
1901    }
1902    if ((error = file_close(&fp, do_fsync)) != 0) {
1903      semsg(_("E80: Error when closing file %s: %s"),
1904            fname, 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{
1912  rettv->vval.v_string = NULL;
1913  rettv->v_type = VAR_STRING;
1914}
1915
1916/// "browsedir(title, initdir)" function
1917void f_browsedir(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1918{
1919  f_browse(argvars, rettv, fptr);
1920}