Skip to main content

SandboxBuilder

Struct SandboxBuilder 

Source
pub struct SandboxBuilder { /* private fields */ }
Expand description

Builds a Sandbox.

Start from SandboxBuilder::from_file, SandboxBuilder::from_bytes or SandboxBuilder::from_snapshot, chain the settings you need, then call SandboxBuilder::build. Every setting has a default, so a builder with no adjustments is valid.

By default only the HostPrint host function is registered, which writes guest output to the host’s stdout. Replace it with Self::host_print.

§Examples

From a guest binary on disk:

let mut sandbox = SandboxBuilder::from_file("guest.bin")
    .heap_size(1024 * 1024)
    .host_function("Add", |a: i32, b: i32| a + b)
    .build()?;

let result: String = sandbox.call("Echo", "hello".to_string())?;

From a snapshot. The snapshot carries the guest binary and the state it was taken in, so no guest binary is given here. The builder must still register every host function the snapshot was taken with:

let mut sandbox = SandboxBuilder::from_file("guest.bin")
    .host_function("Add", |a: i32, b: i32| a + b)
    .build()?;
let snapshot = sandbox.snapshot()?;

let mut restored = SandboxBuilder::from_snapshot(snapshot)
    .host_function("Add", |a: i32, b: i32| a + b)
    .build()?;

let result: String = restored.call("Echo", "hello".to_string())?;

Implementations§

Source§

impl SandboxBuilder

Source

pub fn from_file(path: impl AsRef<Path>) -> Self

Build a sandbox running the guest binary at path, an ELF file.

Source

pub fn from_bytes(buffer: impl Into<Vec<u8>>) -> Self

Build a sandbox running the guest binary held in buffer, the contents of an ELF file.

Source

pub fn from_snapshot(snapshot: Arc<Snapshot>) -> Self

Build a sandbox restoring the guest from snapshot.

Source

pub fn build(self) -> Result<Sandbox>

Create the sandbox.

§Errors

When building from a snapshot, returns an error if Self::init_data or Self::guest_log_level are set. The snapshot already carries both, so they have no effect there.

Source§

impl SandboxBuilder

Source

pub fn init_data( self, data: impl Into<Vec<u8>>, flags: MemoryRegionFlags, ) -> Self

Sets the sandbox init_data into the sandbox’s memory when it is built, with flags as the guest’s permissions on that region.

Note: Self::build errors if this setting is set and the builder’s source is a snapshot, as the snapshot already contains the init data.

Source

pub fn mapped_file_cow(self, path: impl AsRef<Path>, guest_base: u64) -> Self

Map the contents of the file at path into the guest at guest_base, copy-on-write.

guest_base must be page-aligned and lie outside the sandbox’s primary shared memory region. Violations surface as an error from Self::build, not here. Call this once per file to map several.

Source

pub unsafe fn mapped_memory_region(self, region: MemoryRegion) -> Self

Maps a region of host memory into the sandbox address space.

The base address and length must meet platform alignment requirements (typically page-aligned). The region_type field is ignored as guest page table entries are not created.

§Safety

The caller must ensure the host memory region remains valid and unmodified for the lifetime of the sandbox this builder produces.

Source

pub fn guest_log_level(self, level: LevelFilter) -> Self

Sets the maximum log level for guest code execution.

If not set, the log level is determined by the RUST_LOG environment variable, defaulting to LevelFilter::ERROR if unset.

Note: Self::build errors if this setting is set and the builder’s source is a snapshot, as the log level is already captured in the snapshot.

Source

pub fn get_guest_log_level(&self) -> Option<LevelFilter>

The maximum log level for guest code execution, or None if not set.

Source§

impl SandboxBuilder

Source

pub fn host_function<Args: ParameterTuple, Output: SupportedReturnType>( self, name: impl AsRef<str>, host_func: impl Into<HostFunction<Output, Args>>, ) -> Self

Registers a host function that the guest can call.

Note: registering under the name HostPrint overrides guest printing. Prefer Self::host_print, which checks the signature at compile time.

Source

pub fn host_print( self, print_func: impl Into<HostFunction<i32, (String,)>>, ) -> Self

Registers the special “HostPrint” function for guest printing.

This overrides the default behavior of writing to stdout. The function expects the signature FnMut(String) -> i32 and will be called when the guest wants to print output.

Source

pub fn host_functions(self, host_funcs: HostFunctions) -> Self

Registers every host function in host_funcs.

Entries whose names are already registered are overwritten.

Note: an entry named HostPrint overrides guest printing. Prefer Self::host_print, which checks the signature at compile time.

Source§

impl SandboxBuilder

Source

pub fn input_data_size(self, size: usize) -> Self

Set the size of the memory buffer made available for input to the guest. Values below SandboxConfiguration::MIN_INPUT_SIZE are clamped up.

Source

pub fn get_input_data_size(&self) -> usize

The size of the memory buffer made available for input to the guest.

Source

pub fn output_data_size(self, size: usize) -> Self

Set the size of the memory buffer made available for output from the guest. Values below SandboxConfiguration::MIN_OUTPUT_SIZE are clamped up.

Source

pub fn get_output_data_size(&self) -> usize

The size of the memory buffer made available for output from the guest.

Source

pub fn heap_size(self, size: u64) -> Self

Set the guest heap size. A size of 0 selects SandboxConfiguration::DEFAULT_HEAP_SIZE.

Source

pub fn get_heap_size(&self) -> u64

The guest heap size, defaulting to SandboxConfiguration::DEFAULT_HEAP_SIZE when no override is set.

Source

pub fn scratch_size(self, size: usize) -> Self

Set how much writable memory to offer the guest.

Source

pub fn get_scratch_size(&self) -> usize

How much writable memory is offered to the guest.

Source

pub fn guest_msrs(self, indices: &[u32]) -> Result<Self, GuestMsrError>

Declare MSRs the guest owns, saved and restored with the rest of the sandbox state. Adds to the declared set, so repeated calls accumulate.

See SandboxConfiguration::guest_msrs for the platform-specific behavior and the capacity limit.

§Errors

Returns GuestMsrError::CapacityExceeded if the distinct entries would exceed SandboxConfiguration::MAX_GUEST_MSRS. The declared set is unchanged on error.

Source

pub fn interrupt_retry_delay(self, delay: Duration) -> Self

Set how long to wait between attempts to signal the VCPU thread.

Source

pub fn get_interrupt_retry_delay(&self) -> Duration

How long to wait between attempts to signal the VCPU thread.

Source

pub fn interrupt_vcpu_sigrtmin_offset(self, offset: u8) -> Result<Self>

Set the offset from SIGRTMIN for the signal used to interrupt the VCPU thread.

§Errors

Returns an error if SIGRTMIN + offset exceeds SIGRTMAX.

Source

pub fn get_interrupt_vcpu_sigrtmin_offset(&self) -> u8

The offset from SIGRTMIN for the signal used to interrupt the VCPU thread.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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.
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