-
Notifications
You must be signed in to change notification settings - Fork 907
/
filesystem-disk-unix.c++
1795 lines (1593 loc) · 61.3 KB
/
filesystem-disk-unix.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
// Copyright (c) 2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if !_WIN32
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
// Request 64-bit off_t. (The code will still work if we get 32-bit off_t as long as actual files
// are under 4GB.)
#endif
#include "filesystem.h"
#include "debug.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>
#include "vector.h"
#include "miniposix.h"
#include <algorithm>
#if __linux__
#include <syscall.h>
#include <linux/fs.h>
#include <sys/sendfile.h>
#endif
namespace kj {
namespace {
#define HIDDEN_PREFIX ".kj-tmp."
// Prefix for temp files which should be hidden when listing a directory.
//
// If you change this, make sure to update the unit test.
#ifdef O_CLOEXEC
#define MAYBE_O_CLOEXEC O_CLOEXEC
#else
#define MAYBE_O_CLOEXEC 0
#endif
#ifdef O_DIRECTORY
#define MAYBE_O_DIRECTORY O_DIRECTORY
#else
#define MAYBE_O_DIRECTORY 0
#endif
#if __APPLE__
// Mac OSX defines SEEK_HOLE, but it doesn't work. ("Inappropriate ioctl for device", it says.)
#undef SEEK_HOLE
#endif
#if __BIONIC__
// No no DTTOIF function
#undef DT_UNKNOWN
#endif
static void setCloexec(int fd) KJ_UNUSED;
static void setCloexec(int fd) {
// Set the O_CLOEXEC flag on the given fd.
//
// We try to avoid the need to call this by taking advantage of syscall flags that set it
// atomically on new file descriptors. Unfortunately some platforms do not support such syscalls.
#ifdef FIOCLEX
// Yay, we can set the flag in one call.
KJ_SYSCALL_HANDLE_ERRORS(ioctl(fd, FIOCLEX)) {
case EINVAL:
case EOPNOTSUPP:
break;
default:
KJ_FAIL_SYSCALL("ioctl(fd, FIOCLEX)", error) { break; }
break;
} else {
// success
return;
}
#endif
// Sadness, we must resort to read/modify/write.
//
// (On many platforms, FD_CLOEXEC is the only flag modifiable via F_SETFD and therefore we could
// skip the read... but it seems dangerous to assume that's true of all platforms, and anyway
// most platforms support FIOCLEX.)
int flags;
KJ_SYSCALL(flags = fcntl(fd, F_GETFD));
if (!(flags & FD_CLOEXEC)) {
KJ_SYSCALL(fcntl(fd, F_SETFD, flags | FD_CLOEXEC));
}
}
static Date toKjDate(struct timespec tv) {
return tv.tv_sec * SECONDS + tv.tv_nsec * NANOSECONDS + UNIX_EPOCH;
}
static FsNode::Type modeToType(mode_t mode) {
switch (mode & S_IFMT) {
case S_IFREG : return FsNode::Type::FILE;
case S_IFDIR : return FsNode::Type::DIRECTORY;
case S_IFLNK : return FsNode::Type::SYMLINK;
case S_IFBLK : return FsNode::Type::BLOCK_DEVICE;
case S_IFCHR : return FsNode::Type::CHARACTER_DEVICE;
case S_IFIFO : return FsNode::Type::NAMED_PIPE;
case S_IFSOCK: return FsNode::Type::SOCKET;
default: return FsNode::Type::OTHER;
}
}
static FsNode::Metadata statToMetadata(struct stat& stats) {
// Probably st_ino and st_dev are usually under 32 bits, so mix by rotating st_dev left 32 bits
// and XOR.
uint64_t d = stats.st_dev;
uint64_t hash = ((d << 32) | (d >> 32)) ^ stats.st_ino;
return FsNode::Metadata {
modeToType(stats.st_mode),
implicitCast<uint64_t>(stats.st_size),
implicitCast<uint64_t>(stats.st_blocks * 512u),
#if __APPLE__
toKjDate(stats.st_mtimespec),
#else
toKjDate(stats.st_mtim),
#endif
implicitCast<uint>(stats.st_nlink),
hash
};
}
static bool rmrf(int fd, StringPtr path);
static void rmrfChildrenAndClose(int fd) {
// Assumes fd is seeked to beginning.
DIR* dir = fdopendir(fd);
if (dir == nullptr) {
close(fd);
KJ_FAIL_SYSCALL("fdopendir", errno);
};
KJ_DEFER(closedir(dir));
for (;;) {
errno = 0;
struct dirent* entry = readdir(dir);
if (entry == nullptr) {
int error = errno;
if (error == 0) {
break;
} else {
KJ_FAIL_SYSCALL("readdir", error);
}
}
if (entry->d_name[0] == '.' &&
(entry->d_name[1] == '\0' ||
(entry->d_name[1] == '.' &&
entry->d_name[2] == '\0'))) {
// ignore . and ..
} else {
#ifdef DT_UNKNOWN // d_type is not available on all platforms.
if (entry->d_type == DT_DIR) {
int subdirFd;
KJ_SYSCALL(subdirFd = openat(
fd, entry->d_name, O_RDONLY | MAYBE_O_DIRECTORY | MAYBE_O_CLOEXEC | O_NOFOLLOW));
rmrfChildrenAndClose(subdirFd);
KJ_SYSCALL(unlinkat(fd, entry->d_name, AT_REMOVEDIR));
} else if (entry->d_type != DT_UNKNOWN) {
KJ_SYSCALL(unlinkat(fd, entry->d_name, 0));
} else {
#endif
KJ_ASSERT(rmrf(fd, entry->d_name));
#ifdef DT_UNKNOWN
}
#endif
}
}
}
static bool rmrf(int fd, StringPtr path) {
struct stat stats;
KJ_SYSCALL_HANDLE_ERRORS(fstatat(fd, path.cStr(), &stats, AT_SYMLINK_NOFOLLOW)) {
case ENOENT:
case ENOTDIR:
// Doesn't exist.
return false;
default:
KJ_FAIL_SYSCALL("lstat(path)", error, path) { return false; }
}
if (S_ISDIR(stats.st_mode)) {
int subdirFd;
KJ_SYSCALL(subdirFd = openat(
fd, path.cStr(), O_RDONLY | MAYBE_O_DIRECTORY | MAYBE_O_CLOEXEC | O_NOFOLLOW)) {
return false;
}
rmrfChildrenAndClose(subdirFd);
KJ_SYSCALL(unlinkat(fd, path.cStr(), AT_REMOVEDIR)) { return false; }
} else {
KJ_SYSCALL(unlinkat(fd, path.cStr(), 0)) { return false; }
}
return true;
}
struct MmapRange {
uint64_t offset;
uint64_t size;
};
static MmapRange getMmapRange(uint64_t offset, uint64_t size) {
// Comes up with an offset and size to pass to mmap(), given an offset and size requested by
// the caller, and considering the fact that mappings must start at a page boundary.
//
// The offset is rounded down to the nearest page boundary, and the size is increased to
// compensate. Note that the endpoint of the mapping is *not* rounded up to a page boundary, as
// mmap() does not actually require this, and it causes trouble on some systems (notably Cygwin).
#ifndef _SC_PAGESIZE
#define _SC_PAGESIZE _SC_PAGE_SIZE
#endif
static const uint64_t pageSize = sysconf(_SC_PAGESIZE);
uint64_t pageMask = pageSize - 1;
uint64_t realOffset = offset & ~pageMask;
return { realOffset, offset + size - realOffset };
}
class MmapDisposer: public ArrayDisposer {
protected:
void disposeImpl(void* firstElement, size_t elementSize, size_t elementCount,
size_t capacity, void (*destroyElement)(void*)) const {
auto range = getMmapRange(reinterpret_cast<uintptr_t>(firstElement),
elementSize * elementCount);
KJ_SYSCALL(munmap(reinterpret_cast<byte*>(range.offset), range.size)) { break; }
}
};
constexpr MmapDisposer mmapDisposer = MmapDisposer();
class DiskHandle {
// We need to implement each of ReadableFile, AppendableFile, File, ReadableDirectory, and
// Directory for disk handles. There is a lot of implementation overlap between these, especially
// stat(), sync(), etc. We can't have everything inherit from a common DiskFsNode that implements
// these because then we get diamond inheritance which means we need to make all our inheritance
// virtual which means downcasting requires RTTI which violates our goal of supporting compiling
// with no RTTI. So instead we have the DiskHandle class which implements all the methods without
// inheriting anything, and then we have DiskFile, DiskDirectory, etc. hold this and delegate to
// it. Ugly, but works.
public:
DiskHandle(AutoCloseFd&& fd): fd(kj::mv(fd)) {}
// OsHandle ------------------------------------------------------------------
AutoCloseFd clone() const {
int fd2;
#ifdef F_DUPFD_CLOEXEC
KJ_SYSCALL_HANDLE_ERRORS(fd2 = fcntl(fd, F_DUPFD_CLOEXEC, 3)) {
case EINVAL:
case EOPNOTSUPP:
// fall back
break;
default:
KJ_FAIL_SYSCALL("fnctl(fd, F_DUPFD_CLOEXEC, 3)", error) { break; }
break;
} else {
return AutoCloseFd(fd2);
}
#endif
KJ_SYSCALL(fd2 = ::dup(fd));
AutoCloseFd result(fd2);
setCloexec(result);
return result;
}
int getFd() const {
return fd.get();
}
void setFd(AutoCloseFd newFd) {
// Used for one hack in DiskFilesystem's constructor...
fd = kj::mv(newFd);
}
// FsNode --------------------------------------------------------------------
FsNode::Metadata stat() const {
struct stat stats;
KJ_SYSCALL(::fstat(fd, &stats));
return statToMetadata(stats);
}
void sync() const {
#if __APPLE__
// For whatever reason, fsync() on OSX only flushes kernel buffers. It does not flush hardware
// disk buffers. This makes it not very useful. But OSX documents fcntl F_FULLFSYNC which does
// the right thing. Why they don't just make fsync() do the right thing, I do not know.
KJ_SYSCALL(fcntl(fd, F_FULLFSYNC));
#else
KJ_SYSCALL(fsync(fd));
#endif
}
void datasync() const {
// The presence of the _POSIX_SYNCHRONIZED_IO define is supposed to tell us that fdatasync()
// exists. But Apple defines this yet doesn't offer fdatasync(). Thanks, Apple.
#if _POSIX_SYNCHRONIZED_IO && !__APPLE__
KJ_SYSCALL(fdatasync(fd));
#else
this->sync();
#endif
}
// ReadableFile --------------------------------------------------------------
size_t read(uint64_t offset, ArrayPtr<byte> buffer) const {
// pread() probably never returns short reads unless it hits EOF. Unfortunately, though, per
// spec we are not allowed to assume this.
size_t total = 0;
while (buffer.size() > 0) {
ssize_t n;
KJ_SYSCALL(n = pread(fd, buffer.begin(), buffer.size(), offset));
if (n == 0) break;
total += n;
offset += n;
buffer = buffer.slice(n, buffer.size());
}
return total;
}
Array<const byte> mmap(uint64_t offset, uint64_t size) const {
if (size == 0) return nullptr; // zero-length mmap() returns EINVAL, so avoid it
auto range = getMmapRange(offset, size);
const void* mapping = ::mmap(NULL, range.size, PROT_READ, MAP_SHARED, fd, range.offset);
if (mapping == MAP_FAILED) {
KJ_FAIL_SYSCALL("mmap", errno);
}
return Array<const byte>(reinterpret_cast<const byte*>(mapping) + (offset - range.offset),
size, mmapDisposer);
}
Array<byte> mmapPrivate(uint64_t offset, uint64_t size) const {
if (size == 0) return nullptr; // zero-length mmap() returns EINVAL, so avoid it
auto range = getMmapRange(offset, size);
void* mapping = ::mmap(NULL, range.size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, range.offset);
if (mapping == MAP_FAILED) {
KJ_FAIL_SYSCALL("mmap", errno);
}
return Array<byte>(reinterpret_cast<byte*>(mapping) + (offset - range.offset),
size, mmapDisposer);
}
// File ----------------------------------------------------------------------
void write(uint64_t offset, ArrayPtr<const byte> data) const {
// pwrite() probably never returns short writes unless there's no space left on disk.
// Unfortunately, though, per spec we are not allowed to assume this.
while (data.size() > 0) {
ssize_t n;
KJ_SYSCALL(n = pwrite(fd, data.begin(), data.size(), offset));
KJ_ASSERT(n > 0, "pwrite() returned zero?");
offset += n;
data = data.slice(n, data.size());
}
}
void zero(uint64_t offset, uint64_t size) const {
// If FALLOC_FL_PUNCH_HOLE is defined, use it to efficiently zero the area.
//
// A fallocate() wrapper was only added to Android's Bionic C library as of API level 21,
// but FALLOC_FL_PUNCH_HOLE is apparently defined in the headers before that, so we'll
// have to explicitly test for that case.
#if defined(FALLOC_FL_PUNCH_HOLE) && !(__ANDROID__ && __BIONIC__ && __ANDROID_API__ < 21)
KJ_SYSCALL_HANDLE_ERRORS(
fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, size)) {
case EOPNOTSUPP:
// fall back to below
break;
default:
KJ_FAIL_SYSCALL("fallocate(FALLOC_FL_PUNCH_HOLE)", error) { return; }
} else {
return;
}
#endif
static const byte ZEROS[4096] = { 0 };
#if __APPLE__ || __CYGWIN__ || (defined(__ANDROID__) && __ANDROID_API__ < 24)
// Mac & Cygwin & Android API levels 23 and lower doesn't have pwritev().
while (size > sizeof(ZEROS)) {
write(offset, ZEROS);
size -= sizeof(ZEROS);
offset += sizeof(ZEROS);
}
write(offset, kj::arrayPtr(ZEROS, size));
#else
// Use a 4k buffer of zeros amplified by iov to write zeros with as few syscalls as possible.
size_t count = (size + sizeof(ZEROS) - 1) / sizeof(ZEROS);
const size_t iovmax = miniposix::iovMax();
KJ_STACK_ARRAY(struct iovec, iov, kj::min(iovmax, count), 16, 256);
for (auto& item: iov) {
item.iov_base = const_cast<byte*>(ZEROS);
item.iov_len = sizeof(ZEROS);
}
while (size > 0) {
size_t iovCount;
if (size >= iov.size() * sizeof(ZEROS)) {
iovCount = iov.size();
} else {
iovCount = size / sizeof(ZEROS);
size_t rem = size % sizeof(ZEROS);
if (rem > 0) {
iov[iovCount++].iov_len = rem;
}
}
ssize_t n;
KJ_SYSCALL(n = pwritev(fd, iov.begin(), count, offset));
KJ_ASSERT(n > 0, "pwrite() returned zero?");
offset += n;
size -= n;
}
#endif
}
void truncate(uint64_t size) const {
KJ_SYSCALL(ftruncate(fd, size));
}
class WritableFileMappingImpl final: public WritableFileMapping {
public:
WritableFileMappingImpl(Array<byte> bytes): bytes(kj::mv(bytes)) {}
ArrayPtr<byte> get() const override {
// const_cast OK because WritableFileMapping does indeed provide a writable view despite
// being const itself.
return arrayPtr(const_cast<byte*>(bytes.begin()), bytes.size());
}
void changed(ArrayPtr<byte> slice) const override {
KJ_REQUIRE(slice.begin() >= bytes.begin() && slice.end() <= bytes.end(),
"byte range is not part of this mapping");
if (slice.size() == 0) return;
// msync() requires page-alignment, apparently, so use getMmapRange() to accomplish that.
auto range = getMmapRange(reinterpret_cast<uintptr_t>(slice.begin()), slice.size());
KJ_SYSCALL(msync(reinterpret_cast<void*>(range.offset), range.size, MS_ASYNC));
}
void sync(ArrayPtr<byte> slice) const override {
KJ_REQUIRE(slice.begin() >= bytes.begin() && slice.end() <= bytes.end(),
"byte range is not part of this mapping");
if (slice.size() == 0) return;
// msync() requires page-alignment, apparently, so use getMmapRange() to accomplish that.
auto range = getMmapRange(reinterpret_cast<uintptr_t>(slice.begin()), slice.size());
KJ_SYSCALL(msync(reinterpret_cast<void*>(range.offset), range.size, MS_SYNC));
}
private:
Array<byte> bytes;
};
Own<const WritableFileMapping> mmapWritable(uint64_t offset, uint64_t size) const {
if (size == 0) {
// zero-length mmap() returns EINVAL, so avoid it
return heap<WritableFileMappingImpl>(nullptr);
}
auto range = getMmapRange(offset, size);
void* mapping = ::mmap(NULL, range.size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, range.offset);
if (mapping == MAP_FAILED) {
KJ_FAIL_SYSCALL("mmap", errno);
}
auto array = Array<byte>(reinterpret_cast<byte*>(mapping) + (offset - range.offset),
size, mmapDisposer);
return heap<WritableFileMappingImpl>(kj::mv(array));
}
size_t copyChunk(uint64_t offset, int fromFd, uint64_t fromOffset, uint64_t size) const {
// Copies a range of bytes from `fromFd` to this file in the most efficient way possible for
// the OS. Only returns less than `size` if EOF. Does not account for holes.
#if __linux__
{
KJ_SYSCALL(lseek(fd, offset, SEEK_SET));
off_t fromPos = fromOffset;
off_t end = fromOffset + size;
while (fromPos < end) {
ssize_t n;
KJ_SYSCALL_HANDLE_ERRORS(n = sendfile(fd, fromFd, &fromPos, end - fromPos)) {
case EINVAL:
case ENOSYS:
goto sendfileNotAvailable;
default:
KJ_FAIL_SYSCALL("sendfile", error) { return fromPos - fromOffset; }
}
if (n == 0) break;
}
return fromPos - fromOffset;
}
sendfileNotAvailable:
#endif
uint64_t total = 0;
while (size > 0) {
byte buffer[4096];
ssize_t n;
KJ_SYSCALL(n = pread(fromFd, buffer, kj::min(sizeof(buffer), size), fromOffset));
if (n == 0) break;
write(offset, arrayPtr(buffer, n));
fromOffset += n;
offset += n;
total += n;
size -= n;
}
return total;
}
kj::Maybe<size_t> copy(uint64_t offset, const ReadableFile& from,
uint64_t fromOffset, uint64_t size) const {
KJ_IF_MAYBE(otherFd, from.getFd()) {
#ifdef FICLONE
if (offset == 0 && fromOffset == 0 && size == kj::maxValue && stat().size == 0) {
if (ioctl(fd, FICLONE, *otherFd) >= 0) {
return stat().size;
}
} else if (size > 0) { // src_length = 0 has special meaning for the syscall, so avoid.
struct file_clone_range range;
memset(&range, 0, sizeof(range));
range.src_fd = *otherFd;
range.dest_offset = offset;
range.src_offset = fromOffset;
range.src_length = size == kj::maxValue ? 0 : size;
if (ioctl(fd, FICLONERANGE, &range) >= 0) {
// TODO(someday): What does FICLONERANGE actually do if the range goes past EOF? The docs
// don't say. Maybe it only copies the parts that exist. Maybe it punches holes for the
// rest. Where does the destination file's EOF marker end up? Who knows?
return kj::min(from.stat().size - fromOffset, size);
}
} else {
// size == 0
return size_t(0);
}
// ioctl failed. Almost all failures documented for these are of the form "the operation is
// not supported for the filesystem(s) specified", so fall back to other approaches.
#endif
off_t toPos = offset;
off_t fromPos = fromOffset;
off_t end = size == kj::maxValue ? off_t(kj::maxValue) : off_t(fromOffset + size);
for (;;) {
// Handle data.
{
// Find out how much data there is before the next hole.
off_t nextHole;
#ifdef SEEK_HOLE
KJ_SYSCALL_HANDLE_ERRORS(nextHole = lseek(*otherFd, fromPos, SEEK_HOLE)) {
case EINVAL:
// SEEK_HOLE probably not supported. Assume no holes.
nextHole = end;
break;
case ENXIO:
// Past EOF. Stop here.
return fromPos - fromOffset;
default:
KJ_FAIL_SYSCALL("lseek(fd, pos, SEEK_HOLE)", error) { return fromPos - fromOffset; }
}
#else
// SEEK_HOLE not supported. Assume no holes.
nextHole = end;
#endif
// Copy the next chunk of data.
off_t copyTo = kj::min(end, nextHole);
size_t amount = copyTo - fromPos;
if (amount > 0) {
size_t n = copyChunk(toPos, *otherFd, fromPos, amount);
fromPos += n;
toPos += n;
if (n < amount) {
return fromPos - fromOffset;
}
}
if (fromPos == end) {
return fromPos - fromOffset;
}
}
#ifdef SEEK_HOLE
// Handle hole.
{
// Find out how much hole there is before the next data.
off_t nextData;
KJ_SYSCALL_HANDLE_ERRORS(nextData = lseek(*otherFd, fromPos, SEEK_DATA)) {
case EINVAL:
// SEEK_DATA probably not supported. But we should only have gotten here if we
// were expecting a hole.
KJ_FAIL_ASSERT("can't determine hole size; SEEK_DATA not supported");
break;
case ENXIO:
// No more data. Set to EOF.
KJ_SYSCALL(nextData = lseek(*otherFd, 0, SEEK_END));
if (nextData > end) {
end = nextData;
}
break;
default:
KJ_FAIL_SYSCALL("lseek(fd, pos, SEEK_HOLE)", error) { return fromPos - fromOffset; }
}
// Write zeros.
off_t zeroTo = kj::min(end, nextData);
off_t amount = zeroTo - fromPos;
if (amount > 0) {
zero(toPos, amount);
toPos += amount;
fromPos = zeroTo;
}
if (fromPos == end) {
return fromPos - fromOffset;
}
}
#endif
}
}
// Indicates caller should call File::copy() default implementation.
return nullptr;
}
// ReadableDirectory ---------------------------------------------------------
template <typename Func>
auto list(bool needTypes, Func&& func) const
-> Array<Decay<decltype(func(instance<StringPtr>(), instance<FsNode::Type>()))>> {
// Seek to start of directory.
KJ_SYSCALL(lseek(fd, 0, SEEK_SET));
// Unfortunately, fdopendir() takes ownership of the file descriptor. Therefore we need to
// make a duplicate.
int duped;
KJ_SYSCALL(duped = dup(fd));
DIR* dir = fdopendir(duped);
if (dir == nullptr) {
close(duped);
KJ_FAIL_SYSCALL("fdopendir", errno);
}
KJ_DEFER(closedir(dir));
typedef Decay<decltype(func(instance<StringPtr>(), instance<FsNode::Type>()))> Entry;
kj::Vector<Entry> entries;
for (;;) {
errno = 0;
struct dirent* entry = readdir(dir);
if (entry == nullptr) {
int error = errno;
if (error == 0) {
break;
} else {
KJ_FAIL_SYSCALL("readdir", error);
}
}
kj::StringPtr name = entry->d_name;
if (name != "." && name != ".." && !name.startsWith(HIDDEN_PREFIX)) {
#ifdef DT_UNKNOWN // d_type is not available on all platforms.
if (entry->d_type != DT_UNKNOWN) {
entries.add(func(name, modeToType(DTTOIF(entry->d_type))));
} else {
#endif
if (needTypes) {
// Unknown type. Fall back to stat.
struct stat stats;
KJ_SYSCALL(fstatat(fd, name.cStr(), &stats, AT_SYMLINK_NOFOLLOW));
entries.add(func(name, modeToType(stats.st_mode)));
} else {
entries.add(func(name, FsNode::Type::OTHER));
}
#ifdef DT_UNKNOWN
}
#endif
}
}
auto result = entries.releaseAsArray();
std::sort(result.begin(), result.end());
return result;
}
Array<String> listNames() const {
return list(false, [](StringPtr name, FsNode::Type type) { return heapString(name); });
}
Array<ReadableDirectory::Entry> listEntries() const {
return list(true, [](StringPtr name, FsNode::Type type) {
return ReadableDirectory::Entry { type, heapString(name), };
});
}
bool exists(PathPtr path) const {
KJ_SYSCALL_HANDLE_ERRORS(faccessat(fd, path.toString().cStr(), F_OK, 0)) {
case ENOENT:
case ENOTDIR:
return false;
default:
KJ_FAIL_SYSCALL("faccessat(fd, path)", error, path) { return false; }
}
return true;
}
Maybe<FsNode::Metadata> tryLstat(PathPtr path) const {
struct stat stats;
KJ_SYSCALL_HANDLE_ERRORS(fstatat(fd, path.toString().cStr(), &stats, AT_SYMLINK_NOFOLLOW)) {
case ENOENT:
case ENOTDIR:
return nullptr;
default:
KJ_FAIL_SYSCALL("faccessat(fd, path)", error, path) { return nullptr; }
}
return statToMetadata(stats);
}
Maybe<Own<const ReadableFile>> tryOpenFile(PathPtr path) const {
int newFd;
KJ_SYSCALL_HANDLE_ERRORS(newFd = openat(
fd, path.toString().cStr(), O_RDONLY | MAYBE_O_CLOEXEC)) {
case ENOENT:
case ENOTDIR:
return nullptr;
default:
KJ_FAIL_SYSCALL("openat(fd, path, O_RDONLY)", error, path) { return nullptr; }
}
kj::AutoCloseFd result(newFd);
#ifndef O_CLOEXEC
setCloexec(result);
#endif
return newDiskReadableFile(kj::mv(result));
}
Maybe<AutoCloseFd> tryOpenSubdirInternal(PathPtr path) const {
int newFd;
KJ_SYSCALL_HANDLE_ERRORS(newFd = openat(
fd, path.toString().cStr(), O_RDONLY | MAYBE_O_CLOEXEC | MAYBE_O_DIRECTORY)) {
case ENOENT:
return nullptr;
case ENOTDIR:
// Could mean that a parent is not a directory, which we treat as "doesn't exist".
// Could also mean that the specified file is not a directory, which should throw.
// Check using exists().
if (!exists(path)) {
return nullptr;
}
KJ_FALLTHROUGH;
default:
KJ_FAIL_SYSCALL("openat(fd, path, O_DIRECTORY)", error, path) { return nullptr; }
}
kj::AutoCloseFd result(newFd);
#ifndef O_CLOEXEC
setCloexec(result);
#endif
return kj::mv(result);
}
Maybe<Own<const ReadableDirectory>> tryOpenSubdir(PathPtr path) const {
return tryOpenSubdirInternal(path).map(newDiskReadableDirectory);
}
Maybe<String> tryReadlink(PathPtr path) const {
size_t trySize = 256;
for (;;) {
KJ_STACK_ARRAY(char, buf, trySize, 256, 4096);
ssize_t n = readlinkat(fd, path.toString().cStr(), buf.begin(), buf.size());
if (n < 0) {
int error = errno;
switch (error) {
case EINTR:
continue;
case ENOENT:
case ENOTDIR:
case EINVAL: // not a link
return nullptr;
default:
KJ_FAIL_SYSCALL("readlinkat(fd, path)", error, path) { return nullptr; }
}
}
if (n >= buf.size()) {
// Didn't give it enough space. Better retry with a bigger buffer.
trySize *= 2;
continue;
}
return heapString(buf.begin(), n);
}
}
// Directory -----------------------------------------------------------------
bool tryMkdir(PathPtr path, WriteMode mode, bool noThrow) const {
// Internal function to make a directory.
auto filename = path.toString();
mode_t acl = has(mode, WriteMode::PRIVATE) ? 0700 : 0777;
KJ_SYSCALL_HANDLE_ERRORS(mkdirat(fd, filename.cStr(), acl)) {
case EEXIST: {
// Apparently this path exists.
if (!has(mode, WriteMode::MODIFY)) {
// Require exclusive create.
return false;
}
// MODIFY is allowed, so we just need to check whether the existing entry is a directory.
struct stat stats;
KJ_SYSCALL_HANDLE_ERRORS(fstatat(fd, filename.cStr(), &stats, 0)) {
default:
// mkdir() says EEXIST but we can't stat it. Maybe it's a dangling link, or maybe
// we can't access it for some reason. Assume failure.
//
// TODO(someday): Maybe we should be creating the directory at the target of the
// link?
goto failed;
}
return (stats.st_mode & S_IFMT) == S_IFDIR;
}
case ENOENT:
if (has(mode, WriteMode::CREATE_PARENT) && path.size() > 0 &&
tryMkdir(path.parent(), WriteMode::CREATE | WriteMode::MODIFY |
WriteMode::CREATE_PARENT, true)) {
// Retry, but make sure we don't try to create the parent again.
return tryMkdir(path, mode - WriteMode::CREATE_PARENT, noThrow);
} else {
goto failed;
}
default:
failed:
if (noThrow) {
// Caller requested no throwing.
return false;
} else {
KJ_FAIL_SYSCALL("mkdirat(fd, path)", error, path);
}
}
return true;
}
kj::Maybe<String> createNamedTemporary(
PathPtr finalName, WriteMode mode, Function<int(StringPtr)> tryCreate) const {
// Create a temporary file which will eventually replace `finalName`.
//
// Calls `tryCreate` to actually create the temporary, passing in the desired path. tryCreate()
// is expected to behave like a syscall, returning a negative value and setting `errno` on
// error. tryCreate() MUST fail with EEXIST if the path exists -- this is not checked in
// advance, since it needs to be checked atomically. In the case of EEXIST, tryCreate() will
// be called again with a new path.
//
// Returns the temporary path that succeeded. Only returns nullptr if there was an exception
// but we're compiled with -fno-exceptions.
if (finalName.size() == 0) {
KJ_FAIL_REQUIRE("can't replace self") { break; }
return nullptr;
}
static uint counter = 0;
static const pid_t pid = getpid();
String pathPrefix;
if (finalName.size() > 1) {
pathPrefix = kj::str(finalName.parent(), '/');
}
auto path = kj::str(pathPrefix, HIDDEN_PREFIX, pid, '.', counter++, '.',
finalName.basename()[0], ".partial");
KJ_SYSCALL_HANDLE_ERRORS(tryCreate(path)) {
case EEXIST:
return createNamedTemporary(finalName, mode, kj::mv(tryCreate));
case ENOENT:
if (has(mode, WriteMode::CREATE_PARENT) && finalName.size() > 1 &&
tryMkdir(finalName.parent(), WriteMode::CREATE | WriteMode::MODIFY |
WriteMode::CREATE_PARENT, true)) {
// Retry, but make sure we don't try to create the parent again.
mode = mode - WriteMode::CREATE_PARENT;
return createNamedTemporary(finalName, mode, kj::mv(tryCreate));
}
KJ_FALLTHROUGH;
default:
KJ_FAIL_SYSCALL("create(path)", error, path) { break; }
return nullptr;
}
return kj::mv(path);
}
bool tryReplaceNode(PathPtr path, WriteMode mode, Function<int(StringPtr)> tryCreate) const {
// Replaces the given path with an object created by calling tryCreate().
//
// tryCreate() must behave like a syscall which creates the node at the path passed to it,
// returning a negative value on error. If the path passed to tryCreate already exists, it
// MUST fail with EEXIST.
//
// When `mode` includes MODIFY, replaceNode() reacts to EEXIST by creating the node in a
// temporary location and then rename()ing it into place.
if (path.size() == 0) {
KJ_FAIL_REQUIRE("can't replace self") { return false; }
}
auto filename = path.toString();
if (has(mode, WriteMode::CREATE)) {
// First try just cerating the node in-place.
KJ_SYSCALL_HANDLE_ERRORS(tryCreate(filename)) {
case EEXIST:
// Target exists.
if (has(mode, WriteMode::MODIFY)) {
// Fall back to MODIFY path, below.
break;
} else {
return false;
}
case ENOENT:
if (has(mode, WriteMode::CREATE_PARENT) && path.size() > 0 &&
tryMkdir(path.parent(), WriteMode::CREATE | WriteMode::MODIFY |
WriteMode::CREATE_PARENT, true)) {
// Retry, but make sure we don't try to create the parent again.
return tryReplaceNode(path, mode - WriteMode::CREATE_PARENT, kj::mv(tryCreate));
}
KJ_FALLTHROUGH;
default:
KJ_FAIL_SYSCALL("create(path)", error, path) { return false; }
} else {
// Success.
return true;
}
}
// Either we don't have CREATE mode or the target already exists. We need to perform a
// replacement instead.
KJ_IF_MAYBE(tempPath, createNamedTemporary(path, mode, kj::mv(tryCreate))) {
if (tryCommitReplacement(filename, fd, *tempPath, mode)) {
return true;
} else {
KJ_SYSCALL_HANDLE_ERRORS(unlinkat(fd, tempPath->cStr(), 0)) {
case ENOENT:
// meh
break;
default:
KJ_FAIL_SYSCALL("unlinkat(fd, tempPath, 0)", error, *tempPath);
}
return false;
}
} else {
// threw, but exceptions are disabled
return false;