hyperlight-host 0.14.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
/*
Copyright 2025  The Hyperlight Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

use std::fmt::Debug;
use std::option::Option;
use std::path::Path;
use std::sync::{Arc, Mutex};

use tracing::{Span, instrument};
use tracing_core::LevelFilter;

use super::host_funcs::{FunctionRegistry, default_writer_func};
use super::snapshot::Snapshot;
use super::uninitialized_evolve::evolve_impl_multi_use;
use crate::func::host_functions::{HostFunction, register_host_function};
use crate::func::{ParameterTuple, SupportedReturnType};
#[cfg(feature = "build-metadata")]
use crate::log_build_details;
use crate::mem::memory_region::{DEFAULT_GUEST_BLOB_MEM_FLAGS, MemoryRegionFlags};
use crate::mem::mgr::SandboxMemoryManager;
#[cfg(feature = "nanvix-unstable")]
use crate::mem::shared_mem::HostSharedMemory;
use crate::mem::shared_mem::{ExclusiveSharedMemory, SharedMemory};
use crate::sandbox::SandboxConfiguration;
use crate::{MultiUseSandbox, Result, new_error};

#[cfg(any(crashdump, gdb))]
#[derive(Clone, Debug, Default)]
pub(crate) struct SandboxRuntimeConfig {
    #[cfg(crashdump)]
    pub(crate) binary_path: Option<String>,
    #[cfg(gdb)]
    pub(crate) debug_info: Option<super::config::DebugInfo>,
    #[cfg(crashdump)]
    pub(crate) guest_core_dump: bool,
    /// The original entry point address of the loaded guest binary
    /// (load_addr + ELF entry offset). Used for AT_ENTRY in core dumps
    /// so GDB can compute the correct load offset for PIE binaries.
    ///
    /// `None` until resolved from the snapshot's `NextAction::Initialise`
    /// in `set_up_hypervisor_partition`.
    #[cfg(crashdump)]
    pub(crate) entry_point: Option<u64>,
}

/// A host-authoritative shared counter exposed to the guest via a `u64`
/// in guest scratch memory.
///
/// Created via [`UninitializedSandbox::guest_counter()`]. The host owns
/// the counter value and is the only writer: [`increment()`](Self::increment)
/// and [`decrement()`](Self::decrement) update the cached value and write
/// to shared memory via [`HostSharedMemory::write()`]. [`value()`](Self::value)
/// returns the cached value — the host never reads back from guest memory,
/// so a malicious guest cannot influence the host's view of the counter.
///
/// Thread safety is provided by an internal `Mutex`, so `increment()` and
/// `decrement()` take `&self` rather than `&mut self`.
///
/// The counter holds an `Arc<Mutex<Option<HostSharedMemory>>>` that is
/// shared with [`UninitializedSandbox`]. The `Option` is `None` until
/// [`evolve()`](UninitializedSandbox::evolve) populates it, at which point
/// the counter can issue volatile writes via the proper protocol.
///
/// Only one `GuestCounter` may be created per sandbox; a second call to
/// [`UninitializedSandbox::guest_counter()`] returns an error.
#[cfg(feature = "nanvix-unstable")]
pub struct GuestCounter {
    inner: Mutex<GuestCounterInner>,
}

#[cfg(feature = "nanvix-unstable")]
struct GuestCounterInner {
    deferred_hshm: Arc<Mutex<Option<HostSharedMemory>>>,
    offset: usize,
    value: u64,
}

#[cfg(feature = "nanvix-unstable")]
impl core::fmt::Debug for GuestCounter {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("GuestCounter").finish_non_exhaustive()
    }
}

#[cfg(feature = "nanvix-unstable")]
impl GuestCounter {
    /// Increments the counter by one and writes it to guest memory.
    pub fn increment(&self) -> Result<()> {
        let mut inner = self.inner.lock().map_err(|e| new_error!("{e}"))?;
        let shm = {
            let guard = inner.deferred_hshm.lock().map_err(|e| new_error!("{e}"))?;
            guard
                .as_ref()
                .ok_or_else(|| {
                    new_error!("GuestCounter cannot be used before shared memory is built")
                })?
                .clone()
        };
        let new_value = inner
            .value
            .checked_add(1)
            .ok_or_else(|| new_error!("GuestCounter overflow"))?;
        shm.write::<u64>(inner.offset, new_value)?;
        inner.value = new_value;
        Ok(())
    }

    /// Decrements the counter by one and writes it to guest memory.
    pub fn decrement(&self) -> Result<()> {
        let mut inner = self.inner.lock().map_err(|e| new_error!("{e}"))?;
        let shm = {
            let guard = inner.deferred_hshm.lock().map_err(|e| new_error!("{e}"))?;
            guard
                .as_ref()
                .ok_or_else(|| {
                    new_error!("GuestCounter cannot be used before shared memory is built")
                })?
                .clone()
        };
        let new_value = inner
            .value
            .checked_sub(1)
            .ok_or_else(|| new_error!("GuestCounter underflow"))?;
        shm.write::<u64>(inner.offset, new_value)?;
        inner.value = new_value;
        Ok(())
    }

    /// Returns the current host-side value of the counter.
    pub fn value(&self) -> Result<u64> {
        let inner = self.inner.lock().map_err(|e| new_error!("{e}"))?;
        Ok(inner.value)
    }
}

/// A preliminary sandbox that represents allocated memory and registered host functions,
/// but has not yet created the underlying virtual machine.
///
/// This struct holds the configuration and setup needed for a sandbox without actually
/// creating the VM. It allows you to:
/// - Set up memory layout and load guest binary data
/// - Register host functions that will be available to the guest
/// - Configure sandbox settings before VM creation
///
/// The virtual machine is not created until you call [`evolve`](Self::evolve) to transform
/// this into an initialized [`MultiUseSandbox`].
pub struct UninitializedSandbox {
    /// Registered host functions
    pub(crate) host_funcs: Arc<Mutex<FunctionRegistry>>,
    /// The memory manager for the sandbox.
    pub(crate) mgr: SandboxMemoryManager<ExclusiveSharedMemory>,
    pub(crate) max_guest_log_level: Option<LevelFilter>,
    pub(crate) config: SandboxConfiguration,
    #[cfg(any(crashdump, gdb))]
    pub(crate) rt_cfg: SandboxRuntimeConfig,
    pub(crate) load_info: crate::mem::exe::LoadInfo,
    // This is needed to convey the stack pointer between the snapshot
    // and the HyperlightVm creation
    pub(crate) stack_top_gva: u64,
    /// Populated by [`evolve()`](Self::evolve) with a [`HostSharedMemory`]
    /// view of scratch memory. Code that needs host-style volatile access
    /// before `evolve()` (e.g. `GuestCounter`) can clone this `Arc` and
    /// will see `Some` once `evolve()` completes.
    #[cfg(feature = "nanvix-unstable")]
    pub(crate) deferred_hshm: Arc<Mutex<Option<HostSharedMemory>>>,
    /// Set to `true` once a [`GuestCounter`] has been handed out via
    /// [`guest_counter()`](Self::guest_counter). Prevents creating
    /// multiple counters that would have divergent cached values.
    #[cfg(feature = "nanvix-unstable")]
    counter_taken: std::sync::atomic::AtomicBool,
    /// File mappings prepared by [`Self::map_file_cow`] that will be
    /// applied to the VM during [`Self::evolve`].
    pub(crate) pending_file_mappings: Vec<super::file_mapping::PreparedFileMapping>,
}

impl Debug for UninitializedSandbox {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UninitializedSandbox")
            .field("memory_layout", &self.mgr.layout)
            .finish()
    }
}

/// A `GuestBinary` is either a buffer or the file path to some data (e.g., a guest binary).
#[derive(Debug)]
pub enum GuestBinary<'a> {
    /// A buffer containing the GuestBinary
    Buffer(&'a [u8]),
    /// A path to the GuestBinary
    FilePath(String),
}
impl<'a> GuestBinary<'a> {
    /// If the guest binary is identified by a file, canonicalise the path
    ///
    /// For [`GuestBinary::FilePath`], this resolves the path to its canonical
    /// form. For [`GuestBinary::Buffer`], this method is a no-op.
    /// TODO: Maybe we should make the GuestEnvironment or
    ///       GuestBinary constructors crate-private and turn this
    ///       into an invariant on one of those types.
    pub fn canonicalize(&mut self) -> Result<()> {
        if let GuestBinary::FilePath(p) = self {
            let canon = Path::new(&p)
                .canonicalize()
                .map_err(|e| new_error!("GuestBinary not found: '{}': {}", p, e))?
                .into_os_string()
                .into_string()
                .map_err(|e| new_error!("Error converting OsString to String: {:?}", e))?;
            *self = GuestBinary::FilePath(canon)
        }
        Ok(())
    }
}

/// A `GuestBlob` containing data and the permissions for its use.
#[derive(Debug)]
pub struct GuestBlob<'a> {
    /// The data contained in the blob.
    pub data: &'a [u8],
    /// The permissions for the blob in memory.
    /// By default, it's READ
    pub permissions: MemoryRegionFlags,
}

impl<'a> From<&'a [u8]> for GuestBlob<'a> {
    fn from(data: &'a [u8]) -> Self {
        GuestBlob {
            data,
            permissions: DEFAULT_GUEST_BLOB_MEM_FLAGS,
        }
    }
}

/// Container for a guest binary and optional initialization data.
///
/// This struct combines a guest binary (either from a file or memory buffer) with
/// optional data that will be available to the guest during execution.
#[derive(Debug)]
pub struct GuestEnvironment<'a, 'b> {
    /// The guest binary, which can be a file path or a buffer.
    pub guest_binary: GuestBinary<'a>,
    /// An optional guest blob, which can be used to provide additional data to the guest.
    pub init_data: Option<GuestBlob<'b>>,
}

impl<'a, 'b> GuestEnvironment<'a, 'b> {
    /// Creates a new `GuestEnvironment` with the given guest binary and an optional guest blob.
    pub fn new(guest_binary: GuestBinary<'a>, init_data: Option<&'b [u8]>) -> Self {
        GuestEnvironment {
            guest_binary,
            init_data: init_data.map(GuestBlob::from),
        }
    }
}

impl<'a> From<GuestBinary<'a>> for GuestEnvironment<'a, '_> {
    fn from(guest_binary: GuestBinary<'a>) -> Self {
        GuestEnvironment {
            guest_binary,
            init_data: None,
        }
    }
}

impl UninitializedSandbox {
    /// Creates a [`GuestCounter`] at a fixed offset in scratch memory.
    ///
    /// The counter lives at `SCRATCH_TOP_GUEST_COUNTER_OFFSET` bytes from
    /// the top of scratch memory, so both host and guest can locate it
    /// without an explicit GPA parameter.
    ///
    /// The returned counter holds an `Arc` clone of the sandbox's
    /// `deferred_hshm`, so it will automatically gain access to the
    /// [`HostSharedMemory`] once [`evolve()`](Self::evolve) completes.
    ///
    /// This method can only be called once; a second call returns an error
    /// because multiple counters would have divergent cached values.
    #[cfg(feature = "nanvix-unstable")]
    pub fn guest_counter(&mut self) -> Result<GuestCounter> {
        use std::sync::atomic::Ordering;

        use hyperlight_common::layout::SCRATCH_TOP_GUEST_COUNTER_OFFSET;

        if self.counter_taken.swap(true, Ordering::Relaxed) {
            return Err(new_error!(
                "GuestCounter has already been created for this sandbox"
            ));
        }

        let scratch_size = self.mgr.scratch_mem.mem_size();
        if (SCRATCH_TOP_GUEST_COUNTER_OFFSET as usize) > scratch_size {
            return Err(new_error!(
                "scratch memory too small for guest counter (size {:#x}, need offset {:#x})",
                scratch_size,
                SCRATCH_TOP_GUEST_COUNTER_OFFSET,
            ));
        }

        let offset = scratch_size - SCRATCH_TOP_GUEST_COUNTER_OFFSET as usize;
        let deferred_hshm = self.deferred_hshm.clone();

        Ok(GuestCounter {
            inner: Mutex::new(GuestCounterInner {
                deferred_hshm,
                offset,
                value: 0,
            }),
        })
    }

    // Creates a new uninitialized sandbox from a pre-built snapshot.
    // Note that since memory configuration is part of the snapshot the only configuration
    // that can be changed (from the original snapshot) is the configuration defines the behaviour of
    // `InterruptHandler` on Linux.
    //
    // This is ok for now as this is not a public function
    fn from_snapshot(
        snapshot: Arc<Snapshot>,
        cfg: Option<SandboxConfiguration>,
        #[cfg(crashdump)] binary_path: Option<String>,
    ) -> Result<Self> {
        #[cfg(feature = "build-metadata")]
        log_build_details();

        // hyperlight is only supported on Windows 11 and Windows Server 2022 and later
        #[cfg(target_os = "windows")]
        check_windows_version()?;

        let sandbox_cfg = cfg.unwrap_or_default();

        #[cfg(any(crashdump, gdb))]
        let rt_cfg = {
            #[cfg(crashdump)]
            let guest_core_dump = sandbox_cfg.get_guest_core_dump();

            #[cfg(gdb)]
            let debug_info = sandbox_cfg.get_guest_debug_info();

            SandboxRuntimeConfig {
                #[cfg(crashdump)]
                binary_path,
                #[cfg(gdb)]
                debug_info,
                #[cfg(crashdump)]
                guest_core_dump,
                // entry_point is set later in set_up_hypervisor_partition
                // once the entrypoint is resolved from the snapshot
                #[cfg(crashdump)]
                entry_point: None,
            }
        };

        let mem_mgr_wrapper =
            SandboxMemoryManager::<ExclusiveSharedMemory>::from_snapshot(snapshot.as_ref())?;

        let host_funcs = Arc::new(Mutex::new(FunctionRegistry::default()));

        let mut sandbox = Self {
            host_funcs,
            mgr: mem_mgr_wrapper,
            max_guest_log_level: None,
            config: sandbox_cfg,
            #[cfg(any(crashdump, gdb))]
            rt_cfg,
            load_info: snapshot.load_info(),
            stack_top_gva: snapshot.stack_top_gva(),
            #[cfg(feature = "nanvix-unstable")]
            deferred_hshm: Arc::new(Mutex::new(None)),
            #[cfg(feature = "nanvix-unstable")]
            counter_taken: std::sync::atomic::AtomicBool::new(false),
            pending_file_mappings: Vec::new(),
        };

        // If we were passed a writer for host print register it otherwise use the default.
        sandbox.register_print(default_writer_func)?;

        crate::debug!("Sandbox created:  {:#?}", sandbox);

        Ok(sandbox)
    }

    /// Creates a new uninitialized sandbox for the given guest environment.
    ///
    /// The guest binary can be provided as either a file path or memory buffer.
    /// An optional configuration can customize memory sizes and sandbox settings.
    /// After creation, register host functions using [`register`](Self::register)
    /// before calling [`evolve`](Self::evolve) to complete initialization and create the VM.
    #[instrument(
        err(Debug),
        skip(env),
        parent = Span::current()
    )]
    pub fn new<'a, 'b>(
        env: impl Into<GuestEnvironment<'a, 'b>>,
        cfg: Option<SandboxConfiguration>,
    ) -> Result<Self> {
        let cfg = cfg.unwrap_or_default();
        let env = env.into();
        #[cfg(crashdump)]
        let binary_path = match &env.guest_binary {
            GuestBinary::FilePath(path) => Some(path.clone()),
            GuestBinary::Buffer(_) => None,
        };
        let snapshot = Snapshot::from_env(env, cfg)?;
        Self::from_snapshot(
            Arc::new(snapshot),
            Some(cfg),
            #[cfg(crashdump)]
            binary_path,
        )
    }

    /// Creates and initializes the virtual machine, transforming this into a ready-to-use sandbox.
    ///
    /// This method consumes the `UninitializedSandbox` and performs the final initialization
    /// steps to create the underlying virtual machine. Once evolved, the resulting
    /// [`MultiUseSandbox`] can execute guest code and handle function calls.
    #[instrument(err(Debug), skip_all, parent = Span::current(), level = "Trace")]
    pub fn evolve(self) -> Result<MultiUseSandbox> {
        evolve_impl_multi_use(self)
    }

    /// Map the contents of a file into the guest at a particular address.
    ///
    /// The file mapping is prepared immediately (host-side OS work) but
    /// the actual VM-side mapping is deferred until [`evolve()`](Self::evolve).
    ///
    /// An optional `label` identifies this mapping in the PEB's
    /// `FileMappingInfo` array (max 63 bytes, defaults to the file name).
    ///
    /// The `guest_base` must be page-aligned and must lie **outside**
    /// the sandbox's primary shared memory region (`BASE_ADDRESS` to
    /// `BASE_ADDRESS + shared_mem_size`).
    ///
    /// Returns the length of the mapping in bytes.
    #[instrument(err(Debug), skip(self, file_path, guest_base, label), parent = Span::current())]
    pub fn map_file_cow(
        &mut self,
        file_path: &std::path::Path,
        guest_base: u64,
        label: Option<&str>,
    ) -> crate::Result<u64> {
        // Fail fast if the preallocated PEB array is already full.
        if self.pending_file_mappings.len() >= hyperlight_common::mem::MAX_FILE_MAPPINGS {
            return Err(crate::HyperlightError::Error(format!(
                "map_file_cow: file mapping limit reached ({} of {})",
                self.pending_file_mappings.len(),
                hyperlight_common::mem::MAX_FILE_MAPPINGS,
            )));
        }

        // Validate that guest_base is outside the sandbox's primary memory slot.
        // (Full range check happens after prepare_file_cow when we know the mapped size.)
        let shared_size = self.mgr.shared_mem.mem_size() as u64;
        let base_addr = crate::mem::layout::SandboxMemoryLayout::BASE_ADDRESS as u64;

        let prepared = super::file_mapping::prepare_file_cow(file_path, guest_base, label)?;

        // Validate full mapped range doesn't overlap shared memory.
        let mapping_end = guest_base
            .checked_add(prepared.size as u64)
            .ok_or_else(|| {
                crate::HyperlightError::Error(format!(
                    "map_file_cow: guest address overflow: {:#x} + {:#x}",
                    guest_base, prepared.size
                ))
            })?;
        let shared_end = base_addr.checked_add(shared_size).ok_or_else(|| {
            crate::HyperlightError::Error("shared memory end overflow".to_string())
        })?;
        if guest_base < shared_end && mapping_end > base_addr {
            return Err(crate::HyperlightError::Error(format!(
                "map_file_cow: mapping [{:#x}..{:#x}) overlaps sandbox shared memory [{:#x}..{:#x})",
                guest_base, mapping_end, base_addr, shared_end,
            )));
        }

        let size = prepared.size as u64;

        // Check for overlaps with existing pending file mappings.
        let new_start = guest_base;
        let new_end = mapping_end;
        for existing in &self.pending_file_mappings {
            let ex_start = existing.guest_base;
            let ex_end = ex_start.checked_add(existing.size as u64).ok_or_else(|| {
                crate::HyperlightError::Error(format!(
                    "map_file_cow: existing mapping address overflow: {:#x} + {:#x}",
                    ex_start, existing.size
                ))
            })?;
            if new_start < ex_end && new_end > ex_start {
                return Err(crate::HyperlightError::Error(format!(
                    "map_file_cow: mapping [{:#x}..{:#x}) overlaps existing mapping [{:#x}..{:#x})",
                    new_start, new_end, ex_start, ex_end,
                )));
            }
        }

        self.pending_file_mappings.push(prepared);
        Ok(size)
    }

    /// Returns the total size of the sandbox shared memory region in bytes.
    ///
    /// This is useful for placing file mappings at guest physical addresses
    /// that don't overlap the primary shared memory slot.
    pub fn shared_mem_size(&self) -> usize {
        self.mgr.shared_mem.mem_size()
    }

    /// Sets the maximum log level for guest code execution.
    ///
    /// If not set, the log level is determined by the `RUST_LOG` environment variable,
    /// defaulting to [`LevelFilter::Error`] if unset.
    pub fn set_max_guest_log_level(&mut self, log_level: LevelFilter) {
        self.max_guest_log_level = Some(log_level);
    }

    /// Registers a host function that the guest can call.
    pub fn register<Args: ParameterTuple, Output: SupportedReturnType>(
        &mut self,
        name: impl AsRef<str>,
        host_func: impl Into<HostFunction<Output, Args>>,
    ) -> Result<()> {
        register_host_function(host_func, self, name.as_ref())
    }

    /// Registers the special "HostPrint" function for guest printing.
    ///
    /// This overrides the default behavior of writing to stdout.
    /// The function expects the signature `FnMut(String) -> i32`
    /// and will be called when the guest wants to print output.
    pub fn register_print(
        &mut self,
        print_func: impl Into<HostFunction<i32, (String,)>>,
    ) -> Result<()> {
        self.register("HostPrint", print_func)
    }

    /// Populate the deferred `HostSharedMemory` slot without running
    /// the full `evolve()` pipeline. Used in tests where guest boot
    /// is not available.
    #[cfg(all(test, feature = "nanvix-unstable"))]
    fn simulate_build(&self) {
        let hshm = self.mgr.scratch_mem.as_host_shared_memory();
        #[allow(clippy::unwrap_used)]
        {
            *self.deferred_hshm.lock().unwrap() = Some(hshm);
        }
    }
}
// Check to see if the current version of Windows is supported
// Hyperlight is only supported on Windows 11 and Windows Server 2022 and later
#[cfg(target_os = "windows")]
fn check_windows_version() -> Result<()> {
    use windows_version::{OsVersion, is_server};
    const WINDOWS_MAJOR: u32 = 10;
    const WINDOWS_MINOR: u32 = 0;
    const WINDOWS_PACK: u32 = 0;

    // Windows Server 2022 has version numbers 10.0.20348 or greater
    if is_server() {
        if OsVersion::current() < OsVersion::new(WINDOWS_MAJOR, WINDOWS_MINOR, WINDOWS_PACK, 20348)
        {
            return Err(new_error!(
                "Hyperlight Requires Windows Server 2022 or newer"
            ));
        }
    } else if OsVersion::current()
        < OsVersion::new(WINDOWS_MAJOR, WINDOWS_MINOR, WINDOWS_PACK, 22000)
    {
        return Err(new_error!("Hyperlight Requires Windows 11 or newer"));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::mpsc::channel;
    use std::{fs, thread};

    use crossbeam_queue::ArrayQueue;
    use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue};
    use hyperlight_testing::simple_guest_as_string;

    use crate::sandbox::SandboxConfiguration;
    use crate::sandbox::uninitialized::{GuestBinary, GuestEnvironment};
    use crate::{MultiUseSandbox, Result, UninitializedSandbox, new_error};

    #[test]
    fn test_load_extra_blob() {
        let binary_path = simple_guest_as_string().unwrap();
        let buffer = [0xde, 0xad, 0xbe, 0xef];
        let guest_env =
            GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), Some(&buffer));

        let uninitialized_sandbox = UninitializedSandbox::new(guest_env, None).unwrap();
        let mut sandbox: MultiUseSandbox = uninitialized_sandbox.evolve().unwrap();

        let res = sandbox
            .call::<Vec<u8>>("ReadFromUserMemory", (4u64, buffer.to_vec()))
            .expect("Failed to call ReadFromUserMemory");

        assert_eq!(res, buffer.to_vec());
    }

    #[test]
    fn test_new_sandbox() {
        // Guest Binary exists at path

        let binary_path = simple_guest_as_string().unwrap();
        let sandbox = UninitializedSandbox::new(GuestBinary::FilePath(binary_path.clone()), None);
        assert!(sandbox.is_ok());

        // Guest Binary does not exist at path

        let mut binary_path_does_not_exist = binary_path.clone();
        binary_path_does_not_exist.push_str(".nonexistent");
        let uninitialized_sandbox =
            UninitializedSandbox::new(GuestBinary::FilePath(binary_path_does_not_exist), None);
        assert!(uninitialized_sandbox.is_err());

        // Non default memory configuration
        let cfg = {
            let mut cfg = SandboxConfiguration::default();
            cfg.set_input_data_size(0x1000);
            cfg.set_output_data_size(0x1000);
            cfg.set_heap_size(0x1000);
            Some(cfg)
        };

        let uninitialized_sandbox =
            UninitializedSandbox::new(GuestBinary::FilePath(binary_path.clone()), cfg);
        assert!(uninitialized_sandbox.is_ok());

        let uninitialized_sandbox =
            UninitializedSandbox::new(GuestBinary::FilePath(binary_path), None).unwrap();

        // Get a Sandbox from an uninitialized sandbox without a call back function

        let _sandbox: MultiUseSandbox = uninitialized_sandbox.evolve().unwrap();

        // Test with a valid guest binary buffer

        let binary_path = simple_guest_as_string().unwrap();
        let sandbox =
            UninitializedSandbox::new(GuestBinary::Buffer(&fs::read(binary_path).unwrap()), None);
        assert!(sandbox.is_ok());

        // Test with a invalid guest binary buffer

        let binary_path = simple_guest_as_string().unwrap();
        let mut bytes = fs::read(binary_path).unwrap();
        let _ = bytes.split_off(100);
        let sandbox = UninitializedSandbox::new(GuestBinary::Buffer(&bytes), None);
        assert!(sandbox.is_err());
    }

    #[test]
    fn test_host_functions() {
        let uninitialized_sandbox = || {
            UninitializedSandbox::new(
                GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
                None,
            )
            .unwrap()
        };

        // simple register + call
        {
            let mut usbox = uninitialized_sandbox();

            usbox.register("test0", |arg: i32| Ok(arg + 1)).unwrap();

            let sandbox: Result<MultiUseSandbox> = usbox.evolve();
            assert!(sandbox.is_ok());
            let sandbox = sandbox.unwrap();

            let host_funcs = sandbox
                .host_funcs
                .try_lock()
                .map_err(|_| new_error!("Error locking"));

            assert!(host_funcs.is_ok());

            let res = host_funcs
                .unwrap()
                .call_host_function("test0", vec![ParameterValue::Int(1)])
                .unwrap();

            assert_eq!(res, ReturnValue::Int(2));
        }

        // multiple parameters register + call
        {
            let mut usbox = uninitialized_sandbox();

            usbox.register("test1", |a: i32, b: i32| Ok(a + b)).unwrap();

            let sandbox: Result<MultiUseSandbox> = usbox.evolve();
            assert!(sandbox.is_ok());
            let sandbox = sandbox.unwrap();

            let host_funcs = sandbox
                .host_funcs
                .try_lock()
                .map_err(|_| new_error!("Error locking"));

            assert!(host_funcs.is_ok());

            let res = host_funcs
                .unwrap()
                .call_host_function(
                    "test1",
                    vec![ParameterValue::Int(1), ParameterValue::Int(2)],
                )
                .unwrap();

            assert_eq!(res, ReturnValue::Int(3));
        }

        // incorrect arguments register + call
        {
            let mut usbox = uninitialized_sandbox();

            usbox
                .register("test2", |msg: String| {
                    println!("test2 called: {}", msg);
                    Ok(())
                })
                .unwrap();

            let sandbox: Result<MultiUseSandbox> = usbox.evolve();
            assert!(sandbox.is_ok());
            let sandbox = sandbox.unwrap();

            let host_funcs = sandbox
                .host_funcs
                .try_lock()
                .map_err(|_| new_error!("Error locking"));

            assert!(host_funcs.is_ok());

            let res = host_funcs.unwrap().call_host_function("test2", vec![]);
            assert!(res.is_err());
        }

        // calling a function that doesn't exist
        {
            let usbox = uninitialized_sandbox();
            let sandbox: Result<MultiUseSandbox> = usbox.evolve();
            assert!(sandbox.is_ok());
            let sandbox = sandbox.unwrap();

            let host_funcs = sandbox
                .host_funcs
                .try_lock()
                .map_err(|_| new_error!("Error locking"));

            assert!(host_funcs.is_ok());

            let res = host_funcs.unwrap().call_host_function("test4", vec![]);
            assert!(res.is_err());
        }
    }

    #[test]
    fn test_host_print() {
        // writer as a FnMut closure mutating a captured variable and then trying to access the captured variable
        // after the Sandbox instance has been dropped
        // this example is fairly contrived but we should still support such an approach.

        let (tx, rx) = channel();

        let writer = move |msg| {
            let _ = tx.send(msg);
            Ok(0)
        };

        let mut sandbox = UninitializedSandbox::new(
            GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
            None,
        )
        .expect("Failed to create sandbox");

        sandbox
            .register_print(writer)
            .expect("Failed to register host print function");

        let host_funcs = sandbox
            .host_funcs
            .try_lock()
            .map_err(|_| new_error!("Error locking"));

        assert!(host_funcs.is_ok());

        host_funcs.unwrap().host_print("test".to_string()).unwrap();

        drop(sandbox);

        let received_msgs: Vec<_> = rx.into_iter().collect();
        assert_eq!(received_msgs, ["test"]);

        // There may be cases where a mutable reference to the captured variable is not required to be used outside the closure
        // e.g. if the function is writing to a file or a socket etc.

        // writer as a FnMut closure mutating a captured variable but not trying to access the captured variable

        // This seems more realistic as the client is creating a file to be written to in the closure
        // and then accessing the file a different handle.
        // The problem is that captured_file still needs static lifetime so even though we can access the data through the second file handle
        // this still does not work as the captured_file is dropped at the end of the function

        // TODO: Currently, we block any writes that are not to
        // the stdout/stderr file handles, so this code is commented
        // out until we can register writer functions like any other
        // host functions with their own set of extra allowed syscalls.
        // In particular, this code should be brought back once we have addressed the issue

        // let captured_file = Arc::new(Mutex::new(NamedTempFile::new().unwrap()));
        // let capture_file_clone = captured_file.clone();
        //
        // let capture_file_lock = captured_file
        //     .try_lock()
        //     .map_err(|_| new_error!("Error locking"))
        //     .unwrap();
        // let mut file = capture_file_lock.reopen().unwrap();
        // drop(capture_file_lock);
        //
        // let writer = move |msg: String| -> Result<i32> {
        //     let mut captured_file = capture_file_clone
        //         .try_lock()
        //         .map_err(|_| new_error!("Error locking"))
        //         .unwrap();
        //     captured_file.write_all(msg.as_bytes()).unwrap();
        //     Ok(0)
        // };
        //
        // let writer_func = Arc::new(Mutex::new(writer));
        //
        // let sandbox = UninitializedSandbox::new(
        //     GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
        //     None,
        //     None,
        //     Some(&writer_func),
        // )
        // .expect("Failed to create sandbox");
        //
        // let host_funcs = sandbox
        //     .host_funcs
        //     .try_lock()
        //     .map_err(|_| new_error!("Error locking"));
        //
        // assert!(host_funcs.is_ok());
        //
        // host_funcs.unwrap().host_print("test2".to_string()).unwrap();
        //
        // let mut buffer = String::new();
        // file.read_to_string(&mut buffer).unwrap();
        // assert_eq!(buffer, "test2");

        // writer as a function

        fn fn_writer(msg: String) -> Result<i32> {
            assert_eq!(msg, "test2");
            Ok(0)
        }

        let mut sandbox = UninitializedSandbox::new(
            GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
            None,
        )
        .expect("Failed to create sandbox");

        sandbox
            .register_print(fn_writer)
            .expect("Failed to register host print function");

        let host_funcs = sandbox
            .host_funcs
            .try_lock()
            .map_err(|_| new_error!("Error locking"));

        assert!(host_funcs.is_ok());

        host_funcs.unwrap().host_print("test2".to_string()).unwrap();

        // writer as a method

        let mut test_host_print = TestHostPrint::new();

        // create a closure over the struct method

        let writer_closure = move |s| test_host_print.write(s);

        let mut sandbox = UninitializedSandbox::new(
            GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
            None,
        )
        .expect("Failed to create sandbox");

        sandbox
            .register_print(writer_closure)
            .expect("Failed to register host print function");

        let host_funcs = sandbox
            .host_funcs
            .try_lock()
            .map_err(|_| new_error!("Error locking"));

        assert!(host_funcs.is_ok());

        host_funcs.unwrap().host_print("test3".to_string()).unwrap();
    }

    struct TestHostPrint {}

    impl TestHostPrint {
        fn new() -> Self {
            TestHostPrint {}
        }

        fn write(&mut self, msg: String) -> Result<i32> {
            assert_eq!(msg, "test3");
            Ok(0)
        }
    }

    #[test]
    fn check_create_and_use_sandbox_on_different_threads() {
        let unintializedsandbox_queue = Arc::new(ArrayQueue::<UninitializedSandbox>::new(10));
        let sandbox_queue = Arc::new(ArrayQueue::<MultiUseSandbox>::new(10));

        for i in 0..10 {
            let simple_guest_path = simple_guest_as_string().expect("Guest Binary Missing");
            let unintializedsandbox = {
                let err_string = format!("failed to create UninitializedSandbox {i}");
                let err_str = err_string.as_str();
                UninitializedSandbox::new(GuestBinary::FilePath(simple_guest_path), None)
                    .expect(err_str)
            };

            {
                let err_string = format!("Failed to push UninitializedSandbox {i}");
                let err_str = err_string.as_str();

                unintializedsandbox_queue
                    .push(unintializedsandbox)
                    .expect(err_str);
            }
        }

        let thread_handles = (0..10)
            .map(|i| {
                let uq = unintializedsandbox_queue.clone();
                let sq = sandbox_queue.clone();
                thread::spawn(move || {
                    let uninitialized_sandbox = uq.pop().unwrap_or_else(|| {
                        panic!("Failed to pop UninitializedSandbox thread {}", i)
                    });

                    let host_funcs = uninitialized_sandbox
                        .host_funcs
                        .try_lock()
                        .map_err(|_| new_error!("Error locking"));

                    assert!(host_funcs.is_ok());

                    host_funcs
                        .unwrap()
                        .host_print(format!("Print from UninitializedSandbox on Thread {}\n", i))
                        .unwrap();

                    let sandbox = uninitialized_sandbox.evolve().unwrap_or_else(|_| {
                        panic!("Failed to initialize UninitializedSandbox thread {}", i)
                    });

                    sq.push(sandbox).unwrap_or_else(|_| {
                        panic!("Failed to push UninitializedSandbox thread {}", i)
                    })
                })
            })
            .collect::<Vec<_>>();

        for handle in thread_handles {
            handle.join().unwrap();
        }

        let thread_handles = (0..10)
            .map(|i| {
                let sq = sandbox_queue.clone();
                thread::spawn(move || {
                    let sandbox = sq
                        .pop()
                        .unwrap_or_else(|| panic!("Failed to pop Sandbox thread {}", i));

                    let host_funcs = sandbox
                        .host_funcs
                        .try_lock()
                        .map_err(|_| new_error!("Error locking"));

                    assert!(host_funcs.is_ok());

                    host_funcs
                        .unwrap()
                        .host_print(format!("Print from Sandbox on Thread {}\n", i))
                        .unwrap();
                })
            })
            .collect::<Vec<_>>();

        for handle in thread_handles {
            handle.join().unwrap();
        }
    }

    /// Tests that tracing spans and events are properly emitted when a tracing subscriber is set.
    ///
    /// This test verifies:
    /// 1. Spans are created with correct attributes (correlation_id)
    /// 2. Nested spans from UninitializedSandbox::new are properly parented
    /// 3. Error events are emitted when sandbox creation fails
    ///
    /// NOTE: The `#[instrument]` callsite on `UninitializedSandbox::new` uses
    /// tracing's global interest cache. If another test thread registers that
    /// callsite first (with the no-op subscriber), the cached `Interest::never()`
    /// will suppress span creation on our thread. To work around this, we:
    /// 1. Make a warmup call to force-register the callsite
    /// 2. Call `rebuild_interest_cache()` to overwrite the cached interest with
    ///    our subscriber's `Interest::sometimes()`
    /// 3. Clear recorded state and run the real test
    #[test]
    #[cfg(feature = "build-metadata")]
    fn test_trace_trace() {
        use hyperlight_testing::tracing_subscriber::TracingSubscriber;
        use tracing::Level;
        use tracing_core::Subscriber;
        use tracing_core::callsite::rebuild_interest_cache;
        use uuid::Uuid;

        /// Helper to extract a string value from nested JSON: obj["span"]["attributes"][key]
        fn get_span_attr<'a>(span: &'a serde_json::Value, key: &str) -> Option<&'a str> {
            span.get("span")?.get("attributes")?.get(key)?.as_str()
        }

        /// Helper to extract event field: obj["event"][field]
        fn get_event_field<'a>(event: &'a serde_json::Value, field: &str) -> Option<&'a str> {
            event.get("event")?.get(field)?.as_str()
        }

        /// Helper to extract event metadata field: obj["event"]["metadata"][field]
        fn get_event_metadata<'a>(event: &'a serde_json::Value, field: &str) -> Option<&'a str> {
            event.get("event")?.get("metadata")?.get(field)?.as_str()
        }

        let subscriber = TracingSubscriber::new(Level::TRACE);

        tracing::subscriber::with_default(subscriber.clone(), || {
            // Warmup: force-register the #[instrument] callsite on
            // UninitializedSandbox::new by calling it once. This ensures the
            // callsite exists in the global registry regardless of whether
            // another thread already registered it.
            let bad_path = simple_guest_as_string().unwrap() + "does_not_exist";
            let _ = UninitializedSandbox::new(GuestBinary::FilePath(bad_path.clone()), None);

            // Rebuild the interest cache. Now that the callsite is guaranteed
            // to be registered, this will overwrite any cached Interest::never()
            // (from another thread's no-op subscriber) with our subscriber's
            // Interest::sometimes(), ensuring subsequent calls create spans.
            rebuild_interest_cache();

            // Clear all state from the warmup call
            subscriber.clear();

            let correlation_id = Uuid::new_v4().to_string();
            let _span = tracing::error_span!("test_trace_logs", %correlation_id).entered();

            // Verify we're in a span with correct name
            let (test_span_id, span_meta) = subscriber
                .current_span()
                .into_inner()
                .expect("Should be inside a span");
            assert_eq!(span_meta.name(), "test_trace_logs");

            // Verify correlation_id was recorded
            let span_data = subscriber.get_span(test_span_id.into_u64());
            let recorded_id =
                get_span_attr(&span_data, "correlation_id").expect("correlation_id not found");
            assert_eq!(recorded_id, correlation_id);

            // Try to create a sandbox with a non-existent binary - this should fail
            // and emit an error event
            let result = UninitializedSandbox::new(GuestBinary::FilePath(bad_path), None);
            assert!(result.is_err(), "Sandbox creation should fail");

            // Verify we're still in our test span
            let (current_id, _) = subscriber
                .current_span()
                .into_inner()
                .expect("Should still be inside a span");
            assert_eq!(
                current_id.into_u64(),
                test_span_id.into_u64(),
                "Should still be in the test span"
            );

            // Verify a span named "new" was created by UninitializedSandbox::new
            // (look up by name rather than hardcoded ID to avoid fragility)
            let all_spans = subscriber.get_all_spans();
            let _new_span_entry = all_spans
                .iter()
                .find(|&(&id, _)| {
                    id != test_span_id.into_u64()
                        && subscriber.get_span_metadata(id).name() == "new"
                })
                .expect("Expected a span named 'new' from UninitializedSandbox::new");

            // Verify the error event was emitted
            let events = subscriber.get_events();
            assert_eq!(events.len(), 1, "Expected exactly one error event");

            let event = &events[0];
            let level = get_event_metadata(event, "level").expect("event should have level");
            let error = get_event_field(event, "error").expect("event should have error field");
            let target = get_event_metadata(event, "target").expect("event should have target");
            let module_path =
                get_event_metadata(event, "module_path").expect("event should have module_path");

            assert_eq!(level, "ERROR");
            assert!(
                error.contains("GuestBinary not found"),
                "Error should mention 'GuestBinary not found', got: {error}"
            );
            assert_eq!(target, "hyperlight_host::sandbox::uninitialized");
            assert_eq!(module_path, "hyperlight_host::sandbox::uninitialized");
        });
    }

    #[test]
    #[ignore]
    // Tests that traces are emitted as log records when there is no trace
    // subscriber configured.
    #[cfg(feature = "build-metadata")]
    fn test_log_trace() {
        use std::path::PathBuf;

        use hyperlight_testing::logger::{LOGGER as TEST_LOGGER, Logger as TestLogger};
        use log::Level;
        use tracing_core::callsite::rebuild_interest_cache;

        {
            TestLogger::initialize_test_logger();
            TEST_LOGGER.set_max_level(log::LevelFilter::Trace);

            // This makes sure that the metadata interest cache is rebuilt so that
            // the log records are emitted for the trace records

            rebuild_interest_cache();

            let mut invalid_binary_path = simple_guest_as_string().unwrap();
            invalid_binary_path.push_str("does_not_exist");

            let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_binary_path), None);
            assert!(sbox.is_err());

            // When tracing is creating log records it will create a log
            // record for the creation of the span (from the instrument
            // attribute), and will then create a log record for the entry to
            // and exit from the span.
            //
            // It also creates a log record for the span being dropped.
            //
            // In addition there are 14 info log records created for build information
            //
            // So we expect 19 log records for this test, four for the span and
            // then one for the error as the file that we are attempting to
            // load into the sandbox does not exist, plus the 14 info log records

            let num_calls = TEST_LOGGER.num_log_calls();
            assert_eq!(13, num_calls);

            // Log record 1

            let logcall = TEST_LOGGER.get_log_call(0).unwrap();
            assert_eq!(Level::Info, logcall.level);

            assert!(logcall.args.starts_with("new; cfg"));
            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);

            // Log record 2

            let logcall = TEST_LOGGER.get_log_call(1).unwrap();
            assert_eq!(Level::Trace, logcall.level);
            assert_eq!(logcall.args, "-> new;");
            assert_eq!("tracing::span::active", logcall.target);

            // Log record 17

            let logcall = TEST_LOGGER.get_log_call(10).unwrap();
            assert_eq!(Level::Error, logcall.level);
            assert!(
                logcall
                    .args
                    .starts_with("error=Error(\"GuestBinary not found:")
            );
            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);

            // Log record 18

            let logcall = TEST_LOGGER.get_log_call(11).unwrap();
            assert_eq!(Level::Trace, logcall.level);
            assert_eq!(logcall.args, "<- new;");
            assert_eq!("tracing::span::active", logcall.target);

            // Log record 19

            let logcall = TEST_LOGGER.get_log_call(12).unwrap();
            assert_eq!(Level::Trace, logcall.level);
            assert_eq!(logcall.args, "-- new;");
            assert_eq!("tracing::span", logcall.target);
        }
        {
            // test to ensure an invalid binary logs & traces properly
            TEST_LOGGER.clear_log_calls();
            TEST_LOGGER.set_max_level(log::LevelFilter::Info);

            let mut valid_binary_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
            valid_binary_path.push("src");
            valid_binary_path.push("sandbox");
            valid_binary_path.push("initialized.rs");

            let sbox = UninitializedSandbox::new(
                GuestBinary::FilePath(valid_binary_path.into_os_string().into_string().unwrap()),
                None,
            );
            assert!(sbox.is_err());

            // There should be 2 calls this time when we change to the log
            // LevelFilter to Info.
            let num_calls = TEST_LOGGER.num_log_calls();
            assert_eq!(2, num_calls);

            // Log record 1

            let logcall = TEST_LOGGER.get_log_call(0).unwrap();
            assert_eq!(Level::Info, logcall.level);

            assert!(logcall.args.starts_with("new; cfg"));
            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);

            // Log record 2

            let logcall = TEST_LOGGER.get_log_call(1).unwrap();
            assert_eq!(Level::Error, logcall.level);
            assert!(
                logcall
                    .args
                    .starts_with("error=Error(\"GuestBinary not found:")
            );
            assert_eq!("hyperlight_host::sandbox::uninitialized", logcall.target);
        }
        {
            TEST_LOGGER.clear_log_calls();
            TEST_LOGGER.set_max_level(log::LevelFilter::Error);

            let sbox = {
                let res = UninitializedSandbox::new(
                    GuestBinary::FilePath(simple_guest_as_string().unwrap()),
                    None,
                );
                res.unwrap()
            };
            let _: Result<MultiUseSandbox> = sbox.evolve();

            let num_calls = TEST_LOGGER.num_log_calls();

            assert_eq!(0, num_calls);
        }
    }

    #[test]
    fn test_invalid_path() {
        let invalid_path = "some/path/that/does/not/exist";
        let sbox = UninitializedSandbox::new(GuestBinary::FilePath(invalid_path.to_string()), None);
        println!("{:?}", sbox);
        #[cfg(target_os = "windows")]
        assert!(
            matches!(sbox, Err(e) if e.to_string().contains("GuestBinary not found: 'some/path/that/does/not/exist': The system cannot find the path specified. (os error 3)"))
        );
        #[cfg(target_os = "linux")]
        assert!(
            matches!(sbox, Err(e) if e.to_string().contains("GuestBinary not found: 'some/path/that/does/not/exist': No such file or directory (os error 2)"))
        );
    }

    #[test]
    fn test_from_snapshot_various_configurations() {
        use crate::sandbox::snapshot::Snapshot;

        let binary_path = simple_guest_as_string().unwrap();

        // Test 1: Create snapshot with default config, create multiple sandboxes from it
        {
            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);

            let snapshot = Arc::new(
                Snapshot::from_env(env, Default::default())
                    .expect("Failed to create snapshot with default config"),
            );

            // Create first sandbox from snapshot
            let sandbox1 = UninitializedSandbox::from_snapshot(
                snapshot.clone(),
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create first sandbox from snapshot");

            // Create second sandbox from same snapshot
            let sandbox2 = UninitializedSandbox::from_snapshot(
                snapshot.clone(),
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create second sandbox from snapshot");

            // Both should be able to evolve independently
            let _evolved1: MultiUseSandbox = sandbox1.evolve().expect("Failed to evolve sandbox1");
            let _evolved2: MultiUseSandbox = sandbox2.evolve().expect("Failed to evolve sandbox2");
        }

        // Test 2: Create snapshot with custom heap size
        {
            let mut cfg = SandboxConfiguration::default();
            cfg.set_heap_size(16 * 1024 * 1024); // 16MB heap

            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);

            let snapshot = Arc::new(
                Snapshot::from_env(env, cfg)
                    .expect("Failed to create snapshot with custom heap size"),
            );

            let sandbox = UninitializedSandbox::from_snapshot(
                snapshot,
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox from snapshot with custom heap");

            let _evolved: MultiUseSandbox = sandbox.evolve().expect("Failed to evolve sandbox");
        }

        // Test 3: Create snapshot with custom scratch size
        {
            let mut cfg = SandboxConfiguration::default();
            cfg.set_scratch_size(256 * 1024); // 256KB scratch

            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);

            let snapshot = Arc::new(
                Snapshot::from_env(env, cfg)
                    .expect("Failed to create snapshot with custom stack size"),
            );

            let sandbox = UninitializedSandbox::from_snapshot(
                snapshot,
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox from snapshot with custom stack");

            let _evolved: MultiUseSandbox = sandbox.evolve().expect("Failed to evolve sandbox");
        }

        // Test 4: Create snapshot with custom input/output buffer sizes
        {
            let mut cfg = SandboxConfiguration::default();
            cfg.set_input_data_size(64 * 1024); // 64KB input
            cfg.set_output_data_size(64 * 1024); // 64KB output

            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);

            let snapshot = Arc::new(
                Snapshot::from_env(env, cfg)
                    .expect("Failed to create snapshot with custom buffer sizes"),
            );

            let sandbox = UninitializedSandbox::from_snapshot(
                snapshot,
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox from snapshot with custom buffers");

            let _evolved: MultiUseSandbox = sandbox.evolve().expect("Failed to evolve sandbox");
        }

        // Test 5: Create snapshot with all custom settings
        {
            let mut cfg = SandboxConfiguration::default();
            cfg.set_heap_size(32 * 1024 * 1024); // 32MB heap
            cfg.set_scratch_size(256 * 1024 * 2); // 512KB scratch (256KB will be input/output)
            cfg.set_input_data_size(128 * 1024); // 128KB input
            cfg.set_output_data_size(128 * 1024); // 128KB output

            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);

            let snapshot = Arc::new(
                Snapshot::from_env(env, cfg)
                    .expect("Failed to create snapshot with all custom settings"),
            );

            // Create multiple sandboxes from the same snapshot
            let sandbox1 = UninitializedSandbox::from_snapshot(
                snapshot.clone(),
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox1 from fully customized snapshot");
            let sandbox2 = UninitializedSandbox::from_snapshot(
                snapshot.clone(),
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox2 from fully customized snapshot");
            let sandbox3 = UninitializedSandbox::from_snapshot(
                snapshot.clone(),
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox3 from fully customized snapshot");

            let _evolved1: MultiUseSandbox = sandbox1.evolve().expect("Failed to evolve sandbox1");
            let _evolved2: MultiUseSandbox = sandbox2.evolve().expect("Failed to evolve sandbox2");
            let _evolved3: MultiUseSandbox = sandbox3.evolve().expect("Failed to evolve sandbox3");
        }

        // Test 6: Create snapshot from binary buffer instead of file path
        {
            let binary_bytes = fs::read(&binary_path).expect("Failed to read binary file");

            let snapshot = Arc::new(
                Snapshot::from_env(GuestBinary::Buffer(&binary_bytes), Default::default())
                    .expect("Failed to create snapshot from buffer"),
            );

            let sandbox = UninitializedSandbox::from_snapshot(
                snapshot,
                None,
                #[cfg(crashdump)]
                None,
            )
            .expect("Failed to create sandbox from buffer-based snapshot");

            let _evolved: MultiUseSandbox = sandbox.evolve().expect("Failed to evolve sandbox");
        }

        // Test 7: Register host functions on sandboxes created from snapshot
        {
            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);

            let snapshot = Arc::new(
                Snapshot::from_env(env, Default::default()).expect("Failed to create snapshot"),
            );

            let mut sandbox = UninitializedSandbox::from_snapshot(
                snapshot,
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox from snapshot");

            // Register a custom host function
            sandbox
                .register("CustomAdd", |a: i32, b: i32| Ok(a + b))
                .expect("Failed to register custom function");

            let evolved: MultiUseSandbox = sandbox.evolve().expect("Failed to evolve sandbox");

            // Verify the host function was registered
            let host_funcs = evolved
                .host_funcs
                .try_lock()
                .expect("Failed to lock host funcs");

            let result = host_funcs
                .call_host_function(
                    "CustomAdd",
                    vec![ParameterValue::Int(10), ParameterValue::Int(20)],
                )
                .expect("Failed to call CustomAdd");

            assert_eq!(result, ReturnValue::Int(30));
        }

        // Test 8: Create snapshot with init data (guest blob)
        {
            let init_data = [0xCA, 0xFE, 0xBA, 0xBE];
            let guest_env =
                GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), Some(&init_data));

            let snapshot = Arc::new(
                Snapshot::from_env(guest_env, Default::default())
                    .expect("Failed to create snapshot with init data"),
            );

            let sandbox = UninitializedSandbox::from_snapshot(
                snapshot,
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create sandbox from snapshot with init data");

            let _evolved: MultiUseSandbox = sandbox.evolve().expect("Failed to evolve sandbox");
        }

        // Test 9: Create snapshot from existing sandbox
        {
            let env = GuestEnvironment::new(GuestBinary::FilePath(binary_path.clone()), None);
            let orig_snapshot = Arc::new(
                Snapshot::from_env(env, Default::default())
                    .expect("Failed to create snapshot with default config"),
            );
            let orig_sandbox = UninitializedSandbox::from_snapshot(
                orig_snapshot,
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create orig_sandbox");
            let mut initialized_sandbox = orig_sandbox
                .evolve()
                .expect("Failed to evolve orig_sandbox");
            let new_snapshot = initialized_sandbox
                .snapshot()
                .expect("Failed to create new_snapshot");
            let new_sandbox = UninitializedSandbox::from_snapshot(
                new_snapshot,
                None,
                #[cfg(crashdump)]
                Some(binary_path.clone()),
            )
            .expect("Failed to create new_sandbox");
            let _evolved = new_sandbox.evolve().expect("Failed to evolve new_sandbox");
        }
    }

    #[cfg(feature = "nanvix-unstable")]
    mod guest_counter_tests {
        use hyperlight_testing::simple_guest_as_string;

        use crate::UninitializedSandbox;
        use crate::sandbox::uninitialized::GuestBinary;

        fn make_sandbox() -> UninitializedSandbox {
            UninitializedSandbox::new(
                GuestBinary::FilePath(simple_guest_as_string().expect("Guest Binary Missing")),
                None,
            )
            .expect("Failed to create sandbox")
        }

        #[test]
        fn create_guest_counter() {
            let mut sandbox = make_sandbox();
            let counter = sandbox.guest_counter();
            assert!(counter.is_ok());
        }

        #[test]
        fn only_one_counter_allowed() {
            let mut sandbox = make_sandbox();
            let _c1 = sandbox.guest_counter().unwrap();
            let c2 = sandbox.guest_counter();
            assert!(c2.is_err());
        }

        #[test]
        fn fails_before_build() {
            let mut sandbox = make_sandbox();
            let counter = sandbox.guest_counter().unwrap();
            assert!(counter.increment().is_err());
            assert!(counter.decrement().is_err());
        }

        #[test]
        fn increment_decrement() {
            let mut sandbox = make_sandbox();
            let counter = sandbox.guest_counter().unwrap();
            sandbox.simulate_build();

            counter.increment().unwrap();
            assert_eq!(counter.value().unwrap(), 1);
            counter.increment().unwrap();
            assert_eq!(counter.value().unwrap(), 2);
            counter.decrement().unwrap();
            assert_eq!(counter.value().unwrap(), 1);
        }

        #[test]
        fn underflow_returns_error() {
            let mut sandbox = make_sandbox();
            let counter = sandbox.guest_counter().unwrap();
            sandbox.simulate_build();

            assert_eq!(counter.value().unwrap(), 0);
            let result = counter.decrement();
            assert!(result.is_err());
        }
    }
}