hyperlight-host 0.19.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
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
// 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, 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, SnapshotMemoryBacking};
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
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BackingSource {
    /// Snapshot layer index.
    Snapshot(usize),
    Scratch,
    /// Dynamic region index.
    Dynamic(usize),
}

/// A guest physical range resolved to its backing memory.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GuestBacking {
    pub(crate) source: BackingSource,
    pub(crate) offset: usize,
}

/// Guest physical memory with scratch locked for exclusive access.
pub(crate) struct GuestPhysicalMemoryView<'a> {
    snapshot: &'a SnapshotMemoryBacking<HostSharedMemory>,
    scratch: &'a [u8],
    dynamic: &'a [MemoryRegion],
    layout: SandboxMemoryLayout,
}

impl<'a> GuestPhysicalMemoryView<'a> {
    /// Runs `f` with a view of `snapshot`, `scratch` and `dynamic`. Scratch
    /// stays locked until `f` returns.
    pub(crate) fn with_memory<T>(
        snapshot: &SnapshotMemoryBacking<HostSharedMemory>,
        scratch: &HostSharedMemory,
        dynamic: &[MemoryRegion],
        layout: SandboxMemoryLayout,
        f: impl FnOnce(&GuestPhysicalMemoryView<'_>) -> Result<T>,
    ) -> Result<T> {
        scratch.with_exclusive_contents(|scratch| {
            f(&GuestPhysicalMemoryView {
                snapshot,
                scratch,
                dynamic,
                layout,
            })
        })?
    }

    pub(crate) fn snapshot(&self) -> &'a SnapshotMemoryBacking<HostSharedMemory> {
        self.snapshot
    }

    pub(crate) fn resolve(&self, gpa: u64, len: usize) -> Option<GuestBacking> {
        let end = gpa.checked_add(u64::try_from(len).ok()?)?;
        let scratch_start =
            hyperlight_common::layout::scratch_base_gpa(self.layout.get_scratch_size());
        let scratch_end = scratch_start.checked_add(self.layout.get_scratch_size() as u64)?;
        if scratch_start <= gpa && end <= scratch_end {
            return Some(GuestBacking {
                source: BackingSource::Scratch,
                offset: usize::try_from(gpa - scratch_start).ok()?,
            });
        }
        if let Some((layer_index, offset)) = self.snapshot.resolve(gpa, len) {
            return Some(GuestBacking {
                source: BackingSource::Snapshot(layer_index),
                offset,
            });
        }
        self.dynamic
            .iter()
            .enumerate()
            .find_map(|(region_index, region)| {
                let start = u64::try_from(region.guest_region.start).ok()?;
                let region_end = u64::try_from(region.guest_region.end).ok()?;
                if start <= gpa && end <= region_end {
                    Some(GuestBacking {
                        source: BackingSource::Dynamic(region_index),
                        offset: usize::try_from(gpa - start).ok()?,
                    })
                } else {
                    None
                }
            })
    }

    pub(crate) fn read(&self, gpa: u64, destination: &mut [u8]) -> Result<GuestBacking> {
        let backing = self
            .resolve(gpa, destination.len())
            .ok_or_else(|| new_error!("GPA range is not backed: {gpa:#x}"))?;
        self.read_backing(backing, destination)?;
        Ok(backing)
    }

    pub(crate) fn read_backing(&self, backing: GuestBacking, destination: &mut [u8]) -> Result<()> {
        let offset = backing.offset;
        match backing.source {
            BackingSource::Snapshot(layer_index) => {
                self.snapshot
                    .copy_layer_to_slice(layer_index, destination, offset)?
            }
            BackingSource::Scratch => {
                let source = offset
                    .checked_add(destination.len())
                    .and_then(|end| self.scratch.get(offset..end))
                    .ok_or_else(|| new_error!("scratch read range is out of bounds"))?;
                destination.copy_from_slice(source);
            }
            BackingSource::Dynamic(region_index) => {
                let region = &self.dynamic[region_index];
                #[allow(clippy::useless_conversion)]
                let host_start: usize = region.host_region.start.into();
                #[allow(clippy::useless_conversion)]
                let host_end: usize = region.host_region.end.into();
                let source_end = offset
                    .checked_add(destination.len())
                    .ok_or_else(|| new_error!("dynamic memory read range overflows"))?;
                let host_len = host_end
                    .checked_sub(host_start)
                    .ok_or_else(|| new_error!("dynamic memory host range is invalid"))?;
                if source_end > host_len {
                    return Err(new_error!("dynamic memory read range is out of bounds"));
                }
                let source_start = host_start
                    .checked_add(offset)
                    .ok_or_else(|| new_error!("dynamic memory host address overflows"))?;
                // SAFETY: Dynamic regions come from `Sandbox::map_region`, whose
                // contract keeps them valid and unmodified for the sandbox's
                // lifetime. The checks above bound this read.
                unsafe {
                    std::ptr::copy(
                        source_start as *const u8,
                        destination.as_mut_ptr(),
                        destination.len(),
                    )
                };
            }
        }
        Ok(())
    }

    #[cfg(crashdump)]
    fn host_range(&self, gpa: u64, len: usize) -> Result<std::ops::Range<usize>> {
        let backing = self
            .resolve(gpa, len)
            .ok_or_else(|| new_error!("GPA range is not backed: {gpa:#x}"))?;
        let offset = backing.offset;
        let (base, backing_len) = match backing.source {
            BackingSource::Snapshot(layer_index) => self.snapshot.host_range(layer_index)?,
            BackingSource::Scratch => (self.scratch.as_ptr() as usize, self.scratch.len()),
            BackingSource::Dynamic(region_index) => {
                let region = &self.dynamic[region_index];
                #[allow(clippy::useless_conversion)]
                let start: usize = region.host_region.start.into();
                #[allow(clippy::useless_conversion)]
                let end: usize = region.host_region.end.into();
                (start, end - start)
            }
        };
        let end_offset = offset
            .checked_add(len)
            .filter(|end| *end <= backing_len)
            .ok_or_else(|| new_error!("resolved GPA range is out of bounds"))?;
        let start = base
            .checked_add(offset)
            .ok_or_else(|| new_error!("resolved host address overflows"))?;
        let end = base
            .checked_add(end_offset)
            .ok_or_else(|| new_error!("resolved host address overflows"))?;
        Ok(start..end)
    }
}
#[cfg(any(feature = "mem_profile", feature = "trace_guest", test))]
pub(crate) struct GuestVirtualMemoryReader<'a> {
    memory: &'a GuestPhysicalMemoryView<'a>,
    root_pt: u64,
    cached_page: Option<(u64, u64)>,
}

#[cfg(any(feature = "mem_profile", feature = "trace_guest", test))]
impl<'a> GuestVirtualMemoryReader<'a> {
    fn new(memory: &'a GuestPhysicalMemoryView<'a>, root_pt: u64) -> Self {
        Self {
            memory,
            root_pt,
            cached_page: None,
        }
    }

    fn translate_page(&mut self, page_gva: u64) -> Result<u64> {
        if let Some((cached_gva, cached_gpa)) = self.cached_page
            && cached_gva == page_gva
        {
            return Ok(cached_gpa);
        }

        use crate::sandbox::snapshot::PageTableReader;

        let pt_buf = PageTableReader::new(self.memory, self.root_pt);
        // SAFETY: The vCPU is stopped for this outb, so its page tables cannot
        // change during the walk.
        let mapping = unsafe {
            hyperlight_common::vmem::virt_to_phys(
                &pt_buf,
                page_gva,
                hyperlight_common::vmem::PAGE_SIZE as u64,
            )
        }
        .next();
        // A suppressed read leaves a not-present entry behind, so ask before
        // blaming the guest for an unmapped page.
        pt_buf.finish()?;
        let mapping = mapping.ok_or_else(|| new_error!("GVA page is not mapped: {page_gva:#x}"))?;
        let mapping_offset = page_gva
            .checked_sub(mapping.virt_base)
            .ok_or_else(|| new_error!("page-table mapping starts after requested GVA"))?;
        if mapping
            .len
            .checked_sub(mapping_offset)
            .is_none_or(|len| len < hyperlight_common::vmem::PAGE_SIZE as u64)
        {
            return Err(new_error!(
                "page-table mapping does not cover requested GVA page"
            ));
        }
        let page_gpa = mapping
            .phys_base
            .checked_add(mapping_offset)
            .ok_or_else(|| new_error!("guest physical address overflows"))?;
        self.cached_page = Some((page_gva, page_gpa));
        Ok(page_gpa)
    }

    pub(crate) fn read_exact(&mut self, gva: u64, destination: &mut [u8]) -> Result<()> {
        gva.checked_add(u64::try_from(destination.len())?)
            .ok_or_else(|| new_error!("guest virtual address overflows"))?;
        let mut copied = 0usize;
        while copied < destination.len() {
            let current_gva = gva
                .checked_add(u64::try_from(copied)?)
                .ok_or_else(|| new_error!("guest virtual address overflows"))?;
            let page_gva = current_gva / hyperlight_common::vmem::PAGE_SIZE as u64
                * hyperlight_common::vmem::PAGE_SIZE as u64;
            let page_offset = usize::try_from(current_gva - page_gva)?;
            let chunk_len =
                (destination.len() - copied).min(hyperlight_common::vmem::PAGE_SIZE - page_offset);
            let gpa = self
                .translate_page(page_gva)?
                .checked_add(u64::try_from(page_offset)?)
                .ok_or_else(|| new_error!("guest physical address overflows"))?;
            self.memory
                .read(gpa, &mut destination[copied..copied + chunk_len])?;
            copied += chunk_len;
        }
        Ok(())
    }
}

/// 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,
}

/// Scratch-top slots the host writes and the guest applies and clears on its
/// next entry.
const GUEST_REQUEST_OFFSETS: [u64; 2] = [
    hyperlight_common::layout::SCRATCH_TOP_LIBC_RNG_SEED_OFFSET,
    hyperlight_common::layout::SCRATCH_TOP_GUEST_LOG_LEVEL_OFFSET,
];

/// 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: SnapshotMemoryBacking<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,
{
    /// First GPA available to the guest scratch allocator.
    pub(crate) fn first_free_scratch_gpa(&self) -> u64 {
        self.layout.get_pt_base_gpa() + self.shared_mem.page_table_len() as u64
    }

    /// Create a new `SandboxMemoryManager` with the given parameters
    #[instrument(skip_all, parent = Span::current(), level= "Trace")]
    pub(crate) fn new(
        layout: SandboxMemoryLayout,
        shared_mem: SnapshotMemoryBacking<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 = SnapshotMemoryBacking::from_snapshot(s.snapshot_memory().clone())?;
        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.mbx_scratch_offset();

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

        Ok((host_mgr, guest_mgr))
    }
}

impl SandboxMemoryManager<HostSharedMemory> {
    /// Runs `f` with a view of guest physical memory, including `dynamic`.
    pub(crate) fn with_guest_memory<T>(
        &self,
        dynamic: &[MemoryRegion],
        f: impl FnOnce(&GuestPhysicalMemoryView<'_>) -> Result<T>,
    ) -> Result<T> {
        GuestPhysicalMemoryView::with_memory(
            &self.shared_mem,
            &self.scratch_mem,
            dynamic,
            self.layout,
            f,
        )
    }

    #[cfg(any(feature = "mem_profile", feature = "trace_guest", test))]
    pub(crate) fn with_guest_virtual_memory_reader<T>(
        &self,
        root_pt: u64,
        f: impl FnOnce(&mut GuestVirtualMemoryReader<'_>) -> Result<T>,
    ) -> Result<T> {
        self.with_guest_memory(&[], |memory| {
            f(&mut GuestVirtualMemoryReader::new(memory, root_pt))
        })
    }

    /// 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,
        scratch_size: usize,
    ) -> 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 layout = self.layout;
        let original_entrypoint = self.original_entrypoint;
        let snapshot_generation = self.snapshot_count + 1;
        let snapshot = self.with_guest_memory(&mapped_regions, |memory| {
            Snapshot::new(
                memory,
                layout,
                crate::mem::exe::LoadInfo::dummy(),
                root_pt_gpas,
                rsp_gva,
                sregs,
                #[cfg(target_arch = "x86_64")]
                msrs,
                next_action,
                original_entrypoint,
                snapshot_generation,
                host_functions,
                virtq,
                scratch_size,
            )
        })?;
        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.mbx_scratch_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.mbx_scratch_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}"
            ))),
        }
    }

    fn replace_snapshot_memory(
        &mut self,
        snapshot: &Snapshot,
    ) -> Result<SnapshotMemoryBacking<GuestSharedMemory>> {
        let new_snapshot_mem =
            SnapshotMemoryBacking::from_snapshot(snapshot.snapshot_memory().clone())?;
        let (hsnapshot, gsnapshot) = new_snapshot_mem.build();
        self.shared_mem = hsnapshot;
        Ok(gsnapshot)
    }

    fn apply_snapshot_metadata(&mut self, snapshot: &Snapshot) {
        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();
    }

    /// Installs memory produced by a capture without restoring runtime state.
    ///
    /// A capture with another scratch size moves the scratch base and page
    /// tables. It gets new scratch, which the caller maps.
    pub(crate) fn install_captured_snapshot(
        &mut self,
        snapshot: &Snapshot,
    ) -> Result<(
        SnapshotMemoryBacking<GuestSharedMemory>,
        Option<GuestSharedMemory>,
    )> {
        if snapshot.layout().get_scratch_size() != self.scratch_mem.mem_size() {
            let requests = self.guest_requests()?;
            let memory = self.restore_snapshot(snapshot)?;
            self.set_guest_requests(requests)?;
            return Ok(memory);
        }
        let used_scratch_end = self.used_scratch_end_gpa()?;
        let gsnapshot = self.replace_snapshot_memory(snapshot)?;
        self.apply_snapshot_metadata(snapshot);
        self.update_snapshot_scratch_bookkeeping()?;
        self.zero_freed_scratch(used_scratch_end)?;
        Ok((gsnapshot, None))
    }

    /// The end of the scratch the guest has allocated: its allocator's next
    /// free page. The guest controls that value, so it is held to the
    /// transport arena, where the guest's allocator stops.
    fn used_scratch_end_gpa(&self) -> Result<u64> {
        let offset = self.scratch_mem.mem_size()
            - hyperlight_common::layout::SCRATCH_TOP_ALLOCATOR_OFFSET as usize;
        let end = self.scratch_mem.read::<u64>(offset)?;
        Ok(end.min(self.layout.get_transport_arena().base_addr()))
    }

    /// Bytes of scratch the guest has allocated since the allocator was
    /// last reset, at build, restore or snapshot.
    pub(crate) fn scratch_allocated_bytes(&self) -> Result<u64> {
        Ok(self
            .used_scratch_end_gpa()?
            .saturating_sub(self.first_free_scratch_gpa()))
    }

    /// Zeroes the scratch pages freed by resetting the allocator, up to
    /// `end`, the allocator's end as `used_scratch_end_gpa` read it.
    fn zero_freed_scratch(&mut self, end: u64) -> Result<()> {
        let scratch_base = hyperlight_common::layout::scratch_base_gpa(self.scratch_mem.mem_size());
        let start = self.first_free_scratch_gpa();
        if end <= start {
            return Ok(());
        }
        let start = usize::try_from(start - scratch_base)?;
        let end = usize::try_from(end - scratch_base)?;
        self.scratch_mem
            .with_exclusivity(|scratch| scratch.as_mut_slice()[start..end].fill(0))?;
        Ok(())
    }

    /// Restore base memory after the caller checks snapshot compatibility.
    pub(crate) fn restore_snapshot(
        &mut self,
        snapshot: &Snapshot,
    ) -> Result<(
        SnapshotMemoryBacking<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 = self.replace_snapshot_memory(snapshot)?;
        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.apply_snapshot_metadata(snapshot);
        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.mbx_scratch_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)
    }

    fn guest_requests(&self) -> Result<[u64; 2]> {
        let scratch_size = self.scratch_mem.mem_size();
        let mut values = [0; 2];
        for (value, offset) in values.iter_mut().zip(GUEST_REQUEST_OFFSETS) {
            *value = self
                .scratch_mem
                .read::<u64>(scratch_size - offset as usize)?;
        }
        Ok(values)
    }

    fn set_guest_requests(&mut self, values: [u64; 2]) -> Result<()> {
        for (value, offset) in values.into_iter().zip(GUEST_REQUEST_OFFSETS) {
            self.update_scratch_bookkeeping_item(offset, value)?;
        }
        Ok(())
    }

    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_snapshot_scratch_bookkeeping()?;

        Ok(())
    }

    fn update_snapshot_scratch_bookkeeping(&mut self) -> Result<()> {
        use hyperlight_common::layout::*;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_ALLOCATOR_OFFSET,
            self.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,
        )?;
        self.update_scratch_bookkeeping_item(
            SCRATCH_TOP_HEAP_EXECUTABLE_OFFSET,
            cfg!(feature = "executable_heap") as u64,
        )?;
        // 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 page_tables = self.shared_mem.page_table_bytes();
        let offset = self.layout.get_pt_base_scratch_offset();
        self.scratch_mem
            .with_exclusivity(|scratch| scratch.copy_from_slice(page_tables, 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::PageTableReader;

        let len = hyperlight_common::layout::SCRATCH_TOP_GVA;
        self.with_guest_memory(mmap_regions, |memory| {
            let pt_buf = PageTableReader::new(memory, root_pt);
            let mut regions: Vec<CrashDumpRegion> = Vec::new();
            let mut saw_mapping = false;
            // SAFETY: Crash handling runs with the vCPU stopped, so its page tables
            // cannot change during the walk.
            for mapping in unsafe { hyperlight_common::vmem::virt_to_phys(&pt_buf, 0, len as u64) }
            {
                saw_mapping = true;
                let (flags, region_type) = mapping_kind_to_flags(&mapping.kind);
                let mut mapped = 0usize;
                let mapping_len = usize::try_from(mapping.len)?;
                while mapped < mapping_len {
                    let chunk_len = (mapping_len - mapped).min(hyperlight_common::vmem::PAGE_SIZE);
                    let gpa = mapping
                        .phys_base
                        .checked_add(u64::try_from(mapped)?)
                        .ok_or_else(|| new_error!("crash-dump GPA overflows"))?;
                    let Some(host_region) = memory.host_range(gpa, chunk_len).ok() else {
                        mapped += chunk_len;
                        continue;
                    };
                    let virt_base = usize::try_from(mapping.virt_base)?
                        .checked_add(mapped)
                        .ok_or_else(|| new_error!("crash-dump GVA overflows"))?;
                    let virt_end = virt_base
                        .checked_add(chunk_len)
                        .ok_or_else(|| new_error!("crash-dump GVA range overflows"))?;

                    if !try_coalesce_region(
                        &mut regions,
                        virt_base,
                        virt_end,
                        host_region.start,
                        flags,
                    ) {
                        regions.push(CrashDumpRegion {
                            guest_region: virt_base..virt_end,
                            host_region,
                            flags,
                            region_type,
                        });
                    }
                    mapped += chunk_len;
                }
            }
            if !saw_mapping {
                return Err(new_error!("No page table mappings found (len {len})",));
            }

            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(
        &self,
        gva: u64,
        len: usize,
        root_pt: u64,
    ) -> Result<Vec<u8>> {
        let mut result = vec![0; len];
        self.with_guest_virtual_memory_reader(root_pt, |reader| {
            reader.read_exact(gva, &mut result)
        })?;
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    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;
    use hyperlight_common::vmem::{self, BasicMapping, Mapping, MappingKind, PAGE_SIZE};
    #[cfg(target_arch = "x86_64")]
    use hyperlight_testing::sandbox_sizes::{
        LARGE_SCRATCH_SIZE, MEDIUM_SCRATCH_SIZE, SMALL_SCRATCH_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::layout::SandboxMemoryLayout;
    use crate::mem::memory_region::MemoryRegionType;
    use crate::mem::shared_mem::{ExclusiveSharedMemory, ReadonlySharedMemory};
    use crate::mem::virtq::tests::{H2G_BUFFER_SIZE, SCRATCH_SIZE, TestCase, memory_layout};
    use crate::sandbox::SandboxConfiguration;
    #[cfg(target_arch = "x86_64")]
    use crate::sandbox::snapshot::Snapshot;
    use crate::sandbox::snapshot::memory::tests::flat_memory;
    use crate::sandbox::snapshot::{SnapshotBlob, SnapshotMemory};

    fn manager(case: &TestCase) -> SandboxMemoryManager<HostSharedMemory> {
        let host_page_size = page_size::get();
        let layout = memory_layout();
        let snapshot = Arc::new(flat_memory(
            &vec![0; host_page_size],
            &[0; PAGE_SIZE],
            SandboxMemoryLayout::BASE_ADDRESS as u64,
            hyperlight_common::layout::scratch_base_gpa(layout.get_scratch_size()),
        ));

        let mut mgr = SandboxMemoryManager::new(
            layout,
            SnapshotMemoryBacking::from_snapshot(snapshot)
                .unwrap()
                .build()
                .0,
            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.mbx_scratch_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.mbx_scratch_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.mbx_scratch_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 (8MiB scratch)", {
                let mut cfg = SandboxConfiguration::default();
                cfg.set_scratch_size(SMALL_SCRATCH_SIZE);
                cfg
            }),
            ("medium (64MiB scratch)", {
                let mut cfg = SandboxConfiguration::default();
                cfg.set_scratch_size(MEDIUM_SCRATCH_SIZE);
                cfg
            }),
            ("large (256MiB scratch)", {
                let mut cfg = SandboxConfiguration::default();
                cfg.set_scratch_size(LARGE_SCRATCH_SIZE);
                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());
    }

    #[test]
    fn snapshot_memory_backing_reads_across_layers() {
        let host_page_size = page_size::get();
        let base = SandboxMemoryLayout::BASE_ADDRESS as u64;
        let scratch = base + (4 * host_page_size) as u64;
        let layer = |gpa_start: u64, value: u8| {
            let data_len = host_page_size;
            let mut storage = ExclusiveSharedMemory::new(data_len).unwrap();
            storage
                .copy_from_slice(&vec![value; host_page_size], 0)
                .unwrap();
            let storage = storage.freeze(data_len).unwrap();
            Arc::new(SnapshotBlob::new(storage, gpa_start, 0, scratch).unwrap())
        };
        let first = layer(base, 0x11);
        let second = layer(base + host_page_size as u64, 0x22);
        let memory = Arc::new(
            SnapshotMemory::new(
                Box::new([first, second]),
                crate::sandbox::snapshot::memory::tests::stub_page_tables(),
            )
            .unwrap(),
        );
        let (snapshot, _) = SnapshotMemoryBacking::from_snapshot(memory)
            .unwrap()
            .build();
        let mut bytes = [0; 2];

        snapshot
            .read_snapshot_gpa(base + host_page_size as u64 - 1, &mut bytes)
            .unwrap();

        assert_eq!(bytes, [0x11, 0x22]);
        assert!(
            snapshot
                .read_snapshot_gpa(base + 2 * host_page_size as u64 - 1, &mut bytes)
                .is_err()
        );
    }

    fn virtual_reader_manager() -> (SandboxMemoryManager<HostSharedMemory>, u64, u64) {
        let cfg = SandboxConfiguration::default();
        let layout = SandboxMemoryLayout::new(cfg, PAGE_SIZE, 0, None).unwrap();
        let host_page_size = page_size::get();
        let base = SandboxMemoryLayout::BASE_ADDRESS as u64;
        let second_gpa = base + host_page_size as u64;
        let scratch_base = hyperlight_common::layout::scratch_base_gpa(layout.get_scratch_size());
        let scratch_gpa = scratch_base + layout.get_scratch_size() as u64 - 0x10000;
        let pt_base = layout.get_pt_base_gpa();
        let pt_buf = GuestPageTableBuffer::new(pt_base as usize);
        let kind = MappingKind::Basic(BasicMapping {
            readable: true,
            writable: false,
            executable: false,
        });
        // SAFETY: The local page-table buffer has no concurrent writers.
        unsafe {
            vmem::map(
                &pt_buf,
                Mapping {
                    phys_base: base,
                    virt_base: base,
                    len: PAGE_SIZE as u64,
                    kind,
                },
            );
            vmem::map(
                &pt_buf,
                Mapping {
                    phys_base: second_gpa,
                    virt_base: base + PAGE_SIZE as u64,
                    len: PAGE_SIZE as u64,
                    kind,
                },
            );
            vmem::map(
                &pt_buf,
                Mapping {
                    phys_base: scratch_gpa,
                    virt_base: base + 2 * PAGE_SIZE as u64,
                    len: PAGE_SIZE as u64,
                    kind,
                },
            );
        }
        let page_tables = pt_buf.into_bytes();
        layout.ensure_page_tables_fit(page_tables.len()).unwrap();

        let first_storage =
            ReadonlySharedMemory::from_bytes(&vec![0x11; host_page_size], host_page_size).unwrap();
        let first = Arc::new(SnapshotBlob::new(first_storage, base, 0, scratch_base).unwrap());

        let second_storage =
            ReadonlySharedMemory::from_bytes(&vec![0x22; host_page_size], host_page_size).unwrap();
        let second =
            Arc::new(SnapshotBlob::new(second_storage, second_gpa, 0, scratch_base).unwrap());
        let memory = Arc::new(
            SnapshotMemory::new(
                Box::new([first, second]),
                crate::sandbox::snapshot::memory::tests::page_tables_from_bytes(&page_tables),
            )
            .unwrap(),
        );
        let manager = SandboxMemoryManager::new(
            layout,
            SnapshotMemoryBacking::from_snapshot(memory).unwrap(),
            ExclusiveSharedMemory::new(layout.get_scratch_size()).unwrap(),
            NextAction::None,
        );
        let (manager, _) = manager.build().unwrap();
        manager
            .scratch_mem
            .copy_from_slice(
                &vec![0x33; PAGE_SIZE],
                (scratch_gpa - scratch_base) as usize,
            )
            .unwrap();
        (manager, pt_base, base)
    }

    #[test]
    fn virtual_reader_reads_across_snapshot_layers() {
        let (manager, pt_base, base) = virtual_reader_manager();
        let mut bytes = [0u8; 2];

        manager
            .with_guest_virtual_memory_reader(pt_base, |reader| {
                reader.read_exact(base + PAGE_SIZE as u64 - 1, &mut bytes)
            })
            .unwrap();

        assert_eq!(bytes, [0x11, 0x22]);
    }

    #[test]
    fn virtual_reader_reads_snapshot_and_cow_scratch_across_pages() {
        let (manager, root, base) = virtual_reader_manager();
        let mut bytes = [0; 2];
        manager
            .with_guest_virtual_memory_reader(root, |reader| {
                reader.read_exact(base + 2 * PAGE_SIZE as u64 - 1, &mut bytes)
            })
            .unwrap();
        assert_eq!(bytes, [0x22, 0x33]);
    }

    #[test]
    fn virtual_reader_rejects_unmapped_and_overflowing_ranges() {
        let (manager, root, base) = virtual_reader_manager();
        manager
            .with_guest_virtual_memory_reader(root, |reader| {
                assert!(
                    reader
                        .read_exact(base + 3 * PAGE_SIZE as u64, &mut [0])
                        .is_err()
                );
                assert!(reader.read_exact(u64::MAX, &mut [0; 2]).is_err());
                assert!(reader.read_exact(u64::MAX, &mut []).is_ok());
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn virtual_reader_reports_invalid_page_tables() {
        let (manager, _, base) = virtual_reader_manager();
        let error = manager
            .with_guest_virtual_memory_reader(u64::MAX, |reader| reader.read_exact(base, &mut [0]))
            .unwrap_err();
        assert!(error.to_string().contains("unbacked"));
    }

    #[test]
    fn guest_physical_memory_view_resolves_scratch_and_dynamic_edges() {
        let host_page_size = page_size::get();
        let layout =
            SandboxMemoryLayout::new(SandboxConfiguration::default(), PAGE_SIZE, 0, None).unwrap();
        let scratch_start = hyperlight_common::layout::scratch_base_gpa(layout.get_scratch_size());
        let snapshot = Arc::new(flat_memory(
            &[0u8; PAGE_SIZE],
            &[0; PAGE_SIZE],
            SandboxMemoryLayout::BASE_ADDRESS as u64,
            scratch_start,
        ));
        let (snapshot, _) = SnapshotMemoryBacking::from_snapshot(snapshot)
            .unwrap()
            .build();

        let mut scratch = ExclusiveSharedMemory::new(layout.get_scratch_size()).unwrap();
        scratch.copy_from_slice(&[0x11], 0).unwrap();
        scratch
            .copy_from_slice(&[0x22], layout.get_scratch_size() - 1)
            .unwrap();
        let (scratch, _) = scratch.build();

        let dynamic_gpa = SandboxMemoryLayout::BASE_ADDRESS as u64 + host_page_size as u64;
        let mut dynamic = ExclusiveSharedMemory::new(host_page_size).unwrap();
        dynamic.copy_from_slice(&[0x33], 0).unwrap();
        dynamic
            .copy_from_slice(&[0x44], host_page_size - 1)
            .unwrap();
        let (dynamic, dynamic_guest) = dynamic.build();
        let dynamic_region = dynamic_guest.mapping_at(dynamic_gpa, MemoryRegionType::Scratch);
        let dynamic_regions = [dynamic_region];
        GuestPhysicalMemoryView::with_memory(
            &snapshot,
            &scratch,
            &dynamic_regions,
            layout,
            |view| {
                let mut byte = [0u8; 1];

                assert_eq!(
                    view.read(scratch_start, &mut byte).unwrap(),
                    GuestBacking {
                        source: BackingSource::Scratch,
                        offset: 0,
                    }
                );
                assert_eq!(byte, [0x11]);
                assert_eq!(
                    view.read(
                        scratch_start + layout.get_scratch_size() as u64 - 1,
                        &mut byte,
                    )
                    .unwrap(),
                    GuestBacking {
                        source: BackingSource::Scratch,
                        offset: layout.get_scratch_size() - 1,
                    }
                );
                assert_eq!(byte, [0x22]);
                assert_eq!(
                    view.read(dynamic_gpa, &mut byte).unwrap(),
                    GuestBacking {
                        source: BackingSource::Dynamic(0),
                        offset: 0,
                    }
                );
                assert_eq!(byte, [0x33]);
                assert_eq!(
                    view.read(dynamic_gpa + host_page_size as u64 - 1, &mut byte)
                        .unwrap(),
                    GuestBacking {
                        source: BackingSource::Dynamic(0),
                        offset: host_page_size - 1,
                    }
                );
                assert_eq!(byte, [0x44]);
                assert!(
                    view.resolve(dynamic_gpa + host_page_size as u64 - 1, 2)
                        .is_none()
                );
                assert!(
                    view.resolve(scratch_start + layout.get_scratch_size() as u64 - 1, 2,)
                        .is_none()
                );
                Ok(())
            },
        )
        .unwrap();

        drop(dynamic);
        drop(dynamic_guest);
    }
}