-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
file.gr
2118 lines (1861 loc) 路 53.6 KB
/
file.gr
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
/**
* Utilities for accessing the filesystem & working with files.
*
* Many of the functions in this module are not intended to be used directly, but rather for other libraries to be built on top of them.
*
* @example from "wasi/file" include File
*/
module File
from "runtime/unsafe/wasmi32" include WasmI32
use WasmI32.{
(+),
(-),
(*),
(<<),
(>>),
(>>>),
(==),
(!=),
(<),
(<=),
(>),
(>=),
(&),
(|),
}
from "runtime/unsafe/wasmi64" include WasmI64
from "runtime/wasi" include Wasi
from "runtime/unsafe/memory" include Memory
from "runtime/dataStructures" include DataStructures
use DataStructures.{
tagSimpleNumber,
untagSimpleNumber,
allocateArray,
allocateBytes,
allocateString,
newInt32,
newInt64,
allocateInt64,
}
from "list" include List
/**
* Represents a handle to an open file on the system.
*/
provide enum FileDescriptor {
FileDescriptor(Number),
}
/**
* Flags that determine how paths should be resolved when looking up a file or directory.
*/
provide enum LookupFlag {
/**
* Follow symlinks
*/
SymlinkFollow,
}
// TODO(#775): This has specific ordering requirements because of ambiguous type inference
@unsafe
let rec combineLookupFlagsHelp = (acc, dirflags) => {
match (dirflags) {
[hd, ...tl] => {
let flag = match (hd) {
SymlinkFollow => Wasi._LOOKUP_FLAG_SYMLINK_FOLLOW,
}
combineLookupFlagsHelp(acc | flag, tl)
},
[] => acc,
}
}
@unsafe
let combineLookupFlags = dirflags => {
combineLookupFlagsHelp(0n, dirflags)
}
/**
* Flags that determine how a file or directory should be opened.
*/
provide enum OpenFlag {
/**
* Create file if it does not exist.
*/
Create,
/**
* Fail if not a directory.
*/
Directory,
/**
* Fail if file already exists.
*/
Exclusive,
/**
* Truncate file to size 0.
*/
Truncate,
}
// TODO(#775): This has specific ordering requirements because of ambiguous type inference
@unsafe
let rec combineOpenFlagsHelp = (acc, dirflags) => {
match (dirflags) {
[hd, ...tl] => {
let flag = match (hd) {
Create => Wasi._OPEN_FLAG_CREAT,
Directory => Wasi._OPEN_FLAG_DIRECTORY,
Exclusive => Wasi._OPEN_FLAG_EXCL,
Truncate => Wasi._OPEN_FLAG_TRUNC,
}
combineOpenFlagsHelp(acc | flag, tl)
},
[] => acc,
}
}
@unsafe
let combineOpenFlags = dirflags => {
combineOpenFlagsHelp(0n, dirflags)
}
/**
* Flags that determine which rights a `FileDescriptor` should have
* and which rights new `FileDescriptor`s should inherit from it.
*/
provide enum Rights {
/**
* The right to invoke `fdDatasync`.
* If `PathOpen` is set, includes the right to invoke
* `pathOpen` with `FdFlag::Dsync`.
*/
FdDatasync,
/**
* The right to invoke `fdRead`.
* If `Rights::FdSeek` is set, includes the right to invoke `fdPread`.
*/
FdRead,
/**
* The right to invoke `fdSeek`. This flag implies `Rights::FdTell`.
*/
FdSeek,
/**
* The right to invoke `fdSetFlags`.
*/
FdSetFlags,
/**
* The right to invoke `fdSync`.
* If `PathOpen` is set, includes the right to invoke
* `pathOpen` with `FdFlag::Rsync` and `FdFlag::Dsync`.
*/
FdSync,
/**
* The right to invoke `fdSeek` in such a way that the file offset
* remains unaltered (i.e., `Whence::Current` with offset zero), or to
* invoke `fdTell`.
*/
FdTell,
/**
* The right to invoke `fdWrite`.
* If `Rights::FdSeek` is set, includes the right to invoke `fdPwrite`.
*/
FdWrite,
/**
* The right to invoke `fdAdvise`.
*/
FdAdvise,
/**
* The right to invoke `fdAllocate`.
*/
FdAllocate,
/**
* The right to invoke `pathCreateDirectory`.
*/
PathCreateDirectory,
/**
* If `PathOpen` is set, the right to invoke `pathOpen` with `OpenFlag::Create`.
*/
PathCreateFile,
/**
* The right to invoke `pathLink` with the file descriptor as the
* source directory.
*/
PathLinkSource,
/**
* The right to invoke `pathLink` with the file descriptor as the
* target directory.
*/
PathLinkTarget,
/**
* The right to invoke `pathOpen`.
*/
PathOpen,
/**
* The right to invoke `fdReaddir`.
*/
FdReaddir,
/**
* The right to invoke `pathReadlink`.
*/
PathReadlink,
/**
* The right to invoke `pathRename` with the file descriptor as the source directory.
*/
PathRenameSource,
/**
* The right to invoke `pathRename` with the file descriptor as the target directory.
*/
PathRenameTarget,
/**
* The right to invoke `pathFilestats`.
*/
PathFilestats,
/**
* The right to change a file's size (there's no `pathSetSize`).
* If `PathOpen` is set, includes the right to invoke `pathOpen` with `OpenFlag::Truncate`.
*/
PathSetSize,
/**
* The right to invoke `pathSetAccessTime`, `pathSetAccessTimeNow`, `pathSetModifiedTime`, or `pathSetModifiedTimeNow`.
*/
PathSetTimes,
/**
* The right to invoke `fdFilestats`.
*/
FdFilestats,
/**
* The right to invoke `fdSetSize`.
*/
FdSetSize,
/**
* The right to invoke `fdSetAccessTime`, `fdSetAccessTimeNow`, `fdSetModifiedTime`, or `fdSetModifiedTimeNow`.
*/
FdSetTimes,
/**
* The right to invoke `pathSymlink`.
*/
PathSymlink,
/**
* The right to invoke `pathRemoveDirectory`.
*/
PathRemoveDirectory,
/**
* The right to invoke `pathUnlinkFile`.
*/
PathUnlinkFile,
/**
* If `Rights::FdRead` is set, includes the right to invoke `pollOneoff` (not yet implemented) to subscribe to `EventType::FdRead`.
* If `Rights::FdWrite` is set, includes the right to invoke `pollOneoff` (not yet implemented) to subscribe to `EventType::FdWrite`.
*/
PollFdReadwrite,
/**
* The right to invoke `sockShutdown` (not yet implemented).
*/
SockShutdown,
}
// Grain currently cannot close over unsafe wasm i64s, so these are here in
// module so they get inlined
@unsafe
let _RIGHT_FD_DATASYNC = 1N
@unsafe
let _RIGHT_FD_READ = 2N
@unsafe
let _RIGHT_FD_SEEK = 4N
@unsafe
let _RIGHT_FD_FDSTAT_SET_FLAGS = 8N
@unsafe
let _RIGHT_FD_SYNC = 16N
@unsafe
let _RIGHT_FD_TELL = 32N
@unsafe
let _RIGHT_FD_WRITE = 64N
@unsafe
let _RIGHT_FD_ADVISE = 128N
@unsafe
let _RIGHT_FD_ALLOCATE = 256N
@unsafe
let _RIGHT_PATH_CREATE_DIRECTORY = 512N
@unsafe
let _RIGHT_PATH_CREATE_FILE = 1024N
@unsafe
let _RIGHT_PATH_LINK_SOURCE = 2048N
@unsafe
let _RIGHT_PATH_LINK_TARGET = 4096N
@unsafe
let _RIGHT_PATH_OPEN = 8192N
@unsafe
let _RIGHT_FD_READDIR = 16384N
@unsafe
let _RIGHT_PATH_READLINK = 32768N
@unsafe
let _RIGHT_PATH_RENAME_SOURCE = 65536N
@unsafe
let _RIGHT_PATH_RENAME_TARGET = 131072N
@unsafe
let _RIGHT_PATH_FILESTAT_GET = 262144N
@unsafe
let _RIGHT_PATH_FILESTAT_SET_SIZE = 524288N
@unsafe
let _RIGHT_PATH_FILESTAT_SET_TIMES = 1048576N
@unsafe
let _RIGHT_FD_FILESTAT_GET = 2097152N
@unsafe
let _RIGHT_FD_FILESTAT_SET_SIZE = 4194304N
@unsafe
let _RIGHT_FD_FILESTAT_SET_TIMES = 8388608N
@unsafe
let _RIGHT_PATH_SYMLINK = 16777216N
@unsafe
let _RIGHT_PATH_REMOVE_DIRECTORY = 33554432N
@unsafe
let _RIGHT_PATH_UNLINK_FILE = 67108864N
@unsafe
let _RIGHT_POLL_FD_READWRITE = 134217728N
@unsafe
let _RIGHT_SOCK_SHUTDOWN = 268435456N
// TODO(#775): This has specific ordering requirements because of ambiguous type inference
@unsafe
let rec combineRightsHelp = (acc, dirflags) => {
use WasmI64.{ (|) }
match (dirflags) {
[] => acc,
[hd, ...tl] => {
let flag = match (hd) {
FdDatasync => _RIGHT_FD_DATASYNC,
FdRead => _RIGHT_FD_READ,
FdSeek => _RIGHT_FD_SEEK,
FdSetFlags => _RIGHT_FD_FDSTAT_SET_FLAGS,
FdSync => _RIGHT_FD_SYNC,
FdTell => _RIGHT_FD_TELL,
FdWrite => _RIGHT_FD_WRITE,
FdAdvise => _RIGHT_FD_ADVISE,
FdAllocate => _RIGHT_FD_ALLOCATE,
PathCreateDirectory => _RIGHT_PATH_CREATE_DIRECTORY,
PathCreateFile => _RIGHT_PATH_CREATE_FILE,
PathLinkSource => _RIGHT_PATH_LINK_SOURCE,
PathLinkTarget => _RIGHT_PATH_LINK_TARGET,
PathOpen => _RIGHT_PATH_OPEN,
FdReaddir => _RIGHT_FD_READDIR,
PathReadlink => _RIGHT_PATH_READLINK,
PathRenameSource => _RIGHT_PATH_RENAME_SOURCE,
PathRenameTarget => _RIGHT_PATH_RENAME_TARGET,
PathFilestats => _RIGHT_PATH_FILESTAT_GET,
PathSetSize => _RIGHT_PATH_FILESTAT_SET_SIZE,
PathSetTimes => _RIGHT_PATH_FILESTAT_SET_TIMES,
FdFilestats => _RIGHT_FD_FILESTAT_GET,
FdSetSize => _RIGHT_FD_FILESTAT_SET_SIZE,
FdSetTimes => _RIGHT_FD_FILESTAT_SET_TIMES,
PathSymlink => _RIGHT_PATH_SYMLINK,
PathRemoveDirectory => _RIGHT_PATH_REMOVE_DIRECTORY,
PathUnlinkFile => _RIGHT_PATH_UNLINK_FILE,
PollFdReadwrite => _RIGHT_POLL_FD_READWRITE,
SockShutdown => _RIGHT_SOCK_SHUTDOWN,
_ => {
ignore(fail "Unknown file right")
// `fail` won't allow us to get here, but this is necessary
// to make the wasm types work out
0N
},
}
combineRightsHelp(flag | acc, tl)
},
}
}
@unsafe
let combineRights = dirflags => {
combineRightsHelp(0N, dirflags)
}
/**
* Flags that determine the mode(s) that a `FileDescriptor` operates in.
*/
provide enum FdFlag {
/**
* Append mode: Data written to the file is always appended to the file's end.
*/
Append,
/**
* Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized.
*/
Dsync,
/**
* Non-blocking mode.
*/
Nonblock,
/**
* Synchronized read I/O operations.
*/
Rsync,
// Write according to synchronized I/O file integrity completion. In
// addition to synchronizing the data stored in the file, the implementation
// may also synchronously update the file's metadata.
Sync,
}
// TODO(#775): This has specific ordering requirements because of ambiguous type inference
@unsafe
let rec combineFdFlagsHelp = (acc, dirflags) => {
match (dirflags) {
[hd, ...tl] => {
let flag = match (hd) {
Append => Wasi._FDFLAG_APPEND,
Dsync => Wasi._FDFLAG_DSYNC,
Nonblock => Wasi._FDFLAG_NONBLOCK,
Rsync => Wasi._FDFLAG_RSYNC,
Sync => Wasi._FDFLAG_SYNC,
}
combineFdFlagsHelp(acc | flag, tl)
},
[] => acc,
}
}
@unsafe
let combineFdFlags = dirflags => {
combineFdFlagsHelp(0n, dirflags)
}
/**
* The type of file a `FileDescriptor` refers to.
*/
provide enum Filetype {
/**
* The type of the file descriptor or file is unknown or is different from any of the other types specified.
*/
Unknown,
/**
* The file descriptor or file refers to a block device inode.
*/
BlockDevice,
/**
* The file descriptor or file refers to a character device inode.
*/
CharacterDevice,
/**
* The file descriptor or file refers to a directory inode.
*/
Directory,
/**
* The file descriptor or file refers to a regular file inode.
*/
RegularFile,
/**
* The file descriptor or file refers to a datagram socket.
*/
SocketDatagram,
/**
* The file descriptor or file refers to a byte-stream socket.
*/
SocketStream,
/**
* The file refers to a symbolic link inode.
*/
SymbolicLink,
}
// TODO(#775): This has specific ordering requirements because of ambiguous type inference
@unsafe
let filetypeFromNumber = filetype => {
match (filetype) {
0n => Unknown,
1n => BlockDevice,
2n => CharacterDevice,
3n => Directory,
4n => RegularFile,
5n => SocketDatagram,
6n => SocketStream,
7n => SymbolicLink,
_ => fail "Unknown filetype",
}
}
/**
* Flags that determine where seeking should begin in a file.
*/
provide enum Whence {
/**
* Seek relative to start-of-file.
*/
Set,
/**
* Seek relative to current position.
*/
Current,
/**
* Seek relative to end-of-file.
*/
End,
}
/**
* Information about a `FileDescriptor`.
*/
provide record Stats {
filetype: Filetype,
flags: List<FdFlag>,
rights: List<Rights>,
rightsInheriting: List<Rights>,
}
/**
* Information about the file that a `FileDescriptor` refers to.
*/
provide record Filestats {
device: Int64,
inode: Int64,
filetype: Filetype,
linkcount: Int64,
size: Int64,
accessed: Int64,
modified: Int64,
changed: Int64,
}
/**
* An entry in a directory.
*/
provide record DirectoryEntry {
inode: Int64,
filetype: Filetype,
path: String,
}
/**
* Information about a preopened directory
*/
provide enum Prestat {
Dir{ prefix: String, fd: FileDescriptor },
}
/**
* The `FileDescriptor` for `stdin`.
*/
provide let stdin = FileDescriptor(0)
/**
* The `FileDescriptor` for `stdout`.
*/
provide let stdout = FileDescriptor(1)
/**
* The `FileDescriptor` for `stderr`.
*/
provide let stderr = FileDescriptor(2)
/**
* Open a file or directory.
*
* @param dirFd: The directory in which path resolution starts
* @param dirFlags: Flags which affect path resolution
* @param path: The path to the file or directory
* @param openFlags: Flags that decide how the path will be opened
* @param rights: The rights that dictate what may be done with the returned file descriptor
* @param rightsInheriting: The rights that dictate what may be done with file descriptors derived from this file descriptor
* @param flags: Flags which affect read/write operations on this file descriptor
* @returns `Ok(fd)` of the opened file or directory if successful or `Err(exception)` otherwise
*/
@unsafe
provide let pathOpen = (
dirFd: FileDescriptor,
dirFlags: List<LookupFlag>,
path: String,
openFlags: List<OpenFlag>,
rights: List<Rights>,
rightsInheriting: List<Rights>,
flags: List<FdFlag>,
) => {
let dirFdArg = dirFd
let pathArg = path
let rightsInheritingArg = rightsInheriting
let dirFd = match (dirFd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let combinedDirFlags = combineLookupFlags(dirFlags)
let mut path = WasmI32.fromGrain(path)
let pathLength = WasmI32.load(path, 4n)
path += 8n // Offset the string pointer to the start of the string
let combinedOFlags = combineOpenFlags(openFlags)
let rightsBase = combineRights(rights)
let rightsInheriting = combineRights(rightsInheriting)
let combinedFsFlags = combineFdFlags(flags)
let newFd = Memory.malloc(4n)
let err = Wasi.path_open(
dirFd,
combinedDirFlags,
path,
pathLength,
combinedOFlags,
rightsBase,
rightsInheriting,
combinedFsFlags,
newFd
)
if (err != Wasi._ESUCCESS) {
Memory.free(newFd)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
let fd = FileDescriptor(tagSimpleNumber(WasmI32.load(newFd, 0n)))
Memory.free(newFd)
return Ok(fd)
}
/**
* Read from a file descriptor.
*
* @param fd: The file descriptor to read from
* @param size: The maximum number of bytes to read from the file descriptor
* @returns `Ok((contents, numBytes))` of bytes read and the number of bytes read if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdRead = (fd: FileDescriptor, size: Number) => {
let fdArg = fd
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let n = WasmI32.fromGrain(size) >> 1n
let iovs = Memory.malloc(3n * 4n)
let strPtr = allocateBytes(n)
WasmI32.store(iovs, strPtr + 2n * 4n, 0n)
WasmI32.store(iovs, n, 4n)
let mut nread = iovs + 3n * 4n
let err = Wasi.fd_read(fd, iovs, 1n, nread)
if (err != Wasi._ESUCCESS) {
Memory.free(iovs)
Memory.free(strPtr)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
nread = WasmI32.load(nread, 0n)
WasmI32.store(strPtr, nread, 4n)
Memory.free(iovs)
return Ok((WasmI32.toGrain(strPtr): Bytes, tagSimpleNumber(nread)))
}
/**
* Read from a file descriptor without updating the file descriptor's offset.
*
* @param fd: The file descriptor to read from
* @param offset: The position within the file to begin reading
* @param size: The maximum number of bytes to read from the file descriptor
* @returns `Ok((contents, numBytes))` of bytes read and the number of bytes read if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdPread = (fd: FileDescriptor, offset: Int64, size: Number) => {
let fdArg = fd
let offsetArg = offset
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let offset = WasmI64.load(WasmI32.fromGrain(offset), 8n)
let n = WasmI32.fromGrain(size) >> 1n
let iovs = Memory.malloc(3n * 4n)
let strPtr = allocateBytes(n)
WasmI32.store(iovs, strPtr + 2n * 4n, 0n)
WasmI32.store(iovs, n, 4n)
let mut nread = iovs + 3n * 4n
let err = Wasi.fd_pread(fd, iovs, 1n, offset, nread)
if (err != Wasi._ESUCCESS) {
Memory.free(iovs)
Memory.free(strPtr)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
nread = WasmI32.load(nread, 0n)
WasmI32.store(strPtr, nread, 4n)
Memory.free(iovs)
return Ok((WasmI32.toGrain(strPtr): Bytes, tagSimpleNumber(nread)))
}
/**
* Get information about a preopened directory.
*
* @param fd: The file descriptor to check
* @returns `Ok(Dir{prefix, fd})` if successful or `Err(exception)` otherwise
*
* @since v0.6.0
*/
@unsafe
provide let fdPrestatGet = (fd: FileDescriptor) => {
let fdArg = fd
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let dir = Memory.malloc(8n)
let err = Wasi.fd_prestat_get(fd, dir)
if (err != Wasi._ESUCCESS) {
Memory.free(dir)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
let prefixLen = WasmI32.load(dir, 4n)
Memory.free(dir)
let prefix = allocateString(prefixLen)
let err = Wasi.fd_prestat_dir_name(fd, prefix + 8n, prefixLen)
if (err != Wasi._ESUCCESS) {
Memory.free(prefix)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
if (
prefixLen > 0n &&
WasmI32.eqz(WasmI32.load8U(prefix + prefixLen - 1n, 8n))
) {
// in uvwasi environments the string is null-terminated and the size is reported including it
// https://github.com/grain-lang/grain/issues/1818
WasmI32.store(prefix, prefixLen - 1n, 4n)
}
let prefix = WasmI32.toGrain(prefix): String
let fd = fdArg
return Ok(Dir{ prefix, fd })
}
/**
* Write to a file descriptor.
*
* @param fd: The file descriptor to which data will be written
* @param data: The data to be written
* @returns `Ok(numBytes)` of the number of bytes written if successful or `Err(Exception)` otherwise
*/
@unsafe
provide let fdWrite = (fd: FileDescriptor, data: Bytes) => {
let fdArg = fd
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let iovs = Memory.malloc(3n * 4n)
let strPtr = WasmI32.fromGrain(data)
WasmI32.store(iovs, strPtr + 8n, 0n)
WasmI32.store(iovs, WasmI32.load(strPtr, 4n), 4n)
let mut nwritten = iovs + 3n * 4n
let err = Wasi.fd_write(fd, iovs, 1n, nwritten)
if (err != Wasi._ESUCCESS) {
Memory.free(iovs)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
nwritten = WasmI32.load(nwritten, 0n)
Memory.free(iovs)
return Ok(tagSimpleNumber(nwritten))
}
/**
* Write to a file descriptor without updating the file descriptor's offset.
*
* @param fd: The file descriptor to which data will be written
* @param data: The data to be written
* @param offset: The position within the file to begin writing
* @returns `Ok(numBytes)` of the number of bytes written if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdPwrite = (fd: FileDescriptor, data: Bytes, offset: Int64) => {
let fdArg = fd
let offsetArg = offset
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let iovs = Memory.malloc(3n * 4n)
let strPtr = WasmI32.fromGrain(data)
WasmI32.store(iovs, strPtr + 2n * 4n, 0n)
WasmI32.store(iovs, WasmI32.load(strPtr, 4n), 4n)
let offset = WasmI64.load(WasmI32.fromGrain(offset), 8n)
let mut nwritten = iovs + 3n * 4n
let err = Wasi.fd_pwrite(fd, iovs, 1n, offset, nwritten)
if (err != Wasi._ESUCCESS) {
Memory.free(iovs)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
nwritten = WasmI32.load(nwritten, 0n)
Memory.free(iovs)
return Ok(tagSimpleNumber(nwritten))
}
/**
* Allocate space within a file.
*
* @param fd: The file descriptor in which space will be allocated
* @param offset: The position within the file to begin writing
* @param size: The number of bytes to allocate
* @returns `Ok(void)` if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdAllocate = (fd: FileDescriptor, offset: Int64, size: Int64) => {
let fdArg = fd
let offsetArg = offset
let sizeArg = size
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let offset = WasmI64.load(WasmI32.fromGrain(offset), 8n)
let size = WasmI64.load(WasmI32.fromGrain(size), 8n)
let err = Wasi.fd_allocate(fd, offset, size)
if (err != Wasi._ESUCCESS) {
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
return Ok(void)
}
/**
* Close a file descriptor.
*
* @param fd: The file descriptor to close
* @returns `Ok(void)` if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdClose = (fd: FileDescriptor) => {
let fdArg = fd
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let err = Wasi.fd_close(fd)
if (err != Wasi._ESUCCESS) {
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
return Ok(void)
}
/**
* Synchronize the data of a file to disk.
*
* @param fd: The file descriptor to synchronize
* @returns `Ok(void)` if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdDatasync = (fd: FileDescriptor) => {
let fdArg = fd
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let err = Wasi.fd_datasync(fd)
if (err != Wasi._ESUCCESS) {
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
return Ok(void)
}
/**
* Synchronize the data and metadata of a file to disk.
*
* @param fd: The file descriptor to synchronize
* @returns `Ok(void)` if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdSync = (fd: FileDescriptor) => {
let fdArg = fd
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let err = Wasi.fd_sync(fd)
if (err != Wasi._ESUCCESS) {
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
return Ok(void)
}
let orderedFdflags = [Append, Dsync, Nonblock, Rsync, Sync]
let orderedRights = [
FdDatasync,
FdRead,
FdSeek,
FdSetFlags,
FdSync,
FdTell,
FdWrite,
FdAdvise,
FdAllocate,
PathCreateDirectory,
PathCreateFile,
PathLinkSource,
PathLinkTarget,
PathOpen,
FdReaddir,
PathReadlink,
PathRenameSource,
PathRenameTarget,
PathFilestats,
PathSetSize,
PathSetTimes,
FdFilestats,
FdSetSize,
FdSetTimes,
PathSymlink,
PathRemoveDirectory,
PathUnlinkFile,
PollFdReadwrite,
SockShutdown,
]
/**
* Retrieve information about a file descriptor.
*
* @param fd: The file descriptor of which to retrieve information
* @returns `Ok(stats)` of the `Stats` associated with the file descriptor if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdStats = (fd: FileDescriptor) => {
let fdArg = fd
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}
let structPtr = Memory.malloc(24n)
let err = Wasi.fd_fdstat_get(fd, structPtr)
if (err != Wasi._ESUCCESS) {
Memory.free(structPtr)
return Err(Wasi.SystemError(tagSimpleNumber(err)))
}
let filetype = WasmI32.load8U(structPtr, 0n)
let filetype = filetypeFromNumber(filetype)
let flagsToWasmVal = (flag, i) => {
let fdflags = WasmI32.load16U(structPtr, 4n)
WasmI32.gtU(fdflags & 1n << (WasmI32.fromGrain(i) >> 1n), 0n)
}
let fdflagsList = List.filteri(flagsToWasmVal, orderedFdflags)
use WasmI64.{ (&), gtU as (>), (<<) }
let flagsToWasmVal = (flag, i) => {
let rights = WasmI64.load(structPtr, 8n)
(rights & 1N << WasmI64.extendI32U(WasmI32.fromGrain(i) >> 1n)) > 0N
}
let rightsList = List.filteri(flagsToWasmVal, orderedRights)
let flagsToWasmVal = (flag, i) => {
let rightsInheriting = WasmI64.load(structPtr, 16n)
(rightsInheriting & 1N << WasmI64.extendI32U(WasmI32.fromGrain(i) >> 1n)) >
0N
}
let rightsInheritingList = List.filteri(flagsToWasmVal, orderedRights)
Memory.free(structPtr)
return Ok(
{
filetype,
flags: fdflagsList,
rights: rightsList,
rightsInheriting: rightsInheritingList,
},
)
}
/**
* Update the flags associated with a file descriptor.
*
* @param fd: The file descriptor to update flags
* @param flags: The flags to apply to the file descriptor
* @returns `Ok(void)` if successful or `Err(exception)` otherwise
*/
@unsafe
provide let fdSetFlags = (fd: FileDescriptor, flags: List<FdFlag>) => {
let fdArg = fd
let flagsArg = flags
let fd = match (fd) {
FileDescriptor(n) => WasmI32.fromGrain(n) >> 1n,
}