1use 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;
22use crate::sandbox::SandboxConfiguration;
23use crate::{Result, Sandbox, new_error};
24
25pub struct UninitializedSandbox {
37 pub(crate) host_funcs: Arc<Mutex<FunctionRegistry>>,
39 pub(crate) mgr: SandboxMemoryManager<ExclusiveSharedMemory>,
41 pub(crate) config: SandboxConfiguration,
42 pub(crate) load_info: crate::mem::exe::LoadInfo,
43 pub(crate) stack_top_gva: u64,
46 pub(crate) pending_file_mappings: Vec<super::file_mapping::PreparedFileMapping>,
49}
50
51impl Debug for UninitializedSandbox {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("UninitializedSandbox")
54 .field("memory_layout", &self.mgr.layout)
55 .finish()
56 }
57}
58
59#[derive(Debug)]
61pub enum GuestBinary {
62 Buffer(Vec<u8>),
64 FilePath(PathBuf),
66}
67impl GuestBinary {
68 pub fn canonicalize(&mut self) -> Result<()> {
76 if let GuestBinary::FilePath(p) = self {
77 *p = p
78 .canonicalize()
79 .map_err(|e| new_error!("GuestBinary not found: '{}': {}", p.display(), e))?;
80 }
81 Ok(())
82 }
83}
84
85#[derive(Debug)]
87pub struct GuestBlob<'a> {
88 pub data: &'a [u8],
90 pub permissions: MemoryRegionFlags,
93}
94
95impl<'a> From<&'a [u8]> for GuestBlob<'a> {
96 fn from(data: &'a [u8]) -> Self {
97 GuestBlob {
98 data,
99 permissions: DEFAULT_GUEST_BLOB_MEM_FLAGS,
100 }
101 }
102}
103
104#[derive(Debug)]
111pub struct GuestEnvironment<'b> {
112 pub guest_binary: GuestBinary,
114 pub init_data: Option<GuestBlob<'b>>,
116}
117
118impl<'b> GuestEnvironment<'b> {
119 pub fn new(guest_binary: GuestBinary, init_data: Option<&'b [u8]>) -> Self {
121 GuestEnvironment {
122 guest_binary,
123 init_data: init_data.map(GuestBlob::from),
124 }
125 }
126}
127
128impl From<GuestBinary> for GuestEnvironment<'_> {
129 fn from(guest_binary: GuestBinary) -> Self {
130 GuestEnvironment {
131 guest_binary,
132 init_data: None,
133 }
134 }
135}
136
137impl UninitializedSandbox {
138 fn from_snapshot(snapshot: Arc<Snapshot>, cfg: Option<SandboxConfiguration>) -> Result<Self> {
145 #[cfg(feature = "build-metadata")]
146 log_build_details();
147
148 #[cfg(target_os = "windows")]
150 check_windows_version()?;
151
152 let sandbox_cfg = cfg.unwrap_or_default();
153
154 let mem_mgr_wrapper =
155 SandboxMemoryManager::<ExclusiveSharedMemory>::from_snapshot(snapshot.as_ref())?;
156
157 let host_funcs = Arc::new(Mutex::new(FunctionRegistry::with_default_host_print()));
158
159 let sandbox = Self {
160 host_funcs,
161 mgr: mem_mgr_wrapper,
162 config: sandbox_cfg,
163 load_info: snapshot.load_info(),
164 stack_top_gva: snapshot.stack_top_gva(),
165 pending_file_mappings: Vec::new(),
166 };
167
168 crate::debug!("Sandbox created: {:#?}", sandbox);
169
170 Ok(sandbox)
171 }
172
173 #[instrument(
180 err(Debug),
181 skip(env),
182 parent = Span::current()
183 )]
184 pub fn new<'b>(
185 env: impl Into<GuestEnvironment<'b>>,
186 cfg: Option<SandboxConfiguration>,
187 ) -> Result<Self> {
188 let cfg = cfg.unwrap_or_default();
189 let snapshot = Snapshot::from_env(env, cfg)?;
190 Self::from_snapshot(Arc::new(snapshot), Some(cfg))
191 }
192
193 #[instrument(err(Debug), skip_all, parent = Span::current(), level = "Trace")]
199 pub fn evolve(self) -> Result<Sandbox> {
200 initialize_sandbox(self)
201 }
202
203 #[instrument(err(Debug), skip(self, file_path, guest_base), parent = Span::current())]
218 pub fn map_file_cow(
219 &mut self,
220 file_path: &std::path::Path,
221 guest_base: u64,
222 ) -> crate::Result<u64> {
223 let shared_size = self.mgr.shared_mem.gpa_span_len() as u64;
226 let base_addr = crate::mem::layout::SandboxMemoryLayout::BASE_ADDRESS as u64;
227
228 let prepared = super::file_mapping::prepare_file_cow(file_path, guest_base)?;
229
230 let mapping_end = guest_base
232 .checked_add(prepared.size as u64)
233 .ok_or_else(|| {
234 crate::HyperlightError::Error(format!(
235 "map_file_cow: guest address overflow: {:#x} + {:#x}",
236 guest_base, prepared.size
237 ))
238 })?;
239 let shared_end = base_addr.checked_add(shared_size).ok_or_else(|| {
240 crate::HyperlightError::Error("shared memory end overflow".to_string())
241 })?;
242 if guest_base < shared_end && mapping_end > base_addr {
243 return Err(crate::HyperlightError::Error(format!(
244 "map_file_cow: mapping [{:#x}..{:#x}) overlaps sandbox shared memory [{:#x}..{:#x})",
245 guest_base, mapping_end, base_addr, shared_end,
246 )));
247 }
248
249 let size = prepared.size as u64;
250
251 let new_start = guest_base;
253 let new_end = mapping_end;
254 for existing in &self.pending_file_mappings {
255 let ex_start = existing.guest_base;
256 let ex_end = ex_start.checked_add(existing.size as u64).ok_or_else(|| {
257 crate::HyperlightError::Error(format!(
258 "map_file_cow: existing mapping address overflow: {:#x} + {:#x}",
259 ex_start, existing.size
260 ))
261 })?;
262 if new_start < ex_end && new_end > ex_start {
263 return Err(crate::HyperlightError::Error(format!(
264 "map_file_cow: mapping [{:#x}..{:#x}) overlaps existing mapping [{:#x}..{:#x})",
265 new_start, new_end, ex_start, ex_end,
266 )));
267 }
268 }
269
270 self.pending_file_mappings.push(prepared);
271 Ok(size)
272 }
273
274 pub fn shared_mem_size(&self) -> usize {
279 self.mgr.shared_mem.gpa_span_len()
280 }
281
282 pub fn set_max_guest_log_level(&mut self, log_level: LevelFilter) {
287 self.config.set_max_guest_log_level(log_level);
288 }
289
290 pub fn register<Args: ParameterTuple, Output: SupportedReturnType>(
292 &mut self,
293 name: impl AsRef<str>,
294 host_func: impl Into<HostFunction<Output, Args>>,
295 ) -> Result<()> {
296 register_host_function(host_func, self, name.as_ref())
297 }
298
299 pub fn register_print(
305 &mut self,
306 print_func: impl Into<HostFunction<i32, (String,)>>,
307 ) -> Result<()> {
308 self.register("HostPrint", print_func)
309 }
310}
311#[cfg(target_os = "windows")]
314fn check_windows_version() -> Result<()> {
315 use windows_version::{OsVersion, is_server};
316 const WINDOWS_MAJOR: u32 = 10;
317 const WINDOWS_MINOR: u32 = 0;
318 const WINDOWS_PACK: u32 = 0;
319
320 if is_server() {
322 if OsVersion::current() < OsVersion::new(WINDOWS_MAJOR, WINDOWS_MINOR, WINDOWS_PACK, 20348)
323 {
324 return Err(new_error!(
325 "Hyperlight Requires Windows Server 2022 or newer"
326 ));
327 }
328 } else if OsVersion::current()
329 < OsVersion::new(WINDOWS_MAJOR, WINDOWS_MINOR, WINDOWS_PACK, 22000)
330 {
331 return Err(new_error!("Hyperlight Requires Windows 11 or newer"));
332 }
333 Ok(())
334}
335
336#[cfg(test)]
337mod tests {
338 use std::sync::Arc;
339 use std::sync::mpsc::channel;
340 use std::{fs, thread};
341
342 use crossbeam_queue::ArrayQueue;
343 use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue};
344 use hyperlight_testing::simple_guest_as_pathbuf;
345
346 use crate::sandbox::SandboxConfiguration;
347 use crate::sandbox::uninitialized::{GuestBinary, GuestEnvironment};
348 use crate::{Result, Sandbox, UninitializedSandbox, new_error};
349
350 #[cfg(target_os = "linux")]
351 #[test]
352 fn guest_binary_loads_from_non_utf8_path() {
353 use std::ffi::OsString;
354 use std::os::unix::ffi::OsStringExt;
355
356 let temp_dir = tempfile::tempdir().unwrap();
357 let guest_path = temp_dir
358 .path()
359 .join(OsString::from_vec(b"guest-\xff".to_vec()));
360 fs::copy(simple_guest_as_pathbuf(), &guest_path).unwrap();
361
362 let sandbox = UninitializedSandbox::new(GuestBinary::FilePath(guest_path), None);
363
364 assert!(sandbox.is_ok());
365 }
366
367 #[test]
368 fn test_load_extra_blob() {
369 let binary_path = simple_guest_as_pathbuf();
370 let buffer = [0xde, 0xad, 0xbe, 0xef];
371 let guest_env =
372 GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), Some(&buffer));
373
374 let uninitialized_sandbox = UninitializedSandbox::new(guest_env, None).unwrap();
375 let mut sandbox = uninitialized_sandbox.evolve().unwrap();
376
377 let res = sandbox
378 .call::<Vec<u8>>("ReadFromUserMemory", (4u64, buffer.to_vec()))
379 .expect("Failed to call ReadFromUserMemory");
380
381 assert_eq!(res, buffer.to_vec());
382 }
383
384 #[test]
385 fn test_new_sandbox() {
386 let binary_path = simple_guest_as_pathbuf();
389 let sandbox = UninitializedSandbox::new(GuestBinary::FilePath(binary_path.clone()), None);
390 assert!(sandbox.is_ok());
391
392 let mut binary_path_does_not_exist = binary_path.clone();
395 binary_path_does_not_exist
396 .as_mut_os_string()
397 .push(".nonexistent");
398 let uninitialized_sandbox =
399 UninitializedSandbox::new(GuestBinary::FilePath(binary_path_does_not_exist), None);
400 assert!(uninitialized_sandbox.is_err());
401
402 let cfg = {
404 let mut cfg = SandboxConfiguration::default();
405 cfg.set_scratch_size(SandboxConfiguration::DEFAULT_SCRATCH_SIZE * 2);
406 Some(cfg)
407 };
408
409 let uninitialized_sandbox =
410 UninitializedSandbox::new(GuestBinary::FilePath(binary_path.clone()), cfg);
411 assert!(uninitialized_sandbox.is_ok());
412
413 let uninitialized_sandbox =
414 UninitializedSandbox::new(GuestBinary::FilePath(binary_path), None).unwrap();
415
416 let _sandbox = uninitialized_sandbox.evolve().unwrap();
419
420 let binary_path = simple_guest_as_pathbuf();
423 let sandbox =
424 UninitializedSandbox::new(GuestBinary::Buffer(fs::read(binary_path).unwrap()), None);
425 assert!(sandbox.is_ok());
426
427 let binary_path = simple_guest_as_pathbuf();
430 let mut bytes = fs::read(binary_path).unwrap();
431 let _ = bytes.split_off(100);
432 let sandbox = UninitializedSandbox::new(GuestBinary::Buffer(bytes), None);
433 assert!(sandbox.is_err());
434 }
435
436 #[test]
437 fn test_host_functions() {
438 let uninitialized_sandbox = || {
439 UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
440 .unwrap()
441 };
442
443 {
445 let mut usbox = uninitialized_sandbox();
446
447 usbox.register("test0", |arg: i32| Ok(arg + 1)).unwrap();
448
449 let sandbox: Result<Sandbox> = usbox.evolve();
450 assert!(sandbox.is_ok());
451 let sandbox = sandbox.unwrap();
452
453 let host_funcs = sandbox
454 .host_funcs
455 .try_lock()
456 .map_err(|_| new_error!("Error locking"));
457
458 assert!(host_funcs.is_ok());
459
460 let res = host_funcs
461 .unwrap()
462 .call_host_function("test0", vec![ParameterValue::Int(1)])
463 .unwrap();
464
465 assert_eq!(res, ReturnValue::Int(2));
466 }
467
468 {
470 let mut usbox = uninitialized_sandbox();
471
472 usbox.register("test1", |a: i32, b: i32| Ok(a + b)).unwrap();
473
474 let sandbox: Result<Sandbox> = usbox.evolve();
475 assert!(sandbox.is_ok());
476 let sandbox = sandbox.unwrap();
477
478 let host_funcs = sandbox
479 .host_funcs
480 .try_lock()
481 .map_err(|_| new_error!("Error locking"));
482
483 assert!(host_funcs.is_ok());
484
485 let res = host_funcs
486 .unwrap()
487 .call_host_function(
488 "test1",
489 vec![ParameterValue::Int(1), ParameterValue::Int(2)],
490 )
491 .unwrap();
492
493 assert_eq!(res, ReturnValue::Int(3));
494 }
495
496 {
498 let mut usbox = uninitialized_sandbox();
499
500 usbox
501 .register("test2", |msg: String| {
502 println!("test2 called: {}", msg);
503 Ok(())
504 })
505 .unwrap();
506
507 let sandbox: Result<Sandbox> = usbox.evolve();
508 assert!(sandbox.is_ok());
509 let sandbox = sandbox.unwrap();
510
511 let host_funcs = sandbox
512 .host_funcs
513 .try_lock()
514 .map_err(|_| new_error!("Error locking"));
515
516 assert!(host_funcs.is_ok());
517
518 let res = host_funcs.unwrap().call_host_function("test2", vec![]);
519 assert!(res.is_err());
520 }
521
522 {
524 let usbox = uninitialized_sandbox();
525 let sandbox: Result<Sandbox> = usbox.evolve();
526 assert!(sandbox.is_ok());
527 let sandbox = sandbox.unwrap();
528
529 let host_funcs = sandbox
530 .host_funcs
531 .try_lock()
532 .map_err(|_| new_error!("Error locking"));
533
534 assert!(host_funcs.is_ok());
535
536 let res = host_funcs.unwrap().call_host_function("test4", vec![]);
537 assert!(res.is_err());
538 }
539 }
540
541 #[test]
542 fn test_host_print() {
543 let (tx, rx) = channel();
548
549 let writer = move |msg| {
550 let _ = tx.send(msg);
551 Ok(0)
552 };
553
554 let mut sandbox =
555 UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
556 .expect("Failed to create sandbox");
557
558 sandbox
559 .register_print(writer)
560 .expect("Failed to register host print function");
561
562 let host_funcs = sandbox
563 .host_funcs
564 .try_lock()
565 .map_err(|_| new_error!("Error locking"));
566
567 assert!(host_funcs.is_ok());
568
569 host_funcs.unwrap().host_print("test".to_string()).unwrap();
570
571 drop(sandbox);
572
573 let received_msgs: Vec<_> = rx.into_iter().collect();
574 assert_eq!(received_msgs, ["test"]);
575
576 fn fn_writer(msg: String) -> Result<i32> {
637 assert_eq!(msg, "test2");
638 Ok(0)
639 }
640
641 let mut sandbox =
642 UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
643 .expect("Failed to create sandbox");
644
645 sandbox
646 .register_print(fn_writer)
647 .expect("Failed to register host print function");
648
649 let host_funcs = sandbox
650 .host_funcs
651 .try_lock()
652 .map_err(|_| new_error!("Error locking"));
653
654 assert!(host_funcs.is_ok());
655
656 host_funcs.unwrap().host_print("test2".to_string()).unwrap();
657
658 let mut test_host_print = TestHostPrint::new();
661
662 let writer_closure = move |s| test_host_print.write(s);
665
666 let mut sandbox =
667 UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_as_pathbuf()), None)
668 .expect("Failed to create sandbox");
669
670 sandbox
671 .register_print(writer_closure)
672 .expect("Failed to register host print function");
673
674 let host_funcs = sandbox
675 .host_funcs
676 .try_lock()
677 .map_err(|_| new_error!("Error locking"));
678
679 assert!(host_funcs.is_ok());
680
681 host_funcs.unwrap().host_print("test3".to_string()).unwrap();
682 }
683
684 struct TestHostPrint {}
685
686 impl TestHostPrint {
687 fn new() -> Self {
688 TestHostPrint {}
689 }
690
691 fn write(&mut self, msg: String) -> Result<i32> {
692 assert_eq!(msg, "test3");
693 Ok(0)
694 }
695 }
696
697 #[test]
698 fn check_create_and_use_sandbox_on_different_threads() {
699 let unintializedsandbox_queue = Arc::new(ArrayQueue::<UninitializedSandbox>::new(10));
700 let sandbox_queue = Arc::new(ArrayQueue::<Sandbox>::new(10));
701
702 for i in 0..10 {
703 let simple_guest_path = simple_guest_as_pathbuf();
704 let unintializedsandbox = {
705 let err_string = format!("failed to create UninitializedSandbox {i}");
706 let err_str = err_string.as_str();
707 UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_path), None)
708 .expect(err_str)
709 };
710
711 {
712 let err_string = format!("Failed to push UninitializedSandbox {i}");
713 let err_str = err_string.as_str();
714
715 unintializedsandbox_queue
716 .push(unintializedsandbox)
717 .expect(err_str);
718 }
719 }
720
721 let thread_handles = (0..10)
722 .map(|i| {
723 let uq = unintializedsandbox_queue.clone();
724 let sq = sandbox_queue.clone();
725 thread::spawn(move || {
726 let uninitialized_sandbox = uq.pop().unwrap_or_else(|| {
727 panic!("Failed to pop UninitializedSandbox thread {}", i)
728 });
729
730 let host_funcs = uninitialized_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
738 .unwrap()
739 .host_print(format!("Print from UninitializedSandbox on Thread {}\n", i))
740 .unwrap();
741
742 let sandbox = uninitialized_sandbox.evolve().unwrap_or_else(|_| {
743 panic!("Failed to initialize UninitializedSandbox thread {}", i)
744 });
745
746 sq.push(sandbox).unwrap_or_else(|_| {
747 panic!("Failed to push UninitializedSandbox thread {}", i)
748 })
749 })
750 })
751 .collect::<Vec<_>>();
752
753 for handle in thread_handles {
754 handle.join().unwrap();
755 }
756
757 let thread_handles = (0..10)
758 .map(|i| {
759 let sq = sandbox_queue.clone();
760 thread::spawn(move || {
761 let sandbox = sq
762 .pop()
763 .unwrap_or_else(|| panic!("Failed to pop Sandbox thread {}", i));
764
765 let host_funcs = sandbox
766 .host_funcs
767 .try_lock()
768 .map_err(|_| new_error!("Error locking"));
769
770 assert!(host_funcs.is_ok());
771
772 host_funcs
773 .unwrap()
774 .host_print(format!("Print from Sandbox on Thread {}\n", i))
775 .unwrap();
776 })
777 })
778 .collect::<Vec<_>>();
779
780 for handle in thread_handles {
781 handle.join().unwrap();
782 }
783 }
784
785 #[test]
801 #[cfg(feature = "build-metadata")]
802 fn test_trace_trace() {
803 use hyperlight_testing::tracing_subscriber::TracingSubscriber;
804 use tracing::Level;
805 use tracing_core::Subscriber;
806 use tracing_core::callsite::rebuild_interest_cache;
807 use uuid::Uuid;
808
809 fn get_span_attr<'a>(span: &'a serde_json::Value, key: &str) -> Option<&'a str> {
811 span.get("span")?.get("attributes")?.get(key)?.as_str()
812 }
813
814 fn get_event_field<'a>(event: &'a serde_json::Value, field: &str) -> Option<&'a str> {
816 event.get("event")?.get(field)?.as_str()
817 }
818
819 fn get_event_metadata<'a>(event: &'a serde_json::Value, field: &str) -> Option<&'a str> {
821 event.get("event")?.get("metadata")?.get(field)?.as_str()
822 }
823
824 let subscriber = TracingSubscriber::new(Level::TRACE);
825
826 tracing::subscriber::with_default(subscriber.clone(), || {
827 let mut bad_path = simple_guest_as_pathbuf();
832 bad_path.as_mut_os_string().push("does_not_exist");
833 let _ = UninitializedSandbox::new(GuestBinary::FilePath(bad_path.clone()), None);
834
835 rebuild_interest_cache();
840
841 subscriber.clear();
843
844 let correlation_id = Uuid::new_v4().to_string();
845 let _span = tracing::error_span!("test_trace_logs", %correlation_id).entered();
846
847 let (test_span_id, span_meta) = subscriber
849 .current_span()
850 .into_inner()
851 .expect("Should be inside a span");
852 assert_eq!(span_meta.name(), "test_trace_logs");
853
854 let span_data = subscriber.get_span(test_span_id.into_u64());
856 let recorded_id =
857 get_span_attr(&span_data, "correlation_id").expect("correlation_id not found");
858 assert_eq!(recorded_id, correlation_id);
859
860 let result = UninitializedSandbox::new(GuestBinary::FilePath(bad_path), None);
863 assert!(result.is_err(), "Sandbox creation should fail");
864
865 let (current_id, _) = subscriber
867 .current_span()
868 .into_inner()
869 .expect("Should still be inside a span");
870 assert_eq!(
871 current_id.into_u64(),
872 test_span_id.into_u64(),
873 "Should still be in the test span"
874 );
875
876 let all_spans = subscriber.get_all_spans();
879 let _new_span_entry = all_spans
880 .iter()
881 .find(|&(&id, _)| {
882 id != test_span_id.into_u64()
883 && subscriber.get_span_metadata(id).name() == "new"
884 })
885 .expect("Expected a span named 'new' from UninitializedSandbox::new");
886
887 let events = subscriber.get_events();
889 assert_eq!(events.len(), 1, "Expected exactly one error event");
890
891 let event = &events[0];
892 let level = get_event_metadata(event, "level").expect("event should have level");
893 let error = get_event_field(event, "error").expect("event should have error field");
894 let target = get_event_metadata(event, "target").expect("event should have target");
895 let module_path =
896 get_event_metadata(event, "module_path").expect("event should have module_path");
897
898 assert_eq!(level, "ERROR");
899 assert!(
900 error.contains("GuestBinary not found"),
901 "Error should mention 'GuestBinary not found', got: {error}"
902 );
903 assert_eq!(target, "hyperlight_host::sandbox::uninitialized");
904 assert_eq!(module_path, "hyperlight_host::sandbox::uninitialized");
905 });
906 }
907
908 #[test]
909 #[ignore]
910 #[cfg(feature = "build-metadata")]
913 fn test_log_trace() {
914 use std::path::PathBuf;
915
916 use hyperlight_testing::logger::{LOGGER as TEST_LOGGER, Logger as TestLogger};
917 use log::Level;
918 use tracing_core::callsite::rebuild_interest_cache;
919
920 {
921 TestLogger::initialize_test_logger();
922 TEST_LOGGER.set_max_level(log::LevelFilter::Trace);
923
924 rebuild_interest_cache();
928
929 let mut invalid_binary_path = simple_guest_as_pathbuf();
930 invalid_binary_path
931 .as_mut_os_string()
932 .push("does_not_exist");
933
934 let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_binary_path), None);
935 assert!(sbox.is_err());
936
937 let num_calls = TEST_LOGGER.num_log_calls();
951 assert_eq!(13, num_calls);
952
953 let logcall = TEST_LOGGER.get_log_call(0).unwrap();
956 assert_eq!(Level::Info, logcall.level);
957
958 assert!(logcall.args.starts_with("new; cfg"));
959 assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
960
961 let logcall = TEST_LOGGER.get_log_call(1).unwrap();
964 assert_eq!(Level::Trace, logcall.level);
965 assert_eq!(logcall.args, "-> new;");
966 assert_eq!("tracing::span::active", logcall.target);
967
968 let logcall = TEST_LOGGER.get_log_call(10).unwrap();
971 assert_eq!(Level::Error, logcall.level);
972 assert!(
973 logcall
974 .args
975 .starts_with("error=Error(\"GuestBinary not found:")
976 );
977 assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
978
979 let logcall = TEST_LOGGER.get_log_call(11).unwrap();
982 assert_eq!(Level::Trace, logcall.level);
983 assert_eq!(logcall.args, "<- new;");
984 assert_eq!("tracing::span::active", logcall.target);
985
986 let logcall = TEST_LOGGER.get_log_call(12).unwrap();
989 assert_eq!(Level::Trace, logcall.level);
990 assert_eq!(logcall.args, "-- new;");
991 assert_eq!("tracing::span", logcall.target);
992 }
993 {
994 TEST_LOGGER.clear_log_calls();
996 TEST_LOGGER.set_max_level(log::LevelFilter::Info);
997
998 let mut invalid_binary_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1000 invalid_binary_path.push("Cargo.toml");
1001
1002 let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_binary_path), None);
1003 assert!(sbox.is_err());
1004
1005 let num_calls = TEST_LOGGER.num_log_calls();
1008 assert_eq!(2, num_calls);
1009
1010 let logcall = TEST_LOGGER.get_log_call(0).unwrap();
1013 assert_eq!(Level::Info, logcall.level);
1014
1015 assert!(logcall.args.starts_with("new; cfg"));
1016 assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
1017
1018 let logcall = TEST_LOGGER.get_log_call(1).unwrap();
1021 assert_eq!(Level::Error, logcall.level);
1022 assert!(logcall.args.starts_with("error=PEFileProcessingFailure"));
1023 assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
1024 }
1025 {
1026 TEST_LOGGER.clear_log_calls();
1027 TEST_LOGGER.set_max_level(log::LevelFilter::Error);
1028
1029 let sbox = {
1030 let res = UninitializedSandbox::new(
1031 GuestBinary::FilePath(simple_guest_as_pathbuf()),
1032 None,
1033 );
1034 res.unwrap()
1035 };
1036 let _: Result<Sandbox> = sbox.evolve();
1037
1038 let num_calls = TEST_LOGGER.num_log_calls();
1039
1040 assert_eq!(0, num_calls);
1041 }
1042 }
1043
1044 #[test]
1045 fn test_invalid_path() {
1046 let invalid_path = "some/path/that/does/not/exist";
1047 let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_path.into()), None);
1048 println!("{:?}", sbox);
1049 #[cfg(target_os = "windows")]
1050 assert!(
1051 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)"))
1052 );
1053 #[cfg(target_os = "linux")]
1054 assert!(
1055 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)"))
1056 );
1057 }
1058
1059 #[test]
1060 fn test_from_snapshot_various_configurations() {
1061 use crate::sandbox::snapshot::Snapshot;
1062
1063 let binary_path = simple_guest_as_pathbuf();
1064
1065 {
1067 let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1068
1069 let snapshot = Arc::new(
1070 Snapshot::from_env(env, Default::default())
1071 .expect("Failed to create snapshot with default config"),
1072 );
1073
1074 let sandbox1 = UninitializedSandbox::from_snapshot(snapshot.clone(), None)
1076 .expect("Failed to create first sandbox from snapshot");
1077
1078 let sandbox2 = UninitializedSandbox::from_snapshot(snapshot.clone(), None)
1080 .expect("Failed to create second sandbox from snapshot");
1081
1082 let _evolved1 = sandbox1.evolve().expect("Failed to evolve sandbox1");
1084 let _evolved2 = sandbox2.evolve().expect("Failed to evolve sandbox2");
1085 }
1086
1087 {
1089 let mut cfg = SandboxConfiguration::default();
1090 cfg.set_scratch_size(SandboxConfiguration::DEFAULT_SCRATCH_SIZE + 64 * 1024);
1091
1092 let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1093
1094 let snapshot = Arc::new(
1095 Snapshot::from_env(env, cfg)
1096 .expect("Failed to create snapshot with custom stack size"),
1097 );
1098
1099 let sandbox = UninitializedSandbox::from_snapshot(snapshot, None)
1100 .expect("Failed to create sandbox from snapshot with custom stack");
1101
1102 let _evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1103 }
1104
1105 {
1107 let mut cfg = SandboxConfiguration::default();
1108 cfg.set_scratch_size(512 * 1024); let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1111
1112 let snapshot = Arc::new(
1113 Snapshot::from_env(env, cfg)
1114 .expect("Failed to create snapshot with all custom settings"),
1115 );
1116
1117 let sandbox1 = UninitializedSandbox::from_snapshot(snapshot.clone(), None)
1119 .expect("Failed to create sandbox1 from fully customized snapshot");
1120 let sandbox2 = UninitializedSandbox::from_snapshot(snapshot.clone(), None)
1121 .expect("Failed to create sandbox2 from fully customized snapshot");
1122 let sandbox3 = UninitializedSandbox::from_snapshot(snapshot.clone(), None)
1123 .expect("Failed to create sandbox3 from fully customized snapshot");
1124
1125 let _evolved1 = sandbox1.evolve().expect("Failed to evolve sandbox1");
1126 let _evolved2 = sandbox2.evolve().expect("Failed to evolve sandbox2");
1127 let _evolved3 = sandbox3.evolve().expect("Failed to evolve sandbox3");
1128 }
1129
1130 {
1132 let binary_bytes = fs::read(&binary_path).expect("Failed to read binary file");
1133
1134 let snapshot = Arc::new(
1135 Snapshot::from_env(GuestBinary::Buffer(binary_bytes), Default::default())
1136 .expect("Failed to create snapshot from buffer"),
1137 );
1138
1139 let sandbox = UninitializedSandbox::from_snapshot(snapshot, None)
1140 .expect("Failed to create sandbox from buffer-based snapshot");
1141
1142 let _evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1143 }
1144
1145 {
1147 let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1148
1149 let snapshot = Arc::new(
1150 Snapshot::from_env(env, Default::default()).expect("Failed to create snapshot"),
1151 );
1152
1153 let mut sandbox = UninitializedSandbox::from_snapshot(snapshot, None)
1154 .expect("Failed to create sandbox from snapshot");
1155
1156 sandbox
1158 .register("CustomAdd", |a: i32, b: i32| Ok(a + b))
1159 .expect("Failed to register custom function");
1160
1161 let evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1162
1163 let host_funcs = evolved
1165 .host_funcs
1166 .try_lock()
1167 .expect("Failed to lock host funcs");
1168
1169 let result = host_funcs
1170 .call_host_function(
1171 "CustomAdd",
1172 vec![ParameterValue::Int(10), ParameterValue::Int(20)],
1173 )
1174 .expect("Failed to call CustomAdd");
1175
1176 assert_eq!(result, ReturnValue::Int(30));
1177 }
1178
1179 {
1181 let init_data = [0xCA, 0xFE, 0xBA, 0xBE];
1182 let guest_env =
1183 GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), Some(&init_data));
1184
1185 let snapshot = Arc::new(
1186 Snapshot::from_env(guest_env, Default::default())
1187 .expect("Failed to create snapshot with init data"),
1188 );
1189
1190 let sandbox = UninitializedSandbox::from_snapshot(snapshot, None)
1191 .expect("Failed to create sandbox from snapshot with init data");
1192
1193 let _evolved = sandbox.evolve().expect("Failed to evolve sandbox");
1194 }
1195
1196 {
1198 let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
1199 let orig_snapshot = Arc::new(
1200 Snapshot::from_env(env, Default::default())
1201 .expect("Failed to create snapshot with default config"),
1202 );
1203 let orig_sandbox = UninitializedSandbox::from_snapshot(orig_snapshot, None)
1204 .expect("Failed to create orig_sandbox");
1205 let mut initialized_sandbox = orig_sandbox
1206 .evolve()
1207 .expect("Failed to evolve orig_sandbox");
1208 let new_snapshot = initialized_sandbox
1209 .snapshot()
1210 .expect("Failed to create new_snapshot");
1211 let new_sandbox = UninitializedSandbox::from_snapshot(new_snapshot, None)
1212 .expect("Failed to create new_sandbox");
1213 let _evolved = new_sandbox.evolve().expect("Failed to evolve new_sandbox");
1214 }
1215 }
1216}