Fix lint warnings/errors

This commit is contained in:
ptitSeb
2022-06-08 15:18:50 +02:00
committed by Manos Pitsidianakis
parent 5d7767fdb5
commit 3e9de243a5
32 changed files with 2304 additions and 2383 deletions

View File

@@ -11,11 +11,11 @@
//!
//! Ready?
use std::io::{Read, Write};
use wasmer::{Instance, Module, Store};
use wasmer_compiler_cranelift::Cranelift;
use wasmer_engine_universal::Universal;
use wasmer_wasi::{Pipe, WasiState};
use std::io::{Read, Write};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wasm_path = concat!(

View File

@@ -88,7 +88,11 @@ impl<'a, T: ValueType> WasmRef<'a, T> {
/// Get a `WasmPtr` fror this `WasmRef`.
#[inline]
pub fn as_ptr<M: MemorySize>(self) -> WasmPtr<T, M> {
let offset: M::Offset = self.offset.try_into().map_err(|_| "invalid offset into memory").unwrap();
let offset: M::Offset = self
.offset
.try_into()
.map_err(|_| "invalid offset into memory")
.unwrap();
WasmPtr::<T, M>::new(offset)
}

View File

@@ -1,5 +1,5 @@
use crate::RuntimeError;
use crate::{Memory, Memory32, Memory64, WasmPtr, MemorySize};
use crate::{Memory, Memory32, Memory64, MemorySize, WasmPtr};
use std::{
convert::TryInto,
fmt,
@@ -88,7 +88,11 @@ impl<'a, T: ValueType> WasmRef<'a, T> {
/// Get a `WasmPtr` fror this `WasmRef`.
#[inline]
pub fn as_ptr<M: MemorySize>(self) -> WasmPtr<T, M> {
let offset: M::Offset = self.offset.try_into().map_err(|_| "invalid offset into memory").unwrap();
let offset: M::Offset = self
.offset
.try_into()
.map_err(|_| "invalid offset into memory")
.unwrap();
WasmPtr::<T, M>::new(offset)
}

View File

@@ -41,7 +41,10 @@ pub struct Wasi {
/// Enable experimental IO devices
#[cfg(feature = "experimental-io-devices")]
#[cfg_attr(feature = "experimental-io-devices", structopt(long = "enable-experimental-io-devices"))]
#[cfg_attr(
feature = "experimental-io-devices",
structopt(long = "enable-experimental-io-devices")
)]
enable_experimental_io_devices: bool,
/// Allow WASI modules to import multiple versions of WASI without a warning.
@@ -93,9 +96,9 @@ impl Wasi {
}
}
let mut wasi_env = wasi_state_builder.finalize()?;
let wasi_env = wasi_state_builder.finalize()?;
let mut wasi_thread = wasi_env.new_thread();
let import_object = wasi_env.import_object_for_all_wasi_versions(module)?;
let import_object = wasi_thread.import_object_for_all_wasi_versions(module)?;
let instance = Instance::new(module, &import_object)?;
Ok(instance)
}

View File

@@ -83,6 +83,7 @@ pub use crate::indexes::{
pub use crate::initializers::{
DataInitializer, DataInitializerLocation, OwnedDataInitializer, TableInitializer,
};
pub use crate::memory::{Memory32, Memory64, MemorySize};
pub use crate::module::{ExportsIterator, ImportsIterator, ModuleInfo};
pub use crate::native::{NativeWasmType, ValueType};
pub use crate::units::{
@@ -93,9 +94,6 @@ pub use types::{
ExportType, ExternType, FunctionType, GlobalInit, GlobalType, ImportType, MemoryType,
Mutability, TableType, Type, V128,
};
pub use crate::memory::{
MemorySize, Memory32, Memory64
};
#[cfg(feature = "enable-rkyv")]
pub use archives::ArchivableIndexMap;

View File

@@ -52,33 +52,33 @@ impl MemoryStyle {
/// This allows code to be generic over 32-bit and 64-bit memories.
pub unsafe trait MemorySize: Copy {
/// Type used to represent an offset into a memory. This is `u32` or `u64`.
type Offset: Default +
std::fmt::Debug +
std::fmt::Display +
Eq +
Ord +
PartialEq<Self::Offset> +
PartialOrd<Self::Offset> +
Clone +
Copy +
ValueType +
Into<u64> +
From<u32> +
From<u16> +
From<u8> +
TryFrom<u64> +
TryFrom<u32> +
TryFrom<u16> +
TryFrom<u8> +
TryInto<usize> +
TryInto<u64> +
TryInto<u32> +
TryInto<u16> +
TryInto<u8> +
TryFrom<usize> +
Add<Self::Offset> +
Sum<Self::Offset> +
AddAssign<Self::Offset>;
type Offset: Default
+ std::fmt::Debug
+ std::fmt::Display
+ Eq
+ Ord
+ PartialEq<Self::Offset>
+ PartialOrd<Self::Offset>
+ Clone
+ Copy
+ ValueType
+ Into<u64>
+ From<u32>
+ From<u16>
+ From<u8>
+ TryFrom<u64>
+ TryFrom<u32>
+ TryFrom<u16>
+ TryFrom<u8>
+ TryInto<usize>
+ TryInto<u64>
+ TryInto<u32>
+ TryInto<u16>
+ TryInto<u8>
+ TryFrom<usize>
+ Add<Self::Offset>
+ Sum<Self::Offset>
+ AddAssign<Self::Offset>;
/// Type used to pass this value as an argument or return value for a Wasm function.
type Native: super::NativeWasmType;

View File

@@ -3,8 +3,8 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use thiserror::Error;
pub use wasmer_vfs::StdioMode;
pub use wasmer_vfs::FileDescriptor;
pub use wasmer_vfs::StdioMode;
pub type Result<T> = std::result::Result<T, BusError>;
@@ -16,17 +16,12 @@ pub struct BusDescriptor(usize);
#[repr(transparent)]
pub struct CallDescriptor(usize);
pub trait VirtualBus: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualBus: fmt::Debug + Send + Sync + 'static {
/// Starts a new WAPM sub process
fn new_spawn(
&self,
) -> SpawnOptions;
fn new_spawn(&self) -> SpawnOptions;
/// Creates a listener thats used to receive BUS commands
fn listen(
&self
)-> Result<Box<dyn VirtualBusListener + Sync>>;
fn listen(&self) -> Result<Box<dyn VirtualBusListener + Sync>>;
}
pub trait VirtualBusSpawner {
@@ -159,40 +154,33 @@ impl SpawnOptions {
}
#[derive(Debug)]
pub struct BusSpawnedProcess
{
pub struct BusSpawnedProcess {
/// Handle of the instance
pub handle: BusDescriptor,
/// Reference to the spawned instance
pub inst: Box<dyn VirtualBusProcess + Sync>,
}
pub trait VirtualBusScope: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualBusScope: fmt::Debug + Send + Sync + 'static {
//// Returns true if the invokable target has finished
fn poll_finished(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<()>;
fn poll_finished(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()>;
}
pub trait VirtualBusInvokable: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualBusInvokable: fmt::Debug + Send + Sync + 'static {
/// Invokes a service within this instance
fn invoke(
&self,
topic: String,
format: BusDataFormat,
buf: &[u8]
buf: &[u8],
) -> Result<Box<dyn VirtualBusInvocation + Sync>>;
}
pub trait VirtualBusProcess: VirtualBusScope + VirtualBusInvokable + fmt::Debug + Send + Sync + 'static
pub trait VirtualBusProcess:
VirtualBusScope + VirtualBusInvokable + fmt::Debug + Send + Sync + 'static
{
/// Returns the exit code if the instance has finished
fn exit_code(
&self,
) -> Option<u32>;
fn exit_code(&self) -> Option<u32>;
/// Returns a file descriptor used to read the STDIN
fn stdin_fd(&self) -> Option<FileDescriptor>;
@@ -204,18 +192,15 @@ pub trait VirtualBusProcess: VirtualBusScope + VirtualBusInvokable + fmt::Debug
fn stderr_fd(&self) -> Option<FileDescriptor>;
}
pub trait VirtualBusInvocation: VirtualBusScope + VirtualBusInvokable + fmt::Debug + Send + Sync + 'static
pub trait VirtualBusInvocation:
VirtualBusScope + VirtualBusInvokable + fmt::Debug + Send + Sync + 'static
{
/// Polls for new listen events related to this context
fn poll_event(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<BusInvocationEvent>;
fn poll_event(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<BusInvocationEvent>;
}
#[derive(Debug)]
pub enum BusInvocationEvent
{
pub enum BusInvocationEvent {
/// The server has sent some out-of-band data to you
Callback {
/// Topic that this call relates to
@@ -234,18 +219,13 @@ pub enum BusInvocationEvent
},
}
pub trait VirtualBusListener: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualBusListener: fmt::Debug + Send + Sync + 'static {
/// Polls for new calls to this service
fn poll_call(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<BusCallEvent>;
fn poll_call(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<BusCallEvent>;
}
#[derive(Debug)]
pub struct BusCallEvent
{
pub struct BusCallEvent {
/// Topic that this call relates to
pub topic: String,
/// Reference to the call itself
@@ -256,28 +236,15 @@ pub struct BusCallEvent
pub data: Vec<u8>,
}
pub trait VirtualBusCalled: VirtualBusListener + fmt::Debug + Send + Sync + 'static
{
pub trait VirtualBusCalled: VirtualBusListener + fmt::Debug + Send + Sync + 'static {
/// Sends an out-of-band message back to the caller
fn callback(
&self,
topic: String,
format: BusDataFormat,
buf: &[u8],
) -> Result<()>;
fn callback(&self, topic: String, format: BusDataFormat, buf: &[u8]) -> Result<()>;
/// Informs the caller that their call has failed
fn fault(
self,
fault: BusError,
) -> Result<()>;
fn fault(self, fault: BusError) -> Result<()>;
/// Finishes the call and returns a particular response
fn reply(
self,
format: BusDataFormat,
buf: &[u8],
) -> Result<()>;
fn reply(self, format: BusDataFormat, buf: &[u8]) -> Result<()>;
}
/// Format that the supplied data is in
@@ -294,8 +261,7 @@ pub enum BusDataFormat {
#[derive(Debug, Default)]
pub struct UnsupportedVirtualBus {}
impl VirtualBus
for UnsupportedVirtualBus {
impl VirtualBus for UnsupportedVirtualBus {
fn new_spawn(&self) -> SpawnOptions {
SpawnOptions::new(Box::new(UnsupportedVirtualBusSpawner::default()))
}
@@ -308,8 +274,7 @@ for UnsupportedVirtualBus {
#[derive(Debug, Default)]
pub struct UnsupportedVirtualBusSpawner {}
impl VirtualBusSpawner
for UnsupportedVirtualBusSpawner {
impl VirtualBusSpawner for UnsupportedVirtualBusSpawner {
fn spawn(&mut self, _name: &str, _config: &SpawnOptionsConfig) -> Result<BusSpawnedProcess> {
Err(BusError::Unsupported)
}

View File

@@ -177,7 +177,11 @@ impl TryInto<Metadata> for fs::Metadata {
pub struct FileOpener;
impl crate::FileOpener for FileOpener {
fn open(&mut self, path: &Path, conf: &OpenOptionsConfig) -> Result<Box<dyn VirtualFile + Sync>> {
fn open(
&mut self,
path: &Path,
conf: &OpenOptionsConfig,
) -> Result<Box<dyn VirtualFile + Sync>> {
// TODO: handle create implying write, etc.
let read = conf.read();
let write = conf.write();

View File

@@ -51,7 +51,11 @@ impl dyn FileSystem + 'static {
}
pub trait FileOpener {
fn open(&mut self, path: &Path, conf: &OpenOptionsConfig) -> Result<Box<dyn VirtualFile + Sync>>;
fn open(
&mut self,
path: &Path,
conf: &OpenOptionsConfig,
) -> Result<Box<dyn VirtualFile + Sync>>;
}
#[derive(Debug, Clone)]

View File

@@ -10,7 +10,11 @@ pub struct FileOpener {
}
impl crate::FileOpener for FileOpener {
fn open(&mut self, path: &Path, conf: &OpenOptionsConfig) -> Result<Box<dyn VirtualFile + Sync>> {
fn open(
&mut self,
path: &Path,
conf: &OpenOptionsConfig,
) -> Result<Box<dyn VirtualFile + Sync>> {
let read = conf.read();
let mut write = conf.write();
let append = conf.append();

View File

@@ -2,12 +2,12 @@ use std::fmt;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::net::Shutdown;
use std::net::SocketAddr;
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use std::sync::mpsc;
use thiserror::Error;
pub use bytes::Bytes;
@@ -21,32 +21,26 @@ pub type SocketDescriptor = wasmer_vfs::FileDescriptor;
/// Represents an IP address and its netmask
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct IpCidr
{
pub struct IpCidr {
pub ip: IpAddr,
pub prefix: u8,
}
/// Represents a routing entry in the routing table of the interface
#[derive(Clone, Debug)]
pub struct IpRoute
{
pub struct IpRoute {
pub cidr: IpCidr,
pub via_router: IpAddr,
pub preferred_until: Option<Duration>,
pub expires_at: Option<Duration>
pub expires_at: Option<Duration>,
}
/// An implementation of virtual networking
pub trait VirtualNetworking: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualNetworking: fmt::Debug + Send + Sync + 'static {
/// Establishes a web socket connection
/// (note: this does not use the virtual sockets and is standalone
/// functionality that works without the network being connected)
fn ws_connect(
&self,
url: &str,
) -> Result<Box<dyn VirtualWebSocket + Sync>>;
fn ws_connect(&self, url: &str) -> Result<Box<dyn VirtualWebSocket + Sync>>;
/// Makes a HTTP request to a remote web resource
/// The headers are separated by line breaks
@@ -62,56 +56,31 @@ pub trait VirtualNetworking: fmt::Debug + Send + Sync + 'static
/// Bridges this local network with a remote network, which is required in
/// order to make lower level networking calls (such as UDP/TCP)
fn bridge(
&self,
network: &str,
access_token: &str,
security: StreamSecurity,
) -> Result<()>;
fn bridge(&self, network: &str, access_token: &str, security: StreamSecurity) -> Result<()>;
/// Disconnects from the remote network essentially unbridging it
fn unbridge(
&self,
) -> Result<()>;
fn unbridge(&self) -> Result<()>;
/// Acquires an IP address on the network and configures the routing tables
fn dhcp_acquire(
&self,
) -> Result<Vec<IpAddr>>;
fn dhcp_acquire(&self) -> Result<Vec<IpAddr>>;
/// Adds a static IP address to the interface with a netmask prefix
fn ip_add(
&self,
ip: IpAddr,
prefix: u8,
) -> Result<()>;
fn ip_add(&self, ip: IpAddr, prefix: u8) -> Result<()>;
/// Removes a static (or dynamic) IP address from the interface
fn ip_remove(
&self,
ip: IpAddr,
) -> Result<()>;
fn ip_remove(&self, ip: IpAddr) -> Result<()>;
/// Clears all the assigned IP addresses for this interface
fn ip_clear(
&self,
) -> Result<()>;
fn ip_clear(&self) -> Result<()>;
/// Lists all the IP addresses currently assigned to this interface
fn ip_list(
&self,
) -> Result<Vec<IpCidr>>;
fn ip_list(&self) -> Result<Vec<IpCidr>>;
/// Returns the hardware MAC address for this interface
fn mac(
&self,
) -> Result<[u8; 6]>;
fn mac(&self) -> Result<[u8; 6]>;
/// Adds a default gateway to the routing table
fn gateway_set(
&self,
ip: IpAddr,
) -> Result<()>;
fn gateway_set(&self, ip: IpAddr) -> Result<()>;
/// Adds a specific route to the routing table
fn route_add(
@@ -123,26 +92,17 @@ pub trait VirtualNetworking: fmt::Debug + Send + Sync + 'static
) -> Result<()>;
/// Removes a routing rule from the routing table
fn route_remove(
&self,
cidr: IpAddr,
) -> Result<()>;
fn route_remove(&self, cidr: IpAddr) -> Result<()>;
/// Clears the routing table for this interface
fn route_clear(
&self,
) -> Result<()>;
fn route_clear(&self) -> Result<()>;
/// Lists all the routes defined in the routing table for this interface
fn route_list(
&self,
) -> Result<Vec<IpRoute>>;
fn route_list(&self) -> Result<Vec<IpRoute>>;
/// Creates a low level socket that can read and write Ethernet packets
/// directly to the interface
fn bind_raw(
&self,
) -> Result<Box<dyn VirtualRawSocket + Sync>>;
fn bind_raw(&self) -> Result<Box<dyn VirtualRawSocket + Sync>>;
/// Lists for TCP connections on a specific IP and Port combination
/// Multiple servers (processes or threads) can bind to the same port if they each set
@@ -167,10 +127,7 @@ pub trait VirtualNetworking: fmt::Debug + Send + Sync + 'static
/// Creates a socket that can be used to send and receive ICMP packets
/// from a paritcular IP address
fn bind_icmp(
&self,
addr: IpAddr,
) -> Result<Box<dyn VirtualIcmpSocket + Sync>>;
fn bind_icmp(&self, addr: IpAddr) -> Result<Box<dyn VirtualIcmpSocket + Sync>>;
/// Opens a TCP connection to a particular destination IP address and port
fn connect_tcp(
@@ -191,8 +148,7 @@ pub trait VirtualNetworking: fmt::Debug + Send + Sync + 'static
/// Holds the interface used to work with a pending HTTP request
#[derive(Debug)]
pub struct SocketHttpRequest
{
pub struct SocketHttpRequest {
/// Used to send the request bytes to the HTTP server
/// (once all bytes are send the sender should be closed)
pub request: Option<mpsc::Sender<Vec<u8>>>,
@@ -208,8 +164,7 @@ pub struct SocketHttpRequest
/// Represents the final result of a HTTP request
#[derive(Debug)]
pub struct HttpStatus
{
pub struct HttpStatus {
/// Indicates if the HTTP request was redirected to another URL / server
pub redirected: bool,
/// Size of the data held in the response receiver
@@ -221,8 +176,7 @@ pub struct HttpStatus
}
#[derive(Debug)]
pub struct SocketReceive
{
pub struct SocketReceive {
/// Data that was received
pub data: Bytes,
/// Indicates if the data was truncated (e.g. UDP packet)
@@ -230,93 +184,65 @@ pub struct SocketReceive
}
#[derive(Debug)]
pub struct SocketReceiveFrom
{
pub struct SocketReceiveFrom {
/// Data that was received
pub data: Bytes,
/// Indicates if the data was truncated (e.g. UDP packet)
pub truncated: bool,
/// Peer sender address of the data
pub addr: SocketAddr
pub addr: SocketAddr,
}
pub trait VirtualTcpListener: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualTcpListener: fmt::Debug + Send + Sync + 'static {
/// Accepts an connection attempt that was made to this listener
fn accept(
&self,
) -> Result<(Box<dyn VirtualTcpSocket + Sync>, SocketAddr)>;
fn accept(&self) -> Result<(Box<dyn VirtualTcpSocket + Sync>, SocketAddr)>;
/// Accepts an connection attempt that was made to this listener (or times out)
fn accept_timeout(
&self,
timeout: Duration
timeout: Duration,
) -> Result<(Box<dyn VirtualTcpSocket + Sync>, SocketAddr)>;
/// Sets the accept timeout
fn set_timeout(
&mut self,
timeout: Option<Duration>
) -> Result<()>;
fn set_timeout(&mut self, timeout: Option<Duration>) -> Result<()>;
/// Gets the accept timeout
fn timeout(
&self
) -> Result<Option<Duration>>;
fn timeout(&self) -> Result<Option<Duration>>;
/// Returns the local address of this TCP listener
fn addr_local(
&self,
) -> Result<SocketAddr>;
fn addr_local(&self) -> Result<SocketAddr>;
/// Sets how many network hops the packets are permitted for new connections
fn set_ttl(
&mut self,
ttl: u8,
) -> Result<()>;
fn set_ttl(&mut self, ttl: u8) -> Result<()>;
/// Returns the maximum number of network hops before packets are dropped
fn ttl(
&self,
) -> Result<u8>;
fn ttl(&self) -> Result<u8>;
}
pub trait VirtualSocket: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualSocket: fmt::Debug + Send + Sync + 'static {
/// Sets how many network hops the packets are permitted for new connections
fn set_ttl(
&mut self,
ttl: u32,
) -> Result<()>;
fn set_ttl(&mut self, ttl: u32) -> Result<()>;
/// Returns the maximum number of network hops before packets are dropped
fn ttl(
&self,
) -> Result<u32>;
fn ttl(&self) -> Result<u32>;
/// Returns the local address for this socket
fn addr_local(
&self,
) -> Result<SocketAddr>;
fn addr_local(&self) -> Result<SocketAddr>;
/// Returns the status/state of the socket
fn status(
&self,
) -> Result<SocketStatus>;
fn status(&self) -> Result<SocketStatus>;
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SocketStatus
{
pub enum SocketStatus {
Opening,
Opened,
Closed,
Failed
Failed,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum StreamSecurity
{
pub enum StreamSecurity {
Unencrypted,
AnyEncyption,
ClassicEncryption,
@@ -324,131 +250,86 @@ pub enum StreamSecurity
}
/// Interface used for sending and receiving data from a web socket
pub trait VirtualWebSocket: fmt::Debug + Send + Sync + 'static
{
pub trait VirtualWebSocket: fmt::Debug + Send + Sync + 'static {
/// Sends out a datagram or stream of bytes on this socket
fn send(
&mut self,
data: Bytes,
) -> Result<usize>;
fn send(&mut self, data: Bytes) -> Result<usize>;
/// FLushes all the datagrams
fn flush(
&mut self,
) -> Result<()>;
fn flush(&mut self) -> Result<()>;
/// Recv a packet from the socket
fn recv(
&mut self,
) -> Result<SocketReceive>;
fn recv(&mut self) -> Result<SocketReceive>;
}
/// Connected sockets have a persistent connection to a remote peer
pub trait VirtualConnectedSocket: VirtualSocket + fmt::Debug + Send + Sync + 'static
{
pub trait VirtualConnectedSocket: VirtualSocket + fmt::Debug + Send + Sync + 'static {
/// Determines how long the socket will remain in a TIME_WAIT
/// after it disconnects (only the one that initiates the close will
/// be in a TIME_WAIT state thus the clients should always do this rather
/// than the server)
fn set_linger(
&mut self,
linger: Option<Duration>,
) -> Result<()>;
fn set_linger(&mut self, linger: Option<Duration>) -> Result<()>;
/// Returns how long the socket will remain in a TIME_WAIT
/// after it disconnects
fn linger(
&self,
) -> Result<Option<Duration>>;
fn linger(&self) -> Result<Option<Duration>>;
/// Sends out a datagram or stream of bytes on this socket
fn send(
&mut self,
data: Bytes,
) -> Result<usize>;
fn send(&mut self, data: Bytes) -> Result<usize>;
/// FLushes all the datagrams
fn flush(
&mut self,
) -> Result<()>;
fn flush(&mut self) -> Result<()>;
/// Recv a packet from the socket
fn recv(
&mut self,
) -> Result<SocketReceive>;
fn recv(&mut self) -> Result<SocketReceive>;
/// Peeks for a packet from the socket
fn peek(
&mut self,
) -> Result<SocketReceive>;
fn peek(&mut self) -> Result<SocketReceive>;
}
/// Connectionless sockets are able to send and receive datagrams and stream
/// bytes to multiple addresses at the same time (peer-to-peer)
pub trait VirtualConnectionlessSocket: VirtualSocket + fmt::Debug + Send + Sync + 'static
{
pub trait VirtualConnectionlessSocket: VirtualSocket + fmt::Debug + Send + Sync + 'static {
/// Sends out a datagram or stream of bytes on this socket
/// to a specific address
fn send_to(
&mut self,
data: Bytes,
addr: SocketAddr,
) -> Result<usize>;
fn send_to(&mut self, data: Bytes, addr: SocketAddr) -> Result<usize>;
/// Recv a packet from the socket
fn recv_from(
&mut self,
) -> Result<SocketReceiveFrom>;
fn recv_from(&mut self) -> Result<SocketReceiveFrom>;
/// Peeks for a packet from the socket
fn peek_from(
&mut self,
) -> Result<SocketReceiveFrom>;
fn peek_from(&mut self) -> Result<SocketReceiveFrom>;
}
/// ICMP sockets are low level devices bound to a specific address
/// that can send and receive ICMP packets
pub trait VirtualIcmpSocket: VirtualConnectionlessSocket + fmt::Debug + Send + Sync + 'static
pub trait VirtualIcmpSocket:
VirtualConnectionlessSocket + fmt::Debug + Send + Sync + 'static
{
}
pub trait VirtualRawSocket: VirtualSocket + fmt::Debug + Send + Sync + 'static
{
pub trait VirtualRawSocket: VirtualSocket + fmt::Debug + Send + Sync + 'static {
/// Sends out a raw packet on this socket
fn send(
&mut self,
data: Bytes,
) -> Result<usize>;
fn send(&mut self, data: Bytes) -> Result<usize>;
/// FLushes all the datagrams
fn flush(
&mut self,
) -> Result<()>;
fn flush(&mut self) -> Result<()>;
/// Recv a packet from the socket
fn recv(
&mut self,
) -> Result<SocketReceive>;
fn recv(&mut self) -> Result<SocketReceive>;
/// Tells the raw socket and its backing switch that all packets
/// should be received by this socket even if they are not
/// destined for this device
fn set_promiscuous(
&mut self,
promiscuous: bool
) -> Result<()>;
fn set_promiscuous(&mut self, promiscuous: bool) -> Result<()>;
/// Returns if the socket is running in promiscuous mode whereby it
/// will receive all packets even if they are not destined for the
/// local interface
fn promiscuous(
&self,
) -> Result<bool>;
fn promiscuous(&self) -> Result<bool>;
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TimeType
{
pub enum TimeType {
ReadTimeout,
WriteTimeout,
AcceptTimeout,
@@ -456,199 +337,133 @@ pub enum TimeType
Linger,
}
pub trait VirtualTcpSocket: VirtualConnectedSocket + fmt::Debug + Send + Sync + 'static
{
pub trait VirtualTcpSocket: VirtualConnectedSocket + fmt::Debug + Send + Sync + 'static {
/// Sets the timeout for a specific action on the socket
fn set_opt_time(
&mut self,
ty: TimeType,
timeout: Option<Duration>,
) -> Result<()>;
fn set_opt_time(&mut self, ty: TimeType, timeout: Option<Duration>) -> Result<()>;
/// Returns one of the previous set timeouts
fn opt_time(
&self,
ty: TimeType,
) -> Result<Option<Duration>>;
fn opt_time(&self, ty: TimeType) -> Result<Option<Duration>>;
/// Sets the receive buffer size which acts as a trottle for how
/// much data is buffered on this side of the pipe
fn set_recv_buf_size(
&mut self,
size: usize,
) -> Result<()>;
fn set_recv_buf_size(&mut self, size: usize) -> Result<()>;
/// Size of the receive buffer that holds all data that has not
/// yet been read
fn recv_buf_size(
&self,
) -> Result<usize>;
fn recv_buf_size(&self) -> Result<usize>;
/// Sets the size of the send buffer which will hold the bytes of
/// data while they are being sent over to the peer
fn set_send_buf_size(
&mut self,
size: usize,
) -> Result<()>;
fn set_send_buf_size(&mut self, size: usize) -> Result<()>;
/// Size of the send buffer that holds all data that is currently
/// being transmitted.
fn send_buf_size(
&self,
) -> Result<usize>;
fn send_buf_size(&self) -> Result<usize>;
/// When NO_DELAY is set the data that needs to be transmitted to
/// the peer is sent immediately rather than waiting for a bigger
/// batch of data, this reduces latency but increases encapsulation
/// overhead.
fn set_nodelay(
&mut self,
reuse: bool
) -> Result<()>;
fn set_nodelay(&mut self, reuse: bool) -> Result<()>;
/// Indicates if the NO_DELAY flag is set which means that data
/// is immediately sent to the peer without waiting. This reduces
/// latency but increases encapsulation overhead.
fn nodelay(
&self,
) -> Result<bool>;
fn nodelay(&self) -> Result<bool>;
/// Returns the address (IP and Port) of the peer socket that this
/// is conencted to
fn addr_peer(
&self,
) -> Result<SocketAddr>;
fn addr_peer(&self) -> Result<SocketAddr>;
/// Causes all the data held in the send buffer to be immediately
/// flushed to the destination peer
fn flush(
&mut self,
) -> Result<()>;
fn flush(&mut self) -> Result<()>;
/// Shuts down either the READER or WRITER sides of the socket
/// connection.
fn shutdown(
&mut self,
how: Shutdown,
) -> Result<()>;
fn shutdown(&mut self, how: Shutdown) -> Result<()>;
}
pub trait VirtualUdpSocket: VirtualConnectedSocket + VirtualConnectionlessSocket + fmt::Debug + Send + Sync + 'static
pub trait VirtualUdpSocket:
VirtualConnectedSocket + VirtualConnectionlessSocket + fmt::Debug + Send + Sync + 'static
{
/// Connects to a destination peer so that the normal
/// send/recv operations can be used.
fn connect(
&mut self,
addr: SocketAddr,
) -> Result<()>;
fn connect(&mut self, addr: SocketAddr) -> Result<()>;
/// Sets a flag that means that the UDP socket is able
/// to receive and process broadcast packets.
fn set_broadcast(
&mut self,
broadcast: bool
) -> Result<()>;
fn set_broadcast(&mut self, broadcast: bool) -> Result<()>;
/// Indicates if the SO_BROADCAST flag is set which means
/// that the UDP socket will receive and process broadcast
/// packets
fn broadcast(
&self,
) -> Result<bool>;
fn broadcast(&self) -> Result<bool>;
/// Sets a flag that indicates if multicast packets that
/// this socket is a member of will be looped back to
/// the sending socket. This applies to IPv4 addresses
fn set_multicast_loop_v4(
&mut self,
val: bool
) -> Result<()>;
fn set_multicast_loop_v4(&mut self, val: bool) -> Result<()>;
/// Gets a flag that indicates if multicast packets that
/// this socket is a member of will be looped back to
/// the sending socket. This applies to IPv4 addresses
fn multicast_loop_v4(
&self,
) -> Result<bool>;
fn multicast_loop_v4(&self) -> Result<bool>;
/// Sets a flag that indicates if multicast packets that
/// this socket is a member of will be looped back to
/// the sending socket. This applies to IPv6 addresses
fn set_multicast_loop_v6(
&mut self,
val: bool
) -> Result<()>;
fn set_multicast_loop_v6(&mut self, val: bool) -> Result<()>;
/// Gets a flag that indicates if multicast packets that
/// this socket is a member of will be looped back to
/// the sending socket. This applies to IPv6 addresses
fn multicast_loop_v6(
&self,
) -> Result<bool>;
fn multicast_loop_v6(&self) -> Result<bool>;
/// Sets the TTL for IPv4 multicast packets which is the
/// number of network hops before the packet is dropped
fn set_multicast_ttl_v4(
&mut self,
ttl: u32,
) -> Result<()>;
fn set_multicast_ttl_v4(&mut self, ttl: u32) -> Result<()>;
/// Gets the TTL for IPv4 multicast packets which is the
/// number of network hops before the packet is dropped
fn multicast_ttl_v4(
&self,
) -> Result<u32>;
fn multicast_ttl_v4(&self) -> Result<u32>;
/// Tells this interface that it will subscribe to a
/// particular multicast address. This applies to IPv4 addresses
fn join_multicast_v4(
&mut self,
multiaddr: Ipv4Addr,
iface: Ipv4Addr,
) -> Result<()>;
fn join_multicast_v4(&mut self, multiaddr: Ipv4Addr, iface: Ipv4Addr) -> Result<()>;
/// Tells this interface that it will unsubscribe to a
/// particular multicast address. This applies to IPv4 addresses
fn leave_multicast_v4(
&mut self,
multiaddr: Ipv4Addr,
iface: Ipv4Addr,
) -> Result<()>;
fn leave_multicast_v4(&mut self, multiaddr: Ipv4Addr, iface: Ipv4Addr) -> Result<()>;
/// Tells this interface that it will subscribe to a
/// particular multicast address. This applies to IPv6 addresses
fn join_multicast_v6(
&mut self,
multiaddr: Ipv6Addr,
iface: u32,
) -> Result<()>;
fn join_multicast_v6(&mut self, multiaddr: Ipv6Addr, iface: u32) -> Result<()>;
/// Tells this interface that it will unsubscribe to a
/// particular multicast address. This applies to IPv6 addresses
fn leave_multicast_v6(
&mut self,
multiaddr: Ipv6Addr,
iface: u32,
) -> Result<()>;
fn leave_multicast_v6(&mut self, multiaddr: Ipv6Addr, iface: u32) -> Result<()>;
/// Returns the remote address of this UDP socket if it has been
/// connected to a specific target destination address
fn addr_peer(
&self,
) -> Result<Option<SocketAddr>>;
fn addr_peer(&self) -> Result<Option<SocketAddr>>;
}
#[derive(Debug, Default)]
pub struct UnsupportedVirtualNetworking {}
impl VirtualNetworking
for UnsupportedVirtualNetworking
{
impl VirtualNetworking for UnsupportedVirtualNetworking {
fn ws_connect(&self, _url: &str) -> Result<Box<dyn VirtualWebSocket + Sync>> {
Err(NetworkError::Unsupported)
}
fn http_request(&self, _url: &str, _method: &str, _headers: &str, _gzip: bool) -> Result<SocketHttpRequest> {
fn http_request(
&self,
_url: &str,
_method: &str,
_headers: &str,
_gzip: bool,
) -> Result<SocketHttpRequest> {
Err(NetworkError::Unsupported)
}
@@ -688,7 +503,13 @@ for UnsupportedVirtualNetworking
Err(NetworkError::Unsupported)
}
fn route_add(&self, _cidr: IpCidr, _via_router: IpAddr, _preferred_until: Option<Duration>, _expires_at: Option<Duration>) -> Result<()> {
fn route_add(
&self,
_cidr: IpCidr,
_via_router: IpAddr,
_preferred_until: Option<Duration>,
_expires_at: Option<Duration>,
) -> Result<()> {
Err(NetworkError::Unsupported)
}
@@ -712,19 +533,40 @@ for UnsupportedVirtualNetworking
Err(NetworkError::Unsupported)
}
fn listen_tcp(&self, _addr: SocketAddr, _only_v6: bool, _reuse_port: bool, _reuse_addr: bool) -> Result<Box<dyn VirtualTcpListener + Sync>> {
fn listen_tcp(
&self,
_addr: SocketAddr,
_only_v6: bool,
_reuse_port: bool,
_reuse_addr: bool,
) -> Result<Box<dyn VirtualTcpListener + Sync>> {
Err(NetworkError::Unsupported)
}
fn connect_tcp(&self, _addr: SocketAddr, _peer: SocketAddr, _timeout: Option<Duration>) -> Result<Box<dyn VirtualTcpSocket + Sync>> {
fn connect_tcp(
&self,
_addr: SocketAddr,
_peer: SocketAddr,
_timeout: Option<Duration>,
) -> Result<Box<dyn VirtualTcpSocket + Sync>> {
Err(NetworkError::Unsupported)
}
fn bind_udp(&self, _addr: SocketAddr, _reuse_port: bool, _reuse_addr: bool) -> Result<Box<dyn VirtualUdpSocket + Sync>> {
fn bind_udp(
&self,
_addr: SocketAddr,
_reuse_port: bool,
_reuse_addr: bool,
) -> Result<Box<dyn VirtualUdpSocket + Sync>> {
Err(NetworkError::Unsupported)
}
fn resolve(&self, _host: &str, _port: Option<u16>, _dns_server: Option<IpAddr>) -> Result<Vec<IpAddr>> {
fn resolve(
&self,
_host: &str,
_port: Option<u16>,
_dns_server: Option<IpAddr>,
) -> Result<Vec<IpAddr>> {
Err(NetworkError::Unsupported)
}
}

View File

@@ -1,52 +1,23 @@
#![allow(unused_variables)]
use std::time::Duration;
use std::net::{
IpAddr,
SocketAddr,
Shutdown, Ipv6Addr, Ipv4Addr,
};
use std::io::{
Read,
Write,
};
use bytes::{Bytes, BytesMut};
use wasmer_vnet::{
io_err_into_net_error,
VirtualConnectedSocket,
VirtualSocket,
VirtualNetworking,
VirtualWebSocket,
VirtualTcpListener,
VirtualRawSocket,
VirtualUdpSocket,
VirtualIcmpSocket,
VirtualTcpSocket,
SocketHttpRequest,
StreamSecurity,
SocketReceive,
SocketStatus,
IpCidr,
IpRoute,
TimeType,
Result,
NetworkError, VirtualConnectionlessSocket, SocketReceiveFrom
};
use std::io::{Read, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
use std::time::Duration;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};
use wasmer_vnet::{
io_err_into_net_error, IpCidr, IpRoute, NetworkError, Result, SocketHttpRequest, SocketReceive,
SocketReceiveFrom, SocketStatus, StreamSecurity, TimeType, VirtualConnectedSocket,
VirtualConnectionlessSocket, VirtualIcmpSocket, VirtualNetworking, VirtualRawSocket,
VirtualSocket, VirtualTcpListener, VirtualTcpSocket, VirtualUdpSocket, VirtualWebSocket,
};
#[derive(Debug, Default)]
pub struct LocalNetworking
{
}
pub struct LocalNetworking {}
#[allow(unused_variables)]
impl VirtualNetworking
for LocalNetworking
{
fn ws_connect(
&self,
url: &str,
) -> Result<Box<dyn VirtualWebSocket + Sync>> {
impl VirtualNetworking for LocalNetworking {
fn ws_connect(&self, url: &str) -> Result<Box<dyn VirtualWebSocket + Sync>> {
Err(NetworkError::Unsupported)
}
@@ -60,64 +31,39 @@ for LocalNetworking
Err(NetworkError::Unsupported)
}
fn bridge(
&self,
network: &str,
access_token: &str,
security: StreamSecurity,
) -> Result<()> {
fn bridge(&self, network: &str, access_token: &str, security: StreamSecurity) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn unbridge(
&self,
) -> Result<()> {
fn unbridge(&self) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn dhcp_acquire(
&self,
) -> Result<Vec<IpAddr>> {
fn dhcp_acquire(&self) -> Result<Vec<IpAddr>> {
Err(NetworkError::Unsupported)
}
fn ip_add(
&self,
ip: IpAddr,
prefix: u8,
) -> Result<()> {
fn ip_add(&self, ip: IpAddr, prefix: u8) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn ip_remove(
&self,
ip: IpAddr,
) -> Result<()> {
fn ip_remove(&self, ip: IpAddr) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn ip_clear(
&self,
) -> Result<()> {
fn ip_clear(&self) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn ip_list(
&self,
) -> Result<Vec<IpCidr>> {
fn ip_list(&self) -> Result<Vec<IpCidr>> {
Err(NetworkError::Unsupported)
}
fn mac(
&self,
) -> Result<[u8; 6]> {
fn mac(&self) -> Result<[u8; 6]> {
Err(NetworkError::Unsupported)
}
fn gateway_set(
&self,
ip: IpAddr,
) -> Result<()> {
fn gateway_set(&self, ip: IpAddr) -> Result<()> {
Err(NetworkError::Unsupported)
}
@@ -131,28 +77,19 @@ for LocalNetworking
Err(NetworkError::Unsupported)
}
fn route_remove(
&self,
cidr: IpAddr,
) -> Result<()> {
fn route_remove(&self, cidr: IpAddr) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn route_clear(
&self,
) -> Result<()> {
fn route_clear(&self) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn route_list(
&self,
) -> Result<Vec<IpRoute>> {
fn route_list(&self) -> Result<Vec<IpRoute>> {
Err(NetworkError::Unsupported)
}
fn bind_raw(
&self,
) -> Result<Box<dyn VirtualRawSocket + Sync>> {
fn bind_raw(&self) -> Result<Box<dyn VirtualRawSocket + Sync>> {
Err(NetworkError::Unsupported)
}
@@ -164,10 +101,12 @@ for LocalNetworking
reuse_addr: bool,
) -> Result<Box<dyn VirtualTcpListener + Sync>> {
let listener = std::net::TcpListener::bind(addr)
.map(|sock| Box::new(LocalTcpListener {
.map(|sock| {
Box::new(LocalTcpListener {
stream: sock,
timeout: None,
}))
})
})
.map_err(io_err_into_net_error)?;
Ok(listener)
}
@@ -178,15 +117,11 @@ for LocalNetworking
_reuse_port: bool,
_reuse_addr: bool,
) -> Result<Box<dyn VirtualUdpSocket + Sync>> {
let socket = std::net::UdpSocket::bind(addr)
.map_err(io_err_into_net_error)?;
let socket = std::net::UdpSocket::bind(addr).map_err(io_err_into_net_error)?;
Ok(Box::new(LocalUdpSocket(socket, addr)))
}
fn bind_icmp(
&self,
addr: IpAddr,
) -> Result<Box<dyn VirtualIcmpSocket + Sync>> {
fn bind_icmp(&self, addr: IpAddr) -> Result<Box<dyn VirtualIcmpSocket + Sync>> {
Err(NetworkError::Unsupported)
}
@@ -202,8 +137,7 @@ for LocalNetworking
std::net::TcpStream::connect(peer)
}
.map_err(io_err_into_net_error)?;
let peer = stream.peer_addr()
.map_err(io_err_into_net_error)?;
let peer = stream.peer_addr().map_err(io_err_into_net_error)?;
Ok(Box::new(LocalTcpStream {
stream,
addr: peer,
@@ -218,22 +152,16 @@ for LocalNetworking
dns_server: Option<IpAddr>,
) -> Result<Vec<IpAddr>> {
use std::net::ToSocketAddrs;
Ok(
if let Some(port) = port {
Ok(if let Some(port) = port {
let host = format!("{}:{}", host, port);
host.to_socket_addrs()
.map(|a| a
.map(|a| a.ip())
.collect::<Vec<_>>())
.map(|a| a.map(|a| a.ip()).collect::<Vec<_>>())
.map_err(io_err_into_net_error)?
} else {
host.to_socket_addrs()
.map(|a| a
.map(|a| a.ip())
.collect::<Vec<_>>())
.map(|a| a.map(|a| a.ip()).collect::<Vec<_>>())
.map_err(io_err_into_net_error)?
}
)
})
}
}
@@ -243,27 +171,26 @@ pub struct LocalTcpListener {
timeout: Option<Duration>,
}
impl VirtualTcpListener
for LocalTcpListener
{
fn accept(
&self,
) -> Result<(Box<dyn VirtualTcpSocket + Sync>, SocketAddr)> {
impl VirtualTcpListener for LocalTcpListener {
fn accept(&self) -> Result<(Box<dyn VirtualTcpSocket + Sync>, SocketAddr)> {
if let Some(timeout) = &self.timeout {
return self.accept_timeout(timeout.clone())
return self.accept_timeout(timeout.clone());
}
let (sock, addr) = self.stream.accept()
let (sock, addr) = self
.stream
.accept()
.map(|(sock, addr)| {
(Box::new(LocalTcpStream {
(
Box::new(LocalTcpStream {
stream: sock,
addr: addr.clone(),
connect_timeout: None,
}), addr)
}),
addr,
)
})
.map_err(io_err_into_net_error)?;
Ok(
(sock, addr)
)
Ok((sock, addr))
}
#[cfg(feature = "wasix")]
@@ -271,18 +198,21 @@ for LocalTcpListener
&self,
timeout: Duration,
) -> Result<(Box<dyn VirtualTcpSocket + Sync>, SocketAddr)> {
let (sock, addr) = self.stream.accept_timeout(timeout)
let (sock, addr) = self
.stream
.accept_timeout(timeout)
.map(|(sock, addr)| {
(Box::new(LocalTcpStream {
(
Box::new(LocalTcpStream {
stream: sock,
addr: addr.clone(),
connect_timeout: None,
}), addr)
}),
addr,
)
})
.map_err(io_err_into_net_error)?;
Ok(
(sock, addr)
)
Ok((sock, addr))
}
#[cfg(not(feature = "wasix"))]
@@ -294,41 +224,27 @@ for LocalTcpListener
}
/// Sets the accept timeout
fn set_timeout(
&mut self,
timeout: Option<Duration>
) -> Result<()> {
fn set_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
self.timeout = timeout;
Ok(())
}
/// Gets the accept timeout
fn timeout(
&self
) -> Result<Option<Duration>> {
fn timeout(&self) -> Result<Option<Duration>> {
Ok(self.timeout.clone())
}
fn addr_local(
&self,
) -> Result<SocketAddr> {
self.stream
.local_addr()
.map_err(io_err_into_net_error)
fn addr_local(&self) -> Result<SocketAddr> {
self.stream.local_addr().map_err(io_err_into_net_error)
}
fn set_ttl(
&mut self,
ttl: u8,
) -> Result<()> {
fn set_ttl(&mut self, ttl: u8) -> Result<()> {
self.stream
.set_ttl(ttl as u32)
.map_err(io_err_into_net_error)
}
fn ttl(
&self,
) -> Result<u8> {
fn ttl(&self) -> Result<u8> {
self.stream
.ttl()
.map(|ttl| ttl as u8)
@@ -343,31 +259,31 @@ pub struct LocalTcpStream {
connect_timeout: Option<Duration>,
}
impl VirtualTcpSocket
for LocalTcpStream
{
fn set_opt_time(
&mut self,
ty: TimeType,
timeout: Option<Duration>,
) -> Result<()> {
impl VirtualTcpSocket for LocalTcpStream {
fn set_opt_time(&mut self, ty: TimeType, timeout: Option<Duration>) -> Result<()> {
match ty {
TimeType::ReadTimeout => self.stream.set_read_timeout(timeout).map_err(io_err_into_net_error),
TimeType::WriteTimeout => self.stream.set_write_timeout(timeout).map_err(io_err_into_net_error),
TimeType::ReadTimeout => self
.stream
.set_read_timeout(timeout)
.map_err(io_err_into_net_error),
TimeType::WriteTimeout => self
.stream
.set_write_timeout(timeout)
.map_err(io_err_into_net_error),
TimeType::ConnectTimeout => {
self.connect_timeout = timeout;
Ok(())
},
}
#[cfg(feature = "wasix")]
TimeType::Linger => self.stream.set_linger(timeout).map_err(io_err_into_net_error),
TimeType::Linger => self
.stream
.set_linger(timeout)
.map_err(io_err_into_net_error),
_ => Err(NetworkError::InvalidInput),
}
}
fn opt_time(
&self,
ty: TimeType,
) -> Result<Option<Duration>> {
fn opt_time(&self, ty: TimeType) -> Result<Option<Duration>> {
match ty {
TimeType::ReadTimeout => self.stream.read_timeout().map_err(io_err_into_net_error),
TimeType::WriteTimeout => self.stream.write_timeout().map_err(io_err_into_net_error),
@@ -378,433 +294,294 @@ for LocalTcpStream
}
}
fn set_recv_buf_size(
&mut self,
size: usize,
) -> Result<()> {
fn set_recv_buf_size(&mut self, size: usize) -> Result<()> {
Ok(())
}
fn recv_buf_size(
&self,
) -> Result<usize> {
fn recv_buf_size(&self) -> Result<usize> {
Err(NetworkError::Unsupported)
}
fn set_send_buf_size(
&mut self,
size: usize,
) -> Result<()> {
fn set_send_buf_size(&mut self, size: usize) -> Result<()> {
Ok(())
}
fn send_buf_size(
&self,
) -> Result<usize> {
fn send_buf_size(&self) -> Result<usize> {
Err(NetworkError::Unsupported)
}
fn set_nodelay(
&mut self,
nodelay: bool
) -> Result<()> {
self.stream.set_nodelay(nodelay).map_err(io_err_into_net_error)
fn set_nodelay(&mut self, nodelay: bool) -> Result<()> {
self.stream
.set_nodelay(nodelay)
.map_err(io_err_into_net_error)
}
fn nodelay(
&self,
) -> Result<bool> {
fn nodelay(&self) -> Result<bool> {
self.stream.nodelay().map_err(io_err_into_net_error)
}
fn addr_peer(
&self,
) -> Result<SocketAddr> {
fn addr_peer(&self) -> Result<SocketAddr> {
Ok(self.addr.clone())
}
fn flush(
&mut self,
) -> Result<()> {
fn flush(&mut self) -> Result<()> {
Ok(())
}
fn shutdown(
&mut self,
how: Shutdown,
) -> Result<()> {
fn shutdown(&mut self, how: Shutdown) -> Result<()> {
self.stream.shutdown(how).map_err(io_err_into_net_error)
}
}
impl VirtualConnectedSocket
for LocalTcpStream
{
fn set_linger(
&mut self,
linger: Option<Duration>,
) -> Result<()> {
impl VirtualConnectedSocket for LocalTcpStream {
fn set_linger(&mut self, linger: Option<Duration>) -> Result<()> {
#[cfg(feature = "wasix")]
self.stream.set_linger(linger).map_err(io_err_into_net_error)?;
self.stream
.set_linger(linger)
.map_err(io_err_into_net_error)?;
Ok(())
}
#[cfg(feature = "wasix")]
fn linger(
&self,
) -> Result<Option<Duration>> {
fn linger(&self) -> Result<Option<Duration>> {
self.stream.linger().map_err(io_err_into_net_error)
}
#[cfg(not(feature = "wasix"))]
fn linger(
&self,
) -> Result<Option<Duration>> {
fn linger(&self) -> Result<Option<Duration>> {
Ok(None)
}
fn send(
&mut self,
data: Bytes,
) -> Result<usize> {
self.stream.write_all(&data[..])
fn send(&mut self, data: Bytes) -> Result<usize> {
self.stream
.write_all(&data[..])
.map(|_| data.len())
.map_err(io_err_into_net_error)
}
fn flush(
&mut self,
) -> Result<()> {
self.stream.flush()
.map_err(io_err_into_net_error)
fn flush(&mut self) -> Result<()> {
self.stream.flush().map_err(io_err_into_net_error)
}
fn recv(
&mut self,
) -> Result<SocketReceive> {
fn recv(&mut self) -> Result<SocketReceive> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let read = self.stream.read(&mut buf[..])
let read = self
.stream
.read(&mut buf[..])
.map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(
SocketReceive {
Ok(SocketReceive {
data: buf,
truncated: read == buf_size
}
)
truncated: read == buf_size,
})
}
fn peek(
&mut self,
) -> Result<SocketReceive> {
fn peek(&mut self) -> Result<SocketReceive> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let read = self.stream.peek(&mut buf[..])
let read = self
.stream
.peek(&mut buf[..])
.map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(
SocketReceive {
Ok(SocketReceive {
data: buf,
truncated: read == buf_size
}
)
truncated: read == buf_size,
})
}
}
impl VirtualSocket
for LocalTcpStream
{
fn set_ttl(
&mut self,
ttl: u32,
) -> Result<()> {
self.stream.set_ttl(ttl)
.map_err(io_err_into_net_error)
impl VirtualSocket for LocalTcpStream {
fn set_ttl(&mut self, ttl: u32) -> Result<()> {
self.stream.set_ttl(ttl).map_err(io_err_into_net_error)
}
fn ttl(
&self,
) -> Result<u32> {
self.stream.ttl()
.map_err(io_err_into_net_error)
fn ttl(&self) -> Result<u32> {
self.stream.ttl().map_err(io_err_into_net_error)
}
fn addr_local(
&self,
) -> Result<SocketAddr> {
self.stream.local_addr()
.map_err(io_err_into_net_error)
fn addr_local(&self) -> Result<SocketAddr> {
self.stream.local_addr().map_err(io_err_into_net_error)
}
fn status(
&self,
) -> Result<SocketStatus> {
Ok(
SocketStatus::Opened
)
fn status(&self) -> Result<SocketStatus> {
Ok(SocketStatus::Opened)
}
}
#[derive(Debug)]
pub struct LocalUdpSocket(std::net::UdpSocket, SocketAddr);
impl VirtualUdpSocket
for LocalUdpSocket
{
fn connect(
&mut self,
addr: SocketAddr,
) -> Result<()> {
self.0.connect(addr)
impl VirtualUdpSocket for LocalUdpSocket {
fn connect(&mut self, addr: SocketAddr) -> Result<()> {
self.0.connect(addr).map_err(io_err_into_net_error)
}
fn set_broadcast(&mut self, broadcast: bool) -> Result<()> {
self.0
.set_broadcast(broadcast)
.map_err(io_err_into_net_error)
}
fn set_broadcast(
&mut self,
broadcast: bool
) -> Result<()> {
self.0.set_broadcast(broadcast)
fn broadcast(&self) -> Result<bool> {
self.0.broadcast().map_err(io_err_into_net_error)
}
fn set_multicast_loop_v4(&mut self, val: bool) -> Result<()> {
self.0
.set_multicast_loop_v4(val)
.map_err(io_err_into_net_error)
}
fn broadcast(
&self,
) -> Result<bool> {
self.0.broadcast()
fn multicast_loop_v4(&self) -> Result<bool> {
self.0.multicast_loop_v4().map_err(io_err_into_net_error)
}
fn set_multicast_loop_v6(&mut self, val: bool) -> Result<()> {
self.0
.set_multicast_loop_v6(val)
.map_err(io_err_into_net_error)
}
fn set_multicast_loop_v4(
&mut self,
val: bool
) -> Result<()> {
self.0.set_multicast_loop_v4(val)
fn multicast_loop_v6(&self) -> Result<bool> {
self.0.multicast_loop_v6().map_err(io_err_into_net_error)
}
fn set_multicast_ttl_v4(&mut self, ttl: u32) -> Result<()> {
self.0
.set_multicast_ttl_v4(ttl)
.map_err(io_err_into_net_error)
}
fn multicast_loop_v4(
&self,
) -> Result<bool> {
self.0.multicast_loop_v4()
fn multicast_ttl_v4(&self) -> Result<u32> {
self.0.multicast_ttl_v4().map_err(io_err_into_net_error)
}
fn join_multicast_v4(&mut self, multiaddr: Ipv4Addr, iface: Ipv4Addr) -> Result<()> {
self.0
.join_multicast_v4(&multiaddr, &iface)
.map_err(io_err_into_net_error)
}
fn set_multicast_loop_v6(
&mut self,
val: bool
) -> Result<()> {
self.0.set_multicast_loop_v6(val)
fn leave_multicast_v4(&mut self, multiaddr: Ipv4Addr, iface: Ipv4Addr) -> Result<()> {
self.0
.leave_multicast_v4(&multiaddr, &iface)
.map_err(io_err_into_net_error)
}
fn multicast_loop_v6(
&self,
) -> Result<bool> {
self.0.multicast_loop_v6()
fn join_multicast_v6(&mut self, multiaddr: Ipv6Addr, iface: u32) -> Result<()> {
self.0
.join_multicast_v6(&multiaddr, iface)
.map_err(io_err_into_net_error)
}
fn set_multicast_ttl_v4(
&mut self,
ttl: u32,
) -> Result<()> {
self.0.set_multicast_ttl_v4(ttl)
fn leave_multicast_v6(&mut self, multiaddr: Ipv6Addr, iface: u32) -> Result<()> {
self.0
.leave_multicast_v6(&multiaddr, iface)
.map_err(io_err_into_net_error)
}
fn multicast_ttl_v4(
&self,
) -> Result<u32> {
self.0.multicast_ttl_v4()
.map_err(io_err_into_net_error)
}
fn join_multicast_v4(
&mut self,
multiaddr: Ipv4Addr,
iface: Ipv4Addr,
) -> Result<()> {
self.0.join_multicast_v4(&multiaddr, &iface)
.map_err(io_err_into_net_error)
}
fn leave_multicast_v4(
&mut self,
multiaddr: Ipv4Addr,
iface: Ipv4Addr,
) -> Result<()> {
self.0.leave_multicast_v4(&multiaddr, &iface)
.map_err(io_err_into_net_error)
}
fn join_multicast_v6(
&mut self,
multiaddr: Ipv6Addr,
iface: u32,
) -> Result<()> {
self.0.join_multicast_v6(&multiaddr, iface)
.map_err(io_err_into_net_error)
}
fn leave_multicast_v6(
&mut self,
multiaddr: Ipv6Addr,
iface: u32,
) -> Result<()> {
self.0.leave_multicast_v6(&multiaddr, iface)
.map_err(io_err_into_net_error)
}
fn addr_peer(
&self,
) -> Result<Option<SocketAddr>> {
self.0.peer_addr()
fn addr_peer(&self) -> Result<Option<SocketAddr>> {
self.0
.peer_addr()
.map(|a| Some(a))
.map_err(io_err_into_net_error)
}
}
impl VirtualConnectedSocket
for LocalUdpSocket
{
fn set_linger(
&mut self,
linger: Option<Duration>,
) -> Result<()> {
impl VirtualConnectedSocket for LocalUdpSocket {
fn set_linger(&mut self, linger: Option<Duration>) -> Result<()> {
Err(NetworkError::Unsupported)
}
fn linger(
&self,
) -> Result<Option<Duration>> {
fn linger(&self) -> Result<Option<Duration>> {
Err(NetworkError::Unsupported)
}
fn send(
&mut self,
data: Bytes,
) -> Result<usize> {
self.0.send(&data[..])
.map_err(io_err_into_net_error)
fn send(&mut self, data: Bytes) -> Result<usize> {
self.0.send(&data[..]).map_err(io_err_into_net_error)
}
fn flush(
&mut self,
) -> Result<()> {
fn flush(&mut self) -> Result<()> {
Ok(())
}
fn recv(
&mut self,
) -> Result<SocketReceive> {
fn recv(&mut self) -> Result<SocketReceive> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let read = self.0.recv(&mut buf[..])
.map_err(io_err_into_net_error)?;
let read = self.0.recv(&mut buf[..]).map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(
SocketReceive {
data: buf,
truncated: read == buf_size
}
)
}
fn peek(
&mut self,
) -> Result<SocketReceive> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let read = self.0.peek(&mut buf[..])
.map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(
SocketReceive {
data: buf,
truncated: read == buf_size
}
)
}
}
impl VirtualConnectionlessSocket
for LocalUdpSocket
{
fn send_to(
&mut self,
data: Bytes,
addr: SocketAddr,
) -> Result<usize> {
self.0.send_to(&data[..], addr)
.map_err(io_err_into_net_error)
}
fn recv_from(
&mut self,
) -> Result<SocketReceiveFrom> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let (read, peer) = self.0.recv_from(&mut buf[..])
.map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(
SocketReceiveFrom {
Ok(SocketReceive {
data: buf,
truncated: read == buf_size,
addr: peer
}
)
})
}
fn peek_from(
&mut self,
) -> Result<SocketReceiveFrom> {
fn peek(&mut self) -> Result<SocketReceive> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let (read, peer) = self.0.peek_from(&mut buf[..])
.map_err(io_err_into_net_error)?;
let read = self.0.peek(&mut buf[..]).map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(
SocketReceiveFrom {
Ok(SocketReceive {
data: buf,
truncated: read == buf_size,
addr: peer
}
)
})
}
}
impl VirtualSocket
for LocalUdpSocket
{
fn set_ttl(
&mut self,
ttl: u32,
) -> Result<()> {
self.0.set_ttl(ttl)
impl VirtualConnectionlessSocket for LocalUdpSocket {
fn send_to(&mut self, data: Bytes, addr: SocketAddr) -> Result<usize> {
self.0
.send_to(&data[..], addr)
.map_err(io_err_into_net_error)
}
fn ttl(
&self,
) -> Result<u32> {
self.0.ttl()
.map_err(io_err_into_net_error)
fn recv_from(&mut self) -> Result<SocketReceiveFrom> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let (read, peer) = self
.0
.recv_from(&mut buf[..])
.map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(SocketReceiveFrom {
data: buf,
truncated: read == buf_size,
addr: peer,
})
}
fn addr_local(
&self,
) -> Result<SocketAddr> {
self.0.local_addr()
.map_err(io_err_into_net_error)
fn peek_from(&mut self) -> Result<SocketReceiveFrom> {
let buf_size = 8192;
let mut buf = BytesMut::with_capacity(buf_size);
let (read, peer) = self
.0
.peek_from(&mut buf[..])
.map_err(io_err_into_net_error)?;
let buf = Bytes::from(buf).slice(..read);
Ok(SocketReceiveFrom {
data: buf,
truncated: read == buf_size,
addr: peer,
})
}
}
fn status(
&self,
) -> Result<SocketStatus> {
Ok(
SocketStatus::Opened
)
impl VirtualSocket for LocalUdpSocket {
fn set_ttl(&mut self, ttl: u32) -> Result<()> {
self.0.set_ttl(ttl).map_err(io_err_into_net_error)
}
fn ttl(&self) -> Result<u32> {
self.0.ttl().map_err(io_err_into_net_error)
}
fn addr_local(&self) -> Result<SocketAddr> {
self.0.local_addr().map_err(io_err_into_net_error)
}
fn status(&self) -> Result<SocketStatus> {
Ok(SocketStatus::Opened)
}
}

View File

@@ -1,6 +1,6 @@
use super::*;
use wasmer_derive::ValueType;
use wasmer_types::MemorySize;
use super::*;
pub type __wasi_busdatatype_t = u8;
pub const __WASI_BUS_DATA_TYPE_CALL: __wasi_busdatatype_t = 0;
@@ -50,7 +50,7 @@ pub struct __wasi_bus_handles_t {
#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)]
#[repr(C)]
pub struct __wasi_busevent_exit_t {
pub rval: __wasi_exitcode_t
pub rval: __wasi_exitcode_t,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueType)]

View File

@@ -12,13 +12,13 @@
extern crate wasmer_types as wasmer;
mod advice;
mod bus;
mod directory;
mod error;
mod event;
mod file;
mod bus;
mod net;
mod io;
mod net;
mod signal;
mod subscription;
mod time;
@@ -26,13 +26,13 @@ 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 bus::*;
pub use net::*;
pub use io::*;
pub use net::*;
pub use signal::*;
pub use subscription::*;
pub use versions::*;

View File

@@ -1,5 +1,5 @@
use wasmer_derive::ValueType;
use super::*;
use wasmer_derive::ValueType;
use crate::__wasi_option_timestamp_t;

View File

@@ -1,5 +1,5 @@
use wasmer_derive::ValueType;
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;

View File

@@ -35,39 +35,41 @@ compile_error!(
#[macro_use]
mod macros;
mod runtime;
mod state;
mod syscalls;
mod utils;
mod runtime;
use crate::syscalls::*;
pub use crate::state::{
Fd, Pipe, Stderr, Stdin, Stdout, WasiFs, WasiInodes, WasiState, WasiStateBuilder, WasiStateCreationError,
ALL_RIGHTS, VIRTUAL_ROOT_FD,
Fd, Pipe, Stderr, Stdin, Stdout, WasiFs, WasiInodes, WasiState, WasiStateBuilder,
WasiStateCreationError, ALL_RIGHTS, VIRTUAL_ROOT_FD,
};
pub use crate::syscalls::types;
pub use crate::utils::{get_wasi_version, get_wasi_versions, is_wasi_module, WasiVersion};
pub use wasmer_vbus::{UnsupportedVirtualBus, VirtualBus};
#[deprecated(since = "2.1.0", note = "Please use `wasmer_vfs::FsError`")]
pub use wasmer_vfs::FsError as WasiFsError;
#[deprecated(since = "2.1.0", note = "Please use `wasmer_vfs::VirtualFile`")]
pub use wasmer_vfs::VirtualFile as WasiFile;
pub use wasmer_vfs::{FsError, VirtualFile};
pub use wasmer_vbus::{VirtualBus, UnsupportedVirtualBus};
pub use wasmer_vnet::{VirtualNetworking, UnsupportedVirtualNetworking};
pub use wasmer_vnet::{UnsupportedVirtualNetworking, VirtualNetworking};
use wasmer_wasi_types::__WASI_CLOCK_MONOTONIC;
use derivative::*;
use std::ops::Deref;
use thiserror::Error;
use wasmer::{
imports, Function, Imports, LazyInit, Memory, MemoryAccessError, Module, Store, WasmerEnv,
MemorySize, Memory32,
imports, Function, Imports, LazyInit, Memory, Memory32, MemoryAccessError, MemorySize, Module,
Store, WasmerEnv,
};
use std::time::Duration;
pub use runtime::{
PlugableRuntimeImplementation, WasiRuntimeImplementation, WasiThreadError, WasiTtyState,
};
use std::sync::{Arc, RwLockReadGuard, RwLockWriteGuard};
pub use runtime::{WasiRuntimeImplementation, PlugableRuntimeImplementation, WasiThreadError, WasiTtyState};
use std::time::Duration;
/// This is returned in `RuntimeError`.
/// Use `downcast` or `downcast_ref` to retrieve the `ExitCode`.
@@ -84,10 +86,14 @@ pub enum WasiError {
pub struct WasiThreadId(u32);
impl From<u32> for WasiThreadId {
fn from(id: u32) -> Self { Self(id) }
fn from(id: u32) -> Self {
Self(id)
}
}
impl Into<u32> for WasiThreadId {
fn into(self) -> u32 { self.0 }
fn into(self) -> u32 {
self.0
}
}
/// WASI processes can have multiple threads attached to the same environment
@@ -131,14 +137,18 @@ impl WasiThread {
let now = platform_clock_time_get(__WASI_CLOCK_MONOTONIC, 1_000_000).unwrap() as u128;
let delta = match now.checked_sub(start) {
Some(a) => a,
None => { break; }
None => {
break;
}
};
if delta >= duration {
break;
}
let remaining = match duration.checked_sub(delta) {
Some(a) => Duration::from_nanos(a as u64),
None => { break; }
None => {
break;
}
};
std::thread::sleep(remaining.min(Duration::from_millis(10)));
self.yield_now()?;
@@ -254,7 +264,8 @@ impl WasiEnv {
/// Overrides the runtime implementation for this environment
pub fn set_runtime<R>(&mut self, runtime: R)
where R: WasiRuntimeImplementation + Send + Sync + 'static
where
R: WasiRuntimeImplementation + Send + Sync + 'static,
{
self.runtime = Arc::new(runtime);
}

View File

@@ -1,13 +1,13 @@
use std::fmt;
use std::ops::Deref;
use std::sync::atomic::{AtomicU32, Ordering};
use std::fmt;
use thiserror::Error;
use wasmer_vbus::{VirtualBus, UnsupportedVirtualBus};
use wasmer_vnet::{VirtualNetworking};
use wasmer_vbus::{UnsupportedVirtualBus, VirtualBus};
use wasmer_vnet::VirtualNetworking;
use super::types::*;
use super::WasiError;
use super::WasiThreadId;
use super::types::*;
#[derive(Error, Debug)]
pub enum WasiThreadError {
@@ -17,13 +17,11 @@ pub enum WasiThreadError {
MethodNotFound,
}
impl Into<__wasi_errno_t>
for WasiThreadError
{
impl Into<__wasi_errno_t> for WasiThreadError {
fn into(self) -> __wasi_errno_t {
match self {
WasiThreadError::Unsupported => __WASI_ENOTSUP,
WasiThreadError::MethodNotFound => __WASI_EINVAL
WasiThreadError::MethodNotFound => __WASI_EINVAL,
}
}
}
@@ -43,8 +41,7 @@ pub struct WasiTtyState {
/// Represents an implementation of the WASI runtime - by default everything is
/// unimplemented.
pub trait WasiRuntimeImplementation: fmt::Debug + Sync
{
pub trait WasiRuntimeImplementation: fmt::Debug + Sync {
/// For WASI runtimes that support it they can implement a message BUS implementation
/// which allows runtimes to pass serialized messages between each other similar to
/// RPC's. BUS implementation can be implemented that communicate across runtimes
@@ -74,11 +71,15 @@ pub trait WasiRuntimeImplementation: fmt::Debug + Sync
}
/// Sets the TTY state
fn tty_set(&self, _tty_state: WasiTtyState) {
}
fn tty_set(&self, _tty_state: WasiTtyState) {}
/// Spawns a new thread by invoking the
fn thread_spawn(&self, _method: &str, _user_data: u64, _reactor: bool) -> Result<WasiThreadId, WasiThreadError> {
fn thread_spawn(
&self,
_method: &str,
_user_data: u64,
_reactor: bool,
) -> Result<WasiThreadId, WasiThreadError> {
Err(WasiThreadError::Unsupported)
}
@@ -107,31 +108,29 @@ pub trait WasiRuntimeImplementation: fmt::Debug + Sync
}
#[derive(Debug)]
pub struct PlugableRuntimeImplementation
{
pub struct PlugableRuntimeImplementation {
pub bus: Box<dyn VirtualBus + Sync>,
pub networking: Box<dyn VirtualNetworking + Sync>,
pub thread_id_seed: AtomicU32,
}
impl PlugableRuntimeImplementation
{
impl PlugableRuntimeImplementation {
pub fn set_bus_implementation<I>(&mut self, bus: I)
where I: VirtualBus + Sync
where
I: VirtualBus + Sync,
{
self.bus = Box::new(bus)
}
pub fn set_networking_implementation<I>(&mut self, net: I)
where I: VirtualNetworking + Sync
where
I: VirtualNetworking + Sync,
{
self.networking = Box::new(net)
}
}
impl Default
for PlugableRuntimeImplementation
{
impl Default for PlugableRuntimeImplementation {
fn default() -> Self {
Self {
#[cfg(not(feature = "host-vnet"))]
@@ -144,8 +143,7 @@ for PlugableRuntimeImplementation
}
}
impl WasiRuntimeImplementation
for PlugableRuntimeImplementation {
impl WasiRuntimeImplementation for PlugableRuntimeImplementation {
fn bus<'a>(&'a self) -> &'a (dyn VirtualBus) {
self.bus.deref()
}

View File

@@ -4,10 +4,10 @@ use crate::state::{default_fs_backing, WasiFs, WasiState};
use crate::syscalls::types::{__WASI_STDERR_FILENO, __WASI_STDIN_FILENO, __WASI_STDOUT_FILENO};
use crate::{WasiEnv, WasiInodes};
use generational_arena::Arena;
use std::sync::Arc;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::RwLock;
use thiserror::Error;
use wasmer_vfs::{FsError, VirtualFile};
@@ -329,7 +329,8 @@ impl WasiStateBuilder {
/// Sets the WASI runtime implementation and overrides the default
/// implementation
pub fn runtime<R>(&mut self, runtime: R) -> &mut Self
where R: crate::WasiRuntimeImplementation + Send + Sync + 'static
where
R: crate::WasiRuntimeImplementation + Send + Sync + 'static,
{
self.runtime_override = Some(Arc::new(runtime));
self
@@ -456,7 +457,8 @@ impl WasiStateBuilder {
}
if let Some(f) = &self.setup_fs_fn {
f(inodes.deref_mut(), &mut wasi_fs).map_err(WasiStateCreationError::WasiFsSetupError)?;
f(inodes.deref_mut(), &mut wasi_fs)
.map_err(WasiStateCreationError::WasiFsSetupError)?;
}
wasi_fs
};

View File

@@ -16,14 +16,14 @@
#![allow(clippy::cognitive_complexity, clippy::too_many_arguments)]
mod builder;
mod types;
mod socket;
mod pipe;
mod socket;
mod types;
pub use self::builder::*;
pub use self::types::*;
pub use self::socket::*;
pub use self::pipe::*;
pub use self::socket::*;
pub use self::types::*;
use crate::syscalls::types::*;
use crate::utils::map_io_err;
use generational_arena::Arena;
@@ -32,17 +32,16 @@ pub use generational_arena::Index as Inode;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::collections::VecDeque;
use std::sync::Arc;
use std::sync::mpsc;
use std::sync::Arc;
use std::{
borrow::Borrow,
io::Write,
ops::{Deref, DerefMut},
path::{Path, PathBuf},
sync::{
Mutex,
atomic::{AtomicU32, AtomicU64, Ordering},
RwLock, RwLockReadGuard, RwLockWriteGuard,
Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard,
},
};
use tracing::{debug, trace};
@@ -196,7 +195,6 @@ pub enum Kind {
/// Receiver that wakes sleeping threads
wakers: Arc<Mutex<VecDeque<mpsc::Sender<()>>>>,
},
}
#[derive(Debug, Clone)]
@@ -856,10 +854,7 @@ impl WasiFs {
}
/// Changes the current directory
pub fn set_current_dir(
&self,
path: &str
) {
pub fn set_current_dir(&self, path: &str) {
let mut guard = self.current_dir.lock().unwrap();
*guard = path.to_string();
}
@@ -881,7 +876,13 @@ impl WasiFs {
let guard = self.current_dir.lock().unwrap();
guard.clone()
};
let inode = self.get_inode_at_path_inner(inodes, VIRTUAL_ROOT_FD, current_dir.as_str(), symlink_count, true)?;
let inode = self.get_inode_at_path_inner(
inodes,
VIRTUAL_ROOT_FD,
current_dir.as_str(),
symlink_count,
true,
)?;
Ok((inode, current_dir))
}
@@ -919,7 +920,8 @@ impl WasiFs {
// path to the inode before we do the search
if path.components().next().map(|c| c.as_os_str().to_str()).flatten() == Some(".")
&& base == VIRTUAL_ROOT_FD // File queries will occur on the root first
&& symlink_count == 0 // The resolving of the current path only should happen once and not after symbolic links are followed
&& symlink_count == 0
// The resolving of the current path only should happen once and not after symbolic links are followed
{
(cur_inode, _) = self.get_current_dir_inner(inodes, symlink_count + 1)?;
}
@@ -949,9 +951,7 @@ impl WasiFs {
return Err(__WASI_EACCES);
}
}
"." => {
continue 'path_iter
},
"." => continue 'path_iter,
_ => (),
}
// used for full resolution of symlinks
@@ -1111,7 +1111,10 @@ impl WasiFs {
return Err(__WASI_ENOENT);
}
}
Kind::File { .. } | Kind::Socket { .. } | Kind::Pipe { .. } | Kind::EventNotifications { .. } => {
Kind::File { .. }
| Kind::Socket { .. }
| Kind::Pipe { .. }
| Kind::EventNotifications { .. } => {
return Err(__WASI_ENOTDIR);
}
Kind::Symlink {
@@ -1512,10 +1515,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: __wasi_fd_t) -> Result<__wasi_fd_t, __wasi_errno_t> {
let fd = self.get_fd(fd)?;
let idx = self.next_fd.fetch_add(1, Ordering::AcqRel);
self.fd_map.write().unwrap().insert(

View File

@@ -1,17 +1,16 @@
use std::sync::mpsc;
use std::sync::Mutex;
use std::ops::DerefMut;
use crate::syscalls::types::*;
use crate::syscalls::{read_bytes, write_bytes};
use bytes::{Buf, Bytes};
use std::convert::TryInto;
use std::io::{self, Read};
use bytes::{Buf, Bytes};
use std::ops::DerefMut;
use std::sync::mpsc;
use std::sync::Mutex;
use wasmer::MemorySize;
use crate::syscalls::types::*;
use wasmer::{Memory, WasmSlice};
use crate::syscalls::{read_bytes, write_bytes};
#[derive(Debug)]
pub struct WasiPipe
{
pub struct WasiPipe {
/// Sends bytes down the pipe
tx: Mutex<mpsc::Sender<Vec<u8>>>,
/// Receives bytes from the pipe
@@ -20,55 +19,62 @@ pub struct WasiPipe
read_buffer: Option<Bytes>,
}
impl WasiPipe
{
pub fn new() -> (WasiPipe, WasiPipe)
{
impl WasiPipe {
pub fn new() -> (WasiPipe, WasiPipe) {
let (tx1, rx1) = mpsc::channel();
let (tx2, rx2) = mpsc::channel();
let pipe1 = WasiPipe {
tx: Mutex::new(tx1),
rx: Mutex::new(rx2),
read_buffer: None
read_buffer: None,
};
let pipe2 = WasiPipe {
tx: Mutex::new(tx2),
rx: Mutex::new(rx1),
read_buffer: None
read_buffer: None,
};
(pipe1, pipe2)
}
pub fn recv<M: MemorySize>(&mut self, memory: &Memory, iov: WasmSlice<__wasi_iovec_t<M>>) -> Result<usize, __wasi_errno_t> {
pub fn recv<M: MemorySize>(
&mut self,
memory: &Memory,
iov: WasmSlice<__wasi_iovec_t<M>>,
) -> Result<usize, __wasi_errno_t> {
loop {
if let Some(buf) = self.read_buffer.as_mut() {
let buf_len = buf.len();
if buf_len > 0 {
let reader = buf.as_ref();
let read = read_bytes(reader, memory, iov)
.map(|_| buf_len as usize)?;
let read = read_bytes(reader, memory, iov).map(|_| buf_len as usize)?;
buf.advance(read);
return Ok(read);
}
}
let rx = self.rx.lock().unwrap();
let data = rx.recv()
.map_err(|_| __WASI_EIO)?;
let data = rx.recv().map_err(|_| __WASI_EIO)?;
self.read_buffer.replace(Bytes::from(data));
}
}
pub fn send<M: MemorySize>(&mut self, memory: &Memory, iov: WasmSlice<__wasi_ciovec_t<M>>) -> Result<usize, __wasi_errno_t> {
let buf_len: M::Offset = iov.iter().filter_map(|a| a.read().ok()).map(|a| a.buf_len).sum();
pub fn send<M: MemorySize>(
&mut self,
memory: &Memory,
iov: WasmSlice<__wasi_ciovec_t<M>>,
) -> Result<usize, __wasi_errno_t> {
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 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(|_| __WASI_EIO)?;
Ok(buf_len)
}
@@ -87,27 +93,25 @@ impl WasiPipe
}
}
impl Read
for WasiPipe
{
impl Read for WasiPipe {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
loop {
if let Some(inner_buf) = self.read_buffer.as_mut() {
let buf_len = inner_buf.len();
if buf_len > 0 {
let mut reader = inner_buf.as_ref();
let read = reader.read(buf)
.map(|_| buf_len as usize)?;
let read = reader.read(buf).map(|_| buf_len as usize)?;
inner_buf.advance(read);
return Ok(read);
}
}
let rx = self.rx.lock().unwrap();
let data = rx.recv()
.map_err(|_| io::Error::new(
let data = rx.recv().map_err(|_| {
io::Error::new(
io::ErrorKind::BrokenPipe,
format!("the wasi pipe is not connected"),
))?;
)
})?;
self.read_buffer.replace(Bytes::from(data));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -5,9 +5,9 @@ use serde::{Deserialize, Serialize};
#[cfg(all(unix, feature = "sys-poll"))]
use std::convert::TryInto;
use std::{
sync::{Arc, Mutex},
collections::VecDeque,
io::{self, Read, Seek, Write},
sync::{Arc, Mutex},
time::Duration,
};
@@ -17,7 +17,7 @@ pub use wasmer_vfs::host_fs::{Stderr, Stdin, Stdout};
pub use wasmer_vfs::mem_fs::{Stderr, Stdin, Stdout};
use wasmer_vfs::{FsError, VirtualFile};
use wasmer_vnet::{NetworkError};
use wasmer_vnet::NetworkError;
pub fn fs_error_from_wasi_err(err: __wasi_errno_t) -> FsError {
match err {
@@ -237,7 +237,13 @@ pub(crate) fn poll(
revents: 0,
})
.collect::<Vec<_>>();
let result = unsafe { libc::poll(fds.as_mut_ptr(), selfs.len() as _, timeout.as_millis() as i32) };
let result = unsafe {
libc::poll(
fds.as_mut_ptr(),
selfs.len() as _,
timeout.as_millis() as i32,
)
};
if result < 0 {
// TODO: check errno and return value
@@ -268,17 +274,19 @@ pub(crate) fn poll(
let mut builder = PollEventBuilder::new();
let file = files[n];
let can_read = file
.bytes_available_read()?
.map(|_| true)
.unwrap_or(false);
let can_read = file.bytes_available_read()?.map(|_| true).unwrap_or(false);
let can_write = file
.bytes_available_write()?
.map(|s| s > 0)
.unwrap_or(false);
let is_closed = file.is_open() == false;
tracing::debug!("poll_evt can_read={} can_write={} is_closed={}", can_read, can_write, is_closed);
tracing::debug!(
"poll_evt can_read={} can_write={} is_closed={}",
can_read,
can_write,
is_closed
);
for event in iterate_poll_events(events[n]) {
match event {

View File

@@ -1,6 +1,6 @@
use crate::syscalls;
use crate::syscalls::types::{self, snapshot0};
use crate::{mem_error_to_wasi, WasiEnv, WasiError, WasiThread, MemorySize, Memory32};
use crate::{mem_error_to_wasi, Memory32, MemorySize, WasiEnv, WasiError, WasiThread};
use wasmer::WasmPtr;
/// Wrapper around `syscalls::fd_filestat_get` with extra logic to handle the size
@@ -72,7 +72,8 @@ pub fn path_filestat_get(
let new_buf: WasmPtr<types::__wasi_filestat_t, Memory32> = buf.cast();
let new_filestat_setup: types::__wasi_filestat_t = wasi_try_mem!(new_buf.read(memory));
let result = syscalls::path_filestat_get::<Memory32>(thread, fd, flags, path, path_len, new_buf);
let result =
syscalls::path_filestat_get::<Memory32>(thread, fd, flags, path, path_len, new_buf);
let memory = thread.memory();
let new_filestat = wasi_try_mem!(new_buf.deref(memory).read());
@@ -158,7 +159,8 @@ pub fn poll_oneoff(
}
// make the call
let result = syscalls::poll_oneoff::<Memory32>(thread, in_new_type_ptr, out_, nsubscriptions, nevents);
let result =
syscalls::poll_oneoff::<Memory32>(thread, in_new_type_ptr, out_, nsubscriptions, nevents);
// replace the old values of in, in case the calling code reuses the memory
let memory = thread.memory();

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
#![deny(dead_code)]
use crate::{WasiError, WasiState, WasiThread};
use wasmer::{Memory, Memory32, MemorySize, WasmPtr, WasmSlice};
use wasmer_wasi_types::*;
use wasmer::{Memory, WasmPtr, WasmSlice, MemorySize, Memory32};
use crate::{WasiThread, WasiState, WasiError};
type MemoryType = Memory32;
type MemoryOffset = u32;
@@ -193,7 +193,11 @@ pub(crate) fn fd_readdir(
super::fd_readdir::<MemoryType>(thread, fd, buf, buf_len, cookie, bufused)
}
pub(crate) fn fd_renumber(thread: &WasiThread, from: __wasi_fd_t, to: __wasi_fd_t) -> __wasi_errno_t {
pub(crate) fn fd_renumber(
thread: &WasiThread,
from: __wasi_fd_t,
to: __wasi_fd_t,
) -> __wasi_errno_t {
super::fd_renumber(thread, from, to)
}
@@ -259,7 +263,9 @@ pub(crate) fn path_filestat_set_times(
st_mtim: __wasi_timestamp_t,
fst_flags: __wasi_fstflags_t,
) -> __wasi_errno_t {
super::path_filestat_set_times::<MemoryType>(thread, fd, flags, path, path_len, st_atim, st_mtim, fst_flags)
super::path_filestat_set_times::<MemoryType>(
thread, fd, flags, path, path_len, st_atim, st_mtim, fst_flags,
)
}
pub(crate) fn path_link(
@@ -272,7 +278,16 @@ pub(crate) fn path_link(
new_path: WasmPtr<u8, MemoryType>,
new_path_len: MemoryOffset,
) -> __wasi_errno_t {
super::path_link::<MemoryType>(thread, old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len)
super::path_link::<MemoryType>(
thread,
old_fd,
old_flags,
old_path,
old_path_len,
new_fd,
new_path,
new_path_len,
)
}
pub(crate) fn path_open(
@@ -287,7 +302,18 @@ pub(crate) fn path_open(
fs_flags: __wasi_fdflags_t,
fd: WasmPtr<__wasi_fd_t, MemoryType>,
) -> __wasi_errno_t {
super::path_open::<MemoryType>(thread, dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd)
super::path_open::<MemoryType>(
thread,
dirfd,
dirflags,
path,
path_len,
o_flags,
fs_rights_base,
fs_rights_inheriting,
fs_flags,
fd,
)
}
pub(crate) fn path_readlink(
@@ -320,7 +346,15 @@ pub(crate) fn path_rename(
new_path: WasmPtr<u8, MemoryType>,
new_path_len: MemoryOffset,
) -> __wasi_errno_t {
super::path_rename::<MemoryType>(thread, old_fd, old_path, old_path_len, new_fd, new_path, new_path_len)
super::path_rename::<MemoryType>(
thread,
old_fd,
old_path,
old_path_len,
new_fd,
new_path,
new_path_len,
)
}
pub(crate) fn path_symlink(
@@ -364,7 +398,7 @@ pub(crate) fn proc_raise(thread: &WasiThread, sig: __wasi_signal_t) -> __wasi_er
pub(crate) fn random_get(
thread: &WasiThread,
buf: WasmPtr<u8, MemoryType>,
buf_len: MemoryOffset
buf_len: MemoryOffset,
) -> __wasi_errno_t {
super::random_get::<MemoryType>(thread, buf, buf_len)
}
@@ -382,7 +416,15 @@ pub(crate) fn sock_recv(
ro_data_len: WasmPtr<MemoryOffset, MemoryType>,
ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
super::sock_recv::<MemoryType>(thread, sock, ri_data, ri_data_len, ri_flags, ro_data_len, ro_flags)
super::sock_recv::<MemoryType>(
thread,
sock,
ri_data,
ri_data_len,
ri_flags,
ro_data_len,
ro_flags,
)
}
pub(crate) fn sock_send(

View File

@@ -1,7 +1,7 @@
#![deny(dead_code)]
use crate::{WasiError, WasiState, WasiThread};
use wasmer::{Memory, Memory32, MemorySize, WasmPtr, WasmSlice};
use wasmer_wasi_types::*;
use wasmer::{Memory, WasmPtr, WasmSlice, MemorySize, Memory32};
use crate::{WasiThread, WasiState, WasiError};
type MemoryType = Memory32;
type MemoryOffset = u32;
@@ -193,7 +193,11 @@ pub(crate) fn fd_readdir(
super::fd_readdir::<MemoryType>(thread, fd, buf, buf_len, cookie, bufused)
}
pub(crate) fn fd_renumber(thread: &WasiThread, from: __wasi_fd_t, to: __wasi_fd_t) -> __wasi_errno_t {
pub(crate) fn fd_renumber(
thread: &WasiThread,
from: __wasi_fd_t,
to: __wasi_fd_t,
) -> __wasi_errno_t {
super::fd_renumber(thread, from, to)
}
@@ -259,7 +263,9 @@ pub(crate) fn path_filestat_set_times(
st_mtim: __wasi_timestamp_t,
fst_flags: __wasi_fstflags_t,
) -> __wasi_errno_t {
super::path_filestat_set_times::<MemoryType>(thread, fd, flags, path, path_len, st_atim, st_mtim, fst_flags)
super::path_filestat_set_times::<MemoryType>(
thread, fd, flags, path, path_len, st_atim, st_mtim, fst_flags,
)
}
pub(crate) fn path_link(
@@ -272,7 +278,16 @@ pub(crate) fn path_link(
new_path: WasmPtr<u8, MemoryType>,
new_path_len: MemoryOffset,
) -> __wasi_errno_t {
super::path_link::<MemoryType>(thread, old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len)
super::path_link::<MemoryType>(
thread,
old_fd,
old_flags,
old_path,
old_path_len,
new_fd,
new_path,
new_path_len,
)
}
pub(crate) fn path_open(
@@ -287,7 +302,18 @@ pub(crate) fn path_open(
fs_flags: __wasi_fdflags_t,
fd: WasmPtr<__wasi_fd_t, MemoryType>,
) -> __wasi_errno_t {
super::path_open::<MemoryType>(thread, dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd)
super::path_open::<MemoryType>(
thread,
dirfd,
dirflags,
path,
path_len,
o_flags,
fs_rights_base,
fs_rights_inheriting,
fs_flags,
fd,
)
}
pub(crate) fn path_readlink(
@@ -320,7 +346,15 @@ pub(crate) fn path_rename(
new_path: WasmPtr<u8, MemoryType>,
new_path_len: MemoryOffset,
) -> __wasi_errno_t {
super::path_rename::<MemoryType>(thread, old_fd, old_path, old_path_len, new_fd, new_path, new_path_len)
super::path_rename::<MemoryType>(
thread,
old_fd,
old_path,
old_path_len,
new_fd,
new_path,
new_path_len,
)
}
pub(crate) fn path_symlink(
@@ -364,7 +398,7 @@ pub(crate) fn proc_raise(thread: &WasiThread, sig: __wasi_signal_t) -> __wasi_er
pub(crate) fn random_get(
thread: &WasiThread,
buf: WasmPtr<u8, MemoryType>,
buf_len: MemoryOffset
buf_len: MemoryOffset,
) -> __wasi_errno_t {
super::random_get::<MemoryType>(thread, buf, buf_len)
}
@@ -449,10 +483,7 @@ pub(crate) fn thread_id(
super::thread_id::<MemoryType>(thread, ret_tid)
}
pub(crate) fn thread_join(
thread: &WasiThread,
tid: __wasi_tid_t,
) -> __wasi_errno_t {
pub(crate) fn thread_join(thread: &WasiThread, tid: __wasi_tid_t) -> __wasi_errno_t {
super::thread_join(thread, tid)
}
@@ -497,7 +528,22 @@ pub(crate) fn bus_spawn_local(
working_dir_len: MemoryOffset,
ret_handles: WasmPtr<__wasi_bus_handles_t, MemoryType>,
) -> __wasi_errno_t {
super::bus_spawn_local::<MemoryType>(thread, name, name_len, chroot, args, args_len, preopen, preopen_len, stdin, stdout, stderr, working_dir, working_dir_len, ret_handles)
super::bus_spawn_local::<MemoryType>(
thread,
name,
name_len,
chroot,
args,
args_len,
preopen,
preopen_len,
stdin,
stdout,
stderr,
working_dir,
working_dir_len,
ret_handles,
)
}
pub(crate) fn bus_spawn_remote(
@@ -520,13 +566,29 @@ pub(crate) fn bus_spawn_remote(
token_len: MemoryOffset,
ret_handles: WasmPtr<__wasi_bus_handles_t, MemoryType>,
) -> __wasi_errno_t {
super::bus_spawn_remote::<MemoryType>(thread, name, name_len, chroot, args, args_len, preopen, preopen_len, working_dir, working_dir_len, stdin, stdout, stderr, instance, instance_len, token, token_len, ret_handles)
super::bus_spawn_remote::<MemoryType>(
thread,
name,
name_len,
chroot,
args,
args_len,
preopen,
preopen_len,
working_dir,
working_dir_len,
stdin,
stdout,
stderr,
instance,
instance_len,
token,
token_len,
ret_handles,
)
}
pub(crate) fn bus_close(
thread: &WasiThread,
bid: __wasi_bid_t,
) -> __wasi_errno_t {
pub(crate) fn bus_close(thread: &WasiThread, bid: __wasi_bid_t) -> __wasi_errno_t {
super::bus_close(thread, bid)
}
@@ -542,7 +604,9 @@ pub(crate) fn bus_invoke(
buf_len: MemoryOffset,
ret_cid: WasmPtr<__wasi_cid_t, MemoryType>,
) -> __wasi_errno_t {
super::bus_invoke::<MemoryType>(thread, bid, cid, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid)
super::bus_invoke::<MemoryType>(
thread, bid, cid, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid,
)
}
pub(crate) fn bus_fault(
@@ -553,10 +617,7 @@ pub(crate) fn bus_fault(
super::bus_fault(thread, cid, fault)
}
pub(crate) fn bus_drop(
thread: &WasiThread,
cid: __wasi_cid_t,
) -> __wasi_errno_t {
pub(crate) fn bus_drop(thread: &WasiThread, cid: __wasi_cid_t) -> __wasi_errno_t {
super::bus_drop(thread, cid)
}
@@ -612,7 +673,9 @@ pub(crate) fn bus_poll_data(
buf_len: MemoryOffset,
ret_evt: WasmPtr<__wasi_busevent_data_t<MemoryType>, MemoryType>,
) -> __wasi_errno_t {
super::bus_poll_data::<MemoryType>(thread, bid, timeout, topic, topic_len, buf, buf_len, ret_evt)
super::bus_poll_data::<MemoryType>(
thread, bid, timeout, topic, topic_len, buf, buf_len, ret_evt,
)
}
pub(crate) fn port_bridge(
@@ -626,15 +689,11 @@ pub(crate) fn port_bridge(
super::port_bridge::<MemoryType>(thread, network, network_len, token, token_len, security)
}
pub(crate) fn port_unbridge(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_unbridge(thread: &WasiThread) -> __wasi_errno_t {
super::port_unbridge(thread)
}
pub(crate) fn port_dhcp_acquire(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_dhcp_acquire(thread: &WasiThread) -> __wasi_errno_t {
super::port_dhcp_acquire(thread)
}
@@ -652,9 +711,7 @@ pub(crate) fn port_addr_remove(
super::port_addr_remove::<MemoryType>(thread, addr)
}
pub(crate) fn port_addr_clear(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_addr_clear(thread: &WasiThread) -> __wasi_errno_t {
super::port_addr_clear(thread)
}
@@ -697,9 +754,7 @@ pub(crate) fn port_route_remove(
super::port_route_remove::<MemoryType>(thread, ip)
}
pub(crate) fn port_route_clear(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_route_clear(thread: &WasiThread) -> __wasi_errno_t {
super::port_route_clear(thread)
}
@@ -731,7 +786,17 @@ pub(crate) fn http_request(
gzip: __wasi_bool_t,
ret_handles: WasmPtr<__wasi_http_handles_t, MemoryType>,
) -> __wasi_errno_t {
super::http_request::<MemoryType>(thread, url, url_len, method, method_len, headers, headers_len, gzip, ret_handles)
super::http_request::<MemoryType>(
thread,
url,
url_len,
method,
method_len,
headers,
headers_len,
gzip,
ret_handles,
)
}
pub(crate) fn http_status(
@@ -749,7 +814,7 @@ pub(crate) fn http_status(
pub(crate) fn sock_status(
thread: &WasiThread,
sock: __wasi_fd_t,
ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>
ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>,
) -> __wasi_errno_t {
super::sock_status::<MemoryType>(thread, sock, ret_status)
}
@@ -913,7 +978,15 @@ pub(crate) fn sock_recv(
ro_data_len: WasmPtr<MemoryOffset, MemoryType>,
ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
super::sock_recv::<MemoryType>(thread, sock, ri_data, ri_data_len, ri_flags, ro_data_len, ro_flags)
super::sock_recv::<MemoryType>(
thread,
sock,
ri_data,
ri_data_len,
ri_flags,
ro_data_len,
ro_flags,
)
}
pub(crate) fn sock_recv_from(
@@ -926,7 +999,16 @@ pub(crate) fn sock_recv_from(
ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>,
ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
super::sock_recv_from::<MemoryType>(thread, sock, ri_data, ri_data_len, ri_flags, ro_data_len, ro_flags, ro_addr)
super::sock_recv_from::<MemoryType>(
thread,
sock,
ri_data,
ri_data_len,
ri_flags,
ro_data_len,
ro_flags,
ro_addr,
)
}
pub(crate) fn sock_send(
@@ -949,7 +1031,15 @@ pub(crate) fn sock_send_to(
addr: WasmPtr<__wasi_addr_port_t, MemoryType>,
ret_data_len: WasmPtr<MemoryOffset, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
super::sock_send_to::<MemoryType>(thread, sock, si_data, si_data_len, si_flags, addr, ret_data_len)
super::sock_send_to::<MemoryType>(
thread,
sock,
si_data,
si_data_len,
si_flags,
addr,
ret_data_len,
)
}
pub(crate) fn sock_send_file(
@@ -960,9 +1050,7 @@ pub(crate) fn sock_send_file(
count: __wasi_filesize_t,
ret_sent: WasmPtr<__wasi_filesize_t, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
unsafe {
super::sock_send_file::<MemoryType>(thread, out_fd, in_fd, offset, count, ret_sent)
}
unsafe { super::sock_send_file::<MemoryType>(thread, out_fd, in_fd, offset, count, ret_sent) }
}
pub(crate) fn sock_shutdown(

View File

@@ -1,7 +1,7 @@
#![deny(dead_code)]
use crate::{WasiError, WasiState, WasiThread};
use wasmer::{Memory, Memory64, MemorySize, WasmPtr, WasmSlice};
use wasmer_wasi_types::*;
use wasmer::{Memory, WasmPtr, WasmSlice, MemorySize, Memory64};
use crate::{WasiThread, WasiState, WasiError};
type MemoryType = Memory64;
type MemoryOffset = u64;
@@ -193,7 +193,11 @@ pub(crate) fn fd_readdir(
super::fd_readdir::<MemoryType>(thread, fd, buf, buf_len, cookie, bufused)
}
pub(crate) fn fd_renumber(thread: &WasiThread, from: __wasi_fd_t, to: __wasi_fd_t) -> __wasi_errno_t {
pub(crate) fn fd_renumber(
thread: &WasiThread,
from: __wasi_fd_t,
to: __wasi_fd_t,
) -> __wasi_errno_t {
super::fd_renumber(thread, from, to)
}
@@ -259,7 +263,9 @@ pub(crate) fn path_filestat_set_times(
st_mtim: __wasi_timestamp_t,
fst_flags: __wasi_fstflags_t,
) -> __wasi_errno_t {
super::path_filestat_set_times::<MemoryType>(thread, fd, flags, path, path_len, st_atim, st_mtim, fst_flags)
super::path_filestat_set_times::<MemoryType>(
thread, fd, flags, path, path_len, st_atim, st_mtim, fst_flags,
)
}
pub(crate) fn path_link(
@@ -272,7 +278,16 @@ pub(crate) fn path_link(
new_path: WasmPtr<u8, MemoryType>,
new_path_len: MemoryOffset,
) -> __wasi_errno_t {
super::path_link::<MemoryType>(thread, old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len)
super::path_link::<MemoryType>(
thread,
old_fd,
old_flags,
old_path,
old_path_len,
new_fd,
new_path,
new_path_len,
)
}
pub(crate) fn path_open(
@@ -287,7 +302,18 @@ pub(crate) fn path_open(
fs_flags: __wasi_fdflags_t,
fd: WasmPtr<__wasi_fd_t, MemoryType>,
) -> __wasi_errno_t {
super::path_open::<MemoryType>(thread, dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd)
super::path_open::<MemoryType>(
thread,
dirfd,
dirflags,
path,
path_len,
o_flags,
fs_rights_base,
fs_rights_inheriting,
fs_flags,
fd,
)
}
pub(crate) fn path_readlink(
@@ -320,7 +346,15 @@ pub(crate) fn path_rename(
new_path: WasmPtr<u8, MemoryType>,
new_path_len: MemoryOffset,
) -> __wasi_errno_t {
super::path_rename::<MemoryType>(thread, old_fd, old_path, old_path_len, new_fd, new_path, new_path_len)
super::path_rename::<MemoryType>(
thread,
old_fd,
old_path,
old_path_len,
new_fd,
new_path,
new_path_len,
)
}
pub(crate) fn path_symlink(
@@ -364,7 +398,7 @@ pub(crate) fn proc_raise(thread: &WasiThread, sig: __wasi_signal_t) -> __wasi_er
pub(crate) fn random_get(
thread: &WasiThread,
buf: WasmPtr<u8, MemoryType>,
buf_len: MemoryOffset
buf_len: MemoryOffset,
) -> __wasi_errno_t {
super::random_get::<MemoryType>(thread, buf, buf_len)
}
@@ -449,10 +483,7 @@ pub(crate) fn thread_id(
super::thread_id::<MemoryType>(thread, ret_tid)
}
pub(crate) fn thread_join(
thread: &WasiThread,
tid: __wasi_tid_t,
) -> __wasi_errno_t {
pub(crate) fn thread_join(thread: &WasiThread, tid: __wasi_tid_t) -> __wasi_errno_t {
super::thread_join(thread, tid)
}
@@ -497,7 +528,22 @@ pub(crate) fn bus_spawn_local(
working_dir_len: MemoryOffset,
ret_handles: WasmPtr<__wasi_bus_handles_t, MemoryType>,
) -> __wasi_errno_t {
super::bus_spawn_local::<MemoryType>(thread, name, name_len, chroot, args, args_len, preopen, preopen_len, stdin, stdout, stderr, working_dir, working_dir_len, ret_handles)
super::bus_spawn_local::<MemoryType>(
thread,
name,
name_len,
chroot,
args,
args_len,
preopen,
preopen_len,
stdin,
stdout,
stderr,
working_dir,
working_dir_len,
ret_handles,
)
}
pub(crate) fn bus_spawn_remote(
@@ -520,13 +566,29 @@ pub(crate) fn bus_spawn_remote(
token_len: MemoryOffset,
ret_handles: WasmPtr<__wasi_bus_handles_t, MemoryType>,
) -> __wasi_errno_t {
super::bus_spawn_remote::<MemoryType>(thread, name, name_len, chroot, args, args_len, preopen, preopen_len, working_dir, working_dir_len, stdin, stdout, stderr, instance, instance_len, token, token_len, ret_handles)
super::bus_spawn_remote::<MemoryType>(
thread,
name,
name_len,
chroot,
args,
args_len,
preopen,
preopen_len,
working_dir,
working_dir_len,
stdin,
stdout,
stderr,
instance,
instance_len,
token,
token_len,
ret_handles,
)
}
pub(crate) fn bus_close(
thread: &WasiThread,
bid: __wasi_bid_t,
) -> __wasi_errno_t {
pub(crate) fn bus_close(thread: &WasiThread, bid: __wasi_bid_t) -> __wasi_errno_t {
super::bus_close(thread, bid)
}
@@ -542,7 +604,9 @@ pub(crate) fn bus_invoke(
buf_len: MemoryOffset,
ret_cid: WasmPtr<__wasi_cid_t, MemoryType>,
) -> __wasi_errno_t {
super::bus_invoke::<MemoryType>(thread, bid, cid, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid)
super::bus_invoke::<MemoryType>(
thread, bid, cid, keep_alive, topic, topic_len, format, buf, buf_len, ret_cid,
)
}
pub(crate) fn bus_fault(
@@ -553,10 +617,7 @@ pub(crate) fn bus_fault(
super::bus_fault(thread, cid, fault)
}
pub(crate) fn bus_drop(
thread: &WasiThread,
cid: __wasi_cid_t,
) -> __wasi_errno_t {
pub(crate) fn bus_drop(thread: &WasiThread, cid: __wasi_cid_t) -> __wasi_errno_t {
super::bus_drop(thread, cid)
}
@@ -612,7 +673,9 @@ pub(crate) fn bus_poll_data(
buf_len: MemoryOffset,
ret_evt: WasmPtr<__wasi_busevent_data_t<MemoryType>, MemoryType>,
) -> __wasi_errno_t {
super::bus_poll_data::<MemoryType>(thread, bid, timeout, topic, topic_len, buf, buf_len, ret_evt)
super::bus_poll_data::<MemoryType>(
thread, bid, timeout, topic, topic_len, buf, buf_len, ret_evt,
)
}
pub(crate) fn port_bridge(
@@ -626,15 +689,11 @@ pub(crate) fn port_bridge(
super::port_bridge::<MemoryType>(thread, network, network_len, token, token_len, security)
}
pub(crate) fn port_unbridge(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_unbridge(thread: &WasiThread) -> __wasi_errno_t {
super::port_unbridge(thread)
}
pub(crate) fn port_dhcp_acquire(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_dhcp_acquire(thread: &WasiThread) -> __wasi_errno_t {
super::port_dhcp_acquire(thread)
}
@@ -652,9 +711,7 @@ pub(crate) fn port_addr_remove(
super::port_addr_remove::<MemoryType>(thread, addr)
}
pub(crate) fn port_addr_clear(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_addr_clear(thread: &WasiThread) -> __wasi_errno_t {
super::port_addr_clear(thread)
}
@@ -697,9 +754,7 @@ pub(crate) fn port_route_remove(
super::port_route_remove::<MemoryType>(thread, ip)
}
pub(crate) fn port_route_clear(
thread: &WasiThread,
) -> __wasi_errno_t {
pub(crate) fn port_route_clear(thread: &WasiThread) -> __wasi_errno_t {
super::port_route_clear(thread)
}
@@ -731,7 +786,17 @@ pub(crate) fn http_request(
gzip: __wasi_bool_t,
ret_handles: WasmPtr<__wasi_http_handles_t, MemoryType>,
) -> __wasi_errno_t {
super::http_request::<MemoryType>(thread, url, url_len, method, method_len, headers, headers_len, gzip, ret_handles)
super::http_request::<MemoryType>(
thread,
url,
url_len,
method,
method_len,
headers,
headers_len,
gzip,
ret_handles,
)
}
pub(crate) fn http_status(
@@ -749,7 +814,7 @@ pub(crate) fn http_status(
pub(crate) fn sock_status(
thread: &WasiThread,
sock: __wasi_fd_t,
ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>
ret_status: WasmPtr<__wasi_sockstatus_t, MemoryType>,
) -> __wasi_errno_t {
super::sock_status::<MemoryType>(thread, sock, ret_status)
}
@@ -913,7 +978,15 @@ pub(crate) fn sock_recv(
ro_data_len: WasmPtr<MemoryOffset, MemoryType>,
ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
super::sock_recv::<MemoryType>(thread, sock, ri_data, ri_data_len, ri_flags, ro_data_len, ro_flags)
super::sock_recv::<MemoryType>(
thread,
sock,
ri_data,
ri_data_len,
ri_flags,
ro_data_len,
ro_flags,
)
}
pub(crate) fn sock_recv_from(
@@ -926,7 +999,16 @@ pub(crate) fn sock_recv_from(
ro_flags: WasmPtr<__wasi_roflags_t, MemoryType>,
ro_addr: WasmPtr<__wasi_addr_port_t, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
super::sock_recv_from::<MemoryType>(thread, sock, ri_data, ri_data_len, ri_flags, ro_data_len, ro_flags, ro_addr)
super::sock_recv_from::<MemoryType>(
thread,
sock,
ri_data,
ri_data_len,
ri_flags,
ro_data_len,
ro_flags,
ro_addr,
)
}
pub(crate) fn sock_send(
@@ -949,7 +1031,15 @@ pub(crate) fn sock_send_to(
addr: WasmPtr<__wasi_addr_port_t, MemoryType>,
ret_data_len: WasmPtr<MemoryOffset, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
super::sock_send_to::<MemoryType>(thread, sock, si_data, si_data_len, si_flags, addr, ret_data_len)
super::sock_send_to::<MemoryType>(
thread,
sock,
si_data,
si_data_len,
si_flags,
addr,
ret_data_len,
)
}
pub(crate) fn sock_send_file(
@@ -960,9 +1050,7 @@ pub(crate) fn sock_send_file(
count: __wasi_filesize_t,
ret_sent: WasmPtr<__wasi_filesize_t, MemoryType>,
) -> Result<__wasi_errno_t, WasiError> {
unsafe {
super::sock_send_file::<MemoryType>(thread, out_fd, in_fd, offset, count, ret_sent)
}
unsafe { super::sock_send_file::<MemoryType>(thread, out_fd, in_fd, offset, count, ret_sent) }
}
pub(crate) fn sock_shutdown(

View File

@@ -1,6 +1,6 @@
use super::types::*;
use std::collections::BTreeSet;
use wasmer::Module;
use super::types::*;
#[allow(dead_code)]
/// Check if a provided module is compiled for some version of WASI.
@@ -104,22 +104,19 @@ impl Ord for WasiVersion {
return std::cmp::Ordering::Equal;
}
match (*self, *other) {
(Self::Snapshot1, Self::Snapshot0) => {
std::cmp::Ordering::Greater
}
(Self::Snapshot1, Self::Snapshot0) => std::cmp::Ordering::Greater,
(Self::Wasix32v1, Self::Snapshot1) | (Self::Wasix32v1, Self::Snapshot0) => {
std::cmp::Ordering::Greater
}
(Self::Wasix64v1, Self::Wasix32v1) | (Self::Wasix64v1, Self::Snapshot1) | (Self::Wasix64v1, Self::Snapshot0) => {
std::cmp::Ordering::Greater
}
(Self::Latest, Self::Wasix64v1) | (Self::Latest, Self::Wasix32v1) | (Self::Latest, Self::Snapshot1) | (Self::Latest, Self::Snapshot0) => {
std::cmp::Ordering::Greater
}
(Self::Wasix64v1, Self::Wasix32v1)
| (Self::Wasix64v1, Self::Snapshot1)
| (Self::Wasix64v1, Self::Snapshot0) => std::cmp::Ordering::Greater,
(Self::Latest, Self::Wasix64v1)
| (Self::Latest, Self::Wasix32v1)
| (Self::Latest, Self::Snapshot1)
| (Self::Latest, Self::Snapshot0) => std::cmp::Ordering::Greater,
// they are not equal and not greater so they must be less
(_, _) => {
std::cmp::Ordering::Less
}
(_, _) => std::cmp::Ordering::Less,
}
}
}

View File

@@ -99,7 +99,10 @@ impl Config {
}
}
pub fn compiler_config(&self, #[allow(unused_variables)] canonicalize_nans: bool) -> Box<dyn CompilerConfig> {
pub fn compiler_config(
&self,
#[allow(unused_variables)] canonicalize_nans: bool,
) -> Box<dyn CompilerConfig> {
match &self.compiler {
#[cfg(feature = "cranelift")]
Compiler::Cranelift => {

View File

@@ -1,8 +1,8 @@
use anyhow::Context;
use std::fs::{read_dir, File, OpenOptions, ReadDir};
use std::io::{self, Read, Seek, Write};
use std::sync::{Arc, Mutex, mpsc};
use std::path::{Path, PathBuf};
use std::sync::{mpsc, Arc, Mutex};
use wasmer::{Imports, Instance, Module, Store};
use wasmer_vfs::{host_fs, mem_fs, FileSystem};
use wasmer_wasi::types::{__wasi_filesize_t, __wasi_timestamp_t};
@@ -130,7 +130,12 @@ impl<'a> WasiTest<'a> {
fn create_wasi_env(
&self,
filesystem_kind: WasiFileSystemKind,
) -> anyhow::Result<(WasiEnv, Vec<tempfile::TempDir>, mpsc::Receiver<Vec<u8>>, mpsc::Receiver<Vec<u8>>)> {
) -> anyhow::Result<(
WasiEnv,
Vec<tempfile::TempDir>,
mpsc::Receiver<Vec<u8>>,
mpsc::Receiver<Vec<u8>>,
)> {
let mut builder = WasiState::new(self.wasm_path);
let stdin_pipe = Pipe::new();
@@ -524,7 +529,12 @@ struct OutputCapturerer {
impl OutputCapturerer {
fn new() -> (Self, mpsc::Receiver<Vec<u8>>) {
let (tx, rx) = mpsc::channel();
(Self { output: Arc::new(Mutex::new(tx)) }, rx)
(
Self {
output: Arc::new(Mutex::new(tx)),
},
rx,
)
}
}
@@ -564,29 +574,32 @@ impl Seek for OutputCapturerer {
}
impl Write for OutputCapturerer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.output.lock().unwrap().send(buf.to_vec())
.map_err(|err| io::Error::new(
io::ErrorKind::BrokenPipe, err.to_string(),
))?;
self.output
.lock()
.unwrap()
.send(buf.to_vec())
.map_err(|err| io::Error::new(io::ErrorKind::BrokenPipe, err.to_string()))?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.output.lock().unwrap().send(buf.to_vec())
.map_err(|err| io::Error::new(
io::ErrorKind::BrokenPipe, err.to_string(),
))?;
self.output
.lock()
.unwrap()
.send(buf.to_vec())
.map_err(|err| io::Error::new(io::ErrorKind::BrokenPipe, err.to_string()))?;
Ok(())
}
fn write_fmt(&mut self, fmt: std::fmt::Arguments) -> io::Result<()> {
let mut buf = Vec::<u8>::new();
buf.write_fmt(fmt)?;
self.output.lock().unwrap().send(buf)
.map_err(|err| io::Error::new(
io::ErrorKind::BrokenPipe, err.to_string(),
))?;
self.output
.lock()
.unwrap()
.send(buf)
.map_err(|err| io::Error::new(io::ErrorKind::BrokenPipe, err.to_string()))?;
Ok(())
}
}