wasmtime_wasi

Struct WasiCtxBuilder

source
pub struct WasiCtxBuilder { /* private fields */ }
Expand description

Builder-style structure used to create a WasiCtx.

This type is used to create a WasiCtx that is considered per-Store state. The build method is used to finish the building process and produce a finalized WasiCtx.

§Examples

use wasmtime_wasi::{WasiCtxBuilder, WasiCtx};

let mut wasi = WasiCtxBuilder::new();
wasi.arg("./foo.wasm");
wasi.arg("--help");
wasi.env("FOO", "bar");

let wasi: WasiCtx = wasi.build();

Implementations§

source§

impl WasiCtxBuilder

source

pub fn new() -> Self

Creates a builder for a new context with default parameters set.

The current defaults are:

  • stdin is closed
  • stdout and stderr eat all input and it doesn’t go anywhere
  • no env vars
  • no arguments
  • no preopens
  • clocks use the host implementation of wall/monotonic clocks
  • RNGs are all initialized with random state and suitable generator quality to satisfy the requirements of WASI APIs.
  • TCP/UDP are allowed but all addresses are denied by default.
  • wasi:network/ip-name-lookup is denied by default.

These defaults can all be updated via the various builder configuration methods below.

source

pub fn stdin(&mut self, stdin: impl StdinStream + 'static) -> &mut Self

Provides a custom implementation of stdin to use.

By default stdin is closed but an example of using the host’s native stdin looks like:

use wasmtime_wasi::{stdin, WasiCtxBuilder};

let mut wasi = WasiCtxBuilder::new();
wasi.stdin(stdin());

Note that inheriting the process’s stdin can also be done through inherit_stdin.

source

pub fn stdout(&mut self, stdout: impl StdoutStream + 'static) -> &mut Self

Same as stdin, but for stdout.

source

pub fn stderr(&mut self, stderr: impl StdoutStream + 'static) -> &mut Self

Same as stdin, but for stderr.

source

pub fn inherit_stdin(&mut self) -> &mut Self

Configures this context’s stdin stream to read the host process’s stdin.

Note that concurrent reads of stdin can produce surprising results so when using this it’s typically best to have a single wasm instance in the process using this.

source

pub fn inherit_stdout(&mut self) -> &mut Self

Configures this context’s stdout stream to write to the host process’s stdout.

Note that unlike inherit_stdin multiple instances printing to stdout works well.

source

pub fn inherit_stderr(&mut self) -> &mut Self

Configures this context’s stderr stream to write to the host process’s stderr.

Note that unlike inherit_stdin multiple instances printing to stderr works well.

source

pub fn inherit_stdio(&mut self) -> &mut Self

Configures all of stdin, stdout, and stderr to be inherited from the host process.

See inherit_stdin for some rationale on why this should only be done in situations of one-instance-per-process.

source

pub fn allow_blocking_current_thread(&mut self, enable: bool) -> &mut Self

Configures whether or not blocking operations made through this WasiCtx are allowed to block the current thread.

WASI is currently implemented on top of the Rust Tokio library. While most WASI APIs are non-blocking some are instead blocking from the perspective of WebAssembly. For example opening a file is a blocking operation with respect to WebAssembly but it’s implemented as an asynchronous operation on the host. This is currently done with Tokio’s spawn_blocking.

When WebAssembly is used in a synchronous context, for example when Config::async_support is disabled, then this asynchronous operation is quickly turned back into a synchronous operation with a block_on in Rust. This switching back-and-forth between a blocking a non-blocking context can have overhead, and this option exists to help alleviate this overhead.

This option indicates that for WASI functions that are blocking from the perspective of WebAssembly it’s ok to block the native thread as well. This means that this back-and-forth between async and sync won’t happen and instead blocking operations are performed on-thread (such as opening a file). This can improve the performance of WASI operations when async support is disabled.

source

pub fn envs(&mut self, env: &[(impl AsRef<str>, impl AsRef<str>)]) -> &mut Self

Appends multiple environment variables at once for this builder.

All environment variables are appended to the list of environment variables that this builder will configure.

At this time environment variables are not deduplicated and if the same key is set twice then the guest will see two entries for the same key.

§Examples
use wasmtime_wasi::{stdin, WasiCtxBuilder};

let mut wasi = WasiCtxBuilder::new();
wasi.envs(&[
    ("FOO", "bar"),
    ("HOME", "/somewhere"),
]);
source

pub fn env(&mut self, k: impl AsRef<str>, v: impl AsRef<str>) -> &mut Self

Appends a single environment variable for this builder.

At this time environment variables are not deduplicated and if the same key is set twice then the guest will see two entries for the same key.

§Examples
use wasmtime_wasi::{stdin, WasiCtxBuilder};

let mut wasi = WasiCtxBuilder::new();
wasi.env("FOO", "bar");
source

pub fn inherit_env(&mut self) -> &mut Self

Configures all environment variables to be inherited from the calling process into this configuration.

This will use envs to append all host-defined environment variables.

source

pub fn args(&mut self, args: &[impl AsRef<str>]) -> &mut Self

Appends a list of arguments to the argument array to pass to wasm.

source

pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self

Appends a single argument to get passed to wasm.

source

pub fn inherit_args(&mut self) -> &mut Self

Appends all host process arguments to the list of arguments to get passed to wasm.

source

pub fn preopened_dir( &mut self, host_path: impl AsRef<Path>, guest_path: impl AsRef<str>, dir_perms: DirPerms, file_perms: FilePerms, ) -> Result<&mut Self>

Configures a “preopened directory” to be available to WebAssembly.

By default WebAssembly does not have access to the filesystem because there are no preopened directories. All filesystem operations, such as opening a file, are done through a preexisting handle. This means that to provide WebAssembly access to a directory it must be configured through this API.

WASI will also prevent access outside of files provided here. For example .. can’t be used to traverse up from the host_path provided here to the containing directory.

  • host_path - a path to a directory on the host to open and make accessible to WebAssembly. Note that the name of this directory in the guest is configured with guest_path below.
  • guest_path - the name of the preopened directory from WebAssembly’s perspective. Note that this does not need to match the host’s name for the directory.
  • dir_perms - this is the permissions that wasm will have to operate on guest_path. This can be used, for example, to provide readonly access to a directory.
  • file_perms - similar to dir_perms but corresponds to the maximum set of permissions that can be used for any file in this directory.
§Errors

This method will return an error if host_path cannot be opened.

§Examples
use wasmtime_wasi::{WasiCtxBuilder, DirPerms, FilePerms};

let mut wasi = WasiCtxBuilder::new();

// Make `./host-directory` available in the guest as `.`
wasi.preopened_dir("./host-directory", ".", DirPerms::all(), FilePerms::all());

// Make `./readonly` available in the guest as `./ro`
wasi.preopened_dir("./readonly", "./ro", DirPerms::READ, FilePerms::READ);
source

pub fn secure_random( &mut self, random: impl RngCore + Send + 'static, ) -> &mut Self

Set the generator for the wasi:random/random number generator to the custom generator specified.

Note that contexts have a default RNG configured which is a suitable generator for WASI and is configured with a random seed per-context.

Guest code may rely on this random number generator to produce fresh unpredictable random data in order to maintain its security invariants, and ideally should use the insecure random API otherwise, so using any prerecorded or otherwise predictable data may compromise security.

source

pub fn insecure_random( &mut self, insecure_random: impl RngCore + Send + 'static, ) -> &mut Self

Configures the generator for wasi:random/insecure.

The insecure_random generator provided will be used for all randomness requested by the wasi:random/insecure interface.

source

pub fn insecure_random_seed(&mut self, insecure_random_seed: u128) -> &mut Self

Configures the seed to be returned from wasi:random/insecure-seed to the specified custom value.

By default this number is randomly generated when a builder is created.

source

pub fn wall_clock(&mut self, clock: impl HostWallClock + 'static) -> &mut Self

Configures wasi:clocks/wall-clock to use the clock specified.

By default the host’s wall clock is used.

source

pub fn monotonic_clock( &mut self, clock: impl HostMonotonicClock + 'static, ) -> &mut Self

Configures wasi:clocks/monotonic-clock to use the clock specified.

By default the host’s monotonic clock is used.

source

pub fn inherit_network(&mut self) -> &mut Self

Allow all network addresses accessible to the host.

This method will inherit all network addresses meaning that any address can be bound by the guest or connected to by the guest using any protocol.

See also WasiCtxBuilder::socket_addr_check.

source

pub fn socket_addr_check<F>(&mut self, check: F) -> &mut Self
where F: Fn(SocketAddr, SocketAddrUse) -> Pin<Box<dyn Future<Output = bool> + Send + Sync>> + Send + Sync + 'static,

A check that will be called for each socket address that is used.

Returning true will permit socket connections to the SocketAddr, while returning false will reject the connection.

source

pub fn allow_ip_name_lookup(&mut self, enable: bool) -> &mut Self

Allow usage of wasi:sockets/ip-name-lookup

By default this is disabled.

source

pub fn allow_udp(&mut self, enable: bool) -> &mut Self

Allow usage of UDP.

This is enabled by default, but can be disabled if UDP should be blanket disabled.

source

pub fn allow_tcp(&mut self, enable: bool) -> &mut Self

Allow usage of TCP

This is enabled by default, but can be disabled if TCP should be blanket disabled.

source

pub fn build(&mut self) -> WasiCtx

Uses the configured context so far to construct the final WasiCtx.

Note that each WasiCtxBuilder can only be used to “build” once, and calling this method twice will panic.

§Panics

Panics if this method is called twice. Each WasiCtxBuilder can be used to create only a single WasiCtx. Repeated usage of this method is not allowed and should use a second builder instead.

source

pub fn build_p1(&mut self) -> WasiP1Ctx

Available on crate feature preview1 only.

Builds a WASIp1 context instead of a WasiCtx.

This method is the same as build but it creates a WasiP1Ctx instead. This is intended for use with the preview1 module of this crate

§Panics

Panics if this method is called twice. Each WasiCtxBuilder can be used to create only a single WasiCtx or WasiP1Ctx. Repeated usage of this method is not allowed and should use a second builder instead.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> GetSetFdFlags for T

§

fn get_fd_flags(&self) -> Result<FdFlags, Error>
where T: AsFilelike,

Query the “status” flags for the self file descriptor.
§

fn new_set_fd_flags(&self, fd_flags: FdFlags) -> Result<SetFdFlags<T>, Error>
where T: AsFilelike,

Create a new SetFdFlags value for use with set_fd_flags. Read more
§

fn set_fd_flags(&mut self, set_fd_flags: SetFdFlags<T>) -> Result<(), Error>
where T: AsFilelike,

Set the “status” flags for the self file descriptor. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Pointer = u32

§

fn debug( pointer: <T as Pointee>::Pointer, f: &mut Formatter<'_>, ) -> Result<(), Error>

source§

impl<T> Same for T

source§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more