diff options
| author | Henry <mail@henrygressmann.de> | 2026-09-15 15:23:11 +0200 |
|---|---|---|
| committer | Henry <mail@henrygressmann.de> | 2026-09-15 15:27:00 +0200 |
| commit | dc8e5732d71b6f66e730b090ab02bdccc69ec888 (patch) | |
| tree | 1c48f5b6d785517fbccf7fb62806bb3ec6c22b2d /crates/wasi | |
| parent | 741955aed21c814a0805386a4f9be997c2eb1199 (diff) | |
feat: initial wasi p1 implementation
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/wasi')
| -rw-r--r-- | crates/wasi/Cargo.toml | 25 | ||||
| -rw-r--r-- | crates/wasi/README.md | 10 | ||||
| -rw-r--r-- | crates/wasi/src/lib.rs | 4 | ||||
| -rw-r--r-- | crates/wasi/src/p1/abi.rs | 300 | ||||
| -rw-r--r-- | crates/wasi/src/p1/ctx.rs | 293 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/clock.rs | 28 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/command.rs | 72 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/fd.rs | 423 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/mod.rs | 101 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/path.rs | 258 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/poll.rs | 219 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/process.rs | 20 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/random.rs | 25 | ||||
| -rw-r--r-- | crates/wasi/src/p1/imports/sock.rs | 124 | ||||
| -rw-r--r-- | crates/wasi/src/p1/memory.rs | 115 | ||||
| -rw-r--r-- | crates/wasi/src/p1/mod.rs | 22 | ||||
| -rw-r--r-- | crates/wasi/tests/p1.rs | 357 |
17 files changed, 2396 insertions, 0 deletions
diff --git a/crates/wasi/Cargo.toml b/crates/wasi/Cargo.toml new file mode 100644 index 0000000..e4d0ef0 --- /dev/null +++ b/crates/wasi/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "tinywasm-wasi" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +description = "WASI support for TinyWasm" +repository.workspace = true +license.workspace = true +keywords = ["tinywasm", "wasi", "wasm", "webassembly"] +categories = ["wasm"] +publish = false + +[dependencies] +cap-fs-ext = "4.0.3" +cap-std = "4.0.3" +getrandom = "0.4.3" +rustix = { version = "1.1.4", features = ["event", "fs", "net"] } +tinywasm = { workspace = true, default-features = false, features = ["state"] } + +[dev-dependencies] +tinywasm = { workspace = true, features = ["parser", "state"] } +wat.workspace = true + +[lints] +workspace = true diff --git a/crates/wasi/README.md b/crates/wasi/README.md new file mode 100644 index 0000000..1c173aa --- /dev/null +++ b/crates/wasi/README.md @@ -0,0 +1,10 @@ +# tinywasm-wasi + +Experimental WASI support for TinyWasm mainly targeting \*nix systems (Windows support is very limited). Currently unreleased. + +Some behavior is based on the Bytecode Alliance `wasi-common` and +`wasmtime-wasi` implementations. + +## Future WASI support + +Preview 2 and 3 are not planned for TinyWasm, we're probably going to wait for the final WASI 1.0 release and implement that instead. diff --git a/crates/wasi/src/lib.rs b/crates/wasi/src/lib.rs new file mode 100644 index 0000000..ef47a4d --- /dev/null +++ b/crates/wasi/src/lib.rs @@ -0,0 +1,4 @@ +//! WASI support for TinyWasm. + +/// WASI Preview 1 +pub mod p1; diff --git a/crates/wasi/src/p1/abi.rs b/crates/wasi/src/p1/abi.rs new file mode 100644 index 0000000..c331a6b --- /dev/null +++ b/crates/wasi/src/p1/abi.rs @@ -0,0 +1,300 @@ +use std::ffi::OsStr; +use std::io; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use cap_fs_ext::{MetadataExt, SystemTimeSpec}; +use cap_std::fs::Metadata; + +#[derive(Clone, Copy)] +pub(super) struct Errno(u16); + +impl From<Errno> for i32 { + fn from(errno: Errno) -> Self { + i32::from(errno.0) + } +} + +pub(super) const SUCCESS: Errno = Errno(0); +pub(super) const ACCESS: Errno = Errno(2); +pub(super) const ADDRINUSE: Errno = Errno(3); +pub(super) const ADDRNOTAVAIL: Errno = Errno(4); +pub(super) const AGAIN: Errno = Errno(6); +pub(super) const BADF: Errno = Errno(8); +pub(super) const CONNABORTED: Errno = Errno(13); +pub(super) const CONNREFUSED: Errno = Errno(14); +pub(super) const CONNRESET: Errno = Errno(15); +pub(super) const EXIST: Errno = Errno(20); +pub(super) const FAULT: Errno = Errno(21); +pub(super) const FBIG: Errno = Errno(22); +pub(super) const ILSEQ: Errno = Errno(25); +pub(super) const INTR: Errno = Errno(27); +pub(super) const INVAL: Errno = Errno(28); +pub(super) const IO: Errno = Errno(29); +pub(super) const ISDIR: Errno = Errno(31); +pub(super) const LOOP: Errno = Errno(32); +pub(super) const MFILE: Errno = Errno(33); +pub(super) const MLINK: Errno = Errno(34); +pub(super) const NAMETOOLONG: Errno = Errno(37); +pub(super) const NOMEM: Errno = Errno(48); +pub(super) const NOENT: Errno = Errno(44); +pub(super) const NOSPC: Errno = Errno(51); +pub(super) const NOTCONN: Errno = Errno(53); +pub(super) const NOTDIR: Errno = Errno(54); +pub(super) const NOTEMPTY: Errno = Errno(55); +pub(super) const NOTSOCK: Errno = Errno(57); +pub(super) const NOTSUP: Errno = Errno(58); +pub(super) const OVERFLOW: Errno = Errno(61); +pub(super) const PIPE: Errno = Errno(64); +pub(super) const ROFS: Errno = Errno(69); +pub(super) const SPIPE: Errno = Errno(70); +pub(super) const TIMEDOUT: Errno = Errno(73); +pub(super) const XDEV: Errno = Errno(75); +pub(super) const NOTCAPABLE: Errno = Errno(76); + +pub(super) const FILETYPE_UNKNOWN: u8 = 0; +pub(super) const FILETYPE_BLOCK_DEVICE: u8 = 1; +pub(super) const FILETYPE_CHARACTER_DEVICE: u8 = 2; +pub(super) const FILETYPE_DIRECTORY: u8 = 3; +pub(super) const FILETYPE_REGULAR_FILE: u8 = 4; +pub(super) const FILETYPE_SOCKET_DGRAM: u8 = 5; +pub(super) const FILETYPE_SOCKET_STREAM: u8 = 6; +pub(super) const FILETYPE_SYMBOLIC_LINK: u8 = 7; + +pub(super) const FDFLAG_APPEND: u16 = 1; +pub(super) const FDFLAG_DSYNC: u16 = 2; +pub(super) const FDFLAG_NONBLOCK: u16 = 4; +pub(super) const FDFLAG_RSYNC: u16 = 8; +pub(super) const FDFLAG_SYNC: u16 = 16; +pub(super) const FDFLAGS_ALL: u16 = 31; + +pub(super) const OFLAG_CREAT: u16 = 1; +pub(super) const OFLAG_DIRECTORY: u16 = 2; +pub(super) const OFLAG_EXCL: u16 = 4; +pub(super) const OFLAG_TRUNC: u16 = 8; +pub(super) const OFLAGS_ALL: u16 = 15; +pub(super) const LOOKUP_SYMLINK_FOLLOW: u32 = 1; + +pub(super) const RIGHT_FD_DATASYNC: u64 = 1 << 0; +pub(super) const RIGHT_FD_READ: u64 = 1 << 1; +pub(super) const RIGHT_FD_SEEK: u64 = 1 << 2; +pub(super) const RIGHT_FD_FDSTAT_SET_FLAGS: u64 = 1 << 3; +pub(super) const RIGHT_FD_SYNC: u64 = 1 << 4; +pub(super) const RIGHT_FD_TELL: u64 = 1 << 5; +pub(super) const RIGHT_FD_WRITE: u64 = 1 << 6; +pub(super) const RIGHT_FD_ADVISE: u64 = 1 << 7; +pub(super) const RIGHT_FD_ALLOCATE: u64 = 1 << 8; +pub(super) const RIGHT_PATH_CREATE_DIRECTORY: u64 = 1 << 9; +pub(super) const RIGHT_PATH_CREATE_FILE: u64 = 1 << 10; +pub(super) const RIGHT_PATH_LINK_SOURCE: u64 = 1 << 11; +pub(super) const RIGHT_PATH_LINK_TARGET: u64 = 1 << 12; +pub(super) const RIGHT_PATH_OPEN: u64 = 1 << 13; +pub(super) const RIGHT_FD_READDIR: u64 = 1 << 14; +pub(super) const RIGHT_PATH_READLINK: u64 = 1 << 15; +pub(super) const RIGHT_PATH_RENAME_SOURCE: u64 = 1 << 16; +pub(super) const RIGHT_PATH_RENAME_TARGET: u64 = 1 << 17; +pub(super) const RIGHT_PATH_FILESTAT_GET: u64 = 1 << 18; +pub(super) const RIGHT_PATH_FILESTAT_SET_SIZE: u64 = 1 << 19; +pub(super) const RIGHT_PATH_FILESTAT_SET_TIMES: u64 = 1 << 20; +pub(super) const RIGHT_FD_FILESTAT_GET: u64 = 1 << 21; +pub(super) const RIGHT_FD_FILESTAT_SET_SIZE: u64 = 1 << 22; +pub(super) const RIGHT_FD_FILESTAT_SET_TIMES: u64 = 1 << 23; +pub(super) const RIGHT_PATH_SYMLINK: u64 = 1 << 24; +pub(super) const RIGHT_PATH_REMOVE_DIRECTORY: u64 = 1 << 25; +pub(super) const RIGHT_PATH_UNLINK_FILE: u64 = 1 << 26; +pub(super) const RIGHT_POLL_FD_READWRITE: u64 = 1 << 27; +pub(super) const RIGHT_SOCK_SHUTDOWN: u64 = 1 << 28; +pub(super) const RIGHT_SOCK_ACCEPT: u64 = 1 << 29; +pub(super) const FILE_RIGHTS: u64 = RIGHT_FD_DATASYNC + | RIGHT_FD_READ + | RIGHT_FD_SEEK + | RIGHT_FD_FDSTAT_SET_FLAGS + | RIGHT_FD_SYNC + | RIGHT_FD_TELL + | RIGHT_FD_WRITE + | RIGHT_FD_ADVISE + | RIGHT_FD_ALLOCATE + | RIGHT_FD_FILESTAT_GET + | RIGHT_FD_FILESTAT_SET_SIZE + | RIGHT_FD_FILESTAT_SET_TIMES + | RIGHT_POLL_FD_READWRITE; +pub(super) const DIRECTORY_RIGHTS: u64 = RIGHT_PATH_CREATE_DIRECTORY + | RIGHT_PATH_CREATE_FILE + | RIGHT_PATH_LINK_SOURCE + | RIGHT_PATH_LINK_TARGET + | RIGHT_PATH_OPEN + | RIGHT_FD_READDIR + | RIGHT_PATH_READLINK + | RIGHT_PATH_RENAME_SOURCE + | RIGHT_PATH_RENAME_TARGET + | RIGHT_PATH_FILESTAT_GET + | RIGHT_PATH_FILESTAT_SET_SIZE + | RIGHT_PATH_FILESTAT_SET_TIMES + | RIGHT_FD_FILESTAT_GET + | RIGHT_FD_FILESTAT_SET_TIMES + | RIGHT_PATH_SYMLINK + | RIGHT_PATH_REMOVE_DIRECTORY + | RIGHT_PATH_UNLINK_FILE; + +pub(super) const FSTFLAG_ATIM: u16 = 1; +pub(super) const FSTFLAG_ATIM_NOW: u16 = 2; +pub(super) const FSTFLAG_MTIM: u16 = 4; +pub(super) const FSTFLAG_MTIM_NOW: u16 = 8; +pub(super) const FSTFLAGS_ALL: u16 = 15; + +pub(super) fn io_errno(error: &io::Error) -> Errno { + use io::ErrorKind; + match error.kind() { + ErrorKind::NotFound => NOENT, + ErrorKind::PermissionDenied => ACCESS, + ErrorKind::AddrInUse => ADDRINUSE, + ErrorKind::AddrNotAvailable => ADDRNOTAVAIL, + ErrorKind::AlreadyExists => EXIST, + ErrorKind::ConnectionAborted => CONNABORTED, + ErrorKind::ConnectionRefused => CONNREFUSED, + ErrorKind::ConnectionReset => CONNRESET, + ErrorKind::InvalidInput | ErrorKind::InvalidData => INVAL, + ErrorKind::WouldBlock => AGAIN, + ErrorKind::WriteZero | ErrorKind::UnexpectedEof => IO, + ErrorKind::BrokenPipe => PIPE, + ErrorKind::StorageFull => NOSPC, + ErrorKind::NotADirectory => NOTDIR, + ErrorKind::NotConnected => NOTCONN, + ErrorKind::IsADirectory => ISDIR, + ErrorKind::DirectoryNotEmpty => NOTEMPTY, + ErrorKind::FileTooLarge => FBIG, + ErrorKind::CrossesDevices => XDEV, + ErrorKind::Interrupted => INTR, + ErrorKind::OutOfMemory => NOMEM, + ErrorKind::ReadOnlyFilesystem => ROFS, + ErrorKind::TooManyLinks => MLINK, + ErrorKind::TimedOut => TIMEDOUT, + ErrorKind::Unsupported => NOTSUP, + _ => platform_io_errno(error), + } +} + +#[cfg(any(target_os = "android", target_os = "linux"))] +fn platform_io_errno(error: &io::Error) -> Errno { + match error.raw_os_error() { + Some(36) => NAMETOOLONG, + Some(40) => LOOP, + _ => IO, + } +} + +#[cfg(not(any(target_os = "android", target_os = "linux")))] +fn platform_io_errno(_error: &io::Error) -> Errno { + IO +} + +impl From<rustix::io::Errno> for Errno { + fn from(error: rustix::io::Errno) -> Self { + use rustix::io::Errno as E; + match error { + E::INTR => INTR, + E::ACCESS | E::PERM => ACCESS, + E::BADF => BADF, + E::INVAL => INVAL, + E::MFILE => MFILE, + E::NOMEM => NOMEM, + E::NOSPC => NOSPC, + E::NOSYS | E::NOTSUP => NOTSUP, + E::XDEV => XDEV, + E::LOOP => LOOP, + _ => io_errno(&io::Error::from(error)), + } + } +} + +pub(super) fn path_errno(error: &io::Error) -> Errno { + if error.kind() == io::ErrorKind::PermissionDenied { NOTCAPABLE } else { io_errno(error) } +} + +pub(super) fn file_type(metadata: &Metadata) -> u8 { + use cap_fs_ext::FileTypeExt; + + let ty = metadata.file_type(); + if ty.is_dir() { + FILETYPE_DIRECTORY + } else if ty.is_file() { + FILETYPE_REGULAR_FILE + } else if ty.is_symlink() { + FILETYPE_SYMBOLIC_LINK + } else if ty.is_block_device() { + FILETYPE_BLOCK_DEVICE + } else if ty.is_char_device() { + FILETYPE_CHARACTER_DEVICE + } else if ty.is_socket() { + FILETYPE_SOCKET_STREAM + } else { + FILETYPE_UNKNOWN + } +} + +fn timestamp(time: io::Result<cap_std::time::SystemTime>) -> u64 { + time.ok() + .and_then(|time| time.into_std().duration_since(UNIX_EPOCH).ok()) + .and_then(|duration| u64::try_from(duration.as_nanos()).ok()) + .unwrap_or(0) +} + +pub(super) fn realtime_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|duration| u64::try_from(duration.as_nanos()).ok()) + .unwrap_or(0) +} + +pub(super) fn filestat(metadata: &Metadata) -> [u8; 64] { + let mut bytes = [0; 64]; + put(&mut bytes, 0, metadata.dev().to_le_bytes()); + put(&mut bytes, 8, metadata.ino().to_le_bytes()); + bytes[16] = file_type(metadata); + put(&mut bytes, 24, metadata.nlink().to_le_bytes()); + put(&mut bytes, 32, metadata.len().to_le_bytes()); + put(&mut bytes, 40, timestamp(metadata.accessed()).to_le_bytes()); + put(&mut bytes, 48, timestamp(metadata.modified()).to_le_bytes()); + put(&mut bytes, 56, status_change_timestamp(metadata).to_le_bytes()); + bytes +} + +fn status_change_timestamp(metadata: &Metadata) -> u64 { + #[cfg(unix)] + { + let seconds = cap_std::fs::MetadataExt::ctime(metadata); + let nanoseconds = cap_std::fs::MetadataExt::ctime_nsec(metadata); + if seconds < 0 || nanoseconds < 0 { + return 0; + } + (seconds as u64).saturating_mul(1_000_000_000).saturating_add(nanoseconds as u64) + } + #[cfg(not(unix))] + timestamp(metadata.created()) +} + +pub(super) fn time_spec(flags: u16, explicit: u16, now: u16, timestamp: u64) -> Option<SystemTimeSpec> { + if flags & now != 0 { + Some(SystemTimeSpec::SymbolicNow) + } else if flags & explicit != 0 { + Some(SystemTimeSpec::Absolute(cap_std::time::SystemTime::from_std( + UNIX_EPOCH + Duration::from_nanos(timestamp), + ))) + } else { + None + } +} + +pub(super) fn os_bytes(value: &OsStr) -> Vec<u8> { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + value.as_bytes().to_vec() + } + #[cfg(not(unix))] + value.to_string_lossy().into_owned().into_bytes() +} + +pub(super) fn put<const N: usize>(buffer: &mut [u8], offset: usize, bytes: [u8; N]) { + buffer[offset..offset + N].copy_from_slice(&bytes); +} diff --git a/crates/wasi/src/p1/ctx.rs b/crates/wasi/src/p1/ctx.rs new file mode 100644 index 0000000..e7b8652 --- /dev/null +++ b/crates/wasi/src/p1/ctx.rs @@ -0,0 +1,293 @@ +use std::fmt::{Display, Formatter}; +use std::net::{TcpListener, TcpStream, UdpSocket}; +use std::path::Path; + +use cap_std::ambient_authority; +use cap_std::fs::{Dir, File}; +use tinywasm::{Error, FuncContext}; + +use super::abi::*; + +pub(super) const MAX_DESCRIPTORS: usize = 4096; +const SOCKET_RIGHTS: u64 = RIGHT_FD_READ + | RIGHT_FD_WRITE + | RIGHT_FD_FDSTAT_SET_FLAGS + | RIGHT_FD_FILESTAT_GET + | RIGHT_POLL_FD_READWRITE + | RIGHT_SOCK_SHUTDOWN; + +pub(super) enum Resource { + Stdin, + Stdout, + Stderr, + File(File), + Directory(Dir), + TcpListener(TcpListener), + TcpStream(TcpStream), + UdpSocket(UdpSocket), +} + +pub(super) struct Descriptor { + pub(super) resource: Resource, + pub(super) rights: u64, + pub(super) inheriting_rights: u64, + pub(super) flags: u16, + pub(super) preopen_path: Option<Vec<u8>>, +} + +impl Descriptor { + pub(super) fn file_type(&self) -> u8 { + match &self.resource { + Resource::Stdin | Resource::Stdout | Resource::Stderr => FILETYPE_CHARACTER_DEVICE, + Resource::File(_) => FILETYPE_REGULAR_FILE, + Resource::Directory(_) => FILETYPE_DIRECTORY, + Resource::TcpListener(_) | Resource::TcpStream(_) => FILETYPE_SOCKET_STREAM, + Resource::UdpSocket(_) => FILETYPE_SOCKET_DGRAM, + } + } + + pub(super) fn require_rights(&self, rights: u64) -> Result<(), Errno> { + if self.rights & rights == rights { Ok(()) } else { Err(super::abi::NOTCAPABLE) } + } +} + +/// Configures the host resources available to a WASI Preview 1 command. +pub struct WasiCtx { + pub(super) args: Vec<Vec<u8>>, + pub(super) env: Vec<Vec<u8>>, + pub(super) descriptors: Vec<Option<Descriptor>>, + pub(super) exit_status: Option<u32>, + pub(super) monotonic_start: std::time::Instant, +} + +impl Default for WasiCtx { + fn default() -> Self { + Self { + args: Vec::new(), + env: Vec::new(), + descriptors: vec![None, None, None], + exit_status: None, + monotonic_start: std::time::Instant::now(), + } + } +} + +impl WasiCtx { + /// Creates an empty context without access to host standard I/O or files. + pub fn new() -> Self { + Self::default() + } + + /// Sets UTF-8 command-line arguments visible to the guest. + pub fn with_args(self, args: impl IntoIterator<Item = impl Into<String>>) -> Result<Self, WasiCtxError> { + self.with_args_bytes(args.into_iter().map(|value| value.into().into_bytes())) + } + + /// Sets byte command-line arguments visible to the guest. + pub fn with_args_bytes(mut self, args: impl IntoIterator<Item = impl Into<Vec<u8>>>) -> Result<Self, WasiCtxError> { + self.args = args.into_iter().map(|value| validate_bytes(value.into())).collect::<Result<_, _>>()?; + Ok(self) + } + + /// Sets UTF-8 environment variables visible to the guest. + pub fn with_env( + self, + env: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>, + ) -> Result<Self, WasiCtxError> { + self.with_env_bytes(env.into_iter().map(|(key, value)| (key.into().into_bytes(), value.into().into_bytes()))) + } + + /// Sets byte environment variables visible to the guest. + pub fn with_env_bytes( + mut self, + env: impl IntoIterator<Item = (impl Into<Vec<u8>>, impl Into<Vec<u8>>)>, + ) -> Result<Self, WasiCtxError> { + self.env = env + .into_iter() + .map(|(key, value)| { + let mut entry = key.into(); + entry.push(b'='); + entry.extend(value.into()); + validate_bytes(entry) + }) + .collect::<Result<_, _>>()?; + Ok(self) + } + + /// Allows the guest to read inherited standard input. + pub fn inherit_stdin(self) -> Self { + self.inherit_fd(0, Resource::Stdin, RIGHT_FD_READ) + } + + /// Allows the guest to write inherited standard output. + pub fn inherit_stdout(self) -> Self { + self.inherit_fd(1, Resource::Stdout, RIGHT_FD_WRITE) + } + + /// Allows the guest to write inherited standard error. + pub fn inherit_stderr(self) -> Self { + self.inherit_fd(2, Resource::Stderr, RIGHT_FD_WRITE) + } + + /// Allows the guest to use inherited standard input, output, and error. + pub fn inherit_stdio(self) -> Self { + self.inherit_stdin().inherit_stdout().inherit_stderr() + } + + /// Adds a capability directory and returns it as a guest preopen at fd 3 or above. + pub fn preopen_dir( + mut self, + host_path: impl AsRef<Path>, + guest_path: impl AsRef<[u8]>, + ) -> Result<Self, WasiCtxError> { + let guest_path = validate_bytes(guest_path.as_ref().to_vec())?; + if guest_path.is_empty() { + return Err(WasiCtxError::InvalidPreopenPath); + } + let dir = Dir::open_ambient_dir(host_path, ambient_authority()).map_err(WasiCtxError::Io)?; + self.insert_descriptor(Descriptor { + resource: Resource::Directory(dir), + rights: DIRECTORY_RIGHTS, + inheriting_rights: DIRECTORY_RIGHTS | FILE_RIGHTS, + flags: 0, + preopen_path: Some(guest_path), + }) + .map_err(|_| WasiCtxError::TooManyDescriptors)?; + Ok(self) + } + + /// Inserts a TCP listener capability and returns its guest file descriptor. + pub fn insert_tcp_listener(&mut self, listener: TcpListener) -> Result<u32, WasiCtxError> { + listener.set_nonblocking(false).map_err(WasiCtxError::Io)?; + self.insert_descriptor(Descriptor { + resource: Resource::TcpListener(listener), + rights: RIGHT_FD_READ + | RIGHT_FD_FDSTAT_SET_FLAGS + | RIGHT_FD_FILESTAT_GET + | RIGHT_POLL_FD_READWRITE + | RIGHT_SOCK_ACCEPT, + inheriting_rights: SOCKET_RIGHTS, + flags: 0, + preopen_path: None, + }) + .map_err(|_| WasiCtxError::TooManyDescriptors) + } + + /// Inserts a connected TCP stream capability and returns its guest file descriptor. + pub fn insert_tcp_stream(&mut self, stream: TcpStream) -> Result<u32, WasiCtxError> { + self.insert_socket(Resource::TcpStream(stream)) + } + + /// Inserts a UDP socket capability and returns its guest file descriptor. + /// + /// `sock_send` requires the supplied socket to be connected. Receiving is + /// supported for connected and unconnected sockets. + pub fn insert_udp_socket(&mut self, socket: UdpSocket) -> Result<u32, WasiCtxError> { + self.insert_socket(Resource::UdpSocket(socket)) + } + + /// Returns the status supplied to `proc_exit`, if it was called. + pub fn exit_status(&self) -> Option<u32> { + self.exit_status + } + + /// Takes and clears the status supplied to `proc_exit`. + pub fn take_exit_status(&mut self) -> Option<u32> { + self.exit_status.take() + } + + pub(super) fn descriptor(&self, fd: i32) -> Result<&Descriptor, Errno> { + self.descriptors.get(fd as u32 as usize).and_then(Option::as_ref).ok_or(super::abi::BADF) + } + + pub(super) fn descriptor_mut(&mut self, fd: i32) -> Result<&mut Descriptor, Errno> { + self.descriptors.get_mut(fd as u32 as usize).and_then(Option::as_mut).ok_or(super::abi::BADF) + } + + pub(super) fn insert_descriptor(&mut self, descriptor: Descriptor) -> Result<u32, Errno> { + if let Some((index, slot)) = self.descriptors.iter_mut().enumerate().skip(3).find(|(_, slot)| slot.is_none()) { + *slot = Some(descriptor); + Ok(index as u32) + } else { + if self.descriptors.len() >= MAX_DESCRIPTORS { + return Err(super::abi::MFILE); + } + let fd = self.descriptors.len() as u32; + self.descriptors.push(Some(descriptor)); + Ok(fd) + } + } + + fn inherit_fd(mut self, fd: usize, resource: Resource, rights: u64) -> Self { + self.descriptors[fd] = Some(Descriptor { + resource, + rights: rights | RIGHT_FD_FILESTAT_GET | RIGHT_POLL_FD_READWRITE, + inheriting_rights: 0, + flags: 0, + preopen_path: None, + }); + self + } + + fn insert_socket(&mut self, resource: Resource) -> Result<u32, WasiCtxError> { + match &resource { + Resource::TcpStream(stream) => stream.set_nonblocking(false), + Resource::UdpSocket(socket) => socket.set_nonblocking(false), + _ => unreachable!(), + } + .map_err(WasiCtxError::Io)?; + self.insert_descriptor(Descriptor { + resource, + rights: SOCKET_RIGHTS, + inheriting_rights: 0, + flags: 0, + preopen_path: None, + }) + .map_err(|_| WasiCtxError::TooManyDescriptors) + } +} + +/// An invalid WASI context configuration. +#[derive(Debug)] +pub enum WasiCtxError { + /// An argument, environment variable, or guest path contains a nul byte. + NulByte, + /// A preopen guest path is empty. + InvalidPreopenPath, + /// A host preopen directory could not be opened. + Io(std::io::Error), + /// The context has reached its descriptor limit. + TooManyDescriptors, +} + +impl Display for WasiCtxError { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + Self::NulByte => f.write_str("WASI strings cannot contain nul bytes"), + Self::InvalidPreopenPath => f.write_str("WASI preopen guest paths cannot be empty"), + Self::Io(error) => write!(f, "failed to configure WASI host resource: {error}"), + Self::TooManyDescriptors => f.write_str("WASI descriptor limit reached"), + } + } +} + +impl std::error::Error for WasiCtxError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } + } +} + +fn validate_bytes(value: Vec<u8>) -> Result<Vec<u8>, WasiCtxError> { + if value.contains(&0) { Err(WasiCtxError::NulByte) } else { Ok(value) } +} + +pub(super) fn state<'a>(ctx: &'a FuncContext<'_>) -> tinywasm::Result<&'a WasiCtx> { + ctx.state::<WasiCtx>().ok_or_else(|| Error::Other("WasiCtx is missing from the store".into())) +} + +pub(super) fn state_mut<'a>(ctx: &'a mut FuncContext<'_>) -> tinywasm::Result<&'a mut WasiCtx> { + ctx.state_mut::<WasiCtx>().ok_or_else(|| Error::Other("WasiCtx is missing from the store".into())) +} diff --git a/crates/wasi/src/p1/imports/clock.rs b/crates/wasi/src/p1/imports/clock.rs new file mode 100644 index 0000000..d8eedbf --- /dev/null +++ b/crates/wasi/src/p1/imports/clock.rs @@ -0,0 +1,28 @@ +use tinywasm::FuncContext; + +use crate::p1::abi::{Errno, INVAL, SUCCESS, realtime_now}; +use crate::p1::ctx::state; +use crate::p1::memory::GuestMemory; + +use super::WasiResult; + +pub(super) fn clock_res_get(mut ctx: FuncContext<'_>, (clock_id, result_ptr): (i32, i32)) -> WasiResult<Errno> { + if !matches!(clock_id, 0 | 1) { + return Ok(INVAL); + } + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), result_ptr, &1_u64.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn clock_time_get( + mut ctx: FuncContext<'_>, + (clock_id, _precision, result_ptr): (i32, i64, i32), +) -> WasiResult<Errno> { + let timestamp = match clock_id { + 0 => realtime_now(), + 1 => state(&ctx)?.monotonic_start.elapsed().as_nanos().try_into().unwrap_or(u64::MAX), + _ => return Ok(INVAL), + }; + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), result_ptr, ×tamp.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS)) +} diff --git a/crates/wasi/src/p1/imports/command.rs b/crates/wasi/src/p1/imports/command.rs new file mode 100644 index 0000000..129bf04 --- /dev/null +++ b/crates/wasi/src/p1/imports/command.rs @@ -0,0 +1,72 @@ +use tinywasm::FuncContext; + +use crate::p1::abi::{Errno, OVERFLOW, SUCCESS}; +use crate::p1::ctx::state; +use crate::p1::memory::GuestMemory; + +use super::WasiResult; + +pub(super) fn args_sizes_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> { + let sizes = sizes(&state(&ctx)?.args)?; + sizes_get(ctx, pointers, sizes) +} + +pub(super) fn environ_sizes_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> { + let sizes = sizes(&state(&ctx)?.env)?; + sizes_get(ctx, pointers, sizes) +} + +fn sizes_get( + mut ctx: FuncContext<'_>, + (count_ptr, size_ptr): (i32, i32), + (count, size): (u32, u32), +) -> WasiResult<Errno> { + let memory = GuestMemory::new(&ctx)?; + memory.check_range(&ctx, count_ptr as u32 as usize, 4)?; + memory.check_range(&ctx, size_ptr as u32 as usize, 4)?; + memory.write(ctx.store_mut(), count_ptr, &count.to_le_bytes())?; + Ok(memory.write(ctx.store_mut(), size_ptr, &size.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS)) +} + +fn sizes(values: &[Vec<u8>]) -> Result<(u32, u32), Errno> { + Ok((values.len().try_into().map_err(|_| OVERFLOW)?, string_array_size(values).ok_or(OVERFLOW)?)) +} + +pub(super) fn args_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> { + let values = state(&ctx)?.args.clone(); + array_get(ctx, pointers, values) +} + +pub(super) fn environ_get(ctx: FuncContext<'_>, pointers: (i32, i32)) -> WasiResult<Errno> { + let values = state(&ctx)?.env.clone(); + array_get(ctx, pointers, values) +} + +fn array_get(mut ctx: FuncContext<'_>, (array_ptr, buffer_ptr): (i32, i32), values: Vec<Vec<u8>>) -> WasiResult<Errno> { + let Some(pointer_len) = values.len().checked_mul(4) else { return Ok(OVERFLOW) }; + let Some(buffer_len) = string_array_size(&values).map(|value| value as usize) else { return Ok(OVERFLOW) }; + let array_offset = array_ptr as u32 as usize; + let buffer_offset = buffer_ptr as u32 as usize; + let mut pointers = Vec::with_capacity(pointer_len); + let mut buffer = Vec::with_capacity(buffer_len); + for value in values { + let Some(pointer) = buffer_offset.checked_add(buffer.len()).and_then(|value| u32::try_from(value).ok()) else { + return Ok(OVERFLOW); + }; + pointers.extend_from_slice(&pointer.to_le_bytes()); + buffer.extend_from_slice(&value); + buffer.push(0); + } + let memory = GuestMemory::new(&ctx)?; + memory.check_range(&ctx, array_offset, pointers.len())?; + memory.check_range(&ctx, buffer_offset, buffer.len())?; + memory.write_at(ctx.store_mut(), array_offset, &pointers)?; + Ok(memory.write_at(ctx.store_mut(), buffer_offset, &buffer).map_or_else(|errno| errno, |()| SUCCESS)) +} + +fn string_array_size(values: &[Vec<u8>]) -> Option<u32> { + values + .iter() + .try_fold(0usize, |size, value| size.checked_add(value.len())?.checked_add(1)) + .and_then(|size| u32::try_from(size).ok()) +} diff --git a/crates/wasi/src/p1/imports/fd.rs b/crates/wasi/src/p1/imports/fd.rs new file mode 100644 index 0000000..18eb122 --- /dev/null +++ b/crates/wasi/src/p1/imports/fd.rs @@ -0,0 +1,423 @@ +use std::io::{Read, Seek, SeekFrom, Write}; + +use cap_fs_ext::{DirEntryExt, DirExt, MetadataExt}; +use cap_std::fs::FileExt; +use tinywasm::FuncContext; + +use crate::p1::abi::*; +use crate::p1::ctx::{MAX_DESCRIPTORS, Resource, state, state_mut}; +use crate::p1::memory::GuestMemory; + +use super::WasiResult; + +pub(super) fn fd_close(mut ctx: FuncContext<'_>, fd: i32) -> WasiResult<Errno> { + let index = fd as u32 as usize; + let Some(slot) = state_mut(&mut ctx)?.descriptors.get_mut(index) else { return Ok(BADF) }; + if slot.take().is_none() { Ok(BADF) } else { Ok(SUCCESS) } +} + +pub(super) fn fd_renumber(mut ctx: FuncContext<'_>, (from, to): (i32, i32)) -> WasiResult<Errno> { + let from = from as u32 as usize; + let to = to as u32 as usize; + let wasi = state_mut(&mut ctx)?; + if from >= wasi.descriptors.len() || wasi.descriptors[from].is_none() { + return Ok(BADF); + } + if from == to { + return Ok(SUCCESS); + } + if to >= MAX_DESCRIPTORS { + return Ok(MFILE); + } + if to >= wasi.descriptors.len() { + wasi.descriptors.resize_with(to + 1, || None); + } + wasi.descriptors[to] = wasi.descriptors[from].take(); + Ok(SUCCESS) +} + +pub(super) fn fd_fdstat_get(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> { + let descriptor = state(&ctx)?.descriptor(fd)?; + let mut bytes = [0; 24]; + bytes[0] = match &descriptor.resource { + Resource::File(file) => file_type(&file.metadata().map_err(|error| io_errno(&error))?), + _ => descriptor.file_type(), + }; + put(&mut bytes, 2, descriptor.flags.to_le_bytes()); + put(&mut bytes, 8, descriptor.rights.to_le_bytes()); + put(&mut bytes, 16, descriptor.inheriting_rights.to_le_bytes()); + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn fd_fdstat_set_flags(mut ctx: FuncContext<'_>, (fd, flags): (i32, i32)) -> WasiResult<Errno> { + let flags = flags as u32; + if flags > FDFLAGS_ALL.into() { + return Ok(INVAL); + } + if flags & u32::from(FDFLAG_DSYNC | FDFLAG_RSYNC | FDFLAG_SYNC) != 0 { + return Ok(INVAL); + } + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_FDSTAT_SET_FLAGS)?; + let flags = flags as u16; + let nonblocking = flags & FDFLAG_NONBLOCK != 0; + match &descriptor.resource { + Resource::TcpListener(listener) if flags == FDFLAG_NONBLOCK || flags == 0 => { + listener.set_nonblocking(nonblocking).map_err(|error| io_errno(&error))? + } + Resource::TcpStream(stream) if flags == FDFLAG_NONBLOCK || flags == 0 => { + stream.set_nonblocking(nonblocking).map_err(|error| io_errno(&error))? + } + Resource::UdpSocket(socket) if flags == FDFLAG_NONBLOCK || flags == 0 => { + socket.set_nonblocking(nonblocking).map_err(|error| io_errno(&error))? + } + Resource::TcpListener(_) | Resource::TcpStream(_) | Resource::UdpSocket(_) => return Ok(INVAL), + Resource::File(file) => set_file_status_flags(file, flags)?, + Resource::Stdin | Resource::Stdout | Resource::Stderr | Resource::Directory(_) => return Ok(BADF), + }; + descriptor.flags = flags; + Ok(SUCCESS) +} + +pub(super) fn fd_fdstat_set_rights( + mut ctx: FuncContext<'_>, + (fd, rights, inheriting_rights): (i32, i64, i64), +) -> WasiResult<Errno> { + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + let rights = rights as u64; + let inheriting_rights = inheriting_rights as u64; + if rights & !descriptor.rights != 0 || inheriting_rights & !descriptor.inheriting_rights != 0 { + return Ok(NOTCAPABLE); + } + descriptor.rights = rights; + descriptor.inheriting_rights = inheriting_rights; + Ok(SUCCESS) +} + +pub(super) fn fd_filestat_get(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> { + let descriptor = state(&ctx)?.descriptor(fd)?; + descriptor.require_rights(RIGHT_FD_FILESTAT_GET)?; + let bytes = match &descriptor.resource { + Resource::File(file) => filestat(&file.metadata().map_err(|error| io_errno(&error))?), + Resource::Directory(dir) => filestat(&dir.dir_metadata().map_err(|error| io_errno(&error))?), + Resource::Stdin + | Resource::Stdout + | Resource::Stderr + | Resource::TcpListener(_) + | Resource::TcpStream(_) + | Resource::UdpSocket(_) => { + let mut bytes = [0; 64]; + bytes[16] = descriptor.file_type(); + bytes + } + }; + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn fd_filestat_set_size(mut ctx: FuncContext<'_>, (fd, size): (i32, i64)) -> WasiResult<Errno> { + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_FILESTAT_SET_SIZE)?; + let Resource::File(file) = &descriptor.resource else { return Ok(ISDIR) }; + Ok(file.set_len(size as u64).map_or_else(|error| io_errno(&error), |()| SUCCESS)) +} + +pub(super) fn fd_filestat_set_times( + mut ctx: FuncContext<'_>, + (fd, atim, mtim, flags): (i32, i64, i64, i32), +) -> WasiResult<Errno> { + let flags = flags as u32; + if flags > u32::from(FSTFLAGS_ALL) + || flags & u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW) == u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW) + || flags & u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW) == u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW) + { + return Ok(INVAL); + } + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_FILESTAT_SET_TIMES)?; + if flags == 0 { + return Ok(SUCCESS); + } + if let Resource::Directory(dir) = &descriptor.resource { + let atime = time_spec(flags as u16, FSTFLAG_ATIM, FSTFLAG_ATIM_NOW, atim as u64); + let mtime = time_spec(flags as u16, FSTFLAG_MTIM, FSTFLAG_MTIM_NOW, mtim as u64); + return Ok(dir.set_times(".", atime, mtime).map_or_else(|error| io_errno(&error), |()| SUCCESS)); + } + #[cfg(any(target_os = "android", target_os = "linux"))] + { + let Resource::File(file) = &descriptor.resource else { return Ok(NOTSUP) }; + let access = rustix_time(flags as u16, FSTFLAG_ATIM, FSTFLAG_ATIM_NOW, atim as u64)?; + let modification = rustix_time(flags as u16, FSTFLAG_MTIM, FSTFLAG_MTIM_NOW, mtim as u64)?; + let times = rustix::fs::Timestamps { last_access: access, last_modification: modification }; + Ok(rustix::fs::futimens(file, ×).map_or_else(Errno::from, |()| SUCCESS)) + } + #[cfg(not(any(target_os = "android", target_os = "linux")))] + { + let _ = (atim, mtim, descriptor); + Ok(NOTSUP) + } +} + +pub(super) fn fd_read(ctx: FuncContext<'_>, args: (i32, i32, i32, i32)) -> WasiResult<Errno> { + read_from_fd(ctx, args, None) +} + +pub(super) fn fd_pread( + ctx: FuncContext<'_>, + (fd, iovecs_ptr, iovecs_len, offset, result_ptr): (i32, i32, i32, i64, i32), +) -> WasiResult<Errno> { + read_from_fd(ctx, (fd, iovecs_ptr, iovecs_len, result_ptr), Some(offset as u64)) +} + +fn read_from_fd( + mut ctx: FuncContext<'_>, + (fd, iovecs_ptr, iovecs_len, result_ptr): (i32, i32, i32, i32), + offset: Option<u64>, +) -> WasiResult<Errno> { + let memory = GuestMemory::new(&ctx)?; + let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?; + memory.check_range(&ctx, result_ptr as u32 as usize, 4)?; + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_READ | if offset.is_some() { RIGHT_FD_SEEK } else { 0 })?; + let mut buffer = Vec::new(); + buffer.try_reserve_exact(iovecs.byte_len).map_err(|_| NOMEM)?; + buffer.resize(iovecs.byte_len, 0); + let read = match &mut descriptor.resource { + Resource::Stdin => std::io::stdin().lock().read(&mut buffer), + Resource::File(file) if let Some(offset) = offset => { + file.read_at(&mut buffer, checked_offset(offset, iovecs.byte_len)?) + } + Resource::File(file) => file.read(&mut buffer), + Resource::TcpStream(stream) => stream.read(&mut buffer), + Resource::UdpSocket(socket) => socket.recv(&mut buffer), + Resource::Directory(_) => return Ok(ISDIR), + _ => return Ok(BADF), + } + .map_err(|error| io_errno(&error))?; + memory.scatter(ctx.store_mut(), &iovecs, &buffer[..read])?; + Ok(memory.write(ctx.store_mut(), result_ptr, &(read as u32).to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn fd_write(ctx: FuncContext<'_>, args: (i32, i32, i32, i32)) -> WasiResult<Errno> { + write_to_fd(ctx, args, None) +} + +pub(super) fn fd_pwrite( + ctx: FuncContext<'_>, + (fd, iovecs_ptr, iovecs_len, offset, result_ptr): (i32, i32, i32, i64, i32), +) -> WasiResult<Errno> { + write_to_fd(ctx, (fd, iovecs_ptr, iovecs_len, result_ptr), Some(offset as u64)) +} + +fn write_to_fd( + mut ctx: FuncContext<'_>, + (fd, iovecs_ptr, iovecs_len, result_ptr): (i32, i32, i32, i32), + offset: Option<u64>, +) -> WasiResult<Errno> { + let memory = GuestMemory::new(&ctx)?; + let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?; + memory.check_range(&ctx, result_ptr as u32 as usize, 4)?; + let data = memory.gather(&ctx, &iovecs)?; + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_WRITE | if offset.is_some() { RIGHT_FD_SEEK } else { 0 })?; + let written = match &mut descriptor.resource { + Resource::Stdout => std::io::stdout().lock().write(&data), + Resource::Stderr => std::io::stderr().lock().write(&data), + Resource::File(file) if let Some(offset) = offset => file.write_at(&data, checked_offset(offset, data.len())?), + Resource::File(file) => file.write(&data), + Resource::TcpStream(stream) => stream.write(&data), + Resource::UdpSocket(socket) => socket.send(&data), + Resource::Directory(_) => return Ok(ISDIR), + _ => return Ok(BADF), + } + .map_err(|error| io_errno(&error))?; + Ok(memory + .write(ctx.store_mut(), result_ptr, &(written as u32).to_le_bytes()) + .map_or_else(|errno| errno, |()| SUCCESS)) +} + +fn checked_offset(offset: u64, len: usize) -> Result<u64, Errno> { + offset.checked_add(len as u64).map(|_| offset).ok_or(OVERFLOW) +} + +#[cfg(unix)] +fn set_file_status_flags(file: &cap_std::fs::File, flags: u16) -> Result<(), Errno> { + let mut host_flags = rustix::fs::fcntl_getfl(file).map_err(Errno::from)?; + host_flags.set(rustix::fs::OFlags::APPEND, flags & FDFLAG_APPEND != 0); + host_flags.set(rustix::fs::OFlags::NONBLOCK, flags & FDFLAG_NONBLOCK != 0); + rustix::fs::fcntl_setfl(file, host_flags).map_err(Errno::from) +} + +#[cfg(not(unix))] +fn set_file_status_flags(_file: &cap_std::fs::File, _flags: u16) -> Result<(), Errno> { + Err(NOTSUP) +} + +pub(super) fn fd_seek( + mut ctx: FuncContext<'_>, + (fd, offset, whence, result_ptr): (i32, i64, i32, i32), +) -> WasiResult<Errno> { + let memory = GuestMemory::new(&ctx)?; + memory.check_range(&ctx, result_ptr as u32 as usize, 8)?; + let position = match whence { + 0 if offset >= 0 => SeekFrom::Start(offset as u64), + 0 => return Ok(INVAL), + 1 => SeekFrom::Current(offset), + 2 => SeekFrom::End(offset), + _ => return Ok(INVAL), + }; + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(if whence == 1 && offset == 0 { RIGHT_FD_TELL } else { RIGHT_FD_SEEK })?; + let Resource::File(file) = &mut descriptor.resource else { return Ok(SPIPE) }; + let offset = file.seek(position).map_err(|error| io_errno(&error))?; + Ok(memory.write(ctx.store_mut(), result_ptr, &offset.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn fd_tell(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> { + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_TELL)?; + let Resource::File(file) = &mut descriptor.resource else { return Ok(SPIPE) }; + let offset = file.stream_position().map_err(|error| io_errno(&error))?; + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), result_ptr, &offset.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn fd_sync(ctx: FuncContext<'_>, fd: i32) -> WasiResult<Errno> { + sync_fd(ctx, fd, false) +} + +pub(super) fn fd_datasync(ctx: FuncContext<'_>, fd: i32) -> WasiResult<Errno> { + sync_fd(ctx, fd, true) +} + +fn sync_fd(mut ctx: FuncContext<'_>, fd: i32, data_only: bool) -> WasiResult<Errno> { + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(if data_only { RIGHT_FD_DATASYNC } else { RIGHT_FD_SYNC })?; + let Resource::File(file) = &descriptor.resource else { return Ok(INVAL) }; + Ok((if data_only { file.sync_data() } else { file.sync_all() }).map_or_else(|error| io_errno(&error), |()| SUCCESS)) +} + +pub(super) fn fd_allocate(mut ctx: FuncContext<'_>, (fd, offset, len): (i32, i64, i64)) -> WasiResult<Errno> { + let offset = offset as u64; + let len = len as u64; + if offset.checked_add(len).is_none() { + return Ok(FBIG); + } + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_ALLOCATE)?; + let Resource::File(_) = &descriptor.resource else { return Ok(BADF) }; + Ok(NOTSUP) +} + +pub(super) fn fd_advise( + mut ctx: FuncContext<'_>, + (fd, offset, len, advice): (i32, i64, i64, i32), +) -> WasiResult<Errno> { + if !(0..=5).contains(&advice) { + return Ok(INVAL); + } + let descriptor = state_mut(&mut ctx)?.descriptor_mut(fd)?; + descriptor.require_rights(RIGHT_FD_ADVISE)?; + let Resource::File(file) = &descriptor.resource else { return Ok(BADF) }; + if (offset as u64).checked_add(len as u64).is_none() { + return Ok(OVERFLOW); + } + #[cfg(any(target_os = "android", target_os = "linux"))] + { + let advice = match advice { + 0 => rustix::fs::Advice::Normal, + 1 => rustix::fs::Advice::Sequential, + 2 => rustix::fs::Advice::Random, + 3 => rustix::fs::Advice::WillNeed, + 4 => rustix::fs::Advice::DontNeed, + 5 => rustix::fs::Advice::NoReuse, + _ => unreachable!(), + }; + Ok(rustix::fs::fadvise(file, offset as u64, std::num::NonZeroU64::new(len as u64), advice) + .map_or_else(Errno::from, |()| SUCCESS)) + } + #[cfg(not(any(target_os = "android", target_os = "linux")))] + { + let _ = (file, offset, len); + Ok(SUCCESS) + } +} + +pub(super) fn fd_prestat_get(mut ctx: FuncContext<'_>, (fd, result_ptr): (i32, i32)) -> WasiResult<Errno> { + let descriptor = state(&ctx)?.descriptor(fd)?; + let Some(path) = &descriptor.preopen_path else { return Ok(BADF) }; + let Some(len) = u32::try_from(path.len()).ok() else { return Ok(OVERFLOW) }; + let mut bytes = [0; 8]; + put(&mut bytes, 4, len.to_le_bytes()); + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn fd_prestat_dir_name( + mut ctx: FuncContext<'_>, + (fd, path_ptr, path_len): (i32, i32, i32), +) -> WasiResult<Errno> { + let descriptor = state(&ctx)?.descriptor(fd)?; + let Some(path) = descriptor.preopen_path.clone() else { return Ok(BADF) }; + if path.len() > path_len as u32 as usize { + return Ok(NAMETOOLONG); + } + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), path_ptr, &path).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn fd_readdir( + mut ctx: FuncContext<'_>, + (fd, buffer_ptr, buffer_len, cookie, used_ptr): (i32, i32, i32, i64, i32), +) -> WasiResult<Errno> { + let capacity = buffer_len as u32 as usize; + let memory = GuestMemory::new(&ctx)?; + memory.check_range(&ctx, buffer_ptr as u32 as usize, buffer_len as u32 as usize)?; + memory.check_range(&ctx, used_ptr as u32 as usize, 4)?; + let descriptor = state(&ctx)?.descriptor(fd)?; + descriptor.require_rights(RIGHT_FD_READDIR)?; + let Resource::Directory(dir) = &descriptor.resource else { return Ok(NOTDIR) }; + let entries = dir.entries().map_err(|error| io_errno(&error))?; + let cookie = usize::try_from(cookie as u64).map_err(|_| OVERFLOW)?; + let mut output = Vec::new(); + output.try_reserve_exact(capacity).map_err(|_| NOMEM)?; + for (index, entry) in entries.enumerate().skip(cookie) { + let entry = entry.map_err(|error| io_errno(&error))?; + let name = os_bytes(&entry.file_name()); + let metadata = entry.full_metadata().map_err(|error| io_errno(&error))?; + let mut header = [0; 24]; + let Some(next) = u64::try_from(index).ok().and_then(|index| index.checked_add(1)) else { + return Ok(OVERFLOW); + }; + put(&mut header, 0, next.to_le_bytes()); + put(&mut header, 8, metadata.ino().to_le_bytes()); + put(&mut header, 16, u32::try_from(name.len()).unwrap_or(u32::MAX).to_le_bytes()); + header[20] = file_type(&metadata); + let remaining = capacity.saturating_sub(output.len()); + output.extend_from_slice(&header[..remaining.min(header.len())]); + let remaining = capacity.saturating_sub(output.len()); + output.extend_from_slice(&name[..remaining.min(name.len())]); + if output.len() == capacity { + break; + } + } + memory.write(ctx.store_mut(), buffer_ptr, &output)?; + Ok(memory + .write(ctx.store_mut(), used_ptr, &(output.len() as u32).to_le_bytes()) + .map_or_else(|errno| errno, |()| SUCCESS)) +} + +#[cfg(any(target_os = "android", target_os = "linux"))] +fn rustix_time(flags: u16, explicit: u16, now: u16, timestamp: u64) -> Result<rustix::fs::Timespec, Errno> { + if flags & now != 0 { + Ok(rustix::fs::Timespec { tv_sec: 0, tv_nsec: rustix::fs::UTIME_NOW }) + } else if flags & explicit != 0 { + Ok(rustix::fs::Timespec { + tv_sec: i64::try_from(timestamp / 1_000_000_000).map_err(|_| OVERFLOW)?, + tv_nsec: (timestamp % 1_000_000_000) as _, + }) + } else { + Ok(rustix::fs::Timespec { tv_sec: 0, tv_nsec: rustix::fs::UTIME_OMIT }) + } +} diff --git a/crates/wasi/src/p1/imports/mod.rs b/crates/wasi/src/p1/imports/mod.rs new file mode 100644 index 0000000..eff8d0f --- /dev/null +++ b/crates/wasi/src/p1/imports/mod.rs @@ -0,0 +1,101 @@ +mod clock; +mod command; +mod fd; +mod path; +mod poll; +mod process; +mod random; +mod sock; + +use tinywasm::{HostFunction, Imports}; + +use super::abi::Errno; + +const MODULE: &str = "wasi_snapshot_preview1"; + +type WasiResult<T> = Result<T, WasiError>; + +enum WasiError { + Errno(Errno), + Host(tinywasm::Error), +} + +impl From<Errno> for WasiError { + fn from(errno: Errno) -> Self { + Self::Errno(errno) + } +} + +impl From<tinywasm::Error> for WasiError { + fn from(error: tinywasm::Error) -> Self { + Self::Host(error) + } +} + +pub(super) fn register(imports: &mut Imports) { + register_import(imports, "args_get", command::args_get); + register_import(imports, "args_sizes_get", command::args_sizes_get); + register_import(imports, "environ_get", command::environ_get); + register_import(imports, "environ_sizes_get", command::environ_sizes_get); + register_import(imports, "clock_res_get", clock::clock_res_get); + register_import(imports, "clock_time_get", clock::clock_time_get); + register_import(imports, "fd_advise", fd::fd_advise); + register_import(imports, "fd_allocate", fd::fd_allocate); + register_import(imports, "fd_close", fd::fd_close); + register_import(imports, "fd_datasync", fd::fd_datasync); + register_import(imports, "fd_fdstat_get", fd::fd_fdstat_get); + register_import(imports, "fd_fdstat_set_flags", fd::fd_fdstat_set_flags); + register_import(imports, "fd_fdstat_set_rights", fd::fd_fdstat_set_rights); + register_import(imports, "fd_filestat_get", fd::fd_filestat_get); + register_import(imports, "fd_filestat_set_size", fd::fd_filestat_set_size); + register_import(imports, "fd_filestat_set_times", fd::fd_filestat_set_times); + register_import(imports, "fd_pread", fd::fd_pread); + register_import(imports, "fd_prestat_get", fd::fd_prestat_get); + register_import(imports, "fd_prestat_dir_name", fd::fd_prestat_dir_name); + register_import(imports, "fd_pwrite", fd::fd_pwrite); + register_import(imports, "fd_read", fd::fd_read); + register_import(imports, "fd_readdir", fd::fd_readdir); + register_import(imports, "fd_renumber", fd::fd_renumber); + register_import(imports, "fd_seek", fd::fd_seek); + register_import(imports, "fd_sync", fd::fd_sync); + register_import(imports, "fd_tell", fd::fd_tell); + register_import(imports, "fd_write", fd::fd_write); + register_import(imports, "path_create_directory", path::path_create_directory); + register_import(imports, "path_filestat_get", path::path_filestat_get); + register_import(imports, "path_filestat_set_times", path::path_filestat_set_times); + register_import(imports, "path_link", path::path_link); + register_import(imports, "path_open", path::path_open); + register_import(imports, "path_readlink", path::path_readlink); + register_import(imports, "path_remove_directory", path::path_remove_directory); + register_import(imports, "path_rename", path::path_rename); + register_import(imports, "path_symlink", path::path_symlink); + register_import(imports, "path_unlink_file", path::path_unlink_file); + register_import(imports, "poll_oneoff", poll::poll_oneoff); + imports.define(MODULE, "proc_exit", HostFunction::from(process::proc_exit)); + register_import(imports, "proc_raise", process::proc_raise); + register_import(imports, "sched_yield", process::sched_yield); + register_import(imports, "random_get", random::random_get); + register_import(imports, "sock_accept", sock::sock_accept); + register_import(imports, "sock_recv", sock::sock_recv); + register_import(imports, "sock_send", sock::sock_send); + register_import(imports, "sock_shutdown", sock::sock_shutdown); +} + +fn register_import<P>( + imports: &mut Imports, + name: &str, + function: fn(tinywasm::FuncContext<'_>, P) -> WasiResult<Errno>, +) where + P: tinywasm::FromWasmValues + 'static, +{ + imports.define( + MODULE, + name, + HostFunction::from(move |ctx: tinywasm::FuncContext<'_>, args: P| -> tinywasm::Result<i32> { + match function(ctx, args) { + Ok(errno) | Err(WasiError::Errno(errno)) => Ok(errno.into()), + Err(WasiError::Host(error)) => Err(error), + } + }), + ); +} diff --git a/crates/wasi/src/p1/imports/path.rs b/crates/wasi/src/p1/imports/path.rs new file mode 100644 index 0000000..648f0cb --- /dev/null +++ b/crates/wasi/src/p1/imports/path.rs @@ -0,0 +1,258 @@ +use std::path::PathBuf; + +use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt, OpenOptionsMaybeDirExt, OpenOptionsSyncExt}; +use cap_std::fs::{Dir, OpenOptions}; +use tinywasm::FuncContext; + +use crate::p1::abi::*; +use crate::p1::ctx::{Descriptor, Resource, state, state_mut}; +use crate::p1::memory::GuestMemory; + +use super::WasiResult; + +const MAX_PATH_BYTES: usize = 4096; + +pub(super) fn path_create_directory( + ctx: FuncContext<'_>, + (fd, path_ptr, path_len): (i32, i32, i32), +) -> WasiResult<Errno> { + let path = guest_path(&ctx, path_ptr, path_len)?; + let dir = directory(&ctx, fd, RIGHT_PATH_CREATE_DIRECTORY)?; + Ok(dir.create_dir(path).map_or_else(|error| path_errno(&error), |()| SUCCESS)) +} + +pub(super) fn path_remove_directory( + ctx: FuncContext<'_>, + (fd, path_ptr, path_len): (i32, i32, i32), +) -> WasiResult<Errno> { + let path = guest_path(&ctx, path_ptr, path_len)?; + let dir = directory(&ctx, fd, RIGHT_PATH_REMOVE_DIRECTORY)?; + Ok(dir.remove_dir(path).map_or_else(|error| path_errno(&error), |()| SUCCESS)) +} + +pub(super) fn path_unlink_file(ctx: FuncContext<'_>, (fd, path_ptr, path_len): (i32, i32, i32)) -> WasiResult<Errno> { + let path = guest_path(&ctx, path_ptr, path_len)?; + let dir = directory(&ctx, fd, RIGHT_PATH_UNLINK_FILE)?; + Ok(dir.remove_file_or_symlink(path).map_or_else(|error| path_errno(&error), |()| SUCCESS)) +} + +pub(super) fn path_open( + mut ctx: FuncContext<'_>, + (fd, lookup_flags, path_ptr, path_len, open_flags, rights, inheriting_rights, fd_flags, result_ptr): ( + i32, + i32, + i32, + i32, + i32, + i64, + i64, + i32, + i32, + ), +) -> WasiResult<Errno> { + let lookup_flags = lookup_flags as u32; + if lookup_flags & !LOOKUP_SYMLINK_FOLLOW != 0 + || open_flags as u32 > OFLAGS_ALL.into() + || fd_flags as u32 > FDFLAGS_ALL.into() + { + return Ok(INVAL); + } + let open_flags = open_flags as u16; + let fd_flags = fd_flags as u16; + if fd_flags & (FDFLAG_DSYNC | FDFLAG_RSYNC | FDFLAG_SYNC) != 0 { + return Ok(NOTSUP); + } + let follow = lookup_flags & LOOKUP_SYMLINK_FOLLOW != 0; + let create = open_flags & OFLAG_CREAT != 0; + let exclusive = open_flags & OFLAG_EXCL != 0; + let truncate = open_flags & OFLAG_TRUNC != 0; + if exclusive && !create { + return Ok(INVAL); + } + if open_flags & OFLAG_DIRECTORY != 0 && (create || truncate) { + return Ok(ISDIR); + } + let path = guest_path(&ctx, path_ptr, path_len)?; + let memory = GuestMemory::new(&ctx)?; + memory.check_range(&ctx, result_ptr as u32 as usize, 4)?; + let parent = state(&ctx)?.descriptor(fd)?; + parent.require_rights(RIGHT_PATH_OPEN)?; + let rights = rights as u64; + let inheriting_rights = inheriting_rights as u64; + if rights & !parent.inheriting_rights != 0 || inheriting_rights & !parent.inheriting_rights != 0 { + return Ok(NOTCAPABLE); + } + if create && parent.rights & RIGHT_PATH_CREATE_FILE == 0 { + return Ok(NOTCAPABLE); + } + if truncate && parent.rights & RIGHT_PATH_FILESTAT_SET_SIZE == 0 { + return Ok(NOTCAPABLE); + } + let Resource::Directory(parent_dir) = &parent.resource else { return Ok(NOTDIR) }; + let parent_dir = parent_dir.try_clone().map_err(|error| path_errno(&error))?; + let mut options = OpenOptions::new(); + let write = create || truncate || rights & (RIGHT_FD_WRITE | RIGHT_FD_ALLOCATE | RIGHT_FD_FILESTAT_SET_SIZE) != 0; + options + .read(rights & RIGHT_FD_READ != 0 || !write) + .write(write) + .append(write && fd_flags & FDFLAG_APPEND != 0) + .create(create) + .create_new(exclusive) + .truncate(truncate) + .follow(if follow { FollowSymlinks::Yes } else { FollowSymlinks::No }) + .nonblock(fd_flags & FDFLAG_NONBLOCK != 0) + .maybe_dir(true); + let file = parent_dir.open_with(&path, &options).map_err(|error| path_errno(&error))?; + let descriptor = if file.metadata().map_err(|error| path_errno(&error))?.is_dir() { + Descriptor { + resource: Resource::Directory(Dir::reopen_dir(&file).map_err(|error| path_errno(&error))?), + rights: rights & DIRECTORY_RIGHTS, + inheriting_rights, + flags: fd_flags, + preopen_path: None, + } + } else { + if open_flags & OFLAG_DIRECTORY != 0 { + return Ok(NOTDIR); + } + Descriptor { + resource: Resource::File(file), + rights: rights & FILE_RIGHTS, + inheriting_rights: 0, + flags: fd_flags, + preopen_path: None, + } + }; + let new_fd = state_mut(&mut ctx)?.insert_descriptor(descriptor)?; + if let Err(errno) = memory.write(ctx.store_mut(), result_ptr, &new_fd.to_le_bytes()) { + let _ = state_mut(&mut ctx)?.descriptors[new_fd as usize].take(); + return Ok(errno); + } + Ok(SUCCESS) +} + +pub(super) fn path_filestat_get( + mut ctx: FuncContext<'_>, + (fd, lookup_flags, path_ptr, path_len, result_ptr): (i32, i32, i32, i32, i32), +) -> WasiResult<Errno> { + let lookup_flags = lookup_flags as u32; + if lookup_flags & !LOOKUP_SYMLINK_FOLLOW != 0 { + return Ok(INVAL); + } + let follow = lookup_flags & LOOKUP_SYMLINK_FOLLOW != 0; + let path = guest_path(&ctx, path_ptr, path_len)?; + let dir = directory(&ctx, fd, RIGHT_PATH_FILESTAT_GET)?; + let metadata = if follow { dir.metadata(&path) } else { dir.symlink_metadata(&path) }; + let metadata = metadata.map_err(|error| path_errno(&error))?; + let bytes = filestat(&metadata); + let memory = GuestMemory::new(&ctx)?; + Ok(memory.write(ctx.store_mut(), result_ptr, &bytes).map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn path_filestat_set_times( + ctx: FuncContext<'_>, + (fd, lookup_flags, path_ptr, path_len, atim, mtim, flags): (i32, i32, i32, i32, i64, i64, i32), +) -> WasiResult<Errno> { + let lookup_flags = lookup_flags as u32; + let flags = flags as u32; + if lookup_flags & !LOOKUP_SYMLINK_FOLLOW != 0 + || flags > FSTFLAGS_ALL.into() + || flags & u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW) == u32::from(FSTFLAG_ATIM | FSTFLAG_ATIM_NOW) + || flags & u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW) == u32::from(FSTFLAG_MTIM | FSTFLAG_MTIM_NOW) + { + return Ok(INVAL); + } + let follow = lookup_flags & LOOKUP_SYMLINK_FOLLOW != 0; + let path = guest_path(&ctx, path_ptr, path_len)?; + let dir = directory(&ctx, fd, RIGHT_PATH_FILESTAT_SET_TIMES)?; + if flags == 0 { + return Ok(SUCCESS); + } + let atime = time_spec(flags as u16, FSTFLAG_ATIM, FSTFLAG_ATIM_NOW, atim as u64); + let mtime = time_spec(flags as u16, FSTFLAG_MTIM, FSTFLAG_MTIM_NOW, mtim as u64); + let result = if follow { dir.set_times(&path, atime, mtime) } else { dir.set_symlink_times(&path, atime, mtime) }; + Ok(result.map_or_else(|error| path_errno(&error), |()| SUCCESS)) +} + +pub(super) fn path_link( + ctx: FuncContext<'_>, + (old_fd, flags, old_ptr, old_len, new_fd, new_ptr, new_len): (i32, i32, i32, i32, i32, i32, i32), +) -> WasiResult<Errno> { + if flags != 0 { + return Ok(INVAL); + } + let old_path = guest_path(&ctx, old_ptr, old_len)?; + let new_path = guest_path(&ctx, new_ptr, new_len)?; + let old_dir = directory(&ctx, old_fd, RIGHT_PATH_LINK_SOURCE)?; + let new_dir = directory(&ctx, new_fd, RIGHT_PATH_LINK_TARGET)?; + Ok(old_dir.hard_link(old_path, &new_dir, new_path).map_or_else(|error| path_errno(&error), |()| SUCCESS)) +} + +pub(super) fn path_rename( + ctx: FuncContext<'_>, + (old_fd, old_ptr, old_len, new_fd, new_ptr, new_len): (i32, i32, i32, i32, i32, i32), +) -> WasiResult<Errno> { + let old_path = guest_path(&ctx, old_ptr, old_len)?; + let new_path = guest_path(&ctx, new_ptr, new_len)?; + let old_dir = directory(&ctx, old_fd, RIGHT_PATH_RENAME_SOURCE)?; + let new_dir = directory(&ctx, new_fd, RIGHT_PATH_RENAME_TARGET)?; + Ok(old_dir.rename(old_path, &new_dir, new_path).map_or_else(|error| path_errno(&error), |()| SUCCESS)) +} + +pub(super) fn path_readlink( + mut ctx: FuncContext<'_>, + (fd, path_ptr, path_len, buffer_ptr, buffer_len, used_ptr): (i32, i32, i32, i32, i32, i32), +) -> WasiResult<Errno> { + let memory = GuestMemory::new(&ctx)?; + memory.check_range(&ctx, buffer_ptr as u32 as usize, buffer_len as u32 as usize)?; + memory.check_range(&ctx, used_ptr as u32 as usize, 4)?; + let path = guest_path(&ctx, path_ptr, path_len)?; + let dir = directory(&ctx, fd, RIGHT_PATH_READLINK)?; + let target = dir.read_link_contents(path).map_err(|error| path_errno(&error))?; + let bytes = os_bytes(target.as_os_str()); + let written = bytes.len().min(buffer_len as u32 as usize); + memory.write(ctx.store_mut(), buffer_ptr, &bytes[..written])?; + Ok(memory + .write(ctx.store_mut(), used_ptr, &(written as u32).to_le_bytes()) + .map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn path_symlink( + ctx: FuncContext<'_>, + (old_ptr, old_len, fd, new_ptr, new_len): (i32, i32, i32, i32, i32), +) -> WasiResult<Errno> { + let memory = GuestMemory::new(&ctx)?; + if old_len as u32 as usize > MAX_PATH_BYTES { + return Ok(NAMETOOLONG); + } + let target_bytes = memory.read(&ctx, old_ptr, old_len)?; + if target_bytes.contains(&0) { + return Ok(ILSEQ); + } + let target = PathBuf::from(std::str::from_utf8(&target_bytes).map_err(|_| ILSEQ)?); + let new_path = guest_path(&ctx, new_ptr, new_len)?; + let dir = directory(&ctx, fd, RIGHT_PATH_SYMLINK)?; + Ok(DirExt::symlink(&dir, target, new_path).map_or_else(|error| path_errno(&error), |()| SUCCESS)) +} + +fn directory(ctx: &FuncContext<'_>, fd: i32, right: u64) -> Result<Dir, Errno> { + let descriptor = state(ctx).map_err(|_| IO)?.descriptor(fd)?; + descriptor.require_rights(right)?; + let Resource::Directory(dir) = &descriptor.resource else { return Err(NOTDIR) }; + dir.try_clone().map_err(|error| path_errno(&error)) +} + +fn guest_path(ctx: &FuncContext<'_>, pointer: i32, len: i32) -> Result<PathBuf, Errno> { + if len as u32 as usize > MAX_PATH_BYTES { + return Err(NAMETOOLONG); + } + let memory = GuestMemory::new(ctx).map_err(|_| IO)?; + let bytes = memory.read(ctx, pointer, len)?; + if bytes.is_empty() { + return Err(NOENT); + } + if bytes.contains(&0) { + return Err(INVAL); + } + Ok(PathBuf::from(std::str::from_utf8(&bytes).map_err(|_| ILSEQ)?)) +} diff --git a/crates/wasi/src/p1/imports/poll.rs b/crates/wasi/src/p1/imports/poll.rs new file mode 100644 index 0000000..8098b74 --- /dev/null +++ b/crates/wasi/src/p1/imports/poll.rs @@ -0,0 +1,219 @@ +use std::io::Seek; + +use rustix::event::{PollFd, PollFlags, Timespec}; +use tinywasm::FuncContext; + +use crate::p1::abi::*; +use crate::p1::ctx::{Resource, state}; +use crate::p1::memory::GuestMemory; + +use super::WasiResult; + +enum Readiness { + Ready, + Clock(u64), + Poll, +} + +struct PendingEvent { + bytes: [u8; 32], + readiness: Readiness, +} + +struct PollTarget { + event_index: usize, + fd: i32, + event_type: u8, +} + +impl PendingEvent { + fn new(userdata: u64, error: Errno, event_type: u8, available: u64, readiness: Readiness) -> Self { + let mut bytes = [0; 32]; + put(&mut bytes, 0, userdata.to_le_bytes()); + put(&mut bytes, 8, (i32::from(error) as u16).to_le_bytes()); + bytes[10] = event_type; + put(&mut bytes, 16, available.to_le_bytes()); + Self { bytes, readiness } + } +} + +pub(super) fn poll_oneoff( + mut ctx: FuncContext<'_>, + (subscriptions_ptr, events_ptr, count, result_ptr): (i32, i32, i32, i32), +) -> WasiResult<Errno> { + let count = count as u32 as usize; + if count == 0 || count > 1024 { + return Ok(INVAL); + } + let memory = GuestMemory::new(&ctx)?; + let subscriptions = memory.read_at(&ctx, subscriptions_ptr as u32 as usize, count * 48)?; + memory.check_range(&ctx, events_ptr as u32 as usize, count * 32)?; + memory.check_range(&ctx, result_ptr as u32 as usize, 4)?; + + let mut pending_events = Vec::with_capacity(count); + let mut poll_targets = Vec::new(); + let mut minimum_wait: Option<u64> = None; + for subscription in subscriptions.as_chunks::<48>().0 { + let userdata = u64::from_le_bytes(subscription[..8].try_into().expect("userdata")); + let event_type = subscription[8]; + if event_type == 0 { + let wait = clock_wait(&ctx, subscription)?; + minimum_wait = Some(minimum_wait.map_or(wait, |current| current.min(wait))); + pending_events.push(PendingEvent::new(userdata, SUCCESS, event_type, 0, Readiness::Clock(wait))); + } else if matches!(event_type, 1 | 2) { + let fd = u32::from_le_bytes(subscription[16..20].try_into().expect("fd")) as i32; + subscribe_fd(&ctx, fd, userdata, event_type, &mut pending_events, &mut poll_targets)?; + } else { + return Ok(INVAL); + } + } + + let immediately_ready = + pending_events.iter().any(|event| matches!(event.readiness, Readiness::Ready | Readiness::Clock(0))); + let timeout = if immediately_ready { Some(0) } else { minimum_wait }; + let elapsed = wait_for_events(&ctx, &poll_targets, &mut pending_events, timeout)?; + let mut bytes = Vec::with_capacity(pending_events.len() * 32); + for event in pending_events { + if matches!(event.readiness, Readiness::Ready) + || matches!(event.readiness, Readiness::Clock(wait) if wait <= elapsed) + { + bytes.extend_from_slice(&event.bytes); + } + } + let event_count = (bytes.len() / 32) as u32; + memory.write(ctx.store_mut(), events_ptr, &bytes)?; + Ok(memory.write(ctx.store_mut(), result_ptr, &event_count.to_le_bytes()).map_or_else(|errno| errno, |()| SUCCESS)) +} + +fn clock_wait(ctx: &FuncContext<'_>, subscription: &[u8; 48]) -> WasiResult<u64> { + let clock_id = u32::from_le_bytes(subscription[16..20].try_into().expect("clock id")); + let timeout = u64::from_le_bytes(subscription[24..32].try_into().expect("timeout")); + let flags = u16::from_le_bytes(subscription[40..42].try_into().expect("flags")); + if !matches!(clock_id, 0 | 1) || flags & !1 != 0 { + return Err(INVAL.into()); + } + let now = if clock_id == 0 { + realtime_now() + } else { + state(ctx)?.monotonic_start.elapsed().as_nanos().try_into().unwrap_or(u64::MAX) + }; + Ok(if flags & 1 != 0 { timeout.saturating_sub(now) } else { timeout }) +} + +fn subscribe_fd( + ctx: &FuncContext<'_>, + fd: i32, + userdata: u64, + event_type: u8, + pending_events: &mut Vec<PendingEvent>, + poll_targets: &mut Vec<PollTarget>, +) -> WasiResult<()> { + let required_right = if event_type == 1 { RIGHT_FD_READ } else { RIGHT_FD_WRITE }; + let descriptor = match state(ctx)?.descriptor(fd) { + Ok(descriptor) => descriptor, + Err(errno) => { + pending_events.push(PendingEvent::new(userdata, errno, event_type, 0, Readiness::Ready)); + return Ok(()); + } + }; + if let Err(errno) = descriptor.require_rights(required_right | RIGHT_POLL_FD_READWRITE) { + pending_events.push(PendingEvent::new(userdata, errno, event_type, 0, Readiness::Ready)); + return Ok(()); + } + if let Resource::File(file) = &descriptor.resource { + let available = if event_type == 1 { + file.try_clone() + .and_then(|mut file| { + let position = file.stream_position()?; + Ok(file.metadata()?.len().saturating_sub(position)) + }) + .unwrap_or(0) + } else { + 0 + }; + pending_events.push(PendingEvent::new(userdata, SUCCESS, event_type, available, Readiness::Ready)); + return Ok(()); + } + poll_targets.push(PollTarget { event_index: pending_events.len(), fd, event_type }); + pending_events.push(PendingEvent::new(userdata, SUCCESS, event_type, 0, Readiness::Poll)); + Ok(()) +} + +fn wait_for_events( + ctx: &FuncContext<'_>, + poll_targets: &[PollTarget], + pending_events: &mut [PendingEvent], + timeout_ns: Option<u64>, +) -> WasiResult<u64> { + let started = std::time::Instant::now(); + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + let stderr = std::io::stderr(); + let wasi = state(ctx)?; + let mut poll_fds = Vec::with_capacity(poll_targets.len()); + for target in poll_targets { + let flags = if target.event_type == 1 { PollFlags::IN } else { PollFlags::OUT }; + let descriptor = wasi.descriptor(target.fd)?; + let poll_fd = match &descriptor.resource { + Resource::Stdin => PollFd::new(&stdin, flags), + Resource::Stdout => PollFd::new(&stdout, flags), + Resource::Stderr => PollFd::new(&stderr, flags), + Resource::TcpListener(listener) => PollFd::new(listener, flags), + Resource::TcpStream(stream) => PollFd::new(stream, flags), + Resource::UdpSocket(socket) => PollFd::new(socket, flags), + Resource::File(_) | Resource::Directory(_) => unreachable!(), + }; + poll_fds.push(poll_fd); + } + let timeout = timeout_ns.map(|nanoseconds| Timespec { + tv_sec: (nanoseconds / 1_000_000_000).try_into().unwrap_or(i64::MAX), + tv_nsec: (nanoseconds % 1_000_000_000) as _, + }); + if poll_fds.is_empty() { + if let Some(nanoseconds) = timeout_ns { + std::thread::sleep(std::time::Duration::from_nanos(nanoseconds)); + } + } else { + loop { + match rustix::event::poll(&mut poll_fds, timeout.as_ref()) { + Err(rustix::io::Errno::INTR) => continue, + result => { + result.map_err(Errno::from)?; + break; + } + } + } + } + for (target, poll_fd) in poll_targets.iter().zip(poll_fds) { + let flags = poll_fd.revents(); + if flags.intersects(PollFlags::IN | PollFlags::OUT | PollFlags::ERR | PollFlags::HUP | PollFlags::NVAL) { + pending_events[target.event_index].readiness = Readiness::Ready; + let error = if flags.contains(PollFlags::NVAL) { + BADF + } else if flags.contains(PollFlags::ERR) { + IO + } else { + SUCCESS + }; + put(&mut pending_events[target.event_index].bytes, 8, (i32::from(error) as u16).to_le_bytes()); + if target.event_type == 1 { + let resource = &wasi.descriptor(target.fd)?.resource; + let available = match resource { + Resource::Stdin => rustix::io::ioctl_fionread(&stdin), + Resource::TcpStream(stream) => rustix::io::ioctl_fionread(stream), + Resource::UdpSocket(socket) => rustix::io::ioctl_fionread(socket), + _ => Ok(0), + } + .unwrap_or(0); + put(&mut pending_events[target.event_index].bytes, 16, available.to_le_bytes()); + if matches!(resource, Resource::TcpStream(_)) && available == 0 { + put(&mut pending_events[target.event_index].bytes, 24, 1_u16.to_le_bytes()); + } + } + if flags.contains(PollFlags::HUP) { + put(&mut pending_events[target.event_index].bytes, 24, 1_u16.to_le_bytes()); + } + } + } + Ok(u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)) +} diff --git a/crates/wasi/src/p1/imports/process.rs b/crates/wasi/src/p1/imports/process.rs new file mode 100644 index 0000000..9d9571e --- /dev/null +++ b/crates/wasi/src/p1/imports/process.rs @@ -0,0 +1,20 @@ +use tinywasm::{Error, FuncContext}; + +use crate::p1::abi::{Errno, NOTSUP, SUCCESS}; +use crate::p1::ctx::state_mut; + +use super::WasiResult; + +pub(super) fn proc_exit(mut ctx: FuncContext<'_>, status: i32) -> tinywasm::Result<()> { + state_mut(&mut ctx)?.exit_status = Some(status as u32); + Err(Error::Other("WASI process exited".into())) +} + +pub(super) fn proc_raise(_ctx: FuncContext<'_>, _signal: i32) -> WasiResult<Errno> { + Ok(NOTSUP) +} + +pub(super) fn sched_yield(_ctx: FuncContext<'_>, (): ()) -> WasiResult<Errno> { + std::thread::yield_now(); + Ok(SUCCESS) +} diff --git a/crates/wasi/src/p1/imports/random.rs b/crates/wasi/src/p1/imports/random.rs new file mode 100644 index 0000000..84d06e9 --- /dev/null +++ b/crates/wasi/src/p1/imports/random.rs @@ -0,0 +1,25 @@ +use tinywasm::FuncContext; + +use crate::p1::abi::{Errno, IO, SUCCESS}; +use crate::p1::memory::GuestMemory; + +use super::WasiResult; + +pub(super) fn random_get(mut ctx: FuncContext<'_>, (buffer_ptr, buffer_len): (i32, i32)) -> WasiResult<Errno> { + let memory = GuestMemory::new(&ctx)?; + let offset = buffer_ptr as u32 as usize; + let len = buffer_len as u32 as usize; + memory.check_range(&ctx, offset, len)?; + + let mut chunk = [0_u8; 64 * 1024]; + let mut written = 0; + while written < len { + let chunk_len = (len - written).min(chunk.len()); + if getrandom::fill(&mut chunk[..chunk_len]).is_err() { + return Ok(IO); + } + memory.write_at(ctx.store_mut(), offset + written, &chunk[..chunk_len])?; + written += chunk_len; + } + Ok(SUCCESS) +} diff --git a/crates/wasi/src/p1/imports/sock.rs b/crates/wasi/src/p1/imports/sock.rs new file mode 100644 index 0000000..f938835 --- /dev/null +++ b/crates/wasi/src/p1/imports/sock.rs @@ -0,0 +1,124 @@ +use std::io::{IoSliceMut, Write}; + +use tinywasm::FuncContext; + +use crate::p1::abi::*; +use crate::p1::ctx::{Descriptor, Resource, state, state_mut}; +use crate::p1::memory::GuestMemory; + +use super::WasiResult; + +pub(super) fn sock_accept(mut ctx: FuncContext<'_>, (fd, flags, result_ptr): (i32, i32, i32)) -> WasiResult<Errno> { + if flags as u32 > FDFLAGS_ALL.into() { + return Ok(INVAL); + } + let flags = flags as u16; + let memory = GuestMemory::new(&ctx)?; + memory.check_range(&ctx, result_ptr as u32 as usize, 4)?; + let descriptor = state(&ctx)?.descriptor(fd)?; + descriptor.require_rights(RIGHT_SOCK_ACCEPT)?; + let Resource::TcpListener(listener) = &descriptor.resource else { return Ok(NOTSOCK) }; + let rights = descriptor.inheriting_rights; + let (stream, _) = listener.accept().map_err(|error| io_errno(&error))?; + stream.set_nonblocking(flags & FDFLAG_NONBLOCK != 0).map_err(|error| io_errno(&error))?; + let new_fd = state_mut(&mut ctx)?.insert_descriptor(Descriptor { + resource: Resource::TcpStream(stream), + rights, + inheriting_rights: 0, + flags, + preopen_path: None, + })?; + if let Err(errno) = memory.write(ctx.store_mut(), result_ptr, &new_fd.to_le_bytes()) { + let _ = state_mut(&mut ctx)?.descriptors[new_fd as usize].take(); + return Ok(errno); + } + Ok(SUCCESS) +} + +pub(super) fn sock_recv( + mut ctx: FuncContext<'_>, + (fd, iovecs_ptr, iovecs_len, flags, data_len_ptr, result_flags_ptr): (i32, i32, i32, i32, i32, i32), +) -> WasiResult<Errno> { + if flags as u32 & !3 != 0 { + return Ok(INVAL); + } + let memory = GuestMemory::new(&ctx)?; + let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?; + memory.check_range(&ctx, data_len_ptr as u32 as usize, 4)?; + memory.check_range(&ctx, result_flags_ptr as u32 as usize, 2)?; + let mut buffer = Vec::new(); + buffer.try_reserve_exact(iovecs.byte_len).map_err(|_| NOMEM)?; + buffer.resize(iovecs.byte_len, 0); + let descriptor = state(&ctx)?.descriptor(fd)?; + descriptor.require_rights(RIGHT_FD_READ)?; + let mut recv_flags = rustix::net::RecvFlags::empty(); + if flags & 1 != 0 { + recv_flags |= rustix::net::RecvFlags::PEEK; + } + if flags & 2 != 0 { + recv_flags |= rustix::net::RecvFlags::WAITALL; + } + let (received, truncated) = match &descriptor.resource { + Resource::TcpStream(stream) => { + (rustix::net::recv(stream, &mut buffer[..], recv_flags).map_err(Errno::from)?.1, false) + } + Resource::UdpSocket(socket) => { + let mut slices = [IoSliceMut::new(&mut buffer)]; + let mut control = rustix::net::RecvAncillaryBuffer::default(); + let message = rustix::net::recvmsg(socket, &mut slices, &mut control, recv_flags).map_err(Errno::from)?; + (message.bytes, message.flags.contains(rustix::net::ReturnFlags::TRUNC)) + } + _ => return Ok(NOTSOCK), + }; + let written = received; + memory.scatter(ctx.store_mut(), &iovecs, &buffer[..written])?; + memory.write(ctx.store_mut(), data_len_ptr, &(written as u32).to_le_bytes())?; + let result_flags = u16::from(truncated); + Ok(memory + .write(ctx.store_mut(), result_flags_ptr, &result_flags.to_le_bytes()) + .map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn sock_send( + mut ctx: FuncContext<'_>, + (fd, iovecs_ptr, iovecs_len, flags, data_len_ptr): (i32, i32, i32, i32, i32), +) -> WasiResult<Errno> { + if flags != 0 { + return Ok(INVAL); + } + let memory = GuestMemory::new(&ctx)?; + let iovecs = memory.read_iovecs(&ctx, iovecs_ptr, iovecs_len)?; + memory.check_range(&ctx, data_len_ptr as u32 as usize, 4)?; + let data = memory.gather(&ctx, &iovecs)?; + let descriptor = state(&ctx)?.descriptor(fd)?; + descriptor.require_rights(RIGHT_FD_WRITE)?; + let sent = match &descriptor.resource { + Resource::TcpStream(stream) => { + let mut stream = stream; + stream.write(&data) + } + Resource::UdpSocket(socket) => socket.send(&data), + _ => return Ok(NOTSOCK), + } + .map_err(|error| io_errno(&error))?; + Ok(memory + .write(ctx.store_mut(), data_len_ptr, &(sent as u32).to_le_bytes()) + .map_or_else(|errno| errno, |()| SUCCESS)) +} + +pub(super) fn sock_shutdown(ctx: FuncContext<'_>, (fd, how): (i32, i32)) -> WasiResult<Errno> { + let how = match how { + 1 => rustix::net::Shutdown::Read, + 2 => rustix::net::Shutdown::Write, + 3 => rustix::net::Shutdown::Both, + _ => return Ok(INVAL), + }; + let descriptor = state(&ctx)?.descriptor(fd)?; + descriptor.require_rights(RIGHT_SOCK_SHUTDOWN)?; + let result = match &descriptor.resource { + Resource::TcpStream(stream) => rustix::net::shutdown(stream, how), + Resource::UdpSocket(socket) => rustix::net::shutdown(socket, how), + _ => return Ok(NOTSOCK), + }; + Ok(result.map_or_else(Errno::from, |()| SUCCESS)) +} diff --git a/crates/wasi/src/p1/memory.rs b/crates/wasi/src/p1/memory.rs new file mode 100644 index 0000000..38b4c6a --- /dev/null +++ b/crates/wasi/src/p1/memory.rs @@ -0,0 +1,115 @@ +use tinywasm::types::MemoryArch; +use tinywasm::{Error, FuncContext, Memory, Store}; + +use super::abi::{Errno, FAULT, INVAL, NOMEM}; + +const MAX_IOVECS: usize = 1024; +const MAX_IO_BYTES: usize = 16 * 1024 * 1024; + +/// Provides checked access to a guest's wasm32 memory. +pub(super) struct GuestMemory(Memory); + +/// A bounded and validated guest iovec array. +pub(super) struct GuestIovecs { + pub(super) entries: Vec<(usize, usize)>, + pub(super) byte_len: usize, +} + +impl GuestMemory { + /// Finds and validates the guest's exported memory. + pub(super) fn new(ctx: &FuncContext<'_>) -> tinywasm::Result<Self> { + let memory = ctx.memory("memory")?; + if memory.ty(ctx.store())?.arch() != MemoryArch::I32 { + return Err(Error::UnsupportedFeature("WASI Preview 1 requires wasm32 memory")); + } + Ok(Self(memory)) + } + + /// Reads bytes using a wasm32 pointer and length. + pub(super) fn read(&self, store: &Store, pointer: i32, len: i32) -> Result<Vec<u8>, Errno> { + let len = len as u32 as usize; + self.read_at(store, pointer as u32 as usize, len) + } + + /// Reads bytes using host-sized offsets. + pub(super) fn read_at(&self, store: &Store, offset: usize, len: usize) -> Result<Vec<u8>, Errno> { + if !self.is_valid_range(store, offset, len) { + return Err(FAULT); + } + let mut bytes = Vec::new(); + bytes.try_reserve_exact(len).map_err(|_| NOMEM)?; + bytes.resize(len, 0); + self.0.read_exact(store, offset, &mut bytes).map_err(|_| FAULT)?; + Ok(bytes) + } + + /// Writes bytes using a wasm32 pointer. + pub(super) fn write(&self, store: &mut Store, pointer: i32, bytes: &[u8]) -> Result<(), Errno> { + self.write_at(store, pointer as u32 as usize, bytes) + } + + /// Writes bytes using a host-sized offset. + pub(super) fn write_at(&self, store: &mut Store, offset: usize, bytes: &[u8]) -> Result<(), Errno> { + self.check_range(store, offset, bytes.len())?; + self.0.copy_from_slice(store, offset, bytes).map_err(|_| FAULT) + } + + /// Validates that a guest memory range is accessible. + pub(super) fn check_range(&self, store: &Store, offset: usize, len: usize) -> Result<(), Errno> { + if self.is_valid_range(store, offset, len) { Ok(()) } else { Err(FAULT) } + } + + /// Reads and validates a guest iovec array. + pub(super) fn read_iovecs(&self, store: &Store, pointer: i32, count: i32) -> Result<GuestIovecs, Errno> { + let count = count as u32 as usize; + if count > MAX_IOVECS { + return Err(INVAL); + } + let table_len = count.checked_mul(8).ok_or(INVAL)?; + let table = self.read_at(store, pointer as u32 as usize, table_len)?; + let mut total = 0usize; + let mut entries = Vec::new(); + entries.try_reserve_exact(count).map_err(|_| NOMEM)?; + for entry in table.as_chunks::<8>().0 { + let offset = u32::from_le_bytes(entry[..4].try_into().expect("iovec field")) as usize; + let len = u32::from_le_bytes(entry[4..].try_into().expect("iovec field")) as usize; + total = total.checked_add(len).ok_or(INVAL)?; + if total > MAX_IO_BYTES || !self.is_valid_range(store, offset, len) { + return Err(if total > MAX_IO_BYTES { INVAL } else { FAULT }); + } + entries.push((offset, len)); + } + Ok(GuestIovecs { entries, byte_len: total }) + } + + /// Copies guest iovec contents into one contiguous buffer. + pub(super) fn gather(&self, store: &Store, iovecs: &GuestIovecs) -> Result<Vec<u8>, Errno> { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(iovecs.byte_len).map_err(|_| NOMEM)?; + bytes.resize(iovecs.byte_len, 0); + let mut destination = 0; + for &(offset, len) in &iovecs.entries { + self.0.read_exact(store, offset, &mut bytes[destination..destination + len]).map_err(|_| FAULT)?; + destination += len; + } + Ok(bytes) + } + + /// Copies one contiguous buffer into guest iovecs. + pub(super) fn scatter(&self, store: &mut Store, iovecs: &GuestIovecs, bytes: &[u8]) -> Result<(), Errno> { + let mut source = 0; + for &(offset, len) in &iovecs.entries { + let len = len.min(bytes.len() - source); + self.write_at(store, offset, &bytes[source..source + len])?; + source += len; + if source == bytes.len() { + break; + } + } + Ok(()) + } + + fn is_valid_range(&self, store: &Store, offset: usize, len: usize) -> bool { + self.0.len(store).ok().is_some_and(|memory_len| offset.checked_add(len).is_some_and(|end| end <= memory_len)) + } +} diff --git a/crates/wasi/src/p1/mod.rs b/crates/wasi/src/p1/mod.rs new file mode 100644 index 0000000..8a852e8 --- /dev/null +++ b/crates/wasi/src/p1/mod.rs @@ -0,0 +1,22 @@ +//! Synchronous WASI Preview 1 command support. + +mod abi; +mod ctx; +mod imports; +mod memory; + +pub use ctx::{WasiCtx, WasiCtxError}; + +use tinywasm::Imports; + +/// Creates a new [`Imports`] object with the WASI Preview 1 namespace registered. +pub fn imports() -> Imports { + let mut imports = Imports::new(); + register(&mut imports); + imports +} + +/// Registers the frozen WASI Preview 1 namespace on an [`Imports`] object. +pub fn register(imports: &mut Imports) { + self::imports::register(imports); +} diff --git a/crates/wasi/tests/p1.rs b/crates/wasi/tests/p1.rs new file mode 100644 index 0000000..e41ca39 --- /dev/null +++ b/crates/wasi/tests/p1.rs @@ -0,0 +1,357 @@ +use tinywasm::{Imports, ModuleInstance, Store}; +use tinywasm_wasi::p1::{WasiCtx, imports, register}; + +struct TempDir(std::path::PathBuf); + +impl TempDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "tinywasm-wasi-{name}-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir(&path).unwrap(); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn module(source: &str) -> tinywasm::Module { + tinywasm::parse_bytes(&wat::parse_str(source).unwrap()).unwrap() +} + +#[test] +fn links_the_frozen_preview1_surface() -> tinywasm::Result<()> { + let module = module( + r#"(module + (import "wasi_snapshot_preview1" "clock_res_get" (func (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_advise" (func (param i32 i64 i64 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_allocate" (func (param i32 i64 i64) (result i32))) + (import "wasi_snapshot_preview1" "fd_close" (func (param i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_datasync" (func (param i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_fdstat_set_flags" (func (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_fdstat_set_rights" (func (param i32 i64 i64) (result i32))) + (import "wasi_snapshot_preview1" "fd_filestat_set_size" (func (param i32 i64) (result i32))) + (import "wasi_snapshot_preview1" "fd_filestat_set_times" (func (param i32 i64 i64 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_pread" (func (param i32 i32 i32 i64 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_pwrite" (func (param i32 i32 i32 i64 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_readdir" (func (param i32 i32 i32 i64 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_renumber" (func (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_seek" (func (param i32 i64 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_sync" (func (param i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_tell" (func (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_create_directory" (func (param i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_filestat_get" (func (param i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_filestat_set_times" (func (param i32 i32 i32 i32 i64 i64 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_link" (func (param i32 i32 i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_readlink" (func (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_remove_directory" (func (param i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_rename" (func (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_symlink" (func (param i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_unlink_file" (func (param i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "poll_oneoff" (func (param i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "proc_raise" (func (param i32) (result i32))) + (import "wasi_snapshot_preview1" "sched_yield" (func (result i32))) + (import "wasi_snapshot_preview1" "sock_accept" (func (param i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_recv" (func (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_send" (func (param i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_shutdown" (func (param i32 i32) (result i32))))"#, + ); + let mut store = Store::default().with_state(WasiCtx::new()); + let mut imports = Imports::new(); + register(&mut imports); + ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + Ok(()) +} + +#[test] +fn writes_arguments_and_environment() -> tinywasm::Result<()> { + let module = module( + r#"(module + (import "wasi_snapshot_preview1" "args_sizes_get" (func $args_sizes_get (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "args_get" (func $args_get (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "environ_sizes_get" (func $environ_sizes_get (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "environ_get" (func $environ_get (param i32 i32) (result i32))) + (memory (export "memory") 1) + (func (export "run") (result i32) + i32.const 0 i32.const 4 call $args_sizes_get drop + i32.const 8 i32.const 32 call $args_get drop + i32.const 16 i32.const 20 call $environ_sizes_get drop + i32.const 24 i32.const 48 call $environ_get))"#, + ); + let wasi = WasiCtx::new().with_args(["app.wasm", "one"]).unwrap().with_env([("MODE", "test")]).unwrap(); + let mut store = Store::default().with_state(wasi); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0); + + let memory = instance.memory("memory")?; + let mut sizes = [0; 24]; + memory.read_exact(&store, 0, &mut sizes)?; + assert_eq!(u32::from_le_bytes(sizes[0..4].try_into().unwrap()), 2); + assert_eq!(u32::from_le_bytes(sizes[4..8].try_into().unwrap()), 13); + assert_eq!(u32::from_le_bytes(sizes[16..20].try_into().unwrap()), 1); + assert_eq!(u32::from_le_bytes(sizes[20..24].try_into().unwrap()), 10); + assert_eq!(memory.read_vec(&store, 32, 13)?, b"app.wasm\0one\0"); + assert_eq!(memory.read_vec(&store, 48, 10)?, b"MODE=test\0"); + Ok(()) +} + +#[test] +fn handles_process_exit_and_unsupported_raise() -> tinywasm::Result<()> { + let exit_module = module( + r#"(module + (import "wasi_snapshot_preview1" "proc_exit" (func $proc_exit (param i32))) + (func (export "_start") + i32.const 7 + call $proc_exit + unreachable))"#, + ); + let mut store = Store::default().with_state(WasiCtx::new()); + let instance = ModuleInstance::instantiate(&mut store, &exit_module, Some(&imports()))?; + assert!(instance.func::<(), ()>(&store, "_start")?.call(&mut store, ()).is_err()); + let wasi = store.state_mut::<WasiCtx>().unwrap(); + assert_eq!(wasi.exit_status(), Some(7)); + assert_eq!(wasi.take_exit_status(), Some(7)); + assert_eq!(wasi.exit_status(), None); + + let raise_module = module( + r#"(module + (import "wasi_snapshot_preview1" "proc_raise" (func $proc_raise (param i32) (result i32))) + (func (export "run") (result i32) + i32.const 15 call $proc_raise))"#, + ); + let mut store = Store::default().with_state(WasiCtx::new()); + let instance = ModuleInstance::instantiate(&mut store, &raise_module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 58); + Ok(()) +} + +#[test] +fn uses_preopened_files_and_enforces_descriptor_rights() -> tinywasm::Result<()> { + let temp = TempDir::new("preopen-rights"); + std::fs::write(temp.0.join("hello.txt"), b"hello").unwrap(); + let read_module = module( + r#"(module + (import "wasi_snapshot_preview1" "fd_prestat_get" (func $prestat (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_prestat_dir_name" (func $prestat_name (param i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_read" (func $read (param i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_filestat_get" (func $stat (param i32 i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 0) "\c8\00\00\00\05\00\00\00") + (data (i32.const 100) "hello.txt") + (func (export "run") (result i32) + i32.const 3 i32.const 20 call $prestat drop + i32.const 3 i32.const 32 i32.const 16 call $prestat_name drop + i32.const 3 i32.const 1 i32.const 100 i32.const 9 i32.const 0 + i64.const 2097154 i64.const 0 i32.const 0 i32.const 12 call $open drop + i32.const 12 i32.load i32.const 0 i32.const 1 i32.const 16 call $read drop + i32.const 12 i32.load i32.const 256 call $stat))"#, + ); + let wasi = WasiCtx::new().preopen_dir(&temp.0, "/sandbox").unwrap(); + let mut store = Store::default().with_state(wasi); + let instance = ModuleInstance::instantiate(&mut store, &read_module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0); + let memory = instance.memory("memory")?; + assert_eq!(memory.read_vec(&store, 32, 8)?, b"/sandbox"); + assert_eq!(memory.read_vec(&store, 200, 5)?, b"hello"); + assert_eq!(memory.read_vec(&store, 256 + 16, 1)?, [4]); + let stat = memory.read_vec(&store, 256, 64)?; + assert_eq!(u64::from_le_bytes(stat[32..40].try_into().unwrap()), 5); + + let rights_module = module( + r#"(module + (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_fdstat_set_rights" (func $rights (param i32 i64 i64) (result i32))) + (import "wasi_snapshot_preview1" "fd_read" (func $read (param i32 i32 i32 i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 0) "\80\00\00\00\01\00\00\00") + (data (i32.const 32) "hello.txt") + (func (export "run") (result i32) + i32.const 3 i32.const 1 i32.const 32 i32.const 9 i32.const 0 + i64.const 2 i64.const 0 i32.const 0 i32.const 64 call $open drop + i32.const 64 i32.load i64.const 0 i64.const 0 call $rights drop + i32.const 64 i32.load i32.const 0 i32.const 1 i32.const 68 call $read))"#, + ); + let wasi = WasiCtx::new().preopen_dir(&temp.0, "/").unwrap(); + let mut store = Store::default().with_state(wasi); + let instance = ModuleInstance::instantiate(&mut store, &rights_module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 76); + Ok(()) +} + +#[test] +fn prevents_preopen_capability_escape() -> tinywasm::Result<()> { + let parent = TempDir::new("escape"); + let sandbox = parent.0.join("sandbox"); + std::fs::create_dir(&sandbox).unwrap(); + std::fs::write(parent.0.join("outside.txt"), b"secret").unwrap(); + let module = module( + r#"(module + (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 32) "../outside.txt") + (func (export "run") (result i32) + i32.const 3 i32.const 1 i32.const 32 i32.const 14 i32.const 0 + i64.const 2 i64.const 0 i32.const 0 i32.const 0 call $open))"#, + ); + let mut store = Store::default().with_state(WasiCtx::new().preopen_dir(&sandbox, "/").unwrap()); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 76); + assert_eq!(std::fs::read(parent.0.join("outside.txt")).unwrap(), b"secret"); + Ok(()) +} + +#[test] +fn provides_clocks_randomness_and_timer_polling() -> tinywasm::Result<()> { + let module = module( + r#"(module + (import "wasi_snapshot_preview1" "clock_time_get" (func $clock (param i32 i64 i32) (result i32))) + (import "wasi_snapshot_preview1" "random_get" (func $random (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "poll_oneoff" (func $poll (param i32 i32 i32 i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 0) "\2a\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\01\00\00\00\00\00\00\00\40\42\0f\00\00\00\00\00\01\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00") + (func (export "run") (result i32) + i32.const 0 i32.const 64 i32.const 1 i32.const 128 call $poll drop + i32.const 0 i64.const 1 i32.const 160 call $clock drop + i32.const 1 i64.const 1 i32.const 168 call $clock drop + i32.const 192 i32.const 32 call $random))"#, + ); + let mut store = Store::default().with_state(WasiCtx::new()); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0); + let memory = instance.memory("memory")?; + let event = memory.read_vec(&store, 64, 32)?; + assert_eq!(u64::from_le_bytes(event[0..8].try_into().unwrap()), 42); + assert_eq!(u16::from_le_bytes(event[8..10].try_into().unwrap()), 0); + assert_eq!(event[10], 0); + assert_eq!(memory.read_vec(&store, 128, 4)?, 1_u32.to_le_bytes()); + assert_ne!(u64::from_le_bytes(memory.read_vec(&store, 160, 8)?.try_into().unwrap()), 0); + assert!(memory.read_vec(&store, 192, 32)?.iter().any(|byte| *byte != 0)); + Ok(()) +} + +#[test] +fn polls_accepts_and_uses_tcp_streams() -> tinywasm::Result<()> { + use std::io::{Read, Write}; + + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let peer = std::thread::spawn(move || { + let mut stream = std::net::TcpStream::connect(address).unwrap(); + stream.write_all(b"hello").unwrap(); + let mut reply = [0; 5]; + stream.read_exact(&mut reply).unwrap(); + reply + }); + let module = module( + r#"(module + (import "wasi_snapshot_preview1" "poll_oneoff" (func $poll (param i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_accept" (func $accept (param i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_recv" (func $recv (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_send" (func $send (param i32 i32 i32 i32 i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 0) "\64\00\00\00\05\00\00\00\78\00\00\00\05\00\00\00") + (data (i32.const 120) "world") + (data (i32.const 160) "\2a\00\00\00\00\00\00\00\01\00\00\00\00\00\00\00\03\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00") + (func (export "run") (result i32) + i32.const 160 i32.const 224 i32.const 1 i32.const 256 call $poll drop + i32.const 3 i32.const 0 i32.const 32 call $accept drop + i32.const 32 i32.load i32.const 0 i32.const 1 i32.const 0 i32.const 16 i32.const 20 call $recv drop + i32.const 32 i32.load i32.const 8 i32.const 1 i32.const 0 i32.const 24 call $send))"#, + ); + let mut wasi = WasiCtx::new(); + assert_eq!(wasi.insert_tcp_listener(listener).unwrap(), 3); + let mut store = Store::default().with_state(wasi); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0); + let memory = instance.memory("memory")?; + let event = memory.read_vec(&store, 224, 32)?; + assert_eq!(u64::from_le_bytes(event[0..8].try_into().unwrap()), 42); + assert_eq!(event[10], 1); + assert_eq!(memory.read_vec(&store, 256, 4)?, 1_u32.to_le_bytes()); + assert_eq!(memory.read_vec(&store, 100, 5)?, b"hello"); + assert_eq!(memory.read_vec(&store, 16, 4)?, 5_u32.to_le_bytes()); + assert_eq!(memory.read_vec(&store, 24, 4)?, 5_u32.to_le_bytes()); + assert_eq!(peer.join().unwrap(), *b"world"); + Ok(()) +} + +#[test] +fn sends_and_receives_udp_datagrams() -> tinywasm::Result<()> { + let socket = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let peer = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + socket.connect(peer.local_addr().unwrap()).unwrap(); + peer.connect(socket.local_addr().unwrap()).unwrap(); + peer.send(b"hello!").unwrap(); + let module = module( + r#"(module + (import "wasi_snapshot_preview1" "fd_fdstat_set_flags" (func $set_flags (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_recv" (func $recv (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "sock_send" (func $send (param i32 i32 i32 i32 i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 0) "\64\00\00\00\05\00\00\00\78\00\00\00\05\00\00\00") + (data (i32.const 120) "world") + (func (export "run") (result i32) + i32.const 3 i32.const 0 i32.const 1 i32.const 0 i32.const 16 i32.const 20 call $recv drop + i32.const 3 i32.const 8 i32.const 1 i32.const 0 i32.const 24 call $send) + (func (export "nonblocking_recv") (result i32) + i32.const 3 i32.const 4 call $set_flags drop + i32.const 3 i32.const 0 i32.const 1 i32.const 0 i32.const 16 i32.const 20 call $recv))"#, + ); + let mut wasi = WasiCtx::new(); + assert_eq!(wasi.insert_udp_socket(socket).unwrap(), 3); + let mut store = Store::default().with_state(wasi); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0); + let memory = instance.memory("memory")?; + assert_eq!(memory.read_vec(&store, 100, 5)?, b"hello"); + assert_eq!(memory.read_vec(&store, 20, 2)?, 1_u16.to_le_bytes()); + let mut reply = [0; 5]; + peer.recv(&mut reply).unwrap(); + assert_eq!(reply, *b"world"); + assert_eq!(instance.func::<(), i32>(&store, "nonblocking_recv")?.call(&mut store, ())?, 6); + Ok(()) +} + +#[test] +fn performs_descriptor_io_and_lifecycle_operations() -> tinywasm::Result<()> { + let temp = TempDir::new("descriptor-lifecycle"); + let module = module( + r#"(module + (import "wasi_snapshot_preview1" "path_open" (func $open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_write" (func $write (param i32 i32 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_tell" (func $tell (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_seek" (func $seek (param i32 i64 i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_renumber" (func $renumber (param i32 i32) (result i32))) + (import "wasi_snapshot_preview1" "fd_close" (func $close (param i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 0) "\80\00\00\00\05\00\00\00\85\00\00\00\01\00\00\00") + (data (i32.const 32) "data") + (data (i32.const 128) "hello!") + (func (export "run") (result i32) + i32.const 3 i32.const 1 i32.const 32 i32.const 4 i32.const 9 + i64.const 100 i64.const 0 i32.const 0 i32.const 64 call $open drop + i32.const 64 i32.load i32.const 0 i32.const 1 i32.const 68 call $write drop + i32.const 64 i32.load i32.const 72 call $tell drop + i32.const 64 i32.load i64.const 1 i32.const 0 i32.const 80 call $seek drop + i32.const 64 i32.load i32.const 10 call $renumber drop + i32.const 10 i32.const 8 i32.const 1 i32.const 88 call $write drop + i32.const 10 call $close))"#, + ); + let mut store = Store::default().with_state(WasiCtx::new().preopen_dir(&temp.0, "/").unwrap()); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?; + assert_eq!(instance.func::<(), i32>(&store, "run")?.call(&mut store, ())?, 0); + let memory = instance.memory("memory")?; + assert_eq!(memory.read_vec(&store, 68, 4)?, 5_u32.to_le_bytes()); + assert_eq!(memory.read_vec(&store, 72, 8)?, 5_u64.to_le_bytes()); + assert_eq!(memory.read_vec(&store, 80, 8)?, 1_u64.to_le_bytes()); + assert_eq!(memory.read_vec(&store, 88, 4)?, 1_u32.to_le_bytes()); + assert_eq!(std::fs::read(temp.0.join("data")).unwrap(), b"h!llo"); + Ok(()) +} |
