sandlock-core 0.8.5

Lightweight process sandbox using Landlock, seccomp-bpf, and seccomp user notification
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
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
// Seccomp user notification supervisor — async event loop that receives
// notifications from the kernel, dispatches them to handler functions, and
// sends responses.

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::io;
use std::net::IpAddr;
use std::os::unix::io::{AsRawFd, OwnedFd, RawFd};
use std::pin::Pin;
use std::sync::Arc;

use crate::error::NotifError;
use crate::arch;
use crate::sys::structs::{
    SeccompNotif, SeccompNotifAddfd, SeccompNotifResp,
    SECCOMP_ADDFD_FLAG_SEND, SECCOMP_IOCTL_NOTIF_ADDFD, SECCOMP_IOCTL_NOTIF_ID_VALID, SECCOMP_IOCTL_NOTIF_RECV,
    SECCOMP_IOCTL_NOTIF_SEND, SECCOMP_IOCTL_NOTIF_SET_FLAGS,
    SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP, SECCOMP_USER_NOTIF_FLAG_CONTINUE,
    ENOMEM,
};

// ============================================================
// NotifAction — how the supervisor should respond
// ============================================================

/// A one-shot callback invoked with the child-side fd number returned by
/// `SECCOMP_IOCTL_NOTIF_ADDFD` after a successful `InjectFdSendTracked`.
/// Wraps a boxed closure with a manual `Debug` impl so that `NotifAction`
/// can keep deriving `Debug`.  The closure is both `Send` and `Sync` so
/// that `&NotifAction` remains `Send` (required because `NotifAction` is
/// borrowed across `.await` points in the notifier loop).
pub struct OnInjectSuccess(pub Box<dyn FnOnce(i32) + Send + Sync>);

impl std::fmt::Debug for OnInjectSuccess {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("OnInjectSuccess(<callback>)")
    }
}

impl OnInjectSuccess {
    pub fn new<F: FnOnce(i32) + Send + Sync + 'static>(f: F) -> Self {
        Self(Box::new(f))
    }
}

/// A deferred decision: an owned, `'static` future that produces the real
/// [`NotifAction`] off the supervisor's notification loop.
///
/// A handler returns [`NotifAction::Defer`] when computing the response is
/// slow (a network round-trip, a blocking syscall) and must not stall the
/// single supervisor task that gates every other trapped syscall.  The
/// supervisor moves the future onto a worker, lets the loop proceed, and
/// sends the response (via the still-valid `notif.id`) when the future
/// resolves.  The future is `'static` because it outlives the borrowed
/// `HandlerCtx` — capture what you need (`notif` is `Copy`, `notif_fd` is a
/// `RawFd`) by value rather than borrowing `&self`.
///
/// The deferred future need only be `Send` (not `Sync`): the supervisor
/// moves it onto a worker task and never shares it by reference.  Requiring
/// `Sync` of user futures would be a leaky bound (it would reject a future
/// capturing, say, a `Cell`), so it is not required.
pub struct Deferred(Pin<Box<dyn Future<Output = NotifAction> + Send + 'static>>);

// Safety: `NotifAction` must stay `Sync` so it can live in `Sync` contexts
// (handler `&self` state, etc.; the `Handler` trait is `Send + Sync`), which
// requires `Deferred: Sync`.  A `Send`-only future is not `Sync`, but the
// boxed future is unreachable through a shared `&Deferred`: the field is
// private, `Debug` touches only a static string, and `run(self)` consumes
// the value (it is never callable through `&self`).  With no path to poll or
// read the future via a shared reference, sharing `&Deferred` across threads
// cannot race, so asserting `Sync` is sound while keeping user futures
// `Send`-only.
unsafe impl Sync for Deferred {}

impl std::fmt::Debug for Deferred {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Deferred(<future>)")
    }
}

impl Deferred {
    pub fn new<F: Future<Output = NotifAction> + Send + 'static>(f: F) -> Self {
        Self(Box::pin(f))
    }

    /// Drive the deferred future to its terminal action.  Consumes `self`
    /// because the future is run exactly once, on a worker task.
    pub async fn run(self) -> NotifAction {
        self.0.await
    }
}

/// How the supervisor should respond to a notification.
#[derive(Debug)]
pub enum NotifAction {
    /// SECCOMP_USER_NOTIF_FLAG_CONTINUE — let the syscall proceed.
    Continue,
    /// Return -1 with the given errno.
    Errno(i32),
    /// Inject a file descriptor into the child, then continue.
    InjectFd { srcfd: RawFd, targetfd: i32 },
    /// Inject a file descriptor using SECCOMP_ADDFD_FLAG_SEND (atomically responds).
    /// The child sees the injected fd as the return value of the syscall.
    /// The `OwnedFd` is closed automatically after the ioctl completes.
    /// `newfd_flags` controls flags on the injected fd (e.g. O_CLOEXEC).
    InjectFdSend { srcfd: OwnedFd, newfd_flags: u32 },
    /// Like `InjectFdSend`, but also invokes `on_success` with the
    /// child-side fd number that `SECCOMP_IOCTL_NOTIF_ADDFD` returned.
    /// Used when the caller needs to track the exact fd number allocated
    /// in the child (e.g. to key per-fd state without TOCTOU).
    InjectFdSendTracked {
        srcfd: OwnedFd,
        newfd_flags: u32,
        on_success: OnInjectSuccess,
    },
    /// Synthetic return value (the child sees this as the syscall result).
    ReturnValue(i64),
    /// Don't respond — used for checkpoint/freeze.
    Hold,
    /// Kill the child process group (OOM-kill semantics).
    /// Fields: signal, process group leader pid.
    Kill { sig: i32, pgid: i32 },
    /// Defer the response: run the carried future on a worker task and
    /// send its terminal action later, keyed by `notif.id`.  Non-`Continue`,
    /// so it short-circuits the handler chain — a deferring handler makes a
    /// terminal decision.  See [`Deferred`].
    Defer(Deferred),
}

impl NotifAction {
    /// Construct a [`NotifAction::Defer`] from a `'static` future.  Ergonomic
    /// shorthand for `NotifAction::Defer(Deferred::new(fut))`.
    pub fn defer<F: Future<Output = NotifAction> + Send + 'static>(fut: F) -> Self {
        NotifAction::Defer(Deferred::new(fut))
    }

    /// Inject `content` into the child as the syscall's returned fd, backed by
    /// a sealed (read-only, fixed-size), `O_CLOEXEC` in-memory file.
    ///
    /// The fd is created, populated, sealed, and owned end to end by sandlock;
    /// the caller never sees or closes it. On allocation failure this collapses
    /// to `Errno(EIO)`, so a handler can return it directly:
    ///
    /// ```ignore
    /// return NotifAction::inject_bytes(&secret);
    /// ```
    ///
    /// For a *writable* injected fd, build one with
    /// [`content_memfd(content, false)`](content_memfd) and pass it to
    /// [`NotifAction::InjectFdSend`] yourself.
    pub fn inject_bytes(content: &[u8]) -> NotifAction {
        match content_memfd(content, true) {
            Ok(fd) => NotifAction::InjectFdSend {
                srcfd: fd,
                newfd_flags: libc::O_CLOEXEC as u32,
            },
            Err(_) => NotifAction::Errno(libc::EIO),
        }
    }
}

/// Create an anonymous in-memory file ("memfd") populated with `content` and
/// rewound to offset 0, ready to inject as a syscall's returned fd via
/// [`NotifAction::InjectFdSend`].
///
/// When `seal` is true the fd is sealed read-only and fixed-size
/// (`F_SEAL_SEAL | F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK`) so the guest
/// cannot modify or resize the content it is handed. Sealing is best-effort:
/// on a kernel without sealing support the fd is still returned, bounded by
/// the rest of the policy. Pass `false` only when the guest genuinely needs a
/// writable injected fd.
///
/// Most callers want [`NotifAction::inject_bytes`], which wraps this in the
/// common sealed + `O_CLOEXEC` configuration.
pub fn content_memfd(content: &[u8], seal: bool) -> io::Result<OwnedFd> {
    use std::io::{Seek, SeekFrom, Write};
    use std::os::unix::io::FromRawFd;

    let flags = if seal {
        (libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING) as u32
    } else {
        libc::MFD_CLOEXEC as u32
    };
    let memfd = crate::sys::syscall::memfd_create("sandlock-content", flags)?;

    // Write the content and rewind. Borrow the raw fd for File I/O without
    // transferring ownership: `memfd` (the OwnedFd) keeps owning it.
    {
        let raw = memfd.as_raw_fd();
        let mut file = unsafe { std::fs::File::from_raw_fd(raw) };
        let res = file
            .write_all(content)
            .and_then(|()| file.seek(SeekFrom::Start(0)).map(|_| ()));
        std::mem::forget(file); // don't close `raw`; `memfd` still owns it
        res?;
    }

    if seal {
        // Best-effort: ignore failure on kernels lacking sealing support.
        let seals =
            libc::F_SEAL_SEAL | libc::F_SEAL_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK;
        unsafe { libc::fcntl(memfd.as_raw_fd(), libc::F_ADD_SEALS, seals) };
    }

    Ok(memfd)
}

/// Collapse a deferred future's resolved action into a sendable terminal
/// action.  A deferred future that itself resolves to `Defer` is a bug
/// (no nested deferral); collapse it to `EIO` so the trapped child gets a
/// definite response instead of wedging forever waiting for one.
fn finalize_deferred(action: NotifAction) -> NotifAction {
    match action {
        NotifAction::Defer(_) => NotifAction::Errno(libc::EIO),
        other => other,
    }
}

// ============================================================
// NetworkPolicy — network access policy enum
// ============================================================

/// Per-IP port allowlist. `Any` is used by `policy_fn` IP-only
/// overrides (legacy `restrict_network(ips)` API where the user
/// restricts the destination IP set but not ports).
#[derive(Debug, Clone)]
pub enum PortAllow {
    /// Any port permitted to this IP.
    Any,
    /// Only these ports permitted to this IP.
    Specific(HashSet<u16>),
}

/// Global network policy for the sandbox.
#[derive(Debug, Clone)]
pub enum NetworkPolicy {
    /// No IP-level restriction for this protocol. On the on-behalf path this
    /// is only ever reached *with* a destination policy active (e.g. a `*:*` /
    /// `:*` allow-all-ports rule), so here it means "allow any destination."
    /// The empty-`net_allow` deny-all case never reaches this arm: with no
    /// destination policy the connect is returned to the kernel and Landlock's
    /// `CONNECT_TCP` deny-all governs it.
    Unrestricted,
    /// Endpoint-level allowlist: a connection is permitted iff the
    /// destination IP and port match at least one entry below.
    AllowList {
        /// Per-IP port rules. From `--net-allow host:ports` after
        /// hostname resolution, or from `policy_fn` overrides.
        per_ip: HashMap<IpAddr, PortAllow>,
        /// (network, allowed-ports) rules from `--net-allow` IP/CIDR
        /// targets, matched by containment with no DNS. `PortAllow::Any`
        /// permits every port to the range.
        cidrs: Vec<(crate::network::IpCidr, PortAllow)>,
        /// Ports permitted for any IP (from `--net-allow :port` /
        /// `*:port`).
        any_ip_ports: HashSet<u16>,
    },
    /// Default-allow denylist: a connection is permitted unless the
    /// destination IP/port matches a deny rule. From `--net-deny`.
    DenyList {
        /// (network, denied-ports) rules. `PortAllow::Any` denies every
        /// port to the network; `Specific` denies only those ports.
        cidrs: Vec<(crate::network::IpCidr, PortAllow)>,
        /// Ports denied for any IP (the `:port` form).
        any_ip_ports: HashSet<u16>,
        /// Deny everything (the `:*` / `*:*` form). Rare; here for
        /// completeness so the form is not silently a no-op.
        deny_all: bool,
    },
}

impl NetworkPolicy {
    /// True iff a connection to (ip, port) should be permitted.
    pub fn allows(&self, ip: IpAddr, port: u16) -> bool {
        // `::ffff:a.b.c.d` is the same destination as `a.b.c.d` (a
        // dual-stack socket reaches it over IPv4), and CIDR matching is
        // family-exact: match rules against the canonical form so the
        // mapped spelling can't bypass a v4 rule.
        let ip = ip.to_canonical();
        match self {
            NetworkPolicy::Unrestricted => true,
            NetworkPolicy::AllowList { per_ip, cidrs, any_ip_ports } => {
                if any_ip_ports.contains(&port) {
                    return true;
                }
                match per_ip.get(&ip) {
                    Some(PortAllow::Any) => return true,
                    Some(PortAllow::Specific(s)) if s.contains(&port) => return true,
                    _ => {}
                }
                for (net, allowed) in cidrs {
                    if net.contains(ip) {
                        match allowed {
                            PortAllow::Any => return true,
                            PortAllow::Specific(s) => {
                                if s.contains(&port) {
                                    return true;
                                }
                            }
                        }
                    }
                }
                false
            }
            NetworkPolicy::DenyList { cidrs, any_ip_ports, deny_all } => {
                if *deny_all {
                    return false;
                }
                if any_ip_ports.contains(&port) {
                    return false;
                }
                for (net, denied) in cidrs {
                    if net.contains(ip) {
                        match denied {
                            PortAllow::Any => return false,
                            PortAllow::Specific(s) => {
                                if s.contains(&port) {
                                    return false;
                                }
                            }
                        }
                    }
                }
                true
            }
        }
    }
}

/// Check if a path-bearing notification targets a denied path.
///
/// For two-path syscalls (renameat2, linkat), checks both source and
/// destination paths — a denied file must not be linked, renamed, or
/// overwritten.
///
/// Each resolved path is checked both as-is (lexical normalization) and
/// after following symlinks via `canonicalize`.  This prevents bypass via
/// pre-existing symlinks, relative symlinks, or symlink chains that
/// ultimately resolve to a denied path.
pub(crate) fn is_path_denied_for_notif(
    policy_fn_state: &super::state::PolicyFnState,
    notif: &SeccompNotif,
    notif_fd: RawFd,
) -> bool {
    if let Some(path) = resolve_path_for_notif(notif, notif_fd) {
        if is_denied_with_symlink_resolve(policy_fn_state, &path) {
            return true;
        }
    }
    // For two-path syscalls, also check the second (destination) path.
    if let Some(path) = resolve_second_path_for_notif(notif, notif_fd) {
        if is_denied_with_symlink_resolve(policy_fn_state, &path) {
            return true;
        }
    }
    false
}

/// Check a path against denied entries, also resolving symlinks.
///
/// First checks the lexical path, then `canonicalize`s to follow symlinks
/// and checks the real path.  This catches pre-existing symlinks, relative
/// symlinks, and symlink chains that resolve to a denied file.
fn is_denied_with_symlink_resolve(
    policy_fn_state: &super::state::PolicyFnState,
    path: &str,
) -> bool {
    // Check the literal (lexically normalized) path first.
    if policy_fn_state.is_path_denied(path) {
        return true;
    }
    // Follow symlinks and re-check against denied entries.
    if let Ok(real) = std::fs::canonicalize(path) {
        if policy_fn_state.is_path_denied(&real.to_string_lossy()) {
            return true;
        }
        // Identity check: catches a denied file reached via a hardlink or a
        // pre-existing alias, where the resolved path itself is not denied
        // but the file identity is. Best-effort here (path-based precheck);
        // the race-free authority is the fd identity check in the on-behalf
        // open.
        if let Some(id) = super::state::file_id_of_path(&real.to_string_lossy()) {
            if policy_fn_state.is_id_denied(&id) {
                return true;
            }
        }
    }
    false
}

/// `RESOLVE_NO_MAGICLINKS` — forbid `/proc` magic-link redirection during
/// on-behalf resolution while still following ordinary symlinks the way the
/// child's own open would.
const RESOLVE_NO_MAGICLINKS: u64 = 0x02;

/// Kernel `struct open_how` for `openat2`.
#[repr(C)]
struct OpenHow {
    flags: u64,
    mode: u64,
    resolve: u64,
}

fn last_errno(fallback: i32) -> i32 {
    io::Error::last_os_error().raw_os_error().unwrap_or(fallback)
}

/// `openat2` relative to `dirfd`. Returns an owned fd or the errno.
fn openat2_at(dirfd: RawFd, path: &std::ffi::CStr, flags: u64, mode: u64, resolve: u64)
    -> Result<OwnedFd, i32>
{
    use std::os::unix::io::FromRawFd;
    let how = OpenHow { flags, mode, resolve };
    let fd = unsafe {
        libc::syscall(
            arch::SYS_OPENAT2,
            dirfd,
            path.as_ptr(),
            &how as *const OpenHow,
            std::mem::size_of::<OpenHow>(),
        )
    } as i32;
    if fd < 0 {
        Err(last_errno(libc::ENOENT))
    } else {
        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
    }
}

/// Capture an `O_PATH` fd to the directory the child's open resolves against,
/// taken from the child's own view so a concurrent `chdir`/dirfd swap cannot
/// move the resolution base after we read it.
fn open_base_dir(pid: u32, dirfd: i64) -> Result<OwnedFd, i32> {
    use std::os::unix::io::FromRawFd;
    if dirfd as i32 == libc::AT_FDCWD {
        let cwd = std::ffi::CString::new(format!("/proc/{}/cwd", pid)).map_err(|_| libc::EINVAL)?;
        let fd = unsafe {
            libc::open(cwd.as_ptr(), libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC)
        };
        if fd < 0 {
            return Err(last_errno(libc::EACCES));
        }
        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
    } else {
        dup_fd_from_pid(pid, dirfd as i32).map_err(|_| libc::EBADF)
    }
}

/// Real path of an open fd via its `/proc/self/fd` magic link.
fn realpath_of_fd(fd: RawFd) -> Option<std::path::PathBuf> {
    std::fs::read_link(format!("/proc/self/fd/{}", fd)).ok()
}


fn path_under_any(path: &std::path::Path, list: &[std::path::PathBuf]) -> bool {
    list.iter().any(|p| path.starts_with(p))
}

/// Decide whether `realpath` may be opened with `flags` under the deny set
/// and the (conservative) grant lists. Returns `Some(errno)` to refuse,
/// `None` to allow. Never over-allows relative to the configured grants: a
/// path outside every grant is refused, so this can only be stricter than
/// Landlock, never looser (an over-deny is a functional gap, an over-allow
/// would be an escape).
fn deny_open_verdict(
    realpath: &std::path::Path,
    flags: u64,
    policy: &NotifPolicy,
    pfs: &super::state::PolicyFnState,
) -> Option<i32> {
    if pfs.is_path_denied(&realpath.to_string_lossy()) {
        return Some(libc::EACCES);
    }
    let acc = flags as i32 & libc::O_ACCMODE;
    let is_write = acc == libc::O_WRONLY
        || acc == libc::O_RDWR
        || (flags & libc::O_TRUNC as u64) != 0
        || (flags & libc::O_CREAT as u64) != 0;
    let allowed = if is_write {
        path_under_any(realpath, &policy.chroot_writable)
    } else {
        path_under_any(realpath, &policy.chroot_readable)
            || path_under_any(realpath, &policy.chroot_writable)
    };
    if allowed { None } else { Some(libc::EACCES) }
}

/// open/openat/openat2 argument layout, normalized across the spellings.
struct OpenArgs {
    dirfd: i64,
    path_ptr: u64,
    flags: u64,
    mode: u64,
    /// `openat2` `resolve` flags (`RESOLVE_*`); 0 for `open`/`openat`.
    resolve: u64,
}

/// Decode the open arguments. `openat2` carries flags/mode/resolve inside a
/// `struct open_how` in child memory, so its decode reads child memory and
/// can fail; `None` means "could not decode" and the caller soft-falls-through
/// (the kernel's own re-read fails the same way).
fn decode_open_args(notif: &SeccompNotif, notif_fd: RawFd) -> Option<OpenArgs> {
    let a = &notif.data.args;
    let nr = notif.data.nr as i64;
    if nr == libc::SYS_openat {
        Some(OpenArgs { dirfd: a[0] as i64, path_ptr: a[1], flags: a[2], mode: a[3], resolve: 0 })
    } else if nr == arch::SYS_OPENAT2 {
        // openat2(dirfd, pathname, struct open_how *how, size_t size),
        // open_how = { u64 flags, u64 mode, u64 resolve }.
        let how_ptr = a[2];
        let want = (a[3] as usize).min(std::mem::size_of::<OpenHow>());
        if how_ptr == 0 || want < 16 {
            return None; // need at least flags + mode
        }
        let bytes = read_child_mem(notif_fd, notif.id, notif.pid, how_ptr, want).ok()?;
        if bytes.len() < 16 {
            return None;
        }
        let flags = u64::from_ne_bytes(bytes[0..8].try_into().ok()?);
        let mode = u64::from_ne_bytes(bytes[8..16].try_into().ok()?);
        let resolve = if bytes.len() >= 24 {
            u64::from_ne_bytes(bytes[16..24].try_into().ok()?)
        } else {
            0
        };
        Some(OpenArgs { dirfd: a[0] as i64, path_ptr: a[1], flags, mode, resolve })
    } else {
        // legacy open(path, flags, mode) — AT_FDCWD implied.
        Some(OpenArgs { dirfd: libc::AT_FDCWD as i64, path_ptr: a[0], flags: a[1], mode: a[2], resolve: 0 })
    }
}

/// Wrap a freshly opened raw fd into an `InjectFdSend`, honoring the child's
/// `O_CLOEXEC` request. Ownership of `raw_fd` moves into the action.
fn inject_open_result(raw_fd: i32, flags: u64) -> NotifAction {
    use std::os::unix::io::FromRawFd;
    if raw_fd < 0 {
        return NotifAction::Errno(last_errno(libc::EACCES));
    }
    let owned = unsafe { OwnedFd::from_raw_fd(raw_fd) };
    let newfd_flags = if flags & libc::O_CLOEXEC as u64 != 0 {
        libc::O_CLOEXEC as u32
    } else {
        0
    };
    NotifAction::InjectFdSend { srcfd: owned, newfd_flags }
}

/// Existing-file branch: vet the pinned inode behind `probe`, then reopen it
/// race-free via its `/proc/self/fd` magic link with the child's real access
/// mode (binds to the inode, not the original path).
fn reopen_existing_on_behalf(
    probe: OwnedFd,
    flags: u64,
    policy: &NotifPolicy,
    pfs: &super::state::PolicyFnState,
) -> NotifAction {
    // File exists. Refuse O_CREAT|O_EXCL the way the kernel would.
    if (flags & libc::O_CREAT as u64) != 0 && (flags & libc::O_EXCL as u64) != 0 {
        return NotifAction::Errno(libc::EEXIST);
    }
    let realpath = match realpath_of_fd(probe.as_raw_fd()) {
        Some(p) => p,
        None => return NotifAction::Errno(libc::EACCES),
    };
    if let Some(errno) = deny_open_verdict(&realpath, flags, policy, pfs) {
        return NotifAction::Errno(errno);
    }
    // Identity check on the pinned file: a denied file reached via a hardlink,
    // a rename to a non-denied name, or a pre-existing alias has a realpath
    // that is not denied, but its handle identity is. Race-free — this is the
    // exact file the child will receive.
    if let Some(id) = super::state::file_id_of_fd(probe.as_raw_fd()) {
        if pfs.is_id_denied(&id) {
            return NotifAction::Errno(libc::EACCES);
        }
    }
    // Resolution-only flags are stripped from the reopen.
    let reopen_flags =
        flags as i32 & !(libc::O_CREAT | libc::O_EXCL | libc::O_PATH | libc::O_NOFOLLOW);
    let proc_path = match std::ffi::CString::new(format!("/proc/self/fd/{}", probe.as_raw_fd())) {
        Ok(c) => c,
        Err(_) => return NotifAction::Errno(libc::EIO),
    };
    let fd = unsafe { libc::open(proc_path.as_ptr(), reopen_flags) };
    inject_open_result(fd, flags)
}

/// O_CREAT branch: resolve the parent directory race-free, vet the would-be
/// target, then create the leaf inside that pinned parent (the dir inode is
/// fixed, only the leaf name is appended).
fn create_new_on_behalf(
    base: &OwnedFd,
    path: &str,
    flags: u64,
    mode: u64,
    resolve: u64,
    policy: &NotifPolicy,
    pfs: &super::state::PolicyFnState,
) -> NotifAction {
    let p = std::path::Path::new(path);
    let file_name = match p.file_name() {
        Some(f) => f,
        None => return NotifAction::Errno(libc::ENOENT),
    };
    let parent = p.parent().unwrap_or(std::path::Path::new("."));
    let parent_str = match parent.to_str() {
        Some("") | None => ".",
        Some(s) => s,
    };
    let c_parent = match std::ffi::CString::new(parent_str) {
        Ok(c) => c,
        Err(_) => return NotifAction::Errno(libc::EINVAL),
    };
    let parent_fd = match openat2_at(
        base.as_raw_fd(),
        &c_parent,
        (libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) as u64,
        0,
        RESOLVE_NO_MAGICLINKS | resolve,
    ) {
        Ok(f) => f,
        Err(e) => return NotifAction::Errno(e),
    };
    let parent_real = match realpath_of_fd(parent_fd.as_raw_fd()) {
        Some(p) => p,
        None => return NotifAction::Errno(libc::EACCES),
    };
    if let Some(errno) = deny_open_verdict(&parent_real.join(file_name), flags, policy, pfs) {
        return NotifAction::Errno(errno);
    }
    let c_name = match std::ffi::CString::new(file_name.as_encoded_bytes()) {
        Ok(c) => c,
        Err(_) => return NotifAction::Errno(libc::EINVAL),
    };
    let create_flags = flags as i32 & !(libc::O_PATH | libc::O_NOFOLLOW);
    let fd = unsafe { libc::openat(parent_fd.as_raw_fd(), c_name.as_ptr(), create_flags, mode) };
    inject_open_result(fd, flags)
}

/// Perform `openat`/`open` on behalf of the child, race-free, when a deny is
/// active. Resolves once (pinning the inode), enforces deny + grant on the
/// pinned target, then hands the child an fd to that exact inode via
/// `InjectFdSend`. Returns `Continue` only when no allow/deny decision was
/// made on content we resolved (unreadable path / no allowlist configured),
/// matching the precheck's existing soft fall-through.
fn on_behalf_open_for_deny(
    notif: &SeccompNotif,
    policy: &NotifPolicy,
    pfs: &super::state::PolicyFnState,
    notif_fd: RawFd,
) -> NotifAction {
    // No allowlist configured (Landlock is not allowlisting the filesystem):
    // there is no grant to check against, so taking over the open could only
    // wrongly deny. Leave it to the existing precheck/kernel path.
    if policy.chroot_readable.is_empty() && policy.chroot_writable.is_empty() {
        return NotifAction::Continue;
    }

    let OpenArgs { dirfd, path_ptr, flags, mode, resolve } =
        match decode_open_args(notif, notif_fd) {
            Some(a) => a,
            None => return NotifAction::Continue, // kernel's re-read fails the same way
        };

    let path = match read_child_cstr(notif_fd, notif.id, notif.pid, path_ptr, 4096) {
        Some(p) => p,
        None => return NotifAction::Continue, // kernel's re-read fails the same way
    };
    let c_path = match std::ffi::CString::new(path.clone()) {
        Ok(c) => c,
        Err(_) => return NotifAction::Errno(libc::EINVAL),
    };
    let base = match open_base_dir(notif.pid, dirfd) {
        Ok(b) => b,
        Err(e) => return NotifAction::Errno(e),
    };

    // Side-effect-free probe; mirror the child's no-follow intent for the
    // final component and any `openat2` RESOLVE_* flags it requested.
    let probe_flags = (libc::O_PATH | libc::O_CLOEXEC) as u64 | (flags & libc::O_NOFOLLOW as u64);
    match openat2_at(base.as_raw_fd(), &c_path, probe_flags, 0, RESOLVE_NO_MAGICLINKS | resolve) {
        Ok(probe) => reopen_existing_on_behalf(probe, flags, policy, pfs),
        Err(errno) if errno == libc::ENOENT && (flags & libc::O_CREAT as u64) != 0 => {
            create_new_on_behalf(&base, &path, flags, mode, resolve, policy, pfs)
        }
        Err(errno) => NotifAction::Errno(errno),
    }
}

/// Read the thread-group leader (Tgid) of a thread from `/proc/<tid>/status`.
fn tgid_of(tid: u32) -> Option<u32> {
    let status = std::fs::read_to_string(format!("/proc/{}/status", tid)).ok()?;
    status
        .lines()
        .find_map(|l| l.strip_prefix("Tgid:").and_then(|r| r.trim().parse().ok()))
}

/// Duplicate a file descriptor from an arbitrary process (by PID/TID) into the supervisor.
///
/// `pidfd_getfd` (Linux 5.6+) needs a pidfd for the owning *process*. All threads
/// of a process share one fd table, so the process's pidfd dups any thread's fd:
/// `pidfd_open(pid, 0)` gives it directly when `pid` is a thread-group leader,
/// otherwise we resolve the leader via `Tgid` in `/proc/<pid>/status` and open
/// that. The triggering thread is frozen on the seccomp notification, so its
/// Tgid cannot race with pid reuse. Works on any kernel with `pidfd_getfd`.
pub(crate) fn dup_fd_from_pid(pid: u32, target_fd: i32) -> io::Result<OwnedFd> {
    use crate::sys::syscall::{pidfd_getfd, pidfd_open};
    let pidfd = pidfd_open(pid, 0).or_else(|e| match tgid_of(pid) {
        Some(tgid) if tgid != pid => pidfd_open(tgid, 0),
        _ => Err(e),
    })?;
    pidfd_getfd(&pidfd, target_fd, 0)
}

// ============================================================
// NotifPolicy — policy for the notification supervisor
// ============================================================

/// Policy for the notification supervisor.
pub struct NotifPolicy {
    pub max_memory_bytes: u64,
    pub max_processes: u32,
    pub has_memory_limit: bool,
    /// A **network destination policy** is active: a `net_allow` allowlist, a
    /// `net_deny` denylist, an HTTP ACL, or a live `policy_fn` (i.e.
    /// `network_destination_policy`). Despite the historical singular framing
    /// this is *not* only an allowlist. When set, the on-behalf path is the
    /// IP-level enforcer for connect/sendto/sendmsg and those handlers must
    /// never `Continue`; when clear, the syscalls are trapped only to gate
    /// named `AF_UNIX` sockets and IP destinations are returned to the kernel
    /// so Landlock/BPF govern them.
    pub has_net_destination_policy: bool,
    /// `--net-deny-bind` is active: trap `bind()` and register the on-behalf
    /// handler so denied TCP ports can be refused (independent of the
    /// connect-side `has_net_destination_policy`).
    pub has_bind_denylist: bool,
    /// Named (pathname) `AF_UNIX` connect gate. When true, `connect()` to a
    /// named unix socket whose path is not covered by an fs-write grant is
    /// denied with EACCES. Landlock has no access right for unix-socket
    /// connect, so the seccomp layer closes the escape; abstract sockets are
    /// handled by `LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET` instead.
    pub has_unix_fs_gate: bool,
    pub has_random_seed: bool,
    pub has_time_start: bool,
    /// Argv-safety gate: the supervisor must freeze every task that
    /// could mutate argv before any consumer reads it. True when
    /// `policy_fn` is active or when a handler is bound to
    /// execve/execveat (such handlers can call `read_child_mem`).
    /// Also gates ptrace fork-event tracking so `ProcessIndex` is
    /// complete when the freeze enumerates it.
    pub argv_safety_required: bool,
    pub time_offset: i64,
    pub num_cpus: Option<u32>,
    pub port_remap: bool,
    pub cow_enabled: bool,
    pub chroot_root: Option<std::path::PathBuf>,
    /// Virtual paths allowed for reading under chroot (original user-specified paths).
    pub chroot_readable: Vec<std::path::PathBuf>,
    /// Virtual paths allowed for writing under chroot (original user-specified paths).
    pub chroot_writable: Vec<std::path::PathBuf>,
    /// Virtual paths explicitly denied under chroot.
    pub chroot_denied: Vec<std::path::PathBuf>,
    /// Mount mappings: (virtual_path, host_path) pairs.
    pub chroot_mounts: Vec<(std::path::PathBuf, std::path::PathBuf)>,
    /// Virtual paths of mounts that are read-only: writes are denied even
    /// though the path is mounted (and therefore readable). Used for the host
    /// procfs mount and OCI `ro` bind mounts so a writable rootfs cannot make
    /// e.g. `/proc/sys/*` writable.
    pub chroot_mount_ro: Vec<std::path::PathBuf>,
    pub deterministic_dirs: bool,
    pub virtual_hostname: Option<String>,
    pub has_http_acl: bool,
    /// Synthetic `/etc/hosts` served to the sandbox. Always populated:
    /// `openat("/etc/hosts")` returns a memfd with this content so the
    /// host's on-disk `/etc/hosts` never leaks in. The content is the
    /// loopback base plus any concrete hostnames resolved from `net_allow`.
    pub virtual_etc_hosts: String,
    /// User-declared trust-bundle paths to splice the MITM CA into.
    pub ca_inject_paths: Vec<std::path::PathBuf>,
    /// Active MITM CA public cert (PEM bytes) to inject. `Some` only when
    /// HTTPS MITM is active (BYO or generated).
    pub ca_inject_pem: Option<std::sync::Arc<Vec<u8>>>,
}

impl NotifPolicy {
    /// Whether an IP-family `connect()` must be handled on-behalf by the
    /// supervisor, given the destination's loopback-ness.
    ///
    /// This is the connect-side form of the invariant the `sendto`/`sendmsg`
    /// handlers already follow: with [`Self::has_net_destination_policy`] the
    /// on-behalf path is the IP-level enforcer and must never `Continue`;
    /// without it there is nothing to enforce and the syscall is returned to
    /// the kernel. `connect()` adds one wrinkle over datagram sends —
    /// `port_remap` rewrites the destination, but only for **loopback** — so
    /// that is the sole extra reason to supervise an otherwise-unpoliced IP
    /// connect. When this returns `false`, the connect was trapped purely to
    /// gate named `AF_UNIX` sockets, and deferring to the kernel lets the
    /// child's own Landlock `CONNECT_TCP` rules govern it (deny-all for an
    /// empty `net_allow`); handling it on-behalf would run it in the
    /// unconfined supervisor and bypass that decision.
    pub(crate) fn ip_connect_supervised(&self, dest_is_loopback: bool) -> bool {
        self.has_net_destination_policy || (self.port_remap && dest_is_loopback)
    }
}

// ============================================================
// Low-level ioctl helpers
// ============================================================

/// Receive a seccomp notification from the kernel.
/// ioctl(fd, SECCOMP_IOCTL_NOTIF_RECV, &notif)
fn recv_notif(fd: RawFd) -> io::Result<SeccompNotif> {
    let mut notif: SeccompNotif = unsafe { std::mem::zeroed() };
    let ret = unsafe {
        libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_RECV as libc::c_ulong, &mut notif as *mut _)
    };
    if ret < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(notif)
    }
}

/// Result of a non-blocking probe on the seccomp notif fd.
enum NotifFdState {
    /// At least one INIT-state notification is queued. `recv_notif`
    /// will return without blocking.
    Pending,
    /// No notifications and no terminal flags. Wait for the next
    /// epoll edge before probing again.
    Empty,
    /// `POLLHUP`/`POLLERR`/`POLLNVAL` set, or `poll(2)` itself failed:
    /// filter has been released or the fd is invalid. The supervisor
    /// should exit; subsequent waits would busy-spin because epoll
    /// keeps reporting the fd ready.
    Terminal,
}

/// Non-blocking probe of the seccomp notif fd.
///
/// `SECCOMP_IOCTL_NOTIF_RECV` ignores `O_NONBLOCK` and calls
/// `wait_event_interruptible` unconditionally (kernel/seccomp.c
/// `seccomp_notify_recv`). So `recv_notif` cannot be invoked
/// speculatively to detect an empty queue. This helper uses
/// `poll(timeout=0)` as a non-blocking predictor: if POLLIN is set
/// the kernel will hand us a notification without blocking; if a
/// terminal flag is set the fd will keep waking AsyncFd until the
/// supervisor exits.
fn probe_notif_fd(fd: RawFd) -> NotifFdState {
    let mut pfd = libc::pollfd {
        fd,
        events: libc::POLLIN,
        revents: 0,
    };
    let r = unsafe { libc::poll(&mut pfd, 1, 0) };
    if r > 0 && (pfd.revents & libc::POLLIN) != 0 {
        return NotifFdState::Pending;
    }
    if r < 0 || (pfd.revents & (libc::POLLHUP | libc::POLLERR | libc::POLLNVAL)) != 0 {
        return NotifFdState::Terminal;
    }
    NotifFdState::Empty
}

/// Send a response with SECCOMP_USER_NOTIF_FLAG_CONTINUE.
fn respond_continue(fd: RawFd, id: u64) -> io::Result<()> {
    let resp = SeccompNotifResp {
        id,
        val: 0,
        error: 0,
        flags: SECCOMP_USER_NOTIF_FLAG_CONTINUE,
    };
    send_resp_raw(fd, &resp)
}

/// Send a response that returns -1 with the given errno.
fn respond_errno(fd: RawFd, id: u64, errno: i32) -> io::Result<()> {
    let resp = SeccompNotifResp {
        id,
        val: 0,
        error: -errno,
        flags: 0,
    };
    send_resp_raw(fd, &resp)
}

/// Send a response with a synthetic return value.
fn respond_value(fd: RawFd, id: u64, val: i64) -> io::Result<()> {
    let resp = SeccompNotifResp {
        id,
        val,
        error: 0,
        flags: 0,
    };
    send_resp_raw(fd, &resp)
}

/// Fail-closed response used when fd injection fails.
///
/// Denies the syscall with `EACCES` rather than letting it continue: a
/// `SECCOMP_USER_NOTIF_FLAG_CONTINUE` here would let the child's original
/// syscall run unmediated against the host path, silently bypassing
/// chroot/file confinement. (Regression guard: this must never be a CONTINUE
/// response.)
fn inject_failure_resp(id: u64) -> SeccompNotifResp {
    SeccompNotifResp {
        id,
        val: 0,
        error: -libc::EACCES,
        flags: 0,
    }
}

/// Inject a file descriptor into the child process using SECCOMP_ADDFD_FLAG_SEND.
///
/// Uses the SEND flag to atomically inject the fd and respond to the syscall.
/// The ioctl return value is the fd number assigned in the child process.
/// After this call, no additional SECCOMP_IOCTL_NOTIF_SEND is needed.
fn inject_fd_and_send(fd: RawFd, id: u64, srcfd: RawFd, newfd_flags: u32) -> io::Result<i32> {
    let addfd = SeccompNotifAddfd {
        id,
        flags: SECCOMP_ADDFD_FLAG_SEND,
        srcfd: srcfd as u32,
        newfd: 0,   // ignored when SECCOMP_ADDFD_FLAG_SETFD is not set
        newfd_flags,
    };
    let ret = unsafe {
        libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_ADDFD as libc::c_ulong, &addfd as *const _)
    };
    if ret < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(ret as i32)
    }
}

/// Inject a file descriptor into the child process (without responding).
/// ioctl(fd, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd)
fn inject_fd(fd: RawFd, id: u64, srcfd: RawFd, targetfd: i32) -> io::Result<()> {
    let addfd = SeccompNotifAddfd {
        id,
        flags: 0,
        srcfd: srcfd as u32,
        newfd: targetfd as u32,
        newfd_flags: 0,
    };
    let ret = unsafe {
        libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_ADDFD as libc::c_ulong, &addfd as *const _)
    };
    if ret < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

/// Raw ioctl to send a notification response.
fn send_resp_raw(fd: RawFd, resp: &SeccompNotifResp) -> io::Result<()> {
    let ret = unsafe {
        libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_SEND as libc::c_ulong, resp as *const _)
    };
    if ret < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

/// Check whether a notification ID is still valid (TOCTOU guard).
/// ioctl(fd, SECCOMP_IOCTL_NOTIF_ID_VALID, &id)
pub(crate) fn id_valid(fd: RawFd, id: u64) -> io::Result<()> {
    let ret = unsafe {
        libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_ID_VALID as libc::c_ulong, &id as *const _)
    };
    if ret < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

/// Try to enable sync wakeup (Linux 6.7+). Ignores errors.
fn try_set_sync_wakeup(fd: RawFd) {
    let flags: u64 = SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP as u64;
    unsafe {
        libc::ioctl(fd, SECCOMP_IOCTL_NOTIF_SET_FLAGS as libc::c_ulong, &flags as *const _);
    }
}

// ============================================================
// Child memory access helpers
// ============================================================

/// Read bytes from a child process via process_vm_readv (single syscall).
fn read_child_mem_vm(pid: u32, addr: u64, len: usize) -> Result<Vec<u8>, NotifError> {
    let mut buf = vec![0u8; len];
    let local_iov = libc::iovec {
        iov_base: buf.as_mut_ptr() as *mut libc::c_void,
        iov_len: len,
    };
    let remote_iov = libc::iovec {
        iov_base: addr as *mut libc::c_void,
        iov_len: len,
    };
    let ret = unsafe {
        libc::process_vm_readv(pid as i32, &local_iov, 1, &remote_iov, 1, 0)
    };
    if ret < 0 {
        Err(NotifError::ChildMemoryRead(io::Error::last_os_error()))
    } else {
        buf.truncate(ret as usize);
        Ok(buf)
    }
}

/// Write bytes to a child process via process_vm_writev (single syscall).
fn write_child_mem_vm(pid: u32, addr: u64, data: &[u8]) -> Result<(), NotifError> {
    let local_iov = libc::iovec {
        iov_base: data.as_ptr() as *mut libc::c_void,
        iov_len: data.len(),
    };
    let remote_iov = libc::iovec {
        iov_base: addr as *mut libc::c_void,
        iov_len: data.len(),
    };
    let ret = unsafe {
        libc::process_vm_writev(pid as i32, &local_iov, 1, &remote_iov, 1, 0)
    };
    if ret < 0 {
        Err(NotifError::ChildMemoryRead(io::Error::last_os_error()))
    } else if (ret as usize) < data.len() {
        Err(NotifError::ChildMemoryRead(io::Error::new(
            io::ErrorKind::WriteZero,
            format!("short write: {} of {} bytes", ret, data.len()),
        )))
    } else {
        Ok(())
    }
}

/// Read bytes from a child process via `process_vm_readv` with TOCTOU validation.
///
/// Calls `id_valid` before and after the read to ensure the notification is
/// still live (kernel did not abort or release the trapped syscall while the
/// supervisor was reading guest memory).
///
/// Public — used by downstream `Handler` implementations to read syscall
/// arguments that the kernel passes by pointer (paths in `openat`, buffers
/// in `write`/`writev`, etc.).
pub fn read_child_mem(
    notif_fd: RawFd,
    id: u64,
    pid: u32,
    addr: u64,
    len: usize,
) -> Result<Vec<u8>, NotifError> {
    id_valid(notif_fd, id).map_err(NotifError::Ioctl)?;
    let result = read_child_mem_vm(pid, addr, len)?;
    id_valid(notif_fd, id).map_err(NotifError::Ioctl)?;
    Ok(result)
}

/// Read a NUL-terminated string from child memory without crossing unmapped
/// page boundaries in a single `process_vm_readv` call.
///
/// TOCTOU-safe — internally calls [`read_child_mem`], inheriting the
/// `id_valid` checks bracketing each `process_vm_readv` call.
///
/// Page-aware: reads up to a page boundary at a time and stops at the
/// first NUL byte, never crossing into unmapped memory.  Returns
/// `None` for `addr == 0`, `max_len == 0`, a read failure, or a string
/// that exceeds `max_len` without a NUL.
///
/// Public — used by downstream `Handler` implementations that read
/// path arguments from notifications (`openat`, `unlinkat`, `statx`,
/// `newfstatat`, etc.).
pub fn read_child_cstr(
    notif_fd: RawFd,
    id: u64,
    pid: u32,
    addr: u64,
    max_len: usize,
) -> Option<String> {
    if addr == 0 || max_len == 0 {
        return None;
    }

    const PAGE_SIZE: u64 = 4096;
    let mut result = Vec::with_capacity(max_len.min(256));
    let mut cur = addr;
    while result.len() < max_len {
        let page_remaining = PAGE_SIZE - (cur % PAGE_SIZE);
        let remaining = max_len - result.len();
        let to_read = page_remaining.min(remaining as u64) as usize;
        let bytes = read_child_mem(notif_fd, id, pid, cur, to_read).ok()?;
        if let Some(nul) = bytes.iter().position(|&b| b == 0) {
            result.extend_from_slice(&bytes[..nul]);
            return String::from_utf8(result).ok();
        }
        result.extend_from_slice(&bytes);
        cur += to_read as u64;
    }

    String::from_utf8(result).ok()
}

/// Write bytes to a child process via `process_vm_writev` with TOCTOU validation.
///
/// Same TOCTOU contract as [`read_child_mem`].  Public for downstream
/// `Handler` implementations that synthesise syscall results into
/// guest memory (e.g. fake `getdents64` listings populated from a
/// virtual directory index, or synthesised `stat` buffers).
pub fn write_child_mem(
    notif_fd: RawFd,
    id: u64,
    pid: u32,
    addr: u64,
    data: &[u8],
) -> Result<(), NotifError> {
    id_valid(notif_fd, id).map_err(NotifError::Ioctl)?;
    write_child_mem_vm(pid, addr, data)?;
    id_valid(notif_fd, id).map_err(NotifError::Ioctl)?;
    Ok(())
}

/// Write bytes to a child, forcing past read-only page protections.
///
/// [`write_child_mem`] uses `process_vm_writev`, which honors the target VMA's
/// protection bits and so returns `EFAULT` when the destination page is
/// read-only — e.g. a `.rodata` path literal a program hands to
/// `chdir`/`execve`. This variant writes through `/proc/<pid>/mem`, whose writes
/// use `FOLL_FORCE` and therefore copy-on-write past a read-only mapping (the
/// same mechanism a debugger uses to plant a breakpoint in read-only `.text`).
/// It handles writable and read-only destinations through one path, so the
/// argument-rewrite sites need no `EFAULT` fallback.
///
/// Use ONLY for rewriting an *input* path argument the child owns that the
/// kernel re-reads under `SECCOMP_USER_NOTIF_FLAG_CONTINUE` (the `chdir`/`execve`
/// path rewrites). Do NOT use it for syscall *output* buffers (`stat`,
/// `getdents`, `getcwd`, `readlink`, the `getsockname`/`recvfrom` source
/// address): if a child supplies a read-only output buffer the real syscall
/// would `EFAULT`, and faithful emulation must too — keep those on
/// [`write_child_mem`]. (`bind`/`connect` need nothing here: they are emulated
/// on-behalf on a duped fd and never rewrite the child's sockaddr.)
///
/// Opening `/proc/<pid>/mem` for write needs `PTRACE_MODE_ATTACH_FSCREDS` over
/// the child (no actual attach or stop): satisfied by the supervisor as the
/// child's same-uid parent under the common Yama scopes. Returns `Err` (so the
/// caller can still surface `EFAULT`) if the `mem` file can't be opened or
/// written — it never silently no-ops. TOCTOU-safe: brackets the write with
/// `id_valid` like [`write_child_mem`].
pub fn write_child_mem_force(
    notif_fd: RawFd,
    id: u64,
    pid: u32,
    addr: u64,
    data: &[u8],
) -> Result<(), NotifError> {
    id_valid(notif_fd, id).map_err(NotifError::Ioctl)?;
    write_child_mem_proc(pid, addr, data)?;
    id_valid(notif_fd, id).map_err(NotifError::Ioctl)?;
    Ok(())
}

/// Write bytes to a process's memory via `/proc/<pid>/mem` (open + `pwrite`).
///
/// Inner helper for [`write_child_mem_force`]; the file offset is the target
/// virtual address. Writes here use `FOLL_FORCE`, so they copy-on-write past a
/// read-only destination page where [`write_child_mem_vm`] (`process_vm_writev`)
/// returns `EFAULT`.
fn write_child_mem_proc(pid: u32, addr: u64, data: &[u8]) -> Result<(), NotifError> {
    use std::os::unix::fs::FileExt;
    let mem = std::fs::OpenOptions::new()
        .write(true)
        .open(format!("/proc/{}/mem", pid))
        .map_err(NotifError::ChildMemoryWrite)?;
    mem.write_all_at(data, addr)
        .map_err(NotifError::ChildMemoryWrite)?;
    Ok(())
}

/// Kernel limit on a single argv/envp string (MAX_ARG_STRLEN, 32 pages).
/// A longer string makes execve fail with E2BIG, so no string that could
/// matter to a successful exec exceeds this.
const EXEC_MAX_ARG_STRLEN: usize = 32 * 4096;

/// Upper bound on argv/envp entries scanned. The kernel's argument budget
/// (pointers count toward it) keeps any exec that could succeed far below
/// this; it only stops a runaway scan of a corrupt, unterminated array,
/// whose exec the kernel would fail anyway.
const EXEC_MAX_PTR_ENTRIES: usize = 1 << 20;

/// Byte range `[start, end)` that the path rewrite will overwrite in the
/// child, plus the relocation buffer being assembled for it.
struct ExecRewritePlan {
    /// Bytes to write at the path pointer: the fd path, then every
    /// relocated string, all NUL-terminated.
    buf: Vec<u8>,
    /// Pointer-slot patches: (slot address in the argv/envp array,
    /// relocated string address).
    patches: Vec<(u64, u64)>,
}

/// Read a NULL-terminated pointer array (argv or envp) from child memory.
/// Chunked at page boundaries because a single straddling read fails whole
/// if any page is unmapped, and mappings are page-granular.
fn read_exec_ptr_array(
    read: &mut impl FnMut(u64, usize) -> Result<Vec<u8>, NotifError>,
    base: u64,
) -> Result<Vec<u64>, NotifError> {
    if base == 0 {
        return Ok(Vec::new());
    }
    const PAGE: u64 = 4096;
    let mut ptrs = Vec::new();
    let mut pending: Vec<u8> = Vec::new();
    let mut cur = base;
    loop {
        let chunk = (PAGE - cur % PAGE) as usize;
        let bytes = read(cur, chunk)?;
        cur += chunk as u64;
        pending.extend_from_slice(&bytes);
        let mut consumed = 0;
        while pending.len() - consumed >= 8 {
            let ptr = u64::from_ne_bytes(pending[consumed..consumed + 8].try_into().unwrap());
            consumed += 8;
            if ptr == 0 {
                return Ok(ptrs);
            }
            ptrs.push(ptr);
            if ptrs.len() >= EXEC_MAX_PTR_ENTRIES {
                return Ok(ptrs);
            }
        }
        pending.drain(..consumed);
    }
}

/// Read exactly `len` bytes starting at `addr`, chunked at page boundaries.
fn read_exec_range(
    read: &mut impl FnMut(u64, usize) -> Result<Vec<u8>, NotifError>,
    addr: u64,
    len: usize,
) -> Result<Vec<u8>, NotifError> {
    let mut out = Vec::with_capacity(len);
    let mut cur = addr;
    while out.len() < len {
        let chunk = ((4096 - cur % 4096) as usize).min(len - out.len());
        out.extend_from_slice(&read(cur, chunk)?);
        cur += chunk as u64;
    }
    Ok(out)
}

/// Read a NUL-terminated string (NUL excluded) of at most
/// `EXEC_MAX_ARG_STRLEN` bytes, chunked at page boundaries.
fn read_exec_cstr(
    read: &mut impl FnMut(u64, usize) -> Result<Vec<u8>, NotifError>,
    addr: u64,
) -> Result<Vec<u8>, NotifError> {
    let mut out = Vec::new();
    let mut cur = addr;
    while out.len() < EXEC_MAX_ARG_STRLEN {
        let chunk = ((4096 - cur % 4096) as usize).min(EXEC_MAX_ARG_STRLEN - out.len());
        let bytes = read(cur, chunk)?;
        if let Some(n) = bytes.iter().position(|&b| b == 0) {
            out.extend_from_slice(&bytes[..n]);
            return Ok(out);
        }
        out.extend_from_slice(&bytes);
        cur += chunk as u64;
    }
    Err(NotifError::Supervisor(format!(
        "exec arg string at {addr:#x} exceeds MAX_ARG_STRLEN"
    )))
}

/// Compute the write buffer and pointer patches for rewriting an exec path
/// to `fd_path` without corrupting any argv/envp string.
///
/// The rewrite overwrites `[path_ptr, path_ptr + buf.len())`. Any argv/envp
/// string overlapping that window is appended to the buffer (preserving its
/// original bytes, read before any write happens) and every pointer slot
/// referencing it is patched to the relocated copy. Appending grows the
/// window, which can pull further strings in, hence the fixpoint loop.
///
/// Overlap comes in two shapes:
/// - a string starting inside the window (the common shell aliasing where
///   path == argv[0]);
/// - a string starting below `path_ptr` whose tail reaches it (the caller
///   passed a path pointer into the middle of a longer string). Reaching
///   means no NUL between its start and `path_ptr`; candidates are walked
///   downward so each gap segment is read once, and once a NUL is seen every
///   lower string is known to terminate before the window.
///
/// Fails if the argv/envp pointer arrays themselves fall inside the final
/// window: the kernel reads those arrays after we return, and they cannot be
/// moved because their addresses live in syscall registers.
fn plan_exec_rewrite(
    read: &mut impl FnMut(u64, usize) -> Result<Vec<u8>, NotifError>,
    path_ptr: u64,
    fd_path: &[u8],
    argv_ptr: u64,
    envp_ptr: u64,
) -> Result<ExecRewritePlan, NotifError> {
    let argv = read_exec_ptr_array(read, argv_ptr)?;
    let envp = read_exec_ptr_array(read, envp_ptr)?;
    let slots: Vec<(u64, u64)> = argv
        .iter()
        .enumerate()
        .map(|(i, &p)| (argv_ptr + 8 * i as u64, p))
        .chain(envp.iter().enumerate().map(|(i, &p)| (envp_ptr + 8 * i as u64, p)))
        .collect();

    let mut buf = fd_path.to_vec();
    let mut relocated: std::collections::BTreeMap<u64, u64> = std::collections::BTreeMap::new();
    let relocate = |buf: &mut Vec<u8>,
                        relocated: &mut std::collections::BTreeMap<u64, u64>,
                        read: &mut dyn FnMut(u64, usize) -> Result<Vec<u8>, NotifError>,
                        ptr: u64|
     -> Result<(), NotifError> {
        let s = read_exec_cstr(&mut |a, l| read(a, l), ptr)?;
        relocated.insert(ptr, path_ptr + buf.len() as u64);
        buf.extend_from_slice(&s);
        buf.push(0);
        Ok(())
    };

    // Strings whose tail reaches path_ptr from below. Anything further than
    // MAX_ARG_STRLEN below cannot reach it within a string the kernel would
    // accept.
    let mut below: Vec<u64> = slots
        .iter()
        .map(|&(_, p)| p)
        .filter(|&p| p < path_ptr && path_ptr - p < EXEC_MAX_ARG_STRLEN as u64)
        .collect();
    below.sort_unstable();
    below.dedup();
    let mut nul_free_from = path_ptr;
    for &p in below.iter().rev() {
        let seg = read_exec_range(read, p, (nul_free_from - p) as usize)?;
        if seg.contains(&0) {
            break;
        }
        relocate(&mut buf, &mut relocated, read, p)?;
        nul_free_from = p;
    }

    // Strings starting inside the (growing) window.
    loop {
        let end = path_ptr + buf.len() as u64;
        let mut grew = false;
        for &(_, p) in &slots {
            if !relocated.contains_key(&p) && p >= path_ptr && p < end {
                relocate(&mut buf, &mut relocated, read, p)?;
                grew = true;
            }
        }
        if !grew {
            break;
        }
    }

    let end = path_ptr + buf.len() as u64;
    for (base, n) in [(argv_ptr, argv.len()), (envp_ptr, envp.len())] {
        if base != 0 && base < end && base + 8 * (n as u64 + 1) > path_ptr {
            return Err(NotifError::Supervisor(
                "execve argv/envp pointer array overlaps the path rewrite window".into(),
            ));
        }
    }

    let patches = slots
        .iter()
        .filter_map(|&(slot, p)| relocated.get(&p).map(|&np| (slot, np)))
        .collect();
    Ok(ExecRewritePlan { buf, patches })
}

/// Rewrite an execve/execveat path argument to `/proc/self/fd/<child_fd>`,
/// preserving every argv/envp string the rewrite would clobber.
///
/// A user-notif supervisor cannot change syscall registers, so redirecting
/// an exec to an injected fd means overwriting the child's path buffer in
/// place. Shells and `execvp`-style callers commonly pass the same buffer as
/// both the exec path and argv[0] (dash execs `./m` with path == argv[0]),
/// and libcs may pack other argv/envp strings right after it; a blind
/// overwrite corrupts whatever the fd path lands on. Multicall binaries
/// (busybox, uutils coreutils) then dispatch on basename(argv[0]) = "N" and
/// fail. [`plan_exec_rewrite`] relocates every affected string past the fd
/// path and patches the pointer slots, so the exec'd program sees its
/// original arguments for any string layout.
///
/// Writing past the original path buffer is safe because execve replaces the
/// whole address space on success, and the kernel copies the path and
/// argv/envp strings out of the old address space only after this returns
/// Continue, before anything else runs in the child. If the exec fails
/// instead (e.g. the injected fd is not executable), the child keeps running
/// with the rewritten buffer and patched pointers; argv is preserved so the
/// damage is confined to the path string, same as before this helper.
///
/// Pointer slots are 8 bytes: the BPF filter kills non-native-arch syscalls
/// before they reach the notif fd, and every supported native arch is
/// 64-bit.
///
/// `argv_ptr`/`envp_ptr` are the syscall's argv/envp arguments (args[1]/[2]
/// for execve, args[2]/[3] for execveat); 0 (NULL) arrays are skipped.
pub(crate) fn rewrite_exec_path_to_fd(
    notif_fd: RawFd,
    id: u64,
    pid: u32,
    path_ptr: u64,
    argv_ptr: u64,
    envp_ptr: u64,
    child_fd: i32,
) -> Result<(), NotifError> {
    let fd_path = format!("/proc/self/fd/{}\0", child_fd);
    let mut read = |addr: u64, len: usize| read_child_mem(notif_fd, id, pid, addr, len);
    let plan = plan_exec_rewrite(&mut read, path_ptr, fd_path.as_bytes(), argv_ptr, envp_ptr)?;
    write_child_mem_force(notif_fd, id, pid, path_ptr, &plan.buf)?;
    for (slot, new_ptr) in plan.patches {
        write_child_mem_force(notif_fd, id, pid, slot, &new_ptr.to_ne_bytes())?;
    }
    Ok(())
}

// ============================================================
// Response dispatch
// ============================================================

/// Dispatch a `NotifAction` to the appropriate low-level response function.
fn send_response(fd: RawFd, id: u64, action: NotifAction) -> io::Result<()> {
    match action {
        NotifAction::Continue => respond_continue(fd, id),
        NotifAction::Errno(errno) => respond_errno(fd, id, errno),
        NotifAction::InjectFd { srcfd, targetfd } => {
            inject_fd(fd, id, srcfd, targetfd)?;
            respond_continue(fd, id)
        }
        NotifAction::InjectFdSend { srcfd, newfd_flags } => {
            // SECCOMP_ADDFD_FLAG_SEND atomically injects the fd and responds.
            // No separate NOTIF_SEND needed after this.
            // On failure, deny (fail closed) rather than letting the original
            // syscall continue unmediated against the host path.
            // srcfd (OwnedFd) is dropped at end of this arm, closing the fd.
            match inject_fd_and_send(fd, id, srcfd.as_raw_fd(), newfd_flags) {
                Ok(_new_fd) => Ok(()),
                Err(_) => send_resp_raw(fd, &inject_failure_resp(id)),
            }
        }
        NotifAction::InjectFdSendTracked { srcfd, newfd_flags, on_success } => {
            match inject_fd_and_send(fd, id, srcfd.as_raw_fd(), newfd_flags) {
                Ok(new_fd) => {
                    (on_success.0)(new_fd);
                    Ok(())
                }
                Err(_) => send_resp_raw(fd, &inject_failure_resp(id)),
            }
        }
        NotifAction::ReturnValue(val) => respond_value(fd, id, val),
        NotifAction::Hold => Ok(()), // Don't send a response.
        NotifAction::Defer(_) => {
            // Defer is intercepted in `handle_notification` and never reaches
            // here on the normal path. If it ever does, fail closed with EIO
            // rather than dropping the future and wedging the child.
            debug_assert!(false, "Defer reached send_response; should be intercepted earlier");
            respond_errno(fd, id, libc::EIO)
        }
        NotifAction::Kill { sig, pgid } => {
            // Kill the entire process group, then return ENOMEM so the
            // seccomp notification is resolved (avoids a kernel warning).
            unsafe { libc::killpg(pgid, sig) };
            respond_errno(fd, id, ENOMEM)
        }
    }
}

// ============================================================
// vDSO re-patching after exec
// ============================================================

/// Re-patch the vDSO if the base address changed (e.g. after exec replaces it).
fn maybe_patch_vdso(pid: i32, procfs: &mut super::state::ProcfsState, policy: &NotifPolicy) {
    let base = match crate::vdso::find_vdso_base(pid) {
        Ok(addr) => addr,
        Err(_) => return,
    };
    if base == procfs.vdso_patched_addr {
        return; // already patched this vDSO
    }
    let time_offset = if policy.has_time_start { Some(policy.time_offset) } else { None };
    if crate::vdso::patch(pid, time_offset, policy.has_random_seed).is_ok() {
        procfs.vdso_patched_addr = base;
    }
}

// ============================================================
// Policy event emission
// ============================================================

/// Map a syscall number to a human-readable name for the policy callback.
fn syscall_name(nr: i64) -> &'static str {
    match nr {
        n if n == libc::SYS_openat => "openat",
        n if n == libc::SYS_connect => "connect",
        n if n == libc::SYS_sendto => "sendto",
        n if n == libc::SYS_sendmsg => "sendmsg",
        n if n == libc::SYS_sendmmsg => "sendmmsg",
        n if n == libc::SYS_bind => "bind",
        n if n == libc::SYS_clone => "clone",
        n if n == libc::SYS_clone3 => "clone3",
        n if Some(n) == arch::sys_vfork() => "vfork",
        n if Some(n) == arch::sys_fork() => "fork",
        n if n == libc::SYS_execve => "execve",
        n if n == libc::SYS_execveat => "execveat",
        n if n == libc::SYS_mmap => "mmap",
        n if n == libc::SYS_munmap => "munmap",
        n if n == libc::SYS_brk => "brk",
        n if n == libc::SYS_getrandom => "getrandom",
        n if n == libc::SYS_unlinkat => "unlinkat",
        n if n == libc::SYS_mkdirat => "mkdirat",
        _ => "unknown",
    }
}

/// Map a syscall number to a high-level category.
fn syscall_category(nr: i64) -> crate::policy_fn::SyscallCategory {
    use crate::policy_fn::SyscallCategory;
    match nr {
        n if n == libc::SYS_openat || n == libc::SYS_unlinkat
            || n == libc::SYS_mkdirat || n == libc::SYS_renameat2
            || n == libc::SYS_symlinkat || n == libc::SYS_linkat
            || n == libc::SYS_fchmodat || n == libc::SYS_fchownat
            || n == libc::SYS_truncate || n == libc::SYS_readlinkat
            || n == libc::SYS_newfstatat || n == libc::SYS_statx
            || n == libc::SYS_faccessat || n == libc::SYS_getdents64
            || Some(n) == arch::sys_getdents() => SyscallCategory::File,
        n if n == libc::SYS_connect || n == libc::SYS_sendto
            || n == libc::SYS_sendmsg || n == libc::SYS_sendmmsg
            || n == libc::SYS_bind
            || n == libc::SYS_getsockname => SyscallCategory::Network,
        n if n == libc::SYS_clone || n == libc::SYS_clone3
            || Some(n) == arch::sys_vfork() || Some(n) == arch::sys_fork()
            || n == libc::SYS_execve || n == libc::SYS_execveat => SyscallCategory::Process,
        n if n == libc::SYS_mmap || n == libc::SYS_munmap
            || n == libc::SYS_brk || n == libc::SYS_mremap
            => SyscallCategory::Memory,
        _ => SyscallCategory::File, // default
    }
}

/// Read the parent PID from /proc/{pid}/stat.
fn read_ppid(pid: u32) -> Option<u32> {
    let stat = std::fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?;
    // Format: "pid (comm) state ppid ..."
    // Find the closing ')' then split the rest
    let close_paren = stat.rfind(')')?;
    let rest = &stat[close_paren + 2..]; // skip ") "
    let fields: Vec<&str> = rest.split_whitespace().collect();
    // fields[0] = state, fields[1] = ppid
    fields.get(1)?.parse().ok()
}

/// Read a NUL-terminated path from child memory (up to 256 bytes).
fn read_path_for_event(notif: &SeccompNotif, addr: u64, notif_fd: RawFd) -> Option<String> {
    if addr == 0 { return None; }
    let bytes = read_child_mem(notif_fd, notif.id, notif.pid, addr, 256).ok()?;
    let nul = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
    String::from_utf8(bytes[..nul].to_vec()).ok()
}

fn normalize_path(path: &std::path::Path) -> String {
    use std::path::{Component, PathBuf};

    let mut normalized = PathBuf::new();
    let absolute = path.is_absolute();
    if absolute {
        normalized.push("/");
    }

    for component in path.components() {
        match component {
            Component::RootDir | Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            Component::Normal(part) => normalized.push(part),
            Component::Prefix(_) => {}
        }
    }

    if normalized.as_os_str().is_empty() {
        if absolute { "/".into() } else { ".".into() }
    } else {
        normalized.to_string_lossy().into_owned()
    }
}

fn resolve_at_path_for_event(notif: &SeccompNotif, dirfd: i64, path: &str) -> Option<String> {
    use std::path::Path;

    if Path::new(path).is_absolute() {
        return Some(normalize_path(Path::new(path)));
    }

    let dirfd32 = dirfd as i32;
    let base = if dirfd32 == libc::AT_FDCWD {
        std::fs::read_link(format!("/proc/{}/cwd", notif.pid)).ok()?
    } else {
        std::fs::read_link(format!("/proc/{}/fd/{}", notif.pid, dirfd32)).ok()?
    };

    Some(normalize_path(&base.join(path)))
}

fn resolve_path_for_notif(notif: &SeccompNotif, notif_fd: RawFd) -> Option<String> {
    let nr = notif.data.nr as i64;
    match nr {
        n if n == libc::SYS_openat || n == arch::SYS_OPENAT2 => {
            // openat(dirfd, pathname, flags, mode) and
            // openat2(dirfd, pathname, how, size) share (dirfd, pathname).
            let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?;
            resolve_at_path_for_event(notif, notif.data.args[0] as i64, &path)
        }
        n if Some(n) == arch::sys_open() || n == libc::SYS_execve => {
            let path = read_path_for_event(notif, notif.data.args[0], notif_fd)?;
            resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path)
        }
        n if n == libc::SYS_execveat => {
            let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?;
            resolve_at_path_for_event(notif, notif.data.args[0] as i64, &path)
        }
        // linkat(olddirfd, oldpath, newdirfd, newpath, flags)
        // Check the source (old) path — deny if it's a denied file being linked away.
        n if n == libc::SYS_linkat => {
            let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?;
            resolve_at_path_for_event(notif, notif.data.args[0] as i64, &path)
        }
        // renameat2(olddirfd, oldpath, newdirfd, newpath, flags)
        // Check the source (old) path — deny if a denied file is being renamed away.
        n if n == libc::SYS_renameat2 => {
            let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?;
            resolve_at_path_for_event(notif, notif.data.args[0] as i64, &path)
        }
        // symlinkat/symlink intentionally omitted: creating a symlink does
        // not access its target, so there is nothing to gate here. Any later
        // open through the symlink resolves to the real target and is denied
        // race-free on the open path (issue #111). See `on_behalf_open_for_deny`.
        // link(oldpath, newpath) — legacy, AT_FDCWD implied for both
        n if Some(n) == arch::sys_link() => {
            let path = read_path_for_event(notif, notif.data.args[0], notif_fd)?;
            resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path)
        }
        // rename(oldpath, newpath) — legacy, AT_FDCWD implied for both
        n if Some(n) == arch::sys_rename() => {
            let path = read_path_for_event(notif, notif.data.args[0], notif_fd)?;
            resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path)
        }
        _ => None,
    }
}

/// Resolve the second (destination) path for two-path syscalls.
///
/// Returns `None` for syscalls that only have a single path argument.
fn resolve_second_path_for_notif(notif: &SeccompNotif, notif_fd: RawFd) -> Option<String> {
    let nr = notif.data.nr as i64;
    match nr {
        // renameat2(olddirfd, oldpath, newdirfd, newpath, flags)
        n if n == libc::SYS_renameat2 => {
            let path = read_path_for_event(notif, notif.data.args[3], notif_fd)?;
            resolve_at_path_for_event(notif, notif.data.args[2] as i64, &path)
        }
        // linkat(olddirfd, oldpath, newdirfd, newpath, flags)
        // Destination of a hardlink to a denied file should also be denied
        // (prevents overwriting a denied file via linkat).
        n if n == libc::SYS_linkat => {
            let path = read_path_for_event(notif, notif.data.args[3], notif_fd)?;
            resolve_at_path_for_event(notif, notif.data.args[2] as i64, &path)
        }
        // rename(oldpath, newpath) — legacy
        n if Some(n) == arch::sys_rename() => {
            let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?;
            resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path)
        }
        // link(oldpath, newpath) — legacy
        n if Some(n) == arch::sys_link() => {
            let path = read_path_for_event(notif, notif.data.args[1], notif_fd)?;
            resolve_at_path_for_event(notif, libc::AT_FDCWD as i64, &path)
        }
        _ => None,
    }
}

/// Extract IP and port from a sockaddr in child memory. Parsing (including
/// v4-mapped canonicalization) is shared with the enforcement path so the
/// policy_fn callback judges the same address the policy layer does.
fn read_sockaddr_for_event(notif: &SeccompNotif, addr: u64, len: usize, notif_fd: RawFd)
    -> (Option<std::net::IpAddr>, Option<u16>)
{
    if addr == 0 || len < 4 { return (None, None); }
    let bytes = match read_child_mem(notif_fd, notif.id, notif.pid, addr, len.min(128)) {
        Ok(b) => b,
        Err(_) => return (None, None),
    };
    let ip = crate::network::materialize::parse_ip_from_sockaddr(&bytes);
    let port = crate::network::materialize::parse_port_from_sockaddr(&bytes);
    (ip, port.filter(|&p| p > 0))
}

/// Read argv (NULL-terminated array of char* in child memory) for execve.
/// Capped at 64 entries × 256 bytes/entry as a safety bound.
fn read_argv_for_event(notif: &SeccompNotif, argv_ptr: u64, notif_fd: RawFd) -> Option<Vec<String>> {
    if argv_ptr == 0 { return None; }
    let mut args = Vec::new();
    let ptr_size = std::mem::size_of::<u64>();

    for i in 0..64u64 {
        let ptr_addr = argv_ptr + i * ptr_size as u64;
        let ptr_bytes = read_child_mem(notif_fd, notif.id, notif.pid, ptr_addr, ptr_size).ok()?;
        let str_ptr = u64::from_ne_bytes(ptr_bytes[..8].try_into().ok()?);
        if str_ptr == 0 { break; } // NULL terminator

        if let Some(s) = read_path_for_event(notif, str_ptr, notif_fd) {
            args.push(s);
        } else {
            break;
        }
    }

    if args.is_empty() { None } else { Some(args) }
}

/// Resolve a held syscall's policy_fn gate outcome into a verdict.
///
/// `received` is the verdict the callback sent, or `None` if the gate timed
/// out or its channel closed before a decision arrived. A held syscall is one
/// whose verdict matters (execve, connect, openat, ...); when no decision
/// arrives we fail closed and deny rather than letting the syscall proceed.
fn resolve_held_gate(
    received: Option<crate::policy_fn::Verdict>,
) -> Option<crate::policy_fn::Verdict> {
    match received {
        Some(v) => Some(v),
        None => Some(crate::policy_fn::Verdict::Deny),
    }
}

/// Emit a syscall event to the policy_fn callback thread (if active).
/// Returns the callback's verdict for held syscalls.
async fn emit_policy_event(
    notif: &SeccompNotif,
    action: &NotifAction,
    policy_fn_state: &Arc<tokio::sync::Mutex<super::state::PolicyFnState>>,
    notif_fd: RawFd,
) -> Option<crate::policy_fn::Verdict> {
    let pfs = policy_fn_state.lock().await;
    let tx = match pfs.event_tx.as_ref() {
        Some(tx) => tx.clone(),
        None => return None,
    };
    drop(pfs);

    let nr = notif.data.nr as i64;
    let denied = matches!(action, NotifAction::Errno(_));
    let name = syscall_name(nr);
    let category = syscall_category(nr);
    let parent_pid = read_ppid(notif.pid);

    // Extract metadata based on syscall type.
    //
    // Path strings are deliberately NOT extracted: the kernel re-reads
    // user-memory pointers after Continue, so any path-string-based
    // decision is racy (issue #27). Path-based access control belongs
    // in static Landlock rules.
    //
    // argv IS extracted for allowed execve/execveat notifications:
    // the supervisor freezes every task in the sandbox (siblings +
    // peers) before this callback reads argv and keeps that freeze
    // through Continue, so the post-Continue re-read sees the same
    // memory we read here.
    //
    // Network fields are TOCTOU-safe because connect/sendto/bind are
    // performed on-behalf via pidfd_getfd; the kernel never re-reads
    // child memory for those syscalls.
    let mut host = None;
    let mut port = None;
    let mut size = None;
    let mut argv = None;

    if !denied && (nr == libc::SYS_execve || nr == libc::SYS_execveat) {
        // execve(pathname, argv, envp):       args[1] = argv ptr
        // execveat(dirfd, pathname, argv, ..): args[2] = argv ptr
        let argv_ptr = if nr == libc::SYS_execveat {
            notif.data.args[2]
        } else {
            notif.data.args[1]
        };
        argv = read_argv_for_event(notif, argv_ptr, notif_fd);
    }

    if nr == libc::SYS_connect || nr == libc::SYS_sendto || nr == libc::SYS_bind {
        // connect(fd, addr, addrlen): args[1]=addr, args[2]=len
        let addr_ptr = notif.data.args[1];
        let addr_len = notif.data.args[2] as usize;
        let (h, p) = read_sockaddr_for_event(notif, addr_ptr, addr_len, notif_fd);
        host = h;
        port = p;
    }

    if nr == libc::SYS_mmap {
        // mmap(addr, length, ...): args[1] = length
        size = Some(notif.data.args[1]);
    }

    let event = crate::policy_fn::SyscallEvent {
        syscall: name.to_string(),
        category,
        pid: notif.pid,
        parent_pid,
        host,
        port,
        size,
        argv,
        denied,
    };

    // Hold syscalls where the callback's verdict matters.
    // The child is blocked until the callback returns.
    let is_held = nr == libc::SYS_execve || nr == libc::SYS_execveat
        || nr == libc::SYS_connect || nr == libc::SYS_sendto
        || nr == libc::SYS_bind || nr == libc::SYS_openat;

    if is_held {
        let (gate_tx, gate_rx) = tokio::sync::oneshot::channel();
        let _ = tx.send(crate::policy_fn::PolicyEvent {
            event,
            gate: Some(gate_tx),
        });
        let received = match tokio::time::timeout(std::time::Duration::from_secs(5), gate_rx).await {
            Ok(Ok(verdict)) => Some(verdict),
            _ => None, // timeout or channel closed
        };
        resolve_held_gate(received)
    } else {
        let _ = tx.send(crate::policy_fn::PolicyEvent {
            event,
            gate: None,
        });
        None
    }
}

// ============================================================
// Per-notification handler (runs in a spawned task)
// ============================================================

/// Process a single seccomp notification: vDSO re-patch, path denial check,
/// dispatch, policy event emission, and response.
/// Maximum number of deferred handler futures running concurrently. Caps
/// the worker fan-out (and any resources those workers hold, e.g. memfds or
/// sockets) so a burst of deferrals cannot exhaust the supervisor process.
const DEFER_MAX_INFLIGHT: usize = 64;

/// Maximum time a deferred handler future may run before the supervisor gives
/// up and fails the trapped syscall closed. Bounds the worst case so a hung
/// future (e.g. a stalled network fetch in a token-injection handler) cannot
/// park the child forever or permanently leak its `DEFER_MAX_INFLIGHT` slot.
const DEFER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Drive a deferred future to its terminal action, bounded by `limit`.
///
/// On timeout, fail closed with `EIO` so the trapped child gets a definite
/// response instead of parking forever; `finalize_deferred` still guards a
/// future that resolves to a nested `Defer`.
async fn run_deferred_within(deferred: Deferred, limit: std::time::Duration) -> NotifAction {
    match tokio::time::timeout(limit, deferred.run()).await {
        Ok(action) => finalize_deferred(action),
        Err(_) => {
            eprintln!(
                "sandlock: deferred handler exceeded {:?}; failing syscall with EIO",
                limit
            );
            NotifAction::Errno(libc::EIO)
        }
    }
}

/// Spawn a worker task that drives a deferred handler future to its terminal
/// action and sends the seccomp response, keyed by `id`. The `permit` is
/// held for the worker's lifetime, releasing its `DEFER_MAX_INFLIGHT` slot on
/// completion. A stale `id` (child exited mid-defer) makes `send_response`
/// a no-op, matching the inline path's "child may have exited" tolerance.
fn spawn_deferred(
    fd: RawFd,
    id: u64,
    deferred: Deferred,
    permit: tokio::sync::OwnedSemaphorePermit,
) {
    tokio::spawn(async move {
        let _permit = permit; // released when the worker finishes
        let action = run_deferred_within(deferred, DEFER_TIMEOUT).await;
        let _ = send_response(fd, id, action);
    });
}

async fn handle_notification(
    notif: SeccompNotif,
    ctx: &Arc<super::ctx::SupervisorCtx>,
    dispatch_table: &super::dispatch::DispatchTable,
    fd: RawFd,
    defer_sem: &Arc<tokio::sync::Semaphore>,
) {
    let policy = &ctx.policy;

    // Ensure every pid that produces a notification has per-process
    // supervisor state and an exit watcher. The fork handler runs on
    // the *parent* pid (the child doesn't exist yet at clone-time), so
    // the child gets registered the first time it issues a notified
    // syscall.
    crate::resource::register_child_if_new(ctx, notif.pid as i32).await;

    // Re-patch vDSO if needed (exec replaces it with a fresh copy).
    if policy.has_time_start || policy.has_random_seed {
        let mut pfs = ctx.procfs.lock().await;
        maybe_patch_vdso(notif.pid as i32, &mut pfs, policy);
    }

    // Check dynamic path denials before dispatch
    let mut action = {
        let nr = notif.data.nr as i64;
        // symlinkat/symlink are not gated: creating a symlink does not access
        // its target (any open through it is denied race-free on the open
        // path). See `resolve_path_for_notif`.
        let mut path_check_nrs = vec![
            libc::SYS_openat, arch::SYS_OPENAT2, libc::SYS_execve, libc::SYS_execveat,
            libc::SYS_linkat, libc::SYS_renameat2,
        ];
        path_check_nrs.extend([
            arch::sys_open(), arch::sys_link(), arch::sys_rename(),
        ].into_iter().flatten());
        let should_precheck_denied = policy.chroot_root.is_none()
            && path_check_nrs.contains(&nr);
        if should_precheck_denied {
            let pfs = ctx.policy_fn.lock().await;
            if is_path_denied_for_notif(&pfs, &notif, fd) {
                NotifAction::Errno(libc::EACCES)
            } else {
                let has_denied = pfs.has_denied_paths();
                drop(pfs);
                // Let normal dispatch run first so /proc virtualization and
                // other handlers still win for their paths.
                let action = dispatch_table.dispatch(notif, fd).await;
                // A bare `Continue` for openat/open is the racy window: the
                // supervisor's resolution said "not denied", but the kernel
                // re-resolves after Continue and a racing thread can swap a
                // symlink to reach a denied carve-out inside a granted tree
                // (issue #111). Run the open on-behalf against the pinned
                // inode and inject the fd so the kernel never re-resolves.
                // Other path syscalls keep the best-effort precheck above
                // (documented follow-up — they return no fd to inject).
                let is_openat_family = nr == libc::SYS_openat
                    || nr == arch::SYS_OPENAT2
                    || Some(nr) == arch::sys_open();
                if matches!(action, NotifAction::Continue) && is_openat_family && has_denied {
                    let pfs = ctx.policy_fn.lock().await;
                    on_behalf_open_for_deny(&notif, policy, &pfs, fd)
                } else {
                    action
                }
            }
        } else {
            dispatch_table.dispatch(notif, fd).await
        }
    };

    let nr = notif.data.nr as i64;
    let fork_counted = matches!(action, NotifAction::Continue)
        && crate::resource::fork_counted_on_continue(&notif, fd);

    // TOCTOU-close for execve (issue #27): freeze every sandbox task
    // that could mutate argv before policy_fn reads argv and before the
    // kernel re-reads it after Continue. This covers two writer classes:
    //   1. Sibling threads of the calling tid (same TGID, share mm).
    //   2. Peer processes in other TGIDs that alias argv pages via
    //      MAP_SHARED mappings or share mm via clone(CLONE_VM).
    //
    // The freeze enumerates ProcessIndex. With policy_fn active, that
    // index is complete: fork-like syscalls are traced at creation time
    // below, before new children can run user code.
    //
    // Strict on failure: if we cannot establish the freeze, we cannot
    // safely expose argv or allow execve, so we deny with EPERM.
    let mut exec_freeze = None;
    if matches!(action, NotifAction::Continue)
        && policy.argv_safety_required
        && crate::freeze::requires_freeze_on_continue(nr)
    {
        match crate::freeze::freeze_sandbox_for_execve(
            &ctx.processes,
            notif.pid as i32,
        ) {
            Ok(outcome) => {
                exec_freeze = Some(outcome);
            }
            Err(e) => {
                eprintln!(
                    "sandlock: argv-safety freeze failed for pid {}: {} \
                     — denying execve to preserve TOCTOU invariant",
                    notif.pid, e
                );
                action = NotifAction::Errno(libc::EPERM);
            }
        }
    }

    // Emit event to policy_fn callback if active. For execve, argv is
    // only populated after `exec_freeze` has stopped every possible
    // writer, and those tasks stay stopped until after NOTIF_SEND.
    if let Some(verdict) = emit_policy_event(&notif, &action, &ctx.policy_fn, fd).await {
        use crate::policy_fn::Verdict;
        match verdict {
            Verdict::Deny => { action = NotifAction::Errno(libc::EPERM); }
            Verdict::DenyWith(errno) => { action = NotifAction::Errno(errno); }
            Verdict::Audit => { /* allow, but could log here */ }
            Verdict::Allow => {}
        }
    }

    if fork_counted && !matches!(action, NotifAction::Continue) {
        crate::resource::rollback_fork_count(&ctx.resource).await;
    }

    // With policy_fn active, fork-like syscalls are traced for exactly
    // one ptrace event so ProcessIndex becomes complete before the new
    // child can run user code. That closes the race where a peer
    // process could exist without ever having produced a notification.
    let mut creation_trace = None;
    if matches!(action, NotifAction::Continue)
        && crate::resource::requires_process_creation_tracking(&notif, fd, policy)
    {
        match crate::resource::prepare_process_creation_tracking(ctx, notif.pid as i32).await {
            Ok(trace) => {
                creation_trace = Some(trace);
            }
            Err(e) => {
                eprintln!(
                    "sandlock: process-creation tracking failed for pid {}: {} \
                     — denying fork-like syscall to preserve argv TOCTOU invariant",
                    notif.pid, e
                );
                if fork_counted {
                    crate::resource::rollback_fork_count(&ctx.resource).await;
                }
                action = NotifAction::Errno(libc::EPERM);
            }
        }
    }

    // Deferred response: run the handler's future on a worker task so the
    // single supervisor loop is not blocked waiting for slow work (a network
    // round-trip, a blocking syscall). The trapped child stays parked in the
    // syscall; the worker sends the real response later, keyed by notif.id.
    //
    // Deferral is refused on syscalls whose Continue path requires the
    // execve argv-safety freeze or fork creation-tracking: sending the
    // response off-loop would skip that TOCTOU-closing work. (When `action`
    // is Defer it is not Continue, so `exec_freeze`/`creation_trace` above
    // are already None — there is nothing to unwind here.)
    if let NotifAction::Defer(deferred) = action {
        if crate::freeze::requires_freeze_on_continue(nr)
            || crate::resource::requires_process_creation_tracking(&notif, fd, policy)
        {
            let _ = send_response(fd, notif.id, NotifAction::Errno(libc::EPERM));
            return;
        }
        match Arc::clone(defer_sem).try_acquire_owned() {
            Ok(permit) => spawn_deferred(fd, notif.id, deferred, permit),
            // Too many deferrals in flight: fail fast with EAGAIN rather than
            // blocking the loop or letting unbounded workers accrete.
            Err(_) => {
                let _ = send_response(fd, notif.id, NotifAction::Errno(libc::EAGAIN));
            }
        }
        return;
    }

    // Ignore error — child may have exited between recv and response.
    let exec_continued = exec_freeze.is_some() && matches!(action, NotifAction::Continue);
    let send_result = send_response(fd, notif.id, action);

    if let Some(trace) = creation_trace {
        if send_result.is_ok() {
            match crate::resource::finish_process_creation_tracking(trace).await {
                Ok(true) => {}
                Ok(false) => {
                    crate::resource::rollback_fork_count(&ctx.resource).await;
                }
                Err(e) => {
                    crate::resource::rollback_fork_count(&ctx.resource).await;
                    eprintln!(
                        "sandlock: process-creation tracking completion failed for pid {}: {}",
                        notif.pid, e
                    );
                }
            }
        } else {
            crate::resource::rollback_fork_count(&ctx.resource).await;
            crate::resource::abort_process_creation_tracking(trace).await;
        }
    }

    if let Some(freeze) = exec_freeze {
        if exec_continued && send_result.is_ok() {
            crate::freeze::detach_peers(&freeze.peer_tids);
        } else {
            crate::freeze::detach_all(&freeze);
        }
    }
}

// ============================================================
// Main supervisor loop
// ============================================================

/// Async event loop that processes seccomp notifications.
///
/// Runs until the notification fd is closed (child exits or filter is removed).
///
/// `pending_handlers` are user-supplied syscall handlers registered after all
/// builtin handlers.  For the default behaviour without any custom handlers
/// pass an empty `Vec`.
pub async fn supervisor(
    notif_fd: OwnedFd,
    ctx: Arc<super::ctx::SupervisorCtx>,
    pending_handlers: Vec<(i64, std::sync::Arc<dyn super::dispatch::Handler>)>,
    startup: tokio::sync::oneshot::Sender<io::Result<()>>,
) {
    // Register the notif fd with the Tokio IO driver so we can wait for
    // readiness via epoll instead of a dedicated blocking thread.
    let async_fd = match tokio::io::unix::AsyncFd::with_interest(
        notif_fd,
        tokio::io::Interest::READABLE,
    ) {
        Ok(fd) => fd,
        Err(err) => {
            let _ = startup.send(Err(err));
            return;
        }
    };
    let fd = async_fd.get_ref().as_raw_fd();

    // Build the dispatch table once at startup.
    let dispatch_table = Arc::new(super::dispatch::build_dispatch_table(
        &ctx.policy,
        &ctx.resource,
        &ctx,
        pending_handlers,
    ));

    // Try to enable sync wakeup (Linux 6.7+, ignore error on older kernels).
    try_set_sync_wakeup(fd);

    // The IO driver has the fd registered; subsequent block_on cycles
    // can resume this task and pick up readiness events. Tell the
    // caller it is safe to release the child.
    let _ = startup.send(Ok(()));

    // Periodic sweep as a defensive backstop in case pidfd-based
    // lifecycle cleanup misses an entry (e.g. pidfd_open failed for a
    // child on an old kernel, or its watcher panicked). At 5 minutes
    // this is cheap enough to leave on; the primary cleanup path is
    // still per-child pidfd readiness in `spawn_pid_watcher`.
    let gc = tokio::spawn(process_index_gc(Arc::clone(&ctx.processes)));

    // Bounds the number of in-flight deferred handler futures (see
    // `DEFER_MAX_INFLIGHT`). Shared across all notifications this supervisor
    // processes.
    let defer_sem = Arc::new(tokio::sync::Semaphore::new(DEFER_MAX_INFLIGHT));

    // Edge-triggered drain: each `readable().await` returns once per
    // epoll edge, then we drain the kernel queue via `probe_notif_fd`
    // until empty. The drain is necessary because tokio's AsyncFd is
    // edge-triggered and `recv_notif` does not signal "would block",
    // so a burst of arrivals between two `readable().await` calls
    // would coalesce into a single wake event.
    //
    // Notifications are processed sequentially (not spawned) to avoid
    // mutex contention between concurrent handlers.
    'outer: loop {
        let mut ready = match async_fd.readable().await {
            Ok(r) => r,
            Err(_) => break 'outer,
        };
        ready.clear_ready();
        drop(ready);

        loop {
            match probe_notif_fd(fd) {
                NotifFdState::Pending => {
                    let notif = match recv_notif(fd) {
                        Ok(n) => n,
                        Err(e) if e.raw_os_error() == Some(libc::EINTR) => continue,
                        Err(_) => break 'outer,
                    };
                    handle_notification(notif, &ctx, &dispatch_table, fd, &defer_sem).await;
                }
                NotifFdState::Empty => break,
                NotifFdState::Terminal => break 'outer,
            }
        }
    }

    gc.abort();
}

/// Periodic sweep that drops `ProcessIndex` entries for exited PIDs.
/// Per-process state hangs off these entries via `Arc`, so dropping
/// them releases everything in one step.
async fn process_index_gc(processes: Arc<super::state::ProcessIndex>) {
    let interval = std::time::Duration::from_secs(300);
    loop {
        tokio::time::sleep(interval).await;
        if processes.len() == 0 {
            continue;
        }
        processes.prune_dead();
    }
}

/// Spawn a per-child task that awaits the pidfd becoming readable
/// (process exit) and then runs unified cleanup across every
/// per-process supervisor map.
///
/// The watcher *owns* the pidfd via `AsyncFd<OwnedFd>` — the kernel
/// fd stays alive for as long as tokio's IO driver has it registered,
/// and is closed exactly once when the watcher task ends. This avoids
/// a TOCTOU where dropping the fd from a separate map could let a
/// recycled fd be deregistered from epoll.
pub(crate) fn spawn_pid_watcher(
    ctx: Arc<super::ctx::SupervisorCtx>,
    key: super::state::PidKey,
    pidfd: std::os::unix::io::OwnedFd,
) {
    tokio::spawn(async move {
        let async_fd = match tokio::io::unix::AsyncFd::with_interest(
            pidfd,
            tokio::io::Interest::READABLE,
        ) {
            Ok(f) => f,
            Err(_) => {
                // AsyncFd registration failed (extremely unusual);
                // fall back to immediate cleanup so we don't leak the
                // index entry. The OwnedFd we passed in is consumed
                // by `with_interest`'s Err return and will close on
                // drop here.
                cleanup_pid(&ctx, key).await;
                return;
            }
        };
        // pidfd becomes readable when the process exits; we don't
        // read any data, so `readable()` is just an await point.
        let _ = async_fd.readable().await;
        cleanup_pid(&ctx, key).await;
        // async_fd drops here, closing the pidfd.
    });
}

/// Drop the supervisor's per-process state for `key`. With every
/// per-process map living inside `PerProcessState` (owned by
/// `ProcessIndex`), this is a single unregister — the entry's `Arc`
/// drops here, and remaining clones held by in-flight handlers will
/// drop with their tasks, freeing `PerProcessState` automatically.
pub(crate) async fn cleanup_pid(ctx: &super::ctx::SupervisorCtx, key: super::state::PidKey) {
    ctx.processes.unregister(key);
}

// ============================================================
// Tests
// ============================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::io::FromRawFd;

    fn gettid() -> u32 {
        (unsafe { libc::syscall(libc::SYS_gettid) }) as u32
    }

    // ---- plan_exec_rewrite ----

    /// Fake child memory: whole zero-filled pages at FAKE_BASE, so the
    /// page-chunked readers never run off a mapped page mid-scan and a
    /// zero word naturally terminates a pointer array.
    const FAKE_BASE: u64 = 0x10000;
    const FD: &[u8] = b"/proc/self/fd/3\0"; // 16 bytes

    fn put(mem: &mut [u8], addr: u64, bytes: &[u8]) {
        let off = (addr - FAKE_BASE) as usize;
        mem[off..off + bytes.len()].copy_from_slice(bytes);
    }

    fn put_ptrs(mem: &mut [u8], addr: u64, ptrs: &[u64]) {
        for (i, &p) in ptrs.iter().enumerate() {
            put(mem, addr + 8 * i as u64, &p.to_ne_bytes());
        }
    }

    fn plan(
        mem: &[u8],
        path_ptr: u64,
        argv_ptr: u64,
        envp_ptr: u64,
    ) -> Result<ExecRewritePlan, NotifError> {
        let mut read = |addr: u64, len: usize| {
            let off = addr
                .checked_sub(FAKE_BASE)
                .ok_or_else(|| NotifError::Supervisor("read below fake memory".into()))?
                as usize;
            mem.get(off..off + len)
                .map(|s| s.to_vec())
                .ok_or_else(|| NotifError::Supervisor("read past fake memory".into()))
        };
        plan_exec_rewrite(&mut read, path_ptr, FD, argv_ptr, envp_ptr)
    }

    #[test]
    fn exec_rewrite_plain_when_no_string_overlaps() {
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"./m\0");
        put(&mut mem, FAKE_BASE + 0x200, b"prog\0");
        put_ptrs(&mut mem, FAKE_BASE + 0x800, &[FAKE_BASE + 0x200]);
        let p = plan(&mem, FAKE_BASE, FAKE_BASE + 0x800, 0).unwrap();
        assert_eq!(p.buf, FD);
        assert!(p.patches.is_empty());
    }

    #[test]
    fn exec_rewrite_relocates_aliased_argv0() {
        // The common shell case: execve path and argv[0] are the same buffer.
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"./m\0");
        put_ptrs(&mut mem, FAKE_BASE + 0x800, &[FAKE_BASE]);
        let p = plan(&mem, FAKE_BASE, FAKE_BASE + 0x800, 0).unwrap();
        assert_eq!(p.buf, [FD, b"./m\0".as_slice()].concat());
        assert_eq!(p.patches, vec![(FAKE_BASE + 0x800, FAKE_BASE + 16)]);
    }

    #[test]
    fn exec_rewrite_relocates_packed_argv1() {
        // argv[1] sits right after the path string, inside the fd-path
        // window; both strings must survive.
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"./echo\0EXEC_OK\0");
        put_ptrs(&mut mem, FAKE_BASE + 0x800, &[FAKE_BASE, FAKE_BASE + 7]);
        let p = plan(&mem, FAKE_BASE, FAKE_BASE + 0x800, 0).unwrap();
        assert_eq!(p.buf, [FD, b"./echo\0EXEC_OK\0".as_slice()].concat());
        assert_eq!(
            p.patches,
            vec![
                (FAKE_BASE + 0x800, FAKE_BASE + 16),
                (FAKE_BASE + 0x808, FAKE_BASE + 23),
            ]
        );
    }

    #[test]
    fn exec_rewrite_relocates_string_reaching_window_from_below() {
        // The path pointer aims into the tail of argv[0] ("echo" inside
        // "/bin/echo"): the whole string must be relocated.
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"/bin/echo\0");
        put_ptrs(&mut mem, FAKE_BASE + 0x800, &[FAKE_BASE]);
        let p = plan(&mem, FAKE_BASE + 5, FAKE_BASE + 0x800, 0).unwrap();
        assert_eq!(p.buf, [FD, b"/bin/echo\0".as_slice()].concat());
        assert_eq!(p.patches, vec![(FAKE_BASE + 0x800, FAKE_BASE + 5 + 16)]);
    }

    #[test]
    fn exec_rewrite_skips_terminated_string_below_window() {
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"a\0");
        put(&mut mem, FAKE_BASE + 8, b"./m\0");
        put_ptrs(&mut mem, FAKE_BASE + 0x800, &[FAKE_BASE]);
        let p = plan(&mem, FAKE_BASE + 8, FAKE_BASE + 0x800, 0).unwrap();
        assert_eq!(p.buf, FD);
        assert!(p.patches.is_empty());
    }

    #[test]
    fn exec_rewrite_relocates_envp_string() {
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"./m\0K=V\0");
        put(&mut mem, FAKE_BASE + 0x200, b"prog\0");
        put_ptrs(&mut mem, FAKE_BASE + 0x800, &[FAKE_BASE + 0x200]);
        put_ptrs(&mut mem, FAKE_BASE + 0x900, &[FAKE_BASE + 4]);
        let p = plan(&mem, FAKE_BASE, FAKE_BASE + 0x800, FAKE_BASE + 0x900).unwrap();
        assert_eq!(p.buf, [FD, b"K=V\0".as_slice()].concat());
        assert_eq!(p.patches, vec![(FAKE_BASE + 0x900, FAKE_BASE + 16)]);
    }

    #[test]
    fn exec_rewrite_window_growth_pulls_in_later_string() {
        // argv[1] starts past the fd path but inside the window once the
        // relocated argv[0] extends it.
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"./m\0");
        put(&mut mem, FAKE_BASE + 18, b"Z\0");
        put_ptrs(&mut mem, FAKE_BASE + 0x800, &[FAKE_BASE, FAKE_BASE + 18]);
        let p = plan(&mem, FAKE_BASE, FAKE_BASE + 0x800, 0).unwrap();
        assert_eq!(p.buf, [FD, b"./m\0".as_slice(), b"Z\0".as_slice()].concat());
        assert_eq!(
            p.patches,
            vec![
                (FAKE_BASE + 0x800, FAKE_BASE + 16),
                (FAKE_BASE + 0x808, FAKE_BASE + 20),
            ]
        );
    }

    #[test]
    fn exec_rewrite_rejects_pointer_array_inside_window() {
        // The arrays cannot be moved (their addresses live in registers), so
        // a layout where the rewrite would smash them must fail closed.
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"./m\0");
        put_ptrs(&mut mem, FAKE_BASE + 8, &[FAKE_BASE + 0x200]);
        put(&mut mem, FAKE_BASE + 0x200, b"prog\0");
        assert!(plan(&mem, FAKE_BASE, FAKE_BASE + 8, 0).is_err());
    }

    #[test]
    fn exec_rewrite_null_arrays() {
        let mut mem = vec![0u8; 4096];
        put(&mut mem, FAKE_BASE, b"./m\0");
        let p = plan(&mem, FAKE_BASE, 0, 0).unwrap();
        assert_eq!(p.buf, FD);
        assert!(p.patches.is_empty());
    }

    #[test]
    fn inject_failure_response_denies_not_continues() {
        // When fd injection fails, the supervisor must fail closed: deny the
        // syscall instead of letting it continue unmediated against the host
        // path (which would silently bypass chroot/file confinement).
        let resp = inject_failure_resp(123);
        assert_eq!(resp.id, 123);
        assert_eq!(
            resp.flags & SECCOMP_USER_NOTIF_FLAG_CONTINUE,
            0,
            "fd-injection failure must not respond with CONTINUE"
        );
        assert_ne!(resp.error, 0, "fd-injection failure must be a denial");
        assert_eq!(resp.error, -libc::EACCES);
    }

    #[test]
    fn held_gate_no_decision_denies() {
        use crate::policy_fn::Verdict;
        // A held syscall whose policy_fn gate times out or whose channel closes
        // (received == None) must fail closed: deny, not allow the syscall.
        assert!(matches!(resolve_held_gate(None), Some(Verdict::Deny)));
    }

    #[test]
    fn held_gate_passes_through_callback_verdict() {
        use crate::policy_fn::Verdict;
        // A real verdict from the callback is forwarded unchanged.
        assert!(matches!(
            resolve_held_gate(Some(Verdict::Allow)),
            Some(Verdict::Allow)
        ));
        assert!(matches!(
            resolve_held_gate(Some(Verdict::Deny)),
            Some(Verdict::Deny)
        ));
        assert!(matches!(
            resolve_held_gate(Some(Verdict::DenyWith(13))),
            Some(Verdict::DenyWith(13))
        ));
    }

    #[test]
    fn tgid_of_main_thread_is_own_pid() {
        // The main thread's tid equals the process pid, and its Tgid is the pid.
        assert_eq!(tgid_of(gettid()), Some(std::process::id()));
    }

    #[test]
    fn tgid_of_worker_thread_resolves_to_process() {
        // A non-leader thread's Tgid is the process pid, not its own tid.
        let (tid_tx, tid_rx) = std::sync::mpsc::channel();
        let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
        let h = std::thread::spawn(move || {
            tid_tx.send(gettid()).unwrap();
            done_rx.recv().ok(); // stay alive until the test has read /proc
        });
        let worker_tid = tid_rx.recv().unwrap();
        let pid = std::process::id();
        assert_ne!(worker_tid, pid, "worker tid must differ from pid");
        assert_eq!(tgid_of(worker_tid), Some(pid));
        done_tx.send(()).ok();
        h.join().unwrap();
    }

    #[test]
    fn dup_fd_from_pid_handles_worker_thread_fd() {
        use std::os::unix::io::AsRawFd;
        // Open an fd in a non-leader worker thread, then duplicate it by that
        // thread's tid. Exercises the tid->process pidfd resolution end to end
        // (PIDFD_THREAD on >=6.9, the /proc Tgid fallback on older kernels).
        let (info_tx, info_rx) = std::sync::mpsc::channel();
        let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
        let h = std::thread::spawn(move || {
            let f = std::fs::File::open("/dev/null").unwrap();
            info_tx.send((gettid(), f.as_raw_fd())).unwrap();
            done_rx.recv().ok();
            drop(f);
        });
        let (worker_tid, fd) = info_rx.recv().unwrap();
        let dup = dup_fd_from_pid(worker_tid, fd);
        done_tx.send(()).ok();
        h.join().unwrap();
        assert!(dup.is_ok(), "dup_fd_from_pid for a worker-thread fd failed: {:?}", dup.err());
    }

    #[test]
    fn read_child_cstr_returns_none_for_null_addr_or_zero_max_len() {
        // Smoke: addr == 0 short-circuits without touching the child.
        assert!(read_child_cstr(-1, 0, 0, 0, 4096).is_none());
        // max_len == 0 also short-circuits.
        assert!(read_child_cstr(-1, 0, 0, 0xdeadbeef, 0).is_none());
    }

    #[test]
    fn test_notif_action_debug() {
        // Ensure all variants implement Debug.
        let _ = format!("{:?}", NotifAction::Continue);
        let _ = format!("{:?}", NotifAction::Errno(1));
        let _ = format!("{:?}", NotifAction::InjectFd { srcfd: 3, targetfd: 4 });
        // Use a real fd (dup'd from stderr) so OwnedFd can safely close it.
        let test_fd = unsafe { OwnedFd::from_raw_fd(libc::dup(2)) };
        let _ = format!("{:?}", NotifAction::InjectFdSend { srcfd: test_fd, newfd_flags: 0 });
        let _ = format!("{:?}", NotifAction::ReturnValue(42));
        let _ = format!("{:?}", NotifAction::Hold);
        let _ = format!("{:?}", NotifAction::Kill { sig: 9, pgid: 1 });
        let _ = format!("{:?}", NotifAction::defer(async { NotifAction::Continue }));
    }

    #[tokio::test]
    async fn deferred_future_need_not_be_sync() {
        // A deferred future may capture Send-but-not-Sync state across an
        // await. `Cell` is Send but never Sync; holding it across `.await`
        // makes the future !Sync. Only `Send` is required (the supervisor
        // moves the future to a worker, never shares it by reference).
        use std::cell::Cell;
        let action = NotifAction::defer(async move {
            let counter = Cell::new(0);
            counter.set(counter.get() + 41);
            tokio::task::yield_now().await; // hold the !Sync Cell across await
            NotifAction::ReturnValue(counter.get() + 1)
        });
        let NotifAction::Defer(d) = action else { panic!("expected Defer") };
        assert!(matches!(d.run().await, NotifAction::ReturnValue(42)));
    }

    #[tokio::test]
    async fn deferred_runs_to_its_terminal_action() {
        // A Defer carries a future; running it yields the deferred decision.
        let action = NotifAction::defer(async { NotifAction::ReturnValue(7) });
        let NotifAction::Defer(deferred) = action else {
            panic!("defer() must construct a NotifAction::Defer");
        };
        assert!(matches!(deferred.run().await, NotifAction::ReturnValue(7)));
    }

    #[tokio::test(start_paused = true)]
    async fn deferred_times_out_to_eio() {
        // A deferred future that exceeds its limit must fail closed (EIO) so
        // the trapped child gets a definite response instead of parking
        // forever (and leaking its DEFER_MAX_INFLIGHT slot).
        let slow = Deferred::new(async {
            tokio::time::sleep(std::time::Duration::from_secs(60)).await;
            NotifAction::ReturnValue(7)
        });
        let action = run_deferred_within(slow, std::time::Duration::from_secs(1)).await;
        assert!(matches!(action, NotifAction::Errno(e) if e == libc::EIO));
    }

    #[tokio::test(start_paused = true)]
    async fn deferred_within_limit_passes_through() {
        // A future that resolves within the limit returns its terminal action.
        let fast = Deferred::new(async { NotifAction::ReturnValue(7) });
        let action = run_deferred_within(fast, std::time::Duration::from_secs(1)).await;
        assert!(matches!(action, NotifAction::ReturnValue(7)));
    }

    #[test]
    fn finalize_deferred_collapses_nested_defer_to_eio() {
        // A deferred future that itself resolves to Defer is a bug: collapse
        // to EIO so the trapped child is never wedged waiting for a response.
        let nested = NotifAction::defer(async { NotifAction::Continue });
        assert!(matches!(finalize_deferred(nested), NotifAction::Errno(e) if e == libc::EIO));
        // Non-nested terminal actions pass through unchanged.
        assert!(matches!(finalize_deferred(NotifAction::Continue), NotifAction::Continue));
        assert!(matches!(
            finalize_deferred(NotifAction::ReturnValue(3)),
            NotifAction::ReturnValue(3)
        ));
    }

    #[test]
    fn content_memfd_roundtrips_content() {
        use std::io::Read;
        let fd = content_memfd(b"hello world", true).expect("content_memfd");
        // The fd is rewound to offset 0, so a plain read returns the content.
        let mut f = std::fs::File::from(fd);
        let mut buf = String::new();
        f.read_to_string(&mut buf).unwrap();
        assert_eq!(buf, "hello world");
    }

    #[test]
    fn content_memfd_sealed_applies_write_seal() {
        let fd = content_memfd(b"data", true).expect("content_memfd");
        let seals = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GET_SEALS) };
        assert!(seals >= 0, "F_GET_SEALS failed");
        assert!(
            seals & libc::F_SEAL_WRITE != 0,
            "expected F_SEAL_WRITE on a sealed memfd, got {seals:#x}"
        );
    }

    #[test]
    fn content_memfd_unsealed_has_no_write_seal() {
        let fd = content_memfd(b"data", false).expect("content_memfd");
        let seals = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GET_SEALS) };
        assert!(seals >= 0, "F_GET_SEALS failed");
        assert_eq!(
            seals & libc::F_SEAL_WRITE,
            0,
            "unsealed memfd must not carry a write seal, got {seals:#x}"
        );
    }

    #[test]
    fn inject_bytes_produces_sealed_cloexec_injectfdsend() {
        use std::io::Read;
        match NotifAction::inject_bytes(b"payload") {
            NotifAction::InjectFdSend { srcfd, newfd_flags } => {
                assert_eq!(newfd_flags, libc::O_CLOEXEC as u32);
                let seals = unsafe { libc::fcntl(srcfd.as_raw_fd(), libc::F_GET_SEALS) };
                assert!(seals & libc::F_SEAL_WRITE != 0, "inject_bytes must seal");
                let mut f = std::fs::File::from(srcfd);
                let mut buf = String::new();
                f.read_to_string(&mut buf).unwrap();
                assert_eq!(buf, "payload");
            }
            other => panic!("expected InjectFdSend, got {other:?}"),
        }
    }

    #[test]
    fn test_network_state_new() {
        let ns = super::super::state::NetworkState::new();
        assert!(matches!(ns.tcp_policy, NetworkPolicy::Unrestricted));
        assert!(matches!(ns.udp_policy, NetworkPolicy::Unrestricted));
        assert!(matches!(ns.icmp_policy, NetworkPolicy::Unrestricted));
        assert!(ns.port_map.bound_ports.is_empty());
    }

    #[test]
    fn test_time_random_state_new() {
        let tr = super::super::state::TimeRandomState::new(None, None);
        assert!(tr.time_offset.is_none());
        assert!(tr.random_state.is_none());
    }

    #[test]
    fn test_resource_state_new() {
        let rs = super::super::state::ResourceState::new(1024 * 1024, 10);
        assert_eq!(rs.mem_used, 0);
        assert_eq!(rs.max_memory_bytes, 1024 * 1024);
        assert_eq!(rs.max_processes, 10);
        assert!(!rs.hold_forks);
        assert!(rs.held_notif_ids.is_empty());
    }

    #[test]
    fn test_process_vm_readv_self() {
        let data: u64 = 0xDEADBEEF_CAFEBABE;
        let addr = &data as *const u64 as u64;
        let pid = std::process::id();
        let result = read_child_mem_vm(pid, addr, 8);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        let read_val = u64::from_ne_bytes(bytes[..8].try_into().unwrap());
        assert_eq!(read_val, 0xDEADBEEF_CAFEBABE);
    }

    #[test]
    fn test_process_vm_writev_self() {
        let mut data: u64 = 0;
        let addr = &mut data as *mut u64 as u64;
        let pid = std::process::id();
        let payload = 0x1234567890ABCDEFu64.to_ne_bytes();
        let result = write_child_mem_vm(pid, addr, &payload);
        assert!(result.is_ok());
        assert_eq!(data, 0x1234567890ABCDEF);
    }

    /// The force-write path (`/proc/<pid>/mem`, FOLL_FORCE) must overwrite a
    /// read-only page where `process_vm_writev` (`write_child_mem_vm`) refuses.
    /// A read-only private page stands in for the `.rodata` path literal a child
    /// hands to chdir/execve — the exact case the chroot/cow rewrite sites hit.
    #[test]
    fn write_child_mem_proc_forces_past_readonly_page() {
        const PAGE: usize = 4096;
        let orig = b"/some/rodata/path\0";
        let newb = b"/proc/self/fd/7\0\0"; // fits within the page, near orig's len

        let addr = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                PAGE,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
                -1,
                0,
            )
        };
        assert_ne!(addr, libc::MAP_FAILED, "mmap failed");
        unsafe { std::ptr::copy_nonoverlapping(orig.as_ptr(), addr as *mut u8, orig.len()) };

        // Flip the page read-only: a normal store would now SIGSEGV, and
        // process_vm_writev honors the protection and fails.
        assert_eq!(
            unsafe { libc::mprotect(addr, PAGE, libc::PROT_READ) },
            0,
            "mprotect PROT_READ failed"
        );

        let pid = std::process::id();
        let uaddr = addr as u64;

        assert!(
            write_child_mem_vm(pid, uaddr, newb).is_err(),
            "process_vm_writev must fail on a read-only page"
        );

        // FOLL_FORCE via /proc/<pid>/mem copies-on-write past the RO page.
        write_child_mem_proc(pid, uaddr, newb)
            .expect("force-write through /proc/pid/mem must succeed on a read-only page");

        // The write landed at the target address (page is still RO-mapped, so a
        // plain read is fine and reflects the COW'd contents).
        let got = unsafe { std::slice::from_raw_parts(addr as *const u8, newb.len()) };
        assert_eq!(got, newb, "forced write must be visible at the target address");

        unsafe { libc::munmap(addr, PAGE) };
    }

    #[test]
    fn denylist_blocks_matching_cidr_allows_rest() {
        use crate::network::IpCidr;
        let policy = NetworkPolicy::DenyList {
            cidrs: vec![(IpCidr::parse("10.0.0.0/8").unwrap(), PortAllow::Any)],
            any_ip_ports: HashSet::new(),
            deny_all: false,
        };
        assert!(!policy.allows("10.1.2.3".parse().unwrap(), 443)); // denied
        assert!(policy.allows("8.8.8.8".parse().unwrap(), 443));   // allowed
    }

    #[test]
    fn denylist_blocks_any_ip_port() {
        let mut ports = HashSet::new();
        ports.insert(25u16);
        let policy = NetworkPolicy::DenyList {
            cidrs: Vec::new(),
            any_ip_ports: ports,
            deny_all: false,
        };
        assert!(!policy.allows("8.8.8.8".parse().unwrap(), 25)); // denied
        assert!(policy.allows("8.8.8.8".parse().unwrap(), 80));  // allowed
    }

    #[test]
    fn denylist_specific_ports_on_cidr() {
        use crate::network::IpCidr;
        let mut ports = HashSet::new();
        ports.insert(443u16);
        let policy = NetworkPolicy::DenyList {
            cidrs: vec![(IpCidr::parse("1.2.3.4/32").unwrap(), PortAllow::Specific(ports))],
            any_ip_ports: HashSet::new(),
            deny_all: false,
        };
        assert!(!policy.allows("1.2.3.4".parse().unwrap(), 443)); // denied
        assert!(policy.allows("1.2.3.4".parse().unwrap(), 80));   // allowed
    }

    #[test]
    fn allowlist_permits_matching_cidr_only() {
        use crate::network::IpCidr;
        let mut ports = HashSet::new();
        ports.insert(80u16);
        let policy = NetworkPolicy::AllowList {
            per_ip: HashMap::new(),
            cidrs: vec![(IpCidr::parse("10.0.0.0/8").unwrap(), PortAllow::Specific(ports))],
            any_ip_ports: HashSet::new(),
        };
        assert!(policy.allows("10.1.2.3".parse().unwrap(), 80));   // in range, port ok
        assert!(!policy.allows("10.1.2.3".parse().unwrap(), 443)); // in range, wrong port
        assert!(!policy.allows("8.8.8.8".parse().unwrap(), 80));   // out of range
    }

    #[test]
    fn allowlist_cidr_all_ports() {
        use crate::network::IpCidr;
        let policy = NetworkPolicy::AllowList {
            per_ip: HashMap::new(),
            cidrs: vec![(IpCidr::parse("192.168.0.0/16").unwrap(), PortAllow::Any)],
            any_ip_ports: HashSet::new(),
        };
        assert!(policy.allows("192.168.5.5".parse().unwrap(), 9999)); // any port in range
        assert!(!policy.allows("10.0.0.1".parse().unwrap(), 9999));   // out of range
    }

    #[test]
    fn denylist_blocks_v4_mapped_ipv6_form_of_denied_ip() {
        // A dual-stack AF_INET6 socket connecting to ::ffff:169.254.169.254
        // reaches 169.254.169.254 over IPv4, so a v4 deny rule must match
        // the mapped form or the denylist is bypassable.
        use crate::network::IpCidr;
        let policy = NetworkPolicy::DenyList {
            cidrs: vec![(IpCidr::parse("169.254.169.254").unwrap(), PortAllow::Any)],
            any_ip_ports: HashSet::new(),
            deny_all: false,
        };
        assert!(!policy.allows("::ffff:169.254.169.254".parse().unwrap(), 80));
    }

    #[test]
    fn allowlist_accepts_v4_mapped_ipv6_form_of_allowed_ip() {
        // Mirror of the deny case: the mapped form is the same destination,
        // so a v4 allow entry must match it (per_ip and cidr paths both).
        use crate::network::IpCidr;
        let mut per_ip = HashMap::new();
        per_ip.insert("1.2.3.4".parse().unwrap(), PortAllow::Any);
        let policy = NetworkPolicy::AllowList {
            per_ip,
            cidrs: vec![(IpCidr::parse("10.0.0.0/8").unwrap(), PortAllow::Any)],
            any_ip_ports: HashSet::new(),
        };
        assert!(policy.allows("::ffff:1.2.3.4".parse().unwrap(), 443));
        assert!(policy.allows("::ffff:10.1.2.3".parse().unwrap(), 443));
        assert!(!policy.allows("::ffff:8.8.8.8".parse().unwrap(), 443));
    }
}