hyperlight-host 0.18.0

A lightweight Virtual Machine Manager that can be hosted in an application to safely run untrusted or code within a VM partition with very low latency and overhead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025 The Hyperlight Authors.

use std::cmp::max;
use std::time::Duration;

use hyperlight_common::log_level::GuestLogFilter;
use hyperlight_common::virtq::G2H_LOWER_SLOT_SIZE;
use hyperlight_common::vmem::PAGE_SIZE;
#[cfg(target_os = "linux")]
use libc::c_int;
use tracing::{Span, instrument};
use tracing_core::LevelFilter;

/// Used for passing debug configuration to a sandbox
#[cfg(gdb)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct DebugInfo {
    /// Guest debug port
    pub port: u16,
}

/// Errors returned when declaring guest MSRs.
#[cfg(target_arch = "x86_64")]
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum GuestMsrError {
    /// The declared MSR set exceeds its fixed capacity.
    #[error("declared guest MSRs exceed the maximum of {maximum} distinct entries")]
    CapacityExceeded {
        /// Maximum number of distinct declared MSRs.
        maximum: usize,
    },
}

/// The complete set of configuration needed to create a Sandbox
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(C)]
pub struct SandboxConfiguration {
    /// Guest core dump output directory
    /// This field is by default set to true which means the value core dumps will be placed in:
    /// - HYPERLIGHT_CORE_DUMP_DIR environment variable if it is set
    /// - default value of the temporary directory
    ///
    /// The core dump files generation can be disabled by setting this field to false.
    #[cfg(crashdump)]
    guest_core_dump: bool,
    /// Guest gdb debug port
    #[cfg(gdb)]
    guest_debug_info: Option<DebugInfo>,
    /// The heap size to use in the guest sandbox. If set to 0, the heap
    /// size will be determined from the PE file header
    ///
    /// Note: this is a C-compatible struct, so even though this optional
    /// field should be represented as an `Option`, that type is not
    /// FFI-safe, so it cannot be.
    heap_size_override: u64,
    /// Delay between interrupt retries. This duration specifies how long to wait
    /// between attempts to send signals to the thread running the sandbox's VCPU.
    /// Multiple retries may be necessary because signals only interrupt the VCPU
    /// thread when the vcpu thread is in kernel space. There's a narrow window during which a
    /// signal can be delivered to the thread, but the thread may not yet
    /// have entered kernel space.
    interrupt_retry_delay: Duration,
    /// Offset from `SIGRTMIN` used to determine the signal number for interrupting
    /// the VCPU thread. The actual signal sent is `SIGRTMIN + interrupt_vcpu_sigrtmin_offset`.
    ///
    /// This signal must fall within the valid real-time signal range supported by the host.
    ///
    /// Note: Since real-time signals can vary across platforms, ensure that the offset
    /// results in a signal number that is not already in use by other components of the system.
    interrupt_vcpu_sigrtmin_offset: u8,
    /// How much writable memory to offer the guest
    scratch_size: usize,
    /// The maximum log level enabled for guest code execution.
    ///
    /// If unset, the level is determined from the `RUST_LOG` environment
    /// variable, defaulting to [`LevelFilter::ERROR`] when no level is found.
    /// Stored as the guest ABI's numeric log-filter value, with `u64::MAX`
    /// representing an unset value, to keep this `#[repr(C)]` struct FFI-safe.
    max_guest_log_level: u64,
    /// Number of descriptors in the G2H virtqueue.
    g2h_queue_size: usize,
    /// Number of descriptors in the H2G virtqueue.
    h2g_queue_size: usize,
    /// Capacity of each G2H upper-tier buffer.
    g2h_buffer_size: usize,
    /// Capacity of each H2G buffer.
    h2g_buffer_size: usize,
    /// Number of pages in the G2H buffer pool.
    g2h_pool_pages: usize,
    /// Number of pages in the H2G buffer pool.
    h2g_pool_pages: usize,
    /// Declared guest MSRs, stored inline to keep this type `Copy`.
    #[cfg(target_arch = "x86_64")]
    guest_msrs: [u32; Self::MAX_GUEST_MSRS],
    /// Number of valid entries in `guest_msrs`.
    #[cfg(target_arch = "x86_64")]
    guest_msrs_count: usize,
}

impl SandboxConfiguration {
    /// The default interrupt retry delay
    pub const DEFAULT_INTERRUPT_RETRY_DELAY: Duration = Duration::from_micros(500);
    /// The default signal offset from `SIGRTMIN` used to determine the signal number for interrupting
    pub const INTERRUPT_VCPU_SIGRTMIN_OFFSET: u8 = 0;
    /// The default heap size of a hyperlight sandbox
    pub const DEFAULT_HEAP_SIZE: u64 = 131072;
    /// Scratch backs the default heap, transport pools, page tables, and exception stack.
    /// The size is 16 KiB aligned for macOS hosts.
    /// TODO: revisit when https://github.com/hyperlight-dev/hyperlight/issues/1925 is fixed
    pub const DEFAULT_SCRATCH_SIZE: usize = 0x64000;
    /// The default G2H virtqueue descriptor count.
    pub const DEFAULT_G2H_QUEUE_SIZE: usize = 64;
    /// The default H2G virtqueue descriptor count.
    pub const DEFAULT_H2G_QUEUE_SIZE: usize = 32;
    /// The default G2H upper-tier buffer size.
    pub const DEFAULT_G2H_BUFFER_SIZE: usize = PAGE_SIZE;
    /// The default H2G buffer size.
    pub const DEFAULT_H2G_BUFFER_SIZE: usize = PAGE_SIZE;
    /// The default total number of G2H pool pages.
    pub const DEFAULT_G2H_POOL_PAGES: usize = 12;
    /// The default total number of H2G pool pages.
    pub const DEFAULT_H2G_POOL_PAGES: usize = 8;
    /// The minimum G2H virtqueue descriptor count.
    const MIN_QUEUE_SIZE: usize = 2;
    /// The maximum G2H virtqueue descriptor count.
    const MAX_QUEUE_SIZE: usize = 32_768;
    /// The minimum configured transport buffer size.
    const MIN_BUFFER_SIZE: usize = G2H_LOWER_SLOT_SIZE;
    /// The maximum configured transport buffer size.
    const MAX_BUFFER_SIZE: usize = u32::MAX as usize;
    /// Maximum number of distinct guest MSRs that can be declared.
    /// KVM supports at most 16 MSR filter ranges. Each index may require its
    /// own range, so 16 is the portable limit across backends.
    #[cfg(target_arch = "x86_64")]
    pub const MAX_GUEST_MSRS: usize = 16;
    const MAX_GUEST_LOG_LEVEL_UNSET: u64 = u64::MAX;

    /// Create a new configuration for a sandbox with the given sizes.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    fn new(
        heap_size_override: Option<u64>,
        scratch_size: usize,
        interrupt_retry_delay: Duration,
        interrupt_vcpu_sigrtmin_offset: u8,
        #[cfg(gdb)] guest_debug_info: Option<DebugInfo>,
        #[cfg(crashdump)] guest_core_dump: bool,
    ) -> Self {
        Self {
            heap_size_override: heap_size_override.unwrap_or(0),
            scratch_size,
            max_guest_log_level: Self::MAX_GUEST_LOG_LEVEL_UNSET,
            g2h_queue_size: Self::DEFAULT_G2H_QUEUE_SIZE,
            h2g_queue_size: Self::DEFAULT_H2G_QUEUE_SIZE,
            g2h_buffer_size: Self::DEFAULT_G2H_BUFFER_SIZE,
            h2g_buffer_size: Self::DEFAULT_H2G_BUFFER_SIZE,
            g2h_pool_pages: Self::DEFAULT_G2H_POOL_PAGES,
            h2g_pool_pages: Self::DEFAULT_H2G_POOL_PAGES,
            interrupt_retry_delay,
            interrupt_vcpu_sigrtmin_offset,
            #[cfg(gdb)]
            guest_debug_info,
            #[cfg(crashdump)]
            guest_core_dump,
            #[cfg(target_arch = "x86_64")]
            guest_msrs: [0; Self::MAX_GUEST_MSRS],
            #[cfg(target_arch = "x86_64")]
            guest_msrs_count: 0,
        }
    }

    /// Set the heap size to use in the guest sandbox. If set to 0, the heap size will be determined from the PE file header
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_heap_size(&mut self, heap_size: u64) {
        self.heap_size_override = heap_size;
    }

    /// Sets the interrupt retry delay
    #[cfg(any(kvm, mshv3, hvf))]
    pub fn set_interrupt_retry_delay(&mut self, delay: Duration) {
        self.interrupt_retry_delay = delay;
    }

    /// Get the delay between retries for interrupts
    #[cfg(any(kvm, mshv3, hvf))]
    pub fn get_interrupt_retry_delay(&self) -> Duration {
        self.interrupt_retry_delay
    }

    /// Get the signal offset from `SIGRTMIN` used to determine the signal number for interrupting the VCPU thread
    #[cfg(target_os = "linux")]
    pub fn get_interrupt_vcpu_sigrtmin_offset(&self) -> u8 {
        self.interrupt_vcpu_sigrtmin_offset
    }

    /// Declares the MSRs the guest depends on.
    ///
    /// A declared MSR's value is part of the sandbox's saved state: captured by
    /// [`Sandbox::snapshot`](crate::Sandbox::snapshot) and written
    /// back on [`Sandbox::restore`](crate::Sandbox::restore). Every
    /// MSR you do not declare is reset to a clean default on each restore.
    ///
    /// If this method is not called, only a small core of essential CPU state
    /// (kernel GS base, TSC) is saved and restored.
    ///
    /// # Platform-specific behavior
    ///
    /// * On KVM, declaring an MSR is also what lets the guest access it. The
    ///   guest faults on any `RDMSR`/`WRMSR` of an undeclared MSR.
    /// * On MSHV and WHP there is no such enforcement, so declaration only
    ///   controls what is saved and restored, not what the guest may touch.
    ///
    /// Duplicate indices, within the slice or against the existing set, are
    /// ignored and do not count toward capacity.
    ///
    /// # Errors
    ///
    /// Returns [`GuestMsrError::CapacityExceeded`] if the distinct entries
    /// would exceed [`Self::MAX_GUEST_MSRS`]. The declared set is unchanged on
    /// error.
    #[cfg(target_arch = "x86_64")]
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn guest_msrs(&mut self, indices: &[u32]) -> Result<&mut Self, GuestMsrError> {
        let additional = indices
            .iter()
            .enumerate()
            .filter(|(position, index)| {
                !self.guest_msrs[..self.guest_msrs_count].contains(index)
                    && !indices[..*position].contains(index)
            })
            .count();
        if additional > Self::MAX_GUEST_MSRS - self.guest_msrs_count {
            return Err(GuestMsrError::CapacityExceeded {
                maximum: Self::MAX_GUEST_MSRS,
            });
        }
        for &index in indices {
            if !self.guest_msrs[..self.guest_msrs_count].contains(&index) {
                self.guest_msrs[self.guest_msrs_count] = index;
                self.guest_msrs_count += 1;
            }
        }
        Ok(self)
    }

    /// Returns the declared guest MSRs.
    #[cfg(target_arch = "x86_64")]
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn get_guest_msrs(&self) -> &[u32] {
        &self.guest_msrs[..self.guest_msrs_count]
    }

    /// Sets the offset from `SIGRTMIN` to determine the real-time signal used for
    /// interrupting the VCPU thread.
    ///
    /// The final signal number is computed as `SIGRTMIN + offset`, and it must fall within
    /// the valid range of real-time signals supported by the host system.
    ///
    /// Returns Ok(()) if the offset is valid, or an error if it exceeds the maximum real-time signal number.
    #[cfg(target_os = "linux")]
    pub fn set_interrupt_vcpu_sigrtmin_offset(&mut self, offset: u8) -> crate::Result<()> {
        if libc::SIGRTMIN() + offset as c_int > libc::SIGRTMAX() {
            return Err(crate::new_error!(
                "Invalid SIGRTMIN offset: {}. It exceeds the maximum real-time signal number.",
                offset
            ));
        }
        self.interrupt_vcpu_sigrtmin_offset = offset;
        Ok(())
    }

    /// Toggles the guest core dump generation for a sandbox
    /// Setting this to false disables the core dump generation
    /// This is only used when the `crashdump` feature is enabled
    #[cfg(crashdump)]
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_guest_core_dump(&mut self, enable: bool) {
        self.guest_core_dump = enable;
    }

    /// Sets the configuration for the guest debug
    #[cfg(gdb)]
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_guest_debug_info(&mut self, debug_info: DebugInfo) {
        self.guest_debug_info = Some(debug_info);
    }

    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn get_scratch_size(&self) -> usize {
        self.scratch_size
    }

    /// Set the size of the scratch regiong
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_scratch_size(&mut self, scratch_size: usize) {
        self.scratch_size = scratch_size;
    }

    /// Sets the maximum log level for guest code execution.
    ///
    /// If not set, the level is determined from the `RUST_LOG` environment
    /// variable, defaulting to [`LevelFilter::ERROR`] when no level is found.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_max_guest_log_level(&mut self, log_level: LevelFilter) {
        self.max_guest_log_level = GuestLogFilter::from(log_level).into();
    }

    pub(crate) fn get_max_guest_log_level(&self) -> Option<LevelFilter> {
        if self.max_guest_log_level == Self::MAX_GUEST_LOG_LEVEL_UNSET {
            None
        } else {
            GuestLogFilter::try_from(self.max_guest_log_level)
                .ok()
                .map(Into::into)
        }
    }

    /// Get the G2H virtqueue descriptor count.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn get_g2h_queue_size(&self) -> usize {
        self.g2h_queue_size
    }

    /// Set the G2H virtqueue descriptor count.
    ///
    /// Values are rounded up to a power of two in `2..=32768`.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_g2h_queue_size(&mut self, size: usize) {
        self.g2h_queue_size = Self::normalize_queue_size(size);
    }

    /// Get the H2G virtqueue descriptor count.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn get_h2g_queue_size(&self) -> usize {
        self.h2g_queue_size
    }

    /// Set the H2G virtqueue descriptor count.
    ///
    /// Values are rounded up to a power of two in `2..=32768`.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_h2g_queue_size(&mut self, size: usize) {
        self.h2g_queue_size = Self::normalize_queue_size(size);
    }

    /// Get the capacity of each G2H upper-tier buffer.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn get_g2h_buffer_size(&self) -> usize {
        self.g2h_buffer_size
    }

    /// Set the capacity of each G2H upper-tier buffer.
    ///
    /// Values are clamped to `256..=u32::MAX`.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_g2h_buffer_size(&mut self, size: usize) {
        self.g2h_buffer_size = size.clamp(Self::MIN_BUFFER_SIZE, Self::MAX_BUFFER_SIZE);
        self.g2h_pool_pages = max(
            self.g2h_pool_pages,
            Self::min_g2h_pool_pages(self.g2h_buffer_size),
        );
    }

    /// Get the capacity of each H2G buffer.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn get_h2g_buffer_size(&self) -> usize {
        self.h2g_buffer_size
    }

    /// Set the capacity of each H2G buffer.
    ///
    /// Values are clamped to `256..=u32::MAX`.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_h2g_buffer_size(&mut self, size: usize) {
        self.h2g_buffer_size = size.clamp(Self::MIN_BUFFER_SIZE, Self::MAX_BUFFER_SIZE);
        self.h2g_pool_pages = max(
            self.h2g_pool_pages,
            Self::min_h2g_pool_pages(self.h2g_buffer_size),
        );
    }

    /// Get the total number of G2H pool pages.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn get_g2h_pool_pages(&self) -> usize {
        self.g2h_pool_pages
    }

    /// Set the total number of G2H pool pages.
    ///
    /// The pool contains one lower-tier page and at least one upper buffer.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_g2h_pool_pages(&mut self, pages: usize) {
        self.g2h_pool_pages = max(pages, Self::min_g2h_pool_pages(self.g2h_buffer_size));
    }

    /// Get the total number of H2G pool pages.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn get_h2g_pool_pages(&self) -> usize {
        self.h2g_pool_pages
    }

    /// Set the total number of H2G pool pages.
    ///
    /// The pool contains at least one H2G buffer.
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub fn set_h2g_pool_pages(&mut self, pages: usize) {
        self.h2g_pool_pages = max(pages, Self::min_h2g_pool_pages(self.h2g_buffer_size));
    }

    #[cfg(crashdump)]
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn get_guest_core_dump(&self) -> bool {
        self.guest_core_dump
    }

    #[cfg(gdb)]
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn get_guest_debug_info(&self) -> Option<DebugInfo> {
        self.guest_debug_info
    }

    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    fn heap_size_override_opt(&self) -> Option<u64> {
        (self.heap_size_override > 0).then_some(self.heap_size_override)
    }

    /// If self.heap_size_override is non-zero, return it. Otherwise,
    /// return exe_info.heap_reserve()
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn get_heap_size(&self) -> u64 {
        self.heap_size_override_opt()
            .unwrap_or(Self::DEFAULT_HEAP_SIZE)
    }

    fn normalize_queue_size(size: usize) -> usize {
        size.clamp(Self::MIN_QUEUE_SIZE, Self::MAX_QUEUE_SIZE)
            .next_power_of_two()
    }

    fn min_g2h_pool_pages(buffer_size: usize) -> usize {
        1 + Self::min_h2g_pool_pages(buffer_size)
    }

    fn min_h2g_pool_pages(buffer_size: usize) -> usize {
        buffer_size.div_ceil(PAGE_SIZE)
    }
}

impl Default for SandboxConfiguration {
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    fn default() -> Self {
        Self::new(
            None,
            Self::DEFAULT_SCRATCH_SIZE,
            Self::DEFAULT_INTERRUPT_RETRY_DELAY,
            Self::INTERRUPT_VCPU_SIGRTMIN_OFFSET,
            #[cfg(gdb)]
            None,
            #[cfg(crashdump)]
            true,
        )
    }
}

#[cfg(test)]
mod tests {
    use hyperlight_common::vmem::PAGE_SIZE;
    use tracing_core::LevelFilter;

    #[cfg(target_arch = "x86_64")]
    use super::GuestMsrError;
    use super::SandboxConfiguration;

    #[test]
    fn max_guest_log_level_defaults_to_none_and_round_trips_all_levels() {
        let mut cfg = SandboxConfiguration::default();
        assert_eq!(cfg.get_max_guest_log_level(), None);

        for level in [
            LevelFilter::OFF,
            LevelFilter::ERROR,
            LevelFilter::WARN,
            LevelFilter::INFO,
            LevelFilter::DEBUG,
            LevelFilter::TRACE,
        ] {
            cfg.set_max_guest_log_level(level);
            assert_eq!(cfg.get_max_guest_log_level(), Some(level));
        }
    }

    #[test]
    fn default_scratch_size_supports_16k_pages() {
        let cfg = SandboxConfiguration::default();
        assert!(cfg.get_scratch_size().is_multiple_of(16 * 1024));
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn guest_msrs_reports_overflow() {
        let mut cfg = SandboxConfiguration::default();
        for index in 0..SandboxConfiguration::MAX_GUEST_MSRS as u32 {
            cfg.guest_msrs(&[index]).unwrap();
        }

        cfg.guest_msrs(&[0]).unwrap();
        assert_eq!(
            cfg.guest_msrs(&[SandboxConfiguration::MAX_GUEST_MSRS as u32]),
            Err(GuestMsrError::CapacityExceeded {
                maximum: SandboxConfiguration::MAX_GUEST_MSRS,
            })
        );
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn bulk_guest_msrs_overflow_is_atomic() {
        let mut cfg = SandboxConfiguration::default();
        cfg.guest_msrs(&[1, 2]).unwrap();
        let oversized: Vec<u32> = (3..=SandboxConfiguration::MAX_GUEST_MSRS as u32 + 1).collect();

        assert!(matches!(
            cfg.guest_msrs(&oversized),
            Err(GuestMsrError::CapacityExceeded { .. })
        ));
        assert_eq!(cfg.get_guest_msrs(), &[1, 2]);
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn guest_msrs_dedups_and_preserves_order() {
        let mut cfg = SandboxConfiguration::default();
        cfg.guest_msrs(&[0x10]).unwrap();
        cfg.guest_msrs(&[0x20, 0x20, 0x10, 0x30, 0x20]).unwrap();
        // 0x10 already present, 0x20 and 0x30 added once each in first-seen order.
        assert_eq!(cfg.get_guest_msrs(), &[0x10, 0x20, 0x30]);
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn guest_msrs_duplicates_do_not_count_toward_capacity() {
        let mut cfg = SandboxConfiguration::default();
        let fill: Vec<u32> = (0..SandboxConfiguration::MAX_GUEST_MSRS as u32 - 1).collect();
        cfg.guest_msrs(&fill).unwrap();
        // One slot remains. Three copies of one new index count as a single
        // distinct entry and fit.
        cfg.guest_msrs(&[u32::MAX, u32::MAX, u32::MAX]).unwrap();
        assert_eq!(
            cfg.get_guest_msrs().len(),
            SandboxConfiguration::MAX_GUEST_MSRS
        );
    }

    #[test]
    fn overrides() {
        const HEAP_SIZE_OVERRIDE: u64 = 0x50000;
        const SCRATCH_SIZE_OVERRIDE: usize = 0x60000;
        let mut cfg = SandboxConfiguration::new(
            Some(HEAP_SIZE_OVERRIDE),
            SCRATCH_SIZE_OVERRIDE,
            SandboxConfiguration::DEFAULT_INTERRUPT_RETRY_DELAY,
            SandboxConfiguration::INTERRUPT_VCPU_SIGRTMIN_OFFSET,
            #[cfg(gdb)]
            None,
            #[cfg(crashdump)]
            true,
        );

        let heap_size = cfg.get_heap_size();
        let scratch_size = cfg.get_scratch_size();
        assert_eq!(HEAP_SIZE_OVERRIDE, heap_size);
        assert_eq!(SCRATCH_SIZE_OVERRIDE, scratch_size);

        cfg.heap_size_override = 2048;
        cfg.scratch_size = 0x40000;
        assert_eq!(2048, cfg.heap_size_override);
        assert_eq!(0x40000, cfg.scratch_size);
        assert_eq!(
            SandboxConfiguration::DEFAULT_G2H_QUEUE_SIZE,
            cfg.get_g2h_queue_size()
        );
        assert_eq!(
            SandboxConfiguration::DEFAULT_H2G_QUEUE_SIZE,
            cfg.get_h2g_queue_size()
        );
        assert_eq!(
            SandboxConfiguration::DEFAULT_G2H_BUFFER_SIZE,
            cfg.get_g2h_buffer_size()
        );
        assert_eq!(
            SandboxConfiguration::DEFAULT_H2G_BUFFER_SIZE,
            cfg.get_h2g_buffer_size()
        );
        assert_eq!(
            SandboxConfiguration::DEFAULT_G2H_POOL_PAGES,
            cfg.get_g2h_pool_pages()
        );
        assert_eq!(
            SandboxConfiguration::DEFAULT_H2G_POOL_PAGES,
            cfg.get_h2g_pool_pages()
        );
    }

    #[test]
    fn queue_sizes_are_normalized() {
        let mut cfg = SandboxConfiguration::default();
        for (size, expected) in [
            (0, 2),
            (1, 2),
            (2, 2),
            (3, 4),
            (32_767, 32_768),
            (32_768, 32_768),
            (32_769, 32_768),
            (usize::MAX, 32_768),
        ] {
            cfg.set_g2h_queue_size(size);
            cfg.set_h2g_queue_size(size);
            assert_eq!(expected, cfg.get_g2h_queue_size());
            assert_eq!(expected, cfg.get_h2g_queue_size());
        }
    }

    #[test]
    fn buffer_sizes_are_normalized_without_page_rounding() {
        let mut cfg = SandboxConfiguration::default();

        cfg.set_g2h_buffer_size(0);
        cfg.set_h2g_buffer_size(0);
        assert_eq!(256, cfg.get_g2h_buffer_size());
        assert_eq!(256, cfg.get_h2g_buffer_size());

        cfg.set_g2h_buffer_size(3000);
        cfg.set_h2g_buffer_size(3001);
        assert_eq!(3000, cfg.get_g2h_buffer_size());
        assert_eq!(3001, cfg.get_h2g_buffer_size());

        cfg.set_g2h_buffer_size(usize::MAX);
        cfg.set_h2g_buffer_size(usize::MAX);
        assert_eq!(u32::MAX as usize, cfg.get_g2h_buffer_size());
        assert_eq!(u32::MAX as usize, cfg.get_h2g_buffer_size());
    }

    #[test]
    fn pool_page_counts_are_normalized() {
        let mut cfg = SandboxConfiguration::default();

        cfg.set_g2h_pool_pages(0);
        cfg.set_h2g_pool_pages(0);
        assert_eq!(2, cfg.get_g2h_pool_pages());
        assert_eq!(1, cfg.get_h2g_pool_pages());

        cfg.set_g2h_buffer_size(PAGE_SIZE + 1);
        cfg.set_h2g_buffer_size(PAGE_SIZE + 1);
        assert_eq!(3, cfg.get_g2h_pool_pages());
        assert_eq!(2, cfg.get_h2g_pool_pages());

        cfg.set_g2h_pool_pages(2);
        cfg.set_h2g_pool_pages(1);
        assert_eq!(3, cfg.get_g2h_pool_pages());
        assert_eq!(2, cfg.get_h2g_pool_pages());

        cfg.set_g2h_pool_pages(4);
        cfg.set_h2g_pool_pages(3);
        assert_eq!(4, cfg.get_g2h_pool_pages());
        assert_eq!(3, cfg.get_h2g_pool_pages());
    }

    mod proptests {
        use proptest::prelude::*;

        use super::SandboxConfiguration;
        #[cfg(gdb)]
        use crate::sandbox::config::DebugInfo;

        proptest! {
            #[test]
            fn heap_size_override(size in 0x1000..=0x10000u64) {
                let mut cfg = SandboxConfiguration::default();
                cfg.set_heap_size(size);
                prop_assert_eq!(size, cfg.heap_size_override);
            }

            #[test]
            #[cfg(gdb)]
            fn guest_debug_info(port in 9000..=u16::MAX) {
                let mut cfg = SandboxConfiguration::default();
                let debug_info = DebugInfo { port };
                cfg.set_guest_debug_info(debug_info);
                prop_assert_eq!(debug_info, *cfg.get_guest_debug_info().as_ref().unwrap());
            }
        }
    }
}