-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathmod.rs
1870 lines (1741 loc) · 68.2 KB
/
mod.rs
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
use crate::preview2::bindings::cli_base::{preopens, stderr, stdin, stdout};
use crate::preview2::bindings::clocks::{monotonic_clock, wall_clock};
use crate::preview2::bindings::filesystem::filesystem;
use crate::preview2::bindings::io::streams;
use crate::preview2::filesystem::TableFsExt;
use crate::preview2::preview2::filesystem::TableReaddirExt;
use crate::preview2::{bindings, TableError, WasiView};
use anyhow::{anyhow, bail, Context};
use std::borrow::Borrow;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::mem::{size_of, size_of_val};
use std::ops::{Deref, DerefMut};
use std::slice;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use wiggle::tracing::instrument;
use wiggle::{GuestError, GuestPtr, GuestSliceMut, GuestStrCow, GuestType};
#[derive(Clone, Debug)]
struct File {
/// The handle to the preview2 descriptor that this file is referencing.
fd: filesystem::Descriptor,
/// The current-position pointer.
position: Arc<AtomicU64>,
/// In append mode, all writes append to the file.
append: bool,
/// In blocking mode, read and write calls dispatch to blocking_read and
/// blocking_write on the underlying streams. When false, read and write
/// dispatch to stream's plain read and write.
blocking: bool,
}
#[derive(Clone, Debug)]
enum Descriptor {
Stdin(preopens::InputStream),
Stdout(preopens::OutputStream),
Stderr(preopens::OutputStream),
PreopenDirectory((filesystem::Descriptor, String)),
File(File),
}
#[derive(Debug, Default)]
pub struct WasiPreview1Adapter {
descriptors: Option<Descriptors>,
}
#[derive(Debug, Default)]
struct Descriptors {
used: BTreeMap<u32, Descriptor>,
free: Vec<u32>,
}
impl Deref for Descriptors {
type Target = BTreeMap<u32, Descriptor>;
fn deref(&self) -> &Self::Target {
&self.used
}
}
impl DerefMut for Descriptors {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.used
}
}
impl Descriptors {
/// Initializes [Self] using `preopens`
fn new(
preopens: &mut (impl preopens::Host + stdin::Host + stdout::Host + stderr::Host + ?Sized),
) -> Result<Self, types::Error> {
let stdin = preopens
.get_stdin()
.context("failed to call `get-stdin`")
.map_err(types::Error::trap)?;
let stdout = preopens
.get_stdout()
.context("failed to call `get-stdout`")
.map_err(types::Error::trap)?;
let stderr = preopens
.get_stderr()
.context("failed to call `get-stderr`")
.map_err(types::Error::trap)?;
let directories = preopens
.get_directories()
.context("failed to call `get-directories`")
.map_err(types::Error::trap)?;
let mut descriptors = Self::default();
descriptors.push(Descriptor::Stdin(stdin))?;
descriptors.push(Descriptor::Stdout(stdout))?;
descriptors.push(Descriptor::Stderr(stderr))?;
for dir in directories {
descriptors.push(Descriptor::PreopenDirectory(dir))?;
}
Ok(descriptors)
}
/// Returns next descriptor number, which was never assigned
fn unused(&self) -> Result<u32> {
match self.last_key_value() {
Some((fd, _)) => {
if let Some(fd) = fd.checked_add(1) {
return Ok(fd);
}
if self.len() == u32::MAX as usize {
return Err(types::Errno::Loop.into());
}
// TODO: Optimize
Ok((0..u32::MAX)
.rev()
.find(|fd| !self.contains_key(fd))
.expect("failed to find an unused file descriptor"))
}
None => Ok(0),
}
}
/// Removes the [Descriptor] corresponding to `fd`
fn remove(&mut self, fd: types::Fd) -> Option<Descriptor> {
let fd = fd.into();
let desc = self.used.remove(&fd)?;
self.free.push(fd);
Some(desc)
}
/// Pushes the [Descriptor] returning corresponding number.
/// This operation will try to reuse numbers previously removed via [`Self::remove`]
/// and rely on [`Self::unused`] if no free numbers are recorded
fn push(&mut self, desc: Descriptor) -> Result<u32> {
let fd = if let Some(fd) = self.free.pop() {
fd
} else {
self.unused()?
};
assert!(self.insert(fd, desc).is_none());
Ok(fd)
}
/// Like [Self::push], but for [`File`]
fn push_file(&mut self, file: File) -> Result<u32> {
self.push(Descriptor::File(file))
}
}
impl WasiPreview1Adapter {
pub fn new() -> Self {
Self::default()
}
}
// Any context that needs to support preview 1 will impl this trait. They can
// construct the needed member with WasiPreview1Adapter::new().
pub trait WasiPreview1View: Send + Sync + WasiView {
fn adapter(&self) -> &WasiPreview1Adapter;
fn adapter_mut(&mut self) -> &mut WasiPreview1Adapter;
}
/// A mutably-borrowed [`WasiPreview1View`] implementation, which provides access to the stored
/// state. It can be thought of as an in-flight [`WasiPreview1Adapter`] transaction, all
/// changes will be recorded in the underlying [`WasiPreview1Adapter`] returned by
/// [`WasiPreview1View::adapter_mut`] on [`Drop`] of this struct.
// NOTE: This exists for the most part just due to the fact that `bindgen` generates methods with
// `&mut self` receivers and so this struct lets us extend the lifetime of the `&mut self` borrow
// of the [`WasiPreview1View`] to provide means to return mutably and immutably borrowed [`Descriptors`]
// without having to rely on something like `Arc<Mutex<Descriptors>>`, while also being able to
// call methods like [`TableFsExt::is_file`] and hiding complexity from preview1 method implementations.
struct Transaction<'a, T: WasiPreview1View + ?Sized> {
view: &'a mut T,
descriptors: Cell<Descriptors>,
}
impl<T: WasiPreview1View + ?Sized> Drop for Transaction<'_, T> {
/// Record changes in the [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
fn drop(&mut self) {
let descriptors = self.descriptors.take();
self.view.adapter_mut().descriptors = Some(descriptors);
}
}
impl<T: WasiPreview1View + ?Sized> Transaction<'_, T> {
/// Borrows [`Descriptor`] corresponding to `fd`.
///
/// # Errors
///
/// Returns [`types::Errno::Badf`] if no [`Descriptor`] is found
fn get_descriptor(&mut self, fd: types::Fd) -> Result<&Descriptor> {
let fd = fd.into();
let desc = self
.descriptors
.get_mut()
.get(&fd)
.ok_or(types::Errno::Badf)?;
Ok(desc)
}
/// Borrows [`File`] corresponding to `fd`
/// if it describes a [`Descriptor::File`] of [`crate::preview2::filesystem::File`] type
fn get_file(&mut self, fd: types::Fd) -> Result<&File> {
let fd = fd.into();
match self.descriptors.get_mut().get(&fd) {
Some(Descriptor::File(file @ File { fd, .. })) if self.view.table().is_file(*fd) => {
Ok(file)
}
_ => Err(types::Errno::Badf.into()),
}
}
/// Mutably borrows [`File`] corresponding to `fd`
/// if it describes a [`Descriptor::File`] of [`crate::preview2::filesystem::File`] type
fn get_file_mut(&mut self, fd: types::Fd) -> Result<&mut File> {
let fd = fd.into();
match self.descriptors.get_mut().get_mut(&fd) {
Some(Descriptor::File(file)) if self.view.table().is_file(file.fd) => Ok(file),
_ => Err(types::Errno::Badf.into()),
}
}
/// Borrows [`File`] corresponding to `fd`
/// if it describes a [`Descriptor::File`] of [`crate::preview2::filesystem::File`] type.
///
/// # Errors
///
/// Returns [`types::Errno::Spipe`] if the descriptor corresponds to stdio
fn get_seekable(&mut self, fd: types::Fd) -> Result<&File> {
let fd = fd.into();
match self.descriptors.get_mut().get(&fd) {
Some(Descriptor::File(file @ File { fd, .. })) if self.view.table().is_file(*fd) => {
Ok(file)
}
Some(Descriptor::Stdin(..) | Descriptor::Stdout(..) | Descriptor::Stderr(..)) => {
// NOTE: legacy implementation returns SPIPE here
Err(types::Errno::Spipe.into())
}
_ => Err(types::Errno::Badf.into()),
}
}
/// Returns [`filesystem::Descriptor`] corresponding to `fd`
fn get_fd(&mut self, fd: types::Fd) -> Result<filesystem::Descriptor> {
match self.get_descriptor(fd)? {
Descriptor::File(File { fd, .. }) => Ok(*fd),
Descriptor::PreopenDirectory((fd, _)) => Ok(*fd),
Descriptor::Stdin(stream) => Ok(*stream),
Descriptor::Stdout(stream) | Descriptor::Stderr(stream) => Ok(*stream),
}
}
/// Returns [`filesystem::Descriptor`] corresponding to `fd`
/// if it describes a [`Descriptor::File`] of [`crate::preview2::filesystem::File`] type
fn get_file_fd(&mut self, fd: types::Fd) -> Result<filesystem::Descriptor> {
self.get_file(fd).map(|File { fd, .. }| *fd)
}
/// Returns [`filesystem::Descriptor`] corresponding to `fd`
/// if it describes a [`Descriptor::File`] or [`Descriptor::PreopenDirectory`]
/// of [`crate::preview2::filesystem::Dir`] type
fn get_dir_fd(&mut self, fd: types::Fd) -> Result<filesystem::Descriptor> {
let fd = fd.into();
match self.descriptors.get_mut().get(&fd) {
Some(Descriptor::File(File { fd, .. })) if self.view.table().is_dir(*fd) => Ok(*fd),
Some(Descriptor::PreopenDirectory((fd, _))) => Ok(*fd),
_ => Err(types::Errno::Badf.into()),
}
}
}
trait WasiPreview1ViewExt:
WasiPreview1View + preopens::Host + stdin::Host + stdout::Host + stderr::Host
{
/// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
/// and returns [`Transaction`] on success
fn transact(&mut self) -> Result<Transaction<'_, Self>, types::Error> {
let descriptors = if let Some(descriptors) = self.adapter_mut().descriptors.take() {
descriptors
} else {
Descriptors::new(self)?
}
.into();
Ok(Transaction {
view: self,
descriptors,
})
}
/// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
/// and returns [`filesystem::Descriptor`] corresponding to `fd`
fn get_fd(&mut self, fd: types::Fd) -> Result<filesystem::Descriptor, types::Error> {
let mut st = self.transact()?;
let fd = st.get_fd(fd)?;
Ok(fd)
}
/// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
/// and returns [`filesystem::Descriptor`] corresponding to `fd`
/// if it describes a [`Descriptor::File`] of [`crate::preview2::filesystem::File`] type
fn get_file_fd(&mut self, fd: types::Fd) -> Result<filesystem::Descriptor, types::Error> {
let mut st = self.transact()?;
let fd = st.get_file_fd(fd)?;
Ok(fd)
}
/// Lazily initializes [`WasiPreview1Adapter`] returned by [`WasiPreview1View::adapter_mut`]
/// and returns [`filesystem::Descriptor`] corresponding to `fd`
/// if it describes a [`Descriptor::File`] or [`Descriptor::PreopenDirectory`]
/// of [`crate::preview2::filesystem::Dir`] type
fn get_dir_fd(&mut self, fd: types::Fd) -> Result<filesystem::Descriptor, types::Error> {
let mut st = self.transact()?;
let fd = st.get_dir_fd(fd)?;
Ok(fd)
}
}
impl<T: WasiPreview1View + preopens::Host> WasiPreview1ViewExt for T {}
pub fn add_to_linker<
T: WasiPreview1View
+ bindings::cli_base::environment::Host
+ bindings::cli_base::exit::Host
+ bindings::cli_base::preopens::Host
+ bindings::filesystem::filesystem::Host
+ bindings::sync_io::poll::poll::Host
+ bindings::random::random::Host
+ bindings::io::streams::Host
+ bindings::clocks::monotonic_clock::Host
+ bindings::clocks::wall_clock::Host,
>(
linker: &mut wasmtime::Linker<T>,
) -> anyhow::Result<()> {
wasi_snapshot_preview1::add_to_linker(linker, |t| t)
}
// Generate the wasi_snapshot_preview1::WasiSnapshotPreview1 trait,
// and the module types.
// None of the generated modules, traits, or types should be used externally
// to this module.
wiggle::from_witx!({
witx: ["$CARGO_MANIFEST_DIR/witx/wasi_snapshot_preview1.witx"],
async: {
wasi_snapshot_preview1::{
fd_advise, fd_close, fd_datasync, fd_fdstat_get, fd_filestat_get, fd_filestat_set_size,
fd_filestat_set_times, fd_read, fd_pread, fd_seek, fd_sync, fd_readdir, fd_write,
fd_pwrite, poll_oneoff, path_create_directory, path_filestat_get,
path_filestat_set_times, path_link, path_open, path_readlink, path_remove_directory,
path_rename, path_symlink, path_unlink_file
}
},
errors: { errno => trappable Error },
});
impl wiggle::GuestErrorType for types::Errno {
fn success() -> Self {
Self::Success
}
}
fn systimespec(set: bool, ts: types::Timestamp, now: bool) -> Result<filesystem::NewTimestamp> {
if set && now {
Err(types::Errno::Inval.into())
} else if set {
Ok(filesystem::NewTimestamp::Timestamp(filesystem::Datetime {
seconds: ts / 1_000_000_000,
nanoseconds: (ts % 1_000_000_000) as _,
}))
} else if now {
Ok(filesystem::NewTimestamp::Now)
} else {
Ok(filesystem::NewTimestamp::NoChange)
}
}
impl TryFrom<wall_clock::Datetime> for types::Timestamp {
type Error = types::Errno;
fn try_from(
wall_clock::Datetime {
seconds,
nanoseconds,
}: wall_clock::Datetime,
) -> Result<Self, Self::Error> {
types::Timestamp::from(seconds)
.checked_mul(1_000_000_000)
.and_then(|ns| ns.checked_add(nanoseconds.into()))
.ok_or(types::Errno::Overflow)
}
}
impl From<types::Lookupflags> for filesystem::PathFlags {
fn from(flags: types::Lookupflags) -> Self {
if flags.contains(types::Lookupflags::SYMLINK_FOLLOW) {
filesystem::PathFlags::SYMLINK_FOLLOW
} else {
filesystem::PathFlags::empty()
}
}
}
impl From<types::Oflags> for filesystem::OpenFlags {
fn from(flags: types::Oflags) -> Self {
let mut out = filesystem::OpenFlags::empty();
if flags.contains(types::Oflags::CREAT) {
out |= filesystem::OpenFlags::CREATE;
}
if flags.contains(types::Oflags::DIRECTORY) {
out |= filesystem::OpenFlags::DIRECTORY;
}
if flags.contains(types::Oflags::EXCL) {
out |= filesystem::OpenFlags::EXCLUSIVE;
}
if flags.contains(types::Oflags::TRUNC) {
out |= filesystem::OpenFlags::TRUNCATE;
}
out
}
}
impl From<types::Advice> for filesystem::Advice {
fn from(advice: types::Advice) -> Self {
match advice {
types::Advice::Normal => filesystem::Advice::Normal,
types::Advice::Sequential => filesystem::Advice::Sequential,
types::Advice::Random => filesystem::Advice::Random,
types::Advice::Willneed => filesystem::Advice::WillNeed,
types::Advice::Dontneed => filesystem::Advice::DontNeed,
types::Advice::Noreuse => filesystem::Advice::NoReuse,
}
}
}
impl TryFrom<filesystem::DescriptorType> for types::Filetype {
type Error = anyhow::Error;
fn try_from(ty: filesystem::DescriptorType) -> Result<Self, Self::Error> {
match ty {
filesystem::DescriptorType::RegularFile => Ok(types::Filetype::RegularFile),
filesystem::DescriptorType::Directory => Ok(types::Filetype::Directory),
filesystem::DescriptorType::BlockDevice => Ok(types::Filetype::BlockDevice),
filesystem::DescriptorType::CharacterDevice => Ok(types::Filetype::CharacterDevice),
// preview1 never had a FIFO code.
filesystem::DescriptorType::Fifo => Ok(types::Filetype::Unknown),
// TODO: Add a way to disginguish between FILETYPE_SOCKET_STREAM and
// FILETYPE_SOCKET_DGRAM.
filesystem::DescriptorType::Socket => {
bail!("sockets are not currently supported")
}
filesystem::DescriptorType::SymbolicLink => Ok(types::Filetype::SymbolicLink),
filesystem::DescriptorType::Unknown => Ok(types::Filetype::Unknown),
}
}
}
impl From<filesystem::ErrorCode> for types::Errno {
fn from(code: filesystem::ErrorCode) -> Self {
match code {
filesystem::ErrorCode::Access => types::Errno::Acces,
filesystem::ErrorCode::WouldBlock => types::Errno::Again,
filesystem::ErrorCode::Already => types::Errno::Already,
filesystem::ErrorCode::BadDescriptor => types::Errno::Badf,
filesystem::ErrorCode::Busy => types::Errno::Busy,
filesystem::ErrorCode::Deadlock => types::Errno::Deadlk,
filesystem::ErrorCode::Quota => types::Errno::Dquot,
filesystem::ErrorCode::Exist => types::Errno::Exist,
filesystem::ErrorCode::FileTooLarge => types::Errno::Fbig,
filesystem::ErrorCode::IllegalByteSequence => types::Errno::Ilseq,
filesystem::ErrorCode::InProgress => types::Errno::Inprogress,
filesystem::ErrorCode::Interrupted => types::Errno::Intr,
filesystem::ErrorCode::Invalid => types::Errno::Inval,
filesystem::ErrorCode::Io => types::Errno::Io,
filesystem::ErrorCode::IsDirectory => types::Errno::Isdir,
filesystem::ErrorCode::Loop => types::Errno::Loop,
filesystem::ErrorCode::TooManyLinks => types::Errno::Mlink,
filesystem::ErrorCode::MessageSize => types::Errno::Msgsize,
filesystem::ErrorCode::NameTooLong => types::Errno::Nametoolong,
filesystem::ErrorCode::NoDevice => types::Errno::Nodev,
filesystem::ErrorCode::NoEntry => types::Errno::Noent,
filesystem::ErrorCode::NoLock => types::Errno::Nolck,
filesystem::ErrorCode::InsufficientMemory => types::Errno::Nomem,
filesystem::ErrorCode::InsufficientSpace => types::Errno::Nospc,
filesystem::ErrorCode::Unsupported => types::Errno::Notsup,
filesystem::ErrorCode::NotDirectory => types::Errno::Notdir,
filesystem::ErrorCode::NotEmpty => types::Errno::Notempty,
filesystem::ErrorCode::NotRecoverable => types::Errno::Notrecoverable,
filesystem::ErrorCode::NoTty => types::Errno::Notty,
filesystem::ErrorCode::NoSuchDevice => types::Errno::Nxio,
filesystem::ErrorCode::Overflow => types::Errno::Overflow,
filesystem::ErrorCode::NotPermitted => types::Errno::Perm,
filesystem::ErrorCode::Pipe => types::Errno::Pipe,
filesystem::ErrorCode::ReadOnly => types::Errno::Rofs,
filesystem::ErrorCode::InvalidSeek => types::Errno::Spipe,
filesystem::ErrorCode::TextFileBusy => types::Errno::Txtbsy,
filesystem::ErrorCode::CrossDevice => types::Errno::Xdev,
}
}
}
impl From<std::num::TryFromIntError> for types::Error {
fn from(_: std::num::TryFromIntError) -> Self {
types::Errno::Overflow.into()
}
}
impl From<GuestError> for types::Error {
fn from(err: GuestError) -> Self {
use wiggle::GuestError::*;
match err {
InvalidFlagValue { .. } => types::Errno::Inval.into(),
InvalidEnumValue { .. } => types::Errno::Inval.into(),
// As per
// https://github.com/WebAssembly/wasi/blob/main/legacy/tools/witx-docs.md#pointers
//
// > If a misaligned pointer is passed to a function, the function
// > shall trap.
// >
// > If an out-of-bounds pointer is passed to a function and the
// > function needs to dereference it, the function shall trap.
//
// so this turns OOB and misalignment errors into traps.
PtrOverflow { .. } | PtrOutOfBounds { .. } | PtrNotAligned { .. } => {
types::Error::trap(err.into())
}
PtrBorrowed { .. } => types::Errno::Fault.into(),
InvalidUtf8 { .. } => types::Errno::Ilseq.into(),
TryFromIntError { .. } => types::Errno::Overflow.into(),
SliceLengthsDiffer { .. } => types::Errno::Fault.into(),
BorrowCheckerOutOfHandles { .. } => types::Errno::Fault.into(),
InFunc { err, .. } => types::Error::from(*err),
}
}
}
impl From<filesystem::ErrorCode> for types::Error {
fn from(code: filesystem::ErrorCode) -> Self {
types::Errno::from(code).into()
}
}
impl TryFrom<filesystem::Error> for types::Errno {
type Error = anyhow::Error;
fn try_from(err: filesystem::Error) -> Result<Self, Self::Error> {
match err.downcast() {
Ok(code) => Ok(code.into()),
Err(e) => Err(e),
}
}
}
impl TryFrom<filesystem::Error> for types::Error {
type Error = anyhow::Error;
fn try_from(err: filesystem::Error) -> Result<Self, Self::Error> {
match err.downcast() {
Ok(code) => Ok(code.into()),
Err(e) => Err(e),
}
}
}
impl From<TableError> for types::Error {
fn from(err: TableError) -> Self {
types::Error::trap(err.into())
}
}
type Result<T, E = types::Error> = std::result::Result<T, E>;
fn write_bytes<'a>(
ptr: impl Borrow<GuestPtr<'a, u8>>,
buf: impl AsRef<[u8]>,
) -> Result<GuestPtr<'a, u8>, types::Error> {
// NOTE: legacy implementation always returns Inval errno
let buf = buf.as_ref();
let len = buf.len().try_into()?;
let ptr = ptr.borrow();
ptr.as_array(len).copy_from_slice(buf)?;
let next = ptr.add(len)?;
Ok(next)
}
fn write_byte<'a>(ptr: impl Borrow<GuestPtr<'a, u8>>, byte: u8) -> Result<GuestPtr<'a, u8>> {
let ptr = ptr.borrow();
ptr.write(byte)?;
let next = ptr.add(1)?;
Ok(next)
}
fn read_str<'a>(ptr: impl Borrow<GuestPtr<'a, str>>) -> Result<GuestStrCow<'a>> {
let s = ptr.borrow().as_cow()?;
Ok(s)
}
fn read_string<'a>(ptr: impl Borrow<GuestPtr<'a, str>>) -> Result<String> {
read_str(ptr).map(|s| s.to_string())
}
// Find first non-empty buffer.
fn first_non_empty_ciovec(ciovs: &types::CiovecArray<'_>) -> Result<Option<Vec<u8>>> {
for iov in ciovs.iter() {
let iov = iov?.read()?;
if iov.buf_len == 0 {
continue;
}
return Ok(Some(iov.buf.as_array(iov.buf_len).to_vec()?));
}
Ok(None)
}
// Find first non-empty buffer.
fn first_non_empty_iovec<'a>(
iovs: &types::IovecArray<'a>,
) -> Result<Option<GuestSliceMut<'a, u8>>> {
iovs.iter()
.map(|iov| {
let iov = iov?.read()?;
if iov.buf_len == 0 {
return Ok(None);
}
let slice = iov.buf.as_array(iov.buf_len).as_slice_mut()?;
Ok(slice)
})
.find_map(Result::transpose)
.transpose()
}
#[async_trait::async_trait]
// Implement the WasiSnapshotPreview1 trait using only the traits that are
// required for T, i.e., in terms of the preview 2 wit interface, and state
// stored in the WasiPreview1Adapter struct.
impl<
T: WasiPreview1View
+ bindings::cli_base::environment::Host
+ bindings::cli_base::exit::Host
+ bindings::cli_base::preopens::Host
+ bindings::filesystem::filesystem::Host
+ bindings::sync_io::poll::poll::Host
+ bindings::random::random::Host
+ bindings::io::streams::Host
+ bindings::clocks::monotonic_clock::Host
+ bindings::clocks::wall_clock::Host,
> wasi_snapshot_preview1::WasiSnapshotPreview1 for T
{
#[instrument(skip(self))]
fn args_get<'b>(
&mut self,
argv: &GuestPtr<'b, GuestPtr<'b, u8>>,
argv_buf: &GuestPtr<'b, u8>,
) -> Result<(), types::Error> {
self.get_arguments()
.context("failed to call `get-arguments`")
.map_err(types::Error::trap)?
.into_iter()
.try_fold((*argv, *argv_buf), |(argv, argv_buf), arg| -> Result<_> {
argv.write(argv_buf)?;
let argv = argv.add(1)?;
let argv_buf = write_bytes(argv_buf, arg)?;
let argv_buf = write_byte(argv_buf, 0)?;
Ok((argv, argv_buf))
})?;
Ok(())
}
#[instrument(skip(self))]
fn args_sizes_get(&mut self) -> Result<(types::Size, types::Size), types::Error> {
let args = self
.get_arguments()
.context("failed to call `get-arguments`")
.map_err(types::Error::trap)?;
let num = args.len().try_into().map_err(|_| types::Errno::Overflow)?;
let len = args
.iter()
.map(|buf| buf.len() + 1) // Each argument is expected to be `\0` terminated.
.sum::<usize>()
.try_into()
.map_err(|_| types::Errno::Overflow)?;
Ok((num, len))
}
#[instrument(skip(self))]
fn environ_get<'b>(
&mut self,
environ: &GuestPtr<'b, GuestPtr<'b, u8>>,
environ_buf: &GuestPtr<'b, u8>,
) -> Result<(), types::Error> {
self.get_environment()
.context("failed to call `get-environment`")
.map_err(types::Error::trap)?
.into_iter()
.try_fold(
(*environ, *environ_buf),
|(environ, environ_buf), (k, v)| -> Result<_, types::Error> {
environ.write(environ_buf)?;
let environ = environ.add(1)?;
let environ_buf = write_bytes(environ_buf, k)?;
let environ_buf = write_byte(environ_buf, b'=')?;
let environ_buf = write_bytes(environ_buf, v)?;
let environ_buf = write_byte(environ_buf, 0)?;
Ok((environ, environ_buf))
},
)?;
Ok(())
}
#[instrument(skip(self))]
fn environ_sizes_get(&mut self) -> Result<(types::Size, types::Size), types::Error> {
let environ = self
.get_environment()
.context("failed to call `get-environment`")
.map_err(types::Error::trap)?;
let num = environ.len().try_into()?;
let len = environ
.iter()
.map(|(k, v)| k.len() + 1 + v.len() + 1) // Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s.
.sum::<usize>()
.try_into()?;
Ok((num, len))
}
#[instrument(skip(self))]
fn clock_res_get(&mut self, id: types::Clockid) -> Result<types::Timestamp, types::Error> {
let res = match id {
types::Clockid::Realtime => wall_clock::Host::resolution(self)
.context("failed to call `wall_clock::resolution`")
.map_err(types::Error::trap)?
.try_into()?,
types::Clockid::Monotonic => monotonic_clock::Host::resolution(self)
.context("failed to call `monotonic_clock::resolution`")
.map_err(types::Error::trap)?,
types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
return Err(types::Errno::Badf.into())
}
};
Ok(res)
}
#[instrument(skip(self))]
fn clock_time_get(
&mut self,
id: types::Clockid,
_precision: types::Timestamp,
) -> Result<types::Timestamp, types::Error> {
let now = match id {
types::Clockid::Realtime => wall_clock::Host::now(self)
.context("failed to call `wall_clock::now`")
.map_err(types::Error::trap)?
.try_into()?,
types::Clockid::Monotonic => monotonic_clock::Host::now(self)
.context("failed to call `monotonic_clock::now`")
.map_err(types::Error::trap)?,
types::Clockid::ProcessCputimeId | types::Clockid::ThreadCputimeId => {
return Err(types::Errno::Badf.into())
}
};
Ok(now)
}
#[instrument(skip(self))]
async fn fd_advise(
&mut self,
fd: types::Fd,
offset: types::Filesize,
len: types::Filesize,
advice: types::Advice,
) -> Result<(), types::Error> {
let fd = self.get_file_fd(fd)?;
self.advise(fd, offset, len, advice.into())
.await
.map_err(|e| {
e.try_into()
.context("failed to call `advise`")
.unwrap_or_else(types::Error::trap)
})
}
/// Force the allocation of space in a file.
/// NOTE: This is similar to `posix_fallocate` in POSIX.
#[instrument(skip(self))]
fn fd_allocate(
&mut self,
fd: types::Fd,
_offset: types::Filesize,
_len: types::Filesize,
) -> Result<(), types::Error> {
self.get_file_fd(fd)?;
Err(types::Errno::Notsup.into())
}
/// Close a file descriptor.
/// NOTE: This is similar to `close` in POSIX.
#[instrument(skip(self))]
async fn fd_close(&mut self, fd: types::Fd) -> Result<(), types::Error> {
let desc = self
.transact()?
.descriptors
.get_mut()
.remove(fd)
.ok_or(types::Errno::Badf)?
.clone();
match desc {
Descriptor::Stdin(stream) => streams::Host::drop_input_stream(self, stream)
.await
.context("failed to call `drop-input-stream`"),
Descriptor::Stdout(stream) | Descriptor::Stderr(stream) => {
streams::Host::drop_output_stream(self, stream)
.await
.context("failed to call `drop-output-stream`")
}
Descriptor::File(File { fd, .. }) | Descriptor::PreopenDirectory((fd, _)) => self
.drop_descriptor(fd)
.await
.context("failed to call `drop-descriptor`"),
}
.map_err(types::Error::trap)
}
/// Synchronize the data of a file to disk.
/// NOTE: This is similar to `fdatasync` in POSIX.
#[instrument(skip(self))]
async fn fd_datasync(&mut self, fd: types::Fd) -> Result<(), types::Error> {
let fd = self.get_file_fd(fd)?;
self.sync_data(fd).await.map_err(|e| {
e.try_into()
.context("failed to call `sync-data`")
.unwrap_or_else(types::Error::trap)
})
}
/// Get the attributes of a file descriptor.
/// NOTE: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well as additional fields.
#[instrument(skip(self))]
async fn fd_fdstat_get(&mut self, fd: types::Fd) -> Result<types::Fdstat, types::Error> {
let (fd, blocking, append) = match self.transact()?.get_descriptor(fd)? {
Descriptor::Stdin(..) => {
let fs_rights_base = types::Rights::FD_READ;
return Ok(types::Fdstat {
fs_filetype: types::Filetype::CharacterDevice,
fs_flags: types::Fdflags::empty(),
fs_rights_base,
fs_rights_inheriting: fs_rights_base,
});
}
Descriptor::Stdout(..) | Descriptor::Stderr(..) => {
let fs_rights_base = types::Rights::FD_WRITE;
return Ok(types::Fdstat {
fs_filetype: types::Filetype::CharacterDevice,
fs_flags: types::Fdflags::empty(),
fs_rights_base,
fs_rights_inheriting: fs_rights_base,
});
}
Descriptor::PreopenDirectory((_, _)) => {
// Hard-coded set or rights expected by many userlands:
let fs_rights_base = types::Rights::PATH_CREATE_DIRECTORY
| types::Rights::PATH_CREATE_FILE
| types::Rights::PATH_LINK_SOURCE
| types::Rights::PATH_LINK_TARGET
| types::Rights::PATH_OPEN
| types::Rights::FD_READDIR
| types::Rights::PATH_READLINK
| types::Rights::PATH_RENAME_SOURCE
| types::Rights::PATH_RENAME_TARGET
| types::Rights::PATH_SYMLINK
| types::Rights::PATH_REMOVE_DIRECTORY
| types::Rights::PATH_UNLINK_FILE
| types::Rights::PATH_FILESTAT_GET
| types::Rights::PATH_FILESTAT_SET_TIMES
| types::Rights::FD_FILESTAT_GET
| types::Rights::FD_FILESTAT_SET_TIMES;
let fs_rights_inheriting = fs_rights_base
| types::Rights::FD_DATASYNC
| types::Rights::FD_READ
| types::Rights::FD_SEEK
| types::Rights::FD_FDSTAT_SET_FLAGS
| types::Rights::FD_SYNC
| types::Rights::FD_TELL
| types::Rights::FD_WRITE
| types::Rights::FD_ADVISE
| types::Rights::FD_ALLOCATE
| types::Rights::FD_FILESTAT_GET
| types::Rights::FD_FILESTAT_SET_SIZE
| types::Rights::FD_FILESTAT_SET_TIMES
| types::Rights::POLL_FD_READWRITE;
return Ok(types::Fdstat {
fs_filetype: types::Filetype::Directory,
fs_flags: types::Fdflags::empty(),
fs_rights_base,
fs_rights_inheriting,
});
}
Descriptor::File(File {
fd,
blocking,
append,
..
}) => (*fd, *blocking, *append),
};
// TODO: use `try_join!` to poll both futures async, unfortunately that is not currently
// possible, because `bindgen` generates methods with `&mut self` receivers.
let flags = self.get_flags(fd).await.map_err(|e| {
e.try_into()
.context("failed to call `get-flags`")
.unwrap_or_else(types::Error::trap)
})?;
let fs_filetype = self
.get_type(fd)
.await
.map_err(|e| {
e.try_into()
.context("failed to call `get-type`")
.unwrap_or_else(types::Error::trap)
})?
.try_into()
.map_err(types::Error::trap)?;
let mut fs_flags = types::Fdflags::empty();
let mut fs_rights_base = types::Rights::all();
if !flags.contains(filesystem::DescriptorFlags::READ) {
fs_rights_base &= !types::Rights::FD_READ;
}
if !flags.contains(filesystem::DescriptorFlags::WRITE) {
fs_rights_base &= !types::Rights::FD_WRITE;
}
if flags.contains(filesystem::DescriptorFlags::DATA_INTEGRITY_SYNC) {
fs_flags |= types::Fdflags::DSYNC;
}
if flags.contains(filesystem::DescriptorFlags::REQUESTED_WRITE_SYNC) {
fs_flags |= types::Fdflags::RSYNC;
}
if flags.contains(filesystem::DescriptorFlags::FILE_INTEGRITY_SYNC) {
fs_flags |= types::Fdflags::SYNC;
}
if append {
fs_flags |= types::Fdflags::APPEND;
}
if !blocking {
fs_flags |= types::Fdflags::NONBLOCK;
}
Ok(types::Fdstat {
fs_filetype,
fs_flags,
fs_rights_base,
fs_rights_inheriting: fs_rights_base,
})
}
/// Adjust the flags associated with a file descriptor.
/// NOTE: This is similar to `fcntl(fd, F_SETFL, flags)` in POSIX.
#[instrument(skip(self))]
fn fd_fdstat_set_flags(
&mut self,
fd: types::Fd,
flags: types::Fdflags,
) -> Result<(), types::Error> {
let mut st = self.transact()?;
let File {
append, blocking, ..
} = st.get_file_mut(fd)?;
// Only support changing the NONBLOCK or APPEND flags.
if flags.contains(types::Fdflags::DSYNC)
|| flags.contains(types::Fdflags::SYNC)
|| flags.contains(types::Fdflags::RSYNC)
{
return Err(types::Errno::Inval.into());
}
*append = flags.contains(types::Fdflags::APPEND);
*blocking = !flags.contains(types::Fdflags::NONBLOCK);
Ok(())
}
/// Does not do anything if `fd` corresponds to a valid descriptor and returns `[types::Errno::Badf]` error otherwise.
#[instrument(skip(self))]
fn fd_fdstat_set_rights(
&mut self,
fd: types::Fd,
_fs_rights_base: types::Rights,
_fs_rights_inheriting: types::Rights,
) -> Result<(), types::Error> {
self.get_fd(fd)?;
Ok(())
}
/// Return the attributes of an open file.
#[instrument(skip(self))]
async fn fd_filestat_get(&mut self, fd: types::Fd) -> Result<types::Filestat, types::Error> {
let desc = self.transact()?.get_descriptor(fd)?.clone();
match desc {
Descriptor::Stdin(..) | Descriptor::Stdout(..) | Descriptor::Stderr(..) => {
Ok(types::Filestat {