summaryrefslogtreecommitdiff
path: root/crates/wasi/src/p1/imports
diff options
context:
space:
mode:
authorHenry <mail@henrygressmann.de>2026-09-15 15:23:11 +0200
committerHenry <mail@henrygressmann.de>2026-09-15 15:27:00 +0200
commitdc8e5732d71b6f66e730b090ab02bdccc69ec888 (patch)
tree1c48f5b6d785517fbccf7fb62806bb3ec6c22b2d /crates/wasi/src/p1/imports
parent741955aed21c814a0805386a4f9be997c2eb1199 (diff)
feat: initial wasi p1 implementation
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/wasi/src/p1/imports')
-rw-r--r--crates/wasi/src/p1/imports/clock.rs28
-rw-r--r--crates/wasi/src/p1/imports/command.rs72
-rw-r--r--crates/wasi/src/p1/imports/fd.rs423
-rw-r--r--crates/wasi/src/p1/imports/mod.rs101
-rw-r--r--crates/wasi/src/p1/imports/path.rs258
-rw-r--r--crates/wasi/src/p1/imports/poll.rs219
-rw-r--r--crates/wasi/src/p1/imports/process.rs20
-rw-r--r--crates/wasi/src/p1/imports/random.rs25
-rw-r--r--crates/wasi/src/p1/imports/sock.rs124
9 files changed, 1270 insertions, 0 deletions
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, &timestamp.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, &times).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))
+}