hyperlight-host 0.17.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025 The Hyperlight Authors.

use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterType, ReturnType};
use hyperlight_common::flatbuffer_wrappers::host_function_definition::HostFunctionDefinition;
use hyperlight_common::vmem::PAGE_SIZE;
use serde::{Deserialize, Serialize};

use super::media_types::SNAPSHOT_ABI_VERSION;
use crate::hypervisor::regs::CommonSpecialRegisters;
#[cfg(target_arch = "x86_64")]
use crate::hypervisor::regs::MsrEntry;
use crate::mem::layout::SandboxMemoryLayout;

// --- Arch and hypervisor identifiers --------------------------------

/// Guest architecture the snapshot was captured for. Checked on load
/// against the running host.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(super) enum Arch {
    X86_64,
    Aarch64,
}

impl Arch {
    pub(super) fn current() -> Self {
        #[cfg(target_arch = "x86_64")]
        {
            Self::X86_64
        }
        #[cfg(target_arch = "aarch64")]
        {
            Self::Aarch64
        }
    }

    /// Lowercase token matching the config JSON serialization, used
    /// for the advisory arch annotation on the manifest descriptor.
    pub(super) fn as_str(&self) -> &'static str {
        match self {
            Self::X86_64 => "x86_64",
            Self::Aarch64 => "aarch64",
        }
    }
}

/// Hypervisor backend the snapshot was captured under. Checked on
/// load because vCPU register state is backend-specific.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(super) enum Hypervisor {
    Kvm,
    Mshv,
    Whp,
    Hvf,
}

impl Hypervisor {
    pub(super) fn current() -> Option<Self> {
        #[allow(unused_imports)]
        use crate::hypervisor::virtual_machine::HypervisorType;
        use crate::hypervisor::virtual_machine::get_available_hypervisor;

        match get_available_hypervisor() {
            #[cfg(kvm)]
            Some(HypervisorType::Kvm) => Some(Self::Kvm),
            #[cfg(mshv3)]
            Some(HypervisorType::Mshv) => Some(Self::Mshv),
            #[cfg(target_os = "windows")]
            Some(HypervisorType::Whp) => Some(Self::Whp),
            #[cfg(hvf)]
            Some(HypervisorType::Hvf) => Some(Self::Hvf),
            None => None,
        }
    }

    fn name(&self) -> &'static str {
        match self {
            Self::Kvm => "KVM",
            Self::Mshv => "MSHV",
            Self::Whp => "WHP",
            Self::Hvf => "HVF",
        }
    }

    /// Lowercase token matching the config JSON serialization, used
    /// for the advisory hypervisor annotation on the manifest
    /// descriptor.
    pub(super) fn as_str(&self) -> &'static str {
        match self {
            Self::Kvm => "kvm",
            Self::Mshv => "mshv",
            Self::Whp => "whp",
            Self::Hvf => "hvf",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct CpuVendor(String);

impl CpuVendor {
    /// The vendor identifier of the running host.
    pub(super) fn current() -> Self {
        #[cfg(target_arch = "x86_64")]
        {
            // SAFETY: CPUID leaf 0 is always available on x86_64.
            // TODO: Remove the `unsafe`/allow when MSRV is raised above
            // 1.89. On Rust 1.89 `__cpuid` requires `unsafe`; on newer
            // compilers it is safe and clippy flags it as unnecessary.
            #[allow(unused_unsafe)]
            let r = unsafe { core::arch::x86_64::__cpuid(0) };
            let mut bytes = [0u8; 12];
            bytes[0..4].copy_from_slice(&r.ebx.to_le_bytes());
            bytes[4..8].copy_from_slice(&r.edx.to_le_bytes());
            bytes[8..12].copy_from_slice(&r.ecx.to_le_bytes());
            Self(String::from_utf8_lossy(&bytes).into_owned())
        }
        #[cfg(all(target_arch = "aarch64", target_os = "linux"))]
        {
            let midr: u64;
            // SAFETY: Linux emulates MIDR_EL1 reads from EL0.
            unsafe { core::arch::asm!("mrs {}, MIDR_EL1", out(reg) midr) };
            let implementer = (midr >> 24) & 0xff;
            // `0x` prefix padded to width 4, e.g. Apple `0x61`, Arm `0x41`.
            Self(format!("{implementer:#04x}"))
        }
        #[cfg(all(target_arch = "aarch64", target_os = "macos"))]
        {
            Self("0x61".to_string())
        }
    }

    pub(super) fn as_str(&self) -> &str {
        &self.0
    }

    /// Short, stable token naming this vendor for snapshot golden
    /// tags, or `None` for a vendor the goldens do not cover.
    pub(crate) fn golden_tag(&self) -> Option<&'static str> {
        match self.0.as_str() {
            "GenuineIntel" => Some("intel"),
            "AuthenticAMD" => Some("amd"),
            // aarch64 MIDR_EL1 implementer byte for Apple silicon.
            "0x61" => Some("apple"),
            _ => None,
        }
    }
}

// --- Config JSON shape ----------------------------------------------

/// Top-level Hyperlight snapshot config JSON. Lives at
/// `blobs/sha256/<config-digest>` with media type
/// `application/vnd.hyperlight.snapshot.config.v1+json`.
///
/// In OCI terms this is the "image config" blob that the manifest's
/// `config` descriptor points to. It describes the accompanying
/// memory layer (the snapshot bytes) and everything the loader needs
/// to reconstruct a runnable `Snapshot`.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct OciSnapshotConfig {
    /// Hyperlight crate version that produced this config. Recorded
    /// for diagnostics. Not checked on load.
    pub(super) hyperlight_version: String,
    pub(super) arch: Arch,
    /// Memory blob ABI version. See `SNAPSHOT_ABI_VERSION`.
    pub(super) abi_version: u32,
    pub(super) hypervisor: Hypervisor,
    /// CPU vendor captured at snapshot time. Checked on load.
    pub(super) cpu_vendor: CpuVendor,
    /// Top of the guest stack, in guest virtual address space.
    pub(super) stack_top_gva: u64,
    /// Guest virtual address the loader resumes the paused call at.
    pub(super) entrypoint_addr: u64,
    /// Guest virtual address of the ELF entry point
    /// (`load_addr + e_entry - base_va`), preserved across the
    /// Initialise->Call transition. Fills `AT_ENTRY` in core dumps so
    /// gdb resolves PIE symbols.
    pub(super) original_entrypoint_addr: u64,
    /// Special registers captured from the paused vCPU, restored
    /// verbatim when resuming the call.
    pub(super) sregs: CommonSpecialRegisters,
    /// The MSRs saved in this snapshot. An empty field restores the destination
    /// baseline.
    #[cfg(target_arch = "x86_64")]
    pub(super) msrs: Vec<MsrEntry>,
    pub(super) layout: MemoryLayout,
    /// Total size of the memory blob in bytes (including the guest
    /// page-table tail, if any). Equal to `self.memory.mem_size()`.
    pub(super) memory_size: u64,
    /// Names and signatures of host functions registered when this
    /// snapshot was taken. Validated against the loader's registry.
    pub(super) host_functions: Vec<HostFunction>,
    /// Generation counter for the snapshot. Restored verbatim into
    /// the `Snapshot` so guest-visible bookkeeping at
    /// `SCRATCH_TOP_SNAPSHOT_GENERATION_OFFSET` is continuous across
    /// save/load.
    pub(super) snapshot_generation: u64,
}

/// Sizes and permissions of the regions inside the snapshot blob,
/// enough for the loader to rebuild a `SandboxMemoryLayout`.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct MemoryLayout {
    pub(super) input_data_size: usize,
    pub(super) output_data_size: usize,
    pub(super) heap_size: usize,
    pub(super) code_size: usize,
    pub(super) init_data_size: usize,
    /// Memory region flag bits. `None` means default permissions.
    pub(super) init_data_permissions: Option<u32>,
    pub(super) scratch_size: usize,
    pub(super) snapshot_size: usize,
    pub(super) pt_size: Option<usize>,
}

/// Name and signature of one host function registered when the
/// snapshot was taken. The loader validates these against the
/// registry of the sandbox it is restoring into.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct HostFunction {
    function_name: String,
    parameter_types: Vec<ParameterTypeRepr>,
    return_type: ReturnTypeRepr,
}

/// JSON-friendly mirror of
/// [`hyperlight_common::flatbuffer_wrappers::function_types::ParameterType`].
/// Kept local so we don't have to plumb serde through `hyperlight_common`.
/// The `match`es below are exhaustive: any new variant upstream forces
/// an explicit decision here.
#[derive(Serialize, Deserialize, Copy, Clone)]
#[serde(rename_all = "snake_case")]
enum ParameterTypeRepr {
    Int,
    UInt,
    Long,
    ULong,
    Float,
    Double,
    String,
    Bool,
    VecBytes,
}

/// JSON-friendly mirror of
/// [`hyperlight_common::flatbuffer_wrappers::function_types::ReturnType`].
#[derive(Serialize, Deserialize, Copy, Clone)]
#[serde(rename_all = "snake_case")]
enum ReturnTypeRepr {
    Int,
    UInt,
    Long,
    ULong,
    Float,
    Double,
    String,
    Bool,
    Void,
    VecBytes,
}

impl From<&ParameterType> for ParameterTypeRepr {
    fn from(p: &ParameterType) -> Self {
        match p {
            ParameterType::Int => Self::Int,
            ParameterType::UInt => Self::UInt,
            ParameterType::Long => Self::Long,
            ParameterType::ULong => Self::ULong,
            ParameterType::Float => Self::Float,
            ParameterType::Double => Self::Double,
            ParameterType::String => Self::String,
            ParameterType::Bool => Self::Bool,
            ParameterType::VecBytes => Self::VecBytes,
        }
    }
}

impl From<ParameterTypeRepr> for ParameterType {
    fn from(r: ParameterTypeRepr) -> Self {
        match r {
            ParameterTypeRepr::Int => Self::Int,
            ParameterTypeRepr::UInt => Self::UInt,
            ParameterTypeRepr::Long => Self::Long,
            ParameterTypeRepr::ULong => Self::ULong,
            ParameterTypeRepr::Float => Self::Float,
            ParameterTypeRepr::Double => Self::Double,
            ParameterTypeRepr::String => Self::String,
            ParameterTypeRepr::Bool => Self::Bool,
            ParameterTypeRepr::VecBytes => Self::VecBytes,
        }
    }
}

impl From<&ReturnType> for ReturnTypeRepr {
    fn from(r: &ReturnType) -> Self {
        match r {
            ReturnType::Int => Self::Int,
            ReturnType::UInt => Self::UInt,
            ReturnType::Long => Self::Long,
            ReturnType::ULong => Self::ULong,
            ReturnType::Float => Self::Float,
            ReturnType::Double => Self::Double,
            ReturnType::String => Self::String,
            ReturnType::Bool => Self::Bool,
            ReturnType::Void => Self::Void,
            ReturnType::VecBytes => Self::VecBytes,
        }
    }
}

impl From<ReturnTypeRepr> for ReturnType {
    fn from(r: ReturnTypeRepr) -> Self {
        match r {
            ReturnTypeRepr::Int => Self::Int,
            ReturnTypeRepr::UInt => Self::UInt,
            ReturnTypeRepr::Long => Self::Long,
            ReturnTypeRepr::ULong => Self::ULong,
            ReturnTypeRepr::Float => Self::Float,
            ReturnTypeRepr::Double => Self::Double,
            ReturnTypeRepr::String => Self::String,
            ReturnTypeRepr::Bool => Self::Bool,
            ReturnTypeRepr::Void => Self::Void,
            ReturnTypeRepr::VecBytes => Self::VecBytes,
        }
    }
}

impl From<&HostFunctionDefinition> for HostFunction {
    fn from(d: &HostFunctionDefinition) -> Self {
        let parameter_types = d
            .parameter_types
            .as_ref()
            .map(|v| v.iter().map(ParameterTypeRepr::from).collect())
            .unwrap_or_default();
        Self {
            function_name: d.function_name.clone(),
            parameter_types,
            return_type: ReturnTypeRepr::from(&d.return_type),
        }
    }
}

impl From<HostFunction> for HostFunctionDefinition {
    fn from(r: HostFunction) -> Self {
        Self {
            function_name: r.function_name,
            parameter_types: Some(r.parameter_types.into_iter().map(Into::into).collect()),
            return_type: r.return_type.into(),
        }
    }
}

impl OciSnapshotConfig {
    pub(super) fn validate_for_load(&self) -> crate::Result<()> {
        if self.arch != Arch::current() {
            return Err(crate::new_error!(
                "snapshot architecture mismatch: file is {:?}, current host is {:?} \
                 (snapshot produced by hyperlight {})",
                self.arch,
                Arch::current(),
                self.hyperlight_version
            ));
        }
        if self.abi_version != SNAPSHOT_ABI_VERSION {
            return Err(crate::new_error!(
                "snapshot ABI version mismatch: file has version {}, this build expects {}. \
                 The snapshot must be regenerated from the guest binary \
                 (snapshot produced by hyperlight {}).",
                self.abi_version,
                SNAPSHOT_ABI_VERSION,
                self.hyperlight_version
            ));
        }
        let current_hv = Hypervisor::current()
            .ok_or_else(|| crate::new_error!("no hypervisor available to load snapshot"))?;
        if self.hypervisor != current_hv {
            return Err(crate::new_error!(
                "snapshot hypervisor mismatch: file was created on {} but the current hypervisor is {} \
                 (snapshot produced by hyperlight {})",
                self.hypervisor.name(),
                current_hv.name(),
                self.hyperlight_version
            ));
        }
        let current_vendor = CpuVendor::current();
        if self.cpu_vendor != current_vendor {
            return Err(crate::new_error!(
                "snapshot CPU vendor mismatch: file was created on {} but the current CPU is {} \
                 (snapshot produced by hyperlight {})",
                self.cpu_vendor.as_str(),
                current_vendor.as_str(),
                self.hyperlight_version
            ));
        }
        // Bound memory size early so the subsequent file-size check
        // does not have to deal with absurd values.
        if self.memory_size == 0 || self.memory_size > SandboxMemoryLayout::MAX_MEMORY_SIZE as u64 {
            return Err(crate::new_error!(
                "snapshot memory_size ({}) is out of range",
                self.memory_size
            ));
        }
        if !(self.memory_size as usize).is_multiple_of(PAGE_SIZE) {
            return Err(crate::new_error!(
                "snapshot memory_size ({}) is not a multiple of PAGE_SIZE",
                self.memory_size
            ));
        }
        // `snapshot_size` is the guest-visible prefix of the blob,
        // mapped at `BASE_ADDRESS`. `pt_size` is the page-table tail
        // after it, present in the blob and host mapping but outside
        // the guest mapping. They sum to `memory_size`.
        if self.layout.snapshot_size == 0 {
            return Err(crate::new_error!("snapshot snapshot_size must be nonzero"));
        }
        if !self.layout.snapshot_size.is_multiple_of(PAGE_SIZE) {
            return Err(crate::new_error!(
                "snapshot snapshot_size ({}) is not a multiple of PAGE_SIZE",
                self.layout.snapshot_size
            ));
        }
        let pt = self
            .layout
            .pt_size
            .ok_or_else(|| crate::new_error!("snapshot pt_size is missing"))?;
        if pt == 0 {
            return Err(crate::new_error!("snapshot pt_size must be nonzero"));
        }
        if !pt.is_multiple_of(PAGE_SIZE) {
            return Err(crate::new_error!(
                "snapshot pt_size ({}) is not a multiple of PAGE_SIZE",
                pt
            ));
        }
        // The total memory size might be bigger because it has to
        // take into account the host page size, as well as the guest
        // page size.
        let total_size = (self.layout.snapshot_size as u64)
            .saturating_add(pt as u64)
            .next_multiple_of(page_size::get() as u64);
        if total_size != self.memory_size {
            return Err(crate::new_error!(
                "snapshot snapshot_size ({}) + pt_size ({}), rounded to {}, does not equal memory_size ({})",
                self.layout.snapshot_size,
                pt,
                total_size,
                self.memory_size
            ));
        }
        // Cap each layout field at `MAX_MEMORY_SIZE` so the later
        // size and offset sums in `SandboxMemoryLayout` cannot
        // overflow `u64`. Whether the regions fit the snapshot is
        // checked against `snapshot_size` in `load_inner`.
        let max_region = SandboxMemoryLayout::MAX_MEMORY_SIZE;
        for (name, value) in [
            ("input_data_size", self.layout.input_data_size),
            ("output_data_size", self.layout.output_data_size),
            ("heap_size", self.layout.heap_size),
            ("code_size", self.layout.code_size),
            ("init_data_size", self.layout.init_data_size),
            ("scratch_size", self.layout.scratch_size),
        ] {
            if value > max_region {
                return Err(crate::new_error!(
                    "snapshot layout field {} ({}) exceeds maximum allowed {}",
                    name,
                    value,
                    max_region
                ));
            }
        }

        // The saved dispatch entrypoint must be in the executable code
        // region. Code occupies the page-rounded prefix of the snapshot.
        let code_lo = SandboxMemoryLayout::BASE_ADDRESS as u64;
        let code_hi = code_lo
            .checked_add(self.layout.code_size.next_multiple_of(PAGE_SIZE) as u64)
            .ok_or_else(|| {
                crate::new_error!(
                    "snapshot layout overflow: BASE_ADDRESS + code_size ({}) does not fit in u64",
                    self.layout.code_size
                )
            })?;
        if self.entrypoint_addr < code_lo || self.entrypoint_addr >= code_hi {
            return Err(crate::new_error!(
                "snapshot entrypoint addr {:#x} is outside the code region [{:#x}, {:#x})",
                self.entrypoint_addr,
                code_lo,
                code_hi
            ));
        }
        #[cfg(target_arch = "aarch64")]
        if !self.entrypoint_addr.is_multiple_of(4) {
            return Err(crate::new_error!(
                "snapshot entrypoint addr {:#x} is not 4-byte aligned",
                self.entrypoint_addr
            ));
        }

        // ELF entry point GVA for `AT_ENTRY` in core dumps. It must point
        // inside the snapshot region, like `entrypoint_addr`.
        let snapshot_hi = code_lo
            .checked_add(self.layout.snapshot_size as u64)
            .ok_or_else(|| {
                crate::new_error!(
                    "snapshot layout overflow: BASE_ADDRESS + snapshot_size ({}) does not fit in u64",
                    self.layout.snapshot_size
                )
            })?;
        if self.original_entrypoint_addr < code_lo || self.original_entrypoint_addr >= snapshot_hi {
            return Err(crate::new_error!(
                "snapshot original entrypoint addr {:#x} is outside the snapshot region [{:#x}, {:#x})",
                self.original_entrypoint_addr,
                code_lo,
                snapshot_hi
            ));
        }

        // `stack_top_gva` is restored directly into the guest stack
        // pointer. It must be aligned and in the guest address range.
        let max_gva = hyperlight_common::layout::SCRATCH_TOP_GVA as u64;
        if self.stack_top_gva == 0 || self.stack_top_gva > max_gva {
            return Err(crate::new_error!(
                "snapshot stack_top_gva {:#x} is outside the valid range (0, {:#x}]",
                self.stack_top_gva,
                max_gva
            ));
        }
        if !self.stack_top_gva.is_multiple_of(16) {
            return Err(crate::new_error!(
                "snapshot stack_top_gva {:#x} is not 16-byte aligned",
                self.stack_top_gva
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterType, ReturnType};

    use super::*;
    #[cfg(target_arch = "x86_64")]
    use crate::hypervisor::regs::{CommonSegmentRegister, CommonTableRegister};

    /// Build a `CommonSegmentRegister` whose every field holds a
    /// distinct value, so a transposed field in the
    /// `CommonSpecialRegisters` conversion produces an inequality.
    #[cfg(target_arch = "x86_64")]
    fn distinct_segment(start: u64) -> CommonSegmentRegister {
        CommonSegmentRegister {
            base: start,
            limit: (start + 1) as u32,
            selector: (start + 2) as u16,
            type_: (start + 3) as u8,
            present: (start + 4) as u8,
            dpl: (start + 5) as u8,
            db: (start + 6) as u8,
            s: (start + 7) as u8,
            l: (start + 8) as u8,
            g: (start + 9) as u8,
            avl: (start + 10) as u8,
            unusable: (start + 11) as u8,
            padding: (start + 12) as u8,
        }
    }

    #[cfg(target_arch = "x86_64")]
    fn distinct_table(start: u64) -> CommonTableRegister {
        CommonTableRegister {
            base: start,
            limit: (start + 1) as u16,
        }
    }

    /// Special registers with a unique value in every field, including
    /// a nonzero `cr3`.
    fn distinct_sregs() -> CommonSpecialRegisters {
        #[cfg(target_arch = "x86_64")]
        let sr = CommonSpecialRegisters {
            cs: distinct_segment(10),
            ds: distinct_segment(30),
            es: distinct_segment(50),
            fs: distinct_segment(70),
            gs: distinct_segment(90),
            ss: distinct_segment(110),
            tr: distinct_segment(130),
            ldt: distinct_segment(150),
            gdt: distinct_table(170),
            idt: distinct_table(180),
            cr0: 200,
            cr2: 201,
            cr3: 202,
            cr4: 203,
            cr8: 204,
            efer: 205,
            apic_base: 206,
            interrupt_bitmap: [207, 208, 209, 210],
        };
        #[cfg(target_arch = "aarch64")]
        let sr = CommonSpecialRegisters {
            ttbr0_el1: 10,
            tcr_el1: 20,
            mair_el1: 30,
            sctlr_el1: 40,
            cpacr_el1: 50,
            vbar_el1: 60,
            sp_el1: 60,
        };
        sr
    }

    /// Round-tripping special registers through serde preserves every
    /// field. `cr3` is the sole exception: it is omitted from the
    /// config and recomputed at load, so it returns as zero.
    #[test]
    fn sregs_round_trip_preserves_all_fields_except_cr3() {
        let original = distinct_sregs();
        let serialized = serde_json::to_vec(&original).unwrap();
        let restored: CommonSpecialRegisters = serde_json::from_slice(&serialized).unwrap();

        let mut expected = original;
        #[cfg(target_arch = "x86_64")]
        {
            expected.cr3 = 0;
        }
        #[cfg(target_arch = "aarch64")]
        {
            expected.ttbr0_el1 = 0;
        }
        assert_eq!(restored, expected);
    }

    /// Captured MSRs survive the serde round-trip through the config,
    /// including index and value for every entry.
    #[cfg(target_arch = "x86_64")]
    #[test]
    fn msrs_round_trip_preserves_every_entry() {
        let original = gating_config_with_msrs(Some(vec![
            MsrEntry {
                index: 0xC000_0102,
                value: 0xDEAD_BEEF,
            },
            MsrEntry {
                index: 0x10,
                value: 0x1234_5678_9ABC_DEF0,
            },
        ]));
        let json = serde_json::to_vec(&original).unwrap();
        let restored: OciSnapshotConfig = serde_json::from_slice(&json).unwrap();
        assert_eq!(restored.msrs, original.msrs);
    }

    /// A config JSON with no MSR state is rejected.
    #[cfg(target_arch = "x86_64")]
    #[test]
    fn config_without_msrs_is_rejected() {
        let with = gating_config_with_msrs(Some(vec![MsrEntry {
            index: 0x10,
            value: 1,
        }]));
        let mut json: serde_json::Value =
            serde_json::from_slice(&serde_json::to_vec(&with).unwrap()).unwrap();
        assert!(json.as_object_mut().unwrap().remove("msrs").is_some());

        let err = serde_json::from_value::<OciSnapshotConfig>(json)
            .err()
            .expect("config without msrs should fail to deserialize")
            .to_string();
        assert!(err.contains("missing field `msrs`"), "got: {err}");
    }

    /// Every `ParameterType` survives the round-trip through its serde
    /// mirror, guarding against a transposed variant in either match.
    #[test]
    fn parameter_type_repr_round_trips_every_variant() {
        let variants = [
            ParameterType::Int,
            ParameterType::UInt,
            ParameterType::Long,
            ParameterType::ULong,
            ParameterType::Float,
            ParameterType::Double,
            ParameterType::String,
            ParameterType::Bool,
            ParameterType::VecBytes,
        ];
        for p in variants {
            let back: ParameterType = ParameterTypeRepr::from(&p).into();
            assert_eq!(back, p, "parameter type {:?} did not round-trip", p);
        }
    }

    /// Every `ReturnType` survives the round-trip through its serde
    /// mirror, guarding against a transposed variant in either match.
    #[test]
    fn return_type_repr_round_trips_every_variant() {
        let variants = [
            ReturnType::Int,
            ReturnType::UInt,
            ReturnType::Long,
            ReturnType::ULong,
            ReturnType::Float,
            ReturnType::Double,
            ReturnType::String,
            ReturnType::Bool,
            ReturnType::Void,
            ReturnType::VecBytes,
        ];
        for r in variants {
            let back: ReturnType = ReturnTypeRepr::from(&r).into();
            assert_eq!(back, r, "return type {:?} did not round-trip", r);
        }
    }

    /// `CpuVendor::current` returns the expected host vendor. Ignored
    /// by default and run explicitly in CI, where the runner hardware
    /// is known. Extend the allowlist when new runner hardware is
    /// added.
    #[test]
    #[ignore = "hardware-specific; run explicitly in CI"]
    fn cpu_vendor_current_is_recognized() {
        let vendor = CpuVendor::current();
        let v = vendor.as_str();
        #[cfg(target_arch = "x86_64")]
        assert!(
            matches!(v, "GenuineIntel" | "AuthenticAMD"),
            "unrecognized x86_64 CPU vendor: {v:?}"
        );
        #[cfg(all(target_arch = "aarch64", target_os = "linux"))]
        // MIDR_EL1 implementer byte for Apple silicon.
        assert_eq!(v, "0x61", "unexpected aarch64 CPU implementer");
        #[cfg(all(target_arch = "aarch64", target_os = "macos"))]
        assert_eq!(v, "0x61", "unexpected aarch64 CPU implementer");
    }

    /// The architecture the current host is not running.
    fn other_arch() -> Arch {
        match Arch::current() {
            Arch::X86_64 => Arch::Aarch64,
            Arch::Aarch64 => Arch::X86_64,
        }
    }

    /// A config whose `arch` and `abi_version` match the current
    /// build, so the architecture and ABI gates pass and a test can
    /// trip a later gate in isolation. The layout is minimal: the
    /// gating checks under test short-circuit before reading it.
    fn gating_config() -> OciSnapshotConfig {
        OciSnapshotConfig {
            hyperlight_version: "test".to_string(),
            arch: Arch::current(),
            abi_version: SNAPSHOT_ABI_VERSION,
            hypervisor: Hypervisor::Mshv,
            cpu_vendor: CpuVendor::current(),
            stack_top_gva: 0x2000,
            entrypoint_addr: SandboxMemoryLayout::BASE_ADDRESS as u64,
            original_entrypoint_addr: SandboxMemoryLayout::BASE_ADDRESS as u64,
            sregs: distinct_sregs(),
            #[cfg(target_arch = "x86_64")]
            msrs: Vec::new(),
            layout: MemoryLayout {
                input_data_size: 0,
                output_data_size: 0,
                heap_size: 0,
                code_size: 0,
                init_data_size: 0,
                init_data_permissions: None,
                scratch_size: 0,
                snapshot_size: PAGE_SIZE,
                pt_size: None,
            },
            memory_size: PAGE_SIZE as u64,
            host_functions: Vec::new(),
            snapshot_generation: 0,
        }
    }

    /// `gating_config` with a chosen MSR set, for serde tests.
    #[cfg(target_arch = "x86_64")]
    fn gating_config_with_msrs(msrs: Option<Vec<MsrEntry>>) -> OciSnapshotConfig {
        OciSnapshotConfig {
            msrs: msrs.unwrap_or_default(),
            ..gating_config()
        }
    }

    /// A snapshot built for a different architecture is rejected.
    #[test]
    fn validate_for_load_rejects_arch_mismatch() {
        let mut cfg = gating_config();
        cfg.arch = other_arch();
        let err = cfg.validate_for_load().unwrap_err().to_string();
        assert!(err.contains("architecture mismatch"), "got: {err}");
    }

    /// A snapshot stamped with a different ABI version is rejected.
    #[test]
    fn validate_for_load_rejects_abi_version_mismatch() {
        let mut cfg = gating_config();
        cfg.abi_version = SNAPSHOT_ABI_VERSION.wrapping_add(1);
        let err = cfg.validate_for_load().unwrap_err().to_string();
        assert!(err.contains("ABI version mismatch"), "got: {err}");
    }

    /// A snapshot captured under a different hypervisor backend is
    /// rejected. Without a live backend the load is rejected outright,
    /// which exercises the same gate from the other side.
    #[test]
    fn validate_for_load_rejects_hypervisor_mismatch() {
        let Some(current) = Hypervisor::current() else {
            let cfg = gating_config();
            let err = cfg.validate_for_load().unwrap_err().to_string();
            assert!(err.contains("no hypervisor available"), "got: {err}");
            return;
        };
        let other = [Hypervisor::Kvm, Hypervisor::Mshv, Hypervisor::Whp]
            .into_iter()
            .find(|h| *h != current)
            .expect("three backends, at least one differs from current");
        let mut cfg = gating_config();
        cfg.hypervisor = other;
        let err = cfg.validate_for_load().unwrap_err().to_string();
        assert!(err.contains("hypervisor mismatch"), "got: {err}");
    }
}

#[cfg(test)]
mod schema_pin {
    use super::*;

    #[cfg(target_arch = "x86_64")]
    const PINNED_CALL: &str = r#"{
  "hyperlight_version": "x.y.z",
  "arch": "x86_64",
  "abi_version": 1,
  "hypervisor": "mshv",
  "cpu_vendor": "intel",
  "stack_top_gva": 3735928559,
  "entrypoint_addr": 8192,
  "original_entrypoint_addr": 4096,
  "sregs": {
    "cs": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "ds": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "es": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "fs": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "gs": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "ss": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "tr": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "ldt": {
      "base": 1,
      "limit": 2,
      "selector": 3,
      "type_": 4,
      "present": 5,
      "dpl": 6,
      "db": 7,
      "s": 8,
      "l": 9,
      "g": 10,
      "avl": 11,
      "unusable": 12,
      "padding": 13
    },
    "gdt": {
      "base": 1,
      "limit": 2
    },
    "idt": {
      "base": 3,
      "limit": 4
    },
    "cr0": 1,
    "cr2": 2,
    "cr4": 4,
    "cr8": 5,
    "efer": 6,
    "apic_base": 7,
    "interrupt_bitmap": [
      8,
      9,
      10,
      11
    ]
  },
  "msrs": [
    {
      "index": 16,
      "value": 42
    },
    {
      "index": 3221225474,
      "value": 3735928559
    }
  ],
  "layout": {
    "input_data_size": 1,
    "output_data_size": 2,
    "heap_size": 3,
    "code_size": 4,
    "init_data_size": 5,
    "init_data_permissions": null,
    "scratch_size": 8,
    "snapshot_size": 9,
    "pt_size": null
  },
  "memory_size": 65536,
  "host_functions": [
    {
      "function_name": "fn_void",
      "parameter_types": [
        "bool"
      ],
      "return_type": "void"
    }
  ],
  "snapshot_generation": 42
}"#;

    #[cfg(target_arch = "aarch64")]
    const PINNED_CALL: &str = r#"{
  "hyperlight_version": "x.y.z",
  "arch": "aarch64",
  "abi_version": 1,
  "hypervisor": "mshv",
  "cpu_vendor": "intel",
  "stack_top_gva": 3735928559,
  "entrypoint_addr": 8192,
  "original_entrypoint_addr": 4096,
  "sregs": {
    "tcr_el1": 1,
    "mair_el1": 2,
    "sctlr_el1": 3,
    "cpacr_el1": 4,
    "vbar_el1": 5,
    "sp_el1": 6
  },
  "layout": {
    "input_data_size": 1,
    "output_data_size": 2,
    "heap_size": 3,
    "code_size": 4,
    "init_data_size": 5,
    "init_data_permissions": null,
    "scratch_size": 8,
    "snapshot_size": 9,
    "pt_size": null
  },
  "memory_size": 65536,
  "host_functions": [
    {
      "function_name": "fn_void",
      "parameter_types": [
        "bool"
      ],
      "return_type": "void"
    }
  ],
  "snapshot_generation": 42
}"#;

    const PINNED_ARCH: &str = r#"[
  "x86_64",
  "aarch64"
]"#;

    const PINNED_HYPERVISOR: &str = r#"[
  "kvm",
  "mshv",
  "whp"
]"#;

    fn assert_round_trip(pinned: &str) {
        let pinned_value: serde_json::Value =
            serde_json::from_str(pinned).expect("pinned JSON must deserialize as a value");
        let parsed: OciSnapshotConfig =
            serde_json::from_value(pinned_value.clone()).expect("pinned JSON must deserialize");
        let actual = serde_json::to_string_pretty(&parsed).expect("serialize");
        let actual_value: serde_json::Value =
            serde_json::from_str(&actual).expect("serialized config must deserialize");
        assert_eq!(
            actual_value, pinned_value,
            "Snapshot config JSON schema changed. If the change can break \
             existing snapshots on disk, bump `MT_CONFIG_V1` in \
             `super::media_types` and follow `docs/snapshot-versioning.md`. \
             Either way, paste the actual output below into the matching \
             `PINNED_*`.\n\nactual:\n{actual}"
        );
    }

    #[test]
    fn call_round_trip() {
        assert_round_trip(PINNED_CALL);
    }

    #[test]
    fn arch_variants_round_trip() {
        let parsed: Vec<Arch> =
            serde_json::from_str(PINNED_ARCH).expect("pinned arch JSON must deserialize");
        let actual = serde_json::to_string_pretty(&parsed).expect("serialize");
        assert_eq!(actual.trim(), PINNED_ARCH.trim(), "Arch variants changed.");
    }

    #[test]
    fn hypervisor_variants_round_trip() {
        let parsed: Vec<Hypervisor> = serde_json::from_str(PINNED_HYPERVISOR)
            .expect("pinned hypervisor JSON must deserialize");
        let actual = serde_json::to_string_pretty(&parsed).expect("serialize");
        assert_eq!(
            actual.trim(),
            PINNED_HYPERVISOR.trim(),
            "Hypervisor variants changed."
        );
    }
}