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///     .scratch_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 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 how much writable memory to offer the guest. Scratch backs the
308    /// guest heap and stack.
309    pub fn scratch_size(mut self, size: usize) -> Self {
310        self.cfg.set_scratch_size(size);
311        self
312    }
313
314    /// How much writable memory is offered to the guest.
315    pub fn get_scratch_size(&self) -> usize {
316        self.cfg.get_scratch_size()
317    }
318
319    /// Set the G2H virtqueue descriptor count.
320    ///
321    /// See [`SandboxConfiguration::set_g2h_queue_size`] for normalization.
322    pub fn g2h_queue_size(mut self, size: usize) -> Self {
323        self.cfg.set_g2h_queue_size(size);
324        self
325    }
326
327    /// Set the H2G virtqueue descriptor count.
328    ///
329    /// See [`SandboxConfiguration::set_h2g_queue_size`] for normalization.
330    pub fn h2g_queue_size(mut self, size: usize) -> Self {
331        self.cfg.set_h2g_queue_size(size);
332        self
333    }
334
335    /// Set the G2H upper-tier buffer capacity in bytes.
336    ///
337    /// Clamps the size via [`SandboxConfiguration::set_g2h_buffer_size`]
338    /// and grows the pool if needed.
339    pub fn g2h_buffer_size(mut self, size: usize) -> Self {
340        self.cfg.set_g2h_buffer_size(size);
341        self
342    }
343
344    /// Set the H2G buffer capacity in bytes.
345    ///
346    /// Clamps the size via [`SandboxConfiguration::set_h2g_buffer_size`]
347    /// and grows the pool if needed.
348    pub fn h2g_buffer_size(mut self, size: usize) -> Self {
349        self.cfg.set_h2g_buffer_size(size);
350        self
351    }
352
353    /// Set the G2H pool size in guest pages.
354    ///
355    /// See [`SandboxConfiguration::set_g2h_pool_pages`] for the minimum capacity.
356    pub fn g2h_pool_pages(mut self, pages: usize) -> Self {
357        self.cfg.set_g2h_pool_pages(pages);
358        self
359    }
360
361    /// Set the H2G pool size in guest pages.
362    ///
363    /// See [`SandboxConfiguration::set_h2g_pool_pages`] for the minimum capacity.
364    pub fn h2g_pool_pages(mut self, pages: usize) -> Self {
365        self.cfg.set_h2g_pool_pages(pages);
366        self
367    }
368
369    /// Declare MSRs the guest owns, saved and restored with the rest of the
370    /// sandbox state. Adds to the declared set, so repeated calls accumulate.
371    ///
372    /// See [`SandboxConfiguration::guest_msrs`] for the platform-specific
373    /// behavior and the capacity limit.
374    ///
375    /// # Errors
376    ///
377    /// Returns [`GuestMsrError::CapacityExceeded`] if the distinct entries
378    /// would exceed [`SandboxConfiguration::MAX_GUEST_MSRS`]. The declared set
379    /// is unchanged on error.
380    #[cfg(target_arch = "x86_64")]
381    pub fn guest_msrs(mut self, indices: &[u32]) -> std::result::Result<Self, GuestMsrError> {
382        self.cfg.guest_msrs(indices)?;
383        Ok(self)
384    }
385
386    /// Set how long to wait between attempts to signal the VCPU thread.
387    #[cfg(target_os = "linux")]
388    pub fn interrupt_retry_delay(mut self, delay: Duration) -> Self {
389        self.cfg.set_interrupt_retry_delay(delay);
390        self
391    }
392
393    /// How long to wait between attempts to signal the VCPU thread.
394    #[cfg(target_os = "linux")]
395    pub fn get_interrupt_retry_delay(&self) -> Duration {
396        self.cfg.get_interrupt_retry_delay()
397    }
398
399    /// Set the offset from `SIGRTMIN` for the signal used to interrupt the VCPU
400    /// thread.
401    ///
402    /// # Errors
403    ///
404    /// Returns an error if `SIGRTMIN + offset` exceeds `SIGRTMAX`.
405    #[cfg(target_os = "linux")]
406    pub fn interrupt_vcpu_sigrtmin_offset(mut self, offset: u8) -> Result<Self> {
407        self.cfg.set_interrupt_vcpu_sigrtmin_offset(offset)?;
408        Ok(self)
409    }
410
411    /// The offset from `SIGRTMIN` for the signal used to interrupt the VCPU thread.
412    #[cfg(target_os = "linux")]
413    pub fn get_interrupt_vcpu_sigrtmin_offset(&self) -> u8 {
414        self.cfg.get_interrupt_vcpu_sigrtmin_offset()
415    }
416
417    /// Toggle guest core dump generation.
418    #[cfg(crashdump)]
419    pub fn guest_core_dump(mut self, enabled: bool) -> Self {
420        self.cfg.set_guest_core_dump(enabled);
421        self
422    }
423
424    /// Whether guest core dump generation is enabled.
425    #[cfg(crashdump)]
426    pub fn get_guest_core_dump(&self) -> bool {
427        self.cfg.get_guest_core_dump()
428    }
429
430    /// Set the guest debug configuration.
431    #[cfg(gdb)]
432    pub fn guest_debug_info(mut self, debug_info: DebugInfo) -> Self {
433        self.cfg.set_guest_debug_info(debug_info);
434        self
435    }
436
437    /// The guest debug configuration, or `None` when debugging is not configured.
438    #[cfg(gdb)]
439    pub fn get_guest_debug_info(&self) -> Option<DebugInfo> {
440        self.cfg.get_guest_debug_info()
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use hyperlight_common::vmem::PAGE_SIZE;
447    use hyperlight_testing::simple_guest_as_string;
448    use tracing_core::LevelFilter;
449
450    use super::SandboxBuilder;
451    use crate::mem::memory_region::MemoryRegionFlags;
452
453    #[test]
454    fn transport_settings_are_normalized() {
455        let builder = SandboxBuilder::from_bytes([])
456            .g2h_queue_size(3)
457            .h2g_queue_size(usize::MAX)
458            .g2h_buffer_size(0)
459            .h2g_buffer_size(2 * PAGE_SIZE + 1)
460            .g2h_pool_pages(0)
461            .h2g_pool_pages(0);
462
463        assert_eq!(builder.cfg.get_g2h_queue_size(), 4);
464        assert_eq!(builder.cfg.get_h2g_queue_size(), 32_768);
465        assert_eq!(builder.cfg.get_g2h_buffer_size(), 256);
466        assert_eq!(builder.cfg.get_h2g_buffer_size(), 2 * PAGE_SIZE + 1);
467        assert_eq!(builder.cfg.get_g2h_pool_pages(), 2);
468        assert_eq!(builder.cfg.get_h2g_pool_pages(), 3);
469    }
470
471    #[test]
472    fn transport_buffer_growth_raises_pool_minima() {
473        let builder = SandboxBuilder::from_bytes([])
474            .g2h_pool_pages(0)
475            .h2g_pool_pages(0)
476            .g2h_buffer_size(PAGE_SIZE + 1)
477            .h2g_buffer_size(3 * PAGE_SIZE + 1);
478
479        assert_eq!(builder.cfg.get_g2h_buffer_size(), PAGE_SIZE + 1);
480        assert_eq!(builder.cfg.get_h2g_buffer_size(), 3 * PAGE_SIZE + 1);
481        assert_eq!(builder.cfg.get_g2h_pool_pages(), 3);
482        assert_eq!(builder.cfg.get_h2g_pool_pages(), 4);
483    }
484
485    #[test]
486    fn build_from_file() {
487        let path = simple_guest_as_string().unwrap();
488        let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
489
490        let result = sandbox.call::<String>("Echo", "hello".to_string()).unwrap();
491        assert_eq!(result, "hello");
492    }
493
494    #[test]
495    fn build_from_bytes() {
496        let bytes = std::fs::read(simple_guest_as_string().unwrap()).unwrap();
497        let mut sandbox = SandboxBuilder::from_bytes(bytes).build().unwrap();
498
499        let result = sandbox.call::<String>("Echo", "hello".to_string()).unwrap();
500        assert_eq!(result, "hello");
501    }
502
503    #[test]
504    fn build_from_snapshot() {
505        let path = simple_guest_as_string().unwrap();
506        let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
507        let snapshot = sandbox.snapshot().unwrap();
508
509        let mut restored = SandboxBuilder::from_snapshot(snapshot).build().unwrap();
510
511        let result = restored
512            .call::<String>("Echo", "hello".to_string())
513            .unwrap();
514        assert_eq!(result, "hello");
515    }
516
517    #[test]
518    fn build_from_snapshot_rejects_init_data_and_accepts_guest_log_level() {
519        let path = simple_guest_as_string().unwrap();
520        let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
521        let snapshot = sandbox.snapshot().unwrap();
522
523        assert!(
524            SandboxBuilder::from_snapshot(snapshot.clone())
525                .init_data([0u8; 8], MemoryRegionFlags::READ)
526                .build()
527                .is_err()
528        );
529
530        assert!(
531            SandboxBuilder::from_snapshot(snapshot)
532                .guest_log_level(LevelFilter::INFO)
533                .build()
534                .is_ok()
535        );
536    }
537}