-
Notifications
You must be signed in to change notification settings - Fork 824
/
mod.rs
5624 lines (5132 loc) · 185 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
#![allow(unused, clippy::too_many_arguments, clippy::cognitive_complexity)]
pub mod types {
pub use wasmer_wasi_types::*;
}
#[cfg(any(
target_os = "freebsd",
target_os = "linux",
target_os = "android",
target_vendor = "apple"
))]
pub mod unix;
#[cfg(any(target_arch = "wasm32"))]
pub mod wasm32;
#[cfg(any(target_os = "windows"))]
pub mod windows;
pub mod legacy;
//pub mod wasi;
#[cfg(feature = "wasix")]
pub mod wasix32;
#[cfg(feature = "wasix")]
pub mod wasix64;
use self::types::*;
use crate::state::{bus_error_into_wasi_err, wasi_error_into_bus_err, InodeHttpSocketType};
use crate::utils::map_io_err;
use crate::WasiBusProcessId;
use crate::{
mem_error_to_wasi,
state::{
self, fs_error_into_wasi_err, iterate_poll_events, net_error_into_wasi_err, poll,
virtual_file_type_to_wasi_file_type, Fd, Inode, InodeSocket, InodeSocketKind, InodeVal,
Kind, PollEvent, PollEventBuilder, WasiPipe, WasiState, MAX_SYMLINKS,
},
WasiEnv, WasiError, WasiThread, WasiThreadId,
};
use bytes::Bytes;
use std::borrow::{Borrow, Cow};
use std::convert::{Infallible, TryInto};
use std::io::{self, Read, Seek, Write};
use std::mem::transmute;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::ops::{Deref, DerefMut};
use std::sync::atomic::AtomicU64;
use std::sync::{atomic::Ordering, Mutex};
use std::sync::{mpsc, Arc};
use std::time::Duration;
use tracing::{debug, error, trace, warn};
use wasmer::{
AsStoreMut, Extern, FunctionEnv, FunctionEnvMut, Instance, Memory, Memory32, Memory64,
MemorySize, MemoryView, Module, RuntimeError, Value, WasmPtr, WasmSlice,
};
use wasmer_vbus::{FileDescriptor, StdioMode};
use wasmer_vfs::{FsError, VirtualFile};
use wasmer_vnet::{SocketHttpRequest, StreamSecurity};
#[cfg(any(
target_os = "freebsd",
target_os = "linux",
target_os = "android",
target_vendor = "apple"
))]
pub use unix::*;
#[cfg(any(target_os = "windows"))]
pub use windows::*;
#[cfg(any(target_arch = "wasm32"))]
pub use wasm32::*;
fn to_offset<M: MemorySize>(offset: usize) -> Result<M::Offset, __wasi_errno_t> {
let ret: M::Offset = offset.try_into().map_err(|_| __WASI_EINVAL)?;
Ok(ret)
}
fn from_offset<M: MemorySize>(offset: M::Offset) -> Result<usize, __wasi_errno_t> {
let ret: usize = offset.try_into().map_err(|_| __WASI_EINVAL)?;
Ok(ret)
}
fn write_bytes_inner<T: Write, M: MemorySize>(
mut write_loc: T,
memory: &MemoryView,
iovs_arr_cell: WasmSlice<__wasi_ciovec_t<M>>,
) -> Result<usize, __wasi_errno_t> {
let mut bytes_written = 0usize;
for iov in iovs_arr_cell.iter() {
let iov_inner = iov.read().map_err(mem_error_to_wasi)?;
let bytes = WasmPtr::<u8, M>::new(iov_inner.buf)
.slice(memory, iov_inner.buf_len)
.map_err(mem_error_to_wasi)?;
let bytes = bytes.read_to_vec().map_err(mem_error_to_wasi)?;
write_loc.write_all(&bytes).map_err(map_io_err)?;
bytes_written += from_offset::<M>(iov_inner.buf_len)?;
}
Ok(bytes_written)
}
pub(crate) fn write_bytes<T: Write, M: MemorySize>(
mut write_loc: T,
memory: &MemoryView,
iovs_arr: WasmSlice<__wasi_ciovec_t<M>>,
) -> Result<usize, __wasi_errno_t> {
let result = write_bytes_inner::<_, M>(&mut write_loc, memory, iovs_arr);
write_loc.flush();
result
}
pub(crate) fn read_bytes<T: Read, M: MemorySize>(
mut reader: T,
memory: &MemoryView,
iovs_arr: WasmSlice<__wasi_iovec_t<M>>,
) -> Result<usize, __wasi_errno_t> {
let mut bytes_read = 0usize;
// We allocate the raw_bytes first once instead of
// N times in the loop.
let mut raw_bytes: Vec<u8> = vec![0; 1024];
for iov in iovs_arr.iter() {
let iov_inner = iov.read().map_err(mem_error_to_wasi)?;
raw_bytes.clear();
let to_read = from_offset::<M>(iov_inner.buf_len)?;
raw_bytes.resize(to_read, 0);
let has_read = reader.read(&mut raw_bytes).map_err(map_io_err)?;
let buf = WasmPtr::<u8, M>::new(iov_inner.buf)
.slice(memory, iov_inner.buf_len)
.map_err(mem_error_to_wasi)?;
buf.write_slice(&raw_bytes).map_err(mem_error_to_wasi)?;
bytes_read += has_read;
if has_read != to_read {
return Ok(bytes_read);
}
}
Ok(bytes_read)
}
/// checks that `rights_check_set` is a subset of `rights_set`
fn has_rights(rights_set: __wasi_rights_t, rights_check_set: __wasi_rights_t) -> bool {
rights_set | rights_check_set == rights_set
}
fn __sock_actor<T, F>(
ctx: &FunctionEnvMut<'_, WasiEnv>,
sock: __wasi_fd_t,
rights: __wasi_rights_t,
actor: F,
) -> Result<T, __wasi_errno_t>
where
F: FnOnce(&crate::state::InodeSocket) -> Result<T, __wasi_errno_t>,
{
let env = ctx.data();
let (_, state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = state.fs.get_fd(sock)?;
let ret = {
if rights != 0 && !has_rights(fd_entry.rights, rights) {
return Err(__WASI_EACCES);
}
let inode_idx = fd_entry.inode;
let inode = &inodes.arena[inode_idx];
let mut guard = inode.read();
let deref = guard.deref();
match deref {
Kind::Socket { socket } => actor(socket)?,
_ => {
return Err(__WASI_ENOTSOCK);
}
}
};
Ok(ret)
}
fn __sock_actor_mut<T, F>(
ctx: &FunctionEnvMut<'_, WasiEnv>,
sock: __wasi_fd_t,
rights: __wasi_rights_t,
actor: F,
) -> Result<T, __wasi_errno_t>
where
F: FnOnce(&mut crate::state::InodeSocket) -> Result<T, __wasi_errno_t>,
{
let env = ctx.data();
let (_, state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = state.fs.get_fd(sock)?;
let ret = {
if rights != 0 && !has_rights(fd_entry.rights, rights) {
return Err(__WASI_EACCES);
}
let inode_idx = fd_entry.inode;
let inode = &inodes.arena[inode_idx];
let mut guard = inode.write();
let deref_mut = guard.deref_mut();
match deref_mut {
Kind::Socket { socket } => actor(socket)?,
_ => {
return Err(__WASI_ENOTSOCK);
}
}
};
Ok(ret)
}
fn __sock_upgrade<F>(
ctx: &FunctionEnvMut<'_, WasiEnv>,
sock: __wasi_fd_t,
rights: __wasi_rights_t,
actor: F,
) -> Result<(), __wasi_errno_t>
where
F: FnOnce(
&mut crate::state::InodeSocket,
) -> Result<Option<crate::state::InodeSocket>, __wasi_errno_t>,
{
let env = ctx.data();
let (_, state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = state.fs.get_fd(sock)?;
if rights != 0 && !has_rights(fd_entry.rights, rights) {
return Err(__WASI_EACCES);
}
let inode_idx = fd_entry.inode;
let inode = &inodes.arena[inode_idx];
let mut guard = inode.write();
let deref_mut = guard.deref_mut();
match deref_mut {
Kind::Socket { socket } => {
let new_socket = actor(socket)?;
if let Some(mut new_socket) = new_socket {
std::mem::swap(socket, &mut new_socket);
}
}
_ => {
return Err(__WASI_ENOTSOCK);
}
}
Ok(())
}
#[must_use]
fn write_buffer_array<M: MemorySize>(
memory: &MemoryView,
from: &[Vec<u8>],
ptr_buffer: WasmPtr<WasmPtr<u8, M>, M>,
buffer: WasmPtr<u8, M>,
) -> __wasi_errno_t {
let ptrs = wasi_try_mem!(ptr_buffer.slice(memory, wasi_try!(to_offset::<M>(from.len()))));
let mut current_buffer_offset = 0usize;
for ((i, sub_buffer), ptr) in from.iter().enumerate().zip(ptrs.iter()) {
trace!("ptr: {:?}, subbuffer: {:?}", ptr, sub_buffer);
let mut buf_offset = buffer.offset();
buf_offset += wasi_try!(to_offset::<M>(current_buffer_offset));
let new_ptr = WasmPtr::new(buf_offset);
wasi_try_mem!(ptr.write(new_ptr));
let data =
wasi_try_mem!(new_ptr.slice(memory, wasi_try!(to_offset::<M>(sub_buffer.len()))));
wasi_try_mem!(data.write_slice(sub_buffer));
wasi_try_mem!(wasi_try_mem!(
new_ptr.add_offset(wasi_try!(to_offset::<M>(sub_buffer.len())))
)
.write(memory, 0));
current_buffer_offset += sub_buffer.len() + 1;
}
__WASI_ESUCCESS
}
fn get_current_time_in_nanos() -> Result<__wasi_timestamp_t, __wasi_errno_t> {
let now = std::time::SystemTime::now();
let duration = now
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.map_err(|_| __WASI_EIO)?;
Ok(duration.as_nanos() as __wasi_timestamp_t)
}
/// ### `args_get()`
/// Read command-line argument data.
/// The sizes of the buffers should match that returned by [`args_sizes_get()`](#args_sizes_get).
/// Inputs:
/// - `char **argv`
/// A pointer to a buffer to write the argument pointers.
/// - `char *argv_buf`
/// A pointer to a buffer to write the argument string data.
///
pub fn args_get<M: MemorySize>(
mut ctx: FunctionEnvMut<'_, WasiEnv>,
argv: WasmPtr<WasmPtr<u8, M>, M>,
argv_buf: WasmPtr<u8, M>,
) -> __wasi_errno_t {
debug!("wasi::args_get");
let env = ctx.data();
let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0);
let result = write_buffer_array(&memory, &state.args, argv, argv_buf);
debug!(
"=> args:\n{}",
state
.args
.iter()
.enumerate()
.map(|(i, v)| format!("{:>20}: {}", i, ::std::str::from_utf8(v).unwrap()))
.collect::<Vec<String>>()
.join("\n")
);
result
}
/// ### `args_sizes_get()`
/// Return command-line argument data sizes.
/// Outputs:
/// - `size_t *argc`
/// The number of arguments.
/// - `size_t *argv_buf_size`
/// The size of the argument string data.
pub fn args_sizes_get<M: MemorySize>(
mut ctx: FunctionEnvMut<'_, WasiEnv>,
argc: WasmPtr<M::Offset, M>,
argv_buf_size: WasmPtr<M::Offset, M>,
) -> __wasi_errno_t {
debug!("wasi::args_sizes_get");
let env = ctx.data();
let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0);
let argc = argc.deref(&memory);
let argv_buf_size = argv_buf_size.deref(&memory);
let argc_val: M::Offset = wasi_try!(state.args.len().try_into().map_err(|_| __WASI_EOVERFLOW));
let argv_buf_size_val: usize = state.args.iter().map(|v| v.len() + 1).sum();
let argv_buf_size_val: M::Offset =
wasi_try!(argv_buf_size_val.try_into().map_err(|_| __WASI_EOVERFLOW));
wasi_try_mem!(argc.write(argc_val));
wasi_try_mem!(argv_buf_size.write(argv_buf_size_val));
debug!("=> argc={}, argv_buf_size={}", argc_val, argv_buf_size_val);
__WASI_ESUCCESS
}
/// ### `clock_res_get()`
/// Get the resolution of the specified clock
/// Input:
/// - `__wasi_clockid_t clock_id`
/// The ID of the clock to get the resolution of
/// Output:
/// - `__wasi_timestamp_t *resolution`
/// The resolution of the clock in nanoseconds
pub fn clock_res_get<M: MemorySize>(
mut ctx: FunctionEnvMut<'_, WasiEnv>,
clock_id: __wasi_clockid_t,
resolution: WasmPtr<__wasi_timestamp_t, M>,
) -> __wasi_errno_t {
trace!("wasi::clock_res_get");
let env = ctx.data();
let memory = env.memory_view(&ctx);
let out_addr = resolution.deref(&memory);
let t_out = wasi_try!(platform_clock_res_get(clock_id, out_addr));
wasi_try_mem!(resolution.write(&memory, t_out as __wasi_timestamp_t));
__WASI_ESUCCESS
}
/// ### `clock_time_get()`
/// Get the time of the specified clock
/// Inputs:
/// - `__wasi_clockid_t clock_id`
/// The ID of the clock to query
/// - `__wasi_timestamp_t precision`
/// The maximum amount of error the reading may have
/// Output:
/// - `__wasi_timestamp_t *time`
/// The value of the clock in nanoseconds
pub fn clock_time_get<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
clock_id: __wasi_clockid_t,
precision: __wasi_timestamp_t,
time: WasmPtr<__wasi_timestamp_t, M>,
) -> __wasi_errno_t {
debug!(
"wasi::clock_time_get clock_id: {}, precision: {}",
clock_id, precision
);
let env = ctx.data();
let memory = env.memory_view(&ctx);
let t_out = wasi_try!(platform_clock_time_get(clock_id, precision));
wasi_try_mem!(time.write(&memory, t_out as __wasi_timestamp_t));
let result = __WASI_ESUCCESS;
trace!(
"time: {} => {}",
wasi_try_mem!(time.deref(&memory).read()),
result
);
result
}
/// ### `environ_get()`
/// Read environment variable data.
/// The sizes of the buffers should match that returned by [`environ_sizes_get()`](#environ_sizes_get).
/// Inputs:
/// - `char **environ`
/// A pointer to a buffer to write the environment variable pointers.
/// - `char *environ_buf`
/// A pointer to a buffer to write the environment variable string data.
pub fn environ_get<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
environ: WasmPtr<WasmPtr<u8, M>, M>,
environ_buf: WasmPtr<u8, M>,
) -> __wasi_errno_t {
debug!(
"wasi::environ_get. Environ: {:?}, environ_buf: {:?}",
environ, environ_buf
);
let env = ctx.data();
let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0);
trace!(" -> State envs: {:?}", state.envs);
write_buffer_array(&memory, &state.envs, environ, environ_buf)
}
/// ### `environ_sizes_get()`
/// Return command-line argument data sizes.
/// Outputs:
/// - `size_t *environ_count`
/// The number of environment variables.
/// - `size_t *environ_buf_size`
/// The size of the environment variable string data.
pub fn environ_sizes_get<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
environ_count: WasmPtr<M::Offset, M>,
environ_buf_size: WasmPtr<M::Offset, M>,
) -> __wasi_errno_t {
trace!("wasi::environ_sizes_get");
let env = ctx.data();
let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0);
let environ_count = environ_count.deref(&memory);
let environ_buf_size = environ_buf_size.deref(&memory);
let env_var_count: M::Offset =
wasi_try!(state.envs.len().try_into().map_err(|_| __WASI_EOVERFLOW));
let env_buf_size: usize = state.envs.iter().map(|v| v.len() + 1).sum();
let env_buf_size: M::Offset = wasi_try!(env_buf_size.try_into().map_err(|_| __WASI_EOVERFLOW));
wasi_try_mem!(environ_count.write(env_var_count));
wasi_try_mem!(environ_buf_size.write(env_buf_size));
trace!(
"env_var_count: {}, env_buf_size: {}",
env_var_count,
env_buf_size
);
__WASI_ESUCCESS
}
/// ### `fd_advise()`
/// Advise the system about how a file will be used
/// Inputs:
/// - `__wasi_fd_t fd`
/// The file descriptor the advice applies to
/// - `__wasi_filesize_t offset`
/// The offset from which the advice applies
/// - `__wasi_filesize_t len`
/// The length from the offset to which the advice applies
/// - `__wasi_advice_t advice`
/// The advice to give
pub fn fd_advise(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
offset: __wasi_filesize_t,
len: __wasi_filesize_t,
advice: __wasi_advice_t,
) -> __wasi_errno_t {
debug!("wasi::fd_advise: fd={}", fd);
// this is used for our own benefit, so just returning success is a valid
// implementation for now
__WASI_ESUCCESS
}
/// ### `fd_allocate`
/// Allocate extra space for a file descriptor
/// Inputs:
/// - `__wasi_fd_t fd`
/// The file descriptor to allocate for
/// - `__wasi_filesize_t offset`
/// The offset from the start marking the beginning of the allocation
/// - `__wasi_filesize_t len`
/// The length from the offset marking the end of the allocation
pub fn fd_allocate(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
offset: __wasi_filesize_t,
len: __wasi_filesize_t,
) -> __wasi_errno_t {
debug!("wasi::fd_allocate");
let env = ctx.data();
let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = wasi_try!(state.fs.get_fd(fd));
let inode = fd_entry.inode;
if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_ALLOCATE) {
return __WASI_EACCES;
}
let new_size = wasi_try!(offset.checked_add(len).ok_or(__WASI_EINVAL));
{
let mut guard = inodes.arena[inode].write();
let deref_mut = guard.deref_mut();
match deref_mut {
Kind::File { handle, .. } => {
if let Some(handle) = handle {
wasi_try!(handle.set_len(new_size).map_err(fs_error_into_wasi_err));
} else {
return __WASI_EBADF;
}
}
Kind::Socket { .. } => return __WASI_EBADF,
Kind::Pipe { .. } => return __WASI_EBADF,
Kind::Buffer { buffer } => {
buffer.resize(new_size as usize, 0);
}
Kind::Symlink { .. } => return __WASI_EBADF,
Kind::EventNotifications { .. } => return __WASI_EBADF,
Kind::Dir { .. } | Kind::Root { .. } => return __WASI_EISDIR,
}
}
inodes.arena[inode].stat.write().unwrap().st_size = new_size;
debug!("New file size: {}", new_size);
__WASI_ESUCCESS
}
/// ### `fd_close()`
/// Close an open file descriptor
/// Inputs:
/// - `__wasi_fd_t fd`
/// A file descriptor mapping to an open file to close
/// Errors:
/// - `__WASI_EISDIR`
/// If `fd` is a directory
/// - `__WASI_EBADF`
/// If `fd` is invalid or not open
pub fn fd_close(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t {
debug!("wasi::fd_close: fd={}", fd);
let env = ctx.data();
let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = wasi_try!(state.fs.get_fd(fd));
wasi_try!(state.fs.close_fd(inodes.deref(), fd));
__WASI_ESUCCESS
}
/// ### `fd_datasync()`
/// Synchronize the file data to disk
/// Inputs:
/// - `__wasi_fd_t fd`
/// The file descriptor to sync
pub fn fd_datasync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t {
debug!("wasi::fd_datasync");
let env = ctx.data();
let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = wasi_try!(state.fs.get_fd(fd));
if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_DATASYNC) {
return __WASI_EACCES;
}
if let Err(e) = state.fs.flush(inodes.deref(), fd) {
e
} else {
__WASI_ESUCCESS
}
}
/// ### `fd_fdstat_get()`
/// Get metadata of a file descriptor
/// Input:
/// - `__wasi_fd_t fd`
/// The file descriptor whose metadata will be accessed
/// Output:
/// - `__wasi_fdstat_t *buf`
/// The location where the metadata will be written
pub fn fd_fdstat_get<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
buf_ptr: WasmPtr<__wasi_fdstat_t, M>,
) -> __wasi_errno_t {
debug!(
"wasi::fd_fdstat_get: fd={}, buf_ptr={}",
fd,
buf_ptr.offset()
);
let env = ctx.data();
let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let stat = wasi_try!(state.fs.fdstat(inodes.deref(), fd));
let buf = buf_ptr.deref(&memory);
wasi_try_mem!(buf.write(stat));
__WASI_ESUCCESS
}
/// ### `fd_fdstat_set_flags()`
/// Set file descriptor flags for a file descriptor
/// Inputs:
/// - `__wasi_fd_t fd`
/// The file descriptor to apply the new flags to
/// - `__wasi_fdflags_t flags`
/// The flags to apply to `fd`
pub fn fd_fdstat_set_flags(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
flags: __wasi_fdflags_t,
) -> __wasi_errno_t {
debug!("wasi::fd_fdstat_set_flags");
let env = ctx.data();
let (_, mut state) = env.get_memory_and_wasi_state(&ctx, 0);
let mut fd_map = state.fs.fd_map.write().unwrap();
let fd_entry = wasi_try!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF));
if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FDSTAT_SET_FLAGS) {
return __WASI_EACCES;
}
fd_entry.flags = flags;
__WASI_ESUCCESS
}
/// ### `fd_fdstat_set_rights()`
/// Set the rights of a file descriptor. This can only be used to remove rights
/// Inputs:
/// - `__wasi_fd_t fd`
/// The file descriptor to apply the new rights to
/// - `__wasi_rights_t fs_rights_base`
/// The rights to apply to `fd`
/// - `__wasi_rights_t fs_rights_inheriting`
/// The inheriting rights to apply to `fd`
pub fn fd_fdstat_set_rights(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
fs_rights_base: __wasi_rights_t,
fs_rights_inheriting: __wasi_rights_t,
) -> __wasi_errno_t {
debug!("wasi::fd_fdstat_set_rights");
let env = ctx.data();
let (_, mut state) = env.get_memory_and_wasi_state(&ctx, 0);
let mut fd_map = state.fs.fd_map.write().unwrap();
let fd_entry = wasi_try!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF));
// ensure new rights are a subset of current rights
if fd_entry.rights | fs_rights_base != fd_entry.rights
|| fd_entry.rights_inheriting | fs_rights_inheriting != fd_entry.rights_inheriting
{
return __WASI_ENOTCAPABLE;
}
fd_entry.rights = fs_rights_base;
fd_entry.rights_inheriting = fs_rights_inheriting;
__WASI_ESUCCESS
}
/// ### `fd_filestat_get()`
/// Get the metadata of an open file
/// Input:
/// - `__wasi_fd_t fd`
/// The open file descriptor whose metadata will be read
/// Output:
/// - `__wasi_filestat_t *buf`
/// Where the metadata from `fd` will be written
pub fn fd_filestat_get<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
buf: WasmPtr<__wasi_filestat_t, M>,
) -> __wasi_errno_t {
debug!("wasi::fd_filestat_get");
let env = ctx.data();
let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = wasi_try!(state.fs.get_fd(fd));
if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FILESTAT_GET) {
return __WASI_EACCES;
}
let stat = wasi_try!(state.fs.filestat_fd(inodes.deref(), fd));
let buf = buf.deref(&memory);
wasi_try_mem!(buf.write(stat));
__WASI_ESUCCESS
}
/// ### `fd_filestat_set_size()`
/// Change the size of an open file, zeroing out any new bytes
/// Inputs:
/// - `__wasi_fd_t fd`
/// File descriptor to adjust
/// - `__wasi_filesize_t st_size`
/// New size that `fd` will be set to
pub fn fd_filestat_set_size(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
st_size: __wasi_filesize_t,
) -> __wasi_errno_t {
debug!("wasi::fd_filestat_set_size");
let env = ctx.data();
let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = wasi_try!(state.fs.get_fd(fd));
let inode = fd_entry.inode;
if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FILESTAT_SET_SIZE) {
return __WASI_EACCES;
}
{
let mut guard = inodes.arena[inode].write();
let deref_mut = guard.deref_mut();
match deref_mut {
Kind::File { handle, .. } => {
if let Some(handle) = handle {
wasi_try!(handle.set_len(st_size).map_err(fs_error_into_wasi_err));
} else {
return __WASI_EBADF;
}
}
Kind::Buffer { buffer } => {
buffer.resize(st_size as usize, 0);
}
Kind::Socket { .. } => return __WASI_EBADF,
Kind::Pipe { .. } => return __WASI_EBADF,
Kind::Symlink { .. } => return __WASI_EBADF,
Kind::EventNotifications { .. } => return __WASI_EBADF,
Kind::Dir { .. } | Kind::Root { .. } => return __WASI_EISDIR,
}
}
inodes.arena[inode].stat.write().unwrap().st_size = st_size;
__WASI_ESUCCESS
}
/// ### `fd_filestat_set_times()`
/// Set timestamp metadata on a file
/// Inputs:
/// - `__wasi_timestamp_t st_atim`
/// Last accessed time
/// - `__wasi_timestamp_t st_mtim`
/// Last modified time
/// - `__wasi_fstflags_t fst_flags`
/// Bit-vector for controlling which times get set
pub fn fd_filestat_set_times(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
st_atim: __wasi_timestamp_t,
st_mtim: __wasi_timestamp_t,
fst_flags: __wasi_fstflags_t,
) -> __wasi_errno_t {
debug!("wasi::fd_filestat_set_times");
let env = ctx.data();
let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let fd_entry = wasi_try!(state.fs.get_fd(fd));
if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FILESTAT_SET_TIMES) {
return __WASI_EACCES;
}
if (fst_flags & __WASI_FILESTAT_SET_ATIM != 0 && fst_flags & __WASI_FILESTAT_SET_ATIM_NOW != 0)
|| (fst_flags & __WASI_FILESTAT_SET_MTIM != 0
&& fst_flags & __WASI_FILESTAT_SET_MTIM_NOW != 0)
{
return __WASI_EINVAL;
}
let inode_idx = fd_entry.inode;
let inode = &inodes.arena[inode_idx];
if fst_flags & __WASI_FILESTAT_SET_ATIM != 0 || fst_flags & __WASI_FILESTAT_SET_ATIM_NOW != 0 {
let time_to_set = if fst_flags & __WASI_FILESTAT_SET_ATIM != 0 {
st_atim
} else {
wasi_try!(get_current_time_in_nanos())
};
inode.stat.write().unwrap().st_atim = time_to_set;
}
if fst_flags & __WASI_FILESTAT_SET_MTIM != 0 || fst_flags & __WASI_FILESTAT_SET_MTIM_NOW != 0 {
let time_to_set = if fst_flags & __WASI_FILESTAT_SET_MTIM != 0 {
st_mtim
} else {
wasi_try!(get_current_time_in_nanos())
};
inode.stat.write().unwrap().st_mtim = time_to_set;
}
__WASI_ESUCCESS
}
/// ### `fd_pread()`
/// Read from the file at the given offset without updating the file cursor.
/// This acts like a stateless version of Seek + Read
/// Inputs:
/// - `__wasi_fd_t fd`
/// The file descriptor to read the data with
/// - `const __wasi_iovec_t* iovs'
/// Vectors where the data will be stored
/// - `size_t iovs_len`
/// The number of vectors to store the data into
/// - `__wasi_filesize_t offset`
/// The file cursor to use: the starting position from which data will be read
/// Output:
/// - `size_t nread`
/// The number of bytes read
pub fn fd_pread<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
iovs: WasmPtr<__wasi_iovec_t<M>, M>,
iovs_len: M::Offset,
offset: __wasi_filesize_t,
nread: WasmPtr<M::Offset, M>,
) -> Result<__wasi_errno_t, WasiError> {
trace!("wasi::fd_pread: fd={}, offset={}", fd, offset);
let env = ctx.data();
let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let iovs = wasi_try_mem_ok!(iovs.slice(&memory, iovs_len));
let nread_ref = nread.deref(&memory);
let fd_entry = wasi_try_ok!(state.fs.get_fd(fd));
let bytes_read = match fd {
__WASI_STDIN_FILENO => {
let mut guard = wasi_try_ok!(
inodes
.stdin_mut(&state.fs.fd_map)
.map_err(fs_error_into_wasi_err),
env
);
if let Some(ref mut stdin) = guard.deref_mut() {
wasi_try_ok!(read_bytes(stdin, &memory, iovs), env)
} else {
return Ok(__WASI_EBADF);
}
}
__WASI_STDOUT_FILENO => return Ok(__WASI_EINVAL),
__WASI_STDERR_FILENO => return Ok(__WASI_EINVAL),
_ => {
let inode = fd_entry.inode;
if !(has_rights(fd_entry.rights, __WASI_RIGHT_FD_READ)
&& has_rights(fd_entry.rights, __WASI_RIGHT_FD_SEEK))
{
debug!(
"Invalid rights on {:X}: expected READ and SEEK",
fd_entry.rights
);
return Ok(__WASI_EACCES);
}
let mut guard = inodes.arena[inode].write();
let deref_mut = guard.deref_mut();
match deref_mut {
Kind::File { handle, .. } => {
if let Some(h) = handle {
wasi_try_ok!(
h.seek(std::io::SeekFrom::Start(offset as u64))
.map_err(map_io_err),
env
);
wasi_try_ok!(read_bytes(h, &memory, iovs), env)
} else {
return Ok(__WASI_EINVAL);
}
}
Kind::Socket { socket } => {
wasi_try_ok!(socket.recv(&memory, iovs), env)
}
Kind::Pipe { pipe } => {
wasi_try_ok!(pipe.recv(&memory, iovs), env)
}
Kind::EventNotifications { .. } => return Ok(__WASI_EINVAL),
Kind::Dir { .. } | Kind::Root { .. } => return Ok(__WASI_EISDIR),
Kind::Symlink { .. } => unimplemented!("Symlinks in wasi::fd_pread"),
Kind::Buffer { buffer } => {
wasi_try_ok!(read_bytes(&buffer[(offset as usize)..], &memory, iovs), env)
}
}
}
};
let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| __WASI_EOVERFLOW));
wasi_try_mem_ok!(nread_ref.write(bytes_read));
debug!("Success: {} bytes read", bytes_read);
Ok(__WASI_ESUCCESS)
}
/// ### `fd_prestat_get()`
/// Get metadata about a preopened file descriptor
/// Input:
/// - `__wasi_fd_t fd`
/// The preopened file descriptor to query
/// Output:
/// - `__wasi_prestat *buf`
/// Where the metadata will be written
pub fn fd_prestat_get<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
buf: WasmPtr<__wasi_prestat_t, M>,
) -> __wasi_errno_t {
trace!("wasi::fd_prestat_get: fd={}", fd);
let env = ctx.data();
let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let prestat_ptr = buf.deref(&memory);
wasi_try_mem!(
prestat_ptr.write(wasi_try!(state.fs.prestat_fd(inodes.deref(), fd).map_err(
|code| {
debug!("fd_prestat_get failed (fd={}) - errno={}", fd, code);
code
}
)))
);
__WASI_ESUCCESS
}
pub fn fd_prestat_dir_name<M: MemorySize>(
ctx: FunctionEnvMut<'_, WasiEnv>,
fd: __wasi_fd_t,
path: WasmPtr<u8, M>,
path_len: M::Offset,
) -> __wasi_errno_t {
trace!(
"wasi::fd_prestat_dir_name: fd={}, path_len={}",
fd,
path_len
);
let env = ctx.data();
let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0);
let path_chars = wasi_try_mem!(path.slice(&memory, path_len));
let real_inode = wasi_try!(state.fs.get_fd_inode(fd));
let inode_val = &inodes.arena[real_inode];
// check inode-val.is_preopened?
trace!("=> inode: {:?}", inode_val);
let guard = inode_val.read();
let deref = guard.deref();
match deref {
Kind::Dir { .. } | Kind::Root { .. } => {
// TODO: verify this: null termination, etc
let path_len: u64 = path_len.into();
if (inode_val.name.len() as u64) < path_len {
wasi_try_mem!(path_chars
.subslice(0..inode_val.name.len() as u64)
.write_slice(inode_val.name.as_bytes()));
wasi_try_mem!(path_chars.index(inode_val.name.len() as u64).write(0));
trace!("=> result: \"{}\"", inode_val.name);
__WASI_ESUCCESS
} else {
__WASI_EOVERFLOW
}
}
Kind::Symlink { .. }
| Kind::Buffer { .. }
| Kind::File { .. }
| Kind::Socket { .. }
| Kind::Pipe { .. }
| Kind::EventNotifications { .. } => __WASI_ENOTDIR,
}
}
/// ### `fd_pwrite()`
/// Write to a file without adjusting its offset
/// Inputs:
/// - `__wasi_fd_t`
/// File descriptor (opened with writing) to write to
/// - `const __wasi_ciovec_t *iovs`
/// List of vectors to read data from
/// - `u32 iovs_len`