use hyperlight_host::func::HostFunction;
use hyperlight_host::sandbox::SandboxConfiguration;
use hyperlight_host::{GuestBinary, HyperlightError, Result, is_hypervisor_present};
use super::proto_wasm_sandbox::ProtoWasmSandbox;
pub const MIN_SCRATCH_SIZE: usize = 2 * 1024 * 1024;
pub const MIN_INPUT_DATA_SIZE: usize = 192 * 1024;
pub const MIN_HEAP_SIZE: u64 = 1024 * 1024;
#[derive(Clone)]
pub struct SandboxBuilder {
config: SandboxConfiguration,
host_print_fn: Option<HostFunction<i32, (String,)>>,
}
impl SandboxBuilder {
pub fn new() -> Self {
let mut config: SandboxConfiguration = Default::default();
config.set_input_data_size(MIN_INPUT_DATA_SIZE);
config.set_heap_size(MIN_HEAP_SIZE);
config.set_scratch_size(MIN_SCRATCH_SIZE);
Self {
config,
host_print_fn: None,
}
}
#[cfg(gdb)]
pub fn with_debugging_enabled(mut self, port: u16) -> Self {
let debug_info = hyperlight_host::sandbox::config::DebugInfo { port };
self.config.set_guest_debug_info(debug_info);
self
}
pub fn with_host_print_fn(
mut self,
host_print_fn: impl Into<HostFunction<i32, (String,)>>,
) -> Self {
self.host_print_fn = Some(host_print_fn.into());
self
}
pub fn with_guest_output_buffer_size(mut self, guest_output_buffer_size: usize) -> Self {
self.config.set_output_data_size(guest_output_buffer_size);
self
}
pub fn with_guest_input_buffer_size(mut self, guest_input_buffer_size: usize) -> Self {
if guest_input_buffer_size > MIN_INPUT_DATA_SIZE {
self.config.set_input_data_size(guest_input_buffer_size);
}
self
}
pub fn with_guest_scratch_size(mut self, guest_scratch_size: usize) -> Self {
if guest_scratch_size > MIN_SCRATCH_SIZE {
self.config.set_scratch_size(guest_scratch_size);
}
self
}
pub fn with_guest_heap_size(mut self, guest_heap_size: u64) -> Self {
if guest_heap_size > MIN_HEAP_SIZE {
self.config.set_heap_size(guest_heap_size);
}
self
}
#[cfg(feature = "crashdump")]
pub fn with_crashdump_enabled(mut self, enabled: bool) -> Self {
self.config.set_guest_core_dump(enabled);
self
}
pub fn build(self) -> Result<ProtoWasmSandbox> {
if !is_hypervisor_present() {
return Err(HyperlightError::NoHypervisorFound());
}
let guest_binary = GuestBinary::Buffer(&super::WASM_RUNTIME);
let mut proto_wasm_sandbox = ProtoWasmSandbox::new(Some(self.config), guest_binary)?;
if let Some(host_print_fn) = self.host_print_fn {
proto_wasm_sandbox.register_print(host_print_fn)?;
}
Ok(proto_wasm_sandbox)
}
}
impl Default for SandboxBuilder {
fn default() -> Self {
Self::new()
}
}