diff --git a/Cargo.lock b/Cargo.lock index fe78d5ade1c..748f1311862 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -280,7 +280,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6358dedf60f4d9b8db43ad187391afe959746101346fe51bb978126bec61dfb" dependencies = [ "clap 3.2.17", - "heck", + "heck 0.4.0", "indexmap", "log", "proc-macro2", @@ -382,7 +382,7 @@ version = "3.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13547f7012c01ab4a0e8f8967730ada8f9fdf419e8b6c792788f39cf4e46eefa" dependencies = [ - "heck", + "heck 0.4.0", "proc-macro-error", "proc-macro2", "quote", @@ -1133,6 +1133,15 @@ dependencies = [ "ahash", ] +[[package]] +name = "heck" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "heck" version = "0.4.0" @@ -1185,6 +1194,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "id-arena" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005" + [[package]] name = "ident_case" version = "1.0.1" @@ -1798,6 +1813,17 @@ dependencies = [ "syn", ] +[[package]] +name = "pulldown-cmark" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffade02495f22453cd593159ea2f59827aae7f53fa8323f756799b670881dcf8" +dependencies = [ + "bitflags", + "memchr", + "unicase", +] + [[package]] name = "quote" version = "1.0.21" @@ -2590,6 +2616,21 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" + [[package]] name = "toml" version = "0.5.9" @@ -2724,12 +2765,33 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" +[[package]] +name = "unicode-normalization" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854cbdc4f7bc6ae19c820d44abdc3277ac3e1b2b93db20a636825d9322fb60e6" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99" + [[package]] name = "unicode-width" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" +[[package]] +name = "unicode-xid" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" + [[package]] name = "unix_mode" version = "0.1.3" @@ -3293,6 +3355,7 @@ dependencies = [ "wasmer-vnet", "wasmer-wasi-local-networking", "wasmer-wasi-types", + "wasmer-wasi-types-generated", "winapi", ] @@ -3328,6 +3391,16 @@ dependencies = [ "time", "wasmer-derive", "wasmer-types", + "wasmer-wasi-types-generated", +] + +[[package]] +name = "wasmer-wasi-types-generated" +version = "3.0.0-beta" +dependencies = [ + "wasmer-derive", + "wasmer-types", + "wit-bindgen-gen-rust-wasm", ] [[package]] @@ -3665,6 +3738,46 @@ version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" +[[package]] +name = "wit-bindgen-gen-core" +version = "0.1.0" +source = "git+https://github.com/wasmerio/wit-bindgen.git?branch=main#005a9e6d5befe4652c0e6e05578b245ab96b3cea" +dependencies = [ + "anyhow", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-gen-rust" +version = "0.1.0" +source = "git+https://github.com/wasmerio/wit-bindgen.git?branch=main#005a9e6d5befe4652c0e6e05578b245ab96b3cea" +dependencies = [ + "heck 0.3.3", + "wit-bindgen-gen-core", +] + +[[package]] +name = "wit-bindgen-gen-rust-wasm" +version = "0.1.0" +source = "git+https://github.com/wasmerio/wit-bindgen.git?branch=main#005a9e6d5befe4652c0e6e05578b245ab96b3cea" +dependencies = [ + "heck 0.3.3", + "wit-bindgen-gen-core", + "wit-bindgen-gen-rust", +] + +[[package]] +name = "wit-parser" +version = "0.1.0" +source = "git+https://github.com/wasmerio/wit-bindgen.git?branch=main#005a9e6d5befe4652c0e6e05578b245ab96b3cea" +dependencies = [ + "anyhow", + "id-arena", + "pulldown-cmark", + "unicode-normalization", + "unicode-xid", +] + [[package]] name = "x11-dl" version = "2.20.0" diff --git a/Cargo.toml b/Cargo.toml index 6ee42dd2c37..3cb8f29b56e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,7 @@ members = [ "lib/vm", "lib/wasi", "lib/wasi-types", + "lib/wasi-types-generated", "lib/wasi-experimental-io-devices", "lib/wasi-local-networking", "lib/types", diff --git a/lib/api/src/js/externals/memory_view.rs b/lib/api/src/js/externals/memory_view.rs index 45863229d5f..a219572207e 100644 --- a/lib/api/src/js/externals/memory_view.rs +++ b/lib/api/src/js/externals/memory_view.rs @@ -58,6 +58,35 @@ impl<'a> MemoryView<'a> { self.size } + // TODO: do we want a proper implementation here instead? + /// Retrieve a slice of the memory contents. + /// + /// # Safety + /// + /// Until the returned slice is dropped, it is undefined behaviour to + /// modify the memory contents in any way including by calling a wasm + /// function that writes to the memory or by resizing the memory. + #[doc(hidden)] + pub unsafe fn data_unchecked(&self) -> &[u8] { + unimplemented!("direct data pointer access is not possible in JavaScript"); + } + + // TODO: do we want a proper implementation here instead? + /// Retrieve a mutable slice of the memory contents. + /// + /// # Safety + /// + /// This method provides interior mutability without an UnsafeCell. Until + /// the returned value is dropped, it is undefined behaviour to read or + /// write to the pointed-to memory in any way except through this slice, + /// including by calling a wasm function that reads the memory contents or + /// by resizing this Memory. + #[allow(clippy::mut_from_ref)] + #[doc(hidden)] + pub unsafe fn data_unchecked_mut(&self) -> &mut [u8] { + unimplemented!("direct data pointer access is not possible in JavaScript"); + } + /// Returns the size (in [`Pages`]) of the `Memory`. /// /// # Example diff --git a/lib/types/src/value.rs b/lib/types/src/value.rs index 2347832cc03..e07d2d5231e 100644 --- a/lib/types/src/value.rs +++ b/lib/types/src/value.rs @@ -98,6 +98,7 @@ macro_rules! primitives { )*) } primitives! { + bool i8 u8 i16 u16 i32 u32 diff --git a/lib/wasi-experimental-io-devices/src/link-ext.rs b/lib/wasi-experimental-io-devices/src/link-ext.rs index d549810b52c..6ebfc5ad7b5 100644 --- a/lib/wasi-experimental-io-devices/src/link-ext.rs +++ b/lib/wasi-experimental-io-devices/src/link-ext.rs @@ -5,7 +5,10 @@ use std::collections::{BTreeSet, VecDeque}; use std::convert::TryInto; use std::io::{Read, Seek, SeekFrom, Write}; use tracing::debug; -use wasmer_wasi::{types::*, WasiInodes}; +use wasmer_wasi::{ + types::{wasi::Filesize, *}, + WasiInodes, +}; use wasmer_wasi::{Fd, VirtualFile, WasiFs, WasiFsError, ALL_RIGHTS, VIRTUAL_ROOT_FD}; use minifb::{Key, KeyRepeat, MouseButton, Scale, Window, WindowOptions}; @@ -417,7 +420,7 @@ impl VirtualFile for FrameBuffer { fn size(&self) -> u64 { 0 } - fn set_len(&mut self, _new_size: __wasi_filesize_t) -> Result<(), WasiFsError> { + fn set_len(&mut self, _new_size: Filesize) -> Result<(), WasiFsError> { Ok(()) } fn unlink(&mut self) -> Result<(), WasiFsError> { diff --git a/lib/wasi-types-generated/Cargo.toml b/lib/wasi-types-generated/Cargo.toml new file mode 100644 index 00000000000..20d4b359c14 --- /dev/null +++ b/lib/wasi-types-generated/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "wasmer-wasi-types-generated" +version = "3.0.0-beta" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +wasmer-derive = { path = "../derive", version = "=3.0.0-beta" } +wasmer-types = { path = "../types", version = "=3.0.0-beta" } + +[dependencies.wit-bindgen-rust] +default-features = false +git = "https://github.com/wasmerio/wit-bindgen.git" +branch = "main" +package = "wit-bindgen-gen-rust-wasm" + +[features] +js = [] +sys = [] \ No newline at end of file diff --git a/lib/wasi-types-generated/regenerate.sh b/lib/wasi-types-generated/regenerate.sh new file mode 100755 index 00000000000..b83f7f7884e --- /dev/null +++ b/lib/wasi-types-generated/regenerate.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +BASEDIR=$(dirname "$0") + +rm -f \ + "$BASEDIR"/src/bindings.rs \ + "$BASEDIR"/src/*/bindings.rs + +# TODO: merge typenames.wit and wasi_unstable.wit + +wit-bindgen rust-wasm \ + --import \ + "$BASEDIR"/wit-clean/typenames.wit \ + --out-dir "$BASEDIR"/src/wasi + +#wit-bindgen rust-wasm --import wit/wasi-snapshot0.wit wit/wasi-filesystem.wit --out-dir . diff --git a/lib/wasi-types-generated/src/lib.rs b/lib/wasi-types-generated/src/lib.rs new file mode 100644 index 00000000000..26801020bba --- /dev/null +++ b/lib/wasi-types-generated/src/lib.rs @@ -0,0 +1,4 @@ +pub mod wasi; +pub mod wasi_filesystem; +pub mod wasi_io_typenames; +pub mod wasi_snapshot0; \ No newline at end of file diff --git a/lib/wasi-types-generated/src/wasi/bindings.rs b/lib/wasi-types-generated/src/wasi/bindings.rs new file mode 100644 index 00000000000..74825629268 --- /dev/null +++ b/lib/wasi-types-generated/src/wasi/bindings.rs @@ -0,0 +1,1731 @@ +#[allow(clippy::all)] +mod typenames { + /// Non-negative file size or length of a region within a file. + pub type Filesize = u64; + /// Timestamp in nanoseconds. + pub type Timestamp = u64; + /// A file descriptor handle. + pub type Fd = u32; + /// A reference to the offset of a directory entry. + pub type Dircookie = u64; + /// The type for the `dirent::d-namlen` field of `dirent` struct. + pub type Dirnamlen = u32; + /// File serial number that is unique within its file system. + pub type Inode = u64; + /// Identifier for a device containing a file system. Can be used in combination + /// with `inode` to uniquely identify a file or directory in the filesystem. + pub type Device = u64; + pub type Linkcount = u64; + pub type Snapshot0Linkcount = u32; + pub type Tid = u32; + pub type Pid = u32; + /// Identifiers for clocks, snapshot0 version. + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Snapshot0Clockid { + /// The clock measuring real time. Time value zero corresponds with + /// 1970-01-01T00:00:00Z. + Realtime, + /// The store-wide monotonic clock, which is defined as a clock measuring + /// real time, whose value cannot be adjusted and which cannot have negative + /// clock jumps. The epoch of this clock is undefined. The absolute time + /// value of this clock therefore has no meaning. + Monotonic, + /// The CPU-time clock associated with the current process. + ProcessCputimeId, + /// The CPU-time clock associated with the current thread. + ThreadCputimeId, + } + impl core::fmt::Debug for Snapshot0Clockid { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Snapshot0Clockid::Realtime => { + f.debug_tuple("Snapshot0Clockid::Realtime").finish() + } + Snapshot0Clockid::Monotonic => { + f.debug_tuple("Snapshot0Clockid::Monotonic").finish() + } + Snapshot0Clockid::ProcessCputimeId => { + f.debug_tuple("Snapshot0Clockid::ProcessCputimeId").finish() + } + Snapshot0Clockid::ThreadCputimeId => { + f.debug_tuple("Snapshot0Clockid::ThreadCputimeId").finish() + } + } + } + } + /// Identifiers for clocks. + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Clockid { + /// The clock measuring real time. Time value zero corresponds with + /// 1970-01-01T00:00:00Z. + Realtime, + /// The store-wide monotonic clock, which is defined as a clock measuring + /// real time, whose value cannot be adjusted and which cannot have negative + /// clock jumps. The epoch of this clock is undefined. The absolute time + /// value of this clock therefore has no meaning. + Monotonic, + } + impl core::fmt::Debug for Clockid { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Clockid::Realtime => { + f.debug_tuple("Clockid::Realtime").finish() + } + Clockid::Monotonic => { + f.debug_tuple("Clockid::Monotonic").finish() + } + } + } + } + /// Error codes returned by functions. + /// Not all of these error codes are returned by the functions provided by this + /// API; some are used in higher-level library layers, and others are provided + /// merely for alignment with POSIX. + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Errno { + /// No error occurred. System call completed successfully. + Success, + /// Argument list too long. + Toobig, + /// Permission denied. + Access, + /// Address in use. + Addrinuse, + /// Address not available. + Addrnotavail, + /// Address family not supported. + Afnosupport, + /// Resource unavailable, or operation would block. + Again, + /// Connection already in progress. + Already, + /// Bad file descriptor. + Badf, + /// Bad message. + Badmsg, + /// Device or resource busy. + Busy, + /// Operation canceled. + Canceled, + /// No child processes. + Child, + /// Connection aborted. + Connaborted, + /// Connection refused. + Connrefused, + /// Connection reset. + Connreset, + /// Resource deadlock would occur. + Deadlk, + /// Destination address required. + Destaddrreq, + /// Mathematics argument out of domain of function. + Dom, + /// Reserved. + Dquot, + /// File exists. + Exist, + /// Bad address. + Fault, + /// File too large. + Fbig, + /// Host is unreachable. + Hostunreach, + /// Identifier removed. + Idrm, + /// Illegal byte sequence. + Ilseq, + /// Operation in progress. + Inprogress, + /// Interrupted function. + Intr, + /// Invalid argument. + Inval, + /// I/O error. + Io, + /// Socket is connected. + Isconn, + /// Is a directory. + Isdir, + /// Too many levels of symbolic links. + Loop, + /// File descriptor value too large. + Mfile, + /// Too many links. + Mlink, + /// Message too large. + Msgsize, + /// Reserved. + Multihop, + /// Filename too long. + Nametoolong, + /// Network is down. + Netdown, + /// Connection aborted by network. + Netreset, + /// Network unreachable. + Netunreach, + /// Too many files open in system. + Nfile, + /// No buffer space available. + Nobufs, + /// No such device. + Nodev, + /// No such file or directory. + Noent, + /// Executable file format error. + Noexec, + /// No locks available. + Nolck, + /// Reserved. + Nolink, + /// Not enough space. + Nomem, + /// No message of the desired type. + Nomsg, + /// Protocol not available. + Noprotoopt, + /// No space left on device. + Nospc, + /// Function not supported. + Nosys, + /// The socket is not connected. + Notconn, + /// Not a directory or a symbolic link to a directory. + Notdir, + /// Directory not empty. + Notempty, + /// State not recoverable. + Notrecoverable, + /// Not a socket. + Notsock, + /// Not supported, or operation not supported on socket. + Notsup, + /// Inappropriate I/O control operation. + Notty, + /// No such device or address. + Nxio, + /// Value too large to be stored in data type. + Overflow, + /// Previous owner died. + Ownerdead, + /// Operation not permitted. + Perm, + /// Broken pipe. + Pipe, + /// Protocol error. + Proto, + /// Protocol not supported. + Protonosupport, + /// Protocol wrong type for socket. + Prototype, + /// Result too large. + Range, + /// Read-only file system. + Rofs, + /// Invalid seek. + Spipe, + /// No such process. + Srch, + /// Reserved. + Stale, + /// Connection timed out. + Timedout, + /// Text file busy. + Txtbsy, + /// Cross-device link. + Xdev, + /// Extension: Capabilities insufficient. + Notcapable, + } + impl Errno{ + pub fn name(&self) -> &'static str { + match self { + Errno::Success => "success", + Errno::Toobig => "toobig", + Errno::Access => "access", + Errno::Addrinuse => "addrinuse", + Errno::Addrnotavail => "addrnotavail", + Errno::Afnosupport => "afnosupport", + Errno::Again => "again", + Errno::Already => "already", + Errno::Badf => "badf", + Errno::Badmsg => "badmsg", + Errno::Busy => "busy", + Errno::Canceled => "canceled", + Errno::Child => "child", + Errno::Connaborted => "connaborted", + Errno::Connrefused => "connrefused", + Errno::Connreset => "connreset", + Errno::Deadlk => "deadlk", + Errno::Destaddrreq => "destaddrreq", + Errno::Dom => "dom", + Errno::Dquot => "dquot", + Errno::Exist => "exist", + Errno::Fault => "fault", + Errno::Fbig => "fbig", + Errno::Hostunreach => "hostunreach", + Errno::Idrm => "idrm", + Errno::Ilseq => "ilseq", + Errno::Inprogress => "inprogress", + Errno::Intr => "intr", + Errno::Inval => "inval", + Errno::Io => "io", + Errno::Isconn => "isconn", + Errno::Isdir => "isdir", + Errno::Loop => "loop", + Errno::Mfile => "mfile", + Errno::Mlink => "mlink", + Errno::Msgsize => "msgsize", + Errno::Multihop => "multihop", + Errno::Nametoolong => "nametoolong", + Errno::Netdown => "netdown", + Errno::Netreset => "netreset", + Errno::Netunreach => "netunreach", + Errno::Nfile => "nfile", + Errno::Nobufs => "nobufs", + Errno::Nodev => "nodev", + Errno::Noent => "noent", + Errno::Noexec => "noexec", + Errno::Nolck => "nolck", + Errno::Nolink => "nolink", + Errno::Nomem => "nomem", + Errno::Nomsg => "nomsg", + Errno::Noprotoopt => "noprotoopt", + Errno::Nospc => "nospc", + Errno::Nosys => "nosys", + Errno::Notconn => "notconn", + Errno::Notdir => "notdir", + Errno::Notempty => "notempty", + Errno::Notrecoverable => "notrecoverable", + Errno::Notsock => "notsock", + Errno::Notsup => "notsup", + Errno::Notty => "notty", + Errno::Nxio => "nxio", + Errno::Overflow => "overflow", + Errno::Ownerdead => "ownerdead", + Errno::Perm => "perm", + Errno::Pipe => "pipe", + Errno::Proto => "proto", + Errno::Protonosupport => "protonosupport", + Errno::Prototype => "prototype", + Errno::Range => "range", + Errno::Rofs => "rofs", + Errno::Spipe => "spipe", + Errno::Srch => "srch", + Errno::Stale => "stale", + Errno::Timedout => "timedout", + Errno::Txtbsy => "txtbsy", + Errno::Xdev => "xdev", + Errno::Notcapable => "notcapable", + } + } + pub fn message(&self) -> &'static str { + match self { + Errno::Success => "No error occurred. System call completed successfully.", + Errno::Toobig => "Argument list too long.", + Errno::Access => "Permission denied.", + Errno::Addrinuse => "Address in use.", + Errno::Addrnotavail => "Address not available.", + Errno::Afnosupport => "Address family not supported.", + Errno::Again => "Resource unavailable, or operation would block.", + Errno::Already => "Connection already in progress.", + Errno::Badf => "Bad file descriptor.", + Errno::Badmsg => "Bad message.", + Errno::Busy => "Device or resource busy.", + Errno::Canceled => "Operation canceled.", + Errno::Child => "No child processes.", + Errno::Connaborted => "Connection aborted.", + Errno::Connrefused => "Connection refused.", + Errno::Connreset => "Connection reset.", + Errno::Deadlk => "Resource deadlock would occur.", + Errno::Destaddrreq => "Destination address required.", + Errno::Dom => "Mathematics argument out of domain of function.", + Errno::Dquot => "Reserved.", + Errno::Exist => "File exists.", + Errno::Fault => "Bad address.", + Errno::Fbig => "File too large.", + Errno::Hostunreach => "Host is unreachable.", + Errno::Idrm => "Identifier removed.", + Errno::Ilseq => "Illegal byte sequence.", + Errno::Inprogress => "Operation in progress.", + Errno::Intr => "Interrupted function.", + Errno::Inval => "Invalid argument.", + Errno::Io => "I/O error.", + Errno::Isconn => "Socket is connected.", + Errno::Isdir => "Is a directory.", + Errno::Loop => "Too many levels of symbolic links.", + Errno::Mfile => "File descriptor value too large.", + Errno::Mlink => "Too many links.", + Errno::Msgsize => "Message too large.", + Errno::Multihop => "Reserved.", + Errno::Nametoolong => "Filename too long.", + Errno::Netdown => "Network is down.", + Errno::Netreset => "Connection aborted by network.", + Errno::Netunreach => "Network unreachable.", + Errno::Nfile => "Too many files open in system.", + Errno::Nobufs => "No buffer space available.", + Errno::Nodev => "No such device.", + Errno::Noent => "No such file or directory.", + Errno::Noexec => "Executable file format error.", + Errno::Nolck => "No locks available.", + Errno::Nolink => "Reserved.", + Errno::Nomem => "Not enough space.", + Errno::Nomsg => "No message of the desired type.", + Errno::Noprotoopt => "Protocol not available.", + Errno::Nospc => "No space left on device.", + Errno::Nosys => "Function not supported.", + Errno::Notconn => "The socket is not connected.", + Errno::Notdir => "Not a directory or a symbolic link to a directory.", + Errno::Notempty => "Directory not empty.", + Errno::Notrecoverable => "State not recoverable.", + Errno::Notsock => "Not a socket.", + Errno::Notsup => "Not supported, or operation not supported on socket.", + Errno::Notty => "Inappropriate I/O control operation.", + Errno::Nxio => "No such device or address.", + Errno::Overflow => "Value too large to be stored in data type.", + Errno::Ownerdead => "Previous owner died.", + Errno::Perm => "Operation not permitted.", + Errno::Pipe => "Broken pipe.", + Errno::Proto => "Protocol error.", + Errno::Protonosupport => "Protocol not supported.", + Errno::Prototype => "Protocol wrong type for socket.", + Errno::Range => "Result too large.", + Errno::Rofs => "Read-only file system.", + Errno::Spipe => "Invalid seek.", + Errno::Srch => "No such process.", + Errno::Stale => "Reserved.", + Errno::Timedout => "Connection timed out.", + Errno::Txtbsy => "Text file busy.", + Errno::Xdev => "Cross-device link.", + Errno::Notcapable => "Extension: Capabilities insufficient.", + } + } + } + impl core::fmt::Debug for Errno{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Errno") + .field("code", &(*self as i32)) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } + } + impl core::fmt::Display for Errno{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{} (error {})", self.name(), *self as i32)} + } + + impl std::error::Error for Errno{} + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum BusErrno { + /// No error occurred. Call completed successfully. + Success, + /// Failed during serialization + Ser, + /// Failed during deserialization + Des, + /// Invalid WAPM process + Wapm, + /// Failed to fetch the WAPM process + Fetch, + /// Failed to compile the WAPM process + Compile, + /// Invalid ABI + Abi, + /// Call was aborted + Aborted, + /// Bad handle + Badhandle, + /// Invalid topic + Topic, + /// Invalid callback + Badcb, + /// Call is unsupported + Unsupported, + /// Bad request + Badrequest, + /// Access denied + Denied, + /// Internal error has occured + Internal, + /// Memory allocation failed + Alloc, + /// Invocation has failed + Invoke, + /// Already consumed + Consumed, + /// Memory access violation + Memviolation, + /// Some other unhandled error. If you see this, it's probably a bug. + Unknown, + } + impl BusErrno{ + pub fn name(&self) -> &'static str { + match self { + BusErrno::Success => "success", + BusErrno::Ser => "ser", + BusErrno::Des => "des", + BusErrno::Wapm => "wapm", + BusErrno::Fetch => "fetch", + BusErrno::Compile => "compile", + BusErrno::Abi => "abi", + BusErrno::Aborted => "aborted", + BusErrno::Badhandle => "badhandle", + BusErrno::Topic => "topic", + BusErrno::Badcb => "badcb", + BusErrno::Unsupported => "unsupported", + BusErrno::Badrequest => "badrequest", + BusErrno::Denied => "denied", + BusErrno::Internal => "internal", + BusErrno::Alloc => "alloc", + BusErrno::Invoke => "invoke", + BusErrno::Consumed => "consumed", + BusErrno::Memviolation => "memviolation", + BusErrno::Unknown => "unknown", + } + } + pub fn message(&self) -> &'static str { + match self { + BusErrno::Success => "No error occurred. Call completed successfully.", + BusErrno::Ser => "Failed during serialization", + BusErrno::Des => "Failed during deserialization", + BusErrno::Wapm => "Invalid WAPM process", + BusErrno::Fetch => "Failed to fetch the WAPM process", + BusErrno::Compile => "Failed to compile the WAPM process", + BusErrno::Abi => "Invalid ABI", + BusErrno::Aborted => "Call was aborted", + BusErrno::Badhandle => "Bad handle", + BusErrno::Topic => "Invalid topic", + BusErrno::Badcb => "Invalid callback", + BusErrno::Unsupported => "Call is unsupported", + BusErrno::Badrequest => "Bad request", + BusErrno::Denied => "Access denied", + BusErrno::Internal => "Internal error has occured", + BusErrno::Alloc => "Memory allocation failed", + BusErrno::Invoke => "Invocation has failed", + BusErrno::Consumed => "Already consumed", + BusErrno::Memviolation => "Memory access violation", + BusErrno::Unknown => "Some other unhandled error. If you see this, it's probably a bug.", + } + } + } + impl core::fmt::Debug for BusErrno{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("BusErrno") + .field("code", &(*self as i32)) + .field("name", &self.name()) + .field("message", &self.message()) + .finish() + } + } + impl core::fmt::Display for BusErrno{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{} (error {})", self.name(), *self as i32)} + } + + impl std::error::Error for BusErrno{} + wit_bindgen_rust::bitflags::bitflags! { + /// File descriptor rights, determining which actions may be performed. + pub struct Rights: u64 { + /// The right to invoke `fd_datasync`. + /// + /// If `rights::path_open` is set, includes the right to invoke + /// `path_open` with `fdflags::dsync`. + const FD_DATASYNC = 1 << 0; + /// The right to invoke `fd_read` and `sock_recv`. + /// + /// If `rights::fd_seek` is set, includes the right to invoke `fd_pread`. + const FD_READ = 1 << 1; + /// The right to invoke `fd_seek`. This flag implies `rights::fd_tell`. + const FD_SEEK = 1 << 2; + /// The right to invoke `fd_fdstat_set_flags`. + const FD_FDSTAT_SET_FLAGS = 1 << 3; + /// The right to invoke `fd_sync`. + /// + /// If `rights::path_open` is set, includes the right to invoke + /// `path_open` with `fdflags::rsync` and `fdflags::dsync`. + const FD_SYNC = 1 << 4; + /// The right to invoke `fd_seek` in such a way that the file offset + /// remains unaltered (i.e., `whence::cur` with offset zero), or to + /// invoke `fd_tell`. + const FD_TELL = 1 << 5; + /// The right to invoke `fd_write` and `sock_send`. + /// If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`. + const FD_WRITE = 1 << 6; + /// The right to invoke `fd_advise`. + const FD_ADVISE = 1 << 7; + /// The right to invoke `fd_allocate`. + const FD_ALLOCATE = 1 << 8; + /// The right to invoke `path_create_directory`. + const PATH_CREATE_DIRECTORY = 1 << 9; + /// If `rights::path_open` is set, the right to invoke `path_open` with `oflags::creat`. + const PATH_CREATE_FILE = 1 << 10; + /// The right to invoke `path_link` with the file descriptor as the + /// source directory. + const PATH_LINK_SOURCE = 1 << 11; + /// The right to invoke `path_link` with the file descriptor as the + /// target directory. + const PATH_LINK_TARGET = 1 << 12; + /// The right to invoke `path_open`. + const PATH_OPEN = 1 << 13; + /// The right to invoke `fd_readdir`. + const FD_READDIR = 1 << 14; + /// The right to invoke `path_readlink`. + const PATH_READLINK = 1 << 15; + /// The right to invoke `path_rename` with the file descriptor as the source directory. + const PATH_RENAME_SOURCE = 1 << 16; + /// The right to invoke `path_rename` with the file descriptor as the target directory. + const PATH_RENAME_TARGET = 1 << 17; + /// The right to invoke `path_filestat_get`. + const PATH_FILESTAT_GET = 1 << 18; + /// The right to change a file's size (there is no `path_filestat_set_size`). + /// If `rights::path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`. + const PATH_FILESTAT_SET_SIZE = 1 << 19; + /// The right to invoke `path_filestat_set_times`. + const PATH_FILESTAT_SET_TIMES = 1 << 20; + /// The right to invoke `fd_filestat_get`. + const FD_FILESTAT_GET = 1 << 21; + /// The right to invoke `fd_filestat_set_size`. + const FD_FILESTAT_SET_SIZE = 1 << 22; + /// The right to invoke `fd_filestat_set_times`. + const FD_FILESTAT_SET_TIMES = 1 << 23; + /// The right to invoke `path_symlink`. + const PATH_SYMLINK = 1 << 24; + /// The right to invoke `path_remove_directory`. + const PATH_REMOVE_DIRECTORY = 1 << 25; + /// The right to invoke `path_unlink_file`. + const PATH_UNLINK_FILE = 1 << 26; + /// If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_read`. + /// If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_write`. + const POLL_FD_READWRITE = 1 << 27; + /// The right to invoke `sock_shutdown`. + const SOCK_SHUTDOWN = 1 << 28; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_ACCEPT = 1 << 29; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_CONNECT = 1 << 30; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_LISTEN = 1 << 31; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_BIND = 1 << 32; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_RECV = 1 << 33; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_SEND = 1 << 34; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_ADDR_LOCAL = 1 << 35; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_ADDR_REMOTE = 1 << 36; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_RECV_FROM = 1 << 37; + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + const SOCK_SEND_TO = 1 << 38; + } + } + impl Rights { + /// Convert from a raw integer, preserving any unknown bits. See + /// + pub fn from_bits_preserve(bits: u64) -> Self { + Self { bits } + } + } + /// The type of a file descriptor or file. + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Filetype { + /// The type of the file descriptor or file is unknown or is different from any of the other types specified. + Unknown, + /// The file descriptor or file refers to a block device inode. + BlockDevice, + /// The file descriptor or file refers to a character device inode. + CharacterDevice, + /// The file descriptor or file refers to a directory inode. + Directory, + /// The file descriptor or file refers to a regular file inode. + RegularFile, + /// The file descriptor or file refers to a datagram socket. + SocketDgram, + /// The file descriptor or file refers to a byte-stream socket. + SocketStream, + /// The file refers to a symbolic link inode. + SymbolicLink, + /// The file descriptor or file refers to a FIFO. + Fifo, + } + impl core::fmt::Debug for Filetype { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Filetype::Unknown => { + f.debug_tuple("Filetype::Unknown").finish() + } + Filetype::BlockDevice => { + f.debug_tuple("Filetype::BlockDevice").finish() + } + Filetype::CharacterDevice => { + f.debug_tuple("Filetype::CharacterDevice").finish() + } + Filetype::Directory => { + f.debug_tuple("Filetype::Directory").finish() + } + Filetype::RegularFile => { + f.debug_tuple("Filetype::RegularFile").finish() + } + Filetype::SocketDgram => { + f.debug_tuple("Filetype::SocketDgram").finish() + } + Filetype::SocketStream => { + f.debug_tuple("Filetype::SocketStream").finish() + } + Filetype::SymbolicLink => { + f.debug_tuple("Filetype::SymbolicLink").finish() + } + Filetype::Fifo => { + f.debug_tuple("Filetype::Fifo").finish() + } + } + } + } + /// A directory entry. + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Dirent { + /// The offset of the next directory entry stored in this directory. + pub d_next: Dircookie, + /// The serial number of the file referred to by this directory entry. + pub d_ino: Inode, + /// The type of the file referred to by this directory entry. + pub d_type: Filetype, + /// The length of the name of the directory entry. + pub d_namlen: Dirnamlen, + } + impl core::fmt::Debug for Dirent { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Dirent").field("d-next", &self.d_next).field("d-ino", &self.d_ino).field("d-type", &self.d_type).field("d-namlen", &self.d_namlen).finish()} + } + /// File or memory access pattern advisory information. + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Advice { + /// The application has no advice to give on its behavior with respect to the specified data. + Normal, + /// The application expects to access the specified data sequentially from lower offsets to higher offsets. + Sequential, + /// The application expects to access the specified data in a random order. + Random, + /// The application expects to access the specified data in the near future. + Willneed, + /// The application expects that it will not access the specified data in the near future. + Dontneed, + /// The application expects to access the specified data once and then not reuse it thereafter. + Noreuse, + } + impl core::fmt::Debug for Advice { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Advice::Normal => { + f.debug_tuple("Advice::Normal").finish() + } + Advice::Sequential => { + f.debug_tuple("Advice::Sequential").finish() + } + Advice::Random => { + f.debug_tuple("Advice::Random").finish() + } + Advice::Willneed => { + f.debug_tuple("Advice::Willneed").finish() + } + Advice::Dontneed => { + f.debug_tuple("Advice::Dontneed").finish() + } + Advice::Noreuse => { + f.debug_tuple("Advice::Noreuse").finish() + } + } + } + } + wit_bindgen_rust::bitflags::bitflags! { + /// File descriptor flags. + pub struct Fdflags: u8 { + /// Append mode: Data written to the file is always appended to the file's end. + const APPEND = 1 << 0; + /// Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized. + const DSYNC = 1 << 1; + /// Non-blocking mode. + const NONBLOCK = 1 << 2; + /// Synchronized read I/O operations. + const RSYNC = 1 << 3; + /// Write according to synchronized I/O file integrity completion. In + /// addition to synchronizing the data stored in the file, the implementation + /// may also synchronously update the file's metadata. + const SYNC = 1 << 4; + } + } + impl Fdflags { + /// Convert from a raw integer, preserving any unknown bits. See + /// + pub fn from_bits_preserve(bits: u8) -> Self { + Self { bits } + } + } + /// File descriptor attributes. + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Fdstat { + /// File type. + pub fs_filetype: Filetype, + /// File descriptor flags. + pub fs_flags: Fdflags, + /// Rights that apply to this file descriptor. + pub fs_rights_base: Rights, + /// Maximum set of rights that may be installed on new file descriptors that + /// are created through this file descriptor, e.g., through `path_open`. + pub fs_rights_inheriting: Rights, + } + impl core::fmt::Debug for Fdstat { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Fdstat").field("fs-filetype", &self.fs_filetype).field("fs-flags", &self.fs_flags).field("fs-rights-base", &self.fs_rights_base).field("fs-rights-inheriting", &self.fs_rights_inheriting).finish()} + } + wit_bindgen_rust::bitflags::bitflags! { + /// Which file time attributes to adjust. + pub struct Fstflags: u8 { + /// Adjust the last data access timestamp to the value stored in `filestat::atim`. + const SET_ATIM = 1 << 0; + /// Adjust the last data access timestamp to the time of clock `clockid::realtime`. + const SET_ATIM_NOW = 1 << 1; + /// Adjust the last data modification timestamp to the value stored in `filestat::mtim`. + const SET_MTIM = 1 << 2; + /// Adjust the last data modification timestamp to the time of clock `clockid::realtime`. + const SET_MTIM_NOW = 1 << 3; + } + } + impl Fstflags { + /// Convert from a raw integer, preserving any unknown bits. See + /// + pub fn from_bits_preserve(bits: u8) -> Self { + Self { bits } + } + } + wit_bindgen_rust::bitflags::bitflags! { + /// Flags determining the method of how paths are resolved. + pub struct Lookup: u8 { + /// As long as the resolved path corresponds to a symbolic link, it is expanded. + const SYMLINK_FOLLOW = 1 << 0; + } + } + impl Lookup { + /// Convert from a raw integer, preserving any unknown bits. See + /// + pub fn from_bits_preserve(bits: u8) -> Self { + Self { bits } + } + } + wit_bindgen_rust::bitflags::bitflags! { + /// Open flags used by `path_open`. + pub struct Oflags: u8 { + /// Create file if it does not exist. + const CREATE = 1 << 0; + /// Fail if not a directory. + const DIRECTORY = 1 << 1; + /// Fail if file already exists. + const EXCL = 1 << 2; + /// Truncate file to size 0. + const TRUNC = 1 << 3; + } + } + impl Oflags { + /// Convert from a raw integer, preserving any unknown bits. See + /// + pub fn from_bits_preserve(bits: u8) -> Self { + Self { bits } + } + } + /// User-provided value that may be attached to objects that is retained when + /// extracted from the implementation. + pub type Userdata = u64; + /// Type of a subscription to an event or its occurrence. + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Eventtype { + /// The time value of clock `subscription_clock::id` has + /// reached timestamp `subscription_clock::timeout`. + Clock, + /// File descriptor `subscription_fd_readwrite::fd` has data + /// available for reading. This event always triggers for regular files. + FdRead, + /// File descriptor `subscription_fd_readwrite::fd` has capacity + /// available for writing. This event always triggers for regular files. + FdWrite, + } + impl core::fmt::Debug for Eventtype { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Eventtype::Clock => { + f.debug_tuple("Eventtype::Clock").finish() + } + Eventtype::FdRead => { + f.debug_tuple("Eventtype::FdRead").finish() + } + Eventtype::FdWrite => { + f.debug_tuple("Eventtype::FdWrite").finish() + } + } + } + } + wit_bindgen_rust::bitflags::bitflags! { + /// Flags determining how to interpret the timestamp provided in + /// `subscription-clock::timeout`. + pub struct Subclockflags: u8 { + /// If set, treat the timestamp provided in + /// `subscription-clock::timeout` as an absolute timestamp of clock + /// `subscription-clock::id`. If clear, treat the timestamp + /// provided in `subscription-clock::timeout` relative to the + /// current time value of clock `subscription-clock::id`. + const SUBSCRIPTION_CLOCK_ABSTIME = 1 << 0; + } + } + impl Subclockflags { + /// Convert from a raw integer, preserving any unknown bits. See + /// + pub fn from_bits_preserve(bits: u8) -> Self { + Self { bits } + } + } + /// The contents of a `subscription` when type is `eventtype::clock`. + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Snapshot0SubscriptionClock { + /// The user-defined unique identifier of the clock. + pub identifier: Userdata, + /// The clock against which to compare the timestamp. + pub id: Snapshot0Clockid, + /// The absolute or relative timestamp. + pub timeout: Timestamp, + /// The amount of time that the implementation may wait additionally + /// to coalesce with other events. + pub precision: Timestamp, + /// Flags specifying whether the timeout is absolute or relative + pub flags: Subclockflags, + } + impl core::fmt::Debug for Snapshot0SubscriptionClock { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Snapshot0SubscriptionClock").field("identifier", &self.identifier).field("id", &self.id).field("timeout", &self.timeout).field("precision", &self.precision).field("flags", &self.flags).finish()} + } + /// The contents of a `subscription` when type is `eventtype::clock`. + #[repr(C)] + #[derive(Copy, Clone)] + pub struct SubscriptionClock { + /// The clock against which to compare the timestamp. + pub clock_id: Clockid, + /// The absolute or relative timestamp. + pub timeout: Timestamp, + /// The amount of time that the implementation may wait additionally + /// to coalesce with other events. + pub precision: Timestamp, + /// Flags specifying whether the timeout is absolute or relative + pub flags: Subclockflags, + } + impl core::fmt::Debug for SubscriptionClock { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("SubscriptionClock").field("clock-id", &self.clock_id).field("timeout", &self.timeout).field("precision", &self.precision).field("flags", &self.flags).finish()} + } + /// Identifiers for preopened capabilities. + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Preopentype { + /// A pre-opened directory. + Dir, + } + impl core::fmt::Debug for Preopentype { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Preopentype::Dir => { + f.debug_tuple("Preopentype::Dir").finish() + } + } + } + } + wit_bindgen_rust::bitflags::bitflags! { + /// The state of the file descriptor subscribed to with + /// `eventtype::fd_read` or `eventtype::fd_write`. + pub struct Eventrwflags: u8 { + /// The peer of this socket has closed or disconnected. + const FD_READWRITE_HANGUP = 1 << 0; + } + } + impl Eventrwflags { + /// Convert from a raw integer, preserving any unknown bits. See + /// + pub fn from_bits_preserve(bits: u8) -> Self { + Self { bits } + } + } + /// The contents of an `event` for the `eventtype::fd_read` and + /// `eventtype::fd_write` variants + #[repr(C)] + #[derive(Copy, Clone)] + pub struct EventFdReadwrite { + /// The number of bytes available for reading or writing. + pub nbytes: Filesize, + /// The state of the file descriptor. + pub flags: Eventrwflags, + } + impl core::fmt::Debug for EventFdReadwrite { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("EventFdReadwrite").field("nbytes", &self.nbytes).field("flags", &self.flags).finish()} + } + /// An event that occurred. + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Event { + /// User-provided value that got attached to `subscription::userdata`. + pub userdata: Userdata, + /// If non-zero, an error that occurred while processing the subscription request. + pub error: Errno, + /// The type of the event that occurred, and the contents of the event + pub data: EventEnum, + } + impl core::fmt::Debug for Event { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Event").field("userdata", &self.userdata).field("error", &self.error).field("data", &self.data).finish()} + } + /// The contents of an `event`. + #[derive(Clone, Copy)] + pub enum EventEnum{ + FdRead(EventFdReadwrite), + FdWrite(EventFdReadwrite), + Clock, + } + impl core::fmt::Debug for EventEnum { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + EventEnum::FdRead(e) => { + f.debug_tuple("EventEnum::FdRead").field(e).finish() + } + EventEnum::FdWrite(e) => { + f.debug_tuple("EventEnum::FdWrite").field(e).finish() + } + EventEnum::Clock => { + f.debug_tuple("EventEnum::Clock").finish() + } + } + } + } + /// The contents of a `subscription`, snapshot0 version. + #[derive(Clone, Copy)] + pub enum Snapshot0SubscriptionEnum{ + Clock(Snapshot0SubscriptionClock), + Read(SubscriptionFsReadwrite), + Write(SubscriptionFsReadwrite), + } + impl core::fmt::Debug for Snapshot0SubscriptionEnum { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Snapshot0SubscriptionEnum::Clock(e) => { + f.debug_tuple("Snapshot0SubscriptionEnum::Clock").field(e).finish() + } + Snapshot0SubscriptionEnum::Read(e) => { + f.debug_tuple("Snapshot0SubscriptionEnum::Read").field(e).finish() + } + Snapshot0SubscriptionEnum::Write(e) => { + f.debug_tuple("Snapshot0SubscriptionEnum::Write").field(e).finish() + } + } + } + } + /// The contents of a `subscription`. + #[derive(Clone, Copy)] + pub enum SubscriptionEnum{ + Clock(SubscriptionClock), + Read(SubscriptionFsReadwrite), + Write(SubscriptionFsReadwrite), + } + impl core::fmt::Debug for SubscriptionEnum { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + SubscriptionEnum::Clock(e) => { + f.debug_tuple("SubscriptionEnum::Clock").field(e).finish() + } + SubscriptionEnum::Read(e) => { + f.debug_tuple("SubscriptionEnum::Read").field(e).finish() + } + SubscriptionEnum::Write(e) => { + f.debug_tuple("SubscriptionEnum::Write").field(e).finish() + } + } + } + } + /// The contents of a `subscription` when the variant is + /// `eventtype::fd_read` or `eventtype::fd_write`. + #[repr(C)] + #[derive(Copy, Clone)] + pub struct SubscriptionFsReadwrite { + /// The file descriptor on which to wait for it to become ready for reading or writing. + pub file_descriptor: Fd, + } + impl core::fmt::Debug for SubscriptionFsReadwrite { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("SubscriptionFsReadwrite").field("file-descriptor", &self.file_descriptor).finish()} + } + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Snapshot0Subscription { + pub userdata: Userdata, + pub data: Snapshot0SubscriptionEnum, + } + impl core::fmt::Debug for Snapshot0Subscription { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Snapshot0Subscription").field("userdata", &self.userdata).field("data", &self.data).finish()} + } + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Subscription { + pub userdata: Userdata, + pub data: SubscriptionEnum, + } + impl core::fmt::Debug for Subscription { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Subscription").field("userdata", &self.userdata).field("data", &self.data).finish()} + } + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Socktype { + Dgram, + Stream, + Raw, + Seqpacket, + } + impl core::fmt::Debug for Socktype { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Socktype::Dgram => { + f.debug_tuple("Socktype::Dgram").finish() + } + Socktype::Stream => { + f.debug_tuple("Socktype::Stream").finish() + } + Socktype::Raw => { + f.debug_tuple("Socktype::Raw").finish() + } + Socktype::Seqpacket => { + f.debug_tuple("Socktype::Seqpacket").finish() + } + } + } + } + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Sockstatus { + Opening, + Opened, + Closed, + Failed, + } + impl core::fmt::Debug for Sockstatus { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Sockstatus::Opening => { + f.debug_tuple("Sockstatus::Opening").finish() + } + Sockstatus::Opened => { + f.debug_tuple("Sockstatus::Opened").finish() + } + Sockstatus::Closed => { + f.debug_tuple("Sockstatus::Closed").finish() + } + Sockstatus::Failed => { + f.debug_tuple("Sockstatus::Failed").finish() + } + } + } + } + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Sockoption { + Noop, + ReusePort, + ReuseAddr, + NoDelay, + DontRoute, + OnlyV6, + Broadcast, + MulticastLoopV4, + MulticastLoopV6, + Promiscuous, + Listening, + LastError, + KeepAlive, + Linger, + OobInline, + RecvBufSize, + SendBufSize, + RecvLowat, + SendLowat, + RecvTimeout, + SendTimeout, + ConnectTimeout, + AcceptTimeout, + Ttl, + MulticastTtlV4, + Type, + Proto, + } + impl core::fmt::Debug for Sockoption { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Sockoption::Noop => { + f.debug_tuple("Sockoption::Noop").finish() + } + Sockoption::ReusePort => { + f.debug_tuple("Sockoption::ReusePort").finish() + } + Sockoption::ReuseAddr => { + f.debug_tuple("Sockoption::ReuseAddr").finish() + } + Sockoption::NoDelay => { + f.debug_tuple("Sockoption::NoDelay").finish() + } + Sockoption::DontRoute => { + f.debug_tuple("Sockoption::DontRoute").finish() + } + Sockoption::OnlyV6 => { + f.debug_tuple("Sockoption::OnlyV6").finish() + } + Sockoption::Broadcast => { + f.debug_tuple("Sockoption::Broadcast").finish() + } + Sockoption::MulticastLoopV4 => { + f.debug_tuple("Sockoption::MulticastLoopV4").finish() + } + Sockoption::MulticastLoopV6 => { + f.debug_tuple("Sockoption::MulticastLoopV6").finish() + } + Sockoption::Promiscuous => { + f.debug_tuple("Sockoption::Promiscuous").finish() + } + Sockoption::Listening => { + f.debug_tuple("Sockoption::Listening").finish() + } + Sockoption::LastError => { + f.debug_tuple("Sockoption::LastError").finish() + } + Sockoption::KeepAlive => { + f.debug_tuple("Sockoption::KeepAlive").finish() + } + Sockoption::Linger => { + f.debug_tuple("Sockoption::Linger").finish() + } + Sockoption::OobInline => { + f.debug_tuple("Sockoption::OobInline").finish() + } + Sockoption::RecvBufSize => { + f.debug_tuple("Sockoption::RecvBufSize").finish() + } + Sockoption::SendBufSize => { + f.debug_tuple("Sockoption::SendBufSize").finish() + } + Sockoption::RecvLowat => { + f.debug_tuple("Sockoption::RecvLowat").finish() + } + Sockoption::SendLowat => { + f.debug_tuple("Sockoption::SendLowat").finish() + } + Sockoption::RecvTimeout => { + f.debug_tuple("Sockoption::RecvTimeout").finish() + } + Sockoption::SendTimeout => { + f.debug_tuple("Sockoption::SendTimeout").finish() + } + Sockoption::ConnectTimeout => { + f.debug_tuple("Sockoption::ConnectTimeout").finish() + } + Sockoption::AcceptTimeout => { + f.debug_tuple("Sockoption::AcceptTimeout").finish() + } + Sockoption::Ttl => { + f.debug_tuple("Sockoption::Ttl").finish() + } + Sockoption::MulticastTtlV4 => { + f.debug_tuple("Sockoption::MulticastTtlV4").finish() + } + Sockoption::Type => { + f.debug_tuple("Sockoption::Type").finish() + } + Sockoption::Proto => { + f.debug_tuple("Sockoption::Proto").finish() + } + } + } + } + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Streamsecurity { + Unencrypted, + AnyEncryption, + ClassicEncryption, + DoubleEncryption, + } + impl core::fmt::Debug for Streamsecurity { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Streamsecurity::Unencrypted => { + f.debug_tuple("Streamsecurity::Unencrypted").finish() + } + Streamsecurity::AnyEncryption => { + f.debug_tuple("Streamsecurity::AnyEncryption").finish() + } + Streamsecurity::ClassicEncryption => { + f.debug_tuple("Streamsecurity::ClassicEncryption").finish() + } + Streamsecurity::DoubleEncryption => { + f.debug_tuple("Streamsecurity::DoubleEncryption").finish() + } + } + } + } + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Addressfamily { + Unspec, + Inet4, + Inet6, + Unix, + } + impl core::fmt::Debug for Addressfamily { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Addressfamily::Unspec => { + f.debug_tuple("Addressfamily::Unspec").finish() + } + Addressfamily::Inet4 => { + f.debug_tuple("Addressfamily::Inet4").finish() + } + Addressfamily::Inet6 => { + f.debug_tuple("Addressfamily::Inet6").finish() + } + Addressfamily::Unix => { + f.debug_tuple("Addressfamily::Unix").finish() + } + } + } + } + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Snapshot0Filestat { + pub st_dev: Device, + pub st_ino: Inode, + pub st_filetype: Filetype, + pub st_nlink: Snapshot0Linkcount, + pub st_size: Filesize, + pub st_atim: Timestamp, + pub st_mtim: Timestamp, + pub st_ctim: Timestamp, + } + impl core::fmt::Debug for Snapshot0Filestat { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Snapshot0Filestat").field("st-dev", &self.st_dev).field("st-ino", &self.st_ino).field("st-filetype", &self.st_filetype).field("st-nlink", &self.st_nlink).field("st-size", &self.st_size).field("st-atim", &self.st_atim).field("st-mtim", &self.st_mtim).field("st-ctim", &self.st_ctim).finish()} + } + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Filestat { + pub st_dev: Device, + pub st_ino: Inode, + pub st_filetype: Filetype, + pub st_nlink: Linkcount, + pub st_size: Filesize, + pub st_atim: Timestamp, + pub st_mtim: Timestamp, + pub st_ctim: Timestamp, + } + impl core::fmt::Debug for Filestat { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Filestat").field("st-dev", &self.st_dev).field("st-ino", &self.st_ino).field("st-filetype", &self.st_filetype).field("st-nlink", &self.st_nlink).field("st-size", &self.st_size).field("st-atim", &self.st_atim).field("st-mtim", &self.st_mtim).field("st-ctim", &self.st_ctim).finish()} + } + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Snapshot0Whence { + Cur, + End, + Set, + } + impl core::fmt::Debug for Snapshot0Whence { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Snapshot0Whence::Cur => { + f.debug_tuple("Snapshot0Whence::Cur").finish() + } + Snapshot0Whence::End => { + f.debug_tuple("Snapshot0Whence::End").finish() + } + Snapshot0Whence::Set => { + f.debug_tuple("Snapshot0Whence::Set").finish() + } + } + } + } + #[repr(u8)] + #[derive(Clone, Copy, PartialEq, Eq)] + pub enum Whence { + Set, + Cur, + End, + } + impl core::fmt::Debug for Whence { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Whence::Set => { + f.debug_tuple("Whence::Set").finish() + } + Whence::Cur => { + f.debug_tuple("Whence::Cur").finish() + } + Whence::End => { + f.debug_tuple("Whence::End").finish() + } + } + } + } + #[repr(C)] + #[derive(Copy, Clone)] + pub struct Tty { + pub cols: u32, + pub rows: u32, + pub width: u32, + pub height: u32, + pub stdin_tty: bool, + pub stdout_tty: bool, + pub stderr_tty: bool, + pub echo: bool, + pub line_buffered: bool, + } + impl core::fmt::Debug for Tty { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Tty").field("cols", &self.cols).field("rows", &self.rows).field("width", &self.width).field("height", &self.height).field("stdin-tty", &self.stdin_tty).field("stdout-tty", &self.stdout_tty).field("stderr-tty", &self.stderr_tty).field("echo", &self.echo).field("line-buffered", &self.line_buffered).finish()} + } + /// Dummy function to expose types into generated code + pub fn expose_types_dummy_func(fd: Fd,dirent: Dirent,event_enum: EventEnum,event: Event,fdstat: Fdstat,subscription_clock: SubscriptionClock,snapshot0_subscription_clock: Snapshot0SubscriptionClock,subscription: Subscription,snapshot0_subscription: Snapshot0Subscription,device: Device,linkcount: Linkcount,snapshot0_linkcount: Snapshot0Linkcount,filestat: Filestat,snapshot0_filestat: Snapshot0Filestat,tty: Tty,tid: Tid,pid: Pid,) -> (){ + unsafe { + let ptr0 = TYPENAMES_RET_AREA.0.as_mut_ptr() as i32; + *((ptr0 + 0) as *mut i32) = wit_bindgen_rust::rt::as_i32(fd); + let Dirent{ d_next:d_next1, d_ino:d_ino1, d_type:d_type1, d_namlen:d_namlen1, } = dirent; + *((ptr0 + 8) as *mut i64) = wit_bindgen_rust::rt::as_i64(d_next1); + *((ptr0 + 16) as *mut i64) = wit_bindgen_rust::rt::as_i64(d_ino1); + *((ptr0 + 24) as *mut u8) = (match d_type1 { + Filetype::Unknown => 0, + Filetype::BlockDevice => 1, + Filetype::CharacterDevice => 2, + Filetype::Directory => 3, + Filetype::RegularFile => 4, + Filetype::SocketDgram => 5, + Filetype::SocketStream => 6, + Filetype::SymbolicLink => 7, + Filetype::Fifo => 8, + }) as u8; + *((ptr0 + 28) as *mut i32) = wit_bindgen_rust::rt::as_i32(d_namlen1); + match event_enum { + EventEnum::FdRead(e) => { + *((ptr0 + 32) as *mut u8) = (0i32) as u8; + let EventFdReadwrite{ nbytes:nbytes2, flags:flags2, } = e; + *((ptr0 + 40) as *mut i64) = wit_bindgen_rust::rt::as_i64(nbytes2); + let flags3 = flags2; + *((ptr0 + 48) as *mut u8) = ((flags3.bits() >> 0) as i32) as u8; + + }, + EventEnum::FdWrite(e) => { + *((ptr0 + 32) as *mut u8) = (1i32) as u8; + let EventFdReadwrite{ nbytes:nbytes4, flags:flags4, } = e; + *((ptr0 + 40) as *mut i64) = wit_bindgen_rust::rt::as_i64(nbytes4); + let flags5 = flags4; + *((ptr0 + 48) as *mut u8) = ((flags5.bits() >> 0) as i32) as u8; + + }, + EventEnum::Clock=> { + let e = (); + { + *((ptr0 + 32) as *mut u8) = (2i32) as u8; + let () = e; + + } + } + }; + let Event{ userdata:userdata6, error:error6, data:data6, } = event; + *((ptr0 + 56) as *mut i64) = wit_bindgen_rust::rt::as_i64(userdata6); + *((ptr0 + 64) as *mut u8) = (match error6 { + Errno::Success => 0, + Errno::Toobig => 1, + Errno::Access => 2, + Errno::Addrinuse => 3, + Errno::Addrnotavail => 4, + Errno::Afnosupport => 5, + Errno::Again => 6, + Errno::Already => 7, + Errno::Badf => 8, + Errno::Badmsg => 9, + Errno::Busy => 10, + Errno::Canceled => 11, + Errno::Child => 12, + Errno::Connaborted => 13, + Errno::Connrefused => 14, + Errno::Connreset => 15, + Errno::Deadlk => 16, + Errno::Destaddrreq => 17, + Errno::Dom => 18, + Errno::Dquot => 19, + Errno::Exist => 20, + Errno::Fault => 21, + Errno::Fbig => 22, + Errno::Hostunreach => 23, + Errno::Idrm => 24, + Errno::Ilseq => 25, + Errno::Inprogress => 26, + Errno::Intr => 27, + Errno::Inval => 28, + Errno::Io => 29, + Errno::Isconn => 30, + Errno::Isdir => 31, + Errno::Loop => 32, + Errno::Mfile => 33, + Errno::Mlink => 34, + Errno::Msgsize => 35, + Errno::Multihop => 36, + Errno::Nametoolong => 37, + Errno::Netdown => 38, + Errno::Netreset => 39, + Errno::Netunreach => 40, + Errno::Nfile => 41, + Errno::Nobufs => 42, + Errno::Nodev => 43, + Errno::Noent => 44, + Errno::Noexec => 45, + Errno::Nolck => 46, + Errno::Nolink => 47, + Errno::Nomem => 48, + Errno::Nomsg => 49, + Errno::Noprotoopt => 50, + Errno::Nospc => 51, + Errno::Nosys => 52, + Errno::Notconn => 53, + Errno::Notdir => 54, + Errno::Notempty => 55, + Errno::Notrecoverable => 56, + Errno::Notsock => 57, + Errno::Notsup => 58, + Errno::Notty => 59, + Errno::Nxio => 60, + Errno::Overflow => 61, + Errno::Ownerdead => 62, + Errno::Perm => 63, + Errno::Pipe => 64, + Errno::Proto => 65, + Errno::Protonosupport => 66, + Errno::Prototype => 67, + Errno::Range => 68, + Errno::Rofs => 69, + Errno::Spipe => 70, + Errno::Srch => 71, + Errno::Stale => 72, + Errno::Timedout => 73, + Errno::Txtbsy => 74, + Errno::Xdev => 75, + Errno::Notcapable => 76, + }) as u8; + match data6 { + EventEnum::FdRead(e) => { + *((ptr0 + 72) as *mut u8) = (0i32) as u8; + let EventFdReadwrite{ nbytes:nbytes7, flags:flags7, } = e; + *((ptr0 + 80) as *mut i64) = wit_bindgen_rust::rt::as_i64(nbytes7); + let flags8 = flags7; + *((ptr0 + 88) as *mut u8) = ((flags8.bits() >> 0) as i32) as u8; + + }, + EventEnum::FdWrite(e) => { + *((ptr0 + 72) as *mut u8) = (1i32) as u8; + let EventFdReadwrite{ nbytes:nbytes9, flags:flags9, } = e; + *((ptr0 + 80) as *mut i64) = wit_bindgen_rust::rt::as_i64(nbytes9); + let flags10 = flags9; + *((ptr0 + 88) as *mut u8) = ((flags10.bits() >> 0) as i32) as u8; + + }, + EventEnum::Clock=> { + let e = (); + { + *((ptr0 + 72) as *mut u8) = (2i32) as u8; + let () = e; + + } + } + }; + let Fdstat{ fs_filetype:fs_filetype11, fs_flags:fs_flags11, fs_rights_base:fs_rights_base11, fs_rights_inheriting:fs_rights_inheriting11, } = fdstat; + *((ptr0 + 96) as *mut u8) = (match fs_filetype11 { + Filetype::Unknown => 0, + Filetype::BlockDevice => 1, + Filetype::CharacterDevice => 2, + Filetype::Directory => 3, + Filetype::RegularFile => 4, + Filetype::SocketDgram => 5, + Filetype::SocketStream => 6, + Filetype::SymbolicLink => 7, + Filetype::Fifo => 8, + }) as u8; + let flags12 = fs_flags11; + *((ptr0 + 97) as *mut u8) = ((flags12.bits() >> 0) as i32) as u8; + let flags13 = fs_rights_base11; + *((ptr0 + 104) as *mut i32) = (flags13.bits() >> 32) as i32; + *((ptr0 + 100) as *mut i32) = (flags13.bits() >> 0) as i32; + let flags14 = fs_rights_inheriting11; + *((ptr0 + 112) as *mut i32) = (flags14.bits() >> 32) as i32; + *((ptr0 + 108) as *mut i32) = (flags14.bits() >> 0) as i32; + let SubscriptionClock{ clock_id:clock_id15, timeout:timeout15, precision:precision15, flags:flags15, } = subscription_clock; + *((ptr0 + 120) as *mut u8) = (match clock_id15 { + Clockid::Realtime => 0, + Clockid::Monotonic => 1, + }) as u8; + *((ptr0 + 128) as *mut i64) = wit_bindgen_rust::rt::as_i64(timeout15); + *((ptr0 + 136) as *mut i64) = wit_bindgen_rust::rt::as_i64(precision15); + let flags16 = flags15; + *((ptr0 + 144) as *mut u8) = ((flags16.bits() >> 0) as i32) as u8; + let Snapshot0SubscriptionClock{ identifier:identifier17, id:id17, timeout:timeout17, precision:precision17, flags:flags17, } = snapshot0_subscription_clock; + *((ptr0 + 152) as *mut i64) = wit_bindgen_rust::rt::as_i64(identifier17); + *((ptr0 + 160) as *mut u8) = (match id17 { + Snapshot0Clockid::Realtime => 0, + Snapshot0Clockid::Monotonic => 1, + Snapshot0Clockid::ProcessCputimeId => 2, + Snapshot0Clockid::ThreadCputimeId => 3, + }) as u8; + *((ptr0 + 168) as *mut i64) = wit_bindgen_rust::rt::as_i64(timeout17); + *((ptr0 + 176) as *mut i64) = wit_bindgen_rust::rt::as_i64(precision17); + let flags18 = flags17; + *((ptr0 + 184) as *mut u8) = ((flags18.bits() >> 0) as i32) as u8; + let Subscription{ userdata:userdata19, data:data19, } = subscription; + *((ptr0 + 192) as *mut i64) = wit_bindgen_rust::rt::as_i64(userdata19); + match data19 { + SubscriptionEnum::Clock(e) => { + *((ptr0 + 200) as *mut u8) = (0i32) as u8; + let SubscriptionClock{ clock_id:clock_id20, timeout:timeout20, precision:precision20, flags:flags20, } = e; + *((ptr0 + 208) as *mut u8) = (match clock_id20 { + Clockid::Realtime => 0, + Clockid::Monotonic => 1, + }) as u8; + *((ptr0 + 216) as *mut i64) = wit_bindgen_rust::rt::as_i64(timeout20); + *((ptr0 + 224) as *mut i64) = wit_bindgen_rust::rt::as_i64(precision20); + let flags21 = flags20; + *((ptr0 + 232) as *mut u8) = ((flags21.bits() >> 0) as i32) as u8; + + }, + SubscriptionEnum::Read(e) => { + *((ptr0 + 200) as *mut u8) = (1i32) as u8; + let SubscriptionFsReadwrite{ file_descriptor:file_descriptor22, } = e; + *((ptr0 + 208) as *mut i32) = wit_bindgen_rust::rt::as_i32(file_descriptor22); + + }, + SubscriptionEnum::Write(e) => { + *((ptr0 + 200) as *mut u8) = (2i32) as u8; + let SubscriptionFsReadwrite{ file_descriptor:file_descriptor23, } = e; + *((ptr0 + 208) as *mut i32) = wit_bindgen_rust::rt::as_i32(file_descriptor23); + + }, + }; + let Snapshot0Subscription{ userdata:userdata24, data:data24, } = snapshot0_subscription; + *((ptr0 + 240) as *mut i64) = wit_bindgen_rust::rt::as_i64(userdata24); + match data24 { + Snapshot0SubscriptionEnum::Clock(e) => { + *((ptr0 + 248) as *mut u8) = (0i32) as u8; + let Snapshot0SubscriptionClock{ identifier:identifier25, id:id25, timeout:timeout25, precision:precision25, flags:flags25, } = e; + *((ptr0 + 256) as *mut i64) = wit_bindgen_rust::rt::as_i64(identifier25); + *((ptr0 + 264) as *mut u8) = (match id25 { + Snapshot0Clockid::Realtime => 0, + Snapshot0Clockid::Monotonic => 1, + Snapshot0Clockid::ProcessCputimeId => 2, + Snapshot0Clockid::ThreadCputimeId => 3, + }) as u8; + *((ptr0 + 272) as *mut i64) = wit_bindgen_rust::rt::as_i64(timeout25); + *((ptr0 + 280) as *mut i64) = wit_bindgen_rust::rt::as_i64(precision25); + let flags26 = flags25; + *((ptr0 + 288) as *mut u8) = ((flags26.bits() >> 0) as i32) as u8; + + }, + Snapshot0SubscriptionEnum::Read(e) => { + *((ptr0 + 248) as *mut u8) = (1i32) as u8; + let SubscriptionFsReadwrite{ file_descriptor:file_descriptor27, } = e; + *((ptr0 + 256) as *mut i32) = wit_bindgen_rust::rt::as_i32(file_descriptor27); + + }, + Snapshot0SubscriptionEnum::Write(e) => { + *((ptr0 + 248) as *mut u8) = (2i32) as u8; + let SubscriptionFsReadwrite{ file_descriptor:file_descriptor28, } = e; + *((ptr0 + 256) as *mut i32) = wit_bindgen_rust::rt::as_i32(file_descriptor28); + + }, + }; + *((ptr0 + 296) as *mut i64) = wit_bindgen_rust::rt::as_i64(device); + *((ptr0 + 304) as *mut i64) = wit_bindgen_rust::rt::as_i64(linkcount); + *((ptr0 + 312) as *mut i32) = wit_bindgen_rust::rt::as_i32(snapshot0_linkcount); + let Filestat{ st_dev:st_dev29, st_ino:st_ino29, st_filetype:st_filetype29, st_nlink:st_nlink29, st_size:st_size29, st_atim:st_atim29, st_mtim:st_mtim29, st_ctim:st_ctim29, } = filestat; + *((ptr0 + 320) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_dev29); + *((ptr0 + 328) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_ino29); + *((ptr0 + 336) as *mut u8) = (match st_filetype29 { + Filetype::Unknown => 0, + Filetype::BlockDevice => 1, + Filetype::CharacterDevice => 2, + Filetype::Directory => 3, + Filetype::RegularFile => 4, + Filetype::SocketDgram => 5, + Filetype::SocketStream => 6, + Filetype::SymbolicLink => 7, + Filetype::Fifo => 8, + }) as u8; + *((ptr0 + 344) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_nlink29); + *((ptr0 + 352) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_size29); + *((ptr0 + 360) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_atim29); + *((ptr0 + 368) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_mtim29); + *((ptr0 + 376) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_ctim29); + let Snapshot0Filestat{ st_dev:st_dev30, st_ino:st_ino30, st_filetype:st_filetype30, st_nlink:st_nlink30, st_size:st_size30, st_atim:st_atim30, st_mtim:st_mtim30, st_ctim:st_ctim30, } = snapshot0_filestat; + *((ptr0 + 384) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_dev30); + *((ptr0 + 392) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_ino30); + *((ptr0 + 400) as *mut u8) = (match st_filetype30 { + Filetype::Unknown => 0, + Filetype::BlockDevice => 1, + Filetype::CharacterDevice => 2, + Filetype::Directory => 3, + Filetype::RegularFile => 4, + Filetype::SocketDgram => 5, + Filetype::SocketStream => 6, + Filetype::SymbolicLink => 7, + Filetype::Fifo => 8, + }) as u8; + *((ptr0 + 404) as *mut i32) = wit_bindgen_rust::rt::as_i32(st_nlink30); + *((ptr0 + 408) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_size30); + *((ptr0 + 416) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_atim30); + *((ptr0 + 424) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_mtim30); + *((ptr0 + 432) as *mut i64) = wit_bindgen_rust::rt::as_i64(st_ctim30); + let Tty{ cols:cols31, rows:rows31, width:width31, height:height31, stdin_tty:stdin_tty31, stdout_tty:stdout_tty31, stderr_tty:stderr_tty31, echo:echo31, line_buffered:line_buffered31, } = tty; + *((ptr0 + 440) as *mut i32) = wit_bindgen_rust::rt::as_i32(cols31); + *((ptr0 + 444) as *mut i32) = wit_bindgen_rust::rt::as_i32(rows31); + *((ptr0 + 448) as *mut i32) = wit_bindgen_rust::rt::as_i32(width31); + *((ptr0 + 452) as *mut i32) = wit_bindgen_rust::rt::as_i32(height31); + *((ptr0 + 456) as *mut u8) = (match stdin_tty31 { true => 1, false => 0 }) as u8; + *((ptr0 + 457) as *mut u8) = (match stdout_tty31 { true => 1, false => 0 }) as u8; + *((ptr0 + 458) as *mut u8) = (match stderr_tty31 { true => 1, false => 0 }) as u8; + *((ptr0 + 459) as *mut u8) = (match echo31 { true => 1, false => 0 }) as u8; + *((ptr0 + 460) as *mut u8) = (match line_buffered31 { true => 1, false => 0 }) as u8; + *((ptr0 + 464) as *mut i32) = wit_bindgen_rust::rt::as_i32(tid); + *((ptr0 + 468) as *mut i32) = wit_bindgen_rust::rt::as_i32(pid); + #[link(wasm_import_module = "typenames")] + extern "C" { + #[cfg_attr(target_arch = "wasm32", link_name = "expose-types-dummy-func")] + #[cfg_attr(not(target_arch = "wasm32"), link_name = "typenames_expose-types-dummy-func")] + fn wit_import(_: i32, ); + } + wit_import(ptr0); + () + } + } + + #[repr(align(8))] + struct RetArea([u8; 472]); + static mut TYPENAMES_RET_AREA: RetArea = RetArea([0; 472]); +} diff --git a/lib/wasi-types-generated/src/wasi/mod.rs b/lib/wasi-types-generated/src/wasi/mod.rs new file mode 100644 index 00000000000..0c4b65f0029 --- /dev/null +++ b/lib/wasi-types-generated/src/wasi/mod.rs @@ -0,0 +1,1384 @@ +mod bindings; +pub use bindings::wasi::*; + +use std::mem::MaybeUninit; +use wasmer_types::ValueType; + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Errno { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for BusErrno { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Filetype { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Socktype { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Sockstatus { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Sockoption { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Streamsecurity { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Addressfamily { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Snapshot0Whence { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +impl Filetype { + pub fn name(self) -> &'static str { + match self { + Self::Unknown => "Unknown", + Self::BlockDevice => "Block device", + Self::CharacterDevice => "Character device", + Self::Directory => "Directory", + Self::RegularFile => "Regular file", + Self::SocketDgram => "Socket dgram", + Self::SocketStream => "Socket stream", + Self::SymbolicLink => "Symbolic link", + Self::Fifo => "Fifo", + } + } +} + +unsafe impl ValueType for Event { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + self.userdata + .zero_padding_bytes(&mut bytes[field!(userdata)..field_end!(userdata)]); + zero!(field_end!(userdata), field!(error)); + self.error + .zero_padding_bytes(&mut bytes[field!(error)..field_end!(error)]); + zero!(field_end!(error), field!(data)); + self.data + .zero_padding_bytes(&mut bytes[field!(data)..field_end!(data)]); + zero!(field_end!(data), std::mem::size_of_val(self)); + } +} + +unsafe impl ValueType for Tty { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.cols + .zero_padding_bytes(&mut bytes[field!(cols)..field_end!(cols)]); + zero!(field_end!(cols), field!(rows)); + + self.rows + .zero_padding_bytes(&mut bytes[field!(rows)..field_end!(rows)]); + zero!(field_end!(rows), field!(width)); + + self.width + .zero_padding_bytes(&mut bytes[field!(width)..field_end!(width)]); + zero!(field_end!(width), field!(height)); + + self.height + .zero_padding_bytes(&mut bytes[field!(height)..field_end!(height)]); + zero!(field_end!(height), field!(stdin_tty)); + + self.stdin_tty + .zero_padding_bytes(&mut bytes[field!(stdin_tty)..field_end!(stdin_tty)]); + zero!(field_end!(stdin_tty), field!(stdout_tty)); + + self.stdout_tty + .zero_padding_bytes(&mut bytes[field!(stdout_tty)..field_end!(stdout_tty)]); + zero!(field_end!(stdout_tty), field!(stderr_tty)); + + self.stderr_tty + .zero_padding_bytes(&mut bytes[field!(stderr_tty)..field_end!(stderr_tty)]); + zero!(field_end!(stderr_tty), field!(echo)); + + self.echo + .zero_padding_bytes(&mut bytes[field!(echo)..field_end!(echo)]); + zero!(field_end!(echo), field!(line_buffered)); + + self.line_buffered + .zero_padding_bytes(&mut bytes[field!(line_buffered)..field_end!(line_buffered)]); + zero!(field_end!(line_buffered), std::mem::size_of_val(self)); + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Eventtype { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Rights { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +impl Rights { + pub const fn all_socket() -> Self { + Self::from_bits_truncate( + Self::FD_FDSTAT_SET_FLAGS.bits() + | Self::FD_FILESTAT_GET.bits() + | Self::FD_READ.bits() + | Self::FD_WRITE.bits() + | Self::POLL_FD_READWRITE.bits() + | Self::SOCK_SHUTDOWN.bits() + | Self::SOCK_CONNECT.bits() + | Self::SOCK_LISTEN.bits() + | Self::SOCK_BIND.bits() + | Self::SOCK_ACCEPT.bits() + | Self::SOCK_RECV.bits() + | Self::SOCK_SEND.bits() + | Self::SOCK_ADDR_LOCAL.bits() + | Self::SOCK_ADDR_REMOTE.bits() + | Self::SOCK_RECV_FROM.bits() + | Self::SOCK_SEND_TO.bits(), + ) + } + + /// expects a single right, returns None if out of bounds or > 1 bit set + pub fn to_str(self) -> Option<&'static str> { + Some(match self { + Rights::FD_DATASYNC => "Rights::FD_DATASYNC", + Rights::FD_READ => "Rights::FD_READ", + Rights::FD_SEEK => "Rights::FD_SEEK", + Rights::FD_FDSTAT_SET_FLAGS => "Rights::FD_FDSTAT_SET_FLAGS", + Rights::FD_SYNC => "Rights::FD_SYNC", + Rights::FD_TELL => "Rights::FD_TELL", + Rights::FD_WRITE => "Rights::FD_WRITE", + Rights::FD_ADVISE => "Rights::FD_ADVISE", + Rights::FD_ALLOCATE => "Rights::FD_ALLOCATE", + Rights::PATH_CREATE_DIRECTORY => "Rights::PATH_CREATE_DIRECTORY", + Rights::PATH_CREATE_FILE => "Rights::PATH_CREATE_FILE", + Rights::PATH_LINK_SOURCE => "Rights::PATH_LINK_SOURCE", + Rights::PATH_LINK_TARGET => "Rights::PATH_LINK_TARGET", + Rights::PATH_OPEN => "Rights::PATH_OPEN", + Rights::FD_READDIR => "Rights::FD_READDIR", + Rights::PATH_READLINK => "Rights::PATH_READLINK", + Rights::PATH_RENAME_SOURCE => "Rights::PATH_RENAME_SOURCE", + Rights::PATH_RENAME_TARGET => "Rights::PATH_RENAME_TARGET", + Rights::PATH_FILESTAT_GET => "Rights::PATH_FILESTAT_GET", + Rights::PATH_FILESTAT_SET_SIZE => "Rights::PATH_FILESTAT_SET_SIZE", + Rights::PATH_FILESTAT_SET_TIMES => "Rights::PATH_FILESTAT_SET_TIMES", + Rights::FD_FILESTAT_GET => "Rights::FD_FILESTAT_GET", + Rights::FD_FILESTAT_SET_SIZE => "Rights::FD_FILESTAT_SET_SIZE", + Rights::FD_FILESTAT_SET_TIMES => "Rights::FD_FILESTAT_SET_TIMES", + Rights::PATH_SYMLINK => "Rights::PATH_SYMLINK", + Rights::PATH_REMOVE_DIRECTORY => "Rights::PATH_REMOVE_DIRECTORY", + Rights::PATH_UNLINK_FILE => "Rights::PATH_UNLINK_FILE", + Rights::POLL_FD_READWRITE => "Rights::POLL_FD_READWRITE", + Rights::SOCK_SHUTDOWN => "Rights::SOCK_SHUTDOWN", + Rights::SOCK_ACCEPT => "Rights::SOCK_ACCEPT", + Rights::SOCK_CONNECT => "Rights::SOCK_CONNECT", + Rights::SOCK_LISTEN => "Rights::SOCK_LISTEN", + Rights::SOCK_BIND => "Rights::SOCK_BIND", + Rights::SOCK_RECV => "Rights::SOCK_RECV", + Rights::SOCK_SEND => "Rights::SOCK_SEND", + Rights::SOCK_ADDR_LOCAL => "Rights::SOCK_ADDR_LOCAL", + Rights::SOCK_ADDR_REMOTE => "Rights::SOCK_ADDR_REMOTE", + Rights::SOCK_RECV_FROM => "Rights::SOCK_RECV_FROM", + Rights::SOCK_SEND_TO => "Rights::SOCK_SEND_TO", + _ => return None, + }) + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Eventrwflags { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Fstflags { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for SubscriptionEnum { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + match self { + SubscriptionEnum::Clock(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + SubscriptionEnum::Read(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + SubscriptionEnum::Write(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + } + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for EventEnum { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + match self { + Self::Clock => { + zero!(field!(self), std::mem::size_of_val(self)) + } + Self::FdRead(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + Self::FdWrite(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + } + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Snapshot0SubscriptionEnum { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + match self { + Snapshot0SubscriptionEnum::Clock(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + Snapshot0SubscriptionEnum::Read(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + Snapshot0SubscriptionEnum::Write(d) => { + d.zero_padding_bytes(&mut bytes[field!(d)..field_end!(d)]); + zero!(field_end!(d), std::mem::size_of_val(self)) + } + } + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Subclockflags { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Clockid { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Fdflags { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Preopentype { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for EventFdReadwrite { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.nbytes + .zero_padding_bytes(&mut bytes[field!(nbytes)..field_end!(nbytes)]); + zero!(field_end!(nbytes), field!(flags)); + + self.flags + .zero_padding_bytes(&mut bytes[field!(flags)..field_end!(flags)]); + zero!(field_end!(flags), std::mem::size_of_val(self)); + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Fdstat { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.fs_filetype + .zero_padding_bytes(&mut bytes[field!(fs_filetype)..field_end!(fs_filetype)]); + zero!(field_end!(fs_filetype), field!(fs_flags)); + + self.fs_flags + .zero_padding_bytes(&mut bytes[field!(fs_flags)..field_end!(fs_flags)]); + zero!(field_end!(fs_flags), field!(fs_rights_base)); + + self.fs_rights_base + .zero_padding_bytes(&mut bytes[field!(fs_rights_base)..field_end!(fs_rights_base)]); + zero!( + field_end!(fs_rights_inheriting), + std::mem::size_of_val(self) + ); + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Snapshot0SubscriptionClock { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.identifier + .zero_padding_bytes(&mut bytes[field!(identifier)..field_end!(identifier)]); + zero!(field_end!(identifier), field!(id)); + + self.id + .zero_padding_bytes(&mut bytes[field!(id)..field_end!(id)]); + zero!(field_end!(id), field!(timeout)); + + self.timeout + .zero_padding_bytes(&mut bytes[field!(timeout)..field_end!(timeout)]); + zero!(field_end!(timeout), field!(precision)); + + self.precision + .zero_padding_bytes(&mut bytes[field!(precision)..field_end!(precision)]); + zero!(field_end!(precision), field!(flags)); + + self.flags + .zero_padding_bytes(&mut bytes[field!(flags)..field_end!(flags)]); + zero!(field_end!(flags), std::mem::size_of_val(self)); + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for SubscriptionFsReadwrite { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.file_descriptor + .zero_padding_bytes(&mut bytes[field!(file_descriptor)..field_end!(file_descriptor)]); + zero!(field_end!(file_descriptor), std::mem::size_of_val(self)); + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for SubscriptionClock { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.clock_id + .zero_padding_bytes(&mut bytes[field!(clock_id)..field_end!(clock_id)]); + zero!(field_end!(clock_id), field!(timeout)); + + self.timeout + .zero_padding_bytes(&mut bytes[field!(timeout)..field_end!(timeout)]); + zero!(field_end!(timeout), field!(precision)); + + self.precision + .zero_padding_bytes(&mut bytes[field!(precision)..field_end!(precision)]); + zero!(field_end!(precision), field!(flags)); + + self.flags + .zero_padding_bytes(&mut bytes[field!(flags)..field_end!(flags)]); + zero!(field_end!(flags), std::mem::size_of_val(self)); + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Subscription { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.userdata + .zero_padding_bytes(&mut bytes[field!(userdata)..field_end!(userdata)]); + zero!(field_end!(userdata), field!(data)); + + self.data + .zero_padding_bytes(&mut bytes[field!(data)..field_end!(data)]); + zero!(field_end!(data), std::mem::size_of_val(self)); + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Snapshot0Subscription { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + + self.userdata + .zero_padding_bytes(&mut bytes[field!(userdata)..field_end!(userdata)]); + zero!(field_end!(userdata), field!(data)); + + self.data + .zero_padding_bytes(&mut bytes[field!(data)..field_end!(data)]); + zero!(field_end!(data), std::mem::size_of_val(self)); + } +} + +unsafe impl ValueType for Snapshot0Filestat { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + self.st_dev + .zero_padding_bytes(&mut bytes[field!(st_dev)..field_end!(st_dev)]); + zero!(field_end!(st_dev), field!(st_ino)); + + self.st_ino + .zero_padding_bytes(&mut bytes[field!(st_ino)..field_end!(st_ino)]); + zero!(field_end!(st_ino), field!(st_filetype)); + + self.st_filetype + .zero_padding_bytes(&mut bytes[field!(st_filetype)..field_end!(st_filetype)]); + zero!(field_end!(st_filetype), field!(st_nlink)); + + self.st_nlink + .zero_padding_bytes(&mut bytes[field!(st_nlink)..field_end!(st_nlink)]); + zero!(field_end!(st_nlink), field!(st_size)); + + self.st_size + .zero_padding_bytes(&mut bytes[field!(st_size)..field_end!(st_size)]); + zero!(field_end!(st_size), field!(st_atim)); + + self.st_atim + .zero_padding_bytes(&mut bytes[field!(st_atim)..field_end!(st_atim)]); + zero!(field_end!(st_atim), field!(st_mtim)); + + self.st_mtim + .zero_padding_bytes(&mut bytes[field!(st_mtim)..field_end!(st_mtim)]); + zero!(field_end!(st_mtim), field!(st_ctim)); + + self.st_ctim + .zero_padding_bytes(&mut bytes[field!(st_ctim)..field_end!(st_ctim)]); + zero!(field_end!(st_ctim), std::mem::size_of_val(self)); + } +} + +unsafe impl ValueType for Filestat { + fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { + macro_rules! field { + ($($f:tt)*) => { + &self.$($f)* as *const _ as usize - self as *const _ as usize + }; + } + macro_rules! field_end { + ($($f:tt)*) => { + field!($($f)*) + std::mem::size_of_val(&self.$($f)*) + }; + } + macro_rules! zero { + ($start:expr, $end:expr) => { + for i in $start..$end { + bytes[i] = MaybeUninit::new(0); + } + }; + } + self.st_dev + .zero_padding_bytes(&mut bytes[field!(st_dev)..field_end!(st_dev)]); + zero!(field_end!(st_dev), field!(st_ino)); + + self.st_ino + .zero_padding_bytes(&mut bytes[field!(st_ino)..field_end!(st_ino)]); + zero!(field_end!(st_ino), field!(st_filetype)); + + self.st_filetype + .zero_padding_bytes(&mut bytes[field!(st_filetype)..field_end!(st_filetype)]); + zero!(field_end!(st_filetype), field!(st_nlink)); + + self.st_nlink + .zero_padding_bytes(&mut bytes[field!(st_nlink)..field_end!(st_nlink)]); + zero!(field_end!(st_nlink), field!(st_size)); + + self.st_size + .zero_padding_bytes(&mut bytes[field!(st_size)..field_end!(st_size)]); + zero!(field_end!(st_size), field!(st_atim)); + + self.st_atim + .zero_padding_bytes(&mut bytes[field!(st_atim)..field_end!(st_atim)]); + zero!(field_end!(st_atim), field!(st_mtim)); + + self.st_mtim + .zero_padding_bytes(&mut bytes[field!(st_mtim)..field_end!(st_mtim)]); + zero!(field_end!(st_mtim), field!(st_ctim)); + + self.st_ctim + .zero_padding_bytes(&mut bytes[field!(st_ctim)..field_end!(st_ctim)]); + zero!(field_end!(st_ctim), std::mem::size_of_val(self)); + } +} + +impl Default for Filestat { + fn default() -> Self { + Self { + st_dev: Default::default(), + st_ino: Default::default(), + st_filetype: Filetype::Unknown, + st_nlink: 1, + st_size: Default::default(), + st_atim: Default::default(), + st_mtim: Default::default(), + st_ctim: Default::default(), + } + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Errno { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Success, + 1 => Self::Toobig, + 2 => Self::Access, + 3 => Self::Addrinuse, + 4 => Self::Addrnotavail, + 5 => Self::Afnosupport, + 6 => Self::Again, + 7 => Self::Already, + 8 => Self::Badf, + 9 => Self::Badmsg, + 10 => Self::Busy, + 11 => Self::Canceled, + 12 => Self::Child, + 13 => Self::Connaborted, + 14 => Self::Connrefused, + 15 => Self::Connreset, + 16 => Self::Deadlk, + 17 => Self::Destaddrreq, + 18 => Self::Dom, + 19 => Self::Dquot, + 20 => Self::Exist, + 21 => Self::Fault, + 22 => Self::Fbig, + 23 => Self::Hostunreach, + 24 => Self::Idrm, + 25 => Self::Ilseq, + 26 => Self::Inprogress, + 27 => Self::Intr, + 28 => Self::Inval, + 29 => Self::Io, + 30 => Self::Isconn, + 31 => Self::Isdir, + 32 => Self::Loop, + 33 => Self::Mfile, + 34 => Self::Mlink, + 35 => Self::Msgsize, + 36 => Self::Multihop, + 37 => Self::Nametoolong, + 38 => Self::Netdown, + 39 => Self::Netreset, + 40 => Self::Netunreach, + 41 => Self::Nfile, + 42 => Self::Nobufs, + 43 => Self::Nodev, + 44 => Self::Noent, + 45 => Self::Noexec, + 46 => Self::Nolck, + 47 => Self::Nolink, + 48 => Self::Nomem, + 49 => Self::Nomsg, + 50 => Self::Noprotoopt, + 51 => Self::Nospc, + 52 => Self::Nosys, + 53 => Self::Notconn, + 54 => Self::Notdir, + 55 => Self::Notempty, + 56 => Self::Notrecoverable, + 57 => Self::Notsock, + 58 => Self::Notsup, + 59 => Self::Notty, + 60 => Self::Nxio, + 61 => Self::Overflow, + 62 => Self::Ownerdead, + 63 => Self::Perm, + 64 => Self::Pipe, + 65 => Self::Proto, + 66 => Self::Protonosupport, + 67 => Self::Prototype, + 68 => Self::Range, + 69 => Self::Rofs, + 70 => Self::Spipe, + 71 => Self::Srch, + 72 => Self::Stale, + 73 => Self::Timedout, + 74 => Self::Txtbsy, + 75 => Self::Xdev, + 76 => Self::Notcapable, + // TODO: What should we map invalid native values to? + _ => Self::Inval, + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for BusErrno { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Success, + 1 => Self::Ser, + 2 => Self::Des, + 3 => Self::Wapm, + 4 => Self::Fetch, + 5 => Self::Compile, + 6 => Self::Abi, + 7 => Self::Aborted, + 8 => Self::Badhandle, + 9 => Self::Topic, + 10 => Self::Badcb, + 11 => Self::Unsupported, + 12 => Self::Badrequest, + 13 => Self::Denied, + 14 => Self::Internal, + 15 => Self::Alloc, + 16 => Self::Invoke, + 17 => Self::Consumed, + 18 => Self::Memviolation, + 19 => Self::Unknown, + // TODO: What should we map invalid native values to? + _ => Self::Unknown, + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Advice { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Normal, + 1 => Self::Sequential, + 2 => Self::Random, + 3 => Self::Willneed, + 4 => Self::Dontneed, + 5 => Self::Noreuse, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Socktype { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Dgram, + 1 => Self::Stream, + 2 => Self::Raw, + 3 => Self::Seqpacket, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Sockstatus { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Opening, + 1 => Self::Opened, + 2 => Self::Closed, + 3 => Self::Failed, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Streamsecurity { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Unencrypted, + 1 => Self::AnyEncryption, + 2 => Self::ClassicEncryption, + 3 => Self::DoubleEncryption, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Rights { + type Native = i64; + + fn to_native(self) -> Self::Native { + self.bits() as i64 + } + + fn from_native(n: Self::Native) -> Self { + Self::from_bits_truncate(n as u64) + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Eventrwflags { + type Native = i32; + + fn to_native(self) -> Self::Native { + self.bits() as i32 + } + fn from_native(n: Self::Native) -> Self { + Self::from_bits_truncate(n as u8) + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Fstflags { + type Native = i32; + + fn to_native(self) -> Self::Native { + self.bits() as i32 + } + fn from_native(n: Self::Native) -> Self { + Self::from_bits_truncate(n as u8) + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Subclockflags { + type Native = i32; + + fn to_native(self) -> Self::Native { + self.bits() as i32 + } + fn from_native(n: Self::Native) -> Self { + Self::from_bits_truncate(n as u8) + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Clockid { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Realtime, + 1 => Self::Monotonic, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Snapshot0Clockid { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Realtime, + 1 => Self::Monotonic, + 2 => Self::ProcessCputimeId, + 3 => Self::ThreadCputimeId, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Sockoption { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Noop, + 1 => Self::ReusePort, + 2 => Self::ReuseAddr, + 3 => Self::NoDelay, + 4 => Self::DontRoute, + 5 => Self::OnlyV6, + 6 => Self::Broadcast, + 7 => Self::MulticastLoopV4, + 8 => Self::MulticastLoopV6, + 9 => Self::Promiscuous, + 10 => Self::Listening, + 11 => Self::LastError, + 12 => Self::KeepAlive, + 13 => Self::Linger, + 14 => Self::OobInline, + 15 => Self::RecvBufSize, + 16 => Self::SendBufSize, + 17 => Self::RecvLowat, + 18 => Self::SendLowat, + 19 => Self::RecvTimeout, + 20 => Self::SendTimeout, + 21 => Self::ConnectTimeout, + 22 => Self::AcceptTimeout, + 23 => Self::Ttl, + 24 => Self::MulticastTtlV4, + 25 => Self::Type, + 26 => Self::Proto, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +impl std::fmt::Display for Sockoption { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let s = match *self { + Self::Noop => "Sockoption::Noop", + Self::ReusePort => "Sockoption::ReusePort", + Self::ReuseAddr => "Sockoption::ReuseAddr", + Self::NoDelay => "Sockoption::NoDelay", + Self::DontRoute => "Sockoption::DontRoute", + Self::OnlyV6 => "Sockoption::OnlyV6", + Self::Broadcast => "Sockoption::Broadcast", + Self::MulticastLoopV4 => "Sockoption::MulticastLoopV4", + Self::MulticastLoopV6 => "Sockoption::MulticastLoopV6", + Self::Promiscuous => "Sockoption::Promiscuous", + Self::Listening => "Sockoption::Listening", + Self::LastError => "Sockoption::LastError", + Self::KeepAlive => "Sockoption::KeepAlive", + Self::Linger => "Sockoption::Linger", + Self::OobInline => "Sockoption::OobInline", + Self::RecvBufSize => "Sockoption::RecvBufSize", + Self::SendBufSize => "Sockoption::SendBufSize", + Self::RecvLowat => "Sockoption::RecvLowat", + Self::SendLowat => "Sockoption::SendLowat", + Self::RecvTimeout => "Sockoption::RecvTimeout", + Self::SendTimeout => "Sockoption::SendTimeout", + Self::ConnectTimeout => "Sockoption::ConnectTimeout", + Self::AcceptTimeout => "Sockoption::AcceptTimeout", + Self::Ttl => "Sockoption::Ttl", + Self::MulticastTtlV4 => "Sockoption::MulticastTtlV4", + Self::Type => "Sockoption::Type", + Self::Proto => "Sockoption::Proto", + }; + write!(f, "{}", s) + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Fdflags { + type Native = i32; + + fn to_native(self) -> Self::Native { + self.bits() as i32 + } + fn from_native(n: Self::Native) -> Self { + Self::from_bits_truncate(n as u8) + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Preopentype { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Dir, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Addressfamily { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Unspec, + 1 => Self::Inet4, + 2 => Self::Inet6, + 3 => Self::Unix, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Snapshot0Whence { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Cur, + 1 => Self::End, + 2 => Self::Set, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl wit_bindgen_wasmer::wasmer::FromToNativeWasmType for Whence { + type Native = i32; + + fn to_native(self) -> Self::Native { + self as i32 + } + fn from_native(n: Self::Native) -> Self { + match n { + 0 => Self::Set, + 1 => Self::Cur, + 2 => Self::End, + // TODO: What should we map invalid native values to? + _ => todo!("Need to decide what to do here…"), + } + } + + #[cfg(feature = "sys")] + fn is_from_store(&self, _store: &impl wit_bindgen_wasmer::wasmer::AsStoreRef) -> bool { + // TODO: find correct implementation + false + } +} + +// TODO: if necessary, must be implemented in wit-bindgen +unsafe impl ValueType for Snapshot0Clockid { + #[inline] + fn zero_padding_bytes(&self, _bytes: &mut [MaybeUninit]) {} +} + +impl Eventtype { + pub fn to_str(self) -> &'static str { + match self { + Eventtype::Clock => "Wasi::Eventtype::Clock", + Eventtype::FdRead => "Wasi::Eventtype::FdRead", + Eventtype::FdWrite => "Wasi::Eventtype::FdWrite", + } + } +} + +/// Workaround implementation because `wit-bindgen` does not generate +/// type aliases, but instead creates the same filetype in each module +/// for `use` statements in the `.wit` file. +impl From for Snapshot0Clockid { + fn from(other: Clockid) -> Self { + match other { + Clockid::Realtime => Self::Realtime, + Clockid::Monotonic => Self::Monotonic, + } + } +} + +impl From for Clockid { + fn from(other: Snapshot0Clockid) -> Self { + match other { + Snapshot0Clockid::Realtime => Self::Realtime, + Snapshot0Clockid::Monotonic => Self::Monotonic, + Snapshot0Clockid::ProcessCputimeId => todo!("not implemented for now"), + Snapshot0Clockid::ThreadCputimeId => todo!("not implemented for now"), + } + } +} + +impl From for SubscriptionClock { + fn from(other: Snapshot0SubscriptionClock) -> Self { + // TODO: this removes Snapshot0SubscriptionClock::identifier, I don't + // think this is how it should be + Self { + clock_id: Clockid::from(other.id), + timeout: other.timeout, + precision: other.precision, + flags: other.flags, + } + } +} + +impl From for SubscriptionEnum { + fn from(other: Snapshot0SubscriptionEnum) -> Self { + match other { + Snapshot0SubscriptionEnum::Clock(d) => Self::Clock(SubscriptionClock::from(d)), + Snapshot0SubscriptionEnum::Read(d) => Self::Read(d), + Snapshot0SubscriptionEnum::Write(d) => Self::Write(d), + } + } +} + +impl From for Subscription { + fn from(other: Snapshot0Subscription) -> Self { + Self { + userdata: other.userdata, + data: SubscriptionEnum::from(other.data), + } + } +} diff --git a/lib/wasi-types-generated/src/wasi_filesystem/mod.rs b/lib/wasi-types-generated/src/wasi_filesystem/mod.rs new file mode 100644 index 00000000000..e69de29bb2d diff --git a/lib/wasi-types-generated/src/wasi_io_typenames/mod.rs b/lib/wasi-types-generated/src/wasi_io_typenames/mod.rs new file mode 100644 index 00000000000..e69de29bb2d diff --git a/lib/wasi-types-generated/src/wasi_snapshot0/mod.rs b/lib/wasi-types-generated/src/wasi_snapshot0/mod.rs new file mode 100644 index 00000000000..e69de29bb2d diff --git a/lib/wasi-types-generated/wit-clean/typenames.wit b/lib/wasi-types-generated/wit-clean/typenames.wit new file mode 100644 index 00000000000..019d3bf0184 --- /dev/null +++ b/lib/wasi-types-generated/wit-clean/typenames.wit @@ -0,0 +1,814 @@ +// Extracted from: +// https://github.com/WebAssembly/WASI/blob/main/phases/old/snapshot_0/witx/typenames.witx +// https://github.com/WebAssembly/wasi-io/blob/main/standard/io/witx/typenames.witx + + + +/// Dummy function to expose types into generated code +expose-types-dummy-func: func( + fd: fd, + dirent: dirent, + event-enum: event-enum, + event: event, + fdstat: fdstat, + subscription-clock: subscription-clock, + snapshot0-subscription-clock: snapshot0-subscription-clock, + subscription: subscription, + snapshot0-subscription: snapshot0-subscription, + device: device, + linkcount: linkcount, + snapshot0-linkcount: snapshot0-linkcount, + filestat: filestat, + snapshot0-filestat: snapshot0-filestat, + tty: tty, + tid: tid, + pid: pid, +) + + + +/// Type names used by low-level WASI interfaces. + +/// An array size. +/// +/// Note: This is similar to `size_t` in POSIX. +// TODO: This is defined as `usize` in the original witx file. Should verify that this type is good as it is defined here +type size = u32 + +/// Non-negative file size or length of a region within a file. +type filesize = u64 + +/// Timestamp in nanoseconds. +type timestamp = u64 + +/// A file descriptor handle. +// TODO: this is of type `handle` in the witx file +type fd = u32 + +/// A reference to the offset of a directory entry. +type dircookie = u64 + +// In an `fd_readdir` call, this value signifies the start of the directory. +// TODO: this cannot be represented in .wit files as of today +// (@witx const $dircookie $start 0) + +/// The type for the `dirent::d-namlen` field of `dirent` struct. +type dirnamlen = u32 + +/// File serial number that is unique within its file system. +type inode = u64 + +/// Identifier for a device containing a file system. Can be used in combination +/// with `inode` to uniquely identify a file or directory in the filesystem. +type device = u64 + +type linkcount = u64 +type snapshot0-linkcount = u32 + +type tid = u32 +type pid = u32 + +/// Identifiers for clocks, snapshot0 version. +enum snapshot0-clockid { + // TODO: wit appears to not have support for enum tag types + //(@witx tag u32) + + /// The clock measuring real time. Time value zero corresponds with + /// 1970-01-01T00:00:00Z. + realtime, + /// The store-wide monotonic clock, which is defined as a clock measuring + /// real time, whose value cannot be adjusted and which cannot have negative + /// clock jumps. The epoch of this clock is undefined. The absolute time + /// value of this clock therefore has no meaning. + monotonic, + /// The CPU-time clock associated with the current process. + process-cputime-id, + /// The CPU-time clock associated with the current thread. + thread-cputime-id, +} + +/// Identifiers for clocks. +enum clockid { + // TODO: wit appears to not have support for enum tag types + //(@witx tag u32) + + /// The clock measuring real time. Time value zero corresponds with + /// 1970-01-01T00:00:00Z. + realtime, + /// The store-wide monotonic clock, which is defined as a clock measuring + /// real time, whose value cannot be adjusted and which cannot have negative + /// clock jumps. The epoch of this clock is undefined. The absolute time + /// value of this clock therefore has no meaning. + monotonic, +} + +/// Error codes returned by functions. +/// Not all of these error codes are returned by the functions provided by this +/// API; some are used in higher-level library layers, and others are provided +/// merely for alignment with POSIX. +enum errno { + // TODO: wit appears to not have support for enum tag types + //(@witx tag u16) + + /// No error occurred. System call completed successfully. + success, + /// Argument list too long. + toobig, + /// Permission denied. + access, + /// Address in use. + addrinuse, + /// Address not available. + addrnotavail, + /// Address family not supported. + afnosupport, + /// Resource unavailable, or operation would block. + again, + /// Connection already in progress. + already, + /// Bad file descriptor. + badf, + /// Bad message. + badmsg, + /// Device or resource busy. + busy, + /// Operation canceled. + canceled, + /// No child processes. + child, + /// Connection aborted. + connaborted, + /// Connection refused. + connrefused, + /// Connection reset. + connreset, + /// Resource deadlock would occur. + deadlk, + /// Destination address required. + destaddrreq, + /// Mathematics argument out of domain of function. + dom, + /// Reserved. + dquot, + /// File exists. + exist, + /// Bad address. + fault, + /// File too large. + fbig, + /// Host is unreachable. + hostunreach, + /// Identifier removed. + idrm, + /// Illegal byte sequence. + ilseq, + /// Operation in progress. + inprogress, + /// Interrupted function. + intr, + /// Invalid argument. + inval, + /// I/O error. + io, + /// Socket is connected. + isconn, + /// Is a directory. + isdir, + /// Too many levels of symbolic links. + loop, + /// File descriptor value too large. + mfile, + /// Too many links. + mlink, + /// Message too large. + msgsize, + /// Reserved. + multihop, + /// Filename too long. + nametoolong, + /// Network is down. + netdown, + /// Connection aborted by network. + netreset, + /// Network unreachable. + netunreach, + /// Too many files open in system. + nfile, + /// No buffer space available. + nobufs, + /// No such device. + nodev, + /// No such file or directory. + noent, + /// Executable file format error. + noexec, + /// No locks available. + nolck, + /// Reserved. + nolink, + /// Not enough space. + nomem, + /// No message of the desired type. + nomsg, + /// Protocol not available. + noprotoopt, + /// No space left on device. + nospc, + /// Function not supported. + nosys, + /// The socket is not connected. + notconn, + /// Not a directory or a symbolic link to a directory. + notdir, + /// Directory not empty. + notempty, + /// State not recoverable. + notrecoverable, + /// Not a socket. + notsock, + /// Not supported, or operation not supported on socket. + notsup, + /// Inappropriate I/O control operation. + notty, + /// No such device or address. + nxio, + /// Value too large to be stored in data type. + overflow, + /// Previous owner died. + ownerdead, + /// Operation not permitted. + perm, + /// Broken pipe. + pipe, + /// Protocol error. + proto, + /// Protocol not supported. + protonosupport, + /// Protocol wrong type for socket. + prototype, + /// Result too large. + range, + /// Read-only file system. + rofs, + /// Invalid seek. + spipe, + /// No such process. + srch, + /// Reserved. + stale, + /// Connection timed out. + timedout, + /// Text file busy. + txtbsy, + /// Cross-device link. + xdev, + /// Extension: Capabilities insufficient. + notcapable, +} + +enum bus-errno { + // TODO: wit appears to not have support for enum tag types + //(@witx tag u32) + + /// No error occurred. Call completed successfully. + success, + /// Failed during serialization + ser, + /// Failed during deserialization + des, + /// Invalid WAPM process + wapm, + /// Failed to fetch the WAPM process + fetch, + /// Failed to compile the WAPM process + compile, + /// Invalid ABI + abi, + /// Call was aborted + aborted, + /// Bad handle + badhandle, + /// Invalid topic + topic, + /// Invalid callback + badcb, + /// Call is unsupported + unsupported, + /// Bad request + badrequest, + /// Access denied + denied, + /// Internal error has occured + internal, + /// Memory allocation failed + alloc, + /// Invocation has failed + invoke, + /// Already consumed + consumed, + /// Memory access violation + memviolation, + /// Some other unhandled error. If you see this, it's probably a bug. + unknown, +} + +/// File descriptor rights, determining which actions may be performed. +flags rights { + // TODO: wit doesnt appear to support repr + // flags (@witx repr u64) + + /// The right to invoke `fd_datasync`. + /// + /// If `rights::path_open` is set, includes the right to invoke + /// `path_open` with `fdflags::dsync`. + fd-datasync, + /// The right to invoke `fd_read` and `sock_recv`. + /// + /// If `rights::fd_seek` is set, includes the right to invoke `fd_pread`. + fd-read, + /// The right to invoke `fd_seek`. This flag implies `rights::fd_tell`. + fd-seek, + /// The right to invoke `fd_fdstat_set_flags`. + fd-fdstat-set-flags, + /// The right to invoke `fd_sync`. + /// + /// If `rights::path_open` is set, includes the right to invoke + /// `path_open` with `fdflags::rsync` and `fdflags::dsync`. + fd-sync, + /// The right to invoke `fd_seek` in such a way that the file offset + /// remains unaltered (i.e., `whence::cur` with offset zero), or to + /// invoke `fd_tell`. + fd-tell, + /// The right to invoke `fd_write` and `sock_send`. + /// If `rights::fd_seek` is set, includes the right to invoke `fd_pwrite`. + fd-write, + /// The right to invoke `fd_advise`. + fd-advise, + /// The right to invoke `fd_allocate`. + fd-allocate, + /// The right to invoke `path_create_directory`. + path-create-directory, + /// If `rights::path_open` is set, the right to invoke `path_open` with `oflags::creat`. + path-create-file, + /// The right to invoke `path_link` with the file descriptor as the + /// source directory. + path-link-source, + /// The right to invoke `path_link` with the file descriptor as the + /// target directory. + path-link-target, + /// The right to invoke `path_open`. + path-open, + /// The right to invoke `fd_readdir`. + fd-readdir, + /// The right to invoke `path_readlink`. + path-readlink, + /// The right to invoke `path_rename` with the file descriptor as the source directory. + path-rename-source, + /// The right to invoke `path_rename` with the file descriptor as the target directory. + path-rename-target, + /// The right to invoke `path_filestat_get`. + path-filestat-get, + /// The right to change a file's size (there is no `path_filestat_set_size`). + /// If `rights::path_open` is set, includes the right to invoke `path_open` with `oflags::trunc`. + path-filestat-set-size, + /// The right to invoke `path_filestat_set_times`. + path-filestat-set-times, + /// The right to invoke `fd_filestat_get`. + fd-filestat-get, + /// The right to invoke `fd_filestat_set_size`. + fd-filestat-set-size, + /// The right to invoke `fd_filestat_set_times`. + fd-filestat-set-times, + /// The right to invoke `path_symlink`. + path-symlink, + /// The right to invoke `path_remove_directory`. + path-remove-directory, + /// The right to invoke `path_unlink_file`. + path-unlink-file, + /// If `rights::fd_read` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_read`. + /// If `rights::fd_write` is set, includes the right to invoke `poll_oneoff` to subscribe to `eventtype::fd_write`. + poll-fd-readwrite, + /// The right to invoke `sock_shutdown`. + sock-shutdown, + + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-accept, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-connect, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-listen, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-bind, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-recv, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-send, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-addr-local, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-addr-remote, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-recv-from, + /// TODO: Found in wasmer-wasi-types rust project, but not in wasi-snapshot0 + sock-send-to, +} + +/// The type of a file descriptor or file. +enum filetype { + // TODO: wit appears to not have support for enum tag types + //(@witx tag u8) + + /// The type of the file descriptor or file is unknown or is different from any of the other types specified. + unknown, + /// The file descriptor or file refers to a block device inode. + block-device, + /// The file descriptor or file refers to a character device inode. + character-device, + /// The file descriptor or file refers to a directory inode. + directory, + /// The file descriptor or file refers to a regular file inode. + regular-file, + /// The file descriptor or file refers to a datagram socket. + socket-dgram, + /// The file descriptor or file refers to a byte-stream socket. + socket-stream, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The file descriptor or file refers to a FIFO. + fifo, +} + +/// A directory entry, snapshot0 version. +record snapshot0-dirent { + /// The offset of the next directory entry stored in this directory. + d-next: dircookie, + /// The serial number of the file referred to by this directory entry. + d-ino: inode, + /// The length of the name of the directory entry. + d-namlen: dirnamlen, + /// The type of the file referred to by this directory entry. + d-type: filetype, +} + +/// A directory entry. +record dirent { + /// The offset of the next directory entry stored in this directory. + d-next: dircookie, + /// The serial number of the file referred to by this directory entry. + d-ino: inode, + /// The type of the file referred to by this directory entry. + d-type: filetype, + /// The length of the name of the directory entry. + d-namlen: dirnamlen, +} + +/// File or memory access pattern advisory information. +enum advice { + // TODO: wit appears to not have support for enum tag types + //enum (@witx tag u8) + + /// The application has no advice to give on its behavior with respect to the specified data. + normal, + /// The application expects to access the specified data sequentially from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random order. + random, + /// The application expects to access the specified data in the near future. + willneed, + /// The application expects that it will not access the specified data in the near future. + dontneed, + /// The application expects to access the specified data once and then not reuse it thereafter. + noreuse, +} + +/// File descriptor flags. +flags fdflags { + // TODO: wit appears to not have support for flags repr + //(@witx repr u16) + + /// Append mode: Data written to the file is always appended to the file's end. + append, + /// Write according to synchronized I/O data integrity completion. Only the data stored in the file is synchronized. + dsync, + /// Non-blocking mode. + nonblock, + /// Synchronized read I/O operations. + rsync, + /// Write according to synchronized I/O file integrity completion. In + /// addition to synchronizing the data stored in the file, the implementation + /// may also synchronously update the file's metadata. + sync, +} + +/// File descriptor attributes. +record fdstat { + /// File type. + fs-filetype: filetype, + /// File descriptor flags. + fs-flags: fdflags, + /// Rights that apply to this file descriptor. + fs-rights-base: rights, + /// Maximum set of rights that may be installed on new file descriptors that + /// are created through this file descriptor, e.g., through `path_open`. + fs-rights-inheriting: rights, +} + +/// Which file time attributes to adjust. +flags fstflags { + // TODO: wit appears to not have support for flags repr + //(@witx repr u16) + + /// Adjust the last data access timestamp to the value stored in `filestat::atim`. + set-atim, + /// Adjust the last data access timestamp to the time of clock `clockid::realtime`. + set-atim-now, + /// Adjust the last data modification timestamp to the value stored in `filestat::mtim`. + set-mtim, + /// Adjust the last data modification timestamp to the time of clock `clockid::realtime`. + set-mtim-now, +} + +/// Flags determining the method of how paths are resolved. +flags lookup { + // TODO: wit appears to not have support for flags repr + //(@witx repr u32) + + /// As long as the resolved path corresponds to a symbolic link, it is expanded. + symlink-follow, +} + +/// Open flags used by `path_open`. +flags oflags { + // TODO: wit appears to not have support for flags repr + //(@witx repr u16) + + /// Create file if it does not exist. + create, + /// Fail if not a directory. + directory, + /// Fail if file already exists. + excl, + /// Truncate file to size 0. + trunc, +} + +/// User-provided value that may be attached to objects that is retained when +/// extracted from the implementation. +type userdata = u64 + +/// Type of a subscription to an event or its occurrence. +enum eventtype { + // TODO: wit appears to not have support for enum tag types + //(@witx tag u8) + + /// The time value of clock `subscription_clock::id` has + /// reached timestamp `subscription_clock::timeout`. + clock, + /// File descriptor `subscription_fd_readwrite::fd` has data + /// available for reading. This event always triggers for regular files. + fd-read, + /// File descriptor `subscription_fd_readwrite::fd` has capacity + /// available for writing. This event always triggers for regular files. + fd-write, +} + +/// Flags determining how to interpret the timestamp provided in +/// `subscription-clock::timeout`. +flags subclockflags { + // TODO: wit appears to not have support for flags repr + //@witx repr u16) + /// If set, treat the timestamp provided in + /// `subscription-clock::timeout` as an absolute timestamp of clock + /// `subscription-clock::id`. If clear, treat the timestamp + /// provided in `subscription-clock::timeout` relative to the + /// current time value of clock `subscription-clock::id`. + subscription-clock-abstime, +} + +/// The contents of a `subscription` when type is `eventtype::clock`. +record snapshot0-subscription-clock { + /// The user-defined unique identifier of the clock. + identifier: userdata, + /// The clock against which to compare the timestamp. + id: snapshot0-clockid, + /// The absolute or relative timestamp. + timeout: timestamp, + /// The amount of time that the implementation may wait additionally + /// to coalesce with other events. + precision: timestamp, + /// Flags specifying whether the timeout is absolute or relative + %flags: subclockflags +} + +/// The contents of a `subscription` when type is `eventtype::clock`. +record subscription-clock { + /// The clock against which to compare the timestamp. + clock-id: clockid, + /// The absolute or relative timestamp. + timeout: timestamp, + /// The amount of time that the implementation may wait additionally + /// to coalesce with other events. + precision: timestamp, + /// Flags specifying whether the timeout is absolute or relative + %flags: subclockflags, +} + +/// Identifiers for preopened capabilities. +enum preopentype { + // TODO: wit appears to not have support for enum tag types + //(@witx tag u8) + + /// A pre-opened directory. + dir, +} + +/// The state of the file descriptor subscribed to with +/// `eventtype::fd_read` or `eventtype::fd_write`. +flags eventrwflags { + // TODO: wit appears to not have support for flags repr + //@witx repr u16) + + /// The peer of this socket has closed or disconnected. + fd-readwrite-hangup, +} + +/// The contents of an `event` for the `eventtype::fd_read` and +/// `eventtype::fd_write` variants +record event-fd-readwrite { + /// The number of bytes available for reading or writing. + nbytes: filesize, + /// The state of the file descriptor. + %flags: eventrwflags, +} + +/// An event that occurred. +record event { + /// User-provided value that got attached to `subscription::userdata`. + userdata: userdata, + /// If non-zero, an error that occurred while processing the subscription request. + error: errno, + /// The type of the event that occurred, and the contents of the event + data: event-enum +} + +/// The contents of an `event`. +variant event-enum { + // TODO: wit appears to not have support for tag type + //(@witx tag $eventtype) + fd-read(event-fd-readwrite), + fd-write(event-fd-readwrite), + clock, +} + + +/// An event that occurred. +record snapshot0-event { + /// User-provided value that got attached to `subscription::userdata`. + userdata: userdata, + /// If non-zero, an error that occurred while processing the subscription request. + error: errno, + /// The type of event that occured + %type: eventtype, + /// The contents of the event, if it is an `eventtype::fd_read` or + /// `eventtype::fd_write`. `eventtype::clock` events ignore this field. + fd-readwrite: event-fd-readwrite, +} + +/// The contents of a `subscription`, snapshot0 version. +variant snapshot0-subscription-enum { + // TODO: wit appears to have no support for tag types + //(@witx tag $eventtype) + clock(snapshot0-subscription-clock), + read(subscription-fs-readwrite), + write(subscription-fs-readwrite), +} + +/// The contents of a `subscription`. +variant subscription-enum { + // TODO: wit appears to have no support for tag types + //(@witx tag $eventtype) + clock(subscription-clock), + read(subscription-fs-readwrite), + write(subscription-fs-readwrite), +} + +/// The contents of a `subscription` when the variant is +/// `eventtype::fd_read` or `eventtype::fd_write`. +record subscription-fs-readwrite { + /// The file descriptor on which to wait for it to become ready for reading or writing. + file-descriptor: fd, +} + +record snapshot0-subscription { + userdata: userdata, + data: snapshot0-subscription-enum, +} + +record subscription { + userdata: userdata, + data: subscription-enum, +} + +enum socktype { + dgram, + %stream, + raw, + seqpacket, +} + +enum sockstatus { + opening, + opened, + closed, + failed, +} + +enum sockoption { + noop, + reuse-port, + reuse-addr, + no-delay, + dont-route, + only-v6, + broadcast, + multicast-loop-v4, + multicast-loop-v6, + promiscuous, + listening, + last-error, + keep-alive, + linger, + oob-inline, + recv-buf-size, + send-buf-size, + recv-lowat, + send-lowat, + recv-timeout, + send-timeout, + connect-timeout, + accept-timeout, + ttl, + multicast-ttl-v4, + %type, + proto, +} + +enum streamsecurity { + unencrypted, + any-encryption, + classic-encryption, + double-encryption, +} + +enum addressfamily { + unspec, + inet4, + inet6, + unix, +} + +record snapshot0-filestat { + st-dev: device, + st-ino: inode, + st-filetype: filetype, + st-nlink: snapshot0-linkcount, + st-size: filesize, + st-atim: timestamp, + st-mtim: timestamp, + st-ctim: timestamp, +} + +record filestat { + st-dev: device, + st-ino: inode, + st-filetype: filetype, + st-nlink: linkcount, + st-size: filesize, + st-atim: timestamp, + st-mtim: timestamp, + st-ctim: timestamp, +} + +enum snapshot0-whence { + cur, + end, + set, +} + +enum whence { + set, + cur, + end, +} + +record tty { + cols: u32, + rows: u32, + width: u32, + height: u32, + stdin-tty: bool, + stdout-tty: bool, + stderr-tty: bool, + echo: bool, + line-buffered: bool, +} diff --git a/lib/wasi-types-generated/wit-clean/wasi_unstable.wit b/lib/wasi-types-generated/wit-clean/wasi_unstable.wit new file mode 100644 index 00000000000..6255fc09dc0 --- /dev/null +++ b/lib/wasi-types-generated/wit-clean/wasi_unstable.wit @@ -0,0 +1,3 @@ + +// TODO: translate https://github.com/WebAssembly/WASI/blob/main/phases/old/snapshot_0/witx/wasi_unstable.witx +// if importing doesn't work, put it in typenames.wit \ No newline at end of file diff --git a/lib/wasi-types-generated/wit/wasi-filesystem.wit b/lib/wasi-types-generated/wit/wasi-filesystem.wit new file mode 100644 index 00000000000..78be8e6ce7e --- /dev/null +++ b/lib/wasi-types-generated/wit/wasi-filesystem.wit @@ -0,0 +1,626 @@ +// Extracted from https://github.com/WebAssembly/wasi-filesystem/blob/main/wasi-filesystem.wit.md + +/// Size of a range of bytes in memory. +type size = u32 + +/// Non-negative file size or length of a region within a file. +type filesize = u64 + +/// Relative offset within a file. +type filedelta = s64 + +/// Timestamp in nanoseconds. +/// +/// TODO: wasi-clocks is moving to seconds+nanoseconds. +type timestamp = u64 + +/// Information associated with a descriptor. +/// +/// Note: This was called `fdstat` in earlier versions of WASI. +record info { + /// The type of filesystem object referenced by a descriptor. + %type: %type, + /// Flags associated with a descriptor. + %flags: %flags, +} + +/// The type of a filesystem object referenced by a descriptor. +/// +/// Note: This was called `filetype` in earlier versions of WASI. +enum %type { + /// The type of the descriptor or file is unknown or is different from + /// any of the other types specified. + unknown, + /// The descriptor refers to a block device inode. + block-device, + /// The descriptor refers to a character device inode. + character-device, + /// The descriptor refers to a directory inode. + directory, + /// The descriptor refers to a named pipe. + fifo, + /// The file refers to a symbolic link inode. + symbolic-link, + /// The descriptor refers to a regular file inode. + regular-file, + /// The descriptor refers to a socket. + socket, +} + +/// Descriptor flags. +/// +/// Note: This was called `fd-flags` in earlier versions of WASI. +flags %flags { + /// Read mode: Data can be read. + read, + /// Write mode: Data can be written to. + write, + /// Append mode: Data written to the file is always appended to the file's + /// end. + append, + /// Write according to synchronized I/O data integrity completion. Only the + /// data stored in the file is synchronized. + dsync, + /// Non-blocking mode. + nonblock, + /// Synchronized read I/O operations. + rsync, + /// Write according to synchronized I/O file integrity completion. In + /// addition to synchronizing the data stored in the file, the + /// implementation may also synchronously update the file's metadata. + sync, +} + +/// File attributes. +/// +/// Note: This was called `filestat` in earlier versions of WASI. +record stat { + /// Device ID of device containing the file. + dev: device, + /// File serial number. + ino: inode, + /// File type. + %type: %type, + /// Number of hard links to the file. + nlink: linkcount, + /// For regular files, the file size in bytes. For symbolic links, the length + /// in bytes of the pathname contained in the symbolic link. + size: filesize, + /// Last data access timestamp. + atim: timestamp, + /// Last data modification timestamp. + mtim: timestamp, + /// Last file status change timestamp. + ctim: timestamp, +} + +/// Flags determining the method of how paths are resolved. +flags at-flags { + /// As long as the resolved path corresponds to a symbolic link, it is expanded. + symlink-follow, +} + +/// Open flags used by `open-at`. +flags o-flags { + /// Create file if it does not exist. + create, + /// Fail if not a directory. + directory, + /// Fail if file already exists. + excl, + /// Truncate file to size 0. + trunc, +} + +/// Permissions mode used by `open-at`, `change-permissions-at`, and similar. +flags mode { + /// True if the resource is considered readable by the containing + /// filesystem. + readable, + /// True if the resource is considered writeable by the containing + /// filesystem. + writeable, + /// True if the resource is considered executable by the containing + /// filesystem. This does not apply to directories. + executable, +} + +/// Number of hard links to an inode. +type linkcount = u64 + +/// Identifier for a device containing a file system. Can be used in combination +/// with `inode` to uniquely identify a file or directory in the filesystem. +type device = u64 + +/// Filesystem object serial number that is unique within its file system. +type inode = u64 + +/// When setting a timestamp, this gives the value to set it to. +variant new-timestamp { + /// Leave the timestamp set to its previous value. + no-change, + /// Set the timestamp to the current time of the system clock associated + /// with the filesystem. + now, + /// Set the timestamp to the given value. + timestamp(timestamp), +} + +/// A directory entry. +record dirent { + /// The serial number of the file referred to by this directory entry. + ino: inode, + /// The length of the name of the directory entry. + namelen: size, + /// The type of the file referred to by this directory entry. + %type: %type, +} + +/// Error codes returned by functions. +/// Not all of these error codes are returned by the functions provided by this +/// API; some are used in higher-level library layers, and others are provided +/// merely for alignment with POSIX. +enum errno { + /// No error occurred. System call completed successfully. + success, + /// Argument list too long. This is similar to `E2BIG` in POSIX. + toobig, + /// Permission denied. + access, + /// Address in use. + addrinuse, + /// Address not available. + addrnotavail, + /// Address family not supported. + afnosupport, + /// Resource unavailable, or operation would block. + again, + /// Connection already in progress. + already, + /// Bad message. + badmsg, + /// Device or resource busy. + busy, + /// Operation canceled. + canceled, + /// No child processes. + child, + /// Connection aborted. + connaborted, + /// Connection refused. + connrefused, + /// Connection reset. + connreset, + /// Resource deadlock would occur. + deadlk, + /// Destination address required. + destaddrreq, + /// Mathematics argument out of domain of function. + dom, + /// Reserved. + dquot, + /// File exists. + exist, + /// Bad address. + fault, + /// File too large. + fbig, + /// Host is unreachable. + hostunreach, + /// Identifier removed. + idrm, + /// Illegal byte sequence. + ilseq, + /// Operation in progress. + inprogress, + /// Interrupted function. + intr, + /// Invalid argument. + inval, + /// I/O error. + io, + /// Socket is connected. + isconn, + /// Is a directory. + isdir, + /// Too many levels of symbolic links. + loop, + /// File descriptor value too large. + mfile, + /// Too many links. + mlink, + /// Message too large. + msgsize, + /// Reserved. + multihop, + /// Filename too long. + nametoolong, + /// Network is down. + netdown, + /// Connection aborted by network. + netreset, + /// Network unreachable. + netunreach, + /// Too many files open in system. + nfile, + /// No buffer space available. + nobufs, + /// No such device. + nodev, + /// No such file or directory. + noent, + /// Executable file format error. + noexec, + /// No locks available. + nolck, + /// Reserved. + nolink, + /// Not enough space. + nomem, + /// No message of the desired type. + nomsg, + /// Protocol not available. + noprotoopt, + /// No space left on device. + nospc, + /// Function not supported. + nosys, + /// The socket is not connected. + notconn, + /// Not a directory or a symbolic link to a directory. + notdir, + /// Directory not empty. + notempty, + /// State not recoverable. + notrecoverable, + /// Not a socket. + notsock, + /// Not supported, or operation not supported on socket. + notsup, + /// Inappropriate I/O control operation. + notty, + /// No such device or address. + nxio, + /// Value too large to be stored in data type. + overflow, + /// Previous owner died. + ownerdead, + /// Operation not permitted. + perm, + /// Broken pipe. + pipe, + /// Protocol error. + proto, + /// Protocol not supported. + protonosupport, + /// Protocol wrong type for socket. + prototype, + /// Result too large. + range, + /// Read-only file system. + rofs, + /// Invalid seek. + spipe, + /// No such process. + srch, + /// Reserved. + stale, + /// Connection timed out. + timedout, + /// Text file busy. + txtbsy, + /// Cross-device link. + xdev, +} + +/// File or memory access pattern advisory information. +enum advice { + /// The application has no advice to give on its behavior with respect to the specified data. + normal, + /// The application expects to access the specified data sequentially from lower offsets to higher offsets. + sequential, + /// The application expects to access the specified data in a random order. + random, + /// The application expects to access the specified data in the near future. + will-need, + /// The application expects that it will not access the specified data in the near future. + dont-need, + /// The application expects to access the specified data once and then not reuse it thereafter. + no-reuse, +} + +/// The position relative to which to set the offset of the descriptor. +variant seek-from { + /// Seek relative to start-of-file. + set(filesize), + /// Seek relative to current position. + cur(filedelta), + /// Seek relative to end-of-file. + end(filesize), +} + +/// A descriptor is a reference to a filesystem object, which may be a file, +/// directory, named pipe, special file, or other object on which filesystem +/// calls may be made. +resource descriptor { + /// Provide file advisory information on a descriptor. + /// + /// This is similar to `posix_fadvise` in POSIX. + fadvise: func( + /// The offset within the file to which the advisory applies. + offset: u64, + /// The length of the region to which the advisory applies. + len: u64, + /// The advice. + advice: advice + ) -> expected + + /// Force the allocation of space in a file. + /// + /// Note: This is similar to `posix_fallocate` in POSIX. + fallocate: func( + /// The offset at which to start the allocation. + offset: filesize, + /// The length of the area that is allocated. + len: filesize + ) -> expected + + /// Synchronize the data of a file to disk. + /// + /// Note: This is similar to `fdatasync` in POSIX. + datasync: func() -> expected + + /// Get information associated with a descriptor. + /// + /// Note: This returns similar flags to `fsync(fd, F_GETFL)` in POSIX, as well + /// as additional fields. + /// + /// Note: This was called `fdstat_get` in earlier versions of WASI. + info: func() -> expected + + /// Adjust the size of an open file. If this increases the file's size, the + /// extra bytes are filled with zeros. + /// + /// Note: This was called `fd_filestat_set_size` in earlier versions of WASI. + set-size: func(size: filesize) -> expected + + /// Adjust the timestamps of an open file or directory. + /// + /// Note: This is similar to `futimens` in POSIX. + /// + /// Note: This was called `fd_filestat_set_times` in earlier versions of WASI. + set-times: func( + /// The desired values of the data access timestamp. + atim: new-timestamp, + /// The desired values of the data modification timestamp. + mtim: new-timestamp, + ) -> expected + +// /// Read from a descriptor, without using and updating the descriptor's offset. +// /// +// /// Note: This is similar to `pread` in POSIX. +// pread: func( +// /// The offset within the file at which to read. +// offset: filesize, +// ) -> stream +// +// /// Write to a descriptor, without using and updating the descriptor's offset. +// /// +// /// Note: This is similar to `pwrite` in POSIX. +// pwrite: func( +// /// Data to write +// buf: stream, +// /// The offset within the file at which to write. +// offset: filesize, +// ) -> future> +// +// /// Read from a descriptor. +// /// +// /// The meaning of `read` on a directory is unspecified. +// /// +// /// Note: This is similar to `read` in POSIX. +// read: func() -> stream +// +// /// Read directory entries from a directory. +// /// +// /// When successful, the contents of the output buffer consist of a sequence of +// /// directory entries. Each directory entry consists of a `dirent` object, +// /// followed by `dirent::d_namlen` bytes holding the name of the directory +// /// entry. +// /// +// /// This function fills the output buffer as much as possible, potentially +// /// truncating the last directory entry. This allows the caller to grow its +// /// read buffer size in case it's too small to fit a single large directory +// /// entry, or skip the oversized directory entry. +// readdir: func( +// /// If true, rewind the current position to the beginning before reading. +// rewind: bool +// ) -> stream + + /// Move the offset of a descriptor. + /// + /// The meaning of `seek` on a directory is unspecified. + /// + /// Returns new offset of the descriptor, relative to the start of the file. + /// + /// Note: This is similar to `lseek` in POSIX. + seek: func( + /// The method to compute the new offset. + %from: seek-from, + ) -> expected + + /// Synchronize the data and metadata of a file to disk. + /// + /// Note: This is similar to `fsync` in POSIX. + sync: func() -> expected + + /// Return the current offset of a descriptor. + /// + /// Returns the current offset of the descriptor, relative to the start of the file. + /// + /// Note: This is similar to `lseek(fd, 0, SEEK_CUR)` in POSIX. + tell: func() -> expected + +// /// Write to a descriptor. +// /// +// /// Note: This is similar to `write` in POSIX. +// write: func( +// /// Data to write +// buf: stream, +// ) -> future> + + /// Create a directory. + /// + /// Note: This is similar to `mkdirat` in POSIX. + create-directory-at: func( + /// The relative path at which to create the directory. + path: string, + ) -> expected + + /// Return the attributes of a file or directory. + /// + /// Note: This is similar to `fstatat` in POSIX. + /// + /// Note: This was called `fd_filestat_get` in earlier versions of WASI. + stat-at: func( + /// Flags determining the method of how the path is resolved. + at-flags: at-flags, + /// The relative path of the file or directory to inspect. + path: string, + ) -> expected + + /// Adjust the timestamps of a file or directory. + /// + /// Note: This is similar to `utimensat` in POSIX. + /// + /// Note: This was called `path_filestat_set_times` in earlier versions of WASI. + set-times-at: func( + /// Flags determining the method of how the path is resolved. + at-flags: at-flags, + /// The relative path of the file or directory to operate on. + path: string, + /// The desired values of the data access timestamp. + atim: new-timestamp, + /// The desired values of the data modification timestamp. + mtim: new-timestamp, + ) -> expected + + /// Create a hard link. + /// + /// Note: This is similar to `linkat` in POSIX. + link-at: func( + /// Flags determining the method of how the path is resolved. + old-at-flags: at-flags, + /// The relative source path from which to link. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: handle descriptor, + /// The relative destination path at which to create the hard link. + new-path: string, + ) -> expected + + /// Open a file or directory. + /// + /// The returned descriptor is not guaranteed to be the lowest-numbered + /// descriptor not currently open/ it is randomized to prevent applications + /// from depending on making assumptions about indexes, since this is + /// error-prone in multi-threaded contexts. The returned descriptor is + /// guaranteed to be less than 2**31. + /// + /// Note: This is similar to `openat` in POSIX. + open-at: func( + /// Flags determining the method of how the path is resolved. + at-flags: at-flags, + /// The relative path of the object to open. + path: string, + /// The method by which to open the file. + o-flags: o-flags, + /// Flags to use for the resulting descriptor. + %flags: %flags, + /// Permissions to use when creating a new file. + mode: mode + ) -> expected + + /// Read the contents of a symbolic link. + /// + /// Note: This is similar to `readlinkat` in POSIX. + readlink-at: func( + /// The relative path of the symbolic link from which to read. + path: string, + ) -> expected + + /// Remove a directory. + /// + /// Return `errno::notempty` if the directory is not empty. + /// + /// Note: This is similar to `unlinkat(fd, path, AT_REMOVEDIR)` in POSIX. + remove-directory-at: func( + /// The relative path to a directory to remove. + path: string, + ) -> expected + + /// Rename a filesystem object. + /// + /// Note: This is similar to `renameat` in POSIX. + rename-at: func( + /// The relative source path of the file or directory to rename. + old-path: string, + /// The base directory for `new-path`. + new-descriptor: handle descriptor, + /// The relative destination path to which to rename the file or directory. + new-path: string, + ) -> expected + + /// Create a symbolic link. + /// + /// Note: This is similar to `symlinkat` in POSIX. + symlink-at: func( + /// The contents of the symbolic link. + old-path: string, + /// The relative destination path at which to create the symbolic link. + new-path: string, + ) -> expected + + /// Unlink a filesystem object that is not a directory. + /// + /// Return `errno::isdir` if the path refers to a directory. + /// Note: This is similar to `unlinkat(fd, path, 0)` in POSIX. + unlink-file-at: func( + /// The relative path to a file to unlink. + path: string, + ) -> expected + + /// Change the permissions of a filesystem object that is not a directory. + /// + /// Note that the ultimate meanings of these permissions is + /// filesystem-specific. + /// + /// Note: This is similar to `fchmodat` in POSIX. + change-file-permissions-at: func( + /// Flags determining the method of how the path is resolved. + at-flags: at-flags, + /// The relative path to operate on. + path: string, + /// The new permissions for the filesystem object. + mode: mode, + ) -> expected + + /// Change the permissions of a directory. + /// + /// Note that the ultimate meanings of these permissions is + /// filesystem-specific. + /// + /// Unlike in POSIX, the `executable` flag is not reinterpreted as a "search" + /// flag. `read` on a directory implies readability and searchability, and + /// `execute` is not valid for directories. + /// + /// Note: This is similar to `fchmodat` in POSIX. + change-directory-permissions-at: func( + /// Flags determining the method of how the path is resolved. + at-flags: at-flags, + /// The relative path to operate on. + path: string, + /// The new permissions for the directory. + mode: mode, + ) -> expected +} diff --git a/lib/wasi-types-generated/wit/wasi-io-typenames.wit b/lib/wasi-types-generated/wit/wasi-io-typenames.wit new file mode 100644 index 00000000000..2be2ed04538 --- /dev/null +++ b/lib/wasi-types-generated/wit/wasi-io-typenames.wit @@ -0,0 +1,195 @@ +// Extracted from https://github.com/WebAssembly/wasi-io/blob/main/standard/io/witx/typenames.witx + +/// Size of a range of bytes in memory. +type size = u32 + +/// A region of memory for scatter/gather reads. +record iovec { + /// The address of the buffer to be filled. + /// TODO: (field $buf (@witx pointer u8)) + /// wit has no "pointer" + /// pointer + buf: size, + /// The length of the buffer to be filled. + buf-len: size, +} + +/// A region of memory for scatter/gather writes. +record ciovec { + /// The address of the buffer to be written. + /// TODO: (field $buf (field $buf (@witx const_pointer u8))): wit has no "pointer" + buf: size, + /// The length of the buffer to be written. + buf-len: size, +} + +type iovec-array: list + +type ciovec-array: list + +/// Relative offset within a file. +type filedelta = s64 + +/// The position relative to which to set the offset of the file descriptor. +enum whence { + /// Seek relative to start-of-file. + set, + /// Seek relative to current position. + cur, + /// Seek relative to end-of-file. + end, +} + +/// Number of hard links to an inode. +type linkcount = s64 + +/// File permissions. This represents the permissions associated with a +/// file in a filesystem, and don't fully reflect all the conditions +/// which determine whether a given WASI program can access the file. +/// +/// TODO: (@witx repr u8) +flags permissions { + /// For files, permission to read the file. + /// For directories, permission to do `readdir` and access files + /// within the directory. + /// + /// Note: This is similar to the read bit being set on files, and the + /// read *and* execute bits being set on directories, in POSIX. + read, + /// For files, permission to mutate the file. + /// For directories, permission to create, remove, and rename items + /// within the directory. + write, + /// For files, permission to "execute" the file, using whatever + /// concept of "executing" the host filesystem has. + /// This flag is not valid for directories. + execute, + /// For filesystems which have a concept of multiple "users", this flag + /// indicates that the file is only accessible by the effective "user" + /// that the WASI store uses to access the filesystem, and inaccessible + /// to other "users". + private, +} + +/// File attributes. +record filestat { + /// Device ID of device containing the file. + $dev $device) + /// File serial number. + $ino $inode) + /// File type. + $filetype $filetype) + /// File permissions. + $permissions $permissions) + /// Number of hard links to the file. + $nlink $linkcount) + /// For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link. + $size $filesize) + /// Last data access timestamp. + $atim $timestamp) + /// Last data modification timestamp. + $mtim $timestamp) + /// Last file status change timestamp. + $ctim $timestamp) +} + +// +// ;;; +// (typename $filestat +// (record + +// ) +// ) +// + + + +// ;;; The contents of a `subscription` when type is type is +// ;;; `eventtype::fd_read` or `eventtype::fd_write`. +// (typename $subscription_fd_readwrite +// (record +// ;;; The file descriptor on which to wait for it to become ready for reading or writing. +// (field $fd $fd) +// ) +// ) +// +// ;;; The contents of a `subscription`. +// (typename $subscription_u +// (union (@witx tag $eventtype) +// $subscription_clock +// $subscription_fd_readwrite +// $subscription_fd_readwrite +// ) +// ) +// +// ;;; Subscription to an event. +// (typename $subscription +// (record +// ;;; User-provided value that is attached to the subscription in the +// ;;; implementation and returned through `event::userdata`. +// (field $userdata $userdata) +// ;;; The type of the event to which to subscribe, and the contents of the subscription. +// (field $u $subscription_u) +// ) +// ) +// +// ;;; Exit code generated by a program when exiting. +// (typename $exitcode u8) +// +// ;;; Indicate the program exited successfully. +// ;;; +// ;;; Note: This is similar to `EXIT_SUCCESS` in POSIX. +// (@witx const $exitcode $success 0) +// +// ;;; Indicate the program exited unsuccessfully. +// ;;; +// ;;; Note: This is similar to `EXIT_FAILURE` in POSIX. +// (@witx const $exitcode $failure 1) +// +// ;;; Flags provided to `sock_recv`. +// (typename $riflags +// (flags (@witx repr u16) +// ;;; Returns the message without removing it from the socket's receive queue. +// $recv_peek +// ;;; On byte-stream sockets, block until the full amount of data can be returned. +// $recv_waitall +// ) +// ) +// +// ;;; Flags returned by `sock_recv`. +// (typename $roflags +// (flags (@witx repr u16) +// ;;; Returned by `sock_recv`: Message data has been truncated. +// $recv_data_truncated +// ) +// ) +// +// ;;; Flags provided to `sock_send`. As there are currently no flags +// ;;; defined, it must be set to zero. +// (typename $siflags u16) +// +// ;;; Which channels on a socket to shut down. +// (typename $sdflags +// (flags (@witx repr u8) +// ;;; Disables further receive operations. +// $rd +// ;;; Disables further send operations. +// $wr +// ) +// ) + +// ;;; The contents of a `prestat` when its type is `preopentype::dir`. +// (typename $prestat_dir +// (record +// ;;; The length of the directory name for use with `fd_prestat_dir_name`. +// (field $pr_name_len $size) +// ) +// ) +// +// ;;; Information about a pre-opened capability. +// (typename $prestat +// (union (@witx tag $preopentype) +// ;;; When type is `preopentype::dir`: +// $prestat_dir +// ) +// ) diff --git a/lib/wasi-types-generated/wit/wasi-snapshot0.wit b/lib/wasi-types-generated/wit/wasi-snapshot0.wit new file mode 100644 index 00000000000..ddd81089eea --- /dev/null +++ b/lib/wasi-types-generated/wit/wasi-snapshot0.wit @@ -0,0 +1,249 @@ +// Extracted from https://github.com/WebAssembly/WASI/blob/main/phases/old/snapshot_0/witx/typenames.witx + + + + + + + +// ;;; A region of memory for scatter/gather reads. +// (typename $iovec +// (record +// ;;; The address of the buffer to be filled. +// (field $buf (@witx pointer u8)) +// ;;; The length of the buffer to be filled. +// (field $buf_len $size) +// ) +// ) +// +// ;;; A region of memory for scatter/gather writes. +// (typename $ciovec +// (record +// ;;; The address of the buffer to be written. +// (field $buf (@witx const_pointer u8)) +// ;;; The length of the buffer to be written. +// (field $buf_len $size) +// ) +// ) +// +// (typename $iovec_array (list $iovec)) +// (typename $ciovec_array (list $ciovec)) +// +// ;;; Relative offset within a file. +// (typename $filedelta s64) +// +// ;;; The position relative to which to set the offset of the file descriptor. +// (typename $whence +// (enum (@witx tag u8) +// ;;; Seek relative to current position. +// $cur +// ;;; Seek relative to end-of-file. +// $end +// ;;; Seek relative to start-of-file. +// $set +// ) +// ) + +// ;;; Number of hard links to an inode. +// (typename $linkcount u32) +// +// ;;; File attributes. +// (typename $filestat +// (record +// ;;; Device ID of device containing the file. +// (field $dev $device) +// ;;; File serial number. +// (field $ino $inode) +// ;;; File type. +// (field $filetype $filetype) +// ;;; Number of hard links to the file. +// (field $nlink $linkcount) +// ;;; For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link. +// (field $size $filesize) +// ;;; Last data access timestamp. +// (field $atim $timestamp) +// ;;; Last data modification timestamp. +// (field $mtim $timestamp) +// ;;; Last file status change timestamp. +// (field $ctim $timestamp) +// ) +// ) + + +// ;;; The contents of a `subscription` when the variant is +// ;;; `eventtype::fd_read` or `eventtype::fd_write`. +// (typename $subscription_fd_readwrite +// (record +// ;;; The file descriptor on which to wait for it to become ready for reading or writing. +// (field $file_descriptor $fd) +// ) +// ) +// +// ;;; The contents of a `subscription`. +// (typename $subscription_u +// (union (@witx tag $eventtype) +// $subscription_clock +// $subscription_fd_readwrite +// $subscription_fd_readwrite +// ) +// ) +// +// ;;; Subscription to an event. +// (typename $subscription +// (record +// ;;; User-provided value that is attached to the subscription in the +// ;;; implementation and returned through `event::userdata`. +// (field $userdata $userdata) +// ;;; The type of the event to which to subscribe. +// (field $u $subscription_u) +// ) +// ) +// +// ;;; Exit code generated by a process when exiting. +// (typename $exitcode u32) +// +// ;;; Signal condition. +// (typename $signal +// (enum (@witx tag u8) +// ;;; No signal. Note that POSIX has special semantics for `kill(pid, 0)`, +// ;;; so this value is reserved. +// $none +// ;;; Hangup. +// ;;; Action: Terminates the process. +// $hup +// ;;; Terminate interrupt signal. +// ;;; Action: Terminates the process. +// $int +// ;;; Terminal quit signal. +// ;;; Action: Terminates the process. +// $quit +// ;;; Illegal instruction. +// ;;; Action: Terminates the process. +// $ill +// ;;; Trace/breakpoint trap. +// ;;; Action: Terminates the process. +// $trap +// ;;; Process abort signal. +// ;;; Action: Terminates the process. +// $abrt +// ;;; Access to an undefined portion of a memory object. +// ;;; Action: Terminates the process. +// $bus +// ;;; Erroneous arithmetic operation. +// ;;; Action: Terminates the process. +// $fpe +// ;;; Kill. +// ;;; Action: Terminates the process. +// $kill +// ;;; User-defined signal 1. +// ;;; Action: Terminates the process. +// $usr1 +// ;;; Invalid memory reference. +// ;;; Action: Terminates the process. +// $segv +// ;;; User-defined signal 2. +// ;;; Action: Terminates the process. +// $usr2 +// ;;; Write on a pipe with no one to read it. +// ;;; Action: Ignored. +// $pipe +// ;;; Alarm clock. +// ;;; Action: Terminates the process. +// $alrm +// ;;; Termination signal. +// ;;; Action: Terminates the process. +// $term +// ;;; Child process terminated, stopped, or continued. +// ;;; Action: Ignored. +// $chld +// ;;; Continue executing, if stopped. +// ;;; Action: Continues executing, if stopped. +// $cont +// ;;; Stop executing. +// ;;; Action: Stops executing. +// $stop +// ;;; Terminal stop signal. +// ;;; Action: Stops executing. +// $tstp +// ;;; Background process attempting read. +// ;;; Action: Stops executing. +// $ttin +// ;;; Background process attempting write. +// ;;; Action: Stops executing. +// $ttou +// ;;; High bandwidth data is available at a socket. +// ;;; Action: Ignored. +// $urg +// ;;; CPU time limit exceeded. +// ;;; Action: Terminates the process. +// $xcpu +// ;;; File size limit exceeded. +// ;;; Action: Terminates the process. +// $xfsz +// ;;; Virtual timer expired. +// ;;; Action: Terminates the process. +// $vtalrm +// ;;; Profiling timer expired. +// ;;; Action: Terminates the process. +// $prof +// ;;; Window changed. +// ;;; Action: Ignored. +// $winch +// ;;; I/O possible. +// ;;; Action: Terminates the process. +// $poll +// ;;; Power failure. +// ;;; Action: Terminates the process. +// $pwr +// ;;; Bad system call. +// ;;; Action: Terminates the process. +// $sys +// ) +// ) +// +// ;;; Flags provided to `sock_recv`. +// (typename $riflags +// (flags (@witx repr u16) +// ;;; Returns the message without removing it from the socket's receive queue. +// $recv_peek +// ;;; On byte-stream sockets, block until the full amount of data can be returned. +// $recv_waitall +// ) +// ) +// +// ;;; Flags returned by `sock_recv`. +// (typename $roflags +// (flags (@witx repr u16) +// ;;; Returned by `sock_recv`: Message data has been truncated. +// $recv_data_truncated +// ) +// ) +// +// ;;; Flags provided to `sock_send`. As there are currently no flags +// ;;; defined, it must be set to zero. +// (typename $siflags u16) +// +// ;;; Which channels on a socket to shut down. +// (typename $sdflags +// (flags (@witx repr u8) +// ;;; Disables further receive operations. +// $rd +// ;;; Disables further send operations. +// $wr +// ) +// ) + +// ;;; The contents of a $prestat when type is `preopentype::dir`. +// (typename $prestat_dir +// (record +// ;;; The length of the directory name for use with `fd_prestat_dir_name`. +// (field $pr_name_len $size) +// ) +// ) +// +// ;;; Information about a pre-opened capability. +// (typename $prestat +// (union (@witx tag $preopentype) +// $prestat_dir +// ) +// ) diff --git a/lib/wasi-types/Cargo.toml b/lib/wasi-types/Cargo.toml index d89a5410ab2..bfcef194396 100644 --- a/lib/wasi-types/Cargo.toml +++ b/lib/wasi-types/Cargo.toml @@ -13,6 +13,7 @@ edition = "2018" [dependencies] wasmer-types = { path = "../types", version = "=3.0.0-beta" } wasmer-derive = { path = "../derive", version = "=3.0.0-beta" } +wasmer-wasi-types-generated = { path = "../wasi-types-generated", version = "=3.0.0-beta" } serde = { version = "1.0", features = ["derive"], optional = true } byteorder = "1.3" time = "0.2" diff --git a/lib/wasi-types/src/advice.rs b/lib/wasi-types/src/advice.rs deleted file mode 100644 index 55cf4aebcd2..00000000000 --- a/lib/wasi-types/src/advice.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub type __wasi_advice_t = u8; -pub const __WASI_ADVICE_NORMAL: u8 = 0; -pub const __WASI_ADVICE_SEQUENTIAL: u8 = 1; -pub const __WASI_ADVICE_RANDOM: u8 = 2; -pub const __WASI_ADVICE_WILLNEED: u8 = 3; -pub const __WASI_ADVICE_DONTNEED: u8 = 4; -pub const __WASI_ADVICE_NOREUSE: u8 = 5; diff --git a/lib/wasi-types/src/bus.rs b/lib/wasi-types/src/bus.rs index ff8bea2ecb3..737db4b0194 100644 --- a/lib/wasi-types/src/bus.rs +++ b/lib/wasi-types/src/bus.rs @@ -1,6 +1,7 @@ use super::*; use wasmer_derive::ValueType; use wasmer_types::MemorySize; +use wasmer_wasi_types_generated::wasi::{BusErrno, Fd}; pub type __wasi_busdataformat_t = u8; pub const __WASI_BUS_DATA_FORMAT_RAW: __wasi_busdataformat_t = 0; @@ -34,7 +35,7 @@ pub type __wasi_cid_t = u8; #[repr(C)] pub struct __wasi_option_fd_t { pub tag: __wasi_option_t, - pub fd: __wasi_fd_t, + pub fd: Fd, } #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] @@ -85,7 +86,7 @@ pub struct __wasi_busevent_result_t { #[repr(C)] pub struct __wasi_busevent_fault_t { pub cid: __wasi_cid_t, - pub err: __bus_errno_t, + pub err: BusErrno, } #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] diff --git a/lib/wasi-types/src/directory.rs b/lib/wasi-types/src/directory.rs index d43b709f61f..d7bdbfe231f 100644 --- a/lib/wasi-types/src/directory.rs +++ b/lib/wasi-types/src/directory.rs @@ -1,58 +1,68 @@ -use crate::*; use std::mem; -use wasmer_derive::ValueType; +use wasmer_wasi_types_generated::wasi; -pub type __wasi_dircookie_t = u64; -pub const __WASI_DIRCOOKIE_START: u64 = 0; +pub const __WASI_DIRCOOKIE_START: wasi::Dircookie = 0; -#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] -#[repr(C)] -pub struct __wasi_dirent_t { - pub d_next: __wasi_dircookie_t, - pub d_ino: __wasi_inode_t, - pub d_namlen: u32, - pub d_type: __wasi_filetype_t, -} - -pub fn dirent_to_le_bytes(ent: &__wasi_dirent_t) -> Vec { +pub fn dirent_to_le_bytes(ent: &wasi::Dirent) -> Vec { let out: Vec = std::iter::empty() .chain(ent.d_next.to_le_bytes()) .chain(ent.d_ino.to_le_bytes()) .chain(ent.d_namlen.to_le_bytes()) - .chain(u32::from(ent.d_type).to_le_bytes()) + .chain(u32::from(ent.d_type as u8).to_le_bytes()) .collect(); - assert_eq!(out.len(), mem::size_of::<__wasi_dirent_t>()); + assert_eq!(out.len(), mem::size_of::()); out } #[cfg(test)] mod tests { - use super::{__wasi_dirent_t, dirent_to_le_bytes}; + use super::dirent_to_le_bytes; + use wasmer_wasi_types_generated::wasi; #[test] fn test_dirent_to_le_bytes() { - let s = __wasi_dirent_t { + let s = wasi::Dirent { d_next: 0x0123456789abcdef, d_ino: 0xfedcba9876543210, d_namlen: 0xaabbccdd, - d_type: 0x99, + d_type: wasi::Filetype::Directory, }; assert_eq!( vec![ // d_next - 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01, + 0xef, + 0xcd, + 0xab, + 0x89, + 0x67, + 0x45, + 0x23, + 0x01, // // d_ino - 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe, + 0x10, + 0x32, + 0x54, + 0x76, + 0x98, + 0xba, + 0xdc, + 0xfe, // // d_namelen - 0xdd, 0xcc, 0xbb, 0xaa, + 0xdd, + 0xcc, + 0xbb, + 0xaa, // // d_type // plus padding - 0x99, 0x00, 0x00, 0x00, + wasi::Filetype::Directory as u8, + 0x00, + 0x00, + 0x00, ], dirent_to_le_bytes(&s) ); diff --git a/lib/wasi-types/src/error.rs b/lib/wasi-types/src/error.rs deleted file mode 100644 index fa1bf528126..00000000000 --- a/lib/wasi-types/src/error.rs +++ /dev/null @@ -1,100 +0,0 @@ -pub type __wasi_errno_t = u16; -pub const __WASI_ESUCCESS: u16 = 0; -pub const __WASI_E2BIG: u16 = 1; -pub const __WASI_EACCES: u16 = 2; -pub const __WASI_EADDRINUSE: u16 = 3; -pub const __WASI_EADDRNOTAVAIL: u16 = 4; -pub const __WASI_EAFNOSUPPORT: u16 = 5; -pub const __WASI_EAGAIN: u16 = 6; -pub const __WASI_EALREADY: u16 = 7; -pub const __WASI_EBADF: u16 = 8; -pub const __WASI_EBADMSG: u16 = 9; -pub const __WASI_EBUSY: u16 = 10; -pub const __WASI_ECANCELED: u16 = 11; -pub const __WASI_ECHILD: u16 = 12; -pub const __WASI_ECONNABORTED: u16 = 13; -pub const __WASI_ECONNREFUSED: u16 = 14; -pub const __WASI_ECONNRESET: u16 = 15; -pub const __WASI_EDEADLK: u16 = 16; -pub const __WASI_EDESTADDRREQ: u16 = 17; -pub const __WASI_EDOM: u16 = 18; -pub const __WASI_EDQUOT: u16 = 19; -pub const __WASI_EEXIST: u16 = 20; -pub const __WASI_EFAULT: u16 = 21; -pub const __WASI_EFBIG: u16 = 22; -pub const __WASI_EHOSTUNREACH: u16 = 23; -pub const __WASI_EIDRM: u16 = 24; -pub const __WASI_EILSEQ: u16 = 25; -pub const __WASI_EINPROGRESS: u16 = 26; -pub const __WASI_EINTR: u16 = 27; -pub const __WASI_EINVAL: u16 = 28; -pub const __WASI_EIO: u16 = 29; -pub const __WASI_EISCONN: u16 = 30; -pub const __WASI_EISDIR: u16 = 31; -pub const __WASI_ELOOP: u16 = 32; -pub const __WASI_EMFILE: u16 = 33; -pub const __WASI_EMLINK: u16 = 34; -pub const __WASI_EMSGSIZE: u16 = 35; -pub const __WASI_EMULTIHOP: u16 = 36; -pub const __WASI_ENAMETOOLONG: u16 = 37; -pub const __WASI_ENETDOWN: u16 = 38; -pub const __WASI_ENETRESET: u16 = 39; -pub const __WASI_ENETUNREACH: u16 = 40; -pub const __WASI_ENFILE: u16 = 41; -pub const __WASI_ENOBUFS: u16 = 42; -pub const __WASI_ENODEV: u16 = 43; -pub const __WASI_ENOENT: u16 = 44; -pub const __WASI_ENOEXEC: u16 = 45; -pub const __WASI_ENOLCK: u16 = 46; -pub const __WASI_ENOLINK: u16 = 47; -pub const __WASI_ENOMEM: u16 = 48; -pub const __WASI_ENOMSG: u16 = 49; -pub const __WASI_ENOPROTOOPT: u16 = 50; -pub const __WASI_ENOSPC: u16 = 51; -pub const __WASI_ENOSYS: u16 = 52; -pub const __WASI_ENOTCONN: u16 = 53; -pub const __WASI_ENOTDIR: u16 = 54; -pub const __WASI_ENOTEMPTY: u16 = 55; -pub const __WASI_ENOTRECOVERABLE: u16 = 56; -pub const __WASI_ENOTSOCK: u16 = 57; -pub const __WASI_ENOTSUP: u16 = 58; -pub const __WASI_ENOTTY: u16 = 59; -pub const __WASI_ENXIO: u16 = 60; -pub const __WASI_EOVERFLOW: u16 = 61; -pub const __WASI_EOWNERDEAD: u16 = 62; -pub const __WASI_EPERM: u16 = 63; -pub const __WASI_EPIPE: u16 = 64; -pub const __WASI_EPROTO: u16 = 65; -pub const __WASI_EPROTONOSUPPORT: u16 = 66; -pub const __WASI_EPROTOTYPE: u16 = 67; -pub const __WASI_ERANGE: u16 = 68; -pub const __WASI_EROFS: u16 = 69; -pub const __WASI_ESPIPE: u16 = 70; -pub const __WASI_ESRCH: u16 = 71; -pub const __WASI_ESTALE: u16 = 72; -pub const __WASI_ETIMEDOUT: u16 = 73; -pub const __WASI_ETXTBSY: u16 = 74; -pub const __WASI_EXDEV: u16 = 75; -pub const __WASI_ENOTCAPABLE: u16 = 76; - -pub type __bus_errno_t = u32; -pub const __BUS_ESUCCESS: u32 = 0; -pub const __BUS_ESER: u32 = 1; -pub const __BUS_EDES: u32 = 2; -pub const __BUS_EWAPM: u32 = 3; -pub const __BUS_EFETCH: u32 = 4; -pub const __BUS_ECOMPILE: u32 = 5; -pub const __BUS_EABI: u32 = 6; -pub const __BUS_EABORTED: u32 = 7; -pub const __BUS_EBADHANDLE: u32 = 8; -pub const __BUS_ETOPIC: u32 = 9; -pub const __BUS_EBADCB: u32 = 10; -pub const __BUS_EUNSUPPORTED: u32 = 11; -pub const __BUS_EBADREQUEST: u32 = 12; -pub const __BUS_EDENIED: u32 = 13; -pub const __BUS_EINTERNAL: u32 = 14; -pub const __BUS_EALLOC: u32 = 15; -pub const __BUS_EINVOKE: u32 = 16; -pub const __BUS_ECONSUMED: u32 = 17; -pub const __BUS_EMEMVIOLATION: u32 = 18; -pub const __BUS_EUNKNOWN: u32 = 19; diff --git a/lib/wasi-types/src/event.rs b/lib/wasi-types/src/event.rs deleted file mode 100644 index c368f5b9b5a..00000000000 --- a/lib/wasi-types/src/event.rs +++ /dev/null @@ -1,126 +0,0 @@ -use crate::*; -use std::{ - fmt, - mem::{self, MaybeUninit}, -}; -use wasmer_derive::ValueType; -use wasmer_types::ValueType; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] -#[repr(C)] -pub struct __wasi_event_fd_readwrite_t { - pub nbytes: __wasi_filesize_t, - pub flags: __wasi_eventrwflags_t, -} - -#[derive(Copy, Clone)] -#[repr(C)] -pub union __wasi_event_u { - pub fd_readwrite: __wasi_event_fd_readwrite_t, -} - -// TODO: remove this implementation of Debug when `__wasi_event_u` gets more than 1 variant -impl fmt::Debug for __wasi_event_u { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("__wasi_event_u") - .field("fd_readwrite", unsafe { &self.fd_readwrite }) - .finish() - } -} - -#[derive(Debug, Copy, Clone)] -pub enum EventEnum { - FdReadWrite { - nbytes: __wasi_filesize_t, - flags: __wasi_eventrwflags_t, - }, -} - -impl EventEnum { - pub fn untagged(self) -> __wasi_event_u { - match self { - EventEnum::FdReadWrite { nbytes, flags } => __wasi_event_u { - fd_readwrite: __wasi_event_fd_readwrite_t { nbytes, flags }, - }, - } - } -} - -#[derive(Debug, Copy, Clone)] -#[repr(C)] -pub struct __wasi_event_t { - pub userdata: __wasi_userdata_t, - pub error: __wasi_errno_t, - pub type_: __wasi_eventtype_t, - pub u: __wasi_event_u, -} - -impl __wasi_event_t { - pub fn tagged(&self) -> Option { - match self.type_ { - __WASI_EVENTTYPE_FD_READ | __WASI_EVENTTYPE_FD_WRITE => Some(EventEnum::FdReadWrite { - nbytes: unsafe { self.u.fd_readwrite.nbytes }, - flags: unsafe { self.u.fd_readwrite.flags }, - }), - _ => None, - } - } -} - -unsafe impl ValueType for __wasi_event_t { - fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { - macro_rules! field { - ($($f:tt)*) => { - &self.$($f)* as *const _ as usize - self as *const _ as usize - }; - } - macro_rules! field_end { - ($($f:tt)*) => { - field!($($f)*) + mem::size_of_val(&self.$($f)*) - }; - } - macro_rules! zero { - ($start:expr, $end:expr) => { - for i in $start..$end { - bytes[i] = MaybeUninit::new(0); - } - }; - } - self.userdata - .zero_padding_bytes(&mut bytes[field!(userdata)..field_end!(userdata)]); - zero!(field_end!(userdata), field!(error)); - self.error - .zero_padding_bytes(&mut bytes[field!(error)..field_end!(error)]); - zero!(field_end!(error), field!(type_)); - self.type_ - .zero_padding_bytes(&mut bytes[field!(type_)..field_end!(type_)]); - zero!(field_end!(type_), field!(u)); - match self.type_ { - __WASI_EVENTTYPE_FD_READ | __WASI_EVENTTYPE_FD_WRITE => unsafe { - self.u.fd_readwrite.zero_padding_bytes( - &mut bytes[field!(u.fd_readwrite)..field_end!(u.fd_readwrite)], - ); - zero!(field_end!(u.fd_readwrite), field_end!(u)); - }, - _ => zero!(field!(u), field_end!(u)), - } - zero!(field_end!(u), mem::size_of_val(self)); - } -} - -pub type __wasi_eventrwflags_t = u16; -pub const __WASI_EVENT_FD_READWRITE_HANGUP: u16 = 1 << 0; - -pub type __wasi_eventtype_t = u8; -pub const __WASI_EVENTTYPE_CLOCK: u8 = 0; -pub const __WASI_EVENTTYPE_FD_READ: u8 = 1; -pub const __WASI_EVENTTYPE_FD_WRITE: u8 = 2; - -pub fn eventtype_to_str(event_type: __wasi_eventtype_t) -> &'static str { - match event_type { - __WASI_EVENTTYPE_CLOCK => "__WASI_EVENTTYPE_CLOCK", - __WASI_EVENTTYPE_FD_READ => "__WASI_EVENTTYPE_FD_READ", - __WASI_EVENTTYPE_FD_WRITE => "__WASI_EVENTTYPE_FD_WRITE", - _ => "INVALID EVENTTYPE", - } -} diff --git a/lib/wasi-types/src/file.rs b/lib/wasi-types/src/file.rs index 0d58ba9bbe4..f2d75d68062 100644 --- a/lib/wasi-types/src/file.rs +++ b/lib/wasi-types/src/file.rs @@ -1,36 +1,18 @@ -use crate::*; -#[cfg(feature = "enable-serde")] -use serde::{Deserialize, Serialize}; use std::{ fmt, mem::{self, MaybeUninit}, }; use wasmer_derive::ValueType; use wasmer_types::ValueType; +use wasmer_wasi_types_generated::wasi::{Fd, Preopentype, Rights}; -pub type __wasi_device_t = u64; - -pub type __wasi_fd_t = u32; -pub const __WASI_STDIN_FILENO: __wasi_fd_t = 0; -pub const __WASI_STDOUT_FILENO: __wasi_fd_t = 1; -pub const __WASI_STDERR_FILENO: __wasi_fd_t = 2; - -pub type __wasi_pid_t = u32; -pub type __wasi_tid_t = u32; - -pub type __wasi_fdflags_t = u16; -pub const __WASI_FDFLAG_APPEND: __wasi_fdflags_t = 1 << 0; -pub const __WASI_FDFLAG_DSYNC: __wasi_fdflags_t = 1 << 1; -pub const __WASI_FDFLAG_NONBLOCK: __wasi_fdflags_t = 1 << 2; -pub const __WASI_FDFLAG_RSYNC: __wasi_fdflags_t = 1 << 3; -pub const __WASI_FDFLAG_SYNC: __wasi_fdflags_t = 1 << 4; +pub const __WASI_STDIN_FILENO: Fd = 0; +pub const __WASI_STDOUT_FILENO: Fd = 1; +pub const __WASI_STDERR_FILENO: Fd = 2; pub type __wasi_eventfdflags = u16; pub const __WASI_EVENTFDFLAGS_SEMAPHORE: __wasi_eventfdflags = 1 << 0; -pub type __wasi_preopentype_t = u8; -pub const __WASI_PREOPENTYPE_DIR: __wasi_preopentype_t = 0; - #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] #[repr(C)] pub struct __wasi_prestat_u_dir_t { @@ -52,7 +34,7 @@ impl fmt::Debug for __wasi_prestat_u { #[derive(Debug, Copy, Clone)] #[repr(C)] pub struct __wasi_prestat_t { - pub pr_type: __wasi_preopentype_t, + pub pr_type: Preopentype, pub u: __wasi_prestat_u, } @@ -75,10 +57,9 @@ impl __wasi_prestat_t { #[allow(clippy::trivially_copy_pass_by_ref)] pub fn tagged(&self) -> Option { match self.pr_type { - __WASI_PREOPENTYPE_DIR => Some(PrestatEnum::Dir { + Preopentype::Dir => Some(PrestatEnum::Dir { pr_name_len: unsafe { self.u.dir.pr_name_len }, }), - _ => None, } } } @@ -106,131 +87,19 @@ unsafe impl ValueType for __wasi_prestat_t { .zero_padding_bytes(&mut bytes[field!(pr_type)..field_end!(pr_type)]); zero!(field_end!(pr_type), field!(u)); match self.pr_type { - __WASI_PREOPENTYPE_DIR => unsafe { + Preopentype::Dir => unsafe { self.u .dir .zero_padding_bytes(&mut bytes[field!(u.dir)..field_end!(u.dir)]); zero!(field_end!(u.dir), field_end!(u)); }, - _ => zero!(field!(u), field_end!(u)), } zero!(field_end!(u), mem::size_of_val(self)); } } -#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] -#[repr(C)] -pub struct __wasi_fdstat_t { - pub fs_filetype: __wasi_filetype_t, - pub fs_flags: __wasi_fdflags_t, - pub fs_rights_base: __wasi_rights_t, - pub fs_rights_inheriting: __wasi_rights_t, -} - pub type __wasi_filedelta_t = i64; -pub type __wasi_filesize_t = u64; - -#[derive(Copy, Clone, PartialEq, Eq, ValueType)] -#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] -#[repr(C)] -pub struct __wasi_filestat_t { - pub st_dev: __wasi_device_t, - pub st_ino: __wasi_inode_t, - pub st_filetype: __wasi_filetype_t, - pub st_nlink: __wasi_linkcount_t, - pub st_size: __wasi_filesize_t, - pub st_atim: __wasi_timestamp_t, - pub st_mtim: __wasi_timestamp_t, - pub st_ctim: __wasi_timestamp_t, -} - -impl Default for __wasi_filestat_t { - fn default() -> Self { - __wasi_filestat_t { - st_dev: Default::default(), - st_ino: Default::default(), - st_filetype: __WASI_FILETYPE_UNKNOWN, - st_nlink: 1, - st_size: Default::default(), - st_atim: Default::default(), - st_mtim: Default::default(), - st_ctim: Default::default(), - } - } -} - -impl fmt::Debug for __wasi_filestat_t { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let convert_ts_into_time_string = |ts| { - let tspec = ::time::OffsetDateTime::from_unix_timestamp_nanos(ts); - format!("{} ({})", tspec.format("%a, %d %b %Y %T %z"), ts) - }; - f.debug_struct("__wasi_filestat_t") - .field("st_dev", &self.st_dev) - .field("st_ino", &self.st_ino) - .field( - "st_filetype", - &format!( - "{} ({})", - wasi_filetype_to_name(self.st_filetype), - self.st_filetype, - ), - ) - .field("st_nlink", &self.st_nlink) - .field("st_size", &self.st_size) - .field( - "st_atim", - &convert_ts_into_time_string(self.st_atim as i128), - ) - .field( - "st_mtim", - &convert_ts_into_time_string(self.st_mtim as i128), - ) - .field( - "st_ctim", - &convert_ts_into_time_string(self.st_ctim as i128), - ) - .finish() - } -} - -pub fn wasi_filetype_to_name(ft: __wasi_filetype_t) -> &'static str { - match ft { - __WASI_FILETYPE_UNKNOWN => "Unknown", - __WASI_FILETYPE_BLOCK_DEVICE => "Block device", - __WASI_FILETYPE_CHARACTER_DEVICE => "Character device", - __WASI_FILETYPE_DIRECTORY => "Directory", - __WASI_FILETYPE_REGULAR_FILE => "Regular file", - __WASI_FILETYPE_SOCKET_DGRAM => "Socket dgram", - __WASI_FILETYPE_SOCKET_STREAM => "Socket stream", - __WASI_FILETYPE_SYMBOLIC_LINK => "Symbolic link", - _ => "Invalid", - } -} - -pub type __wasi_filetype_t = u8; -pub const __WASI_FILETYPE_UNKNOWN: __wasi_filetype_t = 0; -pub const __WASI_FILETYPE_BLOCK_DEVICE: __wasi_filetype_t = 1; -pub const __WASI_FILETYPE_CHARACTER_DEVICE: __wasi_filetype_t = 2; -pub const __WASI_FILETYPE_DIRECTORY: __wasi_filetype_t = 3; -pub const __WASI_FILETYPE_REGULAR_FILE: __wasi_filetype_t = 4; -pub const __WASI_FILETYPE_SOCKET_DGRAM: __wasi_filetype_t = 5; -pub const __WASI_FILETYPE_SOCKET_STREAM: __wasi_filetype_t = 6; -pub const __WASI_FILETYPE_SYMBOLIC_LINK: __wasi_filetype_t = 7; -pub const __WASI_FILETYPE_SOCKET_RAW: __wasi_filetype_t = 8; -pub const __WASI_FILETYPE_SOCKET_SEQPACKET: __wasi_filetype_t = 9; - -pub type __wasi_fstflags_t = u16; -pub const __WASI_FILESTAT_SET_ATIM: __wasi_fstflags_t = 1 << 0; -pub const __WASI_FILESTAT_SET_ATIM_NOW: __wasi_fstflags_t = 1 << 1; -pub const __WASI_FILESTAT_SET_MTIM: __wasi_fstflags_t = 1 << 2; -pub const __WASI_FILESTAT_SET_MTIM_NOW: __wasi_fstflags_t = 1 << 3; - -pub type __wasi_inode_t = u64; - -pub type __wasi_linkcount_t = u64; - pub type __wasi_lookupflags_t = u32; pub const __WASI_LOOKUP_SYMLINK_FOLLOW: __wasi_lookupflags_t = 1 << 0; @@ -240,98 +109,16 @@ pub const __WASI_O_DIRECTORY: __wasi_oflags_t = 1 << 1; pub const __WASI_O_EXCL: __wasi_oflags_t = 1 << 2; pub const __WASI_O_TRUNC: __wasi_oflags_t = 1 << 3; -pub type __wasi_rights_t = u64; -pub const __WASI_RIGHT_FD_DATASYNC: __wasi_rights_t = 1 << 0; -pub const __WASI_RIGHT_FD_READ: __wasi_rights_t = 1 << 1; -pub const __WASI_RIGHT_FD_SEEK: __wasi_rights_t = 1 << 2; -pub const __WASI_RIGHT_FD_FDSTAT_SET_FLAGS: __wasi_rights_t = 1 << 3; -pub const __WASI_RIGHT_FD_SYNC: __wasi_rights_t = 1 << 4; -pub const __WASI_RIGHT_FD_TELL: __wasi_rights_t = 1 << 5; -pub const __WASI_RIGHT_FD_WRITE: __wasi_rights_t = 1 << 6; -pub const __WASI_RIGHT_FD_ADVISE: __wasi_rights_t = 1 << 7; -pub const __WASI_RIGHT_FD_ALLOCATE: __wasi_rights_t = 1 << 8; -pub const __WASI_RIGHT_PATH_CREATE_DIRECTORY: __wasi_rights_t = 1 << 9; -pub const __WASI_RIGHT_PATH_CREATE_FILE: __wasi_rights_t = 1 << 10; -pub const __WASI_RIGHT_PATH_LINK_SOURCE: __wasi_rights_t = 1 << 11; -pub const __WASI_RIGHT_PATH_LINK_TARGET: __wasi_rights_t = 1 << 12; -pub const __WASI_RIGHT_PATH_OPEN: __wasi_rights_t = 1 << 13; -pub const __WASI_RIGHT_FD_READDIR: __wasi_rights_t = 1 << 14; -pub const __WASI_RIGHT_PATH_READLINK: __wasi_rights_t = 1 << 15; -pub const __WASI_RIGHT_PATH_RENAME_SOURCE: __wasi_rights_t = 1 << 16; -pub const __WASI_RIGHT_PATH_RENAME_TARGET: __wasi_rights_t = 1 << 17; -pub const __WASI_RIGHT_PATH_FILESTAT_GET: __wasi_rights_t = 1 << 18; -pub const __WASI_RIGHT_PATH_FILESTAT_SET_SIZE: __wasi_rights_t = 1 << 19; -pub const __WASI_RIGHT_PATH_FILESTAT_SET_TIMES: __wasi_rights_t = 1 << 20; -pub const __WASI_RIGHT_FD_FILESTAT_GET: __wasi_rights_t = 1 << 21; -pub const __WASI_RIGHT_FD_FILESTAT_SET_SIZE: __wasi_rights_t = 1 << 22; -pub const __WASI_RIGHT_FD_FILESTAT_SET_TIMES: __wasi_rights_t = 1 << 23; -pub const __WASI_RIGHT_PATH_SYMLINK: __wasi_rights_t = 1 << 24; -pub const __WASI_RIGHT_PATH_REMOVE_DIRECTORY: __wasi_rights_t = 1 << 25; -pub const __WASI_RIGHT_PATH_UNLINK_FILE: __wasi_rights_t = 1 << 26; -pub const __WASI_RIGHT_POLL_FD_READWRITE: __wasi_rights_t = 1 << 27; -pub const __WASI_RIGHT_SOCK_SHUTDOWN: __wasi_rights_t = 1 << 28; -pub const __WASI_RIGHT_SOCK_ACCEPT: __wasi_rights_t = 1 << 29; -pub const __WASI_RIGHT_SOCK_CONNECT: __wasi_rights_t = 1 << 30; -pub const __WASI_RIGHT_SOCK_LISTEN: __wasi_rights_t = 1 << 31; -pub const __WASI_RIGHT_SOCK_BIND: __wasi_rights_t = 1 << 32; -pub const __WASI_RIGHT_SOCK_RECV: __wasi_rights_t = 1 << 33; -pub const __WASI_RIGHT_SOCK_SEND: __wasi_rights_t = 1 << 34; -pub const __WASI_RIGHT_SOCK_ADDR_LOCAL: __wasi_rights_t = 1 << 35; -pub const __WASI_RIGHT_SOCK_ADDR_REMOTE: __wasi_rights_t = 1 << 36; -pub const __WASI_RIGHT_SOCK_RECV_FROM: __wasi_rights_t = 1 << 37; -pub const __WASI_RIGHT_SOCK_SEND_TO: __wasi_rights_t = 1 << 38; - /// function for debugging rights issues #[allow(dead_code)] -pub fn print_right_set(rights: __wasi_rights_t) { +pub fn print_right_set(rights: Rights) { // BTreeSet for consistent order let mut right_set = std::collections::BTreeSet::new(); for i in 0..28 { - let cur_right = rights & (1 << i); - if cur_right != 0 { - right_set.insert(right_to_string(cur_right).unwrap_or("INVALID RIGHT")); + let cur_right = rights & Rights::from_bits(1 << i).unwrap(); + if !cur_right.is_empty() { + right_set.insert(cur_right.to_str().unwrap_or("INVALID RIGHT")); } } println!("{:#?}", right_set); } - -/// expects a single right, returns None if out of bounds or > 1 bit set -pub fn right_to_string(right: __wasi_rights_t) -> Option<&'static str> { - Some(match right { - __WASI_RIGHT_FD_DATASYNC => "__WASI_RIGHT_FD_DATASYNC", - __WASI_RIGHT_FD_READ => "__WASI_RIGHT_FD_READ", - __WASI_RIGHT_FD_SEEK => "__WASI_RIGHT_FD_SEEK", - __WASI_RIGHT_FD_FDSTAT_SET_FLAGS => "__WASI_RIGHT_FD_FDSTAT_SET_FLAGS", - __WASI_RIGHT_FD_SYNC => "__WASI_RIGHT_FD_SYNC", - __WASI_RIGHT_FD_TELL => "__WASI_RIGHT_FD_TELL", - __WASI_RIGHT_FD_WRITE => "__WASI_RIGHT_FD_WRITE", - __WASI_RIGHT_FD_ADVISE => "__WASI_RIGHT_FD_ADVISE", - __WASI_RIGHT_FD_ALLOCATE => "__WASI_RIGHT_FD_ALLOCATE", - __WASI_RIGHT_PATH_CREATE_DIRECTORY => "__WASI_RIGHT_PATH_CREATE_DIRECTORY", - __WASI_RIGHT_PATH_CREATE_FILE => "__WASI_RIGHT_PATH_CREATE_FILE", - __WASI_RIGHT_PATH_LINK_SOURCE => "__WASI_RIGHT_PATH_LINK_SOURCE", - __WASI_RIGHT_PATH_LINK_TARGET => "__WASI_RIGHT_PATH_LINK_TARGET", - __WASI_RIGHT_PATH_OPEN => "__WASI_RIGHT_PATH_OPEN", - __WASI_RIGHT_FD_READDIR => "__WASI_RIGHT_FD_READDIR", - __WASI_RIGHT_PATH_READLINK => "__WASI_RIGHT_PATH_READLINK", - __WASI_RIGHT_PATH_RENAME_SOURCE => "__WASI_RIGHT_PATH_RENAME_SOURCE", - __WASI_RIGHT_PATH_RENAME_TARGET => "__WASI_RIGHT_PATH_RENAME_TARGET", - __WASI_RIGHT_PATH_FILESTAT_GET => "__WASI_RIGHT_PATH_FILESTAT_GET", - __WASI_RIGHT_PATH_FILESTAT_SET_SIZE => "__WASI_RIGHT_PATH_FILESTAT_SET_SIZE", - __WASI_RIGHT_PATH_FILESTAT_SET_TIMES => "__WASI_RIGHT_PATH_FILESTAT_SET_TIMES", - __WASI_RIGHT_FD_FILESTAT_GET => "__WASI_RIGHT_FD_FILESTAT_GET", - __WASI_RIGHT_FD_FILESTAT_SET_SIZE => "__WASI_RIGHT_FD_FILESTAT_SET_SIZE", - __WASI_RIGHT_FD_FILESTAT_SET_TIMES => "__WASI_RIGHT_FD_FILESTAT_SET_TIMES", - __WASI_RIGHT_PATH_SYMLINK => "__WASI_RIGHT_PATH_SYMLINK", - __WASI_RIGHT_PATH_UNLINK_FILE => "__WASI_RIGHT_PATH_UNLINK_FILE", - __WASI_RIGHT_PATH_REMOVE_DIRECTORY => "__WASI_RIGHT_PATH_REMOVE_DIRECTORY", - __WASI_RIGHT_POLL_FD_READWRITE => "__WASI_RIGHT_POLL_FD_READWRITE", - __WASI_RIGHT_SOCK_SHUTDOWN => "__WASI_RIGHT_SOCK_SHUTDOWN", - _ => return None, - }) -} - -pub type __wasi_whence_t = u8; -pub const __WASI_WHENCE_SET: __wasi_whence_t = 0; -pub const __WASI_WHENCE_CUR: __wasi_whence_t = 1; -pub const __WASI_WHENCE_END: __wasi_whence_t = 2; diff --git a/lib/wasi-types/src/io.rs b/lib/wasi-types/src/io.rs index f80ffcfb3eb..9f695073062 100644 --- a/lib/wasi-types/src/io.rs +++ b/lib/wasi-types/src/io.rs @@ -1,7 +1,6 @@ use wasmer_derive::ValueType; use wasmer_types::MemorySize; - -use crate::__wasi_fd_t; +use wasmer_wasi_types_generated::wasi::Fd; pub type __wasi_count_t = u32; @@ -27,25 +26,11 @@ pub struct __wasi_iovec_t { pub buf_len: M::Offset, } -#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] -#[repr(C)] -pub struct __wasi_tty_t { - pub cols: u32, - pub rows: u32, - pub width: u32, - pub height: u32, - pub stdin_tty: __wasi_bool_t, - pub stdout_tty: __wasi_bool_t, - pub stderr_tty: __wasi_bool_t, - pub echo: __wasi_bool_t, - pub line_buffered: __wasi_bool_t, -} - #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] #[repr(C)] pub struct __wasi_pipe_handles_t { - pub pipe: __wasi_fd_t, - pub other: __wasi_fd_t, + pub pipe: Fd, + pub other: Fd, } pub type __wasi_stdiomode_t = u8; diff --git a/lib/wasi-types/src/lib.rs b/lib/wasi-types/src/lib.rs index 14f9bff188b..7c85be5aae7 100644 --- a/lib/wasi-types/src/lib.rs +++ b/lib/wasi-types/src/lib.rs @@ -11,31 +11,23 @@ // Needed for #[derive(ValueType)] extern crate wasmer_types as wasmer; -mod advice; mod bus; mod directory; -mod error; -mod event; mod file; mod io; mod net; mod signal; mod subscription; mod time; -mod versions; pub use crate::time::*; -pub use advice::*; pub use bus::*; pub use directory::*; -pub use error::*; -pub use event::*; pub use file::*; pub use io::*; pub use net::*; pub use signal::*; pub use subscription::*; -pub use versions::*; pub type __wasi_exitcode_t = u32; diff --git a/lib/wasi-types/src/net.rs b/lib/wasi-types/src/net.rs index 7f0cbd79f64..79a11e7d6f0 100644 --- a/lib/wasi-types/src/net.rs +++ b/lib/wasi-types/src/net.rs @@ -1,55 +1,9 @@ use super::*; use wasmer_derive::ValueType; +use wasmer_wasi_types_generated::wasi::{Addressfamily, Fd, Filesize}; use crate::__wasi_option_timestamp_t; -pub type __wasi_socktype_t = u16; -pub const __WASI_SOCK_TYPE_DGRAM: __wasi_socktype_t = 0; -pub const __WASI_SOCK_TYPE_STREAM: __wasi_socktype_t = 1; -pub const __WASI_SOCK_TYPE_RAW: __wasi_socktype_t = 2; -pub const __WASI_SOCK_TYPE_SEQPACKET: __wasi_socktype_t = 3; - -pub type __wasi_sockstatus_t = u8; -pub const __WASI_SOCK_STATUS_OPENING: __wasi_sockstatus_t = 0; -pub const __WASI_SOCK_STATUS_OPENED: __wasi_sockstatus_t = 1; -pub const __WASI_SOCK_STATUS_CLOSED: __wasi_sockstatus_t = 2; -pub const __WASI_SOCK_STATUS_FAILED: __wasi_sockstatus_t = 3; - -pub type __wasi_sockoption_t = u8; -pub const __WASI_SOCK_OPTION_NOOP: __wasi_sockoption_t = 0; -pub const __WASI_SOCK_OPTION_REUSE_PORT: __wasi_sockoption_t = 1; -pub const __WASI_SOCK_OPTION_REUSE_ADDR: __wasi_sockoption_t = 2; -pub const __WASI_SOCK_OPTION_NO_DELAY: __wasi_sockoption_t = 3; -pub const __WASI_SOCK_OPTION_DONT_ROUTE: __wasi_sockoption_t = 4; -pub const __WASI_SOCK_OPTION_ONLY_V6: __wasi_sockoption_t = 5; -pub const __WASI_SOCK_OPTION_BROADCAST: __wasi_sockoption_t = 6; -pub const __WASI_SOCK_OPTION_MULTICAST_LOOP_V4: __wasi_sockoption_t = 7; -pub const __WASI_SOCK_OPTION_MULTICAST_LOOP_V6: __wasi_sockoption_t = 8; -pub const __WASI_SOCK_OPTION_PROMISCUOUS: __wasi_sockoption_t = 9; -pub const __WASI_SOCK_OPTION_LISTENING: __wasi_sockoption_t = 10; -pub const __WASI_SOCK_OPTION_LAST_ERROR: __wasi_sockoption_t = 11; -pub const __WASI_SOCK_OPTION_KEEP_ALIVE: __wasi_sockoption_t = 12; -pub const __WASI_SOCK_OPTION_LINGER: __wasi_sockoption_t = 13; -pub const __WASI_SOCK_OPTION_OOB_INLINE: __wasi_sockoption_t = 14; -pub const __WASI_SOCK_OPTION_RECV_BUF_SIZE: __wasi_sockoption_t = 15; -pub const __WASI_SOCK_OPTION_SEND_BUF_SIZE: __wasi_sockoption_t = 16; -pub const __WASI_SOCK_OPTION_RECV_LOWAT: __wasi_sockoption_t = 17; -pub const __WASI_SOCK_OPTION_SEND_LOWAT: __wasi_sockoption_t = 18; -pub const __WASI_SOCK_OPTION_RECV_TIMEOUT: __wasi_sockoption_t = 19; -pub const __WASI_SOCK_OPTION_SEND_TIMEOUT: __wasi_sockoption_t = 20; -pub const __WASI_SOCK_OPTION_CONNECT_TIMEOUT: __wasi_sockoption_t = 21; -pub const __WASI_SOCK_OPTION_ACCEPT_TIMEOUT: __wasi_sockoption_t = 22; -pub const __WASI_SOCK_OPTION_TTL: __wasi_sockoption_t = 23; -pub const __WASI_SOCK_OPTION_MULTICAST_TTL_V4: __wasi_sockoption_t = 24; -pub const __WASI_SOCK_OPTION_TYPE: __wasi_sockoption_t = 25; -pub const __WASI_SOCK_OPTION_PROTO: __wasi_sockoption_t = 26; - -pub type __wasi_streamsecurity_t = u8; -pub const __WASI_STREAM_SECURITY_UNENCRYPTED: __wasi_streamsecurity_t = 0; -pub const __WASI_STREAM_SECURITY_ANY_ENCRYPTION: __wasi_streamsecurity_t = 1; -pub const __WASI_STREAM_SECURITY_CLASSIC_ENCRYPTION: __wasi_streamsecurity_t = 2; -pub const __WASI_STREAM_SECURITY_DOUBLE_ENCRYPTION: __wasi_streamsecurity_t = 3; - pub type __wasi_sockproto_t = u16; pub const __WASI_SOCK_PROTO_IP: __wasi_sockproto_t = 0; pub const __WASI_SOCK_PROTO_ICMP: __wasi_sockproto_t = 1; @@ -322,12 +276,6 @@ pub struct __wasi_hardwareaddress_t { pub octs: [u8; 6], } -pub type __wasi_addressfamily_t = u16; -pub const __WASI_ADDRESS_FAMILY_UNSPEC: __wasi_addressfamily_t = 0; -pub const __WASI_ADDRESS_FAMILY_INET4: __wasi_addressfamily_t = 1; -pub const __WASI_ADDRESS_FAMILY_INET6: __wasi_addressfamily_t = 2; -pub const __WASI_ADDRESS_FAMILY_UNIX: __wasi_addressfamily_t = 3; - #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] #[repr(C)] pub struct __wasi_addr_unspec_t { @@ -417,7 +365,7 @@ pub struct __wasi_addr_u { #[derive(Debug, Copy, Clone, ValueType)] #[repr(C)] pub struct __wasi_addr_t { - pub tag: __wasi_addressfamily_t, + pub tag: Addressfamily, pub u: __wasi_addr_u, } @@ -430,7 +378,7 @@ pub struct __wasi_addr_port_u { #[derive(Debug, Copy, Clone, ValueType)] #[repr(C)] pub struct __wasi_addr_port_t { - pub tag: __wasi_addressfamily_t, + pub tag: Addressfamily, pub u: __wasi_addr_port_u, } @@ -443,7 +391,7 @@ pub struct __wasi_cidr_u { #[derive(Debug, Copy, Clone, ValueType)] #[repr(C)] pub struct __wasi_cidr_t { - pub tag: __wasi_addressfamily_t, + pub tag: Addressfamily, pub u: __wasi_cidr_u, } @@ -459,9 +407,9 @@ pub struct __wasi_route_t { #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] #[repr(C)] pub struct __wasi_http_handles_t { - pub req: __wasi_fd_t, - pub res: __wasi_fd_t, - pub hdr: __wasi_fd_t, + pub req: Fd, + pub res: Fd, + pub hdr: Fd, } #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] @@ -469,7 +417,7 @@ pub struct __wasi_http_handles_t { pub struct __wasi_http_status_t { pub ok: __wasi_bool_t, pub redirect: __wasi_bool_t, - pub size: __wasi_filesize_t, + pub size: Filesize, pub status: u16, } diff --git a/lib/wasi-types/src/subscription.rs b/lib/wasi-types/src/subscription.rs index be8d0c4768e..e47e26eb31c 100644 --- a/lib/wasi-types/src/subscription.rs +++ b/lib/wasi-types/src/subscription.rs @@ -1,100 +1,40 @@ -use crate::*; -use std::convert::TryFrom; -use std::fmt; -use std::mem::{self, MaybeUninit}; -use wasmer_derive::ValueType; -use wasmer_types::ValueType; - -pub type __wasi_subclockflags_t = u16; -pub const __WASI_SUBSCRIPTION_CLOCK_ABSTIME: u16 = 1 << 0; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] -#[repr(C)] -pub struct __wasi_subscription_clock_t { - pub clock_id: __wasi_clockid_t, - pub timeout: __wasi_timestamp_t, - pub precision: __wasi_timestamp_t, - pub flags: __wasi_subclockflags_t, -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] -#[repr(C)] -pub struct __wasi_subscription_fs_readwrite_t { - pub fd: __wasi_fd_t, -} - -#[derive(Copy, Clone)] -#[repr(C)] -pub union __wasi_subscription_u { - pub clock: __wasi_subscription_clock_t, - pub fd_readwrite: __wasi_subscription_fs_readwrite_t, -} - -#[derive(Copy, Clone)] -#[repr(C)] -pub struct __wasi_subscription_t { - pub userdata: __wasi_userdata_t, - pub type_: __wasi_eventtype_t, - pub u: __wasi_subscription_u, -} +use wasmer_wasi_types_generated::wasi::{Eventtype, SubscriptionClock, SubscriptionFsReadwrite}; /// Safe Rust wrapper around `__wasi_subscription_t::type_` and `__wasi_subscription_t::u` #[derive(Debug, Clone)] pub enum EventType { - Clock(__wasi_subscription_clock_t), - Read(__wasi_subscription_fs_readwrite_t), - Write(__wasi_subscription_fs_readwrite_t), + Clock(SubscriptionClock), + Read(SubscriptionFsReadwrite), + Write(SubscriptionFsReadwrite), } impl EventType { - pub fn raw_tag(&self) -> __wasi_eventtype_t { + pub fn raw_tag(&self) -> Eventtype { match self { - EventType::Clock(_) => __WASI_EVENTTYPE_CLOCK, - EventType::Read(_) => __WASI_EVENTTYPE_FD_READ, - EventType::Write(_) => __WASI_EVENTTYPE_FD_WRITE, + EventType::Clock(_) => Eventtype::Clock, + EventType::Read(_) => Eventtype::FdRead, + EventType::Write(_) => Eventtype::FdWrite, } } } -/// Safe Rust wrapper around `__wasi_subscription_t` -#[derive(Debug, Clone)] -pub struct WasiSubscription { - pub user_data: __wasi_userdata_t, - pub event_type: EventType, -} - -impl TryFrom<__wasi_subscription_t> for WasiSubscription { - type Error = __wasi_errno_t; - - fn try_from(ws: __wasi_subscription_t) -> Result { - Ok(Self { - user_data: ws.userdata, - event_type: match ws.type_ { - __WASI_EVENTTYPE_CLOCK => EventType::Clock(unsafe { ws.u.clock }), - __WASI_EVENTTYPE_FD_READ => EventType::Read(unsafe { ws.u.fd_readwrite }), - __WASI_EVENTTYPE_FD_WRITE => EventType::Write(unsafe { ws.u.fd_readwrite }), - _ => return Err(__WASI_EINVAL), - }, - }) - } -} - +/* TODO: re-enable and adjust if still required impl TryFrom for __wasi_subscription_t { - type Error = __wasi_errno_t; + type Error = Errno; fn try_from(ws: WasiSubscription) -> Result { #[allow(unreachable_patterns)] let (type_, u) = match ws.event_type { - EventType::Clock(c) => (__WASI_EVENTTYPE_CLOCK, __wasi_subscription_u { clock: c }), + EventType::Clock(c) => (Eventtype::Clock, __wasi_subscription_u { clock: c }), EventType::Read(rw) => ( - __WASI_EVENTTYPE_FD_READ, + Eventtype::FdRead, __wasi_subscription_u { fd_readwrite: rw }, ), EventType::Write(rw) => ( - __WASI_EVENTTYPE_FD_WRITE, + Eventtype::FdWrite, __wasi_subscription_u { fd_readwrite: rw }, ), - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }; Ok(Self { @@ -109,15 +49,12 @@ impl fmt::Debug for __wasi_subscription_t { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("__wasi_subscription_t") .field("userdata", &self.userdata) - .field("type", &eventtype_to_str(self.type_)) + .field("type", &self.type_.to_str()) .field( "u", match self.type_ { - __WASI_EVENTTYPE_CLOCK => unsafe { &self.u.clock }, - __WASI_EVENTTYPE_FD_READ | __WASI_EVENTTYPE_FD_WRITE => unsafe { - &self.u.fd_readwrite - }, - _ => &"INVALID EVENTTYPE", + Eventtype::Clock => unsafe { &self.u.clock }, + Eventtype::FdRead | Eventtype::FdWrite => unsafe { &self.u.fd_readwrite }, }, ) .finish() @@ -150,19 +87,18 @@ unsafe impl ValueType for __wasi_subscription_t { .zero_padding_bytes(&mut bytes[field!(type_)..field_end!(type_)]); zero!(field_end!(type_), field!(u)); match self.type_ { - __WASI_EVENTTYPE_FD_READ | __WASI_EVENTTYPE_FD_WRITE => unsafe { + Eventtype::FdRead | Eventtype::FdWrite => unsafe { self.u.fd_readwrite.zero_padding_bytes( &mut bytes[field!(u.fd_readwrite)..field_end!(u.fd_readwrite)], ); zero!(field_end!(u.fd_readwrite), field_end!(u)); }, - __WASI_EVENTTYPE_CLOCK => unsafe { + Eventtype::Clock => unsafe { self.u .clock .zero_padding_bytes(&mut bytes[field!(u.clock)..field_end!(u.clock)]); zero!(field_end!(u.clock), field_end!(u)); }, - _ => zero!(field!(u), field_end!(u)), } zero!(field_end!(u), mem::size_of_val(self)); } @@ -176,13 +112,12 @@ pub enum SubscriptionEnum { impl __wasi_subscription_t { pub fn tagged(&self) -> Option { match self.type_ { - __WASI_EVENTTYPE_CLOCK => Some(SubscriptionEnum::Clock(unsafe { self.u.clock })), - __WASI_EVENTTYPE_FD_READ | __WASI_EVENTTYPE_FD_WRITE => { - Some(SubscriptionEnum::FdReadWrite(unsafe { - self.u.fd_readwrite - })) - } - _ => None, + Eventtype::Clock => Some(SubscriptionEnum::Clock(unsafe { self.u.clock })), + Eventtype::FdRead | Eventtype::FdWrite => Some(SubscriptionEnum::FdReadWrite(unsafe { + self.u.fd_readwrite + })), } } } + +*/ diff --git a/lib/wasi-types/src/time.rs b/lib/wasi-types/src/time.rs index de9a2b26b92..63a19fae493 100644 --- a/lib/wasi-types/src/time.rs +++ b/lib/wasi-types/src/time.rs @@ -1,17 +1,10 @@ use super::io::__wasi_option_t; use wasmer_derive::ValueType; - -pub type __wasi_clockid_t = u32; -pub const __WASI_CLOCK_REALTIME: __wasi_clockid_t = 0; -pub const __WASI_CLOCK_MONOTONIC: __wasi_clockid_t = 1; -pub const __WASI_CLOCK_PROCESS_CPUTIME_ID: __wasi_clockid_t = 2; -pub const __WASI_CLOCK_THREAD_CPUTIME_ID: __wasi_clockid_t = 3; - -pub type __wasi_timestamp_t = u64; +use wasmer_wasi_types_generated::wasi::Timestamp; #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] #[repr(C)] pub struct __wasi_option_timestamp_t { pub tag: __wasi_option_t, - pub u: __wasi_timestamp_t, + pub u: Timestamp, } diff --git a/lib/wasi-types/src/versions/mod.rs b/lib/wasi-types/src/versions/mod.rs deleted file mode 100644 index 9ed2b1d4f5f..00000000000 --- a/lib/wasi-types/src/versions/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod snapshot0; diff --git a/lib/wasi-types/src/versions/snapshot0.rs b/lib/wasi-types/src/versions/snapshot0.rs deleted file mode 100644 index 45fec2bb339..00000000000 --- a/lib/wasi-types/src/versions/snapshot0.rs +++ /dev/null @@ -1,151 +0,0 @@ -use crate::*; -#[cfg(feature = "enable-serde")] -use serde::{Deserialize, Serialize}; -use std::fmt; -use std::mem::{self, MaybeUninit}; -use wasmer_derive::ValueType; -use wasmer_types::ValueType; - -pub type __wasi_linkcount_t = u32; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)] -#[repr(C)] -pub struct __wasi_subscription_clock_t { - pub userdata: __wasi_userdata_t, - pub clock_id: __wasi_clockid_t, - pub timeout: __wasi_timestamp_t, - pub precision: __wasi_timestamp_t, - pub flags: __wasi_subclockflags_t, -} - -#[derive(Copy, Clone)] -#[repr(C)] -pub union __wasi_subscription_u { - pub clock: __wasi_subscription_clock_t, - pub fd_readwrite: __wasi_subscription_fs_readwrite_t, -} - -#[derive(Copy, Clone)] -#[repr(C)] -pub struct __wasi_subscription_t { - pub userdata: __wasi_userdata_t, - pub type_: __wasi_eventtype_t, - pub u: __wasi_subscription_u, -} - -unsafe impl ValueType for __wasi_subscription_t { - fn zero_padding_bytes(&self, bytes: &mut [MaybeUninit]) { - macro_rules! field { - ($($f:tt)*) => { - &self.$($f)* as *const _ as usize - self as *const _ as usize - }; - } - macro_rules! field_end { - ($($f:tt)*) => { - field!($($f)*) + mem::size_of_val(&self.$($f)*) - }; - } - macro_rules! zero { - ($start:expr, $end:expr) => { - for i in $start..$end { - bytes[i] = MaybeUninit::new(0); - } - }; - } - self.userdata - .zero_padding_bytes(&mut bytes[field!(userdata)..field_end!(userdata)]); - zero!(field_end!(userdata), field!(type_)); - self.type_ - .zero_padding_bytes(&mut bytes[field!(type_)..field_end!(type_)]); - zero!(field_end!(type_), field!(u)); - match self.type_ { - __WASI_EVENTTYPE_FD_READ | __WASI_EVENTTYPE_FD_WRITE => unsafe { - self.u.fd_readwrite.zero_padding_bytes( - &mut bytes[field!(u.fd_readwrite)..field_end!(u.fd_readwrite)], - ); - zero!(field_end!(u.fd_readwrite), field_end!(u)); - }, - __WASI_EVENTTYPE_CLOCK => unsafe { - self.u - .clock - .zero_padding_bytes(&mut bytes[field!(u.clock)..field_end!(u.clock)]); - zero!(field_end!(u.clock), field_end!(u)); - }, - _ => zero!(field!(u), field_end!(u)), - } - zero!(field_end!(u), mem::size_of_val(self)); - } -} - -pub type __wasi_whence_t = u8; -pub const __WASI_WHENCE_CUR: u8 = 0; -pub const __WASI_WHENCE_END: u8 = 1; -pub const __WASI_WHENCE_SET: u8 = 2; - -#[derive(Copy, Clone, PartialEq, Eq, ValueType)] -#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] -#[repr(C)] -pub struct __wasi_filestat_t { - pub st_dev: __wasi_device_t, - pub st_ino: __wasi_inode_t, - pub st_filetype: __wasi_filetype_t, - pub st_nlink: __wasi_linkcount_t, - pub st_size: __wasi_filesize_t, - pub st_atim: __wasi_timestamp_t, - pub st_mtim: __wasi_timestamp_t, - pub st_ctim: __wasi_timestamp_t, -} - -impl fmt::Debug for __wasi_filestat_t { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let convert_ts_into_time_string = |ts| { - let tspec = ::time::OffsetDateTime::from_unix_timestamp_nanos(ts); - format!("{} ({})", tspec.format("%a, %d %b %Y %T %z"), ts) - }; - f.debug_struct("__wasi_filestat_t") - .field("st_dev", &self.st_dev) - .field("st_ino", &self.st_ino) - .field( - "st_filetype", - &format!( - "{} ({})", - wasi_filetype_to_name(self.st_filetype), - self.st_filetype, - ), - ) - .field("st_nlink", &self.st_nlink) - .field("st_size", &self.st_size) - .field( - "st_atim", - &convert_ts_into_time_string(self.st_atim as i128), - ) - .field( - "st_mtim", - &convert_ts_into_time_string(self.st_mtim as i128), - ) - .field( - "st_ctim", - &convert_ts_into_time_string(self.st_ctim as i128), - ) - .finish() - } -} - -impl fmt::Debug for __wasi_subscription_t { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("__wasi_subscription_t") - .field("userdata", &self.userdata) - .field("type", &eventtype_to_str(self.type_)) - .field( - "u", - match self.type_ { - __WASI_EVENTTYPE_CLOCK => unsafe { &self.u.clock }, - __WASI_EVENTTYPE_FD_READ | __WASI_EVENTTYPE_FD_WRITE => unsafe { - &self.u.fd_readwrite - }, - _ => &"INVALID EVENTTYPE", - }, - ) - .finish() - } -} diff --git a/lib/wasi/Cargo.toml b/lib/wasi/Cargo.toml index c02fff666e0..3819635a42f 100644 --- a/lib/wasi/Cargo.toml +++ b/lib/wasi/Cargo.toml @@ -22,6 +22,7 @@ wasmer-vfs = { path = "../vfs", version = "=3.0.0-beta", default-features = fals wasmer-vbus = { path = "../vbus", version = "=3.0.0-beta", default-features = false } wasmer-vnet = { path = "../vnet", version = "=3.0.0-beta", default-features = false } wasmer-wasi-local-networking = { path = "../wasi-local-networking", version = "=3.0.0-beta", default-features = false, optional = true } +wasmer-wasi-types-generated = { path = "../wasi-types-generated", version = "=3.0.0-beta", default-features = false } typetag = { version = "0.1", optional = true } serde = { version = "1.0", default-features = false, features = ["derive"], optional = true } bincode = { version = "1.3", optional = true } @@ -46,11 +47,11 @@ tracing-wasm = "0.2" default = ["sys-default"] wasix = [] -sys = ["wasmer/sys", "wasix"] +sys = ["wasmer/sys", "wasix", "wasmer-wasi-types-generated/sys"] sys-default = ["wasmer/wat", "wasmer/compiler", "sys", "logging", "host-fs", "sys-poll", "host-vnet" ] sys-poll = [] -js = ["wasmer/js", "mem-fs", "wasmer-vfs/no-time", "getrandom/js", "chrono"] +js = ["wasmer/js", "mem-fs", "wasmer-vfs/no-time", "getrandom/js", "chrono", "wasmer-wasi-types-generated/js"] js-default = ["js", "wasmer/js-default"] test-js = ["js", "wasmer/js-default", "wasmer/wat"] diff --git a/lib/wasi/src/lib.rs b/lib/wasi/src/lib.rs index 11f64498378..de768e8834e 100644 --- a/lib/wasi/src/lib.rs +++ b/lib/wasi/src/lib.rs @@ -57,7 +57,6 @@ pub use wasmer_vfs::FsError as WasiFsError; pub use wasmer_vfs::VirtualFile as WasiFile; pub use wasmer_vfs::{FsError, VirtualFile}; pub use wasmer_vnet::{UnsupportedVirtualNetworking, VirtualNetworking}; -use wasmer_wasi_types::__WASI_CLOCK_MONOTONIC; use derivative::*; use std::ops::Deref; @@ -66,6 +65,7 @@ use wasmer::{ imports, namespace, AsStoreMut, AsStoreRef, Exports, Function, FunctionEnv, Imports, Memory, Memory32, MemoryAccessError, MemorySize, MemoryView, Module, TypedFunction, }; +use wasmer_wasi_types_generated::wasi::{BusErrno, Errno, Snapshot0Clockid}; pub use runtime::{ PluggableRuntimeImplementation, WasiRuntimeImplementation, WasiThreadError, WasiTtyState, @@ -292,10 +292,12 @@ impl WasiEnv { // Sleeps for a period of time pub fn sleep(&self, duration: Duration) -> Result<(), WasiError> { let duration = duration.as_nanos(); - let start = platform_clock_time_get(__WASI_CLOCK_MONOTONIC, 1_000_000).unwrap() as u128; + let start = + platform_clock_time_get(Snapshot0Clockid::Monotonic, 1_000_000).unwrap() as u128; self.yield_now()?; loop { - let now = platform_clock_time_get(__WASI_CLOCK_MONOTONIC, 1_000_000).unwrap() as u128; + let now = + platform_clock_time_get(Snapshot0Clockid::Monotonic, 1_000_000).unwrap() as u128; let delta = match now.checked_sub(start) { Some(a) => a, None => { @@ -780,20 +782,20 @@ fn generate_import_object_wasix64_v1( } } -fn mem_error_to_wasi(err: MemoryAccessError) -> types::__wasi_errno_t { +fn mem_error_to_wasi(err: MemoryAccessError) -> Errno { match err { - MemoryAccessError::HeapOutOfBounds => types::__WASI_EFAULT, - MemoryAccessError::Overflow => types::__WASI_EOVERFLOW, - MemoryAccessError::NonUtf8String => types::__WASI_EINVAL, - _ => types::__WASI_EINVAL, + MemoryAccessError::HeapOutOfBounds => Errno::Fault, + MemoryAccessError::Overflow => Errno::Overflow, + MemoryAccessError::NonUtf8String => Errno::Inval, + _ => Errno::Inval, } } -fn mem_error_to_bus(err: MemoryAccessError) -> types::__bus_errno_t { +fn mem_error_to_bus(err: MemoryAccessError) -> BusErrno { match err { - MemoryAccessError::HeapOutOfBounds => types::__BUS_EMEMVIOLATION, - MemoryAccessError::Overflow => types::__BUS_EMEMVIOLATION, - MemoryAccessError::NonUtf8String => types::__BUS_EBADREQUEST, - _ => types::__BUS_EUNKNOWN, + MemoryAccessError::HeapOutOfBounds => BusErrno::Memviolation, + MemoryAccessError::Overflow => BusErrno::Memviolation, + MemoryAccessError::NonUtf8String => BusErrno::Badrequest, + _ => BusErrno::Unknown, } } diff --git a/lib/wasi/src/macros.rs b/lib/wasi/src/macros.rs index b9ec4245597..450e88cd637 100644 --- a/lib/wasi/src/macros.rs +++ b/lib/wasi/src/macros.rs @@ -4,7 +4,7 @@ /// succeeded or returns the error value. macro_rules! wasi_try { ($expr:expr) => {{ - let res: Result<_, crate::syscalls::types::__wasi_errno_t> = $expr; + let res: Result<_, crate::syscalls::types::wasi::Errno> = $expr; match res { Ok(val) => { tracing::trace!("wasi::wasi_try::val: {:?}", val); @@ -22,7 +22,7 @@ macro_rules! wasi_try { /// succeeded or returns the error value. Results are wrapped in an Ok macro_rules! wasi_try_ok { ($expr:expr) => {{ - let res: Result<_, crate::syscalls::types::__wasi_errno_t> = $expr; + let res: Result<_, crate::syscalls::types::wasi::Errno> = $expr; match res { Ok(val) => { tracing::trace!("wasi::wasi_try_ok::val: {:?}", val); @@ -36,14 +36,14 @@ macro_rules! wasi_try_ok { }}; ($expr:expr, $thread:expr) => {{ - let res: Result<_, crate::syscalls::types::__wasi_errno_t> = $expr; + let res: Result<_, crate::syscalls::types::wasi::Errno> = $expr; match res { Ok(val) => { tracing::trace!("wasi::wasi_try_ok::val: {:?}", val); val } Err(err) => { - if err == __WASI_EINTR { + if err == crate::syscalls::types::wasi::Errno::Intr { $thread.yield_now()?; } tracing::debug!("wasi::wasi_try_ok::err: {:?}", err); @@ -57,7 +57,7 @@ macro_rules! wasi_try_ok { /// succeeded or returns the error value. macro_rules! wasi_try_bus { ($expr:expr) => {{ - let res: Result<_, crate::syscalls::types::__bus_errno_t> = $expr; + let res: Result<_, crate::syscalls::types::wasi::BusErrno> = $expr; match res { Ok(val) => { tracing::trace!("wasi::wasi_try_bus::val: {:?}", val); @@ -71,21 +71,21 @@ macro_rules! wasi_try_bus { }}; } -/// Like `wasi_try` but converts a `MemoryAccessError` to a __wasi_errno_t`. +/// Like `wasi_try` but converts a `MemoryAccessError` to a `wasi::Errno`. macro_rules! wasi_try_mem { ($expr:expr) => {{ wasi_try!($expr.map_err($crate::mem_error_to_wasi)) }}; } -/// Like `wasi_try` but converts a `MemoryAccessError` to a __bus_errno_t`. +/// Like `wasi_try` but converts a `MemoryAccessError` to a `wasi::BusErrno`. macro_rules! wasi_try_mem_bus { ($expr:expr) => {{ wasi_try_bus!($expr.map_err($crate::mem_error_to_bus)) }}; } -/// Like `wasi_try` but converts a `MemoryAccessError` to a __wasi_errno_t`. +/// Like `wasi_try` but converts a `MemoryAccessError` to a `wasi::Errno`. macro_rules! wasi_try_mem_ok { ($expr:expr) => {{ wasi_try_ok!($expr.map_err($crate::mem_error_to_wasi)) diff --git a/lib/wasi/src/runtime.rs b/lib/wasi/src/runtime.rs index 00c208bd166..a931272ec23 100644 --- a/lib/wasi/src/runtime.rs +++ b/lib/wasi/src/runtime.rs @@ -4,8 +4,8 @@ use std::sync::atomic::{AtomicU32, Ordering}; use thiserror::Error; use wasmer_vbus::{UnsupportedVirtualBus, VirtualBus}; use wasmer_vnet::VirtualNetworking; +use wasmer_wasi_types_generated::wasi::Errno; -use super::types::*; use super::WasiError; use super::WasiThreadId; @@ -17,11 +17,11 @@ pub enum WasiThreadError { MethodNotFound, } -impl From for __wasi_errno_t { - fn from(a: WasiThreadError) -> __wasi_errno_t { +impl From for Errno { + fn from(a: WasiThreadError) -> Errno { match a { - WasiThreadError::Unsupported => __WASI_ENOTSUP, - WasiThreadError::MethodNotFound => __WASI_EINVAL, + WasiThreadError::Unsupported => Errno::Notsup, + WasiThreadError::MethodNotFound => Errno::Inval, } } } diff --git a/lib/wasi/src/state/guard.rs b/lib/wasi/src/state/guard.rs index e37c9c97845..d3a84ffcabd 100644 --- a/lib/wasi/src/state/guard.rs +++ b/lib/wasi/src/state/guard.rs @@ -50,7 +50,7 @@ pub(crate) struct WasiStateFileGuard { } impl WasiStateFileGuard { - pub fn new(state: &WasiState, fd: __wasi_fd_t) -> Result, FsError> { + pub fn new(state: &WasiState, fd: wasi::Fd) -> Result, FsError> { let inodes = state.inodes.read().unwrap(); let fd_map = state.fs.fd_map.read().unwrap(); if let Some(fd) = fd_map.get(&fd) { diff --git a/lib/wasi/src/state/mod.rs b/lib/wasi/src/state/mod.rs index 4b1a75a718d..c4fafe4a73f 100644 --- a/lib/wasi/src/state/mod.rs +++ b/lib/wasi/src/state/mod.rs @@ -52,26 +52,41 @@ use std::{ }; use tracing::{debug, trace}; use wasmer_vbus::BusSpawnedProcess; +use wasmer_wasi_types_generated::wasi::{ + Errno, Fd as WasiFd, Fdflags, Fdstat, Filesize, Filestat, Filetype, Preopentype, Rights, +}; use wasmer_vfs::{FileSystem, FsError, OpenOptions, VirtualFile}; /// the fd value of the virtual root -pub const VIRTUAL_ROOT_FD: __wasi_fd_t = 3; +pub const VIRTUAL_ROOT_FD: WasiFd = 3; /// all the rights enabled -pub const ALL_RIGHTS: __wasi_rights_t = 0x1FFF_FFFF; -const STDIN_DEFAULT_RIGHTS: __wasi_rights_t = __WASI_RIGHT_FD_DATASYNC - | __WASI_RIGHT_FD_READ - | __WASI_RIGHT_FD_SYNC - | __WASI_RIGHT_FD_ADVISE - | __WASI_RIGHT_FD_FILESTAT_GET - | __WASI_RIGHT_POLL_FD_READWRITE; -const STDOUT_DEFAULT_RIGHTS: __wasi_rights_t = __WASI_RIGHT_FD_DATASYNC - | __WASI_RIGHT_FD_WRITE - | __WASI_RIGHT_FD_SYNC - | __WASI_RIGHT_FD_ADVISE - | __WASI_RIGHT_FD_FILESTAT_GET - | __WASI_RIGHT_POLL_FD_READWRITE; -const STDERR_DEFAULT_RIGHTS: __wasi_rights_t = STDOUT_DEFAULT_RIGHTS; +pub const ALL_RIGHTS: Rights = Rights::all(); +const STDIN_DEFAULT_RIGHTS: Rights = { + // This might seem a bit overenineered, but it's the only way I + // discovered for getting the values in a const environment + Rights::from_bits_truncate( + Rights::FD_DATASYNC.bits() + | Rights::FD_READ.bits() + | Rights::FD_SYNC.bits() + | Rights::FD_ADVISE.bits() + | Rights::FD_FILESTAT_GET.bits() + | Rights::POLL_FD_READWRITE.bits(), + ) +}; +const STDOUT_DEFAULT_RIGHTS: Rights = { + // This might seem a bit overenineered, but it's the only way I + // discovered for getting the values in a const environment + Rights::from_bits_truncate( + Rights::FD_DATASYNC.bits() + | Rights::FD_SYNC.bits() + | Rights::FD_WRITE.bits() + | Rights::FD_ADVISE.bits() + | Rights::FD_FILESTAT_GET.bits() + | Rights::POLL_FD_READWRITE.bits(), + ) +}; +const STDERR_DEFAULT_RIGHTS: Rights = STDOUT_DEFAULT_RIGHTS; /// A completely aribtrary "big enough" number used as the upper limit for /// the number of symlinks that can be traversed when resolving a path @@ -81,7 +96,7 @@ pub const MAX_SYMLINKS: u32 = 128; #[derive(Debug)] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] pub struct InodeVal { - pub stat: RwLock<__wasi_filestat_t>, + pub stat: RwLock, pub is_preopened: bool, pub name: String, pub kind: RwLock, @@ -149,7 +164,7 @@ pub enum Kind { /// - There is always a closer pre-opened dir to the symlink file (by definition of the root being a collection of preopened dirs) Symlink { /// The preopened dir that this symlink file is relative to (via `path_to_symlink`) - base_po_dir: __wasi_fd_t, + base_po_dir: WasiFd, /// The path to the symlink from the `base_po_dir` path_to_symlink: PathBuf, /// the value of the symlink as a relative path @@ -172,9 +187,9 @@ pub enum Kind { #[derive(Debug, Clone)] #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] pub struct Fd { - pub rights: __wasi_rights_t, - pub rights_inheriting: __wasi_rights_t, - pub flags: __wasi_fdflags_t, + pub rights: Rights, + pub rights_inheriting: Rights, + pub flags: Fdflags, pub offset: u64, /// Flags that determine how the [`Fd`] can be used. /// @@ -212,14 +227,11 @@ pub struct WasiInodes { impl WasiInodes { /// gets either a normal inode or an orphaned inode - pub fn get_inodeval( - &self, - inode: generational_arena::Index, - ) -> Result<&InodeVal, __wasi_errno_t> { + pub fn get_inodeval(&self, inode: generational_arena::Index) -> Result<&InodeVal, Errno> { if let Some(iv) = self.arena.get(inode) { Ok(iv) } else { - self.orphan_fds.get(&inode).ok_or(__WASI_EBADF) + self.orphan_fds.get(&inode).ok_or(Errno::Badf) } } @@ -227,11 +239,11 @@ impl WasiInodes { pub fn get_inodeval_mut( &mut self, inode: generational_arena::Index, - ) -> Result<&mut InodeVal, __wasi_errno_t> { + ) -> Result<&mut InodeVal, Errno> { if let Some(iv) = self.arena.get_mut(inode) { Ok(iv) } else { - self.orphan_fds.get_mut(&inode).ok_or(__WASI_EBADF) + self.orphan_fds.get_mut(&inode).ok_or(Errno::Badf) } } @@ -285,7 +297,7 @@ impl WasiInodes { fn std_dev_get<'a>( &'a self, fd_map: &RwLock>, - fd: __wasi_fd_t, + fd: WasiFd, ) -> Result, FsError> { if let Some(fd) = fd_map.read().unwrap().get(&fd) { let guard = self.arena[fd.inode].read(); @@ -305,7 +317,7 @@ impl WasiInodes { fn std_dev_get_mut<'a>( &'a self, fd_map: &RwLock>, - fd: __wasi_fd_t, + fd: WasiFd, ) -> Result, FsError> { if let Some(fd) = fd_map.read().unwrap().get(&fd) { let guard = self.arena[fd.inode].write(); @@ -404,19 +416,19 @@ impl WasiFs { path: PathBuf::from(preopen_name), entries: Default::default(), }; - let rights = __WASI_RIGHT_FD_ADVISE - | __WASI_RIGHT_FD_TELL - | __WASI_RIGHT_FD_SEEK - | __WASI_RIGHT_FD_READ - | __WASI_RIGHT_PATH_OPEN - | __WASI_RIGHT_FD_READDIR - | __WASI_RIGHT_PATH_READLINK - | __WASI_RIGHT_PATH_FILESTAT_GET - | __WASI_RIGHT_FD_FILESTAT_GET - | __WASI_RIGHT_PATH_LINK_SOURCE - | __WASI_RIGHT_PATH_RENAME_SOURCE - | __WASI_RIGHT_POLL_FD_READWRITE - | __WASI_RIGHT_SOCK_SHUTDOWN; + let rights = Rights::FD_ADVISE + | Rights::FD_TELL + | Rights::FD_SEEK + | Rights::FD_READ + | Rights::PATH_OPEN + | Rights::FD_READDIR + | Rights::PATH_READLINK + | Rights::PATH_FILESTAT_GET + | Rights::FD_FILESTAT_GET + | Rights::PATH_LINK_SOURCE + | Rights::PATH_RENAME_SOURCE + | Rights::POLL_FD_READWRITE + | Rights::SOCK_SHUTDOWN; let inode = wasi_fs .create_inode(inodes, kind, true, preopen_name.clone()) .map_err(|e| { @@ -427,7 +439,7 @@ impl WasiFs { })?; let fd_flags = Fd::READ; let fd = wasi_fs - .create_fd(rights, rights, 0, fd_flags, inode) + .create_fd(rights, rights, Fdflags::empty(), fd_flags, inode) .map_err(|e| format!("Could not open fd for file {:?}: {}", preopen_name, e))?; { let mut guard = inodes.arena[root_inode].write(); @@ -478,44 +490,43 @@ impl WasiFs { let rights = { // TODO: review tell' and fd_readwrite - let mut rights = - __WASI_RIGHT_FD_ADVISE | __WASI_RIGHT_FD_TELL | __WASI_RIGHT_FD_SEEK; + let mut rights = Rights::FD_ADVISE | Rights::FD_TELL | Rights::FD_SEEK; if *read { - rights |= __WASI_RIGHT_FD_READ - | __WASI_RIGHT_PATH_OPEN - | __WASI_RIGHT_FD_READDIR - | __WASI_RIGHT_PATH_READLINK - | __WASI_RIGHT_PATH_FILESTAT_GET - | __WASI_RIGHT_FD_FILESTAT_GET - | __WASI_RIGHT_PATH_LINK_SOURCE - | __WASI_RIGHT_PATH_RENAME_SOURCE - | __WASI_RIGHT_POLL_FD_READWRITE - | __WASI_RIGHT_SOCK_SHUTDOWN; + rights |= Rights::FD_READ + | Rights::PATH_OPEN + | Rights::FD_READDIR + | Rights::PATH_READLINK + | Rights::PATH_FILESTAT_GET + | Rights::FD_FILESTAT_GET + | Rights::PATH_LINK_SOURCE + | Rights::PATH_RENAME_SOURCE + | Rights::POLL_FD_READWRITE + | Rights::SOCK_SHUTDOWN; } if *write { - rights |= __WASI_RIGHT_FD_DATASYNC - | __WASI_RIGHT_FD_FDSTAT_SET_FLAGS - | __WASI_RIGHT_FD_WRITE - | __WASI_RIGHT_FD_SYNC - | __WASI_RIGHT_FD_ALLOCATE - | __WASI_RIGHT_PATH_OPEN - | __WASI_RIGHT_PATH_RENAME_TARGET - | __WASI_RIGHT_PATH_FILESTAT_SET_SIZE - | __WASI_RIGHT_PATH_FILESTAT_SET_TIMES - | __WASI_RIGHT_FD_FILESTAT_SET_SIZE - | __WASI_RIGHT_FD_FILESTAT_SET_TIMES - | __WASI_RIGHT_PATH_REMOVE_DIRECTORY - | __WASI_RIGHT_PATH_UNLINK_FILE - | __WASI_RIGHT_POLL_FD_READWRITE - | __WASI_RIGHT_SOCK_SHUTDOWN; + rights |= Rights::FD_DATASYNC + | Rights::FD_FDSTAT_SET_FLAGS + | Rights::FD_WRITE + | Rights::FD_SYNC + | Rights::FD_ALLOCATE + | Rights::PATH_OPEN + | Rights::PATH_RENAME_TARGET + | Rights::PATH_FILESTAT_SET_SIZE + | Rights::PATH_FILESTAT_SET_TIMES + | Rights::FD_FILESTAT_SET_SIZE + | Rights::FD_FILESTAT_SET_TIMES + | Rights::PATH_REMOVE_DIRECTORY + | Rights::PATH_UNLINK_FILE + | Rights::POLL_FD_READWRITE + | Rights::SOCK_SHUTDOWN; } if *create { - rights |= __WASI_RIGHT_PATH_CREATE_DIRECTORY - | __WASI_RIGHT_PATH_CREATE_FILE - | __WASI_RIGHT_PATH_LINK_TARGET - | __WASI_RIGHT_PATH_OPEN - | __WASI_RIGHT_PATH_RENAME_TARGET - | __WASI_RIGHT_PATH_SYMLINK; + rights |= Rights::PATH_CREATE_DIRECTORY + | Rights::PATH_CREATE_FILE + | Rights::PATH_LINK_TARGET + | Rights::PATH_OPEN + | Rights::PATH_RENAME_TARGET + | Rights::PATH_SYMLINK; } rights @@ -546,7 +557,7 @@ impl WasiFs { fd_flags }; let fd = wasi_fs - .create_fd(rights, rights, 0, fd_flags, inode) + .create_fd(rights, rights, Fdflags::empty(), fd_flags, inode) .map_err(|e| format!("Could not open fd for file {:?}: {}", path, e))?; { let mut guard = inodes.arena[root_inode].write(); @@ -596,23 +607,25 @@ impl WasiFs { // TODO: make this a list of positive rigths instead of negative ones // root gets all right for now let root_rights = all_rights - /*& (!__WASI_RIGHT_FD_WRITE) - & (!__WASI_RIGHT_FD_ALLOCATE) - & (!__WASI_RIGHT_PATH_CREATE_DIRECTORY) - & (!__WASI_RIGHT_PATH_CREATE_FILE) - & (!__WASI_RIGHT_PATH_LINK_SOURCE) - & (!__WASI_RIGHT_PATH_RENAME_SOURCE) - & (!__WASI_RIGHT_PATH_RENAME_TARGET) - & (!__WASI_RIGHT_PATH_FILESTAT_SET_SIZE) - & (!__WASI_RIGHT_PATH_FILESTAT_SET_TIMES) - & (!__WASI_RIGHT_FD_FILESTAT_SET_SIZE) - & (!__WASI_RIGHT_FD_FILESTAT_SET_TIMES) - & (!__WASI_RIGHT_PATH_SYMLINK) - & (!__WASI_RIGHT_PATH_UNLINK_FILE) - & (!__WASI_RIGHT_PATH_REMOVE_DIRECTORY)*/; + /* + & (!Rights::FD_WRITE) + & (!Rights::FD_ALLOCATE) + & (!Rights::PATH_CREATE_DIRECTORY) + & (!Rights::PATH_CREATE_FILE) + & (!Rights::PATH_LINK_SOURCE) + & (!Rights::PATH_RENAME_SOURCE) + & (!Rights::PATH_RENAME_TARGET) + & (!Rights::PATH_FILESTAT_SET_SIZE) + & (!Rights::PATH_FILESTAT_SET_TIMES) + & (!Rights::FD_FILESTAT_SET_SIZE) + & (!Rights::FD_FILESTAT_SET_TIMES) + & (!Rights::PATH_SYMLINK) + & (!Rights::PATH_UNLINK_FILE) + & (!Rights::PATH_REMOVE_DIRECTORY) + */; let inode = wasi_fs.create_virtual_root(inodes); let fd = wasi_fs - .create_fd(root_rights, root_rights, 0, Fd::READ, inode) + .create_fd(root_rights, root_rights, Fdflags::empty(), Fd::READ, inode) .map_err(|e| format!("Could not create root fd: {}", e))?; wasi_fs.preopen_fds.write().unwrap().push(fd); inode @@ -639,12 +652,12 @@ impl WasiFs { pub unsafe fn open_dir_all( &mut self, inodes: &mut WasiInodes, - base: __wasi_fd_t, + base: WasiFd, name: String, - rights: __wasi_rights_t, - rights_inheriting: __wasi_rights_t, - flags: __wasi_fdflags_t, - ) -> Result<__wasi_fd_t, FsError> { + rights: Rights, + rights_inheriting: Rights, + flags: Fdflags, + ) -> Result { // TODO: check permissions here? probably not, but this should be // an explicit choice, so justify it in a comment when we remove this one let mut cur_inode = self.get_fd_inode(base).map_err(fs_error_from_wasi_err)?; @@ -714,14 +727,14 @@ impl WasiFs { pub fn open_file_at( &mut self, inodes: &mut WasiInodes, - base: __wasi_fd_t, + base: WasiFd, file: Box, open_flags: u16, name: String, - rights: __wasi_rights_t, - rights_inheriting: __wasi_rights_t, - flags: __wasi_fdflags_t, - ) -> Result<__wasi_fd_t, FsError> { + rights: Rights, + rights_inheriting: Rights, + flags: Fdflags, + ) -> Result { // TODO: check permissions here? probably not, but this should be // an explicit choice, so justify it in a comment when we remove this one let base_inode = self.get_fd_inode(base).map_err(fs_error_from_wasi_err)?; @@ -774,7 +787,7 @@ impl WasiFs { pub fn swap_file( &self, inodes: &WasiInodes, - fd: __wasi_fd_t, + fd: WasiFd, file: Box, ) -> Result>, FsError> { let mut ret = Some(file); @@ -811,8 +824,8 @@ impl WasiFs { pub(crate) fn filestat_resync_size( &self, inodes: &WasiInodes, - fd: __wasi_fd_t, - ) -> Result<__wasi_filesize_t, __wasi_errno_t> { + fd: WasiFd, + ) -> Result { let inode = self.get_fd_inode(fd)?; let mut guard = inodes.arena[inode].write(); let deref_mut = guard.deref_mut(); @@ -823,13 +836,13 @@ impl WasiFs { drop(guard); inodes.arena[inode].stat.write().unwrap().st_size = new_size; - Ok(new_size as __wasi_filesize_t) + Ok(new_size as Filesize) } else { - Err(__WASI_EBADF) + Err(Errno::Badf) } } - Kind::Dir { .. } | Kind::Root { .. } => Err(__WASI_EISDIR), - _ => Err(__WASI_EINVAL), + Kind::Dir { .. } | Kind::Root { .. } => Err(Errno::Isdir), + _ => Err(Errno::Inval), } } @@ -843,17 +856,17 @@ impl WasiFs { pub fn get_current_dir( &self, inodes: &mut WasiInodes, - base: __wasi_fd_t, - ) -> Result<(Inode, String), __wasi_errno_t> { + base: WasiFd, + ) -> Result<(Inode, String), Errno> { self.get_current_dir_inner(inodes, base, 0) } pub(crate) fn get_current_dir_inner( &self, inodes: &mut WasiInodes, - base: __wasi_fd_t, + base: WasiFd, symlink_count: u32, - ) -> Result<(Inode, String), __wasi_errno_t> { + ) -> Result<(Inode, String), Errno> { let current_dir = { let guard = self.current_dir.lock().unwrap(); guard.clone() @@ -889,9 +902,9 @@ impl WasiFs { path: &str, mut symlink_count: u32, follow_symlinks: bool, - ) -> Result { + ) -> Result { if symlink_count > MAX_SYMLINKS { - return Err(__WASI_EMLINK); + return Err(Errno::Mlink); } let path: &Path = Path::new(path); @@ -920,7 +933,7 @@ impl WasiFs { cur_inode = *p; continue 'path_iter; } else { - return Err(__WASI_EACCES); + return Err(Errno::Access); } } "." => continue 'path_iter, @@ -942,7 +955,7 @@ impl WasiFs { .fs_backing .symlink_metadata(&file) .ok() - .ok_or(__WASI_ENOENT)?; + .ok_or(Errno::Noent)?; let file_type = metadata.file_type(); // we want to insert newly opened dirs and files, but not transient symlinks // TODO: explain why (think about this deeply when well rested) @@ -985,18 +998,17 @@ impl WasiFs { #[cfg(unix)] { //use std::os::unix::fs::FileTypeExt; - let file_type: __wasi_filetype_t = if file_type.is_char_device() - { - __WASI_FILETYPE_CHARACTER_DEVICE + let file_type: Filetype = if file_type.is_char_device() { + Filetype::CharacterDevice } else if file_type.is_block_device() { - __WASI_FILETYPE_BLOCK_DEVICE + Filetype::BlockDevice } else if file_type.is_fifo() { // FIFO doesn't seem to fit any other type, so unknown - __WASI_FILETYPE_UNKNOWN + Filetype::Unknown } else if file_type.is_socket() { - // TODO: how do we know if it's a `__WASI_FILETYPE_SOCKET_STREAM` or - // a `__WASI_FILETYPE_SOCKET_DGRAM`? - __WASI_FILETYPE_SOCKET_STREAM + // TODO: how do we know if it's a `SocketStream` or + // a `SocketDgram`? + Filetype::SocketStream } else { unimplemented!("state::get_inode_at_path unknown file type: not file, directory, symlink, char device, block device, fifo, or socket"); }; @@ -1012,9 +1024,9 @@ impl WasiFs { kind, false, file.to_string_lossy().to_string(), - __wasi_filestat_t { + Filestat { st_filetype: file_type, - ..__wasi_filestat_t::default() + ..Filestat::default() }, ); @@ -1080,14 +1092,14 @@ impl WasiFs { { cur_inode = *entry; } else { - return Err(__WASI_ENOENT); + return Err(Errno::Noent); } } Kind::File { .. } | Kind::Socket { .. } | Kind::Pipe { .. } | Kind::EventNotifications { .. } => { - return Err(__WASI_ENOTDIR); + return Err(Errno::Notdir); } Kind::Symlink { base_po_dir, @@ -1151,11 +1163,11 @@ impl WasiFs { &self, inodes: &WasiInodes, path: &'path Path, - ) -> Result<(__wasi_fd_t, &'path Path), __wasi_errno_t> { + ) -> Result<(WasiFd, &'path Path), Errno> { enum BaseFdAndRelPath<'a> { None, BestMatch { - fd: __wasi_fd_t, + fd: WasiFd, rel_path: &'a Path, max_seen: usize, }, @@ -1199,7 +1211,7 @@ impl WasiFs { } match res { // this error may not make sense depending on where it's called - BaseFdAndRelPath::None => Err(__WASI_EINVAL), + BaseFdAndRelPath::None => Err(Errno::Inval), BaseFdAndRelPath::BestMatch { fd, rel_path, .. } => Ok((fd, rel_path)), } } @@ -1209,9 +1221,9 @@ impl WasiFs { pub(crate) fn path_depth_from_fd( &self, inodes: &WasiInodes, - fd: __wasi_fd_t, + fd: WasiFd, inode: Inode, - ) -> Result { + ) -> Result { let mut counter = 0; let base_inode = self.get_fd_inode(fd)?; let mut cur_inode = inode; @@ -1226,7 +1238,7 @@ impl WasiFs { cur_inode = *p; } } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), } } @@ -1242,10 +1254,10 @@ impl WasiFs { pub(crate) fn get_inode_at_path( &self, inodes: &mut WasiInodes, - base: __wasi_fd_t, + base: WasiFd, path: &str, follow_symlinks: bool, - ) -> Result { + ) -> Result { let start_inode = if !path.starts_with('/') && self.is_wasix.load(Ordering::Acquire) { let (cur_inode, _) = self.get_current_dir(inodes, base)?; cur_inode @@ -1261,15 +1273,15 @@ impl WasiFs { pub(crate) fn get_parent_inode_at_path( &self, inodes: &mut WasiInodes, - base: __wasi_fd_t, + base: WasiFd, path: &Path, follow_symlinks: bool, - ) -> Result<(Inode, String), __wasi_errno_t> { + ) -> Result<(Inode, String), Errno> { let mut parent_dir = std::path::PathBuf::new(); let mut components = path.components().rev(); let new_entity_name = components .next() - .ok_or(__WASI_EINVAL)? + .ok_or(Errno::Inval)? .as_os_str() .to_string_lossy() .to_string(); @@ -1280,70 +1292,59 @@ impl WasiFs { .map(|v| (v, new_entity_name)) } - pub fn get_fd(&self, fd: __wasi_fd_t) -> Result { + pub fn get_fd(&self, fd: WasiFd) -> Result { self.fd_map .read() .unwrap() .get(&fd) - .ok_or(__WASI_EBADF) + .ok_or(Errno::Badf) .map(|a| a.clone()) } - pub fn get_fd_inode( - &self, - fd: __wasi_fd_t, - ) -> Result { + pub fn get_fd_inode(&self, fd: WasiFd) -> Result { self.fd_map .read() .unwrap() .get(&fd) - .ok_or(__WASI_EBADF) + .ok_or(Errno::Badf) .map(|a| a.inode) } - pub fn filestat_fd( - &self, - inodes: &WasiInodes, - fd: __wasi_fd_t, - ) -> Result<__wasi_filestat_t, __wasi_errno_t> { + pub fn filestat_fd(&self, inodes: &WasiInodes, fd: WasiFd) -> Result { let inode = self.get_fd_inode(fd)?; Ok(*inodes.arena[inode].stat.read().unwrap().deref()) } - pub fn fdstat( - &self, - inodes: &WasiInodes, - fd: __wasi_fd_t, - ) -> Result<__wasi_fdstat_t, __wasi_errno_t> { + pub fn fdstat(&self, inodes: &WasiInodes, fd: WasiFd) -> Result { match fd { __WASI_STDIN_FILENO => { - return Ok(__wasi_fdstat_t { - fs_filetype: __WASI_FILETYPE_CHARACTER_DEVICE, - fs_flags: 0, + return Ok(Fdstat { + fs_filetype: Filetype::CharacterDevice, + fs_flags: Fdflags::empty(), fs_rights_base: STDIN_DEFAULT_RIGHTS, - fs_rights_inheriting: 0, + fs_rights_inheriting: Rights::empty(), }) } __WASI_STDOUT_FILENO => { - return Ok(__wasi_fdstat_t { - fs_filetype: __WASI_FILETYPE_CHARACTER_DEVICE, - fs_flags: __WASI_FDFLAG_APPEND, + return Ok(Fdstat { + fs_filetype: Filetype::CharacterDevice, + fs_flags: Fdflags::APPEND, fs_rights_base: STDOUT_DEFAULT_RIGHTS, - fs_rights_inheriting: 0, + fs_rights_inheriting: Rights::empty(), }) } __WASI_STDERR_FILENO => { - return Ok(__wasi_fdstat_t { - fs_filetype: __WASI_FILETYPE_CHARACTER_DEVICE, - fs_flags: __WASI_FDFLAG_APPEND, + return Ok(Fdstat { + fs_filetype: Filetype::CharacterDevice, + fs_flags: Fdflags::APPEND, fs_rights_base: STDERR_DEFAULT_RIGHTS, - fs_rights_inheriting: 0, + fs_rights_inheriting: Rights::empty(), }) } VIRTUAL_ROOT_FD => { - return Ok(__wasi_fdstat_t { - fs_filetype: __WASI_FILETYPE_DIRECTORY, - fs_flags: 0, + return Ok(Fdstat { + fs_filetype: Filetype::Directory, + fs_flags: Fdflags::empty(), // TODO: fix this fs_rights_base: ALL_RIGHTS, fs_rights_inheriting: ALL_RIGHTS, @@ -1356,12 +1357,12 @@ impl WasiFs { let guard = inodes.arena[fd.inode].read(); let deref = guard.deref(); - Ok(__wasi_fdstat_t { + Ok(Fdstat { fs_filetype: match deref { - Kind::File { .. } => __WASI_FILETYPE_REGULAR_FILE, - Kind::Dir { .. } => __WASI_FILETYPE_DIRECTORY, - Kind::Symlink { .. } => __WASI_FILETYPE_SYMBOLIC_LINK, - _ => __WASI_FILETYPE_UNKNOWN, + Kind::File { .. } => Filetype::RegularFile, + Kind::Dir { .. } => Filetype::Directory, + Kind::Symlink { .. } => Filetype::SymbolicLink, + _ => Filetype::Unknown, }, fs_flags: fd.flags, fs_rights_base: fd.rights, @@ -1369,11 +1370,7 @@ impl WasiFs { }) } - pub fn prestat_fd( - &self, - inodes: &WasiInodes, - fd: __wasi_fd_t, - ) -> Result<__wasi_prestat_t, __wasi_errno_t> { + pub fn prestat_fd(&self, inodes: &WasiInodes, fd: WasiFd) -> Result<__wasi_prestat_t, Errno> { let inode = self.get_fd_inode(fd)?; trace!("in prestat_fd {:?}", self.get_fd(fd)?); @@ -1382,13 +1379,13 @@ impl WasiFs { if inode_val.is_preopened { Ok(self.prestat_fd_inner(inode_val)) } else { - Err(__WASI_EBADF) + Err(Errno::Badf) } } pub(crate) fn prestat_fd_inner(&self, inode_val: &InodeVal) -> __wasi_prestat_t { __wasi_prestat_t { - pr_type: __WASI_PREOPENTYPE_DIR, + pr_type: Preopentype::Dir, u: PrestatEnum::Dir { // REVIEW: pr_name_len: inode_val.name.len() as u32 + 1, @@ -1397,7 +1394,7 @@ impl WasiFs { } } - pub fn flush(&self, inodes: &WasiInodes, fd: __wasi_fd_t) -> Result<(), __wasi_errno_t> { + pub fn flush(&self, inodes: &WasiInodes, fd: WasiFd) -> Result<(), Errno> { match fd { __WASI_STDIN_FILENO => (), __WASI_STDOUT_FILENO => inodes @@ -1405,17 +1402,17 @@ impl WasiFs { .map_err(fs_error_into_wasi_err)? .as_mut() .map(|f| f.flush().map_err(map_io_err)) - .unwrap_or_else(|| Err(__WASI_EIO))?, + .unwrap_or_else(|| Err(Errno::Io))?, __WASI_STDERR_FILENO => inodes .stderr_mut(&self.fd_map) .map_err(fs_error_into_wasi_err)? .as_mut() .and_then(|f| f.flush().ok()) - .ok_or(__WASI_EIO)?, + .ok_or(Errno::Io)?, _ => { let fd = self.get_fd(fd)?; - if fd.rights & __WASI_RIGHT_FD_DATASYNC == 0 { - return Err(__WASI_EACCES); + if !fd.rights.contains(Rights::FD_DATASYNC) { + return Err(Errno::Access); } let mut guard = inodes.arena[fd.inode].write(); @@ -1423,12 +1420,12 @@ impl WasiFs { match deref_mut { Kind::File { handle: Some(file), .. - } => file.flush().map_err(|_| __WASI_EIO)?, + } => file.flush().map_err(|_| Errno::Io)?, // TODO: verify this behavior - Kind::Dir { .. } => return Err(__WASI_EISDIR), + Kind::Dir { .. } => return Err(Errno::Isdir), Kind::Symlink { .. } => unimplemented!("WasiFs::flush Kind::Symlink"), Kind::Buffer { .. } => (), - _ => return Err(__WASI_EIO), + _ => return Err(Errno::Io), } } } @@ -1442,7 +1439,7 @@ impl WasiFs { kind: Kind, is_preopened: bool, name: String, - ) -> Result { + ) -> Result { let stat = self.get_stat_for_kind(inodes, &kind)?; Ok(self.create_inode_with_stat(inodes, kind, is_preopened, name, stat)) } @@ -1455,7 +1452,7 @@ impl WasiFs { is_preopened: bool, name: String, ) -> Inode { - let stat = __wasi_filestat_t::default(); + let stat = Filestat::default(); self.create_inode_with_stat(inodes, kind, is_preopened, name, stat) } @@ -1466,7 +1463,7 @@ impl WasiFs { kind: Kind, is_preopened: bool, name: String, - mut stat: __wasi_filestat_t, + mut stat: Filestat, ) -> Inode { stat.st_ino = self.get_next_inode_index(); @@ -1480,12 +1477,12 @@ impl WasiFs { pub fn create_fd( &self, - rights: __wasi_rights_t, - rights_inheriting: __wasi_rights_t, - flags: __wasi_fdflags_t, + rights: Rights, + rights_inheriting: Rights, + flags: Fdflags, open_flags: u16, inode: Inode, - ) -> Result<__wasi_fd_t, __wasi_errno_t> { + ) -> Result { let idx = self.next_fd.fetch_add(1, Ordering::AcqRel); self.fd_map.write().unwrap().insert( idx, @@ -1501,7 +1498,7 @@ impl WasiFs { Ok(idx) } - pub fn clone_fd(&self, fd: __wasi_fd_t) -> Result<__wasi_fd_t, __wasi_errno_t> { + pub fn clone_fd(&self, fd: WasiFd) -> Result { let fd = self.get_fd(fd)?; let idx = self.next_fd.fetch_add(1, Ordering::AcqRel); self.fd_map.write().unwrap().insert( @@ -1531,10 +1528,10 @@ impl WasiFs { } fn create_virtual_root(&self, inodes: &mut WasiInodes) -> Inode { - let stat = __wasi_filestat_t { - st_filetype: __WASI_FILETYPE_DIRECTORY, + let stat = Filestat { + st_filetype: Filetype::Directory, st_ino: self.get_next_inode_index(), - ..__wasi_filestat_t::default() + ..Filestat::default() }; let root_kind = Kind::Root { entries: HashMap::new(), @@ -1555,7 +1552,7 @@ impl WasiFs { "stdout", __WASI_STDOUT_FILENO, STDOUT_DEFAULT_RIGHTS, - __WASI_FDFLAG_APPEND, + Fdflags::APPEND, ); } fn create_stdin(&self, inodes: &mut WasiInodes) { @@ -1565,7 +1562,7 @@ impl WasiFs { "stdin", __WASI_STDIN_FILENO, STDIN_DEFAULT_RIGHTS, - 0, + Fdflags::empty(), ); } fn create_stderr(&self, inodes: &mut WasiInodes) { @@ -1575,7 +1572,7 @@ impl WasiFs { "stderr", __WASI_STDERR_FILENO, STDERR_DEFAULT_RIGHTS, - __WASI_FDFLAG_APPEND, + Fdflags::APPEND, ); } @@ -1584,14 +1581,14 @@ impl WasiFs { inodes: &mut WasiInodes, handle: Box, name: &'static str, - raw_fd: __wasi_fd_t, - rights: __wasi_rights_t, - fd_flags: __wasi_fdflags_t, + raw_fd: WasiFd, + rights: Rights, + fd_flags: Fdflags, ) { - let stat = __wasi_filestat_t { - st_filetype: __WASI_FILETYPE_CHARACTER_DEVICE, + let stat = Filestat { + st_filetype: Filetype::CharacterDevice, st_ino: self.get_next_inode_index(), - ..__wasi_filestat_t::default() + ..Filestat::default() }; let kind = Kind::File { fd: Some(raw_fd), @@ -1610,7 +1607,7 @@ impl WasiFs { raw_fd, Fd { rights, - rights_inheriting: 0, + rights_inheriting: Rights::empty(), flags: fd_flags, // since we're not calling open on this, we don't need open flags open_flags: 0, @@ -1620,22 +1617,18 @@ impl WasiFs { ); } - pub fn get_stat_for_kind( - &self, - inodes: &WasiInodes, - kind: &Kind, - ) -> Result<__wasi_filestat_t, __wasi_errno_t> { + pub fn get_stat_for_kind(&self, inodes: &WasiInodes, kind: &Kind) -> Result { let md = match kind { Kind::File { handle, path, .. } => match handle { Some(wf) => { - return Ok(__wasi_filestat_t { - st_filetype: __WASI_FILETYPE_REGULAR_FILE, + return Ok(Filestat { + st_filetype: Filetype::RegularFile, st_size: wf.size(), st_atim: wf.last_accessed(), st_mtim: wf.last_modified(), st_ctim: wf.created_time(), - ..__wasi_filestat_t::default() + ..Filestat::default() }) } None => self @@ -1675,24 +1668,20 @@ impl WasiFs { _ => unreachable!("Symlink pointing to something that's not a directory as its base preopened directory"), } } - _ => return Err(__WASI_EIO), + _ => return Err(Errno::Io), }; - Ok(__wasi_filestat_t { + Ok(Filestat { st_filetype: virtual_file_type_to_wasi_file_type(md.file_type()), st_size: md.len(), st_atim: md.accessed(), st_mtim: md.modified(), st_ctim: md.created(), - ..__wasi_filestat_t::default() + ..Filestat::default() }) } /// Closes an open FD, handling all details such as FD being preopen - pub(crate) fn close_fd( - &self, - inodes: &WasiInodes, - fd: __wasi_fd_t, - ) -> Result<(), __wasi_errno_t> { + pub(crate) fn close_fd(&self, inodes: &WasiInodes, fd: WasiFd) -> Result<(), Errno> { let inode = self.get_fd_inode(fd)?; let inodeval = inodes.get_inodeval(inode)?; let is_preopened = inodeval.is_preopened; @@ -1715,7 +1704,7 @@ impl WasiFs { debug!("Closing dir {:?}", &path); let key = path .file_name() - .ok_or(__WASI_EINVAL)? + .ok_or(Errno::Inval)? .to_string_lossy() .to_string(); if let Some(p) = *parent { @@ -1753,12 +1742,12 @@ impl WasiFs { } else { // this shouldn't be possible anymore due to Root debug!("HIT UNREACHABLE CODE! Non-root directory does not have a parent"); - return Err(__WASI_EINVAL); + return Err(Errno::Inval); } } Kind::EventNotifications { .. } => {} - Kind::Root { .. } => return Err(__WASI_EACCES), - Kind::Symlink { .. } | Kind::Buffer { .. } => return Err(__WASI_EINVAL), + Kind::Root { .. } => return Err(Errno::Access), + Kind::Symlink { .. } | Kind::Buffer { .. } => return Err(Errno::Inval), } Ok(()) @@ -1770,21 +1759,21 @@ impl WasiState { pub(crate) fn fs_read_dir>( &self, path: P, - ) -> Result { + ) -> Result { self.fs .fs_backing .read_dir(path.as_ref()) .map_err(fs_error_into_wasi_err) } - pub(crate) fn fs_create_dir>(&self, path: P) -> Result<(), __wasi_errno_t> { + pub(crate) fn fs_create_dir>(&self, path: P) -> Result<(), Errno> { self.fs .fs_backing .create_dir(path.as_ref()) .map_err(fs_error_into_wasi_err) } - pub(crate) fn fs_remove_dir>(&self, path: P) -> Result<(), __wasi_errno_t> { + pub(crate) fn fs_remove_dir>(&self, path: P) -> Result<(), Errno> { self.fs .fs_backing .remove_dir(path.as_ref()) @@ -1795,14 +1784,14 @@ impl WasiState { &self, from: P, to: Q, - ) -> Result<(), __wasi_errno_t> { + ) -> Result<(), Errno> { self.fs .fs_backing .rename(from.as_ref(), to.as_ref()) .map_err(fs_error_into_wasi_err) } - pub(crate) fn fs_remove_file>(&self, path: P) -> Result<(), __wasi_errno_t> { + pub(crate) fn fs_remove_file>(&self, path: P) -> Result<(), Errno> { self.fs .fs_backing .remove_file(path.as_ref()) @@ -1938,7 +1927,7 @@ impl WasiState { /// Expects one of `__WASI_STDIN_FILENO`, `__WASI_STDOUT_FILENO`, `__WASI_STDERR_FILENO`. fn std_dev_get( &self, - fd: __wasi_fd_t, + fd: WasiFd, ) -> Result>, FsError> { let ret = WasiStateFileGuard::new(self, fd)?.map(|a| { let ret = Box::new(a); @@ -1949,15 +1938,15 @@ impl WasiState { } } -pub fn virtual_file_type_to_wasi_file_type(file_type: wasmer_vfs::FileType) -> __wasi_filetype_t { +pub fn virtual_file_type_to_wasi_file_type(file_type: wasmer_vfs::FileType) -> Filetype { // TODO: handle other file types if file_type.is_dir() { - __WASI_FILETYPE_DIRECTORY + Filetype::Directory } else if file_type.is_file() { - __WASI_FILETYPE_REGULAR_FILE + Filetype::RegularFile } else if file_type.is_symlink() { - __WASI_FILETYPE_SYMBOLIC_LINK + Filetype::SymbolicLink } else { - __WASI_FILETYPE_UNKNOWN + Filetype::Unknown } } diff --git a/lib/wasi/src/state/pipe.rs b/lib/wasi/src/state/pipe.rs index 12c0084d43d..4ce34e78f72 100644 --- a/lib/wasi/src/state/pipe.rs +++ b/lib/wasi/src/state/pipe.rs @@ -8,6 +8,7 @@ use std::sync::mpsc; use std::sync::Mutex; use wasmer::WasmSlice; use wasmer::{MemorySize, MemoryView}; +use wasmer_wasi_types_generated::wasi::Errno; #[derive(Debug)] pub struct WasiPipe { @@ -43,7 +44,7 @@ impl WasiPipe { &mut self, memory: &MemoryView, iov: WasmSlice<__wasi_iovec_t>, - ) -> Result { + ) -> Result { loop { if let Some(buf) = self.read_buffer.as_mut() { let buf_len = buf.len(); @@ -55,7 +56,7 @@ impl WasiPipe { } } let rx = self.rx.lock().unwrap(); - let data = rx.recv().map_err(|_| __WASI_EIO)?; + let data = rx.recv().map_err(|_| Errno::Io)?; self.read_buffer.replace(Bytes::from(data)); } } @@ -64,17 +65,17 @@ impl WasiPipe { &mut self, memory: &MemoryView, iov: WasmSlice<__wasi_ciovec_t>, - ) -> Result { + ) -> Result { let buf_len: M::Offset = iov .iter() .filter_map(|a| a.read().ok()) .map(|a| a.buf_len) .sum(); - let buf_len: usize = buf_len.try_into().map_err(|_| __WASI_EINVAL)?; + let buf_len: usize = buf_len.try_into().map_err(|_| Errno::Inval)?; let mut buf = Vec::with_capacity(buf_len); write_bytes(&mut buf, memory, iov)?; let tx = self.tx.lock().unwrap(); - tx.send(buf).map_err(|_| __WASI_EIO)?; + tx.send(buf).map_err(|_| Errno::Io)?; Ok(buf_len) } diff --git a/lib/wasi/src/state/socket.rs b/lib/wasi/src/state/socket.rs index 9f1b9765478..c304d6f9c1a 100644 --- a/lib/wasi/src/state/socket.rs +++ b/lib/wasi/src/state/socket.rs @@ -16,6 +16,7 @@ use wasmer_vnet::{ IpCidr, IpRoute, SocketHttpRequest, VirtualIcmpSocket, VirtualNetworking, VirtualRawSocket, VirtualTcpListener, VirtualTcpSocket, VirtualUdpSocket, VirtualWebSocket, }; +use wasmer_wasi_types_generated::wasi::{Addressfamily, Errno, Fdflags, Sockoption, Socktype}; #[cfg(feature = "enable-serde")] use serde::{Deserialize, Serialize}; @@ -35,8 +36,8 @@ pub enum InodeHttpSocketType { //#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] pub enum InodeSocketKind { PreSocket { - family: __wasi_addressfamily_t, - ty: __wasi_socktype_t, + family: Addressfamily, + ty: Socktype, pt: __wasi_sockproto_t, addr: Option, only_v6: bool, @@ -89,38 +90,37 @@ pub enum WasiSocketOption { Proto, } -impl From<__wasi_sockoption_t> for WasiSocketOption { - fn from(opt: __wasi_sockoption_t) -> Self { +impl From for WasiSocketOption { + fn from(opt: Sockoption) -> Self { use WasiSocketOption::*; match opt { - __WASI_SOCK_OPTION_NOOP => Noop, - __WASI_SOCK_OPTION_REUSE_PORT => ReusePort, - __WASI_SOCK_OPTION_REUSE_ADDR => ReuseAddr, - __WASI_SOCK_OPTION_NO_DELAY => NoDelay, - __WASI_SOCK_OPTION_DONT_ROUTE => DontRoute, - __WASI_SOCK_OPTION_ONLY_V6 => OnlyV6, - __WASI_SOCK_OPTION_BROADCAST => Broadcast, - __WASI_SOCK_OPTION_MULTICAST_LOOP_V4 => MulticastLoopV4, - __WASI_SOCK_OPTION_MULTICAST_LOOP_V6 => MulticastLoopV6, - __WASI_SOCK_OPTION_PROMISCUOUS => Promiscuous, - __WASI_SOCK_OPTION_LISTENING => Listening, - __WASI_SOCK_OPTION_LAST_ERROR => LastError, - __WASI_SOCK_OPTION_KEEP_ALIVE => KeepAlive, - __WASI_SOCK_OPTION_LINGER => Linger, - __WASI_SOCK_OPTION_OOB_INLINE => OobInline, - __WASI_SOCK_OPTION_RECV_BUF_SIZE => RecvBufSize, - __WASI_SOCK_OPTION_SEND_BUF_SIZE => SendBufSize, - __WASI_SOCK_OPTION_RECV_LOWAT => RecvLowat, - __WASI_SOCK_OPTION_SEND_LOWAT => SendLowat, - __WASI_SOCK_OPTION_RECV_TIMEOUT => RecvTimeout, - __WASI_SOCK_OPTION_SEND_TIMEOUT => SendTimeout, - __WASI_SOCK_OPTION_CONNECT_TIMEOUT => ConnectTimeout, - __WASI_SOCK_OPTION_ACCEPT_TIMEOUT => AcceptTimeout, - __WASI_SOCK_OPTION_TTL => Ttl, - __WASI_SOCK_OPTION_MULTICAST_TTL_V4 => MulticastTtlV4, - __WASI_SOCK_OPTION_TYPE => Type, - __WASI_SOCK_OPTION_PROTO => Proto, - _ => Noop, + Sockoption::Noop => Noop, + Sockoption::ReusePort => ReusePort, + Sockoption::ReuseAddr => ReuseAddr, + Sockoption::NoDelay => NoDelay, + Sockoption::DontRoute => DontRoute, + Sockoption::OnlyV6 => OnlyV6, + Sockoption::Broadcast => Broadcast, + Sockoption::MulticastLoopV4 => MulticastLoopV4, + Sockoption::MulticastLoopV6 => MulticastLoopV6, + Sockoption::Promiscuous => Promiscuous, + Sockoption::Listening => Listening, + Sockoption::LastError => LastError, + Sockoption::KeepAlive => KeepAlive, + Sockoption::Linger => Linger, + Sockoption::OobInline => OobInline, + Sockoption::RecvBufSize => RecvBufSize, + Sockoption::SendBufSize => SendBufSize, + Sockoption::RecvLowat => RecvLowat, + Sockoption::SendLowat => SendLowat, + Sockoption::RecvTimeout => RecvTimeout, + Sockoption::SendTimeout => SendTimeout, + Sockoption::ConnectTimeout => ConnectTimeout, + Sockoption::AcceptTimeout => AcceptTimeout, + Sockoption::Ttl => Ttl, + Sockoption::MulticastTtlV4 => MulticastTtlV4, + Sockoption::Type => Type, + Sockoption::Proto => Proto, } } } @@ -162,7 +162,7 @@ impl InodeSocket { &mut self, net: &(dyn VirtualNetworking), set_addr: SocketAddr, - ) -> Result, __wasi_errno_t> { + ) -> Result, Errno> { match &mut self.kind { InodeSocketKind::PreSocket { family, @@ -173,18 +173,18 @@ impl InodeSocket { .. } => { match *family { - __WASI_ADDRESS_FAMILY_INET4 => { + Addressfamily::Inet4 => { if !set_addr.is_ipv4() { - return Err(__WASI_EINVAL); + return Err(Errno::Inval); } } - __WASI_ADDRESS_FAMILY_INET6 => { + Addressfamily::Inet6 => { if !set_addr.is_ipv6() { - return Err(__WASI_EINVAL); + return Err(Errno::Inval); } } _ => { - return Err(__WASI_ENOTSUP); + return Err(Errno::Notsup); } } @@ -192,21 +192,21 @@ impl InodeSocket { let addr = (*addr).unwrap(); Ok(match *ty { - __WASI_SOCK_TYPE_STREAM => { + Socktype::Stream => { // we already set the socket address - next we need a bind or connect so nothing // more to do at this time None } - __WASI_SOCK_TYPE_DGRAM => { + Socktype::Dgram => { let socket = net .bind_udp(addr, *reuse_port, *reuse_addr) .map_err(net_error_into_wasi_err)?; Some(InodeSocket::new(InodeSocketKind::UdpSocket(socket))) } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }) } - _ => Err(__WASI_ENOTSUP), + _ => Err(Errno::Notsup), } } @@ -214,7 +214,7 @@ impl InodeSocket { &mut self, net: &(dyn VirtualNetworking), _backlog: usize, - ) -> Result, __wasi_errno_t> { + ) -> Result, Errno> { match &self.kind { InodeSocketKind::PreSocket { ty, @@ -225,9 +225,9 @@ impl InodeSocket { accept_timeout, .. } => Ok(match *ty { - __WASI_SOCK_TYPE_STREAM => { + Socktype::Stream => { if addr.is_none() { - return Err(__WASI_EINVAL); + return Err(Errno::Inval); } let addr = *addr.as_ref().unwrap(); let mut socket = net @@ -240,38 +240,38 @@ impl InodeSocket { } Some(InodeSocket::new(InodeSocketKind::TcpListener(socket))) } - _ => return Err(__WASI_ENOTSUP), + _ => return Err(Errno::Notsup), }), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } pub fn accept( &self, - _fd_flags: __wasi_fdflags_t, - ) -> Result<(Box, SocketAddr), __wasi_errno_t> { + _fd_flags: Fdflags, + ) -> Result<(Box, SocketAddr), Errno> { let (sock, addr) = match &self.kind { InodeSocketKind::TcpListener(sock) => sock.accept().map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Notconn), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), }?; Ok((sock, addr)) } pub fn accept_timeout( &self, - _fd_flags: __wasi_fdflags_t, + _fd_flags: Fdflags, timeout: Duration, - ) -> Result<(Box, SocketAddr), __wasi_errno_t> { + ) -> Result<(Box, SocketAddr), Errno> { let (sock, addr) = match &self.kind { InodeSocketKind::TcpListener(sock) => sock .accept_timeout(timeout) .map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Notconn), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), }?; Ok((sock, addr)) } @@ -280,7 +280,7 @@ impl InodeSocket { &mut self, net: &(dyn VirtualNetworking), peer: SocketAddr, - ) -> Result, __wasi_errno_t> { + ) -> Result, Errno> { match &mut self.kind { InodeSocketKind::PreSocket { ty, @@ -290,7 +290,7 @@ impl InodeSocket { connect_timeout, .. } => Ok(match *ty { - __WASI_SOCK_TYPE_STREAM => { + Socktype::Stream => { let addr = match addr { Some(a) => *a, None => { @@ -316,19 +316,19 @@ impl InodeSocket { } Some(InodeSocket::new(InodeSocketKind::TcpStream(socket))) } - __WASI_SOCK_TYPE_DGRAM => return Err(__WASI_EINVAL), - _ => return Err(__WASI_ENOTSUP), + Socktype::Dgram => return Err(Errno::Inval), + _ => return Err(Errno::Notsup), }), InodeSocketKind::UdpSocket(sock) => { sock.connect(peer).map_err(net_error_into_wasi_err)?; Ok(None) } - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn status(&self) -> Result { + pub fn status(&self) -> Result { Ok(match &self.kind { InodeSocketKind::PreSocket { .. } => WasiSocketStatus::Opening, InodeSocketKind::WebSocket(_) => WasiSocketStatus::Opened, @@ -341,14 +341,14 @@ impl InodeSocket { }) } - pub fn http_status(&self) -> Result { + pub fn http_status(&self) -> Result { Ok(match &self.kind { InodeSocketKind::HttpRequest(http, ..) => { let http = http.lock().unwrap(); let guard = http.status.lock().unwrap(); let status = guard .recv() - .map_err(|_| __WASI_EIO)? + .map_err(|_| Errno::Io)? .map_err(net_error_into_wasi_err)?; WasiHttpStatus { ok: true, @@ -357,12 +357,12 @@ impl InodeSocket { size: status.size as u64, } } - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), }) } - pub fn addr_local(&self) -> Result { + pub fn addr_local(&self) -> Result { Ok(match &self.kind { InodeSocketKind::PreSocket { family, addr, .. } => { if let Some(addr) = addr { @@ -370,9 +370,9 @@ impl InodeSocket { } else { SocketAddr::new( match *family { - __WASI_ADDRESS_FAMILY_INET4 => IpAddr::V4(Ipv4Addr::UNSPECIFIED), - __WASI_ADDRESS_FAMILY_INET6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED), - _ => return Err(__WASI_EINVAL), + Addressfamily::Inet4 => IpAddr::V4(Ipv4Addr::UNSPECIFIED), + Addressfamily::Inet6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED), + _ => return Err(Errno::Inval), }, 0, ) @@ -388,18 +388,18 @@ impl InodeSocket { InodeSocketKind::UdpSocket(sock) => { sock.addr_local().map_err(net_error_into_wasi_err)? } - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), }) } - pub fn addr_peer(&self) -> Result { + pub fn addr_peer(&self) -> Result { Ok(match &self.kind { InodeSocketKind::PreSocket { family, .. } => SocketAddr::new( match *family { - __WASI_ADDRESS_FAMILY_INET4 => IpAddr::V4(Ipv4Addr::UNSPECIFIED), - __WASI_ADDRESS_FAMILY_INET6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED), - _ => return Err(__WASI_EINVAL), + Addressfamily::Inet4 => IpAddr::V4(Ipv4Addr::UNSPECIFIED), + Addressfamily::Inet6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED), + _ => return Err(Errno::Inval), }, 0, ), @@ -423,16 +423,12 @@ impl InodeSocket { ) }) })?, - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), }) } - pub fn set_opt_flag( - &mut self, - option: WasiSocketOption, - val: bool, - ) -> Result<(), __wasi_errno_t> { + pub fn set_opt_flag(&mut self, option: WasiSocketOption, val: bool) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::PreSocket { only_v6, @@ -444,20 +440,20 @@ impl InodeSocket { WasiSocketOption::OnlyV6 => *only_v6 = val, WasiSocketOption::ReusePort => *reuse_port = val, WasiSocketOption::ReuseAddr => *reuse_addr = val, - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }; } InodeSocketKind::Raw(sock) => match option { WasiSocketOption::Promiscuous => { sock.set_promiscuous(val).map_err(net_error_into_wasi_err)? } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, InodeSocketKind::TcpStream(sock) => match option { WasiSocketOption::NoDelay => { sock.set_nodelay(val).map_err(net_error_into_wasi_err)? } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, InodeSocketKind::UdpSocket(sock) => match option { WasiSocketOption::Broadcast => { @@ -469,15 +465,15 @@ impl InodeSocket { WasiSocketOption::MulticastLoopV6 => sock .set_multicast_loop_v6(val) .map_err(net_error_into_wasi_err)?, - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), } Ok(()) } - pub fn get_opt_flag(&self, option: WasiSocketOption) -> Result { + pub fn get_opt_flag(&self, option: WasiSocketOption) -> Result { Ok(match &self.kind { InodeSocketKind::PreSocket { only_v6, @@ -488,17 +484,17 @@ impl InodeSocket { WasiSocketOption::OnlyV6 => *only_v6, WasiSocketOption::ReusePort => *reuse_port, WasiSocketOption::ReuseAddr => *reuse_addr, - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, InodeSocketKind::Raw(sock) => match option { WasiSocketOption::Promiscuous => { sock.promiscuous().map_err(net_error_into_wasi_err)? } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, InodeSocketKind::TcpStream(sock) => match option { WasiSocketOption::NoDelay => sock.nodelay().map_err(net_error_into_wasi_err)?, - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, InodeSocketKind::UdpSocket(sock) => match option { WasiSocketOption::Broadcast => sock.broadcast().map_err(net_error_into_wasi_err)?, @@ -508,14 +504,14 @@ impl InodeSocket { WasiSocketOption::MulticastLoopV6 => { sock.multicast_loop_v6().map_err(net_error_into_wasi_err)? } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), }) } - pub fn set_send_buf_size(&mut self, size: usize) -> Result<(), __wasi_errno_t> { + pub fn set_send_buf_size(&mut self, size: usize) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::PreSocket { send_buf_size, .. } => { *send_buf_size = Some(size); @@ -524,13 +520,13 @@ impl InodeSocket { sock.set_send_buf_size(size) .map_err(net_error_into_wasi_err)?; } - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), } Ok(()) } - pub fn send_buf_size(&self) -> Result { + pub fn send_buf_size(&self) -> Result { match &self.kind { InodeSocketKind::PreSocket { send_buf_size, .. } => { Ok((*send_buf_size).unwrap_or_default()) @@ -538,12 +534,12 @@ impl InodeSocket { InodeSocketKind::TcpStream(sock) => { sock.send_buf_size().map_err(net_error_into_wasi_err) } - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn set_recv_buf_size(&mut self, size: usize) -> Result<(), __wasi_errno_t> { + pub fn set_recv_buf_size(&mut self, size: usize) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::PreSocket { recv_buf_size, .. } => { *recv_buf_size = Some(size); @@ -552,13 +548,13 @@ impl InodeSocket { sock.set_recv_buf_size(size) .map_err(net_error_into_wasi_err)?; } - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), } Ok(()) } - pub fn recv_buf_size(&self) -> Result { + pub fn recv_buf_size(&self) -> Result { match &self.kind { InodeSocketKind::PreSocket { recv_buf_size, .. } => { Ok((*recv_buf_size).unwrap_or_default()) @@ -566,31 +562,28 @@ impl InodeSocket { InodeSocketKind::TcpStream(sock) => { sock.recv_buf_size().map_err(net_error_into_wasi_err) } - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn set_linger( - &mut self, - linger: Option, - ) -> Result<(), __wasi_errno_t> { + pub fn set_linger(&mut self, linger: Option) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::TcpStream(sock) => { sock.set_linger(linger).map_err(net_error_into_wasi_err) } - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn linger(&self) -> Result, __wasi_errno_t> { + pub fn linger(&self) -> Result, Errno> { match &self.kind { InodeSocketKind::TcpStream(sock) => sock.linger().map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } @@ -598,7 +591,7 @@ impl InodeSocket { &mut self, ty: TimeType, timeout: Option, - ) -> Result<(), __wasi_errno_t> { + ) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::TcpStream(sock) => sock .set_opt_time(ty, timeout) @@ -607,7 +600,7 @@ impl InodeSocket { TimeType::AcceptTimeout => { sock.set_timeout(timeout).map_err(net_error_into_wasi_err) } - _ => Err(__WASI_EINVAL), + _ => Err(Errno::Inval), }, InodeSocketKind::PreSocket { recv_timeout, @@ -632,19 +625,19 @@ impl InodeSocket { *send_timeout = timeout; Ok(()) } - _ => Err(__WASI_EIO), + _ => Err(Errno::Io), }, - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn opt_time(&self, ty: TimeType) -> Result, __wasi_errno_t> { + pub fn opt_time(&self, ty: TimeType) -> Result, Errno> { match &self.kind { InodeSocketKind::TcpStream(sock) => sock.opt_time(ty).map_err(net_error_into_wasi_err), InodeSocketKind::TcpListener(sock) => match ty { TimeType::AcceptTimeout => sock.timeout().map_err(net_error_into_wasi_err), - _ => Err(__WASI_EINVAL), + _ => Err(Errno::Inval), }, InodeSocketKind::PreSocket { recv_timeout, @@ -657,67 +650,63 @@ impl InodeSocket { TimeType::AcceptTimeout => Ok(*accept_timeout), TimeType::ReadTimeout => Ok(*recv_timeout), TimeType::WriteTimeout => Ok(*send_timeout), - _ => Err(__WASI_EINVAL), + _ => Err(Errno::Inval), }, - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn set_ttl(&mut self, ttl: u32) -> Result<(), __wasi_errno_t> { + pub fn set_ttl(&mut self, ttl: u32) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::TcpStream(sock) => sock.set_ttl(ttl).map_err(net_error_into_wasi_err), InodeSocketKind::UdpSocket(sock) => sock.set_ttl(ttl).map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn ttl(&self) -> Result { + pub fn ttl(&self) -> Result { match &self.kind { InodeSocketKind::TcpStream(sock) => sock.ttl().map_err(net_error_into_wasi_err), InodeSocketKind::UdpSocket(sock) => sock.ttl().map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn set_multicast_ttl_v4(&mut self, ttl: u32) -> Result<(), __wasi_errno_t> { + pub fn set_multicast_ttl_v4(&mut self, ttl: u32) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::UdpSocket(sock) => sock .set_multicast_ttl_v4(ttl) .map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn multicast_ttl_v4(&self) -> Result { + pub fn multicast_ttl_v4(&self) -> Result { match &self.kind { InodeSocketKind::UdpSocket(sock) => { sock.multicast_ttl_v4().map_err(net_error_into_wasi_err) } - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn join_multicast_v4( - &mut self, - multiaddr: Ipv4Addr, - iface: Ipv4Addr, - ) -> Result<(), __wasi_errno_t> { + pub fn join_multicast_v4(&mut self, multiaddr: Ipv4Addr, iface: Ipv4Addr) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::UdpSocket(sock) => sock .join_multicast_v4(multiaddr, iface) .map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } @@ -725,44 +714,36 @@ impl InodeSocket { &mut self, multiaddr: Ipv4Addr, iface: Ipv4Addr, - ) -> Result<(), __wasi_errno_t> { + ) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::UdpSocket(sock) => sock .leave_multicast_v4(multiaddr, iface) .map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn join_multicast_v6( - &mut self, - multiaddr: Ipv6Addr, - iface: u32, - ) -> Result<(), __wasi_errno_t> { + pub fn join_multicast_v6(&mut self, multiaddr: Ipv6Addr, iface: u32) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::UdpSocket(sock) => sock .join_multicast_v6(multiaddr, iface) .map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } - pub fn leave_multicast_v6( - &mut self, - multiaddr: Ipv6Addr, - iface: u32, - ) -> Result<(), __wasi_errno_t> { + pub fn leave_multicast_v6(&mut self, multiaddr: Ipv6Addr, iface: u32) -> Result<(), Errno> { match &mut self.kind { InodeSocketKind::UdpSocket(sock) => sock .leave_multicast_v6(multiaddr, iface) .map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_EIO), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Io), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } } @@ -770,13 +751,13 @@ impl InodeSocket { &mut self, memory: &MemoryView, iov: WasmSlice<__wasi_ciovec_t>, - ) -> Result { + ) -> Result { let buf_len: M::Offset = iov .iter() .filter_map(|a| a.read().ok()) .map(|a| a.buf_len) .sum(); - let buf_len: usize = buf_len.try_into().map_err(|_| __WASI_EINVAL)?; + let buf_len: usize = buf_len.try_into().map_err(|_| Errno::Inval)?; let mut buf = Vec::with_capacity(buf_len); write_bytes(&mut buf, memory, iov)?; match &mut self.kind { @@ -785,13 +766,13 @@ impl InodeSocket { match ty { InodeHttpSocketType::Request => { if sock.request.is_none() { - return Err(__WASI_EIO); + return Err(Errno::Io); } let request = sock.request.as_ref().unwrap(); - request.send(buf).map(|_| buf_len).map_err(|_| __WASI_EIO) + request.send(buf).map(|_| buf_len).map_err(|_| Errno::Io) } _ => { - return Err(__WASI_EIO); + return Err(Errno::Io); } } } @@ -808,14 +789,14 @@ impl InodeSocket { InodeSocketKind::UdpSocket(sock) => { sock.send(Bytes::from(buf)).map_err(net_error_into_wasi_err) } - InodeSocketKind::PreSocket { .. } => Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Notconn), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } .map(|_| buf_len) } - pub fn send_bytes(&mut self, buf: Bytes) -> Result { + pub fn send_bytes(&mut self, buf: Bytes) -> Result { let buf_len = buf.len(); match &mut self.kind { InodeSocketKind::HttpRequest(sock, ty) => { @@ -823,16 +804,16 @@ impl InodeSocket { match ty { InodeHttpSocketType::Request => { if sock.request.is_none() { - return Err(__WASI_EIO); + return Err(Errno::Io); } let request = sock.request.as_ref().unwrap(); request .send(buf.to_vec()) .map(|_| buf_len) - .map_err(|_| __WASI_EIO) + .map_err(|_| Errno::Io) } _ => { - return Err(__WASI_EIO); + return Err(Errno::Io); } } } @@ -843,9 +824,9 @@ impl InodeSocket { InodeSocketKind::Raw(sock) => sock.send(buf).map_err(net_error_into_wasi_err), InodeSocketKind::TcpStream(sock) => sock.send(buf).map_err(net_error_into_wasi_err), InodeSocketKind::UdpSocket(sock) => sock.send(buf).map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Notconn), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } .map(|_| buf_len) } @@ -855,7 +836,7 @@ impl InodeSocket { memory: &MemoryView, iov: WasmSlice<__wasi_ciovec_t>, addr: WasmPtr<__wasi_addr_port_t, M>, - ) -> Result { + ) -> Result { let (addr_ip, addr_port) = read_ip_port(memory, addr)?; let addr = SocketAddr::new(addr_ip, addr_port); let buf_len: M::Offset = iov @@ -863,7 +844,7 @@ impl InodeSocket { .filter_map(|a| a.read().ok()) .map(|a| a.buf_len) .sum(); - let buf_len: usize = buf_len.try_into().map_err(|_| __WASI_EINVAL)?; + let buf_len: usize = buf_len.try_into().map_err(|_| Errno::Inval)?; let mut buf = Vec::with_capacity(buf_len); write_bytes(&mut buf, memory, iov)?; match &mut self.kind { @@ -873,9 +854,9 @@ impl InodeSocket { InodeSocketKind::UdpSocket(sock) => sock .send_to(Bytes::from(buf), addr) .map_err(net_error_into_wasi_err), - InodeSocketKind::PreSocket { .. } => Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => Err(__WASI_EIO), - _ => Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => Err(Errno::Notconn), + InodeSocketKind::Closed => Err(Errno::Io), + _ => Err(Errno::Notsup), } .map(|_| buf_len) } @@ -884,7 +865,7 @@ impl InodeSocket { &mut self, memory: &MemoryView, iov: WasmSlice<__wasi_iovec_t>, - ) -> Result { + ) -> Result { loop { if let Some(buf) = self.read_buffer.as_mut() { let buf_len = buf.len(); @@ -905,22 +886,22 @@ impl InodeSocket { match ty { InodeHttpSocketType::Response => { if sock.response.is_none() { - return Err(__WASI_EIO); + return Err(Errno::Io); } let response = sock.response.as_ref().unwrap(); - Bytes::from(response.recv().map_err(|_| __WASI_EIO)?) + Bytes::from(response.recv().map_err(|_| Errno::Io)?) } InodeHttpSocketType::Headers => { if sock.headers.is_none() { - return Err(__WASI_EIO); + return Err(Errno::Io); } let headers = sock.headers.as_ref().unwrap(); - let headers = headers.recv().map_err(|_| __WASI_EIO)?; + let headers = headers.recv().map_err(|_| Errno::Io)?; let headers = format!("{}: {}", headers.0, headers.1); Bytes::from(headers.as_bytes().to_vec()) } _ => { - return Err(__WASI_EIO); + return Err(Errno::Io); } } } @@ -940,9 +921,9 @@ impl InodeSocket { let read = sock.recv().map_err(net_error_into_wasi_err)?; read.data } - InodeSocketKind::PreSocket { .. } => return Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => return Err(Errno::Notconn), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), }; self.read_buffer.replace(data); self.read_addr.take(); @@ -954,7 +935,7 @@ impl InodeSocket { memory: &MemoryView, iov: WasmSlice<__wasi_iovec_t>, addr: WasmPtr<__wasi_addr_port_t, M>, - ) -> Result { + ) -> Result { loop { if let Some(buf) = self.read_buffer.as_mut() { if !buf.is_empty() { @@ -972,16 +953,16 @@ impl InodeSocket { InodeSocketKind::UdpSocket(sock) => { sock.recv_from().map_err(net_error_into_wasi_err)? } - InodeSocketKind::PreSocket { .. } => return Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => return Err(Errno::Notconn), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), }; self.read_buffer.replace(rcv.data); self.read_addr.replace(rcv.addr); } } - pub fn shutdown(&mut self, how: std::net::Shutdown) -> Result<(), __wasi_errno_t> { + pub fn shutdown(&mut self, how: std::net::Shutdown) -> Result<(), Errno> { use std::net::Shutdown; match &mut self.kind { InodeSocketKind::TcpStream(sock) => { @@ -1004,9 +985,9 @@ impl InodeSocket { } }; } - InodeSocketKind::PreSocket { .. } => return Err(__WASI_ENOTCONN), - InodeSocketKind::Closed => return Err(__WASI_EIO), - _ => return Err(__WASI_ENOTSUP), + InodeSocketKind::PreSocket { .. } => return Err(Errno::Notconn), + InodeSocketKind::Closed => return Err(Errno::Io), + _ => return Err(Errno::Notsup), } Ok(()) } @@ -1132,25 +1113,25 @@ impl Drop for InodeSocket { pub(crate) fn read_ip( memory: &MemoryView, ptr: WasmPtr<__wasi_addr_t, M>, -) -> Result { +) -> Result { let addr_ptr = ptr.deref(memory); let addr = addr_ptr.read().map_err(crate::mem_error_to_wasi)?; let o = addr.u.octs; Ok(match addr.tag { - __WASI_ADDRESS_FAMILY_INET4 => IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], o[3])), - __WASI_ADDRESS_FAMILY_INET6 => { + Addressfamily::Inet4 => IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], o[3])), + Addressfamily::Inet6 => { let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(o) }; IpAddr::V6(Ipv6Addr::new(a, b, c, d, e, f, g, h)) } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }) } pub(crate) fn read_ip_v4( memory: &MemoryView, ptr: WasmPtr<__wasi_addr_ip4_t, M>, -) -> Result { +) -> Result { let addr_ptr = ptr.deref(memory); let addr = addr_ptr.read().map_err(crate::mem_error_to_wasi)?; @@ -1161,7 +1142,7 @@ pub(crate) fn read_ip_v4( pub(crate) fn read_ip_v6( memory: &MemoryView, ptr: WasmPtr<__wasi_addr_ip6_t, M>, -) -> Result { +) -> Result { let addr_ptr = ptr.deref(memory); let addr = addr_ptr.read().map_err(crate::mem_error_to_wasi)?; @@ -1173,12 +1154,12 @@ pub(crate) fn write_ip( memory: &MemoryView, ptr: WasmPtr<__wasi_addr_t, M>, ip: IpAddr, -) -> Result<(), __wasi_errno_t> { +) -> Result<(), Errno> { let ip = match ip { IpAddr::V4(ip) => { let o = ip.octets(); __wasi_addr_t { - tag: __WASI_ADDRESS_FAMILY_INET4, + tag: Addressfamily::Inet4, u: __wasi_addr_u { octs: [o[0], o[1], o[2], o[3], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], }, @@ -1187,7 +1168,7 @@ pub(crate) fn write_ip( IpAddr::V6(ip) => { let o = ip.octets(); __wasi_addr_t { - tag: __WASI_ADDRESS_FAMILY_INET6, + tag: Addressfamily::Inet6, u: __wasi_addr_u { octs: o }, } } @@ -1202,17 +1183,17 @@ pub(crate) fn write_ip( pub(crate) fn read_cidr( memory: &MemoryView, ptr: WasmPtr<__wasi_cidr_t, M>, -) -> Result { +) -> Result { let addr_ptr = ptr.deref(memory); let addr = addr_ptr.read().map_err(crate::mem_error_to_wasi)?; let o = addr.u.octs; Ok(match addr.tag { - __WASI_ADDRESS_FAMILY_INET4 => IpCidr { + Addressfamily::Inet4 => IpCidr { ip: IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], o[3])), prefix: o[4], }, - __WASI_ADDRESS_FAMILY_INET6 => { + Addressfamily::Inet6 => { let [a, b, c, d, e, f, g, h] = { let o = [ o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], o[11], @@ -1225,7 +1206,7 @@ pub(crate) fn read_cidr( prefix: o[16], } } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }) } @@ -1234,13 +1215,13 @@ pub(crate) fn write_cidr( memory: &MemoryView, ptr: WasmPtr<__wasi_cidr_t, M>, cidr: IpCidr, -) -> Result<(), __wasi_errno_t> { +) -> Result<(), Errno> { let p = cidr.prefix; let cidr = match cidr.ip { IpAddr::V4(ip) => { let o = ip.octets(); __wasi_cidr_t { - tag: __WASI_ADDRESS_FAMILY_INET4, + tag: Addressfamily::Inet4, u: __wasi_cidr_u { octs: [ o[0], o[1], o[2], o[3], p, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -1251,7 +1232,7 @@ pub(crate) fn write_cidr( IpAddr::V6(ip) => { let o = ip.octets(); __wasi_cidr_t { - tag: __WASI_ADDRESS_FAMILY_INET6, + tag: Addressfamily::Inet6, u: __wasi_cidr_u { octs: [ o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], o[11], @@ -1270,17 +1251,17 @@ pub(crate) fn write_cidr( pub(crate) fn read_ip_port( memory: &MemoryView, ptr: WasmPtr<__wasi_addr_port_t, M>, -) -> Result<(IpAddr, u16), __wasi_errno_t> { +) -> Result<(IpAddr, u16), Errno> { let addr_ptr = ptr.deref(memory); let addr = addr_ptr.read().map_err(crate::mem_error_to_wasi)?; let o = addr.u.octs; Ok(match addr.tag { - __WASI_ADDRESS_FAMILY_INET4 => { + Addressfamily::Inet4 => { let port = u16::from_ne_bytes([o[0], o[1]]); (IpAddr::V4(Ipv4Addr::new(o[2], o[3], o[4], o[5])), port) } - __WASI_ADDRESS_FAMILY_INET6 => { + Addressfamily::Inet6 => { let [a, b, c, d, e, f, g, h] = { let o = [ o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], o[11], o[12], o[13], @@ -1293,7 +1274,7 @@ pub(crate) fn read_ip_port( u16::from_ne_bytes([o[0], o[1]]), ) } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }) } @@ -1303,13 +1284,13 @@ pub(crate) fn write_ip_port( ptr: WasmPtr<__wasi_addr_port_t, M>, ip: IpAddr, port: u16, -) -> Result<(), __wasi_errno_t> { +) -> Result<(), Errno> { let p = port.to_be_bytes(); let ipport = match ip { IpAddr::V4(ip) => { let o = ip.octets(); __wasi_addr_port_t { - tag: __WASI_ADDRESS_FAMILY_INET4, + tag: Addressfamily::Inet4, u: __wasi_addr_port_u { octs: [ p[0], p[1], o[0], o[1], o[2], o[3], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -1320,7 +1301,7 @@ pub(crate) fn write_ip_port( IpAddr::V6(ip) => { let o = ip.octets(); __wasi_addr_port_t { - tag: __WASI_ADDRESS_FAMILY_INET6, + tag: Addressfamily::Inet6, u: __wasi_addr_port_u { octs: [ p[0], p[1], o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], @@ -1340,7 +1321,7 @@ pub(crate) fn write_ip_port( pub(crate) fn read_route( memory: &MemoryView, ptr: WasmPtr<__wasi_route_t, M>, -) -> Result { +) -> Result { let route_ptr = ptr.deref(memory); let route = route_ptr.read().map_err(crate::mem_error_to_wasi)?; @@ -1348,11 +1329,11 @@ pub(crate) fn read_route( cidr: { let o = route.cidr.u.octs; match route.cidr.tag { - __WASI_ADDRESS_FAMILY_INET4 => IpCidr { + Addressfamily::Inet4 => IpCidr { ip: IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], o[3])), prefix: o[4], }, - __WASI_ADDRESS_FAMILY_INET6 => { + Addressfamily::Inet6 => { let [a, b, c, d, e, f, g, h] = { let o = [ o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], @@ -1365,29 +1346,29 @@ pub(crate) fn read_route( prefix: o[16], } } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), } }, via_router: { let o = route.via_router.u.octs; match route.via_router.tag { - __WASI_ADDRESS_FAMILY_INET4 => IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], o[3])), - __WASI_ADDRESS_FAMILY_INET6 => { + Addressfamily::Inet4 => IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], o[3])), + Addressfamily::Inet6 => { let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(o) }; IpAddr::V6(Ipv6Addr::new(a, b, c, d, e, f, g, h)) } - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), } }, preferred_until: match route.preferred_until.tag { __WASI_OPTION_NONE => None, __WASI_OPTION_SOME => Some(Duration::from_nanos(route.preferred_until.u)), - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, expires_at: match route.expires_at.tag { __WASI_OPTION_NONE => None, __WASI_OPTION_SOME => Some(Duration::from_nanos(route.expires_at.u)), - _ => return Err(__WASI_EINVAL), + _ => return Err(Errno::Inval), }, }) } @@ -1396,14 +1377,14 @@ pub(crate) fn write_route( memory: &MemoryView, ptr: WasmPtr<__wasi_route_t, M>, route: IpRoute, -) -> Result<(), __wasi_errno_t> { +) -> Result<(), Errno> { let cidr = { let p = route.cidr.prefix; match route.cidr.ip { IpAddr::V4(ip) => { let o = ip.octets(); __wasi_cidr_t { - tag: __WASI_ADDRESS_FAMILY_INET4, + tag: Addressfamily::Inet4, u: __wasi_cidr_u { octs: [ o[0], o[1], o[2], o[3], p, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -1414,7 +1395,7 @@ pub(crate) fn write_route( IpAddr::V6(ip) => { let o = ip.octets(); __wasi_cidr_t { - tag: __WASI_ADDRESS_FAMILY_INET6, + tag: Addressfamily::Inet6, u: __wasi_cidr_u { octs: [ o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], @@ -1429,7 +1410,7 @@ pub(crate) fn write_route( IpAddr::V4(ip) => { let o = ip.octets(); __wasi_addr_t { - tag: __WASI_ADDRESS_FAMILY_INET4, + tag: Addressfamily::Inet4, u: __wasi_addr_u { octs: [o[0], o[1], o[2], o[3], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], }, @@ -1438,7 +1419,7 @@ pub(crate) fn write_route( IpAddr::V6(ip) => { let o = ip.octets(); __wasi_addr_t { - tag: __WASI_ADDRESS_FAMILY_INET6, + tag: Addressfamily::Inet6, u: __wasi_addr_u { octs: o }, } } @@ -1475,22 +1456,3 @@ pub(crate) fn write_route( route_ptr.write(route).map_err(crate::mem_error_to_wasi)?; Ok(()) } - -pub(crate) fn all_socket_rights() -> __wasi_rights_t { - __WASI_RIGHT_FD_FDSTAT_SET_FLAGS - | __WASI_RIGHT_FD_FILESTAT_GET - | __WASI_RIGHT_FD_READ - | __WASI_RIGHT_FD_WRITE - | __WASI_RIGHT_POLL_FD_READWRITE - | __WASI_RIGHT_SOCK_SHUTDOWN - | __WASI_RIGHT_SOCK_CONNECT - | __WASI_RIGHT_SOCK_LISTEN - | __WASI_RIGHT_SOCK_BIND - | __WASI_RIGHT_SOCK_ACCEPT - | __WASI_RIGHT_SOCK_RECV - | __WASI_RIGHT_SOCK_SEND - | __WASI_RIGHT_SOCK_ADDR_LOCAL - | __WASI_RIGHT_SOCK_ADDR_REMOTE - | __WASI_RIGHT_SOCK_RECV_FROM - | __WASI_RIGHT_SOCK_SEND_TO -} diff --git a/lib/wasi/src/state/types.rs b/lib/wasi/src/state/types.rs index 462a008f19f..5b6f655bc85 100644 --- a/lib/wasi/src/state/types.rs +++ b/lib/wasi/src/state/types.rs @@ -1,5 +1,4 @@ /// types for use in the WASI filesystem -use crate::syscalls::types::*; #[cfg(feature = "enable-serde")] use serde::{Deserialize, Serialize}; #[cfg(all(unix, feature = "sys-poll"))] @@ -11,6 +10,7 @@ use std::{ time::Duration, }; use wasmer_vbus::BusError; +use wasmer_wasi_types_generated::wasi::{BusErrno, Errno}; #[cfg(feature = "host-fs")] pub use wasmer_vfs::host_fs::{Stderr, Stdin, Stdout}; @@ -20,135 +20,136 @@ pub use wasmer_vfs::mem_fs::{Stderr, Stdin, Stdout}; use wasmer_vfs::{FsError, VirtualFile}; use wasmer_vnet::NetworkError; -pub fn fs_error_from_wasi_err(err: __wasi_errno_t) -> FsError { +pub fn fs_error_from_wasi_err(err: Errno) -> FsError { match err { - __WASI_EBADF => FsError::InvalidFd, - __WASI_EEXIST => FsError::AlreadyExists, - __WASI_EIO => FsError::IOError, - __WASI_EADDRINUSE => FsError::AddressInUse, - __WASI_EADDRNOTAVAIL => FsError::AddressNotAvailable, - __WASI_EPIPE => FsError::BrokenPipe, - __WASI_ECONNABORTED => FsError::ConnectionAborted, - __WASI_ECONNREFUSED => FsError::ConnectionRefused, - __WASI_ECONNRESET => FsError::ConnectionReset, - __WASI_EINTR => FsError::Interrupted, - __WASI_EINVAL => FsError::InvalidInput, - __WASI_ENOTCONN => FsError::NotConnected, - __WASI_ENODEV => FsError::NoDevice, - __WASI_ENOENT => FsError::EntityNotFound, - __WASI_EPERM => FsError::PermissionDenied, - __WASI_ETIMEDOUT => FsError::TimedOut, - __WASI_EPROTO => FsError::UnexpectedEof, - __WASI_EAGAIN => FsError::WouldBlock, - __WASI_ENOSPC => FsError::WriteZero, - __WASI_ENOTEMPTY => FsError::DirectoryNotEmpty, + Errno::Badf => FsError::InvalidFd, + Errno::Exist => FsError::AlreadyExists, + Errno::Io => FsError::IOError, + Errno::Addrinuse => FsError::AddressInUse, + Errno::Addrnotavail => FsError::AddressNotAvailable, + Errno::Pipe => FsError::BrokenPipe, + Errno::Connaborted => FsError::ConnectionAborted, + Errno::Connrefused => FsError::ConnectionRefused, + Errno::Connreset => FsError::ConnectionReset, + Errno::Intr => FsError::Interrupted, + Errno::Inval => FsError::InvalidInput, + Errno::Notconn => FsError::NotConnected, + Errno::Nodev => FsError::NoDevice, + Errno::Noent => FsError::EntityNotFound, + Errno::Perm => FsError::PermissionDenied, + Errno::Timedout => FsError::TimedOut, + Errno::Proto => FsError::UnexpectedEof, + Errno::Again => FsError::WouldBlock, + Errno::Nospc => FsError::WriteZero, + Errno::Notempty => FsError::DirectoryNotEmpty, _ => FsError::UnknownError, } } -pub fn fs_error_into_wasi_err(fs_error: FsError) -> __wasi_errno_t { +pub fn fs_error_into_wasi_err(fs_error: FsError) -> Errno { match fs_error { - FsError::AlreadyExists => __WASI_EEXIST, - FsError::AddressInUse => __WASI_EADDRINUSE, - FsError::AddressNotAvailable => __WASI_EADDRNOTAVAIL, - FsError::BaseNotDirectory => __WASI_ENOTDIR, - FsError::BrokenPipe => __WASI_EPIPE, - FsError::ConnectionAborted => __WASI_ECONNABORTED, - FsError::ConnectionRefused => __WASI_ECONNREFUSED, - FsError::ConnectionReset => __WASI_ECONNRESET, - FsError::Interrupted => __WASI_EINTR, - FsError::InvalidData => __WASI_EIO, - FsError::InvalidFd => __WASI_EBADF, - FsError::InvalidInput => __WASI_EINVAL, - FsError::IOError => __WASI_EIO, - FsError::NoDevice => __WASI_ENODEV, - FsError::NotAFile => __WASI_EINVAL, - FsError::NotConnected => __WASI_ENOTCONN, - FsError::EntityNotFound => __WASI_ENOENT, - FsError::PermissionDenied => __WASI_EPERM, - FsError::TimedOut => __WASI_ETIMEDOUT, - FsError::UnexpectedEof => __WASI_EPROTO, - FsError::WouldBlock => __WASI_EAGAIN, - FsError::WriteZero => __WASI_ENOSPC, - FsError::DirectoryNotEmpty => __WASI_ENOTEMPTY, - FsError::Lock | FsError::UnknownError => __WASI_EIO, + FsError::AlreadyExists => Errno::Exist, + FsError::AddressInUse => Errno::Addrinuse, + FsError::AddressNotAvailable => Errno::Addrnotavail, + FsError::BaseNotDirectory => Errno::Notdir, + FsError::BrokenPipe => Errno::Pipe, + FsError::ConnectionAborted => Errno::Connaborted, + FsError::ConnectionRefused => Errno::Connrefused, + FsError::ConnectionReset => Errno::Connreset, + FsError::Interrupted => Errno::Intr, + FsError::InvalidData => Errno::Io, + FsError::InvalidFd => Errno::Badf, + FsError::InvalidInput => Errno::Inval, + FsError::IOError => Errno::Io, + FsError::NoDevice => Errno::Nodev, + FsError::NotAFile => Errno::Inval, + FsError::NotConnected => Errno::Notconn, + FsError::EntityNotFound => Errno::Noent, + FsError::PermissionDenied => Errno::Perm, + FsError::TimedOut => Errno::Timedout, + FsError::UnexpectedEof => Errno::Proto, + FsError::WouldBlock => Errno::Again, + FsError::WriteZero => Errno::Nospc, + FsError::DirectoryNotEmpty => Errno::Notempty, + FsError::Lock | FsError::UnknownError => Errno::Io, } } -pub fn net_error_into_wasi_err(net_error: NetworkError) -> __wasi_errno_t { +pub fn net_error_into_wasi_err(net_error: NetworkError) -> Errno { match net_error { - NetworkError::InvalidFd => __WASI_EBADF, - NetworkError::AlreadyExists => __WASI_EEXIST, - NetworkError::Lock => __WASI_EIO, - NetworkError::IOError => __WASI_EIO, - NetworkError::AddressInUse => __WASI_EADDRINUSE, - NetworkError::AddressNotAvailable => __WASI_EADDRNOTAVAIL, - NetworkError::BrokenPipe => __WASI_EPIPE, - NetworkError::ConnectionAborted => __WASI_ECONNABORTED, - NetworkError::ConnectionRefused => __WASI_ECONNREFUSED, - NetworkError::ConnectionReset => __WASI_ECONNRESET, - NetworkError::Interrupted => __WASI_EINTR, - NetworkError::InvalidData => __WASI_EIO, - NetworkError::InvalidInput => __WASI_EINVAL, - NetworkError::NotConnected => __WASI_ENOTCONN, - NetworkError::NoDevice => __WASI_ENODEV, - NetworkError::PermissionDenied => __WASI_EPERM, - NetworkError::TimedOut => __WASI_ETIMEDOUT, - NetworkError::UnexpectedEof => __WASI_EPROTO, - NetworkError::WouldBlock => __WASI_EAGAIN, - NetworkError::WriteZero => __WASI_ENOSPC, - NetworkError::Unsupported => __WASI_ENOTSUP, - NetworkError::UnknownError => __WASI_EIO, + NetworkError::InvalidFd => Errno::Badf, + NetworkError::AlreadyExists => Errno::Exist, + NetworkError::Lock => Errno::Io, + NetworkError::IOError => Errno::Io, + NetworkError::AddressInUse => Errno::Addrinuse, + NetworkError::AddressNotAvailable => Errno::Addrnotavail, + NetworkError::BrokenPipe => Errno::Pipe, + NetworkError::ConnectionAborted => Errno::Connaborted, + NetworkError::ConnectionRefused => Errno::Connrefused, + NetworkError::ConnectionReset => Errno::Connreset, + NetworkError::Interrupted => Errno::Intr, + NetworkError::InvalidData => Errno::Io, + NetworkError::InvalidInput => Errno::Inval, + NetworkError::NotConnected => Errno::Notconn, + NetworkError::NoDevice => Errno::Nodev, + NetworkError::PermissionDenied => Errno::Perm, + NetworkError::TimedOut => Errno::Timedout, + NetworkError::UnexpectedEof => Errno::Proto, + NetworkError::WouldBlock => Errno::Again, + NetworkError::WriteZero => Errno::Nospc, + NetworkError::Unsupported => Errno::Notsup, + NetworkError::UnknownError => Errno::Io, } } -pub fn bus_error_into_wasi_err(bus_error: BusError) -> __bus_errno_t { +pub fn bus_error_into_wasi_err(bus_error: BusError) -> BusErrno { use BusError::*; match bus_error { - Serialization => __BUS_ESER, - Deserialization => __BUS_EDES, - InvalidWapm => __BUS_EWAPM, - FetchFailed => __BUS_EFETCH, - CompileError => __BUS_ECOMPILE, - InvalidABI => __BUS_EABI, - Aborted => __BUS_EABORTED, - BadHandle => __BUS_EBADHANDLE, - InvalidTopic => __BUS_ETOPIC, - BadCallback => __BUS_EBADCB, - Unsupported => __BUS_EUNSUPPORTED, - BadRequest => __BUS_EBADREQUEST, - AccessDenied => __BUS_EDENIED, - InternalError => __BUS_EINTERNAL, - MemoryAllocationFailed => __BUS_EALLOC, - InvokeFailed => __BUS_EINVOKE, - AlreadyConsumed => __BUS_ECONSUMED, - MemoryAccessViolation => __BUS_EMEMVIOLATION, - UnknownError => __BUS_EUNKNOWN, + Serialization => BusErrno::Ser, + Deserialization => BusErrno::Des, + InvalidWapm => BusErrno::Wapm, + FetchFailed => BusErrno::Fetch, + CompileError => BusErrno::Compile, + InvalidABI => BusErrno::Abi, + Aborted => BusErrno::Aborted, + BadHandle => BusErrno::Badhandle, + InvalidTopic => BusErrno::Topic, + BadCallback => BusErrno::Badcb, + Unsupported => BusErrno::Unsupported, + BadRequest => BusErrno::Badrequest, + AccessDenied => BusErrno::Denied, + InternalError => BusErrno::Internal, + MemoryAllocationFailed => BusErrno::Alloc, + InvokeFailed => BusErrno::Invoke, + AlreadyConsumed => BusErrno::Consumed, + MemoryAccessViolation => BusErrno::Memviolation, + UnknownError => BusErrno::Unknown, } } -pub fn wasi_error_into_bus_err(bus_error: __bus_errno_t) -> BusError { +pub fn wasi_error_into_bus_err(bus_error: BusErrno) -> BusError { use BusError::*; match bus_error { - __BUS_ESER => Serialization, - __BUS_EDES => Deserialization, - __BUS_EWAPM => InvalidWapm, - __BUS_EFETCH => FetchFailed, - __BUS_ECOMPILE => CompileError, - __BUS_EABI => InvalidABI, - __BUS_EABORTED => Aborted, - __BUS_EBADHANDLE => BadHandle, - __BUS_ETOPIC => InvalidTopic, - __BUS_EBADCB => BadCallback, - __BUS_EUNSUPPORTED => Unsupported, - __BUS_EBADREQUEST => BadRequest, - __BUS_EDENIED => AccessDenied, - __BUS_EINTERNAL => InternalError, - __BUS_EALLOC => MemoryAllocationFailed, - __BUS_EINVOKE => InvokeFailed, - __BUS_ECONSUMED => AlreadyConsumed, - __BUS_EMEMVIOLATION => MemoryAccessViolation, - /*__BUS_EUNKNOWN |*/ _ => UnknownError, + BusErrno::Success => UnknownError, + BusErrno::Ser => Serialization, + BusErrno::Des => Deserialization, + BusErrno::Wapm => InvalidWapm, + BusErrno::Fetch => FetchFailed, + BusErrno::Compile => CompileError, + BusErrno::Abi => InvalidABI, + BusErrno::Aborted => Aborted, + BusErrno::Badhandle => BadHandle, + BusErrno::Topic => InvalidTopic, + BusErrno::Badcb => BadCallback, + BusErrno::Unsupported => Unsupported, + BusErrno::Badrequest => BadRequest, + BusErrno::Denied => AccessDenied, + BusErrno::Internal => InternalError, + BusErrno::Alloc => MemoryAllocationFailed, + BusErrno::Invoke => InvokeFailed, + BusErrno::Consumed => AlreadyConsumed, + BusErrno::Memviolation => MemoryAccessViolation, + BusErrno::Unknown => UnknownError, } } @@ -452,8 +453,8 @@ impl VirtualFile for Pipe { /* TODO: Think about using this trait WasiFdBacking: std::fmt::Debug { - fn get_stat(&self) -> &__wasi_filestat_t; - fn get_stat_mut(&mut self) -> &mut __wasi_filestat_t; + fn get_stat(&self) -> &Filestat; + fn get_stat_mut(&mut self) -> &mut Filestat; fn is_preopened(&self) -> bool; fn get_name(&self) -> &str; } diff --git a/lib/wasi/src/syscalls/legacy/snapshot0.rs b/lib/wasi/src/syscalls/legacy/snapshot0.rs index 033abe11e04..d5182db9936 100644 --- a/lib/wasi/src/syscalls/legacy/snapshot0.rs +++ b/lib/wasi/src/syscalls/legacy/snapshot0.rs @@ -1,7 +1,11 @@ use crate::syscalls; -use crate::syscalls::types::{self, snapshot0}; +use crate::syscalls::types; use crate::{mem_error_to_wasi, Memory32, MemorySize, WasiEnv, WasiError, WasiThread}; use wasmer::{AsStoreMut, FunctionEnvMut, WasmPtr}; +use wasmer_wasi_types_generated::wasi::{ + Errno, Event, Fd, Filesize, Filestat, Filetype, Snapshot0Filestat, Snapshot0Subscription, + Snapshot0Whence, Subscription, Whence, +}; /// Wrapper around `syscalls::fd_filestat_get` with extra logic to handle the size /// difference of `wasi_filestat_t` @@ -11,19 +15,20 @@ use wasmer::{AsStoreMut, FunctionEnvMut, WasmPtr}; /// that syscall, then it may break. pub fn fd_filestat_get( mut ctx: FunctionEnvMut, - fd: types::__wasi_fd_t, - buf: WasmPtr, -) -> types::__wasi_errno_t { + fd: Fd, + buf: WasmPtr, +) -> Errno { let env = ctx.data(); let memory = env.memory_view(&ctx); + // TODO: understand what's happening inside this function, then do the correct thing // transmute the WasmPtr into a WasmPtr where T2 > T1, this will read extra memory. // The edge case of this cenv.mausing an OOB is not handled, if the new field is OOB, then the entire // memory access will fail. - let new_buf: WasmPtr = buf.cast(); + let new_buf: WasmPtr = buf.cast(); // Copy the data including the extra data - let new_filestat_setup: types::__wasi_filestat_t = wasi_try_mem!(new_buf.read(&memory)); + let new_filestat_setup: Filestat = wasi_try_mem!(new_buf.read(&memory)); // Set up complete, make the call with the pointer that will write to the // struct and some unrelated memory after the struct. @@ -36,7 +41,7 @@ pub fn fd_filestat_get( // get the values written to memory let new_filestat = wasi_try_mem!(new_buf.deref(&memory).read()); // translate the new struct into the old struct in host memory - let old_stat = snapshot0::__wasi_filestat_t { + let old_stat = Snapshot0Filestat { st_dev: new_filestat.st_dev, st_ino: new_filestat.st_ino, st_filetype: new_filestat.st_filetype, @@ -55,25 +60,27 @@ pub fn fd_filestat_get( // into memory leaving it as it should be wasi_try_mem!(buf.deref(&memory).write(old_stat)); - result + Errno::from(result) } /// Wrapper around `syscalls::path_filestat_get` with extra logic to handle the size /// difference of `wasi_filestat_t` pub fn path_filestat_get( mut ctx: FunctionEnvMut, - fd: types::__wasi_fd_t, + fd: Fd, flags: types::__wasi_lookupflags_t, path: WasmPtr, path_len: u32, - buf: WasmPtr, -) -> types::__wasi_errno_t { + buf: WasmPtr, +) -> Errno { + // TODO: understand what's happening inside this function, then do the correct thing + // see `fd_filestat_get` in this file for an explanation of this strange behavior let env = ctx.data(); let memory = env.memory_view(&ctx); - let new_buf: WasmPtr = buf.cast(); - let new_filestat_setup: types::__wasi_filestat_t = wasi_try_mem!(new_buf.read(&memory)); + let new_buf: WasmPtr = buf.cast(); + let new_filestat_setup: Filestat = wasi_try_mem!(new_buf.read(&memory)); let result = syscalls::path_filestat_get::(ctx.as_mut(), fd, flags, path, path_len, new_buf); @@ -82,7 +89,7 @@ pub fn path_filestat_get( let env = ctx.data(); let memory = env.memory_view(&ctx); let new_filestat = wasi_try_mem!(new_buf.deref(&memory).read()); - let old_stat = snapshot0::__wasi_filestat_t { + let old_stat = Snapshot0Filestat { st_dev: new_filestat.st_dev, st_ino: new_filestat.st_ino, st_filetype: new_filestat.st_filetype, @@ -100,20 +107,18 @@ pub fn path_filestat_get( } /// Wrapper around `syscalls::fd_seek` with extra logic to remap the values -/// of `__wasi_whence_t` +/// of `Whence` pub fn fd_seek( ctx: FunctionEnvMut, - fd: types::__wasi_fd_t, + fd: Fd, offset: types::__wasi_filedelta_t, - whence: snapshot0::__wasi_whence_t, - newoffset: WasmPtr, -) -> Result { + whence: Snapshot0Whence, + newoffset: WasmPtr, +) -> Result { let new_whence = match whence { - snapshot0::__WASI_WHENCE_CUR => types::__WASI_WHENCE_CUR, - snapshot0::__WASI_WHENCE_END => types::__WASI_WHENCE_END, - snapshot0::__WASI_WHENCE_SET => types::__WASI_WHENCE_SET, - // if it's invalid, let the new fd_seek handle it - _ => whence, + Snapshot0Whence::Cur => Whence::Cur, + Snapshot0Whence::End => Whence::End, + Snapshot0Whence::Set => Whence::Set, }; syscalls::fd_seek::(ctx, fd, offset, new_whence, newoffset) } @@ -122,11 +127,12 @@ pub fn fd_seek( /// userdata field back pub fn poll_oneoff( mut ctx: FunctionEnvMut, - in_: WasmPtr, - out_: WasmPtr, + in_: WasmPtr, + out_: WasmPtr, nsubscriptions: u32, nevents: WasmPtr, -) -> Result { +) -> Result { + // TODO: verify that the assumptions in the comment here still applyd // in this case the new type is smaller than the old type, so it all fits into memory, // we just need to readjust and copy it @@ -138,31 +144,14 @@ pub fn poll_oneoff( let in_origs = wasi_try_mem_ok!(in_origs.read_to_vec()); // get a pointer to the smaller new type - let in_new_type_ptr: WasmPtr = in_.cast(); + let in_new_type_ptr: WasmPtr = in_.cast(); for (in_sub_new, orig) in wasi_try_mem_ok!(in_new_type_ptr.slice(&memory, nsubscriptions_offset)) .iter() .zip(in_origs.iter()) { - wasi_try_mem_ok!(in_sub_new.write(types::__wasi_subscription_t { - userdata: orig.userdata, - type_: orig.type_, - u: if orig.type_ == types::__WASI_EVENTTYPE_CLOCK { - types::__wasi_subscription_u { - clock: types::__wasi_subscription_clock_t { - clock_id: unsafe { orig.u.clock.clock_id }, - timeout: unsafe { orig.u.clock.timeout }, - precision: unsafe { orig.u.clock.precision }, - flags: unsafe { orig.u.clock.flags }, - }, - } - } else { - types::__wasi_subscription_u { - fd_readwrite: unsafe { orig.u.fd_readwrite }, - } - }, - })); + wasi_try_mem_ok!(in_sub_new.write(Subscription::from(*orig))); } // make the call diff --git a/lib/wasi/src/syscalls/mod.rs b/lib/wasi/src/syscalls/mod.rs index 903abae2a27..d851da5092f 100644 --- a/lib/wasi/src/syscalls/mod.rs +++ b/lib/wasi/src/syscalls/mod.rs @@ -2,6 +2,7 @@ pub mod types { pub use wasmer_wasi_types::*; + pub use wasmer_wasi_types_generated::wasi; } #[cfg(any( @@ -23,7 +24,16 @@ pub mod wasix32; #[cfg(feature = "wasix")] pub mod wasix64; -use self::types::*; +use self::types::{ + wasi::{ + Addressfamily, Advice, BusErrno, Clockid, Dircookie, Dirent, Errno, Event, EventEnum, + EventFdReadwrite, Eventrwflags, Eventtype, Fd as WasiFd, Fdflags, Fdstat, Filesize, + Filestat, Filetype, Fstflags, Linkcount, Pid, Rights, Snapshot0Clockid, Sockoption, + Sockstatus, Socktype, Streamsecurity, Subscription, SubscriptionEnum, + SubscriptionFsReadwrite, Tid, Timestamp, Tty, Whence, + }, + *, +}; use crate::state::{bus_error_into_wasi_err, wasi_error_into_bus_err, InodeHttpSocketType}; use crate::utils::map_io_err; use crate::WasiBusProcessId; @@ -31,10 +41,10 @@ use crate::{ mem_error_to_wasi, state::{ self, fs_error_into_wasi_err, iterate_poll_events, net_error_into_wasi_err, poll, - virtual_file_type_to_wasi_file_type, Fd, Inode, InodeSocket, InodeSocketKind, InodeVal, - Kind, PollEvent, PollEventBuilder, WasiPipe, WasiState, MAX_SYMLINKS, + virtual_file_type_to_wasi_file_type, Inode, InodeSocket, InodeSocketKind, InodeVal, Kind, + PollEvent, PollEventBuilder, WasiPipe, WasiState, MAX_SYMLINKS, }, - WasiEnv, WasiError, WasiThread, WasiThreadId, + Fd, WasiEnv, WasiError, WasiThread, WasiThreadId, }; use bytes::Bytes; use std::borrow::{Borrow, Cow}; @@ -70,13 +80,13 @@ pub use windows::*; #[cfg(any(target_arch = "wasm32"))] pub use wasm32::*; -fn to_offset(offset: usize) -> Result { - let ret: M::Offset = offset.try_into().map_err(|_| __WASI_EINVAL)?; +fn to_offset(offset: usize) -> Result { + let ret: M::Offset = offset.try_into().map_err(|_| Errno::Inval)?; Ok(ret) } -fn from_offset(offset: M::Offset) -> Result { - let ret: usize = offset.try_into().map_err(|_| __WASI_EINVAL)?; +fn from_offset(offset: M::Offset) -> Result { + let ret: usize = offset.try_into().map_err(|_| Errno::Inval)?; Ok(ret) } @@ -84,7 +94,7 @@ fn write_bytes_inner( mut write_loc: T, memory: &MemoryView, iovs_arr_cell: WasmSlice<__wasi_ciovec_t>, -) -> Result { +) -> Result { let mut bytes_written = 0usize; for iov in iovs_arr_cell.iter() { let iov_inner = iov.read().map_err(mem_error_to_wasi)?; @@ -103,7 +113,7 @@ pub(crate) fn write_bytes( mut write_loc: T, memory: &MemoryView, iovs_arr: WasmSlice<__wasi_ciovec_t>, -) -> Result { +) -> Result { let result = write_bytes_inner::<_, M>(&mut write_loc, memory, iovs_arr); write_loc.flush(); result @@ -113,7 +123,7 @@ pub(crate) fn read_bytes( mut reader: T, memory: &MemoryView, iovs_arr: WasmSlice<__wasi_iovec_t>, -) -> Result { +) -> Result { let mut bytes_read = 0usize; // We allocate the raw_bytes first once instead of @@ -139,27 +149,22 @@ pub(crate) fn read_bytes( Ok(bytes_read) } -/// checks that `rights_check_set` is a subset of `rights_set` -fn has_rights(rights_set: __wasi_rights_t, rights_check_set: __wasi_rights_t) -> bool { - rights_set | rights_check_set == rights_set -} - fn __sock_actor( ctx: &FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - rights: __wasi_rights_t, + sock: WasiFd, + rights: Rights, actor: F, -) -> Result +) -> Result where - F: FnOnce(&crate::state::InodeSocket) -> Result, + F: FnOnce(&crate::state::InodeSocket) -> Result, { let env = ctx.data(); let (_, state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = state.fs.get_fd(sock)?; let ret = { - if rights != 0 && !has_rights(fd_entry.rights, rights) { - return Err(__WASI_EACCES); + if !rights.is_empty() && !fd_entry.rights.contains(rights) { + return Err(Errno::Access); } let inode_idx = fd_entry.inode; @@ -170,7 +175,7 @@ where match deref { Kind::Socket { socket } => actor(socket)?, _ => { - return Err(__WASI_ENOTSOCK); + return Err(Errno::Notsock); } } }; @@ -180,20 +185,20 @@ where fn __sock_actor_mut( ctx: &FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - rights: __wasi_rights_t, + sock: WasiFd, + rights: Rights, actor: F, -) -> Result +) -> Result where - F: FnOnce(&mut crate::state::InodeSocket) -> Result, + F: FnOnce(&mut crate::state::InodeSocket) -> Result, { let env = ctx.data(); let (_, state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = state.fs.get_fd(sock)?; let ret = { - if rights != 0 && !has_rights(fd_entry.rights, rights) { - return Err(__WASI_EACCES); + if !rights.is_empty() && !fd_entry.rights.contains(rights) { + return Err(Errno::Access); } let inode_idx = fd_entry.inode; @@ -204,7 +209,7 @@ where match deref_mut { Kind::Socket { socket } => actor(socket)?, _ => { - return Err(__WASI_ENOTSOCK); + return Err(Errno::Notsock); } } }; @@ -214,21 +219,19 @@ where fn __sock_upgrade( ctx: &FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - rights: __wasi_rights_t, + sock: WasiFd, + rights: Rights, actor: F, -) -> Result<(), __wasi_errno_t> +) -> Result<(), Errno> where - F: FnOnce( - &mut crate::state::InodeSocket, - ) -> Result, __wasi_errno_t>, + F: FnOnce(&mut crate::state::InodeSocket) -> Result, Errno>, { let env = ctx.data(); let (_, state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = state.fs.get_fd(sock)?; - if rights != 0 && !has_rights(fd_entry.rights, rights) { - return Err(__WASI_EACCES); + if !rights.is_empty() && !fd_entry.rights.contains(rights) { + return Err(Errno::Access); } let inode_idx = fd_entry.inode; @@ -245,7 +248,7 @@ where } } _ => { - return Err(__WASI_ENOTSOCK); + return Err(Errno::Notsock); } } @@ -258,7 +261,7 @@ fn write_buffer_array( from: &[Vec], ptr_buffer: WasmPtr, M>, buffer: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { let ptrs = wasi_try_mem!(ptr_buffer.slice(memory, wasi_try!(to_offset::(from.len())))); let mut current_buffer_offset = 0usize; @@ -280,15 +283,15 @@ fn write_buffer_array( current_buffer_offset += sub_buffer.len() + 1; } - __WASI_ESUCCESS + Errno::Success } -fn get_current_time_in_nanos() -> Result<__wasi_timestamp_t, __wasi_errno_t> { +fn get_current_time_in_nanos() -> Result { let now = std::time::SystemTime::now(); let duration = now .duration_since(std::time::SystemTime::UNIX_EPOCH) - .map_err(|_| __WASI_EIO)?; - Ok(duration.as_nanos() as __wasi_timestamp_t) + .map_err(|_| Errno::Io)?; + Ok(duration.as_nanos() as Timestamp) } /// ### `args_get()` @@ -304,7 +307,7 @@ pub fn args_get( mut ctx: FunctionEnvMut<'_, WasiEnv>, argv: WasmPtr, M>, argv_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::args_get"); let env = ctx.data(); let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0); @@ -336,7 +339,7 @@ pub fn args_sizes_get( mut ctx: FunctionEnvMut<'_, WasiEnv>, argc: WasmPtr, argv_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::args_sizes_get"); let env = ctx.data(); let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0); @@ -344,68 +347,74 @@ pub fn args_sizes_get( let argc = argc.deref(&memory); let argv_buf_size = argv_buf_size.deref(&memory); - let argc_val: M::Offset = wasi_try!(state.args.len().try_into().map_err(|_| __WASI_EOVERFLOW)); + let argc_val: M::Offset = wasi_try!(state.args.len().try_into().map_err(|_| Errno::Overflow)); let argv_buf_size_val: usize = state.args.iter().map(|v| v.len() + 1).sum(); let argv_buf_size_val: M::Offset = - wasi_try!(argv_buf_size_val.try_into().map_err(|_| __WASI_EOVERFLOW)); + wasi_try!(argv_buf_size_val.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem!(argc.write(argc_val)); wasi_try_mem!(argv_buf_size.write(argv_buf_size_val)); debug!("=> argc={}, argv_buf_size={}", argc_val, argv_buf_size_val); - __WASI_ESUCCESS + Errno::Success } /// ### `clock_res_get()` /// Get the resolution of the specified clock /// Input: -/// - `__wasi_clockid_t clock_id` +/// - `Clockid clock_id` /// The ID of the clock to get the resolution of /// Output: -/// - `__wasi_timestamp_t *resolution` +/// - `Timestamp *resolution` /// The resolution of the clock in nanoseconds pub fn clock_res_get( mut ctx: FunctionEnvMut<'_, WasiEnv>, - clock_id: __wasi_clockid_t, - resolution: WasmPtr<__wasi_timestamp_t, M>, -) -> __wasi_errno_t { + clock_id: Clockid, + resolution: WasmPtr, +) -> Errno { trace!("wasi::clock_res_get"); let env = ctx.data(); let memory = env.memory_view(&ctx); let out_addr = resolution.deref(&memory); - let t_out = wasi_try!(platform_clock_res_get(clock_id, out_addr)); - wasi_try_mem!(resolution.write(&memory, t_out as __wasi_timestamp_t)); - __WASI_ESUCCESS + let t_out = wasi_try!(platform_clock_res_get( + Snapshot0Clockid::from(clock_id), + out_addr + )); + wasi_try_mem!(resolution.write(&memory, t_out as Timestamp)); + Errno::Success } /// ### `clock_time_get()` /// Get the time of the specified clock /// Inputs: -/// - `__wasi_clockid_t clock_id` +/// - `Clockid clock_id` /// The ID of the clock to query -/// - `__wasi_timestamp_t precision` +/// - `Timestamp precision` /// The maximum amount of error the reading may have /// Output: -/// - `__wasi_timestamp_t *time` +/// - `Timestamp *time` /// The value of the clock in nanoseconds pub fn clock_time_get( ctx: FunctionEnvMut<'_, WasiEnv>, - clock_id: __wasi_clockid_t, - precision: __wasi_timestamp_t, - time: WasmPtr<__wasi_timestamp_t, M>, -) -> __wasi_errno_t { + clock_id: Clockid, + precision: Timestamp, + time: WasmPtr, +) -> Errno { debug!( "wasi::clock_time_get clock_id: {}, precision: {}", - clock_id, precision + clock_id as u8, precision ); let env = ctx.data(); let memory = env.memory_view(&ctx); - let t_out = wasi_try!(platform_clock_time_get(clock_id, precision)); - wasi_try_mem!(time.write(&memory, t_out as __wasi_timestamp_t)); + let t_out = wasi_try!(platform_clock_time_get( + Snapshot0Clockid::from(clock_id), + precision + )); + wasi_try_mem!(time.write(&memory, t_out as Timestamp)); - let result = __WASI_ESUCCESS; + let result = Errno::Success; trace!( "time: {} => {}", wasi_try_mem!(time.deref(&memory).read()), @@ -426,7 +435,7 @@ pub fn environ_get( ctx: FunctionEnvMut<'_, WasiEnv>, environ: WasmPtr, M>, environ_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!( "wasi::environ_get. Environ: {:?}, environ_buf: {:?}", environ, environ_buf @@ -449,7 +458,7 @@ pub fn environ_sizes_get( ctx: FunctionEnvMut<'_, WasiEnv>, environ_count: WasmPtr, environ_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { trace!("wasi::environ_sizes_get"); let env = ctx.data(); let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0); @@ -458,9 +467,9 @@ pub fn environ_sizes_get( let environ_buf_size = environ_buf_size.deref(&memory); let env_var_count: M::Offset = - wasi_try!(state.envs.len().try_into().map_err(|_| __WASI_EOVERFLOW)); + wasi_try!(state.envs.len().try_into().map_err(|_| Errno::Overflow)); let env_buf_size: usize = state.envs.iter().map(|v| v.len() + 1).sum(); - let env_buf_size: M::Offset = wasi_try!(env_buf_size.try_into().map_err(|_| __WASI_EOVERFLOW)); + let env_buf_size: M::Offset = wasi_try!(env_buf_size.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem!(environ_count.write(env_var_count)); wasi_try_mem!(environ_buf_size.write(env_buf_size)); @@ -470,59 +479,59 @@ pub fn environ_sizes_get( env_buf_size ); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_advise()` /// Advise the system about how a file will be used /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor the advice applies to -/// - `__wasi_filesize_t offset` +/// - `Filesize offset` /// The offset from which the advice applies -/// - `__wasi_filesize_t len` +/// - `Filesize len` /// The length from the offset to which the advice applies /// - `__wasi_advice_t advice` /// The advice to give pub fn fd_advise( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, - advice: __wasi_advice_t, -) -> __wasi_errno_t { + fd: WasiFd, + offset: Filesize, + len: Filesize, + advice: Advice, +) -> Errno { debug!("wasi::fd_advise: fd={}", fd); // this is used for our own benefit, so just returning success is a valid // implementation for now - __WASI_ESUCCESS + Errno::Success } /// ### `fd_allocate` /// Allocate extra space for a file descriptor /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor to allocate for -/// - `__wasi_filesize_t offset` +/// - `Filesize offset` /// The offset from the start marking the beginning of the allocation -/// - `__wasi_filesize_t len` +/// - `Filesize len` /// The length from the offset marking the end of the allocation pub fn fd_allocate( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: WasiFd, + offset: Filesize, + len: Filesize, +) -> Errno { debug!("wasi::fd_allocate"); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = wasi_try!(state.fs.get_fd(fd)); let inode = fd_entry.inode; - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_ALLOCATE) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_ALLOCATE) { + return Errno::Access; } - let new_size = wasi_try!(offset.checked_add(len).ok_or(__WASI_EINVAL)); + let new_size = wasi_try!(offset.checked_add(len).ok_or(Errno::Inval)); { let mut guard = inodes.arena[inode].write(); let deref_mut = guard.deref_mut(); @@ -531,36 +540,36 @@ pub fn fd_allocate( if let Some(handle) = handle { wasi_try!(handle.set_len(new_size).map_err(fs_error_into_wasi_err)); } else { - return __WASI_EBADF; + return Errno::Badf; } } - Kind::Socket { .. } => return __WASI_EBADF, - Kind::Pipe { .. } => return __WASI_EBADF, + Kind::Socket { .. } => return Errno::Badf, + Kind::Pipe { .. } => return Errno::Badf, Kind::Buffer { buffer } => { buffer.resize(new_size as usize, 0); } - Kind::Symlink { .. } => return __WASI_EBADF, - Kind::EventNotifications { .. } => return __WASI_EBADF, - Kind::Dir { .. } | Kind::Root { .. } => return __WASI_EISDIR, + Kind::Symlink { .. } => return Errno::Badf, + Kind::EventNotifications { .. } => return Errno::Badf, + Kind::Dir { .. } | Kind::Root { .. } => return Errno::Isdir, } } inodes.arena[inode].stat.write().unwrap().st_size = new_size; debug!("New file size: {}", new_size); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_close()` /// Close an open file descriptor /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// A file descriptor mapping to an open file to close /// Errors: -/// - `__WASI_EISDIR` +/// - `Errno::Isdir` /// If `fd` is a directory -/// - `__WASI_EBADF` +/// - `Errno::Badf` /// If `fd` is invalid or not open -pub fn fd_close(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub fn fd_close(ctx: FunctionEnvMut<'_, WasiEnv>, fd: WasiFd) -> Errno { debug!("wasi::fd_close: fd={}", fd); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); @@ -569,43 +578,43 @@ pub fn fd_close(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_err wasi_try!(state.fs.close_fd(inodes.deref(), fd)); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_datasync()` /// Synchronize the file data to disk /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor to sync -pub fn fd_datasync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +pub fn fd_datasync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: WasiFd) -> Errno { debug!("wasi::fd_datasync"); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = wasi_try!(state.fs.get_fd(fd)); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_DATASYNC) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_DATASYNC) { + return Errno::Access; } if let Err(e) = state.fs.flush(inodes.deref(), fd) { e } else { - __WASI_ESUCCESS + Errno::Success } } /// ### `fd_fdstat_get()` /// Get metadata of a file descriptor /// Input: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor whose metadata will be accessed /// Output: -/// - `__wasi_fdstat_t *buf` +/// - `Fdstat *buf` /// The location where the metadata will be written pub fn fd_fdstat_get( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - buf_ptr: WasmPtr<__wasi_fdstat_t, M>, -) -> __wasi_errno_t { + fd: WasiFd, + buf_ptr: WasmPtr, +) -> Errno { debug!( "wasi::fd_fdstat_get: fd={}, buf_ptr={}", fd, @@ -619,88 +628,84 @@ pub fn fd_fdstat_get( wasi_try_mem!(buf.write(stat)); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_fdstat_set_flags()` /// Set file descriptor flags for a file descriptor /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor to apply the new flags to -/// - `__wasi_fdflags_t flags` +/// - `Fdflags flags` /// The flags to apply to `fd` -pub fn fd_fdstat_set_flags( - ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - flags: __wasi_fdflags_t, -) -> __wasi_errno_t { +pub fn fd_fdstat_set_flags(ctx: FunctionEnvMut<'_, WasiEnv>, fd: WasiFd, flags: Fdflags) -> Errno { debug!("wasi::fd_fdstat_set_flags"); let env = ctx.data(); let (_, mut state) = env.get_memory_and_wasi_state(&ctx, 0); let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try!(fd_map.get_mut(&fd).ok_or(Errno::Badf)); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FDSTAT_SET_FLAGS) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_FDSTAT_SET_FLAGS) { + return Errno::Access; } fd_entry.flags = flags; - __WASI_ESUCCESS + Errno::Success } /// ### `fd_fdstat_set_rights()` /// Set the rights of a file descriptor. This can only be used to remove rights /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor to apply the new rights to -/// - `__wasi_rights_t fs_rights_base` +/// - `Rights fs_rights_base` /// The rights to apply to `fd` -/// - `__wasi_rights_t fs_rights_inheriting` +/// - `Rights fs_rights_inheriting` /// The inheriting rights to apply to `fd` pub fn fd_fdstat_set_rights( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - fs_rights_base: __wasi_rights_t, - fs_rights_inheriting: __wasi_rights_t, -) -> __wasi_errno_t { + fd: WasiFd, + fs_rights_base: Rights, + fs_rights_inheriting: Rights, +) -> Errno { debug!("wasi::fd_fdstat_set_rights"); let env = ctx.data(); let (_, mut state) = env.get_memory_and_wasi_state(&ctx, 0); let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try!(fd_map.get_mut(&fd).ok_or(Errno::Badf)); // ensure new rights are a subset of current rights if fd_entry.rights | fs_rights_base != fd_entry.rights || fd_entry.rights_inheriting | fs_rights_inheriting != fd_entry.rights_inheriting { - return __WASI_ENOTCAPABLE; + return Errno::Notcapable; } fd_entry.rights = fs_rights_base; fd_entry.rights_inheriting = fs_rights_inheriting; - __WASI_ESUCCESS + Errno::Success } /// ### `fd_filestat_get()` /// Get the metadata of an open file /// Input: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The open file descriptor whose metadata will be read /// Output: -/// - `__wasi_filestat_t *buf` +/// - `Filestat *buf` /// Where the metadata from `fd` will be written pub fn fd_filestat_get( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - buf: WasmPtr<__wasi_filestat_t, M>, -) -> __wasi_errno_t { + fd: WasiFd, + buf: WasmPtr, +) -> Errno { debug!("wasi::fd_filestat_get"); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = wasi_try!(state.fs.get_fd(fd)); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FILESTAT_GET) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_FILESTAT_GET) { + return Errno::Access; } let stat = wasi_try!(state.fs.filestat_fd(inodes.deref(), fd)); @@ -708,29 +713,29 @@ pub fn fd_filestat_get( let buf = buf.deref(&memory); wasi_try_mem!(buf.write(stat)); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_filestat_set_size()` /// Change the size of an open file, zeroing out any new bytes /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// File descriptor to adjust -/// - `__wasi_filesize_t st_size` +/// - `Filesize st_size` /// New size that `fd` will be set to pub fn fd_filestat_set_size( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - st_size: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: WasiFd, + st_size: Filesize, +) -> Errno { debug!("wasi::fd_filestat_set_size"); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = wasi_try!(state.fs.get_fd(fd)); let inode = fd_entry.inode; - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FILESTAT_SET_SIZE) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_FILESTAT_SET_SIZE) { + return Errno::Access; } { @@ -741,61 +746,60 @@ pub fn fd_filestat_set_size( if let Some(handle) = handle { wasi_try!(handle.set_len(st_size).map_err(fs_error_into_wasi_err)); } else { - return __WASI_EBADF; + return Errno::Badf; } } Kind::Buffer { buffer } => { buffer.resize(st_size as usize, 0); } - Kind::Socket { .. } => return __WASI_EBADF, - Kind::Pipe { .. } => return __WASI_EBADF, - Kind::Symlink { .. } => return __WASI_EBADF, - Kind::EventNotifications { .. } => return __WASI_EBADF, - Kind::Dir { .. } | Kind::Root { .. } => return __WASI_EISDIR, + Kind::Socket { .. } => return Errno::Badf, + Kind::Pipe { .. } => return Errno::Badf, + Kind::Symlink { .. } => return Errno::Badf, + Kind::EventNotifications { .. } => return Errno::Badf, + Kind::Dir { .. } | Kind::Root { .. } => return Errno::Isdir, } } inodes.arena[inode].stat.write().unwrap().st_size = st_size; - __WASI_ESUCCESS + Errno::Success } /// ### `fd_filestat_set_times()` /// Set timestamp metadata on a file /// Inputs: -/// - `__wasi_timestamp_t st_atim` +/// - `Timestamp st_atim` /// Last accessed time -/// - `__wasi_timestamp_t st_mtim` +/// - `Timestamp st_mtim` /// Last modified time -/// - `__wasi_fstflags_t fst_flags` +/// - `Fstflags fst_flags` /// Bit-vector for controlling which times get set pub fn fd_filestat_set_times( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + fd: WasiFd, + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { debug!("wasi::fd_filestat_set_times"); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = wasi_try!(state.fs.get_fd(fd)); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_FILESTAT_SET_TIMES) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_FILESTAT_SET_TIMES) { + return Errno::Access; } - if (fst_flags & __WASI_FILESTAT_SET_ATIM != 0 && fst_flags & __WASI_FILESTAT_SET_ATIM_NOW != 0) - || (fst_flags & __WASI_FILESTAT_SET_MTIM != 0 - && fst_flags & __WASI_FILESTAT_SET_MTIM_NOW != 0) + if (fst_flags.contains(Fstflags::SET_ATIM) && fst_flags.contains(Fstflags::SET_ATIM_NOW)) + || (fst_flags.contains(Fstflags::SET_MTIM) && fst_flags.contains(Fstflags::SET_MTIM_NOW)) { - return __WASI_EINVAL; + return Errno::Inval; } let inode_idx = fd_entry.inode; let inode = &inodes.arena[inode_idx]; - if fst_flags & __WASI_FILESTAT_SET_ATIM != 0 || fst_flags & __WASI_FILESTAT_SET_ATIM_NOW != 0 { - let time_to_set = if fst_flags & __WASI_FILESTAT_SET_ATIM != 0 { + if fst_flags.contains(Fstflags::SET_ATIM) || fst_flags.contains(Fstflags::SET_ATIM_NOW) { + let time_to_set = if fst_flags.contains(Fstflags::SET_ATIM) { st_atim } else { wasi_try!(get_current_time_in_nanos()) @@ -803,8 +807,8 @@ pub fn fd_filestat_set_times( inode.stat.write().unwrap().st_atim = time_to_set; } - if fst_flags & __WASI_FILESTAT_SET_MTIM != 0 || fst_flags & __WASI_FILESTAT_SET_MTIM_NOW != 0 { - let time_to_set = if fst_flags & __WASI_FILESTAT_SET_MTIM != 0 { + if fst_flags.contains(Fstflags::SET_MTIM) || fst_flags.contains(Fstflags::SET_MTIM_NOW) { + let time_to_set = if fst_flags.contains(Fstflags::SET_MTIM) { st_mtim } else { wasi_try!(get_current_time_in_nanos()) @@ -812,32 +816,32 @@ pub fn fd_filestat_set_times( inode.stat.write().unwrap().st_mtim = time_to_set; } - __WASI_ESUCCESS + Errno::Success } /// ### `fd_pread()` /// Read from the file at the given offset without updating the file cursor. /// This acts like a stateless version of Seek + Read /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor to read the data with /// - `const __wasi_iovec_t* iovs' /// Vectors where the data will be stored /// - `size_t iovs_len` /// The number of vectors to store the data into -/// - `__wasi_filesize_t offset` +/// - `Filesize offset` /// The file cursor to use: the starting position from which data will be read /// Output: /// - `size_t nread` /// The number of bytes read pub fn fd_pread( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_iovec_t, M>, iovs_len: M::Offset, - offset: __wasi_filesize_t, + offset: Filesize, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { trace!("wasi::fd_pread: fd={}, offset={}", fd, offset); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); @@ -857,22 +861,20 @@ pub fn fd_pread( if let Some(ref mut stdin) = guard.deref_mut() { wasi_try_ok!(read_bytes(stdin, &memory, iovs), env) } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } - __WASI_STDOUT_FILENO => return Ok(__WASI_EINVAL), - __WASI_STDERR_FILENO => return Ok(__WASI_EINVAL), + __WASI_STDOUT_FILENO => return Ok(Errno::Inval), + __WASI_STDERR_FILENO => return Ok(Errno::Inval), _ => { let inode = fd_entry.inode; - if !(has_rights(fd_entry.rights, __WASI_RIGHT_FD_READ) - && has_rights(fd_entry.rights, __WASI_RIGHT_FD_SEEK)) - { + if !fd_entry.rights.contains(Rights::FD_READ | Rights::FD_SEEK) { debug!( "Invalid rights on {:X}: expected READ and SEEK", fd_entry.rights ); - return Ok(__WASI_EACCES); + return Ok(Errno::Access); } let mut guard = inodes.arena[inode].write(); let deref_mut = guard.deref_mut(); @@ -886,7 +888,7 @@ pub fn fd_pread( ); wasi_try_ok!(read_bytes(h, &memory, iovs), env) } else { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } } Kind::Socket { socket } => { @@ -895,8 +897,8 @@ pub fn fd_pread( Kind::Pipe { pipe } => { wasi_try_ok!(pipe.recv(&memory, iovs), env) } - Kind::EventNotifications { .. } => return Ok(__WASI_EINVAL), - Kind::Dir { .. } | Kind::Root { .. } => return Ok(__WASI_EISDIR), + Kind::EventNotifications { .. } => return Ok(Errno::Inval), + Kind::Dir { .. } | Kind::Root { .. } => return Ok(Errno::Isdir), Kind::Symlink { .. } => unimplemented!("Symlinks in wasi::fd_pread"), Kind::Buffer { buffer } => { wasi_try_ok!(read_bytes(&buffer[(offset as usize)..], &memory, iovs), env) @@ -905,25 +907,25 @@ pub fn fd_pread( } }; - let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| __WASI_EOVERFLOW)); + let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(nread_ref.write(bytes_read)); debug!("Success: {} bytes read", bytes_read); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `fd_prestat_get()` /// Get metadata about a preopened file descriptor /// Input: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The preopened file descriptor to query /// Output: /// - `__wasi_prestat *buf` /// Where the metadata will be written pub fn fd_prestat_get( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, buf: WasmPtr<__wasi_prestat_t, M>, -) -> __wasi_errno_t { +) -> Errno { trace!("wasi::fd_prestat_get: fd={}", fd); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); @@ -938,15 +940,15 @@ pub fn fd_prestat_get( ))) ); - __WASI_ESUCCESS + Errno::Success } pub fn fd_prestat_dir_name( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { trace!( "wasi::fd_prestat_dir_name: fd={}, path_len={}", fd, @@ -976,9 +978,9 @@ pub fn fd_prestat_dir_name( trace!("=> result: \"{}\"", inode_val.name); - __WASI_ESUCCESS + Errno::Success } else { - __WASI_EOVERFLOW + Errno::Overflow } } Kind::Symlink { .. } @@ -986,32 +988,32 @@ pub fn fd_prestat_dir_name( | Kind::File { .. } | Kind::Socket { .. } | Kind::Pipe { .. } - | Kind::EventNotifications { .. } => __WASI_ENOTDIR, + | Kind::EventNotifications { .. } => Errno::Notdir, } } /// ### `fd_pwrite()` /// Write to a file without adjusting its offset /// Inputs: -/// - `__wasi_fd_t` +/// - `Fd` /// File descriptor (opened with writing) to write to /// - `const __wasi_ciovec_t *iovs` /// List of vectors to read data from /// - `u32 iovs_len` /// Length of data in `iovs` -/// - `__wasi_filesize_t offset` +/// - `Filesize offset` /// The offset to write at /// Output: /// - `u32 *nwritten` /// Number of bytes written pub fn fd_pwrite( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_ciovec_t, M>, iovs_len: M::Offset, - offset: __wasi_filesize_t, + offset: Filesize, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { trace!("wasi::fd_pwrite"); // TODO: refactor, this is just copied from `fd_write`... let env = ctx.data(); @@ -1021,7 +1023,7 @@ pub fn fd_pwrite( let fd_entry = wasi_try_ok!(state.fs.get_fd(fd)); let bytes_written = match fd { - __WASI_STDIN_FILENO => return Ok(__WASI_EINVAL), + __WASI_STDIN_FILENO => return Ok(Errno::Inval), __WASI_STDOUT_FILENO => { let mut guard = wasi_try_ok!( inodes @@ -1032,7 +1034,7 @@ pub fn fd_pwrite( if let Some(ref mut stdout) = guard.deref_mut() { wasi_try_ok!(write_bytes(stdout, &memory, iovs_arr), env) } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } __WASI_STDERR_FILENO => { @@ -1045,14 +1047,12 @@ pub fn fd_pwrite( if let Some(ref mut stderr) = guard.deref_mut() { wasi_try_ok!(write_bytes(stderr, &memory, iovs_arr), env) } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } _ => { - if !(has_rights(fd_entry.rights, __WASI_RIGHT_FD_WRITE) - && has_rights(fd_entry.rights, __WASI_RIGHT_FD_SEEK)) - { - return Ok(__WASI_EACCES); + if !fd_entry.rights.contains(Rights::FD_WRITE | Rights::FD_SEEK) { + return Ok(Errno::Access); } let inode_idx = fd_entry.inode; @@ -1071,7 +1071,7 @@ pub fn fd_pwrite( ); wasi_try_ok!(write_bytes(handle, &memory, iovs_arr), env) } else { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } } Kind::Socket { socket } => { @@ -1082,9 +1082,9 @@ pub fn fd_pwrite( } Kind::Dir { .. } | Kind::Root { .. } => { // TODO: verify - return Ok(__WASI_EISDIR); + return Ok(Errno::Isdir); } - Kind::EventNotifications { .. } => return Ok(__WASI_EINVAL), + Kind::EventNotifications { .. } => return Ok(Errno::Inval), Kind::Symlink { .. } => unimplemented!("Symlinks in wasi::fd_pwrite"), Kind::Buffer { buffer } => { wasi_try_ok!( @@ -1097,16 +1097,16 @@ pub fn fd_pwrite( }; let bytes_written: M::Offset = - wasi_try_ok!(bytes_written.try_into().map_err(|_| __WASI_EOVERFLOW)); + wasi_try_ok!(bytes_written.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(nwritten_ref.write(bytes_written)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `fd_read()` /// Read data from file descriptor /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// File descriptor from which data will be read /// - `const __wasi_iovec_t *iovs` /// Vectors where data will be stored @@ -1118,11 +1118,11 @@ pub fn fd_pwrite( /// pub fn fd_read( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_iovec_t, M>, iovs_len: M::Offset, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { trace!("wasi::fd_read: fd={}", fd); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); @@ -1142,17 +1142,17 @@ pub fn fd_read( if let Some(ref mut stdin) = guard.deref_mut() { wasi_try_ok!(read_bytes(stdin, &memory, iovs_arr), env) } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } - __WASI_STDOUT_FILENO | __WASI_STDERR_FILENO => return Ok(__WASI_EINVAL), + __WASI_STDOUT_FILENO | __WASI_STDERR_FILENO => return Ok(Errno::Inval), _ => { - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_READ) { + if !fd_entry.rights.contains(Rights::FD_READ) { // TODO: figure out the error to return when lacking rights - return Ok(__WASI_EACCES); + return Ok(Errno::Access); } - let is_non_blocking = fd_entry.flags & __WASI_FDFLAG_NONBLOCK != 0; + let is_non_blocking = fd_entry.flags.contains(Fdflags::NONBLOCK); let offset = fd_entry.offset as usize; let inode_idx = fd_entry.inode; let inode = &inodes.arena[inode_idx]; @@ -1171,7 +1171,7 @@ pub fn fd_read( ); wasi_try_ok!(read_bytes(handle, &memory, iovs_arr), env) } else { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } } Kind::Socket { socket } => { @@ -1182,7 +1182,7 @@ pub fn fd_read( } Kind::Dir { .. } | Kind::Root { .. } => { // TODO: verify - return Ok(__WASI_EISDIR); + return Ok(Errno::Isdir); } Kind::EventNotifications { counter, @@ -1228,7 +1228,7 @@ pub fn fd_read( // If its none blocking then exit if is_non_blocking { - return Ok(__WASI_EAGAIN); + return Ok(Errno::Again); } // Yield for a fixed period of time and then check again @@ -1248,28 +1248,28 @@ pub fn fd_read( // reborrow let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(Errno::Badf)); fd_entry.offset += bytes_read as u64; bytes_read } }; - let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| __WASI_EOVERFLOW)); + let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(nread_ref.write(bytes_read)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `fd_readdir()` /// Read data from directory specified by file descriptor /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// File descriptor from which directory data will be read /// - `void *buf` /// Buffer where directory entries are stored /// - `u32 buf_len` /// Length of data in `buf` -/// - `__wasi_dircookie_t cookie` +/// - `Dircookie cookie` /// Where the directory reading should start from /// Output: /// - `u32 *bufused` @@ -1277,12 +1277,12 @@ pub fn fd_read( /// directory has been read pub fn fd_readdir( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, buf: WasmPtr, buf_len: M::Offset, - cookie: __wasi_dircookie_t, + cookie: Dircookie, bufused: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { trace!("wasi::fd_readdir"); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); @@ -1295,7 +1295,7 @@ pub fn fd_readdir( let mut cur_cookie = cookie; let mut buf_idx = 0usize; - let entries: Vec<(String, u8, u64)> = { + let entries: Vec<(String, Filetype, u64)> = { let guard = inodes.arena[working_dir.inode].read(); let deref = guard.deref(); match deref { @@ -1320,7 +1320,7 @@ pub fn fd_readdir( filename, filetype, 0, // TODO: inode )) }) - .collect::, _>>()); + .collect::, _>>()); entry_vec.extend( entries .iter() @@ -1333,8 +1333,8 @@ pub fn fd_readdir( ); // adding . and .. special folders // TODO: inode - entry_vec.push((".".to_string(), __WASI_FILETYPE_DIRECTORY, 0)); - entry_vec.push(("..".to_string(), __WASI_FILETYPE_DIRECTORY, 0)); + entry_vec.push((".".to_string(), Filetype::Directory, 0)); + entry_vec.push(("..".to_string(), Filetype::Directory, 0)); entry_vec.sort_by(|a, b| a.0.cmp(&b.0)); entry_vec } @@ -1360,7 +1360,7 @@ pub fn fd_readdir( | Kind::Buffer { .. } | Kind::Socket { .. } | Kind::Pipe { .. } - | Kind::EventNotifications { .. } => return __WASI_ENOTDIR, + | Kind::EventNotifications { .. } => return Errno::Notdir, } }; @@ -1368,7 +1368,7 @@ pub fn fd_readdir( cur_cookie += 1; let namlen = entry_path_str.len(); debug!("Returning dirent for {}", entry_path_str); - let dirent = __wasi_dirent_t { + let dirent = Dirent { d_next: cur_cookie, d_ino: *ino, d_namlen: namlen as u32, @@ -1378,13 +1378,13 @@ pub fn fd_readdir( let buf_len: u64 = buf_len.into(); let upper_limit = std::cmp::min( (buf_len - buf_idx as u64) as usize, - std::mem::size_of::<__wasi_dirent_t>(), + std::mem::size_of::(), ); for (i, b) in dirent_bytes.iter().enumerate().take(upper_limit) { wasi_try_mem!(buf_arr.index((i + buf_idx) as u64).write(*b)); } buf_idx += upper_limit; - if upper_limit != std::mem::size_of::<__wasi_dirent_t>() { + if upper_limit != std::mem::size_of::() { break; } let upper_limit = std::cmp::min((buf_len - buf_idx as u64) as usize, namlen); @@ -1397,29 +1397,25 @@ pub fn fd_readdir( } } - let buf_idx: M::Offset = wasi_try!(buf_idx.try_into().map_err(|_| __WASI_EOVERFLOW)); + let buf_idx: M::Offset = wasi_try!(buf_idx.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem!(bufused_ref.write(buf_idx)); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_renumber()` /// Atomically copy file descriptor /// Inputs: -/// - `__wasi_fd_t from` +/// - `Fd from` /// File descriptor to copy -/// - `__wasi_fd_t to` +/// - `Fd to` /// Location to copy file descriptor to -pub fn fd_renumber( - ctx: FunctionEnvMut<'_, WasiEnv>, - from: __wasi_fd_t, - to: __wasi_fd_t, -) -> __wasi_errno_t { +pub fn fd_renumber(ctx: FunctionEnvMut<'_, WasiEnv>, from: WasiFd, to: WasiFd) -> Errno { debug!("wasi::fd_renumber: from={}, to={}", from, to); let env = ctx.data(); let (_, mut state) = env.get_memory_and_wasi_state(&ctx, 0); let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try!(fd_map.get_mut(&from).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try!(fd_map.get_mut(&from).ok_or(Errno::Badf)); let new_fd_entry = Fd { // TODO: verify this is correct @@ -1429,22 +1425,22 @@ pub fn fd_renumber( fd_map.insert(to, new_fd_entry); fd_map.remove(&from); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_dup()` /// Duplicates the file handle /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// File handle to be cloned /// Outputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The new file handle that is a duplicate of the original pub fn fd_dup( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - ret_fd: WasmPtr<__wasi_fd_t, M>, -) -> __wasi_errno_t { + fd: WasiFd, + ret_fd: WasmPtr, +) -> Errno { debug!("wasi::fd_dup"); let env = ctx.data(); @@ -1453,7 +1449,7 @@ pub fn fd_dup( wasi_try_mem!(ret_fd.write(&memory, fd)); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_event()` @@ -1462,8 +1458,8 @@ pub fn fd_event( ctx: FunctionEnvMut<'_, WasiEnv>, initial_val: u64, flags: __wasi_eventfdflags, - ret_fd: WasmPtr<__wasi_fd_t, M>, -) -> __wasi_errno_t { + ret_fd: WasmPtr, +) -> Errno { debug!("wasi::fd_event"); let env = ctx.data(); @@ -1481,51 +1477,53 @@ pub fn fd_event( false, "event".to_string(), ); - let rights = __WASI_RIGHT_FD_READ | __WASI_RIGHT_FD_WRITE | __WASI_RIGHT_POLL_FD_READWRITE; - let fd = wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode)); + let rights = Rights::FD_READ | Rights::FD_WRITE | Rights::POLL_FD_READWRITE; + let fd = wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode)); wasi_try_mem!(ret_fd.write(&memory, fd)); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_seek()` /// Update file descriptor offset /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// File descriptor to mutate /// - `__wasi_filedelta_t offset` /// Number of bytes to adjust offset by -/// - `__wasi_whence_t whence` +/// - `Whence whence` /// What the offset is relative to /// Output: -/// - `__wasi_filesize_t *fd` +/// - `Filesize *fd` /// The new offset relative to the start of the file pub fn fd_seek( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, offset: __wasi_filedelta_t, - whence: __wasi_whence_t, - newoffset: WasmPtr<__wasi_filesize_t, M>, -) -> Result<__wasi_errno_t, WasiError> { + whence: Whence, + newoffset: WasmPtr, +) -> Result { trace!("wasi::fd_seek: fd={}, offset={}", fd, offset); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let new_offset_ref = newoffset.deref(&memory); let fd_entry = wasi_try_ok!(state.fs.get_fd(fd)); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_SEEK) { - return Ok(__WASI_EACCES); + if !fd_entry.rights.contains(Rights::FD_SEEK) { + return Ok(Errno::Access); } // TODO: handle case if fd is a dir? match whence { - __WASI_WHENCE_CUR => { + Whence::Cur => { let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(Errno::Badf)); fd_entry.offset = (fd_entry.offset as i64 + offset) as u64 } - __WASI_WHENCE_END => { + Whence::End => { use std::io::SeekFrom; let inode_idx = fd_entry.inode; let mut guard = inodes.arena[inode_idx].write(); @@ -1539,10 +1537,10 @@ pub fn fd_seek( // TODO: handle case if fd_entry.offset uses 64 bits of a u64 drop(guard); let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(Errno::Badf)); fd_entry.offset = (end as i64 + offset) as u64; } else { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } } Kind::Symlink { .. } => { @@ -1554,46 +1552,46 @@ pub fn fd_seek( | Kind::Pipe { .. } | Kind::EventNotifications { .. } => { // TODO: check this - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } Kind::Buffer { .. } => { // seeking buffers probably makes sense // TODO: implement this - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } } } - __WASI_WHENCE_SET => { + Whence::Set => { let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(Errno::Badf)); fd_entry.offset = offset as u64 } - _ => return Ok(__WASI_EINVAL), + _ => return Ok(Errno::Inval), } // reborrow let fd_entry = wasi_try_ok!(state.fs.get_fd(fd)); wasi_try_mem_ok!(new_offset_ref.write(fd_entry.offset)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `fd_sync()` /// Synchronize file and metadata to disk (TODO: expand upon what this means in our system) /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor to sync /// Errors: /// TODO: figure out which errors this should return -/// - `__WASI_EPERM` -/// - `__WASI_ENOTCAPABLE` -pub fn fd_sync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errno_t { +/// - `Errno::Perm` +/// - `Errno::Notcapable` +pub fn fd_sync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: WasiFd) -> Errno { debug!("wasi::fd_sync"); debug!("=> fd={}", fd); let env = ctx.data(); let (_, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); let fd_entry = wasi_try!(state.fs.get_fd(fd)); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_SYNC) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_SYNC) { + return Errno::Access; } let inode = fd_entry.inode; @@ -1606,34 +1604,34 @@ pub fn fd_sync(ctx: FunctionEnvMut<'_, WasiEnv>, fd: __wasi_fd_t) -> __wasi_errn if let Some(h) = handle { wasi_try!(h.sync_to_disk().map_err(fs_error_into_wasi_err)); } else { - return __WASI_EINVAL; + return Errno::Inval; } } - Kind::Root { .. } | Kind::Dir { .. } => return __WASI_EISDIR, + Kind::Root { .. } | Kind::Dir { .. } => return Errno::Isdir, Kind::Buffer { .. } | Kind::Symlink { .. } | Kind::Socket { .. } | Kind::Pipe { .. } - | Kind::EventNotifications { .. } => return __WASI_EINVAL, + | Kind::EventNotifications { .. } => return Errno::Inval, } } - __WASI_ESUCCESS + Errno::Success } /// ### `fd_tell()` /// Get the offset of the file descriptor /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The file descriptor to access /// Output: -/// - `__wasi_filesize_t *offset` +/// - `Filesize *offset` /// The offset of `fd` relative to the start of the file pub fn fd_tell( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, - offset: WasmPtr<__wasi_filesize_t, M>, -) -> __wasi_errno_t { + fd: WasiFd, + offset: WasmPtr, +) -> Errno { debug!("wasi::fd_tell"); let env = ctx.data(); let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0); @@ -1641,19 +1639,19 @@ pub fn fd_tell( let fd_entry = wasi_try!(state.fs.get_fd(fd)); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_TELL) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::FD_TELL) { + return Errno::Access; } wasi_try_mem!(offset_ref.write(fd_entry.offset)); - __WASI_ESUCCESS + Errno::Success } /// ### `fd_write()` /// Write data to the file descriptor /// Inputs: -/// - `__wasi_fd_t` +/// - `Fd` /// File descriptor (opened with writing) to write to /// - `const __wasi_ciovec_t *iovs` /// List of vectors to read data from @@ -1666,11 +1664,11 @@ pub fn fd_tell( /// pub fn fd_write( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_ciovec_t, M>, iovs_len: M::Offset, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { trace!("wasi::fd_write: fd={}", fd); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); @@ -1679,7 +1677,7 @@ pub fn fd_write( let fd_entry = wasi_try_ok!(state.fs.get_fd(fd)); let bytes_written = match fd { - __WASI_STDIN_FILENO => return Ok(__WASI_EINVAL), + __WASI_STDIN_FILENO => return Ok(Errno::Inval), __WASI_STDOUT_FILENO => { let mut guard = wasi_try_ok!( inodes @@ -1690,7 +1688,7 @@ pub fn fd_write( if let Some(ref mut stdout) = guard.deref_mut() { wasi_try_ok!(write_bytes(stdout, &memory, iovs_arr), env) } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } __WASI_STDERR_FILENO => { @@ -1703,12 +1701,12 @@ pub fn fd_write( if let Some(ref mut stderr) = guard.deref_mut() { wasi_try_ok!(write_bytes(stderr, &memory, iovs_arr), env) } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } _ => { - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_WRITE) { - return Ok(__WASI_EACCES); + if !fd_entry.rights.contains(Rights::FD_WRITE) { + return Ok(Errno::Access); } let offset = fd_entry.offset as usize; @@ -1729,7 +1727,7 @@ pub fn fd_write( ); wasi_try_ok!(write_bytes(handle, &memory, iovs_arr), env) } else { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } } Kind::Socket { socket } => { @@ -1740,7 +1738,7 @@ pub fn fd_write( } Kind::Dir { .. } | Kind::Root { .. } => { // TODO: verify - return Ok(__WASI_EISDIR); + return Ok(Errno::Isdir); } Kind::EventNotifications { counter, wakers, .. @@ -1748,7 +1746,7 @@ pub fn fd_write( let mut val = 0u64.to_ne_bytes(); let written = wasi_try_ok!(write_bytes(&mut val[..], &memory, iovs_arr)); if written != val.len() { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } let val = u64::from_ne_bytes(val); @@ -1774,7 +1772,7 @@ pub fn fd_write( // reborrow { let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try_ok!(fd_map.get_mut(&fd).ok_or(Errno::Badf)); fd_entry.offset += bytes_written as u64; } wasi_try_ok!(state.fs.filestat_resync_size(inodes.deref(), fd), env); @@ -1784,24 +1782,24 @@ pub fn fd_write( }; let bytes_written: M::Offset = - wasi_try_ok!(bytes_written.try_into().map_err(|_| __WASI_EOVERFLOW)); + wasi_try_ok!(bytes_written.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(nwritten_ref.write(bytes_written)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `fd_pipe()` /// Creates ta pipe that feeds data between two file handles /// Output: -/// - `__wasi_fd_t` +/// - `Fd` /// First file handle that represents one end of the pipe -/// - `__wasi_fd_t` +/// - `Fd` /// Second file handle that represents the other end of the pipe pub fn fd_pipe( ctx: FunctionEnvMut<'_, WasiEnv>, - ro_fd1: WasmPtr<__wasi_fd_t, M>, - ro_fd2: WasmPtr<__wasi_fd_t, M>, -) -> __wasi_errno_t { + ro_fd1: WasmPtr, + ro_fd2: WasmPtr, +) -> Errno { trace!("wasi::fd_pipe"); let env = ctx.data(); @@ -1822,20 +1820,24 @@ pub fn fd_pipe( "pipe".to_string(), ); - let rights = super::state::all_socket_rights(); - let fd1 = wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode1)); - let fd2 = wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode2)); + let rights = Rights::all_socket(); + let fd1 = wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode1)); + let fd2 = wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode2)); wasi_try_mem!(ro_fd1.write(&memory, fd1)); wasi_try_mem!(ro_fd2.write(&memory, fd2)); - __WASI_ESUCCESS + Errno::Success } /// ### `path_create_directory()` /// Create directory at a path /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The directory that the path is relative to /// - `const char *path` /// String containing path data @@ -1843,14 +1845,14 @@ pub fn fd_pipe( /// The length of `path` /// Errors: /// Required Rights: -/// - __WASI_RIGHT_PATH_CREATE_DIRECTORY +/// - Rights::PATH_CREATE_DIRECTORY /// This right must be set on the directory that the file is created in (TODO: verify that this is true) pub fn path_create_directory( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::path_create_directory"); let env = ctx.data(); let (memory, state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); @@ -1859,11 +1861,11 @@ pub fn path_create_directory( { let guard = inodes.arena[working_dir.inode].read(); if let Kind::Root { .. } = guard.deref() { - return __WASI_EACCES; + return Errno::Access; } } - if !has_rights(working_dir.rights, __WASI_RIGHT_PATH_CREATE_DIRECTORY) { - return __WASI_EACCES; + if !working_dir.rights.contains(Rights::PATH_CREATE_DIRECTORY) { + return Errno::Access; } let path_string = unsafe { get_input_str!(&memory, path, path_len) }; debug!("=> fd: {}, path: {}", fd, &path_string); @@ -1875,11 +1877,11 @@ pub fn path_create_directory( comp.as_os_str() .to_str() .map(|inner_str| inner_str.to_string()) - .ok_or(__WASI_EINVAL) + .ok_or(Errno::Inval) }) - .collect::, __wasi_errno_t>>()); + .collect::, Errno>>()); if path_vec.is_empty() { - return __WASI_EINVAL; + return Errno::Inval; } debug!("Looking at components {:?}", &path_vec); @@ -1921,8 +1923,8 @@ pub fn path_create_directory( 0, &adjusted_path.to_string_lossy(), ) { - if adjusted_path_stat.st_filetype != __WASI_FILETYPE_DIRECTORY { - return __WASI_ENOTDIR; + if adjusted_path_stat.st_filetype != Filetype::Directory { + return Errno::Notdir; } } else { wasi_try!(state.fs_create_dir(&adjusted_path)); @@ -1952,18 +1954,18 @@ pub fn path_create_directory( cur_dir_inode = new_inode; } } - Kind::Root { .. } => return __WASI_EACCES, - _ => return __WASI_ENOTDIR, + Kind::Root { .. } => return Errno::Access, + _ => return Errno::Notdir, } } - __WASI_ESUCCESS + Errno::Success } /// ### `path_filestat_get()` /// Access metadata about a file or directory /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The directory that `path` is relative to /// - `__wasi_lookupflags_t flags` /// Flags to control how `path` is understood @@ -1976,12 +1978,12 @@ pub fn path_create_directory( /// The location where the metadata will be stored pub fn path_filestat_get( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: M::Offset, - buf: WasmPtr<__wasi_filestat_t, M>, -) -> __wasi_errno_t { + buf: WasmPtr, +) -> Errno { debug!("wasi::path_filestat_get (fd={})", fd); let env = ctx.data(); let (memory, mut state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); @@ -1999,13 +2001,13 @@ pub fn path_filestat_get( wasi_try_mem!(buf.deref(&memory).write(stat)); - __WASI_ESUCCESS + Errno::Success } /// ### `path_filestat_get()` /// Access metadata about a file or directory /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The directory that `path` is relative to /// - `__wasi_lookupflags_t flags` /// Flags to control how `path` is understood @@ -2020,14 +2022,14 @@ pub fn path_filestat_get_internal( memory: &MemoryView, state: &WasiState, inodes: &mut crate::WasiInodes, - fd: __wasi_fd_t, + fd: WasiFd, flags: __wasi_lookupflags_t, path_string: &str, -) -> Result<__wasi_filestat_t, __wasi_errno_t> { +) -> Result { let root_dir = state.fs.get_fd(fd)?; - if !has_rights(root_dir.rights, __WASI_RIGHT_PATH_FILESTAT_GET) { - return Err(__WASI_EACCES); + if !root_dir.rights.contains(Rights::PATH_FILESTAT_GET) { + return Err(Errno::Access); } debug!("=> base_fd: {}, path: {}", fd, path_string); @@ -2048,7 +2050,7 @@ pub fn path_filestat_get_internal( /// ### `path_filestat_set_times()` /// Update time metadata on a file or directory /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The directory relative to which the path is resolved /// - `__wasi_lookupflags_t flags` /// Flags to control how the path is understood @@ -2056,35 +2058,34 @@ pub fn path_filestat_get_internal( /// String containing the file path /// - `u32 path_len` /// The length of the `path` string -/// - `__wasi_timestamp_t st_atim` +/// - `Timestamp st_atim` /// The timestamp that the last accessed time attribute is set to -/// - `__wasi_timestamp_t st_mtim` +/// - `Timestamp st_mtim` /// The timestamp that the last modified time attribute is set to -/// - `__wasi_fstflags_t fst_flags` +/// - `Fstflags fst_flags` /// A bitmask controlling which attributes are set pub fn path_filestat_set_times( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: M::Offset, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { debug!("wasi::path_filestat_set_times"); let env = ctx.data(); let (memory, mut state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); let fd_entry = wasi_try!(state.fs.get_fd(fd)); let fd_inode = fd_entry.inode; - if !has_rights(fd_entry.rights, __WASI_RIGHT_PATH_FILESTAT_SET_TIMES) { - return __WASI_EACCES; + if !fd_entry.rights.contains(Rights::PATH_FILESTAT_SET_TIMES) { + return Errno::Access; } - if (fst_flags & __WASI_FILESTAT_SET_ATIM != 0 && fst_flags & __WASI_FILESTAT_SET_ATIM_NOW != 0) - || (fst_flags & __WASI_FILESTAT_SET_MTIM != 0 - && fst_flags & __WASI_FILESTAT_SET_MTIM_NOW != 0) + if (fst_flags.contains(Fstflags::SET_ATIM) && fst_flags.contains(Fstflags::SET_ATIM_NOW)) + || (fst_flags.contains(Fstflags::SET_MTIM) && fst_flags.contains(Fstflags::SET_MTIM_NOW)) { - return __WASI_EINVAL; + return Errno::Inval; } let path_string = unsafe { get_input_str!(&memory, path, path_len) }; @@ -2103,16 +2104,16 @@ pub fn path_filestat_set_times( let inode = &inodes.arena[fd_inode]; - if fst_flags & __WASI_FILESTAT_SET_ATIM != 0 || fst_flags & __WASI_FILESTAT_SET_ATIM_NOW != 0 { - let time_to_set = if fst_flags & __WASI_FILESTAT_SET_ATIM != 0 { + if fst_flags.contains(Fstflags::SET_ATIM) || fst_flags.contains(Fstflags::SET_ATIM_NOW) { + let time_to_set = if fst_flags.contains(Fstflags::SET_ATIM) { st_atim } else { wasi_try!(get_current_time_in_nanos()) }; inode.stat.write().unwrap().st_atim = time_to_set; } - if fst_flags & __WASI_FILESTAT_SET_MTIM != 0 || fst_flags & __WASI_FILESTAT_SET_MTIM_NOW != 0 { - let time_to_set = if fst_flags & __WASI_FILESTAT_SET_MTIM != 0 { + if fst_flags.contains(Fstflags::SET_MTIM) || fst_flags.contains(Fstflags::SET_MTIM_NOW) { + let time_to_set = if fst_flags.contains(Fstflags::SET_MTIM) { st_mtim } else { wasi_try!(get_current_time_in_nanos()) @@ -2120,13 +2121,13 @@ pub fn path_filestat_set_times( inode.stat.write().unwrap().st_mtim = time_to_set; } - __WASI_ESUCCESS + Errno::Success } /// ### `path_link()` /// Create a hard link /// Inputs: -/// - `__wasi_fd_t old_fd` +/// - `Fd old_fd` /// The directory relative to which the `old_path` is /// - `__wasi_lookupflags_t old_flags` /// Flags to control how `old_path` is understood @@ -2134,7 +2135,7 @@ pub fn path_filestat_set_times( /// String containing the old file path /// - `u32 old_path_len` /// Length of the `old_path` string -/// - `__wasi_fd_t new_fd` +/// - `Fd new_fd` /// The directory relative to which the `new_path` is /// - `const char *new_path` /// String containing the new file path @@ -2142,14 +2143,14 @@ pub fn path_filestat_set_times( /// Length of the `new_path` string pub fn path_link( ctx: FunctionEnvMut<'_, WasiEnv>, - old_fd: __wasi_fd_t, + old_fd: WasiFd, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, old_path_len: M::Offset, - new_fd: __wasi_fd_t, + new_fd: WasiFd, new_path: WasmPtr, new_path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::path_link"); if old_flags & __WASI_LOOKUP_SYMLINK_FOLLOW != 0 { debug!(" - will follow symlinks when opening path"); @@ -2165,10 +2166,10 @@ pub fn path_link( old_fd, &old_path_str, new_fd, new_path_str ); - if !(has_rights(source_fd.rights, __WASI_RIGHT_PATH_LINK_SOURCE) - && has_rights(target_fd.rights, __WASI_RIGHT_PATH_LINK_TARGET)) + if !source_fd.rights.contains(Rights::PATH_LINK_SOURCE) + || !target_fd.rights.contains(Rights::PATH_LINK_TARGET) { - return __WASI_EACCES; + return Errno::Access; } let source_inode = wasi_try!(state.fs.get_inode_at_path( @@ -2185,9 +2186,8 @@ pub fn path_link( false )); - if inodes.arena[source_inode].stat.write().unwrap().st_nlink == __wasi_linkcount_t::max_value() - { - return __WASI_EMLINK; + if inodes.arena[source_inode].stat.write().unwrap().st_nlink == Linkcount::max_value() { + return Errno::Mlink; } { let mut guard = inodes.arena[target_parent_inode].write(); @@ -2195,28 +2195,28 @@ pub fn path_link( match deref_mut { Kind::Dir { entries, .. } => { if entries.contains_key(&new_entry_name) { - return __WASI_EEXIST; + return Errno::Exist; } entries.insert(new_entry_name, source_inode); } - Kind::Root { .. } => return __WASI_EINVAL, + Kind::Root { .. } => return Errno::Inval, Kind::File { .. } | Kind::Symlink { .. } | Kind::Buffer { .. } | Kind::Socket { .. } | Kind::Pipe { .. } - | Kind::EventNotifications { .. } => return __WASI_ENOTDIR, + | Kind::EventNotifications { .. } => return Errno::Notdir, } } inodes.arena[source_inode].stat.write().unwrap().st_nlink += 1; - __WASI_ESUCCESS + Errno::Success } /// ### `path_open()` /// Open file located at the given path /// Inputs: -/// - `__wasi_fd_t dirfd` +/// - `Fd dirfd` /// The fd corresponding to the directory that the file is in /// - `__wasi_lookupflags_t dirflags` /// Flags specifying how the path will be resolved @@ -2226,29 +2226,29 @@ pub fn path_link( /// The length of the `path` string /// - `__wasi_oflags_t o_flags` /// How the file will be opened -/// - `__wasi_rights_t fs_rights_base` +/// - `Rights fs_rights_base` /// The rights of the created file descriptor -/// - `__wasi_rights_t fs_rightsinheriting` +/// - `Rights fs_rightsinheriting` /// The rights of file descriptors derived from the created file descriptor -/// - `__wasi_fdflags_t fs_flags` +/// - `Fdflags fs_flags` /// The flags of the file descriptor /// Output: -/// - `__wasi_fd_t* fd` +/// - `Fd* fd` /// The new file descriptor /// Possible Errors: -/// - `__WASI_EACCES`, `__WASI_EBADF`, `__WASI_EFAULT`, `__WASI_EFBIG?`, `__WASI_EINVAL`, `__WASI_EIO`, `__WASI_ELOOP`, `__WASI_EMFILE`, `__WASI_ENAMETOOLONG?`, `__WASI_ENFILE`, `__WASI_ENOENT`, `__WASI_ENOTDIR`, `__WASI_EROFS`, and `__WASI_ENOTCAPABLE` +/// - `Errno::Access`, `Errno::Badf`, `Errno::Fault`, `Errno::Fbig?`, `Errno::Inval`, `Errno::Io`, `Errno::Loop`, `Errno::Mfile`, `Errno::Nametoolong?`, `Errno::Nfile`, `Errno::Noent`, `Errno::Notdir`, `Errno::Rofs`, and `Errno::Notcapable` pub fn path_open( ctx: FunctionEnvMut<'_, WasiEnv>, - dirfd: __wasi_fd_t, + dirfd: WasiFd, dirflags: __wasi_lookupflags_t, path: WasmPtr, path_len: M::Offset, o_flags: __wasi_oflags_t, - fs_rights_base: __wasi_rights_t, - fs_rights_inheriting: __wasi_rights_t, - fs_flags: __wasi_fdflags_t, - fd: WasmPtr<__wasi_fd_t, M>, -) -> __wasi_errno_t { + fs_rights_base: Rights, + fs_rights_inheriting: Rights, + fs_flags: Fdflags, + fd: WasmPtr, +) -> Errno { debug!("wasi::path_open"); if dirflags & __WASI_LOOKUP_SYMLINK_FOLLOW != 0 { debug!(" - will follow symlinks when opening path"); @@ -2258,7 +2258,7 @@ pub fn path_open( /* TODO: find actual upper bound on name size (also this is a path, not a name :think-fish:) */ let path_len64: u64 = path_len.into(); if path_len64 > 1024u64 * 1024u64 { - return __WASI_ENAMETOOLONG; + return Errno::Nametoolong; } let fd_ref = fd.deref(&memory); @@ -2273,8 +2273,8 @@ pub fn path_open( let working_dir_rights_inheriting = working_dir.rights_inheriting; // ASSUMPTION: open rights apply recursively - if !has_rights(working_dir.rights, __WASI_RIGHT_PATH_OPEN) { - return __WASI_EACCES; + if !working_dir.rights.contains(Rights::PATH_OPEN) { + return Errno::Access; } let path_string = unsafe { get_input_str!(&memory, path, path_len) }; @@ -2308,21 +2308,21 @@ pub fn path_open( // short circuit if we're dealing with a special file assert!(handle.is_some()); wasi_try_mem!(fd_ref.write(*special_fd)); - return __WASI_ESUCCESS; + return Errno::Success; } if o_flags & __WASI_O_DIRECTORY != 0 { - return __WASI_ENOTDIR; + return Errno::Notdir; } if o_flags & __WASI_O_EXCL != 0 { - return __WASI_EEXIST; + return Errno::Exist; } - let write_permission = adjusted_rights & __WASI_RIGHT_FD_WRITE != 0; + let write_permission = adjusted_rights.contains(Rights::FD_WRITE); // append, truncate, and create all require the permission to write let (append_permission, truncate_permission, create_permission) = if write_permission { ( - fs_flags & __WASI_FDFLAG_APPEND != 0, + fs_flags.contains(Fdflags::APPEND), o_flags & __WASI_O_TRUNC != 0, o_flags & __WASI_O_CREAT != 0, ) @@ -2337,7 +2337,7 @@ pub fn path_open( .append(append_permission) .truncate(truncate_permission); open_flags |= Fd::READ; - if adjusted_rights & __WASI_RIGHT_FD_WRITE != 0 { + if adjusted_rights.contains(Rights::FD_WRITE) { open_flags |= Fd::WRITE; } if o_flags & __WASI_O_CREAT != 0 { @@ -2372,7 +2372,7 @@ pub fn path_open( debug!("Maybe creating file"); if o_flags & __WASI_O_CREAT != 0 { if o_flags & __WASI_O_DIRECTORY != 0 { - return __WASI_ENOTDIR; + return Errno::Notdir; } debug!("Creating file"); // strip end file name @@ -2392,8 +2392,8 @@ pub fn path_open( new_path.push(&new_entity_name); new_path } - Kind::Root { .. } => return __WASI_EACCES, - _ => return __WASI_EINVAL, + Kind::Root { .. } => return Errno::Access, + _ => return Errno::Inval, } }; // once we got the data we need from the parent, we lookup the host file @@ -2401,7 +2401,7 @@ pub fn path_open( let handle = { let open_options = open_options .read(true) - .append(fs_flags & __WASI_FDFLAG_APPEND != 0) + .append(fs_flags.contains(Fdflags::APPEND)) // TODO: ensure these rights are actually valid given parent, etc. // write access is required for creating a file .write(true) @@ -2463,13 +2463,13 @@ pub fn path_open( wasi_try_mem!(fd_ref.write(out_fd)); debug!("wasi::path_open returning fd {}", out_fd); - __WASI_ESUCCESS + Errno::Success } /// ### `path_readlink()` /// Read the value of a symlink /// Inputs: -/// - `__wasi_fd_t dir_fd` +/// - `Fd dir_fd` /// The base directory from which `path` is understood /// - `const char *path` /// Pointer to UTF-8 bytes that make up the path to the symlink @@ -2484,20 +2484,20 @@ pub fn path_open( /// The number of bytes written to `buf` pub fn path_readlink( ctx: FunctionEnvMut<'_, WasiEnv>, - dir_fd: __wasi_fd_t, + dir_fd: WasiFd, path: WasmPtr, path_len: M::Offset, buf: WasmPtr, buf_len: M::Offset, buf_used: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::path_readlink"); let env = ctx.data(); let (memory, mut state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); let base_dir = wasi_try!(state.fs.get_fd(dir_fd)); - if !has_rights(base_dir.rights, __WASI_RIGHT_PATH_READLINK) { - return __WASI_EACCES; + if !base_dir.rights.contains(Rights::PATH_READLINK) { + return Errno::Access; } let path_str = unsafe { get_input_str!(&memory, path, path_len) }; let inode = wasi_try!(state @@ -2512,7 +2512,7 @@ pub fn path_readlink( let buf_len: u64 = buf_len.into(); let bytes = rel_path_str.bytes(); if bytes.len() as u64 >= buf_len { - return __WASI_EOVERFLOW; + return Errno::Overflow; } let bytes: Vec<_> = bytes.collect(); @@ -2521,23 +2521,23 @@ pub fn path_readlink( // should we null terminate this? let bytes_len: M::Offset = - wasi_try!(bytes.len().try_into().map_err(|_| __WASI_EOVERFLOW)); + wasi_try!(bytes.len().try_into().map_err(|_| Errno::Overflow)); wasi_try_mem!(buf_used.deref(&memory).write(bytes_len)); } else { - return __WASI_EINVAL; + return Errno::Inval; } } - __WASI_ESUCCESS + Errno::Success } -/// Returns __WASI_ENOTEMTPY if directory is not empty +/// Returns Errno::Notemtpy if directory is not empty pub fn path_remove_directory( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { // TODO check if fd is a dir, ensure it's within sandbox, etc. debug!("wasi::path_remove_directory"); let env = ctx.data(); @@ -2562,12 +2562,12 @@ pub fn path_remove_directory( match deref { Kind::Dir { entries, path, .. } => { if !entries.is_empty() || wasi_try!(state.fs_read_dir(path)).count() != 0 { - return __WASI_ENOTEMPTY; + return Errno::Notempty; } path.clone() } - Kind::Root { .. } => return __WASI_EACCES, - _ => return __WASI_ENOTDIR, + Kind::Root { .. } => return Errno::Access, + _ => return Errno::Notdir, } }; @@ -2578,11 +2578,11 @@ pub fn path_remove_directory( Kind::Dir { ref mut entries, .. } => { - let removed_inode = wasi_try!(entries.remove(&childs_name).ok_or(__WASI_EINVAL)); + let removed_inode = wasi_try!(entries.remove(&childs_name).ok_or(Errno::Inval)); // TODO: make this a debug assert in the future assert!(inode == removed_inode); } - Kind::Root { .. } => return __WASI_EACCES, + Kind::Root { .. } => return Errno::Access, _ => unreachable!( "Internal logic error in wasi::path_remove_directory, parent is not a directory" ), @@ -2601,19 +2601,19 @@ pub fn path_remove_directory( return err; } - __WASI_ESUCCESS + Errno::Success } /// ### `path_rename()` /// Rename a file or directory /// Inputs: -/// - `__wasi_fd_t old_fd` +/// - `Fd old_fd` /// The base directory for `old_path` /// - `const char* old_path` /// Pointer to UTF8 bytes, the file to be renamed /// - `u32 old_path_len` /// The number of bytes to read from `old_path` -/// - `__wasi_fd_t new_fd` +/// - `Fd new_fd` /// The base directory for `new_path` /// - `const char* new_path` /// Pointer to UTF8 bytes, the new file name @@ -2621,13 +2621,13 @@ pub fn path_remove_directory( /// The number of bytes to read from `new_path` pub fn path_rename( ctx: FunctionEnvMut<'_, WasiEnv>, - old_fd: __wasi_fd_t, + old_fd: WasiFd, old_path: WasmPtr, old_path_len: M::Offset, - new_fd: __wasi_fd_t, + new_fd: WasiFd, new_path: WasmPtr, new_path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { debug!( "wasi::path_rename: old_fd = {}, new_fd = {}", old_fd, new_fd @@ -2642,12 +2642,12 @@ pub fn path_rename( { let source_fd = wasi_try!(state.fs.get_fd(old_fd)); - if !has_rights(source_fd.rights, __WASI_RIGHT_PATH_RENAME_SOURCE) { - return __WASI_EACCES; + if !source_fd.rights.contains(Rights::PATH_RENAME_SOURCE) { + return Errno::Access; } let target_fd = wasi_try!(state.fs.get_fd(new_fd)); - if !has_rights(target_fd.rights, __WASI_RIGHT_PATH_RENAME_TARGET) { - return __WASI_EACCES; + if !target_fd.rights.contains(Rights::PATH_RENAME_TARGET) { + return Errno::Access; } } @@ -2668,7 +2668,7 @@ pub fn path_rename( ) .is_ok() { - return __WASI_EEXIST; + return Errno::Exist; } let (source_parent_inode, source_entry_name) = wasi_try!(state @@ -2684,15 +2684,15 @@ pub fn path_rename( match deref { Kind::Dir { entries, path, .. } => { if entries.contains_key(&target_entry_name) { - return __WASI_EEXIST; + return Errno::Exist; } let mut out_path = path.clone(); out_path.push(std::path::Path::new(&target_entry_name)); out_path } - Kind::Root { .. } => return __WASI_ENOTCAPABLE, + Kind::Root { .. } => return Errno::Notcapable, Kind::Socket { .. } | Kind::Pipe { .. } | Kind::EventNotifications { .. } => { - return __WASI_EINVAL + return Errno::Inval } Kind::Symlink { .. } | Kind::File { .. } | Kind::Buffer { .. } => { unreachable!("Fatal internal logic error: parent of inode is not a directory") @@ -2705,11 +2705,11 @@ pub fn path_rename( let deref_mut = guard.deref_mut(); match deref_mut { Kind::Dir { entries, .. } => { - wasi_try!(entries.remove(&source_entry_name).ok_or(__WASI_ENOENT)) + wasi_try!(entries.remove(&source_entry_name).ok_or(Errno::Noent)) } - Kind::Root { .. } => return __WASI_ENOTCAPABLE, + Kind::Root { .. } => return Errno::Notcapable, Kind::Socket { .. } | Kind::Pipe { .. } | Kind::EventNotifications { .. } => { - return __WASI_EINVAL + return Errno::Inval } Kind::Symlink { .. } | Kind::File { .. } | Kind::Buffer { .. } => { unreachable!("Fatal internal logic error: parent of inode is not a directory") @@ -2788,7 +2788,7 @@ pub fn path_rename( } } - __WASI_ESUCCESS + Errno::Success } /// ### `path_symlink()` @@ -2798,7 +2798,7 @@ pub fn path_rename( /// Array of UTF-8 bytes representing the source path /// - `u32 old_path_len` /// The number of bytes to read from `old_path` -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The base directory from which the paths are understood /// - `const char *new_path` /// Array of UTF-8 bytes representing the target path @@ -2808,18 +2808,18 @@ pub fn path_symlink( ctx: FunctionEnvMut<'_, WasiEnv>, old_path: WasmPtr, old_path_len: M::Offset, - fd: __wasi_fd_t, + fd: WasiFd, new_path: WasmPtr, new_path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::path_symlink"); let env = ctx.data(); let (memory, mut state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); let old_path_str = unsafe { get_input_str!(&memory, old_path, old_path_len) }; let new_path_str = unsafe { get_input_str!(&memory, new_path, new_path_len) }; let base_fd = wasi_try!(state.fs.get_fd(fd)); - if !has_rights(base_fd.rights, __WASI_RIGHT_PATH_SYMLINK) { - return __WASI_EACCES; + if !base_fd.rights.contains(Rights::PATH_SYMLINK) { + return Errno::Access; } // get the depth of the parent + 1 (UNDER INVESTIGATION HMMMMMMMM THINK FISH ^ THINK FISH) @@ -2846,12 +2846,12 @@ pub fn path_symlink( match deref { Kind::Dir { entries, .. } => { if entries.contains_key(&entry_name) { - return __WASI_EEXIST; + return Errno::Exist; } } - Kind::Root { .. } => return __WASI_ENOTCAPABLE, + Kind::Root { .. } => return Errno::Notcapable, Kind::Socket { .. } | Kind::Pipe { .. } | Kind::EventNotifications { .. } => { - return __WASI_EINVAL + return Errno::Inval } Kind::File { .. } | Kind::Symlink { .. } | Kind::Buffer { .. } => { unreachable!("get_parent_inode_at_path returned something other than a Dir or Root") @@ -2893,13 +2893,13 @@ pub fn path_symlink( } } - __WASI_ESUCCESS + Errno::Success } /// ### `path_unlink_file()` /// Unlink a file, deleting if the number of hardlinks is 1 /// Inputs: -/// - `__wasi_fd_t fd` +/// - `Fd fd` /// The base file descriptor from which the path is understood /// - `const char *path` /// Array of UTF-8 bytes representing the path @@ -2907,17 +2907,17 @@ pub fn path_symlink( /// The number of bytes in the `path` array pub fn path_unlink_file( ctx: FunctionEnvMut<'_, WasiEnv>, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::path_unlink_file"); let env = ctx.data(); let (memory, mut state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); let base_dir = wasi_try!(state.fs.get_fd(fd)); - if !has_rights(base_dir.rights, __WASI_RIGHT_PATH_UNLINK_FILE) { - return __WASI_EACCES; + if !base_dir.rights.contains(Rights::PATH_UNLINK_FILE) { + return Errno::Access; } let path_str = unsafe { get_input_str!(&memory, path, path_len) }; debug!("Requested file: {}", path_str); @@ -2939,13 +2939,13 @@ pub fn path_unlink_file( Kind::Dir { ref mut entries, .. } => { - let removed_inode = wasi_try!(entries.remove(&childs_name).ok_or(__WASI_EINVAL)); + let removed_inode = wasi_try!(entries.remove(&childs_name).ok_or(Errno::Inval)); // TODO: make this a debug assert in the future assert!(inode == removed_inode); debug_assert!(inodes.arena[inode].stat.read().unwrap().st_nlink > 0); removed_inode } - Kind::Root { .. } => return __WASI_EACCES, + Kind::Root { .. } => return Errno::Access, _ => unreachable!( "Internal logic error in wasi::path_unlink_file, parent is not a directory" ), @@ -2973,7 +2973,7 @@ pub fn path_unlink_file( wasi_try!(state.fs_remove_file(path)); } } - Kind::Dir { .. } | Kind::Root { .. } => return __WASI_EISDIR, + Kind::Dir { .. } | Kind::Root { .. } => return Errno::Isdir, Kind::Symlink { .. } => { // TODO: actually delete real symlinks and do nothing for virtual symlinks } @@ -3003,7 +3003,7 @@ pub fn path_unlink_file( } } - __WASI_ESUCCESS + Errno::Success } /// ### `poll_oneoff()` @@ -3011,7 +3011,7 @@ pub fn path_unlink_file( /// Inputs: /// - `const __wasi_subscription_t *in` /// The events to subscribe to -/// - `__wasi_event_t *out` +/// - `Event *out` /// The events that have occured /// - `u32 nsubscriptions` /// The number of subscriptions and the number of events @@ -3020,11 +3020,11 @@ pub fn path_unlink_file( /// The number of events seen pub fn poll_oneoff( ctx: FunctionEnvMut<'_, WasiEnv>, - in_: WasmPtr<__wasi_subscription_t, M>, - out_: WasmPtr<__wasi_event_t, M>, + in_: WasmPtr, + out_: WasmPtr, nsubscriptions: M::Offset, nevents: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { trace!("wasi::poll_oneoff"); trace!(" => nsubscriptions = {}", nsubscriptions); let env = ctx.data(); @@ -3041,44 +3041,42 @@ pub fn poll_oneoff( let mut time_to_sleep = Duration::from_millis(5); for sub in subscription_array.iter() { - let s: WasiSubscription = wasi_try_ok!(wasi_try_mem_ok!(sub.read()).try_into()); + let s: Subscription = wasi_try_mem_ok!(sub.read()); let mut peb = PollEventBuilder::new(); - let fd = match s.event_type { - EventType::Read(__wasi_subscription_fs_readwrite_t { fd }) => { - match fd { + let fd = match s.data { + SubscriptionEnum::Read(SubscriptionFsReadwrite { file_descriptor }) => { + match file_descriptor { __WASI_STDIN_FILENO | __WASI_STDOUT_FILENO | __WASI_STDERR_FILENO => (), _ => { - let fd_entry = wasi_try_ok!(state.fs.get_fd(fd), env); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_READ) { - return Ok(__WASI_EACCES); + let fd_entry = wasi_try_ok!(state.fs.get_fd(file_descriptor), env); + if !fd_entry.rights.contains(Rights::FD_READ) { + return Ok(Errno::Access); } } } in_events.push(peb.add(PollEvent::PollIn).build()); - Some(fd) + Some(file_descriptor) } - EventType::Write(__wasi_subscription_fs_readwrite_t { fd }) => { - match fd { + SubscriptionEnum::Write(SubscriptionFsReadwrite { file_descriptor }) => { + match file_descriptor { __WASI_STDIN_FILENO | __WASI_STDOUT_FILENO | __WASI_STDERR_FILENO => (), _ => { - let fd_entry = wasi_try_ok!(state.fs.get_fd(fd), env); - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_WRITE) { - return Ok(__WASI_EACCES); + let fd_entry = wasi_try_ok!(state.fs.get_fd(file_descriptor), env); + if !fd_entry.rights.contains(Rights::FD_WRITE) { + return Ok(Errno::Access); } } } in_events.push(peb.add(PollEvent::PollOut).build()); - Some(fd) + Some(file_descriptor) } - EventType::Clock(clock_info) => { - if clock_info.clock_id == __WASI_CLOCK_REALTIME - || clock_info.clock_id == __WASI_CLOCK_MONOTONIC - { + SubscriptionEnum::Clock(clock_info) => { + if matches!(clock_info.clock_id, Clockid::Realtime | Clockid::Monotonic) { // this is a hack // TODO: do this properly time_to_sleep = Duration::from_nanos(clock_info.timeout); - clock_subs.push((clock_info, s.user_data)); + clock_subs.push((clock_info, s.userdata)); None } else { unimplemented!("Polling not implemented for clocks yet"); @@ -3115,8 +3113,8 @@ pub fn poll_oneoff( _ => { let fd_entry = wasi_try_ok!(state.fs.get_fd(fd), env); let inode = fd_entry.inode; - if !has_rights(fd_entry.rights, __WASI_RIGHT_POLL_FD_READWRITE) { - return Ok(__WASI_EACCES); + if !fd_entry.rights.contains(Rights::POLL_FD_READWRITE) { + return Ok(Errno::Access); } { @@ -3127,13 +3125,13 @@ pub fn poll_oneoff( if let Some(h) = handle { crate::state::InodeValFileReadGuard { guard } } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } Kind::Socket { .. } | Kind::Pipe { .. } | Kind::EventNotifications { .. } => { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } Kind::Dir { .. } | Kind::Root { .. } @@ -3153,17 +3151,17 @@ pub fn poll_oneoff( let fds = { let mut f = vec![]; for fd in fd_guards.iter() { - f.push(wasi_try_ok!(fd.as_ref().ok_or(__WASI_EBADF)).deref()); + f.push(wasi_try_ok!(fd.as_ref().ok_or(Errno::Badf)).deref()); } f }; let mut seen_events = vec![Default::default(); in_events.len()]; - let start = platform_clock_time_get(__WASI_CLOCK_MONOTONIC, 1_000_000).unwrap() as u128; + let start = platform_clock_time_get(Snapshot0Clockid::Monotonic, 1_000_000).unwrap() as u128; let mut triggered = 0; while triggered == 0 { - let now = platform_clock_time_get(__WASI_CLOCK_MONOTONIC, 1_000_000).unwrap() as u128; + let now = platform_clock_time_get(Snapshot0Clockid::Monotonic, 1_000_000).unwrap() as u128; let delta = match now.checked_sub(start) { Some(a) => Duration::from_nanos(a as u64), None => Duration::ZERO, @@ -3193,15 +3191,15 @@ pub fn poll_oneoff( } for (i, seen_event) in seen_events.into_iter().enumerate() { - let mut flags = 0; - let mut error = __WASI_EAGAIN; + let mut flags = Eventrwflags::empty(); + let mut error = Errno::Again; let mut bytes_available = 0; let event_iter = iterate_poll_events(seen_event); for event in event_iter { match event { - PollEvent::PollError => error = __WASI_EIO, - PollEvent::PollHangUp => flags = __WASI_EVENT_FD_READWRITE_HANGUP, - PollEvent::PollInvalid => error = __WASI_EINVAL, + PollEvent::PollError => error = Errno::Io, + PollEvent::PollHangUp => flags = Eventrwflags::FD_READWRITE_HANGUP, + PollEvent::PollInvalid => error = Errno::Inval, PollEvent::PollIn => { bytes_available = wasi_try_ok!( fds[i] @@ -3210,7 +3208,7 @@ pub fn poll_oneoff( env ) .unwrap_or(0usize); - error = __WASI_ESUCCESS; + error = Errno::Success; } PollEvent::PollOut => { bytes_available = wasi_try_ok!( @@ -3220,21 +3218,23 @@ pub fn poll_oneoff( env ) .unwrap_or(0usize); - error = __WASI_ESUCCESS; + error = Errno::Success; } } } - let event = __wasi_event_t { + let event = Event { userdata: wasi_try_mem_ok!(subscription_array.index(i as u64).read()).userdata, error, - type_: wasi_try_mem_ok!(subscription_array.index(i as u64).read()).type_, - u: unsafe { - __wasi_event_u { - fd_readwrite: __wasi_event_fd_readwrite_t { - nbytes: bytes_available as u64, - flags, - }, - } + data: match wasi_try_mem_ok!(subscription_array.index(i as u64).read()).data { + SubscriptionEnum::Read(d) => EventEnum::FdRead(EventFdReadwrite { + nbytes: bytes_available as u64, + flags, + }), + SubscriptionEnum::Write(d) => EventEnum::FdWrite(EventFdReadwrite { + nbytes: bytes_available as u64, + flags, + }), + SubscriptionEnum::Clock(_) => EventEnum::Clock, }, }; wasi_try_mem_ok!(event_array.index(events_seen as u64).write(event)); @@ -3242,26 +3242,18 @@ pub fn poll_oneoff( } if triggered == 0 { for (clock_info, userdata) in clock_subs { - let event = __wasi_event_t { + let event = Event { userdata, - error: __WASI_ESUCCESS, - type_: __WASI_EVENTTYPE_CLOCK, - u: unsafe { - __wasi_event_u { - fd_readwrite: __wasi_event_fd_readwrite_t { - nbytes: 0, - flags: 0, - }, - } - }, + error: Errno::Success, + data: EventEnum::Clock, }; wasi_try_mem_ok!(event_array.index(events_seen as u64).write(event)); events_seen += 1; } } - let events_seen: M::Offset = wasi_try_ok!(events_seen.try_into().map_err(|_| __WASI_EOVERFLOW)); + let events_seen: M::Offset = wasi_try_ok!(events_seen.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(out_ptr.write(events_seen)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `proc_exit()` @@ -3285,18 +3277,18 @@ pub fn proc_exit( /// Inputs: /// - `__wasi_signal_t` /// Signal to be raised for this process -pub fn proc_raise(ctx: FunctionEnvMut<'_, WasiEnv>, sig: __wasi_signal_t) -> __wasi_errno_t { +pub fn proc_raise(ctx: FunctionEnvMut<'_, WasiEnv>, sig: __wasi_signal_t) -> Errno { debug!("wasi::proc_raise"); unimplemented!("wasi::proc_raise") } /// ### `sched_yield()` /// Yields execution of the thread -pub fn sched_yield(ctx: FunctionEnvMut<'_, WasiEnv>) -> Result<__wasi_errno_t, WasiError> { +pub fn sched_yield(ctx: FunctionEnvMut<'_, WasiEnv>) -> Result { trace!("wasi::sched_yield"); let env = ctx.data(); env.yield_now()?; - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `random_get()` @@ -3310,7 +3302,7 @@ pub fn random_get( ctx: FunctionEnvMut<'_, WasiEnv>, buf: WasmPtr, buf_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { trace!("wasi::random_get buf_len: {}", buf_len); let env = ctx.data(); let memory = env.memory_view(&ctx); @@ -3321,9 +3313,9 @@ pub fn random_get( Ok(()) => { let buf = wasi_try_mem!(buf.slice(&memory, buf_len)); wasi_try_mem!(buf.write_slice(&u8_buffer)); - __WASI_ESUCCESS + Errno::Success } - Err(_) => __WASI_EIO, + Err(_) => Errno::Io, } } @@ -3331,51 +3323,36 @@ pub fn random_get( /// Retrieves the current state of the TTY pub fn tty_get( ctx: FunctionEnvMut<'_, WasiEnv>, - tty_state: WasmPtr<__wasi_tty_t, M>, -) -> __wasi_errno_t { + tty_state: WasmPtr, +) -> Errno { debug!("wasi::tty_stdin"); let env = ctx.data(); let state = env.runtime.tty_get(); - let state = __wasi_tty_t { + let state = Tty { cols: state.cols, rows: state.rows, width: state.width, height: state.height, - stdin_tty: match state.stdin_tty { - false => __WASI_BOOL_FALSE, - true => __WASI_BOOL_TRUE, - }, - stdout_tty: match state.stdout_tty { - false => __WASI_BOOL_FALSE, - true => __WASI_BOOL_TRUE, - }, - stderr_tty: match state.stderr_tty { - false => __WASI_BOOL_FALSE, - true => __WASI_BOOL_TRUE, - }, - echo: match state.echo { - false => __WASI_BOOL_FALSE, - true => __WASI_BOOL_TRUE, - }, - line_buffered: match state.line_buffered { - false => __WASI_BOOL_FALSE, - true => __WASI_BOOL_TRUE, - }, + stdin_tty: state.stdin_tty, + stdout_tty: state.stdout_tty, + stderr_tty: state.stderr_tty, + echo: state.echo, + line_buffered: state.line_buffered, }; let memory = env.memory_view(&ctx); wasi_try_mem!(tty_state.write(&memory, state)); - __WASI_ESUCCESS + Errno::Success } /// ### `tty_set()` /// Updates the properties of the rect pub fn tty_set( ctx: FunctionEnvMut<'_, WasiEnv>, - tty_state: WasmPtr<__wasi_tty_t, M>, -) -> __wasi_errno_t { + tty_state: WasmPtr, +) -> Errno { debug!("wasi::tty_set"); let env = ctx.data(); @@ -3386,36 +3363,16 @@ pub fn tty_set( rows: state.rows, width: state.width, height: state.height, - stdin_tty: match state.stdin_tty { - __WASI_BOOL_FALSE => false, - __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, - }, - stdout_tty: match state.stdout_tty { - __WASI_BOOL_FALSE => false, - __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, - }, - stderr_tty: match state.stderr_tty { - __WASI_BOOL_FALSE => false, - __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, - }, - echo: match state.echo { - __WASI_BOOL_FALSE => false, - __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, - }, - line_buffered: match state.line_buffered { - __WASI_BOOL_FALSE => false, - __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, - }, + stdin_tty: state.stdin_tty, + stdout_tty: state.stdout_tty, + stderr_tty: state.stderr_tty, + echo: state.echo, + line_buffered: state.line_buffered, }; env.runtime.tty_set(state); - __WASI_ESUCCESS + Errno::Success } /// ### `getcwd()` @@ -3426,7 +3383,7 @@ pub fn getcwd( ctx: FunctionEnvMut<'_, WasiEnv>, path: WasmPtr, path_len: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::getcwd"); let env = ctx.data(); let (memory, mut state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); @@ -3442,7 +3399,7 @@ pub fn getcwd( let cur_dir = cur_dir.as_bytes(); wasi_try_mem!(path_len.write(&memory, wasi_try!(to_offset::(cur_dir.len())))); if cur_dir.len() as u64 >= max_path_len { - return __WASI_EOVERFLOW; + return Errno::Overflow; } let cur_dir = { @@ -3452,13 +3409,13 @@ pub fn getcwd( u8_buffer[..cur_dir_len].clone_from_slice(cur_dir); u8_buffer[cur_dir_len] = 0; } else { - return __WASI_EOVERFLOW; + return Errno::Overflow; } u8_buffer }; wasi_try_mem!(path_slice.write_slice(&cur_dir[..])); - __WASI_ESUCCESS + Errno::Success } /// ### `chdir()` @@ -3467,14 +3424,14 @@ pub fn chdir( ctx: FunctionEnvMut<'_, WasiEnv>, path: WasmPtr, path_len: M::Offset, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::chdir"); let env = ctx.data(); let (memory, mut state) = env.get_memory_and_wasi_state(&ctx, 0); let path = unsafe { get_input_str!(&memory, path, path_len) }; state.fs.set_current_dir(path.as_str()); - __WASI_ESUCCESS + Errno::Success } /// ### `thread_spawn()` @@ -3501,8 +3458,8 @@ pub fn thread_spawn( method_len: M::Offset, user_data: u64, reactor: __wasi_bool_t, - ret_tid: WasmPtr<__wasi_tid_t, M>, -) -> __wasi_errno_t { + ret_tid: WasmPtr, +) -> Errno { debug!("wasi::thread_spawn"); let env = ctx.data(); let memory = env.memory_view(&ctx); @@ -3510,12 +3467,12 @@ pub fn thread_spawn( // Load the callback function if method.as_str() != "_thread_start" { - return __WASI_ENOTCAPABLE; + return Errno::Notcapable; }; /* let funct = unsafe { if env.thread_start_ref().is_none() { - return __WASI_EADDRNOTAVAIL; + return Errno::Addrnotavail; } env.thread_start_ref_unchecked() }; @@ -3524,7 +3481,7 @@ pub fn thread_spawn( let reactor = match reactor { __WASI_BOOL_FALSE => false, __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, + _ => return Errno::Inval, }; // Create the sub-thread @@ -3565,15 +3522,15 @@ pub fn thread_spawn( drop(sub_thread); })) .map_err(|err| { - let err: __wasi_errno_t = err.into(); + let err: Errno = err.into(); err })); id }; - let child: __wasi_tid_t = child.into(); + let child: Tid = child.into(); wasi_try_mem!(ret_tid.write(&memory, child)); - __WASI_ESUCCESS + Errno::Success } /// ### `thread_sleep()` @@ -3584,14 +3541,14 @@ pub fn thread_spawn( /// * `duration` - Amount of time that the thread should sleep pub fn thread_sleep( ctx: FunctionEnvMut<'_, WasiEnv>, - duration: __wasi_timestamp_t, -) -> Result<__wasi_errno_t, WasiError> { + duration: Timestamp, +) -> Result { debug!("wasi::thread_sleep"); let env = ctx.data(); let duration = Duration::from_nanos(duration as u64); env.sleep(duration)?; - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `thread_id()` @@ -3599,15 +3556,15 @@ pub fn thread_sleep( /// (threads indices are sequencial from zero) pub fn thread_id( ctx: FunctionEnvMut<'_, WasiEnv>, - ret_tid: WasmPtr<__wasi_tid_t, M>, -) -> __wasi_errno_t { + ret_tid: WasmPtr, +) -> Errno { debug!("wasi::thread_id"); let env = ctx.data(); - let tid: __wasi_tid_t = env.id.into(); + let tid: Tid = env.id.into(); let memory = env.memory_view(&ctx); wasi_try_mem!(ret_tid.write(&memory, tid)); - __WASI_ESUCCESS + Errno::Success } /// ### `thread_join()` @@ -3617,10 +3574,7 @@ pub fn thread_id( /// ## Parameters /// /// * `tid` - Handle of the thread to wait on -pub fn thread_join( - ctx: FunctionEnvMut<'_, WasiEnv>, - tid: __wasi_tid_t, -) -> Result<__wasi_errno_t, WasiError> { +pub fn thread_join(ctx: FunctionEnvMut<'_, WasiEnv>, tid: Tid) -> Result { debug!("wasi::thread_join"); let env = ctx.data(); @@ -3636,9 +3590,9 @@ pub fn thread_join( } env.yield_now()?; } - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } else { - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } } @@ -3648,36 +3602,33 @@ pub fn thread_join( pub fn thread_parallelism( ctx: FunctionEnvMut<'_, WasiEnv>, ret_parallelism: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::thread_parallelism"); let env = ctx.data(); let parallelism = wasi_try!(env.runtime().thread_parallelism().map_err(|err| { - let err: __wasi_errno_t = err.into(); + let err: Errno = err.into(); err })); - let parallelism: M::Offset = wasi_try!(parallelism.try_into().map_err(|_| __WASI_EOVERFLOW)); + let parallelism: M::Offset = wasi_try!(parallelism.try_into().map_err(|_| Errno::Overflow)); let memory = env.memory_view(&ctx); wasi_try_mem!(ret_parallelism.write(&memory, parallelism)); - __WASI_ESUCCESS + Errno::Success } /// ### `getpid()` /// Returns the handle of the current process -pub fn getpid( - ctx: FunctionEnvMut<'_, WasiEnv>, - ret_pid: WasmPtr<__wasi_pid_t, M>, -) -> __wasi_errno_t { +pub fn getpid(ctx: FunctionEnvMut<'_, WasiEnv>, ret_pid: WasmPtr) -> Errno { debug!("wasi::getpid"); let env = ctx.data(); let pid = env.runtime().getpid(); if let Some(pid) = pid { let memory = env.memory_view(&ctx); - wasi_try_mem!(ret_pid.write(&memory, pid as __wasi_pid_t)); - __WASI_ESUCCESS + wasi_try_mem!(ret_pid.write(&memory, pid as Pid)); + Errno::Success } else { - __WASI_ENOTSUP + Errno::Notsup } } @@ -3693,7 +3644,7 @@ pub fn getpid( pub fn thread_exit( ctx: FunctionEnvMut<'_, WasiEnv>, exitcode: __wasi_exitcode_t, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { debug!("wasi::thread_exit"); Err(WasiError::Exit(exitcode)) } @@ -3732,7 +3683,7 @@ pub fn process_spawn( working_dir: WasmPtr, working_dir_len: M::Offset, ret_handles: WasmPtr<__wasi_bus_handles_t, M>, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); let memory = env.memory_view(&ctx); @@ -3803,7 +3754,7 @@ pub fn process_spawn( wasi_try_mem_bus!(ret_handles.write(&memory, handles)); - __BUS_ESUCCESS + BusErrno::Success } /// Spawns a new bus process for a particular web WebAssembly @@ -3824,7 +3775,7 @@ pub fn bus_open_local( name_len: M::Offset, reuse: __wasi_bool_t, ret_bid: WasmPtr<__wasi_bid_t, M>, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); let memory = env.memory_view(&ctx); @@ -3859,7 +3810,7 @@ pub fn bus_open_remote( token: WasmPtr, token_len: M::Offset, ret_bid: WasmPtr<__wasi_bid_t, M>, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); let memory = env.memory_view(&ctx); @@ -3882,7 +3833,7 @@ fn bus_open_local_internal( instance: Option, token: Option, ret_bid: WasmPtr<__wasi_bid_t, M>, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); let memory = env.memory_view(&ctx); @@ -3894,7 +3845,7 @@ fn bus_open_local_internal( if let Some(bid) = guard.process_reuse.get(&name) { if guard.processes.contains_key(bid) { wasi_try_mem_bus!(ret_bid.write(&memory, (*bid).into())); - return __BUS_ESUCCESS; + return BusErrno::Success; } } } @@ -3930,7 +3881,7 @@ fn bus_open_local_internal( wasi_try_mem_bus!(ret_bid.write(&memory, bid.into())); - __BUS_ESUCCESS + BusErrno::Success } /// Closes a bus process and releases all associated resources @@ -3938,7 +3889,7 @@ fn bus_open_local_internal( /// ## Parameters /// /// * `bid` - Handle of the bus process handle to be closed -pub fn bus_close(ctx: FunctionEnvMut<'_, WasiEnv>, bid: __wasi_bid_t) -> __bus_errno_t { +pub fn bus_close(ctx: FunctionEnvMut<'_, WasiEnv>, bid: __wasi_bid_t) -> BusErrno { trace!("wasi::bus_close (bid={})", bid); let bid: WasiBusProcessId = bid.into(); @@ -3946,7 +3897,7 @@ pub fn bus_close(ctx: FunctionEnvMut<'_, WasiEnv>, bid: __wasi_bid_t) -> __bus_e let mut guard = env.state.threading.lock().unwrap(); guard.processes.remove(&bid); - __BUS_EUNSUPPORTED + BusErrno::Unsupported } /// Invokes a call within a running bus process. @@ -3970,7 +3921,7 @@ pub fn bus_call( buf: WasmPtr, buf_len: M::Offset, ret_cid: WasmPtr<__wasi_cid_t, M>, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); let memory = env.memory_view(&ctx); @@ -3983,7 +3934,7 @@ pub fn bus_call( buf_len ); - __BUS_EUNSUPPORTED + BusErrno::Unsupported } /// Invokes a call within the context of another call @@ -4007,7 +3958,7 @@ pub fn bus_subcall( buf: WasmPtr, buf_len: M::Offset, ret_cid: WasmPtr<__wasi_cid_t, M>, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); let memory = env.memory_view(&ctx); @@ -4020,7 +3971,7 @@ pub fn bus_subcall( buf_len ); - __BUS_EUNSUPPORTED + BusErrno::Unsupported } /// Polls for any outstanding events from a particular @@ -4039,20 +3990,20 @@ pub fn bus_subcall( /// Returns the number of events that have occured pub fn bus_poll( ctx: FunctionEnvMut<'_, WasiEnv>, - timeout: __wasi_timestamp_t, + timeout: Timestamp, events: WasmPtr, nevents: M::Offset, malloc: WasmPtr, malloc_len: M::Offset, ret_nevents: WasmPtr, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); let memory = env.memory_view(&ctx); let malloc = unsafe { get_input_str_bus!(&memory, malloc, malloc_len) }; trace!("wasi::bus_poll (timeout={}, malloc={})", timeout, malloc); - __BUS_EUNSUPPORTED + BusErrno::Unsupported } /// Replies to a call that was made to this process @@ -4071,7 +4022,7 @@ pub fn call_reply( format: __wasi_busdataformat_t, buf: WasmPtr, buf_len: M::Offset, -) -> __bus_errno_t { +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); trace!( @@ -4081,7 +4032,7 @@ pub fn call_reply( buf_len ); - __BUS_EUNSUPPORTED + BusErrno::Unsupported } /// Causes a fault on a particular call that was made @@ -4095,13 +4046,13 @@ pub fn call_reply( pub fn call_fault( ctx: FunctionEnvMut<'_, WasiEnv>, cid: __wasi_cid_t, - fault: __bus_errno_t, -) -> __bus_errno_t { + fault: BusErrno, +) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); debug!("wasi::call_fault (cid={}, fault={})", cid, fault); - __BUS_EUNSUPPORTED + BusErrno::Unsupported } /// Closes a bus call based on its bus call handle @@ -4109,12 +4060,12 @@ pub fn call_fault( /// ## Parameters /// /// * `cid` - Handle of the bus call handle to be dropped -pub fn call_close(ctx: FunctionEnvMut<'_, WasiEnv>, cid: __wasi_cid_t) -> __bus_errno_t { +pub fn call_close(ctx: FunctionEnvMut<'_, WasiEnv>, cid: __wasi_cid_t) -> BusErrno { let env = ctx.data(); let bus = env.runtime.bus(); trace!("wasi::call_close (cid={})", cid); - __BUS_EUNSUPPORTED + BusErrno::Unsupported } /// ### `ws_connect()` @@ -4131,8 +4082,8 @@ pub fn ws_connect( ctx: FunctionEnvMut<'_, WasiEnv>, url: WasmPtr, url_len: M::Offset, - ret_sock: WasmPtr<__wasi_fd_t, M>, -) -> __wasi_errno_t { + ret_sock: WasmPtr, +) -> Errno { debug!("wasi::ws_connect"); let env = ctx.data(); let memory = env.memory_view(&ctx); @@ -4155,12 +4106,14 @@ pub fn ws_connect( false, "socket".to_string(), ); - let rights = super::state::all_socket_rights(); - let fd = wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode)); + let rights = Rights::all_socket(); + let fd = wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode)); wasi_try_mem!(ret_sock.write(&memory, fd)); - __WASI_ESUCCESS + Errno::Success } /// ### `http_request()` @@ -4189,7 +4142,7 @@ pub fn http_request( headers_len: M::Offset, gzip: __wasi_bool_t, ret_handles: WasmPtr<__wasi_http_handles_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::http_request"); let env = ctx.data(); let memory = env.memory_view(&ctx); @@ -4200,7 +4153,7 @@ pub fn http_request( let gzip = match gzip { __WASI_BOOL_FALSE => false, __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, + _ => return Errno::Inval, }; let socket = wasi_try!(env @@ -4265,17 +4218,23 @@ pub fn http_request( false, "http_headers".to_string(), ); - let rights = super::state::all_socket_rights(); + let rights = Rights::all_socket(); let handles = __wasi_http_handles_t { - req: wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode_req)), - res: wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode_res)), - hdr: wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode_hdr)), + req: wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode_req)), + res: wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode_res)), + hdr: wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode_hdr)), }; wasi_try_mem!(ret_handles.write(&memory, handles)); - __WASI_ESUCCESS + Errno::Success } /// ### `http_status()` @@ -4288,16 +4247,16 @@ pub fn http_request( /// status of this HTTP request pub fn http_status( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, status: WasmPtr<__wasi_http_status_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::http_status"); let env = ctx.data(); let memory = env.memory_view(&ctx); let ref_status = status.deref(&memory); - let http_status = wasi_try!(__sock_actor(&ctx, sock, 0, |socket| { + let http_status = wasi_try!(__sock_actor(&ctx, sock, Rights::empty(), |socket| { socket.http_status() })); @@ -4314,7 +4273,7 @@ pub fn http_status( wasi_try_mem!(ref_status.write(status)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_bridge()` @@ -4331,44 +4290,44 @@ pub fn port_bridge( network_len: M::Offset, token: WasmPtr, token_len: M::Offset, - security: __wasi_streamsecurity_t, -) -> __wasi_errno_t { + security: Streamsecurity, +) -> Errno { debug!("wasi::port_bridge"); let env = ctx.data(); let memory = env.memory_view(&ctx); let network = unsafe { get_input_str!(&memory, network, network_len) }; let token = unsafe { get_input_str!(&memory, token, token_len) }; let security = match security { - __WASI_STREAM_SECURITY_UNENCRYPTED => StreamSecurity::Unencrypted, - __WASI_STREAM_SECURITY_ANY_ENCRYPTION => StreamSecurity::AnyEncyption, - __WASI_STREAM_SECURITY_CLASSIC_ENCRYPTION => StreamSecurity::ClassicEncryption, - __WASI_STREAM_SECURITY_DOUBLE_ENCRYPTION => StreamSecurity::DoubleEncryption, - _ => return __WASI_EINVAL, + Streamsecurity::Unencrypted => StreamSecurity::Unencrypted, + Streamsecurity::AnyEncryption => StreamSecurity::AnyEncyption, + Streamsecurity::ClassicEncryption => StreamSecurity::ClassicEncryption, + Streamsecurity::DoubleEncryption => StreamSecurity::DoubleEncryption, + _ => return Errno::Inval, }; wasi_try!(env .net() .bridge(network.as_str(), token.as_str(), security) .map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_unbridge()` /// Disconnects from a remote network -pub fn port_unbridge(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_unbridge(ctx: FunctionEnvMut<'_, WasiEnv>) -> Errno { debug!("wasi::port_unbridge"); let env = ctx.data(); wasi_try!(env.net().unbridge().map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_dhcp_acquire()` /// Acquires a set of IP addresses using DHCP -pub fn port_dhcp_acquire(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_dhcp_acquire(ctx: FunctionEnvMut<'_, WasiEnv>) -> Errno { debug!("wasi::port_dhcp_acquire"); let env = ctx.data(); wasi_try!(env.net().dhcp_acquire().map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_addr_add()` @@ -4380,7 +4339,7 @@ pub fn port_dhcp_acquire(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { pub fn port_addr_add( ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_cidr_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_addr_add"); let env = ctx.data(); let memory = env.memory_view(&ctx); @@ -4389,7 +4348,7 @@ pub fn port_addr_add( .net() .ip_add(cidr.ip, cidr.prefix) .map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_addr_remove()` @@ -4401,22 +4360,22 @@ pub fn port_addr_add( pub fn port_addr_remove( ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_addr_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_addr_remove"); let env = ctx.data(); let memory = env.memory_view(&ctx); let ip = wasi_try!(super::state::read_ip(&memory, ip)); wasi_try!(env.net().ip_remove(ip).map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_addr_clear()` /// Clears all the addresses on the local port -pub fn port_addr_clear(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_addr_clear(ctx: FunctionEnvMut<'_, WasiEnv>) -> Errno { debug!("wasi::port_addr_clear"); let env = ctx.data(); wasi_try!(env.net().ip_clear().map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_mac()` @@ -4424,14 +4383,14 @@ pub fn port_addr_clear(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { pub fn port_mac( ctx: FunctionEnvMut<'_, WasiEnv>, ret_mac: WasmPtr<__wasi_hardwareaddress_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_mac"); let env = ctx.data(); let memory = env.memory_view(&ctx); let mac = wasi_try!(env.net().mac().map_err(net_error_into_wasi_err)); let mac = __wasi_hardwareaddress_t { octs: mac }; wasi_try_mem!(ret_mac.write(&memory, mac)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_ip_list()` @@ -4451,21 +4410,21 @@ pub fn port_addr_list( ctx: FunctionEnvMut<'_, WasiEnv>, addrs: WasmPtr<__wasi_cidr_t, M>, naddrs: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_addr_list"); let env = ctx.data(); let memory = env.memory_view(&ctx); let max_addrs = wasi_try_mem!(naddrs.read(&memory)); - let max_addrs: u64 = wasi_try!(max_addrs.try_into().map_err(|_| __WASI_EOVERFLOW)); + let max_addrs: u64 = wasi_try!(max_addrs.try_into().map_err(|_| Errno::Overflow)); let ref_addrs = wasi_try_mem!(addrs.slice(&memory, wasi_try!(to_offset::(max_addrs as usize)))); let addrs = wasi_try!(env.net().ip_list().map_err(net_error_into_wasi_err)); - let addrs_len: M::Offset = wasi_try!(addrs.len().try_into().map_err(|_| __WASI_EOVERFLOW)); + let addrs_len: M::Offset = wasi_try!(addrs.len().try_into().map_err(|_| Errno::Overflow)); wasi_try_mem!(naddrs.write(&memory, addrs_len)); if addrs.len() as u64 > max_addrs { - return __WASI_EOVERFLOW; + return Errno::Overflow; } for n in 0..addrs.len() { @@ -4473,7 +4432,7 @@ pub fn port_addr_list( super::state::write_cidr(&memory, nip.as_ptr::(), *addrs.get(n).unwrap()); } - __WASI_ESUCCESS + Errno::Success } /// ### `port_gateway_set()` @@ -4485,14 +4444,14 @@ pub fn port_addr_list( pub fn port_gateway_set( ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_addr_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_gateway_set"); let env = ctx.data(); let memory = env.memory_view(&ctx); let ip = wasi_try!(super::state::read_ip(&memory, ip)); wasi_try!(env.net().gateway_set(ip).map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_route_add()` @@ -4503,7 +4462,7 @@ pub fn port_route_add( via_router: WasmPtr<__wasi_addr_t, M>, preferred_until: WasmPtr<__wasi_option_timestamp_t, M>, expires_at: WasmPtr<__wasi_option_timestamp_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_route_add"); let env = ctx.data(); let memory = env.memory_view(&ctx); @@ -4513,20 +4472,20 @@ pub fn port_route_add( let preferred_until = match preferred_until.tag { __WASI_OPTION_NONE => None, __WASI_OPTION_SOME => Some(Duration::from_nanos(preferred_until.u)), - _ => return __WASI_EINVAL, + _ => return Errno::Inval, }; let expires_at = wasi_try_mem!(expires_at.read(&memory)); let expires_at = match expires_at.tag { __WASI_OPTION_NONE => None, __WASI_OPTION_SOME => Some(Duration::from_nanos(expires_at.u)), - _ => return __WASI_EINVAL, + _ => return Errno::Inval, }; wasi_try!(env .net() .route_add(cidr, via_router, preferred_until, expires_at) .map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_route_remove()` @@ -4534,22 +4493,22 @@ pub fn port_route_add( pub fn port_route_remove( ctx: FunctionEnvMut<'_, WasiEnv>, ip: WasmPtr<__wasi_addr_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_route_remove"); let env = ctx.data(); let memory = env.memory_view(&ctx); let ip = wasi_try!(super::state::read_ip(&memory, ip)); wasi_try!(env.net().route_remove(ip).map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_route_clear()` /// Clears all the routes in the local port -pub fn port_route_clear(ctx: FunctionEnvMut<'_, WasiEnv>) -> __wasi_errno_t { +pub fn port_route_clear(ctx: FunctionEnvMut<'_, WasiEnv>) -> Errno { debug!("wasi::port_route_clear"); let env = ctx.data(); wasi_try!(env.net().route_clear().map_err(net_error_into_wasi_err)); - __WASI_ESUCCESS + Errno::Success } /// ### `port_route_list()` @@ -4565,22 +4524,22 @@ pub fn port_route_list( ctx: FunctionEnvMut<'_, WasiEnv>, routes: WasmPtr<__wasi_route_t, M>, nroutes: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::port_route_list"); let env = ctx.data(); let memory = env.memory_view(&ctx); let nroutes = nroutes.deref(&memory); let max_routes: usize = wasi_try!(wasi_try_mem!(nroutes.read()) .try_into() - .map_err(|_| __WASI_EINVAL)); + .map_err(|_| Errno::Inval)); let ref_routes = wasi_try_mem!(routes.slice(&memory, wasi_try!(to_offset::(max_routes)))); let routes = wasi_try!(env.net().route_list().map_err(net_error_into_wasi_err)); - let routes_len: M::Offset = wasi_try!(routes.len().try_into().map_err(|_| __WASI_EINVAL)); + let routes_len: M::Offset = wasi_try!(routes.len().try_into().map_err(|_| Errno::Inval)); wasi_try_mem!(nroutes.write(routes_len)); if routes.len() > max_routes { - return __WASI_EOVERFLOW; + return Errno::Overflow; } for n in 0..routes.len() { @@ -4592,7 +4551,7 @@ pub fn port_route_list( ); } - __WASI_ESUCCESS + Errno::Success } /// ### `sock_shutdown()` @@ -4604,9 +4563,9 @@ pub fn port_route_list( /// * `how` - Which channels on the socket to shut down. pub fn sock_shutdown( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, how: __wasi_sdflags_t, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_shutdown"); let both = __WASI_SHUT_RD | __WASI_SHUT_WR; @@ -4614,43 +4573,45 @@ pub fn sock_shutdown( __WASI_SHUT_RD => std::net::Shutdown::Read, __WASI_SHUT_WR => std::net::Shutdown::Write, a if a == both => std::net::Shutdown::Both, - _ => return __WASI_EINVAL, + _ => return Errno::Inval, }; wasi_try!(__sock_actor_mut( &ctx, sock, - __WASI_RIGHT_SOCK_SHUTDOWN, + Rights::SOCK_SHUTDOWN, |socket| { socket.shutdown(how) } )); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_status()` /// Returns the current status of a socket pub fn sock_status( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - ret_status: WasmPtr<__wasi_sockstatus_t, M>, -) -> __wasi_errno_t { + sock: WasiFd, + ret_status: WasmPtr, +) -> Errno { debug!("wasi::sock_status"); - let status = wasi_try!(__sock_actor(&ctx, sock, 0, |socket| { socket.status() })); + let status = wasi_try!(__sock_actor(&ctx, sock, Rights::empty(), |socket| { + socket.status() + })); use super::state::WasiSocketStatus; let status = match status { - WasiSocketStatus::Opening => __WASI_SOCK_STATUS_OPENING, - WasiSocketStatus::Opened => __WASI_SOCK_STATUS_OPENED, - WasiSocketStatus::Closed => __WASI_SOCK_STATUS_CLOSED, - WasiSocketStatus::Failed => __WASI_SOCK_STATUS_FAILED, + WasiSocketStatus::Opening => Sockstatus::Opening, + WasiSocketStatus::Opened => Sockstatus::Opened, + WasiSocketStatus::Closed => Sockstatus::Closed, + WasiSocketStatus::Failed => Sockstatus::Failed, }; let env = ctx.data(); let memory = env.memory_view(&ctx); wasi_try_mem!(ret_status.write(&memory, status)); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_addr_local()` @@ -4666,12 +4627,12 @@ pub fn sock_status( /// * `fd` - Socket that the address is bound to pub fn sock_addr_local( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, ret_addr: WasmPtr<__wasi_addr_port_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_addr_local"); - let addr = wasi_try!(__sock_actor(&ctx, sock, 0, |socket| { + let addr = wasi_try!(__sock_actor(&ctx, sock, Rights::empty(), |socket| { socket.addr_local() })); let memory = ctx.data().memory_view(&ctx); @@ -4681,7 +4642,7 @@ pub fn sock_addr_local( addr.ip(), addr.port() )); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_addr_peer()` @@ -4697,13 +4658,15 @@ pub fn sock_addr_local( /// * `fd` - Socket that the address is bound to pub fn sock_addr_peer( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, ro_addr: WasmPtr<__wasi_addr_port_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_addr_peer"); let env = ctx.data(); - let addr = wasi_try!(__sock_actor(&ctx, sock, 0, |socket| { socket.addr_peer() })); + let addr = wasi_try!(__sock_actor(&ctx, sock, Rights::empty(), |socket| { + socket.addr_peer() + })); let memory = env.memory_view(&ctx); wasi_try!(super::state::write_ip_port( &memory, @@ -4711,7 +4674,7 @@ pub fn sock_addr_peer( addr.ip(), addr.port() )); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_open()` @@ -4735,18 +4698,18 @@ pub fn sock_addr_peer( /// The file descriptor of the socket that has been opened. pub fn sock_open( ctx: FunctionEnvMut<'_, WasiEnv>, - af: __wasi_addressfamily_t, - ty: __wasi_socktype_t, + af: Addressfamily, + ty: Socktype, pt: __wasi_sockproto_t, - ro_sock: WasmPtr<__wasi_fd_t, M>, -) -> __wasi_errno_t { + ro_sock: WasmPtr, +) -> Errno { debug!("wasi::sock_open"); let env = ctx.data(); let (memory, state, mut inodes) = env.get_memory_and_wasi_state_and_inodes_mut(&ctx, 0); let kind = match ty { - __WASI_SOCK_TYPE_STREAM | __WASI_SOCK_TYPE_DGRAM => Kind::Socket { + Socktype::Stream | Socktype::Dgram => Kind::Socket { socket: InodeSocket::new(InodeSocketKind::PreSocket { family: af, ty, @@ -4763,7 +4726,7 @@ pub fn sock_open( accept_timeout: None, }), }, - _ => return __WASI_ENOTSUP, + _ => return Errno::Notsup, }; let inode = state.fs.create_inode_with_default_stat( @@ -4772,12 +4735,14 @@ pub fn sock_open( false, "socket".to_string(), ); - let rights = super::state::all_socket_rights(); - let fd = wasi_try!(state.fs.create_fd(rights, rights, 0, 0, inode)); + let rights = Rights::all_socket(); + let fd = wasi_try!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode)); wasi_try_mem!(ro_sock.write(&memory, fd)); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_set_opt_flag()` @@ -4791,23 +4756,23 @@ pub fn sock_open( /// * `flag` - Value to set the option to pub fn sock_set_opt_flag( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: WasiFd, + opt: Sockoption, flag: __wasi_bool_t, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_set_opt_flag(ty={})", opt); let flag = match flag { __WASI_BOOL_FALSE => false, __WASI_BOOL_TRUE => true, - _ => return __WASI_EINVAL, + _ => return Errno::Inval, }; let option: super::state::WasiSocketOption = opt.into(); - wasi_try!(__sock_actor_mut(&ctx, sock, 0, |socket| { + wasi_try!(__sock_actor_mut(&ctx, sock, Rights::empty(), |socket| { socket.set_opt_flag(option, flag) })); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_get_opt_flag()` @@ -4820,16 +4785,16 @@ pub fn sock_set_opt_flag( /// * `sockopt` - Socket option to be retrieved pub fn sock_get_opt_flag( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: WasiFd, + opt: Sockoption, ret_flag: WasmPtr<__wasi_bool_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_get_opt_flag(ty={})", opt); let env = ctx.data(); let memory = env.memory_view(&ctx); let option: super::state::WasiSocketOption = opt.into(); - let flag = wasi_try!(__sock_actor(&ctx, sock, 0, |socket| { + let flag = wasi_try!(__sock_actor(&ctx, sock, Rights::empty(), |socket| { socket.get_opt_flag(option) })); let flag = match flag { @@ -4839,7 +4804,7 @@ pub fn sock_get_opt_flag( wasi_try_mem!(ret_flag.write(&memory, flag)); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_set_opt_time()` @@ -4852,10 +4817,10 @@ pub fn sock_get_opt_flag( /// * `time` - Value to set the time to pub fn sock_set_opt_time( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: WasiFd, + opt: Sockoption, time: WasmPtr<__wasi_option_timestamp_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_set_opt_time(ty={})", opt); let env = ctx.data(); @@ -4864,23 +4829,23 @@ pub fn sock_set_opt_time( let time = match time.tag { __WASI_OPTION_NONE => None, __WASI_OPTION_SOME => Some(Duration::from_nanos(time.u)), - _ => return __WASI_EINVAL, + _ => return Errno::Inval, }; let ty = match opt { - __WASI_SOCK_OPTION_RECV_TIMEOUT => wasmer_vnet::TimeType::ReadTimeout, - __WASI_SOCK_OPTION_SEND_TIMEOUT => wasmer_vnet::TimeType::WriteTimeout, - __WASI_SOCK_OPTION_CONNECT_TIMEOUT => wasmer_vnet::TimeType::ConnectTimeout, - __WASI_SOCK_OPTION_ACCEPT_TIMEOUT => wasmer_vnet::TimeType::AcceptTimeout, - __WASI_SOCK_OPTION_LINGER => wasmer_vnet::TimeType::Linger, - _ => return __WASI_EINVAL, + Sockoption::RecvTimeout => wasmer_vnet::TimeType::ReadTimeout, + Sockoption::SendTimeout => wasmer_vnet::TimeType::WriteTimeout, + Sockoption::ConnectTimeout => wasmer_vnet::TimeType::ConnectTimeout, + Sockoption::AcceptTimeout => wasmer_vnet::TimeType::AcceptTimeout, + Sockoption::Linger => wasmer_vnet::TimeType::Linger, + _ => return Errno::Inval, }; let option: super::state::WasiSocketOption = opt.into(); - wasi_try!(__sock_actor_mut(&ctx, sock, 0, |socket| { + wasi_try!(__sock_actor_mut(&ctx, sock, Rights::empty(), |socket| { socket.set_opt_time(ty, time) })); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_get_opt_time()` @@ -4892,24 +4857,24 @@ pub fn sock_set_opt_time( /// * `sockopt` - Socket option to be retrieved pub fn sock_get_opt_time( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: WasiFd, + opt: Sockoption, ret_time: WasmPtr<__wasi_option_timestamp_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_get_opt_time(ty={})", opt); let env = ctx.data(); let memory = env.memory_view(&ctx); let ty = match opt { - __WASI_SOCK_OPTION_RECV_TIMEOUT => wasmer_vnet::TimeType::ReadTimeout, - __WASI_SOCK_OPTION_SEND_TIMEOUT => wasmer_vnet::TimeType::WriteTimeout, - __WASI_SOCK_OPTION_CONNECT_TIMEOUT => wasmer_vnet::TimeType::ConnectTimeout, - __WASI_SOCK_OPTION_ACCEPT_TIMEOUT => wasmer_vnet::TimeType::AcceptTimeout, - __WASI_SOCK_OPTION_LINGER => wasmer_vnet::TimeType::Linger, - _ => return __WASI_EINVAL, + Sockoption::RecvTimeout => wasmer_vnet::TimeType::ReadTimeout, + Sockoption::SendTimeout => wasmer_vnet::TimeType::WriteTimeout, + Sockoption::ConnectTimeout => wasmer_vnet::TimeType::ConnectTimeout, + Sockoption::AcceptTimeout => wasmer_vnet::TimeType::AcceptTimeout, + Sockoption::Linger => wasmer_vnet::TimeType::Linger, + _ => return Errno::Inval, }; - let time = wasi_try!(__sock_actor(&ctx, sock, 0, |socket| { + let time = wasi_try!(__sock_actor(&ctx, sock, Rights::empty(), |socket| { socket.opt_time(ty) })); let time = match time { @@ -4919,13 +4884,13 @@ pub fn sock_get_opt_time( }, Some(timeout) => __wasi_option_timestamp_t { tag: __WASI_OPTION_SOME, - u: timeout.as_nanos() as __wasi_timestamp_t, + u: timeout.as_nanos() as Timestamp, }, }; wasi_try_mem!(ret_time.write(&memory, time)); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_set_opt_size() @@ -4939,32 +4904,32 @@ pub fn sock_get_opt_time( /// * `size` - Buffer size pub fn sock_set_opt_size( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, - size: __wasi_filesize_t, -) -> __wasi_errno_t { + sock: WasiFd, + opt: Sockoption, + size: Filesize, +) -> Errno { debug!("wasi::sock_set_opt_size(ty={})", opt); let ty = match opt { - __WASI_SOCK_OPTION_RECV_TIMEOUT => wasmer_vnet::TimeType::ReadTimeout, - __WASI_SOCK_OPTION_SEND_TIMEOUT => wasmer_vnet::TimeType::WriteTimeout, - __WASI_SOCK_OPTION_CONNECT_TIMEOUT => wasmer_vnet::TimeType::ConnectTimeout, - __WASI_SOCK_OPTION_ACCEPT_TIMEOUT => wasmer_vnet::TimeType::AcceptTimeout, - __WASI_SOCK_OPTION_LINGER => wasmer_vnet::TimeType::Linger, - _ => return __WASI_EINVAL, + Sockoption::RecvTimeout => wasmer_vnet::TimeType::ReadTimeout, + Sockoption::SendTimeout => wasmer_vnet::TimeType::WriteTimeout, + Sockoption::ConnectTimeout => wasmer_vnet::TimeType::ConnectTimeout, + Sockoption::AcceptTimeout => wasmer_vnet::TimeType::AcceptTimeout, + Sockoption::Linger => wasmer_vnet::TimeType::Linger, + _ => return Errno::Inval, }; let option: super::state::WasiSocketOption = opt.into(); - wasi_try!(__sock_actor_mut(&ctx, sock, 0, |socket| { + wasi_try!(__sock_actor_mut(&ctx, sock, Rights::empty(), |socket| { match opt { - __WASI_SOCK_OPTION_RECV_BUF_SIZE => socket.set_recv_buf_size(size as usize), - __WASI_SOCK_OPTION_SEND_BUF_SIZE => socket.set_send_buf_size(size as usize), - __WASI_SOCK_OPTION_TTL => socket.set_ttl(size as u32), - __WASI_SOCK_OPTION_MULTICAST_TTL_V4 => socket.set_multicast_ttl_v4(size as u32), - _ => Err(__WASI_EINVAL), + Sockoption::RecvBufSize => socket.set_recv_buf_size(size as usize), + Sockoption::SendBufSize => socket.set_send_buf_size(size as usize), + Sockoption::Ttl => socket.set_ttl(size as u32), + Sockoption::MulticastTtlV4 => socket.set_multicast_ttl_v4(size as u32), + _ => Err(Errno::Inval), } })); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_get_opt_size()` @@ -4977,32 +4942,26 @@ pub fn sock_set_opt_size( /// * `sockopt` - Socket option to be retrieved pub fn sock_get_opt_size( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, - ret_size: WasmPtr<__wasi_filesize_t, M>, -) -> __wasi_errno_t { + sock: WasiFd, + opt: Sockoption, + ret_size: WasmPtr, +) -> Errno { debug!("wasi::sock_get_opt_size(ty={})", opt); let env = ctx.data(); let memory = env.memory_view(&ctx); - let size = wasi_try!(__sock_actor(&ctx, sock, 0, |socket| { + let size = wasi_try!(__sock_actor(&ctx, sock, Rights::empty(), |socket| { match opt { - __WASI_SOCK_OPTION_RECV_BUF_SIZE => { - socket.recv_buf_size().map(|a| a as __wasi_filesize_t) - } - __WASI_SOCK_OPTION_SEND_BUF_SIZE => { - socket.send_buf_size().map(|a| a as __wasi_filesize_t) - } - __WASI_SOCK_OPTION_TTL => socket.ttl().map(|a| a as __wasi_filesize_t), - __WASI_SOCK_OPTION_MULTICAST_TTL_V4 => { - socket.multicast_ttl_v4().map(|a| a as __wasi_filesize_t) - } - _ => Err(__WASI_EINVAL), + Sockoption::RecvBufSize => socket.recv_buf_size().map(|a| a as Filesize), + Sockoption::SendBufSize => socket.send_buf_size().map(|a| a as Filesize), + Sockoption::Ttl => socket.ttl().map(|a| a as Filesize), + Sockoption::MulticastTtlV4 => socket.multicast_ttl_v4().map(|a| a as Filesize), + _ => Err(Errno::Inval), } })); wasi_try_mem!(ret_size.write(&memory, size)); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_join_multicast_v4()` @@ -5015,20 +4974,20 @@ pub fn sock_get_opt_size( /// * `interface` - Interface that will join pub fn sock_join_multicast_v4( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, multiaddr: WasmPtr<__wasi_addr_ip4_t, M>, iface: WasmPtr<__wasi_addr_ip4_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_join_multicast_v4"); let env = ctx.data(); let memory = env.memory_view(&ctx); let multiaddr = wasi_try!(super::state::read_ip_v4(&memory, multiaddr)); let iface = wasi_try!(super::state::read_ip_v4(&memory, iface)); - wasi_try!(__sock_actor_mut(&ctx, sock, 0, |socket| { + wasi_try!(__sock_actor_mut(&ctx, sock, Rights::empty(), |socket| { socket.join_multicast_v4(multiaddr, iface) })); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_leave_multicast_v4()` @@ -5041,20 +5000,20 @@ pub fn sock_join_multicast_v4( /// * `interface` - Interface that will left pub fn sock_leave_multicast_v4( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, multiaddr: WasmPtr<__wasi_addr_ip4_t, M>, iface: WasmPtr<__wasi_addr_ip4_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_leave_multicast_v4"); let env = ctx.data(); let memory = env.memory_view(&ctx); let multiaddr = wasi_try!(super::state::read_ip_v4(&memory, multiaddr)); let iface = wasi_try!(super::state::read_ip_v4(&memory, iface)); - wasi_try!(__sock_actor_mut(&ctx, sock, 0, |socket| { + wasi_try!(__sock_actor_mut(&ctx, sock, Rights::empty(), |socket| { socket.leave_multicast_v4(multiaddr, iface) })); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_join_multicast_v6()` @@ -5067,19 +5026,19 @@ pub fn sock_leave_multicast_v4( /// * `interface` - Interface that will join pub fn sock_join_multicast_v6( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, multiaddr: WasmPtr<__wasi_addr_ip6_t, M>, iface: u32, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_join_multicast_v6"); let env = ctx.data(); let memory = env.memory_view(&ctx); let multiaddr = wasi_try!(super::state::read_ip_v6(&memory, multiaddr)); - wasi_try!(__sock_actor_mut(&ctx, sock, 0, |socket| { + wasi_try!(__sock_actor_mut(&ctx, sock, Rights::empty(), |socket| { socket.join_multicast_v6(multiaddr, iface) })); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_leave_multicast_v6()` @@ -5092,19 +5051,19 @@ pub fn sock_join_multicast_v6( /// * `interface` - Interface that will left pub fn sock_leave_multicast_v6( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, multiaddr: WasmPtr<__wasi_addr_ip6_t, M>, iface: u32, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_leave_multicast_v6"); let env = ctx.data(); let memory = env.memory_view(&ctx); let multiaddr = wasi_try!(super::state::read_ip_v6(&memory, multiaddr)); - wasi_try!(__sock_actor_mut(&ctx, sock, 0, |socket| { + wasi_try!(__sock_actor_mut(&ctx, sock, Rights::empty(), |socket| { socket.leave_multicast_v6(multiaddr, iface) })); - __WASI_ESUCCESS + Errno::Success } /// ### `sock_bind()` @@ -5117,22 +5076,19 @@ pub fn sock_leave_multicast_v6( /// * `addr` - Address to bind the socket to pub fn sock_bind( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, addr: WasmPtr<__wasi_addr_port_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_bind"); let env = ctx.data(); let memory = env.memory_view(&ctx); let addr = wasi_try!(super::state::read_ip_port(&memory, addr)); let addr = SocketAddr::new(addr.0, addr.1); - wasi_try!(__sock_upgrade( - &ctx, - sock, - __WASI_RIGHT_SOCK_BIND, - |socket| { socket.bind(env.net(), addr) } - )); - __WASI_ESUCCESS + wasi_try!(__sock_upgrade(&ctx, sock, Rights::SOCK_BIND, |socket| { + socket.bind(env.net(), addr) + })); + Errno::Success } /// ### `sock_listen()` @@ -5149,20 +5105,17 @@ pub fn sock_bind( /// * `backlog` - Maximum size of the queue for pending connections pub fn sock_listen( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, backlog: M::Offset, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_listen"); let env = ctx.data(); - let backlog: usize = wasi_try!(backlog.try_into().map_err(|_| __WASI_EINVAL)); - wasi_try!(__sock_upgrade( - &ctx, - sock, - __WASI_RIGHT_SOCK_BIND, - |socket| { socket.listen(env.net(), backlog) } - )); - __WASI_ESUCCESS + let backlog: usize = wasi_try!(backlog.try_into().map_err(|_| Errno::Inval)); + wasi_try!(__sock_upgrade(&ctx, sock, Rights::SOCK_BIND, |socket| { + socket.listen(env.net(), backlog) + })); + Errno::Success } /// ### `sock_accept()` @@ -5179,11 +5132,11 @@ pub fn sock_listen( /// New socket connection pub fn sock_accept( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - fd_flags: __wasi_fdflags_t, - ro_fd: WasmPtr<__wasi_fd_t, M>, + sock: WasiFd, + fd_flags: Fdflags, + ro_fd: WasmPtr, ro_addr: WasmPtr<__wasi_addr_port_t, M>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { debug!("wasi::sock_accept"); let env = ctx.data(); @@ -5192,18 +5145,18 @@ pub fn sock_accept( let (_, state) = env.get_memory_and_wasi_state(&ctx, 0); loop { wasi_try_ok!( - match __sock_actor(&ctx, sock, __WASI_RIGHT_SOCK_ACCEPT, |socket| socket + match __sock_actor(&ctx, sock, Rights::SOCK_ACCEPT, |socket| socket .accept_timeout(fd_flags, Duration::from_millis(5))) { Ok(a) => { ret = a; break; } - Err(__WASI_ETIMEDOUT) => { + Err(Errno::Timedout) => { env.yield_now()?; continue; } - Err(__WASI_EAGAIN) => { + Err(Errno::Again) => { env.sleep(Duration::from_millis(5))?; continue; } @@ -5226,8 +5179,10 @@ pub fn sock_accept( "socket".to_string(), ); - let rights = super::state::all_socket_rights(); - let fd = wasi_try_ok!(state.fs.create_fd(rights, rights, 0, 0, inode)); + let rights = Rights::all_socket(); + let fd = wasi_try_ok!(state + .fs + .create_fd(rights, rights, Fdflags::empty(), 0, inode)); wasi_try_mem_ok!(ro_fd.write(&memory, fd)); wasi_try_ok!(super::state::write_ip_port( @@ -5237,7 +5192,7 @@ pub fn sock_accept( addr.port() )); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `sock_connect()` @@ -5254,22 +5209,19 @@ pub fn sock_accept( /// * `addr` - Address of the socket to connect to pub fn sock_connect( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, addr: WasmPtr<__wasi_addr_port_t, M>, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::sock_connect"); let env = ctx.data(); let memory = env.memory_view(&ctx); let addr = wasi_try!(super::state::read_ip_port(&memory, addr)); let addr = SocketAddr::new(addr.0, addr.1); - wasi_try!(__sock_upgrade( - &ctx, - sock, - __WASI_RIGHT_SOCK_CONNECT, - |socket| { socket.connect(env.net(), addr) } - )); - __WASI_ESUCCESS + wasi_try!(__sock_upgrade(&ctx, sock, Rights::SOCK_CONNECT, |socket| { + socket.connect(env.net(), addr) + })); + Errno::Success } /// ### `sock_recv()` @@ -5287,31 +5239,28 @@ pub fn sock_connect( /// Number of bytes stored in ri_data and message flags. pub fn sock_recv( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, ri_data: WasmPtr<__wasi_iovec_t, M>, ri_data_len: M::Offset, _ri_flags: __wasi_riflags_t, ro_data_len: WasmPtr, ro_flags: WasmPtr<__wasi_roflags_t, M>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { debug!("wasi::sock_recv"); let env = ctx.data(); let memory = env.memory_view(&ctx); let iovs_arr = wasi_try_mem_ok!(ri_data.slice(&memory, ri_data_len)); - let bytes_read = wasi_try_ok!(__sock_actor_mut( - &ctx, - sock, - __WASI_RIGHT_SOCK_RECV, - |socket| { socket.recv(&memory, iovs_arr) } - )); - let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| __WASI_EOVERFLOW)); + let bytes_read = wasi_try_ok!(__sock_actor_mut(&ctx, sock, Rights::SOCK_RECV, |socket| { + socket.recv(&memory, iovs_arr) + })); + let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(ro_flags.write(&memory, 0)); wasi_try_mem_ok!(ro_data_len.write(&memory, bytes_read)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `sock_recv_from()` @@ -5329,14 +5278,14 @@ pub fn sock_recv( /// Number of bytes stored in ri_data and message flags. pub fn sock_recv_from( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, ri_data: WasmPtr<__wasi_iovec_t, M>, ri_data_len: M::Offset, _ri_flags: __wasi_riflags_t, ro_data_len: WasmPtr, ro_flags: WasmPtr<__wasi_roflags_t, M>, ro_addr: WasmPtr<__wasi_addr_port_t, M>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { debug!("wasi::sock_recv_from"); let env = ctx.data(); @@ -5346,15 +5295,15 @@ pub fn sock_recv_from( let bytes_read = wasi_try_ok!(__sock_actor_mut( &ctx, sock, - __WASI_RIGHT_SOCK_RECV_FROM, + Rights::SOCK_RECV_FROM, |socket| { socket.recv_from(&memory, iovs_arr, ro_addr) } )); - let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| __WASI_EOVERFLOW)); + let bytes_read: M::Offset = wasi_try_ok!(bytes_read.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(ro_flags.write(&memory, 0)); wasi_try_mem_ok!(ro_data_len.write(&memory, bytes_read)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `sock_send()` @@ -5372,30 +5321,27 @@ pub fn sock_recv_from( /// Number of bytes transmitted. pub fn sock_send( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, si_data: WasmPtr<__wasi_ciovec_t, M>, si_data_len: M::Offset, _si_flags: __wasi_siflags_t, ret_data_len: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { debug!("wasi::sock_send"); let env = ctx.data(); let memory = env.memory_view(&ctx); let iovs_arr = wasi_try_mem_ok!(si_data.slice(&memory, si_data_len)); - let bytes_written = wasi_try_ok!(__sock_actor_mut( - &ctx, - sock, - __WASI_RIGHT_SOCK_SEND, - |socket| { socket.send(&memory, iovs_arr) } - )); + let bytes_written = wasi_try_ok!(__sock_actor_mut(&ctx, sock, Rights::SOCK_SEND, |socket| { + socket.send(&memory, iovs_arr) + })); let bytes_written: M::Offset = - wasi_try_ok!(bytes_written.try_into().map_err(|_| __WASI_EOVERFLOW)); + wasi_try_ok!(bytes_written.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(ret_data_len.write(&memory, bytes_written)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `sock_send_to()` @@ -5414,13 +5360,13 @@ pub fn sock_send( /// Number of bytes transmitted. pub fn sock_send_to( ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, + sock: WasiFd, si_data: WasmPtr<__wasi_ciovec_t, M>, si_data_len: M::Offset, _si_flags: __wasi_siflags_t, addr: WasmPtr<__wasi_addr_port_t, M>, ret_data_len: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { debug!("wasi::sock_send_to"); let env = ctx.data(); @@ -5430,15 +5376,15 @@ pub fn sock_send_to( let bytes_written = wasi_try_ok!(__sock_actor_mut( &ctx, sock, - __WASI_RIGHT_SOCK_SEND_TO, + Rights::SOCK_SEND_TO, |socket| { socket.send_to::(&memory, iovs_arr, addr) } )); let bytes_written: M::Offset = - wasi_try_ok!(bytes_written.try_into().map_err(|_| __WASI_EOVERFLOW)); + wasi_try_ok!(bytes_written.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem_ok!(ret_data_len.write(&memory, bytes_written as M::Offset)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `sock_send_file()` @@ -5455,12 +5401,12 @@ pub fn sock_send_to( /// Number of bytes transmitted. pub unsafe fn sock_send_file( mut ctx: FunctionEnvMut<'_, WasiEnv>, - sock: __wasi_fd_t, - in_fd: __wasi_fd_t, - offset: __wasi_filesize_t, - mut count: __wasi_filesize_t, - ret_sent: WasmPtr<__wasi_filesize_t, M>, -) -> Result<__wasi_errno_t, WasiError> { + sock: WasiFd, + in_fd: WasiFd, + offset: Filesize, + mut count: Filesize, + ret_sent: WasmPtr, +) -> Result { debug!("wasi::send_file"); let env = ctx.data(); let (memory, mut state, inodes) = env.get_memory_and_wasi_state_and_inodes(&ctx, 0); @@ -5468,12 +5414,12 @@ pub unsafe fn sock_send_file( // Set the offset of the file { let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try_ok!(fd_map.get_mut(&in_fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try_ok!(fd_map.get_mut(&in_fd).ok_or(Errno::Badf)); fd_entry.offset = offset as u64; } // Enter a loop that will process all the data - let mut total_written: __wasi_filesize_t = 0; + let mut total_written: Filesize = 0; while (count > 0) { let mut buf = [0; 4096]; let sub_count = count.min(4096); @@ -5491,14 +5437,14 @@ pub unsafe fn sock_send_file( if let Some(ref mut stdin) = guard.deref_mut() { wasi_try_ok!(stdin.read(&mut buf).map_err(map_io_err)) } else { - return Ok(__WASI_EBADF); + return Ok(Errno::Badf); } } - __WASI_STDOUT_FILENO | __WASI_STDERR_FILENO => return Ok(__WASI_EINVAL), + __WASI_STDOUT_FILENO | __WASI_STDERR_FILENO => return Ok(Errno::Inval), _ => { - if !has_rights(fd_entry.rights, __WASI_RIGHT_FD_READ) { + if !fd_entry.rights.contains(Rights::FD_READ) { // TODO: figure out the error to return when lacking rights - return Ok(__WASI_EACCES); + return Ok(Errno::Access); } let offset = fd_entry.offset as usize; @@ -5519,7 +5465,7 @@ pub unsafe fn sock_send_file( ); wasi_try_ok!(handle.read(&mut buf).map_err(map_io_err)) } else { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } } Kind::Socket { socket } => { @@ -5529,10 +5475,10 @@ pub unsafe fn sock_send_file( wasi_try_ok!(pipe.read(&mut buf).map_err(map_io_err)) } Kind::Dir { .. } | Kind::Root { .. } => { - return Ok(__WASI_EISDIR); + return Ok(Errno::Isdir); } Kind::EventNotifications { .. } => { - return Ok(__WASI_EINVAL); + return Ok(Errno::Inval); } Kind::Symlink { .. } => unimplemented!("Symlinks in wasi::fd_read"), Kind::Buffer { buffer } => { @@ -5544,7 +5490,7 @@ pub unsafe fn sock_send_file( // reborrow let mut fd_map = state.fs.fd_map.write().unwrap(); - let fd_entry = wasi_try_ok!(fd_map.get_mut(&in_fd).ok_or(__WASI_EBADF)); + let fd_entry = wasi_try_ok!(fd_map.get_mut(&in_fd).ok_or(Errno::Badf)); fd_entry.offset += bytes_read as u64; bytes_read @@ -5552,21 +5498,17 @@ pub unsafe fn sock_send_file( }; // Write it down to the socket - let bytes_written = wasi_try_ok!(__sock_actor_mut( - &ctx, - sock, - __WASI_RIGHT_SOCK_SEND, - |socket| { - let buf = (buf[..]).to_vec(); + let bytes_written = + wasi_try_ok!(__sock_actor_mut(&ctx, sock, Rights::SOCK_SEND, |socket| { + let buf = (&buf[..]).to_vec(); socket.send_bytes::(Bytes::from(buf)) - } - )); + })); total_written += bytes_written as u64; } - wasi_try_mem_ok!(ret_sent.write(&memory, total_written as __wasi_filesize_t)); + wasi_try_mem_ok!(ret_sent.write(&memory, total_written as Filesize)); - Ok(__WASI_ESUCCESS) + Ok(Errno::Success) } /// ### `resolve()` @@ -5595,10 +5537,10 @@ pub fn resolve( addrs: WasmPtr<__wasi_addr_t, M>, naddrs: M::Offset, ret_naddrs: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { debug!("wasi::resolve"); - let naddrs: usize = wasi_try!(naddrs.try_into().map_err(|_| __WASI_EINVAL)); + let naddrs: usize = wasi_try!(naddrs.try_into().map_err(|_| Errno::Inval)); let env = ctx.data(); let memory = env.memory_view(&ctx); let host_str = unsafe { get_input_str!(&memory, host, host_len) }; @@ -5617,8 +5559,8 @@ pub fn resolve( idx += 1; } - let idx: M::Offset = wasi_try!(idx.try_into().map_err(|_| __WASI_EOVERFLOW)); + let idx: M::Offset = wasi_try!(idx.try_into().map_err(|_| Errno::Overflow)); wasi_try_mem!(ret_naddrs.write(&memory, idx)); - __WASI_ESUCCESS + Errno::Success } diff --git a/lib/wasi/src/syscalls/unix/mod.rs b/lib/wasi/src/syscalls/unix/mod.rs index 9e3a5e35d16..a079f9c66e8 100644 --- a/lib/wasi/src/syscalls/unix/mod.rs +++ b/lib/wasi/src/syscalls/unix/mod.rs @@ -5,17 +5,18 @@ use libc::{ }; use std::mem; use wasmer::WasmRef; +use wasmer_wasi_types_generated::wasi::{Errno, Snapshot0Clockid, Timestamp}; pub fn platform_clock_res_get( - clock_id: __wasi_clockid_t, - resolution: WasmRef<__wasi_timestamp_t>, -) -> Result { + clock_id: Snapshot0Clockid, + resolution: WasmRef, +) -> Result { let unix_clock_id = match clock_id { - __WASI_CLOCK_MONOTONIC => CLOCK_MONOTONIC, - __WASI_CLOCK_PROCESS_CPUTIME_ID => CLOCK_PROCESS_CPUTIME_ID, - __WASI_CLOCK_REALTIME => CLOCK_REALTIME, - __WASI_CLOCK_THREAD_CPUTIME_ID => CLOCK_THREAD_CPUTIME_ID, - _ => return Err(__WASI_EINVAL), + Snapshot0Clockid::Monotonic => CLOCK_MONOTONIC, + Snapshot0Clockid::ProcessCputimeId => CLOCK_PROCESS_CPUTIME_ID, + Snapshot0Clockid::Realtime => CLOCK_REALTIME, + Snapshot0Clockid::ThreadCputimeId => CLOCK_THREAD_CPUTIME_ID, + _ => return Err(Errno::Inval), }; let (output, timespec_out) = unsafe { @@ -31,15 +32,15 @@ pub fn platform_clock_res_get( } pub fn platform_clock_time_get( - clock_id: __wasi_clockid_t, - precision: __wasi_timestamp_t, -) -> Result { + clock_id: Snapshot0Clockid, + precision: Timestamp, +) -> Result { let unix_clock_id = match clock_id { - __WASI_CLOCK_MONOTONIC => CLOCK_MONOTONIC, - __WASI_CLOCK_PROCESS_CPUTIME_ID => CLOCK_PROCESS_CPUTIME_ID, - __WASI_CLOCK_REALTIME => CLOCK_REALTIME, - __WASI_CLOCK_THREAD_CPUTIME_ID => CLOCK_THREAD_CPUTIME_ID, - _ => return Err(__WASI_EINVAL), + Snapshot0Clockid::Monotonic => CLOCK_MONOTONIC, + Snapshot0Clockid::ProcessCputimeId => CLOCK_PROCESS_CPUTIME_ID, + Snapshot0Clockid::Realtime => CLOCK_REALTIME, + Snapshot0Clockid::ThreadCputimeId => CLOCK_THREAD_CPUTIME_ID, + _ => return Err(Errno::Inval), }; let (output, timespec_out) = unsafe { diff --git a/lib/wasi/src/syscalls/wasi.rs b/lib/wasi/src/syscalls/wasi.rs index b2575f6e53c..63109da0baf 100644 --- a/lib/wasi/src/syscalls/wasi.rs +++ b/lib/wasi/src/syscalls/wasi.rs @@ -1,7 +1,10 @@ #![deny(dead_code)] use crate::{WasiEnv, WasiError, WasiState, WasiThread}; -use wasmer::{StoreMut, Memory, Memory32, MemorySize, WasmPtr, WasmSlice}; -use wasmer_wasi_types::*; +use wasmer::{Memory, Memory32, MemorySize, StoreMut, WasmPtr, WasmSlice}; +use wasmer_wasi_types::{ + wasi::{Errno, Event, Fd as WasiFd, Filesize, Fstflags, Fstflags, Timestamp, Whence}, + *, +}; type MemoryType = Memory32; type MemoryOffset = u32; @@ -10,7 +13,7 @@ pub(crate) fn args_get( ctx: FunctionEnvMut, argv: WasmPtr, MemoryType>, argv_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::args_get::(ctx, argv, argv_buf) } @@ -18,24 +21,24 @@ pub(crate) fn args_sizes_get( ctx: FunctionEnvMut, argc: WasmPtr, argv_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::args_sizes_get::(ctx, argc, argv_buf_size) } pub(crate) fn clock_res_get( ctx: FunctionEnvMut, - clock_id: __wasi_clockid_t, - resolution: WasmPtr<__wasi_timestamp_t, MemoryType>, -) -> __wasi_errno_t { + clock_id: wasi_snapshot0::Clockid, + resolution: WasmPtr, +) -> Errno { super::clock_res_get::(ctx, clock_id, resolution) } pub(crate) fn clock_time_get( ctx: FunctionEnvMut, - clock_id: __wasi_clockid_t, - precision: __wasi_timestamp_t, - time: WasmPtr<__wasi_timestamp_t, MemoryType>, -) -> __wasi_errno_t { + clock_id: wasi_snapshot0::Clockid, + precision: Timestamp, + time: WasmPtr, +) -> Errno { super::clock_time_get::(ctx, clock_id, precision, time) } @@ -43,7 +46,7 @@ pub(crate) fn environ_get( ctx: FunctionEnvMut, environ: WasmPtr, MemoryType>, environ_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::environ_get::(ctx, environ, environ_buf) } @@ -51,218 +54,214 @@ pub(crate) fn environ_sizes_get( ctx: FunctionEnvMut, environ_count: WasmPtr, environ_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::environ_sizes_get::(ctx, environ_count, environ_buf_size) } pub(crate) fn fd_advise( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, + fd: WasiFd, + offset: Filesize, + len: Filesize, advice: __wasi_advice_t, -) -> __wasi_errno_t { +) -> Errno { super::fd_advise(ctx, fd, offset, len, advice) } pub(crate) fn fd_allocate( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: WasiFd, + offset: Filesize, + len: Filesize, +) -> Errno { super::fd_allocate(ctx, fd, offset, len) } -pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: WasiFd) -> Errno { super::fd_close(ctx, fd) } -pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: WasiFd) -> Errno { super::fd_datasync(ctx, fd) } pub(crate) fn fd_fdstat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - buf_ptr: WasmPtr<__wasi_fdstat_t, MemoryType>, -) -> __wasi_errno_t { + fd: WasiFd, + buf_ptr: WasmPtr, +) -> Errno { super::fd_fdstat_get::(ctx, fd, buf_ptr) } pub(crate) fn fd_fdstat_set_flags( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - flags: __wasi_fdflags_t, -) -> __wasi_errno_t { + fd: WasiFd, + flags: WasiFdflags, +) -> Errno { super::fd_fdstat_set_flags(ctx, fd, flags) } pub(crate) fn fd_fdstat_set_rights( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, -) -> __wasi_errno_t { +) -> Errno { super::fd_fdstat_set_rights(ctx, fd, fs_rights_base, fs_rights_inheriting) } pub(crate) fn fd_filestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - buf: WasmPtr<__wasi_filestat_t, MemoryType>, -) -> __wasi_errno_t { + fd: WasiFd, + buf: WasmPtr, +) -> Errno { super::fd_filestat_get::(ctx, fd, buf) } pub(crate) fn fd_filestat_set_size( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - st_size: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: WasiFd, + st_size: Filesize, +) -> Errno { super::fd_filestat_set_size(ctx, fd, st_size) } pub(crate) fn fd_filestat_set_times( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + fd: WasiFd, + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { super::fd_filestat_set_times(ctx, fd, st_atim, st_mtim, fst_flags) } pub(crate) fn fd_pread( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, - offset: __wasi_filesize_t, + offset: Filesize, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_pread::(ctx, fd, iovs, iovs_len, offset, nread) } pub(crate) fn fd_prestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, buf: WasmPtr<__wasi_prestat_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::fd_prestat_get::(ctx, fd, buf) } pub(crate) fn fd_prestat_dir_name( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::fd_prestat_dir_name::(ctx, fd, path, path_len) } pub(crate) fn fd_pwrite( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, - offset: __wasi_filesize_t, + offset: Filesize, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_pwrite::(ctx, fd, iovs, iovs_len, offset, nwritten) } pub(crate) fn fd_read( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_read::(ctx, fd, iovs, iovs_len, nread) } pub(crate) fn fd_readdir( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, buf: WasmPtr, buf_len: MemoryOffset, cookie: __wasi_dircookie_t, bufused: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::fd_readdir::(ctx, fd, buf, buf_len, cookie, bufused) } -pub(crate) fn fd_renumber( - ctx: FunctionEnvMut, - from: __wasi_fd_t, - to: __wasi_fd_t, -) -> __wasi_errno_t { +pub(crate) fn fd_renumber(ctx: FunctionEnvMut, from: WasiFd, to: WasiFd) -> Errno { super::fd_renumber(ctx, from, to) } pub(crate) fn fd_seek( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, offset: __wasi_filedelta_t, - whence: __wasi_whence_t, - newoffset: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { + whence: Whence, + newoffset: WasmPtr, +) -> Result { super::fd_seek::(ctx, fd, offset, whence, newoffset) } -pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: WasiFd) -> Errno { super::fd_sync(ctx, fd) } pub(crate) fn fd_tell( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> __wasi_errno_t { + fd: WasiFd, + offset: WasmPtr, +) -> Errno { super::fd_tell::(ctx, fd, offset) } pub(crate) fn fd_write( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_write::(ctx, fd, iovs, iovs_len, nwritten) } pub(crate) fn path_create_directory( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_create_directory::(ctx, fd, path, path_len) } pub(crate) fn path_filestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, - buf: WasmPtr<__wasi_filestat_t, MemoryType>, -) -> __wasi_errno_t { + buf: WasmPtr, +) -> Errno { super::path_filestat_get::(ctx, fd, flags, path, path_len, buf) } pub(crate) fn path_filestat_set_times( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { super::path_filestat_set_times::( ctx, fd, flags, path, path_len, st_atim, st_mtim, fst_flags, ) @@ -270,14 +269,14 @@ pub(crate) fn path_filestat_set_times( pub(crate) fn path_link( ctx: FunctionEnvMut, - old_fd: __wasi_fd_t, + old_fd: WasiFd, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, old_path_len: MemoryOffset, - new_fd: __wasi_fd_t, + new_fd: WasiFd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_link::( ctx, old_fd, @@ -292,16 +291,16 @@ pub(crate) fn path_link( pub(crate) fn path_open( ctx: FunctionEnvMut, - dirfd: __wasi_fd_t, + dirfd: WasiFd, dirflags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, o_flags: __wasi_oflags_t, fs_rights_base: __wasi_rights_t, fs_rights_inheriting: __wasi_rights_t, - fs_flags: __wasi_fdflags_t, - fd: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + fs_flags: WasiFdflags, + fd: WasmPtr, +) -> Errno { super::path_open::( ctx, dirfd, @@ -318,34 +317,34 @@ pub(crate) fn path_open( pub(crate) fn path_readlink( ctx: FunctionEnvMut, - dir_fd: __wasi_fd_t, + dir_fd: WasiFd, path: WasmPtr, path_len: MemoryOffset, buf: WasmPtr, buf_len: MemoryOffset, buf_used: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::path_readlink::(ctx, dir_fd, path, path_len, buf, buf_len, buf_used) } pub(crate) fn path_remove_directory( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_remove_directory::(ctx, fd, path, path_len) } pub(crate) fn path_rename( ctx: FunctionEnvMut, - old_fd: __wasi_fd_t, + old_fd: WasiFd, old_path: WasmPtr, old_path_len: MemoryOffset, - new_fd: __wasi_fd_t, + new_fd: WasiFd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_rename::( ctx, old_fd, @@ -361,29 +360,29 @@ pub(crate) fn path_symlink( ctx: FunctionEnvMut, old_path: WasmPtr, old_path_len: MemoryOffset, - fd: __wasi_fd_t, + fd: WasiFd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_symlink::(ctx, old_path, old_path_len, fd, new_path, new_path_len) } pub(crate) fn path_unlink_file( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: WasiFd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_unlink_file::(ctx, fd, path, path_len) } pub(crate) fn poll_oneoff( ctx: FunctionEnvMut, in_: WasmPtr<__wasi_subscription_t, MemoryType>, - out_: WasmPtr<__wasi_event_t, MemoryType>, + out_: WasmPtr, nsubscriptions: MemoryOffset, nevents: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::poll_oneoff::(ctx, in_, out_, nsubscriptions, nevents) } @@ -394,7 +393,7 @@ pub(crate) fn proc_exit( super::proc_exit(ctx, code) } -pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> __wasi_errno_t { +pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> Errno { super::proc_raise(ctx, sig) } @@ -402,23 +401,23 @@ pub(crate) fn random_get( ctx: FunctionEnvMut, buf: WasmPtr, buf_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::random_get::(ctx, buf, buf_len) } -pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result { super::sched_yield(ctx) } pub(crate) fn sock_recv( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: WasiFd, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, ri_flags: __wasi_riflags_t, ro_data_len: WasmPtr, ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_recv::( ctx, sock, @@ -432,19 +431,19 @@ pub(crate) fn sock_recv( pub(crate) fn sock_send( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: WasiFd, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, si_flags: __wasi_siflags_t, ret_data_len: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_send::(ctx, sock, si_data, si_data_len, si_flags, ret_data_len) } pub(crate) fn sock_shutdown( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: WasiFd, how: __wasi_sdflags_t, -) -> __wasi_errno_t { +) -> Errno { super::sock_shutdown(ctx, sock, how) } diff --git a/lib/wasi/src/syscalls/wasix32.rs b/lib/wasi/src/syscalls/wasix32.rs index 5cb6899c3ef..68ead9c1de2 100644 --- a/lib/wasi/src/syscalls/wasix32.rs +++ b/lib/wasi/src/syscalls/wasix32.rs @@ -2,6 +2,11 @@ use crate::{WasiEnv, WasiError, WasiState, WasiThread}; use wasmer::{FunctionEnvMut, Memory, Memory32, MemorySize, StoreMut, WasmPtr, WasmSlice}; use wasmer_wasi_types::*; +use wasmer_wasi_types_generated::wasi::{ + Addressfamily, Advice, BusErrno, Clockid, Dircookie, Errno, Event, Fd, Fdflags, Fdstat, + Filesize, Filestat, Fstflags, Pid, Rights, Sockoption, Sockstatus, Socktype, Streamsecurity, + Subscription, Tid, Timestamp, Tty, Whence, +}; type MemoryType = Memory32; type MemoryOffset = u32; @@ -10,7 +15,7 @@ pub(crate) fn args_get( ctx: FunctionEnvMut, argv: WasmPtr, MemoryType>, argv_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::args_get::(ctx, argv, argv_buf) } @@ -18,24 +23,24 @@ pub(crate) fn args_sizes_get( ctx: FunctionEnvMut, argc: WasmPtr, argv_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::args_sizes_get::(ctx, argc, argv_buf_size) } pub(crate) fn clock_res_get( ctx: FunctionEnvMut, - clock_id: __wasi_clockid_t, - resolution: WasmPtr<__wasi_timestamp_t, MemoryType>, -) -> __wasi_errno_t { + clock_id: Clockid, + resolution: WasmPtr, +) -> Errno { super::clock_res_get::(ctx, clock_id, resolution) } pub(crate) fn clock_time_get( ctx: FunctionEnvMut, - clock_id: __wasi_clockid_t, - precision: __wasi_timestamp_t, - time: WasmPtr<__wasi_timestamp_t, MemoryType>, -) -> __wasi_errno_t { + clock_id: Clockid, + precision: Timestamp, + time: WasmPtr, +) -> Errno { super::clock_time_get::(ctx, clock_id, precision, time) } @@ -43,7 +48,7 @@ pub(crate) fn environ_get( ctx: FunctionEnvMut, environ: WasmPtr, MemoryType>, environ_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::environ_get::(ctx, environ, environ_buf) } @@ -51,218 +56,210 @@ pub(crate) fn environ_sizes_get( ctx: FunctionEnvMut, environ_count: WasmPtr, environ_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::environ_sizes_get::(ctx, environ_count, environ_buf_size) } pub(crate) fn fd_advise( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, - advice: __wasi_advice_t, -) -> __wasi_errno_t { + fd: Fd, + offset: Filesize, + len: Filesize, + advice: Advice, +) -> Errno { super::fd_advise(ctx, fd, offset, len, advice) } pub(crate) fn fd_allocate( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: Fd, + offset: Filesize, + len: Filesize, +) -> Errno { super::fd_allocate(ctx, fd, offset, len) } -pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: Fd) -> Errno { super::fd_close(ctx, fd) } -pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: Fd) -> Errno { super::fd_datasync(ctx, fd) } pub(crate) fn fd_fdstat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - buf_ptr: WasmPtr<__wasi_fdstat_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + buf_ptr: WasmPtr, +) -> Errno { super::fd_fdstat_get::(ctx, fd, buf_ptr) } -pub(crate) fn fd_fdstat_set_flags( - ctx: FunctionEnvMut, - fd: __wasi_fd_t, - flags: __wasi_fdflags_t, -) -> __wasi_errno_t { +pub(crate) fn fd_fdstat_set_flags(ctx: FunctionEnvMut, fd: Fd, flags: Fdflags) -> Errno { super::fd_fdstat_set_flags(ctx, fd, flags) } pub(crate) fn fd_fdstat_set_rights( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - fs_rights_base: __wasi_rights_t, - fs_rights_inheriting: __wasi_rights_t, -) -> __wasi_errno_t { + fd: Fd, + fs_rights_base: Rights, + fs_rights_inheriting: Rights, +) -> Errno { super::fd_fdstat_set_rights(ctx, fd, fs_rights_base, fs_rights_inheriting) } pub(crate) fn fd_filestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - buf: WasmPtr<__wasi_filestat_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + buf: WasmPtr, +) -> Errno { super::fd_filestat_get::(ctx, fd, buf) } pub(crate) fn fd_filestat_set_size( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - st_size: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: Fd, + st_size: Filesize, +) -> Errno { super::fd_filestat_set_size(ctx, fd, st_size) } pub(crate) fn fd_filestat_set_times( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + fd: Fd, + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { super::fd_filestat_set_times(ctx, fd, st_atim, st_mtim, fst_flags) } pub(crate) fn fd_pread( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, - offset: __wasi_filesize_t, + offset: Filesize, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_pread::(ctx, fd, iovs, iovs_len, offset, nread) } pub(crate) fn fd_prestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, buf: WasmPtr<__wasi_prestat_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::fd_prestat_get::(ctx, fd, buf) } pub(crate) fn fd_prestat_dir_name( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::fd_prestat_dir_name::(ctx, fd, path, path_len) } pub(crate) fn fd_pwrite( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, - offset: __wasi_filesize_t, + offset: Filesize, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_pwrite::(ctx, fd, iovs, iovs_len, offset, nwritten) } pub(crate) fn fd_read( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_read::(ctx, fd, iovs, iovs_len, nread) } pub(crate) fn fd_readdir( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, buf: WasmPtr, buf_len: MemoryOffset, - cookie: __wasi_dircookie_t, + cookie: Dircookie, bufused: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::fd_readdir::(ctx, fd, buf, buf_len, cookie, bufused) } -pub(crate) fn fd_renumber( - ctx: FunctionEnvMut, - from: __wasi_fd_t, - to: __wasi_fd_t, -) -> __wasi_errno_t { +pub(crate) fn fd_renumber(ctx: FunctionEnvMut, from: Fd, to: Fd) -> Errno { super::fd_renumber(ctx, from, to) } pub(crate) fn fd_seek( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, offset: __wasi_filedelta_t, - whence: __wasi_whence_t, - newoffset: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { + whence: Whence, + newoffset: WasmPtr, +) -> Result { super::fd_seek::(ctx, fd, offset, whence, newoffset) } -pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: Fd) -> Errno { super::fd_sync(ctx, fd) } pub(crate) fn fd_tell( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + offset: WasmPtr, +) -> Errno { super::fd_tell::(ctx, fd, offset) } pub(crate) fn fd_write( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_write::(ctx, fd, iovs, iovs_len, nwritten) } pub(crate) fn path_create_directory( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_create_directory::(ctx, fd, path, path_len) } pub(crate) fn path_filestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, - buf: WasmPtr<__wasi_filestat_t, MemoryType>, -) -> __wasi_errno_t { + buf: WasmPtr, +) -> Errno { super::path_filestat_get::(ctx, fd, flags, path, path_len, buf) } pub(crate) fn path_filestat_set_times( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { super::path_filestat_set_times::( ctx, fd, flags, path, path_len, st_atim, st_mtim, fst_flags, ) @@ -270,14 +267,14 @@ pub(crate) fn path_filestat_set_times( pub(crate) fn path_link( ctx: FunctionEnvMut, - old_fd: __wasi_fd_t, + old_fd: Fd, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, old_path_len: MemoryOffset, - new_fd: __wasi_fd_t, + new_fd: Fd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_link::( ctx, old_fd, @@ -292,16 +289,16 @@ pub(crate) fn path_link( pub(crate) fn path_open( ctx: FunctionEnvMut, - dirfd: __wasi_fd_t, + dirfd: Fd, dirflags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, o_flags: __wasi_oflags_t, - fs_rights_base: __wasi_rights_t, - fs_rights_inheriting: __wasi_rights_t, - fs_flags: __wasi_fdflags_t, - fd: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + fs_rights_base: Rights, + fs_rights_inheriting: Rights, + fs_flags: Fdflags, + fd: WasmPtr, +) -> Errno { super::path_open::( ctx, dirfd, @@ -318,34 +315,34 @@ pub(crate) fn path_open( pub(crate) fn path_readlink( ctx: FunctionEnvMut, - dir_fd: __wasi_fd_t, + dir_fd: Fd, path: WasmPtr, path_len: MemoryOffset, buf: WasmPtr, buf_len: MemoryOffset, buf_used: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::path_readlink::(ctx, dir_fd, path, path_len, buf, buf_len, buf_used) } pub(crate) fn path_remove_directory( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_remove_directory::(ctx, fd, path, path_len) } pub(crate) fn path_rename( ctx: FunctionEnvMut, - old_fd: __wasi_fd_t, + old_fd: Fd, old_path: WasmPtr, old_path_len: MemoryOffset, - new_fd: __wasi_fd_t, + new_fd: Fd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_rename::( ctx, old_fd, @@ -361,29 +358,29 @@ pub(crate) fn path_symlink( ctx: FunctionEnvMut, old_path: WasmPtr, old_path_len: MemoryOffset, - fd: __wasi_fd_t, + fd: Fd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_symlink::(ctx, old_path, old_path_len, fd, new_path, new_path_len) } pub(crate) fn path_unlink_file( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_unlink_file::(ctx, fd, path, path_len) } pub(crate) fn poll_oneoff( ctx: FunctionEnvMut, - in_: WasmPtr<__wasi_subscription_t, MemoryType>, - out_: WasmPtr<__wasi_event_t, MemoryType>, + in_: WasmPtr, + out_: WasmPtr, nsubscriptions: MemoryOffset, nevents: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::poll_oneoff::(ctx, in_, out_, nsubscriptions, nevents) } @@ -394,7 +391,7 @@ pub(crate) fn proc_exit( super::proc_exit(ctx, code) } -pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> __wasi_errno_t { +pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> Errno { super::proc_raise(ctx, sig) } @@ -402,15 +399,15 @@ pub(crate) fn random_get( ctx: FunctionEnvMut, buf: WasmPtr, buf_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::random_get::(ctx, buf, buf_len) } pub(crate) fn fd_dup( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + ret_fd: WasmPtr, +) -> Errno { super::fd_dup::(ctx, fd, ret_fd) } @@ -418,30 +415,24 @@ pub(crate) fn fd_event( ctx: FunctionEnvMut, initial_val: u64, flags: __wasi_eventfdflags, - ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ret_fd: WasmPtr, +) -> Errno { super::fd_event(ctx, initial_val, flags, ret_fd) } pub(crate) fn fd_pipe( ctx: FunctionEnvMut, - ro_fd1: WasmPtr<__wasi_fd_t, MemoryType>, - ro_fd2: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ro_fd1: WasmPtr, + ro_fd2: WasmPtr, +) -> Errno { super::fd_pipe::(ctx, ro_fd1, ro_fd2) } -pub(crate) fn tty_get( - ctx: FunctionEnvMut, - tty_state: WasmPtr<__wasi_tty_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn tty_get(ctx: FunctionEnvMut, tty_state: WasmPtr) -> Errno { super::tty_get::(ctx, tty_state) } -pub(crate) fn tty_set( - ctx: FunctionEnvMut, - tty_state: WasmPtr<__wasi_tty_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn tty_set(ctx: FunctionEnvMut, tty_state: WasmPtr) -> Errno { super::tty_set::(ctx, tty_state) } @@ -449,7 +440,7 @@ pub(crate) fn getcwd( ctx: FunctionEnvMut, path: WasmPtr, path_len: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::getcwd::(ctx, path, path_len) } @@ -457,7 +448,7 @@ pub(crate) fn chdir( ctx: FunctionEnvMut, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::chdir::(ctx, path, path_len) } @@ -467,54 +458,45 @@ pub(crate) fn thread_spawn( method_len: MemoryOffset, user_data: u64, reactor: __wasi_bool_t, - ret_tid: WasmPtr<__wasi_tid_t, MemoryType>, -) -> __wasi_errno_t { + ret_tid: WasmPtr, +) -> Errno { super::thread_spawn::(ctx, method, method_len, user_data, reactor, ret_tid) } pub(crate) fn thread_sleep( ctx: FunctionEnvMut, - duration: __wasi_timestamp_t, -) -> Result<__wasi_errno_t, WasiError> { + duration: Timestamp, +) -> Result { super::thread_sleep(ctx, duration) } -pub(crate) fn thread_id( - ctx: FunctionEnvMut, - ret_tid: WasmPtr<__wasi_tid_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn thread_id(ctx: FunctionEnvMut, ret_tid: WasmPtr) -> Errno { super::thread_id::(ctx, ret_tid) } -pub(crate) fn thread_join( - ctx: FunctionEnvMut, - tid: __wasi_tid_t, -) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn thread_join(ctx: FunctionEnvMut, tid: Tid) -> Result { super::thread_join(ctx, tid) } pub(crate) fn thread_parallelism( ctx: FunctionEnvMut, ret_parallelism: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::thread_parallelism::(ctx, ret_parallelism) } pub(crate) fn thread_exit( ctx: FunctionEnvMut, exitcode: __wasi_exitcode_t, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::thread_exit(ctx, exitcode) } -pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result { super::sched_yield(ctx) } -pub(crate) fn getpid( - ctx: FunctionEnvMut, - ret_pid: WasmPtr<__wasi_pid_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn getpid(ctx: FunctionEnvMut, ret_pid: WasmPtr) -> Errno { super::getpid::(ctx, ret_pid) } @@ -533,7 +515,7 @@ pub(crate) fn process_spawn( working_dir: WasmPtr, working_dir_len: MemoryOffset, ret_handles: WasmPtr<__wasi_bus_handles_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::process_spawn::( ctx, name, @@ -558,7 +540,7 @@ pub(crate) fn bus_open_local( name_len: MemoryOffset, reuse: __wasi_bool_t, ret_bid: WasmPtr<__wasi_bid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_open_local::(ctx, name, name_len, reuse, ret_bid) } @@ -572,7 +554,7 @@ pub(crate) fn bus_open_remote( token: WasmPtr, token_len: MemoryOffset, ret_bid: WasmPtr<__wasi_bid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_open_remote::( ctx, name, @@ -586,7 +568,7 @@ pub(crate) fn bus_open_remote( ) } -pub(crate) fn bus_close(ctx: FunctionEnvMut, bid: __wasi_bid_t) -> __bus_errno_t { +pub(crate) fn bus_close(ctx: FunctionEnvMut, bid: __wasi_bid_t) -> BusErrno { super::bus_close(ctx, bid) } @@ -600,7 +582,7 @@ pub(crate) fn bus_call( buf: WasmPtr, buf_len: MemoryOffset, ret_cid: WasmPtr<__wasi_cid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_call::( ctx, bid, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid, ) @@ -616,7 +598,7 @@ pub(crate) fn bus_subcall( buf: WasmPtr, buf_len: MemoryOffset, ret_cid: WasmPtr<__wasi_cid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_subcall::( ctx, parent, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid, ) @@ -624,13 +606,13 @@ pub(crate) fn bus_subcall( pub(crate) fn bus_poll( ctx: FunctionEnvMut, - timeout: __wasi_timestamp_t, + timeout: Timestamp, events: WasmPtr, nevents: MemoryOffset, malloc: WasmPtr, malloc_len: MemoryOffset, ret_nevents: WasmPtr, -) -> __bus_errno_t { +) -> BusErrno { super::bus_poll::( ctx, timeout, @@ -648,19 +630,19 @@ pub(crate) fn call_reply( format: __wasi_busdataformat_t, buf: WasmPtr, buf_len: MemoryOffset, -) -> __bus_errno_t { +) -> BusErrno { super::call_reply::(ctx, cid, format, buf, buf_len) } pub(crate) fn call_fault( ctx: FunctionEnvMut, cid: __wasi_cid_t, - fault: __bus_errno_t, -) -> __bus_errno_t { + fault: BusErrno, +) -> BusErrno { super::call_fault(ctx, cid, fault) } -pub(crate) fn call_close(ctx: FunctionEnvMut, cid: __wasi_cid_t) -> __bus_errno_t { +pub(crate) fn call_close(ctx: FunctionEnvMut, cid: __wasi_cid_t) -> BusErrno { super::call_close(ctx, cid) } @@ -670,34 +652,34 @@ pub(crate) fn port_bridge( network_len: MemoryOffset, token: WasmPtr, token_len: MemoryOffset, - security: __wasi_streamsecurity_t, -) -> __wasi_errno_t { + security: Streamsecurity, +) -> Errno { super::port_bridge::(ctx, network, network_len, token, token_len, security) } -pub(crate) fn port_unbridge(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_unbridge(ctx: FunctionEnvMut) -> Errno { super::port_unbridge(ctx) } -pub(crate) fn port_dhcp_acquire(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_dhcp_acquire(ctx: FunctionEnvMut) -> Errno { super::port_dhcp_acquire(ctx) } pub(crate) fn port_addr_add( ctx: FunctionEnvMut, addr: WasmPtr<__wasi_cidr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_addr_add::(ctx, addr) } pub(crate) fn port_addr_remove( ctx: FunctionEnvMut, addr: WasmPtr<__wasi_addr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_addr_remove::(ctx, addr) } -pub(crate) fn port_addr_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_addr_clear(ctx: FunctionEnvMut) -> Errno { super::port_addr_clear(ctx) } @@ -705,21 +687,21 @@ pub(crate) fn port_addr_list( ctx: FunctionEnvMut, addrs: WasmPtr<__wasi_cidr_t, MemoryType>, naddrs: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::port_addr_list::(ctx, addrs, naddrs) } pub(crate) fn port_mac( ctx: FunctionEnvMut, ret_mac: WasmPtr<__wasi_hardwareaddress_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_mac::(ctx, ret_mac) } pub(crate) fn port_gateway_set( ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_gateway_set::(ctx, ip) } @@ -729,18 +711,18 @@ pub(crate) fn port_route_add( via_router: WasmPtr<__wasi_addr_t, MemoryType>, preferred_until: WasmPtr<__wasi_option_timestamp_t, MemoryType>, expires_at: WasmPtr<__wasi_option_timestamp_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_route_add::(ctx, cidr, via_router, preferred_until, expires_at) } pub(crate) fn port_route_remove( ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_route_remove::(ctx, ip) } -pub(crate) fn port_route_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_route_clear(ctx: FunctionEnvMut) -> Errno { super::port_route_clear(ctx) } @@ -748,7 +730,7 @@ pub(crate) fn port_route_list( ctx: FunctionEnvMut, routes: WasmPtr<__wasi_route_t, MemoryType>, nroutes: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::port_route_list::(ctx, routes, nroutes) } @@ -756,8 +738,8 @@ pub(crate) fn ws_connect( ctx: FunctionEnvMut, url: WasmPtr, url_len: MemoryOffset, - ret_sock: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ret_sock: WasmPtr, +) -> Errno { super::ws_connect::(ctx, url, url_len, ret_sock) } @@ -771,7 +753,7 @@ pub(crate) fn http_request( headers_len: MemoryOffset, gzip: __wasi_bool_t, ret_handles: WasmPtr<__wasi_http_handles_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::http_request::( ctx, url, @@ -787,183 +769,179 @@ pub(crate) fn http_request( pub(crate) fn http_status( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, status: WasmPtr<__wasi_http_status_t, MemoryType>, status_text: WasmPtr, status_text_len: WasmPtr, headers: WasmPtr, headers_len: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::http_status::(ctx, sock, status) } pub(crate) fn sock_status( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>, -) -> __wasi_errno_t { + sock: Fd, + ret_status: WasmPtr, +) -> Errno { super::sock_status::(ctx, sock, ret_status) } pub(crate) fn sock_addr_local( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ret_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_addr_local::(ctx, sock, ret_addr) } pub(crate) fn sock_addr_peer( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_addr_peer::(ctx, sock, ro_addr) } pub(crate) fn sock_open( ctx: FunctionEnvMut, - af: __wasi_addressfamily_t, - ty: __wasi_socktype_t, + af: Addressfamily, + ty: Socktype, pt: __wasi_sockproto_t, - ro_sock: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ro_sock: WasmPtr, +) -> Errno { super::sock_open::(ctx, af, ty, pt, ro_sock) } pub(crate) fn sock_set_opt_flag( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, flag: __wasi_bool_t, -) -> __wasi_errno_t { +) -> Errno { super::sock_set_opt_flag(ctx, sock, opt, flag) } pub(crate) fn sock_get_opt_flag( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, ret_flag: WasmPtr<__wasi_bool_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_get_opt_flag::(ctx, sock, opt, ret_flag) } pub fn sock_set_opt_time( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_set_opt_time(ctx, sock, opt, time) } pub fn sock_get_opt_time( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, ret_time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_get_opt_time(ctx, sock, opt, ret_time) } pub fn sock_set_opt_size( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, - size: __wasi_filesize_t, -) -> __wasi_errno_t { + sock: Fd, + opt: Sockoption, + size: Filesize, +) -> Errno { super::sock_set_opt_size(ctx, sock, opt, size) } pub fn sock_get_opt_size( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, - ret_size: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> __wasi_errno_t { + sock: Fd, + opt: Sockoption, + ret_size: WasmPtr, +) -> Errno { super::sock_get_opt_size(ctx, sock, opt, ret_size) } pub(crate) fn sock_join_multicast_v4( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_join_multicast_v4::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_leave_multicast_v4( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_leave_multicast_v4::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_join_multicast_v6( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, -) -> __wasi_errno_t { +) -> Errno { super::sock_join_multicast_v6::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_leave_multicast_v6( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, -) -> __wasi_errno_t { +) -> Errno { super::sock_leave_multicast_v6::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_bind( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_bind::(ctx, sock, addr) } -pub(crate) fn sock_listen( - ctx: FunctionEnvMut, - sock: __wasi_fd_t, - backlog: MemoryOffset, -) -> __wasi_errno_t { +pub(crate) fn sock_listen(ctx: FunctionEnvMut, sock: Fd, backlog: MemoryOffset) -> Errno { super::sock_listen::(ctx, sock, backlog) } pub(crate) fn sock_accept( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - fd_flags: __wasi_fdflags_t, - ro_fd: WasmPtr<__wasi_fd_t, MemoryType>, + sock: Fd, + fd_flags: Fdflags, + ro_fd: WasmPtr, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_accept::(ctx, sock, fd_flags, ro_fd, ro_addr) } pub(crate) fn sock_connect( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_connect::(ctx, sock, addr) } pub(crate) fn sock_recv( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, ri_flags: __wasi_riflags_t, ro_data_len: WasmPtr, ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_recv::( ctx, sock, @@ -977,14 +955,14 @@ pub(crate) fn sock_recv( pub(crate) fn sock_recv_from( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, ri_flags: __wasi_riflags_t, ro_data_len: WasmPtr, ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_recv_from::( ctx, sock, @@ -999,24 +977,24 @@ pub(crate) fn sock_recv_from( pub(crate) fn sock_send( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, si_flags: __wasi_siflags_t, ret_data_len: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_send::(ctx, sock, si_data, si_data_len, si_flags, ret_data_len) } pub(crate) fn sock_send_to( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, si_flags: __wasi_siflags_t, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ret_data_len: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_send_to::( ctx, sock, @@ -1030,20 +1008,20 @@ pub(crate) fn sock_send_to( pub(crate) fn sock_send_file( ctx: FunctionEnvMut, - out_fd: __wasi_fd_t, - in_fd: __wasi_fd_t, - offset: __wasi_filesize_t, - count: __wasi_filesize_t, - ret_sent: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { + out_fd: Fd, + in_fd: Fd, + offset: Filesize, + count: Filesize, + ret_sent: WasmPtr, +) -> Result { unsafe { super::sock_send_file::(ctx, out_fd, in_fd, offset, count, ret_sent) } } pub(crate) fn sock_shutdown( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, how: __wasi_sdflags_t, -) -> __wasi_errno_t { +) -> Errno { super::sock_shutdown(ctx, sock, how) } @@ -1055,6 +1033,6 @@ pub(crate) fn resolve( ips: WasmPtr<__wasi_addr_t, MemoryType>, nips: MemoryOffset, ret_nips: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::resolve::(ctx, host, host_len, port, ips, nips, ret_nips) } diff --git a/lib/wasi/src/syscalls/wasix64.rs b/lib/wasi/src/syscalls/wasix64.rs index b42307e0da8..52ab6a3303d 100644 --- a/lib/wasi/src/syscalls/wasix64.rs +++ b/lib/wasi/src/syscalls/wasix64.rs @@ -2,6 +2,11 @@ use crate::{WasiEnv, WasiError, WasiState, WasiThread}; use wasmer::{FunctionEnvMut, Memory, Memory64, MemorySize, StoreMut, WasmPtr, WasmSlice}; use wasmer_wasi_types::*; +use wasmer_wasi_types_generated::wasi::{ + Addressfamily, Advice, BusErrno, Clockid, Dircookie, Errno, Event, Fd, Fdflags, Fdstat, + Filesize, Filestat, Fstflags, Pid, Rights, Sockoption, Sockstatus, Socktype, Streamsecurity, + Subscription, Tid, Timestamp, Tty, Whence, +}; type MemoryType = Memory64; type MemoryOffset = u64; @@ -10,7 +15,7 @@ pub(crate) fn args_get( ctx: FunctionEnvMut, argv: WasmPtr, MemoryType>, argv_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::args_get::(ctx, argv, argv_buf) } @@ -18,24 +23,24 @@ pub(crate) fn args_sizes_get( ctx: FunctionEnvMut, argc: WasmPtr, argv_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::args_sizes_get::(ctx, argc, argv_buf_size) } pub(crate) fn clock_res_get( ctx: FunctionEnvMut, - clock_id: __wasi_clockid_t, - resolution: WasmPtr<__wasi_timestamp_t, MemoryType>, -) -> __wasi_errno_t { + clock_id: Clockid, + resolution: WasmPtr, +) -> Errno { super::clock_res_get::(ctx, clock_id, resolution) } pub(crate) fn clock_time_get( ctx: FunctionEnvMut, - clock_id: __wasi_clockid_t, - precision: __wasi_timestamp_t, - time: WasmPtr<__wasi_timestamp_t, MemoryType>, -) -> __wasi_errno_t { + clock_id: Clockid, + precision: Timestamp, + time: WasmPtr, +) -> Errno { super::clock_time_get::(ctx, clock_id, precision, time) } @@ -43,7 +48,7 @@ pub(crate) fn environ_get( ctx: FunctionEnvMut, environ: WasmPtr, MemoryType>, environ_buf: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::environ_get::(ctx, environ, environ_buf) } @@ -51,218 +56,210 @@ pub(crate) fn environ_sizes_get( ctx: FunctionEnvMut, environ_count: WasmPtr, environ_buf_size: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::environ_sizes_get::(ctx, environ_count, environ_buf_size) } pub(crate) fn fd_advise( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, - advice: __wasi_advice_t, -) -> __wasi_errno_t { + fd: Fd, + offset: Filesize, + len: Filesize, + advice: Advice, +) -> Errno { super::fd_advise(ctx, fd, offset, len, advice) } pub(crate) fn fd_allocate( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: __wasi_filesize_t, - len: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: Fd, + offset: Filesize, + len: Filesize, +) -> Errno { super::fd_allocate(ctx, fd, offset, len) } -pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_close(ctx: FunctionEnvMut, fd: Fd) -> Errno { super::fd_close(ctx, fd) } -pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_datasync(ctx: FunctionEnvMut, fd: Fd) -> Errno { super::fd_datasync(ctx, fd) } pub(crate) fn fd_fdstat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - buf_ptr: WasmPtr<__wasi_fdstat_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + buf_ptr: WasmPtr, +) -> Errno { super::fd_fdstat_get::(ctx, fd, buf_ptr) } -pub(crate) fn fd_fdstat_set_flags( - ctx: FunctionEnvMut, - fd: __wasi_fd_t, - flags: __wasi_fdflags_t, -) -> __wasi_errno_t { +pub(crate) fn fd_fdstat_set_flags(ctx: FunctionEnvMut, fd: Fd, flags: Fdflags) -> Errno { super::fd_fdstat_set_flags(ctx, fd, flags) } pub(crate) fn fd_fdstat_set_rights( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - fs_rights_base: __wasi_rights_t, - fs_rights_inheriting: __wasi_rights_t, -) -> __wasi_errno_t { + fd: Fd, + fs_rights_base: Rights, + fs_rights_inheriting: Rights, +) -> Errno { super::fd_fdstat_set_rights(ctx, fd, fs_rights_base, fs_rights_inheriting) } pub(crate) fn fd_filestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - buf: WasmPtr<__wasi_filestat_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + buf: WasmPtr, +) -> Errno { super::fd_filestat_get::(ctx, fd, buf) } pub(crate) fn fd_filestat_set_size( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - st_size: __wasi_filesize_t, -) -> __wasi_errno_t { + fd: Fd, + st_size: Filesize, +) -> Errno { super::fd_filestat_set_size(ctx, fd, st_size) } pub(crate) fn fd_filestat_set_times( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + fd: Fd, + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { super::fd_filestat_set_times(ctx, fd, st_atim, st_mtim, fst_flags) } pub(crate) fn fd_pread( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, - offset: __wasi_filesize_t, + offset: Filesize, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_pread::(ctx, fd, iovs, iovs_len, offset, nread) } pub(crate) fn fd_prestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, buf: WasmPtr<__wasi_prestat_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::fd_prestat_get::(ctx, fd, buf) } pub(crate) fn fd_prestat_dir_name( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::fd_prestat_dir_name::(ctx, fd, path, path_len) } pub(crate) fn fd_pwrite( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, - offset: __wasi_filesize_t, + offset: Filesize, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_pwrite::(ctx, fd, iovs, iovs_len, offset, nwritten) } pub(crate) fn fd_read( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_iovec_t, MemoryType>, iovs_len: MemoryOffset, nread: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_read::(ctx, fd, iovs, iovs_len, nread) } pub(crate) fn fd_readdir( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, buf: WasmPtr, buf_len: MemoryOffset, - cookie: __wasi_dircookie_t, + cookie: Dircookie, bufused: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::fd_readdir::(ctx, fd, buf, buf_len, cookie, bufused) } -pub(crate) fn fd_renumber( - ctx: FunctionEnvMut, - from: __wasi_fd_t, - to: __wasi_fd_t, -) -> __wasi_errno_t { +pub(crate) fn fd_renumber(ctx: FunctionEnvMut, from: Fd, to: Fd) -> Errno { super::fd_renumber(ctx, from, to) } pub(crate) fn fd_seek( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, offset: __wasi_filedelta_t, - whence: __wasi_whence_t, - newoffset: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { + whence: Whence, + newoffset: WasmPtr, +) -> Result { super::fd_seek::(ctx, fd, offset, whence, newoffset) } -pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: __wasi_fd_t) -> __wasi_errno_t { +pub(crate) fn fd_sync(ctx: FunctionEnvMut, fd: Fd) -> Errno { super::fd_sync(ctx, fd) } pub(crate) fn fd_tell( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - offset: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + offset: WasmPtr, +) -> Errno { super::fd_tell::(ctx, fd, offset) } pub(crate) fn fd_write( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, iovs: WasmPtr<__wasi_ciovec_t, MemoryType>, iovs_len: MemoryOffset, nwritten: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::fd_write::(ctx, fd, iovs, iovs_len, nwritten) } pub(crate) fn path_create_directory( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_create_directory::(ctx, fd, path, path_len) } pub(crate) fn path_filestat_get( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, - buf: WasmPtr<__wasi_filestat_t, MemoryType>, -) -> __wasi_errno_t { + buf: WasmPtr, +) -> Errno { super::path_filestat_get::(ctx, fd, flags, path, path_len, buf) } pub(crate) fn path_filestat_set_times( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, flags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, - st_atim: __wasi_timestamp_t, - st_mtim: __wasi_timestamp_t, - fst_flags: __wasi_fstflags_t, -) -> __wasi_errno_t { + st_atim: Timestamp, + st_mtim: Timestamp, + fst_flags: Fstflags, +) -> Errno { super::path_filestat_set_times::( ctx, fd, flags, path, path_len, st_atim, st_mtim, fst_flags, ) @@ -270,14 +267,14 @@ pub(crate) fn path_filestat_set_times( pub(crate) fn path_link( ctx: FunctionEnvMut, - old_fd: __wasi_fd_t, + old_fd: Fd, old_flags: __wasi_lookupflags_t, old_path: WasmPtr, old_path_len: MemoryOffset, - new_fd: __wasi_fd_t, + new_fd: Fd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_link::( ctx, old_fd, @@ -292,16 +289,16 @@ pub(crate) fn path_link( pub(crate) fn path_open( ctx: FunctionEnvMut, - dirfd: __wasi_fd_t, + dirfd: Fd, dirflags: __wasi_lookupflags_t, path: WasmPtr, path_len: MemoryOffset, o_flags: __wasi_oflags_t, - fs_rights_base: __wasi_rights_t, - fs_rights_inheriting: __wasi_rights_t, - fs_flags: __wasi_fdflags_t, - fd: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + fs_rights_base: Rights, + fs_rights_inheriting: Rights, + fs_flags: Fdflags, + fd: WasmPtr, +) -> Errno { super::path_open::( ctx, dirfd, @@ -318,34 +315,34 @@ pub(crate) fn path_open( pub(crate) fn path_readlink( ctx: FunctionEnvMut, - dir_fd: __wasi_fd_t, + dir_fd: Fd, path: WasmPtr, path_len: MemoryOffset, buf: WasmPtr, buf_len: MemoryOffset, buf_used: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::path_readlink::(ctx, dir_fd, path, path_len, buf, buf_len, buf_used) } pub(crate) fn path_remove_directory( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_remove_directory::(ctx, fd, path, path_len) } pub(crate) fn path_rename( ctx: FunctionEnvMut, - old_fd: __wasi_fd_t, + old_fd: Fd, old_path: WasmPtr, old_path_len: MemoryOffset, - new_fd: __wasi_fd_t, + new_fd: Fd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_rename::( ctx, old_fd, @@ -361,29 +358,29 @@ pub(crate) fn path_symlink( ctx: FunctionEnvMut, old_path: WasmPtr, old_path_len: MemoryOffset, - fd: __wasi_fd_t, + fd: Fd, new_path: WasmPtr, new_path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_symlink::(ctx, old_path, old_path_len, fd, new_path, new_path_len) } pub(crate) fn path_unlink_file( ctx: FunctionEnvMut, - fd: __wasi_fd_t, + fd: Fd, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::path_unlink_file::(ctx, fd, path, path_len) } pub(crate) fn poll_oneoff( ctx: FunctionEnvMut, - in_: WasmPtr<__wasi_subscription_t, MemoryType>, - out_: WasmPtr<__wasi_event_t, MemoryType>, + in_: WasmPtr, + out_: WasmPtr, nsubscriptions: MemoryOffset, nevents: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::poll_oneoff::(ctx, in_, out_, nsubscriptions, nevents) } @@ -394,7 +391,7 @@ pub(crate) fn proc_exit( super::proc_exit(ctx, code) } -pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> __wasi_errno_t { +pub(crate) fn proc_raise(ctx: FunctionEnvMut, sig: __wasi_signal_t) -> Errno { super::proc_raise(ctx, sig) } @@ -402,15 +399,15 @@ pub(crate) fn random_get( ctx: FunctionEnvMut, buf: WasmPtr, buf_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::random_get::(ctx, buf, buf_len) } pub(crate) fn fd_dup( ctx: FunctionEnvMut, - fd: __wasi_fd_t, - ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + fd: Fd, + ret_fd: WasmPtr, +) -> Errno { super::fd_dup::(ctx, fd, ret_fd) } @@ -418,30 +415,24 @@ pub(crate) fn fd_event( ctx: FunctionEnvMut, initial_val: u64, flags: __wasi_eventfdflags, - ret_fd: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ret_fd: WasmPtr, +) -> Errno { super::fd_event(ctx, initial_val, flags, ret_fd) } pub(crate) fn fd_pipe( ctx: FunctionEnvMut, - ro_fd1: WasmPtr<__wasi_fd_t, MemoryType>, - ro_fd2: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ro_fd1: WasmPtr, + ro_fd2: WasmPtr, +) -> Errno { super::fd_pipe::(ctx, ro_fd1, ro_fd2) } -pub(crate) fn tty_get( - ctx: FunctionEnvMut, - tty_state: WasmPtr<__wasi_tty_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn tty_get(ctx: FunctionEnvMut, tty_state: WasmPtr) -> Errno { super::tty_get::(ctx, tty_state) } -pub(crate) fn tty_set( - ctx: FunctionEnvMut, - tty_state: WasmPtr<__wasi_tty_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn tty_set(ctx: FunctionEnvMut, tty_state: WasmPtr) -> Errno { super::tty_set::(ctx, tty_state) } @@ -449,7 +440,7 @@ pub(crate) fn getcwd( ctx: FunctionEnvMut, path: WasmPtr, path_len: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::getcwd::(ctx, path, path_len) } @@ -457,7 +448,7 @@ pub(crate) fn chdir( ctx: FunctionEnvMut, path: WasmPtr, path_len: MemoryOffset, -) -> __wasi_errno_t { +) -> Errno { super::chdir::(ctx, path, path_len) } @@ -467,54 +458,45 @@ pub(crate) fn thread_spawn( method_len: MemoryOffset, user_data: u64, reactor: __wasi_bool_t, - ret_tid: WasmPtr<__wasi_tid_t, MemoryType>, -) -> __wasi_errno_t { + ret_tid: WasmPtr, +) -> Errno { super::thread_spawn::(ctx, method, method_len, user_data, reactor, ret_tid) } pub(crate) fn thread_sleep( ctx: FunctionEnvMut, - duration: __wasi_timestamp_t, -) -> Result<__wasi_errno_t, WasiError> { + duration: Timestamp, +) -> Result { super::thread_sleep(ctx, duration) } -pub(crate) fn thread_id( - ctx: FunctionEnvMut, - ret_tid: WasmPtr<__wasi_tid_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn thread_id(ctx: FunctionEnvMut, ret_tid: WasmPtr) -> Errno { super::thread_id::(ctx, ret_tid) } -pub(crate) fn thread_join( - ctx: FunctionEnvMut, - tid: __wasi_tid_t, -) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn thread_join(ctx: FunctionEnvMut, tid: Tid) -> Result { super::thread_join(ctx, tid) } pub(crate) fn thread_parallelism( ctx: FunctionEnvMut, ret_parallelism: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::thread_parallelism::(ctx, ret_parallelism) } pub(crate) fn thread_exit( ctx: FunctionEnvMut, exitcode: __wasi_exitcode_t, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::thread_exit(ctx, exitcode) } -pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result<__wasi_errno_t, WasiError> { +pub(crate) fn sched_yield(ctx: FunctionEnvMut) -> Result { super::sched_yield(ctx) } -pub(crate) fn getpid( - ctx: FunctionEnvMut, - ret_pid: WasmPtr<__wasi_pid_t, MemoryType>, -) -> __wasi_errno_t { +pub(crate) fn getpid(ctx: FunctionEnvMut, ret_pid: WasmPtr) -> Errno { super::getpid::(ctx, ret_pid) } @@ -533,7 +515,7 @@ pub(crate) fn process_spawn( working_dir: WasmPtr, working_dir_len: MemoryOffset, ret_handles: WasmPtr<__wasi_bus_handles_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::process_spawn::( ctx, name, @@ -558,7 +540,7 @@ pub(crate) fn bus_open_local( name_len: MemoryOffset, reuse: __wasi_bool_t, ret_bid: WasmPtr<__wasi_bid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_open_local::(ctx, name, name_len, reuse, ret_bid) } @@ -572,7 +554,7 @@ pub(crate) fn bus_open_remote( token: WasmPtr, token_len: MemoryOffset, ret_bid: WasmPtr<__wasi_bid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_open_remote::( ctx, name, @@ -586,7 +568,7 @@ pub(crate) fn bus_open_remote( ) } -pub(crate) fn bus_close(ctx: FunctionEnvMut, bid: __wasi_bid_t) -> __bus_errno_t { +pub(crate) fn bus_close(ctx: FunctionEnvMut, bid: __wasi_bid_t) -> BusErrno { super::bus_close(ctx, bid) } @@ -600,7 +582,7 @@ pub(crate) fn bus_call( buf: WasmPtr, buf_len: MemoryOffset, ret_cid: WasmPtr<__wasi_cid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_call::( ctx, bid, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid, ) @@ -616,7 +598,7 @@ pub(crate) fn bus_subcall( buf: WasmPtr, buf_len: MemoryOffset, ret_cid: WasmPtr<__wasi_cid_t, MemoryType>, -) -> __bus_errno_t { +) -> BusErrno { super::bus_subcall::( ctx, parent, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid, ) @@ -624,13 +606,13 @@ pub(crate) fn bus_subcall( pub(crate) fn bus_poll( ctx: FunctionEnvMut, - timeout: __wasi_timestamp_t, + timeout: Timestamp, events: WasmPtr, nevents: MemoryOffset, malloc: WasmPtr, malloc_len: MemoryOffset, ret_nevents: WasmPtr, -) -> __bus_errno_t { +) -> BusErrno { super::bus_poll::( ctx, timeout, @@ -648,19 +630,19 @@ pub(crate) fn call_reply( format: __wasi_busdataformat_t, buf: WasmPtr, buf_len: MemoryOffset, -) -> __bus_errno_t { +) -> BusErrno { super::call_reply::(ctx, cid, format, buf, buf_len) } pub(crate) fn call_fault( ctx: FunctionEnvMut, cid: __wasi_cid_t, - fault: __bus_errno_t, -) -> __bus_errno_t { + fault: BusErrno, +) -> BusErrno { super::call_fault(ctx, cid, fault) } -pub(crate) fn call_close(ctx: FunctionEnvMut, cid: __wasi_cid_t) -> __bus_errno_t { +pub(crate) fn call_close(ctx: FunctionEnvMut, cid: __wasi_cid_t) -> BusErrno { super::call_close(ctx, cid) } @@ -670,34 +652,34 @@ pub(crate) fn port_bridge( network_len: MemoryOffset, token: WasmPtr, token_len: MemoryOffset, - security: __wasi_streamsecurity_t, -) -> __wasi_errno_t { + security: Streamsecurity, +) -> Errno { super::port_bridge::(ctx, network, network_len, token, token_len, security) } -pub(crate) fn port_unbridge(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_unbridge(ctx: FunctionEnvMut) -> Errno { super::port_unbridge(ctx) } -pub(crate) fn port_dhcp_acquire(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_dhcp_acquire(ctx: FunctionEnvMut) -> Errno { super::port_dhcp_acquire(ctx) } pub(crate) fn port_addr_add( ctx: FunctionEnvMut, addr: WasmPtr<__wasi_cidr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_addr_add::(ctx, addr) } pub(crate) fn port_addr_remove( ctx: FunctionEnvMut, addr: WasmPtr<__wasi_addr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_addr_remove::(ctx, addr) } -pub(crate) fn port_addr_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_addr_clear(ctx: FunctionEnvMut) -> Errno { super::port_addr_clear(ctx) } @@ -705,21 +687,21 @@ pub(crate) fn port_addr_list( ctx: FunctionEnvMut, addrs: WasmPtr<__wasi_cidr_t, MemoryType>, naddrs: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::port_addr_list::(ctx, addrs, naddrs) } pub(crate) fn port_mac( ctx: FunctionEnvMut, ret_mac: WasmPtr<__wasi_hardwareaddress_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_mac::(ctx, ret_mac) } pub(crate) fn port_gateway_set( ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_gateway_set::(ctx, ip) } @@ -729,18 +711,18 @@ pub(crate) fn port_route_add( via_router: WasmPtr<__wasi_addr_t, MemoryType>, preferred_until: WasmPtr<__wasi_option_timestamp_t, MemoryType>, expires_at: WasmPtr<__wasi_option_timestamp_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_route_add::(ctx, cidr, via_router, preferred_until, expires_at) } pub(crate) fn port_route_remove( ctx: FunctionEnvMut, ip: WasmPtr<__wasi_addr_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::port_route_remove::(ctx, ip) } -pub(crate) fn port_route_clear(ctx: FunctionEnvMut) -> __wasi_errno_t { +pub(crate) fn port_route_clear(ctx: FunctionEnvMut) -> Errno { super::port_route_clear(ctx) } @@ -748,7 +730,7 @@ pub(crate) fn port_route_list( ctx: FunctionEnvMut, routes: WasmPtr<__wasi_route_t, MemoryType>, nroutes: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::port_route_list::(ctx, routes, nroutes) } @@ -756,8 +738,8 @@ pub(crate) fn ws_connect( ctx: FunctionEnvMut, url: WasmPtr, url_len: MemoryOffset, - ret_sock: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ret_sock: WasmPtr, +) -> Errno { super::ws_connect::(ctx, url, url_len, ret_sock) } @@ -771,7 +753,7 @@ pub(crate) fn http_request( headers_len: MemoryOffset, gzip: __wasi_bool_t, ret_handles: WasmPtr<__wasi_http_handles_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::http_request::( ctx, url, @@ -787,183 +769,179 @@ pub(crate) fn http_request( pub(crate) fn http_status( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, status: WasmPtr<__wasi_http_status_t, MemoryType>, status_text: WasmPtr, status_text_len: WasmPtr, headers: WasmPtr, headers_len: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::http_status::(ctx, sock, status) } pub(crate) fn sock_status( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>, -) -> __wasi_errno_t { + sock: Fd, + ret_status: WasmPtr, +) -> Errno { super::sock_status::(ctx, sock, ret_status) } pub(crate) fn sock_addr_local( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ret_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_addr_local::(ctx, sock, ret_addr) } pub(crate) fn sock_addr_peer( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_addr_peer::(ctx, sock, ro_addr) } pub(crate) fn sock_open( ctx: FunctionEnvMut, - af: __wasi_addressfamily_t, - ty: __wasi_socktype_t, + af: Addressfamily, + ty: Socktype, pt: __wasi_sockproto_t, - ro_sock: WasmPtr<__wasi_fd_t, MemoryType>, -) -> __wasi_errno_t { + ro_sock: WasmPtr, +) -> Errno { super::sock_open::(ctx, af, ty, pt, ro_sock) } pub(crate) fn sock_set_opt_flag( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, flag: __wasi_bool_t, -) -> __wasi_errno_t { +) -> Errno { super::sock_set_opt_flag(ctx, sock, opt, flag) } pub(crate) fn sock_get_opt_flag( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, ret_flag: WasmPtr<__wasi_bool_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_get_opt_flag::(ctx, sock, opt, ret_flag) } pub fn sock_set_opt_time( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_set_opt_time(ctx, sock, opt, time) } pub fn sock_get_opt_time( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, + sock: Fd, + opt: Sockoption, ret_time: WasmPtr<__wasi_option_timestamp_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_get_opt_time(ctx, sock, opt, ret_time) } pub fn sock_set_opt_size( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, - size: __wasi_filesize_t, -) -> __wasi_errno_t { + sock: Fd, + opt: Sockoption, + size: Filesize, +) -> Errno { super::sock_set_opt_size(ctx, sock, opt, size) } pub fn sock_get_opt_size( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - opt: __wasi_sockoption_t, - ret_size: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> __wasi_errno_t { + sock: Fd, + opt: Sockoption, + ret_size: WasmPtr, +) -> Errno { super::sock_get_opt_size(ctx, sock, opt, ret_size) } pub(crate) fn sock_join_multicast_v4( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_join_multicast_v4::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_leave_multicast_v4( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip4_t, MemoryType>, iface: WasmPtr<__wasi_addr_ip4_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_leave_multicast_v4::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_join_multicast_v6( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, -) -> __wasi_errno_t { +) -> Errno { super::sock_join_multicast_v6::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_leave_multicast_v6( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, multiaddr: WasmPtr<__wasi_addr_ip6_t, MemoryType>, iface: u32, -) -> __wasi_errno_t { +) -> Errno { super::sock_leave_multicast_v6::(ctx, sock, multiaddr, iface) } pub(crate) fn sock_bind( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_bind::(ctx, sock, addr) } -pub(crate) fn sock_listen( - ctx: FunctionEnvMut, - sock: __wasi_fd_t, - backlog: MemoryOffset, -) -> __wasi_errno_t { +pub(crate) fn sock_listen(ctx: FunctionEnvMut, sock: Fd, backlog: MemoryOffset) -> Errno { super::sock_listen::(ctx, sock, backlog) } pub(crate) fn sock_accept( ctx: FunctionEnvMut, - sock: __wasi_fd_t, - fd_flags: __wasi_fdflags_t, - ro_fd: WasmPtr<__wasi_fd_t, MemoryType>, + sock: Fd, + fd_flags: Fdflags, + ro_fd: WasmPtr, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_accept::(ctx, sock, fd_flags, ro_fd, ro_addr) } pub(crate) fn sock_connect( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> __wasi_errno_t { +) -> Errno { super::sock_connect::(ctx, sock, addr) } pub(crate) fn sock_recv( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, ri_flags: __wasi_riflags_t, ro_data_len: WasmPtr, ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_recv::( ctx, sock, @@ -977,14 +955,14 @@ pub(crate) fn sock_recv( pub(crate) fn sock_recv_from( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, ri_data: WasmPtr<__wasi_iovec_t, MemoryType>, ri_data_len: MemoryOffset, ri_flags: __wasi_riflags_t, ro_data_len: WasmPtr, ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>, ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_recv_from::( ctx, sock, @@ -999,24 +977,24 @@ pub(crate) fn sock_recv_from( pub(crate) fn sock_send( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, si_flags: __wasi_siflags_t, ret_data_len: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_send::(ctx, sock, si_data, si_data_len, si_flags, ret_data_len) } pub(crate) fn sock_send_to( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, si_data: WasmPtr<__wasi_ciovec_t, MemoryType>, si_data_len: MemoryOffset, si_flags: __wasi_siflags_t, addr: WasmPtr<__wasi_addr_port_t, MemoryType>, ret_data_len: WasmPtr, -) -> Result<__wasi_errno_t, WasiError> { +) -> Result { super::sock_send_to::( ctx, sock, @@ -1030,20 +1008,20 @@ pub(crate) fn sock_send_to( pub(crate) fn sock_send_file( ctx: FunctionEnvMut, - out_fd: __wasi_fd_t, - in_fd: __wasi_fd_t, - offset: __wasi_filesize_t, - count: __wasi_filesize_t, - ret_sent: WasmPtr<__wasi_filesize_t, MemoryType>, -) -> Result<__wasi_errno_t, WasiError> { + out_fd: Fd, + in_fd: Fd, + offset: Filesize, + count: Filesize, + ret_sent: WasmPtr, +) -> Result { unsafe { super::sock_send_file::(ctx, out_fd, in_fd, offset, count, ret_sent) } } pub(crate) fn sock_shutdown( ctx: FunctionEnvMut, - sock: __wasi_fd_t, + sock: Fd, how: __wasi_sdflags_t, -) -> __wasi_errno_t { +) -> Errno { super::sock_shutdown(ctx, sock, how) } @@ -1055,6 +1033,6 @@ pub(crate) fn resolve( ips: WasmPtr<__wasi_addr_t, MemoryType>, nips: MemoryOffset, ret_nips: WasmPtr, -) -> __wasi_errno_t { +) -> Errno { super::resolve::(ctx, host, host_len, port, ips, nips, ret_nips) } diff --git a/lib/wasi/src/syscalls/wasm32.rs b/lib/wasi/src/syscalls/wasm32.rs index d9f56ac85c1..2796eca5e7d 100644 --- a/lib/wasi/src/syscalls/wasm32.rs +++ b/lib/wasi/src/syscalls/wasm32.rs @@ -1,26 +1,29 @@ -use crate::syscalls::types::*; +use crate::syscalls::types::{ + wasi::{Errno, Snapshot0Clockid, Timestamp}, + *, +}; use chrono::prelude::*; use std::mem; use wasmer::WasmRef; pub fn platform_clock_res_get( - clock_id: __wasi_clockid_t, - resolution: WasmRef<__wasi_timestamp_t>, -) -> Result { + clock_id: Snapshot0Clockid, + resolution: WasmRef, +) -> Result { let t_out = match clock_id { - __WASI_CLOCK_MONOTONIC => 10_000_000, - __WASI_CLOCK_REALTIME => 1, - __WASI_CLOCK_PROCESS_CPUTIME_ID => 1, - __WASI_CLOCK_THREAD_CPUTIME_ID => 1, - _ => return Err(__WASI_EINVAL), + Snapshot0Clockid::Monotonic => 10_000_000, + Snapshot0Clockid::Realtime => 1, + Snapshot0Clockid::ProcessCputimeId => 1, + Snapshot0Clockid::ThreadCputimeId => 1, + _ => return Err(Errno::Inval), }; Ok(t_out) } pub fn platform_clock_time_get( - clock_id: __wasi_clockid_t, - precision: __wasi_timestamp_t, -) -> Result { + clock_id: Snapshot0Clockid, + precision: Timestamp, +) -> Result { let new_time: DateTime = Local::now(); Ok(new_time.timestamp_nanos() as i64) } diff --git a/lib/wasi/src/syscalls/windows.rs b/lib/wasi/src/syscalls/windows.rs index c461fa44ca8..35ae6f8f691 100644 --- a/lib/wasi/src/syscalls/windows.rs +++ b/lib/wasi/src/syscalls/windows.rs @@ -1,53 +1,57 @@ -use crate::syscalls::types::*; +use crate::syscalls::types::{wasi::Timestamp, *}; use tracing::debug; use wasmer::WasmRef; pub fn platform_clock_res_get( - clock_id: __wasi_clockid_t, - resolution: WasmRef<__wasi_timestamp_t>, -) -> Result { + clock_id: wasi_snapshot0::Clockid, + resolution: WasmRef, +) -> Result { let resolution_val = match clock_id { // resolution of monotonic clock at 10ms, from: // https://docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-gettickcount64 - __WASI_CLOCK_MONOTONIC => 10_000_000, + wasi_snapshot0::Clockid::Monotonic => 10_000_000, // TODO: verify or compute this - __WASI_CLOCK_REALTIME => 1, - __WASI_CLOCK_PROCESS_CPUTIME_ID => { - return Err(__WASI_EINVAL); + wasi_snapshot0::Clockid::Realtime => 1, + wasi_snapshot0::Clockid::ProcessCputimeId => { + return Err(wasi_snapshot0::Errno::Inval); } - __WASI_CLOCK_THREAD_CPUTIME_ID => { - return Err(__WASI_EINVAL); + wasi_snapshot0::Clockid::ThreadCputimeId => { + return Err(wasi_snapshot0::Errno::Inval); } - _ => return Err(__WASI_EINVAL), + _ => return Err(wasi_snapshot0::Errno::Inval), }; Ok(resolution_val) } pub fn platform_clock_time_get( - clock_id: __wasi_clockid_t, - precision: __wasi_timestamp_t, -) -> Result { + clock_id: wasi_snapshot0::Clockid, + precision: Timestamp, +) -> Result { let nanos = match clock_id { - __WASI_CLOCK_MONOTONIC => { + wasi_snapshot0::Clockid::MONOTONIC => { let tick_ms = unsafe { winapi::um::sysinfoapi::GetTickCount64() }; tick_ms * 1_000_000 } - __WASI_CLOCK_REALTIME => { + wasi_snapshot0::Clockid::REALTIME => { let duration = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_err(|e| { debug!("Error in wasi::platform_clock_time_get: {:?}", e); - __WASI_EIO + wasi_snapshot0::Errno::Io })?; duration.as_nanos() as u64 } - __WASI_CLOCK_PROCESS_CPUTIME_ID => { - unimplemented!("wasi::platform_clock_time_get(__WASI_CLOCK_PROCESS_CPUTIME_ID, ..)") + wasi_snapshot0::Clockid::ProcessCputimeId => { + unimplemented!( + "wasi::platform_clock_time_get(wasi_snapshot0::Clockid::ProcessCputimeId, ..)" + ) } - __WASI_CLOCK_THREAD_CPUTIME_ID => { - unimplemented!("wasi::platform_clock_time_get(__WASI_CLOCK_THREAD_CPUTIME_ID, ..)") + wasi_snapshot0::Clockid::ThreadCputimeId => { + unimplemented!( + "wasi::platform_clock_time_get(wasi_snapshot0::Clockid::ThreadCputimeId, ..)" + ) } - _ => return Err(__WASI_EINVAL), + _ => return Err(wasi_snapshot0::Errno::Inval), }; Ok(nanos as i64) } diff --git a/lib/wasi/src/utils.rs b/lib/wasi/src/utils.rs index 0fbc5c221c6..2c00f329122 100644 --- a/lib/wasi/src/utils.rs +++ b/lib/wasi/src/utils.rs @@ -1,6 +1,6 @@ -use super::types::*; use std::collections::BTreeSet; use wasmer::Module; +use wasmer_wasi_types_generated::wasi::Errno; #[allow(dead_code)] /// Check if a provided module is compiled for some version of WASI. @@ -22,29 +22,29 @@ pub fn is_wasix_module(module: &Module) -> bool { } } -pub fn map_io_err(err: std::io::Error) -> __wasi_errno_t { +pub fn map_io_err(err: std::io::Error) -> Errno { use std::io::ErrorKind; match err.kind() { - ErrorKind::NotFound => __WASI_ENOENT, - ErrorKind::PermissionDenied => __WASI_EPERM, - ErrorKind::ConnectionRefused => __WASI_ECONNREFUSED, - ErrorKind::ConnectionReset => __WASI_ECONNRESET, - ErrorKind::ConnectionAborted => __WASI_ECONNABORTED, - ErrorKind::NotConnected => __WASI_ENOTCONN, - ErrorKind::AddrInUse => __WASI_EADDRINUSE, - ErrorKind::AddrNotAvailable => __WASI_EADDRNOTAVAIL, - ErrorKind::BrokenPipe => __WASI_EPIPE, - ErrorKind::AlreadyExists => __WASI_EEXIST, - ErrorKind::WouldBlock => __WASI_EAGAIN, - ErrorKind::InvalidInput => __WASI_EIO, - ErrorKind::InvalidData => __WASI_EIO, - ErrorKind::TimedOut => __WASI_ETIMEDOUT, - ErrorKind::WriteZero => __WASI_EIO, - ErrorKind::Interrupted => __WASI_EINTR, - ErrorKind::Other => __WASI_EIO, - ErrorKind::UnexpectedEof => __WASI_EIO, - ErrorKind::Unsupported => __WASI_ENOTSUP, - _ => __WASI_EIO, + ErrorKind::NotFound => Errno::Noent, + ErrorKind::PermissionDenied => Errno::Perm, + ErrorKind::ConnectionRefused => Errno::Connrefused, + ErrorKind::ConnectionReset => Errno::Connreset, + ErrorKind::ConnectionAborted => Errno::Connaborted, + ErrorKind::NotConnected => Errno::Notconn, + ErrorKind::AddrInUse => Errno::Addrinuse, + ErrorKind::AddrNotAvailable => Errno::Addrnotavail, + ErrorKind::BrokenPipe => Errno::Pipe, + ErrorKind::AlreadyExists => Errno::Exist, + ErrorKind::WouldBlock => Errno::Again, + ErrorKind::InvalidInput => Errno::Io, + ErrorKind::InvalidData => Errno::Io, + ErrorKind::TimedOut => Errno::Timedout, + ErrorKind::WriteZero => Errno::Io, + ErrorKind::Interrupted => Errno::Intr, + ErrorKind::Other => Errno::Io, + ErrorKind::UnexpectedEof => Errno::Io, + ErrorKind::Unsupported => Errno::Notsup, + _ => Errno::Io, } } diff --git a/tests/lib/wast/src/wasi_wast.rs b/tests/lib/wast/src/wasi_wast.rs index 6b2e13aac4c..e31993deb0f 100644 --- a/tests/lib/wast/src/wasi_wast.rs +++ b/tests/lib/wast/src/wasi_wast.rs @@ -3,10 +3,9 @@ use std::fs::{read_dir, File, OpenOptions, ReadDir}; use std::io::{self, Read, Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::{mpsc, Arc, Mutex}; -use wasmer::FunctionEnv; -use wasmer::{Imports, Instance, Module, Store}; +use wasmer::{FunctionEnv, Imports, Instance, Module, Store}; use wasmer_vfs::{host_fs, mem_fs, FileSystem}; -use wasmer_wasi::types::{__wasi_filesize_t, __wasi_timestamp_t}; +use wasmer_wasi::types::wasi::{Filesize, Timestamp}; use wasmer_wasi::{ generate_import_object_from_env, get_wasi_version, FsError, Pipe, VirtualFile, WasiEnv, WasiFunctionEnv, WasiState, WasiVersion, @@ -614,19 +613,19 @@ impl Write for OutputCapturerer { } impl VirtualFile for OutputCapturerer { - fn last_accessed(&self) -> __wasi_timestamp_t { + fn last_accessed(&self) -> Timestamp { 0 } - fn last_modified(&self) -> __wasi_timestamp_t { + fn last_modified(&self) -> Timestamp { 0 } - fn created_time(&self) -> __wasi_timestamp_t { + fn created_time(&self) -> Timestamp { 0 } fn size(&self) -> u64 { 0 } - fn set_len(&mut self, _new_size: __wasi_filesize_t) -> Result<(), FsError> { + fn set_len(&mut self, _new_size: Filesize) -> Result<(), FsError> { Ok(()) } fn unlink(&mut self) -> Result<(), FsError> {