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, 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 #[cfg(crashdump)]
41 pub(crate) entry_point: Option<u64>,
42}
43
44pub struct UninitializedSandbox {
56 pub(crate) host_funcs: Arc<Mutex<FunctionRegistry>>,
58 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 pub(crate) stack_top_gva: u64,
67 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#[derive(Debug)]
82pub enum GuestBinary {
83 Buffer(Vec<u8>),
85 FilePath(PathBuf),
87}
88impl GuestBinary {
89 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#[derive(Debug)]
108pub struct GuestBlob<'a> {
109 pub data: &'a [u8],
111 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#[derive(Debug)]
132pub struct GuestEnvironment<'b> {
133 pub guest_binary: GuestBinary,
135 pub init_data: Option<GuestBlob<'b>>,
137}
138
139impl<'b> GuestEnvironment<'b> {
140 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 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 #[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 #[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 #[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 #[instrument(err(Debug), skip_all, parent = Span::current(), level = "Trace")]
259 pub fn evolve(self) -> Result<Sandbox> {
260 initialize_sandbox(self)
261 }
262
263 #[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 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 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 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 pub fn shared_mem_size(&self) -> usize {
335 self.mgr.shared_mem.mem_size()
336 }
337
338 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 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 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#[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 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 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 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 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 let _sandbox = uninitialized_sandbox.evolve().unwrap();
475
476 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 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 {
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 {
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 {
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 {
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 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 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 let mut test_host_print = TestHostPrint::new();
717
718 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 #[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 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 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 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 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_interest_cache();
896
897 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 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 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 let result = UninitializedSandbox::new(GuestBinary::FilePath(bad_path), None);
919 assert!(result.is_err(), "Sandbox creation should fail");
920
921 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 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 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 #[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 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 let num_calls = TEST_LOGGER.num_log_calls();
1007 assert_eq!(13, num_calls);
1008
1009 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 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 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 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 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_LOGGER.clear_log_calls();
1052 TEST_LOGGER.set_max_level(log::LevelFilter::Info);
1053
1054 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 let num_calls = TEST_LOGGER.num_log_calls();
1064 assert_eq!(2, num_calls);
1065
1066 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 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 {
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 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 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 let _evolved1 = sandbox1.evolve().expect("Failed to evolve sandbox1");
1150 let _evolved2 = sandbox2.evolve().expect("Failed to evolve sandbox2");
1151 }
1152
1153 {
1155 let mut cfg = SandboxConfiguration::default();
1156 cfg.set_heap_size(16 * 1024 * 1024); 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 {
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 {
1201 let mut cfg = SandboxConfiguration::default();
1202 cfg.set_heap_size(32 * 1024 * 1024); cfg.set_scratch_size(512 * 1024); 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 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 {
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 {
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 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 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 {
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 {
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}