Skip to main content

hyperlight_host/sandbox/
uninitialized.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025 The Hyperlight Authors.
3
4use std::fmt::Debug;
5use std::option::Option;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex};
8
9use tracing::{Span, instrument};
10use tracing_core::LevelFilter;
11
12use super::host_funcs::FunctionRegistry;
13use super::snapshot::Snapshot;
14use super::uninitialized_evolve::initialize_sandbox;
15use crate::func::host_functions::{HostFunction, register_host_function};
16use crate::func::{ParameterTuple, SupportedReturnType};
17#[cfg(feature = "build-metadata")]
18use crate::log_build_details;
19use crate::mem::memory_region::{DEFAULT_GUEST_BLOB_MEM_FLAGS, MemoryRegionFlags};
20use crate::mem::mgr::SandboxMemoryManager;
21use crate::mem::shared_mem::{ExclusiveSharedMemory, SharedMemory};
22use crate::sandbox::SandboxConfiguration;
23use crate::{Result, Sandbox, new_error};
24
25#[cfg(any(crashdump, gdb))]
26#[derive(Clone, Debug, Default)]
27pub(crate) struct SandboxRuntimeConfig {
28    #[cfg(crashdump)]
29    pub(crate) binary_path: Option<PathBuf>,
30    #[cfg(gdb)]
31    pub(crate) debug_info: Option<super::config::DebugInfo>,
32    #[cfg(crashdump)]
33    pub(crate) guest_core_dump: bool,
34    /// The original entry point address of the loaded guest binary
35    /// (load_addr + ELF entry offset). Used for AT_ENTRY in core dumps
36    /// so GDB can compute the correct load offset for PIE binaries.
37    ///
38    /// `None` until resolved from the snapshot's `NextAction::Initialise`
39    /// in `set_up_hypervisor_partition`.
40    #[cfg(crashdump)]
41    pub(crate) entry_point: Option<u64>,
42}
43
44/// A preliminary sandbox that represents allocated memory and registered host functions,
45/// but has not yet created the underlying virtual machine.
46///
47/// This struct holds the configuration and setup needed for a sandbox without actually
48/// creating the VM. It allows you to:
49/// - Set up memory layout and load guest binary data
50/// - Register host functions that will be available to the guest
51/// - Configure sandbox settings before VM creation
52///
53/// The virtual machine is not created until you call [`evolve`](Self::evolve) to transform
54/// this into an initialized [`Sandbox`].
55pub struct UninitializedSandbox {
56    /// Registered host functions
57    pub(crate) host_funcs: Arc<Mutex<FunctionRegistry>>,
58    /// The memory manager for the sandbox.
59    pub(crate) mgr: SandboxMemoryManager<ExclusiveSharedMemory>,
60    pub(crate) config: SandboxConfiguration,
61    #[cfg(any(crashdump, gdb))]
62    pub(crate) rt_cfg: SandboxRuntimeConfig,
63    pub(crate) load_info: crate::mem::exe::LoadInfo,
64    // This is needed to convey the stack pointer between the snapshot
65    // and the HyperlightVm creation
66    pub(crate) stack_top_gva: u64,
67    /// File mappings prepared by [`Self::map_file_cow`] that will be
68    /// applied to the VM during [`Self::evolve`].
69    pub(crate) pending_file_mappings: Vec<super::file_mapping::PreparedFileMapping>,
70}
71
72impl Debug for UninitializedSandbox {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.debug_struct("UninitializedSandbox")
75            .field("memory_layout", &self.mgr.layout)
76            .finish()
77    }
78}
79
80/// A `GuestBinary` is either a buffer or the file path to some data (e.g., a guest binary).
81#[derive(Debug)]
82pub enum GuestBinary {
83    /// A buffer containing the GuestBinary
84    Buffer(Vec<u8>),
85    /// A path to the GuestBinary
86    FilePath(PathBuf),
87}
88impl GuestBinary {
89    /// If the guest binary is identified by a file, canonicalise the path
90    ///
91    /// For [`GuestBinary::FilePath`], this resolves the path to its canonical
92    /// form. For [`GuestBinary::Buffer`], this method is a no-op.
93    /// TODO: Maybe we should make the GuestEnvironment or
94    ///       GuestBinary constructors crate-private and turn this
95    ///       into an invariant on one of those types.
96    pub fn canonicalize(&mut self) -> Result<()> {
97        if let GuestBinary::FilePath(p) = self {
98            *p = p
99                .canonicalize()
100                .map_err(|e| new_error!("GuestBinary not found: '{}': {}", p.display(), e))?;
101        }
102        Ok(())
103    }
104}
105
106/// A `GuestBlob` containing data and the permissions for its use.
107#[derive(Debug)]
108pub struct GuestBlob<'a> {
109    /// The data contained in the blob.
110    pub data: &'a [u8],
111    /// The permissions for the blob in memory.
112    /// By default, it's READ
113    pub permissions: MemoryRegionFlags,
114}
115
116impl<'a> From<&'a [u8]> for GuestBlob<'a> {
117    fn from(data: &'a [u8]) -> Self {
118        GuestBlob {
119            data,
120            permissions: DEFAULT_GUEST_BLOB_MEM_FLAGS,
121        }
122    }
123}
124
125/// Container for a guest binary and optional initialization data.
126///
127/// This struct combines a guest binary (either from a file or memory buffer) with
128/// optional data that will be available to the guest during execution.
129///
130/// The guest binary is owned. `'b` is the lifetime of the borrowed init data.
131#[derive(Debug)]
132pub struct GuestEnvironment<'b> {
133    /// The guest binary, which can be a file path or a buffer.
134    pub guest_binary: GuestBinary,
135    /// An optional guest blob, which can be used to provide additional data to the guest.
136    pub init_data: Option<GuestBlob<'b>>,
137}
138
139impl<'b> GuestEnvironment<'b> {
140    /// Creates a new `GuestEnvironment` with the given guest binary and an optional guest blob.
141    pub fn new(guest_binary: GuestBinary, init_data: Option<&'b [u8]>) -> Self {
142        GuestEnvironment {
143            guest_binary,
144            init_data: init_data.map(GuestBlob::from),
145        }
146    }
147}
148
149impl From<GuestBinary> for GuestEnvironment<'_> {
150    fn from(guest_binary: GuestBinary) -> Self {
151        GuestEnvironment {
152            guest_binary,
153            init_data: None,
154        }
155    }
156}
157
158impl UninitializedSandbox {
159    // Creates a new uninitialized sandbox from a pre-built snapshot.
160    // Note that since memory configuration is part of the snapshot the only configuration
161    // that can be changed (from the original snapshot) is the configuration defines the behaviour of
162    // `InterruptHandler` on Linux.
163    //
164    // This is ok for now as this is not a public function
165    fn from_snapshot(
166        snapshot: Arc<Snapshot>,
167        cfg: Option<SandboxConfiguration>,
168        #[cfg(crashdump)] binary_path: Option<PathBuf>,
169    ) -> Result<Self> {
170        #[cfg(feature = "build-metadata")]
171        log_build_details();
172
173        // hyperlight is only supported on Windows 11 and Windows Server 2022 and later
174        #[cfg(target_os = "windows")]
175        check_windows_version()?;
176
177        let sandbox_cfg = cfg.unwrap_or_default();
178
179        #[cfg(any(crashdump, gdb))]
180        let rt_cfg = {
181            #[cfg(crashdump)]
182            let guest_core_dump = sandbox_cfg.get_guest_core_dump();
183
184            #[cfg(gdb)]
185            let debug_info = sandbox_cfg.get_guest_debug_info();
186
187            SandboxRuntimeConfig {
188                #[cfg(crashdump)]
189                binary_path,
190                #[cfg(gdb)]
191                debug_info,
192                #[cfg(crashdump)]
193                guest_core_dump,
194                // entry_point is set later in set_up_hypervisor_partition
195                // once the entrypoint is resolved from the snapshot
196                #[cfg(crashdump)]
197                entry_point: None,
198            }
199        };
200
201        let mem_mgr_wrapper =
202            SandboxMemoryManager::<ExclusiveSharedMemory>::from_snapshot(snapshot.as_ref())?;
203
204        let host_funcs = Arc::new(Mutex::new(FunctionRegistry::with_default_host_print()));
205
206        let sandbox = Self {
207            host_funcs,
208            mgr: mem_mgr_wrapper,
209            config: sandbox_cfg,
210            #[cfg(any(crashdump, gdb))]
211            rt_cfg,
212            load_info: snapshot.load_info(),
213            stack_top_gva: snapshot.stack_top_gva(),
214            pending_file_mappings: Vec::new(),
215        };
216
217        crate::debug!("Sandbox created:  {:#?}", sandbox);
218
219        Ok(sandbox)
220    }
221
222    /// Creates a new uninitialized sandbox for the given guest environment.
223    ///
224    /// The guest binary can be provided as either a file path or memory buffer.
225    /// An optional configuration can customize memory sizes and sandbox settings.
226    /// After creation, register host functions using [`register`](Self::register)
227    /// before calling [`evolve`](Self::evolve) to complete initialization and create the VM.
228    #[instrument(
229        err(Debug),
230        skip(env),
231        parent = Span::current()
232    )]
233    pub fn new<'b>(
234        env: impl Into<GuestEnvironment<'b>>,
235        cfg: Option<SandboxConfiguration>,
236    ) -> Result<Self> {
237        let cfg = cfg.unwrap_or_default();
238        let env = env.into();
239        #[cfg(crashdump)]
240        let binary_path = match &env.guest_binary {
241            GuestBinary::FilePath(path) => Some(path.clone()),
242            GuestBinary::Buffer(_) => None,
243        };
244        let snapshot = Snapshot::from_env(env, cfg)?;
245        Self::from_snapshot(
246            Arc::new(snapshot),
247            Some(cfg),
248            #[cfg(crashdump)]
249            binary_path,
250        )
251    }
252
253    /// Creates and initializes the virtual machine, transforming this into a ready-to-use sandbox.
254    ///
255    /// This method consumes the `UninitializedSandbox` and performs the final initialization
256    /// steps to create the underlying virtual machine. Once evolved, the resulting
257    /// [`Sandbox`] can execute guest code and handle function calls.
258    #[instrument(err(Debug), skip_all, parent = Span::current(), level = "Trace")]
259    pub fn evolve(self) -> Result<Sandbox> {
260        initialize_sandbox(self)
261    }
262
263    /// Map the contents of a file into the guest at a particular address.
264    ///
265    /// The file mapping is prepared immediately (host-side OS work) but
266    /// the actual VM-side mapping is deferred until [`evolve()`](Self::evolve).
267    ///
268    /// The `guest_base` must be page-aligned and must lie **outside**
269    /// the sandbox's primary shared memory region (`BASE_ADDRESS` to
270    /// `BASE_ADDRESS + shared_mem_size`).
271    ///
272    /// Returns the length of the mapping in bytes.
273    #[instrument(err(Debug), skip(self, file_path, guest_base), parent = Span::current())]
274    pub fn map_file_cow(
275        &mut self,
276        file_path: &std::path::Path,
277        guest_base: u64,
278    ) -> crate::Result<u64> {
279        // Validate that guest_base is outside the sandbox's primary memory slot.
280        // (Full range check happens after prepare_file_cow when we know the mapped size.)
281        let shared_size = self.mgr.shared_mem.mem_size() as u64;
282        let base_addr = crate::mem::layout::SandboxMemoryLayout::BASE_ADDRESS as u64;
283
284        let prepared = super::file_mapping::prepare_file_cow(file_path, guest_base)?;
285
286        // Validate full mapped range doesn't overlap shared memory.
287        let mapping_end = guest_base
288            .checked_add(prepared.size as u64)
289            .ok_or_else(|| {
290                crate::HyperlightError::Error(format!(
291                    "map_file_cow: guest address overflow: {:#x} + {:#x}",
292                    guest_base, prepared.size
293                ))
294            })?;
295        let shared_end = base_addr.checked_add(shared_size).ok_or_else(|| {
296            crate::HyperlightError::Error("shared memory end overflow".to_string())
297        })?;
298        if guest_base < shared_end && mapping_end > base_addr {
299            return Err(crate::HyperlightError::Error(format!(
300                "map_file_cow: mapping [{:#x}..{:#x}) overlaps sandbox shared memory [{:#x}..{:#x})",
301                guest_base, mapping_end, base_addr, shared_end,
302            )));
303        }
304
305        let size = prepared.size as u64;
306
307        // Check for overlaps with existing pending file mappings.
308        let new_start = guest_base;
309        let new_end = mapping_end;
310        for existing in &self.pending_file_mappings {
311            let ex_start = existing.guest_base;
312            let ex_end = ex_start.checked_add(existing.size as u64).ok_or_else(|| {
313                crate::HyperlightError::Error(format!(
314                    "map_file_cow: existing mapping address overflow: {:#x} + {:#x}",
315                    ex_start, existing.size
316                ))
317            })?;
318            if new_start < ex_end && new_end > ex_start {
319                return Err(crate::HyperlightError::Error(format!(
320                    "map_file_cow: mapping [{:#x}..{:#x}) overlaps existing mapping [{:#x}..{:#x})",
321                    new_start, new_end, ex_start, ex_end,
322                )));
323            }
324        }
325
326        self.pending_file_mappings.push(prepared);
327        Ok(size)
328    }
329
330    /// Returns the total size of the sandbox shared memory region in bytes.
331    ///
332    /// This is useful for placing file mappings at guest physical addresses
333    /// that don't overlap the primary shared memory slot.
334    pub fn shared_mem_size(&self) -> usize {
335        self.mgr.shared_mem.mem_size()
336    }
337
338    /// Sets the maximum log level for guest code execution.
339    ///
340    /// If not set, the log level is determined by the `RUST_LOG` environment variable,
341    /// defaulting to [`LevelFilter::ERROR`] if unset.
342    pub fn set_max_guest_log_level(&mut self, log_level: LevelFilter) {
343        self.config.set_max_guest_log_level(log_level);
344    }
345
346    /// Registers a host function that the guest can call.
347    pub fn register<Args: ParameterTuple, Output: SupportedReturnType>(
348        &mut self,
349        name: impl AsRef<str>,
350        host_func: impl Into<HostFunction<Output, Args>>,
351    ) -> Result<()> {
352        register_host_function(host_func, self, name.as_ref())
353    }
354
355    /// Registers the special "HostPrint" function for guest printing.
356    ///
357    /// This overrides the default behavior of writing to stdout.
358    /// The function expects the signature `FnMut(String) -> i32`
359    /// and will be called when the guest wants to print output.
360    pub fn register_print(
361        &mut self,
362        print_func: impl Into<HostFunction<i32, (String,)>>,
363    ) -> Result<()> {
364        self.register("HostPrint", print_func)
365    }
366}
367// Check to see if the current version of Windows is supported
368// Hyperlight is only supported on Windows 11 and Windows Server 2022 and later
369#[cfg(target_os = "windows")]
370fn check_windows_version() -> Result<()> {
371    use windows_version::{OsVersion, is_server};
372    const WINDOWS_MAJOR: u32 = 10;
373    const WINDOWS_MINOR: u32 = 0;
374    const WINDOWS_PACK: u32 = 0;
375
376    // Windows Server 2022 has version numbers 10.0.20348 or greater
377    if is_server() {
378        if OsVersion::current() < OsVersion::new(WINDOWS_MAJOR, WINDOWS_MINOR, WINDOWS_PACK, 20348)
379        {
380            return Err(new_error!(
381                "Hyperlight Requires Windows Server 2022 or newer"
382            ));
383        }
384    } else if OsVersion::current()
385        < OsVersion::new(WINDOWS_MAJOR, WINDOWS_MINOR, WINDOWS_PACK, 22000)
386    {
387        return Err(new_error!("Hyperlight Requires Windows 11 or newer"));
388    }
389    Ok(())
390}
391
392#[cfg(test)]
393mod tests {
394    use std::sync::Arc;
395    use std::sync::mpsc::channel;
396    use std::{fs, thread};
397
398    use crossbeam_queue::ArrayQueue;
399    use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue};
400    use hyperlight_testing::simple_guest_as_pathbuf;
401
402    use crate::sandbox::SandboxConfiguration;
403    use crate::sandbox::uninitialized::{GuestBinary, GuestEnvironment};
404    use crate::{Result, Sandbox, UninitializedSandbox, new_error};
405
406    #[cfg(target_os = "linux")]
407    #[test]
408    fn guest_binary_loads_from_non_utf8_path() {
409        use std::ffi::OsString;
410        use std::os::unix::ffi::OsStringExt;
411
412        let temp_dir = tempfile::tempdir().unwrap();
413        let guest_path = temp_dir
414            .path()
415            .join(OsString::from_vec(b"guest-\xff".to_vec()));
416        fs::copy(simple_guest_as_pathbuf(), &guest_path).unwrap();
417
418        let sandbox = UninitializedSandbox::new(GuestBinary::FilePath(guest_path), None);
419
420        assert!(sandbox.is_ok());
421    }
422
423    #[test]
424    fn test_load_extra_blob() {
425        let binary_path = simple_guest_as_pathbuf();
426        let buffer = [0xde, 0xad, 0xbe, 0xef];
427        let guest_env =
428            GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), Some(&buffer));
429
430        let uninitialized_sandbox = UninitializedSandbox::new(guest_env, None).unwrap();
431        let mut sandbox = uninitialized_sandbox.evolve().unwrap();
432
433        let res = sandbox
434            .call::<Vec<u8>>("ReadFromUserMemory", (4u64, buffer.to_vec()))
435            .expect("Failed to call ReadFromUserMemory");
436
437        assert_eq!(res, buffer.to_vec());
438    }
439
440    #[test]
441    fn test_new_sandbox() {
442        // Guest Binary exists at path
443
444        let binary_path = simple_guest_as_pathbuf();
445        let sandbox = UninitializedSandbox::new(GuestBinary::FilePath(binary_path.clone()), None);
446        assert!(sandbox.is_ok());
447
448        // Guest Binary does not exist at path
449
450        let mut binary_path_does_not_exist = binary_path.clone();
451        binary_path_does_not_exist
452            .as_mut_os_string()
453            .push(".nonexistent");
454        let uninitialized_sandbox =
455            UninitializedSandbox::new(GuestBinary::FilePath(binary_path_does_not_exist), None);
456        assert!(uninitialized_sandbox.is_err());
457
458        // Non default memory configuration
459        let cfg = {
460            let mut cfg = SandboxConfiguration::default();
461            cfg.set_heap_size(0x1000);
462            Some(cfg)
463        };
464
465        let uninitialized_sandbox =
466            UninitializedSandbox::new(GuestBinary::FilePath(binary_path.clone()), cfg);
467        assert!(uninitialized_sandbox.is_ok());
468
469        let uninitialized_sandbox =
470            UninitializedSandbox::new(GuestBinary::FilePath(binary_path), None).unwrap();
471
472        // Get a Sandbox from an uninitialized sandbox without a call back function
473
474        let _sandbox = uninitialized_sandbox.evolve().unwrap();
475
476        // Test with a valid guest binary buffer
477
478        let binary_path = simple_guest_as_pathbuf();
479        let sandbox =
480            UninitializedSandbox::new(GuestBinary::Buffer(fs::read(binary_path).unwrap()), None);
481        assert!(sandbox.is_ok());
482
483        // Test with a invalid guest binary buffer
484
485        let binary_path = simple_guest_as_pathbuf();
486        let mut bytes = fs::read(binary_path).unwrap();
487        let _ = bytes.split_off(100);
488        let sandbox = UninitializedSandbox::new(GuestBinary::Buffer(bytes), None);
489        assert!(sandbox.is_err());
490    }
491
492    #[test]
493    fn test_host_functions() {
494        let uninitialized_sandbox = || {
495            UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
496                .unwrap()
497        };
498
499        // simple register + call
500        {
501            let mut usbox = uninitialized_sandbox();
502
503            usbox.register("test0", |arg: i32| Ok(arg + 1)).unwrap();
504
505            let sandbox: Result<Sandbox> = usbox.evolve();
506            assert!(sandbox.is_ok());
507            let sandbox = sandbox.unwrap();
508
509            let host_funcs = sandbox
510                .host_funcs
511                .try_lock()
512                .map_err(|_| new_error!("Error locking"));
513
514            assert!(host_funcs.is_ok());
515
516            let res = host_funcs
517                .unwrap()
518                .call_host_function("test0", vec![ParameterValue::Int(1)])
519                .unwrap();
520
521            assert_eq!(res, ReturnValue::Int(2));
522        }
523
524        // multiple parameters register + call
525        {
526            let mut usbox = uninitialized_sandbox();
527
528            usbox.register("test1", |a: i32, b: i32| Ok(a + b)).unwrap();
529
530            let sandbox: Result<Sandbox> = usbox.evolve();
531            assert!(sandbox.is_ok());
532            let sandbox = sandbox.unwrap();
533
534            let host_funcs = sandbox
535                .host_funcs
536                .try_lock()
537                .map_err(|_| new_error!("Error locking"));
538
539            assert!(host_funcs.is_ok());
540
541            let res = host_funcs
542                .unwrap()
543                .call_host_function(
544                    "test1",
545                    vec![ParameterValue::Int(1), ParameterValue::Int(2)],
546                )
547                .unwrap();
548
549            assert_eq!(res, ReturnValue::Int(3));
550        }
551
552        // incorrect arguments register + call
553        {
554            let mut usbox = uninitialized_sandbox();
555
556            usbox
557                .register("test2", |msg: String| {
558                    println!("test2 called: {}", msg);
559                    Ok(())
560                })
561                .unwrap();
562
563            let sandbox: Result<Sandbox> = usbox.evolve();
564            assert!(sandbox.is_ok());
565            let sandbox = sandbox.unwrap();
566
567            let host_funcs = sandbox
568                .host_funcs
569                .try_lock()
570                .map_err(|_| new_error!("Error locking"));
571
572            assert!(host_funcs.is_ok());
573
574            let res = host_funcs.unwrap().call_host_function("test2", vec![]);
575            assert!(res.is_err());
576        }
577
578        // calling a function that doesn't exist
579        {
580            let usbox = uninitialized_sandbox();
581            let sandbox: Result<Sandbox> = usbox.evolve();
582            assert!(sandbox.is_ok());
583            let sandbox = sandbox.unwrap();
584
585            let host_funcs = sandbox
586                .host_funcs
587                .try_lock()
588                .map_err(|_| new_error!("Error locking"));
589
590            assert!(host_funcs.is_ok());
591
592            let res = host_funcs.unwrap().call_host_function("test4", vec![]);
593            assert!(res.is_err());
594        }
595    }
596
597    #[test]
598    fn test_host_print() {
599        // writer as a FnMut closure mutating a captured variable and then trying to access the captured variable
600        // after the Sandbox instance has been dropped
601        // this example is fairly contrived but we should still support such an approach.
602
603        let (tx, rx) = channel();
604
605        let writer = move |msg| {
606            let _ = tx.send(msg);
607            Ok(0)
608        };
609
610        let mut sandbox =
611            UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
612                .expect("Failed to create sandbox");
613
614        sandbox
615            .register_print(writer)
616            .expect("Failed to register host print function");
617
618        let host_funcs = sandbox
619            .host_funcs
620            .try_lock()
621            .map_err(|_| new_error!("Error locking"));
622
623        assert!(host_funcs.is_ok());
624
625        host_funcs.unwrap().host_print("test".to_string()).unwrap();
626
627        drop(sandbox);
628
629        let received_msgs: Vec<_> = rx.into_iter().collect();
630        assert_eq!(received_msgs, ["test"]);
631
632        // There may be cases where a mutable reference to the captured variable is not required to be used outside the closure
633        // e.g. if the function is writing to a file or a socket etc.
634
635        // writer as a FnMut closure mutating a captured variable but not trying to access the captured variable
636
637        // This seems more realistic as the client is creating a file to be written to in the closure
638        // and then accessing the file a different handle.
639        // The problem is that captured_file still needs static lifetime so even though we can access the data through the second file handle
640        // this still does not work as the captured_file is dropped at the end of the function
641
642        // TODO: Currently, we block any writes that are not to
643        // the stdout/stderr file handles, so this code is commented
644        // out until we can register writer functions like any other
645        // host functions with their own set of extra allowed syscalls.
646        // In particular, this code should be brought back once we have addressed the issue
647
648        // let captured_file = Arc::new(Mutex::new(NamedTempFile::new().unwrap()));
649        // let capture_file_clone = captured_file.clone();
650        //
651        // let capture_file_lock = captured_file
652        //     .try_lock()
653        //     .map_err(|_| new_error!("Error locking"))
654        //     .unwrap();
655        // let mut file = capture_file_lock.reopen().unwrap();
656        // drop(capture_file_lock);
657        //
658        // let writer = move |msg: String| -> Result<i32> {
659        //     let mut captured_file = capture_file_clone
660        //         .try_lock()
661        //         .map_err(|_| new_error!("Error locking"))
662        //         .unwrap();
663        //     captured_file.write_all(msg.as_bytes()).unwrap();
664        //     Ok(0)
665        // };
666        //
667        // let writer_func = Arc::new(Mutex::new(writer));
668        //
669        // let sandbox = UninitializedSandbox::new(
670        //     GuestBinary::FilePath(simple_guest_as_pathbuf()),
671        //     None,
672        //     None,
673        //     Some(&writer_func),
674        // )
675        // .expect("Failed to create sandbox");
676        //
677        // let host_funcs = sandbox
678        //     .host_funcs
679        //     .try_lock()
680        //     .map_err(|_| new_error!("Error locking"));
681        //
682        // assert!(host_funcs.is_ok());
683        //
684        // host_funcs.unwrap().host_print("test2".to_string()).unwrap();
685        //
686        // let mut buffer = String::new();
687        // file.read_to_string(&mut buffer).unwrap();
688        // assert_eq!(buffer, "test2");
689
690        // writer as a function
691
692        fn fn_writer(msg: String) -> Result<i32> {
693            assert_eq!(msg, "test2");
694            Ok(0)
695        }
696
697        let mut sandbox =
698            UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
699                .expect("Failed to create sandbox");
700
701        sandbox
702            .register_print(fn_writer)
703            .expect("Failed to register host print function");
704
705        let host_funcs = sandbox
706            .host_funcs
707            .try_lock()
708            .map_err(|_| new_error!("Error locking"));
709
710        assert!(host_funcs.is_ok());
711
712        host_funcs.unwrap().host_print("test2".to_string()).unwrap();
713
714        // writer as a method
715
716        let mut test_host_print = TestHostPrint::new();
717
718        // create a closure over the struct method
719
720        let writer_closure = move |s| test_host_print.write(s);
721
722        let mut sandbox =
723            UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
724                .expect("Failed to create sandbox");
725
726        sandbox
727            .register_print(writer_closure)
728            .expect("Failed to register host print function");
729
730        let host_funcs = sandbox
731            .host_funcs
732            .try_lock()
733            .map_err(|_| new_error!("Error locking"));
734
735        assert!(host_funcs.is_ok());
736
737        host_funcs.unwrap().host_print("test3".to_string()).unwrap();
738    }
739
740    struct TestHostPrint {}
741
742    impl TestHostPrint {
743        fn new() -> Self {
744            TestHostPrint {}
745        }
746
747        fn write(&mut self, msg: String) -> Result<i32> {
748            assert_eq!(msg, "test3");
749            Ok(0)
750        }
751    }
752
753    #[test]
754    fn check_create_and_use_sandbox_on_different_threads() {
755        let unintializedsandbox_queue = Arc::new(ArrayQueue::<UninitializedSandbox>::new(10));
756        let sandbox_queue = Arc::new(ArrayQueue::<Sandbox>::new(10));
757
758        for i in 0..10 {
759            let simple_guest_path = simple_guest_as_pathbuf();
760            let unintializedsandbox = {
761                let err_string = format!("failed to create UninitializedSandbox {i}");
762                let err_str = err_string.as_str();
763                UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_path), None)
764                    .expect(err_str)
765            };
766
767            {
768                let err_string = format!("Failed to push UninitializedSandbox {i}");
769                let err_str = err_string.as_str();
770
771                unintializedsandbox_queue
772                    .push(unintializedsandbox)
773                    .expect(err_str);
774            }
775        }
776
777        let thread_handles = (0..10)
778            .map(|i| {
779                let uq = unintializedsandbox_queue.clone();
780                let sq = sandbox_queue.clone();
781                thread::spawn(move || {
782                    let uninitialized_sandbox = uq.pop().unwrap_or_else(|| {
783                        panic!("Failed to pop UninitializedSandbox thread {}", i)
784                    });
785
786                    let host_funcs = uninitialized_sandbox
787                        .host_funcs
788                        .try_lock()
789                        .map_err(|_| new_error!("Error locking"));
790
791                    assert!(host_funcs.is_ok());
792
793                    host_funcs
794                        .unwrap()
795                        .host_print(format!("Print from UninitializedSandbox on Thread {}\n", i))
796                        .unwrap();
797
798                    let sandbox = uninitialized_sandbox.evolve().unwrap_or_else(|_| {
799                        panic!("Failed to initialize UninitializedSandbox thread {}", i)
800                    });
801
802                    sq.push(sandbox).unwrap_or_else(|_| {
803                        panic!("Failed to push UninitializedSandbox thread {}", i)
804                    })
805                })
806            })
807            .collect::<Vec<_>>();
808
809        for handle in thread_handles {
810            handle.join().unwrap();
811        }
812
813        let thread_handles = (0..10)
814            .map(|i| {
815                let sq = sandbox_queue.clone();
816                thread::spawn(move || {
817                    let sandbox = sq
818                        .pop()
819                        .unwrap_or_else(|| panic!("Failed to pop Sandbox thread {}", i));
820
821                    let host_funcs = sandbox
822                        .host_funcs
823                        .try_lock()
824                        .map_err(|_| new_error!("Error locking"));
825
826                    assert!(host_funcs.is_ok());
827
828                    host_funcs
829                        .unwrap()
830                        .host_print(format!("Print from Sandbox on Thread {}\n", i))
831                        .unwrap();
832                })
833            })
834            .collect::<Vec<_>>();
835
836        for handle in thread_handles {
837            handle.join().unwrap();
838        }
839    }
840
841    /// Tests that tracing spans and events are properly emitted when a tracing subscriber is set.
842    ///
843    /// This test verifies:
844    /// 1. Spans are created with correct attributes (correlation_id)
845    /// 2. Nested spans from UninitializedSandbox::new are properly parented
846    /// 3. Error events are emitted when sandbox creation fails
847    ///
848    /// NOTE: The `#[instrument]` callsite on `UninitializedSandbox::new` uses
849    /// tracing's global interest cache. If another test thread registers that
850    /// callsite first (with the no-op subscriber), the cached `Interest::never()`
851    /// will suppress span creation on our thread. To work around this, we:
852    /// 1. Make a warmup call to force-register the callsite
853    /// 2. Call `rebuild_interest_cache()` to overwrite the cached interest with
854    ///    our subscriber's `Interest::sometimes()`
855    /// 3. Clear recorded state and run the real test
856    #[test]
857    #[cfg(feature = "build-metadata")]
858    fn test_trace_trace() {
859        use hyperlight_testing::tracing_subscriber::TracingSubscriber;
860        use tracing::Level;
861        use tracing_core::Subscriber;
862        use tracing_core::callsite::rebuild_interest_cache;
863        use uuid::Uuid;
864
865        /// Helper to extract a string value from nested JSON: obj["span"]["attributes"][key]
866        fn get_span_attr<'a>(span: &'a serde_json::Value, key: &str) -> Option<&'a str> {
867            span.get("span")?.get("attributes")?.get(key)?.as_str()
868        }
869
870        /// Helper to extract event field: obj["event"][field]
871        fn get_event_field<'a>(event: &'a serde_json::Value, field: &str) -> Option<&'a str> {
872            event.get("event")?.get(field)?.as_str()
873        }
874
875        /// Helper to extract event metadata field: obj["event"]["metadata"][field]
876        fn get_event_metadata<'a>(event: &'a serde_json::Value, field: &str) -> Option<&'a str> {
877            event.get("event")?.get("metadata")?.get(field)?.as_str()
878        }
879
880        let subscriber = TracingSubscriber::new(Level::TRACE);
881
882        tracing::subscriber::with_default(subscriber.clone(), || {
883            // Warmup: force-register the #[instrument] callsite on
884            // UninitializedSandbox::new by calling it once. This ensures the
885            // callsite exists in the global registry regardless of whether
886            // another thread already registered it.
887            let mut bad_path = simple_guest_as_pathbuf();
888            bad_path.as_mut_os_string().push("does_not_exist");
889            let _ = UninitializedSandbox::new(GuestBinary::FilePath(bad_path.clone()), None);
890
891            // Rebuild the interest cache. Now that the callsite is guaranteed
892            // to be registered, this will overwrite any cached Interest::never()
893            // (from another thread's no-op subscriber) with our subscriber's
894            // Interest::sometimes(), ensuring subsequent calls create spans.
895            rebuild_interest_cache();
896
897            // Clear all state from the warmup call
898            subscriber.clear();
899
900            let correlation_id = Uuid::new_v4().to_string();
901            let _span = tracing::error_span!("test_trace_logs", %correlation_id).entered();
902
903            // Verify we're in a span with correct name
904            let (test_span_id, span_meta) = subscriber
905                .current_span()
906                .into_inner()
907                .expect("Should be inside a span");
908            assert_eq!(span_meta.name(), "test_trace_logs");
909
910            // Verify correlation_id was recorded
911            let span_data = subscriber.get_span(test_span_id.into_u64());
912            let recorded_id =
913                get_span_attr(&span_data, "correlation_id").expect("correlation_id not found");
914            assert_eq!(recorded_id, correlation_id);
915
916            // Try to create a sandbox with a non-existent binary - this should fail
917            // and emit an error event
918            let result = UninitializedSandbox::new(GuestBinary::FilePath(bad_path), None);
919            assert!(result.is_err(), "Sandbox creation should fail");
920
921            // Verify we're still in our test span
922            let (current_id, _) = subscriber
923                .current_span()
924                .into_inner()
925                .expect("Should still be inside a span");
926            assert_eq!(
927                current_id.into_u64(),
928                test_span_id.into_u64(),
929                "Should still be in the test span"
930            );
931
932            // Verify a span named "new" was created by UninitializedSandbox::new
933            // (look up by name rather than hardcoded ID to avoid fragility)
934            let all_spans = subscriber.get_all_spans();
935            let _new_span_entry = all_spans
936                .iter()
937                .find(|&(&id, _)| {
938                    id != test_span_id.into_u64()
939                        && subscriber.get_span_metadata(id).name() == "new"
940                })
941                .expect("Expected a span named 'new' from UninitializedSandbox::new");
942
943            // Verify the error event was emitted
944            let events = subscriber.get_events();
945            assert_eq!(events.len(), 1, "Expected exactly one error event");
946
947            let event = &events[0];
948            let level = get_event_metadata(event, "level").expect("event should have level");
949            let error = get_event_field(event, "error").expect("event should have error field");
950            let target = get_event_metadata(event, "target").expect("event should have target");
951            let module_path =
952                get_event_metadata(event, "module_path").expect("event should have module_path");
953
954            assert_eq!(level, "ERROR");
955            assert!(
956                error.contains("GuestBinary not found"),
957                "Error should mention 'GuestBinary not found', got: {error}"
958            );
959            assert_eq!(target, "hyperlight_host::sandbox::uninitialized");
960            assert_eq!(module_path, "hyperlight_host::sandbox::uninitialized");
961        });
962    }
963
964    #[test]
965    #[ignore]
966    // Tests that traces are emitted as log records when there is no trace
967    // subscriber configured.
968    #[cfg(feature = "build-metadata")]
969    fn test_log_trace() {
970        use std::path::PathBuf;
971
972        use hyperlight_testing::logger::{LOGGER as TEST_LOGGER, Logger as TestLogger};
973        use log::Level;
974        use tracing_core::callsite::rebuild_interest_cache;
975
976        {
977            TestLogger::initialize_test_logger();
978            TEST_LOGGER.set_max_level(log::LevelFilter::Trace);
979
980            // This makes sure that the metadata interest cache is rebuilt so that
981            // the log records are emitted for the trace records
982
983            rebuild_interest_cache();
984
985            let mut invalid_binary_path = simple_guest_as_pathbuf();
986            invalid_binary_path
987                .as_mut_os_string()
988                .push("does_not_exist");
989
990            let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_binary_path), None);
991            assert!(sbox.is_err());
992
993            // When tracing is creating log records it will create a log
994            // record for the creation of the span (from the instrument
995            // attribute), and will then create a log record for the entry to
996            // and exit from the span.
997            //
998            // It also creates a log record for the span being dropped.
999            //
1000            // In addition there are 14 info log records created for build information
1001            //
1002            // So we expect 19 log records for this test, four for the span and
1003            // then one for the error as the file that we are attempting to
1004            // load into the sandbox does not exist, plus the 14 info log records
1005
1006            let num_calls = TEST_LOGGER.num_log_calls();
1007            assert_eq!(13, num_calls);
1008
1009            // Log record 1
1010
1011            let logcall = TEST_LOGGER.get_log_call(0).unwrap();
1012            assert_eq!(Level::Info, logcall.level);
1013
1014            assert!(logcall.args.starts_with("new; cfg"));
1015            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
1016
1017            // Log record 2
1018
1019            let logcall = TEST_LOGGER.get_log_call(1).unwrap();
1020            assert_eq!(Level::Trace, logcall.level);
1021            assert_eq!(logcall.args, "-> new;");
1022            assert_eq!("tracing::span::active", logcall.target);
1023
1024            // Log record 17
1025
1026            let logcall = TEST_LOGGER.get_log_call(10).unwrap();
1027            assert_eq!(Level::Error, logcall.level);
1028            assert!(
1029                logcall
1030                    .args
1031                    .starts_with("error=Error(\"GuestBinary not found:")
1032            );
1033            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
1034
1035            // Log record 18
1036
1037            let logcall = TEST_LOGGER.get_log_call(11).unwrap();
1038            assert_eq!(Level::Trace, logcall.level);
1039            assert_eq!(logcall.args, "<- new;");
1040            assert_eq!("tracing::span::active", logcall.target);
1041
1042            // Log record 19
1043
1044            let logcall = TEST_LOGGER.get_log_call(12).unwrap();
1045            assert_eq!(Level::Trace, logcall.level);
1046            assert_eq!(logcall.args, "-- new;");
1047            assert_eq!("tracing::span", logcall.target);
1048        }
1049        {
1050            // test to ensure an invalid binary logs & traces properly
1051            TEST_LOGGER.clear_log_calls();
1052            TEST_LOGGER.set_max_level(log::LevelFilter::Info);
1053
1054            // An existing file that is never a valid guest binary.
1055            let mut invalid_binary_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1056            invalid_binary_path.push("Cargo.toml");
1057
1058            let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_binary_path), None);
1059            assert!(sbox.is_err());
1060
1061            // There should be 2 calls this time when we change to the log
1062            // LevelFilter to Info.
1063            let num_calls = TEST_LOGGER.num_log_calls();
1064            assert_eq!(2, num_calls);
1065
1066            // Log record 1
1067
1068            let logcall = TEST_LOGGER.get_log_call(0).unwrap();
1069            assert_eq!(Level::Info, logcall.level);
1070
1071            assert!(logcall.args.starts_with("new; cfg"));
1072            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
1073
1074            // Log record 2
1075
1076            let logcall = TEST_LOGGER.get_log_call(1).unwrap();
1077            assert_eq!(Level::Error, logcall.level);
1078            assert!(logcall.args.starts_with("error=PEFileProcessingFailure"));
1079            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
1080        }
1081        {
1082            TEST_LOGGER.clear_log_calls();
1083            TEST_LOGGER.set_max_level(log::LevelFilter::Error);
1084
1085            let sbox = {
1086                let res = UninitializedSandbox::new(
1087                    GuestBinary::FilePath(simple_guest_as_pathbuf()),
1088                    None,
1089                );
1090                res.unwrap()
1091            };
1092            let _: Result<Sandbox> = sbox.evolve();
1093
1094            let num_calls = TEST_LOGGER.num_log_calls();
1095
1096            assert_eq!(0, num_calls);
1097        }
1098    }
1099
1100    #[test]
1101    fn test_invalid_path() {
1102        let invalid_path = "some/path/that/does/not/exist";
1103        let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_path.into()), None);
1104        println!("{:?}", sbox);
1105        #[cfg(target_os = "windows")]
1106        assert!(
1107            matches!(sbox, Err(e) if e.to_string().contains("GuestBinary not found: 'some/path/that/does/not/exist': The system cannot find the path specified. (os error 3)"))
1108        );
1109        #[cfg(target_os = "linux")]
1110        assert!(
1111            matches!(sbox, Err(e) if e.to_string().contains("GuestBinary not found: 'some/path/that/does/not/exist': No such file or directory (os error 2)"))
1112        );
1113    }
1114
1115    #[test]
1116    fn test_from_snapshot_various_configurations() {
1117        use crate::sandbox::snapshot::Snapshot;
1118
1119        let binary_path = simple_guest_as_pathbuf();
1120
1121        // Test 1: Create snapshot with default config, create multiple sandboxes from it
1122        {
1123            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1124
1125            let snapshot = Arc::new(
1126                Snapshot::from_env(env, Default::default())
1127                    .expect("Failed to create snapshot with default config"),
1128            );
1129
1130            // Create first sandbox from snapshot
1131            let sandbox1 = UninitializedSandbox::from_snapshot(
1132                snapshot.clone(),
1133                None,
1134                #[cfg(crashdump)]
1135                Some(binary_path.clone()),
1136            )
1137            .expect("Failed to create first sandbox from snapshot");
1138
1139            // Create second sandbox from same snapshot
1140            let sandbox2 = UninitializedSandbox::from_snapshot(
1141                snapshot.clone(),
1142                None,
1143                #[cfg(crashdump)]
1144                Some(binary_path.clone()),
1145            )
1146            .expect("Failed to create second sandbox from snapshot");
1147
1148            // Both should be able to evolve independently
1149            let _evolved1 = sandbox1.evolve().expect("Failed to evolve sandbox1");
1150            let _evolved2 = sandbox2.evolve().expect("Failed to evolve sandbox2");
1151        }
1152
1153        // Test 2: Create snapshot with custom heap size
1154        {
1155            let mut cfg = SandboxConfiguration::default();
1156            cfg.set_heap_size(16 * 1024 * 1024); // 16MB heap
1157
1158            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1159
1160            let snapshot = Arc::new(
1161                Snapshot::from_env(env, cfg)
1162                    .expect("Failed to create snapshot with custom heap size"),
1163            );
1164
1165            let sandbox = UninitializedSandbox::from_snapshot(
1166                snapshot,
1167                None,
1168                #[cfg(crashdump)]
1169                Some(binary_path.clone()),
1170            )
1171            .expect("Failed to create sandbox from snapshot with custom heap");
1172
1173            let _evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1174        }
1175
1176        // Test 3: Create snapshot with custom scratch size
1177        {
1178            let mut cfg = SandboxConfiguration::default();
1179            cfg.set_scratch_size(SandboxConfiguration::DEFAULT_SCRATCH_SIZE + 64 * 1024);
1180
1181            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1182
1183            let snapshot = Arc::new(
1184                Snapshot::from_env(env, cfg)
1185                    .expect("Failed to create snapshot with custom stack size"),
1186            );
1187
1188            let sandbox = UninitializedSandbox::from_snapshot(
1189                snapshot,
1190                None,
1191                #[cfg(crashdump)]
1192                Some(binary_path.clone()),
1193            )
1194            .expect("Failed to create sandbox from snapshot with custom stack");
1195
1196            let _evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1197        }
1198
1199        // Test 4: Create snapshot with custom heap and scratch sizes
1200        {
1201            let mut cfg = SandboxConfiguration::default();
1202            cfg.set_heap_size(32 * 1024 * 1024); // 32MB heap
1203            cfg.set_scratch_size(512 * 1024); // 512KB scratch
1204
1205            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1206
1207            let snapshot = Arc::new(
1208                Snapshot::from_env(env, cfg)
1209                    .expect("Failed to create snapshot with all custom settings"),
1210            );
1211
1212            // Create multiple sandboxes from the same snapshot
1213            let sandbox1 = UninitializedSandbox::from_snapshot(
1214                snapshot.clone(),
1215                None,
1216                #[cfg(crashdump)]
1217                Some(binary_path.clone()),
1218            )
1219            .expect("Failed to create sandbox1 from fully customized snapshot");
1220            let sandbox2 = UninitializedSandbox::from_snapshot(
1221                snapshot.clone(),
1222                None,
1223                #[cfg(crashdump)]
1224                Some(binary_path.clone()),
1225            )
1226            .expect("Failed to create sandbox2 from fully customized snapshot");
1227            let sandbox3 = UninitializedSandbox::from_snapshot(
1228                snapshot.clone(),
1229                None,
1230                #[cfg(crashdump)]
1231                Some(binary_path.clone()),
1232            )
1233            .expect("Failed to create sandbox3 from fully customized snapshot");
1234
1235            let _evolved1 = sandbox1.evolve().expect("Failed to evolve sandbox1");
1236            let _evolved2 = sandbox2.evolve().expect("Failed to evolve sandbox2");
1237            let _evolved3 = sandbox3.evolve().expect("Failed to evolve sandbox3");
1238        }
1239
1240        // Test 5: Create snapshot from binary buffer instead of file path
1241        {
1242            let binary_bytes = fs::read(&binary_path).expect("Failed to read binary file");
1243
1244            let snapshot = Arc::new(
1245                Snapshot::from_env(GuestBinary::Buffer(binary_bytes), Default::default())
1246                    .expect("Failed to create snapshot from buffer"),
1247            );
1248
1249            let sandbox = UninitializedSandbox::from_snapshot(
1250                snapshot,
1251                None,
1252                #[cfg(crashdump)]
1253                None,
1254            )
1255            .expect("Failed to create sandbox from buffer-based snapshot");
1256
1257            let _evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1258        }
1259
1260        // Test 6: Register host functions on sandboxes created from snapshot
1261        {
1262            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1263
1264            let snapshot = Arc::new(
1265                Snapshot::from_env(env, Default::default()).expect("Failed to create snapshot"),
1266            );
1267
1268            let mut sandbox = UninitializedSandbox::from_snapshot(
1269                snapshot,
1270                None,
1271                #[cfg(crashdump)]
1272                Some(binary_path.clone()),
1273            )
1274            .expect("Failed to create sandbox from snapshot");
1275
1276            // Register a custom host function
1277            sandbox
1278                .register("CustomAdd", |a: i32, b: i32| Ok(a + b))
1279                .expect("Failed to register custom function");
1280
1281            let evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1282
1283            // Verify the host function was registered
1284            let host_funcs = evolved
1285                .host_funcs
1286                .try_lock()
1287                .expect("Failed to lock host funcs");
1288
1289            let result = host_funcs
1290                .call_host_function(
1291                    "CustomAdd",
1292                    vec![ParameterValue::Int(10), ParameterValue::Int(20)],
1293                )
1294                .expect("Failed to call CustomAdd");
1295
1296            assert_eq!(result, ReturnValue::Int(30));
1297        }
1298
1299        // Test 7: Create snapshot with init data (guest blob)
1300        {
1301            let init_data = [0xCA, 0xFE, 0xBA, 0xBE];
1302            let guest_env =
1303                GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), Some(&init_data));
1304
1305            let snapshot = Arc::new(
1306                Snapshot::from_env(guest_env, Default::default())
1307                    .expect("Failed to create snapshot with init data"),
1308            );
1309
1310            let sandbox = UninitializedSandbox::from_snapshot(
1311                snapshot,
1312                None,
1313                #[cfg(crashdump)]
1314                Some(binary_path.clone()),
1315            )
1316            .expect("Failed to create sandbox from snapshot with init data");
1317
1318            let _evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1319        }
1320
1321        // Test 8: Create snapshot from existing sandbox
1322        {
1323            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1324            let orig_snapshot = Arc::new(
1325                Snapshot::from_env(env, Default::default())
1326                    .expect("Failed to create snapshot with default config"),
1327            );
1328            let orig_sandbox = UninitializedSandbox::from_snapshot(
1329                orig_snapshot,
1330                None,
1331                #[cfg(crashdump)]
1332                Some(binary_path.clone()),
1333            )
1334            .expect("Failed to create orig_sandbox");
1335            let mut initialized_sandbox = orig_sandbox
1336                .evolve()
1337                .expect("Failed to evolve orig_sandbox");
1338            let new_snapshot = initialized_sandbox
1339                .snapshot()
1340                .expect("Failed to create new_snapshot");
1341            let new_sandbox = UninitializedSandbox::from_snapshot(
1342                new_snapshot,
1343                None,
1344                #[cfg(crashdump)]
1345                Some(binary_path.clone()),
1346            )
1347            .expect("Failed to create new_sandbox");
1348            let _evolved = new_sandbox.evolve().expect("Failed to evolve new_sandbox");
1349        }
1350    }
1351}