robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
41.7 KiB1561 linesraw
1// fs.c -- filesystem access
2#include <assert.h>
3#include <errno.h>
4#include <fcntl.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#include <sys/types.h>
13#include <uv.h>
14
15#ifdef MSWIN
16# include <io.h>
17# include <shlobj.h>
18#endif
19
20#include "auto/config.h"
21#include "nvim/os/fs.h"
22#include "nvim/os/os_defs.h"
23
24#ifdef HAVE_ACL
25# ifdef HAVE_SYS_ACL_H
26#  include <sys/acl.h>
27# endif
28# ifdef HAVE_SYS_ACCESS_H
29#  include <sys/access.h>
30# endif
31#endif
32
33#ifdef HAVE_XATTR
34# include <sys/xattr.h>
35#endif
36
37#include "nvim/api/private/helpers.h"
38#include "nvim/ascii_defs.h"
39#include "nvim/errors.h"
40#include "nvim/gettext_defs.h"
41#include "nvim/globals.h"
42#include "nvim/log.h"
43#include "nvim/macros_defs.h"
44#include "nvim/memory.h"
45#include "nvim/message.h"
46#include "nvim/option_vars.h"
47#include "nvim/os/os.h"
48#include "nvim/path.h"
49#include "nvim/types_defs.h"
50#include "nvim/ui.h"
51#include "nvim/vim_defs.h"
52
53#ifdef HAVE_SYS_UIO_H
54# include <sys/uio.h>
55#endif
56
57#ifdef MSWIN
58# include "nvim/mbyte.h"
59# include "nvim/option.h"
60# include "nvim/os/os_win_console.h"
61# include "nvim/strings.h"
62#endif
63
64#include "os/fs.c.generated.h"
65
66#ifdef HAVE_XATTR
67static const char e_xattr_erange[]
68  = N_("E1506: Buffer too small to copy xattr value or key");
69static const char e_xattr_e2big[]
70  = N_("E1508: Size of the extended attribute value is larger than the maximum size allowed");
71static const char e_xattr_other[]
72  = N_("E1509: Error occurred when reading or writing extended attribute");
73#endif
74
75#define RUN_UV_FS_FUNC(ret, func, ...) \
76  do { \
77    uv_fs_t req; \
78    ret = func(NULL, &req, __VA_ARGS__); \
79    uv_fs_req_cleanup(&req); \
80  } while (0)
81
82// Many fs functions from libuv return that value on success.
83static const int kLibuvSuccess = 0;
84
85/// Changes the current directory to `path`.
86///
87/// @return 0 on success, or negative error code.
88int os_chdir(const char *path)
89  FUNC_ATTR_NONNULL_ALL
90{
91  if (p_verbose >= 5) {
92    verbose_enter();
93    smsg(0, "chdir(%s)", path);
94    verbose_leave();
95  }
96  int err = uv_chdir(path);
97  if (err == 0) {
98    ui_call_chdir(cstr_as_string(path));
99  }
100  return err;
101}
102
103/// Get the name of current directory.
104///
105/// @param buf Buffer to store the directory name.
106/// @param len Length of `buf`.
107/// @return `OK` for success, `FAIL` for failure.
108int os_dirname(char *buf, size_t len)
109  FUNC_ATTR_NONNULL_ALL
110{
111  int error_number;
112  if ((error_number = uv_cwd(buf, &len)) != kLibuvSuccess) {
113    xstrlcpy(buf, uv_strerror(error_number), len);
114    return FAIL;
115  }
116  TO_SLASH(buf);
117  return OK;
118}
119
120/// Check if the given path is a directory and not a symlink to a directory.
121/// @return `true` if `name` is a directory and NOT a symlink to a directory.
122///         `false` if `name` is not a directory or if an error occurred.
123bool os_isrealdir(const char *name)
124  FUNC_ATTR_NONNULL_ALL
125{
126  uv_fs_t request;
127  if (uv_fs_lstat(NULL, &request, name, NULL) != kLibuvSuccess) {
128    return false;
129  }
130  if (S_ISLNK(request.statbuf.st_mode)) {
131    return false;
132  }
133  return S_ISDIR(request.statbuf.st_mode);
134}
135
136/// Check if the given path exists and is a directory.
137///
138/// @return `true` if `name` is a directory.
139bool os_isdir(const char *name)
140  FUNC_ATTR_NONNULL_ALL
141{
142  int32_t mode = os_getperm(name);
143  if (mode < 0) {
144    return false;
145  }
146
147  return S_ISDIR(mode);
148}
149
150/// Check what `name` is:
151/// @return NODE_NORMAL: file or directory (or doesn't exist)
152///         NODE_WRITABLE: writable device, socket, fifo, etc.
153///         NODE_OTHER: non-writable things
154int os_nodetype(const char *name)
155  FUNC_ATTR_NONNULL_ALL
156{
157#ifndef MSWIN  // Unix
158  uv_stat_t statbuf;
159  if (0 != os_stat(name, &statbuf)) {
160    return NODE_NORMAL;  // File doesn't exist.
161  }
162  // uv_handle_type does not distinguish BLK and DIR.
163  //    Related: https://github.com/joyent/libuv/pull/1421
164  if (S_ISREG(statbuf.st_mode) || S_ISDIR(statbuf.st_mode)) {
165    return NODE_NORMAL;
166  }
167  if (S_ISBLK(statbuf.st_mode)) {  // block device isn't writable
168    return NODE_OTHER;
169  }
170  // Everything else is writable?
171  // buf_write() expects NODE_WRITABLE for char device /dev/stderr.
172  return NODE_WRITABLE;
173#else  // Windows
174  // Edge case from Vim os_win32.c:
175  // We can't open a file with a name "\\.\con" or "\\.\prn", trying to read
176  // from it later will cause Vim to hang. Thus return NODE_WRITABLE here.
177  if (strncmp(name, "\\\\.\\", 4) == 0) {
178    return NODE_WRITABLE;
179  }
180
181  // Vim os_win32.c:mch_nodetype does (since 7.4.015):
182  //    wn = enc_to_utf16(name, NULL);
183  //    hFile = CreatFile(wn, ...)
184  // to get a HANDLE. Whereas libuv just calls _get_osfhandle() on the fd we
185  // give it. But uv_fs_open later calls fs__capture_path which does a similar
186  // utf8-to-utf16 dance and saves us the hassle.
187
188  // macOS: os_open(/dev/stderr) would return UV_EACCES.
189  int fd = os_open(name, O_RDONLY
190# ifdef O_NONBLOCK
191                   | O_NONBLOCK
192# endif
193                   , 0);
194  if (fd < 0) {  // open() failed.
195    return NODE_NORMAL;
196  }
197  int guess = uv_guess_handle(fd);
198  if (close(fd) == -1) {
199    ELOG("close(%d) failed. name='%s'", fd, name);
200  }
201
202  switch (guess) {
203  case UV_TTY:          // FILE_TYPE_CHAR
204    return NODE_WRITABLE;
205  case UV_FILE:         // FILE_TYPE_DISK
206    return NODE_NORMAL;
207  case UV_NAMED_PIPE:   // not handled explicitly in Vim os_win32.c
208  case UV_UDP:          // unix only
209  case UV_TCP:          // unix only
210  case UV_UNKNOWN_HANDLE:
211  default:
212    return NODE_OTHER;  // Vim os_win32.c default
213  }
214#endif
215}
216
217/// Gets the absolute path of the currently running executable.
218/// May fail if procfs is missing. #6734
219/// @see path_exepath
220///
221/// @param[out] buffer Full path to the executable.
222/// @param[in]  size   Size of `buffer`.
223///
224/// @return 0 on success, or libuv error code.
225int os_exepath(char *buffer, size_t *size)
226  FUNC_ATTR_NONNULL_ALL
227{
228  int r = uv_exepath(buffer, size);
229  TO_SLASH(buffer);
230  return r;
231}
232
233/// Checks if the file `name` is executable.
234///
235/// @param[in]  name     Filename to check.
236/// @param[out,allocated] abspath  Returns resolved exe path, if not NULL.
237/// @param[in] use_path  Also search $PATH.
238///
239/// @return true if `name` is executable and
240///   - can be found in $PATH,
241///   - is relative to current dir or
242///   - is absolute.
243///
244/// @return `false` otherwise.
245bool os_can_exe(const char *name, char **abspath, bool use_path)
246  FUNC_ATTR_NONNULL_ARG(1)
247{
248  if (!use_path || gettail_dir(name) != name) {
249#ifdef MSWIN
250    return is_executable_ext(name, abspath);
251#else
252    // Must have path separator, cannot execute files in the current directory.
253    return ((use_path || gettail_dir(name) != name)
254            && is_executable(name, abspath));
255#endif
256    return false;
257  }
258
259  return is_executable_in_path(name, abspath);
260}
261
262/// Returns true if `name` is an executable file.
263///
264/// @param[in]            name     Filename to check.
265/// @param[out,allocated] abspath  Returns full exe path, if not NULL.
266static bool is_executable(const char *name, char **abspath)
267  FUNC_ATTR_NONNULL_ARG(1)
268{
269  int32_t mode = os_getperm(name);
270
271  if (mode < 0) {
272    return false;
273  }
274
275#ifdef MSWIN
276  // Windows does not have exec bit; just check if the file exists and is not
277  // a directory.
278  const bool ok = S_ISREG(mode);
279#else
280  int r = -1;
281  if (S_ISREG(mode)) {
282    RUN_UV_FS_FUNC(r, uv_fs_access, name, X_OK, NULL);
283  }
284  const bool ok = (r == 0);
285#endif
286  if (ok && abspath != NULL) {
287    *abspath = save_abs_path(name);
288  }
289  return ok;
290}
291
292#ifdef MSWIN
293/// Checks if file `name` is executable under any of these conditions:
294/// - extension is in $PATHEXT and `name` is executable
295/// - result of any $PATHEXT extension appended to `name` is executable
296static bool is_executable_ext(const char *name, char **abspath)
297  FUNC_ATTR_NONNULL_ARG(1)
298{
299  const bool is_unix_shell = strstr(path_tail(p_sh), "powershell") == NULL
300                             && strstr(path_tail(p_sh), "pwsh") == NULL
301                             && strstr(path_tail(p_sh), "sh") != NULL;
302  char *nameext = strrchr(name, '.');
303  size_t nameext_len = nameext ? strlen(nameext) : 0;
304  xstrlcpy(os_buf, name, sizeof(os_buf));
305  char *buf_end = xstrchrnul(os_buf, NUL);
306  const char *pathext = os_getenv_noalloc("PATHEXT");
307  if (!pathext) {
308    pathext = ".com;.exe;.bat;.cmd";
309  }
310  const char *ext = pathext;
311  while (*ext) {
312    // If $PATHEXT itself contains dot:
313    if (ext[0] == '.' && (ext[1] == NUL || ext[1] == ENV_SEPCHAR)) {
314      if (is_executable(name, abspath)) {
315        return true;
316      }
317      // Skip it.
318      ext++;
319      if (*ext) {
320        ext++;
321      }
322      continue;
323    }
324
325    const char *ext_end = ext;
326    size_t ext_len =
327      copy_option_part((char **)&ext_end, buf_end,
328                       sizeof(os_buf) - (size_t)(buf_end - os_buf), ENV_SEPSTR);
329    if (ext_len != 0) {
330      bool in_pathext = nameext_len == ext_len
331                        && 0 == mb_strnicmp(nameext, ext, ext_len);
332
333      if (((in_pathext || is_unix_shell) && is_executable(name, abspath))
334          || is_executable(os_buf, abspath)) {
335        return true;
336      }
337    }
338    ext = ext_end;
339  }
340  return false;
341}
342#else
343# define is_executable_ext is_executable
344#endif
345
346/// Checks if a file is in `$PATH` and is executable.
347///
348/// @param[in]  name  Filename to check.
349/// @param[out] abspath  Returns resolved executable path, if not NULL.
350///
351/// @return `true` if `name` is an executable inside `$PATH`.
352static bool is_executable_in_path(const char *name, char **abspath)
353  FUNC_ATTR_NONNULL_ARG(1)
354{
355  char *path_env = os_getenv("PATH");
356  if (path_env == NULL) {
357    return false;
358  }
359
360#ifdef MSWIN
361  char *path = NULL;
362  if (!os_env_exists("NoDefaultCurrentDirectoryInExePath", false)
363      && strstr(path_tail(p_sh), "cmd.exe") != NULL) {
364    // Prepend ".;" to $PATH.
365    size_t pathlen = strlen(path_env);
366    path = xmallocz(pathlen + 2);
367    memcpy(path, "." ENV_SEPSTR, 2);
368    memcpy(path + 2, path_env, pathlen);
369  } else {
370    path = xstrdup(path_env);
371  }
372#else
373  char *path = xstrdup(path_env);
374#endif
375
376  const size_t bufsize = strlen(name) + strlen(path) + 2;
377  char *buf = xmalloc(bufsize);
378
379  // Walk through all entries in $PATH to check if "name" exists there and
380  // is an executable file.
381  char *p = path;
382  bool rv = false;
383  while (true) {
384    char *e = xstrchrnul(p, ENV_SEPCHAR);
385
386    // Combine the $PATH segment with `name`.
387    xmemcpyz(buf, p, (size_t)(e - p));
388    (void)append_path(buf, name, bufsize);
389
390    if (is_executable_ext(buf, abspath)) {
391      rv = true;
392      goto end;
393    }
394
395    if (*e != ENV_SEPCHAR) {
396      // End of $PATH without finding any executable called name.
397      goto end;
398    }
399
400    p = e + 1;
401  }
402
403end:
404  xfree(buf);
405  xfree(path);
406  xfree(path_env);
407  return rv;
408}
409
410/// Opens or creates a file and returns a non-negative integer representing
411/// the lowest-numbered unused file descriptor, for use in subsequent system
412/// calls (read, write, lseek, fcntl, etc.). If the operation fails, a libuv
413/// error code is returned, and no file is created or modified.
414///
415/// @param path Filename
416/// @param flags Bitwise OR of flags defined in <fcntl.h>
417/// @param mode Permissions for the newly-created file (IGNORED if 'flags' is
418///        not `O_CREAT` or `O_TMPFILE`), subject to the current umask
419/// @return file descriptor, or negative error code on failure
420int os_open(const char *path, int flags, int mode)
421{
422  if (path == NULL) {  // uv_fs_open asserts on NULL. #7561
423    return UV_EINVAL;
424  }
425  int r;
426  RUN_UV_FS_FUNC(r, uv_fs_open, path, flags, mode, NULL);
427  return r;
428}
429
430/// Compatibility wrapper conforming to fopen(3).
431///
432/// Windows: works with UTF-16 filepaths by delegating to libuv (os_open).
433///
434/// Future: remove this, migrate callers to os/fileio.c ?
435///         But file_open_fd does not support O_RDWR yet.
436///
437/// @param path  Filename
438/// @param flags  String flags, one of { r w a r+ w+ a+ rb wb ab }
439/// @return FILE pointer, or NULL on error.
440FILE *os_fopen(const char *path, const char *flags)
441{
442  assert(flags != NULL && strlen(flags) > 0 && strlen(flags) <= 2);
443  int iflags = 0;
444  // Per table in fopen(3) manpage.
445  if (flags[1] == NUL || flags[1] == 'b') {
446    switch (flags[0]) {
447    case 'r':
448      iflags = O_RDONLY;
449      break;
450    case 'w':
451      iflags = O_WRONLY | O_CREAT | O_TRUNC;
452      break;
453    case 'a':
454      iflags = O_WRONLY | O_CREAT | O_APPEND;
455      break;
456    default:
457      abort();
458    }
459#ifdef MSWIN
460    if (flags[1] == 'b') {
461      iflags |= O_BINARY;
462    }
463#endif
464  } else {
465    // char 0 must be one of ('r','w','a').
466    // char 1 is always '+' ('b' is handled above).
467    assert(flags[1] == '+');
468    switch (flags[0]) {
469    case 'r':
470      iflags = O_RDWR;
471      break;
472    case 'w':
473      iflags = O_RDWR | O_CREAT | O_TRUNC;
474      break;
475    case 'a':
476      iflags = O_RDWR | O_CREAT | O_APPEND;
477      break;
478    default:
479      abort();
480    }
481  }
482  // Per fopen(3) manpage: default to 0666, it will be umask-adjusted.
483  int fd = os_open(path, iflags, 0666);
484  if (fd < 0) {
485    return NULL;
486  }
487  return fdopen(fd, flags);
488}
489
490/// Sets file descriptor `fd` to close-on-exec (Unix) or non-inheritable (Windows).
491///
492/// @return -1 if failed to set, 0 otherwise.
493int os_set_cloexec(const int fd)
494{
495#ifdef HAVE_FD_CLOEXEC
496  int e;
497  int fdflags = fcntl(fd, F_GETFD);
498  if (fdflags < 0) {
499    e = errno;
500    ELOG("Failed to get flags on descriptor %d: %s", fd, strerror(e));
501    errno = e;
502    return -1;
503  }
504  if ((fdflags & FD_CLOEXEC) == 0
505      && fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC) == -1) {
506    e = errno;
507    ELOG("Failed to set CLOEXEC on descriptor %d: %s", fd, strerror(e));
508    errno = e;
509    return -1;
510  }
511  return 0;
512#elif defined(MSWIN)
513  HANDLE h = (HANDLE)_get_osfhandle(fd);
514  if (h == INVALID_HANDLE_VALUE
515      || !SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0)) {
516    return -1;
517  }
518  return 0;
519#else
520  return -1;
521#endif
522}
523
524/// Close a file
525///
526/// @return 0 or libuv error code on failure.
527int os_close(const int fd)
528{
529  int r;
530  RUN_UV_FS_FUNC(r, uv_fs_close, fd, NULL);
531  return r;
532}
533
534/// Duplicate file descriptor
535///
536/// @param[in]  fd  File descriptor to duplicate.
537///
538/// @return New file descriptor or libuv error code (< 0).
539int os_dup(const int fd)
540  FUNC_ATTR_WARN_UNUSED_RESULT
541{
542  int ret;
543os_dup_dup:
544  ret = dup(fd);
545  if (ret < 0) {
546    const int error = os_translate_sys_error(errno);
547    errno = 0;
548    if (error == UV_EINTR) {
549      goto os_dup_dup;
550    } else {
551      return error;
552    }
553  }
554  return ret;
555}
556
557/// Duplicates file descriptor `fd` and marks the copy close-on-exec (Unix) / non-inheritable
558/// (Windows), so the duped fd is not leaked to spawned child processes.
559///
560/// @return New file descriptor, or libuv error code (< 0) if the dup failed.
561int os_dup_cloexec(const int fd)
562  FUNC_ATTR_WARN_UNUSED_RESULT
563{
564  int newfd = os_dup(fd);
565  if (newfd >= 0) {
566    os_set_cloexec(newfd);
567  }
568  return newfd;
569}
570
571/// Open the file descriptor for stdin.
572int os_open_stdin_fd(void)
573{
574  int stdin_dup_fd;
575  if (stdin_fd > 0) {
576    stdin_dup_fd = stdin_fd;
577  } else {
578    stdin_dup_fd = os_dup(STDIN_FILENO);
579#ifdef MSWIN
580    // Replace the original stdin with the console input handle.
581    os_redirect_stdin_to_conin();
582#endif
583  }
584  return stdin_dup_fd;
585}
586
587/// Read from a file
588///
589/// Handles EINTR, but not other errors.
590///
591/// @param[in]  fd  File descriptor to read from.
592/// @param[out]  ret_eof  Is set to true if EOF was encountered, otherwise set
593///                       to false. Initial value is ignored.
594/// @param[out]  ret_buf  Buffer to write to. May be NULL if size is zero.
595/// @param[in]  size  Amount of bytes to read.
596/// @param[in]  non_blocking  Do not restart syscall if EAGAIN was encountered.
597///
598/// @return Number of bytes read or libuv error code (< 0).
599ptrdiff_t os_read(const int fd, bool *const ret_eof, char *const ret_buf, const size_t size,
600                  const bool non_blocking)
601  FUNC_ATTR_WARN_UNUSED_RESULT
602{
603  *ret_eof = false;
604  if (ret_buf == NULL) {
605    assert(size == 0);
606    return 0;
607  }
608  size_t read_bytes = 0;
609  while (read_bytes != size) {
610    assert(size >= read_bytes);
611    const ptrdiff_t cur_read_bytes = read(fd, ret_buf + read_bytes,
612                                          IO_COUNT(size - read_bytes));
613    if (cur_read_bytes > 0) {
614      read_bytes += (size_t)cur_read_bytes;
615    }
616    if (cur_read_bytes < 0) {
617      const int error = os_translate_sys_error(errno);
618      errno = 0;
619      if (non_blocking && error == UV_EAGAIN) {
620        break;
621      } else if (error == UV_EINTR || error == UV_EAGAIN) {
622        continue;
623      } else {
624        return (ptrdiff_t)error;
625      }
626    }
627    if (cur_read_bytes == 0) {
628      *ret_eof = true;
629      break;
630    }
631  }
632  return (ptrdiff_t)read_bytes;
633}
634
635#ifdef HAVE_READV
636/// Read from a file to multiple buffers at once
637///
638/// Wrapper for readv().
639///
640/// @param[in]  fd  File descriptor to read from.
641/// @param[out]  ret_eof  Is set to true if EOF was encountered, otherwise set
642///                       to false. Initial value is ignored.
643/// @param[out]  iov  Description of buffers to write to. Note: this description
644///                   may change, it is incorrect to use data it points to after
645///                   os_readv().
646/// @param[in]  iov_size  Number of buffers in iov.
647/// @param[in]  non_blocking  Do not restart syscall if EAGAIN was encountered.
648///
649/// @return Number of bytes read or libuv error code (< 0).
650ptrdiff_t os_readv(const int fd, bool *const ret_eof, struct iovec *iov, size_t iov_size,
651                   const bool non_blocking)
652  FUNC_ATTR_NONNULL_ALL
653{
654  *ret_eof = false;
655  size_t read_bytes = 0;
656  size_t toread = 0;
657  for (size_t i = 0; i < iov_size; i++) {
658    // Overflow, trying to read too much data
659    assert(toread <= SIZE_MAX - iov[i].iov_len);
660    toread += iov[i].iov_len;
661  }
662  while (read_bytes < toread && iov_size && !*ret_eof) {
663    ptrdiff_t cur_read_bytes = readv(fd, iov, (int)iov_size);
664    if (cur_read_bytes == 0) {
665      *ret_eof = true;
666    }
667    if (cur_read_bytes > 0) {
668      read_bytes += (size_t)cur_read_bytes;
669      while (iov_size && cur_read_bytes) {
670        if (cur_read_bytes < (ptrdiff_t)iov->iov_len) {
671          iov->iov_len -= (size_t)cur_read_bytes;
672          iov->iov_base = (char *)iov->iov_base + cur_read_bytes;
673          cur_read_bytes = 0;
674        } else {
675          cur_read_bytes -= (ptrdiff_t)iov->iov_len;
676          iov_size--;
677          iov++;
678        }
679      }
680    } else if (cur_read_bytes < 0) {
681      const int error = os_translate_sys_error(errno);
682      errno = 0;
683      if (non_blocking && error == UV_EAGAIN) {
684        break;
685      } else if (error == UV_EINTR || error == UV_EAGAIN) {
686        continue;
687      } else {
688        return (ptrdiff_t)error;
689      }
690    }
691  }
692  return (ptrdiff_t)read_bytes;
693}
694#endif  // HAVE_READV
695
696/// Write to a file
697///
698/// @param[in]  fd  File descriptor to write to.
699/// @param[in]  buf  Data to write. May be NULL if size is zero.
700/// @param[in]  size  Amount of bytes to write.
701/// @param[in]  non_blocking  Do not restart syscall if EAGAIN was encountered.
702///
703/// @return Number of bytes written or libuv error code (< 0).
704ptrdiff_t os_write(const int fd, const char *const buf, const size_t size, const bool non_blocking)
705  FUNC_ATTR_WARN_UNUSED_RESULT
706{
707  if (buf == NULL) {
708    assert(size == 0);
709    return 0;
710  }
711  size_t written_bytes = 0;
712  while (written_bytes != size) {
713    assert(size >= written_bytes);
714    const ptrdiff_t cur_written_bytes = write(fd, buf + written_bytes,
715                                              IO_COUNT(size - written_bytes));
716    if (cur_written_bytes > 0) {
717      written_bytes += (size_t)cur_written_bytes;
718    }
719    if (cur_written_bytes < 0) {
720      const int error = os_translate_sys_error(errno);
721      errno = 0;
722      if (non_blocking && error == UV_EAGAIN) {
723        break;
724      } else if (error == UV_EINTR || error == UV_EAGAIN) {
725        continue;
726      } else {
727        return error;
728      }
729    }
730    if (cur_written_bytes == 0) {
731      return UV_UNKNOWN;
732    }
733  }
734  return (ptrdiff_t)written_bytes;
735}
736
737/// Copies a file from `path` to `new_path`.
738///
739/// @see http://docs.libuv.org/en/v1.x/fs.html#c.uv_fs_copyfile
740///
741/// @param path Path of file to be copied
742/// @param path_new Path of new file
743/// @param flags Bitwise OR of flags defined in <uv.h>
744/// @return 0 on success, or libuv error code on failure.
745int os_copy(const char *path, const char *new_path, int flags)
746{
747  int r;
748  RUN_UV_FS_FUNC(r, uv_fs_copyfile, path, new_path, flags, NULL);
749  return r;
750}
751
752/// Flushes file modifications to disk.
753///
754/// @param fd the file descriptor of the file to flush to disk.
755///
756/// @return 0 on success, or libuv error code on failure.
757int os_fsync(int fd)
758{
759  int r;
760  RUN_UV_FS_FUNC(r, uv_fs_fsync, fd, NULL);
761  g_stats.fsync++;
762  return r;
763}
764
765/// Get stat information for a file.
766///
767/// @return libuv return code, or -errno
768static int os_stat(const char *name, uv_stat_t *statbuf)
769  FUNC_ATTR_NONNULL_ARG(2)
770{
771  if (!name) {
772    return UV_EINVAL;
773  }
774  uv_fs_t request;
775  int result = uv_fs_stat(NULL, &request, name, NULL);
776  if (result == kLibuvSuccess) {
777    *statbuf = request.statbuf;
778  }
779  uv_fs_req_cleanup(&request);
780  return result;
781}
782
783/// Get the file permissions for a given file.
784///
785/// @return libuv error code on error.
786int32_t os_getperm(const char *name)
787{
788  uv_stat_t statbuf;
789  int stat_result = os_stat(name, &statbuf);
790  if (stat_result == kLibuvSuccess) {
791    return (int32_t)statbuf.st_mode;
792  }
793  return stat_result;
794}
795
796/// Set the permission of a file.
797///
798/// @return `OK` for success, `FAIL` for failure.
799int os_setperm(const char *const name, int perm)
800  FUNC_ATTR_NONNULL_ALL
801{
802  int r;
803  RUN_UV_FS_FUNC(r, uv_fs_chmod, name, perm, NULL);
804  return (r == kLibuvSuccess ? OK : FAIL);
805}
806
807/// Set the permission of the file referred to by the open file descriptor.
808///
809/// @return `OK` for success, `FAIL` for failure.
810int os_fsetperm(int fd, int perm)
811{
812  int r;
813  RUN_UV_FS_FUNC(r, uv_fs_fchmod, fd, perm, NULL);
814  return (r == kLibuvSuccess ? OK : FAIL);
815}
816
817#ifdef HAVE_XATTR
818/// Copy extended attributes from_file to to_file
819void os_copy_xattr(const char *from_file, const char *to_file)
820{
821  if (from_file == NULL) {
822    return;
823  }
824
825  // get the length of the extended attributes
826  ssize_t size = listxattr((char *)from_file, NULL, 0);
827  // not supported or no attributes to copy
828  if (size <= 0) {
829    return;
830  }
831  char *xattr_buf = xmalloc((size_t)size);
832  size = listxattr(from_file, xattr_buf, (size_t)size);
833  ssize_t tsize = size;
834
835  errno = 0;
836
837  ssize_t max_vallen = 0;
838  char *val = NULL;
839  const char *errmsg = NULL;
840
841  for (int round = 0; round < 2; round++) {
842    char *key = xattr_buf;
843    if (round == 1) {
844      size = tsize;
845    }
846
847    while (size > 0) {
848      ssize_t vallen = getxattr(from_file, key, val, round ? (size_t)max_vallen : 0);
849      // only set the attribute in the second round
850      if (vallen >= 0 && round
851          && setxattr(to_file, key, val, (size_t)vallen, 0) == 0) {
852        //
853      } else if (errno) {
854        switch (errno) {
855        case E2BIG:
856          errmsg = e_xattr_e2big;
857          goto error_exit;
858        case ENOTSUP:
859        case EACCES:
860        case EPERM:
861          break;
862        case ERANGE:
863          errmsg = e_xattr_erange;
864          goto error_exit;
865        default:
866          errmsg = e_xattr_other;
867          goto error_exit;
868        }
869      }
870
871      if (round == 0 && vallen > max_vallen) {
872        max_vallen = vallen;
873      }
874
875      // add one for terminating null
876      ssize_t keylen = (ssize_t)strlen(key) + 1;
877      size -= keylen;
878      key += keylen;
879    }
880    if (round) {
881      break;
882    }
883
884    val = xmalloc((size_t)max_vallen + 1);
885  }
886error_exit:
887  xfree(xattr_buf);
888  xfree(val);
889
890  if (errmsg != NULL) {
891    emsg(_(errmsg));
892  }
893}
894#endif
895
896// Return a pointer to the ACL of file "fname" in allocated memory.
897// Return NULL if the ACL is not available for whatever reason.
898vim_acl_T os_get_acl(const char *fname)
899{
900  vim_acl_T ret = NULL;
901  return ret;
902}
903
904// Set the ACL of file "fname" to "acl" (unless it's NULL).
905void os_set_acl(const char *fname, vim_acl_T aclent)
906{
907  if (aclent == NULL) {
908    return;
909  }
910}
911
912void os_free_acl(vim_acl_T aclent)
913{
914  if (aclent == NULL) {
915    return;
916  }
917}
918
919#ifdef UNIX
920/// Checks if the current user owns a file.
921///
922/// Uses both uv_fs_stat() and uv_fs_lstat() via os_fileinfo() and
923/// os_fileinfo_link() respectively for extra security.
924bool os_file_owned(const char *fname)
925  FUNC_ATTR_NONNULL_ALL
926{
927  uid_t uid = getuid();
928  FileInfo finfo;
929  bool file_owned = os_fileinfo(fname, &finfo) && finfo.stat.st_uid == uid;
930  bool link_owned = os_fileinfo_link(fname, &finfo) && finfo.stat.st_uid == uid;
931  return file_owned && link_owned;
932}
933#else
934bool os_file_owned(const char *fname)
935{
936  return true;  // TODO(justinmk): Windows. #8244
937}
938#endif
939
940/// Changes the owner and group of a file, like chown(2).
941///
942/// @return 0 on success, or libuv error code on failure.
943///
944/// @note If `owner` or `group` is -1, then that ID is not changed.
945int os_chown(const char *path, uv_uid_t owner, uv_gid_t group)
946{
947  int r;
948  RUN_UV_FS_FUNC(r, uv_fs_chown, path, owner, group, NULL);
949  return r;
950}
951
952/// Changes the owner and group of the file referred to by the open file
953/// descriptor, like fchown(2).
954///
955/// @return 0 on success, or libuv error code on failure.
956///
957/// @note If `owner` or `group` is -1, then that ID is not changed.
958int os_fchown(int fd, uv_uid_t owner, uv_gid_t group)
959{
960  int r;
961  RUN_UV_FS_FUNC(r, uv_fs_fchown, fd, owner, group, NULL);
962  return r;
963}
964
965/// Check if a path exists.
966///
967/// @return `true` if `path` exists
968bool os_path_exists(const char *path)
969{
970  uv_stat_t statbuf;
971  return os_stat(path, &statbuf) == kLibuvSuccess;
972}
973
974/// Sets file access and modification times.
975///
976/// @see POSIX utime(2)
977///
978/// @param path   File path.
979/// @param atime  Last access time.
980/// @param mtime  Last modification time.
981///
982/// @return 0 on success, or negative error code.
983int os_file_settime(const char *path, double atime, double mtime)
984{
985  int r;
986  RUN_UV_FS_FUNC(r, uv_fs_utime, path, atime, mtime, NULL);
987  return r;
988}
989
990/// Check if a file is readable.
991///
992/// @return true if `name` is readable, otherwise false.
993bool os_file_is_readable(const char *name)
994  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
995{
996  int r;
997  RUN_UV_FS_FUNC(r, uv_fs_access, name, R_OK, NULL);
998  return (r == 0);
999}
1000
1001/// Check if a file is writable.
1002///
1003/// @return `0` if `name` is not writable,
1004/// @return `1` if `name` is writable,
1005/// @return `2` for a directory which we have rights to write into.
1006int os_file_is_writable(const char *name)
1007  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1008{
1009  int r;
1010  RUN_UV_FS_FUNC(r, uv_fs_access, name, W_OK, NULL);
1011  if (r == 0) {
1012    return os_isdir(name) ? 2 : 1;
1013  }
1014  return 0;
1015}
1016
1017/// Rename a file or directory.
1018///
1019/// @return `OK` for success, `FAIL` for failure.
1020int os_rename(const char *path, const char *new_path)
1021  FUNC_ATTR_NONNULL_ALL
1022{
1023  int r;
1024  RUN_UV_FS_FUNC(r, uv_fs_rename, path, new_path, NULL);
1025  return (r == kLibuvSuccess ? OK : FAIL);
1026}
1027
1028/// Make a directory.
1029///
1030/// @return `0` for success, libuv error code for failure.
1031int os_mkdir(const char *path, int32_t mode)
1032  FUNC_ATTR_NONNULL_ALL
1033{
1034  int r;
1035  RUN_UV_FS_FUNC(r, uv_fs_mkdir, path, mode, NULL);
1036  return r;
1037}
1038
1039/// Make a directory, with higher levels when needed
1040///
1041/// @param[in]  dir  Directory to create.
1042/// @param[in]  mode  Permissions for the newly-created directory.
1043/// @param[out]  failed_dir  If it failed to create directory, then this
1044///                          argument is set to an allocated string containing
1045///                          the name of the directory which os_mkdir_recurse
1046///                          failed to create. I.e. it will contain dir or any
1047///                          of the higher level directories.
1048/// @param[out]  created     Set to the full name of the first created directory.
1049///                          It will be NULL until that happens.
1050///
1051/// @return `0` for success, libuv error code for failure.
1052int os_mkdir_recurse(const char *const dir, int32_t mode, char **const failed_dir,
1053                     char **const created)
1054  FUNC_ATTR_NONNULL_ARG(1, 3) FUNC_ATTR_WARN_UNUSED_RESULT
1055{
1056  // Get end of directory name in "dir".
1057  // We're done when it's "/" or "c:/".
1058  const size_t dirlen = strlen(dir);
1059  char *const curdir = xmemdupz(dir, dirlen);
1060  char *const past_head = get_past_head(curdir);
1061  char *e = curdir + dirlen;
1062  const char *const real_end = e;
1063  const char past_head_save = *past_head;
1064  while (!os_isdir(curdir)) {
1065    e = path_tail_with_sep(curdir);
1066    if (e <= past_head) {
1067      *past_head = NUL;
1068      break;
1069    }
1070    *e = NUL;
1071  }
1072  while (e != real_end) {
1073    if (e > past_head) {
1074      *e = PATHSEP;
1075    } else {
1076      *past_head = past_head_save;
1077    }
1078    const size_t component_len = strlen(e);
1079    e += component_len;
1080    if (e == real_end
1081        && memcnt(e - component_len, PATHSEP, component_len) == component_len) {
1082      // Path ends with something like "////". Ignore this.
1083      break;
1084    }
1085    int ret;
1086    if ((ret = os_mkdir(curdir, mode)) != 0) {
1087      *failed_dir = curdir;
1088      return ret;
1089    } else if (created != NULL && *created == NULL) {
1090      *created = FullName_save(curdir, false);
1091    }
1092  }
1093  xfree(curdir);
1094  return 0;
1095}
1096
1097/// Create the parent directory of a file if it does not exist
1098///
1099/// @param[in] fname Full path of the file name whose parent directories
1100///                  we want to create
1101/// @param[in] mode  Permissions for the newly-created directory.
1102///
1103/// @return `0` for success, libuv error code for failure.
1104int os_file_mkdir(char *fname, int32_t mode)
1105  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1106{
1107  if (!dir_of_file_exists(fname)) {
1108    char *tail = path_tail_with_sep(fname);
1109    char *last_char = tail + strlen(tail) - 1;
1110    if (vim_ispathsep(*last_char)) {
1111      emsg(_(e_noname));
1112      return -1;
1113    }
1114    char c = *tail;
1115    *tail = NUL;
1116    int r;
1117    char *failed_dir;
1118    if (((r = os_mkdir_recurse(fname, mode, &failed_dir, NULL)) < 0)) {
1119      semsg(_(e_mkdir), failed_dir, os_strerror(r));
1120      xfree(failed_dir);
1121    }
1122    *tail = c;
1123    return r;
1124  }
1125  return 0;
1126}
1127
1128/// Create a unique temporary directory.
1129///
1130/// @param[in] templ Template of the path to the directory with XXXXXX
1131///                  which would be replaced by random chars.
1132/// @param[out] path Path to created directory for success, undefined for
1133///                  failure.
1134/// @return `0` for success, non-zero for failure.
1135int os_mkdtemp(const char *templ, char *path)
1136  FUNC_ATTR_NONNULL_ALL
1137{
1138  uv_fs_t request;
1139  int result = uv_fs_mkdtemp(NULL, &request, templ, NULL);
1140  if (result == kLibuvSuccess) {
1141    xstrlcpy(path, request.path, TEMP_FILE_PATH_MAXLEN);
1142    TO_SLASH(path);
1143  }
1144  uv_fs_req_cleanup(&request);
1145  return result;
1146}
1147
1148/// Remove a directory.
1149///
1150/// @return `0` for success, non-zero for failure.
1151int os_rmdir(const char *path)
1152  FUNC_ATTR_NONNULL_ALL
1153{
1154  int r;
1155  RUN_UV_FS_FUNC(r, uv_fs_rmdir, path, NULL);
1156  return r;
1157}
1158
1159/// Opens a directory.
1160/// @param[out] dir   The Directory object.
1161/// @param      path  Path to the directory.
1162/// @returns true if dir contains one or more items, false if not or an error
1163///          occurred.
1164bool os_scandir(Directory *dir, const char *path)
1165  FUNC_ATTR_NONNULL_ALL
1166{
1167  int r = uv_fs_scandir(NULL, &dir->request, path, 0, NULL);
1168  if (r < 0) {
1169    os_closedir(dir);
1170  }
1171  return r >= 0;
1172}
1173
1174/// Increments the directory pointer.
1175/// @param dir  The Directory object.
1176/// @returns a pointer to the next path in `dir` or `NULL`.
1177const char *os_scandir_next(Directory *dir)
1178  FUNC_ATTR_NONNULL_ALL
1179{
1180  int err = uv_fs_scandir_next(&dir->request, &dir->ent);
1181  return err != UV_EOF ? dir->ent.name : NULL;
1182}
1183
1184/// Frees memory associated with `os_scandir()`.
1185/// @param dir  The directory.
1186void os_closedir(Directory *dir)
1187  FUNC_ATTR_NONNULL_ALL
1188{
1189  uv_fs_req_cleanup(&dir->request);
1190}
1191
1192/// Remove a file.
1193///
1194/// @return `0` for success, non-zero for failure.
1195int os_remove(const char *path)
1196  FUNC_ATTR_NONNULL_ALL
1197{
1198  int r;
1199  RUN_UV_FS_FUNC(r, uv_fs_unlink, path, NULL);
1200  return r;
1201}
1202
1203/// Get the file information for a given path
1204///
1205/// @param path Path to the file.
1206/// @param[out] file_info Pointer to a FileInfo to put the information in.
1207/// @return `true` on success, `false` for failure.
1208bool os_fileinfo(const char *path, FileInfo *file_info)
1209  FUNC_ATTR_NONNULL_ARG(2)
1210{
1211  CLEAR_POINTER(file_info);
1212  return os_stat(path, &(file_info->stat)) == kLibuvSuccess;
1213}
1214
1215/// Parses `path` into a `FileInfo` structure.
1216///
1217/// TODO(ntdiary): Could be extended for path.c cleanup and path normalization
1218/// logic. Eventually merge this with `os_fileinfo`
1219///
1220/// TODO(justinmk): return value is meaningless currently.
1221bool os_fileinfo2(const char *path, FileInfo *info)
1222  FUNC_ATTR_NONNULL_ALL
1223{
1224  CLEAR_POINTER(info);
1225  if (path_with_url(path)) {
1226    return true;
1227  }
1228  // Preserves the leading two "/"; 3+ "///…" collapse to a single "/" (IEEE 1003.1).
1229  // Same rule applies to kPathUNC/kPathGeneric on Windows, but not to kPathDevice or
1230  // kPathDeviceUNC, where the leading "//" is significant.
1231  const char *p = path_skip_sep(path, false);
1232  size_t leading_slashes = (size_t)(p - path);
1233#ifdef MSWIN
1234  if (leading_slashes == 0 && ASCII_ISALPHA(p[0]) && p[1] == ':') {
1235    info->type = kPathDrive;
1236    p = path_skip_sep(p + 2, false);
1237    info->rest_off = (size_t)(p - path);
1238    return true;
1239  }
1240  if (leading_slashes >= 2 && (p[0] == '?' || p[0] == '.')) {
1241    if (!vim_ispathsep_nocolon(p[1])) {
1242      return true;
1243    }
1244    info->type = kPathDevice;
1245    info->prefix_off = leading_slashes - 2;
1246    p = path_skip_sep(p + 2, false);
1247    if (vim_strnicmp_asc(p, "unc", 3) == 0 && vim_ispathsep_nocolon(p[3])) {
1248      info->type = kPathDeviceUNC;
1249      p = path_skip_sep(p + 4, false);
1250      info->root_off = (size_t)(p - path);
1251      goto server;
1252    }
1253    info->root_off = (size_t)(p - path);
1254    if (ASCII_ISALPHA(p[0]) && p[1] == ':') {
1255      p += 2;
1256    }
1257    p = path_skip_sep(path_next_component(p), false);
1258    info->rest_off = (size_t)(p - path);
1259    return true;
1260  }
1261  if (leading_slashes == 2) {
1262    info->type = kPathUNC;
1263  server:
1264    p = path_skip_sep(path_next_component(p), false);
1265    p = path_skip_sep(path_next_component(p), false);
1266    info->rest_off = (size_t)(p - path);
1267    return true;
1268  }
1269#endif
1270  info->type = kPathGeneric;
1271  info->rest_off = leading_slashes;
1272  info->root_off = leading_slashes > 2 ? leading_slashes - 1 : 0;
1273  info->prefix_off = info->root_off;
1274  return true;
1275}
1276
1277/// Get the file information for a given path without following links
1278///
1279/// @param path Path to the file.
1280/// @param[out] file_info Pointer to a FileInfo to put the information in.
1281/// @return `true` on success, `false` for failure.
1282bool os_fileinfo_link(const char *path, FileInfo *file_info)
1283  FUNC_ATTR_NONNULL_ARG(2)
1284{
1285  CLEAR_POINTER(file_info);
1286  if (path == NULL) {
1287    return false;
1288  }
1289  uv_fs_t request;
1290  bool ok = uv_fs_lstat(NULL, &request, path, NULL) == kLibuvSuccess;
1291  if (ok) {
1292    file_info->stat = request.statbuf;
1293  }
1294  uv_fs_req_cleanup(&request);
1295  return ok;
1296}
1297
1298/// Get the file information for a given file descriptor
1299///
1300/// @param file_descriptor File descriptor of the file.
1301/// @param[out] file_info Pointer to a FileInfo to put the information in.
1302/// @return `true` on success, `false` for failure.
1303bool os_fileinfo_fd(int file_descriptor, FileInfo *file_info)
1304  FUNC_ATTR_NONNULL_ALL
1305{
1306  uv_fs_t request;
1307  CLEAR_POINTER(file_info);
1308  bool ok = uv_fs_fstat(NULL,
1309                        &request,
1310                        file_descriptor,
1311                        NULL) == kLibuvSuccess;
1312  if (ok) {
1313    file_info->stat = request.statbuf;
1314  }
1315  uv_fs_req_cleanup(&request);
1316  return ok;
1317}
1318
1319/// Compare the inodes of two FileInfos
1320///
1321/// @return `true` if the two FileInfos represent the same file.
1322bool os_fileinfo_id_equal(const FileInfo *file_info_1, const FileInfo *file_info_2)
1323  FUNC_ATTR_NONNULL_ALL
1324{
1325  return file_info_1->stat.st_ino == file_info_2->stat.st_ino
1326         && file_info_1->stat.st_dev == file_info_2->stat.st_dev;
1327}
1328
1329/// Get the `FileID` of a `FileInfo`
1330///
1331/// @param file_info Pointer to the `FileInfo`
1332/// @param[out] file_id Pointer to a `FileID`
1333void os_fileinfo_id(const FileInfo *file_info, FileID *file_id)
1334  FUNC_ATTR_NONNULL_ALL
1335{
1336  file_id->inode = file_info->stat.st_ino;
1337  file_id->device_id = file_info->stat.st_dev;
1338}
1339
1340/// Get the inode of a `FileInfo`
1341///
1342/// @deprecated Use `FileID` instead, this function is only needed in memline.c
1343/// @param file_info Pointer to the `FileInfo`
1344/// @return the inode number
1345uint64_t os_fileinfo_inode(const FileInfo *file_info)
1346  FUNC_ATTR_NONNULL_ALL
1347{
1348  return file_info->stat.st_ino;
1349}
1350
1351/// Get the size of a file from a `FileInfo`.
1352///
1353/// @return filesize in bytes.
1354uint64_t os_fileinfo_size(const FileInfo *file_info)
1355  FUNC_ATTR_NONNULL_ALL
1356{
1357  return file_info->stat.st_size;
1358}
1359
1360/// Get the number of hardlinks from a `FileInfo`.
1361///
1362/// @return number of hardlinks.
1363uint64_t os_fileinfo_hardlinks(const FileInfo *file_info)
1364  FUNC_ATTR_NONNULL_ALL
1365{
1366  return file_info->stat.st_nlink;
1367}
1368
1369/// Get the blocksize from a `FileInfo`.
1370///
1371/// @return blocksize in bytes.
1372uint64_t os_fileinfo_blocksize(const FileInfo *file_info)
1373  FUNC_ATTR_NONNULL_ALL
1374{
1375  return file_info->stat.st_blksize;
1376}
1377
1378/// Get the `FileID` for a given path
1379///
1380/// @param path Path to the file.
1381/// @param[out] file_info Pointer to a `FileID` to fill in.
1382/// @return `true` on success, `false` for failure.
1383bool os_fileid(const char *path, FileID *file_id)
1384  FUNC_ATTR_NONNULL_ALL
1385{
1386  uv_stat_t statbuf;
1387  if (os_stat(path, &statbuf) == kLibuvSuccess) {
1388    file_id->inode = statbuf.st_ino;
1389    file_id->device_id = statbuf.st_dev;
1390    return true;
1391  }
1392  return false;
1393}
1394
1395/// Check if two `FileID`s are equal
1396///
1397/// @param file_id_1 Pointer to first `FileID`
1398/// @param file_id_2 Pointer to second `FileID`
1399/// @return `true` if the two `FileID`s represent te same file.
1400bool os_fileid_equal(const FileID *file_id_1, const FileID *file_id_2)
1401  FUNC_ATTR_NONNULL_ALL
1402{
1403  return file_id_1->inode == file_id_2->inode
1404         && file_id_1->device_id == file_id_2->device_id;
1405}
1406
1407/// Return the canonicalized absolute pathname.
1408///
1409/// @param[in] name Filename to be canonicalized.
1410/// @param[out] buf Buffer to store the canonicalized values.
1411///                 If it is NULL, memory is allocated. In that case, the caller
1412///                 should deallocate this buffer.
1413/// @param[in] len  The length of the buffer.
1414///
1415/// @return pointer to the buf on success, or NULL.
1416char *os_realpath(const char *name, char *buf, size_t len)
1417  FUNC_ATTR_NONNULL_ARG(1)
1418{
1419  uv_fs_t request;
1420  int result = uv_fs_realpath(NULL, &request, name, NULL);
1421  if (result == kLibuvSuccess) {
1422    if (buf == NULL) {
1423      buf = xmalloc(len);
1424    }
1425    xstrlcpy(buf, request.ptr, len);
1426    TO_SLASH(buf);
1427  }
1428  uv_fs_req_cleanup(&request);
1429  return result == kLibuvSuccess ? buf : NULL;
1430}
1431
1432#ifdef MSWIN
1433/// When "fname" is the name of a shortcut (*.lnk) resolve the file it points
1434/// to and return that name in allocated memory.
1435/// Otherwise NULL is returned.
1436char *os_resolve_shortcut(const char *fname)
1437  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC
1438{
1439  HRESULT hr;
1440  IPersistFile *ppf = NULL;
1441  OLECHAR wsz[MAX_PATH];
1442  char *rfname = NULL;
1443  IShellLinkW *pslw = NULL;
1444  WIN32_FIND_DATAW ffdw;
1445
1446  // Check if the file name ends in ".lnk". Avoid calling CoCreateInstance(),
1447  // it's quite slow.
1448  if (fname == NULL) {
1449    return rfname;
1450  }
1451  const size_t len = strlen(fname);
1452  if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0) {
1453    return rfname;
1454  }
1455
1456  CoInitialize(NULL);
1457
1458  // create a link manager object and request its interface
1459  hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1460                        &IID_IShellLinkW, (void **)&pslw);
1461  if (hr == S_OK) {
1462    wchar_t *p;
1463    const int r = utf8_to_utf16(fname, -1, &p);
1464    if (r != 0) {
1465      semsg("utf8_to_utf16 failed: %d", r);
1466    } else if (p != NULL) {
1467      // Get a pointer to the IPersistFile interface.
1468      hr = pslw->lpVtbl->QueryInterface(pslw, &IID_IPersistFile, (void **)&ppf);
1469      if (hr != S_OK) {
1470        goto shortcut_errorw;
1471      }
1472
1473      // "load" the name and resolve the link
1474      hr = ppf->lpVtbl->Load(ppf, p, STGM_READ);
1475      if (hr != S_OK) {
1476        goto shortcut_errorw;
1477      }
1478
1479# if 0  // This makes Vim wait a long time if the target does not exist.
1480      hr = pslw->lpVtbl->Resolve(pslw, NULL, SLR_NO_UI);
1481      if (hr != S_OK) {
1482        goto shortcut_errorw;
1483      }
1484# endif
1485
1486      // Get the path to the link target.
1487      ZeroMemory(wsz, MAX_PATH * sizeof(wchar_t));
1488      hr = pslw->lpVtbl->GetPath(pslw, wsz, MAX_PATH, &ffdw, 0);
1489      if (hr == S_OK && wsz[0] != NUL) {
1490        const int r2 = utf16_to_utf8(wsz, -1, &rfname);
1491        if (r2 != 0) {
1492          semsg("utf16_to_utf8 failed: %d", r2);
1493        }
1494      }
1495
1496shortcut_errorw:
1497      xfree(p);
1498      goto shortcut_end;
1499    }
1500  }
1501
1502shortcut_end:
1503  // Release all interface pointers (both belong to the same object)
1504  if (ppf != NULL) {
1505    ppf->lpVtbl->Release(ppf);
1506  }
1507  if (pslw != NULL) {
1508    pslw->lpVtbl->Release(pslw);
1509  }
1510
1511  CoUninitialize();
1512  TO_SLASH(rfname);
1513  return rfname;
1514}
1515
1516# define IS_PATH_SEP(c) ((c) == L'\\' || (c) == L'/')
1517/// Returns true if the path contains a reparse point (junction or symbolic
1518/// link). Otherwise false in returned.
1519bool os_is_reparse_point_include(const char *path)
1520{
1521  wchar_t *p, *q, *utf16_path;
1522  wchar_t buf[MAX_PATH];
1523  DWORD attr;
1524  bool result = false;
1525
1526  const int r = utf8_to_utf16(path, -1, &utf16_path);
1527  if (r != 0) {
1528    semsg("utf8_to_utf16 failed: %d", r);
1529    return false;
1530  }
1531
1532  p = utf16_path;
1533  if (isalpha((uint8_t)p[0]) && p[1] == L':' && IS_PATH_SEP(p[2])) {
1534    p += 3;
1535  } else if (IS_PATH_SEP(p[0]) && IS_PATH_SEP(p[1])) {
1536    p += 2;
1537  }
1538
1539  while (*p != L'\0') {
1540    q = wcspbrk(p, L"\\/");
1541    if (q == NULL) {
1542      p = q = utf16_path + wcslen(utf16_path);
1543    } else {
1544      p = q + 1;
1545    }
1546    if (q - utf16_path >= MAX_PATH) {
1547      break;
1548    }
1549    wcsncpy(buf, utf16_path, (size_t)(q - utf16_path));
1550    buf[q - utf16_path] = L'\0';
1551    attr = GetFileAttributesW(buf);
1552    if (attr != INVALID_FILE_ATTRIBUTES
1553        && (attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
1554      result = true;
1555      break;
1556    }
1557  }
1558  xfree(utf16_path);
1559  return result;
1560}
1561#endif