-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
fs.c
1472 lines (1362 loc) · 39.1 KB
/
fs.c
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
// 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 <sys/types.h>
#include <uv.h>
#ifdef MSWIN
# include <shlobj.h>
#endif
#include "auto/config.h"
#include "nvim/os/fs.h"
#include "nvim/os/os_defs.h"
#if defined(HAVE_ACL)
# ifdef HAVE_SYS_ACL_H
# include <sys/acl.h>
# endif
# ifdef HAVE_SYS_ACCESS_H
# include <sys/access.h>
# endif
#endif
#ifdef HAVE_XATTR
# include <sys/xattr.h>
#endif
#include "nvim/api/private/helpers.h"
#include "nvim/ascii_defs.h"
#include "nvim/gettext_defs.h"
#include "nvim/globals.h"
#include "nvim/log.h"
#include "nvim/macros_defs.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/option_vars.h"
#include "nvim/os/os.h"
#include "nvim/path.h"
#include "nvim/types_defs.h"
#include "nvim/ui.h"
#include "nvim/vim_defs.h"
#ifdef HAVE_SYS_UIO_H
# include <sys/uio.h>
#endif
#ifdef MSWIN
# include "nvim/mbyte.h"
# include "nvim/option.h"
# include "nvim/os/os_win_console.h"
# include "nvim/strings.h"
#endif
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "os/fs.c.generated.h"
#endif
#ifdef HAVE_XATTR
static const char e_xattr_erange[]
= N_("E1506: Buffer too small to copy xattr value or key");
static const char e_xattr_e2big[]
= N_("E1508: Size of the extended attribute value is larger than the maximum size allowed");
static const char e_xattr_other[]
= N_("E1509: Error occurred when reading or writing extended attribute");
#endif
#define RUN_UV_FS_FUNC(ret, func, ...) \
do { \
uv_fs_t req; \
ret = func(NULL, &req, __VA_ARGS__); \
uv_fs_req_cleanup(&req); \
} while (0)
// Many fs functions from libuv return that value on success.
static const int kLibuvSuccess = 0;
/// 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(0, "chdir(%s)", path);
verbose_leave();
}
int err = uv_chdir(path);
if (err == 0) {
ui_call_chdir(cstr_as_string(path));
}
return err;
}
/// 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;
if (uv_fs_lstat(NULL, &request, name, NULL) != kLibuvSuccess) {
return false;
}
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;
while (true) {
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;
}
/// Open the file descriptor for stdin.
int os_open_stdin_fd(void)
{
int stdin_dup_fd;
if (stdin_fd > 0) {
stdin_dup_fd = stdin_fd;
} else {
stdin_dup_fd = os_dup(STDIN_FILENO);
#ifdef MSWIN
// Replace the original stdin with the console input handle.
os_replace_stdin_to_conin();
#endif
}
return stdin_dup_fd;
}
/// 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;
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 {
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;
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 {
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;
int result = uv_fs_stat(NULL, &request, name, NULL);
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);
}
#ifdef HAVE_XATTR
/// Copy extended attributes from_file to to_file
void os_copy_xattr(const char *from_file, const char *to_file)
{
if (from_file == NULL) {
return;
}
// get the length of the extended attributes
ssize_t size = listxattr((char *)from_file, NULL, 0);
// not supported or no attributes to copy
if (size <= 0) {
return;
}
char *xattr_buf = xmalloc((size_t)size);
size = listxattr(from_file, xattr_buf, (size_t)size);
ssize_t tsize = size;
errno = 0;
ssize_t max_vallen = 0;
char *val = NULL;
const char *errmsg = NULL;
for (int round = 0; round < 2; round++) {
char *key = xattr_buf;
if (round == 1) {
size = tsize;
}
while (size > 0) {
ssize_t vallen = getxattr(from_file, key, val, round ? (size_t)max_vallen : 0);
// only set the attribute in the second round
if (vallen >= 0 && round
&& setxattr(to_file, key, val, (size_t)vallen, 0) == 0) {
//
} else if (errno) {
switch (errno) {
case E2BIG:
errmsg = e_xattr_e2big;
goto error_exit;
case ENOTSUP:
case EACCES:
case EPERM:
break;
case ERANGE:
errmsg = e_xattr_erange;
goto error_exit;
default:
errmsg = e_xattr_other;
goto error_exit;
}
}
if (round == 0 && vallen > max_vallen) {
max_vallen = vallen;
}
// add one for terminating null
ssize_t keylen = (ssize_t)strlen(key) + 1;
size -= keylen;
key += keylen;
}
if (round) {
break;
}
val = xmalloc((size_t)max_vallen + 1);
}
error_exit:
xfree(xattr_buf);
xfree(val);
if (errmsg != NULL) {
emsg(_(errmsg));
}
}
#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;
}
}
#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;