aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/os/fs.c
blob: 6157341ec9b0ed93fcd0dcff5da40b7658b61e70 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

// fs.c -- filesystem access
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include "auto/config.h"
#include "nvim/gettext.h"
#include "nvim/globals.h"
#include "nvim/log.h"
#include "nvim/macros.h"
#include "nvim/option_defs.h"
#include "nvim/os/fs_defs.h"
#include "nvim/types.h"
#include "nvim/vim.h"

#ifdef HAVE_SYS_UIO_H
# include <sys/uio.h>
#endif

#include <uv.h>

#include "nvim/ascii.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/os/os.h"
#include "nvim/path.h"

struct iovec;

#ifdef MSWIN
# include "nvim/mbyte.h"  // for utf8_to_utf16, utf16_to_utf8
#endif

#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "os/fs.c.generated.h"
#endif

#define RUN_UV_FS_FUNC(ret, func, ...) \
  do { \
    bool did_try_to_free = false; \
uv_call_start: {} \
    uv_fs_t req; \
    fs_loop_lock(); \
    ret = func(&fs_loop, &req, __VA_ARGS__); \
    uv_fs_req_cleanup(&req); \
    fs_loop_unlock(); \
    if (ret == UV_ENOMEM && !did_try_to_free) { \
      try_to_free_memory(); \
      did_try_to_free = true; \
      goto uv_call_start; \
    } \
  } while (0)

// Many fs functions from libuv return that value on success.
static const int kLibuvSuccess = 0;
static uv_loop_t fs_loop;
static uv_mutex_t fs_loop_mutex;

// Initialize the fs module
void fs_init(void)
{
  uv_loop_init(&fs_loop);
  uv_mutex_init_recursive(&fs_loop_mutex);
}

/// TODO(bfredl): some of these operations should
/// be possible to do the private libuv loop of the
/// thread, instead of contending the global fs loop
void fs_loop_lock(void)
{
  uv_mutex_lock(&fs_loop_mutex);
}

void fs_loop_unlock(void)
{
  uv_mutex_unlock(&fs_loop_mutex);
}

/// Changes the current directory to `path`.
///
/// @return 0 on success, or negative error code.
int os_chdir(const char *path)
  FUNC_ATTR_NONNULL_ALL
{
  if (p_verbose >= 5) {
    verbose_enter();
    smsg("chdir(%s)", path);
    verbose_leave();
  }
  return uv_chdir(path);
}

/// Get the name of current directory.
///
/// @param buf Buffer to store the directory name.
/// @param len Length of `buf`.
/// @return `OK` for success, `FAIL` for failure.
int os_dirname(char *buf, size_t len)
  FUNC_ATTR_NONNULL_ALL
{
  int error_number;
  if ((error_number = uv_cwd(buf, &len)) != kLibuvSuccess) {
    xstrlcpy(buf, uv_strerror(error_number), len);
    return FAIL;
  }
  return OK;
}

/// Check if the given path is a directory and not a symlink to a directory.
/// @return `true` if `name` is a directory and NOT a symlink to a directory.
///         `false` if `name` is not a directory or if an error occurred.
bool os_isrealdir(const char *name)
  FUNC_ATTR_NONNULL_ALL
{
  uv_fs_t request;
  fs_loop_lock();
  if (uv_fs_lstat(&fs_loop, &request, name, NULL) != kLibuvSuccess) {
    fs_loop_unlock();
    return false;
  }
  fs_loop_unlock();
  if (S_ISLNK(request.statbuf.st_mode)) {
    return false;
  }
  return S_ISDIR(request.statbuf.st_mode);
}

/// Check if the given path exists and is a directory.
///
/// @return `true` if `name` is a directory.
bool os_isdir(const char *name)
  FUNC_ATTR_NONNULL_ALL
{
  int32_t mode = os_getperm(name);
  if (mode < 0) {
    return false;
  }

  return S_ISDIR(mode);
}

/// Check what `name` is:
/// @return NODE_NORMAL: file or directory (or doesn't exist)
///         NODE_WRITABLE: writable device, socket, fifo, etc.
///         NODE_OTHER: non-writable things
int os_nodetype(const char *name)
  FUNC_ATTR_NONNULL_ALL
{
#ifndef MSWIN  // Unix
  uv_stat_t statbuf;
  if (0 != os_stat(name, &statbuf)) {
    return NODE_NORMAL;  // File doesn't exist.
  }
  // uv_handle_type does not distinguish BLK and DIR.
  //    Related: https://github.com/joyent/libuv/pull/1421
  if (S_ISREG(statbuf.st_mode) || S_ISDIR(statbuf.st_mode)) {
    return NODE_NORMAL;
  }
  if (S_ISBLK(statbuf.st_mode)) {  // block device isn't writable
    return NODE_OTHER;
  }
  // Everything else is writable?
  // buf_write() expects NODE_WRITABLE for char device /dev/stderr.
  return NODE_WRITABLE;
#else  // Windows
  // Edge case from Vim os_win32.c:
  // We can't open a file with a name "\\.\con" or "\\.\prn", trying to read
  // from it later will cause Vim to hang. Thus return NODE_WRITABLE here.
  if (strncmp(name, "\\\\.\\", 4) == 0) {
    return NODE_WRITABLE;
  }

  // Vim os_win32.c:mch_nodetype does (since 7.4.015):
  //    wn = enc_to_utf16(name, NULL);
  //    hFile = CreatFile(wn, ...)
  // to get a HANDLE. Whereas libuv just calls _get_osfhandle() on the fd we
  // give it. But uv_fs_open later calls fs__capture_path which does a similar
  // utf8-to-utf16 dance and saves us the hassle.

  // macOS: os_open(/dev/stderr) would return UV_EACCES.
  int fd = os_open(name, O_RDONLY
# ifdef O_NONBLOCK
                   | O_NONBLOCK
# endif
                   , 0);
  if (fd < 0) {  // open() failed.
    return NODE_NORMAL;
  }
  int guess = uv_guess_handle(fd);
  if (close(fd) == -1) {
    ELOG("close(%d) failed. name='%s'", fd, name);
  }

  switch (guess) {
  case UV_TTY:          // FILE_TYPE_CHAR
    return NODE_WRITABLE;
  case UV_FILE:         // FILE_TYPE_DISK
    return NODE_NORMAL;
  case UV_NAMED_PIPE:   // not handled explicitly in Vim os_win32.c
  case UV_UDP:          // unix only
  case UV_TCP:          // unix only
  case UV_UNKNOWN_HANDLE:
  default:
    return NODE_OTHER;  // Vim os_win32.c default
  }
#endif
}

/// Gets the absolute path of the currently running executable.
/// May fail if procfs is missing. #6734
/// @see path_exepath
///
/// @param[out] buffer Full path to the executable.
/// @param[in]  size   Size of `buffer`.
///
/// @return 0 on success, or libuv error code.
int os_exepath(char *buffer, size_t *size)
  FUNC_ATTR_NONNULL_ALL
{
  return uv_exepath(buffer, size);
}

/// Checks if the file `name` is executable.
///
/// @param[in]  name     Filename to check.
/// @param[out,allocated] abspath  Returns resolved exe path, if not NULL.
/// @param[in] use_path  Also search $PATH.
///
/// @return true if `name` is executable and
///   - can be found in $PATH,
///   - is relative to current dir or
///   - is absolute.
///
/// @return `false` otherwise.
bool os_can_exe(const char *name, char **abspath, bool use_path)
  FUNC_ATTR_NONNULL_ARG(1)
{
  if (!use_path || gettail_dir(name) != name) {
#ifdef MSWIN
    if (is_executable_ext(name, abspath)) {
#else
    // Must have path separator, cannot execute files in the current directory.
    if ((use_path || gettail_dir(name) != name)
        && is_executable(name, abspath)) {
#endif
      return true;
    }
    return false;
  }

  return is_executable_in_path(name, abspath);
}

/// Returns true if `name` is an executable file.
///
/// @param[in]            name     Filename to check.
/// @param[out,allocated] abspath  Returns full exe path, if not NULL.
static bool is_executable(const char *name, char **abspath)
  FUNC_ATTR_NONNULL_ARG(1)
{
  int32_t mode = os_getperm(name);

  if (mode < 0) {
    return false;
  }

#ifdef MSWIN
  // Windows does not have exec bit; just check if the file exists and is not
  // a directory.
  const bool ok = S_ISREG(mode);
#else
  int r = -1;
  if (S_ISREG(mode)) {
    RUN_UV_FS_FUNC(r, uv_fs_access, name, X_OK, NULL);
  }
  const bool ok = (r == 0);
#endif
  if (ok && abspath != NULL) {
    *abspath = save_abs_path(name);
  }
  return ok;
}

#ifdef MSWIN
/// Checks if file `name` is executable under any of these conditions:
/// - extension is in $PATHEXT and `name` is executable
/// - result of any $PATHEXT extension appended to `name` is executable
static bool is_executable_ext(const char *name, char **abspath)
  FUNC_ATTR_NONNULL_ARG(1)
{
  const bool is_unix_shell = strstr(path_tail(p_sh), "powershell") == NULL
                             && strstr(path_tail(p_sh), "pwsh") == NULL
                             && strstr(path_tail(p_sh), "sh") != NULL;
  char *nameext = strrchr(name, '.');
  size_t nameext_len = nameext ? strlen(nameext) : 0;
  xstrlcpy(os_buf, name, sizeof(os_buf));
  char *buf_end = xstrchrnul(os_buf, '\0');
  const char *pathext = os_getenv("PATHEXT");
  if (!pathext) {
    pathext = ".com;.exe;.bat;.cmd";
  }
  const char *ext = pathext;
  while (*ext) {
    // If $PATHEXT itself contains dot:
    if (ext[0] == '.' && (ext[1] == '\0' || ext[1] == ENV_SEPCHAR)) {
      if (is_executable(name, abspath)) {
        return true;
      }
      // Skip it.
      ext++;
      if (*ext) {
        ext++;
      }
      continue;
    }

    const char *ext_end = ext;
    size_t ext_len =
      copy_option_part((char **)&ext_end, buf_end,
                       sizeof(os_buf) - (size_t)(buf_end - os_buf), ENV_SEPSTR);
    if (ext_len != 0) {
      bool in_pathext = nameext_len == ext_len
                        && 0 == mb_strnicmp(nameext, ext, ext_len);

      if (((in_pathext || is_unix_shell) && is_executable(name, abspath))
          || is_executable(os_buf, abspath)) {
        return true;
      }
    }
    ext = ext_end;
  }
  return false;
}
#endif

/// Checks if a file is in `$PATH` and is executable.
///
/// @param[in]  name  Filename to check.
/// @param[out] abspath  Returns resolved executable path, if not NULL.
///
/// @return `true` if `name` is an executable inside `$PATH`.
static bool is_executable_in_path(const char *name, char **abspath)
  FUNC_ATTR_NONNULL_ARG(1)
{
  const char *path_env = os_getenv("PATH");
  if (path_env == NULL) {
    return false;
  }

#ifdef MSWIN
  // Prepend ".;" to $PATH.
  size_t pathlen = strlen(path_env);
  char *path = memcpy(xmallocz(pathlen + 2), "." ENV_SEPSTR, 2);
  memcpy(path + 2, path_env, pathlen);
#else
  char *path = xstrdup(path_env);
#endif

  size_t buf_len = strlen(name) + strlen(path) + 2;
  char *buf = xmalloc(buf_len);

  // Walk through all entries in $PATH to check if "name" exists there and
  // is an executable file.
  char *p = path;
  bool rv = false;
  for (;;) {
    char *e = xstrchrnul(p, ENV_SEPCHAR);

    // Combine the $PATH segment with `name`.
    xstrlcpy(buf, p, (size_t)(e - p) + 1);
    append_path(buf, name, buf_len);

#ifdef MSWIN
    if (is_executable_ext(buf, abspath)) {
#else
    if (is_executable(buf, abspath)) {
#endif
      rv = true;
      goto end;
    }

    if (*e != ENV_SEPCHAR) {
      // End of $PATH without finding any executable called name.
      goto end;
    }

    p = e + 1;
  }

end:
  xfree(buf);
  xfree(path);
  return rv;
}

/// Opens or creates a file and returns a non-negative integer representing
/// the lowest-numbered unused file descriptor, for use in subsequent system
/// calls (read, write, lseek, fcntl, etc.). If the operation fails, a libuv
/// error code is returned, and no file is created or modified.
///
/// @param path Filename
/// @param flags Bitwise OR of flags defined in <fcntl.h>
/// @param mode Permissions for the newly-created file (IGNORED if 'flags' is
///        not `O_CREAT` or `O_TMPFILE`), subject to the current umask
/// @return file descriptor, or negative error code on failure
int os_open(const char *path, int flags, int mode)
{
  if (path == NULL) {  // uv_fs_open asserts on NULL. #7561
    return UV_EINVAL;
  }
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_open, path, flags, mode, NULL);
  return r;
}

/// Compatibility wrapper conforming to fopen(3).
///
/// Windows: works with UTF-16 filepaths by delegating to libuv (os_open).
///
/// Future: remove this, migrate callers to os/fileio.c ?
///         But file_open_fd does not support O_RDWR yet.
///
/// @param path  Filename
/// @param flags  String flags, one of { r w a r+ w+ a+ rb wb ab }
/// @return FILE pointer, or NULL on error.
FILE *os_fopen(const char *path, const char *flags)
{
  assert(flags != NULL && strlen(flags) > 0 && strlen(flags) <= 2);
  int iflags = 0;
  // Per table in fopen(3) manpage.
  if (flags[1] == '\0' || flags[1] == 'b') {
    switch (flags[0]) {
    case 'r':
      iflags = O_RDONLY;
      break;
    case 'w':
      iflags = O_WRONLY | O_CREAT | O_TRUNC;
      break;
    case 'a':
      iflags = O_WRONLY | O_CREAT | O_APPEND;
      break;
    default:
      abort();
    }
#ifdef MSWIN
    if (flags[1] == 'b') {
      iflags |= O_BINARY;
    }
#endif
  } else {
    // char 0 must be one of ('r','w','a').
    // char 1 is always '+' ('b' is handled above).
    assert(flags[1] == '+');
    switch (flags[0]) {
    case 'r':
      iflags = O_RDWR;
      break;
    case 'w':
      iflags = O_RDWR | O_CREAT | O_TRUNC;
      break;
    case 'a':
      iflags = O_RDWR | O_CREAT | O_APPEND;
      break;
    default:
      abort();
    }
  }
  // Per fopen(3) manpage: default to 0666, it will be umask-adjusted.
  int fd = os_open(path, iflags, 0666);
  if (fd < 0) {
    return NULL;
  }
  return fdopen(fd, flags);
}

/// Sets file descriptor `fd` to close-on-exec.
//
// @return -1 if failed to set, 0 otherwise.
int os_set_cloexec(const int fd)
{
#ifdef HAVE_FD_CLOEXEC
  int e;
  int fdflags = fcntl(fd, F_GETFD);
  if (fdflags < 0) {
    e = errno;
    ELOG("Failed to get flags on descriptor %d: %s", fd, strerror(e));
    errno = e;
    return -1;
  }
  if ((fdflags & FD_CLOEXEC) == 0
      && fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC) == -1) {
    e = errno;
    ELOG("Failed to set CLOEXEC on descriptor %d: %s", fd, strerror(e));
    errno = e;
    return -1;
  }
  return 0;
#endif

  // No FD_CLOEXEC flag. On Windows, the file should have been opened with
  // O_NOINHERIT anyway.
  return -1;
}

/// Close a file
///
/// @return 0 or libuv error code on failure.
int os_close(const int fd)
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_close, fd, NULL);
  return r;
}

/// Duplicate file descriptor
///
/// @param[in]  fd  File descriptor to duplicate.
///
/// @return New file descriptor or libuv error code (< 0).
int os_dup(const int fd)
  FUNC_ATTR_WARN_UNUSED_RESULT
{
  int ret;
os_dup_dup:
  ret = dup(fd);
  if (ret < 0) {
    const int error = os_translate_sys_error(errno);
    errno = 0;
    if (error == UV_EINTR) {
      goto os_dup_dup;
    } else {
      return error;
    }
  }
  return ret;
}

/// Read from a file
///
/// Handles EINTR and ENOMEM, but not other errors.
///
/// @param[in]  fd  File descriptor to read from.
/// @param[out]  ret_eof  Is set to true if EOF was encountered, otherwise set
///                       to false. Initial value is ignored.
/// @param[out]  ret_buf  Buffer to write to. May be NULL if size is zero.
/// @param[in]  size  Amount of bytes to read.
/// @param[in]  non_blocking  Do not restart syscall if EAGAIN was encountered.
///
/// @return Number of bytes read or libuv error code (< 0).
ptrdiff_t os_read(const int fd, bool *const ret_eof, char *const ret_buf, const size_t size,
                  const bool non_blocking)
  FUNC_ATTR_WARN_UNUSED_RESULT
{
  *ret_eof = false;
  if (ret_buf == NULL) {
    assert(size == 0);
    return 0;
  }
  size_t read_bytes = 0;
  bool did_try_to_free = false;
  while (read_bytes != size) {
    assert(size >= read_bytes);
    const ptrdiff_t cur_read_bytes = read(fd, ret_buf + read_bytes,
                                          IO_COUNT(size - read_bytes));
    if (cur_read_bytes > 0) {
      read_bytes += (size_t)cur_read_bytes;
    }
    if (cur_read_bytes < 0) {
      const int error = os_translate_sys_error(errno);
      errno = 0;
      if (non_blocking && error == UV_EAGAIN) {
        break;
      } else if (error == UV_EINTR || error == UV_EAGAIN) {
        continue;
      } else if (error == UV_ENOMEM && !did_try_to_free) {
        try_to_free_memory();
        did_try_to_free = true;
        continue;
      } else {
        return (ptrdiff_t)error;
      }
    }
    if (cur_read_bytes == 0) {
      *ret_eof = true;
      break;
    }
  }
  return (ptrdiff_t)read_bytes;
}

#ifdef HAVE_READV
/// Read from a file to multiple buffers at once
///
/// Wrapper for readv().
///
/// @param[in]  fd  File descriptor to read from.
/// @param[out]  ret_eof  Is set to true if EOF was encountered, otherwise set
///                       to false. Initial value is ignored.
/// @param[out]  iov  Description of buffers to write to. Note: this description
///                   may change, it is incorrect to use data it points to after
///                   os_readv().
/// @param[in]  iov_size  Number of buffers in iov.
/// @param[in]  non_blocking  Do not restart syscall if EAGAIN was encountered.
///
/// @return Number of bytes read or libuv error code (< 0).
ptrdiff_t os_readv(const int fd, bool *const ret_eof, struct iovec *iov, size_t iov_size,
                   const bool non_blocking)
  FUNC_ATTR_NONNULL_ALL
{
  *ret_eof = false;
  size_t read_bytes = 0;
  bool did_try_to_free = false;
  size_t toread = 0;
  for (size_t i = 0; i < iov_size; i++) {
    // Overflow, trying to read too much data
    assert(toread <= SIZE_MAX - iov[i].iov_len);
    toread += iov[i].iov_len;
  }
  while (read_bytes < toread && iov_size && !*ret_eof) {
    ptrdiff_t cur_read_bytes = readv(fd, iov, (int)iov_size);
    if (cur_read_bytes == 0) {
      *ret_eof = true;
    }
    if (cur_read_bytes > 0) {
      read_bytes += (size_t)cur_read_bytes;
      while (iov_size && cur_read_bytes) {
        if (cur_read_bytes < (ptrdiff_t)iov->iov_len) {
          iov->iov_len -= (size_t)cur_read_bytes;
          iov->iov_base = (char *)iov->iov_base + cur_read_bytes;
          cur_read_bytes = 0;
        } else {
          cur_read_bytes -= (ptrdiff_t)iov->iov_len;
          iov_size--;
          iov++;
        }
      }
    } else if (cur_read_bytes < 0) {
      const int error = os_translate_sys_error(errno);
      errno = 0;
      if (non_blocking && error == UV_EAGAIN) {
        break;
      } else if (error == UV_EINTR || error == UV_EAGAIN) {
        continue;
      } else if (error == UV_ENOMEM && !did_try_to_free) {
        try_to_free_memory();
        did_try_to_free = true;
        continue;
      } else {
        return (ptrdiff_t)error;
      }
    }
  }
  return (ptrdiff_t)read_bytes;
}
#endif  // HAVE_READV

/// Write to a file
///
/// @param[in]  fd  File descriptor to write to.
/// @param[in]  buf  Data to write. May be NULL if size is zero.
/// @param[in]  size  Amount of bytes to write.
/// @param[in]  non_blocking  Do not restart syscall if EAGAIN was encountered.
///
/// @return Number of bytes written or libuv error code (< 0).
ptrdiff_t os_write(const int fd, const char *const buf, const size_t size, const bool non_blocking)
  FUNC_ATTR_WARN_UNUSED_RESULT
{
  if (buf == NULL) {
    assert(size == 0);
    return 0;
  }
  size_t written_bytes = 0;
  while (written_bytes != size) {
    assert(size >= written_bytes);
    const ptrdiff_t cur_written_bytes = write(fd, buf + written_bytes,
                                              IO_COUNT(size - written_bytes));
    if (cur_written_bytes > 0) {
      written_bytes += (size_t)cur_written_bytes;
    }
    if (cur_written_bytes < 0) {
      const int error = os_translate_sys_error(errno);
      errno = 0;
      if (non_blocking && error == UV_EAGAIN) {
        break;
      } else if (error == UV_EINTR || error == UV_EAGAIN) {
        continue;
      } else {
        return error;
      }
    }
    if (cur_written_bytes == 0) {
      return UV_UNKNOWN;
    }
  }
  return (ptrdiff_t)written_bytes;
}

/// Copies a file from `path` to `new_path`.
///
/// @see http://docs.libuv.org/en/v1.x/fs.html#c.uv_fs_copyfile
///
/// @param path Path of file to be copied
/// @param path_new Path of new file
/// @param flags Bitwise OR of flags defined in <uv.h>
/// @return 0 on success, or libuv error code on failure.
int os_copy(const char *path, const char *new_path, int flags)
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_copyfile, path, new_path, flags, NULL);
  return r;
}

/// Flushes file modifications to disk.
///
/// @param fd the file descriptor of the file to flush to disk.
///
/// @return 0 on success, or libuv error code on failure.
int os_fsync(int fd)
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_fsync, fd, NULL);
  g_stats.fsync++;
  return r;
}

/// Get stat information for a file.
///
/// @return libuv return code, or -errno
static int os_stat(const char *name, uv_stat_t *statbuf)
  FUNC_ATTR_NONNULL_ARG(2)
{
  if (!name) {
    return UV_EINVAL;
  }
  uv_fs_t request;
  fs_loop_lock();
  int result = uv_fs_stat(&fs_loop, &request, name, NULL);
  fs_loop_unlock();
  if (result == kLibuvSuccess) {
    *statbuf = request.statbuf;
  }
  uv_fs_req_cleanup(&request);
  return result;
}

/// Get the file permissions for a given file.
///
/// @return libuv error code on error.
int32_t os_getperm(const char *name)
{
  uv_stat_t statbuf;
  int stat_result = os_stat(name, &statbuf);
  if (stat_result == kLibuvSuccess) {
    return (int32_t)statbuf.st_mode;
  }
  return stat_result;
}

/// Set the permission of a file.
///
/// @return `OK` for success, `FAIL` for failure.
int os_setperm(const char *const name, int perm)
  FUNC_ATTR_NONNULL_ALL
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_chmod, name, perm, NULL);
  return (r == kLibuvSuccess ? OK : FAIL);
}

#if defined(HAVE_ACL)
# ifdef HAVE_SYS_ACL_H
#  include <sys/acl.h>
# endif
# ifdef HAVE_SYS_ACCESS_H
#  include <sys/access.h>
# endif

// Return a pointer to the ACL of file "fname" in allocated memory.
// Return NULL if the ACL is not available for whatever reason.
vim_acl_T os_get_acl(const char *fname)
{
  vim_acl_T ret = NULL;
  return ret;
}

// Set the ACL of file "fname" to "acl" (unless it's NULL).
void os_set_acl(const char *fname, vim_acl_T aclent)
{
  if (aclent == NULL) {
    return;
  }
}

void os_free_acl(vim_acl_T aclent)
{
  if (aclent == NULL) {
    return;
  }
}
#endif

#ifdef UNIX
/// Checks if the current user owns a file.
///
/// Uses both uv_fs_stat() and uv_fs_lstat() via os_fileinfo() and
/// os_fileinfo_link() respectively for extra security.
bool os_file_owned(const char *fname)
  FUNC_ATTR_NONNULL_ALL
{
  uid_t uid = getuid();
  FileInfo finfo;
  bool file_owned = os_fileinfo(fname, &finfo) && finfo.stat.st_uid == uid;
  bool link_owned = os_fileinfo_link(fname, &finfo) && finfo.stat.st_uid == uid;
  return file_owned && link_owned;
}
#else
bool os_file_owned(const char *fname)
{
  return true;  // TODO(justinmk): Windows. #8244
}
#endif

/// Changes the owner and group of a file, like chown(2).
///
/// @return 0 on success, or libuv error code on failure.
///
/// @note If `owner` or `group` is -1, then that ID is not changed.
int os_chown(const char *path, uv_uid_t owner, uv_gid_t group)
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_chown, path, owner, group, NULL);
  return r;
}

/// Changes the owner and group of the file referred to by the open file
/// descriptor, like fchown(2).
///
/// @return 0 on success, or libuv error code on failure.
///
/// @note If `owner` or `group` is -1, then that ID is not changed.
int os_fchown(int fd, uv_uid_t owner, uv_gid_t group)
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_fchown, fd, owner, group, NULL);
  return r;
}

/// Check if a path exists.
///
/// @return `true` if `path` exists
bool os_path_exists(const char *path)
{
  uv_stat_t statbuf;
  return os_stat(path, &statbuf) == kLibuvSuccess;
}

/// Sets file access and modification times.
///
/// @see POSIX utime(2)
///
/// @param path   File path.
/// @param atime  Last access time.
/// @param mtime  Last modification time.
///
/// @return 0 on success, or negative error code.
int os_file_settime(const char *path, double atime, double mtime)
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_utime, path, atime, mtime, NULL);
  return r;
}

/// Check if a file is readable.
///
/// @return true if `name` is readable, otherwise false.
bool os_file_is_readable(const char *name)
  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_access, name, R_OK, NULL);
  return (r == 0);
}

/// Check if a file is writable.
///
/// @return `0` if `name` is not writable,
/// @return `1` if `name` is writable,
/// @return `2` for a directory which we have rights to write into.
int os_file_is_writable(const char *name)
  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_access, name, W_OK, NULL);
  if (r == 0) {
    return os_isdir(name) ? 2 : 1;
  }
  return 0;
}

/// Rename a file or directory.
///
/// @return `OK` for success, `FAIL` for failure.
int os_rename(const char *path, const char *new_path)
  FUNC_ATTR_NONNULL_ALL
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_rename, path, new_path, NULL);
  return (r == kLibuvSuccess ? OK : FAIL);
}

/// Make a directory.
///
/// @return `0` for success, libuv error code for failure.
int os_mkdir(const char *path, int32_t mode)
  FUNC_ATTR_NONNULL_ALL
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_mkdir, path, mode, NULL);
  return r;
}

/// Make a directory, with higher levels when needed
///
/// @param[in]  dir  Directory to create.
/// @param[in]  mode  Permissions for the newly-created directory.
/// @param[out]  failed_dir  If it failed to create directory, then this
///                          argument is set to an allocated string containing
///                          the name of the directory which os_mkdir_recurse
///                          failed to create. I.e. it will contain dir or any
///                          of the higher level directories.
///
/// @return `0` for success, libuv error code for failure.
int os_mkdir_recurse(const char *const dir, int32_t mode, char **const failed_dir)
  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
  // Get end of directory name in "dir".
  // We're done when it's "/" or "c:/".
  const size_t dirlen = strlen(dir);
  char *const curdir = xmemdupz(dir, dirlen);
  char *const past_head = get_past_head(curdir);
  char *e = curdir + dirlen;
  const char *const real_end = e;
  const char past_head_save = *past_head;
  while (!os_isdir(curdir)) {
    e = path_tail_with_sep(curdir);
    if (e <= past_head) {
      *past_head = NUL;
      break;
    }
    *e = NUL;
  }
  while (e != real_end) {
    if (e > past_head) {
      *e = PATHSEP;
    } else {
      *past_head = past_head_save;
    }
    const size_t component_len = strlen(e);
    e += component_len;
    if (e == real_end
        && memcnt(e - component_len, PATHSEP, component_len) == component_len) {
      // Path ends with something like "////". Ignore this.
      break;
    }
    int ret;
    if ((ret = os_mkdir(curdir, mode)) != 0) {
      *failed_dir = curdir;
      return ret;
    }
  }
  xfree(curdir);
  return 0;
}

/// Create the parent directory of a file if it does not exist
///
/// @param[in] fname Full path of the file name whose parent directories
///                  we want to create
/// @param[in] mode  Permissions for the newly-created directory.
///
/// @return `0` for success, libuv error code for failure.
int os_file_mkdir(char *fname, int32_t mode)
  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
  if (!dir_of_file_exists(fname)) {
    char *tail = path_tail_with_sep(fname);
    char *last_char = tail + strlen(tail) - 1;
    if (vim_ispathsep(*last_char)) {
      emsg(_(e_noname));
      return -1;
    }
    char c = *tail;
    *tail = NUL;
    int r;
    char *failed_dir;
    if (((r = os_mkdir_recurse(fname, mode, &failed_dir)) < 0)) {
      semsg(_(e_mkdir), failed_dir, os_strerror(r));
      xfree(failed_dir);
    }
    *tail = c;
    return r;
  }
  return 0;
}

/// Create a unique temporary directory.
///
/// @param[in] template Template of the path to the directory with XXXXXX
///                     which would be replaced by random chars.
/// @param[out] path Path to created directory for success, undefined for
///                  failure.
/// @return `0` for success, non-zero for failure.
int os_mkdtemp(const char *template, char *path)
  FUNC_ATTR_NONNULL_ALL
{
  uv_fs_t request;
  fs_loop_lock();
  int result = uv_fs_mkdtemp(&fs_loop, &request, template, NULL);
  fs_loop_unlock();
  if (result == kLibuvSuccess) {
    xstrlcpy(path, request.path, TEMP_FILE_PATH_MAXLEN);
  }
  uv_fs_req_cleanup(&request);
  return result;
}

/// Remove a directory.
///
/// @return `0` for success, non-zero for failure.
int os_rmdir(const char *path)
  FUNC_ATTR_NONNULL_ALL
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_rmdir, path, NULL);
  return r;
}

/// Opens a directory.
/// @param[out] dir   The Directory object.
/// @param      path  Path to the directory.
/// @returns true if dir contains one or more items, false if not or an error
///          occurred.
bool os_scandir(Directory *dir, const char *path)
  FUNC_ATTR_NONNULL_ALL
{
  fs_loop_lock();
  int r = uv_fs_scandir(&fs_loop, &dir->request, path, 0, NULL);
  fs_loop_unlock();
  if (r < 0) {
    os_closedir(dir);
  }
  return r >= 0;
}

/// Increments the directory pointer.
/// @param dir  The Directory object.
/// @returns a pointer to the next path in `dir` or `NULL`.
const char *os_scandir_next(Directory *dir)
  FUNC_ATTR_NONNULL_ALL
{
  int err = uv_fs_scandir_next(&dir->request, &dir->ent);
  return err != UV_EOF ? dir->ent.name : NULL;
}

/// Frees memory associated with `os_scandir()`.
/// @param dir  The directory.
void os_closedir(Directory *dir)
  FUNC_ATTR_NONNULL_ALL
{
  uv_fs_req_cleanup(&dir->request);
}

/// Remove a file.
///
/// @return `0` for success, non-zero for failure.
int os_remove(const char *path)
  FUNC_ATTR_NONNULL_ALL
{
  int r;
  RUN_UV_FS_FUNC(r, uv_fs_unlink, path, NULL);
  return r;
}

/// Get the file information for a given path
///
/// @param path Path to the file.
/// @param[out] file_info Pointer to a FileInfo to put the information in.
/// @return `true` on success, `false` for failure.
bool os_fileinfo(const char *path, FileInfo *file_info)
  FUNC_ATTR_NONNULL_ARG(2)
{
  CLEAR_POINTER(file_info);
  return os_stat(path, &(file_info->stat)) == kLibuvSuccess;
}

/// Get the file information for a given path without following links
///
/// @param path Path to the file.
/// @param[out] file_info Pointer to a FileInfo to put the information in.
/// @return `true` on success, `false` for failure.
bool os_fileinfo_link(const char *path, FileInfo *file_info)
  FUNC_ATTR_NONNULL_ARG(2)
{
  CLEAR_POINTER(file_info);
  if (path == NULL) {
    return false;
  }
  uv_fs_t request;
  fs_loop_lock();
  bool ok = uv_fs_lstat(&fs_loop, &request, path, NULL) == kLibuvSuccess;
  fs_loop_unlock();
  if (ok) {
    file_info->stat = request.statbuf;
  }
  uv_fs_req_cleanup(&request);
  return ok;
}

/// Get the file information for a given file descriptor
///
/// @param file_descriptor File descriptor of the file.
/// @param[out] file_info Pointer to a FileInfo to put the information in.
/// @return `true` on success, `false` for failure.
bool os_fileinfo_fd(int file_descriptor, FileInfo *file_info)
  FUNC_ATTR_NONNULL_ALL
{
  uv_fs_t request;
  CLEAR_POINTER(file_info);
  fs_loop_lock();
  bool ok = uv_fs_fstat(&fs_loop,
                        &request,
                        file_descriptor,
                        NULL) == kLibuvSuccess;
  if (ok) {
    file_info->stat = request.statbuf;
  }
  uv_fs_req_cleanup(&request);
  fs_loop_unlock();
  return ok;
}

/// Compare the inodes of two FileInfos
///
/// @return `true` if the two FileInfos represent the same file.
bool os_fileinfo_id_equal(const FileInfo *file_info_1, const FileInfo *file_info_2)
  FUNC_ATTR_NONNULL_ALL
{
  return file_info_1->stat.st_ino == file_info_2->stat.st_ino
         && file_info_1->stat.st_dev == file_info_2->stat.st_dev;
}

/// Get the `FileID` of a `FileInfo`
///
/// @param file_info Pointer to the `FileInfo`
/// @param[out] file_id Pointer to a `FileID`
void os_fileinfo_id(const FileInfo *file_info, FileID *file_id)
  FUNC_ATTR_NONNULL_ALL
{
  file_id->inode = file_info->stat.st_ino;
  file_id->device_id = file_info->stat.st_dev;
}

/// Get the inode of a `FileInfo`
///
/// @deprecated Use `FileID` instead, this function is only needed in memline.c
/// @param file_info Pointer to the `FileInfo`
/// @return the inode number
uint64_t os_fileinfo_inode(const FileInfo *file_info)
  FUNC_ATTR_NONNULL_ALL
{
  return file_info->stat.st_ino;
}

/// Get the size of a file from a `FileInfo`.
///
/// @return filesize in bytes.
uint64_t os_fileinfo_size(const FileInfo *file_info)
  FUNC_ATTR_NONNULL_ALL
{
  return file_info->stat.st_size;
}

/// Get the number of hardlinks from a `FileInfo`.
///
/// @return number of hardlinks.
uint64_t os_fileinfo_hardlinks(const FileInfo *file_info)
  FUNC_ATTR_NONNULL_ALL
{
  return file_info->stat.st_nlink;
}

/// Get the blocksize from a `FileInfo`.
///
/// @return blocksize in bytes.
uint64_t os_fileinfo_blocksize(const FileInfo *file_info)
  FUNC_ATTR_NONNULL_ALL
{
  return file_info->stat.st_blksize;
}

/// Get the `FileID` for a given path
///
/// @param path Path to the file.
/// @param[out] file_info Pointer to a `FileID` to fill in.
/// @return `true` on success, `false` for failure.
bool os_fileid(const char *path, FileID *file_id)
  FUNC_ATTR_NONNULL_ALL
{
  uv_stat_t statbuf;
  if (os_stat(path, &statbuf) == kLibuvSuccess) {
    file_id->inode = statbuf.st_ino;
    file_id->device_id = statbuf.st_dev;
    return true;
  }
  return false;
}

/// Check if two `FileID`s are equal
///
/// @param file_id_1 Pointer to first `FileID`
/// @param file_id_2 Pointer to second `FileID`
/// @return `true` if the two `FileID`s represent te same file.
bool os_fileid_equal(const FileID *file_id_1, const FileID *file_id_2)
  FUNC_ATTR_NONNULL_ALL
{
  return file_id_1->inode == file_id_2->inode
         && file_id_1->device_id == file_id_2->device_id;
}

/// Check if a `FileID` is equal to a `FileInfo`
///
/// @param file_id Pointer to a `FileID`
/// @param file_info Pointer to a `FileInfo`
/// @return `true` if the `FileID` and the `FileInfo` represent te same file.
bool os_fileid_equal_fileinfo(const FileID *file_id, const FileInfo *file_info)
  FUNC_ATTR_NONNULL_ALL
{
  return file_id->inode == file_info->stat.st_ino
         && file_id->device_id == file_info->stat.st_dev;
}

/// Return the canonicalized absolute pathname.
///
/// @param[in] name Filename to be canonicalized.
/// @param[out] buf Buffer to store the canonicalized values. A minimum length
//                  of MAXPATHL+1 is required. If it is NULL, memory is
//                  allocated. In that case, the caller should deallocate this
//                  buffer.
///
/// @return pointer to the buf on success, or NULL.
char *os_realpath(const char *name, char *buf)
  FUNC_ATTR_NONNULL_ARG(1)
{
  uv_fs_t request;
  fs_loop_lock();
  int result = uv_fs_realpath(&fs_loop, &request, name, NULL);
  if (result == kLibuvSuccess) {
    if (buf == NULL) {
      buf = xmallocz(MAXPATHL);
    }
    xstrlcpy(buf, request.ptr, MAXPATHL + 1);
  }
  uv_fs_req_cleanup(&request);
  fs_loop_unlock();
  return result == kLibuvSuccess ? buf : NULL;
}

#ifdef MSWIN
# include <shlobj.h>

/// When "fname" is the name of a shortcut (*.lnk) resolve the file it points
/// to and return that name in allocated memory.
/// Otherwise NULL is returned.
char *os_resolve_shortcut(const char *fname)
  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC
{
  HRESULT hr;
  IPersistFile *ppf = NULL;
  OLECHAR wsz[MAX_PATH];
  char *rfname = NULL;
  IShellLinkW *pslw = NULL;
  WIN32_FIND_DATAW ffdw;

  // Check if the file name ends in ".lnk". Avoid calling CoCreateInstance(),
  // it's quite slow.
  if (fname == NULL) {
    return rfname;
  }
  const size_t len = strlen(fname);
  if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0) {
    return rfname;
  }

  CoInitialize(NULL);

  // create a link manager object and request its interface
  hr = CoCreateInstance(&CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                        &IID_IShellLinkW, (void **)&pslw);
  if (hr == S_OK) {
    wchar_t *p;
    const int r = utf8_to_utf16(fname, -1, &p);
    if (r != 0) {
      semsg("utf8_to_utf16 failed: %d", r);
    } else if (p != NULL) {
      // Get a pointer to the IPersistFile interface.
      hr = pslw->lpVtbl->QueryInterface(pslw, &IID_IPersistFile, (void **)&ppf);
      if (hr != S_OK) {
        goto shortcut_errorw;
      }

      // "load" the name and resolve the link
      hr = ppf->lpVtbl->Load(ppf, p, STGM_READ);
      if (hr != S_OK) {
        goto shortcut_errorw;
      }

# if 0  // This makes Vim wait a long time if the target does not exist.
      hr = pslw->lpVtbl->Resolve(pslw, NULL, SLR_NO_UI);
      if (hr != S_OK) {
        goto shortcut_errorw;
      }
# endif

      // Get the path to the link target.
      ZeroMemory(wsz, MAX_PATH * sizeof(wchar_t));
      hr = pslw->lpVtbl->GetPath(pslw, wsz, MAX_PATH, &ffdw, 0);
      if (hr == S_OK && wsz[0] != NUL) {
        const int r2 = utf16_to_utf8(wsz, -1, &rfname);
        if (r2 != 0) {
          semsg("utf16_to_utf8 failed: %d", r2);
        }
      }

shortcut_errorw:
      xfree(p);
      goto shortcut_end;
    }
  }

shortcut_end:
  // Release all interface pointers (both belong to the same object)
  if (ppf != NULL) {
    ppf->lpVtbl->Release(ppf);
  }
  if (pslw != NULL) {
    pslw->lpVtbl->Release(pslw);
  }

  CoUninitialize();
  return rfname;
}

# define IS_PATH_SEP(c) ((c) == L'\\' || (c) == L'/')
/// Returns true if the path contains a reparse point (junction or symbolic
/// link). Otherwise false in returned.
bool os_is_reparse_point_include(const char *path)
{
  wchar_t *p, *q, *utf16_path;
  wchar_t buf[MAX_PATH];
  DWORD attr;
  bool result = false;

  const int r = utf8_to_utf16(path, -1, &utf16_path);
  if (r != 0) {
    semsg("utf8_to_utf16 failed: %d", r);
    return false;
  }

  p = utf16_path;
  if (isalpha((uint8_t)p[0]) && p[1] == L':' && IS_PATH_SEP(p[2])) {
    p += 3;
  } else if (IS_PATH_SEP(p[0]) && IS_PATH_SEP(p[1])) {
    p += 2;
  }

  while (*p != L'\0') {
    q = wcspbrk(p, L"\\/");
    if (q == NULL) {
      p = q = utf16_path + wcslen(utf16_path);
    } else {
      p = q + 1;
    }
    if (q - utf16_path >= MAX_PATH) {
      break;
    }
    wcsncpy(buf, utf16_path, (size_t)(q - utf16_path));
    buf[q - utf16_path] = L'\0';
    attr = GetFileAttributesW(buf);
    if (attr != INVALID_FILE_ATTRIBUTES
        && (attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
      result = true;
      break;
    }
  }
  xfree(utf16_path);
  return result;
}
#endif