Skip to main content

hyperlight_host/sandbox/
builder.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4use std::path::Path;
5use std::sync::{Arc, Mutex};
6#[cfg(target_os = "linux")]
7use std::time::Duration;
8
9use hyperlight_common::func::{ParameterTuple, SupportedReturnType};
10use tracing_core::LevelFilter;
11
12use crate::func::HostFunction;
13use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags};
14use crate::sandbox::SandboxConfiguration;
15#[cfg(gdb)]
16use crate::sandbox::config::DebugInfo;
17#[cfg(target_arch = "x86_64")]
18use crate::sandbox::config::GuestMsrError;
19use crate::sandbox::host_funcs::FunctionEntry;
20use crate::sandbox::snapshot::Snapshot;
21use crate::sandbox::uninitialized::{GuestBlob, GuestEnvironment};
22use crate::{GuestBinary, HostFunctions, Result, Sandbox, UninitializedSandbox, new_error};
23
24/// What a [`SandboxBuilder`] builds the sandbox from.
25enum Source {
26    GuestBinary(GuestBinary),
27    Snapshot(Arc<Snapshot>),
28}
29
30impl Source {
31    fn file(path: impl AsRef<Path>) -> Self {
32        Self::GuestBinary(GuestBinary::FilePath(path.as_ref().to_path_buf()))
33    }
34
35    fn bytes(buffer: impl Into<Vec<u8>>) -> Self {
36        Self::GuestBinary(GuestBinary::Buffer(buffer.into()))
37    }
38}
39
40/// Builds a [`Sandbox`].
41///
42/// Start from [`SandboxBuilder::from_file`],
43/// [`SandboxBuilder::from_bytes`] or [`SandboxBuilder::from_snapshot`],
44/// chain the settings you need, then call [`SandboxBuilder::build`]. Every
45/// setting has a default, so a builder with no adjustments is valid.
46///
47/// By default only the `HostPrint` host function is registered, which writes
48/// guest output to the host's stdout. Replace it with [`Self::host_print`].
49///
50/// # Examples
51///
52/// From a guest binary on disk:
53///
54/// ```no_run
55/// # use hyperlight_host::{Result, SandboxBuilder};
56/// # fn example() -> Result<()> {
57/// let mut sandbox = SandboxBuilder::from_file("guest.bin")
58///     .heap_size(1024 * 1024)
59///     .host_function("Add", |a: i32, b: i32| a + b)
60///     .build()?;
61///
62/// let result: String = sandbox.call("Echo", "hello".to_string())?;
63/// # Ok(())
64/// # }
65/// ```
66///
67/// From a snapshot. The snapshot carries the guest binary and the state it was
68/// taken in, so no guest binary is given here. The builder must still register
69/// every host function the snapshot was taken with:
70///
71/// ```no_run
72/// # use hyperlight_host::{Result, SandboxBuilder};
73/// # fn example() -> Result<()> {
74/// let mut sandbox = SandboxBuilder::from_file("guest.bin")
75///     .host_function("Add", |a: i32, b: i32| a + b)
76///     .build()?;
77/// let snapshot = sandbox.snapshot()?;
78///
79/// let mut restored = SandboxBuilder::from_snapshot(snapshot)
80///     .host_function("Add", |a: i32, b: i32| a + b)
81///     .build()?;
82///
83/// let result: String = restored.call("Echo", "hello".to_string())?;
84/// # Ok(())
85/// # }
86/// ```
87pub struct SandboxBuilder {
88    source: Source,
89    cfg: SandboxConfiguration,
90    host_funcs: HostFunctions,
91    init_data: Option<(Vec<u8>, MemoryRegionFlags)>,
92    mapped_file_cow: Vec<(std::path::PathBuf, u64)>,
93    mapped_memory_regions: Vec<MemoryRegion>,
94    guest_log_level: Option<LevelFilter>,
95}
96
97impl SandboxBuilder {
98    fn with_source(source: Source) -> Self {
99        Self {
100            source,
101            cfg: SandboxConfiguration::default(),
102            host_funcs: HostFunctions::default(),
103            init_data: None,
104            mapped_file_cow: Vec::new(),
105            mapped_memory_regions: Vec::new(),
106            guest_log_level: None,
107        }
108    }
109
110    /// Build a sandbox running the guest binary at `path`, an ELF file.
111    pub fn from_file(path: impl AsRef<Path>) -> Self {
112        Self::with_source(Source::file(path))
113    }
114
115    /// Build a sandbox running the guest binary held in `buffer`, the contents
116    /// of an ELF file.
117    pub fn from_bytes(buffer: impl Into<Vec<u8>>) -> Self {
118        Self::with_source(Source::bytes(buffer))
119    }
120
121    /// Build a sandbox restoring the guest from `snapshot`.
122    ///
123    /// The snapshot's layout overrides heap, scratch, and transport settings.
124    pub fn from_snapshot(snapshot: Arc<Snapshot>) -> Self {
125        Self::with_source(Source::Snapshot(snapshot))
126    }
127
128    /// Create the sandbox.
129    ///
130    /// # Errors
131    ///
132    /// When building from a snapshot, returns an error if [`Self::init_data`]
133    /// is set because the snapshot already contains it.
134    pub fn build(self) -> Result<Sandbox> {
135        let Self {
136            source,
137            mut cfg,
138            host_funcs,
139            init_data,
140            mapped_file_cow,
141            mapped_memory_regions,
142            guest_log_level,
143        } = self;
144
145        let mut sandbox = match source {
146            Source::GuestBinary(guest_binary) => {
147                let env = GuestEnvironment {
148                    init_data: init_data.as_ref().map(|(data, flags)| GuestBlob {
149                        data,
150                        permissions: *flags,
151                    }),
152                    guest_binary,
153                };
154
155                let mut uninitialized_sandbox = UninitializedSandbox::new(env, Some(cfg))?;
156
157                uninitialized_sandbox.host_funcs = Arc::new(Mutex::new(host_funcs.into_inner()));
158
159                for (path, guest_base) in mapped_file_cow {
160                    uninitialized_sandbox.map_file_cow(&path, guest_base)?;
161                }
162
163                if let Some(log_level) = guest_log_level {
164                    uninitialized_sandbox.set_max_guest_log_level(log_level);
165                }
166
167                uninitialized_sandbox.evolve()?
168            }
169            Source::Snapshot(snapshot) => {
170                if init_data.is_some() {
171                    return Err(new_error!(
172                        "init_data has no effect when building from a snapshot, as the snapshot already contains it"
173                    ));
174                }
175
176                if let Some(log_level) = guest_log_level {
177                    cfg.set_max_guest_log_level(log_level);
178                }
179
180                let mut sandbox = Sandbox::from_snapshot(snapshot, host_funcs, Some(cfg))?;
181
182                for (path, guest_base) in mapped_file_cow {
183                    sandbox.map_file_cow(&path, guest_base)?;
184                }
185
186                sandbox
187            }
188        };
189
190        for region in mapped_memory_regions {
191            // SAFETY: the caller of `mapped_memory_region` guaranteed each region
192            // stays valid and unmodified for the lifetime of this sandbox.
193            unsafe { sandbox.map_region(&region)? };
194        }
195
196        Ok(sandbox)
197    }
198}
199
200impl SandboxBuilder {
201    /// Sets the sandbox `init_data` into the sandbox's memory when it is built, with `flags` as
202    /// the guest's permissions on that region.
203    ///
204    /// Note: [`Self::build`] errors if this setting is set and the builder's
205    /// source is a snapshot, as the snapshot already contains the init data.
206    pub fn init_data(mut self, data: impl Into<Vec<u8>>, flags: MemoryRegionFlags) -> Self {
207        self.init_data = Some((data.into(), flags));
208        self
209    }
210
211    /// Map the contents of the file at `path` into the guest at `guest_base`,
212    /// copy-on-write.
213    ///
214    /// `guest_base` must be page-aligned and lie outside the sandbox's primary
215    /// shared memory region. Violations surface as an error from
216    /// [`Self::build`], not here. Call this once per file to map several.
217    pub fn mapped_file_cow(mut self, path: impl AsRef<Path>, guest_base: u64) -> Self {
218        self.mapped_file_cow
219            .push((path.as_ref().to_path_buf(), guest_base));
220        self
221    }
222
223    /// Maps a region of host memory into the sandbox address space.
224    ///
225    /// The base address and length must meet platform alignment requirements
226    /// (typically page-aligned). The `region_type` field is ignored as guest
227    /// page table entries are not created.
228    ///
229    /// # Safety
230    ///
231    /// The caller must ensure the host memory region remains valid and
232    /// unmodified for the lifetime of the sandbox this builder produces.
233    pub unsafe fn mapped_memory_region(mut self, region: MemoryRegion) -> Self {
234        self.mapped_memory_regions.push(region);
235        self
236    }
237
238    /// Sets the maximum log level for guest code execution.
239    ///
240    /// If not set, the log level is determined by the `RUST_LOG` environment variable,
241    /// defaulting to [`LevelFilter::ERROR`] if unset.
242    ///
243    /// When building from a snapshot, this overrides the level captured in the
244    /// snapshot for subsequent guest calls.
245    pub fn guest_log_level(mut self, level: LevelFilter) -> Self {
246        self.guest_log_level = Some(level);
247        self
248    }
249
250    /// The maximum log level for guest code execution, or `None` if not set.
251    pub fn get_guest_log_level(&self) -> Option<LevelFilter> {
252        self.guest_log_level
253    }
254}
255
256impl SandboxBuilder {
257    /// Registers a host function that the guest can call.
258    ///
259    /// Note: registering under the name `HostPrint` overrides guest printing.
260    /// Prefer [`Self::host_print`], which checks the signature at compile time.
261    pub fn host_function<Args: ParameterTuple, Output: SupportedReturnType>(
262        mut self,
263        name: impl AsRef<str>,
264        host_func: impl Into<HostFunction<Output, Args>>,
265    ) -> Self {
266        let func = host_func.into().into();
267        let name = name.as_ref().to_string();
268
269        let entry = FunctionEntry {
270            function: func,
271            parameter_types: Args::TYPE,
272            return_type: Output::TYPE,
273        };
274
275        self.host_funcs
276            .inner_mut()
277            .register_host_function(name, entry);
278        self
279    }
280
281    /// Registers the special "HostPrint" function for guest printing.
282    ///
283    /// This overrides the default behavior of writing to stdout.
284    /// The function expects the signature `FnMut(String) -> i32`
285    /// and will be called when the guest wants to print output.
286    pub fn host_print(self, print_func: impl Into<HostFunction<i32, (String,)>>) -> Self {
287        self.host_function("HostPrint", print_func)
288    }
289
290    /// Registers every host function in `host_funcs`.
291    ///
292    /// Entries whose names are already registered are overwritten.
293    ///
294    /// Note: an entry named `HostPrint` overrides guest printing. Prefer
295    /// [`Self::host_print`], which checks the signature at compile time.
296    pub fn host_functions(mut self, host_funcs: HostFunctions) -> Self {
297        for (func_name, func_entry) in host_funcs.into_iter() {
298            self.host_funcs
299                .inner_mut()
300                .register_host_function(func_name, func_entry);
301        }
302        self
303    }
304}
305
306impl SandboxBuilder {
307    /// Set the guest heap size. A size of 0 selects
308    /// [`SandboxConfiguration::DEFAULT_HEAP_SIZE`].
309    pub fn heap_size(mut self, size: u64) -> Self {
310        self.cfg.set_heap_size(size);
311        self
312    }
313
314    /// The guest heap size, defaulting to
315    /// [`SandboxConfiguration::DEFAULT_HEAP_SIZE`] when no override is set.
316    pub fn get_heap_size(&self) -> u64 {
317        self.cfg.get_heap_size()
318    }
319
320    /// Set how much writable memory to offer the guest.
321    pub fn scratch_size(mut self, size: usize) -> Self {
322        self.cfg.set_scratch_size(size);
323        self
324    }
325
326    /// How much writable memory is offered to the guest.
327    pub fn get_scratch_size(&self) -> usize {
328        self.cfg.get_scratch_size()
329    }
330
331    /// Set the G2H virtqueue descriptor count.
332    ///
333    /// See [`SandboxConfiguration::set_g2h_queue_size`] for normalization.
334    pub fn g2h_queue_size(mut self, size: usize) -> Self {
335        self.cfg.set_g2h_queue_size(size);
336        self
337    }
338
339    /// Set the H2G virtqueue descriptor count.
340    ///
341    /// See [`SandboxConfiguration::set_h2g_queue_size`] for normalization.
342    pub fn h2g_queue_size(mut self, size: usize) -> Self {
343        self.cfg.set_h2g_queue_size(size);
344        self
345    }
346
347    /// Set the G2H upper-tier buffer capacity in bytes.
348    ///
349    /// Clamps the size via [`SandboxConfiguration::set_g2h_buffer_size`]
350    /// and grows the pool if needed.
351    pub fn g2h_buffer_size(mut self, size: usize) -> Self {
352        self.cfg.set_g2h_buffer_size(size);
353        self
354    }
355
356    /// Set the H2G buffer capacity in bytes.
357    ///
358    /// Clamps the size via [`SandboxConfiguration::set_h2g_buffer_size`]
359    /// and grows the pool if needed.
360    pub fn h2g_buffer_size(mut self, size: usize) -> Self {
361        self.cfg.set_h2g_buffer_size(size);
362        self
363    }
364
365    /// Set the G2H pool size in guest pages.
366    ///
367    /// See [`SandboxConfiguration::set_g2h_pool_pages`] for the minimum capacity.
368    pub fn g2h_pool_pages(mut self, pages: usize) -> Self {
369        self.cfg.set_g2h_pool_pages(pages);
370        self
371    }
372
373    /// Set the H2G pool size in guest pages.
374    ///
375    /// See [`SandboxConfiguration::set_h2g_pool_pages`] for the minimum capacity.
376    pub fn h2g_pool_pages(mut self, pages: usize) -> Self {
377        self.cfg.set_h2g_pool_pages(pages);
378        self
379    }
380
381    /// Declare MSRs the guest owns, saved and restored with the rest of the
382    /// sandbox state. Adds to the declared set, so repeated calls accumulate.
383    ///
384    /// See [`SandboxConfiguration::guest_msrs`] for the platform-specific
385    /// behavior and the capacity limit.
386    ///
387    /// # Errors
388    ///
389    /// Returns [`GuestMsrError::CapacityExceeded`] if the distinct entries
390    /// would exceed [`SandboxConfiguration::MAX_GUEST_MSRS`]. The declared set
391    /// is unchanged on error.
392    #[cfg(target_arch = "x86_64")]
393    pub fn guest_msrs(mut self, indices: &[u32]) -> std::result::Result<Self, GuestMsrError> {
394        self.cfg.guest_msrs(indices)?;
395        Ok(self)
396    }
397
398    /// Set how long to wait between attempts to signal the VCPU thread.
399    #[cfg(target_os = "linux")]
400    pub fn interrupt_retry_delay(mut self, delay: Duration) -> Self {
401        self.cfg.set_interrupt_retry_delay(delay);
402        self
403    }
404
405    /// How long to wait between attempts to signal the VCPU thread.
406    #[cfg(target_os = "linux")]
407    pub fn get_interrupt_retry_delay(&self) -> Duration {
408        self.cfg.get_interrupt_retry_delay()
409    }
410
411    /// Set the offset from `SIGRTMIN` for the signal used to interrupt the VCPU
412    /// thread.
413    ///
414    /// # Errors
415    ///
416    /// Returns an error if `SIGRTMIN + offset` exceeds `SIGRTMAX`.
417    #[cfg(target_os = "linux")]
418    pub fn interrupt_vcpu_sigrtmin_offset(mut self, offset: u8) -> Result<Self> {
419        self.cfg.set_interrupt_vcpu_sigrtmin_offset(offset)?;
420        Ok(self)
421    }
422
423    /// The offset from `SIGRTMIN` for the signal used to interrupt the VCPU thread.
424    #[cfg(target_os = "linux")]
425    pub fn get_interrupt_vcpu_sigrtmin_offset(&self) -> u8 {
426        self.cfg.get_interrupt_vcpu_sigrtmin_offset()
427    }
428
429    /// Toggle guest core dump generation.
430    #[cfg(crashdump)]
431    pub fn guest_core_dump(mut self, enabled: bool) -> Self {
432        self.cfg.set_guest_core_dump(enabled);
433        self
434    }
435
436    /// Whether guest core dump generation is enabled.
437    #[cfg(crashdump)]
438    pub fn get_guest_core_dump(&self) -> bool {
439        self.cfg.get_guest_core_dump()
440    }
441
442    /// Set the guest debug configuration.
443    #[cfg(gdb)]
444    pub fn guest_debug_info(mut self, debug_info: DebugInfo) -> Self {
445        self.cfg.set_guest_debug_info(debug_info);
446        self
447    }
448
449    /// The guest debug configuration, or `None` when debugging is not configured.
450    #[cfg(gdb)]
451    pub fn get_guest_debug_info(&self) -> Option<DebugInfo> {
452        self.cfg.get_guest_debug_info()
453    }
454}
455
456#[cfg(test)]
457mod tests {
458    use hyperlight_common::vmem::PAGE_SIZE;
459    use hyperlight_testing::simple_guest_as_string;
460    use tracing_core::LevelFilter;
461
462    use super::SandboxBuilder;
463    use crate::mem::memory_region::MemoryRegionFlags;
464
465    #[test]
466    fn transport_settings_are_normalized() {
467        let builder = SandboxBuilder::from_bytes([])
468            .g2h_queue_size(3)
469            .h2g_queue_size(usize::MAX)
470            .g2h_buffer_size(0)
471            .h2g_buffer_size(2 * PAGE_SIZE + 1)
472            .g2h_pool_pages(0)
473            .h2g_pool_pages(0);
474
475        assert_eq!(builder.cfg.get_g2h_queue_size(), 4);
476        assert_eq!(builder.cfg.get_h2g_queue_size(), 32_768);
477        assert_eq!(builder.cfg.get_g2h_buffer_size(), 256);
478        assert_eq!(builder.cfg.get_h2g_buffer_size(), 2 * PAGE_SIZE + 1);
479        assert_eq!(builder.cfg.get_g2h_pool_pages(), 2);
480        assert_eq!(builder.cfg.get_h2g_pool_pages(), 3);
481    }
482
483    #[test]
484    fn transport_buffer_growth_raises_pool_minima() {
485        let builder = SandboxBuilder::from_bytes([])
486            .g2h_pool_pages(0)
487            .h2g_pool_pages(0)
488            .g2h_buffer_size(PAGE_SIZE + 1)
489            .h2g_buffer_size(3 * PAGE_SIZE + 1);
490
491        assert_eq!(builder.cfg.get_g2h_buffer_size(), PAGE_SIZE + 1);
492        assert_eq!(builder.cfg.get_h2g_buffer_size(), 3 * PAGE_SIZE + 1);
493        assert_eq!(builder.cfg.get_g2h_pool_pages(), 3);
494        assert_eq!(builder.cfg.get_h2g_pool_pages(), 4);
495    }
496
497    #[test]
498    fn build_from_file() {
499        let path = simple_guest_as_string().unwrap();
500        let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
501
502        let result = sandbox.call::<String>("Echo", "hello".to_string()).unwrap();
503        assert_eq!(result, "hello");
504    }
505
506    #[test]
507    fn build_from_bytes() {
508        let bytes = std::fs::read(simple_guest_as_string().unwrap()).unwrap();
509        let mut sandbox = SandboxBuilder::from_bytes(bytes).build().unwrap();
510
511        let result = sandbox.call::<String>("Echo", "hello".to_string()).unwrap();
512        assert_eq!(result, "hello");
513    }
514
515    #[test]
516    fn build_from_snapshot() {
517        let path = simple_guest_as_string().unwrap();
518        let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
519        let snapshot = sandbox.snapshot().unwrap();
520
521        let mut restored = SandboxBuilder::from_snapshot(snapshot).build().unwrap();
522
523        let result = restored
524            .call::<String>("Echo", "hello".to_string())
525            .unwrap();
526        assert_eq!(result, "hello");
527    }
528
529    #[test]
530    fn build_from_snapshot_rejects_init_data_and_accepts_guest_log_level() {
531        let path = simple_guest_as_string().unwrap();
532        let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
533        let snapshot = sandbox.snapshot().unwrap();
534
535        assert!(
536            SandboxBuilder::from_snapshot(snapshot.clone())
537                .init_data([0u8; 8], MemoryRegionFlags::READ)
538                .build()
539                .is_err()
540        );
541
542        assert!(
543            SandboxBuilder::from_snapshot(snapshot)
544                .guest_log_level(LevelFilter::INFO)
545                .build()
546                .is_ok()
547        );
548    }
549}