hermit-run 0.4.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
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
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

use std::any::Any;
use std::ffi::CString;
use std::fs;
use std::fs::File;
use std::io;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use std::panic;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;

use anyhow::anyhow;
use detcore_model::config::MountInfoRootRewrite;
use hermit::Context;
use hermit::Error;
use hermit::FailureKind;
use hermit::HERMIT_DEADLINE_EXIT;
use hermit::SerializableError;
use hermit::SkidOvershootError;
use hermit::capture_mountinfo_identity_order;
use nix::sched::CpuSet;
use nix::sched::sched_getaffinity;
use nix::sys::signal::SaFlags;
use nix::sys::signal::SigAction;
use nix::sys::signal::SigHandler;
use nix::sys::signal::SigSet;
use nix::sys::signal::Signal;
use nix::sys::signal::sigaction;
use nix::unistd::Pid;
use reverie::process::Container;
use reverie::process::ExitStatus;
use reverie::process::Mount;
use reverie::process::MountFlags;
use reverie::process::Namespace;
use reverie::process::RunError;

const GROUP_FILE: &str = "/etc/group";
const NSCD_DIR: &str = "/var/run/nscd";
const OVERFLOW_GID: &str = "65534";
const DETERMINISTIC_GROUP_ROOT: &[u8] = b"/tmpvol/.hermit/etc/group";
const DETERMINISTIC_NSCD_ROOT: &[u8] = b"/tmpvol/.hermit/run/nscd";
const DETERMINISTIC_TMP_ROOT: &[u8] = b"/tmpvol/.hermit/tmp";

#[derive(Debug)]
struct MountInfoRootSource {
    source: Option<File>,
    target: PathBuf,
    deterministic_root: Option<Vec<u8>>,
    rewrite_descendant_roots: bool,
    raw_mountpoint_prefix: Option<Vec<u8>>,
    deterministic_mountpoint_prefix: Option<Vec<u8>>,
}

fn open_path(path: &Path) -> io::Result<File> {
    let path = CString::new(path.as_os_str().as_bytes())
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?;
    // O_PATH pins the object without requiring read permission.  The descriptor
    // remains valid if a path is renamed after this point, which is exactly why
    // provenance is carried by descriptors rather than by a second stat(path).
    let fd = unsafe { libc::open(path.as_ptr(), libc::O_PATH | libc::O_CLOEXEC) };
    if fd < 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `open` returned a new owned descriptor above.
    Ok(unsafe { File::from_raw_fd(fd) })
}

fn mount_id_for_fd(fd: i32) -> io::Result<u64> {
    let contents = fs::read(format!("/proc/self/fdinfo/{fd}"))?;
    detcore_model::procfs::parse_fdinfo_mount_id(&contents).ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "fdinfo must contain exactly one decimal mnt_id field",
        )
    })
}

fn mountinfo_root_for_id(raw_mount_id: u64) -> io::Result<Vec<u8>> {
    let contents = fs::read("/proc/self/mountinfo")?;
    let rows = detcore_model::procfs::parse_mountinfo(&contents).ok_or_else(|| {
        io::Error::new(io::ErrorKind::InvalidData, "mountinfo has a malformed row")
    })?;
    rows.into_iter()
        .find(|row| row.raw_mount_id == raw_mount_id)
        .map(|row| row.root)
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "mountinfo omitted the proven mount ID",
            )
        })
}

fn mountinfo_escape_path(path: &Path) -> Vec<u8> {
    let mut encoded = Vec::new();
    for byte in path.as_os_str().as_bytes() {
        match byte {
            b' ' => encoded.extend_from_slice(b"\\040"),
            b'\t' => encoded.extend_from_slice(b"\\011"),
            b'\n' => encoded.extend_from_slice(b"\\012"),
            b'\\' => encoded.extend_from_slice(b"\\134"),
            byte => encoded.push(*byte),
        }
    }
    encoded
}

impl MountInfoRootSource {
    fn new(source: &Path, target: &Path, deterministic_root: &[u8]) -> Result<Self, Error> {
        Ok(Self {
            source: Some(open_path(source).with_context(|| {
                format!(
                    "Failed to pin mountinfo provenance source {}",
                    source.display()
                )
            })?),
            target: target.to_path_buf(),
            deterministic_root: Some(deterministic_root.to_vec()),
            rewrite_descendant_roots: false,
            raw_mountpoint_prefix: None,
            deterministic_mountpoint_prefix: None,
        })
    }

    fn private_tmp(source: &Path) -> Result<Self, Error> {
        let mut provenance = Self::new(source, Path::new("/tmp"), DETERMINISTIC_TMP_ROOT)?;
        provenance.rewrite_descendant_roots = true;
        provenance.raw_mountpoint_prefix = Some(mountinfo_escape_path(source));
        provenance.deterministic_mountpoint_prefix = Some(b"/tmp".to_vec());
        Ok(provenance)
    }

    /// Preserve a user-provided `/tmp` mount's own root while translating the
    /// randomly named staging mountpoint back to the guest path. This does not
    /// claim Hermit ownership of the mounted filesystem: the exact top mount is
    /// selected by a held target descriptor after setup, and only field 5's
    /// internal staging prefix is rewritten.
    fn translated_tmp_mountpoint(staging_path: &Path) -> Self {
        Self {
            source: None,
            target: PathBuf::from("/tmp"),
            deterministic_root: None,
            rewrite_descendant_roots: false,
            raw_mountpoint_prefix: Some(mountinfo_escape_path(staging_path)),
            deterministic_mountpoint_prefix: Some(b"/tmp".to_vec()),
        }
    }

    fn resolve(&self) -> Result<MountInfoRootRewrite, Error> {
        let target = open_path(&self.target).with_context(|| {
            format!(
                "Failed to pin mountinfo provenance target {}",
                self.target.display()
            )
        })?;
        let target_metadata = target.metadata().with_context(|| {
            format!(
                "Failed to inspect pinned mountinfo provenance target {}",
                self.target.display()
            )
        })?;
        if let Some(source) = &self.source {
            let source_metadata = source.metadata().with_context(|| {
                format!(
                    "Failed to inspect pinned mountinfo provenance source for {}",
                    self.target.display()
                )
            })?;
            if (source_metadata.dev(), source_metadata.ino())
                != (target_metadata.dev(), target_metadata.ino())
            {
                return Err(Error::msg(format!(
                    "Refusing mountinfo provenance for {}: the completed mount target does not match \
                     the pinned Hermit-owned source",
                    self.target.display()
                )));
            }
        }
        let raw_mount_id = mount_id_for_fd(target.as_raw_fd()).with_context(|| {
            format!(
                "Failed to identify the mount containing proven target {}",
                self.target.display()
            )
        })?;
        let observed_root = (self.rewrite_descendant_roots || self.deterministic_root.is_none())
            .then(|| mountinfo_root_for_id(raw_mount_id))
            .transpose()
            .with_context(|| {
                format!(
                    "Failed to identify the proven mount root for {}",
                    self.target.display()
                )
            })?;
        let deterministic_root = self
            .deterministic_root
            .clone()
            .or_else(|| observed_root.clone())
            .expect("an explicit or observed root is required");
        Ok(MountInfoRootRewrite {
            raw_mount_id,
            deterministic_root: deterministic_root.clone(),
            raw_root_prefix: self.rewrite_descendant_roots.then(|| {
                observed_root
                    .clone()
                    .expect("descendant rewriting captured the observed root")
            }),
            deterministic_root_prefix: self.rewrite_descendant_roots.then_some(deterministic_root),
            raw_mountpoint_prefix: self.raw_mountpoint_prefix.clone(),
            deterministic_mountpoint_prefix: self.deterministic_mountpoint_prefix.clone(),
        })
    }
}

// Bind mount sources must outlive Reverie's pre-exec container setup, which
// applies the mounts in the forked child before exec. Hold this guard in the
// caller until after `Container::run` returns so the backing temp files still
// exist when the child binds them.
pub(super) struct IdentityGuard {
    _group_file: Option<tempfile::NamedTempFile>,
    _nscd_dir: Option<tempfile::TempDir>,
    mountinfo_roots: Vec<MountInfoRootSource>,
    user_mount_targets: Vec<PathBuf>,
}

impl IdentityGuard {
    /// A guard that owns no backing temp files, for container configurations
    /// (e.g. `--image`) that supply their filesystem from another source and do
    /// not use the frozen-identity bind mounts.
    pub(super) fn empty() -> Self {
        Self {
            _group_file: None,
            _nscd_dir: None,
            mountinfo_roots: Vec::new(),
            user_mount_targets: Vec::new(),
        }
    }

    /// Include an automatically-created private `/tmp` in mountinfo provenance.
    /// User-supplied `--tmp` paths deliberately do not call this method.
    pub(super) fn add_private_tmp(&mut self, source: &Path) -> Result<(), Error> {
        self.mountinfo_roots
            .push(MountInfoRootSource::private_tmp(source)?);
        Ok(())
    }

    /// Translate the internal staging path used for an explicit user mount at
    /// `/tmp`, without rewriting the user mount's root or claiming it as a
    /// Hermit-owned filesystem.
    pub(super) fn add_translated_tmp_mountpoint(&mut self, staging_path: &Path) {
        self.mountinfo_roots
            .push(MountInfoRootSource::translated_tmp_mountpoint(staging_path));
    }

    /// Drop provenance for a Hermit mount hidden by an explicit user mount.
    /// The hidden mount must also be omitted from the mount plan: otherwise its
    /// private root would remain visible as a lower stacked mountinfo row even
    /// though no pathname could reopen that exact layer afterward.
    pub(super) fn discard_mounts_shadowed_by(
        &mut self,
        mounts: &mut Vec<Mount>,
        overriding_target: &Path,
    ) {
        // Host canonicalization describes the namespace only until the first
        // user mount that can replace an ancestor of this target. After that,
        // pathname resolution must follow the ordered mount plan rather than
        // the launcher's host tree. For example, mounting a new `/var` changes
        // what a later `/var/run/nscd` names and must not remove the earlier
        // hardening mount installed at the host-resolved `/run/nscd`.
        let resolution_changed = self
            .user_mount_targets
            .iter()
            .any(|earlier| overriding_target.starts_with(earlier));
        let resolved_override = if resolution_changed {
            overriding_target.to_path_buf()
        } else {
            canonical_mount_target(overriding_target)
        };
        mounts.retain(|mount| {
            !canonical_mount_target(mount.get_target()).starts_with(&resolved_override)
        });
        self.mountinfo_roots.retain(|source| {
            !canonical_mount_target(&source.target).starts_with(&resolved_override)
        });
        self.user_mount_targets
            .push(overriding_target.to_path_buf());
    }

    /// Resolve proven source objects to exact mount IDs in the completed guest
    /// namespace.  This runs after all mounts are installed and before the guest
    /// starts, while the namespace is quiescent.  Held source and target
    /// descriptors plus the target fd's `mnt_id` avoid both pathname TOCTOU and
    /// ambiguity from stacked mounts sharing one textual mountpoint.
    pub(super) fn mountinfo_root_rewrites(&self) -> Result<Vec<MountInfoRootRewrite>, Error> {
        self.mountinfo_roots
            .iter()
            .map(MountInfoRootSource::resolve)
            .collect()
    }

    /// Capture the exact raw mount-ID order used by Detcore's snapshot-local
    /// canonicalizer. This runs in the completed, quiescent guest namespace.
    pub(super) fn mountinfo_identity_order(&self) -> Result<Vec<u64>, Error> {
        capture_mountinfo_identity_order()
            .context("Failed to capture guest mountinfo identity order")
    }
}

fn canonical_mount_target(path: &Path) -> PathBuf {
    for ancestor in path.ancestors() {
        if let Ok(mut canonical) = fs::canonicalize(ancestor)
            && let Ok(suffix) = path.strip_prefix(ancestor)
        {
            canonical.push(suffix);
            return canonical;
        }
    }
    path.to_path_buf()
}

#[cfg(test)]
pub(super) fn mount_target_is_shadowed(target: &Path, overriding_target: &Path) -> bool {
    canonical_mount_target(target).starts_with(canonical_mount_target(overriding_target))
}

/// Snapshot the host group database into a private temp file, appending a
/// synthetic overflow group (`nobody:x:65534`) when the host lacks one. Binding
/// this frozen copy read-only over `/etc/group` keeps guest group-name
/// resolution stable across otherwise-identical runs.
fn frozen_group_file() -> Result<tempfile::NamedTempFile, Error> {
    let mut contents = fs::read_to_string(GROUP_FILE)
        .context("Failed to read the host group database for the guest")?;
    let has_overflow_group = contents.lines().any(|line| {
        line.split(':')
            .nth(2)
            .is_some_and(|gid| gid == OVERFLOW_GID)
    });
    if !has_overflow_group {
        if !contents.ends_with('\n') {
            contents.push('\n');
        }
        contents.push_str("nobody:x:");
        contents.push_str(OVERFLOW_GID);
        contents.push_str(":\n");
    }

    let mut group_file = tempfile::NamedTempFile::new()
        .context("Failed to create the frozen group database for the guest")?;
    group_file
        .write_all(contents.as_bytes())
        .context("Failed to populate the frozen group database for the guest")?;
    group_file
        .as_file()
        .set_permissions(fs::Permissions::from_mode(0o644))
        .context("Failed to set permissions on the frozen guest group database")?;
    Ok(group_file)
}

/// Deterministic identity-resolution mounts shared by `run`, `record`, and
/// `replay`: a frozen `/etc/group` and an empty directory over the host nscd
/// cache. These keep guest NSS lookups from reaching nondeterministic host
/// state (the nscd cache and the systemd-userdb socket), so record/replay
/// reproduce the same group/user resolution that `run` mode already enforces.
/// Returns the mounts plus a guard that must outlive container setup.
pub(super) fn identity_hardening_mounts() -> Result<(Vec<Mount>, IdentityGuard), Error> {
    let group_file = frozen_group_file()?;
    let mut mountinfo_roots = vec![MountInfoRootSource::new(
        group_file.path(),
        Path::new(GROUP_FILE),
        DETERMINISTIC_GROUP_ROOT,
    )?];
    let mut mounts = vec![Mount::bind(group_file.path(), GROUP_FILE).readonly()];

    // Host nscd cache readiness is external state and can differ between runs.
    let nscd_dir = if Path::new(NSCD_DIR).is_dir() {
        let directory =
            tempfile::TempDir::new().context("Failed to create the empty guest nscd directory")?;
        // Preserve Linux pathname resolution: on distributions where
        // /var/run is a symlink to /run, mounting the hardening directory at
        // the resolved target keeps it reachable even if a user later mounts
        // an unrelated /var tree.
        let target = canonical_mount_target(Path::new(NSCD_DIR));
        mountinfo_roots.push(MountInfoRootSource::new(
            directory.path(),
            &target,
            DETERMINISTIC_NSCD_ROOT,
        )?);
        mounts.push(Mount::bind(directory.path(), target).readonly());
        Some(directory)
    } else {
        None
    };

    Ok((
        mounts,
        IdentityGuard {
            _group_file: Some(group_file),
            _nscd_dir: nscd_dir,
            mountinfo_roots,
            user_mount_targets: Vec::new(),
        },
    ))
}

fn choose_affinity_core(allowed: &[usize]) -> Option<usize> {
    (!allowed.is_empty()).then(|| allowed[rand::random_range(0..allowed.len())])
}

fn cpu_ids(affinity: &CpuSet) -> Vec<usize> {
    (0..CpuSet::count())
        .filter(|cpu| affinity.is_set(*cpu).unwrap_or(false))
        .collect()
}

pub(super) fn apply_affinity(container: &mut Container, pin_threads: bool) {
    if pin_threads {
        let affinity = sched_getaffinity(Pid::from_raw(0))
            .expect("failed to query the tracer's allowed CPU affinity mask");
        let allowed = cpu_ids(&affinity);
        let rand_core = choose_affinity_core(&allowed)
            .expect("the tracer's allowed CPU affinity mask is empty");
        tracing::info!("Pinning tracer and guest threads to core {}", rand_core);
        container.affinity(rand_core);
    }
}

pub fn default_container(pin_threads: bool) -> Container {
    let mut container = Container::new();
    container
        .unshare(Namespace::PID)
        .map_root()
        .hostname("hermetic-container.local")
        .domainname("local")
        .mount(Mount::proc().allow_readonly_fallback());

    apply_affinity(&mut container, pin_threads);
    container
}

/// PROTOTYPE: a container whose root filesystem is a materialized OCI image
/// rootfs. This is the *filesystem half* of hermit-as-container-runtime: the
/// guest's file inputs come deterministically from the pinned image rather than
/// from the host filesystem.
///
/// Like the replay chroot path (`replay.rs`), mounts are applied at their
/// literal (pre-chroot) target paths and then `chroot(rootfs)` makes them
/// visible under the new root. We therefore mount the deterministic `/proc`
/// *into* `<rootfs>/proc` (pre-created by the materializer) before chrooting, so
/// the guest sees a `/proc` after entering the image root. The image already
/// carries its own `/etc/group`, loader, and libc — pinned by the image digest —
/// so the frozen-identity hardening mounts that `run` normally adds are
/// unnecessary here. The returned [`IdentityGuard`] still records an
/// automatically-created private `/tmp`; a user-supplied `--tmp` remains
/// unclaimed.
///
/// The CLI currently enables this only for the ptrace backend. Other backends
/// have distinct launch/runtime-file requirements and must be qualified before
/// they can safely share this filesystem setup.
pub(super) fn image_container(
    rootfs: &Path,
    tmpfs: &Path,
    pin_threads: bool,
    private_tmp: bool,
) -> Result<(Container, IdentityGuard), Error> {
    let mut container = Container::new();
    container
        .unshare(Namespace::PID)
        .map_root()
        .hostname("hermetic-container.local")
        .domainname("local");

    // The cache is a deterministic input, not a writable container layer. Bind
    // it onto itself and remount it read-only so a guest cannot poison later
    // runs or mutate run one underneath `--verify` run two. A fresh writable
    // /tmp is mounted separately for ordinary scratch files.
    //
    // Use Reverie's read-only bind rather than a hand-written
    // `MS_BIND | MS_REMOUNT | MS_RDONLY`. When the cache lives on a filesystem
    // mounted `nosuid`, `nodev` or `noexec` outside this user namespace, the
    // kernel locks those flags on the copied mount and refuses (EPERM) any
    // remount that omits them. Reverie restates the source's locked flags in
    // its read-only remount; the hand-written remount did not, so every image
    // run failed at spawn under such a cache.
    container.mount(Mount::bind(rootfs, rootfs).readonly());
    container.mount(Mount::bind(tmpfs, rootfs.join("tmp")).rshared());

    // Mount the deterministic /proc into the target root. The materializer
    // guarantees <rootfs>/proc exists, so we do not need `touch_target()` (which
    // defers dir creation to the pre-exec child on a tiny clone stack).
    let proc_target = rootfs.join("proc");
    container.mount(Mount::proc().allow_readonly_fallback().target(&proc_target));

    // A minimal /dev. An OCI image layer ships no device nodes, so without this
    // the guest sees an empty /dev on a read-only root: `> /dev/null` fails with
    // EROFS and anything wanting a pty fails outright.
    //
    // Every node here is one whose contents a guest cannot use to observe the
    // host:
    //
    // * `null`, `zero` and `full` have kernel-defined, constant behaviour.
    // * `random` and `urandom` are bound only so that `open(2)` finds an inode.
    //   Detcore classifies these two by the path the guest opened
    //   (`FdType::Rng`, see `detcore/src/syscalls/files.rs`) and serves reads
    //   from its deterministic PRNG, so the host entropy pool is never read.
    //   Binding the host node therefore restores functionality without handing
    //   the guest host entropy -- but it does mean the determinism of these two
    //   rests on Detcore's path classification, not on the mount.
    //
    // Deliberately absent:
    //
    // * `/dev/tty` -- its contents *are* the caller's controlling terminal, so it
    //   is pure host coupling, and the guest's behaviour would depend on whether
    //   Hermit was invoked from a terminal or a pipe. Removing exactly that kind
    //   of environmental coupling is the point of image mode. Absent,
    //   `open("/dev/tty")` reports ENOENT instead of ENXIO; both mean "no
    //   controlling terminal".
    // * `/dev/shm` -- a writable shared-memory area is cross-process shared state
    //   and a determinism question in its own right, and nothing in the current
    //   image workloads needs it.
    let dev_root = rootfs.join("dev");
    for node in crate::image::DEV_BIND_TARGETS {
        container.mount(Mount::bind(
            Path::new("/dev").join(node),
            dev_root.join(node),
        ));
    }

    // A FRESH devpts instance, not a bind of the host's. `newinstance` numbers
    // this container's ptys from 0 independently of the host, which is both the
    // isolation-correct and the deterministic choice: binding the host
    // `/dev/ptmx` would allocate out of the host's devpts and leak host-global
    // pty numbers into the guest. `ptmxmode=0666` makes the instance's own
    // `pts/ptmx` usable, which is what the `/dev/ptmx -> pts/ptmx` symlink the
    // materializer creates points at.
    container.mount(
        Mount::devpts(dev_root.join("pts"))
            .data("newinstance,ptmxmode=0666")
            .flags(MountFlags::MS_NOSUID | MountFlags::MS_NOEXEC),
    );

    // Enter the image root last, mirroring the replay chroot ordering
    // (mounts first, then chroot).
    container.chroot(rootfs);

    apply_affinity(&mut container, pin_threads);
    let mut identity_sources = IdentityGuard::empty();
    if private_tmp {
        identity_sources.add_private_tmp(tmpfs)?;
    }
    Ok((container, identity_sources))
}

/// A [`default_container`] hardened with the deterministic identity mounts
/// (frozen `/etc/group`, hidden nscd cache) that `run` mode applies. Replay
/// uses this so guest NSS resolution matches `run` and does not reach
/// nondeterministic host identity state. The returned [`IdentityGuard`] must be
/// held until after `Container::run` returns.
pub(super) fn deterministic_container() -> Result<(Container, IdentityGuard), Error> {
    let mut container = default_container(true);
    let (mounts, identity_guard) = identity_hardening_mounts()?;
    container.mounts(mounts);
    Ok((container, identity_guard))
}

/// Tie the container's init process to the lifetime of the `hermit` process
/// that created it.
///
/// [`Container::run`] forks the process that carries the guest into a fresh PID
/// namespace, so that process is PID 1 *of that namespace*. Linux gives a
/// namespace init the same protection it gives the system init: a signal whose
/// disposition is `SIG_DFL` is discarded rather than delivered, even when the
/// sender is in an ancestor namespace. Only `SIGKILL` and `SIGSTOP` from an
/// ancestor still get through.
///
/// That is why an external deadline could not end a hung run. `timeout N`
/// sends `SIGTERM` to the process group; the outer `hermit` process obeys it
/// and dies, the init process discards it, `timeout` sees its own direct child
/// gone and exits 124 without ever escalating, and the init process is
/// reparented to host PID 1 and keeps running. `timeout --kill-after` does not
/// help, because the escalation is conditioned on that already-dead direct
/// child. Three runs survived this way for more than 45 hours and filled the
/// filesystem.
///
/// `PR_SET_PDEATHSIG` closes that hole from inside: when the thread that forked
/// this process exits, the kernel sends us `SIGKILL`, which is precisely one of
/// the two signals a namespace init cannot ignore. Every existing caller keeps
/// working and no exit code changes, which is why this lives here rather than
/// in each of the ~20 scripts that wrap `hermit` in `timeout`.
///
/// Reverie uses the same idiom for exec'd untraced members in
/// `safeptrace/src/notifier.rs`.
///
/// One residual gap: if the parent somehow died between the fork and this call,
/// no death signal will ever arrive. The usual `getppid()` guard for that race
/// is unavailable here, because inside a new PID namespace the out-of-namespace
/// parent is not mapped and `getppid()` reports 0 whether or not it is alive.
/// Closing it completely would mean arming the signal inside
/// `Container::run` before container setup, which is a Reverie-side change.
/// The window is a few milliseconds of container setup, and the case this
/// guards against is a supervisor deadline seconds or minutes later.
fn arm_parent_death_signal() -> Result<(), Error> {
    // SAFETY: `PR_SET_PDEATHSIG` only sets the calling thread's parent-death
    // signal attribute. It reads and writes no caller memory, and the remaining
    // arguments are ignored for this option.
    if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) } == -1 {
        return Err(std::io::Error::last_os_error()).context(
            "Failed to arm the container init parent-death signal \
             (prctl(PR_SET_PDEATHSIG, SIGKILL)); refusing to start a guest that \
             an expiring deadline could not then kill",
        );
    }
    Ok(())
}

/// The signals whose default action is to terminate the process and which a
/// supervisor, a shell, or a terminal actually sends when it wants a run to
/// stop. Every one of them is discarded by the kernel while the container init
/// leaves it at `SIG_DFL`, so all three are dead letters today: `SIGTERM` from
/// a deadline, `SIGINT` from Ctrl-C, and `SIGHUP` when the owning terminal or
/// agent session goes away.
const CONTAINER_INIT_STOP_SIGNALS: [Signal; 3] = [Signal::SIGTERM, Signal::SIGINT, Signal::SIGHUP];

/// Terminate the container init on a stop signal.
///
/// The exit code is the conventional `128 + signo` a shell reports for a
/// process killed by that signal, rather than a genuine signalled wait status,
/// because a namespace init cannot produce the latter. The usual way to honour
/// a signal faithfully -- restore `SIG_DFL`, unblock, re-raise -- is measurably
/// unavailable here: a plain process dies from that sequence with
/// `WIFSIGNALED` set, but a namespace init survives it, because a self-sent
/// signal does not come from an ancestor namespace and so is discarded exactly
/// like the original. Reporting `128 + signo` is the closest honest
/// approximation available.
///
/// Exiting is a complete teardown, not just this process leaving: the kernel
/// `SIGKILL`s every remaining member of a PID namespace whose init exits, so
/// the guest goes with it instead of being orphaned into a namespace with no
/// init.
extern "C" fn on_container_init_stop_signal(signal: libc::c_int) {
    // SAFETY: `_exit` is async-signal-safe and is the only thing this handler
    // does. It deliberately skips destructors: there is nothing in this process
    // whose cleanup is worth blocking a requested shutdown on, and the
    // caller-side guards live in the parent process.
    unsafe { libc::_exit(128 + signal) }
}

/// Make the container init answer the signals a supervisor actually sends.
///
/// [`arm_parent_death_signal`] handles the case where the `hermit` process
/// dies. This handles the case where it does not: a `SIGTERM` aimed at the run
/// itself, a Ctrl-C, or a `SIGHUP` when the session ends. The kernel discards
/// those only while the disposition is `SIG_DFL`; installing any handler at all
/// is what makes them deliverable to a namespace init, so this both restores
/// the expected behaviour and gives hermit a place to shut a run down on
/// purpose rather than being shot.
///
/// The inherited signal mask matters as much as the disposition. A blocked
/// signal stays pending forever and the handler never runs, which would leave
/// the same silent no-op with a handler installed to suggest otherwise, so the
/// mask is cleared for these three. `record_start.rs` learned the same lesson
/// about `SIGALRM`.
///
/// This runs only after Reverie has set up the container. Until then the init
/// relies on the [`ContainerInitStopSignalBridge`] it inherited at clone.
fn install_container_init_stop_handlers() -> Result<(), Error> {
    let action = SigAction::new(
        SigHandler::Handler(on_container_init_stop_signal),
        SaFlags::empty(),
        SigSet::empty(),
    );

    let mut unblock = SigSet::empty();
    for signal in CONTAINER_INIT_STOP_SIGNALS {
        // SAFETY: the handler performs only `_exit`, which is
        // async-signal-safe, and the action outlives the call.
        unsafe { sigaction(signal, &action) }
            .with_context(|| format!("Failed to install the container init {signal} handler"))?;
        unblock.add(signal);
    }

    unblock
        .thread_unblock()
        .context("Failed to unblock the container init stop signals")?;

    Ok(())
}

/// The pid of the process that installed a [`ContainerInitStopSignalBridge`].
///
/// [`bridge_container_init_stop_signal`] compares it with `getpid()` to tell
/// the `hermit` process, which installed the bridge, apart from a container init
/// that inherited it at clone. A container init with its own PID namespace sees
/// itself as PID 1, and one without sees its own host PID, so neither matches
/// unless the `hermit` process is itself PID 1; see
/// [`ContainerInitStopSignalBridge::install`] for that case.
static STOP_SIGNAL_BRIDGE_HOLDER: AtomicI32 = AtomicI32::new(0);

/// The stop-signal disposition the `hermit` process holds while it clones a
/// container init. See [`ContainerInitStopSignalBridge`].
///
/// In the container init this is [`on_container_init_stop_signal`]: exit
/// `128 + signo`, and so take the namespace down with it.
///
/// In the `hermit` process it reproduces `SIG_DFL`. It restores the default
/// disposition, unblocks the signal and raises it again, so the process dies
/// from the signal with the same wait status it would have had without the
/// bridge. If the `hermit` process is itself a namespace init, the kernel
/// discards the raised signal exactly as it would have discarded the original,
/// and the handler returns.
extern "C" fn bridge_container_init_stop_signal(signal: libc::c_int) {
    // SAFETY: getpid(2) is async-signal-safe, and so is a lock-free atomic load.
    if unsafe { libc::getpid() } != STOP_SIGNAL_BRIDGE_HOLDER.load(Ordering::Relaxed) {
        // Does not return.
        on_container_init_stop_signal(signal);
    }
    // SAFETY: sigaction(2), sigemptyset(3), sigaddset(3), sigprocmask(2) and
    // raise(3) are async-signal-safe, and every pointer passed refers to a local
    // that outlives the call.
    unsafe {
        let mut default: libc::sigaction = std::mem::zeroed();
        default.sa_sigaction = libc::SIG_DFL;
        libc::sigaction(signal, &default, std::ptr::null_mut());
        let mut unblock: libc::sigset_t = std::mem::zeroed();
        libc::sigemptyset(&mut unblock);
        libc::sigaddset(&mut unblock, signal);
        libc::sigprocmask(libc::SIG_UNBLOCK, &unblock, std::ptr::null_mut());
        libc::raise(signal);
    }
}

/// The action currently installed for `signal`, read without changing it.
fn current_signal_action(signal: Signal) -> Result<libc::sigaction, Error> {
    // SAFETY: a null new action makes sigaction(2) a pure query, and `current`
    // is a correctly sized out-parameter that is read only on success.
    let mut current: libc::sigaction = unsafe { std::mem::zeroed() };
    if unsafe { libc::sigaction(signal as libc::c_int, std::ptr::null(), &mut current) } == -1 {
        return Err(std::io::Error::last_os_error())
            .with_context(|| format!("Failed to read the {signal} disposition"));
    }
    Ok(current)
}

/// Stop signals aimed at a container init before it arms its own handlers.
///
/// [`install_container_init_stop_handlers`] runs as the first statement of the
/// container closure. Reverie calls that closure only after it has set up the
/// container: identity maps, mounts, the root change and the new `/proc`. The
/// container init is a PID-namespace init from the moment `clone` returns, and
/// it is visible in `/proc` from then on. For that whole setup window it has
/// whatever disposition it inherited from `hermit`, which is normally
/// `SIG_DFL`, so a `SIGTERM`, `SIGINT` or `SIGHUP` aimed at it is discarded by
/// the kernel at send time. The handler installed a moment later cannot recover
/// a signal that was never queued, so the run keeps going as if nobody had
/// asked it to stop.
///
/// Measured before this guard existed, with a probe that signalled each run's
/// init as soon as it appeared in `/proc`: 12 of 60 signals were sent while
/// `/proc` still showed no handler, and 9 of those 12 were lost (the init was
/// still running 3 seconds later). None of the other 48 was lost. With the guard
/// in place, none of 60 was lost. The integration test
/// `container_init_honours_signals_aimed_at_it_directly` failed this way 6 times
/// in one batch of 360 runs on a loaded host, and none in another.
///
/// No hermit code runs in the container init before Reverie's setup, so the
/// disposition has to be in place when it is created. This guard installs
/// [`bridge_container_init_stop_signal`] in the `hermit` process around the
/// clone, and the new init inherits it. Reverie's setup leaves these
/// dispositions alone: it clears the signal mask and resets only `SIGPIPE`.
/// The container init then replaces the bridge with its own handler.
///
/// Only `SIG_DFL` dispositions are bridged. The bridge reproduces the default
/// action in the `hermit` process exactly, but it cannot reproduce `SIG_IGN`
/// without turning an ignored signal into an interrupted system call, and a
/// handler someone installed deliberately is not ours to replace. A stop signal
/// that `hermit` itself ignores, such as `SIGHUP` under `nohup`, therefore
/// stays discarded until the container init arms.
///
/// Holding a mask instead of a handler would not work. The container init would
/// queue a blocked signal, but Reverie's setup unblocks everything before the
/// handler exists, and the kernel then discards a signal that is still at
/// `SIG_DFL` or `SIG_IGN`. Blocking the signals would also defer a `SIGTERM`
/// aimed at `hermit` itself for the whole run.
#[must_use = "the bridge is removed when this guard is dropped"]
pub(super) struct ContainerInitStopSignalBridge {
    /// Which entries of [`CONTAINER_INIT_STOP_SIGNALS`] this guard bridged.
    bridged: [bool; CONTAINER_INIT_STOP_SIGNALS.len()],
    /// The exact `sa_sigaction` value this guard installed. Drop compares the
    /// current action with this value rather than taking the function's
    /// address again, because Rust does not promise that one function has only
    /// one address.
    handler: libc::sighandler_t,
}

impl ContainerInitStopSignalBridge {
    /// Bridge every stop signal that is currently at `SIG_DFL`.
    ///
    /// Call this in the thread that clones the container init, immediately
    /// before the clone. The query and the install are not one atomic step, so
    /// this relies on the requirement Container already places on its caller:
    /// no other thread is running.
    pub(super) fn install() -> Result<Self, Error> {
        let handler: extern "C" fn(libc::c_int) = bridge_container_init_stop_signal;
        let mut guard = Self {
            bridged: [false; CONTAINER_INIT_STOP_SIGNALS.len()],
            handler: handler as libc::sighandler_t,
        };
        // SAFETY: getpid(2) has no preconditions.
        let holder = unsafe { libc::getpid() };
        if holder == 1 {
            // The container init with its own PID namespace would also see
            // itself as PID 1, so the bridge could not tell the two processes
            // apart. The bridge stays out of the way here, and the container
            // init behaves as it did before the bridge existed. A `hermit` that
            // is PID 1 is a namespace init, so the kernel discards these signals
            // for it in any case.
            return Ok(guard);
        }
        STOP_SIGNAL_BRIDGE_HOLDER.store(holder, Ordering::Relaxed);

        // SAFETY: an all-zero sigaction is a valid value.
        let mut bridge: libc::sigaction = unsafe { std::mem::zeroed() };
        bridge.sa_sigaction = guard.handler;
        bridge.sa_flags = libc::SA_RESTART;
        // SAFETY: sigemptyset(3) and sigaddset(3) only write the mask they are
        // given, which is a field of the local above.
        unsafe {
            libc::sigemptyset(&mut bridge.sa_mask);
            for signal in CONTAINER_INIT_STOP_SIGNALS {
                libc::sigaddset(&mut bridge.sa_mask, signal as libc::c_int);
            }
        }
        for (index, signal) in CONTAINER_INIT_STOP_SIGNALS.into_iter().enumerate() {
            if current_signal_action(signal)?.sa_sigaction != libc::SIG_DFL {
                continue;
            }
            // SAFETY: in the container init the handler performs only `_exit`.
            // In this process it performs only the async-signal-safe calls
            // listed in its body. `bridge` outlives the call.
            if unsafe { libc::sigaction(signal as libc::c_int, &bridge, std::ptr::null_mut()) }
                == -1
            {
                return Err(std::io::Error::last_os_error()).with_context(|| {
                    format!("Failed to install the container init {signal} bridge")
                });
            }
            guard.bridged[index] = true;
        }
        Ok(guard)
    }
}

impl Drop for ContainerInitStopSignalBridge {
    fn drop(&mut self) {
        let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
        for (index, signal) in CONTAINER_INIT_STOP_SIGNALS.into_iter().enumerate() {
            if !self.bridged[index] {
                continue;
            }
            // Undo only our own bridge. The handler may already have restored
            // `SIG_DFL`, and any other action was installed after us on purpose.
            let still_bridged = current_signal_action(signal)
                .is_ok_and(|current| current.sa_sigaction == self.handler);
            if still_bridged {
                // SAFETY: restoring the default action installs no handler.
                let _ = unsafe { sigaction(signal, &default) };
            }
        }
    }
}

/// Test-only: hold a freshly cloned container init before it arms its guards,
/// so a test can aim a stop signal at an init that does not yet have its own
/// handlers.
///
/// Without this the window is well under a millisecond to a few milliseconds of
/// container setup, and an integration test lands in it only by chance: 6 times
/// in one batch of 360 runs on a loaded host, and none in another.
/// [`CONTAINER_INIT_ARMING_STALL`] is longer than any budget that test
/// waits for, so a signal sent within those budgets is necessarily sent, and
/// acted on, before the container init installed anything itself.
///
/// This is keyed off an environment variable rather than `cfg(test)` for the
/// same reason as `run_timeout::stall_the_unwind_if_asked`: the bridge lives in
/// the shipped binary and must be exercised there. The variable is read in the
/// container init from the `hermit` process's environment, never from the
/// guest's.
pub(super) fn stall_container_init_before_arming_if_asked() {
    if std::env::var_os(CONTAINER_INIT_ARMING_STALL_ENV).as_deref()
        != Some(std::ffi::OsStr::new("1"))
    {
        return;
    }
    // Rename the thread for the length of the stall, so the test can see that
    // the init really is waiting here, rather than inferring it from timing or
    // passing against a binary that ignores the variable.
    let mut name = [0u8; 16];
    // SAFETY: PR_GET_NAME writes at most 16 bytes, including the terminator,
    // into `name`; PR_SET_NAME reads a NUL-terminated string of at most 16.
    unsafe {
        libc::prctl(libc::PR_GET_NAME, name.as_mut_ptr());
        libc::prctl(libc::PR_SET_NAME, c"unarmed-init".as_ptr());
    }
    std::thread::sleep(CONTAINER_INIT_ARMING_STALL);
    // SAFETY: as above; `name` is still NUL-terminated.
    unsafe { libc::prctl(libc::PR_SET_NAME, name.as_ptr()) };
}

/// See [`stall_container_init_before_arming_if_asked`].
pub(super) const CONTAINER_INIT_ARMING_STALL_ENV: &str =
    "HERMIT_INTERNAL_STALL_CONTAINER_INIT_BEFORE_ARMING";

/// See [`stall_container_init_before_arming_if_asked`]. The integration test
/// `container_init_honours_signals_sent_before_it_arms` copies this value and
/// the thread name the stall sets.
pub(super) const CONTAINER_INIT_ARMING_STALL: std::time::Duration =
    std::time::Duration::from_secs(60);

/// Arm both container-init guards. Call this as the FIRST statement inside any
/// `Container::run` closure that is not going through [`with_container`].
///
/// Why this is public rather than folded into [`with_container`]: `hermit record`
/// -- every spelling, including `record --verify` -- calls [`Container::run`]
/// directly at six sites in `record_start.rs` and never goes through
/// `with_container`. Those containers come from `recording_container()` ->
/// `configured_container()` -> `default_container(true)`, which unshares
/// `Namespace::PID`, so each one is a namespace init with exactly the bug the
/// guards exist to fix. An adversarial review of the original change caught this:
/// the claim that "all entry points funnel through `with_container`" was FALSE,
/// and `record --verify` is precisely the long-running command an external
/// deadline most needs to be able to end.
///
/// The structurally better home for this is reverie's `Container::run`, before
/// `setup()`, which would also close the fork-to-prctl window. That is a
/// reverie-side change plus a pin bump; this closes the six sites now.
pub(super) fn arm_container_init_guards() -> Result<(), SerializableError> {
    arm_parent_death_signal().map_err(SerializableError::from)?;
    install_container_init_stop_handlers().map_err(SerializableError::from)?;
    Ok(())
}

/// Where the most recent panic inside the container child happened.
///
/// `catch_unwind` hands back the panic PAYLOAD but not the LOCATION, and the
/// location is the more useful half of a divergence report. A panic hook is the
/// only place the location is available, so record it there and read it back
/// after the unwind.
static PANIC_LOCATION: OnceLock<Mutex<Option<String>>> = OnceLock::new();

fn panic_location() -> &'static Mutex<Option<String>> {
    PANIC_LOCATION.get_or_init(|| Mutex::new(None))
}

/// Install the location-recording hook, once, in the container child.
///
/// The previous hook is still called, so the ordinary `thread '...' panicked
/// at ...` report continues to reach stderr; this only ADDS a machine-readable
/// copy of the location.
fn install_panic_location_hook() {
    static INSTALLED: OnceLock<()> = OnceLock::new();
    INSTALLED.get_or_init(|| {
        let previous = panic::take_hook();
        panic::set_hook(Box::new(move |info| {
            if let Some(location) = info.location() {
                let recorded = format!(
                    "{}:{}:{}",
                    location.file(),
                    location.line(),
                    location.column()
                );
                if let Ok(mut slot) = panic_location().lock() {
                    *slot = Some(recorded);
                }
            }
            previous(info);
        }));
    });
}

fn take_panic_location() -> String {
    panic_location()
        .lock()
        .ok()
        .and_then(|mut slot| slot.take())
        .unwrap_or_else(|| "<unknown location>".to_string())
}

fn panic_message(payload: &(dyn Any + Send)) -> String {
    if let Some(message) = payload.downcast_ref::<&'static str>() {
        (*message).to_string()
    } else if let Some(message) = payload.downcast_ref::<String>() {
        message.clone()
    } else {
        "<panic payload was not a string>".to_string()
    }
}

/// Run `f`, converting a panic into an ordinary error.
///
/// WHY THIS EXISTS. The container child's entry point is `extern "C"` (see
/// `reverie_process::clone::clone_with_stack`) and is therefore NOUNWIND. A
/// panic that reaches it hits `panic_cannot_unwind` and ABORTS, and the parent
/// reports that abort as `Signaled(SIGSEGV, true)` -- indistinguishable from a
/// genuine memory fault, with the cause carried nowhere except stderr. That has
/// already sent one investigation hunting a bad dereference that did not exist.
/// Catching the unwind HERE, in Hermit's own closure, means the panic never
/// reaches the nounwind frame and instead travels the result channel
/// `Container::run` already provides.
///
/// This deliberately does NOT change how a REAL fault behaves: `catch_unwind`
/// cannot catch `SIGSEGV`, so a genuine memory fault in the child still aborts
/// and is still reported as a signal. Keeping those two outcomes
/// distinguishable is the point of the change, so both directions are covered
/// by tests.
/// Deliberate fault injection for the two-directional test below. INERT unless
/// `HERMIT_TEST_CONTAINER_CHILD_FAULT` is set, so it cannot fire in normal use.
///
/// Both arms are required, and the SECOND is the one that gives the test its
/// force: if a real fault stopped reporting as a signal after this change, the
/// change would have made a genuine memory error indistinguishable from a
/// caught panic, which is the same blindness in the other direction.
/// ⚠️ AND IT TAKES THE CALL SITE, BECAUSE A FAULT THAT CANNOT BE AIMED CANNOT
/// TEST MORE THAN THE FIRST SITE IT REACHES. `record` enters a container at six
/// sites; with only `HERMIT_TEST_CONTAINER_CHILD_FAULT` set, the FIRST child to
/// run faults and every later stage is never entered. Two of the six -- the
/// replay stages of `--verify` and `--verify-with-gdbex` -- are therefore
/// unreachable by any test, so their classification was asserted rather than
/// measured. `HERMIT_TEST_CONTAINER_CHILD_FAULT_SITE` names which one to hit.
///
/// A LABEL RATHER THAN AN OCCURRENCE INDEX, deliberately. An index is positional:
/// it silently retargets the moment a call site is added, removed or reordered,
/// and the test keeps passing while aiming somewhere else. A label is identity,
/// and identity is the thing whose absence made these two sites untestable. An
/// occurrence counter also cannot be process-local -- each `run_guarded` forks a
/// fresh child and this runs in the CHILD, so a static counter resets to zero
/// every time.
///
/// Unset `..._SITE` keeps the previous behaviour exactly: fault at whichever site
/// is reached first. Existing callers and tests are unaffected.
fn inject_test_fault(site: &str) {
    if std::env::var("HERMIT_TEST_CONTAINER_CHILD_FAULT_SITE").is_ok_and(|want| want != site) {
        return;
    }
    match std::env::var("HERMIT_TEST_CONTAINER_CHILD_FAULT")
        .ok()
        .as_deref()
    {
        Some("panic") => {
            panic!("deliberate container-child panic for fault-injection testing at site {site}")
        }
        Some("segv") => {
            // A genuine memory fault, NOT a panic. catch_unwind must not touch this.
            unsafe { std::ptr::null_mut::<u8>().write_volatile(1) };
        }
        _ => {}
    }
}

/// Returns a [`SerializableError`] rather than a bare [`Error`] so the CLASS
/// survives: a caught panic is tagged HERE, at the only point that still knows
/// one happened, and the tag then crosses the process boundary with the message.
#[cfg(test)]
fn catch_child_panic<F, T>(f: &mut F) -> Result<T, SerializableError>
where
    F: FnMut() -> Result<T, Error>,
{
    install_panic_location_hook();
    match panic::catch_unwind(panic::AssertUnwindSafe(|| {
        inject_test_fault("with_container");
        f()
    })) {
        Ok(result) => result.map_err(SerializableError::from),
        Err(payload) => {
            let location = take_panic_location();
            Err(SerializableError::from(anyhow!(
                "panic in container child at {location}: {}",
                panic_message(&*payload)
            ))
            .into_panic())
        }
    }
}

/// Same child panic boundary with the original explicit call-site fault label.
pub(super) fn catch_child_panic_at<F, T>(
    site: &'static str,
    mut f: F,
) -> Result<T, SerializableError>
where
    F: FnMut() -> Result<T, Error>,
{
    install_panic_location_hook();
    match panic::catch_unwind(panic::AssertUnwindSafe(|| {
        inject_test_fault(site);
        f()
    })) {
        Ok(result) => result.map_err(SerializableError::from),
        Err(payload) => Err(SerializableError::from(anyhow!(
            "panic in container child at {}: {}",
            take_panic_location(),
            panic_message(&*payload)
        ))
        .into_panic()),
    }
}

/// The container child exited with a status IT DID NOT CHOOSE.
///
/// ⚠️ THIS TYPE EXISTS BECAUSE THE STATUS USED TO BE THROWN AWAY HERE, and the
/// information was never missing — only discarded. reverie reports the child's
/// real status as a typed `RunError::ExitStatus(ExitStatus)`; `with_container`
/// then wrote `.context("Sandbox container exited unexpectedly")?`, which turns
/// that typed value into an opaque `anyhow::Error` whose exit code survives only
/// inside Display prose. Nothing downstream could branch on it without parsing
/// English, so a tracer panic (container child dies with Rust's 101) and an
/// ordinary CLI error — a bad flag, an unwritable log path — became the same
/// thing one layer up.
///
/// Carrying it as a downcastable type is the whole fix: no new plumbing, no new
/// channel, just stopping the discard. `main` recovers it with
/// `anyhow::Error::downcast_ref`.
#[derive(Debug)]
pub struct ContainerChildExit(pub ExitStatus);

impl std::fmt::Display for ContainerChildExit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Keep the human text the caller already saw. This type changes what is
        // MACHINE-readable, not what an operator reads.
        write!(f, "Sandbox container exited unexpectedly: {:?}", self.0)
    }
}

impl std::error::Error for ContainerChildExit {}

/// Hermit DELIBERATELY refused the run; the child exited a status hermit CHOSE.
///
/// ⚠️ THIS IS THE INVERSE OF [`ContainerChildExit`], AND SEPARATING THEM IS THE
/// WHOLE POINT. That type means "the child died of something no handler caught".
/// This one means "a fail-closed policy stopped the run on purpose". They are
/// the same observation at this boundary — a container child that exited — and
/// they demand opposite responses: file a bug against hermit, versus read the
/// refusal hermit just printed and change the program or the flags.
///
/// Before this, a policy refusal arrived as `ContainerChildExit(Exited(1))` and
/// surfaced as `HERMIT_INTERNAL_FAILURE class=container-child-exit`, exit 125 —
/// a correct refusal reported as an accident, sending the reader to look for a
/// defect in a shutdown path that behaved as designed.
///
/// The status is the only channel across the fork boundary, so
/// `HERMIT_POLICY_REFUSAL_EXIT` is what carries the distinction. It is safe to
/// key on: an ordinary guest exit does NOT arrive here — it is returned as a
/// value through the `Ok(Ok(..))` arm, which is why `hermit run -- sh -c 'exit
/// 122'` still reports 122 with no failure marker.
#[derive(Debug)]
// A unit struct on purpose: the status is `HERMIT_POLICY_REFUSAL_EXIT` by
// construction -- it is what the match arm keys on -- so carrying a copy would
// be a second place for it to be wrong.
pub struct PolicyRefusal;

impl std::fmt::Display for PolicyRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Hermit refused the run: a fail-closed policy stopped it before completion. \
             This is not a hermit failure; the refusal reason is above."
        )
    }
}

impl std::error::Error for PolicyRefusal {}

/// The container child was terminated by a signal, reported as `128 + signo`.
///
/// Reattaches "a `--timeout` deadline fired" on the PARENT side of the
/// container boundary, where `hermit::GuestTimedOut` no longer exists as a type.
///
/// Carries no number, unlike [`SignalDeath`]: the seconds are already in the
/// child's message and re-parsing them out of English is exactly what
/// `FailureKind` exists to avoid.
#[derive(Debug)]
pub struct RunTimeoutMarker;

impl std::fmt::Display for RunTimeoutMarker {
    /// ⚠️ IT DOES NOT SAY "SEE THE REASON ABOVE", AND AN EARLIER VERSION DID.
    /// [`PolicyRefusal`] can say that truthfully because detcore logs the
    /// refusal before exiting, so the reason really is earlier on stderr. Here
    /// the child's message arrives as a CAUSE, which `display_error` prints
    /// BELOW this line -- measured: the chain reads "Error: ... above" followed
    /// by "> Guest exceeded the --timeout bound of 3 seconds". Pointing the
    /// reader the wrong way is worse than not pointing at all.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "the --timeout bound fired")
    }
}

impl std::error::Error for RunTimeoutMarker {}

/// Carries the signal, unlike [`PolicyRefusal`], because there is more than one
/// and the number is the whole content of the report.
#[derive(Debug)]
pub struct SignalDeath(pub i32);

impl std::fmt::Display for SignalDeath {
    /// ⚠️ IT DOES NOT SAY WHERE THE SIGNAL CAME FROM, AND AN EARLIER VERSION DID.
    /// It read "the run was stopped from outside", which hermit cannot know:
    /// `handle_signal_event` carries no origin, so a guest that signals ITSELF
    /// produces the identical report. Measured --
    /// `hermit run --sigint-instakill -- /bin/sh -c 'kill -INT $$'` exits 130 and
    /// printed that the run was stopped externally, when nothing external
    /// happened. agent(hermit-005)'s codex lane found it.
    ///
    /// That is the same defect this whole change exists to remove: a report
    /// asserting something the system has no channel to observe. What hermit
    /// DOES know is that the container died of a signal rather than of a hermit
    /// decision, and that is now all it claims.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Hermit's container was terminated by signal {}. This is not a hermit \
             failure and not a refusal: hermit did not choose to stop this run.",
            self.0
        )
    }
}

impl std::error::Error for SignalDeath {}

/// The container child PANICKED, and the panic was caught and reported.
///
/// Distinct from [`ContainerChildExit`], which is the child dying of something
/// no handler caught. Both are "the tracer broke"; neither is an ordinary CLI
/// error, and before this they were all three the same thing.
#[derive(Debug)]
pub struct ContainerChildPanic(pub Error);

impl std::fmt::Display for ContainerChildPanic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for ContainerChildPanic {}

/// Helper to run a function inside a container, taking care to display any
/// errors and propagate the exit status.
#[cfg(test)]
pub fn with_container<F, T>(container: &mut Container, mut f: F) -> Result<T, Error>
where
    F: FnMut() -> Result<T, Error>,
    T: serde::Serialize + serde::de::DeserializeOwned,
{
    classify_container_result(container.run(|| {
        // Runs in the freshly forked container init, not in the caller.
        arm_container_init_guards()?;
        catch_child_panic(&mut f)
    }))
}

/// Preserve the primary class from a settled container result. The owned CLI
/// adapter also calls this for its strict error-only failed-child channel.
pub fn classify_container_result<T>(
    ran: Result<Result<T, SerializableError>, RunError>,
) -> Result<T, Error> {
    match ran {
        // The child ran and REPORTED something. Whether that was a caught panic
        // or an error it chose to return is exactly what `kind` preserves; both
        // used to arrive as indistinguishable prose.
        Ok(Ok(value)) => Ok(value),
        Ok(Err(reported)) => {
            let kind = reported.kind();
            let error = Error::from(reported);
            Err(match kind {
                FailureKind::Panic => Error::new(ContainerChildPanic(error)),
                // ⚠️ A REFUSAL REPORTED THROUGH THE ERROR CHANNEL IS STILL A
                // REFUSAL. `hermit record` reaches the same fail-closed policy
                // as `hermit run` but is configured to return a typed error
                // instead of shutting the container down, so it never produces
                // the exit status the run path keys on. Without this arm the two
                // spellings of one policy reported 122 and 125 respectively --
                // "hermit refused" and "hermit broke" -- for the same decision.
                //
                // ⚠️ THE CAUSE IS KEPT AS CONTEXT, NOT REPLACED. `PolicyRefusal`
                // says "the refusal reason is above", which is true on the run
                // path because detcore logs it before exiting. Here the reason
                // -- WHICH syscall -- exists only inside this error, so
                // `Error::new(PolicyRefusal)` would discard the one diagnostic
                // the operator needs while claiming it was printed. Attaching it
                // as context keeps the downcast working and the chain intact.
                FailureKind::PolicyRefusal => error.context(PolicyRefusal),
                FailureKind::SkidOvershoot { count } => error
                    .context(SkidOvershootError::new(count))
                    .context(PolicyRefusal),
                // ⚠️ THE LIMIT IS RE-DERIVED, NOT RE-PARSED. `kind` says a
                // deadline fired; the seconds live only in the message the
                // child wrote, and `RunTimeoutMarker` deliberately carries no
                // number rather than scraping one back out of English. The
                // message itself is still printed as the error chain, so the
                // operator sees the bound; only the machine-readable class is
                // reconstructed here.
                FailureKind::RunTimeout => error.context(RunTimeoutMarker),
                FailureKind::Error => error,
            })
        }
        // PRESERVED, not flattened: the child died with a status it did not pick.
        // A DELIBERATE refusal is separated from an unchosen death BEFORE the
        // catch-all below, because at this boundary they look identical: both
        // are a container child that exited. Only the status distinguishes
        // them, and only because `unrecoverable_shutdown` chose one that says
        // so.
        Err(RunError::ExitStatus(status))
            if status.code() == Some(detcore_model::HERMIT_POLICY_REFUSAL_EXIT) =>
        {
            Err(Error::new(PolicyRefusal))
        }
        // A DEADLINE HERMIT ITSELF ENFORCED, and it needs its own arm for exactly
        // the reason the refusal above does: the init chose this status on
        // purpose, and without an arm it falls through to `ContainerChildExit`
        // and is reported as "the child died with a status it did not pick" --
        // exit 125, `class=container-child-exit`, i.e. "hermit broke" for a
        // bound working as designed. Measured before this arm existed: the
        // `run --timeout` fallback exited the init 124 and the run reported 125.
        Err(RunError::ExitStatus(status)) if status.code() == Some(HERMIT_DEADLINE_EXIT) => {
            Err(Error::new(RunTimeoutMarker))
        }
        // A signal death, before the catch-all for the same reason the refusal arm
        // is: falling through would report a signal-terminated run as an
        // internal failure. `sigint_instakill` and `on_container_init_stop_signal`
        // both land here.
        Err(RunError::ExitStatus(status))
            if status
                .code()
                .and_then(detcore_model::signal_from_exit_status)
                .is_some() =>
        {
            let signal = status
                .code()
                .and_then(detcore_model::signal_from_exit_status)
                .expect("guard just matched");
            Err(Error::new(SignalDeath(signal)))
        }
        Err(RunError::ExitStatus(status)) => Err(Error::new(ContainerChildExit(status))),
        // A spawn failure is a genuine CLI-side failure and keeps its prose.
        Err(error @ RunError::Spawn(_)) => {
            Err(Error::new(error).context("Sandbox container failed to spawn"))
        }
    }
}

#[cfg(test)]
#[path = "../../../tests/common/readonly_proc.rs"]
mod readonly_proc;

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

    /// How long a signalled test child may take to exit before it counts as
    /// having ignored the signal. A child that honours it exits within
    /// microseconds; this only bounds the failing case.
    const STOP_SIGNAL_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);

    /// Run `body` in a forked process, so that the process-wide signal
    /// dispositions and namespaces it changes cannot reach the test harness or
    /// any other test running beside it.
    fn in_isolated_process<T>(body: impl FnMut() -> Result<T, String>) -> T
    where
        T: serde::Serialize + serde::de::DeserializeOwned,
    {
        Container::new()
            .run(body)
            .expect("the isolated test process should run to completion")
            .unwrap_or_else(|error| panic!("{error}"))
    }

    fn set_default_stop_dispositions() -> Result<(), String> {
        let default = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
        for signal in CONTAINER_INIT_STOP_SIGNALS {
            // SAFETY: the default action installs no handler.
            unsafe { sigaction(signal, &default) }.map_err(|error| format!("{signal}: {error}"))?;
        }
        Ok(())
    }

    /// Enter a new user and PID namespace, so that the next child this process
    /// forks is PID 1 of that namespace: a namespace init, like the container
    /// init, for which the kernel discards `SIG_DFL` signals from outside.
    fn enter_new_pid_namespace() -> Result<(), String> {
        // SAFETY: `unshare` touches no caller memory. This process is a fresh
        // fork and has one thread, as a new user namespace requires.
        if unsafe { libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWPID) } == -1 {
            return Err(format!("unshare: {}", io::Error::last_os_error()));
        }
        Ok(())
    }

    /// Fork a child that runs `prepare`, reports through a pipe that it has
    /// done so, and then waits for signals forever without installing any
    /// handler of its own. Returns the child's pid once it has reported.
    fn fork_waiting_child(prepare: fn() -> bool) -> Result<libc::pid_t, String> {
        let mut fds = [0; 2];
        // SAFETY: `fds` is a correctly sized out-parameter.
        if unsafe { libc::pipe(fds.as_mut_ptr()) } == -1 {
            return Err(format!("pipe: {}", io::Error::last_os_error()));
        }
        // SAFETY: the parent is single-threaded, and the child calls only
        // `prepare`, then async-signal-safe functions, and never returns.
        match unsafe { libc::fork() } {
            -1 => Err(format!("fork: {}", io::Error::last_os_error())),
            0 => unsafe {
                libc::close(fds[0]);
                if !prepare() {
                    libc::_exit(99);
                }
                libc::write(fds[1], [1u8].as_ptr().cast(), 1);
                libc::close(fds[1]);
                loop {
                    libc::pause();
                }
            },
            child => {
                let mut ready = 0u8;
                // SAFETY: both descriptors came from the pipe above, and
                // `ready` is a one-byte buffer that outlives the read.
                let read = unsafe {
                    libc::close(fds[1]);
                    let read = libc::read(fds[0], (&mut ready as *mut u8).cast(), 1);
                    libc::close(fds[0]);
                    read
                };
                if read != 1 {
                    return Err(format!(
                        "child {child} exited without reporting that it was ready, so its \
                         preparation failed"
                    ));
                }
                Ok(child)
            }
        }
    }

    /// Send `signal` to `child` and wait for it to exit. Returns its raw wait
    /// status, or `None` if it was still running [`STOP_SIGNAL_BUDGET`] later,
    /// in which case it is killed and reaped.
    fn signal_and_reap(child: libc::pid_t, signal: Signal) -> Result<Option<i32>, String> {
        // SAFETY: `kill` takes a pid and a signal number and touches no caller
        // memory. `child` is our own unreaped child.
        if unsafe { libc::kill(child, signal as libc::c_int) } == -1 {
            return Err(format!(
                "kill({child}, {signal}): {}",
                io::Error::last_os_error()
            ));
        }
        let deadline = std::time::Instant::now() + STOP_SIGNAL_BUDGET;
        loop {
            let mut status = 0;
            // SAFETY: `status` is a valid out-parameter for waitpid(2).
            match unsafe { libc::waitpid(child, &mut status, libc::WNOHANG) } {
                reaped if reaped == child => return Ok(Some(status)),
                -1 => return Err(format!("waitpid({child}): {}", io::Error::last_os_error())),
                _ => {}
            }
            if std::time::Instant::now() >= deadline {
                // SAFETY: as above. SIGKILL reaches a namespace init from its
                // parent namespace, so the blocking wait returns.
                unsafe {
                    libc::kill(child, libc::SIGKILL);
                    libc::waitpid(child, &mut status, 0);
                }
                return Ok(None);
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    fn describe_wait_status(status: Option<i32>) -> String {
        match status {
            None => format!("still running {STOP_SIGNAL_BUDGET:?} after the signal"),
            Some(status) if libc::WIFEXITED(status) => {
                format!("exited {}", libc::WEXITSTATUS(status))
            }
            Some(status) if libc::WIFSIGNALED(status) => {
                format!("killed by signal {}", libc::WTERMSIG(status))
            }
            Some(status) => format!("wait status {status:#x}"),
        }
    }

    /// The window the bridge closes, reproduced without timing: the namespace
    /// init is forked while the bridge is installed and never installs a
    /// handler of its own, so every signal here arrives before the init has
    /// armed anything. Without the bridge the kernel discards all three and the
    /// init is still running when the budget expires.
    #[test]
    fn a_namespace_init_honours_stop_signals_sent_before_it_arms() {
        for signal in CONTAINER_INIT_STOP_SIGNALS {
            let status = in_isolated_process(|| {
                set_default_stop_dispositions()?;
                let _bridge = ContainerInitStopSignalBridge::install()
                    .map_err(|error| format!("{error:#}"))?;
                enter_new_pid_namespace()?;
                let init = fork_waiting_child(|| true)?;
                signal_and_reap(init, signal)
            });
            assert!(
                status.is_some_and(|status| libc::WIFEXITED(status)
                    && libc::WEXITSTATUS(status) == 128 + signal as i32),
                "{signal}: a namespace init that had not armed its own handlers should \
                 exit {}, as `on_container_init_stop_signal` does; it {}",
                128 + signal as i32,
                describe_wait_status(status)
            );
        }
    }

    /// The bridge must not change what a stop signal does to the process that
    /// holds it: the `hermit` process still dies from the signal itself, with
    /// the wait status `SIG_DFL` would have given it.
    #[test]
    fn the_process_holding_the_bridge_still_dies_from_stop_signals() {
        fn hold_the_bridge() -> bool {
            if set_default_stop_dispositions().is_err() {
                return false;
            }
            match ContainerInitStopSignalBridge::install() {
                Ok(bridge) => {
                    std::mem::forget(bridge);
                    true
                }
                Err(_) => false,
            }
        }
        for signal in CONTAINER_INIT_STOP_SIGNALS {
            let status = in_isolated_process(|| {
                let holder = fork_waiting_child(hold_the_bridge)?;
                signal_and_reap(holder, signal)
            });
            assert!(
                status
                    .is_some_and(|status| libc::WIFSIGNALED(status)
                        && libc::WTERMSIG(status) == signal as i32),
                "{signal}: the process holding the bridge should be killed by {signal}; it {}",
                describe_wait_status(status)
            );
        }
    }

    /// Only `SIG_DFL` is bridged, and dropping the guard restores exactly
    /// what was there before.
    #[test]
    fn the_bridge_leaves_ignored_and_handled_signals_alone_and_restores_the_default() {
        extern "C" fn someone_elses_handler(_signal: libc::c_int) {}
        let dispositions = in_isolated_process(|| {
            let read = || -> Result<Vec<libc::sighandler_t>, String> {
                CONTAINER_INIT_STOP_SIGNALS
                    .into_iter()
                    .map(|signal| {
                        current_signal_action(signal)
                            .map(|action| action.sa_sigaction)
                            .map_err(|error| format!("{error:#}"))
                    })
                    .collect()
            };
            let actions = [
                SigHandler::SigDfl,
                SigHandler::SigIgn,
                SigHandler::Handler(someone_elses_handler),
            ];
            for (signal, handler) in CONTAINER_INIT_STOP_SIGNALS.into_iter().zip(actions) {
                let action = SigAction::new(handler, SaFlags::empty(), SigSet::empty());
                // SAFETY: the handler does nothing, and it is never invoked.
                unsafe { sigaction(signal, &action) }
                    .map_err(|error| format!("{signal}: {error}"))?;
            }
            let before = read()?;
            let bridge =
                ContainerInitStopSignalBridge::install().map_err(|error| format!("{error:#}"))?;
            let during = read()?;
            let installed = bridge.handler;
            drop(bridge);
            Ok((before, during, read()?, installed))
        });
        // Compare the values the kernel reports rather than function addresses
        // taken here, which Rust does not promise are unique.
        let (before, during, after, installed) = dispositions;
        let other = before[2];
        assert_eq!(
            before[..2],
            [libc::SIG_DFL, libc::SIG_IGN],
            "SIGTERM starts at SIG_DFL and SIGINT at SIG_IGN"
        );
        assert!(
            ![libc::SIG_DFL, libc::SIG_IGN, installed].contains(&other),
            "SIGHUP starts at a handler that is not the bridge"
        );
        assert_eq!(
            during,
            vec![installed, libc::SIG_IGN, other],
            "only SIGTERM, the signal at SIG_DFL, is bridged while the guard is held"
        );
        assert_eq!(
            after, before,
            "dropping the guard restores every disposition it found"
        );
    }

    /// A `hermit` process that is itself PID 1 cannot be told apart from a
    /// container init with its own PID namespace, so the bridge stays out of
    /// the way rather than guessing which of the two it is running in.
    #[test]
    fn the_bridge_is_not_installed_by_a_process_that_is_pid_1() {
        fn install_as_pid_1() -> bool {
            // SAFETY: getpid(2) has no preconditions.
            if unsafe { libc::getpid() } != 1 || set_default_stop_dispositions().is_err() {
                return false;
            }
            let Ok(bridge) = ContainerInitStopSignalBridge::install() else {
                return false;
            };
            let untouched = CONTAINER_INIT_STOP_SIGNALS.into_iter().all(|signal| {
                current_signal_action(signal)
                    .is_ok_and(|action| action.sa_sigaction == libc::SIG_DFL)
            });
            drop(bridge);
            untouched
        }
        // A child whose check fails exits before reporting, which fails here.
        in_isolated_process(|| {
            enter_new_pid_namespace()?;
            let init = fork_waiting_child(install_as_pid_1)?;
            signal_and_reap(init, Signal::SIGKILL).map(drop)
        });
    }

    fn namespace_proc_contents() -> Result<(String, String), String> {
        Ok((
            fs::read_to_string("/proc/mounts").map_err(|error| error.to_string())?,
            fs::read_to_string("/proc/self/status").map_err(|error| error.to_string())?,
        ))
    }

    #[test]
    fn default_container_uses_readonly_proc_fallback() {
        // The outer child confines the irreversible seccomp filter to this test.
        let (mounts, status) = Container::new()
            .run(|| {
                readonly_proc::deny_writable_mounts().map_err(|error| error.to_string())?;
                default_container(false)
                    .run(namespace_proc_contents)
                    .map_err(|error| format!("{error:?}"))?
            })
            .unwrap()
            .expect("default container should retry its denied proc mount read-only");
        readonly_proc::assert_readonly_proc(&mounts, &status, 1);
    }

    #[test]
    fn image_container_uses_readonly_proc_fallback() {
        let rootfs = tempfile::tempdir().unwrap();
        let tmpfs = tempfile::tempdir().unwrap();
        for directory in ["proc", "tmp", "dev/pts"] {
            fs::create_dir_all(rootfs.path().join(directory)).unwrap();
        }
        for node in crate::image::DEV_BIND_TARGETS {
            File::create(rootfs.path().join("dev").join(node)).unwrap();
        }

        let (mounts, status) = Container::new()
            .run(|| {
                readonly_proc::deny_writable_mounts().map_err(|error| error.to_string())?;
                let (mut container, _identity) =
                    image_container(rootfs.path(), tmpfs.path(), false, true)
                        .map_err(|error| error.to_string())?;
                // This closure is already loaded, so the image needs no executable
                // or libraries. It reads the proc mount after entering the chroot.
                container
                    .run(namespace_proc_contents)
                    .map_err(|error| format!("{error:?}"))?
            })
            .unwrap()
            .expect("image container should retry its denied proc mount read-only");
        readonly_proc::assert_readonly_proc(&mounts, &status, 1);
    }

    /// The image cache can live on a filesystem mounted `nosuid,nodev` outside
    /// Hermit's user namespace (a hardened `/tmp`, a CI sandbox's scratch
    /// tmpfs). The kernel locks those flags on the mount copied into Hermit's
    /// namespace, so the read-only remount of the image root must restate them.
    /// A remount that asks only for `MS_RDONLY` fails with EPERM and the image
    /// container never starts. This builds that filesystem in an outer user
    /// namespace, so the result does not depend on how the host mounted its
    /// temporary directory, and checks that the image root comes up read-only
    /// with both locked flags still present.
    #[test]
    fn image_container_accepts_a_rootfs_on_a_nosuid_nodev_filesystem() {
        fn root_mount_flags() -> Result<(bool, bool, bool), String> {
            let mut stat = std::mem::MaybeUninit::<libc::statvfs>::uninit();
            // SAFETY: the path is a valid NUL-terminated string and `stat` is a
            // correctly sized out-parameter that is read only on success.
            let rc = unsafe { libc::statvfs(c"/".as_ptr(), stat.as_mut_ptr()) };
            if rc != 0 {
                return Err(format!("statvfs /: {}", io::Error::last_os_error()));
            }
            // SAFETY: statvfs returned 0, so it initialized `stat`.
            let flags = unsafe { stat.assume_init() }.f_flag;
            Ok((
                flags & libc::ST_RDONLY != 0,
                flags & libc::ST_NOSUID != 0,
                flags & libc::ST_NODEV != 0,
            ))
        }

        let base = tempfile::tempdir().unwrap();
        let base_path = base.path().to_owned();
        let flags = Container::new()
            .map_root()
            .mount(Mount::tmpfs(&base_path).flags(MountFlags::MS_NOSUID | MountFlags::MS_NODEV))
            .run(move || -> Result<(bool, bool, bool), String> {
                let rootfs = base_path.join("rootfs");
                let tmpfs = base_path.join("scratch");
                for directory in ["proc", "tmp", "dev/pts"] {
                    fs::create_dir_all(rootfs.join(directory)).map_err(|e| e.to_string())?;
                }
                for node in crate::image::DEV_BIND_TARGETS {
                    File::create(rootfs.join("dev").join(node)).map_err(|e| e.to_string())?;
                }
                fs::create_dir(&tmpfs).map_err(|e| e.to_string())?;
                let (mut container, _identity) = image_container(&rootfs, &tmpfs, false, true)
                    .map_err(|error| error.to_string())?;
                container
                    .run(root_mount_flags)
                    .map_err(|error| format!("{error:?}"))?
            })
            .expect("run the outer namespace holding the nosuid,nodev filesystem")
            .expect("an image root on a nosuid,nodev filesystem must mount read-only");
        assert_eq!(
            flags,
            (true, true, true),
            "image root (read-only, nosuid, nodev) flags inside the container"
        );
    }

    /// ⚠️ RECORD MODE REACHES THE SAME POLICY BY A DIFFERENT CHANNEL, and for
    /// one release the two channels disagreed about what happened.
    ///
    /// `hermit run` sets `shutdown_on_unsupported_syscall`, so a refusal calls
    /// `unrecoverable_shutdown` and the STATUS carries the meaning (122).
    /// `hermit record` sets `exit_on_unsupported_syscall` with
    /// `shutdown_on_unsupported_syscall: false` (metadata.rs), so it returns a
    /// typed `UnsupportedSyscallError` through Reverie and produces no status of
    /// its own -- arriving as an ordinary reported error, i.e. 125 and
    /// `class=container-child-exit`, "hermit broke", for a decision hermit made
    /// on purpose.
    ///
    /// Set the kind back to `FailureKind::Error` and this fails.
    #[test]
    fn a_refusal_reported_through_the_error_channel_is_still_a_refusal() {
        let refusal = SerializableError::from(anyhow::Error::new(
            detcore::UnsupportedSyscallError(reverie::syscalls::Sysno::kexec_load),
        ));
        assert_eq!(
            refusal.kind(),
            FailureKind::PolicyRefusal,
            "an UnsupportedSyscallError must be classified at the boundary, which is the \
             last place its TYPE still exists -- past it everything is strings"
        );

        let classified = classify_container_result::<()>(Ok(Err(refusal)))
            .expect_err("a refusal is not a success");
        assert!(
            classified.downcast_ref::<PolicyRefusal>().is_some(),
            "record mode must report the same class as run mode for the same policy"
        );
        assert!(
            classified.downcast_ref::<ContainerChildPanic>().is_none(),
            "a refusal is not a panic"
        );
        // ⚠️ THE CAUSE MUST SURVIVE. `PolicyRefusal` says the reason is above; on
        // this path the reason exists ONLY in this chain, so replacing the error
        // rather than contextualising it would delete the only diagnostic naming
        // WHICH syscall while still claiming it was printed.
        assert!(
            format!("{classified:#}").contains("kexec_load"),
            "the refused syscall must survive into the reported chain: {classified:#}"
        );

        // ⚠️ CONTROL: an ordinary reported error must NOT become a refusal, or
        // this arm would relabel every child-reported failure as deliberate.
        let ordinary = SerializableError::from(anyhow::anyhow!("something broke"));
        assert_eq!(ordinary.kind(), FailureKind::Error);
        let classified = classify_container_result::<()>(Ok(Err(ordinary)))
            .expect_err("an error is not a success");
        assert!(classified.downcast_ref::<PolicyRefusal>().is_none());
    }

    #[test]
    fn skid_overshoot_count_survives_the_container_boundary() {
        let reported = SerializableError::from(Error::new(SkidOvershootError::new(3)));
        assert_eq!(reported.kind(), FailureKind::SkidOvershoot { count: 3 });

        let classified = classify_container_result::<()>(Ok(Err(reported)))
            .expect_err("a skid overshoot is not a success");
        assert!(classified.downcast_ref::<PolicyRefusal>().is_some());
        assert_eq!(
            classified
                .downcast_ref::<SkidOvershootError>()
                .expect("the parent must recover the typed cause")
                .count(),
            3
        );
    }

    /// ⚠️ THE RECOGNITION HALF, WHICH THE END-TO-END TEST DOES NOT WITNESS.
    /// `a_guest_exiting_a_reserved_status_is_not_reported_as_hermit` in
    /// `tests/cli.rs` runs real guests, so every status it sees arrives through
    /// the `Ok(Ok(..))` arm and it never reaches the classifier at all --
    /// agent(hermit-007)'s codex lane proved that by mutation: it still passed
    /// with the signal classifier deleted outright. That test establishes a
    /// guest's own 122/130 is still reported as the guest, which is real and is
    /// the gap hermit#2659 left, but it cannot witness this.
    ///
    /// Feeding the classifier a synthesized `Exited(130)` directly is what
    /// witnesses it, and needs no signal delivery -- which matters because the
    /// end-to-end SIGINT path may not be observable from outside at all: the
    /// outer process can die of the same signal before the child's status is
    /// ever classified.
    ///
    /// Delete the signal arm in `classify_container_result` and this fails.
    #[test]
    fn a_container_child_exiting_in_the_signal_band_is_not_an_internal_failure() {
        use reverie::process::ExitStatus;

        let signal_death = classify_container_result::<()>(Err(RunError::ExitStatus(
            ExitStatus::Exited(detcore_model::HERMIT_SIGINT_DEATH_EXIT),
        )))
        .expect_err("a signal death is not a success");
        assert!(
            signal_death.downcast_ref::<SignalDeath>().is_some(),
            "Exited(130) must classify as a signal death, not as an unchosen child \
             exit -- LiteInst and the exit-code path both key on this distinction"
        );
        assert!(
            signal_death.downcast_ref::<ContainerChildExit>().is_none(),
            "a signal death must not also read as an unaccounted container exit"
        );

        // The refusal arm must still win for 122: the two arms are adjacent and
        // ordering decides meaning.
        let refusal = classify_container_result::<()>(Err(RunError::ExitStatus(
            ExitStatus::Exited(detcore_model::HERMIT_POLICY_REFUSAL_EXIT),
        )))
        .expect_err("a refusal is not a success");
        assert!(refusal.downcast_ref::<PolicyRefusal>().is_some());
        assert!(
            refusal.downcast_ref::<SignalDeath>().is_none(),
            "122 must not parse as a signal death; the const-assert pins them disjoint"
        );

        // ⚠️ CONTROL: a status in neither reserved set must STILL be an unchosen
        // child exit. Without this, a classifier that returned SignalDeath for
        // everything would pass the rows above.
        let unchosen =
            classify_container_result::<()>(Err(RunError::ExitStatus(ExitStatus::Exited(7))))
                .expect_err("an unaccounted exit is not a success");
        assert!(unchosen.downcast_ref::<ContainerChildExit>().is_some());
        assert!(unchosen.downcast_ref::<SignalDeath>().is_none());
    }

    #[test]
    fn child_panic_becomes_an_error_naming_message_and_location() {
        let mut f = || -> Result<(), Error> { panic!("divergence detail that must survive") };
        let reported =
            catch_child_panic(&mut f).expect_err("a panic must not be reported as success");
        // The discriminant is the point: prose alone could not say "panic".
        assert_eq!(
            reported.kind(),
            FailureKind::Panic,
            "a caught panic must be tagged as one at the catch site"
        );
        let error = Error::from(reported);
        let rendered = format!("{error:#}");
        assert!(
            rendered.contains("divergence detail that must survive"),
            "panic message was lost: {rendered}"
        );
        assert!(
            rendered.contains("container.rs:"),
            "panic location was lost, which is the half catch_unwind does not give us: {rendered}"
        );
    }

    #[test]
    fn ordinary_results_pass_through_unchanged() {
        let mut ok = || -> Result<u32, Error> { Ok(7) };
        assert_eq!(catch_child_panic(&mut ok).unwrap(), 7);
        let mut err = || -> Result<u32, Error> { Err(anyhow!("a plain error, not a panic")) };
        let reported = catch_child_panic(&mut err).unwrap_err();
        assert_eq!(
            reported.kind(),
            FailureKind::Error,
            "an ordinary reported error must NOT be tagged as a panic"
        );
        let rendered = format!("{:#}", Error::from(reported));
        assert!(
            rendered.contains("a plain error, not a panic"),
            "{rendered}"
        );
        assert!(
            !rendered.contains("panic in container child"),
            "an ordinary error must not be relabelled as a panic: {rendered}"
        );
    }

    // The frozen group database must always resolve the overflow GID so that
    // guest group-name lookups (e.g. `groups`) do not depend on nondeterministic
    // host NSS. This is what keeps record/replay identity resolution matching
    // `run` mode regardless of whether the host `/etc/group` lists 65534.
    #[test]
    fn identity_hardening_freezes_group_with_overflow_entry() {
        let (mounts, guard) =
            identity_hardening_mounts().expect("identity hardening mounts should be constructible");
        assert!(
            !mounts.is_empty(),
            "expected at least the frozen /etc/group mount"
        );
        let group_file = guard
            ._group_file
            .as_ref()
            .expect("identity hardening must produce a frozen group file");
        let contents = fs::read_to_string(group_file.path())
            .expect("frozen group database should be readable");
        assert!(
            contents
                .lines()
                .any(|line| line.split(':').nth(2) == Some(OVERFLOW_GID)),
            "frozen group database must resolve overflow gid {OVERFLOW_GID}:\n{contents}"
        );
    }

    #[test]
    fn mountinfo_provenance_uses_object_identity_not_temp_name_or_target() {
        let actual = tempfile::NamedTempFile::new().expect("create actual temporary source");
        let target = actual.path().to_path_buf();
        let matching =
            MountInfoRootSource::new(actual.path(), &target, b"/tmpvol/.hermit/matching").unwrap();
        let guard = IdentityGuard {
            _group_file: Some(actual),
            _nscd_dir: None,
            mountinfo_roots: vec![matching],
            user_mount_targets: Vec::new(),
        };

        let rewrites = guard.mountinfo_root_rewrites().unwrap();
        assert_eq!(rewrites.len(), 1);
        assert_eq!(rewrites[0].deterministic_root, b"/tmpvol/.hermit/matching");
        assert_eq!(rewrites[0].raw_root_prefix, None);
        assert_eq!(rewrites[0].raw_mountpoint_prefix, None);
        assert_ne!(rewrites[0].raw_mount_id, 0);
    }

    #[test]
    fn private_tmp_provenance_marks_descendant_roots_for_rewriting() {
        let private_tmp = tempfile::TempDir::new().expect("create private tmp");
        let provenance = MountInfoRootSource::private_tmp(private_tmp.path()).unwrap();
        assert!(provenance.rewrite_descendant_roots);
        assert_eq!(
            provenance.raw_mountpoint_prefix.as_deref(),
            Some(mountinfo_escape_path(private_tmp.path()).as_slice())
        );
        assert_eq!(
            provenance.deterministic_mountpoint_prefix.as_deref(),
            Some(b"/tmp".as_slice())
        );
    }

    #[test]
    fn image_container_registers_only_an_automatic_private_tmp() {
        let rootfs = tempfile::TempDir::new().expect("create image rootfs");
        let private_tmp = tempfile::TempDir::new().expect("create private tmp");
        let (_, generated) = image_container(rootfs.path(), private_tmp.path(), false, true)
            .expect("construct image container with generated tmp");
        assert_eq!(generated.mountinfo_roots.len(), 1);

        let (_, supplied) = image_container(rootfs.path(), private_tmp.path(), false, false)
            .expect("construct image container with user tmp");
        assert!(supplied.mountinfo_roots.is_empty());
    }

    #[test]
    fn fdinfo_mount_id_parser_refuses_malformed_duplicates_and_missing_fields() {
        assert_eq!(
            detcore_model::procfs::parse_fdinfo_mount_id(b"pos:\t0\nmnt_id:\t37\n").unwrap(),
            37
        );
        for malformed in [
            "pos:\t0\n",
            "mnt_id:\tbad\nmnt_id:\t37\n",
            "mnt_id:\t37\nmnt_id:\t38\n",
            "mnt_id:\t37 trailing\n",
            "mnt_id:\t18446744073709551616\n",
        ] {
            assert!(
                detcore_model::procfs::parse_fdinfo_mount_id(malformed.as_bytes()).is_none(),
                "accepted malformed fdinfo: {malformed:?}"
            );
        }
    }

    #[test]
    fn mountinfo_provenance_refuses_a_same_target_lookalike() {
        let actual = tempfile::NamedTempFile::new().expect("create actual temporary source");
        let lookalike = tempfile::NamedTempFile::new().expect("create lookalike temporary source");
        let target = actual.path().to_path_buf();
        let same_target_wrong_source =
            MountInfoRootSource::new(lookalike.path(), &target, b"/tmpvol/.hermit/lookalike")
                .unwrap();
        let guard = IdentityGuard {
            _group_file: Some(actual),
            _nscd_dir: None,
            mountinfo_roots: vec![same_target_wrong_source],
            user_mount_targets: Vec::new(),
        };

        let error = guard.mountinfo_root_rewrites().unwrap_err().to_string();
        assert!(error.contains("does not match the pinned Hermit-owned source"));
    }

    #[test]
    fn explicit_tmp_mount_discards_private_tmp_provenance_before_resolution() {
        let private_tmp = tempfile::TempDir::new().expect("create private tmp");
        let mut guard = IdentityGuard::empty();
        guard.add_private_tmp(private_tmp.path()).unwrap();
        assert_eq!(guard.mountinfo_roots.len(), 1);

        let mut mounts = Vec::new();
        guard.discard_mounts_shadowed_by(&mut mounts, Path::new("/tmp"));
        assert!(guard.mountinfo_roots.is_empty());
    }

    #[test]
    fn ordered_user_mounts_do_not_reuse_stale_host_resolution() {
        let var_run_is_run = fs::canonicalize("/var/run").ok() == fs::canonicalize("/run").ok();
        if !var_run_is_run {
            return;
        }

        let mut guard = IdentityGuard::empty();
        guard.mountinfo_roots.push(MountInfoRootSource {
            source: None,
            target: PathBuf::from("/run/nscd"),
            deterministic_root: Some(DETERMINISTIC_NSCD_ROOT.to_vec()),
            rewrite_descendant_roots: false,
            raw_mountpoint_prefix: None,
            deterministic_mountpoint_prefix: None,
        });
        let mut mounts = vec![Mount::bind("/tmp", "/run/nscd")];

        guard.discard_mounts_shadowed_by(&mut mounts, Path::new("/var"));
        guard.discard_mounts_shadowed_by(&mut mounts, Path::new("/var/run/nscd"));

        assert_eq!(mounts.len(), 1);
        assert_eq!(guard.mountinfo_roots.len(), 1);

        for direct_target in ["/run", "/var/run/nscd"] {
            let mut guard = IdentityGuard::empty();
            guard.mountinfo_roots.push(MountInfoRootSource {
                source: None,
                target: PathBuf::from("/run/nscd"),
                deterministic_root: Some(DETERMINISTIC_NSCD_ROOT.to_vec()),
                rewrite_descendant_roots: false,
                raw_mountpoint_prefix: None,
                deterministic_mountpoint_prefix: None,
            });
            let mut mounts = vec![Mount::bind("/tmp", "/run/nscd")];
            guard.discard_mounts_shadowed_by(&mut mounts, Path::new(direct_target));
            assert!(mounts.is_empty(), "{direct_target} must shadow /run/nscd");
            assert!(guard.mountinfo_roots.is_empty());
        }
    }

    #[test]
    fn shadow_detection_follows_the_host_var_run_target() {
        let var_run_is_run = fs::canonicalize("/var/run").ok() == fs::canonicalize("/run").ok();
        assert_eq!(
            mount_target_is_shadowed(Path::new("/var/run/nscd"), Path::new("/var")),
            !var_run_is_run
        );
        assert_eq!(
            mount_target_is_shadowed(Path::new("/var/run/nscd"), Path::new("/run")),
            var_run_is_run
        );
        assert!(!mount_target_is_shadowed(
            Path::new("/var/run/nscd"),
            Path::new("/var/lib")
        ));
    }

    #[test]
    fn affinity_core_is_an_actual_member_of_a_sparse_allowed_mask() {
        let mut affinity = CpuSet::new();
        for cpu in [7, 31, 211] {
            affinity.set(cpu).expect("valid sparse CPU id");
        }
        let allowed = cpu_ids(&affinity);
        assert_eq!(allowed, [7, 31, 211]);
        for _ in 0..128 {
            let selected = choose_affinity_core(&allowed).expect("non-empty mask");
            assert!(allowed.contains(&selected), "selected CPU {selected}");
        }
        assert_eq!(choose_affinity_core(&[]), None);
    }
}