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
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025 The Hyperlight Authors.

use flatbuffers::FlatBufferBuilder;
use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall;
use hyperlight_common::flatbuffer_wrappers::function_types::FunctionCallResult;
use hyperlight_common::flatbuffer_wrappers::host_function_details::HostFunctionDetails;
use hyperlight_common::flatbuffer_wrappers::util::estimate_flatbuffer_capacity;
use hyperlight_common::log_level::GuestLogFilter;
use hyperlight_common::transport::{Buf, EncodedMessage, ExternalValues, MailboxValue, MsgKind};
use hyperlight_common::virtq::ReplyChain;
use hyperlight_common::vmem::{self, PAGE_TABLE_SIZE};
#[cfg(crashdump)]
use hyperlight_common::vmem::{BasicMapping, MappingKind};
use tracing::{Span, instrument};

use super::layout::SandboxMemoryLayout;
use super::shared_mem::{
    ExclusiveSharedMemory, GuestSharedMemory, HostSharedMemory, ReadonlySharedMemory, SharedMemory,
};
use super::virtq::{self, G2hConsumer, H2gConsumer, VirtqSnapshot};
use crate::hypervisor::regs::CommonSpecialRegisters;
use crate::mem::memory_region::MemoryRegion;
#[cfg(crashdump)]
use crate::mem::memory_region::{CrashDumpRegion, MemoryRegionFlags, MemoryRegionType};
use crate::sandbox::snapshot::{NextAction, Snapshot};
use crate::{HyperlightError, Result, new_error};

#[cfg(crashdump)]
fn mapping_kind_to_flags(kind: &MappingKind) -> (MemoryRegionFlags, MemoryRegionType) {
    match kind {
        MappingKind::Basic(BasicMapping {
            readable,
            writable,
            executable,
        }) => {
            let mut flags = MemoryRegionFlags::empty();
            if *readable {
                flags |= MemoryRegionFlags::READ;
            }
            if *writable {
                flags |= MemoryRegionFlags::WRITE;
            }
            if *executable {
                flags |= MemoryRegionFlags::EXECUTE;
            }
            (flags, MemoryRegionType::Snapshot)
        }
        MappingKind::Cow(cow) => {
            let mut flags = MemoryRegionFlags::empty();
            if cow.readable {
                flags |= MemoryRegionFlags::READ;
            }
            if cow.executable {
                flags |= MemoryRegionFlags::EXECUTE;
            }
            (flags, MemoryRegionType::Scratch)
        }
        MappingKind::Unmapped => (MemoryRegionFlags::empty(), MemoryRegionType::Snapshot),
        MappingKind::ZeroInit(bm) => {
            let mut flags = MemoryRegionFlags::empty();
            if bm.readable {
                flags |= MemoryRegionFlags::READ;
            }
            if bm.writable {
                flags |= MemoryRegionFlags::WRITE;
            }
            if bm.executable {
                flags |= MemoryRegionFlags::EXECUTE;
            }
            (flags, MemoryRegionType::Snapshot)
        }
    }
}

/// Try to extend the last region in `regions` if the new page is contiguous
/// in both guest and host address space and has the same flags.
///
/// Returns `true` if the region was coalesced, `false` if a new region is needed.
#[cfg(crashdump)]
fn try_coalesce_region(
    regions: &mut [CrashDumpRegion],
    virt_base: usize,
    virt_end: usize,
    host_base: usize,
    flags: MemoryRegionFlags,
) -> bool {
    if let Some(last) = regions.last_mut()
        && last.guest_region.end == virt_base
        && last.host_region.end == host_base
        && last.flags == flags
    {
        last.guest_region.end = virt_end;
        last.host_region.end = host_base + (virt_end - virt_base);
        return true;
    }
    false
}

// It would be nice to have a simple type alias
// `SnapshotSharedMemory<S: SharedMemory>` that abstracts over the
// fact that the snapshot shared memory is `ReadonlySharedMemory`
// normally, but there is (temporary) support for writable
// `GuestSharedMemory` with `#[cfg(gdb)]`. Unfortunately, rustc gets
// annoyed about an unused type parameter, unless one goes to a little
// bit of effort to trick it...
mod unused_hack {
    #[cfg(not(unshared_snapshot_mem))]
    use crate::mem::shared_mem::ReadonlySharedMemory;
    use crate::mem::shared_mem::SharedMemory;
    pub trait SnapshotSharedMemoryT {
        type T<S: SharedMemory>;
    }
    pub struct SnapshotSharedMemory_;
    impl SnapshotSharedMemoryT for SnapshotSharedMemory_ {
        #[cfg(not(unshared_snapshot_mem))]
        type T<S: SharedMemory> = ReadonlySharedMemory;
        #[cfg(unshared_snapshot_mem)]
        type T<S: SharedMemory> = S;
    }
    pub type SnapshotSharedMemory<S> = <SnapshotSharedMemory_ as SnapshotSharedMemoryT>::T<S>;
}
impl ReadonlySharedMemory {
    pub(crate) fn to_mgr_snapshot_mem(
        &self,
    ) -> Result<SnapshotSharedMemory<ExclusiveSharedMemory>> {
        #[cfg(not(unshared_snapshot_mem))]
        let ret = self.clone();
        #[cfg(unshared_snapshot_mem)]
        let ret = self.copy_to_writable()?;
        Ok(ret)
    }
}
pub(crate) use unused_hack::SnapshotSharedMemory;

/// Guest operations the host accepts during a VM entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExecutionMode {
    /// Guest initialization and guest function calls.
    Unrestricted,
    /// Snapshot checkpoint preparation. Host function calls are rejected.
    Restricted,
}

/// A struct that is responsible for laying out and managing the memory
/// for a given `Sandbox`.
pub(crate) struct SandboxMemoryManager<S: SharedMemory> {
    /// Shared memory for the Sandbox
    pub(crate) shared_mem: SnapshotSharedMemory<S>,
    /// Scratch memory for the Sandbox
    pub(crate) scratch_mem: S,
    /// The memory layout of the underlying shared memory
    pub(crate) layout: SandboxMemoryLayout,
    /// The next action to perform when this sandbox resumes:
    /// `Initialise` before the guest has run, `Call` afterwards.
    pub(crate) next_action: NextAction,
    /// Guest virtual address of the guest binary's ELF entry point,
    /// preserved across the `Initialise` -> `Call` transition so it
    /// can fill `AT_ENTRY` in guest core dumps. 0 if unknown.
    pub(crate) original_entrypoint: u64,
    /// Buffer for accumulating guest abort messages
    pub(crate) abort_buffer: Vec<u8>,
    /// Guest operations the host accepts during the current VM entry.
    pub(crate) execution_mode: ExecutionMode,
    /// Generation counter: how many snapshots have been taken from
    /// this sandbox's execution path from init to here. Incremented
    /// on each `snapshot` call; on `restore_snapshot` we inherit the
    /// restored snapshot's own generation number so the guest-visible
    /// counter tracks which snapshot the sandbox is a clone of.
    pub(crate) snapshot_count: u64,
    /// G2H consumer bound to the current scratch mapping.
    pub(crate) g2h_consumer: Option<G2hConsumer>,
    /// H2G consumer bound to the current scratch mapping.
    pub(crate) h2g_consumer: Option<H2gConsumer>,
    /// Correlation ID sequence survives consumer replacement and manager cloning.
    next_guest_cid: u32,
}

impl<S: Clone + SharedMemory> Clone for SandboxMemoryManager<S> {
    fn clone(&self) -> Self {
        Self {
            shared_mem: self.shared_mem.clone(),
            scratch_mem: self.scratch_mem.clone(),
            layout: self.layout,
            next_action: self.next_action,
            original_entrypoint: self.original_entrypoint,
            abort_buffer: self.abort_buffer.clone(),
            execution_mode: self.execution_mode,
            snapshot_count: self.snapshot_count,
            g2h_consumer: None,
            h2g_consumer: None,
            next_guest_cid: self.next_guest_cid,
        }
    }
}

/// Buffer for building guest page tables during snapshot creation.
/// `TableAddr` is an absolute GPA (u64) so the same address space is
/// used regardless of entry size.
pub(crate) struct GuestPageTableBuffer {
    buffer: std::cell::RefCell<Vec<u8>>,
    phys_base: usize,
    /// Absolute GPA of the currently-active root table. For
    /// multi-root guests, `set_root` switches which root subsequent
    /// `vmem::map` / `vmem::space_aware_map` calls target — typically
    /// to an address previously returned by `alloc_table`.
    root: std::cell::Cell<u64>,
}

impl vmem::TableReadOps for GuestPageTableBuffer {
    type TableAddr = u64;

    fn entry_addr(addr: u64, offset: u64) -> u64 {
        addr + offset
    }

    unsafe fn read_entry(&self, addr: u64) -> vmem::PageTableEntry {
        let buffer = self.buffer.borrow();
        let byte_offset = addr as usize - self.phys_base;
        let pte_size = core::mem::size_of::<vmem::PageTableEntry>();
        let Some(bytes) = buffer.get(byte_offset..byte_offset + pte_size) else {
            return 0;
        };
        let mut buf = [0u8; 8];
        buf[..pte_size].copy_from_slice(bytes);
        vmem::PageTableEntry::from_le_bytes(buf[..pte_size].try_into().unwrap_or_default())
    }

    fn to_phys(addr: u64) -> vmem::PhysAddr {
        addr as vmem::PhysAddr
    }

    fn from_phys(addr: vmem::PhysAddr) -> u64 {
        #[allow(clippy::unnecessary_cast)]
        {
            addr as u64
        }
    }

    fn root_table(&self) -> u64 {
        self.root.get()
    }
}

impl vmem::TableOps for GuestPageTableBuffer {
    type TableMovability = vmem::MayNotMoveTable;

    unsafe fn alloc_table(&self) -> u64 {
        let mut b = self.buffer.borrow_mut();
        let offset = b.len();
        b.resize(offset + PAGE_TABLE_SIZE, 0);
        (self.phys_base + offset) as u64
    }

    unsafe fn write_entry(&self, addr: u64, entry: vmem::PageTableEntry) -> Option<vmem::Void> {
        let mut b = self.buffer.borrow_mut();
        let byte_offset = addr as usize - self.phys_base;
        let pte_size = core::mem::size_of::<vmem::PageTableEntry>();
        if let Some(slice) = b.get_mut(byte_offset..byte_offset + pte_size) {
            slice.copy_from_slice(&entry.to_le_bytes()[..pte_size]);
        }
        None
    }

    unsafe fn update_root(&self, impossible: vmem::Void) {
        match impossible {}
    }
}

impl core::convert::AsRef<GuestPageTableBuffer> for GuestPageTableBuffer {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl GuestPageTableBuffer {
    /// Create a new buffer with an initial zeroed root table at
    /// `phys_base`. The returned buffer's current root is `phys_base`;
    /// additional roots can be obtained by calling `alloc_table`.
    pub(crate) fn new(phys_base: usize) -> Self {
        GuestPageTableBuffer {
            buffer: std::cell::RefCell::new(vec![0u8; PAGE_TABLE_SIZE]),
            phys_base,
            root: std::cell::Cell::new(phys_base as u64),
        }
    }

    /// Switch the active root. `addr` must have been obtained either
    /// as the initial root GPA (`phys_base`) or via `alloc_table`.
    pub(crate) fn set_root(&self, addr: u64) {
        self.root.set(addr);
    }

    /// GPA of the initial root allocated by `new`.
    pub(crate) fn initial_root(&self) -> u64 {
        self.phys_base as u64
    }

    #[cfg(test)]
    #[allow(dead_code)]
    pub(crate) fn size(&self) -> usize {
        self.buffer.borrow().len()
    }

    pub(crate) fn into_bytes(self) -> Box<[u8]> {
        self.buffer.into_inner().into_boxed_slice()
    }
}

impl<S> SandboxMemoryManager<S>
where
    S: SharedMemory,
{
    /// Create a new `SandboxMemoryManager` with the given parameters
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn new(
        layout: SandboxMemoryLayout,
        shared_mem: SnapshotSharedMemory<S>,
        scratch_mem: S,
        next_action: NextAction,
    ) -> Self {
        Self {
            layout,
            shared_mem,
            scratch_mem,
            next_action,
            original_entrypoint: 0,
            abort_buffer: Vec::new(),
            execution_mode: ExecutionMode::Unrestricted,
            snapshot_count: 0,
            g2h_consumer: None,
            h2g_consumer: None,
            next_guest_cid: 1,
        }
    }

    /// Get mutable access to the abort buffer
    pub(crate) fn get_abort_buffer_mut(&mut self) -> &mut Vec<u8> {
        &mut self.abort_buffer
    }
}

impl SandboxMemoryManager<ExclusiveSharedMemory> {
    pub(crate) fn from_snapshot(s: &Snapshot) -> Result<Self> {
        let layout = *s.layout();
        let shared_mem = s.memory().to_mgr_snapshot_mem()?;
        let scratch_mem = ExclusiveSharedMemory::new(s.layout().get_scratch_size())?;
        let next_action = s.next_action();
        let mut mgr = Self::new(layout, shared_mem, scratch_mem, next_action);
        mgr.original_entrypoint = s.original_entrypoint();
        // Inherit the snapshot's generation number for the same
        // reason `restore_snapshot` does: the guest-visible counter
        // reflects "which snapshot is the sandbox currently a clone
        // of", not "how many snapshots this partition has taken".
        mgr.snapshot_count = s.snapshot_generation();
        Ok(mgr)
    }

    /// Wraps ExclusiveSharedMemory::build
    // Morally, this should not have to be a Result: this operation is
    // infallible. The source of the Result is
    // update_scratch_bookkeeping(), which calls functions that can
    // fail due to bounds checks (which are statically known to be ok
    // in this situation) or due to failing to take the scratch shared
    // memory lock, but the scratch shared memory is built in this
    // function, its lock does not escape before the end of the
    // function, and the lock is taken by no other code path, so we
    // know it is not contended.
    pub fn build(
        self,
    ) -> Result<(
        SandboxMemoryManager<HostSharedMemory>,
        SandboxMemoryManager<GuestSharedMemory>,
    )> {
        let (hshm, gshm) = self.shared_mem.build();
        let (hscratch, gscratch) = self.scratch_mem.build();
        let mut host_mgr = SandboxMemoryManager {
            shared_mem: hshm,
            scratch_mem: hscratch,
            layout: self.layout,
            next_action: self.next_action,
            original_entrypoint: self.original_entrypoint,
            abort_buffer: self.abort_buffer,
            execution_mode: self.execution_mode,
            snapshot_count: self.snapshot_count,
            g2h_consumer: None,
            h2g_consumer: None,
            next_guest_cid: self.next_guest_cid,
        };
        let guest_mgr = SandboxMemoryManager {
            shared_mem: gshm,
            scratch_mem: gscratch,
            layout: self.layout,
            next_action: self.next_action,
            original_entrypoint: self.original_entrypoint,
            abort_buffer: Vec::new(), // Guest doesn't need abort buffer
            execution_mode: self.execution_mode,
            snapshot_count: self.snapshot_count,
            g2h_consumer: None,
            h2g_consumer: None,
            next_guest_cid: self.next_guest_cid,
        };
        host_mgr.update_scratch_bookkeeping()?;

        if matches!(host_mgr.next_action, NextAction::Initialise(_)) {
            let cp = MailboxValue::CheckpointPending.as_bytes();
            let mbx = host_mgr.layout.get_transport_arena().mbx_offset();

            host_mgr.scratch_mem.copy_from_slice(cp, mbx)?;
            host_mgr.create_virtq_consumers()?;
        }

        Ok((host_mgr, guest_mgr))
    }
}

impl SandboxMemoryManager<HostSharedMemory> {
    /// Create a snapshot with the given mapped regions.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn snapshot(
        &mut self,
        mapped_regions: Vec<MemoryRegion>,
        root_pt_gpas: &[u64],
        rsp_gva: u64,
        sregs: CommonSpecialRegisters,
        #[cfg(target_arch = "x86_64")] msrs: Vec<crate::hypervisor::regs::MsrEntry>,
        next_action: NextAction,
        host_functions: HostFunctionDetails,
    ) -> Result<Snapshot> {
        let virtq = match (&self.g2h_consumer, &self.h2g_consumer) {
            (Some(_), Some(_)) => Some(VirtqSnapshot::capture(&self.layout, &self.scratch_mem)?),
            (None, None) => None,
            _ => return Err(new_error!("virtqueue consumer ownership is incomplete")),
        };

        let snapshot = Snapshot::new(
            &mut self.shared_mem,
            &mut self.scratch_mem,
            self.layout,
            crate::mem::exe::LoadInfo::dummy(),
            mapped_regions,
            root_pt_gpas,
            rsp_gva,
            sregs,
            #[cfg(target_arch = "x86_64")]
            msrs,
            next_action,
            self.original_entrypoint,
            self.snapshot_count + 1,
            host_functions,
            virtq,
        )?;
        self.snapshot_count = snapshot.snapshot_generation();
        Ok(snapshot)
    }

    /// Create host consumers before the guest initializes the transport.
    ///
    /// The consumers begin at cursor zero and observe descriptors published
    /// during the first guest entry.
    fn create_virtq_consumers(&mut self) -> Result<()> {
        if self.g2h_consumer.is_some() || self.h2g_consumer.is_some() {
            return Err(new_error!("virtqueue consumers already exist"));
        }

        let (g2h, h2g) = virtq::create_consumers(&self.layout, &self.scratch_mem)?;
        self.g2h_consumer = Some(g2h);
        self.h2g_consumer = Some(h2g);
        Ok(())
    }

    /// Restore admitted ring images into this scratch mapping.
    pub(crate) fn restore_virtq(&mut self, snapshot: &VirtqSnapshot) -> Result<()> {
        if self.g2h_consumer.is_some() || self.h2g_consumer.is_some() {
            return Err(new_error!("virtqueue consumers are already attached"));
        }

        let (g2h, h2g) = snapshot.restore(&self.layout, &self.scratch_mem)?;
        self.g2h_consumer = Some(g2h);
        self.h2g_consumer = Some(h2g);
        Ok(())
    }

    /// Write a guest function call into the H2G virtqueue.
    #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn write_guest_function_call(&mut self, call: &FunctionCall) -> Result<u32> {
        let cid = self.next_guest_cid;
        let params = call.parameters.as_deref().unwrap_or_default();
        let cap = estimate_flatbuffer_capacity(&call.function_name, params);

        let mut builder = FlatBufferBuilder::with_capacity(cap);
        let mut externals = ExternalValues::new();

        let control = call.encode(&mut builder, &mut externals)?;

        let Some(msg) = EncodedMessage::new(MsgKind::Request, cid, control, externals) else {
            return Err(new_error!("H2G request exceeds the wire payload limit"));
        };

        self.write_h2g_message(&msg)?;

        self.next_guest_cid = cid.wrapping_add(1);
        if self.next_guest_cid == 0 {
            self.next_guest_cid = 1;
        }

        Ok(cid)
    }

    fn write_h2g_message(&mut self, message: &EncodedMessage<'_>) -> Result<()> {
        let consumer = self.h2g_consumer.as_mut().ok_or_else(|| {
            HyperlightError::TransportError("H2G consumer is not attached".into())
        })?;

        let buffer_size = self.layout.get_h2g_buffer_size();
        let buffer_count = message.total_len().div_ceil(buffer_size);

        // Keep a buffer for a control call that releases retained external bytes.
        let control_reserve = usize::from(message.external_len() != 0);

        // H2G receive buffers are writable-only, so any readable payload is malformed.
        let maybe_buffers = consumer
            .poll_batch(buffer_count, control_reserve, 0)
            .map_err(|error| {
                HyperlightError::TransportError(format!("H2G poll failed: {error}"))
            })?;

        let Some(buffers) = maybe_buffers else {
            return Err(new_error!(
                "H2G capacity cannot provide {buffer_count} buffers with {control_reserve} spare"
            ));
        };

        // The message is a contiguous sequence of bytes, but the buffers are a chain of possibly
        // non contiguous slices. Write the message into the buffers in order, advancing the message
        // cursor as we go.
        let mut message = message.as_buf();

        for (recv, reply) in buffers {
            let ReplyChain::Writable(mut buffer) = reply else {
                return Err(HyperlightError::TransportError(
                    "H2G receive buffer is not writable".into(),
                ));
            };

            if buffer.desc_count() != 1 || buffer.capacity() != buffer_size {
                return Err(HyperlightError::TransportError(
                    "H2G receive buffer has an invalid shape".into(),
                ));
            }

            while message.has_remaining() && buffer.remaining() != 0 {
                let written = buffer.write(message.chunk()).map_err(|err| {
                    HyperlightError::TransportError(format!("H2G write failed: {err}"))
                })?;

                message.advance(written);
            }

            consumer.complete(recv, buffer).map_err(|err| {
                HyperlightError::TransportError(format!("H2G completion failed: {err}"))
            })?;
        }

        debug_assert!(!message.has_remaining());
        Ok(())
    }

    /// Read a guest function result from the G2H virtqueue.
    #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn read_h2g_result_from_g2h(&mut self, cid: u32) -> Result<FunctionCallResult> {
        let max_recv_len = self.layout.get_g2h_queue_dims().pool_len();

        let Some(consumer) = self.g2h_consumer.as_mut() else {
            return Err(HyperlightError::TransportError(
                "G2H consumer is not attached".into(),
            ));
        };

        loop {
            let maybe_next = consumer.poll(max_recv_len).map_err(|err| {
                HyperlightError::TransportError(format!("G2H poll failed: {err}"))
            })?;

            let Some((mut recv, reply)) = maybe_next else {
                return Err(HyperlightError::TransportError(
                    "G2H has no guest function result after halt".into(),
                ));
            };

            let header = virtq::read_message_header(&mut recv).map_err(|err| {
                HyperlightError::TransportError(format!("Failed to read G2H result header: {err}"))
            })?;

            if !matches!(&reply, ReplyChain::Ack(_)) {
                return Err(HyperlightError::TransportError(
                    "G2H result entry has writable buffers".into(),
                ));
            }

            match header.kind {
                MsgKind::Log => {
                    if header.cid != 0 {
                        return Err(HyperlightError::TransportError(
                            "G2H log has a correlation ID".into(),
                        ));
                    }

                    let log = virtq::read_guest_log_data(&mut recv).map_err(|err| {
                        HyperlightError::TransportError(format!("Failed to read G2H log: {err}"))
                    })?;

                    consumer.complete(recv, reply).map_err(|err| {
                        HyperlightError::TransportError(format!(
                            "Failed to complete G2H log: {err}"
                        ))
                    })?;

                    crate::sandbox::outb::emit_guest_log(&log);
                }
                MsgKind::Response => {
                    if header.cid != cid {
                        return Err(HyperlightError::TransportError(
                            "G2H guest function result correlation ID mismatch".into(),
                        ));
                    }

                    let result = virtq::read_guest_function_call_result(&mut recv);
                    consumer.complete(recv, reply).map_err(|err| {
                        HyperlightError::TransportError(format!(
                            "Failed to complete G2H guest function result: {err}"
                        ))
                    })?;

                    return result.map_err(|err| {
                        HyperlightError::TransportError(format!(
                            "Failed to decode G2H guest function result: {err}"
                        ))
                    });
                }
                kind => {
                    return Err(HyperlightError::TransportError(format!(
                        "Expected G2H guest function result, got {kind:?}"
                    )));
                }
            }
        }
    }

    /// Publish an internal request for guest-side snapshot canonicalization.
    ///
    /// The pending marker distinguishes a completed checkpoint from an early halt.
    pub(crate) fn begin_snapshot_checkpoint(&mut self) -> Result<()> {
        let offset = self.layout.get_transport_arena().mbx_offset();
        let cp = MailboxValue::CheckpointPending.as_bytes();
        self.scratch_mem.copy_from_slice(cp, offset)?;

        let message = EncodedMessage::new_snapshot_cp();
        self.write_h2g_message(&message)
    }

    /// Reset consumers and require the guest's completion status.
    pub(crate) fn finish_snapshot_checkpoint(&mut self) -> Result<()> {
        let Some(g2h) = self.g2h_consumer.as_mut() else {
            return Err(new_error!("G2H consumer is not attached"));
        };

        let Some(h2g) = self.h2g_consumer.as_mut() else {
            return Err(new_error!("H2G consumer is not attached"));
        };

        g2h.reset()?;
        h2g.reset()?;

        let status = self
            .scratch_mem
            .read::<u64>(self.layout.get_transport_arena().mbx_offset())
            .map_err(|error| HyperlightError::TransportError(error.to_string()))?;

        match MailboxValue::try_from(status) {
            Ok(MailboxValue::CheckpointComplete) => Ok(()),
            Ok(MailboxValue::CheckpointPending) => Err(HyperlightError::TransportError(
                "Guest did not publish snapshot checkpoint status".into(),
            )),
            Err(_) => Err(HyperlightError::TransportError(format!(
                "Guest published invalid snapshot checkpoint status {status:#x}"
            ))),
        }
    }

    /// Restore base memory after the caller checks snapshot compatibility.
    pub(crate) fn restore_snapshot(
        &mut self,
        snapshot: &Snapshot,
    ) -> Result<(
        Option<SnapshotSharedMemory<GuestSharedMemory>>,
        Option<GuestSharedMemory>,
    )> {
        let virtq = snapshot.virtq();

        if virtq.is_none() && matches!(snapshot.next_action(), NextAction::Call(_)) {
            return Err(new_error!(
                "running snapshot has no canonical transport state"
            ));
        }

        self.g2h_consumer = None;
        self.h2g_consumer = None;
        self.execution_mode = ExecutionMode::Unrestricted;

        // A panic during restricted dispatch can skip the mode reset.
        self.execution_mode = ExecutionMode::Unrestricted;

        let gsnapshot = if *snapshot.memory() == self.shared_mem {
            // If the snapshot memory is already the correct memory,
            // which is readonly, don't bother with restoring it,
            // since its contents must be the same.  Note that in the
            // #[cfg(unshared_snapshot_mem)] case, this condition will
            // never be true, since even immediately after a restore,
            // self.shared_mem is a (writable) copy, not the original
            // shared_mem.
            None
        } else {
            let new_snapshot_mem = snapshot.memory().to_mgr_snapshot_mem()?;
            let (hsnapshot, gsnapshot) = new_snapshot_mem.build();
            self.shared_mem = hsnapshot;
            Some(gsnapshot)
        };
        let new_scratch_size = snapshot.layout().get_scratch_size();
        let gscratch = if new_scratch_size == self.scratch_mem.mem_size() {
            // zero_or_replace picks the fastest zeroing strategy for
            // the current platform (see SharedMemory::zero_or_replace).
            self.scratch_mem.zero_or_replace()?
        } else {
            let new_scratch_mem = ExclusiveSharedMemory::new(new_scratch_size)?;
            let (hscratch, gscratch) = new_scratch_mem.build();
            // Even though this destroys the reference to the host
            // side of the old scratch mapping, the VM should still
            // own the reference to the guest side of the old scratch
            // mapping, so it won't actually be deallocated until it
            // has been unmapped from the VM.
            self.scratch_mem = hscratch;
            Some(gscratch)
        };
        self.layout = *snapshot.layout();
        // Inherit the snapshot's own generation number — the
        // guest-visible counter reflects "which snapshot is the
        // sandbox currently a clone of", not "how many restores have
        // happened into this (possibly-reused) partition".
        self.snapshot_count = snapshot.snapshot_generation();
        // Carry the guest ELF entry point across restore so crashdumps
        // report the restored image's entry.
        self.original_entrypoint = snapshot.original_entrypoint();
        self.update_scratch_bookkeeping()?;
        if let Some(virtq) = virtq {
            self.restore_virtq(virtq)?;
        } else if matches!(snapshot.next_action(), NextAction::Initialise(_)) {
            self.scratch_mem.copy_from_slice(
                MailboxValue::CheckpointPending.as_bytes(),
                self.layout.get_transport_arena().mbx_offset(),
            )?;
            self.create_virtq_consumers()?;
        }
        Ok((gsnapshot, gscratch))
    }

    #[inline]
    fn update_scratch_bookkeeping_item(&mut self, offset: u64, value: u64) -> Result<()> {
        let scratch_size = self.scratch_mem.mem_size();
        let base_offset = scratch_size - offset as usize;
        self.scratch_mem
            .write::<u64>(base_offset, value)
            .map_err(From::from)
    }

    pub(crate) fn request_libc_rng_reseed(&mut self, seed: u32) -> Result<()> {
        // Zero means no request. The upper half marks a pending request, and
        // the lower half contains the complete u32 seed.
        self.update_scratch_bookkeeping_item(
            hyperlight_common::layout::SCRATCH_TOP_LIBC_RNG_SEED_OFFSET,
            (1_u64 << 32) | u64::from(seed),
        )
    }

    pub(crate) fn request_guest_log_level_update(
        &mut self,
        log_level: tracing_core::LevelFilter,
    ) -> Result<()> {
        self.update_scratch_bookkeeping_item(
            hyperlight_common::layout::SCRATCH_TOP_GUEST_LOG_LEVEL_OFFSET,
            (hyperlight_common::log_level::GUEST_LOG_FILTER_UPDATE_PENDING)
                | u64::from(GuestLogFilter::from(log_level)),
        )
    }

    fn update_scratch_bookkeeping(&mut self) -> Result<()> {
        use hyperlight_common::layout::*;
        let scratch_size = self.scratch_mem.mem_size();
        self.update_scratch_bookkeeping_item(SCRATCH_TOP_SIZE_OFFSET, scratch_size as u64)?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_ALLOCATOR_OFFSET,
            self.layout.get_first_free_scratch_gpa(),
        )?;
        // Record the GPA of the snapshot's copy of the page tables.
        // The copy lives at the tail of the snapshot blob; we copy it
        // into scratch below so the guest walker can run against
        // mutable, TLB-fresh tables. The guest reads this GPA during
        // CoW fault-in to follow the original PTs on the first write
        // — until the HV can execute directly out of the
        // snapshot-resident PTs, at which point the whole split goes
        // away.
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_SNAPSHOT_PT_GPA_BASE_OFFSET,
            self.layout.get_pt_base_gpa(),
        )?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_SNAPSHOT_GENERATION_OFFSET,
            self.snapshot_count,
        )?;
        // Record the G2H and H2G queue sizes, pool page counts, and buffer sizes.
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_G2H_QUEUE_SIZE_OFFSET,
            u64::try_from(self.layout.get_g2h_queue_size())?,
        )?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_G2H_POOL_PAGES_OFFSET,
            u64::try_from(self.layout.get_g2h_pool_pages())?,
        )?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_G2H_BUFFER_SIZE_OFFSET,
            u64::try_from(self.layout.get_g2h_buffer_size())?,
        )?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_H2G_QUEUE_SIZE_OFFSET,
            u64::try_from(self.layout.get_h2g_queue_size())?,
        )?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_H2G_POOL_PAGES_OFFSET,
            u64::try_from(self.layout.get_h2g_pool_pages())?,
        )?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_H2G_BUFFER_SIZE_OFFSET,
            u64::try_from(self.layout.get_h2g_buffer_size())?,
        )?;

        let transport_arena = self.layout.get_transport_arena();
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_TRANSPORT_ARENA_GPA_OFFSET,
            transport_arena.base_addr(),
        )?;

        // Copy page tables from `shared_mem` into scratch. PT bytes
        // are appended to the snapshot blob at build time and live
        // just past the end of the guest-visible KVM slot (see
        // `Snapshot::new`). Keeping them outside the KVM slot avoids
        // overlapping with `map_file_cow` regions installed
        // immediately after the snapshot in the guest PA space.
        let snapshot_pt_end = self.shared_mem.mem_size();
        let snapshot_pt_size = self.layout.get_pt_size();
        let snapshot_pt_start =
            snapshot_pt_end - snapshot_pt_size.next_multiple_of(page_size::get());
        self.scratch_mem.with_exclusivity(|scratch| {
            #[cfg(not(unshared_snapshot_mem))]
            let bytes = &self.shared_mem.as_slice()[snapshot_pt_start..snapshot_pt_end];
            #[cfg(unshared_snapshot_mem)]
            let bytes = {
                let mut bytes = vec![0u8; snapshot_pt_size];
                self.shared_mem
                    .copy_to_slice(&mut bytes, snapshot_pt_start)?;
                bytes
            };
            #[allow(clippy::needless_borrow)]
            scratch.copy_from_slice(&bytes, self.layout.get_pt_base_scratch_offset())
        })??;

        Ok(())
    }

    /// Build the list of guest memory regions for a crash dump.
    ///
    /// By default, walks the guest page tables to discover
    /// GVA→GPA mappings and translates them to host-backed regions.
    #[cfg(crashdump)]
    pub(crate) fn get_guest_memory_regions(
        &mut self,
        root_pt: u64,
        mmap_regions: &[MemoryRegion],
    ) -> Result<Vec<CrashDumpRegion>> {
        use crate::sandbox::snapshot::SharedMemoryPageTableBuffer;

        let len = hyperlight_common::layout::SCRATCH_TOP_GVA;

        let regions = self.shared_mem.with_contents(|snapshot| {
            self.scratch_mem.with_contents(|scratch| {
                let pt_buf =
                    SharedMemoryPageTableBuffer::new(snapshot, scratch, self.layout, root_pt);

                let mappings: Vec<_> =
                    unsafe { hyperlight_common::vmem::virt_to_phys(&pt_buf, 0, len as u64) }
                        .collect();

                if mappings.is_empty() {
                    return Err(new_error!("No page table mappings found (len {len})",));
                }

                let mut regions: Vec<CrashDumpRegion> = Vec::new();
                for mapping in &mappings {
                    let virt_base = mapping.virt_base as usize;
                    let virt_end = (mapping.virt_base + mapping.len) as usize;

                    if let Some(resolved) = self.layout.resolve_gpa(mapping.phys_base, mmap_regions)
                    {
                        let (flags, region_type) = mapping_kind_to_flags(&mapping.kind);
                        let resolved = resolved.with_memories(snapshot, scratch);
                        let contents = resolved.as_ref();
                        let host_base = contents.as_ptr() as usize;
                        let host_len = (mapping.len as usize).min(contents.len());

                        if try_coalesce_region(&mut regions, virt_base, virt_end, host_base, flags)
                        {
                            continue;
                        }

                        regions.push(CrashDumpRegion {
                            guest_region: virt_base..virt_end,
                            host_region: host_base..host_base + host_len,
                            flags,
                            region_type,
                        });
                    }
                }

                Ok(regions)
            })
        })???;

        Ok(regions)
    }

    /// Read guest memory at a Guest Virtual Address (GVA) by walking the
    /// page tables to translate GVA → GPA, then reading from the correct
    /// backing memory (shared_mem or scratch_mem).
    ///
    /// This is necessary because with Copy-on-Write (CoW) the guest's
    /// virtual pages are backed by physical pages in the scratch
    /// region rather than being identity-mapped.
    ///
    /// # Arguments
    /// * `gva` - The Guest Virtual Address to read from
    /// * `len` - The number of bytes to read
    /// * `root_pt` - The root page table physical address (CR3)
    #[cfg(feature = "trace_guest")]
    pub(crate) fn read_guest_memory_by_gva(
        &mut self,
        gva: u64,
        len: usize,
        root_pt: u64,
    ) -> Result<Vec<u8>> {
        use hyperlight_common::vmem::PAGE_SIZE;

        use crate::sandbox::snapshot::{SharedMemoryPageTableBuffer, access_gpa};

        self.shared_mem.with_contents(|snap| {
            self.scratch_mem.with_contents(|scratch| {
                let pt_buf = SharedMemoryPageTableBuffer::new(snap, scratch, self.layout, root_pt);

                // Walk page tables to get all mappings that cover the GVA range
                let mappings: Vec<_> = unsafe {
                    hyperlight_common::vmem::virt_to_phys(&pt_buf, gva, len as u64)
                }
                .collect();

                if mappings.is_empty() {
                    return Err(new_error!(
                        "No page table mappings found for GVA {:#x} (len {})",
                        gva,
                        len,
                    ));
                }

                // Resulting vector of bytes to return
                let mut result = Vec::with_capacity(len);
                let mut current_gva = gva;

                for mapping in &mappings {
                    // The page table walker should only return valid mappings
                    // that cover our current read position.
                    if mapping.virt_base > current_gva {
                        return Err(new_error!(
                            "Page table walker returned mapping with virt_base {:#x} > current read position {:#x}",
                            mapping.virt_base,
                            current_gva,
                        ));
                    }

                    // Calculate the offset within this page where to start copying
                    let page_offset = (current_gva - mapping.virt_base) as usize;

                    let bytes_remaining = len - result.len();
                    let available_in_page = PAGE_SIZE - page_offset;
                    let bytes_to_copy = bytes_remaining.min(available_in_page);

                    // Translate the GPA to host memory
                    let gpa = mapping.phys_base + page_offset as u64;
                    let (mem, offset) = access_gpa(snap, scratch, self.layout, gpa)
                        .ok_or_else(|| {
                            new_error!(
                                "Failed to resolve GPA {:#x} to host memory (GVA {:#x})",
                                gpa,
                                gva
                            )
                        })?;

                    let slice = mem
                        .get(offset..offset + bytes_to_copy)
                        .ok_or_else(|| {
                            new_error!(
                                "GPA {:#x} resolved to out-of-bounds host offset {} (need {} bytes)",
                                gpa,
                                offset,
                                bytes_to_copy
                            )
                        })?;

                    result.extend_from_slice(slice);
                    current_gva += bytes_to_copy as u64;
                }

                if result.len() != len {
                    tracing::error!(
                        "Page table walker returned mappings that don't cover the full requested length: got {}, expected {}",
                        result.len(),
                        len,
                    );
                    return Err(new_error!(
                        "Could not read full GVA range: got {} of {} bytes {:?}",
                        result.len(),
                        len,
                        mappings
                    ));
                }

                Ok(result)
            })
        })??
    }
}

#[cfg(test)]
mod tests {
    use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCallType;
    use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType};
    use hyperlight_common::transport::{
        MsgHeader, SIZE_PREFIX_LEN, size_prefix_payload_len, size_prefixed_len,
    };
    use hyperlight_common::virtq::DescFlags;
    #[cfg(target_arch = "x86_64")]
    use hyperlight_testing::sandbox_sizes::{LARGE_HEAP_SIZE, MEDIUM_HEAP_SIZE, SMALL_HEAP_SIZE};
    #[cfg(target_arch = "x86_64")]
    use hyperlight_testing::simple_guest_as_pathbuf;

    use super::*;
    #[cfg(target_arch = "x86_64")]
    use crate::GuestBinary;
    use crate::mem::virtq::tests::{H2G_BUFFER_SIZE, SCRATCH_SIZE, TestCase, memory_layout};
    #[cfg(target_arch = "x86_64")]
    use crate::sandbox::SandboxConfiguration;

    fn manager(case: &TestCase) -> SandboxMemoryManager<HostSharedMemory> {
        let host_page_size = page_size::get();

        #[cfg(not(unshared_snapshot_mem))]
        let shared_mem =
            ReadonlySharedMemory::from_bytes(&vec![0; host_page_size], host_page_size).unwrap();

        #[cfg(unshared_snapshot_mem)]
        let shared_mem = ExclusiveSharedMemory::new(host_page_size)
            .unwrap()
            .build()
            .0;

        let mut mgr = SandboxMemoryManager::new(
            memory_layout(),
            shared_mem,
            case.scratch.clone(),
            NextAction::None,
        );

        mgr.h2g_consumer = Some(case.h2g_consumer());
        mgr
    }

    fn h2g_call(bytes: usize) -> FunctionCall {
        let params = (bytes != 0).then(|| vec![ParameterValue::VecBytes(vec![0xa5; bytes])]);
        FunctionCall::new(
            "call".to_string(),
            params,
            FunctionCallType::Guest,
            ReturnType::Void,
        )
    }

    #[test]
    fn rejects_invalid_h2g_descriptors() {
        for (len, expected) in [
            (H2G_BUFFER_SIZE as u32, "Payload data too large"),
            (0, "not writable"),
        ] {
            let case = TestCase::new();
            let mut mgr = manager(&case);
            let mut desc = case.h2g_desc(0);

            desc.flags &= !DescFlags::WRITE.bits();
            desc.len = len;
            case.set_h2g_desc(0, desc);

            let error = mgr.write_guest_function_call(&h2g_call(0)).unwrap_err();

            assert!(error.to_string().contains(expected), "{error:#}");
            assert!(error.is_poison_error());
            assert!(matches!(error, HyperlightError::TransportError(_)));
        }
    }

    #[test]
    fn partial_h2g_write_is_fatal() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        let mut desc = case.h2g_desc(1);

        desc.addr = hyperlight_common::layout::scratch_base_gva(SCRATCH_SIZE) + SCRATCH_SIZE as u64;
        case.set_h2g_desc(1, desc);

        let error = mgr
            .write_guest_function_call(&h2g_call(H2G_BUFFER_SIZE + 1024))
            .unwrap_err();

        assert!(error.to_string().contains("Memory write"), "{error:#}");
        assert!(error.is_poison_error());
        assert!(matches!(error, HyperlightError::TransportError(_)));
        assert_eq!(mgr.h2g_consumer.as_ref().unwrap().used_cursor().head(), 1);
    }

    #[test]
    fn insufficient_h2g_capacity_rolls_back() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        let cursor = mgr.h2g_consumer.as_ref().unwrap().avail_cursor();

        let error = mgr
            .write_guest_function_call(&h2g_call(H2G_BUFFER_SIZE * 4))
            .unwrap_err();

        assert!(error.to_string().contains("H2G capacity"), "{error:#}");
        assert!(!error.is_poison_error());
        assert_eq!(mgr.h2g_consumer.as_ref().unwrap().avail_cursor(), cursor);
        assert_eq!(mgr.write_guest_function_call(&h2g_call(0)).unwrap(), 1);
    }

    #[test]
    fn missing_g2h_result_is_fatal() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        mgr.g2h_consumer = Some(case.g2h_consumer());

        let Err(error) = mgr.read_h2g_result_from_g2h(1) else {
            panic!("expected missing G2H result");
        };

        assert!(
            error
                .to_string()
                .contains("G2H has no guest function result")
        );
        assert!(error.is_poison_error());
        assert!(matches!(error, HyperlightError::TransportError(_)));
    }

    #[test]
    fn writes_dense_h2g_request_and_reserves_control_buffer() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        let external_len = H2G_BUFFER_SIZE * 2;
        let buffers: Vec<_> = (0..4).map(|index| case.h2g_desc(index).addr).collect();

        let cid = mgr
            .write_guest_function_call(&h2g_call(external_len))
            .unwrap();

        let used = mgr.h2g_consumer.as_ref().unwrap().avail_cursor().head();
        let wire: Vec<u8> = (0..used)
            .flat_map(|index| case.h2g_buffer(index, buffers[index as usize]))
            .collect();

        let header = MsgHeader::from_bytes(&wire[..MsgHeader::SIZE]).unwrap();
        assert_eq!(header.kind, MsgKind::Request);
        assert_eq!(header.cid, cid);
        assert_eq!(header.payload_len as usize, wire.len() - MsgHeader::SIZE);

        let control =
            size_prefix_payload_len(&wire[MsgHeader::SIZE..MsgHeader::SIZE + SIZE_PREFIX_LEN])
                .unwrap();

        let control_len = size_prefixed_len(control).unwrap();
        let external = &wire[MsgHeader::SIZE + control_len..];
        assert_eq!(external, vec![0xa5; external_len]);

        let cursor = mgr.h2g_consumer.as_ref().unwrap().avail_cursor();
        let error = mgr.write_guest_function_call(&h2g_call(1)).unwrap_err();

        assert!(error.to_string().contains("H2G capacity"), "{error:#}");
        assert_eq!(mgr.h2g_consumer.as_ref().unwrap().avail_cursor(), cursor);
        assert_eq!(mgr.write_guest_function_call(&h2g_call(0)).unwrap(), 2);
    }

    #[test]
    fn writes_header_only_snapshot_checkpoint() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        let buffer = case.h2g_desc(0).addr;

        let mbx = mgr.layout.get_transport_arena().mbx_offset();
        let cp = MailboxValue::CheckpointComplete.as_bytes();

        mgr.scratch_mem.copy_from_slice(cp, mbx).unwrap();
        mgr.begin_snapshot_checkpoint().unwrap();

        let wire = case.h2g_buffer(0, buffer);
        let header = MsgHeader::from_bytes(&wire).unwrap();

        assert_eq!(wire.len(), MsgHeader::SIZE);
        assert_eq!(header.kind, MsgKind::SnapshotCheckpoint);
        assert_eq!(header.cid, 0);
        assert_eq!(header.payload_len, 0);
        assert_eq!(mgr.next_guest_cid, 1);

        assert_eq!(
            MailboxValue::try_from(mgr.scratch_mem.read::<u64>(mbx).unwrap()).unwrap(),
            MailboxValue::CheckpointPending
        );
    }

    #[test]
    fn incomplete_snapshot_checkpoint_is_fatal() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        mgr.g2h_consumer = Some(case.g2h_consumer());
        mgr.begin_snapshot_checkpoint().unwrap();

        let error = mgr.finish_snapshot_checkpoint().unwrap_err();

        assert!(matches!(error, HyperlightError::TransportError(_)));
        assert!(error.is_poison_error());
    }

    #[test]
    fn reads_completed_snapshot_checkpoint_status() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        mgr.g2h_consumer = Some(case.g2h_consumer());
        mgr.begin_snapshot_checkpoint().unwrap();
        let mbx = mgr.layout.get_transport_arena().mbx_offset();
        mgr.scratch_mem
            .copy_from_slice(MailboxValue::CheckpointComplete.as_bytes(), mbx)
            .unwrap();

        mgr.finish_snapshot_checkpoint().unwrap();
        let consumer = mgr.h2g_consumer.as_ref().unwrap();
        assert_eq!(consumer.avail_cursor().head(), 0);
        assert_eq!(consumer.used_cursor().head(), 0);
    }

    #[test]
    fn invalid_checkpoint_status_is_fatal() {
        for status in [2, 3, 0xa000, u64::MAX - 1, u64::MAX] {
            let queue = TestCase::new();
            let mut mgr = manager(&queue);
            mgr.g2h_consumer = Some(queue.g2h_consumer());
            let mbx = mgr.layout.get_transport_arena().mbx_offset();
            mgr.scratch_mem.write::<u64>(mbx, status).unwrap();
            let error = mgr.finish_snapshot_checkpoint().unwrap_err();

            assert!(matches!(error, HyperlightError::TransportError(_)));
            assert!(error.is_poison_error(), "{error}");
        }
    }

    #[test]
    fn guest_cid_wraps_without_zero() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        mgr.next_guest_cid = u32::MAX;

        assert_eq!(
            mgr.write_guest_function_call(&h2g_call(0)).unwrap(),
            u32::MAX
        );
        assert_eq!(mgr.write_guest_function_call(&h2g_call(0)).unwrap(), 1);
    }

    #[test]
    fn cloning_preserves_guest_cids_without_consumers() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        mgr.g2h_consumer = Some(case.g2h_consumer());
        mgr.write_guest_function_call(&h2g_call(0)).unwrap();

        let cloned = mgr.clone();

        assert!(cloned.g2h_consumer.is_none());
        assert!(cloned.h2g_consumer.is_none());
        assert_eq!(cloned.next_guest_cid, 2);
        assert!(mgr.g2h_consumer.is_some());
        assert!(mgr.h2g_consumer.is_some());
    }

    #[test]
    fn restoring_transport_preserves_guest_cids() {
        let case = TestCase::new();
        let mut mgr = manager(&case);
        mgr.g2h_consumer = Some(case.g2h_consumer());
        let captured = VirtqSnapshot::capture(&mgr.layout, &mgr.scratch_mem).unwrap();
        assert_eq!(mgr.write_guest_function_call(&h2g_call(0)).unwrap(), 1);

        mgr.g2h_consumer = None;
        mgr.h2g_consumer = None;
        mgr.restore_virtq(&captured).unwrap();

        assert_eq!(mgr.write_guest_function_call(&h2g_call(0)).unwrap(), 2);
    }

    /// Build a snapshot for the given configuration and verify the
    /// NULL page is not mapped in its page tables.
    #[cfg(target_arch = "x86_64")]
    fn verify_page_tables(name: &str, config: SandboxConfiguration) {
        let path = simple_guest_as_pathbuf();
        let snapshot = Snapshot::from_env(GuestBinary::FilePath(path), config)
            .unwrap_or_else(|e| panic!("{}: failed to create snapshot: {}", name, e));

        // Verify NULL page (0x0) is NOT mapped
        assert!(
            unsafe { hyperlight_common::vmem::virt_to_phys(&snapshot, 0, 1) }
                .next()
                .is_none(),
            "{}: NULL page (0x0) should NOT be mapped",
            name
        );
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn test_page_tables_for_various_configurations() {
        let test_cases: [(&str, SandboxConfiguration); 4] = [
            ("default", { SandboxConfiguration::default() }),
            ("small (8MB heap)", {
                let mut cfg = SandboxConfiguration::default();
                cfg.set_heap_size(SMALL_HEAP_SIZE);
                cfg
            }),
            ("medium (64MB heap)", {
                let mut cfg = SandboxConfiguration::default();
                cfg.set_heap_size(MEDIUM_HEAP_SIZE);
                cfg
            }),
            ("large (256MB heap)", {
                let mut cfg = SandboxConfiguration::default();
                cfg.set_heap_size(LARGE_HEAP_SIZE);
                cfg.set_scratch_size(0x100000);
                cfg
            }),
        ];

        for (name, config) in test_cases {
            verify_page_tables(name, config);
        }
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn build_creates_virtq_consumers_before_initialization() {
        let path = simple_guest_as_pathbuf();
        let bin = GuestBinary::FilePath(path);
        let config = SandboxConfiguration::default();

        let snapshot = Snapshot::from_env(bin, config).unwrap();

        let mgr = SandboxMemoryManager::from_snapshot(&snapshot).unwrap();
        let (mgr, _) = mgr.build().unwrap();

        assert!(mgr.g2h_consumer.is_some());
        assert!(mgr.h2g_consumer.is_some());
    }
}