-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathsyscalls.cpp
1798 lines (1562 loc) · 52.1 KB
/
syscalls.cpp
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 2021 The Emscripten Authors. All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License. Both these licenses can be
// found in the LICENSE file.
// Syscall implementations.
#define _LARGEFILE64_SOURCE // For F_GETLK64 etc
#include <dirent.h>
#include <emscripten/emscripten.h>
#include <emscripten/heap.h>
#include <emscripten/html5.h>
#include <errno.h>
#include <mutex>
#include <poll.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <syscall_arch.h>
#include <unistd.h>
#include <utility>
#include <vector>
#include <wasi/api.h>
#include "backend.h"
#include "file.h"
#include "file_table.h"
#include "paths.h"
#include "pipe_backend.h"
#include "special_files.h"
#include "wasmfs.h"
// File permission macros for wasmfs.
// Used to improve readability compared to those in stat.h
#define WASMFS_PERM_READ 0444
#define WASMFS_PERM_WRITE 0222
#define WASMFS_PERM_EXECUTE 0111
// In Linux, the maximum length for a filename is 255 bytes.
#define WASMFS_NAME_MAX 255
extern "C" {
using namespace wasmfs;
int __syscall_dup3(int oldfd, int newfd, int flags) {
if (flags & !O_CLOEXEC) {
// TODO: Test this case.
return -EINVAL;
}
auto fileTable = wasmFS.getFileTable().locked();
auto oldOpenFile = fileTable.getEntry(oldfd);
if (!oldOpenFile) {
return -EBADF;
}
if (newfd < 0 || newfd >= WASMFS_FD_MAX) {
return -EBADF;
}
if (oldfd == newfd) {
return -EINVAL;
}
// If the file descriptor newfd was previously open, it will just be
// overwritten silently.
(void)fileTable.setEntry(newfd, oldOpenFile);
return newfd;
}
int __syscall_dup(int fd) {
auto fileTable = wasmFS.getFileTable().locked();
// Check that an open file exists corresponding to the given fd.
auto openFile = fileTable.getEntry(fd);
if (!openFile) {
return -EBADF;
}
return fileTable.addEntry(openFile);
}
// This enum specifies whether file offset will be provided by the open file
// state or provided by argument in the case of pread or pwrite.
enum class OffsetHandling { OpenFileState, Argument };
// Internal write function called by __wasi_fd_write and __wasi_fd_pwrite
// Receives an open file state offset.
// Optionally sets open file state offset.
static __wasi_errno_t writeAtOffset(OffsetHandling setOffset,
__wasi_fd_t fd,
const __wasi_ciovec_t* iovs,
size_t iovs_len,
__wasi_size_t* nwritten,
__wasi_filesize_t offset = 0) {
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return __WASI_ERRNO_BADF;
}
if (iovs_len < 0 || offset < 0) {
return __WASI_ERRNO_INVAL;
}
auto lockedOpenFile = openFile->locked();
auto file = lockedOpenFile.getFile()->dynCast<DataFile>();
if (!file) {
return __WASI_ERRNO_ISDIR;
}
auto lockedFile = file->locked();
if (setOffset == OffsetHandling::OpenFileState) {
if (lockedOpenFile.getFlags() & O_APPEND) {
off_t size = lockedFile.getSize();
if (size < 0) {
// Translate to WASI standard of positive return codes.
return -size;
}
offset = size;
lockedOpenFile.setPosition(offset);
} else {
offset = lockedOpenFile.getPosition();
}
}
// TODO: Check open file access mode for write permissions.
size_t bytesWritten = 0;
for (size_t i = 0; i < iovs_len; i++) {
const uint8_t* buf = iovs[i].buf;
off_t len = iovs[i].buf_len;
// Check if buf_len specifies a positive length buffer but buf is a
// null pointer
if (!buf && len > 0) {
return __WASI_ERRNO_INVAL;
}
// Check if the sum of the buf_len values overflows an off_t (63 bits).
if (addWillOverFlow(offset, (__wasi_filesize_t)bytesWritten)) {
return __WASI_ERRNO_FBIG;
}
auto result = lockedFile.write(buf, len, offset + bytesWritten);
if (result < 0) {
// This individual write failed. Report the error unless we've already
// written some bytes, in which case report a successful short write.
if (bytesWritten > 0) {
break;
}
return -result;
}
// The write was successful.
bytesWritten += result;
if (result < len) {
// The write was short, so stop here.
break;
}
}
*nwritten = bytesWritten;
if (setOffset == OffsetHandling::OpenFileState &&
lockedOpenFile.getFile()->isSeekable()) {
lockedOpenFile.setPosition(offset + bytesWritten);
}
if (bytesWritten) {
lockedFile.updateMTime();
}
return __WASI_ERRNO_SUCCESS;
}
// Internal read function called by __wasi_fd_read and __wasi_fd_pread
// Receives an open file state offset.
// Optionally sets open file state offset.
// TODO: combine this with writeAtOffset because the code is nearly identical.
static __wasi_errno_t readAtOffset(OffsetHandling setOffset,
__wasi_fd_t fd,
const __wasi_iovec_t* iovs,
size_t iovs_len,
__wasi_size_t* nread,
__wasi_filesize_t offset = 0) {
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return __WASI_ERRNO_BADF;
}
auto lockedOpenFile = openFile->locked();
if (setOffset == OffsetHandling::OpenFileState) {
offset = lockedOpenFile.getPosition();
}
if (iovs_len < 0 || offset < 0) {
return __WASI_ERRNO_INVAL;
}
// TODO: Check open file access mode for read permissions.
auto file = lockedOpenFile.getFile()->dynCast<DataFile>();
// If file is nullptr, then the file was not a DataFile.
if (!file) {
return __WASI_ERRNO_ISDIR;
}
auto lockedFile = file->locked();
size_t bytesRead = 0;
for (size_t i = 0; i < iovs_len; i++) {
uint8_t* buf = iovs[i].buf;
size_t len = iovs[i].buf_len;
if (!buf && len > 0) {
return __WASI_ERRNO_INVAL;
}
// TODO: Check for overflow when adding offset + bytesRead.
auto result = lockedFile.read(buf, len, offset + bytesRead);
if (result < 0) {
// This individual read failed. Report the error unless we've already read
// some bytes, in which case report a successful short read.
if (bytesRead > 0) {
break;
}
return -result;
}
// The read was successful.
// Backends must only return len or less.
assert(result <= len);
bytesRead += result;
if (result < len) {
// The read was short, so stop here.
break;
}
}
*nread = bytesRead;
if (setOffset == OffsetHandling::OpenFileState &&
lockedOpenFile.getFile()->isSeekable()) {
lockedOpenFile.setPosition(offset + bytesRead);
}
return __WASI_ERRNO_SUCCESS;
}
__wasi_errno_t __wasi_fd_write(__wasi_fd_t fd,
const __wasi_ciovec_t* iovs,
size_t iovs_len,
__wasi_size_t* nwritten) {
return writeAtOffset(
OffsetHandling::OpenFileState, fd, iovs, iovs_len, nwritten);
}
__wasi_errno_t __wasi_fd_read(__wasi_fd_t fd,
const __wasi_iovec_t* iovs,
size_t iovs_len,
__wasi_size_t* nread) {
return readAtOffset(OffsetHandling::OpenFileState, fd, iovs, iovs_len, nread);
}
__wasi_errno_t __wasi_fd_pwrite(__wasi_fd_t fd,
const __wasi_ciovec_t* iovs,
size_t iovs_len,
__wasi_filesize_t offset,
__wasi_size_t* nwritten) {
return writeAtOffset(
OffsetHandling::Argument, fd, iovs, iovs_len, nwritten, offset);
}
__wasi_errno_t __wasi_fd_pread(__wasi_fd_t fd,
const __wasi_iovec_t* iovs,
size_t iovs_len,
__wasi_filesize_t offset,
__wasi_size_t* nread) {
return readAtOffset(
OffsetHandling::Argument, fd, iovs, iovs_len, nread, offset);
}
__wasi_errno_t __wasi_fd_close(__wasi_fd_t fd) {
std::shared_ptr<DataFile> closee;
{
// Do not hold the file table lock while performing the close.
auto fileTable = wasmFS.getFileTable().locked();
auto entry = fileTable.getEntry(fd);
if (!entry) {
return __WASI_ERRNO_BADF;
}
closee = fileTable.setEntry(fd, nullptr);
}
if (closee) {
// Translate to WASI standard of positive return codes.
int ret = -closee->locked().close();
assert(ret >= 0);
return ret;
}
return __WASI_ERRNO_SUCCESS;
}
__wasi_errno_t __wasi_fd_sync(__wasi_fd_t fd) {
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return __WASI_ERRNO_BADF;
}
// Nothing to flush for anything but a data file, but also not an error either
// way. TODO: in the future we may want syncing of directories.
auto dataFile = openFile->locked().getFile()->dynCast<DataFile>();
if (dataFile) {
auto ret = dataFile->locked().flush();
assert(ret <= 0);
// Translate to WASI standard of positive return codes.
return -ret;
}
return __WASI_ERRNO_SUCCESS;
}
int __syscall_fdatasync(int fd) {
// TODO: Optimize this to avoid unnecessarily flushing unnecessary metadata.
return __wasi_fd_sync(fd);
}
backend_t wasmfs_get_backend_by_fd(int fd) {
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return NullBackend;
}
return openFile->locked().getFile()->getBackend();
}
// This function is exposed to users to allow them to obtain a backend_t for a
// specified path.
backend_t wasmfs_get_backend_by_path(const char* path) {
auto parsed = path::parseFile(path);
if (parsed.getError()) {
// Could not find the file.
return NullBackend;
}
return parsed.getFile()->getBackend();
}
static timespec ms_to_timespec(double ms) {
long long seconds = ms / 1000;
timespec ts;
ts.tv_sec = seconds; // seconds
ts.tv_nsec = (ms - (seconds * 1000)) * 1000 * 1000; // nanoseconds
return ts;
}
int __syscall_newfstatat(int dirfd, intptr_t path, intptr_t buf, int flags) {
// Only accept valid flags.
if (flags & ~(AT_EMPTY_PATH | AT_NO_AUTOMOUNT | AT_SYMLINK_NOFOLLOW)) {
// TODO: Test this case.
return -EINVAL;
}
auto parsed = path::getFileAt(dirfd, (char*)path, flags);
if (auto err = parsed.getError()) {
return err;
}
auto file = parsed.getFile();
// Extract the information from the file.
auto lockedFile = file->locked();
auto buffer = (struct stat*)buf;
off_t size = lockedFile.getSize();
if (size < 0) {
return size;
}
buffer->st_size = size;
// ATTN: hard-coded constant values are copied from the existing JS file
// system. Specific values were chosen to match existing library_fs.js
// values.
// ID of device containing file: Hardcode 1 for now, no meaning at the
// moment for Emscripten.
buffer->st_dev = 1;
buffer->st_mode = lockedFile.getMode();
buffer->st_ino = file->getIno();
// The number of hard links is 1 since they are unsupported.
buffer->st_nlink = 1;
buffer->st_uid = 0;
buffer->st_gid = 0;
// Device ID (if special file) No meaning right now for Emscripten.
buffer->st_rdev = 0;
// The syscall docs state this is hardcoded to # of 512 byte blocks.
buffer->st_blocks = (buffer->st_size + 511) / 512;
// Specifies the preferred blocksize for efficient disk I/O.
buffer->st_blksize = 4096;
buffer->st_atim = ms_to_timespec(lockedFile.getATime());
buffer->st_mtim = ms_to_timespec(lockedFile.getMTime());
buffer->st_ctim = ms_to_timespec(lockedFile.getCTime());
return __WASI_ERRNO_SUCCESS;
}
int __syscall_stat64(intptr_t path, intptr_t buf) {
return __syscall_newfstatat(AT_FDCWD, path, buf, 0);
}
int __syscall_lstat64(intptr_t path, intptr_t buf) {
return __syscall_newfstatat(AT_FDCWD, path, buf, AT_SYMLINK_NOFOLLOW);
}
int __syscall_fstat64(int fd, intptr_t buf) {
return __syscall_newfstatat(fd, (intptr_t) "", buf, AT_EMPTY_PATH);
}
// When calling doOpen(), we may request an FD be returned, or we may not need
// that return value (in which case no FD need be allocated, and we return 0 on
// success).
enum class OpenReturnMode { FD, Nothing };
static __wasi_fd_t doOpen(path::ParsedParent parsed,
int flags,
mode_t mode,
backend_t backend = NullBackend,
OpenReturnMode returnMode = OpenReturnMode::FD) {
int accessMode = (flags & O_ACCMODE);
if (accessMode != O_WRONLY && accessMode != O_RDONLY &&
accessMode != O_RDWR) {
return -EINVAL;
}
// TODO: remove assert when all functionality is complete.
assert((flags & ~(O_CREAT | O_EXCL | O_DIRECTORY | O_TRUNC | O_APPEND |
O_RDWR | O_WRONLY | O_RDONLY | O_LARGEFILE | O_NOFOLLOW |
O_CLOEXEC | O_NONBLOCK)) == 0);
if (auto err = parsed.getError()) {
return err;
}
auto& [parent, childName] = parsed.getParentChild();
if (childName.size() > WASMFS_NAME_MAX) {
return -ENAMETOOLONG;
}
std::shared_ptr<File> child;
{
auto lockedParent = parent->locked();
child = lockedParent.getChild(std::string(childName));
// The requested node was not found.
if (!child) {
// If curr is the last element and the create flag is specified
// If O_DIRECTORY is also specified, still create a regular file:
// https://man7.org/linux/man-pages/man2/open.2.html#BUGS
if (!(flags & O_CREAT)) {
return -ENOENT;
}
// Inserting into an unlinked directory is not allowed.
if (!lockedParent.getParent()) {
return -ENOENT;
}
// Mask out everything except the permissions bits.
mode &= S_IALLUGO;
// If there is no explicitly provided backend, use the parent's backend.
if (!backend) {
backend = parent->getBackend();
}
// TODO: Check write permissions on the parent directory.
std::shared_ptr<File> created;
if (backend == parent->getBackend()) {
created = lockedParent.insertDataFile(std::string(childName), mode);
if (!created) {
// TODO Receive a specific error code, and report it here. For now,
// report a generic error.
return -EIO;
}
} else {
created = backend->createFile(mode);
if (!created) {
// TODO Receive a specific error code, and report it here. For now,
// report a generic error.
return -EIO;
}
[[maybe_unused]] bool mounted =
lockedParent.mountChild(std::string(childName), created);
assert(mounted);
}
// TODO: Check that the insert actually succeeds.
if (returnMode == OpenReturnMode::Nothing) {
return 0;
}
std::shared_ptr<OpenFileState> openFile;
if (auto err = OpenFileState::create(created, flags, openFile)) {
assert(err < 0);
return err;
}
return wasmFS.getFileTable().locked().addEntry(openFile);
}
}
if (auto link = child->dynCast<Symlink>()) {
if (flags & O_NOFOLLOW) {
return -ELOOP;
}
// TODO: The link dereference count starts back at 0 here. We could
// propagate it from the previous path parsing instead.
auto target = link->getTarget();
auto parsedLink = path::getFileFrom(parent, target);
if (auto err = parsedLink.getError()) {
return err;
}
child = parsedLink.getFile();
}
assert(!child->is<Symlink>());
// Return an error if the file exists and O_CREAT and O_EXCL are specified.
if ((flags & O_EXCL) && (flags & O_CREAT)) {
return -EEXIST;
}
if (child->is<Directory>() && (accessMode != O_RDONLY || (flags & O_CREAT))) {
return -EISDIR;
}
// Check user permissions.
auto fileMode = child->locked().getMode();
if ((accessMode == O_RDONLY || accessMode == O_RDWR) &&
!(fileMode & WASMFS_PERM_READ)) {
return -EACCES;
}
if ((accessMode == O_WRONLY || accessMode == O_RDWR) &&
!(fileMode & WASMFS_PERM_WRITE)) {
return -EACCES;
}
// Fail if O_DIRECTORY is specified and pathname is not a directory
if (flags & O_DIRECTORY && !child->is<Directory>()) {
return -ENOTDIR;
}
// Note that we open the file before truncating it because some backends may
// truncate opened files more efficiently (e.g. OPFS).
std::shared_ptr<OpenFileState> openFile;
if (auto err = OpenFileState::create(child, flags, openFile)) {
assert(err < 0);
return err;
}
// If O_TRUNC, truncate the file if possible.
if (flags & O_TRUNC) {
if (!child->is<DataFile>()) {
return -EISDIR;
}
if ((fileMode & WASMFS_PERM_WRITE) == 0) {
return -EACCES;
}
// Try to truncate the file, continuing silently if we cannot.
(void)child->cast<DataFile>()->locked().setSize(0);
}
return wasmFS.getFileTable().locked().addEntry(openFile);
}
// This function is exposed to users and allows users to create a file in a
// specific backend. An fd to an open file is returned.
int wasmfs_create_file(char* pathname, mode_t mode, backend_t backend) {
static_assert(std::is_same_v<decltype(doOpen(0, 0, 0, 0)), unsigned int>,
"unexpected conversion from result of doOpen to int");
return doOpen(
path::parseParent((char*)pathname), O_CREAT | O_EXCL, mode, backend);
}
// TODO: Test this with non-AT_FDCWD values.
int __syscall_openat(int dirfd, intptr_t path, int flags, ...) {
mode_t mode = 0;
va_list v1;
va_start(v1, flags);
mode = va_arg(v1, int);
va_end(v1);
return doOpen(path::parseParent((char*)path, dirfd), flags, mode);
}
int __syscall_mknodat(int dirfd, intptr_t path, int mode, int dev) {
assert(dev == 0); // TODO: support special devices
if (mode & S_IFDIR) {
return -EINVAL;
}
if (mode & S_IFIFO) {
return -EPERM;
}
return doOpen(path::parseParent((char*)path, dirfd),
O_CREAT | O_EXCL,
mode,
NullBackend,
OpenReturnMode::Nothing);
}
static int doMkdir(path::ParsedParent parsed, int mode) {
if (auto err = parsed.getError()) {
return err;
}
auto& [parent, childNameView] = parsed.getParentChild();
std::string childName(childNameView);
auto lockedParent = parent->locked();
if (childName.size() > WASMFS_NAME_MAX) {
return -ENAMETOOLONG;
}
// Check if the requested directory already exists.
if (lockedParent.getChild(childName)) {
return -EEXIST;
}
// Mask rwx permissions for user, group and others, and the sticky bit.
// This prevents users from entering S_IFREG for example.
// https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
mode &= S_IRWXUGO | S_ISVTX;
if (!(lockedParent.getMode() & WASMFS_PERM_WRITE)) {
return -EACCES;
}
if (!lockedParent.insertDirectory(childName, mode)) {
// TODO Receive a specific error code, and report it here. For now, report
// a generic error.
return -EIO;
}
// TODO: Check that the insertion is successful.
return 0;
}
int wasmfs_mount(const char* path, backend_t backend) {
path::ParsedParent parsed = path::parseParent(path);
if (auto err = parsed.getError()) {
return err;
}
auto& [parent, childNameView] = parsed.getParentChild();
auto lockedParent = parent->locked();
std::string childName(childNameView);
// Child must exist and must be directory
auto child = lockedParent.getChild(childName);
if (!child) {
return -EEXIST;
}
if (!child->dynCast<Directory>()) {
return -ENOTDIR;
}
auto created = backend->createDirectory(0777);
if (!created) {
// TODO Receive a specific error code, and report it here. For now, report
// a generic error.
return -EIO;
}
[[maybe_unused]] bool mounted = lockedParent.mountChild(childName, created);
assert(mounted);
return 0;
}
// Legacy function, use wasmfs_mount instead.
int wasmfs_create_directory(const char* path, int mode, backend_t backend) {
static_assert(std::is_same_v<decltype(doMkdir(0, 0)), int>,
"unexpected conversion from result of doMkdir to int");
int rtn = doMkdir(path::parseParent(path), mode);
if (rtn != 0) {
return rtn;
}
return wasmfs_mount(path, backend);
}
// TODO: Test this.
int __syscall_mkdirat(int dirfd, intptr_t path, int mode) {
return doMkdir(path::parseParent((char*)path, dirfd), mode);
}
__wasi_errno_t __wasi_fd_seek(__wasi_fd_t fd,
__wasi_filedelta_t offset,
__wasi_whence_t whence,
__wasi_filesize_t* newoffset) {
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return __WASI_ERRNO_BADF;
}
auto lockedOpenFile = openFile->locked();
if (!lockedOpenFile.getFile()->isSeekable()) {
return __WASI_ERRNO_SPIPE;
}
off_t position;
if (whence == SEEK_SET) {
position = offset;
} else if (whence == SEEK_CUR) {
position = lockedOpenFile.getPosition() + offset;
} else if (whence == SEEK_END) {
// Only the open file state is altered in seek. Locking the underlying
// data file here once is sufficient.
off_t size = lockedOpenFile.getFile()->locked().getSize();
if (size < 0) {
// Translate to WASI standard of positive return codes.
return -size;
}
position = size + offset;
} else {
return __WASI_ERRNO_INVAL;
}
if (position < 0) {
return __WASI_ERRNO_INVAL;
}
lockedOpenFile.setPosition(position);
if (newoffset) {
*newoffset = position;
}
return __WASI_ERRNO_SUCCESS;
}
static int doChdir(std::shared_ptr<File>& file) {
auto dir = file->dynCast<Directory>();
if (!dir) {
return -ENOTDIR;
}
wasmFS.setCWD(dir);
return 0;
}
int __syscall_chdir(intptr_t path) {
auto parsed = path::parseFile((char*)path);
if (auto err = parsed.getError()) {
return err;
}
return doChdir(parsed.getFile());
}
int __syscall_fchdir(int fd) {
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return -EBADF;
}
return doChdir(openFile->locked().getFile());
}
int __syscall_getcwd(intptr_t buf, size_t size) {
// Check if buf points to a bad address.
if (!buf && size > 0) {
return -EFAULT;
}
// Check if the size argument is zero and buf is not a null pointer.
if (buf && size == 0) {
return -EINVAL;
}
auto curr = wasmFS.getCWD();
std::string result = "";
while (curr != wasmFS.getRootDirectory()) {
auto parent = curr->locked().getParent();
// Check if the parent exists. The parent may not exist if the CWD or one
// of its ancestors has been unlinked.
if (!parent) {
return -ENOENT;
}
auto name = parent->locked().getName(curr);
result = '/' + name + result;
curr = parent;
}
// Check if the cwd is the root directory.
if (result.empty()) {
result = "/";
}
int len = result.length() + 1;
// Check if the size argument is less than the length of the absolute
// pathname of the working directory, including null terminator.
if (len > size) {
return -ERANGE;
}
// Return value is a null-terminated c string.
strcpy((char*)buf, result.c_str());
return len;
}
__wasi_errno_t __wasi_fd_fdstat_get(__wasi_fd_t fd, __wasi_fdstat_t* stat) {
// TODO: This is only partial implementation of __wasi_fd_fdstat_get. Enough
// to get __wasi_fd_is_valid working.
// There are other fields in the stat structure that we should really
// be filling in here.
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return __WASI_ERRNO_BADF;
}
if (openFile->locked().getFile()->is<Directory>()) {
stat->fs_filetype = __WASI_FILETYPE_DIRECTORY;
} else {
stat->fs_filetype = __WASI_FILETYPE_REGULAR_FILE;
}
return __WASI_ERRNO_SUCCESS;
}
// TODO: Test this with non-AT_FDCWD values.
int __syscall_unlinkat(int dirfd, intptr_t path, int flags) {
if (flags & ~AT_REMOVEDIR) {
// TODO: Test this case.
return -EINVAL;
}
// It is invalid for rmdir paths to end in ".", but we need to distinguish
// this case from the case of `parseParent` returning (root, '.') when parsing
// "/", so we need to find the invalid "/." manually.
if (flags == AT_REMOVEDIR) {
std::string_view p((char*)path);
// Ignore trailing '/'.
while (!p.empty() && p.back() == '/') {
p.remove_suffix(1);
}
if (p.size() >= 2 && p.substr(p.size() - 2) == std::string_view("/.")) {
return -EINVAL;
}
}
auto parsed = path::parseParent((char*)path, dirfd);
if (auto err = parsed.getError()) {
return err;
}
auto& [parent, childNameView] = parsed.getParentChild();
std::string childName(childNameView);
auto lockedParent = parent->locked();
auto file = lockedParent.getChild(childName);
if (!file) {
return -ENOENT;
}
// Disallow removing the root directory, even if it is empty.
if (file == wasmFS.getRootDirectory()) {
return -EBUSY;
}
auto lockedFile = file->locked();
if (auto dir = file->dynCast<Directory>()) {
if (flags != AT_REMOVEDIR) {
return -EISDIR;
}
// A directory can only be removed if it has no entries.
if (dir->locked().getNumEntries() > 0) {
return -ENOTEMPTY;
}
} else {
// A normal file or symlink.
if (flags == AT_REMOVEDIR) {
return -ENOTDIR;
}
}
// Cannot unlink/rmdir if the parent dir doesn't have write permissions.
if (!(lockedParent.getMode() & WASMFS_PERM_WRITE)) {
return -EACCES;
}
// Input is valid, perform the unlink.
return lockedParent.removeChild(childName);
}
int __syscall_rmdir(intptr_t path) {
return __syscall_unlinkat(AT_FDCWD, path, AT_REMOVEDIR);
}
// wasmfs_unmount is similar to __syscall_unlinkat, but assumes AT_REMOVEDIR is
// true and will only unlink mountpoints (Empty and nonempty).
int wasmfs_unmount(const char* path) {
auto parsed = path::parseParent(path, AT_FDCWD);
if (auto err = parsed.getError()) {
return err;
}
auto& [parent, childNameView] = parsed.getParentChild();
std::string childName(childNameView);
auto lockedParent = parent->locked();
auto file = lockedParent.getChild(childName);
if (!file) {
return -ENOENT;
}
// Disallow removing the root directory, even if it is empty.
if (file == wasmFS.getRootDirectory()) {
return -EBUSY;
}
if (!file->dynCast<Directory>()) {
// A normal file or symlink.
return -ENOTDIR;
}
if (parent->getBackend() == file->getBackend()) {
// The child is not a valid mountpoint.
return -EINVAL;
}
// Input is valid, perform the unlink.
return lockedParent.removeChild(childName);
}
int __syscall_getdents64(int fd, intptr_t dirp, size_t count) {
dirent* result = (dirent*)dirp;
// Check if the result buffer is too small.
if (count / sizeof(dirent) == 0) {
return -EINVAL;
}
auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
if (!openFile) {
return -EBADF;
}
auto lockedOpenFile = openFile->locked();
auto dir = lockedOpenFile.getFile()->dynCast<Directory>();
if (!dir) {
return -ENOTDIR;
}
auto lockedDir = dir->locked();
// A directory's position corresponds to the index in its entries vector.
int index = lockedOpenFile.getPosition();
// If this directory has been unlinked and has no parent, then it is
// completely empty.
auto parent = lockedDir.getParent();
if (!parent) {
return 0;
}
off_t bytesRead = 0;
const auto& dirents = openFile->dirents;
for (; index < dirents.size() && bytesRead + sizeof(dirent) <= count;
index++) {
const auto& entry = dirents[index];
result->d_ino = entry.ino;
result->d_off = index + 1;
result->d_reclen = sizeof(dirent);
switch (entry.kind) {
case File::UnknownKind:
result->d_type = DT_UNKNOWN;
break;
case File::DataFileKind:
result->d_type = DT_REG;
break;
case File::DirectoryKind:
result->d_type = DT_DIR;
break;
case File::SymlinkKind:
result->d_type = DT_LNK;
break;
default:
result->d_type = DT_UNKNOWN;
break;
}
assert(entry.name.size() + 1 <= sizeof(result->d_name));
strcpy(result->d_name, entry.name.c_str());
++result;
bytesRead += sizeof(dirent);
}
// Update position
lockedOpenFile.setPosition(index);
return bytesRead;
}
// TODO: Test this with non-AT_FDCWD values.
int __syscall_renameat(int olddirfd,
intptr_t oldpath,
int newdirfd,
intptr_t newpath) {
// Rename is the only syscall that needs to (or is allowed to) acquire locks
// on two directories at once. It requires locks on both the old and new
// parent directories to ensure that the moved file can be atomically removed
// from the old directory and added to the new directory without something
// changing that would prevent the move.
//
// To prevent deadlock in the case of simultaneous renames, serialize renames
// with an additional global lock.
static std::mutex renameMutex;
std::lock_guard<std::mutex> renameLock(renameMutex);
// Get the old directory.
auto parsedOld = path::parseParent((char*)oldpath, olddirfd);