hermit-detcore 0.5.0

Detcore: the deterministic scheduler and syscall determinization core of the Hermit execution engine.
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
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
/*
 * 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.
 */

//! Deterministic file descriptor

use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::time::Duration;

use nix::fcntl::OFlag;
use reverie::syscalls::Errno;
use serde::Deserialize;
use serde::Serialize;

use crate::dirents::DirEntry;
use crate::dirents::DirectoryOrder;
use crate::dirents::DirectoryStream;
use crate::procfs::ProcfsFile;
use crate::procfs::ProcfsSnapshotContext;
use crate::procfs::TimerSlackReadPreview;
use crate::procfs_inode::DirectoryInodes;
use crate::resources::ResourceID;
use crate::stat::*;
use crate::tool_global::SnapshotMark;
use crate::types::RawFd;
use crate::types::*;

/// file descriptor type
#[derive(
    PartialEq,
    Eq,
    Debug,
    Default,
    Clone,
    Copy,
    Hash,
    Serialize,
    Deserialize
)]
pub enum FdType {
    /// Regular fd, such as from openat
    #[default]
    Regular,
    /// signalfd
    Signalfd,
    /// eventfd
    Eventfd,
    /// timerfd
    Timerfd,
    /// inotify instance
    Inotify,
    /// epoll instance (from epoll_create/epoll_create1)
    Epoll,
    /// socket fd
    Socket,
    /// pipe fd
    Pipe,
    /// memfd
    Memfd,
    /// pidfd
    Pidfd,
    /// userfaultfd
    Userfaultfd,
    /// Random-number generator device
    Rng,
}

/// How an active network trace mode classifies a socket's family and type
/// (see `crate::syscalls::network_trace`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum NetworkSocketKind {
    /// Not an IPv4 or IPv6 socket, or no network trace mode was active.
    #[default]
    NotInet,
    /// An IPv4 or IPv6 TCP stream socket. `connect` checks the address
    /// against the socket's family, as Linux does.
    InetStream {
        /// Whether the socket is `AF_INET6`.
        ipv6: bool,
    },
    /// Any other IPv4 or IPv6 socket, such as UDP or raw.
    InetOther,
}

/// Read provenance authenticated at the container's initial image: a terminal
/// checked with TCGETS, the launcher's actually created controller input pipe,
/// or a readable pipe end the initial image holds on fds 0-2
/// (`FileMetadata::discover_inherited_pipes`).
///
/// The original open-file identity distinguishes aliases from separate opens
/// of the same tty. The raw identity is used only to validate an exec handoff;
/// it is never a guest-visible inode or a scheduler resource.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct InheritedExternalRead {
    pub(crate) origin: OpenFileId,
    pub(crate) dev: u64,
    pub(crate) inode: u64,
    pub(crate) rdev: u64,
    pub(crate) file_type: u32,
    pub(crate) access_mode: i32,
    pub(crate) resource: Option<ResourceID>,
}

impl std::fmt::Debug for InheritedExternalRead {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Kernel identity authenticates a private handoff; distinct launches
        // must not compare their host pipe/terminal inode numbers.
        f.debug_struct("InheritedExternalRead")
            .field("origin", &self.origin)
            .field("file_type", &self.file_type)
            .field("access_mode", &self.access_mode)
            .field("resource", &self.resource)
            .finish_non_exhaustive()
    }
}

/// Deterministic file descriptor
///
/// Notice `statbuf` can be cached here, this is because
/// `stat` is valid as long as fd stays open.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetFd {
    /// underlying file descriptor
    pub(crate) fd: RawFd,
    /// Per-slot descriptor flags, currently only `O_CLOEXEC`.
    fd_flags: i32,
    /// State shared by every descriptor referring to the same Linux `struct file`.
    open_file: Arc<Mutex<OpenFileState>>,
}

/// A handle on an open file description that Detcore models, which does not
/// keep it alive: once no modeled descriptor refers to the description, the
/// handle reaches nothing. Where one tool process serves every guest process
/// (ptrace, KVM), a descriptor that reaches the same Linux `struct file` by a
/// route Detcore does not model (`SCM_RIGHTS`) joins the description through
/// it, as a `dup` would (`Detcore::adopt_received_placeholders`).
#[derive(Clone, Debug)]
pub(crate) struct OpenFileHandle(std::sync::Weak<Mutex<OpenFileState>>);

impl OpenFileHandle {
    /// Descriptor `fd` of the description, if any modeled descriptor still
    /// refers to it: an alias, sharing its cursor, snapshot and status flags,
    /// with `FD_CLOEXEC` as `cloexec` says.
    pub(crate) fn descriptor(&self, fd: RawFd, cloexec: bool) -> Option<DetFd> {
        let open_file = self.0.upgrade()?;
        let mut detfd = DetFd {
            fd,
            fd_flags: 0,
            open_file,
        };
        detfd.set_cloexec(cloexec);
        Some(detfd)
    }
}

/// A socket's receive timeout (`SO_RCVTIMEO`, socket(7)), as the guest set it.
// TODO-HUMAN-REVIEW(PR-3908)
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum ReceiveTimeout {
    /// No timeout: a blocking call waits indefinitely. Also what a zero
    /// value sets.
    #[default]
    None,
    /// A negative second count, which Linux stores as a zero timeout, so a
    /// blocking call fails at once with `EAGAIN`. `getsockopt` reads it back
    /// as zero, the same as `None`.
    Immediate,
    /// Wait at most this long. Never so long that Linux stores no timeout.
    After(Duration),
    /// Set by a call whose value Detcore could not read.
    Unknown,
}

impl ReceiveTimeout {
    /// The timeout a successful `setsockopt(SO_RCVTIMEO)` with `value` sets.
    /// (Linux has already refused a microsecond count out of range.)
    ///
    /// Linux stores a second count too large to count in scheduler ticks, at
    /// least `LONG_MAX / HZ - 1`, as no timeout (`MAX_SCHEDULE_TIMEOUT`), so
    /// such an accept restarts after a signal like an untimed one. The model
    /// takes the bound for the largest `HZ`, 1000; on a kernel with a smaller
    /// `HZ`, record's check against the kernel refuses a value between the two.
    pub(crate) fn set_by(value: libc::timeval) -> Self {
        const UNBOUNDED_SECONDS: libc::time_t = libc::time_t::MAX / 1000 - 1;
        if value.tv_sec < 0 {
            Self::Immediate
        } else if (value.tv_sec == 0 && value.tv_usec == 0) || value.tv_sec >= UNBOUNDED_SECONDS {
            Self::None
        } else {
            Self::After(
                Duration::from_secs(value.tv_sec as u64)
                    + Duration::from_micros(value.tv_usec.max(0) as u64),
            )
        }
    }
}

/// Where the model of one open file description lives.
///
/// Every `DetFd` method reaches the model through `DetFd::with_description`,
/// so a handle's state can change from `Local` to `Shared` under every alias
/// at once, escaped clones included, because they all hold the same `Arc`.
// The state always lives inside the one `Arc` allocation its aliases share,
// so boxing `Local` would add a second allocation to every open.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Serialize, Deserialize)]
enum OpenFileState {
    /// Only this process can reach the open file description, so the model
    /// lives here until a copied runtime or new image needs a shared owner.
    Local(OpenFileDescription),
    /// Several guest processes share the open file description, so the one
    /// canonical model lives in Detcore's global state and this handle holds
    /// none. Each access takes the model through the installed
    /// [`SharedOpenFileChannel`] and publishes it back. Promotion precedes
    /// native fork/exec: <https://github.com/rrnewton/hermit/issues/4381>.
    Shared(SharedOpenFile),
}

/// The process-local part of a shared open file description: its identity,
/// and the runtime lock that is never part of the model.
#[derive(Debug, Serialize, Deserialize)]
struct SharedOpenFile {
    id: OpenFileId,
    /// Serves `DetFd::directory_lock` for this process's aliases, as the
    /// description's own lock does for a local description.
    #[serde(skip)]
    directory_lock: Arc<futures::lock::Mutex<()>>,
}

/// The canonical model of an open file description that several guest
/// processes share. Detcore's global state stores it, and a
/// [`SharedOpenFileChannel`] carries it to and from the process that holds
/// the lease. Its contents are private to Detcore.
#[derive(Debug, Serialize, Deserialize)]
pub struct OpenFileModel(OpenFileDescription);

impl OpenFileModel {
    /// The open file description this model describes.
    pub(crate) fn id(&self) -> OpenFileId {
        self.0.id
    }

    #[cfg(test)]
    pub(crate) fn path_for_test(&self) -> Option<PathBuf> {
        self.0.path.clone()
    }
}

/// The canonical model of one shared open file description, taken by one
/// process for the length of one synchronous `DetFd` method call.
#[derive(Debug, Serialize, Deserialize)]
pub struct OpenFileLease {
    /// The open file description the lease covers.
    pub id: OpenFileId,
    /// Names this lease, so that the global state can refuse a late,
    /// duplicate or foreign publish.
    pub sequence: u64,
    /// The canonical model as of the take.
    pub model: OpenFileModel,
}

/// A failure to take or publish a shared open file description.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SharedOpenFileError(pub String);

impl fmt::Display for SharedOpenFileError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.0)
    }
}

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

/// Synchronous access to the canonical models of shared open file
/// descriptions.
///
/// A `DetFd` method on a shared handle calls `take`, runs its synchronous
/// body on the model, and calls `publish`, all while it holds the handle's
/// local lock and without awaiting. So a lease never outlives one method
/// call. Detcore names no backend here: the backend that runs Detcore inside
/// each guest process installs an implementation with
/// [`install_shared_open_file_channel`].
pub trait SharedOpenFileChannel: Send + Sync {
    /// Publishes the initial local model. A duplicate identity is refused.
    /// The caller exposes shared handles only after this succeeds.
    fn promote(&self, model: &OpenFileModel) -> Result<(), SharedOpenFileError>;

    /// Takes the canonical model of `id` and starts a lease on it.
    fn take(&self, id: OpenFileId) -> Result<OpenFileLease, SharedOpenFileError>;

    /// Stores `lease.model` as the canonical model of `lease.id` and ends the
    /// lease. A publish that does not name the current lease is refused.
    fn publish(&self, lease: OpenFileLease) -> Result<(), SharedOpenFileError>;
}

static SHARED_OPEN_FILE_CHANNEL: OnceLock<Box<dyn SharedOpenFileChannel>> = OnceLock::new();

/// Installs this process's channel to shared open file descriptions. Only the
/// first channel installed in a process is retained; a later one is returned.
pub fn install_shared_open_file_channel(
    channel: Box<dyn SharedOpenFileChannel>,
) -> Result<(), Box<dyn SharedOpenFileChannel>> {
    SHARED_OPEN_FILE_CHANNEL.set(channel)
}

/// Runs `f` on the canonical model of the shared open file description `id`.
///
/// A missing channel, a failed take or publish, or a lease for another
/// description is an infrastructure failure, not something the guest's
/// syscall can report, so it panics. The model is published even when `f`
/// returns an error value, so the lease always ends; `f` itself decides what
/// it changed. If `f` panics, the lease is never published and the process
/// is lost with it.
fn with_shared_description<R>(id: OpenFileId, f: impl FnOnce(&mut OpenFileDescription) -> R) -> R {
    let channel = SHARED_OPEN_FILE_CHANNEL.get().unwrap_or_else(|| {
        panic!(
            "open file description {id:?} is shared, but no shared open file channel is installed"
        )
    });
    let mut lease = channel.take(id).unwrap_or_else(|error| {
        panic!("taking shared open file description {id:?} failed: {error}")
    });
    assert_eq!(
        lease.id, id,
        "the shared open file channel returned a lease for another description"
    );
    assert_eq!(
        lease.model.0.id, id,
        "the shared open file channel returned the model of another description"
    );
    let result = f(&mut lease.model.0);
    channel.publish(lease).unwrap_or_else(|error| {
        panic!("publishing shared open file description {id:?} failed: {error}")
    });
    result
}

#[derive(Serialize, Deserialize)]
struct OpenFileDescription {
    id: OpenFileId,
    /// fd type
    ty: FdType,
    /// Immutable inherited-read provenance. Neither guest-created PTYs nor
    /// unknown FIFOs acquire it merely by becoming stdio.
    #[serde(default)]
    inherited_external_read: Option<InheritedExternalRead>,
    /// Process named by a pidfd created through `pidfd_open`.
    ///
    /// This is shared by descriptor aliases just like the kernel pidfd object.
    /// `None` means either that this is not a pidfd or that Detcore did not
    /// observe enough provenance to identify its target.
    #[serde(default)]
    pidfd_target: Option<DetPid>,
    /// The task directory this open file is, where it was opened as one: a
    /// `/proc/self` or `/proc/thread-self` spelling with the selector replaced
    /// by the opener's numbers, or a `/proc/<pid>` or `/proc/<pid>/task/<tid>`
    /// spelling itself, and the identity of the task it named then. A name
    /// relative to it is looked up below that task's directory, whoever looks
    /// it up, while that task lives, as Linux binds a task directory to its
    /// task at the open (`Detcore::procfs_spelling_at`). The recorded `path`
    /// keeps the spelling. Shared by descriptor aliases and a fork's copies.
    #[serde(default)]
    procfs_reached: Option<(PathBuf, Option<crate::procfs::TaskIncarnation>)>,
    /// This open file is the `/proc/self` or `/proc/thread-self` link itself
    /// (an `O_PATH | O_NOFOLLOW` open), not the directory it leads to, so no
    /// name is below it (ENOTDIR), whatever its recorded `path` spells.
    #[serde(default)]
    procfs_link_itself: bool,
    /// File status flags shared by dup and fork aliases.
    status_flags: i32,
    /// File path associated with fd.
    /// This cannot be relied upon. Special devices won't have it, for example.
    path: Option<PathBuf>,
    /// Cached det/virtual inode.
    /// This cannot be relied upon. Special devices won't have it, for example.
    /// However if `ty` indicates a `Regular` file, then there should reliably be an inode.
    inode: Option<DetInode>,
    /// inode is dirty
    dirty: bool,

    /// Irrespective of whether the file descriptor is marked logically blocking by the
    /// user, this tracks whether Detcore has converted the fd to nonblocking for its own
    /// purposes.
    physically_nonblocking: bool,

    /// A FIFO opened by path in `hermit run`, still `Regular` and physically
    /// blocking: its first blocking read or write that finds a guest holding
    /// the other end makes it an internally polled `Pipe`
    /// (`Detcore::fifo_polls_if_a_guest_holds_its_peer`).
    #[serde(default)]
    fifo_awaiting_guest_peer: bool,

    /// cached statbuf
    ///
    /// This is the RAW stat from the file system, NOT determinized.
    ///
    /// Some of these fields will change at runtime. But the following fields will
    /// be constant when `virtualize_metadata` is on, over the life of the DetFd:
    ///  - dev, rdev, blksize
    ///
    /// This should always be `Some` for regular files, as we eagerly populate it.
    stat: Option<DetStat>,
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1096): Review canonical random-device cursor sharing.
    /// Cursor into Hermit's backend-independent random-device byte stream.
    #[serde(default)]
    random_device_offset: u64,
    /// resource
    resource: Option<ResourceID>,
    /// Deterministic snapshot state for selected procfs files.
    procfs: Option<ProcfsFile>,
    /// Signal phase 1's kernel account of the file, recorded at its open by a
    /// process that handles SIGALRM (`sigalrm_phase1::kernel_provenance`).
    #[serde(default)]
    sigalrm_phase1: Option<crate::sigalrm_phase1::Phase1Provenance>,
    /// Sorted directory stream, created by the first `getdents` call that
    /// succeeds on this open file description.
    #[serde(default)]
    directory: Option<DirectoryStream>,
    /// True while `getdents` on this open file reads the host directory one
    /// kernel buffer at a time, because no whole-directory snapshot can stand
    /// in for its position. See `use_host_directory_order`; an `lseek` back
    /// to 0 clears it.
    #[serde(default)]
    directory_host_order: bool,
    /// Held across a whole `getdents` or `lseek` on this open file
    /// description. Reading the host directory takes several injected
    /// syscalls on the shared kernel position, and the kernel's own per-file
    /// position lock covers only one of them; without this, two unsequentialized
    /// threads could interleave their reads and each keep part of the
    /// directory. Sequentialized threads never contend for it.
    ///
    /// This must stay a runtime-agnostic lock that uses no thread-locals.
    /// The DBT backend polls these handlers on DynamoRIO application
    /// threads, outside any Tokio runtime. Tokio's own locks charge each
    /// poll to a per-thread budget kept in a thread-local that has a
    /// destructor, and registering a thread-local destructor on a DynamoRIO
    /// application thread crashes DynamoRIO: the run exits with status 255
    /// and loses its evidence FINAL frames.
    #[serde(skip)]
    directory_lock: Arc<futures::lock::Mutex<()>>,
    /// Logical timestamp of the last packet delivered through this socket.
    socket_receive_timestamp: Option<LogicalTime>,
    /// True when this open file is an `AF_NETLINK`/`NETLINK_SOCK_DIAG` socket,
    /// whose binary dump replies carry host-assigned socket inode numbers that
    /// must be determinized (see `crate::sock_diag`).
    sock_diag: bool,
    /// Whether this open file is a `NETLINK_ROUTE` socket whose link-dump
    /// replies carry live interface counters that must be zeroed (see
    /// `crate::netlink_route`).
    netlink_route: bool,
    /// True when this socket connected to an IPv4 or IPv6 loopback peer.
    #[serde(default)]
    loopback_peer: bool,
    /// True when this socket is a channel of the external network trace, so
    /// its traffic is recorded or replayed (see `crate::syscalls::network_trace`).
    #[serde(default)]
    network_channel: bool,
    /// The socket's `SO_RCVLOWAT` while a network trace mode is active, or
    /// `None` for the default of one byte.
    #[serde(default)]
    network_lowat: Option<usize>,
    /// The socket's family and type, recorded at creation while a network
    /// trace mode is active.
    #[serde(default)]
    network_socket: NetworkSocketKind,
    /// True when this socket is one end of a `socketpair(2)`, whose two
    /// endpoints are therefore both container-internal. See
    /// `syscall_targets_internal_fd`.
    #[serde(default)]
    socketpair_endpoint: bool,
    /// True when `accept(2)` or `accept4(2)` returned this socket. Record and
    /// replay keep such a connection only in the log, and replay stands in an
    /// eventfd for it. See `is_accepted_connection`.
    #[serde(default)]
    accepted_connection: bool,
    /// True when record/replay runs a blocking `accept(2)` on this socket in
    /// the caller's turn, one nonblocking attempt at a time. `socket(2)` sets
    /// it for a stream socket the container created. See
    /// `is_accept_in_turn_listener`.
    // TODO-HUMAN-REVIEW(PR-3908)
    #[serde(default)]
    accept_in_turn_eligible: bool,
    /// True once this socket was named in an `SCM_RIGHTS` message, so a
    /// process outside Detcore's view may hold it. Permanent. See
    /// `is_exported`.
    #[serde(default)]
    exported: bool,
    /// The receive timeout the last successful `setsockopt(SO_RCVTIMEO)` on
    /// this socket set, which a blocking accept in turn waits by. See
    /// `receive_timeout`.
    #[serde(default)]
    receive_timeout: ReceiveTimeout,
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#2373)
    /// The `flock(2)` mode this open file description currently holds, as the
    /// bare `LOCK_SH`/`LOCK_EX` constant, or `None` when it holds no lock.
    ///
    /// `flock` locks are a property of the open file description, not of the
    /// descriptor slot and not of the inode, which is exactly the granularity
    /// this struct models: `dup`/`fork` aliases share one lock, two separate
    /// `open`s of the same file contend with each other.
    ///
    /// Detcore tracks this only so `handle_flock` can tell a first acquisition
    /// (where a failed `LOCK_NB` probe changes nothing) from a *conversion* of
    /// an already-held lock (where Linux drops the old lock before it can fail).
    /// It is a cache of what Detcore itself granted, never an authority: it is
    /// written only after the kernel reports success.
    #[serde(default)]
    flock_mode: Option<i32>,
    /// Whether `flock_mode` describes the kernel state. Descriptors created by
    /// an intercepted syscall start known-unlocked; descriptors discovered
    /// after entering the guest can already carry a lock.
    #[serde(default)]
    flock_mode_known: bool,
    /// Whether Detcore has EVER known this description's lock state.
    ///
    /// This separates two different unknowns that `flock_mode_known == false`
    /// otherwise collapses. A descriptor Detcore never observed -- stdin,
    /// stdout, stderr, a live-discovered fd -- has no cached claim at all, so
    /// there is nothing about it that can be STALE. A descriptor that was known
    /// and then invalidated by a process copy does have a claim that may now be
    /// wrong. Only the second is a reason to refuse `vfork`.
    #[serde(default)]
    flock_mode_ever_known: bool,
    /// A timerfd's expirations as a function of virtual time, once the guest
    /// has armed or disarmed it through Detcore (`VirtualTimerfd`). `None` for
    /// every other description, and for a timerfd Detcore leaves to the host
    /// (record/replay, or no virtual time).
    #[serde(default)]
    timerfd: Option<VirtualTimerfd>,
    /// The pipe or FIFO this description is an end of, for handing the turn
    /// to a thread polling it once another thread readies it
    /// (`--pipe-wake-latency`, https://github.com/rrnewton/hermit/issues/4380).
    /// Set only while that option is on; `None` otherwise, and for a
    /// descriptor whose channel Detcore does not know.
    #[serde(default)]
    channel: Option<crate::pipe_wake::ChannelEnd>,
    /// True once Detcore read this description's OFD and flock locks from its
    /// fdinfo after a call through it (`Detcore::refresh_description_locks`):
    /// from then on, each table's last close or replacement of it is reported
    /// to `procfs::locks::LockLedger`. Shared by every alias, as the
    /// description is. Not printed, so descriptions log as before.
    #[serde(default)]
    lock_tracked: bool,
    /// True once this description was registered on reception over
    /// `SCM_RIGHTS` (`Detcore::refresh_description_locks`): the sender's
    /// entry in `procfs::locks::LockLedger` may name the same kernel
    /// description under another identity. Not printed.
    #[serde(default)]
    received_for_locks: bool,
    /// True once this description may hold an OFD lock: an `F_OFD_SETLK` or
    /// `F_OFD_SETLKW` went through it, its fdinfo showed one, or its fdinfo
    /// could not be read. DBT refuses a copied `vfork` child, which would run
    /// its lock calls natively, while one does. Not printed.
    #[serde(default)]
    may_hold_ofd_lock: bool,
}
/// Written out, not derived, so that `channel` is printed only when it is set:
/// a run without `--pipe-wake-latency` logs every description exactly as
/// before the field existed.
impl std::fmt::Debug for OpenFileDescription {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug = f.debug_struct("OpenFileDescription");
        debug.field("id", &self.id);
        debug.field("ty", &self.ty);
        debug.field("inherited_external_read", &self.inherited_external_read);
        debug.field("pidfd_target", &self.pidfd_target);
        debug.field("procfs_reached", &self.procfs_reached);
        debug.field("status_flags", &self.status_flags);
        debug.field("path", &self.path);
        debug.field("inode", &self.inode);
        debug.field("dirty", &self.dirty);
        debug.field("physically_nonblocking", &self.physically_nonblocking);
        debug.field("fifo_awaiting_guest_peer", &self.fifo_awaiting_guest_peer);
        debug.field("stat", &self.stat);
        debug.field("random_device_offset", &self.random_device_offset);
        debug.field("resource", &self.resource);
        debug.field("procfs", &self.procfs);
        debug.field("sigalrm_phase1", &self.sigalrm_phase1);
        debug.field("directory", &self.directory);
        debug.field("directory_host_order", &self.directory_host_order);
        debug.field("directory_lock", &self.directory_lock);
        debug.field("socket_receive_timestamp", &self.socket_receive_timestamp);
        debug.field("sock_diag", &self.sock_diag);
        debug.field("netlink_route", &self.netlink_route);
        debug.field("loopback_peer", &self.loopback_peer);
        debug.field("network_channel", &self.network_channel);
        debug.field("network_lowat", &self.network_lowat);
        debug.field("network_socket", &self.network_socket);
        debug.field("socketpair_endpoint", &self.socketpair_endpoint);
        debug.field("accepted_connection", &self.accepted_connection);
        debug.field("accept_in_turn_eligible", &self.accept_in_turn_eligible);
        debug.field("exported", &self.exported);
        debug.field("receive_timeout", &self.receive_timeout);
        debug.field("flock_mode", &self.flock_mode);
        debug.field("flock_mode_known", &self.flock_mode_known);
        debug.field("flock_mode_ever_known", &self.flock_mode_ever_known);
        debug.field("timerfd", &self.timerfd);
        if let Some(channel) = &self.channel {
            debug.field("channel", channel);
        }
        debug.finish()
    }
}

/// A timerfd's expirations counted on Detcore's virtual clock instead of the
/// host's (timerfd_create(2)).
///
/// The host timerfd behind the descriptor is never armed with the guest's
/// setting, so the host cannot make it readable at a host-timed moment.
/// Instead, when a thread of the process observes the descriptor after the
/// virtual deadline (`crate::syscalls::timerfd`), Detcore counts the
/// expirations here and makes the host descriptor readable before the guest's
/// probe runs; a `read` then returns the count kept here.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct VirtualTimerfd {
    /// The next expiration not yet counted, or `None` when disarmed.
    pub(crate) deadline: Option<LogicalTime>,
    /// The reload interval in nanoseconds, 0 for a one-shot timer.
    pub(crate) interval_ns: u64,
    /// Expirations counted but not yet read.
    pub(crate) unread: u64,
}

impl VirtualTimerfd {
    /// The state `timerfd_settime` leaves: armed at `deadline` (or disarmed
    /// with `None`), with no expiration pending, as Linux discards the count.
    /// A disarmed timer keeps `interval_ns`, which `timerfd_gettime` reports.
    pub(crate) fn set(deadline: Option<LogicalTime>, interval_ns: u64) -> Self {
        VirtualTimerfd {
            deadline,
            interval_ns,
            unread: 0,
        }
    }

    /// Counts every expiration at or before `now`, as Linux would have by
    /// then, and returns how many were added. A periodic timer moves to its
    /// first expiration after `now`; a one-shot timer disarms.
    pub(crate) fn expire_through(&mut self, now: LogicalTime) -> u64 {
        let Some(deadline) = self.deadline else {
            return 0;
        };
        if now < deadline {
            return 0;
        }
        let elapsed = now.as_nanos() - deadline.as_nanos();
        let added = match elapsed.checked_div(self.interval_ns) {
            // A one-shot timer expires once and disarms.
            None => {
                self.deadline = None;
                1
            }
            Some(periods) => {
                let added = 1 + periods;
                self.deadline = Some(LogicalTime::from_nanos(
                    deadline
                        .as_nanos()
                        .saturating_add(added.saturating_mul(self.interval_ns)),
                ));
                added
            }
        };
        self.unread = self.unread.saturating_add(added);
        added
    }

    /// `timerfd_gettime`'s answer at `now`, after `expire_through(now)`: the
    /// time left to the next expiration (0 when disarmed) and the interval,
    /// both in nanoseconds.
    pub(crate) fn remaining(&self, now: LogicalTime) -> (u64, u64) {
        let left = self.deadline.map_or(0, |deadline| {
            deadline.as_nanos().saturating_sub(now.as_nanos())
        });
        (left, self.interval_ns)
    }
}

impl PartialEq for DetFd {
    fn eq(&self, other: &Self) -> bool {
        self.fd == other.fd
    }
}

impl Eq for DetFd {}

impl Hash for DetFd {
    // fd is owned by process and is unique per process/thread
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.fd.hash(state);
    }
}

/// If the flags specify O_NONBLOCK.
fn oflags_nonblocking(flags: i32) -> bool {
    let o_nonblock = OFlag::O_NONBLOCK.bits();
    flags & o_nonblock == o_nonblock
}

impl DetFd {
    /// Publish a local description before another process or image can use
    /// it. Every escaped alias switches together under the existing mutex.
    /// Failure leaves the local model intact and must stop the lifecycle.
    pub(crate) fn promote(&self) -> Result<(), SharedOpenFileError> {
        let mut state = self.open_file.lock().expect("open file mutex poisoned");
        let OpenFileState::Local(description) = &*state else {
            return Ok(());
        };
        let shared = SharedOpenFile {
            id: description.id,
            directory_lock: Arc::clone(&description.directory_lock),
        };
        let OpenFileState::Local(description) =
            std::mem::replace(&mut *state, OpenFileState::Shared(shared))
        else {
            unreachable!()
        };
        let model = OpenFileModel(description);
        let result = SHARED_OPEN_FILE_CHANNEL
            .get()
            .ok_or_else(|| SharedOpenFileError("no shared open file channel installed".into()))
            .and_then(|channel| channel.promote(&model));
        if result.is_err() {
            *state = OpenFileState::Local(model.0);
        }
        result
    }

    pub(crate) fn is_shared(&self) -> bool {
        matches!(
            *self.open_file.lock().expect("open file mutex poisoned"),
            OpenFileState::Shared(_)
        )
    }

    /// A new process needs its own unlocked runtime lock, but the same
    /// canonical identity. The caller interns aliases after copying the table.
    pub(crate) fn fork_shared_handle(&self) -> Self {
        let state = self.open_file.lock().expect("open file mutex poisoned");
        let mut copied = self.clone();
        if let OpenFileState::Shared(shared) = &*state {
            copied.open_file = Arc::new(Mutex::new(OpenFileState::Shared(SharedOpenFile {
                id: shared.id,
                directory_lock: Arc::default(),
            })));
        }
        copied
    }

    /// Restore an authenticated survivor from the existing exec handover.
    pub(crate) fn shared_survivor(fd: RawFd, id: OpenFileId) -> Self {
        Self {
            fd,
            fd_flags: 0,
            open_file: Arc::new(Mutex::new(OpenFileState::Shared(SharedOpenFile {
                id,
                directory_lock: Arc::default(),
            }))),
        }
    }

    /// Only a copied local flock cache can become stale at fork. Shared
    /// models retain kernel-observed lock changes without a pre-grant RPC.
    pub(crate) fn forget_local_flock_mode_at_fork(&self) {
        let mut state = self.open_file.lock().expect("open file mutex poisoned");
        if let OpenFileState::Local(description) = &mut *state {
            description.flock_mode = None;
            description.flock_mode_known = false;
        }
    }

    /// Inspect only local ownership and the skipped directory lease. This
    /// never takes a canonical shared-OFD lease or contacts its channel.
    /// The caller separately owns quiescence across this temporary probe.
    pub(crate) fn validate_native_exec_runtime_state(
        &self,
    ) -> Result<(OpenFileId, usize), crate::native_exec::NativeExecCutError> {
        use crate::native_exec::NativeExecCutError;

        let state = crate::native_exec::try_native_exec_lock(&self.open_file, "open_file")?;
        let (id, directory_lock) = match &*state {
            OpenFileState::Local(description) => (description.id, &description.directory_lock),
            OpenFileState::Shared(shared) => (shared.id, &shared.directory_lock),
        };
        let _lease = directory_lock
            .try_lock()
            .ok_or(NativeExecCutError::LiveCapability("directory lease"))?;
        Ok((id, Arc::as_ptr(&self.open_file) as usize))
    }

    /// create a new detfd from rawfd
    pub fn new(fd: RawFd, flags: OFlag, ty: FdType, id: OpenFileId) -> Self {
        let bits = flags.bits();
        DetFd {
            fd,
            fd_flags: bits & OFlag::O_CLOEXEC.bits(),
            open_file: Arc::new(Mutex::new(OpenFileState::Local(OpenFileDescription {
                id,
                ty,
                pidfd_target: None,
                procfs_reached: None,
                procfs_link_itself: false,
                inherited_external_read: None,
                status_flags: bits & !OFlag::O_CLOEXEC.bits(),
                path: None,
                inode: None,
                dirty: false,
                fifo_awaiting_guest_peer: false,
                stat: None,
                random_device_offset: 0,
                resource: None,
                procfs: None,
                sigalrm_phase1: None,
                directory: None,
                directory_host_order: false,
                directory_lock: Default::default(),
                socket_receive_timestamp: None,
                sock_diag: false,
                netlink_route: false,
                loopback_peer: false,
                network_channel: false,
                network_lowat: None,
                network_socket: NetworkSocketKind::NotInet,
                socketpair_endpoint: false,
                accepted_connection: false,
                accept_in_turn_eligible: false,
                exported: false,
                receive_timeout: ReceiveTimeout::None,
                flock_mode: None,
                flock_mode_known: true,
                flock_mode_ever_known: true,
                timerfd: None,
                channel: None,
                lock_tracked: false,
                received_for_locks: false,
                may_hold_ofd_lock: false,
                // By default, we assume it matches the flags we were given:
                physically_nonblocking: oflags_nonblocking(bits),
            }))),
        }
    }

    /// Runs `f` on this open file description's model while holding the lock
    /// every alias shares. One call is one atomic step on the model, whether
    /// the model is local or shared (see [`OpenFileState`]). `f` must not
    /// access this description through another `DetFd` method or alias, and
    /// must not await.
    fn with_description<R>(&self, f: impl FnOnce(&mut OpenFileDescription) -> R) -> R {
        let mut state = self.open_file.lock().expect("open file mutex poisoned");
        match &mut *state {
            OpenFileState::Local(description) => f(description),
            OpenFileState::Shared(shared) => with_shared_description(shared.id, f),
        }
    }

    /// A handle on this descriptor's open file description that does not
    /// keep it alive ([`OpenFileHandle`]).
    pub(crate) fn open_file_handle(&self) -> OpenFileHandle {
        OpenFileHandle(Arc::downgrade(&self.open_file))
    }

    /// update fd
    pub fn with_fd(mut self, fd: RawFd) -> Self {
        self.fd = fd;
        self
    }
    /// change fd type
    pub fn with_type(self, ty: FdType) -> Self {
        self.with_description(|d| d.ty = ty);
        self
    }
    /// Set per-slot descriptor flags on a newly duplicated fd.
    pub fn with_fd_flags(mut self, flags: OFlag) -> Self {
        self.fd_flags = flags.bits() & OFlag::O_CLOEXEC.bits();
        self
    }
    /// set path associated with `fd`
    pub fn with_path<P: AsRef<Path>>(self, path: P) -> Self {
        let path = Some(PathBuf::from(path.as_ref()));
        self.with_description(|d| d.path = path);
        self
    }
    /// set virtual inode
    pub fn with_inode(self, inode: DetInode) -> Self {
        self.with_description(|d| d.inode = Some(inode));
        self
    }
    /// set dirty flag
    pub fn with_dirty(self, dirty: bool) -> Self {
        self.with_description(|d| d.dirty = dirty);
        self
    }
    /// update statbuf
    pub fn with_stat<S: Into<Option<DetStat>>>(self, stat: S) -> Self {
        let stat = stat.into();
        self.with_description(|d| d.stat = stat);
        self
    }
    /// set resource id
    pub fn with_resource<S: Into<Option<ResourceID>>>(self, resource: S) -> Self {
        let resource = resource.into();
        self.with_description(|d| d.resource = resource);
        self
    }

    /// Update the scheduler resource shared by aliases of this open file.
    pub(crate) fn set_resource<S: Into<Option<ResourceID>>>(&self, resource: S) {
        let resource = resource.into();
        self.with_description(|d| d.resource = resource);
    }

    pub(crate) fn inherited_external_read(&self) -> Option<InheritedExternalRead> {
        self.with_description(|d| d.inherited_external_read.clone())
    }

    pub(crate) fn set_inherited_external_read(&self, terminal: InheritedExternalRead) {
        self.with_description(|d| d.inherited_external_read = Some(terminal));
    }

    /// If fd is non blocking
    pub fn is_nonblocking(&self) -> bool {
        self.with_description(|d| oflags_nonblocking(d.status_flags))
    }

    /// Whether close-on-exec is set for this descriptor slot.
    pub fn is_cloexec(&self) -> bool {
        self.fd_flags & OFlag::O_CLOEXEC.bits() != 0
    }

    /// Update close-on-exec for this descriptor slot only.
    pub fn set_cloexec(&mut self, enabled: bool) {
        self.fd_flags = if enabled { OFlag::O_CLOEXEC.bits() } else { 0 };
    }

    /// Update both the logical (guest-visible) and physical (scheduler)
    /// nonblocking status for every alias of this open file description. Use this
    /// only when the physical fd genuinely tracks the guest's request; when
    /// Detcore forces the fd physically nonblocking for the scheduler, update the
    /// logical view alone via [`Self::set_logical_nonblocking`].
    pub fn set_nonblocking(&self, enabled: bool) {
        self.with_description(|description| {
            if enabled {
                description.status_flags |= OFlag::O_NONBLOCK.bits();
            } else {
                description.status_flags &= !OFlag::O_NONBLOCK.bits();
            }
            description.physically_nonblocking = enabled;
        })
    }

    /// Update only the logical (guest-visible) O_NONBLOCK status flag, leaving
    /// the physical (scheduler) nonblocking state untouched. This lets a guest
    /// clear O_NONBLOCK while Detcore keeps the fd physically nonblocking, which
    /// the scheduler relies on for nonblockize-and-retry.
    pub fn set_logical_nonblocking(&self, enabled: bool) {
        self.with_description(|description| {
            if enabled {
                description.status_flags |= OFlag::O_NONBLOCK.bits();
            } else {
                description.status_flags &= !OFlag::O_NONBLOCK.bits();
            }
        })
    }

    /// Makes this descriptor refer to `other`'s open file description object.
    pub(crate) fn share_open_file_with(&mut self, other: &DetFd) {
        self.open_file = Arc::clone(&other.open_file);
    }

    /// Stable identity shared by dup and fork aliases. A shared handle keeps
    /// its identity locally, so this never takes the canonical model.
    pub fn open_file_id(&self) -> OpenFileId {
        match &*self.open_file.lock().expect("open file mutex poisoned") {
            OpenFileState::Local(description) => description.id,
            OpenFileState::Shared(shared) => shared.id,
        }
    }

    /// Number of modeled descriptor slots that retain this open file description.
    pub(crate) fn open_file_alias_count(&self) -> usize {
        Arc::strong_count(&self.open_file)
    }

    /// File type attached to the open file description.
    pub fn ty(&self) -> FdType {
        self.with_description(|d| d.ty)
    }

    /// This timerfd's virtual-time model, if Detcore keeps one.
    pub(crate) fn virtual_timerfd(&self) -> Option<VirtualTimerfd> {
        self.with_description(|d| d.timerfd)
    }

    /// Replace this timerfd's virtual-time model, under every alias.
    pub(crate) fn set_virtual_timerfd(&self, timerfd: Option<VirtualTimerfd>) {
        self.with_description(|d| {
            debug_assert_eq!(d.ty, FdType::Timerfd);
            d.timerfd = timerfd;
        })
    }

    /// Record the process identity carried by a newly created pidfd.
    pub(crate) fn set_pidfd_target(&self, target: DetPid) {
        self.with_description(|description| {
            debug_assert_eq!(description.ty, FdType::Pidfd);
            description.pidfd_target = Some(target);
        })
    }

    /// Return the process identity carried by this pidfd, when known.
    pub(crate) fn pidfd_target(&self) -> Option<DetPid> {
        self.with_description(|d| d.pidfd_target)
    }

    /// Record where the `/proc` selector spelling this open file was opened
    /// by led (`OpenFileDescription::procfs_reached`).
    /// `incarnation` is the identity of the task the selector reached, where
    /// Detcore asked its process table (`procfs::TaskIncarnation`): a name
    /// below it is that task's while no other task holds its numbers.
    pub(crate) fn set_procfs_reached(
        &self,
        reached: PathBuf,
        incarnation: Option<crate::procfs::TaskIncarnation>,
    ) {
        self.with_description(|d| d.procfs_reached = Some((reached, incarnation)))
    }

    /// Record that this open file is a `/proc` selector link itself
    /// (`OpenFileDescription::procfs_link_itself`).
    pub(crate) fn set_procfs_link_itself(&self) {
        self.with_description(|d| d.procfs_link_itself = true)
    }

    /// Whether this open file is a `/proc` selector link itself.
    pub(crate) fn procfs_link_itself(&self) -> bool {
        self.with_description(|d| d.procfs_link_itself)
    }

    /// The task directory this open file is, if Detcore knows it
    /// (`OpenFileDescription::procfs_reached`).
    pub(crate) fn procfs_reached(
        &self,
    ) -> Option<(PathBuf, Option<crate::procfs::TaskIncarnation>)> {
        self.with_description(|d| d.procfs_reached.clone())
    }

    /// The pipe or FIFO this descriptor is an end of, when
    /// `--pipe-wake-latency` is on and Detcore knows it
    /// (`crate::pipe_wake`).
    pub(crate) fn channel(&self) -> Option<crate::pipe_wake::ChannelEnd> {
        self.with_description(|d| d.channel)
    }

    /// Name the pipe or FIFO this descriptor's open file description is an
    /// end of. Shared by every alias of the description.
    pub(crate) fn set_channel(&self, channel: crate::pipe_wake::ChannelEnd) {
        self.with_description(|d| d.channel = Some(channel))
    }

    /// Resource attached to the open file description.
    pub fn resource(&self) -> Option<ResourceID> {
        self.with_description(|d| d.resource.clone())
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1096): Review canonical random-device cursor sharing.
    /// Return the cursor shared by aliases of this random-device open file.
    #[cfg(test)]
    pub(crate) fn random_device_offset(&self) -> u64 {
        self.with_description(|d| d.random_device_offset)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1096): Review canonical random-device cursor sharing.
    /// Advance the cursor shared by aliases of this random-device open file.
    #[cfg(test)]
    pub(crate) fn advance_random_device_offset(&self, count: usize) {
        self.with_description(|description| {
            description.random_device_offset = description
                .random_device_offset
                .saturating_add(count as u64);
        })
    }

    /// Copy from the shared random-device cursor and commit the returned byte count.
    ///
    /// The description stays locked throughout the synchronous copy. The closure
    /// must not access this description through another `DetFd` method or alias.
    /// Clone the descriptor and drop its metadata guard before entering this
    /// transaction; the closure must not acquire Detcore metadata/description
    /// locks or await. This preserves the metadata-before-description lock order.
    /// A large copy can block relaxed-mode aliases for its bounded duration.
    /// An error leaves the cursor unchanged; it does not undo guest memory writes.
    pub(crate) fn with_random_device_stream<R>(
        &self,
        copy: impl FnOnce(u64) -> Result<usize, R>,
    ) -> Result<usize, R> {
        self.with_description(|description| {
            let copied = copy(description.random_device_offset)?;
            description.random_device_offset = description
                .random_device_offset
                .saturating_add(copied as u64);
            Ok(copied)
        })
    }

    /// Path used to open this file description, when it was observable.
    pub(crate) fn path(&self) -> Option<PathBuf> {
        self.with_description(|d| d.path.clone())
    }

    /// Record the resolved path used to open this file description.
    pub(crate) fn set_path<P: AsRef<Path>>(&self, path: P) {
        let path = Some(path.as_ref().to_path_buf());
        self.with_description(|d| d.path = path);
    }

    /// Attach deterministic procfs snapshot state to this open file description.
    pub(crate) fn set_procfs(&self, procfs: ProcfsFile) {
        self.with_description(|d| d.procfs = Some(procfs));
    }

    /// The procfs path of a file Detcore opened with no kernel object behind
    /// it (`ProcfsFile::is_rendered`): this descriptor is a placeholder.
    pub(crate) fn procfs_rendered_path(&self) -> Option<&'static Path> {
        self.with_description(|d| d.procfs.as_ref().and_then(ProcfsFile::opened_path))
    }

    /// The procfs path of a file whose every byte Detcore renders
    /// (`ProcfsFile::rendered_path`), whether Detcore opened it as a
    /// placeholder or the kernel opened it: through a symbolic link or `..`,
    /// after `chroot`, or under record and replay. `files` are the files the
    /// session renders (`Detcore::rendered_files`).
    pub(crate) fn procfs_renderable_path(
        &self,
        files: crate::procfs::RenderedFiles,
    ) -> Option<&'static Path> {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .and_then(|procfs| procfs.served_rendered_path(files))
        })
    }

    /// Whether Linux reads this procfs file through `read_iter`
    /// (`ProcfsFile::has_read_iter`).
    pub(crate) fn procfs_has_read_iter(&self) -> bool {
        self.with_description(|d| d.procfs.as_ref().is_none_or(ProcfsFile::has_read_iter))
    }

    /// Whether Detcore keeps this procfs file's kernel position at its own
    /// cursor: a placeholder, or a fixed file the kernel opened (whose
    /// snapshot Detcore renders without reading the kernel's file). A backend
    /// that rediscovers descriptors after `exec` reads the position back.
    pub(crate) fn procfs_keeps_kernel_position(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(|procfs| procfs.is_rendered() || procfs.snapshot_is_fixed())
        })
    }

    /// Whether this procfs file's snapshot seeks only from the start or the
    /// position (`ProcfsFile::seeks_only_from_start_or_position`).
    pub(crate) fn procfs_seeks_only_from_start_or_position(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(ProcfsFile::seeks_only_from_start_or_position)
        })
    }

    /// Whether a short copy of a read of this procfs file is `EFAULT`
    /// (`ProcfsFile::faults_on_a_short_copy`).
    pub(crate) fn procfs_faults_on_a_short_copy(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(ProcfsFile::faults_on_a_short_copy)
        })
    }

    /// The bytes a procfs file's snapshot starts from in place of a capture
    /// of the kernel's file, if it takes none: a rendered file's template
    /// (`ProcfsFile::rendering_template`), or nothing for a fixed file the
    /// kernel opened (through a symbolic link, after `chroot`, under record
    /// and replay), whose bytes are the description's whatever the kernel's
    /// file holds (`ProcfsFile::snapshot_is_fixed`).
    pub(crate) fn procfs_rendering_template(&self) -> Option<&'static [u8]> {
        self.with_description(|d| {
            d.procfs.as_ref().and_then(|procfs| {
                if procfs.is_rendered() {
                    Some(procfs.rendering_template())
                } else if procfs.snapshot_is_fixed() {
                    Some(&b""[..])
                } else {
                    None
                }
            })
        })
    }

    /// Whether Detcore opened this procfs file without a kernel object behind
    /// it and its first read takes its snapshot at an uptime the placeholder
    /// carries (`ProcfsFile::snapshot_carries_uptime`,
    /// `Detcore::first_read_uptime`).
    pub(crate) fn procfs_rendered_at_first_read(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(|procfs| procfs.is_rendered() && procfs.snapshot_carries_uptime())
        })
    }

    /// Whether this procfs open file description still needs its initial snapshot.
    pub(crate) fn procfs_needs_snapshot(&self) -> bool {
        self.with_description(|d| d.procfs.as_ref().is_some_and(ProcfsFile::needs_snapshot))
    }

    /// Whether reads of this open file description are served from a procfs
    /// snapshot, already taken or still to be taken.
    pub(crate) fn procfs_serves_snapshot(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(|procfs| procfs.needs_snapshot() || procfs.position().1.is_some())
        })
    }

    /// Signal phase 1's kernel account of this file, if one was recorded.
    pub(crate) fn sigalrm_phase1_provenance(
        &self,
    ) -> Option<crate::sigalrm_phase1::Phase1Provenance> {
        self.with_description(|d| d.sigalrm_phase1)
    }

    /// Record signal phase 1's kernel account of this file.
    pub(crate) fn set_sigalrm_phase1_provenance(
        &self,
        provenance: crate::sigalrm_phase1::Phase1Provenance,
    ) {
        self.with_description(|d| d.sigalrm_phase1 = Some(provenance));
    }

    /// Whether this procfs file's snapshot cannot wait to be taken
    /// (`ProcfsFile::capture_cannot_wait`).
    pub(crate) fn procfs_capture_cannot_wait(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(ProcfsFile::capture_cannot_wait)
        })
    }

    /// Whether this procfs snapshot consumes deterministic random bytes.
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-955): Review deterministic kernel UUID generation.
    /// Whether this snapshot has maps-format headers needing determinized
    /// device and inode columns.
    pub(crate) fn procfs_needs_mapping_identities(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(ProcfsFile::needs_mapping_identities)
        })
    }

    pub(crate) fn procfs_is_maps(&self) -> bool {
        self.with_description(|d| d.procfs.as_ref().is_some_and(ProcfsFile::is_maps))
    }

    pub(crate) fn procfs_maps_target(&self) -> Option<crate::procfs::MapsTarget> {
        self.with_description(|d| d.procfs.as_ref().and_then(ProcfsFile::maps_target))
    }

    /// Carry the opened maps description, including its old target and cursor,
    /// through the authenticated exec handoff instead of rediscovering a target.
    pub(crate) fn maps_for_exec(&self) -> Option<ProcfsFile> {
        self.with_description(|d| d.procfs.as_ref().filter(|p| p.is_maps()).cloned())
    }

    /// Whether this procfs file lists the guest's own address space, so
    /// its capture must not create a mapping that the listing would show.
    pub(crate) fn procfs_lists_address_space(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(ProcfsFile::lists_address_space)
        })
    }

    /// The view of the mounts this kernel-opened procfs file reads, as its
    /// open pinned it (`ProcfsFile::pinned_mount_view`).
    pub(crate) fn procfs_pinned_mount_view(&self) -> Option<bool> {
        self.with_description(|d| d.procfs.as_ref().and_then(ProcfsFile::pinned_mount_view))
    }

    /// Which rendering of the container mount table this procfs file is, if
    /// it is one (`ProcfsFile::mount_table_rendering`).
    pub(crate) fn procfs_mount_table_rendering(
        &self,
    ) -> Option<crate::procfs::MountTableRendering> {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .and_then(ProcfsFile::mount_table_rendering)
        })
    }

    pub(crate) fn procfs_needs_mountinfo_identities(&self) -> bool {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .is_some_and(ProcfsFile::needs_mountinfo_identities)
        })
    }

    /// Whether this descriptor's procfs file is `/proc/locks`, whose rows
    /// Detcore filters to the guest's own (`procfs::locks`).
    pub(crate) fn procfs_lists_locks(&self) -> bool {
        self.with_description(|d| d.procfs.as_ref().is_some_and(ProcfsFile::lists_locks))
    }

    pub(crate) fn procfs_needs_random_uuid(&self) -> bool {
        self.with_description(|d| d.procfs.as_ref().is_some_and(ProcfsFile::needs_random_uuid))
    }

    pub(crate) fn procfs_is_cpuinfo(&self) -> bool {
        self.with_description(|d| d.procfs.as_ref().is_some_and(ProcfsFile::is_cpuinfo))
    }

    pub(crate) fn procfs_needs_boot_time(&self) -> bool {
        self.with_description(|d| d.procfs.as_ref().is_some_and(ProcfsFile::needs_boot_time))
    }

    /// The kernel process numbers a process's `stat` or `status` named by
    /// number holds in `contents` (`ProcfsFile::kernel_numbers_held`).
    pub(crate) fn procfs_kernel_numbers_held(&self, contents: &[u8]) -> Vec<i32> {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .map_or_else(Vec::new, |file| file.kernel_numbers_held(contents))
        })
    }

    /// The guest thread whose signal mask the status snapshot about to be
    /// taken reports (`ProcfsFile::status_mask_thread`).
    pub(crate) fn procfs_status_mask_thread(&self, contents: &[u8]) -> Option<i32> {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .and_then(|file| file.status_mask_thread(contents))
        })
    }

    /// The guest's numbers for the kernel's numbers in the snapshot about to
    /// be taken (`ProcfsFile::set_guest_numbers`).
    pub(crate) fn set_procfs_guest_numbers(&self, numbers: std::collections::BTreeMap<i32, i32>) {
        self.with_description(|d| {
            if let Some(file) = d.procfs.as_mut() {
                file.set_guest_numbers(numbers);
            }
        })
    }

    /// Initialize the deterministic snapshot shared by all aliases.
    // TODO-HUMAN-REVIEW(PR-723): Review procfs snapshot identity parameters.
    // TODO-HUMAN-REVIEW(PR-955): Review deterministic UUID snapshot input.
    pub(crate) fn initialize_procfs(&self, contents: Vec<u8>, context: ProcfsSnapshotContext) {
        self.with_description(|d| {
            d.procfs
                .as_mut()
                .expect("procfs fd disappeared while taking its snapshot")
                .initialize(contents, context)
        });
    }

    /// Preview the snapshot bytes at its shared offset, with that offset,
    /// without consuming them.
    pub(crate) fn preview_procfs(&self, maximum: usize) -> Option<(usize, Vec<u8>)> {
        self.with_description(|description| {
            let procfs = description.procfs.as_ref()?;
            let (offset, _) = procfs.position();
            procfs.take_at(offset, maximum).map(|bytes| (offset, bytes))
        })
    }

    /// Advance the shared offset by the bytes a read copied to the guest.
    pub(crate) fn commit_procfs_read(&self, offset: usize, copied: usize) {
        self.with_description(|d| {
            d.procfs
                .as_mut()
                .expect("procfs fd disappeared while committing a read")
                .commit_read(offset, copied)
        });
    }

    /// Read a deterministic procfs snapshot without changing its shared cursor.
    pub(crate) fn take_procfs_at(&self, offset: usize, maximum: usize) -> Option<Vec<u8>> {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .and_then(|procfs| procfs.take_at(offset, maximum))
        })
    }

    /// Namespace-visible task id and stable proc inode bound at open time.
    pub(crate) fn procfs_timer_slack_binding(&self) -> Option<(i32, u64, u64)> {
        self.with_description(|d| d.procfs.as_ref().and_then(ProcfsFile::timer_slack_binding))
    }

    /// Preview bytes without consuming the snapshot shared by dup/fork aliases.
    pub(crate) fn preview_procfs_timer_slack(
        &self,
        value: u64,
        maximum: usize,
    ) -> Option<TimerSlackReadPreview> {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .and_then(|procfs| procfs.preview_timer_slack(value, maximum))
        })
    }

    /// Commit bytes only after their guest-memory copy succeeds.
    pub(crate) fn commit_procfs_timer_slack_read(
        &self,
        preview: &TimerSlackReadPreview,
        copied: usize,
    ) {
        self.with_description(|d| {
            d.procfs
                .as_mut()
                .expect("timer-slack procfs state disappeared")
                .commit_timer_slack_read(preview, copied)
        });
    }

    /// Read a fresh timer-slack value at an explicit offset.
    pub(crate) fn take_procfs_timer_slack_at(
        &self,
        value: u64,
        offset: usize,
        maximum: usize,
    ) -> Option<Vec<u8>> {
        self.with_description(|d| {
            d.procfs
                .as_ref()
                .and_then(|procfs| procfs.take_timer_slack_at(value, offset, maximum))
        })
    }

    /// The lock serializing `getdents` and `lseek` on this open file
    /// description across every alias of it. For a shared description it
    /// covers only this process's aliases: the lock protects unsequentialized
    /// threads, and a description is shared only where threads are
    /// sequentialized.
    pub(crate) fn directory_lock(&self) -> Arc<futures::lock::Mutex<()>> {
        match &*self.open_file.lock().expect("open file mutex poisoned") {
            OpenFileState::Local(description) => Arc::clone(&description.directory_lock),
            OpenFileState::Shared(shared) => Arc::clone(&shared.directory_lock),
        }
    }

    /// Whether a `getdents` call has created a directory stream here. Only a
    /// successful read of the host directory creates one, so this also proves
    /// the open file is a directory.
    pub(crate) fn has_directory_stream(&self) -> bool {
        self.with_description(|d| d.directory.is_some())
    }

    /// Whether `getdents` on this open file reads the host directory one
    /// kernel buffer at a time instead of from a sorted stream.
    pub(crate) fn directory_in_host_order(&self) -> bool {
        self.with_description(|d| d.directory_host_order)
    }

    /// Read this open file's directory one kernel buffer at a time until it
    /// is seeked back to 0: its position was moved before the first
    /// `getdents`, or a read of the host directory after the first failed, so
    /// no snapshot of the whole directory could be taken. A guest buffer too
    /// small for the next entry does not land here: the stream answers it
    /// with `EINVAL`, as Linux does. Any stream is dropped, so `lseek`
    /// reaches the kernel again.
    pub(crate) fn use_host_directory_order(&self) {
        self.with_description(|description| {
            description.directory_host_order = true;
            description.directory = None;
        })
    }

    /// Serve this open file's directory as a sorted stream again, from its
    /// next `getdents`: its kernel position is back at 0.
    pub(crate) fn use_directory_stream(&self) {
        self.with_description(|d| d.directory_host_order = false);
    }

    /// Whether the next `getdents` must read the host directory.
    pub(crate) fn directory_needs_snapshot(&self) -> bool {
        self.with_description(|d| {
            d.directory
                .as_ref()
                .is_none_or(DirectoryStream::needs_snapshot)
        })
    }

    /// Install a snapshot freshly read in host order, creating the stream at
    /// position 0 if this is the open file's first `getdents`.
    ///
    /// `mark` is the inode pool's state read just before the host directory
    /// was (see `SnapshotMark`), and `inodes` how to key the inode numbers of
    /// its entries, decided then too.
    pub(crate) fn install_directory_snapshot(
        &self,
        entries: Vec<DirEntry>,
        mark: SnapshotMark,
        inodes: DirectoryInodes,
        order: DirectoryOrder,
    ) {
        self.with_description(|d| {
            let stream = d.directory.get_or_insert_with(DirectoryStream::default);
            stream.install(entries, order);
            stream.note_snapshot_mark(mark);
            stream.note_snapshot_inodes(inodes);
        });
    }

    /// Run `f` on the directory stream shared by every alias of this open file.
    /// `EBADF` if there is none: under `--no-sequentialize-threads`, another
    /// thread can close or replace the descriptor after its caller found one.
    pub(crate) fn with_directory_stream<R>(
        &self,
        f: impl FnOnce(&mut DirectoryStream) -> R,
    ) -> Result<R, Errno> {
        self.with_description(|d| d.directory.as_mut().map(f).ok_or(Errno::EBADF))
    }

    /// Return the shared procfs cursor and initialized snapshot length.
    pub(crate) fn procfs_position(&self) -> Option<(usize, Option<usize>)> {
        self.with_description(|d| d.procfs.as_ref().map(ProcfsFile::position))
    }

    pub(crate) fn procfs_target_fd(&self) -> Option<i32> {
        self.with_description(|d| d.procfs.as_ref().and_then(ProcfsFile::target_fd))
    }

    /// Move the cursor shared by every alias of a procfs open file as the
    /// guest's `lseek` does (`ProcfsFile::seek_to`).
    pub(crate) fn seek_procfs(&self, offset: usize) {
        self.with_description(|d| {
            d.procfs
                .as_mut()
                .expect("procfs fd disappeared while seeking it")
                .seek_to(offset)
        });
    }

    /// Update the cursor shared by every alias of a procfs open file.
    pub(crate) fn set_procfs_offset(&self, offset: usize) {
        self.with_description(|d| {
            d.procfs
                .as_mut()
                .expect("procfs fd disappeared while updating its offset")
                .set_offset(offset)
        });
    }

    /// Cached stat data attached to the backing object.
    pub fn stat(&self) -> Option<DetStat> {
        self.with_description(|d| d.stat)
    }

    /// Whether Detcore has made the open file description physically nonblocking.
    pub fn physically_nonblocking(&self) -> bool {
        self.with_description(|d| d.physically_nonblocking)
    }

    pub(crate) fn status_flags(&self) -> i32 {
        self.with_description(|d| d.status_flags)
    }

    /// Mark every alias of this open file description physically nonblocking.
    pub fn set_physically_nonblocking(&self) {
        self.with_description(|d| d.physically_nonblocking = true);
    }

    /// Whether this is a FIFO that may still become an internally polled pipe
    /// (see `OpenFileDescription::fifo_awaiting_guest_peer`).
    pub(crate) fn fifo_awaiting_guest_peer(&self) -> bool {
        self.with_description(|d| d.fifo_awaiting_guest_peer)
    }

    /// Mark a `Regular` FIFO as one that may become an internally polled pipe.
    pub(crate) fn mark_fifo_awaiting_guest_peer(&self) {
        self.with_description(|d| {
            debug_assert_eq!(d.ty, FdType::Regular);
            d.fifo_awaiting_guest_peer = true;
        });
    }

    /// The FIFO is now physically nonblocking (Detcore set `O_NONBLOCK`, here
    /// or through another process sharing the open file description): treat
    /// it from now on as a scheduler-managed pipe, as `pipe2` creates.
    pub(crate) fn fifo_joins_internal_polling(&self) {
        self.with_description(|d| {
            debug_assert!(d.fifo_awaiting_guest_peer);
            d.fifo_awaiting_guest_peer = false;
            d.ty = FdType::Pipe;
            d.physically_nonblocking = true;
        });
    }

    /// Update file status flags for every alias of this open file description.
    pub fn set_status_flags(&self, flags: i32) {
        self.with_description(|description| {
            // F_SETFL cannot change how this description was opened. Access
            // checks must retain these bits even when an alias passes only
            // O_NONBLOCK (whose access-mode bits happen to spell O_RDONLY).
            let mutable = (OFlag::O_APPEND
                | OFlag::O_ASYNC
                | OFlag::O_DIRECT
                | OFlag::O_NOATIME
                | OFlag::O_NONBLOCK)
                .bits();
            description.status_flags = (description.status_flags & !mutable) | (flags & mutable);
            description.physically_nonblocking = oflags_nonblocking(description.status_flags);
        })
    }

    // TODO-HUMAN-REVIEW(PR-912): Review open-file sharing of socket receive timestamps.
    /// Record the logical time at which a socket delivered its most recent packet.
    pub(crate) fn set_socket_receive_timestamp(&self, timestamp: LogicalTime) {
        self.with_description(|d| d.socket_receive_timestamp = Some(timestamp));
    }

    /// Return the last receive timestamp shared by every alias of this socket.
    pub(crate) fn socket_receive_timestamp(&self) -> Option<LogicalTime> {
        self.with_description(|d| d.socket_receive_timestamp)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1064)
    /// Mark this open file as a `NETLINK_SOCK_DIAG` socket. Shared across every
    /// dup/fork alias of the same open file description.
    pub(crate) fn set_sock_diag(&self) {
        self.with_description(|d| d.sock_diag = true);
    }

    // TODO-HUMAN-REVIEW(PR-1064)
    /// Whether this open file is a `NETLINK_SOCK_DIAG` socket whose dump replies
    /// must have their socket inode numbers determinized.
    pub(crate) fn is_sock_diag(&self) -> bool {
        self.with_description(|d| d.sock_diag)
    }

    /// Mark this open file as a `NETLINK_ROUTE` socket. Like `set_sock_diag`
    /// this applies to the open file description, so a dup or fork alias of the
    /// same socket is covered too.
    pub(crate) fn set_netlink_route(&self) {
        self.with_description(|d| d.netlink_route = true);
    }

    /// Whether this open file is a `NETLINK_ROUTE` socket whose link-dump
    /// replies carry live interface counters.
    pub(crate) fn is_netlink_route(&self) -> bool {
        self.with_description(|d| d.netlink_route)
    }

    /// Update whether this open file is connected to a loopback peer.
    pub(crate) fn set_loopback_peer(&self, loopback_peer: bool) {
        self.with_description(|d| d.loopback_peer = loopback_peer);
    }

    /// Whether this open file is a socket connected to a loopback peer.
    pub(crate) fn is_loopback_peer(&self) -> bool {
        self.with_description(|d| d.loopback_peer)
    }

    /// Mark this open file as an external network trace channel.
    pub(crate) fn set_network_channel(&self) {
        self.with_description(|d| d.network_channel = true);
    }

    /// Whether this open file is an external network trace channel.
    pub(crate) fn is_network_channel(&self) -> bool {
        self.with_description(|d| d.network_channel)
    }

    /// Record the socket's `SO_RCVLOWAT`.
    pub(crate) fn set_network_lowat(&self, lowat: usize) {
        self.with_description(|d| d.network_lowat = Some(lowat));
    }

    /// The socket's `SO_RCVLOWAT`.
    pub(crate) fn network_lowat(&self) -> usize {
        self.with_description(|d| d.network_lowat.unwrap_or(1))
    }

    /// Record the socket's family and type for the network trace.
    pub(crate) fn set_network_socket(&self, kind: NetworkSocketKind) {
        self.with_description(|d| d.network_socket = kind);
    }

    /// The socket's family and type as the network trace classified it.
    pub(crate) fn network_socket(&self) -> NetworkSocketKind {
        self.with_description(|d| d.network_socket)
    }

    /// Mark this open file as one end of a `socketpair(2)`. Like
    /// `set_netlink_route` this applies to the open file description, so a dup
    /// or fork alias of the same endpoint is covered too -- which is the case
    /// that matters, since the usual way to use a socketpair is to fork and let
    /// each side inherit one end.
    pub(crate) fn set_socketpair_endpoint(&self) {
        self.with_description(|d| d.socketpair_endpoint = true);
    }

    /// Whether this open file is one end of a `socketpair(2)`, and therefore
    /// container-internal.
    pub(crate) fn is_socketpair_endpoint(&self) -> bool {
        self.with_description(|d| d.socketpair_endpoint)
    }

    /// Mark this open file as a connection returned by `accept(2)` or
    /// `accept4(2)`. It applies to the open file description, so dup and fork
    /// aliases are covered too.
    pub(crate) fn set_accepted_connection(&self) {
        self.with_description(|d| d.accepted_connection = true);
    }

    /// Whether `accept(2)` or `accept4(2)` returned this open file.
    pub(crate) fn is_accepted_connection(&self) -> bool {
        self.with_description(|d| d.accepted_connection)
    }

    /// Mark this open file as a listener whose blocking `accept(2)` runs in
    /// the caller's turn under record/replay. It applies to the open file
    /// description, so dup and fork aliases are covered too.
    pub(crate) fn set_accept_in_turn_eligible(&self) {
        self.with_description(|d| d.accept_in_turn_eligible = true);
    }

    /// Whether a blocking `accept(2)` on this open file runs in the caller's
    /// turn: it was marked eligible and has not been exported.
    pub(crate) fn is_accept_in_turn_listener(&self) -> bool {
        self.with_description(|d| d.accept_in_turn_eligible && !d.exported)
    }

    /// Whether this open file was marked eligible, exported or not.
    pub(crate) fn is_accept_in_turn_eligible(&self) -> bool {
        self.with_description(|d| d.accept_in_turn_eligible)
    }

    /// Mark this open file description's locks as followed by
    /// `procfs::locks::LockLedger`. Permanent.
    pub(crate) fn set_lock_tracked(&self) {
        self.with_description(|d| d.lock_tracked = true);
    }

    /// Whether `procfs::locks::LockLedger` follows this description's locks.
    pub(crate) fn is_lock_tracked(&self) -> bool {
        self.with_description(|d| d.lock_tracked)
    }

    /// Mark this description as registered on reception over `SCM_RIGHTS`.
    /// Permanent.
    pub(crate) fn set_received_for_locks(&self) {
        self.with_description(|d| d.received_for_locks = true);
    }

    /// Whether this description was registered on reception over
    /// `SCM_RIGHTS`.
    pub(crate) fn is_received_for_locks(&self) -> bool {
        self.with_description(|d| d.received_for_locks)
    }

    /// Mark this description as one that may hold an OFD lock. Permanent.
    pub(crate) fn set_may_hold_ofd_lock(&self) {
        self.with_description(|d| d.may_hold_ofd_lock = true);
    }

    /// Whether this description may hold an OFD lock.
    pub(crate) fn may_hold_ofd_lock(&self) -> bool {
        self.with_description(|d| d.may_hold_ofd_lock)
    }

    /// Mark this open file as passed over `SCM_RIGHTS`. Permanent.
    pub(crate) fn set_exported(&self) {
        self.with_description(|d| d.exported = true);
    }

    /// Whether this open file was passed over `SCM_RIGHTS`.
    pub(crate) fn is_exported(&self) -> bool {
        self.with_description(|d| d.exported)
    }

    /// Record the receive timeout a successful `setsockopt(SO_RCVTIMEO)` set.
    pub(crate) fn set_receive_timeout(&self, timeout: ReceiveTimeout) {
        self.with_description(|d| d.receive_timeout = timeout);
    }

    /// The receive timeout `setsockopt(SO_RCVTIMEO)` calls set through any
    /// descriptor Detcore tracks for this open file description, dup, fork and
    /// exec aliases included. A copy that reached a guest some other way, which
    /// Detcore tracks as a description of its own, does not update it; record
    /// checks the model against the kernel before a blocking accept relies on
    /// it.
    pub(crate) fn receive_timeout(&self) -> ReceiveTimeout {
        self.with_description(|d| d.receive_timeout)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#2373)
    /// Return the known `flock(2)` state for this open file description.
    ///
    /// The outer `None` means Detcore did not observe the descriptor's history.
    /// `Some(None)` means known-unlocked; `Some(Some(mode))` means the kernel
    /// granted `LOCK_SH` or `LOCK_EX` through this handler.
    pub(crate) fn known_flock_mode(&self) -> Option<Option<i32>> {
        self.with_description(|description| {
            description
                .flock_mode_known
                .then_some(description.flock_mode)
        })
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#2373)
    /// Record the `flock(2)` mode this open file description now holds. Every
    /// `dup`/`fork` alias observes the change, matching the kernel, where one
    /// `flock` lock belongs to the whole open file description.
    pub(crate) fn set_flock_mode(&self, mode: Option<i32>) {
        self.with_description(|description| {
            if description.flock_mode_known {
                description.flock_mode = mode;
            }
        })
    }

    /// Mark the kernel lock state unknown without changing the kernel lock.
    /// This is required for live-discovered and externally received file
    /// descriptions, whose history Detcore did not observe.
    pub(crate) fn forget_flock_mode(&self) {
        self.with_description(|description| {
            description.flock_mode = None;
            description.flock_mode_known = false;
        })
    }

    /// Record that Detcore never observed this description's lock history, as
    /// opposed to having known it and then invalidated it. Used for descriptors
    /// that existed before Detcore began observing the guest.
    pub(crate) fn mark_flock_mode_unobserved(&self) {
        self.forget_flock_mode();
        self.with_description(|description| {
            description.flock_mode_ever_known = false;
        })
    }

    /// True when a cached lock claim existed and may now be wrong.
    pub(crate) fn flock_mode_may_be_stale(&self) -> bool {
        self.with_description(|description| {
            description.flock_mode_ever_known && !description.flock_mode_known
        })
    }
}

impl fmt::Display for DetFd {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "DetFd({})", self.fd)
    }
}

/// Restores descriptor aliasing after deserialization: every descriptor with
/// the same `OpenFileId` refers to one open file description object again.
///
/// Serialization writes an `Arc`'s contents, not its identity, so two
/// descriptors that shared one description (after `dup`) come back as two
/// independent copies, and a read through one would no longer move the
/// other's cursor. Within one table an `OpenFileId` names exactly one open
/// file description, so the copies with one id are identical, and the first
/// (lowest descriptor number) is kept. Descriptor flags (`FD_CLOEXEC`) stay
/// per descriptor.
pub(crate) fn intern_open_files(handles: &mut std::collections::HashMap<RawFd, DetFd>) {
    let mut fds: Vec<RawFd> = handles.keys().copied().collect();
    fds.sort_unstable();
    let mut first: std::collections::HashMap<OpenFileId, DetFd> = std::collections::HashMap::new();
    for fd in fds {
        let detfd = handles.get_mut(&fd).expect("listed descriptor");
        match first.get(&detfd.open_file_id()) {
            Some(kept) => detfd.share_open_file_with(kept),
            None => {
                first.insert(detfd.open_file_id(), detfd.clone());
            }
        }
    }
}

impl DetFd {
    /// A copy of this local description's model, for tests of the global
    /// store.
    #[cfg(test)]
    pub(crate) fn model_for_test(&self) -> OpenFileModel {
        self.with_description(|d| {
            OpenFileModel(serde_json::from_value(serde_json::to_value(&*d).unwrap()).unwrap())
        })
    }

    /// Moves this open file description's model out to a test's canonical
    /// store and makes every alias a shared handle, keeping this process's
    /// directory lock. Production promotion uses the acknowledged lease protocol.
    #[cfg(test)]
    fn share_for_test(&self) -> OpenFileModel {
        let mut state = self.open_file.lock().expect("open file mutex poisoned");
        let OpenFileState::Local(description) = &*state else {
            panic!("open file description is already shared");
        };
        let shared = SharedOpenFile {
            id: description.id,
            directory_lock: Arc::clone(&description.directory_lock),
        };
        let OpenFileState::Local(description) =
            std::mem::replace(&mut *state, OpenFileState::Shared(shared))
        else {
            unreachable!("checked above");
        };
        OpenFileModel(description)
    }
}

#[cfg(test)]
pub(crate) fn install_test_shared_open_file_channel() {
    let _ = tests::MemoryChannel::installed();
}

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

    #[test]
    fn native_exec_directory_lease_probe_preserves_idle_stream_and_aliases() {
        use crate::native_exec::NativeExecCutError;

        let id = OpenFileId::new(DetTid::from_raw(42), 7);
        let fd = DetFd::new(30, OFlag::O_DIRECTORY, FdType::Regular, id);
        let alias = fd.clone().with_fd(31);
        fd.install_directory_snapshot(
            vec![
                DirEntry {
                    name: b"b".to_vec(),
                    ino: 19,
                    off: 41,
                    ty: libc::DT_REG,
                },
                DirEntry {
                    name: b"a".to_vec(),
                    ino: 17,
                    off: 43,
                    ty: libc::DT_REG,
                },
            ],
            SnapshotMark {
                retirements: 3,
                threads_counted: 7,
            },
            DirectoryInodes::new(11, None),
            DirectoryOrder::NameBytes,
        );
        alias
            .with_directory_stream(|stream| stream.advance(1))
            .unwrap();
        let before = serde_json::to_value(&fd).unwrap();
        assert_eq!(
            fd.validate_native_exec_runtime_state().unwrap(),
            alias.validate_native_exec_runtime_state().unwrap()
        );
        assert_eq!(serde_json::to_value(&fd).unwrap(), before);
        let lock = alias.directory_lock();
        let lease = lock.try_lock().unwrap();
        assert_eq!(
            fd.validate_native_exec_runtime_state(),
            Err(NativeExecCutError::LiveCapability("directory lease"))
        );
        assert!(
            lock.try_lock().is_none(),
            "validation must not release the owned lease"
        );
        drop(lease);
        assert_eq!(serde_json::to_value(&fd).unwrap(), before);
        assert_eq!(
            fd.with_directory_stream(|stream| stream.position())
                .unwrap(),
            1
        );
        let guard = fd.open_file.lock().unwrap();
        assert_eq!(
            alias.validate_native_exec_runtime_state(),
            Err(NativeExecCutError::LockUnavailable("open_file"))
        );
        drop(guard);
        fd.validate_native_exec_runtime_state().unwrap();
    }

    #[test]
    fn native_exec_shared_descriptor_probe_never_takes_canonical_model() {
        let id = OpenFileId::new(DetTid::from_raw(42), 9);
        let fd = DetFd::new(30, OFlag::empty(), FdType::Rng, id);
        fd.advance_random_device_offset(37);
        let model = fd.share_for_test();
        let alias = fd.clone().with_fd(31);
        // Do not install a channel. with_description on this handle would
        // need one; a local runtime probe must not touch canonical state.
        assert_eq!(
            fd.validate_native_exec_runtime_state().unwrap(),
            alias.validate_native_exec_runtime_state().unwrap()
        );
        assert_eq!(model.0.random_device_offset, 37);
        let lock = alias.directory_lock();
        let lease = lock.try_lock().unwrap();
        assert_eq!(
            fd.validate_native_exec_runtime_state(),
            Err(crate::native_exec::NativeExecCutError::LiveCapability(
                "directory lease"
            ))
        );
        drop(lease);
        assert_eq!(model.0.random_device_offset, 37);
    }

    #[test]
    fn random_access_modes_survive_status_updates_through_aliases() {
        for mode in [
            OFlag::O_RDONLY,
            OFlag::O_WRONLY,
            OFlag::O_RDWR,
            OFlag::O_ACCMODE,
            OFlag::O_PATH,
        ] {
            let original = DetFd::new(
                3,
                mode,
                FdType::Rng,
                OpenFileId::new(DetTid::from_raw(1), 0),
            );
            let alias = original.clone().with_fd(4);
            for update in [
                OFlag::O_NONBLOCK,
                OFlag::O_RDWR,
                OFlag::O_WRONLY,
                OFlag::O_PATH | OFlag::O_NONBLOCK,
            ] {
                alias.set_status_flags(update.bits());
                assert_eq!(
                    original.status_flags() & (OFlag::O_ACCMODE | OFlag::O_PATH).bits(),
                    mode.bits()
                );
                assert_eq!(
                    original.is_nonblocking(),
                    update.contains(OFlag::O_NONBLOCK)
                );
            }
        }
    }

    #[test]
    fn random_status_updates_preserve_immutable_flags_and_replace_mutable_flags() {
        let immutable = OFlag::O_RDWR | OFlag::O_SYNC;
        let original = DetFd::new(
            3,
            immutable | OFlag::O_APPEND | OFlag::O_NONBLOCK,
            FdType::Rng,
            OpenFileId::new(DetTid::from_raw(1), 0),
        );
        let alias = original.clone().with_fd(4);
        alias.set_status_flags((OFlag::O_WRONLY | OFlag::O_ASYNC | OFlag::O_NOATIME).bits());
        assert_eq!(
            original.status_flags(),
            (immutable | OFlag::O_ASYNC | OFlag::O_NOATIME).bits()
        );
        assert!(!original.physically_nonblocking());
        alias.set_status_flags(OFlag::O_NONBLOCK.bits());
        assert_eq!(
            original.status_flags(),
            (immutable | OFlag::O_NONBLOCK).bits()
        );
        assert!(original.physically_nonblocking());
    }

    #[test]
    fn dup_shares_open_file_state_but_not_slot_flags() {
        let owner = DetTid::from_raw(10);
        let original = DetFd::new(
            3,
            OFlag::O_NONBLOCK,
            FdType::Socket,
            OpenFileId::new(owner, 0),
        );
        let duplicate = original.clone().with_fd(4).with_fd_flags(OFlag::O_CLOEXEC);

        assert_eq!(original.open_file_id(), duplicate.open_file_id());
        assert!(
            !original.is_cloexec(),
            "dup must not alter the source fd flags"
        );
        assert!(
            duplicate.is_cloexec(),
            "dup3(O_CLOEXEC) applies to the new slot"
        );
        assert!(
            duplicate.is_nonblocking(),
            "dup must preserve shared status flags"
        );

        duplicate.set_status_flags(OFlag::empty().bits());
        assert!(
            !original.is_nonblocking(),
            "status flag changes through one alias must be visible through every alias"
        );

        let timestamp = LogicalTime::from_nanos(2_345_678_901);
        original.set_socket_receive_timestamp(timestamp);
        assert_eq!(duplicate.socket_receive_timestamp(), Some(timestamp));

        assert!(!original.is_sock_diag());
        original.set_sock_diag();
        assert!(
            duplicate.is_sock_diag(),
            "sock_diag marking through one alias must be visible through every alias"
        );

        assert!(!original.is_loopback_peer());
        duplicate.set_loopback_peer(true);
        assert!(
            original.is_loopback_peer(),
            "loopback-peer marking through one alias must be visible through every alias"
        );
        original.set_loopback_peer(false);
        assert!(
            !duplicate.is_loopback_peer(),
            "reconnects through one alias must clear loopback state for every alias"
        );
    }

    /// `flock(2)` locks belong to the open file description, so every `dup`
    /// alias must see one lock, while a separate `open` of the same file is a
    /// distinct contender with its own state.
    #[test]
    fn flock_mode_is_shared_by_dup_aliases_and_private_to_separate_opens() {
        let owner = DetTid::from_raw(10);
        let original = DetFd::new(
            3,
            OFlag::empty(),
            FdType::Regular,
            OpenFileId::new(owner, 0),
        );
        let duplicate = original.clone().with_fd(4);
        let separate_open = DetFd::new(
            5,
            OFlag::empty(),
            FdType::Regular,
            OpenFileId::new(owner, 1),
        );

        assert_eq!(original.known_flock_mode(), Some(None));
        original.set_flock_mode(Some(libc::LOCK_SH));
        assert_eq!(
            duplicate.known_flock_mode(),
            Some(Some(libc::LOCK_SH)),
            "a dup alias shares the open file description's flock lock"
        );
        assert_eq!(
            separate_open.known_flock_mode(),
            Some(None),
            "a separate open of the same file is an independent flock contender"
        );

        duplicate.set_flock_mode(Some(libc::LOCK_EX));
        assert_eq!(original.known_flock_mode(), Some(Some(libc::LOCK_EX)));
        duplicate.set_flock_mode(None);
        assert_eq!(
            original.known_flock_mode(),
            Some(None),
            "LOCK_UN through one alias releases the whole open file description"
        );

        duplicate.forget_flock_mode();
        assert_eq!(
            original.known_flock_mode(),
            None,
            "unknown state must be shared by every alias of the open file description"
        );
        original.set_flock_mode(Some(libc::LOCK_SH));
        assert_eq!(
            duplicate.known_flock_mode(),
            None,
            "a later call cannot make externally mutable lock state reliable again"
        );
    }

    #[test]
    fn pidfd_target_is_shared_by_descriptor_aliases() {
        let target = DetPid::from_raw(41);
        let original = DetFd::new(
            3,
            OFlag::O_CLOEXEC,
            FdType::Pidfd,
            OpenFileId::new(DetTid::from_raw(7), 0),
        );
        let duplicate = original.clone().with_fd(4);

        assert_eq!(original.pidfd_target(), None);
        original.set_pidfd_target(target);
        assert_eq!(original.pidfd_target(), Some(target));
        assert_eq!(duplicate.pidfd_target(), Some(target));
    }

    #[test]
    fn toggling_logical_nonblocking_preserves_physical() {
        // Models FIONBIO on an fd that Detcore forced physically nonblocking for
        // the scheduler: the guest-visible flag changes, but the physical state
        // must survive.
        let owner = DetTid::from_raw(10);
        let fd = DetFd::new(3, OFlag::empty(), FdType::Socket, OpenFileId::new(owner, 0));
        fd.set_physically_nonblocking();
        fd.set_logical_nonblocking(true);
        assert!(fd.is_nonblocking());
        assert!(fd.physically_nonblocking());

        fd.set_logical_nonblocking(false);
        assert!(
            !fd.is_nonblocking(),
            "the guest must observe O_NONBLOCK cleared"
        );
        assert!(
            fd.physically_nonblocking(),
            "the scheduler's physical nonblocking state must be preserved"
        );

        fd.set_logical_nonblocking(true);
        assert!(fd.is_nonblocking());
        assert!(
            fd.physically_nonblocking(),
            "setting the logical flag must not discard physical tracking"
        );

        // The both-flags setter still tracks physical alongside logical.
        fd.set_nonblocking(false);
        assert!(!fd.is_nonblocking());
        assert!(!fd.physically_nonblocking());
    }

    #[test]
    fn procfs_offsets_are_shared_by_dup_aliases() {
        let owner = DetTid::from_raw(10);
        let original = DetFd::new(
            3,
            OFlag::empty(),
            FdType::Regular,
            OpenFileId::new(owner, 0),
        );
        // A `seq_file` file, which serves reads at any position.
        original.set_procfs(ProcfsFile::from_path(Path::new("/proc/version")).unwrap());
        original.initialize_procfs(
            Vec::new(),
            ProcfsSnapshotContext {
                virtual_pid: 1,
                ..ProcfsSnapshotContext::default()
            },
        );
        let duplicate = original.clone().with_fd(4);

        assert_eq!(original.preview_procfs(2).unwrap(), (0, b"Li".to_vec()));
        assert_eq!(duplicate.procfs_position().unwrap().0, 0);
        original.commit_procfs_read(0, 2);
        assert_eq!(duplicate.procfs_position().unwrap().0, 2);
        assert_eq!(duplicate.take_procfs_at(4, 1).unwrap(), b"x");
        assert_eq!(original.procfs_position().unwrap().0, 2);

        // A read that copied nothing leaves the shared cursor in place.
        let (offset, _) = duplicate.preview_procfs(4).unwrap();
        duplicate.commit_procfs_read(offset, 0);
        assert_eq!(original.procfs_position().unwrap().0, 2);

        duplicate.set_procfs_offset(0);
        assert_eq!(
            original.preview_procfs(128).unwrap(),
            (
                0,
                crate::procfs::FixedProcfsFile::Version
                    .contents(&crate::machine::MachineDescription::default())
            )
        );
    }

    #[test]
    fn random_device_offsets_are_shared_by_dup_aliases() {
        let owner = DetTid::from_raw(10);
        let original = DetFd::new(3, OFlag::empty(), FdType::Rng, OpenFileId::new(owner, 0));
        let duplicate = original.clone().with_fd(4);

        assert_eq!(original.random_device_offset(), 0);
        duplicate.advance_random_device_offset(50);
        assert_eq!(original.random_device_offset(), 50);
    }

    #[test]
    fn random_device_stream_commits_returned_prefix_for_dup_aliases() {
        let owner = DetTid::from_raw(10);
        let id = OpenFileId::new(owner, 0);
        let original = DetFd::new(3, OFlag::empty(), FdType::Rng, id);
        let duplicate = original.clone().with_fd(4);
        original.advance_random_device_offset(7);

        assert_eq!(
            duplicate.with_random_device_stream(|offset| {
                assert_eq!(offset, 7);
                // A copy requesting eight bytes completed only this prefix.
                Ok::<_, ()>(3)
            }),
            Ok(3)
        );
        assert_eq!(original.random_device_offset(), 10);
        assert_eq!(duplicate.random_device_offset(), 10);
        assert_eq!(
            original.with_random_device_stream(|offset| {
                assert_eq!(offset, 10);
                Ok::<_, ()>(2)
            }),
            Ok(2)
        );
        assert_eq!(original.random_device_offset(), 12);
        assert_eq!(duplicate.random_device_offset(), 12);
        assert_eq!(original.open_file_id(), id);
        assert_eq!(duplicate.open_file_id(), id);
        assert!(Arc::ptr_eq(&original.open_file, &duplicate.open_file));
    }

    #[test]
    fn random_device_stream_preserves_error_identity_and_cursor() {
        let owner = DetTid::from_raw(10);
        let original = DetFd::new(3, OFlag::empty(), FdType::Rng, OpenFileId::new(owner, 0));
        let duplicate = original.clone().with_fd(4);
        original.advance_random_device_offset(11);
        let failure = Arc::new(String::from("copy failure"));

        let error = duplicate
            .with_random_device_stream(|offset| {
                assert_eq!(offset, 11);
                Err(Arc::clone(&failure))
            })
            .unwrap_err();
        assert!(Arc::ptr_eq(&error, &failure));
        assert_eq!(original.random_device_offset(), 11);
        assert_eq!(duplicate.random_device_offset(), 11);
        assert_eq!(original.open_file_id(), duplicate.open_file_id());
    }

    #[test]
    fn random_device_stream_saturates_independently_of_partitioning() {
        let owner = DetTid::from_raw(10);
        for initial in [u64::MAX - 2, u64::MAX] {
            let whole = DetFd::new(3, OFlag::empty(), FdType::Rng, OpenFileId::new(owner, 0));
            let split = DetFd::new(4, OFlag::empty(), FdType::Rng, OpenFileId::new(owner, 1));
            whole.with_description(|d| d.random_device_offset = initial);
            split.with_description(|d| d.random_device_offset = initial);

            assert_eq!(
                whole.with_random_device_stream(|offset| {
                    assert_eq!(offset, initial);
                    Ok::<_, ()>(4)
                }),
                Ok(4)
            );
            assert_eq!(whole.random_device_offset(), u64::MAX);
            assert_eq!(
                split.with_random_device_stream(|offset| {
                    assert_eq!(offset, initial);
                    Ok::<_, ()>(1)
                }),
                Ok(1)
            );
            assert_eq!(split.random_device_offset(), initial.saturating_add(1));
            assert_eq!(
                split.with_random_device_stream(|offset| {
                    assert_eq!(offset, initial.saturating_add(1));
                    Ok::<_, ()>(3)
                }),
                Ok(3)
            );
            assert_eq!(split.random_device_offset(), u64::MAX);
        }
    }

    #[test]
    fn random_device_stream_holds_alias_lock_while_copying() {
        let owner = DetTid::from_raw(10);
        let original = DetFd::new(3, OFlag::empty(), FdType::Rng, OpenFileId::new(owner, 0));
        let duplicate = original.clone().with_fd(4);

        assert_eq!(
            original.with_random_device_stream(|offset| {
                assert_eq!(offset, 0);
                // A nonblocking attempt cannot deadlock the copy, and observes
                // whether another thread could access the shared cursor here.
                assert!(
                    std::thread::spawn(move || {
                        matches!(
                            duplicate.open_file.try_lock(),
                            Err(std::sync::TryLockError::WouldBlock)
                        )
                    })
                    .join()
                    .unwrap()
                );
                Ok::<_, ()>(5)
            }),
            Ok(5)
        );
        assert_eq!(original.random_device_offset(), 5);
    }

    /// A path argument whose conversion checks that no alias's description
    /// lock is held while it converts.
    struct PathProbe {
        alias: DetFd,
    }

    impl AsRef<Path> for PathProbe {
        fn as_ref(&self) -> &Path {
            assert!(
                self.alias.open_file.try_lock().is_ok(),
                "an argument conversion ran under the description lock"
            );
            Path::new("/probe")
        }
    }

    #[test]
    fn argument_conversions_run_before_the_description_lock() {
        let original = DetFd::new(
            3,
            OFlag::O_RDONLY,
            FdType::Regular,
            OpenFileId::new(DetTid::from_raw(11), 0),
        );
        let alias = original.clone().with_fd(4);
        original.set_path(PathProbe {
            alias: alias.clone(),
        });
        let original = original.with_path(PathProbe {
            alias: alias.clone(),
        });
        assert_eq!(alias.path(), Some(PathBuf::from("/probe")));
        drop(original);
    }

    #[test]
    fn separate_opens_have_distinct_identity() {
        let owner = DetTid::from_raw(10);
        let first = DetFd::new(
            3,
            OFlag::empty(),
            FdType::Regular,
            OpenFileId::new(owner, 0),
        );
        let second = DetFd::new(
            4,
            OFlag::empty(),
            FdType::Regular,
            OpenFileId::new(owner, 1),
        );

        assert_ne!(first.open_file_id(), second.open_file_id());
    }

    /// The canonical store of the tests' shared open file descriptions, and
    /// the channel installed for this test process. Each test uses its own
    /// creator task, so tests running in parallel never share a description.
    #[derive(Default)]
    pub(super) struct MemoryChannel {
        store: Mutex<std::collections::HashMap<OpenFileId, Canonical>>,
    }

    struct Canonical {
        /// `None` while a lease holds the model.
        model: Option<OpenFileModel>,
        sequence: u64,
        takes: usize,
    }

    struct InstalledMemoryChannel(&'static MemoryChannel);

    impl SharedOpenFileChannel for InstalledMemoryChannel {
        fn promote(&self, model: &OpenFileModel) -> Result<(), SharedOpenFileError> {
            let mut store = self.0.store.lock().unwrap();
            if store.contains_key(&model.id()) {
                return Err(SharedOpenFileError("duplicate test promotion".into()));
            }
            let copied = serde_json::from_value(serde_json::to_value(model).unwrap()).unwrap();
            store.insert(
                model.id(),
                Canonical {
                    model: Some(copied),
                    sequence: 0,
                    takes: 0,
                },
            );
            Ok(())
        }

        fn take(&self, id: OpenFileId) -> Result<OpenFileLease, SharedOpenFileError> {
            let mut store = self.0.store.lock().unwrap();
            let canonical = store
                .get_mut(&id)
                .ok_or_else(|| SharedOpenFileError(format!("{id:?} is not shared")))?;
            let model = canonical
                .model
                .take()
                .ok_or_else(|| SharedOpenFileError(format!("{id:?} is already leased")))?;
            canonical.sequence += 1;
            canonical.takes += 1;
            Ok(OpenFileLease {
                id,
                sequence: canonical.sequence,
                model,
            })
        }

        fn publish(&self, lease: OpenFileLease) -> Result<(), SharedOpenFileError> {
            let mut store = self.0.store.lock().unwrap();
            let canonical = store
                .get_mut(&lease.id)
                .ok_or_else(|| SharedOpenFileError(format!("{:?} is not shared", lease.id)))?;
            if canonical.model.is_some() || canonical.sequence != lease.sequence {
                return Err(SharedOpenFileError(format!(
                    "{:?}: publish names no current lease",
                    lease.id
                )));
            }
            canonical.model = Some(lease.model);
            Ok(())
        }
    }

    impl MemoryChannel {
        pub(super) fn installed() -> &'static MemoryChannel {
            static CHANNEL: OnceLock<MemoryChannel> = OnceLock::new();
            let channel = CHANNEL.get_or_init(MemoryChannel::default);
            // Only the first installation is kept, and it is this channel.
            let _ = install_shared_open_file_channel(Box::new(InstalledMemoryChannel(channel)));
            channel
        }

        fn share(&self, detfd: &DetFd) {
            let model = detfd.share_for_test();
            let previous = self.store.lock().unwrap().insert(
                model.0.id,
                Canonical {
                    model: Some(model),
                    sequence: 0,
                    takes: 0,
                },
            );
            assert!(previous.is_none());
        }

        fn takes(&self, id: OpenFileId) -> usize {
            self.store.lock().unwrap()[&id].takes
        }

        /// Runs `f` on the canonical model, which must not be leased.
        fn canonical<R>(&self, id: OpenFileId, f: impl FnOnce(&OpenFileDescription) -> R) -> R {
            let store = self.store.lock().unwrap();
            f(&store[&id]
                .model
                .as_ref()
                .expect("a lease outlived its method call")
                .0)
        }
    }

    #[test]
    fn a_shared_handle_reaches_the_canonical_model_through_every_alias() {
        let channel = MemoryChannel::installed();
        let id = OpenFileId::new(DetTid::from_raw(9001), 0);
        let original = DetFd::new(3, OFlag::O_RDWR, FdType::Regular, id);
        let alias = original.clone().with_fd(4);
        // A clone that escaped the descriptor table before the promotion.
        let escaped = original.clone();
        channel.share(&original);

        alias.set_status_flags(OFlag::O_NONBLOCK.bits());
        assert_eq!(channel.takes(id), 1);
        assert!(channel.canonical(id, |model| oflags_nonblocking(model.status_flags)));
        assert!(original.is_nonblocking());
        assert!(escaped.is_nonblocking());
        assert_eq!(
            escaped.status_flags() & OFlag::O_ACCMODE.bits(),
            OFlag::O_RDWR.bits()
        );
        assert_eq!(channel.takes(id), 4);
        assert_eq!(original.open_file_alias_count(), 3);
    }

    #[test]
    fn promoted_fork_handles_keep_one_cursor_without_pregrant_access() {
        let channel = MemoryChannel::installed();
        let id = OpenFileId::new(DetTid::from_raw(9010), 0);
        let parent = DetFd::new(3, OFlag::O_RDONLY, FdType::Rng, id);
        let alias = parent.clone().with_fd(4).with_fd_flags(OFlag::O_CLOEXEC);
        parent
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 0);
                Ok(7)
            })
            .unwrap();
        parent.set_flock_mode(Some(libc::LOCK_SH));
        parent.promote().unwrap();
        alias.promote().unwrap(); // The escaped alias does not publish twice.
        let takes = channel.takes(id);
        let lock = parent.directory_lock();
        let held = lock.try_lock().unwrap();
        let child = alias.fork_shared_handle();
        child.forget_local_flock_mode_at_fork();
        assert_eq!(
            channel.takes(id),
            takes,
            "child metadata construction must be RPC-free"
        );
        assert!(child.directory_lock().try_lock().is_some());
        assert!(child.is_cloexec());
        assert_eq!(child.known_flock_mode(), Some(Some(libc::LOCK_SH)));
        child
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 7);
                Ok(5)
            })
            .unwrap();
        parent
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 12);
                Ok(3)
            })
            .unwrap();
        assert_eq!(
            child.with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 15);
                Err(Errno::EFAULT)
            }),
            Err(Errno::EFAULT)
        );
        child.set_flock_mode(None);
        assert_eq!(parent.known_flock_mode(), Some(None));
        drop(child);
        let successor = DetFd::shared_survivor(3, id);
        successor
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 15);
                Ok(0)
            })
            .unwrap();
        let reopened = DetFd::new(
            3,
            OFlag::O_RDONLY,
            FdType::Rng,
            OpenFileId::new(DetTid::from_raw(9010), 1),
        );
        reopened.promote().unwrap();
        reopened
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 0);
                Ok(1)
            })
            .unwrap();
        successor
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 15);
                Ok(0)
            })
            .unwrap();
        drop(held);
    }

    #[test]
    fn identity_and_directory_lock_never_take_the_shared_model() {
        let channel = MemoryChannel::installed();
        let id = OpenFileId::new(DetTid::from_raw(9002), 0);
        let original = DetFd::new(3, OFlag::O_RDONLY, FdType::Regular, id);
        let local_lock = original.directory_lock();
        channel.share(&original);

        assert_eq!(original.open_file_id(), id);
        assert!(Arc::ptr_eq(&original.directory_lock(), &local_lock));
        assert!(Arc::ptr_eq(
            &original.clone().with_fd(4).directory_lock(),
            &local_lock
        ));
        assert_eq!(channel.takes(id), 0);
    }

    #[test]
    fn a_shared_handle_serializes_only_its_identity() {
        let channel = MemoryChannel::installed();
        let id = OpenFileId::new(DetTid::from_raw(9003), 0);
        let original = DetFd::new(3, OFlag::O_RDONLY, FdType::Regular, id).with_path("/a");
        channel.share(&original);

        let encoded = serde_json::to_string(&original).unwrap();
        assert!(encoded.contains("Shared"), "{encoded}");
        assert!(!encoded.contains("status_flags"), "{encoded}");
        assert!(!encoded.contains("/a"), "{encoded}");
        assert_eq!(channel.takes(id), 0);

        // A restored table interns its shared handles by identity, as it
        // does local ones, without taking the model.
        let mut handles = std::collections::HashMap::new();
        for fd in [3, 4] {
            let restored: DetFd = serde_json::from_str(&encoded).unwrap();
            handles.insert(fd, restored.with_fd(fd));
        }
        intern_open_files(&mut handles);
        assert_eq!(handles[&4].open_file_alias_count(), 2);
        assert_eq!(channel.takes(id), 0);
        assert_eq!(handles[&4].path(), Some(PathBuf::from("/a")));
        assert_eq!(channel.takes(id), 1);
    }

    #[test]
    fn a_failed_random_device_copy_still_ends_the_lease() {
        let channel = MemoryChannel::installed();
        let id = OpenFileId::new(DetTid::from_raw(9004), 0);
        let original = DetFd::new(3, OFlag::empty(), FdType::Rng, id);
        channel.share(&original);

        assert_eq!(
            original.with_random_device_stream(|_| Err::<usize, _>(())),
            Err(())
        );
        assert_eq!(channel.canonical(id, |model| model.random_device_offset), 0);
        assert_eq!(
            original.with_random_device_stream(|offset| {
                assert_eq!(offset, 0);
                Ok::<_, ()>(5)
            }),
            Ok(5)
        );
        assert_eq!(channel.canonical(id, |model| model.random_device_offset), 5);
        assert_eq!(channel.takes(id), 2);
    }

    fn at(ns: u64) -> LogicalTime {
        LogicalTime::from_nanos(ns)
    }

    /// A one-shot timerfd counts one expiration once virtual time reaches its
    /// deadline, then disarms; before the deadline it counts none.
    #[test]
    fn a_one_shot_timerfd_expires_once_at_its_virtual_deadline() {
        let mut timer = VirtualTimerfd::set(Some(at(1_000)), 0);
        assert_eq!(timer.expire_through(at(999)), 0);
        assert_eq!(timer.remaining(at(999)), (1, 0));
        assert_eq!(timer.expire_through(at(1_000)), 1);
        assert_eq!(
            timer,
            VirtualTimerfd {
                deadline: None,
                interval_ns: 0,
                unread: 1
            }
        );
        assert_eq!(timer.expire_through(at(5_000)), 0);
        assert_eq!(timer.remaining(at(5_000)), (0, 0));
    }

    /// A periodic timerfd observed late counts every expiration it missed,
    /// exactly, and its next deadline stays on the original grid: the count
    /// is a function of virtual time, not of how often it was observed.
    #[test]
    fn a_periodic_timerfd_counts_every_missed_expiration_on_its_grid() {
        let mut once = VirtualTimerfd::set(Some(at(1_000)), 300);
        assert_eq!(once.expire_through(at(1_950)), 4);
        assert_eq!(once.deadline, Some(at(2_200)));
        assert_eq!(once.remaining(at(1_950)), (250, 300));

        let mut often = VirtualTimerfd::set(Some(at(1_000)), 300);
        let mut added = 0;
        for now in [1_000, 1_100, 1_300, 1_599, 1_950] {
            added += often.expire_through(at(now));
        }
        assert_eq!(added, 4);
        assert_eq!(often, once);
    }

    /// A timer disarmed with a zero value keeps its interval for
    /// `timerfd_gettime`, as Linux does, and never expires.
    #[test]
    fn a_disarmed_timerfd_keeps_its_interval_and_never_expires() {
        let mut timer = VirtualTimerfd::set(None, 300);
        assert_eq!(timer.expire_through(at(u64::MAX / 2)), 0);
        assert_eq!(timer.remaining(at(5)), (0, 300));
        assert_eq!(timer.unread, 0);
    }

    /// Setting a timerfd discards its unread expirations, as Linux does.
    #[test]
    fn setting_a_timerfd_discards_unread_expirations() {
        let mut timer = VirtualTimerfd::set(Some(at(10)), 0);
        timer.expire_through(at(20));
        assert_eq!(timer.unread, 1);
        assert_eq!(VirtualTimerfd::set(None, 0).unread, 0);
    }
}