hermit-run 0.5.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
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
/*
 * 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.
 */

//! Ptrace safety net for syscall instructions missed by SaBRe rewriting.

use std::collections::HashMap;
use std::collections::HashSet;
use std::fs;
use std::io::Read;
use std::ops::Range;
use std::os::unix::process::CommandExt;
use std::os::unix::process::ExitStatusExt;
use std::path::Path;
use std::path::PathBuf;
use std::process::ExitStatus;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;

use anyhow::Context;
use anyhow::Error;
use anyhow::anyhow;
pub use detcore_model::summary::PathEvidence;
use nix::sys::ptrace;
use nix::sys::signal::Signal;
use nix::sys::wait::WaitPidFlag;
use nix::sys::wait::WaitStatus;
use nix::sys::wait::waitpid;
use nix::unistd::Pid;
use reverie_sabre_stats::SabrePatchRoute;
use reverie_sabre_stats::SabreSlowPath;
use reverie_sabre_stats::SabreStats;

const SYSCALL_INSN: [u8; 2] = [0x0f, 0x05];
// SaBRe's SIGILL handler recognizes this reserved two-byte instruction as a
// syscall site that could not be expanded to an out-of-line jump.
const SABRE_SYSCALL_MARKER: [u8; 2] = [0x0f, 0xff];

#[derive(Debug)]
pub struct Output {
    pub status: ExitStatus,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
    pub path_evidence: PathEvidence,
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct MappingClassification {
    trusted: bool,
    trusted_shared_object: Option<PathBuf>,
}

#[derive(Default)]
struct TraceeState {
    pending_patch: Option<PendingPatch>,
    pending_bootstrap: Option<i64>,
}

struct PendingPatch {
    site: usize,
    syscall: u64,
}

struct SignalDiagnostic {
    signal: Signal,
    si_code: Option<i32>,
    si_errno: Option<i32>,
    fault_address: Option<usize>,
    mapping: Option<MappingDiagnostic>,
    instruction_bytes: Option<[u8; 16]>,
    registers: libc::user_regs_struct,
}

struct MappingDiagnostic {
    line: String,
    relative_offset: usize,
    file_offset: usize,
}

fn should_replace_signal_diagnostic(
    existing: Option<(Signal, Option<i32>, bool)>,
    signal: Signal,
    si_code: Option<i32>,
) -> bool {
    // SaBRe handles its reserved SIGILL markers in-process. For an unknown hardware SIGILL it
    // restores SIG_DFL and raises SIGILL again, producing a second ptrace stop from SI_TKILL.
    // Preserve the original kernel fault context across that re-raise, but let a later hardware
    // fault replace it so a successfully handled marker cannot leave stale diagnostics behind.
    if let Some((Signal::SIGILL, Some(existing_code), existing_is_marker)) = existing
        && signal == Signal::SIGILL
        && existing_code > 0
        && !existing_is_marker
        && si_code.is_none_or(|code| code <= 0)
    {
        return false;
    }
    true
}

fn is_sabre_sigill_marker(instruction_bytes: Option<&[u8; 16]>) -> bool {
    instruction_bytes
        .is_some_and(|bytes| matches!(&bytes[..2], [0x0f, 0xff] | [0x0f, 0x0b] | [0x0f, 0x0c]))
}

fn final_physical_exit(status: &WaitStatus) -> Option<(Pid, ExitStatus)> {
    match *status {
        WaitStatus::Exited(pid, code) => Some((pid, ExitStatus::from_raw(code << 8))),
        WaitStatus::Signaled(pid, signal, core_dumped) => {
            let raw = signal as i32 | if core_dumped { 0x80 } else { 0 };
            Some((pid, ExitStatus::from_raw(raw)))
        }
        _ => None,
    }
}

/// Identity of one address space (`mm`). Assigned by this supervisor rather
/// than read from the kernel, which exposes no stable mm identifier.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
struct AddressSpaceId(u64);

/// Page-classification cache, keyed by ADDRESS SPACE rather than by tracee.
///
/// The classification of a page is a property of the mm that maps it, not of
/// the thread that happened to fault on it. Keying by `Pid` was unsound: under
/// `CLONE_VM` every thread in a group shares one mm, so a mutation observed on
/// thread A evicted only A's entries and a sibling B kept serving the
/// pre-mutation verdict for the same page -- letting a raw syscall at a page
/// that is no longer trusted bypass both redirection and accounting, which is
/// exactly the invisible-site class this evidence exists to close.
struct MappingCache {
    entries: HashMap<(AddressSpaceId, usize), MappingClassification>,
    /// Which address space each tracee currently runs in.
    spaces: HashMap<Pid, AddressSpaceId>,
    /// Spaces `space_of` invented for a tracee that reached a stop before its
    /// parent's clone/fork/vfork event placed it. Such a space can stand in
    /// for an mm that other tracees know under a different id.
    provisional: HashSet<AddressSpaceId>,
    next: u64,
}

impl MappingCache {
    fn new(root: Pid) -> Self {
        Self {
            entries: HashMap::new(),
            spaces: HashMap::from([(root, AddressSpaceId(0))]),
            provisional: HashSet::new(),
            next: 1,
        }
    }

    fn fresh(&mut self) -> AddressSpaceId {
        let id = AddressSpaceId(self.next);
        self.next += 1;
        id
    }

    /// The address space `pid` runs in. An unknown tracee gets a fresh space:
    /// we have never cached anything for it, so it can hold nothing stale.
    /// That space is PROVISIONAL until the parent's event places the tracee,
    /// because the tracee may really share its parent's mm.
    fn space_of(&mut self, pid: Pid) -> AddressSpaceId {
        if let Some(id) = self.spaces.get(&pid) {
            return *id;
        }
        let id = self.fresh();
        self.provisional.insert(id);
        self.spaces.insert(pid, id);
        id
    }

    fn get(&mut self, pid: Pid, page: usize) -> Option<&MappingClassification> {
        let space = self.space_of(pid);
        self.entries.get(&(space, page))
    }

    fn insert(&mut self, pid: Pid, page: usize, classification: MappingClassification) {
        let space = self.space_of(pid);
        self.entries.insert((space, page), classification);
    }

    /// Drop every cached page of the address space `pid` runs in -- including
    /// entries cached while a SIBLING thread was executing.
    fn invalidate_address_space(&mut self, pid: Pid) {
        let space = self.space_of(pid);
        self.entries.retain(|(cached, _), _| *cached != space);
    }

    /// Apply one completed mutator's `eviction` to the address space `pid`
    /// runs in, including entries cached while a SIBLING was executing.
    ///
    /// A tracee in a provisional space reached this stop before its parent's
    /// clone event placed it, so the mm it really mutated may be known to the
    /// cache under another id that no range here would reach. Drop the whole
    /// cache then. That is never less than the whole-space eviction every
    /// mutator used to perform.
    fn evict(&mut self, pid: Pid, eviction: &Eviction) {
        let space = self.space_of(pid);
        if self.provisional.contains(&space) {
            self.entries.clear();
            return;
        }
        match eviction {
            Eviction::WholeSpace => self.entries.retain(|(cached, _), _| *cached != space),
            Eviction::Ranges(ranges) => self.entries.retain(|(cached, page), _| {
                *cached != space || !ranges.iter().any(|range| range.contains(page))
            }),
        }
    }

    /// `child` shares `parent`'s address space (CLONE_VM / vfork).
    fn share_address_space(&mut self, parent: Pid, child: Pid) {
        let space = self.space_of(parent);
        self.spaces.insert(child, space);
    }

    /// `child` gets its own address space (fork).
    fn new_address_space(&mut self, child: Pid) {
        let space = self.fresh();
        self.spaces.insert(child, space);
    }

    /// `pid` exec'd: the old mm is gone, so discard it and start a fresh one.
    fn replace_address_space(&mut self, pid: Pid) {
        self.invalidate_address_space(pid);
        let space = self.fresh();
        self.spaces.insert(pid, space);
    }

    /// `pid` exited. Its cached pages stay valid for any sibling still sharing
    /// the mm, so they are dropped only once the last user is gone.
    fn forget(&mut self, pid: Pid) {
        let Some(space) = self.spaces.remove(&pid) else {
            return;
        };
        if !self.spaces.values().any(|other| *other == space) {
            self.entries.retain(|(cached, _), _| *cached != space);
            self.provisional.remove(&space);
        }
    }

    /// Place a newly announced `child` in the right address space.
    ///
    /// `shares_mm` is an OBSERVATION of the child that now exists -- see
    /// `mm_sharing` -- not a prediction from the clone arguments. An earlier
    /// revision read `CLONE_VM` out of the tracee's `clone_args` at the clone3
    /// syscall-entry stop, which is before the kernel copies that buffer: a
    /// concurrently runnable sibling thread could rewrite it in the window and
    /// the recorded intent then disagreed with the child the kernel actually
    /// made, in both directions. Demonstrated with a tracer that rewrites the
    /// buffer after the entry read; `kcmp(KCMP_VM)` at this stop reported the
    /// opposite of the entry value each time.
    fn admit_child(&mut self, parent: Pid, child: Pid, shares_mm: MmSharing) {
        match shares_mm {
            MmSharing::Shared => self.share_address_space(parent, child),
            MmSharing::Private => self.new_address_space(child),
        }
    }
}

struct Supervisor {
    root: Pid,
    tracees: HashSet<Pid>,
    states: HashMap<Pid, TraceeState>,
    mapping_cache: MappingCache,
    /// Identity (inode + canonical path) of the launched SaBRe loader and
    /// plugin. Resolved
    /// once at construction so the exemption binds to the objects this
    /// supervisor actually started, not to whatever a mapping calls itself.
    sabre_id: Option<FileId>,
    plugin_id: Option<FileId>,
    readiness: Arc<AtomicBool>,
    ready_observed: bool,
    patched_sites: HashSet<(Pid, usize)>,
    trusted_shared_object_sites: HashSet<(Pid, usize)>,
    trusted_shared_objects: HashSet<PathBuf>,
    signal_diagnostics: HashMap<Pid, SignalDiagnostic>,
    physical_exit_observer: Arc<detcore::GlobalState>,
    bootstrap_launch: Option<super::sabre_bootstrap::Launch>,
    bootstrap: Option<super::sabre_bootstrap::Bootstrap>,
    /// The statistics page shared with the guest's SaBRe loader, which counts
    /// the dispatches; this supervisor adds its own stops and patches.
    stats: SabreStats,
}

impl Supervisor {
    fn new(
        root: Pid,
        sabre: PathBuf,
        plugin: PathBuf,
        readiness: Arc<AtomicBool>,
        physical_exit_observer: Arc<detcore::GlobalState>,
        bootstrap_launch: super::sabre_bootstrap::Launch,
        stats: SabreStats,
    ) -> Self {
        Self {
            root,
            tracees: HashSet::from([root]),
            states: HashMap::from([(root, TraceeState::default())]),
            mapping_cache: MappingCache::new(root),
            sabre_id: launched_file_id(&sabre),
            plugin_id: launched_file_id(&plugin),
            readiness,
            ready_observed: false,
            patched_sites: HashSet::new(),
            trusted_shared_object_sites: HashSet::new(),
            trusted_shared_objects: HashSet::new(),
            signal_diagnostics: HashMap::new(),
            physical_exit_observer,
            bootstrap_launch: Some(bootstrap_launch),
            bootstrap: None,
            stats,
        }
    }

    fn run(mut self) -> Result<(ExitStatus, PathEvidence), Error> {
        let result = self.run_inner();
        if result.is_err() {
            // Keep every child admitted at a kernel clone stop in the owned
            // set before a bootstrap refusal. Only these traced generations
            // are signalled; no process-name/fleet lookup is involved.
            for pid in &self.tracees {
                let _ = nix::sys::signal::kill(*pid, Signal::SIGKILL);
            }
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
            while !self.tracees.is_empty() && std::time::Instant::now() < deadline {
                let owned: Vec<_> = self.tracees.iter().copied().collect();
                for pid in owned {
                    match waitpid(pid, Some(WaitPidFlag::__WALL | WaitPidFlag::WNOHANG)) {
                        Ok(status) if final_physical_exit(&status).is_some() => {
                            self.remove_tracee(pid);
                            self.physical_exit_observer
                                .complete_physical_process_exit(pid.as_raw());
                        }
                        Ok(
                            WaitStatus::Stopped(..)
                            | WaitStatus::PtraceEvent(..)
                            | WaitStatus::PtraceSyscall(..),
                        ) => {
                            let _ = ptrace::cont(pid, Some(Signal::SIGKILL));
                        }
                        Ok(_) | Err(nix::errno::Errno::EINTR) => {}
                        Err(error) => {
                            return Err(anyhow!(
                                "SaBRe owned-child cleanup refused after {result:?}: {error}"
                            ));
                        }
                    }
                }
                if !self.tracees.is_empty() {
                    std::thread::sleep(std::time::Duration::from_millis(10));
                }
            }
            if !self.tracees.is_empty() {
                return Err(anyhow!(
                    "SaBRe owned-child cleanup timed out after {result:?}"
                ));
            }
        }
        result
    }

    fn run_inner(&mut self) -> Result<(ExitStatus, PathEvidence), Error> {
        ptrace::attach(self.root).context("failed to attach SaBRe supervisor worker")?;
        match waitpid(self.root, Some(WaitPidFlag::__WALL))? {
            WaitStatus::Stopped(pid, Signal::SIGSTOP) if pid == self.root => {}
            status => {
                return Err(anyhow!(
                    "unexpected SaBRe supervisor attach stop: {status:?}"
                ));
            }
        }
        tracing::trace!(
            target: "hermit::sabre::fallback",
            tid = self.root.as_raw(),
            "received supervisor attach stop",
        );
        self.bootstrap = Some(super::sabre_bootstrap::Bootstrap::new(
            self.root,
            self.bootstrap_launch
                .take()
                .ok_or_else(|| anyhow!("bootstrap launch consumed twice"))?,
        )?);
        self.set_options(self.root)
            .context("failed to set options on the initial SaBRe tracee")?;
        ptrace::syscall(self.root, None)
            .context("failed to resume the initial SaBRe tracee with PTRACE_SYSCALL")?;

        let mut root_status = None;
        while !self.tracees.is_empty() {
            let status = match waitpid(Pid::from_raw(-1), Some(WaitPidFlag::__WALL)) {
                Ok(status) => status,
                Err(nix::errno::Errno::EINTR) => continue,
                Err(error) => return Err(error.into()),
            };
            tracing::trace!(
                target: "hermit::sabre::fallback",
                ?status,
                "received ptrace wait status",
            );
            if let Some((pid, exit_status)) = final_physical_exit(&status) {
                if let WaitStatus::Signaled(_, signal, _) = status
                    && let Some(diagnostic) = self
                        .signal_diagnostics
                        .get(&pid)
                        .filter(|diagnostic| diagnostic.signal == signal)
                {
                    let instruction_bytes = diagnostic.instruction_bytes.as_ref().map(|bytes| {
                        bytes
                            .iter()
                            .map(|byte| format!("{byte:02x}"))
                            .collect::<Vec<_>>()
                            .join(" ")
                    });
                    tracing::error!(
                        target: "hermit::sabre::fallback",
                        tid = pid.as_raw(),
                        ?signal,
                        si_code = diagnostic.si_code,
                        si_errno = diagnostic.si_errno,
                        rip = format!("{:#x}", diagnostic.registers.rip),
                        rsp = format!("{:#x}", diagnostic.registers.rsp),
                        fault_address = diagnostic
                            .fault_address
                            .map(|address| format!("{address:#x}")),
                        mapping = diagnostic
                            .mapping
                            .as_ref()
                            .map(|mapping| mapping.line.as_str()),
                        file_offset = diagnostic
                            .mapping
                            .as_ref()
                            .map(|mapping| format!("{:#x}", mapping.file_offset)),
                        relative_offset = diagnostic
                            .mapping
                            .as_ref()
                            .map(|mapping| format!("{:#x}", mapping.relative_offset)),
                        instruction_bytes,
                        rax = format!("{:#x}", diagnostic.registers.rax),
                        rbx = format!("{:#x}", diagnostic.registers.rbx),
                        rcx = format!("{:#x}", diagnostic.registers.rcx),
                        rdx = format!("{:#x}", diagnostic.registers.rdx),
                        rsi = format!("{:#x}", diagnostic.registers.rsi),
                        rdi = format!("{:#x}", diagnostic.registers.rdi),
                        rbp = format!("{:#x}", diagnostic.registers.rbp),
                        r8 = format!("{:#x}", diagnostic.registers.r8),
                        r9 = format!("{:#x}", diagnostic.registers.r9),
                        r10 = format!("{:#x}", diagnostic.registers.r10),
                        r11 = format!("{:#x}", diagnostic.registers.r11),
                        r12 = format!("{:#x}", diagnostic.registers.r12),
                        r13 = format!("{:#x}", diagnostic.registers.r13),
                        r14 = format!("{:#x}", diagnostic.registers.r14),
                        r15 = format!("{:#x}", diagnostic.registers.r15),
                        orig_rax = format!("{:#x}", diagnostic.registers.orig_rax),
                        eflags = format!("{:#x}", diagnostic.registers.eflags),
                        cs = format!("{:#x}", diagnostic.registers.cs),
                        ss = format!("{:#x}", diagnostic.registers.ss),
                        fs_base = format!("{:#x}", diagnostic.registers.fs_base),
                        gs_base = format!("{:#x}", diagnostic.registers.gs_base),
                        "SaBRe tracee terminated by a fatal signal",
                    );
                }
                self.remove_tracee(pid);
                self.physical_exit_observer
                    .complete_physical_process_exit(pid.as_raw());
                if pid == self.root {
                    root_status = Some(exit_status);
                }
                continue;
            }
            match status {
                WaitStatus::PtraceSyscall(pid) => self.handle_syscall_stop(pid)?,
                WaitStatus::PtraceEvent(pid, _, event) => self.handle_ptrace_event(pid, event)?,
                WaitStatus::Stopped(pid, signal) => {
                    self.bootstrap
                        .as_mut()
                        .expect("attached bootstrap")
                        .signal(pid, signal)?;
                    if signal == Signal::SIGSTOP && pid != self.root {
                        self.states.entry(pid).or_default();
                        self.tracees.insert(pid);
                        self.set_options(pid)?;
                        self.resume(pid, None)?;
                    } else {
                        if !matches!(signal, Signal::SIGSTOP | Signal::SIGCHLD) {
                            let registers = ptrace::getregs(pid).ok();
                            let rip = registers.as_ref().map_or(0, |registers| registers.rip);
                            let captures_fault_context = matches!(
                                signal,
                                Signal::SIGSEGV
                                    | Signal::SIGILL
                                    | Signal::SIGBUS
                                    | Signal::SIGFPE
                                    | Signal::SIGABRT
                            );
                            if captures_fault_context {
                                let siginfo = ptrace::getsiginfo(pid).ok();
                                let si_code = siginfo.as_ref().map(|info| info.si_code);
                                let existing =
                                    self.signal_diagnostics.get(&pid).map(|diagnostic| {
                                        (
                                            diagnostic.signal,
                                            diagnostic.si_code,
                                            is_sabre_sigill_marker(
                                                diagnostic.instruction_bytes.as_ref(),
                                            ),
                                        )
                                    });
                                if should_replace_signal_diagnostic(existing, signal, si_code) {
                                    if let Some(registers) = registers {
                                        let fault_address = siginfo
                                            .as_ref()
                                            .filter(|info| info.si_code > 0)
                                            .map(|info| unsafe { info.si_addr() as usize });
                                        let mapping = fs::read_to_string(format!(
                                            "/proc/{}/maps",
                                            pid.as_raw()
                                        ))
                                        .ok()
                                        .and_then(|maps| mapping_diagnostic(&maps, rip as usize));
                                        let instruction_bytes =
                                            read_diagnostic_bytes(pid, rip as usize).ok();
                                        self.signal_diagnostics.insert(
                                            pid,
                                            SignalDiagnostic {
                                                signal,
                                                si_code,
                                                si_errno: siginfo
                                                    .as_ref()
                                                    .map(|info| info.si_errno),
                                                fault_address,
                                                mapping,
                                                instruction_bytes,
                                                registers,
                                            },
                                        );
                                    } else {
                                        self.signal_diagnostics.remove(&pid);
                                    }
                                }
                            }
                            tracing::debug!(
                                target: "hermit::sabre::fallback",
                                tid = pid.as_raw(),
                                ?signal,
                                rip = format!("{rip:#x}"),
                                "forwarding signal to tracee",
                            );
                        }
                        self.resume(pid, Some(signal))?;
                    }
                }
                WaitStatus::Exited(..) | WaitStatus::Signaled(..) => unreachable!(),
                WaitStatus::Continued(_) | WaitStatus::StillAlive => {}
            }
        }

        let status = root_status.ok_or_else(|| anyhow!("SaBRe root tracee disappeared"))?;
        let mut trusted_shared_objects = self
            .trusted_shared_objects
            .iter()
            .map(|path| path.display().to_string())
            .collect::<Vec<_>>();
        trusted_shared_objects.sort();
        Ok((
            status,
            PathEvidence {
                schema: PathEvidence::SCHEMA,
                guest_rpc_observed: self.readiness.load(Ordering::Acquire),
                ptrace_fallback_sites: self.patched_sites.len(),
                trusted_shared_object_sites: self.trusted_shared_object_sites.len(),
                trusted_shared_objects,
            },
        ))
    }

    fn set_options(&self, pid: Pid) -> Result<(), Error> {
        ptrace::setoptions(
            pid,
            ptrace::Options::PTRACE_O_EXITKILL
                | ptrace::Options::PTRACE_O_TRACESYSGOOD
                | ptrace::Options::PTRACE_O_TRACECLONE
                | ptrace::Options::PTRACE_O_TRACEFORK
                | ptrace::Options::PTRACE_O_TRACEVFORK
                | ptrace::Options::PTRACE_O_TRACEEXEC
                | ptrace::Options::PTRACE_O_TRACEEXIT,
        )?;
        Ok(())
    }

    fn handle_syscall_stop(&mut self, pid: Pid) -> Result<(), Error> {
        let syscall_info = get_syscall_info(pid)?;
        tracing::trace!(
            target: "hermit::sabre::fallback",
            tid = pid.as_raw(),
            op = syscall_info.op,
            "decoded ptrace syscall stop",
        );
        match syscall_info.op {
            libc::PTRACE_SYSCALL_INFO_ENTRY => {
                self.stats
                    .increment_slow_path(SabreSlowPath::PtraceSyscallEntry);
                let mut regs = ptrace::getregs(pid)?;
                let state = self.states.entry(pid).or_default();
                if state.pending_bootstrap.is_some() || state.pending_patch.is_some() {
                    return Err(anyhow!("overlapping SaBRe syscall-entry state for {pid}"));
                }
                if let Some(response) = self
                    .bootstrap
                    .as_mut()
                    .expect("attached bootstrap")
                    .request(pid, &regs)?
                {
                    regs.orig_rax = u64::MAX;
                    ptrace::setregs(pid, regs)?;
                    self.states.entry(pid).or_default().pending_bootstrap = Some(response);
                    return self.resume(pid, None);
                }
                let site = regs
                    .rip
                    .checked_sub(SYSCALL_INSN.len() as u64)
                    .ok_or_else(|| anyhow!("invalid syscall RIP {:#x} in tracee {pid}", regs.rip))?
                    as usize;
                let bytes = read_two_bytes(pid, site)?;
                let fallback_ready = self.fallback_ready()?;
                if pid != self.root {
                    tracing::trace!(
                        target: "hermit::sabre::fallback",
                        tid = pid.as_raw(),
                        nr = regs.orig_rax,
                        site = format!("{site:#x}"),
                        raw = bytes == SYSCALL_INSN,
                        "child syscall entry",
                    );
                }
                if bytes == SYSCALL_INSN && fallback_ready {
                    let mapping = self.classify_mapping(pid, site)?;
                    if let Some(path) = mapping.trusted_shared_object {
                        self.trusted_shared_object_sites.insert((pid, site));
                        self.trusted_shared_objects.insert(path);
                    }
                    if !mapping.trusted {
                        write_two_bytes(pid, site, SABRE_SYSCALL_MARKER)?;
                        self.stats.record_patch(
                            site as u64,
                            SABRE_SYSCALL_MARKER.len() as u8,
                            SabrePatchRoute::PtraceInstalledMarker,
                        );
                        self.stats
                            .increment_slow_path(SabreSlowPath::PtraceRawSyscallRedirect);
                        let syscall = regs.orig_rax;
                        regs.orig_rax = u64::MAX;
                        ptrace::setregs(pid, regs)?;
                        self.states.entry(pid).or_default().pending_patch =
                            Some(PendingPatch { site, syscall });
                        self.patched_sites.insert((pid, site));
                        tracing::debug!(
                            target: "hermit::sabre::fallback",
                            tid = pid.as_raw(),
                            address = site,
                            "redirecting raw syscall instruction through the SaBRe handler",
                        );
                    }
                }
            }
            libc::PTRACE_SYSCALL_INFO_EXIT => {
                self.stats
                    .increment_slow_path(SabreSlowPath::PtraceSyscallExit);
                // A cached verdict describes the mapping that occupied that page
                // when it was classified. mmap/munmap/mremap/mprotect/brk/shmat
                // can replace or re-permission that page in-process, so a page
                // previously classified as trusted can come to host a
                // completely different raw-syscall site. Whenever this tracee
                // mutates its ADDRESS SPACE, drop the cached pages the
                // mutation can have changed: its exact page range where the
                // kernel confines the change to one, otherwise the whole space
                // (see `mutation_eviction`). The next site there is
                // reclassified against live /proc/<pid>/maps. Evicting the
                // whole space on EVERY mutation made each later site re-read
                // and re-parse that file, which was most of this supervisor's
                // CPU: https://github.com/rrnewton/hermit/issues/3378.
                let exit_regs = ptrace::getregs(pid)?;
                if let Some(response) = self.states.entry(pid).or_default().pending_bootstrap.take()
                {
                    if exit_regs.orig_rax != u64::MAX
                        || self.states.entry(pid).or_default().pending_patch.is_some()
                    {
                        return Err(anyhow!("mismatched bootstrap syscall exit for {pid}"));
                    }
                    let mut regs = exit_regs;
                    regs.rax = response as u64;
                    ptrace::setregs(pid, regs)?;
                    return self.resume(pid, None);
                }
                if mutates_address_space(exit_regs.orig_rax) {
                    // Evict from the whole ADDRESS SPACE, not just this
                    // thread's entries: CLONE_VM siblings share one mm, so a
                    // sibling would otherwise keep serving a pre-mutation
                    // verdict for the very page this syscall just replaced.
                    self.mapping_cache
                        .evict(pid, &mutation_eviction(&exit_regs));
                }
                if let Some(pending) = self.states.entry(pid).or_default().pending_patch.take() {
                    let mut regs = exit_regs;
                    regs.rax = pending.syscall;
                    regs.orig_rax = pending.syscall;
                    regs.rip = pending.site as u64;
                    ptrace::setregs(pid, regs)?;
                }
            }
            _ => {}
        }
        ptrace::syscall(pid, None)?;
        Ok(())
    }

    fn handle_ptrace_event(&mut self, pid: Pid, event: libc::c_int) -> Result<(), Error> {
        if !self.tracees.contains(&pid) {
            return Err(anyhow!("ptrace event is not in the owned SaBRe lineage"));
        }
        if matches!(
            event,
            libc::PTRACE_EVENT_CLONE | libc::PTRACE_EVENT_FORK | libc::PTRACE_EVENT_VFORK
        ) {
            let child = Pid::from_raw(ptrace::getevent(pid)? as i32);
            self.tracees.insert(child);
            self.states.entry(child).or_default();
            // Ask the kernel whether the child it just made shares this mm.
            // Both tasks are alive at THIS stop and nowhere later, which is the
            // only window in which the question can be answered by observation
            // rather than predicted from the clone arguments.
            let shares_mm = mm_sharing(pid, child);
            self.mapping_cache.admit_child(pid, child, shares_mm);
        } else if event == libc::PTRACE_EVENT_EXEC {
            // exec installs a brand-new mm and tears down the old one.
            self.mapping_cache.replace_address_space(pid);
            self.states.insert(pid, TraceeState::default());
            self.signal_diagnostics.remove(&pid);
        }
        // The kernel-reported child is already owned above before this can
        // reject an unsupported pre-handoff transition.
        self.bootstrap
            .as_mut()
            .expect("attached bootstrap")
            .event(pid, event)?;
        self.resume(pid, None)
    }

    fn resume(&self, pid: Pid, signal: Option<Signal>) -> Result<(), Error> {
        ptrace::syscall(pid, signal)?;
        Ok(())
    }
    fn fallback_ready(&mut self) -> Result<bool, Error> {
        let ready = self.readiness.load(Ordering::Acquire);
        if ready && !self.ready_observed {
            self.ready_observed = true;
            tracing::debug!(
                target: "hermit::sabre::fallback",
                "SaBRe fallback readiness observed",
            );
        }
        Ok(ready)
    }

    fn classify_mapping(
        &mut self,
        pid: Pid,
        address: usize,
    ) -> Result<MappingClassification, Error> {
        let page = address & !(PAGE_SIZE - 1);
        if let Some(classification) = self.mapping_cache.get(pid, page) {
            return Ok(classification.clone());
        }
        let maps = fs::read_to_string(format!("/proc/{}/maps", pid.as_raw()))?;
        let classification = mapping_entry(&maps, address).map_or(
            MappingClassification {
                trusted: false,
                trusted_shared_object: None,
            },
            |entry| classify_mapping(&entry, self.sabre_id.as_ref(), self.plugin_id.as_ref()),
        );
        self.mapping_cache.insert(pid, page, classification.clone());
        Ok(classification)
    }

    fn remove_tracee(&mut self, pid: Pid) {
        if let Some(bootstrap) = self.bootstrap.as_mut() {
            bootstrap.forget(pid);
        }
        self.tracees.remove(&pid);
        self.states.remove(&pid);
        self.mapping_cache.forget(pid);
        self.signal_diagnostics.remove(&pid);
    }
}

// nix 0.30.1 passes a null `addr` to PTRACE_GET_SYSCALL_INFO, but Linux
// defines that argument as the size of the output buffer. Use the kernel ABI
// directly until the upstream wrapper supplies the required size.
fn get_syscall_info(pid: Pid) -> Result<libc::ptrace_syscall_info, Error> {
    let mut info = std::mem::MaybeUninit::<libc::ptrace_syscall_info>::zeroed();
    let size = std::mem::size_of::<libc::ptrace_syscall_info>();
    let written = unsafe {
        libc::ptrace(
            libc::PTRACE_GET_SYSCALL_INFO,
            pid.as_raw(),
            size as *mut libc::c_void,
            info.as_mut_ptr().cast::<libc::c_void>(),
        )
    };
    if written < 0 {
        return Err(std::io::Error::last_os_error().into());
    }
    if written == 0 {
        return Err(anyhow!(
            "PTRACE_GET_SYSCALL_INFO returned no data for {pid}"
        ));
    }
    Ok(unsafe { info.assume_init() })
}

fn mapping_line(maps: &str, address: usize) -> Option<&str> {
    maps.lines().find_map(|line| {
        let mut fields = line.split_whitespace();
        let range = fields.next()?;
        let mut limits = range.split('-');
        let start = usize::from_str_radix(limits.next()?, 16).ok()?;
        let end = usize::from_str_radix(limits.next()?, 16).ok()?;
        (start <= address && address < end).then_some(line)
    })
}

/// Identity of a mapped file: its `inode` plus the canonicalized path the
/// object resolves to. This names the object itself rather than a path anyone
/// can reproduce with the same basename.
///
/// `dev` is deliberately NOT part of the identity. It looks like the obvious
/// second component and it is the one that does not survive the comparison:
/// `stat(2)` reports the filesystem's `st_dev`, while `/proc/<pid>/maps` prints
/// the SUPERBLOCK device, and on btrfs those differ because every subvolume
/// gets its own anonymous `st_dev`. Measured on one file on a btrfs developer
/// box: `stat()` gives `st_dev = 46` (rendered `00:2e`) while the maps row for
/// the very same mapping of that very same inode prints `00:2d`. Comparing
/// them made the SaBRe loader unrecognisable as infrastructure, so the
/// supervisor patched a UD0 marker into the loader's own text and the guest
/// died with SIGSEGV. `inode` is the discriminating component and it agrees;
/// the canonicalized path is what rules out an inode collision across
/// filesystems, which is the only way two distinct files can share one.
#[derive(Clone, Debug, Eq, PartialEq)]
struct FileId {
    inode: u64,
    path: PathBuf,
}

/// One parsed `/proc/<pid>/maps` row: `range perms offset dev inode path`.
struct MappingEntry<'a> {
    inode: Option<u64>,
    path: &'a str,
}

impl MappingEntry<'_> {
    /// `None` for anonymous or pseudo mappings (inode 0), which have no file
    /// identity to bind to and therefore can never match a launched object.
    fn file_id(&self) -> Option<FileId> {
        match self.inode {
            Some(inode) if inode != 0 => {
                // The kernel already prints an absolute, resolved path here;
                // canonicalizing anyway keeps both sides of the comparison in
                // the same form. A path that no longer resolves (a deleted or
                // replaced file) yields `None`, which fails CLOSED: no identity
                // means no match and therefore no exemption.
                let path = fs::canonicalize(Path::new(self.path)).ok()?;
                Some(FileId { inode, path })
            }
            _ => None,
        }
    }
}

/// Identity of a path this supervisor launched. `None` when the file cannot be
/// stat'ed, which fails CLOSED: an unknown identity matches no mapping, so the
/// exemption is withheld rather than granted.
fn launched_file_id(path: &Path) -> Option<FileId> {
    use std::os::unix::fs::MetadataExt;
    let metadata = fs::metadata(path).ok()?;
    let canonical = fs::canonicalize(path).ok()?;
    Some(FileId {
        inode: metadata.ino(),
        path: canonical,
    })
}

fn mapping_entry(maps: &str, address: usize) -> Option<MappingEntry<'_>> {
    let mut fields = mapping_line(maps, address)?.split_whitespace();
    fields.next()?; // range
    fields.next()?; // perms
    fields.next()?; // offset
    // dev: the superblock device column is parsed past but deliberately NOT
    // stored — it is not part of file identity, because btrfs disagrees with
    // stat's `st_dev` for the same inode (see the `FileId` doc above).
    fields.next()?; // dev
    let inode = fields.next()?;
    Some(MappingEntry {
        inode: inode.parse::<u64>().ok(),
        path: fields.next().unwrap_or(""),
    })
}

fn mapping_diagnostic(maps: &str, address: usize) -> Option<MappingDiagnostic> {
    let line = mapping_line(maps, address)?;
    let mut fields = line.split_whitespace();
    let mut limits = fields.next()?.split('-');
    let start = usize::from_str_radix(limits.next()?, 16).ok()?;
    fields.next()?;
    let mapping_offset = usize::from_str_radix(fields.next()?, 16).ok()?;
    let relative_offset = address.checked_sub(start)?;
    Some(MappingDiagnostic {
        line: line.to_owned(),
        relative_offset,
        file_offset: mapping_offset.checked_add(relative_offset)?,
    })
}

/// Syscalls that can replace, move, unmap or re-permission a page in the
/// tracee's address space. A cached page classification is only valid until one
/// of these runs, so observing any of them evicts the cached pages it can have
/// changed (`mutation_eviction`).
const ADDRESS_SPACE_MUTATORS: [u64; 6] = [
    libc::SYS_mmap as u64,
    libc::SYS_munmap as u64,
    libc::SYS_mremap as u64,
    libc::SYS_mprotect as u64,
    libc::SYS_brk as u64,
    libc::SYS_shmat as u64,
];

/// True when `nr` is an address-space mutator. On x86-64 the syscall number
/// remains in `orig_rax` at the syscall-exit stop, which is where the cache is
/// invalidated -- after the mapping change has actually taken effect.
fn mutates_address_space(nr: u64) -> bool {
    ADDRESS_SPACE_MUTATORS.contains(&nr)
}

/// Size of the pages the mapping cache is keyed by.
const PAGE_SIZE: usize = 4096;

/// The smallest hugetlb page size on x86-64. The only other one, 1 GiB, is a
/// multiple of it. A hugetlb vma always starts on a boundary of its own page
/// size, so a range that contains no multiple of this cannot start one.
const MIN_HUGE_PAGE_SIZE: usize = 2 * 1024 * 1024;

/// Which cached pages one completed address-space mutator can have changed.
#[derive(Clone, Debug, Eq, PartialEq)]
enum Eviction {
    /// Only the pages that start inside one of these page-aligned ranges.
    Ranges(Vec<Range<usize>>),
    /// Every page of the address space.
    WholeSpace,
}

/// `[addr, addr + len)` widened to whole pages, the way the kernel rounds the
/// length of every call `mutation_eviction` gives a range for. `None` when the
/// end overflows.
fn page_range(addr: u64, len: u64) -> Option<Range<usize>> {
    let start = usize::try_from(addr).ok()?;
    let end = start
        .checked_add(usize::try_from(len).ok()?)?
        .checked_next_multiple_of(PAGE_SIZE)?;
    Some(start & !(PAGE_SIZE - 1)..end)
}

/// True when `range` contains a multiple of `MIN_HUGE_PAGE_SIZE`, the only
/// place a hugetlb vma can start. An overflow counts as containing one.
fn contains_huge_page_boundary(range: &Range<usize>) -> bool {
    range
        .start
        .checked_next_multiple_of(MIN_HUGE_PAGE_SIZE)
        .is_none_or(|boundary| boundary < range.end)
}

/// Which cached pages a completed address-space mutator can have changed, read
/// from the registers at its syscall-exit stop: `orig_rax` is the syscall,
/// `rax` its result, and its arguments are still in rdi, rsi, rdx, r10 and r8.
///
/// Ranges are returned only where the kernel confines a SUCCESSFUL call to
/// pages that its arguments and result determine, each rounded out to whole
/// pages:
///
///   * munmap and mprotect change nothing outside `[addr, addr + len)`;
///   * mmap changes only the new mapping `[result, result + len)`. With
///     MAP_FIXED that includes unmapping whatever was there, which the kernel
///     does for exactly that range, splitting any vma that straddles an edge;
///   * mremap changes only its old range `[old_addr, old_addr + old_len)` and
///     its new range `[result, result + new_len)`, whether it resizes in place
///     or moves: MREMAP_MAYMOVE, MREMAP_FIXED and MREMAP_DONTUNMAP (which
///     leaves the old range mapped). MREMAP_FIXED first unmaps the requested
///     destination `[new_addr, new_addr + new_len)`, so that range goes too;
///     it is the new range unless a driver's get_unmapped_area disregards
///     MAP_FIXED.
///
/// Everything else evicts the whole space, as every mutator used to:
///
///   * a failed call, because mmap with MAP_FIXED unmaps before it can fail,
///     and mprotect can fail after changing part of its range;
///   * brk and shmat, whose extent is not in their registers, and any other
///     syscall number;
///   * anything that may be a hugetlb mapping, which the kernel sizes in huge
///     pages rather than base pages: mmap with MAP_HUGETLB, an mmap result on
///     a huge-page boundary (a hugetlbfs file needs no flag, but its mappings
///     always start on one), and an mremap range that contains a huge-page
///     boundary (every hugetlb vma starts on one). The kernel refuses to split
///     a hugetlb vma off such a boundary, so munmap, mprotect and MAP_FIXED
///     fail rather than reach past their range;
///   * mprotect with PROT_GROWSDOWN or PROT_GROWSUP, which extends the change
///     to the edge of the vma;
///   * mremap with an old length of 0, which duplicates a shared mapping;
///   * a range whose end overflows.
fn mutation_eviction(regs: &libc::user_regs_struct) -> Eviction {
    // The kernel reports failure as -errno, in [-4095, -1].
    if (-4095..0).contains(&(regs.rax as i64)) {
        return Eviction::WholeSpace;
    }
    let ranges = match regs.orig_rax as libc::c_long {
        libc::SYS_mmap => {
            let hugetlb_flag = (regs.r10 & libc::MAP_HUGETLB as u64) != 0;
            let on_huge_page_boundary = regs.rax.is_multiple_of(MIN_HUGE_PAGE_SIZE as u64);
            if hugetlb_flag || on_huge_page_boundary {
                None
            } else {
                page_range(regs.rax, regs.rsi).map(|mapped| vec![mapped])
            }
        }
        libc::SYS_munmap => page_range(regs.rdi, regs.rsi).map(|unmapped| vec![unmapped]),
        // pkey_mprotect is the same kernel function with the same range
        // arguments. ADDRESS_SPACE_MUTATORS does not list it, so today the
        // supervisor never asks about it; protection is not part of a verdict.
        libc::SYS_mprotect | libc::SYS_pkey_mprotect => {
            let grows = (libc::PROT_GROWSDOWN | libc::PROT_GROWSUP) as u64;
            if (regs.rdx & grows) != 0 {
                None
            } else {
                page_range(regs.rdi, regs.rsi).map(|protected| vec![protected])
            }
        }
        libc::SYS_mremap if regs.rsi != 0 => {
            let new = page_range(regs.rax, regs.rdx);
            let requested = page_range(regs.r8, regs.rdx);
            let fixed = (regs.r10 & libc::MREMAP_FIXED as u64) != 0;
            let mut ranges = vec![page_range(regs.rdi, regs.rsi), new.clone()];
            if fixed && requested != new {
                ranges.push(requested);
            }
            ranges
                .into_iter()
                .collect::<Option<Vec<_>>>()
                .filter(|ranges| !ranges.iter().any(contains_huge_page_boundary))
        }
        _ => None,
    };
    ranges.map_or(Eviction::WholeSpace, Eviction::Ranges)
}

/// Whether two tasks share one address space.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum MmSharing {
    Shared,
    Private,
}

/// `kcmp(2)`'s "compare address spaces" selector. `KCMP_FILE` is 0 and
/// `KCMP_VM` is 1; getting that backwards silently compares file descriptor 0,
/// which two related tasks almost always share, so every answer comes back
/// "shared".
const KCMP_VM: libc::c_int = 1;

/// Ask the KERNEL whether `child` shares `parent`'s address space.
///
/// This is an observation of the tasks that now exist, taken at the
/// `PTRACE_EVENT_*` stop where both are alive. It deliberately replaces the
/// earlier approach of predicting the answer from clone arguments:
///
///   * `clone(2)` carries its flags in a register, which a sibling cannot
///     change while the caller is stopped -- that read was sound, and
///   * `clone3(2)` carries them in a USER BUFFER that the kernel copies AFTER
///     the syscall-entry stop. Sibling threads stay runnable across that stop,
///     so the buffer can change in the window and the prediction can be wrong
///     in either direction. Measured with a tracer that rewrites the buffer
///     after the entry read: pre-copy flags said SHARED where the child was
///     private, and said private where the child was SHARED.
///
/// Rather than keep two rules with different trust properties, every clone
/// shape is now answered the same way, by the kernel, after the fact.
///
/// `kcmp` needs both tasks alive: called after either exits it fails with
/// `ESRCH`. Any failure -- including a kernel built without
/// `CONFIG_CHECKPOINT_RESTORE`, where the syscall is `ENOSYS` -- falls back to
/// `Shared`, which over-evicts. Over-eviction costs one re-read of
/// `/proc/<pid>/maps`; under-eviction leaves a stale trusted verdict that a raw
/// syscall can hide behind.
fn mm_sharing(parent: Pid, child: Pid) -> MmSharing {
    // SAFETY: kcmp takes only scalars and returns a scalar.
    let result = unsafe {
        libc::syscall(
            libc::SYS_kcmp,
            parent.as_raw() as libc::c_long,
            child.as_raw() as libc::c_long,
            KCMP_VM as libc::c_long,
            0 as libc::c_long,
            0 as libc::c_long,
        )
    };
    interpret_kcmp_vm(result)
}

/// `kcmp` returns 0 when the two address spaces are the SAME, an ordering
/// value (1/2/3) when they differ, and -1 on error. Split out so the mapping --
/// including the fail-safe on error -- is testable without spawning tasks.
fn interpret_kcmp_vm(result: libc::c_long) -> MmSharing {
    match result {
        0 => MmSharing::Shared,
        r if r > 0 => MmSharing::Private,
        // Errors fail SAFE: assume sharing rather than risk a stale verdict.
        _ => MmSharing::Shared,
    }
}

/// Kernel-supplied mappings whose raw syscall sites are causally identified as
/// infrastructure the guest cannot have rewritten. `[vdso]` and `[vsyscall]`
/// are mapped by the kernel and are not writable, so SaBRe cannot expand a
/// syscall site inside them and the supervisor must not try to patch one.
///
/// They are exempt from REDIRECTION only — never from ACCOUNTING. A raw syscall
/// executed here did not traverse the measured in-guest SaBRe handler, so it is
/// still recorded as a trusted-native site and still makes the cell ineligible.
/// Exempting a mapping from both redirection and counting is the one
/// combination that makes a real raw syscall disappear from the evidence.
const CAUSAL_KERNEL_MAPPINGS: [&str; 2] = ["[vdso]", "[vsyscall]"];

fn classify_mapping(
    entry: &MappingEntry<'_>,
    sabre: Option<&FileId>,
    plugin: Option<&FileId>,
) -> MappingClassification {
    let path = entry.path;
    if path.starts_with('[') {
        // Only the causally identified kernel mappings above are exempt from
        // redirection, and even those are counted. Every other bracket-named
        // mapping -- `[stack]`, `[heap]`, or any future kernel name -- is NOT
        // infrastructure: fall through to `trusted: false` so the site is
        // redirected through the SaBRe handler and counted as a fallback site.
        if CAUSAL_KERNEL_MAPPINGS.contains(&path) {
            return MappingClassification {
                trusted: true,
                trusted_shared_object: Some(PathBuf::from(path)),
            };
        }
        return MappingClassification {
            trusted: false,
            trusted_shared_object: None,
        };
    }
    let path = Path::new(path.strip_suffix(" (deleted)").unwrap_or(path));
    // Bind the infrastructure exemption to the identity of the objects this
    // supervisor actually launched (inode plus canonical path, both resolved
    // from the same `/proc/<pid>/maps` line), not to their basenames. A
    // basename match would
    // exempt any unrelated mapping that happens to be called `sabre` or
    // `libdetcore_sabre.so`.
    let mapped = entry.file_id();
    let infrastructure = matches!((mapped.as_ref(), sabre), (Some(seen), Some(known)) if seen == known)
        || matches!((mapped.as_ref(), plugin), (Some(seen), Some(known)) if seen == known);
    if infrastructure {
        return MappingClassification {
            trusted: true,
            trusted_shared_object: None,
        };
    }
    // SaBRe owns shared-library rewriting. A raw syscall that still reaches the
    // supervisor from another shared object ran outside the measured in-guest
    // interception path. Keep trusting it for runtime safety, but report it so
    // compatibility accounting cannot credit the cell to SaBRe.
    let trusted_shared_object = path
        .file_name()
        .is_some_and(|name| name.to_string_lossy().contains(".so"))
        .then(|| path.to_path_buf());
    MappingClassification {
        trusted: trusted_shared_object.is_some(),
        trusted_shared_object,
    }
}

fn read_two_bytes(pid: Pid, address: usize) -> Result<[u8; 2], Error> {
    let word_size = std::mem::size_of::<libc::c_long>();
    let aligned = address & !(word_size - 1);
    let offset = address - aligned;
    let first = ptrace::read(pid, aligned as ptrace::AddressType)?.to_ne_bytes();
    if offset + 1 < word_size {
        Ok([first[offset], first[offset + 1]])
    } else {
        let second = ptrace::read(pid, (aligned + word_size) as ptrace::AddressType)?.to_ne_bytes();
        Ok([first[offset], second[0]])
    }
}

fn read_diagnostic_bytes(pid: Pid, address: usize) -> Result<[u8; 16], Error> {
    let mut bytes = [0; 16];
    let word_size = std::mem::size_of::<libc::c_long>();
    for (index, chunk) in bytes.chunks_mut(word_size).enumerate() {
        let word = ptrace::read(pid, (address + index * word_size) as ptrace::AddressType)?;
        chunk.copy_from_slice(&word.to_ne_bytes()[..chunk.len()]);
    }
    Ok(bytes)
}

fn write_two_bytes(pid: Pid, address: usize, bytes: [u8; 2]) -> Result<(), Error> {
    let word_size = std::mem::size_of::<libc::c_long>();
    let aligned = address & !(word_size - 1);
    let offset = address - aligned;
    let mut first = ptrace::read(pid, aligned as ptrace::AddressType)?.to_ne_bytes();
    first[offset] = bytes[0];
    if offset + 1 < word_size {
        first[offset + 1] = bytes[1];
        ptrace::write(
            pid,
            aligned as ptrace::AddressType,
            libc::c_long::from_ne_bytes(first),
        )?;
    } else {
        ptrace::write(
            pid,
            aligned as ptrace::AddressType,
            libc::c_long::from_ne_bytes(first),
        )?;
        let second_address = aligned + word_size;
        let mut second = ptrace::read(pid, second_address as ptrace::AddressType)?.to_ne_bytes();
        second[0] = bytes[1];
        ptrace::write(
            pid,
            second_address as ptrace::AddressType,
            libc::c_long::from_ne_bytes(second),
        )?;
    }
    Ok(())
}

// Each argument is a distinct resource the supervisor takes ownership of.
#[allow(clippy::too_many_arguments)]
pub async fn run(
    mut command: std::process::Command,
    sabre: PathBuf,
    plugin: PathBuf,
    readiness: Arc<AtomicBool>,
    physical_exit_observer: Arc<detcore::GlobalState>,
    bootstrap_launch: super::sabre_bootstrap::Launch,
    stats: SabreStats,
    capture_output: bool,
) -> Result<Output, Error> {
    if capture_output {
        command.stdout(Stdio::piped()).stderr(Stdio::piped());
    }
    // Spawn before creating the blocking supervisor worker. A worker thread consumes a task ID
    // in the guest PID namespace; creating it first shifts the root guest from PID 3 to PID 4 and
    // makes otherwise identical ptrace and SaBRe programs observe different process identities.
    let child = spawn_tracee(command)?;
    let root = Pid::from_raw(child.id() as i32);
    match waitpid(root, Some(WaitPidFlag::__WALL))? {
        WaitStatus::Stopped(pid, Signal::SIGTRAP) if pid == root => {}
        status => return Err(anyhow!("unexpected initial SaBRe ptrace stop: {status:?}")),
    }
    // Ptrace ownership belongs to the individual tracer task, not its thread group. Leave the
    // tracee stopped while handing ownership from this async caller to the blocking supervisor.
    // Injecting SIGSTOP as part of detach prevents any guest instruction from running in between.
    ptrace::detach(root, Some(Signal::SIGSTOP))
        .context("failed to hand SaBRe tracee to supervisor worker")?;
    tokio::task::spawn_blocking(move || {
        run_blocking(
            child,
            sabre,
            plugin,
            readiness,
            physical_exit_observer,
            bootstrap_launch,
            stats,
        )
    })
    .await
    .context("SaBRe ptrace supervisor task panicked")?
}

fn spawn_tracee(mut command: std::process::Command) -> Result<std::process::Child, Error> {
    // TODO-HUMAN-REVIEW(PR-845): Review SaBRe launch-time ASLR disabling.
    // PTRACE_TRACEME makes exec stop with SIGTRAP. A pre-exec SIGSTOP would
    // deadlock std::process::Command on its exec error pipe. personality(2)
    // is async-signal-safe and survives the SaBRe and guest execs.
    unsafe {
        command.pre_exec(|| {
            let current = libc::personality(0xffff_ffff);
            if current == -1 {
                return Err(std::io::Error::last_os_error());
            }
            let deterministic = current as libc::c_ulong | libc::ADDR_NO_RANDOMIZE as libc::c_ulong;
            if libc::personality(deterministic) == -1 {
                return Err(std::io::Error::last_os_error());
            }
            ptrace::traceme().map_err(std::io::Error::from)
        });
    }

    command
        .spawn()
        .context("failed to spawn ptraced SaBRe guest")
}

fn run_blocking(
    mut child: std::process::Child,
    sabre: PathBuf,
    plugin: PathBuf,
    readiness: Arc<AtomicBool>,
    physical_exit_observer: Arc<detcore::GlobalState>,
    bootstrap_launch: super::sabre_bootstrap::Launch,
    stats: SabreStats,
) -> Result<Output, Error> {
    let root = Pid::from_raw(child.id() as i32);
    let stdout = child.stdout.take();
    let stderr = child.stderr.take();
    drop(child);

    let stdout_thread = std::thread::spawn(move || read_pipe(stdout));
    let stderr_thread = std::thread::spawn(move || read_pipe(stderr));
    let supervised = Supervisor::new(
        root,
        sabre,
        plugin,
        readiness,
        physical_exit_observer,
        bootstrap_launch,
        stats,
    )
    .run();
    // Supervisor owns error cleanup and reaping. Its former root PID may be
    // reused after run returns, including when cleanup reports an error.
    let stdout = stdout_thread
        .join()
        .map_err(|_| anyhow!("SaBRe stdout reader panicked"))??;
    let stderr = stderr_thread
        .join()
        .map_err(|_| anyhow!("SaBRe stderr reader panicked"))??;
    let (status, path_evidence) = supervised?;
    Ok(Output {
        status,
        stdout,
        stderr,
        path_evidence,
    })
}

fn read_pipe<R: Read>(pipe: Option<R>) -> Result<Vec<u8>, std::io::Error> {
    let mut bytes = Vec::new();
    if let Some(mut pipe) = pipe {
        pipe.read_to_end(&mut bytes)?;
    }
    Ok(bytes)
}

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

    #[test]
    fn acknowledges_only_final_physical_exit_statuses() {
        let child = Pid::from_raw(17);
        let parent = Pid::from_raw(11);

        assert_eq!(
            final_physical_exit(&WaitStatus::Exited(child, 0)).map(|(pid, _)| pid),
            Some(child)
        );
        assert_eq!(
            final_physical_exit(&WaitStatus::Signaled(child, Signal::SIGKILL, false))
                .map(|(pid, _)| pid),
            Some(child)
        );
        assert!(
            final_physical_exit(&WaitStatus::PtraceEvent(
                child,
                Signal::SIGTRAP,
                libc::PTRACE_EVENT_EXIT,
            ))
            .is_none()
        );
        assert!(final_physical_exit(&WaitStatus::Stopped(parent, Signal::SIGCHLD)).is_none());
    }

    #[test]
    fn preserves_hardware_sigill_across_userspace_reraise() {
        const KERNEL_FAULT: i32 = 2;
        const USER_RERAISE: i32 = -6;
        let hardware = Some((Signal::SIGILL, Some(KERNEL_FAULT), false));

        assert!(!should_replace_signal_diagnostic(
            hardware,
            Signal::SIGILL,
            Some(USER_RERAISE),
        ));
        assert!(!should_replace_signal_diagnostic(
            hardware,
            Signal::SIGILL,
            None,
        ));
        assert!(should_replace_signal_diagnostic(
            hardware,
            Signal::SIGILL,
            Some(KERNEL_FAULT),
        ));
        assert!(should_replace_signal_diagnostic(
            hardware,
            Signal::SIGSEGV,
            Some(KERNEL_FAULT),
        ));
        assert!(should_replace_signal_diagnostic(
            Some((Signal::SIGILL, Some(KERNEL_FAULT), true)),
            Signal::SIGILL,
            Some(USER_RERAISE),
        ));
        assert!(should_replace_signal_diagnostic(
            Some((Signal::SIGILL, Some(USER_RERAISE), false)),
            Signal::SIGILL,
            Some(USER_RERAISE),
        ));
    }

    #[test]
    fn recognizes_sabre_sigill_markers() {
        for marker in [[0x0f, 0xff], [0x0f, 0x0b], [0x0f, 0x0c]] {
            let mut bytes = [0; 16];
            bytes[..2].copy_from_slice(&marker);
            assert!(is_sabre_sigill_marker(Some(&bytes)));
        }

        let mut unknown = [0; 16];
        unknown[..2].copy_from_slice(&[0x62, 0xf1]);
        assert!(!is_sabre_sigill_marker(Some(&unknown)));
        assert!(!is_sabre_sigill_marker(None));
    }

    #[test]
    fn finds_mapping_path() {
        let maps = concat!(
            "1000-2000 r-xp 00002000 00:00 0 /tmp/sabre\n",
            "3000-4000 rwxp 00000000 00:00 0 \n",
        );
        assert_eq!(
            mapping_entry(maps, 0x1234).map(|entry| entry.path),
            Some("/tmp/sabre")
        );
        assert_eq!(
            mapping_entry(maps, 0x3456).map(|entry| entry.path),
            Some("")
        );
        assert!(mapping_entry(maps, 0x2500).is_none());
        let diagnostic = mapping_diagnostic(maps, 0x1234).unwrap();
        assert_eq!(diagnostic.relative_offset, 0x234);
        assert_eq!(diagnostic.file_offset, 0x2234);
        assert_eq!(
            diagnostic.line,
            "1000-2000 r-xp 00002000 00:00 0 /tmp/sabre"
        );
    }

    // Rewritten for the identity-based contract. The previous version of this
    // test asserted the two defects codex found: it required a different-root
    // `libdetcore_sabre.so` and `[vdso]` to be `trusted` with NO counted site --
    // the one combination that makes a real raw syscall vanish from evidence.
    #[test]
    fn classifies_runtime_mapping_attribution() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (sabre_path, sabre) = real_file(dir.path(), "sabre");
        let (plugin_path, plugin) = real_file(dir.path(), "libdetcore_sabre.so");

        // The launched objects themselves: exempt and uncounted, because they
        // ARE the measured interception path. Real files, and the maps rows
        // carry a dev that does NOT match stat() -- see the regression test.
        for (inode, path) in [
            (sabre.inode, sabre_path.to_str().expect("utf8")),
            (plugin.inode, plugin_path.to_str().expect("utf8")),
        ] {
            let maps = maps_row("1000-2000", "00:2d", inode, path);
            let entry = mapping_entry(&maps, 0x1234).unwrap();
            assert_eq!(
                classify_mapping(&entry, Some(&sabre), Some(&plugin)),
                MappingClassification {
                    trusted: true,
                    trusted_shared_object: None
                },
                "{path} is a launched object and must be exempt"
            );
        }

        // A DIFFERENT object wearing the plugin's basename is refused, even
        // with the ` (deleted)` suffix the old test used.
        let maps = maps_row(
            "1000-2000",
            "fd:01",
            7777,
            "/different/root/libdetcore_sabre.so (deleted)",
        );
        let entry = mapping_entry(&maps, 0x1234).unwrap();
        assert_eq!(
            classify_mapping(&entry, Some(&sabre), Some(&plugin)),
            MappingClassification {
                trusted: true,
                trusted_shared_object: Some(PathBuf::from("/different/root/libdetcore_sabre.so")),
            },
            "a basename impostor must be counted as a trusted-native site, not exempted"
        );

        // Ordinary shared object: trusted for runtime safety, counted for
        // accounting. Unchanged contract.
        let maps = maps_row("1000-2000", "fd:01", 55, "/usr/lib/libc.so.6");
        let entry = mapping_entry(&maps, 0x1234).unwrap();
        assert_eq!(
            classify_mapping(&entry, Some(&sabre), Some(&plugin)),
            MappingClassification {
                trusted: true,
                trusted_shared_object: Some(PathBuf::from("/usr/lib/libc.so.6")),
            }
        );

        // Non-library and anonymous mappings are redirected and counted as
        // fallback sites. Unchanged contract.
        for (inode, path) in [(66, "/usr/bin/echo"), (0, "")] {
            let maps = maps_row("1000-2000", "fd:01", inode, path);
            let entry = mapping_entry(&maps, 0x1234).unwrap();
            assert_eq!(
                classify_mapping(&entry, Some(&sabre), Some(&plugin)),
                MappingClassification {
                    trusted: false,
                    trusted_shared_object: None
                }
            );
        }
    }

    /// One synthetic `/proc/<pid>/maps` row. Columns are exactly what the
    /// kernel prints: `range perms offset dev inode path`.
    fn maps_row(range: &str, dev: &str, inode: u64, path: &str) -> String {
        format!("{range} r-xp 00000000 {dev} {inode} {path}\n")
    }

    fn classify(maps: &str, address: usize, sabre: Option<&FileId>) -> MappingClassification {
        let entry = mapping_entry(maps, address).expect("mapping row must parse");
        classify_mapping(&entry, sabre, None)
    }

    /// A real file on disk, plus its identity. The synthetic-row tests below
    /// must use REAL paths: identity is now (inode, canonicalized path), and a
    /// fabricated path resolves to nothing and therefore matches nothing.
    fn real_file(dir: &std::path::Path, name: &str) -> (PathBuf, FileId) {
        let path = dir.join(name);
        fs::write(&path, b"object").expect("write fixture");
        let id = launched_file_id(&path).expect("fixture must have an identity");
        (path, id)
    }

    // FINDING 1 -- bracketed mappings.
    //
    // POSITIVE: a raw syscall in the kernel-supplied [vdso] is exempt from
    // REDIRECTION (it is not writable, so it cannot be patched) but is still
    // COUNTED, so the cell cannot be silently credited to SaBRe.
    #[test]
    fn vdso_raw_syscall_is_counted_not_silently_trusted() {
        let maps = maps_row("7ffff7fc9000-7ffff7fcb000", "00:00", 0, "[vdso]");
        let classification = classify(&maps, 0x7ffff7fc9010, None);
        assert!(
            classification.trusted,
            "[vdso] is not writable, so it must not be redirected"
        );
        assert_eq!(
            classification.trusted_shared_object,
            Some(PathBuf::from("[vdso]")),
            "a [vdso] raw syscall did not traverse the SaBRe handler and must be counted"
        );
    }

    // NEGATIVE: any other bracket-named mapping is NOT causally identified
    // infrastructure. An executable [stack] hosting a raw syscall must be
    // redirected and counted as a fallback site, never silently exempted.
    #[test]
    fn non_infrastructure_bracket_mapping_is_refused() {
        for name in ["[stack]", "[heap]", "[anon:jit]"] {
            let maps = maps_row("7ffffffde000-7ffffffff000", "00:00", 0, name);
            let classification = classify(&maps, 0x7ffffffde010, None);
            assert!(
                !classification.trusted,
                "{name} must be redirected through the SaBRe handler, not exempted"
            );
        }
    }

    // FINDING 2, THE REAL-MAPPING TEST. The reviewer's closing requirement was
    // "a test that would have failed today -- one exercising the real launched
    // loader rather than a synthetic maps row", and the reason is exact: every
    // other test here builds BOTH halves of the comparison itself, so dev and
    // inode agree by construction and the btrfs disagreement is invisible to
    // them by design. This one fabricates neither half. It mmaps a real file,
    // finds the kernel's own row for that mapping in /proc/self/maps, and
    // requires the identity derived from the maps row to equal the identity
    // derived from stat() on the same path.
    //
    // On btrfs at the previous head this FAILS: stat() reports the subvolume's
    // anonymous st_dev while maps prints the superblock's, so the two FileIds
    // differ in `dev` despite naming one object. It passes iff identity is
    // built from components that actually agree.
    #[test]
    fn a_real_mapping_and_stat_agree_on_the_same_object() {
        use std::io::Write;

        let mut file = tempfile::NamedTempFile::new().expect("tempfile");
        file.write_all(&[0u8; 4096]).expect("write");
        file.flush().expect("flush");
        let path = file.path().to_path_buf();

        // Map it, so the kernel prints a row for this exact object.
        let fd = fs::File::open(&path).expect("open");
        let mapping = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                4096,
                libc::PROT_READ,
                libc::MAP_PRIVATE,
                std::os::unix::io::AsRawFd::as_raw_fd(&fd),
                0,
            )
        };
        assert_ne!(mapping, libc::MAP_FAILED, "mmap of the fixture failed");
        let address = mapping as usize;

        // Other tests can map non-UTF-8 Linux filenames in this same mm.
        // Read bytes and select our exact mmap base before decoding its row;
        // the tempfile path and the kernel's numeric columns are UTF-8.
        let maps = fs::read("/proc/self/maps").expect("read own maps");
        let prefix = format!("{address:08x}-");
        let row = maps
            .split(|byte| *byte == b'\n')
            .find(|row| row.starts_with(prefix.as_bytes()))
            .expect("our own mapping must have a row");
        let row = std::str::from_utf8(row).expect("our fixture's mapping row must be UTF-8");
        let entry = mapping_entry(row, address).expect("our own mapping must contain its base");
        let from_maps = entry
            .file_id()
            .expect("a file-backed mapping has an identity");
        let from_stat = launched_file_id(&path).expect("the fixture must stat");

        // SAFETY: `mapping` is the address mmap just returned for this length.
        unsafe { libc::munmap(mapping, 4096) };

        assert_eq!(
            from_maps, from_stat,
            "the identity of one object must not depend on which side of the \
             kernel it is observed from; a mismatch here is what patched the \
             SaBRe loader's own text and SIGSEGV'd the guest"
        );
    }

    // FINDING 2 -- infrastructure identity.
    //
    // POSITIVE, and this is the REGRESSION TEST: the launched loader is
    // recognised even when the maps `dev` column disagrees with `stat()`.
    // The row below deliberately carries a WRONG dev (`00:2d` against a
    // `stat()` that will report something else), which is exactly what btrfs
    // produces for a real file: same inode, different device, because each
    // subvolume gets its own anonymous `st_dev` while maps prints the
    // superblock's. Under the previous dev+inode identity this assertion
    // FAILS -- the loader is not recognised, its text is patched with UD0, and
    // the guest SIGSEGVs. That is the defect this test exists to catch.
    #[test]
    fn launched_sabre_object_is_recognised_despite_a_disagreeing_dev_column() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (path, id) = real_file(dir.path(), "sabre");
        let maps = maps_row(
            "400000-401000",
            "00:2d",
            id.inode,
            path.to_str().expect("utf8 path"),
        );
        let classification = classify(&maps, 0x400010, Some(&id));
        assert!(
            classification.trusted,
            "the launched loader must stay infrastructure even when the maps dev \
             column disagrees with stat() (btrfs subvolume anon dev)"
        );
        assert_eq!(classification.trusted_shared_object, None);
    }

    // NEGATIVE: an impostor with the SAME BASENAME but a different object
    // identity must NOT inherit the exemption. This is the planted bypass.
    #[test]
    fn same_basename_different_object_is_refused() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (_, known) = real_file(dir.path(), "sabre");
        let attacker = dir.path().join("attacker");
        fs::create_dir(&attacker).expect("mkdir");
        let (impostor_path, impostor) = real_file(&attacker, "sabre");
        assert_ne!(
            known.inode, impostor.inode,
            "fixtures must be distinct files"
        );
        let maps = maps_row(
            "500000-501000",
            "fd:01",
            impostor.inode,
            impostor_path.to_str().expect("utf8 path"),
        );
        let classification = classify(&maps, 0x500010, Some(&known));
        assert!(
            !classification.trusted,
            "basename `sabre` must not exempt a different object"
        );
        assert_eq!(classification.trusted_shared_object, None);
    }

    // NEGATIVE: an unstat-able launched path yields no identity, and a missing
    // identity must withhold the exemption (fail closed) rather than grant it.
    #[test]
    fn unknown_launched_identity_grants_no_exemption() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (path, id) = real_file(dir.path(), "sabre");
        let maps = maps_row(
            "400000-401000",
            "fd:01",
            id.inode,
            path.to_str().expect("utf8 path"),
        );
        let classification = classify(&maps, 0x400010, None);
        assert!(
            !classification.trusted,
            "an unresolved launched identity must not exempt anything"
        );
    }

    // A shared object that is neither infrastructure nor kernel mapping stays
    // trusted-for-safety but counted, which is the pre-existing contract this
    // change must not weaken.
    #[test]
    fn other_shared_object_remains_counted() {
        let maps = maps_row(
            "7f0000000000-7f0000001000",
            "fd:01",
            77,
            "/usr/lib64/libc.so.6",
        );
        let dir = tempfile::tempdir().expect("tempdir");
        let (_, known) = real_file(dir.path(), "sabre");
        let classification = classify(&maps, 0x7f0000000010, Some(&known));
        assert!(classification.trusted);
        assert_eq!(
            classification.trusted_shared_object,
            Some(PathBuf::from("/usr/lib64/libc.so.6"))
        );
    }

    // FINDING 3 -- cache invalidation. Both sides of the predicate that decides
    // whether a tracee's cached page verdicts survive a syscall.
    fn trusted() -> MappingClassification {
        MappingClassification {
            trusted: true,
            trusted_shared_object: None,
        }
    }

    /// FINDING 2, the unsound case. Threads A and B share one address space
    /// (`CLONE_VM`). B caches a page as trusted; A then mutates the address
    /// space. B MUST NOT keep serving the pre-mutation verdict for that page --
    /// under the old `(Pid, page)` keying only A's entries were evicted, so B
    /// went on treating a page that may no longer be trusted as trusted, and a
    /// raw syscall there bypassed both redirection and accounting.
    #[test]
    fn sibling_thread_cannot_serve_a_stale_classification_after_a_shared_mm_mutation() {
        const PAGE: usize = 0x1000;
        let a = Pid::from_raw(100);
        let b = Pid::from_raw(101);
        let mut cache = MappingCache::new(a);
        cache.share_address_space(a, b);

        // B observes the page and caches it.
        cache.insert(b, PAGE, trusted());
        assert!(
            cache.get(b, PAGE).is_some(),
            "precondition: B has a cached verdict, so the eviction below is not vacuous"
        );

        // A mutates the SHARED address space.
        cache.invalidate_address_space(a);

        assert!(
            cache.get(b, PAGE).is_none(),
            "a sibling sharing the mm must lose its cached verdict when ANY thread \
             in that mm mutates the address space"
        );

        // Folded range-eviction scenario; see this commit's message.
        a_sibling_thread_sees_a_range_eviction();
    }

    /// The matching control: eviction must be scoped to the address space that
    /// actually changed, not global. A task in an UNRELATED mm keeps its cache,
    /// so the fix is a re-keying rather than a blanket flush.
    #[test]
    fn unrelated_address_space_is_not_over_evicted() {
        const PAGE: usize = 0x1000;
        let a = Pid::from_raw(100);
        let b = Pid::from_raw(101);
        let unrelated = Pid::from_raw(200);
        let mut cache = MappingCache::new(a);
        cache.share_address_space(a, b);
        cache.new_address_space(unrelated);

        cache.insert(b, PAGE, trusted());
        cache.insert(unrelated, PAGE, trusted());

        cache.invalidate_address_space(a);

        assert!(cache.get(b, PAGE).is_none(), "the mutated mm is evicted");
        assert!(
            cache.get(unrelated, PAGE).is_some(),
            "a different address space maps a different page at the same address \
             and must keep its verdict"
        );

        // Folded range-eviction scenario; see this commit's message.
        a_failed_mutator_evicts_the_whole_space();
        // Folded range-eviction scenario; see this commit's message.
        a_range_eviction_leaves_an_unrelated_address_space_alone();
    }

    /// Fork a child of the requested shape, run `check` while it is alive, then
    /// reap it. Real tasks, because the property under test is what the KERNEL
    /// did -- a hand-built pid pair would test nothing.
    fn with_child<F: FnOnce(Pid, Pid)>(share_mm: bool, check: F) {
        const STACK: usize = 1 << 20;
        let mut stack = vec![0u8; STACK];
        let child = if share_mm {
            // CLONE_VM|SIGCHLD: shares the mm AND is reported as
            // PTRACE_EVENT_FORK, the shape that defeats an event-kind rule.
            let top = unsafe { stack.as_mut_ptr().add(STACK) } as *mut libc::c_void;
            extern "C" fn sleeper(_: *mut libc::c_void) -> libc::c_int {
                unsafe { libc::pause() };
                0
            }
            unsafe {
                libc::clone(
                    sleeper,
                    top,
                    libc::CLONE_VM | libc::SIGCHLD,
                    std::ptr::null_mut(),
                )
            }
        } else {
            match unsafe { libc::fork() } {
                0 => unsafe {
                    libc::pause();
                    libc::_exit(0)
                },
                pid => pid,
            }
        };
        assert!(child > 0, "failed to create the {share_mm} child");
        let parent = Pid::from_raw(unsafe { libc::getpid() });
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            check(parent, Pid::from_raw(child))
        }));
        unsafe {
            libc::kill(child, libc::SIGKILL);
            libc::waitpid(child, std::ptr::null_mut(), libc::__WALL);
        }
        if let Err(payload) = result {
            std::panic::resume_unwind(payload);
        }
    }

    /// The oracle itself, against real tasks, both ways.
    ///
    /// This is the whole reason the clone arguments are no longer consulted: a
    /// `CLONE_VM` child is reported as `PTRACE_EVENT_FORK` when its exit signal
    /// is `SIGCHLD`, so the event kind cannot tell these two apart -- but the
    /// kernel can, and does.
    #[test]
    fn the_kernel_distinguishes_a_shared_mm_from_a_private_one() {
        with_child(true, |parent, child| {
            assert_eq!(
                mm_sharing(parent, child),
                MmSharing::Shared,
                "a CLONE_VM child shares the caller's address space"
            );
        });
        with_child(false, |parent, child| {
            assert_eq!(
                mm_sharing(parent, child),
                MmSharing::Private,
                "a forked child gets its own address space"
            );
        });
    }

    /// A `CLONE_VM` child must lose a cached verdict when the parent mutates the
    /// shared mm -- driven end to end from the real child through the real
    /// oracle into the real cache, with no hand-supplied sharing answer.
    #[test]
    fn a_clone_vm_child_cannot_serve_a_stale_classification() {
        const PAGE: usize = 0x5000;
        with_child(true, |parent, child| {
            let mut cache = MappingCache::new(parent);
            cache.admit_child(parent, child, mm_sharing(parent, child));

            cache.insert(child, PAGE, trusted());
            assert!(
                cache.get(child, PAGE).is_some(),
                "precondition: the child has a cached verdict, so the eviction is not vacuous"
            );

            cache.invalidate_address_space(parent);

            assert!(
                cache.get(child, PAGE).is_none(),
                "the child shares the mm the parent just mutated, so its cached \
                 verdict must be dropped"
            );
        });

        // Folded range-eviction scenario; see this commit's message.
        a_clone_vm_child_sees_a_range_eviction();
    }

    /// The control on the same end-to-end path: a child with its OWN mm keeps
    /// its cache, so the oracle did not collapse into "always share".
    #[test]
    fn a_private_mm_child_keeps_its_own_address_space() {
        const PAGE: usize = 0x6000;
        with_child(false, |parent, child| {
            let mut cache = MappingCache::new(parent);
            cache.admit_child(parent, child, mm_sharing(parent, child));

            cache.insert(child, PAGE, trusted());
            cache.invalidate_address_space(parent);

            assert!(
                cache.get(child, PAGE).is_some(),
                "a private mm cannot be reached by the parent's mutation"
            );
        });
    }

    /// `clone3(2)` specifically, with the buffer CLOBBERED after the call --
    /// the regression test for the race that motivated this design.
    ///
    /// `clone3` passes its flags in a user buffer that the kernel copies after
    /// the syscall-entry ptrace stop, so any implementation that reads that
    /// buffer is reading something a concurrently runnable sibling can still
    /// change. Here the parent overwrites `flags` immediately after the call,
    /// which is what such a sibling would do: a buffer-reading implementation
    /// then sees `0` and concludes "private", while the child the kernel
    /// actually created shares the mm. The kernel oracle is unaffected because
    /// it inspects the child, not the request.
    #[test]
    fn clone3_sharing_is_read_from_the_child_not_from_a_clobberable_buffer() {
        #[repr(C)]
        #[derive(Default)]
        struct CloneArgs {
            flags: u64,
            pidfd: u64,
            child_tid: u64,
            parent_tid: u64,
            exit_signal: u64,
            stack: u64,
            stack_size: u64,
            tls: u64,
        }
        const STACK: usize = 1 << 20;
        let mut stack = vec![0u8; STACK];
        let mut args = CloneArgs {
            flags: libc::CLONE_VM as u64,
            exit_signal: libc::SIGCHLD as u64,
            stack: stack.as_mut_ptr() as u64,
            stack_size: STACK as u64,
            ..Default::default()
        };
        let child = unsafe {
            libc::syscall(
                libc::SYS_clone3,
                &mut args as *mut CloneArgs,
                std::mem::size_of::<CloneArgs>(),
            )
        };
        if child == 0 {
            // In the child, on the supplied stack: do nothing that could unwind.
            unsafe {
                libc::pause();
                libc::_exit(0)
            };
        }
        assert!(
            child > 0,
            "clone3 failed: {}",
            std::io::Error::last_os_error()
        );

        // The racing write. Any implementation that consults the request rather
        // than the child now has CLONE_VM erased under it.
        args.flags = 0;
        assert_eq!(
            args.flags & libc::CLONE_VM as u64,
            0,
            "the request now reads private"
        );

        let parent = Pid::from_raw(unsafe { libc::getpid() });
        let child = Pid::from_raw(child as i32);
        let observed = mm_sharing(parent, child);

        unsafe {
            libc::kill(child.as_raw(), libc::SIGKILL);
            libc::waitpid(child.as_raw(), std::ptr::null_mut(), libc::__WALL);
        }

        assert_eq!(
            observed,
            MmSharing::Shared,
            "the child shares the mm; reading the clobbered request would have said private"
        );
    }

    /// The kcmp result mapping, including the fail-safe. A dead task, a kernel
    /// without CONFIG_CHECKPOINT_RESTORE, or any other error must resolve to
    /// SHARED: over-eviction costs a `/proc/<pid>/maps` re-read, under-eviction
    /// leaves a stale verdict a raw syscall can hide behind.
    #[test]
    fn an_unanswerable_kcmp_fails_safe_to_shared() {
        assert_eq!(interpret_kcmp_vm(0), MmSharing::Shared, "0 means same mm");
        for ordered in [1, 2, 3] {
            assert_eq!(
                interpret_kcmp_vm(ordered),
                MmSharing::Private,
                "a nonzero ordering value means the address spaces differ"
            );
        }
        assert_eq!(
            interpret_kcmp_vm(-1),
            MmSharing::Shared,
            "an error must fail safe to sharing, never to private"
        );
    }

    /// And the same fail-safe through the live path: asking about a pid that
    /// cannot be compared must not report `Private`.
    #[test]
    fn mm_sharing_of_an_unavailable_task_fails_safe_to_shared() {
        // A pid that is not ours to inspect; kcmp refuses rather than answering.
        let parent = Pid::from_raw(unsafe { libc::getpid() });
        assert_eq!(
            mm_sharing(parent, Pid::from_raw(-1)),
            MmSharing::Shared,
            "an unanswerable comparison must over-evict, not under-evict"
        );
    }

    /// fork does NOT share the mm, so a forked child must not be evicted by its
    /// parent's mutations -- the other direction of the same scoping property.
    #[test]
    fn forked_child_gets_its_own_address_space() {
        const PAGE: usize = 0x2000;
        let parent = Pid::from_raw(100);
        let child = Pid::from_raw(101);
        let mut cache = MappingCache::new(parent);
        cache.new_address_space(child);

        cache.insert(child, PAGE, trusted());
        cache.invalidate_address_space(parent);

        assert!(
            cache.get(child, PAGE).is_some(),
            "fork installs a separate mm; the parent's mutation cannot reach it"
        );

        // Folded range-eviction scenario; see this commit's message.
        a_mutation_before_admission_drops_every_cached_page();
    }

    /// exec replaces the mm outright, so nothing cached against the old one may
    /// survive for the exec'ing task.
    #[test]
    fn exec_discards_the_previous_address_space() {
        const PAGE: usize = 0x3000;
        let pid = Pid::from_raw(100);
        let mut cache = MappingCache::new(pid);
        cache.insert(pid, PAGE, trusted());

        cache.replace_address_space(pid);

        assert!(
            cache.get(pid, PAGE).is_none(),
            "exec installs a new mm; the old classification describes a dead address space"
        );

        // Folded range-eviction scenario; see this commit's message.
        a_range_eviction_drops_pages_in_range_and_keeps_the_rest();
        // Folded range-eviction scenario; see this commit's message.
        a_zero_length_mprotect_evicts_nothing();
        // Folded range-eviction scenario; see this commit's message.
        mremap_evicts_both_its_old_and_its_new_range();
    }

    /// A thread exiting must not evict pages its siblings still rely on, but the
    /// last user leaving must free them.
    #[test]
    fn cached_pages_outlive_one_thread_but_not_the_whole_group() {
        const PAGE: usize = 0x4000;
        let a = Pid::from_raw(100);
        let b = Pid::from_raw(101);
        let mut cache = MappingCache::new(a);
        cache.share_address_space(a, b);
        cache.insert(a, PAGE, trusted());

        cache.forget(b);
        assert!(
            cache.get(a, PAGE).is_some(),
            "a sibling exiting does not invalidate the surviving thread's view"
        );

        cache.forget(a);
        assert!(
            cache.entries.is_empty(),
            "the last user of an address space releases its cached pages"
        );
    }

    #[test]
    fn address_space_mutators_invalidate_and_others_do_not() {
        for nr in [
            libc::SYS_mmap,
            libc::SYS_munmap,
            libc::SYS_mremap,
            libc::SYS_mprotect,
            libc::SYS_brk,
            libc::SYS_shmat,
        ] {
            assert!(
                mutates_address_space(nr as u64),
                "syscall {nr} changes the address space and must invalidate the cache"
            );
        }
        for nr in [libc::SYS_read, libc::SYS_write, libc::SYS_getpid] {
            assert!(
                !mutates_address_space(nr as u64),
                "syscall {nr} cannot change a mapping and must not invalidate the cache"
            );
        }

        // Folded range-eviction scenario; see this commit's message.
        mmap_and_mprotect_ranges();
        // Folded range-eviction scenario; see this commit's message.
        calls_without_a_provable_range_evict_the_whole_space();
        // Folded range-eviction scenario; see this commit's message.
        possible_hugetlb_mappings_evict_the_whole_space();
        // Folded range-eviction scenario; see this commit's message.
        growing_mprotect_evicts_the_whole_space();
        // Folded range-eviction scenario; see this commit's message.
        an_overflowing_range_evicts_the_whole_space();
    }

    // Range-precise eviction (https://github.com/rrnewton/hermit/issues/3378).

    /// Registers at the syscall-exit stop of `nr` returning `result`, with the
    /// arguments still in rdi, rsi, rdx and r10 as the x86-64 ABI leaves them.
    fn exit_regs(nr: libc::c_long, args: [u64; 4], result: i64) -> libc::user_regs_struct {
        // SAFETY: user_regs_struct is plain integers, so all-zero is a value.
        let mut regs: libc::user_regs_struct = unsafe { std::mem::zeroed() };
        regs.orig_rax = nr as u64;
        regs.rdi = args[0];
        regs.rsi = args[1];
        regs.rdx = args[2];
        regs.r10 = args[3];
        regs.rax = result as u64;
        regs
    }

    fn ranges(ranges: &[Range<usize>]) -> Eviction {
        Eviction::Ranges(ranges.to_vec())
    }

    /// The eviction of the single range `[start, end)`. A one-element array of
    /// ranges is what clippy::single_range_in_vec_init refuses.
    fn one_range(start: usize, end: usize) -> Eviction {
        let range = start..end;
        Eviction::Ranges(vec![range])
    }

    /// A page inside the mutated range is evicted and a page outside it is
    /// kept, including the neighbours on both sides. The length is rounded up
    /// to a whole page, as the kernel does, so a partial last page goes too.
    fn a_range_eviction_drops_pages_in_range_and_keeps_the_rest() {
        let pid = Pid::from_raw(100);
        let mut cache = MappingCache::new(pid);
        for page in [0xf000, 0x10000, 0x11000, 0x12000] {
            cache.insert(pid, page, trusted());
        }

        let munmap = exit_regs(libc::SYS_munmap, [0x10000, 0x1800, 0, 0], 0);
        let eviction = mutation_eviction(&munmap);
        assert_eq!(eviction, one_range(0x10000, 0x12000));
        cache.evict(pid, &eviction);

        assert!(cache.get(pid, 0x10000).is_none(), "first page in range");
        assert!(
            cache.get(pid, 0x11000).is_none(),
            "the partial last page is unmapped too"
        );
        assert!(
            cache.get(pid, 0xf000).is_some(),
            "the page before the range"
        );
        assert!(
            cache.get(pid, 0x12000).is_some(),
            "the page after the range"
        );
    }

    /// mmap names the new mapping by its RESULT, including MAP_FIXED over
    /// pages that were already mapped, which the kernel unmaps for exactly
    /// that range; mprotect names its arguments.
    fn mmap_and_mprotect_ranges() {
        let fixed = (libc::MAP_FIXED | libc::MAP_PRIVATE | libc::MAP_ANONYMOUS) as u64;
        let prot = (libc::PROT_READ | libc::PROT_EXEC) as u64;
        assert_eq!(
            mutation_eviction(&exit_regs(
                libc::SYS_mmap,
                [0x30000, 0x2000, prot, fixed],
                0x30000
            )),
            one_range(0x30000, 0x32000),
            "MAP_FIXED over existing pages"
        );
        assert_eq!(
            mutation_eviction(&exit_regs(
                libc::SYS_mmap,
                [0, 0x2001, prot, libc::MAP_PRIVATE as u64],
                0x7f00_0000_1000
            )),
            one_range(0x7f00_0000_1000, 0x7f00_0000_4000),
            "a kernel-chosen address, length rounded up"
        );
        for nr in [libc::SYS_mprotect, libc::SYS_pkey_mprotect] {
            assert_eq!(
                mutation_eviction(&exit_regs(nr, [0x40000, 0x1000, prot, 0], 0)),
                one_range(0x40000, 0x41000),
                "syscall {nr}"
            );
        }
    }

    /// A zero-length mprotect succeeds without touching anything.
    fn a_zero_length_mprotect_evicts_nothing() {
        let pid = Pid::from_raw(100);
        let mut cache = MappingCache::new(pid);
        cache.insert(pid, 0x40000, trusted());
        let prot = libc::PROT_READ as u64;
        let eviction = mutation_eviction(&exit_regs(libc::SYS_mprotect, [0x40000, 0, prot, 0], 0));
        assert_eq!(eviction, one_range(0x40000, 0x40000));
        cache.evict(pid, &eviction);
        assert!(cache.get(pid, 0x40000).is_some());
    }

    /// mremap changes both its old and its new range, whether it resizes in
    /// place or moves, and whichever of MREMAP_MAYMOVE, MREMAP_FIXED and
    /// MREMAP_DONTUNMAP it was given. Both ranges must be evicted and a page
    /// between or beyond them kept. MREMAP_FIXED also unmaps the destination
    /// it names in r8, which is evicted as well when it is not the result.
    fn mremap_evicts_both_its_old_and_its_new_range() {
        let maymove = libc::MREMAP_MAYMOVE as u64;
        let fixed = (libc::MREMAP_MAYMOVE | libc::MREMAP_FIXED) as u64;
        let dontunmap = (libc::MREMAP_MAYMOVE | libc::MREMAP_DONTUNMAP) as u64;
        for (flags, new_len) in [(maymove, 0x3000), (fixed, 0x3000), (dontunmap, 0x2000)] {
            let mut regs = exit_regs(libc::SYS_mremap, [0x20000, 0x2000, new_len, flags], 0x40000);
            regs.r8 = 0x40000;
            let eviction = mutation_eviction(&regs);
            let new_end = 0x40000 + new_len as usize;
            assert_eq!(
                eviction,
                ranges(&[0x20000..0x22000, 0x40000..new_end]),
                "flags {flags:#x}"
            );

            let pid = Pid::from_raw(100);
            let mut cache = MappingCache::new(pid);
            for page in [
                0x1f000, 0x20000, 0x21000, 0x22000, 0x40000, 0x41000, new_end,
            ] {
                cache.insert(pid, page, trusted());
            }
            cache.evict(pid, &eviction);
            for page in [0x20000, 0x21000, 0x40000, 0x41000] {
                assert!(cache.get(pid, page).is_none(), "{page:#x} was remapped");
            }
            for page in [0x1f000, 0x22000, new_end] {
                assert!(cache.get(pid, page).is_some(), "{page:#x} was not");
            }
        }

        let mut elsewhere = exit_regs(libc::SYS_mremap, [0x20000, 0x2000, 0x3000, fixed], 0x40000);
        elsewhere.r8 = 0x60000;
        let eviction = mutation_eviction(&elsewhere);
        assert_eq!(
            eviction,
            ranges(&[0x20000..0x22000, 0x40000..0x43000, 0x60000..0x63000]),
            "MREMAP_FIXED unmapped r8 even though the move went elsewhere"
        );
        let pid = Pid::from_raw(100);
        let mut cache = MappingCache::new(pid);
        for page in [0x5f000, 0x60000, 0x62000, 0x63000] {
            cache.insert(pid, page, trusted());
        }
        cache.evict(pid, &eviction);
        for page in [0x60000, 0x62000] {
            assert!(cache.get(pid, page).is_none(), "{page:#x} was unmapped");
        }
        for page in [0x5f000, 0x63000] {
            assert!(cache.get(pid, page).is_some(), "{page:#x} was not");
        }

        assert_eq!(
            mutation_eviction(&exit_regs(
                libc::SYS_mremap,
                [0x20000, 0x2000, 0x4000, 0],
                0x20000
            )),
            ranges(&[0x20000..0x22000, 0x20000..0x24000]),
            "growth in place"
        );
    }

    /// A failed call can still have changed part of its range, or more than
    /// it names, so every error evicts every page of the space -- but only of
    /// that space.
    fn a_failed_mutator_evicts_the_whole_space() {
        let prot = libc::PROT_READ as u64;
        let fixed = libc::MAP_FIXED as u64;
        let calls = [
            (libc::SYS_mmap, [0x10000, 0x1000, prot, fixed]),
            (libc::SYS_munmap, [0x10000, 0x1000, 0, 0]),
            (libc::SYS_mprotect, [0x10000, 0x1000, prot, 0]),
            (libc::SYS_mremap, [0x10000, 0x1000, 0x1000, 0]),
            (libc::SYS_brk, [0x10000, 0, 0, 0]),
            (libc::SYS_shmat, [1, 0x10000, 0, 0]),
        ];
        let errors = [-4095, -(libc::ENOMEM as i64), -(libc::EINVAL as i64), -1];
        for (nr, args) in calls {
            for error in errors {
                let eviction = mutation_eviction(&exit_regs(nr, args, error));
                assert_eq!(eviction, Eviction::WholeSpace, "syscall {nr} -> {error}");

                let a = Pid::from_raw(100);
                let b = Pid::from_raw(101);
                let unrelated = Pid::from_raw(200);
                let mut cache = MappingCache::new(a);
                cache.share_address_space(a, b);
                cache.new_address_space(unrelated);
                cache.insert(b, 0x10000, trusted());
                cache.insert(b, 0x900000, trusted());
                cache.insert(unrelated, 0x10000, trusted());
                cache.evict(a, &eviction);
                assert!(cache.get(b, 0x10000).is_none(), "the named page");
                assert!(cache.get(b, 0x900000).is_none(), "a page far outside it");
                assert!(
                    cache.get(unrelated, 0x10000).is_some(),
                    "another address space"
                );
            }
        }
    }

    /// brk and shmat do not name their extent in their registers, so they keep
    /// the whole-space eviction, as does any number not handled explicitly.
    fn calls_without_a_provable_range_evict_the_whole_space() {
        for (nr, args, result) in [
            (libc::SYS_brk, [0x60_0000, 0, 0, 0], 0x60_0000),
            (libc::SYS_shmat, [3, 0, 0, 0], 0x7f00_0000_1000),
            (libc::SYS_getpid, [0, 0, 0, 0], 100),
        ] {
            assert_eq!(
                mutation_eviction(&exit_regs(nr, args, result)),
                Eviction::WholeSpace,
                "syscall {nr}"
            );
        }
        assert_eq!(
            mutation_eviction(&exit_regs(
                libc::SYS_mremap,
                [0x20000, 0, 0x2000, libc::MREMAP_MAYMOVE as u64],
                0x40000
            )),
            Eviction::WholeSpace,
            "an old length of 0 duplicates a shared mapping"
        );
    }

    /// A hugetlb mapping is sized in huge pages, so wherever one may be
    /// involved the base-page range is not trusted and the whole space goes.
    fn possible_hugetlb_mappings_evict_the_whole_space() {
        const HUGE: u64 = MIN_HUGE_PAGE_SIZE as u64;
        let prot = libc::PROT_READ as u64;
        let private = libc::MAP_PRIVATE as u64;
        let huge_flag = private | libc::MAP_ANONYMOUS as u64 | libc::MAP_HUGETLB as u64;
        let mmap = |flags: u64, result: u64| {
            mutation_eviction(&exit_regs(
                libc::SYS_mmap,
                [0, 0x1000, prot, flags],
                result as i64,
            ))
        };
        assert_eq!(
            mmap(huge_flag, 3 * HUGE + 0x1000),
            Eviction::WholeSpace,
            "MAP_HUGETLB"
        );
        assert_eq!(
            mmap(private, 3 * HUGE),
            Eviction::WholeSpace,
            "a hugetlbfs file needs no flag but always lands on a huge-page boundary"
        );
        assert_eq!(
            mmap(private, 1 << 30),
            Eviction::WholeSpace,
            "a 1 GiB boundary"
        );
        assert_eq!(
            mmap(private, 3 * HUGE + 0x1000),
            one_range(0x60_1000, 0x60_2000),
            "one page past a boundary cannot be hugetlb"
        );

        let mremap = |old: u64, old_len: u64, new_len: u64, result: u64| {
            mutation_eviction(&exit_regs(
                libc::SYS_mremap,
                [old, old_len, new_len, libc::MREMAP_MAYMOVE as u64],
                result as i64,
            ))
        };
        assert_eq!(
            mremap(HUGE, 0x1000, 0x1000, 0x7f00_0000_1000),
            Eviction::WholeSpace,
            "an old range starting on a boundary"
        );
        assert_eq!(
            mremap(HUGE - 0x1000, 0x2000, 0x1000, 0x7f00_0000_1000),
            Eviction::WholeSpace,
            "an old range containing a boundary"
        );
        assert_eq!(
            mremap(0x1000, 0x1000, 0x2000, 5 * HUGE - 0x1000),
            Eviction::WholeSpace,
            "a new range containing a boundary"
        );
        assert_eq!(
            mremap(HUGE - 0x2000, 0x2000, 0x1000, 0x7f00_0000_1000),
            ranges(&[0x1f_e000..0x20_0000, 0x7f00_0000_1000..0x7f00_0000_2000]),
            "an old range ending exactly at a boundary does not contain it"
        );
    }

    /// PROT_GROWSDOWN and PROT_GROWSUP extend mprotect to the edge of the vma,
    /// which the registers do not name.
    fn growing_mprotect_evicts_the_whole_space() {
        for grows in [libc::PROT_GROWSDOWN, libc::PROT_GROWSUP] {
            let prot = (libc::PROT_READ | grows) as u64;
            assert_eq!(
                mutation_eviction(&exit_regs(
                    libc::SYS_mprotect,
                    [0x40000, 0x1000, prot, 0],
                    0
                )),
                Eviction::WholeSpace,
                "prot {prot:#x}"
            );
        }
    }

    /// A range whose end does not fit in the address width is not trusted.
    fn an_overflowing_range_evicts_the_whole_space() {
        assert_eq!(
            mutation_eviction(&exit_regs(
                libc::SYS_munmap,
                [u64::MAX - 0xfff, 0x2000, 0, 0],
                0
            )),
            Eviction::WholeSpace
        );
        assert_eq!(
            mutation_eviction(&exit_regs(
                libc::SYS_mprotect,
                [u64::MAX - 0xfff, 0x800, 0, 0],
                0
            )),
            Eviction::WholeSpace,
            "rounding the end up to a page overflows"
        );
    }

    /// A sibling THREAD sharing the mm loses its cached verdict for a page in
    /// the mutated range, even though a different thread made the call.
    fn a_sibling_thread_sees_a_range_eviction() {
        let a = Pid::from_raw(100);
        let b = Pid::from_raw(101);
        let mut cache = MappingCache::new(a);
        cache.share_address_space(a, b);
        cache.insert(b, 0x10000, trusted());
        cache.insert(b, 0x20000, trusted());

        let prot = libc::PROT_READ as u64;
        let mprotect = exit_regs(libc::SYS_mprotect, [0x10000, 0x1000, prot, 0], 0);
        cache.evict(a, &mutation_eviction(&mprotect));

        assert!(
            cache.get(b, 0x10000).is_none(),
            "in range, cached by the sibling"
        );
        assert!(cache.get(b, 0x20000).is_some(), "out of range");
    }

    /// The same through a real CLONE_VM child that is NOT a thread, placed by
    /// the kernel oracle, in both directions: either sharer's mutation evicts
    /// the other's cached page in range.
    fn a_clone_vm_child_sees_a_range_eviction() {
        with_child(true, |parent, child| {
            let mut cache = MappingCache::new(parent);
            cache.admit_child(parent, child, mm_sharing(parent, child));
            let munmap = |addr| exit_regs(libc::SYS_munmap, [addr, 0x1000, 0, 0], 0);

            cache.insert(child, 0x10000, trusted());
            cache.insert(child, 0x20000, trusted());
            cache.evict(parent, &mutation_eviction(&munmap(0x10000)));
            assert!(cache.get(child, 0x10000).is_none(), "parent's mutation");
            assert!(cache.get(child, 0x20000).is_some(), "out of range");

            cache.insert(parent, 0x30000, trusted());
            cache.evict(child, &mutation_eviction(&munmap(0x30000)));
            assert!(cache.get(parent, 0x30000).is_none(), "child's mutation");
            assert!(cache.get(parent, 0x20000).is_some(), "out of range");
        });
    }

    /// A range eviction stays inside the mutated address space: another mm
    /// maps something else at the same address and keeps its verdict.
    fn a_range_eviction_leaves_an_unrelated_address_space_alone() {
        let a = Pid::from_raw(100);
        let unrelated = Pid::from_raw(200);
        let mut cache = MappingCache::new(a);
        cache.new_address_space(unrelated);
        cache.insert(a, 0x10000, trusted());
        cache.insert(unrelated, 0x10000, trusted());

        let munmap = exit_regs(libc::SYS_munmap, [0x10000, 0x1000, 0, 0], 0);
        cache.evict(a, &mutation_eviction(&munmap));

        assert!(cache.get(a, 0x10000).is_none());
        assert!(cache.get(unrelated, 0x10000).is_some());
    }

    /// A tracee that stops before its parent's clone event has placed it runs
    /// in a provisional space that may stand for its parent's mm under another
    /// id. Its mutation cannot be aimed, so it drops the whole cache; once the
    /// event places it, its ranges apply to the real space again.
    fn a_mutation_before_admission_drops_every_cached_page() {
        let parent = Pid::from_raw(100);
        let early = Pid::from_raw(101);
        let mut cache = MappingCache::new(parent);
        cache.insert(parent, 0x10000, trusted());
        cache.insert(parent, 0x20000, trusted());

        let munmap = exit_regs(libc::SYS_munmap, [0x10000, 0x1000, 0, 0], 0);
        cache.evict(early, &mutation_eviction(&munmap));
        assert!(
            cache.entries.is_empty(),
            "an unplaced tracee may share the parent's mm, so nothing may survive"
        );

        cache.admit_child(parent, early, MmSharing::Shared);
        cache.insert(parent, 0x10000, trusted());
        cache.insert(parent, 0x20000, trusted());
        cache.evict(early, &mutation_eviction(&munmap));
        assert!(cache.get(parent, 0x10000).is_none(), "placed: in range");
        assert!(cache.get(parent, 0x20000).is_some(), "placed: out of range");
    }
}