1use std::path::Path;
5use std::sync::{Arc, Mutex};
6#[cfg(target_os = "linux")]
7use std::time::Duration;
8
9use hyperlight_common::func::{ParameterTuple, SupportedReturnType};
10use tracing_core::LevelFilter;
11
12use crate::func::HostFunction;
13use crate::mem::memory_region::{MemoryRegion, MemoryRegionFlags};
14use crate::sandbox::SandboxConfiguration;
15#[cfg(gdb)]
16use crate::sandbox::config::DebugInfo;
17#[cfg(target_arch = "x86_64")]
18use crate::sandbox::config::GuestMsrError;
19use crate::sandbox::host_funcs::FunctionEntry;
20use crate::sandbox::snapshot::Snapshot;
21use crate::sandbox::uninitialized::{GuestBlob, GuestEnvironment};
22use crate::{GuestBinary, HostFunctions, Result, Sandbox, UninitializedSandbox, new_error};
23
24enum Source {
26 GuestBinary(GuestBinary),
27 Snapshot(Arc<Snapshot>),
28}
29
30impl Source {
31 fn file(path: impl AsRef<Path>) -> Self {
32 Self::GuestBinary(GuestBinary::FilePath(path.as_ref().to_path_buf()))
33 }
34
35 fn bytes(buffer: impl Into<Vec<u8>>) -> Self {
36 Self::GuestBinary(GuestBinary::Buffer(buffer.into()))
37 }
38}
39
40pub struct SandboxBuilder {
88 source: Source,
89 cfg: SandboxConfiguration,
90 host_funcs: HostFunctions,
91 init_data: Option<(Vec<u8>, MemoryRegionFlags)>,
92 mapped_file_cow: Vec<(std::path::PathBuf, u64)>,
93 mapped_memory_regions: Vec<MemoryRegion>,
94 guest_log_level: Option<LevelFilter>,
95}
96
97impl SandboxBuilder {
98 fn with_source(source: Source) -> Self {
99 Self {
100 source,
101 cfg: SandboxConfiguration::default(),
102 host_funcs: HostFunctions::default(),
103 init_data: None,
104 mapped_file_cow: Vec::new(),
105 mapped_memory_regions: Vec::new(),
106 guest_log_level: None,
107 }
108 }
109
110 pub fn from_file(path: impl AsRef<Path>) -> Self {
112 Self::with_source(Source::file(path))
113 }
114
115 pub fn from_bytes(buffer: impl Into<Vec<u8>>) -> Self {
118 Self::with_source(Source::bytes(buffer))
119 }
120
121 pub fn from_snapshot(snapshot: Arc<Snapshot>) -> Self {
125 Self::with_source(Source::Snapshot(snapshot))
126 }
127
128 pub fn build(self) -> Result<Sandbox> {
135 let Self {
136 source,
137 mut cfg,
138 host_funcs,
139 init_data,
140 mapped_file_cow,
141 mapped_memory_regions,
142 guest_log_level,
143 } = self;
144
145 let mut sandbox = match source {
146 Source::GuestBinary(guest_binary) => {
147 let env = GuestEnvironment {
148 init_data: init_data.as_ref().map(|(data, flags)| GuestBlob {
149 data,
150 permissions: *flags,
151 }),
152 guest_binary,
153 };
154
155 let mut uninitialized_sandbox = UninitializedSandbox::new(env, Some(cfg))?;
156
157 uninitialized_sandbox.host_funcs = Arc::new(Mutex::new(host_funcs.into_inner()));
158
159 for (path, guest_base) in mapped_file_cow {
160 uninitialized_sandbox.map_file_cow(&path, guest_base)?;
161 }
162
163 if let Some(log_level) = guest_log_level {
164 uninitialized_sandbox.set_max_guest_log_level(log_level);
165 }
166
167 uninitialized_sandbox.evolve()?
168 }
169 Source::Snapshot(snapshot) => {
170 if init_data.is_some() {
171 return Err(new_error!(
172 "init_data has no effect when building from a snapshot, as the snapshot already contains it"
173 ));
174 }
175
176 if let Some(log_level) = guest_log_level {
177 cfg.set_max_guest_log_level(log_level);
178 }
179
180 let mut sandbox = Sandbox::from_snapshot(snapshot, host_funcs, Some(cfg))?;
181
182 for (path, guest_base) in mapped_file_cow {
183 sandbox.map_file_cow(&path, guest_base)?;
184 }
185
186 sandbox
187 }
188 };
189
190 for region in mapped_memory_regions {
191 unsafe { sandbox.map_region(®ion)? };
194 }
195
196 Ok(sandbox)
197 }
198}
199
200impl SandboxBuilder {
201 pub fn init_data(mut self, data: impl Into<Vec<u8>>, flags: MemoryRegionFlags) -> Self {
207 self.init_data = Some((data.into(), flags));
208 self
209 }
210
211 pub fn mapped_file_cow(mut self, path: impl AsRef<Path>, guest_base: u64) -> Self {
218 self.mapped_file_cow
219 .push((path.as_ref().to_path_buf(), guest_base));
220 self
221 }
222
223 pub unsafe fn mapped_memory_region(mut self, region: MemoryRegion) -> Self {
234 self.mapped_memory_regions.push(region);
235 self
236 }
237
238 pub fn guest_log_level(mut self, level: LevelFilter) -> Self {
246 self.guest_log_level = Some(level);
247 self
248 }
249
250 pub fn get_guest_log_level(&self) -> Option<LevelFilter> {
252 self.guest_log_level
253 }
254}
255
256impl SandboxBuilder {
257 pub fn host_function<Args: ParameterTuple, Output: SupportedReturnType>(
262 mut self,
263 name: impl AsRef<str>,
264 host_func: impl Into<HostFunction<Output, Args>>,
265 ) -> Self {
266 let func = host_func.into().into();
267 let name = name.as_ref().to_string();
268
269 let entry = FunctionEntry {
270 function: func,
271 parameter_types: Args::TYPE,
272 return_type: Output::TYPE,
273 };
274
275 self.host_funcs
276 .inner_mut()
277 .register_host_function(name, entry);
278 self
279 }
280
281 pub fn host_print(self, print_func: impl Into<HostFunction<i32, (String,)>>) -> Self {
287 self.host_function("HostPrint", print_func)
288 }
289
290 pub fn host_functions(mut self, host_funcs: HostFunctions) -> Self {
297 for (func_name, func_entry) in host_funcs.into_iter() {
298 self.host_funcs
299 .inner_mut()
300 .register_host_function(func_name, func_entry);
301 }
302 self
303 }
304}
305
306impl SandboxBuilder {
307 pub fn heap_size(mut self, size: u64) -> Self {
310 self.cfg.set_heap_size(size);
311 self
312 }
313
314 pub fn get_heap_size(&self) -> u64 {
317 self.cfg.get_heap_size()
318 }
319
320 pub fn scratch_size(mut self, size: usize) -> Self {
322 self.cfg.set_scratch_size(size);
323 self
324 }
325
326 pub fn get_scratch_size(&self) -> usize {
328 self.cfg.get_scratch_size()
329 }
330
331 pub fn g2h_queue_size(mut self, size: usize) -> Self {
335 self.cfg.set_g2h_queue_size(size);
336 self
337 }
338
339 pub fn h2g_queue_size(mut self, size: usize) -> Self {
343 self.cfg.set_h2g_queue_size(size);
344 self
345 }
346
347 pub fn g2h_buffer_size(mut self, size: usize) -> Self {
352 self.cfg.set_g2h_buffer_size(size);
353 self
354 }
355
356 pub fn h2g_buffer_size(mut self, size: usize) -> Self {
361 self.cfg.set_h2g_buffer_size(size);
362 self
363 }
364
365 pub fn g2h_pool_pages(mut self, pages: usize) -> Self {
369 self.cfg.set_g2h_pool_pages(pages);
370 self
371 }
372
373 pub fn h2g_pool_pages(mut self, pages: usize) -> Self {
377 self.cfg.set_h2g_pool_pages(pages);
378 self
379 }
380
381 #[cfg(target_arch = "x86_64")]
393 pub fn guest_msrs(mut self, indices: &[u32]) -> std::result::Result<Self, GuestMsrError> {
394 self.cfg.guest_msrs(indices)?;
395 Ok(self)
396 }
397
398 #[cfg(target_os = "linux")]
400 pub fn interrupt_retry_delay(mut self, delay: Duration) -> Self {
401 self.cfg.set_interrupt_retry_delay(delay);
402 self
403 }
404
405 #[cfg(target_os = "linux")]
407 pub fn get_interrupt_retry_delay(&self) -> Duration {
408 self.cfg.get_interrupt_retry_delay()
409 }
410
411 #[cfg(target_os = "linux")]
418 pub fn interrupt_vcpu_sigrtmin_offset(mut self, offset: u8) -> Result<Self> {
419 self.cfg.set_interrupt_vcpu_sigrtmin_offset(offset)?;
420 Ok(self)
421 }
422
423 #[cfg(target_os = "linux")]
425 pub fn get_interrupt_vcpu_sigrtmin_offset(&self) -> u8 {
426 self.cfg.get_interrupt_vcpu_sigrtmin_offset()
427 }
428
429 #[cfg(crashdump)]
431 pub fn guest_core_dump(mut self, enabled: bool) -> Self {
432 self.cfg.set_guest_core_dump(enabled);
433 self
434 }
435
436 #[cfg(crashdump)]
438 pub fn get_guest_core_dump(&self) -> bool {
439 self.cfg.get_guest_core_dump()
440 }
441
442 #[cfg(gdb)]
444 pub fn guest_debug_info(mut self, debug_info: DebugInfo) -> Self {
445 self.cfg.set_guest_debug_info(debug_info);
446 self
447 }
448
449 #[cfg(gdb)]
451 pub fn get_guest_debug_info(&self) -> Option<DebugInfo> {
452 self.cfg.get_guest_debug_info()
453 }
454}
455
456#[cfg(test)]
457mod tests {
458 use hyperlight_common::vmem::PAGE_SIZE;
459 use hyperlight_testing::simple_guest_as_string;
460 use tracing_core::LevelFilter;
461
462 use super::SandboxBuilder;
463 use crate::mem::memory_region::MemoryRegionFlags;
464
465 #[test]
466 fn transport_settings_are_normalized() {
467 let builder = SandboxBuilder::from_bytes([])
468 .g2h_queue_size(3)
469 .h2g_queue_size(usize::MAX)
470 .g2h_buffer_size(0)
471 .h2g_buffer_size(2 * PAGE_SIZE + 1)
472 .g2h_pool_pages(0)
473 .h2g_pool_pages(0);
474
475 assert_eq!(builder.cfg.get_g2h_queue_size(), 4);
476 assert_eq!(builder.cfg.get_h2g_queue_size(), 32_768);
477 assert_eq!(builder.cfg.get_g2h_buffer_size(), 256);
478 assert_eq!(builder.cfg.get_h2g_buffer_size(), 2 * PAGE_SIZE + 1);
479 assert_eq!(builder.cfg.get_g2h_pool_pages(), 2);
480 assert_eq!(builder.cfg.get_h2g_pool_pages(), 3);
481 }
482
483 #[test]
484 fn transport_buffer_growth_raises_pool_minima() {
485 let builder = SandboxBuilder::from_bytes([])
486 .g2h_pool_pages(0)
487 .h2g_pool_pages(0)
488 .g2h_buffer_size(PAGE_SIZE + 1)
489 .h2g_buffer_size(3 * PAGE_SIZE + 1);
490
491 assert_eq!(builder.cfg.get_g2h_buffer_size(), PAGE_SIZE + 1);
492 assert_eq!(builder.cfg.get_h2g_buffer_size(), 3 * PAGE_SIZE + 1);
493 assert_eq!(builder.cfg.get_g2h_pool_pages(), 3);
494 assert_eq!(builder.cfg.get_h2g_pool_pages(), 4);
495 }
496
497 #[test]
498 fn build_from_file() {
499 let path = simple_guest_as_string().unwrap();
500 let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
501
502 let result = sandbox.call::<String>("Echo", "hello".to_string()).unwrap();
503 assert_eq!(result, "hello");
504 }
505
506 #[test]
507 fn build_from_bytes() {
508 let bytes = std::fs::read(simple_guest_as_string().unwrap()).unwrap();
509 let mut sandbox = SandboxBuilder::from_bytes(bytes).build().unwrap();
510
511 let result = sandbox.call::<String>("Echo", "hello".to_string()).unwrap();
512 assert_eq!(result, "hello");
513 }
514
515 #[test]
516 fn build_from_snapshot() {
517 let path = simple_guest_as_string().unwrap();
518 let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
519 let snapshot = sandbox.snapshot().unwrap();
520
521 let mut restored = SandboxBuilder::from_snapshot(snapshot).build().unwrap();
522
523 let result = restored
524 .call::<String>("Echo", "hello".to_string())
525 .unwrap();
526 assert_eq!(result, "hello");
527 }
528
529 #[test]
530 fn build_from_snapshot_rejects_init_data_and_accepts_guest_log_level() {
531 let path = simple_guest_as_string().unwrap();
532 let mut sandbox = SandboxBuilder::from_file(path).build().unwrap();
533 let snapshot = sandbox.snapshot().unwrap();
534
535 assert!(
536 SandboxBuilder::from_snapshot(snapshot.clone())
537 .init_data([0u8; 8], MemoryRegionFlags::READ)
538 .build()
539 .is_err()
540 );
541
542 assert!(
543 SandboxBuilder::from_snapshot(snapshot)
544 .guest_log_level(LevelFilter::INFO)
545 .build()
546 .is_ok()
547 );
548 }
549}